1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | 'use strict';
|
12 |
|
13 | Object.defineProperty(exports, '__esModule', { value: true });
|
14 |
|
15 | function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
16 |
|
17 | var util$2 = _interopDefault(require('util'));
|
18 | var path = require('path');
|
19 | var path__default = _interopDefault(path);
|
20 | var acorn = require('acorn');
|
21 | var acorn__default = _interopDefault(acorn);
|
22 | var fs = require('fs');
|
23 | var fs__default = _interopDefault(fs);
|
24 | var events = require('events');
|
25 | var tty = _interopDefault(require('tty'));
|
26 | var net = _interopDefault(require('net'));
|
27 | var url = _interopDefault(require('url'));
|
28 | var module$1 = _interopDefault(require('module'));
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | var extendStatics = function(d, b) {
|
47 | extendStatics = Object.setPrototypeOf ||
|
48 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
49 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
50 | return extendStatics(d, b);
|
51 | };
|
52 |
|
53 | function __extends(d, b) {
|
54 | extendStatics(d, b);
|
55 | function __() { this.constructor = d; }
|
56 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
57 | }
|
58 |
|
59 | var __assign = function() {
|
60 | __assign = Object.assign || function __assign(t) {
|
61 | for (var s, i = 1, n = arguments.length; i < n; i++) {
|
62 | s = arguments[i];
|
63 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
|
64 | }
|
65 | return t;
|
66 | };
|
67 | return __assign.apply(this, arguments);
|
68 | };
|
69 |
|
70 | function __rest(s, e) {
|
71 | var t = {};
|
72 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
73 | t[p] = s[p];
|
74 | if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
75 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
|
76 | t[p[i]] = s[p[i]];
|
77 | return t;
|
78 | }
|
79 |
|
80 | function __decorate(decorators, target, key, desc) {
|
81 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
82 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
83 | 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;
|
84 | return c > 3 && r && Object.defineProperty(target, key, r), r;
|
85 | }
|
86 |
|
87 | function __param(paramIndex, decorator) {
|
88 | return function (target, key) { decorator(target, key, paramIndex); }
|
89 | }
|
90 |
|
91 | function __metadata(metadataKey, metadataValue) {
|
92 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
|
93 | }
|
94 |
|
95 | function __awaiter(thisArg, _arguments, P, generator) {
|
96 | return new (P || (P = Promise))(function (resolve, reject) {
|
97 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
98 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
99 | function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
100 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
101 | });
|
102 | }
|
103 |
|
104 | function __generator(thisArg, body) {
|
105 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
106 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
107 | function verb(n) { return function (v) { return step([n, v]); }; }
|
108 | function step(op) {
|
109 | if (f) throw new TypeError("Generator is already executing.");
|
110 | while (_) try {
|
111 | 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;
|
112 | if (y = 0, t) op = [op[0] & 2, t.value];
|
113 | switch (op[0]) {
|
114 | case 0: case 1: t = op; break;
|
115 | case 4: _.label++; return { value: op[1], done: false };
|
116 | case 5: _.label++; y = op[1]; op = [0]; continue;
|
117 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
118 | default:
|
119 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
120 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
121 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
122 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
123 | if (t[2]) _.ops.pop();
|
124 | _.trys.pop(); continue;
|
125 | }
|
126 | op = body.call(thisArg, _);
|
127 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
128 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
129 | }
|
130 | }
|
131 |
|
132 | function __exportStar(m, exports) {
|
133 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
134 | }
|
135 |
|
136 | function __values(o) {
|
137 | var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
|
138 | if (m) return m.call(o);
|
139 | return {
|
140 | next: function () {
|
141 | if (o && i >= o.length) o = void 0;
|
142 | return { value: o && o[i++], done: !o };
|
143 | }
|
144 | };
|
145 | }
|
146 |
|
147 | function __read(o, n) {
|
148 | var m = typeof Symbol === "function" && o[Symbol.iterator];
|
149 | if (!m) return o;
|
150 | var i = m.call(o), r, ar = [], e;
|
151 | try {
|
152 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
153 | }
|
154 | catch (error) { e = { error: error }; }
|
155 | finally {
|
156 | try {
|
157 | if (r && !r.done && (m = i["return"])) m.call(i);
|
158 | }
|
159 | finally { if (e) throw e.error; }
|
160 | }
|
161 | return ar;
|
162 | }
|
163 |
|
164 | function __spread() {
|
165 | for (var ar = [], i = 0; i < arguments.length; i++)
|
166 | ar = ar.concat(__read(arguments[i]));
|
167 | return ar;
|
168 | }
|
169 |
|
170 | function __await(v) {
|
171 | return this instanceof __await ? (this.v = v, this) : new __await(v);
|
172 | }
|
173 |
|
174 | function __asyncGenerator(thisArg, _arguments, generator) {
|
175 | if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
176 | var g = generator.apply(thisArg, _arguments || []), i, q = [];
|
177 | return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
|
178 | 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); }); }; }
|
179 | function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
|
180 | function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
|
181 | function fulfill(value) { resume("next", value); }
|
182 | function reject(value) { resume("throw", value); }
|
183 | function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
|
184 | }
|
185 |
|
186 | function __asyncDelegator(o) {
|
187 | var i, p;
|
188 | return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
|
189 | 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; }
|
190 | }
|
191 |
|
192 | function __asyncValues(o) {
|
193 | if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
194 | var m = o[Symbol.asyncIterator], i;
|
195 | 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);
|
196 | 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); }); }; }
|
197 | function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
198 | }
|
199 |
|
200 | function __makeTemplateObject(cooked, raw) {
|
201 | if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
|
202 | return cooked;
|
203 | }
|
204 | function __importStar(mod) {
|
205 | if (mod && mod.__esModule) return mod;
|
206 | var result = {};
|
207 | if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
208 | result.default = mod;
|
209 | return result;
|
210 | }
|
211 |
|
212 | function __importDefault(mod) {
|
213 | return (mod && mod.__esModule) ? mod : { default: mod };
|
214 | }
|
215 |
|
216 | var tslib_1 = Object.freeze({
|
217 | __extends: __extends,
|
218 | get __assign () { return __assign; },
|
219 | __rest: __rest,
|
220 | __decorate: __decorate,
|
221 | __param: __param,
|
222 | __metadata: __metadata,
|
223 | __awaiter: __awaiter,
|
224 | __generator: __generator,
|
225 | __exportStar: __exportStar,
|
226 | __values: __values,
|
227 | __read: __read,
|
228 | __spread: __spread,
|
229 | __await: __await,
|
230 | __asyncGenerator: __asyncGenerator,
|
231 | __asyncDelegator: __asyncDelegator,
|
232 | __asyncValues: __asyncValues,
|
233 | __makeTemplateObject: __makeTemplateObject,
|
234 | __importStar: __importStar,
|
235 | __importDefault: __importDefault
|
236 | });
|
237 |
|
238 | var version = "1.11.1";
|
239 |
|
240 | var minimalisticAssert = assert;
|
241 |
|
242 | function assert(val, msg) {
|
243 | if (!val)
|
244 | throw new Error(msg || 'Assertion failed');
|
245 | }
|
246 |
|
247 | assert.equal = function assertEqual(l, r, msg) {
|
248 | if (l != r)
|
249 | throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
|
250 | };
|
251 |
|
252 | var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
253 |
|
254 | function createCommonjsModule(fn, module) {
|
255 | return module = { exports: {} }, fn(module, module.exports), module.exports;
|
256 | }
|
257 |
|
258 | var inherits_browser = createCommonjsModule(function (module) {
|
259 | if (typeof Object.create === 'function') {
|
260 |
|
261 | module.exports = function inherits(ctor, superCtor) {
|
262 | ctor.super_ = superCtor;
|
263 | ctor.prototype = Object.create(superCtor.prototype, {
|
264 | constructor: {
|
265 | value: ctor,
|
266 | enumerable: false,
|
267 | writable: true,
|
268 | configurable: true
|
269 | }
|
270 | });
|
271 | };
|
272 | } else {
|
273 |
|
274 | module.exports = function inherits(ctor, superCtor) {
|
275 | ctor.super_ = superCtor;
|
276 | var TempCtor = function () {};
|
277 | TempCtor.prototype = superCtor.prototype;
|
278 | ctor.prototype = new TempCtor();
|
279 | ctor.prototype.constructor = ctor;
|
280 | };
|
281 | }
|
282 | });
|
283 |
|
284 | var inherits = createCommonjsModule(function (module) {
|
285 | try {
|
286 | var util = util$2;
|
287 | if (typeof util.inherits !== 'function') throw '';
|
288 | module.exports = util.inherits;
|
289 | } catch (e) {
|
290 | module.exports = inherits_browser;
|
291 | }
|
292 | });
|
293 |
|
294 | var inherits_1 = inherits;
|
295 |
|
296 | function isSurrogatePair(msg, i) {
|
297 | if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
|
298 | return false;
|
299 | }
|
300 | if (i < 0 || i + 1 >= msg.length) {
|
301 | return false;
|
302 | }
|
303 | return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
|
304 | }
|
305 |
|
306 | function toArray(msg, enc) {
|
307 | if (Array.isArray(msg))
|
308 | return msg.slice();
|
309 | if (!msg)
|
310 | return [];
|
311 | var res = [];
|
312 | if (typeof msg === 'string') {
|
313 | if (!enc) {
|
314 |
|
315 |
|
316 |
|
317 |
|
318 | var p = 0;
|
319 | for (var i = 0; i < msg.length; i++) {
|
320 | var c = msg.charCodeAt(i);
|
321 | if (c < 128) {
|
322 | res[p++] = c;
|
323 | } else if (c < 2048) {
|
324 | res[p++] = (c >> 6) | 192;
|
325 | res[p++] = (c & 63) | 128;
|
326 | } else if (isSurrogatePair(msg, i)) {
|
327 | c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
|
328 | res[p++] = (c >> 18) | 240;
|
329 | res[p++] = ((c >> 12) & 63) | 128;
|
330 | res[p++] = ((c >> 6) & 63) | 128;
|
331 | res[p++] = (c & 63) | 128;
|
332 | } else {
|
333 | res[p++] = (c >> 12) | 224;
|
334 | res[p++] = ((c >> 6) & 63) | 128;
|
335 | res[p++] = (c & 63) | 128;
|
336 | }
|
337 | }
|
338 | } else if (enc === 'hex') {
|
339 | msg = msg.replace(/[^a-z0-9]+/ig, '');
|
340 | if (msg.length % 2 !== 0)
|
341 | msg = '0' + msg;
|
342 | for (i = 0; i < msg.length; i += 2)
|
343 | res.push(parseInt(msg[i] + msg[i + 1], 16));
|
344 | }
|
345 | } else {
|
346 | for (i = 0; i < msg.length; i++)
|
347 | res[i] = msg[i] | 0;
|
348 | }
|
349 | return res;
|
350 | }
|
351 | var toArray_1 = toArray;
|
352 |
|
353 | function toHex(msg) {
|
354 | var res = '';
|
355 | for (var i = 0; i < msg.length; i++)
|
356 | res += zero2(msg[i].toString(16));
|
357 | return res;
|
358 | }
|
359 | var toHex_1 = toHex;
|
360 |
|
361 | function htonl(w) {
|
362 | var res = (w >>> 24) |
|
363 | ((w >>> 8) & 0xff00) |
|
364 | ((w << 8) & 0xff0000) |
|
365 | ((w & 0xff) << 24);
|
366 | return res >>> 0;
|
367 | }
|
368 | var htonl_1 = htonl;
|
369 |
|
370 | function toHex32(msg, endian) {
|
371 | var res = '';
|
372 | for (var i = 0; i < msg.length; i++) {
|
373 | var w = msg[i];
|
374 | if (endian === 'little')
|
375 | w = htonl(w);
|
376 | res += zero8(w.toString(16));
|
377 | }
|
378 | return res;
|
379 | }
|
380 | var toHex32_1 = toHex32;
|
381 |
|
382 | function zero2(word) {
|
383 | if (word.length === 1)
|
384 | return '0' + word;
|
385 | else
|
386 | return word;
|
387 | }
|
388 | var zero2_1 = zero2;
|
389 |
|
390 | function zero8(word) {
|
391 | if (word.length === 7)
|
392 | return '0' + word;
|
393 | else if (word.length === 6)
|
394 | return '00' + word;
|
395 | else if (word.length === 5)
|
396 | return '000' + word;
|
397 | else if (word.length === 4)
|
398 | return '0000' + word;
|
399 | else if (word.length === 3)
|
400 | return '00000' + word;
|
401 | else if (word.length === 2)
|
402 | return '000000' + word;
|
403 | else if (word.length === 1)
|
404 | return '0000000' + word;
|
405 | else
|
406 | return word;
|
407 | }
|
408 | var zero8_1 = zero8;
|
409 |
|
410 | function join32(msg, start, end, endian) {
|
411 | var len = end - start;
|
412 | minimalisticAssert(len % 4 === 0);
|
413 | var res = new Array(len / 4);
|
414 | for (var i = 0, k = start; i < res.length; i++, k += 4) {
|
415 | var w;
|
416 | if (endian === 'big')
|
417 | w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
|
418 | else
|
419 | w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
|
420 | res[i] = w >>> 0;
|
421 | }
|
422 | return res;
|
423 | }
|
424 | var join32_1 = join32;
|
425 |
|
426 | function split32(msg, endian) {
|
427 | var res = new Array(msg.length * 4);
|
428 | for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
|
429 | var m = msg[i];
|
430 | if (endian === 'big') {
|
431 | res[k] = m >>> 24;
|
432 | res[k + 1] = (m >>> 16) & 0xff;
|
433 | res[k + 2] = (m >>> 8) & 0xff;
|
434 | res[k + 3] = m & 0xff;
|
435 | } else {
|
436 | res[k + 3] = m >>> 24;
|
437 | res[k + 2] = (m >>> 16) & 0xff;
|
438 | res[k + 1] = (m >>> 8) & 0xff;
|
439 | res[k] = m & 0xff;
|
440 | }
|
441 | }
|
442 | return res;
|
443 | }
|
444 | var split32_1 = split32;
|
445 |
|
446 | function rotr32(w, b) {
|
447 | return (w >>> b) | (w << (32 - b));
|
448 | }
|
449 | var rotr32_1 = rotr32;
|
450 |
|
451 | function rotl32(w, b) {
|
452 | return (w << b) | (w >>> (32 - b));
|
453 | }
|
454 | var rotl32_1 = rotl32;
|
455 |
|
456 | function sum32(a, b) {
|
457 | return (a + b) >>> 0;
|
458 | }
|
459 | var sum32_1 = sum32;
|
460 |
|
461 | function sum32_3(a, b, c) {
|
462 | return (a + b + c) >>> 0;
|
463 | }
|
464 | var sum32_3_1 = sum32_3;
|
465 |
|
466 | function sum32_4(a, b, c, d) {
|
467 | return (a + b + c + d) >>> 0;
|
468 | }
|
469 | var sum32_4_1 = sum32_4;
|
470 |
|
471 | function sum32_5(a, b, c, d, e) {
|
472 | return (a + b + c + d + e) >>> 0;
|
473 | }
|
474 | var sum32_5_1 = sum32_5;
|
475 |
|
476 | function sum64(buf, pos, ah, al) {
|
477 | var bh = buf[pos];
|
478 | var bl = buf[pos + 1];
|
479 |
|
480 | var lo = (al + bl) >>> 0;
|
481 | var hi = (lo < al ? 1 : 0) + ah + bh;
|
482 | buf[pos] = hi >>> 0;
|
483 | buf[pos + 1] = lo;
|
484 | }
|
485 | var sum64_1 = sum64;
|
486 |
|
487 | function sum64_hi(ah, al, bh, bl) {
|
488 | var lo = (al + bl) >>> 0;
|
489 | var hi = (lo < al ? 1 : 0) + ah + bh;
|
490 | return hi >>> 0;
|
491 | }
|
492 | var sum64_hi_1 = sum64_hi;
|
493 |
|
494 | function sum64_lo(ah, al, bh, bl) {
|
495 | var lo = al + bl;
|
496 | return lo >>> 0;
|
497 | }
|
498 | var sum64_lo_1 = sum64_lo;
|
499 |
|
500 | function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
|
501 | var carry = 0;
|
502 | var lo = al;
|
503 | lo = (lo + bl) >>> 0;
|
504 | carry += lo < al ? 1 : 0;
|
505 | lo = (lo + cl) >>> 0;
|
506 | carry += lo < cl ? 1 : 0;
|
507 | lo = (lo + dl) >>> 0;
|
508 | carry += lo < dl ? 1 : 0;
|
509 |
|
510 | var hi = ah + bh + ch + dh + carry;
|
511 | return hi >>> 0;
|
512 | }
|
513 | var sum64_4_hi_1 = sum64_4_hi;
|
514 |
|
515 | function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
|
516 | var lo = al + bl + cl + dl;
|
517 | return lo >>> 0;
|
518 | }
|
519 | var sum64_4_lo_1 = sum64_4_lo;
|
520 |
|
521 | function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
|
522 | var carry = 0;
|
523 | var lo = al;
|
524 | lo = (lo + bl) >>> 0;
|
525 | carry += lo < al ? 1 : 0;
|
526 | lo = (lo + cl) >>> 0;
|
527 | carry += lo < cl ? 1 : 0;
|
528 | lo = (lo + dl) >>> 0;
|
529 | carry += lo < dl ? 1 : 0;
|
530 | lo = (lo + el) >>> 0;
|
531 | carry += lo < el ? 1 : 0;
|
532 |
|
533 | var hi = ah + bh + ch + dh + eh + carry;
|
534 | return hi >>> 0;
|
535 | }
|
536 | var sum64_5_hi_1 = sum64_5_hi;
|
537 |
|
538 | function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
|
539 | var lo = al + bl + cl + dl + el;
|
540 |
|
541 | return lo >>> 0;
|
542 | }
|
543 | var sum64_5_lo_1 = sum64_5_lo;
|
544 |
|
545 | function rotr64_hi(ah, al, num) {
|
546 | var r = (al << (32 - num)) | (ah >>> num);
|
547 | return r >>> 0;
|
548 | }
|
549 | var rotr64_hi_1 = rotr64_hi;
|
550 |
|
551 | function rotr64_lo(ah, al, num) {
|
552 | var r = (ah << (32 - num)) | (al >>> num);
|
553 | return r >>> 0;
|
554 | }
|
555 | var rotr64_lo_1 = rotr64_lo;
|
556 |
|
557 | function shr64_hi(ah, al, num) {
|
558 | return ah >>> num;
|
559 | }
|
560 | var shr64_hi_1 = shr64_hi;
|
561 |
|
562 | function shr64_lo(ah, al, num) {
|
563 | var r = (ah << (32 - num)) | (al >>> num);
|
564 | return r >>> 0;
|
565 | }
|
566 | var shr64_lo_1 = shr64_lo;
|
567 |
|
568 | var utils = {
|
569 | inherits: inherits_1,
|
570 | toArray: toArray_1,
|
571 | toHex: toHex_1,
|
572 | htonl: htonl_1,
|
573 | toHex32: toHex32_1,
|
574 | zero2: zero2_1,
|
575 | zero8: zero8_1,
|
576 | join32: join32_1,
|
577 | split32: split32_1,
|
578 | rotr32: rotr32_1,
|
579 | rotl32: rotl32_1,
|
580 | sum32: sum32_1,
|
581 | sum32_3: sum32_3_1,
|
582 | sum32_4: sum32_4_1,
|
583 | sum32_5: sum32_5_1,
|
584 | sum64: sum64_1,
|
585 | sum64_hi: sum64_hi_1,
|
586 | sum64_lo: sum64_lo_1,
|
587 | sum64_4_hi: sum64_4_hi_1,
|
588 | sum64_4_lo: sum64_4_lo_1,
|
589 | sum64_5_hi: sum64_5_hi_1,
|
590 | sum64_5_lo: sum64_5_lo_1,
|
591 | rotr64_hi: rotr64_hi_1,
|
592 | rotr64_lo: rotr64_lo_1,
|
593 | shr64_hi: shr64_hi_1,
|
594 | shr64_lo: shr64_lo_1
|
595 | };
|
596 |
|
597 | function BlockHash() {
|
598 | this.pending = null;
|
599 | this.pendingTotal = 0;
|
600 | this.blockSize = this.constructor.blockSize;
|
601 | this.outSize = this.constructor.outSize;
|
602 | this.hmacStrength = this.constructor.hmacStrength;
|
603 | this.padLength = this.constructor.padLength / 8;
|
604 | this.endian = 'big';
|
605 |
|
606 | this._delta8 = this.blockSize / 8;
|
607 | this._delta32 = this.blockSize / 32;
|
608 | }
|
609 | var BlockHash_1 = BlockHash;
|
610 |
|
611 | BlockHash.prototype.update = function update(msg, enc) {
|
612 |
|
613 | msg = utils.toArray(msg, enc);
|
614 | if (!this.pending)
|
615 | this.pending = msg;
|
616 | else
|
617 | this.pending = this.pending.concat(msg);
|
618 | this.pendingTotal += msg.length;
|
619 |
|
620 |
|
621 | if (this.pending.length >= this._delta8) {
|
622 | msg = this.pending;
|
623 |
|
624 |
|
625 | var r = msg.length % this._delta8;
|
626 | this.pending = msg.slice(msg.length - r, msg.length);
|
627 | if (this.pending.length === 0)
|
628 | this.pending = null;
|
629 |
|
630 | msg = utils.join32(msg, 0, msg.length - r, this.endian);
|
631 | for (var i = 0; i < msg.length; i += this._delta32)
|
632 | this._update(msg, i, i + this._delta32);
|
633 | }
|
634 |
|
635 | return this;
|
636 | };
|
637 |
|
638 | BlockHash.prototype.digest = function digest(enc) {
|
639 | this.update(this._pad());
|
640 | minimalisticAssert(this.pending === null);
|
641 |
|
642 | return this._digest(enc);
|
643 | };
|
644 |
|
645 | BlockHash.prototype._pad = function pad() {
|
646 | var len = this.pendingTotal;
|
647 | var bytes = this._delta8;
|
648 | var k = bytes - ((len + this.padLength) % bytes);
|
649 | var res = new Array(k + this.padLength);
|
650 | res[0] = 0x80;
|
651 | for (var i = 1; i < k; i++)
|
652 | res[i] = 0;
|
653 |
|
654 |
|
655 | len <<= 3;
|
656 | if (this.endian === 'big') {
|
657 | for (var t = 8; t < this.padLength; t++)
|
658 | res[i++] = 0;
|
659 |
|
660 | res[i++] = 0;
|
661 | res[i++] = 0;
|
662 | res[i++] = 0;
|
663 | res[i++] = 0;
|
664 | res[i++] = (len >>> 24) & 0xff;
|
665 | res[i++] = (len >>> 16) & 0xff;
|
666 | res[i++] = (len >>> 8) & 0xff;
|
667 | res[i++] = len & 0xff;
|
668 | } else {
|
669 | res[i++] = len & 0xff;
|
670 | res[i++] = (len >>> 8) & 0xff;
|
671 | res[i++] = (len >>> 16) & 0xff;
|
672 | res[i++] = (len >>> 24) & 0xff;
|
673 | res[i++] = 0;
|
674 | res[i++] = 0;
|
675 | res[i++] = 0;
|
676 | res[i++] = 0;
|
677 |
|
678 | for (t = 8; t < this.padLength; t++)
|
679 | res[i++] = 0;
|
680 | }
|
681 |
|
682 | return res;
|
683 | };
|
684 |
|
685 | var common = {
|
686 | BlockHash: BlockHash_1
|
687 | };
|
688 |
|
689 | var rotr32$1 = utils.rotr32;
|
690 |
|
691 | function ft_1(s, x, y, z) {
|
692 | if (s === 0)
|
693 | return ch32(x, y, z);
|
694 | if (s === 1 || s === 3)
|
695 | return p32(x, y, z);
|
696 | if (s === 2)
|
697 | return maj32(x, y, z);
|
698 | }
|
699 | var ft_1_1 = ft_1;
|
700 |
|
701 | function ch32(x, y, z) {
|
702 | return (x & y) ^ ((~x) & z);
|
703 | }
|
704 | var ch32_1 = ch32;
|
705 |
|
706 | function maj32(x, y, z) {
|
707 | return (x & y) ^ (x & z) ^ (y & z);
|
708 | }
|
709 | var maj32_1 = maj32;
|
710 |
|
711 | function p32(x, y, z) {
|
712 | return x ^ y ^ z;
|
713 | }
|
714 | var p32_1 = p32;
|
715 |
|
716 | function s0_256(x) {
|
717 | return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
|
718 | }
|
719 | var s0_256_1 = s0_256;
|
720 |
|
721 | function s1_256(x) {
|
722 | return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
|
723 | }
|
724 | var s1_256_1 = s1_256;
|
725 |
|
726 | function g0_256(x) {
|
727 | return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
|
728 | }
|
729 | var g0_256_1 = g0_256;
|
730 |
|
731 | function g1_256(x) {
|
732 | return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
|
733 | }
|
734 | var g1_256_1 = g1_256;
|
735 |
|
736 | var common$1 = {
|
737 | ft_1: ft_1_1,
|
738 | ch32: ch32_1,
|
739 | maj32: maj32_1,
|
740 | p32: p32_1,
|
741 | s0_256: s0_256_1,
|
742 | s1_256: s1_256_1,
|
743 | g0_256: g0_256_1,
|
744 | g1_256: g1_256_1
|
745 | };
|
746 |
|
747 | var sum32$1 = utils.sum32;
|
748 | var sum32_4$1 = utils.sum32_4;
|
749 | var sum32_5$1 = utils.sum32_5;
|
750 | var ch32$1 = common$1.ch32;
|
751 | var maj32$1 = common$1.maj32;
|
752 | var s0_256$1 = common$1.s0_256;
|
753 | var s1_256$1 = common$1.s1_256;
|
754 | var g0_256$1 = common$1.g0_256;
|
755 | var g1_256$1 = common$1.g1_256;
|
756 |
|
757 | var BlockHash$1 = common.BlockHash;
|
758 |
|
759 | var sha256_K = [
|
760 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
|
761 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
762 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
763 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
764 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
765 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
766 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
767 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
768 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
769 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
770 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
|
771 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
772 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
|
773 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
774 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
775 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
776 | ];
|
777 |
|
778 | function SHA256() {
|
779 | if (!(this instanceof SHA256))
|
780 | return new SHA256();
|
781 |
|
782 | BlockHash$1.call(this);
|
783 | this.h = [
|
784 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
785 | 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
|
786 | ];
|
787 | this.k = sha256_K;
|
788 | this.W = new Array(64);
|
789 | }
|
790 | utils.inherits(SHA256, BlockHash$1);
|
791 | var _256 = SHA256;
|
792 |
|
793 | SHA256.blockSize = 512;
|
794 | SHA256.outSize = 256;
|
795 | SHA256.hmacStrength = 192;
|
796 | SHA256.padLength = 64;
|
797 |
|
798 | SHA256.prototype._update = function _update(msg, start) {
|
799 | var W = this.W;
|
800 |
|
801 | for (var i = 0; i < 16; i++)
|
802 | W[i] = msg[start + i];
|
803 | for (; i < W.length; i++)
|
804 | W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
|
805 |
|
806 | var a = this.h[0];
|
807 | var b = this.h[1];
|
808 | var c = this.h[2];
|
809 | var d = this.h[3];
|
810 | var e = this.h[4];
|
811 | var f = this.h[5];
|
812 | var g = this.h[6];
|
813 | var h = this.h[7];
|
814 |
|
815 | minimalisticAssert(this.k.length === W.length);
|
816 | for (i = 0; i < W.length; i++) {
|
817 | var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
|
818 | var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
|
819 | h = g;
|
820 | g = f;
|
821 | f = e;
|
822 | e = sum32$1(d, T1);
|
823 | d = c;
|
824 | c = b;
|
825 | b = a;
|
826 | a = sum32$1(T1, T2);
|
827 | }
|
828 |
|
829 | this.h[0] = sum32$1(this.h[0], a);
|
830 | this.h[1] = sum32$1(this.h[1], b);
|
831 | this.h[2] = sum32$1(this.h[2], c);
|
832 | this.h[3] = sum32$1(this.h[3], d);
|
833 | this.h[4] = sum32$1(this.h[4], e);
|
834 | this.h[5] = sum32$1(this.h[5], f);
|
835 | this.h[6] = sum32$1(this.h[6], g);
|
836 | this.h[7] = sum32$1(this.h[7], h);
|
837 | };
|
838 |
|
839 | SHA256.prototype._digest = function digest(enc) {
|
840 | if (enc === 'hex')
|
841 | return utils.toHex32(this.h, 'big');
|
842 | else
|
843 | return utils.split32(this.h, 'big');
|
844 | };
|
845 |
|
846 | var charToInteger = {};
|
847 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
|
848 | for (var i = 0; i < chars.length; i++) {
|
849 | charToInteger[chars.charCodeAt(i)] = i;
|
850 | }
|
851 | function decode(mappings) {
|
852 | var generatedCodeColumn = 0;
|
853 | var sourceFileIndex = 0;
|
854 | var sourceCodeLine = 0;
|
855 | var sourceCodeColumn = 0;
|
856 | var nameIndex = 0;
|
857 | var decoded = [];
|
858 | var line = [];
|
859 | var segment = [];
|
860 | for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
|
861 | var c = mappings.charCodeAt(i);
|
862 | if (c === 44) {
|
863 | if (segment.length)
|
864 | line.push(new Int32Array(segment));
|
865 | segment = [];
|
866 | j = 0;
|
867 | }
|
868 | else if (c === 59) {
|
869 | if (segment.length)
|
870 | line.push(new Int32Array(segment));
|
871 | segment = [];
|
872 | j = 0;
|
873 | decoded.push(line);
|
874 | line = [];
|
875 | generatedCodeColumn = 0;
|
876 | }
|
877 | else {
|
878 | var integer = charToInteger[c];
|
879 | if (integer === undefined) {
|
880 | throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
|
881 | }
|
882 | var hasContinuationBit = integer & 32;
|
883 | integer &= 31;
|
884 | value += integer << shift;
|
885 | if (hasContinuationBit) {
|
886 | shift += 5;
|
887 | }
|
888 | else {
|
889 | var shouldNegate = value & 1;
|
890 | value >>= 1;
|
891 | var num = shouldNegate ? -value : value;
|
892 | if (j == 0) {
|
893 | generatedCodeColumn += num;
|
894 | segment.push(generatedCodeColumn);
|
895 | }
|
896 | else if (j === 1) {
|
897 | sourceFileIndex += num;
|
898 | segment.push(sourceFileIndex);
|
899 | }
|
900 | else if (j === 2) {
|
901 | sourceCodeLine += num;
|
902 | segment.push(sourceCodeLine);
|
903 | }
|
904 | else if (j === 3) {
|
905 | sourceCodeColumn += num;
|
906 | segment.push(sourceCodeColumn);
|
907 | }
|
908 | else if (j === 4) {
|
909 | nameIndex += num;
|
910 | segment.push(nameIndex);
|
911 | }
|
912 | j++;
|
913 | value = shift = 0;
|
914 | }
|
915 | }
|
916 | }
|
917 | if (segment.length)
|
918 | line.push(new Int32Array(segment));
|
919 | decoded.push(line);
|
920 | return decoded;
|
921 | }
|
922 | function encode(decoded) {
|
923 | var sourceFileIndex = 0;
|
924 | var sourceCodeLine = 0;
|
925 | var sourceCodeColumn = 0;
|
926 | var nameIndex = 0;
|
927 | var mappings = '';
|
928 | for (var i = 0; i < decoded.length; i++) {
|
929 | var line = decoded[i];
|
930 | if (i > 0)
|
931 | mappings += ';';
|
932 | if (line.length === 0)
|
933 | continue;
|
934 | var generatedCodeColumn = 0;
|
935 | var lineMappings = [];
|
936 | for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
|
937 | var segment = line_1[_i];
|
938 | var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
|
939 | generatedCodeColumn = segment[0];
|
940 | if (segment.length > 1) {
|
941 | segmentMappings +=
|
942 | encodeInteger(segment[1] - sourceFileIndex) +
|
943 | encodeInteger(segment[2] - sourceCodeLine) +
|
944 | encodeInteger(segment[3] - sourceCodeColumn);
|
945 | sourceFileIndex = segment[1];
|
946 | sourceCodeLine = segment[2];
|
947 | sourceCodeColumn = segment[3];
|
948 | }
|
949 | if (segment.length === 5) {
|
950 | segmentMappings += encodeInteger(segment[4] - nameIndex);
|
951 | nameIndex = segment[4];
|
952 | }
|
953 | lineMappings.push(segmentMappings);
|
954 | }
|
955 | mappings += lineMappings.join(',');
|
956 | }
|
957 | return mappings;
|
958 | }
|
959 | function encodeInteger(num) {
|
960 | var result = '';
|
961 | num = num < 0 ? (-num << 1) | 1 : num << 1;
|
962 | do {
|
963 | var clamped = num & 31;
|
964 | num >>= 5;
|
965 | if (num > 0) {
|
966 | clamped |= 32;
|
967 | }
|
968 | result += chars[clamped];
|
969 | } while (num > 0);
|
970 | return result;
|
971 | }
|
972 |
|
973 | var Chunk = function Chunk(start, end, content) {
|
974 | this.start = start;
|
975 | this.end = end;
|
976 | this.original = content;
|
977 |
|
978 | this.intro = '';
|
979 | this.outro = '';
|
980 |
|
981 | this.content = content;
|
982 | this.storeName = false;
|
983 | this.edited = false;
|
984 |
|
985 |
|
986 | Object.defineProperties(this, {
|
987 | previous: { writable: true, value: null },
|
988 | next: { writable: true, value: null }
|
989 | });
|
990 | };
|
991 |
|
992 | Chunk.prototype.appendLeft = function appendLeft (content) {
|
993 | this.outro += content;
|
994 | };
|
995 |
|
996 | Chunk.prototype.appendRight = function appendRight (content) {
|
997 | this.intro = this.intro + content;
|
998 | };
|
999 |
|
1000 | Chunk.prototype.clone = function clone () {
|
1001 | var chunk = new Chunk(this.start, this.end, this.original);
|
1002 |
|
1003 | chunk.intro = this.intro;
|
1004 | chunk.outro = this.outro;
|
1005 | chunk.content = this.content;
|
1006 | chunk.storeName = this.storeName;
|
1007 | chunk.edited = this.edited;
|
1008 |
|
1009 | return chunk;
|
1010 | };
|
1011 |
|
1012 | Chunk.prototype.contains = function contains (index) {
|
1013 | return this.start < index && index < this.end;
|
1014 | };
|
1015 |
|
1016 | Chunk.prototype.eachNext = function eachNext (fn) {
|
1017 | var chunk = this;
|
1018 | while (chunk) {
|
1019 | fn(chunk);
|
1020 | chunk = chunk.next;
|
1021 | }
|
1022 | };
|
1023 |
|
1024 | Chunk.prototype.eachPrevious = function eachPrevious (fn) {
|
1025 | var chunk = this;
|
1026 | while (chunk) {
|
1027 | fn(chunk);
|
1028 | chunk = chunk.previous;
|
1029 | }
|
1030 | };
|
1031 |
|
1032 | Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
|
1033 | this.content = content;
|
1034 | if (!contentOnly) {
|
1035 | this.intro = '';
|
1036 | this.outro = '';
|
1037 | }
|
1038 | this.storeName = storeName;
|
1039 |
|
1040 | this.edited = true;
|
1041 |
|
1042 | return this;
|
1043 | };
|
1044 |
|
1045 | Chunk.prototype.prependLeft = function prependLeft (content) {
|
1046 | this.outro = content + this.outro;
|
1047 | };
|
1048 |
|
1049 | Chunk.prototype.prependRight = function prependRight (content) {
|
1050 | this.intro = content + this.intro;
|
1051 | };
|
1052 |
|
1053 | Chunk.prototype.split = function split (index) {
|
1054 | var sliceIndex = index - this.start;
|
1055 |
|
1056 | var originalBefore = this.original.slice(0, sliceIndex);
|
1057 | var originalAfter = this.original.slice(sliceIndex);
|
1058 |
|
1059 | this.original = originalBefore;
|
1060 |
|
1061 | var newChunk = new Chunk(index, this.end, originalAfter);
|
1062 | newChunk.outro = this.outro;
|
1063 | this.outro = '';
|
1064 |
|
1065 | this.end = index;
|
1066 |
|
1067 | if (this.edited) {
|
1068 |
|
1069 | newChunk.edit('', false);
|
1070 | this.content = '';
|
1071 | } else {
|
1072 | this.content = originalBefore;
|
1073 | }
|
1074 |
|
1075 | newChunk.next = this.next;
|
1076 | if (newChunk.next) { newChunk.next.previous = newChunk; }
|
1077 | newChunk.previous = this;
|
1078 | this.next = newChunk;
|
1079 |
|
1080 | return newChunk;
|
1081 | };
|
1082 |
|
1083 | Chunk.prototype.toString = function toString () {
|
1084 | return this.intro + this.content + this.outro;
|
1085 | };
|
1086 |
|
1087 | Chunk.prototype.trimEnd = function trimEnd (rx) {
|
1088 | this.outro = this.outro.replace(rx, '');
|
1089 | if (this.outro.length) { return true; }
|
1090 |
|
1091 | var trimmed = this.content.replace(rx, '');
|
1092 |
|
1093 | if (trimmed.length) {
|
1094 | if (trimmed !== this.content) {
|
1095 | this.split(this.start + trimmed.length).edit('', undefined, true);
|
1096 | }
|
1097 | return true;
|
1098 |
|
1099 | } else {
|
1100 | this.edit('', undefined, true);
|
1101 |
|
1102 | this.intro = this.intro.replace(rx, '');
|
1103 | if (this.intro.length) { return true; }
|
1104 | }
|
1105 | };
|
1106 |
|
1107 | Chunk.prototype.trimStart = function trimStart (rx) {
|
1108 | this.intro = this.intro.replace(rx, '');
|
1109 | if (this.intro.length) { return true; }
|
1110 |
|
1111 | var trimmed = this.content.replace(rx, '');
|
1112 |
|
1113 | if (trimmed.length) {
|
1114 | if (trimmed !== this.content) {
|
1115 | this.split(this.end - trimmed.length);
|
1116 | this.edit('', undefined, true);
|
1117 | }
|
1118 | return true;
|
1119 |
|
1120 | } else {
|
1121 | this.edit('', undefined, true);
|
1122 |
|
1123 | this.outro = this.outro.replace(rx, '');
|
1124 | if (this.outro.length) { return true; }
|
1125 | }
|
1126 | };
|
1127 |
|
1128 | var btoa = function () {
|
1129 | throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
|
1130 | };
|
1131 | if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
|
1132 | btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
|
1133 | } else if (typeof Buffer === 'function') {
|
1134 | btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
|
1135 | }
|
1136 |
|
1137 | var SourceMap = function SourceMap(properties) {
|
1138 | this.version = 3;
|
1139 | this.file = properties.file;
|
1140 | this.sources = properties.sources;
|
1141 | this.sourcesContent = properties.sourcesContent;
|
1142 | this.names = properties.names;
|
1143 | this.mappings = encode(properties.mappings);
|
1144 | };
|
1145 |
|
1146 | SourceMap.prototype.toString = function toString () {
|
1147 | return JSON.stringify(this);
|
1148 | };
|
1149 |
|
1150 | SourceMap.prototype.toUrl = function toUrl () {
|
1151 | return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
|
1152 | };
|
1153 |
|
1154 | function guessIndent(code) {
|
1155 | var lines = code.split('\n');
|
1156 |
|
1157 | var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
|
1158 | var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
|
1159 |
|
1160 | if (tabbed.length === 0 && spaced.length === 0) {
|
1161 | return null;
|
1162 | }
|
1163 |
|
1164 |
|
1165 |
|
1166 |
|
1167 | if (tabbed.length >= spaced.length) {
|
1168 | return '\t';
|
1169 | }
|
1170 |
|
1171 |
|
1172 | var min = spaced.reduce(function (previous, current) {
|
1173 | var numSpaces = /^ +/.exec(current)[0].length;
|
1174 | return Math.min(numSpaces, previous);
|
1175 | }, Infinity);
|
1176 |
|
1177 | return new Array(min + 1).join(' ');
|
1178 | }
|
1179 |
|
1180 | function getRelativePath(from, to) {
|
1181 | var fromParts = from.split(/[/\\]/);
|
1182 | var toParts = to.split(/[/\\]/);
|
1183 |
|
1184 | fromParts.pop();
|
1185 |
|
1186 | while (fromParts[0] === toParts[0]) {
|
1187 | fromParts.shift();
|
1188 | toParts.shift();
|
1189 | }
|
1190 |
|
1191 | if (fromParts.length) {
|
1192 | var i = fromParts.length;
|
1193 | while (i--) { fromParts[i] = '..'; }
|
1194 | }
|
1195 |
|
1196 | return fromParts.concat(toParts).join('/');
|
1197 | }
|
1198 |
|
1199 | var toString = Object.prototype.toString;
|
1200 |
|
1201 | function isObject(thing) {
|
1202 | return toString.call(thing) === '[object Object]';
|
1203 | }
|
1204 |
|
1205 | function getLocator(source) {
|
1206 | var originalLines = source.split('\n');
|
1207 | var lineOffsets = [];
|
1208 |
|
1209 | for (var i = 0, pos = 0; i < originalLines.length; i++) {
|
1210 | lineOffsets.push(pos);
|
1211 | pos += originalLines[i].length + 1;
|
1212 | }
|
1213 |
|
1214 | return function locate(index) {
|
1215 | var i = 0;
|
1216 | var j = lineOffsets.length;
|
1217 | while (i < j) {
|
1218 | var m = (i + j) >> 1;
|
1219 | if (index < lineOffsets[m]) {
|
1220 | j = m;
|
1221 | } else {
|
1222 | i = m + 1;
|
1223 | }
|
1224 | }
|
1225 | var line = i - 1;
|
1226 | var column = index - lineOffsets[line];
|
1227 | return { line: line, column: column };
|
1228 | };
|
1229 | }
|
1230 |
|
1231 | var Mappings = function Mappings(hires) {
|
1232 | this.hires = hires;
|
1233 | this.generatedCodeLine = 0;
|
1234 | this.generatedCodeColumn = 0;
|
1235 | this.raw = [];
|
1236 | this.rawSegments = this.raw[this.generatedCodeLine] = [];
|
1237 | this.pending = null;
|
1238 | };
|
1239 |
|
1240 | Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
|
1241 | if (content.length) {
|
1242 | var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
1243 | if (nameIndex >= 0) {
|
1244 | segment.push(nameIndex);
|
1245 | }
|
1246 | this.rawSegments.push(segment);
|
1247 | } else if (this.pending) {
|
1248 | this.rawSegments.push(this.pending);
|
1249 | }
|
1250 |
|
1251 | this.advance(content);
|
1252 | this.pending = null;
|
1253 | };
|
1254 |
|
1255 | Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
|
1256 | var originalCharIndex = chunk.start;
|
1257 | var first = true;
|
1258 |
|
1259 | while (originalCharIndex < chunk.end) {
|
1260 | if (this.hires || first || sourcemapLocations[originalCharIndex]) {
|
1261 | this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
|
1262 | }
|
1263 |
|
1264 | if (original[originalCharIndex] === '\n') {
|
1265 | loc.line += 1;
|
1266 | loc.column = 0;
|
1267 | this.generatedCodeLine += 1;
|
1268 | this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
1269 | this.generatedCodeColumn = 0;
|
1270 | } else {
|
1271 | loc.column += 1;
|
1272 | this.generatedCodeColumn += 1;
|
1273 | }
|
1274 |
|
1275 | originalCharIndex += 1;
|
1276 | first = false;
|
1277 | }
|
1278 |
|
1279 | this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
1280 | };
|
1281 |
|
1282 | Mappings.prototype.advance = function advance (str) {
|
1283 | if (!str) { return; }
|
1284 |
|
1285 | var lines = str.split('\n');
|
1286 |
|
1287 | if (lines.length > 1) {
|
1288 | for (var i = 0; i < lines.length - 1; i++) {
|
1289 | this.generatedCodeLine++;
|
1290 | this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
1291 | }
|
1292 | this.generatedCodeColumn = 0;
|
1293 | }
|
1294 |
|
1295 | this.generatedCodeColumn += lines[lines.length - 1].length;
|
1296 | };
|
1297 |
|
1298 | var n = '\n';
|
1299 |
|
1300 | var warned = {
|
1301 | insertLeft: false,
|
1302 | insertRight: false,
|
1303 | storeName: false
|
1304 | };
|
1305 |
|
1306 | var MagicString = function MagicString(string, options) {
|
1307 | if ( options === void 0 ) options = {};
|
1308 |
|
1309 | var chunk = new Chunk(0, string.length, string);
|
1310 |
|
1311 | Object.defineProperties(this, {
|
1312 | original: { writable: true, value: string },
|
1313 | outro: { writable: true, value: '' },
|
1314 | intro: { writable: true, value: '' },
|
1315 | firstChunk: { writable: true, value: chunk },
|
1316 | lastChunk: { writable: true, value: chunk },
|
1317 | lastSearchedChunk: { writable: true, value: chunk },
|
1318 | byStart: { writable: true, value: {} },
|
1319 | byEnd: { writable: true, value: {} },
|
1320 | filename: { writable: true, value: options.filename },
|
1321 | indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
|
1322 | sourcemapLocations: { writable: true, value: {} },
|
1323 | storedNames: { writable: true, value: {} },
|
1324 | indentStr: { writable: true, value: guessIndent(string) }
|
1325 | });
|
1326 |
|
1327 | this.byStart[0] = chunk;
|
1328 | this.byEnd[string.length] = chunk;
|
1329 | };
|
1330 |
|
1331 | MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
|
1332 | this.sourcemapLocations[char] = true;
|
1333 | };
|
1334 |
|
1335 | MagicString.prototype.append = function append (content) {
|
1336 | if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
|
1337 |
|
1338 | this.outro += content;
|
1339 | return this;
|
1340 | };
|
1341 |
|
1342 | MagicString.prototype.appendLeft = function appendLeft (index, content) {
|
1343 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
1344 |
|
1345 | this._split(index);
|
1346 |
|
1347 | var chunk = this.byEnd[index];
|
1348 |
|
1349 | if (chunk) {
|
1350 | chunk.appendLeft(content);
|
1351 | } else {
|
1352 | this.intro += content;
|
1353 | }
|
1354 | return this;
|
1355 | };
|
1356 |
|
1357 | MagicString.prototype.appendRight = function appendRight (index, content) {
|
1358 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
1359 |
|
1360 | this._split(index);
|
1361 |
|
1362 | var chunk = this.byStart[index];
|
1363 |
|
1364 | if (chunk) {
|
1365 | chunk.appendRight(content);
|
1366 | } else {
|
1367 | this.outro += content;
|
1368 | }
|
1369 | return this;
|
1370 | };
|
1371 |
|
1372 | MagicString.prototype.clone = function clone () {
|
1373 | var cloned = new MagicString(this.original, { filename: this.filename });
|
1374 |
|
1375 | var originalChunk = this.firstChunk;
|
1376 | var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
|
1377 |
|
1378 | while (originalChunk) {
|
1379 | cloned.byStart[clonedChunk.start] = clonedChunk;
|
1380 | cloned.byEnd[clonedChunk.end] = clonedChunk;
|
1381 |
|
1382 | var nextOriginalChunk = originalChunk.next;
|
1383 | var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
|
1384 |
|
1385 | if (nextClonedChunk) {
|
1386 | clonedChunk.next = nextClonedChunk;
|
1387 | nextClonedChunk.previous = clonedChunk;
|
1388 |
|
1389 | clonedChunk = nextClonedChunk;
|
1390 | }
|
1391 |
|
1392 | originalChunk = nextOriginalChunk;
|
1393 | }
|
1394 |
|
1395 | cloned.lastChunk = clonedChunk;
|
1396 |
|
1397 | if (this.indentExclusionRanges) {
|
1398 | cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
|
1399 | }
|
1400 |
|
1401 | Object.keys(this.sourcemapLocations).forEach(function (loc) {
|
1402 | cloned.sourcemapLocations[loc] = true;
|
1403 | });
|
1404 |
|
1405 | return cloned;
|
1406 | };
|
1407 |
|
1408 | MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
|
1409 | var this$1 = this;
|
1410 |
|
1411 | options = options || {};
|
1412 |
|
1413 | var sourceIndex = 0;
|
1414 | var names = Object.keys(this.storedNames);
|
1415 | var mappings = new Mappings(options.hires);
|
1416 |
|
1417 | var locate = getLocator(this.original);
|
1418 |
|
1419 | if (this.intro) {
|
1420 | mappings.advance(this.intro);
|
1421 | }
|
1422 |
|
1423 | this.firstChunk.eachNext(function (chunk) {
|
1424 | var loc = locate(chunk.start);
|
1425 |
|
1426 | if (chunk.intro.length) { mappings.advance(chunk.intro); }
|
1427 |
|
1428 | if (chunk.edited) {
|
1429 | mappings.addEdit(
|
1430 | sourceIndex,
|
1431 | chunk.content,
|
1432 | loc,
|
1433 | chunk.storeName ? names.indexOf(chunk.original) : -1
|
1434 | );
|
1435 | } else {
|
1436 | mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
|
1437 | }
|
1438 |
|
1439 | if (chunk.outro.length) { mappings.advance(chunk.outro); }
|
1440 | });
|
1441 |
|
1442 | return {
|
1443 | file: options.file ? options.file.split(/[/\\]/).pop() : null,
|
1444 | sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
|
1445 | sourcesContent: options.includeContent ? [this.original] : [null],
|
1446 | names: names,
|
1447 | mappings: mappings.raw
|
1448 | };
|
1449 | };
|
1450 |
|
1451 | MagicString.prototype.generateMap = function generateMap (options) {
|
1452 | return new SourceMap(this.generateDecodedMap(options));
|
1453 | };
|
1454 |
|
1455 | MagicString.prototype.getIndentString = function getIndentString () {
|
1456 | return this.indentStr === null ? '\t' : this.indentStr;
|
1457 | };
|
1458 |
|
1459 | MagicString.prototype.indent = function indent (indentStr, options) {
|
1460 | var pattern = /^[^\r\n]/gm;
|
1461 |
|
1462 | if (isObject(indentStr)) {
|
1463 | options = indentStr;
|
1464 | indentStr = undefined;
|
1465 | }
|
1466 |
|
1467 | indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
|
1468 |
|
1469 | if (indentStr === '') { return this; }
|
1470 |
|
1471 | options = options || {};
|
1472 |
|
1473 |
|
1474 | var isExcluded = {};
|
1475 |
|
1476 | if (options.exclude) {
|
1477 | var exclusions =
|
1478 | typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
|
1479 | exclusions.forEach(function (exclusion) {
|
1480 | for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
|
1481 | isExcluded[i] = true;
|
1482 | }
|
1483 | });
|
1484 | }
|
1485 |
|
1486 | var shouldIndentNextCharacter = options.indentStart !== false;
|
1487 | var replacer = function (match) {
|
1488 | if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
|
1489 | shouldIndentNextCharacter = true;
|
1490 | return match;
|
1491 | };
|
1492 |
|
1493 | this.intro = this.intro.replace(pattern, replacer);
|
1494 |
|
1495 | var charIndex = 0;
|
1496 | var chunk = this.firstChunk;
|
1497 |
|
1498 | while (chunk) {
|
1499 | var end = chunk.end;
|
1500 |
|
1501 | if (chunk.edited) {
|
1502 | if (!isExcluded[charIndex]) {
|
1503 | chunk.content = chunk.content.replace(pattern, replacer);
|
1504 |
|
1505 | if (chunk.content.length) {
|
1506 | shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
|
1507 | }
|
1508 | }
|
1509 | } else {
|
1510 | charIndex = chunk.start;
|
1511 |
|
1512 | while (charIndex < end) {
|
1513 | if (!isExcluded[charIndex]) {
|
1514 | var char = this.original[charIndex];
|
1515 |
|
1516 | if (char === '\n') {
|
1517 | shouldIndentNextCharacter = true;
|
1518 | } else if (char !== '\r' && shouldIndentNextCharacter) {
|
1519 | shouldIndentNextCharacter = false;
|
1520 |
|
1521 | if (charIndex === chunk.start) {
|
1522 | chunk.prependRight(indentStr);
|
1523 | } else {
|
1524 | this._splitChunk(chunk, charIndex);
|
1525 | chunk = chunk.next;
|
1526 | chunk.prependRight(indentStr);
|
1527 | }
|
1528 | }
|
1529 | }
|
1530 |
|
1531 | charIndex += 1;
|
1532 | }
|
1533 | }
|
1534 |
|
1535 | charIndex = chunk.end;
|
1536 | chunk = chunk.next;
|
1537 | }
|
1538 |
|
1539 | this.outro = this.outro.replace(pattern, replacer);
|
1540 |
|
1541 | return this;
|
1542 | };
|
1543 |
|
1544 | MagicString.prototype.insert = function insert () {
|
1545 | throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
|
1546 | };
|
1547 |
|
1548 | MagicString.prototype.insertLeft = function insertLeft (index, content) {
|
1549 | if (!warned.insertLeft) {
|
1550 | console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead');
|
1551 | warned.insertLeft = true;
|
1552 | }
|
1553 |
|
1554 | return this.appendLeft(index, content);
|
1555 | };
|
1556 |
|
1557 | MagicString.prototype.insertRight = function insertRight (index, content) {
|
1558 | if (!warned.insertRight) {
|
1559 | console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead');
|
1560 | warned.insertRight = true;
|
1561 | }
|
1562 |
|
1563 | return this.prependRight(index, content);
|
1564 | };
|
1565 |
|
1566 | MagicString.prototype.move = function move (start, end, index) {
|
1567 | if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
|
1568 |
|
1569 | this._split(start);
|
1570 | this._split(end);
|
1571 | this._split(index);
|
1572 |
|
1573 | var first = this.byStart[start];
|
1574 | var last = this.byEnd[end];
|
1575 |
|
1576 | var oldLeft = first.previous;
|
1577 | var oldRight = last.next;
|
1578 |
|
1579 | var newRight = this.byStart[index];
|
1580 | if (!newRight && last === this.lastChunk) { return this; }
|
1581 | var newLeft = newRight ? newRight.previous : this.lastChunk;
|
1582 |
|
1583 | if (oldLeft) { oldLeft.next = oldRight; }
|
1584 | if (oldRight) { oldRight.previous = oldLeft; }
|
1585 |
|
1586 | if (newLeft) { newLeft.next = first; }
|
1587 | if (newRight) { newRight.previous = last; }
|
1588 |
|
1589 | if (!first.previous) { this.firstChunk = last.next; }
|
1590 | if (!last.next) {
|
1591 | this.lastChunk = first.previous;
|
1592 | this.lastChunk.next = null;
|
1593 | }
|
1594 |
|
1595 | first.previous = newLeft;
|
1596 | last.next = newRight || null;
|
1597 |
|
1598 | if (!newLeft) { this.firstChunk = first; }
|
1599 | if (!newRight) { this.lastChunk = last; }
|
1600 | return this;
|
1601 | };
|
1602 |
|
1603 | MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
|
1604 | if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
|
1605 |
|
1606 | while (start < 0) { start += this.original.length; }
|
1607 | while (end < 0) { end += this.original.length; }
|
1608 |
|
1609 | if (end > this.original.length) { throw new Error('end is out of bounds'); }
|
1610 | if (start === end)
|
1611 | { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
|
1612 |
|
1613 | this._split(start);
|
1614 | this._split(end);
|
1615 |
|
1616 | if (options === true) {
|
1617 | if (!warned.storeName) {
|
1618 | console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string');
|
1619 | warned.storeName = true;
|
1620 | }
|
1621 |
|
1622 | options = { storeName: true };
|
1623 | }
|
1624 | var storeName = options !== undefined ? options.storeName : false;
|
1625 | var contentOnly = options !== undefined ? options.contentOnly : false;
|
1626 |
|
1627 | if (storeName) {
|
1628 | var original = this.original.slice(start, end);
|
1629 | this.storedNames[original] = true;
|
1630 | }
|
1631 |
|
1632 | var first = this.byStart[start];
|
1633 | var last = this.byEnd[end];
|
1634 |
|
1635 | if (first) {
|
1636 | if (end > first.end && first.next !== this.byStart[first.end]) {
|
1637 | throw new Error('Cannot overwrite across a split point');
|
1638 | }
|
1639 |
|
1640 | first.edit(content, storeName, contentOnly);
|
1641 |
|
1642 | if (first !== last) {
|
1643 | var chunk = first.next;
|
1644 | while (chunk !== last) {
|
1645 | chunk.edit('', false);
|
1646 | chunk = chunk.next;
|
1647 | }
|
1648 |
|
1649 | chunk.edit('', false);
|
1650 | }
|
1651 | } else {
|
1652 |
|
1653 | var newChunk = new Chunk(start, end, '').edit(content, storeName);
|
1654 |
|
1655 |
|
1656 | last.next = newChunk;
|
1657 | newChunk.previous = last;
|
1658 | }
|
1659 | return this;
|
1660 | };
|
1661 |
|
1662 | MagicString.prototype.prepend = function prepend (content) {
|
1663 | if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
|
1664 |
|
1665 | this.intro = content + this.intro;
|
1666 | return this;
|
1667 | };
|
1668 |
|
1669 | MagicString.prototype.prependLeft = function prependLeft (index, content) {
|
1670 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
1671 |
|
1672 | this._split(index);
|
1673 |
|
1674 | var chunk = this.byEnd[index];
|
1675 |
|
1676 | if (chunk) {
|
1677 | chunk.prependLeft(content);
|
1678 | } else {
|
1679 | this.intro = content + this.intro;
|
1680 | }
|
1681 | return this;
|
1682 | };
|
1683 |
|
1684 | MagicString.prototype.prependRight = function prependRight (index, content) {
|
1685 | if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
|
1686 |
|
1687 | this._split(index);
|
1688 |
|
1689 | var chunk = this.byStart[index];
|
1690 |
|
1691 | if (chunk) {
|
1692 | chunk.prependRight(content);
|
1693 | } else {
|
1694 | this.outro = content + this.outro;
|
1695 | }
|
1696 | return this;
|
1697 | };
|
1698 |
|
1699 | MagicString.prototype.remove = function remove (start, end) {
|
1700 | while (start < 0) { start += this.original.length; }
|
1701 | while (end < 0) { end += this.original.length; }
|
1702 |
|
1703 | if (start === end) { return this; }
|
1704 |
|
1705 | if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
|
1706 | if (start > end) { throw new Error('end must be greater than start'); }
|
1707 |
|
1708 | this._split(start);
|
1709 | this._split(end);
|
1710 |
|
1711 | var chunk = this.byStart[start];
|
1712 |
|
1713 | while (chunk) {
|
1714 | chunk.intro = '';
|
1715 | chunk.outro = '';
|
1716 | chunk.edit('');
|
1717 |
|
1718 | chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
1719 | }
|
1720 | return this;
|
1721 | };
|
1722 |
|
1723 | MagicString.prototype.lastChar = function lastChar () {
|
1724 | if (this.outro.length)
|
1725 | { return this.outro[this.outro.length - 1]; }
|
1726 | var chunk = this.lastChunk;
|
1727 | do {
|
1728 | if (chunk.outro.length)
|
1729 | { return chunk.outro[chunk.outro.length - 1]; }
|
1730 | if (chunk.content.length)
|
1731 | { return chunk.content[chunk.content.length - 1]; }
|
1732 | if (chunk.intro.length)
|
1733 | { return chunk.intro[chunk.intro.length - 1]; }
|
1734 | } while (chunk = chunk.previous);
|
1735 | if (this.intro.length)
|
1736 | { return this.intro[this.intro.length - 1]; }
|
1737 | return '';
|
1738 | };
|
1739 |
|
1740 | MagicString.prototype.lastLine = function lastLine () {
|
1741 | var lineIndex = this.outro.lastIndexOf(n);
|
1742 | if (lineIndex !== -1)
|
1743 | { return this.outro.substr(lineIndex + 1); }
|
1744 | var lineStr = this.outro;
|
1745 | var chunk = this.lastChunk;
|
1746 | do {
|
1747 | if (chunk.outro.length > 0) {
|
1748 | lineIndex = chunk.outro.lastIndexOf(n);
|
1749 | if (lineIndex !== -1)
|
1750 | { return chunk.outro.substr(lineIndex + 1) + lineStr; }
|
1751 | lineStr = chunk.outro + lineStr;
|
1752 | }
|
1753 |
|
1754 | if (chunk.content.length > 0) {
|
1755 | lineIndex = chunk.content.lastIndexOf(n);
|
1756 | if (lineIndex !== -1)
|
1757 | { return chunk.content.substr(lineIndex + 1) + lineStr; }
|
1758 | lineStr = chunk.content + lineStr;
|
1759 | }
|
1760 |
|
1761 | if (chunk.intro.length > 0) {
|
1762 | lineIndex = chunk.intro.lastIndexOf(n);
|
1763 | if (lineIndex !== -1)
|
1764 | { return chunk.intro.substr(lineIndex + 1) + lineStr; }
|
1765 | lineStr = chunk.intro + lineStr;
|
1766 | }
|
1767 | } while (chunk = chunk.previous);
|
1768 | lineIndex = this.intro.lastIndexOf(n);
|
1769 | if (lineIndex !== -1)
|
1770 | { return this.intro.substr(lineIndex + 1) + lineStr; }
|
1771 | return this.intro + lineStr;
|
1772 | };
|
1773 |
|
1774 | MagicString.prototype.slice = function slice (start, end) {
|
1775 | if ( start === void 0 ) start = 0;
|
1776 | if ( end === void 0 ) end = this.original.length;
|
1777 |
|
1778 | while (start < 0) { start += this.original.length; }
|
1779 | while (end < 0) { end += this.original.length; }
|
1780 |
|
1781 | var result = '';
|
1782 |
|
1783 |
|
1784 | var chunk = this.firstChunk;
|
1785 | while (chunk && (chunk.start > start || chunk.end <= start)) {
|
1786 |
|
1787 | if (chunk.start < end && chunk.end >= end) {
|
1788 | return result;
|
1789 | }
|
1790 |
|
1791 | chunk = chunk.next;
|
1792 | }
|
1793 |
|
1794 | if (chunk && chunk.edited && chunk.start !== start)
|
1795 | { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
|
1796 |
|
1797 | var startChunk = chunk;
|
1798 | while (chunk) {
|
1799 | if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
|
1800 | result += chunk.intro;
|
1801 | }
|
1802 |
|
1803 | var containsEnd = chunk.start < end && chunk.end >= end;
|
1804 | if (containsEnd && chunk.edited && chunk.end !== end)
|
1805 | { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
|
1806 |
|
1807 | var sliceStart = startChunk === chunk ? start - chunk.start : 0;
|
1808 | var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
|
1809 |
|
1810 | result += chunk.content.slice(sliceStart, sliceEnd);
|
1811 |
|
1812 | if (chunk.outro && (!containsEnd || chunk.end === end)) {
|
1813 | result += chunk.outro;
|
1814 | }
|
1815 |
|
1816 | if (containsEnd) {
|
1817 | break;
|
1818 | }
|
1819 |
|
1820 | chunk = chunk.next;
|
1821 | }
|
1822 |
|
1823 | return result;
|
1824 | };
|
1825 |
|
1826 |
|
1827 | MagicString.prototype.snip = function snip (start, end) {
|
1828 | var clone = this.clone();
|
1829 | clone.remove(0, start);
|
1830 | clone.remove(end, clone.original.length);
|
1831 |
|
1832 | return clone;
|
1833 | };
|
1834 |
|
1835 | MagicString.prototype._split = function _split (index) {
|
1836 | if (this.byStart[index] || this.byEnd[index]) { return; }
|
1837 |
|
1838 | var chunk = this.lastSearchedChunk;
|
1839 | var searchForward = index > chunk.end;
|
1840 |
|
1841 | while (chunk) {
|
1842 | if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
|
1843 |
|
1844 | chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
|
1845 | }
|
1846 | };
|
1847 |
|
1848 | MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
|
1849 | if (chunk.edited && chunk.content.length) {
|
1850 |
|
1851 | var loc = getLocator(this.original)(index);
|
1852 | throw new Error(
|
1853 | ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
|
1854 | );
|
1855 | }
|
1856 |
|
1857 | var newChunk = chunk.split(index);
|
1858 |
|
1859 | this.byEnd[index] = chunk;
|
1860 | this.byStart[index] = newChunk;
|
1861 | this.byEnd[newChunk.end] = newChunk;
|
1862 |
|
1863 | if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
|
1864 |
|
1865 | this.lastSearchedChunk = chunk;
|
1866 | return true;
|
1867 | };
|
1868 |
|
1869 | MagicString.prototype.toString = function toString () {
|
1870 | var str = this.intro;
|
1871 |
|
1872 | var chunk = this.firstChunk;
|
1873 | while (chunk) {
|
1874 | str += chunk.toString();
|
1875 | chunk = chunk.next;
|
1876 | }
|
1877 |
|
1878 | return str + this.outro;
|
1879 | };
|
1880 |
|
1881 | MagicString.prototype.isEmpty = function isEmpty () {
|
1882 | var chunk = this.firstChunk;
|
1883 | do {
|
1884 | if (chunk.intro.length && chunk.intro.trim() ||
|
1885 | chunk.content.length && chunk.content.trim() ||
|
1886 | chunk.outro.length && chunk.outro.trim())
|
1887 | { return false; }
|
1888 | } while (chunk = chunk.next);
|
1889 | return true;
|
1890 | };
|
1891 |
|
1892 | MagicString.prototype.length = function length () {
|
1893 | var chunk = this.firstChunk;
|
1894 | var length = 0;
|
1895 | do {
|
1896 | length += chunk.intro.length + chunk.content.length + chunk.outro.length;
|
1897 | } while (chunk = chunk.next);
|
1898 | return length;
|
1899 | };
|
1900 |
|
1901 | MagicString.prototype.trimLines = function trimLines () {
|
1902 | return this.trim('[\\r\\n]');
|
1903 | };
|
1904 |
|
1905 | MagicString.prototype.trim = function trim (charType) {
|
1906 | return this.trimStart(charType).trimEnd(charType);
|
1907 | };
|
1908 |
|
1909 | MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
|
1910 | var rx = new RegExp((charType || '\\s') + '+$');
|
1911 |
|
1912 | this.outro = this.outro.replace(rx, '');
|
1913 | if (this.outro.length) { return true; }
|
1914 |
|
1915 | var chunk = this.lastChunk;
|
1916 |
|
1917 | do {
|
1918 | var end = chunk.end;
|
1919 | var aborted = chunk.trimEnd(rx);
|
1920 |
|
1921 |
|
1922 | if (chunk.end !== end) {
|
1923 | if (this.lastChunk === chunk) {
|
1924 | this.lastChunk = chunk.next;
|
1925 | }
|
1926 |
|
1927 | this.byEnd[chunk.end] = chunk;
|
1928 | this.byStart[chunk.next.start] = chunk.next;
|
1929 | this.byEnd[chunk.next.end] = chunk.next;
|
1930 | }
|
1931 |
|
1932 | if (aborted) { return true; }
|
1933 | chunk = chunk.previous;
|
1934 | } while (chunk);
|
1935 |
|
1936 | return false;
|
1937 | };
|
1938 |
|
1939 | MagicString.prototype.trimEnd = function trimEnd (charType) {
|
1940 | this.trimEndAborted(charType);
|
1941 | return this;
|
1942 | };
|
1943 | MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
|
1944 | var rx = new RegExp('^' + (charType || '\\s') + '+');
|
1945 |
|
1946 | this.intro = this.intro.replace(rx, '');
|
1947 | if (this.intro.length) { return true; }
|
1948 |
|
1949 | var chunk = this.firstChunk;
|
1950 |
|
1951 | do {
|
1952 | var end = chunk.end;
|
1953 | var aborted = chunk.trimStart(rx);
|
1954 |
|
1955 | if (chunk.end !== end) {
|
1956 |
|
1957 | if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
|
1958 |
|
1959 | this.byEnd[chunk.end] = chunk;
|
1960 | this.byStart[chunk.next.start] = chunk.next;
|
1961 | this.byEnd[chunk.next.end] = chunk.next;
|
1962 | }
|
1963 |
|
1964 | if (aborted) { return true; }
|
1965 | chunk = chunk.next;
|
1966 | } while (chunk);
|
1967 |
|
1968 | return false;
|
1969 | };
|
1970 |
|
1971 | MagicString.prototype.trimStart = function trimStart (charType) {
|
1972 | this.trimStartAborted(charType);
|
1973 | return this;
|
1974 | };
|
1975 |
|
1976 | var hasOwnProp = Object.prototype.hasOwnProperty;
|
1977 |
|
1978 | var Bundle = function Bundle(options) {
|
1979 | if ( options === void 0 ) options = {};
|
1980 |
|
1981 | this.intro = options.intro || '';
|
1982 | this.separator = options.separator !== undefined ? options.separator : '\n';
|
1983 | this.sources = [];
|
1984 | this.uniqueSources = [];
|
1985 | this.uniqueSourceIndexByFilename = {};
|
1986 | };
|
1987 |
|
1988 | Bundle.prototype.addSource = function addSource (source) {
|
1989 | if (source instanceof MagicString) {
|
1990 | return this.addSource({
|
1991 | content: source,
|
1992 | filename: source.filename,
|
1993 | separator: this.separator
|
1994 | });
|
1995 | }
|
1996 |
|
1997 | if (!isObject(source) || !source.content) {
|
1998 | throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
|
1999 | }
|
2000 |
|
2001 | ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
|
2002 | if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
|
2003 | });
|
2004 |
|
2005 | if (source.separator === undefined) {
|
2006 |
|
2007 | source.separator = this.separator;
|
2008 | }
|
2009 |
|
2010 | if (source.filename) {
|
2011 | if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
|
2012 | this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
|
2013 | this.uniqueSources.push({ filename: source.filename, content: source.content.original });
|
2014 | } else {
|
2015 | var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
|
2016 | if (source.content.original !== uniqueSource.content) {
|
2017 | throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
|
2018 | }
|
2019 | }
|
2020 | }
|
2021 |
|
2022 | this.sources.push(source);
|
2023 | return this;
|
2024 | };
|
2025 |
|
2026 | Bundle.prototype.append = function append (str, options) {
|
2027 | this.addSource({
|
2028 | content: new MagicString(str),
|
2029 | separator: (options && options.separator) || ''
|
2030 | });
|
2031 |
|
2032 | return this;
|
2033 | };
|
2034 |
|
2035 | Bundle.prototype.clone = function clone () {
|
2036 | var bundle = new Bundle({
|
2037 | intro: this.intro,
|
2038 | separator: this.separator
|
2039 | });
|
2040 |
|
2041 | this.sources.forEach(function (source) {
|
2042 | bundle.addSource({
|
2043 | filename: source.filename,
|
2044 | content: source.content.clone(),
|
2045 | separator: source.separator
|
2046 | });
|
2047 | });
|
2048 |
|
2049 | return bundle;
|
2050 | };
|
2051 |
|
2052 | Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
|
2053 | var this$1 = this;
|
2054 | if ( options === void 0 ) options = {};
|
2055 |
|
2056 | var names = [];
|
2057 | this.sources.forEach(function (source) {
|
2058 | Object.keys(source.content.storedNames).forEach(function (name) {
|
2059 | if (!~names.indexOf(name)) { names.push(name); }
|
2060 | });
|
2061 | });
|
2062 |
|
2063 | var mappings = new Mappings(options.hires);
|
2064 |
|
2065 | if (this.intro) {
|
2066 | mappings.advance(this.intro);
|
2067 | }
|
2068 |
|
2069 | this.sources.forEach(function (source, i) {
|
2070 | if (i > 0) {
|
2071 | mappings.advance(this$1.separator);
|
2072 | }
|
2073 |
|
2074 | var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
|
2075 | var magicString = source.content;
|
2076 | var locate = getLocator(magicString.original);
|
2077 |
|
2078 | if (magicString.intro) {
|
2079 | mappings.advance(magicString.intro);
|
2080 | }
|
2081 |
|
2082 | magicString.firstChunk.eachNext(function (chunk) {
|
2083 | var loc = locate(chunk.start);
|
2084 |
|
2085 | if (chunk.intro.length) { mappings.advance(chunk.intro); }
|
2086 |
|
2087 | if (source.filename) {
|
2088 | if (chunk.edited) {
|
2089 | mappings.addEdit(
|
2090 | sourceIndex,
|
2091 | chunk.content,
|
2092 | loc,
|
2093 | chunk.storeName ? names.indexOf(chunk.original) : -1
|
2094 | );
|
2095 | } else {
|
2096 | mappings.addUneditedChunk(
|
2097 | sourceIndex,
|
2098 | chunk,
|
2099 | magicString.original,
|
2100 | loc,
|
2101 | magicString.sourcemapLocations
|
2102 | );
|
2103 | }
|
2104 | } else {
|
2105 | mappings.advance(chunk.content);
|
2106 | }
|
2107 |
|
2108 | if (chunk.outro.length) { mappings.advance(chunk.outro); }
|
2109 | });
|
2110 |
|
2111 | if (magicString.outro) {
|
2112 | mappings.advance(magicString.outro);
|
2113 | }
|
2114 | });
|
2115 |
|
2116 | return {
|
2117 | file: options.file ? options.file.split(/[/\\]/).pop() : null,
|
2118 | sources: this.uniqueSources.map(function (source) {
|
2119 | return options.file ? getRelativePath(options.file, source.filename) : source.filename;
|
2120 | }),
|
2121 | sourcesContent: this.uniqueSources.map(function (source) {
|
2122 | return options.includeContent ? source.content : null;
|
2123 | }),
|
2124 | names: names,
|
2125 | mappings: mappings.raw
|
2126 | };
|
2127 | };
|
2128 |
|
2129 | Bundle.prototype.generateMap = function generateMap (options) {
|
2130 | return new SourceMap(this.generateDecodedMap(options));
|
2131 | };
|
2132 |
|
2133 | Bundle.prototype.getIndentString = function getIndentString () {
|
2134 | var indentStringCounts = {};
|
2135 |
|
2136 | this.sources.forEach(function (source) {
|
2137 | var indentStr = source.content.indentStr;
|
2138 |
|
2139 | if (indentStr === null) { return; }
|
2140 |
|
2141 | if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
|
2142 | indentStringCounts[indentStr] += 1;
|
2143 | });
|
2144 |
|
2145 | return (
|
2146 | Object.keys(indentStringCounts).sort(function (a, b) {
|
2147 | return indentStringCounts[a] - indentStringCounts[b];
|
2148 | })[0] || '\t'
|
2149 | );
|
2150 | };
|
2151 |
|
2152 | Bundle.prototype.indent = function indent (indentStr) {
|
2153 | var this$1 = this;
|
2154 |
|
2155 | if (!arguments.length) {
|
2156 | indentStr = this.getIndentString();
|
2157 | }
|
2158 |
|
2159 | if (indentStr === '') { return this; }
|
2160 |
|
2161 | var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
|
2162 |
|
2163 | this.sources.forEach(function (source, i) {
|
2164 | var separator = source.separator !== undefined ? source.separator : this$1.separator;
|
2165 | var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
|
2166 |
|
2167 | source.content.indent(indentStr, {
|
2168 | exclude: source.indentExclusionRanges,
|
2169 | indentStart: indentStart
|
2170 | });
|
2171 |
|
2172 | trailingNewline = source.content.lastChar() === '\n';
|
2173 | });
|
2174 |
|
2175 | if (this.intro) {
|
2176 | this.intro =
|
2177 | indentStr +
|
2178 | this.intro.replace(/^[^\n]/gm, function (match, index) {
|
2179 | return index > 0 ? indentStr + match : match;
|
2180 | });
|
2181 | }
|
2182 |
|
2183 | return this;
|
2184 | };
|
2185 |
|
2186 | Bundle.prototype.prepend = function prepend (str) {
|
2187 | this.intro = str + this.intro;
|
2188 | return this;
|
2189 | };
|
2190 |
|
2191 | Bundle.prototype.toString = function toString () {
|
2192 | var this$1 = this;
|
2193 |
|
2194 | var body = this.sources
|
2195 | .map(function (source, i) {
|
2196 | var separator = source.separator !== undefined ? source.separator : this$1.separator;
|
2197 | var str = (i > 0 ? separator : '') + source.content.toString();
|
2198 |
|
2199 | return str;
|
2200 | })
|
2201 | .join('');
|
2202 |
|
2203 | return this.intro + body;
|
2204 | };
|
2205 |
|
2206 | Bundle.prototype.isEmpty = function isEmpty () {
|
2207 | if (this.intro.length && this.intro.trim())
|
2208 | { return false; }
|
2209 | if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
|
2210 | { return false; }
|
2211 | return true;
|
2212 | };
|
2213 |
|
2214 | Bundle.prototype.length = function length () {
|
2215 | return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
|
2216 | };
|
2217 |
|
2218 | Bundle.prototype.trimLines = function trimLines () {
|
2219 | return this.trim('[\\r\\n]');
|
2220 | };
|
2221 |
|
2222 | Bundle.prototype.trim = function trim (charType) {
|
2223 | return this.trimStart(charType).trimEnd(charType);
|
2224 | };
|
2225 |
|
2226 | Bundle.prototype.trimStart = function trimStart (charType) {
|
2227 | var rx = new RegExp('^' + (charType || '\\s') + '+');
|
2228 | this.intro = this.intro.replace(rx, '');
|
2229 |
|
2230 | if (!this.intro) {
|
2231 | var source;
|
2232 | var i = 0;
|
2233 |
|
2234 | do {
|
2235 | source = this.sources[i++];
|
2236 | if (!source) {
|
2237 | break;
|
2238 | }
|
2239 | } while (!source.content.trimStartAborted(charType));
|
2240 | }
|
2241 |
|
2242 | return this;
|
2243 | };
|
2244 |
|
2245 | Bundle.prototype.trimEnd = function trimEnd (charType) {
|
2246 | var rx = new RegExp((charType || '\\s') + '+$');
|
2247 |
|
2248 | var source;
|
2249 | var i = this.sources.length - 1;
|
2250 |
|
2251 | do {
|
2252 | source = this.sources[i--];
|
2253 | if (!source) {
|
2254 | this.intro = this.intro.replace(rx, '');
|
2255 | break;
|
2256 | }
|
2257 | } while (!source.content.trimEndAborted(charType));
|
2258 |
|
2259 | return this;
|
2260 | };
|
2261 |
|
2262 | var BlockStatement = 'BlockStatement';
|
2263 | var CallExpression = 'CallExpression';
|
2264 | var ClassDeclaration = 'ClassDeclaration';
|
2265 | var ExportAllDeclaration = 'ExportAllDeclaration';
|
2266 | var ExportDefaultDeclaration = 'ExportDefaultDeclaration';
|
2267 | var ExpressionStatement = 'ExpressionStatement';
|
2268 | var FunctionDeclaration = 'FunctionDeclaration';
|
2269 | var FunctionExpression = 'FunctionExpression';
|
2270 | var Identifier = 'Identifier';
|
2271 | var ImportDefaultSpecifier = 'ImportDefaultSpecifier';
|
2272 | var ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
|
2273 | var Literal = 'Literal';
|
2274 | var MemberExpression = 'MemberExpression';
|
2275 | var Program = 'Program';
|
2276 | var Property = 'Property';
|
2277 | var ReturnStatement = 'ReturnStatement';
|
2278 | var TemplateLiteral = 'TemplateLiteral';
|
2279 | var VariableDeclaration = 'VariableDeclaration';
|
2280 |
|
2281 | var CallOptions = (function () {
|
2282 | function CallOptions(_a) {
|
2283 | 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;
|
2284 | this.withNew = withNew;
|
2285 | this.args = args;
|
2286 | this.callIdentifier = callIdentifier;
|
2287 | }
|
2288 | CallOptions.create = function (callOptions) {
|
2289 | return new this(callOptions);
|
2290 | };
|
2291 | CallOptions.prototype.equals = function (callOptions) {
|
2292 | return callOptions && this.callIdentifier === callOptions.callIdentifier;
|
2293 | };
|
2294 | return CallOptions;
|
2295 | }());
|
2296 |
|
2297 | var UNKNOWN_KEY = { UNKNOWN_KEY: true };
|
2298 | var EMPTY_PATH = [];
|
2299 | var UNKNOWN_PATH = [UNKNOWN_KEY];
|
2300 | function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions) {
|
2301 | if (inheritedDescriptions === void 0) { inheritedDescriptions = null; }
|
2302 | return Object.create(inheritedDescriptions, memberDescriptions);
|
2303 | }
|
2304 | var UNKNOWN_VALUE = { UNKNOWN_VALUE: true };
|
2305 | var UNKNOWN_EXPRESSION = {
|
2306 | deoptimizePath: function () { },
|
2307 | getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
|
2308 | getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
|
2309 | hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
|
2310 | hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
|
2311 | hasEffectsWhenCalledAtPath: function () { return true; },
|
2312 | include: function () { },
|
2313 | included: true,
|
2314 | toString: function () { return '[[UNKNOWN]]'; }
|
2315 | };
|
2316 | var UNDEFINED_EXPRESSION = {
|
2317 | deoptimizePath: function () { },
|
2318 | getLiteralValueAtPath: function () { return undefined; },
|
2319 | getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
|
2320 | hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
|
2321 | hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
|
2322 | hasEffectsWhenCalledAtPath: function () { return true; },
|
2323 | include: function () { },
|
2324 | included: true,
|
2325 | toString: function () { return 'undefined'; }
|
2326 | };
|
2327 | var returnsUnknown = {
|
2328 | value: {
|
2329 | callsArgs: null,
|
2330 | mutatesSelf: false,
|
2331 | returns: null,
|
2332 | returnsPrimitive: UNKNOWN_EXPRESSION
|
2333 | }
|
2334 | };
|
2335 | var mutatesSelfReturnsUnknown = {
|
2336 | value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
|
2337 | };
|
2338 | var callsArgReturnsUnknown = {
|
2339 | value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
|
2340 | };
|
2341 | var UnknownArrayExpression = (function () {
|
2342 | function UnknownArrayExpression() {
|
2343 | this.included = false;
|
2344 | }
|
2345 | UnknownArrayExpression.prototype.deoptimizePath = function () { };
|
2346 | UnknownArrayExpression.prototype.getLiteralValueAtPath = function () {
|
2347 | return UNKNOWN_VALUE;
|
2348 | };
|
2349 | UnknownArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
2350 | if (path.length === 1) {
|
2351 | return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
|
2352 | }
|
2353 | return UNKNOWN_EXPRESSION;
|
2354 | };
|
2355 | UnknownArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
2356 | return path.length > 1;
|
2357 | };
|
2358 | UnknownArrayExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
|
2359 | return path.length > 1;
|
2360 | };
|
2361 | UnknownArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
2362 | if (path.length === 1) {
|
2363 | return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
|
2364 | }
|
2365 | return true;
|
2366 | };
|
2367 | UnknownArrayExpression.prototype.include = function () {
|
2368 | this.included = true;
|
2369 | };
|
2370 | UnknownArrayExpression.prototype.toString = function () {
|
2371 | return '[[UNKNOWN ARRAY]]';
|
2372 | };
|
2373 | return UnknownArrayExpression;
|
2374 | }());
|
2375 | var returnsArray = {
|
2376 | value: {
|
2377 | callsArgs: null,
|
2378 | mutatesSelf: false,
|
2379 | returns: UnknownArrayExpression,
|
2380 | returnsPrimitive: null
|
2381 | }
|
2382 | };
|
2383 | var mutatesSelfReturnsArray = {
|
2384 | value: {
|
2385 | callsArgs: null,
|
2386 | mutatesSelf: true,
|
2387 | returns: UnknownArrayExpression,
|
2388 | returnsPrimitive: null
|
2389 | }
|
2390 | };
|
2391 | var callsArgReturnsArray = {
|
2392 | value: {
|
2393 | callsArgs: [0],
|
2394 | mutatesSelf: false,
|
2395 | returns: UnknownArrayExpression,
|
2396 | returnsPrimitive: null
|
2397 | }
|
2398 | };
|
2399 | var callsArgMutatesSelfReturnsArray = {
|
2400 | value: {
|
2401 | callsArgs: [0],
|
2402 | mutatesSelf: true,
|
2403 | returns: UnknownArrayExpression,
|
2404 | returnsPrimitive: null
|
2405 | }
|
2406 | };
|
2407 | var UNKNOWN_LITERAL_BOOLEAN = {
|
2408 | deoptimizePath: function () { },
|
2409 | getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
|
2410 | getReturnExpressionWhenCalledAtPath: function (path) {
|
2411 | if (path.length === 1) {
|
2412 | return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
|
2413 | }
|
2414 | return UNKNOWN_EXPRESSION;
|
2415 | },
|
2416 | hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
|
2417 | hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
|
2418 | hasEffectsWhenCalledAtPath: function (path) {
|
2419 | if (path.length === 1) {
|
2420 | var subPath = path[0];
|
2421 | return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
|
2422 | }
|
2423 | return true;
|
2424 | },
|
2425 | include: function () { },
|
2426 | included: true,
|
2427 | toString: function () { return '[[UNKNOWN BOOLEAN]]'; }
|
2428 | };
|
2429 | var returnsBoolean = {
|
2430 | value: {
|
2431 | callsArgs: null,
|
2432 | mutatesSelf: false,
|
2433 | returns: null,
|
2434 | returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
|
2435 | }
|
2436 | };
|
2437 | var callsArgReturnsBoolean = {
|
2438 | value: {
|
2439 | callsArgs: [0],
|
2440 | mutatesSelf: false,
|
2441 | returns: null,
|
2442 | returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
|
2443 | }
|
2444 | };
|
2445 | var UNKNOWN_LITERAL_NUMBER = {
|
2446 | deoptimizePath: function () { },
|
2447 | getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
|
2448 | getReturnExpressionWhenCalledAtPath: function (path) {
|
2449 | if (path.length === 1) {
|
2450 | return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
|
2451 | }
|
2452 | return UNKNOWN_EXPRESSION;
|
2453 | },
|
2454 | hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
|
2455 | hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
|
2456 | hasEffectsWhenCalledAtPath: function (path) {
|
2457 | if (path.length === 1) {
|
2458 | var subPath = path[0];
|
2459 | return typeof subPath !== 'string' || !literalNumberMembers[subPath];
|
2460 | }
|
2461 | return true;
|
2462 | },
|
2463 | include: function () { },
|
2464 | included: true,
|
2465 | toString: function () { return '[[UNKNOWN NUMBER]]'; }
|
2466 | };
|
2467 | var returnsNumber = {
|
2468 | value: {
|
2469 | callsArgs: null,
|
2470 | mutatesSelf: false,
|
2471 | returns: null,
|
2472 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2473 | }
|
2474 | };
|
2475 | var mutatesSelfReturnsNumber = {
|
2476 | value: {
|
2477 | callsArgs: null,
|
2478 | mutatesSelf: true,
|
2479 | returns: null,
|
2480 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2481 | }
|
2482 | };
|
2483 | var callsArgReturnsNumber = {
|
2484 | value: {
|
2485 | callsArgs: [0],
|
2486 | mutatesSelf: false,
|
2487 | returns: null,
|
2488 | returnsPrimitive: UNKNOWN_LITERAL_NUMBER
|
2489 | }
|
2490 | };
|
2491 | var UNKNOWN_LITERAL_STRING = {
|
2492 | deoptimizePath: function () { },
|
2493 | getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
|
2494 | getReturnExpressionWhenCalledAtPath: function (path) {
|
2495 | if (path.length === 1) {
|
2496 | return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
|
2497 | }
|
2498 | return UNKNOWN_EXPRESSION;
|
2499 | },
|
2500 | hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
|
2501 | hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
|
2502 | hasEffectsWhenCalledAtPath: function (path, callOptions, options) {
|
2503 | if (path.length === 1) {
|
2504 | return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, options);
|
2505 | }
|
2506 | return true;
|
2507 | },
|
2508 | include: function () { },
|
2509 | included: true,
|
2510 | toString: function () { return '[[UNKNOWN STRING]]'; }
|
2511 | };
|
2512 | var returnsString = {
|
2513 | value: {
|
2514 | callsArgs: null,
|
2515 | mutatesSelf: false,
|
2516 | returns: null,
|
2517 | returnsPrimitive: UNKNOWN_LITERAL_STRING
|
2518 | }
|
2519 | };
|
2520 | var UnknownObjectExpression = (function () {
|
2521 | function UnknownObjectExpression() {
|
2522 | this.included = false;
|
2523 | }
|
2524 | UnknownObjectExpression.prototype.deoptimizePath = function () { };
|
2525 | UnknownObjectExpression.prototype.getLiteralValueAtPath = function () {
|
2526 | return UNKNOWN_VALUE;
|
2527 | };
|
2528 | UnknownObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
2529 | if (path.length === 1) {
|
2530 | return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
|
2531 | }
|
2532 | return UNKNOWN_EXPRESSION;
|
2533 | };
|
2534 | UnknownObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
2535 | return path.length > 1;
|
2536 | };
|
2537 | UnknownObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
|
2538 | return path.length > 1;
|
2539 | };
|
2540 | UnknownObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
2541 | if (path.length === 1) {
|
2542 | return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, options);
|
2543 | }
|
2544 | return true;
|
2545 | };
|
2546 | UnknownObjectExpression.prototype.include = function () {
|
2547 | this.included = true;
|
2548 | };
|
2549 | UnknownObjectExpression.prototype.toString = function () {
|
2550 | return '[[UNKNOWN OBJECT]]';
|
2551 | };
|
2552 | return UnknownObjectExpression;
|
2553 | }());
|
2554 | var objectMembers = assembleMemberDescriptions({
|
2555 | hasOwnProperty: returnsBoolean,
|
2556 | isPrototypeOf: returnsBoolean,
|
2557 | propertyIsEnumerable: returnsBoolean,
|
2558 | toLocaleString: returnsString,
|
2559 | toString: returnsString,
|
2560 | valueOf: returnsUnknown
|
2561 | });
|
2562 | var arrayMembers = assembleMemberDescriptions({
|
2563 | concat: returnsArray,
|
2564 | copyWithin: mutatesSelfReturnsArray,
|
2565 | every: callsArgReturnsBoolean,
|
2566 | fill: mutatesSelfReturnsArray,
|
2567 | filter: callsArgReturnsArray,
|
2568 | find: callsArgReturnsUnknown,
|
2569 | findIndex: callsArgReturnsNumber,
|
2570 | forEach: callsArgReturnsUnknown,
|
2571 | includes: returnsBoolean,
|
2572 | indexOf: returnsNumber,
|
2573 | join: returnsString,
|
2574 | lastIndexOf: returnsNumber,
|
2575 | map: callsArgReturnsArray,
|
2576 | pop: mutatesSelfReturnsUnknown,
|
2577 | push: mutatesSelfReturnsNumber,
|
2578 | reduce: callsArgReturnsUnknown,
|
2579 | reduceRight: callsArgReturnsUnknown,
|
2580 | reverse: mutatesSelfReturnsArray,
|
2581 | shift: mutatesSelfReturnsUnknown,
|
2582 | slice: returnsArray,
|
2583 | some: callsArgReturnsBoolean,
|
2584 | sort: callsArgMutatesSelfReturnsArray,
|
2585 | splice: mutatesSelfReturnsArray,
|
2586 | unshift: mutatesSelfReturnsNumber
|
2587 | }, objectMembers);
|
2588 | var literalBooleanMembers = assembleMemberDescriptions({
|
2589 | valueOf: returnsBoolean
|
2590 | }, objectMembers);
|
2591 | var literalNumberMembers = assembleMemberDescriptions({
|
2592 | toExponential: returnsString,
|
2593 | toFixed: returnsString,
|
2594 | toLocaleString: returnsString,
|
2595 | toPrecision: returnsString,
|
2596 | valueOf: returnsNumber
|
2597 | }, objectMembers);
|
2598 | var literalStringMembers = assembleMemberDescriptions({
|
2599 | charAt: returnsString,
|
2600 | charCodeAt: returnsNumber,
|
2601 | codePointAt: returnsNumber,
|
2602 | concat: returnsString,
|
2603 | endsWith: returnsBoolean,
|
2604 | includes: returnsBoolean,
|
2605 | indexOf: returnsNumber,
|
2606 | lastIndexOf: returnsNumber,
|
2607 | localeCompare: returnsNumber,
|
2608 | match: returnsBoolean,
|
2609 | normalize: returnsString,
|
2610 | padEnd: returnsString,
|
2611 | padStart: returnsString,
|
2612 | repeat: returnsString,
|
2613 | replace: {
|
2614 | value: {
|
2615 | callsArgs: [1],
|
2616 | mutatesSelf: false,
|
2617 | returns: null,
|
2618 | returnsPrimitive: UNKNOWN_LITERAL_STRING
|
2619 | }
|
2620 | },
|
2621 | search: returnsNumber,
|
2622 | slice: returnsString,
|
2623 | split: returnsArray,
|
2624 | startsWith: returnsBoolean,
|
2625 | substr: returnsString,
|
2626 | substring: returnsString,
|
2627 | toLocaleLowerCase: returnsString,
|
2628 | toLocaleUpperCase: returnsString,
|
2629 | toLowerCase: returnsString,
|
2630 | toUpperCase: returnsString,
|
2631 | trim: returnsString,
|
2632 | valueOf: returnsString
|
2633 | }, objectMembers);
|
2634 | function getLiteralMembersForValue(value) {
|
2635 | switch (typeof value) {
|
2636 | case 'boolean':
|
2637 | return literalBooleanMembers;
|
2638 | case 'number':
|
2639 | return literalNumberMembers;
|
2640 | case 'string':
|
2641 | return literalStringMembers;
|
2642 | default:
|
2643 | return Object.create(null);
|
2644 | }
|
2645 | }
|
2646 | function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, options) {
|
2647 | if (typeof memberName !== 'string' || !members[memberName])
|
2648 | return true;
|
2649 | if (members[memberName].mutatesSelf && parentIncluded)
|
2650 | return true;
|
2651 | if (!members[memberName].callsArgs)
|
2652 | return false;
|
2653 | for (var _i = 0, _a = members[memberName].callsArgs; _i < _a.length; _i++) {
|
2654 | var argIndex = _a[_i];
|
2655 | if (callOptions.args[argIndex] &&
|
2656 | callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, CallOptions.create({
|
2657 | args: [],
|
2658 | callIdentifier: {},
|
2659 | withNew: false
|
2660 | }), options.getHasEffectsWhenCalledOptions()))
|
2661 | return true;
|
2662 | }
|
2663 | return false;
|
2664 | }
|
2665 | function getMemberReturnExpressionWhenCalled(members, memberName) {
|
2666 | if (typeof memberName !== 'string' || !members[memberName])
|
2667 | return UNKNOWN_EXPRESSION;
|
2668 | return members[memberName].returnsPrimitive !== null
|
2669 | ? members[memberName].returnsPrimitive
|
2670 | : new members[memberName].returns();
|
2671 | }
|
2672 |
|
2673 | var Variable = (function () {
|
2674 | function Variable(name) {
|
2675 | this.exportName = null;
|
2676 | this.included = false;
|
2677 | this.isId = false;
|
2678 | this.isReassigned = false;
|
2679 | this.reexported = false;
|
2680 | this.renderBaseName = null;
|
2681 | this.renderName = null;
|
2682 | this.safeExportName = null;
|
2683 | this.name = name;
|
2684 | }
|
2685 | |
2686 |
|
2687 |
|
2688 |
|
2689 | Variable.prototype.addReference = function (_identifier) { };
|
2690 | Variable.prototype.deoptimizePath = function (_path) { };
|
2691 | Variable.prototype.getBaseVariableName = function () {
|
2692 | return this.renderBaseName || this.renderName || this.name;
|
2693 | };
|
2694 | Variable.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
|
2695 | return UNKNOWN_VALUE;
|
2696 | };
|
2697 | Variable.prototype.getName = function () {
|
2698 | var name = this.renderName || this.name;
|
2699 | return this.renderBaseName ? this.renderBaseName + "." + name : name;
|
2700 | };
|
2701 | Variable.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
|
2702 | return UNKNOWN_EXPRESSION;
|
2703 | };
|
2704 | Variable.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
2705 | return path.length > 0;
|
2706 | };
|
2707 | Variable.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
|
2708 | return true;
|
2709 | };
|
2710 | Variable.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
|
2711 | return true;
|
2712 | };
|
2713 | |
2714 |
|
2715 |
|
2716 |
|
2717 |
|
2718 |
|
2719 | Variable.prototype.include = function () {
|
2720 | this.included = true;
|
2721 | };
|
2722 | Variable.prototype.setRenderNames = function (baseName, name) {
|
2723 | this.renderBaseName = baseName;
|
2724 | this.renderName = name;
|
2725 | };
|
2726 | Variable.prototype.setSafeName = function (name) {
|
2727 | this.renderName = name;
|
2728 | };
|
2729 | Variable.prototype.toString = function () {
|
2730 | return this.name;
|
2731 | };
|
2732 | return Variable;
|
2733 | }());
|
2734 |
|
2735 |
|
2736 | var MAX_PATH_DEPTH = 7;
|
2737 | var LocalVariable = (function (_super) {
|
2738 | __extends(LocalVariable, _super);
|
2739 | function LocalVariable(name, declarator, init, context) {
|
2740 | var _this = _super.call(this, name) || this;
|
2741 | _this.additionalInitializers = null;
|
2742 | _this.expressionsToBeDeoptimized = [];
|
2743 | _this.declarations = declarator ? [declarator] : [];
|
2744 | _this.init = init;
|
2745 | _this.deoptimizationTracker = context.deoptimizationTracker;
|
2746 | _this.module = context.module;
|
2747 | return _this;
|
2748 | }
|
2749 | LocalVariable.prototype.addDeclaration = function (identifier, init) {
|
2750 | this.declarations.push(identifier);
|
2751 | if (this.additionalInitializers === null) {
|
2752 | this.additionalInitializers = this.init === null ? [] : [this.init];
|
2753 | this.init = UNKNOWN_EXPRESSION;
|
2754 | this.isReassigned = true;
|
2755 | }
|
2756 | if (init !== null) {
|
2757 | this.additionalInitializers.push(init);
|
2758 | }
|
2759 | };
|
2760 | LocalVariable.prototype.consolidateInitializers = function () {
|
2761 | if (this.additionalInitializers !== null) {
|
2762 | for (var _i = 0, _a = this.additionalInitializers; _i < _a.length; _i++) {
|
2763 | var initializer = _a[_i];
|
2764 | initializer.deoptimizePath(UNKNOWN_PATH);
|
2765 | }
|
2766 | this.additionalInitializers = null;
|
2767 | }
|
2768 | };
|
2769 | LocalVariable.prototype.deoptimizePath = function (path) {
|
2770 | if (path.length > MAX_PATH_DEPTH)
|
2771 | return;
|
2772 | if (!(this.isReassigned || this.deoptimizationTracker.track(this, path))) {
|
2773 | if (path.length === 0) {
|
2774 | if (!this.isReassigned) {
|
2775 | this.isReassigned = true;
|
2776 | for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
|
2777 | var expression = _a[_i];
|
2778 | expression.deoptimizeCache();
|
2779 | }
|
2780 | if (this.init) {
|
2781 | this.init.deoptimizePath(UNKNOWN_PATH);
|
2782 | }
|
2783 | }
|
2784 | }
|
2785 | else if (this.init) {
|
2786 | this.init.deoptimizePath(path);
|
2787 | }
|
2788 | }
|
2789 | };
|
2790 | LocalVariable.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
2791 | if (this.isReassigned ||
|
2792 | !this.init ||
|
2793 | path.length > MAX_PATH_DEPTH ||
|
2794 | recursionTracker.isTracked(this.init, path)) {
|
2795 | return UNKNOWN_VALUE;
|
2796 | }
|
2797 | this.expressionsToBeDeoptimized.push(origin);
|
2798 | return this.init.getLiteralValueAtPath(path, recursionTracker.track(this.init, path), origin);
|
2799 | };
|
2800 | LocalVariable.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
2801 | if (this.isReassigned ||
|
2802 | !this.init ||
|
2803 | path.length > MAX_PATH_DEPTH ||
|
2804 | recursionTracker.isTracked(this.init, path)) {
|
2805 | return UNKNOWN_EXPRESSION;
|
2806 | }
|
2807 | this.expressionsToBeDeoptimized.push(origin);
|
2808 | return this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.init, path), origin);
|
2809 | };
|
2810 | LocalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
2811 | if (path.length === 0)
|
2812 | return false;
|
2813 | return (this.isReassigned ||
|
2814 | path.length > MAX_PATH_DEPTH ||
|
2815 | (this.init &&
|
2816 | !options.hasNodeBeenAccessedAtPath(path, this.init) &&
|
2817 | this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init))));
|
2818 | };
|
2819 | LocalVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
2820 | if (this.included || path.length > MAX_PATH_DEPTH)
|
2821 | return true;
|
2822 | if (path.length === 0)
|
2823 | return false;
|
2824 | return (this.isReassigned ||
|
2825 | (this.init &&
|
2826 | !options.hasNodeBeenAssignedAtPath(path, this.init) &&
|
2827 | this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init))));
|
2828 | };
|
2829 | LocalVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
2830 | if (path.length > MAX_PATH_DEPTH)
|
2831 | return true;
|
2832 | return (this.isReassigned ||
|
2833 | (this.init &&
|
2834 | !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) &&
|
2835 | this.init.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions))));
|
2836 | };
|
2837 | LocalVariable.prototype.include = function () {
|
2838 | if (!this.included) {
|
2839 | this.included = true;
|
2840 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
2841 | var declaration = _a[_i];
|
2842 |
|
2843 | if (!declaration.included)
|
2844 | declaration.include(false);
|
2845 | var node = declaration.parent;
|
2846 | while (!node.included) {
|
2847 |
|
2848 |
|
2849 | node.included = true;
|
2850 | if (node.type === Program)
|
2851 | break;
|
2852 | node = node.parent;
|
2853 | }
|
2854 | }
|
2855 | }
|
2856 | };
|
2857 | return LocalVariable;
|
2858 | }(Variable));
|
2859 | LocalVariable.prototype.isLocal = true;
|
2860 |
|
2861 | function isExportDefaultVariable(variable) {
|
2862 | return variable.isDefault;
|
2863 | }
|
2864 | var ExportDefaultVariable = (function (_super) {
|
2865 | __extends(ExportDefaultVariable, _super);
|
2866 | function ExportDefaultVariable(name, exportDefaultDeclaration, context) {
|
2867 | var _this = _super.call(this, name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context) || this;
|
2868 |
|
2869 | _this.originalId = null;
|
2870 | var declaration = exportDefaultDeclaration.declaration;
|
2871 | if ((declaration.type === FunctionDeclaration ||
|
2872 | declaration.type === ClassDeclaration) &&
|
2873 | declaration.id) {
|
2874 | _this.hasId = true;
|
2875 | _this.originalId = declaration.id;
|
2876 | }
|
2877 | else if (declaration.type === Identifier) {
|
2878 | _this.originalId = declaration;
|
2879 | }
|
2880 | return _this;
|
2881 | }
|
2882 | ExportDefaultVariable.prototype.addReference = function (identifier) {
|
2883 | if (!this.hasId) {
|
2884 | this.name = identifier.name;
|
2885 | }
|
2886 | };
|
2887 | ExportDefaultVariable.prototype.getName = function () {
|
2888 | return this.referencesOriginal() ? this.originalId.variable.getName() : _super.prototype.getName.call(this);
|
2889 | };
|
2890 | ExportDefaultVariable.prototype.getOriginalVariable = function () {
|
2891 | return (this.originalId && this.originalId.variable) || null;
|
2892 | };
|
2893 | ExportDefaultVariable.prototype.getOriginalVariableName = function () {
|
2894 | return (this.originalId && this.originalId.name) || null;
|
2895 | };
|
2896 | ExportDefaultVariable.prototype.referencesOriginal = function () {
|
2897 | return this.originalId && (this.hasId || !this.originalId.variable.isReassigned);
|
2898 | };
|
2899 | ExportDefaultVariable.prototype.setRenderNames = function (baseName, name) {
|
2900 | if (this.referencesOriginal()) {
|
2901 | this.originalId.variable.setRenderNames(baseName, name);
|
2902 | }
|
2903 | else {
|
2904 | _super.prototype.setRenderNames.call(this, baseName, name);
|
2905 | }
|
2906 | };
|
2907 | ExportDefaultVariable.prototype.setSafeName = function (name) {
|
2908 | if (this.referencesOriginal()) {
|
2909 | this.originalId.variable.setSafeName(name);
|
2910 | }
|
2911 | else {
|
2912 | _super.prototype.setSafeName.call(this, name);
|
2913 | }
|
2914 | };
|
2915 | return ExportDefaultVariable;
|
2916 | }(LocalVariable));
|
2917 | ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName;
|
2918 | ExportDefaultVariable.prototype.isDefault = true;
|
2919 |
|
2920 | var MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
|
2921 | var INTEROP_DEFAULT_VARIABLE = '_interopDefault';
|
2922 |
|
2923 | var ExportShimVariable = (function (_super) {
|
2924 | __extends(ExportShimVariable, _super);
|
2925 | function ExportShimVariable(module) {
|
2926 | var _this = _super.call(this, MISSING_EXPORT_SHIM_VARIABLE) || this;
|
2927 | _this.module = module;
|
2928 | return _this;
|
2929 | }
|
2930 | return ExportShimVariable;
|
2931 | }(Variable));
|
2932 |
|
2933 | var pureFunctions = {};
|
2934 | var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
|
2935 | var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
|
2936 | var 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(' ');
|
2937 | var allSimdMethods = [];
|
2938 | simdTypes.forEach(function (t) {
|
2939 | simdMethods.forEach(function (m) {
|
2940 | allSimdMethods.push("SIMD." + t + "." + m);
|
2941 | });
|
2942 | });
|
2943 | [
|
2944 | 'Array.isArray',
|
2945 | 'Error',
|
2946 | 'EvalError',
|
2947 | 'InternalError',
|
2948 | 'RangeError',
|
2949 | 'ReferenceError',
|
2950 | 'SyntaxError',
|
2951 | 'TypeError',
|
2952 | 'URIError',
|
2953 | 'isFinite',
|
2954 | 'isNaN',
|
2955 | 'parseFloat',
|
2956 | 'parseInt',
|
2957 | 'decodeURI',
|
2958 | 'decodeURIComponent',
|
2959 | 'encodeURI',
|
2960 | 'encodeURIComponent',
|
2961 | 'escape',
|
2962 | 'unescape',
|
2963 | 'Object',
|
2964 | 'Object.create',
|
2965 | 'Object.getNotifier',
|
2966 | 'Object.getOwn',
|
2967 | 'Object.getOwnPropertyDescriptor',
|
2968 | 'Object.getOwnPropertyNames',
|
2969 | 'Object.getOwnPropertySymbols',
|
2970 | 'Object.getPrototypeOf',
|
2971 | 'Object.is',
|
2972 | 'Object.isExtensible',
|
2973 | 'Object.isFrozen',
|
2974 | 'Object.isSealed',
|
2975 | 'Object.keys',
|
2976 | 'Boolean',
|
2977 | 'Number',
|
2978 | 'Number.isFinite',
|
2979 | 'Number.isInteger',
|
2980 | 'Number.isNaN',
|
2981 | 'Number.isSafeInteger',
|
2982 | 'Number.parseFloat',
|
2983 | 'Number.parseInt',
|
2984 | 'Symbol',
|
2985 | 'Symbol.for',
|
2986 | 'Symbol.keyFor',
|
2987 | 'Math.abs',
|
2988 | 'Math.acos',
|
2989 | 'Math.acosh',
|
2990 | 'Math.asin',
|
2991 | 'Math.asinh',
|
2992 | 'Math.atan',
|
2993 | 'Math.atan2',
|
2994 | 'Math.atanh',
|
2995 | 'Math.cbrt',
|
2996 | 'Math.ceil',
|
2997 | 'Math.clz32',
|
2998 | 'Math.cos',
|
2999 | 'Math.cosh',
|
3000 | 'Math.exp',
|
3001 | 'Math.expm1',
|
3002 | 'Math.floor',
|
3003 | 'Math.fround',
|
3004 | 'Math.hypot',
|
3005 | 'Math.imul',
|
3006 | 'Math.log',
|
3007 | 'Math.log10',
|
3008 | 'Math.log1p',
|
3009 | 'Math.log2',
|
3010 | 'Math.max',
|
3011 | 'Math.min',
|
3012 | 'Math.pow',
|
3013 | 'Math.random',
|
3014 | 'Math.round',
|
3015 | 'Math.sign',
|
3016 | 'Math.sin',
|
3017 | 'Math.sinh',
|
3018 | 'Math.sqrt',
|
3019 | 'Math.tan',
|
3020 | 'Math.tanh',
|
3021 | 'Math.trunc',
|
3022 | 'Date',
|
3023 | 'Date.UTC',
|
3024 | 'Date.now',
|
3025 | 'Date.parse',
|
3026 | 'String',
|
3027 | 'String.fromCharCode',
|
3028 | 'String.fromCodePoint',
|
3029 | 'String.raw',
|
3030 | 'RegExp',
|
3031 | 'Map',
|
3032 | 'Set',
|
3033 | 'WeakMap',
|
3034 | 'WeakSet',
|
3035 | 'ArrayBuffer',
|
3036 | 'ArrayBuffer.isView',
|
3037 | 'DataView',
|
3038 | 'Promise.all',
|
3039 | 'Promise.race',
|
3040 | 'Promise.resolve',
|
3041 | 'Intl.Collator',
|
3042 | 'Intl.Collator.supportedLocalesOf',
|
3043 | 'Intl.DateTimeFormat',
|
3044 | 'Intl.DateTimeFormat.supportedLocalesOf',
|
3045 | 'Intl.NumberFormat',
|
3046 | 'Intl.NumberFormat.supportedLocalesOf'
|
3047 |
|
3048 | ]
|
3049 | .concat(arrayTypes, arrayTypes.map(function (t) { return t + ".from"; }), arrayTypes.map(function (t) { return t + ".of"; }), simdTypes.map(function (t) { return "SIMD." + t; }), allSimdMethods)
|
3050 | .forEach(function (name) { return (pureFunctions[name] = true); });
|
3051 |
|
3052 | var GlobalVariable = (function (_super) {
|
3053 | __extends(GlobalVariable, _super);
|
3054 | function GlobalVariable() {
|
3055 | return _super !== null && _super.apply(this, arguments) || this;
|
3056 | }
|
3057 | GlobalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
3058 |
|
3059 | return (path.length > 0 &&
|
3060 | !this.isPureFunctionMember(path) &&
|
3061 | !(this.name === 'Reflect' && path.length === 1));
|
3062 | };
|
3063 | GlobalVariable.prototype.hasEffectsWhenCalledAtPath = function (path) {
|
3064 | return !pureFunctions[[this.name].concat(path).join('.')];
|
3065 | };
|
3066 | GlobalVariable.prototype.isPureFunctionMember = function (path) {
|
3067 | return (pureFunctions[[this.name].concat(path).join('.')] ||
|
3068 | (path.length >= 1 && pureFunctions[[this.name].concat(path.slice(0, -1)).join('.')]) ||
|
3069 | (path.length >= 2 &&
|
3070 | pureFunctions[[this.name].concat(path.slice(0, -2)).join('.')] &&
|
3071 | path[path.length - 2] === 'prototype'));
|
3072 | };
|
3073 | return GlobalVariable;
|
3074 | }(Variable));
|
3075 |
|
3076 | var NamespaceVariable = (function (_super) {
|
3077 | __extends(NamespaceVariable, _super);
|
3078 | function NamespaceVariable(context) {
|
3079 | var _this = _super.call(this, context.getModuleName()) || this;
|
3080 | _this.memberVariables = Object.create(null);
|
3081 | _this.containsExternalNamespace = false;
|
3082 | _this.referencedEarly = false;
|
3083 | _this.references = [];
|
3084 | _this.context = context;
|
3085 | _this.module = context.module;
|
3086 | for (var _i = 0, _a = _this.context.getExports().concat(_this.context.getReexports()); _i < _a.length; _i++) {
|
3087 | var name = _a[_i];
|
3088 | if (name[0] === '*' && name.length > 1)
|
3089 | _this.containsExternalNamespace = true;
|
3090 | _this.memberVariables[name] = _this.context.traceExport(name);
|
3091 | }
|
3092 | return _this;
|
3093 | }
|
3094 | NamespaceVariable.prototype.addReference = function (identifier) {
|
3095 | this.references.push(identifier);
|
3096 | this.name = identifier.name;
|
3097 | };
|
3098 |
|
3099 |
|
3100 |
|
3101 |
|
3102 | NamespaceVariable.prototype.deoptimizePath = function () {
|
3103 | for (var key in this.memberVariables) {
|
3104 | this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
|
3105 | }
|
3106 | };
|
3107 | NamespaceVariable.prototype.include = function () {
|
3108 | if (!this.included) {
|
3109 | if (this.containsExternalNamespace) {
|
3110 | this.context.error({
|
3111 | code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
|
3112 | id: this.module.id,
|
3113 | message: "Cannot create an explicit namespace object for module \"" + this.context.getModuleName() + "\" because it contains a reexported external namespace"
|
3114 | }, undefined);
|
3115 | }
|
3116 | this.included = true;
|
3117 | for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
|
3118 | var identifier = _a[_i];
|
3119 | if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
|
3120 | this.referencedEarly = true;
|
3121 | break;
|
3122 | }
|
3123 | }
|
3124 | if (this.context.preserveModules) {
|
3125 | for (var _b = 0, _c = Object.keys(this.memberVariables); _b < _c.length; _b++) {
|
3126 | var memberName = _c[_b];
|
3127 | this.memberVariables[memberName].include();
|
3128 | }
|
3129 | }
|
3130 | else {
|
3131 | for (var _d = 0, _e = Object.keys(this.memberVariables); _d < _e.length; _d++) {
|
3132 | var memberName = _e[_d];
|
3133 | this.context.includeVariable(this.memberVariables[memberName]);
|
3134 | }
|
3135 | }
|
3136 | }
|
3137 | };
|
3138 | NamespaceVariable.prototype.renderBlock = function (options) {
|
3139 | var _this = this;
|
3140 | var _ = options.compact ? '' : ' ';
|
3141 | var n = options.compact ? '' : '\n';
|
3142 | var t = options.indent;
|
3143 | var members = Object.keys(this.memberVariables).map(function (name) {
|
3144 | var original = _this.memberVariables[name];
|
3145 | if (_this.referencedEarly || original.isReassigned) {
|
3146 | return t + "get " + name + _ + "()" + _ + "{" + _ + "return " + original.getName() + (options.compact ? '' : ';') + _ + "}";
|
3147 | }
|
3148 | return "" + t + name + ": " + original.getName();
|
3149 | });
|
3150 | var name = this.getName();
|
3151 | var callee = options.freeze ? "/*#__PURE__*/Object.freeze" : '';
|
3152 | var output = options.varOrConst + " " + name + " = " + (options.namespaceToStringTag
|
3153 | ? "{" + n + members.join("," + n) + n + "};"
|
3154 | : callee + "({" + n + members.join("," + n) + n + "});");
|
3155 | if (options.namespaceToStringTag) {
|
3156 | output += n + "if" + _ + "(typeof Symbol" + _ + "!==" + _ + "'undefined'" + _ + "&&" + _ + "Symbol.toStringTag)" + n;
|
3157 | output += t + "Object.defineProperty(" + name + "," + _ + "Symbol.toStringTag," + _ + "{" + _ + "value:" + _ + "'Module'" + _ + "});" + n;
|
3158 | output += "else" + (n || ' ');
|
3159 | output += t + "Object.defineProperty(" + name + "," + _ + "'toString'," + _ + "{" + _ + "value:" + _ + "function" + _ + "()" + _ + "{" + _ + "return" + _ + "'[object Module]'" + (options.compact ? ';' : '') + _ + "}" + _ + "});" + n;
|
3160 | output += callee + "(" + name + ");";
|
3161 | }
|
3162 | if (options.format === 'system' && this.exportName) {
|
3163 | output += n + "exports('" + this.exportName + "'," + _ + name + ");";
|
3164 | }
|
3165 | return output;
|
3166 | };
|
3167 | NamespaceVariable.prototype.renderFirst = function () {
|
3168 | return this.referencedEarly;
|
3169 | };
|
3170 | return NamespaceVariable;
|
3171 | }(Variable));
|
3172 | NamespaceVariable.prototype.isNamespace = true;
|
3173 |
|
3174 | var ExternalVariable = (function (_super) {
|
3175 | __extends(ExternalVariable, _super);
|
3176 | function ExternalVariable(module, name) {
|
3177 | var _this = _super.call(this, name) || this;
|
3178 | _this.module = module;
|
3179 | _this.isNamespace = name === '*';
|
3180 | _this.referenced = false;
|
3181 | return _this;
|
3182 | }
|
3183 | ExternalVariable.prototype.addReference = function (identifier) {
|
3184 | this.referenced = true;
|
3185 | if (this.name === 'default' || this.name === '*') {
|
3186 | this.module.suggestName(identifier.name);
|
3187 | }
|
3188 | };
|
3189 | ExternalVariable.prototype.include = function () {
|
3190 | if (!this.included) {
|
3191 | this.included = true;
|
3192 | this.module.used = true;
|
3193 | }
|
3194 | };
|
3195 | return ExternalVariable;
|
3196 | }(Variable));
|
3197 | ExternalVariable.prototype.isExternal = true;
|
3198 |
|
3199 | var 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(' ');
|
3200 | var 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(' ');
|
3201 | var blacklisted = Object.create(null);
|
3202 | reservedWords.concat(builtins).forEach(function (word) { return (blacklisted[word] = true); });
|
3203 | var illegalCharacters = /[^$_a-zA-Z0-9]/g;
|
3204 | var startsWithDigit = function (str) { return /\d/.test(str[0]); };
|
3205 | function isLegal(str) {
|
3206 | if (startsWithDigit(str) || blacklisted[str]) {
|
3207 | return false;
|
3208 | }
|
3209 | return !illegalCharacters.test(str);
|
3210 | }
|
3211 | function makeLegal(str) {
|
3212 | str = str.replace(/-(\w)/g, function (_, letter) { return letter.toUpperCase(); }).replace(illegalCharacters, '_');
|
3213 | if (startsWithDigit(str) || blacklisted[str])
|
3214 | str = "_" + str;
|
3215 | return str;
|
3216 | }
|
3217 |
|
3218 | var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
|
3219 | var relativePath = /^\.?\.\//;
|
3220 | function isAbsolute(path) {
|
3221 | return absolutePath.test(path);
|
3222 | }
|
3223 | function isRelative(path) {
|
3224 | return relativePath.test(path);
|
3225 | }
|
3226 | function normalize(path) {
|
3227 | if (path.indexOf('\\') == -1)
|
3228 | return path;
|
3229 | return path.replace(/\\/g, '/');
|
3230 | }
|
3231 |
|
3232 | var ExternalModule = (function () {
|
3233 | function ExternalModule(_a) {
|
3234 | var graph = _a.graph, id = _a.id;
|
3235 | this.exportsNames = false;
|
3236 | this.exportsNamespace = false;
|
3237 | this.isEntryPoint = false;
|
3238 | this.isExternal = true;
|
3239 | this.mostCommonSuggestion = 0;
|
3240 | this.reexported = false;
|
3241 | this.renderPath = undefined;
|
3242 | this.renormalizeRenderPath = false;
|
3243 | this.used = false;
|
3244 | this.graph = graph;
|
3245 | this.id = id;
|
3246 | this.execIndex = Infinity;
|
3247 | var parts = id.split(/[\\/]/);
|
3248 | this.variableName = makeLegal(parts.pop());
|
3249 | this.nameSuggestions = Object.create(null);
|
3250 | this.declarations = Object.create(null);
|
3251 | this.exportedVariables = new Map();
|
3252 | }
|
3253 | ExternalModule.prototype.getVariableForExportName = function (name, _isExportAllSearch) {
|
3254 | if (name !== 'default' && name !== '*')
|
3255 | this.exportsNames = true;
|
3256 | if (name === '*')
|
3257 | this.exportsNamespace = true;
|
3258 | var declaration = this.declarations[name];
|
3259 | if (declaration)
|
3260 | return declaration;
|
3261 | this.declarations[name] = declaration = new ExternalVariable(this, name);
|
3262 | this.exportedVariables.set(declaration, name);
|
3263 | return declaration;
|
3264 | };
|
3265 | ExternalModule.prototype.setRenderPath = function (options, inputBase) {
|
3266 | this.renderPath = '';
|
3267 | if (options.paths) {
|
3268 | this.renderPath =
|
3269 | typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
|
3270 | }
|
3271 | if (!this.renderPath) {
|
3272 | if (!isAbsolute(this.id)) {
|
3273 | this.renderPath = this.id;
|
3274 | }
|
3275 | else {
|
3276 | this.renderPath = normalize(path.relative(inputBase, this.id));
|
3277 | this.renormalizeRenderPath = true;
|
3278 | }
|
3279 | }
|
3280 | return this.renderPath;
|
3281 | };
|
3282 | ExternalModule.prototype.suggestName = function (name) {
|
3283 | if (!this.nameSuggestions[name])
|
3284 | this.nameSuggestions[name] = 0;
|
3285 | this.nameSuggestions[name] += 1;
|
3286 | if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
|
3287 | this.mostCommonSuggestion = this.nameSuggestions[name];
|
3288 | this.variableName = name;
|
3289 | }
|
3290 | };
|
3291 | ExternalModule.prototype.warnUnusedImports = function () {
|
3292 | var _this = this;
|
3293 | var unused = Object.keys(this.declarations).filter(function (name) {
|
3294 | if (name === '*')
|
3295 | return false;
|
3296 | var declaration = _this.declarations[name];
|
3297 | return !declaration.included && !_this.reexported && !declaration.referenced;
|
3298 | });
|
3299 | if (unused.length === 0)
|
3300 | return;
|
3301 | var names = unused.length === 1
|
3302 | ? "'" + unused[0] + "' is"
|
3303 | : unused
|
3304 | .slice(0, -1)
|
3305 | .map(function (name) { return "'" + name + "'"; })
|
3306 | .join(', ') + " and '" + unused.slice(-1) + "' are";
|
3307 | this.graph.warn({
|
3308 | code: 'UNUSED_EXTERNAL_IMPORT',
|
3309 | message: names + " imported from external module '" + this.id + "' but never used",
|
3310 | names: unused,
|
3311 | source: this.id
|
3312 | });
|
3313 | };
|
3314 | return ExternalModule;
|
3315 | }());
|
3316 |
|
3317 | var esModuleExport = "Object.defineProperty(exports, '__esModule', { value: true });";
|
3318 | var compactEsModuleExport = "Object.defineProperty(exports,'__esModule',{value:true});";
|
3319 |
|
3320 | function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism) {
|
3321 | if (mechanism === void 0) { mechanism = 'return '; }
|
3322 | var _ = compact ? '' : ' ';
|
3323 | var n = compact ? '' : '\n';
|
3324 | if (!namedExportsMode) {
|
3325 | var local_1;
|
3326 | exports.some(function (expt) {
|
3327 | if (expt.exported === 'default') {
|
3328 | local_1 = expt.local;
|
3329 | return true;
|
3330 | }
|
3331 | return false;
|
3332 | });
|
3333 |
|
3334 | if (!local_1) {
|
3335 | dependencies.some(function (dep) {
|
3336 | if (!dep.reexports)
|
3337 | return false;
|
3338 | return dep.reexports.some(function (expt) {
|
3339 | if (expt.reexported === 'default') {
|
3340 | local_1 = dep.namedExportsMode ? dep.name + "." + expt.imported : dep.name;
|
3341 | return true;
|
3342 | }
|
3343 | return false;
|
3344 | });
|
3345 | });
|
3346 | }
|
3347 | return "" + mechanism + local_1 + ";";
|
3348 | }
|
3349 | var exportBlock = '';
|
3350 |
|
3351 | dependencies.forEach(function (_a) {
|
3352 | var name = _a.name, reexports = _a.reexports;
|
3353 | if (reexports && namedExportsMode) {
|
3354 | reexports.forEach(function (specifier) {
|
3355 | if (specifier.reexported === '*') {
|
3356 | if (!compact && exportBlock)
|
3357 | exportBlock += '\n';
|
3358 | exportBlock +=
|
3359 | "Object.keys(" + name + ").forEach(function" + _ + "(key)" + _ + "{" + n +
|
3360 | (t + "Object.defineProperty(exports," + _ + "key," + _ + "{" + n) +
|
3361 | ("" + t + t + "enumerable:" + _ + "true," + n) +
|
3362 | ("" + t + t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
|
3363 | ("" + t + t + t + "return " + name + "[key];" + n) +
|
3364 | ("" + t + t + "}" + n + t + "});" + n + "});");
|
3365 | }
|
3366 | });
|
3367 | }
|
3368 | });
|
3369 | dependencies.forEach(function (_a) {
|
3370 | var name = _a.name, imports = _a.imports, reexports = _a.reexports, isChunk = _a.isChunk, depNamedExportsMode = _a.namedExportsMode;
|
3371 | if (reexports && namedExportsMode) {
|
3372 | reexports.forEach(function (specifier) {
|
3373 | if (specifier.imported === 'default' && !isChunk) {
|
3374 | var exportsNamesOrNamespace = (imports && imports.some(function (specifier) { return specifier.imported !== 'default'; })) ||
|
3375 | (reexports &&
|
3376 | reexports.some(function (specifier) { return specifier.imported !== 'default' && specifier.imported !== '*'; }));
|
3377 | var reexportsDefaultAsDefault = reexports &&
|
3378 | reexports.some(function (specifier) { return specifier.imported === 'default' && specifier.reexported === 'default'; });
|
3379 | if (exportBlock && !compact)
|
3380 | exportBlock += '\n';
|
3381 | if (exportsNamesOrNamespace || reexportsDefaultAsDefault)
|
3382 | exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + (interop !== false ? '__default' : '.default') + ";";
|
3383 | else
|
3384 | exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
|
3385 | }
|
3386 | else if (specifier.imported !== '*') {
|
3387 | if (exportBlock && !compact)
|
3388 | exportBlock += '\n';
|
3389 | var importName = specifier.imported === 'default' && !depNamedExportsMode
|
3390 | ? name
|
3391 | : name + "." + specifier.imported;
|
3392 | exportBlock += specifier.needsLiveBinding
|
3393 | ? "Object.defineProperty(exports," + _ + "'" + specifier.reexported + "'," + _ + "{" + n +
|
3394 | (t + "enumerable:" + _ + "true," + n) +
|
3395 | (t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
|
3396 | ("" + t + t + "return " + importName + ";" + n + t + "}" + n + "});")
|
3397 | : "exports." + specifier.reexported + _ + "=" + _ + importName + ";";
|
3398 | }
|
3399 | else if (specifier.reexported !== '*') {
|
3400 | if (exportBlock && !compact)
|
3401 | exportBlock += '\n';
|
3402 | exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
|
3403 | }
|
3404 | });
|
3405 | }
|
3406 | });
|
3407 | exports.forEach(function (expt) {
|
3408 | var lhs = "exports." + expt.exported;
|
3409 | var rhs = expt.local;
|
3410 | if (lhs === rhs) {
|
3411 | return;
|
3412 | }
|
3413 | if (exportBlock && !compact)
|
3414 | exportBlock += '\n';
|
3415 | exportBlock += "" + lhs + _ + "=" + _ + rhs + ";";
|
3416 | });
|
3417 | return exportBlock;
|
3418 | }
|
3419 |
|
3420 | function getInteropBlock(dependencies, options, varOrConst) {
|
3421 | return dependencies
|
3422 | .map(function (_a) {
|
3423 | var name = _a.name, exportsNames = _a.exportsNames, exportsDefault = _a.exportsDefault, namedExportsMode = _a.namedExportsMode;
|
3424 | if (!namedExportsMode)
|
3425 | return;
|
3426 | if (!exportsDefault || options.interop === false)
|
3427 | return null;
|
3428 | if (exportsNames) {
|
3429 | if (options.compact)
|
3430 | return varOrConst + " " + name + "__default='default'in " + name + "?" + name + "['default']:" + name + ";";
|
3431 | return varOrConst + " " + name + "__default = 'default' in " + name + " ? " + name + "['default'] : " + name + ";";
|
3432 | }
|
3433 | if (options.compact)
|
3434 | return name + "=" + name + "&&" + name + ".hasOwnProperty('default')?" + name + "['default']:" + name + ";";
|
3435 | return name + " = " + name + " && " + name + ".hasOwnProperty('default') ? " + name + "['default'] : " + name + ";";
|
3436 | })
|
3437 | .filter(Boolean)
|
3438 | .join(options.compact ? '' : '\n');
|
3439 | }
|
3440 |
|
3441 | var builtins$1 = {
|
3442 | assert: true,
|
3443 | buffer: true,
|
3444 | console: true,
|
3445 | constants: true,
|
3446 | domain: true,
|
3447 | events: true,
|
3448 | http: true,
|
3449 | https: true,
|
3450 | os: true,
|
3451 | path: true,
|
3452 | process: true,
|
3453 | punycode: true,
|
3454 | querystring: true,
|
3455 | stream: true,
|
3456 | string_decoder: true,
|
3457 | timers: true,
|
3458 | tty: true,
|
3459 | url: true,
|
3460 | util: true,
|
3461 | vm: true,
|
3462 | zlib: true
|
3463 | };
|
3464 |
|
3465 | function warnOnBuiltins(warn, dependencies) {
|
3466 | var externalBuiltins = dependencies.map(function (_a) {
|
3467 | var id = _a.id;
|
3468 | return id;
|
3469 | }).filter(function (id) { return id in builtins$1; });
|
3470 | if (!externalBuiltins.length)
|
3471 | return;
|
3472 | var detail = externalBuiltins.length === 1
|
3473 | ? "module ('" + externalBuiltins[0] + "')"
|
3474 | : "modules (" + externalBuiltins
|
3475 | .slice(0, -1)
|
3476 | .map(function (name) { return "'" + name + "'"; })
|
3477 | .join(', ') + " and '" + externalBuiltins.slice(-1) + "')";
|
3478 | warn({
|
3479 | code: 'MISSING_NODE_BUILTINS',
|
3480 | 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",
|
3481 | modules: externalBuiltins
|
3482 | });
|
3483 | }
|
3484 |
|
3485 |
|
3486 |
|
3487 |
|
3488 |
|
3489 |
|
3490 | function removeExtensionFromRelativeAmdId(id) {
|
3491 | if (id[0] === '.' && id.endsWith('.js')) {
|
3492 | return id.slice(0, -3);
|
3493 | }
|
3494 | return id;
|
3495 | }
|
3496 | function amd(magicString, _a, options) {
|
3497 | 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;
|
3498 | warnOnBuiltins(warn, dependencies);
|
3499 | var deps = dependencies.map(function (m) { return "'" + removeExtensionFromRelativeAmdId(m.id) + "'"; });
|
3500 | var args = dependencies.map(function (m) { return m.name; });
|
3501 | var n = options.compact ? '' : '\n';
|
3502 | var _ = options.compact ? '' : ' ';
|
3503 | if (namedExportsMode && hasExports) {
|
3504 | args.unshift("exports");
|
3505 | deps.unshift("'exports'");
|
3506 | }
|
3507 | if (dynamicImport) {
|
3508 | args.unshift('require');
|
3509 | deps.unshift("'require'");
|
3510 | }
|
3511 | if (needsAmdModule) {
|
3512 | args.unshift('module');
|
3513 | deps.unshift("'module'");
|
3514 | }
|
3515 | var amdOptions = options.amd || {};
|
3516 | var params = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
|
3517 | (deps.length ? "[" + deps.join("," + _) + "]," + _ : "");
|
3518 | var useStrict = options.strict !== false ? _ + "'use strict';" : "";
|
3519 | var define = amdOptions.define || 'define';
|
3520 | var wrapperStart = define + "(" + params + "function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + useStrict + n + n;
|
3521 |
|
3522 | var interopBlock = getInteropBlock(dependencies, options, varOrConst);
|
3523 | if (interopBlock)
|
3524 | magicString.prepend(interopBlock + n + n);
|
3525 | if (intro)
|
3526 | magicString.prepend(intro);
|
3527 | var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
|
3528 | if (exportBlock)
|
3529 | magicString.append(n + n + exportBlock);
|
3530 | if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
|
3531 | magicString.append("" + n + n + (options.compact ? compactEsModuleExport : esModuleExport));
|
3532 | if (outro)
|
3533 | magicString.append(outro);
|
3534 | return magicString
|
3535 | .indent(t)
|
3536 | .append(n + n + '});')
|
3537 | .prepend(wrapperStart);
|
3538 | }
|
3539 |
|
3540 | function cjs(magicString, _a, options) {
|
3541 | 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;
|
3542 | var n = options.compact ? '' : '\n';
|
3543 | var _ = options.compact ? '' : ' ';
|
3544 | intro =
|
3545 | (options.strict === false ? intro : "'use strict';" + n + n + intro) +
|
3546 | (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
|
3547 | ? "" + (options.compact ? compactEsModuleExport : esModuleExport) + n + n
|
3548 | : '');
|
3549 | var needsInterop = false;
|
3550 | var interop = options.interop !== false;
|
3551 | var importBlock;
|
3552 | var definingVariable = false;
|
3553 | importBlock = '';
|
3554 | for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
|
3555 | 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;
|
3556 | if (!reexports && !imports) {
|
3557 | if (importBlock) {
|
3558 | importBlock += !options.compact || definingVariable ? ";" + n : ',';
|
3559 | }
|
3560 | definingVariable = false;
|
3561 | importBlock += "require('" + id + "')";
|
3562 | }
|
3563 | else {
|
3564 | importBlock +=
|
3565 | options.compact && definingVariable ? ',' : "" + (importBlock ? ";" + n : '') + varOrConst + " ";
|
3566 | definingVariable = true;
|
3567 | if (!interop || isChunk || !exportsDefault || !namedExportsMode_1) {
|
3568 | importBlock += "" + name + _ + "=" + _ + "require('" + id + "')";
|
3569 | }
|
3570 | else {
|
3571 | needsInterop = true;
|
3572 | if (exportsNames)
|
3573 | importBlock += "" + name + _ + "=" + _ + "require('" + id + "')" + (options.compact ? ',' : ";\n" + varOrConst + " ") + name + "__default" + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(" + name + ")";
|
3574 | else
|
3575 | importBlock += "" + name + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(require('" + id + "'))";
|
3576 | }
|
3577 | }
|
3578 | }
|
3579 | if (importBlock)
|
3580 | importBlock += ';';
|
3581 | if (needsInterop) {
|
3582 | var ex = options.compact ? 'e' : 'ex';
|
3583 | intro +=
|
3584 | "function " + INTEROP_DEFAULT_VARIABLE + _ + "(" + ex + ")" + _ + "{" + _ + "return" + _ +
|
3585 | ("(" + ex + _ + "&&" + _ + "(typeof " + ex + _ + "===" + _ + "'object')" + _ + "&&" + _ + "'default'" + _ + "in " + ex + ")" + _) +
|
3586 | ("?" + _ + ex + "['default']" + _ + ":" + _ + ex + (options.compact ? '' : '; ') + "}" + n + n);
|
3587 | }
|
3588 | if (importBlock)
|
3589 | intro += importBlock + n + n;
|
3590 | var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, "module.exports" + _ + "=" + _);
|
3591 | magicString.prepend(intro);
|
3592 | if (exportBlock)
|
3593 | magicString.append(n + n + exportBlock);
|
3594 | if (outro)
|
3595 | magicString.append(outro);
|
3596 | return magicString;
|
3597 | }
|
3598 |
|
3599 | function esm(magicString, _a, options) {
|
3600 | var intro = _a.intro, outro = _a.outro, dependencies = _a.dependencies, exports = _a.exports;
|
3601 | var _ = options.compact ? '' : ' ';
|
3602 | var n = options.compact ? '' : '\n';
|
3603 | var importBlock = dependencies
|
3604 | .map(function (_a) {
|
3605 | var id = _a.id, reexports = _a.reexports, imports = _a.imports, name = _a.name;
|
3606 | if (!reexports && !imports) {
|
3607 | return "import" + _ + "'" + id + "';";
|
3608 | }
|
3609 | var output = '';
|
3610 | if (imports) {
|
3611 | var defaultImport_1 = imports.find(function (specifier) { return specifier.imported === 'default'; });
|
3612 | var starImport_1 = imports.find(function (specifier) { return specifier.imported === '*'; });
|
3613 | if (starImport_1) {
|
3614 | output += "import" + _ + "*" + _ + "as " + starImport_1.local + " from" + _ + "'" + id + "';";
|
3615 | if (imports.length > 1)
|
3616 | output += n;
|
3617 | }
|
3618 | if (defaultImport_1 && imports.length === 1) {
|
3619 | output += "import " + defaultImport_1.local + " from" + _ + "'" + id + "';";
|
3620 | }
|
3621 | else if (!starImport_1 || imports.length > 1) {
|
3622 | output += "import " + (defaultImport_1 ? defaultImport_1.local + "," + _ : '') + "{" + _ + imports
|
3623 | .filter(function (specifier) { return specifier !== defaultImport_1 && specifier !== starImport_1; })
|
3624 | .map(function (specifier) {
|
3625 | if (specifier.imported === specifier.local) {
|
3626 | return specifier.imported;
|
3627 | }
|
3628 | else {
|
3629 | return specifier.imported + " as " + specifier.local;
|
3630 | }
|
3631 | })
|
3632 | .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
|
3633 | }
|
3634 | }
|
3635 | if (reexports) {
|
3636 | if (imports)
|
3637 | output += n;
|
3638 | var starExport_1 = reexports.find(function (specifier) { return specifier.reexported === '*'; });
|
3639 | var namespaceReexport_1 = reexports.find(function (specifier) { return specifier.imported === '*' && specifier.reexported !== '*'; });
|
3640 | if (starExport_1) {
|
3641 | output += "export" + _ + "*" + _ + "from" + _ + "'" + id + "';";
|
3642 | if (reexports.length === 1) {
|
3643 | return output;
|
3644 | }
|
3645 | output += n;
|
3646 | }
|
3647 | if (namespaceReexport_1) {
|
3648 | if (!imports ||
|
3649 | !imports.some(function (specifier) { return specifier.imported === '*' && specifier.local === name; }))
|
3650 | output += "import" + _ + "*" + _ + "as " + name + " from" + _ + "'" + id + "';" + n;
|
3651 | output += "export" + _ + "{" + _ + (name === namespaceReexport_1.reexported
|
3652 | ? name
|
3653 | : name + " as " + namespaceReexport_1.reexported) + " };";
|
3654 | if (reexports.length === (starExport_1 ? 2 : 1)) {
|
3655 | return output;
|
3656 | }
|
3657 | output += n;
|
3658 | }
|
3659 | output += "export" + _ + "{" + _ + reexports
|
3660 | .filter(function (specifier) { return specifier !== starExport_1 && specifier !== namespaceReexport_1; })
|
3661 | .map(function (specifier) {
|
3662 | if (specifier.imported === specifier.reexported) {
|
3663 | return specifier.imported;
|
3664 | }
|
3665 | else {
|
3666 | return specifier.imported + " as " + specifier.reexported;
|
3667 | }
|
3668 | })
|
3669 | .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
|
3670 | }
|
3671 | return output;
|
3672 | })
|
3673 | .join(n);
|
3674 | if (importBlock)
|
3675 | intro += importBlock + n + n;
|
3676 | if (intro)
|
3677 | magicString.prepend(intro);
|
3678 | var exportBlock = [];
|
3679 | var exportDeclaration = [];
|
3680 | exports.forEach(function (specifier) {
|
3681 | if (specifier.exported === 'default') {
|
3682 | exportBlock.push("export default " + specifier.local + ";");
|
3683 | }
|
3684 | else {
|
3685 | exportDeclaration.push(specifier.exported === specifier.local
|
3686 | ? specifier.local
|
3687 | : specifier.local + " as " + specifier.exported);
|
3688 | }
|
3689 | });
|
3690 | if (exportDeclaration.length) {
|
3691 | exportBlock.push("export" + _ + "{" + _ + exportDeclaration.join("," + _) + _ + "};");
|
3692 | }
|
3693 | if (exportBlock.length)
|
3694 | magicString.append(n + n + exportBlock.join(n).trim());
|
3695 | if (outro)
|
3696 | magicString.append(outro);
|
3697 | return magicString.trim();
|
3698 | }
|
3699 |
|
3700 | function getLocator$1(source, options) {
|
3701 | if (options === void 0) { options = {}; }
|
3702 | var offsetLine = options.offsetLine || 0;
|
3703 | var offsetColumn = options.offsetColumn || 0;
|
3704 | var originalLines = source.split('\n');
|
3705 | var start = 0;
|
3706 | var lineRanges = originalLines.map(function (line, i) {
|
3707 | var end = start + line.length + 1;
|
3708 | var range = { start: start, end: end, line: i };
|
3709 | start = end;
|
3710 | return range;
|
3711 | });
|
3712 | var i = 0;
|
3713 | function rangeContains(range, index) {
|
3714 | return range.start <= index && index < range.end;
|
3715 | }
|
3716 | function getLocation(range, index) {
|
3717 | return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
|
3718 | }
|
3719 | function locate(search, startIndex) {
|
3720 | if (typeof search === 'string') {
|
3721 | search = source.indexOf(search, startIndex || 0);
|
3722 | }
|
3723 | var range = lineRanges[i];
|
3724 | var d = search >= range.end ? 1 : -1;
|
3725 | while (range) {
|
3726 | if (rangeContains(range, search))
|
3727 | return getLocation(range, search);
|
3728 | i += d;
|
3729 | range = lineRanges[i];
|
3730 | }
|
3731 | }
|
3732 | return locate;
|
3733 | }
|
3734 | function locate(source, search, options) {
|
3735 | if (typeof options === 'number') {
|
3736 | throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
|
3737 | }
|
3738 | return getLocator$1(source, options)(search, options && options.startIndex);
|
3739 | }
|
3740 |
|
3741 | function spaces(i) {
|
3742 | var result = '';
|
3743 | while (i--)
|
3744 | result += ' ';
|
3745 | return result;
|
3746 | }
|
3747 | function tabsToSpaces(str) {
|
3748 | return str.replace(/^\t+/, function (match) { return match.split('\t').join(' '); });
|
3749 | }
|
3750 | function getCodeFrame(source, line, column) {
|
3751 | var lines = source.split('\n');
|
3752 | var frameStart = Math.max(0, line - 3);
|
3753 | var frameEnd = Math.min(line + 2, lines.length);
|
3754 | lines = lines.slice(frameStart, frameEnd);
|
3755 | while (!/\S/.test(lines[lines.length - 1])) {
|
3756 | lines.pop();
|
3757 | frameEnd -= 1;
|
3758 | }
|
3759 | var digits = String(frameEnd).length;
|
3760 | return lines
|
3761 | .map(function (str, i) {
|
3762 | var isErrorLine = frameStart + i + 1 === line;
|
3763 | var lineNum = String(i + frameStart + 1);
|
3764 | while (lineNum.length < digits)
|
3765 | lineNum = " " + lineNum;
|
3766 | if (isErrorLine) {
|
3767 | var indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
|
3768 | return lineNum + ": " + tabsToSpaces(str) + "\n" + indicator;
|
3769 | }
|
3770 | return lineNum + ": " + tabsToSpaces(str);
|
3771 | })
|
3772 | .join('\n');
|
3773 | }
|
3774 |
|
3775 | function getAliasName(id) {
|
3776 | var base = path.basename(id);
|
3777 | return base.substr(0, base.length - path.extname(id).length);
|
3778 | }
|
3779 | function relativeId(id) {
|
3780 | if (typeof process === 'undefined' || !isAbsolute(id))
|
3781 | return id;
|
3782 | return path.relative(process.cwd(), id);
|
3783 | }
|
3784 | function isPlainName(name) {
|
3785 |
|
3786 | return !(name[0] === '/' ||
|
3787 | (name[1] === '.' && (name[2] === '/' || (name[2] === '.' && name[3] === '/'))));
|
3788 | }
|
3789 |
|
3790 | function error(base, props) {
|
3791 | if (base instanceof Error === false)
|
3792 | base = Object.assign(new Error(base.message), base);
|
3793 | if (props)
|
3794 | Object.assign(base, props);
|
3795 | throw base;
|
3796 | }
|
3797 | function augmentCodeLocation(object, pos, source, id) {
|
3798 | if (pos.line !== undefined && pos.column !== undefined) {
|
3799 | var line = pos.line, column = pos.column;
|
3800 | object.loc = { file: id, line: line, column: column };
|
3801 | }
|
3802 | else {
|
3803 | object.pos = pos;
|
3804 | var _a = locate(source, pos, { offsetLine: 1 }), line = _a.line, column = _a.column;
|
3805 | object.loc = { file: id, line: line, column: column };
|
3806 | }
|
3807 | if (object.frame === undefined) {
|
3808 | var _b = object.loc, line = _b.line, column = _b.column;
|
3809 | object.frame = getCodeFrame(source, line, column);
|
3810 | }
|
3811 | }
|
3812 | var Errors;
|
3813 | (function (Errors) {
|
3814 | Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
|
3815 | Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
|
3816 | Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
|
3817 | Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
|
3818 | Errors["BAD_LOADER"] = "BAD_LOADER";
|
3819 | Errors["CHUNK_NOT_FOUND"] = "CHUNK_NOT_FOUND";
|
3820 | Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
|
3821 | Errors["INVALID_ASSET_NAME"] = "INVALID_ASSET_NAME";
|
3822 | Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
|
3823 | Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
|
3824 | Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
|
3825 | Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
|
3826 | Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
|
3827 | Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
|
3828 | Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
|
3829 | })(Errors || (Errors = {}));
|
3830 | function errAssetNotFinalisedForFileName(asset) {
|
3831 | return {
|
3832 | code: Errors.ASSET_NOT_FINALISED,
|
3833 | message: "Plugin error - Unable to get file name for asset \"" + asset.name + "\". Ensure that the source is set and that generate is called first."
|
3834 | };
|
3835 | }
|
3836 | function errChunkNotGeneratedForFileName(entry) {
|
3837 | return {
|
3838 | code: Errors.CHUNK_NOT_GENERATED,
|
3839 | message: "Plugin error - Unable to get file name for chunk \"" + entry.name + "\". Ensure that generate is called first."
|
3840 | };
|
3841 | }
|
3842 | function errAssetReferenceIdNotFoundForFilename(assetReferenceId) {
|
3843 | return {
|
3844 | code: Errors.ASSET_NOT_FOUND,
|
3845 | message: "Plugin error - Unable to get file name for unknown asset \"" + assetReferenceId + "\"."
|
3846 | };
|
3847 | }
|
3848 | function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
|
3849 | return {
|
3850 | code: Errors.ASSET_NOT_FOUND,
|
3851 | message: "Plugin error - Unable to set the source for unknown asset \"" + assetReferenceId + "\"."
|
3852 | };
|
3853 | }
|
3854 | function errAssetSourceAlreadySet(asset) {
|
3855 | return {
|
3856 | code: Errors.ASSET_SOURCE_ALREADY_SET,
|
3857 | message: "Plugin error - Unable to set the source for asset \"" + asset.name + "\", source already set."
|
3858 | };
|
3859 | }
|
3860 | function errAssetSourceMissingForSetSource(asset) {
|
3861 | return {
|
3862 | code: Errors.ASSET_SOURCE_MISSING,
|
3863 | message: "Plugin error creating asset \"" + asset.name + "\", setAssetSource call without a source."
|
3864 | };
|
3865 | }
|
3866 | function errNoAssetSourceSet(asset) {
|
3867 | return {
|
3868 | code: Errors.ASSET_SOURCE_MISSING,
|
3869 | message: "Plugin error creating asset \"" + asset.name + "\" - no asset source set."
|
3870 | };
|
3871 | }
|
3872 | function errBadLoader(id) {
|
3873 | return {
|
3874 | code: Errors.BAD_LOADER,
|
3875 | message: "Error loading " + relativeId(id) + ": plugin load hook should return a string, a { code, map } object, or nothing/null"
|
3876 | };
|
3877 | }
|
3878 | function errChunkReferenceIdNotFoundForFilename(chunkReferenceId) {
|
3879 | return {
|
3880 | code: Errors.CHUNK_NOT_FOUND,
|
3881 | message: "Plugin error - Unable to get file name for unknown chunk \"" + chunkReferenceId + "\"."
|
3882 | };
|
3883 | }
|
3884 | function errInvalidAssetName(name) {
|
3885 | return {
|
3886 | code: Errors.INVALID_ASSET_NAME,
|
3887 | message: "Plugin error creating asset, name \"" + name + "\" is not a plain (non relative or absolute URL) string name."
|
3888 | };
|
3889 | }
|
3890 | function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
|
3891 | return {
|
3892 | code: Errors.INVALID_CHUNK,
|
3893 | message: "Cannot assign " + relativeId(moduleId) + " to the \"" + assignToAlias + "\" chunk as it is already in the \"" + currentAlias + "\" chunk."
|
3894 | };
|
3895 | }
|
3896 | function errInternalIdCannotBeExternal(source, importer) {
|
3897 | return {
|
3898 | code: Errors.INVALID_EXTERNAL_ID,
|
3899 | message: "'" + source + "' is imported as an external by " + relativeId(importer) + ", but is already an existing non-external module id."
|
3900 | };
|
3901 | }
|
3902 | function errInvalidRollupPhaseForAddWatchFile() {
|
3903 | return {
|
3904 | code: Errors.INVALID_ROLLUP_PHASE,
|
3905 | message: "Cannot call addWatchFile after the build has finished."
|
3906 | };
|
3907 | }
|
3908 | function errInvalidRollupPhaseForEmitChunk() {
|
3909 | return {
|
3910 | code: Errors.INVALID_ROLLUP_PHASE,
|
3911 | message: "Cannot call emitChunk after module loading has finished."
|
3912 | };
|
3913 | }
|
3914 | function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
|
3915 | return {
|
3916 | code: Errors.NAMESPACE_CONFLICT,
|
3917 | message: "Conflicting namespaces: " + relativeId(reexportingModule.id) + " re-exports '" + name + "' from both " + relativeId(reexportingModule.exportsAll[name]) + " and " + relativeId(additionalExportAllModule.exportsAll[name]) + " (will be ignored)",
|
3918 | name: name,
|
3919 | reexporter: reexportingModule.id,
|
3920 | sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
|
3921 | };
|
3922 | }
|
3923 | function errEntryCannotBeExternal(unresolvedId) {
|
3924 | return {
|
3925 | code: Errors.UNRESOLVED_ENTRY,
|
3926 | message: "Entry module cannot be external (" + relativeId(unresolvedId) + ")."
|
3927 | };
|
3928 | }
|
3929 | function errUnresolvedEntry(unresolvedId) {
|
3930 | return {
|
3931 | code: Errors.UNRESOLVED_ENTRY,
|
3932 | message: "Could not resolve entry module (" + relativeId(unresolvedId) + ")."
|
3933 | };
|
3934 | }
|
3935 | function errUnresolvedImport(source, importer) {
|
3936 | return {
|
3937 | code: Errors.UNRESOLVED_IMPORT,
|
3938 | message: "Could not resolve '" + source + "' from " + relativeId(importer)
|
3939 | };
|
3940 | }
|
3941 | function errUnresolvedImportTreatedAsExternal(source, importer) {
|
3942 | return {
|
3943 | code: Errors.UNRESOLVED_IMPORT,
|
3944 | importer: relativeId(importer),
|
3945 | message: "'" + source + "' is imported by " + relativeId(importer) + ", but could not be resolved \u2013 treating it as an external dependency",
|
3946 | source: source,
|
3947 | url: 'https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency'
|
3948 | };
|
3949 | }
|
3950 |
|
3951 |
|
3952 |
|
3953 | var shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
|
3954 | function property(prop) {
|
3955 | return shouldUseDot.test(prop) ? "." + prop : "['" + prop + "']";
|
3956 | }
|
3957 | function keypath(keypath) {
|
3958 | return keypath
|
3959 | .split('.')
|
3960 | .map(property)
|
3961 | .join('');
|
3962 | }
|
3963 |
|
3964 | function setupNamespace(name, root, globals, compact) {
|
3965 | var parts = name.split('.');
|
3966 | if (globals) {
|
3967 | parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
|
3968 | }
|
3969 | var _ = compact ? '' : ' ';
|
3970 | parts.pop();
|
3971 | var acc = root;
|
3972 | return (parts
|
3973 | .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}" + (compact ? '' : ';')); })
|
3974 | .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
|
3975 | }
|
3976 | function assignToDeepVariable(deepName, root, globals, compact, assignment) {
|
3977 | var _ = compact ? '' : ' ';
|
3978 | var parts = deepName.split('.');
|
3979 | if (globals) {
|
3980 | parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
|
3981 | }
|
3982 | var last = parts.pop();
|
3983 | var acc = root;
|
3984 | var deepAssignment = parts
|
3985 | .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}"); })
|
3986 | .concat("" + acc + property(last))
|
3987 | .join("," + _)
|
3988 | .concat(_ + "=" + _ + assignment);
|
3989 | if (parts.length > 0) {
|
3990 | deepAssignment = "(" + deepAssignment + ")";
|
3991 | }
|
3992 | return deepAssignment;
|
3993 | }
|
3994 |
|
3995 | function trimEmptyImports(dependencies) {
|
3996 | var i = dependencies.length;
|
3997 | while (i--) {
|
3998 | var dependency = dependencies[i];
|
3999 | if (dependency.exportsDefault || dependency.exportsNames) {
|
4000 | return dependencies.slice(0, i + 1);
|
4001 | }
|
4002 | }
|
4003 | return [];
|
4004 | }
|
4005 |
|
4006 | var thisProp = function (name) { return "this" + keypath(name); };
|
4007 | function iife(magicString, _a, options) {
|
4008 | 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;
|
4009 | var _ = options.compact ? '' : ' ';
|
4010 | var n = options.compact ? '' : '\n';
|
4011 | var extend = options.extend, name = options.name;
|
4012 | var isNamespaced = name && name.indexOf('.') !== -1;
|
4013 | var useVariableAssignment = !extend && !isNamespaced;
|
4014 | if (name && useVariableAssignment && !isLegal(name)) {
|
4015 | error({
|
4016 | code: 'ILLEGAL_IDENTIFIER_AS_NAME',
|
4017 | message: "Given name (" + name + ") is not legal JS identifier. If you need this you can try --extend option"
|
4018 | });
|
4019 | }
|
4020 | warnOnBuiltins(warn, dependencies);
|
4021 | var external = trimEmptyImports(dependencies);
|
4022 | var deps = external.map(function (dep) { return dep.globalName || 'null'; });
|
4023 | var args = external.map(function (m) { return m.name; });
|
4024 | if (hasExports && !name) {
|
4025 | error({
|
4026 | code: 'INVALID_OPTION',
|
4027 | message: "You must supply \"output.name\" for IIFE bundles."
|
4028 | });
|
4029 | }
|
4030 | if (namedExportsMode && hasExports) {
|
4031 | if (extend) {
|
4032 | deps.unshift("" + thisProp(name) + _ + "=" + _ + thisProp(name) + _ + "||" + _ + "{}");
|
4033 | args.unshift('exports');
|
4034 | }
|
4035 | else {
|
4036 | deps.unshift('{}');
|
4037 | args.unshift('exports');
|
4038 | }
|
4039 | }
|
4040 | var useStrict = options.strict !== false ? t + "'use strict';" + n + n : "";
|
4041 | var wrapperIntro = "(function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + n + useStrict;
|
4042 | if (hasExports && (!extend || !namedExportsMode)) {
|
4043 | wrapperIntro =
|
4044 | (useVariableAssignment ? varOrConst + " " + name : thisProp(name)) +
|
4045 | (_ + "=" + _ + wrapperIntro);
|
4046 | }
|
4047 | if (isNamespaced && hasExports) {
|
4048 | wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
|
4049 | }
|
4050 | var wrapperOutro = "" + n + n + "}(" + deps.join("," + _) + "));";
|
4051 | if (!extend && namedExportsMode && hasExports) {
|
4052 | wrapperOutro = "" + n + n + t + "return exports;" + wrapperOutro;
|
4053 | }
|
4054 |
|
4055 | var interopBlock = getInteropBlock(dependencies, options, varOrConst);
|
4056 | if (interopBlock)
|
4057 | magicString.prepend(interopBlock + n + n);
|
4058 | if (intro)
|
4059 | magicString.prepend(intro);
|
4060 | var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
|
4061 | if (exportBlock)
|
4062 | magicString.append(n + n + exportBlock);
|
4063 | if (outro)
|
4064 | magicString.append(outro);
|
4065 | return magicString
|
4066 | .indent(t)
|
4067 | .prepend(wrapperIntro)
|
4068 | .append(wrapperOutro);
|
4069 | }
|
4070 |
|
4071 | function getStarExcludes(_a) {
|
4072 | var dependencies = _a.dependencies, exports = _a.exports;
|
4073 | var starExcludes = new Set(exports.map(function (expt) { return expt.exported; }));
|
4074 | if (!starExcludes.has('default'))
|
4075 | starExcludes.add('default');
|
4076 |
|
4077 | dependencies.forEach(function (_a) {
|
4078 | var reexports = _a.reexports;
|
4079 | if (reexports)
|
4080 | reexports.forEach(function (reexport) {
|
4081 | if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
|
4082 | starExcludes.add(reexport.reexported);
|
4083 | });
|
4084 | });
|
4085 | return starExcludes;
|
4086 | }
|
4087 | var getStarExcludesBlock = function (starExcludes, varOrConst, _, t, n) {
|
4088 | return starExcludes
|
4089 | ? "" + n + t + varOrConst + " _starExcludes" + _ + "=" + _ + "{" + _ + Array.from(starExcludes).join(":" + _ + "1," + _) + (starExcludes.size ? ":" + _ + "1" : '') + _ + "};"
|
4090 | : '';
|
4091 | };
|
4092 | var getImportBindingsBlock = function (importBindings, _, t, n) { return (importBindings.length ? "" + n + t + "var " + importBindings.join("," + _) + ";" : ''); };
|
4093 | function getExportsBlock(exports, _, t, n) {
|
4094 | if (exports.length === 0) {
|
4095 | return '';
|
4096 | }
|
4097 | if (exports.length === 1) {
|
4098 | return "" + t + t + t + "exports('" + exports[0].name + "'," + _ + exports[0].value + ");" + n + n;
|
4099 | }
|
4100 | return ("" + t + t + t + "exports({" + n +
|
4101 | exports.map(function (_a) {
|
4102 | var name = _a.name, value = _a.value;
|
4103 | return "" + t + t + t + t + name + ":" + _ + value;
|
4104 | }).join("," + n) +
|
4105 | ("" + n + t + t + t + "});" + n + n));
|
4106 | }
|
4107 | var getHoistedExportsBlock = function (exports, _, t, n) {
|
4108 | return getExportsBlock(exports
|
4109 | .filter(function (expt) { return expt.hoisted || expt.uninitialized; })
|
4110 | .map(function (expt) { return ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local }); }), _, t, n);
|
4111 | };
|
4112 | var getMissingExportsBlock = function (exports, _, t, n) {
|
4113 | return getExportsBlock(exports
|
4114 | .filter(function (expt) { return expt.local === MISSING_EXPORT_SHIM_VARIABLE; })
|
4115 | .map(function (expt) { return ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE }); }), _, t, n);
|
4116 | };
|
4117 | function system(magicString, _a, options) {
|
4118 | var dependencies = _a.dependencies, exports = _a.exports, t = _a.indentString, intro = _a.intro, outro = _a.outro, usesTopLevelAwait = _a.usesTopLevelAwait, varOrConst = _a.varOrConst;
|
4119 | var n = options.compact ? '' : '\n';
|
4120 | var _ = options.compact ? '' : ' ';
|
4121 | var dependencyIds = dependencies.map(function (m) { return "'" + m.id + "'"; });
|
4122 | var importBindings = [];
|
4123 | var starExcludes;
|
4124 | var setters = [];
|
4125 | dependencies.forEach(function (_a) {
|
4126 | var imports = _a.imports, reexports = _a.reexports;
|
4127 | var setter = [];
|
4128 | if (imports) {
|
4129 | imports.forEach(function (specifier) {
|
4130 | importBindings.push(specifier.local);
|
4131 | if (specifier.imported === '*') {
|
4132 | setter.push("" + specifier.local + _ + "=" + _ + "module;");
|
4133 | }
|
4134 | else {
|
4135 | setter.push("" + specifier.local + _ + "=" + _ + "module." + specifier.imported + ";");
|
4136 | }
|
4137 | });
|
4138 | }
|
4139 | if (reexports) {
|
4140 | var createdSetter_1 = false;
|
4141 |
|
4142 | if (reexports.length > 1 ||
|
4143 | (reexports.length === 1 &&
|
4144 | (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
|
4145 |
|
4146 | reexports.forEach(function (specifier) {
|
4147 | if (specifier.reexported !== '*')
|
4148 | return;
|
4149 |
|
4150 | if (!starExcludes) {
|
4151 | starExcludes = getStarExcludes({ dependencies: dependencies, exports: exports });
|
4152 | }
|
4153 | if (!createdSetter_1) {
|
4154 | setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
|
4155 | createdSetter_1 = true;
|
4156 | }
|
4157 | setter.push("for" + _ + "(var _$p" + _ + "in" + _ + "module)" + _ + "{");
|
4158 | setter.push(t + "if" + _ + "(!_starExcludes[_$p])" + _ + "_setter[_$p]" + _ + "=" + _ + "module[_$p];");
|
4159 | setter.push('}');
|
4160 | });
|
4161 |
|
4162 | reexports.forEach(function (specifier) {
|
4163 | if (specifier.imported !== '*' || specifier.reexported === '*')
|
4164 | return;
|
4165 | setter.push("exports('" + specifier.reexported + "'," + _ + "module);");
|
4166 | });
|
4167 |
|
4168 | reexports.forEach(function (specifier) {
|
4169 | if (specifier.reexported === '*' || specifier.imported === '*')
|
4170 | return;
|
4171 | if (!createdSetter_1) {
|
4172 | setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
|
4173 | createdSetter_1 = true;
|
4174 | }
|
4175 | setter.push("_setter." + specifier.reexported + _ + "=" + _ + "module." + specifier.imported + ";");
|
4176 | });
|
4177 | if (createdSetter_1) {
|
4178 | setter.push('exports(_setter);');
|
4179 | }
|
4180 | }
|
4181 | else {
|
4182 |
|
4183 | reexports.forEach(function (specifier) {
|
4184 | setter.push("exports('" + specifier.reexported + "'," + _ + "module." + specifier.imported + ");");
|
4185 | });
|
4186 | }
|
4187 | }
|
4188 | setters.push(setter.join("" + n + t + t + t));
|
4189 | });
|
4190 | var registeredName = options.name ? "'" + options.name + "'," + _ : '';
|
4191 | var wrapperStart = "System.register(" + registeredName + "[" +
|
4192 | dependencyIds.join("," + _) +
|
4193 | ("]," + _ + "function" + _ + "(exports," + _ + "module)" + _ + "{" + n + t + "'use strict';") +
|
4194 | getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
|
4195 | getImportBindingsBlock(importBindings, _, t, n) +
|
4196 | ("" + n + t + "return" + _ + "{" + (setters.length
|
4197 | ? "" + n + t + t + "setters:" + _ + "[" + setters
|
4198 | .map(function (s) {
|
4199 | return s
|
4200 | ? "function" + _ + "(module)" + _ + "{" + n + t + t + t + s + n + t + t + "}"
|
4201 | : "function" + _ + "()" + _ + "{}";
|
4202 | })
|
4203 | .join("," + _) + "],"
|
4204 | : '') + n);
|
4205 | wrapperStart +=
|
4206 | "" + t + t + "execute:" + _ + (usesTopLevelAwait ? "async" + _ : '') + "function" + _ + "()" + _ + "{" + n + n +
|
4207 | getHoistedExportsBlock(exports, _, t, n);
|
4208 | var wrapperEnd = "" + n + n +
|
4209 | getMissingExportsBlock(exports, _, t, n) +
|
4210 | ("" + t + t + "}" + n + t + "}" + (options.compact ? '' : ';') + n + "});");
|
4211 | if (intro)
|
4212 | magicString.prepend(intro);
|
4213 | if (outro)
|
4214 | magicString.append(outro);
|
4215 | return magicString
|
4216 | .indent("" + t + t + t)
|
4217 | .append(wrapperEnd)
|
4218 | .prepend(wrapperStart);
|
4219 | }
|
4220 |
|
4221 | function globalProp(name, globalVar) {
|
4222 | if (!name)
|
4223 | return 'null';
|
4224 | return "" + globalVar + keypath(name);
|
4225 | }
|
4226 | function safeAccess(name, globalVar, _) {
|
4227 | var parts = name.split('.');
|
4228 | var acc = globalVar;
|
4229 | return parts.map(function (part) { return ((acc += property(part)), acc); }).join(_ + "&&" + _);
|
4230 | }
|
4231 | function umd(magicString, _a, options) {
|
4232 | 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;
|
4233 | var _ = options.compact ? '' : ' ';
|
4234 | var n = options.compact ? '' : '\n';
|
4235 | var factoryVar = options.compact ? 'f' : 'factory';
|
4236 | var globalVar = options.compact ? 'g' : 'global';
|
4237 | if (hasExports && !options.name) {
|
4238 | error({
|
4239 | code: 'INVALID_OPTION',
|
4240 | message: 'You must supply "output.name" for UMD bundles.'
|
4241 | });
|
4242 | }
|
4243 | warnOnBuiltins(warn, dependencies);
|
4244 | var amdDeps = dependencies.map(function (m) { return "'" + m.id + "'"; });
|
4245 | var cjsDeps = dependencies.map(function (m) { return "require('" + m.id + "')"; });
|
4246 | var trimmedImports = trimEmptyImports(dependencies);
|
4247 | var globalDeps = trimmedImports.map(function (module) { return globalProp(module.globalName, globalVar); });
|
4248 | var factoryArgs = trimmedImports.map(function (m) { return m.name; });
|
4249 | if (namedExportsMode && (hasExports || options.noConflict === true)) {
|
4250 | amdDeps.unshift("'exports'");
|
4251 | cjsDeps.unshift("exports");
|
4252 | globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, (options.extend ? "" + globalProp(options.name, globalVar) + _ + "||" + _ : '') + "{}"));
|
4253 | factoryArgs.unshift('exports');
|
4254 | }
|
4255 | var amdOptions = options.amd || {};
|
4256 | var amdParams = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
|
4257 | (amdDeps.length ? "[" + amdDeps.join("," + _) + "]," + _ : "");
|
4258 | var define = amdOptions.define || 'define';
|
4259 | var cjsExport = !namedExportsMode && hasExports ? "module.exports" + _ + "=" + _ : "";
|
4260 | var useStrict = options.strict !== false ? _ + "'use strict';" + n : "";
|
4261 | var iifeExport;
|
4262 | if (options.noConflict === true) {
|
4263 | var noConflictExportsVar = options.compact ? 'e' : 'exports';
|
4264 | var factory = void 0;
|
4265 | if (!namedExportsMode && hasExports) {
|
4266 | factory = "var " + noConflictExportsVar + _ + "=" + _ + assignToDeepVariable(options.name, globalVar, options.globals, options.compact, factoryVar + "(" + globalDeps.join("," + _) + ")") + ";";
|
4267 | }
|
4268 | else if (namedExportsMode) {
|
4269 | var module = globalDeps.shift();
|
4270 | factory =
|
4271 | "var " + noConflictExportsVar + _ + "=" + _ + module + ";" + n +
|
4272 | ("" + t + t + factoryVar + "(" + [noConflictExportsVar].concat(globalDeps).join("," + _) + ");");
|
4273 | }
|
4274 | iifeExport =
|
4275 | "(function" + _ + "()" + _ + "{" + n +
|
4276 | ("" + t + t + "var current" + _ + "=" + _ + safeAccess(options.name, globalVar, _) + ";" + n) +
|
4277 | ("" + t + t + factory + n) +
|
4278 | ("" + t + t + noConflictExportsVar + ".noConflict" + _ + "=" + _ + "function" + _ + "()" + _ + "{" + _) +
|
4279 | ("" + globalProp(options.name, globalVar) + _ + "=" + _ + "current;" + _ + "return " + noConflictExportsVar + (options.compact ? '' : '; ') + "};" + n) +
|
4280 | (t + "}())");
|
4281 | }
|
4282 | else {
|
4283 | iifeExport = factoryVar + "(" + globalDeps.join("," + _) + ")";
|
4284 | if (!namedExportsMode && hasExports) {
|
4285 | iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
|
4286 | }
|
4287 | }
|
4288 | var iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
|
4289 | var globalParam = iifeNeedsGlobal ? globalVar + "," + _ : '';
|
4290 | var globalArg = iifeNeedsGlobal ? "this," + _ : '';
|
4291 | var iifeStart = iifeNeedsGlobal ? "(" + globalVar + _ + "=" + _ + globalVar + _ + "||" + _ + "self," + _ : '';
|
4292 | var iifeEnd = iifeNeedsGlobal ? ')' : '';
|
4293 | var cjsIntro = iifeNeedsGlobal
|
4294 | ? t + "typeof exports" + _ + "===" + _ + "'object'" + _ + "&&" + _ + "typeof module" + _ + "!==" + _ + "'undefined'" + _ + "?" +
|
4295 | ("" + _ + cjsExport + factoryVar + "(" + cjsDeps.join("," + _) + ")" + _ + ":" + n)
|
4296 | : '';
|
4297 | var wrapperIntro = "(function" + _ + "(" + globalParam + factoryVar + ")" + _ + "{" + n +
|
4298 | cjsIntro +
|
4299 | (t + "typeof " + define + _ + "===" + _ + "'function'" + _ + "&&" + _ + define + ".amd" + _ + "?" + _ + define + "(" + amdParams + factoryVar + ")" + _ + ":" + n) +
|
4300 | ("" + t + iifeStart + iifeExport + iifeEnd + ";" + n) +
|
4301 | ("}(" + globalArg + "function" + _ + "(" + factoryArgs.join(', ') + ")" + _ + "{" + useStrict + n);
|
4302 | var wrapperOutro = n + n + '}));';
|
4303 |
|
4304 | var interopBlock = getInteropBlock(dependencies, options, varOrConst);
|
4305 | if (interopBlock)
|
4306 | magicString.prepend(interopBlock + n + n);
|
4307 | if (intro)
|
4308 | magicString.prepend(intro);
|
4309 | var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
|
4310 | if (exportBlock)
|
4311 | magicString.append(n + n + exportBlock);
|
4312 | if (namedExportsMode && hasExports && options.esModule)
|
4313 | magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
|
4314 | if (outro)
|
4315 | magicString.append(outro);
|
4316 | return magicString
|
4317 | .trim()
|
4318 | .indent(t)
|
4319 | .append(wrapperOutro)
|
4320 | .prepend(wrapperIntro);
|
4321 | }
|
4322 |
|
4323 | var finalisers = { system: system, amd: amd, cjs: cjs, es: esm, iife: iife, umd: umd };
|
4324 |
|
4325 | var extractors = {
|
4326 | ArrayPattern: function (names, param) {
|
4327 | for (var _i = 0, _a = param.elements; _i < _a.length; _i++) {
|
4328 | var element = _a[_i];
|
4329 | if (element)
|
4330 | extractors[element.type](names, element);
|
4331 | }
|
4332 | },
|
4333 | AssignmentPattern: function (names, param) {
|
4334 | extractors[param.left.type](names, param.left);
|
4335 | },
|
4336 | Identifier: function (names, param) {
|
4337 | names.push(param.name);
|
4338 | },
|
4339 | MemberExpression: function () { },
|
4340 | ObjectPattern: function (names, param) {
|
4341 | for (var _i = 0, _a = param.properties; _i < _a.length; _i++) {
|
4342 | var prop = _a[_i];
|
4343 | if (prop.type === 'RestElement') {
|
4344 | extractors.RestElement(names, prop);
|
4345 | }
|
4346 | else {
|
4347 | extractors[prop.value.type](names, prop.value);
|
4348 | }
|
4349 | }
|
4350 | },
|
4351 | RestElement: function (names, param) {
|
4352 | extractors[param.argument.type](names, param.argument);
|
4353 | }
|
4354 | };
|
4355 | var extractAssignedNames = function extractAssignedNames(param) {
|
4356 | var names = [];
|
4357 | extractors[param.type](names, param);
|
4358 | return names;
|
4359 | };
|
4360 |
|
4361 | var BLANK = Object.create(null);
|
4362 |
|
4363 | function treeshakeNode(node, code, start, end) {
|
4364 | code.remove(start, end);
|
4365 | if (node.annotations) {
|
4366 | for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
|
4367 | var annotation = _a[_i];
|
4368 | if (annotation.start < start) {
|
4369 | code.remove(annotation.start, annotation.end);
|
4370 | }
|
4371 | else {
|
4372 | return;
|
4373 | }
|
4374 | }
|
4375 | }
|
4376 | }
|
4377 | function removeAnnotations(node, code) {
|
4378 | if (!node.annotations && node.parent.type === ExpressionStatement) {
|
4379 | node = node.parent;
|
4380 | }
|
4381 | if (node.annotations) {
|
4382 | for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
|
4383 | var annotation = _a[_i];
|
4384 | code.remove(annotation.start, annotation.end);
|
4385 | }
|
4386 | }
|
4387 | }
|
4388 |
|
4389 | var NO_SEMICOLON = { isNoStatement: true };
|
4390 | function findFirstOccurrenceOutsideComment(code, searchString, start) {
|
4391 | if (start === void 0) { start = 0; }
|
4392 | var searchPos, charCodeAfterSlash;
|
4393 | searchPos = code.indexOf(searchString, start);
|
4394 | while (true) {
|
4395 | start = code.indexOf('/', start);
|
4396 | if (start === -1 || start > searchPos)
|
4397 | return searchPos;
|
4398 | charCodeAfterSlash = code.charCodeAt(++start);
|
4399 | ++start;
|
4400 | if (charCodeAfterSlash === 47 ) {
|
4401 | start = code.indexOf('\n', start) + 1;
|
4402 | if (start === 0)
|
4403 | return -1;
|
4404 | if (start > searchPos) {
|
4405 | searchPos = code.indexOf(searchString, start);
|
4406 | }
|
4407 | }
|
4408 | else if (charCodeAfterSlash === 42 ) {
|
4409 | start = code.indexOf('*/', start) + 2;
|
4410 | if (start > searchPos) {
|
4411 | searchPos = code.indexOf(searchString, start);
|
4412 | }
|
4413 | }
|
4414 | }
|
4415 | }
|
4416 | function findFirstLineBreakOutsideComment(code, start) {
|
4417 | if (start === void 0) { start = 0; }
|
4418 | var lineBreakPos, charCodeAfterSlash;
|
4419 | lineBreakPos = code.indexOf('\n', start);
|
4420 | while (true) {
|
4421 | start = code.indexOf('/', start);
|
4422 | if (start === -1 || start > lineBreakPos)
|
4423 | return lineBreakPos;
|
4424 | charCodeAfterSlash = code.charCodeAt(++start);
|
4425 | if (charCodeAfterSlash === 47 )
|
4426 | return lineBreakPos;
|
4427 | ++start;
|
4428 | if (charCodeAfterSlash === 42 ) {
|
4429 | start = code.indexOf('*/', start) + 2;
|
4430 | if (start > lineBreakPos) {
|
4431 | lineBreakPos = code.indexOf('\n', start);
|
4432 | }
|
4433 | }
|
4434 | }
|
4435 | }
|
4436 | function renderStatementList(statements, code, start, end, options) {
|
4437 | if (statements.length === 0)
|
4438 | return;
|
4439 | var currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
|
4440 | var nextNode = statements[0];
|
4441 | var nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
|
4442 | if (nextNodeNeedsBoundaries) {
|
4443 | nextNodeStart =
|
4444 | start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
|
4445 | }
|
4446 | for (var nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
|
4447 | currentNode = nextNode;
|
4448 | currentNodeStart = nextNodeStart;
|
4449 | currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
|
4450 | nextNode = statements[nextIndex];
|
4451 | nextNodeNeedsBoundaries =
|
4452 | nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
|
4453 | if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
|
4454 | nextNodeStart =
|
4455 | currentNode.end +
|
4456 | findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
|
4457 | 1;
|
4458 | if (currentNode.included) {
|
4459 | currentNodeNeedsBoundaries
|
4460 | ? currentNode.render(code, options, {
|
4461 | end: nextNodeStart,
|
4462 | start: currentNodeStart
|
4463 | })
|
4464 | : currentNode.render(code, options);
|
4465 | }
|
4466 | else {
|
4467 | treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
|
4468 | }
|
4469 | }
|
4470 | else {
|
4471 | currentNode.render(code, options);
|
4472 | }
|
4473 | }
|
4474 | }
|
4475 |
|
4476 | function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
|
4477 | var splitUpNodes = [];
|
4478 | var node, nextNode, nextNodeStart, contentEnd, char;
|
4479 | var separator = start - 1;
|
4480 | for (var nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
|
4481 | nextNode = nodes[nextIndex];
|
4482 | if (node !== undefined) {
|
4483 | separator =
|
4484 | node.end +
|
4485 | findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
|
4486 | }
|
4487 | nextNodeStart = contentEnd =
|
4488 | separator +
|
4489 | 2 +
|
4490 | findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
|
4491 | while (((char = code.original.charCodeAt(nextNodeStart)),
|
4492 | char === 32 || char === 9 || char === 10 || char === 13) )
|
4493 | nextNodeStart++;
|
4494 | if (node !== undefined) {
|
4495 | splitUpNodes.push({
|
4496 | contentEnd: contentEnd,
|
4497 | end: nextNodeStart,
|
4498 | node: node,
|
4499 | separator: separator,
|
4500 | start: start
|
4501 | });
|
4502 | }
|
4503 | node = nextNode;
|
4504 | start = nextNodeStart;
|
4505 | }
|
4506 | splitUpNodes.push({
|
4507 | contentEnd: end,
|
4508 | end: end,
|
4509 | node: node,
|
4510 | separator: null,
|
4511 | start: start
|
4512 | });
|
4513 | return splitUpNodes;
|
4514 | }
|
4515 |
|
4516 | var chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
|
4517 | var base = 64;
|
4518 | function toBase64(num) {
|
4519 | var outStr = '';
|
4520 | do {
|
4521 | var curDigit = num % base;
|
4522 | num = Math.floor(num / base);
|
4523 | outStr = chars$1[curDigit] + outStr;
|
4524 | } while (num !== 0);
|
4525 | return outStr;
|
4526 | }
|
4527 |
|
4528 | function getSafeName(baseName, usedNames) {
|
4529 | var safeName = baseName;
|
4530 | var count = 1;
|
4531 | while (usedNames[safeName]) {
|
4532 | safeName = baseName + "$" + toBase64(count++);
|
4533 | }
|
4534 | usedNames[safeName] = true;
|
4535 | return safeName;
|
4536 | }
|
4537 |
|
4538 | var Scope = (function () {
|
4539 | function Scope() {
|
4540 | this.children = [];
|
4541 | this.variables = Object.create(null);
|
4542 | }
|
4543 | Scope.prototype.addDeclaration = function (identifier, context, init, _isHoisted) {
|
4544 | if (init === void 0) { init = null; }
|
4545 | var name = identifier.name;
|
4546 | if (this.variables[name]) {
|
4547 | this.variables[name].addDeclaration(identifier, init);
|
4548 | }
|
4549 | else {
|
4550 | this.variables[name] = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
|
4551 | }
|
4552 | return this.variables[name];
|
4553 | };
|
4554 | Scope.prototype.contains = function (name) {
|
4555 | return name in this.variables;
|
4556 | };
|
4557 | Scope.prototype.findVariable = function (_name) {
|
4558 | throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
|
4559 | };
|
4560 | return Scope;
|
4561 | }());
|
4562 |
|
4563 | var ChildScope = (function (_super) {
|
4564 | __extends(ChildScope, _super);
|
4565 | function ChildScope(parent) {
|
4566 | var _this = _super.call(this) || this;
|
4567 | _this.accessedOutsideVariables = Object.create(null);
|
4568 | _this.parent = parent;
|
4569 | parent.children.push(_this);
|
4570 | return _this;
|
4571 | }
|
4572 | ChildScope.prototype.addNamespaceMemberAccess = function (name, variable) {
|
4573 | this.accessedOutsideVariables[name] = variable;
|
4574 | if (this.parent instanceof ChildScope) {
|
4575 | this.parent.addNamespaceMemberAccess(name, variable);
|
4576 | }
|
4577 | };
|
4578 | ChildScope.prototype.addReturnExpression = function (expression) {
|
4579 | this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
|
4580 | };
|
4581 | ChildScope.prototype.contains = function (name) {
|
4582 | return name in this.variables || this.parent.contains(name);
|
4583 | };
|
4584 | ChildScope.prototype.deconflict = function (forbiddenNames) {
|
4585 | var usedNames = Object.assign(Object.create(null), forbiddenNames);
|
4586 | for (var _i = 0, _a = Object.keys(this.accessedOutsideVariables); _i < _a.length; _i++) {
|
4587 | var name = _a[_i];
|
4588 | var variable = this.accessedOutsideVariables[name];
|
4589 | if (variable.included) {
|
4590 | usedNames[variable.getBaseVariableName()] = true;
|
4591 | }
|
4592 | }
|
4593 | for (var _b = 0, _c = Object.keys(this.variables); _b < _c.length; _b++) {
|
4594 | var name = _c[_b];
|
4595 | var variable = this.variables[name];
|
4596 | if (variable.included) {
|
4597 | variable.setSafeName(getSafeName(name, usedNames));
|
4598 | }
|
4599 | }
|
4600 | for (var _d = 0, _e = this.children; _d < _e.length; _d++) {
|
4601 | var scope = _e[_d];
|
4602 | scope.deconflict(forbiddenNames);
|
4603 | }
|
4604 | };
|
4605 | ChildScope.prototype.findLexicalBoundary = function () {
|
4606 | return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
|
4607 | };
|
4608 | ChildScope.prototype.findVariable = function (name) {
|
4609 | var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
|
4610 | if (knownVariable) {
|
4611 | return knownVariable;
|
4612 | }
|
4613 | return (this.accessedOutsideVariables[name] = this.parent.findVariable(name));
|
4614 | };
|
4615 | return ChildScope;
|
4616 | }(Scope));
|
4617 |
|
4618 |
|
4619 |
|
4620 |
|
4621 |
|
4622 |
|
4623 |
|
4624 |
|
4625 |
|
4626 | var DELETE = 'delete';
|
4627 |
|
4628 |
|
4629 | var SHIFT = 5;
|
4630 | var SIZE = 1 << SHIFT;
|
4631 | var MASK = SIZE - 1;
|
4632 |
|
4633 |
|
4634 |
|
4635 | var NOT_SET = {};
|
4636 |
|
4637 |
|
4638 | function MakeRef() {
|
4639 | return { value: false };
|
4640 | }
|
4641 |
|
4642 | function SetRef(ref) {
|
4643 | if (ref) {
|
4644 | ref.value = true;
|
4645 | }
|
4646 | }
|
4647 |
|
4648 |
|
4649 |
|
4650 |
|
4651 | function OwnerID() {}
|
4652 |
|
4653 | function ensureSize(iter) {
|
4654 | if (iter.size === undefined) {
|
4655 | iter.size = iter.__iterate(returnTrue);
|
4656 | }
|
4657 | return iter.size;
|
4658 | }
|
4659 |
|
4660 | function wrapIndex(iter, index) {
|
4661 |
|
4662 |
|
4663 |
|
4664 |
|
4665 |
|
4666 |
|
4667 |
|
4668 | if (typeof index !== 'number') {
|
4669 | var uint32Index = index >>> 0;
|
4670 | if ('' + uint32Index !== index || uint32Index === 4294967295) {
|
4671 | return NaN;
|
4672 | }
|
4673 | index = uint32Index;
|
4674 | }
|
4675 | return index < 0 ? ensureSize(iter) + index : index;
|
4676 | }
|
4677 |
|
4678 | function returnTrue() {
|
4679 | return true;
|
4680 | }
|
4681 |
|
4682 | function wholeSlice(begin, end, size) {
|
4683 | return (
|
4684 | ((begin === 0 && !isNeg(begin)) ||
|
4685 | (size !== undefined && begin <= -size)) &&
|
4686 | (end === undefined || (size !== undefined && end >= size))
|
4687 | );
|
4688 | }
|
4689 |
|
4690 | function resolveBegin(begin, size) {
|
4691 | return resolveIndex(begin, size, 0);
|
4692 | }
|
4693 |
|
4694 | function resolveEnd(end, size) {
|
4695 | return resolveIndex(end, size, size);
|
4696 | }
|
4697 |
|
4698 | function resolveIndex(index, size, defaultIndex) {
|
4699 |
|
4700 |
|
4701 | return index === undefined
|
4702 | ? defaultIndex
|
4703 | : isNeg(index)
|
4704 | ? size === Infinity
|
4705 | ? size
|
4706 | : Math.max(0, size + index) | 0
|
4707 | : size === undefined || size === index
|
4708 | ? index
|
4709 | : Math.min(size, index) | 0;
|
4710 | }
|
4711 |
|
4712 | function isNeg(value) {
|
4713 |
|
4714 | return value < 0 || (value === 0 && 1 / value === -Infinity);
|
4715 | }
|
4716 |
|
4717 |
|
4718 | var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
|
4719 |
|
4720 | function isCollection(maybeCollection) {
|
4721 | return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]);
|
4722 | }
|
4723 |
|
4724 | var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
|
4725 |
|
4726 | function isKeyed(maybeKeyed) {
|
4727 | return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]);
|
4728 | }
|
4729 |
|
4730 | var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
|
4731 |
|
4732 | function isIndexed(maybeIndexed) {
|
4733 | return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]);
|
4734 | }
|
4735 |
|
4736 | function isAssociative(maybeAssociative) {
|
4737 | return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
|
4738 | }
|
4739 |
|
4740 | var Collection = function Collection(value) {
|
4741 | return isCollection(value) ? value : Seq(value);
|
4742 | };
|
4743 |
|
4744 | var KeyedCollection = (function (Collection) {
|
4745 | function KeyedCollection(value) {
|
4746 | return isKeyed(value) ? value : KeyedSeq(value);
|
4747 | }
|
4748 |
|
4749 | if ( Collection ) KeyedCollection.__proto__ = Collection;
|
4750 | KeyedCollection.prototype = Object.create( Collection && Collection.prototype );
|
4751 | KeyedCollection.prototype.constructor = KeyedCollection;
|
4752 |
|
4753 | return KeyedCollection;
|
4754 | }(Collection));
|
4755 |
|
4756 | var IndexedCollection = (function (Collection) {
|
4757 | function IndexedCollection(value) {
|
4758 | return isIndexed(value) ? value : IndexedSeq(value);
|
4759 | }
|
4760 |
|
4761 | if ( Collection ) IndexedCollection.__proto__ = Collection;
|
4762 | IndexedCollection.prototype = Object.create( Collection && Collection.prototype );
|
4763 | IndexedCollection.prototype.constructor = IndexedCollection;
|
4764 |
|
4765 | return IndexedCollection;
|
4766 | }(Collection));
|
4767 |
|
4768 | var SetCollection = (function (Collection) {
|
4769 | function SetCollection(value) {
|
4770 | return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
|
4771 | }
|
4772 |
|
4773 | if ( Collection ) SetCollection.__proto__ = Collection;
|
4774 | SetCollection.prototype = Object.create( Collection && Collection.prototype );
|
4775 | SetCollection.prototype.constructor = SetCollection;
|
4776 |
|
4777 | return SetCollection;
|
4778 | }(Collection));
|
4779 |
|
4780 | Collection.Keyed = KeyedCollection;
|
4781 | Collection.Indexed = IndexedCollection;
|
4782 | Collection.Set = SetCollection;
|
4783 |
|
4784 | var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
|
4785 |
|
4786 | function isSeq(maybeSeq) {
|
4787 | return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]);
|
4788 | }
|
4789 |
|
4790 | var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
|
4791 |
|
4792 | function isRecord(maybeRecord) {
|
4793 | return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]);
|
4794 | }
|
4795 |
|
4796 | function isImmutable(maybeImmutable) {
|
4797 | return isCollection(maybeImmutable) || isRecord(maybeImmutable);
|
4798 | }
|
4799 |
|
4800 | var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
|
4801 |
|
4802 | function isOrdered(maybeOrdered) {
|
4803 | return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]);
|
4804 | }
|
4805 |
|
4806 | var ITERATE_KEYS = 0;
|
4807 | var ITERATE_VALUES = 1;
|
4808 | var ITERATE_ENTRIES = 2;
|
4809 |
|
4810 | var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
|
4811 | var FAUX_ITERATOR_SYMBOL = '@@iterator';
|
4812 |
|
4813 | var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
|
4814 |
|
4815 | var Iterator = function Iterator(next) {
|
4816 | this.next = next;
|
4817 | };
|
4818 |
|
4819 | Iterator.prototype.toString = function toString () {
|
4820 | return '[Iterator]';
|
4821 | };
|
4822 |
|
4823 | Iterator.KEYS = ITERATE_KEYS;
|
4824 | Iterator.VALUES = ITERATE_VALUES;
|
4825 | Iterator.ENTRIES = ITERATE_ENTRIES;
|
4826 |
|
4827 | Iterator.prototype.inspect = Iterator.prototype.toSource = function() {
|
4828 | return this.toString();
|
4829 | };
|
4830 | Iterator.prototype[ITERATOR_SYMBOL] = function() {
|
4831 | return this;
|
4832 | };
|
4833 |
|
4834 | function iteratorValue(type, k, v, iteratorResult) {
|
4835 | var value = type === 0 ? k : type === 1 ? v : [k, v];
|
4836 | iteratorResult
|
4837 | ? (iteratorResult.value = value)
|
4838 | : (iteratorResult = {
|
4839 | value: value,
|
4840 | done: false,
|
4841 | });
|
4842 | return iteratorResult;
|
4843 | }
|
4844 |
|
4845 | function iteratorDone() {
|
4846 | return { value: undefined, done: true };
|
4847 | }
|
4848 |
|
4849 | function hasIterator(maybeIterable) {
|
4850 | return !!getIteratorFn(maybeIterable);
|
4851 | }
|
4852 |
|
4853 | function isIterator(maybeIterator) {
|
4854 | return maybeIterator && typeof maybeIterator.next === 'function';
|
4855 | }
|
4856 |
|
4857 | function getIterator(iterable) {
|
4858 | var iteratorFn = getIteratorFn(iterable);
|
4859 | return iteratorFn && iteratorFn.call(iterable);
|
4860 | }
|
4861 |
|
4862 | function getIteratorFn(iterable) {
|
4863 | var iteratorFn =
|
4864 | iterable &&
|
4865 | ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
|
4866 | iterable[FAUX_ITERATOR_SYMBOL]);
|
4867 | if (typeof iteratorFn === 'function') {
|
4868 | return iteratorFn;
|
4869 | }
|
4870 | }
|
4871 |
|
4872 | var hasOwnProperty = Object.prototype.hasOwnProperty;
|
4873 |
|
4874 | function isArrayLike(value) {
|
4875 | if (Array.isArray(value) || typeof value === 'string') {
|
4876 | return true;
|
4877 | }
|
4878 |
|
4879 | return (
|
4880 | value &&
|
4881 | typeof value === 'object' &&
|
4882 | Number.isInteger(value.length) &&
|
4883 | value.length >= 0 &&
|
4884 | (value.length === 0
|
4885 | ?
|
4886 | Object.keys(value).length === 1
|
4887 | :
|
4888 |
|
4889 | value.hasOwnProperty(value.length - 1))
|
4890 | );
|
4891 | }
|
4892 |
|
4893 | var Seq = (function (Collection$$1) {
|
4894 | function Seq(value) {
|
4895 | return value === null || value === undefined
|
4896 | ? emptySequence()
|
4897 | : isImmutable(value)
|
4898 | ? value.toSeq()
|
4899 | : seqFromValue(value);
|
4900 | }
|
4901 |
|
4902 | if ( Collection$$1 ) Seq.__proto__ = Collection$$1;
|
4903 | Seq.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
|
4904 | Seq.prototype.constructor = Seq;
|
4905 |
|
4906 | Seq.prototype.toSeq = function toSeq () {
|
4907 | return this;
|
4908 | };
|
4909 |
|
4910 | Seq.prototype.toString = function toString () {
|
4911 | return this.__toString('Seq {', '}');
|
4912 | };
|
4913 |
|
4914 | Seq.prototype.cacheResult = function cacheResult () {
|
4915 | if (!this._cache && this.__iterateUncached) {
|
4916 | this._cache = this.entrySeq().toArray();
|
4917 | this.size = this._cache.length;
|
4918 | }
|
4919 | return this;
|
4920 | };
|
4921 |
|
4922 |
|
4923 |
|
4924 | Seq.prototype.__iterate = function __iterate (fn, reverse) {
|
4925 | var cache = this._cache;
|
4926 | if (cache) {
|
4927 | var size = cache.length;
|
4928 | var i = 0;
|
4929 | while (i !== size) {
|
4930 | var entry = cache[reverse ? size - ++i : i++];
|
4931 | if (fn(entry[1], entry[0], this) === false) {
|
4932 | break;
|
4933 | }
|
4934 | }
|
4935 | return i;
|
4936 | }
|
4937 | return this.__iterateUncached(fn, reverse);
|
4938 | };
|
4939 |
|
4940 |
|
4941 |
|
4942 | Seq.prototype.__iterator = function __iterator (type, reverse) {
|
4943 | var cache = this._cache;
|
4944 | if (cache) {
|
4945 | var size = cache.length;
|
4946 | var i = 0;
|
4947 | return new Iterator(function () {
|
4948 | if (i === size) {
|
4949 | return iteratorDone();
|
4950 | }
|
4951 | var entry = cache[reverse ? size - ++i : i++];
|
4952 | return iteratorValue(type, entry[0], entry[1]);
|
4953 | });
|
4954 | }
|
4955 | return this.__iteratorUncached(type, reverse);
|
4956 | };
|
4957 |
|
4958 | return Seq;
|
4959 | }(Collection));
|
4960 |
|
4961 | var KeyedSeq = (function (Seq) {
|
4962 | function KeyedSeq(value) {
|
4963 | return value === null || value === undefined
|
4964 | ? emptySequence().toKeyedSeq()
|
4965 | : isCollection(value)
|
4966 | ? isKeyed(value)
|
4967 | ? value.toSeq()
|
4968 | : value.fromEntrySeq()
|
4969 | : isRecord(value)
|
4970 | ? value.toSeq()
|
4971 | : keyedSeqFromValue(value);
|
4972 | }
|
4973 |
|
4974 | if ( Seq ) KeyedSeq.__proto__ = Seq;
|
4975 | KeyedSeq.prototype = Object.create( Seq && Seq.prototype );
|
4976 | KeyedSeq.prototype.constructor = KeyedSeq;
|
4977 |
|
4978 | KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () {
|
4979 | return this;
|
4980 | };
|
4981 |
|
4982 | return KeyedSeq;
|
4983 | }(Seq));
|
4984 |
|
4985 | var IndexedSeq = (function (Seq) {
|
4986 | function IndexedSeq(value) {
|
4987 | return value === null || value === undefined
|
4988 | ? emptySequence()
|
4989 | : isCollection(value)
|
4990 | ? isKeyed(value)
|
4991 | ? value.entrySeq()
|
4992 | : value.toIndexedSeq()
|
4993 | : isRecord(value)
|
4994 | ? value.toSeq().entrySeq()
|
4995 | : indexedSeqFromValue(value);
|
4996 | }
|
4997 |
|
4998 | if ( Seq ) IndexedSeq.__proto__ = Seq;
|
4999 | IndexedSeq.prototype = Object.create( Seq && Seq.prototype );
|
5000 | IndexedSeq.prototype.constructor = IndexedSeq;
|
5001 |
|
5002 | IndexedSeq.of = function of (/*...values*/) {
|
5003 | return IndexedSeq(arguments);
|
5004 | };
|
5005 |
|
5006 | IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () {
|
5007 | return this;
|
5008 | };
|
5009 |
|
5010 | IndexedSeq.prototype.toString = function toString () {
|
5011 | return this.__toString('Seq [', ']');
|
5012 | };
|
5013 |
|
5014 | return IndexedSeq;
|
5015 | }(Seq));
|
5016 |
|
5017 | var SetSeq = (function (Seq) {
|
5018 | function SetSeq(value) {
|
5019 | return (isCollection(value) && !isAssociative(value)
|
5020 | ? value
|
5021 | : IndexedSeq(value)
|
5022 | ).toSetSeq();
|
5023 | }
|
5024 |
|
5025 | if ( Seq ) SetSeq.__proto__ = Seq;
|
5026 | SetSeq.prototype = Object.create( Seq && Seq.prototype );
|
5027 | SetSeq.prototype.constructor = SetSeq;
|
5028 |
|
5029 | SetSeq.of = function of (/*...values*/) {
|
5030 | return SetSeq(arguments);
|
5031 | };
|
5032 |
|
5033 | SetSeq.prototype.toSetSeq = function toSetSeq () {
|
5034 | return this;
|
5035 | };
|
5036 |
|
5037 | return SetSeq;
|
5038 | }(Seq));
|
5039 |
|
5040 | Seq.isSeq = isSeq;
|
5041 | Seq.Keyed = KeyedSeq;
|
5042 | Seq.Set = SetSeq;
|
5043 | Seq.Indexed = IndexedSeq;
|
5044 |
|
5045 | Seq.prototype[IS_SEQ_SYMBOL] = true;
|
5046 |
|
5047 |
|
5048 |
|
5049 | var ArraySeq = (function (IndexedSeq) {
|
5050 | function ArraySeq(array) {
|
5051 | this._array = array;
|
5052 | this.size = array.length;
|
5053 | }
|
5054 |
|
5055 | if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq;
|
5056 | ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
|
5057 | ArraySeq.prototype.constructor = ArraySeq;
|
5058 |
|
5059 | ArraySeq.prototype.get = function get (index, notSetValue) {
|
5060 | return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
|
5061 | };
|
5062 |
|
5063 | ArraySeq.prototype.__iterate = function __iterate (fn, reverse) {
|
5064 | var array = this._array;
|
5065 | var size = array.length;
|
5066 | var i = 0;
|
5067 | while (i !== size) {
|
5068 | var ii = reverse ? size - ++i : i++;
|
5069 | if (fn(array[ii], ii, this) === false) {
|
5070 | break;
|
5071 | }
|
5072 | }
|
5073 | return i;
|
5074 | };
|
5075 |
|
5076 | ArraySeq.prototype.__iterator = function __iterator (type, reverse) {
|
5077 | var array = this._array;
|
5078 | var size = array.length;
|
5079 | var i = 0;
|
5080 | return new Iterator(function () {
|
5081 | if (i === size) {
|
5082 | return iteratorDone();
|
5083 | }
|
5084 | var ii = reverse ? size - ++i : i++;
|
5085 | return iteratorValue(type, ii, array[ii]);
|
5086 | });
|
5087 | };
|
5088 |
|
5089 | return ArraySeq;
|
5090 | }(IndexedSeq));
|
5091 |
|
5092 | var ObjectSeq = (function (KeyedSeq) {
|
5093 | function ObjectSeq(object) {
|
5094 | var keys = Object.keys(object);
|
5095 | this._object = object;
|
5096 | this._keys = keys;
|
5097 | this.size = keys.length;
|
5098 | }
|
5099 |
|
5100 | if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq;
|
5101 | ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
|
5102 | ObjectSeq.prototype.constructor = ObjectSeq;
|
5103 |
|
5104 | ObjectSeq.prototype.get = function get (key, notSetValue) {
|
5105 | if (notSetValue !== undefined && !this.has(key)) {
|
5106 | return notSetValue;
|
5107 | }
|
5108 | return this._object[key];
|
5109 | };
|
5110 |
|
5111 | ObjectSeq.prototype.has = function has (key) {
|
5112 | return hasOwnProperty.call(this._object, key);
|
5113 | };
|
5114 |
|
5115 | ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) {
|
5116 | var object = this._object;
|
5117 | var keys = this._keys;
|
5118 | var size = keys.length;
|
5119 | var i = 0;
|
5120 | while (i !== size) {
|
5121 | var key = keys[reverse ? size - ++i : i++];
|
5122 | if (fn(object[key], key, this) === false) {
|
5123 | break;
|
5124 | }
|
5125 | }
|
5126 | return i;
|
5127 | };
|
5128 |
|
5129 | ObjectSeq.prototype.__iterator = function __iterator (type, reverse) {
|
5130 | var object = this._object;
|
5131 | var keys = this._keys;
|
5132 | var size = keys.length;
|
5133 | var i = 0;
|
5134 | return new Iterator(function () {
|
5135 | if (i === size) {
|
5136 | return iteratorDone();
|
5137 | }
|
5138 | var key = keys[reverse ? size - ++i : i++];
|
5139 | return iteratorValue(type, key, object[key]);
|
5140 | });
|
5141 | };
|
5142 |
|
5143 | return ObjectSeq;
|
5144 | }(KeyedSeq));
|
5145 | ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
|
5146 |
|
5147 | var CollectionSeq = (function (IndexedSeq) {
|
5148 | function CollectionSeq(collection) {
|
5149 | this._collection = collection;
|
5150 | this.size = collection.length || collection.size;
|
5151 | }
|
5152 |
|
5153 | if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq;
|
5154 | CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
|
5155 | CollectionSeq.prototype.constructor = CollectionSeq;
|
5156 |
|
5157 | CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
|
5158 | if (reverse) {
|
5159 | return this.cacheResult().__iterate(fn, reverse);
|
5160 | }
|
5161 | var collection = this._collection;
|
5162 | var iterator = getIterator(collection);
|
5163 | var iterations = 0;
|
5164 | if (isIterator(iterator)) {
|
5165 | var step;
|
5166 | while (!(step = iterator.next()).done) {
|
5167 | if (fn(step.value, iterations++, this) === false) {
|
5168 | break;
|
5169 | }
|
5170 | }
|
5171 | }
|
5172 | return iterations;
|
5173 | };
|
5174 |
|
5175 | CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
|
5176 | if (reverse) {
|
5177 | return this.cacheResult().__iterator(type, reverse);
|
5178 | }
|
5179 | var collection = this._collection;
|
5180 | var iterator = getIterator(collection);
|
5181 | if (!isIterator(iterator)) {
|
5182 | return new Iterator(iteratorDone);
|
5183 | }
|
5184 | var iterations = 0;
|
5185 | return new Iterator(function () {
|
5186 | var step = iterator.next();
|
5187 | return step.done ? step : iteratorValue(type, iterations++, step.value);
|
5188 | });
|
5189 | };
|
5190 |
|
5191 | return CollectionSeq;
|
5192 | }(IndexedSeq));
|
5193 |
|
5194 |
|
5195 |
|
5196 | var EMPTY_SEQ;
|
5197 |
|
5198 | function emptySequence() {
|
5199 | return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
|
5200 | }
|
5201 |
|
5202 | function keyedSeqFromValue(value) {
|
5203 | var seq = Array.isArray(value)
|
5204 | ? new ArraySeq(value)
|
5205 | : hasIterator(value)
|
5206 | ? new CollectionSeq(value)
|
5207 | : undefined;
|
5208 | if (seq) {
|
5209 | return seq.fromEntrySeq();
|
5210 | }
|
5211 | if (typeof value === 'object') {
|
5212 | return new ObjectSeq(value);
|
5213 | }
|
5214 | throw new TypeError(
|
5215 | 'Expected Array or collection object of [k, v] entries, or keyed object: ' +
|
5216 | value
|
5217 | );
|
5218 | }
|
5219 |
|
5220 | function indexedSeqFromValue(value) {
|
5221 | var seq = maybeIndexedSeqFromValue(value);
|
5222 | if (seq) {
|
5223 | return seq;
|
5224 | }
|
5225 | throw new TypeError(
|
5226 | 'Expected Array or collection object of values: ' + value
|
5227 | );
|
5228 | }
|
5229 |
|
5230 | function seqFromValue(value) {
|
5231 | var seq = maybeIndexedSeqFromValue(value);
|
5232 | if (seq) {
|
5233 | return seq;
|
5234 | }
|
5235 | if (typeof value === 'object') {
|
5236 | return new ObjectSeq(value);
|
5237 | }
|
5238 | throw new TypeError(
|
5239 | 'Expected Array or collection object of values, or keyed object: ' + value
|
5240 | );
|
5241 | }
|
5242 |
|
5243 | function maybeIndexedSeqFromValue(value) {
|
5244 | return isArrayLike(value)
|
5245 | ? new ArraySeq(value)
|
5246 | : hasIterator(value)
|
5247 | ? new CollectionSeq(value)
|
5248 | : undefined;
|
5249 | }
|
5250 |
|
5251 | var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
|
5252 |
|
5253 | function isMap(maybeMap) {
|
5254 | return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]);
|
5255 | }
|
5256 |
|
5257 | function isOrderedMap(maybeOrderedMap) {
|
5258 | return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
|
5259 | }
|
5260 |
|
5261 | function isValueObject(maybeValue) {
|
5262 | return Boolean(
|
5263 | maybeValue &&
|
5264 | typeof maybeValue.equals === 'function' &&
|
5265 | typeof maybeValue.hashCode === 'function'
|
5266 | );
|
5267 | }
|
5268 |
|
5269 |
|
5270 |
|
5271 |
|
5272 |
|
5273 |
|
5274 |
|
5275 |
|
5276 |
|
5277 |
|
5278 |
|
5279 |
|
5280 |
|
5281 |
|
5282 |
|
5283 |
|
5284 |
|
5285 |
|
5286 |
|
5287 |
|
5288 |
|
5289 |
|
5290 |
|
5291 |
|
5292 |
|
5293 |
|
5294 |
|
5295 |
|
5296 |
|
5297 |
|
5298 |
|
5299 |
|
5300 |
|
5301 |
|
5302 |
|
5303 |
|
5304 |
|
5305 |
|
5306 |
|
5307 |
|
5308 |
|
5309 |
|
5310 |
|
5311 |
|
5312 |
|
5313 |
|
5314 |
|
5315 |
|
5316 |
|
5317 |
|
5318 |
|
5319 |
|
5320 |
|
5321 |
|
5322 |
|
5323 | function is(valueA, valueB) {
|
5324 | if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
|
5325 | return true;
|
5326 | }
|
5327 | if (!valueA || !valueB) {
|
5328 | return false;
|
5329 | }
|
5330 | if (
|
5331 | typeof valueA.valueOf === 'function' &&
|
5332 | typeof valueB.valueOf === 'function'
|
5333 | ) {
|
5334 | valueA = valueA.valueOf();
|
5335 | valueB = valueB.valueOf();
|
5336 | if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
|
5337 | return true;
|
5338 | }
|
5339 | if (!valueA || !valueB) {
|
5340 | return false;
|
5341 | }
|
5342 | }
|
5343 | return !!(
|
5344 | isValueObject(valueA) &&
|
5345 | isValueObject(valueB) &&
|
5346 | valueA.equals(valueB)
|
5347 | );
|
5348 | }
|
5349 |
|
5350 | var imul =
|
5351 | typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
|
5352 | ? Math.imul
|
5353 | : function imul(a, b) {
|
5354 | a |= 0;
|
5355 | b |= 0;
|
5356 | var c = a & 0xffff;
|
5357 | var d = b & 0xffff;
|
5358 |
|
5359 | return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0;
|
5360 | };
|
5361 |
|
5362 |
|
5363 |
|
5364 |
|
5365 |
|
5366 | function smi(i32) {
|
5367 | return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
|
5368 | }
|
5369 |
|
5370 | var defaultValueOf = Object.prototype.valueOf;
|
5371 |
|
5372 | function hash(o) {
|
5373 | switch (typeof o) {
|
5374 | case 'boolean':
|
5375 |
|
5376 |
|
5377 |
|
5378 | return o ? 0x42108421 : 0x42108420;
|
5379 | case 'number':
|
5380 | return hashNumber(o);
|
5381 | case 'string':
|
5382 | return o.length > STRING_HASH_CACHE_MIN_STRLEN
|
5383 | ? cachedHashString(o)
|
5384 | : hashString(o);
|
5385 | case 'object':
|
5386 | case 'function':
|
5387 | if (o === null) {
|
5388 | return 0x42108422;
|
5389 | }
|
5390 | if (typeof o.hashCode === 'function') {
|
5391 |
|
5392 | return smi(o.hashCode(o));
|
5393 | }
|
5394 | if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
|
5395 | o = o.valueOf(o);
|
5396 | }
|
5397 | return hashJSObj(o);
|
5398 | case 'undefined':
|
5399 | return 0x42108423;
|
5400 | default:
|
5401 | if (typeof o.toString === 'function') {
|
5402 | return hashString(o.toString());
|
5403 | }
|
5404 | throw new Error('Value type ' + typeof o + ' cannot be hashed.');
|
5405 | }
|
5406 | }
|
5407 |
|
5408 |
|
5409 | function hashNumber(n) {
|
5410 | if (n !== n || n === Infinity) {
|
5411 | return 0;
|
5412 | }
|
5413 | var hash = n | 0;
|
5414 | if (hash !== n) {
|
5415 | hash ^= n * 0xffffffff;
|
5416 | }
|
5417 | while (n > 0xffffffff) {
|
5418 | n /= 0xffffffff;
|
5419 | hash ^= n;
|
5420 | }
|
5421 | return smi(hash);
|
5422 | }
|
5423 |
|
5424 | function cachedHashString(string) {
|
5425 | var hashed = stringHashCache[string];
|
5426 | if (hashed === undefined) {
|
5427 | hashed = hashString(string);
|
5428 | if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
|
5429 | STRING_HASH_CACHE_SIZE = 0;
|
5430 | stringHashCache = {};
|
5431 | }
|
5432 | STRING_HASH_CACHE_SIZE++;
|
5433 | stringHashCache[string] = hashed;
|
5434 | }
|
5435 | return hashed;
|
5436 | }
|
5437 |
|
5438 |
|
5439 | function hashString(string) {
|
5440 |
|
5441 |
|
5442 |
|
5443 |
|
5444 |
|
5445 |
|
5446 | var hashed = 0;
|
5447 | for (var ii = 0; ii < string.length; ii++) {
|
5448 | hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
|
5449 | }
|
5450 | return smi(hashed);
|
5451 | }
|
5452 |
|
5453 | function hashJSObj(obj) {
|
5454 | var hashed;
|
5455 | if (usingWeakMap) {
|
5456 | hashed = weakMap.get(obj);
|
5457 | if (hashed !== undefined) {
|
5458 | return hashed;
|
5459 | }
|
5460 | }
|
5461 |
|
5462 | hashed = obj[UID_HASH_KEY];
|
5463 | if (hashed !== undefined) {
|
5464 | return hashed;
|
5465 | }
|
5466 |
|
5467 | if (!canDefineProperty) {
|
5468 | hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
|
5469 | if (hashed !== undefined) {
|
5470 | return hashed;
|
5471 | }
|
5472 |
|
5473 | hashed = getIENodeHash(obj);
|
5474 | if (hashed !== undefined) {
|
5475 | return hashed;
|
5476 | }
|
5477 | }
|
5478 |
|
5479 | hashed = ++objHashUID;
|
5480 | if (objHashUID & 0x40000000) {
|
5481 | objHashUID = 0;
|
5482 | }
|
5483 |
|
5484 | if (usingWeakMap) {
|
5485 | weakMap.set(obj, hashed);
|
5486 | } else if (isExtensible !== undefined && isExtensible(obj) === false) {
|
5487 | throw new Error('Non-extensible objects are not allowed as keys.');
|
5488 | } else if (canDefineProperty) {
|
5489 | Object.defineProperty(obj, UID_HASH_KEY, {
|
5490 | enumerable: false,
|
5491 | configurable: false,
|
5492 | writable: false,
|
5493 | value: hashed,
|
5494 | });
|
5495 | } else if (
|
5496 | obj.propertyIsEnumerable !== undefined &&
|
5497 | obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable
|
5498 | ) {
|
5499 |
|
5500 |
|
5501 |
|
5502 |
|
5503 | obj.propertyIsEnumerable = function() {
|
5504 | return this.constructor.prototype.propertyIsEnumerable.apply(
|
5505 | this,
|
5506 | arguments
|
5507 | );
|
5508 | };
|
5509 | obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
|
5510 | } else if (obj.nodeType !== undefined) {
|
5511 |
|
5512 |
|
5513 |
|
5514 |
|
5515 | obj[UID_HASH_KEY] = hashed;
|
5516 | } else {
|
5517 | throw new Error('Unable to set a non-enumerable property on object.');
|
5518 | }
|
5519 |
|
5520 | return hashed;
|
5521 | }
|
5522 |
|
5523 |
|
5524 | var isExtensible = Object.isExtensible;
|
5525 |
|
5526 |
|
5527 | var canDefineProperty = (function() {
|
5528 | try {
|
5529 | Object.defineProperty({}, '@', {});
|
5530 | return true;
|
5531 | } catch (e) {
|
5532 | return false;
|
5533 | }
|
5534 | })();
|
5535 |
|
5536 |
|
5537 |
|
5538 | function getIENodeHash(node) {
|
5539 | if (node && node.nodeType > 0) {
|
5540 | switch (node.nodeType) {
|
5541 | case 1:
|
5542 | return node.uniqueID;
|
5543 | case 9:
|
5544 | return node.documentElement && node.documentElement.uniqueID;
|
5545 | }
|
5546 | }
|
5547 | }
|
5548 |
|
5549 |
|
5550 | var usingWeakMap = typeof WeakMap === 'function';
|
5551 | var weakMap;
|
5552 | if (usingWeakMap) {
|
5553 | weakMap = new WeakMap();
|
5554 | }
|
5555 |
|
5556 | var objHashUID = 0;
|
5557 |
|
5558 | var UID_HASH_KEY = '__immutablehash__';
|
5559 | if (typeof Symbol === 'function') {
|
5560 | UID_HASH_KEY = Symbol(UID_HASH_KEY);
|
5561 | }
|
5562 |
|
5563 | var STRING_HASH_CACHE_MIN_STRLEN = 16;
|
5564 | var STRING_HASH_CACHE_MAX_SIZE = 255;
|
5565 | var STRING_HASH_CACHE_SIZE = 0;
|
5566 | var stringHashCache = {};
|
5567 |
|
5568 | var ToKeyedSequence = (function (KeyedSeq$$1) {
|
5569 | function ToKeyedSequence(indexed, useKeys) {
|
5570 | this._iter = indexed;
|
5571 | this._useKeys = useKeys;
|
5572 | this.size = indexed.size;
|
5573 | }
|
5574 |
|
5575 | if ( KeyedSeq$$1 ) ToKeyedSequence.__proto__ = KeyedSeq$$1;
|
5576 | ToKeyedSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
|
5577 | ToKeyedSequence.prototype.constructor = ToKeyedSequence;
|
5578 |
|
5579 | ToKeyedSequence.prototype.get = function get (key, notSetValue) {
|
5580 | return this._iter.get(key, notSetValue);
|
5581 | };
|
5582 |
|
5583 | ToKeyedSequence.prototype.has = function has (key) {
|
5584 | return this._iter.has(key);
|
5585 | };
|
5586 |
|
5587 | ToKeyedSequence.prototype.valueSeq = function valueSeq () {
|
5588 | return this._iter.valueSeq();
|
5589 | };
|
5590 |
|
5591 | ToKeyedSequence.prototype.reverse = function reverse () {
|
5592 | var this$1 = this;
|
5593 |
|
5594 | var reversedSequence = reverseFactory(this, true);
|
5595 | if (!this._useKeys) {
|
5596 | reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); };
|
5597 | }
|
5598 | return reversedSequence;
|
5599 | };
|
5600 |
|
5601 | ToKeyedSequence.prototype.map = function map (mapper, context) {
|
5602 | var this$1 = this;
|
5603 |
|
5604 | var mappedSequence = mapFactory(this, mapper, context);
|
5605 | if (!this._useKeys) {
|
5606 | mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); };
|
5607 | }
|
5608 | return mappedSequence;
|
5609 | };
|
5610 |
|
5611 | ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) {
|
5612 | var this$1 = this;
|
5613 |
|
5614 | return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
|
5615 | };
|
5616 |
|
5617 | ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) {
|
5618 | return this._iter.__iterator(type, reverse);
|
5619 | };
|
5620 |
|
5621 | return ToKeyedSequence;
|
5622 | }(KeyedSeq));
|
5623 | ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
|
5624 |
|
5625 | var ToIndexedSequence = (function (IndexedSeq$$1) {
|
5626 | function ToIndexedSequence(iter) {
|
5627 | this._iter = iter;
|
5628 | this.size = iter.size;
|
5629 | }
|
5630 |
|
5631 | if ( IndexedSeq$$1 ) ToIndexedSequence.__proto__ = IndexedSeq$$1;
|
5632 | ToIndexedSequence.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
|
5633 | ToIndexedSequence.prototype.constructor = ToIndexedSequence;
|
5634 |
|
5635 | ToIndexedSequence.prototype.includes = function includes (value) {
|
5636 | return this._iter.includes(value);
|
5637 | };
|
5638 |
|
5639 | ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) {
|
5640 | var this$1 = this;
|
5641 |
|
5642 | var i = 0;
|
5643 | reverse && ensureSize(this);
|
5644 | return this._iter.__iterate(
|
5645 | function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); },
|
5646 | reverse
|
5647 | );
|
5648 | };
|
5649 |
|
5650 | ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) {
|
5651 | var this$1 = this;
|
5652 |
|
5653 | var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
|
5654 | var i = 0;
|
5655 | reverse && ensureSize(this);
|
5656 | return new Iterator(function () {
|
5657 | var step = iterator.next();
|
5658 | return step.done
|
5659 | ? step
|
5660 | : iteratorValue(
|
5661 | type,
|
5662 | reverse ? this$1.size - ++i : i++,
|
5663 | step.value,
|
5664 | step
|
5665 | );
|
5666 | });
|
5667 | };
|
5668 |
|
5669 | return ToIndexedSequence;
|
5670 | }(IndexedSeq));
|
5671 |
|
5672 | var ToSetSequence = (function (SetSeq$$1) {
|
5673 | function ToSetSequence(iter) {
|
5674 | this._iter = iter;
|
5675 | this.size = iter.size;
|
5676 | }
|
5677 |
|
5678 | if ( SetSeq$$1 ) ToSetSequence.__proto__ = SetSeq$$1;
|
5679 | ToSetSequence.prototype = Object.create( SetSeq$$1 && SetSeq$$1.prototype );
|
5680 | ToSetSequence.prototype.constructor = ToSetSequence;
|
5681 |
|
5682 | ToSetSequence.prototype.has = function has (key) {
|
5683 | return this._iter.includes(key);
|
5684 | };
|
5685 |
|
5686 | ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) {
|
5687 | var this$1 = this;
|
5688 |
|
5689 | return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse);
|
5690 | };
|
5691 |
|
5692 | ToSetSequence.prototype.__iterator = function __iterator (type, reverse) {
|
5693 | var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
|
5694 | return new Iterator(function () {
|
5695 | var step = iterator.next();
|
5696 | return step.done
|
5697 | ? step
|
5698 | : iteratorValue(type, step.value, step.value, step);
|
5699 | });
|
5700 | };
|
5701 |
|
5702 | return ToSetSequence;
|
5703 | }(SetSeq));
|
5704 |
|
5705 | var FromEntriesSequence = (function (KeyedSeq$$1) {
|
5706 | function FromEntriesSequence(entries) {
|
5707 | this._iter = entries;
|
5708 | this.size = entries.size;
|
5709 | }
|
5710 |
|
5711 | if ( KeyedSeq$$1 ) FromEntriesSequence.__proto__ = KeyedSeq$$1;
|
5712 | FromEntriesSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
|
5713 | FromEntriesSequence.prototype.constructor = FromEntriesSequence;
|
5714 |
|
5715 | FromEntriesSequence.prototype.entrySeq = function entrySeq () {
|
5716 | return this._iter.toSeq();
|
5717 | };
|
5718 |
|
5719 | FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) {
|
5720 | var this$1 = this;
|
5721 |
|
5722 | return this._iter.__iterate(function (entry) {
|
5723 |
|
5724 |
|
5725 | if (entry) {
|
5726 | validateEntry(entry);
|
5727 | var indexedCollection = isCollection(entry);
|
5728 | return fn(
|
5729 | indexedCollection ? entry.get(1) : entry[1],
|
5730 | indexedCollection ? entry.get(0) : entry[0],
|
5731 | this$1
|
5732 | );
|
5733 | }
|
5734 | }, reverse);
|
5735 | };
|
5736 |
|
5737 | FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) {
|
5738 | var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
|
5739 | return new Iterator(function () {
|
5740 | while (true) {
|
5741 | var step = iterator.next();
|
5742 | if (step.done) {
|
5743 | return step;
|
5744 | }
|
5745 | var entry = step.value;
|
5746 |
|
5747 |
|
5748 | if (entry) {
|
5749 | validateEntry(entry);
|
5750 | var indexedCollection = isCollection(entry);
|
5751 | return iteratorValue(
|
5752 | type,
|
5753 | indexedCollection ? entry.get(0) : entry[0],
|
5754 | indexedCollection ? entry.get(1) : entry[1],
|
5755 | step
|
5756 | );
|
5757 | }
|
5758 | }
|
5759 | });
|
5760 | };
|
5761 |
|
5762 | return FromEntriesSequence;
|
5763 | }(KeyedSeq));
|
5764 |
|
5765 | ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough;
|
5766 |
|
5767 | function flipFactory(collection) {
|
5768 | var flipSequence = makeSequence(collection);
|
5769 | flipSequence._iter = collection;
|
5770 | flipSequence.size = collection.size;
|
5771 | flipSequence.flip = function () { return collection; };
|
5772 | flipSequence.reverse = function() {
|
5773 | var reversedSequence = collection.reverse.apply(this);
|
5774 | reversedSequence.flip = function () { return collection.reverse(); };
|
5775 | return reversedSequence;
|
5776 | };
|
5777 | flipSequence.has = function (key) { return collection.includes(key); };
|
5778 | flipSequence.includes = function (key) { return collection.has(key); };
|
5779 | flipSequence.cacheResult = cacheResultThrough;
|
5780 | flipSequence.__iterateUncached = function(fn, reverse) {
|
5781 | var this$1 = this;
|
5782 |
|
5783 | return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse);
|
5784 | };
|
5785 | flipSequence.__iteratorUncached = function(type, reverse) {
|
5786 | if (type === ITERATE_ENTRIES) {
|
5787 | var iterator = collection.__iterator(type, reverse);
|
5788 | return new Iterator(function () {
|
5789 | var step = iterator.next();
|
5790 | if (!step.done) {
|
5791 | var k = step.value[0];
|
5792 | step.value[0] = step.value[1];
|
5793 | step.value[1] = k;
|
5794 | }
|
5795 | return step;
|
5796 | });
|
5797 | }
|
5798 | return collection.__iterator(
|
5799 | type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
|
5800 | reverse
|
5801 | );
|
5802 | };
|
5803 | return flipSequence;
|
5804 | }
|
5805 |
|
5806 | function mapFactory(collection, mapper, context) {
|
5807 | var mappedSequence = makeSequence(collection);
|
5808 | mappedSequence.size = collection.size;
|
5809 | mappedSequence.has = function (key) { return collection.has(key); };
|
5810 | mappedSequence.get = function (key, notSetValue) {
|
5811 | var v = collection.get(key, NOT_SET);
|
5812 | return v === NOT_SET
|
5813 | ? notSetValue
|
5814 | : mapper.call(context, v, key, collection);
|
5815 | };
|
5816 | mappedSequence.__iterateUncached = function(fn, reverse) {
|
5817 | var this$1 = this;
|
5818 |
|
5819 | return collection.__iterate(
|
5820 | function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; },
|
5821 | reverse
|
5822 | );
|
5823 | };
|
5824 | mappedSequence.__iteratorUncached = function(type, reverse) {
|
5825 | var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
|
5826 | return new Iterator(function () {
|
5827 | var step = iterator.next();
|
5828 | if (step.done) {
|
5829 | return step;
|
5830 | }
|
5831 | var entry = step.value;
|
5832 | var key = entry[0];
|
5833 | return iteratorValue(
|
5834 | type,
|
5835 | key,
|
5836 | mapper.call(context, entry[1], key, collection),
|
5837 | step
|
5838 | );
|
5839 | });
|
5840 | };
|
5841 | return mappedSequence;
|
5842 | }
|
5843 |
|
5844 | function reverseFactory(collection, useKeys) {
|
5845 | var this$1 = this;
|
5846 |
|
5847 | var reversedSequence = makeSequence(collection);
|
5848 | reversedSequence._iter = collection;
|
5849 | reversedSequence.size = collection.size;
|
5850 | reversedSequence.reverse = function () { return collection; };
|
5851 | if (collection.flip) {
|
5852 | reversedSequence.flip = function() {
|
5853 | var flipSequence = flipFactory(collection);
|
5854 | flipSequence.reverse = function () { return collection.flip(); };
|
5855 | return flipSequence;
|
5856 | };
|
5857 | }
|
5858 | reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
|
5859 | reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
|
5860 | reversedSequence.includes = function (value) { return collection.includes(value); };
|
5861 | reversedSequence.cacheResult = cacheResultThrough;
|
5862 | reversedSequence.__iterate = function(fn, reverse) {
|
5863 | var this$1 = this;
|
5864 |
|
5865 | var i = 0;
|
5866 | reverse && ensureSize(collection);
|
5867 | return collection.__iterate(
|
5868 | function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); },
|
5869 | !reverse
|
5870 | );
|
5871 | };
|
5872 | reversedSequence.__iterator = function (type, reverse) {
|
5873 | var i = 0;
|
5874 | reverse && ensureSize(collection);
|
5875 | var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
|
5876 | return new Iterator(function () {
|
5877 | var step = iterator.next();
|
5878 | if (step.done) {
|
5879 | return step;
|
5880 | }
|
5881 | var entry = step.value;
|
5882 | return iteratorValue(
|
5883 | type,
|
5884 | useKeys ? entry[0] : reverse ? this$1.size - ++i : i++,
|
5885 | entry[1],
|
5886 | step
|
5887 | );
|
5888 | });
|
5889 | };
|
5890 | return reversedSequence;
|
5891 | }
|
5892 |
|
5893 | function filterFactory(collection, predicate, context, useKeys) {
|
5894 | var filterSequence = makeSequence(collection);
|
5895 | if (useKeys) {
|
5896 | filterSequence.has = function (key) {
|
5897 | var v = collection.get(key, NOT_SET);
|
5898 | return v !== NOT_SET && !!predicate.call(context, v, key, collection);
|
5899 | };
|
5900 | filterSequence.get = function (key, notSetValue) {
|
5901 | var v = collection.get(key, NOT_SET);
|
5902 | return v !== NOT_SET && predicate.call(context, v, key, collection)
|
5903 | ? v
|
5904 | : notSetValue;
|
5905 | };
|
5906 | }
|
5907 | filterSequence.__iterateUncached = function(fn, reverse) {
|
5908 | var this$1 = this;
|
5909 |
|
5910 | var iterations = 0;
|
5911 | collection.__iterate(function (v, k, c) {
|
5912 | if (predicate.call(context, v, k, c)) {
|
5913 | iterations++;
|
5914 | return fn(v, useKeys ? k : iterations - 1, this$1);
|
5915 | }
|
5916 | }, reverse);
|
5917 | return iterations;
|
5918 | };
|
5919 | filterSequence.__iteratorUncached = function(type, reverse) {
|
5920 | var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
|
5921 | var iterations = 0;
|
5922 | return new Iterator(function () {
|
5923 | while (true) {
|
5924 | var step = iterator.next();
|
5925 | if (step.done) {
|
5926 | return step;
|
5927 | }
|
5928 | var entry = step.value;
|
5929 | var key = entry[0];
|
5930 | var value = entry[1];
|
5931 | if (predicate.call(context, value, key, collection)) {
|
5932 | return iteratorValue(type, useKeys ? key : iterations++, value, step);
|
5933 | }
|
5934 | }
|
5935 | });
|
5936 | };
|
5937 | return filterSequence;
|
5938 | }
|
5939 |
|
5940 | function countByFactory(collection, grouper, context) {
|
5941 | var groups = Map$1().asMutable();
|
5942 | collection.__iterate(function (v, k) {
|
5943 | groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
|
5944 | });
|
5945 | return groups.asImmutable();
|
5946 | }
|
5947 |
|
5948 | function groupByFactory(collection, grouper, context) {
|
5949 | var isKeyedIter = isKeyed(collection);
|
5950 | var groups = (isOrdered(collection) ? OrderedMap() : Map$1()).asMutable();
|
5951 | collection.__iterate(function (v, k) {
|
5952 | groups.update(
|
5953 | grouper.call(context, v, k, collection),
|
5954 | function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }
|
5955 | );
|
5956 | });
|
5957 | var coerce = collectionClass(collection);
|
5958 | return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
|
5959 | }
|
5960 |
|
5961 | function sliceFactory(collection, begin, end, useKeys) {
|
5962 | var originalSize = collection.size;
|
5963 |
|
5964 | if (wholeSlice(begin, end, originalSize)) {
|
5965 | return collection;
|
5966 | }
|
5967 |
|
5968 | var resolvedBegin = resolveBegin(begin, originalSize);
|
5969 | var resolvedEnd = resolveEnd(end, originalSize);
|
5970 |
|
5971 |
|
5972 |
|
5973 |
|
5974 | if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
|
5975 | return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
|
5976 | }
|
5977 |
|
5978 |
|
5979 |
|
5980 |
|
5981 |
|
5982 | var resolvedSize = resolvedEnd - resolvedBegin;
|
5983 | var sliceSize;
|
5984 | if (resolvedSize === resolvedSize) {
|
5985 | sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
|
5986 | }
|
5987 |
|
5988 | var sliceSeq = makeSequence(collection);
|
5989 |
|
5990 |
|
5991 |
|
5992 | sliceSeq.size =
|
5993 | sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
|
5994 |
|
5995 | if (!useKeys && isSeq(collection) && sliceSize >= 0) {
|
5996 | sliceSeq.get = function(index, notSetValue) {
|
5997 | index = wrapIndex(this, index);
|
5998 | return index >= 0 && index < sliceSize
|
5999 | ? collection.get(index + resolvedBegin, notSetValue)
|
6000 | : notSetValue;
|
6001 | };
|
6002 | }
|
6003 |
|
6004 | sliceSeq.__iterateUncached = function(fn, reverse) {
|
6005 | var this$1 = this;
|
6006 |
|
6007 | if (sliceSize === 0) {
|
6008 | return 0;
|
6009 | }
|
6010 | if (reverse) {
|
6011 | return this.cacheResult().__iterate(fn, reverse);
|
6012 | }
|
6013 | var skipped = 0;
|
6014 | var isSkipping = true;
|
6015 | var iterations = 0;
|
6016 | collection.__iterate(function (v, k) {
|
6017 | if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
|
6018 | iterations++;
|
6019 | return (
|
6020 | fn(v, useKeys ? k : iterations - 1, this$1) !== false &&
|
6021 | iterations !== sliceSize
|
6022 | );
|
6023 | }
|
6024 | });
|
6025 | return iterations;
|
6026 | };
|
6027 |
|
6028 | sliceSeq.__iteratorUncached = function(type, reverse) {
|
6029 | if (sliceSize !== 0 && reverse) {
|
6030 | return this.cacheResult().__iterator(type, reverse);
|
6031 | }
|
6032 | // Don't bother instantiating parent iterator if taking 0.
|
6033 | if (sliceSize === 0) {
|
6034 | return new Iterator(iteratorDone);
|
6035 | }
|
6036 | var iterator = collection.__iterator(type, reverse);
|
6037 | var skipped = 0;
|
6038 | var iterations = 0;
|
6039 | return new Iterator(function () {
|
6040 | while (skipped++ < resolvedBegin) {
|
6041 | iterator.next();
|
6042 | }
|
6043 | if (++iterations > sliceSize) {
|
6044 | return iteratorDone();
|
6045 | }
|
6046 | var step = iterator.next();
|
6047 | if (useKeys || type === ITERATE_VALUES || step.done) {
|
6048 | return step;
|
6049 | }
|
6050 | if (type === ITERATE_KEYS) {
|
6051 | return iteratorValue(type, iterations - 1, undefined, step);
|
6052 | }
|
6053 | return iteratorValue(type, iterations - 1, step.value[1], step);
|
6054 | });
|
6055 | };
|
6056 |
|
6057 | return sliceSeq;
|
6058 | }
|
6059 |
|
6060 | function takeWhileFactory(collection, predicate, context) {
|
6061 | var takeSequence = makeSequence(collection);
|
6062 | takeSequence.__iterateUncached = function(fn, reverse) {
|
6063 | var this$1 = this;
|
6064 |
|
6065 | if (reverse) {
|
6066 | return this.cacheResult().__iterate(fn, reverse);
|
6067 | }
|
6068 | var iterations = 0;
|
6069 | collection.__iterate(
|
6070 | function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); }
|
6071 | );
|
6072 | return iterations;
|
6073 | };
|
6074 | takeSequence.__iteratorUncached = function(type, reverse) {
|
6075 | var this$1 = this;
|
6076 |
|
6077 | if (reverse) {
|
6078 | return this.cacheResult().__iterator(type, reverse);
|
6079 | }
|
6080 | var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
|
6081 | var iterating = true;
|
6082 | return new Iterator(function () {
|
6083 | if (!iterating) {
|
6084 | return iteratorDone();
|
6085 | }
|
6086 | var step = iterator.next();
|
6087 | if (step.done) {
|
6088 | return step;
|
6089 | }
|
6090 | var entry = step.value;
|
6091 | var k = entry[0];
|
6092 | var v = entry[1];
|
6093 | if (!predicate.call(context, v, k, this$1)) {
|
6094 | iterating = false;
|
6095 | return iteratorDone();
|
6096 | }
|
6097 | return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
|
6098 | });
|
6099 | };
|
6100 | return takeSequence;
|
6101 | }
|
6102 |
|
6103 | function skipWhileFactory(collection, predicate, context, useKeys) {
|
6104 | var skipSequence = makeSequence(collection);
|
6105 | skipSequence.__iterateUncached = function(fn, reverse) {
|
6106 | var this$1 = this;
|
6107 |
|
6108 | if (reverse) {
|
6109 | return this.cacheResult().__iterate(fn, reverse);
|
6110 | }
|
6111 | var isSkipping = true;
|
6112 | var iterations = 0;
|
6113 | collection.__iterate(function (v, k, c) {
|
6114 | if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
|
6115 | iterations++;
|
6116 | return fn(v, useKeys ? k : iterations - 1, this$1);
|
6117 | }
|
6118 | });
|
6119 | return iterations;
|
6120 | };
|
6121 | skipSequence.__iteratorUncached = function(type, reverse) {
|
6122 | var this$1 = this;
|
6123 |
|
6124 | if (reverse) {
|
6125 | return this.cacheResult().__iterator(type, reverse);
|
6126 | }
|
6127 | var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
|
6128 | var skipping = true;
|
6129 | var iterations = 0;
|
6130 | return new Iterator(function () {
|
6131 | var step;
|
6132 | var k;
|
6133 | var v;
|
6134 | do {
|
6135 | step = iterator.next();
|
6136 | if (step.done) {
|
6137 | if (useKeys || type === ITERATE_VALUES) {
|
6138 | return step;
|
6139 | }
|
6140 | if (type === ITERATE_KEYS) {
|
6141 | return iteratorValue(type, iterations++, undefined, step);
|
6142 | }
|
6143 | return iteratorValue(type, iterations++, step.value[1], step);
|
6144 | }
|
6145 | var entry = step.value;
|
6146 | k = entry[0];
|
6147 | v = entry[1];
|
6148 | skipping && (skipping = predicate.call(context, v, k, this$1));
|
6149 | } while (skipping);
|
6150 | return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
|
6151 | });
|
6152 | };
|
6153 | return skipSequence;
|
6154 | }
|
6155 |
|
6156 | function concatFactory(collection, values) {
|
6157 | var isKeyedCollection = isKeyed(collection);
|
6158 | var iters = [collection]
|
6159 | .concat(values)
|
6160 | .map(function (v) {
|
6161 | if (!isCollection(v)) {
|
6162 | v = isKeyedCollection
|
6163 | ? keyedSeqFromValue(v)
|
6164 | : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
|
6165 | } else if (isKeyedCollection) {
|
6166 | v = KeyedCollection(v);
|
6167 | }
|
6168 | return v;
|
6169 | })
|
6170 | .filter(function (v) { return v.size !== 0; });
|
6171 |
|
6172 | if (iters.length === 0) {
|
6173 | return collection;
|
6174 | }
|
6175 |
|
6176 | if (iters.length === 1) {
|
6177 | var singleton = iters[0];
|
6178 | if (
|
6179 | singleton === collection ||
|
6180 | (isKeyedCollection && isKeyed(singleton)) ||
|
6181 | (isIndexed(collection) && isIndexed(singleton))
|
6182 | ) {
|
6183 | return singleton;
|
6184 | }
|
6185 | }
|
6186 |
|
6187 | var concatSeq = new ArraySeq(iters);
|
6188 | if (isKeyedCollection) {
|
6189 | concatSeq = concatSeq.toKeyedSeq();
|
6190 | } else if (!isIndexed(collection)) {
|
6191 | concatSeq = concatSeq.toSetSeq();
|
6192 | }
|
6193 | concatSeq = concatSeq.flatten(true);
|
6194 | concatSeq.size = iters.reduce(function (sum, seq) {
|
6195 | if (sum !== undefined) {
|
6196 | var size = seq.size;
|
6197 | if (size !== undefined) {
|
6198 | return sum + size;
|
6199 | }
|
6200 | }
|
6201 | }, 0);
|
6202 | return concatSeq;
|
6203 | }
|
6204 |
|
6205 | function flattenFactory(collection, depth, useKeys) {
|
6206 | var flatSequence = makeSequence(collection);
|
6207 | flatSequence.__iterateUncached = function(fn, reverse) {
|
6208 | if (reverse) {
|
6209 | return this.cacheResult().__iterate(fn, reverse);
|
6210 | }
|
6211 | var iterations = 0;
|
6212 | var stopped = false;
|
6213 | function flatDeep(iter, currentDepth) {
|
6214 | iter.__iterate(function (v, k) {
|
6215 | if ((!depth || currentDepth < depth) && isCollection(v)) {
|
6216 | flatDeep(v, currentDepth + 1);
|
6217 | } else {
|
6218 | iterations++;
|
6219 | if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
|
6220 | stopped = true;
|
6221 | }
|
6222 | }
|
6223 | return !stopped;
|
6224 | }, reverse);
|
6225 | }
|
6226 | flatDeep(collection, 0);
|
6227 | return iterations;
|
6228 | };
|
6229 | flatSequence.__iteratorUncached = function(type, reverse) {
|
6230 | if (reverse) {
|
6231 | return this.cacheResult().__iterator(type, reverse);
|
6232 | }
|
6233 | var iterator = collection.__iterator(type, reverse);
|
6234 | var stack = [];
|
6235 | var iterations = 0;
|
6236 | return new Iterator(function () {
|
6237 | while (iterator) {
|
6238 | var step = iterator.next();
|
6239 | if (step.done !== false) {
|
6240 | iterator = stack.pop();
|
6241 | continue;
|
6242 | }
|
6243 | var v = step.value;
|
6244 | if (type === ITERATE_ENTRIES) {
|
6245 | v = v[1];
|
6246 | }
|
6247 | if ((!depth || stack.length < depth) && isCollection(v)) {
|
6248 | stack.push(iterator);
|
6249 | iterator = v.__iterator(type, reverse);
|
6250 | } else {
|
6251 | return useKeys ? step : iteratorValue(type, iterations++, v, step);
|
6252 | }
|
6253 | }
|
6254 | return iteratorDone();
|
6255 | });
|
6256 | };
|
6257 | return flatSequence;
|
6258 | }
|
6259 |
|
6260 | function flatMapFactory(collection, mapper, context) {
|
6261 | var coerce = collectionClass(collection);
|
6262 | return collection
|
6263 | .toSeq()
|
6264 | .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
|
6265 | .flatten(true);
|
6266 | }
|
6267 |
|
6268 | function interposeFactory(collection, separator) {
|
6269 | var interposedSequence = makeSequence(collection);
|
6270 | interposedSequence.size = collection.size && collection.size * 2 - 1;
|
6271 | interposedSequence.__iterateUncached = function(fn, reverse) {
|
6272 | var this$1 = this;
|
6273 |
|
6274 | var iterations = 0;
|
6275 | collection.__iterate(
|
6276 | function (v) { return (!iterations || fn(separator, iterations++, this$1) !== false) &&
|
6277 | fn(v, iterations++, this$1) !== false; },
|
6278 | reverse
|
6279 | );
|
6280 | return iterations;
|
6281 | };
|
6282 | interposedSequence.__iteratorUncached = function(type, reverse) {
|
6283 | var iterator = collection.__iterator(ITERATE_VALUES, reverse);
|
6284 | var iterations = 0;
|
6285 | var step;
|
6286 | return new Iterator(function () {
|
6287 | if (!step || iterations % 2) {
|
6288 | step = iterator.next();
|
6289 | if (step.done) {
|
6290 | return step;
|
6291 | }
|
6292 | }
|
6293 | return iterations % 2
|
6294 | ? iteratorValue(type, iterations++, separator)
|
6295 | : iteratorValue(type, iterations++, step.value, step);
|
6296 | });
|
6297 | };
|
6298 | return interposedSequence;
|
6299 | }
|
6300 |
|
6301 | function sortFactory(collection, comparator, mapper) {
|
6302 | if (!comparator) {
|
6303 | comparator = defaultComparator;
|
6304 | }
|
6305 | var isKeyedCollection = isKeyed(collection);
|
6306 | var index = 0;
|
6307 | var entries = collection
|
6308 | .toSeq()
|
6309 | .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
|
6310 | .valueSeq()
|
6311 | .toArray();
|
6312 | entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(
|
6313 | isKeyedCollection
|
6314 | ? function (v, i) {
|
6315 | entries[i].length = 2;
|
6316 | }
|
6317 | : function (v, i) {
|
6318 | entries[i] = v[1];
|
6319 | }
|
6320 | );
|
6321 | return isKeyedCollection
|
6322 | ? KeyedSeq(entries)
|
6323 | : isIndexed(collection)
|
6324 | ? IndexedSeq(entries)
|
6325 | : SetSeq(entries);
|
6326 | }
|
6327 |
|
6328 | function maxFactory(collection, comparator, mapper) {
|
6329 | if (!comparator) {
|
6330 | comparator = defaultComparator;
|
6331 | }
|
6332 | if (mapper) {
|
6333 | var entry = collection
|
6334 | .toSeq()
|
6335 | .map(function (v, k) { return [v, mapper(v, k, collection)]; })
|
6336 | .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
|
6337 | return entry && entry[0];
|
6338 | }
|
6339 | return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
|
6340 | }
|
6341 |
|
6342 | function maxCompare(comparator, a, b) {
|
6343 | var comp = comparator(b, a);
|
6344 | // b is considered the new max if the comparator declares them equal, but
|
6345 | // they are not equal and b is in fact a nullish value.
|
6346 | return (
|
6347 | (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
|
6348 | comp > 0
|
6349 | );
|
6350 | }
|
6351 |
|
6352 | function zipWithFactory(keyIter, zipper, iters, zipAll) {
|
6353 | var zipSequence = makeSequence(keyIter);
|
6354 | var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
|
6355 | zipSequence.size = zipAll ? sizes.max() : sizes.min();
|
6356 | // Note: this a generic base implementation of __iterate in terms of
|
6357 | // __iterator which may be more generically useful in the future.
|
6358 | zipSequence.__iterate = function(fn, reverse) {
|
6359 | /* generic:
|
6360 | var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
|
6361 | var step;
|
6362 | var iterations = 0;
|
6363 | while (!(step = iterator.next()).done) {
|
6364 | iterations++;
|
6365 | if (fn(step.value[1], step.value[0], this) === false) {
|
6366 | break;
|
6367 | }
|
6368 | }
|
6369 | return iterations;
|
6370 | */
|
6371 | // indexed:
|
6372 | var iterator = this.__iterator(ITERATE_VALUES, reverse);
|
6373 | var step;
|
6374 | var iterations = 0;
|
6375 | while (!(step = iterator.next()).done) {
|
6376 | if (fn(step.value, iterations++, this) === false) {
|
6377 | break;
|
6378 | }
|
6379 | }
|
6380 | return iterations;
|
6381 | };
|
6382 | zipSequence.__iteratorUncached = function(type, reverse) {
|
6383 | var iterators = iters.map(
|
6384 | function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }
|
6385 | );
|
6386 | var iterations = 0;
|
6387 | var isDone = false;
|
6388 | return new Iterator(function () {
|
6389 | var steps;
|
6390 | if (!isDone) {
|
6391 | steps = iterators.map(function (i) { return i.next(); });
|
6392 | isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; });
|
6393 | }
|
6394 | if (isDone) {
|
6395 | return iteratorDone();
|
6396 | }
|
6397 | return iteratorValue(
|
6398 | type,
|
6399 | iterations++,
|
6400 | zipper.apply(null, steps.map(function (s) { return s.value; }))
|
6401 | );
|
6402 | });
|
6403 | };
|
6404 | return zipSequence;
|
6405 | }
|
6406 |
|
6407 | // #pragma Helper Functions
|
6408 |
|
6409 | function reify(iter, seq) {
|
6410 | return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
|
6411 | }
|
6412 |
|
6413 | function validateEntry(entry) {
|
6414 | if (entry !== Object(entry)) {
|
6415 | throw new TypeError('Expected [K, V] tuple: ' + entry);
|
6416 | }
|
6417 | }
|
6418 |
|
6419 | function collectionClass(collection) {
|
6420 | return isKeyed(collection)
|
6421 | ? KeyedCollection
|
6422 | : isIndexed(collection)
|
6423 | ? IndexedCollection
|
6424 | : SetCollection;
|
6425 | }
|
6426 |
|
6427 | function makeSequence(collection) {
|
6428 | return Object.create(
|
6429 | (isKeyed(collection)
|
6430 | ? KeyedSeq
|
6431 | : isIndexed(collection)
|
6432 | ? IndexedSeq
|
6433 | : SetSeq
|
6434 | ).prototype
|
6435 | );
|
6436 | }
|
6437 |
|
6438 | function cacheResultThrough() {
|
6439 | if (this._iter.cacheResult) {
|
6440 | this._iter.cacheResult();
|
6441 | this.size = this._iter.size;
|
6442 | return this;
|
6443 | }
|
6444 | return Seq.prototype.cacheResult.call(this);
|
6445 | }
|
6446 |
|
6447 | function defaultComparator(a, b) {
|
6448 | if (a === undefined && b === undefined) {
|
6449 | return 0;
|
6450 | }
|
6451 |
|
6452 | if (a === undefined) {
|
6453 | return 1;
|
6454 | }
|
6455 |
|
6456 | if (b === undefined) {
|
6457 | return -1;
|
6458 | }
|
6459 |
|
6460 | return a > b ? 1 : a < b ? -1 : 0;
|
6461 | }
|
6462 |
|
6463 | // http://jsperf.com/copy-array-inline
|
6464 | function arrCopy(arr, offset) {
|
6465 | offset = offset || 0;
|
6466 | var len = Math.max(0, arr.length - offset);
|
6467 | var newArr = new Array(len);
|
6468 | for (var ii = 0; ii < len; ii++) {
|
6469 | newArr[ii] = arr[ii + offset];
|
6470 | }
|
6471 | return newArr;
|
6472 | }
|
6473 |
|
6474 | function invariant(condition, error) {
|
6475 | if (!condition) { throw new Error(error); }
|
6476 | }
|
6477 |
|
6478 | function assertNotInfinite(size) {
|
6479 | invariant(
|
6480 | size !== Infinity,
|
6481 | 'Cannot perform this action with an infinite size.'
|
6482 | );
|
6483 | }
|
6484 |
|
6485 | function coerceKeyPath(keyPath) {
|
6486 | if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
|
6487 | return keyPath;
|
6488 | }
|
6489 | if (isOrdered(keyPath)) {
|
6490 | return keyPath.toArray();
|
6491 | }
|
6492 | throw new TypeError(
|
6493 | 'Invalid keyPath: expected Ordered Collection or Array: ' + keyPath
|
6494 | );
|
6495 | }
|
6496 |
|
6497 | function isPlainObj(value) {
|
6498 | return (
|
6499 | value &&
|
6500 | (typeof value.constructor !== 'function' ||
|
6501 | value.constructor.name === 'Object')
|
6502 | );
|
6503 | }
|
6504 |
|
6505 | /**
|
6506 | * Returns true if the value is a potentially-persistent data structure, either
|
6507 | * provided by Immutable.js or a plain Array or Object.
|
6508 | */
|
6509 | function isDataStructure(value) {
|
6510 | return (
|
6511 | typeof value === 'object' &&
|
6512 | (isImmutable(value) || Array.isArray(value) || isPlainObj(value))
|
6513 | );
|
6514 | }
|
6515 |
|
6516 | /**
|
6517 | * Converts a value to a string, adding quotes if a string was provided.
|
6518 | */
|
6519 | function quoteString(value) {
|
6520 | try {
|
6521 | return typeof value === 'string' ? JSON.stringify(value) : String(value);
|
6522 | } catch (_ignoreError) {
|
6523 | return JSON.stringify(value);
|
6524 | }
|
6525 | }
|
6526 |
|
6527 | function has(collection, key) {
|
6528 | return isImmutable(collection)
|
6529 | ? collection.has(key)
|
6530 | : isDataStructure(collection) && hasOwnProperty.call(collection, key);
|
6531 | }
|
6532 |
|
6533 | function get(collection, key, notSetValue) {
|
6534 | return isImmutable(collection)
|
6535 | ? collection.get(key, notSetValue)
|
6536 | : !has(collection, key)
|
6537 | ? notSetValue
|
6538 | : typeof collection.get === 'function'
|
6539 | ? collection.get(key)
|
6540 | : collection[key];
|
6541 | }
|
6542 |
|
6543 | function shallowCopy(from) {
|
6544 | if (Array.isArray(from)) {
|
6545 | return arrCopy(from);
|
6546 | }
|
6547 | var to = {};
|
6548 | for (var key in from) {
|
6549 | if (hasOwnProperty.call(from, key)) {
|
6550 | to[key] = from[key];
|
6551 | }
|
6552 | }
|
6553 | return to;
|
6554 | }
|
6555 |
|
6556 | function remove(collection, key) {
|
6557 | if (!isDataStructure(collection)) {
|
6558 | throw new TypeError(
|
6559 | 'Cannot update non-data-structure value: ' + collection
|
6560 | );
|
6561 | }
|
6562 | if (isImmutable(collection)) {
|
6563 | if (!collection.remove) {
|
6564 | throw new TypeError(
|
6565 | 'Cannot update immutable value without .remove() method: ' + collection
|
6566 | );
|
6567 | }
|
6568 | return collection.remove(key);
|
6569 | }
|
6570 | if (!hasOwnProperty.call(collection, key)) {
|
6571 | return collection;
|
6572 | }
|
6573 | var collectionCopy = shallowCopy(collection);
|
6574 | if (Array.isArray(collectionCopy)) {
|
6575 | collectionCopy.splice(key, 1);
|
6576 | } else {
|
6577 | delete collectionCopy[key];
|
6578 | }
|
6579 | return collectionCopy;
|
6580 | }
|
6581 |
|
6582 | function set(collection, key, value) {
|
6583 | if (!isDataStructure(collection)) {
|
6584 | throw new TypeError(
|
6585 | 'Cannot update non-data-structure value: ' + collection
|
6586 | );
|
6587 | }
|
6588 | if (isImmutable(collection)) {
|
6589 | if (!collection.set) {
|
6590 | throw new TypeError(
|
6591 | 'Cannot update immutable value without .set() method: ' + collection
|
6592 | );
|
6593 | }
|
6594 | return collection.set(key, value);
|
6595 | }
|
6596 | if (hasOwnProperty.call(collection, key) && value === collection[key]) {
|
6597 | return collection;
|
6598 | }
|
6599 | var collectionCopy = shallowCopy(collection);
|
6600 | collectionCopy[key] = value;
|
6601 | return collectionCopy;
|
6602 | }
|
6603 |
|
6604 | function updateIn(collection, keyPath, notSetValue, updater) {
|
6605 | if (!updater) {
|
6606 | updater = notSetValue;
|
6607 | notSetValue = undefined;
|
6608 | }
|
6609 | var updatedValue = updateInDeeply(
|
6610 | isImmutable(collection),
|
6611 | collection,
|
6612 | coerceKeyPath(keyPath),
|
6613 | 0,
|
6614 | notSetValue,
|
6615 | updater
|
6616 | );
|
6617 | return updatedValue === NOT_SET ? notSetValue : updatedValue;
|
6618 | }
|
6619 |
|
6620 | function updateInDeeply(
|
6621 | inImmutable,
|
6622 | existing,
|
6623 | keyPath,
|
6624 | i,
|
6625 | notSetValue,
|
6626 | updater
|
6627 | ) {
|
6628 | var wasNotSet = existing === NOT_SET;
|
6629 | if (i === keyPath.length) {
|
6630 | var existingValue = wasNotSet ? notSetValue : existing;
|
6631 | var newValue = updater(existingValue);
|
6632 | return newValue === existingValue ? existing : newValue;
|
6633 | }
|
6634 | if (!wasNotSet && !isDataStructure(existing)) {
|
6635 | throw new TypeError(
|
6636 | 'Cannot update within non-data-structure value in path [' +
|
6637 | keyPath.slice(0, i).map(quoteString) +
|
6638 | ']: ' +
|
6639 | existing
|
6640 | );
|
6641 | }
|
6642 | var key = keyPath[i];
|
6643 | var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
|
6644 | var nextUpdated = updateInDeeply(
|
6645 | nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting),
|
6646 | nextExisting,
|
6647 | keyPath,
|
6648 | i + 1,
|
6649 | notSetValue,
|
6650 | updater
|
6651 | );
|
6652 | return nextUpdated === nextExisting
|
6653 | ? existing
|
6654 | : nextUpdated === NOT_SET
|
6655 | ? remove(existing, key)
|
6656 | : set(
|
6657 | wasNotSet ? (inImmutable ? emptyMap() : {}) : existing,
|
6658 | key,
|
6659 | nextUpdated
|
6660 | );
|
6661 | }
|
6662 |
|
6663 | function setIn(collection, keyPath, value) {
|
6664 | return updateIn(collection, keyPath, NOT_SET, function () { return value; });
|
6665 | }
|
6666 |
|
6667 | function setIn$1(keyPath, v) {
|
6668 | return setIn(this, keyPath, v);
|
6669 | }
|
6670 |
|
6671 | function removeIn(collection, keyPath) {
|
6672 | return updateIn(collection, keyPath, function () { return NOT_SET; });
|
6673 | }
|
6674 |
|
6675 | function deleteIn(keyPath) {
|
6676 | return removeIn(this, keyPath);
|
6677 | }
|
6678 |
|
6679 | function update(collection, key, notSetValue, updater) {
|
6680 | return updateIn(collection, [key], notSetValue, updater);
|
6681 | }
|
6682 |
|
6683 | function update$1(key, notSetValue, updater) {
|
6684 | return arguments.length === 1
|
6685 | ? key(this)
|
6686 | : update(this, key, notSetValue, updater);
|
6687 | }
|
6688 |
|
6689 | function updateIn$1(keyPath, notSetValue, updater) {
|
6690 | return updateIn(this, keyPath, notSetValue, updater);
|
6691 | }
|
6692 |
|
6693 | function merge() {
|
6694 | var iters = [], len = arguments.length;
|
6695 | while ( len-- ) iters[ len ] = arguments[ len ];
|
6696 |
|
6697 | return mergeIntoKeyedWith(this, iters);
|
6698 | }
|
6699 |
|
6700 | function mergeWith(merger) {
|
6701 | var iters = [], len = arguments.length - 1;
|
6702 | while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
|
6703 |
|
6704 | if (typeof merger !== 'function') {
|
6705 | throw new TypeError('Invalid merger function: ' + merger);
|
6706 | }
|
6707 | return mergeIntoKeyedWith(this, iters, merger);
|
6708 | }
|
6709 |
|
6710 | function mergeIntoKeyedWith(collection, collections, merger) {
|
6711 | var iters = [];
|
6712 | for (var ii = 0; ii < collections.length; ii++) {
|
6713 | var collection$1 = KeyedCollection(collections[ii]);
|
6714 | if (collection$1.size !== 0) {
|
6715 | iters.push(collection$1);
|
6716 | }
|
6717 | }
|
6718 | if (iters.length === 0) {
|
6719 | return collection;
|
6720 | }
|
6721 | if (
|
6722 | collection.toSeq().size === 0 &&
|
6723 | !collection.__ownerID &&
|
6724 | iters.length === 1
|
6725 | ) {
|
6726 | return collection.constructor(iters[0]);
|
6727 | }
|
6728 | return collection.withMutations(function (collection) {
|
6729 | var mergeIntoCollection = merger
|
6730 | ? function (value, key) {
|
6731 | update(
|
6732 | collection,
|
6733 | key,
|
6734 | NOT_SET,
|
6735 | function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); }
|
6736 | );
|
6737 | }
|
6738 | : function (value, key) {
|
6739 | collection.set(key, value);
|
6740 | };
|
6741 | for (var ii = 0; ii < iters.length; ii++) {
|
6742 | iters[ii].forEach(mergeIntoCollection);
|
6743 | }
|
6744 | });
|
6745 | }
|
6746 |
|
6747 | function merge$1(collection) {
|
6748 | var sources = [], len = arguments.length - 1;
|
6749 | while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
|
6750 |
|
6751 | return mergeWithSources(collection, sources);
|
6752 | }
|
6753 |
|
6754 | function mergeWith$1(merger, collection) {
|
6755 | var sources = [], len = arguments.length - 2;
|
6756 | while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
|
6757 |
|
6758 | return mergeWithSources(collection, sources, merger);
|
6759 | }
|
6760 |
|
6761 | function mergeDeep(collection) {
|
6762 | var sources = [], len = arguments.length - 1;
|
6763 | while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
|
6764 |
|
6765 | return mergeDeepWithSources(collection, sources);
|
6766 | }
|
6767 |
|
6768 | function mergeDeepWith(merger, collection) {
|
6769 | var sources = [], len = arguments.length - 2;
|
6770 | while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
|
6771 |
|
6772 | return mergeDeepWithSources(collection, sources, merger);
|
6773 | }
|
6774 |
|
6775 | function mergeDeepWithSources(collection, sources, merger) {
|
6776 | return mergeWithSources(collection, sources, deepMergerWith(merger));
|
6777 | }
|
6778 |
|
6779 | function mergeWithSources(collection, sources, merger) {
|
6780 | if (!isDataStructure(collection)) {
|
6781 | throw new TypeError(
|
6782 | 'Cannot merge into non-data-structure value: ' + collection
|
6783 | );
|
6784 | }
|
6785 | if (isImmutable(collection)) {
|
6786 | return typeof merger === 'function' && collection.mergeWith
|
6787 | ? collection.mergeWith.apply(collection, [ merger ].concat( sources ))
|
6788 | : collection.merge
|
6789 | ? collection.merge.apply(collection, sources)
|
6790 | : collection.concat.apply(collection, sources);
|
6791 | }
|
6792 | var isArray = Array.isArray(collection);
|
6793 | var merged = collection;
|
6794 | var Collection$$1 = isArray ? IndexedCollection : KeyedCollection;
|
6795 | var mergeItem = isArray
|
6796 | ? function (value) {
|
6797 | // Copy on write
|
6798 | if (merged === collection) {
|
6799 | merged = shallowCopy(merged);
|
6800 | }
|
6801 | merged.push(value);
|
6802 | }
|
6803 | : function (value, key) {
|
6804 | var hasVal = hasOwnProperty.call(merged, key);
|
6805 | var nextVal =
|
6806 | hasVal && merger ? merger(merged[key], value, key) : value;
|
6807 | if (!hasVal || nextVal !== merged[key]) {
|
6808 | // Copy on write
|
6809 | if (merged === collection) {
|
6810 | merged = shallowCopy(merged);
|
6811 | }
|
6812 | merged[key] = nextVal;
|
6813 | }
|
6814 | };
|
6815 | for (var i = 0; i < sources.length; i++) {
|
6816 | Collection$$1(sources[i]).forEach(mergeItem);
|
6817 | }
|
6818 | return merged;
|
6819 | }
|
6820 |
|
6821 | function deepMergerWith(merger) {
|
6822 | function deepMerger(oldValue, newValue, key) {
|
6823 | return isDataStructure(oldValue) && isDataStructure(newValue)
|
6824 | ? mergeWithSources(oldValue, [newValue], deepMerger)
|
6825 | : merger
|
6826 | ? merger(oldValue, newValue, key)
|
6827 | : newValue;
|
6828 | }
|
6829 | return deepMerger;
|
6830 | }
|
6831 |
|
6832 | function mergeDeep$1() {
|
6833 | var iters = [], len = arguments.length;
|
6834 | while ( len-- ) iters[ len ] = arguments[ len ];
|
6835 |
|
6836 | return mergeDeepWithSources(this, iters);
|
6837 | }
|
6838 |
|
6839 | function mergeDeepWith$1(merger) {
|
6840 | var iters = [], len = arguments.length - 1;
|
6841 | while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
|
6842 |
|
6843 | return mergeDeepWithSources(this, iters, merger);
|
6844 | }
|
6845 |
|
6846 | function mergeIn(keyPath) {
|
6847 | var iters = [], len = arguments.length - 1;
|
6848 | while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
|
6849 |
|
6850 | return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
|
6851 | }
|
6852 |
|
6853 | function mergeDeepIn(keyPath) {
|
6854 | var iters = [], len = arguments.length - 1;
|
6855 | while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
|
6856 |
|
6857 | return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }
|
6858 | );
|
6859 | }
|
6860 |
|
6861 | function withMutations(fn) {
|
6862 | var mutable = this.asMutable();
|
6863 | fn(mutable);
|
6864 | return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
|
6865 | }
|
6866 |
|
6867 | function asMutable() {
|
6868 | return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
|
6869 | }
|
6870 |
|
6871 | function asImmutable() {
|
6872 | return this.__ensureOwner();
|
6873 | }
|
6874 |
|
6875 | function wasAltered() {
|
6876 | return this.__altered;
|
6877 | }
|
6878 |
|
6879 | var Map$1 = /*@__PURE__*/(function (KeyedCollection$$1) {
|
6880 | function Map(value) {
|
6881 | return value === null || value === undefined
|
6882 | ? emptyMap()
|
6883 | : isMap(value) && !isOrdered(value)
|
6884 | ? value
|
6885 | : emptyMap().withMutations(function (map) {
|
6886 | var iter = KeyedCollection$$1(value);
|
6887 | assertNotInfinite(iter.size);
|
6888 | iter.forEach(function (v, k) { return map.set(k, v); });
|
6889 | });
|
6890 | }
|
6891 |
|
6892 | if ( KeyedCollection$$1 ) Map.__proto__ = KeyedCollection$$1;
|
6893 | Map.prototype = Object.create( KeyedCollection$$1 && KeyedCollection$$1.prototype );
|
6894 | Map.prototype.constructor = Map;
|
6895 |
|
6896 | Map.of = function of () {
|
6897 | var keyValues = [], len = arguments.length;
|
6898 | while ( len-- ) keyValues[ len ] = arguments[ len ];
|
6899 |
|
6900 | return emptyMap().withMutations(function (map) {
|
6901 | for (var i = 0; i < keyValues.length; i += 2) {
|
6902 | if (i + 1 >= keyValues.length) {
|
6903 | throw new Error('Missing value for key: ' + keyValues[i]);
|
6904 | }
|
6905 | map.set(keyValues[i], keyValues[i + 1]);
|
6906 | }
|
6907 | });
|
6908 | };
|
6909 |
|
6910 | Map.prototype.toString = function toString () {
|
6911 | return this.__toString('Map {', '}');
|
6912 | };
|
6913 |
|
6914 | // @pragma Access
|
6915 |
|
6916 | Map.prototype.get = function get (k, notSetValue) {
|
6917 | return this._root
|
6918 | ? this._root.get(0, undefined, k, notSetValue)
|
6919 | : notSetValue;
|
6920 | };
|
6921 |
|
6922 | // @pragma Modification
|
6923 |
|
6924 | Map.prototype.set = function set (k, v) {
|
6925 | return updateMap(this, k, v);
|
6926 | };
|
6927 |
|
6928 | Map.prototype.remove = function remove (k) {
|
6929 | return updateMap(this, k, NOT_SET);
|
6930 | };
|
6931 |
|
6932 | Map.prototype.deleteAll = function deleteAll (keys) {
|
6933 | var collection = Collection(keys);
|
6934 |
|
6935 | if (collection.size === 0) {
|
6936 | return this;
|
6937 | }
|
6938 |
|
6939 | return this.withMutations(function (map) {
|
6940 | collection.forEach(function (key) { return map.remove(key); });
|
6941 | });
|
6942 | };
|
6943 |
|
6944 | Map.prototype.clear = function clear () {
|
6945 | if (this.size === 0) {
|
6946 | return this;
|
6947 | }
|
6948 | if (this.__ownerID) {
|
6949 | this.size = 0;
|
6950 | this._root = null;
|
6951 | this.__hash = undefined;
|
6952 | this.__altered = true;
|
6953 | return this;
|
6954 | }
|
6955 | return emptyMap();
|
6956 | };
|
6957 |
|
6958 | // @pragma Composition
|
6959 |
|
6960 | Map.prototype.sort = function sort (comparator) {
|
6961 | // Late binding
|
6962 | return OrderedMap(sortFactory(this, comparator));
|
6963 | };
|
6964 |
|
6965 | Map.prototype.sortBy = function sortBy (mapper, comparator) {
|
6966 | // Late binding
|
6967 | return OrderedMap(sortFactory(this, comparator, mapper));
|
6968 | };
|
6969 |
|
6970 | Map.prototype.map = function map (mapper, context) {
|
6971 | return this.withMutations(function (map) {
|
6972 | map.forEach(function (value, key) {
|
6973 | map.set(key, mapper.call(context, value, key, map));
|
6974 | });
|
6975 | });
|
6976 | };
|
6977 |
|
6978 | // @pragma Mutability
|
6979 |
|
6980 | Map.prototype.__iterator = function __iterator (type, reverse) {
|
6981 | return new MapIterator(this, type, reverse);
|
6982 | };
|
6983 |
|
6984 | Map.prototype.__iterate = function __iterate (fn, reverse) {
|
6985 | var this$1 = this;
|
6986 |
|
6987 | var iterations = 0;
|
6988 | this._root &&
|
6989 | this._root.iterate(function (entry) {
|
6990 | iterations++;
|
6991 | return fn(entry[1], entry[0], this$1);
|
6992 | }, reverse);
|
6993 | return iterations;
|
6994 | };
|
6995 |
|
6996 | Map.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
6997 | if (ownerID === this.__ownerID) {
|
6998 | return this;
|
6999 | }
|
7000 | if (!ownerID) {
|
7001 | if (this.size === 0) {
|
7002 | return emptyMap();
|
7003 | }
|
7004 | this.__ownerID = ownerID;
|
7005 | this.__altered = false;
|
7006 | return this;
|
7007 | }
|
7008 | return makeMap(this.size, this._root, ownerID, this.__hash);
|
7009 | };
|
7010 |
|
7011 | return Map;
|
7012 | }(KeyedCollection));
|
7013 |
|
7014 | Map$1.isMap = isMap;
|
7015 |
|
7016 | var MapPrototype = Map$1.prototype;
|
7017 | MapPrototype[IS_MAP_SYMBOL] = true;
|
7018 | MapPrototype[DELETE] = MapPrototype.remove;
|
7019 | MapPrototype.removeAll = MapPrototype.deleteAll;
|
7020 | MapPrototype.setIn = setIn$1;
|
7021 | MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
|
7022 | MapPrototype.update = update$1;
|
7023 | MapPrototype.updateIn = updateIn$1;
|
7024 | MapPrototype.merge = MapPrototype.concat = merge;
|
7025 | MapPrototype.mergeWith = mergeWith;
|
7026 | MapPrototype.mergeDeep = mergeDeep$1;
|
7027 | MapPrototype.mergeDeepWith = mergeDeepWith$1;
|
7028 | MapPrototype.mergeIn = mergeIn;
|
7029 | MapPrototype.mergeDeepIn = mergeDeepIn;
|
7030 | MapPrototype.withMutations = withMutations;
|
7031 | MapPrototype.wasAltered = wasAltered;
|
7032 | MapPrototype.asImmutable = asImmutable;
|
7033 | MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
|
7034 | MapPrototype['@@transducer/step'] = function(result, arr) {
|
7035 | return result.set(arr[0], arr[1]);
|
7036 | };
|
7037 | MapPrototype['@@transducer/result'] = function(obj) {
|
7038 | return obj.asImmutable();
|
7039 | };
|
7040 |
|
7041 | // #pragma Trie Nodes
|
7042 |
|
7043 | var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
|
7044 | this.ownerID = ownerID;
|
7045 | this.entries = entries;
|
7046 | };
|
7047 |
|
7048 | ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
|
7049 | var entries = this.entries;
|
7050 | for (var ii = 0, len = entries.length; ii < len; ii++) {
|
7051 | if (is(key, entries[ii][0])) {
|
7052 | return entries[ii][1];
|
7053 | }
|
7054 | }
|
7055 | return notSetValue;
|
7056 | };
|
7057 |
|
7058 | ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
|
7059 | var removed = value === NOT_SET;
|
7060 |
|
7061 | var entries = this.entries;
|
7062 | var idx = 0;
|
7063 | var len = entries.length;
|
7064 | for (; idx < len; idx++) {
|
7065 | if (is(key, entries[idx][0])) {
|
7066 | break;
|
7067 | }
|
7068 | }
|
7069 | var exists = idx < len;
|
7070 |
|
7071 | if (exists ? entries[idx][1] === value : removed) {
|
7072 | return this;
|
7073 | }
|
7074 |
|
7075 | SetRef(didAlter);
|
7076 | (removed || !exists) && SetRef(didChangeSize);
|
7077 |
|
7078 | if (removed && entries.length === 1) {
|
7079 | return; // undefined
|
7080 | }
|
7081 |
|
7082 | if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
|
7083 | return createNodes(ownerID, entries, key, value);
|
7084 | }
|
7085 |
|
7086 | var isEditable = ownerID && ownerID === this.ownerID;
|
7087 | var newEntries = isEditable ? entries : arrCopy(entries);
|
7088 |
|
7089 | if (exists) {
|
7090 | if (removed) {
|
7091 | idx === len - 1
|
7092 | ? newEntries.pop()
|
7093 | : (newEntries[idx] = newEntries.pop());
|
7094 | } else {
|
7095 | newEntries[idx] = [key, value];
|
7096 | }
|
7097 | } else {
|
7098 | newEntries.push([key, value]);
|
7099 | }
|
7100 |
|
7101 | if (isEditable) {
|
7102 | this.entries = newEntries;
|
7103 | return this;
|
7104 | }
|
7105 |
|
7106 | return new ArrayMapNode(ownerID, newEntries);
|
7107 | };
|
7108 |
|
7109 | var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
|
7110 | this.ownerID = ownerID;
|
7111 | this.bitmap = bitmap;
|
7112 | this.nodes = nodes;
|
7113 | };
|
7114 |
|
7115 | BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
|
7116 | if (keyHash === undefined) {
|
7117 | keyHash = hash(key);
|
7118 | }
|
7119 | var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
|
7120 | var bitmap = this.bitmap;
|
7121 | return (bitmap & bit) === 0
|
7122 | ? notSetValue
|
7123 | : this.nodes[popCount(bitmap & (bit - 1))].get(
|
7124 | shift + SHIFT,
|
7125 | keyHash,
|
7126 | key,
|
7127 | notSetValue
|
7128 | );
|
7129 | };
|
7130 |
|
7131 | BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
|
7132 | if (keyHash === undefined) {
|
7133 | keyHash = hash(key);
|
7134 | }
|
7135 | var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
|
7136 | var bit = 1 << keyHashFrag;
|
7137 | var bitmap = this.bitmap;
|
7138 | var exists = (bitmap & bit) !== 0;
|
7139 |
|
7140 | if (!exists && value === NOT_SET) {
|
7141 | return this;
|
7142 | }
|
7143 |
|
7144 | var idx = popCount(bitmap & (bit - 1));
|
7145 | var nodes = this.nodes;
|
7146 | var node = exists ? nodes[idx] : undefined;
|
7147 | var newNode = updateNode(
|
7148 | node,
|
7149 | ownerID,
|
7150 | shift + SHIFT,
|
7151 | keyHash,
|
7152 | key,
|
7153 | value,
|
7154 | didChangeSize,
|
7155 | didAlter
|
7156 | );
|
7157 |
|
7158 | if (newNode === node) {
|
7159 | return this;
|
7160 | }
|
7161 |
|
7162 | if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
|
7163 | return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
|
7164 | }
|
7165 |
|
7166 | if (
|
7167 | exists &&
|
7168 | !newNode &&
|
7169 | nodes.length === 2 &&
|
7170 | isLeafNode(nodes[idx ^ 1])
|
7171 | ) {
|
7172 | return nodes[idx ^ 1];
|
7173 | }
|
7174 |
|
7175 | if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
|
7176 | return newNode;
|
7177 | }
|
7178 |
|
7179 | var isEditable = ownerID && ownerID === this.ownerID;
|
7180 | var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
|
7181 | var newNodes = exists
|
7182 | ? newNode
|
7183 | ? setAt(nodes, idx, newNode, isEditable)
|
7184 | : spliceOut(nodes, idx, isEditable)
|
7185 | : spliceIn(nodes, idx, newNode, isEditable);
|
7186 |
|
7187 | if (isEditable) {
|
7188 | this.bitmap = newBitmap;
|
7189 | this.nodes = newNodes;
|
7190 | return this;
|
7191 | }
|
7192 |
|
7193 | return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
|
7194 | };
|
7195 |
|
7196 | var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
|
7197 | this.ownerID = ownerID;
|
7198 | this.count = count;
|
7199 | this.nodes = nodes;
|
7200 | };
|
7201 |
|
7202 | HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
|
7203 | if (keyHash === undefined) {
|
7204 | keyHash = hash(key);
|
7205 | }
|
7206 | var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
|
7207 | var node = this.nodes[idx];
|
7208 | return node
|
7209 | ? node.get(shift + SHIFT, keyHash, key, notSetValue)
|
7210 | : notSetValue;
|
7211 | };
|
7212 |
|
7213 | HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
|
7214 | if (keyHash === undefined) {
|
7215 | keyHash = hash(key);
|
7216 | }
|
7217 | var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
|
7218 | var removed = value === NOT_SET;
|
7219 | var nodes = this.nodes;
|
7220 | var node = nodes[idx];
|
7221 |
|
7222 | if (removed && !node) {
|
7223 | return this;
|
7224 | }
|
7225 |
|
7226 | var newNode = updateNode(
|
7227 | node,
|
7228 | ownerID,
|
7229 | shift + SHIFT,
|
7230 | keyHash,
|
7231 | key,
|
7232 | value,
|
7233 | didChangeSize,
|
7234 | didAlter
|
7235 | );
|
7236 | if (newNode === node) {
|
7237 | return this;
|
7238 | }
|
7239 |
|
7240 | var newCount = this.count;
|
7241 | if (!node) {
|
7242 | newCount++;
|
7243 | } else if (!newNode) {
|
7244 | newCount--;
|
7245 | if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
|
7246 | return packNodes(ownerID, nodes, newCount, idx);
|
7247 | }
|
7248 | }
|
7249 |
|
7250 | var isEditable = ownerID && ownerID === this.ownerID;
|
7251 | var newNodes = setAt(nodes, idx, newNode, isEditable);
|
7252 |
|
7253 | if (isEditable) {
|
7254 | this.count = newCount;
|
7255 | this.nodes = newNodes;
|
7256 | return this;
|
7257 | }
|
7258 |
|
7259 | return new HashArrayMapNode(ownerID, newCount, newNodes);
|
7260 | };
|
7261 |
|
7262 | var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
|
7263 | this.ownerID = ownerID;
|
7264 | this.keyHash = keyHash;
|
7265 | this.entries = entries;
|
7266 | };
|
7267 |
|
7268 | HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
|
7269 | var entries = this.entries;
|
7270 | for (var ii = 0, len = entries.length; ii < len; ii++) {
|
7271 | if (is(key, entries[ii][0])) {
|
7272 | return entries[ii][1];
|
7273 | }
|
7274 | }
|
7275 | return notSetValue;
|
7276 | };
|
7277 |
|
7278 | HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
|
7279 | if (keyHash === undefined) {
|
7280 | keyHash = hash(key);
|
7281 | }
|
7282 |
|
7283 | var removed = value === NOT_SET;
|
7284 |
|
7285 | if (keyHash !== this.keyHash) {
|
7286 | if (removed) {
|
7287 | return this;
|
7288 | }
|
7289 | SetRef(didAlter);
|
7290 | SetRef(didChangeSize);
|
7291 | return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
|
7292 | }
|
7293 |
|
7294 | var entries = this.entries;
|
7295 | var idx = 0;
|
7296 | var len = entries.length;
|
7297 | for (; idx < len; idx++) {
|
7298 | if (is(key, entries[idx][0])) {
|
7299 | break;
|
7300 | }
|
7301 | }
|
7302 | var exists = idx < len;
|
7303 |
|
7304 | if (exists ? entries[idx][1] === value : removed) {
|
7305 | return this;
|
7306 | }
|
7307 |
|
7308 | SetRef(didAlter);
|
7309 | (removed || !exists) && SetRef(didChangeSize);
|
7310 |
|
7311 | if (removed && len === 2) {
|
7312 | return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
|
7313 | }
|
7314 |
|
7315 | var isEditable = ownerID && ownerID === this.ownerID;
|
7316 | var newEntries = isEditable ? entries : arrCopy(entries);
|
7317 |
|
7318 | if (exists) {
|
7319 | if (removed) {
|
7320 | idx === len - 1
|
7321 | ? newEntries.pop()
|
7322 | : (newEntries[idx] = newEntries.pop());
|
7323 | } else {
|
7324 | newEntries[idx] = [key, value];
|
7325 | }
|
7326 | } else {
|
7327 | newEntries.push([key, value]);
|
7328 | }
|
7329 |
|
7330 | if (isEditable) {
|
7331 | this.entries = newEntries;
|
7332 | return this;
|
7333 | }
|
7334 |
|
7335 | return new HashCollisionNode(ownerID, this.keyHash, newEntries);
|
7336 | };
|
7337 |
|
7338 | var ValueNode = function ValueNode(ownerID, keyHash, entry) {
|
7339 | this.ownerID = ownerID;
|
7340 | this.keyHash = keyHash;
|
7341 | this.entry = entry;
|
7342 | };
|
7343 |
|
7344 | ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
|
7345 | return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
|
7346 | };
|
7347 |
|
7348 | ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
|
7349 | var removed = value === NOT_SET;
|
7350 | var keyMatch = is(key, this.entry[0]);
|
7351 | if (keyMatch ? value === this.entry[1] : removed) {
|
7352 | return this;
|
7353 | }
|
7354 |
|
7355 | SetRef(didAlter);
|
7356 |
|
7357 | if (removed) {
|
7358 | SetRef(didChangeSize);
|
7359 | return; // undefined
|
7360 | }
|
7361 |
|
7362 | if (keyMatch) {
|
7363 | if (ownerID && ownerID === this.ownerID) {
|
7364 | this.entry[1] = value;
|
7365 | return this;
|
7366 | }
|
7367 | return new ValueNode(ownerID, this.keyHash, [key, value]);
|
7368 | }
|
7369 |
|
7370 | SetRef(didChangeSize);
|
7371 | return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
|
7372 | };
|
7373 |
|
7374 | // #pragma Iterators
|
7375 |
|
7376 | ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function(
|
7377 | fn,
|
7378 | reverse
|
7379 | ) {
|
7380 | var entries = this.entries;
|
7381 | for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
|
7382 | if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
|
7383 | return false;
|
7384 | }
|
7385 | }
|
7386 | };
|
7387 |
|
7388 | BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function(
|
7389 | fn,
|
7390 | reverse
|
7391 | ) {
|
7392 | var nodes = this.nodes;
|
7393 | for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
|
7394 | var node = nodes[reverse ? maxIndex - ii : ii];
|
7395 | if (node && node.iterate(fn, reverse) === false) {
|
7396 | return false;
|
7397 | }
|
7398 | }
|
7399 | };
|
7400 |
|
7401 | // eslint-disable-next-line no-unused-vars
|
7402 | ValueNode.prototype.iterate = function(fn, reverse) {
|
7403 | return fn(this.entry);
|
7404 | };
|
7405 |
|
7406 | var MapIterator = /*@__PURE__*/(function (Iterator$$1) {
|
7407 | function MapIterator(map, type, reverse) {
|
7408 | this._type = type;
|
7409 | this._reverse = reverse;
|
7410 | this._stack = map._root && mapIteratorFrame(map._root);
|
7411 | }
|
7412 |
|
7413 | if ( Iterator$$1 ) MapIterator.__proto__ = Iterator$$1;
|
7414 | MapIterator.prototype = Object.create( Iterator$$1 && Iterator$$1.prototype );
|
7415 | MapIterator.prototype.constructor = MapIterator;
|
7416 |
|
7417 | MapIterator.prototype.next = function next () {
|
7418 | var type = this._type;
|
7419 | var stack = this._stack;
|
7420 | while (stack) {
|
7421 | var node = stack.node;
|
7422 | var index = stack.index++;
|
7423 | var maxIndex = (void 0);
|
7424 | if (node.entry) {
|
7425 | if (index === 0) {
|
7426 | return mapIteratorValue(type, node.entry);
|
7427 | }
|
7428 | } else if (node.entries) {
|
7429 | maxIndex = node.entries.length - 1;
|
7430 | if (index <= maxIndex) {
|
7431 | return mapIteratorValue(
|
7432 | type,
|
7433 | node.entries[this._reverse ? maxIndex - index : index]
|
7434 | );
|
7435 | }
|
7436 | } else {
|
7437 | maxIndex = node.nodes.length - 1;
|
7438 | if (index <= maxIndex) {
|
7439 | var subNode = node.nodes[this._reverse ? maxIndex - index : index];
|
7440 | if (subNode) {
|
7441 | if (subNode.entry) {
|
7442 | return mapIteratorValue(type, subNode.entry);
|
7443 | }
|
7444 | stack = this._stack = mapIteratorFrame(subNode, stack);
|
7445 | }
|
7446 | continue;
|
7447 | }
|
7448 | }
|
7449 | stack = this._stack = this._stack.__prev;
|
7450 | }
|
7451 | return iteratorDone();
|
7452 | };
|
7453 |
|
7454 | return MapIterator;
|
7455 | }(Iterator));
|
7456 |
|
7457 | function mapIteratorValue(type, entry) {
|
7458 | return iteratorValue(type, entry[0], entry[1]);
|
7459 | }
|
7460 |
|
7461 | function mapIteratorFrame(node, prev) {
|
7462 | return {
|
7463 | node: node,
|
7464 | index: 0,
|
7465 | __prev: prev,
|
7466 | };
|
7467 | }
|
7468 |
|
7469 | function makeMap(size, root, ownerID, hash$$1) {
|
7470 | var map = Object.create(MapPrototype);
|
7471 | map.size = size;
|
7472 | map._root = root;
|
7473 | map.__ownerID = ownerID;
|
7474 | map.__hash = hash$$1;
|
7475 | map.__altered = false;
|
7476 | return map;
|
7477 | }
|
7478 |
|
7479 | var EMPTY_MAP;
|
7480 | function emptyMap() {
|
7481 | return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
|
7482 | }
|
7483 |
|
7484 | function updateMap(map, k, v) {
|
7485 | var newRoot;
|
7486 | var newSize;
|
7487 | if (!map._root) {
|
7488 | if (v === NOT_SET) {
|
7489 | return map;
|
7490 | }
|
7491 | newSize = 1;
|
7492 | newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
|
7493 | } else {
|
7494 | var didChangeSize = MakeRef();
|
7495 | var didAlter = MakeRef();
|
7496 | newRoot = updateNode(
|
7497 | map._root,
|
7498 | map.__ownerID,
|
7499 | 0,
|
7500 | undefined,
|
7501 | k,
|
7502 | v,
|
7503 | didChangeSize,
|
7504 | didAlter
|
7505 | );
|
7506 | if (!didAlter.value) {
|
7507 | return map;
|
7508 | }
|
7509 | newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
|
7510 | }
|
7511 | if (map.__ownerID) {
|
7512 | map.size = newSize;
|
7513 | map._root = newRoot;
|
7514 | map.__hash = undefined;
|
7515 | map.__altered = true;
|
7516 | return map;
|
7517 | }
|
7518 | return newRoot ? makeMap(newSize, newRoot) : emptyMap();
|
7519 | }
|
7520 |
|
7521 | function updateNode(
|
7522 | node,
|
7523 | ownerID,
|
7524 | shift,
|
7525 | keyHash,
|
7526 | key,
|
7527 | value,
|
7528 | didChangeSize,
|
7529 | didAlter
|
7530 | ) {
|
7531 | if (!node) {
|
7532 | if (value === NOT_SET) {
|
7533 | return node;
|
7534 | }
|
7535 | SetRef(didAlter);
|
7536 | SetRef(didChangeSize);
|
7537 | return new ValueNode(ownerID, keyHash, [key, value]);
|
7538 | }
|
7539 | return node.update(
|
7540 | ownerID,
|
7541 | shift,
|
7542 | keyHash,
|
7543 | key,
|
7544 | value,
|
7545 | didChangeSize,
|
7546 | didAlter
|
7547 | );
|
7548 | }
|
7549 |
|
7550 | function isLeafNode(node) {
|
7551 | return (
|
7552 | node.constructor === ValueNode || node.constructor === HashCollisionNode
|
7553 | );
|
7554 | }
|
7555 |
|
7556 | function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
|
7557 | if (node.keyHash === keyHash) {
|
7558 | return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
|
7559 | }
|
7560 |
|
7561 | var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
|
7562 | var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
|
7563 |
|
7564 | var newNode;
|
7565 | var nodes =
|
7566 | idx1 === idx2
|
7567 | ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
|
7568 | : ((newNode = new ValueNode(ownerID, keyHash, entry)),
|
7569 | idx1 < idx2 ? [node, newNode] : [newNode, node]);
|
7570 |
|
7571 | return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
|
7572 | }
|
7573 |
|
7574 | function createNodes(ownerID, entries, key, value) {
|
7575 | if (!ownerID) {
|
7576 | ownerID = new OwnerID();
|
7577 | }
|
7578 | var node = new ValueNode(ownerID, hash(key), [key, value]);
|
7579 | for (var ii = 0; ii < entries.length; ii++) {
|
7580 | var entry = entries[ii];
|
7581 | node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
|
7582 | }
|
7583 | return node;
|
7584 | }
|
7585 |
|
7586 | function packNodes(ownerID, nodes, count, excluding) {
|
7587 | var bitmap = 0;
|
7588 | var packedII = 0;
|
7589 | var packedNodes = new Array(count);
|
7590 | for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
|
7591 | var node = nodes[ii];
|
7592 | if (node !== undefined && ii !== excluding) {
|
7593 | bitmap |= bit;
|
7594 | packedNodes[packedII++] = node;
|
7595 | }
|
7596 | }
|
7597 | return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
|
7598 | }
|
7599 |
|
7600 | function expandNodes(ownerID, nodes, bitmap, including, node) {
|
7601 | var count = 0;
|
7602 | var expandedNodes = new Array(SIZE);
|
7603 | for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
|
7604 | expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
|
7605 | }
|
7606 | expandedNodes[including] = node;
|
7607 | return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
|
7608 | }
|
7609 |
|
7610 | function popCount(x) {
|
7611 | x -= (x >> 1) & 0x55555555;
|
7612 | x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
|
7613 | x = (x + (x >> 4)) & 0x0f0f0f0f;
|
7614 | x += x >> 8;
|
7615 | x += x >> 16;
|
7616 | return x & 0x7f;
|
7617 | }
|
7618 |
|
7619 | function setAt(array, idx, val, canEdit) {
|
7620 | var newArray = canEdit ? array : arrCopy(array);
|
7621 | newArray[idx] = val;
|
7622 | return newArray;
|
7623 | }
|
7624 |
|
7625 | function spliceIn(array, idx, val, canEdit) {
|
7626 | var newLen = array.length + 1;
|
7627 | if (canEdit && idx + 1 === newLen) {
|
7628 | array[idx] = val;
|
7629 | return array;
|
7630 | }
|
7631 | var newArray = new Array(newLen);
|
7632 | var after = 0;
|
7633 | for (var ii = 0; ii < newLen; ii++) {
|
7634 | if (ii === idx) {
|
7635 | newArray[ii] = val;
|
7636 | after = -1;
|
7637 | } else {
|
7638 | newArray[ii] = array[ii + after];
|
7639 | }
|
7640 | }
|
7641 | return newArray;
|
7642 | }
|
7643 |
|
7644 | function spliceOut(array, idx, canEdit) {
|
7645 | var newLen = array.length - 1;
|
7646 | if (canEdit && idx === newLen) {
|
7647 | array.pop();
|
7648 | return array;
|
7649 | }
|
7650 | var newArray = new Array(newLen);
|
7651 | var after = 0;
|
7652 | for (var ii = 0; ii < newLen; ii++) {
|
7653 | if (ii === idx) {
|
7654 | after = 1;
|
7655 | }
|
7656 | newArray[ii] = array[ii + after];
|
7657 | }
|
7658 | return newArray;
|
7659 | }
|
7660 |
|
7661 | var MAX_ARRAY_MAP_SIZE = SIZE / 4;
|
7662 | var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
|
7663 | var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
|
7664 |
|
7665 | var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
|
7666 |
|
7667 | function isList(maybeList) {
|
7668 | return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]);
|
7669 | }
|
7670 |
|
7671 | var List = /*@__PURE__*/(function (IndexedCollection$$1) {
|
7672 | function List(value) {
|
7673 | var empty = emptyList();
|
7674 | if (value === null || value === undefined) {
|
7675 | return empty;
|
7676 | }
|
7677 | if (isList(value)) {
|
7678 | return value;
|
7679 | }
|
7680 | var iter = IndexedCollection$$1(value);
|
7681 | var size = iter.size;
|
7682 | if (size === 0) {
|
7683 | return empty;
|
7684 | }
|
7685 | assertNotInfinite(size);
|
7686 | if (size > 0 && size < SIZE) {
|
7687 | return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
|
7688 | }
|
7689 | return empty.withMutations(function (list) {
|
7690 | list.setSize(size);
|
7691 | iter.forEach(function (v, i) { return list.set(i, v); });
|
7692 | });
|
7693 | }
|
7694 |
|
7695 | if ( IndexedCollection$$1 ) List.__proto__ = IndexedCollection$$1;
|
7696 | List.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
|
7697 | List.prototype.constructor = List;
|
7698 |
|
7699 | List.of = function of (/*...values*/) {
|
7700 | return this(arguments);
|
7701 | };
|
7702 |
|
7703 | List.prototype.toString = function toString () {
|
7704 | return this.__toString('List [', ']');
|
7705 | };
|
7706 |
|
7707 | // @pragma Access
|
7708 |
|
7709 | List.prototype.get = function get (index, notSetValue) {
|
7710 | index = wrapIndex(this, index);
|
7711 | if (index >= 0 && index < this.size) {
|
7712 | index += this._origin;
|
7713 | var node = listNodeFor(this, index);
|
7714 | return node && node.array[index & MASK];
|
7715 | }
|
7716 | return notSetValue;
|
7717 | };
|
7718 |
|
7719 | // @pragma Modification
|
7720 |
|
7721 | List.prototype.set = function set (index, value) {
|
7722 | return updateList(this, index, value);
|
7723 | };
|
7724 |
|
7725 | List.prototype.remove = function remove (index) {
|
7726 | return !this.has(index)
|
7727 | ? this
|
7728 | : index === 0
|
7729 | ? this.shift()
|
7730 | : index === this.size - 1
|
7731 | ? this.pop()
|
7732 | : this.splice(index, 1);
|
7733 | };
|
7734 |
|
7735 | List.prototype.insert = function insert (index, value) {
|
7736 | return this.splice(index, 0, value);
|
7737 | };
|
7738 |
|
7739 | List.prototype.clear = function clear () {
|
7740 | if (this.size === 0) {
|
7741 | return this;
|
7742 | }
|
7743 | if (this.__ownerID) {
|
7744 | this.size = this._origin = this._capacity = 0;
|
7745 | this._level = SHIFT;
|
7746 | this._root = this._tail = null;
|
7747 | this.__hash = undefined;
|
7748 | this.__altered = true;
|
7749 | return this;
|
7750 | }
|
7751 | return emptyList();
|
7752 | };
|
7753 |
|
7754 | List.prototype.push = function push (/*...values*/) {
|
7755 | var values = arguments;
|
7756 | var oldSize = this.size;
|
7757 | return this.withMutations(function (list) {
|
7758 | setListBounds(list, 0, oldSize + values.length);
|
7759 | for (var ii = 0; ii < values.length; ii++) {
|
7760 | list.set(oldSize + ii, values[ii]);
|
7761 | }
|
7762 | });
|
7763 | };
|
7764 |
|
7765 | List.prototype.pop = function pop () {
|
7766 | return setListBounds(this, 0, -1);
|
7767 | };
|
7768 |
|
7769 | List.prototype.unshift = function unshift (/*...values*/) {
|
7770 | var values = arguments;
|
7771 | return this.withMutations(function (list) {
|
7772 | setListBounds(list, -values.length);
|
7773 | for (var ii = 0; ii < values.length; ii++) {
|
7774 | list.set(ii, values[ii]);
|
7775 | }
|
7776 | });
|
7777 | };
|
7778 |
|
7779 | List.prototype.shift = function shift () {
|
7780 | return setListBounds(this, 1);
|
7781 | };
|
7782 |
|
7783 | // @pragma Composition
|
7784 |
|
7785 | List.prototype.concat = function concat (/*...collections*/) {
|
7786 | var arguments$1 = arguments;
|
7787 |
|
7788 | var seqs = [];
|
7789 | for (var i = 0; i < arguments.length; i++) {
|
7790 | var argument = arguments$1[i];
|
7791 | var seq = IndexedCollection$$1(
|
7792 | typeof argument !== 'string' && hasIterator(argument)
|
7793 | ? argument
|
7794 | : [argument]
|
7795 | );
|
7796 | if (seq.size !== 0) {
|
7797 | seqs.push(seq);
|
7798 | }
|
7799 | }
|
7800 | if (seqs.length === 0) {
|
7801 | return this;
|
7802 | }
|
7803 | if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
|
7804 | return this.constructor(seqs[0]);
|
7805 | }
|
7806 | return this.withMutations(function (list) {
|
7807 | seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
|
7808 | });
|
7809 | };
|
7810 |
|
7811 | List.prototype.setSize = function setSize (size) {
|
7812 | return setListBounds(this, 0, size);
|
7813 | };
|
7814 |
|
7815 | List.prototype.map = function map (mapper, context) {
|
7816 | var this$1 = this;
|
7817 |
|
7818 | return this.withMutations(function (list) {
|
7819 | for (var i = 0; i < this$1.size; i++) {
|
7820 | list.set(i, mapper.call(context, list.get(i), i, list));
|
7821 | }
|
7822 | });
|
7823 | };
|
7824 |
|
7825 | // @pragma Iteration
|
7826 |
|
7827 | List.prototype.slice = function slice (begin, end) {
|
7828 | var size = this.size;
|
7829 | if (wholeSlice(begin, end, size)) {
|
7830 | return this;
|
7831 | }
|
7832 | return setListBounds(
|
7833 | this,
|
7834 | resolveBegin(begin, size),
|
7835 | resolveEnd(end, size)
|
7836 | );
|
7837 | };
|
7838 |
|
7839 | List.prototype.__iterator = function __iterator (type, reverse) {
|
7840 | var index = reverse ? this.size : 0;
|
7841 | var values = iterateList(this, reverse);
|
7842 | return new Iterator(function () {
|
7843 | var value = values();
|
7844 | return value === DONE
|
7845 | ? iteratorDone()
|
7846 | : iteratorValue(type, reverse ? --index : index++, value);
|
7847 | });
|
7848 | };
|
7849 |
|
7850 | List.prototype.__iterate = function __iterate (fn, reverse) {
|
7851 | var index = reverse ? this.size : 0;
|
7852 | var values = iterateList(this, reverse);
|
7853 | var value;
|
7854 | while ((value = values()) !== DONE) {
|
7855 | if (fn(value, reverse ? --index : index++, this) === false) {
|
7856 | break;
|
7857 | }
|
7858 | }
|
7859 | return index;
|
7860 | };
|
7861 |
|
7862 | List.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
7863 | if (ownerID === this.__ownerID) {
|
7864 | return this;
|
7865 | }
|
7866 | if (!ownerID) {
|
7867 | if (this.size === 0) {
|
7868 | return emptyList();
|
7869 | }
|
7870 | this.__ownerID = ownerID;
|
7871 | this.__altered = false;
|
7872 | return this;
|
7873 | }
|
7874 | return makeList(
|
7875 | this._origin,
|
7876 | this._capacity,
|
7877 | this._level,
|
7878 | this._root,
|
7879 | this._tail,
|
7880 | ownerID,
|
7881 | this.__hash
|
7882 | );
|
7883 | };
|
7884 |
|
7885 | return List;
|
7886 | }(IndexedCollection));
|
7887 |
|
7888 | List.isList = isList;
|
7889 |
|
7890 | var ListPrototype = List.prototype;
|
7891 | ListPrototype[IS_LIST_SYMBOL] = true;
|
7892 | ListPrototype[DELETE] = ListPrototype.remove;
|
7893 | ListPrototype.merge = ListPrototype.concat;
|
7894 | ListPrototype.setIn = setIn$1;
|
7895 | ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
|
7896 | ListPrototype.update = update$1;
|
7897 | ListPrototype.updateIn = updateIn$1;
|
7898 | ListPrototype.mergeIn = mergeIn;
|
7899 | ListPrototype.mergeDeepIn = mergeDeepIn;
|
7900 | ListPrototype.withMutations = withMutations;
|
7901 | ListPrototype.wasAltered = wasAltered;
|
7902 | ListPrototype.asImmutable = asImmutable;
|
7903 | ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
|
7904 | ListPrototype['@@transducer/step'] = function(result, arr) {
|
7905 | return result.push(arr);
|
7906 | };
|
7907 | ListPrototype['@@transducer/result'] = function(obj) {
|
7908 | return obj.asImmutable();
|
7909 | };
|
7910 |
|
7911 | var VNode = function VNode(array, ownerID) {
|
7912 | this.array = array;
|
7913 | this.ownerID = ownerID;
|
7914 | };
|
7915 |
|
7916 | // TODO: seems like these methods are very similar
|
7917 |
|
7918 | VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) {
|
7919 | if (index === level ? 1 << level : this.array.length === 0) {
|
7920 | return this;
|
7921 | }
|
7922 | var originIndex = (index >>> level) & MASK;
|
7923 | if (originIndex >= this.array.length) {
|
7924 | return new VNode([], ownerID);
|
7925 | }
|
7926 | var removingFirst = originIndex === 0;
|
7927 | var newChild;
|
7928 | if (level > 0) {
|
7929 | var oldChild = this.array[originIndex];
|
7930 | newChild =
|
7931 | oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
|
7932 | if (newChild === oldChild && removingFirst) {
|
7933 | return this;
|
7934 | }
|
7935 | }
|
7936 | if (removingFirst && !newChild) {
|
7937 | return this;
|
7938 | }
|
7939 | var editable = editableVNode(this, ownerID);
|
7940 | if (!removingFirst) {
|
7941 | for (var ii = 0; ii < originIndex; ii++) {
|
7942 | editable.array[ii] = undefined;
|
7943 | }
|
7944 | }
|
7945 | if (newChild) {
|
7946 | editable.array[originIndex] = newChild;
|
7947 | }
|
7948 | return editable;
|
7949 | };
|
7950 |
|
7951 | VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) {
|
7952 | if (index === (level ? 1 << level : 0) || this.array.length === 0) {
|
7953 | return this;
|
7954 | }
|
7955 | var sizeIndex = ((index - 1) >>> level) & MASK;
|
7956 | if (sizeIndex >= this.array.length) {
|
7957 | return this;
|
7958 | }
|
7959 |
|
7960 | var newChild;
|
7961 | if (level > 0) {
|
7962 | var oldChild = this.array[sizeIndex];
|
7963 | newChild =
|
7964 | oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
|
7965 | if (newChild === oldChild && sizeIndex === this.array.length - 1) {
|
7966 | return this;
|
7967 | }
|
7968 | }
|
7969 |
|
7970 | var editable = editableVNode(this, ownerID);
|
7971 | editable.array.splice(sizeIndex + 1);
|
7972 | if (newChild) {
|
7973 | editable.array[sizeIndex] = newChild;
|
7974 | }
|
7975 | return editable;
|
7976 | };
|
7977 |
|
7978 | var DONE = {};
|
7979 |
|
7980 | function iterateList(list, reverse) {
|
7981 | var left = list._origin;
|
7982 | var right = list._capacity;
|
7983 | var tailPos = getTailOffset(right);
|
7984 | var tail = list._tail;
|
7985 |
|
7986 | return iterateNodeOrLeaf(list._root, list._level, 0);
|
7987 |
|
7988 | function iterateNodeOrLeaf(node, level, offset) {
|
7989 | return level === 0
|
7990 | ? iterateLeaf(node, offset)
|
7991 | : iterateNode(node, level, offset);
|
7992 | }
|
7993 |
|
7994 | function iterateLeaf(node, offset) {
|
7995 | var array = offset === tailPos ? tail && tail.array : node && node.array;
|
7996 | var from = offset > left ? 0 : left - offset;
|
7997 | var to = right - offset;
|
7998 | if (to > SIZE) {
|
7999 | to = SIZE;
|
8000 | }
|
8001 | return function () {
|
8002 | if (from === to) {
|
8003 | return DONE;
|
8004 | }
|
8005 | var idx = reverse ? --to : from++;
|
8006 | return array && array[idx];
|
8007 | };
|
8008 | }
|
8009 |
|
8010 | function iterateNode(node, level, offset) {
|
8011 | var values;
|
8012 | var array = node && node.array;
|
8013 | var from = offset > left ? 0 : (left - offset) >> level;
|
8014 | var to = ((right - offset) >> level) + 1;
|
8015 | if (to > SIZE) {
|
8016 | to = SIZE;
|
8017 | }
|
8018 | return function () {
|
8019 | while (true) {
|
8020 | if (values) {
|
8021 | var value = values();
|
8022 | if (value !== DONE) {
|
8023 | return value;
|
8024 | }
|
8025 | values = null;
|
8026 | }
|
8027 | if (from === to) {
|
8028 | return DONE;
|
8029 | }
|
8030 | var idx = reverse ? --to : from++;
|
8031 | values = iterateNodeOrLeaf(
|
8032 | array && array[idx],
|
8033 | level - SHIFT,
|
8034 | offset + (idx << level)
|
8035 | );
|
8036 | }
|
8037 | };
|
8038 | }
|
8039 | }
|
8040 |
|
8041 | function makeList(origin, capacity, level, root, tail, ownerID, hash) {
|
8042 | var list = Object.create(ListPrototype);
|
8043 | list.size = capacity - origin;
|
8044 | list._origin = origin;
|
8045 | list._capacity = capacity;
|
8046 | list._level = level;
|
8047 | list._root = root;
|
8048 | list._tail = tail;
|
8049 | list.__ownerID = ownerID;
|
8050 | list.__hash = hash;
|
8051 | list.__altered = false;
|
8052 | return list;
|
8053 | }
|
8054 |
|
8055 | var EMPTY_LIST;
|
8056 | function emptyList() {
|
8057 | return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
|
8058 | }
|
8059 |
|
8060 | function updateList(list, index, value) {
|
8061 | index = wrapIndex(list, index);
|
8062 |
|
8063 | if (index !== index) {
|
8064 | return list;
|
8065 | }
|
8066 |
|
8067 | if (index >= list.size || index < 0) {
|
8068 | return list.withMutations(function (list) {
|
8069 | index < 0
|
8070 | ? setListBounds(list, index).set(0, value)
|
8071 | : setListBounds(list, 0, index + 1).set(index, value);
|
8072 | });
|
8073 | }
|
8074 |
|
8075 | index += list._origin;
|
8076 |
|
8077 | var newTail = list._tail;
|
8078 | var newRoot = list._root;
|
8079 | var didAlter = MakeRef();
|
8080 | if (index >= getTailOffset(list._capacity)) {
|
8081 | newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
|
8082 | } else {
|
8083 | newRoot = updateVNode(
|
8084 | newRoot,
|
8085 | list.__ownerID,
|
8086 | list._level,
|
8087 | index,
|
8088 | value,
|
8089 | didAlter
|
8090 | );
|
8091 | }
|
8092 |
|
8093 | if (!didAlter.value) {
|
8094 | return list;
|
8095 | }
|
8096 |
|
8097 | if (list.__ownerID) {
|
8098 | list._root = newRoot;
|
8099 | list._tail = newTail;
|
8100 | list.__hash = undefined;
|
8101 | list.__altered = true;
|
8102 | return list;
|
8103 | }
|
8104 | return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
|
8105 | }
|
8106 |
|
8107 | function updateVNode(node, ownerID, level, index, value, didAlter) {
|
8108 | var idx = (index >>> level) & MASK;
|
8109 | var nodeHas = node && idx < node.array.length;
|
8110 | if (!nodeHas && value === undefined) {
|
8111 | return node;
|
8112 | }
|
8113 |
|
8114 | var newNode;
|
8115 |
|
8116 | if (level > 0) {
|
8117 | var lowerNode = node && node.array[idx];
|
8118 | var newLowerNode = updateVNode(
|
8119 | lowerNode,
|
8120 | ownerID,
|
8121 | level - SHIFT,
|
8122 | index,
|
8123 | value,
|
8124 | didAlter
|
8125 | );
|
8126 | if (newLowerNode === lowerNode) {
|
8127 | return node;
|
8128 | }
|
8129 | newNode = editableVNode(node, ownerID);
|
8130 | newNode.array[idx] = newLowerNode;
|
8131 | return newNode;
|
8132 | }
|
8133 |
|
8134 | if (nodeHas && node.array[idx] === value) {
|
8135 | return node;
|
8136 | }
|
8137 |
|
8138 | if (didAlter) {
|
8139 | SetRef(didAlter);
|
8140 | }
|
8141 |
|
8142 | newNode = editableVNode(node, ownerID);
|
8143 | if (value === undefined && idx === newNode.array.length - 1) {
|
8144 | newNode.array.pop();
|
8145 | } else {
|
8146 | newNode.array[idx] = value;
|
8147 | }
|
8148 | return newNode;
|
8149 | }
|
8150 |
|
8151 | function editableVNode(node, ownerID) {
|
8152 | if (ownerID && node && ownerID === node.ownerID) {
|
8153 | return node;
|
8154 | }
|
8155 | return new VNode(node ? node.array.slice() : [], ownerID);
|
8156 | }
|
8157 |
|
8158 | function listNodeFor(list, rawIndex) {
|
8159 | if (rawIndex >= getTailOffset(list._capacity)) {
|
8160 | return list._tail;
|
8161 | }
|
8162 | if (rawIndex < 1 << (list._level + SHIFT)) {
|
8163 | var node = list._root;
|
8164 | var level = list._level;
|
8165 | while (node && level > 0) {
|
8166 | node = node.array[(rawIndex >>> level) & MASK];
|
8167 | level -= SHIFT;
|
8168 | }
|
8169 | return node;
|
8170 | }
|
8171 | }
|
8172 |
|
8173 | function setListBounds(list, begin, end) {
|
8174 | // Sanitize begin & end using this shorthand for ToInt32(argument)
|
8175 | // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
|
8176 | if (begin !== undefined) {
|
8177 | begin |= 0;
|
8178 | }
|
8179 | if (end !== undefined) {
|
8180 | end |= 0;
|
8181 | }
|
8182 | var owner = list.__ownerID || new OwnerID();
|
8183 | var oldOrigin = list._origin;
|
8184 | var oldCapacity = list._capacity;
|
8185 | var newOrigin = oldOrigin + begin;
|
8186 | var newCapacity =
|
8187 | end === undefined
|
8188 | ? oldCapacity
|
8189 | : end < 0
|
8190 | ? oldCapacity + end
|
8191 | : oldOrigin + end;
|
8192 | if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
|
8193 | return list;
|
8194 | }
|
8195 |
|
8196 | // If it's going to end after it starts, it's empty.
|
8197 | if (newOrigin >= newCapacity) {
|
8198 | return list.clear();
|
8199 | }
|
8200 |
|
8201 | var newLevel = list._level;
|
8202 | var newRoot = list._root;
|
8203 |
|
8204 | // New origin might need creating a higher root.
|
8205 | var offsetShift = 0;
|
8206 | while (newOrigin + offsetShift < 0) {
|
8207 | newRoot = new VNode(
|
8208 | newRoot && newRoot.array.length ? [undefined, newRoot] : [],
|
8209 | owner
|
8210 | );
|
8211 | newLevel += SHIFT;
|
8212 | offsetShift += 1 << newLevel;
|
8213 | }
|
8214 | if (offsetShift) {
|
8215 | newOrigin += offsetShift;
|
8216 | oldOrigin += offsetShift;
|
8217 | newCapacity += offsetShift;
|
8218 | oldCapacity += offsetShift;
|
8219 | }
|
8220 |
|
8221 | var oldTailOffset = getTailOffset(oldCapacity);
|
8222 | var newTailOffset = getTailOffset(newCapacity);
|
8223 |
|
8224 | // New size might need creating a higher root.
|
8225 | while (newTailOffset >= 1 << (newLevel + SHIFT)) {
|
8226 | newRoot = new VNode(
|
8227 | newRoot && newRoot.array.length ? [newRoot] : [],
|
8228 | owner
|
8229 | );
|
8230 | newLevel += SHIFT;
|
8231 | }
|
8232 |
|
8233 | // Locate or create the new tail.
|
8234 | var oldTail = list._tail;
|
8235 | var newTail =
|
8236 | newTailOffset < oldTailOffset
|
8237 | ? listNodeFor(list, newCapacity - 1)
|
8238 | : newTailOffset > oldTailOffset
|
8239 | ? new VNode([], owner)
|
8240 | : oldTail;
|
8241 |
|
8242 | // Merge Tail into tree.
|
8243 | if (
|
8244 | oldTail &&
|
8245 | newTailOffset > oldTailOffset &&
|
8246 | newOrigin < oldCapacity &&
|
8247 | oldTail.array.length
|
8248 | ) {
|
8249 | newRoot = editableVNode(newRoot, owner);
|
8250 | var node = newRoot;
|
8251 | for (var level = newLevel; level > SHIFT; level -= SHIFT) {
|
8252 | var idx = (oldTailOffset >>> level) & MASK;
|
8253 | node = node.array[idx] = editableVNode(node.array[idx], owner);
|
8254 | }
|
8255 | node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
|
8256 | }
|
8257 |
|
8258 | // If the size has been reduced, there's a chance the tail needs to be trimmed.
|
8259 | if (newCapacity < oldCapacity) {
|
8260 | newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
|
8261 | }
|
8262 |
|
8263 | // If the new origin is within the tail, then we do not need a root.
|
8264 | if (newOrigin >= newTailOffset) {
|
8265 | newOrigin -= newTailOffset;
|
8266 | newCapacity -= newTailOffset;
|
8267 | newLevel = SHIFT;
|
8268 | newRoot = null;
|
8269 | newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
|
8270 |
|
8271 | // Otherwise, if the root has been trimmed, garbage collect.
|
8272 | } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
|
8273 | offsetShift = 0;
|
8274 |
|
8275 | // Identify the new top root node of the subtree of the old root.
|
8276 | while (newRoot) {
|
8277 | var beginIndex = (newOrigin >>> newLevel) & MASK;
|
8278 | if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
|
8279 | break;
|
8280 | }
|
8281 | if (beginIndex) {
|
8282 | offsetShift += (1 << newLevel) * beginIndex;
|
8283 | }
|
8284 | newLevel -= SHIFT;
|
8285 | newRoot = newRoot.array[beginIndex];
|
8286 | }
|
8287 |
|
8288 | // Trim the new sides of the new root.
|
8289 | if (newRoot && newOrigin > oldOrigin) {
|
8290 | newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
|
8291 | }
|
8292 | if (newRoot && newTailOffset < oldTailOffset) {
|
8293 | newRoot = newRoot.removeAfter(
|
8294 | owner,
|
8295 | newLevel,
|
8296 | newTailOffset - offsetShift
|
8297 | );
|
8298 | }
|
8299 | if (offsetShift) {
|
8300 | newOrigin -= offsetShift;
|
8301 | newCapacity -= offsetShift;
|
8302 | }
|
8303 | }
|
8304 |
|
8305 | if (list.__ownerID) {
|
8306 | list.size = newCapacity - newOrigin;
|
8307 | list._origin = newOrigin;
|
8308 | list._capacity = newCapacity;
|
8309 | list._level = newLevel;
|
8310 | list._root = newRoot;
|
8311 | list._tail = newTail;
|
8312 | list.__hash = undefined;
|
8313 | list.__altered = true;
|
8314 | return list;
|
8315 | }
|
8316 | return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
|
8317 | }
|
8318 |
|
8319 | function getTailOffset(size) {
|
8320 | return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
|
8321 | }
|
8322 |
|
8323 | var OrderedMap = /*@__PURE__*/(function (Map$$1) {
|
8324 | function OrderedMap(value) {
|
8325 | return value === null || value === undefined
|
8326 | ? emptyOrderedMap()
|
8327 | : isOrderedMap(value)
|
8328 | ? value
|
8329 | : emptyOrderedMap().withMutations(function (map) {
|
8330 | var iter = KeyedCollection(value);
|
8331 | assertNotInfinite(iter.size);
|
8332 | iter.forEach(function (v, k) { return map.set(k, v); });
|
8333 | });
|
8334 | }
|
8335 |
|
8336 | if ( Map$$1 ) OrderedMap.__proto__ = Map$$1;
|
8337 | OrderedMap.prototype = Object.create( Map$$1 && Map$$1.prototype );
|
8338 | OrderedMap.prototype.constructor = OrderedMap;
|
8339 |
|
8340 | OrderedMap.of = function of (/*...values*/) {
|
8341 | return this(arguments);
|
8342 | };
|
8343 |
|
8344 | OrderedMap.prototype.toString = function toString () {
|
8345 | return this.__toString('OrderedMap {', '}');
|
8346 | };
|
8347 |
|
8348 | // @pragma Access
|
8349 |
|
8350 | OrderedMap.prototype.get = function get (k, notSetValue) {
|
8351 | var index = this._map.get(k);
|
8352 | return index !== undefined ? this._list.get(index)[1] : notSetValue;
|
8353 | };
|
8354 |
|
8355 | // @pragma Modification
|
8356 |
|
8357 | OrderedMap.prototype.clear = function clear () {
|
8358 | if (this.size === 0) {
|
8359 | return this;
|
8360 | }
|
8361 | if (this.__ownerID) {
|
8362 | this.size = 0;
|
8363 | this._map.clear();
|
8364 | this._list.clear();
|
8365 | return this;
|
8366 | }
|
8367 | return emptyOrderedMap();
|
8368 | };
|
8369 |
|
8370 | OrderedMap.prototype.set = function set (k, v) {
|
8371 | return updateOrderedMap(this, k, v);
|
8372 | };
|
8373 |
|
8374 | OrderedMap.prototype.remove = function remove (k) {
|
8375 | return updateOrderedMap(this, k, NOT_SET);
|
8376 | };
|
8377 |
|
8378 | OrderedMap.prototype.wasAltered = function wasAltered () {
|
8379 | return this._map.wasAltered() || this._list.wasAltered();
|
8380 | };
|
8381 |
|
8382 | OrderedMap.prototype.__iterate = function __iterate (fn, reverse) {
|
8383 | var this$1 = this;
|
8384 |
|
8385 | return this._list.__iterate(
|
8386 | function (entry) { return entry && fn(entry[1], entry[0], this$1); },
|
8387 | reverse
|
8388 | );
|
8389 | };
|
8390 |
|
8391 | OrderedMap.prototype.__iterator = function __iterator (type, reverse) {
|
8392 | return this._list.fromEntrySeq().__iterator(type, reverse);
|
8393 | };
|
8394 |
|
8395 | OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
8396 | if (ownerID === this.__ownerID) {
|
8397 | return this;
|
8398 | }
|
8399 | var newMap = this._map.__ensureOwner(ownerID);
|
8400 | var newList = this._list.__ensureOwner(ownerID);
|
8401 | if (!ownerID) {
|
8402 | if (this.size === 0) {
|
8403 | return emptyOrderedMap();
|
8404 | }
|
8405 | this.__ownerID = ownerID;
|
8406 | this._map = newMap;
|
8407 | this._list = newList;
|
8408 | return this;
|
8409 | }
|
8410 | return makeOrderedMap(newMap, newList, ownerID, this.__hash);
|
8411 | };
|
8412 |
|
8413 | return OrderedMap;
|
8414 | }(Map$1));
|
8415 |
|
8416 | OrderedMap.isOrderedMap = isOrderedMap;
|
8417 |
|
8418 | OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
|
8419 | OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
|
8420 |
|
8421 | function makeOrderedMap(map, list, ownerID, hash) {
|
8422 | var omap = Object.create(OrderedMap.prototype);
|
8423 | omap.size = map ? map.size : 0;
|
8424 | omap._map = map;
|
8425 | omap._list = list;
|
8426 | omap.__ownerID = ownerID;
|
8427 | omap.__hash = hash;
|
8428 | return omap;
|
8429 | }
|
8430 |
|
8431 | var EMPTY_ORDERED_MAP;
|
8432 | function emptyOrderedMap() {
|
8433 | return (
|
8434 | EMPTY_ORDERED_MAP ||
|
8435 | (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))
|
8436 | );
|
8437 | }
|
8438 |
|
8439 | function updateOrderedMap(omap, k, v) {
|
8440 | var map = omap._map;
|
8441 | var list = omap._list;
|
8442 | var i = map.get(k);
|
8443 | var has = i !== undefined;
|
8444 | var newMap;
|
8445 | var newList;
|
8446 | if (v === NOT_SET) {
|
8447 | // removed
|
8448 | if (!has) {
|
8449 | return omap;
|
8450 | }
|
8451 | if (list.size >= SIZE && list.size >= map.size * 2) {
|
8452 | newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
|
8453 | newMap = newList
|
8454 | .toKeyedSeq()
|
8455 | .map(function (entry) { return entry[0]; })
|
8456 | .flip()
|
8457 | .toMap();
|
8458 | if (omap.__ownerID) {
|
8459 | newMap.__ownerID = newList.__ownerID = omap.__ownerID;
|
8460 | }
|
8461 | } else {
|
8462 | newMap = map.remove(k);
|
8463 | newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
|
8464 | }
|
8465 | } else if (has) {
|
8466 | if (v === list.get(i)[1]) {
|
8467 | return omap;
|
8468 | }
|
8469 | newMap = map;
|
8470 | newList = list.set(i, [k, v]);
|
8471 | } else {
|
8472 | newMap = map.set(k, list.size);
|
8473 | newList = list.set(list.size, [k, v]);
|
8474 | }
|
8475 | if (omap.__ownerID) {
|
8476 | omap.size = newMap.size;
|
8477 | omap._map = newMap;
|
8478 | omap._list = newList;
|
8479 | omap.__hash = undefined;
|
8480 | return omap;
|
8481 | }
|
8482 | return makeOrderedMap(newMap, newList);
|
8483 | }
|
8484 |
|
8485 | var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
|
8486 |
|
8487 | function isStack(maybeStack) {
|
8488 | return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]);
|
8489 | }
|
8490 |
|
8491 | var Stack = /*@__PURE__*/(function (IndexedCollection$$1) {
|
8492 | function Stack(value) {
|
8493 | return value === null || value === undefined
|
8494 | ? emptyStack()
|
8495 | : isStack(value)
|
8496 | ? value
|
8497 | : emptyStack().pushAll(value);
|
8498 | }
|
8499 |
|
8500 | if ( IndexedCollection$$1 ) Stack.__proto__ = IndexedCollection$$1;
|
8501 | Stack.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
|
8502 | Stack.prototype.constructor = Stack;
|
8503 |
|
8504 | Stack.of = function of (/*...values*/) {
|
8505 | return this(arguments);
|
8506 | };
|
8507 |
|
8508 | Stack.prototype.toString = function toString () {
|
8509 | return this.__toString('Stack [', ']');
|
8510 | };
|
8511 |
|
8512 | // @pragma Access
|
8513 |
|
8514 | Stack.prototype.get = function get (index, notSetValue) {
|
8515 | var head = this._head;
|
8516 | index = wrapIndex(this, index);
|
8517 | while (head && index--) {
|
8518 | head = head.next;
|
8519 | }
|
8520 | return head ? head.value : notSetValue;
|
8521 | };
|
8522 |
|
8523 | Stack.prototype.peek = function peek () {
|
8524 | return this._head && this._head.value;
|
8525 | };
|
8526 |
|
8527 | // @pragma Modification
|
8528 |
|
8529 | Stack.prototype.push = function push (/*...values*/) {
|
8530 | var arguments$1 = arguments;
|
8531 |
|
8532 | if (arguments.length === 0) {
|
8533 | return this;
|
8534 | }
|
8535 | var newSize = this.size + arguments.length;
|
8536 | var head = this._head;
|
8537 | for (var ii = arguments.length - 1; ii >= 0; ii--) {
|
8538 | head = {
|
8539 | value: arguments$1[ii],
|
8540 | next: head,
|
8541 | };
|
8542 | }
|
8543 | if (this.__ownerID) {
|
8544 | this.size = newSize;
|
8545 | this._head = head;
|
8546 | this.__hash = undefined;
|
8547 | this.__altered = true;
|
8548 | return this;
|
8549 | }
|
8550 | return makeStack(newSize, head);
|
8551 | };
|
8552 |
|
8553 | Stack.prototype.pushAll = function pushAll (iter) {
|
8554 | iter = IndexedCollection$$1(iter);
|
8555 | if (iter.size === 0) {
|
8556 | return this;
|
8557 | }
|
8558 | if (this.size === 0 && isStack(iter)) {
|
8559 | return iter;
|
8560 | }
|
8561 | assertNotInfinite(iter.size);
|
8562 | var newSize = this.size;
|
8563 | var head = this._head;
|
8564 | iter.__iterate(function (value) {
|
8565 | newSize++;
|
8566 | head = {
|
8567 | value: value,
|
8568 | next: head,
|
8569 | };
|
8570 | }, /* reverse */ true);
|
8571 | if (this.__ownerID) {
|
8572 | this.size = newSize;
|
8573 | this._head = head;
|
8574 | this.__hash = undefined;
|
8575 | this.__altered = true;
|
8576 | return this;
|
8577 | }
|
8578 | return makeStack(newSize, head);
|
8579 | };
|
8580 |
|
8581 | Stack.prototype.pop = function pop () {
|
8582 | return this.slice(1);
|
8583 | };
|
8584 |
|
8585 | Stack.prototype.clear = function clear () {
|
8586 | if (this.size === 0) {
|
8587 | return this;
|
8588 | }
|
8589 | if (this.__ownerID) {
|
8590 | this.size = 0;
|
8591 | this._head = undefined;
|
8592 | this.__hash = undefined;
|
8593 | this.__altered = true;
|
8594 | return this;
|
8595 | }
|
8596 | return emptyStack();
|
8597 | };
|
8598 |
|
8599 | Stack.prototype.slice = function slice (begin, end) {
|
8600 | if (wholeSlice(begin, end, this.size)) {
|
8601 | return this;
|
8602 | }
|
8603 | var resolvedBegin = resolveBegin(begin, this.size);
|
8604 | var resolvedEnd = resolveEnd(end, this.size);
|
8605 | if (resolvedEnd !== this.size) {
|
8606 | // super.slice(begin, end);
|
8607 | return IndexedCollection$$1.prototype.slice.call(this, begin, end);
|
8608 | }
|
8609 | var newSize = this.size - resolvedBegin;
|
8610 | var head = this._head;
|
8611 | while (resolvedBegin--) {
|
8612 | head = head.next;
|
8613 | }
|
8614 | if (this.__ownerID) {
|
8615 | this.size = newSize;
|
8616 | this._head = head;
|
8617 | this.__hash = undefined;
|
8618 | this.__altered = true;
|
8619 | return this;
|
8620 | }
|
8621 | return makeStack(newSize, head);
|
8622 | };
|
8623 |
|
8624 | // @pragma Mutability
|
8625 |
|
8626 | Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
8627 | if (ownerID === this.__ownerID) {
|
8628 | return this;
|
8629 | }
|
8630 | if (!ownerID) {
|
8631 | if (this.size === 0) {
|
8632 | return emptyStack();
|
8633 | }
|
8634 | this.__ownerID = ownerID;
|
8635 | this.__altered = false;
|
8636 | return this;
|
8637 | }
|
8638 | return makeStack(this.size, this._head, ownerID, this.__hash);
|
8639 | };
|
8640 |
|
8641 | // @pragma Iteration
|
8642 |
|
8643 | Stack.prototype.__iterate = function __iterate (fn, reverse) {
|
8644 | var this$1 = this;
|
8645 |
|
8646 | if (reverse) {
|
8647 | return new ArraySeq(this.toArray()).__iterate(
|
8648 | function (v, k) { return fn(v, k, this$1); },
|
8649 | reverse
|
8650 | );
|
8651 | }
|
8652 | var iterations = 0;
|
8653 | var node = this._head;
|
8654 | while (node) {
|
8655 | if (fn(node.value, iterations++, this) === false) {
|
8656 | break;
|
8657 | }
|
8658 | node = node.next;
|
8659 | }
|
8660 | return iterations;
|
8661 | };
|
8662 |
|
8663 | Stack.prototype.__iterator = function __iterator (type, reverse) {
|
8664 | if (reverse) {
|
8665 | return new ArraySeq(this.toArray()).__iterator(type, reverse);
|
8666 | }
|
8667 | var iterations = 0;
|
8668 | var node = this._head;
|
8669 | return new Iterator(function () {
|
8670 | if (node) {
|
8671 | var value = node.value;
|
8672 | node = node.next;
|
8673 | return iteratorValue(type, iterations++, value);
|
8674 | }
|
8675 | return iteratorDone();
|
8676 | });
|
8677 | };
|
8678 |
|
8679 | return Stack;
|
8680 | }(IndexedCollection));
|
8681 |
|
8682 | Stack.isStack = isStack;
|
8683 |
|
8684 | var StackPrototype = Stack.prototype;
|
8685 | StackPrototype[IS_STACK_SYMBOL] = true;
|
8686 | StackPrototype.shift = StackPrototype.pop;
|
8687 | StackPrototype.unshift = StackPrototype.push;
|
8688 | StackPrototype.unshiftAll = StackPrototype.pushAll;
|
8689 | StackPrototype.withMutations = withMutations;
|
8690 | StackPrototype.wasAltered = wasAltered;
|
8691 | StackPrototype.asImmutable = asImmutable;
|
8692 | StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
|
8693 | StackPrototype['@@transducer/step'] = function(result, arr) {
|
8694 | return result.unshift(arr);
|
8695 | };
|
8696 | StackPrototype['@@transducer/result'] = function(obj) {
|
8697 | return obj.asImmutable();
|
8698 | };
|
8699 |
|
8700 | function makeStack(size, head, ownerID, hash) {
|
8701 | var map = Object.create(StackPrototype);
|
8702 | map.size = size;
|
8703 | map._head = head;
|
8704 | map.__ownerID = ownerID;
|
8705 | map.__hash = hash;
|
8706 | map.__altered = false;
|
8707 | return map;
|
8708 | }
|
8709 |
|
8710 | var EMPTY_STACK;
|
8711 | function emptyStack() {
|
8712 | return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
|
8713 | }
|
8714 |
|
8715 | var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
|
8716 |
|
8717 | function isSet(maybeSet) {
|
8718 | return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]);
|
8719 | }
|
8720 |
|
8721 | function isOrderedSet(maybeOrderedSet) {
|
8722 | return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
|
8723 | }
|
8724 |
|
8725 | function deepEqual(a, b) {
|
8726 | if (a === b) {
|
8727 | return true;
|
8728 | }
|
8729 |
|
8730 | if (
|
8731 | !isCollection(b) ||
|
8732 | (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
|
8733 | (a.__hash !== undefined &&
|
8734 | b.__hash !== undefined &&
|
8735 | a.__hash !== b.__hash) ||
|
8736 | isKeyed(a) !== isKeyed(b) ||
|
8737 | isIndexed(a) !== isIndexed(b) ||
|
8738 | isOrdered(a) !== isOrdered(b)
|
8739 | ) {
|
8740 | return false;
|
8741 | }
|
8742 |
|
8743 | if (a.size === 0 && b.size === 0) {
|
8744 | return true;
|
8745 | }
|
8746 |
|
8747 | var notAssociative = !isAssociative(a);
|
8748 |
|
8749 | if (isOrdered(a)) {
|
8750 | var entries = a.entries();
|
8751 | return (
|
8752 | b.every(function (v, k) {
|
8753 | var entry = entries.next().value;
|
8754 | return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
|
8755 | }) && entries.next().done
|
8756 | );
|
8757 | }
|
8758 |
|
8759 | var flipped = false;
|
8760 |
|
8761 | if (a.size === undefined) {
|
8762 | if (b.size === undefined) {
|
8763 | if (typeof a.cacheResult === 'function') {
|
8764 | a.cacheResult();
|
8765 | }
|
8766 | } else {
|
8767 | flipped = true;
|
8768 | var _ = a;
|
8769 | a = b;
|
8770 | b = _;
|
8771 | }
|
8772 | }
|
8773 |
|
8774 | var allEqual = true;
|
8775 | var bSize = b.__iterate(function (v, k) {
|
8776 | if (
|
8777 | notAssociative
|
8778 | ? !a.has(v)
|
8779 | : flipped
|
8780 | ? !is(v, a.get(k, NOT_SET))
|
8781 | : !is(a.get(k, NOT_SET), v)
|
8782 | ) {
|
8783 | allEqual = false;
|
8784 | return false;
|
8785 | }
|
8786 | });
|
8787 |
|
8788 | return allEqual && a.size === bSize;
|
8789 | }
|
8790 |
|
8791 | /**
|
8792 | * Contributes additional methods to a constructor
|
8793 | */
|
8794 | function mixin(ctor, methods) {
|
8795 | var keyCopier = function (key) {
|
8796 | ctor.prototype[key] = methods[key];
|
8797 | };
|
8798 | Object.keys(methods).forEach(keyCopier);
|
8799 | Object.getOwnPropertySymbols &&
|
8800 | Object.getOwnPropertySymbols(methods).forEach(keyCopier);
|
8801 | return ctor;
|
8802 | }
|
8803 |
|
8804 | function toJS(value) {
|
8805 | if (!value || typeof value !== 'object') {
|
8806 | return value;
|
8807 | }
|
8808 | if (!isCollection(value)) {
|
8809 | if (!isDataStructure(value)) {
|
8810 | return value;
|
8811 | }
|
8812 | value = Seq(value);
|
8813 | }
|
8814 | if (isKeyed(value)) {
|
8815 | var result$1 = {};
|
8816 | value.__iterate(function (v, k) {
|
8817 | result$1[k] = toJS(v);
|
8818 | });
|
8819 | return result$1;
|
8820 | }
|
8821 | var result = [];
|
8822 | value.__iterate(function (v) {
|
8823 | result.push(toJS(v));
|
8824 | });
|
8825 | return result;
|
8826 | }
|
8827 |
|
8828 | var Set$1 = /*@__PURE__*/(function (SetCollection$$1) {
|
8829 | function Set(value) {
|
8830 | return value === null || value === undefined
|
8831 | ? emptySet()
|
8832 | : isSet(value) && !isOrdered(value)
|
8833 | ? value
|
8834 | : emptySet().withMutations(function (set) {
|
8835 | var iter = SetCollection$$1(value);
|
8836 | assertNotInfinite(iter.size);
|
8837 | iter.forEach(function (v) { return set.add(v); });
|
8838 | });
|
8839 | }
|
8840 |
|
8841 | if ( SetCollection$$1 ) Set.__proto__ = SetCollection$$1;
|
8842 | Set.prototype = Object.create( SetCollection$$1 && SetCollection$$1.prototype );
|
8843 | Set.prototype.constructor = Set;
|
8844 |
|
8845 | Set.of = function of (/*...values*/) {
|
8846 | return this(arguments);
|
8847 | };
|
8848 |
|
8849 | Set.fromKeys = function fromKeys (value) {
|
8850 | return this(KeyedCollection(value).keySeq());
|
8851 | };
|
8852 |
|
8853 | Set.intersect = function intersect (sets) {
|
8854 | sets = Collection(sets).toArray();
|
8855 | return sets.length
|
8856 | ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
|
8857 | : emptySet();
|
8858 | };
|
8859 |
|
8860 | Set.union = function union (sets) {
|
8861 | sets = Collection(sets).toArray();
|
8862 | return sets.length
|
8863 | ? SetPrototype.union.apply(Set(sets.pop()), sets)
|
8864 | : emptySet();
|
8865 | };
|
8866 |
|
8867 | Set.prototype.toString = function toString () {
|
8868 | return this.__toString('Set {', '}');
|
8869 | };
|
8870 |
|
8871 | // @pragma Access
|
8872 |
|
8873 | Set.prototype.has = function has (value) {
|
8874 | return this._map.has(value);
|
8875 | };
|
8876 |
|
8877 | // @pragma Modification
|
8878 |
|
8879 | Set.prototype.add = function add (value) {
|
8880 | return updateSet(this, this._map.set(value, value));
|
8881 | };
|
8882 |
|
8883 | Set.prototype.remove = function remove (value) {
|
8884 | return updateSet(this, this._map.remove(value));
|
8885 | };
|
8886 |
|
8887 | Set.prototype.clear = function clear () {
|
8888 | return updateSet(this, this._map.clear());
|
8889 | };
|
8890 |
|
8891 | // @pragma Composition
|
8892 |
|
8893 | Set.prototype.map = function map (mapper, context) {
|
8894 | var this$1 = this;
|
8895 |
|
8896 | var removes = [];
|
8897 | var adds = [];
|
8898 | this.forEach(function (value) {
|
8899 | var mapped = mapper.call(context, value, value, this$1);
|
8900 | if (mapped !== value) {
|
8901 | removes.push(value);
|
8902 | adds.push(mapped);
|
8903 | }
|
8904 | });
|
8905 | return this.withMutations(function (set) {
|
8906 | removes.forEach(function (value) { return set.remove(value); });
|
8907 | adds.forEach(function (value) { return set.add(value); });
|
8908 | });
|
8909 | };
|
8910 |
|
8911 | Set.prototype.union = function union () {
|
8912 | var iters = [], len = arguments.length;
|
8913 | while ( len-- ) iters[ len ] = arguments[ len ];
|
8914 |
|
8915 | iters = iters.filter(function (x) { return x.size !== 0; });
|
8916 | if (iters.length === 0) {
|
8917 | return this;
|
8918 | }
|
8919 | if (this.size === 0 && !this.__ownerID && iters.length === 1) {
|
8920 | return this.constructor(iters[0]);
|
8921 | }
|
8922 | return this.withMutations(function (set) {
|
8923 | for (var ii = 0; ii < iters.length; ii++) {
|
8924 | SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); });
|
8925 | }
|
8926 | });
|
8927 | };
|
8928 |
|
8929 | Set.prototype.intersect = function intersect () {
|
8930 | var iters = [], len = arguments.length;
|
8931 | while ( len-- ) iters[ len ] = arguments[ len ];
|
8932 |
|
8933 | if (iters.length === 0) {
|
8934 | return this;
|
8935 | }
|
8936 | iters = iters.map(function (iter) { return SetCollection$$1(iter); });
|
8937 | var toRemove = [];
|
8938 | this.forEach(function (value) {
|
8939 | if (!iters.every(function (iter) { return iter.includes(value); })) {
|
8940 | toRemove.push(value);
|
8941 | }
|
8942 | });
|
8943 | return this.withMutations(function (set) {
|
8944 | toRemove.forEach(function (value) {
|
8945 | set.remove(value);
|
8946 | });
|
8947 | });
|
8948 | };
|
8949 |
|
8950 | Set.prototype.subtract = function subtract () {
|
8951 | var iters = [], len = arguments.length;
|
8952 | while ( len-- ) iters[ len ] = arguments[ len ];
|
8953 |
|
8954 | if (iters.length === 0) {
|
8955 | return this;
|
8956 | }
|
8957 | iters = iters.map(function (iter) { return SetCollection$$1(iter); });
|
8958 | var toRemove = [];
|
8959 | this.forEach(function (value) {
|
8960 | if (iters.some(function (iter) { return iter.includes(value); })) {
|
8961 | toRemove.push(value);
|
8962 | }
|
8963 | });
|
8964 | return this.withMutations(function (set) {
|
8965 | toRemove.forEach(function (value) {
|
8966 | set.remove(value);
|
8967 | });
|
8968 | });
|
8969 | };
|
8970 |
|
8971 | Set.prototype.sort = function sort (comparator) {
|
8972 | // Late binding
|
8973 | return OrderedSet(sortFactory(this, comparator));
|
8974 | };
|
8975 |
|
8976 | Set.prototype.sortBy = function sortBy (mapper, comparator) {
|
8977 | // Late binding
|
8978 | return OrderedSet(sortFactory(this, comparator, mapper));
|
8979 | };
|
8980 |
|
8981 | Set.prototype.wasAltered = function wasAltered () {
|
8982 | return this._map.wasAltered();
|
8983 | };
|
8984 |
|
8985 | Set.prototype.__iterate = function __iterate (fn, reverse) {
|
8986 | var this$1 = this;
|
8987 |
|
8988 | return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse);
|
8989 | };
|
8990 |
|
8991 | Set.prototype.__iterator = function __iterator (type, reverse) {
|
8992 | return this._map.__iterator(type, reverse);
|
8993 | };
|
8994 |
|
8995 | Set.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
8996 | if (ownerID === this.__ownerID) {
|
8997 | return this;
|
8998 | }
|
8999 | var newMap = this._map.__ensureOwner(ownerID);
|
9000 | if (!ownerID) {
|
9001 | if (this.size === 0) {
|
9002 | return this.__empty();
|
9003 | }
|
9004 | this.__ownerID = ownerID;
|
9005 | this._map = newMap;
|
9006 | return this;
|
9007 | }
|
9008 | return this.__make(newMap, ownerID);
|
9009 | };
|
9010 |
|
9011 | return Set;
|
9012 | }(SetCollection));
|
9013 |
|
9014 | Set$1.isSet = isSet;
|
9015 |
|
9016 | var SetPrototype = Set$1.prototype;
|
9017 | SetPrototype[IS_SET_SYMBOL] = true;
|
9018 | SetPrototype[DELETE] = SetPrototype.remove;
|
9019 | SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
|
9020 | SetPrototype.withMutations = withMutations;
|
9021 | SetPrototype.asImmutable = asImmutable;
|
9022 | SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
|
9023 | SetPrototype['@@transducer/step'] = function(result, arr) {
|
9024 | return result.add(arr);
|
9025 | };
|
9026 | SetPrototype['@@transducer/result'] = function(obj) {
|
9027 | return obj.asImmutable();
|
9028 | };
|
9029 |
|
9030 | SetPrototype.__empty = emptySet;
|
9031 | SetPrototype.__make = makeSet;
|
9032 |
|
9033 | function updateSet(set, newMap) {
|
9034 | if (set.__ownerID) {
|
9035 | set.size = newMap.size;
|
9036 | set._map = newMap;
|
9037 | return set;
|
9038 | }
|
9039 | return newMap === set._map
|
9040 | ? set
|
9041 | : newMap.size === 0
|
9042 | ? set.__empty()
|
9043 | : set.__make(newMap);
|
9044 | }
|
9045 |
|
9046 | function makeSet(map, ownerID) {
|
9047 | var set = Object.create(SetPrototype);
|
9048 | set.size = map ? map.size : 0;
|
9049 | set._map = map;
|
9050 | set.__ownerID = ownerID;
|
9051 | return set;
|
9052 | }
|
9053 |
|
9054 | var EMPTY_SET;
|
9055 | function emptySet() {
|
9056 | return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
|
9057 | }
|
9058 |
|
9059 | /**
|
9060 | * Returns a lazy seq of nums from start (inclusive) to end
|
9061 | * (exclusive), by step, where start defaults to 0, step to 1, and end to
|
9062 | * infinity. When start is equal to end, returns empty list.
|
9063 | */
|
9064 | var Range = /*@__PURE__*/(function (IndexedSeq$$1) {
|
9065 | function Range(start, end, step) {
|
9066 | if (!(this instanceof Range)) {
|
9067 | return new Range(start, end, step);
|
9068 | }
|
9069 | invariant(step !== 0, 'Cannot step a Range by 0');
|
9070 | start = start || 0;
|
9071 | if (end === undefined) {
|
9072 | end = Infinity;
|
9073 | }
|
9074 | step = step === undefined ? 1 : Math.abs(step);
|
9075 | if (end < start) {
|
9076 | step = -step;
|
9077 | }
|
9078 | this._start = start;
|
9079 | this._end = end;
|
9080 | this._step = step;
|
9081 | this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
|
9082 | if (this.size === 0) {
|
9083 | if (EMPTY_RANGE) {
|
9084 | return EMPTY_RANGE;
|
9085 | }
|
9086 | EMPTY_RANGE = this;
|
9087 | }
|
9088 | }
|
9089 |
|
9090 | if ( IndexedSeq$$1 ) Range.__proto__ = IndexedSeq$$1;
|
9091 | Range.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
|
9092 | Range.prototype.constructor = Range;
|
9093 |
|
9094 | Range.prototype.toString = function toString () {
|
9095 | if (this.size === 0) {
|
9096 | return 'Range []';
|
9097 | }
|
9098 | return (
|
9099 | 'Range [ ' +
|
9100 | this._start +
|
9101 | '...' +
|
9102 | this._end +
|
9103 | (this._step !== 1 ? ' by ' + this._step : '') +
|
9104 | ' ]'
|
9105 | );
|
9106 | };
|
9107 |
|
9108 | Range.prototype.get = function get (index, notSetValue) {
|
9109 | return this.has(index)
|
9110 | ? this._start + wrapIndex(this, index) * this._step
|
9111 | : notSetValue;
|
9112 | };
|
9113 |
|
9114 | Range.prototype.includes = function includes (searchValue) {
|
9115 | var possibleIndex = (searchValue - this._start) / this._step;
|
9116 | return (
|
9117 | possibleIndex >= 0 &&
|
9118 | possibleIndex < this.size &&
|
9119 | possibleIndex === Math.floor(possibleIndex)
|
9120 | );
|
9121 | };
|
9122 |
|
9123 | Range.prototype.slice = function slice (begin, end) {
|
9124 | if (wholeSlice(begin, end, this.size)) {
|
9125 | return this;
|
9126 | }
|
9127 | begin = resolveBegin(begin, this.size);
|
9128 | end = resolveEnd(end, this.size);
|
9129 | if (end <= begin) {
|
9130 | return new Range(0, 0);
|
9131 | }
|
9132 | return new Range(
|
9133 | this.get(begin, this._end),
|
9134 | this.get(end, this._end),
|
9135 | this._step
|
9136 | );
|
9137 | };
|
9138 |
|
9139 | Range.prototype.indexOf = function indexOf (searchValue) {
|
9140 | var offsetValue = searchValue - this._start;
|
9141 | if (offsetValue % this._step === 0) {
|
9142 | var index = offsetValue / this._step;
|
9143 | if (index >= 0 && index < this.size) {
|
9144 | return index;
|
9145 | }
|
9146 | }
|
9147 | return -1;
|
9148 | };
|
9149 |
|
9150 | Range.prototype.lastIndexOf = function lastIndexOf (searchValue) {
|
9151 | return this.indexOf(searchValue);
|
9152 | };
|
9153 |
|
9154 | Range.prototype.__iterate = function __iterate (fn, reverse) {
|
9155 | var size = this.size;
|
9156 | var step = this._step;
|
9157 | var value = reverse ? this._start + (size - 1) * step : this._start;
|
9158 | var i = 0;
|
9159 | while (i !== size) {
|
9160 | if (fn(value, reverse ? size - ++i : i++, this) === false) {
|
9161 | break;
|
9162 | }
|
9163 | value += reverse ? -step : step;
|
9164 | }
|
9165 | return i;
|
9166 | };
|
9167 |
|
9168 | Range.prototype.__iterator = function __iterator (type, reverse) {
|
9169 | var size = this.size;
|
9170 | var step = this._step;
|
9171 | var value = reverse ? this._start + (size - 1) * step : this._start;
|
9172 | var i = 0;
|
9173 | return new Iterator(function () {
|
9174 | if (i === size) {
|
9175 | return iteratorDone();
|
9176 | }
|
9177 | var v = value;
|
9178 | value += reverse ? -step : step;
|
9179 | return iteratorValue(type, reverse ? size - ++i : i++, v);
|
9180 | });
|
9181 | };
|
9182 |
|
9183 | Range.prototype.equals = function equals (other) {
|
9184 | return other instanceof Range
|
9185 | ? this._start === other._start &&
|
9186 | this._end === other._end &&
|
9187 | this._step === other._step
|
9188 | : deepEqual(this, other);
|
9189 | };
|
9190 |
|
9191 | return Range;
|
9192 | }(IndexedSeq));
|
9193 |
|
9194 | var EMPTY_RANGE;
|
9195 |
|
9196 | function getIn(collection, searchKeyPath, notSetValue) {
|
9197 | var keyPath = coerceKeyPath(searchKeyPath);
|
9198 | var i = 0;
|
9199 | while (i !== keyPath.length) {
|
9200 | collection = get(collection, keyPath[i++], NOT_SET);
|
9201 | if (collection === NOT_SET) {
|
9202 | return notSetValue;
|
9203 | }
|
9204 | }
|
9205 | return collection;
|
9206 | }
|
9207 |
|
9208 | function getIn$1(searchKeyPath, notSetValue) {
|
9209 | return getIn(this, searchKeyPath, notSetValue);
|
9210 | }
|
9211 |
|
9212 | function hasIn(collection, keyPath) {
|
9213 | return getIn(collection, keyPath, NOT_SET) !== NOT_SET;
|
9214 | }
|
9215 |
|
9216 | function hasIn$1(searchKeyPath) {
|
9217 | return hasIn(this, searchKeyPath);
|
9218 | }
|
9219 |
|
9220 | function toObject() {
|
9221 | assertNotInfinite(this.size);
|
9222 | var object = {};
|
9223 | this.__iterate(function (v, k) {
|
9224 | object[k] = v;
|
9225 | });
|
9226 | return object;
|
9227 | }
|
9228 |
|
9229 | // Note: all of these methods are deprecated.
|
9230 | Collection.isIterable = isCollection;
|
9231 | Collection.isKeyed = isKeyed;
|
9232 | Collection.isIndexed = isIndexed;
|
9233 | Collection.isAssociative = isAssociative;
|
9234 | Collection.isOrdered = isOrdered;
|
9235 |
|
9236 | Collection.Iterator = Iterator;
|
9237 |
|
9238 | mixin(Collection, {
|
9239 | // ### Conversion to other types
|
9240 |
|
9241 | toArray: function toArray() {
|
9242 | assertNotInfinite(this.size);
|
9243 | var array = new Array(this.size || 0);
|
9244 | var useTuples = isKeyed(this);
|
9245 | var i = 0;
|
9246 | this.__iterate(function (v, k) {
|
9247 | // Keyed collections produce an array of tuples.
|
9248 | array[i++] = useTuples ? [k, v] : v;
|
9249 | });
|
9250 | return array;
|
9251 | },
|
9252 |
|
9253 | toIndexedSeq: function toIndexedSeq() {
|
9254 | return new ToIndexedSequence(this);
|
9255 | },
|
9256 |
|
9257 | toJS: function toJS$1() {
|
9258 | return toJS(this);
|
9259 | },
|
9260 |
|
9261 | toKeyedSeq: function toKeyedSeq() {
|
9262 | return new ToKeyedSequence(this, true);
|
9263 | },
|
9264 |
|
9265 | toMap: function toMap() {
|
9266 | // Use Late Binding here to solve the circular dependency.
|
9267 | return Map$1(this.toKeyedSeq());
|
9268 | },
|
9269 |
|
9270 | toObject: toObject,
|
9271 |
|
9272 | toOrderedMap: function toOrderedMap() {
|
9273 | // Use Late Binding here to solve the circular dependency.
|
9274 | return OrderedMap(this.toKeyedSeq());
|
9275 | },
|
9276 |
|
9277 | toOrderedSet: function toOrderedSet() {
|
9278 | // Use Late Binding here to solve the circular dependency.
|
9279 | return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
|
9280 | },
|
9281 |
|
9282 | toSet: function toSet() {
|
9283 | // Use Late Binding here to solve the circular dependency.
|
9284 | return Set$1(isKeyed(this) ? this.valueSeq() : this);
|
9285 | },
|
9286 |
|
9287 | toSetSeq: function toSetSeq() {
|
9288 | return new ToSetSequence(this);
|
9289 | },
|
9290 |
|
9291 | toSeq: function toSeq() {
|
9292 | return isIndexed(this)
|
9293 | ? this.toIndexedSeq()
|
9294 | : isKeyed(this)
|
9295 | ? this.toKeyedSeq()
|
9296 | : this.toSetSeq();
|
9297 | },
|
9298 |
|
9299 | toStack: function toStack() {
|
9300 | // Use Late Binding here to solve the circular dependency.
|
9301 | return Stack(isKeyed(this) ? this.valueSeq() : this);
|
9302 | },
|
9303 |
|
9304 | toList: function toList() {
|
9305 | // Use Late Binding here to solve the circular dependency.
|
9306 | return List(isKeyed(this) ? this.valueSeq() : this);
|
9307 | },
|
9308 |
|
9309 | // ### Common JavaScript methods and properties
|
9310 |
|
9311 | toString: function toString() {
|
9312 | return '[Collection]';
|
9313 | },
|
9314 |
|
9315 | __toString: function __toString(head, tail) {
|
9316 | if (this.size === 0) {
|
9317 | return head + tail;
|
9318 | }
|
9319 | return (
|
9320 | head +
|
9321 | ' ' +
|
9322 | this.toSeq()
|
9323 | .map(this.__toStringMapper)
|
9324 | .join(', ') +
|
9325 | ' ' +
|
9326 | tail
|
9327 | );
|
9328 | },
|
9329 |
|
9330 | // ### ES6 Collection methods (ES6 Array and Map)
|
9331 |
|
9332 | concat: function concat() {
|
9333 | var values = [], len = arguments.length;
|
9334 | while ( len-- ) values[ len ] = arguments[ len ];
|
9335 |
|
9336 | return reify(this, concatFactory(this, values));
|
9337 | },
|
9338 |
|
9339 | includes: function includes(searchValue) {
|
9340 | return this.some(function (value) { return is(value, searchValue); });
|
9341 | },
|
9342 |
|
9343 | entries: function entries() {
|
9344 | return this.__iterator(ITERATE_ENTRIES);
|
9345 | },
|
9346 |
|
9347 | every: function every(predicate, context) {
|
9348 | assertNotInfinite(this.size);
|
9349 | var returnValue = true;
|
9350 | this.__iterate(function (v, k, c) {
|
9351 | if (!predicate.call(context, v, k, c)) {
|
9352 | returnValue = false;
|
9353 | return false;
|
9354 | }
|
9355 | });
|
9356 | return returnValue;
|
9357 | },
|
9358 |
|
9359 | filter: function filter(predicate, context) {
|
9360 | return reify(this, filterFactory(this, predicate, context, true));
|
9361 | },
|
9362 |
|
9363 | find: function find(predicate, context, notSetValue) {
|
9364 | var entry = this.findEntry(predicate, context);
|
9365 | return entry ? entry[1] : notSetValue;
|
9366 | },
|
9367 |
|
9368 | forEach: function forEach(sideEffect, context) {
|
9369 | assertNotInfinite(this.size);
|
9370 | return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
|
9371 | },
|
9372 |
|
9373 | join: function join(separator) {
|
9374 | assertNotInfinite(this.size);
|
9375 | separator = separator !== undefined ? '' + separator : ',';
|
9376 | var joined = '';
|
9377 | var isFirst = true;
|
9378 | this.__iterate(function (v) {
|
9379 | isFirst ? (isFirst = false) : (joined += separator);
|
9380 | joined += v !== null && v !== undefined ? v.toString() : '';
|
9381 | });
|
9382 | return joined;
|
9383 | },
|
9384 |
|
9385 | keys: function keys() {
|
9386 | return this.__iterator(ITERATE_KEYS);
|
9387 | },
|
9388 |
|
9389 | map: function map(mapper, context) {
|
9390 | return reify(this, mapFactory(this, mapper, context));
|
9391 | },
|
9392 |
|
9393 | reduce: function reduce$1(reducer, initialReduction, context) {
|
9394 | return reduce(
|
9395 | this,
|
9396 | reducer,
|
9397 | initialReduction,
|
9398 | context,
|
9399 | arguments.length < 2,
|
9400 | false
|
9401 | );
|
9402 | },
|
9403 |
|
9404 | reduceRight: function reduceRight(reducer, initialReduction, context) {
|
9405 | return reduce(
|
9406 | this,
|
9407 | reducer,
|
9408 | initialReduction,
|
9409 | context,
|
9410 | arguments.length < 2,
|
9411 | true
|
9412 | );
|
9413 | },
|
9414 |
|
9415 | reverse: function reverse() {
|
9416 | return reify(this, reverseFactory(this, true));
|
9417 | },
|
9418 |
|
9419 | slice: function slice(begin, end) {
|
9420 | return reify(this, sliceFactory(this, begin, end, true));
|
9421 | },
|
9422 |
|
9423 | some: function some(predicate, context) {
|
9424 | return !this.every(not(predicate), context);
|
9425 | },
|
9426 |
|
9427 | sort: function sort(comparator) {
|
9428 | return reify(this, sortFactory(this, comparator));
|
9429 | },
|
9430 |
|
9431 | values: function values() {
|
9432 | return this.__iterator(ITERATE_VALUES);
|
9433 | },
|
9434 |
|
9435 | // ### More sequential methods
|
9436 |
|
9437 | butLast: function butLast() {
|
9438 | return this.slice(0, -1);
|
9439 | },
|
9440 |
|
9441 | isEmpty: function isEmpty() {
|
9442 | return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
|
9443 | },
|
9444 |
|
9445 | count: function count(predicate, context) {
|
9446 | return ensureSize(
|
9447 | predicate ? this.toSeq().filter(predicate, context) : this
|
9448 | );
|
9449 | },
|
9450 |
|
9451 | countBy: function countBy(grouper, context) {
|
9452 | return countByFactory(this, grouper, context);
|
9453 | },
|
9454 |
|
9455 | equals: function equals(other) {
|
9456 | return deepEqual(this, other);
|
9457 | },
|
9458 |
|
9459 | entrySeq: function entrySeq() {
|
9460 | var collection = this;
|
9461 | if (collection._cache) {
|
9462 | // We cache as an entries array, so we can just return the cache!
|
9463 | return new ArraySeq(collection._cache);
|
9464 | }
|
9465 | var entriesSequence = collection
|
9466 | .toSeq()
|
9467 | .map(entryMapper)
|
9468 | .toIndexedSeq();
|
9469 | entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
|
9470 | return entriesSequence;
|
9471 | },
|
9472 |
|
9473 | filterNot: function filterNot(predicate, context) {
|
9474 | return this.filter(not(predicate), context);
|
9475 | },
|
9476 |
|
9477 | findEntry: function findEntry(predicate, context, notSetValue) {
|
9478 | var found = notSetValue;
|
9479 | this.__iterate(function (v, k, c) {
|
9480 | if (predicate.call(context, v, k, c)) {
|
9481 | found = [k, v];
|
9482 | return false;
|
9483 | }
|
9484 | });
|
9485 | return found;
|
9486 | },
|
9487 |
|
9488 | findKey: function findKey(predicate, context) {
|
9489 | var entry = this.findEntry(predicate, context);
|
9490 | return entry && entry[0];
|
9491 | },
|
9492 |
|
9493 | findLast: function findLast(predicate, context, notSetValue) {
|
9494 | return this.toKeyedSeq()
|
9495 | .reverse()
|
9496 | .find(predicate, context, notSetValue);
|
9497 | },
|
9498 |
|
9499 | findLastEntry: function findLastEntry(predicate, context, notSetValue) {
|
9500 | return this.toKeyedSeq()
|
9501 | .reverse()
|
9502 | .findEntry(predicate, context, notSetValue);
|
9503 | },
|
9504 |
|
9505 | findLastKey: function findLastKey(predicate, context) {
|
9506 | return this.toKeyedSeq()
|
9507 | .reverse()
|
9508 | .findKey(predicate, context);
|
9509 | },
|
9510 |
|
9511 | first: function first(notSetValue) {
|
9512 | return this.find(returnTrue, null, notSetValue);
|
9513 | },
|
9514 |
|
9515 | flatMap: function flatMap(mapper, context) {
|
9516 | return reify(this, flatMapFactory(this, mapper, context));
|
9517 | },
|
9518 |
|
9519 | flatten: function flatten(depth) {
|
9520 | return reify(this, flattenFactory(this, depth, true));
|
9521 | },
|
9522 |
|
9523 | fromEntrySeq: function fromEntrySeq() {
|
9524 | return new FromEntriesSequence(this);
|
9525 | },
|
9526 |
|
9527 | get: function get(searchKey, notSetValue) {
|
9528 | return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
|
9529 | },
|
9530 |
|
9531 | getIn: getIn$1,
|
9532 |
|
9533 | groupBy: function groupBy(grouper, context) {
|
9534 | return groupByFactory(this, grouper, context);
|
9535 | },
|
9536 |
|
9537 | has: function has(searchKey) {
|
9538 | return this.get(searchKey, NOT_SET) !== NOT_SET;
|
9539 | },
|
9540 |
|
9541 | hasIn: hasIn$1,
|
9542 |
|
9543 | isSubset: function isSubset(iter) {
|
9544 | iter = typeof iter.includes === 'function' ? iter : Collection(iter);
|
9545 | return this.every(function (value) { return iter.includes(value); });
|
9546 | },
|
9547 |
|
9548 | isSuperset: function isSuperset(iter) {
|
9549 | iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
|
9550 | return iter.isSubset(this);
|
9551 | },
|
9552 |
|
9553 | keyOf: function keyOf(searchValue) {
|
9554 | return this.findKey(function (value) { return is(value, searchValue); });
|
9555 | },
|
9556 |
|
9557 | keySeq: function keySeq() {
|
9558 | return this.toSeq()
|
9559 | .map(keyMapper)
|
9560 | .toIndexedSeq();
|
9561 | },
|
9562 |
|
9563 | last: function last(notSetValue) {
|
9564 | return this.toSeq()
|
9565 | .reverse()
|
9566 | .first(notSetValue);
|
9567 | },
|
9568 |
|
9569 | lastKeyOf: function lastKeyOf(searchValue) {
|
9570 | return this.toKeyedSeq()
|
9571 | .reverse()
|
9572 | .keyOf(searchValue);
|
9573 | },
|
9574 |
|
9575 | max: function max(comparator) {
|
9576 | return maxFactory(this, comparator);
|
9577 | },
|
9578 |
|
9579 | maxBy: function maxBy(mapper, comparator) {
|
9580 | return maxFactory(this, comparator, mapper);
|
9581 | },
|
9582 |
|
9583 | min: function min(comparator) {
|
9584 | return maxFactory(
|
9585 | this,
|
9586 | comparator ? neg(comparator) : defaultNegComparator
|
9587 | );
|
9588 | },
|
9589 |
|
9590 | minBy: function minBy(mapper, comparator) {
|
9591 | return maxFactory(
|
9592 | this,
|
9593 | comparator ? neg(comparator) : defaultNegComparator,
|
9594 | mapper
|
9595 | );
|
9596 | },
|
9597 |
|
9598 | rest: function rest() {
|
9599 | return this.slice(1);
|
9600 | },
|
9601 |
|
9602 | skip: function skip(amount) {
|
9603 | return amount === 0 ? this : this.slice(Math.max(0, amount));
|
9604 | },
|
9605 |
|
9606 | skipLast: function skipLast(amount) {
|
9607 | return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
|
9608 | },
|
9609 |
|
9610 | skipWhile: function skipWhile(predicate, context) {
|
9611 | return reify(this, skipWhileFactory(this, predicate, context, true));
|
9612 | },
|
9613 |
|
9614 | skipUntil: function skipUntil(predicate, context) {
|
9615 | return this.skipWhile(not(predicate), context);
|
9616 | },
|
9617 |
|
9618 | sortBy: function sortBy(mapper, comparator) {
|
9619 | return reify(this, sortFactory(this, comparator, mapper));
|
9620 | },
|
9621 |
|
9622 | take: function take(amount) {
|
9623 | return this.slice(0, Math.max(0, amount));
|
9624 | },
|
9625 |
|
9626 | takeLast: function takeLast(amount) {
|
9627 | return this.slice(-Math.max(0, amount));
|
9628 | },
|
9629 |
|
9630 | takeWhile: function takeWhile(predicate, context) {
|
9631 | return reify(this, takeWhileFactory(this, predicate, context));
|
9632 | },
|
9633 |
|
9634 | takeUntil: function takeUntil(predicate, context) {
|
9635 | return this.takeWhile(not(predicate), context);
|
9636 | },
|
9637 |
|
9638 | update: function update(fn) {
|
9639 | return fn(this);
|
9640 | },
|
9641 |
|
9642 | valueSeq: function valueSeq() {
|
9643 | return this.toIndexedSeq();
|
9644 | },
|
9645 |
|
9646 | // ### Hashable Object
|
9647 |
|
9648 | hashCode: function hashCode() {
|
9649 | return this.__hash || (this.__hash = hashCollection(this));
|
9650 | },
|
9651 |
|
9652 | // ### Internal
|
9653 |
|
9654 | // abstract __iterate(fn, reverse)
|
9655 |
|
9656 | // abstract __iterator(type, reverse)
|
9657 | });
|
9658 |
|
9659 | var CollectionPrototype = Collection.prototype;
|
9660 | CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
|
9661 | CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
|
9662 | CollectionPrototype.toJSON = CollectionPrototype.toArray;
|
9663 | CollectionPrototype.__toStringMapper = quoteString;
|
9664 | CollectionPrototype.inspect = CollectionPrototype.toSource = function() {
|
9665 | return this.toString();
|
9666 | };
|
9667 | CollectionPrototype.chain = CollectionPrototype.flatMap;
|
9668 | CollectionPrototype.contains = CollectionPrototype.includes;
|
9669 |
|
9670 | mixin(KeyedCollection, {
|
9671 | // ### More sequential methods
|
9672 |
|
9673 | flip: function flip() {
|
9674 | return reify(this, flipFactory(this));
|
9675 | },
|
9676 |
|
9677 | mapEntries: function mapEntries(mapper, context) {
|
9678 | var this$1 = this;
|
9679 |
|
9680 | var iterations = 0;
|
9681 | return reify(
|
9682 | this,
|
9683 | this.toSeq()
|
9684 | .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); })
|
9685 | .fromEntrySeq()
|
9686 | );
|
9687 | },
|
9688 |
|
9689 | mapKeys: function mapKeys(mapper, context) {
|
9690 | var this$1 = this;
|
9691 |
|
9692 | return reify(
|
9693 | this,
|
9694 | this.toSeq()
|
9695 | .flip()
|
9696 | .map(function (k, v) { return mapper.call(context, k, v, this$1); })
|
9697 | .flip()
|
9698 | );
|
9699 | },
|
9700 | });
|
9701 |
|
9702 | var KeyedCollectionPrototype = KeyedCollection.prototype;
|
9703 | KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
|
9704 | KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
|
9705 | KeyedCollectionPrototype.toJSON = toObject;
|
9706 | KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
|
9707 |
|
9708 | mixin(IndexedCollection, {
|
9709 | // ### Conversion to other types
|
9710 |
|
9711 | toKeyedSeq: function toKeyedSeq() {
|
9712 | return new ToKeyedSequence(this, false);
|
9713 | },
|
9714 |
|
9715 | // ### ES6 Collection methods (ES6 Array and Map)
|
9716 |
|
9717 | filter: function filter(predicate, context) {
|
9718 | return reify(this, filterFactory(this, predicate, context, false));
|
9719 | },
|
9720 |
|
9721 | findIndex: function findIndex(predicate, context) {
|
9722 | var entry = this.findEntry(predicate, context);
|
9723 | return entry ? entry[0] : -1;
|
9724 | },
|
9725 |
|
9726 | indexOf: function indexOf(searchValue) {
|
9727 | var key = this.keyOf(searchValue);
|
9728 | return key === undefined ? -1 : key;
|
9729 | },
|
9730 |
|
9731 | lastIndexOf: function lastIndexOf(searchValue) {
|
9732 | var key = this.lastKeyOf(searchValue);
|
9733 | return key === undefined ? -1 : key;
|
9734 | },
|
9735 |
|
9736 | reverse: function reverse() {
|
9737 | return reify(this, reverseFactory(this, false));
|
9738 | },
|
9739 |
|
9740 | slice: function slice(begin, end) {
|
9741 | return reify(this, sliceFactory(this, begin, end, false));
|
9742 | },
|
9743 |
|
9744 | splice: function splice(index, removeNum /*, ...values*/) {
|
9745 | var numArgs = arguments.length;
|
9746 | removeNum = Math.max(removeNum || 0, 0);
|
9747 | if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
|
9748 | return this;
|
9749 | }
|
9750 | // If index is negative, it should resolve relative to the size of the
|
9751 | // collection. However size may be expensive to compute if not cached, so
|
9752 | // only call count() if the number is in fact negative.
|
9753 | index = resolveBegin(index, index < 0 ? this.count() : this.size);
|
9754 | var spliced = this.slice(0, index);
|
9755 | return reify(
|
9756 | this,
|
9757 | numArgs === 1
|
9758 | ? spliced
|
9759 | : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
|
9760 | );
|
9761 | },
|
9762 |
|
9763 | // ### More collection methods
|
9764 |
|
9765 | findLastIndex: function findLastIndex(predicate, context) {
|
9766 | var entry = this.findLastEntry(predicate, context);
|
9767 | return entry ? entry[0] : -1;
|
9768 | },
|
9769 |
|
9770 | first: function first(notSetValue) {
|
9771 | return this.get(0, notSetValue);
|
9772 | },
|
9773 |
|
9774 | flatten: function flatten(depth) {
|
9775 | return reify(this, flattenFactory(this, depth, false));
|
9776 | },
|
9777 |
|
9778 | get: function get(index, notSetValue) {
|
9779 | index = wrapIndex(this, index);
|
9780 | return index < 0 ||
|
9781 | (this.size === Infinity || (this.size !== undefined && index > this.size))
|
9782 | ? notSetValue
|
9783 | : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
|
9784 | },
|
9785 |
|
9786 | has: function has(index) {
|
9787 | index = wrapIndex(this, index);
|
9788 | return (
|
9789 | index >= 0 &&
|
9790 | (this.size !== undefined
|
9791 | ? this.size === Infinity || index < this.size
|
9792 | : this.indexOf(index) !== -1)
|
9793 | );
|
9794 | },
|
9795 |
|
9796 | interpose: function interpose(separator) {
|
9797 | return reify(this, interposeFactory(this, separator));
|
9798 | },
|
9799 |
|
9800 | interleave: function interleave(/*...collections*/) {
|
9801 | var collections = [this].concat(arrCopy(arguments));
|
9802 | var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
|
9803 | var interleaved = zipped.flatten(true);
|
9804 | if (zipped.size) {
|
9805 | interleaved.size = zipped.size * collections.length;
|
9806 | }
|
9807 | return reify(this, interleaved);
|
9808 | },
|
9809 |
|
9810 | keySeq: function keySeq() {
|
9811 | return Range(0, this.size);
|
9812 | },
|
9813 |
|
9814 | last: function last(notSetValue) {
|
9815 | return this.get(-1, notSetValue);
|
9816 | },
|
9817 |
|
9818 | skipWhile: function skipWhile(predicate, context) {
|
9819 | return reify(this, skipWhileFactory(this, predicate, context, false));
|
9820 | },
|
9821 |
|
9822 | zip: function zip(/*, ...collections */) {
|
9823 | var collections = [this].concat(arrCopy(arguments));
|
9824 | return reify(this, zipWithFactory(this, defaultZipper, collections));
|
9825 | },
|
9826 |
|
9827 | zipAll: function zipAll(/*, ...collections */) {
|
9828 | var collections = [this].concat(arrCopy(arguments));
|
9829 | return reify(this, zipWithFactory(this, defaultZipper, collections, true));
|
9830 | },
|
9831 |
|
9832 | zipWith: function zipWith(zipper /*, ...collections */) {
|
9833 | var collections = arrCopy(arguments);
|
9834 | collections[0] = this;
|
9835 | return reify(this, zipWithFactory(this, zipper, collections));
|
9836 | },
|
9837 | });
|
9838 |
|
9839 | var IndexedCollectionPrototype = IndexedCollection.prototype;
|
9840 | IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
|
9841 | IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
|
9842 |
|
9843 | mixin(SetCollection, {
|
9844 | // ### ES6 Collection methods (ES6 Array and Map)
|
9845 |
|
9846 | get: function get(value, notSetValue) {
|
9847 | return this.has(value) ? value : notSetValue;
|
9848 | },
|
9849 |
|
9850 | includes: function includes(value) {
|
9851 | return this.has(value);
|
9852 | },
|
9853 |
|
9854 | // ### More sequential methods
|
9855 |
|
9856 | keySeq: function keySeq() {
|
9857 | return this.valueSeq();
|
9858 | },
|
9859 | });
|
9860 |
|
9861 | SetCollection.prototype.has = CollectionPrototype.includes;
|
9862 | SetCollection.prototype.contains = SetCollection.prototype.includes;
|
9863 |
|
9864 | // Mixin subclasses
|
9865 |
|
9866 | mixin(KeyedSeq, KeyedCollection.prototype);
|
9867 | mixin(IndexedSeq, IndexedCollection.prototype);
|
9868 | mixin(SetSeq, SetCollection.prototype);
|
9869 |
|
9870 | // #pragma Helper functions
|
9871 |
|
9872 | function reduce(collection, reducer, reduction, context, useFirst, reverse) {
|
9873 | assertNotInfinite(collection.size);
|
9874 | collection.__iterate(function (v, k, c) {
|
9875 | if (useFirst) {
|
9876 | useFirst = false;
|
9877 | reduction = v;
|
9878 | } else {
|
9879 | reduction = reducer.call(context, reduction, v, k, c);
|
9880 | }
|
9881 | }, reverse);
|
9882 | return reduction;
|
9883 | }
|
9884 |
|
9885 | function keyMapper(v, k) {
|
9886 | return k;
|
9887 | }
|
9888 |
|
9889 | function entryMapper(v, k) {
|
9890 | return [k, v];
|
9891 | }
|
9892 |
|
9893 | function not(predicate) {
|
9894 | return function() {
|
9895 | return !predicate.apply(this, arguments);
|
9896 | };
|
9897 | }
|
9898 |
|
9899 | function neg(predicate) {
|
9900 | return function() {
|
9901 | return -predicate.apply(this, arguments);
|
9902 | };
|
9903 | }
|
9904 |
|
9905 | function defaultZipper() {
|
9906 | return arrCopy(arguments);
|
9907 | }
|
9908 |
|
9909 | function defaultNegComparator(a, b) {
|
9910 | return a < b ? 1 : a > b ? -1 : 0;
|
9911 | }
|
9912 |
|
9913 | function hashCollection(collection) {
|
9914 | if (collection.size === Infinity) {
|
9915 | return 0;
|
9916 | }
|
9917 | var ordered = isOrdered(collection);
|
9918 | var keyed = isKeyed(collection);
|
9919 | var h = ordered ? 1 : 0;
|
9920 | var size = collection.__iterate(
|
9921 | keyed
|
9922 | ? ordered
|
9923 | ? function (v, k) {
|
9924 | h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
|
9925 | }
|
9926 | : function (v, k) {
|
9927 | h = (h + hashMerge(hash(v), hash(k))) | 0;
|
9928 | }
|
9929 | : ordered
|
9930 | ? function (v) {
|
9931 | h = (31 * h + hash(v)) | 0;
|
9932 | }
|
9933 | : function (v) {
|
9934 | h = (h + hash(v)) | 0;
|
9935 | }
|
9936 | );
|
9937 | return murmurHashOfSize(size, h);
|
9938 | }
|
9939 |
|
9940 | function murmurHashOfSize(size, h) {
|
9941 | h = imul(h, 0xcc9e2d51);
|
9942 | h = imul((h << 15) | (h >>> -15), 0x1b873593);
|
9943 | h = imul((h << 13) | (h >>> -13), 5);
|
9944 | h = ((h + 0xe6546b64) | 0) ^ size;
|
9945 | h = imul(h ^ (h >>> 16), 0x85ebca6b);
|
9946 | h = imul(h ^ (h >>> 13), 0xc2b2ae35);
|
9947 | h = smi(h ^ (h >>> 16));
|
9948 | return h;
|
9949 | }
|
9950 |
|
9951 | function hashMerge(a, b) {
|
9952 | return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
|
9953 | }
|
9954 |
|
9955 | var OrderedSet = /*@__PURE__*/(function (Set$$1) {
|
9956 | function OrderedSet(value) {
|
9957 | return value === null || value === undefined
|
9958 | ? emptyOrderedSet()
|
9959 | : isOrderedSet(value)
|
9960 | ? value
|
9961 | : emptyOrderedSet().withMutations(function (set) {
|
9962 | var iter = SetCollection(value);
|
9963 | assertNotInfinite(iter.size);
|
9964 | iter.forEach(function (v) { return set.add(v); });
|
9965 | });
|
9966 | }
|
9967 |
|
9968 | if ( Set$$1 ) OrderedSet.__proto__ = Set$$1;
|
9969 | OrderedSet.prototype = Object.create( Set$$1 && Set$$1.prototype );
|
9970 | OrderedSet.prototype.constructor = OrderedSet;
|
9971 |
|
9972 | OrderedSet.of = function of (/*...values*/) {
|
9973 | return this(arguments);
|
9974 | };
|
9975 |
|
9976 | OrderedSet.fromKeys = function fromKeys (value) {
|
9977 | return this(KeyedCollection(value).keySeq());
|
9978 | };
|
9979 |
|
9980 | OrderedSet.prototype.toString = function toString () {
|
9981 | return this.__toString('OrderedSet {', '}');
|
9982 | };
|
9983 |
|
9984 | return OrderedSet;
|
9985 | }(Set$1));
|
9986 |
|
9987 | OrderedSet.isOrderedSet = isOrderedSet;
|
9988 |
|
9989 | var OrderedSetPrototype = OrderedSet.prototype;
|
9990 | OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
|
9991 | OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
|
9992 | OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
|
9993 |
|
9994 | OrderedSetPrototype.__empty = emptyOrderedSet;
|
9995 | OrderedSetPrototype.__make = makeOrderedSet;
|
9996 |
|
9997 | function makeOrderedSet(map, ownerID) {
|
9998 | var set = Object.create(OrderedSetPrototype);
|
9999 | set.size = map ? map.size : 0;
|
10000 | set._map = map;
|
10001 | set.__ownerID = ownerID;
|
10002 | return set;
|
10003 | }
|
10004 |
|
10005 | var EMPTY_ORDERED_SET;
|
10006 | function emptyOrderedSet() {
|
10007 | return (
|
10008 | EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))
|
10009 | );
|
10010 | }
|
10011 |
|
10012 | var Record = function Record(defaultValues, name) {
|
10013 | var hasInitialized;
|
10014 |
|
10015 | var RecordType = function Record(values) {
|
10016 | var this$1 = this;
|
10017 |
|
10018 | if (values instanceof RecordType) {
|
10019 | return values;
|
10020 | }
|
10021 | if (!(this instanceof RecordType)) {
|
10022 | return new RecordType(values);
|
10023 | }
|
10024 | if (!hasInitialized) {
|
10025 | hasInitialized = true;
|
10026 | var keys = Object.keys(defaultValues);
|
10027 | var indices = (RecordTypePrototype._indices = {});
|
10028 | // Deprecated: left to attempt not to break any external code which
|
10029 | // relies on a ._name property existing on record instances.
|
10030 | // Use Record.getDescriptiveName() instead
|
10031 | RecordTypePrototype._name = name;
|
10032 | RecordTypePrototype._keys = keys;
|
10033 | RecordTypePrototype._defaultValues = defaultValues;
|
10034 | for (var i = 0; i < keys.length; i++) {
|
10035 | var propName = keys[i];
|
10036 | indices[propName] = i;
|
10037 | if (RecordTypePrototype[propName]) {
|
10038 | /* eslint-disable no-console */
|
10039 | typeof console === 'object' &&
|
10040 | console.warn &&
|
10041 | console.warn(
|
10042 | 'Cannot define ' +
|
10043 | recordName(this) +
|
10044 | ' with property "' +
|
10045 | propName +
|
10046 | '" since that property name is part of the Record API.'
|
10047 | );
|
10048 | /* eslint-enable no-console */
|
10049 | } else {
|
10050 | setProp(RecordTypePrototype, propName);
|
10051 | }
|
10052 | }
|
10053 | }
|
10054 | this.__ownerID = undefined;
|
10055 | this._values = List().withMutations(function (l) {
|
10056 | l.setSize(this$1._keys.length);
|
10057 | KeyedCollection(values).forEach(function (v, k) {
|
10058 | l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v);
|
10059 | });
|
10060 | });
|
10061 | };
|
10062 |
|
10063 | var RecordTypePrototype = (RecordType.prototype = Object.create(
|
10064 | RecordPrototype
|
10065 | ));
|
10066 | RecordTypePrototype.constructor = RecordType;
|
10067 |
|
10068 | if (name) {
|
10069 | RecordType.displayName = name;
|
10070 | }
|
10071 |
|
10072 | return RecordType;
|
10073 | };
|
10074 |
|
10075 | Record.prototype.toString = function toString () {
|
10076 | var str = recordName(this) + ' { ';
|
10077 | var keys = this._keys;
|
10078 | var k;
|
10079 | for (var i = 0, l = keys.length; i !== l; i++) {
|
10080 | k = keys[i];
|
10081 | str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
|
10082 | }
|
10083 | return str + ' }';
|
10084 | };
|
10085 |
|
10086 | Record.prototype.equals = function equals (other) {
|
10087 | return (
|
10088 | this === other ||
|
10089 | (other &&
|
10090 | this._keys === other._keys &&
|
10091 | recordSeq(this).equals(recordSeq(other)))
|
10092 | );
|
10093 | };
|
10094 |
|
10095 | Record.prototype.hashCode = function hashCode () {
|
10096 | return recordSeq(this).hashCode();
|
10097 | };
|
10098 |
|
10099 | // @pragma Access
|
10100 |
|
10101 | Record.prototype.has = function has (k) {
|
10102 | return this._indices.hasOwnProperty(k);
|
10103 | };
|
10104 |
|
10105 | Record.prototype.get = function get (k, notSetValue) {
|
10106 | if (!this.has(k)) {
|
10107 | return notSetValue;
|
10108 | }
|
10109 | var index = this._indices[k];
|
10110 | var value = this._values.get(index);
|
10111 | return value === undefined ? this._defaultValues[k] : value;
|
10112 | };
|
10113 |
|
10114 | // @pragma Modification
|
10115 |
|
10116 | Record.prototype.set = function set (k, v) {
|
10117 | if (this.has(k)) {
|
10118 | var newValues = this._values.set(
|
10119 | this._indices[k],
|
10120 | v === this._defaultValues[k] ? undefined : v
|
10121 | );
|
10122 | if (newValues !== this._values && !this.__ownerID) {
|
10123 | return makeRecord(this, newValues);
|
10124 | }
|
10125 | }
|
10126 | return this;
|
10127 | };
|
10128 |
|
10129 | Record.prototype.remove = function remove (k) {
|
10130 | return this.set(k);
|
10131 | };
|
10132 |
|
10133 | Record.prototype.clear = function clear () {
|
10134 | var newValues = this._values.clear().setSize(this._keys.length);
|
10135 | return this.__ownerID ? this : makeRecord(this, newValues);
|
10136 | };
|
10137 |
|
10138 | Record.prototype.wasAltered = function wasAltered () {
|
10139 | return this._values.wasAltered();
|
10140 | };
|
10141 |
|
10142 | Record.prototype.toSeq = function toSeq () {
|
10143 | return recordSeq(this);
|
10144 | };
|
10145 |
|
10146 | Record.prototype.toJS = function toJS$1 () {
|
10147 | return toJS(this);
|
10148 | };
|
10149 |
|
10150 | Record.prototype.entries = function entries () {
|
10151 | return this.__iterator(ITERATE_ENTRIES);
|
10152 | };
|
10153 |
|
10154 | Record.prototype.__iterator = function __iterator (type, reverse) {
|
10155 | return recordSeq(this).__iterator(type, reverse);
|
10156 | };
|
10157 |
|
10158 | Record.prototype.__iterate = function __iterate (fn, reverse) {
|
10159 | return recordSeq(this).__iterate(fn, reverse);
|
10160 | };
|
10161 |
|
10162 | Record.prototype.__ensureOwner = function __ensureOwner (ownerID) {
|
10163 | if (ownerID === this.__ownerID) {
|
10164 | return this;
|
10165 | }
|
10166 | var newValues = this._values.__ensureOwner(ownerID);
|
10167 | if (!ownerID) {
|
10168 | this.__ownerID = ownerID;
|
10169 | this._values = newValues;
|
10170 | return this;
|
10171 | }
|
10172 | return makeRecord(this, newValues, ownerID);
|
10173 | };
|
10174 |
|
10175 | Record.isRecord = isRecord;
|
10176 | Record.getDescriptiveName = recordName;
|
10177 | var RecordPrototype = Record.prototype;
|
10178 | RecordPrototype[IS_RECORD_SYMBOL] = true;
|
10179 | RecordPrototype[DELETE] = RecordPrototype.remove;
|
10180 | RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
|
10181 | RecordPrototype.getIn = getIn$1;
|
10182 | RecordPrototype.hasIn = CollectionPrototype.hasIn;
|
10183 | RecordPrototype.merge = merge;
|
10184 | RecordPrototype.mergeWith = mergeWith;
|
10185 | RecordPrototype.mergeIn = mergeIn;
|
10186 | RecordPrototype.mergeDeep = mergeDeep$1;
|
10187 | RecordPrototype.mergeDeepWith = mergeDeepWith$1;
|
10188 | RecordPrototype.mergeDeepIn = mergeDeepIn;
|
10189 | RecordPrototype.setIn = setIn$1;
|
10190 | RecordPrototype.update = update$1;
|
10191 | RecordPrototype.updateIn = updateIn$1;
|
10192 | RecordPrototype.withMutations = withMutations;
|
10193 | RecordPrototype.asMutable = asMutable;
|
10194 | RecordPrototype.asImmutable = asImmutable;
|
10195 | RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
|
10196 | RecordPrototype.toJSON = RecordPrototype.toObject =
|
10197 | CollectionPrototype.toObject;
|
10198 | RecordPrototype.inspect = RecordPrototype.toSource = function() {
|
10199 | return this.toString();
|
10200 | };
|
10201 |
|
10202 | function makeRecord(likeRecord, values, ownerID) {
|
10203 | var record = Object.create(Object.getPrototypeOf(likeRecord));
|
10204 | record._values = values;
|
10205 | record.__ownerID = ownerID;
|
10206 | return record;
|
10207 | }
|
10208 |
|
10209 | function recordName(record) {
|
10210 | return record.constructor.displayName || record.constructor.name || 'Record';
|
10211 | }
|
10212 |
|
10213 | function recordSeq(record) {
|
10214 | return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
|
10215 | }
|
10216 |
|
10217 | function setProp(prototype, name) {
|
10218 | try {
|
10219 | Object.defineProperty(prototype, name, {
|
10220 | get: function() {
|
10221 | return this.get(name);
|
10222 | },
|
10223 | set: function(value) {
|
10224 | invariant(this.__ownerID, 'Cannot set on an immutable record.');
|
10225 | this.set(name, value);
|
10226 | },
|
10227 | });
|
10228 | } catch (error) {
|
10229 | // Object.defineProperty failed. Probably IE8.
|
10230 | }
|
10231 | }
|
10232 |
|
10233 | /**
|
10234 | * Returns a lazy Seq of `value` repeated `times` times. When `times` is
|
10235 | * undefined, returns an infinite sequence of `value`.
|
10236 | */
|
10237 | var Repeat = /*@__PURE__*/(function (IndexedSeq$$1) {
|
10238 | function Repeat(value, times) {
|
10239 | if (!(this instanceof Repeat)) {
|
10240 | return new Repeat(value, times);
|
10241 | }
|
10242 | this._value = value;
|
10243 | this.size = times === undefined ? Infinity : Math.max(0, times);
|
10244 | if (this.size === 0) {
|
10245 | if (EMPTY_REPEAT) {
|
10246 | return EMPTY_REPEAT;
|
10247 | }
|
10248 | EMPTY_REPEAT = this;
|
10249 | }
|
10250 | }
|
10251 |
|
10252 | if ( IndexedSeq$$1 ) Repeat.__proto__ = IndexedSeq$$1;
|
10253 | Repeat.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
|
10254 | Repeat.prototype.constructor = Repeat;
|
10255 |
|
10256 | Repeat.prototype.toString = function toString () {
|
10257 | if (this.size === 0) {
|
10258 | return 'Repeat []';
|
10259 | }
|
10260 | return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
|
10261 | };
|
10262 |
|
10263 | Repeat.prototype.get = function get (index, notSetValue) {
|
10264 | return this.has(index) ? this._value : notSetValue;
|
10265 | };
|
10266 |
|
10267 | Repeat.prototype.includes = function includes (searchValue) {
|
10268 | return is(this._value, searchValue);
|
10269 | };
|
10270 |
|
10271 | Repeat.prototype.slice = function slice (begin, end) {
|
10272 | var size = this.size;
|
10273 | return wholeSlice(begin, end, size)
|
10274 | ? this
|
10275 | : new Repeat(
|
10276 | this._value,
|
10277 | resolveEnd(end, size) - resolveBegin(begin, size)
|
10278 | );
|
10279 | };
|
10280 |
|
10281 | Repeat.prototype.reverse = function reverse () {
|
10282 | return this;
|
10283 | };
|
10284 |
|
10285 | Repeat.prototype.indexOf = function indexOf (searchValue) {
|
10286 | if (is(this._value, searchValue)) {
|
10287 | return 0;
|
10288 | }
|
10289 | return -1;
|
10290 | };
|
10291 |
|
10292 | Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) {
|
10293 | if (is(this._value, searchValue)) {
|
10294 | return this.size;
|
10295 | }
|
10296 | return -1;
|
10297 | };
|
10298 |
|
10299 | Repeat.prototype.__iterate = function __iterate (fn, reverse) {
|
10300 | var size = this.size;
|
10301 | var i = 0;
|
10302 | while (i !== size) {
|
10303 | if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
|
10304 | break;
|
10305 | }
|
10306 | }
|
10307 | return i;
|
10308 | };
|
10309 |
|
10310 | Repeat.prototype.__iterator = function __iterator (type, reverse) {
|
10311 | var this$1 = this;
|
10312 |
|
10313 | var size = this.size;
|
10314 | var i = 0;
|
10315 | return new Iterator(
|
10316 | function () { return i === size
|
10317 | ? iteratorDone()
|
10318 | : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); }
|
10319 | );
|
10320 | };
|
10321 |
|
10322 | Repeat.prototype.equals = function equals (other) {
|
10323 | return other instanceof Repeat
|
10324 | ? is(this._value, other._value)
|
10325 | : deepEqual(other);
|
10326 | };
|
10327 |
|
10328 | return Repeat;
|
10329 | }(IndexedSeq));
|
10330 |
|
10331 | var EMPTY_REPEAT;
|
10332 |
|
10333 | function fromJS(value, converter) {
|
10334 | return fromJSWith(
|
10335 | [],
|
10336 | converter || defaultConverter,
|
10337 | value,
|
10338 | '',
|
10339 | converter && converter.length > 2 ? [] : undefined,
|
10340 | { '': value }
|
10341 | );
|
10342 | }
|
10343 |
|
10344 | function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
|
10345 | var toSeq = Array.isArray(value)
|
10346 | ? IndexedSeq
|
10347 | : isPlainObj(value)
|
10348 | ? KeyedSeq
|
10349 | : null;
|
10350 | if (toSeq) {
|
10351 | if (~stack.indexOf(value)) {
|
10352 | throw new TypeError('Cannot convert circular structure to Immutable');
|
10353 | }
|
10354 | stack.push(value);
|
10355 | keyPath && key !== '' && keyPath.push(key);
|
10356 | var converted = converter.call(
|
10357 | parentValue,
|
10358 | key,
|
10359 | toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }
|
10360 | ),
|
10361 | keyPath && keyPath.slice()
|
10362 | );
|
10363 | stack.pop();
|
10364 | keyPath && keyPath.pop();
|
10365 | return converted;
|
10366 | }
|
10367 | return value;
|
10368 | }
|
10369 |
|
10370 | function defaultConverter(k, v) {
|
10371 | return isKeyed(v) ? v.toMap() : v.toList();
|
10372 | }
|
10373 |
|
10374 | var version$1 = "4.0.0-rc.11";
|
10375 |
|
10376 | var Immutable = {
|
10377 | version: version$1,
|
10378 |
|
10379 | Collection: Collection,
|
10380 | // Note: Iterable is deprecated
|
10381 | Iterable: Collection,
|
10382 |
|
10383 | Seq: Seq,
|
10384 | Map: Map$1,
|
10385 | OrderedMap: OrderedMap,
|
10386 | List: List,
|
10387 | Stack: Stack,
|
10388 | Set: Set$1,
|
10389 | OrderedSet: OrderedSet,
|
10390 |
|
10391 | Record: Record,
|
10392 | Range: Range,
|
10393 | Repeat: Repeat,
|
10394 |
|
10395 | is: is,
|
10396 | fromJS: fromJS,
|
10397 | hash: hash,
|
10398 |
|
10399 | isImmutable: isImmutable,
|
10400 | isCollection: isCollection,
|
10401 | isKeyed: isKeyed,
|
10402 | isIndexed: isIndexed,
|
10403 | isAssociative: isAssociative,
|
10404 | isOrdered: isOrdered,
|
10405 | isValueObject: isValueObject,
|
10406 | isSeq: isSeq,
|
10407 | isList: isList,
|
10408 | isMap: isMap,
|
10409 | isOrderedMap: isOrderedMap,
|
10410 | isStack: isStack,
|
10411 | isSet: isSet,
|
10412 | isOrderedSet: isOrderedSet,
|
10413 | isRecord: isRecord,
|
10414 |
|
10415 | get: get,
|
10416 | getIn: getIn,
|
10417 | has: has,
|
10418 | hasIn: hasIn,
|
10419 | merge: merge$1,
|
10420 | mergeDeep: mergeDeep,
|
10421 | mergeWith: mergeWith$1,
|
10422 | mergeDeepWith: mergeDeepWith,
|
10423 | remove: remove,
|
10424 | removeIn: removeIn,
|
10425 | set: set,
|
10426 | setIn: setIn,
|
10427 | update: update,
|
10428 | updateIn: updateIn,
|
10429 | };
|
10430 |
|
10431 | var OptionTypes;
|
10432 | (function (OptionTypes) {
|
10433 | OptionTypes[OptionTypes["IGNORED_LABELS"] = 0] = "IGNORED_LABELS";
|
10434 | OptionTypes[OptionTypes["ACCESSED_NODES"] = 1] = "ACCESSED_NODES";
|
10435 | OptionTypes[OptionTypes["ARGUMENTS_VARIABLES"] = 2] = "ARGUMENTS_VARIABLES";
|
10436 | OptionTypes[OptionTypes["ASSIGNED_NODES"] = 3] = "ASSIGNED_NODES";
|
10437 | OptionTypes[OptionTypes["IGNORE_BREAK_STATEMENTS"] = 4] = "IGNORE_BREAK_STATEMENTS";
|
10438 | OptionTypes[OptionTypes["IGNORE_RETURN_AWAIT_YIELD"] = 5] = "IGNORE_RETURN_AWAIT_YIELD";
|
10439 | OptionTypes[OptionTypes["NODES_CALLED_AT_PATH_WITH_OPTIONS"] = 6] = "NODES_CALLED_AT_PATH_WITH_OPTIONS";
|
10440 | OptionTypes[OptionTypes["REPLACED_VARIABLE_INITS"] = 7] = "REPLACED_VARIABLE_INITS";
|
10441 | OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ACCESSED_AT_PATH"] = 8] = "RETURN_EXPRESSIONS_ACCESSED_AT_PATH";
|
10442 | OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"] = 9] = "RETURN_EXPRESSIONS_ASSIGNED_AT_PATH";
|
10443 | OptionTypes[OptionTypes["RETURN_EXPRESSIONS_CALLED_AT_PATH"] = 10] = "RETURN_EXPRESSIONS_CALLED_AT_PATH";
|
10444 | })(OptionTypes || (OptionTypes = {}));
|
10445 | var RESULT_KEY = {};
|
10446 | var ExecutionPathOptions = /** @class */ (function () {
|
10447 | function ExecutionPathOptions(optionValues) {
|
10448 | this.optionValues = optionValues;
|
10449 | }
|
10450 | ExecutionPathOptions.create = function () {
|
10451 | return new this(Immutable.Map());
|
10452 | };
|
10453 | ExecutionPathOptions.prototype.addAccessedNodeAtPath = function (path, node) {
|
10454 | return this.setIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]), true);
|
10455 | };
|
10456 | ExecutionPathOptions.prototype.addAccessedReturnExpressionAtPath = function (path, callExpression) {
|
10457 | return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
|
10458 | };
|
10459 | ExecutionPathOptions.prototype.addAssignedNodeAtPath = function (path, node) {
|
10460 | return this.setIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]), true);
|
10461 | };
|
10462 | ExecutionPathOptions.prototype.addAssignedReturnExpressionAtPath = function (path, callExpression) {
|
10463 | return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
|
10464 | };
|
10465 | ExecutionPathOptions.prototype.addCalledNodeAtPathWithOptions = function (path, node, callOptions) {
|
10466 | return this.setIn([OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, node].concat(path, [RESULT_KEY, callOptions]), true);
|
10467 | };
|
10468 | ExecutionPathOptions.prototype.addCalledReturnExpressionAtPath = function (path, callExpression) {
|
10469 | return this.setIn([OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
|
10470 | };
|
10471 | ExecutionPathOptions.prototype.getArgumentsVariables = function () {
|
10472 | return (this.get(OptionTypes.ARGUMENTS_VARIABLES) || []);
|
10473 | };
|
10474 | ExecutionPathOptions.prototype.getHasEffectsWhenCalledOptions = function () {
|
10475 | return this.setIgnoreReturnAwaitYield()
|
10476 | .setIgnoreBreakStatements(false)
|
10477 | .setIgnoreNoLabels();
|
10478 | };
|
10479 | ExecutionPathOptions.prototype.getReplacedVariableInit = function (variable) {
|
10480 | return this.optionValues.getIn([OptionTypes.REPLACED_VARIABLE_INITS, variable]);
|
10481 | };
|
10482 | ExecutionPathOptions.prototype.hasNodeBeenAccessedAtPath = function (path, node) {
|
10483 | return this.optionValues.getIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]));
|
10484 | };
|
10485 | ExecutionPathOptions.prototype.hasNodeBeenAssignedAtPath = function (path, node) {
|
10486 | return this.optionValues.getIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]));
|
10487 | };
|
10488 | ExecutionPathOptions.prototype.hasNodeBeenCalledAtPathWithOptions = function (path, node, callOptions) {
|
10489 | var previousCallOptions = this.optionValues.getIn([
|
10490 | OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS,
|
10491 | node
|
10492 | ].concat(path, [
|
10493 | RESULT_KEY
|
10494 | ]));
|
10495 | return (previousCallOptions &&
|
10496 | previousCallOptions.find(function (_, otherCallOptions) {
|
10497 | return otherCallOptions.equals(callOptions);
|
10498 | }));
|
10499 | };
|
10500 | ExecutionPathOptions.prototype.hasReturnExpressionBeenAccessedAtPath = function (path, callExpression) {
|
10501 | return this.optionValues.getIn([
|
10502 | OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH,
|
10503 | callExpression
|
10504 | ].concat(path, [
|
10505 | RESULT_KEY
|
10506 | ]));
|
10507 | };
|
10508 | ExecutionPathOptions.prototype.hasReturnExpressionBeenAssignedAtPath = function (path, callExpression) {
|
10509 | return this.optionValues.getIn([
|
10510 | OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH,
|
10511 | callExpression
|
10512 | ].concat(path, [
|
10513 | RESULT_KEY
|
10514 | ]));
|
10515 | };
|
10516 | ExecutionPathOptions.prototype.hasReturnExpressionBeenCalledAtPath = function (path, callExpression) {
|
10517 | return this.optionValues.getIn([
|
10518 | OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH,
|
10519 | callExpression
|
10520 | ].concat(path, [
|
10521 | RESULT_KEY
|
10522 | ]));
|
10523 | };
|
10524 | ExecutionPathOptions.prototype.ignoreBreakStatements = function () {
|
10525 | return this.get(OptionTypes.IGNORE_BREAK_STATEMENTS);
|
10526 | };
|
10527 | ExecutionPathOptions.prototype.ignoreLabel = function (labelName) {
|
10528 | return this.optionValues.getIn([OptionTypes.IGNORED_LABELS, labelName]);
|
10529 | };
|
10530 | ExecutionPathOptions.prototype.ignoreReturnAwaitYield = function () {
|
10531 | return this.get(OptionTypes.IGNORE_RETURN_AWAIT_YIELD);
|
10532 | };
|
10533 | ExecutionPathOptions.prototype.replaceVariableInit = function (variable, init) {
|
10534 | return this.setIn([OptionTypes.REPLACED_VARIABLE_INITS, variable], init);
|
10535 | };
|
10536 | ExecutionPathOptions.prototype.setArgumentsVariables = function (variables) {
|
10537 | return this.set(OptionTypes.ARGUMENTS_VARIABLES, variables);
|
10538 | };
|
10539 | ExecutionPathOptions.prototype.setIgnoreBreakStatements = function (value) {
|
10540 | if (value === void 0) { value = true; }
|
10541 | return this.set(OptionTypes.IGNORE_BREAK_STATEMENTS, value);
|
10542 | };
|
10543 | ExecutionPathOptions.prototype.setIgnoreLabel = function (labelName) {
|
10544 | return this.setIn([OptionTypes.IGNORED_LABELS, labelName], true);
|
10545 | };
|
10546 | ExecutionPathOptions.prototype.setIgnoreNoLabels = function () {
|
10547 | return this.remove(OptionTypes.IGNORED_LABELS);
|
10548 | };
|
10549 | ExecutionPathOptions.prototype.setIgnoreReturnAwaitYield = function (value) {
|
10550 | if (value === void 0) { value = true; }
|
10551 | return this.set(OptionTypes.IGNORE_RETURN_AWAIT_YIELD, value);
|
10552 | };
|
10553 | ExecutionPathOptions.prototype.get = function (option) {
|
10554 | return this.optionValues.get(option);
|
10555 | };
|
10556 | ExecutionPathOptions.prototype.remove = function (option) {
|
10557 | return new ExecutionPathOptions(this.optionValues.remove(option));
|
10558 | };
|
10559 | ExecutionPathOptions.prototype.set = function (option, value) {
|
10560 | return new ExecutionPathOptions(this.optionValues.set(option, value));
|
10561 | };
|
10562 | ExecutionPathOptions.prototype.setIn = function (optionPath, value) {
|
10563 | return new ExecutionPathOptions(this.optionValues.setIn(optionPath, value));
|
10564 | };
|
10565 | return ExecutionPathOptions;
|
10566 | }());
|
10567 |
|
10568 | var keys = {
|
10569 | Literal: [],
|
10570 | Program: ['body']
|
10571 | };
|
10572 | function getAndCreateKeys(esTreeNode) {
|
10573 | keys[esTreeNode.type] = Object.keys(esTreeNode).filter(function (key) { return typeof esTreeNode[key] === 'object'; });
|
10574 | return keys[esTreeNode.type];
|
10575 | }
|
10576 |
|
10577 | var NEW_EXECUTION_PATH = ExecutionPathOptions.create();
|
10578 | var NodeBase = /** @class */ (function () {
|
10579 | function NodeBase(esTreeNode, parent, parentScope) {
|
10580 | this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
|
10581 | this.parent = parent;
|
10582 | this.context = parent.context;
|
10583 | this.createScope(parentScope);
|
10584 | this.parseNode(esTreeNode);
|
10585 | this.initialise();
|
10586 | this.context.magicString.addSourcemapLocation(this.start);
|
10587 | this.context.magicString.addSourcemapLocation(this.end);
|
10588 | }
|
10589 | /**
|
10590 | * Override this to bind assignments to variables and do any initialisations that
|
10591 | * require the scopes to be populated with variables.
|
10592 | */
|
10593 | NodeBase.prototype.bind = function () {
|
10594 | for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
|
10595 | var key = _a[_i];
|
10596 | var value = this[key];
|
10597 | if (value === null || key === 'annotations')
|
10598 | continue;
|
10599 | if (Array.isArray(value)) {
|
10600 | for (var _b = 0, value_1 = value; _b < value_1.length; _b++) {
|
10601 | var child = value_1[_b];
|
10602 | if (child !== null)
|
10603 | child.bind();
|
10604 | }
|
10605 | }
|
10606 | else {
|
10607 | value.bind();
|
10608 | }
|
10609 | }
|
10610 | };
|
10611 | /**
|
10612 | * Override if this node should receive a different scope than the parent scope.
|
10613 | */
|
10614 | NodeBase.prototype.createScope = function (parentScope) {
|
10615 | this.scope = parentScope;
|
10616 | };
|
10617 | NodeBase.prototype.declare = function (_kind, _init) { };
|
10618 | NodeBase.prototype.deoptimizePath = function (_path) { };
|
10619 | NodeBase.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
|
10620 | return UNKNOWN_VALUE;
|
10621 | };
|
10622 | NodeBase.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
|
10623 | return UNKNOWN_EXPRESSION;
|
10624 | };
|
10625 | NodeBase.prototype.hasEffects = function (options) {
|
10626 | for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
|
10627 | var key = _a[_i];
|
10628 | var value = this[key];
|
10629 | if (value === null || key === 'annotations')
|
10630 | continue;
|
10631 | if (Array.isArray(value)) {
|
10632 | for (var _b = 0, value_2 = value; _b < value_2.length; _b++) {
|
10633 | var child = value_2[_b];
|
10634 | if (child !== null && child.hasEffects(options))
|
10635 | return true;
|
10636 | }
|
10637 | }
|
10638 | else if (value.hasEffects(options))
|
10639 | return true;
|
10640 | }
|
10641 | return false;
|
10642 | };
|
10643 | NodeBase.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
10644 | return path.length > 0;
|
10645 | };
|
10646 | NodeBase.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
|
10647 | return true;
|
10648 | };
|
10649 | NodeBase.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
|
10650 | return true;
|
10651 | };
|
10652 | NodeBase.prototype.include = function (includeAllChildrenRecursively) {
|
10653 | this.included = true;
|
10654 | for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
|
10655 | var key = _a[_i];
|
10656 | var value = this[key];
|
10657 | if (value === null || key === 'annotations')
|
10658 | continue;
|
10659 | if (Array.isArray(value)) {
|
10660 | for (var _b = 0, value_3 = value; _b < value_3.length; _b++) {
|
10661 | var child = value_3[_b];
|
10662 | if (child !== null)
|
10663 | child.include(includeAllChildrenRecursively);
|
10664 | }
|
10665 | }
|
10666 | else {
|
10667 | value.include(includeAllChildrenRecursively);
|
10668 | }
|
10669 | }
|
10670 | };
|
10671 | NodeBase.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
|
10672 | this.include(includeAllChildrenRecursively);
|
10673 | };
|
10674 | /**
|
10675 | * Override to perform special initialisation steps after the scope is initialised
|
10676 | */
|
10677 | NodeBase.prototype.initialise = function () {
|
10678 | this.included = false;
|
10679 | };
|
10680 | NodeBase.prototype.insertSemicolon = function (code) {
|
10681 | if (code.original[this.end - 1] !== ';') {
|
10682 | code.appendLeft(this.end, ';');
|
10683 | }
|
10684 | };
|
10685 | NodeBase.prototype.locate = function () {
|
10686 | // useful for debugging
|
10687 | var location = locate(this.context.code, this.start, { offsetLine: 1 });
|
10688 | location.file = this.context.fileName;
|
10689 | location.toString = function () { return JSON.stringify(location); };
|
10690 | return location;
|
10691 | };
|
10692 | NodeBase.prototype.parseNode = function (esTreeNode) {
|
10693 | for (var _i = 0, _a = Object.keys(esTreeNode); _i < _a.length; _i++) {
|
10694 | var key = _a[_i];
|
10695 | // That way, we can override this function to add custom initialisation and then call super.parseNode
|
10696 | if (this.hasOwnProperty(key))
|
10697 | continue;
|
10698 | var value = esTreeNode[key];
|
10699 | if (typeof value !== 'object' || value === null || key === 'annotations') {
|
10700 | this[key] = value;
|
10701 | }
|
10702 | else if (Array.isArray(value)) {
|
10703 | this[key] = [];
|
10704 | for (var _b = 0, value_4 = value; _b < value_4.length; _b++) {
|
10705 | var child = value_4[_b];
|
10706 | this[key].push(child === null
|
10707 | ? null
|
10708 | : new (this.context.nodeConstructors[child.type] ||
|
10709 | this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
|
10710 | }
|
10711 | }
|
10712 | else {
|
10713 | this[key] = new (this.context.nodeConstructors[value.type] ||
|
10714 | this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
|
10715 | }
|
10716 | }
|
10717 | };
|
10718 | NodeBase.prototype.render = function (code, options) {
|
10719 | for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
|
10720 | var key = _a[_i];
|
10721 | var value = this[key];
|
10722 | if (value === null || key === 'annotations')
|
10723 | continue;
|
10724 | if (Array.isArray(value)) {
|
10725 | for (var _b = 0, value_5 = value; _b < value_5.length; _b++) {
|
10726 | var child = value_5[_b];
|
10727 | if (child !== null)
|
10728 | child.render(code, options);
|
10729 | }
|
10730 | }
|
10731 | else {
|
10732 | value.render(code, options);
|
10733 | }
|
10734 | }
|
10735 | };
|
10736 | NodeBase.prototype.shouldBeIncluded = function () {
|
10737 | return this.included || this.hasEffects(NEW_EXECUTION_PATH);
|
10738 | };
|
10739 | NodeBase.prototype.toString = function () {
|
10740 | return this.context.code.slice(this.start, this.end);
|
10741 | };
|
10742 | return NodeBase;
|
10743 | }());
|
10744 |
|
10745 | var ClassNode = /** @class */ (function (_super) {
|
10746 | __extends(ClassNode, _super);
|
10747 | function ClassNode() {
|
10748 | return _super !== null && _super.apply(this, arguments) || this;
|
10749 | }
|
10750 | ClassNode.prototype.createScope = function (parentScope) {
|
10751 | this.scope = new ChildScope(parentScope);
|
10752 | };
|
10753 | ClassNode.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
10754 | return path.length > 1;
|
10755 | };
|
10756 | ClassNode.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
|
10757 | return path.length > 1;
|
10758 | };
|
10759 | ClassNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
10760 | return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
|
10761 | (this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)));
|
10762 | };
|
10763 | ClassNode.prototype.initialise = function () {
|
10764 | this.included = false;
|
10765 | if (this.id !== null) {
|
10766 | this.id.declare('class', this);
|
10767 | }
|
10768 | };
|
10769 | return ClassNode;
|
10770 | }(NodeBase));
|
10771 |
|
10772 | function isClassDeclaration(node) {
|
10773 | return node.type === ClassDeclaration;
|
10774 | }
|
10775 | var ClassDeclaration$1 = /** @class */ (function (_super) {
|
10776 | __extends(ClassDeclaration, _super);
|
10777 | function ClassDeclaration() {
|
10778 | return _super !== null && _super.apply(this, arguments) || this;
|
10779 | }
|
10780 | ClassDeclaration.prototype.initialise = function () {
|
10781 | _super.prototype.initialise.call(this);
|
10782 | if (this.id !== null) {
|
10783 | this.id.variable.isId = true;
|
10784 | }
|
10785 | };
|
10786 | ClassDeclaration.prototype.parseNode = function (esTreeNode) {
|
10787 | if (esTreeNode.id !== null) {
|
10788 | this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
|
10789 | }
|
10790 | _super.prototype.parseNode.call(this, esTreeNode);
|
10791 | };
|
10792 | ClassDeclaration.prototype.render = function (code, options) {
|
10793 | if (options.format === 'system' && this.id && this.id.variable.exportName) {
|
10794 | code.appendLeft(this.end, " exports('" + this.id.variable.exportName + "', " + this.id.variable.getName() + ");");
|
10795 | }
|
10796 | _super.prototype.render.call(this, code, options);
|
10797 | };
|
10798 | return ClassDeclaration;
|
10799 | }(ClassNode));
|
10800 |
|
10801 | var getParameterVariable = function (path, options) {
|
10802 | var firstArgNum = parseInt(path[0], 10);
|
10803 | return ((firstArgNum < options.getArgumentsVariables().length &&
|
10804 | options.getArgumentsVariables()[firstArgNum]) ||
|
10805 | UNKNOWN_EXPRESSION);
|
10806 | };
|
10807 | var ArgumentsVariable = /** @class */ (function (_super) {
|
10808 | __extends(ArgumentsVariable, _super);
|
10809 | function ArgumentsVariable(parameters, context) {
|
10810 | var _this = _super.call(this, 'arguments', null, UNKNOWN_EXPRESSION, context) || this;
|
10811 | _this.parameters = parameters;
|
10812 | return _this;
|
10813 | }
|
10814 | ArgumentsVariable.prototype.deoptimizePath = function (path) {
|
10815 | var firstArgNum = parseInt(path[0], 10);
|
10816 | if (path.length > 0) {
|
10817 | if (firstArgNum >= 0 && this.parameters[firstArgNum]) {
|
10818 | this.parameters[firstArgNum].deoptimizePath(path.slice(1));
|
10819 | }
|
10820 | }
|
10821 | };
|
10822 | ArgumentsVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
10823 | return (path.length > 1 &&
|
10824 | getParameterVariable(path, options).hasEffectsWhenAccessedAtPath(path.slice(1), options));
|
10825 | };
|
10826 | ArgumentsVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
10827 | return (path.length === 0 ||
|
10828 | this.included ||
|
10829 | getParameterVariable(path, options).hasEffectsWhenAssignedAtPath(path.slice(1), options));
|
10830 | };
|
10831 | ArgumentsVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
10832 | if (path.length === 0) {
|
10833 | return true;
|
10834 | }
|
10835 | return getParameterVariable(path, options).hasEffectsWhenCalledAtPath(path.slice(1), callOptions, options);
|
10836 | };
|
10837 | return ArgumentsVariable;
|
10838 | }(LocalVariable));
|
10839 |
|
10840 | var ThisVariable = /** @class */ (function (_super) {
|
10841 | __extends(ThisVariable, _super);
|
10842 | function ThisVariable(context) {
|
10843 | return _super.call(this, 'this', null, null, context) || this;
|
10844 | }
|
10845 | ThisVariable.prototype._getInit = function (options) {
|
10846 | return options.getReplacedVariableInit(this) || UNKNOWN_EXPRESSION;
|
10847 | };
|
10848 | ThisVariable.prototype.getLiteralValueAtPath = function () {
|
10849 | return UNKNOWN_VALUE;
|
10850 | };
|
10851 | ThisVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
10852 | return (this._getInit(options).hasEffectsWhenAccessedAtPath(path, options) ||
|
10853 | _super.prototype.hasEffectsWhenAccessedAtPath.call(this, path, options));
|
10854 | };
|
10855 | ThisVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
10856 | return (this._getInit(options).hasEffectsWhenAssignedAtPath(path, options) ||
|
10857 | _super.prototype.hasEffectsWhenAssignedAtPath.call(this, path, options));
|
10858 | };
|
10859 | ThisVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
10860 | return (this._getInit(options).hasEffectsWhenCalledAtPath(path, callOptions, options) ||
|
10861 | _super.prototype.hasEffectsWhenCalledAtPath.call(this, path, callOptions, options));
|
10862 | };
|
10863 | return ThisVariable;
|
10864 | }(LocalVariable));
|
10865 |
|
10866 | var ParameterScope = /** @class */ (function (_super) {
|
10867 | __extends(ParameterScope, _super);
|
10868 | function ParameterScope(parent, context) {
|
10869 | var _this = _super.call(this, parent) || this;
|
10870 | _this.parameters = [];
|
10871 | _this.context = context;
|
10872 | _this.hoistedBodyVarScope = new ChildScope(_this);
|
10873 | return _this;
|
10874 | }
|
10875 | /**
|
10876 | * Adds a parameter to this scope. Parameters must be added in the correct
|
10877 | * order, e.g. from left to right.
|
10878 | */
|
10879 | ParameterScope.prototype.addParameterDeclaration = function (identifier) {
|
10880 | var name = identifier.name;
|
10881 | var variable;
|
10882 | if (name in this.hoistedBodyVarScope.variables) {
|
10883 | variable = this.hoistedBodyVarScope.variables[name];
|
10884 | variable.addDeclaration(identifier, null);
|
10885 | }
|
10886 | else {
|
10887 | variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
|
10888 | }
|
10889 | this.variables[name] = variable;
|
10890 | this.parameters.push(variable);
|
10891 | return variable;
|
10892 | };
|
10893 | ParameterScope.prototype.getParameterVariables = function () {
|
10894 | return this.parameters;
|
10895 | };
|
10896 | return ParameterScope;
|
10897 | }(ChildScope));
|
10898 |
|
10899 | var ReturnValueScope = /** @class */ (function (_super) {
|
10900 | __extends(ReturnValueScope, _super);
|
10901 | function ReturnValueScope() {
|
10902 | var _this = _super !== null && _super.apply(this, arguments) || this;
|
10903 | _this.returnExpression = null;
|
10904 | _this.returnExpressions = [];
|
10905 | return _this;
|
10906 | }
|
10907 | ReturnValueScope.prototype.addReturnExpression = function (expression) {
|
10908 | this.returnExpressions.push(expression);
|
10909 | };
|
10910 | ReturnValueScope.prototype.getReturnExpression = function () {
|
10911 | if (this.returnExpression === null)
|
10912 | this.updateReturnExpression();
|
10913 | return this.returnExpression;
|
10914 | };
|
10915 | ReturnValueScope.prototype.updateReturnExpression = function () {
|
10916 | if (this.returnExpressions.length === 1) {
|
10917 | this.returnExpression = this.returnExpressions[0];
|
10918 | }
|
10919 | else {
|
10920 | this.returnExpression = UNKNOWN_EXPRESSION;
|
10921 | for (var _i = 0, _a = this.returnExpressions; _i < _a.length; _i++) {
|
10922 | var expression = _a[_i];
|
10923 | expression.deoptimizePath(UNKNOWN_PATH);
|
10924 | }
|
10925 | }
|
10926 | };
|
10927 | return ReturnValueScope;
|
10928 | }(ParameterScope));
|
10929 |
|
10930 | var FunctionScope = /** @class */ (function (_super) {
|
10931 | __extends(FunctionScope, _super);
|
10932 | function FunctionScope(parent, context) {
|
10933 | var _this = _super.call(this, parent, context) || this;
|
10934 | _this.variables.arguments = new ArgumentsVariable(_super.prototype.getParameterVariables.call(_this), context);
|
10935 | _this.variables.this = new ThisVariable(context);
|
10936 | return _this;
|
10937 | }
|
10938 | FunctionScope.prototype.findLexicalBoundary = function () {
|
10939 | return this;
|
10940 | };
|
10941 | FunctionScope.prototype.getOptionsWhenCalledWith = function (_a, options) {
|
10942 | var _this = this;
|
10943 | var args = _a.args, withNew = _a.withNew;
|
10944 | return options
|
10945 | .replaceVariableInit(this.variables.this, withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION)
|
10946 | .setArgumentsVariables(args.map(function (parameter, index) { return _super.prototype.getParameterVariables.call(_this)[index] || parameter; }));
|
10947 | };
|
10948 | return FunctionScope;
|
10949 | }(ReturnValueScope));
|
10950 |
|
10951 | var FunctionNode = /** @class */ (function (_super) {
|
10952 | __extends(FunctionNode, _super);
|
10953 | function FunctionNode() {
|
10954 | return _super !== null && _super.apply(this, arguments) || this;
|
10955 | }
|
10956 | FunctionNode.prototype.createScope = function (parentScope) {
|
10957 | this.scope = new FunctionScope(parentScope, this.context);
|
10958 | };
|
10959 | FunctionNode.prototype.deoptimizePath = function (path) {
|
10960 | if (path.length === 1) {
|
10961 | if (path[0] === 'prototype') {
|
10962 | this.isPrototypeDeoptimized = true;
|
10963 | }
|
10964 | else if (path[0] === UNKNOWN_KEY) {
|
10965 | this.isPrototypeDeoptimized = true;
|
10966 | // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
|
10967 | // which means the return expression needs to be reassigned as well
|
10968 | this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
|
10969 | }
|
10970 | }
|
10971 | };
|
10972 | FunctionNode.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
10973 | return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
|
10974 | };
|
10975 | FunctionNode.prototype.hasEffects = function (options) {
|
10976 | return this.id && this.id.hasEffects(options);
|
10977 | };
|
10978 | FunctionNode.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
10979 | if (path.length <= 1) {
|
10980 | return false;
|
10981 | }
|
10982 | return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
|
10983 | };
|
10984 | FunctionNode.prototype.hasEffectsWhenAssignedAtPath = function (path) {
|
10985 | if (path.length <= 1) {
|
10986 | return false;
|
10987 | }
|
10988 | return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
|
10989 | };
|
10990 | FunctionNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
10991 | if (path.length > 0) {
|
10992 | return true;
|
10993 | }
|
10994 | var innerOptions = this.scope.getOptionsWhenCalledWith(callOptions, options);
|
10995 | for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
|
10996 | var param = _a[_i];
|
10997 | if (param.hasEffects(innerOptions))
|
10998 | return true;
|
10999 | }
|
11000 | return this.body.hasEffects(innerOptions);
|
11001 | };
|
11002 | FunctionNode.prototype.include = function (includeAllChildrenRecursively) {
|
11003 | this.scope.variables.arguments.include();
|
11004 | _super.prototype.include.call(this, includeAllChildrenRecursively);
|
11005 | };
|
11006 | FunctionNode.prototype.initialise = function () {
|
11007 | this.included = false;
|
11008 | this.isPrototypeDeoptimized = false;
|
11009 | if (this.id !== null) {
|
11010 | this.id.declare('function', this);
|
11011 | }
|
11012 | for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
|
11013 | var param = _a[_i];
|
11014 | param.declare('parameter', UNKNOWN_EXPRESSION);
|
11015 | }
|
11016 | this.body.addImplicitReturnExpressionToScope();
|
11017 | };
|
11018 | FunctionNode.prototype.parseNode = function (esTreeNode) {
|
11019 | this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope));
|
11020 | _super.prototype.parseNode.call(this, esTreeNode);
|
11021 | };
|
11022 | return FunctionNode;
|
11023 | }(NodeBase));
|
11024 | FunctionNode.prototype.preventChildBlockScope = true;
|
11025 |
|
11026 | function isFunctionDeclaration(node) {
|
11027 | return node.type === FunctionDeclaration;
|
11028 | }
|
11029 | var FunctionDeclaration$1 = /** @class */ (function (_super) {
|
11030 | __extends(FunctionDeclaration, _super);
|
11031 | function FunctionDeclaration() {
|
11032 | return _super !== null && _super.apply(this, arguments) || this;
|
11033 | }
|
11034 | FunctionDeclaration.prototype.initialise = function () {
|
11035 | _super.prototype.initialise.call(this);
|
11036 | if (this.id !== null) {
|
11037 | this.id.variable.isId = true;
|
11038 | }
|
11039 | };
|
11040 | FunctionDeclaration.prototype.parseNode = function (esTreeNode) {
|
11041 | if (esTreeNode.id !== null) {
|
11042 | this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
|
11043 | }
|
11044 | _super.prototype.parseNode.call(this, esTreeNode);
|
11045 | };
|
11046 | return FunctionDeclaration;
|
11047 | }(FunctionNode));
|
11048 |
|
11049 | var WHITESPACE = /\s/;
|
11050 | // The header ends at the first non-white-space after "default"
|
11051 | function getDeclarationStart(code, start) {
|
11052 | if (start === void 0) { start = 0; }
|
11053 | start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
|
11054 | while (WHITESPACE.test(code[start]))
|
11055 | start++;
|
11056 | return start;
|
11057 | }
|
11058 | function getIdInsertPosition(code, declarationKeyword, start) {
|
11059 | if (start === void 0) { start = 0; }
|
11060 | var declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
|
11061 | code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
|
11062 | var generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
|
11063 | if (generatorStarPos === -1) {
|
11064 | return declarationEnd;
|
11065 | }
|
11066 | return declarationEnd + generatorStarPos + 1;
|
11067 | }
|
11068 | function isExportDefaultDeclaration(node) {
|
11069 | return node.type === ExportDefaultDeclaration;
|
11070 | }
|
11071 | var ExportDefaultDeclaration$1 = /** @class */ (function (_super) {
|
11072 | __extends(ExportDefaultDeclaration, _super);
|
11073 | function ExportDefaultDeclaration() {
|
11074 | return _super !== null && _super.apply(this, arguments) || this;
|
11075 | }
|
11076 | ExportDefaultDeclaration.prototype.include = function (includeAllChildrenRecursively) {
|
11077 | _super.prototype.include.call(this, includeAllChildrenRecursively);
|
11078 | if (includeAllChildrenRecursively) {
|
11079 | this.context.includeVariable(this.variable);
|
11080 | }
|
11081 | };
|
11082 | ExportDefaultDeclaration.prototype.initialise = function () {
|
11083 | this.included = false;
|
11084 | this.declarationName =
|
11085 | (this.declaration.id &&
|
11086 | this.declaration.id.name) ||
|
11087 | this.declaration.name;
|
11088 | this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
|
11089 | this.context.addExport(this);
|
11090 | };
|
11091 | ExportDefaultDeclaration.prototype.render = function (code, options, _a) {
|
11092 | var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
|
11093 | var declarationStart = getDeclarationStart(code.original, this.start);
|
11094 | if (isFunctionDeclaration(this.declaration)) {
|
11095 | this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
|
11096 | }
|
11097 | else if (isClassDeclaration(this.declaration)) {
|
11098 | this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
|
11099 | }
|
11100 | else if (this.variable.referencesOriginal()) {
|
11101 | // Remove altogether to prevent re-declaring the same variable
|
11102 | if (options.format === 'system' && this.variable.exportName) {
|
11103 | code.overwrite(start, end, "exports('" + this.variable.exportName + "', " + this.variable.getName() + ");");
|
11104 | }
|
11105 | else {
|
11106 | treeshakeNode(this, code, start, end);
|
11107 | }
|
11108 | return;
|
11109 | }
|
11110 | else if (this.variable.included) {
|
11111 | this.renderVariableDeclaration(code, declarationStart, options);
|
11112 | }
|
11113 | else {
|
11114 | code.remove(this.start, declarationStart);
|
11115 | this.declaration.render(code, options, {
|
11116 | isCalleeOfRenderedParent: false,
|
11117 | renderedParentType: ExpressionStatement
|
11118 | });
|
11119 | if (code.original[this.end - 1] !== ';') {
|
11120 | code.appendLeft(this.end, ';');
|
11121 | }
|
11122 | return;
|
11123 | }
|
11124 | this.declaration.render(code, options);
|
11125 | };
|
11126 | ExportDefaultDeclaration.prototype.renderNamedDeclaration = function (code, declarationStart, declarationKeyword, needsId, options) {
|
11127 | var name = this.variable.getName();
|
11128 | // Remove `export default`
|
11129 | code.remove(this.start, declarationStart);
|
11130 | if (needsId) {
|
11131 | code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), " " + name);
|
11132 | }
|
11133 | if (options.format === 'system' &&
|
11134 | isClassDeclaration(this.declaration) &&
|
11135 | this.variable.exportName) {
|
11136 | code.appendLeft(this.end, " exports('" + this.variable.exportName + "', " + name + ");");
|
11137 | }
|
11138 | };
|
11139 | ExportDefaultDeclaration.prototype.renderVariableDeclaration = function (code, declarationStart, options) {
|
11140 | var systemBinding = options.format === 'system' && this.variable.exportName
|
11141 | ? "exports('" + this.variable.exportName + "', "
|
11142 | : '';
|
11143 | code.overwrite(this.start, declarationStart, options.varOrConst + " " + this.variable.getName() + " = " + systemBinding);
|
11144 | var hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
|
11145 | if (systemBinding) {
|
11146 | code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
|
11147 | }
|
11148 | else if (!hasTrailingSemicolon) {
|
11149 | code.appendLeft(this.end, ';');
|
11150 | }
|
11151 | };
|
11152 | return ExportDefaultDeclaration;
|
11153 | }(NodeBase));
|
11154 | ExportDefaultDeclaration$1.prototype.needsBoundaries = true;
|
11155 |
|
11156 | var ArrayExpression = /** @class */ (function (_super) {
|
11157 | __extends(ArrayExpression, _super);
|
11158 | function ArrayExpression() {
|
11159 | return _super !== null && _super.apply(this, arguments) || this;
|
11160 | }
|
11161 | ArrayExpression.prototype.bind = function () {
|
11162 | _super.prototype.bind.call(this);
|
11163 | for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
|
11164 | var element = _a[_i];
|
11165 | if (element !== null)
|
11166 | element.deoptimizePath(UNKNOWN_PATH);
|
11167 | }
|
11168 | };
|
11169 | ArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
11170 | if (path.length !== 1)
|
11171 | return UNKNOWN_EXPRESSION;
|
11172 | return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
|
11173 | };
|
11174 | ArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
11175 | return path.length > 1;
|
11176 | };
|
11177 | ArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
11178 | if (path.length === 1) {
|
11179 | return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
|
11180 | }
|
11181 | return true;
|
11182 | };
|
11183 | return ArrayExpression;
|
11184 | }(NodeBase));
|
11185 |
|
11186 | var ArrayPattern = /** @class */ (function (_super) {
|
11187 | __extends(ArrayPattern, _super);
|
11188 | function ArrayPattern() {
|
11189 | return _super !== null && _super.apply(this, arguments) || this;
|
11190 | }
|
11191 | ArrayPattern.prototype.addExportedVariables = function (variables) {
|
11192 | for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
|
11193 | var element = _a[_i];
|
11194 | if (element !== null) {
|
11195 | element.addExportedVariables(variables);
|
11196 | }
|
11197 | }
|
11198 | };
|
11199 | ArrayPattern.prototype.declare = function (kind, _init) {
|
11200 | for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
|
11201 | var element = _a[_i];
|
11202 | if (element !== null) {
|
11203 | element.declare(kind, UNKNOWN_EXPRESSION);
|
11204 | }
|
11205 | }
|
11206 | };
|
11207 | ArrayPattern.prototype.deoptimizePath = function (path) {
|
11208 | if (path.length === 0) {
|
11209 | for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
|
11210 | var element = _a[_i];
|
11211 | if (element !== null) {
|
11212 | element.deoptimizePath(path);
|
11213 | }
|
11214 | }
|
11215 | }
|
11216 | };
|
11217 | ArrayPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
11218 | if (path.length > 0)
|
11219 | return true;
|
11220 | for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
|
11221 | var element = _a[_i];
|
11222 | if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
|
11223 | return true;
|
11224 | }
|
11225 | return false;
|
11226 | };
|
11227 | return ArrayPattern;
|
11228 | }(NodeBase));
|
11229 |
|
11230 | var BlockScope = /** @class */ (function (_super) {
|
11231 | __extends(BlockScope, _super);
|
11232 | function BlockScope() {
|
11233 | return _super !== null && _super.apply(this, arguments) || this;
|
11234 | }
|
11235 | BlockScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
|
11236 | if (init === void 0) { init = null; }
|
11237 | if (isHoisted === void 0) { isHoisted = false; }
|
11238 | if (isHoisted) {
|
11239 | return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, true);
|
11240 | }
|
11241 | else {
|
11242 | return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
|
11243 | }
|
11244 | };
|
11245 | return BlockScope;
|
11246 | }(ChildScope));
|
11247 |
|
11248 | var BlockStatement$1 = /** @class */ (function (_super) {
|
11249 | __extends(BlockStatement, _super);
|
11250 | function BlockStatement() {
|
11251 | return _super !== null && _super.apply(this, arguments) || this;
|
11252 | }
|
11253 | BlockStatement.prototype.addImplicitReturnExpressionToScope = function () {
|
11254 | var lastStatement = this.body[this.body.length - 1];
|
11255 | if (!lastStatement || lastStatement.type !== ReturnStatement) {
|
11256 | this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
|
11257 | }
|
11258 | };
|
11259 | BlockStatement.prototype.createScope = function (parentScope) {
|
11260 | this.scope = this.parent.preventChildBlockScope
|
11261 | ? parentScope
|
11262 | : new BlockScope(parentScope);
|
11263 | };
|
11264 | BlockStatement.prototype.hasEffects = function (options) {
|
11265 | for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
|
11266 | var node = _a[_i];
|
11267 | if (node.hasEffects(options))
|
11268 | return true;
|
11269 | }
|
11270 | };
|
11271 | BlockStatement.prototype.include = function (includeAllChildrenRecursively) {
|
11272 | this.included = true;
|
11273 | for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
|
11274 | var node = _a[_i];
|
11275 | if (includeAllChildrenRecursively || node.shouldBeIncluded())
|
11276 | node.include(includeAllChildrenRecursively);
|
11277 | }
|
11278 | };
|
11279 | BlockStatement.prototype.render = function (code, options) {
|
11280 | if (this.body.length) {
|
11281 | renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
|
11282 | }
|
11283 | else {
|
11284 | _super.prototype.render.call(this, code, options);
|
11285 | }
|
11286 | };
|
11287 | return BlockStatement;
|
11288 | }(NodeBase));
|
11289 |
|
11290 | var ArrowFunctionExpression = /** @class */ (function (_super) {
|
11291 | __extends(ArrowFunctionExpression, _super);
|
11292 | function ArrowFunctionExpression() {
|
11293 | return _super !== null && _super.apply(this, arguments) || this;
|
11294 | }
|
11295 | ArrowFunctionExpression.prototype.createScope = function (parentScope) {
|
11296 | this.scope = new ReturnValueScope(parentScope, this.context);
|
11297 | };
|
11298 | ArrowFunctionExpression.prototype.deoptimizePath = function (path) {
|
11299 | // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
|
11300 | // which means the return expression needs to be reassigned
|
11301 | if (path.length === 1 && path[0] === UNKNOWN_KEY) {
|
11302 | this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
|
11303 | }
|
11304 | };
|
11305 | ArrowFunctionExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
11306 | return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
|
11307 | };
|
11308 | ArrowFunctionExpression.prototype.hasEffects = function (_options) {
|
11309 | return false;
|
11310 | };
|
11311 | ArrowFunctionExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
11312 | return path.length > 1;
|
11313 | };
|
11314 | ArrowFunctionExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
|
11315 | return path.length > 1;
|
11316 | };
|
11317 | ArrowFunctionExpression.prototype.hasEffectsWhenCalledAtPath = function (path, _callOptions, options) {
|
11318 | if (path.length > 0) {
|
11319 | return true;
|
11320 | }
|
11321 | for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
|
11322 | var param = _a[_i];
|
11323 | if (param.hasEffects(options))
|
11324 | return true;
|
11325 | }
|
11326 | return this.body.hasEffects(options);
|
11327 | };
|
11328 | ArrowFunctionExpression.prototype.initialise = function () {
|
11329 | this.included = false;
|
11330 | for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
|
11331 | var param = _a[_i];
|
11332 | param.declare('parameter', UNKNOWN_EXPRESSION);
|
11333 | }
|
11334 | if (this.body instanceof BlockStatement$1) {
|
11335 | this.body.addImplicitReturnExpressionToScope();
|
11336 | }
|
11337 | else {
|
11338 | this.scope.addReturnExpression(this.body);
|
11339 | }
|
11340 | };
|
11341 | ArrowFunctionExpression.prototype.parseNode = function (esTreeNode) {
|
11342 | if (esTreeNode.body.type === BlockStatement) {
|
11343 | this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
|
11344 | }
|
11345 | _super.prototype.parseNode.call(this, esTreeNode);
|
11346 | };
|
11347 | return ArrowFunctionExpression;
|
11348 | }(NodeBase));
|
11349 | ArrowFunctionExpression.prototype.preventChildBlockScope = true;
|
11350 |
|
11351 | function getSystemExportStatement(exportedVariables) {
|
11352 | if (exportedVariables.length === 1) {
|
11353 | return "exports('" + (exportedVariables[0].safeExportName ||
|
11354 | exportedVariables[0].exportName) + "', " + exportedVariables[0].getName() + ");";
|
11355 | }
|
11356 | else {
|
11357 | return "exports({" + exportedVariables
|
11358 | .map(function (variable) { return (variable.safeExportName || variable.exportName) + ": " + variable.getName(); })
|
11359 | .join(', ') + "});";
|
11360 | }
|
11361 | }
|
11362 |
|
11363 | var AssignmentExpression = /** @class */ (function (_super) {
|
11364 | __extends(AssignmentExpression, _super);
|
11365 | function AssignmentExpression() {
|
11366 | return _super !== null && _super.apply(this, arguments) || this;
|
11367 | }
|
11368 | AssignmentExpression.prototype.bind = function () {
|
11369 | _super.prototype.bind.call(this);
|
11370 | this.left.deoptimizePath(EMPTY_PATH);
|
11371 | // We cannot propagate mutations of the new binding to the old binding with certainty
|
11372 | this.right.deoptimizePath(UNKNOWN_PATH);
|
11373 | };
|
11374 | AssignmentExpression.prototype.hasEffects = function (options) {
|
11375 | return (this.right.hasEffects(options) ||
|
11376 | this.left.hasEffects(options) ||
|
11377 | this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
|
11378 | };
|
11379 | AssignmentExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
11380 | return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, options);
|
11381 | };
|
11382 | AssignmentExpression.prototype.render = function (code, options) {
|
11383 | this.left.render(code, options);
|
11384 | this.right.render(code, options);
|
11385 | if (options.format === 'system') {
|
11386 | if (this.left.variable && this.left.variable.exportName) {
|
11387 | code.prependLeft(code.original.indexOf('=', this.left.end) + 1, " exports('" + this.left.variable.exportName + "',");
|
11388 | code.appendLeft(this.right.end, ")");
|
11389 | }
|
11390 | else if ('addExportedVariables' in this.left) {
|
11391 | var systemPatternExports = [];
|
11392 | this.left.addExportedVariables(systemPatternExports);
|
11393 | if (systemPatternExports.length > 0) {
|
11394 | code.prependRight(this.start, "function (v) {" + getSystemExportStatement(systemPatternExports) + " return v;} (");
|
11395 | code.appendLeft(this.end, ')');
|
11396 | }
|
11397 | }
|
11398 | }
|
11399 | };
|
11400 | return AssignmentExpression;
|
11401 | }(NodeBase));
|
11402 |
|
11403 | var AssignmentPattern = /** @class */ (function (_super) {
|
11404 | __extends(AssignmentPattern, _super);
|
11405 | function AssignmentPattern() {
|
11406 | return _super !== null && _super.apply(this, arguments) || this;
|
11407 | }
|
11408 | AssignmentPattern.prototype.addExportedVariables = function (variables) {
|
11409 | this.left.addExportedVariables(variables);
|
11410 | };
|
11411 | AssignmentPattern.prototype.bind = function () {
|
11412 | _super.prototype.bind.call(this);
|
11413 | this.left.deoptimizePath(EMPTY_PATH);
|
11414 | this.right.deoptimizePath(UNKNOWN_PATH);
|
11415 | };
|
11416 | AssignmentPattern.prototype.declare = function (kind, init) {
|
11417 | this.left.declare(kind, init);
|
11418 | };
|
11419 | AssignmentPattern.prototype.deoptimizePath = function (path) {
|
11420 | path.length === 0 && this.left.deoptimizePath(path);
|
11421 | };
|
11422 | AssignmentPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
11423 | return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
|
11424 | };
|
11425 | AssignmentPattern.prototype.render = function (code, options, _a) {
|
11426 | var isShorthandProperty = (_a === void 0 ? BLANK : _a).isShorthandProperty;
|
11427 | this.left.render(code, options, { isShorthandProperty: isShorthandProperty });
|
11428 | this.right.render(code, options);
|
11429 | };
|
11430 | return AssignmentPattern;
|
11431 | }(NodeBase));
|
11432 |
|
11433 | var AwaitExpression = /** @class */ (function (_super) {
|
11434 | __extends(AwaitExpression, _super);
|
11435 | function AwaitExpression() {
|
11436 | return _super !== null && _super.apply(this, arguments) || this;
|
11437 | }
|
11438 | AwaitExpression.prototype.hasEffects = function (options) {
|
11439 | return _super.prototype.hasEffects.call(this, options) || !options.ignoreReturnAwaitYield();
|
11440 | };
|
11441 | AwaitExpression.prototype.include = function (includeAllChildrenRecursively) {
|
11442 | _super.prototype.include.call(this, includeAllChildrenRecursively);
|
11443 | if (!this.context.usesTopLevelAwait) {
|
11444 | var parent = this.parent;
|
11445 | do {
|
11446 | if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
|
11447 | return;
|
11448 | } while ((parent = parent.parent));
|
11449 | this.context.usesTopLevelAwait = true;
|
11450 | }
|
11451 | };
|
11452 | AwaitExpression.prototype.render = function (code, options) {
|
11453 | _super.prototype.render.call(this, code, options);
|
11454 | };
|
11455 | return AwaitExpression;
|
11456 | }(NodeBase));
|
11457 |
|
11458 | var binaryOperators = {
|
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 | // At the moment, "**" will be transpiled to Math.pow
|
11465 | '**': function (left, right) { return Math.pow(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 | '<=': function (left, right) { return left <= right; },
|
11472 | '==': function (left, right) { return left == right; },
|
11473 | '===': function (left, right) { return left === right; },
|
11474 | '>': function (left, right) { return left > right; },
|
11475 | '>=': function (left, right) { return left >= right; },
|
11476 | '>>': function (left, right) { return left >> right; },
|
11477 | '>>>': function (left, right) { return left >>> right; },
|
11478 | '^': function (left, right) { return left ^ right; },
|
11479 | in: function () { return UNKNOWN_VALUE; },
|
11480 | instanceof: function () { return UNKNOWN_VALUE; },
|
11481 | '|': function (left, right) { return left | right; }
|
11482 | };
|
11483 | var BinaryExpression = /** @class */ (function (_super) {
|
11484 | __extends(BinaryExpression, _super);
|
11485 | function BinaryExpression() {
|
11486 | return _super !== null && _super.apply(this, arguments) || this;
|
11487 | }
|
11488 | BinaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
11489 | if (path.length > 0)
|
11490 | return UNKNOWN_VALUE;
|
11491 | var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
11492 | if (leftValue === UNKNOWN_VALUE)
|
11493 | return UNKNOWN_VALUE;
|
11494 | var rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
11495 | if (rightValue === UNKNOWN_VALUE)
|
11496 | return UNKNOWN_VALUE;
|
11497 | var operatorFn = binaryOperators[this.operator];
|
11498 | if (!operatorFn)
|
11499 | return UNKNOWN_VALUE;
|
11500 | return operatorFn(leftValue, rightValue);
|
11501 | };
|
11502 | BinaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
11503 | return path.length > 1;
|
11504 | };
|
11505 | return BinaryExpression;
|
11506 | }(NodeBase));
|
11507 |
|
11508 | var BreakStatement = /** @class */ (function (_super) {
|
11509 | __extends(BreakStatement, _super);
|
11510 | function BreakStatement() {
|
11511 | return _super !== null && _super.apply(this, arguments) || this;
|
11512 | }
|
11513 | BreakStatement.prototype.hasEffects = function (options) {
|
11514 | return (_super.prototype.hasEffects.call(this, options) ||
|
11515 | !options.ignoreBreakStatements() ||
|
11516 | (this.label && !options.ignoreLabel(this.label.name)));
|
11517 | };
|
11518 | return BreakStatement;
|
11519 | }(NodeBase));
|
11520 |
|
11521 | var RESULT_KEY$1 = {};
|
11522 | var ImmutableEntityPathTracker = /** @class */ (function () {
|
11523 | function ImmutableEntityPathTracker(existingEntityPaths) {
|
11524 | if (existingEntityPaths === void 0) { existingEntityPaths = Immutable.Map(); }
|
11525 | this.entityPaths = existingEntityPaths;
|
11526 | }
|
11527 | ImmutableEntityPathTracker.prototype.isTracked = function (entity, path) {
|
11528 | return this.entityPaths.getIn([entity].concat(path, [RESULT_KEY$1]));
|
11529 | };
|
11530 | ImmutableEntityPathTracker.prototype.track = function (entity, path) {
|
11531 | return new ImmutableEntityPathTracker(this.entityPaths.setIn([entity].concat(path, [RESULT_KEY$1]), true));
|
11532 | };
|
11533 | return ImmutableEntityPathTracker;
|
11534 | }());
|
11535 | var EMPTY_IMMUTABLE_TRACKER = new ImmutableEntityPathTracker();
|
11536 |
|
11537 | function isReference(node, parent) {
|
11538 | if (node.type === 'MemberExpression') {
|
11539 | return !node.computed && isReference(node.object, node);
|
11540 | }
|
11541 | if (node.type === 'Identifier') {
|
11542 | switch (parent.type) {
|
11543 | // disregard `bar` in `foo.bar`
|
11544 | case 'MemberExpression': return parent.computed || node === parent.object;
|
11545 | // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
|
11546 | case 'MethodDefinition': return parent.computed;
|
11547 | // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
|
11548 | case 'Property': return parent.computed || node === parent.value;
|
11549 | // disregard the `bar` in `export { foo as bar }`
|
11550 | case 'ExportSpecifier': return node === parent.local;
|
11551 | // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
|
11552 | case 'LabeledStatement':
|
11553 | case 'BreakStatement':
|
11554 | case 'ContinueStatement': return false;
|
11555 | default: return true;
|
11556 | }
|
11557 | }
|
11558 | return false;
|
11559 | }
|
11560 |
|
11561 | function isIdentifier(node) {
|
11562 | return node.type === Identifier;
|
11563 | }
|
11564 | var Identifier$1 = /** @class */ (function (_super) {
|
11565 | __extends(Identifier, _super);
|
11566 | function Identifier() {
|
11567 | return _super !== null && _super.apply(this, arguments) || this;
|
11568 | }
|
11569 | Identifier.prototype.addExportedVariables = function (variables) {
|
11570 | if (this.variable.exportName) {
|
11571 | variables.push(this.variable);
|
11572 | }
|
11573 | };
|
11574 | Identifier.prototype.bind = function () {
|
11575 | if (this.bound)
|
11576 | return;
|
11577 | this.bound = true;
|
11578 | if (this.variable === null && isReference(this, this.parent)) {
|
11579 | this.variable = this.scope.findVariable(this.name);
|
11580 | this.variable.addReference(this);
|
11581 | }
|
11582 | if (this.variable !== null &&
|
11583 | this.variable.isLocal &&
|
11584 | this.variable.additionalInitializers !== null) {
|
11585 | this.variable.consolidateInitializers();
|
11586 | }
|
11587 | };
|
11588 | Identifier.prototype.declare = function (kind, init) {
|
11589 | switch (kind) {
|
11590 | case 'var':
|
11591 | case 'function':
|
11592 | this.variable = this.scope.addDeclaration(this, this.context, init, true);
|
11593 | break;
|
11594 | case 'let':
|
11595 | case 'const':
|
11596 | case 'class':
|
11597 | this.variable = this.scope.addDeclaration(this, this.context, init, false);
|
11598 | break;
|
11599 | case 'parameter':
|
11600 | this.variable = this.scope.addParameterDeclaration(this);
|
11601 | break;
|
11602 | default:
|
11603 | throw new Error("Unexpected identifier kind " + kind + ".");
|
11604 | }
|
11605 | };
|
11606 | Identifier.prototype.deoptimizePath = function (path) {
|
11607 | if (!this.bound)
|
11608 | this.bind();
|
11609 | if (this.variable !== null) {
|
11610 | if (path.length === 0 &&
|
11611 | this.name in this.context.importDescriptions &&
|
11612 | !this.scope.contains(this.name)) {
|
11613 | this.disallowImportReassignment();
|
11614 | }
|
11615 | this.variable.deoptimizePath(path);
|
11616 | }
|
11617 | };
|
11618 | Identifier.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
11619 | if (!this.bound)
|
11620 | this.bind();
|
11621 | if (this.variable !== null) {
|
11622 | return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
|
11623 | }
|
11624 | return UNKNOWN_VALUE;
|
11625 | };
|
11626 | Identifier.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
11627 | if (!this.bound)
|
11628 | this.bind();
|
11629 | if (this.variable !== null) {
|
11630 | return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
11631 | }
|
11632 | return UNKNOWN_EXPRESSION;
|
11633 | };
|
11634 | Identifier.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
11635 | return this.variable && this.variable.hasEffectsWhenAccessedAtPath(path, options);
|
11636 | };
|
11637 | Identifier.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
11638 | return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, options);
|
11639 | };
|
11640 | Identifier.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
11641 | return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
11642 | };
|
11643 | Identifier.prototype.include = function (_includeAllChildrenRecursively) {
|
11644 | if (!this.included) {
|
11645 | this.included = true;
|
11646 | if (this.variable !== null) {
|
11647 | this.context.includeVariable(this.variable);
|
11648 | }
|
11649 | }
|
11650 | };
|
11651 | Identifier.prototype.initialise = function () {
|
11652 | this.included = false;
|
11653 | this.bound = false;
|
11654 | // To avoid later shape mutations
|
11655 | if (!this.variable) {
|
11656 | this.variable = null;
|
11657 | }
|
11658 | };
|
11659 | Identifier.prototype.render = function (code, _options, _a) {
|
11660 | var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent, isShorthandProperty = _b.isShorthandProperty;
|
11661 | if (this.variable) {
|
11662 | var name = this.variable.getName();
|
11663 | if (name !== this.name) {
|
11664 | code.overwrite(this.start, this.end, name, {
|
11665 | contentOnly: true,
|
11666 | storeName: true
|
11667 | });
|
11668 | if (isShorthandProperty) {
|
11669 | code.prependRight(this.start, this.name + ": ");
|
11670 | }
|
11671 | }
|
11672 | // In strict mode, any variable named "eval" must be the actual "eval" function
|
11673 | if (name === 'eval' &&
|
11674 | renderedParentType === CallExpression &&
|
11675 | isCalleeOfRenderedParent) {
|
11676 | code.appendRight(this.start, '0, ');
|
11677 | }
|
11678 | }
|
11679 | };
|
11680 | Identifier.prototype.disallowImportReassignment = function () {
|
11681 | this.context.error({
|
11682 | code: 'ILLEGAL_REASSIGNMENT',
|
11683 | message: "Illegal reassignment to import '" + this.name + "'"
|
11684 | }, this.start);
|
11685 | };
|
11686 | return Identifier;
|
11687 | }(NodeBase));
|
11688 |
|
11689 | var CallExpression$1 = /** @class */ (function (_super) {
|
11690 | __extends(CallExpression, _super);
|
11691 | function CallExpression() {
|
11692 | return _super !== null && _super.apply(this, arguments) || this;
|
11693 | }
|
11694 | CallExpression.prototype.bind = function () {
|
11695 | _super.prototype.bind.call(this);
|
11696 | if (this.callee instanceof Identifier$1) {
|
11697 | var variable = this.scope.findVariable(this.callee.name);
|
11698 | if (variable.isNamespace) {
|
11699 | this.context.error({
|
11700 | code: 'CANNOT_CALL_NAMESPACE',
|
11701 | message: "Cannot call a namespace ('" + this.callee.name + "')"
|
11702 | }, this.start);
|
11703 | }
|
11704 | if (this.callee.name === 'eval') {
|
11705 | this.context.warn({
|
11706 | code: 'EVAL',
|
11707 | message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
|
11708 | url: 'https://rollupjs.org/guide/en#avoiding-eval'
|
11709 | }, this.start);
|
11710 | }
|
11711 | }
|
11712 | if (this.returnExpression === null) {
|
11713 | this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
11714 | }
|
11715 | for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
|
11716 | var argument = _a[_i];
|
11717 | // This will make sure all properties of parameters behave as "unknown"
|
11718 | argument.deoptimizePath(UNKNOWN_PATH);
|
11719 | }
|
11720 | };
|
11721 | CallExpression.prototype.deoptimizeCache = function () {
|
11722 | if (this.returnExpression !== UNKNOWN_EXPRESSION) {
|
11723 | this.returnExpression = UNKNOWN_EXPRESSION;
|
11724 | for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
|
11725 | var expression = _a[_i];
|
11726 | expression.deoptimizeCache();
|
11727 | }
|
11728 | }
|
11729 | };
|
11730 | CallExpression.prototype.deoptimizePath = function (path) {
|
11731 | if (path.length > 0 && !this.context.deoptimizationTracker.track(this, path)) {
|
11732 | if (this.returnExpression === null) {
|
11733 | this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
11734 | }
|
11735 | this.returnExpression.deoptimizePath(path);
|
11736 | }
|
11737 | };
|
11738 | CallExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
11739 | if (this.returnExpression === null) {
|
11740 | this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
|
11741 | }
|
11742 | if (this.returnExpression === UNKNOWN_EXPRESSION ||
|
11743 | recursionTracker.isTracked(this.returnExpression, path)) {
|
11744 | return UNKNOWN_VALUE;
|
11745 | }
|
11746 | this.expressionsToBeDeoptimized.push(origin);
|
11747 | return this.returnExpression.getLiteralValueAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
|
11748 | };
|
11749 | CallExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
11750 | if (this.returnExpression === null) {
|
11751 | this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
|
11752 | }
|
11753 | if (this.returnExpression === UNKNOWN_EXPRESSION ||
|
11754 | recursionTracker.isTracked(this.returnExpression, path)) {
|
11755 | return UNKNOWN_EXPRESSION;
|
11756 | }
|
11757 | this.expressionsToBeDeoptimized.push(origin);
|
11758 | return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
|
11759 | };
|
11760 | CallExpression.prototype.hasEffects = function (options) {
|
11761 | for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
|
11762 | var argument = _a[_i];
|
11763 | if (argument.hasEffects(options))
|
11764 | return true;
|
11765 | }
|
11766 | if (this.context.annotations && this.annotatedPure)
|
11767 | return false;
|
11768 | return (this.callee.hasEffects(options) ||
|
11769 | this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
|
11770 | };
|
11771 | CallExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
11772 | return (path.length > 0 &&
|
11773 | !options.hasReturnExpressionBeenAccessedAtPath(path, this) &&
|
11774 | this.returnExpression.hasEffectsWhenAccessedAtPath(path, options.addAccessedReturnExpressionAtPath(path, this)));
|
11775 | };
|
11776 | CallExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
11777 | return (path.length === 0 ||
|
11778 | (!options.hasReturnExpressionBeenAssignedAtPath(path, this) &&
|
11779 | this.returnExpression.hasEffectsWhenAssignedAtPath(path, options.addAssignedReturnExpressionAtPath(path, this))));
|
11780 | };
|
11781 | CallExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
11782 | if (options.hasReturnExpressionBeenCalledAtPath(path, this))
|
11783 | return false;
|
11784 | return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledReturnExpressionAtPath(path, this));
|
11785 | };
|
11786 | CallExpression.prototype.include = function (includeAllChildrenRecursively) {
|
11787 | _super.prototype.include.call(this, includeAllChildrenRecursively);
|
11788 | if (!this.returnExpression.included) {
|
11789 | this.returnExpression.include(false);
|
11790 | }
|
11791 | };
|
11792 | CallExpression.prototype.initialise = function () {
|
11793 | this.included = false;
|
11794 | this.returnExpression = null;
|
11795 | this.callOptions = CallOptions.create({
|
11796 | args: this.arguments,
|
11797 | callIdentifier: this,
|
11798 | withNew: false
|
11799 | });
|
11800 | this.expressionsToBeDeoptimized = [];
|
11801 | };
|
11802 | CallExpression.prototype.render = function (code, options, _a) {
|
11803 | var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
|
11804 | _super.prototype.render.call(this, code, options);
|
11805 | if (renderedParentType === ExpressionStatement &&
|
11806 | this.callee.type === FunctionExpression) {
|
11807 | code.appendRight(this.start, '(');
|
11808 | code.prependLeft(this.end, ')');
|
11809 | }
|
11810 | };
|
11811 | return CallExpression;
|
11812 | }(NodeBase));
|
11813 |
|
11814 | var CatchScope = /** @class */ (function (_super) {
|
11815 | __extends(CatchScope, _super);
|
11816 | function CatchScope() {
|
11817 | return _super !== null && _super.apply(this, arguments) || this;
|
11818 | }
|
11819 | CatchScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
|
11820 | if (init === void 0) { init = null; }
|
11821 | if (isHoisted === void 0) { isHoisted = false; }
|
11822 | if (isHoisted) {
|
11823 | return this.parent.addDeclaration(identifier, context, init, true);
|
11824 | }
|
11825 | else {
|
11826 | return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
|
11827 | }
|
11828 | };
|
11829 | return CatchScope;
|
11830 | }(ParameterScope));
|
11831 |
|
11832 | var CatchClause = /** @class */ (function (_super) {
|
11833 | __extends(CatchClause, _super);
|
11834 | function CatchClause() {
|
11835 | return _super !== null && _super.apply(this, arguments) || this;
|
11836 | }
|
11837 | CatchClause.prototype.createScope = function (parentScope) {
|
11838 | this.scope = new CatchScope(parentScope, this.context);
|
11839 | };
|
11840 | CatchClause.prototype.initialise = function () {
|
11841 | this.included = false;
|
11842 | if (this.param) {
|
11843 | this.param.declare('parameter', UNKNOWN_EXPRESSION);
|
11844 | }
|
11845 | };
|
11846 | CatchClause.prototype.parseNode = function (esTreeNode) {
|
11847 | this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope));
|
11848 | _super.prototype.parseNode.call(this, esTreeNode);
|
11849 | };
|
11850 | return CatchClause;
|
11851 | }(NodeBase));
|
11852 | CatchClause.prototype.preventChildBlockScope = true;
|
11853 |
|
11854 | var ClassBody = /** @class */ (function (_super) {
|
11855 | __extends(ClassBody, _super);
|
11856 | function ClassBody() {
|
11857 | return _super !== null && _super.apply(this, arguments) || this;
|
11858 | }
|
11859 | ClassBody.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
11860 | if (path.length > 0) {
|
11861 | return true;
|
11862 | }
|
11863 | return (this.classConstructor !== null &&
|
11864 | this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
|
11865 | };
|
11866 | ClassBody.prototype.initialise = function () {
|
11867 | this.included = false;
|
11868 | for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
|
11869 | var method = _a[_i];
|
11870 | if (method.kind === 'constructor') {
|
11871 | this.classConstructor = method;
|
11872 | return;
|
11873 | }
|
11874 | }
|
11875 | this.classConstructor = null;
|
11876 | };
|
11877 | return ClassBody;
|
11878 | }(NodeBase));
|
11879 |
|
11880 | var ClassExpression = /** @class */ (function (_super) {
|
11881 | __extends(ClassExpression, _super);
|
11882 | function ClassExpression() {
|
11883 | return _super !== null && _super.apply(this, arguments) || this;
|
11884 | }
|
11885 | return ClassExpression;
|
11886 | }(ClassNode));
|
11887 |
|
11888 | var MultiExpression = /** @class */ (function () {
|
11889 | function MultiExpression(expressions) {
|
11890 | this.expressions = expressions;
|
11891 | }
|
11892 | MultiExpression.prototype.deoptimizePath = function (path) {
|
11893 | for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
|
11894 | var expression = _a[_i];
|
11895 | expression.deoptimizePath(path);
|
11896 | }
|
11897 | };
|
11898 | MultiExpression.prototype.getLiteralValueAtPath = function () {
|
11899 | return UNKNOWN_VALUE;
|
11900 | };
|
11901 | MultiExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
11902 | return new MultiExpression(this.expressions.map(function (expression) {
|
11903 | return expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
11904 | }));
|
11905 | };
|
11906 | MultiExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
11907 | for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
|
11908 | var expression = _a[_i];
|
11909 | if (expression.hasEffectsWhenAccessedAtPath(path, options))
|
11910 | return true;
|
11911 | }
|
11912 | return false;
|
11913 | };
|
11914 | MultiExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
11915 | for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
|
11916 | var expression = _a[_i];
|
11917 | if (expression.hasEffectsWhenAssignedAtPath(path, options))
|
11918 | return true;
|
11919 | }
|
11920 | return false;
|
11921 | };
|
11922 | MultiExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
11923 | for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
|
11924 | var expression = _a[_i];
|
11925 | if (expression.hasEffectsWhenCalledAtPath(path, callOptions, options))
|
11926 | return true;
|
11927 | }
|
11928 | return false;
|
11929 | };
|
11930 | MultiExpression.prototype.include = function () { };
|
11931 | return MultiExpression;
|
11932 | }());
|
11933 |
|
11934 | var ConditionalExpression = /** @class */ (function (_super) {
|
11935 | __extends(ConditionalExpression, _super);
|
11936 | function ConditionalExpression() {
|
11937 | return _super !== null && _super.apply(this, arguments) || this;
|
11938 | }
|
11939 | ConditionalExpression.prototype.bind = function () {
|
11940 | _super.prototype.bind.call(this);
|
11941 | if (!this.isBranchResolutionAnalysed)
|
11942 | this.analyseBranchResolution();
|
11943 | };
|
11944 | ConditionalExpression.prototype.deoptimizeCache = function () {
|
11945 | if (this.usedBranch !== null) {
|
11946 | // We did not track if there were reassignments to the previous branch.
|
11947 | // Also, the return value might need to be reassigned.
|
11948 | this.usedBranch = null;
|
11949 | this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
|
11950 | for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
|
11951 | var expression = _a[_i];
|
11952 | expression.deoptimizeCache();
|
11953 | }
|
11954 | }
|
11955 | };
|
11956 | ConditionalExpression.prototype.deoptimizePath = function (path) {
|
11957 | if (path.length > 0) {
|
11958 | if (!this.isBranchResolutionAnalysed)
|
11959 | this.analyseBranchResolution();
|
11960 | if (this.usedBranch === null) {
|
11961 | this.consequent.deoptimizePath(path);
|
11962 | this.alternate.deoptimizePath(path);
|
11963 | }
|
11964 | else {
|
11965 | this.usedBranch.deoptimizePath(path);
|
11966 | }
|
11967 | }
|
11968 | };
|
11969 | ConditionalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
11970 | if (!this.isBranchResolutionAnalysed)
|
11971 | this.analyseBranchResolution();
|
11972 | if (this.usedBranch === null)
|
11973 | return UNKNOWN_VALUE;
|
11974 | this.expressionsToBeDeoptimized.push(origin);
|
11975 | return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
|
11976 | };
|
11977 | ConditionalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
11978 | if (!this.isBranchResolutionAnalysed)
|
11979 | this.analyseBranchResolution();
|
11980 | if (this.usedBranch === null)
|
11981 | return new MultiExpression([
|
11982 | this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
|
11983 | this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
|
11984 | ]);
|
11985 | this.expressionsToBeDeoptimized.push(origin);
|
11986 | return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
11987 | };
|
11988 | ConditionalExpression.prototype.hasEffects = function (options) {
|
11989 | if (this.test.hasEffects(options))
|
11990 | return true;
|
11991 | if (this.usedBranch === null) {
|
11992 | return this.consequent.hasEffects(options) || this.alternate.hasEffects(options);
|
11993 | }
|
11994 | return this.usedBranch.hasEffects(options);
|
11995 | };
|
11996 | ConditionalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
11997 | if (path.length === 0)
|
11998 | return false;
|
11999 | if (this.usedBranch === null) {
|
12000 | return (this.consequent.hasEffectsWhenAccessedAtPath(path, options) ||
|
12001 | this.alternate.hasEffectsWhenAccessedAtPath(path, options));
|
12002 | }
|
12003 | return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
|
12004 | };
|
12005 | ConditionalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
12006 | if (path.length === 0)
|
12007 | return true;
|
12008 | if (this.usedBranch === null) {
|
12009 | return (this.consequent.hasEffectsWhenAssignedAtPath(path, options) ||
|
12010 | this.alternate.hasEffectsWhenAssignedAtPath(path, options));
|
12011 | }
|
12012 | return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
|
12013 | };
|
12014 | ConditionalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
12015 | if (this.usedBranch === null) {
|
12016 | return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
|
12017 | this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, options));
|
12018 | }
|
12019 | return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
12020 | };
|
12021 | ConditionalExpression.prototype.include = function (includeAllChildrenRecursively) {
|
12022 | this.included = true;
|
12023 | if (includeAllChildrenRecursively || this.usedBranch === null || this.test.shouldBeIncluded()) {
|
12024 | this.test.include(includeAllChildrenRecursively);
|
12025 | this.consequent.include(includeAllChildrenRecursively);
|
12026 | this.alternate.include(includeAllChildrenRecursively);
|
12027 | }
|
12028 | else {
|
12029 | this.usedBranch.include(includeAllChildrenRecursively);
|
12030 | }
|
12031 | };
|
12032 | ConditionalExpression.prototype.initialise = function () {
|
12033 | this.included = false;
|
12034 | this.isBranchResolutionAnalysed = false;
|
12035 | this.usedBranch = null;
|
12036 | this.unusedBranch = null;
|
12037 | this.expressionsToBeDeoptimized = [];
|
12038 | };
|
12039 | ConditionalExpression.prototype.render = function (code, options, _a) {
|
12040 | var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
|
12041 | if (!this.test.included) {
|
12042 | code.remove(this.start, this.usedBranch.start);
|
12043 | code.remove(this.usedBranch.end, this.end);
|
12044 | removeAnnotations(this, code);
|
12045 | this.usedBranch.render(code, options, {
|
12046 | isCalleeOfRenderedParent: renderedParentType
|
12047 | ? isCalleeOfRenderedParent
|
12048 | : this.parent.callee === this,
|
12049 | renderedParentType: renderedParentType || this.parent.type
|
12050 | });
|
12051 | }
|
12052 | else {
|
12053 | _super.prototype.render.call(this, code, options);
|
12054 | }
|
12055 | };
|
12056 | ConditionalExpression.prototype.analyseBranchResolution = function () {
|
12057 | this.isBranchResolutionAnalysed = true;
|
12058 | var testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
12059 | if (testValue !== UNKNOWN_VALUE) {
|
12060 | if (testValue) {
|
12061 | this.usedBranch = this.consequent;
|
12062 | this.unusedBranch = this.alternate;
|
12063 | }
|
12064 | else {
|
12065 | this.usedBranch = this.alternate;
|
12066 | this.unusedBranch = this.consequent;
|
12067 | }
|
12068 | }
|
12069 | };
|
12070 | return ConditionalExpression;
|
12071 | }(NodeBase));
|
12072 |
|
12073 | var DoWhileStatement = /** @class */ (function (_super) {
|
12074 | __extends(DoWhileStatement, _super);
|
12075 | function DoWhileStatement() {
|
12076 | return _super !== null && _super.apply(this, arguments) || this;
|
12077 | }
|
12078 | DoWhileStatement.prototype.hasEffects = function (options) {
|
12079 | return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
|
12080 | };
|
12081 | return DoWhileStatement;
|
12082 | }(NodeBase));
|
12083 |
|
12084 | var EmptyStatement = /** @class */ (function (_super) {
|
12085 | __extends(EmptyStatement, _super);
|
12086 | function EmptyStatement() {
|
12087 | return _super !== null && _super.apply(this, arguments) || this;
|
12088 | }
|
12089 | EmptyStatement.prototype.hasEffects = function () {
|
12090 | return false;
|
12091 | };
|
12092 | return EmptyStatement;
|
12093 | }(NodeBase));
|
12094 |
|
12095 | var ExportAllDeclaration$1 = /** @class */ (function (_super) {
|
12096 | __extends(ExportAllDeclaration, _super);
|
12097 | function ExportAllDeclaration() {
|
12098 | return _super !== null && _super.apply(this, arguments) || this;
|
12099 | }
|
12100 | ExportAllDeclaration.prototype.hasEffects = function () {
|
12101 | return false;
|
12102 | };
|
12103 | ExportAllDeclaration.prototype.initialise = function () {
|
12104 | this.included = false;
|
12105 | this.context.addExport(this);
|
12106 | };
|
12107 | ExportAllDeclaration.prototype.render = function (code, _options, _a) {
|
12108 | var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
|
12109 | code.remove(start, end);
|
12110 | };
|
12111 | return ExportAllDeclaration;
|
12112 | }(NodeBase));
|
12113 | ExportAllDeclaration$1.prototype.needsBoundaries = true;
|
12114 |
|
12115 | var ExportNamedDeclaration = /** @class */ (function (_super) {
|
12116 | __extends(ExportNamedDeclaration, _super);
|
12117 | function ExportNamedDeclaration() {
|
12118 | return _super !== null && _super.apply(this, arguments) || this;
|
12119 | }
|
12120 | ExportNamedDeclaration.prototype.bind = function () {
|
12121 | // Do not bind specifiers
|
12122 | if (this.declaration !== null)
|
12123 | this.declaration.bind();
|
12124 | };
|
12125 | ExportNamedDeclaration.prototype.hasEffects = function (options) {
|
12126 | return this.declaration && this.declaration.hasEffects(options);
|
12127 | };
|
12128 | ExportNamedDeclaration.prototype.initialise = function () {
|
12129 | this.included = false;
|
12130 | this.context.addExport(this);
|
12131 | };
|
12132 | ExportNamedDeclaration.prototype.render = function (code, options, _a) {
|
12133 | var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
|
12134 | if (this.declaration === null) {
|
12135 | code.remove(start, end);
|
12136 | }
|
12137 | else {
|
12138 | code.remove(this.start, this.declaration.start);
|
12139 | this.declaration.render(code, options, { start: start, end: end });
|
12140 | }
|
12141 | };
|
12142 | return ExportNamedDeclaration;
|
12143 | }(NodeBase));
|
12144 | ExportNamedDeclaration.prototype.needsBoundaries = true;
|
12145 |
|
12146 | var ExpressionStatement$1 = /** @class */ (function (_super) {
|
12147 | __extends(ExpressionStatement, _super);
|
12148 | function ExpressionStatement() {
|
12149 | return _super !== null && _super.apply(this, arguments) || this;
|
12150 | }
|
12151 | ExpressionStatement.prototype.initialise = function () {
|
12152 | this.included = false;
|
12153 | if (this.directive &&
|
12154 | this.directive !== 'use strict' &&
|
12155 | this.parent.type === Program) {
|
12156 | this.context.warn(
|
12157 | // This is necessary, because either way (deleting or not) can lead to errors.
|
12158 | {
|
12159 | code: 'MODULE_LEVEL_DIRECTIVE',
|
12160 | message: "Module level directives cause errors when bundled, '" + this.directive + "' was ignored."
|
12161 | }, this.start);
|
12162 | }
|
12163 | };
|
12164 | ExpressionStatement.prototype.render = function (code, options) {
|
12165 | _super.prototype.render.call(this, code, options);
|
12166 | if (this.included)
|
12167 | this.insertSemicolon(code);
|
12168 | };
|
12169 | ExpressionStatement.prototype.shouldBeIncluded = function () {
|
12170 | if (this.directive && this.directive !== 'use strict')
|
12171 | return this.parent.type !== Program;
|
12172 | return _super.prototype.shouldBeIncluded.call(this);
|
12173 | };
|
12174 | return ExpressionStatement;
|
12175 | }(NodeBase));
|
12176 |
|
12177 | var ForInStatement = /** @class */ (function (_super) {
|
12178 | __extends(ForInStatement, _super);
|
12179 | function ForInStatement() {
|
12180 | return _super !== null && _super.apply(this, arguments) || this;
|
12181 | }
|
12182 | ForInStatement.prototype.bind = function () {
|
12183 | this.left.bind();
|
12184 | this.left.deoptimizePath(EMPTY_PATH);
|
12185 | this.right.bind();
|
12186 | this.body.bind();
|
12187 | };
|
12188 | ForInStatement.prototype.createScope = function (parentScope) {
|
12189 | this.scope = new BlockScope(parentScope);
|
12190 | };
|
12191 | ForInStatement.prototype.hasEffects = function (options) {
|
12192 | return ((this.left &&
|
12193 | (this.left.hasEffects(options) ||
|
12194 | this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
|
12195 | (this.right && this.right.hasEffects(options)) ||
|
12196 | this.body.hasEffects(options.setIgnoreBreakStatements()));
|
12197 | };
|
12198 | ForInStatement.prototype.include = function (includeAllChildrenRecursively) {
|
12199 | this.included = true;
|
12200 | this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
|
12201 | this.left.deoptimizePath(EMPTY_PATH);
|
12202 | this.right.include(includeAllChildrenRecursively);
|
12203 | this.body.include(includeAllChildrenRecursively);
|
12204 | };
|
12205 | ForInStatement.prototype.render = function (code, options) {
|
12206 | this.left.render(code, options, NO_SEMICOLON);
|
12207 | this.right.render(code, options, NO_SEMICOLON);
|
12208 | this.body.render(code, options);
|
12209 | };
|
12210 | return ForInStatement;
|
12211 | }(NodeBase));
|
12212 |
|
12213 | var ForOfStatement = /** @class */ (function (_super) {
|
12214 | __extends(ForOfStatement, _super);
|
12215 | function ForOfStatement() {
|
12216 | return _super !== null && _super.apply(this, arguments) || this;
|
12217 | }
|
12218 | ForOfStatement.prototype.bind = function () {
|
12219 | this.left.bind();
|
12220 | this.left.deoptimizePath(EMPTY_PATH);
|
12221 | this.right.bind();
|
12222 | this.body.bind();
|
12223 | };
|
12224 | ForOfStatement.prototype.createScope = function (parentScope) {
|
12225 | this.scope = new BlockScope(parentScope);
|
12226 | };
|
12227 | ForOfStatement.prototype.hasEffects = function (options) {
|
12228 | return ((this.left &&
|
12229 | (this.left.hasEffects(options) ||
|
12230 | this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
|
12231 | (this.right && this.right.hasEffects(options)) ||
|
12232 | this.body.hasEffects(options.setIgnoreBreakStatements()));
|
12233 | };
|
12234 | ForOfStatement.prototype.include = function (includeAllChildrenRecursively) {
|
12235 | this.included = true;
|
12236 | this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
|
12237 | this.left.deoptimizePath(EMPTY_PATH);
|
12238 | this.right.include(includeAllChildrenRecursively);
|
12239 | this.body.include(includeAllChildrenRecursively);
|
12240 | };
|
12241 | ForOfStatement.prototype.render = function (code, options) {
|
12242 | this.left.render(code, options, NO_SEMICOLON);
|
12243 | this.right.render(code, options, NO_SEMICOLON);
|
12244 | this.body.render(code, options);
|
12245 | };
|
12246 | return ForOfStatement;
|
12247 | }(NodeBase));
|
12248 |
|
12249 | var ForStatement = /** @class */ (function (_super) {
|
12250 | __extends(ForStatement, _super);
|
12251 | function ForStatement() {
|
12252 | return _super !== null && _super.apply(this, arguments) || this;
|
12253 | }
|
12254 | ForStatement.prototype.createScope = function (parentScope) {
|
12255 | this.scope = new BlockScope(parentScope);
|
12256 | };
|
12257 | ForStatement.prototype.hasEffects = function (options) {
|
12258 | return ((this.init && this.init.hasEffects(options)) ||
|
12259 | (this.test && this.test.hasEffects(options)) ||
|
12260 | (this.update && this.update.hasEffects(options)) ||
|
12261 | this.body.hasEffects(options.setIgnoreBreakStatements()));
|
12262 | };
|
12263 | ForStatement.prototype.render = function (code, options) {
|
12264 | if (this.init)
|
12265 | this.init.render(code, options, NO_SEMICOLON);
|
12266 | if (this.test)
|
12267 | this.test.render(code, options, NO_SEMICOLON);
|
12268 | if (this.update)
|
12269 | this.update.render(code, options, NO_SEMICOLON);
|
12270 | this.body.render(code, options);
|
12271 | };
|
12272 | return ForStatement;
|
12273 | }(NodeBase));
|
12274 |
|
12275 | var FunctionExpression$1 = /** @class */ (function (_super) {
|
12276 | __extends(FunctionExpression, _super);
|
12277 | function FunctionExpression() {
|
12278 | return _super !== null && _super.apply(this, arguments) || this;
|
12279 | }
|
12280 | return FunctionExpression;
|
12281 | }(FunctionNode));
|
12282 |
|
12283 | var IfStatement = /** @class */ (function (_super) {
|
12284 | __extends(IfStatement, _super);
|
12285 | function IfStatement() {
|
12286 | return _super !== null && _super.apply(this, arguments) || this;
|
12287 | }
|
12288 | IfStatement.prototype.bind = function () {
|
12289 | _super.prototype.bind.call(this);
|
12290 | if (!this.isTestValueAnalysed) {
|
12291 | this.testValue = UNKNOWN_VALUE;
|
12292 | this.isTestValueAnalysed = true;
|
12293 | this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
12294 | }
|
12295 | };
|
12296 | IfStatement.prototype.deoptimizeCache = function () {
|
12297 | this.testValue = UNKNOWN_VALUE;
|
12298 | };
|
12299 | IfStatement.prototype.hasEffects = function (options) {
|
12300 | if (this.test.hasEffects(options))
|
12301 | return true;
|
12302 | if (this.testValue === UNKNOWN_VALUE) {
|
12303 | return (this.consequent.hasEffects(options) ||
|
12304 | (this.alternate !== null && this.alternate.hasEffects(options)));
|
12305 | }
|
12306 | return this.testValue
|
12307 | ? this.consequent.hasEffects(options)
|
12308 | : this.alternate !== null && this.alternate.hasEffects(options);
|
12309 | };
|
12310 | IfStatement.prototype.include = function (includeAllChildrenRecursively) {
|
12311 | this.included = true;
|
12312 | if (includeAllChildrenRecursively) {
|
12313 | this.test.include(true);
|
12314 | this.consequent.include(true);
|
12315 | if (this.alternate !== null) {
|
12316 | this.alternate.include(true);
|
12317 | }
|
12318 | return;
|
12319 | }
|
12320 | var hasUnknownTest = this.testValue === UNKNOWN_VALUE;
|
12321 | if (hasUnknownTest || this.test.shouldBeIncluded()) {
|
12322 | this.test.include(false);
|
12323 | }
|
12324 | if ((hasUnknownTest || this.testValue) && this.consequent.shouldBeIncluded()) {
|
12325 | this.consequent.include(false);
|
12326 | }
|
12327 | if (this.alternate !== null &&
|
12328 | ((hasUnknownTest || !this.testValue) && this.alternate.shouldBeIncluded())) {
|
12329 | this.alternate.include(false);
|
12330 | }
|
12331 | };
|
12332 | IfStatement.prototype.initialise = function () {
|
12333 | this.included = false;
|
12334 | this.isTestValueAnalysed = false;
|
12335 | };
|
12336 | IfStatement.prototype.render = function (code, options) {
|
12337 | // Note that unknown test values are always included
|
12338 | if (!this.test.included &&
|
12339 | (this.testValue
|
12340 | ? this.alternate === null || !this.alternate.included
|
12341 | : !this.consequent.included)) {
|
12342 | var singleRetainedBranch = this.testValue ? this.consequent : this.alternate;
|
12343 | code.remove(this.start, singleRetainedBranch.start);
|
12344 | code.remove(singleRetainedBranch.end, this.end);
|
12345 | removeAnnotations(this, code);
|
12346 | singleRetainedBranch.render(code, options);
|
12347 | }
|
12348 | else {
|
12349 | if (this.test.included) {
|
12350 | this.test.render(code, options);
|
12351 | }
|
12352 | else {
|
12353 | code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
|
12354 | }
|
12355 | if (this.consequent.included) {
|
12356 | this.consequent.render(code, options);
|
12357 | }
|
12358 | else {
|
12359 | code.overwrite(this.consequent.start, this.consequent.end, ';');
|
12360 | }
|
12361 | if (this.alternate !== null) {
|
12362 | if (this.alternate.included) {
|
12363 | this.alternate.render(code, options);
|
12364 | }
|
12365 | else {
|
12366 | code.remove(this.consequent.end, this.alternate.end);
|
12367 | }
|
12368 | }
|
12369 | }
|
12370 | };
|
12371 | return IfStatement;
|
12372 | }(NodeBase));
|
12373 |
|
12374 | var getDynamicImportMechanism = function (options) {
|
12375 | switch (options.format) {
|
12376 | case 'cjs': {
|
12377 | var _ = options.compact ? '' : ' ';
|
12378 | return {
|
12379 | interopLeft: "Promise.resolve({" + _ + "default:" + _ + "require(",
|
12380 | interopRight: ")" + _ + "})",
|
12381 | left: 'Promise.resolve(require(',
|
12382 | right: '))'
|
12383 | };
|
12384 | }
|
12385 | case 'amd': {
|
12386 | var _ = options.compact ? '' : ' ';
|
12387 | var resolve = options.compact ? 'c' : 'resolve';
|
12388 | var reject = options.compact ? 'e' : 'reject';
|
12389 | return {
|
12390 | interopLeft: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
|
12391 | interopRight: "]," + _ + "function" + _ + "(m)" + _ + "{" + _ + resolve + "({" + _ + "default:" + _ + "m" + _ + "})" + _ + "}," + _ + reject + ")" + _ + "})",
|
12392 | left: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
|
12393 | right: "]," + _ + resolve + "," + _ + reject + ")" + _ + "})"
|
12394 | };
|
12395 | }
|
12396 | case 'system':
|
12397 | return {
|
12398 | left: 'module.import(',
|
12399 | right: ')'
|
12400 | };
|
12401 | case 'es':
|
12402 | return {
|
12403 | left: (options.dynamicImportFunction || 'import') + "(",
|
12404 | right: ')'
|
12405 | };
|
12406 | }
|
12407 | };
|
12408 | var Import = /** @class */ (function (_super) {
|
12409 | __extends(Import, _super);
|
12410 | function Import() {
|
12411 | return _super !== null && _super.apply(this, arguments) || this;
|
12412 | }
|
12413 | Import.prototype.include = function () {
|
12414 | this.included = true;
|
12415 | this.context.includeDynamicImport(this);
|
12416 | };
|
12417 | Import.prototype.initialise = function () {
|
12418 | this.included = false;
|
12419 | this.resolutionNamespace = undefined;
|
12420 | this.resolutionInterop = false;
|
12421 | this.context.addDynamicImport(this);
|
12422 | };
|
12423 | Import.prototype.render = function (code, options) {
|
12424 | if (this.resolutionNamespace) {
|
12425 | var _ = options.compact ? '' : ' ';
|
12426 | var s = options.compact ? '' : ';';
|
12427 | code.overwrite(this.parent.start, this.parent.end, "Promise.resolve().then(function" + _ + "()" + _ + "{" + _ + "return " + this.resolutionNamespace + s + _ + "})");
|
12428 | return;
|
12429 | }
|
12430 | var importMechanism = getDynamicImportMechanism(options);
|
12431 | if (importMechanism) {
|
12432 | var leftMechanism = (this.resolutionInterop && importMechanism.interopLeft) || importMechanism.left;
|
12433 | var leftMechanismEnd = findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1;
|
12434 | code.overwrite(this.parent.start, leftMechanismEnd, leftMechanism);
|
12435 | var rightMechanism = (this.resolutionInterop && importMechanism.interopRight) || importMechanism.right;
|
12436 | code.overwrite(this.parent.end - 1, this.parent.end, rightMechanism);
|
12437 | }
|
12438 | };
|
12439 | Import.prototype.renderFinalResolution = function (code, resolution, format) {
|
12440 | if (this.included) {
|
12441 | if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
|
12442 | resolution = resolution.slice(0, -4) + "'";
|
12443 | }
|
12444 | code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution);
|
12445 | }
|
12446 | };
|
12447 | Import.prototype.setResolution = function (interop, namespace) {
|
12448 | if (namespace === void 0) { namespace = undefined; }
|
12449 | this.resolutionInterop = interop;
|
12450 | this.resolutionNamespace = namespace;
|
12451 | };
|
12452 | return Import;
|
12453 | }(NodeBase));
|
12454 |
|
12455 | var ImportDeclaration = /** @class */ (function (_super) {
|
12456 | __extends(ImportDeclaration, _super);
|
12457 | function ImportDeclaration() {
|
12458 | return _super !== null && _super.apply(this, arguments) || this;
|
12459 | }
|
12460 | ImportDeclaration.prototype.bind = function () { };
|
12461 | ImportDeclaration.prototype.hasEffects = function () {
|
12462 | return false;
|
12463 | };
|
12464 | ImportDeclaration.prototype.initialise = function () {
|
12465 | this.included = false;
|
12466 | this.context.addImport(this);
|
12467 | };
|
12468 | ImportDeclaration.prototype.render = function (code, _options, _a) {
|
12469 | var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
|
12470 | code.remove(start, end);
|
12471 | };
|
12472 | return ImportDeclaration;
|
12473 | }(NodeBase));
|
12474 | ImportDeclaration.prototype.needsBoundaries = true;
|
12475 |
|
12476 | var LabeledStatement = /** @class */ (function (_super) {
|
12477 | __extends(LabeledStatement, _super);
|
12478 | function LabeledStatement() {
|
12479 | return _super !== null && _super.apply(this, arguments) || this;
|
12480 | }
|
12481 | LabeledStatement.prototype.hasEffects = function (options) {
|
12482 | return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements());
|
12483 | };
|
12484 | return LabeledStatement;
|
12485 | }(NodeBase));
|
12486 |
|
12487 | function isLiteral(node) {
|
12488 | return node.type === Literal;
|
12489 | }
|
12490 | var Literal$1 = /** @class */ (function (_super) {
|
12491 | __extends(Literal, _super);
|
12492 | function Literal() {
|
12493 | return _super !== null && _super.apply(this, arguments) || this;
|
12494 | }
|
12495 | Literal.prototype.getLiteralValueAtPath = function (path) {
|
12496 | if (path.length > 0 ||
|
12497 | // unknown literals such as bigints can also be null but do not start with an "n"
|
12498 | (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
|
12499 | typeof this.value === 'bigint') {
|
12500 | return UNKNOWN_VALUE;
|
12501 | }
|
12502 | return this.value;
|
12503 | };
|
12504 | Literal.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
|
12505 | if (path.length !== 1)
|
12506 | return UNKNOWN_EXPRESSION;
|
12507 | return getMemberReturnExpressionWhenCalled(this.members, path[0]);
|
12508 | };
|
12509 | Literal.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
12510 | if (this.value === null) {
|
12511 | return path.length > 0;
|
12512 | }
|
12513 | return path.length > 1;
|
12514 | };
|
12515 | Literal.prototype.hasEffectsWhenAssignedAtPath = function (path) {
|
12516 | return path.length > 0;
|
12517 | };
|
12518 | Literal.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
12519 | if (path.length === 1) {
|
12520 | return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options);
|
12521 | }
|
12522 | return true;
|
12523 | };
|
12524 | Literal.prototype.initialise = function () {
|
12525 | this.included = false;
|
12526 | this.members = getLiteralMembersForValue(this.value);
|
12527 | };
|
12528 | Literal.prototype.render = function (code, _options) {
|
12529 | if (typeof this.value === 'string') {
|
12530 | code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
|
12531 | }
|
12532 | };
|
12533 | return Literal;
|
12534 | }(NodeBase));
|
12535 |
|
12536 | var LogicalExpression = /** @class */ (function (_super) {
|
12537 | __extends(LogicalExpression, _super);
|
12538 | function LogicalExpression() {
|
12539 | return _super !== null && _super.apply(this, arguments) || this;
|
12540 | }
|
12541 | LogicalExpression.prototype.bind = function () {
|
12542 | _super.prototype.bind.call(this);
|
12543 | if (!this.isBranchResolutionAnalysed)
|
12544 | this.analyseBranchResolution();
|
12545 | };
|
12546 | LogicalExpression.prototype.deoptimizeCache = function () {
|
12547 | if (this.usedBranch !== null) {
|
12548 | // We did not track if there were reassignments to any of the branches.
|
12549 | // Also, the return values might need reassignment.
|
12550 | this.usedBranch = null;
|
12551 | this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
|
12552 | for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
|
12553 | var expression = _a[_i];
|
12554 | expression.deoptimizeCache();
|
12555 | }
|
12556 | }
|
12557 | };
|
12558 | LogicalExpression.prototype.deoptimizePath = function (path) {
|
12559 | if (path.length > 0) {
|
12560 | if (!this.isBranchResolutionAnalysed)
|
12561 | this.analyseBranchResolution();
|
12562 | if (this.usedBranch === null) {
|
12563 | this.left.deoptimizePath(path);
|
12564 | this.right.deoptimizePath(path);
|
12565 | }
|
12566 | else {
|
12567 | this.usedBranch.deoptimizePath(path);
|
12568 | }
|
12569 | }
|
12570 | };
|
12571 | LogicalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
12572 | if (!this.isBranchResolutionAnalysed)
|
12573 | this.analyseBranchResolution();
|
12574 | if (this.usedBranch === null)
|
12575 | return UNKNOWN_VALUE;
|
12576 | this.expressionsToBeDeoptimized.push(origin);
|
12577 | return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
|
12578 | };
|
12579 | LogicalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
12580 | if (!this.isBranchResolutionAnalysed)
|
12581 | this.analyseBranchResolution();
|
12582 | if (this.usedBranch === null)
|
12583 | return new MultiExpression([
|
12584 | this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
|
12585 | this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
|
12586 | ]);
|
12587 | this.expressionsToBeDeoptimized.push(origin);
|
12588 | return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
12589 | };
|
12590 | LogicalExpression.prototype.hasEffects = function (options) {
|
12591 | if (this.usedBranch === null) {
|
12592 | return this.left.hasEffects(options) || this.right.hasEffects(options);
|
12593 | }
|
12594 | return this.usedBranch.hasEffects(options);
|
12595 | };
|
12596 | LogicalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
12597 | if (path.length === 0)
|
12598 | return false;
|
12599 | if (this.usedBranch === null) {
|
12600 | return (this.left.hasEffectsWhenAccessedAtPath(path, options) ||
|
12601 | this.right.hasEffectsWhenAccessedAtPath(path, options));
|
12602 | }
|
12603 | return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
|
12604 | };
|
12605 | LogicalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
12606 | if (path.length === 0)
|
12607 | return true;
|
12608 | if (this.usedBranch === null) {
|
12609 | return (this.left.hasEffectsWhenAssignedAtPath(path, options) ||
|
12610 | this.right.hasEffectsWhenAssignedAtPath(path, options));
|
12611 | }
|
12612 | return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
|
12613 | };
|
12614 | LogicalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
12615 | if (this.usedBranch === null) {
|
12616 | return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
|
12617 | this.right.hasEffectsWhenCalledAtPath(path, callOptions, options));
|
12618 | }
|
12619 | return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
12620 | };
|
12621 | LogicalExpression.prototype.include = function (includeAllChildrenRecursively) {
|
12622 | this.included = true;
|
12623 | if (includeAllChildrenRecursively ||
|
12624 | this.usedBranch === null ||
|
12625 | this.unusedBranch.shouldBeIncluded()) {
|
12626 | this.left.include(includeAllChildrenRecursively);
|
12627 | this.right.include(includeAllChildrenRecursively);
|
12628 | }
|
12629 | else {
|
12630 | this.usedBranch.include(includeAllChildrenRecursively);
|
12631 | }
|
12632 | };
|
12633 | LogicalExpression.prototype.initialise = function () {
|
12634 | this.included = false;
|
12635 | this.isBranchResolutionAnalysed = false;
|
12636 | this.usedBranch = null;
|
12637 | this.unusedBranch = null;
|
12638 | this.expressionsToBeDeoptimized = [];
|
12639 | };
|
12640 | LogicalExpression.prototype.render = function (code, options, _a) {
|
12641 | var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
|
12642 | if (!this.left.included || !this.right.included) {
|
12643 | code.remove(this.start, this.usedBranch.start);
|
12644 | code.remove(this.usedBranch.end, this.end);
|
12645 | removeAnnotations(this, code);
|
12646 | this.usedBranch.render(code, options, {
|
12647 | isCalleeOfRenderedParent: renderedParentType
|
12648 | ? isCalleeOfRenderedParent
|
12649 | : this.parent.callee === this,
|
12650 | renderedParentType: renderedParentType || this.parent.type
|
12651 | });
|
12652 | }
|
12653 | else {
|
12654 | _super.prototype.render.call(this, code, options);
|
12655 | }
|
12656 | };
|
12657 | LogicalExpression.prototype.analyseBranchResolution = function () {
|
12658 | this.isBranchResolutionAnalysed = true;
|
12659 | var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
12660 | if (leftValue !== UNKNOWN_VALUE) {
|
12661 | if (this.operator === '||' ? leftValue : !leftValue) {
|
12662 | this.usedBranch = this.left;
|
12663 | this.unusedBranch = this.right;
|
12664 | }
|
12665 | else {
|
12666 | this.usedBranch = this.right;
|
12667 | this.unusedBranch = this.left;
|
12668 | }
|
12669 | }
|
12670 | };
|
12671 | return LogicalExpression;
|
12672 | }(NodeBase));
|
12673 |
|
12674 | function getResolvablePropertyKey(memberExpression) {
|
12675 | return memberExpression.computed
|
12676 | ? getResolvableComputedPropertyKey(memberExpression.property)
|
12677 | : memberExpression.property.name;
|
12678 | }
|
12679 | function getResolvableComputedPropertyKey(propertyKey) {
|
12680 | if (propertyKey instanceof Literal$1) {
|
12681 | return String(propertyKey.value);
|
12682 | }
|
12683 | return null;
|
12684 | }
|
12685 | function getPathIfNotComputed(memberExpression) {
|
12686 | var nextPathKey = memberExpression.propertyKey;
|
12687 | var object = memberExpression.object;
|
12688 | if (typeof nextPathKey === 'string') {
|
12689 | if (object instanceof Identifier$1) {
|
12690 | return [
|
12691 | { key: object.name, pos: object.start },
|
12692 | { key: nextPathKey, pos: memberExpression.property.start }
|
12693 | ];
|
12694 | }
|
12695 | if (isMemberExpression(object)) {
|
12696 | var parentPath = getPathIfNotComputed(object);
|
12697 | return (parentPath && parentPath.concat([{ key: nextPathKey, pos: memberExpression.property.start }]));
|
12698 | }
|
12699 | }
|
12700 | return null;
|
12701 | }
|
12702 | function getStringFromPath(path) {
|
12703 | var pathString = path[0].key;
|
12704 | for (var index = 1; index < path.length; index++) {
|
12705 | pathString += '.' + path[index].key;
|
12706 | }
|
12707 | return pathString;
|
12708 | }
|
12709 | function isMemberExpression(node) {
|
12710 | return node.type === MemberExpression;
|
12711 | }
|
12712 | var MemberExpression$1 = /** @class */ (function (_super) {
|
12713 | __extends(MemberExpression, _super);
|
12714 | function MemberExpression() {
|
12715 | var _this = _super !== null && _super.apply(this, arguments) || this;
|
12716 | _this.variable = null;
|
12717 | return _this;
|
12718 | }
|
12719 | MemberExpression.prototype.addExportedVariables = function () { };
|
12720 | MemberExpression.prototype.bind = function () {
|
12721 | if (this.bound)
|
12722 | return;
|
12723 | this.bound = true;
|
12724 | var path = getPathIfNotComputed(this);
|
12725 | var baseVariable = path && this.scope.findVariable(path[0].key);
|
12726 | if (baseVariable && baseVariable.isNamespace) {
|
12727 | var resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
|
12728 | if (!resolvedVariable) {
|
12729 | _super.prototype.bind.call(this);
|
12730 | }
|
12731 | else if (typeof resolvedVariable === 'string') {
|
12732 | this.replacement = resolvedVariable;
|
12733 | }
|
12734 | else {
|
12735 | if (resolvedVariable.isExternal && resolvedVariable.module) {
|
12736 | resolvedVariable.module.suggestName(path[0].key);
|
12737 | }
|
12738 | this.variable = resolvedVariable;
|
12739 | this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
|
12740 | }
|
12741 | }
|
12742 | else {
|
12743 | _super.prototype.bind.call(this);
|
12744 | if (this.propertyKey === null)
|
12745 | this.analysePropertyKey();
|
12746 | }
|
12747 | };
|
12748 | MemberExpression.prototype.deoptimizeCache = function () {
|
12749 | for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
|
12750 | var expression = _a[_i];
|
12751 | expression.deoptimizeCache();
|
12752 | }
|
12753 | };
|
12754 | MemberExpression.prototype.deoptimizePath = function (path) {
|
12755 | if (!this.bound)
|
12756 | this.bind();
|
12757 | if (path.length === 0)
|
12758 | this.disallowNamespaceReassignment();
|
12759 | if (this.variable) {
|
12760 | this.variable.deoptimizePath(path);
|
12761 | }
|
12762 | else {
|
12763 | if (this.propertyKey === null)
|
12764 | this.analysePropertyKey();
|
12765 | this.object.deoptimizePath([this.propertyKey].concat(path));
|
12766 | }
|
12767 | };
|
12768 | MemberExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
12769 | if (this.variable !== null) {
|
12770 | return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
|
12771 | }
|
12772 | if (this.propertyKey === null)
|
12773 | this.analysePropertyKey();
|
12774 | this.expressionsToBeDeoptimized.push(origin);
|
12775 | return this.object.getLiteralValueAtPath([this.propertyKey].concat(path), recursionTracker, origin);
|
12776 | };
|
12777 | MemberExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
12778 | if (this.variable !== null) {
|
12779 | return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
12780 | }
|
12781 | if (this.propertyKey === null)
|
12782 | this.analysePropertyKey();
|
12783 | this.expressionsToBeDeoptimized.push(origin);
|
12784 | return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey].concat(path), recursionTracker, origin);
|
12785 | };
|
12786 | MemberExpression.prototype.hasEffects = function (options) {
|
12787 | return (this.property.hasEffects(options) ||
|
12788 | this.object.hasEffects(options) ||
|
12789 | (this.context.propertyReadSideEffects &&
|
12790 | this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options)));
|
12791 | };
|
12792 | MemberExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
12793 | if (path.length === 0) {
|
12794 | return false;
|
12795 | }
|
12796 | if (this.variable !== null) {
|
12797 | return this.variable.hasEffectsWhenAccessedAtPath(path, options);
|
12798 | }
|
12799 | return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey].concat(path), options);
|
12800 | };
|
12801 | MemberExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
12802 | if (this.variable !== null) {
|
12803 | return this.variable.hasEffectsWhenAssignedAtPath(path, options);
|
12804 | }
|
12805 | return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey].concat(path), options);
|
12806 | };
|
12807 | MemberExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
12808 | if (this.variable !== null) {
|
12809 | return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
12810 | }
|
12811 | return this.object.hasEffectsWhenCalledAtPath([this.propertyKey].concat(path), callOptions, options);
|
12812 | };
|
12813 | MemberExpression.prototype.include = function (includeAllChildrenRecursively) {
|
12814 | if (!this.included) {
|
12815 | this.included = true;
|
12816 | if (this.variable !== null) {
|
12817 | this.context.includeVariable(this.variable);
|
12818 | }
|
12819 | }
|
12820 | this.object.include(includeAllChildrenRecursively);
|
12821 | this.property.include(includeAllChildrenRecursively);
|
12822 | };
|
12823 | MemberExpression.prototype.initialise = function () {
|
12824 | this.included = false;
|
12825 | this.propertyKey = getResolvablePropertyKey(this);
|
12826 | this.variable = null;
|
12827 | this.bound = false;
|
12828 | this.replacement = null;
|
12829 | this.expressionsToBeDeoptimized = [];
|
12830 | };
|
12831 | MemberExpression.prototype.render = function (code, options, _a) {
|
12832 | var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
|
12833 | var isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
|
12834 | if (this.variable || this.replacement) {
|
12835 | var replacement = this.variable ? this.variable.getName() : this.replacement;
|
12836 | if (isCalleeOfDifferentParent)
|
12837 | replacement = '0, ' + replacement;
|
12838 | code.overwrite(this.start, this.end, replacement, {
|
12839 | contentOnly: true,
|
12840 | storeName: true
|
12841 | });
|
12842 | }
|
12843 | else {
|
12844 | if (isCalleeOfDifferentParent) {
|
12845 | code.appendRight(this.start, '0, ');
|
12846 | }
|
12847 | _super.prototype.render.call(this, code, options);
|
12848 | }
|
12849 | };
|
12850 | MemberExpression.prototype.analysePropertyKey = function () {
|
12851 | this.propertyKey = UNKNOWN_KEY;
|
12852 | var value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
12853 | this.propertyKey = value === UNKNOWN_VALUE ? UNKNOWN_KEY : String(value);
|
12854 | };
|
12855 | MemberExpression.prototype.disallowNamespaceReassignment = function () {
|
12856 | if (this.object instanceof Identifier$1 &&
|
12857 | this.scope.findVariable(this.object.name).isNamespace) {
|
12858 | this.context.error({
|
12859 | code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
|
12860 | message: "Illegal reassignment to import '" + this.object.name + "'"
|
12861 | }, this.start);
|
12862 | }
|
12863 | };
|
12864 | MemberExpression.prototype.resolveNamespaceVariables = function (baseVariable, path) {
|
12865 | if (path.length === 0)
|
12866 | return baseVariable;
|
12867 | if (!baseVariable.isNamespace)
|
12868 | return null;
|
12869 | var exportName = path[0].key;
|
12870 | var variable = baseVariable.isExternal
|
12871 | ? baseVariable.module.getVariableForExportName(exportName)
|
12872 | : baseVariable.context.traceExport(exportName);
|
12873 | if (!variable) {
|
12874 | var fileName = baseVariable.isExternal
|
12875 | ? baseVariable.module.id
|
12876 | : baseVariable.context.fileName;
|
12877 | this.context.warn({
|
12878 | code: 'MISSING_EXPORT',
|
12879 | exporter: relativeId(fileName),
|
12880 | importer: relativeId(this.context.fileName),
|
12881 | message: "'" + exportName + "' is not exported by '" + relativeId(fileName) + "'",
|
12882 | missing: exportName,
|
12883 | url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
|
12884 | }, path[0].pos);
|
12885 | return 'undefined';
|
12886 | }
|
12887 | return this.resolveNamespaceVariables(variable, path.slice(1));
|
12888 | };
|
12889 | return MemberExpression;
|
12890 | }(NodeBase));
|
12891 |
|
12892 | var ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
|
12893 | var CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
|
12894 | var MetaProperty = /** @class */ (function (_super) {
|
12895 | __extends(MetaProperty, _super);
|
12896 | function MetaProperty() {
|
12897 | return _super !== null && _super.apply(this, arguments) || this;
|
12898 | }
|
12899 | MetaProperty.prototype.hasEffectsWhenAccessedAtPath = function (path) {
|
12900 | return path.length > 1;
|
12901 | };
|
12902 | MetaProperty.prototype.initialise = function () {
|
12903 | if (this.meta.name === 'import') {
|
12904 | this.context.addImportMeta(this);
|
12905 | }
|
12906 | this.included = false;
|
12907 | };
|
12908 | MetaProperty.prototype.renderFinalMechanism = function (code, chunkId, format, pluginDriver) {
|
12909 | if (!this.included)
|
12910 | return false;
|
12911 | var parent = this.parent;
|
12912 | var importMetaProperty = parent instanceof MemberExpression$1 && typeof parent.propertyKey === 'string'
|
12913 | ? parent.propertyKey
|
12914 | : null;
|
12915 | if (importMetaProperty &&
|
12916 | (importMetaProperty.startsWith(ASSET_PREFIX) || importMetaProperty.startsWith(CHUNK_PREFIX))) {
|
12917 | var assetReferenceId = null;
|
12918 | var chunkReferenceId = null;
|
12919 | var fileName = void 0;
|
12920 | if (importMetaProperty.startsWith(ASSET_PREFIX)) {
|
12921 | assetReferenceId = importMetaProperty.substr(ASSET_PREFIX.length);
|
12922 | fileName = this.context.getAssetFileName(assetReferenceId);
|
12923 | }
|
12924 | else {
|
12925 | chunkReferenceId = importMetaProperty.substr(CHUNK_PREFIX.length);
|
12926 | fileName = this.context.getChunkFileName(chunkReferenceId);
|
12927 | }
|
12928 | var relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
|
12929 | var replacement_1;
|
12930 | if (assetReferenceId !== null) {
|
12931 | // deprecated hook for assets
|
12932 | replacement_1 = pluginDriver.hookFirstSync('resolveAssetUrl', [
|
12933 | {
|
12934 | assetFileName: fileName,
|
12935 | chunkId: chunkId,
|
12936 | format: format,
|
12937 | moduleId: this.context.module.id,
|
12938 | relativeAssetPath: relativePath
|
12939 | }
|
12940 | ]);
|
12941 | }
|
12942 | if (!replacement_1) {
|
12943 | replacement_1 = pluginDriver.hookFirstSync('resolveFileUrl', [
|
12944 | {
|
12945 | assetReferenceId: assetReferenceId,
|
12946 | chunkId: chunkId,
|
12947 | chunkReferenceId: chunkReferenceId,
|
12948 | fileName: fileName,
|
12949 | format: format,
|
12950 | moduleId: this.context.module.id,
|
12951 | relativePath: relativePath
|
12952 | }
|
12953 | ]);
|
12954 | }
|
12955 | code.overwrite(parent.start, parent.end, replacement_1);
|
12956 | return true;
|
12957 | }
|
12958 | var replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
|
12959 | importMetaProperty,
|
12960 | {
|
12961 | chunkId: chunkId,
|
12962 | format: format,
|
12963 | moduleId: this.context.module.id
|
12964 | }
|
12965 | ]);
|
12966 | if (typeof replacement === 'string') {
|
12967 | if (parent instanceof MemberExpression$1) {
|
12968 | code.overwrite(parent.start, parent.end, replacement);
|
12969 | }
|
12970 | else {
|
12971 | code.overwrite(this.start, this.end, replacement);
|
12972 | }
|
12973 | return true;
|
12974 | }
|
12975 | return false;
|
12976 | };
|
12977 | return MetaProperty;
|
12978 | }(NodeBase));
|
12979 |
|
12980 | var MethodDefinition = /** @class */ (function (_super) {
|
12981 | __extends(MethodDefinition, _super);
|
12982 | function MethodDefinition() {
|
12983 | return _super !== null && _super.apply(this, arguments) || this;
|
12984 | }
|
12985 | MethodDefinition.prototype.hasEffects = function (options) {
|
12986 | return this.key.hasEffects(options);
|
12987 | };
|
12988 | MethodDefinition.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
12989 | return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
|
12990 | };
|
12991 | return MethodDefinition;
|
12992 | }(NodeBase));
|
12993 |
|
12994 | var NewExpression = /** @class */ (function (_super) {
|
12995 | __extends(NewExpression, _super);
|
12996 | function NewExpression() {
|
12997 | return _super !== null && _super.apply(this, arguments) || this;
|
12998 | }
|
12999 | NewExpression.prototype.bind = function () {
|
13000 | _super.prototype.bind.call(this);
|
13001 | for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
|
13002 | var argument = _a[_i];
|
13003 | // This will make sure all properties of parameters behave as "unknown"
|
13004 | argument.deoptimizePath(UNKNOWN_PATH);
|
13005 | }
|
13006 | };
|
13007 | NewExpression.prototype.hasEffects = function (options) {
|
13008 | for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
|
13009 | var argument = _a[_i];
|
13010 | if (argument.hasEffects(options))
|
13011 | return true;
|
13012 | }
|
13013 | if (this.annotatedPure)
|
13014 | return false;
|
13015 | return this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions());
|
13016 | };
|
13017 | NewExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
13018 | return path.length > 1;
|
13019 | };
|
13020 | NewExpression.prototype.initialise = function () {
|
13021 | this.included = false;
|
13022 | this.callOptions = CallOptions.create({
|
13023 | args: this.arguments,
|
13024 | callIdentifier: this,
|
13025 | withNew: true
|
13026 | });
|
13027 | };
|
13028 | return NewExpression;
|
13029 | }(NodeBase));
|
13030 |
|
13031 | var SpreadElement = /** @class */ (function (_super) {
|
13032 | __extends(SpreadElement, _super);
|
13033 | function SpreadElement() {
|
13034 | return _super !== null && _super.apply(this, arguments) || this;
|
13035 | }
|
13036 | SpreadElement.prototype.bind = function () {
|
13037 | _super.prototype.bind.call(this);
|
13038 | // Only properties of properties of the argument could become subject to reassignment
|
13039 | // This will also reassign the return values of iterators
|
13040 | this.argument.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
|
13041 | };
|
13042 | return SpreadElement;
|
13043 | }(NodeBase));
|
13044 |
|
13045 | var ObjectExpression = /** @class */ (function (_super) {
|
13046 | __extends(ObjectExpression, _super);
|
13047 | function ObjectExpression() {
|
13048 | return _super !== null && _super.apply(this, arguments) || this;
|
13049 | }
|
13050 | ObjectExpression.prototype.bind = function () {
|
13051 | _super.prototype.bind.call(this);
|
13052 | if (this.propertyMap === null)
|
13053 | this.buildPropertyMap();
|
13054 | };
|
13055 | // We could also track this per-property but this would quickly become much more complex
|
13056 | ObjectExpression.prototype.deoptimizeCache = function () {
|
13057 | if (!this.hasUnknownDeoptimizedProperty)
|
13058 | this.deoptimizeAllProperties();
|
13059 | };
|
13060 | ObjectExpression.prototype.deoptimizePath = function (path) {
|
13061 | if (this.hasUnknownDeoptimizedProperty)
|
13062 | return;
|
13063 | if (this.propertyMap === null)
|
13064 | this.buildPropertyMap();
|
13065 | if (path.length === 0) {
|
13066 | this.deoptimizeAllProperties();
|
13067 | return;
|
13068 | }
|
13069 | var key = path[0];
|
13070 | if (path.length === 1) {
|
13071 | if (typeof key !== 'string') {
|
13072 | this.deoptimizeAllProperties();
|
13073 | return;
|
13074 | }
|
13075 | if (!this.deoptimizedPaths[key]) {
|
13076 | this.deoptimizedPaths[key] = true;
|
13077 | // we only deoptimizeCache exact matches as in all other cases,
|
13078 | // we do not return a literal value or return expression
|
13079 | if (this.expressionsToBeDeoptimized[key]) {
|
13080 | for (var _i = 0, _a = this.expressionsToBeDeoptimized[key]; _i < _a.length; _i++) {
|
13081 | var expression = _a[_i];
|
13082 | expression.deoptimizeCache();
|
13083 | }
|
13084 | }
|
13085 | }
|
13086 | }
|
13087 | var subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
|
13088 | for (var _b = 0, _c = typeof key === 'string'
|
13089 | ? this.propertyMap[key]
|
13090 | ? this.propertyMap[key].propertiesRead
|
13091 | : []
|
13092 | : this.properties; _b < _c.length; _b++) {
|
13093 | var property = _c[_b];
|
13094 | property.deoptimizePath(subPath);
|
13095 | }
|
13096 | };
|
13097 | ObjectExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
13098 | if (this.propertyMap === null)
|
13099 | this.buildPropertyMap();
|
13100 | var key = path[0];
|
13101 | if (path.length === 0 ||
|
13102 | this.hasUnknownDeoptimizedProperty ||
|
13103 | typeof key !== 'string' ||
|
13104 | this.deoptimizedPaths[key])
|
13105 | return UNKNOWN_VALUE;
|
13106 | if (path.length === 1 &&
|
13107 | !this.propertyMap[key] &&
|
13108 | !objectMembers[key] &&
|
13109 | this.unmatchablePropertiesRead.length === 0) {
|
13110 | if (!this.expressionsToBeDeoptimized[key]) {
|
13111 | this.expressionsToBeDeoptimized[key] = [origin];
|
13112 | }
|
13113 | else {
|
13114 | this.expressionsToBeDeoptimized[key].push(origin);
|
13115 | }
|
13116 | return undefined;
|
13117 | }
|
13118 | if (!this.propertyMap[key] ||
|
13119 | this.propertyMap[key].exactMatchRead === null ||
|
13120 | this.propertyMap[key].propertiesRead.length > 1)
|
13121 | return UNKNOWN_VALUE;
|
13122 | if (!this.expressionsToBeDeoptimized[key]) {
|
13123 | this.expressionsToBeDeoptimized[key] = [origin];
|
13124 | }
|
13125 | else {
|
13126 | this.expressionsToBeDeoptimized[key].push(origin);
|
13127 | }
|
13128 | return this.propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
|
13129 | };
|
13130 | ObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
13131 | if (this.propertyMap === null)
|
13132 | this.buildPropertyMap();
|
13133 | var key = path[0];
|
13134 | if (path.length === 0 ||
|
13135 | this.hasUnknownDeoptimizedProperty ||
|
13136 | typeof key !== 'string' ||
|
13137 | this.deoptimizedPaths[key])
|
13138 | return UNKNOWN_EXPRESSION;
|
13139 | if (path.length === 1 &&
|
13140 | objectMembers[key] &&
|
13141 | this.unmatchablePropertiesRead.length === 0 &&
|
13142 | (!this.propertyMap[key] || this.propertyMap[key].exactMatchRead === null))
|
13143 | return getMemberReturnExpressionWhenCalled(objectMembers, key);
|
13144 | if (!this.propertyMap[key] ||
|
13145 | this.propertyMap[key].exactMatchRead === null ||
|
13146 | this.propertyMap[key].propertiesRead.length > 1)
|
13147 | return UNKNOWN_EXPRESSION;
|
13148 | if (!this.expressionsToBeDeoptimized[key]) {
|
13149 | this.expressionsToBeDeoptimized[key] = [origin];
|
13150 | }
|
13151 | else {
|
13152 | this.expressionsToBeDeoptimized[key].push(origin);
|
13153 | }
|
13154 | return this.propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
|
13155 | };
|
13156 | ObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
13157 | if (path.length === 0)
|
13158 | return false;
|
13159 | var key = path[0];
|
13160 | if (path.length > 1 &&
|
13161 | (this.hasUnknownDeoptimizedProperty ||
|
13162 | typeof key !== 'string' ||
|
13163 | this.deoptimizedPaths[key] ||
|
13164 | !this.propertyMap[key] ||
|
13165 | this.propertyMap[key].exactMatchRead === null))
|
13166 | return true;
|
13167 | var subPath = path.slice(1);
|
13168 | for (var _i = 0, _a = typeof key !== 'string'
|
13169 | ? this.properties
|
13170 | : this.propertyMap[key]
|
13171 | ? this.propertyMap[key].propertiesRead
|
13172 | : []; _i < _a.length; _i++) {
|
13173 | var property = _a[_i];
|
13174 | if (property.hasEffectsWhenAccessedAtPath(subPath, options))
|
13175 | return true;
|
13176 | }
|
13177 | return false;
|
13178 | };
|
13179 | ObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13180 | if (path.length === 0)
|
13181 | return false;
|
13182 | var key = path[0];
|
13183 | if (path.length > 1 &&
|
13184 | (this.hasUnknownDeoptimizedProperty ||
|
13185 | typeof key !== 'string' ||
|
13186 | this.deoptimizedPaths[key] ||
|
13187 | !this.propertyMap[key] ||
|
13188 | this.propertyMap[key].exactMatchRead === null))
|
13189 | return true;
|
13190 | var subPath = path.slice(1);
|
13191 | for (var _i = 0, _a = typeof key !== 'string'
|
13192 | ? this.properties
|
13193 | : path.length > 1
|
13194 | ? this.propertyMap[key].propertiesRead
|
13195 | : this.propertyMap[key]
|
13196 | ? this.propertyMap[key].propertiesSet
|
13197 | : []; _i < _a.length; _i++) {
|
13198 | var property = _a[_i];
|
13199 | if (property.hasEffectsWhenAssignedAtPath(subPath, options))
|
13200 | return true;
|
13201 | }
|
13202 | return false;
|
13203 | };
|
13204 | ObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
13205 | var key = path[0];
|
13206 | if (path.length === 0 ||
|
13207 | this.hasUnknownDeoptimizedProperty ||
|
13208 | typeof key !== 'string' ||
|
13209 | this.deoptimizedPaths[key] ||
|
13210 | (this.propertyMap[key]
|
13211 | ? !this.propertyMap[key].exactMatchRead
|
13212 | : path.length > 1 || !objectMembers[key]))
|
13213 | return true;
|
13214 | var subPath = path.slice(1);
|
13215 | for (var _i = 0, _a = this.propertyMap[key] ? this.propertyMap[key].propertiesRead : []; _i < _a.length; _i++) {
|
13216 | var property = _a[_i];
|
13217 | if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options))
|
13218 | return true;
|
13219 | }
|
13220 | if (path.length === 1 && objectMembers[key])
|
13221 | return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, options);
|
13222 | return false;
|
13223 | };
|
13224 | ObjectExpression.prototype.initialise = function () {
|
13225 | this.included = false;
|
13226 | this.hasUnknownDeoptimizedProperty = false;
|
13227 | this.deoptimizedPaths = Object.create(null);
|
13228 | this.propertyMap = null;
|
13229 | this.expressionsToBeDeoptimized = Object.create(null);
|
13230 | };
|
13231 | ObjectExpression.prototype.render = function (code, options, _a) {
|
13232 | var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
|
13233 | _super.prototype.render.call(this, code, options);
|
13234 | if (renderedParentType === ExpressionStatement) {
|
13235 | code.appendRight(this.start, '(');
|
13236 | code.prependLeft(this.end, ')');
|
13237 | }
|
13238 | };
|
13239 | ObjectExpression.prototype.buildPropertyMap = function () {
|
13240 | var _a, _b;
|
13241 | this.propertyMap = Object.create(null);
|
13242 | this.unmatchablePropertiesRead = [];
|
13243 | this.unmatchablePropertiesWrite = [];
|
13244 | for (var index = this.properties.length - 1; index >= 0; index--) {
|
13245 | var property = this.properties[index];
|
13246 | if (property instanceof SpreadElement) {
|
13247 | this.unmatchablePropertiesRead.push(property);
|
13248 | continue;
|
13249 | }
|
13250 | var isWrite = property.kind !== 'get';
|
13251 | var isRead = property.kind !== 'set';
|
13252 | var key = void 0;
|
13253 | if (property.computed) {
|
13254 | var keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
13255 | if (keyValue === UNKNOWN_VALUE) {
|
13256 | if (isRead) {
|
13257 | this.unmatchablePropertiesRead.push(property);
|
13258 | }
|
13259 | else {
|
13260 | this.unmatchablePropertiesWrite.push(property);
|
13261 | }
|
13262 | continue;
|
13263 | }
|
13264 | key = String(keyValue);
|
13265 | }
|
13266 | else if (property.key instanceof Identifier$1) {
|
13267 | key = property.key.name;
|
13268 | }
|
13269 | else {
|
13270 | key = String(property.key.value);
|
13271 | }
|
13272 | var propertyMapProperty = this.propertyMap[key];
|
13273 | if (!propertyMapProperty) {
|
13274 | this.propertyMap[key] = {
|
13275 | exactMatchRead: isRead ? property : null,
|
13276 | exactMatchWrite: isWrite ? property : null,
|
13277 | propertiesRead: isRead ? [property].concat(this.unmatchablePropertiesRead) : [],
|
13278 | propertiesSet: isWrite && !isRead ? [property].concat(this.unmatchablePropertiesWrite) : []
|
13279 | };
|
13280 | continue;
|
13281 | }
|
13282 | if (isRead && propertyMapProperty.exactMatchRead === null) {
|
13283 | propertyMapProperty.exactMatchRead = property;
|
13284 | (_a = propertyMapProperty.propertiesRead).push.apply(_a, [property].concat(this.unmatchablePropertiesRead));
|
13285 | }
|
13286 | if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
|
13287 | propertyMapProperty.exactMatchWrite = property;
|
13288 | (_b = propertyMapProperty.propertiesSet).push.apply(_b, [property].concat(this.unmatchablePropertiesWrite));
|
13289 | }
|
13290 | }
|
13291 | };
|
13292 | ObjectExpression.prototype.deoptimizeAllProperties = function () {
|
13293 | this.hasUnknownDeoptimizedProperty = true;
|
13294 | for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
|
13295 | var property = _a[_i];
|
13296 | property.deoptimizePath(UNKNOWN_PATH);
|
13297 | }
|
13298 | for (var _b = 0, _c = Object.keys(this.expressionsToBeDeoptimized); _b < _c.length; _b++) {
|
13299 | var key = _c[_b];
|
13300 | for (var _d = 0, _e = this.expressionsToBeDeoptimized[key]; _d < _e.length; _d++) {
|
13301 | var expression = _e[_d];
|
13302 | expression.deoptimizeCache();
|
13303 | }
|
13304 | }
|
13305 | };
|
13306 | return ObjectExpression;
|
13307 | }(NodeBase));
|
13308 |
|
13309 | var ObjectPattern = /** @class */ (function (_super) {
|
13310 | __extends(ObjectPattern, _super);
|
13311 | function ObjectPattern() {
|
13312 | return _super !== null && _super.apply(this, arguments) || this;
|
13313 | }
|
13314 | ObjectPattern.prototype.addExportedVariables = function (variables) {
|
13315 | for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
|
13316 | var property = _a[_i];
|
13317 | if (property.type === Property) {
|
13318 | property.value.addExportedVariables(variables);
|
13319 | }
|
13320 | else {
|
13321 | property.argument.addExportedVariables(variables);
|
13322 | }
|
13323 | }
|
13324 | };
|
13325 | ObjectPattern.prototype.declare = function (kind, init) {
|
13326 | for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
|
13327 | var property = _a[_i];
|
13328 | property.declare(kind, init);
|
13329 | }
|
13330 | };
|
13331 | ObjectPattern.prototype.deoptimizePath = function (path) {
|
13332 | if (path.length === 0) {
|
13333 | for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
|
13334 | var property = _a[_i];
|
13335 | property.deoptimizePath(path);
|
13336 | }
|
13337 | }
|
13338 | };
|
13339 | ObjectPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13340 | if (path.length > 0)
|
13341 | return true;
|
13342 | for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
|
13343 | var property = _a[_i];
|
13344 | if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
|
13345 | return true;
|
13346 | }
|
13347 | return false;
|
13348 | };
|
13349 | return ObjectPattern;
|
13350 | }(NodeBase));
|
13351 |
|
13352 | var Program$1 = /** @class */ (function (_super) {
|
13353 | __extends(Program, _super);
|
13354 | function Program() {
|
13355 | return _super !== null && _super.apply(this, arguments) || this;
|
13356 | }
|
13357 | Program.prototype.hasEffects = function (options) {
|
13358 | for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
|
13359 | var node = _a[_i];
|
13360 | if (node.hasEffects(options))
|
13361 | return true;
|
13362 | }
|
13363 | };
|
13364 | Program.prototype.include = function (includeAllChildrenRecursively) {
|
13365 | this.included = true;
|
13366 | for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
|
13367 | var node = _a[_i];
|
13368 | if (includeAllChildrenRecursively || node.shouldBeIncluded()) {
|
13369 | node.include(includeAllChildrenRecursively);
|
13370 | }
|
13371 | }
|
13372 | };
|
13373 | Program.prototype.render = function (code, options) {
|
13374 | if (this.body.length) {
|
13375 | renderStatementList(this.body, code, this.start, this.end, options);
|
13376 | }
|
13377 | else {
|
13378 | _super.prototype.render.call(this, code, options);
|
13379 | }
|
13380 | };
|
13381 | return Program;
|
13382 | }(NodeBase));
|
13383 |
|
13384 | var Property$1 = /** @class */ (function (_super) {
|
13385 | __extends(Property, _super);
|
13386 | function Property() {
|
13387 | var _this = _super !== null && _super.apply(this, arguments) || this;
|
13388 | _this.declarationInit = null;
|
13389 | return _this;
|
13390 | }
|
13391 | Property.prototype.bind = function () {
|
13392 | _super.prototype.bind.call(this);
|
13393 | if (this.kind === 'get' && this.returnExpression === null)
|
13394 | this.updateReturnExpression();
|
13395 | if (this.declarationInit !== null) {
|
13396 | this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
|
13397 | }
|
13398 | };
|
13399 | Property.prototype.declare = function (kind, init) {
|
13400 | this.declarationInit = init;
|
13401 | this.value.declare(kind, UNKNOWN_EXPRESSION);
|
13402 | };
|
13403 | Property.prototype.deoptimizeCache = function () {
|
13404 | // As getter properties directly receive their values from function expressions that always
|
13405 | // have a fixed return value, there is no known situation where a getter is deoptimized.
|
13406 | throw new Error('Unexpected deoptimization');
|
13407 | };
|
13408 | Property.prototype.deoptimizePath = function (path) {
|
13409 | if (this.kind === 'get') {
|
13410 | if (path.length > 0) {
|
13411 | if (this.returnExpression === null)
|
13412 | this.updateReturnExpression();
|
13413 | this.returnExpression.deoptimizePath(path);
|
13414 | }
|
13415 | }
|
13416 | else if (this.kind !== 'set') {
|
13417 | this.value.deoptimizePath(path);
|
13418 | }
|
13419 | };
|
13420 | Property.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
13421 | if (this.kind === 'set') {
|
13422 | return UNKNOWN_VALUE;
|
13423 | }
|
13424 | if (this.kind === 'get') {
|
13425 | if (this.returnExpression === null)
|
13426 | this.updateReturnExpression();
|
13427 | return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
|
13428 | }
|
13429 | return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
|
13430 | };
|
13431 | Property.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
|
13432 | if (this.kind === 'set') {
|
13433 | return UNKNOWN_EXPRESSION;
|
13434 | }
|
13435 | if (this.kind === 'get') {
|
13436 | if (this.returnExpression === null)
|
13437 | this.updateReturnExpression();
|
13438 | return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
13439 | }
|
13440 | return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
|
13441 | };
|
13442 | Property.prototype.hasEffects = function (options) {
|
13443 | return this.key.hasEffects(options) || this.value.hasEffects(options);
|
13444 | };
|
13445 | Property.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
13446 | if (this.kind === 'get') {
|
13447 | return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()) ||
|
13448 | (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, options)));
|
13449 | }
|
13450 | return this.value.hasEffectsWhenAccessedAtPath(path, options);
|
13451 | };
|
13452 | Property.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13453 | if (this.kind === 'get') {
|
13454 | return path.length === 0 || this.returnExpression.hasEffectsWhenAssignedAtPath(path, options);
|
13455 | }
|
13456 | if (this.kind === 'set') {
|
13457 | return (path.length > 0 ||
|
13458 | this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()));
|
13459 | }
|
13460 | return this.value.hasEffectsWhenAssignedAtPath(path, options);
|
13461 | };
|
13462 | Property.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
13463 | if (this.kind === 'get') {
|
13464 | return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
13465 | }
|
13466 | return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options);
|
13467 | };
|
13468 | Property.prototype.initialise = function () {
|
13469 | this.included = false;
|
13470 | this.returnExpression = null;
|
13471 | this.accessorCallOptions = CallOptions.create({
|
13472 | callIdentifier: this,
|
13473 | withNew: false
|
13474 | });
|
13475 | };
|
13476 | Property.prototype.render = function (code, options) {
|
13477 | if (!this.shorthand) {
|
13478 | this.key.render(code, options);
|
13479 | }
|
13480 | this.value.render(code, options, { isShorthandProperty: this.shorthand });
|
13481 | };
|
13482 | Property.prototype.updateReturnExpression = function () {
|
13483 | this.returnExpression = UNKNOWN_EXPRESSION;
|
13484 | this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
|
13485 | };
|
13486 | return Property;
|
13487 | }(NodeBase));
|
13488 |
|
13489 | var RestElement = /** @class */ (function (_super) {
|
13490 | __extends(RestElement, _super);
|
13491 | function RestElement() {
|
13492 | var _this = _super !== null && _super.apply(this, arguments) || this;
|
13493 | _this.declarationInit = null;
|
13494 | return _this;
|
13495 | }
|
13496 | RestElement.prototype.addExportedVariables = function (variables) {
|
13497 | this.argument.addExportedVariables(variables);
|
13498 | };
|
13499 | RestElement.prototype.bind = function () {
|
13500 | _super.prototype.bind.call(this);
|
13501 | if (this.declarationInit !== null) {
|
13502 | this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
|
13503 | }
|
13504 | };
|
13505 | RestElement.prototype.declare = function (kind, init) {
|
13506 | this.argument.declare(kind, UNKNOWN_EXPRESSION);
|
13507 | this.declarationInit = init;
|
13508 | };
|
13509 | RestElement.prototype.deoptimizePath = function (path) {
|
13510 | path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
|
13511 | };
|
13512 | RestElement.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13513 | return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
|
13514 | };
|
13515 | return RestElement;
|
13516 | }(NodeBase));
|
13517 |
|
13518 | var ReturnStatement$1 = /** @class */ (function (_super) {
|
13519 | __extends(ReturnStatement, _super);
|
13520 | function ReturnStatement() {
|
13521 | return _super !== null && _super.apply(this, arguments) || this;
|
13522 | }
|
13523 | ReturnStatement.prototype.hasEffects = function (options) {
|
13524 | return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
|
13525 | };
|
13526 | ReturnStatement.prototype.initialise = function () {
|
13527 | this.included = false;
|
13528 | this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
|
13529 | };
|
13530 | ReturnStatement.prototype.render = function (code, options) {
|
13531 | if (this.argument) {
|
13532 | this.argument.render(code, options);
|
13533 | if (this.argument.start === this.start + 6 /* 'return'.length */) {
|
13534 | code.prependLeft(this.start + 6, ' ');
|
13535 | }
|
13536 | }
|
13537 | };
|
13538 | return ReturnStatement;
|
13539 | }(NodeBase));
|
13540 |
|
13541 | var SequenceExpression = /** @class */ (function (_super) {
|
13542 | __extends(SequenceExpression, _super);
|
13543 | function SequenceExpression() {
|
13544 | return _super !== null && _super.apply(this, arguments) || this;
|
13545 | }
|
13546 | SequenceExpression.prototype.deoptimizePath = function (path) {
|
13547 | if (path.length > 0)
|
13548 | this.expressions[this.expressions.length - 1].deoptimizePath(path);
|
13549 | };
|
13550 | SequenceExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
13551 | return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
|
13552 | };
|
13553 | SequenceExpression.prototype.hasEffects = function (options) {
|
13554 | for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
|
13555 | var expression = _a[_i];
|
13556 | if (expression.hasEffects(options))
|
13557 | return true;
|
13558 | }
|
13559 | return false;
|
13560 | };
|
13561 | SequenceExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
13562 | return (path.length > 0 &&
|
13563 | this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, options));
|
13564 | };
|
13565 | SequenceExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13566 | return (path.length === 0 ||
|
13567 | this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, options));
|
13568 | };
|
13569 | SequenceExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
|
13570 | return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, options);
|
13571 | };
|
13572 | SequenceExpression.prototype.include = function (includeAllChildrenRecursively) {
|
13573 | this.included = true;
|
13574 | for (var i = 0; i < this.expressions.length - 1; i++) {
|
13575 | var node = this.expressions[i];
|
13576 | if (includeAllChildrenRecursively || node.shouldBeIncluded())
|
13577 | node.include(includeAllChildrenRecursively);
|
13578 | }
|
13579 | this.expressions[this.expressions.length - 1].include(includeAllChildrenRecursively);
|
13580 | };
|
13581 | SequenceExpression.prototype.render = function (code, options, _a) {
|
13582 | var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
|
13583 | var firstStart = 0, lastEnd, includedNodes = 0;
|
13584 | for (var _i = 0, _c = getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end); _i < _c.length; _i++) {
|
13585 | var _d = _c[_i], node = _d.node, start = _d.start, end = _d.end;
|
13586 | if (!node.included) {
|
13587 | treeshakeNode(node, code, start, end);
|
13588 | continue;
|
13589 | }
|
13590 | includedNodes++;
|
13591 | if (firstStart === 0)
|
13592 | firstStart = start;
|
13593 | lastEnd = end;
|
13594 | if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
|
13595 | node.render(code, options, {
|
13596 | isCalleeOfRenderedParent: renderedParentType
|
13597 | ? isCalleeOfRenderedParent
|
13598 | : this.parent.callee === this,
|
13599 | renderedParentType: renderedParentType || this.parent.type
|
13600 | });
|
13601 | }
|
13602 | else {
|
13603 | node.render(code, options);
|
13604 | }
|
13605 | }
|
13606 | // Round brackets are part of the actual parent and should be re-added in case the parent changed
|
13607 | if (includedNodes > 1 && renderedParentType) {
|
13608 | code.prependRight(firstStart, '(');
|
13609 | code.appendLeft(lastEnd, ')');
|
13610 | }
|
13611 | };
|
13612 | return SequenceExpression;
|
13613 | }(NodeBase));
|
13614 |
|
13615 | var SwitchCase = /** @class */ (function (_super) {
|
13616 | __extends(SwitchCase, _super);
|
13617 | function SwitchCase() {
|
13618 | return _super !== null && _super.apply(this, arguments) || this;
|
13619 | }
|
13620 | SwitchCase.prototype.include = function (includeAllChildrenRecursively) {
|
13621 | this.included = true;
|
13622 | if (this.test)
|
13623 | this.test.include(includeAllChildrenRecursively);
|
13624 | for (var _i = 0, _a = this.consequent; _i < _a.length; _i++) {
|
13625 | var node = _a[_i];
|
13626 | if (includeAllChildrenRecursively || node.shouldBeIncluded())
|
13627 | node.include(includeAllChildrenRecursively);
|
13628 | }
|
13629 | };
|
13630 | SwitchCase.prototype.render = function (code, options) {
|
13631 | if (this.consequent.length) {
|
13632 | this.test && this.test.render(code, options);
|
13633 | var testEnd = this.test
|
13634 | ? this.test.end
|
13635 | : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
|
13636 | var consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
|
13637 | renderStatementList(this.consequent, code, consequentStart, this.end, options);
|
13638 | }
|
13639 | else {
|
13640 | _super.prototype.render.call(this, code, options);
|
13641 | }
|
13642 | };
|
13643 | return SwitchCase;
|
13644 | }(NodeBase));
|
13645 |
|
13646 | var SwitchStatement = /** @class */ (function (_super) {
|
13647 | __extends(SwitchStatement, _super);
|
13648 | function SwitchStatement() {
|
13649 | return _super !== null && _super.apply(this, arguments) || this;
|
13650 | }
|
13651 | SwitchStatement.prototype.createScope = function (parentScope) {
|
13652 | this.scope = new BlockScope(parentScope);
|
13653 | };
|
13654 | SwitchStatement.prototype.hasEffects = function (options) {
|
13655 | return _super.prototype.hasEffects.call(this, options.setIgnoreBreakStatements());
|
13656 | };
|
13657 | return SwitchStatement;
|
13658 | }(NodeBase));
|
13659 |
|
13660 | var TaggedTemplateExpression = /** @class */ (function (_super) {
|
13661 | __extends(TaggedTemplateExpression, _super);
|
13662 | function TaggedTemplateExpression() {
|
13663 | return _super !== null && _super.apply(this, arguments) || this;
|
13664 | }
|
13665 | TaggedTemplateExpression.prototype.bind = function () {
|
13666 | _super.prototype.bind.call(this);
|
13667 | if (this.tag.type === Identifier) {
|
13668 | var variable = this.scope.findVariable(this.tag.name);
|
13669 | if (variable.isNamespace) {
|
13670 | this.context.error({
|
13671 | code: 'CANNOT_CALL_NAMESPACE',
|
13672 | message: "Cannot call a namespace ('" + this.tag.name + "')"
|
13673 | }, this.start);
|
13674 | }
|
13675 | if (this.tag.name === 'eval') {
|
13676 | this.context.warn({
|
13677 | code: 'EVAL',
|
13678 | message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
|
13679 | url: 'https://rollupjs.org/guide/en#avoiding-eval'
|
13680 | }, this.start);
|
13681 | }
|
13682 | }
|
13683 | };
|
13684 | TaggedTemplateExpression.prototype.hasEffects = function (options) {
|
13685 | return (_super.prototype.hasEffects.call(this, options) ||
|
13686 | this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
|
13687 | };
|
13688 | TaggedTemplateExpression.prototype.initialise = function () {
|
13689 | this.included = false;
|
13690 | this.callOptions = CallOptions.create({
|
13691 | callIdentifier: this,
|
13692 | withNew: false
|
13693 | });
|
13694 | };
|
13695 | return TaggedTemplateExpression;
|
13696 | }(NodeBase));
|
13697 |
|
13698 | var TemplateElement = /** @class */ (function (_super) {
|
13699 | __extends(TemplateElement, _super);
|
13700 | function TemplateElement() {
|
13701 | return _super !== null && _super.apply(this, arguments) || this;
|
13702 | }
|
13703 | TemplateElement.prototype.hasEffects = function (_options) {
|
13704 | return false;
|
13705 | };
|
13706 | return TemplateElement;
|
13707 | }(NodeBase));
|
13708 |
|
13709 | function isTemplateLiteral(node) {
|
13710 | return node.type === TemplateLiteral;
|
13711 | }
|
13712 | var TemplateLiteral$1 = /** @class */ (function (_super) {
|
13713 | __extends(TemplateLiteral, _super);
|
13714 | function TemplateLiteral() {
|
13715 | return _super !== null && _super.apply(this, arguments) || this;
|
13716 | }
|
13717 | TemplateLiteral.prototype.getLiteralValueAtPath = function (path) {
|
13718 | if (path.length > 0 || this.quasis.length !== 1) {
|
13719 | return UNKNOWN_VALUE;
|
13720 | }
|
13721 | return this.quasis[0].value.cooked;
|
13722 | };
|
13723 | TemplateLiteral.prototype.render = function (code, options) {
|
13724 | code.indentExclusionRanges.push([this.start, this.end]);
|
13725 | _super.prototype.render.call(this, code, options);
|
13726 | };
|
13727 | return TemplateLiteral;
|
13728 | }(NodeBase));
|
13729 |
|
13730 | var ModuleScope = /** @class */ (function (_super) {
|
13731 | __extends(ModuleScope, _super);
|
13732 | function ModuleScope(parent, context) {
|
13733 | var _this = _super.call(this, parent) || this;
|
13734 | _this.context = context;
|
13735 | _this.variables.this = new LocalVariable('this', null, UNDEFINED_EXPRESSION, context);
|
13736 | return _this;
|
13737 | }
|
13738 | ModuleScope.prototype.addExportDefaultDeclaration = function (name, exportDefaultDeclaration, context) {
|
13739 | return (this.variables.default = new ExportDefaultVariable(name, exportDefaultDeclaration, context));
|
13740 | };
|
13741 | ModuleScope.prototype.addNamespaceMemberAccess = function (_name, variable) {
|
13742 | if (variable instanceof GlobalVariable) {
|
13743 | this.accessedOutsideVariables[variable.name] = variable;
|
13744 | }
|
13745 | };
|
13746 | ModuleScope.prototype.deconflict = function (forbiddenNames) {
|
13747 | // all module level variables are already deconflicted when deconflicting the chunk
|
13748 | for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
|
13749 | var scope = _a[_i];
|
13750 | scope.deconflict(forbiddenNames);
|
13751 | }
|
13752 | };
|
13753 | ModuleScope.prototype.findLexicalBoundary = function () {
|
13754 | return this;
|
13755 | };
|
13756 | ModuleScope.prototype.findVariable = function (name) {
|
13757 | var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
|
13758 | if (knownVariable) {
|
13759 | return knownVariable;
|
13760 | }
|
13761 | var variable = this.context.traceVariable(name) || this.parent.findVariable(name);
|
13762 | if (variable instanceof GlobalVariable) {
|
13763 | this.accessedOutsideVariables[name] = variable;
|
13764 | }
|
13765 | return variable;
|
13766 | };
|
13767 | return ModuleScope;
|
13768 | }(ChildScope));
|
13769 |
|
13770 | var ThisExpression = /** @class */ (function (_super) {
|
13771 | __extends(ThisExpression, _super);
|
13772 | function ThisExpression() {
|
13773 | return _super !== null && _super.apply(this, arguments) || this;
|
13774 | }
|
13775 | ThisExpression.prototype.bind = function () {
|
13776 | _super.prototype.bind.call(this);
|
13777 | this.variable = this.scope.findVariable('this');
|
13778 | };
|
13779 | ThisExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
|
13780 | return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, options);
|
13781 | };
|
13782 | ThisExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
|
13783 | return this.variable.hasEffectsWhenAssignedAtPath(path, options);
|
13784 | };
|
13785 | ThisExpression.prototype.initialise = function () {
|
13786 | this.included = false;
|
13787 | this.variable = null;
|
13788 | this.alias =
|
13789 | this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
|
13790 | if (this.alias === 'undefined') {
|
13791 | this.context.warn({
|
13792 | code: 'THIS_IS_UNDEFINED',
|
13793 | message: "The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten",
|
13794 | url: "https://rollupjs.org/guide/en#error-this-is-undefined"
|
13795 | }, this.start);
|
13796 | }
|
13797 | };
|
13798 | ThisExpression.prototype.render = function (code, _options) {
|
13799 | if (this.alias !== null) {
|
13800 | code.overwrite(this.start, this.end, this.alias, {
|
13801 | contentOnly: false,
|
13802 | storeName: true
|
13803 | });
|
13804 | }
|
13805 | };
|
13806 | return ThisExpression;
|
13807 | }(NodeBase));
|
13808 |
|
13809 | var ThrowStatement = /** @class */ (function (_super) {
|
13810 | __extends(ThrowStatement, _super);
|
13811 | function ThrowStatement() {
|
13812 | return _super !== null && _super.apply(this, arguments) || this;
|
13813 | }
|
13814 | ThrowStatement.prototype.hasEffects = function (_options) {
|
13815 | return true;
|
13816 | };
|
13817 | return ThrowStatement;
|
13818 | }(NodeBase));
|
13819 |
|
13820 | var unaryOperators = {
|
13821 | '!': function (value) { return !value; },
|
13822 | '+': function (value) { return +value; },
|
13823 | '-': function (value) { return -value; },
|
13824 | delete: function () { return UNKNOWN_VALUE; },
|
13825 | typeof: function (value) { return typeof value; },
|
13826 | void: function () { return undefined; },
|
13827 | '~': function (value) { return ~value; }
|
13828 | };
|
13829 | var UnaryExpression = /** @class */ (function (_super) {
|
13830 | __extends(UnaryExpression, _super);
|
13831 | function UnaryExpression() {
|
13832 | return _super !== null && _super.apply(this, arguments) || this;
|
13833 | }
|
13834 | UnaryExpression.prototype.bind = function () {
|
13835 | _super.prototype.bind.call(this);
|
13836 | if (this.operator === 'delete') {
|
13837 | this.argument.deoptimizePath(EMPTY_PATH);
|
13838 | }
|
13839 | };
|
13840 | UnaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
|
13841 | if (path.length > 0)
|
13842 | return UNKNOWN_VALUE;
|
13843 | var argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
|
13844 | if (argumentValue === UNKNOWN_VALUE)
|
13845 | return UNKNOWN_VALUE;
|
13846 | return unaryOperators[this.operator](argumentValue);
|
13847 | };
|
13848 | UnaryExpression.prototype.hasEffects = function (options) {
|
13849 | return (this.argument.hasEffects(options) ||
|
13850 | (this.operator === 'delete' &&
|
13851 | this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)));
|
13852 | };
|
13853 | UnaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
13854 | if (this.operator === 'void') {
|
13855 | return path.length > 0;
|
13856 | }
|
13857 | return path.length > 1;
|
13858 | };
|
13859 | return UnaryExpression;
|
13860 | }(NodeBase));
|
13861 |
|
13862 | var UnknownNode = /** @class */ (function (_super) {
|
13863 | __extends(UnknownNode, _super);
|
13864 | function UnknownNode() {
|
13865 | return _super !== null && _super.apply(this, arguments) || this;
|
13866 | }
|
13867 | UnknownNode.prototype.hasEffects = function (_options) {
|
13868 | return true;
|
13869 | };
|
13870 | UnknownNode.prototype.include = function () {
|
13871 | _super.prototype.include.call(this, true);
|
13872 | };
|
13873 | return UnknownNode;
|
13874 | }(NodeBase));
|
13875 |
|
13876 | var UpdateExpression = /** @class */ (function (_super) {
|
13877 | __extends(UpdateExpression, _super);
|
13878 | function UpdateExpression() {
|
13879 | return _super !== null && _super.apply(this, arguments) || this;
|
13880 | }
|
13881 | UpdateExpression.prototype.bind = function () {
|
13882 | _super.prototype.bind.call(this);
|
13883 | this.argument.deoptimizePath(EMPTY_PATH);
|
13884 | if (isIdentifier(this.argument)) {
|
13885 | var variable = this.scope.findVariable(this.argument.name);
|
13886 | variable.isReassigned = true;
|
13887 | }
|
13888 | };
|
13889 | UpdateExpression.prototype.hasEffects = function (options) {
|
13890 | return (this.argument.hasEffects(options) ||
|
13891 | this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
|
13892 | };
|
13893 | UpdateExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
|
13894 | return path.length > 1;
|
13895 | };
|
13896 | UpdateExpression.prototype.render = function (code, options) {
|
13897 | this.argument.render(code, options);
|
13898 | var variable = this.argument.variable;
|
13899 | if (options.format === 'system' && variable && variable.exportName) {
|
13900 | var name = variable.getName();
|
13901 | if (this.prefix) {
|
13902 | code.overwrite(this.start, this.end, "exports('" + variable.exportName + "', " + this.operator + name + ")");
|
13903 | }
|
13904 | else {
|
13905 | var op = void 0;
|
13906 | switch (this.operator) {
|
13907 | case '++':
|
13908 | op = name + " + 1";
|
13909 | break;
|
13910 | case '--':
|
13911 | op = name + " - 1";
|
13912 | break;
|
13913 | }
|
13914 | code.overwrite(this.start, this.end, "(exports('" + variable.exportName + "', " + op + "), " + name + this.operator + ")");
|
13915 | }
|
13916 | }
|
13917 | };
|
13918 | return UpdateExpression;
|
13919 | }(NodeBase));
|
13920 |
|
13921 | function isReassignedExportsMember(variable) {
|
13922 | return variable.renderBaseName && variable.exportName && variable.isReassigned;
|
13923 | }
|
13924 | function areAllDeclarationsIncludedAndNotExported(declarations) {
|
13925 | for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
|
13926 | var declarator = declarations_1[_i];
|
13927 | if (!declarator.included) {
|
13928 | return false;
|
13929 | }
|
13930 | if (declarator.id.type === Identifier) {
|
13931 | if (declarator.id.variable.exportName)
|
13932 | return false;
|
13933 | }
|
13934 | else {
|
13935 | var exportedVariables = [];
|
13936 | declarator.id.addExportedVariables(exportedVariables);
|
13937 | if (exportedVariables.length > 0)
|
13938 | return false;
|
13939 | }
|
13940 | }
|
13941 | return true;
|
13942 | }
|
13943 | var VariableDeclaration$1 = /** @class */ (function (_super) {
|
13944 | __extends(VariableDeclaration, _super);
|
13945 | function VariableDeclaration() {
|
13946 | return _super !== null && _super.apply(this, arguments) || this;
|
13947 | }
|
13948 | VariableDeclaration.prototype.deoptimizePath = function (_path) {
|
13949 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
13950 | var declarator = _a[_i];
|
13951 | declarator.deoptimizePath(EMPTY_PATH);
|
13952 | }
|
13953 | };
|
13954 | VariableDeclaration.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
|
13955 | return false;
|
13956 | };
|
13957 | VariableDeclaration.prototype.include = function (includeAllChildrenRecursively) {
|
13958 | this.included = true;
|
13959 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
13960 | var declarator = _a[_i];
|
13961 | if (includeAllChildrenRecursively || declarator.shouldBeIncluded())
|
13962 | declarator.include(includeAllChildrenRecursively);
|
13963 | }
|
13964 | };
|
13965 | VariableDeclaration.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
|
13966 | this.included = true;
|
13967 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
13968 | var declarator = _a[_i];
|
13969 | declarator.include(includeAllChildrenRecursively);
|
13970 | }
|
13971 | };
|
13972 | VariableDeclaration.prototype.initialise = function () {
|
13973 | this.included = false;
|
13974 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
13975 | var declarator = _a[_i];
|
13976 | declarator.declareDeclarator(this.kind);
|
13977 | }
|
13978 | };
|
13979 | VariableDeclaration.prototype.render = function (code, options, nodeRenderOptions) {
|
13980 | if (nodeRenderOptions === void 0) { nodeRenderOptions = BLANK; }
|
13981 | if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
|
13982 | for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
|
13983 | var declarator = _a[_i];
|
13984 | declarator.render(code, options);
|
13985 | }
|
13986 | if (!nodeRenderOptions.isNoStatement &&
|
13987 | code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
|
13988 | code.appendLeft(this.end, ';');
|
13989 | }
|
13990 | }
|
13991 | else {
|
13992 | this.renderReplacedDeclarations(code, options, nodeRenderOptions);
|
13993 | }
|
13994 | };
|
13995 | VariableDeclaration.prototype.renderDeclarationEnd = function (code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
|
13996 | if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
|
13997 | code.remove(this.end - 1, this.end);
|
13998 | }
|
13999 | if (addSemicolon) {
|
14000 | separatorString += ';';
|
14001 | }
|
14002 | if (lastSeparatorPos !== null) {
|
14003 | if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
|
14004 | (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
|
14005 | code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
|
14006 | actualContentEnd--;
|
14007 | if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
|
14008 | actualContentEnd--;
|
14009 | }
|
14010 | }
|
14011 | if (actualContentEnd === lastSeparatorPos + 1) {
|
14012 | code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
|
14013 | }
|
14014 | else {
|
14015 | code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
|
14016 | code.remove(actualContentEnd, renderedContentEnd);
|
14017 | }
|
14018 | }
|
14019 | else {
|
14020 | code.appendLeft(renderedContentEnd, separatorString);
|
14021 | }
|
14022 | if (systemPatternExports.length > 0) {
|
14023 | code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
|
14024 | }
|
14025 | };
|
14026 | VariableDeclaration.prototype.renderReplacedDeclarations = function (code, options, _a) {
|
14027 | var _b = _a.start, start = _b === void 0 ? this.start : _b, _c = _a.end, end = _c === void 0 ? this.end : _c, isNoStatement = _a.isNoStatement;
|
14028 | var separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
|
14029 | var actualContentEnd, renderedContentEnd;
|
14030 | if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
|
14031 | renderedContentEnd = this.start + this.kind.length;
|
14032 | }
|
14033 | else {
|
14034 | renderedContentEnd = separatedNodes[0].start;
|
14035 | }
|
14036 | var lastSeparatorPos = renderedContentEnd - 1;
|
14037 | code.remove(this.start, lastSeparatorPos);
|
14038 | var isInDeclaration = false;
|
14039 | var hasRenderedContent = false;
|
14040 | var separatorString = '', leadingString, nextSeparatorString;
|
14041 | var systemPatternExports = [];
|
14042 | for (var _i = 0, separatedNodes_1 = separatedNodes; _i < separatedNodes_1.length; _i++) {
|
14043 | var _d = separatedNodes_1[_i], node = _d.node, start_1 = _d.start, separator = _d.separator, contentEnd = _d.contentEnd, end_1 = _d.end;
|
14044 | if (!node.included ||
|
14045 | (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable) && node.init === null)) {
|
14046 | code.remove(start_1, end_1);
|
14047 | continue;
|
14048 | }
|
14049 | leadingString = '';
|
14050 | nextSeparatorString = '';
|
14051 | if (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable)) {
|
14052 | if (hasRenderedContent) {
|
14053 | separatorString += ';';
|
14054 | }
|
14055 | isInDeclaration = false;
|
14056 | }
|
14057 | else {
|
14058 | if (options.format === 'system' && node.init !== null) {
|
14059 | if (node.id.type !== Identifier) {
|
14060 | node.id.addExportedVariables(systemPatternExports);
|
14061 | }
|
14062 | else if (node.id.variable.exportName) {
|
14063 | code.prependLeft(code.original.indexOf('=', node.id.end) + 1, " exports('" + (node.id.variable.safeExportName || node.id.variable.exportName) + "',");
|
14064 | nextSeparatorString += ')';
|
14065 | }
|
14066 | }
|
14067 | if (isInDeclaration) {
|
14068 | separatorString += ',';
|
14069 | }
|
14070 | else {
|
14071 | if (hasRenderedContent) {
|
14072 | separatorString += ';';
|
14073 | }
|
14074 | leadingString += this.kind + " ";
|
14075 | isInDeclaration = true;
|
14076 | }
|
14077 | }
|
14078 | if (renderedContentEnd === lastSeparatorPos + 1) {
|
14079 | code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
|
14080 | }
|
14081 | else {
|
14082 | code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
|
14083 | code.appendLeft(renderedContentEnd, leadingString);
|
14084 | }
|
14085 | node.render(code, options);
|
14086 | actualContentEnd = contentEnd;
|
14087 | renderedContentEnd = end_1;
|
14088 | hasRenderedContent = true;
|
14089 | lastSeparatorPos = separator;
|
14090 | separatorString = nextSeparatorString;
|
14091 | }
|
14092 | if (hasRenderedContent) {
|
14093 | this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
|
14094 | }
|
14095 | else {
|
14096 | code.remove(start, end);
|
14097 | }
|
14098 | };
|
14099 | return VariableDeclaration;
|
14100 | }(NodeBase));
|
14101 |
|
14102 | var VariableDeclarator = /** @class */ (function (_super) {
|
14103 | __extends(VariableDeclarator, _super);
|
14104 | function VariableDeclarator() {
|
14105 | return _super !== null && _super.apply(this, arguments) || this;
|
14106 | }
|
14107 | VariableDeclarator.prototype.declareDeclarator = function (kind) {
|
14108 | this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
|
14109 | };
|
14110 | VariableDeclarator.prototype.deoptimizePath = function (path) {
|
14111 | this.id.deoptimizePath(path);
|
14112 | };
|
14113 | VariableDeclarator.prototype.render = function (code, options) {
|
14114 | // This can happen for hoisted variables in dead branches
|
14115 | if (this.init !== null && !this.init.included) {
|
14116 | code.remove(this.id.end, this.end);
|
14117 | this.id.render(code, options);
|
14118 | }
|
14119 | else {
|
14120 | _super.prototype.render.call(this, code, options);
|
14121 | }
|
14122 | };
|
14123 | return VariableDeclarator;
|
14124 | }(NodeBase));
|
14125 |
|
14126 | var WhileStatement = /** @class */ (function (_super) {
|
14127 | __extends(WhileStatement, _super);
|
14128 | function WhileStatement() {
|
14129 | return _super !== null && _super.apply(this, arguments) || this;
|
14130 | }
|
14131 | WhileStatement.prototype.hasEffects = function (options) {
|
14132 | return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
|
14133 | };
|
14134 | return WhileStatement;
|
14135 | }(NodeBase));
|
14136 |
|
14137 | var YieldExpression = /** @class */ (function (_super) {
|
14138 | __extends(YieldExpression, _super);
|
14139 | function YieldExpression() {
|
14140 | return _super !== null && _super.apply(this, arguments) || this;
|
14141 | }
|
14142 | YieldExpression.prototype.bind = function () {
|
14143 | _super.prototype.bind.call(this);
|
14144 | if (this.argument !== null) {
|
14145 | this.argument.deoptimizePath(UNKNOWN_PATH);
|
14146 | }
|
14147 | };
|
14148 | YieldExpression.prototype.hasEffects = function (options) {
|
14149 | return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
|
14150 | };
|
14151 | YieldExpression.prototype.render = function (code, options) {
|
14152 | if (this.argument) {
|
14153 | this.argument.render(code, options);
|
14154 | if (this.argument.start === this.start + 5 /* 'yield'.length */) {
|
14155 | code.prependLeft(this.start + 5, ' ');
|
14156 | }
|
14157 | }
|
14158 | };
|
14159 | return YieldExpression;
|
14160 | }(NodeBase));
|
14161 |
|
14162 | var nodeConstructors = {
|
14163 | ArrayExpression: ArrayExpression,
|
14164 | ArrayPattern: ArrayPattern,
|
14165 | ArrowFunctionExpression: ArrowFunctionExpression,
|
14166 | AssignmentExpression: AssignmentExpression,
|
14167 | AssignmentPattern: AssignmentPattern,
|
14168 | AwaitExpression: AwaitExpression,
|
14169 | BinaryExpression: BinaryExpression,
|
14170 | BlockStatement: BlockStatement$1,
|
14171 | BreakStatement: BreakStatement,
|
14172 | CallExpression: CallExpression$1,
|
14173 | CatchClause: CatchClause,
|
14174 | ClassBody: ClassBody,
|
14175 | ClassDeclaration: ClassDeclaration$1,
|
14176 | ClassExpression: ClassExpression,
|
14177 | ConditionalExpression: ConditionalExpression,
|
14178 | DoWhileStatement: DoWhileStatement,
|
14179 | EmptyStatement: EmptyStatement,
|
14180 | ExportAllDeclaration: ExportAllDeclaration$1,
|
14181 | ExportDefaultDeclaration: ExportDefaultDeclaration$1,
|
14182 | ExportNamedDeclaration: ExportNamedDeclaration,
|
14183 | ExpressionStatement: ExpressionStatement$1,
|
14184 | ForInStatement: ForInStatement,
|
14185 | ForOfStatement: ForOfStatement,
|
14186 | ForStatement: ForStatement,
|
14187 | FunctionDeclaration: FunctionDeclaration$1,
|
14188 | FunctionExpression: FunctionExpression$1,
|
14189 | Identifier: Identifier$1,
|
14190 | IfStatement: IfStatement,
|
14191 | Import: Import,
|
14192 | ImportDeclaration: ImportDeclaration,
|
14193 | LabeledStatement: LabeledStatement,
|
14194 | Literal: Literal$1,
|
14195 | LogicalExpression: LogicalExpression,
|
14196 | MemberExpression: MemberExpression$1,
|
14197 | MetaProperty: MetaProperty,
|
14198 | MethodDefinition: MethodDefinition,
|
14199 | NewExpression: NewExpression,
|
14200 | ObjectExpression: ObjectExpression,
|
14201 | ObjectPattern: ObjectPattern,
|
14202 | Program: Program$1,
|
14203 | Property: Property$1,
|
14204 | RestElement: RestElement,
|
14205 | ReturnStatement: ReturnStatement$1,
|
14206 | SequenceExpression: SequenceExpression,
|
14207 | SpreadElement: SpreadElement,
|
14208 | SwitchCase: SwitchCase,
|
14209 | SwitchStatement: SwitchStatement,
|
14210 | TaggedTemplateExpression: TaggedTemplateExpression,
|
14211 | TemplateElement: TemplateElement,
|
14212 | TemplateLiteral: TemplateLiteral$1,
|
14213 | ThisExpression: ThisExpression,
|
14214 | ThrowStatement: ThrowStatement,
|
14215 | TryStatement: NodeBase,
|
14216 | UnaryExpression: UnaryExpression,
|
14217 | UnknownNode: UnknownNode,
|
14218 | UpdateExpression: UpdateExpression,
|
14219 | VariableDeclaration: VariableDeclaration$1,
|
14220 | VariableDeclarator: VariableDeclarator,
|
14221 | WhileStatement: WhileStatement,
|
14222 | YieldExpression: YieldExpression
|
14223 | };
|
14224 |
|
14225 | function getOriginalLocation(sourcemapChain, location) {
|
14226 | var filteredSourcemapChain = sourcemapChain.filter(function (sourcemap) { return sourcemap.mappings; });
|
14227 | while (filteredSourcemapChain.length > 0) {
|
14228 | var sourcemap = filteredSourcemapChain.pop();
|
14229 | var line = sourcemap.mappings[location.line - 1];
|
14230 | var locationFound = false;
|
14231 | if (line !== undefined) {
|
14232 | for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
|
14233 | var segment = line_1[_i];
|
14234 | if (segment[0] >= location.column) {
|
14235 | if (segment.length < 4)
|
14236 | break;
|
14237 | location = {
|
14238 | column: segment[3],
|
14239 | line: segment[2] + 1,
|
14240 | name: sourcemap.names[segment[4]],
|
14241 | source: sourcemap.sources[segment[1]]
|
14242 | };
|
14243 | locationFound = true;
|
14244 | break;
|
14245 | }
|
14246 | }
|
14247 | }
|
14248 | if (!locationFound) {
|
14249 | throw new Error("Can't resolve original location of error.");
|
14250 | }
|
14251 | }
|
14252 | return location;
|
14253 | }
|
14254 |
|
14255 | // AST walker module for Mozilla Parser API compatible trees
|
14256 |
|
14257 | function skipThrough(node, st, c) { c(node, st); }
|
14258 | function ignore(_node, _st, _c) {}
|
14259 |
|
14260 | // Node walkers.
|
14261 |
|
14262 | var base$1 = {};
|
14263 |
|
14264 | base$1.Program = base$1.BlockStatement = function (node, st, c) {
|
14265 | for (var i = 0, list = node.body; i < list.length; i += 1)
|
14266 | {
|
14267 | var stmt = list[i];
|
14268 |
|
14269 | c(stmt, st, "Statement");
|
14270 | }
|
14271 | };
|
14272 | base$1.Statement = skipThrough;
|
14273 | base$1.EmptyStatement = ignore;
|
14274 | base$1.ExpressionStatement = base$1.ParenthesizedExpression =
|
14275 | function (node, st, c) { return c(node.expression, st, "Expression"); };
|
14276 | base$1.IfStatement = function (node, st, c) {
|
14277 | c(node.test, st, "Expression");
|
14278 | c(node.consequent, st, "Statement");
|
14279 | if (node.alternate) { c(node.alternate, st, "Statement"); }
|
14280 | };
|
14281 | base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
14282 | base$1.BreakStatement = base$1.ContinueStatement = ignore;
|
14283 | base$1.WithStatement = function (node, st, c) {
|
14284 | c(node.object, st, "Expression");
|
14285 | c(node.body, st, "Statement");
|
14286 | };
|
14287 | base$1.SwitchStatement = function (node, st, c) {
|
14288 | c(node.discriminant, st, "Expression");
|
14289 | for (var i = 0, list = node.cases; i < list.length; i += 1) {
|
14290 | var cs = list[i];
|
14291 |
|
14292 | if (cs.test) { c(cs.test, st, "Expression"); }
|
14293 | for (var i$1 = 0, list$1 = cs.consequent; i$1 < list$1.length; i$1 += 1)
|
14294 | {
|
14295 | var cons = list$1[i$1];
|
14296 |
|
14297 | c(cons, st, "Statement");
|
14298 | }
|
14299 | }
|
14300 | };
|
14301 | base$1.SwitchCase = function (node, st, c) {
|
14302 | if (node.test) { c(node.test, st, "Expression"); }
|
14303 | for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
14304 | {
|
14305 | var cons = list[i];
|
14306 |
|
14307 | c(cons, st, "Statement");
|
14308 | }
|
14309 | };
|
14310 | base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
|
14311 | if (node.argument) { c(node.argument, st, "Expression"); }
|
14312 | };
|
14313 | base$1.ThrowStatement = base$1.SpreadElement =
|
14314 | function (node, st, c) { return c(node.argument, st, "Expression"); };
|
14315 | base$1.TryStatement = function (node, st, c) {
|
14316 | c(node.block, st, "Statement");
|
14317 | if (node.handler) { c(node.handler, st); }
|
14318 | if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
14319 | };
|
14320 | base$1.CatchClause = function (node, st, c) {
|
14321 | if (node.param) { c(node.param, st, "Pattern"); }
|
14322 | c(node.body, st, "Statement");
|
14323 | };
|
14324 | base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
|
14325 | c(node.test, st, "Expression");
|
14326 | c(node.body, st, "Statement");
|
14327 | };
|
14328 | base$1.ForStatement = function (node, st, c) {
|
14329 | if (node.init) { c(node.init, st, "ForInit"); }
|
14330 | if (node.test) { c(node.test, st, "Expression"); }
|
14331 | if (node.update) { c(node.update, st, "Expression"); }
|
14332 | c(node.body, st, "Statement");
|
14333 | };
|
14334 | base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
|
14335 | c(node.left, st, "ForInit");
|
14336 | c(node.right, st, "Expression");
|
14337 | c(node.body, st, "Statement");
|
14338 | };
|
14339 | base$1.ForInit = function (node, st, c) {
|
14340 | if (node.type === "VariableDeclaration") { c(node, st); }
|
14341 | else { c(node, st, "Expression"); }
|
14342 | };
|
14343 | base$1.DebuggerStatement = ignore;
|
14344 |
|
14345 | base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
14346 | base$1.VariableDeclaration = function (node, st, c) {
|
14347 | for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
14348 | {
|
14349 | var decl = list[i];
|
14350 |
|
14351 | c(decl, st);
|
14352 | }
|
14353 | };
|
14354 | base$1.VariableDeclarator = function (node, st, c) {
|
14355 | c(node.id, st, "Pattern");
|
14356 | if (node.init) { c(node.init, st, "Expression"); }
|
14357 | };
|
14358 |
|
14359 | base$1.Function = function (node, st, c) {
|
14360 | if (node.id) { c(node.id, st, "Pattern"); }
|
14361 | for (var i = 0, list = node.params; i < list.length; i += 1)
|
14362 | {
|
14363 | var param = list[i];
|
14364 |
|
14365 | c(param, st, "Pattern");
|
14366 | }
|
14367 | c(node.body, st, node.expression ? "Expression" : "Statement");
|
14368 | };
|
14369 |
|
14370 | base$1.Pattern = function (node, st, c) {
|
14371 | if (node.type === "Identifier")
|
14372 | { c(node, st, "VariablePattern"); }
|
14373 | else if (node.type === "MemberExpression")
|
14374 | { c(node, st, "MemberPattern"); }
|
14375 | else
|
14376 | { c(node, st); }
|
14377 | };
|
14378 | base$1.VariablePattern = ignore;
|
14379 | base$1.MemberPattern = skipThrough;
|
14380 | base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
14381 | base$1.ArrayPattern = function (node, st, c) {
|
14382 | for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
14383 | var elt = list[i];
|
14384 |
|
14385 | if (elt) { c(elt, st, "Pattern"); }
|
14386 | }
|
14387 | };
|
14388 | base$1.ObjectPattern = function (node, st, c) {
|
14389 | for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
14390 | var prop = list[i];
|
14391 |
|
14392 | if (prop.type === "Property") {
|
14393 | if (prop.computed) { c(prop.key, st, "Expression"); }
|
14394 | c(prop.value, st, "Pattern");
|
14395 | } else if (prop.type === "RestElement") {
|
14396 | c(prop.argument, st, "Pattern");
|
14397 | }
|
14398 | }
|
14399 | };
|
14400 |
|
14401 | base$1.Expression = skipThrough;
|
14402 | base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
|
14403 | base$1.ArrayExpression = function (node, st, c) {
|
14404 | for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
14405 | var elt = list[i];
|
14406 |
|
14407 | if (elt) { c(elt, st, "Expression"); }
|
14408 | }
|
14409 | };
|
14410 | base$1.ObjectExpression = function (node, st, c) {
|
14411 | for (var i = 0, list = node.properties; i < list.length; i += 1)
|
14412 | {
|
14413 | var prop = list[i];
|
14414 |
|
14415 | c(prop, st);
|
14416 | }
|
14417 | };
|
14418 | base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
|
14419 | base$1.SequenceExpression = function (node, st, c) {
|
14420 | for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
14421 | {
|
14422 | var expr = list[i];
|
14423 |
|
14424 | c(expr, st, "Expression");
|
14425 | }
|
14426 | };
|
14427 | base$1.TemplateLiteral = function (node, st, c) {
|
14428 | for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
14429 | {
|
14430 | var quasi = list[i];
|
14431 |
|
14432 | c(quasi, st);
|
14433 | }
|
14434 |
|
14435 | for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
14436 | {
|
14437 | var expr = list$1[i$1];
|
14438 |
|
14439 | c(expr, st, "Expression");
|
14440 | }
|
14441 | };
|
14442 | base$1.TemplateElement = ignore;
|
14443 | base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
|
14444 | c(node.argument, st, "Expression");
|
14445 | };
|
14446 | base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
|
14447 | c(node.left, st, "Expression");
|
14448 | c(node.right, st, "Expression");
|
14449 | };
|
14450 | base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
|
14451 | c(node.left, st, "Pattern");
|
14452 | c(node.right, st, "Expression");
|
14453 | };
|
14454 | base$1.ConditionalExpression = function (node, st, c) {
|
14455 | c(node.test, st, "Expression");
|
14456 | c(node.consequent, st, "Expression");
|
14457 | c(node.alternate, st, "Expression");
|
14458 | };
|
14459 | base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
|
14460 | c(node.callee, st, "Expression");
|
14461 | if (node.arguments)
|
14462 | { for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
14463 | {
|
14464 | var arg = list[i];
|
14465 |
|
14466 | c(arg, st, "Expression");
|
14467 | } }
|
14468 | };
|
14469 | base$1.MemberExpression = function (node, st, c) {
|
14470 | c(node.object, st, "Expression");
|
14471 | if (node.computed) { c(node.property, st, "Expression"); }
|
14472 | };
|
14473 | base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
|
14474 | if (node.declaration)
|
14475 | { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
14476 | if (node.source) { c(node.source, st, "Expression"); }
|
14477 | };
|
14478 | base$1.ExportAllDeclaration = function (node, st, c) {
|
14479 | c(node.source, st, "Expression");
|
14480 | };
|
14481 | base$1.ImportDeclaration = function (node, st, c) {
|
14482 | for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
14483 | {
|
14484 | var spec = list[i];
|
14485 |
|
14486 | c(spec, st);
|
14487 | }
|
14488 | c(node.source, st, "Expression");
|
14489 | };
|
14490 | base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
|
14491 |
|
14492 | base$1.TaggedTemplateExpression = function (node, st, c) {
|
14493 | c(node.tag, st, "Expression");
|
14494 | c(node.quasi, st, "Expression");
|
14495 | };
|
14496 | base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
14497 | base$1.Class = function (node, st, c) {
|
14498 | if (node.id) { c(node.id, st, "Pattern"); }
|
14499 | if (node.superClass) { c(node.superClass, st, "Expression"); }
|
14500 | c(node.body, st);
|
14501 | };
|
14502 | base$1.ClassBody = function (node, st, c) {
|
14503 | for (var i = 0, list = node.body; i < list.length; i += 1)
|
14504 | {
|
14505 | var elt = list[i];
|
14506 |
|
14507 | c(elt, st);
|
14508 | }
|
14509 | };
|
14510 | base$1.MethodDefinition = base$1.Property = function (node, st, c) {
|
14511 | if (node.computed) { c(node.key, st, "Expression"); }
|
14512 | c(node.value, st, "Expression");
|
14513 | };
|
14514 |
|
14515 | // @ts-ignore
|
14516 | function handlePureAnnotationsOfNode(node, state, type) {
|
14517 | if (type === void 0) { type = node.type; }
|
14518 | var commentNode = state.commentNodes[state.commentIndex];
|
14519 | while (commentNode && node.start >= commentNode.end) {
|
14520 | markPureNode(node, commentNode);
|
14521 | commentNode = state.commentNodes[++state.commentIndex];
|
14522 | }
|
14523 | if (commentNode && commentNode.end <= node.end) {
|
14524 | base$1[type](node, state, handlePureAnnotationsOfNode);
|
14525 | }
|
14526 | }
|
14527 | function markPureNode(node, comment) {
|
14528 | if (node.annotations) {
|
14529 | node.annotations.push(comment);
|
14530 | }
|
14531 | else {
|
14532 | node.annotations = [comment];
|
14533 | }
|
14534 | if (node.type === 'ExpressionStatement') {
|
14535 | node = node.expression;
|
14536 | }
|
14537 | if (node.type === 'CallExpression' || node.type === 'NewExpression') {
|
14538 | node.annotatedPure = true;
|
14539 | }
|
14540 | }
|
14541 | var pureCommentRegex = /[@#]__PURE__/;
|
14542 | var isPureComment = function (comment) { return pureCommentRegex.test(comment.text); };
|
14543 | function markPureCallExpressions(comments, esTreeAst) {
|
14544 | handlePureAnnotationsOfNode(esTreeAst, {
|
14545 | commentIndex: 0,
|
14546 | commentNodes: comments.filter(isPureComment)
|
14547 | });
|
14548 | }
|
14549 |
|
14550 | // this looks ridiculous, but it prevents sourcemap tooling from mistaking
|
14551 | // this for an actual sourceMappingURL
|
14552 | var SOURCEMAPPING_URL = 'sourceMa';
|
14553 | SOURCEMAPPING_URL += 'ppingURL';
|
14554 | var SOURCEMAPPING_URL_RE = new RegExp("^#\\s+" + SOURCEMAPPING_URL + "=.+\\n?");
|
14555 |
|
14556 | var NOOP = function () { };
|
14557 | var getStartTime = function () { return 0; };
|
14558 | var getElapsedTime = function () { return 0; };
|
14559 | var getMemory = function () { return 0; };
|
14560 | var timers = {};
|
14561 | var normalizeHrTime = function (time) { return time[0] * 1e3 + time[1] / 1e6; };
|
14562 | function setTimeHelpers() {
|
14563 | if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
|
14564 | getStartTime = process.hrtime.bind(process);
|
14565 | getElapsedTime = function (previous) { return normalizeHrTime(process.hrtime(previous)); };
|
14566 | }
|
14567 | else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
|
14568 | getStartTime = performance.now.bind(performance);
|
14569 | getElapsedTime = function (previous) { return performance.now() - previous; };
|
14570 | }
|
14571 | if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
|
14572 | getMemory = function () { return process.memoryUsage().heapUsed; };
|
14573 | }
|
14574 | }
|
14575 | function getPersistedLabel(label, level) {
|
14576 | switch (level) {
|
14577 | case 1:
|
14578 | return "# " + label;
|
14579 | case 2:
|
14580 | return "## " + label;
|
14581 | case 3:
|
14582 | return label;
|
14583 | default:
|
14584 | return ' '.repeat(level - 4) + "- " + label;
|
14585 | }
|
14586 | }
|
14587 | function timeStartImpl(label, level) {
|
14588 | if (level === void 0) { level = 3; }
|
14589 | label = getPersistedLabel(label, level);
|
14590 | if (!timers.hasOwnProperty(label)) {
|
14591 | timers[label] = {
|
14592 | memory: 0,
|
14593 | startMemory: undefined,
|
14594 | startTime: undefined,
|
14595 | time: 0,
|
14596 | totalMemory: 0
|
14597 | };
|
14598 | }
|
14599 | var currentMemory = getMemory();
|
14600 | timers[label].startTime = getStartTime();
|
14601 | timers[label].startMemory = currentMemory;
|
14602 | }
|
14603 | function timeEndImpl(label, level) {
|
14604 | if (level === void 0) { level = 3; }
|
14605 | label = getPersistedLabel(label, level);
|
14606 | if (timers.hasOwnProperty(label)) {
|
14607 | var currentMemory = getMemory();
|
14608 | timers[label].time += getElapsedTime(timers[label].startTime);
|
14609 | timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
|
14610 | timers[label].memory += currentMemory - timers[label].startMemory;
|
14611 | }
|
14612 | }
|
14613 | function getTimings() {
|
14614 | var newTimings = {};
|
14615 | Object.keys(timers).forEach(function (label) {
|
14616 | newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
|
14617 | });
|
14618 | return newTimings;
|
14619 | }
|
14620 | var timeStart = NOOP, timeEnd = NOOP;
|
14621 | var TIMED_PLUGIN_HOOKS = {
|
14622 | load: true,
|
14623 | ongenerate: true,
|
14624 | onwrite: true,
|
14625 | resolveDynamicImport: true,
|
14626 | resolveId: true,
|
14627 | transform: true,
|
14628 | transformBundle: true
|
14629 | };
|
14630 | function getPluginWithTimers(plugin, index) {
|
14631 | var timedPlugin = {};
|
14632 | var _loop_1 = function (hook) {
|
14633 | if (TIMED_PLUGIN_HOOKS[hook] === true) {
|
14634 | var timerLabel_1 = "plugin " + index;
|
14635 | if (plugin.name) {
|
14636 | timerLabel_1 += " (" + plugin.name + ")";
|
14637 | }
|
14638 | timerLabel_1 += " - " + hook;
|
14639 | timedPlugin[hook] = function () {
|
14640 | timeStart(timerLabel_1, 4);
|
14641 | var result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
|
14642 | timeEnd(timerLabel_1, 4);
|
14643 | if (result && typeof result.then === 'function') {
|
14644 | timeStart(timerLabel_1 + " (async)", 4);
|
14645 | result.then(function () { return timeEnd(timerLabel_1 + " (async)", 4); });
|
14646 | }
|
14647 | return result;
|
14648 | };
|
14649 | }
|
14650 | else {
|
14651 | timedPlugin[hook] = plugin[hook];
|
14652 | }
|
14653 | };
|
14654 | for (var _i = 0, _a = Object.keys(plugin); _i < _a.length; _i++) {
|
14655 | var hook = _a[_i];
|
14656 | _loop_1(hook);
|
14657 | }
|
14658 | return timedPlugin;
|
14659 | }
|
14660 | function initialiseTimers(inputOptions) {
|
14661 | if (inputOptions.perf) {
|
14662 | timers = {};
|
14663 | setTimeHelpers();
|
14664 | timeStart = timeStartImpl;
|
14665 | timeEnd = timeEndImpl;
|
14666 | inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
|
14667 | }
|
14668 | else {
|
14669 | timeStart = NOOP;
|
14670 | timeEnd = NOOP;
|
14671 | }
|
14672 | }
|
14673 |
|
14674 | function visitStaticModuleDependencies(baseModule, areDependenciesSkipped) {
|
14675 | var modules = [baseModule];
|
14676 | var visitedModules = {};
|
14677 | for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
|
14678 | var module = modules_1[_i];
|
14679 | if (areDependenciesSkipped(module) || module instanceof ExternalModule)
|
14680 | continue;
|
14681 | for (var _a = 0, _b = module.dependencies; _a < _b.length; _a++) {
|
14682 | var dependency = _b[_a];
|
14683 | if (!visitedModules[dependency.id]) {
|
14684 | visitedModules[dependency.id] = true;
|
14685 | modules.push(dependency);
|
14686 | }
|
14687 | }
|
14688 | }
|
14689 | }
|
14690 |
|
14691 | var defaultAcornOptions = {
|
14692 | ecmaVersion: 2019,
|
14693 | preserveParens: false,
|
14694 | sourceType: 'module'
|
14695 | };
|
14696 | function tryParse(module, Parser, acornOptions) {
|
14697 | try {
|
14698 | return Parser.parse(module.code, __assign({}, defaultAcornOptions, acornOptions, { onComment: function (block, text, start, end) {
|
14699 | return module.comments.push({ block: block, text: text, start: start, end: end });
|
14700 | } }));
|
14701 | }
|
14702 | catch (err) {
|
14703 | var message = err.message.replace(/ \(\d+:\d+\)$/, '');
|
14704 | if (module.id.endsWith('.json')) {
|
14705 | message += ' (Note that you need rollup-plugin-json to import JSON files)';
|
14706 | }
|
14707 | else if (!module.id.endsWith('.js')) {
|
14708 | message += ' (Note that you need plugins to import files that are not JavaScript)';
|
14709 | }
|
14710 | module.error({
|
14711 | code: 'PARSE_ERROR',
|
14712 | message: message
|
14713 | }, err.pos);
|
14714 | }
|
14715 | }
|
14716 | function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
|
14717 | importingModule.error({
|
14718 | code: 'MISSING_EXPORT',
|
14719 | message: "'" + exportName + "' is not exported by " + relativeId(importedModule),
|
14720 | url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
|
14721 | }, importerStart);
|
14722 | }
|
14723 | var MISSING_EXPORT_SHIM_DESCRIPTION = {
|
14724 | localName: MISSING_EXPORT_SHIM_VARIABLE
|
14725 | };
|
14726 | var Module = /** @class */ (function () {
|
14727 | function Module(graph, id) {
|
14728 | this.chunkAlias = null;
|
14729 | this.comments = [];
|
14730 | this.dependencies = [];
|
14731 | this.dynamicallyImportedBy = [];
|
14732 | this.dynamicDependencies = [];
|
14733 | this.dynamicImports = [];
|
14734 | this.entryPointsHash = new Uint8Array(10);
|
14735 | this.execIndex = Infinity;
|
14736 | this.exportAllModules = null;
|
14737 | this.exportAllSources = [];
|
14738 | this.exports = Object.create(null);
|
14739 | this.exportsAll = Object.create(null);
|
14740 | this.exportShimVariable = new ExportShimVariable(this);
|
14741 | this.facadeChunk = null;
|
14742 | this.importDescriptions = Object.create(null);
|
14743 | this.importMetas = [];
|
14744 | this.imports = new Set();
|
14745 | this.isEntryPoint = false;
|
14746 | this.isExecuted = false;
|
14747 | this.isUserDefinedEntryPoint = false;
|
14748 | this.manualChunkAlias = null;
|
14749 | this.reexports = Object.create(null);
|
14750 | this.sources = [];
|
14751 | this.usesTopLevelAwait = false;
|
14752 | this.namespaceVariable = undefined;
|
14753 | this.id = id;
|
14754 | this.graph = graph;
|
14755 | this.excludeFromSourcemap = /\0/.test(id);
|
14756 | this.context = graph.getModuleContext(id);
|
14757 | }
|
14758 | Module.prototype.basename = function () {
|
14759 | var base = path.basename(this.id);
|
14760 | var ext = path.extname(this.id);
|
14761 | return makeLegal(ext ? base.slice(0, -ext.length) : base);
|
14762 | };
|
14763 | Module.prototype.bindReferences = function () {
|
14764 | this.ast.bind();
|
14765 | };
|
14766 | Module.prototype.error = function (props, pos) {
|
14767 | if (pos !== undefined) {
|
14768 | props.pos = pos;
|
14769 | var location = locate(this.code, pos, { offsetLine: 1 });
|
14770 | try {
|
14771 | location = getOriginalLocation(this.sourcemapChain, location);
|
14772 | }
|
14773 | catch (e) {
|
14774 | this.warn({
|
14775 | code: 'SOURCEMAP_ERROR',
|
14776 | loc: {
|
14777 | column: location.column,
|
14778 | file: this.id,
|
14779 | line: location.line
|
14780 | },
|
14781 | message: "Error when using sourcemap for reporting an error: " + e.message,
|
14782 | pos: pos
|
14783 | }, undefined);
|
14784 | }
|
14785 | props.loc = {
|
14786 | column: location.column,
|
14787 | file: this.id,
|
14788 | line: location.line
|
14789 | };
|
14790 | props.frame = getCodeFrame(this.originalCode, location.line, location.column);
|
14791 | }
|
14792 | error(props);
|
14793 | };
|
14794 | Module.prototype.getAllExports = function () {
|
14795 | var allExports = Object.assign(Object.create(null), this.exports, this.reexports);
|
14796 | this.exportAllModules.forEach(function (module) {
|
14797 | if (module.isExternal) {
|
14798 | allExports["*" + module.id] = true;
|
14799 | return;
|
14800 | }
|
14801 | for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
|
14802 | var name = _a[_i];
|
14803 | if (name !== 'default')
|
14804 | allExports[name] = true;
|
14805 | }
|
14806 | });
|
14807 | return Object.keys(allExports);
|
14808 | };
|
14809 | Module.prototype.getDynamicImportExpressions = function () {
|
14810 | return this.dynamicImports.map(function (_a) {
|
14811 | var node = _a.node;
|
14812 | var importArgument = node.parent.arguments[0];
|
14813 | if (isTemplateLiteral(importArgument)) {
|
14814 | if (importArgument.expressions.length === 0 && importArgument.quasis.length === 1) {
|
14815 | return importArgument.quasis[0].value.cooked;
|
14816 | }
|
14817 | }
|
14818 | else if (isLiteral(importArgument)) {
|
14819 | if (typeof importArgument.value === 'string') {
|
14820 | return importArgument.value;
|
14821 | }
|
14822 | }
|
14823 | else {
|
14824 | return importArgument;
|
14825 | }
|
14826 | });
|
14827 | };
|
14828 | Module.prototype.getExports = function () {
|
14829 | return Object.keys(this.exports);
|
14830 | };
|
14831 | Module.prototype.getOrCreateNamespace = function () {
|
14832 | return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext)));
|
14833 | };
|
14834 | Module.prototype.getReexports = function () {
|
14835 | var reexports = Object.create(null);
|
14836 | for (var name in this.reexports) {
|
14837 | reexports[name] = true;
|
14838 | }
|
14839 | this.exportAllModules.forEach(function (module) {
|
14840 | if (module.isExternal) {
|
14841 | reexports["*" + module.id] = true;
|
14842 | return;
|
14843 | }
|
14844 | for (var _i = 0, _a = module.getExports().concat(module.getReexports()); _i < _a.length; _i++) {
|
14845 | var name = _a[_i];
|
14846 | if (name !== 'default')
|
14847 | reexports[name] = true;
|
14848 | }
|
14849 | });
|
14850 | return Object.keys(reexports);
|
14851 | };
|
14852 | Module.prototype.getRenderedExports = function () {
|
14853 | // only direct exports are counted here, not reexports at all
|
14854 | var renderedExports = [];
|
14855 | var removedExports = [];
|
14856 | for (var exportName in this.exports) {
|
14857 | var variable = this.getVariableForExportName(exportName);
|
14858 | (variable && variable.included ? renderedExports : removedExports).push(exportName);
|
14859 | }
|
14860 | return { renderedExports: renderedExports, removedExports: removedExports };
|
14861 | };
|
14862 | Module.prototype.getVariableForExportName = function (name, isExportAllSearch) {
|
14863 | if (name[0] === '*') {
|
14864 | if (name.length === 1) {
|
14865 | return this.getOrCreateNamespace();
|
14866 | }
|
14867 | else {
|
14868 | // export * from 'external'
|
14869 | var module = this.graph.moduleById.get(name.slice(1));
|
14870 | return module.getVariableForExportName('*');
|
14871 | }
|
14872 | }
|
14873 | // export { foo } from './other'
|
14874 | var reexportDeclaration = this.reexports[name];
|
14875 | if (reexportDeclaration) {
|
14876 | var declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
|
14877 | if (!declaration) {
|
14878 | handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
|
14879 | }
|
14880 | return declaration;
|
14881 | }
|
14882 | var exportDeclaration = this.exports[name];
|
14883 | if (exportDeclaration) {
|
14884 | if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
|
14885 | return this.exportShimVariable;
|
14886 | }
|
14887 | var name_1 = exportDeclaration.localName;
|
14888 | return this.traceVariable(name_1) || this.graph.scope.findVariable(name_1);
|
14889 | }
|
14890 | if (name !== 'default') {
|
14891 | for (var i = 0; i < this.exportAllModules.length; i += 1) {
|
14892 | var module = this.exportAllModules[i];
|
14893 | var declaration = module.getVariableForExportName(name, true);
|
14894 | if (declaration)
|
14895 | return declaration;
|
14896 | }
|
14897 | }
|
14898 | // we don't want to create shims when we are just
|
14899 | // probing export * modules for exports
|
14900 | if (this.graph.shimMissingExports && !isExportAllSearch) {
|
14901 | this.shimMissingExport(name);
|
14902 | return this.exportShimVariable;
|
14903 | }
|
14904 | };
|
14905 | Module.prototype.include = function () {
|
14906 | if (this.ast.shouldBeIncluded())
|
14907 | this.ast.include(false);
|
14908 | };
|
14909 | Module.prototype.includeAllExports = function () {
|
14910 | if (!this.isExecuted) {
|
14911 | this.graph.needsTreeshakingPass = true;
|
14912 | visitStaticModuleDependencies(this, function (module) {
|
14913 | if (module instanceof ExternalModule || module.isExecuted)
|
14914 | return true;
|
14915 | module.isExecuted = true;
|
14916 | return false;
|
14917 | });
|
14918 | }
|
14919 | for (var _i = 0, _a = this.getExports(); _i < _a.length; _i++) {
|
14920 | var exportName = _a[_i];
|
14921 | var variable = this.getVariableForExportName(exportName);
|
14922 | variable.deoptimizePath(UNKNOWN_PATH);
|
14923 | if (!variable.included) {
|
14924 | variable.include();
|
14925 | this.graph.needsTreeshakingPass = true;
|
14926 | }
|
14927 | }
|
14928 | for (var _b = 0, _c = this.getReexports(); _b < _c.length; _b++) {
|
14929 | var name = _c[_b];
|
14930 | var variable = this.getVariableForExportName(name);
|
14931 | if (variable.isExternal) {
|
14932 | variable.reexported = variable.module.reexported = true;
|
14933 | }
|
14934 | else if (!variable.included) {
|
14935 | variable.include();
|
14936 | variable.deoptimizePath(UNKNOWN_PATH);
|
14937 | this.graph.needsTreeshakingPass = true;
|
14938 | }
|
14939 | }
|
14940 | };
|
14941 | Module.prototype.includeAllInBundle = function () {
|
14942 | this.ast.include(true);
|
14943 | };
|
14944 | Module.prototype.isIncluded = function () {
|
14945 | return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
|
14946 | };
|
14947 | Module.prototype.linkDependencies = function () {
|
14948 | var _this = this;
|
14949 | for (var _i = 0, _a = this.sources; _i < _a.length; _i++) {
|
14950 | var source = _a[_i];
|
14951 | var id = this.resolvedIds[source].id;
|
14952 | if (id) {
|
14953 | var module = this.graph.moduleById.get(id);
|
14954 | this.dependencies.push(module);
|
14955 | }
|
14956 | }
|
14957 | for (var _b = 0, _c = this.dynamicImports; _b < _c.length; _b++) {
|
14958 | var resolution = _c[_b].resolution;
|
14959 | if (resolution instanceof Module || resolution instanceof ExternalModule) {
|
14960 | this.dynamicDependencies.push(resolution);
|
14961 | }
|
14962 | }
|
14963 | this.addModulesToSpecifiers(this.importDescriptions);
|
14964 | this.addModulesToSpecifiers(this.reexports);
|
14965 | this.exportAllModules = this.exportAllSources.map(function (source) {
|
14966 | var id = _this.resolvedIds[source].id;
|
14967 | return _this.graph.moduleById.get(id);
|
14968 | });
|
14969 | };
|
14970 | Module.prototype.render = function (options) {
|
14971 | var magicString = this.magicString.clone();
|
14972 | this.ast.render(magicString, options);
|
14973 | this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
|
14974 | return magicString;
|
14975 | };
|
14976 | Module.prototype.setSource = function (_a) {
|
14977 | var _this = this;
|
14978 | 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;
|
14979 | this.code = code;
|
14980 | this.originalCode = originalCode;
|
14981 | this.originalSourcemap = originalSourcemap;
|
14982 | this.sourcemapChain = sourcemapChain;
|
14983 | this.transformDependencies = transformDependencies;
|
14984 | this.customTransformCache = customTransformCache;
|
14985 | timeStart('generate ast', 3);
|
14986 | this.esTreeAst = ((ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions)));
|
14987 | markPureCallExpressions(this.comments, this.esTreeAst);
|
14988 | timeEnd('generate ast', 3);
|
14989 | this.resolvedIds = resolvedIds || Object.create(null);
|
14990 | // By default, `id` is the file name. Custom resolvers and loaders
|
14991 | // can change that, but it makes sense to use it for the source file name
|
14992 | var fileName = this.id;
|
14993 | this.magicString = new MagicString(code, {
|
14994 | filename: this.excludeFromSourcemap ? null : fileName,
|
14995 | indentExclusionRanges: []
|
14996 | });
|
14997 | this.removeExistingSourceMap();
|
14998 | timeStart('analyse ast', 3);
|
14999 | this.astContext = {
|
15000 | addDynamicImport: this.addDynamicImport.bind(this),
|
15001 | addExport: this.addExport.bind(this),
|
15002 | addImport: this.addImport.bind(this),
|
15003 | addImportMeta: this.addImportMeta.bind(this),
|
15004 | annotations: this.graph.treeshake && this.graph.treeshakingOptions.annotations,
|
15005 | code: code,
|
15006 | deoptimizationTracker: this.graph.deoptimizationTracker,
|
15007 | error: this.error.bind(this),
|
15008 | fileName: fileName,
|
15009 | getAssetFileName: this.graph.pluginDriver.getAssetFileName,
|
15010 | getChunkFileName: this.graph.moduleLoader.getChunkFileName.bind(this.graph.moduleLoader),
|
15011 | getExports: this.getExports.bind(this),
|
15012 | getModuleExecIndex: function () { return _this.execIndex; },
|
15013 | getModuleName: this.basename.bind(this),
|
15014 | getReexports: this.getReexports.bind(this),
|
15015 | importDescriptions: this.importDescriptions,
|
15016 | includeDynamicImport: this.includeDynamicImport.bind(this),
|
15017 | includeVariable: this.includeVariable.bind(this),
|
15018 | isCrossChunkImport: function (importDescription) { return importDescription.module.chunk !== _this.chunk; },
|
15019 | magicString: this.magicString,
|
15020 | module: this,
|
15021 | moduleContext: this.context,
|
15022 | nodeConstructors: nodeConstructors,
|
15023 | preserveModules: this.graph.preserveModules,
|
15024 | propertyReadSideEffects: !this.graph.treeshake || this.graph.treeshakingOptions.propertyReadSideEffects,
|
15025 | traceExport: this.getVariableForExportName.bind(this),
|
15026 | traceVariable: this.traceVariable.bind(this),
|
15027 | treeshake: this.graph.treeshake,
|
15028 | usesTopLevelAwait: false,
|
15029 | warn: this.warn.bind(this)
|
15030 | };
|
15031 | this.scope = new ModuleScope(this.graph.scope, this.astContext);
|
15032 | this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
|
15033 | timeEnd('analyse ast', 3);
|
15034 | };
|
15035 | Module.prototype.toJSON = function () {
|
15036 | return {
|
15037 | ast: this.esTreeAst,
|
15038 | code: this.code,
|
15039 | customTransformCache: this.customTransformCache,
|
15040 | dependencies: this.dependencies.map(function (module) { return module.id; }),
|
15041 | id: this.id,
|
15042 | originalCode: this.originalCode,
|
15043 | originalSourcemap: this.originalSourcemap,
|
15044 | resolvedIds: this.resolvedIds,
|
15045 | sourcemapChain: this.sourcemapChain,
|
15046 | transformAssets: this.transformAssets,
|
15047 | transformDependencies: this.transformDependencies
|
15048 | };
|
15049 | };
|
15050 | Module.prototype.traceVariable = function (name) {
|
15051 | if (name in this.scope.variables) {
|
15052 | return this.scope.variables[name];
|
15053 | }
|
15054 | if (name in this.importDescriptions) {
|
15055 | var importDeclaration = this.importDescriptions[name];
|
15056 | var otherModule = importDeclaration.module;
|
15057 | if (!otherModule.isExternal && importDeclaration.name === '*') {
|
15058 | return otherModule.getOrCreateNamespace();
|
15059 | }
|
15060 | var declaration = otherModule.getVariableForExportName(importDeclaration.name);
|
15061 | if (!declaration) {
|
15062 | handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
|
15063 | }
|
15064 | return declaration;
|
15065 | }
|
15066 | return null;
|
15067 | };
|
15068 | Module.prototype.warn = function (warning, pos) {
|
15069 | if (pos !== undefined) {
|
15070 | warning.pos = pos;
|
15071 | var _a = locate(this.code, pos, { offsetLine: 1 }), line = _a.line, column = _a.column; // TODO trace sourcemaps, cf. error()
|
15072 | warning.loc = { file: this.id, line: line, column: column };
|
15073 | warning.frame = getCodeFrame(this.code, line, column);
|
15074 | }
|
15075 | warning.id = this.id;
|
15076 | this.graph.warn(warning);
|
15077 | };
|
15078 | Module.prototype.addDynamicImport = function (node) {
|
15079 | this.dynamicImports.push({ node: node, resolution: undefined });
|
15080 | };
|
15081 | Module.prototype.addExport = function (node) {
|
15082 | var source = node.source && node.source.value;
|
15083 | // export { name } from './other'
|
15084 | if (source) {
|
15085 | if (this.sources.indexOf(source) === -1)
|
15086 | this.sources.push(source);
|
15087 | if (node.type === ExportAllDeclaration) {
|
15088 | // Store `export * from '...'` statements in an array of delegates.
|
15089 | // When an unknown import is encountered, we see if one of them can satisfy it.
|
15090 | this.exportAllSources.push(source);
|
15091 | }
|
15092 | else {
|
15093 | for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
|
15094 | var specifier = _a[_i];
|
15095 | var name = specifier.exported.name;
|
15096 | if (this.exports[name] || this.reexports[name]) {
|
15097 | this.error({
|
15098 | code: 'DUPLICATE_EXPORT',
|
15099 | message: "A module cannot have multiple exports with the same name ('" + name + "')"
|
15100 | }, specifier.start);
|
15101 | }
|
15102 | this.reexports[name] = {
|
15103 | localName: specifier.local.name,
|
15104 | module: null,
|
15105 | source: source,
|
15106 | start: specifier.start
|
15107 | };
|
15108 | }
|
15109 | }
|
15110 | }
|
15111 | else if (isExportDefaultDeclaration(node)) {
|
15112 | // export default function foo () {}
|
15113 | // export default foo;
|
15114 | // export default 42;
|
15115 | if (this.exports.default) {
|
15116 | this.error({
|
15117 | code: 'DUPLICATE_EXPORT',
|
15118 | message: "A module can only have one default export"
|
15119 | }, node.start);
|
15120 | }
|
15121 | this.exports.default = {
|
15122 | identifier: node.variable.getOriginalVariableName(),
|
15123 | localName: 'default'
|
15124 | };
|
15125 | }
|
15126 | else if (node.declaration) {
|
15127 | // export var { foo, bar } = ...
|
15128 | // export var foo = 42;
|
15129 | // export var a = 1, b = 2, c = 3;
|
15130 | // export function foo () {}
|
15131 | var declaration = node.declaration;
|
15132 | if (declaration.type === VariableDeclaration) {
|
15133 | for (var _b = 0, _c = declaration.declarations; _b < _c.length; _b++) {
|
15134 | var decl = _c[_b];
|
15135 | for (var _d = 0, _e = extractAssignedNames(decl.id); _d < _e.length; _d++) {
|
15136 | var localName = _e[_d];
|
15137 | this.exports[localName] = { localName: localName };
|
15138 | }
|
15139 | }
|
15140 | }
|
15141 | else {
|
15142 | // export function foo () {}
|
15143 | var localName = declaration.id.name;
|
15144 | this.exports[localName] = { localName: localName };
|
15145 | }
|
15146 | }
|
15147 | else {
|
15148 | // export { foo, bar, baz }
|
15149 | for (var _f = 0, _g = node.specifiers; _f < _g.length; _f++) {
|
15150 | var specifier = _g[_f];
|
15151 | var localName = specifier.local.name;
|
15152 | var exportedName = specifier.exported.name;
|
15153 | if (this.exports[exportedName] || this.reexports[exportedName]) {
|
15154 | this.error({
|
15155 | code: 'DUPLICATE_EXPORT',
|
15156 | message: "A module cannot have multiple exports with the same name ('" + exportedName + "')"
|
15157 | }, specifier.start);
|
15158 | }
|
15159 | this.exports[exportedName] = { localName: localName };
|
15160 | }
|
15161 | }
|
15162 | };
|
15163 | Module.prototype.addImport = function (node) {
|
15164 | var source = node.source.value;
|
15165 | if (this.sources.indexOf(source) === -1)
|
15166 | this.sources.push(source);
|
15167 | for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
|
15168 | var specifier = _a[_i];
|
15169 | var localName = specifier.local.name;
|
15170 | if (this.importDescriptions[localName]) {
|
15171 | this.error({
|
15172 | code: 'DUPLICATE_IMPORT',
|
15173 | message: "Duplicated import '" + localName + "'"
|
15174 | }, specifier.start);
|
15175 | }
|
15176 | var isDefault = specifier.type === ImportDefaultSpecifier;
|
15177 | var isNamespace = specifier.type === ImportNamespaceSpecifier;
|
15178 | var name = isDefault
|
15179 | ? 'default'
|
15180 | : isNamespace
|
15181 | ? '*'
|
15182 | : specifier.imported.name;
|
15183 | this.importDescriptions[localName] = { source: source, start: specifier.start, name: name, module: null };
|
15184 | }
|
15185 | };
|
15186 | Module.prototype.addImportMeta = function (node) {
|
15187 | this.importMetas.push(node);
|
15188 | };
|
15189 | Module.prototype.addModulesToSpecifiers = function (specifiers) {
|
15190 | for (var _i = 0, _a = Object.keys(specifiers); _i < _a.length; _i++) {
|
15191 | var name = _a[_i];
|
15192 | var specifier = specifiers[name];
|
15193 | var id = this.resolvedIds[specifier.source].id;
|
15194 | specifier.module = this.graph.moduleById.get(id);
|
15195 | }
|
15196 | };
|
15197 | Module.prototype.includeDynamicImport = function (node) {
|
15198 | var resolution = this.dynamicImports.find(function (dynamicImport) { return dynamicImport.node === node; })
|
15199 | .resolution;
|
15200 | if (resolution instanceof Module) {
|
15201 | resolution.dynamicallyImportedBy.push(this);
|
15202 | resolution.includeAllExports();
|
15203 | }
|
15204 | };
|
15205 | Module.prototype.includeVariable = function (variable) {
|
15206 | if (!variable.included) {
|
15207 | variable.include();
|
15208 | this.graph.needsTreeshakingPass = true;
|
15209 | }
|
15210 | if (variable.module && variable.module !== this) {
|
15211 | this.imports.add(variable);
|
15212 | }
|
15213 | };
|
15214 | Module.prototype.removeExistingSourceMap = function () {
|
15215 | for (var _i = 0, _a = this.comments; _i < _a.length; _i++) {
|
15216 | var comment = _a[_i];
|
15217 | if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
|
15218 | this.magicString.remove(comment.start, comment.end);
|
15219 | }
|
15220 | }
|
15221 | };
|
15222 | Module.prototype.shimMissingExport = function (name) {
|
15223 | if (!this.exports[name]) {
|
15224 | this.graph.warn({
|
15225 | code: 'SHIMMED_EXPORT',
|
15226 | exporter: relativeId(this.id),
|
15227 | exportName: name,
|
15228 | message: "Missing export \"" + name + "\" has been shimmed in module " + relativeId(this.id) + "."
|
15229 | });
|
15230 | this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
|
15231 | }
|
15232 | };
|
15233 | return Module;
|
15234 | }());
|
15235 |
|
15236 | var Source = /** @class */ (function () {
|
15237 | function Source(filename, content) {
|
15238 | this.isOriginal = true;
|
15239 | this.filename = filename;
|
15240 | this.content = content;
|
15241 | }
|
15242 | Source.prototype.traceSegment = function (line, column, name) {
|
15243 | return { line: line, column: column, name: name, source: this };
|
15244 | };
|
15245 | return Source;
|
15246 | }());
|
15247 | var Link = /** @class */ (function () {
|
15248 | function Link(map, sources) {
|
15249 | this.sources = sources;
|
15250 | this.names = map.names;
|
15251 | this.mappings = map.mappings;
|
15252 | }
|
15253 | Link.prototype.traceMappings = function () {
|
15254 | var sources = [];
|
15255 | var sourcesContent = [];
|
15256 | var names = [];
|
15257 | var mappings = [];
|
15258 | for (var _i = 0, _a = this.mappings; _i < _a.length; _i++) {
|
15259 | var line = _a[_i];
|
15260 | var tracedLine = [];
|
15261 | for (var _b = 0, line_1 = line; _b < line_1.length; _b++) {
|
15262 | var segment = line_1[_b];
|
15263 | var source = this.sources[segment[1]];
|
15264 | if (!source)
|
15265 | continue;
|
15266 | var traced = source.traceSegment(segment[2], segment[3], this.names[segment[4]]);
|
15267 | if (traced) {
|
15268 | // newer sources are more likely to be used, so search backwards.
|
15269 | var sourceIndex = sources.lastIndexOf(traced.source.filename);
|
15270 | if (sourceIndex === -1) {
|
15271 | sourceIndex = sources.length;
|
15272 | sources.push(traced.source.filename);
|
15273 | sourcesContent[sourceIndex] = traced.source.content;
|
15274 | }
|
15275 | else if (sourcesContent[sourceIndex] == null) {
|
15276 | sourcesContent[sourceIndex] = traced.source.content;
|
15277 | }
|
15278 | else if (traced.source.content != null &&
|
15279 | sourcesContent[sourceIndex] !== traced.source.content) {
|
15280 | error({
|
15281 | message: "Multiple conflicting contents for sourcemap source " + traced.source.filename
|
15282 | });
|
15283 | }
|
15284 | var tracedSegment = [
|
15285 | segment[0],
|
15286 | sourceIndex,
|
15287 | traced.line,
|
15288 | traced.column
|
15289 | ];
|
15290 | if (traced.name) {
|
15291 | var nameIndex = names.indexOf(traced.name);
|
15292 | if (nameIndex === -1) {
|
15293 | nameIndex = names.length;
|
15294 | names.push(traced.name);
|
15295 | }
|
15296 | tracedSegment[4] = nameIndex;
|
15297 | }
|
15298 | tracedLine.push(tracedSegment);
|
15299 | }
|
15300 | }
|
15301 | mappings.push(tracedLine);
|
15302 | }
|
15303 | return { sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings };
|
15304 | };
|
15305 | Link.prototype.traceSegment = function (line, column, name) {
|
15306 | var segments = this.mappings[line];
|
15307 | if (!segments)
|
15308 | return null;
|
15309 | // binary search through segments for the given column
|
15310 | var i = 0;
|
15311 | var j = segments.length - 1;
|
15312 | while (i <= j) {
|
15313 | var m = (i + j) >> 1;
|
15314 | var segment = segments[m];
|
15315 | if (segment[0] === column) {
|
15316 | var source = this.sources[segment[1]];
|
15317 | if (!source)
|
15318 | return null;
|
15319 | return source.traceSegment(segment[2], segment[3], this.names[segment[4]] || name);
|
15320 | }
|
15321 | if (segment[0] > column) {
|
15322 | j = m - 1;
|
15323 | }
|
15324 | else {
|
15325 | i = m + 1;
|
15326 | }
|
15327 | }
|
15328 | return null;
|
15329 | };
|
15330 | return Link;
|
15331 | }());
|
15332 | // TODO TypeScript: Fix <any> typecasts
|
15333 | function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
|
15334 | function linkMap(source, map) {
|
15335 | if (map.missing) {
|
15336 | bundle.graph.warn({
|
15337 | code: 'SOURCEMAP_BROKEN',
|
15338 | 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",
|
15339 | plugin: map.plugin,
|
15340 | url: "https://rollupjs.org/guide/en#warning-sourcemap-is-likely-to-be-incorrect"
|
15341 | });
|
15342 | map = {
|
15343 | mappings: '',
|
15344 | names: []
|
15345 | };
|
15346 | }
|
15347 | return new Link(map, [source]);
|
15348 | }
|
15349 | var moduleSources = modules
|
15350 | .filter(function (module) { return !module.excludeFromSourcemap; })
|
15351 | .map(function (module) {
|
15352 | var sourcemapChain = module.sourcemapChain;
|
15353 | var source;
|
15354 | var originalSourcemap = module.originalSourcemap;
|
15355 | if (!originalSourcemap) {
|
15356 | source = new Source(module.id, module.originalCode);
|
15357 | }
|
15358 | else {
|
15359 | var sources_1 = originalSourcemap.sources;
|
15360 | var sourcesContent_1 = originalSourcemap.sourcesContent || [];
|
15361 | if (sources_1 == null || (sources_1.length <= 1 && sources_1[0] == null)) {
|
15362 | source = new Source(module.id, sourcesContent_1[0]);
|
15363 | sourcemapChain = [originalSourcemap].concat(sourcemapChain);
|
15364 | }
|
15365 | else {
|
15366 | // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
|
15367 | var directory_1 = path.dirname(module.id) || '.';
|
15368 | var sourceRoot_1 = originalSourcemap.sourceRoot || '.';
|
15369 | var baseSources = sources_1.map(function (source, i) { return new Source(path.resolve(directory_1, sourceRoot_1, source), sourcesContent_1[i]); });
|
15370 | source = new Link(originalSourcemap, baseSources);
|
15371 | }
|
15372 | }
|
15373 | source = sourcemapChain.reduce(linkMap, source);
|
15374 | return source;
|
15375 | });
|
15376 | var source = new Link(map, moduleSources);
|
15377 | source = bundleSourcemapChain.reduce(linkMap, source);
|
15378 | var _a = source.traceMappings(), sources = _a.sources, sourcesContent = _a.sourcesContent, names = _a.names, mappings = _a.mappings;
|
15379 | if (file) {
|
15380 | var directory_2 = path.dirname(file);
|
15381 | sources = sources.map(function (source) { return path.relative(directory_2, source); });
|
15382 | file = path.basename(file);
|
15383 | }
|
15384 | sourcesContent = excludeContent ? null : sourcesContent;
|
15385 | return new SourceMap({ file: file, sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings });
|
15386 | }
|
15387 |
|
15388 | var _a;
|
15389 | var RESERVED_NAMES = Object.assign(Object.create(null), {
|
15390 | await: true,
|
15391 | break: true,
|
15392 | case: true,
|
15393 | catch: true,
|
15394 | class: true,
|
15395 | const: true,
|
15396 | continue: true,
|
15397 | debugger: true,
|
15398 | default: true,
|
15399 | delete: true,
|
15400 | do: true,
|
15401 | else: true,
|
15402 | enum: true,
|
15403 | eval: true,
|
15404 | export: true,
|
15405 | extends: true,
|
15406 | finally: true,
|
15407 | for: true,
|
15408 | function: true,
|
15409 | if: true,
|
15410 | implements: true,
|
15411 | import: true,
|
15412 | in: true,
|
15413 | instanceof: true,
|
15414 | interface: true,
|
15415 | let: true,
|
15416 | new: true,
|
15417 | null: true,
|
15418 | package: true,
|
15419 | private: true,
|
15420 | protected: true,
|
15421 | public: true,
|
15422 | return: true,
|
15423 | static: true,
|
15424 | super: true,
|
15425 | switch: true,
|
15426 | throw: true,
|
15427 | try: true,
|
15428 | typeof: true,
|
15429 | undefined: true,
|
15430 | var: true,
|
15431 | void: true,
|
15432 | while: true,
|
15433 | with: true,
|
15434 | yield: true
|
15435 | });
|
15436 | var NONE = {};
|
15437 | var EXPORTS = { exports: true };
|
15438 | var RESERVED_NAMES_BY_FORMAT = {
|
15439 | amd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
|
15440 | cjs: {
|
15441 | forbiddenNames: RESERVED_NAMES,
|
15442 | formatGlobals: (_a = { exports: true, module: true }, _a[INTEROP_DEFAULT_VARIABLE] = true, _a)
|
15443 | },
|
15444 | es: { formatGlobals: NONE, forbiddenNames: RESERVED_NAMES },
|
15445 | iife: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
|
15446 | system: {
|
15447 | forbiddenNames: Object.assign(Object.create(null), RESERVED_NAMES, EXPORTS),
|
15448 | formatGlobals: NONE
|
15449 | },
|
15450 | umd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES }
|
15451 | };
|
15452 |
|
15453 | var DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
|
15454 | amd: deconflictImportsOther,
|
15455 | cjs: deconflictImportsOther,
|
15456 | es: deconflictImportsEsm,
|
15457 | iife: deconflictImportsOther,
|
15458 | system: deconflictImportsEsm,
|
15459 | umd: deconflictImportsOther
|
15460 | };
|
15461 | function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
|
15462 | var _a = RESERVED_NAMES_BY_FORMAT[format], forbiddenNames = _a.forbiddenNames, formatGlobals = _a.formatGlobals;
|
15463 | Object.assign(usedNames, forbiddenNames);
|
15464 | Object.assign(usedNames, formatGlobals);
|
15465 | addUsedGlobalNames(usedNames, modules);
|
15466 | deconflictTopLevelVariables(usedNames, modules);
|
15467 | DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
|
15468 | for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
|
15469 | var module = modules_1[_i];
|
15470 | module.scope.deconflict(forbiddenNames);
|
15471 | }
|
15472 | }
|
15473 | function addUsedGlobalNames(usedNames, modules) {
|
15474 | var accessedGlobals = Object.assign.apply(Object, [{}].concat(modules.map(function (module) { return module.scope.accessedOutsideVariables; })));
|
15475 | for (var _i = 0, _a = Object.keys(accessedGlobals); _i < _a.length; _i++) {
|
15476 | var name = _a[_i];
|
15477 | var variable = accessedGlobals[name];
|
15478 | if (variable.included) {
|
15479 | usedNames[name] = true;
|
15480 | }
|
15481 | }
|
15482 | }
|
15483 | function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
|
15484 | for (var _i = 0, _a = Array.from(imports); _i < _a.length; _i++) {
|
15485 | var variable = _a[_i];
|
15486 | var module = variable.module;
|
15487 | var name = variable.name;
|
15488 | var proposedName = void 0;
|
15489 | if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
|
15490 | if (name === 'default' && interop && module.exportsNamespace) {
|
15491 | proposedName = module.variableName + '__default';
|
15492 | }
|
15493 | else {
|
15494 | proposedName = module.variableName;
|
15495 | }
|
15496 | }
|
15497 | else {
|
15498 | proposedName = name;
|
15499 | }
|
15500 | variable.setRenderNames(null, getSafeName(proposedName, usedNames));
|
15501 | }
|
15502 | }
|
15503 | function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
|
15504 | for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
|
15505 | var chunkOrExternalModule = dependencies_1[_i];
|
15506 | chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
|
15507 | }
|
15508 | for (var _a = 0, _b = Array.from(imports); _a < _b.length; _a++) {
|
15509 | var variable = _b[_a];
|
15510 | var module = variable.module;
|
15511 | if (module instanceof ExternalModule) {
|
15512 | var name = variable.name;
|
15513 | if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
|
15514 | variable.setRenderNames(null, module.variableName + '__default');
|
15515 | }
|
15516 | else if (name === '*' || name === 'default') {
|
15517 | variable.setRenderNames(null, module.variableName);
|
15518 | }
|
15519 | else {
|
15520 | variable.setRenderNames(module.variableName, null);
|
15521 | }
|
15522 | }
|
15523 | else {
|
15524 | var chunk = module.chunk;
|
15525 | if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
|
15526 | variable.setRenderNames(null, chunk.variableName);
|
15527 | }
|
15528 | else {
|
15529 | variable.setRenderNames(chunk.variableName, module.chunk.getVariableExportName(variable));
|
15530 | }
|
15531 | }
|
15532 | }
|
15533 | }
|
15534 | function deconflictTopLevelVariables(usedNames, modules) {
|
15535 | for (var _i = 0, modules_2 = modules; _i < modules_2.length; _i++) {
|
15536 | var module = modules_2[_i];
|
15537 | var moduleVariables = module.scope.variables;
|
15538 | for (var _a = 0, _b = Object.keys(moduleVariables); _a < _b.length; _a++) {
|
15539 | var name = _b[_a];
|
15540 | var variable = moduleVariables[name];
|
15541 | if (variable.included &&
|
15542 | // this will only happen for exports in some formats
|
15543 | !(variable.renderBaseName ||
|
15544 | (variable instanceof ExportDefaultVariable && variable.referencesOriginal()))) {
|
15545 | variable.setRenderNames(null, getSafeName(variable.name, usedNames));
|
15546 | }
|
15547 | }
|
15548 | var namespace = module.getOrCreateNamespace();
|
15549 | if (namespace.included) {
|
15550 | namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
|
15551 | }
|
15552 | }
|
15553 | }
|
15554 |
|
15555 | var compareExecIndex = function (unitA, unitB) {
|
15556 | return unitA.execIndex > unitB.execIndex ? 1 : -1;
|
15557 | };
|
15558 | function sortByExecutionOrder(units) {
|
15559 | units.sort(compareExecIndex);
|
15560 | }
|
15561 | function analyseModuleExecution(entryModules) {
|
15562 | var nextExecIndex = 0;
|
15563 | var inStaticGraph = true;
|
15564 | var cyclePaths = [];
|
15565 | var analysedModules = {};
|
15566 | var orderedModules = [];
|
15567 | var dynamicImports = [];
|
15568 | var parents = {};
|
15569 | var analyseModule = function (module) {
|
15570 | if (analysedModules[module.id])
|
15571 | return;
|
15572 | if (module instanceof ExternalModule) {
|
15573 | module.execIndex = nextExecIndex++;
|
15574 | analysedModules[module.id] = true;
|
15575 | return;
|
15576 | }
|
15577 | if (inStaticGraph) {
|
15578 | module.isExecuted = true;
|
15579 | }
|
15580 | for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
|
15581 | var dependency = _a[_i];
|
15582 | if (dependency.id in parents) {
|
15583 | if (!analysedModules[dependency.id]) {
|
15584 | cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
|
15585 | }
|
15586 | continue;
|
15587 | }
|
15588 | parents[dependency.id] = module.id;
|
15589 | analyseModule(dependency);
|
15590 | }
|
15591 | for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
|
15592 | var resolution = _c[_b].resolution;
|
15593 | if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
|
15594 | dynamicImports.push(resolution);
|
15595 | }
|
15596 | }
|
15597 | module.execIndex = nextExecIndex++;
|
15598 | analysedModules[module.id] = true;
|
15599 | orderedModules.push(module);
|
15600 | };
|
15601 | for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
|
15602 | var curEntry = entryModules_1[_i];
|
15603 | curEntry.isEntryPoint = true;
|
15604 | if (!parents[curEntry.id]) {
|
15605 | parents[curEntry.id] = null;
|
15606 | analyseModule(curEntry);
|
15607 | }
|
15608 | }
|
15609 | inStaticGraph = false;
|
15610 | for (var _a = 0, dynamicImports_1 = dynamicImports; _a < dynamicImports_1.length; _a++) {
|
15611 | var curEntry = dynamicImports_1[_a];
|
15612 | if (!parents[curEntry.id]) {
|
15613 | parents[curEntry.id] = null;
|
15614 | analyseModule(curEntry);
|
15615 | }
|
15616 | }
|
15617 | return { orderedModules: orderedModules, cyclePaths: cyclePaths };
|
15618 | }
|
15619 | function getCyclePath(id, parentId, parents) {
|
15620 | var path = [relativeId(id)];
|
15621 | var curId = parentId;
|
15622 | while (curId !== id) {
|
15623 | path.push(relativeId(curId));
|
15624 | curId = parents[curId];
|
15625 | if (!curId)
|
15626 | break;
|
15627 | }
|
15628 | path.push(path[0]);
|
15629 | path.reverse();
|
15630 | return path;
|
15631 | }
|
15632 |
|
15633 | function guessIndentString(code) {
|
15634 | var lines = code.split('\n');
|
15635 | var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
|
15636 | var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
|
15637 | if (tabbed.length === 0 && spaced.length === 0) {
|
15638 | return null;
|
15639 | }
|
15640 | // More lines tabbed than spaced? Assume tabs, and
|
15641 | // default to tabs in the case of a tie (or nothing
|
15642 | // to go on)
|
15643 | if (tabbed.length >= spaced.length) {
|
15644 | return '\t';
|
15645 | }
|
15646 | // Otherwise, we need to guess the multiple
|
15647 | var min = spaced.reduce(function (previous, current) {
|
15648 | var numSpaces = /^ +/.exec(current)[0].length;
|
15649 | return Math.min(numSpaces, previous);
|
15650 | }, Infinity);
|
15651 | return new Array(min + 1).join(' ');
|
15652 | }
|
15653 | function getIndentString(modules, options) {
|
15654 | if (options.indent !== true)
|
15655 | return options.indent || '';
|
15656 | for (var i = 0; i < modules.length; i++) {
|
15657 | var indent = guessIndentString(modules[i].originalCode);
|
15658 | if (indent !== null)
|
15659 | return indent;
|
15660 | }
|
15661 | return '\t';
|
15662 | }
|
15663 |
|
15664 | function renderChunk(_a) {
|
15665 | var graph = _a.graph, chunk = _a.chunk, renderChunk = _a.renderChunk, code = _a.code, sourcemapChain = _a.sourcemapChain, options = _a.options;
|
15666 | var renderChunkReducer = function (code, result, plugin) {
|
15667 | if (result == null)
|
15668 | return code;
|
15669 | if (typeof result === 'string')
|
15670 | result = {
|
15671 | code: result,
|
15672 | map: undefined
|
15673 | };
|
15674 | var map = typeof result.map === 'string' ? JSON.parse(result.map) : result.map;
|
15675 | if (map && typeof map.mappings === 'string')
|
15676 | map.mappings = decode(map.mappings);
|
15677 | // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
|
15678 | if (map !== null)
|
15679 | sourcemapChain.push(map || { missing: true, plugin: plugin.name });
|
15680 | return result.code;
|
15681 | };
|
15682 | var inTransformBundle = false;
|
15683 | var inRenderChunk = true;
|
15684 | return graph.pluginDriver
|
15685 | .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
|
15686 | .then(function (code) {
|
15687 | inRenderChunk = false;
|
15688 | return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
|
15689 | })
|
15690 | .then(function (code) {
|
15691 | inTransformBundle = true;
|
15692 | return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
|
15693 | })
|
15694 | .catch(function (err) {
|
15695 | if (inRenderChunk)
|
15696 | throw err;
|
15697 | error(err, {
|
15698 | code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
|
15699 | message: "Error transforming " + ((inTransformBundle ? 'bundle' : 'chunk') +
|
15700 | (err.plugin ? " with '" + err.plugin + "' plugin" : '')) + ": " + err.message,
|
15701 | plugin: err.plugin
|
15702 | });
|
15703 | });
|
15704 | }
|
15705 |
|
15706 | function renderNamePattern(pattern, patternName, getReplacement) {
|
15707 | if (!isPlainName(pattern))
|
15708 | error({
|
15709 | code: 'INVALID_PATTERN',
|
15710 | message: "Invalid output pattern \"" + pattern + "\" for " + patternName + ", cannot be an absolute or relative URL or path."
|
15711 | });
|
15712 | return pattern.replace(/\[(\w+)\]/g, function (_match, type) {
|
15713 | var replacement = getReplacement(type);
|
15714 | if (replacement === undefined)
|
15715 | error({
|
15716 | code: 'INVALID_PATTERN_REPLACEMENT',
|
15717 | message: "\"" + type + "\" is not a valid substitution name in output option " + patternName + " pattern."
|
15718 | });
|
15719 | if (!isPlainName(replacement))
|
15720 | error({
|
15721 | code: 'INVALID_PATTERN_REPLACEMENT',
|
15722 | message: "Invalid replacement \"" + replacement + "\" for \"" + type + "\" in " + patternName + " pattern, must be a plain path name."
|
15723 | });
|
15724 | return replacement;
|
15725 | });
|
15726 | }
|
15727 | function makeUnique(name, existingNames) {
|
15728 | if (name in existingNames === false)
|
15729 | return name;
|
15730 | var ext = path.extname(name);
|
15731 | name = name.substr(0, name.length - ext.length);
|
15732 | var uniqueName, uniqueIndex = 1;
|
15733 | while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
|
15734 | ;
|
15735 | return uniqueName;
|
15736 | }
|
15737 |
|
15738 | function sanitizeFileName(name) {
|
15739 | return name.replace(/[\0]/g, '_');
|
15740 | }
|
15741 |
|
15742 | function getGlobalName(module, globals, graph, hasExports) {
|
15743 | var globalName;
|
15744 | if (typeof globals === 'function') {
|
15745 | globalName = globals(module.id);
|
15746 | }
|
15747 | else if (globals) {
|
15748 | globalName = globals[module.id];
|
15749 | }
|
15750 | if (globalName) {
|
15751 | return globalName;
|
15752 | }
|
15753 | if (hasExports) {
|
15754 | graph.warn({
|
15755 | code: 'MISSING_GLOBAL_NAME',
|
15756 | guess: module.variableName,
|
15757 | message: "No name was provided for external module '" + module.id + "' in output.globals \u2013 guessing '" + module.variableName + "'",
|
15758 | source: module.id
|
15759 | });
|
15760 | return module.variableName;
|
15761 | }
|
15762 | }
|
15763 | function isChunkRendered(chunk) {
|
15764 | return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
|
15765 | }
|
15766 | var Chunk$1 = /** @class */ (function () {
|
15767 | function Chunk(graph, orderedModules) {
|
15768 | this.entryModules = [];
|
15769 | this.exportMode = 'named';
|
15770 | this.facadeModule = null;
|
15771 | this.hasDynamicImport = false;
|
15772 | this.id = undefined;
|
15773 | this.indentString = undefined;
|
15774 | this.manualChunkAlias = null;
|
15775 | this.usedModules = undefined;
|
15776 | this.dependencies = undefined;
|
15777 | this.dynamicDependencies = undefined;
|
15778 | this.exportNames = Object.create(null);
|
15779 | this.exports = new Set();
|
15780 | this.imports = new Set();
|
15781 | this.needsExportsShim = false;
|
15782 | this.renderedDeclarations = undefined;
|
15783 | this.renderedHash = undefined;
|
15784 | this.renderedModuleSources = undefined;
|
15785 | this.renderedSource = null;
|
15786 | this.renderedSourceLength = undefined;
|
15787 | this.sortedExportNames = null;
|
15788 | this.graph = graph;
|
15789 | this.orderedModules = orderedModules;
|
15790 | this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
|
15791 | this.isEmpty = true;
|
15792 | for (var _i = 0, orderedModules_1 = orderedModules; _i < orderedModules_1.length; _i++) {
|
15793 | var module = orderedModules_1[_i];
|
15794 | if (this.isEmpty && module.isIncluded()) {
|
15795 | this.isEmpty = false;
|
15796 | }
|
15797 | if (module.manualChunkAlias) {
|
15798 | this.manualChunkAlias = module.manualChunkAlias;
|
15799 | }
|
15800 | module.chunk = this;
|
15801 | if (module.isEntryPoint ||
|
15802 | module.dynamicallyImportedBy.some(function (module) { return orderedModules.indexOf(module) === -1; })) {
|
15803 | this.entryModules.push(module);
|
15804 | }
|
15805 | }
|
15806 | var entryModule = this.entryModules[0];
|
15807 | if (entryModule) {
|
15808 | this.variableName = makeLegal(path.basename(entryModule.chunkAlias || entryModule.manualChunkAlias || getAliasName(entryModule.id)));
|
15809 | }
|
15810 | else {
|
15811 | this.variableName = '__chunk_' + ++graph.curChunkIndex;
|
15812 | }
|
15813 | }
|
15814 | Chunk.prototype.generateEntryExportsOrMarkAsTainted = function () {
|
15815 | var _this = this;
|
15816 | var exportVariableMaps = this.entryModules.map(function (module) { return ({
|
15817 | map: _this.getVariableExportNamesForModule(module),
|
15818 | module: module
|
15819 | }); });
|
15820 | for (var _i = 0, exportVariableMaps_1 = exportVariableMaps; _i < exportVariableMaps_1.length; _i++) {
|
15821 | var map = exportVariableMaps_1[_i].map;
|
15822 | for (var _a = 0, _b = Array.from(map.keys()); _a < _b.length; _a++) {
|
15823 | var exposedVariable = _b[_a];
|
15824 | this.exports.add(exposedVariable);
|
15825 | }
|
15826 | }
|
15827 | var exposedVariables = Array.from(this.exports);
|
15828 | checkNextEntryModule: for (var _c = 0, exportVariableMaps_2 = exportVariableMaps; _c < exportVariableMaps_2.length; _c++) {
|
15829 | var _d = exportVariableMaps_2[_c], map = _d.map, module = _d.module;
|
15830 | if (!this.graph.preserveModules) {
|
15831 | if (this.manualChunkAlias &&
|
15832 | module.chunkAlias &&
|
15833 | this.manualChunkAlias !== module.chunkAlias) {
|
15834 | continue checkNextEntryModule;
|
15835 | }
|
15836 | for (var _e = 0, exposedVariables_1 = exposedVariables; _e < exposedVariables_1.length; _e++) {
|
15837 | var exposedVariable = exposedVariables_1[_e];
|
15838 | if (!map.has(exposedVariable)) {
|
15839 | continue checkNextEntryModule;
|
15840 | }
|
15841 | }
|
15842 | }
|
15843 | this.facadeModule = module;
|
15844 | for (var _f = 0, _g = Array.from(map); _f < _g.length; _f++) {
|
15845 | var _h = _g[_f], variable = _h[0], exportNames = _h[1];
|
15846 | for (var _j = 0, exportNames_1 = exportNames; _j < exportNames_1.length; _j++) {
|
15847 | var exportName = exportNames_1[_j];
|
15848 | this.exportNames[exportName] = variable;
|
15849 | }
|
15850 | }
|
15851 | return;
|
15852 | }
|
15853 | };
|
15854 | Chunk.prototype.generateId = function (pattern, patternName, addons, options, existingNames) {
|
15855 | var _this = this;
|
15856 | this.id = makeUnique(renderNamePattern(pattern, patternName, function (type) {
|
15857 | switch (type) {
|
15858 | case 'format':
|
15859 | return options.format === 'es' ? 'esm' : options.format;
|
15860 | case 'hash':
|
15861 | return _this.computeContentHashWithDependencies(addons, options);
|
15862 | case 'name':
|
15863 | return _this.getChunkName();
|
15864 | }
|
15865 | }), existingNames);
|
15866 | };
|
15867 | Chunk.prototype.generateIdPreserveModules = function (preserveModulesRelativeDir, existingNames) {
|
15868 | var sanitizedId = sanitizeFileName(this.orderedModules[0].id);
|
15869 | this.id = makeUnique(normalize(isAbsolute(this.orderedModules[0].id)
|
15870 | ? path.relative(preserveModulesRelativeDir, sanitizedId)
|
15871 | : '_virtual/' + path.basename(sanitizedId)), existingNames);
|
15872 | };
|
15873 | Chunk.prototype.generateInternalExports = function (options) {
|
15874 | if (this.facadeModule !== null)
|
15875 | return;
|
15876 | var mangle = options.format === 'system' || options.format === 'es' || options.compact;
|
15877 | var i = 0, safeExportName;
|
15878 | this.exportNames = Object.create(null);
|
15879 | this.sortedExportNames = null;
|
15880 | var exportedVariables = Array.from(this.exports);
|
15881 | if (mangle) {
|
15882 | for (var _i = 0, exportedVariables_1 = exportedVariables; _i < exportedVariables_1.length; _i++) {
|
15883 | var variable = exportedVariables_1[_i];
|
15884 | do {
|
15885 | safeExportName = toBase64(++i);
|
15886 | // skip past leading number identifiers
|
15887 | if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
|
15888 | i += 9 * Math.pow(64, (safeExportName.length - 1));
|
15889 | safeExportName = toBase64(i);
|
15890 | }
|
15891 | } while (RESERVED_NAMES[safeExportName]);
|
15892 | this.exportNames[safeExportName] = variable;
|
15893 | }
|
15894 | }
|
15895 | else {
|
15896 | for (var _a = 0, exportedVariables_2 = exportedVariables; _a < exportedVariables_2.length; _a++) {
|
15897 | var variable = exportedVariables_2[_a];
|
15898 | i = 0;
|
15899 | safeExportName = variable.name;
|
15900 | while (this.exportNames[safeExportName]) {
|
15901 | safeExportName = variable.name + '$' + ++i;
|
15902 | }
|
15903 | this.exportNames[safeExportName] = variable;
|
15904 | }
|
15905 | }
|
15906 | };
|
15907 | Chunk.prototype.getChunkName = function () {
|
15908 | return this.chunkName || (this.chunkName = this.computeChunkName());
|
15909 | };
|
15910 | Chunk.prototype.getDynamicImportIds = function () {
|
15911 | return this.dynamicDependencies.map(function (chunk) { return chunk.id; }).filter(Boolean);
|
15912 | };
|
15913 | Chunk.prototype.getExportNames = function () {
|
15914 | return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
|
15915 | };
|
15916 | Chunk.prototype.getImportIds = function () {
|
15917 | return this.dependencies.map(function (chunk) { return chunk.id; });
|
15918 | };
|
15919 | Chunk.prototype.getRenderedHash = function () {
|
15920 | var _this = this;
|
15921 | if (this.renderedHash)
|
15922 | return this.renderedHash;
|
15923 | if (!this.renderedSource)
|
15924 | return '';
|
15925 | var hash = _256();
|
15926 | hash.update(this.renderedSource.toString());
|
15927 | hash.update(this.getExportNames()
|
15928 | .map(function (exportName) {
|
15929 | var variable = _this.exportNames[exportName];
|
15930 | return relativeId(variable.module.id).replace(/\\/g, '/') + ":" + variable.name + ":" + exportName;
|
15931 | })
|
15932 | .join(','));
|
15933 | return (this.renderedHash = hash.digest('hex'));
|
15934 | };
|
15935 | Chunk.prototype.getRenderedSourceLength = function () {
|
15936 | if (this.renderedSourceLength !== undefined)
|
15937 | return this.renderedSourceLength;
|
15938 | return (this.renderedSourceLength = this.renderedSource.length());
|
15939 | };
|
15940 | Chunk.prototype.getVariableExportName = function (variable) {
|
15941 | if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
|
15942 | return '*';
|
15943 | }
|
15944 | for (var _i = 0, _a = Object.keys(this.exportNames); _i < _a.length; _i++) {
|
15945 | var exportName = _a[_i];
|
15946 | if (this.exportNames[exportName] === variable)
|
15947 | return exportName;
|
15948 | }
|
15949 | };
|
15950 | Chunk.prototype.link = function () {
|
15951 | var dependencies = new Set();
|
15952 | var dynamicDependencies = new Set();
|
15953 | for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
|
15954 | var module = _a[_i];
|
15955 | this.addChunksFromDependencies(module.dependencies, dependencies);
|
15956 | this.addChunksFromDependencies(module.dynamicDependencies, dynamicDependencies);
|
15957 | this.setUpModuleImports(module);
|
15958 | }
|
15959 | this.dependencies = Array.from(dependencies);
|
15960 | this.dynamicDependencies = Array.from(dynamicDependencies);
|
15961 | };
|
15962 | /*
|
15963 | * Performs a full merge of another chunk into this chunk
|
15964 | * chunkList allows updating references in other chunks for the merged chunk to this chunk
|
15965 | * A new facade will be added to chunkList if tainting exports of either as an entry point
|
15966 | */
|
15967 | Chunk.prototype.merge = function (chunk, chunkList, options, inputBase) {
|
15968 | var _this = this;
|
15969 | if (this.facadeModule !== null || chunk.facadeModule !== null)
|
15970 | throw new Error('Internal error: Code splitting chunk merges not supported for facades');
|
15971 | for (var _i = 0, _a = chunk.orderedModules; _i < _a.length; _i++) {
|
15972 | var module = _a[_i];
|
15973 | module.chunk = this;
|
15974 | this.orderedModules.push(module);
|
15975 | }
|
15976 | for (var _b = 0, _c = Array.from(chunk.imports); _b < _c.length; _b++) {
|
15977 | var variable = _c[_b];
|
15978 | if (!this.imports.has(variable) && variable.module.chunk !== this) {
|
15979 | this.imports.add(variable);
|
15980 | }
|
15981 | }
|
15982 | // NB detect when exported variables are orphaned by the merge itself
|
15983 | // (involves reverse tracing dependents)
|
15984 | for (var _d = 0, _e = Array.from(chunk.exports); _d < _e.length; _d++) {
|
15985 | var variable = _e[_d];
|
15986 | if (!this.exports.has(variable)) {
|
15987 | this.exports.add(variable);
|
15988 | }
|
15989 | }
|
15990 | var thisOldExportNames = this.exportNames;
|
15991 | // regenerate internal names
|
15992 | this.generateInternalExports(options);
|
15993 | var updateRenderedDeclaration = function (dep, oldExportNames) {
|
15994 | if (dep.imports) {
|
15995 | for (var _i = 0, _a = dep.imports; _i < _a.length; _i++) {
|
15996 | var impt = _a[_i];
|
15997 | impt.imported = _this.getVariableExportName(oldExportNames[impt.imported]);
|
15998 | }
|
15999 | }
|
16000 | if (dep.reexports) {
|
16001 | for (var _b = 0, _c = dep.reexports; _b < _c.length; _b++) {
|
16002 | var reexport = _c[_b];
|
16003 | reexport.imported = _this.getVariableExportName(oldExportNames[reexport.imported]);
|
16004 | }
|
16005 | }
|
16006 | };
|
16007 | var mergeRenderedDeclaration = function (into, from) {
|
16008 | if (from.imports) {
|
16009 | if (!into.imports) {
|
16010 | into.imports = from.imports;
|
16011 | }
|
16012 | else {
|
16013 | into.imports = into.imports.concat(from.imports);
|
16014 | }
|
16015 | }
|
16016 | if (from.reexports) {
|
16017 | if (!into.reexports) {
|
16018 | into.reexports = from.reexports;
|
16019 | }
|
16020 | else {
|
16021 | into.reexports = into.reexports.concat(from.reexports);
|
16022 | }
|
16023 | }
|
16024 | if (!into.exportsNames && from.exportsNames) {
|
16025 | into.exportsNames = true;
|
16026 | }
|
16027 | if (!into.exportsDefault && from.exportsDefault) {
|
16028 | into.exportsDefault = true;
|
16029 | }
|
16030 | into.name = _this.variableName;
|
16031 | };
|
16032 | // go through the other chunks and update their dependencies
|
16033 | // also update their import and reexport names in the process
|
16034 | for (var _f = 0, chunkList_1 = chunkList; _f < chunkList_1.length; _f++) {
|
16035 | var c = chunkList_1[_f];
|
16036 | var includedDeclaration = void 0;
|
16037 | for (var i = 0; i < c.dependencies.length; i++) {
|
16038 | var dep = c.dependencies[i];
|
16039 | if ((dep === chunk || dep === this) && includedDeclaration) {
|
16040 | var duplicateDeclaration = c.renderedDeclarations.dependencies[i];
|
16041 | updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
|
16042 | mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
|
16043 | c.renderedDeclarations.dependencies.splice(i, 1);
|
16044 | c.dependencies.splice(i--, 1);
|
16045 | }
|
16046 | else if (dep === chunk) {
|
16047 | c.dependencies[i] = this;
|
16048 | includedDeclaration = c.renderedDeclarations.dependencies[i];
|
16049 | updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
|
16050 | }
|
16051 | else if (dep === this) {
|
16052 | includedDeclaration = c.renderedDeclarations.dependencies[i];
|
16053 | updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
|
16054 | }
|
16055 | }
|
16056 | }
|
16057 | // re-render the merged chunk
|
16058 | this.preRender(options, inputBase);
|
16059 | };
|
16060 | // prerender allows chunk hashes and names to be generated before finalizing
|
16061 | Chunk.prototype.preRender = function (options, inputBase) {
|
16062 | timeStart('render modules', 3);
|
16063 | var magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
|
16064 | this.usedModules = [];
|
16065 | this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
|
16066 | var n = options.compact ? '' : '\n';
|
16067 | var _ = options.compact ? '' : ' ';
|
16068 | var renderOptions = {
|
16069 | compact: options.compact,
|
16070 | dynamicImportFunction: options.dynamicImportFunction,
|
16071 | format: options.format,
|
16072 | freeze: options.freeze !== false,
|
16073 | indent: this.indentString,
|
16074 | namespaceToStringTag: options.namespaceToStringTag === true,
|
16075 | varOrConst: options.preferConst ? 'const' : 'var'
|
16076 | };
|
16077 | // Make sure the direct dependencies of a chunk are present to maintain execution order
|
16078 | for (var _i = 0, _a = Array.from(this.imports); _i < _a.length; _i++) {
|
16079 | var module = _a[_i].module;
|
16080 | var chunkOrExternal = module instanceof Module ? module.chunk : module;
|
16081 | if (this.dependencies.indexOf(chunkOrExternal) === -1) {
|
16082 | this.dependencies.push(chunkOrExternal);
|
16083 | }
|
16084 | }
|
16085 | // for static and dynamic entry points, inline the execution list to avoid loading latency
|
16086 | if (!this.graph.preserveModules && this.facadeModule !== null) {
|
16087 | for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
|
16088 | var dep = _c[_b];
|
16089 | if (dep instanceof Chunk)
|
16090 | this.inlineChunkDependencies(dep, true);
|
16091 | }
|
16092 | }
|
16093 | // prune empty dependency chunks, inlining their side-effect dependencies
|
16094 | for (var i = 0; i < this.dependencies.length; i++) {
|
16095 | var dep = this.dependencies[i];
|
16096 | if (dep instanceof Chunk && dep.isEmpty) {
|
16097 | this.dependencies.splice(i--, 1);
|
16098 | this.inlineChunkDependencies(dep, false);
|
16099 | }
|
16100 | }
|
16101 | sortByExecutionOrder(this.dependencies);
|
16102 | this.setIdentifierRenderResolutions(options);
|
16103 | this.prepareDynamicImports();
|
16104 | var hoistedSource = '';
|
16105 | this.renderedModules = Object.create(null);
|
16106 | this.renderedModuleSources = [];
|
16107 | for (var i = 0; i < this.orderedModules.length; i++) {
|
16108 | var module = this.orderedModules[i];
|
16109 | var source = module.render(renderOptions);
|
16110 | source.trim();
|
16111 | if (options.compact && source.lastLine().indexOf('//') !== -1)
|
16112 | source.append('\n');
|
16113 | this.renderedModuleSources.push(source);
|
16114 | var _d = module.getRenderedExports(), renderedExports = _d.renderedExports, removedExports = _d.removedExports;
|
16115 | this.renderedModules[module.id] = {
|
16116 | originalLength: module.originalCode.length,
|
16117 | removedExports: removedExports,
|
16118 | renderedExports: renderedExports,
|
16119 | renderedLength: source.length()
|
16120 | };
|
16121 | var namespace = module.getOrCreateNamespace();
|
16122 | if (namespace.included || !source.isEmpty()) {
|
16123 | magicString.addSource(source);
|
16124 | this.usedModules.push(module);
|
16125 | if (namespace.included && !this.graph.preserveModules) {
|
16126 | var rendered = namespace.renderBlock(renderOptions);
|
16127 | if (namespace.renderFirst())
|
16128 | hoistedSource += n + rendered;
|
16129 | else
|
16130 | magicString.addSource(new MagicString(rendered));
|
16131 | }
|
16132 | }
|
16133 | }
|
16134 | if (hoistedSource)
|
16135 | magicString.prepend(hoistedSource + n + n);
|
16136 | if (this.needsExportsShim) {
|
16137 | magicString.prepend("" + n + renderOptions.varOrConst + " " + MISSING_EXPORT_SHIM_VARIABLE + _ + "=" + _ + "void 0;" + n + n);
|
16138 | }
|
16139 | if (options.compact) {
|
16140 | this.renderedSource = magicString;
|
16141 | }
|
16142 | else {
|
16143 | this.renderedSource = magicString.trim();
|
16144 | }
|
16145 | this.renderedSourceLength = undefined;
|
16146 | this.renderedHash = undefined;
|
16147 | if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
|
16148 | this.graph.warn({
|
16149 | code: 'EMPTY_BUNDLE',
|
16150 | message: 'Generated an empty bundle'
|
16151 | });
|
16152 | }
|
16153 | this.setExternalRenderPaths(options, inputBase);
|
16154 | this.renderedDeclarations = {
|
16155 | dependencies: this.getChunkDependencyDeclarations(options),
|
16156 | exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
|
16157 | };
|
16158 | timeEnd('render modules', 3);
|
16159 | };
|
16160 | Chunk.prototype.render = function (options, addons, outputChunk) {
|
16161 | var _this = this;
|
16162 | timeStart('render format', 3);
|
16163 | if (!this.renderedSource)
|
16164 | throw new Error('Internal error: Chunk render called before preRender');
|
16165 | var finalise = finalisers[options.format];
|
16166 | if (!finalise) {
|
16167 | error({
|
16168 | code: 'INVALID_OPTION',
|
16169 | message: "Invalid format: " + options.format + " - valid options are " + Object.keys(finalisers).join(', ') + "."
|
16170 | });
|
16171 | }
|
16172 | if (options.dynamicImportFunction && options.format !== 'es') {
|
16173 | this.graph.warn({
|
16174 | code: 'INVALID_OPTION',
|
16175 | message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
|
16176 | });
|
16177 | }
|
16178 | // populate ids in the rendered declarations only here
|
16179 | // as chunk ids known only after prerender
|
16180 | for (var i = 0; i < this.dependencies.length; i++) {
|
16181 | var dep = this.dependencies[i];
|
16182 | if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
|
16183 | continue;
|
16184 | var renderedDependency = this.renderedDeclarations.dependencies[i];
|
16185 | var depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
|
16186 | var relPath = this.id ? normalize(path.relative(path.dirname(this.id), depId)) : depId;
|
16187 | if (!relPath.startsWith('../'))
|
16188 | relPath = './' + relPath;
|
16189 | if (dep instanceof Chunk)
|
16190 | renderedDependency.namedExportsMode = dep.exportMode !== 'default';
|
16191 | renderedDependency.id = relPath;
|
16192 | }
|
16193 | this.finaliseDynamicImports(options.format);
|
16194 | var needsAmdModule = this.finaliseImportMetas(options);
|
16195 | var hasExports = this.renderedDeclarations.exports.length !== 0 ||
|
16196 | this.renderedDeclarations.dependencies.some(function (dep) { return dep.reexports && dep.reexports.length !== 0; });
|
16197 | var usesTopLevelAwait = this.orderedModules.some(function (module) { return module.usesTopLevelAwait; });
|
16198 | if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
|
16199 | error({
|
16200 | code: 'INVALID_TLA_FORMAT',
|
16201 | message: "Module format " + options.format + " does not support top-level await. Use the \"es\" or \"system\" output formats rather."
|
16202 | });
|
16203 | }
|
16204 | var magicString = finalise(this.renderedSource, {
|
16205 | dependencies: this.renderedDeclarations.dependencies,
|
16206 | dynamicImport: this.hasDynamicImport,
|
16207 | exports: this.renderedDeclarations.exports,
|
16208 | hasExports: hasExports,
|
16209 | indentString: this.indentString,
|
16210 | intro: addons.intro,
|
16211 | isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
|
16212 | namedExportsMode: this.exportMode !== 'default',
|
16213 | needsAmdModule: needsAmdModule,
|
16214 | outro: addons.outro,
|
16215 | usesTopLevelAwait: usesTopLevelAwait,
|
16216 | varOrConst: options.preferConst ? 'const' : 'var',
|
16217 | warn: this.graph.warn.bind(this.graph)
|
16218 | }, options);
|
16219 | if (addons.banner)
|
16220 | magicString.prepend(addons.banner);
|
16221 | if (addons.footer)
|
16222 | magicString.append(addons.footer);
|
16223 | var prevCode = magicString.toString();
|
16224 | timeEnd('render format', 3);
|
16225 | var map = null;
|
16226 | var chunkSourcemapChain = [];
|
16227 | return renderChunk({
|
16228 | chunk: this,
|
16229 | code: prevCode,
|
16230 | graph: this.graph,
|
16231 | options: options,
|
16232 | renderChunk: outputChunk,
|
16233 | sourcemapChain: chunkSourcemapChain
|
16234 | }).then(function (code) {
|
16235 | if (options.sourcemap) {
|
16236 | timeStart('sourcemap', 3);
|
16237 | var file = void 0;
|
16238 | if (options.file)
|
16239 | file = path.resolve(options.sourcemapFile || options.file);
|
16240 | else if (options.dir)
|
16241 | file = path.resolve(options.dir, _this.id);
|
16242 | else
|
16243 | file = path.resolve(_this.id);
|
16244 | if (_this.graph.pluginDriver.hasLoadersOrTransforms) {
|
16245 | var decodedMap = magicString.generateDecodedMap({});
|
16246 | map = collapseSourcemaps(_this, file, decodedMap, _this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
|
16247 | }
|
16248 | else {
|
16249 | map = magicString.generateMap({ file: file, includeContent: !options.sourcemapExcludeSources });
|
16250 | }
|
16251 | map.sources = map.sources.map(function (sourcePath) {
|
16252 | return normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath);
|
16253 | });
|
16254 | timeEnd('sourcemap', 3);
|
16255 | }
|
16256 | if (options.compact !== true && code[code.length - 1] !== '\n')
|
16257 | code += '\n';
|
16258 | return { code: code, map: map };
|
16259 | });
|
16260 | };
|
16261 | Chunk.prototype.turnIntoFacade = function (facadedModule) {
|
16262 | this.dependencies = [facadedModule.chunk];
|
16263 | this.dynamicDependencies = [];
|
16264 | this.facadeModule = facadedModule;
|
16265 | facadedModule.facadeChunk = this;
|
16266 | for (var _i = 0, _a = facadedModule.getAllExports(); _i < _a.length; _i++) {
|
16267 | var exportName = _a[_i];
|
16268 | var tracedVariable = facadedModule.getVariableForExportName(exportName);
|
16269 | this.exports.add(tracedVariable);
|
16270 | this.exportNames[exportName] = tracedVariable;
|
16271 | }
|
16272 | };
|
16273 | Chunk.prototype.visitDependencies = function (handleDependency) {
|
16274 | var toBeVisited = [this];
|
16275 | var visited = new Set();
|
16276 | for (var _i = 0, toBeVisited_1 = toBeVisited; _i < toBeVisited_1.length; _i++) {
|
16277 | var current = toBeVisited_1[_i];
|
16278 | handleDependency(current);
|
16279 | if (current instanceof ExternalModule)
|
16280 | continue;
|
16281 | for (var _a = 0, _b = current.dependencies.concat(current.dynamicDependencies); _a < _b.length; _a++) {
|
16282 | var dependency = _b[_a];
|
16283 | if (!visited.has(dependency)) {
|
16284 | visited.add(dependency);
|
16285 | toBeVisited.push(dependency);
|
16286 | }
|
16287 | }
|
16288 | }
|
16289 | };
|
16290 | Chunk.prototype.visitStaticDependenciesUntilCondition = function (isConditionSatisfied) {
|
16291 | var seen = new Set();
|
16292 | function visitDep(dep) {
|
16293 | if (seen.has(dep))
|
16294 | return;
|
16295 | seen.add(dep);
|
16296 | if (dep instanceof Chunk) {
|
16297 | for (var _i = 0, _a = dep.dependencies; _i < _a.length; _i++) {
|
16298 | var subDep = _a[_i];
|
16299 | if (visitDep(subDep))
|
16300 | return true;
|
16301 | }
|
16302 | }
|
16303 | return isConditionSatisfied(dep) === true;
|
16304 | }
|
16305 | return visitDep(this);
|
16306 | };
|
16307 | Chunk.prototype.addChunksFromDependencies = function (moduleDependencies, chunkDependencies) {
|
16308 | for (var _i = 0, moduleDependencies_1 = moduleDependencies; _i < moduleDependencies_1.length; _i++) {
|
16309 | var depModule = moduleDependencies_1[_i];
|
16310 | if (depModule.chunk === this) {
|
16311 | continue;
|
16312 | }
|
16313 | var dependency = void 0;
|
16314 | if (depModule instanceof Module) {
|
16315 | dependency = depModule.chunk;
|
16316 | }
|
16317 | else {
|
16318 | if (!depModule.used && this.graph.isPureExternalModule(depModule.id)) {
|
16319 | continue;
|
16320 | }
|
16321 | dependency = depModule;
|
16322 | }
|
16323 | chunkDependencies.add(dependency);
|
16324 | }
|
16325 | };
|
16326 | Chunk.prototype.computeChunkName = function () {
|
16327 | if (this.manualChunkAlias) {
|
16328 | return sanitizeFileName(this.manualChunkAlias);
|
16329 | }
|
16330 | if (this.facadeModule !== null) {
|
16331 | return sanitizeFileName(this.facadeModule.chunkAlias || getAliasName(this.facadeModule.id));
|
16332 | }
|
16333 | for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
|
16334 | var module = _a[_i];
|
16335 | if (module.chunkAlias)
|
16336 | return sanitizeFileName(module.chunkAlias);
|
16337 | }
|
16338 | return 'chunk';
|
16339 | };
|
16340 | Chunk.prototype.computeContentHashWithDependencies = function (addons, options) {
|
16341 | var hash = _256();
|
16342 | hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(function (addon) { return addon || ''; }).join(':'));
|
16343 | hash.update(options.format);
|
16344 | this.visitDependencies(function (dep) {
|
16345 | if (dep instanceof ExternalModule)
|
16346 | hash.update(':' + dep.renderPath);
|
16347 | else
|
16348 | hash.update(dep.getRenderedHash());
|
16349 | });
|
16350 | return hash.digest('hex').substr(0, 8);
|
16351 | };
|
16352 | Chunk.prototype.finaliseDynamicImports = function (format) {
|
16353 | for (var i = 0; i < this.orderedModules.length; i++) {
|
16354 | var module = this.orderedModules[i];
|
16355 | var code = this.renderedModuleSources[i];
|
16356 | for (var _i = 0, _a = module.dynamicImports; _i < _a.length; _i++) {
|
16357 | var _b = _a[_i], node = _b.node, resolution = _b.resolution;
|
16358 | if (!resolution)
|
16359 | continue;
|
16360 | if (resolution instanceof Module) {
|
16361 | if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
|
16362 | var resolutionChunk = resolution.facadeChunk || resolution.chunk;
|
16363 | var relPath = normalize(path.relative(path.dirname(this.id), resolutionChunk.id));
|
16364 | if (!relPath.startsWith('../'))
|
16365 | relPath = './' + relPath;
|
16366 | node.renderFinalResolution(code, "'" + relPath + "'", format);
|
16367 | }
|
16368 | }
|
16369 | else if (resolution instanceof ExternalModule) {
|
16370 | var resolutionId = resolution.id;
|
16371 | if (resolution.renormalizeRenderPath) {
|
16372 | resolutionId = normalize(path.relative(path.dirname(this.id), resolution.renderPath));
|
16373 | if (!resolutionId.startsWith('../'))
|
16374 | resolutionId = './' + resolutionId;
|
16375 | }
|
16376 | node.renderFinalResolution(code, "'" + resolutionId + "'", format);
|
16377 | }
|
16378 | else {
|
16379 | node.renderFinalResolution(code, resolution, format);
|
16380 | }
|
16381 | }
|
16382 | }
|
16383 | };
|
16384 | Chunk.prototype.finaliseImportMetas = function (options) {
|
16385 | var needsAmdModule = false;
|
16386 | for (var i = 0; i < this.orderedModules.length; i++) {
|
16387 | var module = this.orderedModules[i];
|
16388 | var code = this.renderedModuleSources[i];
|
16389 | for (var _i = 0, _a = module.importMetas; _i < _a.length; _i++) {
|
16390 | var importMeta = _a[_i];
|
16391 | if (importMeta.renderFinalMechanism(code, this.id, options.format, this.graph.pluginDriver)) {
|
16392 | needsAmdModule = true;
|
16393 | }
|
16394 | }
|
16395 | }
|
16396 | return needsAmdModule;
|
16397 | };
|
16398 | Chunk.prototype.getChunkDependencyDeclarations = function (options) {
|
16399 | var reexportDeclarations = new Map();
|
16400 | for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
|
16401 | var exportName = _a[_i];
|
16402 | var exportModule = void 0;
|
16403 | var importName = void 0;
|
16404 | var needsLiveBinding = false;
|
16405 | if (exportName[0] === '*') {
|
16406 | exportModule = this.graph.moduleById.get(exportName.substr(1));
|
16407 | importName = exportName = '*';
|
16408 | }
|
16409 | else {
|
16410 | var variable = this.exportNames[exportName];
|
16411 | var module = variable.module;
|
16412 | // skip local exports
|
16413 | if (!module || module.chunk === this)
|
16414 | continue;
|
16415 | if (module instanceof Module) {
|
16416 | exportModule = module.chunk;
|
16417 | importName = module.chunk.getVariableExportName(variable);
|
16418 | needsLiveBinding = variable.isReassigned;
|
16419 | }
|
16420 | else {
|
16421 | exportModule = module;
|
16422 | importName = variable.name;
|
16423 | needsLiveBinding = true;
|
16424 | }
|
16425 | }
|
16426 | var exportDeclaration = reexportDeclarations.get(exportModule);
|
16427 | if (!exportDeclaration)
|
16428 | reexportDeclarations.set(exportModule, (exportDeclaration = []));
|
16429 | exportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding: needsLiveBinding });
|
16430 | }
|
16431 | var importsAsArray = Array.from(this.imports);
|
16432 | var renderedImports = new Set();
|
16433 | var dependencies = [];
|
16434 | for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
|
16435 | var dep = _c[_b];
|
16436 | var imports = [];
|
16437 | for (var _d = 0, importsAsArray_1 = importsAsArray; _d < importsAsArray_1.length; _d++) {
|
16438 | var variable = importsAsArray_1[_d];
|
16439 | var renderedVariable = variable instanceof ExportDefaultVariable && variable.referencesOriginal()
|
16440 | ? variable.getOriginalVariable()
|
16441 | : variable;
|
16442 | if ((variable.module instanceof Module
|
16443 | ? variable.module.chunk === dep
|
16444 | : variable.module === dep) &&
|
16445 | !renderedImports.has(renderedVariable)) {
|
16446 | renderedImports.add(renderedVariable);
|
16447 | var local = variable.getName();
|
16448 | var imported = variable.module instanceof ExternalModule
|
16449 | ? variable.name
|
16450 | : variable.module.chunk.getVariableExportName(variable);
|
16451 | imports.push({ local: local, imported: imported });
|
16452 | }
|
16453 | }
|
16454 | var reexports = reexportDeclarations.get(dep);
|
16455 | var exportsNames = void 0, exportsDefault = void 0;
|
16456 | var namedExportsMode = true;
|
16457 | if (dep instanceof ExternalModule) {
|
16458 | exportsNames = dep.exportsNames || dep.exportsNamespace;
|
16459 | exportsDefault = 'default' in dep.declarations;
|
16460 | }
|
16461 | else {
|
16462 | exportsNames = true;
|
16463 | // we don't want any interop patterns to trigger
|
16464 | exportsDefault = false;
|
16465 | namedExportsMode = dep.exportMode !== 'default';
|
16466 | }
|
16467 | var id = void 0;
|
16468 | var globalName = void 0;
|
16469 | if (dep instanceof ExternalModule) {
|
16470 | id = dep.renderPath;
|
16471 | if (options.format === 'umd' || options.format === 'iife') {
|
16472 | globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
|
16473 | }
|
16474 | }
|
16475 | dependencies.push({
|
16476 | exportsDefault: exportsDefault,
|
16477 | exportsNames: exportsNames,
|
16478 | globalName: globalName,
|
16479 | id: id,
|
16480 | imports: imports.length > 0 ? imports : null,
|
16481 | isChunk: !dep.isExternal,
|
16482 | name: dep.variableName,
|
16483 | namedExportsMode: namedExportsMode,
|
16484 | reexports: reexports
|
16485 | });
|
16486 | }
|
16487 | return dependencies;
|
16488 | };
|
16489 | Chunk.prototype.getChunkExportDeclarations = function () {
|
16490 | var exports = [];
|
16491 | var _loop_1 = function (exportName) {
|
16492 | if (exportName[0] === '*')
|
16493 | return "continue";
|
16494 | var variable = this_1.exportNames[exportName];
|
16495 | var module = variable.module;
|
16496 | if (module && module.chunk !== this_1)
|
16497 | return "continue";
|
16498 | var hoisted = false;
|
16499 | var uninitialized = false;
|
16500 | if (variable instanceof LocalVariable) {
|
16501 | if (variable.init === UNDEFINED_EXPRESSION) {
|
16502 | uninitialized = true;
|
16503 | }
|
16504 | variable.declarations.forEach(function (decl) {
|
16505 | if (decl.type === ExportDefaultDeclaration) {
|
16506 | if (decl.declaration.type === FunctionDeclaration)
|
16507 | hoisted = true;
|
16508 | }
|
16509 | else if (decl.parent.type === FunctionDeclaration) {
|
16510 | hoisted = true;
|
16511 | }
|
16512 | });
|
16513 | }
|
16514 | else if (variable instanceof GlobalVariable) {
|
16515 | hoisted = true;
|
16516 | }
|
16517 | var localName = variable.getName();
|
16518 | exports.push({
|
16519 | exported: exportName === '*' ? localName : exportName,
|
16520 | hoisted: hoisted,
|
16521 | local: localName,
|
16522 | uninitialized: uninitialized
|
16523 | });
|
16524 | };
|
16525 | var this_1 = this;
|
16526 | for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
|
16527 | var exportName = _a[_i];
|
16528 | _loop_1(exportName);
|
16529 | }
|
16530 | return exports;
|
16531 | };
|
16532 | Chunk.prototype.getVariableExportNamesForModule = function (module) {
|
16533 | var exportNamesByVariable = new Map();
|
16534 | for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
|
16535 | var exportName = _a[_i];
|
16536 | var tracedVariable = module.getVariableForExportName(exportName);
|
16537 | if (!tracedVariable || !(tracedVariable.included || tracedVariable.isExternal)) {
|
16538 | continue;
|
16539 | }
|
16540 | var existingExportNames = exportNamesByVariable.get(tracedVariable);
|
16541 | if (existingExportNames) {
|
16542 | existingExportNames.push(exportName);
|
16543 | }
|
16544 | else {
|
16545 | exportNamesByVariable.set(tracedVariable, [exportName]);
|
16546 | }
|
16547 | var exportingModule = tracedVariable.module;
|
16548 | if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
|
16549 | exportingModule.chunk.exports.add(tracedVariable);
|
16550 | }
|
16551 | }
|
16552 | return exportNamesByVariable;
|
16553 | };
|
16554 | Chunk.prototype.inlineChunkDependencies = function (chunk, deep) {
|
16555 | for (var _i = 0, _a = chunk.dependencies; _i < _a.length; _i++) {
|
16556 | var dep = _a[_i];
|
16557 | if (dep instanceof ExternalModule) {
|
16558 | if (this.dependencies.indexOf(dep) === -1)
|
16559 | this.dependencies.push(dep);
|
16560 | }
|
16561 | else {
|
16562 | if (dep === this || this.dependencies.indexOf(dep) !== -1)
|
16563 | continue;
|
16564 | if (!dep.isEmpty)
|
16565 | this.dependencies.push(dep);
|
16566 | if (deep)
|
16567 | this.inlineChunkDependencies(dep, true);
|
16568 | }
|
16569 | }
|
16570 | };
|
16571 | Chunk.prototype.prepareDynamicImports = function () {
|
16572 | for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
|
16573 | var module = _a[_i];
|
16574 | for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
|
16575 | var _d = _c[_b], node = _d.node, resolution = _d.resolution;
|
16576 | if (!resolution)
|
16577 | continue;
|
16578 | if (resolution instanceof Module) {
|
16579 | if (resolution.chunk === this) {
|
16580 | var namespace = resolution.getOrCreateNamespace();
|
16581 | node.setResolution(false, namespace.getName());
|
16582 | }
|
16583 | else {
|
16584 | node.setResolution(false);
|
16585 | }
|
16586 | }
|
16587 | else if (resolution instanceof ExternalModule) {
|
16588 | node.setResolution(false);
|
16589 | }
|
16590 | else {
|
16591 | node.setResolution(false);
|
16592 | }
|
16593 | }
|
16594 | }
|
16595 | };
|
16596 | Chunk.prototype.setExternalRenderPaths = function (options, inputBase) {
|
16597 | for (var _i = 0, _a = this.dependencies.concat(this.dynamicDependencies); _i < _a.length; _i++) {
|
16598 | var dependency = _a[_i];
|
16599 | if (dependency instanceof ExternalModule) {
|
16600 | dependency.setRenderPath(options, inputBase);
|
16601 | }
|
16602 | }
|
16603 | };
|
16604 | Chunk.prototype.setIdentifierRenderResolutions = function (options) {
|
16605 | for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
|
16606 | var exportName = _a[_i];
|
16607 | var exportVariable = this.exportNames[exportName];
|
16608 | if (exportVariable) {
|
16609 | if (exportVariable instanceof ExportShimVariable) {
|
16610 | this.needsExportsShim = true;
|
16611 | }
|
16612 | exportVariable.exportName = exportName;
|
16613 | if (options.format !== 'es' &&
|
16614 | options.format !== 'system' &&
|
16615 | exportVariable.isReassigned &&
|
16616 | !exportVariable.isId &&
|
16617 | (!isExportDefaultVariable(exportVariable) || !exportVariable.hasId)) {
|
16618 | exportVariable.setRenderNames('exports', exportName);
|
16619 | }
|
16620 | else {
|
16621 | exportVariable.setRenderNames(null, null);
|
16622 | }
|
16623 | }
|
16624 | }
|
16625 | var usedNames = Object.create(null);
|
16626 | if (this.needsExportsShim) {
|
16627 | usedNames[MISSING_EXPORT_SHIM_VARIABLE] = true;
|
16628 | }
|
16629 | deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
|
16630 | };
|
16631 | Chunk.prototype.setUpModuleImports = function (module) {
|
16632 | for (var _i = 0, _a = Array.from(module.imports); _i < _a.length; _i++) {
|
16633 | var variable = _a[_i];
|
16634 | if (variable.module.chunk !== this) {
|
16635 | this.imports.add(variable);
|
16636 | if (variable.module instanceof Module) {
|
16637 | variable.module.chunk.exports.add(variable);
|
16638 | }
|
16639 | }
|
16640 | }
|
16641 | if (module.getOrCreateNamespace().included) {
|
16642 | for (var _b = 0, _c = Object.keys(module.reexports); _b < _c.length; _b++) {
|
16643 | var reexportName = _c[_b];
|
16644 | var reexport = module.reexports[reexportName];
|
16645 | var variable = reexport.module.getVariableForExportName(reexport.localName);
|
16646 | if (variable.module.chunk !== this) {
|
16647 | this.imports.add(variable);
|
16648 | if (variable.module instanceof Module) {
|
16649 | variable.module.chunk.exports.add(variable);
|
16650 | }
|
16651 | }
|
16652 | }
|
16653 | }
|
16654 | for (var _d = 0, _e = module.dynamicImports; _d < _e.length; _d++) {
|
16655 | var _f = _e[_d], node = _f.node, resolution = _f.resolution;
|
16656 | if (node.included) {
|
16657 | this.hasDynamicImport = true;
|
16658 | if (resolution instanceof Module && resolution.chunk === this)
|
16659 | resolution.getOrCreateNamespace().include();
|
16660 | }
|
16661 | }
|
16662 | };
|
16663 | return Chunk;
|
16664 | }());
|
16665 |
|
16666 | /*
|
16667 | * Given a chunk list, perform optimizations on that chunk list
|
16668 | * to reduce the mumber of chunks. Mutates the chunks array.
|
16669 | *
|
16670 | * Manual chunks (with chunk.chunkAlias already set) are preserved
|
16671 | * Entry points are carefully preserved as well
|
16672 | *
|
16673 | */
|
16674 | function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
|
16675 | var _loop_1 = function (chunkIndex) {
|
16676 | var mainChunk = chunks[chunkIndex];
|
16677 | var execGroup = [];
|
16678 | mainChunk.visitStaticDependenciesUntilCondition(function (dep) {
|
16679 | if (dep instanceof Chunk$1) {
|
16680 | execGroup.push(dep);
|
16681 | }
|
16682 | });
|
16683 | if (execGroup.length < 2) {
|
16684 | return out_chunkIndex_1 = chunkIndex, "continue";
|
16685 | }
|
16686 | var execGroupIndex = 1;
|
16687 | var seekingFirstMergeCandidate = true;
|
16688 | var lastChunk, chunk = execGroup[0], nextChunk = execGroup[1];
|
16689 | var isMergeCandidate = function (chunk) {
|
16690 | if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
|
16691 | return false;
|
16692 | }
|
16693 | if (!nextChunk || nextChunk.facadeModule !== null) {
|
16694 | return false;
|
16695 | }
|
16696 | if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
|
16697 | return false;
|
16698 | }
|
16699 | // if (!chunk.isPure()) continue;
|
16700 | return true;
|
16701 | };
|
16702 | var _loop_2 = function () {
|
16703 | if (seekingFirstMergeCandidate) {
|
16704 | if (isMergeCandidate(chunk)) {
|
16705 | seekingFirstMergeCandidate = false;
|
16706 | }
|
16707 | return "continue";
|
16708 | }
|
16709 | var remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
|
16710 | if (remainingSize <= 0) {
|
16711 | if (!isMergeCandidate(chunk)) {
|
16712 | seekingFirstMergeCandidate = true;
|
16713 | }
|
16714 | return "continue";
|
16715 | }
|
16716 | // if (!chunk.isPure()) continue;
|
16717 | var chunkDependencies = new Set();
|
16718 | chunk.visitStaticDependenciesUntilCondition(function (dep) { return chunkDependencies.add(dep); });
|
16719 | var ignoreSizeChunks = new Set([chunk, lastChunk]);
|
16720 | if (lastChunk.visitStaticDependenciesUntilCondition(function (dep) {
|
16721 | if (dep === chunk || dep === lastChunk) {
|
16722 | return false;
|
16723 | }
|
16724 | if (chunkDependencies.has(dep)) {
|
16725 | return false;
|
16726 | }
|
16727 | if (dep instanceof ExternalModule) {
|
16728 | return true;
|
16729 | }
|
16730 | remainingSize -= dep.getRenderedSourceLength();
|
16731 | if (remainingSize <= 0) {
|
16732 | return true;
|
16733 | }
|
16734 | ignoreSizeChunks.add(dep);
|
16735 | })) {
|
16736 | if (!isMergeCandidate(chunk)) {
|
16737 | seekingFirstMergeCandidate = true;
|
16738 | }
|
16739 | return "continue";
|
16740 | }
|
16741 | if (chunk.visitStaticDependenciesUntilCondition(function (dep) {
|
16742 | if (ignoreSizeChunks.has(dep)) {
|
16743 | return false;
|
16744 | }
|
16745 | if (dep instanceof ExternalModule) {
|
16746 | return true;
|
16747 | }
|
16748 | remainingSize -= dep.getRenderedSourceLength();
|
16749 | if (remainingSize <= 0) {
|
16750 | return true;
|
16751 | }
|
16752 | })) {
|
16753 | if (!isMergeCandidate(chunk)) {
|
16754 | seekingFirstMergeCandidate = true;
|
16755 | }
|
16756 | return "continue";
|
16757 | }
|
16758 | // within the size limit -> merge!
|
16759 | var optimizedChunkIndex = chunks.indexOf(chunk);
|
16760 | if (optimizedChunkIndex <= chunkIndex)
|
16761 | chunkIndex--;
|
16762 | chunks.splice(optimizedChunkIndex, 1);
|
16763 | lastChunk.merge(chunk, chunks, options, inputBase);
|
16764 | execGroup.splice(--execGroupIndex, 1);
|
16765 | chunk = lastChunk;
|
16766 | // keep going to see if we can merge this with the next again
|
16767 | if (nextChunk && !isMergeCandidate(nextChunk)) {
|
16768 | seekingFirstMergeCandidate = true;
|
16769 | }
|
16770 | };
|
16771 | do {
|
16772 | _loop_2();
|
16773 | } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
|
16774 | out_chunkIndex_1 = chunkIndex;
|
16775 | };
|
16776 | var out_chunkIndex_1;
|
16777 | for (var chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
|
16778 | _loop_1(chunkIndex);
|
16779 | chunkIndex = out_chunkIndex_1;
|
16780 | }
|
16781 | return chunks;
|
16782 | }
|
16783 |
|
16784 | const tt = acorn__default.tokTypes;
|
16785 | const isIdentifierStart = acorn__default.isIdentifierStart;
|
16786 |
|
16787 | var acornBigint = function(Parser) {
|
16788 | return class extends Parser {
|
16789 | parseLiteral(value) {
|
16790 | const node = super.parseLiteral(value);
|
16791 | if (node.raw.charCodeAt(node.raw.length - 1) == 110) node.bigint = this.getNumberInput(node.start, node.end);
|
16792 | return node
|
16793 | }
|
16794 |
|
16795 | readRadixNumber(radix) {
|
16796 | let start = this.pos;
|
16797 | this.pos += 2; // 0x
|
16798 | let val = this.readInt(radix);
|
16799 | if (val === null) this.raise(this.start + 2, `Expected number in radix ${radix}`);
|
16800 | if (this.input.charCodeAt(this.pos) == 110) {
|
16801 | let str = this.getNumberInput(start, this.pos);
|
16802 | val = typeof BigInt !== "undefined" ? BigInt(str) : null;
|
16803 | ++this.pos;
|
16804 | } else if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
|
16805 | return this.finishToken(tt.num, val)
|
16806 | }
|
16807 |
|
16808 | readNumber(startsWithDot) {
|
16809 | let start = this.pos;
|
16810 |
|
16811 | // Not an int
|
16812 | if (startsWithDot) return super.readNumber(startsWithDot)
|
16813 |
|
16814 | // Legacy octal
|
16815 | if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) {
|
16816 | return super.readNumber(startsWithDot)
|
16817 | }
|
16818 |
|
16819 | if (this.readInt(10) === null) this.raise(start, "Invalid number");
|
16820 |
|
16821 | // Not a BigInt, reset and parse again
|
16822 | if (this.input.charCodeAt(this.pos) != 110) {
|
16823 | this.pos = start;
|
16824 | return super.readNumber(startsWithDot)
|
16825 | }
|
16826 |
|
16827 | let str = this.getNumberInput(start, this.pos);
|
16828 | let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
|
16829 | ++this.pos;
|
16830 | return this.finishToken(tt.num, val)
|
16831 | }
|
16832 |
|
16833 | // This is basically a hook for acorn-numeric-separator
|
16834 | getNumberInput(start, end) {
|
16835 | if (super.getNumberInput) return super.getNumberInput(start, end)
|
16836 | return this.input.slice(start, end)
|
16837 | }
|
16838 | }
|
16839 | };
|
16840 |
|
16841 | /* eslint-disable no-underscore-dangle */
|
16842 |
|
16843 | const DynamicImportKey = 'Import';
|
16844 |
|
16845 | // NOTE: This allows `yield import()` to parse correctly.
|
16846 | acorn.tokTypes._import.startsExpr = true;
|
16847 |
|
16848 | function parseDynamicImport() {
|
16849 | const node = this.startNode();
|
16850 | this.next();
|
16851 | if (this.type !== acorn.tokTypes.parenL) {
|
16852 | this.unexpected();
|
16853 | }
|
16854 | return this.finishNode(node, DynamicImportKey);
|
16855 | }
|
16856 |
|
16857 | function parenAfter() {
|
16858 | return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
|
16859 | }
|
16860 |
|
16861 | function dynamicImport(Parser) {
|
16862 | return class extends Parser {
|
16863 | parseStatement(context, topLevel, exports) {
|
16864 | if (this.type === acorn.tokTypes._import && parenAfter.call(this)) {
|
16865 | return this.parseExpressionStatement(this.startNode(), this.parseExpression());
|
16866 | }
|
16867 | return super.parseStatement(context, topLevel, exports);
|
16868 | }
|
16869 |
|
16870 | parseExprAtom(refDestructuringErrors) {
|
16871 | if (this.type === acorn.tokTypes._import) {
|
16872 | return parseDynamicImport.call(this);
|
16873 | }
|
16874 | return super.parseExprAtom(refDestructuringErrors);
|
16875 | }
|
16876 | };
|
16877 | }
|
16878 |
|
16879 | const tt$1 = acorn__default.tokTypes;
|
16880 |
|
16881 | const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
|
16882 |
|
16883 | const nextTokenIsDot = parser => {
|
16884 | skipWhiteSpace.lastIndex = parser.pos;
|
16885 | let skip = skipWhiteSpace.exec(parser.input);
|
16886 | let next = parser.pos + skip[0].length;
|
16887 | return parser.input.slice(next, next + 1) === "."
|
16888 | };
|
16889 |
|
16890 | var acornImportMeta = function(Parser) {
|
16891 | return class extends Parser {
|
16892 | parseExprAtom(refDestructuringErrors) {
|
16893 | if (this.type !== tt$1._import || !nextTokenIsDot(this)) return super.parseExprAtom(refDestructuringErrors)
|
16894 |
|
16895 | if (!this.options.allowImportExportEverywhere && !this.inModule) {
|
16896 | this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
|
16897 | }
|
16898 |
|
16899 | let node = this.startNode();
|
16900 | node.meta = this.parseIdent(true);
|
16901 | this.expect(tt$1.dot);
|
16902 | node.property = this.parseIdent(true);
|
16903 | if (node.property.name !== "meta") {
|
16904 | this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
|
16905 | }
|
16906 | if (this.containsEsc) {
|
16907 | this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
|
16908 | }
|
16909 | return this.finishNode(node, "MetaProperty")
|
16910 | }
|
16911 |
|
16912 | parseStatement(context, topLevel, exports) {
|
16913 | if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
|
16914 | return super.parseStatement(context, topLevel, exports)
|
16915 | }
|
16916 |
|
16917 | let node = this.startNode();
|
16918 | let expr = this.parseExpression();
|
16919 | return this.parseExpressionStatement(node, expr)
|
16920 | }
|
16921 | }
|
16922 | };
|
16923 |
|
16924 | var UndefinedVariable = /** @class */ (function (_super) {
|
16925 | __extends(UndefinedVariable, _super);
|
16926 | function UndefinedVariable() {
|
16927 | return _super.call(this, 'undefined') || this;
|
16928 | }
|
16929 | UndefinedVariable.prototype.getLiteralValueAtPath = function () {
|
16930 | return undefined;
|
16931 | };
|
16932 | return UndefinedVariable;
|
16933 | }(Variable));
|
16934 |
|
16935 | var GlobalScope = /** @class */ (function (_super) {
|
16936 | __extends(GlobalScope, _super);
|
16937 | function GlobalScope() {
|
16938 | var _this = _super.call(this) || this;
|
16939 | _this.variables.undefined = new UndefinedVariable();
|
16940 | return _this;
|
16941 | }
|
16942 | GlobalScope.prototype.findVariable = function (name) {
|
16943 | if (!this.variables[name])
|
16944 | return (this.variables[name] = new GlobalVariable(name));
|
16945 | return this.variables[name];
|
16946 | };
|
16947 | return GlobalScope;
|
16948 | }(Scope));
|
16949 |
|
16950 | var getNewTrackedPaths = function () { return ({
|
16951 | paths: Object.create(null),
|
16952 | tracked: false,
|
16953 | unknownPath: null
|
16954 | }); };
|
16955 | var EntityPathTracker = /** @class */ (function () {
|
16956 | function EntityPathTracker() {
|
16957 | this.entityPaths = new Map();
|
16958 | }
|
16959 | EntityPathTracker.prototype.track = function (entity, path) {
|
16960 | var trackedPaths = this.entityPaths.get(entity);
|
16961 | if (!trackedPaths) {
|
16962 | trackedPaths = getNewTrackedPaths();
|
16963 | this.entityPaths.set(entity, trackedPaths);
|
16964 | }
|
16965 | var pathIndex = 0, trackedSubPaths;
|
16966 | while (pathIndex < path.length) {
|
16967 | var key = path[pathIndex];
|
16968 | if (typeof key === 'string') {
|
16969 | trackedSubPaths = trackedPaths.paths[key];
|
16970 | if (!trackedSubPaths) {
|
16971 | trackedSubPaths = getNewTrackedPaths();
|
16972 | trackedPaths.paths[key] = trackedSubPaths;
|
16973 | }
|
16974 | }
|
16975 | else {
|
16976 | trackedSubPaths = trackedPaths.unknownPath;
|
16977 | if (!trackedSubPaths) {
|
16978 | trackedSubPaths = getNewTrackedPaths();
|
16979 | trackedPaths.unknownPath = trackedSubPaths;
|
16980 | }
|
16981 | }
|
16982 | trackedPaths = trackedSubPaths;
|
16983 | pathIndex++;
|
16984 | }
|
16985 | var found = trackedPaths.tracked;
|
16986 | trackedPaths.tracked = true;
|
16987 | return found;
|
16988 | };
|
16989 | return EntityPathTracker;
|
16990 | }());
|
16991 |
|
16992 | function addWithNewReferenceId(item, idMap, hashBase) {
|
16993 | var referenceId;
|
16994 | do {
|
16995 | var hash = _256();
|
16996 | if (referenceId) {
|
16997 | hash.update(referenceId);
|
16998 | }
|
16999 | else {
|
17000 | hash.update(hashBase);
|
17001 | }
|
17002 | referenceId = hash.digest('hex').substr(0, 8);
|
17003 | } while (idMap.has(referenceId));
|
17004 | idMap.set(referenceId, item);
|
17005 | return referenceId;
|
17006 | }
|
17007 |
|
17008 | function getAssetFileName(asset, existingNames, assetFileNames) {
|
17009 | if (asset.source === undefined)
|
17010 | error(errNoAssetSourceSet(asset));
|
17011 | if (asset.fileName)
|
17012 | return asset.fileName;
|
17013 | return makeUnique(renderNamePattern(assetFileNames, 'assetFileNames', function (name) {
|
17014 | switch (name) {
|
17015 | case 'hash':
|
17016 | var hash = _256();
|
17017 | hash.update(name);
|
17018 | hash.update(':');
|
17019 | hash.update(asset.source);
|
17020 | return hash.digest('hex').substr(0, 8);
|
17021 | case 'name':
|
17022 | return asset.name.substr(0, asset.name.length - path.extname(asset.name).length);
|
17023 | case 'extname':
|
17024 | return path.extname(asset.name);
|
17025 | case 'ext':
|
17026 | return path.extname(asset.name).substr(1);
|
17027 | }
|
17028 | }), existingNames);
|
17029 | }
|
17030 | function createAssetPluginHooks(assetsByReferenceId, outputBundle, assetFileNames) {
|
17031 | return {
|
17032 | emitAsset: function (name, source) {
|
17033 | if (typeof name !== 'string' || !isPlainName(name))
|
17034 | error(errInvalidAssetName(name));
|
17035 | var asset = { name: name, source: source, fileName: undefined };
|
17036 | if (outputBundle && source !== undefined)
|
17037 | finaliseAsset(asset, outputBundle, assetFileNames);
|
17038 | return addWithNewReferenceId(asset, assetsByReferenceId, name);
|
17039 | },
|
17040 | setAssetSource: function (assetReferenceId, source) {
|
17041 | var asset = assetsByReferenceId.get(assetReferenceId);
|
17042 | if (!asset)
|
17043 | error(errAssetReferenceIdNotFoundForSetSource(assetReferenceId));
|
17044 | if (asset.source !== undefined)
|
17045 | error(errAssetSourceAlreadySet(asset));
|
17046 | if (typeof source !== 'string' && !source)
|
17047 | error(errAssetSourceMissingForSetSource(asset));
|
17048 | asset.source = source;
|
17049 | if (outputBundle)
|
17050 | finaliseAsset(asset, outputBundle, assetFileNames);
|
17051 | },
|
17052 | getAssetFileName: function (assetReferenceId) {
|
17053 | var asset = assetsByReferenceId.get(assetReferenceId);
|
17054 | if (!asset)
|
17055 | error(errAssetReferenceIdNotFoundForFilename(assetReferenceId));
|
17056 | if (asset.fileName === undefined)
|
17057 | error(errAssetNotFinalisedForFileName(asset));
|
17058 | return asset.fileName;
|
17059 | }
|
17060 | };
|
17061 | }
|
17062 | function finaliseAsset(asset, outputBundle, assetFileNames) {
|
17063 | var fileName = getAssetFileName(asset, outputBundle, assetFileNames);
|
17064 | asset.fileName = fileName;
|
17065 | outputBundle[fileName] = {
|
17066 | fileName: fileName,
|
17067 | isAsset: true,
|
17068 | source: asset.source
|
17069 | };
|
17070 | }
|
17071 | function createTransformEmitAsset(assetsByReferenceId, emitAsset) {
|
17072 | var assets = [];
|
17073 | return {
|
17074 | assets: assets,
|
17075 | emitAsset: function (name, source) {
|
17076 | var assetReferenceId = emitAsset(name, source);
|
17077 | var asset = assetsByReferenceId.get(assetReferenceId);
|
17078 | assets.push({
|
17079 | fileName: undefined,
|
17080 | name: asset.name,
|
17081 | source: asset.source
|
17082 | });
|
17083 | return assetReferenceId;
|
17084 | }
|
17085 | };
|
17086 | }
|
17087 |
|
17088 | var BuildPhase;
|
17089 | (function (BuildPhase) {
|
17090 | BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
|
17091 | BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
|
17092 | BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
|
17093 | })(BuildPhase || (BuildPhase = {}));
|
17094 |
|
17095 | function mkdirpath(path$1) {
|
17096 | var dir = path.dirname(path$1);
|
17097 | try {
|
17098 | fs.readdirSync(dir);
|
17099 | }
|
17100 | catch (err) {
|
17101 | mkdirpath(dir);
|
17102 | try {
|
17103 | fs.mkdirSync(dir);
|
17104 | }
|
17105 | catch (err2) {
|
17106 | if (err2.code !== 'EEXIST') {
|
17107 | throw err2;
|
17108 | }
|
17109 | }
|
17110 | }
|
17111 | }
|
17112 | function writeFile(dest, data) {
|
17113 | return new Promise(function (fulfil, reject) {
|
17114 | mkdirpath(dest);
|
17115 | fs.writeFile(dest, data, function (err) {
|
17116 | if (err) {
|
17117 | reject(err);
|
17118 | }
|
17119 | else {
|
17120 | fulfil();
|
17121 | }
|
17122 | });
|
17123 | });
|
17124 | }
|
17125 |
|
17126 | function getRollupDefaultPlugin(preserveSymlinks) {
|
17127 | return {
|
17128 | name: 'Rollup Core',
|
17129 | resolveId: createResolveId(preserveSymlinks),
|
17130 | load: function (id) {
|
17131 | return fs.readFileSync(id, 'utf-8');
|
17132 | },
|
17133 | resolveFileUrl: function (_a) {
|
17134 | var relativePath = _a.relativePath, format = _a.format;
|
17135 | return relativeUrlMechanisms[format](relativePath);
|
17136 | },
|
17137 | resolveImportMeta: function (prop, _a) {
|
17138 | var chunkId = _a.chunkId, format = _a.format;
|
17139 | var mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
|
17140 | if (mechanism) {
|
17141 | return mechanism;
|
17142 | }
|
17143 | }
|
17144 | };
|
17145 | }
|
17146 | function findFile(file, preserveSymlinks) {
|
17147 | try {
|
17148 | var stats = fs.lstatSync(file);
|
17149 | if (!preserveSymlinks && stats.isSymbolicLink())
|
17150 | return findFile(fs.realpathSync(file), preserveSymlinks);
|
17151 | if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
|
17152 | // check case
|
17153 | var name = path.basename(file);
|
17154 | var files = fs.readdirSync(path.dirname(file));
|
17155 | if (files.indexOf(name) !== -1)
|
17156 | return file;
|
17157 | }
|
17158 | }
|
17159 | catch (err) {
|
17160 | // suppress
|
17161 | }
|
17162 | }
|
17163 | function addJsExtensionIfNecessary(file, preserveSymlinks) {
|
17164 | var found = findFile(file, preserveSymlinks);
|
17165 | if (found)
|
17166 | return found;
|
17167 | found = findFile(file + '.mjs', preserveSymlinks);
|
17168 | if (found)
|
17169 | return found;
|
17170 | found = findFile(file + '.js', preserveSymlinks);
|
17171 | return found;
|
17172 | }
|
17173 | function createResolveId(preserveSymlinks) {
|
17174 | return function (source, importer) {
|
17175 | if (typeof process === 'undefined') {
|
17176 | error({
|
17177 | code: 'MISSING_PROCESS',
|
17178 | 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",
|
17179 | url: 'https://rollupjs.org/guide/en#a-simple-example'
|
17180 | });
|
17181 | }
|
17182 | // external modules (non-entry modules that start with neither '.' or '/')
|
17183 | // are skipped at this stage.
|
17184 | if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
|
17185 | return null;
|
17186 | // `resolve` processes paths from right to left, prepending them until an
|
17187 | // absolute path is created. Absolute importees therefore shortcircuit the
|
17188 | // resolve call and require no special handing on our part.
|
17189 | // See https://nodejs.org/api/path.html#path_path_resolve_paths
|
17190 | return addJsExtensionIfNecessary(path.resolve(importer ? path.dirname(importer) : path.resolve(), source), preserveSymlinks);
|
17191 | };
|
17192 | }
|
17193 | var getResolveUrl = function (path, URL) {
|
17194 | if (URL === void 0) { URL = 'URL'; }
|
17195 | return "new " + URL + "(" + path + ").href";
|
17196 | };
|
17197 | var getUrlFromDocument = function (chunkId) {
|
17198 | return "(document.currentScript && document.currentScript.src || new URL('" + chunkId + "', document.baseURI).href)";
|
17199 | };
|
17200 | var getGenericImportMetaMechanism = function (getUrl) { return function (prop, chunkId) {
|
17201 | var urlMechanism = getUrl(chunkId);
|
17202 | return prop === null ? "({ url: " + urlMechanism + " })" : prop === 'url' ? urlMechanism : 'undefined';
|
17203 | }; };
|
17204 | var importMetaMechanisms = {
|
17205 | amd: getGenericImportMetaMechanism(function () { return getResolveUrl("module.uri, document.baseURI"); }),
|
17206 | cjs: getGenericImportMetaMechanism(function (chunkId) {
|
17207 | return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __filename", "(require('u' + 'rl').URL)") + " : " + getUrlFromDocument(chunkId) + ")";
|
17208 | }),
|
17209 | iife: getGenericImportMetaMechanism(function (chunkId) { return getUrlFromDocument(chunkId); }),
|
17210 | system: function (prop) { return (prop === null ? "module.meta" : "module.meta." + prop); },
|
17211 | umd: getGenericImportMetaMechanism(function (chunkId) {
|
17212 | return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __filename", "(require('u' + 'rl').URL)") + " : " + getUrlFromDocument(chunkId) + ")";
|
17213 | })
|
17214 | };
|
17215 | var getRelativeUrlFromDocument = function (relativePath) {
|
17216 | return getResolveUrl("(document.currentScript && document.currentScript.src || document.baseURI) + '/../" + relativePath + "'");
|
17217 | };
|
17218 | var relativeUrlMechanisms = {
|
17219 | amd: function (relativePath) { return getResolveUrl("module.uri + '/../" + relativePath + "', document.baseURI"); },
|
17220 | cjs: function (relativePath) {
|
17221 | return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __dirname + '/" + relativePath + "'", "(require('u' + 'rl').URL)") + " : " + getRelativeUrlFromDocument(relativePath) + ")";
|
17222 | },
|
17223 | es: function (relativePath) { return getResolveUrl("'" + relativePath + "', import.meta.url"); },
|
17224 | iife: function (relativePath) { return getRelativeUrlFromDocument(relativePath); },
|
17225 | system: function (relativePath) { return getResolveUrl("'" + relativePath + "', module.meta.url"); },
|
17226 | umd: function (relativePath) {
|
17227 | return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __dirname + '/" + relativePath + "'", "(require('u' + 'rl').URL)") + " : " + getRelativeUrlFromDocument(relativePath) + ")";
|
17228 | }
|
17229 | };
|
17230 |
|
17231 | var deprecatedHookNames = {
|
17232 | ongenerate: 'generateBundle',
|
17233 | onwrite: 'generateBundle',
|
17234 | transformBundle: 'renderChunk',
|
17235 | transformChunk: 'renderChunk'
|
17236 | };
|
17237 | function createPluginDriver(graph, options, pluginCache, watcher) {
|
17238 | var plugins = (options.plugins || []).concat([getRollupDefaultPlugin(options.preserveSymlinks)]);
|
17239 | var _a = createAssetPluginHooks(graph.assetsById), emitAsset = _a.emitAsset, getAssetFileName = _a.getAssetFileName, setAssetSource = _a.setAssetSource;
|
17240 | var existingPluginKeys = {};
|
17241 | var hasLoadersOrTransforms = false;
|
17242 | var pluginContexts = plugins.map(function (plugin, pidx) {
|
17243 | var cacheable = true;
|
17244 | if (typeof plugin.cacheKey !== 'string') {
|
17245 | if (typeof plugin.name !== 'string' || existingPluginKeys[plugin.name]) {
|
17246 | cacheable = false;
|
17247 | }
|
17248 | else {
|
17249 | existingPluginKeys[plugin.name] = true;
|
17250 | }
|
17251 | }
|
17252 | if (!hasLoadersOrTransforms &&
|
17253 | (plugin.load || plugin.transform || plugin.transformBundle || plugin.transformChunk))
|
17254 | hasLoadersOrTransforms = true;
|
17255 | var cacheInstance;
|
17256 | if (!pluginCache) {
|
17257 | cacheInstance = noCache;
|
17258 | }
|
17259 | else if (cacheable) {
|
17260 | var cacheKey = plugin.cacheKey || plugin.name;
|
17261 | cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
|
17262 | }
|
17263 | else {
|
17264 | cacheInstance = uncacheablePlugin(plugin.name);
|
17265 | }
|
17266 | var watcherDeprecationWarningShown = false;
|
17267 | function deprecatedWatchListener(event, handler) {
|
17268 | if (!watcherDeprecationWarningShown) {
|
17269 | context.warn({
|
17270 | code: 'PLUGIN_WATCHER_DEPRECATED',
|
17271 | message: "this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead."
|
17272 | });
|
17273 | watcherDeprecationWarningShown = true;
|
17274 | }
|
17275 | return watcher.on(event, handler);
|
17276 | }
|
17277 | var context = {
|
17278 | addWatchFile: function (id) {
|
17279 | if (graph.phase >= BuildPhase.GENERATE)
|
17280 | this.error(errInvalidRollupPhaseForAddWatchFile());
|
17281 | graph.watchFiles[id] = true;
|
17282 | },
|
17283 | cache: cacheInstance,
|
17284 | emitAsset: emitAsset,
|
17285 | emitChunk: function (id, options) {
|
17286 | if (graph.phase > BuildPhase.LOAD_AND_PARSE)
|
17287 | this.error(errInvalidRollupPhaseForEmitChunk());
|
17288 | return graph.moduleLoader.addEntryModuleAndGetReferenceId({
|
17289 | alias: (options && options.name) || null,
|
17290 | unresolvedId: id
|
17291 | });
|
17292 | },
|
17293 | error: function (err) {
|
17294 | if (typeof err === 'string')
|
17295 | err = { message: err };
|
17296 | if (err.code)
|
17297 | err.pluginCode = err.code;
|
17298 | err.code = 'PLUGIN_ERROR';
|
17299 | err.plugin = plugin.name || "Plugin at position " + (pidx + 1);
|
17300 | error(err);
|
17301 | },
|
17302 | isExternal: function (id, parentId, isResolved) {
|
17303 | if (isResolved === void 0) { isResolved = false; }
|
17304 | return graph.moduleLoader.isExternal(id, parentId, isResolved);
|
17305 | },
|
17306 | getAssetFileName: getAssetFileName,
|
17307 | getChunkFileName: function (chunkReferenceId) {
|
17308 | return graph.moduleLoader.getChunkFileName(chunkReferenceId);
|
17309 | },
|
17310 | getModuleInfo: function (moduleId) {
|
17311 | var foundModule = graph.moduleById.get(moduleId);
|
17312 | if (foundModule == null) {
|
17313 | throw new Error("Unable to find module " + moduleId);
|
17314 | }
|
17315 | return {
|
17316 | id: foundModule.id,
|
17317 | importedIds: foundModule.isExternal
|
17318 | ? []
|
17319 | : foundModule.sources.map(function (id) { return foundModule.resolvedIds[id].id; }),
|
17320 | isExternal: !!foundModule.isExternal
|
17321 | };
|
17322 | },
|
17323 | meta: {
|
17324 | rollupVersion: version
|
17325 | },
|
17326 | moduleIds: graph.moduleById.keys(),
|
17327 | parse: graph.contextParse,
|
17328 | resolveId: function (source, importer) {
|
17329 | return graph.moduleLoader
|
17330 | .resolveId(source, importer)
|
17331 | .then(function (resolveId) { return resolveId && resolveId.id; });
|
17332 | },
|
17333 | resolve: function (source, importer) {
|
17334 | return graph.moduleLoader.resolveId(source, importer);
|
17335 | },
|
17336 | setAssetSource: setAssetSource,
|
17337 | warn: function (warning) {
|
17338 | if (typeof warning === 'string')
|
17339 | warning = { message: warning };
|
17340 | if (warning.code)
|
17341 | warning.pluginCode = warning.code;
|
17342 | warning.code = 'PLUGIN_WARNING';
|
17343 | warning.plugin = plugin.name || "Plugin at position " + (pidx + 1);
|
17344 | graph.warn(warning);
|
17345 | },
|
17346 | watcher: watcher
|
17347 | ? __assign({}, watcher, { addListener: deprecatedWatchListener, on: deprecatedWatchListener })
|
17348 | : undefined
|
17349 | };
|
17350 | return context;
|
17351 | });
|
17352 | function runHookSync(hookName, args, pluginIndex, permitValues, hookContext) {
|
17353 | if (permitValues === void 0) { permitValues = false; }
|
17354 | var plugin = plugins[pluginIndex];
|
17355 | var context = pluginContexts[pluginIndex];
|
17356 | var hook = plugin[hookName];
|
17357 | if (!hook)
|
17358 | return;
|
17359 | var deprecatedHookNewName = deprecatedHookNames[hookName];
|
17360 | if (deprecatedHookNewName)
|
17361 | context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pluginIndex));
|
17362 | if (hookContext) {
|
17363 | context = hookContext(context, plugin);
|
17364 | if (!context || context === pluginContexts[pluginIndex])
|
17365 | throw new Error('Internal Rollup error: hookContext must return a new context object.');
|
17366 | }
|
17367 | try {
|
17368 | // permit values allows values to be returned instead of a functional hook
|
17369 | if (typeof hook !== 'function') {
|
17370 | if (permitValues)
|
17371 | return hook;
|
17372 | error({
|
17373 | code: 'INVALID_PLUGIN_HOOK',
|
17374 | message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
|
17375 | "Plugin at position " + (pluginIndex + 1)) + ", expected a function hook."
|
17376 | });
|
17377 | }
|
17378 | return hook.apply(context, args);
|
17379 | }
|
17380 | catch (err) {
|
17381 | if (typeof err === 'string')
|
17382 | err = { message: err };
|
17383 | if (err.code !== 'PLUGIN_ERROR') {
|
17384 | if (err.code)
|
17385 | err.pluginCode = err.code;
|
17386 | err.code = 'PLUGIN_ERROR';
|
17387 | }
|
17388 | err.plugin = plugin.name || "Plugin at position " + (pluginIndex + 1);
|
17389 | err.hook = hookName;
|
17390 | error(err);
|
17391 | }
|
17392 | }
|
17393 | function runHook(hookName, args, pluginIndex, permitValues, hookContext) {
|
17394 | if (permitValues === void 0) { permitValues = false; }
|
17395 | var plugin = plugins[pluginIndex];
|
17396 | var context = pluginContexts[pluginIndex];
|
17397 | var hook = plugin[hookName];
|
17398 | if (!hook)
|
17399 | return;
|
17400 | var deprecatedHookNewName = deprecatedHookNames[hookName];
|
17401 | if (deprecatedHookNewName)
|
17402 | context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pluginIndex));
|
17403 | if (hookContext) {
|
17404 | context = hookContext(context, plugin);
|
17405 | if (!context || context === pluginContexts[pluginIndex])
|
17406 | throw new Error('Internal Rollup error: hookContext must return a new context object.');
|
17407 | }
|
17408 | return Promise.resolve()
|
17409 | .then(function () {
|
17410 | // permit values allows values to be returned instead of a functional hook
|
17411 | if (typeof hook !== 'function') {
|
17412 | if (permitValues)
|
17413 | return hook;
|
17414 | error({
|
17415 | code: 'INVALID_PLUGIN_HOOK',
|
17416 | message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
|
17417 | "Plugin at position " + (pluginIndex + 1)) + ", expected a function hook."
|
17418 | });
|
17419 | }
|
17420 | return hook.apply(context, args);
|
17421 | })
|
17422 | .catch(function (err) {
|
17423 | if (typeof err === 'string')
|
17424 | err = { message: err };
|
17425 | if (err.code !== 'PLUGIN_ERROR') {
|
17426 | if (err.code)
|
17427 | err.pluginCode = err.code;
|
17428 | err.code = 'PLUGIN_ERROR';
|
17429 | }
|
17430 | err.plugin = plugin.name || "Plugin at position " + (pluginIndex + 1);
|
17431 | err.hook = hookName;
|
17432 | error(err);
|
17433 | });
|
17434 | }
|
17435 | var pluginDriver = {
|
17436 | emitAsset: emitAsset,
|
17437 | getAssetFileName: getAssetFileName,
|
17438 | hasLoadersOrTransforms: hasLoadersOrTransforms,
|
17439 | // chains, ignores returns
|
17440 | hookSeq: function (name, args, hookContext) {
|
17441 | var promise = Promise.resolve();
|
17442 | var _loop_1 = function (i) {
|
17443 | promise = promise.then(function () { return runHook(name, args, i, false, hookContext); });
|
17444 | };
|
17445 | for (var i = 0; i < plugins.length; i++) {
|
17446 | _loop_1(i);
|
17447 | }
|
17448 | return promise;
|
17449 | },
|
17450 | // chains, ignores returns
|
17451 | hookSeqSync: function (name, args, hookContext) {
|
17452 | for (var i = 0; i < plugins.length; i++)
|
17453 | runHookSync(name, args, i, false, hookContext);
|
17454 | },
|
17455 | // chains, first non-null result stops and returns
|
17456 | hookFirst: function (name, args, hookContext) {
|
17457 | var promise = Promise.resolve();
|
17458 | var _loop_2 = function (i) {
|
17459 | promise = promise.then(function (result) {
|
17460 | if (result != null)
|
17461 | return result;
|
17462 | return runHook(name, args, i, false, hookContext);
|
17463 | });
|
17464 | };
|
17465 | for (var i = 0; i < plugins.length; i++) {
|
17466 | _loop_2(i);
|
17467 | }
|
17468 | return promise;
|
17469 | },
|
17470 | // chains synchronously, first non-null result stops and returns
|
17471 | hookFirstSync: function (name, args, hookContext) {
|
17472 | for (var i = 0; i < plugins.length; i++) {
|
17473 | var result = runHookSync(name, args, i, false, hookContext);
|
17474 | if (result != null)
|
17475 | return result;
|
17476 | }
|
17477 | return null;
|
17478 | },
|
17479 | // parallel, ignores returns
|
17480 | hookParallel: function (name, args, hookContext) {
|
17481 | var promises = [];
|
17482 | for (var i = 0; i < plugins.length; i++) {
|
17483 | var hookPromise = runHook(name, args, i, false, hookContext);
|
17484 | if (!hookPromise)
|
17485 | continue;
|
17486 | promises.push(hookPromise);
|
17487 | }
|
17488 | return Promise.all(promises).then(function () { });
|
17489 | },
|
17490 | // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
|
17491 | hookReduceArg0: function (name, _a, reduce, hookContext) {
|
17492 | var arg0 = _a[0], args = _a.slice(1);
|
17493 | var promise = Promise.resolve(arg0);
|
17494 | var _loop_3 = function (i) {
|
17495 | promise = promise.then(function (arg0) {
|
17496 | var hookPromise = runHook(name, [arg0].concat(args), i, false, hookContext);
|
17497 | if (!hookPromise)
|
17498 | return arg0;
|
17499 | return hookPromise.then(function (result) {
|
17500 | return reduce.call(pluginContexts[i], arg0, result, plugins[i]);
|
17501 | });
|
17502 | });
|
17503 | };
|
17504 | for (var i = 0; i < plugins.length; i++) {
|
17505 | _loop_3(i);
|
17506 | }
|
17507 | return promise;
|
17508 | },
|
17509 | // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
|
17510 | hookReduceArg0Sync: function (name, _a, reduce, hookContext) {
|
17511 | var arg0 = _a[0], args = _a.slice(1);
|
17512 | for (var i = 0; i < plugins.length; i++) {
|
17513 | var result = runHookSync(name, [arg0].concat(args), i, false, hookContext);
|
17514 | arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
|
17515 | }
|
17516 | return arg0;
|
17517 | },
|
17518 | // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
|
17519 | hookReduceValue: function (name, initial, args, reduce, hookContext) {
|
17520 | var promise = Promise.resolve(initial);
|
17521 | var _loop_4 = function (i) {
|
17522 | promise = promise.then(function (value) {
|
17523 | var hookPromise = runHook(name, args, i, true, hookContext);
|
17524 | if (!hookPromise)
|
17525 | return value;
|
17526 | return hookPromise.then(function (result) {
|
17527 | return reduce.call(pluginContexts[i], value, result, plugins[i]);
|
17528 | });
|
17529 | });
|
17530 | };
|
17531 | for (var i = 0; i < plugins.length; i++) {
|
17532 | _loop_4(i);
|
17533 | }
|
17534 | return promise;
|
17535 | }
|
17536 | };
|
17537 | return pluginDriver;
|
17538 | }
|
17539 | function createPluginCache(cache) {
|
17540 | return {
|
17541 | has: function (id) {
|
17542 | var item = cache[id];
|
17543 | if (!item)
|
17544 | return false;
|
17545 | item[0] = 0;
|
17546 | return true;
|
17547 | },
|
17548 | get: function (id) {
|
17549 | var item = cache[id];
|
17550 | if (!item)
|
17551 | return undefined;
|
17552 | item[0] = 0;
|
17553 | return item[1];
|
17554 | },
|
17555 | set: function (id, value) {
|
17556 | cache[id] = [0, value];
|
17557 | },
|
17558 | delete: function (id) {
|
17559 | return delete cache[id];
|
17560 | }
|
17561 | };
|
17562 | }
|
17563 | function trackPluginCache(pluginCache) {
|
17564 | var result = { used: false, cache: undefined };
|
17565 | result.cache = {
|
17566 | has: function (id) {
|
17567 | result.used = true;
|
17568 | return pluginCache.has(id);
|
17569 | },
|
17570 | get: function (id) {
|
17571 | result.used = true;
|
17572 | return pluginCache.get(id);
|
17573 | },
|
17574 | set: function (id, value) {
|
17575 | result.used = true;
|
17576 | return pluginCache.set(id, value);
|
17577 | },
|
17578 | delete: function (id) {
|
17579 | result.used = true;
|
17580 | return pluginCache.delete(id);
|
17581 | }
|
17582 | };
|
17583 | return result;
|
17584 | }
|
17585 | var noCache = {
|
17586 | has: function () {
|
17587 | return false;
|
17588 | },
|
17589 | get: function () {
|
17590 | return undefined;
|
17591 | },
|
17592 | set: function () { },
|
17593 | delete: function () {
|
17594 | return false;
|
17595 | }
|
17596 | };
|
17597 | function uncacheablePluginError(pluginName) {
|
17598 | if (!pluginName)
|
17599 | error({
|
17600 | code: 'ANONYMOUS_PLUGIN_CACHE',
|
17601 | message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
|
17602 | });
|
17603 | else
|
17604 | error({
|
17605 | code: 'DUPLICATE_PLUGIN_NAME',
|
17606 | 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)."
|
17607 | });
|
17608 | }
|
17609 | var uncacheablePlugin = function (pluginName) { return ({
|
17610 | has: function () {
|
17611 | uncacheablePluginError(pluginName);
|
17612 | return false;
|
17613 | },
|
17614 | get: function () {
|
17615 | uncacheablePluginError(pluginName);
|
17616 | return undefined;
|
17617 | },
|
17618 | set: function () {
|
17619 | uncacheablePluginError(pluginName);
|
17620 | },
|
17621 | delete: function () {
|
17622 | uncacheablePluginError(pluginName);
|
17623 | return false;
|
17624 | }
|
17625 | }); };
|
17626 | function hookDeprecationWarning(name, newName, plugin, pluginIndex) {
|
17627 | return {
|
17628 | code: name.toUpperCase() + '_HOOK_DEPRECATED',
|
17629 | message: "The " + name + " hook used by plugin " + (plugin.name ||
|
17630 | "at position " + (pluginIndex + 1)) + " is deprecated. The " + newName + " hook should be used instead."
|
17631 | };
|
17632 | }
|
17633 |
|
17634 | function transform(graph, source, module) {
|
17635 | var id = module.id;
|
17636 | var sourcemapChain = [];
|
17637 | var originalSourcemap = typeof source.map === 'string' ? JSON.parse(source.map) : source.map;
|
17638 | if (originalSourcemap && typeof originalSourcemap.mappings === 'string')
|
17639 | originalSourcemap.mappings = decode(originalSourcemap.mappings);
|
17640 | var baseEmitAsset = graph.pluginDriver.emitAsset;
|
17641 | var originalCode = source.code;
|
17642 | var ast = source.ast;
|
17643 | var transformDependencies;
|
17644 | var assets;
|
17645 | var customTransformCache = false;
|
17646 | var trackedPluginCache;
|
17647 | var curPlugin;
|
17648 | var curSource = source.code;
|
17649 | function transformReducer(code, result, plugin) {
|
17650 | // track which plugins use the custom this.cache to opt-out of transform caching
|
17651 | if (!customTransformCache && trackedPluginCache.used)
|
17652 | customTransformCache = true;
|
17653 | if (customTransformCache) {
|
17654 | if (result && Array.isArray(result.dependencies)) {
|
17655 | for (var _i = 0, _a = result.dependencies; _i < _a.length; _i++) {
|
17656 | var dep = _a[_i];
|
17657 | var depId = path.resolve(path.dirname(id), dep);
|
17658 | if (!graph.watchFiles[depId])
|
17659 | graph.watchFiles[depId] = true;
|
17660 | }
|
17661 | }
|
17662 | }
|
17663 | else {
|
17664 | // assets emitted by transform are transformDependencies
|
17665 | if (assets.length)
|
17666 | module.transformAssets = assets;
|
17667 | if (result && Array.isArray(result.dependencies)) {
|
17668 | // not great, but a useful way to track this without assuming WeakMap
|
17669 | if (!curPlugin.warnedTransformDependencies)
|
17670 | this.warn({
|
17671 | code: 'TRANSFORM_DEPENDENCIES_DEPRECATED',
|
17672 | message: "Returning \"dependencies\" from plugin transform hook is deprecated for using this.addWatchFile() instead."
|
17673 | });
|
17674 | curPlugin.warnedTransformDependencies = true;
|
17675 | if (!transformDependencies)
|
17676 | transformDependencies = [];
|
17677 | for (var _b = 0, _c = result.dependencies; _b < _c.length; _b++) {
|
17678 | var dep = _c[_b];
|
17679 | transformDependencies.push(path.resolve(path.dirname(id), dep));
|
17680 | }
|
17681 | }
|
17682 | }
|
17683 | if (result == null)
|
17684 | return code;
|
17685 | if (typeof result === 'string') {
|
17686 | result = {
|
17687 | ast: undefined,
|
17688 | code: result,
|
17689 | map: undefined
|
17690 | };
|
17691 | }
|
17692 | else if (typeof result.map === 'string') {
|
17693 | // `result.map` can only be a string if `result` isn't
|
17694 | result.map = JSON.parse(result.map);
|
17695 | }
|
17696 | if (result.map && typeof result.map.mappings === 'string') {
|
17697 | result.map.mappings = decode(result.map.mappings);
|
17698 | }
|
17699 | // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
|
17700 | if (result.map !== null) {
|
17701 | sourcemapChain.push(result.map || { missing: true, plugin: plugin.name });
|
17702 | }
|
17703 | ast = result.ast;
|
17704 | return result.code;
|
17705 | }
|
17706 | var setAssetSourceErr;
|
17707 | return graph.pluginDriver
|
17708 | .hookReduceArg0('transform', [curSource, id], transformReducer, function (pluginContext, plugin) {
|
17709 | var _a;
|
17710 | curPlugin = plugin;
|
17711 | if (plugin.cacheKey)
|
17712 | customTransformCache = true;
|
17713 | else
|
17714 | trackedPluginCache = trackPluginCache(pluginContext.cache);
|
17715 | var emitAsset;
|
17716 | (_a = createTransformEmitAsset(graph.assetsById, baseEmitAsset), assets = _a.assets, emitAsset = _a.emitAsset);
|
17717 | return __assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn: function (warning, pos) {
|
17718 | if (typeof warning === 'string')
|
17719 | warning = { message: warning };
|
17720 | if (pos)
|
17721 | augmentCodeLocation(warning, pos, curSource, id);
|
17722 | warning.id = id;
|
17723 | warning.hook = 'transform';
|
17724 | pluginContext.warn(warning);
|
17725 | },
|
17726 | error: function (err, pos) {
|
17727 | if (typeof err === 'string')
|
17728 | err = { message: err };
|
17729 | if (pos)
|
17730 | augmentCodeLocation(err, pos, curSource, id);
|
17731 | err.id = id;
|
17732 | err.hook = 'transform';
|
17733 | pluginContext.error(err);
|
17734 | },
|
17735 | emitAsset: emitAsset,
|
17736 | addWatchFile: function (id) {
|
17737 | if (!transformDependencies)
|
17738 | transformDependencies = [];
|
17739 | transformDependencies.push(id);
|
17740 | pluginContext.addWatchFile(id);
|
17741 | },
|
17742 | setAssetSource: function (assetReferenceId, source) {
|
17743 | pluginContext.setAssetSource(assetReferenceId, source);
|
17744 | if (!customTransformCache && !setAssetSourceErr) {
|
17745 | try {
|
17746 | this.error({
|
17747 | code: 'INVALID_SETASSETSOURCE',
|
17748 | message: "setAssetSource cannot be called in transform for caching reasons. Use emitAsset with a source, or call setAssetSource in another hook."
|
17749 | });
|
17750 | }
|
17751 | catch (err) {
|
17752 | setAssetSourceErr = err;
|
17753 | }
|
17754 | }
|
17755 | } });
|
17756 | })
|
17757 | .catch(function (err) {
|
17758 | if (typeof err === 'string')
|
17759 | err = { message: err };
|
17760 | if (err.code !== 'PLUGIN_ERROR') {
|
17761 | if (err.code)
|
17762 | err.pluginCode = err.code;
|
17763 | err.code = 'PLUGIN_ERROR';
|
17764 | }
|
17765 | err.id = id;
|
17766 | error(err);
|
17767 | })
|
17768 | .then(function (code) {
|
17769 | if (!customTransformCache && setAssetSourceErr)
|
17770 | throw setAssetSourceErr;
|
17771 | return {
|
17772 | ast: ast,
|
17773 | code: code,
|
17774 | customTransformCache: customTransformCache,
|
17775 | originalCode: originalCode,
|
17776 | originalSourcemap: originalSourcemap,
|
17777 | sourcemapChain: sourcemapChain,
|
17778 | transformDependencies: transformDependencies
|
17779 | };
|
17780 | });
|
17781 | }
|
17782 |
|
17783 | function normalizeRelativeExternalId(importer, source) {
|
17784 | return isRelative(source) ? path.resolve(importer, '..', source) : source;
|
17785 | }
|
17786 | var ModuleLoader = /** @class */ (function () {
|
17787 | function ModuleLoader(graph, modulesById, pluginDriver, external, getManualChunk) {
|
17788 | var _this = this;
|
17789 | this.entriesByReferenceId = new Map();
|
17790 | this.entryModules = [];
|
17791 | this.latestLoadModulesPromise = Promise.resolve();
|
17792 | this.manualChunkModules = {};
|
17793 | this.loadEntryModule = function (_a) {
|
17794 | var alias = _a.alias, unresolvedId = _a.unresolvedId;
|
17795 | return _this.pluginDriver
|
17796 | .hookFirst('resolveId', [unresolvedId, undefined])
|
17797 | .then(function (resolveIdResult) {
|
17798 | if (resolveIdResult === false ||
|
17799 | (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
|
17800 | error(errEntryCannotBeExternal(unresolvedId));
|
17801 | }
|
17802 | var id = resolveIdResult && typeof resolveIdResult === 'object'
|
17803 | ? resolveIdResult.id
|
17804 | : resolveIdResult;
|
17805 | if (typeof id === 'string') {
|
17806 | return _this.fetchModule(id, undefined).then(function (module) {
|
17807 | if (alias !== null) {
|
17808 | if (module.chunkAlias !== null && module.chunkAlias !== alias) {
|
17809 | error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias));
|
17810 | }
|
17811 | module.chunkAlias = alias;
|
17812 | }
|
17813 | return module;
|
17814 | });
|
17815 | }
|
17816 | error(errUnresolvedEntry(unresolvedId));
|
17817 | });
|
17818 | };
|
17819 | this.graph = graph;
|
17820 | this.modulesById = modulesById;
|
17821 | this.pluginDriver = pluginDriver;
|
17822 | if (typeof external === 'function') {
|
17823 | this.isExternal = function (id, parentId, isResolved) {
|
17824 | return !id.startsWith('\0') && external(id, parentId, isResolved);
|
17825 | };
|
17826 | }
|
17827 | else {
|
17828 | var ids_1 = new Set(Array.isArray(external) ? external : external ? [external] : []);
|
17829 | this.isExternal = function (id) { return ids_1.has(id); };
|
17830 | }
|
17831 | this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : function () { return null; };
|
17832 | }
|
17833 | ModuleLoader.prototype.addEntryModuleAndGetReferenceId = function (unresolvedEntryModule) {
|
17834 | var entryRecord = {
|
17835 | module: null,
|
17836 | name: unresolvedEntryModule.unresolvedId
|
17837 | };
|
17838 | var referenceId = addWithNewReferenceId(entryRecord, this.entriesByReferenceId, unresolvedEntryModule.unresolvedId);
|
17839 | this.addEntryModules([unresolvedEntryModule], false)
|
17840 | .then(function (_a) {
|
17841 | var module = _a.newEntryModules[0];
|
17842 | entryRecord.module = module;
|
17843 | })
|
17844 | .catch(function () {
|
17845 | // Avoid unhandled Promise rejection as the error will be thrown later
|
17846 | // once module loading has finished
|
17847 | });
|
17848 | return referenceId;
|
17849 | };
|
17850 | ModuleLoader.prototype.addEntryModules = function (unresolvedEntryModules, isUserDefined) {
|
17851 | var _this = this;
|
17852 | var loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(this.loadEntryModule)).then(function (entryModules) {
|
17853 | var _loop_1 = function (entryModule) {
|
17854 | entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
|
17855 | var existingEntryModule = _this.entryModules.find(function (module) { return module.id === entryModule.id; });
|
17856 | if (!existingEntryModule) {
|
17857 | _this.entryModules.push(entryModule);
|
17858 | }
|
17859 | };
|
17860 | for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
|
17861 | var entryModule = entryModules_1[_i];
|
17862 | _loop_1(entryModule);
|
17863 | }
|
17864 | return entryModules;
|
17865 | });
|
17866 | return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(function (newEntryModules) { return ({
|
17867 | entryModules: _this.entryModules,
|
17868 | manualChunkModulesByAlias: _this.manualChunkModules,
|
17869 | newEntryModules: newEntryModules
|
17870 | }); });
|
17871 | };
|
17872 | ModuleLoader.prototype.addManualChunks = function (manualChunks) {
|
17873 | var _this = this;
|
17874 | var unresolvedManualChunks = [];
|
17875 | for (var _i = 0, _a = Object.keys(manualChunks); _i < _a.length; _i++) {
|
17876 | var alias = _a[_i];
|
17877 | var manualChunkIds = manualChunks[alias];
|
17878 | for (var _b = 0, manualChunkIds_1 = manualChunkIds; _b < manualChunkIds_1.length; _b++) {
|
17879 | var unresolvedId = manualChunkIds_1[_b];
|
17880 | unresolvedManualChunks.push({ alias: null, unresolvedId: unresolvedId, manualChunkAlias: alias });
|
17881 | }
|
17882 | }
|
17883 | var loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(this.loadEntryModule)).then(function (manualChunkModules) {
|
17884 | for (var index = 0; index < manualChunkModules.length; index++) {
|
17885 | _this.addToManualChunk(unresolvedManualChunks[index].manualChunkAlias, manualChunkModules[index]);
|
17886 | }
|
17887 | });
|
17888 | return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
|
17889 | };
|
17890 | ModuleLoader.prototype.getChunkFileName = function (referenceId) {
|
17891 | var entryRecord = this.entriesByReferenceId.get(referenceId);
|
17892 | if (!entryRecord)
|
17893 | error(errChunkReferenceIdNotFoundForFilename(referenceId));
|
17894 | var fileName = entryRecord.module &&
|
17895 | (entryRecord.module.facadeChunk
|
17896 | ? entryRecord.module.facadeChunk.id
|
17897 | : entryRecord.module.chunk.id);
|
17898 | if (!fileName)
|
17899 | error(errChunkNotGeneratedForFileName(entryRecord));
|
17900 | return fileName;
|
17901 | };
|
17902 | ModuleLoader.prototype.resolveId = function (source, importer) {
|
17903 | var _this = this;
|
17904 | return Promise.resolve(this.isExternal(source, importer, false)
|
17905 | ? { id: source, external: true }
|
17906 | : this.pluginDriver.hookFirst('resolveId', [source, importer])).then(function (result) { return _this.normalizeResolveIdResult(result, importer, source); });
|
17907 | };
|
17908 | ModuleLoader.prototype.addToManualChunk = function (alias, module) {
|
17909 | if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
|
17910 | error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
|
17911 | }
|
17912 | module.manualChunkAlias = alias;
|
17913 | if (!this.manualChunkModules[alias]) {
|
17914 | this.manualChunkModules[alias] = [];
|
17915 | }
|
17916 | this.manualChunkModules[alias].push(module);
|
17917 | };
|
17918 | ModuleLoader.prototype.awaitLoadModulesPromise = function (loadNewModulesPromise) {
|
17919 | var _this = this;
|
17920 | this.latestLoadModulesPromise = Promise.all([
|
17921 | loadNewModulesPromise,
|
17922 | this.latestLoadModulesPromise
|
17923 | ]);
|
17924 | var getCombinedPromise = function () {
|
17925 | var startingPromise = _this.latestLoadModulesPromise;
|
17926 | return startingPromise.then(function () {
|
17927 | if (_this.latestLoadModulesPromise !== startingPromise) {
|
17928 | return getCombinedPromise();
|
17929 | }
|
17930 | });
|
17931 | };
|
17932 | return getCombinedPromise().then(function () { return loadNewModulesPromise; });
|
17933 | };
|
17934 | ModuleLoader.prototype.fetchAllDependencies = function (module) {
|
17935 | var _this = this;
|
17936 | var fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map(function (specifier, index) {
|
17937 | return _this.resolveDynamicImport(specifier, module.id).then(function (resolvedId) {
|
17938 | if (resolvedId === null)
|
17939 | return;
|
17940 | var dynamicImport = module.dynamicImports[index];
|
17941 | if (typeof resolvedId === 'string') {
|
17942 | dynamicImport.resolution = resolvedId;
|
17943 | return;
|
17944 | }
|
17945 | return _this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(function (module) {
|
17946 | dynamicImport.resolution = module;
|
17947 | });
|
17948 | });
|
17949 | }));
|
17950 | fetchDynamicImportsPromise.catch(function () { });
|
17951 | return Promise.all(module.sources.map(function (source) { return _this.resolveAndFetchDependency(module, source); })).then(function () { return fetchDynamicImportsPromise; });
|
17952 | };
|
17953 | ModuleLoader.prototype.fetchModule = function (id, importer) {
|
17954 | var _this = this;
|
17955 | var existingModule = this.modulesById.get(id);
|
17956 | if (existingModule) {
|
17957 | if (existingModule.isExternal)
|
17958 | throw new Error("Cannot fetch external module " + id);
|
17959 | return Promise.resolve(existingModule);
|
17960 | }
|
17961 | var module = new Module(this.graph, id);
|
17962 | this.modulesById.set(id, module);
|
17963 | var manualChunkAlias = this.getManualChunk(id);
|
17964 | if (typeof manualChunkAlias === 'string') {
|
17965 | this.addToManualChunk(manualChunkAlias, module);
|
17966 | }
|
17967 | timeStart('load modules', 3);
|
17968 | return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
|
17969 | .catch(function (err) {
|
17970 | timeEnd('load modules', 3);
|
17971 | var msg = "Could not load " + id;
|
17972 | if (importer)
|
17973 | msg += " (imported by " + importer + ")";
|
17974 | msg += ": " + err.message;
|
17975 | throw new Error(msg);
|
17976 | })
|
17977 | .then(function (source) {
|
17978 | timeEnd('load modules', 3);
|
17979 | if (typeof source === 'string')
|
17980 | return source;
|
17981 | if (source && typeof source === 'object' && typeof source.code === 'string')
|
17982 | return source;
|
17983 | error(errBadLoader(id));
|
17984 | })
|
17985 | .then(function (source) {
|
17986 | var sourceDescription = typeof source === 'string'
|
17987 | ? {
|
17988 | ast: null,
|
17989 | code: source
|
17990 | }
|
17991 | : source;
|
17992 | var cachedModule = _this.graph.cachedModules.get(id);
|
17993 | if (cachedModule &&
|
17994 | !cachedModule.customTransformCache &&
|
17995 | cachedModule.originalCode === sourceDescription.code) {
|
17996 | // re-emit transform assets
|
17997 | if (cachedModule.transformAssets) {
|
17998 | for (var _i = 0, _a = cachedModule.transformAssets; _i < _a.length; _i++) {
|
17999 | var asset = _a[_i];
|
18000 | _this.pluginDriver.emitAsset(asset.name, asset.source);
|
18001 | }
|
18002 | }
|
18003 | return cachedModule;
|
18004 | }
|
18005 | return transform(_this.graph, sourceDescription, module);
|
18006 | })
|
18007 | .then(function (source) {
|
18008 | module.setSource(source);
|
18009 | _this.modulesById.set(id, module);
|
18010 | return _this.fetchAllDependencies(module).then(function () {
|
18011 | for (var name in module.exports) {
|
18012 | if (name !== 'default') {
|
18013 | module.exportsAll[name] = module.id;
|
18014 | }
|
18015 | }
|
18016 | module.exportAllSources.forEach(function (source) {
|
18017 | var id = module.resolvedIds[source].id;
|
18018 | var exportAllModule = _this.modulesById.get(id);
|
18019 | if (exportAllModule instanceof ExternalModule)
|
18020 | return;
|
18021 | for (var name in exportAllModule.exportsAll) {
|
18022 | if (name in module.exportsAll) {
|
18023 | _this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
|
18024 | }
|
18025 | else {
|
18026 | module.exportsAll[name] = exportAllModule.exportsAll[name];
|
18027 | }
|
18028 | }
|
18029 | });
|
18030 | return module;
|
18031 | });
|
18032 | });
|
18033 | };
|
18034 | ModuleLoader.prototype.fetchResolvedDependency = function (source, importer, resolvedId) {
|
18035 | if (resolvedId.external) {
|
18036 | if (!this.modulesById.has(resolvedId.id)) {
|
18037 | this.modulesById.set(resolvedId.id, new ExternalModule({ graph: this.graph, id: resolvedId.id }));
|
18038 | }
|
18039 | var externalModule = this.modulesById.get(resolvedId.id);
|
18040 | if (externalModule instanceof ExternalModule === false) {
|
18041 | error(errInternalIdCannotBeExternal(source, importer));
|
18042 | }
|
18043 | return Promise.resolve(externalModule);
|
18044 | }
|
18045 | else {
|
18046 | return this.fetchModule(resolvedId.id, importer);
|
18047 | }
|
18048 | };
|
18049 | ModuleLoader.prototype.handleMissingImports = function (resolvedId, source, importer) {
|
18050 | if (resolvedId === null) {
|
18051 | if (isRelative(source)) {
|
18052 | error(errUnresolvedImport(source, importer));
|
18053 | }
|
18054 | this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
|
18055 | return { id: source, external: true };
|
18056 | }
|
18057 | return resolvedId;
|
18058 | };
|
18059 | ModuleLoader.prototype.normalizeResolveIdResult = function (resolveIdResult, importer, source) {
|
18060 | var id = '';
|
18061 | var external = false;
|
18062 | if (resolveIdResult) {
|
18063 | if (typeof resolveIdResult === 'object') {
|
18064 | id = resolveIdResult.id;
|
18065 | if (resolveIdResult.external) {
|
18066 | external = true;
|
18067 | }
|
18068 | }
|
18069 | else {
|
18070 | id = resolveIdResult;
|
18071 | if (this.isExternal(id, importer, true)) {
|
18072 | external = true;
|
18073 | }
|
18074 | }
|
18075 | if (external) {
|
18076 | id = normalizeRelativeExternalId(importer, id);
|
18077 | }
|
18078 | }
|
18079 | else {
|
18080 | id = normalizeRelativeExternalId(importer, source);
|
18081 | if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
|
18082 | return null;
|
18083 | }
|
18084 | external = true;
|
18085 | }
|
18086 | return { id: id, external: external };
|
18087 | };
|
18088 | ModuleLoader.prototype.resolveAndFetchDependency = function (module, source) {
|
18089 | var _this = this;
|
18090 | return Promise.resolve(module.resolvedIds[source] ||
|
18091 | this.resolveId(source, module.id).then(function (resolvedId) {
|
18092 | return _this.handleMissingImports(resolvedId, source, module.id);
|
18093 | })).then(function (resolvedId) {
|
18094 | module.resolvedIds[source] = resolvedId;
|
18095 | return _this.fetchResolvedDependency(source, module.id, resolvedId);
|
18096 | });
|
18097 | };
|
18098 | ModuleLoader.prototype.resolveDynamicImport = function (specifier, importer) {
|
18099 | var _this = this;
|
18100 | // TODO we only should expose the acorn AST here
|
18101 | return this.pluginDriver
|
18102 | .hookFirst('resolveDynamicImport', [specifier, importer])
|
18103 | .then(function (resolution) {
|
18104 | if (typeof specifier !== 'string') {
|
18105 | if (typeof resolution === 'string') {
|
18106 | return resolution;
|
18107 | }
|
18108 | if (!resolution) {
|
18109 | return null;
|
18110 | }
|
18111 | return __assign({ external: false }, resolution);
|
18112 | }
|
18113 | if (resolution == null) {
|
18114 | return _this.resolveId(specifier, importer).then(function (resolvedId) {
|
18115 | return _this.handleMissingImports(resolvedId, specifier, importer);
|
18116 | });
|
18117 | }
|
18118 | return _this.handleMissingImports(_this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
|
18119 | });
|
18120 | };
|
18121 | return ModuleLoader;
|
18122 | }());
|
18123 |
|
18124 | var CHAR_CODE_A = 97;
|
18125 | var CHAR_CODE_0 = 48;
|
18126 | function intToHex(num) {
|
18127 | if (num < 10)
|
18128 | return String.fromCharCode(CHAR_CODE_0 + num);
|
18129 | else
|
18130 | return String.fromCharCode(CHAR_CODE_A + (num - 10));
|
18131 | }
|
18132 | function Uint8ArrayToHexString(buffer) {
|
18133 | var str = '';
|
18134 | // hex conversion - 2 chars per 8 bit component
|
18135 | for (var i = 0; i < buffer.length; i++) {
|
18136 | var num = buffer[i];
|
18137 | // big endian conversion, but whatever
|
18138 | str += intToHex(num >> 4);
|
18139 | str += intToHex(num & 0xf);
|
18140 | }
|
18141 | return str;
|
18142 | }
|
18143 | function Uint8ArrayXor(to, from) {
|
18144 | for (var i = 0; i < to.length; i++)
|
18145 | to[i] = to[i] ^ from[i];
|
18146 | return to;
|
18147 | }
|
18148 | function randomUint8Array(len) {
|
18149 | var buffer = new Uint8Array(len);
|
18150 | for (var i = 0; i < buffer.length; i++)
|
18151 | buffer[i] = Math.random() * (2 << 8);
|
18152 | return buffer;
|
18153 | }
|
18154 |
|
18155 | function assignChunkColouringHashes(entryModules, manualChunkModules) {
|
18156 | var currentEntry, currentEntryHash;
|
18157 | var modulesVisitedForCurrentEntry;
|
18158 | var handledEntryPoints = new Set();
|
18159 | var dynamicImports = [];
|
18160 | var addCurrentEntryColourToModule = function (module) {
|
18161 | if (currentEntry.manualChunkAlias) {
|
18162 | module.manualChunkAlias = currentEntry.manualChunkAlias;
|
18163 | module.entryPointsHash = currentEntryHash;
|
18164 | }
|
18165 | else {
|
18166 | Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
|
18167 | }
|
18168 | for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
|
18169 | var dependency = _a[_i];
|
18170 | if (dependency instanceof ExternalModule ||
|
18171 | modulesVisitedForCurrentEntry.has(dependency.id)) {
|
18172 | continue;
|
18173 | }
|
18174 | modulesVisitedForCurrentEntry.add(dependency.id);
|
18175 | if (!handledEntryPoints.has(dependency.id) && !dependency.manualChunkAlias) {
|
18176 | addCurrentEntryColourToModule(dependency);
|
18177 | }
|
18178 | }
|
18179 | for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
|
18180 | var resolution = _c[_b].resolution;
|
18181 | if (resolution instanceof Module &&
|
18182 | resolution.dynamicallyImportedBy.length > 0 &&
|
18183 | !resolution.manualChunkAlias) {
|
18184 | dynamicImports.push(resolution);
|
18185 | }
|
18186 | }
|
18187 | };
|
18188 | if (manualChunkModules) {
|
18189 | for (var _i = 0, _a = Object.keys(manualChunkModules); _i < _a.length; _i++) {
|
18190 | var chunkName = _a[_i];
|
18191 | currentEntryHash = randomUint8Array(10);
|
18192 | for (var _b = 0, _c = manualChunkModules[chunkName]; _b < _c.length; _b++) {
|
18193 | currentEntry = _c[_b];
|
18194 | modulesVisitedForCurrentEntry = new Set(currentEntry.id);
|
18195 | addCurrentEntryColourToModule(currentEntry);
|
18196 | }
|
18197 | }
|
18198 | }
|
18199 | for (var _d = 0, entryModules_1 = entryModules; _d < entryModules_1.length; _d++) {
|
18200 | currentEntry = entryModules_1[_d];
|
18201 | handledEntryPoints.add(currentEntry.id);
|
18202 | currentEntryHash = randomUint8Array(10);
|
18203 | modulesVisitedForCurrentEntry = new Set(currentEntry.id);
|
18204 | if (!currentEntry.manualChunkAlias) {
|
18205 | addCurrentEntryColourToModule(currentEntry);
|
18206 | }
|
18207 | }
|
18208 | for (var _e = 0, dynamicImports_1 = dynamicImports; _e < dynamicImports_1.length; _e++) {
|
18209 | currentEntry = dynamicImports_1[_e];
|
18210 | if (handledEntryPoints.has(currentEntry.id)) {
|
18211 | continue;
|
18212 | }
|
18213 | handledEntryPoints.add(currentEntry.id);
|
18214 | currentEntryHash = randomUint8Array(10);
|
18215 | modulesVisitedForCurrentEntry = new Set(currentEntry.id);
|
18216 | addCurrentEntryColourToModule(currentEntry);
|
18217 | }
|
18218 | }
|
18219 |
|
18220 | function makeOnwarn() {
|
18221 | var warned = Object.create(null);
|
18222 | return function (warning) {
|
18223 | var str = warning.toString();
|
18224 | if (str in warned)
|
18225 | return;
|
18226 | console.error(str);
|
18227 | warned[str] = true;
|
18228 | };
|
18229 | }
|
18230 | function normalizeEntryModules(entryModules) {
|
18231 | if (typeof entryModules === 'string') {
|
18232 | return [{ alias: null, unresolvedId: entryModules }];
|
18233 | }
|
18234 | if (Array.isArray(entryModules)) {
|
18235 | return entryModules.map(function (unresolvedId) { return ({ alias: null, unresolvedId: unresolvedId }); });
|
18236 | }
|
18237 | return Object.keys(entryModules).map(function (alias) { return ({
|
18238 | alias: alias,
|
18239 | unresolvedId: entryModules[alias]
|
18240 | }); });
|
18241 | }
|
18242 | var Graph = /** @class */ (function () {
|
18243 | function Graph(options, watcher) {
|
18244 | var _this = this;
|
18245 | var _a;
|
18246 | this.assetsById = new Map();
|
18247 | this.curChunkIndex = 0;
|
18248 | this.moduleById = new Map();
|
18249 | this.needsTreeshakingPass = false;
|
18250 | this.phase = BuildPhase.LOAD_AND_PARSE;
|
18251 | this.watchFiles = Object.create(null);
|
18252 | this.externalModules = [];
|
18253 | this.modules = [];
|
18254 | this.curChunkIndex = 0;
|
18255 | this.deoptimizationTracker = new EntityPathTracker();
|
18256 | this.cachedModules = new Map();
|
18257 | if (options.cache) {
|
18258 | if (options.cache.modules)
|
18259 | for (var _i = 0, _b = options.cache.modules; _i < _b.length; _i++) {
|
18260 | var module = _b[_i];
|
18261 | this.cachedModules.set(module.id, module);
|
18262 | }
|
18263 | }
|
18264 | if (options.cache !== false) {
|
18265 | this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
|
18266 | // increment access counter
|
18267 | for (var name in this.pluginCache) {
|
18268 | var cache = this.pluginCache[name];
|
18269 | for (var _c = 0, _d = Object.keys(cache); _c < _d.length; _c++) {
|
18270 | var key = _d[_c];
|
18271 | cache[key][0]++;
|
18272 | }
|
18273 | }
|
18274 | }
|
18275 | this.preserveModules = options.preserveModules;
|
18276 | this.cacheExpiry = options.experimentalCacheExpiry;
|
18277 | this.treeshake = options.treeshake !== false;
|
18278 | if (this.treeshake) {
|
18279 | this.treeshakingOptions = options.treeshake
|
18280 | ? {
|
18281 | annotations: options.treeshake.annotations !== false,
|
18282 | propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
|
18283 | pureExternalModules: options.treeshake.pureExternalModules
|
18284 | }
|
18285 | : { propertyReadSideEffects: true, annotations: true, pureExternalModules: false };
|
18286 | if (this.treeshakingOptions.pureExternalModules === true) {
|
18287 | this.isPureExternalModule = function () { return true; };
|
18288 | }
|
18289 | else if (typeof this.treeshakingOptions.pureExternalModules === 'function') {
|
18290 | this.isPureExternalModule = this.treeshakingOptions.pureExternalModules;
|
18291 | }
|
18292 | else if (Array.isArray(this.treeshakingOptions.pureExternalModules)) {
|
18293 | var pureExternalModules_1 = new Set(this.treeshakingOptions.pureExternalModules);
|
18294 | this.isPureExternalModule = function (id) { return pureExternalModules_1.has(id); };
|
18295 | }
|
18296 | else {
|
18297 | this.isPureExternalModule = function () { return false; };
|
18298 | }
|
18299 | }
|
18300 | else {
|
18301 | this.isPureExternalModule = function () { return false; };
|
18302 | }
|
18303 | this.contextParse = function (code, options) {
|
18304 | if (options === void 0) { options = {}; }
|
18305 | return _this.acornParser.parse(code, __assign({}, defaultAcornOptions, options, _this.acornOptions));
|
18306 | };
|
18307 | this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
|
18308 | if (watcher) {
|
18309 | var handleChange_1 = function (id) { return _this.pluginDriver.hookSeqSync('watchChange', [id]); };
|
18310 | watcher.on('change', handleChange_1);
|
18311 | watcher.once('restart', function () {
|
18312 | watcher.removeListener('change', handleChange_1);
|
18313 | });
|
18314 | }
|
18315 | this.shimMissingExports = options.shimMissingExports;
|
18316 | this.scope = new GlobalScope();
|
18317 | this.context = String(options.context);
|
18318 | var optionsModuleContext = options.moduleContext;
|
18319 | if (typeof optionsModuleContext === 'function') {
|
18320 | this.getModuleContext = function (id) { return optionsModuleContext(id) || _this.context; };
|
18321 | }
|
18322 | else if (typeof optionsModuleContext === 'object') {
|
18323 | var moduleContext_1 = new Map();
|
18324 | for (var key in optionsModuleContext) {
|
18325 | moduleContext_1.set(path.resolve(key), optionsModuleContext[key]);
|
18326 | }
|
18327 | this.getModuleContext = function (id) { return moduleContext_1.get(id) || _this.context; };
|
18328 | }
|
18329 | else {
|
18330 | this.getModuleContext = function () { return _this.context; };
|
18331 | }
|
18332 | this.onwarn = options.onwarn || makeOnwarn();
|
18333 | this.acornOptions = options.acorn || {};
|
18334 | var acornPluginsToInject = [];
|
18335 | acornPluginsToInject.push(dynamicImport);
|
18336 | acornPluginsToInject.push(acornImportMeta);
|
18337 | acornPluginsToInject.push(acornBigint);
|
18338 | if (options.experimentalTopLevelAwait) {
|
18339 | this.acornOptions.allowAwaitOutsideFunction = true;
|
18340 | }
|
18341 | var acornInjectPlugins = options.acornInjectPlugins;
|
18342 | acornPluginsToInject.push.apply(acornPluginsToInject, (Array.isArray(acornInjectPlugins)
|
18343 | ? acornInjectPlugins
|
18344 | : acornInjectPlugins
|
18345 | ? [acornInjectPlugins]
|
18346 | : []));
|
18347 | this.acornParser = (_a = acorn.Parser).extend.apply(_a, acornPluginsToInject);
|
18348 | this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, typeof options.manualChunks === 'function' && options.manualChunks);
|
18349 | }
|
18350 | Graph.prototype.build = function (entryModules, manualChunks, inlineDynamicImports) {
|
18351 | // Phase 1 – discovery. We load the entry module and find which
|
18352 | // modules it imports, and import those, until we have all
|
18353 | // of the entry module's dependencies
|
18354 | var _this = this;
|
18355 | timeStart('parse modules', 2);
|
18356 | return Promise.all([
|
18357 | this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
|
18358 | manualChunks &&
|
18359 | typeof manualChunks === 'object' &&
|
18360 | this.moduleLoader.addManualChunks(manualChunks)
|
18361 | ]).then(function (_a) {
|
18362 | var _b = _a[0], entryModules = _b.entryModules, manualChunkModulesByAlias = _b.manualChunkModulesByAlias;
|
18363 | if (entryModules.length === 0) {
|
18364 | throw new Error('You must supply options.input to rollup');
|
18365 | }
|
18366 | for (var _i = 0, _c = Array.from(_this.moduleById.values()); _i < _c.length; _i++) {
|
18367 | var module = _c[_i];
|
18368 | if (module instanceof Module) {
|
18369 | _this.modules.push(module);
|
18370 | _this.watchFiles[module.id] = true;
|
18371 | }
|
18372 | else {
|
18373 | _this.externalModules.push(module);
|
18374 | }
|
18375 | }
|
18376 | timeEnd('parse modules', 2);
|
18377 | _this.phase = BuildPhase.ANALYSE;
|
18378 | // Phase 2 - linking. We populate the module dependency links and
|
18379 | // determine the topological execution order for the bundle
|
18380 | timeStart('analyse dependency graph', 2);
|
18381 | _this.link(entryModules);
|
18382 | timeEnd('analyse dependency graph', 2);
|
18383 | // Phase 3 – marking. We include all statements that should be included
|
18384 | timeStart('mark included statements', 2);
|
18385 | if (inlineDynamicImports) {
|
18386 | if (entryModules.length > 1) {
|
18387 | throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
|
18388 | }
|
18389 | }
|
18390 | for (var _d = 0, entryModules_1 = entryModules; _d < entryModules_1.length; _d++) {
|
18391 | var module = entryModules_1[_d];
|
18392 | module.includeAllExports();
|
18393 | }
|
18394 | _this.includeMarked(_this.modules);
|
18395 | // check for unused external imports
|
18396 | for (var _e = 0, _f = _this.externalModules; _e < _f.length; _e++) {
|
18397 | var externalModule = _f[_e];
|
18398 | externalModule.warnUnusedImports();
|
18399 | }
|
18400 | timeEnd('mark included statements', 2);
|
18401 | // Phase 4 – we construct the chunks, working out the optimal chunking using
|
18402 | // entry point graph colouring, before generating the import and export facades
|
18403 | timeStart('generate chunks', 2);
|
18404 | if (!_this.preserveModules && !inlineDynamicImports) {
|
18405 | assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
|
18406 | }
|
18407 | // TODO: there is one special edge case unhandled here and that is that any module
|
18408 | // exposed as an unresolvable export * (to a graph external export *,
|
18409 | // either as a namespace import reexported or top-level export *)
|
18410 | // should be made to be its own entry point module before chunking
|
18411 | var chunks = [];
|
18412 | if (_this.preserveModules) {
|
18413 | for (var _g = 0, _h = _this.modules; _g < _h.length; _g++) {
|
18414 | var module = _h[_g];
|
18415 | var chunk = new Chunk$1(_this, [module]);
|
18416 | if (module.isEntryPoint || !chunk.isEmpty) {
|
18417 | chunk.entryModules = [module];
|
18418 | }
|
18419 | chunks.push(chunk);
|
18420 | }
|
18421 | }
|
18422 | else {
|
18423 | var chunkModules = {};
|
18424 | for (var _j = 0, _k = _this.modules; _j < _k.length; _j++) {
|
18425 | var module = _k[_j];
|
18426 | var entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
|
18427 | var curChunk = chunkModules[entryPointsHashStr];
|
18428 | if (curChunk) {
|
18429 | curChunk.push(module);
|
18430 | }
|
18431 | else {
|
18432 | chunkModules[entryPointsHashStr] = [module];
|
18433 | }
|
18434 | }
|
18435 | for (var entryHashSum in chunkModules) {
|
18436 | var chunkModulesOrdered = chunkModules[entryHashSum];
|
18437 | sortByExecutionOrder(chunkModulesOrdered);
|
18438 | var chunk = new Chunk$1(_this, chunkModulesOrdered);
|
18439 | chunks.push(chunk);
|
18440 | }
|
18441 | }
|
18442 | // for each chunk module, set up its imports to other
|
18443 | // chunks, if those variables are included after treeshaking
|
18444 | for (var _l = 0, chunks_1 = chunks; _l < chunks_1.length; _l++) {
|
18445 | var chunk = chunks_1[_l];
|
18446 | chunk.link();
|
18447 | }
|
18448 | // filter out empty dependencies
|
18449 | chunks = chunks.filter(isChunkRendered);
|
18450 | // then go over and ensure all entry chunks export their variables
|
18451 | for (var _m = 0, chunks_2 = chunks; _m < chunks_2.length; _m++) {
|
18452 | var chunk = chunks_2[_m];
|
18453 | if (_this.preserveModules || chunk.entryModules.length > 0) {
|
18454 | chunk.generateEntryExportsOrMarkAsTainted();
|
18455 | }
|
18456 | }
|
18457 | // create entry point facades for entry module chunks that have tainted exports
|
18458 | var facades = [];
|
18459 | if (!_this.preserveModules) {
|
18460 | for (var _o = 0, chunks_3 = chunks; _o < chunks_3.length; _o++) {
|
18461 | var chunk = chunks_3[_o];
|
18462 | for (var _p = 0, _q = chunk.entryModules; _p < _q.length; _p++) {
|
18463 | var entryModule = _q[_p];
|
18464 | if (chunk.facadeModule !== entryModule) {
|
18465 | var entryPointFacade = new Chunk$1(_this, []);
|
18466 | entryPointFacade.turnIntoFacade(entryModule);
|
18467 | facades.push(entryPointFacade);
|
18468 | }
|
18469 | }
|
18470 | }
|
18471 | }
|
18472 | timeEnd('generate chunks', 2);
|
18473 | _this.phase = BuildPhase.GENERATE;
|
18474 | return chunks.concat(facades);
|
18475 | });
|
18476 | };
|
18477 | Graph.prototype.finaliseAssets = function (assetFileNames) {
|
18478 | var outputBundle = Object.create(null);
|
18479 | this.assetsById.forEach(function (asset) {
|
18480 | if (asset.source !== undefined)
|
18481 | finaliseAsset(asset, outputBundle, assetFileNames);
|
18482 | });
|
18483 | return outputBundle;
|
18484 | };
|
18485 | Graph.prototype.getCache = function () {
|
18486 | // handle plugin cache eviction
|
18487 | for (var name in this.pluginCache) {
|
18488 | var cache = this.pluginCache[name];
|
18489 | var allDeleted = true;
|
18490 | for (var _i = 0, _a = Object.keys(cache); _i < _a.length; _i++) {
|
18491 | var key = _a[_i];
|
18492 | if (cache[key][0] >= this.cacheExpiry)
|
18493 | delete cache[key];
|
18494 | else
|
18495 | allDeleted = false;
|
18496 | }
|
18497 | if (allDeleted)
|
18498 | delete this.pluginCache[name];
|
18499 | }
|
18500 | return {
|
18501 | modules: this.modules.map(function (module) { return module.toJSON(); }),
|
18502 | plugins: this.pluginCache
|
18503 | };
|
18504 | };
|
18505 | Graph.prototype.includeMarked = function (modules) {
|
18506 | if (this.treeshake) {
|
18507 | var treeshakingPass = 1;
|
18508 | do {
|
18509 | timeStart("treeshaking pass " + treeshakingPass, 3);
|
18510 | this.needsTreeshakingPass = false;
|
18511 | for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
|
18512 | var module = modules_1[_i];
|
18513 | if (module.isExecuted)
|
18514 | module.include();
|
18515 | }
|
18516 | timeEnd("treeshaking pass " + treeshakingPass++, 3);
|
18517 | } while (this.needsTreeshakingPass);
|
18518 | }
|
18519 | else {
|
18520 | // Necessary to properly replace namespace imports
|
18521 | for (var _a = 0, modules_2 = modules; _a < modules_2.length; _a++) {
|
18522 | var module = modules_2[_a];
|
18523 | module.includeAllInBundle();
|
18524 | }
|
18525 | }
|
18526 | };
|
18527 | Graph.prototype.warn = function (warning) {
|
18528 | warning.toString = function () {
|
18529 | var str = '';
|
18530 | if (warning.plugin)
|
18531 | str += "(" + warning.plugin + " plugin) ";
|
18532 | if (warning.loc)
|
18533 | str += relativeId(warning.loc.file) + " (" + warning.loc.line + ":" + warning.loc.column + ") ";
|
18534 | str += warning.message;
|
18535 | return str;
|
18536 | };
|
18537 | this.onwarn(warning);
|
18538 | };
|
18539 | Graph.prototype.link = function (entryModules) {
|
18540 | for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
|
18541 | var module = _a[_i];
|
18542 | module.linkDependencies();
|
18543 | }
|
18544 | var _b = analyseModuleExecution(entryModules), orderedModules = _b.orderedModules, cyclePaths = _b.cyclePaths;
|
18545 | for (var _c = 0, cyclePaths_1 = cyclePaths; _c < cyclePaths_1.length; _c++) {
|
18546 | var cyclePath = cyclePaths_1[_c];
|
18547 | this.warn({
|
18548 | code: 'CIRCULAR_DEPENDENCY',
|
18549 | importer: cyclePath[0],
|
18550 | message: "Circular dependency: " + cyclePath.join(' -> ')
|
18551 | });
|
18552 | }
|
18553 | this.modules = orderedModules;
|
18554 | for (var _d = 0, _e = this.modules; _d < _e.length; _d++) {
|
18555 | var module = _e[_d];
|
18556 | module.bindReferences();
|
18557 | }
|
18558 | this.warnForMissingExports();
|
18559 | };
|
18560 | Graph.prototype.warnForMissingExports = function () {
|
18561 | for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
|
18562 | var module = _a[_i];
|
18563 | for (var _b = 0, _c = Object.keys(module.importDescriptions); _b < _c.length; _b++) {
|
18564 | var importName = _c[_b];
|
18565 | var importDescription = module.importDescriptions[importName];
|
18566 | if (importDescription.name !== '*' &&
|
18567 | !importDescription.module.getVariableForExportName(importDescription.name)) {
|
18568 | module.warn({
|
18569 | code: 'NON_EXISTENT_EXPORT',
|
18570 | message: "Non-existent export '" + importDescription.name + "' is imported from " + relativeId(importDescription.module.id),
|
18571 | name: importDescription.name,
|
18572 | source: importDescription.module.id
|
18573 | }, importDescription.start);
|
18574 | }
|
18575 | }
|
18576 | }
|
18577 | };
|
18578 | return Graph;
|
18579 | }());
|
18580 |
|
18581 | function evalIfFn(strOrFn) {
|
18582 | switch (typeof strOrFn) {
|
18583 | case 'function':
|
18584 | return strOrFn();
|
18585 | case 'string':
|
18586 | return strOrFn;
|
18587 | default:
|
18588 | return '';
|
18589 | }
|
18590 | }
|
18591 | var concatSep = function (out, next) { return (next ? out + "\n" + next : out); };
|
18592 | var concatDblSep = function (out, next) { return (next ? out + "\n\n" + next : out); };
|
18593 | function createAddons(graph, options) {
|
18594 | var pluginDriver = graph.pluginDriver;
|
18595 | return Promise.all([
|
18596 | pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
|
18597 | pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
|
18598 | pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
|
18599 | pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
|
18600 | ])
|
18601 | .then(function (_a) {
|
18602 | var banner = _a[0], footer = _a[1], intro = _a[2], outro = _a[3];
|
18603 | if (intro)
|
18604 | intro += '\n\n';
|
18605 | if (outro)
|
18606 | outro = "\n\n" + outro;
|
18607 | if (banner.length)
|
18608 | banner += '\n';
|
18609 | if (footer.length)
|
18610 | footer = '\n' + footer;
|
18611 | return { intro: intro, outro: outro, banner: banner, footer: footer };
|
18612 | })
|
18613 | .catch(function (err) {
|
18614 | error({
|
18615 | code: 'ADDON_ERROR',
|
18616 | message: "Could not retrieve " + err.hook + ". Check configuration of " + err.plugin + ".\n\tError Message: " + err.message
|
18617 | });
|
18618 | });
|
18619 | }
|
18620 |
|
18621 | function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons) {
|
18622 | var usedIds = {};
|
18623 | var _a = chunks.reduce(function (_a, chunk) {
|
18624 | var entryChunks = _a[0], otherChunks = _a[1];
|
18625 | (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
|
18626 | ? entryChunks
|
18627 | : otherChunks).push(chunk);
|
18628 | return [entryChunks, otherChunks];
|
18629 | }, [[], []]), entryChunks = _a[0], otherChunks = _a[1];
|
18630 | // make sure entry chunk names take precedence with regard to deconflicting
|
18631 | var chunksForNaming = entryChunks.concat(otherChunks);
|
18632 | for (var i = 0; i < chunksForNaming.length; i++) {
|
18633 | var chunk = chunksForNaming[i];
|
18634 | if (outputOptions.file) {
|
18635 | chunk.id = path.basename(outputOptions.file);
|
18636 | }
|
18637 | else if (inputOptions.preserveModules) {
|
18638 | chunk.generateIdPreserveModules(inputBase, usedIds);
|
18639 | }
|
18640 | else {
|
18641 | var pattern = void 0, patternName = void 0;
|
18642 | if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
|
18643 | pattern = outputOptions.entryFileNames || '[name].js';
|
18644 | patternName = 'output.entryFileNames';
|
18645 | }
|
18646 | else {
|
18647 | pattern = outputOptions.chunkFileNames || '[name]-[hash].js';
|
18648 | patternName = 'output.chunkFileNames';
|
18649 | }
|
18650 | chunk.generateId(pattern, patternName, addons, outputOptions, usedIds);
|
18651 | }
|
18652 | usedIds[chunk.id] = true;
|
18653 | }
|
18654 | }
|
18655 |
|
18656 | // ported from https://github.com/substack/node-commondir
|
18657 | function commondir(files) {
|
18658 | if (files.length === 0)
|
18659 | return '/';
|
18660 | if (files.length === 1)
|
18661 | return path.dirname(files[0]);
|
18662 | var commonSegments = files.slice(1).reduce(function (commonSegments, file) {
|
18663 | var pathSegements = file.split(/\/+|\\+/);
|
18664 | var i;
|
18665 | for (i = 0; commonSegments[i] === pathSegements[i] &&
|
18666 | i < Math.min(commonSegments.length, pathSegements.length); i++)
|
18667 | ;
|
18668 | return commonSegments.slice(0, i);
|
18669 | }, files[0].split(/\/+|\\+/));
|
18670 | // Windows correctly handles paths with forward-slashes
|
18671 | return commonSegments.length > 1 ? commonSegments.join('/') : '/';
|
18672 | }
|
18673 |
|
18674 | function badExports(option, keys) {
|
18675 | error({
|
18676 | code: 'INVALID_EXPORT_OPTION',
|
18677 | message: "'" + option + "' was specified for output.exports, but entry module has following exports: " + keys.join(', ')
|
18678 | });
|
18679 | }
|
18680 | function getExportMode(chunk, _a) {
|
18681 | var exportMode = _a.exports, name = _a.name, format = _a.format;
|
18682 | var exportKeys = chunk.getExportNames();
|
18683 | if (exportMode === 'default') {
|
18684 | if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
|
18685 | badExports('default', exportKeys);
|
18686 | }
|
18687 | }
|
18688 | else if (exportMode === 'none' && exportKeys.length) {
|
18689 | badExports('none', exportKeys);
|
18690 | }
|
18691 | if (!exportMode || exportMode === 'auto') {
|
18692 | if (exportKeys.length === 0) {
|
18693 | exportMode = 'none';
|
18694 | }
|
18695 | else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
|
18696 | exportMode = 'default';
|
18697 | }
|
18698 | else {
|
18699 | if (chunk.facadeModule !== null &&
|
18700 | chunk.facadeModule.isEntryPoint &&
|
18701 | format !== 'es' &&
|
18702 | exportKeys.indexOf('default') !== -1) {
|
18703 | chunk.graph.warn({
|
18704 | code: 'MIXED_EXPORTS',
|
18705 | message: "Using named and default exports together. Consumers of your bundle will have to use " + (name ||
|
18706 | 'bundle') + "['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning",
|
18707 | url: "https://rollupjs.org/guide/en#output-exports"
|
18708 | });
|
18709 | }
|
18710 | exportMode = 'named';
|
18711 | }
|
18712 | }
|
18713 | if (!/(?:default|named|none)/.test(exportMode)) {
|
18714 | error({
|
18715 | code: 'INVALID_EXPORT_OPTION',
|
18716 | message: "output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')",
|
18717 | url: "https://rollupjs.org/guide/en#output-exports"
|
18718 | });
|
18719 | }
|
18720 | return exportMode;
|
18721 | }
|
18722 |
|
18723 | var createGetOption = function (config, command) { return function (name, defaultValue) {
|
18724 | return command[name] !== undefined
|
18725 | ? command[name]
|
18726 | : config[name] !== undefined
|
18727 | ? config[name]
|
18728 | : defaultValue;
|
18729 | }; };
|
18730 | var normalizeObjectOptionValue = function (optionValue) {
|
18731 | if (!optionValue) {
|
18732 | return optionValue;
|
18733 | }
|
18734 | if (typeof optionValue !== 'object') {
|
18735 | return {};
|
18736 | }
|
18737 | return optionValue;
|
18738 | };
|
18739 | var getObjectOption = function (config, command, name) {
|
18740 | var commandOption = normalizeObjectOptionValue(command[name]);
|
18741 | var configOption = normalizeObjectOptionValue(config[name]);
|
18742 | if (commandOption !== undefined) {
|
18743 | return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;
|
18744 | }
|
18745 | return configOption;
|
18746 | };
|
18747 | var defaultOnWarn = function (warning) {
|
18748 | if (typeof warning === 'string') {
|
18749 | console.warn(warning);
|
18750 | }
|
18751 | else {
|
18752 | console.warn(warning.message);
|
18753 | }
|
18754 | };
|
18755 | var getOnWarn = function (config, command, defaultOnWarnHandler) {
|
18756 | if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }
|
18757 | return command.silent
|
18758 | ? function () { }
|
18759 | : config.onwarn
|
18760 | ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }
|
18761 | : defaultOnWarnHandler;
|
18762 | };
|
18763 | // TODO Lukas manual chunks should receive the same treatment
|
18764 | var getExternal = function (config, command) {
|
18765 | var configExternal = config.external;
|
18766 | return typeof configExternal === 'function'
|
18767 | ? function (id) {
|
18768 | var rest = [];
|
18769 | for (var _i = 1; _i < arguments.length; _i++) {
|
18770 | rest[_i - 1] = arguments[_i];
|
18771 | }
|
18772 | return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;
|
18773 | }
|
18774 | : (configExternal || []).concat(command.external);
|
18775 | };
|
18776 | var commandAliases = {
|
18777 | c: 'config',
|
18778 | d: 'dir',
|
18779 | e: 'external',
|
18780 | f: 'format',
|
18781 | g: 'globals',
|
18782 | h: 'help',
|
18783 | i: 'input',
|
18784 | m: 'sourcemap',
|
18785 | n: 'name',
|
18786 | o: 'file',
|
18787 | v: 'version',
|
18788 | w: 'watch'
|
18789 | };
|
18790 | function mergeOptions(_a) {
|
18791 | var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, defaultOnWarnHandler = _a.defaultOnWarnHandler;
|
18792 | var command = getCommandOptions(rawCommandOptions);
|
18793 | var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
|
18794 | if (command.output) {
|
18795 | Object.assign(command, command.output);
|
18796 | }
|
18797 | var output = config.output;
|
18798 | var normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
|
18799 | if (normalizedOutputOptions.length === 0)
|
18800 | normalizedOutputOptions.push({});
|
18801 | var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {
|
18802 | return getOutputOptions(singleOutputOptions, command);
|
18803 | });
|
18804 | var unknownOptionErrors = [];
|
18805 | var validInputOptions = Object.keys(inputOptions);
|
18806 | addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
|
18807 | var validOutputOptions = Object.keys(outputOptions[0]);
|
18808 | addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');
|
18809 | var validCliOutputOptions = validOutputOptions.filter(function (option) { return option !== 'sourcemapPathTransform'; });
|
18810 | addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
|
18811 | return {
|
18812 | inputOptions: inputOptions,
|
18813 | optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
|
18814 | outputOptions: outputOptions
|
18815 | };
|
18816 | }
|
18817 | function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {
|
18818 | if (ignoredKeys === void 0) { ignoredKeys = /$./; }
|
18819 | var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });
|
18820 | if (unknownOptions.length > 0)
|
18821 | errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));
|
18822 | }
|
18823 | function getCommandOptions(rawCommandOptions) {
|
18824 | var command = __assign({}, rawCommandOptions);
|
18825 | command.external = rawCommandOptions.external ? rawCommandOptions.external.split(',') : [];
|
18826 | if (rawCommandOptions.globals) {
|
18827 | command.globals = Object.create(null);
|
18828 | rawCommandOptions.globals.split(',').forEach(function (str) {
|
18829 | var names = str.split(':');
|
18830 | command.globals[names[0]] = names[1];
|
18831 | // Add missing Module IDs to external.
|
18832 | if (command.external.indexOf(names[0]) === -1) {
|
18833 | command.external.push(names[0]);
|
18834 | }
|
18835 | });
|
18836 | }
|
18837 | return command;
|
18838 | }
|
18839 | function getInputOptions(config, command, defaultOnWarnHandler) {
|
18840 | if (command === void 0) { command = {}; }
|
18841 | var getOption = createGetOption(config, command);
|
18842 | var inputOptions = {
|
18843 | acorn: config.acorn,
|
18844 | acornInjectPlugins: config.acornInjectPlugins,
|
18845 | cache: getOption('cache'),
|
18846 | chunkGroupingSize: getOption('chunkGroupingSize', 5000),
|
18847 | context: config.context,
|
18848 | experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
|
18849 | experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
|
18850 | experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
|
18851 | external: getExternal(config, command),
|
18852 | inlineDynamicImports: getOption('inlineDynamicImports', false),
|
18853 | input: getOption('input', []),
|
18854 | manualChunks: getOption('manualChunks'),
|
18855 | moduleContext: config.moduleContext,
|
18856 | onwarn: getOnWarn(config, command, defaultOnWarnHandler),
|
18857 | perf: getOption('perf', false),
|
18858 | plugins: config.plugins,
|
18859 | preserveModules: getOption('preserveModules'),
|
18860 | preserveSymlinks: getOption('preserveSymlinks'),
|
18861 | shimMissingExports: getOption('shimMissingExports'),
|
18862 | treeshake: getObjectOption(config, command, 'treeshake'),
|
18863 | watch: config.watch
|
18864 | };
|
18865 | // support rollup({ cache: prevBuildObject })
|
18866 | if (inputOptions.cache && inputOptions.cache.cache)
|
18867 | inputOptions.cache = inputOptions.cache.cache;
|
18868 | return inputOptions;
|
18869 | }
|
18870 | function getOutputOptions(config, command) {
|
18871 | if (command === void 0) { command = {}; }
|
18872 | var getOption = createGetOption(config, command);
|
18873 | var format = getOption('format');
|
18874 | // Handle format aliases
|
18875 | switch (format) {
|
18876 | case 'esm':
|
18877 | case 'module':
|
18878 | format = 'es';
|
18879 | break;
|
18880 | case 'commonjs':
|
18881 | format = 'cjs';
|
18882 | }
|
18883 | return {
|
18884 | amd: __assign({}, config.amd, command.amd),
|
18885 | assetFileNames: getOption('assetFileNames'),
|
18886 | banner: getOption('banner'),
|
18887 | chunkFileNames: getOption('chunkFileNames'),
|
18888 | compact: getOption('compact', false),
|
18889 | dir: getOption('dir'),
|
18890 | dynamicImportFunction: getOption('dynamicImportFunction'),
|
18891 | entryFileNames: getOption('entryFileNames'),
|
18892 | esModule: getOption('esModule', true),
|
18893 | exports: getOption('exports'),
|
18894 | extend: getOption('extend'),
|
18895 | file: getOption('file'),
|
18896 | footer: getOption('footer'),
|
18897 | format: format === 'esm' ? 'es' : format,
|
18898 | freeze: getOption('freeze', true),
|
18899 | globals: getOption('globals'),
|
18900 | indent: getOption('indent', true),
|
18901 | interop: getOption('interop', true),
|
18902 | intro: getOption('intro'),
|
18903 | name: getOption('name'),
|
18904 | namespaceToStringTag: getOption('namespaceToStringTag', false),
|
18905 | noConflict: getOption('noConflict'),
|
18906 | outro: getOption('outro'),
|
18907 | paths: getOption('paths'),
|
18908 | preferConst: getOption('preferConst'),
|
18909 | sourcemap: getOption('sourcemap'),
|
18910 | sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
|
18911 | sourcemapFile: getOption('sourcemapFile'),
|
18912 | sourcemapPathTransform: getOption('sourcemapPathTransform'),
|
18913 | strict: getOption('strict', true)
|
18914 | };
|
18915 | }
|
18916 |
|
18917 | function checkOutputOptions(options) {
|
18918 | if (options.format === 'es6') {
|
18919 | error({
|
18920 | message: 'The "es6" output format is deprecated – use "esm" instead',
|
18921 | url: "https://rollupjs.org/guide/en#output-format"
|
18922 | });
|
18923 | }
|
18924 | if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
|
18925 | error({
|
18926 | message: "You must specify \"output.format\", which can be one of \"amd\", \"cjs\", \"system\", \"esm\", \"iife\" or \"umd\".",
|
18927 | url: "https://rollupjs.org/guide/en#output-format"
|
18928 | });
|
18929 | }
|
18930 | }
|
18931 | function getAbsoluteEntryModulePaths(chunks) {
|
18932 | var absoluteEntryModulePaths = [];
|
18933 | for (var _i = 0, chunks_1 = chunks; _i < chunks_1.length; _i++) {
|
18934 | var chunk = chunks_1[_i];
|
18935 | for (var _a = 0, _b = chunk.entryModules; _a < _b.length; _a++) {
|
18936 | var entryModule = _b[_a];
|
18937 | if (isAbsolute(entryModule.id)) {
|
18938 | absoluteEntryModulePaths.push(entryModule.id);
|
18939 | }
|
18940 | }
|
18941 | }
|
18942 | return absoluteEntryModulePaths;
|
18943 | }
|
18944 | var throwAsyncGenerateError = {
|
18945 | get: function () {
|
18946 | throw new Error("bundle.generate(...) now returns a Promise instead of a { code, map } object");
|
18947 | }
|
18948 | };
|
18949 | function applyOptionHook(inputOptions, plugin) {
|
18950 | if (plugin.options)
|
18951 | return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
|
18952 | return inputOptions;
|
18953 | }
|
18954 | function getInputOptions$1(rawInputOptions) {
|
18955 | if (!rawInputOptions) {
|
18956 | throw new Error('You must supply an options object to rollup');
|
18957 | }
|
18958 | var _a = mergeOptions({
|
18959 | config: rawInputOptions
|
18960 | }), inputOptions = _a.inputOptions, optionError = _a.optionError;
|
18961 | if (optionError)
|
18962 | inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
|
18963 | var plugins = inputOptions.plugins;
|
18964 | inputOptions.plugins = Array.isArray(plugins)
|
18965 | ? plugins.filter(Boolean)
|
18966 | : plugins
|
18967 | ? [plugins]
|
18968 | : [];
|
18969 | inputOptions = inputOptions.plugins.reduce(applyOptionHook, inputOptions);
|
18970 | if (inputOptions.inlineDynamicImports) {
|
18971 | if (inputOptions.preserveModules)
|
18972 | error({
|
18973 | code: 'INVALID_OPTION',
|
18974 | message: "\"preserveModules\" does not support the \"inlineDynamicImports\" option."
|
18975 | });
|
18976 | if (inputOptions.manualChunks)
|
18977 | error({
|
18978 | code: 'INVALID_OPTION',
|
18979 | message: '"manualChunks" option is not supported for "inlineDynamicImports".'
|
18980 | });
|
18981 | if (inputOptions.experimentalOptimizeChunks)
|
18982 | error({
|
18983 | code: 'INVALID_OPTION',
|
18984 | message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
|
18985 | });
|
18986 | if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
|
18987 | (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
|
18988 | error({
|
18989 | code: 'INVALID_OPTION',
|
18990 | message: 'Multiple inputs are not supported for "inlineDynamicImports".'
|
18991 | });
|
18992 | }
|
18993 | else if (inputOptions.preserveModules) {
|
18994 | if (inputOptions.manualChunks)
|
18995 | error({
|
18996 | code: 'INVALID_OPTION',
|
18997 | message: '"preserveModules" does not support the "manualChunks" option.'
|
18998 | });
|
18999 | if (inputOptions.experimentalOptimizeChunks)
|
19000 | error({
|
19001 | code: 'INVALID_OPTION',
|
19002 | message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
|
19003 | });
|
19004 | }
|
19005 | return inputOptions;
|
19006 | }
|
19007 | var curWatcher;
|
19008 | function setWatcher(watcher) {
|
19009 | curWatcher = watcher;
|
19010 | }
|
19011 | function rollup(rawInputOptions) {
|
19012 | try {
|
19013 | var inputOptions_1 = getInputOptions$1(rawInputOptions);
|
19014 | initialiseTimers(inputOptions_1);
|
19015 | var graph_1 = new Graph(inputOptions_1, curWatcher);
|
19016 | curWatcher = undefined;
|
19017 | // remove the cache option from the memory after graph creation (cache is not used anymore)
|
19018 | var useCache_1 = rawInputOptions.cache !== false;
|
19019 | delete inputOptions_1.cache;
|
19020 | delete rawInputOptions.cache;
|
19021 | timeStart('BUILD', 1);
|
19022 | return graph_1.pluginDriver
|
19023 | .hookParallel('buildStart', [inputOptions_1])
|
19024 | .then(function () {
|
19025 | return graph_1.build(inputOptions_1.input, inputOptions_1.manualChunks, inputOptions_1.inlineDynamicImports);
|
19026 | })
|
19027 | .then(function (chunks) { return graph_1.pluginDriver.hookParallel('buildEnd', []).then(function () { return chunks; }); }, function (err) {
|
19028 | return graph_1.pluginDriver.hookParallel('buildEnd', [err]).then(function () {
|
19029 | throw err;
|
19030 | });
|
19031 | })
|
19032 | .then(function (chunks) {
|
19033 | timeEnd('BUILD', 1);
|
19034 | // ensure we only do one optimization pass per build
|
19035 | var optimized = false;
|
19036 | function getOutputOptions(rawOutputOptions) {
|
19037 | return normalizeOutputOptions(inputOptions_1, rawOutputOptions, chunks.length > 1, graph_1.pluginDriver);
|
19038 | }
|
19039 | function generate(outputOptions, isWrite) {
|
19040 | timeStart('GENERATE', 1);
|
19041 | var assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
|
19042 | var outputBundle = graph_1.finaliseAssets(assetFileNames);
|
19043 | var inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
|
19044 | return graph_1.pluginDriver
|
19045 | .hookParallel('renderStart', [])
|
19046 | .then(function () { return createAddons(graph_1, outputOptions); })
|
19047 | .then(function (addons) {
|
19048 | // pre-render all chunks
|
19049 | for (var _i = 0, chunks_2 = chunks; _i < chunks_2.length; _i++) {
|
19050 | var chunk = chunks_2[_i];
|
19051 | if (!inputOptions_1.preserveModules)
|
19052 | chunk.generateInternalExports(outputOptions);
|
19053 | if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
|
19054 | chunk.exportMode = getExportMode(chunk, outputOptions);
|
19055 | }
|
19056 | for (var _a = 0, chunks_3 = chunks; _a < chunks_3.length; _a++) {
|
19057 | var chunk = chunks_3[_a];
|
19058 | chunk.preRender(outputOptions, inputBase);
|
19059 | }
|
19060 | if (!optimized && inputOptions_1.experimentalOptimizeChunks) {
|
19061 | optimizeChunks(chunks, outputOptions, inputOptions_1.chunkGroupingSize, inputBase);
|
19062 | optimized = true;
|
19063 | }
|
19064 | assignChunkIds(chunks, inputOptions_1, outputOptions, inputBase, addons);
|
19065 | var _loop_1 = function (i) {
|
19066 | var chunk = chunks[i];
|
19067 | var facadeModule = chunk.facadeModule;
|
19068 | outputBundle[chunk.id] = {
|
19069 | code: undefined,
|
19070 | dynamicImports: chunk.getDynamicImportIds(),
|
19071 | exports: chunk.getExportNames(),
|
19072 | facadeModuleId: facadeModule && facadeModule.id,
|
19073 | fileName: chunk.id,
|
19074 | imports: chunk.getImportIds(),
|
19075 | isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
|
19076 | isEntry: facadeModule !== null && facadeModule.isEntryPoint,
|
19077 | map: undefined,
|
19078 | modules: chunk.renderedModules,
|
19079 | get name() {
|
19080 | return chunk.getChunkName();
|
19081 | }
|
19082 | };
|
19083 | };
|
19084 | // assign to outputBundle
|
19085 | for (var i = 0; i < chunks.length; i++) {
|
19086 | _loop_1(i);
|
19087 | }
|
19088 | return Promise.all(chunks.map(function (chunk) {
|
19089 | var outputChunk = outputBundle[chunk.id];
|
19090 | return chunk.render(outputOptions, addons, outputChunk).then(function (rendered) {
|
19091 | outputChunk.code = rendered.code;
|
19092 | outputChunk.map = rendered.map;
|
19093 | return graph_1.pluginDriver.hookParallel('ongenerate', [
|
19094 | __assign({ bundle: outputChunk }, outputOptions),
|
19095 | outputChunk
|
19096 | ]);
|
19097 | });
|
19098 | })).then(function () { });
|
19099 | })
|
19100 | .catch(function (error) {
|
19101 | return graph_1.pluginDriver.hookParallel('renderError', [error]).then(function () {
|
19102 | throw error;
|
19103 | });
|
19104 | })
|
19105 | .then(function () {
|
19106 | // run generateBundle hook
|
19107 | // assets emitted during generateBundle are unique to that specific generate call
|
19108 | var assets = new Map(graph_1.assetsById);
|
19109 | var generateAssetPluginHooks = createAssetPluginHooks(assets, outputBundle, assetFileNames);
|
19110 | return graph_1.pluginDriver
|
19111 | .hookSeq('generateBundle', [outputOptions, outputBundle, isWrite], function (context) { return (__assign({}, context, generateAssetPluginHooks)); })
|
19112 | .then(function () {
|
19113 | // throw errors for assets not finalised with a source
|
19114 | assets.forEach(function (asset) {
|
19115 | if (asset.fileName === undefined)
|
19116 | finaliseAsset(asset, outputBundle, assetFileNames);
|
19117 | });
|
19118 | });
|
19119 | })
|
19120 | .then(function () {
|
19121 | timeEnd('GENERATE', 1);
|
19122 | return outputBundle;
|
19123 | });
|
19124 | }
|
19125 | var cache = useCache_1 ? graph_1.getCache() : undefined;
|
19126 | var result = {
|
19127 | cache: cache,
|
19128 | generate: (function (rawOutputOptions) {
|
19129 | var promise = generate(getOutputOptions(rawOutputOptions), false).then(function (result) {
|
19130 | return createOutput(result);
|
19131 | });
|
19132 | Object.defineProperty(promise, 'code', throwAsyncGenerateError);
|
19133 | Object.defineProperty(promise, 'map', throwAsyncGenerateError);
|
19134 | return promise;
|
19135 | }),
|
19136 | watchFiles: Object.keys(graph_1.watchFiles),
|
19137 | write: (function (rawOutputOptions) {
|
19138 | var outputOptions = getOutputOptions(rawOutputOptions);
|
19139 | if (!outputOptions.dir && !outputOptions.file) {
|
19140 | error({
|
19141 | code: 'MISSING_OPTION',
|
19142 | message: 'You must specify "output.file" or "output.dir" for the build.'
|
19143 | });
|
19144 | }
|
19145 | return generate(outputOptions, true).then(function (bundle) {
|
19146 | var chunkCnt = 0;
|
19147 | for (var _i = 0, _a = Object.keys(bundle); _i < _a.length; _i++) {
|
19148 | var fileName = _a[_i];
|
19149 | var file = bundle[fileName];
|
19150 | if (file.isAsset)
|
19151 | continue;
|
19152 | chunkCnt++;
|
19153 | if (chunkCnt > 1)
|
19154 | break;
|
19155 | }
|
19156 | if (chunkCnt > 1) {
|
19157 | if (outputOptions.sourcemapFile)
|
19158 | error({
|
19159 | code: 'INVALID_OPTION',
|
19160 | message: '"output.sourcemapFile" is only supported for single-file builds.'
|
19161 | });
|
19162 | if (typeof outputOptions.file === 'string')
|
19163 | error({
|
19164 | code: 'INVALID_OPTION',
|
19165 | message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
|
19166 | (typeof inputOptions_1.input !== 'string' ||
|
19167 | inputOptions_1.inlineDynamicImports === true
|
19168 | ? ''
|
19169 | : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
|
19170 | });
|
19171 | }
|
19172 | return Promise.all(Object.keys(bundle).map(function (chunkId) {
|
19173 | return writeOutputFile(graph_1, result, bundle[chunkId], outputOptions);
|
19174 | }))
|
19175 | .then(function () { return graph_1.pluginDriver.hookParallel('writeBundle', [bundle]); })
|
19176 | .then(function () { return createOutput(bundle); });
|
19177 | });
|
19178 | })
|
19179 | };
|
19180 | if (inputOptions_1.perf === true)
|
19181 | result.getTimings = getTimings;
|
19182 | return result;
|
19183 | });
|
19184 | }
|
19185 | catch (err) {
|
19186 | return Promise.reject(err);
|
19187 | }
|
19188 | }
|
19189 | var SortingFileType;
|
19190 | (function (SortingFileType) {
|
19191 | SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
|
19192 | SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
|
19193 | SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
|
19194 | })(SortingFileType || (SortingFileType = {}));
|
19195 | function getSortingFileType(file) {
|
19196 | if (file.isAsset) {
|
19197 | return SortingFileType.ASSET;
|
19198 | }
|
19199 | if (file.isEntry) {
|
19200 | return SortingFileType.ENTRY_CHUNK;
|
19201 | }
|
19202 | return SortingFileType.SECONDARY_CHUNK;
|
19203 | }
|
19204 | function createOutput(outputBundle) {
|
19205 | return {
|
19206 | output: Object.keys(outputBundle)
|
19207 | .map(function (fileName) { return outputBundle[fileName]; })
|
19208 | .sort(function (outputFileA, outputFileB) {
|
19209 | var fileTypeA = getSortingFileType(outputFileA);
|
19210 | var fileTypeB = getSortingFileType(outputFileB);
|
19211 | if (fileTypeA === fileTypeB)
|
19212 | return 0;
|
19213 | return fileTypeA < fileTypeB ? -1 : 1;
|
19214 | })
|
19215 | };
|
19216 | }
|
19217 | function isOutputAsset(file) {
|
19218 | return file.isAsset === true;
|
19219 | }
|
19220 | function writeOutputFile(graph, build, outputFile, outputOptions) {
|
19221 | var fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
|
19222 | var writeSourceMapPromise;
|
19223 | var source;
|
19224 | if (isOutputAsset(outputFile)) {
|
19225 | source = outputFile.source;
|
19226 | }
|
19227 | else {
|
19228 | source = outputFile.code;
|
19229 | if (outputOptions.sourcemap && outputFile.map) {
|
19230 | var url = void 0;
|
19231 | if (outputOptions.sourcemap === 'inline') {
|
19232 | url = outputFile.map.toUrl();
|
19233 | }
|
19234 | else {
|
19235 | url = path.basename(outputFile.fileName) + ".map";
|
19236 | writeSourceMapPromise = writeFile(fileName + ".map", outputFile.map.toString());
|
19237 | }
|
19238 | source += "//# " + SOURCEMAPPING_URL + "=" + url + "\n";
|
19239 | }
|
19240 | }
|
19241 | return writeFile(fileName, source)
|
19242 | .then(function () { return writeSourceMapPromise; })
|
19243 | .then(function () {
|
19244 | return !isOutputAsset(outputFile) &&
|
19245 | graph.pluginDriver.hookSeq('onwrite', [
|
19246 | __assign({ bundle: build }, outputOptions),
|
19247 | outputFile
|
19248 | ]);
|
19249 | })
|
19250 | .then(function () { });
|
19251 | }
|
19252 | function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
|
19253 | if (!rawOutputOptions) {
|
19254 | throw new Error('You must supply an options object');
|
19255 | }
|
19256 | var mergedOptions = mergeOptions({
|
19257 | config: {
|
19258 | output: __assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output)
|
19259 | }
|
19260 | });
|
19261 | if (mergedOptions.optionError)
|
19262 | throw new Error(mergedOptions.optionError);
|
19263 | // now outputOptions is an array, but rollup.rollup API doesn't support arrays
|
19264 | var mergedOutputOptions = mergedOptions.outputOptions[0];
|
19265 | var outputOptionsReducer = function (outputOptions, result) {
|
19266 | return result || outputOptions;
|
19267 | };
|
19268 | var outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer);
|
19269 | checkOutputOptions(outputOptions);
|
19270 | if (typeof outputOptions.file === 'string') {
|
19271 | if (typeof outputOptions.dir === 'string')
|
19272 | error({
|
19273 | code: 'INVALID_OPTION',
|
19274 | message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
|
19275 | });
|
19276 | if (inputOptions.preserveModules) {
|
19277 | error({
|
19278 | code: 'INVALID_OPTION',
|
19279 | message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
|
19280 | });
|
19281 | }
|
19282 | if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
|
19283 | error({
|
19284 | code: 'INVALID_OPTION',
|
19285 | message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
|
19286 | });
|
19287 | }
|
19288 | if (hasMultipleChunks) {
|
19289 | if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
|
19290 | error({
|
19291 | code: 'INVALID_OPTION',
|
19292 | message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
|
19293 | });
|
19294 | if (typeof outputOptions.file === 'string')
|
19295 | error({
|
19296 | code: 'INVALID_OPTION',
|
19297 | message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
|
19298 | });
|
19299 | }
|
19300 | return outputOptions;
|
19301 | }
|
19302 |
|
19303 | var types = {
|
19304 | ROOT : 0,
|
19305 | GROUP : 1,
|
19306 | POSITION : 2,
|
19307 | SET : 3,
|
19308 | RANGE : 4,
|
19309 | REPETITION : 5,
|
19310 | REFERENCE : 6,
|
19311 | CHAR : 7,
|
19312 | };
|
19313 |
|
19314 | var INTS = function() {
|
19315 | return [{ type: types.RANGE , from: 48, to: 57 }];
|
19316 | };
|
19317 |
|
19318 | var WORDS = function() {
|
19319 | return [
|
19320 | { type: types.CHAR, value: 95 },
|
19321 | { type: types.RANGE, from: 97, to: 122 },
|
19322 | { type: types.RANGE, from: 65, to: 90 }
|
19323 | ].concat(INTS());
|
19324 | };
|
19325 |
|
19326 | var WHITESPACE$1 = function() {
|
19327 | return [
|
19328 | { type: types.CHAR, value: 9 },
|
19329 | { type: types.CHAR, value: 10 },
|
19330 | { type: types.CHAR, value: 11 },
|
19331 | { type: types.CHAR, value: 12 },
|
19332 | { type: types.CHAR, value: 13 },
|
19333 | { type: types.CHAR, value: 32 },
|
19334 | { type: types.CHAR, value: 160 },
|
19335 | { type: types.CHAR, value: 5760 },
|
19336 | { type: types.CHAR, value: 6158 },
|
19337 | { type: types.CHAR, value: 8192 },
|
19338 | { type: types.CHAR, value: 8193 },
|
19339 | { type: types.CHAR, value: 8194 },
|
19340 | { type: types.CHAR, value: 8195 },
|
19341 | { type: types.CHAR, value: 8196 },
|
19342 | { type: types.CHAR, value: 8197 },
|
19343 | { type: types.CHAR, value: 8198 },
|
19344 | { type: types.CHAR, value: 8199 },
|
19345 | { type: types.CHAR, value: 8200 },
|
19346 | { type: types.CHAR, value: 8201 },
|
19347 | { type: types.CHAR, value: 8202 },
|
19348 | { type: types.CHAR, value: 8232 },
|
19349 | { type: types.CHAR, value: 8233 },
|
19350 | { type: types.CHAR, value: 8239 },
|
19351 | { type: types.CHAR, value: 8287 },
|
19352 | { type: types.CHAR, value: 12288 },
|
19353 | { type: types.CHAR, value: 65279 }
|
19354 | ];
|
19355 | };
|
19356 |
|
19357 | var NOTANYCHAR = function() {
|
19358 | return [
|
19359 | { type: types.CHAR, value: 10 },
|
19360 | { type: types.CHAR, value: 13 },
|
19361 | { type: types.CHAR, value: 8232 },
|
19362 | { type: types.CHAR, value: 8233 },
|
19363 | ];
|
19364 | };
|
19365 |
|
19366 | // Predefined class objects.
|
19367 | var words = function() {
|
19368 | return { type: types.SET, set: WORDS(), not: false };
|
19369 | };
|
19370 |
|
19371 | var notWords = function() {
|
19372 | return { type: types.SET, set: WORDS(), not: true };
|
19373 | };
|
19374 |
|
19375 | var ints = function() {
|
19376 | return { type: types.SET, set: INTS(), not: false };
|
19377 | };
|
19378 |
|
19379 | var notInts = function() {
|
19380 | return { type: types.SET, set: INTS(), not: true };
|
19381 | };
|
19382 |
|
19383 | var whitespace = function() {
|
19384 | return { type: types.SET, set: WHITESPACE$1(), not: false };
|
19385 | };
|
19386 |
|
19387 | var notWhitespace = function() {
|
19388 | return { type: types.SET, set: WHITESPACE$1(), not: true };
|
19389 | };
|
19390 |
|
19391 | var anyChar = function() {
|
19392 | return { type: types.SET, set: NOTANYCHAR(), not: true };
|
19393 | };
|
19394 |
|
19395 | var sets = {
|
19396 | words: words,
|
19397 | notWords: notWords,
|
19398 | ints: ints,
|
19399 | notInts: notInts,
|
19400 | whitespace: whitespace,
|
19401 | notWhitespace: notWhitespace,
|
19402 | anyChar: anyChar
|
19403 | };
|
19404 |
|
19405 | var util = createCommonjsModule(function (module, exports) {
|
19406 | // All of these are private and only used by randexp.
|
19407 | // It's assumed that they will always be called with the correct input.
|
19408 |
|
19409 | var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
|
19410 | var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
|
19411 |
|
19412 | /**
|
19413 | * Finds character representations in str and convert all to
|
19414 | * their respective characters
|
19415 | *
|
19416 | * @param {String} str
|
19417 | * @return {String}
|
19418 | */
|
19419 | exports.strToChars = function(str) {
|
19420 | /* jshint maxlen: false */
|
19421 | var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
|
19422 | str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
|
19423 | if (lbs) {
|
19424 | return s;
|
19425 | }
|
19426 |
|
19427 | var code = b ? 8 :
|
19428 | a16 ? parseInt(a16, 16) :
|
19429 | b16 ? parseInt(b16, 16) :
|
19430 | c8 ? parseInt(c8, 8) :
|
19431 | dctrl ? CTRL.indexOf(dctrl) :
|
19432 | SLSH[eslsh];
|
19433 |
|
19434 | var c = String.fromCharCode(code);
|
19435 |
|
19436 | // Escape special regex characters.
|
19437 | if (/[\[\]{}\^$.|?*+()]/.test(c)) {
|
19438 | c = '\\' + c;
|
19439 | }
|
19440 |
|
19441 | return c;
|
19442 | });
|
19443 |
|
19444 | return str;
|
19445 | };
|
19446 |
|
19447 |
|
19448 | /**
|
19449 | * turns class into tokens
|
19450 | * reads str until it encounters a ] not preceeded by a \
|
19451 | *
|
19452 | * @param {String} str
|
19453 | * @param {String} regexpStr
|
19454 | * @return {Array.<Array.<Object>, Number>}
|
19455 | */
|
19456 | exports.tokenizeClass = function(str, regexpStr) {
|
19457 | /* jshint maxlen: false */
|
19458 | var tokens = [];
|
19459 | var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g;
|
19460 | var rs, c;
|
19461 |
|
19462 |
|
19463 | while ((rs = regexp.exec(str)) != null) {
|
19464 | if (rs[1]) {
|
19465 | tokens.push(sets.words());
|
19466 |
|
19467 | } else if (rs[2]) {
|
19468 | tokens.push(sets.ints());
|
19469 |
|
19470 | } else if (rs[3]) {
|
19471 | tokens.push(sets.whitespace());
|
19472 |
|
19473 | } else if (rs[4]) {
|
19474 | tokens.push(sets.notWords());
|
19475 |
|
19476 | } else if (rs[5]) {
|
19477 | tokens.push(sets.notInts());
|
19478 |
|
19479 | } else if (rs[6]) {
|
19480 | tokens.push(sets.notWhitespace());
|
19481 |
|
19482 | } else if (rs[7]) {
|
19483 | tokens.push({
|
19484 | type: types.RANGE,
|
19485 | from: (rs[8] || rs[9]).charCodeAt(0),
|
19486 | to: rs[10].charCodeAt(0),
|
19487 | });
|
19488 |
|
19489 | } else if (c = rs[12]) {
|
19490 | tokens.push({
|
19491 | type: types.CHAR,
|
19492 | value: c.charCodeAt(0),
|
19493 | });
|
19494 |
|
19495 | } else {
|
19496 | return [tokens, regexp.lastIndex];
|
19497 | }
|
19498 | }
|
19499 |
|
19500 | exports.error(regexpStr, 'Unterminated character class');
|
19501 | };
|
19502 |
|
19503 |
|
19504 | /**
|
19505 | * Shortcut to throw errors.
|
19506 | *
|
19507 | * @param {String} regexp
|
19508 | * @param {String} msg
|
19509 | */
|
19510 | exports.error = function(regexp, msg) {
|
19511 | throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
|
19512 | };
|
19513 | });
|
19514 |
|
19515 | var wordBoundary = function() {
|
19516 | return { type: types.POSITION, value: 'b' };
|
19517 | };
|
19518 |
|
19519 | var nonWordBoundary = function() {
|
19520 | return { type: types.POSITION, value: 'B' };
|
19521 | };
|
19522 |
|
19523 | var begin = function() {
|
19524 | return { type: types.POSITION, value: '^' };
|
19525 | };
|
19526 |
|
19527 | var end = function() {
|
19528 | return { type: types.POSITION, value: '$' };
|
19529 | };
|
19530 |
|
19531 | var positions = {
|
19532 | wordBoundary: wordBoundary,
|
19533 | nonWordBoundary: nonWordBoundary,
|
19534 | begin: begin,
|
19535 | end: end
|
19536 | };
|
19537 |
|
19538 | var lib = function(regexpStr) {
|
19539 | var i = 0, l, c,
|
19540 | start = { type: types.ROOT, stack: []},
|
19541 |
|
19542 | // Keep track of last clause/group and stack.
|
19543 | lastGroup = start,
|
19544 | last = start.stack,
|
19545 | groupStack = [];
|
19546 |
|
19547 |
|
19548 | var repeatErr = function(i) {
|
19549 | util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
|
19550 | };
|
19551 |
|
19552 | // Decode a few escaped characters.
|
19553 | var str = util.strToChars(regexpStr);
|
19554 | l = str.length;
|
19555 |
|
19556 | // Iterate through each character in string.
|
19557 | while (i < l) {
|
19558 | c = str[i++];
|
19559 |
|
19560 | switch (c) {
|
19561 | // Handle escaped characters, inclues a few sets.
|
19562 | case '\\':
|
19563 | c = str[i++];
|
19564 |
|
19565 | switch (c) {
|
19566 | case 'b':
|
19567 | last.push(positions.wordBoundary());
|
19568 | break;
|
19569 |
|
19570 | case 'B':
|
19571 | last.push(positions.nonWordBoundary());
|
19572 | break;
|
19573 |
|
19574 | case 'w':
|
19575 | last.push(sets.words());
|
19576 | break;
|
19577 |
|
19578 | case 'W':
|
19579 | last.push(sets.notWords());
|
19580 | break;
|
19581 |
|
19582 | case 'd':
|
19583 | last.push(sets.ints());
|
19584 | break;
|
19585 |
|
19586 | case 'D':
|
19587 | last.push(sets.notInts());
|
19588 | break;
|
19589 |
|
19590 | case 's':
|
19591 | last.push(sets.whitespace());
|
19592 | break;
|
19593 |
|
19594 | case 'S':
|
19595 | last.push(sets.notWhitespace());
|
19596 | break;
|
19597 |
|
19598 | default:
|
19599 | // Check if c is integer.
|
19600 | // In which case it's a reference.
|
19601 | if (/\d/.test(c)) {
|
19602 | last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
|
19603 |
|
19604 | // Escaped character.
|
19605 | } else {
|
19606 | last.push({ type: types.CHAR, value: c.charCodeAt(0) });
|
19607 | }
|
19608 | }
|
19609 |
|
19610 | break;
|
19611 |
|
19612 |
|
19613 | // Positionals.
|
19614 | case '^':
|
19615 | last.push(positions.begin());
|
19616 | break;
|
19617 |
|
19618 | case '$':
|
19619 | last.push(positions.end());
|
19620 | break;
|
19621 |
|
19622 |
|
19623 | // Handle custom sets.
|
19624 | case '[':
|
19625 | // Check if this class is 'anti' i.e. [^abc].
|
19626 | var not;
|
19627 | if (str[i] === '^') {
|
19628 | not = true;
|
19629 | i++;
|
19630 | } else {
|
19631 | not = false;
|
19632 | }
|
19633 |
|
19634 | // Get all the characters in class.
|
19635 | var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
|
19636 |
|
19637 | // Increase index by length of class.
|
19638 | i += classTokens[1];
|
19639 | last.push({
|
19640 | type: types.SET,
|
19641 | set: classTokens[0],
|
19642 | not: not,
|
19643 | });
|
19644 |
|
19645 | break;
|
19646 |
|
19647 |
|
19648 | // Class of any character except \n.
|
19649 | case '.':
|
19650 | last.push(sets.anyChar());
|
19651 | break;
|
19652 |
|
19653 |
|
19654 | // Push group onto stack.
|
19655 | case '(':
|
19656 | // Create group.
|
19657 | var group = {
|
19658 | type: types.GROUP,
|
19659 | stack: [],
|
19660 | remember: true,
|
19661 | };
|
19662 |
|
19663 | c = str[i];
|
19664 |
|
19665 | // If if this is a special kind of group.
|
19666 | if (c === '?') {
|
19667 | c = str[i + 1];
|
19668 | i += 2;
|
19669 |
|
19670 | // Match if followed by.
|
19671 | if (c === '=') {
|
19672 | group.followedBy = true;
|
19673 |
|
19674 | // Match if not followed by.
|
19675 | } else if (c === '!') {
|
19676 | group.notFollowedBy = true;
|
19677 |
|
19678 | } else if (c !== ':') {
|
19679 | util.error(regexpStr,
|
19680 | 'Invalid group, character \'' + c +
|
19681 | '\' after \'?\' at column ' + (i - 1));
|
19682 | }
|
19683 |
|
19684 | group.remember = false;
|
19685 | }
|
19686 |
|
19687 | // Insert subgroup into current group stack.
|
19688 | last.push(group);
|
19689 |
|
19690 | // Remember the current group for when the group closes.
|
19691 | groupStack.push(lastGroup);
|
19692 |
|
19693 | // Make this new group the current group.
|
19694 | lastGroup = group;
|
19695 | last = group.stack;
|
19696 | break;
|
19697 |
|
19698 |
|
19699 | // Pop group out of stack.
|
19700 | case ')':
|
19701 | if (groupStack.length === 0) {
|
19702 | util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
|
19703 | }
|
19704 | lastGroup = groupStack.pop();
|
19705 |
|
19706 | // Check if this group has a PIPE.
|
19707 | // To get back the correct last stack.
|
19708 | last = lastGroup.options ?
|
19709 | lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
|
19710 | break;
|
19711 |
|
19712 |
|
19713 | // Use pipe character to give more choices.
|
19714 | case '|':
|
19715 | // Create array where options are if this is the first PIPE
|
19716 | // in this clause.
|
19717 | if (!lastGroup.options) {
|
19718 | lastGroup.options = [lastGroup.stack];
|
19719 | delete lastGroup.stack;
|
19720 | }
|
19721 |
|
19722 | // Create a new stack and add to options for rest of clause.
|
19723 | var stack = [];
|
19724 | lastGroup.options.push(stack);
|
19725 | last = stack;
|
19726 | break;
|
19727 |
|
19728 |
|
19729 | // Repetition.
|
19730 | // For every repetition, remove last element from last stack
|
19731 | // then insert back a RANGE object.
|
19732 | // This design is chosen because there could be more than
|
19733 | // one repetition symbols in a regex i.e. `a?+{2,3}`.
|
19734 | case '{':
|
19735 | var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
|
19736 | if (rs !== null) {
|
19737 | if (last.length === 0) {
|
19738 | repeatErr(i);
|
19739 | }
|
19740 | min = parseInt(rs[1], 10);
|
19741 | max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
|
19742 | i += rs[0].length;
|
19743 |
|
19744 | last.push({
|
19745 | type: types.REPETITION,
|
19746 | min: min,
|
19747 | max: max,
|
19748 | value: last.pop(),
|
19749 | });
|
19750 | } else {
|
19751 | last.push({
|
19752 | type: types.CHAR,
|
19753 | value: 123,
|
19754 | });
|
19755 | }
|
19756 | break;
|
19757 |
|
19758 | case '?':
|
19759 | if (last.length === 0) {
|
19760 | repeatErr(i);
|
19761 | }
|
19762 | last.push({
|
19763 | type: types.REPETITION,
|
19764 | min: 0,
|
19765 | max: 1,
|
19766 | value: last.pop(),
|
19767 | });
|
19768 | break;
|
19769 |
|
19770 | case '+':
|
19771 | if (last.length === 0) {
|
19772 | repeatErr(i);
|
19773 | }
|
19774 | last.push({
|
19775 | type: types.REPETITION,
|
19776 | min: 1,
|
19777 | max: Infinity,
|
19778 | value: last.pop(),
|
19779 | });
|
19780 | break;
|
19781 |
|
19782 | case '*':
|
19783 | if (last.length === 0) {
|
19784 | repeatErr(i);
|
19785 | }
|
19786 | last.push({
|
19787 | type: types.REPETITION,
|
19788 | min: 0,
|
19789 | max: Infinity,
|
19790 | value: last.pop(),
|
19791 | });
|
19792 | break;
|
19793 |
|
19794 |
|
19795 | // Default is a character that is not `\[](){}?+*^$`.
|
19796 | default:
|
19797 | last.push({
|
19798 | type: types.CHAR,
|
19799 | value: c.charCodeAt(0),
|
19800 | });
|
19801 | }
|
19802 |
|
19803 | }
|
19804 |
|
19805 | // Check if any groups have not been closed.
|
19806 | if (groupStack.length !== 0) {
|
19807 | util.error(regexpStr, 'Unterminated group');
|
19808 | }
|
19809 |
|
19810 | return start;
|
19811 | };
|
19812 |
|
19813 | var types_1 = types;
|
19814 | lib.types = types_1;
|
19815 |
|
19816 | var types$1 = lib.types;
|
19817 |
|
19818 | var safeRegex = function (re, opts) {
|
19819 | if (!opts) opts = {};
|
19820 | var replimit = opts.limit === undefined ? 25 : opts.limit;
|
19821 |
|
19822 | if (isRegExp(re)) re = re.source;
|
19823 | else if (typeof re !== 'string') re = String(re);
|
19824 |
|
19825 | try { re = lib(re); }
|
19826 | catch (err) { return false }
|
19827 |
|
19828 | var reps = 0;
|
19829 | return (function walk (node, starHeight) {
|
19830 | if (node.type === types$1.REPETITION) {
|
19831 | starHeight ++;
|
19832 | reps ++;
|
19833 | if (starHeight > 1) return false;
|
19834 | if (reps > replimit) return false;
|
19835 | }
|
19836 |
|
19837 | if (node.options) {
|
19838 | for (var i = 0, len = node.options.length; i < len; i++) {
|
19839 | var ok = walk({ stack: node.options[i] }, starHeight);
|
19840 | if (!ok) return false;
|
19841 | }
|
19842 | }
|
19843 | var stack = node.stack || (node.value && node.value.stack);
|
19844 | if (!stack) return true;
|
19845 |
|
19846 | for (var i = 0; i < stack.length; i++) {
|
19847 | var ok = walk(stack[i], starHeight);
|
19848 | if (!ok) return false;
|
19849 | }
|
19850 |
|
19851 | return true;
|
19852 | })(re, 0);
|
19853 | };
|
19854 |
|
19855 | function isRegExp (x) {
|
19856 | return {}.toString.call(x) === '[object RegExp]';
|
19857 | }
|
19858 |
|
19859 | /*!
|
19860 | * isobject <https://github.com/jonschlinkert/isobject>
|
19861 | *
|
19862 | * Copyright (c) 2014-2017, Jon Schlinkert.
|
19863 | * Released under the MIT License.
|
19864 | */
|
19865 |
|
19866 | var isobject = function isObject(val) {
|
19867 | return val != null && typeof val === 'object' && Array.isArray(val) === false;
|
19868 | };
|
19869 |
|
19870 | var toString$1 = Object.prototype.toString;
|
19871 |
|
19872 | var kindOf = function kindOf(val) {
|
19873 | if (val === void 0) return 'undefined';
|
19874 | if (val === null) return 'null';
|
19875 |
|
19876 | var type = typeof val;
|
19877 | if (type === 'boolean') return 'boolean';
|
19878 | if (type === 'string') return 'string';
|
19879 | if (type === 'number') return 'number';
|
19880 | if (type === 'symbol') return 'symbol';
|
19881 | if (type === 'function') {
|
19882 | return isGeneratorFn(val) ? 'generatorfunction' : 'function';
|
19883 | }
|
19884 |
|
19885 | if (isArray(val)) return 'array';
|
19886 | if (isBuffer(val)) return 'buffer';
|
19887 | if (isArguments(val)) return 'arguments';
|
19888 | if (isDate(val)) return 'date';
|
19889 | if (isError(val)) return 'error';
|
19890 | if (isRegexp(val)) return 'regexp';
|
19891 |
|
19892 | switch (ctorName(val)) {
|
19893 | case 'Symbol': return 'symbol';
|
19894 | case 'Promise': return 'promise';
|
19895 |
|
19896 | // Set, Map, WeakSet, WeakMap
|
19897 | case 'WeakMap': return 'weakmap';
|
19898 | case 'WeakSet': return 'weakset';
|
19899 | case 'Map': return 'map';
|
19900 | case 'Set': return 'set';
|
19901 |
|
19902 | // 8-bit typed arrays
|
19903 | case 'Int8Array': return 'int8array';
|
19904 | case 'Uint8Array': return 'uint8array';
|
19905 | case 'Uint8ClampedArray': return 'uint8clampedarray';
|
19906 |
|
19907 | // 16-bit typed arrays
|
19908 | case 'Int16Array': return 'int16array';
|
19909 | case 'Uint16Array': return 'uint16array';
|
19910 |
|
19911 | // 32-bit typed arrays
|
19912 | case 'Int32Array': return 'int32array';
|
19913 | case 'Uint32Array': return 'uint32array';
|
19914 | case 'Float32Array': return 'float32array';
|
19915 | case 'Float64Array': return 'float64array';
|
19916 | }
|
19917 |
|
19918 | if (isGeneratorObj(val)) {
|
19919 | return 'generator';
|
19920 | }
|
19921 |
|
19922 | // Non-plain objects
|
19923 | type = toString$1.call(val);
|
19924 | switch (type) {
|
19925 | case '[object Object]': return 'object';
|
19926 | // iterators
|
19927 | case '[object Map Iterator]': return 'mapiterator';
|
19928 | case '[object Set Iterator]': return 'setiterator';
|
19929 | case '[object String Iterator]': return 'stringiterator';
|
19930 | case '[object Array Iterator]': return 'arrayiterator';
|
19931 | }
|
19932 |
|
19933 | // other
|
19934 | return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
|
19935 | };
|
19936 |
|
19937 | function ctorName(val) {
|
19938 | return val.constructor ? val.constructor.name : null;
|
19939 | }
|
19940 |
|
19941 | function isArray(val) {
|
19942 | if (Array.isArray) return Array.isArray(val);
|
19943 | return val instanceof Array;
|
19944 | }
|
19945 |
|
19946 | function isError(val) {
|
19947 | return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');
|
19948 | }
|
19949 |
|
19950 | function isDate(val) {
|
19951 | if (val instanceof Date) return true;
|
19952 | return typeof val.toDateString === 'function'
|
19953 | && typeof val.getDate === 'function'
|
19954 | && typeof val.setDate === 'function';
|
19955 | }
|
19956 |
|
19957 | function isRegexp(val) {
|
19958 | if (val instanceof RegExp) return true;
|
19959 | return typeof val.flags === 'string'
|
19960 | && typeof val.ignoreCase === 'boolean'
|
19961 | && typeof val.multiline === 'boolean'
|
19962 | && typeof val.global === 'boolean';
|
19963 | }
|
19964 |
|
19965 | function isGeneratorFn(name, val) {
|
19966 | return ctorName(name) === 'GeneratorFunction';
|
19967 | }
|
19968 |
|
19969 | function isGeneratorObj(val) {
|
19970 | return typeof val.throw === 'function'
|
19971 | && typeof val.return === 'function'
|
19972 | && typeof val.next === 'function';
|
19973 | }
|
19974 |
|
19975 | function isArguments(val) {
|
19976 | try {
|
19977 | if (typeof val.length === 'number' && typeof val.callee === 'function') {
|
19978 | return true;
|
19979 | }
|
19980 | } catch (err) {
|
19981 | if (err.message.indexOf('callee') !== -1) {
|
19982 | return true;
|
19983 | }
|
19984 | }
|
19985 | return false;
|
19986 | }
|
19987 |
|
19988 | /**
|
19989 | * If you need to support Safari 5-7 (8-10 yr-old browser),
|
19990 | * take a look at https://github.com/feross/is-buffer
|
19991 | */
|
19992 |
|
19993 | function isBuffer(val) {
|
19994 | if (val.constructor && typeof val.constructor.isBuffer === 'function') {
|
19995 | return val.constructor.isBuffer(val);
|
19996 | }
|
19997 | return false;
|
19998 | }
|
19999 |
|
20000 | // accessor descriptor properties
|
20001 | var accessor = {
|
20002 | get: 'function',
|
20003 | set: 'function',
|
20004 | configurable: 'boolean',
|
20005 | enumerable: 'boolean'
|
20006 | };
|
20007 |
|
20008 | function isAccessorDescriptor(obj, prop) {
|
20009 | if (typeof prop === 'string') {
|
20010 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
20011 | return typeof val !== 'undefined';
|
20012 | }
|
20013 |
|
20014 | if (kindOf(obj) !== 'object') {
|
20015 | return false;
|
20016 | }
|
20017 |
|
20018 | if (has$1(obj, 'value') || has$1(obj, 'writable')) {
|
20019 | return false;
|
20020 | }
|
20021 |
|
20022 | if (!has$1(obj, 'get') || typeof obj.get !== 'function') {
|
20023 | return false;
|
20024 | }
|
20025 |
|
20026 | // tldr: it's valid to have "set" be undefined
|
20027 | // "set" might be undefined if `Object.getOwnPropertyDescriptor`
|
20028 | // was used to get the value, and only `get` was defined by the user
|
20029 | if (has$1(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
|
20030 | return false;
|
20031 | }
|
20032 |
|
20033 | for (var key in obj) {
|
20034 | if (!accessor.hasOwnProperty(key)) {
|
20035 | continue;
|
20036 | }
|
20037 |
|
20038 | if (kindOf(obj[key]) === accessor[key]) {
|
20039 | continue;
|
20040 | }
|
20041 |
|
20042 | if (typeof obj[key] !== 'undefined') {
|
20043 | return false;
|
20044 | }
|
20045 | }
|
20046 | return true;
|
20047 | }
|
20048 |
|
20049 | function has$1(obj, key) {
|
20050 | return {}.hasOwnProperty.call(obj, key);
|
20051 | }
|
20052 |
|
20053 | /**
|
20054 | * Expose `isAccessorDescriptor`
|
20055 | */
|
20056 |
|
20057 | var isAccessorDescriptor_1 = isAccessorDescriptor;
|
20058 |
|
20059 | var isDataDescriptor = function isDataDescriptor(obj, prop) {
|
20060 | // data descriptor properties
|
20061 | var data = {
|
20062 | configurable: 'boolean',
|
20063 | enumerable: 'boolean',
|
20064 | writable: 'boolean'
|
20065 | };
|
20066 |
|
20067 | if (kindOf(obj) !== 'object') {
|
20068 | return false;
|
20069 | }
|
20070 |
|
20071 | if (typeof prop === 'string') {
|
20072 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
20073 | return typeof val !== 'undefined';
|
20074 | }
|
20075 |
|
20076 | if (!('value' in obj) && !('writable' in obj)) {
|
20077 | return false;
|
20078 | }
|
20079 |
|
20080 | for (var key in obj) {
|
20081 | if (key === 'value') continue;
|
20082 |
|
20083 | if (!data.hasOwnProperty(key)) {
|
20084 | continue;
|
20085 | }
|
20086 |
|
20087 | if (kindOf(obj[key]) === data[key]) {
|
20088 | continue;
|
20089 | }
|
20090 |
|
20091 | if (typeof obj[key] !== 'undefined') {
|
20092 | return false;
|
20093 | }
|
20094 | }
|
20095 | return true;
|
20096 | };
|
20097 |
|
20098 | var isDescriptor = function isDescriptor(obj, key) {
|
20099 | if (kindOf(obj) !== 'object') {
|
20100 | return false;
|
20101 | }
|
20102 | if ('get' in obj) {
|
20103 | return isAccessorDescriptor_1(obj, key);
|
20104 | }
|
20105 | return isDataDescriptor(obj, key);
|
20106 | };
|
20107 |
|
20108 | var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)
|
20109 | ? Reflect.defineProperty
|
20110 | : Object.defineProperty;
|
20111 |
|
20112 | var defineProperty = function defineProperty(obj, key, val) {
|
20113 | if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {
|
20114 | throw new TypeError('expected an object, function, or array');
|
20115 | }
|
20116 |
|
20117 | if (typeof key !== 'string') {
|
20118 | throw new TypeError('expected "key" to be a string');
|
20119 | }
|
20120 |
|
20121 | if (isDescriptor(val)) {
|
20122 | define(obj, key, val);
|
20123 | return obj;
|
20124 | }
|
20125 |
|
20126 | define(obj, key, {
|
20127 | configurable: true,
|
20128 | enumerable: false,
|
20129 | writable: true,
|
20130 | value: val
|
20131 | });
|
20132 |
|
20133 | return obj;
|
20134 | };
|
20135 |
|
20136 | function isObjectObject(o) {
|
20137 | return isobject(o) === true
|
20138 | && Object.prototype.toString.call(o) === '[object Object]';
|
20139 | }
|
20140 |
|
20141 | var isPlainObject = function isPlainObject(o) {
|
20142 | var ctor,prot;
|
20143 |
|
20144 | if (isObjectObject(o) === false) return false;
|
20145 |
|
20146 | // If has modified constructor
|
20147 | ctor = o.constructor;
|
20148 | if (typeof ctor !== 'function') return false;
|
20149 |
|
20150 | // If has modified prototype
|
20151 | prot = ctor.prototype;
|
20152 | if (isObjectObject(prot) === false) return false;
|
20153 |
|
20154 | // If constructor does not have an Object-specific method
|
20155 | if (prot.hasOwnProperty('isPrototypeOf') === false) {
|
20156 | return false;
|
20157 | }
|
20158 |
|
20159 | // Most likely a plain Object
|
20160 | return true;
|
20161 | };
|
20162 |
|
20163 | var isExtendable = function isExtendable(val) {
|
20164 | return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
|
20165 | };
|
20166 |
|
20167 | /*!
|
20168 | * assign-symbols <https://github.com/jonschlinkert/assign-symbols>
|
20169 | *
|
20170 | * Copyright (c) 2015, Jon Schlinkert.
|
20171 | * Licensed under the MIT License.
|
20172 | */
|
20173 |
|
20174 | var assignSymbols = function(receiver, objects) {
|
20175 | if (receiver === null || typeof receiver === 'undefined') {
|
20176 | throw new TypeError('expected first argument to be an object.');
|
20177 | }
|
20178 |
|
20179 | if (typeof objects === 'undefined' || typeof Symbol === 'undefined') {
|
20180 | return receiver;
|
20181 | }
|
20182 |
|
20183 | if (typeof Object.getOwnPropertySymbols !== 'function') {
|
20184 | return receiver;
|
20185 | }
|
20186 |
|
20187 | var isEnumerable = Object.prototype.propertyIsEnumerable;
|
20188 | var target = Object(receiver);
|
20189 | var len = arguments.length, i = 0;
|
20190 |
|
20191 | while (++i < len) {
|
20192 | var provider = Object(arguments[i]);
|
20193 | var names = Object.getOwnPropertySymbols(provider);
|
20194 |
|
20195 | for (var j = 0; j < names.length; j++) {
|
20196 | var key = names[j];
|
20197 |
|
20198 | if (isEnumerable.call(provider, key)) {
|
20199 | target[key] = provider[key];
|
20200 | }
|
20201 | }
|
20202 | }
|
20203 | return target;
|
20204 | };
|
20205 |
|
20206 | var extendShallow = Object.assign || function(obj/*, objects*/) {
|
20207 | if (obj === null || typeof obj === 'undefined') {
|
20208 | throw new TypeError('Cannot convert undefined or null to object');
|
20209 | }
|
20210 | if (!isObject$1(obj)) {
|
20211 | obj = {};
|
20212 | }
|
20213 | for (var i = 1; i < arguments.length; i++) {
|
20214 | var val = arguments[i];
|
20215 | if (isString(val)) {
|
20216 | val = toObject$1(val);
|
20217 | }
|
20218 | if (isObject$1(val)) {
|
20219 | assign(obj, val);
|
20220 | assignSymbols(obj, val);
|
20221 | }
|
20222 | }
|
20223 | return obj;
|
20224 | };
|
20225 |
|
20226 | function assign(a, b) {
|
20227 | for (var key in b) {
|
20228 | if (hasOwn(b, key)) {
|
20229 | a[key] = b[key];
|
20230 | }
|
20231 | }
|
20232 | }
|
20233 |
|
20234 | function isString(val) {
|
20235 | return (val && typeof val === 'string');
|
20236 | }
|
20237 |
|
20238 | function toObject$1(str) {
|
20239 | var obj = {};
|
20240 | for (var i in str) {
|
20241 | obj[i] = str[i];
|
20242 | }
|
20243 | return obj;
|
20244 | }
|
20245 |
|
20246 | function isObject$1(val) {
|
20247 | return (val && typeof val === 'object') || isExtendable(val);
|
20248 | }
|
20249 |
|
20250 | /**
|
20251 | * Returns true if the given `key` is an own property of `obj`.
|
20252 | */
|
20253 |
|
20254 | function hasOwn(obj, key) {
|
20255 | return Object.prototype.hasOwnProperty.call(obj, key);
|
20256 | }
|
20257 |
|
20258 | /**
|
20259 | * The main export is a function that takes a `pattern` string and an `options` object.
|
20260 | *
|
20261 | * ```js
|
20262 | & var not = require('regex-not');
|
20263 | & console.log(not('foo'));
|
20264 | & //=> /^(?:(?!^(?:foo)$).)*$/
|
20265 | * ```
|
20266 | *
|
20267 | * @param {String} `pattern`
|
20268 | * @param {Object} `options`
|
20269 | * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.
|
20270 | * @api public
|
20271 | */
|
20272 |
|
20273 | function toRegex(pattern, options) {
|
20274 | return new RegExp(toRegex.create(pattern, options));
|
20275 | }
|
20276 |
|
20277 | /**
|
20278 | * Create a regex-compatible string from the given `pattern` and `options`.
|
20279 | *
|
20280 | * ```js
|
20281 | & var not = require('regex-not');
|
20282 | & console.log(not.create('foo'));
|
20283 | & //=> '^(?:(?!^(?:foo)$).)*$'
|
20284 | * ```
|
20285 | * @param {String} `pattern`
|
20286 | * @param {Object} `options`
|
20287 | * @return {String}
|
20288 | * @api public
|
20289 | */
|
20290 |
|
20291 | toRegex.create = function(pattern, options) {
|
20292 | if (typeof pattern !== 'string') {
|
20293 | throw new TypeError('expected a string');
|
20294 | }
|
20295 |
|
20296 | var opts = extendShallow({}, options);
|
20297 | if (opts.contains === true) {
|
20298 | opts.strictNegate = false;
|
20299 | }
|
20300 |
|
20301 | var open = opts.strictOpen !== false ? '^' : '';
|
20302 | var close = opts.strictClose !== false ? '$' : '';
|
20303 | var endChar = opts.endChar ? opts.endChar : '+';
|
20304 | var str = pattern;
|
20305 |
|
20306 | if (opts.strictNegate === false) {
|
20307 | str = '(?:(?!(?:' + pattern + ')).)' + endChar;
|
20308 | } else {
|
20309 | str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;
|
20310 | }
|
20311 |
|
20312 | var res = open + str + close;
|
20313 | if (opts.safe === true && safeRegex(res) === false) {
|
20314 | throw new Error('potentially unsafe regular expression: ' + res);
|
20315 | }
|
20316 |
|
20317 | return res;
|
20318 | };
|
20319 |
|
20320 | /**
|
20321 | * Expose `toRegex`
|
20322 | */
|
20323 |
|
20324 | var regexNot = toRegex;
|
20325 |
|
20326 | var MAX_LENGTH = 1024 * 64;
|
20327 |
|
20328 | /**
|
20329 | * Session cache
|
20330 | */
|
20331 |
|
20332 | var cache = {};
|
20333 |
|
20334 | /**
|
20335 | * Create a regular expression from the given `pattern` string.
|
20336 | *
|
20337 | * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
|
20338 | * @param {Object} `options`
|
20339 | * @return {RegExp}
|
20340 | * @api public
|
20341 | */
|
20342 |
|
20343 | var toRegex$1 = function(patterns, options) {
|
20344 | if (!Array.isArray(patterns)) {
|
20345 | return makeRe(patterns, options);
|
20346 | }
|
20347 | return makeRe(patterns.join('|'), options);
|
20348 | };
|
20349 |
|
20350 | /**
|
20351 | * Create a regular expression from the given `pattern` string.
|
20352 | *
|
20353 | * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
|
20354 | * @param {Object} `options`
|
20355 | * @return {RegExp}
|
20356 | * @api public
|
20357 | */
|
20358 |
|
20359 | function makeRe(pattern, options) {
|
20360 | if (pattern instanceof RegExp) {
|
20361 | return pattern;
|
20362 | }
|
20363 |
|
20364 | if (typeof pattern !== 'string') {
|
20365 | throw new TypeError('expected a string');
|
20366 | }
|
20367 |
|
20368 | if (pattern.length > MAX_LENGTH) {
|
20369 | throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
|
20370 | }
|
20371 |
|
20372 | var key = pattern;
|
20373 | // do this before shallow cloning options, it's a lot faster
|
20374 | if (!options || (options && options.cache !== false)) {
|
20375 | key = createKey(pattern, options);
|
20376 |
|
20377 | if (cache.hasOwnProperty(key)) {
|
20378 | return cache[key];
|
20379 | }
|
20380 | }
|
20381 |
|
20382 | var opts = extendShallow({}, options);
|
20383 | if (opts.contains === true) {
|
20384 | if (opts.negate === true) {
|
20385 | opts.strictNegate = false;
|
20386 | } else {
|
20387 | opts.strict = false;
|
20388 | }
|
20389 | }
|
20390 |
|
20391 | if (opts.strict === false) {
|
20392 | opts.strictOpen = false;
|
20393 | opts.strictClose = false;
|
20394 | }
|
20395 |
|
20396 | var open = opts.strictOpen !== false ? '^' : '';
|
20397 | var close = opts.strictClose !== false ? '$' : '';
|
20398 | var flags = opts.flags || '';
|
20399 | var regex;
|
20400 |
|
20401 | if (opts.nocase === true && !/i/.test(flags)) {
|
20402 | flags += 'i';
|
20403 | }
|
20404 |
|
20405 | try {
|
20406 | if (opts.negate || typeof opts.strictNegate === 'boolean') {
|
20407 | pattern = regexNot.create(pattern, opts);
|
20408 | }
|
20409 |
|
20410 | var str = open + '(?:' + pattern + ')' + close;
|
20411 | regex = new RegExp(str, flags);
|
20412 |
|
20413 | if (opts.safe === true && safeRegex(regex) === false) {
|
20414 | throw new Error('potentially unsafe regular expression: ' + regex.source);
|
20415 | }
|
20416 |
|
20417 | } catch (err) {
|
20418 | if (opts.strictErrors === true || opts.safe === true) {
|
20419 | err.key = key;
|
20420 | err.pattern = pattern;
|
20421 | err.originalOptions = options;
|
20422 | err.createdOptions = opts;
|
20423 | throw err;
|
20424 | }
|
20425 |
|
20426 | try {
|
20427 | regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$');
|
20428 | } catch (err) {
|
20429 | regex = /.^/; //<= match nothing
|
20430 | }
|
20431 | }
|
20432 |
|
20433 | if (opts.cache !== false) {
|
20434 | memoize(regex, key, pattern, opts);
|
20435 | }
|
20436 | return regex;
|
20437 | }
|
20438 |
|
20439 | /**
|
20440 | * Memoize generated regex. This can result in dramatic speed improvements
|
20441 | * and simplify debugging by adding options and pattern to the regex. It can be
|
20442 | * disabled by passing setting `options.cache` to false.
|
20443 | */
|
20444 |
|
20445 | function memoize(regex, key, pattern, options) {
|
20446 | defineProperty(regex, 'cached', true);
|
20447 | defineProperty(regex, 'pattern', pattern);
|
20448 | defineProperty(regex, 'options', options);
|
20449 | defineProperty(regex, 'key', key);
|
20450 | cache[key] = regex;
|
20451 | }
|
20452 |
|
20453 | /**
|
20454 | * Create the key to use for memoization. The key is generated
|
20455 | * by iterating over the options and concatenating key-value pairs
|
20456 | * to the pattern string.
|
20457 | */
|
20458 |
|
20459 | function createKey(pattern, options) {
|
20460 | if (!options) return pattern;
|
20461 | var key = pattern;
|
20462 | for (var prop in options) {
|
20463 | if (options.hasOwnProperty(prop)) {
|
20464 | key += ';' + prop + '=' + String(options[prop]);
|
20465 | }
|
20466 | }
|
20467 | return key;
|
20468 | }
|
20469 |
|
20470 | /**
|
20471 | * Expose `makeRe`
|
20472 | */
|
20473 |
|
20474 | var makeRe_1 = makeRe;
|
20475 | toRegex$1.makeRe = makeRe_1;
|
20476 |
|
20477 | var arrayUnique = createCommonjsModule(function (module) {
|
20478 |
|
20479 | module.exports = function unique(arr) {
|
20480 | if (!Array.isArray(arr)) {
|
20481 | throw new TypeError('array-unique expects an array.');
|
20482 | }
|
20483 |
|
20484 | var len = arr.length;
|
20485 | var i = -1;
|
20486 |
|
20487 | while (i++ < len) {
|
20488 | var j = i + 1;
|
20489 |
|
20490 | for (; j < arr.length; ++j) {
|
20491 | if (arr[i] === arr[j]) {
|
20492 | arr.splice(j--, 1);
|
20493 | }
|
20494 | }
|
20495 | }
|
20496 | return arr;
|
20497 | };
|
20498 |
|
20499 | module.exports.immutable = function uniqueImmutable(arr) {
|
20500 | if (!Array.isArray(arr)) {
|
20501 | throw new TypeError('array-unique expects an array.');
|
20502 | }
|
20503 |
|
20504 | var arrLen = arr.length;
|
20505 | var newArr = new Array(arrLen);
|
20506 |
|
20507 | for (var i = 0; i < arrLen; i++) {
|
20508 | newArr[i] = arr[i];
|
20509 | }
|
20510 |
|
20511 | return module.exports(newArr);
|
20512 | };
|
20513 | });
|
20514 |
|
20515 | /*!
|
20516 | * is-extendable <https://github.com/jonschlinkert/is-extendable>
|
20517 | *
|
20518 | * Copyright (c) 2015, Jon Schlinkert.
|
20519 | * Licensed under the MIT License.
|
20520 | */
|
20521 |
|
20522 | var isExtendable$1 = function isExtendable(val) {
|
20523 | return typeof val !== 'undefined' && val !== null
|
20524 | && (typeof val === 'object' || typeof val === 'function');
|
20525 | };
|
20526 |
|
20527 | var extendShallow$1 = function extend(o/*, objects*/) {
|
20528 | if (!isExtendable$1(o)) { o = {}; }
|
20529 |
|
20530 | var len = arguments.length;
|
20531 | for (var i = 1; i < len; i++) {
|
20532 | var obj = arguments[i];
|
20533 |
|
20534 | if (isExtendable$1(obj)) {
|
20535 | assign$1(o, obj);
|
20536 | }
|
20537 | }
|
20538 | return o;
|
20539 | };
|
20540 |
|
20541 | function assign$1(a, b) {
|
20542 | for (var key in b) {
|
20543 | if (hasOwn$1(b, key)) {
|
20544 | a[key] = b[key];
|
20545 | }
|
20546 | }
|
20547 | }
|
20548 |
|
20549 | /**
|
20550 | * Returns true if the given `key` is an own property of `obj`.
|
20551 | */
|
20552 |
|
20553 | function hasOwn$1(obj, key) {
|
20554 | return Object.prototype.hasOwnProperty.call(obj, key);
|
20555 | }
|
20556 |
|
20557 | var splitString = function(str, options, fn) {
|
20558 | if (typeof str !== 'string') {
|
20559 | throw new TypeError('expected a string');
|
20560 | }
|
20561 |
|
20562 | if (typeof options === 'function') {
|
20563 | fn = options;
|
20564 | options = null;
|
20565 | }
|
20566 |
|
20567 | // allow separator to be defined as a string
|
20568 | if (typeof options === 'string') {
|
20569 | options = { sep: options };
|
20570 | }
|
20571 |
|
20572 | var opts = extendShallow({sep: '.'}, options);
|
20573 | var quotes = opts.quotes || ['"', "'", '`'];
|
20574 | var brackets;
|
20575 |
|
20576 | if (opts.brackets === true) {
|
20577 | brackets = {
|
20578 | '<': '>',
|
20579 | '(': ')',
|
20580 | '[': ']',
|
20581 | '{': '}'
|
20582 | };
|
20583 | } else if (opts.brackets) {
|
20584 | brackets = opts.brackets;
|
20585 | }
|
20586 |
|
20587 | var tokens = [];
|
20588 | var stack = [];
|
20589 | var arr = [''];
|
20590 | var sep = opts.sep;
|
20591 | var len = str.length;
|
20592 | var idx = -1;
|
20593 | var closeIdx;
|
20594 |
|
20595 | function expected() {
|
20596 | if (brackets && stack.length) {
|
20597 | return brackets[stack[stack.length - 1]];
|
20598 | }
|
20599 | }
|
20600 |
|
20601 | while (++idx < len) {
|
20602 | var ch = str[idx];
|
20603 | var next = str[idx + 1];
|
20604 | var tok = { val: ch, idx: idx, arr: arr, str: str };
|
20605 | tokens.push(tok);
|
20606 |
|
20607 | if (ch === '\\') {
|
20608 | tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next;
|
20609 | tok.escaped = true;
|
20610 | if (typeof fn === 'function') {
|
20611 | fn(tok);
|
20612 | }
|
20613 | arr[arr.length - 1] += tok.val;
|
20614 | idx++;
|
20615 | continue;
|
20616 | }
|
20617 |
|
20618 | if (brackets && brackets[ch]) {
|
20619 | stack.push(ch);
|
20620 | var e = expected();
|
20621 | var i = idx + 1;
|
20622 |
|
20623 | if (str.indexOf(e, i + 1) !== -1) {
|
20624 | while (stack.length && i < len) {
|
20625 | var s = str[++i];
|
20626 | if (s === '\\') {
|
20627 | s++;
|
20628 | continue;
|
20629 | }
|
20630 |
|
20631 | if (quotes.indexOf(s) !== -1) {
|
20632 | i = getClosingQuote(str, s, i + 1);
|
20633 | continue;
|
20634 | }
|
20635 |
|
20636 | e = expected();
|
20637 | if (stack.length && str.indexOf(e, i + 1) === -1) {
|
20638 | break;
|
20639 | }
|
20640 |
|
20641 | if (brackets[s]) {
|
20642 | stack.push(s);
|
20643 | continue;
|
20644 | }
|
20645 |
|
20646 | if (e === s) {
|
20647 | stack.pop();
|
20648 | }
|
20649 | }
|
20650 | }
|
20651 |
|
20652 | closeIdx = i;
|
20653 | if (closeIdx === -1) {
|
20654 | arr[arr.length - 1] += ch;
|
20655 | continue;
|
20656 | }
|
20657 |
|
20658 | ch = str.slice(idx, closeIdx + 1);
|
20659 | tok.val = ch;
|
20660 | tok.idx = idx = closeIdx;
|
20661 | }
|
20662 |
|
20663 | if (quotes.indexOf(ch) !== -1) {
|
20664 | closeIdx = getClosingQuote(str, ch, idx + 1);
|
20665 | if (closeIdx === -1) {
|
20666 | arr[arr.length - 1] += ch;
|
20667 | continue;
|
20668 | }
|
20669 |
|
20670 | if (keepQuotes(ch, opts) === true) {
|
20671 | ch = str.slice(idx, closeIdx + 1);
|
20672 | } else {
|
20673 | ch = str.slice(idx + 1, closeIdx);
|
20674 | }
|
20675 |
|
20676 | tok.val = ch;
|
20677 | tok.idx = idx = closeIdx;
|
20678 | }
|
20679 |
|
20680 | if (typeof fn === 'function') {
|
20681 | fn(tok, tokens);
|
20682 | ch = tok.val;
|
20683 | idx = tok.idx;
|
20684 | }
|
20685 |
|
20686 | if (tok.val === sep && tok.split !== false) {
|
20687 | arr.push('');
|
20688 | continue;
|
20689 | }
|
20690 |
|
20691 | arr[arr.length - 1] += tok.val;
|
20692 | }
|
20693 |
|
20694 | return arr;
|
20695 | };
|
20696 |
|
20697 | function getClosingQuote(str, ch, i, brackets) {
|
20698 | var idx = str.indexOf(ch, i);
|
20699 | if (str.charAt(idx - 1) === '\\') {
|
20700 | return getClosingQuote(str, ch, idx + 1);
|
20701 | }
|
20702 | return idx;
|
20703 | }
|
20704 |
|
20705 | function keepQuotes(ch, opts) {
|
20706 | if (opts.keepDoubleQuotes === true && ch === '"') return true;
|
20707 | if (opts.keepSingleQuotes === true && ch === "'") return true;
|
20708 | return opts.keepQuotes;
|
20709 | }
|
20710 |
|
20711 | function keepEscaping(opts, str, idx) {
|
20712 | if (typeof opts.keepEscaping === 'function') {
|
20713 | return opts.keepEscaping(str, idx);
|
20714 | }
|
20715 | return opts.keepEscaping === true || str[idx + 1] === '\\';
|
20716 | }
|
20717 |
|
20718 | /*!
|
20719 | * arr-flatten <https://github.com/jonschlinkert/arr-flatten>
|
20720 | *
|
20721 | * Copyright (c) 2014-2017, Jon Schlinkert.
|
20722 | * Released under the MIT License.
|
20723 | */
|
20724 |
|
20725 | var arrFlatten = function (arr) {
|
20726 | return flat(arr, []);
|
20727 | };
|
20728 |
|
20729 | function flat(arr, res) {
|
20730 | var i = 0, cur;
|
20731 | var len = arr.length;
|
20732 | for (; i < len; i++) {
|
20733 | cur = arr[i];
|
20734 | Array.isArray(cur) ? flat(cur, res) : res.push(cur);
|
20735 | }
|
20736 | return res;
|
20737 | }
|
20738 |
|
20739 | /*!
|
20740 | * Determine if an object is a Buffer
|
20741 | *
|
20742 | * @author Feross Aboukhadijeh <https://feross.org>
|
20743 | * @license MIT
|
20744 | */
|
20745 |
|
20746 | // The _isBuffer check is for Safari 5-7 support, because it's missing
|
20747 | // Object.prototype.constructor. Remove this eventually
|
20748 | var isBuffer_1 = function (obj) {
|
20749 | return obj != null && (isBuffer$1(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
|
20750 | };
|
20751 |
|
20752 | function isBuffer$1 (obj) {
|
20753 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
|
20754 | }
|
20755 |
|
20756 | // For Node v0.10 support. Remove this eventually.
|
20757 | function isSlowBuffer (obj) {
|
20758 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer$1(obj.slice(0, 0))
|
20759 | }
|
20760 |
|
20761 | var toString$2 = Object.prototype.toString;
|
20762 |
|
20763 | /**
|
20764 | * Get the native `typeof` a value.
|
20765 | *
|
20766 | * @param {*} `val`
|
20767 | * @return {*} Native javascript type
|
20768 | */
|
20769 |
|
20770 | var kindOf$1 = function kindOf(val) {
|
20771 | // primitivies
|
20772 | if (typeof val === 'undefined') {
|
20773 | return 'undefined';
|
20774 | }
|
20775 | if (val === null) {
|
20776 | return 'null';
|
20777 | }
|
20778 | if (val === true || val === false || val instanceof Boolean) {
|
20779 | return 'boolean';
|
20780 | }
|
20781 | if (typeof val === 'string' || val instanceof String) {
|
20782 | return 'string';
|
20783 | }
|
20784 | if (typeof val === 'number' || val instanceof Number) {
|
20785 | return 'number';
|
20786 | }
|
20787 |
|
20788 | // functions
|
20789 | if (typeof val === 'function' || val instanceof Function) {
|
20790 | return 'function';
|
20791 | }
|
20792 |
|
20793 | // array
|
20794 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
20795 | return 'array';
|
20796 | }
|
20797 |
|
20798 | // check for instances of RegExp and Date before calling `toString`
|
20799 | if (val instanceof RegExp) {
|
20800 | return 'regexp';
|
20801 | }
|
20802 | if (val instanceof Date) {
|
20803 | return 'date';
|
20804 | }
|
20805 |
|
20806 | // other objects
|
20807 | var type = toString$2.call(val);
|
20808 |
|
20809 | if (type === '[object RegExp]') {
|
20810 | return 'regexp';
|
20811 | }
|
20812 | if (type === '[object Date]') {
|
20813 | return 'date';
|
20814 | }
|
20815 | if (type === '[object Arguments]') {
|
20816 | return 'arguments';
|
20817 | }
|
20818 | if (type === '[object Error]') {
|
20819 | return 'error';
|
20820 | }
|
20821 |
|
20822 | // buffer
|
20823 | if (isBuffer_1(val)) {
|
20824 | return 'buffer';
|
20825 | }
|
20826 |
|
20827 | // es6: Map, WeakMap, Set, WeakSet
|
20828 | if (type === '[object Set]') {
|
20829 | return 'set';
|
20830 | }
|
20831 | if (type === '[object WeakSet]') {
|
20832 | return 'weakset';
|
20833 | }
|
20834 | if (type === '[object Map]') {
|
20835 | return 'map';
|
20836 | }
|
20837 | if (type === '[object WeakMap]') {
|
20838 | return 'weakmap';
|
20839 | }
|
20840 | if (type === '[object Symbol]') {
|
20841 | return 'symbol';
|
20842 | }
|
20843 |
|
20844 | // typed arrays
|
20845 | if (type === '[object Int8Array]') {
|
20846 | return 'int8array';
|
20847 | }
|
20848 | if (type === '[object Uint8Array]') {
|
20849 | return 'uint8array';
|
20850 | }
|
20851 | if (type === '[object Uint8ClampedArray]') {
|
20852 | return 'uint8clampedarray';
|
20853 | }
|
20854 | if (type === '[object Int16Array]') {
|
20855 | return 'int16array';
|
20856 | }
|
20857 | if (type === '[object Uint16Array]') {
|
20858 | return 'uint16array';
|
20859 | }
|
20860 | if (type === '[object Int32Array]') {
|
20861 | return 'int32array';
|
20862 | }
|
20863 | if (type === '[object Uint32Array]') {
|
20864 | return 'uint32array';
|
20865 | }
|
20866 | if (type === '[object Float32Array]') {
|
20867 | return 'float32array';
|
20868 | }
|
20869 | if (type === '[object Float64Array]') {
|
20870 | return 'float64array';
|
20871 | }
|
20872 |
|
20873 | // must be a plain object
|
20874 | return 'object';
|
20875 | };
|
20876 |
|
20877 | var isNumber = function isNumber(num) {
|
20878 | var type = kindOf$1(num);
|
20879 |
|
20880 | if (type === 'string') {
|
20881 | if (!num.trim()) return false;
|
20882 | } else if (type !== 'number') {
|
20883 | return false;
|
20884 | }
|
20885 |
|
20886 | return (num - num + 1) >= 0;
|
20887 | };
|
20888 |
|
20889 | var extendShallow$2 = function extend(o/*, objects*/) {
|
20890 | if (!isExtendable$1(o)) { o = {}; }
|
20891 |
|
20892 | var len = arguments.length;
|
20893 | for (var i = 1; i < len; i++) {
|
20894 | var obj = arguments[i];
|
20895 |
|
20896 | if (isExtendable$1(obj)) {
|
20897 | assign$2(o, obj);
|
20898 | }
|
20899 | }
|
20900 | return o;
|
20901 | };
|
20902 |
|
20903 | function assign$2(a, b) {
|
20904 | for (var key in b) {
|
20905 | if (hasOwn$2(b, key)) {
|
20906 | a[key] = b[key];
|
20907 | }
|
20908 | }
|
20909 | }
|
20910 |
|
20911 | /**
|
20912 | * Returns true if the given `key` is an own property of `obj`.
|
20913 | */
|
20914 |
|
20915 | function hasOwn$2(obj, key) {
|
20916 | return Object.prototype.hasOwnProperty.call(obj, key);
|
20917 | }
|
20918 |
|
20919 | /*!
|
20920 | * repeat-string <https://github.com/jonschlinkert/repeat-string>
|
20921 | *
|
20922 | * Copyright (c) 2014-2015, Jon Schlinkert.
|
20923 | * Licensed under the MIT License.
|
20924 | */
|
20925 |
|
20926 | /**
|
20927 | * Results cache
|
20928 | */
|
20929 |
|
20930 | var res = '';
|
20931 | var cache$1;
|
20932 |
|
20933 | /**
|
20934 | * Expose `repeat`
|
20935 | */
|
20936 |
|
20937 | var repeatString = repeat;
|
20938 |
|
20939 | /**
|
20940 | * Repeat the given `string` the specified `number`
|
20941 | * of times.
|
20942 | *
|
20943 | * **Example:**
|
20944 | *
|
20945 | * ```js
|
20946 | * var repeat = require('repeat-string');
|
20947 | * repeat('A', 5);
|
20948 | * //=> AAAAA
|
20949 | * ```
|
20950 | *
|
20951 | * @param {String} `string` The string to repeat
|
20952 | * @param {Number} `number` The number of times to repeat the string
|
20953 | * @return {String} Repeated string
|
20954 | * @api public
|
20955 | */
|
20956 |
|
20957 | function repeat(str, num) {
|
20958 | if (typeof str !== 'string') {
|
20959 | throw new TypeError('expected a string');
|
20960 | }
|
20961 |
|
20962 | // cover common, quick use cases
|
20963 | if (num === 1) return str;
|
20964 | if (num === 2) return str + str;
|
20965 |
|
20966 | var max = str.length * num;
|
20967 | if (cache$1 !== str || typeof cache$1 === 'undefined') {
|
20968 | cache$1 = str;
|
20969 | res = '';
|
20970 | } else if (res.length >= max) {
|
20971 | return res.substr(0, max);
|
20972 | }
|
20973 |
|
20974 | while (max > res.length && num > 1) {
|
20975 | if (num & 1) {
|
20976 | res += str;
|
20977 | }
|
20978 |
|
20979 | num >>= 1;
|
20980 | str += str;
|
20981 | }
|
20982 |
|
20983 | res += str;
|
20984 | res = res.substr(0, max);
|
20985 | return res;
|
20986 | }
|
20987 |
|
20988 | var cache$2 = {};
|
20989 |
|
20990 | function toRegexRange(min, max, options) {
|
20991 | if (isNumber(min) === false) {
|
20992 | throw new RangeError('toRegexRange: first argument is invalid.');
|
20993 | }
|
20994 |
|
20995 | if (typeof max === 'undefined' || min === max) {
|
20996 | return String(min);
|
20997 | }
|
20998 |
|
20999 | if (isNumber(max) === false) {
|
21000 | throw new RangeError('toRegexRange: second argument is invalid.');
|
21001 | }
|
21002 |
|
21003 | options = options || {};
|
21004 | var relax = String(options.relaxZeros);
|
21005 | var shorthand = String(options.shorthand);
|
21006 | var capture = String(options.capture);
|
21007 | var key = min + ':' + max + '=' + relax + shorthand + capture;
|
21008 | if (cache$2.hasOwnProperty(key)) {
|
21009 | return cache$2[key].result;
|
21010 | }
|
21011 |
|
21012 | var a = Math.min(min, max);
|
21013 | var b = Math.max(min, max);
|
21014 |
|
21015 | if (Math.abs(a - b) === 1) {
|
21016 | var result = min + '|' + max;
|
21017 | if (options.capture) {
|
21018 | return '(' + result + ')';
|
21019 | }
|
21020 | return result;
|
21021 | }
|
21022 |
|
21023 | var isPadded = padding(min) || padding(max);
|
21024 | var positives = [];
|
21025 | var negatives = [];
|
21026 |
|
21027 | var tok = {min: min, max: max, a: a, b: b};
|
21028 | if (isPadded) {
|
21029 | tok.isPadded = isPadded;
|
21030 | tok.maxLen = String(tok.max).length;
|
21031 | }
|
21032 |
|
21033 | if (a < 0) {
|
21034 | var newMin = b < 0 ? Math.abs(b) : 1;
|
21035 | var newMax = Math.abs(a);
|
21036 | negatives = splitToPatterns(newMin, newMax, tok, options);
|
21037 | a = tok.a = 0;
|
21038 | }
|
21039 |
|
21040 | if (b >= 0) {
|
21041 | positives = splitToPatterns(a, b, tok, options);
|
21042 | }
|
21043 |
|
21044 | tok.negatives = negatives;
|
21045 | tok.positives = positives;
|
21046 | tok.result = siftPatterns(negatives, positives, options);
|
21047 |
|
21048 | if (options.capture && (positives.length + negatives.length) > 1) {
|
21049 | tok.result = '(' + tok.result + ')';
|
21050 | }
|
21051 |
|
21052 | cache$2[key] = tok;
|
21053 | return tok.result;
|
21054 | }
|
21055 |
|
21056 | function siftPatterns(neg, pos, options) {
|
21057 | var onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
|
21058 | var onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
|
21059 | var intersected = filterPatterns(neg, pos, '-?', true, options) || [];
|
21060 | var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
|
21061 | return subpatterns.join('|');
|
21062 | }
|
21063 |
|
21064 | function splitToRanges(min, max) {
|
21065 | min = Number(min);
|
21066 | max = Number(max);
|
21067 |
|
21068 | var nines = 1;
|
21069 | var stops = [max];
|
21070 | var stop = +countNines(min, nines);
|
21071 |
|
21072 | while (min <= stop && stop <= max) {
|
21073 | stops = push(stops, stop);
|
21074 | nines += 1;
|
21075 | stop = +countNines(min, nines);
|
21076 | }
|
21077 |
|
21078 | var zeros = 1;
|
21079 | stop = countZeros(max + 1, zeros) - 1;
|
21080 |
|
21081 | while (min < stop && stop <= max) {
|
21082 | stops = push(stops, stop);
|
21083 | zeros += 1;
|
21084 | stop = countZeros(max + 1, zeros) - 1;
|
21085 | }
|
21086 |
|
21087 | stops.sort(compare);
|
21088 | return stops;
|
21089 | }
|
21090 |
|
21091 | /**
|
21092 | * Convert a range to a regex pattern
|
21093 | * @param {Number} `start`
|
21094 | * @param {Number} `stop`
|
21095 | * @return {String}
|
21096 | */
|
21097 |
|
21098 | function rangeToPattern(start, stop, options) {
|
21099 | if (start === stop) {
|
21100 | return {pattern: String(start), digits: []};
|
21101 | }
|
21102 |
|
21103 | var zipped = zip(String(start), String(stop));
|
21104 | var len = zipped.length, i = -1;
|
21105 |
|
21106 | var pattern = '';
|
21107 | var digits = 0;
|
21108 |
|
21109 | while (++i < len) {
|
21110 | var numbers = zipped[i];
|
21111 | var startDigit = numbers[0];
|
21112 | var stopDigit = numbers[1];
|
21113 |
|
21114 | if (startDigit === stopDigit) {
|
21115 | pattern += startDigit;
|
21116 |
|
21117 | } else if (startDigit !== '0' || stopDigit !== '9') {
|
21118 | pattern += toCharacterClass(startDigit, stopDigit);
|
21119 |
|
21120 | } else {
|
21121 | digits += 1;
|
21122 | }
|
21123 | }
|
21124 |
|
21125 | if (digits) {
|
21126 | pattern += options.shorthand ? '\\d' : '[0-9]';
|
21127 | }
|
21128 |
|
21129 | return { pattern: pattern, digits: [digits] };
|
21130 | }
|
21131 |
|
21132 | function splitToPatterns(min, max, tok, options) {
|
21133 | var ranges = splitToRanges(min, max);
|
21134 | var len = ranges.length;
|
21135 | var idx = -1;
|
21136 |
|
21137 | var tokens = [];
|
21138 | var start = min;
|
21139 | var prev;
|
21140 |
|
21141 | while (++idx < len) {
|
21142 | var range = ranges[idx];
|
21143 | var obj = rangeToPattern(start, range, options);
|
21144 | var zeros = '';
|
21145 |
|
21146 | if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
|
21147 | if (prev.digits.length > 1) {
|
21148 | prev.digits.pop();
|
21149 | }
|
21150 | prev.digits.push(obj.digits[0]);
|
21151 | prev.string = prev.pattern + toQuantifier(prev.digits);
|
21152 | start = range + 1;
|
21153 | continue;
|
21154 | }
|
21155 |
|
21156 | if (tok.isPadded) {
|
21157 | zeros = padZeros(range, tok);
|
21158 | }
|
21159 |
|
21160 | obj.string = zeros + obj.pattern + toQuantifier(obj.digits);
|
21161 | tokens.push(obj);
|
21162 | start = range + 1;
|
21163 | prev = obj;
|
21164 | }
|
21165 |
|
21166 | return tokens;
|
21167 | }
|
21168 |
|
21169 | function filterPatterns(arr, comparison, prefix, intersection, options) {
|
21170 | var res = [];
|
21171 |
|
21172 | for (var i = 0; i < arr.length; i++) {
|
21173 | var tok = arr[i];
|
21174 | var ele = tok.string;
|
21175 |
|
21176 | if (options.relaxZeros !== false) {
|
21177 | if (prefix === '-' && ele.charAt(0) === '0') {
|
21178 | if (ele.charAt(1) === '{') {
|
21179 | ele = '0*' + ele.replace(/^0\{\d+\}/, '');
|
21180 | } else {
|
21181 | ele = '0*' + ele.slice(1);
|
21182 | }
|
21183 | }
|
21184 | }
|
21185 |
|
21186 | if (!intersection && !contains(comparison, 'string', ele)) {
|
21187 | res.push(prefix + ele);
|
21188 | }
|
21189 |
|
21190 | if (intersection && contains(comparison, 'string', ele)) {
|
21191 | res.push(prefix + ele);
|
21192 | }
|
21193 | }
|
21194 | return res;
|
21195 | }
|
21196 |
|
21197 | /**
|
21198 | * Zip strings (`for in` can be used on string characters)
|
21199 | */
|
21200 |
|
21201 | function zip(a, b) {
|
21202 | var arr = [];
|
21203 | for (var ch in a) arr.push([a[ch], b[ch]]);
|
21204 | return arr;
|
21205 | }
|
21206 |
|
21207 | function compare(a, b) {
|
21208 | return a > b ? 1 : b > a ? -1 : 0;
|
21209 | }
|
21210 |
|
21211 | function push(arr, ele) {
|
21212 | if (arr.indexOf(ele) === -1) arr.push(ele);
|
21213 | return arr;
|
21214 | }
|
21215 |
|
21216 | function contains(arr, key, val) {
|
21217 | for (var i = 0; i < arr.length; i++) {
|
21218 | if (arr[i][key] === val) {
|
21219 | return true;
|
21220 | }
|
21221 | }
|
21222 | return false;
|
21223 | }
|
21224 |
|
21225 | function countNines(min, len) {
|
21226 | return String(min).slice(0, -len) + repeatString('9', len);
|
21227 | }
|
21228 |
|
21229 | function countZeros(integer, zeros) {
|
21230 | return integer - (integer % Math.pow(10, zeros));
|
21231 | }
|
21232 |
|
21233 | function toQuantifier(digits) {
|
21234 | var start = digits[0];
|
21235 | var stop = digits[1] ? (',' + digits[1]) : '';
|
21236 | if (!stop && (!start || start === 1)) {
|
21237 | return '';
|
21238 | }
|
21239 | return '{' + start + stop + '}';
|
21240 | }
|
21241 |
|
21242 | function toCharacterClass(a, b) {
|
21243 | return '[' + a + ((b - a === 1) ? '' : '-') + b + ']';
|
21244 | }
|
21245 |
|
21246 | function padding(str) {
|
21247 | return /^-?(0+)\d/.exec(str);
|
21248 | }
|
21249 |
|
21250 | function padZeros(val, tok) {
|
21251 | if (tok.isPadded) {
|
21252 | var diff = Math.abs(tok.maxLen - String(val).length);
|
21253 | switch (diff) {
|
21254 | case 0:
|
21255 | return '';
|
21256 | case 1:
|
21257 | return '0';
|
21258 | default: {
|
21259 | return '0{' + diff + '}';
|
21260 | }
|
21261 | }
|
21262 | }
|
21263 | return val;
|
21264 | }
|
21265 |
|
21266 | /**
|
21267 | * Expose `toRegexRange`
|
21268 | */
|
21269 |
|
21270 | var toRegexRange_1 = toRegexRange;
|
21271 |
|
21272 | /**
|
21273 | * Return a range of numbers or letters.
|
21274 | *
|
21275 | * @param {String} `start` Start of the range
|
21276 | * @param {String} `stop` End of the range
|
21277 | * @param {String} `step` Increment or decrement to use.
|
21278 | * @param {Function} `fn` Custom function to modify each element in the range.
|
21279 | * @return {Array}
|
21280 | */
|
21281 |
|
21282 | function fillRange(start, stop, step, options) {
|
21283 | if (typeof start === 'undefined') {
|
21284 | return [];
|
21285 | }
|
21286 |
|
21287 | if (typeof stop === 'undefined' || start === stop) {
|
21288 | // special case, for handling negative zero
|
21289 | var isString = typeof start === 'string';
|
21290 | if (isNumber(start) && !toNumber(start)) {
|
21291 | return [isString ? '0' : 0];
|
21292 | }
|
21293 | return [start];
|
21294 | }
|
21295 |
|
21296 | if (typeof step !== 'number' && typeof step !== 'string') {
|
21297 | options = step;
|
21298 | step = undefined;
|
21299 | }
|
21300 |
|
21301 | if (typeof options === 'function') {
|
21302 | options = { transform: options };
|
21303 | }
|
21304 |
|
21305 | var opts = extendShallow$2({step: step}, options);
|
21306 | if (opts.step && !isValidNumber(opts.step)) {
|
21307 | if (opts.strictRanges === true) {
|
21308 | throw new TypeError('expected options.step to be a number');
|
21309 | }
|
21310 | return [];
|
21311 | }
|
21312 |
|
21313 | opts.isNumber = isValidNumber(start) && isValidNumber(stop);
|
21314 | if (!opts.isNumber && !isValid(start, stop)) {
|
21315 | if (opts.strictRanges === true) {
|
21316 | throw new RangeError('invalid range arguments: ' + util$2.inspect([start, stop]));
|
21317 | }
|
21318 | return [];
|
21319 | }
|
21320 |
|
21321 | opts.isPadded = isPadded(start) || isPadded(stop);
|
21322 | opts.toString = opts.stringify
|
21323 | || typeof opts.step === 'string'
|
21324 | || typeof start === 'string'
|
21325 | || typeof stop === 'string'
|
21326 | || !opts.isNumber;
|
21327 |
|
21328 | if (opts.isPadded) {
|
21329 | opts.maxLength = Math.max(String(start).length, String(stop).length);
|
21330 | }
|
21331 |
|
21332 | // support legacy minimatch/fill-range options
|
21333 | if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;
|
21334 | if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;
|
21335 | return expand(start, stop, opts);
|
21336 | }
|
21337 |
|
21338 | function expand(start, stop, options) {
|
21339 | var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);
|
21340 | var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);
|
21341 |
|
21342 | var step = Math.abs(toNumber(options.step)) || 1;
|
21343 | if (options.toRegex && step === 1) {
|
21344 | return toRange(a, b, start, stop, options);
|
21345 | }
|
21346 |
|
21347 | var zero = {greater: [], lesser: []};
|
21348 | var asc = a < b;
|
21349 | var arr = new Array(Math.round((asc ? b - a : a - b) / step));
|
21350 | var idx = 0;
|
21351 |
|
21352 | while (asc ? a <= b : a >= b) {
|
21353 | var val = options.isNumber ? a : String.fromCharCode(a);
|
21354 | if (options.toRegex && (val >= 0 || !options.isNumber)) {
|
21355 | zero.greater.push(val);
|
21356 | } else {
|
21357 | zero.lesser.push(Math.abs(val));
|
21358 | }
|
21359 |
|
21360 | if (options.isPadded) {
|
21361 | val = zeros(val, options);
|
21362 | }
|
21363 |
|
21364 | if (options.toString) {
|
21365 | val = String(val);
|
21366 | }
|
21367 |
|
21368 | if (typeof options.transform === 'function') {
|
21369 | arr[idx++] = options.transform(val, a, b, step, idx, arr, options);
|
21370 | } else {
|
21371 | arr[idx++] = val;
|
21372 | }
|
21373 |
|
21374 | if (asc) {
|
21375 | a += step;
|
21376 | } else {
|
21377 | a -= step;
|
21378 | }
|
21379 | }
|
21380 |
|
21381 | if (options.toRegex === true) {
|
21382 | return toSequence(arr, zero, options);
|
21383 | }
|
21384 | return arr;
|
21385 | }
|
21386 |
|
21387 | function toRange(a, b, start, stop, options) {
|
21388 | if (options.isPadded) {
|
21389 | return toRegexRange_1(start, stop, options);
|
21390 | }
|
21391 |
|
21392 | if (options.isNumber) {
|
21393 | return toRegexRange_1(Math.min(a, b), Math.max(a, b), options);
|
21394 | }
|
21395 |
|
21396 | var start = String.fromCharCode(Math.min(a, b));
|
21397 | var stop = String.fromCharCode(Math.max(a, b));
|
21398 | return '[' + start + '-' + stop + ']';
|
21399 | }
|
21400 |
|
21401 | function toSequence(arr, zeros, options) {
|
21402 | var greater = '', lesser = '';
|
21403 | if (zeros.greater.length) {
|
21404 | greater = zeros.greater.join('|');
|
21405 | }
|
21406 | if (zeros.lesser.length) {
|
21407 | lesser = '-(' + zeros.lesser.join('|') + ')';
|
21408 | }
|
21409 | var res = greater && lesser
|
21410 | ? greater + '|' + lesser
|
21411 | : greater || lesser;
|
21412 |
|
21413 | if (options.capture) {
|
21414 | return '(' + res + ')';
|
21415 | }
|
21416 | return res;
|
21417 | }
|
21418 |
|
21419 | function zeros(val, options) {
|
21420 | if (options.isPadded) {
|
21421 | var str = String(val);
|
21422 | var len = str.length;
|
21423 | var dash = '';
|
21424 | if (str.charAt(0) === '-') {
|
21425 | dash = '-';
|
21426 | str = str.slice(1);
|
21427 | }
|
21428 | var diff = options.maxLength - len;
|
21429 | var pad = repeatString('0', diff);
|
21430 | val = (dash + pad + str);
|
21431 | }
|
21432 | if (options.stringify) {
|
21433 | return String(val);
|
21434 | }
|
21435 | return val;
|
21436 | }
|
21437 |
|
21438 | function toNumber(val) {
|
21439 | return Number(val) || 0;
|
21440 | }
|
21441 |
|
21442 | function isPadded(str) {
|
21443 | return /^-?0\d/.test(str);
|
21444 | }
|
21445 |
|
21446 | function isValid(min, max) {
|
21447 | return (isValidNumber(min) || isValidLetter(min))
|
21448 | && (isValidNumber(max) || isValidLetter(max));
|
21449 | }
|
21450 |
|
21451 | function isValidLetter(ch) {
|
21452 | return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch);
|
21453 | }
|
21454 |
|
21455 | function isValidNumber(n) {
|
21456 | return isNumber(n) && !/\./.test(n);
|
21457 | }
|
21458 |
|
21459 | /**
|
21460 | * Expose `fillRange`
|
21461 | * @type {Function}
|
21462 | */
|
21463 |
|
21464 | var fillRange_1 = fillRange;
|
21465 |
|
21466 | /*!
|
21467 | * repeat-element <https://github.com/jonschlinkert/repeat-element>
|
21468 | *
|
21469 | * Copyright (c) 2015-present, Jon Schlinkert.
|
21470 | * Licensed under the MIT license.
|
21471 | */
|
21472 |
|
21473 | var repeatElement = function repeat(ele, num) {
|
21474 | var arr = new Array(num);
|
21475 |
|
21476 | for (var i = 0; i < num; i++) {
|
21477 | arr[i] = ele;
|
21478 | }
|
21479 |
|
21480 | return arr;
|
21481 | };
|
21482 |
|
21483 | var utils_1 = createCommonjsModule(function (module) {
|
21484 |
|
21485 |
|
21486 | var utils = module.exports;
|
21487 |
|
21488 | /**
|
21489 | * Module dependencies
|
21490 | */
|
21491 |
|
21492 | utils.extend = extendShallow$1;
|
21493 | utils.flatten = arrFlatten;
|
21494 | utils.isObject = isobject;
|
21495 | utils.fillRange = fillRange_1;
|
21496 | utils.repeat = repeatElement;
|
21497 | utils.unique = arrayUnique;
|
21498 |
|
21499 | utils.define = function(obj, key, val) {
|
21500 | Object.defineProperty(obj, key, {
|
21501 | writable: true,
|
21502 | configurable: true,
|
21503 | enumerable: false,
|
21504 | value: val
|
21505 | });
|
21506 | };
|
21507 |
|
21508 | /**
|
21509 | * Returns true if the given string contains only empty brace sets.
|
21510 | */
|
21511 |
|
21512 | utils.isEmptySets = function(str) {
|
21513 | return /^(?:\{,\})+$/.test(str);
|
21514 | };
|
21515 |
|
21516 | /**
|
21517 | * Returns true if the given string contains only empty brace sets.
|
21518 | */
|
21519 |
|
21520 | utils.isQuotedString = function(str) {
|
21521 | var open = str.charAt(0);
|
21522 | if (open === '\'' || open === '"' || open === '`') {
|
21523 | return str.slice(-1) === open;
|
21524 | }
|
21525 | return false;
|
21526 | };
|
21527 |
|
21528 | /**
|
21529 | * Create the key to use for memoization. The unique key is generated
|
21530 | * by iterating over the options and concatenating key-value pairs
|
21531 | * to the pattern string.
|
21532 | */
|
21533 |
|
21534 | utils.createKey = function(pattern, options) {
|
21535 | var id = pattern;
|
21536 | if (typeof options === 'undefined') {
|
21537 | return id;
|
21538 | }
|
21539 | var keys = Object.keys(options);
|
21540 | for (var i = 0; i < keys.length; i++) {
|
21541 | var key = keys[i];
|
21542 | id += ';' + key + '=' + String(options[key]);
|
21543 | }
|
21544 | return id;
|
21545 | };
|
21546 |
|
21547 | /**
|
21548 | * Normalize options
|
21549 | */
|
21550 |
|
21551 | utils.createOptions = function(options) {
|
21552 | var opts = utils.extend.apply(null, arguments);
|
21553 | if (typeof opts.expand === 'boolean') {
|
21554 | opts.optimize = !opts.expand;
|
21555 | }
|
21556 | if (typeof opts.optimize === 'boolean') {
|
21557 | opts.expand = !opts.optimize;
|
21558 | }
|
21559 | if (opts.optimize === true) {
|
21560 | opts.makeRe = true;
|
21561 | }
|
21562 | return opts;
|
21563 | };
|
21564 |
|
21565 | /**
|
21566 | * Join patterns in `a` to patterns in `b`
|
21567 | */
|
21568 |
|
21569 | utils.join = function(a, b, options) {
|
21570 | options = options || {};
|
21571 | a = utils.arrayify(a);
|
21572 | b = utils.arrayify(b);
|
21573 |
|
21574 | if (!a.length) return b;
|
21575 | if (!b.length) return a;
|
21576 |
|
21577 | var len = a.length;
|
21578 | var idx = -1;
|
21579 | var arr = [];
|
21580 |
|
21581 | while (++idx < len) {
|
21582 | var val = a[idx];
|
21583 | if (Array.isArray(val)) {
|
21584 | for (var i = 0; i < val.length; i++) {
|
21585 | val[i] = utils.join(val[i], b, options);
|
21586 | }
|
21587 | arr.push(val);
|
21588 | continue;
|
21589 | }
|
21590 |
|
21591 | for (var j = 0; j < b.length; j++) {
|
21592 | var bval = b[j];
|
21593 |
|
21594 | if (Array.isArray(bval)) {
|
21595 | arr.push(utils.join(val, bval, options));
|
21596 | } else {
|
21597 | arr.push(val + bval);
|
21598 | }
|
21599 | }
|
21600 | }
|
21601 | return arr;
|
21602 | };
|
21603 |
|
21604 | /**
|
21605 | * Split the given string on `,` if not escaped.
|
21606 | */
|
21607 |
|
21608 | utils.split = function(str, options) {
|
21609 | var opts = utils.extend({sep: ','}, options);
|
21610 | if (typeof opts.keepQuotes !== 'boolean') {
|
21611 | opts.keepQuotes = true;
|
21612 | }
|
21613 | if (opts.unescape === false) {
|
21614 | opts.keepEscaping = true;
|
21615 | }
|
21616 | return splitString(str, opts, utils.escapeBrackets(opts));
|
21617 | };
|
21618 |
|
21619 | /**
|
21620 | * Expand ranges or sets in the given `pattern`.
|
21621 | *
|
21622 | * @param {String} `str`
|
21623 | * @param {Object} `options`
|
21624 | * @return {Object}
|
21625 | */
|
21626 |
|
21627 | utils.expand = function(str, options) {
|
21628 | var opts = utils.extend({rangeLimit: 10000}, options);
|
21629 | var segs = utils.split(str, opts);
|
21630 | var tok = { segs: segs };
|
21631 |
|
21632 | if (utils.isQuotedString(str)) {
|
21633 | return tok;
|
21634 | }
|
21635 |
|
21636 | if (opts.rangeLimit === true) {
|
21637 | opts.rangeLimit = 10000;
|
21638 | }
|
21639 |
|
21640 | if (segs.length > 1) {
|
21641 | if (opts.optimize === false) {
|
21642 | tok.val = segs[0];
|
21643 | return tok;
|
21644 | }
|
21645 |
|
21646 | tok.segs = utils.stringifyArray(tok.segs);
|
21647 | } else if (segs.length === 1) {
|
21648 | var arr = str.split('..');
|
21649 |
|
21650 | if (arr.length === 1) {
|
21651 | tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
|
21652 | tok.segs = [];
|
21653 | return tok;
|
21654 | }
|
21655 |
|
21656 | if (arr.length === 2 && arr[0] === arr[1]) {
|
21657 | tok.escaped = true;
|
21658 | tok.val = arr[0];
|
21659 | tok.segs = [];
|
21660 | return tok;
|
21661 | }
|
21662 |
|
21663 | if (arr.length > 1) {
|
21664 | if (opts.optimize !== false) {
|
21665 | opts.optimize = true;
|
21666 | delete opts.expand;
|
21667 | }
|
21668 |
|
21669 | if (opts.optimize !== true) {
|
21670 | var min = Math.min(arr[0], arr[1]);
|
21671 | var max = Math.max(arr[0], arr[1]);
|
21672 | var step = arr[2] || 1;
|
21673 |
|
21674 | if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
|
21675 | throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
|
21676 | }
|
21677 | }
|
21678 |
|
21679 | arr.push(opts);
|
21680 | tok.segs = utils.fillRange.apply(null, arr);
|
21681 |
|
21682 | if (!tok.segs.length) {
|
21683 | tok.escaped = true;
|
21684 | tok.val = str;
|
21685 | return tok;
|
21686 | }
|
21687 |
|
21688 | if (opts.optimize === true) {
|
21689 | tok.segs = utils.stringifyArray(tok.segs);
|
21690 | }
|
21691 |
|
21692 | if (tok.segs === '') {
|
21693 | tok.val = str;
|
21694 | } else {
|
21695 | tok.val = tok.segs[0];
|
21696 | }
|
21697 | return tok;
|
21698 | }
|
21699 | } else {
|
21700 | tok.val = str;
|
21701 | }
|
21702 | return tok;
|
21703 | };
|
21704 |
|
21705 | /**
|
21706 | * Ensure commas inside brackets and parens are not split.
|
21707 | * @param {Object} `tok` Token from the `split-string` module
|
21708 | * @return {undefined}
|
21709 | */
|
21710 |
|
21711 | utils.escapeBrackets = function(options) {
|
21712 | return function(tok) {
|
21713 | if (tok.escaped && tok.val === 'b') {
|
21714 | tok.val = '\\b';
|
21715 | return;
|
21716 | }
|
21717 |
|
21718 | if (tok.val !== '(' && tok.val !== '[') return;
|
21719 | var opts = utils.extend({}, options);
|
21720 | var stack = [];
|
21721 | var val = tok.val;
|
21722 | var str = tok.str;
|
21723 | var i = tok.idx - 1;
|
21724 |
|
21725 | while (++i < str.length) {
|
21726 | var ch = str[i];
|
21727 |
|
21728 | if (ch === '\\') {
|
21729 | val += (opts.keepEscaping === false ? '' : ch) + str[++i];
|
21730 | continue;
|
21731 | }
|
21732 |
|
21733 | if (ch === '(') {
|
21734 | stack.push(ch);
|
21735 | }
|
21736 |
|
21737 | if (ch === '[') {
|
21738 | stack.push(ch);
|
21739 | }
|
21740 |
|
21741 | if (ch === ')') {
|
21742 | stack.pop();
|
21743 | if (!stack.length) {
|
21744 | val += ch;
|
21745 | break;
|
21746 | }
|
21747 | }
|
21748 |
|
21749 | if (ch === ']') {
|
21750 | stack.pop();
|
21751 | if (!stack.length) {
|
21752 | val += ch;
|
21753 | break;
|
21754 | }
|
21755 | }
|
21756 | val += ch;
|
21757 | }
|
21758 |
|
21759 | tok.split = false;
|
21760 | tok.val = val.slice(1);
|
21761 | tok.idx = i;
|
21762 | };
|
21763 | };
|
21764 |
|
21765 | /**
|
21766 | * Returns true if the given string looks like a regex quantifier
|
21767 | * @return {Boolean}
|
21768 | */
|
21769 |
|
21770 | utils.isQuantifier = function(str) {
|
21771 | return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
|
21772 | };
|
21773 |
|
21774 | /**
|
21775 | * Cast `val` to an array.
|
21776 | * @param {*} `val`
|
21777 | */
|
21778 |
|
21779 | utils.stringifyArray = function(arr) {
|
21780 | return [utils.arrayify(arr).join('|')];
|
21781 | };
|
21782 |
|
21783 | /**
|
21784 | * Cast `val` to an array.
|
21785 | * @param {*} `val`
|
21786 | */
|
21787 |
|
21788 | utils.arrayify = function(arr) {
|
21789 | if (typeof arr === 'undefined') {
|
21790 | return [];
|
21791 | }
|
21792 | if (typeof arr === 'string') {
|
21793 | return [arr];
|
21794 | }
|
21795 | return arr;
|
21796 | };
|
21797 |
|
21798 | /**
|
21799 | * Returns true if the given `str` is a non-empty string
|
21800 | * @return {Boolean}
|
21801 | */
|
21802 |
|
21803 | utils.isString = function(str) {
|
21804 | return str != null && typeof str === 'string';
|
21805 | };
|
21806 |
|
21807 | /**
|
21808 | * Get the last element from `array`
|
21809 | * @param {Array} `array`
|
21810 | * @return {*}
|
21811 | */
|
21812 |
|
21813 | utils.last = function(arr, n) {
|
21814 | return arr[arr.length - (n || 1)];
|
21815 | };
|
21816 |
|
21817 | utils.escapeRegex = function(str) {
|
21818 | return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
|
21819 | };
|
21820 | });
|
21821 |
|
21822 | var compilers = function(braces, options) {
|
21823 | braces.compiler
|
21824 |
|
21825 | /**
|
21826 | * bos
|
21827 | */
|
21828 |
|
21829 | .set('bos', function() {
|
21830 | if (this.output) return;
|
21831 | this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
|
21832 | this.ast.count = 1;
|
21833 | })
|
21834 |
|
21835 | /**
|
21836 | * Square brackets
|
21837 | */
|
21838 |
|
21839 | .set('bracket', function(node) {
|
21840 | var close = node.close;
|
21841 | var open = !node.escaped ? '[' : '\\[';
|
21842 | var negated = node.negated;
|
21843 | var inner = node.inner;
|
21844 |
|
21845 | inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
|
21846 | if (inner === ']-') {
|
21847 | inner = '\\]\\-';
|
21848 | }
|
21849 |
|
21850 | if (negated && inner.indexOf('.') === -1) {
|
21851 | inner += '.';
|
21852 | }
|
21853 | if (negated && inner.indexOf('/') === -1) {
|
21854 | inner += '/';
|
21855 | }
|
21856 |
|
21857 | var val = open + negated + inner + close;
|
21858 | var queue = node.parent.queue;
|
21859 | var last = utils_1.arrayify(queue.pop());
|
21860 |
|
21861 | queue.push(utils_1.join(last, val));
|
21862 | queue.push.apply(queue, []);
|
21863 | })
|
21864 |
|
21865 | /**
|
21866 | * Brace
|
21867 | */
|
21868 |
|
21869 | .set('brace', function(node) {
|
21870 | node.queue = isEscaped(node) ? [node.val] : [];
|
21871 | node.count = 1;
|
21872 | return this.mapVisit(node.nodes);
|
21873 | })
|
21874 |
|
21875 | /**
|
21876 | * Open
|
21877 | */
|
21878 |
|
21879 | .set('brace.open', function(node) {
|
21880 | node.parent.open = node.val;
|
21881 | })
|
21882 |
|
21883 | /**
|
21884 | * Inner
|
21885 | */
|
21886 |
|
21887 | .set('text', function(node) {
|
21888 | var queue = node.parent.queue;
|
21889 | var escaped = node.escaped;
|
21890 | var segs = [node.val];
|
21891 |
|
21892 | if (node.optimize === false) {
|
21893 | options = utils_1.extend({}, options, {optimize: false});
|
21894 | }
|
21895 |
|
21896 | if (node.multiplier > 1) {
|
21897 | node.parent.count *= node.multiplier;
|
21898 | }
|
21899 |
|
21900 | if (options.quantifiers === true && utils_1.isQuantifier(node.val)) {
|
21901 | escaped = true;
|
21902 |
|
21903 | } else if (node.val.length > 1) {
|
21904 | if (isType(node.parent, 'brace') && !isEscaped(node)) {
|
21905 | var expanded = utils_1.expand(node.val, options);
|
21906 | segs = expanded.segs;
|
21907 |
|
21908 | if (expanded.isOptimized) {
|
21909 | node.parent.isOptimized = true;
|
21910 | }
|
21911 |
|
21912 | // if nothing was expanded, we probably have a literal brace
|
21913 | if (!segs.length) {
|
21914 | var val = (expanded.val || node.val);
|
21915 | if (options.unescape !== false) {
|
21916 | // unescape unexpanded brace sequence/set separators
|
21917 | val = val.replace(/\\([,.])/g, '$1');
|
21918 | // strip quotes
|
21919 | val = val.replace(/["'`]/g, '');
|
21920 | }
|
21921 |
|
21922 | segs = [val];
|
21923 | escaped = true;
|
21924 | }
|
21925 | }
|
21926 |
|
21927 | } else if (node.val === ',') {
|
21928 | if (options.expand) {
|
21929 | node.parent.queue.push(['']);
|
21930 | segs = [''];
|
21931 | } else {
|
21932 | segs = ['|'];
|
21933 | }
|
21934 | } else {
|
21935 | escaped = true;
|
21936 | }
|
21937 |
|
21938 | if (escaped && isType(node.parent, 'brace')) {
|
21939 | if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
|
21940 | node.parent.escaped = true;
|
21941 | } else if (node.parent.length <= 3) {
|
21942 | node.parent.escaped = true;
|
21943 | }
|
21944 | }
|
21945 |
|
21946 | if (!hasQueue(node.parent)) {
|
21947 | node.parent.queue = segs;
|
21948 | return;
|
21949 | }
|
21950 |
|
21951 | var last = utils_1.arrayify(queue.pop());
|
21952 | if (node.parent.count > 1 && options.expand) {
|
21953 | last = multiply(last, node.parent.count);
|
21954 | node.parent.count = 1;
|
21955 | }
|
21956 |
|
21957 | queue.push(utils_1.join(utils_1.flatten(last), segs.shift()));
|
21958 | queue.push.apply(queue, segs);
|
21959 | })
|
21960 |
|
21961 | /**
|
21962 | * Close
|
21963 | */
|
21964 |
|
21965 | .set('brace.close', function(node) {
|
21966 | var queue = node.parent.queue;
|
21967 | var prev = node.parent.parent;
|
21968 | var last = prev.queue.pop();
|
21969 | var open = node.parent.open;
|
21970 | var close = node.val;
|
21971 |
|
21972 | if (open && close && isOptimized(node, options)) {
|
21973 | open = '(';
|
21974 | close = ')';
|
21975 | }
|
21976 |
|
21977 | // if a close brace exists, and the previous segment is one character
|
21978 | // don't wrap the result in braces or parens
|
21979 | var ele = utils_1.last(queue);
|
21980 | if (node.parent.count > 1 && options.expand) {
|
21981 | ele = multiply(queue.pop(), node.parent.count);
|
21982 | node.parent.count = 1;
|
21983 | queue.push(ele);
|
21984 | }
|
21985 |
|
21986 | if (close && typeof ele === 'string' && ele.length === 1) {
|
21987 | open = '';
|
21988 | close = '';
|
21989 | }
|
21990 |
|
21991 | if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
|
21992 | queue.push(utils_1.join(open, queue.pop() || ''));
|
21993 | queue = utils_1.flatten(utils_1.join(queue, close));
|
21994 | }
|
21995 |
|
21996 | if (typeof last === 'undefined') {
|
21997 | prev.queue = [queue];
|
21998 | } else {
|
21999 | prev.queue.push(utils_1.flatten(utils_1.join(last, queue)));
|
22000 | }
|
22001 | })
|
22002 |
|
22003 | /**
|
22004 | * eos
|
22005 | */
|
22006 |
|
22007 | .set('eos', function(node) {
|
22008 | if (this.input) return;
|
22009 |
|
22010 | if (options.optimize !== false) {
|
22011 | this.output = utils_1.last(utils_1.flatten(this.ast.queue));
|
22012 | } else if (Array.isArray(utils_1.last(this.ast.queue))) {
|
22013 | this.output = utils_1.flatten(this.ast.queue.pop());
|
22014 | } else {
|
22015 | this.output = utils_1.flatten(this.ast.queue);
|
22016 | }
|
22017 |
|
22018 | if (node.parent.count > 1 && options.expand) {
|
22019 | this.output = multiply(this.output, node.parent.count);
|
22020 | }
|
22021 |
|
22022 | this.output = utils_1.arrayify(this.output);
|
22023 | this.ast.queue = [];
|
22024 | });
|
22025 |
|
22026 | };
|
22027 |
|
22028 | /**
|
22029 | * Multiply the segments in the current brace level
|
22030 | */
|
22031 |
|
22032 | function multiply(queue, n, options) {
|
22033 | return utils_1.flatten(utils_1.repeat(utils_1.arrayify(queue), n));
|
22034 | }
|
22035 |
|
22036 | /**
|
22037 | * Return true if `node` is escaped
|
22038 | */
|
22039 |
|
22040 | function isEscaped(node) {
|
22041 | return node.escaped === true;
|
22042 | }
|
22043 |
|
22044 | /**
|
22045 | * Returns true if regex parens should be used for sets. If the parent `type`
|
22046 | * is not `brace`, then we're on a root node, which means we should never
|
22047 | * expand segments and open/close braces should be `{}` (since this indicates
|
22048 | * a brace is missing from the set)
|
22049 | */
|
22050 |
|
22051 | function isOptimized(node, options) {
|
22052 | if (node.parent.isOptimized) return true;
|
22053 | return isType(node.parent, 'brace')
|
22054 | && !isEscaped(node.parent)
|
22055 | && options.expand !== true;
|
22056 | }
|
22057 |
|
22058 | /**
|
22059 | * Returns true if the value in `node` should be wrapped in a literal brace.
|
22060 | * @return {Boolean}
|
22061 | */
|
22062 |
|
22063 | function isLiteralBrace(node, options) {
|
22064 | return isEscaped(node.parent) || options.optimize !== false;
|
22065 | }
|
22066 |
|
22067 | /**
|
22068 | * Returns true if the given `node` does not have an inner value.
|
22069 | * @return {Boolean}
|
22070 | */
|
22071 |
|
22072 | function noInner(node, type) {
|
22073 | if (node.parent.queue.length === 1) {
|
22074 | return true;
|
22075 | }
|
22076 | var nodes = node.parent.nodes;
|
22077 | return nodes.length === 3
|
22078 | && isType(nodes[0], 'brace.open')
|
22079 | && !isType(nodes[1], 'text')
|
22080 | && isType(nodes[2], 'brace.close');
|
22081 | }
|
22082 |
|
22083 | /**
|
22084 | * Returns true if the given `node` is the given `type`
|
22085 | * @return {Boolean}
|
22086 | */
|
22087 |
|
22088 | function isType(node, type) {
|
22089 | return typeof node !== 'undefined' && node.type === type;
|
22090 | }
|
22091 |
|
22092 | /**
|
22093 | * Returns true if the given `node` has a non-empty queue.
|
22094 | * @return {Boolean}
|
22095 | */
|
22096 |
|
22097 | function hasQueue(node) {
|
22098 | return Array.isArray(node.queue) && node.queue.length;
|
22099 | }
|
22100 |
|
22101 | // accessor descriptor properties
|
22102 | var accessor$1 = {
|
22103 | get: 'function',
|
22104 | set: 'function',
|
22105 | configurable: 'boolean',
|
22106 | enumerable: 'boolean'
|
22107 | };
|
22108 |
|
22109 | function isAccessorDescriptor$1(obj, prop) {
|
22110 | if (typeof prop === 'string') {
|
22111 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
22112 | return typeof val !== 'undefined';
|
22113 | }
|
22114 |
|
22115 | if (kindOf(obj) !== 'object') {
|
22116 | return false;
|
22117 | }
|
22118 |
|
22119 | if (has$2(obj, 'value') || has$2(obj, 'writable')) {
|
22120 | return false;
|
22121 | }
|
22122 |
|
22123 | if (!has$2(obj, 'get') || typeof obj.get !== 'function') {
|
22124 | return false;
|
22125 | }
|
22126 |
|
22127 | // tldr: it's valid to have "set" be undefined
|
22128 | // "set" might be undefined if `Object.getOwnPropertyDescriptor`
|
22129 | // was used to get the value, and only `get` was defined by the user
|
22130 | if (has$2(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
|
22131 | return false;
|
22132 | }
|
22133 |
|
22134 | for (var key in obj) {
|
22135 | if (!accessor$1.hasOwnProperty(key)) {
|
22136 | continue;
|
22137 | }
|
22138 |
|
22139 | if (kindOf(obj[key]) === accessor$1[key]) {
|
22140 | continue;
|
22141 | }
|
22142 |
|
22143 | if (typeof obj[key] !== 'undefined') {
|
22144 | return false;
|
22145 | }
|
22146 | }
|
22147 | return true;
|
22148 | }
|
22149 |
|
22150 | function has$2(obj, key) {
|
22151 | return {}.hasOwnProperty.call(obj, key);
|
22152 | }
|
22153 |
|
22154 | /**
|
22155 | * Expose `isAccessorDescriptor`
|
22156 | */
|
22157 |
|
22158 | var isAccessorDescriptor_1$1 = isAccessorDescriptor$1;
|
22159 |
|
22160 | var isDataDescriptor$1 = function isDataDescriptor(obj, prop) {
|
22161 | // data descriptor properties
|
22162 | var data = {
|
22163 | configurable: 'boolean',
|
22164 | enumerable: 'boolean',
|
22165 | writable: 'boolean'
|
22166 | };
|
22167 |
|
22168 | if (kindOf(obj) !== 'object') {
|
22169 | return false;
|
22170 | }
|
22171 |
|
22172 | if (typeof prop === 'string') {
|
22173 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
22174 | return typeof val !== 'undefined';
|
22175 | }
|
22176 |
|
22177 | if (!('value' in obj) && !('writable' in obj)) {
|
22178 | return false;
|
22179 | }
|
22180 |
|
22181 | for (var key in obj) {
|
22182 | if (key === 'value') continue;
|
22183 |
|
22184 | if (!data.hasOwnProperty(key)) {
|
22185 | continue;
|
22186 | }
|
22187 |
|
22188 | if (kindOf(obj[key]) === data[key]) {
|
22189 | continue;
|
22190 | }
|
22191 |
|
22192 | if (typeof obj[key] !== 'undefined') {
|
22193 | return false;
|
22194 | }
|
22195 | }
|
22196 | return true;
|
22197 | };
|
22198 |
|
22199 | var isDescriptor$1 = function isDescriptor(obj, key) {
|
22200 | if (kindOf(obj) !== 'object') {
|
22201 | return false;
|
22202 | }
|
22203 | if ('get' in obj) {
|
22204 | return isAccessorDescriptor_1$1(obj, key);
|
22205 | }
|
22206 | return isDataDescriptor$1(obj, key);
|
22207 | };
|
22208 |
|
22209 | var defineProperty$1 = function defineProperty(obj, prop, val) {
|
22210 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
22211 | throw new TypeError('expected an object or function.');
|
22212 | }
|
22213 |
|
22214 | if (typeof prop !== 'string') {
|
22215 | throw new TypeError('expected `prop` to be a string.');
|
22216 | }
|
22217 |
|
22218 | if (isDescriptor$1(val) && ('set' in val || 'get' in val)) {
|
22219 | return Object.defineProperty(obj, prop, val);
|
22220 | }
|
22221 |
|
22222 | return Object.defineProperty(obj, prop, {
|
22223 | configurable: true,
|
22224 | enumerable: false,
|
22225 | writable: true,
|
22226 | value: val
|
22227 | });
|
22228 | };
|
22229 |
|
22230 | var toString$3 = Object.prototype.toString;
|
22231 |
|
22232 | /**
|
22233 | * Get the native `typeof` a value.
|
22234 | *
|
22235 | * @param {*} `val`
|
22236 | * @return {*} Native javascript type
|
22237 | */
|
22238 |
|
22239 | var kindOf$2 = function kindOf(val) {
|
22240 | // primitivies
|
22241 | if (typeof val === 'undefined') {
|
22242 | return 'undefined';
|
22243 | }
|
22244 | if (val === null) {
|
22245 | return 'null';
|
22246 | }
|
22247 | if (val === true || val === false || val instanceof Boolean) {
|
22248 | return 'boolean';
|
22249 | }
|
22250 | if (typeof val === 'string' || val instanceof String) {
|
22251 | return 'string';
|
22252 | }
|
22253 | if (typeof val === 'number' || val instanceof Number) {
|
22254 | return 'number';
|
22255 | }
|
22256 |
|
22257 | // functions
|
22258 | if (typeof val === 'function' || val instanceof Function) {
|
22259 | return 'function';
|
22260 | }
|
22261 |
|
22262 | // array
|
22263 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
22264 | return 'array';
|
22265 | }
|
22266 |
|
22267 | // check for instances of RegExp and Date before calling `toString`
|
22268 | if (val instanceof RegExp) {
|
22269 | return 'regexp';
|
22270 | }
|
22271 | if (val instanceof Date) {
|
22272 | return 'date';
|
22273 | }
|
22274 |
|
22275 | // other objects
|
22276 | var type = toString$3.call(val);
|
22277 |
|
22278 | if (type === '[object RegExp]') {
|
22279 | return 'regexp';
|
22280 | }
|
22281 | if (type === '[object Date]') {
|
22282 | return 'date';
|
22283 | }
|
22284 | if (type === '[object Arguments]') {
|
22285 | return 'arguments';
|
22286 | }
|
22287 | if (type === '[object Error]') {
|
22288 | return 'error';
|
22289 | }
|
22290 |
|
22291 | // buffer
|
22292 | if (isBuffer_1(val)) {
|
22293 | return 'buffer';
|
22294 | }
|
22295 |
|
22296 | // es6: Map, WeakMap, Set, WeakSet
|
22297 | if (type === '[object Set]') {
|
22298 | return 'set';
|
22299 | }
|
22300 | if (type === '[object WeakSet]') {
|
22301 | return 'weakset';
|
22302 | }
|
22303 | if (type === '[object Map]') {
|
22304 | return 'map';
|
22305 | }
|
22306 | if (type === '[object WeakMap]') {
|
22307 | return 'weakmap';
|
22308 | }
|
22309 | if (type === '[object Symbol]') {
|
22310 | return 'symbol';
|
22311 | }
|
22312 |
|
22313 | // typed arrays
|
22314 | if (type === '[object Int8Array]') {
|
22315 | return 'int8array';
|
22316 | }
|
22317 | if (type === '[object Uint8Array]') {
|
22318 | return 'uint8array';
|
22319 | }
|
22320 | if (type === '[object Uint8ClampedArray]') {
|
22321 | return 'uint8clampedarray';
|
22322 | }
|
22323 | if (type === '[object Int16Array]') {
|
22324 | return 'int16array';
|
22325 | }
|
22326 | if (type === '[object Uint16Array]') {
|
22327 | return 'uint16array';
|
22328 | }
|
22329 | if (type === '[object Int32Array]') {
|
22330 | return 'int32array';
|
22331 | }
|
22332 | if (type === '[object Uint32Array]') {
|
22333 | return 'uint32array';
|
22334 | }
|
22335 | if (type === '[object Float32Array]') {
|
22336 | return 'float32array';
|
22337 | }
|
22338 | if (type === '[object Float64Array]') {
|
22339 | return 'float64array';
|
22340 | }
|
22341 |
|
22342 | // must be a plain object
|
22343 | return 'object';
|
22344 | };
|
22345 |
|
22346 | var snapdragonUtil = createCommonjsModule(function (module) {
|
22347 |
|
22348 |
|
22349 | var utils = module.exports;
|
22350 |
|
22351 | /**
|
22352 | * Returns true if the given value is a node.
|
22353 | *
|
22354 | * ```js
|
22355 | * var Node = require('snapdragon-node');
|
22356 | * var node = new Node({type: 'foo'});
|
22357 | * console.log(utils.isNode(node)); //=> true
|
22358 | * console.log(utils.isNode({})); //=> false
|
22359 | * ```
|
22360 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22361 | * @returns {Boolean}
|
22362 | * @api public
|
22363 | */
|
22364 |
|
22365 | utils.isNode = function(node) {
|
22366 | return kindOf$2(node) === 'object' && node.isNode === true;
|
22367 | };
|
22368 |
|
22369 | /**
|
22370 | * Emit an empty string for the given `node`.
|
22371 | *
|
22372 | * ```js
|
22373 | * // do nothing for beginning-of-string
|
22374 | * snapdragon.compiler.set('bos', utils.noop);
|
22375 | * ```
|
22376 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22377 | * @returns {undefined}
|
22378 | * @api public
|
22379 | */
|
22380 |
|
22381 | utils.noop = function(node) {
|
22382 | append(this, '', node);
|
22383 | };
|
22384 |
|
22385 | /**
|
22386 | * Appdend `node.val` to `compiler.output`, exactly as it was created
|
22387 | * by the parser.
|
22388 | *
|
22389 | * ```js
|
22390 | * snapdragon.compiler.set('text', utils.identity);
|
22391 | * ```
|
22392 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22393 | * @returns {undefined}
|
22394 | * @api public
|
22395 | */
|
22396 |
|
22397 | utils.identity = function(node) {
|
22398 | append(this, node.val, node);
|
22399 | };
|
22400 |
|
22401 | /**
|
22402 | * Previously named `.emit`, this method appends the given `val`
|
22403 | * to `compiler.output` for the given node. Useful when you know
|
22404 | * what value should be appended advance, regardless of the actual
|
22405 | * value of `node.val`.
|
22406 | *
|
22407 | * ```js
|
22408 | * snapdragon.compiler
|
22409 | * .set('i', function(node) {
|
22410 | * this.mapVisit(node);
|
22411 | * })
|
22412 | * .set('i.open', utils.append('<i>'))
|
22413 | * .set('i.close', utils.append('</i>'))
|
22414 | * ```
|
22415 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22416 | * @returns {Function} Returns a compiler middleware function.
|
22417 | * @api public
|
22418 | */
|
22419 |
|
22420 | utils.append = function(val) {
|
22421 | return function(node) {
|
22422 | append(this, val, node);
|
22423 | };
|
22424 | };
|
22425 |
|
22426 | /**
|
22427 | * Used in compiler middleware, this onverts an AST node into
|
22428 | * an empty `text` node and deletes `node.nodes` if it exists.
|
22429 | * The advantage of this method is that, as opposed to completely
|
22430 | * removing the node, indices will not need to be re-calculated
|
22431 | * in sibling nodes, and nothing is appended to the output.
|
22432 | *
|
22433 | * ```js
|
22434 | * utils.toNoop(node);
|
22435 | * // convert `node.nodes` to the given value instead of deleting it
|
22436 | * utils.toNoop(node, []);
|
22437 | * ```
|
22438 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22439 | * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.
|
22440 | * @api public
|
22441 | */
|
22442 |
|
22443 | utils.toNoop = function(node, nodes) {
|
22444 | if (nodes) {
|
22445 | node.nodes = nodes;
|
22446 | } else {
|
22447 | delete node.nodes;
|
22448 | node.type = 'text';
|
22449 | node.val = '';
|
22450 | }
|
22451 | };
|
22452 |
|
22453 | /**
|
22454 | * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon
|
22455 | * automatically calls registered compilers, this allows you to pass a visitor
|
22456 | * function.
|
22457 | *
|
22458 | * ```js
|
22459 | * snapdragon.compiler.set('i', function(node) {
|
22460 | * utils.visit(node, function(childNode) {
|
22461 | * // do stuff with "childNode"
|
22462 | * return childNode;
|
22463 | * });
|
22464 | * });
|
22465 | * ```
|
22466 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22467 | * @param {Function} `fn`
|
22468 | * @return {Object} returns the node after recursively visiting all child nodes.
|
22469 | * @api public
|
22470 | */
|
22471 |
|
22472 | utils.visit = function(node, fn) {
|
22473 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22474 | assert(isFunction(fn), 'expected a visitor function');
|
22475 | fn(node);
|
22476 | return node.nodes ? utils.mapVisit(node, fn) : node;
|
22477 | };
|
22478 |
|
22479 | /**
|
22480 | * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by
|
22481 | * [visit](#visit), use this method if you do not want `fn` to be called on
|
22482 | * the first node.
|
22483 | *
|
22484 | * ```js
|
22485 | * snapdragon.compiler.set('i', function(node) {
|
22486 | * utils.mapVisit(node, function(childNode) {
|
22487 | * // do stuff with "childNode"
|
22488 | * return childNode;
|
22489 | * });
|
22490 | * });
|
22491 | * ```
|
22492 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22493 | * @param {Object} `options`
|
22494 | * @param {Function} `fn`
|
22495 | * @return {Object} returns the node
|
22496 | * @api public
|
22497 | */
|
22498 |
|
22499 | utils.mapVisit = function(node, fn) {
|
22500 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22501 | assert(isArray(node.nodes), 'expected node.nodes to be an array');
|
22502 | assert(isFunction(fn), 'expected a visitor function');
|
22503 |
|
22504 | for (var i = 0; i < node.nodes.length; i++) {
|
22505 | utils.visit(node.nodes[i], fn);
|
22506 | }
|
22507 | return node;
|
22508 | };
|
22509 |
|
22510 | /**
|
22511 | * Unshift an `*.open` node onto `node.nodes`.
|
22512 | *
|
22513 | * ```js
|
22514 | * var Node = require('snapdragon-node');
|
22515 | * snapdragon.parser.set('brace', function(node) {
|
22516 | * var match = this.match(/^{/);
|
22517 | * if (match) {
|
22518 | * var parent = new Node({type: 'brace'});
|
22519 | * utils.addOpen(parent, Node);
|
22520 | * console.log(parent.nodes[0]):
|
22521 | * // { type: 'brace.open', val: '' };
|
22522 | *
|
22523 | * // push the parent "brace" node onto the stack
|
22524 | * this.push(parent);
|
22525 | *
|
22526 | * // return the parent node, so it's also added to the AST
|
22527 | * return brace;
|
22528 | * }
|
22529 | * });
|
22530 | * ```
|
22531 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22532 | * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
|
22533 | * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
|
22534 | * @return {Object} Returns the created opening node.
|
22535 | * @api public
|
22536 | */
|
22537 |
|
22538 | utils.addOpen = function(node, Node, val, filter) {
|
22539 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22540 | assert(isFunction(Node), 'expected Node to be a constructor function');
|
22541 |
|
22542 | if (typeof val === 'function') {
|
22543 | filter = val;
|
22544 | val = '';
|
22545 | }
|
22546 |
|
22547 | if (typeof filter === 'function' && !filter(node)) return;
|
22548 | var open = new Node({ type: node.type + '.open', val: val});
|
22549 | var unshift = node.unshift || node.unshiftNode;
|
22550 | if (typeof unshift === 'function') {
|
22551 | unshift.call(node, open);
|
22552 | } else {
|
22553 | utils.unshiftNode(node, open);
|
22554 | }
|
22555 | return open;
|
22556 | };
|
22557 |
|
22558 | /**
|
22559 | * Push a `*.close` node onto `node.nodes`.
|
22560 | *
|
22561 | * ```js
|
22562 | * var Node = require('snapdragon-node');
|
22563 | * snapdragon.parser.set('brace', function(node) {
|
22564 | * var match = this.match(/^}/);
|
22565 | * if (match) {
|
22566 | * var parent = this.parent();
|
22567 | * if (parent.type !== 'brace') {
|
22568 | * throw new Error('missing opening: ' + '}');
|
22569 | * }
|
22570 | *
|
22571 | * utils.addClose(parent, Node);
|
22572 | * console.log(parent.nodes[parent.nodes.length - 1]):
|
22573 | * // { type: 'brace.close', val: '' };
|
22574 | *
|
22575 | * // no need to return a node, since the parent
|
22576 | * // was already added to the AST
|
22577 | * return;
|
22578 | * }
|
22579 | * });
|
22580 | * ```
|
22581 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22582 | * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
|
22583 | * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
|
22584 | * @return {Object} Returns the created closing node.
|
22585 | * @api public
|
22586 | */
|
22587 |
|
22588 | utils.addClose = function(node, Node, val, filter) {
|
22589 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22590 | assert(isFunction(Node), 'expected Node to be a constructor function');
|
22591 |
|
22592 | if (typeof val === 'function') {
|
22593 | filter = val;
|
22594 | val = '';
|
22595 | }
|
22596 |
|
22597 | if (typeof filter === 'function' && !filter(node)) return;
|
22598 | var close = new Node({ type: node.type + '.close', val: val});
|
22599 | var push = node.push || node.pushNode;
|
22600 | if (typeof push === 'function') {
|
22601 | push.call(node, close);
|
22602 | } else {
|
22603 | utils.pushNode(node, close);
|
22604 | }
|
22605 | return close;
|
22606 | };
|
22607 |
|
22608 | /**
|
22609 | * Wraps the given `node` with `*.open` and `*.close` nodes.
|
22610 | *
|
22611 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22612 | * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
|
22613 | * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
|
22614 | * @return {Object} Returns the node
|
22615 | * @api public
|
22616 | */
|
22617 |
|
22618 | utils.wrapNodes = function(node, Node, filter) {
|
22619 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22620 | assert(isFunction(Node), 'expected Node to be a constructor function');
|
22621 |
|
22622 | utils.addOpen(node, Node, filter);
|
22623 | utils.addClose(node, Node, filter);
|
22624 | return node;
|
22625 | };
|
22626 |
|
22627 | /**
|
22628 | * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.
|
22629 | *
|
22630 | * ```js
|
22631 | * var parent = new Node({type: 'foo'});
|
22632 | * var node = new Node({type: 'bar'});
|
22633 | * utils.pushNode(parent, node);
|
22634 | * console.log(parent.nodes[0].type) // 'bar'
|
22635 | * console.log(node.parent.type) // 'foo'
|
22636 | * ```
|
22637 | * @param {Object} `parent`
|
22638 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22639 | * @return {Object} Returns the child node
|
22640 | * @api public
|
22641 | */
|
22642 |
|
22643 | utils.pushNode = function(parent, node) {
|
22644 | assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
|
22645 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22646 |
|
22647 | node.define('parent', parent);
|
22648 | parent.nodes = parent.nodes || [];
|
22649 | parent.nodes.push(node);
|
22650 | return node;
|
22651 | };
|
22652 |
|
22653 | /**
|
22654 | * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.
|
22655 | *
|
22656 | * ```js
|
22657 | * var parent = new Node({type: 'foo'});
|
22658 | * var node = new Node({type: 'bar'});
|
22659 | * utils.unshiftNode(parent, node);
|
22660 | * console.log(parent.nodes[0].type) // 'bar'
|
22661 | * console.log(node.parent.type) // 'foo'
|
22662 | * ```
|
22663 | * @param {Object} `parent`
|
22664 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22665 | * @return {undefined}
|
22666 | * @api public
|
22667 | */
|
22668 |
|
22669 | utils.unshiftNode = function(parent, node) {
|
22670 | assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
|
22671 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22672 |
|
22673 | node.define('parent', parent);
|
22674 | parent.nodes = parent.nodes || [];
|
22675 | parent.nodes.unshift(node);
|
22676 | };
|
22677 |
|
22678 | /**
|
22679 | * Pop the last `node` off of `parent.nodes`. The advantage of
|
22680 | * using this method is that it checks for `node.nodes` and works
|
22681 | * with any version of `snapdragon-node`.
|
22682 | *
|
22683 | * ```js
|
22684 | * var parent = new Node({type: 'foo'});
|
22685 | * utils.pushNode(parent, new Node({type: 'foo'}));
|
22686 | * utils.pushNode(parent, new Node({type: 'bar'}));
|
22687 | * utils.pushNode(parent, new Node({type: 'baz'}));
|
22688 | * console.log(parent.nodes.length); //=> 3
|
22689 | * utils.popNode(parent);
|
22690 | * console.log(parent.nodes.length); //=> 2
|
22691 | * ```
|
22692 | * @param {Object} `parent`
|
22693 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22694 | * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
|
22695 | * @api public
|
22696 | */
|
22697 |
|
22698 | utils.popNode = function(node) {
|
22699 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22700 | if (typeof node.pop === 'function') {
|
22701 | return node.pop();
|
22702 | }
|
22703 | return node.nodes && node.nodes.pop();
|
22704 | };
|
22705 |
|
22706 | /**
|
22707 | * Shift the first `node` off of `parent.nodes`. The advantage of
|
22708 | * using this method is that it checks for `node.nodes` and works
|
22709 | * with any version of `snapdragon-node`.
|
22710 | *
|
22711 | * ```js
|
22712 | * var parent = new Node({type: 'foo'});
|
22713 | * utils.pushNode(parent, new Node({type: 'foo'}));
|
22714 | * utils.pushNode(parent, new Node({type: 'bar'}));
|
22715 | * utils.pushNode(parent, new Node({type: 'baz'}));
|
22716 | * console.log(parent.nodes.length); //=> 3
|
22717 | * utils.shiftNode(parent);
|
22718 | * console.log(parent.nodes.length); //=> 2
|
22719 | * ```
|
22720 | * @param {Object} `parent`
|
22721 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22722 | * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
|
22723 | * @api public
|
22724 | */
|
22725 |
|
22726 | utils.shiftNode = function(node) {
|
22727 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22728 | if (typeof node.shift === 'function') {
|
22729 | return node.shift();
|
22730 | }
|
22731 | return node.nodes && node.nodes.shift();
|
22732 | };
|
22733 |
|
22734 | /**
|
22735 | * Remove the specified `node` from `parent.nodes`.
|
22736 | *
|
22737 | * ```js
|
22738 | * var parent = new Node({type: 'abc'});
|
22739 | * var foo = new Node({type: 'foo'});
|
22740 | * utils.pushNode(parent, foo);
|
22741 | * utils.pushNode(parent, new Node({type: 'bar'}));
|
22742 | * utils.pushNode(parent, new Node({type: 'baz'}));
|
22743 | * console.log(parent.nodes.length); //=> 3
|
22744 | * utils.removeNode(parent, foo);
|
22745 | * console.log(parent.nodes.length); //=> 2
|
22746 | * ```
|
22747 | * @param {Object} `parent`
|
22748 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22749 | * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.
|
22750 | * @api public
|
22751 | */
|
22752 |
|
22753 | utils.removeNode = function(parent, node) {
|
22754 | assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');
|
22755 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22756 |
|
22757 | if (!parent.nodes) {
|
22758 | return null;
|
22759 | }
|
22760 |
|
22761 | if (typeof parent.remove === 'function') {
|
22762 | return parent.remove(node);
|
22763 | }
|
22764 |
|
22765 | var idx = parent.nodes.indexOf(node);
|
22766 | if (idx !== -1) {
|
22767 | return parent.nodes.splice(idx, 1);
|
22768 | }
|
22769 | };
|
22770 |
|
22771 | /**
|
22772 | * Returns true if `node.type` matches the given `type`. Throws a
|
22773 | * `TypeError` if `node` is not an instance of `Node`.
|
22774 | *
|
22775 | * ```js
|
22776 | * var Node = require('snapdragon-node');
|
22777 | * var node = new Node({type: 'foo'});
|
22778 | * console.log(utils.isType(node, 'foo')); // false
|
22779 | * console.log(utils.isType(node, 'bar')); // true
|
22780 | * ```
|
22781 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22782 | * @param {String} `type`
|
22783 | * @return {Boolean}
|
22784 | * @api public
|
22785 | */
|
22786 |
|
22787 | utils.isType = function(node, type) {
|
22788 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22789 | switch (kindOf$2(type)) {
|
22790 | case 'array':
|
22791 | var types = type.slice();
|
22792 | for (var i = 0; i < types.length; i++) {
|
22793 | if (utils.isType(node, types[i])) {
|
22794 | return true;
|
22795 | }
|
22796 | }
|
22797 | return false;
|
22798 | case 'string':
|
22799 | return node.type === type;
|
22800 | case 'regexp':
|
22801 | return type.test(node.type);
|
22802 | default: {
|
22803 | throw new TypeError('expected "type" to be an array, string or regexp');
|
22804 | }
|
22805 | }
|
22806 | };
|
22807 |
|
22808 | /**
|
22809 | * Returns true if the given `node` has the given `type` in `node.nodes`.
|
22810 | * Throws a `TypeError` if `node` is not an instance of `Node`.
|
22811 | *
|
22812 | * ```js
|
22813 | * var Node = require('snapdragon-node');
|
22814 | * var node = new Node({
|
22815 | * type: 'foo',
|
22816 | * nodes: [
|
22817 | * new Node({type: 'bar'}),
|
22818 | * new Node({type: 'baz'})
|
22819 | * ]
|
22820 | * });
|
22821 | * console.log(utils.hasType(node, 'xyz')); // false
|
22822 | * console.log(utils.hasType(node, 'baz')); // true
|
22823 | * ```
|
22824 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22825 | * @param {String} `type`
|
22826 | * @return {Boolean}
|
22827 | * @api public
|
22828 | */
|
22829 |
|
22830 | utils.hasType = function(node, type) {
|
22831 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22832 | if (!Array.isArray(node.nodes)) return false;
|
22833 | for (var i = 0; i < node.nodes.length; i++) {
|
22834 | if (utils.isType(node.nodes[i], type)) {
|
22835 | return true;
|
22836 | }
|
22837 | }
|
22838 | return false;
|
22839 | };
|
22840 |
|
22841 | /**
|
22842 | * Returns the first node from `node.nodes` of the given `type`
|
22843 | *
|
22844 | * ```js
|
22845 | * var node = new Node({
|
22846 | * type: 'foo',
|
22847 | * nodes: [
|
22848 | * new Node({type: 'text', val: 'abc'}),
|
22849 | * new Node({type: 'text', val: 'xyz'})
|
22850 | * ]
|
22851 | * });
|
22852 | *
|
22853 | * var textNode = utils.firstOfType(node.nodes, 'text');
|
22854 | * console.log(textNode.val);
|
22855 | * //=> 'abc'
|
22856 | * ```
|
22857 | * @param {Array} `nodes`
|
22858 | * @param {String} `type`
|
22859 | * @return {Object|undefined} Returns the first matching node or undefined.
|
22860 | * @api public
|
22861 | */
|
22862 |
|
22863 | utils.firstOfType = function(nodes, type) {
|
22864 | for (var i = 0; i < nodes.length; i++) {
|
22865 | var node = nodes[i];
|
22866 | if (utils.isType(node, type)) {
|
22867 | return node;
|
22868 | }
|
22869 | }
|
22870 | };
|
22871 |
|
22872 | /**
|
22873 | * Returns the node at the specified index, or the first node of the
|
22874 | * given `type` from `node.nodes`.
|
22875 | *
|
22876 | * ```js
|
22877 | * var node = new Node({
|
22878 | * type: 'foo',
|
22879 | * nodes: [
|
22880 | * new Node({type: 'text', val: 'abc'}),
|
22881 | * new Node({type: 'text', val: 'xyz'})
|
22882 | * ]
|
22883 | * });
|
22884 | *
|
22885 | * var nodeOne = utils.findNode(node.nodes, 'text');
|
22886 | * console.log(nodeOne.val);
|
22887 | * //=> 'abc'
|
22888 | *
|
22889 | * var nodeTwo = utils.findNode(node.nodes, 1);
|
22890 | * console.log(nodeTwo.val);
|
22891 | * //=> 'xyz'
|
22892 | * ```
|
22893 | *
|
22894 | * @param {Array} `nodes`
|
22895 | * @param {String|Number} `type` Node type or index.
|
22896 | * @return {Object} Returns a node or undefined.
|
22897 | * @api public
|
22898 | */
|
22899 |
|
22900 | utils.findNode = function(nodes, type) {
|
22901 | if (!Array.isArray(nodes)) {
|
22902 | return null;
|
22903 | }
|
22904 | if (typeof type === 'number') {
|
22905 | return nodes[type];
|
22906 | }
|
22907 | return utils.firstOfType(nodes, type);
|
22908 | };
|
22909 |
|
22910 | /**
|
22911 | * Returns true if the given node is an "*.open" node.
|
22912 | *
|
22913 | * ```js
|
22914 | * var Node = require('snapdragon-node');
|
22915 | * var brace = new Node({type: 'brace'});
|
22916 | * var open = new Node({type: 'brace.open'});
|
22917 | * var close = new Node({type: 'brace.close'});
|
22918 | *
|
22919 | * console.log(utils.isOpen(brace)); // false
|
22920 | * console.log(utils.isOpen(open)); // true
|
22921 | * console.log(utils.isOpen(close)); // false
|
22922 | * ```
|
22923 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22924 | * @return {Boolean}
|
22925 | * @api public
|
22926 | */
|
22927 |
|
22928 | utils.isOpen = function(node) {
|
22929 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22930 | return node.type.slice(-5) === '.open';
|
22931 | };
|
22932 |
|
22933 | /**
|
22934 | * Returns true if the given node is a "*.close" node.
|
22935 | *
|
22936 | * ```js
|
22937 | * var Node = require('snapdragon-node');
|
22938 | * var brace = new Node({type: 'brace'});
|
22939 | * var open = new Node({type: 'brace.open'});
|
22940 | * var close = new Node({type: 'brace.close'});
|
22941 | *
|
22942 | * console.log(utils.isClose(brace)); // false
|
22943 | * console.log(utils.isClose(open)); // false
|
22944 | * console.log(utils.isClose(close)); // true
|
22945 | * ```
|
22946 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22947 | * @return {Boolean}
|
22948 | * @api public
|
22949 | */
|
22950 |
|
22951 | utils.isClose = function(node) {
|
22952 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22953 | return node.type.slice(-6) === '.close';
|
22954 | };
|
22955 |
|
22956 | /**
|
22957 | * Returns true if `node.nodes` **has** an `.open` node
|
22958 | *
|
22959 | * ```js
|
22960 | * var Node = require('snapdragon-node');
|
22961 | * var brace = new Node({
|
22962 | * type: 'brace',
|
22963 | * nodes: []
|
22964 | * });
|
22965 | *
|
22966 | * var open = new Node({type: 'brace.open'});
|
22967 | * console.log(utils.hasOpen(brace)); // false
|
22968 | *
|
22969 | * brace.pushNode(open);
|
22970 | * console.log(utils.hasOpen(brace)); // true
|
22971 | * ```
|
22972 | * @param {Object} `node` Instance of [snapdragon-node][]
|
22973 | * @return {Boolean}
|
22974 | * @api public
|
22975 | */
|
22976 |
|
22977 | utils.hasOpen = function(node) {
|
22978 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
22979 | var first = node.first || node.nodes ? node.nodes[0] : null;
|
22980 | if (utils.isNode(first)) {
|
22981 | return first.type === node.type + '.open';
|
22982 | }
|
22983 | return false;
|
22984 | };
|
22985 |
|
22986 | /**
|
22987 | * Returns true if `node.nodes` **has** a `.close` node
|
22988 | *
|
22989 | * ```js
|
22990 | * var Node = require('snapdragon-node');
|
22991 | * var brace = new Node({
|
22992 | * type: 'brace',
|
22993 | * nodes: []
|
22994 | * });
|
22995 | *
|
22996 | * var close = new Node({type: 'brace.close'});
|
22997 | * console.log(utils.hasClose(brace)); // false
|
22998 | *
|
22999 | * brace.pushNode(close);
|
23000 | * console.log(utils.hasClose(brace)); // true
|
23001 | * ```
|
23002 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23003 | * @return {Boolean}
|
23004 | * @api public
|
23005 | */
|
23006 |
|
23007 | utils.hasClose = function(node) {
|
23008 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
23009 | var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;
|
23010 | if (utils.isNode(last)) {
|
23011 | return last.type === node.type + '.close';
|
23012 | }
|
23013 | return false;
|
23014 | };
|
23015 |
|
23016 | /**
|
23017 | * Returns true if `node.nodes` has both `.open` and `.close` nodes
|
23018 | *
|
23019 | * ```js
|
23020 | * var Node = require('snapdragon-node');
|
23021 | * var brace = new Node({
|
23022 | * type: 'brace',
|
23023 | * nodes: []
|
23024 | * });
|
23025 | *
|
23026 | * var open = new Node({type: 'brace.open'});
|
23027 | * var close = new Node({type: 'brace.close'});
|
23028 | * console.log(utils.hasOpen(brace)); // false
|
23029 | * console.log(utils.hasClose(brace)); // false
|
23030 | *
|
23031 | * brace.pushNode(open);
|
23032 | * brace.pushNode(close);
|
23033 | * console.log(utils.hasOpen(brace)); // true
|
23034 | * console.log(utils.hasClose(brace)); // true
|
23035 | * ```
|
23036 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23037 | * @return {Boolean}
|
23038 | * @api public
|
23039 | */
|
23040 |
|
23041 | utils.hasOpenAndClose = function(node) {
|
23042 | return utils.hasOpen(node) && utils.hasClose(node);
|
23043 | };
|
23044 |
|
23045 | /**
|
23046 | * Push the given `node` onto the `state.inside` array for the
|
23047 | * given type. This array is used as a specialized "stack" for
|
23048 | * only the given `node.type`.
|
23049 | *
|
23050 | * ```js
|
23051 | * var state = { inside: {}};
|
23052 | * var node = new Node({type: 'brace'});
|
23053 | * utils.addType(state, node);
|
23054 | * console.log(state.inside);
|
23055 | * //=> { brace: [{type: 'brace'}] }
|
23056 | * ```
|
23057 | * @param {Object} `state` The `compiler.state` object or custom state object.
|
23058 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23059 | * @return {Array} Returns the `state.inside` stack for the given type.
|
23060 | * @api public
|
23061 | */
|
23062 |
|
23063 | utils.addType = function(state, node) {
|
23064 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
23065 | assert(isObject(state), 'expected state to be an object');
|
23066 |
|
23067 | var type = node.parent
|
23068 | ? node.parent.type
|
23069 | : node.type.replace(/\.open$/, '');
|
23070 |
|
23071 | if (!state.hasOwnProperty('inside')) {
|
23072 | state.inside = {};
|
23073 | }
|
23074 | if (!state.inside.hasOwnProperty(type)) {
|
23075 | state.inside[type] = [];
|
23076 | }
|
23077 |
|
23078 | var arr = state.inside[type];
|
23079 | arr.push(node);
|
23080 | return arr;
|
23081 | };
|
23082 |
|
23083 | /**
|
23084 | * Remove the given `node` from the `state.inside` array for the
|
23085 | * given type. This array is used as a specialized "stack" for
|
23086 | * only the given `node.type`.
|
23087 | *
|
23088 | * ```js
|
23089 | * var state = { inside: {}};
|
23090 | * var node = new Node({type: 'brace'});
|
23091 | * utils.addType(state, node);
|
23092 | * console.log(state.inside);
|
23093 | * //=> { brace: [{type: 'brace'}] }
|
23094 | * utils.removeType(state, node);
|
23095 | * //=> { brace: [] }
|
23096 | * ```
|
23097 | * @param {Object} `state` The `compiler.state` object or custom state object.
|
23098 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23099 | * @return {Array} Returns the `state.inside` stack for the given type.
|
23100 | * @api public
|
23101 | */
|
23102 |
|
23103 | utils.removeType = function(state, node) {
|
23104 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
23105 | assert(isObject(state), 'expected state to be an object');
|
23106 |
|
23107 | var type = node.parent
|
23108 | ? node.parent.type
|
23109 | : node.type.replace(/\.close$/, '');
|
23110 |
|
23111 | if (state.inside.hasOwnProperty(type)) {
|
23112 | return state.inside[type].pop();
|
23113 | }
|
23114 | };
|
23115 |
|
23116 | /**
|
23117 | * Returns true if `node.val` is an empty string, or `node.nodes` does
|
23118 | * not contain any non-empty text nodes.
|
23119 | *
|
23120 | * ```js
|
23121 | * var node = new Node({type: 'text'});
|
23122 | * utils.isEmpty(node); //=> true
|
23123 | * node.val = 'foo';
|
23124 | * utils.isEmpty(node); //=> false
|
23125 | * ```
|
23126 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23127 | * @param {Function} `fn`
|
23128 | * @return {Boolean}
|
23129 | * @api public
|
23130 | */
|
23131 |
|
23132 | utils.isEmpty = function(node, fn) {
|
23133 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
23134 |
|
23135 | if (!Array.isArray(node.nodes)) {
|
23136 | if (node.type !== 'text') {
|
23137 | return true;
|
23138 | }
|
23139 | if (typeof fn === 'function') {
|
23140 | return fn(node, node.parent);
|
23141 | }
|
23142 | return !utils.trim(node.val);
|
23143 | }
|
23144 |
|
23145 | for (var i = 0; i < node.nodes.length; i++) {
|
23146 | var child = node.nodes[i];
|
23147 | if (utils.isOpen(child) || utils.isClose(child)) {
|
23148 | continue;
|
23149 | }
|
23150 | if (!utils.isEmpty(child, fn)) {
|
23151 | return false;
|
23152 | }
|
23153 | }
|
23154 |
|
23155 | return true;
|
23156 | };
|
23157 |
|
23158 | /**
|
23159 | * Returns true if the `state.inside` stack for the given type exists
|
23160 | * and has one or more nodes on it.
|
23161 | *
|
23162 | * ```js
|
23163 | * var state = { inside: {}};
|
23164 | * var node = new Node({type: 'brace'});
|
23165 | * console.log(utils.isInsideType(state, 'brace')); //=> false
|
23166 | * utils.addType(state, node);
|
23167 | * console.log(utils.isInsideType(state, 'brace')); //=> true
|
23168 | * utils.removeType(state, node);
|
23169 | * console.log(utils.isInsideType(state, 'brace')); //=> false
|
23170 | * ```
|
23171 | * @param {Object} `state`
|
23172 | * @param {String} `type`
|
23173 | * @return {Boolean}
|
23174 | * @api public
|
23175 | */
|
23176 |
|
23177 | utils.isInsideType = function(state, type) {
|
23178 | assert(isObject(state), 'expected state to be an object');
|
23179 | assert(isString(type), 'expected type to be a string');
|
23180 |
|
23181 | if (!state.hasOwnProperty('inside')) {
|
23182 | return false;
|
23183 | }
|
23184 |
|
23185 | if (!state.inside.hasOwnProperty(type)) {
|
23186 | return false;
|
23187 | }
|
23188 |
|
23189 | return state.inside[type].length > 0;
|
23190 | };
|
23191 |
|
23192 | /**
|
23193 | * Returns true if `node` is either a child or grand-child of the given `type`,
|
23194 | * or `state.inside[type]` is a non-empty array.
|
23195 | *
|
23196 | * ```js
|
23197 | * var state = { inside: {}};
|
23198 | * var node = new Node({type: 'brace'});
|
23199 | * var open = new Node({type: 'brace.open'});
|
23200 | * console.log(utils.isInside(state, open, 'brace')); //=> false
|
23201 | * utils.pushNode(node, open);
|
23202 | * console.log(utils.isInside(state, open, 'brace')); //=> true
|
23203 | * ```
|
23204 | * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.
|
23205 | * @param {Object} `node` Instance of [snapdragon-node][]
|
23206 | * @param {String} `type` The `node.type` to check for.
|
23207 | * @return {Boolean}
|
23208 | * @api public
|
23209 | */
|
23210 |
|
23211 | utils.isInside = function(state, node, type) {
|
23212 | assert(utils.isNode(node), 'expected node to be an instance of Node');
|
23213 | assert(isObject(state), 'expected state to be an object');
|
23214 |
|
23215 | if (Array.isArray(type)) {
|
23216 | for (var i = 0; i < type.length; i++) {
|
23217 | if (utils.isInside(state, node, type[i])) {
|
23218 | return true;
|
23219 | }
|
23220 | }
|
23221 | return false;
|
23222 | }
|
23223 |
|
23224 | var parent = node.parent;
|
23225 | if (typeof type === 'string') {
|
23226 | return (parent && parent.type === type) || utils.isInsideType(state, type);
|
23227 | }
|
23228 |
|
23229 | if (kindOf$2(type) === 'regexp') {
|
23230 | if (parent && parent.type && type.test(parent.type)) {
|
23231 | return true;
|
23232 | }
|
23233 |
|
23234 | var keys = Object.keys(state.inside);
|
23235 | var len = keys.length;
|
23236 | var idx = -1;
|
23237 | while (++idx < len) {
|
23238 | var key = keys[idx];
|
23239 | var val = state.inside[key];
|
23240 |
|
23241 | if (Array.isArray(val) && val.length !== 0 && type.test(key)) {
|
23242 | return true;
|
23243 | }
|
23244 | }
|
23245 | }
|
23246 | return false;
|
23247 | };
|
23248 |
|
23249 | /**
|
23250 | * Get the last `n` element from the given `array`. Used for getting
|
23251 | * a node from `node.nodes.`
|
23252 | *
|
23253 | * @param {Array} `array`
|
23254 | * @param {Number} `n`
|
23255 | * @return {undefined}
|
23256 | * @api public
|
23257 | */
|
23258 |
|
23259 | utils.last = function(arr, n) {
|
23260 | return arr[arr.length - (n || 1)];
|
23261 | };
|
23262 |
|
23263 | /**
|
23264 | * Cast the given `val` to an array.
|
23265 | *
|
23266 | * ```js
|
23267 | * console.log(utils.arrayify(''));
|
23268 | * //=> []
|
23269 | * console.log(utils.arrayify('foo'));
|
23270 | * //=> ['foo']
|
23271 | * console.log(utils.arrayify(['foo']));
|
23272 | * //=> ['foo']
|
23273 | * ```
|
23274 | * @param {any} `val`
|
23275 | * @return {Array}
|
23276 | * @api public
|
23277 | */
|
23278 |
|
23279 | utils.arrayify = function(val) {
|
23280 | if (typeof val === 'string' && val !== '') {
|
23281 | return [val];
|
23282 | }
|
23283 | if (!Array.isArray(val)) {
|
23284 | return [];
|
23285 | }
|
23286 | return val;
|
23287 | };
|
23288 |
|
23289 | /**
|
23290 | * Convert the given `val` to a string by joining with `,`. Useful
|
23291 | * for creating a cheerio/CSS/DOM-style selector from a list of strings.
|
23292 | *
|
23293 | * @param {any} `val`
|
23294 | * @return {Array}
|
23295 | * @api public
|
23296 | */
|
23297 |
|
23298 | utils.stringify = function(val) {
|
23299 | return utils.arrayify(val).join(',');
|
23300 | };
|
23301 |
|
23302 | /**
|
23303 | * Ensure that the given value is a string and call `.trim()` on it,
|
23304 | * or return an empty string.
|
23305 | *
|
23306 | * @param {String} `str`
|
23307 | * @return {String}
|
23308 | * @api public
|
23309 | */
|
23310 |
|
23311 | utils.trim = function(str) {
|
23312 | return typeof str === 'string' ? str.trim() : '';
|
23313 | };
|
23314 |
|
23315 | /**
|
23316 | * Return true if val is an object
|
23317 | */
|
23318 |
|
23319 | function isObject(val) {
|
23320 | return kindOf$2(val) === 'object';
|
23321 | }
|
23322 |
|
23323 | /**
|
23324 | * Return true if val is a string
|
23325 | */
|
23326 |
|
23327 | function isString(val) {
|
23328 | return typeof val === 'string';
|
23329 | }
|
23330 |
|
23331 | /**
|
23332 | * Return true if val is a function
|
23333 | */
|
23334 |
|
23335 | function isFunction(val) {
|
23336 | return typeof val === 'function';
|
23337 | }
|
23338 |
|
23339 | /**
|
23340 | * Return true if val is an array
|
23341 | */
|
23342 |
|
23343 | function isArray(val) {
|
23344 | return Array.isArray(val);
|
23345 | }
|
23346 |
|
23347 | /**
|
23348 | * Shim to ensure the `.append` methods work with any version of snapdragon
|
23349 | */
|
23350 |
|
23351 | function append(compiler, val, node) {
|
23352 | if (typeof compiler.append !== 'function') {
|
23353 | return compiler.emit(val, node);
|
23354 | }
|
23355 | return compiler.append(val, node);
|
23356 | }
|
23357 |
|
23358 | /**
|
23359 | * Simplified assertion. Throws an error is `val` is falsey.
|
23360 | */
|
23361 |
|
23362 | function assert(val, message) {
|
23363 | if (!val) throw new Error(message);
|
23364 | }
|
23365 | });
|
23366 |
|
23367 | var snapdragonNode = createCommonjsModule(function (module, exports) {
|
23368 |
|
23369 |
|
23370 |
|
23371 |
|
23372 | var ownNames;
|
23373 |
|
23374 | /**
|
23375 | * Create a new AST `Node` with the given `val` and `type`.
|
23376 | *
|
23377 | * ```js
|
23378 | * var node = new Node('*', 'Star');
|
23379 | * var node = new Node({type: 'star', val: '*'});
|
23380 | * ```
|
23381 | * @name Node
|
23382 | * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node.
|
23383 | * @param {String} `type` The node type to use when `val` is a string.
|
23384 | * @return {Object} node instance
|
23385 | * @api public
|
23386 | */
|
23387 |
|
23388 | function Node(val, type, parent) {
|
23389 | if (typeof type !== 'string') {
|
23390 | parent = type;
|
23391 | type = null;
|
23392 | }
|
23393 |
|
23394 | defineProperty$1(this, 'parent', parent);
|
23395 | defineProperty$1(this, 'isNode', true);
|
23396 | defineProperty$1(this, 'expect', null);
|
23397 |
|
23398 | if (typeof type !== 'string' && isobject(val)) {
|
23399 | lazyKeys();
|
23400 | var keys = Object.keys(val);
|
23401 | for (var i = 0; i < keys.length; i++) {
|
23402 | var key = keys[i];
|
23403 | if (ownNames.indexOf(key) === -1) {
|
23404 | this[key] = val[key];
|
23405 | }
|
23406 | }
|
23407 | } else {
|
23408 | this.type = type;
|
23409 | this.val = val;
|
23410 | }
|
23411 | }
|
23412 |
|
23413 | /**
|
23414 | * Returns true if the given value is a node.
|
23415 | *
|
23416 | * ```js
|
23417 | * var Node = require('snapdragon-node');
|
23418 | * var node = new Node({type: 'foo'});
|
23419 | * console.log(Node.isNode(node)); //=> true
|
23420 | * console.log(Node.isNode({})); //=> false
|
23421 | * ```
|
23422 | * @param {Object} `node`
|
23423 | * @returns {Boolean}
|
23424 | * @api public
|
23425 | */
|
23426 |
|
23427 | Node.isNode = function(node) {
|
23428 | return snapdragonUtil.isNode(node);
|
23429 | };
|
23430 |
|
23431 | /**
|
23432 | * Define a non-enumberable property on the node instance.
|
23433 | * Useful for adding properties that shouldn't be extended
|
23434 | * or visible during debugging.
|
23435 | *
|
23436 | * ```js
|
23437 | * var node = new Node();
|
23438 | * node.define('foo', 'something non-enumerable');
|
23439 | * ```
|
23440 | * @param {String} `name`
|
23441 | * @param {any} `val`
|
23442 | * @return {Object} returns the node instance
|
23443 | * @api public
|
23444 | */
|
23445 |
|
23446 | Node.prototype.define = function(name, val) {
|
23447 | defineProperty$1(this, name, val);
|
23448 | return this;
|
23449 | };
|
23450 |
|
23451 | /**
|
23452 | * Returns true if `node.val` is an empty string, or `node.nodes` does
|
23453 | * not contain any non-empty text nodes.
|
23454 | *
|
23455 | * ```js
|
23456 | * var node = new Node({type: 'text'});
|
23457 | * node.isEmpty(); //=> true
|
23458 | * node.val = 'foo';
|
23459 | * node.isEmpty(); //=> false
|
23460 | * ```
|
23461 | * @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.
|
23462 | * @return {Boolean}
|
23463 | * @api public
|
23464 | */
|
23465 |
|
23466 | Node.prototype.isEmpty = function(fn) {
|
23467 | return snapdragonUtil.isEmpty(this, fn);
|
23468 | };
|
23469 |
|
23470 | /**
|
23471 | * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and
|
23472 | * set `foo` as `bar.parent`.
|
23473 | *
|
23474 | * ```js
|
23475 | * var foo = new Node({type: 'foo'});
|
23476 | * var bar = new Node({type: 'bar'});
|
23477 | * foo.push(bar);
|
23478 | * ```
|
23479 | * @param {Object} `node`
|
23480 | * @return {Number} Returns the length of `node.nodes`
|
23481 | * @api public
|
23482 | */
|
23483 |
|
23484 | Node.prototype.push = function(node) {
|
23485 | assert(Node.isNode(node), 'expected node to be an instance of Node');
|
23486 | defineProperty$1(node, 'parent', this);
|
23487 |
|
23488 | this.nodes = this.nodes || [];
|
23489 | return this.nodes.push(node);
|
23490 | };
|
23491 |
|
23492 | /**
|
23493 | * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and
|
23494 | * set `foo` as `bar.parent`.
|
23495 | *
|
23496 | * ```js
|
23497 | * var foo = new Node({type: 'foo'});
|
23498 | * var bar = new Node({type: 'bar'});
|
23499 | * foo.unshift(bar);
|
23500 | * ```
|
23501 | * @param {Object} `node`
|
23502 | * @return {Number} Returns the length of `node.nodes`
|
23503 | * @api public
|
23504 | */
|
23505 |
|
23506 | Node.prototype.unshift = function(node) {
|
23507 | assert(Node.isNode(node), 'expected node to be an instance of Node');
|
23508 | defineProperty$1(node, 'parent', this);
|
23509 |
|
23510 | this.nodes = this.nodes || [];
|
23511 | return this.nodes.unshift(node);
|
23512 | };
|
23513 |
|
23514 | /**
|
23515 | * Pop a node from `node.nodes`.
|
23516 | *
|
23517 | * ```js
|
23518 | * var node = new Node({type: 'foo'});
|
23519 | * node.push(new Node({type: 'a'}));
|
23520 | * node.push(new Node({type: 'b'}));
|
23521 | * node.push(new Node({type: 'c'}));
|
23522 | * node.push(new Node({type: 'd'}));
|
23523 | * console.log(node.nodes.length);
|
23524 | * //=> 4
|
23525 | * node.pop();
|
23526 | * console.log(node.nodes.length);
|
23527 | * //=> 3
|
23528 | * ```
|
23529 | * @return {Number} Returns the popped `node`
|
23530 | * @api public
|
23531 | */
|
23532 |
|
23533 | Node.prototype.pop = function() {
|
23534 | return this.nodes && this.nodes.pop();
|
23535 | };
|
23536 |
|
23537 | /**
|
23538 | * Shift a node from `node.nodes`.
|
23539 | *
|
23540 | * ```js
|
23541 | * var node = new Node({type: 'foo'});
|
23542 | * node.push(new Node({type: 'a'}));
|
23543 | * node.push(new Node({type: 'b'}));
|
23544 | * node.push(new Node({type: 'c'}));
|
23545 | * node.push(new Node({type: 'd'}));
|
23546 | * console.log(node.nodes.length);
|
23547 | * //=> 4
|
23548 | * node.shift();
|
23549 | * console.log(node.nodes.length);
|
23550 | * //=> 3
|
23551 | * ```
|
23552 | * @return {Object} Returns the shifted `node`
|
23553 | * @api public
|
23554 | */
|
23555 |
|
23556 | Node.prototype.shift = function() {
|
23557 | return this.nodes && this.nodes.shift();
|
23558 | };
|
23559 |
|
23560 | /**
|
23561 | * Remove `node` from `node.nodes`.
|
23562 | *
|
23563 | * ```js
|
23564 | * node.remove(childNode);
|
23565 | * ```
|
23566 | * @param {Object} `node`
|
23567 | * @return {Object} Returns the removed node.
|
23568 | * @api public
|
23569 | */
|
23570 |
|
23571 | Node.prototype.remove = function(node) {
|
23572 | assert(Node.isNode(node), 'expected node to be an instance of Node');
|
23573 | this.nodes = this.nodes || [];
|
23574 | var idx = node.index;
|
23575 | if (idx !== -1) {
|
23576 | node.index = -1;
|
23577 | return this.nodes.splice(idx, 1);
|
23578 | }
|
23579 | return null;
|
23580 | };
|
23581 |
|
23582 | /**
|
23583 | * Get the first child node from `node.nodes` that matches the given `type`.
|
23584 | * If `type` is a number, the child node at that index is returned.
|
23585 | *
|
23586 | * ```js
|
23587 | * var child = node.find(1); //<= index of the node to get
|
23588 | * var child = node.find('foo'); //<= node.type of a child node
|
23589 | * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type
|
23590 | * var child = node.find(['foo', 'bar']); //<= array of node.type(s)
|
23591 | * ```
|
23592 | * @param {String} `type`
|
23593 | * @return {Object} Returns a child node or undefined.
|
23594 | * @api public
|
23595 | */
|
23596 |
|
23597 | Node.prototype.find = function(type) {
|
23598 | return snapdragonUtil.findNode(this.nodes, type);
|
23599 | };
|
23600 |
|
23601 | /**
|
23602 | * Return true if the node is the given `type`.
|
23603 | *
|
23604 | * ```js
|
23605 | * var node = new Node({type: 'bar'});
|
23606 | * cosole.log(node.isType('foo')); // false
|
23607 | * cosole.log(node.isType(/^(foo|bar)$/)); // true
|
23608 | * cosole.log(node.isType(['foo', 'bar'])); // true
|
23609 | * ```
|
23610 | * @param {String} `type`
|
23611 | * @return {Boolean}
|
23612 | * @api public
|
23613 | */
|
23614 |
|
23615 | Node.prototype.isType = function(type) {
|
23616 | return snapdragonUtil.isType(this, type);
|
23617 | };
|
23618 |
|
23619 | /**
|
23620 | * Return true if the `node.nodes` has the given `type`.
|
23621 | *
|
23622 | * ```js
|
23623 | * var foo = new Node({type: 'foo'});
|
23624 | * var bar = new Node({type: 'bar'});
|
23625 | * foo.push(bar);
|
23626 | *
|
23627 | * cosole.log(foo.hasType('qux')); // false
|
23628 | * cosole.log(foo.hasType(/^(qux|bar)$/)); // true
|
23629 | * cosole.log(foo.hasType(['qux', 'bar'])); // true
|
23630 | * ```
|
23631 | * @param {String} `type`
|
23632 | * @return {Boolean}
|
23633 | * @api public
|
23634 | */
|
23635 |
|
23636 | Node.prototype.hasType = function(type) {
|
23637 | return snapdragonUtil.hasType(this, type);
|
23638 | };
|
23639 |
|
23640 | /**
|
23641 | * Get the siblings array, or `null` if it doesn't exist.
|
23642 | *
|
23643 | * ```js
|
23644 | * var foo = new Node({type: 'foo'});
|
23645 | * var bar = new Node({type: 'bar'});
|
23646 | * var baz = new Node({type: 'baz'});
|
23647 | * foo.push(bar);
|
23648 | * foo.push(baz);
|
23649 | *
|
23650 | * console.log(bar.siblings.length) // 2
|
23651 | * console.log(baz.siblings.length) // 2
|
23652 | * ```
|
23653 | * @return {Array}
|
23654 | * @api public
|
23655 | */
|
23656 |
|
23657 | Object.defineProperty(Node.prototype, 'siblings', {
|
23658 | set: function() {
|
23659 | throw new Error('node.siblings is a getter and cannot be defined');
|
23660 | },
|
23661 | get: function() {
|
23662 | return this.parent ? this.parent.nodes : null;
|
23663 | }
|
23664 | });
|
23665 |
|
23666 | /**
|
23667 | * Get the node's current index from `node.parent.nodes`.
|
23668 | * This should always be correct, even when the parent adds nodes.
|
23669 | *
|
23670 | * ```js
|
23671 | * var foo = new Node({type: 'foo'});
|
23672 | * var bar = new Node({type: 'bar'});
|
23673 | * var baz = new Node({type: 'baz'});
|
23674 | * var qux = new Node({type: 'qux'});
|
23675 | * foo.push(bar);
|
23676 | * foo.push(baz);
|
23677 | * foo.unshift(qux);
|
23678 | *
|
23679 | * console.log(bar.index) // 1
|
23680 | * console.log(baz.index) // 2
|
23681 | * console.log(qux.index) // 0
|
23682 | * ```
|
23683 | * @return {Number}
|
23684 | * @api public
|
23685 | */
|
23686 |
|
23687 | Object.defineProperty(Node.prototype, 'index', {
|
23688 | set: function(index) {
|
23689 | defineProperty$1(this, 'idx', index);
|
23690 | },
|
23691 | get: function() {
|
23692 | if (!Array.isArray(this.siblings)) {
|
23693 | return -1;
|
23694 | }
|
23695 | var tok = this.idx !== -1 ? this.siblings[this.idx] : null;
|
23696 | if (tok !== this) {
|
23697 | this.idx = this.siblings.indexOf(this);
|
23698 | }
|
23699 | return this.idx;
|
23700 | }
|
23701 | });
|
23702 |
|
23703 | /**
|
23704 | * Get the previous node from the siblings array or `null`.
|
23705 | *
|
23706 | * ```js
|
23707 | * var foo = new Node({type: 'foo'});
|
23708 | * var bar = new Node({type: 'bar'});
|
23709 | * var baz = new Node({type: 'baz'});
|
23710 | * foo.push(bar);
|
23711 | * foo.push(baz);
|
23712 | *
|
23713 | * console.log(baz.prev.type) // 'bar'
|
23714 | * ```
|
23715 | * @return {Object}
|
23716 | * @api public
|
23717 | */
|
23718 |
|
23719 | Object.defineProperty(Node.prototype, 'prev', {
|
23720 | set: function() {
|
23721 | throw new Error('node.prev is a getter and cannot be defined');
|
23722 | },
|
23723 | get: function() {
|
23724 | if (Array.isArray(this.siblings)) {
|
23725 | return this.siblings[this.index - 1] || this.parent.prev;
|
23726 | }
|
23727 | return null;
|
23728 | }
|
23729 | });
|
23730 |
|
23731 | /**
|
23732 | * Get the siblings array, or `null` if it doesn't exist.
|
23733 | *
|
23734 | * ```js
|
23735 | * var foo = new Node({type: 'foo'});
|
23736 | * var bar = new Node({type: 'bar'});
|
23737 | * var baz = new Node({type: 'baz'});
|
23738 | * foo.push(bar);
|
23739 | * foo.push(baz);
|
23740 | *
|
23741 | * console.log(bar.siblings.length) // 2
|
23742 | * console.log(baz.siblings.length) // 2
|
23743 | * ```
|
23744 | * @return {Object}
|
23745 | * @api public
|
23746 | */
|
23747 |
|
23748 | Object.defineProperty(Node.prototype, 'next', {
|
23749 | set: function() {
|
23750 | throw new Error('node.next is a getter and cannot be defined');
|
23751 | },
|
23752 | get: function() {
|
23753 | if (Array.isArray(this.siblings)) {
|
23754 | return this.siblings[this.index + 1] || this.parent.next;
|
23755 | }
|
23756 | return null;
|
23757 | }
|
23758 | });
|
23759 |
|
23760 | /**
|
23761 | * Get the first node from `node.nodes`.
|
23762 | *
|
23763 | * ```js
|
23764 | * var foo = new Node({type: 'foo'});
|
23765 | * var bar = new Node({type: 'bar'});
|
23766 | * var baz = new Node({type: 'baz'});
|
23767 | * var qux = new Node({type: 'qux'});
|
23768 | * foo.push(bar);
|
23769 | * foo.push(baz);
|
23770 | * foo.push(qux);
|
23771 | *
|
23772 | * console.log(foo.first.type) // 'bar'
|
23773 | * ```
|
23774 | * @return {Object} The first node, or undefiend
|
23775 | * @api public
|
23776 | */
|
23777 |
|
23778 | Object.defineProperty(Node.prototype, 'first', {
|
23779 | get: function() {
|
23780 | return this.nodes ? this.nodes[0] : null;
|
23781 | }
|
23782 | });
|
23783 |
|
23784 | /**
|
23785 | * Get the last node from `node.nodes`.
|
23786 | *
|
23787 | * ```js
|
23788 | * var foo = new Node({type: 'foo'});
|
23789 | * var bar = new Node({type: 'bar'});
|
23790 | * var baz = new Node({type: 'baz'});
|
23791 | * var qux = new Node({type: 'qux'});
|
23792 | * foo.push(bar);
|
23793 | * foo.push(baz);
|
23794 | * foo.push(qux);
|
23795 | *
|
23796 | * console.log(foo.last.type) // 'qux'
|
23797 | * ```
|
23798 | * @return {Object} The last node, or undefiend
|
23799 | * @api public
|
23800 | */
|
23801 |
|
23802 | Object.defineProperty(Node.prototype, 'last', {
|
23803 | get: function() {
|
23804 | return this.nodes ? snapdragonUtil.last(this.nodes) : null;
|
23805 | }
|
23806 | });
|
23807 |
|
23808 | /**
|
23809 | * Get the last node from `node.nodes`.
|
23810 | *
|
23811 | * ```js
|
23812 | * var foo = new Node({type: 'foo'});
|
23813 | * var bar = new Node({type: 'bar'});
|
23814 | * var baz = new Node({type: 'baz'});
|
23815 | * var qux = new Node({type: 'qux'});
|
23816 | * foo.push(bar);
|
23817 | * foo.push(baz);
|
23818 | * foo.push(qux);
|
23819 | *
|
23820 | * console.log(foo.last.type) // 'qux'
|
23821 | * ```
|
23822 | * @return {Object} The last node, or undefiend
|
23823 | * @api public
|
23824 | */
|
23825 |
|
23826 | Object.defineProperty(Node.prototype, 'scope', {
|
23827 | get: function() {
|
23828 | if (this.isScope !== true) {
|
23829 | return this.parent ? this.parent.scope : this;
|
23830 | }
|
23831 | return this;
|
23832 | }
|
23833 | });
|
23834 |
|
23835 | /**
|
23836 | * Get own property names from Node prototype, but only the
|
23837 | * first time `Node` is instantiated
|
23838 | */
|
23839 |
|
23840 | function lazyKeys() {
|
23841 | if (!ownNames) {
|
23842 | ownNames = Object.getOwnPropertyNames(Node.prototype);
|
23843 | }
|
23844 | }
|
23845 |
|
23846 | /**
|
23847 | * Simplified assertion. Throws an error is `val` is falsey.
|
23848 | */
|
23849 |
|
23850 | function assert(val, message) {
|
23851 | if (!val) throw new Error(message);
|
23852 | }
|
23853 |
|
23854 | /**
|
23855 | * Expose `Node`
|
23856 | */
|
23857 |
|
23858 | exports = module.exports = Node;
|
23859 | });
|
23860 |
|
23861 | /**
|
23862 | * Braces parsers
|
23863 | */
|
23864 |
|
23865 | var parsers = function(braces, options) {
|
23866 | braces.parser
|
23867 | .set('bos', function() {
|
23868 | if (!this.parsed) {
|
23869 | this.ast = this.nodes[0] = new snapdragonNode(this.ast);
|
23870 | }
|
23871 | })
|
23872 |
|
23873 | /**
|
23874 | * Character parsers
|
23875 | */
|
23876 |
|
23877 | .set('escape', function() {
|
23878 | var pos = this.position();
|
23879 | var m = this.match(/^(?:\\(.)|\$\{)/);
|
23880 | if (!m) return;
|
23881 |
|
23882 | var prev = this.prev();
|
23883 | var last = utils_1.last(prev.nodes);
|
23884 |
|
23885 | var node = pos(new snapdragonNode({
|
23886 | type: 'text',
|
23887 | multiplier: 1,
|
23888 | val: m[0]
|
23889 | }));
|
23890 |
|
23891 | if (node.val === '\\\\') {
|
23892 | return node;
|
23893 | }
|
23894 |
|
23895 | if (node.val === '${') {
|
23896 | var str = this.input;
|
23897 | var idx = -1;
|
23898 | var ch;
|
23899 |
|
23900 | while ((ch = str[++idx])) {
|
23901 | this.consume(1);
|
23902 | node.val += ch;
|
23903 | if (ch === '\\') {
|
23904 | node.val += str[++idx];
|
23905 | continue;
|
23906 | }
|
23907 | if (ch === '}') {
|
23908 | break;
|
23909 | }
|
23910 | }
|
23911 | }
|
23912 |
|
23913 | if (this.options.unescape !== false) {
|
23914 | node.val = node.val.replace(/\\([{}])/g, '$1');
|
23915 | }
|
23916 |
|
23917 | if (last.val === '"' && this.input.charAt(0) === '"') {
|
23918 | last.val = node.val;
|
23919 | this.consume(1);
|
23920 | return;
|
23921 | }
|
23922 |
|
23923 | return concatNodes.call(this, pos, node, prev, options);
|
23924 | })
|
23925 |
|
23926 | /**
|
23927 | * Brackets: "[...]" (basic, this is overridden by
|
23928 | * other parsers in more advanced implementations)
|
23929 | */
|
23930 |
|
23931 | .set('bracket', function() {
|
23932 | var isInside = this.isInside('brace');
|
23933 | var pos = this.position();
|
23934 | var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
|
23935 | if (!m) return;
|
23936 |
|
23937 | var prev = this.prev();
|
23938 | var val = m[0];
|
23939 | var negated = m[1] ? '^' : '';
|
23940 | var inner = m[2] || '';
|
23941 | var close = m[3] || '';
|
23942 |
|
23943 | if (isInside && prev.type === 'brace') {
|
23944 | prev.text = prev.text || '';
|
23945 | prev.text += val;
|
23946 | }
|
23947 |
|
23948 | var esc = this.input.slice(0, 2);
|
23949 | if (inner === '' && esc === '\\]') {
|
23950 | inner += esc;
|
23951 | this.consume(2);
|
23952 |
|
23953 | var str = this.input;
|
23954 | var idx = -1;
|
23955 | var ch;
|
23956 |
|
23957 | while ((ch = str[++idx])) {
|
23958 | this.consume(1);
|
23959 | if (ch === ']') {
|
23960 | close = ch;
|
23961 | break;
|
23962 | }
|
23963 | inner += ch;
|
23964 | }
|
23965 | }
|
23966 |
|
23967 | return pos(new snapdragonNode({
|
23968 | type: 'bracket',
|
23969 | val: val,
|
23970 | escaped: close !== ']',
|
23971 | negated: negated,
|
23972 | inner: inner,
|
23973 | close: close
|
23974 | }));
|
23975 | })
|
23976 |
|
23977 | /**
|
23978 | * Empty braces (we capture these early to
|
23979 | * speed up processing in the compiler)
|
23980 | */
|
23981 |
|
23982 | .set('multiplier', function() {
|
23983 | var isInside = this.isInside('brace');
|
23984 | var pos = this.position();
|
23985 | var m = this.match(/^\{((?:,|\{,+\})+)\}/);
|
23986 | if (!m) return;
|
23987 |
|
23988 | this.multiplier = true;
|
23989 | var prev = this.prev();
|
23990 | var val = m[0];
|
23991 |
|
23992 | if (isInside && prev.type === 'brace') {
|
23993 | prev.text = prev.text || '';
|
23994 | prev.text += val;
|
23995 | }
|
23996 |
|
23997 | var node = pos(new snapdragonNode({
|
23998 | type: 'text',
|
23999 | multiplier: 1,
|
24000 | match: m,
|
24001 | val: val
|
24002 | }));
|
24003 |
|
24004 | return concatNodes.call(this, pos, node, prev, options);
|
24005 | })
|
24006 |
|
24007 | /**
|
24008 | * Open
|
24009 | */
|
24010 |
|
24011 | .set('brace.open', function() {
|
24012 | var pos = this.position();
|
24013 | var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
|
24014 | if (!m) return;
|
24015 |
|
24016 | var prev = this.prev();
|
24017 | var last = utils_1.last(prev.nodes);
|
24018 |
|
24019 | // if the last parsed character was an extglob character
|
24020 | // we need to _not optimize_ the brace pattern because
|
24021 | // it might be mistaken for an extglob by a downstream parser
|
24022 | if (last && last.val && isExtglobChar(last.val.slice(-1))) {
|
24023 | last.optimize = false;
|
24024 | }
|
24025 |
|
24026 | var open = pos(new snapdragonNode({
|
24027 | type: 'brace.open',
|
24028 | val: m[0]
|
24029 | }));
|
24030 |
|
24031 | var node = pos(new snapdragonNode({
|
24032 | type: 'brace',
|
24033 | nodes: []
|
24034 | }));
|
24035 |
|
24036 | node.push(open);
|
24037 | prev.push(node);
|
24038 | this.push('brace', node);
|
24039 | })
|
24040 |
|
24041 | /**
|
24042 | * Close
|
24043 | */
|
24044 |
|
24045 | .set('brace.close', function() {
|
24046 | var pos = this.position();
|
24047 | var m = this.match(/^\}/);
|
24048 | if (!m || !m[0]) return;
|
24049 |
|
24050 | var brace = this.pop('brace');
|
24051 | var node = pos(new snapdragonNode({
|
24052 | type: 'brace.close',
|
24053 | val: m[0]
|
24054 | }));
|
24055 |
|
24056 | if (!this.isType(brace, 'brace')) {
|
24057 | if (this.options.strict) {
|
24058 | throw new Error('missing opening "{"');
|
24059 | }
|
24060 | node.type = 'text';
|
24061 | node.multiplier = 0;
|
24062 | node.escaped = true;
|
24063 | return node;
|
24064 | }
|
24065 |
|
24066 | var prev = this.prev();
|
24067 | var last = utils_1.last(prev.nodes);
|
24068 | if (last.text) {
|
24069 | var lastNode = utils_1.last(last.nodes);
|
24070 | if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
|
24071 | var open = last.nodes[0];
|
24072 | var text = last.nodes[1];
|
24073 | if (open.type === 'brace.open' && text && text.type === 'text') {
|
24074 | text.optimize = false;
|
24075 | }
|
24076 | }
|
24077 | }
|
24078 |
|
24079 | if (brace.nodes.length > 2) {
|
24080 | var first = brace.nodes[1];
|
24081 | if (first.type === 'text' && first.val === ',') {
|
24082 | brace.nodes.splice(1, 1);
|
24083 | brace.nodes.push(first);
|
24084 | }
|
24085 | }
|
24086 |
|
24087 | brace.push(node);
|
24088 | })
|
24089 |
|
24090 | /**
|
24091 | * Capture boundary characters
|
24092 | */
|
24093 |
|
24094 | .set('boundary', function() {
|
24095 | var pos = this.position();
|
24096 | var m = this.match(/^[$^](?!\{)/);
|
24097 | if (!m) return;
|
24098 | return pos(new snapdragonNode({
|
24099 | type: 'text',
|
24100 | val: m[0]
|
24101 | }));
|
24102 | })
|
24103 |
|
24104 | /**
|
24105 | * One or zero, non-comma characters wrapped in braces
|
24106 | */
|
24107 |
|
24108 | .set('nobrace', function() {
|
24109 | var isInside = this.isInside('brace');
|
24110 | var pos = this.position();
|
24111 | var m = this.match(/^\{[^,]?\}/);
|
24112 | if (!m) return;
|
24113 |
|
24114 | var prev = this.prev();
|
24115 | var val = m[0];
|
24116 |
|
24117 | if (isInside && prev.type === 'brace') {
|
24118 | prev.text = prev.text || '';
|
24119 | prev.text += val;
|
24120 | }
|
24121 |
|
24122 | return pos(new snapdragonNode({
|
24123 | type: 'text',
|
24124 | multiplier: 0,
|
24125 | val: val
|
24126 | }));
|
24127 | })
|
24128 |
|
24129 | /**
|
24130 | * Text
|
24131 | */
|
24132 |
|
24133 | .set('text', function() {
|
24134 | var isInside = this.isInside('brace');
|
24135 | var pos = this.position();
|
24136 | var m = this.match(/^((?!\\)[^${}[\]])+/);
|
24137 | if (!m) return;
|
24138 |
|
24139 | var prev = this.prev();
|
24140 | var val = m[0];
|
24141 |
|
24142 | if (isInside && prev.type === 'brace') {
|
24143 | prev.text = prev.text || '';
|
24144 | prev.text += val;
|
24145 | }
|
24146 |
|
24147 | var node = pos(new snapdragonNode({
|
24148 | type: 'text',
|
24149 | multiplier: 1,
|
24150 | val: val
|
24151 | }));
|
24152 |
|
24153 | return concatNodes.call(this, pos, node, prev, options);
|
24154 | });
|
24155 | };
|
24156 |
|
24157 | /**
|
24158 | * Returns true if the character is an extglob character.
|
24159 | */
|
24160 |
|
24161 | function isExtglobChar(ch) {
|
24162 | return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
|
24163 | }
|
24164 |
|
24165 | /**
|
24166 | * Combine text nodes, and calculate empty sets (`{,,}`)
|
24167 | * @param {Function} `pos` Function to calculate node position
|
24168 | * @param {Object} `node` AST node
|
24169 | * @return {Object}
|
24170 | */
|
24171 |
|
24172 | function concatNodes(pos, node, parent, options) {
|
24173 | node.orig = node.val;
|
24174 | var prev = this.prev();
|
24175 | var last = utils_1.last(prev.nodes);
|
24176 | var isEscaped = false;
|
24177 |
|
24178 | if (node.val.length > 1) {
|
24179 | var a = node.val.charAt(0);
|
24180 | var b = node.val.slice(-1);
|
24181 |
|
24182 | isEscaped = (a === '"' && b === '"')
|
24183 | || (a === "'" && b === "'")
|
24184 | || (a === '`' && b === '`');
|
24185 | }
|
24186 |
|
24187 | if (isEscaped && options.unescape !== false) {
|
24188 | node.val = node.val.slice(1, node.val.length - 1);
|
24189 | node.escaped = true;
|
24190 | }
|
24191 |
|
24192 | if (node.match) {
|
24193 | var match = node.match[1];
|
24194 | if (!match || match.indexOf('}') === -1) {
|
24195 | match = node.match[0];
|
24196 | }
|
24197 |
|
24198 | // replace each set with a single ","
|
24199 | var val = match.replace(/\{/g, ',').replace(/\}/g, '');
|
24200 | node.multiplier *= val.length;
|
24201 | node.val = '';
|
24202 | }
|
24203 |
|
24204 | var simpleText = last.type === 'text'
|
24205 | && last.multiplier === 1
|
24206 | && node.multiplier === 1
|
24207 | && node.val;
|
24208 |
|
24209 | if (simpleText) {
|
24210 | last.val += node.val;
|
24211 | return;
|
24212 | }
|
24213 |
|
24214 | prev.push(node);
|
24215 | }
|
24216 |
|
24217 | // accessor descriptor properties
|
24218 | var accessor$2 = {
|
24219 | get: 'function',
|
24220 | set: 'function',
|
24221 | configurable: 'boolean',
|
24222 | enumerable: 'boolean'
|
24223 | };
|
24224 |
|
24225 | function isAccessorDescriptor$2(obj, prop) {
|
24226 | if (typeof prop === 'string') {
|
24227 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
24228 | return typeof val !== 'undefined';
|
24229 | }
|
24230 |
|
24231 | if (kindOf(obj) !== 'object') {
|
24232 | return false;
|
24233 | }
|
24234 |
|
24235 | if (has$3(obj, 'value') || has$3(obj, 'writable')) {
|
24236 | return false;
|
24237 | }
|
24238 |
|
24239 | if (!has$3(obj, 'get') || typeof obj.get !== 'function') {
|
24240 | return false;
|
24241 | }
|
24242 |
|
24243 | // tldr: it's valid to have "set" be undefined
|
24244 | // "set" might be undefined if `Object.getOwnPropertyDescriptor`
|
24245 | // was used to get the value, and only `get` was defined by the user
|
24246 | if (has$3(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
|
24247 | return false;
|
24248 | }
|
24249 |
|
24250 | for (var key in obj) {
|
24251 | if (!accessor$2.hasOwnProperty(key)) {
|
24252 | continue;
|
24253 | }
|
24254 |
|
24255 | if (kindOf(obj[key]) === accessor$2[key]) {
|
24256 | continue;
|
24257 | }
|
24258 |
|
24259 | if (typeof obj[key] !== 'undefined') {
|
24260 | return false;
|
24261 | }
|
24262 | }
|
24263 | return true;
|
24264 | }
|
24265 |
|
24266 | function has$3(obj, key) {
|
24267 | return {}.hasOwnProperty.call(obj, key);
|
24268 | }
|
24269 |
|
24270 | /**
|
24271 | * Expose `isAccessorDescriptor`
|
24272 | */
|
24273 |
|
24274 | var isAccessorDescriptor_1$2 = isAccessorDescriptor$2;
|
24275 |
|
24276 | var isDataDescriptor$2 = function isDataDescriptor(obj, prop) {
|
24277 | // data descriptor properties
|
24278 | var data = {
|
24279 | configurable: 'boolean',
|
24280 | enumerable: 'boolean',
|
24281 | writable: 'boolean'
|
24282 | };
|
24283 |
|
24284 | if (kindOf(obj) !== 'object') {
|
24285 | return false;
|
24286 | }
|
24287 |
|
24288 | if (typeof prop === 'string') {
|
24289 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
24290 | return typeof val !== 'undefined';
|
24291 | }
|
24292 |
|
24293 | if (!('value' in obj) && !('writable' in obj)) {
|
24294 | return false;
|
24295 | }
|
24296 |
|
24297 | for (var key in obj) {
|
24298 | if (key === 'value') continue;
|
24299 |
|
24300 | if (!data.hasOwnProperty(key)) {
|
24301 | continue;
|
24302 | }
|
24303 |
|
24304 | if (kindOf(obj[key]) === data[key]) {
|
24305 | continue;
|
24306 | }
|
24307 |
|
24308 | if (typeof obj[key] !== 'undefined') {
|
24309 | return false;
|
24310 | }
|
24311 | }
|
24312 | return true;
|
24313 | };
|
24314 |
|
24315 | var isDescriptor$2 = function isDescriptor(obj, key) {
|
24316 | if (kindOf(obj) !== 'object') {
|
24317 | return false;
|
24318 | }
|
24319 | if ('get' in obj) {
|
24320 | return isAccessorDescriptor_1$2(obj, key);
|
24321 | }
|
24322 | return isDataDescriptor$2(obj, key);
|
24323 | };
|
24324 |
|
24325 | var defineProperty$2 = function defineProperty(obj, prop, val) {
|
24326 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
24327 | throw new TypeError('expected an object or function.');
|
24328 | }
|
24329 |
|
24330 | if (typeof prop !== 'string') {
|
24331 | throw new TypeError('expected `prop` to be a string.');
|
24332 | }
|
24333 |
|
24334 | if (isDescriptor$2(val) && ('set' in val || 'get' in val)) {
|
24335 | return Object.defineProperty(obj, prop, val);
|
24336 | }
|
24337 |
|
24338 | return Object.defineProperty(obj, prop, {
|
24339 | configurable: true,
|
24340 | enumerable: false,
|
24341 | writable: true,
|
24342 | value: val
|
24343 | });
|
24344 | };
|
24345 |
|
24346 | var componentEmitter = createCommonjsModule(function (module) {
|
24347 | /**
|
24348 | * Expose `Emitter`.
|
24349 | */
|
24350 |
|
24351 | {
|
24352 | module.exports = Emitter;
|
24353 | }
|
24354 |
|
24355 | /**
|
24356 | * Initialize a new `Emitter`.
|
24357 | *
|
24358 | * @api public
|
24359 | */
|
24360 |
|
24361 | function Emitter(obj) {
|
24362 | if (obj) return mixin(obj);
|
24363 | }
|
24364 | /**
|
24365 | * Mixin the emitter properties.
|
24366 | *
|
24367 | * @param {Object} obj
|
24368 | * @return {Object}
|
24369 | * @api private
|
24370 | */
|
24371 |
|
24372 | function mixin(obj) {
|
24373 | for (var key in Emitter.prototype) {
|
24374 | obj[key] = Emitter.prototype[key];
|
24375 | }
|
24376 | return obj;
|
24377 | }
|
24378 |
|
24379 | /**
|
24380 | * Listen on the given `event` with `fn`.
|
24381 | *
|
24382 | * @param {String} event
|
24383 | * @param {Function} fn
|
24384 | * @return {Emitter}
|
24385 | * @api public
|
24386 | */
|
24387 |
|
24388 | Emitter.prototype.on =
|
24389 | Emitter.prototype.addEventListener = function(event, fn){
|
24390 | this._callbacks = this._callbacks || {};
|
24391 | (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
|
24392 | .push(fn);
|
24393 | return this;
|
24394 | };
|
24395 |
|
24396 | /**
|
24397 | * Adds an `event` listener that will be invoked a single
|
24398 | * time then automatically removed.
|
24399 | *
|
24400 | * @param {String} event
|
24401 | * @param {Function} fn
|
24402 | * @return {Emitter}
|
24403 | * @api public
|
24404 | */
|
24405 |
|
24406 | Emitter.prototype.once = function(event, fn){
|
24407 | function on() {
|
24408 | this.off(event, on);
|
24409 | fn.apply(this, arguments);
|
24410 | }
|
24411 |
|
24412 | on.fn = fn;
|
24413 | this.on(event, on);
|
24414 | return this;
|
24415 | };
|
24416 |
|
24417 | /**
|
24418 | * Remove the given callback for `event` or all
|
24419 | * registered callbacks.
|
24420 | *
|
24421 | * @param {String} event
|
24422 | * @param {Function} fn
|
24423 | * @return {Emitter}
|
24424 | * @api public
|
24425 | */
|
24426 |
|
24427 | Emitter.prototype.off =
|
24428 | Emitter.prototype.removeListener =
|
24429 | Emitter.prototype.removeAllListeners =
|
24430 | Emitter.prototype.removeEventListener = function(event, fn){
|
24431 | this._callbacks = this._callbacks || {};
|
24432 |
|
24433 | // all
|
24434 | if (0 == arguments.length) {
|
24435 | this._callbacks = {};
|
24436 | return this;
|
24437 | }
|
24438 |
|
24439 | // specific event
|
24440 | var callbacks = this._callbacks['$' + event];
|
24441 | if (!callbacks) return this;
|
24442 |
|
24443 | // remove all handlers
|
24444 | if (1 == arguments.length) {
|
24445 | delete this._callbacks['$' + event];
|
24446 | return this;
|
24447 | }
|
24448 |
|
24449 | // remove specific handler
|
24450 | var cb;
|
24451 | for (var i = 0; i < callbacks.length; i++) {
|
24452 | cb = callbacks[i];
|
24453 | if (cb === fn || cb.fn === fn) {
|
24454 | callbacks.splice(i, 1);
|
24455 | break;
|
24456 | }
|
24457 | }
|
24458 | return this;
|
24459 | };
|
24460 |
|
24461 | /**
|
24462 | * Emit `event` with the given args.
|
24463 | *
|
24464 | * @param {String} event
|
24465 | * @param {Mixed} ...
|
24466 | * @return {Emitter}
|
24467 | */
|
24468 |
|
24469 | Emitter.prototype.emit = function(event){
|
24470 | this._callbacks = this._callbacks || {};
|
24471 | var args = [].slice.call(arguments, 1)
|
24472 | , callbacks = this._callbacks['$' + event];
|
24473 |
|
24474 | if (callbacks) {
|
24475 | callbacks = callbacks.slice(0);
|
24476 | for (var i = 0, len = callbacks.length; i < len; ++i) {
|
24477 | callbacks[i].apply(this, args);
|
24478 | }
|
24479 | }
|
24480 |
|
24481 | return this;
|
24482 | };
|
24483 |
|
24484 | /**
|
24485 | * Return array of callbacks for `event`.
|
24486 | *
|
24487 | * @param {String} event
|
24488 | * @return {Array}
|
24489 | * @api public
|
24490 | */
|
24491 |
|
24492 | Emitter.prototype.listeners = function(event){
|
24493 | this._callbacks = this._callbacks || {};
|
24494 | return this._callbacks['$' + event] || [];
|
24495 | };
|
24496 |
|
24497 | /**
|
24498 | * Check if this emitter has `event` handlers.
|
24499 | *
|
24500 | * @param {String} event
|
24501 | * @return {Boolean}
|
24502 | * @api public
|
24503 | */
|
24504 |
|
24505 | Emitter.prototype.hasListeners = function(event){
|
24506 | return !! this.listeners(event).length;
|
24507 | };
|
24508 | });
|
24509 |
|
24510 | var objectVisit = function visit(thisArg, method, target, val) {
|
24511 | if (!isobject(thisArg) && typeof thisArg !== 'function') {
|
24512 | throw new Error('object-visit expects `thisArg` to be an object.');
|
24513 | }
|
24514 |
|
24515 | if (typeof method !== 'string') {
|
24516 | throw new Error('object-visit expects `method` name to be a string');
|
24517 | }
|
24518 |
|
24519 | if (typeof thisArg[method] !== 'function') {
|
24520 | return thisArg;
|
24521 | }
|
24522 |
|
24523 | var args = [].slice.call(arguments, 3);
|
24524 | target = target || {};
|
24525 |
|
24526 | for (var key in target) {
|
24527 | var arr = [key, target[key]].concat(args);
|
24528 | thisArg[method].apply(thisArg, arr);
|
24529 | }
|
24530 | return thisArg;
|
24531 | };
|
24532 |
|
24533 | /**
|
24534 | * Map `visit` over an array of objects.
|
24535 | *
|
24536 | * @param {Object} `collection` The context in which to invoke `method`
|
24537 | * @param {String} `method` Name of the method to call on `collection`
|
24538 | * @param {Object} `arr` Array of objects.
|
24539 | */
|
24540 |
|
24541 | var mapVisit = function mapVisit(collection, method, val) {
|
24542 | if (isObject$2(val)) {
|
24543 | return objectVisit.apply(null, arguments);
|
24544 | }
|
24545 |
|
24546 | if (!Array.isArray(val)) {
|
24547 | throw new TypeError('expected an array: ' + util$2.inspect(val));
|
24548 | }
|
24549 |
|
24550 | var args = [].slice.call(arguments, 3);
|
24551 |
|
24552 | for (var i = 0; i < val.length; i++) {
|
24553 | var ele = val[i];
|
24554 | if (isObject$2(ele)) {
|
24555 | objectVisit.apply(null, [collection, method, ele].concat(args));
|
24556 | } else {
|
24557 | collection[method].apply(collection, [ele].concat(args));
|
24558 | }
|
24559 | }
|
24560 | };
|
24561 |
|
24562 | function isObject$2(val) {
|
24563 | return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object'));
|
24564 | }
|
24565 |
|
24566 | var collectionVisit = function(collection, method, val) {
|
24567 | var result;
|
24568 |
|
24569 | if (typeof val === 'string' && (method in collection)) {
|
24570 | var args = [].slice.call(arguments, 2);
|
24571 | result = collection[method].apply(collection, args);
|
24572 | } else if (Array.isArray(val)) {
|
24573 | result = mapVisit.apply(null, arguments);
|
24574 | } else {
|
24575 | result = objectVisit.apply(null, arguments);
|
24576 | }
|
24577 |
|
24578 | if (typeof result !== 'undefined') {
|
24579 | return result;
|
24580 | }
|
24581 |
|
24582 | return collection;
|
24583 | };
|
24584 |
|
24585 | var toString$4 = Object.prototype.toString;
|
24586 |
|
24587 | /**
|
24588 | * Get the native `typeof` a value.
|
24589 | *
|
24590 | * @param {*} `val`
|
24591 | * @return {*} Native javascript type
|
24592 | */
|
24593 |
|
24594 | var kindOf$3 = function kindOf(val) {
|
24595 | // primitivies
|
24596 | if (typeof val === 'undefined') {
|
24597 | return 'undefined';
|
24598 | }
|
24599 | if (val === null) {
|
24600 | return 'null';
|
24601 | }
|
24602 | if (val === true || val === false || val instanceof Boolean) {
|
24603 | return 'boolean';
|
24604 | }
|
24605 | if (typeof val === 'string' || val instanceof String) {
|
24606 | return 'string';
|
24607 | }
|
24608 | if (typeof val === 'number' || val instanceof Number) {
|
24609 | return 'number';
|
24610 | }
|
24611 |
|
24612 | // functions
|
24613 | if (typeof val === 'function' || val instanceof Function) {
|
24614 | return 'function';
|
24615 | }
|
24616 |
|
24617 | // array
|
24618 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
24619 | return 'array';
|
24620 | }
|
24621 |
|
24622 | // check for instances of RegExp and Date before calling `toString`
|
24623 | if (val instanceof RegExp) {
|
24624 | return 'regexp';
|
24625 | }
|
24626 | if (val instanceof Date) {
|
24627 | return 'date';
|
24628 | }
|
24629 |
|
24630 | // other objects
|
24631 | var type = toString$4.call(val);
|
24632 |
|
24633 | if (type === '[object RegExp]') {
|
24634 | return 'regexp';
|
24635 | }
|
24636 | if (type === '[object Date]') {
|
24637 | return 'date';
|
24638 | }
|
24639 | if (type === '[object Arguments]') {
|
24640 | return 'arguments';
|
24641 | }
|
24642 | if (type === '[object Error]') {
|
24643 | return 'error';
|
24644 | }
|
24645 |
|
24646 | // buffer
|
24647 | if (isBuffer_1(val)) {
|
24648 | return 'buffer';
|
24649 | }
|
24650 |
|
24651 | // es6: Map, WeakMap, Set, WeakSet
|
24652 | if (type === '[object Set]') {
|
24653 | return 'set';
|
24654 | }
|
24655 | if (type === '[object WeakSet]') {
|
24656 | return 'weakset';
|
24657 | }
|
24658 | if (type === '[object Map]') {
|
24659 | return 'map';
|
24660 | }
|
24661 | if (type === '[object WeakMap]') {
|
24662 | return 'weakmap';
|
24663 | }
|
24664 | if (type === '[object Symbol]') {
|
24665 | return 'symbol';
|
24666 | }
|
24667 |
|
24668 | // typed arrays
|
24669 | if (type === '[object Int8Array]') {
|
24670 | return 'int8array';
|
24671 | }
|
24672 | if (type === '[object Uint8Array]') {
|
24673 | return 'uint8array';
|
24674 | }
|
24675 | if (type === '[object Uint8ClampedArray]') {
|
24676 | return 'uint8clampedarray';
|
24677 | }
|
24678 | if (type === '[object Int16Array]') {
|
24679 | return 'int16array';
|
24680 | }
|
24681 | if (type === '[object Uint16Array]') {
|
24682 | return 'uint16array';
|
24683 | }
|
24684 | if (type === '[object Int32Array]') {
|
24685 | return 'int32array';
|
24686 | }
|
24687 | if (type === '[object Uint32Array]') {
|
24688 | return 'uint32array';
|
24689 | }
|
24690 | if (type === '[object Float32Array]') {
|
24691 | return 'float32array';
|
24692 | }
|
24693 | if (type === '[object Float64Array]') {
|
24694 | return 'float64array';
|
24695 | }
|
24696 |
|
24697 | // must be a plain object
|
24698 | return 'object';
|
24699 | };
|
24700 |
|
24701 | var toObjectPath = function toPath(args) {
|
24702 | if (kindOf$3(args) !== 'arguments') {
|
24703 | args = arguments;
|
24704 | }
|
24705 | return filter(args).join('.');
|
24706 | };
|
24707 |
|
24708 | function filter(arr) {
|
24709 | var len = arr.length;
|
24710 | var idx = -1;
|
24711 | var res = [];
|
24712 |
|
24713 | while (++idx < len) {
|
24714 | var ele = arr[idx];
|
24715 | if (kindOf$3(ele) === 'arguments' || Array.isArray(ele)) {
|
24716 | res.push.apply(res, filter(ele));
|
24717 | } else if (typeof ele === 'string') {
|
24718 | res.push(ele);
|
24719 | }
|
24720 | }
|
24721 | return res;
|
24722 | }
|
24723 |
|
24724 | var arrUnion = function union(init) {
|
24725 | if (!Array.isArray(init)) {
|
24726 | throw new TypeError('arr-union expects the first argument to be an array.');
|
24727 | }
|
24728 |
|
24729 | var len = arguments.length;
|
24730 | var i = 0;
|
24731 |
|
24732 | while (++i < len) {
|
24733 | var arg = arguments[i];
|
24734 | if (!arg) continue;
|
24735 |
|
24736 | if (!Array.isArray(arg)) {
|
24737 | arg = [arg];
|
24738 | }
|
24739 |
|
24740 | for (var j = 0; j < arg.length; j++) {
|
24741 | var ele = arg[j];
|
24742 |
|
24743 | if (init.indexOf(ele) >= 0) {
|
24744 | continue;
|
24745 | }
|
24746 | init.push(ele);
|
24747 | }
|
24748 | }
|
24749 | return init;
|
24750 | };
|
24751 |
|
24752 | /*!
|
24753 | * get-value <https://github.com/jonschlinkert/get-value>
|
24754 | *
|
24755 | * Copyright (c) 2014-2015, Jon Schlinkert.
|
24756 | * Licensed under the MIT License.
|
24757 | */
|
24758 |
|
24759 | var getValue = function(obj, prop, a, b, c) {
|
24760 | if (!isObject$3(obj) || !prop) {
|
24761 | return obj;
|
24762 | }
|
24763 |
|
24764 | prop = toString$5(prop);
|
24765 |
|
24766 | // allowing for multiple properties to be passed as
|
24767 | // a string or array, but much faster (3-4x) than doing
|
24768 | // `[].slice.call(arguments)`
|
24769 | if (a) prop += '.' + toString$5(a);
|
24770 | if (b) prop += '.' + toString$5(b);
|
24771 | if (c) prop += '.' + toString$5(c);
|
24772 |
|
24773 | if (prop in obj) {
|
24774 | return obj[prop];
|
24775 | }
|
24776 |
|
24777 | var segs = prop.split('.');
|
24778 | var len = segs.length;
|
24779 | var i = -1;
|
24780 |
|
24781 | while (obj && (++i < len)) {
|
24782 | var key = segs[i];
|
24783 | while (key[key.length - 1] === '\\') {
|
24784 | key = key.slice(0, -1) + '.' + segs[++i];
|
24785 | }
|
24786 | obj = obj[key];
|
24787 | }
|
24788 | return obj;
|
24789 | };
|
24790 |
|
24791 | function isObject$3(val) {
|
24792 | return val !== null && (typeof val === 'object' || typeof val === 'function');
|
24793 | }
|
24794 |
|
24795 | function toString$5(val) {
|
24796 | if (!val) return '';
|
24797 | if (Array.isArray(val)) {
|
24798 | return val.join('.');
|
24799 | }
|
24800 | return val;
|
24801 | }
|
24802 |
|
24803 | var extendShallow$3 = function extend(o/*, objects*/) {
|
24804 | if (!isExtendable$1(o)) { o = {}; }
|
24805 |
|
24806 | var len = arguments.length;
|
24807 | for (var i = 1; i < len; i++) {
|
24808 | var obj = arguments[i];
|
24809 |
|
24810 | if (isExtendable$1(obj)) {
|
24811 | assign$3(o, obj);
|
24812 | }
|
24813 | }
|
24814 | return o;
|
24815 | };
|
24816 |
|
24817 | function assign$3(a, b) {
|
24818 | for (var key in b) {
|
24819 | if (hasOwn$3(b, key)) {
|
24820 | a[key] = b[key];
|
24821 | }
|
24822 | }
|
24823 | }
|
24824 |
|
24825 | /**
|
24826 | * Returns true if the given `key` is an own property of `obj`.
|
24827 | */
|
24828 |
|
24829 | function hasOwn$3(obj, key) {
|
24830 | return Object.prototype.hasOwnProperty.call(obj, key);
|
24831 | }
|
24832 |
|
24833 | var setValue = function(obj, path, val) {
|
24834 | if (!isExtendable$1(obj)) {
|
24835 | return obj;
|
24836 | }
|
24837 |
|
24838 | if (Array.isArray(path)) {
|
24839 | path = toObjectPath(path);
|
24840 | }
|
24841 |
|
24842 | if (typeof path !== 'string') {
|
24843 | return obj;
|
24844 | }
|
24845 |
|
24846 | var segs = path.split('.');
|
24847 | var len = segs.length, i = -1;
|
24848 | var res = obj;
|
24849 | var last;
|
24850 |
|
24851 | while (++i < len) {
|
24852 | var key = segs[i];
|
24853 |
|
24854 | while (key[key.length - 1] === '\\') {
|
24855 | key = key.slice(0, -1) + '.' + segs[++i];
|
24856 | }
|
24857 |
|
24858 | if (i === len - 1) {
|
24859 | last = key;
|
24860 | break;
|
24861 | }
|
24862 |
|
24863 | if (!isExtendable$1(obj[key])) {
|
24864 | obj[key] = {};
|
24865 | }
|
24866 | obj = obj[key];
|
24867 | }
|
24868 |
|
24869 | if (obj.hasOwnProperty(last) && isExtendable$1(obj[last])) {
|
24870 | if (isPlainObject(val)) {
|
24871 | extendShallow$3(obj[last], val);
|
24872 | } else {
|
24873 | obj[last] = val;
|
24874 | }
|
24875 |
|
24876 | } else {
|
24877 | obj[last] = val;
|
24878 | }
|
24879 | return res;
|
24880 | };
|
24881 |
|
24882 | var unionValue = function unionValue(obj, prop, value) {
|
24883 | if (!isExtendable$1(obj)) {
|
24884 | throw new TypeError('union-value expects the first argument to be an object.');
|
24885 | }
|
24886 |
|
24887 | if (typeof prop !== 'string') {
|
24888 | throw new TypeError('union-value expects `prop` to be a string.');
|
24889 | }
|
24890 |
|
24891 | var arr = arrayify(getValue(obj, prop));
|
24892 | setValue(obj, prop, arrUnion(arr, arrayify(value)));
|
24893 | return obj;
|
24894 | };
|
24895 |
|
24896 | function arrayify(val) {
|
24897 | if (val === null || typeof val === 'undefined') {
|
24898 | return [];
|
24899 | }
|
24900 | if (Array.isArray(val)) {
|
24901 | return val;
|
24902 | }
|
24903 | return [val];
|
24904 | }
|
24905 |
|
24906 | var toString$6 = {}.toString;
|
24907 |
|
24908 | var isarray = Array.isArray || function (arr) {
|
24909 | return toString$6.call(arr) == '[object Array]';
|
24910 | };
|
24911 |
|
24912 | var isobject$1 = function isObject(val) {
|
24913 | return val != null && typeof val === 'object' && isarray(val) === false;
|
24914 | };
|
24915 |
|
24916 | /*!
|
24917 | * has-values <https://github.com/jonschlinkert/has-values>
|
24918 | *
|
24919 | * Copyright (c) 2014-2015, Jon Schlinkert.
|
24920 | * Licensed under the MIT License.
|
24921 | */
|
24922 |
|
24923 | var hasValues = function hasValue(o, noZero) {
|
24924 | if (o === null || o === undefined) {
|
24925 | return false;
|
24926 | }
|
24927 |
|
24928 | if (typeof o === 'boolean') {
|
24929 | return true;
|
24930 | }
|
24931 |
|
24932 | if (typeof o === 'number') {
|
24933 | if (o === 0 && noZero === true) {
|
24934 | return false;
|
24935 | }
|
24936 | return true;
|
24937 | }
|
24938 |
|
24939 | if (o.length !== undefined) {
|
24940 | return o.length !== 0;
|
24941 | }
|
24942 |
|
24943 | for (var key in o) {
|
24944 | if (o.hasOwnProperty(key)) {
|
24945 | return true;
|
24946 | }
|
24947 | }
|
24948 | return false;
|
24949 | };
|
24950 |
|
24951 | var hasValue = function(obj, prop, noZero) {
|
24952 | if (isobject$1(obj)) {
|
24953 | return hasValues(getValue(obj, prop), noZero);
|
24954 | }
|
24955 | return hasValues(obj, prop);
|
24956 | };
|
24957 |
|
24958 | var unsetValue = function unset(obj, prop) {
|
24959 | if (!isobject(obj)) {
|
24960 | throw new TypeError('expected an object.');
|
24961 | }
|
24962 | if (obj.hasOwnProperty(prop)) {
|
24963 | delete obj[prop];
|
24964 | return true;
|
24965 | }
|
24966 |
|
24967 | if (hasValue(obj, prop)) {
|
24968 | var segs = prop.split('.');
|
24969 | var last = segs.pop();
|
24970 | while (segs.length && segs[segs.length - 1].slice(-1) === '\\') {
|
24971 | last = segs.pop().slice(0, -1) + '.' + last;
|
24972 | }
|
24973 | while (segs.length) obj = obj[prop = segs.shift()];
|
24974 | return (delete obj[last]);
|
24975 | }
|
24976 | return true;
|
24977 | };
|
24978 |
|
24979 | var extendShallow$4 = function extend(o/*, objects*/) {
|
24980 | if (!isExtendable$1(o)) { o = {}; }
|
24981 |
|
24982 | var len = arguments.length;
|
24983 | for (var i = 1; i < len; i++) {
|
24984 | var obj = arguments[i];
|
24985 |
|
24986 | if (isExtendable$1(obj)) {
|
24987 | assign$4(o, obj);
|
24988 | }
|
24989 | }
|
24990 | return o;
|
24991 | };
|
24992 |
|
24993 | function assign$4(a, b) {
|
24994 | for (var key in b) {
|
24995 | if (hasOwn$4(b, key)) {
|
24996 | a[key] = b[key];
|
24997 | }
|
24998 | }
|
24999 | }
|
25000 |
|
25001 | /**
|
25002 | * Returns true if the given `key` is an own property of `obj`.
|
25003 | */
|
25004 |
|
25005 | function hasOwn$4(obj, key) {
|
25006 | return Object.prototype.hasOwnProperty.call(obj, key);
|
25007 | }
|
25008 |
|
25009 | var setValue$1 = function(obj, prop, val) {
|
25010 | if (!isExtendable$1(obj)) {
|
25011 | return obj;
|
25012 | }
|
25013 |
|
25014 | if (Array.isArray(prop)) {
|
25015 | prop = [].concat.apply([], prop).join('.');
|
25016 | }
|
25017 |
|
25018 | if (typeof prop !== 'string') {
|
25019 | return obj;
|
25020 | }
|
25021 |
|
25022 | var keys = splitString(prop, {sep: '.', brackets: true});
|
25023 | var len = keys.length;
|
25024 | var idx = -1;
|
25025 | var current = obj;
|
25026 |
|
25027 | while (++idx < len) {
|
25028 | var key = keys[idx];
|
25029 | if (idx !== len - 1) {
|
25030 | if (!isExtendable$1(current[key])) {
|
25031 | current[key] = {};
|
25032 | }
|
25033 | current = current[key];
|
25034 | continue;
|
25035 | }
|
25036 |
|
25037 | if (isPlainObject(current[key]) && isPlainObject(val)) {
|
25038 | current[key] = extendShallow$4({}, current[key], val);
|
25039 | } else {
|
25040 | current[key] = val;
|
25041 | }
|
25042 | }
|
25043 |
|
25044 | return obj;
|
25045 | };
|
25046 |
|
25047 | /**
|
25048 | * Create a `Cache` constructor that when instantiated will
|
25049 | * store values on the given `prop`.
|
25050 | *
|
25051 | * ```js
|
25052 | * var Cache = require('cache-base').namespace('data');
|
25053 | * var cache = new Cache();
|
25054 | *
|
25055 | * cache.set('foo', 'bar');
|
25056 | * //=> {data: {foo: 'bar'}}
|
25057 | * ```
|
25058 | * @param {String} `prop` The property name to use for storing values.
|
25059 | * @return {Function} Returns a custom `Cache` constructor
|
25060 | * @api public
|
25061 | */
|
25062 |
|
25063 | function namespace(prop) {
|
25064 |
|
25065 | /**
|
25066 | * Create a new `Cache`. Internally the `Cache` constructor is created using
|
25067 | * the `namespace` function, with `cache` defined as the storage object.
|
25068 | *
|
25069 | * ```js
|
25070 | * var app = new Cache();
|
25071 | * ```
|
25072 | * @param {Object} `cache` Optionally pass an object to initialize with.
|
25073 | * @constructor
|
25074 | * @api public
|
25075 | */
|
25076 |
|
25077 | function Cache(cache) {
|
25078 | if (prop) {
|
25079 | this[prop] = {};
|
25080 | }
|
25081 | if (cache) {
|
25082 | this.set(cache);
|
25083 | }
|
25084 | }
|
25085 |
|
25086 | /**
|
25087 | * Inherit Emitter
|
25088 | */
|
25089 |
|
25090 | componentEmitter(Cache.prototype);
|
25091 |
|
25092 | /**
|
25093 | * Assign `value` to `key`. Also emits `set` with
|
25094 | * the key and value.
|
25095 | *
|
25096 | * ```js
|
25097 | * app.on('set', function(key, val) {
|
25098 | * // do something when `set` is emitted
|
25099 | * });
|
25100 | *
|
25101 | * app.set(key, value);
|
25102 | *
|
25103 | * // also takes an object or array
|
25104 | * app.set({name: 'Halle'});
|
25105 | * app.set([{foo: 'bar'}, {baz: 'quux'}]);
|
25106 | * console.log(app);
|
25107 | * //=> {name: 'Halle', foo: 'bar', baz: 'quux'}
|
25108 | * ```
|
25109 | *
|
25110 | * @name .set
|
25111 | * @emits `set` with `key` and `value` as arguments.
|
25112 | * @param {String} `key`
|
25113 | * @param {any} `value`
|
25114 | * @return {Object} Returns the instance for chaining.
|
25115 | * @api public
|
25116 | */
|
25117 |
|
25118 | Cache.prototype.set = function(key, val) {
|
25119 | if (Array.isArray(key) && arguments.length === 2) {
|
25120 | key = toObjectPath(key);
|
25121 | }
|
25122 | if (isobject(key) || Array.isArray(key)) {
|
25123 | this.visit('set', key);
|
25124 | } else {
|
25125 | setValue$1(prop ? this[prop] : this, key, val);
|
25126 | this.emit('set', key, val);
|
25127 | }
|
25128 | return this;
|
25129 | };
|
25130 |
|
25131 | /**
|
25132 | * Union `array` to `key`. Also emits `set` with
|
25133 | * the key and value.
|
25134 | *
|
25135 | * ```js
|
25136 | * app.union('a.b', ['foo']);
|
25137 | * app.union('a.b', ['bar']);
|
25138 | * console.log(app.get('a'));
|
25139 | * //=> {b: ['foo', 'bar']}
|
25140 | * ```
|
25141 | * @name .union
|
25142 | * @param {String} `key`
|
25143 | * @param {any} `value`
|
25144 | * @return {Object} Returns the instance for chaining.
|
25145 | * @api public
|
25146 | */
|
25147 |
|
25148 | Cache.prototype.union = function(key, val) {
|
25149 | if (Array.isArray(key) && arguments.length === 2) {
|
25150 | key = toObjectPath(key);
|
25151 | }
|
25152 | var ctx = prop ? this[prop] : this;
|
25153 | unionValue(ctx, key, arrayify$1(val));
|
25154 | this.emit('union', val);
|
25155 | return this;
|
25156 | };
|
25157 |
|
25158 | /**
|
25159 | * Return the value of `key`. Dot notation may be used
|
25160 | * to get [nested property values][get-value].
|
25161 | *
|
25162 | * ```js
|
25163 | * app.set('a.b.c', 'd');
|
25164 | * app.get('a.b');
|
25165 | * //=> {c: 'd'}
|
25166 | *
|
25167 | * app.get(['a', 'b']);
|
25168 | * //=> {c: 'd'}
|
25169 | * ```
|
25170 | *
|
25171 | * @name .get
|
25172 | * @emits `get` with `key` and `value` as arguments.
|
25173 | * @param {String} `key` The name of the property to get. Dot-notation may be used.
|
25174 | * @return {any} Returns the value of `key`
|
25175 | * @api public
|
25176 | */
|
25177 |
|
25178 | Cache.prototype.get = function(key) {
|
25179 | key = toObjectPath(arguments);
|
25180 |
|
25181 | var ctx = prop ? this[prop] : this;
|
25182 | var val = getValue(ctx, key);
|
25183 |
|
25184 | this.emit('get', key, val);
|
25185 | return val;
|
25186 | };
|
25187 |
|
25188 | /**
|
25189 | * Return true if app has a stored value for `key`,
|
25190 | * false only if value is `undefined`.
|
25191 | *
|
25192 | * ```js
|
25193 | * app.set('foo', 'bar');
|
25194 | * app.has('foo');
|
25195 | * //=> true
|
25196 | * ```
|
25197 | *
|
25198 | * @name .has
|
25199 | * @emits `has` with `key` and true or false as arguments.
|
25200 | * @param {String} `key`
|
25201 | * @return {Boolean}
|
25202 | * @api public
|
25203 | */
|
25204 |
|
25205 | Cache.prototype.has = function(key) {
|
25206 | key = toObjectPath(arguments);
|
25207 |
|
25208 | var ctx = prop ? this[prop] : this;
|
25209 | var val = getValue(ctx, key);
|
25210 |
|
25211 | var has = typeof val !== 'undefined';
|
25212 | this.emit('has', key, has);
|
25213 | return has;
|
25214 | };
|
25215 |
|
25216 | /**
|
25217 | * Delete one or more properties from the instance.
|
25218 | *
|
25219 | * ```js
|
25220 | * app.del(); // delete all
|
25221 | * // or
|
25222 | * app.del('foo');
|
25223 | * // or
|
25224 | * app.del(['foo', 'bar']);
|
25225 | * ```
|
25226 | * @name .del
|
25227 | * @emits `del` with the `key` as the only argument.
|
25228 | * @param {String|Array} `key` Property name or array of property names.
|
25229 | * @return {Object} Returns the instance for chaining.
|
25230 | * @api public
|
25231 | */
|
25232 |
|
25233 | Cache.prototype.del = function(key) {
|
25234 | if (Array.isArray(key)) {
|
25235 | this.visit('del', key);
|
25236 | } else {
|
25237 | unsetValue(prop ? this[prop] : this, key);
|
25238 | this.emit('del', key);
|
25239 | }
|
25240 | return this;
|
25241 | };
|
25242 |
|
25243 | /**
|
25244 | * Reset the entire cache to an empty object.
|
25245 | *
|
25246 | * ```js
|
25247 | * app.clear();
|
25248 | * ```
|
25249 | * @api public
|
25250 | */
|
25251 |
|
25252 | Cache.prototype.clear = function() {
|
25253 | if (prop) {
|
25254 | this[prop] = {};
|
25255 | }
|
25256 | };
|
25257 |
|
25258 | /**
|
25259 | * Visit `method` over the properties in the given object, or map
|
25260 | * visit over the object-elements in an array.
|
25261 | *
|
25262 | * @name .visit
|
25263 | * @param {String} `method` The name of the `base` method to call.
|
25264 | * @param {Object|Array} `val` The object or array to iterate over.
|
25265 | * @return {Object} Returns the instance for chaining.
|
25266 | * @api public
|
25267 | */
|
25268 |
|
25269 | Cache.prototype.visit = function(method, val) {
|
25270 | collectionVisit(this, method, val);
|
25271 | return this;
|
25272 | };
|
25273 |
|
25274 | return Cache;
|
25275 | }
|
25276 |
|
25277 | /**
|
25278 | * Cast val to an array
|
25279 | */
|
25280 |
|
25281 | function arrayify$1(val) {
|
25282 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
25283 | }
|
25284 |
|
25285 | /**
|
25286 | * Expose `Cache`
|
25287 | */
|
25288 |
|
25289 | var cacheBase = namespace();
|
25290 |
|
25291 | /**
|
25292 | * Expose `Cache.namespace`
|
25293 | */
|
25294 |
|
25295 | var namespace_1 = namespace;
|
25296 | cacheBase.namespace = namespace_1;
|
25297 |
|
25298 | var isExtendable$2 = function isExtendable(val) {
|
25299 | return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
|
25300 | };
|
25301 |
|
25302 | /*!
|
25303 | * for-in <https://github.com/jonschlinkert/for-in>
|
25304 | *
|
25305 | * Copyright (c) 2014-2017, Jon Schlinkert.
|
25306 | * Released under the MIT License.
|
25307 | */
|
25308 |
|
25309 | var forIn = function forIn(obj, fn, thisArg) {
|
25310 | for (var key in obj) {
|
25311 | if (fn.call(thisArg, obj[key], key, obj) === false) {
|
25312 | break;
|
25313 | }
|
25314 | }
|
25315 | };
|
25316 |
|
25317 | function mixinDeep(target, objects) {
|
25318 | var len = arguments.length, i = 0;
|
25319 | while (++i < len) {
|
25320 | var obj = arguments[i];
|
25321 | if (isObject$4(obj)) {
|
25322 | forIn(obj, copy, target);
|
25323 | }
|
25324 | }
|
25325 | return target;
|
25326 | }
|
25327 |
|
25328 | /**
|
25329 | * Copy properties from the source object to the
|
25330 | * target object.
|
25331 | *
|
25332 | * @param {*} `val`
|
25333 | * @param {String} `key`
|
25334 | */
|
25335 |
|
25336 | function copy(val, key) {
|
25337 | if (key === '__proto__') {
|
25338 | return;
|
25339 | }
|
25340 |
|
25341 | var obj = this[key];
|
25342 | if (isObject$4(val) && isObject$4(obj)) {
|
25343 | mixinDeep(obj, val);
|
25344 | } else {
|
25345 | this[key] = val;
|
25346 | }
|
25347 | }
|
25348 |
|
25349 | /**
|
25350 | * Returns true if `val` is an object or function.
|
25351 | *
|
25352 | * @param {any} val
|
25353 | * @return {Boolean}
|
25354 | */
|
25355 |
|
25356 | function isObject$4(val) {
|
25357 | return isExtendable$2(val) && !Array.isArray(val);
|
25358 | }
|
25359 |
|
25360 | /**
|
25361 | * Expose `mixinDeep`
|
25362 | */
|
25363 |
|
25364 | var mixinDeep_1 = mixinDeep;
|
25365 |
|
25366 | /*!
|
25367 | * pascalcase <https://github.com/jonschlinkert/pascalcase>
|
25368 | *
|
25369 | * Copyright (c) 2015, Jon Schlinkert.
|
25370 | * Licensed under the MIT License.
|
25371 | */
|
25372 |
|
25373 | function pascalcase(str) {
|
25374 | if (typeof str !== 'string') {
|
25375 | throw new TypeError('expected a string.');
|
25376 | }
|
25377 | str = str.replace(/([A-Z])/g, ' $1');
|
25378 | if (str.length === 1) { return str.toUpperCase(); }
|
25379 | str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
|
25380 | str = str.charAt(0).toUpperCase() + str.slice(1);
|
25381 | return str.replace(/[\W_]+(\w|$)/g, function (_, ch) {
|
25382 | return ch.toUpperCase();
|
25383 | });
|
25384 | }
|
25385 |
|
25386 | var pascalcase_1 = pascalcase;
|
25387 |
|
25388 | var toString$7 = Object.prototype.toString;
|
25389 |
|
25390 | /**
|
25391 | * Get the native `typeof` a value.
|
25392 | *
|
25393 | * @param {*} `val`
|
25394 | * @return {*} Native javascript type
|
25395 | */
|
25396 |
|
25397 | var kindOf$4 = function kindOf(val) {
|
25398 | var type = typeof val;
|
25399 |
|
25400 | // primitivies
|
25401 | if (type === 'undefined') {
|
25402 | return 'undefined';
|
25403 | }
|
25404 | if (val === null) {
|
25405 | return 'null';
|
25406 | }
|
25407 | if (val === true || val === false || val instanceof Boolean) {
|
25408 | return 'boolean';
|
25409 | }
|
25410 | if (type === 'string' || val instanceof String) {
|
25411 | return 'string';
|
25412 | }
|
25413 | if (type === 'number' || val instanceof Number) {
|
25414 | return 'number';
|
25415 | }
|
25416 |
|
25417 | // functions
|
25418 | if (type === 'function' || val instanceof Function) {
|
25419 | if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') {
|
25420 | return 'generatorfunction';
|
25421 | }
|
25422 | return 'function';
|
25423 | }
|
25424 |
|
25425 | // array
|
25426 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
25427 | return 'array';
|
25428 | }
|
25429 |
|
25430 | // check for instances of RegExp and Date before calling `toString`
|
25431 | if (val instanceof RegExp) {
|
25432 | return 'regexp';
|
25433 | }
|
25434 | if (val instanceof Date) {
|
25435 | return 'date';
|
25436 | }
|
25437 |
|
25438 | // other objects
|
25439 | type = toString$7.call(val);
|
25440 |
|
25441 | if (type === '[object RegExp]') {
|
25442 | return 'regexp';
|
25443 | }
|
25444 | if (type === '[object Date]') {
|
25445 | return 'date';
|
25446 | }
|
25447 | if (type === '[object Arguments]') {
|
25448 | return 'arguments';
|
25449 | }
|
25450 | if (type === '[object Error]') {
|
25451 | return 'error';
|
25452 | }
|
25453 | if (type === '[object Promise]') {
|
25454 | return 'promise';
|
25455 | }
|
25456 |
|
25457 | // buffer
|
25458 | if (isBuffer$2(val)) {
|
25459 | return 'buffer';
|
25460 | }
|
25461 |
|
25462 | // es6: Map, WeakMap, Set, WeakSet
|
25463 | if (type === '[object Set]') {
|
25464 | return 'set';
|
25465 | }
|
25466 | if (type === '[object WeakSet]') {
|
25467 | return 'weakset';
|
25468 | }
|
25469 | if (type === '[object Map]') {
|
25470 | return 'map';
|
25471 | }
|
25472 | if (type === '[object WeakMap]') {
|
25473 | return 'weakmap';
|
25474 | }
|
25475 | if (type === '[object Symbol]') {
|
25476 | return 'symbol';
|
25477 | }
|
25478 |
|
25479 | if (type === '[object Map Iterator]') {
|
25480 | return 'mapiterator';
|
25481 | }
|
25482 | if (type === '[object Set Iterator]') {
|
25483 | return 'setiterator';
|
25484 | }
|
25485 | if (type === '[object String Iterator]') {
|
25486 | return 'stringiterator';
|
25487 | }
|
25488 | if (type === '[object Array Iterator]') {
|
25489 | return 'arrayiterator';
|
25490 | }
|
25491 |
|
25492 | // typed arrays
|
25493 | if (type === '[object Int8Array]') {
|
25494 | return 'int8array';
|
25495 | }
|
25496 | if (type === '[object Uint8Array]') {
|
25497 | return 'uint8array';
|
25498 | }
|
25499 | if (type === '[object Uint8ClampedArray]') {
|
25500 | return 'uint8clampedarray';
|
25501 | }
|
25502 | if (type === '[object Int16Array]') {
|
25503 | return 'int16array';
|
25504 | }
|
25505 | if (type === '[object Uint16Array]') {
|
25506 | return 'uint16array';
|
25507 | }
|
25508 | if (type === '[object Int32Array]') {
|
25509 | return 'int32array';
|
25510 | }
|
25511 | if (type === '[object Uint32Array]') {
|
25512 | return 'uint32array';
|
25513 | }
|
25514 | if (type === '[object Float32Array]') {
|
25515 | return 'float32array';
|
25516 | }
|
25517 | if (type === '[object Float64Array]') {
|
25518 | return 'float64array';
|
25519 | }
|
25520 |
|
25521 | // must be a plain object
|
25522 | return 'object';
|
25523 | };
|
25524 |
|
25525 | /**
|
25526 | * If you need to support Safari 5-7 (8-10 yr-old browser),
|
25527 | * take a look at https://github.com/feross/is-buffer
|
25528 | */
|
25529 |
|
25530 | function isBuffer$2(val) {
|
25531 | return val.constructor
|
25532 | && typeof val.constructor.isBuffer === 'function'
|
25533 | && val.constructor.isBuffer(val);
|
25534 | }
|
25535 |
|
25536 | var toString$8 = Object.prototype.toString;
|
25537 |
|
25538 | /**
|
25539 | * Get the native `typeof` a value.
|
25540 | *
|
25541 | * @param {*} `val`
|
25542 | * @return {*} Native javascript type
|
25543 | */
|
25544 |
|
25545 | var kindOf$5 = function kindOf(val) {
|
25546 | // primitivies
|
25547 | if (typeof val === 'undefined') {
|
25548 | return 'undefined';
|
25549 | }
|
25550 | if (val === null) {
|
25551 | return 'null';
|
25552 | }
|
25553 | if (val === true || val === false || val instanceof Boolean) {
|
25554 | return 'boolean';
|
25555 | }
|
25556 | if (typeof val === 'string' || val instanceof String) {
|
25557 | return 'string';
|
25558 | }
|
25559 | if (typeof val === 'number' || val instanceof Number) {
|
25560 | return 'number';
|
25561 | }
|
25562 |
|
25563 | // functions
|
25564 | if (typeof val === 'function' || val instanceof Function) {
|
25565 | return 'function';
|
25566 | }
|
25567 |
|
25568 | // array
|
25569 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
25570 | return 'array';
|
25571 | }
|
25572 |
|
25573 | // check for instances of RegExp and Date before calling `toString`
|
25574 | if (val instanceof RegExp) {
|
25575 | return 'regexp';
|
25576 | }
|
25577 | if (val instanceof Date) {
|
25578 | return 'date';
|
25579 | }
|
25580 |
|
25581 | // other objects
|
25582 | var type = toString$8.call(val);
|
25583 |
|
25584 | if (type === '[object RegExp]') {
|
25585 | return 'regexp';
|
25586 | }
|
25587 | if (type === '[object Date]') {
|
25588 | return 'date';
|
25589 | }
|
25590 | if (type === '[object Arguments]') {
|
25591 | return 'arguments';
|
25592 | }
|
25593 | if (type === '[object Error]') {
|
25594 | return 'error';
|
25595 | }
|
25596 |
|
25597 | // buffer
|
25598 | if (isBuffer_1(val)) {
|
25599 | return 'buffer';
|
25600 | }
|
25601 |
|
25602 | // es6: Map, WeakMap, Set, WeakSet
|
25603 | if (type === '[object Set]') {
|
25604 | return 'set';
|
25605 | }
|
25606 | if (type === '[object WeakSet]') {
|
25607 | return 'weakset';
|
25608 | }
|
25609 | if (type === '[object Map]') {
|
25610 | return 'map';
|
25611 | }
|
25612 | if (type === '[object WeakMap]') {
|
25613 | return 'weakmap';
|
25614 | }
|
25615 | if (type === '[object Symbol]') {
|
25616 | return 'symbol';
|
25617 | }
|
25618 |
|
25619 | // typed arrays
|
25620 | if (type === '[object Int8Array]') {
|
25621 | return 'int8array';
|
25622 | }
|
25623 | if (type === '[object Uint8Array]') {
|
25624 | return 'uint8array';
|
25625 | }
|
25626 | if (type === '[object Uint8ClampedArray]') {
|
25627 | return 'uint8clampedarray';
|
25628 | }
|
25629 | if (type === '[object Int16Array]') {
|
25630 | return 'int16array';
|
25631 | }
|
25632 | if (type === '[object Uint16Array]') {
|
25633 | return 'uint16array';
|
25634 | }
|
25635 | if (type === '[object Int32Array]') {
|
25636 | return 'int32array';
|
25637 | }
|
25638 | if (type === '[object Uint32Array]') {
|
25639 | return 'uint32array';
|
25640 | }
|
25641 | if (type === '[object Float32Array]') {
|
25642 | return 'float32array';
|
25643 | }
|
25644 | if (type === '[object Float64Array]') {
|
25645 | return 'float64array';
|
25646 | }
|
25647 |
|
25648 | // must be a plain object
|
25649 | return 'object';
|
25650 | };
|
25651 |
|
25652 | // accessor descriptor properties
|
25653 | var accessor$3 = {
|
25654 | get: 'function',
|
25655 | set: 'function',
|
25656 | configurable: 'boolean',
|
25657 | enumerable: 'boolean'
|
25658 | };
|
25659 |
|
25660 | function isAccessorDescriptor$3(obj, prop) {
|
25661 | if (typeof prop === 'string') {
|
25662 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
25663 | return typeof val !== 'undefined';
|
25664 | }
|
25665 |
|
25666 | if (kindOf$5(obj) !== 'object') {
|
25667 | return false;
|
25668 | }
|
25669 |
|
25670 | if (has$4(obj, 'value') || has$4(obj, 'writable')) {
|
25671 | return false;
|
25672 | }
|
25673 |
|
25674 | if (!has$4(obj, 'get') || typeof obj.get !== 'function') {
|
25675 | return false;
|
25676 | }
|
25677 |
|
25678 | // tldr: it's valid to have "set" be undefined
|
25679 | // "set" might be undefined if `Object.getOwnPropertyDescriptor`
|
25680 | // was used to get the value, and only `get` was defined by the user
|
25681 | if (has$4(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
|
25682 | return false;
|
25683 | }
|
25684 |
|
25685 | for (var key in obj) {
|
25686 | if (!accessor$3.hasOwnProperty(key)) {
|
25687 | continue;
|
25688 | }
|
25689 |
|
25690 | if (kindOf$5(obj[key]) === accessor$3[key]) {
|
25691 | continue;
|
25692 | }
|
25693 |
|
25694 | if (typeof obj[key] !== 'undefined') {
|
25695 | return false;
|
25696 | }
|
25697 | }
|
25698 | return true;
|
25699 | }
|
25700 |
|
25701 | function has$4(obj, key) {
|
25702 | return {}.hasOwnProperty.call(obj, key);
|
25703 | }
|
25704 |
|
25705 | /**
|
25706 | * Expose `isAccessorDescriptor`
|
25707 | */
|
25708 |
|
25709 | var isAccessorDescriptor_1$3 = isAccessorDescriptor$3;
|
25710 |
|
25711 | var toString$9 = Object.prototype.toString;
|
25712 |
|
25713 | /**
|
25714 | * Get the native `typeof` a value.
|
25715 | *
|
25716 | * @param {*} `val`
|
25717 | * @return {*} Native javascript type
|
25718 | */
|
25719 |
|
25720 | var kindOf$6 = function kindOf(val) {
|
25721 | // primitivies
|
25722 | if (typeof val === 'undefined') {
|
25723 | return 'undefined';
|
25724 | }
|
25725 | if (val === null) {
|
25726 | return 'null';
|
25727 | }
|
25728 | if (val === true || val === false || val instanceof Boolean) {
|
25729 | return 'boolean';
|
25730 | }
|
25731 | if (typeof val === 'string' || val instanceof String) {
|
25732 | return 'string';
|
25733 | }
|
25734 | if (typeof val === 'number' || val instanceof Number) {
|
25735 | return 'number';
|
25736 | }
|
25737 |
|
25738 | // functions
|
25739 | if (typeof val === 'function' || val instanceof Function) {
|
25740 | return 'function';
|
25741 | }
|
25742 |
|
25743 | // array
|
25744 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
25745 | return 'array';
|
25746 | }
|
25747 |
|
25748 | // check for instances of RegExp and Date before calling `toString`
|
25749 | if (val instanceof RegExp) {
|
25750 | return 'regexp';
|
25751 | }
|
25752 | if (val instanceof Date) {
|
25753 | return 'date';
|
25754 | }
|
25755 |
|
25756 | // other objects
|
25757 | var type = toString$9.call(val);
|
25758 |
|
25759 | if (type === '[object RegExp]') {
|
25760 | return 'regexp';
|
25761 | }
|
25762 | if (type === '[object Date]') {
|
25763 | return 'date';
|
25764 | }
|
25765 | if (type === '[object Arguments]') {
|
25766 | return 'arguments';
|
25767 | }
|
25768 | if (type === '[object Error]') {
|
25769 | return 'error';
|
25770 | }
|
25771 |
|
25772 | // buffer
|
25773 | if (isBuffer_1(val)) {
|
25774 | return 'buffer';
|
25775 | }
|
25776 |
|
25777 | // es6: Map, WeakMap, Set, WeakSet
|
25778 | if (type === '[object Set]') {
|
25779 | return 'set';
|
25780 | }
|
25781 | if (type === '[object WeakSet]') {
|
25782 | return 'weakset';
|
25783 | }
|
25784 | if (type === '[object Map]') {
|
25785 | return 'map';
|
25786 | }
|
25787 | if (type === '[object WeakMap]') {
|
25788 | return 'weakmap';
|
25789 | }
|
25790 | if (type === '[object Symbol]') {
|
25791 | return 'symbol';
|
25792 | }
|
25793 |
|
25794 | // typed arrays
|
25795 | if (type === '[object Int8Array]') {
|
25796 | return 'int8array';
|
25797 | }
|
25798 | if (type === '[object Uint8Array]') {
|
25799 | return 'uint8array';
|
25800 | }
|
25801 | if (type === '[object Uint8ClampedArray]') {
|
25802 | return 'uint8clampedarray';
|
25803 | }
|
25804 | if (type === '[object Int16Array]') {
|
25805 | return 'int16array';
|
25806 | }
|
25807 | if (type === '[object Uint16Array]') {
|
25808 | return 'uint16array';
|
25809 | }
|
25810 | if (type === '[object Int32Array]') {
|
25811 | return 'int32array';
|
25812 | }
|
25813 | if (type === '[object Uint32Array]') {
|
25814 | return 'uint32array';
|
25815 | }
|
25816 | if (type === '[object Float32Array]') {
|
25817 | return 'float32array';
|
25818 | }
|
25819 | if (type === '[object Float64Array]') {
|
25820 | return 'float64array';
|
25821 | }
|
25822 |
|
25823 | // must be a plain object
|
25824 | return 'object';
|
25825 | };
|
25826 |
|
25827 | // data descriptor properties
|
25828 | var data = {
|
25829 | configurable: 'boolean',
|
25830 | enumerable: 'boolean',
|
25831 | writable: 'boolean'
|
25832 | };
|
25833 |
|
25834 | function isDataDescriptor$3(obj, prop) {
|
25835 | if (kindOf$6(obj) !== 'object') {
|
25836 | return false;
|
25837 | }
|
25838 |
|
25839 | if (typeof prop === 'string') {
|
25840 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
25841 | return typeof val !== 'undefined';
|
25842 | }
|
25843 |
|
25844 | if (!('value' in obj) && !('writable' in obj)) {
|
25845 | return false;
|
25846 | }
|
25847 |
|
25848 | for (var key in obj) {
|
25849 | if (key === 'value') continue;
|
25850 |
|
25851 | if (!data.hasOwnProperty(key)) {
|
25852 | continue;
|
25853 | }
|
25854 |
|
25855 | if (kindOf$6(obj[key]) === data[key]) {
|
25856 | continue;
|
25857 | }
|
25858 |
|
25859 | if (typeof obj[key] !== 'undefined') {
|
25860 | return false;
|
25861 | }
|
25862 | }
|
25863 | return true;
|
25864 | }
|
25865 |
|
25866 | /**
|
25867 | * Expose `isDataDescriptor`
|
25868 | */
|
25869 |
|
25870 | var isDataDescriptor_1 = isDataDescriptor$3;
|
25871 |
|
25872 | var isDescriptor$3 = function isDescriptor(obj, key) {
|
25873 | if (kindOf$4(obj) !== 'object') {
|
25874 | return false;
|
25875 | }
|
25876 | if ('get' in obj) {
|
25877 | return isAccessorDescriptor_1$3(obj, key);
|
25878 | }
|
25879 | return isDataDescriptor_1(obj, key);
|
25880 | };
|
25881 |
|
25882 | var defineProperty$3 = function defineProperty(obj, prop, val) {
|
25883 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
25884 | throw new TypeError('expected an object or function.');
|
25885 | }
|
25886 |
|
25887 | if (typeof prop !== 'string') {
|
25888 | throw new TypeError('expected `prop` to be a string.');
|
25889 | }
|
25890 |
|
25891 | if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
|
25892 | return Object.defineProperty(obj, prop, val);
|
25893 | }
|
25894 |
|
25895 | return Object.defineProperty(obj, prop, {
|
25896 | configurable: true,
|
25897 | enumerable: false,
|
25898 | writable: true,
|
25899 | value: val
|
25900 | });
|
25901 | };
|
25902 |
|
25903 | var toString$a = Object.prototype.toString;
|
25904 |
|
25905 | /**
|
25906 | * Get the native `typeof` a value.
|
25907 | *
|
25908 | * @param {*} `val`
|
25909 | * @return {*} Native javascript type
|
25910 | */
|
25911 |
|
25912 | var kindOf$7 = function kindOf(val) {
|
25913 | // primitivies
|
25914 | if (typeof val === 'undefined') {
|
25915 | return 'undefined';
|
25916 | }
|
25917 | if (val === null) {
|
25918 | return 'null';
|
25919 | }
|
25920 | if (val === true || val === false || val instanceof Boolean) {
|
25921 | return 'boolean';
|
25922 | }
|
25923 | if (typeof val === 'string' || val instanceof String) {
|
25924 | return 'string';
|
25925 | }
|
25926 | if (typeof val === 'number' || val instanceof Number) {
|
25927 | return 'number';
|
25928 | }
|
25929 |
|
25930 | // functions
|
25931 | if (typeof val === 'function' || val instanceof Function) {
|
25932 | return 'function';
|
25933 | }
|
25934 |
|
25935 | // array
|
25936 | if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
|
25937 | return 'array';
|
25938 | }
|
25939 |
|
25940 | // check for instances of RegExp and Date before calling `toString`
|
25941 | if (val instanceof RegExp) {
|
25942 | return 'regexp';
|
25943 | }
|
25944 | if (val instanceof Date) {
|
25945 | return 'date';
|
25946 | }
|
25947 |
|
25948 | // other objects
|
25949 | var type = toString$a.call(val);
|
25950 |
|
25951 | if (type === '[object RegExp]') {
|
25952 | return 'regexp';
|
25953 | }
|
25954 | if (type === '[object Date]') {
|
25955 | return 'date';
|
25956 | }
|
25957 | if (type === '[object Arguments]') {
|
25958 | return 'arguments';
|
25959 | }
|
25960 | if (type === '[object Error]') {
|
25961 | return 'error';
|
25962 | }
|
25963 |
|
25964 | // buffer
|
25965 | if (isBuffer_1(val)) {
|
25966 | return 'buffer';
|
25967 | }
|
25968 |
|
25969 | // es6: Map, WeakMap, Set, WeakSet
|
25970 | if (type === '[object Set]') {
|
25971 | return 'set';
|
25972 | }
|
25973 | if (type === '[object WeakSet]') {
|
25974 | return 'weakset';
|
25975 | }
|
25976 | if (type === '[object Map]') {
|
25977 | return 'map';
|
25978 | }
|
25979 | if (type === '[object WeakMap]') {
|
25980 | return 'weakmap';
|
25981 | }
|
25982 | if (type === '[object Symbol]') {
|
25983 | return 'symbol';
|
25984 | }
|
25985 |
|
25986 | // typed arrays
|
25987 | if (type === '[object Int8Array]') {
|
25988 | return 'int8array';
|
25989 | }
|
25990 | if (type === '[object Uint8Array]') {
|
25991 | return 'uint8array';
|
25992 | }
|
25993 | if (type === '[object Uint8ClampedArray]') {
|
25994 | return 'uint8clampedarray';
|
25995 | }
|
25996 | if (type === '[object Int16Array]') {
|
25997 | return 'int16array';
|
25998 | }
|
25999 | if (type === '[object Uint16Array]') {
|
26000 | return 'uint16array';
|
26001 | }
|
26002 | if (type === '[object Int32Array]') {
|
26003 | return 'int32array';
|
26004 | }
|
26005 | if (type === '[object Uint32Array]') {
|
26006 | return 'uint32array';
|
26007 | }
|
26008 | if (type === '[object Float32Array]') {
|
26009 | return 'float32array';
|
26010 | }
|
26011 | if (type === '[object Float64Array]') {
|
26012 | return 'float64array';
|
26013 | }
|
26014 |
|
26015 | // must be a plain object
|
26016 | return 'object';
|
26017 | };
|
26018 |
|
26019 | /*!
|
26020 | * copy-descriptor <https://github.com/jonschlinkert/copy-descriptor>
|
26021 | *
|
26022 | * Copyright (c) 2015, Jon Schlinkert.
|
26023 | * Licensed under the MIT License.
|
26024 | */
|
26025 |
|
26026 | /**
|
26027 | * Copy a descriptor from one object to another.
|
26028 | *
|
26029 | * ```js
|
26030 | * function App() {
|
26031 | * this.cache = {};
|
26032 | * }
|
26033 | * App.prototype.set = function(key, val) {
|
26034 | * this.cache[key] = val;
|
26035 | * return this;
|
26036 | * };
|
26037 | * Object.defineProperty(App.prototype, 'count', {
|
26038 | * get: function() {
|
26039 | * return Object.keys(this.cache).length;
|
26040 | * }
|
26041 | * });
|
26042 | *
|
26043 | * copy(App.prototype, 'count', 'len');
|
26044 | *
|
26045 | * // create an instance
|
26046 | * var app = new App();
|
26047 | *
|
26048 | * app.set('a', true);
|
26049 | * app.set('b', true);
|
26050 | * app.set('c', true);
|
26051 | *
|
26052 | * console.log(app.count);
|
26053 | * //=> 3
|
26054 | * console.log(app.len);
|
26055 | * //=> 3
|
26056 | * ```
|
26057 | * @name copy
|
26058 | * @param {Object} `receiver` The target object
|
26059 | * @param {Object} `provider` The provider object
|
26060 | * @param {String} `from` The key to copy on provider.
|
26061 | * @param {String} `to` Optionally specify a new key name to use.
|
26062 | * @return {Object}
|
26063 | * @api public
|
26064 | */
|
26065 |
|
26066 | var copyDescriptor = function copyDescriptor(receiver, provider, from, to) {
|
26067 | if (!isObject$5(provider) && typeof provider !== 'function') {
|
26068 | to = from;
|
26069 | from = provider;
|
26070 | provider = receiver;
|
26071 | }
|
26072 | if (!isObject$5(receiver) && typeof receiver !== 'function') {
|
26073 | throw new TypeError('expected the first argument to be an object');
|
26074 | }
|
26075 | if (!isObject$5(provider) && typeof provider !== 'function') {
|
26076 | throw new TypeError('expected provider to be an object');
|
26077 | }
|
26078 |
|
26079 | if (typeof to !== 'string') {
|
26080 | to = from;
|
26081 | }
|
26082 | if (typeof from !== 'string') {
|
26083 | throw new TypeError('expected key to be a string');
|
26084 | }
|
26085 |
|
26086 | if (!(from in provider)) {
|
26087 | throw new Error('property "' + from + '" does not exist');
|
26088 | }
|
26089 |
|
26090 | var val = Object.getOwnPropertyDescriptor(provider, from);
|
26091 | if (val) Object.defineProperty(receiver, to, val);
|
26092 | };
|
26093 |
|
26094 | function isObject$5(val) {
|
26095 | return {}.toString.call(val) === '[object Object]';
|
26096 | }
|
26097 |
|
26098 | var defineProperty$4 = function defineProperty(obj, prop, val) {
|
26099 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
26100 | throw new TypeError('expected an object or function.');
|
26101 | }
|
26102 |
|
26103 | if (typeof prop !== 'string') {
|
26104 | throw new TypeError('expected `prop` to be a string.');
|
26105 | }
|
26106 |
|
26107 | if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
|
26108 | return Object.defineProperty(obj, prop, val);
|
26109 | }
|
26110 |
|
26111 | return Object.defineProperty(obj, prop, {
|
26112 | configurable: true,
|
26113 | enumerable: false,
|
26114 | writable: true,
|
26115 | value: val
|
26116 | });
|
26117 | };
|
26118 |
|
26119 | /**
|
26120 | * Copy static properties, prototype properties, and descriptors from one object to another.
|
26121 | *
|
26122 | * ```js
|
26123 | * function App() {}
|
26124 | * var proto = App.prototype;
|
26125 | * App.prototype.set = function() {};
|
26126 | * App.prototype.get = function() {};
|
26127 | *
|
26128 | * var obj = {};
|
26129 | * copy(obj, proto);
|
26130 | * ```
|
26131 | * @param {Object} `receiver`
|
26132 | * @param {Object} `provider`
|
26133 | * @param {String|Array} `omit` One or more properties to omit
|
26134 | * @return {Object}
|
26135 | * @api public
|
26136 | */
|
26137 |
|
26138 | function copy$1(receiver, provider, omit) {
|
26139 | if (!isObject$6(receiver)) {
|
26140 | throw new TypeError('expected receiving object to be an object.');
|
26141 | }
|
26142 | if (!isObject$6(provider)) {
|
26143 | throw new TypeError('expected providing object to be an object.');
|
26144 | }
|
26145 |
|
26146 | var props = nativeKeys(provider);
|
26147 | var keys = Object.keys(provider);
|
26148 | var len = props.length;
|
26149 | omit = arrayify$2(omit);
|
26150 |
|
26151 | while (len--) {
|
26152 | var key = props[len];
|
26153 |
|
26154 | if (has$5(keys, key)) {
|
26155 | defineProperty$4(receiver, key, provider[key]);
|
26156 | } else if (!(key in receiver) && !has$5(omit, key)) {
|
26157 | copyDescriptor(receiver, provider, key);
|
26158 | }
|
26159 | }
|
26160 | }
|
26161 | /**
|
26162 | * Return true if the given value is an object or function
|
26163 | */
|
26164 |
|
26165 | function isObject$6(val) {
|
26166 | return kindOf$7(val) === 'object' || typeof val === 'function';
|
26167 | }
|
26168 |
|
26169 | /**
|
26170 | * Returns true if an array has any of the given elements, or an
|
26171 | * object has any of the give keys.
|
26172 | *
|
26173 | * ```js
|
26174 | * has(['a', 'b', 'c'], 'c');
|
26175 | * //=> true
|
26176 | *
|
26177 | * has(['a', 'b', 'c'], ['c', 'z']);
|
26178 | * //=> true
|
26179 | *
|
26180 | * has({a: 'b', c: 'd'}, ['c', 'z']);
|
26181 | * //=> true
|
26182 | * ```
|
26183 | * @param {Object} `obj`
|
26184 | * @param {String|Array} `val`
|
26185 | * @return {Boolean}
|
26186 | */
|
26187 |
|
26188 | function has$5(obj, val) {
|
26189 | val = arrayify$2(val);
|
26190 | var len = val.length;
|
26191 |
|
26192 | if (isObject$6(obj)) {
|
26193 | for (var key in obj) {
|
26194 | if (val.indexOf(key) > -1) {
|
26195 | return true;
|
26196 | }
|
26197 | }
|
26198 |
|
26199 | var keys = nativeKeys(obj);
|
26200 | return has$5(keys, val);
|
26201 | }
|
26202 |
|
26203 | if (Array.isArray(obj)) {
|
26204 | var arr = obj;
|
26205 | while (len--) {
|
26206 | if (arr.indexOf(val[len]) > -1) {
|
26207 | return true;
|
26208 | }
|
26209 | }
|
26210 | return false;
|
26211 | }
|
26212 |
|
26213 | throw new TypeError('expected an array or object.');
|
26214 | }
|
26215 |
|
26216 | /**
|
26217 | * Cast the given value to an array.
|
26218 | *
|
26219 | * ```js
|
26220 | * arrayify('foo');
|
26221 | * //=> ['foo']
|
26222 | *
|
26223 | * arrayify(['foo']);
|
26224 | * //=> ['foo']
|
26225 | * ```
|
26226 | *
|
26227 | * @param {String|Array} `val`
|
26228 | * @return {Array}
|
26229 | */
|
26230 |
|
26231 | function arrayify$2(val) {
|
26232 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
26233 | }
|
26234 |
|
26235 | /**
|
26236 | * Returns true if a value has a `contructor`
|
26237 | *
|
26238 | * ```js
|
26239 | * hasConstructor({});
|
26240 | * //=> true
|
26241 | *
|
26242 | * hasConstructor(Object.create(null));
|
26243 | * //=> false
|
26244 | * ```
|
26245 | * @param {Object} `value`
|
26246 | * @return {Boolean}
|
26247 | */
|
26248 |
|
26249 | function hasConstructor(val) {
|
26250 | return isObject$6(val) && typeof val.constructor !== 'undefined';
|
26251 | }
|
26252 |
|
26253 | /**
|
26254 | * Get the native `ownPropertyNames` from the constructor of the
|
26255 | * given `object`. An empty array is returned if the object does
|
26256 | * not have a constructor.
|
26257 | *
|
26258 | * ```js
|
26259 | * nativeKeys({a: 'b', b: 'c', c: 'd'})
|
26260 | * //=> ['a', 'b', 'c']
|
26261 | *
|
26262 | * nativeKeys(function(){})
|
26263 | * //=> ['length', 'caller']
|
26264 | * ```
|
26265 | *
|
26266 | * @param {Object} `obj` Object that has a `constructor`.
|
26267 | * @return {Array} Array of keys.
|
26268 | */
|
26269 |
|
26270 | function nativeKeys(val) {
|
26271 | if (!hasConstructor(val)) return [];
|
26272 | return Object.getOwnPropertyNames(val);
|
26273 | }
|
26274 |
|
26275 | /**
|
26276 | * Expose `copy`
|
26277 | */
|
26278 |
|
26279 | var objectCopy = copy$1;
|
26280 |
|
26281 | /**
|
26282 | * Expose `copy.has` for tests
|
26283 | */
|
26284 |
|
26285 | var has_1 = has$5;
|
26286 | objectCopy.has = has_1;
|
26287 |
|
26288 | var defineProperty$5 = function defineProperty(obj, prop, val) {
|
26289 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
26290 | throw new TypeError('expected an object or function.');
|
26291 | }
|
26292 |
|
26293 | if (typeof prop !== 'string') {
|
26294 | throw new TypeError('expected `prop` to be a string.');
|
26295 | }
|
26296 |
|
26297 | if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
|
26298 | return Object.defineProperty(obj, prop, val);
|
26299 | }
|
26300 |
|
26301 | return Object.defineProperty(obj, prop, {
|
26302 | configurable: true,
|
26303 | enumerable: false,
|
26304 | writable: true,
|
26305 | value: val
|
26306 | });
|
26307 | };
|
26308 |
|
26309 | /**
|
26310 | * Returns a function for extending the static properties,
|
26311 | * prototype properties, and descriptors from the `Parent`
|
26312 | * constructor onto `Child` constructors.
|
26313 | *
|
26314 | * ```js
|
26315 | * var extend = require('static-extend');
|
26316 | * Parent.extend = extend(Parent);
|
26317 | *
|
26318 | * // optionally pass a custom merge function as the second arg
|
26319 | * Parent.extend = extend(Parent, function(Child) {
|
26320 | * Child.prototype.mixin = function(key, val) {
|
26321 | * Child.prototype[key] = val;
|
26322 | * };
|
26323 | * });
|
26324 | *
|
26325 | * // extend "child" constructors
|
26326 | * Parent.extend(Child);
|
26327 | *
|
26328 | * // optionally define prototype methods as the second arg
|
26329 | * Parent.extend(Child, {
|
26330 | * foo: function() {},
|
26331 | * bar: function() {}
|
26332 | * });
|
26333 | * ```
|
26334 | * @param {Function} `Parent` Parent ctor
|
26335 | * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype.
|
26336 | * @param {Function} `Child` Child ctor
|
26337 | * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
|
26338 | * @return {Object}
|
26339 | * @api public
|
26340 | */
|
26341 |
|
26342 | function extend(Parent, extendFn) {
|
26343 | if (typeof Parent !== 'function') {
|
26344 | throw new TypeError('expected Parent to be a function.');
|
26345 | }
|
26346 |
|
26347 | return function(Ctor, proto) {
|
26348 | if (typeof Ctor !== 'function') {
|
26349 | throw new TypeError('expected Ctor to be a function.');
|
26350 | }
|
26351 |
|
26352 | util$2.inherits(Ctor, Parent);
|
26353 | objectCopy(Ctor, Parent);
|
26354 |
|
26355 | // proto can be null or a plain object
|
26356 | if (typeof proto === 'object') {
|
26357 | var obj = Object.create(proto);
|
26358 |
|
26359 | for (var k in obj) {
|
26360 | Ctor.prototype[k] = obj[k];
|
26361 | }
|
26362 | }
|
26363 |
|
26364 | // keep a reference to the parent prototype
|
26365 | defineProperty$5(Ctor.prototype, '_parent_', {
|
26366 | configurable: true,
|
26367 | set: function() {},
|
26368 | get: function() {
|
26369 | return Parent.prototype;
|
26370 | }
|
26371 | });
|
26372 |
|
26373 | if (typeof extendFn === 'function') {
|
26374 | extendFn(Ctor, Parent);
|
26375 | }
|
26376 |
|
26377 | Ctor.extend = extend(Ctor, extendFn);
|
26378 | };
|
26379 | }
|
26380 | /**
|
26381 | * Expose `extend`
|
26382 | */
|
26383 |
|
26384 | var staticExtend = extend;
|
26385 |
|
26386 | var classUtils = createCommonjsModule(function (module) {
|
26387 |
|
26388 |
|
26389 |
|
26390 |
|
26391 |
|
26392 |
|
26393 |
|
26394 | /**
|
26395 | * Expose class utils
|
26396 | */
|
26397 |
|
26398 | var cu = module.exports;
|
26399 |
|
26400 | /**
|
26401 | * Expose class utils: `cu`
|
26402 | */
|
26403 |
|
26404 | cu.isObject = function isObject(val) {
|
26405 | return isobject(val) || typeof val === 'function';
|
26406 | };
|
26407 |
|
26408 | /**
|
26409 | * Returns true if an array has any of the given elements, or an
|
26410 | * object has any of the give keys.
|
26411 | *
|
26412 | * ```js
|
26413 | * cu.has(['a', 'b', 'c'], 'c');
|
26414 | * //=> true
|
26415 | *
|
26416 | * cu.has(['a', 'b', 'c'], ['c', 'z']);
|
26417 | * //=> true
|
26418 | *
|
26419 | * cu.has({a: 'b', c: 'd'}, ['c', 'z']);
|
26420 | * //=> true
|
26421 | * ```
|
26422 | * @param {Object} `obj`
|
26423 | * @param {String|Array} `val`
|
26424 | * @return {Boolean}
|
26425 | * @api public
|
26426 | */
|
26427 |
|
26428 | cu.has = function has(obj, val) {
|
26429 | val = cu.arrayify(val);
|
26430 | var len = val.length;
|
26431 |
|
26432 | if (cu.isObject(obj)) {
|
26433 | for (var key in obj) {
|
26434 | if (val.indexOf(key) > -1) {
|
26435 | return true;
|
26436 | }
|
26437 | }
|
26438 |
|
26439 | var keys = cu.nativeKeys(obj);
|
26440 | return cu.has(keys, val);
|
26441 | }
|
26442 |
|
26443 | if (Array.isArray(obj)) {
|
26444 | var arr = obj;
|
26445 | while (len--) {
|
26446 | if (arr.indexOf(val[len]) > -1) {
|
26447 | return true;
|
26448 | }
|
26449 | }
|
26450 | return false;
|
26451 | }
|
26452 |
|
26453 | throw new TypeError('expected an array or object.');
|
26454 | };
|
26455 |
|
26456 | /**
|
26457 | * Returns true if an array or object has all of the given values.
|
26458 | *
|
26459 | * ```js
|
26460 | * cu.hasAll(['a', 'b', 'c'], 'c');
|
26461 | * //=> true
|
26462 | *
|
26463 | * cu.hasAll(['a', 'b', 'c'], ['c', 'z']);
|
26464 | * //=> false
|
26465 | *
|
26466 | * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']);
|
26467 | * //=> false
|
26468 | * ```
|
26469 | * @param {Object|Array} `val`
|
26470 | * @param {String|Array} `values`
|
26471 | * @return {Boolean}
|
26472 | * @api public
|
26473 | */
|
26474 |
|
26475 | cu.hasAll = function hasAll(val, values) {
|
26476 | values = cu.arrayify(values);
|
26477 | var len = values.length;
|
26478 | while (len--) {
|
26479 | if (!cu.has(val, values[len])) {
|
26480 | return false;
|
26481 | }
|
26482 | }
|
26483 | return true;
|
26484 | };
|
26485 |
|
26486 | /**
|
26487 | * Cast the given value to an array.
|
26488 | *
|
26489 | * ```js
|
26490 | * cu.arrayify('foo');
|
26491 | * //=> ['foo']
|
26492 | *
|
26493 | * cu.arrayify(['foo']);
|
26494 | * //=> ['foo']
|
26495 | * ```
|
26496 | *
|
26497 | * @param {String|Array} `val`
|
26498 | * @return {Array}
|
26499 | * @api public
|
26500 | */
|
26501 |
|
26502 | cu.arrayify = function arrayify(val) {
|
26503 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
26504 | };
|
26505 |
|
26506 | /**
|
26507 | * Noop
|
26508 | */
|
26509 |
|
26510 | cu.noop = function noop() {
|
26511 | return;
|
26512 | };
|
26513 |
|
26514 | /**
|
26515 | * Returns the first argument passed to the function.
|
26516 | */
|
26517 |
|
26518 | cu.identity = function identity(val) {
|
26519 | return val;
|
26520 | };
|
26521 |
|
26522 | /**
|
26523 | * Returns true if a value has a `contructor`
|
26524 | *
|
26525 | * ```js
|
26526 | * cu.hasConstructor({});
|
26527 | * //=> true
|
26528 | *
|
26529 | * cu.hasConstructor(Object.create(null));
|
26530 | * //=> false
|
26531 | * ```
|
26532 | * @param {Object} `value`
|
26533 | * @return {Boolean}
|
26534 | * @api public
|
26535 | */
|
26536 |
|
26537 | cu.hasConstructor = function hasConstructor(val) {
|
26538 | return cu.isObject(val) && typeof val.constructor !== 'undefined';
|
26539 | };
|
26540 |
|
26541 | /**
|
26542 | * Get the native `ownPropertyNames` from the constructor of the
|
26543 | * given `object`. An empty array is returned if the object does
|
26544 | * not have a constructor.
|
26545 | *
|
26546 | * ```js
|
26547 | * cu.nativeKeys({a: 'b', b: 'c', c: 'd'})
|
26548 | * //=> ['a', 'b', 'c']
|
26549 | *
|
26550 | * cu.nativeKeys(function(){})
|
26551 | * //=> ['length', 'caller']
|
26552 | * ```
|
26553 | *
|
26554 | * @param {Object} `obj` Object that has a `constructor`.
|
26555 | * @return {Array} Array of keys.
|
26556 | * @api public
|
26557 | */
|
26558 |
|
26559 | cu.nativeKeys = function nativeKeys(val) {
|
26560 | if (!cu.hasConstructor(val)) return [];
|
26561 | var keys = Object.getOwnPropertyNames(val);
|
26562 | if ('caller' in val) keys.push('caller');
|
26563 | return keys;
|
26564 | };
|
26565 |
|
26566 | /**
|
26567 | * Returns property descriptor `key` if it's an "own" property
|
26568 | * of the given object.
|
26569 | *
|
26570 | * ```js
|
26571 | * function App() {}
|
26572 | * Object.defineProperty(App.prototype, 'count', {
|
26573 | * get: function() {
|
26574 | * return Object.keys(this).length;
|
26575 | * }
|
26576 | * });
|
26577 | * cu.getDescriptor(App.prototype, 'count');
|
26578 | * // returns:
|
26579 | * // {
|
26580 | * // get: [Function],
|
26581 | * // set: undefined,
|
26582 | * // enumerable: false,
|
26583 | * // configurable: false
|
26584 | * // }
|
26585 | * ```
|
26586 | *
|
26587 | * @param {Object} `obj`
|
26588 | * @param {String} `key`
|
26589 | * @return {Object} Returns descriptor `key`
|
26590 | * @api public
|
26591 | */
|
26592 |
|
26593 | cu.getDescriptor = function getDescriptor(obj, key) {
|
26594 | if (!cu.isObject(obj)) {
|
26595 | throw new TypeError('expected an object.');
|
26596 | }
|
26597 | if (typeof key !== 'string') {
|
26598 | throw new TypeError('expected key to be a string.');
|
26599 | }
|
26600 | return Object.getOwnPropertyDescriptor(obj, key);
|
26601 | };
|
26602 |
|
26603 | /**
|
26604 | * Copy a descriptor from one object to another.
|
26605 | *
|
26606 | * ```js
|
26607 | * function App() {}
|
26608 | * Object.defineProperty(App.prototype, 'count', {
|
26609 | * get: function() {
|
26610 | * return Object.keys(this).length;
|
26611 | * }
|
26612 | * });
|
26613 | * var obj = {};
|
26614 | * cu.copyDescriptor(obj, App.prototype, 'count');
|
26615 | * ```
|
26616 | * @param {Object} `receiver`
|
26617 | * @param {Object} `provider`
|
26618 | * @param {String} `name`
|
26619 | * @return {Object}
|
26620 | * @api public
|
26621 | */
|
26622 |
|
26623 | cu.copyDescriptor = function copyDescriptor(receiver, provider, name) {
|
26624 | if (!cu.isObject(receiver)) {
|
26625 | throw new TypeError('expected receiving object to be an object.');
|
26626 | }
|
26627 | if (!cu.isObject(provider)) {
|
26628 | throw new TypeError('expected providing object to be an object.');
|
26629 | }
|
26630 | if (typeof name !== 'string') {
|
26631 | throw new TypeError('expected name to be a string.');
|
26632 | }
|
26633 |
|
26634 | var val = cu.getDescriptor(provider, name);
|
26635 | if (val) Object.defineProperty(receiver, name, val);
|
26636 | };
|
26637 |
|
26638 | /**
|
26639 | * Copy static properties, prototype properties, and descriptors
|
26640 | * from one object to another.
|
26641 | *
|
26642 | * @param {Object} `receiver`
|
26643 | * @param {Object} `provider`
|
26644 | * @param {String|Array} `omit` One or more properties to omit
|
26645 | * @return {Object}
|
26646 | * @api public
|
26647 | */
|
26648 |
|
26649 | cu.copy = function copy(receiver, provider, omit) {
|
26650 | if (!cu.isObject(receiver)) {
|
26651 | throw new TypeError('expected receiving object to be an object.');
|
26652 | }
|
26653 | if (!cu.isObject(provider)) {
|
26654 | throw new TypeError('expected providing object to be an object.');
|
26655 | }
|
26656 | var props = Object.getOwnPropertyNames(provider);
|
26657 | var keys = Object.keys(provider);
|
26658 | var len = props.length,
|
26659 | key;
|
26660 | omit = cu.arrayify(omit);
|
26661 |
|
26662 | while (len--) {
|
26663 | key = props[len];
|
26664 |
|
26665 | if (cu.has(keys, key)) {
|
26666 | defineProperty$3(receiver, key, provider[key]);
|
26667 | } else if (!(key in receiver) && !cu.has(omit, key)) {
|
26668 | cu.copyDescriptor(receiver, provider, key);
|
26669 | }
|
26670 | }
|
26671 | };
|
26672 |
|
26673 | /**
|
26674 | * Inherit the static properties, prototype properties, and descriptors
|
26675 | * from of an object.
|
26676 | *
|
26677 | * @param {Object} `receiver`
|
26678 | * @param {Object} `provider`
|
26679 | * @param {String|Array} `omit` One or more properties to omit
|
26680 | * @return {Object}
|
26681 | * @api public
|
26682 | */
|
26683 |
|
26684 | cu.inherit = function inherit(receiver, provider, omit) {
|
26685 | if (!cu.isObject(receiver)) {
|
26686 | throw new TypeError('expected receiving object to be an object.');
|
26687 | }
|
26688 | if (!cu.isObject(provider)) {
|
26689 | throw new TypeError('expected providing object to be an object.');
|
26690 | }
|
26691 |
|
26692 | var keys = [];
|
26693 | for (var key in provider) {
|
26694 | keys.push(key);
|
26695 | receiver[key] = provider[key];
|
26696 | }
|
26697 |
|
26698 | keys = keys.concat(cu.arrayify(omit));
|
26699 |
|
26700 | var a = provider.prototype || provider;
|
26701 | var b = receiver.prototype || receiver;
|
26702 | cu.copy(b, a, keys);
|
26703 | };
|
26704 |
|
26705 | /**
|
26706 | * Returns a function for extending the static properties,
|
26707 | * prototype properties, and descriptors from the `Parent`
|
26708 | * constructor onto `Child` constructors.
|
26709 | *
|
26710 | * ```js
|
26711 | * var extend = cu.extend(Parent);
|
26712 | * Parent.extend(Child);
|
26713 | *
|
26714 | * // optional methods
|
26715 | * Parent.extend(Child, {
|
26716 | * foo: function() {},
|
26717 | * bar: function() {}
|
26718 | * });
|
26719 | * ```
|
26720 | * @param {Function} `Parent` Parent ctor
|
26721 | * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype.
|
26722 | * @param {Function} `Child` Child ctor
|
26723 | * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
|
26724 | * @return {Object}
|
26725 | * @api public
|
26726 | */
|
26727 |
|
26728 | cu.extend = function() {
|
26729 | // keep it lazy, instead of assigning to `cu.extend`
|
26730 | return staticExtend.apply(null, arguments);
|
26731 | };
|
26732 |
|
26733 | /**
|
26734 | * Bubble up events emitted from static methods on the Parent ctor.
|
26735 | *
|
26736 | * @param {Object} `Parent`
|
26737 | * @param {Array} `events` Event names to bubble up
|
26738 | * @api public
|
26739 | */
|
26740 |
|
26741 | cu.bubble = function(Parent, events) {
|
26742 | events = events || [];
|
26743 | Parent.bubble = function(Child, arr) {
|
26744 | if (Array.isArray(arr)) {
|
26745 | events = arrUnion([], events, arr);
|
26746 | }
|
26747 | var len = events.length;
|
26748 | var idx = -1;
|
26749 | while (++idx < len) {
|
26750 | var name = events[idx];
|
26751 | Parent.on(name, Child.emit.bind(Child, name));
|
26752 | }
|
26753 | cu.bubble(Child, events);
|
26754 | };
|
26755 | };
|
26756 | });
|
26757 |
|
26758 | /**
|
26759 | * Optionally define a custom `cache` namespace to use.
|
26760 | */
|
26761 |
|
26762 | function namespace$1(name) {
|
26763 | var Cache = name ? cacheBase.namespace(name) : cacheBase;
|
26764 | var fns = [];
|
26765 |
|
26766 | /**
|
26767 | * Create an instance of `Base` with the given `config` and `options`.
|
26768 | *
|
26769 | * ```js
|
26770 | * // initialize with `config` and `options`
|
26771 | * var app = new Base({isApp: true}, {abc: true});
|
26772 | * app.set('foo', 'bar');
|
26773 | *
|
26774 | * // values defined with the given `config` object will be on the root of the instance
|
26775 | * console.log(app.baz); //=> undefined
|
26776 | * console.log(app.foo); //=> 'bar'
|
26777 | * // or use `.get`
|
26778 | * console.log(app.get('isApp')); //=> true
|
26779 | * console.log(app.get('foo')); //=> 'bar'
|
26780 | *
|
26781 | * // values defined with the given `options` object will be on `app.options
|
26782 | * console.log(app.options.abc); //=> true
|
26783 | * ```
|
26784 | *
|
26785 | * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation.
|
26786 | * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object.
|
26787 | * @api public
|
26788 | */
|
26789 |
|
26790 | function Base(config, options) {
|
26791 | if (!(this instanceof Base)) {
|
26792 | return new Base(config, options);
|
26793 | }
|
26794 | Cache.call(this, config);
|
26795 | this.is('base');
|
26796 | this.initBase(config, options);
|
26797 | }
|
26798 |
|
26799 | /**
|
26800 | * Inherit cache-base
|
26801 | */
|
26802 |
|
26803 | util$2.inherits(Base, Cache);
|
26804 |
|
26805 | /**
|
26806 | * Add static emitter methods
|
26807 | */
|
26808 |
|
26809 | componentEmitter(Base);
|
26810 |
|
26811 | /**
|
26812 | * Initialize `Base` defaults with the given `config` object
|
26813 | */
|
26814 |
|
26815 | Base.prototype.initBase = function(config, options) {
|
26816 | this.options = mixinDeep_1({}, this.options, options);
|
26817 | this.cache = this.cache || {};
|
26818 | this.define('registered', {});
|
26819 | if (name) this[name] = {};
|
26820 |
|
26821 | // make `app._callbacks` non-enumerable
|
26822 | this.define('_callbacks', this._callbacks);
|
26823 | if (isobject(config)) {
|
26824 | this.visit('set', config);
|
26825 | }
|
26826 | Base.run(this, 'use', fns);
|
26827 | };
|
26828 |
|
26829 | /**
|
26830 | * Set the given `name` on `app._name` and `app.is*` properties. Used for doing
|
26831 | * lookups in plugins.
|
26832 | *
|
26833 | * ```js
|
26834 | * app.is('foo');
|
26835 | * console.log(app._name);
|
26836 | * //=> 'foo'
|
26837 | * console.log(app.isFoo);
|
26838 | * //=> true
|
26839 | * app.is('bar');
|
26840 | * console.log(app.isFoo);
|
26841 | * //=> true
|
26842 | * console.log(app.isBar);
|
26843 | * //=> true
|
26844 | * console.log(app._name);
|
26845 | * //=> 'bar'
|
26846 | * ```
|
26847 | * @name .is
|
26848 | * @param {String} `name`
|
26849 | * @return {Boolean}
|
26850 | * @api public
|
26851 | */
|
26852 |
|
26853 | Base.prototype.is = function(name) {
|
26854 | if (typeof name !== 'string') {
|
26855 | throw new TypeError('expected name to be a string');
|
26856 | }
|
26857 | this.define('is' + pascalcase_1(name), true);
|
26858 | this.define('_name', name);
|
26859 | this.define('_appname', name);
|
26860 | return this;
|
26861 | };
|
26862 |
|
26863 | /**
|
26864 | * Returns true if a plugin has already been registered on an instance.
|
26865 | *
|
26866 | * Plugin implementors are encouraged to use this first thing in a plugin
|
26867 | * to prevent the plugin from being called more than once on the same
|
26868 | * instance.
|
26869 | *
|
26870 | * ```js
|
26871 | * var base = new Base();
|
26872 | * base.use(function(app) {
|
26873 | * if (app.isRegistered('myPlugin')) return;
|
26874 | * // do stuff to `app`
|
26875 | * });
|
26876 | *
|
26877 | * // to also record the plugin as being registered
|
26878 | * base.use(function(app) {
|
26879 | * if (app.isRegistered('myPlugin', true)) return;
|
26880 | * // do stuff to `app`
|
26881 | * });
|
26882 | * ```
|
26883 | * @name .isRegistered
|
26884 | * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once.
|
26885 | * @param {String} `name` The plugin name.
|
26886 | * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument.
|
26887 | * @return {Boolean} Returns true if a plugin is already registered.
|
26888 | * @api public
|
26889 | */
|
26890 |
|
26891 | Base.prototype.isRegistered = function(name, register) {
|
26892 | if (this.registered.hasOwnProperty(name)) {
|
26893 | return true;
|
26894 | }
|
26895 | if (register !== false) {
|
26896 | this.registered[name] = true;
|
26897 | this.emit('plugin', name);
|
26898 | }
|
26899 | return false;
|
26900 | };
|
26901 |
|
26902 | /**
|
26903 | * Define a plugin function to be called immediately upon init. Plugins are chainable
|
26904 | * and expose the following arguments to the plugin function:
|
26905 | *
|
26906 | * - `app`: the current instance of `Base`
|
26907 | * - `base`: the [first ancestor instance](#base) of `Base`
|
26908 | *
|
26909 | * ```js
|
26910 | * var app = new Base()
|
26911 | * .use(foo)
|
26912 | * .use(bar)
|
26913 | * .use(baz)
|
26914 | * ```
|
26915 | * @name .use
|
26916 | * @param {Function} `fn` plugin function to call
|
26917 | * @return {Object} Returns the item instance for chaining.
|
26918 | * @api public
|
26919 | */
|
26920 |
|
26921 | Base.prototype.use = function(fn) {
|
26922 | fn.call(this, this);
|
26923 | return this;
|
26924 | };
|
26925 |
|
26926 | /**
|
26927 | * The `.define` method is used for adding non-enumerable property on the instance.
|
26928 | * Dot-notation is **not supported** with `define`.
|
26929 | *
|
26930 | * ```js
|
26931 | * // arbitrary `render` function using lodash `template`
|
26932 | * app.define('render', function(str, locals) {
|
26933 | * return _.template(str)(locals);
|
26934 | * });
|
26935 | * ```
|
26936 | * @name .define
|
26937 | * @param {String} `key` The name of the property to define.
|
26938 | * @param {any} `value`
|
26939 | * @return {Object} Returns the instance for chaining.
|
26940 | * @api public
|
26941 | */
|
26942 |
|
26943 | Base.prototype.define = function(key, val) {
|
26944 | if (isobject(key)) {
|
26945 | return this.visit('define', key);
|
26946 | }
|
26947 | defineProperty$2(this, key, val);
|
26948 | return this;
|
26949 | };
|
26950 |
|
26951 | /**
|
26952 | * Mix property `key` onto the Base prototype. If base is inherited using
|
26953 | * `Base.extend` this method will be overridden by a new `mixin` method that will
|
26954 | * only add properties to the prototype of the inheriting application.
|
26955 | *
|
26956 | * ```js
|
26957 | * app.mixin('foo', function() {
|
26958 | * // do stuff
|
26959 | * });
|
26960 | * ```
|
26961 | * @name .mixin
|
26962 | * @param {String} `key`
|
26963 | * @param {Object|Array} `val`
|
26964 | * @return {Object} Returns the `base` instance for chaining.
|
26965 | * @api public
|
26966 | */
|
26967 |
|
26968 | Base.prototype.mixin = function(key, val) {
|
26969 | Base.prototype[key] = val;
|
26970 | return this;
|
26971 | };
|
26972 |
|
26973 | /**
|
26974 | * Non-enumberable mixin array, used by the static [Base.mixin]() method.
|
26975 | */
|
26976 |
|
26977 | Base.prototype.mixins = Base.prototype.mixins || [];
|
26978 |
|
26979 | /**
|
26980 | * Getter/setter used when creating nested instances of `Base`, for storing a reference
|
26981 | * to the first ancestor instance. This works by setting an instance of `Base` on the `parent`
|
26982 | * property of a "child" instance. The `base` property defaults to the current instance if
|
26983 | * no `parent` property is defined.
|
26984 | *
|
26985 | * ```js
|
26986 | * // create an instance of `Base`, this is our first ("base") instance
|
26987 | * var first = new Base();
|
26988 | * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later
|
26989 | *
|
26990 | * // create another instance
|
26991 | * var second = new Base();
|
26992 | * // create a reference to the first instance (`first`)
|
26993 | * second.parent = first;
|
26994 | *
|
26995 | * // create another instance
|
26996 | * var third = new Base();
|
26997 | * // create a reference to the previous instance (`second`)
|
26998 | * // repeat this pattern every time a "child" instance is created
|
26999 | * third.parent = second;
|
27000 | *
|
27001 | * // we can always access the first instance using the `base` property
|
27002 | * console.log(first.base.foo);
|
27003 | * //=> 'bar'
|
27004 | * console.log(second.base.foo);
|
27005 | * //=> 'bar'
|
27006 | * console.log(third.base.foo);
|
27007 | * //=> 'bar'
|
27008 | * // and now you know how to get to third base ;)
|
27009 | * ```
|
27010 | * @name .base
|
27011 | * @api public
|
27012 | */
|
27013 |
|
27014 | Object.defineProperty(Base.prototype, 'base', {
|
27015 | configurable: true,
|
27016 | get: function() {
|
27017 | return this.parent ? this.parent.base : this;
|
27018 | }
|
27019 | });
|
27020 |
|
27021 | /**
|
27022 | * Static method for adding global plugin functions that will
|
27023 | * be added to an instance when created.
|
27024 | *
|
27025 | * ```js
|
27026 | * Base.use(function(app) {
|
27027 | * app.foo = 'bar';
|
27028 | * });
|
27029 | * var app = new Base();
|
27030 | * console.log(app.foo);
|
27031 | * //=> 'bar'
|
27032 | * ```
|
27033 | * @name #use
|
27034 | * @param {Function} `fn` Plugin function to use on each instance.
|
27035 | * @return {Object} Returns the `Base` constructor for chaining
|
27036 | * @api public
|
27037 | */
|
27038 |
|
27039 | defineProperty$2(Base, 'use', function(fn) {
|
27040 | fns.push(fn);
|
27041 | return Base;
|
27042 | });
|
27043 |
|
27044 | /**
|
27045 | * Run an array of functions by passing each function
|
27046 | * to a method on the given object specified by the given property.
|
27047 | *
|
27048 | * @param {Object} `obj` Object containing method to use.
|
27049 | * @param {String} `prop` Name of the method on the object to use.
|
27050 | * @param {Array} `arr` Array of functions to pass to the method.
|
27051 | */
|
27052 |
|
27053 | defineProperty$2(Base, 'run', function(obj, prop, arr) {
|
27054 | var len = arr.length, i = 0;
|
27055 | while (len--) {
|
27056 | obj[prop](arr[i++]);
|
27057 | }
|
27058 | return Base;
|
27059 | });
|
27060 |
|
27061 | /**
|
27062 | * Static method for inheriting the prototype and static methods of the `Base` class.
|
27063 | * This method greatly simplifies the process of creating inheritance-based applications.
|
27064 | * See [static-extend][] for more details.
|
27065 | *
|
27066 | * ```js
|
27067 | * var extend = cu.extend(Parent);
|
27068 | * Parent.extend(Child);
|
27069 | *
|
27070 | * // optional methods
|
27071 | * Parent.extend(Child, {
|
27072 | * foo: function() {},
|
27073 | * bar: function() {}
|
27074 | * });
|
27075 | * ```
|
27076 | * @name #extend
|
27077 | * @param {Function} `Ctor` constructor to extend
|
27078 | * @param {Object} `methods` Optional prototype properties to mix in.
|
27079 | * @return {Object} Returns the `Base` constructor for chaining
|
27080 | * @api public
|
27081 | */
|
27082 |
|
27083 | defineProperty$2(Base, 'extend', classUtils.extend(Base, function(Ctor, Parent) {
|
27084 | Ctor.prototype.mixins = Ctor.prototype.mixins || [];
|
27085 |
|
27086 | defineProperty$2(Ctor, 'mixin', function(fn) {
|
27087 | var mixin = fn(Ctor.prototype, Ctor);
|
27088 | if (typeof mixin === 'function') {
|
27089 | Ctor.prototype.mixins.push(mixin);
|
27090 | }
|
27091 | return Ctor;
|
27092 | });
|
27093 |
|
27094 | defineProperty$2(Ctor, 'mixins', function(Child) {
|
27095 | Base.run(Child, 'mixin', Ctor.prototype.mixins);
|
27096 | return Ctor;
|
27097 | });
|
27098 |
|
27099 | Ctor.prototype.mixin = function(key, value) {
|
27100 | Ctor.prototype[key] = value;
|
27101 | return this;
|
27102 | };
|
27103 | return Base;
|
27104 | }));
|
27105 |
|
27106 | /**
|
27107 | * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances.
|
27108 | * When a mixin function returns a function, the returned function is pushed onto the `.mixins`
|
27109 | * array, making it available to be used on inheriting classes whenever `Base.mixins()` is
|
27110 | * called (e.g. `Base.mixins(Child)`).
|
27111 | *
|
27112 | * ```js
|
27113 | * Base.mixin(function(proto) {
|
27114 | * proto.foo = function(msg) {
|
27115 | * return 'foo ' + msg;
|
27116 | * };
|
27117 | * });
|
27118 | * ```
|
27119 | * @name #mixin
|
27120 | * @param {Function} `fn` Function to call
|
27121 | * @return {Object} Returns the `Base` constructor for chaining
|
27122 | * @api public
|
27123 | */
|
27124 |
|
27125 | defineProperty$2(Base, 'mixin', function(fn) {
|
27126 | var mixin = fn(Base.prototype, Base);
|
27127 | if (typeof mixin === 'function') {
|
27128 | Base.prototype.mixins.push(mixin);
|
27129 | }
|
27130 | return Base;
|
27131 | });
|
27132 |
|
27133 | /**
|
27134 | * Static method for running global mixin functions against a child constructor.
|
27135 | * Mixins must be registered before calling this method.
|
27136 | *
|
27137 | * ```js
|
27138 | * Base.extend(Child);
|
27139 | * Base.mixins(Child);
|
27140 | * ```
|
27141 | * @name #mixins
|
27142 | * @param {Function} `Child` Constructor function of a child class
|
27143 | * @return {Object} Returns the `Base` constructor for chaining
|
27144 | * @api public
|
27145 | */
|
27146 |
|
27147 | defineProperty$2(Base, 'mixins', function(Child) {
|
27148 | Base.run(Child, 'mixin', Base.prototype.mixins);
|
27149 | return Base;
|
27150 | });
|
27151 |
|
27152 | /**
|
27153 | * Similar to `util.inherit`, but copies all static properties, prototype properties, and
|
27154 | * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details.
|
27155 | *
|
27156 | * ```js
|
27157 | * Base.inherit(Foo, Bar);
|
27158 | * ```
|
27159 | * @name #inherit
|
27160 | * @param {Function} `Receiver` Receiving (child) constructor
|
27161 | * @param {Function} `Provider` Providing (parent) constructor
|
27162 | * @return {Object} Returns the `Base` constructor for chaining
|
27163 | * @api public
|
27164 | */
|
27165 |
|
27166 | defineProperty$2(Base, 'inherit', classUtils.inherit);
|
27167 | defineProperty$2(Base, 'bubble', classUtils.bubble);
|
27168 | return Base;
|
27169 | }
|
27170 |
|
27171 | /**
|
27172 | * Expose `Base` with default settings
|
27173 | */
|
27174 |
|
27175 | var base$2 = namespace$1();
|
27176 |
|
27177 | /**
|
27178 | * Allow users to define a namespace
|
27179 | */
|
27180 |
|
27181 | var namespace_1$1 = namespace$1;
|
27182 | base$2.namespace = namespace_1$1;
|
27183 |
|
27184 | var defineProperty$6 = function defineProperty(obj, prop, val) {
|
27185 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
27186 | throw new TypeError('expected an object or function.');
|
27187 | }
|
27188 |
|
27189 | if (typeof prop !== 'string') {
|
27190 | throw new TypeError('expected `prop` to be a string.');
|
27191 | }
|
27192 |
|
27193 | if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
|
27194 | return Object.defineProperty(obj, prop, val);
|
27195 | }
|
27196 |
|
27197 | return Object.defineProperty(obj, prop, {
|
27198 | configurable: true,
|
27199 | enumerable: false,
|
27200 | writable: true,
|
27201 | value: val
|
27202 | });
|
27203 | };
|
27204 |
|
27205 | /*!
|
27206 | * use <https://github.com/jonschlinkert/use>
|
27207 | *
|
27208 | * Copyright (c) 2015-2017, Jon Schlinkert.
|
27209 | * Released under the MIT License.
|
27210 | */
|
27211 |
|
27212 | var use = function base(app, options) {
|
27213 | if (!isObject$7(app) && typeof app !== 'function') {
|
27214 | throw new TypeError('expected an object or function');
|
27215 | }
|
27216 |
|
27217 | var opts = isObject$7(options) ? options : {};
|
27218 | var prop = typeof opts.prop === 'string' ? opts.prop : 'fns';
|
27219 | if (!Array.isArray(app[prop])) {
|
27220 | define$1(app, prop, []);
|
27221 | }
|
27222 |
|
27223 | /**
|
27224 | * Define a plugin function to be passed to use. The only
|
27225 | * parameter exposed to the plugin is `app`, the object or function.
|
27226 | * passed to `use(app)`. `app` is also exposed as `this` in plugins.
|
27227 | *
|
27228 | * Additionally, **if a plugin returns a function, the function will
|
27229 | * be pushed onto the `fns` array**, allowing the plugin to be
|
27230 | * called at a later point by the `run` method.
|
27231 | *
|
27232 | * ```js
|
27233 | * var use = require('use');
|
27234 | *
|
27235 | * // define a plugin
|
27236 | * function foo(app) {
|
27237 | * // do stuff
|
27238 | * }
|
27239 | *
|
27240 | * var app = function(){};
|
27241 | * use(app);
|
27242 | *
|
27243 | * // register plugins
|
27244 | * app.use(foo);
|
27245 | * app.use(bar);
|
27246 | * app.use(baz);
|
27247 | * ```
|
27248 | * @name .use
|
27249 | * @param {Function} `fn` plugin function to call
|
27250 | * @api public
|
27251 | */
|
27252 |
|
27253 | define$1(app, 'use', use);
|
27254 |
|
27255 | /**
|
27256 | * Run all plugins on `fns`. Any plugin that returns a function
|
27257 | * when called by `use` is pushed onto the `fns` array.
|
27258 | *
|
27259 | * ```js
|
27260 | * var config = {};
|
27261 | * app.run(config);
|
27262 | * ```
|
27263 | * @name .run
|
27264 | * @param {Object} `value` Object to be modified by plugins.
|
27265 | * @return {Object} Returns the object passed to `run`
|
27266 | * @api public
|
27267 | */
|
27268 |
|
27269 | define$1(app, 'run', function(val) {
|
27270 | if (!isObject$7(val)) return;
|
27271 |
|
27272 | if (!val.use || !val.run) {
|
27273 | define$1(val, prop, val[prop] || []);
|
27274 | define$1(val, 'use', use);
|
27275 | }
|
27276 |
|
27277 | if (!val[prop] || val[prop].indexOf(base) === -1) {
|
27278 | val.use(base);
|
27279 | }
|
27280 |
|
27281 | var self = this || app;
|
27282 | var fns = self[prop];
|
27283 | var len = fns.length;
|
27284 | var idx = -1;
|
27285 |
|
27286 | while (++idx < len) {
|
27287 | val.use(fns[idx]);
|
27288 | }
|
27289 | return val;
|
27290 | });
|
27291 |
|
27292 | /**
|
27293 | * Call plugin `fn`. If a function is returned push it into the
|
27294 | * `fns` array to be called by the `run` method.
|
27295 | */
|
27296 |
|
27297 | function use(type, fn, options) {
|
27298 | var offset = 1;
|
27299 |
|
27300 | if (typeof type === 'string' || Array.isArray(type)) {
|
27301 | fn = wrap(type, fn);
|
27302 | offset++;
|
27303 | } else {
|
27304 | options = fn;
|
27305 | fn = type;
|
27306 | }
|
27307 |
|
27308 | if (typeof fn !== 'function') {
|
27309 | throw new TypeError('expected a function');
|
27310 | }
|
27311 |
|
27312 | var self = this || app;
|
27313 | var fns = self[prop];
|
27314 |
|
27315 | var args = [].slice.call(arguments, offset);
|
27316 | args.unshift(self);
|
27317 |
|
27318 | if (typeof opts.hook === 'function') {
|
27319 | opts.hook.apply(self, args);
|
27320 | }
|
27321 |
|
27322 | var val = fn.apply(self, args);
|
27323 | if (typeof val === 'function' && fns.indexOf(val) === -1) {
|
27324 | fns.push(val);
|
27325 | }
|
27326 | return self;
|
27327 | }
|
27328 |
|
27329 | /**
|
27330 | * Wrap a named plugin function so that it's only called on objects of the
|
27331 | * given `type`
|
27332 | *
|
27333 | * @param {String} `type`
|
27334 | * @param {Function} `fn` Plugin function
|
27335 | * @return {Function}
|
27336 | */
|
27337 |
|
27338 | function wrap(type, fn) {
|
27339 | return function plugin() {
|
27340 | return this.type === type ? fn.apply(this, arguments) : plugin;
|
27341 | };
|
27342 | }
|
27343 |
|
27344 | return app;
|
27345 | };
|
27346 |
|
27347 | function isObject$7(val) {
|
27348 | return val && typeof val === 'object' && !Array.isArray(val);
|
27349 | }
|
27350 |
|
27351 | function define$1(obj, key, val) {
|
27352 | Object.defineProperty(obj, key, {
|
27353 | configurable: true,
|
27354 | writable: true,
|
27355 | value: val
|
27356 | });
|
27357 | }
|
27358 |
|
27359 | /**
|
27360 | * Helpers.
|
27361 | */
|
27362 |
|
27363 | var s = 1000;
|
27364 | var m = s * 60;
|
27365 | var h = m * 60;
|
27366 | var d = h * 24;
|
27367 | var y = d * 365.25;
|
27368 |
|
27369 | /**
|
27370 | * Parse or format the given `val`.
|
27371 | *
|
27372 | * Options:
|
27373 | *
|
27374 | * - `long` verbose formatting [false]
|
27375 | *
|
27376 | * @param {String|Number} val
|
27377 | * @param {Object} [options]
|
27378 | * @throws {Error} throw an error if val is not a non-empty string or a number
|
27379 | * @return {String|Number}
|
27380 | * @api public
|
27381 | */
|
27382 |
|
27383 | var ms = function(val, options) {
|
27384 | options = options || {};
|
27385 | var type = typeof val;
|
27386 | if (type === 'string' && val.length > 0) {
|
27387 | return parse(val);
|
27388 | } else if (type === 'number' && isNaN(val) === false) {
|
27389 | return options.long ? fmtLong(val) : fmtShort(val);
|
27390 | }
|
27391 | throw new Error(
|
27392 | 'val is not a non-empty string or a valid number. val=' +
|
27393 | JSON.stringify(val)
|
27394 | );
|
27395 | };
|
27396 |
|
27397 | /**
|
27398 | * Parse the given `str` and return milliseconds.
|
27399 | *
|
27400 | * @param {String} str
|
27401 | * @return {Number}
|
27402 | * @api private
|
27403 | */
|
27404 |
|
27405 | function parse(str) {
|
27406 | str = String(str);
|
27407 | if (str.length > 100) {
|
27408 | return;
|
27409 | }
|
27410 | var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
|
27411 | str
|
27412 | );
|
27413 | if (!match) {
|
27414 | return;
|
27415 | }
|
27416 | var n = parseFloat(match[1]);
|
27417 | var type = (match[2] || 'ms').toLowerCase();
|
27418 | switch (type) {
|
27419 | case 'years':
|
27420 | case 'year':
|
27421 | case 'yrs':
|
27422 | case 'yr':
|
27423 | case 'y':
|
27424 | return n * y;
|
27425 | case 'days':
|
27426 | case 'day':
|
27427 | case 'd':
|
27428 | return n * d;
|
27429 | case 'hours':
|
27430 | case 'hour':
|
27431 | case 'hrs':
|
27432 | case 'hr':
|
27433 | case 'h':
|
27434 | return n * h;
|
27435 | case 'minutes':
|
27436 | case 'minute':
|
27437 | case 'mins':
|
27438 | case 'min':
|
27439 | case 'm':
|
27440 | return n * m;
|
27441 | case 'seconds':
|
27442 | case 'second':
|
27443 | case 'secs':
|
27444 | case 'sec':
|
27445 | case 's':
|
27446 | return n * s;
|
27447 | case 'milliseconds':
|
27448 | case 'millisecond':
|
27449 | case 'msecs':
|
27450 | case 'msec':
|
27451 | case 'ms':
|
27452 | return n;
|
27453 | default:
|
27454 | return undefined;
|
27455 | }
|
27456 | }
|
27457 |
|
27458 | /**
|
27459 | * Short format for `ms`.
|
27460 | *
|
27461 | * @param {Number} ms
|
27462 | * @return {String}
|
27463 | * @api private
|
27464 | */
|
27465 |
|
27466 | function fmtShort(ms) {
|
27467 | if (ms >= d) {
|
27468 | return Math.round(ms / d) + 'd';
|
27469 | }
|
27470 | if (ms >= h) {
|
27471 | return Math.round(ms / h) + 'h';
|
27472 | }
|
27473 | if (ms >= m) {
|
27474 | return Math.round(ms / m) + 'm';
|
27475 | }
|
27476 | if (ms >= s) {
|
27477 | return Math.round(ms / s) + 's';
|
27478 | }
|
27479 | return ms + 'ms';
|
27480 | }
|
27481 |
|
27482 | /**
|
27483 | * Long format for `ms`.
|
27484 | *
|
27485 | * @param {Number} ms
|
27486 | * @return {String}
|
27487 | * @api private
|
27488 | */
|
27489 |
|
27490 | function fmtLong(ms) {
|
27491 | return plural(ms, d, 'day') ||
|
27492 | plural(ms, h, 'hour') ||
|
27493 | plural(ms, m, 'minute') ||
|
27494 | plural(ms, s, 'second') ||
|
27495 | ms + ' ms';
|
27496 | }
|
27497 |
|
27498 | /**
|
27499 | * Pluralization helper.
|
27500 | */
|
27501 |
|
27502 | function plural(ms, n, name) {
|
27503 | if (ms < n) {
|
27504 | return;
|
27505 | }
|
27506 | if (ms < n * 1.5) {
|
27507 | return Math.floor(ms / n) + ' ' + name;
|
27508 | }
|
27509 | return Math.ceil(ms / n) + ' ' + name + 's';
|
27510 | }
|
27511 |
|
27512 | var debug = createCommonjsModule(function (module, exports) {
|
27513 | /**
|
27514 | * This is the common logic for both the Node.js and web browser
|
27515 | * implementations of `debug()`.
|
27516 | *
|
27517 | * Expose `debug()` as the module.
|
27518 | */
|
27519 |
|
27520 | exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
|
27521 | exports.coerce = coerce;
|
27522 | exports.disable = disable;
|
27523 | exports.enable = enable;
|
27524 | exports.enabled = enabled;
|
27525 | exports.humanize = ms;
|
27526 |
|
27527 | /**
|
27528 | * The currently active debug mode names, and names to skip.
|
27529 | */
|
27530 |
|
27531 | exports.names = [];
|
27532 | exports.skips = [];
|
27533 |
|
27534 | /**
|
27535 | * Map of special "%n" handling functions, for the debug "format" argument.
|
27536 | *
|
27537 | * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
|
27538 | */
|
27539 |
|
27540 | exports.formatters = {};
|
27541 |
|
27542 | /**
|
27543 | * Previous log timestamp.
|
27544 | */
|
27545 |
|
27546 | var prevTime;
|
27547 |
|
27548 | /**
|
27549 | * Select a color.
|
27550 | * @param {String} namespace
|
27551 | * @return {Number}
|
27552 | * @api private
|
27553 | */
|
27554 |
|
27555 | function selectColor(namespace) {
|
27556 | var hash = 0, i;
|
27557 |
|
27558 | for (i in namespace) {
|
27559 | hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
|
27560 | hash |= 0; // Convert to 32bit integer
|
27561 | }
|
27562 |
|
27563 | return exports.colors[Math.abs(hash) % exports.colors.length];
|
27564 | }
|
27565 |
|
27566 | /**
|
27567 | * Create a debugger with the given `namespace`.
|
27568 | *
|
27569 | * @param {String} namespace
|
27570 | * @return {Function}
|
27571 | * @api public
|
27572 | */
|
27573 |
|
27574 | function createDebug(namespace) {
|
27575 |
|
27576 | function debug() {
|
27577 | // disabled?
|
27578 | if (!debug.enabled) return;
|
27579 |
|
27580 | var self = debug;
|
27581 |
|
27582 | // set `diff` timestamp
|
27583 | var curr = +new Date();
|
27584 | var ms = curr - (prevTime || curr);
|
27585 | self.diff = ms;
|
27586 | self.prev = prevTime;
|
27587 | self.curr = curr;
|
27588 | prevTime = curr;
|
27589 |
|
27590 | // turn the `arguments` into a proper Array
|
27591 | var args = new Array(arguments.length);
|
27592 | for (var i = 0; i < args.length; i++) {
|
27593 | args[i] = arguments[i];
|
27594 | }
|
27595 |
|
27596 | args[0] = exports.coerce(args[0]);
|
27597 |
|
27598 | if ('string' !== typeof args[0]) {
|
27599 | // anything else let's inspect with %O
|
27600 | args.unshift('%O');
|
27601 | }
|
27602 |
|
27603 | // apply any `formatters` transformations
|
27604 | var index = 0;
|
27605 | args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
|
27606 | // if we encounter an escaped % then don't increase the array index
|
27607 | if (match === '%%') return match;
|
27608 | index++;
|
27609 | var formatter = exports.formatters[format];
|
27610 | if ('function' === typeof formatter) {
|
27611 | var val = args[index];
|
27612 | match = formatter.call(self, val);
|
27613 |
|
27614 | // now we need to remove `args[index]` since it's inlined in the `format`
|
27615 | args.splice(index, 1);
|
27616 | index--;
|
27617 | }
|
27618 | return match;
|
27619 | });
|
27620 |
|
27621 | // apply env-specific formatting (colors, etc.)
|
27622 | exports.formatArgs.call(self, args);
|
27623 |
|
27624 | var logFn = debug.log || exports.log || console.log.bind(console);
|
27625 | logFn.apply(self, args);
|
27626 | }
|
27627 |
|
27628 | debug.namespace = namespace;
|
27629 | debug.enabled = exports.enabled(namespace);
|
27630 | debug.useColors = exports.useColors();
|
27631 | debug.color = selectColor(namespace);
|
27632 |
|
27633 | // env-specific initialization logic for debug instances
|
27634 | if ('function' === typeof exports.init) {
|
27635 | exports.init(debug);
|
27636 | }
|
27637 |
|
27638 | return debug;
|
27639 | }
|
27640 |
|
27641 | /**
|
27642 | * Enables a debug mode by namespaces. This can include modes
|
27643 | * separated by a colon and wildcards.
|
27644 | *
|
27645 | * @param {String} namespaces
|
27646 | * @api public
|
27647 | */
|
27648 |
|
27649 | function enable(namespaces) {
|
27650 | exports.save(namespaces);
|
27651 |
|
27652 | exports.names = [];
|
27653 | exports.skips = [];
|
27654 |
|
27655 | var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
|
27656 | var len = split.length;
|
27657 |
|
27658 | for (var i = 0; i < len; i++) {
|
27659 | if (!split[i]) continue; // ignore empty strings
|
27660 | namespaces = split[i].replace(/\*/g, '.*?');
|
27661 | if (namespaces[0] === '-') {
|
27662 | exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
|
27663 | } else {
|
27664 | exports.names.push(new RegExp('^' + namespaces + '$'));
|
27665 | }
|
27666 | }
|
27667 | }
|
27668 |
|
27669 | /**
|
27670 | * Disable debug output.
|
27671 | *
|
27672 | * @api public
|
27673 | */
|
27674 |
|
27675 | function disable() {
|
27676 | exports.enable('');
|
27677 | }
|
27678 |
|
27679 | /**
|
27680 | * Returns true if the given mode name is enabled, false otherwise.
|
27681 | *
|
27682 | * @param {String} name
|
27683 | * @return {Boolean}
|
27684 | * @api public
|
27685 | */
|
27686 |
|
27687 | function enabled(name) {
|
27688 | var i, len;
|
27689 | for (i = 0, len = exports.skips.length; i < len; i++) {
|
27690 | if (exports.skips[i].test(name)) {
|
27691 | return false;
|
27692 | }
|
27693 | }
|
27694 | for (i = 0, len = exports.names.length; i < len; i++) {
|
27695 | if (exports.names[i].test(name)) {
|
27696 | return true;
|
27697 | }
|
27698 | }
|
27699 | return false;
|
27700 | }
|
27701 |
|
27702 | /**
|
27703 | * Coerce `val`.
|
27704 | *
|
27705 | * @param {Mixed} val
|
27706 | * @return {Mixed}
|
27707 | * @api private
|
27708 | */
|
27709 |
|
27710 | function coerce(val) {
|
27711 | if (val instanceof Error) return val.stack || val.message;
|
27712 | return val;
|
27713 | }
|
27714 | });
|
27715 |
|
27716 | var browser = createCommonjsModule(function (module, exports) {
|
27717 | /**
|
27718 | * This is the web browser implementation of `debug()`.
|
27719 | *
|
27720 | * Expose `debug()` as the module.
|
27721 | */
|
27722 |
|
27723 | exports = module.exports = debug;
|
27724 | exports.log = log;
|
27725 | exports.formatArgs = formatArgs;
|
27726 | exports.save = save;
|
27727 | exports.load = load;
|
27728 | exports.useColors = useColors;
|
27729 | exports.storage = 'undefined' != typeof chrome
|
27730 | && 'undefined' != typeof chrome.storage
|
27731 | ? chrome.storage.local
|
27732 | : localstorage();
|
27733 |
|
27734 | /**
|
27735 | * Colors.
|
27736 | */
|
27737 |
|
27738 | exports.colors = [
|
27739 | 'lightseagreen',
|
27740 | 'forestgreen',
|
27741 | 'goldenrod',
|
27742 | 'dodgerblue',
|
27743 | 'darkorchid',
|
27744 | 'crimson'
|
27745 | ];
|
27746 |
|
27747 | /**
|
27748 | * Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
27749 | * and the Firebug extension (any Firefox version) are known
|
27750 | * to support "%c" CSS customizations.
|
27751 | *
|
27752 | * TODO: add a `localStorage` variable to explicitly enable/disable colors
|
27753 | */
|
27754 |
|
27755 | function useColors() {
|
27756 | // NB: In an Electron preload script, document will be defined but not fully
|
27757 | // initialized. Since we know we're in Chrome, we'll just detect this case
|
27758 | // explicitly
|
27759 | if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
|
27760 | return true;
|
27761 | }
|
27762 |
|
27763 | // is webkit? http://stackoverflow.com/a/16459606/376773
|
27764 | // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
|
27765 | return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
|
27766 | // is firebug? http://stackoverflow.com/a/398120/376773
|
27767 | (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
|
27768 | // is firefox >= v31?
|
27769 | // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
27770 | (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
|
27771 | // double check webkit in userAgent just in case we are in a worker
|
27772 | (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
|
27773 | }
|
27774 |
|
27775 | /**
|
27776 | * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
27777 | */
|
27778 |
|
27779 | exports.formatters.j = function(v) {
|
27780 | try {
|
27781 | return JSON.stringify(v);
|
27782 | } catch (err) {
|
27783 | return '[UnexpectedJSONParseError]: ' + err.message;
|
27784 | }
|
27785 | };
|
27786 |
|
27787 |
|
27788 | /**
|
27789 | * Colorize log arguments if enabled.
|
27790 | *
|
27791 | * @api public
|
27792 | */
|
27793 |
|
27794 | function formatArgs(args) {
|
27795 | var useColors = this.useColors;
|
27796 |
|
27797 | args[0] = (useColors ? '%c' : '')
|
27798 | + this.namespace
|
27799 | + (useColors ? ' %c' : ' ')
|
27800 | + args[0]
|
27801 | + (useColors ? '%c ' : ' ')
|
27802 | + '+' + exports.humanize(this.diff);
|
27803 |
|
27804 | if (!useColors) return;
|
27805 |
|
27806 | var c = 'color: ' + this.color;
|
27807 | args.splice(1, 0, c, 'color: inherit');
|
27808 |
|
27809 | // the final "%c" is somewhat tricky, because there could be other
|
27810 | // arguments passed either before or after the %c, so we need to
|
27811 | // figure out the correct index to insert the CSS into
|
27812 | var index = 0;
|
27813 | var lastC = 0;
|
27814 | args[0].replace(/%[a-zA-Z%]/g, function(match) {
|
27815 | if ('%%' === match) return;
|
27816 | index++;
|
27817 | if ('%c' === match) {
|
27818 | // we only are interested in the *last* %c
|
27819 | // (the user may have provided their own)
|
27820 | lastC = index;
|
27821 | }
|
27822 | });
|
27823 |
|
27824 | args.splice(lastC, 0, c);
|
27825 | }
|
27826 |
|
27827 | /**
|
27828 | * Invokes `console.log()` when available.
|
27829 | * No-op when `console.log` is not a "function".
|
27830 | *
|
27831 | * @api public
|
27832 | */
|
27833 |
|
27834 | function log() {
|
27835 | // this hackery is required for IE8/9, where
|
27836 | // the `console.log` function doesn't have 'apply'
|
27837 | return 'object' === typeof console
|
27838 | && console.log
|
27839 | && Function.prototype.apply.call(console.log, console, arguments);
|
27840 | }
|
27841 |
|
27842 | /**
|
27843 | * Save `namespaces`.
|
27844 | *
|
27845 | * @param {String} namespaces
|
27846 | * @api private
|
27847 | */
|
27848 |
|
27849 | function save(namespaces) {
|
27850 | try {
|
27851 | if (null == namespaces) {
|
27852 | exports.storage.removeItem('debug');
|
27853 | } else {
|
27854 | exports.storage.debug = namespaces;
|
27855 | }
|
27856 | } catch(e) {}
|
27857 | }
|
27858 |
|
27859 | /**
|
27860 | * Load `namespaces`.
|
27861 | *
|
27862 | * @return {String} returns the previously persisted debug modes
|
27863 | * @api private
|
27864 | */
|
27865 |
|
27866 | function load() {
|
27867 | var r;
|
27868 | try {
|
27869 | r = exports.storage.debug;
|
27870 | } catch(e) {}
|
27871 |
|
27872 | // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
|
27873 | if (!r && typeof process !== 'undefined' && 'env' in process) {
|
27874 | r = process.env.DEBUG;
|
27875 | }
|
27876 |
|
27877 | return r;
|
27878 | }
|
27879 |
|
27880 | /**
|
27881 | * Enable namespaces listed in `localStorage.debug` initially.
|
27882 | */
|
27883 |
|
27884 | exports.enable(load());
|
27885 |
|
27886 | /**
|
27887 | * Localstorage attempts to return the localstorage.
|
27888 | *
|
27889 | * This is necessary because safari throws
|
27890 | * when a user disables cookies/localstorage
|
27891 | * and you attempt to access it.
|
27892 | *
|
27893 | * @return {LocalStorage}
|
27894 | * @api private
|
27895 | */
|
27896 |
|
27897 | function localstorage() {
|
27898 | try {
|
27899 | return window.localStorage;
|
27900 | } catch (e) {}
|
27901 | }
|
27902 | });
|
27903 |
|
27904 | var node = createCommonjsModule(function (module, exports) {
|
27905 | /**
|
27906 | * Module dependencies.
|
27907 | */
|
27908 |
|
27909 |
|
27910 |
|
27911 |
|
27912 | /**
|
27913 | * This is the Node.js implementation of `debug()`.
|
27914 | *
|
27915 | * Expose `debug()` as the module.
|
27916 | */
|
27917 |
|
27918 | exports = module.exports = debug;
|
27919 | exports.init = init;
|
27920 | exports.log = log;
|
27921 | exports.formatArgs = formatArgs;
|
27922 | exports.save = save;
|
27923 | exports.load = load;
|
27924 | exports.useColors = useColors;
|
27925 |
|
27926 | /**
|
27927 | * Colors.
|
27928 | */
|
27929 |
|
27930 | exports.colors = [6, 2, 3, 4, 5, 1];
|
27931 |
|
27932 | /**
|
27933 | * Build up the default `inspectOpts` object from the environment variables.
|
27934 | *
|
27935 | * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
|
27936 | */
|
27937 |
|
27938 | exports.inspectOpts = Object.keys(process.env).filter(function (key) {
|
27939 | return /^debug_/i.test(key);
|
27940 | }).reduce(function (obj, key) {
|
27941 | // camel-case
|
27942 | var prop = key
|
27943 | .substring(6)
|
27944 | .toLowerCase()
|
27945 | .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
|
27946 |
|
27947 | // coerce string value into JS value
|
27948 | var val = process.env[key];
|
27949 | if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
|
27950 | else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
|
27951 | else if (val === 'null') val = null;
|
27952 | else val = Number(val);
|
27953 |
|
27954 | obj[prop] = val;
|
27955 | return obj;
|
27956 | }, {});
|
27957 |
|
27958 | /**
|
27959 | * The file descriptor to write the `debug()` calls to.
|
27960 | * Set the `DEBUG_FD` env variable to override with another value. i.e.:
|
27961 | *
|
27962 | * $ DEBUG_FD=3 node script.js 3>debug.log
|
27963 | */
|
27964 |
|
27965 | var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
|
27966 |
|
27967 | if (1 !== fd && 2 !== fd) {
|
27968 | 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)')();
|
27969 | }
|
27970 |
|
27971 | var stream = 1 === fd ? process.stdout :
|
27972 | 2 === fd ? process.stderr :
|
27973 | createWritableStdioStream(fd);
|
27974 |
|
27975 | /**
|
27976 | * Is stdout a TTY? Colored output is enabled when `true`.
|
27977 | */
|
27978 |
|
27979 | function useColors() {
|
27980 | return 'colors' in exports.inspectOpts
|
27981 | ? Boolean(exports.inspectOpts.colors)
|
27982 | : tty.isatty(fd);
|
27983 | }
|
27984 |
|
27985 | /**
|
27986 | * Map %o to `util.inspect()`, all on a single line.
|
27987 | */
|
27988 |
|
27989 | exports.formatters.o = function(v) {
|
27990 | this.inspectOpts.colors = this.useColors;
|
27991 | return util$2.inspect(v, this.inspectOpts)
|
27992 | .split('\n').map(function(str) {
|
27993 | return str.trim()
|
27994 | }).join(' ');
|
27995 | };
|
27996 |
|
27997 | /**
|
27998 | * Map %o to `util.inspect()`, allowing multiple lines if needed.
|
27999 | */
|
28000 |
|
28001 | exports.formatters.O = function(v) {
|
28002 | this.inspectOpts.colors = this.useColors;
|
28003 | return util$2.inspect(v, this.inspectOpts);
|
28004 | };
|
28005 |
|
28006 | /**
|
28007 | * Adds ANSI color escape codes if enabled.
|
28008 | *
|
28009 | * @api public
|
28010 | */
|
28011 |
|
28012 | function formatArgs(args) {
|
28013 | var name = this.namespace;
|
28014 | var useColors = this.useColors;
|
28015 |
|
28016 | if (useColors) {
|
28017 | var c = this.color;
|
28018 | var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
|
28019 |
|
28020 | args[0] = prefix + args[0].split('\n').join('\n' + prefix);
|
28021 | args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
|
28022 | } else {
|
28023 | args[0] = new Date().toUTCString()
|
28024 | + ' ' + name + ' ' + args[0];
|
28025 | }
|
28026 | }
|
28027 |
|
28028 | /**
|
28029 | * Invokes `util.format()` with the specified arguments and writes to `stream`.
|
28030 | */
|
28031 |
|
28032 | function log() {
|
28033 | return stream.write(util$2.format.apply(util$2, arguments) + '\n');
|
28034 | }
|
28035 |
|
28036 | /**
|
28037 | * Save `namespaces`.
|
28038 | *
|
28039 | * @param {String} namespaces
|
28040 | * @api private
|
28041 | */
|
28042 |
|
28043 | function save(namespaces) {
|
28044 | if (null == namespaces) {
|
28045 | // If you set a process.env field to null or undefined, it gets cast to the
|
28046 | // string 'null' or 'undefined'. Just delete instead.
|
28047 | delete process.env.DEBUG;
|
28048 | } else {
|
28049 | process.env.DEBUG = namespaces;
|
28050 | }
|
28051 | }
|
28052 |
|
28053 | /**
|
28054 | * Load `namespaces`.
|
28055 | *
|
28056 | * @return {String} returns the previously persisted debug modes
|
28057 | * @api private
|
28058 | */
|
28059 |
|
28060 | function load() {
|
28061 | return process.env.DEBUG;
|
28062 | }
|
28063 |
|
28064 | /**
|
28065 | * Copied from `node/src/node.js`.
|
28066 | *
|
28067 | * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
|
28068 | * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
|
28069 | */
|
28070 |
|
28071 | function createWritableStdioStream (fd) {
|
28072 | var stream;
|
28073 | var tty_wrap = process.binding('tty_wrap');
|
28074 |
|
28075 | // Note stream._type is used for test-module-load-list.js
|
28076 |
|
28077 | switch (tty_wrap.guessHandleType(fd)) {
|
28078 | case 'TTY':
|
28079 | stream = new tty.WriteStream(fd);
|
28080 | stream._type = 'tty';
|
28081 |
|
28082 | // Hack to have stream not keep the event loop alive.
|
28083 | // See https://github.com/joyent/node/issues/1726
|
28084 | if (stream._handle && stream._handle.unref) {
|
28085 | stream._handle.unref();
|
28086 | }
|
28087 | break;
|
28088 |
|
28089 | case 'FILE':
|
28090 | var fs = fs__default;
|
28091 | stream = new fs.SyncWriteStream(fd, { autoClose: false });
|
28092 | stream._type = 'fs';
|
28093 | break;
|
28094 |
|
28095 | case 'PIPE':
|
28096 | case 'TCP':
|
28097 | var net$1 = net;
|
28098 | stream = new net$1.Socket({
|
28099 | fd: fd,
|
28100 | readable: false,
|
28101 | writable: true
|
28102 | });
|
28103 |
|
28104 | // FIXME Should probably have an option in net.Socket to create a
|
28105 | // stream from an existing fd which is writable only. But for now
|
28106 | // we'll just add this hack and set the `readable` member to false.
|
28107 | // Test: ./node test/fixtures/echo.js < /etc/passwd
|
28108 | stream.readable = false;
|
28109 | stream.read = null;
|
28110 | stream._type = 'pipe';
|
28111 |
|
28112 | // FIXME Hack to have stream not keep the event loop alive.
|
28113 | // See https://github.com/joyent/node/issues/1726
|
28114 | if (stream._handle && stream._handle.unref) {
|
28115 | stream._handle.unref();
|
28116 | }
|
28117 | break;
|
28118 |
|
28119 | default:
|
28120 | // Probably an error on in uv_guess_handle()
|
28121 | throw new Error('Implement me. Unknown stream file type!');
|
28122 | }
|
28123 |
|
28124 | // For supporting legacy API we put the FD here.
|
28125 | stream.fd = fd;
|
28126 |
|
28127 | stream._isStdio = true;
|
28128 |
|
28129 | return stream;
|
28130 | }
|
28131 |
|
28132 | /**
|
28133 | * Init logic for `debug` instances.
|
28134 | *
|
28135 | * Create a new `inspectOpts` object in case `useColors` is set
|
28136 | * differently for a particular `debug` instance.
|
28137 | */
|
28138 |
|
28139 | function init (debug) {
|
28140 | debug.inspectOpts = {};
|
28141 |
|
28142 | var keys = Object.keys(exports.inspectOpts);
|
28143 | for (var i = 0; i < keys.length; i++) {
|
28144 | debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
|
28145 | }
|
28146 | }
|
28147 |
|
28148 | /**
|
28149 | * Enable namespaces listed in `process.env.DEBUG` initially.
|
28150 | */
|
28151 |
|
28152 | exports.enable(load());
|
28153 | });
|
28154 |
|
28155 | var src = createCommonjsModule(function (module) {
|
28156 | /**
|
28157 | * Detect Electron renderer process, which is node, but we should
|
28158 | * treat as a browser.
|
28159 | */
|
28160 |
|
28161 | if (typeof process !== 'undefined' && process.type === 'renderer') {
|
28162 | module.exports = browser;
|
28163 | } else {
|
28164 | module.exports = node;
|
28165 | }
|
28166 | });
|
28167 |
|
28168 | var extendShallow$5 = function extend(o/*, objects*/) {
|
28169 | if (!isExtendable$1(o)) { o = {}; }
|
28170 |
|
28171 | var len = arguments.length;
|
28172 | for (var i = 1; i < len; i++) {
|
28173 | var obj = arguments[i];
|
28174 |
|
28175 | if (isExtendable$1(obj)) {
|
28176 | assign$5(o, obj);
|
28177 | }
|
28178 | }
|
28179 | return o;
|
28180 | };
|
28181 |
|
28182 | function assign$5(a, b) {
|
28183 | for (var key in b) {
|
28184 | if (hasOwn$5(b, key)) {
|
28185 | a[key] = b[key];
|
28186 | }
|
28187 | }
|
28188 | }
|
28189 |
|
28190 | /**
|
28191 | * Returns true if the given `key` is an own property of `obj`.
|
28192 | */
|
28193 |
|
28194 | function hasOwn$5(obj, key) {
|
28195 | return Object.prototype.hasOwnProperty.call(obj, key);
|
28196 | }
|
28197 |
|
28198 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
28199 | /*
|
28200 | * Copyright 2011 Mozilla Foundation and contributors
|
28201 | * Licensed under the New BSD license. See LICENSE or:
|
28202 | * http://opensource.org/licenses/BSD-3-Clause
|
28203 | */
|
28204 |
|
28205 | var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
|
28206 |
|
28207 | /**
|
28208 | * Encode an integer in the range of 0 to 63 to a single base 64 digit.
|
28209 | */
|
28210 | var encode$1 = function (number) {
|
28211 | if (0 <= number && number < intToCharMap.length) {
|
28212 | return intToCharMap[number];
|
28213 | }
|
28214 | throw new TypeError("Must be between 0 and 63: " + number);
|
28215 | };
|
28216 |
|
28217 | /**
|
28218 | * Decode a single base 64 character code digit to an integer. Returns -1 on
|
28219 | * failure.
|
28220 | */
|
28221 | var decode$1 = function (charCode) {
|
28222 | var bigA = 65; // 'A'
|
28223 | var bigZ = 90; // 'Z'
|
28224 |
|
28225 | var littleA = 97; // 'a'
|
28226 | var littleZ = 122; // 'z'
|
28227 |
|
28228 | var zero = 48; // '0'
|
28229 | var nine = 57; // '9'
|
28230 |
|
28231 | var plus = 43; // '+'
|
28232 | var slash = 47; // '/'
|
28233 |
|
28234 | var littleOffset = 26;
|
28235 | var numberOffset = 52;
|
28236 |
|
28237 | // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
28238 | if (bigA <= charCode && charCode <= bigZ) {
|
28239 | return (charCode - bigA);
|
28240 | }
|
28241 |
|
28242 | // 26 - 51: abcdefghijklmnopqrstuvwxyz
|
28243 | if (littleA <= charCode && charCode <= littleZ) {
|
28244 | return (charCode - littleA + littleOffset);
|
28245 | }
|
28246 |
|
28247 | // 52 - 61: 0123456789
|
28248 | if (zero <= charCode && charCode <= nine) {
|
28249 | return (charCode - zero + numberOffset);
|
28250 | }
|
28251 |
|
28252 | // 62: +
|
28253 | if (charCode == plus) {
|
28254 | return 62;
|
28255 | }
|
28256 |
|
28257 | // 63: /
|
28258 | if (charCode == slash) {
|
28259 | return 63;
|
28260 | }
|
28261 |
|
28262 | // Invalid base64 digit.
|
28263 | return -1;
|
28264 | };
|
28265 |
|
28266 | var base64 = {
|
28267 | encode: encode$1,
|
28268 | decode: decode$1
|
28269 | };
|
28270 |
|
28271 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
28272 | /*
|
28273 | * Copyright 2011 Mozilla Foundation and contributors
|
28274 | * Licensed under the New BSD license. See LICENSE or:
|
28275 | * http://opensource.org/licenses/BSD-3-Clause
|
28276 | *
|
28277 | * Based on the Base 64 VLQ implementation in Closure Compiler:
|
28278 | * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
|
28279 | *
|
28280 | * Copyright 2011 The Closure Compiler Authors. All rights reserved.
|
28281 | * Redistribution and use in source and binary forms, with or without
|
28282 | * modification, are permitted provided that the following conditions are
|
28283 | * met:
|
28284 | *
|
28285 | * * Redistributions of source code must retain the above copyright
|
28286 | * notice, this list of conditions and the following disclaimer.
|
28287 | * * Redistributions in binary form must reproduce the above
|
28288 | * copyright notice, this list of conditions and the following
|
28289 | * disclaimer in the documentation and/or other materials provided
|
28290 | * with the distribution.
|
28291 | * * Neither the name of Google Inc. nor the names of its
|
28292 | * contributors may be used to endorse or promote products derived
|
28293 | * from this software without specific prior written permission.
|
28294 | *
|
28295 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
28296 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
28297 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
28298 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
28299 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
28300 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
28301 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
28302 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
28303 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
28304 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
28305 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
28306 | */
|
28307 |
|
28308 |
|
28309 |
|
28310 | // A single base 64 digit can contain 6 bits of data. For the base 64 variable
|
28311 | // length quantities we use in the source map spec, the first bit is the sign,
|
28312 | // the next four bits are the actual value, and the 6th bit is the
|
28313 | // continuation bit. The continuation bit tells us whether there are more
|
28314 | // digits in this value following this digit.
|
28315 | //
|
28316 | // Continuation
|
28317 | // | Sign
|
28318 | // | |
|
28319 | // V V
|
28320 | // 101011
|
28321 |
|
28322 | var VLQ_BASE_SHIFT = 5;
|
28323 |
|
28324 | // binary: 100000
|
28325 | var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
|
28326 |
|
28327 | // binary: 011111
|
28328 | var VLQ_BASE_MASK = VLQ_BASE - 1;
|
28329 |
|
28330 | // binary: 100000
|
28331 | var VLQ_CONTINUATION_BIT = VLQ_BASE;
|
28332 |
|
28333 | /**
|
28334 | * Converts from a two-complement value to a value where the sign bit is
|
28335 | * placed in the least significant bit. For example, as decimals:
|
28336 | * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
|
28337 | * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
|
28338 | */
|
28339 | function toVLQSigned(aValue) {
|
28340 | return aValue < 0
|
28341 | ? ((-aValue) << 1) + 1
|
28342 | : (aValue << 1) + 0;
|
28343 | }
|
28344 |
|
28345 | /**
|
28346 | * Converts to a two-complement value from a value where the sign bit is
|
28347 | * placed in the least significant bit. For example, as decimals:
|
28348 | * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
|
28349 | * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
|
28350 | */
|
28351 | function fromVLQSigned(aValue) {
|
28352 | var isNegative = (aValue & 1) === 1;
|
28353 | var shifted = aValue >> 1;
|
28354 | return isNegative
|
28355 | ? -shifted
|
28356 | : shifted;
|
28357 | }
|
28358 |
|
28359 | /**
|
28360 | * Returns the base 64 VLQ encoded value.
|
28361 | */
|
28362 | var encode$2 = function base64VLQ_encode(aValue) {
|
28363 | var encoded = "";
|
28364 | var digit;
|
28365 |
|
28366 | var vlq = toVLQSigned(aValue);
|
28367 |
|
28368 | do {
|
28369 | digit = vlq & VLQ_BASE_MASK;
|
28370 | vlq >>>= VLQ_BASE_SHIFT;
|
28371 | if (vlq > 0) {
|
28372 | // There are still more digits in this value, so we must make sure the
|
28373 | // continuation bit is marked.
|
28374 | digit |= VLQ_CONTINUATION_BIT;
|
28375 | }
|
28376 | encoded += base64.encode(digit);
|
28377 | } while (vlq > 0);
|
28378 |
|
28379 | return encoded;
|
28380 | };
|
28381 |
|
28382 | /**
|
28383 | * Decodes the next base 64 VLQ value from the given string and returns the
|
28384 | * value and the rest of the string via the out parameter.
|
28385 | */
|
28386 | var decode$2 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
|
28387 | var strLen = aStr.length;
|
28388 | var result = 0;
|
28389 | var shift = 0;
|
28390 | var continuation, digit;
|
28391 |
|
28392 | do {
|
28393 | if (aIndex >= strLen) {
|
28394 | throw new Error("Expected more digits in base 64 VLQ value.");
|
28395 | }
|
28396 |
|
28397 | digit = base64.decode(aStr.charCodeAt(aIndex++));
|
28398 | if (digit === -1) {
|
28399 | throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
|
28400 | }
|
28401 |
|
28402 | continuation = !!(digit & VLQ_CONTINUATION_BIT);
|
28403 | digit &= VLQ_BASE_MASK;
|
28404 | result = result + (digit << shift);
|
28405 | shift += VLQ_BASE_SHIFT;
|
28406 | } while (continuation);
|
28407 |
|
28408 | aOutParam.value = fromVLQSigned(result);
|
28409 | aOutParam.rest = aIndex;
|
28410 | };
|
28411 |
|
28412 | var base64Vlq = {
|
28413 | encode: encode$2,
|
28414 | decode: decode$2
|
28415 | };
|
28416 |
|
28417 | var util$1 = createCommonjsModule(function (module, exports) {
|
28418 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
28419 | /*
|
28420 | * Copyright 2011 Mozilla Foundation and contributors
|
28421 | * Licensed under the New BSD license. See LICENSE or:
|
28422 | * http://opensource.org/licenses/BSD-3-Clause
|
28423 | */
|
28424 |
|
28425 | /**
|
28426 | * This is a helper function for getting values from parameter/options
|
28427 | * objects.
|
28428 | *
|
28429 | * @param args The object we are extracting values from
|
28430 | * @param name The name of the property we are getting.
|
28431 | * @param defaultValue An optional value to return if the property is missing
|
28432 | * from the object. If this is not specified and the property is missing, an
|
28433 | * error will be thrown.
|
28434 | */
|
28435 | function getArg(aArgs, aName, aDefaultValue) {
|
28436 | if (aName in aArgs) {
|
28437 | return aArgs[aName];
|
28438 | } else if (arguments.length === 3) {
|
28439 | return aDefaultValue;
|
28440 | } else {
|
28441 | throw new Error('"' + aName + '" is a required argument.');
|
28442 | }
|
28443 | }
|
28444 | exports.getArg = getArg;
|
28445 |
|
28446 | var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
|
28447 | var dataUrlRegexp = /^data:.+\,.+$/;
|
28448 |
|
28449 | function urlParse(aUrl) {
|
28450 | var match = aUrl.match(urlRegexp);
|
28451 | if (!match) {
|
28452 | return null;
|
28453 | }
|
28454 | return {
|
28455 | scheme: match[1],
|
28456 | auth: match[2],
|
28457 | host: match[3],
|
28458 | port: match[4],
|
28459 | path: match[5]
|
28460 | };
|
28461 | }
|
28462 | exports.urlParse = urlParse;
|
28463 |
|
28464 | function urlGenerate(aParsedUrl) {
|
28465 | var url = '';
|
28466 | if (aParsedUrl.scheme) {
|
28467 | url += aParsedUrl.scheme + ':';
|
28468 | }
|
28469 | url += '//';
|
28470 | if (aParsedUrl.auth) {
|
28471 | url += aParsedUrl.auth + '@';
|
28472 | }
|
28473 | if (aParsedUrl.host) {
|
28474 | url += aParsedUrl.host;
|
28475 | }
|
28476 | if (aParsedUrl.port) {
|
28477 | url += ":" + aParsedUrl.port;
|
28478 | }
|
28479 | if (aParsedUrl.path) {
|
28480 | url += aParsedUrl.path;
|
28481 | }
|
28482 | return url;
|
28483 | }
|
28484 | exports.urlGenerate = urlGenerate;
|
28485 |
|
28486 | /**
|
28487 | * Normalizes a path, or the path portion of a URL:
|
28488 | *
|
28489 | * - Replaces consecutive slashes with one slash.
|
28490 | * - Removes unnecessary '.' parts.
|
28491 | * - Removes unnecessary '<dir>/..' parts.
|
28492 | *
|
28493 | * Based on code in the Node.js 'path' core module.
|
28494 | *
|
28495 | * @param aPath The path or url to normalize.
|
28496 | */
|
28497 | function normalize(aPath) {
|
28498 | var path = aPath;
|
28499 | var url = urlParse(aPath);
|
28500 | if (url) {
|
28501 | if (!url.path) {
|
28502 | return aPath;
|
28503 | }
|
28504 | path = url.path;
|
28505 | }
|
28506 | var isAbsolute = exports.isAbsolute(path);
|
28507 |
|
28508 | var parts = path.split(/\/+/);
|
28509 | for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
|
28510 | part = parts[i];
|
28511 | if (part === '.') {
|
28512 | parts.splice(i, 1);
|
28513 | } else if (part === '..') {
|
28514 | up++;
|
28515 | } else if (up > 0) {
|
28516 | if (part === '') {
|
28517 | // The first part is blank if the path is absolute. Trying to go
|
28518 | // above the root is a no-op. Therefore we can remove all '..' parts
|
28519 | // directly after the root.
|
28520 | parts.splice(i + 1, up);
|
28521 | up = 0;
|
28522 | } else {
|
28523 | parts.splice(i, 2);
|
28524 | up--;
|
28525 | }
|
28526 | }
|
28527 | }
|
28528 | path = parts.join('/');
|
28529 |
|
28530 | if (path === '') {
|
28531 | path = isAbsolute ? '/' : '.';
|
28532 | }
|
28533 |
|
28534 | if (url) {
|
28535 | url.path = path;
|
28536 | return urlGenerate(url);
|
28537 | }
|
28538 | return path;
|
28539 | }
|
28540 | exports.normalize = normalize;
|
28541 |
|
28542 | /**
|
28543 | * Joins two paths/URLs.
|
28544 | *
|
28545 | * @param aRoot The root path or URL.
|
28546 | * @param aPath The path or URL to be joined with the root.
|
28547 | *
|
28548 | * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
|
28549 | * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
|
28550 | * first.
|
28551 | * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
|
28552 | * is updated with the result and aRoot is returned. Otherwise the result
|
28553 | * is returned.
|
28554 | * - If aPath is absolute, the result is aPath.
|
28555 | * - Otherwise the two paths are joined with a slash.
|
28556 | * - Joining for example 'http://' and 'www.example.com' is also supported.
|
28557 | */
|
28558 | function join(aRoot, aPath) {
|
28559 | if (aRoot === "") {
|
28560 | aRoot = ".";
|
28561 | }
|
28562 | if (aPath === "") {
|
28563 | aPath = ".";
|
28564 | }
|
28565 | var aPathUrl = urlParse(aPath);
|
28566 | var aRootUrl = urlParse(aRoot);
|
28567 | if (aRootUrl) {
|
28568 | aRoot = aRootUrl.path || '/';
|
28569 | }
|
28570 |
|
28571 | // `join(foo, '//www.example.org')`
|
28572 | if (aPathUrl && !aPathUrl.scheme) {
|
28573 | if (aRootUrl) {
|
28574 | aPathUrl.scheme = aRootUrl.scheme;
|
28575 | }
|
28576 | return urlGenerate(aPathUrl);
|
28577 | }
|
28578 |
|
28579 | if (aPathUrl || aPath.match(dataUrlRegexp)) {
|
28580 | return aPath;
|
28581 | }
|
28582 |
|
28583 | // `join('http://', 'www.example.com')`
|
28584 | if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
|
28585 | aRootUrl.host = aPath;
|
28586 | return urlGenerate(aRootUrl);
|
28587 | }
|
28588 |
|
28589 | var joined = aPath.charAt(0) === '/'
|
28590 | ? aPath
|
28591 | : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
|
28592 |
|
28593 | if (aRootUrl) {
|
28594 | aRootUrl.path = joined;
|
28595 | return urlGenerate(aRootUrl);
|
28596 | }
|
28597 | return joined;
|
28598 | }
|
28599 | exports.join = join;
|
28600 |
|
28601 | exports.isAbsolute = function (aPath) {
|
28602 | return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
|
28603 | };
|
28604 |
|
28605 | /**
|
28606 | * Make a path relative to a URL or another path.
|
28607 | *
|
28608 | * @param aRoot The root path or URL.
|
28609 | * @param aPath The path or URL to be made relative to aRoot.
|
28610 | */
|
28611 | function relative(aRoot, aPath) {
|
28612 | if (aRoot === "") {
|
28613 | aRoot = ".";
|
28614 | }
|
28615 |
|
28616 | aRoot = aRoot.replace(/\/$/, '');
|
28617 |
|
28618 | // It is possible for the path to be above the root. In this case, simply
|
28619 | // checking whether the root is a prefix of the path won't work. Instead, we
|
28620 | // need to remove components from the root one by one, until either we find
|
28621 | // a prefix that fits, or we run out of components to remove.
|
28622 | var level = 0;
|
28623 | while (aPath.indexOf(aRoot + '/') !== 0) {
|
28624 | var index = aRoot.lastIndexOf("/");
|
28625 | if (index < 0) {
|
28626 | return aPath;
|
28627 | }
|
28628 |
|
28629 | // If the only part of the root that is left is the scheme (i.e. http://,
|
28630 | // file:///, etc.), one or more slashes (/), or simply nothing at all, we
|
28631 | // have exhausted all components, so the path is not relative to the root.
|
28632 | aRoot = aRoot.slice(0, index);
|
28633 | if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
|
28634 | return aPath;
|
28635 | }
|
28636 |
|
28637 | ++level;
|
28638 | }
|
28639 |
|
28640 | // Make sure we add a "../" for each component we removed from the root.
|
28641 | return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
|
28642 | }
|
28643 | exports.relative = relative;
|
28644 |
|
28645 | var supportsNullProto = (function () {
|
28646 | var obj = Object.create(null);
|
28647 | return !('__proto__' in obj);
|
28648 | }());
|
28649 |
|
28650 | function identity (s) {
|
28651 | return s;
|
28652 | }
|
28653 |
|
28654 | /**
|
28655 | * Because behavior goes wacky when you set `__proto__` on objects, we
|
28656 | * have to prefix all the strings in our set with an arbitrary character.
|
28657 | *
|
28658 | * See https://github.com/mozilla/source-map/pull/31 and
|
28659 | * https://github.com/mozilla/source-map/issues/30
|
28660 | *
|
28661 | * @param String aStr
|
28662 | */
|
28663 | function toSetString(aStr) {
|
28664 | if (isProtoString(aStr)) {
|
28665 | return '$' + aStr;
|
28666 | }
|
28667 |
|
28668 | return aStr;
|
28669 | }
|
28670 | exports.toSetString = supportsNullProto ? identity : toSetString;
|
28671 |
|
28672 | function fromSetString(aStr) {
|
28673 | if (isProtoString(aStr)) {
|
28674 | return aStr.slice(1);
|
28675 | }
|
28676 |
|
28677 | return aStr;
|
28678 | }
|
28679 | exports.fromSetString = supportsNullProto ? identity : fromSetString;
|
28680 |
|
28681 | function isProtoString(s) {
|
28682 | if (!s) {
|
28683 | return false;
|
28684 | }
|
28685 |
|
28686 | var length = s.length;
|
28687 |
|
28688 | if (length < 9 /* "__proto__".length */) {
|
28689 | return false;
|
28690 | }
|
28691 |
|
28692 | if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
|
28693 | s.charCodeAt(length - 2) !== 95 /* '_' */ ||
|
28694 | s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
|
28695 | s.charCodeAt(length - 4) !== 116 /* 't' */ ||
|
28696 | s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
|
28697 | s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
|
28698 | s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
|
28699 | s.charCodeAt(length - 8) !== 95 /* '_' */ ||
|
28700 | s.charCodeAt(length - 9) !== 95 /* '_' */) {
|
28701 | return false;
|
28702 | }
|
28703 |
|
28704 | for (var i = length - 10; i >= 0; i--) {
|
28705 | if (s.charCodeAt(i) !== 36 /* '$' */) {
|
28706 | return false;
|
28707 | }
|
28708 | }
|
28709 |
|
28710 | return true;
|
28711 | }
|
28712 |
|
28713 | /**
|
28714 | * Comparator between two mappings where the original positions are compared.
|
28715 | *
|
28716 | * Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
28717 | * mappings with the same original source/line/column, but different generated
|
28718 | * line and column the same. Useful when searching for a mapping with a
|
28719 | * stubbed out mapping.
|
28720 | */
|
28721 | function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
|
28722 | var cmp = mappingA.source - mappingB.source;
|
28723 | if (cmp !== 0) {
|
28724 | return cmp;
|
28725 | }
|
28726 |
|
28727 | cmp = mappingA.originalLine - mappingB.originalLine;
|
28728 | if (cmp !== 0) {
|
28729 | return cmp;
|
28730 | }
|
28731 |
|
28732 | cmp = mappingA.originalColumn - mappingB.originalColumn;
|
28733 | if (cmp !== 0 || onlyCompareOriginal) {
|
28734 | return cmp;
|
28735 | }
|
28736 |
|
28737 | cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
28738 | if (cmp !== 0) {
|
28739 | return cmp;
|
28740 | }
|
28741 |
|
28742 | cmp = mappingA.generatedLine - mappingB.generatedLine;
|
28743 | if (cmp !== 0) {
|
28744 | return cmp;
|
28745 | }
|
28746 |
|
28747 | return mappingA.name - mappingB.name;
|
28748 | }
|
28749 | exports.compareByOriginalPositions = compareByOriginalPositions;
|
28750 |
|
28751 | /**
|
28752 | * Comparator between two mappings with deflated source and name indices where
|
28753 | * the generated positions are compared.
|
28754 | *
|
28755 | * Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
28756 | * mappings with the same generated line and column, but different
|
28757 | * source/name/original line and column the same. Useful when searching for a
|
28758 | * mapping with a stubbed out mapping.
|
28759 | */
|
28760 | function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
|
28761 | var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
28762 | if (cmp !== 0) {
|
28763 | return cmp;
|
28764 | }
|
28765 |
|
28766 | cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
28767 | if (cmp !== 0 || onlyCompareGenerated) {
|
28768 | return cmp;
|
28769 | }
|
28770 |
|
28771 | cmp = mappingA.source - mappingB.source;
|
28772 | if (cmp !== 0) {
|
28773 | return cmp;
|
28774 | }
|
28775 |
|
28776 | cmp = mappingA.originalLine - mappingB.originalLine;
|
28777 | if (cmp !== 0) {
|
28778 | return cmp;
|
28779 | }
|
28780 |
|
28781 | cmp = mappingA.originalColumn - mappingB.originalColumn;
|
28782 | if (cmp !== 0) {
|
28783 | return cmp;
|
28784 | }
|
28785 |
|
28786 | return mappingA.name - mappingB.name;
|
28787 | }
|
28788 | exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
|
28789 |
|
28790 | function strcmp(aStr1, aStr2) {
|
28791 | if (aStr1 === aStr2) {
|
28792 | return 0;
|
28793 | }
|
28794 |
|
28795 | if (aStr1 > aStr2) {
|
28796 | return 1;
|
28797 | }
|
28798 |
|
28799 | return -1;
|
28800 | }
|
28801 |
|
28802 | /**
|
28803 | * Comparator between two mappings with inflated source and name strings where
|
28804 | * the generated positions are compared.
|
28805 | */
|
28806 | function compareByGeneratedPositionsInflated(mappingA, mappingB) {
|
28807 | var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
28808 | if (cmp !== 0) {
|
28809 | return cmp;
|
28810 | }
|
28811 |
|
28812 | cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
28813 | if (cmp !== 0) {
|
28814 | return cmp;
|
28815 | }
|
28816 |
|
28817 | cmp = strcmp(mappingA.source, mappingB.source);
|
28818 | if (cmp !== 0) {
|
28819 | return cmp;
|
28820 | }
|
28821 |
|
28822 | cmp = mappingA.originalLine - mappingB.originalLine;
|
28823 | if (cmp !== 0) {
|
28824 | return cmp;
|
28825 | }
|
28826 |
|
28827 | cmp = mappingA.originalColumn - mappingB.originalColumn;
|
28828 | if (cmp !== 0) {
|
28829 | return cmp;
|
28830 | }
|
28831 |
|
28832 | return strcmp(mappingA.name, mappingB.name);
|
28833 | }
|
28834 | exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
|
28835 | });
|
28836 |
|
28837 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
28838 | /*
|
28839 | * Copyright 2011 Mozilla Foundation and contributors
|
28840 | * Licensed under the New BSD license. See LICENSE or:
|
28841 | * http://opensource.org/licenses/BSD-3-Clause
|
28842 | */
|
28843 |
|
28844 |
|
28845 | var has$6 = Object.prototype.hasOwnProperty;
|
28846 | var hasNativeMap = typeof Map !== "undefined";
|
28847 |
|
28848 | /**
|
28849 | * A data structure which is a combination of an array and a set. Adding a new
|
28850 | * member is O(1), testing for membership is O(1), and finding the index of an
|
28851 | * element is O(1). Removing elements from the set is not supported. Only
|
28852 | * strings are supported for membership.
|
28853 | */
|
28854 | function ArraySet() {
|
28855 | this._array = [];
|
28856 | this._set = hasNativeMap ? new Map() : Object.create(null);
|
28857 | }
|
28858 |
|
28859 | /**
|
28860 | * Static method for creating ArraySet instances from an existing array.
|
28861 | */
|
28862 | ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
|
28863 | var set = new ArraySet();
|
28864 | for (var i = 0, len = aArray.length; i < len; i++) {
|
28865 | set.add(aArray[i], aAllowDuplicates);
|
28866 | }
|
28867 | return set;
|
28868 | };
|
28869 |
|
28870 | /**
|
28871 | * Return how many unique items are in this ArraySet. If duplicates have been
|
28872 | * added, than those do not count towards the size.
|
28873 | *
|
28874 | * @returns Number
|
28875 | */
|
28876 | ArraySet.prototype.size = function ArraySet_size() {
|
28877 | return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
|
28878 | };
|
28879 |
|
28880 | /**
|
28881 | * Add the given string to this set.
|
28882 | *
|
28883 | * @param String aStr
|
28884 | */
|
28885 | ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
|
28886 | var sStr = hasNativeMap ? aStr : util$1.toSetString(aStr);
|
28887 | var isDuplicate = hasNativeMap ? this.has(aStr) : has$6.call(this._set, sStr);
|
28888 | var idx = this._array.length;
|
28889 | if (!isDuplicate || aAllowDuplicates) {
|
28890 | this._array.push(aStr);
|
28891 | }
|
28892 | if (!isDuplicate) {
|
28893 | if (hasNativeMap) {
|
28894 | this._set.set(aStr, idx);
|
28895 | } else {
|
28896 | this._set[sStr] = idx;
|
28897 | }
|
28898 | }
|
28899 | };
|
28900 |
|
28901 | /**
|
28902 | * Is the given string a member of this set?
|
28903 | *
|
28904 | * @param String aStr
|
28905 | */
|
28906 | ArraySet.prototype.has = function ArraySet_has(aStr) {
|
28907 | if (hasNativeMap) {
|
28908 | return this._set.has(aStr);
|
28909 | } else {
|
28910 | var sStr = util$1.toSetString(aStr);
|
28911 | return has$6.call(this._set, sStr);
|
28912 | }
|
28913 | };
|
28914 |
|
28915 | /**
|
28916 | * What is the index of the given string in the array?
|
28917 | *
|
28918 | * @param String aStr
|
28919 | */
|
28920 | ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
|
28921 | if (hasNativeMap) {
|
28922 | var idx = this._set.get(aStr);
|
28923 | if (idx >= 0) {
|
28924 | return idx;
|
28925 | }
|
28926 | } else {
|
28927 | var sStr = util$1.toSetString(aStr);
|
28928 | if (has$6.call(this._set, sStr)) {
|
28929 | return this._set[sStr];
|
28930 | }
|
28931 | }
|
28932 |
|
28933 | throw new Error('"' + aStr + '" is not in the set.');
|
28934 | };
|
28935 |
|
28936 | /**
|
28937 | * What is the element at the given index?
|
28938 | *
|
28939 | * @param Number aIdx
|
28940 | */
|
28941 | ArraySet.prototype.at = function ArraySet_at(aIdx) {
|
28942 | if (aIdx >= 0 && aIdx < this._array.length) {
|
28943 | return this._array[aIdx];
|
28944 | }
|
28945 | throw new Error('No element indexed by ' + aIdx);
|
28946 | };
|
28947 |
|
28948 | /**
|
28949 | * Returns the array representation of this set (which has the proper indices
|
28950 | * indicated by indexOf). Note that this is a copy of the internal array used
|
28951 | * for storing the members so that no one can mess with internal state.
|
28952 | */
|
28953 | ArraySet.prototype.toArray = function ArraySet_toArray() {
|
28954 | return this._array.slice();
|
28955 | };
|
28956 |
|
28957 | var ArraySet_1 = ArraySet;
|
28958 |
|
28959 | var arraySet = {
|
28960 | ArraySet: ArraySet_1
|
28961 | };
|
28962 |
|
28963 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
28964 | /*
|
28965 | * Copyright 2014 Mozilla Foundation and contributors
|
28966 | * Licensed under the New BSD license. See LICENSE or:
|
28967 | * http://opensource.org/licenses/BSD-3-Clause
|
28968 | */
|
28969 |
|
28970 |
|
28971 |
|
28972 | /**
|
28973 | * Determine whether mappingB is after mappingA with respect to generated
|
28974 | * position.
|
28975 | */
|
28976 | function generatedPositionAfter(mappingA, mappingB) {
|
28977 | // Optimized for most common case
|
28978 | var lineA = mappingA.generatedLine;
|
28979 | var lineB = mappingB.generatedLine;
|
28980 | var columnA = mappingA.generatedColumn;
|
28981 | var columnB = mappingB.generatedColumn;
|
28982 | return lineB > lineA || lineB == lineA && columnB >= columnA ||
|
28983 | util$1.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
|
28984 | }
|
28985 |
|
28986 | /**
|
28987 | * A data structure to provide a sorted view of accumulated mappings in a
|
28988 | * performance conscious manner. It trades a neglibable overhead in general
|
28989 | * case for a large speedup in case of mappings being added in order.
|
28990 | */
|
28991 | function MappingList() {
|
28992 | this._array = [];
|
28993 | this._sorted = true;
|
28994 | // Serves as infimum
|
28995 | this._last = {generatedLine: -1, generatedColumn: 0};
|
28996 | }
|
28997 |
|
28998 | /**
|
28999 | * Iterate through internal items. This method takes the same arguments that
|
29000 | * `Array.prototype.forEach` takes.
|
29001 | *
|
29002 | * NOTE: The order of the mappings is NOT guaranteed.
|
29003 | */
|
29004 | MappingList.prototype.unsortedForEach =
|
29005 | function MappingList_forEach(aCallback, aThisArg) {
|
29006 | this._array.forEach(aCallback, aThisArg);
|
29007 | };
|
29008 |
|
29009 | /**
|
29010 | * Add the given source mapping.
|
29011 | *
|
29012 | * @param Object aMapping
|
29013 | */
|
29014 | MappingList.prototype.add = function MappingList_add(aMapping) {
|
29015 | if (generatedPositionAfter(this._last, aMapping)) {
|
29016 | this._last = aMapping;
|
29017 | this._array.push(aMapping);
|
29018 | } else {
|
29019 | this._sorted = false;
|
29020 | this._array.push(aMapping);
|
29021 | }
|
29022 | };
|
29023 |
|
29024 | /**
|
29025 | * Returns the flat, sorted array of mappings. The mappings are sorted by
|
29026 | * generated position.
|
29027 | *
|
29028 | * WARNING: This method returns internal data without copying, for
|
29029 | * performance. The return value must NOT be mutated, and should be treated as
|
29030 | * an immutable borrow. If you want to take ownership, you must make your own
|
29031 | * copy.
|
29032 | */
|
29033 | MappingList.prototype.toArray = function MappingList_toArray() {
|
29034 | if (!this._sorted) {
|
29035 | this._array.sort(util$1.compareByGeneratedPositionsInflated);
|
29036 | this._sorted = true;
|
29037 | }
|
29038 | return this._array;
|
29039 | };
|
29040 |
|
29041 | var MappingList_1 = MappingList;
|
29042 |
|
29043 | var mappingList = {
|
29044 | MappingList: MappingList_1
|
29045 | };
|
29046 |
|
29047 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
29048 | /*
|
29049 | * Copyright 2011 Mozilla Foundation and contributors
|
29050 | * Licensed under the New BSD license. See LICENSE or:
|
29051 | * http://opensource.org/licenses/BSD-3-Clause
|
29052 | */
|
29053 |
|
29054 |
|
29055 |
|
29056 | var ArraySet$1 = arraySet.ArraySet;
|
29057 | var MappingList$1 = mappingList.MappingList;
|
29058 |
|
29059 | /**
|
29060 | * An instance of the SourceMapGenerator represents a source map which is
|
29061 | * being built incrementally. You may pass an object with the following
|
29062 | * properties:
|
29063 | *
|
29064 | * - file: The filename of the generated source.
|
29065 | * - sourceRoot: A root for all relative URLs in this source map.
|
29066 | */
|
29067 | function SourceMapGenerator(aArgs) {
|
29068 | if (!aArgs) {
|
29069 | aArgs = {};
|
29070 | }
|
29071 | this._file = util$1.getArg(aArgs, 'file', null);
|
29072 | this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
|
29073 | this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
|
29074 | this._sources = new ArraySet$1();
|
29075 | this._names = new ArraySet$1();
|
29076 | this._mappings = new MappingList$1();
|
29077 | this._sourcesContents = null;
|
29078 | }
|
29079 |
|
29080 | SourceMapGenerator.prototype._version = 3;
|
29081 |
|
29082 | /**
|
29083 | * Creates a new SourceMapGenerator based on a SourceMapConsumer
|
29084 | *
|
29085 | * @param aSourceMapConsumer The SourceMap.
|
29086 | */
|
29087 | SourceMapGenerator.fromSourceMap =
|
29088 | function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
|
29089 | var sourceRoot = aSourceMapConsumer.sourceRoot;
|
29090 | var generator = new SourceMapGenerator({
|
29091 | file: aSourceMapConsumer.file,
|
29092 | sourceRoot: sourceRoot
|
29093 | });
|
29094 | aSourceMapConsumer.eachMapping(function (mapping) {
|
29095 | var newMapping = {
|
29096 | generated: {
|
29097 | line: mapping.generatedLine,
|
29098 | column: mapping.generatedColumn
|
29099 | }
|
29100 | };
|
29101 |
|
29102 | if (mapping.source != null) {
|
29103 | newMapping.source = mapping.source;
|
29104 | if (sourceRoot != null) {
|
29105 | newMapping.source = util$1.relative(sourceRoot, newMapping.source);
|
29106 | }
|
29107 |
|
29108 | newMapping.original = {
|
29109 | line: mapping.originalLine,
|
29110 | column: mapping.originalColumn
|
29111 | };
|
29112 |
|
29113 | if (mapping.name != null) {
|
29114 | newMapping.name = mapping.name;
|
29115 | }
|
29116 | }
|
29117 |
|
29118 | generator.addMapping(newMapping);
|
29119 | });
|
29120 | aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
29121 | var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
29122 | if (content != null) {
|
29123 | generator.setSourceContent(sourceFile, content);
|
29124 | }
|
29125 | });
|
29126 | return generator;
|
29127 | };
|
29128 |
|
29129 | /**
|
29130 | * Add a single mapping from original source line and column to the generated
|
29131 | * source's line and column for this source map being created. The mapping
|
29132 | * object should have the following properties:
|
29133 | *
|
29134 | * - generated: An object with the generated line and column positions.
|
29135 | * - original: An object with the original line and column positions.
|
29136 | * - source: The original source file (relative to the sourceRoot).
|
29137 | * - name: An optional original token name for this mapping.
|
29138 | */
|
29139 | SourceMapGenerator.prototype.addMapping =
|
29140 | function SourceMapGenerator_addMapping(aArgs) {
|
29141 | var generated = util$1.getArg(aArgs, 'generated');
|
29142 | var original = util$1.getArg(aArgs, 'original', null);
|
29143 | var source = util$1.getArg(aArgs, 'source', null);
|
29144 | var name = util$1.getArg(aArgs, 'name', null);
|
29145 |
|
29146 | if (!this._skipValidation) {
|
29147 | this._validateMapping(generated, original, source, name);
|
29148 | }
|
29149 |
|
29150 | if (source != null) {
|
29151 | source = String(source);
|
29152 | if (!this._sources.has(source)) {
|
29153 | this._sources.add(source);
|
29154 | }
|
29155 | }
|
29156 |
|
29157 | if (name != null) {
|
29158 | name = String(name);
|
29159 | if (!this._names.has(name)) {
|
29160 | this._names.add(name);
|
29161 | }
|
29162 | }
|
29163 |
|
29164 | this._mappings.add({
|
29165 | generatedLine: generated.line,
|
29166 | generatedColumn: generated.column,
|
29167 | originalLine: original != null && original.line,
|
29168 | originalColumn: original != null && original.column,
|
29169 | source: source,
|
29170 | name: name
|
29171 | });
|
29172 | };
|
29173 |
|
29174 | /**
|
29175 | * Set the source content for a source file.
|
29176 | */
|
29177 | SourceMapGenerator.prototype.setSourceContent =
|
29178 | function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
|
29179 | var source = aSourceFile;
|
29180 | if (this._sourceRoot != null) {
|
29181 | source = util$1.relative(this._sourceRoot, source);
|
29182 | }
|
29183 |
|
29184 | if (aSourceContent != null) {
|
29185 | // Add the source content to the _sourcesContents map.
|
29186 | // Create a new _sourcesContents map if the property is null.
|
29187 | if (!this._sourcesContents) {
|
29188 | this._sourcesContents = Object.create(null);
|
29189 | }
|
29190 | this._sourcesContents[util$1.toSetString(source)] = aSourceContent;
|
29191 | } else if (this._sourcesContents) {
|
29192 | // Remove the source file from the _sourcesContents map.
|
29193 | // If the _sourcesContents map is empty, set the property to null.
|
29194 | delete this._sourcesContents[util$1.toSetString(source)];
|
29195 | if (Object.keys(this._sourcesContents).length === 0) {
|
29196 | this._sourcesContents = null;
|
29197 | }
|
29198 | }
|
29199 | };
|
29200 |
|
29201 | /**
|
29202 | * Applies the mappings of a sub-source-map for a specific source file to the
|
29203 | * source map being generated. Each mapping to the supplied source file is
|
29204 | * rewritten using the supplied source map. Note: The resolution for the
|
29205 | * resulting mappings is the minimium of this map and the supplied map.
|
29206 | *
|
29207 | * @param aSourceMapConsumer The source map to be applied.
|
29208 | * @param aSourceFile Optional. The filename of the source file.
|
29209 | * If omitted, SourceMapConsumer's file property will be used.
|
29210 | * @param aSourceMapPath Optional. The dirname of the path to the source map
|
29211 | * to be applied. If relative, it is relative to the SourceMapConsumer.
|
29212 | * This parameter is needed when the two source maps aren't in the same
|
29213 | * directory, and the source map to be applied contains relative source
|
29214 | * paths. If so, those relative source paths need to be rewritten
|
29215 | * relative to the SourceMapGenerator.
|
29216 | */
|
29217 | SourceMapGenerator.prototype.applySourceMap =
|
29218 | function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
|
29219 | var sourceFile = aSourceFile;
|
29220 | // If aSourceFile is omitted, we will use the file property of the SourceMap
|
29221 | if (aSourceFile == null) {
|
29222 | if (aSourceMapConsumer.file == null) {
|
29223 | throw new Error(
|
29224 | 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
|
29225 | 'or the source map\'s "file" property. Both were omitted.'
|
29226 | );
|
29227 | }
|
29228 | sourceFile = aSourceMapConsumer.file;
|
29229 | }
|
29230 | var sourceRoot = this._sourceRoot;
|
29231 | // Make "sourceFile" relative if an absolute Url is passed.
|
29232 | if (sourceRoot != null) {
|
29233 | sourceFile = util$1.relative(sourceRoot, sourceFile);
|
29234 | }
|
29235 | // Applying the SourceMap can add and remove items from the sources and
|
29236 | // the names array.
|
29237 | var newSources = new ArraySet$1();
|
29238 | var newNames = new ArraySet$1();
|
29239 |
|
29240 | // Find mappings for the "sourceFile"
|
29241 | this._mappings.unsortedForEach(function (mapping) {
|
29242 | if (mapping.source === sourceFile && mapping.originalLine != null) {
|
29243 | // Check if it can be mapped by the source map, then update the mapping.
|
29244 | var original = aSourceMapConsumer.originalPositionFor({
|
29245 | line: mapping.originalLine,
|
29246 | column: mapping.originalColumn
|
29247 | });
|
29248 | if (original.source != null) {
|
29249 | // Copy mapping
|
29250 | mapping.source = original.source;
|
29251 | if (aSourceMapPath != null) {
|
29252 | mapping.source = util$1.join(aSourceMapPath, mapping.source);
|
29253 | }
|
29254 | if (sourceRoot != null) {
|
29255 | mapping.source = util$1.relative(sourceRoot, mapping.source);
|
29256 | }
|
29257 | mapping.originalLine = original.line;
|
29258 | mapping.originalColumn = original.column;
|
29259 | if (original.name != null) {
|
29260 | mapping.name = original.name;
|
29261 | }
|
29262 | }
|
29263 | }
|
29264 |
|
29265 | var source = mapping.source;
|
29266 | if (source != null && !newSources.has(source)) {
|
29267 | newSources.add(source);
|
29268 | }
|
29269 |
|
29270 | var name = mapping.name;
|
29271 | if (name != null && !newNames.has(name)) {
|
29272 | newNames.add(name);
|
29273 | }
|
29274 |
|
29275 | }, this);
|
29276 | this._sources = newSources;
|
29277 | this._names = newNames;
|
29278 |
|
29279 | // Copy sourcesContents of applied map.
|
29280 | aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
29281 | var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
29282 | if (content != null) {
|
29283 | if (aSourceMapPath != null) {
|
29284 | sourceFile = util$1.join(aSourceMapPath, sourceFile);
|
29285 | }
|
29286 | if (sourceRoot != null) {
|
29287 | sourceFile = util$1.relative(sourceRoot, sourceFile);
|
29288 | }
|
29289 | this.setSourceContent(sourceFile, content);
|
29290 | }
|
29291 | }, this);
|
29292 | };
|
29293 |
|
29294 | /**
|
29295 | * A mapping can have one of the three levels of data:
|
29296 | *
|
29297 | * 1. Just the generated position.
|
29298 | * 2. The Generated position, original position, and original source.
|
29299 | * 3. Generated and original position, original source, as well as a name
|
29300 | * token.
|
29301 | *
|
29302 | * To maintain consistency, we validate that any new mapping being added falls
|
29303 | * in to one of these categories.
|
29304 | */
|
29305 | SourceMapGenerator.prototype._validateMapping =
|
29306 | function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
|
29307 | aName) {
|
29308 | // When aOriginal is truthy but has empty values for .line and .column,
|
29309 | // it is most likely a programmer error. In this case we throw a very
|
29310 | // specific error message to try to guide them the right way.
|
29311 | // For example: https://github.com/Polymer/polymer-bundler/pull/519
|
29312 | if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
|
29313 | throw new Error(
|
29314 | 'original.line and original.column are not numbers -- you probably meant to omit ' +
|
29315 | 'the original mapping entirely and only map the generated position. If so, pass ' +
|
29316 | 'null for the original mapping instead of an object with empty or null values.'
|
29317 | );
|
29318 | }
|
29319 |
|
29320 | if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
29321 | && aGenerated.line > 0 && aGenerated.column >= 0
|
29322 | && !aOriginal && !aSource && !aName) {
|
29323 | // Case 1.
|
29324 | return;
|
29325 | }
|
29326 | else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
29327 | && aOriginal && 'line' in aOriginal && 'column' in aOriginal
|
29328 | && aGenerated.line > 0 && aGenerated.column >= 0
|
29329 | && aOriginal.line > 0 && aOriginal.column >= 0
|
29330 | && aSource) {
|
29331 | // Cases 2 and 3.
|
29332 | return;
|
29333 | }
|
29334 | else {
|
29335 | throw new Error('Invalid mapping: ' + JSON.stringify({
|
29336 | generated: aGenerated,
|
29337 | source: aSource,
|
29338 | original: aOriginal,
|
29339 | name: aName
|
29340 | }));
|
29341 | }
|
29342 | };
|
29343 |
|
29344 | /**
|
29345 | * Serialize the accumulated mappings in to the stream of base 64 VLQs
|
29346 | * specified by the source map format.
|
29347 | */
|
29348 | SourceMapGenerator.prototype._serializeMappings =
|
29349 | function SourceMapGenerator_serializeMappings() {
|
29350 | var previousGeneratedColumn = 0;
|
29351 | var previousGeneratedLine = 1;
|
29352 | var previousOriginalColumn = 0;
|
29353 | var previousOriginalLine = 0;
|
29354 | var previousName = 0;
|
29355 | var previousSource = 0;
|
29356 | var result = '';
|
29357 | var next;
|
29358 | var mapping;
|
29359 | var nameIdx;
|
29360 | var sourceIdx;
|
29361 |
|
29362 | var mappings = this._mappings.toArray();
|
29363 | for (var i = 0, len = mappings.length; i < len; i++) {
|
29364 | mapping = mappings[i];
|
29365 | next = '';
|
29366 |
|
29367 | if (mapping.generatedLine !== previousGeneratedLine) {
|
29368 | previousGeneratedColumn = 0;
|
29369 | while (mapping.generatedLine !== previousGeneratedLine) {
|
29370 | next += ';';
|
29371 | previousGeneratedLine++;
|
29372 | }
|
29373 | }
|
29374 | else {
|
29375 | if (i > 0) {
|
29376 | if (!util$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
|
29377 | continue;
|
29378 | }
|
29379 | next += ',';
|
29380 | }
|
29381 | }
|
29382 |
|
29383 | next += base64Vlq.encode(mapping.generatedColumn
|
29384 | - previousGeneratedColumn);
|
29385 | previousGeneratedColumn = mapping.generatedColumn;
|
29386 |
|
29387 | if (mapping.source != null) {
|
29388 | sourceIdx = this._sources.indexOf(mapping.source);
|
29389 | next += base64Vlq.encode(sourceIdx - previousSource);
|
29390 | previousSource = sourceIdx;
|
29391 |
|
29392 | // lines are stored 0-based in SourceMap spec version 3
|
29393 | next += base64Vlq.encode(mapping.originalLine - 1
|
29394 | - previousOriginalLine);
|
29395 | previousOriginalLine = mapping.originalLine - 1;
|
29396 |
|
29397 | next += base64Vlq.encode(mapping.originalColumn
|
29398 | - previousOriginalColumn);
|
29399 | previousOriginalColumn = mapping.originalColumn;
|
29400 |
|
29401 | if (mapping.name != null) {
|
29402 | nameIdx = this._names.indexOf(mapping.name);
|
29403 | next += base64Vlq.encode(nameIdx - previousName);
|
29404 | previousName = nameIdx;
|
29405 | }
|
29406 | }
|
29407 |
|
29408 | result += next;
|
29409 | }
|
29410 |
|
29411 | return result;
|
29412 | };
|
29413 |
|
29414 | SourceMapGenerator.prototype._generateSourcesContent =
|
29415 | function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
|
29416 | return aSources.map(function (source) {
|
29417 | if (!this._sourcesContents) {
|
29418 | return null;
|
29419 | }
|
29420 | if (aSourceRoot != null) {
|
29421 | source = util$1.relative(aSourceRoot, source);
|
29422 | }
|
29423 | var key = util$1.toSetString(source);
|
29424 | return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
|
29425 | ? this._sourcesContents[key]
|
29426 | : null;
|
29427 | }, this);
|
29428 | };
|
29429 |
|
29430 | /**
|
29431 | * Externalize the source map.
|
29432 | */
|
29433 | SourceMapGenerator.prototype.toJSON =
|
29434 | function SourceMapGenerator_toJSON() {
|
29435 | var map = {
|
29436 | version: this._version,
|
29437 | sources: this._sources.toArray(),
|
29438 | names: this._names.toArray(),
|
29439 | mappings: this._serializeMappings()
|
29440 | };
|
29441 | if (this._file != null) {
|
29442 | map.file = this._file;
|
29443 | }
|
29444 | if (this._sourceRoot != null) {
|
29445 | map.sourceRoot = this._sourceRoot;
|
29446 | }
|
29447 | if (this._sourcesContents) {
|
29448 | map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
|
29449 | }
|
29450 |
|
29451 | return map;
|
29452 | };
|
29453 |
|
29454 | /**
|
29455 | * Render the source map being generated to a string.
|
29456 | */
|
29457 | SourceMapGenerator.prototype.toString =
|
29458 | function SourceMapGenerator_toString() {
|
29459 | return JSON.stringify(this.toJSON());
|
29460 | };
|
29461 |
|
29462 | var SourceMapGenerator_1 = SourceMapGenerator;
|
29463 |
|
29464 | var sourceMapGenerator = {
|
29465 | SourceMapGenerator: SourceMapGenerator_1
|
29466 | };
|
29467 |
|
29468 | var binarySearch = createCommonjsModule(function (module, exports) {
|
29469 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
29470 | /*
|
29471 | * Copyright 2011 Mozilla Foundation and contributors
|
29472 | * Licensed under the New BSD license. See LICENSE or:
|
29473 | * http://opensource.org/licenses/BSD-3-Clause
|
29474 | */
|
29475 |
|
29476 | exports.GREATEST_LOWER_BOUND = 1;
|
29477 | exports.LEAST_UPPER_BOUND = 2;
|
29478 |
|
29479 | /**
|
29480 | * Recursive implementation of binary search.
|
29481 | *
|
29482 | * @param aLow Indices here and lower do not contain the needle.
|
29483 | * @param aHigh Indices here and higher do not contain the needle.
|
29484 | * @param aNeedle The element being searched for.
|
29485 | * @param aHaystack The non-empty array being searched.
|
29486 | * @param aCompare Function which takes two elements and returns -1, 0, or 1.
|
29487 | * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
29488 | * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
29489 | * closest element that is smaller than or greater than the one we are
|
29490 | * searching for, respectively, if the exact element cannot be found.
|
29491 | */
|
29492 | function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
|
29493 | // This function terminates when one of the following is true:
|
29494 | //
|
29495 | // 1. We find the exact element we are looking for.
|
29496 | //
|
29497 | // 2. We did not find the exact element, but we can return the index of
|
29498 | // the next-closest element.
|
29499 | //
|
29500 | // 3. We did not find the exact element, and there is no next-closest
|
29501 | // element than the one we are searching for, so we return -1.
|
29502 | var mid = Math.floor((aHigh - aLow) / 2) + aLow;
|
29503 | var cmp = aCompare(aNeedle, aHaystack[mid], true);
|
29504 | if (cmp === 0) {
|
29505 | // Found the element we are looking for.
|
29506 | return mid;
|
29507 | }
|
29508 | else if (cmp > 0) {
|
29509 | // Our needle is greater than aHaystack[mid].
|
29510 | if (aHigh - mid > 1) {
|
29511 | // The element is in the upper half.
|
29512 | return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
|
29513 | }
|
29514 |
|
29515 | // The exact needle element was not found in this haystack. Determine if
|
29516 | // we are in termination case (3) or (2) and return the appropriate thing.
|
29517 | if (aBias == exports.LEAST_UPPER_BOUND) {
|
29518 | return aHigh < aHaystack.length ? aHigh : -1;
|
29519 | } else {
|
29520 | return mid;
|
29521 | }
|
29522 | }
|
29523 | else {
|
29524 | // Our needle is less than aHaystack[mid].
|
29525 | if (mid - aLow > 1) {
|
29526 | // The element is in the lower half.
|
29527 | return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
|
29528 | }
|
29529 |
|
29530 | // we are in termination case (3) or (2) and return the appropriate thing.
|
29531 | if (aBias == exports.LEAST_UPPER_BOUND) {
|
29532 | return mid;
|
29533 | } else {
|
29534 | return aLow < 0 ? -1 : aLow;
|
29535 | }
|
29536 | }
|
29537 | }
|
29538 |
|
29539 | /**
|
29540 | * This is an implementation of binary search which will always try and return
|
29541 | * the index of the closest element if there is no exact hit. This is because
|
29542 | * mappings between original and generated line/col pairs are single points,
|
29543 | * and there is an implicit region between each of them, so a miss just means
|
29544 | * that you aren't on the very start of a region.
|
29545 | *
|
29546 | * @param aNeedle The element you are looking for.
|
29547 | * @param aHaystack The array that is being searched.
|
29548 | * @param aCompare A function which takes the needle and an element in the
|
29549 | * array and returns -1, 0, or 1 depending on whether the needle is less
|
29550 | * than, equal to, or greater than the element, respectively.
|
29551 | * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
29552 | * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
29553 | * closest element that is smaller than or greater than the one we are
|
29554 | * searching for, respectively, if the exact element cannot be found.
|
29555 | * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
|
29556 | */
|
29557 | exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
|
29558 | if (aHaystack.length === 0) {
|
29559 | return -1;
|
29560 | }
|
29561 |
|
29562 | var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
|
29563 | aCompare, aBias || exports.GREATEST_LOWER_BOUND);
|
29564 | if (index < 0) {
|
29565 | return -1;
|
29566 | }
|
29567 |
|
29568 | // We have found either the exact element, or the next-closest element than
|
29569 | // the one we are searching for. However, there may be more than one such
|
29570 | // element. Make sure we always return the smallest of these.
|
29571 | while (index - 1 >= 0) {
|
29572 | if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
|
29573 | break;
|
29574 | }
|
29575 | --index;
|
29576 | }
|
29577 |
|
29578 | return index;
|
29579 | };
|
29580 | });
|
29581 |
|
29582 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
29583 | /*
|
29584 | * Copyright 2011 Mozilla Foundation and contributors
|
29585 | * Licensed under the New BSD license. See LICENSE or:
|
29586 | * http://opensource.org/licenses/BSD-3-Clause
|
29587 | */
|
29588 |
|
29589 | // It turns out that some (most?) JavaScript engines don't self-host
|
29590 | // `Array.prototype.sort`. This makes sense because C++ will likely remain
|
29591 | // faster than JS when doing raw CPU-intensive sorting. However, when using a
|
29592 | // custom comparator function, calling back and forth between the VM's C++ and
|
29593 | // JIT'd JS is rather slow *and* loses JIT type information, resulting in
|
29594 | // worse generated code for the comparator function than would be optimal. In
|
29595 | // fact, when sorting with a comparator, these costs outweigh the benefits of
|
29596 | // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
|
29597 | // a ~3500ms mean speed-up in `bench/bench.html`.
|
29598 |
|
29599 | /**
|
29600 | * Swap the elements indexed by `x` and `y` in the array `ary`.
|
29601 | *
|
29602 | * @param {Array} ary
|
29603 | * The array.
|
29604 | * @param {Number} x
|
29605 | * The index of the first item.
|
29606 | * @param {Number} y
|
29607 | * The index of the second item.
|
29608 | */
|
29609 | function swap(ary, x, y) {
|
29610 | var temp = ary[x];
|
29611 | ary[x] = ary[y];
|
29612 | ary[y] = temp;
|
29613 | }
|
29614 |
|
29615 | /**
|
29616 | * Returns a random integer within the range `low .. high` inclusive.
|
29617 | *
|
29618 | * @param {Number} low
|
29619 | * The lower bound on the range.
|
29620 | * @param {Number} high
|
29621 | * The upper bound on the range.
|
29622 | */
|
29623 | function randomIntInRange(low, high) {
|
29624 | return Math.round(low + (Math.random() * (high - low)));
|
29625 | }
|
29626 |
|
29627 | /**
|
29628 | * The Quick Sort algorithm.
|
29629 | *
|
29630 | * @param {Array} ary
|
29631 | * An array to sort.
|
29632 | * @param {function} comparator
|
29633 | * Function to use to compare two items.
|
29634 | * @param {Number} p
|
29635 | * Start index of the array
|
29636 | * @param {Number} r
|
29637 | * End index of the array
|
29638 | */
|
29639 | function doQuickSort(ary, comparator, p, r) {
|
29640 | // If our lower bound is less than our upper bound, we (1) partition the
|
29641 | // array into two pieces and (2) recurse on each half. If it is not, this is
|
29642 | // the empty array and our base case.
|
29643 |
|
29644 | if (p < r) {
|
29645 | // (1) Partitioning.
|
29646 | //
|
29647 | // The partitioning chooses a pivot between `p` and `r` and moves all
|
29648 | // elements that are less than or equal to the pivot to the before it, and
|
29649 | // all the elements that are greater than it after it. The effect is that
|
29650 | // once partition is done, the pivot is in the exact place it will be when
|
29651 | // the array is put in sorted order, and it will not need to be moved
|
29652 | // again. This runs in O(n) time.
|
29653 |
|
29654 | // Always choose a random pivot so that an input array which is reverse
|
29655 | // sorted does not cause O(n^2) running time.
|
29656 | var pivotIndex = randomIntInRange(p, r);
|
29657 | var i = p - 1;
|
29658 |
|
29659 | swap(ary, pivotIndex, r);
|
29660 | var pivot = ary[r];
|
29661 |
|
29662 | // Immediately after `j` is incremented in this loop, the following hold
|
29663 | // true:
|
29664 | //
|
29665 | // * Every element in `ary[p .. i]` is less than or equal to the pivot.
|
29666 | //
|
29667 | // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
|
29668 | for (var j = p; j < r; j++) {
|
29669 | if (comparator(ary[j], pivot) <= 0) {
|
29670 | i += 1;
|
29671 | swap(ary, i, j);
|
29672 | }
|
29673 | }
|
29674 |
|
29675 | swap(ary, i + 1, j);
|
29676 | var q = i + 1;
|
29677 |
|
29678 | // (2) Recurse on each half.
|
29679 |
|
29680 | doQuickSort(ary, comparator, p, q - 1);
|
29681 | doQuickSort(ary, comparator, q + 1, r);
|
29682 | }
|
29683 | }
|
29684 |
|
29685 | /**
|
29686 | * Sort the given array in-place with the given comparator function.
|
29687 | *
|
29688 | * @param {Array} ary
|
29689 | * An array to sort.
|
29690 | * @param {function} comparator
|
29691 | * Function to use to compare two items.
|
29692 | */
|
29693 | var quickSort_1 = function (ary, comparator) {
|
29694 | doQuickSort(ary, comparator, 0, ary.length - 1);
|
29695 | };
|
29696 |
|
29697 | var quickSort = {
|
29698 | quickSort: quickSort_1
|
29699 | };
|
29700 |
|
29701 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
29702 | /*
|
29703 | * Copyright 2011 Mozilla Foundation and contributors
|
29704 | * Licensed under the New BSD license. See LICENSE or:
|
29705 | * http://opensource.org/licenses/BSD-3-Clause
|
29706 | */
|
29707 |
|
29708 |
|
29709 |
|
29710 | var ArraySet$2 = arraySet.ArraySet;
|
29711 |
|
29712 | var quickSort$1 = quickSort.quickSort;
|
29713 |
|
29714 | function SourceMapConsumer(aSourceMap) {
|
29715 | var sourceMap = aSourceMap;
|
29716 | if (typeof aSourceMap === 'string') {
|
29717 | sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
29718 | }
|
29719 |
|
29720 | return sourceMap.sections != null
|
29721 | ? new IndexedSourceMapConsumer(sourceMap)
|
29722 | : new BasicSourceMapConsumer(sourceMap);
|
29723 | }
|
29724 |
|
29725 | SourceMapConsumer.fromSourceMap = function(aSourceMap) {
|
29726 | return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
|
29727 | };
|
29728 |
|
29729 | /**
|
29730 | * The version of the source mapping spec that we are consuming.
|
29731 | */
|
29732 | SourceMapConsumer.prototype._version = 3;
|
29733 |
|
29734 | // `__generatedMappings` and `__originalMappings` are arrays that hold the
|
29735 | // parsed mapping coordinates from the source map's "mappings" attribute. They
|
29736 | // are lazily instantiated, accessed via the `_generatedMappings` and
|
29737 | // `_originalMappings` getters respectively, and we only parse the mappings
|
29738 | // and create these arrays once queried for a source location. We jump through
|
29739 | // these hoops because there can be many thousands of mappings, and parsing
|
29740 | // them is expensive, so we only want to do it if we must.
|
29741 | //
|
29742 | // Each object in the arrays is of the form:
|
29743 | //
|
29744 | // {
|
29745 | // generatedLine: The line number in the generated code,
|
29746 | // generatedColumn: The column number in the generated code,
|
29747 | // source: The path to the original source file that generated this
|
29748 | // chunk of code,
|
29749 | // originalLine: The line number in the original source that
|
29750 | // corresponds to this chunk of generated code,
|
29751 | // originalColumn: The column number in the original source that
|
29752 | // corresponds to this chunk of generated code,
|
29753 | // name: The name of the original symbol which generated this chunk of
|
29754 | // code.
|
29755 | // }
|
29756 | //
|
29757 | // All properties except for `generatedLine` and `generatedColumn` can be
|
29758 | // `null`.
|
29759 | //
|
29760 | // `_generatedMappings` is ordered by the generated positions.
|
29761 | //
|
29762 | // `_originalMappings` is ordered by the original positions.
|
29763 |
|
29764 | SourceMapConsumer.prototype.__generatedMappings = null;
|
29765 | Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
|
29766 | get: function () {
|
29767 | if (!this.__generatedMappings) {
|
29768 | this._parseMappings(this._mappings, this.sourceRoot);
|
29769 | }
|
29770 |
|
29771 | return this.__generatedMappings;
|
29772 | }
|
29773 | });
|
29774 |
|
29775 | SourceMapConsumer.prototype.__originalMappings = null;
|
29776 | Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
|
29777 | get: function () {
|
29778 | if (!this.__originalMappings) {
|
29779 | this._parseMappings(this._mappings, this.sourceRoot);
|
29780 | }
|
29781 |
|
29782 | return this.__originalMappings;
|
29783 | }
|
29784 | });
|
29785 |
|
29786 | SourceMapConsumer.prototype._charIsMappingSeparator =
|
29787 | function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
|
29788 | var c = aStr.charAt(index);
|
29789 | return c === ";" || c === ",";
|
29790 | };
|
29791 |
|
29792 | /**
|
29793 | * Parse the mappings in a string in to a data structure which we can easily
|
29794 | * query (the ordered arrays in the `this.__generatedMappings` and
|
29795 | * `this.__originalMappings` properties).
|
29796 | */
|
29797 | SourceMapConsumer.prototype._parseMappings =
|
29798 | function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
29799 | throw new Error("Subclasses must implement _parseMappings");
|
29800 | };
|
29801 |
|
29802 | SourceMapConsumer.GENERATED_ORDER = 1;
|
29803 | SourceMapConsumer.ORIGINAL_ORDER = 2;
|
29804 |
|
29805 | SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
|
29806 | SourceMapConsumer.LEAST_UPPER_BOUND = 2;
|
29807 |
|
29808 | /**
|
29809 | * Iterate over each mapping between an original source/line/column and a
|
29810 | * generated line/column in this source map.
|
29811 | *
|
29812 | * @param Function aCallback
|
29813 | * The function that is called with each mapping.
|
29814 | * @param Object aContext
|
29815 | * Optional. If specified, this object will be the value of `this` every
|
29816 | * time that `aCallback` is called.
|
29817 | * @param aOrder
|
29818 | * Either `SourceMapConsumer.GENERATED_ORDER` or
|
29819 | * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
|
29820 | * iterate over the mappings sorted by the generated file's line/column
|
29821 | * order or the original's source/line/column order, respectively. Defaults to
|
29822 | * `SourceMapConsumer.GENERATED_ORDER`.
|
29823 | */
|
29824 | SourceMapConsumer.prototype.eachMapping =
|
29825 | function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
|
29826 | var context = aContext || null;
|
29827 | var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
|
29828 |
|
29829 | var mappings;
|
29830 | switch (order) {
|
29831 | case SourceMapConsumer.GENERATED_ORDER:
|
29832 | mappings = this._generatedMappings;
|
29833 | break;
|
29834 | case SourceMapConsumer.ORIGINAL_ORDER:
|
29835 | mappings = this._originalMappings;
|
29836 | break;
|
29837 | default:
|
29838 | throw new Error("Unknown order of iteration.");
|
29839 | }
|
29840 |
|
29841 | var sourceRoot = this.sourceRoot;
|
29842 | mappings.map(function (mapping) {
|
29843 | var source = mapping.source === null ? null : this._sources.at(mapping.source);
|
29844 | if (source != null && sourceRoot != null) {
|
29845 | source = util$1.join(sourceRoot, source);
|
29846 | }
|
29847 | return {
|
29848 | source: source,
|
29849 | generatedLine: mapping.generatedLine,
|
29850 | generatedColumn: mapping.generatedColumn,
|
29851 | originalLine: mapping.originalLine,
|
29852 | originalColumn: mapping.originalColumn,
|
29853 | name: mapping.name === null ? null : this._names.at(mapping.name)
|
29854 | };
|
29855 | }, this).forEach(aCallback, context);
|
29856 | };
|
29857 |
|
29858 | /**
|
29859 | * Returns all generated line and column information for the original source,
|
29860 | * line, and column provided. If no column is provided, returns all mappings
|
29861 | * corresponding to a either the line we are searching for or the next
|
29862 | * closest line that has any mappings. Otherwise, returns all mappings
|
29863 | * corresponding to the given line and either the column we are searching for
|
29864 | * or the next closest column that has any offsets.
|
29865 | *
|
29866 | * The only argument is an object with the following properties:
|
29867 | *
|
29868 | * - source: The filename of the original source.
|
29869 | * - line: The line number in the original source.
|
29870 | * - column: Optional. the column number in the original source.
|
29871 | *
|
29872 | * and an array of objects is returned, each with the following properties:
|
29873 | *
|
29874 | * - line: The line number in the generated source, or null.
|
29875 | * - column: The column number in the generated source, or null.
|
29876 | */
|
29877 | SourceMapConsumer.prototype.allGeneratedPositionsFor =
|
29878 | function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
|
29879 | var line = util$1.getArg(aArgs, 'line');
|
29880 |
|
29881 | // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
|
29882 | // returns the index of the closest mapping less than the needle. By
|
29883 | // setting needle.originalColumn to 0, we thus find the last mapping for
|
29884 | // the given line, provided such a mapping exists.
|
29885 | var needle = {
|
29886 | source: util$1.getArg(aArgs, 'source'),
|
29887 | originalLine: line,
|
29888 | originalColumn: util$1.getArg(aArgs, 'column', 0)
|
29889 | };
|
29890 |
|
29891 | if (this.sourceRoot != null) {
|
29892 | needle.source = util$1.relative(this.sourceRoot, needle.source);
|
29893 | }
|
29894 | if (!this._sources.has(needle.source)) {
|
29895 | return [];
|
29896 | }
|
29897 | needle.source = this._sources.indexOf(needle.source);
|
29898 |
|
29899 | var mappings = [];
|
29900 |
|
29901 | var index = this._findMapping(needle,
|
29902 | this._originalMappings,
|
29903 | "originalLine",
|
29904 | "originalColumn",
|
29905 | util$1.compareByOriginalPositions,
|
29906 | binarySearch.LEAST_UPPER_BOUND);
|
29907 | if (index >= 0) {
|
29908 | var mapping = this._originalMappings[index];
|
29909 |
|
29910 | if (aArgs.column === undefined) {
|
29911 | var originalLine = mapping.originalLine;
|
29912 |
|
29913 | // Iterate until either we run out of mappings, or we run into
|
29914 | // a mapping for a different line than the one we found. Since
|
29915 | // mappings are sorted, this is guaranteed to find all mappings for
|
29916 | // the line we found.
|
29917 | while (mapping && mapping.originalLine === originalLine) {
|
29918 | mappings.push({
|
29919 | line: util$1.getArg(mapping, 'generatedLine', null),
|
29920 | column: util$1.getArg(mapping, 'generatedColumn', null),
|
29921 | lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
|
29922 | });
|
29923 |
|
29924 | mapping = this._originalMappings[++index];
|
29925 | }
|
29926 | } else {
|
29927 | var originalColumn = mapping.originalColumn;
|
29928 |
|
29929 | // Iterate until either we run out of mappings, or we run into
|
29930 | // a mapping for a different line than the one we were searching for.
|
29931 | // Since mappings are sorted, this is guaranteed to find all mappings for
|
29932 | // the line we are searching for.
|
29933 | while (mapping &&
|
29934 | mapping.originalLine === line &&
|
29935 | mapping.originalColumn == originalColumn) {
|
29936 | mappings.push({
|
29937 | line: util$1.getArg(mapping, 'generatedLine', null),
|
29938 | column: util$1.getArg(mapping, 'generatedColumn', null),
|
29939 | lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
|
29940 | });
|
29941 |
|
29942 | mapping = this._originalMappings[++index];
|
29943 | }
|
29944 | }
|
29945 | }
|
29946 |
|
29947 | return mappings;
|
29948 | };
|
29949 |
|
29950 | var SourceMapConsumer_1 = SourceMapConsumer;
|
29951 |
|
29952 | /**
|
29953 | * A BasicSourceMapConsumer instance represents a parsed source map which we can
|
29954 | * query for information about the original file positions by giving it a file
|
29955 | * position in the generated source.
|
29956 | *
|
29957 | * The only parameter is the raw source map (either as a JSON string, or
|
29958 | * already parsed to an object). According to the spec, source maps have the
|
29959 | * following attributes:
|
29960 | *
|
29961 | * - version: Which version of the source map spec this map is following.
|
29962 | * - sources: An array of URLs to the original source files.
|
29963 | * - names: An array of identifiers which can be referrenced by individual mappings.
|
29964 | * - sourceRoot: Optional. The URL root from which all sources are relative.
|
29965 | * - sourcesContent: Optional. An array of contents of the original source files.
|
29966 | * - mappings: A string of base64 VLQs which contain the actual mappings.
|
29967 | * - file: Optional. The generated file this source map is associated with.
|
29968 | *
|
29969 | * Here is an example source map, taken from the source map spec[0]:
|
29970 | *
|
29971 | * {
|
29972 | * version : 3,
|
29973 | * file: "out.js",
|
29974 | * sourceRoot : "",
|
29975 | * sources: ["foo.js", "bar.js"],
|
29976 | * names: ["src", "maps", "are", "fun"],
|
29977 | * mappings: "AA,AB;;ABCDE;"
|
29978 | * }
|
29979 | *
|
29980 | * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
|
29981 | */
|
29982 | function BasicSourceMapConsumer(aSourceMap) {
|
29983 | var sourceMap = aSourceMap;
|
29984 | if (typeof aSourceMap === 'string') {
|
29985 | sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
29986 | }
|
29987 |
|
29988 | var version = util$1.getArg(sourceMap, 'version');
|
29989 | var sources = util$1.getArg(sourceMap, 'sources');
|
29990 | // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
|
29991 | // requires the array) to play nice here.
|
29992 | var names = util$1.getArg(sourceMap, 'names', []);
|
29993 | var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
|
29994 | var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
|
29995 | var mappings = util$1.getArg(sourceMap, 'mappings');
|
29996 | var file = util$1.getArg(sourceMap, 'file', null);
|
29997 |
|
29998 | // Once again, Sass deviates from the spec and supplies the version as a
|
29999 | // string rather than a number, so we use loose equality checking here.
|
30000 | if (version != this._version) {
|
30001 | throw new Error('Unsupported version: ' + version);
|
30002 | }
|
30003 |
|
30004 | sources = sources
|
30005 | .map(String)
|
30006 | // Some source maps produce relative source paths like "./foo.js" instead of
|
30007 | // "foo.js". Normalize these first so that future comparisons will succeed.
|
30008 | // See bugzil.la/1090768.
|
30009 | .map(util$1.normalize)
|
30010 | // Always ensure that absolute sources are internally stored relative to
|
30011 | // the source root, if the source root is absolute. Not doing this would
|
30012 | // be particularly problematic when the source root is a prefix of the
|
30013 | // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
|
30014 | .map(function (source) {
|
30015 | return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
|
30016 | ? util$1.relative(sourceRoot, source)
|
30017 | : source;
|
30018 | });
|
30019 |
|
30020 | // Pass `true` below to allow duplicate names and sources. While source maps
|
30021 | // are intended to be compressed and deduplicated, the TypeScript compiler
|
30022 | // sometimes generates source maps with duplicates in them. See Github issue
|
30023 | // #72 and bugzil.la/889492.
|
30024 | this._names = ArraySet$2.fromArray(names.map(String), true);
|
30025 | this._sources = ArraySet$2.fromArray(sources, true);
|
30026 |
|
30027 | this.sourceRoot = sourceRoot;
|
30028 | this.sourcesContent = sourcesContent;
|
30029 | this._mappings = mappings;
|
30030 | this.file = file;
|
30031 | }
|
30032 |
|
30033 | BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
|
30034 | BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
|
30035 |
|
30036 | /**
|
30037 | * Create a BasicSourceMapConsumer from a SourceMapGenerator.
|
30038 | *
|
30039 | * @param SourceMapGenerator aSourceMap
|
30040 | * The source map that will be consumed.
|
30041 | * @returns BasicSourceMapConsumer
|
30042 | */
|
30043 | BasicSourceMapConsumer.fromSourceMap =
|
30044 | function SourceMapConsumer_fromSourceMap(aSourceMap) {
|
30045 | var smc = Object.create(BasicSourceMapConsumer.prototype);
|
30046 |
|
30047 | var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
|
30048 | var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
|
30049 | smc.sourceRoot = aSourceMap._sourceRoot;
|
30050 | smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
|
30051 | smc.sourceRoot);
|
30052 | smc.file = aSourceMap._file;
|
30053 |
|
30054 | // Because we are modifying the entries (by converting string sources and
|
30055 | // names to indices into the sources and names ArraySets), we have to make
|
30056 | // a copy of the entry or else bad things happen. Shared mutable state
|
30057 | // strikes again! See github issue #191.
|
30058 |
|
30059 | var generatedMappings = aSourceMap._mappings.toArray().slice();
|
30060 | var destGeneratedMappings = smc.__generatedMappings = [];
|
30061 | var destOriginalMappings = smc.__originalMappings = [];
|
30062 |
|
30063 | for (var i = 0, length = generatedMappings.length; i < length; i++) {
|
30064 | var srcMapping = generatedMappings[i];
|
30065 | var destMapping = new Mapping;
|
30066 | destMapping.generatedLine = srcMapping.generatedLine;
|
30067 | destMapping.generatedColumn = srcMapping.generatedColumn;
|
30068 |
|
30069 | if (srcMapping.source) {
|
30070 | destMapping.source = sources.indexOf(srcMapping.source);
|
30071 | destMapping.originalLine = srcMapping.originalLine;
|
30072 | destMapping.originalColumn = srcMapping.originalColumn;
|
30073 |
|
30074 | if (srcMapping.name) {
|
30075 | destMapping.name = names.indexOf(srcMapping.name);
|
30076 | }
|
30077 |
|
30078 | destOriginalMappings.push(destMapping);
|
30079 | }
|
30080 |
|
30081 | destGeneratedMappings.push(destMapping);
|
30082 | }
|
30083 |
|
30084 | quickSort$1(smc.__originalMappings, util$1.compareByOriginalPositions);
|
30085 |
|
30086 | return smc;
|
30087 | };
|
30088 |
|
30089 | /**
|
30090 | * The version of the source mapping spec that we are consuming.
|
30091 | */
|
30092 | BasicSourceMapConsumer.prototype._version = 3;
|
30093 |
|
30094 | /**
|
30095 | * The list of original sources.
|
30096 | */
|
30097 | Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
|
30098 | get: function () {
|
30099 | return this._sources.toArray().map(function (s) {
|
30100 | return this.sourceRoot != null ? util$1.join(this.sourceRoot, s) : s;
|
30101 | }, this);
|
30102 | }
|
30103 | });
|
30104 |
|
30105 | /**
|
30106 | * Provide the JIT with a nice shape / hidden class.
|
30107 | */
|
30108 | function Mapping() {
|
30109 | this.generatedLine = 0;
|
30110 | this.generatedColumn = 0;
|
30111 | this.source = null;
|
30112 | this.originalLine = null;
|
30113 | this.originalColumn = null;
|
30114 | this.name = null;
|
30115 | }
|
30116 |
|
30117 | /**
|
30118 | * Parse the mappings in a string in to a data structure which we can easily
|
30119 | * query (the ordered arrays in the `this.__generatedMappings` and
|
30120 | * `this.__originalMappings` properties).
|
30121 | */
|
30122 | BasicSourceMapConsumer.prototype._parseMappings =
|
30123 | function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
30124 | var generatedLine = 1;
|
30125 | var previousGeneratedColumn = 0;
|
30126 | var previousOriginalLine = 0;
|
30127 | var previousOriginalColumn = 0;
|
30128 | var previousSource = 0;
|
30129 | var previousName = 0;
|
30130 | var length = aStr.length;
|
30131 | var index = 0;
|
30132 | var cachedSegments = {};
|
30133 | var temp = {};
|
30134 | var originalMappings = [];
|
30135 | var generatedMappings = [];
|
30136 | var mapping, str, segment, end, value;
|
30137 |
|
30138 | while (index < length) {
|
30139 | if (aStr.charAt(index) === ';') {
|
30140 | generatedLine++;
|
30141 | index++;
|
30142 | previousGeneratedColumn = 0;
|
30143 | }
|
30144 | else if (aStr.charAt(index) === ',') {
|
30145 | index++;
|
30146 | }
|
30147 | else {
|
30148 | mapping = new Mapping();
|
30149 | mapping.generatedLine = generatedLine;
|
30150 |
|
30151 | // Because each offset is encoded relative to the previous one,
|
30152 | // many segments often have the same encoding. We can exploit this
|
30153 | // fact by caching the parsed variable length fields of each segment,
|
30154 | // allowing us to avoid a second parse if we encounter the same
|
30155 | // segment again.
|
30156 | for (end = index; end < length; end++) {
|
30157 | if (this._charIsMappingSeparator(aStr, end)) {
|
30158 | break;
|
30159 | }
|
30160 | }
|
30161 | str = aStr.slice(index, end);
|
30162 |
|
30163 | segment = cachedSegments[str];
|
30164 | if (segment) {
|
30165 | index += str.length;
|
30166 | } else {
|
30167 | segment = [];
|
30168 | while (index < end) {
|
30169 | base64Vlq.decode(aStr, index, temp);
|
30170 | value = temp.value;
|
30171 | index = temp.rest;
|
30172 | segment.push(value);
|
30173 | }
|
30174 |
|
30175 | if (segment.length === 2) {
|
30176 | throw new Error('Found a source, but no line and column');
|
30177 | }
|
30178 |
|
30179 | if (segment.length === 3) {
|
30180 | throw new Error('Found a source and line, but no column');
|
30181 | }
|
30182 |
|
30183 | cachedSegments[str] = segment;
|
30184 | }
|
30185 |
|
30186 | // Generated column.
|
30187 | mapping.generatedColumn = previousGeneratedColumn + segment[0];
|
30188 | previousGeneratedColumn = mapping.generatedColumn;
|
30189 |
|
30190 | if (segment.length > 1) {
|
30191 | // Original source.
|
30192 | mapping.source = previousSource + segment[1];
|
30193 | previousSource += segment[1];
|
30194 |
|
30195 | // Original line.
|
30196 | mapping.originalLine = previousOriginalLine + segment[2];
|
30197 | previousOriginalLine = mapping.originalLine;
|
30198 | // Lines are stored 0-based
|
30199 | mapping.originalLine += 1;
|
30200 |
|
30201 | // Original column.
|
30202 | mapping.originalColumn = previousOriginalColumn + segment[3];
|
30203 | previousOriginalColumn = mapping.originalColumn;
|
30204 |
|
30205 | if (segment.length > 4) {
|
30206 | // Original name.
|
30207 | mapping.name = previousName + segment[4];
|
30208 | previousName += segment[4];
|
30209 | }
|
30210 | }
|
30211 |
|
30212 | generatedMappings.push(mapping);
|
30213 | if (typeof mapping.originalLine === 'number') {
|
30214 | originalMappings.push(mapping);
|
30215 | }
|
30216 | }
|
30217 | }
|
30218 |
|
30219 | quickSort$1(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
|
30220 | this.__generatedMappings = generatedMappings;
|
30221 |
|
30222 | quickSort$1(originalMappings, util$1.compareByOriginalPositions);
|
30223 | this.__originalMappings = originalMappings;
|
30224 | };
|
30225 |
|
30226 | /**
|
30227 | * Find the mapping that best matches the hypothetical "needle" mapping that
|
30228 | * we are searching for in the given "haystack" of mappings.
|
30229 | */
|
30230 | BasicSourceMapConsumer.prototype._findMapping =
|
30231 | function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
|
30232 | aColumnName, aComparator, aBias) {
|
30233 | // To return the position we are searching for, we must first find the
|
30234 | // mapping for the given position and then return the opposite position it
|
30235 | // points to. Because the mappings are sorted, we can use binary search to
|
30236 | // find the best mapping.
|
30237 |
|
30238 | if (aNeedle[aLineName] <= 0) {
|
30239 | throw new TypeError('Line must be greater than or equal to 1, got '
|
30240 | + aNeedle[aLineName]);
|
30241 | }
|
30242 | if (aNeedle[aColumnName] < 0) {
|
30243 | throw new TypeError('Column must be greater than or equal to 0, got '
|
30244 | + aNeedle[aColumnName]);
|
30245 | }
|
30246 |
|
30247 | return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
|
30248 | };
|
30249 |
|
30250 | /**
|
30251 | * Compute the last column for each generated mapping. The last column is
|
30252 | * inclusive.
|
30253 | */
|
30254 | BasicSourceMapConsumer.prototype.computeColumnSpans =
|
30255 | function SourceMapConsumer_computeColumnSpans() {
|
30256 | for (var index = 0; index < this._generatedMappings.length; ++index) {
|
30257 | var mapping = this._generatedMappings[index];
|
30258 |
|
30259 | // Mappings do not contain a field for the last generated columnt. We
|
30260 | // can come up with an optimistic estimate, however, by assuming that
|
30261 | // mappings are contiguous (i.e. given two consecutive mappings, the
|
30262 | // first mapping ends where the second one starts).
|
30263 | if (index + 1 < this._generatedMappings.length) {
|
30264 | var nextMapping = this._generatedMappings[index + 1];
|
30265 |
|
30266 | if (mapping.generatedLine === nextMapping.generatedLine) {
|
30267 | mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
|
30268 | continue;
|
30269 | }
|
30270 | }
|
30271 |
|
30272 | // The last mapping for each line spans the entire line.
|
30273 | mapping.lastGeneratedColumn = Infinity;
|
30274 | }
|
30275 | };
|
30276 |
|
30277 | /**
|
30278 | * Returns the original source, line, and column information for the generated
|
30279 | * source's line and column positions provided. The only argument is an object
|
30280 | * with the following properties:
|
30281 | *
|
30282 | * - line: The line number in the generated source.
|
30283 | * - column: The column number in the generated source.
|
30284 | * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
|
30285 | * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
|
30286 | * closest element that is smaller than or greater than the one we are
|
30287 | * searching for, respectively, if the exact element cannot be found.
|
30288 | * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
|
30289 | *
|
30290 | * and an object is returned with the following properties:
|
30291 | *
|
30292 | * - source: The original source file, or null.
|
30293 | * - line: The line number in the original source, or null.
|
30294 | * - column: The column number in the original source, or null.
|
30295 | * - name: The original identifier, or null.
|
30296 | */
|
30297 | BasicSourceMapConsumer.prototype.originalPositionFor =
|
30298 | function SourceMapConsumer_originalPositionFor(aArgs) {
|
30299 | var needle = {
|
30300 | generatedLine: util$1.getArg(aArgs, 'line'),
|
30301 | generatedColumn: util$1.getArg(aArgs, 'column')
|
30302 | };
|
30303 |
|
30304 | var index = this._findMapping(
|
30305 | needle,
|
30306 | this._generatedMappings,
|
30307 | "generatedLine",
|
30308 | "generatedColumn",
|
30309 | util$1.compareByGeneratedPositionsDeflated,
|
30310 | util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
|
30311 | );
|
30312 |
|
30313 | if (index >= 0) {
|
30314 | var mapping = this._generatedMappings[index];
|
30315 |
|
30316 | if (mapping.generatedLine === needle.generatedLine) {
|
30317 | var source = util$1.getArg(mapping, 'source', null);
|
30318 | if (source !== null) {
|
30319 | source = this._sources.at(source);
|
30320 | if (this.sourceRoot != null) {
|
30321 | source = util$1.join(this.sourceRoot, source);
|
30322 | }
|
30323 | }
|
30324 | var name = util$1.getArg(mapping, 'name', null);
|
30325 | if (name !== null) {
|
30326 | name = this._names.at(name);
|
30327 | }
|
30328 | return {
|
30329 | source: source,
|
30330 | line: util$1.getArg(mapping, 'originalLine', null),
|
30331 | column: util$1.getArg(mapping, 'originalColumn', null),
|
30332 | name: name
|
30333 | };
|
30334 | }
|
30335 | }
|
30336 |
|
30337 | return {
|
30338 | source: null,
|
30339 | line: null,
|
30340 | column: null,
|
30341 | name: null
|
30342 | };
|
30343 | };
|
30344 |
|
30345 | /**
|
30346 | * Return true if we have the source content for every source in the source
|
30347 | * map, false otherwise.
|
30348 | */
|
30349 | BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
|
30350 | function BasicSourceMapConsumer_hasContentsOfAllSources() {
|
30351 | if (!this.sourcesContent) {
|
30352 | return false;
|
30353 | }
|
30354 | return this.sourcesContent.length >= this._sources.size() &&
|
30355 | !this.sourcesContent.some(function (sc) { return sc == null; });
|
30356 | };
|
30357 |
|
30358 | /**
|
30359 | * Returns the original source content. The only argument is the url of the
|
30360 | * original source file. Returns null if no original source content is
|
30361 | * available.
|
30362 | */
|
30363 | BasicSourceMapConsumer.prototype.sourceContentFor =
|
30364 | function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
|
30365 | if (!this.sourcesContent) {
|
30366 | return null;
|
30367 | }
|
30368 |
|
30369 | if (this.sourceRoot != null) {
|
30370 | aSource = util$1.relative(this.sourceRoot, aSource);
|
30371 | }
|
30372 |
|
30373 | if (this._sources.has(aSource)) {
|
30374 | return this.sourcesContent[this._sources.indexOf(aSource)];
|
30375 | }
|
30376 |
|
30377 | var url;
|
30378 | if (this.sourceRoot != null
|
30379 | && (url = util$1.urlParse(this.sourceRoot))) {
|
30380 | // XXX: file:// URIs and absolute paths lead to unexpected behavior for
|
30381 | // many users. We can help them out when they expect file:// URIs to
|
30382 | // behave like it would if they were running a local HTTP server. See
|
30383 | // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
|
30384 | var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
|
30385 | if (url.scheme == "file"
|
30386 | && this._sources.has(fileUriAbsPath)) {
|
30387 | return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
|
30388 | }
|
30389 |
|
30390 | if ((!url.path || url.path == "/")
|
30391 | && this._sources.has("/" + aSource)) {
|
30392 | return this.sourcesContent[this._sources.indexOf("/" + aSource)];
|
30393 | }
|
30394 | }
|
30395 |
|
30396 | // This function is used recursively from
|
30397 | // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
|
30398 | // don't want to throw if we can't find the source - we just want to
|
30399 | // return null, so we provide a flag to exit gracefully.
|
30400 | if (nullOnMissing) {
|
30401 | return null;
|
30402 | }
|
30403 | else {
|
30404 | throw new Error('"' + aSource + '" is not in the SourceMap.');
|
30405 | }
|
30406 | };
|
30407 |
|
30408 | /**
|
30409 | * Returns the generated line and column information for the original source,
|
30410 | * line, and column positions provided. The only argument is an object with
|
30411 | * the following properties:
|
30412 | *
|
30413 | * - source: The filename of the original source.
|
30414 | * - line: The line number in the original source.
|
30415 | * - column: The column number in the original source.
|
30416 | * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
|
30417 | * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
|
30418 | * closest element that is smaller than or greater than the one we are
|
30419 | * searching for, respectively, if the exact element cannot be found.
|
30420 | * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
|
30421 | *
|
30422 | * and an object is returned with the following properties:
|
30423 | *
|
30424 | * - line: The line number in the generated source, or null.
|
30425 | * - column: The column number in the generated source, or null.
|
30426 | */
|
30427 | BasicSourceMapConsumer.prototype.generatedPositionFor =
|
30428 | function SourceMapConsumer_generatedPositionFor(aArgs) {
|
30429 | var source = util$1.getArg(aArgs, 'source');
|
30430 | if (this.sourceRoot != null) {
|
30431 | source = util$1.relative(this.sourceRoot, source);
|
30432 | }
|
30433 | if (!this._sources.has(source)) {
|
30434 | return {
|
30435 | line: null,
|
30436 | column: null,
|
30437 | lastColumn: null
|
30438 | };
|
30439 | }
|
30440 | source = this._sources.indexOf(source);
|
30441 |
|
30442 | var needle = {
|
30443 | source: source,
|
30444 | originalLine: util$1.getArg(aArgs, 'line'),
|
30445 | originalColumn: util$1.getArg(aArgs, 'column')
|
30446 | };
|
30447 |
|
30448 | var index = this._findMapping(
|
30449 | needle,
|
30450 | this._originalMappings,
|
30451 | "originalLine",
|
30452 | "originalColumn",
|
30453 | util$1.compareByOriginalPositions,
|
30454 | util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
|
30455 | );
|
30456 |
|
30457 | if (index >= 0) {
|
30458 | var mapping = this._originalMappings[index];
|
30459 |
|
30460 | if (mapping.source === needle.source) {
|
30461 | return {
|
30462 | line: util$1.getArg(mapping, 'generatedLine', null),
|
30463 | column: util$1.getArg(mapping, 'generatedColumn', null),
|
30464 | lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
|
30465 | };
|
30466 | }
|
30467 | }
|
30468 |
|
30469 | return {
|
30470 | line: null,
|
30471 | column: null,
|
30472 | lastColumn: null
|
30473 | };
|
30474 | };
|
30475 |
|
30476 | var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
|
30477 |
|
30478 | /**
|
30479 | * An IndexedSourceMapConsumer instance represents a parsed source map which
|
30480 | * we can query for information. It differs from BasicSourceMapConsumer in
|
30481 | * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
|
30482 | * input.
|
30483 | *
|
30484 | * The only parameter is a raw source map (either as a JSON string, or already
|
30485 | * parsed to an object). According to the spec for indexed source maps, they
|
30486 | * have the following attributes:
|
30487 | *
|
30488 | * - version: Which version of the source map spec this map is following.
|
30489 | * - file: Optional. The generated file this source map is associated with.
|
30490 | * - sections: A list of section definitions.
|
30491 | *
|
30492 | * Each value under the "sections" field has two fields:
|
30493 | * - offset: The offset into the original specified at which this section
|
30494 | * begins to apply, defined as an object with a "line" and "column"
|
30495 | * field.
|
30496 | * - map: A source map definition. This source map could also be indexed,
|
30497 | * but doesn't have to be.
|
30498 | *
|
30499 | * Instead of the "map" field, it's also possible to have a "url" field
|
30500 | * specifying a URL to retrieve a source map from, but that's currently
|
30501 | * unsupported.
|
30502 | *
|
30503 | * Here's an example source map, taken from the source map spec[0], but
|
30504 | * modified to omit a section which uses the "url" field.
|
30505 | *
|
30506 | * {
|
30507 | * version : 3,
|
30508 | * file: "app.js",
|
30509 | * sections: [{
|
30510 | * offset: {line:100, column:10},
|
30511 | * map: {
|
30512 | * version : 3,
|
30513 | * file: "section.js",
|
30514 | * sources: ["foo.js", "bar.js"],
|
30515 | * names: ["src", "maps", "are", "fun"],
|
30516 | * mappings: "AAAA,E;;ABCDE;"
|
30517 | * }
|
30518 | * }],
|
30519 | * }
|
30520 | *
|
30521 | * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
|
30522 | */
|
30523 | function IndexedSourceMapConsumer(aSourceMap) {
|
30524 | var sourceMap = aSourceMap;
|
30525 | if (typeof aSourceMap === 'string') {
|
30526 | sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
30527 | }
|
30528 |
|
30529 | var version = util$1.getArg(sourceMap, 'version');
|
30530 | var sections = util$1.getArg(sourceMap, 'sections');
|
30531 |
|
30532 | if (version != this._version) {
|
30533 | throw new Error('Unsupported version: ' + version);
|
30534 | }
|
30535 |
|
30536 | this._sources = new ArraySet$2();
|
30537 | this._names = new ArraySet$2();
|
30538 |
|
30539 | var lastOffset = {
|
30540 | line: -1,
|
30541 | column: 0
|
30542 | };
|
30543 | this._sections = sections.map(function (s) {
|
30544 | if (s.url) {
|
30545 | // The url field will require support for asynchronicity.
|
30546 | // See https://github.com/mozilla/source-map/issues/16
|
30547 | throw new Error('Support for url field in sections not implemented.');
|
30548 | }
|
30549 | var offset = util$1.getArg(s, 'offset');
|
30550 | var offsetLine = util$1.getArg(offset, 'line');
|
30551 | var offsetColumn = util$1.getArg(offset, 'column');
|
30552 |
|
30553 | if (offsetLine < lastOffset.line ||
|
30554 | (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
|
30555 | throw new Error('Section offsets must be ordered and non-overlapping.');
|
30556 | }
|
30557 | lastOffset = offset;
|
30558 |
|
30559 | return {
|
30560 | generatedOffset: {
|
30561 | // The offset fields are 0-based, but we use 1-based indices when
|
30562 | // encoding/decoding from VLQ.
|
30563 | generatedLine: offsetLine + 1,
|
30564 | generatedColumn: offsetColumn + 1
|
30565 | },
|
30566 | consumer: new SourceMapConsumer(util$1.getArg(s, 'map'))
|
30567 | }
|
30568 | });
|
30569 | }
|
30570 |
|
30571 | IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
|
30572 | IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
|
30573 |
|
30574 | /**
|
30575 | * The version of the source mapping spec that we are consuming.
|
30576 | */
|
30577 | IndexedSourceMapConsumer.prototype._version = 3;
|
30578 |
|
30579 | /**
|
30580 | * The list of original sources.
|
30581 | */
|
30582 | Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
|
30583 | get: function () {
|
30584 | var sources = [];
|
30585 | for (var i = 0; i < this._sections.length; i++) {
|
30586 | for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
|
30587 | sources.push(this._sections[i].consumer.sources[j]);
|
30588 | }
|
30589 | }
|
30590 | return sources;
|
30591 | }
|
30592 | });
|
30593 |
|
30594 | /**
|
30595 | * Returns the original source, line, and column information for the generated
|
30596 | * source's line and column positions provided. The only argument is an object
|
30597 | * with the following properties:
|
30598 | *
|
30599 | * - line: The line number in the generated source.
|
30600 | * - column: The column number in the generated source.
|
30601 | *
|
30602 | * and an object is returned with the following properties:
|
30603 | *
|
30604 | * - source: The original source file, or null.
|
30605 | * - line: The line number in the original source, or null.
|
30606 | * - column: The column number in the original source, or null.
|
30607 | * - name: The original identifier, or null.
|
30608 | */
|
30609 | IndexedSourceMapConsumer.prototype.originalPositionFor =
|
30610 | function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
|
30611 | var needle = {
|
30612 | generatedLine: util$1.getArg(aArgs, 'line'),
|
30613 | generatedColumn: util$1.getArg(aArgs, 'column')
|
30614 | };
|
30615 |
|
30616 | // Find the section containing the generated position we're trying to map
|
30617 | // to an original position.
|
30618 | var sectionIndex = binarySearch.search(needle, this._sections,
|
30619 | function(needle, section) {
|
30620 | var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
|
30621 | if (cmp) {
|
30622 | return cmp;
|
30623 | }
|
30624 |
|
30625 | return (needle.generatedColumn -
|
30626 | section.generatedOffset.generatedColumn);
|
30627 | });
|
30628 | var section = this._sections[sectionIndex];
|
30629 |
|
30630 | if (!section) {
|
30631 | return {
|
30632 | source: null,
|
30633 | line: null,
|
30634 | column: null,
|
30635 | name: null
|
30636 | };
|
30637 | }
|
30638 |
|
30639 | return section.consumer.originalPositionFor({
|
30640 | line: needle.generatedLine -
|
30641 | (section.generatedOffset.generatedLine - 1),
|
30642 | column: needle.generatedColumn -
|
30643 | (section.generatedOffset.generatedLine === needle.generatedLine
|
30644 | ? section.generatedOffset.generatedColumn - 1
|
30645 | : 0),
|
30646 | bias: aArgs.bias
|
30647 | });
|
30648 | };
|
30649 |
|
30650 | /**
|
30651 | * Return true if we have the source content for every source in the source
|
30652 | * map, false otherwise.
|
30653 | */
|
30654 | IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
|
30655 | function IndexedSourceMapConsumer_hasContentsOfAllSources() {
|
30656 | return this._sections.every(function (s) {
|
30657 | return s.consumer.hasContentsOfAllSources();
|
30658 | });
|
30659 | };
|
30660 |
|
30661 | /**
|
30662 | * Returns the original source content. The only argument is the url of the
|
30663 | * original source file. Returns null if no original source content is
|
30664 | * available.
|
30665 | */
|
30666 | IndexedSourceMapConsumer.prototype.sourceContentFor =
|
30667 | function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
|
30668 | for (var i = 0; i < this._sections.length; i++) {
|
30669 | var section = this._sections[i];
|
30670 |
|
30671 | var content = section.consumer.sourceContentFor(aSource, true);
|
30672 | if (content) {
|
30673 | return content;
|
30674 | }
|
30675 | }
|
30676 | if (nullOnMissing) {
|
30677 | return null;
|
30678 | }
|
30679 | else {
|
30680 | throw new Error('"' + aSource + '" is not in the SourceMap.');
|
30681 | }
|
30682 | };
|
30683 |
|
30684 | /**
|
30685 | * Returns the generated line and column information for the original source,
|
30686 | * line, and column positions provided. The only argument is an object with
|
30687 | * the following properties:
|
30688 | *
|
30689 | * - source: The filename of the original source.
|
30690 | * - line: The line number in the original source.
|
30691 | * - column: The column number in the original source.
|
30692 | *
|
30693 | * and an object is returned with the following properties:
|
30694 | *
|
30695 | * - line: The line number in the generated source, or null.
|
30696 | * - column: The column number in the generated source, or null.
|
30697 | */
|
30698 | IndexedSourceMapConsumer.prototype.generatedPositionFor =
|
30699 | function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
|
30700 | for (var i = 0; i < this._sections.length; i++) {
|
30701 | var section = this._sections[i];
|
30702 |
|
30703 | // Only consider this section if the requested source is in the list of
|
30704 | // sources of the consumer.
|
30705 | if (section.consumer.sources.indexOf(util$1.getArg(aArgs, 'source')) === -1) {
|
30706 | continue;
|
30707 | }
|
30708 | var generatedPosition = section.consumer.generatedPositionFor(aArgs);
|
30709 | if (generatedPosition) {
|
30710 | var ret = {
|
30711 | line: generatedPosition.line +
|
30712 | (section.generatedOffset.generatedLine - 1),
|
30713 | column: generatedPosition.column +
|
30714 | (section.generatedOffset.generatedLine === generatedPosition.line
|
30715 | ? section.generatedOffset.generatedColumn - 1
|
30716 | : 0)
|
30717 | };
|
30718 | return ret;
|
30719 | }
|
30720 | }
|
30721 |
|
30722 | return {
|
30723 | line: null,
|
30724 | column: null
|
30725 | };
|
30726 | };
|
30727 |
|
30728 | /**
|
30729 | * Parse the mappings in a string in to a data structure which we can easily
|
30730 | * query (the ordered arrays in the `this.__generatedMappings` and
|
30731 | * `this.__originalMappings` properties).
|
30732 | */
|
30733 | IndexedSourceMapConsumer.prototype._parseMappings =
|
30734 | function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
30735 | this.__generatedMappings = [];
|
30736 | this.__originalMappings = [];
|
30737 | for (var i = 0; i < this._sections.length; i++) {
|
30738 | var section = this._sections[i];
|
30739 | var sectionMappings = section.consumer._generatedMappings;
|
30740 | for (var j = 0; j < sectionMappings.length; j++) {
|
30741 | var mapping = sectionMappings[j];
|
30742 |
|
30743 | var source = section.consumer._sources.at(mapping.source);
|
30744 | if (section.consumer.sourceRoot !== null) {
|
30745 | source = util$1.join(section.consumer.sourceRoot, source);
|
30746 | }
|
30747 | this._sources.add(source);
|
30748 | source = this._sources.indexOf(source);
|
30749 |
|
30750 | var name = section.consumer._names.at(mapping.name);
|
30751 | this._names.add(name);
|
30752 | name = this._names.indexOf(name);
|
30753 |
|
30754 | // The mappings coming from the consumer for the section have
|
30755 | // generated positions relative to the start of the section, so we
|
30756 | // need to offset them to be relative to the start of the concatenated
|
30757 | // generated file.
|
30758 | var adjustedMapping = {
|
30759 | source: source,
|
30760 | generatedLine: mapping.generatedLine +
|
30761 | (section.generatedOffset.generatedLine - 1),
|
30762 | generatedColumn: mapping.generatedColumn +
|
30763 | (section.generatedOffset.generatedLine === mapping.generatedLine
|
30764 | ? section.generatedOffset.generatedColumn - 1
|
30765 | : 0),
|
30766 | originalLine: mapping.originalLine,
|
30767 | originalColumn: mapping.originalColumn,
|
30768 | name: name
|
30769 | };
|
30770 |
|
30771 | this.__generatedMappings.push(adjustedMapping);
|
30772 | if (typeof adjustedMapping.originalLine === 'number') {
|
30773 | this.__originalMappings.push(adjustedMapping);
|
30774 | }
|
30775 | }
|
30776 | }
|
30777 |
|
30778 | quickSort$1(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
|
30779 | quickSort$1(this.__originalMappings, util$1.compareByOriginalPositions);
|
30780 | };
|
30781 |
|
30782 | var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
|
30783 |
|
30784 | var sourceMapConsumer = {
|
30785 | SourceMapConsumer: SourceMapConsumer_1,
|
30786 | BasicSourceMapConsumer: BasicSourceMapConsumer_1,
|
30787 | IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
|
30788 | };
|
30789 |
|
30790 | /* -*- Mode: js; js-indent-level: 2; -*- */
|
30791 | /*
|
30792 | * Copyright 2011 Mozilla Foundation and contributors
|
30793 | * Licensed under the New BSD license. See LICENSE or:
|
30794 | * http://opensource.org/licenses/BSD-3-Clause
|
30795 | */
|
30796 |
|
30797 | var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
|
30798 |
|
30799 |
|
30800 | // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
|
30801 | // operating systems these days (capturing the result).
|
30802 | var REGEX_NEWLINE = /(\r?\n)/;
|
30803 |
|
30804 | // Newline character code for charCodeAt() comparisons
|
30805 | var NEWLINE_CODE = 10;
|
30806 |
|
30807 | // Private symbol for identifying `SourceNode`s when multiple versions of
|
30808 | // the source-map library are loaded. This MUST NOT CHANGE across
|
30809 | // versions!
|
30810 | var isSourceNode = "$$$isSourceNode$$$";
|
30811 |
|
30812 | /**
|
30813 | * SourceNodes provide a way to abstract over interpolating/concatenating
|
30814 | * snippets of generated JavaScript source code while maintaining the line and
|
30815 | * column information associated with the original source code.
|
30816 | *
|
30817 | * @param aLine The original line number.
|
30818 | * @param aColumn The original column number.
|
30819 | * @param aSource The original source's filename.
|
30820 | * @param aChunks Optional. An array of strings which are snippets of
|
30821 | * generated JS, or other SourceNodes.
|
30822 | * @param aName The original identifier.
|
30823 | */
|
30824 | function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
|
30825 | this.children = [];
|
30826 | this.sourceContents = {};
|
30827 | this.line = aLine == null ? null : aLine;
|
30828 | this.column = aColumn == null ? null : aColumn;
|
30829 | this.source = aSource == null ? null : aSource;
|
30830 | this.name = aName == null ? null : aName;
|
30831 | this[isSourceNode] = true;
|
30832 | if (aChunks != null) this.add(aChunks);
|
30833 | }
|
30834 |
|
30835 | /**
|
30836 | * Creates a SourceNode from generated code and a SourceMapConsumer.
|
30837 | *
|
30838 | * @param aGeneratedCode The generated code
|
30839 | * @param aSourceMapConsumer The SourceMap for the generated code
|
30840 | * @param aRelativePath Optional. The path that relative sources in the
|
30841 | * SourceMapConsumer should be relative to.
|
30842 | */
|
30843 | SourceNode.fromStringWithSourceMap =
|
30844 | function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
|
30845 | // The SourceNode we want to fill with the generated code
|
30846 | // and the SourceMap
|
30847 | var node = new SourceNode();
|
30848 |
|
30849 | // All even indices of this array are one line of the generated code,
|
30850 | // while all odd indices are the newlines between two adjacent lines
|
30851 | // (since `REGEX_NEWLINE` captures its match).
|
30852 | // Processed fragments are accessed by calling `shiftNextLine`.
|
30853 | var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
|
30854 | var remainingLinesIndex = 0;
|
30855 | var shiftNextLine = function() {
|
30856 | var lineContents = getNextLine();
|
30857 | // The last line of a file might not have a newline.
|
30858 | var newLine = getNextLine() || "";
|
30859 | return lineContents + newLine;
|
30860 |
|
30861 | function getNextLine() {
|
30862 | return remainingLinesIndex < remainingLines.length ?
|
30863 | remainingLines[remainingLinesIndex++] : undefined;
|
30864 | }
|
30865 | };
|
30866 |
|
30867 | // We need to remember the position of "remainingLines"
|
30868 | var lastGeneratedLine = 1, lastGeneratedColumn = 0;
|
30869 |
|
30870 | // The generate SourceNodes we need a code range.
|
30871 | // To extract it current and last mapping is used.
|
30872 | // Here we store the last mapping.
|
30873 | var lastMapping = null;
|
30874 |
|
30875 | aSourceMapConsumer.eachMapping(function (mapping) {
|
30876 | if (lastMapping !== null) {
|
30877 | // We add the code from "lastMapping" to "mapping":
|
30878 | // First check if there is a new line in between.
|
30879 | if (lastGeneratedLine < mapping.generatedLine) {
|
30880 | // Associate first line with "lastMapping"
|
30881 | addMappingWithCode(lastMapping, shiftNextLine());
|
30882 | lastGeneratedLine++;
|
30883 | lastGeneratedColumn = 0;
|
30884 | // The remaining code is added without mapping
|
30885 | } else {
|
30886 | // There is no new line in between.
|
30887 | // Associate the code between "lastGeneratedColumn" and
|
30888 | // "mapping.generatedColumn" with "lastMapping"
|
30889 | var nextLine = remainingLines[remainingLinesIndex];
|
30890 | var code = nextLine.substr(0, mapping.generatedColumn -
|
30891 | lastGeneratedColumn);
|
30892 | remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
|
30893 | lastGeneratedColumn);
|
30894 | lastGeneratedColumn = mapping.generatedColumn;
|
30895 | addMappingWithCode(lastMapping, code);
|
30896 | // No more remaining code, continue
|
30897 | lastMapping = mapping;
|
30898 | return;
|
30899 | }
|
30900 | }
|
30901 | // We add the generated code until the first mapping
|
30902 | // to the SourceNode without any mapping.
|
30903 | // Each line is added as separate string.
|
30904 | while (lastGeneratedLine < mapping.generatedLine) {
|
30905 | node.add(shiftNextLine());
|
30906 | lastGeneratedLine++;
|
30907 | }
|
30908 | if (lastGeneratedColumn < mapping.generatedColumn) {
|
30909 | var nextLine = remainingLines[remainingLinesIndex];
|
30910 | node.add(nextLine.substr(0, mapping.generatedColumn));
|
30911 | remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
|
30912 | lastGeneratedColumn = mapping.generatedColumn;
|
30913 | }
|
30914 | lastMapping = mapping;
|
30915 | }, this);
|
30916 | // We have processed all mappings.
|
30917 | if (remainingLinesIndex < remainingLines.length) {
|
30918 | if (lastMapping) {
|
30919 | // Associate the remaining code in the current line with "lastMapping"
|
30920 | addMappingWithCode(lastMapping, shiftNextLine());
|
30921 | }
|
30922 | // and add the remaining lines without any mapping
|
30923 | node.add(remainingLines.splice(remainingLinesIndex).join(""));
|
30924 | }
|
30925 |
|
30926 | // Copy sourcesContent into SourceNode
|
30927 | aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
30928 | var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
30929 | if (content != null) {
|
30930 | if (aRelativePath != null) {
|
30931 | sourceFile = util$1.join(aRelativePath, sourceFile);
|
30932 | }
|
30933 | node.setSourceContent(sourceFile, content);
|
30934 | }
|
30935 | });
|
30936 |
|
30937 | return node;
|
30938 |
|
30939 | function addMappingWithCode(mapping, code) {
|
30940 | if (mapping === null || mapping.source === undefined) {
|
30941 | node.add(code);
|
30942 | } else {
|
30943 | var source = aRelativePath
|
30944 | ? util$1.join(aRelativePath, mapping.source)
|
30945 | : mapping.source;
|
30946 | node.add(new SourceNode(mapping.originalLine,
|
30947 | mapping.originalColumn,
|
30948 | source,
|
30949 | code,
|
30950 | mapping.name));
|
30951 | }
|
30952 | }
|
30953 | };
|
30954 |
|
30955 | /**
|
30956 | * Add a chunk of generated JS to this source node.
|
30957 | *
|
30958 | * @param aChunk A string snippet of generated JS code, another instance of
|
30959 | * SourceNode, or an array where each member is one of those things.
|
30960 | */
|
30961 | SourceNode.prototype.add = function SourceNode_add(aChunk) {
|
30962 | if (Array.isArray(aChunk)) {
|
30963 | aChunk.forEach(function (chunk) {
|
30964 | this.add(chunk);
|
30965 | }, this);
|
30966 | }
|
30967 | else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
30968 | if (aChunk) {
|
30969 | this.children.push(aChunk);
|
30970 | }
|
30971 | }
|
30972 | else {
|
30973 | throw new TypeError(
|
30974 | "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
30975 | );
|
30976 | }
|
30977 | return this;
|
30978 | };
|
30979 |
|
30980 | /**
|
30981 | * Add a chunk of generated JS to the beginning of this source node.
|
30982 | *
|
30983 | * @param aChunk A string snippet of generated JS code, another instance of
|
30984 | * SourceNode, or an array where each member is one of those things.
|
30985 | */
|
30986 | SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
|
30987 | if (Array.isArray(aChunk)) {
|
30988 | for (var i = aChunk.length-1; i >= 0; i--) {
|
30989 | this.prepend(aChunk[i]);
|
30990 | }
|
30991 | }
|
30992 | else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
30993 | this.children.unshift(aChunk);
|
30994 | }
|
30995 | else {
|
30996 | throw new TypeError(
|
30997 | "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
30998 | );
|
30999 | }
|
31000 | return this;
|
31001 | };
|
31002 |
|
31003 | /**
|
31004 | * Walk over the tree of JS snippets in this node and its children. The
|
31005 | * walking function is called once for each snippet of JS and is passed that
|
31006 | * snippet and the its original associated source's line/column location.
|
31007 | *
|
31008 | * @param aFn The traversal function.
|
31009 | */
|
31010 | SourceNode.prototype.walk = function SourceNode_walk(aFn) {
|
31011 | var chunk;
|
31012 | for (var i = 0, len = this.children.length; i < len; i++) {
|
31013 | chunk = this.children[i];
|
31014 | if (chunk[isSourceNode]) {
|
31015 | chunk.walk(aFn);
|
31016 | }
|
31017 | else {
|
31018 | if (chunk !== '') {
|
31019 | aFn(chunk, { source: this.source,
|
31020 | line: this.line,
|
31021 | column: this.column,
|
31022 | name: this.name });
|
31023 | }
|
31024 | }
|
31025 | }
|
31026 | };
|
31027 |
|
31028 | /**
|
31029 | * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
|
31030 | * each of `this.children`.
|
31031 | *
|
31032 | * @param aSep The separator.
|
31033 | */
|
31034 | SourceNode.prototype.join = function SourceNode_join(aSep) {
|
31035 | var newChildren;
|
31036 | var i;
|
31037 | var len = this.children.length;
|
31038 | if (len > 0) {
|
31039 | newChildren = [];
|
31040 | for (i = 0; i < len-1; i++) {
|
31041 | newChildren.push(this.children[i]);
|
31042 | newChildren.push(aSep);
|
31043 | }
|
31044 | newChildren.push(this.children[i]);
|
31045 | this.children = newChildren;
|
31046 | }
|
31047 | return this;
|
31048 | };
|
31049 |
|
31050 | /**
|
31051 | * Call String.prototype.replace on the very right-most source snippet. Useful
|
31052 | * for trimming whitespace from the end of a source node, etc.
|
31053 | *
|
31054 | * @param aPattern The pattern to replace.
|
31055 | * @param aReplacement The thing to replace the pattern with.
|
31056 | */
|
31057 | SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
|
31058 | var lastChild = this.children[this.children.length - 1];
|
31059 | if (lastChild[isSourceNode]) {
|
31060 | lastChild.replaceRight(aPattern, aReplacement);
|
31061 | }
|
31062 | else if (typeof lastChild === 'string') {
|
31063 | this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
|
31064 | }
|
31065 | else {
|
31066 | this.children.push(''.replace(aPattern, aReplacement));
|
31067 | }
|
31068 | return this;
|
31069 | };
|
31070 |
|
31071 | /**
|
31072 | * Set the source content for a source file. This will be added to the SourceMapGenerator
|
31073 | * in the sourcesContent field.
|
31074 | *
|
31075 | * @param aSourceFile The filename of the source file
|
31076 | * @param aSourceContent The content of the source file
|
31077 | */
|
31078 | SourceNode.prototype.setSourceContent =
|
31079 | function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
|
31080 | this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
|
31081 | };
|
31082 |
|
31083 | /**
|
31084 | * Walk over the tree of SourceNodes. The walking function is called for each
|
31085 | * source file content and is passed the filename and source content.
|
31086 | *
|
31087 | * @param aFn The traversal function.
|
31088 | */
|
31089 | SourceNode.prototype.walkSourceContents =
|
31090 | function SourceNode_walkSourceContents(aFn) {
|
31091 | for (var i = 0, len = this.children.length; i < len; i++) {
|
31092 | if (this.children[i][isSourceNode]) {
|
31093 | this.children[i].walkSourceContents(aFn);
|
31094 | }
|
31095 | }
|
31096 |
|
31097 | var sources = Object.keys(this.sourceContents);
|
31098 | for (var i = 0, len = sources.length; i < len; i++) {
|
31099 | aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
|
31100 | }
|
31101 | };
|
31102 |
|
31103 | /**
|
31104 | * Return the string representation of this source node. Walks over the tree
|
31105 | * and concatenates all the various snippets together to one string.
|
31106 | */
|
31107 | SourceNode.prototype.toString = function SourceNode_toString() {
|
31108 | var str = "";
|
31109 | this.walk(function (chunk) {
|
31110 | str += chunk;
|
31111 | });
|
31112 | return str;
|
31113 | };
|
31114 |
|
31115 | /**
|
31116 | * Returns the string representation of this source node along with a source
|
31117 | * map.
|
31118 | */
|
31119 | SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
|
31120 | var generated = {
|
31121 | code: "",
|
31122 | line: 1,
|
31123 | column: 0
|
31124 | };
|
31125 | var map = new SourceMapGenerator$1(aArgs);
|
31126 | var sourceMappingActive = false;
|
31127 | var lastOriginalSource = null;
|
31128 | var lastOriginalLine = null;
|
31129 | var lastOriginalColumn = null;
|
31130 | var lastOriginalName = null;
|
31131 | this.walk(function (chunk, original) {
|
31132 | generated.code += chunk;
|
31133 | if (original.source !== null
|
31134 | && original.line !== null
|
31135 | && original.column !== null) {
|
31136 | if(lastOriginalSource !== original.source
|
31137 | || lastOriginalLine !== original.line
|
31138 | || lastOriginalColumn !== original.column
|
31139 | || lastOriginalName !== original.name) {
|
31140 | map.addMapping({
|
31141 | source: original.source,
|
31142 | original: {
|
31143 | line: original.line,
|
31144 | column: original.column
|
31145 | },
|
31146 | generated: {
|
31147 | line: generated.line,
|
31148 | column: generated.column
|
31149 | },
|
31150 | name: original.name
|
31151 | });
|
31152 | }
|
31153 | lastOriginalSource = original.source;
|
31154 | lastOriginalLine = original.line;
|
31155 | lastOriginalColumn = original.column;
|
31156 | lastOriginalName = original.name;
|
31157 | sourceMappingActive = true;
|
31158 | } else if (sourceMappingActive) {
|
31159 | map.addMapping({
|
31160 | generated: {
|
31161 | line: generated.line,
|
31162 | column: generated.column
|
31163 | }
|
31164 | });
|
31165 | lastOriginalSource = null;
|
31166 | sourceMappingActive = false;
|
31167 | }
|
31168 | for (var idx = 0, length = chunk.length; idx < length; idx++) {
|
31169 | if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
|
31170 | generated.line++;
|
31171 | generated.column = 0;
|
31172 | // Mappings end at eol
|
31173 | if (idx + 1 === length) {
|
31174 | lastOriginalSource = null;
|
31175 | sourceMappingActive = false;
|
31176 | } else if (sourceMappingActive) {
|
31177 | map.addMapping({
|
31178 | source: original.source,
|
31179 | original: {
|
31180 | line: original.line,
|
31181 | column: original.column
|
31182 | },
|
31183 | generated: {
|
31184 | line: generated.line,
|
31185 | column: generated.column
|
31186 | },
|
31187 | name: original.name
|
31188 | });
|
31189 | }
|
31190 | } else {
|
31191 | generated.column++;
|
31192 | }
|
31193 | }
|
31194 | });
|
31195 | this.walkSourceContents(function (sourceFile, sourceContent) {
|
31196 | map.setSourceContent(sourceFile, sourceContent);
|
31197 | });
|
31198 |
|
31199 | return { code: generated.code, map: map };
|
31200 | };
|
31201 |
|
31202 | var SourceNode_1 = SourceNode;
|
31203 |
|
31204 | var sourceNode = {
|
31205 | SourceNode: SourceNode_1
|
31206 | };
|
31207 |
|
31208 | /*
|
31209 | * Copyright 2009-2011 Mozilla Foundation and contributors
|
31210 | * Licensed under the New BSD license. See LICENSE.txt or:
|
31211 | * http://opensource.org/licenses/BSD-3-Clause
|
31212 | */
|
31213 | var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
|
31214 | var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
|
31215 | var SourceNode$1 = sourceNode.SourceNode;
|
31216 |
|
31217 | var sourceMap = {
|
31218 | SourceMapGenerator: SourceMapGenerator$2,
|
31219 | SourceMapConsumer: SourceMapConsumer$1,
|
31220 | SourceNode: SourceNode$1
|
31221 | };
|
31222 |
|
31223 | var sourceMapUrl = createCommonjsModule(function (module, exports) {
|
31224 | // Copyright 2014 Simon Lydell
|
31225 | // X11 (“MIT”) Licensed. (See LICENSE.)
|
31226 |
|
31227 | void (function(root, factory) {
|
31228 | {
|
31229 | module.exports = factory();
|
31230 | }
|
31231 | }(commonjsGlobal, function() {
|
31232 |
|
31233 | var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
|
31234 |
|
31235 | var regex = RegExp(
|
31236 | "(?:" +
|
31237 | "/\\*" +
|
31238 | "(?:\\s*\r?\n(?://)?)?" +
|
31239 | "(?:" + innerRegex.source + ")" +
|
31240 | "\\s*" +
|
31241 | "\\*/" +
|
31242 | "|" +
|
31243 | "//(?:" + innerRegex.source + ")" +
|
31244 | ")" +
|
31245 | "\\s*"
|
31246 | );
|
31247 |
|
31248 | return {
|
31249 |
|
31250 | regex: regex,
|
31251 | _innerRegex: innerRegex,
|
31252 |
|
31253 | getFrom: function(code) {
|
31254 | var match = code.match(regex);
|
31255 | return (match ? match[1] || match[2] || "" : null)
|
31256 | },
|
31257 |
|
31258 | existsIn: function(code) {
|
31259 | return regex.test(code)
|
31260 | },
|
31261 |
|
31262 | removeFrom: function(code) {
|
31263 | return code.replace(regex, "")
|
31264 | },
|
31265 |
|
31266 | insertBefore: function(code, string) {
|
31267 | var match = code.match(regex);
|
31268 | if (match) {
|
31269 | return code.slice(0, match.index) + string + code.slice(match.index)
|
31270 | } else {
|
31271 | return code + string
|
31272 | }
|
31273 | }
|
31274 | }
|
31275 |
|
31276 | }));
|
31277 | });
|
31278 |
|
31279 | // Copyright 2014 Simon Lydell
|
31280 | // X11 (“MIT”) Licensed. (See LICENSE.)
|
31281 |
|
31282 |
|
31283 |
|
31284 | function resolveUrl(/* ...urls */) {
|
31285 | return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) {
|
31286 | return url.resolve(resolved, nextUrl)
|
31287 | })
|
31288 | }
|
31289 |
|
31290 | var resolveUrl_1 = resolveUrl;
|
31291 |
|
31292 | var token = '%[a-f0-9]{2}';
|
31293 | var singleMatcher = new RegExp(token, 'gi');
|
31294 | var multiMatcher = new RegExp('(' + token + ')+', 'gi');
|
31295 |
|
31296 | function decodeComponents(components, split) {
|
31297 | try {
|
31298 | // Try to decode the entire string first
|
31299 | return decodeURIComponent(components.join(''));
|
31300 | } catch (err) {
|
31301 | // Do nothing
|
31302 | }
|
31303 |
|
31304 | if (components.length === 1) {
|
31305 | return components;
|
31306 | }
|
31307 |
|
31308 | split = split || 1;
|
31309 |
|
31310 | // Split the array in 2 parts
|
31311 | var left = components.slice(0, split);
|
31312 | var right = components.slice(split);
|
31313 |
|
31314 | return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
|
31315 | }
|
31316 |
|
31317 | function decode$3(input) {
|
31318 | try {
|
31319 | return decodeURIComponent(input);
|
31320 | } catch (err) {
|
31321 | var tokens = input.match(singleMatcher);
|
31322 |
|
31323 | for (var i = 1; i < tokens.length; i++) {
|
31324 | input = decodeComponents(tokens, i).join('');
|
31325 |
|
31326 | tokens = input.match(singleMatcher);
|
31327 | }
|
31328 |
|
31329 | return input;
|
31330 | }
|
31331 | }
|
31332 |
|
31333 | function customDecodeURIComponent(input) {
|
31334 | // Keep track of all the replacements and prefill the map with the `BOM`
|
31335 | var replaceMap = {
|
31336 | '%FE%FF': '\uFFFD\uFFFD',
|
31337 | '%FF%FE': '\uFFFD\uFFFD'
|
31338 | };
|
31339 |
|
31340 | var match = multiMatcher.exec(input);
|
31341 | while (match) {
|
31342 | try {
|
31343 | // Decode as big chunks as possible
|
31344 | replaceMap[match[0]] = decodeURIComponent(match[0]);
|
31345 | } catch (err) {
|
31346 | var result = decode$3(match[0]);
|
31347 |
|
31348 | if (result !== match[0]) {
|
31349 | replaceMap[match[0]] = result;
|
31350 | }
|
31351 | }
|
31352 |
|
31353 | match = multiMatcher.exec(input);
|
31354 | }
|
31355 |
|
31356 | // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
|
31357 | replaceMap['%C2'] = '\uFFFD';
|
31358 |
|
31359 | var entries = Object.keys(replaceMap);
|
31360 |
|
31361 | for (var i = 0; i < entries.length; i++) {
|
31362 | // Replace all decoded components
|
31363 | var key = entries[i];
|
31364 | input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
|
31365 | }
|
31366 |
|
31367 | return input;
|
31368 | }
|
31369 |
|
31370 | var decodeUriComponent = function (encodedURI) {
|
31371 | if (typeof encodedURI !== 'string') {
|
31372 | throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
|
31373 | }
|
31374 |
|
31375 | try {
|
31376 | encodedURI = encodedURI.replace(/\+/g, ' ');
|
31377 |
|
31378 | // Try the built in decoder first
|
31379 | return decodeURIComponent(encodedURI);
|
31380 | } catch (err) {
|
31381 | // Fallback to a more advanced decoder
|
31382 | return customDecodeURIComponent(encodedURI);
|
31383 | }
|
31384 | };
|
31385 |
|
31386 | // Copyright 2017 Simon Lydell
|
31387 | // X11 (“MIT”) Licensed. (See LICENSE.)
|
31388 |
|
31389 |
|
31390 |
|
31391 | function customDecodeUriComponent(string) {
|
31392 | // `decodeUriComponent` turns `+` into ` `, but that's not wanted.
|
31393 | return decodeUriComponent(string.replace(/\+/g, "%2B"))
|
31394 | }
|
31395 |
|
31396 | var decodeUriComponent_1 = customDecodeUriComponent;
|
31397 |
|
31398 | function urix(aPath) {
|
31399 | if (path__default.sep === "\\") {
|
31400 | return aPath
|
31401 | .replace(/\\/g, "/")
|
31402 | .replace(/^[a-z]:\/?/i, "/")
|
31403 | }
|
31404 | return aPath
|
31405 | }
|
31406 |
|
31407 | var urix_1 = urix;
|
31408 |
|
31409 | function atob(str) {
|
31410 | return Buffer.from(str, 'base64').toString('binary');
|
31411 | }
|
31412 |
|
31413 | var nodeAtob = atob.atob = atob;
|
31414 |
|
31415 | // Copyright 2014, 2015, 2016, 2017 Simon Lydell
|
31416 | // X11 (“MIT”) Licensed. (See LICENSE.)
|
31417 |
|
31418 |
|
31419 |
|
31420 |
|
31421 |
|
31422 |
|
31423 |
|
31424 |
|
31425 |
|
31426 | function callbackAsync(callback, error, result) {
|
31427 | setImmediate(function() { callback(error, result); });
|
31428 | }
|
31429 |
|
31430 | function parseMapToJSON(string, data) {
|
31431 | try {
|
31432 | return JSON.parse(string.replace(/^\)\]\}'/, ""))
|
31433 | } catch (error) {
|
31434 | error.sourceMapData = data;
|
31435 | throw error
|
31436 | }
|
31437 | }
|
31438 |
|
31439 | function readSync(read, url, data) {
|
31440 | var readUrl = decodeUriComponent_1(url);
|
31441 | try {
|
31442 | return String(read(readUrl))
|
31443 | } catch (error) {
|
31444 | error.sourceMapData = data;
|
31445 | throw error
|
31446 | }
|
31447 | }
|
31448 |
|
31449 |
|
31450 |
|
31451 | function resolveSourceMap(code, codeUrl, read, callback) {
|
31452 | var mapData;
|
31453 | try {
|
31454 | mapData = resolveSourceMapHelper(code, codeUrl);
|
31455 | } catch (error) {
|
31456 | return callbackAsync(callback, error)
|
31457 | }
|
31458 | if (!mapData || mapData.map) {
|
31459 | return callbackAsync(callback, null, mapData)
|
31460 | }
|
31461 | var readUrl = decodeUriComponent_1(mapData.url);
|
31462 | read(readUrl, function(error, result) {
|
31463 | if (error) {
|
31464 | error.sourceMapData = mapData;
|
31465 | return callback(error)
|
31466 | }
|
31467 | mapData.map = String(result);
|
31468 | try {
|
31469 | mapData.map = parseMapToJSON(mapData.map, mapData);
|
31470 | } catch (error) {
|
31471 | return callback(error)
|
31472 | }
|
31473 | callback(null, mapData);
|
31474 | });
|
31475 | }
|
31476 |
|
31477 | function resolveSourceMapSync(code, codeUrl, read) {
|
31478 | var mapData = resolveSourceMapHelper(code, codeUrl);
|
31479 | if (!mapData || mapData.map) {
|
31480 | return mapData
|
31481 | }
|
31482 | mapData.map = readSync(read, mapData.url, mapData);
|
31483 | mapData.map = parseMapToJSON(mapData.map, mapData);
|
31484 | return mapData
|
31485 | }
|
31486 |
|
31487 | var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/;
|
31488 | var jsonMimeTypeRegex = /^(?:application|text)\/json$/;
|
31489 |
|
31490 | function resolveSourceMapHelper(code, codeUrl) {
|
31491 | codeUrl = urix_1(codeUrl);
|
31492 |
|
31493 | var url = sourceMapUrl.getFrom(code);
|
31494 | if (!url) {
|
31495 | return null
|
31496 | }
|
31497 |
|
31498 | var dataUri = url.match(dataUriRegex);
|
31499 | if (dataUri) {
|
31500 | var mimeType = dataUri[1];
|
31501 | var lastParameter = dataUri[2] || "";
|
31502 | var encoded = dataUri[3] || "";
|
31503 | var data = {
|
31504 | sourceMappingURL: url,
|
31505 | url: null,
|
31506 | sourcesRelativeTo: codeUrl,
|
31507 | map: encoded
|
31508 | };
|
31509 | if (!jsonMimeTypeRegex.test(mimeType)) {
|
31510 | var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain"));
|
31511 | error.sourceMapData = data;
|
31512 | throw error
|
31513 | }
|
31514 | data.map = parseMapToJSON(
|
31515 | lastParameter === ";base64" ? nodeAtob(encoded) : decodeURIComponent(encoded),
|
31516 | data
|
31517 | );
|
31518 | return data
|
31519 | }
|
31520 |
|
31521 | var mapUrl = resolveUrl_1(codeUrl, url);
|
31522 | return {
|
31523 | sourceMappingURL: url,
|
31524 | url: mapUrl,
|
31525 | sourcesRelativeTo: mapUrl,
|
31526 | map: null
|
31527 | }
|
31528 | }
|
31529 |
|
31530 |
|
31531 |
|
31532 | function resolveSources(map, mapUrl, read, options, callback) {
|
31533 | if (typeof options === "function") {
|
31534 | callback = options;
|
31535 | options = {};
|
31536 | }
|
31537 | var pending = map.sources ? map.sources.length : 0;
|
31538 | var result = {
|
31539 | sourcesResolved: [],
|
31540 | sourcesContent: []
|
31541 | };
|
31542 |
|
31543 | if (pending === 0) {
|
31544 | callbackAsync(callback, null, result);
|
31545 | return
|
31546 | }
|
31547 |
|
31548 | var done = function() {
|
31549 | pending--;
|
31550 | if (pending === 0) {
|
31551 | callback(null, result);
|
31552 | }
|
31553 | };
|
31554 |
|
31555 | resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
|
31556 | result.sourcesResolved[index] = fullUrl;
|
31557 | if (typeof sourceContent === "string") {
|
31558 | result.sourcesContent[index] = sourceContent;
|
31559 | callbackAsync(done, null);
|
31560 | } else {
|
31561 | var readUrl = decodeUriComponent_1(fullUrl);
|
31562 | read(readUrl, function(error, source) {
|
31563 | result.sourcesContent[index] = error ? error : String(source);
|
31564 | done();
|
31565 | });
|
31566 | }
|
31567 | });
|
31568 | }
|
31569 |
|
31570 | function resolveSourcesSync(map, mapUrl, read, options) {
|
31571 | var result = {
|
31572 | sourcesResolved: [],
|
31573 | sourcesContent: []
|
31574 | };
|
31575 |
|
31576 | if (!map.sources || map.sources.length === 0) {
|
31577 | return result
|
31578 | }
|
31579 |
|
31580 | resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
|
31581 | result.sourcesResolved[index] = fullUrl;
|
31582 | if (read !== null) {
|
31583 | if (typeof sourceContent === "string") {
|
31584 | result.sourcesContent[index] = sourceContent;
|
31585 | } else {
|
31586 | var readUrl = decodeUriComponent_1(fullUrl);
|
31587 | try {
|
31588 | result.sourcesContent[index] = String(read(readUrl));
|
31589 | } catch (error) {
|
31590 | result.sourcesContent[index] = error;
|
31591 | }
|
31592 | }
|
31593 | }
|
31594 | });
|
31595 |
|
31596 | return result
|
31597 | }
|
31598 |
|
31599 | var endingSlash = /\/?$/;
|
31600 |
|
31601 | function resolveSourcesHelper(map, mapUrl, options, fn) {
|
31602 | options = options || {};
|
31603 | mapUrl = urix_1(mapUrl);
|
31604 | var fullUrl;
|
31605 | var sourceContent;
|
31606 | var sourceRoot;
|
31607 | for (var index = 0, len = map.sources.length; index < len; index++) {
|
31608 | sourceRoot = null;
|
31609 | if (typeof options.sourceRoot === "string") {
|
31610 | sourceRoot = options.sourceRoot;
|
31611 | } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) {
|
31612 | sourceRoot = map.sourceRoot;
|
31613 | }
|
31614 | // If the sourceRoot is the empty string, it is equivalent to not setting
|
31615 | // the property at all.
|
31616 | if (sourceRoot === null || sourceRoot === '') {
|
31617 | fullUrl = resolveUrl_1(mapUrl, map.sources[index]);
|
31618 | } else {
|
31619 | // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes
|
31620 | // `/scripts/subdir/<source>`, not `/scripts/<source>`. Pointing to a file as source root
|
31621 | // does not make sense.
|
31622 | fullUrl = resolveUrl_1(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]);
|
31623 | }
|
31624 | sourceContent = (map.sourcesContent || [])[index];
|
31625 | fn(fullUrl, sourceContent, index);
|
31626 | }
|
31627 | }
|
31628 |
|
31629 |
|
31630 |
|
31631 | function resolve(code, codeUrl, read, options, callback) {
|
31632 | if (typeof options === "function") {
|
31633 | callback = options;
|
31634 | options = {};
|
31635 | }
|
31636 | if (code === null) {
|
31637 | var mapUrl = codeUrl;
|
31638 | var data = {
|
31639 | sourceMappingURL: null,
|
31640 | url: mapUrl,
|
31641 | sourcesRelativeTo: mapUrl,
|
31642 | map: null
|
31643 | };
|
31644 | var readUrl = decodeUriComponent_1(mapUrl);
|
31645 | read(readUrl, function(error, result) {
|
31646 | if (error) {
|
31647 | error.sourceMapData = data;
|
31648 | return callback(error)
|
31649 | }
|
31650 | data.map = String(result);
|
31651 | try {
|
31652 | data.map = parseMapToJSON(data.map, data);
|
31653 | } catch (error) {
|
31654 | return callback(error)
|
31655 | }
|
31656 | _resolveSources(data);
|
31657 | });
|
31658 | } else {
|
31659 | resolveSourceMap(code, codeUrl, read, function(error, mapData) {
|
31660 | if (error) {
|
31661 | return callback(error)
|
31662 | }
|
31663 | if (!mapData) {
|
31664 | return callback(null, null)
|
31665 | }
|
31666 | _resolveSources(mapData);
|
31667 | });
|
31668 | }
|
31669 |
|
31670 | function _resolveSources(mapData) {
|
31671 | resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) {
|
31672 | if (error) {
|
31673 | return callback(error)
|
31674 | }
|
31675 | mapData.sourcesResolved = result.sourcesResolved;
|
31676 | mapData.sourcesContent = result.sourcesContent;
|
31677 | callback(null, mapData);
|
31678 | });
|
31679 | }
|
31680 | }
|
31681 |
|
31682 | function resolveSync(code, codeUrl, read, options) {
|
31683 | var mapData;
|
31684 | if (code === null) {
|
31685 | var mapUrl = codeUrl;
|
31686 | mapData = {
|
31687 | sourceMappingURL: null,
|
31688 | url: mapUrl,
|
31689 | sourcesRelativeTo: mapUrl,
|
31690 | map: null
|
31691 | };
|
31692 | mapData.map = readSync(read, mapUrl, mapData);
|
31693 | mapData.map = parseMapToJSON(mapData.map, mapData);
|
31694 | } else {
|
31695 | mapData = resolveSourceMapSync(code, codeUrl, read);
|
31696 | if (!mapData) {
|
31697 | return null
|
31698 | }
|
31699 | }
|
31700 | var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options);
|
31701 | mapData.sourcesResolved = result.sourcesResolved;
|
31702 | mapData.sourcesContent = result.sourcesContent;
|
31703 | return mapData
|
31704 | }
|
31705 |
|
31706 |
|
31707 |
|
31708 | var sourceMapResolveNode = {
|
31709 | resolveSourceMap: resolveSourceMap,
|
31710 | resolveSourceMapSync: resolveSourceMapSync,
|
31711 | resolveSources: resolveSources,
|
31712 | resolveSourcesSync: resolveSourcesSync,
|
31713 | resolve: resolve,
|
31714 | resolveSync: resolveSync,
|
31715 | parseMapToJSON: parseMapToJSON
|
31716 | };
|
31717 |
|
31718 | /**
|
31719 | * Module dependencies
|
31720 | */
|
31721 |
|
31722 | var extend$1 = extendShallow$5;
|
31723 | var SourceMap$1 = sourceMap;
|
31724 | var sourceMapResolve = sourceMapResolveNode;
|
31725 |
|
31726 | /**
|
31727 | * Convert backslash in the given string to forward slashes
|
31728 | */
|
31729 |
|
31730 | var unixify = function(fp) {
|
31731 | return fp.split(/\\+/).join('/');
|
31732 | };
|
31733 |
|
31734 | /**
|
31735 | * Return true if `val` is a non-empty string
|
31736 | *
|
31737 | * @param {String} `str`
|
31738 | * @return {Boolean}
|
31739 | */
|
31740 |
|
31741 | var isString$1 = function(str) {
|
31742 | return str && typeof str === 'string';
|
31743 | };
|
31744 |
|
31745 | /**
|
31746 | * Cast `val` to an array
|
31747 | * @return {Array}
|
31748 | */
|
31749 |
|
31750 | var arrayify$3 = function(val) {
|
31751 | if (typeof val === 'string') return [val];
|
31752 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
31753 | };
|
31754 |
|
31755 | /**
|
31756 | * Get the last `n` element from the given `array`
|
31757 | * @param {Array} `array`
|
31758 | * @return {*}
|
31759 | */
|
31760 |
|
31761 | var last = function(arr, n) {
|
31762 | return arr[arr.length - (n || 1)];
|
31763 | };
|
31764 |
|
31765 | var utils$1 = {
|
31766 | extend: extend$1,
|
31767 | SourceMap: SourceMap$1,
|
31768 | sourceMapResolve: sourceMapResolve,
|
31769 | unixify: unixify,
|
31770 | isString: isString$1,
|
31771 | arrayify: arrayify$3,
|
31772 | last: last
|
31773 | };
|
31774 |
|
31775 | var sourceMaps = createCommonjsModule(function (module, exports) {
|
31776 |
|
31777 |
|
31778 |
|
31779 |
|
31780 |
|
31781 |
|
31782 | /**
|
31783 | * Expose `mixin()`.
|
31784 | * This code is based on `source-maps-support.js` in reworkcss/css
|
31785 | * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js
|
31786 | * Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>
|
31787 | */
|
31788 |
|
31789 | module.exports = mixin;
|
31790 |
|
31791 | /**
|
31792 | * Mixin source map support into `compiler`.
|
31793 | *
|
31794 | * @param {Object} `compiler`
|
31795 | * @api public
|
31796 | */
|
31797 |
|
31798 | function mixin(compiler) {
|
31799 | defineProperty$6(compiler, '_comment', compiler.comment);
|
31800 | compiler.map = new utils$1.SourceMap.SourceMapGenerator();
|
31801 | compiler.position = { line: 1, column: 1 };
|
31802 | compiler.content = {};
|
31803 | compiler.files = {};
|
31804 |
|
31805 | for (var key in exports) {
|
31806 | defineProperty$6(compiler, key, exports[key]);
|
31807 | }
|
31808 | }
|
31809 |
|
31810 | /**
|
31811 | * Update position.
|
31812 | *
|
31813 | * @param {String} str
|
31814 | */
|
31815 |
|
31816 | exports.updatePosition = function(str) {
|
31817 | var lines = str.match(/\n/g);
|
31818 | if (lines) this.position.line += lines.length;
|
31819 | var i = str.lastIndexOf('\n');
|
31820 | this.position.column = ~i ? str.length - i : this.position.column + str.length;
|
31821 | };
|
31822 |
|
31823 | /**
|
31824 | * Emit `str` with `position`.
|
31825 | *
|
31826 | * @param {String} str
|
31827 | * @param {Object} [pos]
|
31828 | * @return {String}
|
31829 | */
|
31830 |
|
31831 | exports.emit = function(str, node) {
|
31832 | var position = node.position || {};
|
31833 | var source = position.source;
|
31834 | if (source) {
|
31835 | if (position.filepath) {
|
31836 | source = utils$1.unixify(position.filepath);
|
31837 | }
|
31838 |
|
31839 | this.map.addMapping({
|
31840 | source: source,
|
31841 | generated: {
|
31842 | line: this.position.line,
|
31843 | column: Math.max(this.position.column - 1, 0)
|
31844 | },
|
31845 | original: {
|
31846 | line: position.start.line,
|
31847 | column: position.start.column - 1
|
31848 | }
|
31849 | });
|
31850 |
|
31851 | if (position.content) {
|
31852 | this.addContent(source, position);
|
31853 | }
|
31854 | if (position.filepath) {
|
31855 | this.addFile(source, position);
|
31856 | }
|
31857 |
|
31858 | this.updatePosition(str);
|
31859 | this.output += str;
|
31860 | }
|
31861 | return str;
|
31862 | };
|
31863 |
|
31864 | /**
|
31865 | * Adds a file to the source map output if it has not already been added
|
31866 | * @param {String} `file`
|
31867 | * @param {Object} `pos`
|
31868 | */
|
31869 |
|
31870 | exports.addFile = function(file, position) {
|
31871 | if (typeof position.content !== 'string') return;
|
31872 | if (Object.prototype.hasOwnProperty.call(this.files, file)) return;
|
31873 | this.files[file] = position.content;
|
31874 | };
|
31875 |
|
31876 | /**
|
31877 | * Adds a content source to the source map output if it has not already been added
|
31878 | * @param {String} `source`
|
31879 | * @param {Object} `position`
|
31880 | */
|
31881 |
|
31882 | exports.addContent = function(source, position) {
|
31883 | if (typeof position.content !== 'string') return;
|
31884 | if (Object.prototype.hasOwnProperty.call(this.content, source)) return;
|
31885 | this.map.setSourceContent(source, position.content);
|
31886 | };
|
31887 |
|
31888 | /**
|
31889 | * Applies any original source maps to the output and embeds the source file
|
31890 | * contents in the source map.
|
31891 | */
|
31892 |
|
31893 | exports.applySourceMaps = function() {
|
31894 | Object.keys(this.files).forEach(function(file) {
|
31895 | var content = this.files[file];
|
31896 | this.map.setSourceContent(file, content);
|
31897 |
|
31898 | if (this.options.inputSourcemaps === true) {
|
31899 | var originalMap = utils$1.sourceMapResolve.resolveSync(content, file, fs__default.readFileSync);
|
31900 | if (originalMap) {
|
31901 | var map = new utils$1.SourceMap.SourceMapConsumer(originalMap.map);
|
31902 | var relativeTo = originalMap.sourcesRelativeTo;
|
31903 | this.map.applySourceMap(map, file, utils$1.unixify(path__default.dirname(relativeTo)));
|
31904 | }
|
31905 | }
|
31906 | }, this);
|
31907 | };
|
31908 |
|
31909 | /**
|
31910 | * Process comments, drops sourceMap comments.
|
31911 | * @param {Object} node
|
31912 | */
|
31913 |
|
31914 | exports.comment = function(node) {
|
31915 | if (/^# sourceMappingURL=/.test(node.comment)) {
|
31916 | return this.emit('', node.position);
|
31917 | }
|
31918 | return this._comment(node);
|
31919 | };
|
31920 | });
|
31921 |
|
31922 | var debug$1 = src('snapdragon:compiler');
|
31923 |
|
31924 |
|
31925 | /**
|
31926 | * Create a new `Compiler` with the given `options`.
|
31927 | * @param {Object} `options`
|
31928 | */
|
31929 |
|
31930 | function Compiler(options, state) {
|
31931 | debug$1('initializing', __filename);
|
31932 | this.options = utils$1.extend({source: 'string'}, options);
|
31933 | this.state = state || {};
|
31934 | this.compilers = {};
|
31935 | this.output = '';
|
31936 | this.set('eos', function(node) {
|
31937 | return this.emit(node.val, node);
|
31938 | });
|
31939 | this.set('noop', function(node) {
|
31940 | return this.emit(node.val, node);
|
31941 | });
|
31942 | this.set('bos', function(node) {
|
31943 | return this.emit(node.val, node);
|
31944 | });
|
31945 | use(this);
|
31946 | }
|
31947 |
|
31948 | /**
|
31949 | * Prototype methods
|
31950 | */
|
31951 |
|
31952 | Compiler.prototype = {
|
31953 |
|
31954 | /**
|
31955 | * Throw an error message with details including the cursor position.
|
31956 | * @param {String} `msg` Message to use in the Error.
|
31957 | */
|
31958 |
|
31959 | error: function(msg, node) {
|
31960 | var pos = node.position || {start: {column: 0}};
|
31961 | var message = this.options.source + ' column:' + pos.start.column + ': ' + msg;
|
31962 |
|
31963 | var err = new Error(message);
|
31964 | err.reason = msg;
|
31965 | err.column = pos.start.column;
|
31966 | err.source = this.pattern;
|
31967 |
|
31968 | if (this.options.silent) {
|
31969 | this.errors.push(err);
|
31970 | } else {
|
31971 | throw err;
|
31972 | }
|
31973 | },
|
31974 |
|
31975 | /**
|
31976 | * Define a non-enumberable property on the `Compiler` instance.
|
31977 | *
|
31978 | * ```js
|
31979 | * compiler.define('foo', 'bar');
|
31980 | * ```
|
31981 | * @name .define
|
31982 | * @param {String} `key` propery name
|
31983 | * @param {any} `val` property value
|
31984 | * @return {Object} Returns the Compiler instance for chaining.
|
31985 | * @api public
|
31986 | */
|
31987 |
|
31988 | define: function(key, val) {
|
31989 | defineProperty$6(this, key, val);
|
31990 | return this;
|
31991 | },
|
31992 |
|
31993 | /**
|
31994 | * Emit `node.val`
|
31995 | */
|
31996 |
|
31997 | emit: function(str, node) {
|
31998 | this.output += str;
|
31999 | return str;
|
32000 | },
|
32001 |
|
32002 | /**
|
32003 | * Add a compiler `fn` with the given `name`
|
32004 | */
|
32005 |
|
32006 | set: function(name, fn) {
|
32007 | this.compilers[name] = fn;
|
32008 | return this;
|
32009 | },
|
32010 |
|
32011 | /**
|
32012 | * Get compiler `name`.
|
32013 | */
|
32014 |
|
32015 | get: function(name) {
|
32016 | return this.compilers[name];
|
32017 | },
|
32018 |
|
32019 | /**
|
32020 | * Get the previous AST node.
|
32021 | */
|
32022 |
|
32023 | prev: function(n) {
|
32024 | return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' };
|
32025 | },
|
32026 |
|
32027 | /**
|
32028 | * Get the next AST node.
|
32029 | */
|
32030 |
|
32031 | next: function(n) {
|
32032 | return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' };
|
32033 | },
|
32034 |
|
32035 | /**
|
32036 | * Visit `node`.
|
32037 | */
|
32038 |
|
32039 | visit: function(node, nodes, i) {
|
32040 | var fn = this.compilers[node.type];
|
32041 | this.idx = i;
|
32042 |
|
32043 | if (typeof fn !== 'function') {
|
32044 | throw this.error('compiler "' + node.type + '" is not registered', node);
|
32045 | }
|
32046 | return fn.call(this, node, nodes, i);
|
32047 | },
|
32048 |
|
32049 | /**
|
32050 | * Map visit over array of `nodes`.
|
32051 | */
|
32052 |
|
32053 | mapVisit: function(nodes) {
|
32054 | if (!Array.isArray(nodes)) {
|
32055 | throw new TypeError('expected an array');
|
32056 | }
|
32057 | var len = nodes.length;
|
32058 | var idx = -1;
|
32059 | while (++idx < len) {
|
32060 | this.visit(nodes[idx], nodes, idx);
|
32061 | }
|
32062 | return this;
|
32063 | },
|
32064 |
|
32065 | /**
|
32066 | * Compile `ast`.
|
32067 | */
|
32068 |
|
32069 | compile: function(ast, options) {
|
32070 | var opts = utils$1.extend({}, this.options, options);
|
32071 | this.ast = ast;
|
32072 | this.parsingErrors = this.ast.errors;
|
32073 | this.output = '';
|
32074 |
|
32075 | // source map support
|
32076 | if (opts.sourcemap) {
|
32077 | var sourcemaps = sourceMaps;
|
32078 | sourcemaps(this);
|
32079 | this.mapVisit(this.ast.nodes);
|
32080 | this.applySourceMaps();
|
32081 | this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON();
|
32082 | return this;
|
32083 | }
|
32084 |
|
32085 | this.mapVisit(this.ast.nodes);
|
32086 | return this;
|
32087 | }
|
32088 | };
|
32089 |
|
32090 | /**
|
32091 | * Expose `Compiler`
|
32092 | */
|
32093 |
|
32094 | var compiler = Compiler;
|
32095 |
|
32096 | /*!
|
32097 | * map-cache <https://github.com/jonschlinkert/map-cache>
|
32098 | *
|
32099 | * Copyright (c) 2015, Jon Schlinkert.
|
32100 | * Licensed under the MIT License.
|
32101 | */
|
32102 |
|
32103 | var hasOwn$6 = Object.prototype.hasOwnProperty;
|
32104 |
|
32105 | /**
|
32106 | * Expose `MapCache`
|
32107 | */
|
32108 |
|
32109 | var mapCache = MapCache;
|
32110 |
|
32111 | /**
|
32112 | * Creates a cache object to store key/value pairs.
|
32113 | *
|
32114 | * ```js
|
32115 | * var cache = new MapCache();
|
32116 | * ```
|
32117 | *
|
32118 | * @api public
|
32119 | */
|
32120 |
|
32121 | function MapCache(data) {
|
32122 | this.__data__ = data || {};
|
32123 | }
|
32124 |
|
32125 | /**
|
32126 | * Adds `value` to `key` on the cache.
|
32127 | *
|
32128 | * ```js
|
32129 | * cache.set('foo', 'bar');
|
32130 | * ```
|
32131 | *
|
32132 | * @param {String} `key` The key of the value to cache.
|
32133 | * @param {*} `value` The value to cache.
|
32134 | * @returns {Object} Returns the `Cache` object for chaining.
|
32135 | * @api public
|
32136 | */
|
32137 |
|
32138 | MapCache.prototype.set = function mapSet(key, value) {
|
32139 | if (key !== '__proto__') {
|
32140 | this.__data__[key] = value;
|
32141 | }
|
32142 | return this;
|
32143 | };
|
32144 |
|
32145 | /**
|
32146 | * Gets the cached value for `key`.
|
32147 | *
|
32148 | * ```js
|
32149 | * cache.get('foo');
|
32150 | * //=> 'bar'
|
32151 | * ```
|
32152 | *
|
32153 | * @param {String} `key` The key of the value to get.
|
32154 | * @returns {*} Returns the cached value.
|
32155 | * @api public
|
32156 | */
|
32157 |
|
32158 | MapCache.prototype.get = function mapGet(key) {
|
32159 | return key === '__proto__' ? undefined : this.__data__[key];
|
32160 | };
|
32161 |
|
32162 | /**
|
32163 | * Checks if a cached value for `key` exists.
|
32164 | *
|
32165 | * ```js
|
32166 | * cache.has('foo');
|
32167 | * //=> true
|
32168 | * ```
|
32169 | *
|
32170 | * @param {String} `key` The key of the entry to check.
|
32171 | * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`.
|
32172 | * @api public
|
32173 | */
|
32174 |
|
32175 | MapCache.prototype.has = function mapHas(key) {
|
32176 | return key !== '__proto__' && hasOwn$6.call(this.__data__, key);
|
32177 | };
|
32178 |
|
32179 | /**
|
32180 | * Removes `key` and its value from the cache.
|
32181 | *
|
32182 | * ```js
|
32183 | * cache.del('foo');
|
32184 | * ```
|
32185 | * @title .del
|
32186 | * @param {String} `key` The key of the value to remove.
|
32187 | * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`.
|
32188 | * @api public
|
32189 | */
|
32190 |
|
32191 | MapCache.prototype.del = function mapDelete(key) {
|
32192 | return this.has(key) && delete this.__data__[key];
|
32193 | };
|
32194 |
|
32195 | /**
|
32196 | * Store position for a node
|
32197 | */
|
32198 |
|
32199 | var position = function Position(start, parser) {
|
32200 | this.start = start;
|
32201 | this.end = { line: parser.line, column: parser.column };
|
32202 | defineProperty$6(this, 'content', parser.orig);
|
32203 | defineProperty$6(this, 'source', parser.options.source);
|
32204 | };
|
32205 |
|
32206 | var debug$2 = src('snapdragon:parser');
|
32207 |
|
32208 |
|
32209 |
|
32210 | /**
|
32211 | * Create a new `Parser` with the given `input` and `options`.
|
32212 | * @param {String} `input`
|
32213 | * @param {Object} `options`
|
32214 | * @api public
|
32215 | */
|
32216 |
|
32217 | function Parser(options) {
|
32218 | debug$2('initializing', __filename);
|
32219 | this.options = utils$1.extend({source: 'string'}, options);
|
32220 | this.init(this.options);
|
32221 | use(this);
|
32222 | }
|
32223 |
|
32224 | /**
|
32225 | * Prototype methods
|
32226 | */
|
32227 |
|
32228 | Parser.prototype = {
|
32229 | constructor: Parser,
|
32230 |
|
32231 | init: function(options) {
|
32232 | this.orig = '';
|
32233 | this.input = '';
|
32234 | this.parsed = '';
|
32235 |
|
32236 | this.column = 1;
|
32237 | this.line = 1;
|
32238 |
|
32239 | this.regex = new mapCache();
|
32240 | this.errors = this.errors || [];
|
32241 | this.parsers = this.parsers || {};
|
32242 | this.types = this.types || [];
|
32243 | this.sets = this.sets || {};
|
32244 | this.fns = this.fns || [];
|
32245 | this.currentType = 'root';
|
32246 |
|
32247 | var pos = this.position();
|
32248 | this.bos = pos({type: 'bos', val: ''});
|
32249 |
|
32250 | this.ast = {
|
32251 | type: 'root',
|
32252 | errors: this.errors,
|
32253 | nodes: [this.bos]
|
32254 | };
|
32255 |
|
32256 | defineProperty$6(this.bos, 'parent', this.ast);
|
32257 | this.nodes = [this.ast];
|
32258 |
|
32259 | this.count = 0;
|
32260 | this.setCount = 0;
|
32261 | this.stack = [];
|
32262 | },
|
32263 |
|
32264 | /**
|
32265 | * Throw a formatted error with the cursor column and `msg`.
|
32266 | * @param {String} `msg` Message to use in the Error.
|
32267 | */
|
32268 |
|
32269 | error: function(msg, node) {
|
32270 | var pos = node.position || {start: {column: 0, line: 0}};
|
32271 | var line = pos.start.line;
|
32272 | var column = pos.start.column;
|
32273 | var source = this.options.source;
|
32274 |
|
32275 | var message = source + ' <line:' + line + ' column:' + column + '>: ' + msg;
|
32276 | var err = new Error(message);
|
32277 | err.source = source;
|
32278 | err.reason = msg;
|
32279 | err.pos = pos;
|
32280 |
|
32281 | if (this.options.silent) {
|
32282 | this.errors.push(err);
|
32283 | } else {
|
32284 | throw err;
|
32285 | }
|
32286 | },
|
32287 |
|
32288 | /**
|
32289 | * Define a non-enumberable property on the `Parser` instance.
|
32290 | *
|
32291 | * ```js
|
32292 | * parser.define('foo', 'bar');
|
32293 | * ```
|
32294 | * @name .define
|
32295 | * @param {String} `key` propery name
|
32296 | * @param {any} `val` property value
|
32297 | * @return {Object} Returns the Parser instance for chaining.
|
32298 | * @api public
|
32299 | */
|
32300 |
|
32301 | define: function(key, val) {
|
32302 | defineProperty$6(this, key, val);
|
32303 | return this;
|
32304 | },
|
32305 |
|
32306 | /**
|
32307 | * Mark position and patch `node.position`.
|
32308 | */
|
32309 |
|
32310 | position: function() {
|
32311 | var start = { line: this.line, column: this.column };
|
32312 | var self = this;
|
32313 |
|
32314 | return function(node) {
|
32315 | defineProperty$6(node, 'position', new position(start, self));
|
32316 | return node;
|
32317 | };
|
32318 | },
|
32319 |
|
32320 | /**
|
32321 | * Set parser `name` with the given `fn`
|
32322 | * @param {String} `name`
|
32323 | * @param {Function} `fn`
|
32324 | * @api public
|
32325 | */
|
32326 |
|
32327 | set: function(type, fn) {
|
32328 | if (this.types.indexOf(type) === -1) {
|
32329 | this.types.push(type);
|
32330 | }
|
32331 | this.parsers[type] = fn.bind(this);
|
32332 | return this;
|
32333 | },
|
32334 |
|
32335 | /**
|
32336 | * Get parser `name`
|
32337 | * @param {String} `name`
|
32338 | * @api public
|
32339 | */
|
32340 |
|
32341 | get: function(name) {
|
32342 | return this.parsers[name];
|
32343 | },
|
32344 |
|
32345 | /**
|
32346 | * Push a `token` onto the `type` stack.
|
32347 | *
|
32348 | * @param {String} `type`
|
32349 | * @return {Object} `token`
|
32350 | * @api public
|
32351 | */
|
32352 |
|
32353 | push: function(type, token) {
|
32354 | this.sets[type] = this.sets[type] || [];
|
32355 | this.count++;
|
32356 | this.stack.push(token);
|
32357 | return this.sets[type].push(token);
|
32358 | },
|
32359 |
|
32360 | /**
|
32361 | * Pop a token off of the `type` stack
|
32362 | * @param {String} `type`
|
32363 | * @returns {Object} Returns a token
|
32364 | * @api public
|
32365 | */
|
32366 |
|
32367 | pop: function(type) {
|
32368 | this.sets[type] = this.sets[type] || [];
|
32369 | this.count--;
|
32370 | this.stack.pop();
|
32371 | return this.sets[type].pop();
|
32372 | },
|
32373 |
|
32374 | /**
|
32375 | * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`.
|
32376 | *
|
32377 | * @param {String} `type`
|
32378 | * @return {Boolean}
|
32379 | * @api public
|
32380 | */
|
32381 |
|
32382 | isInside: function(type) {
|
32383 | this.sets[type] = this.sets[type] || [];
|
32384 | return this.sets[type].length > 0;
|
32385 | },
|
32386 |
|
32387 | /**
|
32388 | * Return true if `node` is the given `type`.
|
32389 | *
|
32390 | * ```js
|
32391 | * parser.isType(node, 'brace');
|
32392 | * ```
|
32393 | * @param {Object} `node`
|
32394 | * @param {String} `type`
|
32395 | * @return {Boolean}
|
32396 | * @api public
|
32397 | */
|
32398 |
|
32399 | isType: function(node, type) {
|
32400 | return node && node.type === type;
|
32401 | },
|
32402 |
|
32403 | /**
|
32404 | * Get the previous AST node
|
32405 | * @return {Object}
|
32406 | */
|
32407 |
|
32408 | prev: function(n) {
|
32409 | return this.stack.length > 0
|
32410 | ? utils$1.last(this.stack, n)
|
32411 | : utils$1.last(this.nodes, n);
|
32412 | },
|
32413 |
|
32414 | /**
|
32415 | * Update line and column based on `str`.
|
32416 | */
|
32417 |
|
32418 | consume: function(len) {
|
32419 | this.input = this.input.substr(len);
|
32420 | },
|
32421 |
|
32422 | /**
|
32423 | * Update column based on `str`.
|
32424 | */
|
32425 |
|
32426 | updatePosition: function(str, len) {
|
32427 | var lines = str.match(/\n/g);
|
32428 | if (lines) this.line += lines.length;
|
32429 | var i = str.lastIndexOf('\n');
|
32430 | this.column = ~i ? len - i : this.column + len;
|
32431 | this.parsed += str;
|
32432 | this.consume(len);
|
32433 | },
|
32434 |
|
32435 | /**
|
32436 | * Match `regex`, return captures, and update the cursor position by `match[0]` length.
|
32437 | * @param {RegExp} `regex`
|
32438 | * @return {Object}
|
32439 | */
|
32440 |
|
32441 | match: function(regex) {
|
32442 | var m = regex.exec(this.input);
|
32443 | if (m) {
|
32444 | this.updatePosition(m[0], m[0].length);
|
32445 | return m;
|
32446 | }
|
32447 | },
|
32448 |
|
32449 | /**
|
32450 | * Capture `type` with the given regex.
|
32451 | * @param {String} `type`
|
32452 | * @param {RegExp} `regex`
|
32453 | * @return {Function}
|
32454 | */
|
32455 |
|
32456 | capture: function(type, regex) {
|
32457 | if (typeof regex === 'function') {
|
32458 | return this.set.apply(this, arguments);
|
32459 | }
|
32460 |
|
32461 | this.regex.set(type, regex);
|
32462 | this.set(type, function() {
|
32463 | var parsed = this.parsed;
|
32464 | var pos = this.position();
|
32465 | var m = this.match(regex);
|
32466 | if (!m || !m[0]) return;
|
32467 |
|
32468 | var prev = this.prev();
|
32469 | var node = pos({
|
32470 | type: type,
|
32471 | val: m[0],
|
32472 | parsed: parsed,
|
32473 | rest: this.input
|
32474 | });
|
32475 |
|
32476 | if (m[1]) {
|
32477 | node.inner = m[1];
|
32478 | }
|
32479 |
|
32480 | defineProperty$6(node, 'inside', this.stack.length > 0);
|
32481 | defineProperty$6(node, 'parent', prev);
|
32482 | prev.nodes.push(node);
|
32483 | }.bind(this));
|
32484 | return this;
|
32485 | },
|
32486 |
|
32487 | /**
|
32488 | * Create a parser with open and close for parens,
|
32489 | * brackets or braces
|
32490 | */
|
32491 |
|
32492 | capturePair: function(type, openRegex, closeRegex, fn) {
|
32493 | this.sets[type] = this.sets[type] || [];
|
32494 |
|
32495 | /**
|
32496 | * Open
|
32497 | */
|
32498 |
|
32499 | this.set(type + '.open', function() {
|
32500 | var parsed = this.parsed;
|
32501 | var pos = this.position();
|
32502 | var m = this.match(openRegex);
|
32503 | if (!m || !m[0]) return;
|
32504 |
|
32505 | var val = m[0];
|
32506 | this.setCount++;
|
32507 | this.specialChars = true;
|
32508 | var open = pos({
|
32509 | type: type + '.open',
|
32510 | val: val,
|
32511 | rest: this.input
|
32512 | });
|
32513 |
|
32514 | if (typeof m[1] !== 'undefined') {
|
32515 | open.inner = m[1];
|
32516 | }
|
32517 |
|
32518 | var prev = this.prev();
|
32519 | var node = pos({
|
32520 | type: type,
|
32521 | nodes: [open]
|
32522 | });
|
32523 |
|
32524 | defineProperty$6(node, 'rest', this.input);
|
32525 | defineProperty$6(node, 'parsed', parsed);
|
32526 | defineProperty$6(node, 'prefix', m[1]);
|
32527 | defineProperty$6(node, 'parent', prev);
|
32528 | defineProperty$6(open, 'parent', node);
|
32529 |
|
32530 | if (typeof fn === 'function') {
|
32531 | fn.call(this, open, node);
|
32532 | }
|
32533 |
|
32534 | this.push(type, node);
|
32535 | prev.nodes.push(node);
|
32536 | });
|
32537 |
|
32538 | /**
|
32539 | * Close
|
32540 | */
|
32541 |
|
32542 | this.set(type + '.close', function() {
|
32543 | var pos = this.position();
|
32544 | var m = this.match(closeRegex);
|
32545 | if (!m || !m[0]) return;
|
32546 |
|
32547 | var parent = this.pop(type);
|
32548 | var node = pos({
|
32549 | type: type + '.close',
|
32550 | rest: this.input,
|
32551 | suffix: m[1],
|
32552 | val: m[0]
|
32553 | });
|
32554 |
|
32555 | if (!this.isType(parent, type)) {
|
32556 | if (this.options.strict) {
|
32557 | throw new Error('missing opening "' + type + '"');
|
32558 | }
|
32559 |
|
32560 | this.setCount--;
|
32561 | node.escaped = true;
|
32562 | return node;
|
32563 | }
|
32564 |
|
32565 | if (node.suffix === '\\') {
|
32566 | parent.escaped = true;
|
32567 | node.escaped = true;
|
32568 | }
|
32569 |
|
32570 | parent.nodes.push(node);
|
32571 | defineProperty$6(node, 'parent', parent);
|
32572 | });
|
32573 |
|
32574 | return this;
|
32575 | },
|
32576 |
|
32577 | /**
|
32578 | * Capture end-of-string
|
32579 | */
|
32580 |
|
32581 | eos: function() {
|
32582 | var pos = this.position();
|
32583 | if (this.input) return;
|
32584 | var prev = this.prev();
|
32585 |
|
32586 | while (prev.type !== 'root' && !prev.visited) {
|
32587 | if (this.options.strict === true) {
|
32588 | throw new SyntaxError('invalid syntax:' + util$2.inspect(prev, null, 2));
|
32589 | }
|
32590 |
|
32591 | if (!hasDelims(prev)) {
|
32592 | prev.parent.escaped = true;
|
32593 | prev.escaped = true;
|
32594 | }
|
32595 |
|
32596 | visit(prev, function(node) {
|
32597 | if (!hasDelims(node.parent)) {
|
32598 | node.parent.escaped = true;
|
32599 | node.escaped = true;
|
32600 | }
|
32601 | });
|
32602 |
|
32603 | prev = prev.parent;
|
32604 | }
|
32605 |
|
32606 | var tok = pos({
|
32607 | type: 'eos',
|
32608 | val: this.append || ''
|
32609 | });
|
32610 |
|
32611 | defineProperty$6(tok, 'parent', this.ast);
|
32612 | return tok;
|
32613 | },
|
32614 |
|
32615 | /**
|
32616 | * Run parsers to advance the cursor position
|
32617 | */
|
32618 |
|
32619 | next: function() {
|
32620 | var parsed = this.parsed;
|
32621 | var len = this.types.length;
|
32622 | var idx = -1;
|
32623 | var tok;
|
32624 |
|
32625 | while (++idx < len) {
|
32626 | if ((tok = this.parsers[this.types[idx]].call(this))) {
|
32627 | defineProperty$6(tok, 'rest', this.input);
|
32628 | defineProperty$6(tok, 'parsed', parsed);
|
32629 | this.last = tok;
|
32630 | return tok;
|
32631 | }
|
32632 | }
|
32633 | },
|
32634 |
|
32635 | /**
|
32636 | * Parse the given string.
|
32637 | * @return {Array}
|
32638 | */
|
32639 |
|
32640 | parse: function(input) {
|
32641 | if (typeof input !== 'string') {
|
32642 | throw new TypeError('expected a string');
|
32643 | }
|
32644 |
|
32645 | this.init(this.options);
|
32646 | this.orig = input;
|
32647 | this.input = input;
|
32648 | var self = this;
|
32649 |
|
32650 | function parse() {
|
32651 | // check input before calling `.next()`
|
32652 | input = self.input;
|
32653 |
|
32654 | // get the next AST ndoe
|
32655 | var node = self.next();
|
32656 | if (node) {
|
32657 | var prev = self.prev();
|
32658 | if (prev) {
|
32659 | defineProperty$6(node, 'parent', prev);
|
32660 | if (prev.nodes) {
|
32661 | prev.nodes.push(node);
|
32662 | }
|
32663 | }
|
32664 |
|
32665 | if (self.sets.hasOwnProperty(prev.type)) {
|
32666 | self.currentType = prev.type;
|
32667 | }
|
32668 | }
|
32669 |
|
32670 | // if we got here but input is not changed, throw an error
|
32671 | if (self.input && input === self.input) {
|
32672 | throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"');
|
32673 | }
|
32674 | }
|
32675 |
|
32676 | while (this.input) parse();
|
32677 | if (this.stack.length && this.options.strict) {
|
32678 | var node = this.stack.pop();
|
32679 | throw this.error('missing opening ' + node.type + ': "' + this.orig + '"');
|
32680 | }
|
32681 |
|
32682 | var eos = this.eos();
|
32683 | var tok = this.prev();
|
32684 | if (tok.type !== 'eos') {
|
32685 | this.ast.nodes.push(eos);
|
32686 | }
|
32687 |
|
32688 | return this.ast;
|
32689 | }
|
32690 | };
|
32691 |
|
32692 | /**
|
32693 | * Visit `node` with the given `fn`
|
32694 | */
|
32695 |
|
32696 | function visit(node, fn) {
|
32697 | if (!node.visited) {
|
32698 | defineProperty$6(node, 'visited', true);
|
32699 | return node.nodes ? mapVisit$1(node.nodes, fn) : fn(node);
|
32700 | }
|
32701 | return node;
|
32702 | }
|
32703 |
|
32704 | /**
|
32705 | * Map visit over array of `nodes`.
|
32706 | */
|
32707 |
|
32708 | function mapVisit$1(nodes, fn) {
|
32709 | var len = nodes.length;
|
32710 | var idx = -1;
|
32711 | while (++idx < len) {
|
32712 | visit(nodes[idx], fn);
|
32713 | }
|
32714 | }
|
32715 |
|
32716 | function hasOpen(node) {
|
32717 | return node.nodes && node.nodes[0].type === (node.type + '.open');
|
32718 | }
|
32719 |
|
32720 | function hasClose(node) {
|
32721 | return node.nodes && utils$1.last(node.nodes).type === (node.type + '.close');
|
32722 | }
|
32723 |
|
32724 | function hasDelims(node) {
|
32725 | return hasOpen(node) && hasClose(node);
|
32726 | }
|
32727 |
|
32728 | /**
|
32729 | * Expose `Parser`
|
32730 | */
|
32731 |
|
32732 | var parser = Parser;
|
32733 |
|
32734 | /**
|
32735 | * Create a new instance of `Snapdragon` with the given `options`.
|
32736 | *
|
32737 | * ```js
|
32738 | * var snapdragon = new Snapdragon();
|
32739 | * ```
|
32740 | *
|
32741 | * @param {Object} `options`
|
32742 | * @api public
|
32743 | */
|
32744 |
|
32745 | function Snapdragon(options) {
|
32746 | base$2.call(this, null, options);
|
32747 | this.options = utils$1.extend({source: 'string'}, this.options);
|
32748 | this.compiler = new compiler(this.options);
|
32749 | this.parser = new parser(this.options);
|
32750 |
|
32751 | Object.defineProperty(this, 'compilers', {
|
32752 | get: function() {
|
32753 | return this.compiler.compilers;
|
32754 | }
|
32755 | });
|
32756 |
|
32757 | Object.defineProperty(this, 'parsers', {
|
32758 | get: function() {
|
32759 | return this.parser.parsers;
|
32760 | }
|
32761 | });
|
32762 |
|
32763 | Object.defineProperty(this, 'regex', {
|
32764 | get: function() {
|
32765 | return this.parser.regex;
|
32766 | }
|
32767 | });
|
32768 | }
|
32769 |
|
32770 | /**
|
32771 | * Inherit Base
|
32772 | */
|
32773 |
|
32774 | base$2.extend(Snapdragon);
|
32775 |
|
32776 | /**
|
32777 | * Add a parser to `snapdragon.parsers` for capturing the given `type` using
|
32778 | * the specified regex or parser function. A function is useful if you need
|
32779 | * to customize how the token is created and/or have access to the parser
|
32780 | * instance to check options, etc.
|
32781 | *
|
32782 | * ```js
|
32783 | * snapdragon
|
32784 | * .capture('slash', /^\//)
|
32785 | * .capture('dot', function() {
|
32786 | * var pos = this.position();
|
32787 | * var m = this.match(/^\./);
|
32788 | * if (!m) return;
|
32789 | * return pos({
|
32790 | * type: 'dot',
|
32791 | * val: m[0]
|
32792 | * });
|
32793 | * });
|
32794 | * ```
|
32795 | * @param {String} `type`
|
32796 | * @param {RegExp|Function} `regex`
|
32797 | * @return {Object} Returns the parser instance for chaining
|
32798 | * @api public
|
32799 | */
|
32800 |
|
32801 | Snapdragon.prototype.capture = function() {
|
32802 | return this.parser.capture.apply(this.parser, arguments);
|
32803 | };
|
32804 |
|
32805 | /**
|
32806 | * Register a plugin `fn`.
|
32807 | *
|
32808 | * ```js
|
32809 | * var snapdragon = new Snapdgragon([options]);
|
32810 | * snapdragon.use(function() {
|
32811 | * console.log(this); //<= snapdragon instance
|
32812 | * console.log(this.parser); //<= parser instance
|
32813 | * console.log(this.compiler); //<= compiler instance
|
32814 | * });
|
32815 | * ```
|
32816 | * @param {Object} `fn`
|
32817 | * @api public
|
32818 | */
|
32819 |
|
32820 | Snapdragon.prototype.use = function(fn) {
|
32821 | fn.call(this, this);
|
32822 | return this;
|
32823 | };
|
32824 |
|
32825 | /**
|
32826 | * Parse the given `str`.
|
32827 | *
|
32828 | * ```js
|
32829 | * var snapdragon = new Snapdgragon([options]);
|
32830 | * // register parsers
|
32831 | * snapdragon.parser.use(function() {});
|
32832 | *
|
32833 | * // parse
|
32834 | * var ast = snapdragon.parse('foo/bar');
|
32835 | * console.log(ast);
|
32836 | * ```
|
32837 | * @param {String} `str`
|
32838 | * @param {Object} `options` Set `options.sourcemap` to true to enable source maps.
|
32839 | * @return {Object} Returns an AST.
|
32840 | * @api public
|
32841 | */
|
32842 |
|
32843 | Snapdragon.prototype.parse = function(str, options) {
|
32844 | this.options = utils$1.extend({}, this.options, options);
|
32845 | var parsed = this.parser.parse(str, this.options);
|
32846 |
|
32847 | // add non-enumerable parser reference
|
32848 | defineProperty$6(parsed, 'parser', this.parser);
|
32849 | return parsed;
|
32850 | };
|
32851 |
|
32852 | /**
|
32853 | * Compile the given `AST`.
|
32854 | *
|
32855 | * ```js
|
32856 | * var snapdragon = new Snapdgragon([options]);
|
32857 | * // register plugins
|
32858 | * snapdragon.use(function() {});
|
32859 | * // register parser plugins
|
32860 | * snapdragon.parser.use(function() {});
|
32861 | * // register compiler plugins
|
32862 | * snapdragon.compiler.use(function() {});
|
32863 | *
|
32864 | * // parse
|
32865 | * var ast = snapdragon.parse('foo/bar');
|
32866 | *
|
32867 | * // compile
|
32868 | * var res = snapdragon.compile(ast);
|
32869 | * console.log(res.output);
|
32870 | * ```
|
32871 | * @param {Object} `ast`
|
32872 | * @param {Object} `options`
|
32873 | * @return {Object} Returns an object with an `output` property with the rendered string.
|
32874 | * @api public
|
32875 | */
|
32876 |
|
32877 | Snapdragon.prototype.compile = function(ast, options) {
|
32878 | this.options = utils$1.extend({}, this.options, options);
|
32879 | var compiled = this.compiler.compile(ast, this.options);
|
32880 |
|
32881 | // add non-enumerable compiler reference
|
32882 | defineProperty$6(compiled, 'compiler', this.compiler);
|
32883 | return compiled;
|
32884 | };
|
32885 |
|
32886 | /**
|
32887 | * Expose `Snapdragon`
|
32888 | */
|
32889 |
|
32890 | var snapdragon = Snapdragon;
|
32891 |
|
32892 | /**
|
32893 | * Expose `Parser` and `Compiler`
|
32894 | */
|
32895 |
|
32896 | var Compiler_1 = compiler;
|
32897 | var Parser_1 = parser;
|
32898 | snapdragon.Compiler = Compiler_1;
|
32899 | snapdragon.Parser = Parser_1;
|
32900 |
|
32901 | /**
|
32902 | * Customize Snapdragon parser and renderer
|
32903 | */
|
32904 |
|
32905 | function Braces(options) {
|
32906 | this.options = extendShallow$1({}, options);
|
32907 | }
|
32908 |
|
32909 | /**
|
32910 | * Initialize braces
|
32911 | */
|
32912 |
|
32913 | Braces.prototype.init = function(options) {
|
32914 | if (this.isInitialized) return;
|
32915 | this.isInitialized = true;
|
32916 | var opts = utils_1.createOptions({}, this.options, options);
|
32917 | this.snapdragon = this.options.snapdragon || new snapdragon(opts);
|
32918 | this.compiler = this.snapdragon.compiler;
|
32919 | this.parser = this.snapdragon.parser;
|
32920 |
|
32921 | compilers(this.snapdragon, opts);
|
32922 | parsers(this.snapdragon, opts);
|
32923 |
|
32924 | /**
|
32925 | * Call Snapdragon `.parse` method. When AST is returned, we check to
|
32926 | * see if any unclosed braces are left on the stack and, if so, we iterate
|
32927 | * over the stack and correct the AST so that compilers are called in the correct
|
32928 | * order and unbalance braces are properly escaped.
|
32929 | */
|
32930 |
|
32931 | utils_1.define(this.snapdragon, 'parse', function(pattern, options) {
|
32932 | var parsed = snapdragon.prototype.parse.apply(this, arguments);
|
32933 | this.parser.ast.input = pattern;
|
32934 |
|
32935 | var stack = this.parser.stack;
|
32936 | while (stack.length) {
|
32937 | addParent({type: 'brace.close', val: ''}, stack.pop());
|
32938 | }
|
32939 |
|
32940 | function addParent(node, parent) {
|
32941 | utils_1.define(node, 'parent', parent);
|
32942 | parent.nodes.push(node);
|
32943 | }
|
32944 |
|
32945 | // add non-enumerable parser reference
|
32946 | utils_1.define(parsed, 'parser', this.parser);
|
32947 | return parsed;
|
32948 | });
|
32949 | };
|
32950 |
|
32951 | /**
|
32952 | * Decorate `.parse` method
|
32953 | */
|
32954 |
|
32955 | Braces.prototype.parse = function(ast, options) {
|
32956 | if (ast && typeof ast === 'object' && ast.nodes) return ast;
|
32957 | this.init(options);
|
32958 | return this.snapdragon.parse(ast, options);
|
32959 | };
|
32960 |
|
32961 | /**
|
32962 | * Decorate `.compile` method
|
32963 | */
|
32964 |
|
32965 | Braces.prototype.compile = function(ast, options) {
|
32966 | if (typeof ast === 'string') {
|
32967 | ast = this.parse(ast, options);
|
32968 | } else {
|
32969 | this.init(options);
|
32970 | }
|
32971 | return this.snapdragon.compile(ast, options);
|
32972 | };
|
32973 |
|
32974 | /**
|
32975 | * Expand
|
32976 | */
|
32977 |
|
32978 | Braces.prototype.expand = function(pattern) {
|
32979 | var ast = this.parse(pattern, {expand: true});
|
32980 | return this.compile(ast, {expand: true});
|
32981 | };
|
32982 |
|
32983 | /**
|
32984 | * Optimize
|
32985 | */
|
32986 |
|
32987 | Braces.prototype.optimize = function(pattern) {
|
32988 | var ast = this.parse(pattern, {optimize: true});
|
32989 | return this.compile(ast, {optimize: true});
|
32990 | };
|
32991 |
|
32992 | /**
|
32993 | * Expose `Braces`
|
32994 | */
|
32995 |
|
32996 | var braces = Braces;
|
32997 |
|
32998 | /**
|
32999 | * Module dependencies
|
33000 | */
|
33001 |
|
33002 |
|
33003 |
|
33004 |
|
33005 |
|
33006 | /**
|
33007 | * Local dependencies
|
33008 | */
|
33009 |
|
33010 |
|
33011 |
|
33012 |
|
33013 |
|
33014 | var MAX_LENGTH$1 = 1024 * 64;
|
33015 | var cache$3 = {};
|
33016 |
|
33017 | /**
|
33018 | * 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)).
|
33019 | *
|
33020 | * ```js
|
33021 | * var braces = require('braces');
|
33022 | * console.log(braces('{a,b,c}'));
|
33023 | * //=> ['(a|b|c)']
|
33024 | *
|
33025 | * console.log(braces('{a,b,c}', {expand: true}));
|
33026 | * //=> ['a', 'b', 'c']
|
33027 | * ```
|
33028 | * @param {String} `str`
|
33029 | * @param {Object} `options`
|
33030 | * @return {String}
|
33031 | * @api public
|
33032 | */
|
33033 |
|
33034 | function braces$1(pattern, options) {
|
33035 | var key = utils_1.createKey(String(pattern), options);
|
33036 | var arr = [];
|
33037 |
|
33038 | var disabled = options && options.cache === false;
|
33039 | if (!disabled && cache$3.hasOwnProperty(key)) {
|
33040 | return cache$3[key];
|
33041 | }
|
33042 |
|
33043 | if (Array.isArray(pattern)) {
|
33044 | for (var i = 0; i < pattern.length; i++) {
|
33045 | arr.push.apply(arr, braces$1.create(pattern[i], options));
|
33046 | }
|
33047 | } else {
|
33048 | arr = braces$1.create(pattern, options);
|
33049 | }
|
33050 |
|
33051 | if (options && options.nodupes === true) {
|
33052 | arr = arrayUnique(arr);
|
33053 | }
|
33054 |
|
33055 | if (!disabled) {
|
33056 | cache$3[key] = arr;
|
33057 | }
|
33058 | return arr;
|
33059 | }
|
33060 |
|
33061 | /**
|
33062 | * 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.
|
33063 | *
|
33064 | * ```js
|
33065 | * var braces = require('braces');
|
33066 | * console.log(braces.expand('a/{b,c}/d'));
|
33067 | * //=> ['a/b/d', 'a/c/d'];
|
33068 | * ```
|
33069 | * @param {String} `pattern` Brace pattern
|
33070 | * @param {Object} `options`
|
33071 | * @return {Array} Returns an array of expanded values.
|
33072 | * @api public
|
33073 | */
|
33074 |
|
33075 | braces$1.expand = function(pattern, options) {
|
33076 | return braces$1.create(pattern, extendShallow$1({}, options, {expand: true}));
|
33077 | };
|
33078 |
|
33079 | /**
|
33080 | * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
|
33081 | *
|
33082 | * ```js
|
33083 | * var braces = require('braces');
|
33084 | * console.log(braces.expand('a/{b,c}/d'));
|
33085 | * //=> ['a/(b|c)/d']
|
33086 | * ```
|
33087 | * @param {String} `pattern` Brace pattern
|
33088 | * @param {Object} `options`
|
33089 | * @return {Array} Returns an array of expanded values.
|
33090 | * @api public
|
33091 | */
|
33092 |
|
33093 | braces$1.optimize = function(pattern, options) {
|
33094 | return braces$1.create(pattern, options);
|
33095 | };
|
33096 |
|
33097 | /**
|
33098 | * 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.
|
33099 | *
|
33100 | * ```js
|
33101 | * var braces = require('braces');
|
33102 | * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
|
33103 | * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
|
33104 | * ```
|
33105 | * @param {String} `pattern` Brace pattern
|
33106 | * @param {Object} `options`
|
33107 | * @return {Array} Returns an array of expanded values.
|
33108 | * @api public
|
33109 | */
|
33110 |
|
33111 | braces$1.create = function(pattern, options) {
|
33112 | if (typeof pattern !== 'string') {
|
33113 | throw new TypeError('expected a string');
|
33114 | }
|
33115 |
|
33116 | var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
|
33117 | if (pattern.length >= maxLength) {
|
33118 | throw new Error('expected pattern to be less than ' + maxLength + ' characters');
|
33119 | }
|
33120 |
|
33121 | function create() {
|
33122 | if (pattern === '' || pattern.length < 3) {
|
33123 | return [pattern];
|
33124 | }
|
33125 |
|
33126 | if (utils_1.isEmptySets(pattern)) {
|
33127 | return [];
|
33128 | }
|
33129 |
|
33130 | if (utils_1.isQuotedString(pattern)) {
|
33131 | return [pattern.slice(1, -1)];
|
33132 | }
|
33133 |
|
33134 | var proto = new braces(options);
|
33135 | var result = !options || options.expand !== true
|
33136 | ? proto.optimize(pattern, options)
|
33137 | : proto.expand(pattern, options);
|
33138 |
|
33139 | // get the generated pattern(s)
|
33140 | var arr = result.output;
|
33141 |
|
33142 | // filter out empty strings if specified
|
33143 | if (options && options.noempty === true) {
|
33144 | arr = arr.filter(Boolean);
|
33145 | }
|
33146 |
|
33147 | // filter out duplicates if specified
|
33148 | if (options && options.nodupes === true) {
|
33149 | arr = arrayUnique(arr);
|
33150 | }
|
33151 |
|
33152 | Object.defineProperty(arr, 'result', {
|
33153 | enumerable: false,
|
33154 | value: result
|
33155 | });
|
33156 |
|
33157 | return arr;
|
33158 | }
|
33159 |
|
33160 | return memoize$1('create', pattern, options, create);
|
33161 | };
|
33162 |
|
33163 | /**
|
33164 | * Create a regular expression from the given string `pattern`.
|
33165 | *
|
33166 | * ```js
|
33167 | * var braces = require('braces');
|
33168 | *
|
33169 | * console.log(braces.makeRe('id-{200..300}'));
|
33170 | * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
|
33171 | * ```
|
33172 | * @param {String} `pattern` The pattern to convert to regex.
|
33173 | * @param {Object} `options`
|
33174 | * @return {RegExp}
|
33175 | * @api public
|
33176 | */
|
33177 |
|
33178 | braces$1.makeRe = function(pattern, options) {
|
33179 | if (typeof pattern !== 'string') {
|
33180 | throw new TypeError('expected a string');
|
33181 | }
|
33182 |
|
33183 | var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
|
33184 | if (pattern.length >= maxLength) {
|
33185 | throw new Error('expected pattern to be less than ' + maxLength + ' characters');
|
33186 | }
|
33187 |
|
33188 | function makeRe() {
|
33189 | var arr = braces$1(pattern, options);
|
33190 | var opts = extendShallow$1({strictErrors: false}, options);
|
33191 | return toRegex$1(arr, opts);
|
33192 | }
|
33193 |
|
33194 | return memoize$1('makeRe', pattern, options, makeRe);
|
33195 | };
|
33196 |
|
33197 | /**
|
33198 | * Parse the given `str` with the given `options`.
|
33199 | *
|
33200 | * ```js
|
33201 | * var braces = require('braces');
|
33202 | * var ast = braces.parse('a/{b,c}/d');
|
33203 | * console.log(ast);
|
33204 | * // { type: 'root',
|
33205 | * // errors: [],
|
33206 | * // input: 'a/{b,c}/d',
|
33207 | * // nodes:
|
33208 | * // [ { type: 'bos', val: '' },
|
33209 | * // { type: 'text', val: 'a/' },
|
33210 | * // { type: 'brace',
|
33211 | * // nodes:
|
33212 | * // [ { type: 'brace.open', val: '{' },
|
33213 | * // { type: 'text', val: 'b,c' },
|
33214 | * // { type: 'brace.close', val: '}' } ] },
|
33215 | * // { type: 'text', val: '/d' },
|
33216 | * // { type: 'eos', val: '' } ] }
|
33217 | * ```
|
33218 | * @param {String} `pattern` Brace pattern to parse
|
33219 | * @param {Object} `options`
|
33220 | * @return {Object} Returns an AST
|
33221 | * @api public
|
33222 | */
|
33223 |
|
33224 | braces$1.parse = function(pattern, options) {
|
33225 | var proto = new braces(options);
|
33226 | return proto.parse(pattern, options);
|
33227 | };
|
33228 |
|
33229 | /**
|
33230 | * Compile the given `ast` or string with the given `options`.
|
33231 | *
|
33232 | * ```js
|
33233 | * var braces = require('braces');
|
33234 | * var ast = braces.parse('a/{b,c}/d');
|
33235 | * console.log(braces.compile(ast));
|
33236 | * // { options: { source: 'string' },
|
33237 | * // state: {},
|
33238 | * // compilers:
|
33239 | * // { eos: [Function],
|
33240 | * // noop: [Function],
|
33241 | * // bos: [Function],
|
33242 | * // brace: [Function],
|
33243 | * // 'brace.open': [Function],
|
33244 | * // text: [Function],
|
33245 | * // 'brace.close': [Function] },
|
33246 | * // output: [ 'a/(b|c)/d' ],
|
33247 | * // ast:
|
33248 | * // { ... },
|
33249 | * // parsingErrors: [] }
|
33250 | * ```
|
33251 | * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
|
33252 | * @param {Object} `options`
|
33253 | * @return {Object} Returns an object that has an `output` property with the compiled string.
|
33254 | * @api public
|
33255 | */
|
33256 |
|
33257 | braces$1.compile = function(ast, options) {
|
33258 | var proto = new braces(options);
|
33259 | return proto.compile(ast, options);
|
33260 | };
|
33261 |
|
33262 | /**
|
33263 | * Clear the regex cache.
|
33264 | *
|
33265 | * ```js
|
33266 | * braces.clearCache();
|
33267 | * ```
|
33268 | * @api public
|
33269 | */
|
33270 |
|
33271 | braces$1.clearCache = function() {
|
33272 | cache$3 = braces$1.cache = {};
|
33273 | };
|
33274 |
|
33275 | /**
|
33276 | * Memoize a generated regex or function. A unique key is generated
|
33277 | * from the method name, pattern, and user-defined options. Set
|
33278 | * options.memoize to false to disable.
|
33279 | */
|
33280 |
|
33281 | function memoize$1(type, pattern, options, fn) {
|
33282 | var key = utils_1.createKey(type + ':' + pattern, options);
|
33283 | var disabled = options && options.cache === false;
|
33284 | if (disabled) {
|
33285 | braces$1.clearCache();
|
33286 | return fn(pattern, options);
|
33287 | }
|
33288 |
|
33289 | if (cache$3.hasOwnProperty(key)) {
|
33290 | return cache$3[key];
|
33291 | }
|
33292 |
|
33293 | var res = fn(pattern, options);
|
33294 | cache$3[key] = res;
|
33295 | return res;
|
33296 | }
|
33297 |
|
33298 | /**
|
33299 | * Expose `Braces` constructor and methods
|
33300 | * @type {Function}
|
33301 | */
|
33302 |
|
33303 | braces$1.Braces = braces;
|
33304 | braces$1.compilers = compilers;
|
33305 | braces$1.parsers = parsers;
|
33306 | braces$1.cache = cache$3;
|
33307 |
|
33308 | /**
|
33309 | * Expose `braces`
|
33310 | * @type {Function}
|
33311 | */
|
33312 |
|
33313 | var braces_1 = braces$1;
|
33314 |
|
33315 | /**
|
33316 | * Nanomatch compilers
|
33317 | */
|
33318 |
|
33319 | var compilers$1 = function(nanomatch, options) {
|
33320 | function slash() {
|
33321 | if (options && typeof options.slash === 'string') {
|
33322 | return options.slash;
|
33323 | }
|
33324 | if (options && typeof options.slash === 'function') {
|
33325 | return options.slash.call(nanomatch);
|
33326 | }
|
33327 | return '\\\\/';
|
33328 | }
|
33329 |
|
33330 | function star() {
|
33331 | if (options && typeof options.star === 'string') {
|
33332 | return options.star;
|
33333 | }
|
33334 | if (options && typeof options.star === 'function') {
|
33335 | return options.star.call(nanomatch);
|
33336 | }
|
33337 | return '[^' + slash() + ']*?';
|
33338 | }
|
33339 |
|
33340 | var ast = nanomatch.ast = nanomatch.parser.ast;
|
33341 | ast.state = nanomatch.parser.state;
|
33342 | nanomatch.compiler.state = ast.state;
|
33343 | nanomatch.compiler
|
33344 |
|
33345 | /**
|
33346 | * Negation / escaping
|
33347 | */
|
33348 |
|
33349 | .set('not', function(node) {
|
33350 | var prev = this.prev();
|
33351 | if (this.options.nonegate === true || prev.type !== 'bos') {
|
33352 | return this.emit('\\' + node.val, node);
|
33353 | }
|
33354 | return this.emit(node.val, node);
|
33355 | })
|
33356 | .set('escape', function(node) {
|
33357 | if (this.options.unescape && /^[-\w_.]/.test(node.val)) {
|
33358 | return this.emit(node.val, node);
|
33359 | }
|
33360 | return this.emit('\\' + node.val, node);
|
33361 | })
|
33362 | .set('quoted', function(node) {
|
33363 | return this.emit(node.val, node);
|
33364 | })
|
33365 |
|
33366 | /**
|
33367 | * Regex
|
33368 | */
|
33369 |
|
33370 | .set('dollar', function(node) {
|
33371 | if (node.parent.type === 'bracket') {
|
33372 | return this.emit(node.val, node);
|
33373 | }
|
33374 | return this.emit('\\' + node.val, node);
|
33375 | })
|
33376 |
|
33377 | /**
|
33378 | * Dot: "."
|
33379 | */
|
33380 |
|
33381 | .set('dot', function(node) {
|
33382 | if (node.dotfiles === true) this.dotfiles = true;
|
33383 | return this.emit('\\' + node.val, node);
|
33384 | })
|
33385 |
|
33386 | /**
|
33387 | * Slashes: "/" and "\"
|
33388 | */
|
33389 |
|
33390 | .set('backslash', function(node) {
|
33391 | return this.emit(node.val, node);
|
33392 | })
|
33393 | .set('slash', function(node, nodes, i) {
|
33394 | var val = '[' + slash() + ']';
|
33395 | var parent = node.parent;
|
33396 | var prev = this.prev();
|
33397 |
|
33398 | // set "node.hasSlash" to true on all ancestor parens nodes
|
33399 | while (parent.type === 'paren' && !parent.hasSlash) {
|
33400 | parent.hasSlash = true;
|
33401 | parent = parent.parent;
|
33402 | }
|
33403 |
|
33404 | if (prev.addQmark) {
|
33405 | val += '?';
|
33406 | }
|
33407 |
|
33408 | // word boundary
|
33409 | if (node.rest.slice(0, 2) === '\\b') {
|
33410 | return this.emit(val, node);
|
33411 | }
|
33412 |
|
33413 | // globstars
|
33414 | if (node.parsed === '**' || node.parsed === './**') {
|
33415 | this.output = '(?:' + this.output;
|
33416 | return this.emit(val + ')?', node);
|
33417 | }
|
33418 |
|
33419 | // negation
|
33420 | if (node.parsed === '!**' && this.options.nonegate !== true) {
|
33421 | return this.emit(val + '?\\b', node);
|
33422 | }
|
33423 | return this.emit(val, node);
|
33424 | })
|
33425 |
|
33426 | /**
|
33427 | * Square brackets
|
33428 | */
|
33429 |
|
33430 | .set('bracket', function(node) {
|
33431 | var close = node.close;
|
33432 | var open = !node.escaped ? '[' : '\\[';
|
33433 | var negated = node.negated;
|
33434 | var inner = node.inner;
|
33435 | var val = node.val;
|
33436 |
|
33437 | if (node.escaped === true) {
|
33438 | inner = inner.replace(/\\?(\W)/g, '\\$1');
|
33439 | negated = '';
|
33440 | }
|
33441 |
|
33442 | if (inner === ']-') {
|
33443 | inner = '\\]\\-';
|
33444 | }
|
33445 |
|
33446 | if (negated && inner.indexOf('.') === -1) {
|
33447 | inner += '.';
|
33448 | }
|
33449 | if (negated && inner.indexOf('/') === -1) {
|
33450 | inner += '/';
|
33451 | }
|
33452 |
|
33453 | val = open + negated + inner + close;
|
33454 | return this.emit(val, node);
|
33455 | })
|
33456 |
|
33457 | /**
|
33458 | * Square: "[.]" (only matches a single character in brackets)
|
33459 | */
|
33460 |
|
33461 | .set('square', function(node) {
|
33462 | var val = (/^\W/.test(node.val) ? '\\' : '') + node.val;
|
33463 | return this.emit(val, node);
|
33464 | })
|
33465 |
|
33466 | /**
|
33467 | * Question mark: "?"
|
33468 | */
|
33469 |
|
33470 | .set('qmark', function(node) {
|
33471 | var prev = this.prev();
|
33472 | // don't use "slash" variable so that we always avoid
|
33473 | // matching backslashes and slashes with a qmark
|
33474 | var val = '[^.\\\\/]';
|
33475 | if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) {
|
33476 | val = '[^\\\\/]';
|
33477 | }
|
33478 |
|
33479 | if (node.parsed.slice(-1) === '(') {
|
33480 | var ch = node.rest.charAt(0);
|
33481 | if (ch === '!' || ch === '=' || ch === ':') {
|
33482 | return this.emit(node.val, node);
|
33483 | }
|
33484 | }
|
33485 |
|
33486 | if (node.val.length > 1) {
|
33487 | val += '{' + node.val.length + '}';
|
33488 | }
|
33489 | return this.emit(val, node);
|
33490 | })
|
33491 |
|
33492 | /**
|
33493 | * Plus
|
33494 | */
|
33495 |
|
33496 | .set('plus', function(node) {
|
33497 | var prev = node.parsed.slice(-1);
|
33498 | if (prev === ']' || prev === ')') {
|
33499 | return this.emit(node.val, node);
|
33500 | }
|
33501 | if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
|
33502 | return this.emit('\\+', node);
|
33503 | }
|
33504 | var ch = this.output.slice(-1);
|
33505 | if (/\w/.test(ch) && !node.inside) {
|
33506 | return this.emit('+\\+?', node);
|
33507 | }
|
33508 | return this.emit('+', node);
|
33509 | })
|
33510 |
|
33511 | /**
|
33512 | * globstar: '**'
|
33513 | */
|
33514 |
|
33515 | .set('globstar', function(node, nodes, i) {
|
33516 | if (!this.output) {
|
33517 | this.state.leadingGlobstar = true;
|
33518 | }
|
33519 |
|
33520 | var prev = this.prev();
|
33521 | var before = this.prev(2);
|
33522 | var next = this.next();
|
33523 | var after = this.next(2);
|
33524 | var type = prev.type;
|
33525 | var val = node.val;
|
33526 |
|
33527 | if (prev.type === 'slash' && next.type === 'slash') {
|
33528 | if (before.type === 'text') {
|
33529 | this.output += '?';
|
33530 |
|
33531 | if (after.type !== 'text') {
|
33532 | this.output += '\\b';
|
33533 | }
|
33534 | }
|
33535 | }
|
33536 |
|
33537 | var parsed = node.parsed;
|
33538 | if (parsed.charAt(0) === '!') {
|
33539 | parsed = parsed.slice(1);
|
33540 | }
|
33541 |
|
33542 | var isInside = node.isInside.paren || node.isInside.brace;
|
33543 | if (parsed && type !== 'slash' && type !== 'bos' && !isInside) {
|
33544 | val = star();
|
33545 | } else {
|
33546 | val = this.options.dot !== true
|
33547 | ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?'
|
33548 | : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?';
|
33549 | }
|
33550 |
|
33551 | if ((type === 'slash' || type === 'bos') && this.options.dot !== true) {
|
33552 | val = '(?!\\.)' + val;
|
33553 | }
|
33554 |
|
33555 | if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') {
|
33556 | if (after.type === 'text' || after.type === 'star') {
|
33557 | node.addQmark = true;
|
33558 | }
|
33559 | }
|
33560 |
|
33561 | if (this.options.capture) {
|
33562 | val = '(' + val + ')';
|
33563 | }
|
33564 |
|
33565 | return this.emit(val, node);
|
33566 | })
|
33567 |
|
33568 | /**
|
33569 | * Star: "*"
|
33570 | */
|
33571 |
|
33572 | .set('star', function(node, nodes, i) {
|
33573 | var prior = nodes[i - 2] || {};
|
33574 | var prev = this.prev();
|
33575 | var next = this.next();
|
33576 | var type = prev.type;
|
33577 |
|
33578 | function isStart(n) {
|
33579 | return n.type === 'bos' || n.type === 'slash';
|
33580 | }
|
33581 |
|
33582 | if (this.output === '' && this.options.contains !== true) {
|
33583 | this.output = '(?![' + slash() + '])';
|
33584 | }
|
33585 |
|
33586 | if (type === 'bracket' && this.options.bash === false) {
|
33587 | var str = next && next.type === 'bracket' ? star() : '*?';
|
33588 | if (!prev.nodes || prev.nodes[1].type !== 'posix') {
|
33589 | return this.emit(str, node);
|
33590 | }
|
33591 | }
|
33592 |
|
33593 | var prefix = !this.dotfiles && type !== 'text' && type !== 'escape'
|
33594 | ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)')
|
33595 | : '';
|
33596 |
|
33597 | if (isStart(prev) || (isStart(prior) && type === 'not')) {
|
33598 | if (prefix !== '(?!\\.)') {
|
33599 | prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)';
|
33600 | } else {
|
33601 | prefix += '(?=.)';
|
33602 | }
|
33603 | } else if (prefix === '(?!\\.)') {
|
33604 | prefix = '';
|
33605 | }
|
33606 |
|
33607 | if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) {
|
33608 | this.output = '(?!\\.)' + this.output;
|
33609 | }
|
33610 |
|
33611 | var output = prefix + star();
|
33612 | if (this.options.capture) {
|
33613 | output = '(' + output + ')';
|
33614 | }
|
33615 |
|
33616 | return this.emit(output, node);
|
33617 | })
|
33618 |
|
33619 | /**
|
33620 | * Text
|
33621 | */
|
33622 |
|
33623 | .set('text', function(node) {
|
33624 | return this.emit(node.val, node);
|
33625 | })
|
33626 |
|
33627 | /**
|
33628 | * End-of-string
|
33629 | */
|
33630 |
|
33631 | .set('eos', function(node) {
|
33632 | var prev = this.prev();
|
33633 | var val = node.val;
|
33634 |
|
33635 | this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output;
|
33636 | if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') {
|
33637 | val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)');
|
33638 | }
|
33639 |
|
33640 | return this.emit(val, node);
|
33641 | });
|
33642 |
|
33643 | /**
|
33644 | * Allow custom compilers to be passed on options
|
33645 | */
|
33646 |
|
33647 | if (options && typeof options.compilers === 'function') {
|
33648 | options.compilers(nanomatch.compiler);
|
33649 | }
|
33650 | };
|
33651 |
|
33652 | /**
|
33653 | * Characters to use in negation regex (we want to "not" match
|
33654 | * characters that are matched by other parsers)
|
33655 | */
|
33656 |
|
33657 | var cached;
|
33658 | var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+';
|
33659 | var not$1 = createTextRegex(NOT_REGEX);
|
33660 |
|
33661 | /**
|
33662 | * Nanomatch parsers
|
33663 | */
|
33664 |
|
33665 | var parsers$1 = function(nanomatch, options) {
|
33666 | var parser = nanomatch.parser;
|
33667 | var opts = parser.options;
|
33668 |
|
33669 | parser.state = {
|
33670 | slashes: 0,
|
33671 | paths: []
|
33672 | };
|
33673 |
|
33674 | parser.ast.state = parser.state;
|
33675 | parser
|
33676 |
|
33677 | /**
|
33678 | * Beginning-of-string
|
33679 | */
|
33680 |
|
33681 | .capture('prefix', function() {
|
33682 | if (this.parsed) return;
|
33683 | var m = this.match(/^\.[\\/]/);
|
33684 | if (!m) return;
|
33685 | this.state.strictOpen = !!this.options.strictOpen;
|
33686 | this.state.addPrefix = true;
|
33687 | })
|
33688 |
|
33689 | /**
|
33690 | * Escape: "\\."
|
33691 | */
|
33692 |
|
33693 | .capture('escape', function() {
|
33694 | if (this.isInside('bracket')) return;
|
33695 | var pos = this.position();
|
33696 | var m = this.match(/^(?:\\(.)|([$^]))/);
|
33697 | if (!m) return;
|
33698 |
|
33699 | return pos({
|
33700 | type: 'escape',
|
33701 | val: m[2] || m[1]
|
33702 | });
|
33703 | })
|
33704 |
|
33705 | /**
|
33706 | * Quoted strings
|
33707 | */
|
33708 |
|
33709 | .capture('quoted', function() {
|
33710 | var pos = this.position();
|
33711 | var m = this.match(/^["']/);
|
33712 | if (!m) return;
|
33713 |
|
33714 | var quote = m[0];
|
33715 | if (this.input.indexOf(quote) === -1) {
|
33716 | return pos({
|
33717 | type: 'escape',
|
33718 | val: quote
|
33719 | });
|
33720 | }
|
33721 |
|
33722 | var tok = advanceTo(this.input, quote);
|
33723 | this.consume(tok.len);
|
33724 |
|
33725 | return pos({
|
33726 | type: 'quoted',
|
33727 | val: tok.esc
|
33728 | });
|
33729 | })
|
33730 |
|
33731 | /**
|
33732 | * Negations: "!"
|
33733 | */
|
33734 |
|
33735 | .capture('not', function() {
|
33736 | var parsed = this.parsed;
|
33737 | var pos = this.position();
|
33738 | var m = this.match(this.notRegex || /^!+/);
|
33739 | if (!m) return;
|
33740 | var val = m[0];
|
33741 |
|
33742 | var isNegated = (val.length % 2) === 1;
|
33743 | if (parsed === '' && !isNegated) {
|
33744 | val = '';
|
33745 | }
|
33746 |
|
33747 | // if nothing has been parsed, we know `!` is at the start,
|
33748 | // so we need to wrap the result in a negation regex
|
33749 | if (parsed === '' && isNegated && this.options.nonegate !== true) {
|
33750 | this.bos.val = '(?!^(?:';
|
33751 | this.append = ')$).*';
|
33752 | val = '';
|
33753 | }
|
33754 | return pos({
|
33755 | type: 'not',
|
33756 | val: val
|
33757 | });
|
33758 | })
|
33759 |
|
33760 | /**
|
33761 | * Dot: "."
|
33762 | */
|
33763 |
|
33764 | .capture('dot', function() {
|
33765 | var parsed = this.parsed;
|
33766 | var pos = this.position();
|
33767 | var m = this.match(/^\.+/);
|
33768 | if (!m) return;
|
33769 |
|
33770 | var val = m[0];
|
33771 | this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/');
|
33772 |
|
33773 | return pos({
|
33774 | type: 'dot',
|
33775 | dotfiles: this.state.dot,
|
33776 | val: val
|
33777 | });
|
33778 | })
|
33779 |
|
33780 | /**
|
33781 | * Plus: "+"
|
33782 | */
|
33783 |
|
33784 | .capture('plus', /^\+(?!\()/)
|
33785 |
|
33786 | /**
|
33787 | * Question mark: "?"
|
33788 | */
|
33789 |
|
33790 | .capture('qmark', function() {
|
33791 | var parsed = this.parsed;
|
33792 | var pos = this.position();
|
33793 | var m = this.match(/^\?+(?!\()/);
|
33794 | if (!m) return;
|
33795 |
|
33796 | this.state.metachar = true;
|
33797 | this.state.qmark = true;
|
33798 |
|
33799 | return pos({
|
33800 | type: 'qmark',
|
33801 | parsed: parsed,
|
33802 | val: m[0]
|
33803 | });
|
33804 | })
|
33805 |
|
33806 | /**
|
33807 | * Globstar: "**"
|
33808 | */
|
33809 |
|
33810 | .capture('globstar', function() {
|
33811 | var parsed = this.parsed;
|
33812 | var pos = this.position();
|
33813 | var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/);
|
33814 | if (!m) return;
|
33815 |
|
33816 | var type = opts.noglobstar !== true ? 'globstar' : 'star';
|
33817 | var node = pos({type: type, parsed: parsed});
|
33818 | this.state.metachar = true;
|
33819 |
|
33820 | while (this.input.slice(0, 4) === '/**/') {
|
33821 | this.input = this.input.slice(3);
|
33822 | }
|
33823 |
|
33824 | node.isInside = {
|
33825 | brace: this.isInside('brace'),
|
33826 | paren: this.isInside('paren')
|
33827 | };
|
33828 |
|
33829 | if (type === 'globstar') {
|
33830 | this.state.globstar = true;
|
33831 | node.val = '**';
|
33832 |
|
33833 | } else {
|
33834 | this.state.star = true;
|
33835 | node.val = '*';
|
33836 | }
|
33837 |
|
33838 | return node;
|
33839 | })
|
33840 |
|
33841 | /**
|
33842 | * Star: "*"
|
33843 | */
|
33844 |
|
33845 | .capture('star', function() {
|
33846 | var pos = this.position();
|
33847 | var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/;
|
33848 | var m = this.match(starRe);
|
33849 | if (!m) return;
|
33850 |
|
33851 | this.state.metachar = true;
|
33852 | this.state.star = true;
|
33853 | return pos({
|
33854 | type: 'star',
|
33855 | val: m[0]
|
33856 | });
|
33857 | })
|
33858 |
|
33859 | /**
|
33860 | * Slash: "/"
|
33861 | */
|
33862 |
|
33863 | .capture('slash', function() {
|
33864 | var pos = this.position();
|
33865 | var m = this.match(/^\//);
|
33866 | if (!m) return;
|
33867 |
|
33868 | this.state.slashes++;
|
33869 | return pos({
|
33870 | type: 'slash',
|
33871 | val: m[0]
|
33872 | });
|
33873 | })
|
33874 |
|
33875 | /**
|
33876 | * Backslash: "\\"
|
33877 | */
|
33878 |
|
33879 | .capture('backslash', function() {
|
33880 | var pos = this.position();
|
33881 | var m = this.match(/^\\(?![*+?(){}[\]'"])/);
|
33882 | if (!m) return;
|
33883 |
|
33884 | var val = m[0];
|
33885 |
|
33886 | if (this.isInside('bracket')) {
|
33887 | val = '\\';
|
33888 | } else if (val.length > 1) {
|
33889 | val = '\\\\';
|
33890 | }
|
33891 |
|
33892 | return pos({
|
33893 | type: 'backslash',
|
33894 | val: val
|
33895 | });
|
33896 | })
|
33897 |
|
33898 | /**
|
33899 | * Square: "[.]"
|
33900 | */
|
33901 |
|
33902 | .capture('square', function() {
|
33903 | if (this.isInside('bracket')) return;
|
33904 | var pos = this.position();
|
33905 | var m = this.match(/^\[([^!^\\])\]/);
|
33906 | if (!m) return;
|
33907 |
|
33908 | return pos({
|
33909 | type: 'square',
|
33910 | val: m[1]
|
33911 | });
|
33912 | })
|
33913 |
|
33914 | /**
|
33915 | * Brackets: "[...]" (basic, this can be overridden by other parsers)
|
33916 | */
|
33917 |
|
33918 | .capture('bracket', function() {
|
33919 | var pos = this.position();
|
33920 | var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/);
|
33921 | if (!m) return;
|
33922 |
|
33923 | var val = m[0];
|
33924 | var negated = m[1] ? '^' : '';
|
33925 | var inner = (m[2] || '').replace(/\\\\+/, '\\\\');
|
33926 | var close = m[3] || '';
|
33927 |
|
33928 | if (m[2] && inner.length < m[2].length) {
|
33929 | val = val.replace(/\\\\+/, '\\\\');
|
33930 | }
|
33931 |
|
33932 | var esc = this.input.slice(0, 2);
|
33933 | if (inner === '' && esc === '\\]') {
|
33934 | inner += esc;
|
33935 | this.consume(2);
|
33936 |
|
33937 | var str = this.input;
|
33938 | var idx = -1;
|
33939 | var ch;
|
33940 |
|
33941 | while ((ch = str[++idx])) {
|
33942 | this.consume(1);
|
33943 | if (ch === ']') {
|
33944 | close = ch;
|
33945 | break;
|
33946 | }
|
33947 | inner += ch;
|
33948 | }
|
33949 | }
|
33950 |
|
33951 | return pos({
|
33952 | type: 'bracket',
|
33953 | val: val,
|
33954 | escaped: close !== ']',
|
33955 | negated: negated,
|
33956 | inner: inner,
|
33957 | close: close
|
33958 | });
|
33959 | })
|
33960 |
|
33961 | /**
|
33962 | * Text
|
33963 | */
|
33964 |
|
33965 | .capture('text', function() {
|
33966 | if (this.isInside('bracket')) return;
|
33967 | var pos = this.position();
|
33968 | var m = this.match(not$1);
|
33969 | if (!m || !m[0]) return;
|
33970 |
|
33971 | return pos({
|
33972 | type: 'text',
|
33973 | val: m[0]
|
33974 | });
|
33975 | });
|
33976 |
|
33977 | /**
|
33978 | * Allow custom parsers to be passed on options
|
33979 | */
|
33980 |
|
33981 | if (options && typeof options.parsers === 'function') {
|
33982 | options.parsers(nanomatch.parser);
|
33983 | }
|
33984 | };
|
33985 |
|
33986 | /**
|
33987 | * Advance to the next non-escaped character
|
33988 | */
|
33989 |
|
33990 | function advanceTo(input, endChar) {
|
33991 | var ch = input.charAt(0);
|
33992 | var tok = { len: 1, val: '', esc: '' };
|
33993 | var idx = 0;
|
33994 |
|
33995 | function advance() {
|
33996 | if (ch !== '\\') {
|
33997 | tok.esc += '\\' + ch;
|
33998 | tok.val += ch;
|
33999 | }
|
34000 |
|
34001 | ch = input.charAt(++idx);
|
34002 | tok.len++;
|
34003 |
|
34004 | if (ch === '\\') {
|
34005 | advance();
|
34006 | advance();
|
34007 | }
|
34008 | }
|
34009 |
|
34010 | while (ch && ch !== endChar) {
|
34011 | advance();
|
34012 | }
|
34013 | return tok;
|
34014 | }
|
34015 |
|
34016 | /**
|
34017 | * Create text regex
|
34018 | */
|
34019 |
|
34020 | function createTextRegex(pattern) {
|
34021 | if (cached) return cached;
|
34022 | var opts = {contains: true, strictClose: false};
|
34023 | var not = regexNot.create(pattern, opts);
|
34024 | var re = toRegex$1('^(?:[*]\\((?=.)|' + not + ')', opts);
|
34025 | return (cached = re);
|
34026 | }
|
34027 |
|
34028 | /**
|
34029 | * Expose negation string
|
34030 | */
|
34031 |
|
34032 | var not_1 = NOT_REGEX;
|
34033 | parsers$1.not = not_1;
|
34034 |
|
34035 | var fragmentCache = createCommonjsModule(function (module, exports) {
|
34036 |
|
34037 |
|
34038 |
|
34039 | /**
|
34040 | * Create a new `FragmentCache` with an optional object to use for `caches`.
|
34041 | *
|
34042 | * ```js
|
34043 | * var fragment = new FragmentCache();
|
34044 | * ```
|
34045 | * @name FragmentCache
|
34046 | * @param {String} `cacheName`
|
34047 | * @return {Object} Returns the [map-cache][] instance.
|
34048 | * @api public
|
34049 | */
|
34050 |
|
34051 | function FragmentCache(caches) {
|
34052 | this.caches = caches || {};
|
34053 | }
|
34054 |
|
34055 | /**
|
34056 | * Prototype
|
34057 | */
|
34058 |
|
34059 | FragmentCache.prototype = {
|
34060 |
|
34061 | /**
|
34062 | * Get cache `name` from the `fragment.caches` object. Creates a new
|
34063 | * `MapCache` if it doesn't already exist.
|
34064 | *
|
34065 | * ```js
|
34066 | * var cache = fragment.cache('files');
|
34067 | * console.log(fragment.caches.hasOwnProperty('files'));
|
34068 | * //=> true
|
34069 | * ```
|
34070 | * @name .cache
|
34071 | * @param {String} `cacheName`
|
34072 | * @return {Object} Returns the [map-cache][] instance.
|
34073 | * @api public
|
34074 | */
|
34075 |
|
34076 | cache: function(cacheName) {
|
34077 | return this.caches[cacheName] || (this.caches[cacheName] = new mapCache());
|
34078 | },
|
34079 |
|
34080 | /**
|
34081 | * Set a value for property `key` on cache `name`
|
34082 | *
|
34083 | * ```js
|
34084 | * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'}));
|
34085 | * ```
|
34086 | * @name .set
|
34087 | * @param {String} `name`
|
34088 | * @param {String} `key` Property name to set
|
34089 | * @param {any} `val` The value of `key`
|
34090 | * @return {Object} The cache instance for chaining
|
34091 | * @api public
|
34092 | */
|
34093 |
|
34094 | set: function(cacheName, key, val) {
|
34095 | var cache = this.cache(cacheName);
|
34096 | cache.set(key, val);
|
34097 | return cache;
|
34098 | },
|
34099 |
|
34100 | /**
|
34101 | * Returns true if a non-undefined value is set for `key` on fragment cache `name`.
|
34102 | *
|
34103 | * ```js
|
34104 | * var cache = fragment.cache('files');
|
34105 | * cache.set('somefile.js');
|
34106 | *
|
34107 | * console.log(cache.has('somefile.js'));
|
34108 | * //=> true
|
34109 | *
|
34110 | * console.log(cache.has('some-other-file.js'));
|
34111 | * //=> false
|
34112 | * ```
|
34113 | * @name .has
|
34114 | * @param {String} `name` Cache name
|
34115 | * @param {String} `key` Optionally specify a property to check for on cache `name`
|
34116 | * @return {Boolean}
|
34117 | * @api public
|
34118 | */
|
34119 |
|
34120 | has: function(cacheName, key) {
|
34121 | return typeof this.get(cacheName, key) !== 'undefined';
|
34122 | },
|
34123 |
|
34124 | /**
|
34125 | * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method,
|
34126 | * so that cache `name` will be created it doesn't already exist. If `key` is not passed,
|
34127 | * the entire cache (`name`) is returned.
|
34128 | *
|
34129 | * ```js
|
34130 | * var Vinyl = require('vinyl');
|
34131 | * var cache = fragment.cache('files');
|
34132 | * cache.set('somefile.js', new Vinyl({path: 'somefile.js'}));
|
34133 | * console.log(cache.get('somefile.js'));
|
34134 | * //=> <File "somefile.js">
|
34135 | * ```
|
34136 | * @name .get
|
34137 | * @param {String} `name`
|
34138 | * @return {Object} Returns cache `name`, or the value of `key` if specified
|
34139 | * @api public
|
34140 | */
|
34141 |
|
34142 | get: function(name, key) {
|
34143 | var cache = this.cache(name);
|
34144 | if (typeof key === 'string') {
|
34145 | return cache.get(key);
|
34146 | }
|
34147 | return cache;
|
34148 | }
|
34149 | };
|
34150 |
|
34151 | /**
|
34152 | * Expose `FragmentCache`
|
34153 | */
|
34154 |
|
34155 | exports = module.exports = FragmentCache;
|
34156 | });
|
34157 |
|
34158 | var cache$4 = new (fragmentCache)();
|
34159 |
|
34160 | var isWindows = createCommonjsModule(function (module, exports) {
|
34161 | /*!
|
34162 | * is-windows <https://github.com/jonschlinkert/is-windows>
|
34163 | *
|
34164 | * Copyright © 2015-2018, Jon Schlinkert.
|
34165 | * Released under the MIT License.
|
34166 | */
|
34167 |
|
34168 | (function(factory) {
|
34169 | if (exports && 'object' === 'object' && 'object' !== 'undefined') {
|
34170 | module.exports = factory();
|
34171 | } else if (typeof window !== 'undefined') {
|
34172 | window.isWindows = factory();
|
34173 | } else if (typeof commonjsGlobal !== 'undefined') {
|
34174 | commonjsGlobal.isWindows = factory();
|
34175 | } else if (typeof self !== 'undefined') {
|
34176 | self.isWindows = factory();
|
34177 | } else {
|
34178 | this.isWindows = factory();
|
34179 | }
|
34180 | })(function() {
|
34181 | return function isWindows() {
|
34182 | return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE));
|
34183 | };
|
34184 | });
|
34185 | });
|
34186 |
|
34187 | /*!
|
34188 | * arr-diff <https://github.com/jonschlinkert/arr-diff>
|
34189 | *
|
34190 | * Copyright (c) 2014-2017, Jon Schlinkert.
|
34191 | * Released under the MIT License.
|
34192 | */
|
34193 |
|
34194 | var arrDiff = function diff(arr/*, arrays*/) {
|
34195 | var len = arguments.length;
|
34196 | var idx = 0;
|
34197 | while (++idx < len) {
|
34198 | arr = diffArray(arr, arguments[idx]);
|
34199 | }
|
34200 | return arr;
|
34201 | };
|
34202 |
|
34203 | function diffArray(one, two) {
|
34204 | if (!Array.isArray(two)) {
|
34205 | return one.slice();
|
34206 | }
|
34207 |
|
34208 | var tlen = two.length;
|
34209 | var olen = one.length;
|
34210 | var idx = -1;
|
34211 | var arr = [];
|
34212 |
|
34213 | while (++idx < olen) {
|
34214 | var ele = one[idx];
|
34215 |
|
34216 | var hasEle = false;
|
34217 | for (var i = 0; i < tlen; i++) {
|
34218 | var val = two[i];
|
34219 |
|
34220 | if (ele === val) {
|
34221 | hasEle = true;
|
34222 | break;
|
34223 | }
|
34224 | }
|
34225 |
|
34226 | if (hasEle === false) {
|
34227 | arr.push(ele);
|
34228 | }
|
34229 | }
|
34230 | return arr;
|
34231 | }
|
34232 |
|
34233 | var object_pick = function pick(obj, keys) {
|
34234 | if (!isobject(obj) && typeof obj !== 'function') {
|
34235 | return {};
|
34236 | }
|
34237 |
|
34238 | var res = {};
|
34239 | if (typeof keys === 'string') {
|
34240 | if (keys in obj) {
|
34241 | res[keys] = obj[keys];
|
34242 | }
|
34243 | return res;
|
34244 | }
|
34245 |
|
34246 | var len = keys.length;
|
34247 | var idx = -1;
|
34248 |
|
34249 | while (++idx < len) {
|
34250 | var key = keys[idx];
|
34251 | if (key in obj) {
|
34252 | res[key] = obj[key];
|
34253 | }
|
34254 | }
|
34255 | return res;
|
34256 | };
|
34257 |
|
34258 | var utils_1$1 = createCommonjsModule(function (module) {
|
34259 |
|
34260 | var utils = module.exports;
|
34261 |
|
34262 |
|
34263 | /**
|
34264 | * Module dependencies
|
34265 | */
|
34266 |
|
34267 | var isWindows$1 = isWindows();
|
34268 |
|
34269 | utils.define = defineProperty;
|
34270 | utils.diff = arrDiff;
|
34271 | utils.extend = extendShallow;
|
34272 | utils.pick = object_pick;
|
34273 | utils.typeOf = kindOf;
|
34274 | utils.unique = arrayUnique;
|
34275 |
|
34276 | /**
|
34277 | * Returns true if the given value is effectively an empty string
|
34278 | */
|
34279 |
|
34280 | utils.isEmptyString = function(val) {
|
34281 | return String(val) === '' || String(val) === './';
|
34282 | };
|
34283 |
|
34284 | /**
|
34285 | * Returns true if the platform is windows, or `path.sep` is `\\`.
|
34286 | * This is defined as a function to allow `path.sep` to be set in unit tests,
|
34287 | * or by the user, if there is a reason to do so.
|
34288 | * @return {Boolean}
|
34289 | */
|
34290 |
|
34291 | utils.isWindows = function() {
|
34292 | return path__default.sep === '\\' || isWindows$1 === true;
|
34293 | };
|
34294 |
|
34295 | /**
|
34296 | * Return the last element from an array
|
34297 | */
|
34298 |
|
34299 | utils.last = function(arr, n) {
|
34300 | return arr[arr.length - (n || 1)];
|
34301 | };
|
34302 |
|
34303 | /**
|
34304 | * Get the `Snapdragon` instance to use
|
34305 | */
|
34306 |
|
34307 | utils.instantiate = function(ast, options) {
|
34308 | var snapdragon$1;
|
34309 | // if an instance was created by `.parse`, use that instance
|
34310 | if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
|
34311 | snapdragon$1 = ast.snapdragon;
|
34312 | // if the user supplies an instance on options, use that instance
|
34313 | } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
|
34314 | snapdragon$1 = options.snapdragon;
|
34315 | // create a new instance
|
34316 | } else {
|
34317 | snapdragon$1 = new snapdragon(options);
|
34318 | }
|
34319 |
|
34320 | utils.define(snapdragon$1, 'parse', function(str, options) {
|
34321 | var parsed = snapdragon.prototype.parse.call(this, str, options);
|
34322 | parsed.input = str;
|
34323 |
|
34324 | // escape unmatched brace/bracket/parens
|
34325 | var last = this.parser.stack.pop();
|
34326 | if (last && this.options.strictErrors !== true) {
|
34327 | var open = last.nodes[0];
|
34328 | var inner = last.nodes[1];
|
34329 | if (last.type === 'bracket') {
|
34330 | if (inner.val.charAt(0) === '[') {
|
34331 | inner.val = '\\' + inner.val;
|
34332 | }
|
34333 |
|
34334 | } else {
|
34335 | open.val = '\\' + open.val;
|
34336 | var sibling = open.parent.nodes[1];
|
34337 | if (sibling.type === 'star') {
|
34338 | sibling.loose = true;
|
34339 | }
|
34340 | }
|
34341 | }
|
34342 |
|
34343 | // add non-enumerable parser reference
|
34344 | utils.define(parsed, 'parser', this.parser);
|
34345 | return parsed;
|
34346 | });
|
34347 |
|
34348 | return snapdragon$1;
|
34349 | };
|
34350 |
|
34351 | /**
|
34352 | * Create the key to use for memoization. The key is generated
|
34353 | * by iterating over the options and concatenating key-value pairs
|
34354 | * to the pattern string.
|
34355 | */
|
34356 |
|
34357 | utils.createKey = function(pattern, options) {
|
34358 | if (typeof options === 'undefined') {
|
34359 | return pattern;
|
34360 | }
|
34361 | var key = pattern;
|
34362 | for (var prop in options) {
|
34363 | if (options.hasOwnProperty(prop)) {
|
34364 | key += ';' + prop + '=' + String(options[prop]);
|
34365 | }
|
34366 | }
|
34367 | return key;
|
34368 | };
|
34369 |
|
34370 | /**
|
34371 | * Cast `val` to an array
|
34372 | * @return {Array}
|
34373 | */
|
34374 |
|
34375 | utils.arrayify = function(val) {
|
34376 | if (typeof val === 'string') return [val];
|
34377 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
34378 | };
|
34379 |
|
34380 | /**
|
34381 | * Return true if `val` is a non-empty string
|
34382 | */
|
34383 |
|
34384 | utils.isString = function(val) {
|
34385 | return typeof val === 'string';
|
34386 | };
|
34387 |
|
34388 | /**
|
34389 | * Return true if `val` is a non-empty string
|
34390 | */
|
34391 |
|
34392 | utils.isRegex = function(val) {
|
34393 | return utils.typeOf(val) === 'regexp';
|
34394 | };
|
34395 |
|
34396 | /**
|
34397 | * Return true if `val` is a non-empty string
|
34398 | */
|
34399 |
|
34400 | utils.isObject = function(val) {
|
34401 | return utils.typeOf(val) === 'object';
|
34402 | };
|
34403 |
|
34404 | /**
|
34405 | * Escape regex characters in the given string
|
34406 | */
|
34407 |
|
34408 | utils.escapeRegex = function(str) {
|
34409 | return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&');
|
34410 | };
|
34411 |
|
34412 | /**
|
34413 | * Combines duplicate characters in the provided `input` string.
|
34414 | * @param {String} `input`
|
34415 | * @returns {String}
|
34416 | */
|
34417 |
|
34418 | utils.combineDupes = function(input, patterns) {
|
34419 | patterns = utils.arrayify(patterns).join('|').split('|');
|
34420 | patterns = patterns.map(function(s) {
|
34421 | return s.replace(/\\?([+*\\/])/g, '\\$1');
|
34422 | });
|
34423 | var substr = patterns.join('|');
|
34424 | var regex = new RegExp('(' + substr + ')(?=\\1)', 'g');
|
34425 | return input.replace(regex, '');
|
34426 | };
|
34427 |
|
34428 | /**
|
34429 | * Returns true if the given `str` has special characters
|
34430 | */
|
34431 |
|
34432 | utils.hasSpecialChars = function(str) {
|
34433 | return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str);
|
34434 | };
|
34435 |
|
34436 | /**
|
34437 | * Normalize slashes in the given filepath.
|
34438 | *
|
34439 | * @param {String} `filepath`
|
34440 | * @return {String}
|
34441 | */
|
34442 |
|
34443 | utils.toPosixPath = function(str) {
|
34444 | return str.replace(/\\+/g, '/');
|
34445 | };
|
34446 |
|
34447 | /**
|
34448 | * Strip backslashes before special characters in a string.
|
34449 | *
|
34450 | * @param {String} `str`
|
34451 | * @return {String}
|
34452 | */
|
34453 |
|
34454 | utils.unescape = function(str) {
|
34455 | return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
|
34456 | };
|
34457 |
|
34458 | /**
|
34459 | * Strip the drive letter from a windows filepath
|
34460 | * @param {String} `fp`
|
34461 | * @return {String}
|
34462 | */
|
34463 |
|
34464 | utils.stripDrive = function(fp) {
|
34465 | return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp;
|
34466 | };
|
34467 |
|
34468 | /**
|
34469 | * Strip the prefix from a filepath
|
34470 | * @param {String} `fp`
|
34471 | * @return {String}
|
34472 | */
|
34473 |
|
34474 | utils.stripPrefix = function(str) {
|
34475 | if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) {
|
34476 | return str.slice(2);
|
34477 | }
|
34478 | return str;
|
34479 | };
|
34480 |
|
34481 | /**
|
34482 | * Returns true if `str` is a common character that doesn't need
|
34483 | * to be processed to be used for matching.
|
34484 | * @param {String} `str`
|
34485 | * @return {Boolean}
|
34486 | */
|
34487 |
|
34488 | utils.isSimpleChar = function(str) {
|
34489 | return str.trim() === '' || str === '.';
|
34490 | };
|
34491 |
|
34492 | /**
|
34493 | * Returns true if the given str is an escaped or
|
34494 | * unescaped path character
|
34495 | */
|
34496 |
|
34497 | utils.isSlash = function(str) {
|
34498 | return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
|
34499 | };
|
34500 |
|
34501 | /**
|
34502 | * Returns a function that returns true if the given
|
34503 | * pattern matches or contains a `filepath`
|
34504 | *
|
34505 | * @param {String} `pattern`
|
34506 | * @return {Function}
|
34507 | */
|
34508 |
|
34509 | utils.matchPath = function(pattern, options) {
|
34510 | return (options && options.contains)
|
34511 | ? utils.containsPattern(pattern, options)
|
34512 | : utils.equalsPattern(pattern, options);
|
34513 | };
|
34514 |
|
34515 | /**
|
34516 | * Returns true if the given (original) filepath or unixified path are equal
|
34517 | * to the given pattern.
|
34518 | */
|
34519 |
|
34520 | utils._equals = function(filepath, unixPath, pattern) {
|
34521 | return pattern === filepath || pattern === unixPath;
|
34522 | };
|
34523 |
|
34524 | /**
|
34525 | * Returns true if the given (original) filepath or unixified path contain
|
34526 | * the given pattern.
|
34527 | */
|
34528 |
|
34529 | utils._contains = function(filepath, unixPath, pattern) {
|
34530 | return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
|
34531 | };
|
34532 |
|
34533 | /**
|
34534 | * Returns a function that returns true if the given
|
34535 | * pattern is the same as a given `filepath`
|
34536 | *
|
34537 | * @param {String} `pattern`
|
34538 | * @return {Function}
|
34539 | */
|
34540 |
|
34541 | utils.equalsPattern = function(pattern, options) {
|
34542 | var unixify = utils.unixify(options);
|
34543 | options = options || {};
|
34544 |
|
34545 | return function fn(filepath) {
|
34546 | var equal = utils._equals(filepath, unixify(filepath), pattern);
|
34547 | if (equal === true || options.nocase !== true) {
|
34548 | return equal;
|
34549 | }
|
34550 | var lower = filepath.toLowerCase();
|
34551 | return utils._equals(lower, unixify(lower), pattern);
|
34552 | };
|
34553 | };
|
34554 |
|
34555 | /**
|
34556 | * Returns a function that returns true if the given
|
34557 | * pattern contains a `filepath`
|
34558 | *
|
34559 | * @param {String} `pattern`
|
34560 | * @return {Function}
|
34561 | */
|
34562 |
|
34563 | utils.containsPattern = function(pattern, options) {
|
34564 | var unixify = utils.unixify(options);
|
34565 | options = options || {};
|
34566 |
|
34567 | return function(filepath) {
|
34568 | var contains = utils._contains(filepath, unixify(filepath), pattern);
|
34569 | if (contains === true || options.nocase !== true) {
|
34570 | return contains;
|
34571 | }
|
34572 | var lower = filepath.toLowerCase();
|
34573 | return utils._contains(lower, unixify(lower), pattern);
|
34574 | };
|
34575 | };
|
34576 |
|
34577 | /**
|
34578 | * Returns a function that returns true if the given
|
34579 | * regex matches the `filename` of a file path.
|
34580 | *
|
34581 | * @param {RegExp} `re` Matching regex
|
34582 | * @return {Function}
|
34583 | */
|
34584 |
|
34585 | utils.matchBasename = function(re) {
|
34586 | return function(filepath) {
|
34587 | return re.test(filepath) || re.test(path__default.basename(filepath));
|
34588 | };
|
34589 | };
|
34590 |
|
34591 | /**
|
34592 | * Returns the given value unchanced.
|
34593 | * @return {any}
|
34594 | */
|
34595 |
|
34596 | utils.identity = function(val) {
|
34597 | return val;
|
34598 | };
|
34599 |
|
34600 | /**
|
34601 | * Determines the filepath to return based on the provided options.
|
34602 | * @return {any}
|
34603 | */
|
34604 |
|
34605 | utils.value = function(str, unixify, options) {
|
34606 | if (options && options.unixify === false) {
|
34607 | return str;
|
34608 | }
|
34609 | if (options && typeof options.unixify === 'function') {
|
34610 | return options.unixify(str);
|
34611 | }
|
34612 | return unixify(str);
|
34613 | };
|
34614 |
|
34615 | /**
|
34616 | * Returns a function that normalizes slashes in a string to forward
|
34617 | * slashes, strips `./` from beginning of paths, and optionally unescapes
|
34618 | * special characters.
|
34619 | * @return {Function}
|
34620 | */
|
34621 |
|
34622 | utils.unixify = function(options) {
|
34623 | var opts = options || {};
|
34624 | return function(filepath) {
|
34625 | if (opts.stripPrefix !== false) {
|
34626 | filepath = utils.stripPrefix(filepath);
|
34627 | }
|
34628 | if (opts.unescape === true) {
|
34629 | filepath = utils.unescape(filepath);
|
34630 | }
|
34631 | if (opts.unixify === true || utils.isWindows()) {
|
34632 | filepath = utils.toPosixPath(filepath);
|
34633 | }
|
34634 | return filepath;
|
34635 | };
|
34636 | };
|
34637 | });
|
34638 |
|
34639 | /**
|
34640 | * Module dependencies
|
34641 | */
|
34642 |
|
34643 |
|
34644 |
|
34645 |
|
34646 |
|
34647 | /**
|
34648 | * Local dependencies
|
34649 | */
|
34650 |
|
34651 |
|
34652 |
|
34653 |
|
34654 |
|
34655 | var MAX_LENGTH$2 = 1024 * 64;
|
34656 |
|
34657 | /**
|
34658 | * The main function takes a list of strings and one or more
|
34659 | * glob patterns to use for matching.
|
34660 | *
|
34661 | * ```js
|
34662 | * var nm = require('nanomatch');
|
34663 | * nm(list, patterns[, options]);
|
34664 | *
|
34665 | * console.log(nm(['a.js', 'a.txt'], ['*.js']));
|
34666 | * //=> [ 'a.js' ]
|
34667 | * ```
|
34668 | * @param {Array} `list` A list of strings to match
|
34669 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
34670 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34671 | * @return {Array} Returns an array of matches
|
34672 | * @summary false
|
34673 | * @api public
|
34674 | */
|
34675 |
|
34676 | function nanomatch(list, patterns, options) {
|
34677 | patterns = utils_1$1.arrayify(patterns);
|
34678 | list = utils_1$1.arrayify(list);
|
34679 |
|
34680 | var len = patterns.length;
|
34681 | if (list.length === 0 || len === 0) {
|
34682 | return [];
|
34683 | }
|
34684 |
|
34685 | if (len === 1) {
|
34686 | return nanomatch.match(list, patterns[0], options);
|
34687 | }
|
34688 |
|
34689 | var negated = false;
|
34690 | var omit = [];
|
34691 | var keep = [];
|
34692 | var idx = -1;
|
34693 |
|
34694 | while (++idx < len) {
|
34695 | var pattern = patterns[idx];
|
34696 |
|
34697 | if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
|
34698 | omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options));
|
34699 | negated = true;
|
34700 | } else {
|
34701 | keep.push.apply(keep, nanomatch.match(list, pattern, options));
|
34702 | }
|
34703 | }
|
34704 |
|
34705 | // minimatch.match parity
|
34706 | if (negated && keep.length === 0) {
|
34707 | if (options && options.unixify === false) {
|
34708 | keep = list.slice();
|
34709 | } else {
|
34710 | var unixify = utils_1$1.unixify(options);
|
34711 | for (var i = 0; i < list.length; i++) {
|
34712 | keep.push(unixify(list[i]));
|
34713 | }
|
34714 | }
|
34715 | }
|
34716 |
|
34717 | var matches = utils_1$1.diff(keep, omit);
|
34718 | if (!options || options.nodupes !== false) {
|
34719 | return utils_1$1.unique(matches);
|
34720 | }
|
34721 |
|
34722 | return matches;
|
34723 | }
|
34724 |
|
34725 | /**
|
34726 | * Similar to the main function, but `pattern` must be a string.
|
34727 | *
|
34728 | * ```js
|
34729 | * var nm = require('nanomatch');
|
34730 | * nm.match(list, pattern[, options]);
|
34731 | *
|
34732 | * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
|
34733 | * //=> ['a.a', 'a.aa']
|
34734 | * ```
|
34735 | * @param {Array} `list` Array of strings to match
|
34736 | * @param {String} `pattern` Glob pattern to use for matching.
|
34737 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34738 | * @return {Array} Returns an array of matches
|
34739 | * @api public
|
34740 | */
|
34741 |
|
34742 | nanomatch.match = function(list, pattern, options) {
|
34743 | if (Array.isArray(pattern)) {
|
34744 | throw new TypeError('expected pattern to be a string');
|
34745 | }
|
34746 |
|
34747 | var unixify = utils_1$1.unixify(options);
|
34748 | var isMatch = memoize$2('match', pattern, options, nanomatch.matcher);
|
34749 | var matches = [];
|
34750 |
|
34751 | list = utils_1$1.arrayify(list);
|
34752 | var len = list.length;
|
34753 | var idx = -1;
|
34754 |
|
34755 | while (++idx < len) {
|
34756 | var ele = list[idx];
|
34757 | if (ele === pattern || isMatch(ele)) {
|
34758 | matches.push(utils_1$1.value(ele, unixify, options));
|
34759 | }
|
34760 | }
|
34761 |
|
34762 | // if no options were passed, uniquify results and return
|
34763 | if (typeof options === 'undefined') {
|
34764 | return utils_1$1.unique(matches);
|
34765 | }
|
34766 |
|
34767 | if (matches.length === 0) {
|
34768 | if (options.failglob === true) {
|
34769 | throw new Error('no matches found for "' + pattern + '"');
|
34770 | }
|
34771 | if (options.nonull === true || options.nullglob === true) {
|
34772 | return [options.unescape ? utils_1$1.unescape(pattern) : pattern];
|
34773 | }
|
34774 | }
|
34775 |
|
34776 | // if `opts.ignore` was defined, diff ignored list
|
34777 | if (options.ignore) {
|
34778 | matches = nanomatch.not(matches, options.ignore, options);
|
34779 | }
|
34780 |
|
34781 | return options.nodupes !== false ? utils_1$1.unique(matches) : matches;
|
34782 | };
|
34783 |
|
34784 | /**
|
34785 | * Returns true if the specified `string` matches the given glob `pattern`.
|
34786 | *
|
34787 | * ```js
|
34788 | * var nm = require('nanomatch');
|
34789 | * nm.isMatch(string, pattern[, options]);
|
34790 | *
|
34791 | * console.log(nm.isMatch('a.a', '*.a'));
|
34792 | * //=> true
|
34793 | * console.log(nm.isMatch('a.b', '*.a'));
|
34794 | * //=> false
|
34795 | * ```
|
34796 | * @param {String} `string` String to match
|
34797 | * @param {String} `pattern` Glob pattern to use for matching.
|
34798 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34799 | * @return {Boolean} Returns true if the string matches the glob pattern.
|
34800 | * @api public
|
34801 | */
|
34802 |
|
34803 | nanomatch.isMatch = function(str, pattern, options) {
|
34804 | if (typeof str !== 'string') {
|
34805 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
34806 | }
|
34807 |
|
34808 | if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(pattern)) {
|
34809 | return false;
|
34810 | }
|
34811 |
|
34812 | var equals = utils_1$1.equalsPattern(options);
|
34813 | if (equals(str)) {
|
34814 | return true;
|
34815 | }
|
34816 |
|
34817 | var isMatch = memoize$2('isMatch', pattern, options, nanomatch.matcher);
|
34818 | return isMatch(str);
|
34819 | };
|
34820 |
|
34821 | /**
|
34822 | * Returns true if some of the elements in the given `list` match any of the
|
34823 | * given glob `patterns`.
|
34824 | *
|
34825 | * ```js
|
34826 | * var nm = require('nanomatch');
|
34827 | * nm.some(list, patterns[, options]);
|
34828 | *
|
34829 | * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
|
34830 | * // true
|
34831 | * console.log(nm.some(['foo.js'], ['*.js', '!foo.js']));
|
34832 | * // false
|
34833 | * ```
|
34834 | * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
|
34835 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
34836 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34837 | * @return {Boolean} Returns true if any patterns match `str`
|
34838 | * @api public
|
34839 | */
|
34840 |
|
34841 | nanomatch.some = function(list, patterns, options) {
|
34842 | if (typeof list === 'string') {
|
34843 | list = [list];
|
34844 | }
|
34845 |
|
34846 | for (var i = 0; i < list.length; i++) {
|
34847 | if (nanomatch(list[i], patterns, options).length === 1) {
|
34848 | return true;
|
34849 | }
|
34850 | }
|
34851 |
|
34852 | return false;
|
34853 | };
|
34854 |
|
34855 | /**
|
34856 | * Returns true if every element in the given `list` matches
|
34857 | * at least one of the given glob `patterns`.
|
34858 | *
|
34859 | * ```js
|
34860 | * var nm = require('nanomatch');
|
34861 | * nm.every(list, patterns[, options]);
|
34862 | *
|
34863 | * console.log(nm.every('foo.js', ['foo.js']));
|
34864 | * // true
|
34865 | * console.log(nm.every(['foo.js', 'bar.js'], ['*.js']));
|
34866 | * // true
|
34867 | * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
|
34868 | * // false
|
34869 | * console.log(nm.every(['foo.js'], ['*.js', '!foo.js']));
|
34870 | * // false
|
34871 | * ```
|
34872 | * @param {String|Array} `list` The string or array of strings to test.
|
34873 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
34874 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34875 | * @return {Boolean} Returns true if any patterns match `str`
|
34876 | * @api public
|
34877 | */
|
34878 |
|
34879 | nanomatch.every = function(list, patterns, options) {
|
34880 | if (typeof list === 'string') {
|
34881 | list = [list];
|
34882 | }
|
34883 |
|
34884 | for (var i = 0; i < list.length; i++) {
|
34885 | if (nanomatch(list[i], patterns, options).length !== 1) {
|
34886 | return false;
|
34887 | }
|
34888 | }
|
34889 |
|
34890 | return true;
|
34891 | };
|
34892 |
|
34893 | /**
|
34894 | * Returns true if **any** of the given glob `patterns`
|
34895 | * match the specified `string`.
|
34896 | *
|
34897 | * ```js
|
34898 | * var nm = require('nanomatch');
|
34899 | * nm.any(string, patterns[, options]);
|
34900 | *
|
34901 | * console.log(nm.any('a.a', ['b.*', '*.a']));
|
34902 | * //=> true
|
34903 | * console.log(nm.any('a.a', 'b.*'));
|
34904 | * //=> false
|
34905 | * ```
|
34906 | * @param {String|Array} `str` The string to test.
|
34907 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
34908 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34909 | * @return {Boolean} Returns true if any patterns match `str`
|
34910 | * @api public
|
34911 | */
|
34912 |
|
34913 | nanomatch.any = function(str, patterns, options) {
|
34914 | if (typeof str !== 'string') {
|
34915 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
34916 | }
|
34917 |
|
34918 | if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
|
34919 | return false;
|
34920 | }
|
34921 |
|
34922 | if (typeof patterns === 'string') {
|
34923 | patterns = [patterns];
|
34924 | }
|
34925 |
|
34926 | for (var i = 0; i < patterns.length; i++) {
|
34927 | if (nanomatch.isMatch(str, patterns[i], options)) {
|
34928 | return true;
|
34929 | }
|
34930 | }
|
34931 | return false;
|
34932 | };
|
34933 |
|
34934 | /**
|
34935 | * Returns true if **all** of the given `patterns`
|
34936 | * match the specified string.
|
34937 | *
|
34938 | * ```js
|
34939 | * var nm = require('nanomatch');
|
34940 | * nm.all(string, patterns[, options]);
|
34941 | *
|
34942 | * console.log(nm.all('foo.js', ['foo.js']));
|
34943 | * // true
|
34944 | *
|
34945 | * console.log(nm.all('foo.js', ['*.js', '!foo.js']));
|
34946 | * // false
|
34947 | *
|
34948 | * console.log(nm.all('foo.js', ['*.js', 'foo.js']));
|
34949 | * // true
|
34950 | *
|
34951 | * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
|
34952 | * // true
|
34953 | * ```
|
34954 | * @param {String|Array} `str` The string to test.
|
34955 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
34956 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34957 | * @return {Boolean} Returns true if any patterns match `str`
|
34958 | * @api public
|
34959 | */
|
34960 |
|
34961 | nanomatch.all = function(str, patterns, options) {
|
34962 | if (typeof str !== 'string') {
|
34963 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
34964 | }
|
34965 |
|
34966 | if (typeof patterns === 'string') {
|
34967 | patterns = [patterns];
|
34968 | }
|
34969 |
|
34970 | for (var i = 0; i < patterns.length; i++) {
|
34971 | if (!nanomatch.isMatch(str, patterns[i], options)) {
|
34972 | return false;
|
34973 | }
|
34974 | }
|
34975 | return true;
|
34976 | };
|
34977 |
|
34978 | /**
|
34979 | * Returns a list of strings that _**do not match any**_ of the given `patterns`.
|
34980 | *
|
34981 | * ```js
|
34982 | * var nm = require('nanomatch');
|
34983 | * nm.not(list, patterns[, options]);
|
34984 | *
|
34985 | * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a'));
|
34986 | * //=> ['b.b', 'c.c']
|
34987 | * ```
|
34988 | * @param {Array} `list` Array of strings to match.
|
34989 | * @param {String|Array} `patterns` One or more glob pattern to use for matching.
|
34990 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
34991 | * @return {Array} Returns an array of strings that **do not match** the given patterns.
|
34992 | * @api public
|
34993 | */
|
34994 |
|
34995 | nanomatch.not = function(list, patterns, options) {
|
34996 | var opts = extendShallow({}, options);
|
34997 | var ignore = opts.ignore;
|
34998 | delete opts.ignore;
|
34999 |
|
35000 | list = utils_1$1.arrayify(list);
|
35001 |
|
35002 | var matches = utils_1$1.diff(list, nanomatch(list, patterns, opts));
|
35003 | if (ignore) {
|
35004 | matches = utils_1$1.diff(matches, nanomatch(list, ignore));
|
35005 | }
|
35006 |
|
35007 | return opts.nodupes !== false ? utils_1$1.unique(matches) : matches;
|
35008 | };
|
35009 |
|
35010 | /**
|
35011 | * Returns true if the given `string` contains the given pattern. Similar
|
35012 | * to [.isMatch](#isMatch) but the pattern can match any part of the string.
|
35013 | *
|
35014 | * ```js
|
35015 | * var nm = require('nanomatch');
|
35016 | * nm.contains(string, pattern[, options]);
|
35017 | *
|
35018 | * console.log(nm.contains('aa/bb/cc', '*b'));
|
35019 | * //=> true
|
35020 | * console.log(nm.contains('aa/bb/cc', '*d'));
|
35021 | * //=> false
|
35022 | * ```
|
35023 | * @param {String} `str` The string to match.
|
35024 | * @param {String|Array} `patterns` Glob pattern to use for matching.
|
35025 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
35026 | * @return {Boolean} Returns true if the patter matches any part of `str`.
|
35027 | * @api public
|
35028 | */
|
35029 |
|
35030 | nanomatch.contains = function(str, patterns, options) {
|
35031 | if (typeof str !== 'string') {
|
35032 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
35033 | }
|
35034 |
|
35035 | if (typeof patterns === 'string') {
|
35036 | if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
|
35037 | return false;
|
35038 | }
|
35039 |
|
35040 | var equals = utils_1$1.equalsPattern(patterns, options);
|
35041 | if (equals(str)) {
|
35042 | return true;
|
35043 | }
|
35044 | var contains = utils_1$1.containsPattern(patterns, options);
|
35045 | if (contains(str)) {
|
35046 | return true;
|
35047 | }
|
35048 | }
|
35049 |
|
35050 | var opts = extendShallow({}, options, {contains: true});
|
35051 | return nanomatch.any(str, patterns, opts);
|
35052 | };
|
35053 |
|
35054 | /**
|
35055 | * Returns true if the given pattern and options should enable
|
35056 | * the `matchBase` option.
|
35057 | * @return {Boolean}
|
35058 | * @api private
|
35059 | */
|
35060 |
|
35061 | nanomatch.matchBase = function(pattern, options) {
|
35062 | if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
|
35063 | return options.basename === true || options.matchBase === true;
|
35064 | };
|
35065 |
|
35066 | /**
|
35067 | * Filter the keys of the given object with the given `glob` pattern
|
35068 | * and `options`. Does not attempt to match nested keys. If you need this feature,
|
35069 | * use [glob-object][] instead.
|
35070 | *
|
35071 | * ```js
|
35072 | * var nm = require('nanomatch');
|
35073 | * nm.matchKeys(object, patterns[, options]);
|
35074 | *
|
35075 | * var obj = { aa: 'a', ab: 'b', ac: 'c' };
|
35076 | * console.log(nm.matchKeys(obj, '*b'));
|
35077 | * //=> { ab: 'b' }
|
35078 | * ```
|
35079 | * @param {Object} `object` The object with keys to filter.
|
35080 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
35081 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
35082 | * @return {Object} Returns an object with only keys that match the given patterns.
|
35083 | * @api public
|
35084 | */
|
35085 |
|
35086 | nanomatch.matchKeys = function(obj, patterns, options) {
|
35087 | if (!utils_1$1.isObject(obj)) {
|
35088 | throw new TypeError('expected the first argument to be an object');
|
35089 | }
|
35090 | var keys = nanomatch(Object.keys(obj), patterns, options);
|
35091 | return utils_1$1.pick(obj, keys);
|
35092 | };
|
35093 |
|
35094 | /**
|
35095 | * Returns a memoized matcher function from the given glob `pattern` and `options`.
|
35096 | * The returned function takes a string to match as its only argument and returns
|
35097 | * true if the string is a match.
|
35098 | *
|
35099 | * ```js
|
35100 | * var nm = require('nanomatch');
|
35101 | * nm.matcher(pattern[, options]);
|
35102 | *
|
35103 | * var isMatch = nm.matcher('*.!(*a)');
|
35104 | * console.log(isMatch('a.a'));
|
35105 | * //=> false
|
35106 | * console.log(isMatch('a.b'));
|
35107 | * //=> true
|
35108 | * ```
|
35109 | * @param {String} `pattern` Glob pattern
|
35110 | * @param {Object} `options` See available [options](#options) for changing how matches are performed.
|
35111 | * @return {Function} Returns a matcher function.
|
35112 | * @api public
|
35113 | */
|
35114 |
|
35115 | nanomatch.matcher = function matcher(pattern, options) {
|
35116 | if (utils_1$1.isEmptyString(pattern)) {
|
35117 | return function() {
|
35118 | return false;
|
35119 | };
|
35120 | }
|
35121 |
|
35122 | if (Array.isArray(pattern)) {
|
35123 | return compose(pattern, options, matcher);
|
35124 | }
|
35125 |
|
35126 | // if pattern is a regex
|
35127 | if (pattern instanceof RegExp) {
|
35128 | return test(pattern);
|
35129 | }
|
35130 |
|
35131 | // if pattern is invalid
|
35132 | if (!utils_1$1.isString(pattern)) {
|
35133 | throw new TypeError('expected pattern to be an array, string or regex');
|
35134 | }
|
35135 |
|
35136 | // if pattern is a non-glob string
|
35137 | if (!utils_1$1.hasSpecialChars(pattern)) {
|
35138 | if (options && options.nocase === true) {
|
35139 | pattern = pattern.toLowerCase();
|
35140 | }
|
35141 | return utils_1$1.matchPath(pattern, options);
|
35142 | }
|
35143 |
|
35144 | // if pattern is a glob string
|
35145 | var re = nanomatch.makeRe(pattern, options);
|
35146 |
|
35147 | // if `options.matchBase` or `options.basename` is defined
|
35148 | if (nanomatch.matchBase(pattern, options)) {
|
35149 | return utils_1$1.matchBasename(re, options);
|
35150 | }
|
35151 |
|
35152 | function test(regex) {
|
35153 | var equals = utils_1$1.equalsPattern(options);
|
35154 | var unixify = utils_1$1.unixify(options);
|
35155 |
|
35156 | return function(str) {
|
35157 | if (equals(str)) {
|
35158 | return true;
|
35159 | }
|
35160 |
|
35161 | if (regex.test(unixify(str))) {
|
35162 | return true;
|
35163 | }
|
35164 | return false;
|
35165 | };
|
35166 | }
|
35167 |
|
35168 | // create matcher function
|
35169 | var matcherFn = test(re);
|
35170 | // set result object from compiler on matcher function,
|
35171 | // as a non-enumerable property. useful for debugging
|
35172 | utils_1$1.define(matcherFn, 'result', re.result);
|
35173 | return matcherFn;
|
35174 | };
|
35175 |
|
35176 | /**
|
35177 | * Returns an array of matches captured by `pattern` in `string, or
|
35178 | * `null` if the pattern did not match.
|
35179 | *
|
35180 | * ```js
|
35181 | * var nm = require('nanomatch');
|
35182 | * nm.capture(pattern, string[, options]);
|
35183 | *
|
35184 | * console.log(nm.capture('test/*.js', 'test/foo.js'));
|
35185 | * //=> ['foo']
|
35186 | * console.log(nm.capture('test/*.js', 'foo/bar.css'));
|
35187 | * //=> null
|
35188 | * ```
|
35189 | * @param {String} `pattern` Glob pattern to use for matching.
|
35190 | * @param {String} `string` String to match
|
35191 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
35192 | * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
|
35193 | * @api public
|
35194 | */
|
35195 |
|
35196 | nanomatch.capture = function(pattern, str, options) {
|
35197 | var re = nanomatch.makeRe(pattern, extendShallow({capture: true}, options));
|
35198 | var unixify = utils_1$1.unixify(options);
|
35199 |
|
35200 | function match() {
|
35201 | return function(string) {
|
35202 | var match = re.exec(unixify(string));
|
35203 | if (!match) {
|
35204 | return null;
|
35205 | }
|
35206 |
|
35207 | return match.slice(1);
|
35208 | };
|
35209 | }
|
35210 |
|
35211 | var capture = memoize$2('capture', pattern, options, match);
|
35212 | return capture(str);
|
35213 | };
|
35214 |
|
35215 | /**
|
35216 | * Create a regular expression from the given glob `pattern`.
|
35217 | *
|
35218 | * ```js
|
35219 | * var nm = require('nanomatch');
|
35220 | * nm.makeRe(pattern[, options]);
|
35221 | *
|
35222 | * console.log(nm.makeRe('*.js'));
|
35223 | * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
|
35224 | * ```
|
35225 | * @param {String} `pattern` A glob pattern to convert to regex.
|
35226 | * @param {Object} `options` See available [options](#options) for changing how matches are performed.
|
35227 | * @return {RegExp} Returns a regex created from the given pattern.
|
35228 | * @api public
|
35229 | */
|
35230 |
|
35231 | nanomatch.makeRe = function(pattern, options) {
|
35232 | if (pattern instanceof RegExp) {
|
35233 | return pattern;
|
35234 | }
|
35235 |
|
35236 | if (typeof pattern !== 'string') {
|
35237 | throw new TypeError('expected pattern to be a string');
|
35238 | }
|
35239 |
|
35240 | if (pattern.length > MAX_LENGTH$2) {
|
35241 | throw new Error('expected pattern to be less than ' + MAX_LENGTH$2 + ' characters');
|
35242 | }
|
35243 |
|
35244 | function makeRe() {
|
35245 | var opts = utils_1$1.extend({wrap: false}, options);
|
35246 | var result = nanomatch.create(pattern, opts);
|
35247 | var regex = toRegex$1(result.output, opts);
|
35248 | utils_1$1.define(regex, 'result', result);
|
35249 | return regex;
|
35250 | }
|
35251 |
|
35252 | return memoize$2('makeRe', pattern, options, makeRe);
|
35253 | };
|
35254 |
|
35255 | /**
|
35256 | * Parses the given glob `pattern` and returns an object with the compiled `output`
|
35257 | * and optional source `map`.
|
35258 | *
|
35259 | * ```js
|
35260 | * var nm = require('nanomatch');
|
35261 | * nm.create(pattern[, options]);
|
35262 | *
|
35263 | * console.log(nm.create('abc/*.js'));
|
35264 | * // { options: { source: 'string', sourcemap: true },
|
35265 | * // state: {},
|
35266 | * // compilers:
|
35267 | * // { ... },
|
35268 | * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
|
35269 | * // ast:
|
35270 | * // { type: 'root',
|
35271 | * // errors: [],
|
35272 | * // nodes:
|
35273 | * // [ ... ],
|
35274 | * // dot: false,
|
35275 | * // input: 'abc/*.js' },
|
35276 | * // parsingErrors: [],
|
35277 | * // map:
|
35278 | * // { version: 3,
|
35279 | * // sources: [ 'string' ],
|
35280 | * // names: [],
|
35281 | * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
|
35282 | * // sourcesContent: [ 'abc/*.js' ] },
|
35283 | * // position: { line: 1, column: 28 },
|
35284 | * // content: {},
|
35285 | * // files: {},
|
35286 | * // idx: 6 }
|
35287 | * ```
|
35288 | * @param {String} `pattern` Glob pattern to parse and compile.
|
35289 | * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
|
35290 | * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
|
35291 | * @api public
|
35292 | */
|
35293 |
|
35294 | nanomatch.create = function(pattern, options) {
|
35295 | if (typeof pattern !== 'string') {
|
35296 | throw new TypeError('expected a string');
|
35297 | }
|
35298 | function create() {
|
35299 | return nanomatch.compile(nanomatch.parse(pattern, options), options);
|
35300 | }
|
35301 | return memoize$2('create', pattern, options, create);
|
35302 | };
|
35303 |
|
35304 | /**
|
35305 | * Parse the given `str` with the given `options`.
|
35306 | *
|
35307 | * ```js
|
35308 | * var nm = require('nanomatch');
|
35309 | * nm.parse(pattern[, options]);
|
35310 | *
|
35311 | * var ast = nm.parse('a/{b,c}/d');
|
35312 | * console.log(ast);
|
35313 | * // { type: 'root',
|
35314 | * // errors: [],
|
35315 | * // input: 'a/{b,c}/d',
|
35316 | * // nodes:
|
35317 | * // [ { type: 'bos', val: '' },
|
35318 | * // { type: 'text', val: 'a/' },
|
35319 | * // { type: 'brace',
|
35320 | * // nodes:
|
35321 | * // [ { type: 'brace.open', val: '{' },
|
35322 | * // { type: 'text', val: 'b,c' },
|
35323 | * // { type: 'brace.close', val: '}' } ] },
|
35324 | * // { type: 'text', val: '/d' },
|
35325 | * // { type: 'eos', val: '' } ] }
|
35326 | * ```
|
35327 | * @param {String} `str`
|
35328 | * @param {Object} `options`
|
35329 | * @return {Object} Returns an AST
|
35330 | * @api public
|
35331 | */
|
35332 |
|
35333 | nanomatch.parse = function(pattern, options) {
|
35334 | if (typeof pattern !== 'string') {
|
35335 | throw new TypeError('expected a string');
|
35336 | }
|
35337 |
|
35338 | function parse() {
|
35339 | var snapdragon = utils_1$1.instantiate(null, options);
|
35340 | parsers$1(snapdragon, options);
|
35341 |
|
35342 | var ast = snapdragon.parse(pattern, options);
|
35343 | utils_1$1.define(ast, 'snapdragon', snapdragon);
|
35344 | ast.input = pattern;
|
35345 | return ast;
|
35346 | }
|
35347 |
|
35348 | return memoize$2('parse', pattern, options, parse);
|
35349 | };
|
35350 |
|
35351 | /**
|
35352 | * Compile the given `ast` or string with the given `options`.
|
35353 | *
|
35354 | * ```js
|
35355 | * var nm = require('nanomatch');
|
35356 | * nm.compile(ast[, options]);
|
35357 | *
|
35358 | * var ast = nm.parse('a/{b,c}/d');
|
35359 | * console.log(nm.compile(ast));
|
35360 | * // { options: { source: 'string' },
|
35361 | * // state: {},
|
35362 | * // compilers:
|
35363 | * // { eos: [Function],
|
35364 | * // noop: [Function],
|
35365 | * // bos: [Function],
|
35366 | * // brace: [Function],
|
35367 | * // 'brace.open': [Function],
|
35368 | * // text: [Function],
|
35369 | * // 'brace.close': [Function] },
|
35370 | * // output: [ 'a/(b|c)/d' ],
|
35371 | * // ast:
|
35372 | * // { ... },
|
35373 | * // parsingErrors: [] }
|
35374 | * ```
|
35375 | * @param {Object|String} `ast`
|
35376 | * @param {Object} `options`
|
35377 | * @return {Object} Returns an object that has an `output` property with the compiled string.
|
35378 | * @api public
|
35379 | */
|
35380 |
|
35381 | nanomatch.compile = function(ast, options) {
|
35382 | if (typeof ast === 'string') {
|
35383 | ast = nanomatch.parse(ast, options);
|
35384 | }
|
35385 |
|
35386 | function compile() {
|
35387 | var snapdragon = utils_1$1.instantiate(ast, options);
|
35388 | compilers$1(snapdragon, options);
|
35389 | return snapdragon.compile(ast, options);
|
35390 | }
|
35391 |
|
35392 | return memoize$2('compile', ast.input, options, compile);
|
35393 | };
|
35394 |
|
35395 | /**
|
35396 | * Clear the regex cache.
|
35397 | *
|
35398 | * ```js
|
35399 | * nm.clearCache();
|
35400 | * ```
|
35401 | * @api public
|
35402 | */
|
35403 |
|
35404 | nanomatch.clearCache = function() {
|
35405 | nanomatch.cache.__data__ = {};
|
35406 | };
|
35407 |
|
35408 | /**
|
35409 | * Compose a matcher function with the given patterns.
|
35410 | * This allows matcher functions to be compiled once and
|
35411 | * called multiple times.
|
35412 | */
|
35413 |
|
35414 | function compose(patterns, options, matcher) {
|
35415 | var matchers;
|
35416 |
|
35417 | return memoize$2('compose', String(patterns), options, function() {
|
35418 | return function(file) {
|
35419 | // delay composition until it's invoked the first time,
|
35420 | // after that it won't be called again
|
35421 | if (!matchers) {
|
35422 | matchers = [];
|
35423 | for (var i = 0; i < patterns.length; i++) {
|
35424 | matchers.push(matcher(patterns[i], options));
|
35425 | }
|
35426 | }
|
35427 |
|
35428 | var len = matchers.length;
|
35429 | while (len--) {
|
35430 | if (matchers[len](file) === true) {
|
35431 | return true;
|
35432 | }
|
35433 | }
|
35434 | return false;
|
35435 | };
|
35436 | });
|
35437 | }
|
35438 |
|
35439 | /**
|
35440 | * Memoize a generated regex or function. A unique key is generated
|
35441 | * from the `type` (usually method name), the `pattern`, and
|
35442 | * user-defined options.
|
35443 | */
|
35444 |
|
35445 | function memoize$2(type, pattern, options, fn) {
|
35446 | var key = utils_1$1.createKey(type + '=' + pattern, options);
|
35447 |
|
35448 | if (options && options.cache === false) {
|
35449 | return fn(pattern, options);
|
35450 | }
|
35451 |
|
35452 | if (cache$4.has(type, key)) {
|
35453 | return cache$4.get(type, key);
|
35454 | }
|
35455 |
|
35456 | var val = fn(pattern, options);
|
35457 | cache$4.set(type, key, val);
|
35458 | return val;
|
35459 | }
|
35460 |
|
35461 | /**
|
35462 | * Expose compiler, parser and cache on `nanomatch`
|
35463 | */
|
35464 |
|
35465 | nanomatch.compilers = compilers$1;
|
35466 | nanomatch.parsers = parsers$1;
|
35467 | nanomatch.cache = cache$4;
|
35468 |
|
35469 | /**
|
35470 | * Expose `nanomatch`
|
35471 | * @type {Function}
|
35472 | */
|
35473 |
|
35474 | var nanomatch_1 = nanomatch;
|
35475 |
|
35476 | var extendShallow$6 = function extend(o/*, objects*/) {
|
35477 | if (!isExtendable$1(o)) { o = {}; }
|
35478 |
|
35479 | var len = arguments.length;
|
35480 | for (var i = 1; i < len; i++) {
|
35481 | var obj = arguments[i];
|
35482 |
|
35483 | if (isExtendable$1(obj)) {
|
35484 | assign$6(o, obj);
|
35485 | }
|
35486 | }
|
35487 | return o;
|
35488 | };
|
35489 |
|
35490 | function assign$6(a, b) {
|
35491 | for (var key in b) {
|
35492 | if (hasOwn$7(b, key)) {
|
35493 | a[key] = b[key];
|
35494 | }
|
35495 | }
|
35496 | }
|
35497 |
|
35498 | /**
|
35499 | * Returns true if the given `key` is an own property of `obj`.
|
35500 | */
|
35501 |
|
35502 | function hasOwn$7(obj, key) {
|
35503 | return Object.prototype.hasOwnProperty.call(obj, key);
|
35504 | }
|
35505 |
|
35506 | /**
|
35507 | * POSIX character classes
|
35508 | */
|
35509 |
|
35510 | var posixCharacterClasses = {
|
35511 | alnum: 'a-zA-Z0-9',
|
35512 | alpha: 'a-zA-Z',
|
35513 | ascii: '\\x00-\\x7F',
|
35514 | blank: ' \\t',
|
35515 | cntrl: '\\x00-\\x1F\\x7F',
|
35516 | digit: '0-9',
|
35517 | graph: '\\x21-\\x7E',
|
35518 | lower: 'a-z',
|
35519 | print: '\\x20-\\x7E ',
|
35520 | punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
|
35521 | space: ' \\t\\r\\n\\v\\f',
|
35522 | upper: 'A-Z',
|
35523 | word: 'A-Za-z0-9_',
|
35524 | xdigit: 'A-Fa-f0-9'
|
35525 | };
|
35526 |
|
35527 | var compilers$2 = function(brackets) {
|
35528 | brackets.compiler
|
35529 |
|
35530 | /**
|
35531 | * Escaped characters
|
35532 | */
|
35533 |
|
35534 | .set('escape', function(node) {
|
35535 | return this.emit('\\' + node.val.replace(/^\\/, ''), node);
|
35536 | })
|
35537 |
|
35538 | /**
|
35539 | * Text
|
35540 | */
|
35541 |
|
35542 | .set('text', function(node) {
|
35543 | return this.emit(node.val.replace(/([{}])/g, '\\$1'), node);
|
35544 | })
|
35545 |
|
35546 | /**
|
35547 | * POSIX character classes
|
35548 | */
|
35549 |
|
35550 | .set('posix', function(node) {
|
35551 | if (node.val === '[::]') {
|
35552 | return this.emit('\\[::\\]', node);
|
35553 | }
|
35554 |
|
35555 | var val = posixCharacterClasses[node.inner];
|
35556 | if (typeof val === 'undefined') {
|
35557 | val = '[' + node.inner + ']';
|
35558 | }
|
35559 | return this.emit(val, node);
|
35560 | })
|
35561 |
|
35562 | /**
|
35563 | * Non-posix brackets
|
35564 | */
|
35565 |
|
35566 | .set('bracket', function(node) {
|
35567 | return this.mapVisit(node.nodes);
|
35568 | })
|
35569 | .set('bracket.open', function(node) {
|
35570 | return this.emit(node.val, node);
|
35571 | })
|
35572 | .set('bracket.inner', function(node) {
|
35573 | var inner = node.val;
|
35574 |
|
35575 | if (inner === '[' || inner === ']') {
|
35576 | return this.emit('\\' + node.val, node);
|
35577 | }
|
35578 | if (inner === '^]') {
|
35579 | return this.emit('^\\]', node);
|
35580 | }
|
35581 | if (inner === '^') {
|
35582 | return this.emit('^', node);
|
35583 | }
|
35584 |
|
35585 | if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) {
|
35586 | inner = inner.split('-').join('\\-');
|
35587 | }
|
35588 |
|
35589 | var isNegated = inner.charAt(0) === '^';
|
35590 | // add slashes to negated brackets, per spec
|
35591 | if (isNegated && inner.indexOf('/') === -1) {
|
35592 | inner += '/';
|
35593 | }
|
35594 | if (isNegated && inner.indexOf('.') === -1) {
|
35595 | inner += '.';
|
35596 | }
|
35597 |
|
35598 | // don't unescape `0` (octal literal)
|
35599 | inner = inner.replace(/\\([1-9])/g, '$1');
|
35600 | return this.emit(inner, node);
|
35601 | })
|
35602 | .set('bracket.close', function(node) {
|
35603 | var val = node.val.replace(/^\\/, '');
|
35604 | if (node.parent.escaped === true) {
|
35605 | return this.emit('\\' + val, node);
|
35606 | }
|
35607 | return this.emit(val, node);
|
35608 | });
|
35609 | };
|
35610 |
|
35611 | var cached$1;
|
35612 |
|
35613 | /**
|
35614 | * Get the last element from `array`
|
35615 | * @param {Array} `array`
|
35616 | * @return {*}
|
35617 | */
|
35618 |
|
35619 | var last$1 = function(arr) {
|
35620 | return arr[arr.length - 1];
|
35621 | };
|
35622 |
|
35623 | /**
|
35624 | * Create and cache regex to use for text nodes
|
35625 | */
|
35626 |
|
35627 | var createRegex = function(pattern, include) {
|
35628 | if (cached$1) return cached$1;
|
35629 | var opts = {contains: true, strictClose: false};
|
35630 | var not = regexNot.create(pattern, opts);
|
35631 | var re;
|
35632 |
|
35633 | if (typeof include === 'string') {
|
35634 | re = toRegex$1('^(?:' + include + '|' + not + ')', opts);
|
35635 | } else {
|
35636 | re = toRegex$1(not, opts);
|
35637 | }
|
35638 |
|
35639 | return (cached$1 = re);
|
35640 | };
|
35641 |
|
35642 | var utils$2 = {
|
35643 | last: last$1,
|
35644 | createRegex: createRegex
|
35645 | };
|
35646 |
|
35647 | var defineProperty$7 = function defineProperty(obj, prop, val) {
|
35648 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
35649 | throw new TypeError('expected an object or function.');
|
35650 | }
|
35651 |
|
35652 | if (typeof prop !== 'string') {
|
35653 | throw new TypeError('expected `prop` to be a string.');
|
35654 | }
|
35655 |
|
35656 | if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
|
35657 | return Object.defineProperty(obj, prop, val);
|
35658 | }
|
35659 |
|
35660 | return Object.defineProperty(obj, prop, {
|
35661 | configurable: true,
|
35662 | enumerable: false,
|
35663 | writable: true,
|
35664 | value: val
|
35665 | });
|
35666 | };
|
35667 |
|
35668 | /**
|
35669 | * Text regex
|
35670 | */
|
35671 |
|
35672 | var TEXT_REGEX = '(\\[(?=.*\\])|\\])+';
|
35673 | var not$2 = utils$2.createRegex(TEXT_REGEX);
|
35674 |
|
35675 | /**
|
35676 | * Brackets parsers
|
35677 | */
|
35678 |
|
35679 | function parsers$2(brackets) {
|
35680 | brackets.state = brackets.state || {};
|
35681 | brackets.parser.sets.bracket = brackets.parser.sets.bracket || [];
|
35682 | brackets.parser
|
35683 |
|
35684 | .capture('escape', function() {
|
35685 | if (this.isInside('bracket')) return;
|
35686 | var pos = this.position();
|
35687 | var m = this.match(/^\\(.)/);
|
35688 | if (!m) return;
|
35689 |
|
35690 | return pos({
|
35691 | type: 'escape',
|
35692 | val: m[0]
|
35693 | });
|
35694 | })
|
35695 |
|
35696 | /**
|
35697 | * Text parser
|
35698 | */
|
35699 |
|
35700 | .capture('text', function() {
|
35701 | if (this.isInside('bracket')) return;
|
35702 | var pos = this.position();
|
35703 | var m = this.match(not$2);
|
35704 | if (!m || !m[0]) return;
|
35705 |
|
35706 | return pos({
|
35707 | type: 'text',
|
35708 | val: m[0]
|
35709 | });
|
35710 | })
|
35711 |
|
35712 | /**
|
35713 | * POSIX character classes: "[[:alpha:][:digits:]]"
|
35714 | */
|
35715 |
|
35716 | .capture('posix', function() {
|
35717 | var pos = this.position();
|
35718 | var m = this.match(/^\[:(.*?):\](?=.*\])/);
|
35719 | if (!m) return;
|
35720 |
|
35721 | var inside = this.isInside('bracket');
|
35722 | if (inside) {
|
35723 | brackets.posix++;
|
35724 | }
|
35725 |
|
35726 | return pos({
|
35727 | type: 'posix',
|
35728 | insideBracket: inside,
|
35729 | inner: m[1],
|
35730 | val: m[0]
|
35731 | });
|
35732 | })
|
35733 |
|
35734 | /**
|
35735 | * Bracket (noop)
|
35736 | */
|
35737 |
|
35738 | .capture('bracket', function() {})
|
35739 |
|
35740 | /**
|
35741 | * Open: '['
|
35742 | */
|
35743 |
|
35744 | .capture('bracket.open', function() {
|
35745 | var parsed = this.parsed;
|
35746 | var pos = this.position();
|
35747 | var m = this.match(/^\[(?=.*\])/);
|
35748 | if (!m) return;
|
35749 |
|
35750 | var prev = this.prev();
|
35751 | var last = utils$2.last(prev.nodes);
|
35752 |
|
35753 | if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
|
35754 | last.val = last.val.slice(0, last.val.length - 1);
|
35755 | return pos({
|
35756 | type: 'escape',
|
35757 | val: m[0]
|
35758 | });
|
35759 | }
|
35760 |
|
35761 | var open = pos({
|
35762 | type: 'bracket.open',
|
35763 | val: m[0]
|
35764 | });
|
35765 |
|
35766 | if (last.type === 'bracket.open' || this.isInside('bracket')) {
|
35767 | open.val = '\\' + open.val;
|
35768 | open.type = 'bracket.inner';
|
35769 | open.escaped = true;
|
35770 | return open;
|
35771 | }
|
35772 |
|
35773 | var node = pos({
|
35774 | type: 'bracket',
|
35775 | nodes: [open]
|
35776 | });
|
35777 |
|
35778 | defineProperty$7(node, 'parent', prev);
|
35779 | defineProperty$7(open, 'parent', node);
|
35780 | this.push('bracket', node);
|
35781 | prev.nodes.push(node);
|
35782 | })
|
35783 |
|
35784 | /**
|
35785 | * Bracket text
|
35786 | */
|
35787 |
|
35788 | .capture('bracket.inner', function() {
|
35789 | if (!this.isInside('bracket')) return;
|
35790 | var pos = this.position();
|
35791 | var m = this.match(not$2);
|
35792 | if (!m || !m[0]) return;
|
35793 |
|
35794 | var next = this.input.charAt(0);
|
35795 | var val = m[0];
|
35796 |
|
35797 | var node = pos({
|
35798 | type: 'bracket.inner',
|
35799 | val: val
|
35800 | });
|
35801 |
|
35802 | if (val === '\\\\') {
|
35803 | return node;
|
35804 | }
|
35805 |
|
35806 | var first = val.charAt(0);
|
35807 | var last = val.slice(-1);
|
35808 |
|
35809 | if (first === '!') {
|
35810 | val = '^' + val.slice(1);
|
35811 | }
|
35812 |
|
35813 | if (last === '\\' || (val === '^' && next === ']')) {
|
35814 | val += this.input[0];
|
35815 | this.consume(1);
|
35816 | }
|
35817 |
|
35818 | node.val = val;
|
35819 | return node;
|
35820 | })
|
35821 |
|
35822 | /**
|
35823 | * Close: ']'
|
35824 | */
|
35825 |
|
35826 | .capture('bracket.close', function() {
|
35827 | var parsed = this.parsed;
|
35828 | var pos = this.position();
|
35829 | var m = this.match(/^\]/);
|
35830 | if (!m) return;
|
35831 |
|
35832 | var prev = this.prev();
|
35833 | var last = utils$2.last(prev.nodes);
|
35834 |
|
35835 | if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
|
35836 | last.val = last.val.slice(0, last.val.length - 1);
|
35837 |
|
35838 | return pos({
|
35839 | type: 'escape',
|
35840 | val: m[0]
|
35841 | });
|
35842 | }
|
35843 |
|
35844 | var node = pos({
|
35845 | type: 'bracket.close',
|
35846 | rest: this.input,
|
35847 | val: m[0]
|
35848 | });
|
35849 |
|
35850 | if (last.type === 'bracket.open') {
|
35851 | node.type = 'bracket.inner';
|
35852 | node.escaped = true;
|
35853 | return node;
|
35854 | }
|
35855 |
|
35856 | var bracket = this.pop('bracket');
|
35857 | if (!this.isType(bracket, 'bracket')) {
|
35858 | if (this.options.strict) {
|
35859 | throw new Error('missing opening "["');
|
35860 | }
|
35861 | node.type = 'bracket.inner';
|
35862 | node.escaped = true;
|
35863 | return node;
|
35864 | }
|
35865 |
|
35866 | bracket.nodes.push(node);
|
35867 | defineProperty$7(node, 'parent', bracket);
|
35868 | });
|
35869 | }
|
35870 |
|
35871 | /**
|
35872 | * Brackets parsers
|
35873 | */
|
35874 |
|
35875 | var parsers_1 = parsers$2;
|
35876 |
|
35877 | /**
|
35878 | * Expose text regex
|
35879 | */
|
35880 |
|
35881 | var TEXT_REGEX_1 = TEXT_REGEX;
|
35882 | parsers_1.TEXT_REGEX = TEXT_REGEX_1;
|
35883 |
|
35884 | var extendShallow$7 = function extend(o/*, objects*/) {
|
35885 | if (!isExtendable$1(o)) { o = {}; }
|
35886 |
|
35887 | var len = arguments.length;
|
35888 | for (var i = 1; i < len; i++) {
|
35889 | var obj = arguments[i];
|
35890 |
|
35891 | if (isExtendable$1(obj)) {
|
35892 | assign$7(o, obj);
|
35893 | }
|
35894 | }
|
35895 | return o;
|
35896 | };
|
35897 |
|
35898 | function assign$7(a, b) {
|
35899 | for (var key in b) {
|
35900 | if (hasOwn$8(b, key)) {
|
35901 | a[key] = b[key];
|
35902 | }
|
35903 | }
|
35904 | }
|
35905 |
|
35906 | /**
|
35907 | * Returns true if the given `key` is an own property of `obj`.
|
35908 | */
|
35909 |
|
35910 | function hasOwn$8(obj, key) {
|
35911 | return Object.prototype.hasOwnProperty.call(obj, key);
|
35912 | }
|
35913 |
|
35914 | /**
|
35915 | * Local dependencies
|
35916 | */
|
35917 |
|
35918 |
|
35919 |
|
35920 |
|
35921 | /**
|
35922 | * Module dependencies
|
35923 | */
|
35924 |
|
35925 | var debug$3 = src('expand-brackets');
|
35926 |
|
35927 |
|
35928 |
|
35929 |
|
35930 | /**
|
35931 | * Parses the given POSIX character class `pattern` and returns a
|
35932 | * string that can be used for creating regular expressions for matching.
|
35933 | *
|
35934 | * @param {String} `pattern`
|
35935 | * @param {Object} `options`
|
35936 | * @return {Object}
|
35937 | * @api public
|
35938 | */
|
35939 |
|
35940 | function brackets(pattern, options) {
|
35941 | debug$3('initializing from <%s>', __filename);
|
35942 | var res = brackets.create(pattern, options);
|
35943 | return res.output;
|
35944 | }
|
35945 |
|
35946 | /**
|
35947 | * Takes an array of strings and a POSIX character class pattern, and returns a new
|
35948 | * array with only the strings that matched the pattern.
|
35949 | *
|
35950 | * ```js
|
35951 | * var brackets = require('expand-brackets');
|
35952 | * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]'));
|
35953 | * //=> ['a']
|
35954 | *
|
35955 | * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+'));
|
35956 | * //=> ['a', 'ab']
|
35957 | * ```
|
35958 | * @param {Array} `arr` Array of strings to match
|
35959 | * @param {String} `pattern` POSIX character class pattern(s)
|
35960 | * @param {Object} `options`
|
35961 | * @return {Array}
|
35962 | * @api public
|
35963 | */
|
35964 |
|
35965 | brackets.match = function(arr, pattern, options) {
|
35966 | arr = [].concat(arr);
|
35967 | var opts = extendShallow$7({}, options);
|
35968 | var isMatch = brackets.matcher(pattern, opts);
|
35969 | var len = arr.length;
|
35970 | var idx = -1;
|
35971 | var res = [];
|
35972 |
|
35973 | while (++idx < len) {
|
35974 | var ele = arr[idx];
|
35975 | if (isMatch(ele)) {
|
35976 | res.push(ele);
|
35977 | }
|
35978 | }
|
35979 |
|
35980 | if (res.length === 0) {
|
35981 | if (opts.failglob === true) {
|
35982 | throw new Error('no matches found for "' + pattern + '"');
|
35983 | }
|
35984 |
|
35985 | if (opts.nonull === true || opts.nullglob === true) {
|
35986 | return [pattern.split('\\').join('')];
|
35987 | }
|
35988 | }
|
35989 | return res;
|
35990 | };
|
35991 |
|
35992 | /**
|
35993 | * Returns true if the specified `string` matches the given
|
35994 | * brackets `pattern`.
|
35995 | *
|
35996 | * ```js
|
35997 | * var brackets = require('expand-brackets');
|
35998 | *
|
35999 | * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]'));
|
36000 | * //=> true
|
36001 | * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]'));
|
36002 | * //=> false
|
36003 | * ```
|
36004 | * @param {String} `string` String to match
|
36005 | * @param {String} `pattern` Poxis pattern
|
36006 | * @param {String} `options`
|
36007 | * @return {Boolean}
|
36008 | * @api public
|
36009 | */
|
36010 |
|
36011 | brackets.isMatch = function(str, pattern, options) {
|
36012 | return brackets.matcher(pattern, options)(str);
|
36013 | };
|
36014 |
|
36015 | /**
|
36016 | * Takes a POSIX character class pattern and returns a matcher function. The returned
|
36017 | * function takes the string to match as its only argument.
|
36018 | *
|
36019 | * ```js
|
36020 | * var brackets = require('expand-brackets');
|
36021 | * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]');
|
36022 | *
|
36023 | * console.log(isMatch('a.a'));
|
36024 | * //=> false
|
36025 | * console.log(isMatch('a.A'));
|
36026 | * //=> true
|
36027 | * ```
|
36028 | * @param {String} `pattern` Poxis pattern
|
36029 | * @param {String} `options`
|
36030 | * @return {Boolean}
|
36031 | * @api public
|
36032 | */
|
36033 |
|
36034 | brackets.matcher = function(pattern, options) {
|
36035 | var re = brackets.makeRe(pattern, options);
|
36036 | return function(str) {
|
36037 | return re.test(str);
|
36038 | };
|
36039 | };
|
36040 |
|
36041 | /**
|
36042 | * Create a regular expression from the given `pattern`.
|
36043 | *
|
36044 | * ```js
|
36045 | * var brackets = require('expand-brackets');
|
36046 | * var re = brackets.makeRe('[[:alpha:]]');
|
36047 | * console.log(re);
|
36048 | * //=> /^(?:[a-zA-Z])$/
|
36049 | * ```
|
36050 | * @param {String} `pattern` The pattern to convert to regex.
|
36051 | * @param {Object} `options`
|
36052 | * @return {RegExp}
|
36053 | * @api public
|
36054 | */
|
36055 |
|
36056 | brackets.makeRe = function(pattern, options) {
|
36057 | var res = brackets.create(pattern, options);
|
36058 | var opts = extendShallow$7({strictErrors: false}, options);
|
36059 | return toRegex$1(res.output, opts);
|
36060 | };
|
36061 |
|
36062 | /**
|
36063 | * Parses the given POSIX character class `pattern` and returns an object
|
36064 | * with the compiled `output` and optional source `map`.
|
36065 | *
|
36066 | * ```js
|
36067 | * var brackets = require('expand-brackets');
|
36068 | * console.log(brackets('[[:alpha:]]'));
|
36069 | * // { options: { source: 'string' },
|
36070 | * // input: '[[:alpha:]]',
|
36071 | * // state: {},
|
36072 | * // compilers:
|
36073 | * // { eos: [Function],
|
36074 | * // noop: [Function],
|
36075 | * // bos: [Function],
|
36076 | * // not: [Function],
|
36077 | * // escape: [Function],
|
36078 | * // text: [Function],
|
36079 | * // posix: [Function],
|
36080 | * // bracket: [Function],
|
36081 | * // 'bracket.open': [Function],
|
36082 | * // 'bracket.inner': [Function],
|
36083 | * // 'bracket.literal': [Function],
|
36084 | * // 'bracket.close': [Function] },
|
36085 | * // output: '[a-zA-Z]',
|
36086 | * // ast:
|
36087 | * // { type: 'root',
|
36088 | * // errors: [],
|
36089 | * // nodes: [ [Object], [Object], [Object] ] },
|
36090 | * // parsingErrors: [] }
|
36091 | * ```
|
36092 | * @param {String} `pattern`
|
36093 | * @param {Object} `options`
|
36094 | * @return {Object}
|
36095 | * @api public
|
36096 | */
|
36097 |
|
36098 | brackets.create = function(pattern, options) {
|
36099 | var snapdragon$1 = (options && options.snapdragon) || new snapdragon(options);
|
36100 | compilers$2(snapdragon$1);
|
36101 | parsers_1(snapdragon$1);
|
36102 |
|
36103 | var ast = snapdragon$1.parse(pattern, options);
|
36104 | ast.input = pattern;
|
36105 | var res = snapdragon$1.compile(ast, options);
|
36106 | res.input = pattern;
|
36107 | return res;
|
36108 | };
|
36109 |
|
36110 | /**
|
36111 | * Expose `brackets` constructor, parsers and compilers
|
36112 | */
|
36113 |
|
36114 | brackets.compilers = compilers$2;
|
36115 | brackets.parsers = parsers_1;
|
36116 |
|
36117 | /**
|
36118 | * Expose `brackets`
|
36119 | * @type {Function}
|
36120 | */
|
36121 |
|
36122 | var expandBrackets = brackets;
|
36123 |
|
36124 | /**
|
36125 | * Extglob compilers
|
36126 | */
|
36127 |
|
36128 | var compilers$3 = function(extglob) {
|
36129 | function star() {
|
36130 | if (typeof extglob.options.star === 'function') {
|
36131 | return extglob.options.star.apply(this, arguments);
|
36132 | }
|
36133 | if (typeof extglob.options.star === 'string') {
|
36134 | return extglob.options.star;
|
36135 | }
|
36136 | return '.*?';
|
36137 | }
|
36138 |
|
36139 | /**
|
36140 | * Use `expand-brackets` compilers
|
36141 | */
|
36142 |
|
36143 | extglob.use(expandBrackets.compilers);
|
36144 | extglob.compiler
|
36145 |
|
36146 | /**
|
36147 | * Escaped: "\\*"
|
36148 | */
|
36149 |
|
36150 | .set('escape', function(node) {
|
36151 | return this.emit(node.val, node);
|
36152 | })
|
36153 |
|
36154 | /**
|
36155 | * Dot: "."
|
36156 | */
|
36157 |
|
36158 | .set('dot', function(node) {
|
36159 | return this.emit('\\' + node.val, node);
|
36160 | })
|
36161 |
|
36162 | /**
|
36163 | * Question mark: "?"
|
36164 | */
|
36165 |
|
36166 | .set('qmark', function(node) {
|
36167 | var val = '[^\\\\/.]';
|
36168 | var prev = this.prev();
|
36169 |
|
36170 | if (node.parsed.slice(-1) === '(') {
|
36171 | var ch = node.rest.charAt(0);
|
36172 | if (ch !== '!' && ch !== '=' && ch !== ':') {
|
36173 | return this.emit(val, node);
|
36174 | }
|
36175 | return this.emit(node.val, node);
|
36176 | }
|
36177 |
|
36178 | if (prev.type === 'text' && prev.val) {
|
36179 | return this.emit(val, node);
|
36180 | }
|
36181 |
|
36182 | if (node.val.length > 1) {
|
36183 | val += '{' + node.val.length + '}';
|
36184 | }
|
36185 | return this.emit(val, node);
|
36186 | })
|
36187 |
|
36188 | /**
|
36189 | * Plus: "+"
|
36190 | */
|
36191 |
|
36192 | .set('plus', function(node) {
|
36193 | var prev = node.parsed.slice(-1);
|
36194 | if (prev === ']' || prev === ')') {
|
36195 | return this.emit(node.val, node);
|
36196 | }
|
36197 | var ch = this.output.slice(-1);
|
36198 | if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
|
36199 | return this.emit('\\+', node);
|
36200 | }
|
36201 | if (/\w/.test(ch) && !node.inside) {
|
36202 | return this.emit('+\\+?', node);
|
36203 | }
|
36204 | return this.emit('+', node);
|
36205 | })
|
36206 |
|
36207 | /**
|
36208 | * Star: "*"
|
36209 | */
|
36210 |
|
36211 | .set('star', function(node) {
|
36212 | var prev = this.prev();
|
36213 | var prefix = prev.type !== 'text' && prev.type !== 'escape'
|
36214 | ? '(?!\\.)'
|
36215 | : '';
|
36216 |
|
36217 | return this.emit(prefix + star.call(this, node), node);
|
36218 | })
|
36219 |
|
36220 | /**
|
36221 | * Parens
|
36222 | */
|
36223 |
|
36224 | .set('paren', function(node) {
|
36225 | return this.mapVisit(node.nodes);
|
36226 | })
|
36227 | .set('paren.open', function(node) {
|
36228 | var capture = this.options.capture ? '(' : '';
|
36229 |
|
36230 | switch (node.parent.prefix) {
|
36231 | case '!':
|
36232 | case '^':
|
36233 | return this.emit(capture + '(?:(?!(?:', node);
|
36234 | case '*':
|
36235 | case '+':
|
36236 | case '?':
|
36237 | case '@':
|
36238 | return this.emit(capture + '(?:', node);
|
36239 | default: {
|
36240 | var val = node.val;
|
36241 | if (this.options.bash === true) {
|
36242 | val = '\\' + val;
|
36243 | } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') {
|
36244 | val += '?:';
|
36245 | }
|
36246 |
|
36247 | return this.emit(val, node);
|
36248 | }
|
36249 | }
|
36250 | })
|
36251 | .set('paren.close', function(node) {
|
36252 | var capture = this.options.capture ? ')' : '';
|
36253 |
|
36254 | switch (node.prefix) {
|
36255 | case '!':
|
36256 | case '^':
|
36257 | var prefix = /^(\)|$)/.test(node.rest) ? '$' : '';
|
36258 | var str = star.call(this, node);
|
36259 |
|
36260 | // if the extglob has a slash explicitly defined, we know the user wants
|
36261 | // to match slashes, so we need to ensure the "star" regex allows for it
|
36262 | if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) {
|
36263 | str = '.*?';
|
36264 | }
|
36265 |
|
36266 | return this.emit(prefix + ('))' + str + ')') + capture, node);
|
36267 | case '*':
|
36268 | case '+':
|
36269 | case '?':
|
36270 | return this.emit(')' + node.prefix + capture, node);
|
36271 | case '@':
|
36272 | return this.emit(')' + capture, node);
|
36273 | default: {
|
36274 | var val = (this.options.bash === true ? '\\' : '') + ')';
|
36275 | return this.emit(val, node);
|
36276 | }
|
36277 | }
|
36278 | })
|
36279 |
|
36280 | /**
|
36281 | * Text
|
36282 | */
|
36283 |
|
36284 | .set('text', function(node) {
|
36285 | var val = node.val.replace(/[\[\]]/g, '\\$&');
|
36286 | return this.emit(val, node);
|
36287 | });
|
36288 | };
|
36289 |
|
36290 | // accessor descriptor properties
|
36291 | var accessor$4 = {
|
36292 | get: 'function',
|
36293 | set: 'function',
|
36294 | configurable: 'boolean',
|
36295 | enumerable: 'boolean'
|
36296 | };
|
36297 |
|
36298 | function isAccessorDescriptor$4(obj, prop) {
|
36299 | if (typeof prop === 'string') {
|
36300 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
36301 | return typeof val !== 'undefined';
|
36302 | }
|
36303 |
|
36304 | if (kindOf(obj) !== 'object') {
|
36305 | return false;
|
36306 | }
|
36307 |
|
36308 | if (has$7(obj, 'value') || has$7(obj, 'writable')) {
|
36309 | return false;
|
36310 | }
|
36311 |
|
36312 | if (!has$7(obj, 'get') || typeof obj.get !== 'function') {
|
36313 | return false;
|
36314 | }
|
36315 |
|
36316 | // tldr: it's valid to have "set" be undefined
|
36317 | // "set" might be undefined if `Object.getOwnPropertyDescriptor`
|
36318 | // was used to get the value, and only `get` was defined by the user
|
36319 | if (has$7(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
|
36320 | return false;
|
36321 | }
|
36322 |
|
36323 | for (var key in obj) {
|
36324 | if (!accessor$4.hasOwnProperty(key)) {
|
36325 | continue;
|
36326 | }
|
36327 |
|
36328 | if (kindOf(obj[key]) === accessor$4[key]) {
|
36329 | continue;
|
36330 | }
|
36331 |
|
36332 | if (typeof obj[key] !== 'undefined') {
|
36333 | return false;
|
36334 | }
|
36335 | }
|
36336 | return true;
|
36337 | }
|
36338 |
|
36339 | function has$7(obj, key) {
|
36340 | return {}.hasOwnProperty.call(obj, key);
|
36341 | }
|
36342 |
|
36343 | /**
|
36344 | * Expose `isAccessorDescriptor`
|
36345 | */
|
36346 |
|
36347 | var isAccessorDescriptor_1$4 = isAccessorDescriptor$4;
|
36348 |
|
36349 | var isDataDescriptor$4 = function isDataDescriptor(obj, prop) {
|
36350 | // data descriptor properties
|
36351 | var data = {
|
36352 | configurable: 'boolean',
|
36353 | enumerable: 'boolean',
|
36354 | writable: 'boolean'
|
36355 | };
|
36356 |
|
36357 | if (kindOf(obj) !== 'object') {
|
36358 | return false;
|
36359 | }
|
36360 |
|
36361 | if (typeof prop === 'string') {
|
36362 | var val = Object.getOwnPropertyDescriptor(obj, prop);
|
36363 | return typeof val !== 'undefined';
|
36364 | }
|
36365 |
|
36366 | if (!('value' in obj) && !('writable' in obj)) {
|
36367 | return false;
|
36368 | }
|
36369 |
|
36370 | for (var key in obj) {
|
36371 | if (key === 'value') continue;
|
36372 |
|
36373 | if (!data.hasOwnProperty(key)) {
|
36374 | continue;
|
36375 | }
|
36376 |
|
36377 | if (kindOf(obj[key]) === data[key]) {
|
36378 | continue;
|
36379 | }
|
36380 |
|
36381 | if (typeof obj[key] !== 'undefined') {
|
36382 | return false;
|
36383 | }
|
36384 | }
|
36385 | return true;
|
36386 | };
|
36387 |
|
36388 | var isDescriptor$4 = function isDescriptor(obj, key) {
|
36389 | if (kindOf(obj) !== 'object') {
|
36390 | return false;
|
36391 | }
|
36392 | if ('get' in obj) {
|
36393 | return isAccessorDescriptor_1$4(obj, key);
|
36394 | }
|
36395 | return isDataDescriptor$4(obj, key);
|
36396 | };
|
36397 |
|
36398 | var defineProperty$8 = function defineProperty(obj, prop, val) {
|
36399 | if (typeof obj !== 'object' && typeof obj !== 'function') {
|
36400 | throw new TypeError('expected an object or function.');
|
36401 | }
|
36402 |
|
36403 | if (typeof prop !== 'string') {
|
36404 | throw new TypeError('expected `prop` to be a string.');
|
36405 | }
|
36406 |
|
36407 | if (isDescriptor$4(val) && ('set' in val || 'get' in val)) {
|
36408 | return Object.defineProperty(obj, prop, val);
|
36409 | }
|
36410 |
|
36411 | return Object.defineProperty(obj, prop, {
|
36412 | configurable: true,
|
36413 | enumerable: false,
|
36414 | writable: true,
|
36415 | value: val
|
36416 | });
|
36417 | };
|
36418 |
|
36419 | var utils_1$2 = createCommonjsModule(function (module) {
|
36420 |
|
36421 |
|
36422 |
|
36423 |
|
36424 | /**
|
36425 | * Utils
|
36426 | */
|
36427 |
|
36428 | var utils = module.exports;
|
36429 | var cache = utils.cache = new fragmentCache();
|
36430 |
|
36431 | /**
|
36432 | * Cast `val` to an array
|
36433 | * @return {Array}
|
36434 | */
|
36435 |
|
36436 | utils.arrayify = function(val) {
|
36437 | if (!Array.isArray(val)) {
|
36438 | return [val];
|
36439 | }
|
36440 | return val;
|
36441 | };
|
36442 |
|
36443 | /**
|
36444 | * Memoize a generated regex or function
|
36445 | */
|
36446 |
|
36447 | utils.memoize = function(type, pattern, options, fn) {
|
36448 | var key = utils.createKey(type + pattern, options);
|
36449 |
|
36450 | if (cache.has(type, key)) {
|
36451 | return cache.get(type, key);
|
36452 | }
|
36453 |
|
36454 | var val = fn(pattern, options);
|
36455 | if (options && options.cache === false) {
|
36456 | return val;
|
36457 | }
|
36458 |
|
36459 | cache.set(type, key, val);
|
36460 | return val;
|
36461 | };
|
36462 |
|
36463 | /**
|
36464 | * Create the key to use for memoization. The key is generated
|
36465 | * by iterating over the options and concatenating key-value pairs
|
36466 | * to the pattern string.
|
36467 | */
|
36468 |
|
36469 | utils.createKey = function(pattern, options) {
|
36470 | var key = pattern;
|
36471 | if (typeof options === 'undefined') {
|
36472 | return key;
|
36473 | }
|
36474 | for (var prop in options) {
|
36475 | key += ';' + prop + '=' + String(options[prop]);
|
36476 | }
|
36477 | return key;
|
36478 | };
|
36479 |
|
36480 | /**
|
36481 | * Create the regex to use for matching text
|
36482 | */
|
36483 |
|
36484 | utils.createRegex = function(str) {
|
36485 | var opts = {contains: true, strictClose: false};
|
36486 | return regexNot(str, opts);
|
36487 | };
|
36488 | });
|
36489 |
|
36490 | /**
|
36491 | * Characters to use in text regex (we want to "not" match
|
36492 | * characters that are matched by other parsers)
|
36493 | */
|
36494 |
|
36495 | var TEXT_REGEX$1 = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+';
|
36496 | var not$3 = utils_1$2.createRegex(TEXT_REGEX$1);
|
36497 |
|
36498 | /**
|
36499 | * Extglob parsers
|
36500 | */
|
36501 |
|
36502 | function parsers$3(extglob) {
|
36503 | extglob.state = extglob.state || {};
|
36504 |
|
36505 | /**
|
36506 | * Use `expand-brackets` parsers
|
36507 | */
|
36508 |
|
36509 | extglob.use(expandBrackets.parsers);
|
36510 | extglob.parser.sets.paren = extglob.parser.sets.paren || [];
|
36511 | extglob.parser
|
36512 |
|
36513 | /**
|
36514 | * Extglob open: "*("
|
36515 | */
|
36516 |
|
36517 | .capture('paren.open', function() {
|
36518 | var parsed = this.parsed;
|
36519 | var pos = this.position();
|
36520 | var m = this.match(/^([!@*?+])?\(/);
|
36521 | if (!m) return;
|
36522 |
|
36523 | var prev = this.prev();
|
36524 | var prefix = m[1];
|
36525 | var val = m[0];
|
36526 |
|
36527 | var open = pos({
|
36528 | type: 'paren.open',
|
36529 | parsed: parsed,
|
36530 | val: val
|
36531 | });
|
36532 |
|
36533 | var node = pos({
|
36534 | type: 'paren',
|
36535 | prefix: prefix,
|
36536 | nodes: [open]
|
36537 | });
|
36538 |
|
36539 | // if nested negation extglobs, just cancel them out to simplify
|
36540 | if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') {
|
36541 | prev.prefix = '@';
|
36542 | node.prefix = '@';
|
36543 | }
|
36544 |
|
36545 | defineProperty$8(node, 'rest', this.input);
|
36546 | defineProperty$8(node, 'parsed', parsed);
|
36547 | defineProperty$8(node, 'parent', prev);
|
36548 | defineProperty$8(open, 'parent', node);
|
36549 |
|
36550 | this.push('paren', node);
|
36551 | prev.nodes.push(node);
|
36552 | })
|
36553 |
|
36554 | /**
|
36555 | * Extglob close: ")"
|
36556 | */
|
36557 |
|
36558 | .capture('paren.close', function() {
|
36559 | var parsed = this.parsed;
|
36560 | var pos = this.position();
|
36561 | var m = this.match(/^\)/);
|
36562 | if (!m) return;
|
36563 |
|
36564 | var parent = this.pop('paren');
|
36565 | var node = pos({
|
36566 | type: 'paren.close',
|
36567 | rest: this.input,
|
36568 | parsed: parsed,
|
36569 | val: m[0]
|
36570 | });
|
36571 |
|
36572 | if (!this.isType(parent, 'paren')) {
|
36573 | if (this.options.strict) {
|
36574 | throw new Error('missing opening paren: "("');
|
36575 | }
|
36576 | node.escaped = true;
|
36577 | return node;
|
36578 | }
|
36579 |
|
36580 | node.prefix = parent.prefix;
|
36581 | parent.nodes.push(node);
|
36582 | defineProperty$8(node, 'parent', parent);
|
36583 | })
|
36584 |
|
36585 | /**
|
36586 | * Escape: "\\."
|
36587 | */
|
36588 |
|
36589 | .capture('escape', function() {
|
36590 | var pos = this.position();
|
36591 | var m = this.match(/^\\(.)/);
|
36592 | if (!m) return;
|
36593 |
|
36594 | return pos({
|
36595 | type: 'escape',
|
36596 | val: m[0],
|
36597 | ch: m[1]
|
36598 | });
|
36599 | })
|
36600 |
|
36601 | /**
|
36602 | * Question marks: "?"
|
36603 | */
|
36604 |
|
36605 | .capture('qmark', function() {
|
36606 | var parsed = this.parsed;
|
36607 | var pos = this.position();
|
36608 | var m = this.match(/^\?+(?!\()/);
|
36609 | if (!m) return;
|
36610 | extglob.state.metachar = true;
|
36611 | return pos({
|
36612 | type: 'qmark',
|
36613 | rest: this.input,
|
36614 | parsed: parsed,
|
36615 | val: m[0]
|
36616 | });
|
36617 | })
|
36618 |
|
36619 | /**
|
36620 | * Character parsers
|
36621 | */
|
36622 |
|
36623 | .capture('star', /^\*(?!\()/)
|
36624 | .capture('plus', /^\+(?!\()/)
|
36625 | .capture('dot', /^\./)
|
36626 | .capture('text', not$3);
|
36627 | }
|
36628 | /**
|
36629 | * Expose text regex string
|
36630 | */
|
36631 |
|
36632 | var TEXT_REGEX_1$1 = TEXT_REGEX$1;
|
36633 |
|
36634 | /**
|
36635 | * Extglob parsers
|
36636 | */
|
36637 |
|
36638 | var parsers_1$1 = parsers$3;
|
36639 | parsers_1$1.TEXT_REGEX = TEXT_REGEX_1$1;
|
36640 |
|
36641 | /**
|
36642 | * Module dependencies
|
36643 | */
|
36644 |
|
36645 |
|
36646 |
|
36647 |
|
36648 |
|
36649 | /**
|
36650 | * Local dependencies
|
36651 | */
|
36652 |
|
36653 |
|
36654 |
|
36655 |
|
36656 | /**
|
36657 | * Customize Snapdragon parser and renderer
|
36658 | */
|
36659 |
|
36660 | function Extglob(options) {
|
36661 | this.options = extendShallow$6({source: 'extglob'}, options);
|
36662 | this.snapdragon = this.options.snapdragon || new snapdragon(this.options);
|
36663 | this.snapdragon.patterns = this.snapdragon.patterns || {};
|
36664 | this.compiler = this.snapdragon.compiler;
|
36665 | this.parser = this.snapdragon.parser;
|
36666 |
|
36667 | compilers$3(this.snapdragon);
|
36668 | parsers_1$1(this.snapdragon);
|
36669 |
|
36670 | /**
|
36671 | * Override Snapdragon `.parse` method
|
36672 | */
|
36673 |
|
36674 | defineProperty$8(this.snapdragon, 'parse', function(str, options) {
|
36675 | var parsed = snapdragon.prototype.parse.apply(this, arguments);
|
36676 | parsed.input = str;
|
36677 |
|
36678 | // escape unmatched brace/bracket/parens
|
36679 | var last = this.parser.stack.pop();
|
36680 | if (last && this.options.strict !== true) {
|
36681 | var node = last.nodes[0];
|
36682 | node.val = '\\' + node.val;
|
36683 | var sibling = node.parent.nodes[1];
|
36684 | if (sibling.type === 'star') {
|
36685 | sibling.loose = true;
|
36686 | }
|
36687 | }
|
36688 |
|
36689 | // add non-enumerable parser reference
|
36690 | defineProperty$8(parsed, 'parser', this.parser);
|
36691 | return parsed;
|
36692 | });
|
36693 |
|
36694 | /**
|
36695 | * Decorate `.parse` method
|
36696 | */
|
36697 |
|
36698 | defineProperty$8(this, 'parse', function(ast, options) {
|
36699 | return this.snapdragon.parse.apply(this.snapdragon, arguments);
|
36700 | });
|
36701 |
|
36702 | /**
|
36703 | * Decorate `.compile` method
|
36704 | */
|
36705 |
|
36706 | defineProperty$8(this, 'compile', function(ast, options) {
|
36707 | return this.snapdragon.compile.apply(this.snapdragon, arguments);
|
36708 | });
|
36709 |
|
36710 | }
|
36711 |
|
36712 | /**
|
36713 | * Expose `Extglob`
|
36714 | */
|
36715 |
|
36716 | var extglob = Extglob;
|
36717 |
|
36718 | /**
|
36719 | * Module dependencies
|
36720 | */
|
36721 |
|
36722 |
|
36723 |
|
36724 |
|
36725 |
|
36726 | /**
|
36727 | * Local dependencies
|
36728 | */
|
36729 |
|
36730 |
|
36731 |
|
36732 |
|
36733 |
|
36734 | var MAX_LENGTH$3 = 1024 * 64;
|
36735 |
|
36736 | /**
|
36737 | * Convert the given `extglob` pattern into a regex-compatible string. Returns
|
36738 | * an object with the compiled result and the parsed AST.
|
36739 | *
|
36740 | * ```js
|
36741 | * var extglob = require('extglob');
|
36742 | * console.log(extglob('*.!(*a)'));
|
36743 | * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
|
36744 | * ```
|
36745 | * @param {String} `pattern`
|
36746 | * @param {Object} `options`
|
36747 | * @return {String}
|
36748 | * @api public
|
36749 | */
|
36750 |
|
36751 | function extglob$1(pattern, options) {
|
36752 | return extglob$1.create(pattern, options).output;
|
36753 | }
|
36754 |
|
36755 | /**
|
36756 | * Takes an array of strings and an extglob pattern and returns a new
|
36757 | * array that contains only the strings that match the pattern.
|
36758 | *
|
36759 | * ```js
|
36760 | * var extglob = require('extglob');
|
36761 | * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)'));
|
36762 | * //=> ['a.b', 'a.c']
|
36763 | * ```
|
36764 | * @param {Array} `list` Array of strings to match
|
36765 | * @param {String} `pattern` Extglob pattern
|
36766 | * @param {Object} `options`
|
36767 | * @return {Array} Returns an array of matches
|
36768 | * @api public
|
36769 | */
|
36770 |
|
36771 | extglob$1.match = function(list, pattern, options) {
|
36772 | if (typeof pattern !== 'string') {
|
36773 | throw new TypeError('expected pattern to be a string');
|
36774 | }
|
36775 |
|
36776 | list = utils_1$2.arrayify(list);
|
36777 | var isMatch = extglob$1.matcher(pattern, options);
|
36778 | var len = list.length;
|
36779 | var idx = -1;
|
36780 | var matches = [];
|
36781 |
|
36782 | while (++idx < len) {
|
36783 | var ele = list[idx];
|
36784 |
|
36785 | if (isMatch(ele)) {
|
36786 | matches.push(ele);
|
36787 | }
|
36788 | }
|
36789 |
|
36790 | // if no options were passed, uniquify results and return
|
36791 | if (typeof options === 'undefined') {
|
36792 | return arrayUnique(matches);
|
36793 | }
|
36794 |
|
36795 | if (matches.length === 0) {
|
36796 | if (options.failglob === true) {
|
36797 | throw new Error('no matches found for "' + pattern + '"');
|
36798 | }
|
36799 | if (options.nonull === true || options.nullglob === true) {
|
36800 | return [pattern.split('\\').join('')];
|
36801 | }
|
36802 | }
|
36803 |
|
36804 | return options.nodupes !== false ? arrayUnique(matches) : matches;
|
36805 | };
|
36806 |
|
36807 | /**
|
36808 | * Returns true if the specified `string` matches the given
|
36809 | * extglob `pattern`.
|
36810 | *
|
36811 | * ```js
|
36812 | * var extglob = require('extglob');
|
36813 | *
|
36814 | * console.log(extglob.isMatch('a.a', '*.!(*a)'));
|
36815 | * //=> false
|
36816 | * console.log(extglob.isMatch('a.b', '*.!(*a)'));
|
36817 | * //=> true
|
36818 | * ```
|
36819 | * @param {String} `string` String to match
|
36820 | * @param {String} `pattern` Extglob pattern
|
36821 | * @param {String} `options`
|
36822 | * @return {Boolean}
|
36823 | * @api public
|
36824 | */
|
36825 |
|
36826 | extglob$1.isMatch = function(str, pattern, options) {
|
36827 | if (typeof pattern !== 'string') {
|
36828 | throw new TypeError('expected pattern to be a string');
|
36829 | }
|
36830 |
|
36831 | if (typeof str !== 'string') {
|
36832 | throw new TypeError('expected a string');
|
36833 | }
|
36834 |
|
36835 | if (pattern === str) {
|
36836 | return true;
|
36837 | }
|
36838 |
|
36839 | if (pattern === '' || pattern === ' ' || pattern === '.') {
|
36840 | return pattern === str;
|
36841 | }
|
36842 |
|
36843 | var isMatch = utils_1$2.memoize('isMatch', pattern, options, extglob$1.matcher);
|
36844 | return isMatch(str);
|
36845 | };
|
36846 |
|
36847 | /**
|
36848 | * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but
|
36849 | * the pattern can match any part of the string.
|
36850 | *
|
36851 | * ```js
|
36852 | * var extglob = require('extglob');
|
36853 | * console.log(extglob.contains('aa/bb/cc', '*b'));
|
36854 | * //=> true
|
36855 | * console.log(extglob.contains('aa/bb/cc', '*d'));
|
36856 | * //=> false
|
36857 | * ```
|
36858 | * @param {String} `str` The string to match.
|
36859 | * @param {String} `pattern` Glob pattern to use for matching.
|
36860 | * @param {Object} `options`
|
36861 | * @return {Boolean} Returns true if the patter matches any part of `str`.
|
36862 | * @api public
|
36863 | */
|
36864 |
|
36865 | extglob$1.contains = function(str, pattern, options) {
|
36866 | if (typeof str !== 'string') {
|
36867 | throw new TypeError('expected a string');
|
36868 | }
|
36869 |
|
36870 | if (pattern === '' || pattern === ' ' || pattern === '.') {
|
36871 | return pattern === str;
|
36872 | }
|
36873 |
|
36874 | var opts = extendShallow$6({}, options, {contains: true});
|
36875 | opts.strictClose = false;
|
36876 | opts.strictOpen = false;
|
36877 | return extglob$1.isMatch(str, pattern, opts);
|
36878 | };
|
36879 |
|
36880 | /**
|
36881 | * Takes an extglob pattern and returns a matcher function. The returned
|
36882 | * function takes the string to match as its only argument.
|
36883 | *
|
36884 | * ```js
|
36885 | * var extglob = require('extglob');
|
36886 | * var isMatch = extglob.matcher('*.!(*a)');
|
36887 | *
|
36888 | * console.log(isMatch('a.a'));
|
36889 | * //=> false
|
36890 | * console.log(isMatch('a.b'));
|
36891 | * //=> true
|
36892 | * ```
|
36893 | * @param {String} `pattern` Extglob pattern
|
36894 | * @param {String} `options`
|
36895 | * @return {Boolean}
|
36896 | * @api public
|
36897 | */
|
36898 |
|
36899 | extglob$1.matcher = function(pattern, options) {
|
36900 | if (typeof pattern !== 'string') {
|
36901 | throw new TypeError('expected pattern to be a string');
|
36902 | }
|
36903 |
|
36904 | function matcher() {
|
36905 | var re = extglob$1.makeRe(pattern, options);
|
36906 | return function(str) {
|
36907 | return re.test(str);
|
36908 | };
|
36909 | }
|
36910 |
|
36911 | return utils_1$2.memoize('matcher', pattern, options, matcher);
|
36912 | };
|
36913 |
|
36914 | /**
|
36915 | * Convert the given `extglob` pattern into a regex-compatible string. Returns
|
36916 | * an object with the compiled result and the parsed AST.
|
36917 | *
|
36918 | * ```js
|
36919 | * var extglob = require('extglob');
|
36920 | * console.log(extglob.create('*.!(*a)').output);
|
36921 | * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
|
36922 | * ```
|
36923 | * @param {String} `str`
|
36924 | * @param {Object} `options`
|
36925 | * @return {String}
|
36926 | * @api public
|
36927 | */
|
36928 |
|
36929 | extglob$1.create = function(pattern, options) {
|
36930 | if (typeof pattern !== 'string') {
|
36931 | throw new TypeError('expected pattern to be a string');
|
36932 | }
|
36933 |
|
36934 | function create() {
|
36935 | var ext = new extglob(options);
|
36936 | var ast = ext.parse(pattern, options);
|
36937 | return ext.compile(ast, options);
|
36938 | }
|
36939 |
|
36940 | return utils_1$2.memoize('create', pattern, options, create);
|
36941 | };
|
36942 |
|
36943 | /**
|
36944 | * Returns an array of matches captured by `pattern` in `string`, or `null`
|
36945 | * if the pattern did not match.
|
36946 | *
|
36947 | * ```js
|
36948 | * var extglob = require('extglob');
|
36949 | * extglob.capture(pattern, string[, options]);
|
36950 | *
|
36951 | * console.log(extglob.capture('test/*.js', 'test/foo.js'));
|
36952 | * //=> ['foo']
|
36953 | * console.log(extglob.capture('test/*.js', 'foo/bar.css'));
|
36954 | * //=> null
|
36955 | * ```
|
36956 | * @param {String} `pattern` Glob pattern to use for matching.
|
36957 | * @param {String} `string` String to match
|
36958 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
36959 | * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
|
36960 | * @api public
|
36961 | */
|
36962 |
|
36963 | extglob$1.capture = function(pattern, str, options) {
|
36964 | var re = extglob$1.makeRe(pattern, extendShallow$6({capture: true}, options));
|
36965 |
|
36966 | function match() {
|
36967 | return function(string) {
|
36968 | var match = re.exec(string);
|
36969 | if (!match) {
|
36970 | return null;
|
36971 | }
|
36972 |
|
36973 | return match.slice(1);
|
36974 | };
|
36975 | }
|
36976 |
|
36977 | var capture = utils_1$2.memoize('capture', pattern, options, match);
|
36978 | return capture(str);
|
36979 | };
|
36980 |
|
36981 | /**
|
36982 | * Create a regular expression from the given `pattern` and `options`.
|
36983 | *
|
36984 | * ```js
|
36985 | * var extglob = require('extglob');
|
36986 | * var re = extglob.makeRe('*.!(*a)');
|
36987 | * console.log(re);
|
36988 | * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/
|
36989 | * ```
|
36990 | * @param {String} `pattern` The pattern to convert to regex.
|
36991 | * @param {Object} `options`
|
36992 | * @return {RegExp}
|
36993 | * @api public
|
36994 | */
|
36995 |
|
36996 | extglob$1.makeRe = function(pattern, options) {
|
36997 | if (pattern instanceof RegExp) {
|
36998 | return pattern;
|
36999 | }
|
37000 |
|
37001 | if (typeof pattern !== 'string') {
|
37002 | throw new TypeError('expected pattern to be a string');
|
37003 | }
|
37004 |
|
37005 | if (pattern.length > MAX_LENGTH$3) {
|
37006 | throw new Error('expected pattern to be less than ' + MAX_LENGTH$3 + ' characters');
|
37007 | }
|
37008 |
|
37009 | function makeRe() {
|
37010 | var opts = extendShallow$6({strictErrors: false}, options);
|
37011 | if (opts.strictErrors === true) opts.strict = true;
|
37012 | var res = extglob$1.create(pattern, opts);
|
37013 | return toRegex$1(res.output, opts);
|
37014 | }
|
37015 |
|
37016 | var regex = utils_1$2.memoize('makeRe', pattern, options, makeRe);
|
37017 | if (regex.source.length > MAX_LENGTH$3) {
|
37018 | throw new SyntaxError('potentially malicious regex detected');
|
37019 | }
|
37020 |
|
37021 | return regex;
|
37022 | };
|
37023 |
|
37024 | /**
|
37025 | * Cache
|
37026 | */
|
37027 |
|
37028 | extglob$1.cache = utils_1$2.cache;
|
37029 | extglob$1.clearCache = function() {
|
37030 | extglob$1.cache.__data__ = {};
|
37031 | };
|
37032 |
|
37033 | /**
|
37034 | * Expose `Extglob` constructor, parsers and compilers
|
37035 | */
|
37036 |
|
37037 | extglob$1.Extglob = extglob;
|
37038 | extglob$1.compilers = compilers$3;
|
37039 | extglob$1.parsers = parsers_1$1;
|
37040 |
|
37041 | /**
|
37042 | * Expose `extglob`
|
37043 | * @type {Function}
|
37044 | */
|
37045 |
|
37046 | var extglob_1 = extglob$1;
|
37047 |
|
37048 | var compilers$4 = function(snapdragon) {
|
37049 | var compilers = snapdragon.compiler.compilers;
|
37050 | var opts = snapdragon.options;
|
37051 |
|
37052 | // register nanomatch compilers
|
37053 | snapdragon.use(nanomatch_1.compilers);
|
37054 |
|
37055 | // get references to some specific nanomatch compilers before they
|
37056 | // are overridden by the extglob and/or custom compilers
|
37057 | var escape = compilers.escape;
|
37058 | var qmark = compilers.qmark;
|
37059 | var slash = compilers.slash;
|
37060 | var star = compilers.star;
|
37061 | var text = compilers.text;
|
37062 | var plus = compilers.plus;
|
37063 | var dot = compilers.dot;
|
37064 |
|
37065 | // register extglob compilers or escape exglobs if disabled
|
37066 | if (opts.extglob === false || opts.noext === true) {
|
37067 | snapdragon.compiler.use(escapeExtglobs);
|
37068 | } else {
|
37069 | snapdragon.use(extglob_1.compilers);
|
37070 | }
|
37071 |
|
37072 | snapdragon.use(function() {
|
37073 | this.options.star = this.options.star || function(/*node*/) {
|
37074 | return '[^\\\\/]*?';
|
37075 | };
|
37076 | });
|
37077 |
|
37078 | // custom micromatch compilers
|
37079 | snapdragon.compiler
|
37080 |
|
37081 | // reset referenced compiler
|
37082 | .set('dot', dot)
|
37083 | .set('escape', escape)
|
37084 | .set('plus', plus)
|
37085 | .set('slash', slash)
|
37086 | .set('qmark', qmark)
|
37087 | .set('star', star)
|
37088 | .set('text', text);
|
37089 | };
|
37090 |
|
37091 | function escapeExtglobs(compiler) {
|
37092 | compiler.set('paren', function(node) {
|
37093 | var val = '';
|
37094 | visit(node, function(tok) {
|
37095 | if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val;
|
37096 | });
|
37097 | return this.emit(val, node);
|
37098 | });
|
37099 |
|
37100 | /**
|
37101 | * Visit `node` with the given `fn`
|
37102 | */
|
37103 |
|
37104 | function visit(node, fn) {
|
37105 | return node.nodes ? mapVisit(node.nodes, fn) : fn(node);
|
37106 | }
|
37107 |
|
37108 | /**
|
37109 | * Map visit over array of `nodes`.
|
37110 | */
|
37111 |
|
37112 | function mapVisit(nodes, fn) {
|
37113 | var len = nodes.length;
|
37114 | var idx = -1;
|
37115 | while (++idx < len) {
|
37116 | visit(nodes[idx], fn);
|
37117 | }
|
37118 | }
|
37119 | }
|
37120 |
|
37121 | var not$4;
|
37122 |
|
37123 | /**
|
37124 | * Characters to use in negation regex (we want to "not" match
|
37125 | * characters that are matched by other parsers)
|
37126 | */
|
37127 |
|
37128 | var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+';
|
37129 | var createNotRegex = function(opts) {
|
37130 | return not$4 || (not$4 = textRegex(TEXT));
|
37131 | };
|
37132 |
|
37133 | /**
|
37134 | * Parsers
|
37135 | */
|
37136 |
|
37137 | var parsers$4 = function(snapdragon) {
|
37138 | var parsers = snapdragon.parser.parsers;
|
37139 |
|
37140 | // register nanomatch parsers
|
37141 | snapdragon.use(nanomatch_1.parsers);
|
37142 |
|
37143 | // get references to some specific nanomatch parsers before they
|
37144 | // are overridden by the extglob and/or parsers
|
37145 | var escape = parsers.escape;
|
37146 | var slash = parsers.slash;
|
37147 | var qmark = parsers.qmark;
|
37148 | var plus = parsers.plus;
|
37149 | var star = parsers.star;
|
37150 | var dot = parsers.dot;
|
37151 |
|
37152 | // register extglob parsers
|
37153 | snapdragon.use(extglob_1.parsers);
|
37154 |
|
37155 | // custom micromatch parsers
|
37156 | snapdragon.parser
|
37157 | .use(function() {
|
37158 | // override "notRegex" created in nanomatch parser
|
37159 | this.notRegex = /^\!+(?!\()/;
|
37160 | })
|
37161 | // reset the referenced parsers
|
37162 | .capture('escape', escape)
|
37163 | .capture('slash', slash)
|
37164 | .capture('qmark', qmark)
|
37165 | .capture('star', star)
|
37166 | .capture('plus', plus)
|
37167 | .capture('dot', dot)
|
37168 |
|
37169 | /**
|
37170 | * Override `text` parser
|
37171 | */
|
37172 |
|
37173 | .capture('text', function() {
|
37174 | if (this.isInside('bracket')) return;
|
37175 | var pos = this.position();
|
37176 | var m = this.match(createNotRegex(this.options));
|
37177 | if (!m || !m[0]) return;
|
37178 |
|
37179 | // escape regex boundary characters and simple brackets
|
37180 | var val = m[0].replace(/([[\]^$])/g, '\\$1');
|
37181 |
|
37182 | return pos({
|
37183 | type: 'text',
|
37184 | val: val
|
37185 | });
|
37186 | });
|
37187 | };
|
37188 |
|
37189 | /**
|
37190 | * Create text regex
|
37191 | */
|
37192 |
|
37193 | function textRegex(pattern) {
|
37194 | var notStr = regexNot.create(pattern, {contains: true, strictClose: false});
|
37195 | var prefix = '(?:[\\^]|\\\\|';
|
37196 | return toRegex$1(prefix + notStr + ')', {strictClose: false});
|
37197 | }
|
37198 |
|
37199 | var cache$5 = new (fragmentCache)();
|
37200 |
|
37201 | var utils_1$3 = createCommonjsModule(function (module) {
|
37202 |
|
37203 | var utils = module.exports;
|
37204 |
|
37205 |
|
37206 | /**
|
37207 | * Module dependencies
|
37208 | */
|
37209 |
|
37210 |
|
37211 | utils.define = defineProperty;
|
37212 | utils.diff = arrDiff;
|
37213 | utils.extend = extendShallow;
|
37214 | utils.pick = object_pick;
|
37215 | utils.typeOf = kindOf;
|
37216 | utils.unique = arrayUnique;
|
37217 |
|
37218 | /**
|
37219 | * Returns true if the platform is windows, or `path.sep` is `\\`.
|
37220 | * This is defined as a function to allow `path.sep` to be set in unit tests,
|
37221 | * or by the user, if there is a reason to do so.
|
37222 | * @return {Boolean}
|
37223 | */
|
37224 |
|
37225 | utils.isWindows = function() {
|
37226 | return path__default.sep === '\\' || process.platform === 'win32';
|
37227 | };
|
37228 |
|
37229 | /**
|
37230 | * Get the `Snapdragon` instance to use
|
37231 | */
|
37232 |
|
37233 | utils.instantiate = function(ast, options) {
|
37234 | var snapdragon$1;
|
37235 | // if an instance was created by `.parse`, use that instance
|
37236 | if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
|
37237 | snapdragon$1 = ast.snapdragon;
|
37238 | // if the user supplies an instance on options, use that instance
|
37239 | } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
|
37240 | snapdragon$1 = options.snapdragon;
|
37241 | // create a new instance
|
37242 | } else {
|
37243 | snapdragon$1 = new snapdragon(options);
|
37244 | }
|
37245 |
|
37246 | utils.define(snapdragon$1, 'parse', function(str, options) {
|
37247 | var parsed = snapdragon.prototype.parse.apply(this, arguments);
|
37248 | parsed.input = str;
|
37249 |
|
37250 | // escape unmatched brace/bracket/parens
|
37251 | var last = this.parser.stack.pop();
|
37252 | if (last && this.options.strictErrors !== true) {
|
37253 | var open = last.nodes[0];
|
37254 | var inner = last.nodes[1];
|
37255 | if (last.type === 'bracket') {
|
37256 | if (inner.val.charAt(0) === '[') {
|
37257 | inner.val = '\\' + inner.val;
|
37258 | }
|
37259 |
|
37260 | } else {
|
37261 | open.val = '\\' + open.val;
|
37262 | var sibling = open.parent.nodes[1];
|
37263 | if (sibling.type === 'star') {
|
37264 | sibling.loose = true;
|
37265 | }
|
37266 | }
|
37267 | }
|
37268 |
|
37269 | // add non-enumerable parser reference
|
37270 | utils.define(parsed, 'parser', this.parser);
|
37271 | return parsed;
|
37272 | });
|
37273 |
|
37274 | return snapdragon$1;
|
37275 | };
|
37276 |
|
37277 | /**
|
37278 | * Create the key to use for memoization. The key is generated
|
37279 | * by iterating over the options and concatenating key-value pairs
|
37280 | * to the pattern string.
|
37281 | */
|
37282 |
|
37283 | utils.createKey = function(pattern, options) {
|
37284 | if (utils.typeOf(options) !== 'object') {
|
37285 | return pattern;
|
37286 | }
|
37287 | var val = pattern;
|
37288 | var keys = Object.keys(options);
|
37289 | for (var i = 0; i < keys.length; i++) {
|
37290 | var key = keys[i];
|
37291 | val += ';' + key + '=' + String(options[key]);
|
37292 | }
|
37293 | return val;
|
37294 | };
|
37295 |
|
37296 | /**
|
37297 | * Cast `val` to an array
|
37298 | * @return {Array}
|
37299 | */
|
37300 |
|
37301 | utils.arrayify = function(val) {
|
37302 | if (typeof val === 'string') return [val];
|
37303 | return val ? (Array.isArray(val) ? val : [val]) : [];
|
37304 | };
|
37305 |
|
37306 | /**
|
37307 | * Return true if `val` is a non-empty string
|
37308 | */
|
37309 |
|
37310 | utils.isString = function(val) {
|
37311 | return typeof val === 'string';
|
37312 | };
|
37313 |
|
37314 | /**
|
37315 | * Return true if `val` is a non-empty string
|
37316 | */
|
37317 |
|
37318 | utils.isObject = function(val) {
|
37319 | return utils.typeOf(val) === 'object';
|
37320 | };
|
37321 |
|
37322 | /**
|
37323 | * Returns true if the given `str` has special characters
|
37324 | */
|
37325 |
|
37326 | utils.hasSpecialChars = function(str) {
|
37327 | return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str);
|
37328 | };
|
37329 |
|
37330 | /**
|
37331 | * Escape regex characters in the given string
|
37332 | */
|
37333 |
|
37334 | utils.escapeRegex = function(str) {
|
37335 | return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&');
|
37336 | };
|
37337 |
|
37338 | /**
|
37339 | * Normalize slashes in the given filepath.
|
37340 | *
|
37341 | * @param {String} `filepath`
|
37342 | * @return {String}
|
37343 | */
|
37344 |
|
37345 | utils.toPosixPath = function(str) {
|
37346 | return str.replace(/\\+/g, '/');
|
37347 | };
|
37348 |
|
37349 | /**
|
37350 | * Strip backslashes before special characters in a string.
|
37351 | *
|
37352 | * @param {String} `str`
|
37353 | * @return {String}
|
37354 | */
|
37355 |
|
37356 | utils.unescape = function(str) {
|
37357 | return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
|
37358 | };
|
37359 |
|
37360 | /**
|
37361 | * Strip the prefix from a filepath
|
37362 | * @param {String} `fp`
|
37363 | * @return {String}
|
37364 | */
|
37365 |
|
37366 | utils.stripPrefix = function(str) {
|
37367 | if (str.charAt(0) !== '.') {
|
37368 | return str;
|
37369 | }
|
37370 | var ch = str.charAt(1);
|
37371 | if (utils.isSlash(ch)) {
|
37372 | return str.slice(2);
|
37373 | }
|
37374 | return str;
|
37375 | };
|
37376 |
|
37377 | /**
|
37378 | * Returns true if the given str is an escaped or
|
37379 | * unescaped path character
|
37380 | */
|
37381 |
|
37382 | utils.isSlash = function(str) {
|
37383 | return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
|
37384 | };
|
37385 |
|
37386 | /**
|
37387 | * Returns a function that returns true if the given
|
37388 | * pattern matches or contains a `filepath`
|
37389 | *
|
37390 | * @param {String} `pattern`
|
37391 | * @return {Function}
|
37392 | */
|
37393 |
|
37394 | utils.matchPath = function(pattern, options) {
|
37395 | return (options && options.contains)
|
37396 | ? utils.containsPattern(pattern, options)
|
37397 | : utils.equalsPattern(pattern, options);
|
37398 | };
|
37399 |
|
37400 | /**
|
37401 | * Returns true if the given (original) filepath or unixified path are equal
|
37402 | * to the given pattern.
|
37403 | */
|
37404 |
|
37405 | utils._equals = function(filepath, unixPath, pattern) {
|
37406 | return pattern === filepath || pattern === unixPath;
|
37407 | };
|
37408 |
|
37409 | /**
|
37410 | * Returns true if the given (original) filepath or unixified path contain
|
37411 | * the given pattern.
|
37412 | */
|
37413 |
|
37414 | utils._contains = function(filepath, unixPath, pattern) {
|
37415 | return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
|
37416 | };
|
37417 |
|
37418 | /**
|
37419 | * Returns a function that returns true if the given
|
37420 | * pattern is the same as a given `filepath`
|
37421 | *
|
37422 | * @param {String} `pattern`
|
37423 | * @return {Function}
|
37424 | */
|
37425 |
|
37426 | utils.equalsPattern = function(pattern, options) {
|
37427 | var unixify = utils.unixify(options);
|
37428 | options = options || {};
|
37429 |
|
37430 | return function fn(filepath) {
|
37431 | var equal = utils._equals(filepath, unixify(filepath), pattern);
|
37432 | if (equal === true || options.nocase !== true) {
|
37433 | return equal;
|
37434 | }
|
37435 | var lower = filepath.toLowerCase();
|
37436 | return utils._equals(lower, unixify(lower), pattern);
|
37437 | };
|
37438 | };
|
37439 |
|
37440 | /**
|
37441 | * Returns a function that returns true if the given
|
37442 | * pattern contains a `filepath`
|
37443 | *
|
37444 | * @param {String} `pattern`
|
37445 | * @return {Function}
|
37446 | */
|
37447 |
|
37448 | utils.containsPattern = function(pattern, options) {
|
37449 | var unixify = utils.unixify(options);
|
37450 | options = options || {};
|
37451 |
|
37452 | return function(filepath) {
|
37453 | var contains = utils._contains(filepath, unixify(filepath), pattern);
|
37454 | if (contains === true || options.nocase !== true) {
|
37455 | return contains;
|
37456 | }
|
37457 | var lower = filepath.toLowerCase();
|
37458 | return utils._contains(lower, unixify(lower), pattern);
|
37459 | };
|
37460 | };
|
37461 |
|
37462 | /**
|
37463 | * Returns a function that returns true if the given
|
37464 | * regex matches the `filename` of a file path.
|
37465 | *
|
37466 | * @param {RegExp} `re` Matching regex
|
37467 | * @return {Function}
|
37468 | */
|
37469 |
|
37470 | utils.matchBasename = function(re) {
|
37471 | return function(filepath) {
|
37472 | return re.test(path__default.basename(filepath));
|
37473 | };
|
37474 | };
|
37475 |
|
37476 | /**
|
37477 | * Determines the filepath to return based on the provided options.
|
37478 | * @return {any}
|
37479 | */
|
37480 |
|
37481 | utils.value = function(str, unixify, options) {
|
37482 | if (options && options.unixify === false) {
|
37483 | return str;
|
37484 | }
|
37485 | return unixify(str);
|
37486 | };
|
37487 |
|
37488 | /**
|
37489 | * Returns a function that normalizes slashes in a string to forward
|
37490 | * slashes, strips `./` from beginning of paths, and optionally unescapes
|
37491 | * special characters.
|
37492 | * @return {Function}
|
37493 | */
|
37494 |
|
37495 | utils.unixify = function(options) {
|
37496 | options = options || {};
|
37497 | return function(filepath) {
|
37498 | if (utils.isWindows() || options.unixify === true) {
|
37499 | filepath = utils.toPosixPath(filepath);
|
37500 | }
|
37501 | if (options.stripPrefix !== false) {
|
37502 | filepath = utils.stripPrefix(filepath);
|
37503 | }
|
37504 | if (options.unescape === true) {
|
37505 | filepath = utils.unescape(filepath);
|
37506 | }
|
37507 | return filepath;
|
37508 | };
|
37509 | };
|
37510 | });
|
37511 |
|
37512 | /**
|
37513 | * Module dependencies
|
37514 | */
|
37515 |
|
37516 |
|
37517 |
|
37518 |
|
37519 |
|
37520 |
|
37521 | /**
|
37522 | * Local dependencies
|
37523 | */
|
37524 |
|
37525 |
|
37526 |
|
37527 |
|
37528 |
|
37529 | var MAX_LENGTH$4 = 1024 * 64;
|
37530 |
|
37531 | /**
|
37532 | * The main function takes a list of strings and one or more
|
37533 | * glob patterns to use for matching.
|
37534 | *
|
37535 | * ```js
|
37536 | * var mm = require('micromatch');
|
37537 | * mm(list, patterns[, options]);
|
37538 | *
|
37539 | * console.log(mm(['a.js', 'a.txt'], ['*.js']));
|
37540 | * //=> [ 'a.js' ]
|
37541 | * ```
|
37542 | * @param {Array} `list` A list of strings to match
|
37543 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37544 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37545 | * @return {Array} Returns an array of matches
|
37546 | * @summary false
|
37547 | * @api public
|
37548 | */
|
37549 |
|
37550 | function micromatch(list, patterns, options) {
|
37551 | patterns = utils_1$3.arrayify(patterns);
|
37552 | list = utils_1$3.arrayify(list);
|
37553 |
|
37554 | var len = patterns.length;
|
37555 | if (list.length === 0 || len === 0) {
|
37556 | return [];
|
37557 | }
|
37558 |
|
37559 | if (len === 1) {
|
37560 | return micromatch.match(list, patterns[0], options);
|
37561 | }
|
37562 |
|
37563 | var omit = [];
|
37564 | var keep = [];
|
37565 | var idx = -1;
|
37566 |
|
37567 | while (++idx < len) {
|
37568 | var pattern = patterns[idx];
|
37569 |
|
37570 | if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
|
37571 | omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options));
|
37572 | } else {
|
37573 | keep.push.apply(keep, micromatch.match(list, pattern, options));
|
37574 | }
|
37575 | }
|
37576 |
|
37577 | var matches = utils_1$3.diff(keep, omit);
|
37578 | if (!options || options.nodupes !== false) {
|
37579 | return utils_1$3.unique(matches);
|
37580 | }
|
37581 |
|
37582 | return matches;
|
37583 | }
|
37584 |
|
37585 | /**
|
37586 | * Similar to the main function, but `pattern` must be a string.
|
37587 | *
|
37588 | * ```js
|
37589 | * var mm = require('micromatch');
|
37590 | * mm.match(list, pattern[, options]);
|
37591 | *
|
37592 | * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
|
37593 | * //=> ['a.a', 'a.aa']
|
37594 | * ```
|
37595 | * @param {Array} `list` Array of strings to match
|
37596 | * @param {String} `pattern` Glob pattern to use for matching.
|
37597 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37598 | * @return {Array} Returns an array of matches
|
37599 | * @api public
|
37600 | */
|
37601 |
|
37602 | micromatch.match = function(list, pattern, options) {
|
37603 | if (Array.isArray(pattern)) {
|
37604 | throw new TypeError('expected pattern to be a string');
|
37605 | }
|
37606 |
|
37607 | var unixify = utils_1$3.unixify(options);
|
37608 | var isMatch = memoize$3('match', pattern, options, micromatch.matcher);
|
37609 | var matches = [];
|
37610 |
|
37611 | list = utils_1$3.arrayify(list);
|
37612 | var len = list.length;
|
37613 | var idx = -1;
|
37614 |
|
37615 | while (++idx < len) {
|
37616 | var ele = list[idx];
|
37617 | if (ele === pattern || isMatch(ele)) {
|
37618 | matches.push(utils_1$3.value(ele, unixify, options));
|
37619 | }
|
37620 | }
|
37621 |
|
37622 | // if no options were passed, uniquify results and return
|
37623 | if (typeof options === 'undefined') {
|
37624 | return utils_1$3.unique(matches);
|
37625 | }
|
37626 |
|
37627 | if (matches.length === 0) {
|
37628 | if (options.failglob === true) {
|
37629 | throw new Error('no matches found for "' + pattern + '"');
|
37630 | }
|
37631 | if (options.nonull === true || options.nullglob === true) {
|
37632 | return [options.unescape ? utils_1$3.unescape(pattern) : pattern];
|
37633 | }
|
37634 | }
|
37635 |
|
37636 | // if `opts.ignore` was defined, diff ignored list
|
37637 | if (options.ignore) {
|
37638 | matches = micromatch.not(matches, options.ignore, options);
|
37639 | }
|
37640 |
|
37641 | return options.nodupes !== false ? utils_1$3.unique(matches) : matches;
|
37642 | };
|
37643 |
|
37644 | /**
|
37645 | * Returns true if the specified `string` matches the given glob `pattern`.
|
37646 | *
|
37647 | * ```js
|
37648 | * var mm = require('micromatch');
|
37649 | * mm.isMatch(string, pattern[, options]);
|
37650 | *
|
37651 | * console.log(mm.isMatch('a.a', '*.a'));
|
37652 | * //=> true
|
37653 | * console.log(mm.isMatch('a.b', '*.a'));
|
37654 | * //=> false
|
37655 | * ```
|
37656 | * @param {String} `string` String to match
|
37657 | * @param {String} `pattern` Glob pattern to use for matching.
|
37658 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37659 | * @return {Boolean} Returns true if the string matches the glob pattern.
|
37660 | * @api public
|
37661 | */
|
37662 |
|
37663 | micromatch.isMatch = function(str, pattern, options) {
|
37664 | if (typeof str !== 'string') {
|
37665 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
37666 | }
|
37667 |
|
37668 | if (isEmptyString(str) || isEmptyString(pattern)) {
|
37669 | return false;
|
37670 | }
|
37671 |
|
37672 | var equals = utils_1$3.equalsPattern(options);
|
37673 | if (equals(str)) {
|
37674 | return true;
|
37675 | }
|
37676 |
|
37677 | var isMatch = memoize$3('isMatch', pattern, options, micromatch.matcher);
|
37678 | return isMatch(str);
|
37679 | };
|
37680 |
|
37681 | /**
|
37682 | * Returns true if some of the strings in the given `list` match any of the
|
37683 | * given glob `patterns`.
|
37684 | *
|
37685 | * ```js
|
37686 | * var mm = require('micromatch');
|
37687 | * mm.some(list, patterns[, options]);
|
37688 | *
|
37689 | * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
|
37690 | * // true
|
37691 | * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
|
37692 | * // false
|
37693 | * ```
|
37694 | * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
|
37695 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37696 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37697 | * @return {Boolean} Returns true if any patterns match `str`
|
37698 | * @api public
|
37699 | */
|
37700 |
|
37701 | micromatch.some = function(list, patterns, options) {
|
37702 | if (typeof list === 'string') {
|
37703 | list = [list];
|
37704 | }
|
37705 | for (var i = 0; i < list.length; i++) {
|
37706 | if (micromatch(list[i], patterns, options).length === 1) {
|
37707 | return true;
|
37708 | }
|
37709 | }
|
37710 | return false;
|
37711 | };
|
37712 |
|
37713 | /**
|
37714 | * Returns true if every string in the given `list` matches
|
37715 | * any of the given glob `patterns`.
|
37716 | *
|
37717 | * ```js
|
37718 | * var mm = require('micromatch');
|
37719 | * mm.every(list, patterns[, options]);
|
37720 | *
|
37721 | * console.log(mm.every('foo.js', ['foo.js']));
|
37722 | * // true
|
37723 | * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
|
37724 | * // true
|
37725 | * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
|
37726 | * // false
|
37727 | * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
|
37728 | * // false
|
37729 | * ```
|
37730 | * @param {String|Array} `list` The string or array of strings to test.
|
37731 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37732 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37733 | * @return {Boolean} Returns true if any patterns match `str`
|
37734 | * @api public
|
37735 | */
|
37736 |
|
37737 | micromatch.every = function(list, patterns, options) {
|
37738 | if (typeof list === 'string') {
|
37739 | list = [list];
|
37740 | }
|
37741 | for (var i = 0; i < list.length; i++) {
|
37742 | if (micromatch(list[i], patterns, options).length !== 1) {
|
37743 | return false;
|
37744 | }
|
37745 | }
|
37746 | return true;
|
37747 | };
|
37748 |
|
37749 | /**
|
37750 | * Returns true if **any** of the given glob `patterns`
|
37751 | * match the specified `string`.
|
37752 | *
|
37753 | * ```js
|
37754 | * var mm = require('micromatch');
|
37755 | * mm.any(string, patterns[, options]);
|
37756 | *
|
37757 | * console.log(mm.any('a.a', ['b.*', '*.a']));
|
37758 | * //=> true
|
37759 | * console.log(mm.any('a.a', 'b.*'));
|
37760 | * //=> false
|
37761 | * ```
|
37762 | * @param {String|Array} `str` The string to test.
|
37763 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37764 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37765 | * @return {Boolean} Returns true if any patterns match `str`
|
37766 | * @api public
|
37767 | */
|
37768 |
|
37769 | micromatch.any = function(str, patterns, options) {
|
37770 | if (typeof str !== 'string') {
|
37771 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
37772 | }
|
37773 |
|
37774 | if (isEmptyString(str) || isEmptyString(patterns)) {
|
37775 | return false;
|
37776 | }
|
37777 |
|
37778 | if (typeof patterns === 'string') {
|
37779 | patterns = [patterns];
|
37780 | }
|
37781 |
|
37782 | for (var i = 0; i < patterns.length; i++) {
|
37783 | if (micromatch.isMatch(str, patterns[i], options)) {
|
37784 | return true;
|
37785 | }
|
37786 | }
|
37787 | return false;
|
37788 | };
|
37789 |
|
37790 | /**
|
37791 | * Returns true if **all** of the given `patterns` match
|
37792 | * the specified string.
|
37793 | *
|
37794 | * ```js
|
37795 | * var mm = require('micromatch');
|
37796 | * mm.all(string, patterns[, options]);
|
37797 | *
|
37798 | * console.log(mm.all('foo.js', ['foo.js']));
|
37799 | * // true
|
37800 | *
|
37801 | * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
|
37802 | * // false
|
37803 | *
|
37804 | * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
|
37805 | * // true
|
37806 | *
|
37807 | * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
|
37808 | * // true
|
37809 | * ```
|
37810 | * @param {String|Array} `str` The string to test.
|
37811 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37812 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37813 | * @return {Boolean} Returns true if any patterns match `str`
|
37814 | * @api public
|
37815 | */
|
37816 |
|
37817 | micromatch.all = function(str, patterns, options) {
|
37818 | if (typeof str !== 'string') {
|
37819 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
37820 | }
|
37821 | if (typeof patterns === 'string') {
|
37822 | patterns = [patterns];
|
37823 | }
|
37824 | for (var i = 0; i < patterns.length; i++) {
|
37825 | if (!micromatch.isMatch(str, patterns[i], options)) {
|
37826 | return false;
|
37827 | }
|
37828 | }
|
37829 | return true;
|
37830 | };
|
37831 |
|
37832 | /**
|
37833 | * Returns a list of strings that _**do not match any**_ of the given `patterns`.
|
37834 | *
|
37835 | * ```js
|
37836 | * var mm = require('micromatch');
|
37837 | * mm.not(list, patterns[, options]);
|
37838 | *
|
37839 | * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
|
37840 | * //=> ['b.b', 'c.c']
|
37841 | * ```
|
37842 | * @param {Array} `list` Array of strings to match.
|
37843 | * @param {String|Array} `patterns` One or more glob pattern to use for matching.
|
37844 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37845 | * @return {Array} Returns an array of strings that **do not match** the given patterns.
|
37846 | * @api public
|
37847 | */
|
37848 |
|
37849 | micromatch.not = function(list, patterns, options) {
|
37850 | var opts = extendShallow({}, options);
|
37851 | var ignore = opts.ignore;
|
37852 | delete opts.ignore;
|
37853 |
|
37854 | var unixify = utils_1$3.unixify(opts);
|
37855 | list = utils_1$3.arrayify(list).map(unixify);
|
37856 |
|
37857 | var matches = utils_1$3.diff(list, micromatch(list, patterns, opts));
|
37858 | if (ignore) {
|
37859 | matches = utils_1$3.diff(matches, micromatch(list, ignore));
|
37860 | }
|
37861 |
|
37862 | return opts.nodupes !== false ? utils_1$3.unique(matches) : matches;
|
37863 | };
|
37864 |
|
37865 | /**
|
37866 | * Returns true if the given `string` contains the given pattern. Similar
|
37867 | * to [.isMatch](#isMatch) but the pattern can match any part of the string.
|
37868 | *
|
37869 | * ```js
|
37870 | * var mm = require('micromatch');
|
37871 | * mm.contains(string, pattern[, options]);
|
37872 | *
|
37873 | * console.log(mm.contains('aa/bb/cc', '*b'));
|
37874 | * //=> true
|
37875 | * console.log(mm.contains('aa/bb/cc', '*d'));
|
37876 | * //=> false
|
37877 | * ```
|
37878 | * @param {String} `str` The string to match.
|
37879 | * @param {String|Array} `patterns` Glob pattern to use for matching.
|
37880 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37881 | * @return {Boolean} Returns true if the patter matches any part of `str`.
|
37882 | * @api public
|
37883 | */
|
37884 |
|
37885 | micromatch.contains = function(str, patterns, options) {
|
37886 | if (typeof str !== 'string') {
|
37887 | throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
|
37888 | }
|
37889 |
|
37890 | if (typeof patterns === 'string') {
|
37891 | if (isEmptyString(str) || isEmptyString(patterns)) {
|
37892 | return false;
|
37893 | }
|
37894 |
|
37895 | var equals = utils_1$3.equalsPattern(patterns, options);
|
37896 | if (equals(str)) {
|
37897 | return true;
|
37898 | }
|
37899 | var contains = utils_1$3.containsPattern(patterns, options);
|
37900 | if (contains(str)) {
|
37901 | return true;
|
37902 | }
|
37903 | }
|
37904 |
|
37905 | var opts = extendShallow({}, options, {contains: true});
|
37906 | return micromatch.any(str, patterns, opts);
|
37907 | };
|
37908 |
|
37909 | /**
|
37910 | * Returns true if the given pattern and options should enable
|
37911 | * the `matchBase` option.
|
37912 | * @return {Boolean}
|
37913 | * @api private
|
37914 | */
|
37915 |
|
37916 | micromatch.matchBase = function(pattern, options) {
|
37917 | if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
|
37918 | return options.basename === true || options.matchBase === true;
|
37919 | };
|
37920 |
|
37921 | /**
|
37922 | * Filter the keys of the given object with the given `glob` pattern
|
37923 | * and `options`. Does not attempt to match nested keys. If you need this feature,
|
37924 | * use [glob-object][] instead.
|
37925 | *
|
37926 | * ```js
|
37927 | * var mm = require('micromatch');
|
37928 | * mm.matchKeys(object, patterns[, options]);
|
37929 | *
|
37930 | * var obj = { aa: 'a', ab: 'b', ac: 'c' };
|
37931 | * console.log(mm.matchKeys(obj, '*b'));
|
37932 | * //=> { ab: 'b' }
|
37933 | * ```
|
37934 | * @param {Object} `object` The object with keys to filter.
|
37935 | * @param {String|Array} `patterns` One or more glob patterns to use for matching.
|
37936 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
37937 | * @return {Object} Returns an object with only keys that match the given patterns.
|
37938 | * @api public
|
37939 | */
|
37940 |
|
37941 | micromatch.matchKeys = function(obj, patterns, options) {
|
37942 | if (!utils_1$3.isObject(obj)) {
|
37943 | throw new TypeError('expected the first argument to be an object');
|
37944 | }
|
37945 | var keys = micromatch(Object.keys(obj), patterns, options);
|
37946 | return utils_1$3.pick(obj, keys);
|
37947 | };
|
37948 |
|
37949 | /**
|
37950 | * Returns a memoized matcher function from the given glob `pattern` and `options`.
|
37951 | * The returned function takes a string to match as its only argument and returns
|
37952 | * true if the string is a match.
|
37953 | *
|
37954 | * ```js
|
37955 | * var mm = require('micromatch');
|
37956 | * mm.matcher(pattern[, options]);
|
37957 | *
|
37958 | * var isMatch = mm.matcher('*.!(*a)');
|
37959 | * console.log(isMatch('a.a'));
|
37960 | * //=> false
|
37961 | * console.log(isMatch('a.b'));
|
37962 | * //=> true
|
37963 | * ```
|
37964 | * @param {String} `pattern` Glob pattern
|
37965 | * @param {Object} `options` See available [options](#options) for changing how matches are performed.
|
37966 | * @return {Function} Returns a matcher function.
|
37967 | * @api public
|
37968 | */
|
37969 |
|
37970 | micromatch.matcher = function matcher(pattern, options) {
|
37971 | if (Array.isArray(pattern)) {
|
37972 | return compose$1(pattern, options, matcher);
|
37973 | }
|
37974 |
|
37975 | // if pattern is a regex
|
37976 | if (pattern instanceof RegExp) {
|
37977 | return test(pattern);
|
37978 | }
|
37979 |
|
37980 | // if pattern is invalid
|
37981 | if (!utils_1$3.isString(pattern)) {
|
37982 | throw new TypeError('expected pattern to be an array, string or regex');
|
37983 | }
|
37984 |
|
37985 | // if pattern is a non-glob string
|
37986 | if (!utils_1$3.hasSpecialChars(pattern)) {
|
37987 | if (options && options.nocase === true) {
|
37988 | pattern = pattern.toLowerCase();
|
37989 | }
|
37990 | return utils_1$3.matchPath(pattern, options);
|
37991 | }
|
37992 |
|
37993 | // if pattern is a glob string
|
37994 | var re = micromatch.makeRe(pattern, options);
|
37995 |
|
37996 | // if `options.matchBase` or `options.basename` is defined
|
37997 | if (micromatch.matchBase(pattern, options)) {
|
37998 | return utils_1$3.matchBasename(re, options);
|
37999 | }
|
38000 |
|
38001 | function test(regex) {
|
38002 | var equals = utils_1$3.equalsPattern(options);
|
38003 | var unixify = utils_1$3.unixify(options);
|
38004 |
|
38005 | return function(str) {
|
38006 | if (equals(str)) {
|
38007 | return true;
|
38008 | }
|
38009 |
|
38010 | if (regex.test(unixify(str))) {
|
38011 | return true;
|
38012 | }
|
38013 | return false;
|
38014 | };
|
38015 | }
|
38016 |
|
38017 | var fn = test(re);
|
38018 | Object.defineProperty(fn, 'result', {
|
38019 | configurable: true,
|
38020 | enumerable: false,
|
38021 | value: re.result
|
38022 | });
|
38023 | return fn;
|
38024 | };
|
38025 |
|
38026 | /**
|
38027 | * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
|
38028 | *
|
38029 | * ```js
|
38030 | * var mm = require('micromatch');
|
38031 | * mm.capture(pattern, string[, options]);
|
38032 | *
|
38033 | * console.log(mm.capture('test/*.js', 'test/foo.js'));
|
38034 | * //=> ['foo']
|
38035 | * console.log(mm.capture('test/*.js', 'foo/bar.css'));
|
38036 | * //=> null
|
38037 | * ```
|
38038 | * @param {String} `pattern` Glob pattern to use for matching.
|
38039 | * @param {String} `string` String to match
|
38040 | * @param {Object} `options` See available [options](#options) for changing how matches are performed
|
38041 | * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
|
38042 | * @api public
|
38043 | */
|
38044 |
|
38045 | micromatch.capture = function(pattern, str, options) {
|
38046 | var re = micromatch.makeRe(pattern, extendShallow({capture: true}, options));
|
38047 | var unixify = utils_1$3.unixify(options);
|
38048 |
|
38049 | function match() {
|
38050 | return function(string) {
|
38051 | var match = re.exec(unixify(string));
|
38052 | if (!match) {
|
38053 | return null;
|
38054 | }
|
38055 |
|
38056 | return match.slice(1);
|
38057 | };
|
38058 | }
|
38059 |
|
38060 | var capture = memoize$3('capture', pattern, options, match);
|
38061 | return capture(str);
|
38062 | };
|
38063 |
|
38064 | /**
|
38065 | * Create a regular expression from the given glob `pattern`.
|
38066 | *
|
38067 | * ```js
|
38068 | * var mm = require('micromatch');
|
38069 | * mm.makeRe(pattern[, options]);
|
38070 | *
|
38071 | * console.log(mm.makeRe('*.js'));
|
38072 | * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
|
38073 | * ```
|
38074 | * @param {String} `pattern` A glob pattern to convert to regex.
|
38075 | * @param {Object} `options` See available [options](#options) for changing how matches are performed.
|
38076 | * @return {RegExp} Returns a regex created from the given pattern.
|
38077 | * @api public
|
38078 | */
|
38079 |
|
38080 | micromatch.makeRe = function(pattern, options) {
|
38081 | if (typeof pattern !== 'string') {
|
38082 | throw new TypeError('expected pattern to be a string');
|
38083 | }
|
38084 |
|
38085 | if (pattern.length > MAX_LENGTH$4) {
|
38086 | throw new Error('expected pattern to be less than ' + MAX_LENGTH$4 + ' characters');
|
38087 | }
|
38088 |
|
38089 | function makeRe() {
|
38090 | var result = micromatch.create(pattern, options);
|
38091 | var ast_array = [];
|
38092 | var output = result.map(function(obj) {
|
38093 | obj.ast.state = obj.state;
|
38094 | ast_array.push(obj.ast);
|
38095 | return obj.output;
|
38096 | });
|
38097 |
|
38098 | var regex = toRegex$1(output.join('|'), options);
|
38099 | Object.defineProperty(regex, 'result', {
|
38100 | configurable: true,
|
38101 | enumerable: false,
|
38102 | value: ast_array
|
38103 | });
|
38104 | return regex;
|
38105 | }
|
38106 |
|
38107 | return memoize$3('makeRe', pattern, options, makeRe);
|
38108 | };
|
38109 |
|
38110 | /**
|
38111 | * Expand the given brace `pattern`.
|
38112 | *
|
38113 | * ```js
|
38114 | * var mm = require('micromatch');
|
38115 | * console.log(mm.braces('foo/{a,b}/bar'));
|
38116 | * //=> ['foo/(a|b)/bar']
|
38117 | *
|
38118 | * console.log(mm.braces('foo/{a,b}/bar', {expand: true}));
|
38119 | * //=> ['foo/(a|b)/bar']
|
38120 | * ```
|
38121 | * @param {String} `pattern` String with brace pattern to expand.
|
38122 | * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
|
38123 | * @return {Array}
|
38124 | * @api public
|
38125 | */
|
38126 |
|
38127 | micromatch.braces = function(pattern, options) {
|
38128 | if (typeof pattern !== 'string' && !Array.isArray(pattern)) {
|
38129 | throw new TypeError('expected pattern to be an array or string');
|
38130 | }
|
38131 |
|
38132 | function expand() {
|
38133 | if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
|
38134 | return utils_1$3.arrayify(pattern);
|
38135 | }
|
38136 | return braces_1(pattern, options);
|
38137 | }
|
38138 |
|
38139 | return memoize$3('braces', pattern, options, expand);
|
38140 | };
|
38141 |
|
38142 | /**
|
38143 | * Proxy to the [micromatch.braces](#method), for parity with
|
38144 | * minimatch.
|
38145 | */
|
38146 |
|
38147 | micromatch.braceExpand = function(pattern, options) {
|
38148 | var opts = extendShallow({}, options, {expand: true});
|
38149 | return micromatch.braces(pattern, opts);
|
38150 | };
|
38151 |
|
38152 | /**
|
38153 | * Parses the given glob `pattern` and returns an array of abstract syntax
|
38154 | * trees (ASTs), with the compiled `output` and optional source `map` on
|
38155 | * each AST.
|
38156 | *
|
38157 | * ```js
|
38158 | * var mm = require('micromatch');
|
38159 | * mm.create(pattern[, options]);
|
38160 | *
|
38161 | * console.log(mm.create('abc/*.js'));
|
38162 | * // [{ options: { source: 'string', sourcemap: true },
|
38163 | * // state: {},
|
38164 | * // compilers:
|
38165 | * // { ... },
|
38166 | * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
|
38167 | * // ast:
|
38168 | * // { type: 'root',
|
38169 | * // errors: [],
|
38170 | * // nodes:
|
38171 | * // [ ... ],
|
38172 | * // dot: false,
|
38173 | * // input: 'abc/*.js' },
|
38174 | * // parsingErrors: [],
|
38175 | * // map:
|
38176 | * // { version: 3,
|
38177 | * // sources: [ 'string' ],
|
38178 | * // names: [],
|
38179 | * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
|
38180 | * // sourcesContent: [ 'abc/*.js' ] },
|
38181 | * // position: { line: 1, column: 28 },
|
38182 | * // content: {},
|
38183 | * // files: {},
|
38184 | * // idx: 6 }]
|
38185 | * ```
|
38186 | * @param {String} `pattern` Glob pattern to parse and compile.
|
38187 | * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
|
38188 | * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
|
38189 | * @api public
|
38190 | */
|
38191 |
|
38192 | micromatch.create = function(pattern, options) {
|
38193 | return memoize$3('create', pattern, options, function() {
|
38194 | function create(str, opts) {
|
38195 | return micromatch.compile(micromatch.parse(str, opts), opts);
|
38196 | }
|
38197 |
|
38198 | pattern = micromatch.braces(pattern, options);
|
38199 | var len = pattern.length;
|
38200 | var idx = -1;
|
38201 | var res = [];
|
38202 |
|
38203 | while (++idx < len) {
|
38204 | res.push(create(pattern[idx], options));
|
38205 | }
|
38206 | return res;
|
38207 | });
|
38208 | };
|
38209 |
|
38210 | /**
|
38211 | * Parse the given `str` with the given `options`.
|
38212 | *
|
38213 | * ```js
|
38214 | * var mm = require('micromatch');
|
38215 | * mm.parse(pattern[, options]);
|
38216 | *
|
38217 | * var ast = mm.parse('a/{b,c}/d');
|
38218 | * console.log(ast);
|
38219 | * // { type: 'root',
|
38220 | * // errors: [],
|
38221 | * // input: 'a/{b,c}/d',
|
38222 | * // nodes:
|
38223 | * // [ { type: 'bos', val: '' },
|
38224 | * // { type: 'text', val: 'a/' },
|
38225 | * // { type: 'brace',
|
38226 | * // nodes:
|
38227 | * // [ { type: 'brace.open', val: '{' },
|
38228 | * // { type: 'text', val: 'b,c' },
|
38229 | * // { type: 'brace.close', val: '}' } ] },
|
38230 | * // { type: 'text', val: '/d' },
|
38231 | * // { type: 'eos', val: '' } ] }
|
38232 | * ```
|
38233 | * @param {String} `str`
|
38234 | * @param {Object} `options`
|
38235 | * @return {Object} Returns an AST
|
38236 | * @api public
|
38237 | */
|
38238 |
|
38239 | micromatch.parse = function(pattern, options) {
|
38240 | if (typeof pattern !== 'string') {
|
38241 | throw new TypeError('expected a string');
|
38242 | }
|
38243 |
|
38244 | function parse() {
|
38245 | var snapdragon = utils_1$3.instantiate(null, options);
|
38246 | parsers$4(snapdragon, options);
|
38247 |
|
38248 | var ast = snapdragon.parse(pattern, options);
|
38249 | utils_1$3.define(ast, 'snapdragon', snapdragon);
|
38250 | ast.input = pattern;
|
38251 | return ast;
|
38252 | }
|
38253 |
|
38254 | return memoize$3('parse', pattern, options, parse);
|
38255 | };
|
38256 |
|
38257 | /**
|
38258 | * Compile the given `ast` or string with the given `options`.
|
38259 | *
|
38260 | * ```js
|
38261 | * var mm = require('micromatch');
|
38262 | * mm.compile(ast[, options]);
|
38263 | *
|
38264 | * var ast = mm.parse('a/{b,c}/d');
|
38265 | * console.log(mm.compile(ast));
|
38266 | * // { options: { source: 'string' },
|
38267 | * // state: {},
|
38268 | * // compilers:
|
38269 | * // { eos: [Function],
|
38270 | * // noop: [Function],
|
38271 | * // bos: [Function],
|
38272 | * // brace: [Function],
|
38273 | * // 'brace.open': [Function],
|
38274 | * // text: [Function],
|
38275 | * // 'brace.close': [Function] },
|
38276 | * // output: [ 'a/(b|c)/d' ],
|
38277 | * // ast:
|
38278 | * // { ... },
|
38279 | * // parsingErrors: [] }
|
38280 | * ```
|
38281 | * @param {Object|String} `ast`
|
38282 | * @param {Object} `options`
|
38283 | * @return {Object} Returns an object that has an `output` property with the compiled string.
|
38284 | * @api public
|
38285 | */
|
38286 |
|
38287 | micromatch.compile = function(ast, options) {
|
38288 | if (typeof ast === 'string') {
|
38289 | ast = micromatch.parse(ast, options);
|
38290 | }
|
38291 |
|
38292 | return memoize$3('compile', ast.input, options, function() {
|
38293 | var snapdragon = utils_1$3.instantiate(ast, options);
|
38294 | compilers$4(snapdragon, options);
|
38295 | return snapdragon.compile(ast, options);
|
38296 | });
|
38297 | };
|
38298 |
|
38299 | /**
|
38300 | * Clear the regex cache.
|
38301 | *
|
38302 | * ```js
|
38303 | * mm.clearCache();
|
38304 | * ```
|
38305 | * @api public
|
38306 | */
|
38307 |
|
38308 | micromatch.clearCache = function() {
|
38309 | micromatch.cache.caches = {};
|
38310 | };
|
38311 |
|
38312 | /**
|
38313 | * Returns true if the given value is effectively an empty string
|
38314 | */
|
38315 |
|
38316 | function isEmptyString(val) {
|
38317 | return String(val) === '' || String(val) === './';
|
38318 | }
|
38319 |
|
38320 | /**
|
38321 | * Compose a matcher function with the given patterns.
|
38322 | * This allows matcher functions to be compiled once and
|
38323 | * called multiple times.
|
38324 | */
|
38325 |
|
38326 | function compose$1(patterns, options, matcher) {
|
38327 | var matchers;
|
38328 |
|
38329 | return memoize$3('compose', String(patterns), options, function() {
|
38330 | return function(file) {
|
38331 | // delay composition until it's invoked the first time,
|
38332 | // after that it won't be called again
|
38333 | if (!matchers) {
|
38334 | matchers = [];
|
38335 | for (var i = 0; i < patterns.length; i++) {
|
38336 | matchers.push(matcher(patterns[i], options));
|
38337 | }
|
38338 | }
|
38339 |
|
38340 | var len = matchers.length;
|
38341 | while (len--) {
|
38342 | if (matchers[len](file) === true) {
|
38343 | return true;
|
38344 | }
|
38345 | }
|
38346 | return false;
|
38347 | };
|
38348 | });
|
38349 | }
|
38350 |
|
38351 | /**
|
38352 | * Memoize a generated regex or function. A unique key is generated
|
38353 | * from the `type` (usually method name), the `pattern`, and
|
38354 | * user-defined options.
|
38355 | */
|
38356 |
|
38357 | function memoize$3(type, pattern, options, fn) {
|
38358 | var key = utils_1$3.createKey(type + '=' + pattern, options);
|
38359 |
|
38360 | if (options && options.cache === false) {
|
38361 | return fn(pattern, options);
|
38362 | }
|
38363 |
|
38364 | if (cache$5.has(type, key)) {
|
38365 | return cache$5.get(type, key);
|
38366 | }
|
38367 |
|
38368 | var val = fn(pattern, options);
|
38369 | cache$5.set(type, key, val);
|
38370 | return val;
|
38371 | }
|
38372 |
|
38373 | /**
|
38374 | * Expose compiler, parser and cache on `micromatch`
|
38375 | */
|
38376 |
|
38377 | micromatch.compilers = compilers$4;
|
38378 | micromatch.parsers = parsers$4;
|
38379 | micromatch.caches = cache$5.caches;
|
38380 |
|
38381 | /**
|
38382 | * Expose `micromatch`
|
38383 | * @type {Function}
|
38384 | */
|
38385 |
|
38386 | var micromatch_1 = micromatch;
|
38387 | var micromatch_2 = micromatch_1.matcher;
|
38388 |
|
38389 | function ensureArray(thing) {
|
38390 | if (Array.isArray(thing))
|
38391 | return thing;
|
38392 | if (thing == undefined)
|
38393 | return [];
|
38394 | return [thing];
|
38395 | }
|
38396 |
|
38397 | var createFilter = function createFilter(include, exclude) {
|
38398 | var getMatcher = function (id) {
|
38399 | return id instanceof RegExp
|
38400 | ? id
|
38401 | : {
|
38402 | test: micromatch_2(path.resolve(id)
|
38403 | .split(path.sep)
|
38404 | .join('/'))
|
38405 | };
|
38406 | };
|
38407 | var includeMatchers = ensureArray(include).map(getMatcher);
|
38408 | var excludeMatchers = ensureArray(exclude).map(getMatcher);
|
38409 | return function (id) {
|
38410 | if (typeof id !== 'string')
|
38411 | return false;
|
38412 | if (/\0/.test(id))
|
38413 | return false;
|
38414 | id = id.split(path.sep).join('/');
|
38415 | for (var i = 0; i < excludeMatchers.length; ++i) {
|
38416 | var matcher = excludeMatchers[i];
|
38417 | if (matcher.test(id))
|
38418 | return false;
|
38419 | }
|
38420 | for (var i = 0; i < includeMatchers.length; ++i) {
|
38421 | var matcher = includeMatchers[i];
|
38422 | if (matcher.test(id))
|
38423 | return true;
|
38424 | }
|
38425 | return !includeMatchers.length;
|
38426 | };
|
38427 | };
|
38428 |
|
38429 | var modules = {};
|
38430 |
|
38431 | var getModule = function(dir) {
|
38432 | var rootPath = dir ? path__default.resolve(dir) : process.cwd();
|
38433 | var rootName = path__default.join(rootPath, '@root');
|
38434 | var root = modules[rootName];
|
38435 | if (!root) {
|
38436 | root = new module$1(rootName);
|
38437 | root.filename = rootName;
|
38438 | root.paths = module$1._nodeModulePaths(rootPath);
|
38439 | modules[rootName] = root;
|
38440 | }
|
38441 | return root;
|
38442 | };
|
38443 |
|
38444 | var requireRelative = function(requested, relativeTo) {
|
38445 | var root = getModule(relativeTo);
|
38446 | return root.require(requested);
|
38447 | };
|
38448 |
|
38449 | requireRelative.resolve = function(requested, relativeTo) {
|
38450 | var root = getModule(relativeTo);
|
38451 | return module$1._resolveFilename(requested, root);
|
38452 | };
|
38453 |
|
38454 | var requireRelative_1 = requireRelative;
|
38455 |
|
38456 | var chokidar;
|
38457 | try {
|
38458 | chokidar = requireRelative_1('chokidar', process.cwd());
|
38459 | }
|
38460 | catch (err) {
|
38461 | chokidar = null;
|
38462 | }
|
38463 | var chokidar$1 = chokidar;
|
38464 |
|
38465 | var opts = { encoding: 'utf-8', persistent: true };
|
38466 | var watchers = new Map();
|
38467 | function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
|
38468 | if (!watchers.has(chokidarOptionsHash))
|
38469 | watchers.set(chokidarOptionsHash, new Map());
|
38470 | var group = watchers.get(chokidarOptionsHash);
|
38471 | var watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
|
38472 | if (!watcher.fileExists) {
|
38473 | if (isTransformDependency)
|
38474 | throw new Error("Transform dependency " + id + " does not exist.");
|
38475 | }
|
38476 | else {
|
38477 | watcher.addTask(task, isTransformDependency);
|
38478 | }
|
38479 | }
|
38480 | function deleteTask(id, target, chokidarOptionsHash) {
|
38481 | var group = watchers.get(chokidarOptionsHash);
|
38482 | var watcher = group.get(id);
|
38483 | if (watcher)
|
38484 | watcher.deleteTask(target, group);
|
38485 | }
|
38486 | var FileWatcher = /** @class */ (function () {
|
38487 | function FileWatcher(id, chokidarOptions, group) {
|
38488 | var _this = this;
|
38489 | this.id = id;
|
38490 | this.tasks = new Set();
|
38491 | this.transformDependencyTasks = new Set();
|
38492 | var modifiedTime;
|
38493 | try {
|
38494 | var stats = fs.statSync(id);
|
38495 | modifiedTime = +stats.mtime;
|
38496 | this.fileExists = true;
|
38497 | }
|
38498 | catch (err) {
|
38499 | if (err.code === 'ENOENT') {
|
38500 | // can't watch files that don't exist (e.g. injected
|
38501 | // by plugins somehow)
|
38502 | this.fileExists = false;
|
38503 | return;
|
38504 | }
|
38505 | else {
|
38506 | throw err;
|
38507 | }
|
38508 | }
|
38509 | var handleWatchEvent = function (event) {
|
38510 | if (event === 'rename' || event === 'unlink') {
|
38511 | _this.close();
|
38512 | group.delete(id);
|
38513 | _this.trigger(id);
|
38514 | }
|
38515 | else {
|
38516 | var stats = void 0;
|
38517 | try {
|
38518 | stats = fs.statSync(id);
|
38519 | }
|
38520 | catch (err) {
|
38521 | if (err.code === 'ENOENT') {
|
38522 | modifiedTime = -1;
|
38523 | _this.trigger(id);
|
38524 | return;
|
38525 | }
|
38526 | throw err;
|
38527 | }
|
38528 | // debounce
|
38529 | if (+stats.mtime - modifiedTime > 15)
|
38530 | _this.trigger(id);
|
38531 | }
|
38532 | };
|
38533 | if (chokidarOptions) {
|
38534 | this.fsWatcher = chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent);
|
38535 | }
|
38536 | else {
|
38537 | this.fsWatcher = fs.watch(id, opts, handleWatchEvent);
|
38538 | }
|
38539 | group.set(id, this);
|
38540 | }
|
38541 | FileWatcher.prototype.addTask = function (task, isTransformDependency) {
|
38542 | if (isTransformDependency === void 0) { isTransformDependency = false; }
|
38543 | if (isTransformDependency)
|
38544 | this.transformDependencyTasks.add(task);
|
38545 | else
|
38546 | this.tasks.add(task);
|
38547 | };
|
38548 | FileWatcher.prototype.close = function () {
|
38549 | this.fsWatcher.close();
|
38550 | };
|
38551 | FileWatcher.prototype.deleteTask = function (task, group) {
|
38552 | var deleted = this.tasks.delete(task);
|
38553 | deleted = this.transformDependencyTasks.delete(task) || deleted;
|
38554 | if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
|
38555 | group.delete(this.id);
|
38556 | this.close();
|
38557 | }
|
38558 | };
|
38559 | FileWatcher.prototype.trigger = function (id) {
|
38560 | this.tasks.forEach(function (task) {
|
38561 | task.invalidate(id, false);
|
38562 | });
|
38563 | this.transformDependencyTasks.forEach(function (task) {
|
38564 | task.invalidate(id, true);
|
38565 | });
|
38566 | };
|
38567 | return FileWatcher;
|
38568 | }());
|
38569 |
|
38570 | var DELAY = 200;
|
38571 | var Watcher = /** @class */ (function () {
|
38572 | function Watcher(configs) {
|
38573 | var _this = this;
|
38574 | this.invalidatedIds = new Set();
|
38575 | this.rerun = false;
|
38576 | this.succeeded = false;
|
38577 | this.emitter = new (/** @class */ (function (_super) {
|
38578 | __extends(class_1, _super);
|
38579 | function class_1(close) {
|
38580 | var _this = _super.call(this) || this;
|
38581 | _this.close = close;
|
38582 | // Allows more than 10 bundles to be watched without
|
38583 | // showing the `MaxListenersExceededWarning` to the user.
|
38584 | _this.setMaxListeners(Infinity);
|
38585 | return _this;
|
38586 | }
|
38587 | return class_1;
|
38588 | }(events.EventEmitter)))(this.close.bind(this));
|
38589 | this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(function (config) { return new Task(_this, config); });
|
38590 | this.running = true;
|
38591 | process.nextTick(function () { return _this.run(); });
|
38592 | }
|
38593 | Watcher.prototype.close = function () {
|
38594 | if (this.buildTimeout)
|
38595 | clearTimeout(this.buildTimeout);
|
38596 | this.tasks.forEach(function (task) {
|
38597 | task.close();
|
38598 | });
|
38599 | this.emitter.removeAllListeners();
|
38600 | };
|
38601 | Watcher.prototype.emit = function (event, value) {
|
38602 | this.emitter.emit(event, value);
|
38603 | };
|
38604 | Watcher.prototype.invalidate = function (id) {
|
38605 | var _this = this;
|
38606 | if (id) {
|
38607 | this.invalidatedIds.add(id);
|
38608 | }
|
38609 | if (this.running) {
|
38610 | this.rerun = true;
|
38611 | return;
|
38612 | }
|
38613 | if (this.buildTimeout)
|
38614 | clearTimeout(this.buildTimeout);
|
38615 | this.buildTimeout = setTimeout(function () {
|
38616 | _this.buildTimeout = undefined;
|
38617 | _this.invalidatedIds.forEach(function (id) { return _this.emit('change', id); });
|
38618 | _this.invalidatedIds.clear();
|
38619 | _this.emit('restart');
|
38620 | _this.run();
|
38621 | }, DELAY);
|
38622 | };
|
38623 | Watcher.prototype.run = function () {
|
38624 | var _this = this;
|
38625 | this.running = true;
|
38626 | this.emit('event', {
|
38627 | code: 'START'
|
38628 | });
|
38629 | var taskPromise = Promise.resolve();
|
38630 | var _loop_1 = function (task) {
|
38631 | taskPromise = taskPromise.then(function () { return task.run(); });
|
38632 | };
|
38633 | for (var _i = 0, _a = this.tasks; _i < _a.length; _i++) {
|
38634 | var task = _a[_i];
|
38635 | _loop_1(task);
|
38636 | }
|
38637 | return taskPromise
|
38638 | .then(function () {
|
38639 | _this.succeeded = true;
|
38640 | _this.running = false;
|
38641 | _this.emit('event', {
|
38642 | code: 'END'
|
38643 | });
|
38644 | })
|
38645 | .catch(function (error) {
|
38646 | _this.running = false;
|
38647 | _this.emit('event', {
|
38648 | code: _this.succeeded ? 'ERROR' : 'FATAL',
|
38649 | error: error
|
38650 | });
|
38651 | })
|
38652 | .then(function () {
|
38653 | if (_this.rerun) {
|
38654 | _this.rerun = false;
|
38655 | _this.invalidate();
|
38656 | }
|
38657 | });
|
38658 | };
|
38659 | return Watcher;
|
38660 | }());
|
38661 | var Task = /** @class */ (function () {
|
38662 | function Task(watcher, config) {
|
38663 | this.invalidated = true;
|
38664 | this.cache = null;
|
38665 | this.watcher = watcher;
|
38666 | this.closed = false;
|
38667 | this.watched = new Set();
|
38668 | var _a = mergeOptions({
|
38669 | config: config
|
38670 | }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions;
|
38671 | this.inputOptions = inputOptions;
|
38672 | this.outputs = outputOptions;
|
38673 | this.outputFiles = this.outputs.map(function (output) {
|
38674 | if (output.file || output.dir)
|
38675 | return path__default.resolve(output.file || output.dir);
|
38676 | });
|
38677 | var watchOptions = inputOptions.watch || {};
|
38678 | if ('useChokidar' in watchOptions)
|
38679 | watchOptions.chokidar = watchOptions.useChokidar;
|
38680 | var chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
|
38681 | if (chokidarOptions) {
|
38682 | chokidarOptions = __assign({}, (chokidarOptions === true ? {} : chokidarOptions), { disableGlobbing: true, ignoreInitial: true });
|
38683 | }
|
38684 | if (chokidarOptions && !chokidar$1) {
|
38685 | throw new Error("watch.chokidar was provided, but chokidar could not be found. Have you installed it?");
|
38686 | }
|
38687 | this.chokidarOptions = chokidarOptions;
|
38688 | this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
|
38689 | this.filter = createFilter(watchOptions.include, watchOptions.exclude);
|
38690 | }
|
38691 | Task.prototype.close = function () {
|
38692 | var _this = this;
|
38693 | this.closed = true;
|
38694 | this.watched.forEach(function (id) {
|
38695 | deleteTask(id, _this, _this.chokidarOptionsHash);
|
38696 | });
|
38697 | };
|
38698 | Task.prototype.invalidate = function (id, isTransformDependency) {
|
38699 | this.invalidated = true;
|
38700 | if (isTransformDependency) {
|
38701 | this.cache.modules.forEach(function (module) {
|
38702 | if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1)
|
38703 | return;
|
38704 | // effective invalidation
|
38705 | module.originalCode = null;
|
38706 | });
|
38707 | }
|
38708 | this.watcher.invalidate(id);
|
38709 | };
|
38710 | Task.prototype.run = function () {
|
38711 | var _this = this;
|
38712 | if (!this.invalidated)
|
38713 | return;
|
38714 | this.invalidated = false;
|
38715 | var options = __assign({}, this.inputOptions, { cache: this.cache });
|
38716 | var start = Date.now();
|
38717 | this.watcher.emit('event', {
|
38718 | code: 'BUNDLE_START',
|
38719 | input: this.inputOptions.input,
|
38720 | output: this.outputFiles
|
38721 | });
|
38722 | setWatcher(this.watcher.emitter);
|
38723 | return rollup(options)
|
38724 | .then(function (result) {
|
38725 | if (_this.closed)
|
38726 | return;
|
38727 | var watched = (_this.watched = new Set());
|
38728 | _this.cache = result.cache;
|
38729 | _this.watchFiles = result.watchFiles;
|
38730 | _this.cache.modules.forEach(function (module) {
|
38731 | if (module.transformDependencies) {
|
38732 | module.transformDependencies.forEach(function (depId) {
|
38733 | watched.add(depId);
|
38734 | _this.watchFile(depId, true);
|
38735 | });
|
38736 | }
|
38737 | });
|
38738 | _this.watchFiles.forEach(function (id) {
|
38739 | watched.add(id);
|
38740 | _this.watchFile(id);
|
38741 | });
|
38742 | _this.watched.forEach(function (id) {
|
38743 | if (!watched.has(id))
|
38744 | deleteTask(id, _this, _this.chokidarOptionsHash);
|
38745 | });
|
38746 | return Promise.all(_this.outputs.map(function (output) { return result.write(output); })).then(function () { return result; });
|
38747 | })
|
38748 | .then(function (result) {
|
38749 | _this.watcher.emit('event', {
|
38750 | code: 'BUNDLE_END',
|
38751 | duration: Date.now() - start,
|
38752 | input: _this.inputOptions.input,
|
38753 | output: _this.outputFiles,
|
38754 | result: result
|
38755 | });
|
38756 | })
|
38757 | .catch(function (error) {
|
38758 | if (_this.closed)
|
38759 | return;
|
38760 | if (_this.cache) {
|
38761 | // this is necessary to ensure that any 'renamed' files
|
38762 | // continue to be watched following an error
|
38763 | if (_this.cache.modules) {
|
38764 | _this.cache.modules.forEach(function (module) {
|
38765 | if (module.transformDependencies) {
|
38766 | module.transformDependencies.forEach(function (depId) {
|
38767 | _this.watchFile(depId, true);
|
38768 | });
|
38769 | }
|
38770 | });
|
38771 | }
|
38772 | _this.watchFiles.forEach(function (id) {
|
38773 | _this.watchFile(id);
|
38774 | });
|
38775 | }
|
38776 | throw error;
|
38777 | });
|
38778 | };
|
38779 | Task.prototype.watchFile = function (id, isTransformDependency) {
|
38780 | if (isTransformDependency === void 0) { isTransformDependency = false; }
|
38781 | if (!this.filter(id))
|
38782 | return;
|
38783 | if (this.outputFiles.some(function (file) { return file === id; })) {
|
38784 | throw new Error('Cannot import the generated bundle');
|
38785 | }
|
38786 | // this is necessary to ensure that any 'renamed' files
|
38787 | // continue to be watched following an error
|
38788 | addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
|
38789 | };
|
38790 | return Task;
|
38791 | }());
|
38792 | function watch(configs) {
|
38793 | return new Watcher(configs).emitter;
|
38794 | }
|
38795 |
|
38796 | exports.VERSION = version;
|
38797 | exports.rollup = rollup;
|
38798 | exports.watch = watch;
|
38799 | //# sourceMappingURL=rollup.js.map
|