html-crush 4.1.10 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4024 +0,0 @@
1
- /**
2
- * @name html-crush
3
- * @fileoverview Minifies HTML/CSS: valid or broken, pure or mixed with other languages
4
- * @version 4.1.10
5
- * @author Roy Revelt, Codsen Ltd
6
- * @license MIT
7
- * {@link https://codsen.com/os/html-crush/}
8
- */
9
-
10
- (function (global, factory) {
11
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
12
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
13
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.htmlCrush = {}));
14
- }(this, (function (exports) { 'use strict';
15
-
16
- /**
17
- * @name ranges-sort
18
- * @fileoverview Sort string index ranges
19
- * @version 4.0.16
20
- * @author Roy Revelt, Codsen Ltd
21
- * @license MIT
22
- * {@link https://codsen.com/os/ranges-sort/}
23
- */
24
- const defaults$5 = {
25
- strictlyTwoElementsInRangeArrays: false,
26
- progressFn: null
27
- };
28
- function rSort(arrOfRanges, originalOptions) {
29
- if (!Array.isArray(arrOfRanges) || !arrOfRanges.length) {
30
- return arrOfRanges;
31
- }
32
- const opts = { ...defaults$5,
33
- ...originalOptions
34
- };
35
- let culpritsIndex;
36
- let culpritsLen;
37
- if (opts.strictlyTwoElementsInRangeArrays && !arrOfRanges.filter(range => range).every((rangeArr, indx) => {
38
- if (rangeArr.length !== 2) {
39
- culpritsIndex = indx;
40
- culpritsLen = rangeArr.length;
41
- return false;
42
- }
43
- return true;
44
- })) {
45
- throw new TypeError(`ranges-sort: [THROW_ID_03] The first argument should be an array and must consist of arrays which are natural number indexes representing TWO string index ranges. However, ${culpritsIndex}th range (${JSON.stringify(arrOfRanges[culpritsIndex], null, 4)}) has not two but ${culpritsLen} elements!`);
46
- }
47
- if (!arrOfRanges.filter(range => range).every((rangeArr, indx) => {
48
- if (!Number.isInteger(rangeArr[0]) || rangeArr[0] < 0 || !Number.isInteger(rangeArr[1]) || rangeArr[1] < 0) {
49
- culpritsIndex = indx;
50
- return false;
51
- }
52
- return true;
53
- })) {
54
- throw new TypeError(`ranges-sort: [THROW_ID_04] The first argument should be an array and must consist of arrays which are natural number indexes representing string index ranges. However, ${culpritsIndex}th range (${JSON.stringify(arrOfRanges[culpritsIndex], null, 4)}) does not consist of only natural numbers!`);
55
- }
56
- const maxPossibleIterations = arrOfRanges.filter(range => range).length ** 2;
57
- let counter = 0;
58
- return Array.from(arrOfRanges).filter(range => range).sort((range1, range2) => {
59
- if (opts.progressFn) {
60
- counter += 1;
61
- opts.progressFn(Math.floor(counter * 100 / maxPossibleIterations));
62
- }
63
- if (range1[0] === range2[0]) {
64
- if (range1[1] < range2[1]) {
65
- return -1;
66
- }
67
- if (range1[1] > range2[1]) {
68
- return 1;
69
- }
70
- return 0;
71
- }
72
- if (range1[0] < range2[0]) {
73
- return -1;
74
- }
75
- return 1;
76
- });
77
- }
78
-
79
- /**
80
- * @name ranges-merge
81
- * @fileoverview Merge and sort string index ranges
82
- * @version 7.0.16
83
- * @author Roy Revelt, Codsen Ltd
84
- * @license MIT
85
- * {@link https://codsen.com/os/ranges-merge/}
86
- */
87
- const defaults$4 = {
88
- mergeType: 1,
89
- progressFn: null,
90
- joinRangesThatTouchEdges: true
91
- };
92
- function rMerge(arrOfRanges, originalOpts) {
93
- function isObj(something) {
94
- return something && typeof something === "object" && !Array.isArray(something);
95
- }
96
- if (!Array.isArray(arrOfRanges) || !arrOfRanges.length) {
97
- return null;
98
- }
99
- let opts;
100
- if (originalOpts) {
101
- if (isObj(originalOpts)) {
102
- opts = { ...defaults$4,
103
- ...originalOpts
104
- };
105
- if (opts.progressFn && isObj(opts.progressFn) && !Object.keys(opts.progressFn).length) {
106
- opts.progressFn = null;
107
- } else if (opts.progressFn && typeof opts.progressFn !== "function") {
108
- throw new Error(`ranges-merge: [THROW_ID_01] opts.progressFn must be a function! It was given of a type: "${typeof opts.progressFn}", equal to ${JSON.stringify(opts.progressFn, null, 4)}`);
109
- }
110
- if (opts.mergeType && +opts.mergeType !== 1 && +opts.mergeType !== 2) {
111
- throw new Error(`ranges-merge: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof opts.mergeType}", equal to ${JSON.stringify(opts.mergeType, null, 4)}`);
112
- }
113
- if (typeof opts.joinRangesThatTouchEdges !== "boolean") {
114
- throw new Error(`ranges-merge: [THROW_ID_04] opts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof opts.joinRangesThatTouchEdges}", equal to ${JSON.stringify(opts.joinRangesThatTouchEdges, null, 4)}`);
115
- }
116
- } else {
117
- throw new Error(`emlint: [THROW_ID_03] the second input argument must be a plain object. It was given as:\n${JSON.stringify(originalOpts, null, 4)} (type ${typeof originalOpts})`);
118
- }
119
- } else {
120
- opts = { ...defaults$4
121
- };
122
- }
123
- const filtered = arrOfRanges
124
- .filter(range => range).map(subarr => [...subarr]).filter(
125
- rangeArr => rangeArr[2] !== undefined || rangeArr[0] !== rangeArr[1]);
126
- let sortedRanges;
127
- let lastPercentageDone;
128
- let percentageDone;
129
- if (opts.progressFn) {
130
- sortedRanges = rSort(filtered, {
131
- progressFn: percentage => {
132
- percentageDone = Math.floor(percentage / 5);
133
- if (percentageDone !== lastPercentageDone) {
134
- lastPercentageDone = percentageDone;
135
- opts.progressFn(percentageDone);
136
- }
137
- }
138
- });
139
- } else {
140
- sortedRanges = rSort(filtered);
141
- }
142
- if (!sortedRanges) {
143
- return null;
144
- }
145
- const len = sortedRanges.length - 1;
146
- for (let i = len; i > 0; i--) {
147
- if (opts.progressFn) {
148
- percentageDone = Math.floor((1 - i / len) * 78) + 21;
149
- if (percentageDone !== lastPercentageDone && percentageDone > lastPercentageDone) {
150
- lastPercentageDone = percentageDone;
151
- opts.progressFn(percentageDone);
152
- }
153
- }
154
- if (sortedRanges[i][0] <= sortedRanges[i - 1][0] || !opts.joinRangesThatTouchEdges && sortedRanges[i][0] < sortedRanges[i - 1][1] || opts.joinRangesThatTouchEdges && sortedRanges[i][0] <= sortedRanges[i - 1][1]) {
155
- sortedRanges[i - 1][0] = Math.min(sortedRanges[i][0], sortedRanges[i - 1][0]);
156
- sortedRanges[i - 1][1] = Math.max(sortedRanges[i][1], sortedRanges[i - 1][1]);
157
- if (sortedRanges[i][2] !== undefined && (sortedRanges[i - 1][0] >= sortedRanges[i][0] || sortedRanges[i - 1][1] <= sortedRanges[i][1])) {
158
- if (sortedRanges[i - 1][2] !== null) {
159
- if (sortedRanges[i][2] === null && sortedRanges[i - 1][2] !== null) {
160
- sortedRanges[i - 1][2] = null;
161
- } else if (sortedRanges[i - 1][2] != null) {
162
- if (+opts.mergeType === 2 && sortedRanges[i - 1][0] === sortedRanges[i][0]) {
163
- sortedRanges[i - 1][2] = sortedRanges[i][2];
164
- } else {
165
- sortedRanges[i - 1][2] += sortedRanges[i][2];
166
- }
167
- } else {
168
- sortedRanges[i - 1][2] = sortedRanges[i][2];
169
- }
170
- }
171
- }
172
- sortedRanges.splice(i, 1);
173
- i = sortedRanges.length;
174
- }
175
- }
176
- return sortedRanges.length ? sortedRanges : null;
177
- }
178
-
179
- /**
180
- * @name ranges-apply
181
- * @fileoverview Take an array of string index ranges, delete/replace the string according to them
182
- * @version 5.0.16
183
- * @author Roy Revelt, Codsen Ltd
184
- * @license MIT
185
- * {@link https://codsen.com/os/ranges-apply/}
186
- */
187
- function rApply(str, originalRangesArr, progressFn) {
188
- let percentageDone = 0;
189
- let lastPercentageDone = 0;
190
- if (arguments.length === 0) {
191
- throw new Error("ranges-apply: [THROW_ID_01] inputs missing!");
192
- }
193
- if (typeof str !== "string") {
194
- throw new TypeError(`ranges-apply: [THROW_ID_02] first input argument must be a string! Currently it's: ${typeof str}, equal to: ${JSON.stringify(str, null, 4)}`);
195
- }
196
- if (originalRangesArr && !Array.isArray(originalRangesArr)) {
197
- throw new TypeError(`ranges-apply: [THROW_ID_03] second input argument must be an array (or null)! Currently it's: ${typeof originalRangesArr}, equal to: ${JSON.stringify(originalRangesArr, null, 4)}`);
198
- }
199
- if (progressFn && typeof progressFn !== "function") {
200
- throw new TypeError(`ranges-apply: [THROW_ID_04] the third input argument must be a function (or falsey)! Currently it's: ${typeof progressFn}, equal to: ${JSON.stringify(progressFn, null, 4)}`);
201
- }
202
- if (!originalRangesArr || !originalRangesArr.filter(range => range).length) {
203
- return str;
204
- }
205
- let rangesArr;
206
- if (Array.isArray(originalRangesArr) && Number.isInteger(originalRangesArr[0]) && Number.isInteger(originalRangesArr[1])) {
207
- rangesArr = [Array.from(originalRangesArr)];
208
- } else {
209
- rangesArr = Array.from(originalRangesArr);
210
- }
211
- const len = rangesArr.length;
212
- let counter = 0;
213
- rangesArr.filter(range => range).forEach((el, i) => {
214
- if (progressFn) {
215
- percentageDone = Math.floor(counter / len * 10);
216
- /* istanbul ignore else */
217
- if (percentageDone !== lastPercentageDone) {
218
- lastPercentageDone = percentageDone;
219
- progressFn(percentageDone);
220
- }
221
- }
222
- if (!Array.isArray(el)) {
223
- throw new TypeError(`ranges-apply: [THROW_ID_05] ranges array, second input arg., has ${i}th element not an array: ${JSON.stringify(el, null, 4)}, which is ${typeof el}`);
224
- }
225
- if (!Number.isInteger(el[0])) {
226
- if (!Number.isInteger(+el[0]) || +el[0] < 0) {
227
- throw new TypeError(`ranges-apply: [THROW_ID_06] ranges array, second input arg. has ${i}th element, array ${JSON.stringify(el, null, 0)}. Its first element is not an integer, string index, but ${typeof el[0]}, equal to: ${JSON.stringify(el[0], null, 4)}.`);
228
- } else {
229
- rangesArr[i][0] = +rangesArr[i][0];
230
- }
231
- }
232
- if (!Number.isInteger(el[1])) {
233
- if (!Number.isInteger(+el[1]) || +el[1] < 0) {
234
- throw new TypeError(`ranges-apply: [THROW_ID_07] ranges array, second input arg. has ${i}th element, array ${JSON.stringify(el, null, 0)}. Its second element is not an integer, string index, but ${typeof el[1]}, equal to: ${JSON.stringify(el[1], null, 4)}.`);
235
- } else {
236
- rangesArr[i][1] = +rangesArr[i][1];
237
- }
238
- }
239
- counter += 1;
240
- });
241
- const workingRanges = rMerge(rangesArr, {
242
- progressFn: perc => {
243
- if (progressFn) {
244
- percentageDone = 10 + Math.floor(perc / 10);
245
- /* istanbul ignore else */
246
- if (percentageDone !== lastPercentageDone) {
247
- lastPercentageDone = percentageDone;
248
- progressFn(percentageDone);
249
- }
250
- }
251
- }
252
- });
253
- const len2 = Array.isArray(workingRanges) ? workingRanges.length : 0;
254
- /* istanbul ignore else */
255
- if (len2 > 0) {
256
- const tails = str.slice(workingRanges[len2 - 1][1]);
257
- str = workingRanges.reduce((acc, _val, i, arr) => {
258
- if (progressFn) {
259
- percentageDone = 20 + Math.floor(i / len2 * 80);
260
- /* istanbul ignore else */
261
- if (percentageDone !== lastPercentageDone) {
262
- lastPercentageDone = percentageDone;
263
- progressFn(percentageDone);
264
- }
265
- }
266
- const beginning = i === 0 ? 0 : arr[i - 1][1];
267
- const ending = arr[i][0];
268
- return acc + str.slice(beginning, ending) + (arr[i][2] || "");
269
- }, "");
270
- str += tails;
271
- }
272
- return str;
273
- }
274
-
275
- /**
276
- * @name string-collapse-leading-whitespace
277
- * @fileoverview Collapse the leading and trailing whitespace of a string
278
- * @version 5.0.16
279
- * @author Roy Revelt, Codsen Ltd
280
- * @license MIT
281
- * {@link https://codsen.com/os/string-collapse-leading-whitespace/}
282
- */
283
- function collWhitespace(str, originallineBreakLimit = 1) {
284
- const rawNbsp = "\u00A0";
285
- function reverse(s) {
286
- return Array.from(s).reverse().join("");
287
- }
288
- function prep(whitespaceChunk, limit, trailing) {
289
- const firstBreakChar = trailing ? "\n" : "\r";
290
- const secondBreakChar = trailing ? "\r" : "\n";
291
- if (!whitespaceChunk) {
292
- return whitespaceChunk;
293
- }
294
- let crlfCount = 0;
295
- let res = "";
296
- for (let i = 0, len = whitespaceChunk.length; i < len; i++) {
297
- if (whitespaceChunk[i] === firstBreakChar || whitespaceChunk[i] === secondBreakChar && whitespaceChunk[i - 1] !== firstBreakChar) {
298
- crlfCount++;
299
- }
300
- if (`\r\n`.includes(whitespaceChunk[i]) || whitespaceChunk[i] === rawNbsp) {
301
- if (whitespaceChunk[i] === rawNbsp) {
302
- res += whitespaceChunk[i];
303
- } else if (whitespaceChunk[i] === firstBreakChar) {
304
- if (crlfCount <= limit) {
305
- res += whitespaceChunk[i];
306
- if (whitespaceChunk[i + 1] === secondBreakChar) {
307
- res += whitespaceChunk[i + 1];
308
- i++;
309
- }
310
- }
311
- } else if (whitespaceChunk[i] === secondBreakChar && (!whitespaceChunk[i - 1] || whitespaceChunk[i - 1] !== firstBreakChar) && crlfCount <= limit) {
312
- res += whitespaceChunk[i];
313
- }
314
- } else {
315
- if (!whitespaceChunk[i + 1] && !crlfCount) {
316
- res += " ";
317
- }
318
- }
319
- }
320
- return res;
321
- }
322
- if (typeof str === "string" && str.length) {
323
- let lineBreakLimit = 1;
324
- if (typeof +originallineBreakLimit === "number" && Number.isInteger(+originallineBreakLimit) && +originallineBreakLimit >= 0) {
325
- lineBreakLimit = +originallineBreakLimit;
326
- }
327
- let frontPart = "";
328
- let endPart = "";
329
- if (!str.trim()) {
330
- frontPart = str;
331
- } else if (!str[0].trim()) {
332
- for (let i = 0, len = str.length; i < len; i++) {
333
- if (str[i].trim()) {
334
- frontPart = str.slice(0, i);
335
- break;
336
- }
337
- }
338
- }
339
- if (str.trim() && (str.slice(-1).trim() === "" || str.slice(-1) === rawNbsp)) {
340
- for (let i = str.length; i--;) {
341
- if (str[i].trim()) {
342
- endPart = str.slice(i + 1);
343
- break;
344
- }
345
- }
346
- }
347
- return `${prep(frontPart, lineBreakLimit, false)}${str.trim()}${reverse(prep(reverse(endPart), lineBreakLimit, true))}`;
348
- }
349
- return str;
350
- }
351
-
352
- /**
353
- * @name ranges-push
354
- * @fileoverview Gather string index ranges
355
- * @version 5.0.16
356
- * @author Roy Revelt, Codsen Ltd
357
- * @license MIT
358
- * {@link https://codsen.com/os/ranges-push/}
359
- */
360
- function existy(x) {
361
- return x != null;
362
- }
363
- function isNum(something) {
364
- return Number.isInteger(something) && something >= 0;
365
- }
366
- function isStr$2(something) {
367
- return typeof something === "string";
368
- }
369
- const defaults$3 = {
370
- limitToBeAddedWhitespace: false,
371
- limitLinebreaksCount: 1,
372
- mergeType: 1
373
- };
374
- class Ranges {
375
- constructor(originalOpts) {
376
- const opts = { ...defaults$3,
377
- ...originalOpts
378
- };
379
- if (opts.mergeType && opts.mergeType !== 1 && opts.mergeType !== 2) {
380
- if (isStr$2(opts.mergeType) && opts.mergeType.trim() === "1") {
381
- opts.mergeType = 1;
382
- } else if (isStr$2(opts.mergeType) && opts.mergeType.trim() === "2") {
383
- opts.mergeType = 2;
384
- } else {
385
- throw new Error(`ranges-push: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof opts.mergeType}", equal to ${JSON.stringify(opts.mergeType, null, 4)}`);
386
- }
387
- }
388
- this.opts = opts;
389
- this.ranges = [];
390
- }
391
- add(originalFrom, originalTo, addVal) {
392
- if (originalFrom == null && originalTo == null) {
393
- return;
394
- }
395
- if (existy(originalFrom) && !existy(originalTo)) {
396
- if (Array.isArray(originalFrom)) {
397
- if (originalFrom.length) {
398
- if (originalFrom.some(el => Array.isArray(el))) {
399
- originalFrom.forEach(thing => {
400
- if (Array.isArray(thing)) {
401
- this.add(...thing);
402
- }
403
- });
404
- return;
405
- }
406
- if (originalFrom.length && isNum(+originalFrom[0]) && isNum(+originalFrom[1])) {
407
- this.add(...originalFrom);
408
- }
409
- }
410
- return;
411
- }
412
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_12] the first input argument, "from" is set (${JSON.stringify(originalFrom, null, 0)}) but second-one, "to" is not (${JSON.stringify(originalTo, null, 0)})`);
413
- } else if (!existy(originalFrom) && existy(originalTo)) {
414
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_13] the second input argument, "to" is set (${JSON.stringify(originalTo, null, 0)}) but first-one, "from" is not (${JSON.stringify(originalFrom, null, 0)})`);
415
- }
416
- const from = +originalFrom;
417
- const to = +originalTo;
418
- if (isNum(addVal)) {
419
- addVal = String(addVal);
420
- }
421
- if (isNum(from) && isNum(to)) {
422
- if (existy(addVal) && !isStr$2(addVal) && !isNum(addVal)) {
423
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_08] The third argument, the value to add, was given not as string but ${typeof addVal}, equal to:\n${JSON.stringify(addVal, null, 4)}`);
424
- }
425
- if (existy(this.ranges) && Array.isArray(this.last()) && from === this.last()[1]) {
426
- this.last()[1] = to;
427
- if (this.last()[2] === null || addVal === null) ;
428
- if (this.last()[2] !== null && existy(addVal)) {
429
- let calculatedVal = this.last()[2] && this.last()[2].length > 0 && (!this.opts || !this.opts.mergeType || this.opts.mergeType === 1) ? this.last()[2] + addVal : addVal;
430
- if (this.opts.limitToBeAddedWhitespace) {
431
- calculatedVal = collWhitespace(calculatedVal, this.opts.limitLinebreaksCount);
432
- }
433
- if (!(isStr$2(calculatedVal) && !calculatedVal.length)) {
434
- this.last()[2] = calculatedVal;
435
- }
436
- }
437
- } else {
438
- if (!this.ranges) {
439
- this.ranges = [];
440
- }
441
- const whatToPush = addVal !== undefined && !(isStr$2(addVal) && !addVal.length) ? [from, to, addVal && this.opts.limitToBeAddedWhitespace ? collWhitespace(addVal, this.opts.limitLinebreaksCount) : addVal] : [from, to];
442
- this.ranges.push(whatToPush);
443
- }
444
- } else {
445
- if (!(isNum(from) && from >= 0)) {
446
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_09] "from" value, the first input argument, must be a natural number or zero! Currently it's of a type "${typeof from}" equal to: ${JSON.stringify(from, null, 4)}`);
447
- } else {
448
- throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_10] "to" value, the second input argument, must be a natural number or zero! Currently it's of a type "${typeof to}" equal to: ${JSON.stringify(to, null, 4)}`);
449
- }
450
- }
451
- }
452
- push(originalFrom, originalTo, addVal) {
453
- this.add(originalFrom, originalTo, addVal);
454
- }
455
- current() {
456
- if (Array.isArray(this.ranges) && this.ranges.length) {
457
- this.ranges = rMerge(this.ranges, {
458
- mergeType: this.opts.mergeType
459
- });
460
- if (this.ranges && this.opts.limitToBeAddedWhitespace) {
461
- return this.ranges.map(val => {
462
- if (existy(val[2])) {
463
- return [val[0], val[1], collWhitespace(val[2], this.opts.limitLinebreaksCount)];
464
- }
465
- return val;
466
- });
467
- }
468
- return this.ranges;
469
- }
470
- return null;
471
- }
472
- wipe() {
473
- this.ranges = [];
474
- }
475
- replace(givenRanges) {
476
- if (Array.isArray(givenRanges) && givenRanges.length) {
477
- if (!(Array.isArray(givenRanges[0]) && isNum(givenRanges[0][0]))) {
478
- throw new Error(`ranges-push/Ranges/replace(): [THROW_ID_11] Single range was given but we expected array of arrays! The first element, ${JSON.stringify(givenRanges[0], null, 4)} should be an array and its first element should be an integer, a string index.`);
479
- } else {
480
- this.ranges = Array.from(givenRanges);
481
- }
482
- } else {
483
- this.ranges = [];
484
- }
485
- }
486
- last() {
487
- if (Array.isArray(this.ranges) && this.ranges.length) {
488
- return this.ranges[this.ranges.length - 1];
489
- }
490
- return null;
491
- }
492
- }
493
-
494
- /**
495
- * @name arrayiffy-if-string
496
- * @fileoverview Put non-empty strings into arrays, turn empty-ones into empty arrays. Bypass everything else.
497
- * @version 3.13.16
498
- * @author Roy Revelt, Codsen Ltd
499
- * @license MIT
500
- * {@link https://codsen.com/os/arrayiffy-if-string/}
501
- */
502
-
503
- function arrayiffy(something) {
504
- if (typeof something === "string") {
505
- if (something.length) {
506
- return [something];
507
- }
508
- return [];
509
- }
510
- return something;
511
- }
512
-
513
- /**
514
- * @name string-match-left-right
515
- * @fileoverview Match substrings on the left or right of a given index, ignoring whitespace
516
- * @version 7.0.10
517
- * @author Roy Revelt, Codsen Ltd
518
- * @license MIT
519
- * {@link https://codsen.com/os/string-match-left-right/}
520
- */
521
-
522
- function isObj(something) {
523
- return something && typeof something === "object" && !Array.isArray(something);
524
- }
525
- function isStr$1(something) {
526
- return typeof something === "string";
527
- }
528
- const defaults$2 = {
529
- cb: undefined,
530
- i: false,
531
- trimBeforeMatching: false,
532
- trimCharsBeforeMatching: [],
533
- maxMismatches: 0,
534
- firstMustMatch: false,
535
- lastMustMatch: false,
536
- hungry: false
537
- };
538
- const defaultGetNextIdx = index => index + 1;
539
- function march(str, position, whatToMatchVal, originalOpts, special = false, getNextIdx = defaultGetNextIdx) {
540
- const whatToMatchValVal = typeof whatToMatchVal === "function" ? whatToMatchVal() : whatToMatchVal;
541
- if (+position < 0 && special && whatToMatchValVal === "EOL") {
542
- return whatToMatchValVal;
543
- }
544
- const opts = { ...defaults$2,
545
- ...originalOpts
546
- };
547
- if (position >= str.length && !special) {
548
- return false;
549
- }
550
- let charsToCheckCount = special ? 1 : whatToMatchVal.length;
551
- let charsMatchedTotal = 0;
552
- let patienceReducedBeforeFirstMatch = false;
553
- let lastWasMismatched = false;
554
- let atLeastSomethingWasMatched = false;
555
- let patience = opts.maxMismatches;
556
- let i = position;
557
- let somethingFound = false;
558
- let firstCharacterMatched = false;
559
- let lastCharacterMatched = false;
560
- function whitespaceInFrontOfFirstChar() {
561
- return (
562
- charsMatchedTotal === 1 &&
563
- patience < opts.maxMismatches - 1
564
- );
565
- }
566
- while (str[i]) {
567
- const nextIdx = getNextIdx(i);
568
- if (opts.trimBeforeMatching && str[i].trim() === "") {
569
- if (!str[nextIdx] && special && whatToMatchVal === "EOL") {
570
- return true;
571
- }
572
- i = getNextIdx(i);
573
- continue;
574
- }
575
- if (opts && !opts.i && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.includes(str[i]) || opts && opts.i && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.map(val => val.toLowerCase()).includes(str[i].toLowerCase())) {
576
- if (special && whatToMatchVal === "EOL" && !str[nextIdx]) {
577
- return true;
578
- }
579
- i = getNextIdx(i);
580
- continue;
581
- }
582
- const charToCompareAgainst = nextIdx > i ? whatToMatchVal[whatToMatchVal.length - charsToCheckCount] : whatToMatchVal[charsToCheckCount - 1];
583
- if (!opts.i && str[i] === charToCompareAgainst || opts.i && str[i].toLowerCase() === charToCompareAgainst.toLowerCase()) {
584
- if (!somethingFound) {
585
- somethingFound = true;
586
- }
587
- if (!atLeastSomethingWasMatched) {
588
- atLeastSomethingWasMatched = true;
589
- }
590
- if (charsToCheckCount === whatToMatchVal.length) {
591
- firstCharacterMatched = true;
592
- if (patience !== opts.maxMismatches) {
593
- return false;
594
- }
595
- } else if (charsToCheckCount === 1) {
596
- lastCharacterMatched = true;
597
- }
598
- charsToCheckCount -= 1;
599
- charsMatchedTotal++;
600
- if (whitespaceInFrontOfFirstChar()) {
601
- return false;
602
- }
603
- if (!charsToCheckCount) {
604
- return (
605
- charsMatchedTotal !== whatToMatchVal.length ||
606
- patience === opts.maxMismatches ||
607
- !patienceReducedBeforeFirstMatch ? i : false
608
- );
609
- }
610
- } else {
611
- if (!patienceReducedBeforeFirstMatch && !charsMatchedTotal) {
612
- patienceReducedBeforeFirstMatch = true;
613
- }
614
- if (opts.maxMismatches && patience && i) {
615
- patience -= 1;
616
- for (let y = 0; y <= patience; y++) {
617
- const nextCharToCompareAgainst = nextIdx > i ? whatToMatchVal[whatToMatchVal.length - charsToCheckCount + 1 + y] : whatToMatchVal[charsToCheckCount - 2 - y];
618
- const nextCharInSource = str[getNextIdx(i)];
619
- if (nextCharToCompareAgainst && (!opts.i && str[i] === nextCharToCompareAgainst || opts.i && str[i].toLowerCase() === nextCharToCompareAgainst.toLowerCase()) && (
620
- !opts.firstMustMatch || charsToCheckCount !== whatToMatchVal.length)) {
621
- charsMatchedTotal++;
622
- if (whitespaceInFrontOfFirstChar()) {
623
- return false;
624
- }
625
- charsToCheckCount -= 2;
626
- somethingFound = true;
627
- break;
628
- } else if (nextCharInSource && nextCharToCompareAgainst && (!opts.i && nextCharInSource === nextCharToCompareAgainst || opts.i && nextCharInSource.toLowerCase() === nextCharToCompareAgainst.toLowerCase()) && (
629
- !opts.firstMustMatch || charsToCheckCount !== whatToMatchVal.length)) {
630
- if (!charsMatchedTotal && !opts.hungry) {
631
- return false;
632
- }
633
- charsToCheckCount -= 1;
634
- somethingFound = true;
635
- break;
636
- } else if (nextCharToCompareAgainst === undefined && patience >= 0 && somethingFound && (!opts.firstMustMatch || firstCharacterMatched) && (!opts.lastMustMatch || lastCharacterMatched)) {
637
- return i;
638
- }
639
- }
640
- if (!somethingFound) {
641
- lastWasMismatched = i;
642
- }
643
- } else if (i === 0 && charsToCheckCount === 1 && !opts.lastMustMatch && atLeastSomethingWasMatched) {
644
- return 0;
645
- } else {
646
- return false;
647
- }
648
- }
649
- if (lastWasMismatched !== false && lastWasMismatched !== i) {
650
- lastWasMismatched = false;
651
- }
652
- if (charsToCheckCount < 1) {
653
- return i;
654
- }
655
- i = getNextIdx(i);
656
- }
657
- if (charsToCheckCount > 0) {
658
- if (special && whatToMatchValVal === "EOL") {
659
- return true;
660
- }
661
- if (opts && opts.maxMismatches >= charsToCheckCount && atLeastSomethingWasMatched) {
662
- return lastWasMismatched || 0;
663
- }
664
- return false;
665
- }
666
- }
667
- function main(mode, str, position, originalWhatToMatch, originalOpts) {
668
- if (isObj(originalOpts) && Object.prototype.hasOwnProperty.call(originalOpts, "trimBeforeMatching") && typeof originalOpts.trimBeforeMatching !== "boolean") {
669
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_09] opts.trimBeforeMatching should be boolean!${Array.isArray(originalOpts.trimBeforeMatching) ? ` Did you mean to use opts.trimCharsBeforeMatching?` : ""}`);
670
- }
671
- const opts = { ...defaults$2,
672
- ...originalOpts
673
- };
674
- if (typeof opts.trimCharsBeforeMatching === "string") {
675
- opts.trimCharsBeforeMatching = arrayiffy(opts.trimCharsBeforeMatching);
676
- }
677
- opts.trimCharsBeforeMatching = opts.trimCharsBeforeMatching.map(el => isStr$1(el) ? el : String(el));
678
- if (!isStr$1(str)) {
679
- return false;
680
- }
681
- if (!str.length) {
682
- return false;
683
- }
684
- if (!Number.isInteger(position) || position < 0) {
685
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_03] the second argument should be a natural number. Currently it's of a type: ${typeof position}, equal to:\n${JSON.stringify(position, null, 4)}`);
686
- }
687
- let whatToMatch;
688
- let special;
689
- if (isStr$1(originalWhatToMatch)) {
690
- whatToMatch = [originalWhatToMatch];
691
- } else if (Array.isArray(originalWhatToMatch)) {
692
- whatToMatch = originalWhatToMatch;
693
- } else if (!originalWhatToMatch) {
694
- whatToMatch = originalWhatToMatch;
695
- } else if (typeof originalWhatToMatch === "function") {
696
- whatToMatch = [];
697
- whatToMatch.push(originalWhatToMatch);
698
- } else {
699
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_05] the third argument, whatToMatch, is neither string nor array of strings! It's ${typeof originalWhatToMatch}, equal to:\n${JSON.stringify(originalWhatToMatch, null, 4)}`);
700
- }
701
- if (originalOpts && !isObj(originalOpts)) {
702
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_06] the fourth argument, options object, should be a plain object. Currently it's of a type "${typeof originalOpts}", and equal to:\n${JSON.stringify(originalOpts, null, 4)}`);
703
- }
704
- let culpritsIndex = 0;
705
- let culpritsVal = "";
706
- if (opts && opts.trimCharsBeforeMatching && opts.trimCharsBeforeMatching.some((el, i) => {
707
- if (el.length > 1) {
708
- culpritsIndex = i;
709
- culpritsVal = el;
710
- return true;
711
- }
712
- return false;
713
- })) {
714
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_07] the fourth argument, options object contains trimCharsBeforeMatching. It was meant to list the single characters but one of the entries at index ${culpritsIndex} is longer than 1 character, ${culpritsVal.length} (equals to ${culpritsVal}). Please split it into separate characters and put into array as separate elements.`);
715
- }
716
- if (!whatToMatch || !Array.isArray(whatToMatch) ||
717
- Array.isArray(whatToMatch) && !whatToMatch.length ||
718
- Array.isArray(whatToMatch) && whatToMatch.length === 1 && isStr$1(whatToMatch[0]) && !whatToMatch[0].trim()
719
- ) {
720
- if (typeof opts.cb === "function") {
721
- let firstCharOutsideIndex;
722
- let startingPosition = position;
723
- if (mode === "matchLeftIncl" || mode === "matchRight") {
724
- startingPosition += 1;
725
- }
726
- if (mode[5] === "L") {
727
- for (let y = startingPosition; y--;) {
728
- const currentChar = str[y];
729
- if ((!opts.trimBeforeMatching || opts.trimBeforeMatching && currentChar !== undefined && currentChar.trim()) && (!opts.trimCharsBeforeMatching || !opts.trimCharsBeforeMatching.length || currentChar !== undefined && !opts.trimCharsBeforeMatching.includes(currentChar))) {
730
- firstCharOutsideIndex = y;
731
- break;
732
- }
733
- }
734
- } else if (mode.startsWith("matchRight")) {
735
- for (let y = startingPosition; y < str.length; y++) {
736
- const currentChar = str[y];
737
- if ((!opts.trimBeforeMatching || opts.trimBeforeMatching && currentChar.trim()) && (!opts.trimCharsBeforeMatching || !opts.trimCharsBeforeMatching.length || !opts.trimCharsBeforeMatching.includes(currentChar))) {
738
- firstCharOutsideIndex = y;
739
- break;
740
- }
741
- }
742
- }
743
- if (firstCharOutsideIndex === undefined) {
744
- return false;
745
- }
746
- const wholeCharacterOutside = str[firstCharOutsideIndex];
747
- const indexOfTheCharacterAfter = firstCharOutsideIndex + 1;
748
- let theRemainderOfTheString = "";
749
- if (indexOfTheCharacterAfter && indexOfTheCharacterAfter > 0) {
750
- theRemainderOfTheString = str.slice(0, indexOfTheCharacterAfter);
751
- }
752
- if (mode[5] === "L") {
753
- return opts.cb(wholeCharacterOutside, theRemainderOfTheString, firstCharOutsideIndex);
754
- }
755
- if (firstCharOutsideIndex && firstCharOutsideIndex > 0) {
756
- theRemainderOfTheString = str.slice(firstCharOutsideIndex);
757
- }
758
- return opts.cb(wholeCharacterOutside, theRemainderOfTheString, firstCharOutsideIndex);
759
- }
760
- let extraNote = "";
761
- if (!originalOpts) {
762
- extraNote = " More so, the whole options object, the fourth input argument, is missing!";
763
- }
764
- throw new Error(`string-match-left-right/${mode}(): [THROW_ID_08] the third argument, "whatToMatch", was given as an empty string. This means, you intend to match purely by a callback. The callback was not set though, the opts key "cb" is not set!${extraNote}`);
765
- }
766
- for (let i = 0, len = whatToMatch.length; i < len; i++) {
767
- special = typeof whatToMatch[i] === "function";
768
- const whatToMatchVal = whatToMatch[i];
769
- let fullCharacterInFront;
770
- let indexOfTheCharacterInFront;
771
- let restOfStringInFront = "";
772
- let startingPosition = position;
773
- if (mode === "matchRight") {
774
- startingPosition += 1;
775
- } else if (mode === "matchLeft") {
776
- startingPosition -= 1;
777
- }
778
- const found = march(str, startingPosition, whatToMatchVal, opts, special, i2 => mode[5] === "L" ? i2 - 1 : i2 + 1);
779
- if (found && special && typeof whatToMatchVal === "function" && whatToMatchVal() === "EOL") {
780
- return whatToMatchVal() && (opts.cb ? opts.cb(fullCharacterInFront, restOfStringInFront, indexOfTheCharacterInFront) : true) ? whatToMatchVal() : false;
781
- }
782
- if (Number.isInteger(found)) {
783
- indexOfTheCharacterInFront = mode.startsWith("matchLeft") ? found - 1 : found + 1;
784
- if (mode[5] === "L") {
785
- restOfStringInFront = str.slice(0, found);
786
- } else {
787
- restOfStringInFront = str.slice(indexOfTheCharacterInFront);
788
- }
789
- }
790
- if (indexOfTheCharacterInFront < 0) {
791
- indexOfTheCharacterInFront = undefined;
792
- }
793
- if (str[indexOfTheCharacterInFront]) {
794
- fullCharacterInFront = str[indexOfTheCharacterInFront];
795
- }
796
- if (Number.isInteger(found) && (opts.cb ? opts.cb(fullCharacterInFront, restOfStringInFront, indexOfTheCharacterInFront) : true)) {
797
- return whatToMatchVal;
798
- }
799
- }
800
- return false;
801
- }
802
- function matchLeft(str, position, whatToMatch, opts) {
803
- return main("matchLeft", str, position, whatToMatch, opts);
804
- }
805
- function matchRightIncl(str, position, whatToMatch, opts) {
806
- return main("matchRightIncl", str, position, whatToMatch, opts);
807
- }
808
- function matchRight(str, position, whatToMatch, opts) {
809
- return main("matchRight", str, position, whatToMatch, opts);
810
- }
811
-
812
- /**
813
- * @name string-range-expander
814
- * @fileoverview Expands string index ranges within whitespace boundaries until letters are met
815
- * @version 2.0.16
816
- * @author Roy Revelt, Codsen Ltd
817
- * @license MIT
818
- * {@link https://codsen.com/os/string-range-expander/}
819
- */
820
- const defaults$1 = {
821
- str: "",
822
- from: 0,
823
- to: 0,
824
- ifLeftSideIncludesThisThenCropTightly: "",
825
- ifLeftSideIncludesThisCropItToo: "",
826
- ifRightSideIncludesThisThenCropTightly: "",
827
- ifRightSideIncludesThisCropItToo: "",
828
- extendToOneSide: false,
829
- wipeAllWhitespaceOnLeft: false,
830
- wipeAllWhitespaceOnRight: false,
831
- addSingleSpaceToPreventAccidentalConcatenation: false
832
- };
833
- function expander(originalOpts) {
834
- const letterOrDigit = /^[0-9a-zA-Z]+$/;
835
- function isWhitespace(char) {
836
- if (!char || typeof char !== "string") {
837
- return false;
838
- }
839
- return !char.trim();
840
- }
841
- function isStr(something) {
842
- return typeof something === "string";
843
- }
844
- if (!originalOpts || typeof originalOpts !== "object" || Array.isArray(originalOpts)) {
845
- let supplementalString;
846
- if (originalOpts === undefined) {
847
- supplementalString = "but it is missing completely.";
848
- } else if (originalOpts === null) {
849
- supplementalString = "but it was given as null.";
850
- } else {
851
- supplementalString = `but it was given as ${typeof originalOpts}, equal to:\n${JSON.stringify(originalOpts, null, 4)}.`;
852
- }
853
- throw new Error(`string-range-expander: [THROW_ID_01] Input must be a plain object ${supplementalString}`);
854
- } else if (typeof originalOpts === "object" && originalOpts !== null && !Array.isArray(originalOpts) && !Object.keys(originalOpts).length) {
855
- throw new Error(`string-range-expander: [THROW_ID_02] Input must be a plain object but it was given as a plain object without any keys.`);
856
- }
857
- if (typeof originalOpts.from !== "number") {
858
- throw new Error(`string-range-expander: [THROW_ID_03] The input's "from" value opts.from, is not a number! Currently it's given as ${typeof originalOpts.from}, equal to ${JSON.stringify(originalOpts.from, null, 0)}`);
859
- }
860
- if (typeof originalOpts.to !== "number") {
861
- throw new Error(`string-range-expander: [THROW_ID_04] The input's "to" value opts.to, is not a number! Currently it's given as ${typeof originalOpts.to}, equal to ${JSON.stringify(originalOpts.to, null, 0)}`);
862
- }
863
- if (originalOpts && originalOpts.str && !originalOpts.str[originalOpts.from] && originalOpts.from !== originalOpts.to) {
864
- throw new Error(`string-range-expander: [THROW_ID_05] The given input string opts.str ("${originalOpts.str}") must contain the character at index "from" ("${originalOpts.from}")`);
865
- }
866
- if (originalOpts && originalOpts.str && !originalOpts.str[originalOpts.to - 1]) {
867
- throw new Error(`string-range-expander: [THROW_ID_06] The given input string, opts.str ("${originalOpts.str}") must contain the character at index before "to" ("${originalOpts.to - 1}")`);
868
- }
869
- if (originalOpts.from > originalOpts.to) {
870
- throw new Error(`string-range-expander: [THROW_ID_07] The given "from" index, "${originalOpts.from}" is greater than "to" index, "${originalOpts.to}". That's wrong!`);
871
- }
872
- if (isStr(originalOpts.extendToOneSide) && originalOpts.extendToOneSide !== "left" && originalOpts.extendToOneSide !== "right" || !isStr(originalOpts.extendToOneSide) && originalOpts.extendToOneSide !== undefined && originalOpts.extendToOneSide !== false) {
873
- throw new Error(`string-range-expander: [THROW_ID_08] The opts.extendToOneSide value is not recogniseable! It's set to: "${originalOpts.extendToOneSide}" (${typeof originalOpts.extendToOneSide}). It has to be either Boolean "false" or strings "left" or "right"`);
874
- }
875
- const opts = { ...defaults$1,
876
- ...originalOpts
877
- };
878
- if (Array.isArray(opts.ifLeftSideIncludesThisThenCropTightly)) {
879
- let culpritsIndex;
880
- let culpritsValue;
881
- if (opts.ifLeftSideIncludesThisThenCropTightly.every((val, i) => {
882
- if (!isStr(val)) {
883
- culpritsIndex = i;
884
- culpritsValue = val;
885
- return false;
886
- }
887
- return true;
888
- })) {
889
- opts.ifLeftSideIncludesThisThenCropTightly = opts.ifLeftSideIncludesThisThenCropTightly.join("");
890
- } else {
891
- throw new Error(`string-range-expander: [THROW_ID_09] The opts.ifLeftSideIncludesThisThenCropTightly was set to an array:\n${JSON.stringify(opts.ifLeftSideIncludesThisThenCropTightly, null, 4)}. Now, that array contains not only string elements. For example, an element at index ${culpritsIndex} is of a type ${typeof culpritsValue} (equal to ${JSON.stringify(culpritsValue, null, 0)}).`);
892
- }
893
- }
894
- const str = opts.str;
895
- let from = opts.from;
896
- let to = opts.to;
897
- if (opts.extendToOneSide !== "right" && (isWhitespace(str[from - 1]) && (isWhitespace(str[from - 2]) || opts.ifLeftSideIncludesThisCropItToo.includes(str[from - 2])) || str[from - 1] && opts.ifLeftSideIncludesThisCropItToo.includes(str[from - 1]) || opts.wipeAllWhitespaceOnLeft && isWhitespace(str[from - 1]))) {
898
- for (let i = from; i--;) {
899
- if (!opts.ifLeftSideIncludesThisCropItToo.includes(str[i])) {
900
- if (str[i].trim()) {
901
- if (opts.wipeAllWhitespaceOnLeft || opts.ifLeftSideIncludesThisCropItToo.includes(str[i + 1])) {
902
- from = i + 1;
903
- } else {
904
- from = i + 2;
905
- }
906
- break;
907
- } else if (i === 0) {
908
- if (opts.wipeAllWhitespaceOnLeft) {
909
- from = 0;
910
- } else {
911
- from = 1;
912
- }
913
- break;
914
- }
915
- }
916
- }
917
- }
918
- if (opts.extendToOneSide !== "left" && (isWhitespace(str[to]) && (opts.wipeAllWhitespaceOnRight || isWhitespace(str[to + 1])) || opts.ifRightSideIncludesThisCropItToo.includes(str[to]))) {
919
- for (let i = to, len = str.length; i < len; i++) {
920
- if (!opts.ifRightSideIncludesThisCropItToo.includes(str[i]) && (str[i] && str[i].trim() || str[i] === undefined)) {
921
- if (opts.wipeAllWhitespaceOnRight || opts.ifRightSideIncludesThisCropItToo.includes(str[i - 1])) {
922
- to = i;
923
- } else {
924
- to = i - 1;
925
- }
926
- break;
927
- }
928
- }
929
- }
930
- if (opts.extendToOneSide !== "right" && isStr(opts.ifLeftSideIncludesThisThenCropTightly) && opts.ifLeftSideIncludesThisThenCropTightly && (str[from - 2] && opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 2]) || str[from - 1] && opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 1])) || opts.extendToOneSide !== "left" && isStr(opts.ifRightSideIncludesThisThenCropTightly) && opts.ifRightSideIncludesThisThenCropTightly && (str[to + 1] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to + 1]) || str[to] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to]))) {
931
- if (opts.extendToOneSide !== "right" && isWhitespace(str[from - 1]) && !opts.wipeAllWhitespaceOnLeft) {
932
- from -= 1;
933
- }
934
- if (opts.extendToOneSide !== "left" && isWhitespace(str[to]) && !opts.wipeAllWhitespaceOnRight) {
935
- to += 1;
936
- }
937
- }
938
- if (opts.addSingleSpaceToPreventAccidentalConcatenation && str[from - 1] && str[from - 1].trim() && str[to] && str[to].trim() && (!opts.ifLeftSideIncludesThisThenCropTightly && !opts.ifRightSideIncludesThisThenCropTightly || !((!opts.ifLeftSideIncludesThisThenCropTightly || opts.ifLeftSideIncludesThisThenCropTightly.includes(str[from - 1])) && (!opts.ifRightSideIncludesThisThenCropTightly || str[to] && opts.ifRightSideIncludesThisThenCropTightly.includes(str[to])))) && (letterOrDigit.test(str[from - 1]) || letterOrDigit.test(str[to]))) {
939
- return [from, to, " "];
940
- }
941
- return [from, to];
942
- }
943
-
944
- /**
945
- * lodash (Custom Build) <https://lodash.com/>
946
- * Build: `lodash modularize exports="npm" -o ./`
947
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
948
- * Released under MIT license <https://lodash.com/license>
949
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
950
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
951
- */
952
-
953
- /** Used for built-in method references. */
954
- var funcProto = Function.prototype;
955
-
956
- /** Used to resolve the decompiled source of functions. */
957
- var funcToString = funcProto.toString;
958
-
959
- /** Used to infer the `Object` constructor. */
960
- funcToString.call(Object);
961
-
962
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
963
-
964
- function createCommonjsModule(fn) {
965
- var module = { exports: {} };
966
- return fn(module, module.exports), module.exports;
967
- }
968
-
969
- /**
970
- * lodash (Custom Build) <https://lodash.com/>
971
- * Build: `lodash modularize exports="npm" -o ./`
972
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
973
- * Released under MIT license <https://lodash.com/license>
974
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
975
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
976
- */
977
-
978
- createCommonjsModule(function (module, exports) {
979
- /** Used as the size to enable large array optimizations. */
980
- var LARGE_ARRAY_SIZE = 200;
981
-
982
- /** Used to stand-in for `undefined` hash values. */
983
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
984
-
985
- /** Used as references for various `Number` constants. */
986
- var MAX_SAFE_INTEGER = 9007199254740991;
987
-
988
- /** `Object#toString` result references. */
989
- var argsTag = '[object Arguments]',
990
- arrayTag = '[object Array]',
991
- boolTag = '[object Boolean]',
992
- dateTag = '[object Date]',
993
- errorTag = '[object Error]',
994
- funcTag = '[object Function]',
995
- genTag = '[object GeneratorFunction]',
996
- mapTag = '[object Map]',
997
- numberTag = '[object Number]',
998
- objectTag = '[object Object]',
999
- promiseTag = '[object Promise]',
1000
- regexpTag = '[object RegExp]',
1001
- setTag = '[object Set]',
1002
- stringTag = '[object String]',
1003
- symbolTag = '[object Symbol]',
1004
- weakMapTag = '[object WeakMap]';
1005
-
1006
- var arrayBufferTag = '[object ArrayBuffer]',
1007
- dataViewTag = '[object DataView]',
1008
- float32Tag = '[object Float32Array]',
1009
- float64Tag = '[object Float64Array]',
1010
- int8Tag = '[object Int8Array]',
1011
- int16Tag = '[object Int16Array]',
1012
- int32Tag = '[object Int32Array]',
1013
- uint8Tag = '[object Uint8Array]',
1014
- uint8ClampedTag = '[object Uint8ClampedArray]',
1015
- uint16Tag = '[object Uint16Array]',
1016
- uint32Tag = '[object Uint32Array]';
1017
-
1018
- /**
1019
- * Used to match `RegExp`
1020
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
1021
- */
1022
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
1023
-
1024
- /** Used to match `RegExp` flags from their coerced string values. */
1025
- var reFlags = /\w*$/;
1026
-
1027
- /** Used to detect host constructors (Safari). */
1028
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
1029
-
1030
- /** Used to detect unsigned integer values. */
1031
- var reIsUint = /^(?:0|[1-9]\d*)$/;
1032
-
1033
- /** Used to identify `toStringTag` values supported by `_.clone`. */
1034
- var cloneableTags = {};
1035
- cloneableTags[argsTag] = cloneableTags[arrayTag] =
1036
- cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
1037
- cloneableTags[boolTag] = cloneableTags[dateTag] =
1038
- cloneableTags[float32Tag] = cloneableTags[float64Tag] =
1039
- cloneableTags[int8Tag] = cloneableTags[int16Tag] =
1040
- cloneableTags[int32Tag] = cloneableTags[mapTag] =
1041
- cloneableTags[numberTag] = cloneableTags[objectTag] =
1042
- cloneableTags[regexpTag] = cloneableTags[setTag] =
1043
- cloneableTags[stringTag] = cloneableTags[symbolTag] =
1044
- cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
1045
- cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
1046
- cloneableTags[errorTag] = cloneableTags[funcTag] =
1047
- cloneableTags[weakMapTag] = false;
1048
-
1049
- /** Detect free variable `global` from Node.js. */
1050
- var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
1051
-
1052
- /** Detect free variable `self`. */
1053
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
1054
-
1055
- /** Used as a reference to the global object. */
1056
- var root = freeGlobal || freeSelf || Function('return this')();
1057
-
1058
- /** Detect free variable `exports`. */
1059
- var freeExports = exports && !exports.nodeType && exports;
1060
-
1061
- /** Detect free variable `module`. */
1062
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
1063
-
1064
- /** Detect the popular CommonJS extension `module.exports`. */
1065
- var moduleExports = freeModule && freeModule.exports === freeExports;
1066
-
1067
- /**
1068
- * Adds the key-value `pair` to `map`.
1069
- *
1070
- * @private
1071
- * @param {Object} map The map to modify.
1072
- * @param {Array} pair The key-value pair to add.
1073
- * @returns {Object} Returns `map`.
1074
- */
1075
- function addMapEntry(map, pair) {
1076
- // Don't return `map.set` because it's not chainable in IE 11.
1077
- map.set(pair[0], pair[1]);
1078
- return map;
1079
- }
1080
-
1081
- /**
1082
- * Adds `value` to `set`.
1083
- *
1084
- * @private
1085
- * @param {Object} set The set to modify.
1086
- * @param {*} value The value to add.
1087
- * @returns {Object} Returns `set`.
1088
- */
1089
- function addSetEntry(set, value) {
1090
- // Don't return `set.add` because it's not chainable in IE 11.
1091
- set.add(value);
1092
- return set;
1093
- }
1094
-
1095
- /**
1096
- * A specialized version of `_.forEach` for arrays without support for
1097
- * iteratee shorthands.
1098
- *
1099
- * @private
1100
- * @param {Array} [array] The array to iterate over.
1101
- * @param {Function} iteratee The function invoked per iteration.
1102
- * @returns {Array} Returns `array`.
1103
- */
1104
- function arrayEach(array, iteratee) {
1105
- var index = -1,
1106
- length = array ? array.length : 0;
1107
-
1108
- while (++index < length) {
1109
- if (iteratee(array[index], index, array) === false) {
1110
- break;
1111
- }
1112
- }
1113
- return array;
1114
- }
1115
-
1116
- /**
1117
- * Appends the elements of `values` to `array`.
1118
- *
1119
- * @private
1120
- * @param {Array} array The array to modify.
1121
- * @param {Array} values The values to append.
1122
- * @returns {Array} Returns `array`.
1123
- */
1124
- function arrayPush(array, values) {
1125
- var index = -1,
1126
- length = values.length,
1127
- offset = array.length;
1128
-
1129
- while (++index < length) {
1130
- array[offset + index] = values[index];
1131
- }
1132
- return array;
1133
- }
1134
-
1135
- /**
1136
- * A specialized version of `_.reduce` for arrays without support for
1137
- * iteratee shorthands.
1138
- *
1139
- * @private
1140
- * @param {Array} [array] The array to iterate over.
1141
- * @param {Function} iteratee The function invoked per iteration.
1142
- * @param {*} [accumulator] The initial value.
1143
- * @param {boolean} [initAccum] Specify using the first element of `array` as
1144
- * the initial value.
1145
- * @returns {*} Returns the accumulated value.
1146
- */
1147
- function arrayReduce(array, iteratee, accumulator, initAccum) {
1148
- var index = -1,
1149
- length = array ? array.length : 0;
1150
-
1151
- if (initAccum && length) {
1152
- accumulator = array[++index];
1153
- }
1154
- while (++index < length) {
1155
- accumulator = iteratee(accumulator, array[index], index, array);
1156
- }
1157
- return accumulator;
1158
- }
1159
-
1160
- /**
1161
- * The base implementation of `_.times` without support for iteratee shorthands
1162
- * or max array length checks.
1163
- *
1164
- * @private
1165
- * @param {number} n The number of times to invoke `iteratee`.
1166
- * @param {Function} iteratee The function invoked per iteration.
1167
- * @returns {Array} Returns the array of results.
1168
- */
1169
- function baseTimes(n, iteratee) {
1170
- var index = -1,
1171
- result = Array(n);
1172
-
1173
- while (++index < n) {
1174
- result[index] = iteratee(index);
1175
- }
1176
- return result;
1177
- }
1178
-
1179
- /**
1180
- * Gets the value at `key` of `object`.
1181
- *
1182
- * @private
1183
- * @param {Object} [object] The object to query.
1184
- * @param {string} key The key of the property to get.
1185
- * @returns {*} Returns the property value.
1186
- */
1187
- function getValue(object, key) {
1188
- return object == null ? undefined : object[key];
1189
- }
1190
-
1191
- /**
1192
- * Checks if `value` is a host object in IE < 9.
1193
- *
1194
- * @private
1195
- * @param {*} value The value to check.
1196
- * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
1197
- */
1198
- function isHostObject(value) {
1199
- // Many host objects are `Object` objects that can coerce to strings
1200
- // despite having improperly defined `toString` methods.
1201
- var result = false;
1202
- if (value != null && typeof value.toString != 'function') {
1203
- try {
1204
- result = !!(value + '');
1205
- } catch (e) {}
1206
- }
1207
- return result;
1208
- }
1209
-
1210
- /**
1211
- * Converts `map` to its key-value pairs.
1212
- *
1213
- * @private
1214
- * @param {Object} map The map to convert.
1215
- * @returns {Array} Returns the key-value pairs.
1216
- */
1217
- function mapToArray(map) {
1218
- var index = -1,
1219
- result = Array(map.size);
1220
-
1221
- map.forEach(function(value, key) {
1222
- result[++index] = [key, value];
1223
- });
1224
- return result;
1225
- }
1226
-
1227
- /**
1228
- * Creates a unary function that invokes `func` with its argument transformed.
1229
- *
1230
- * @private
1231
- * @param {Function} func The function to wrap.
1232
- * @param {Function} transform The argument transform.
1233
- * @returns {Function} Returns the new function.
1234
- */
1235
- function overArg(func, transform) {
1236
- return function(arg) {
1237
- return func(transform(arg));
1238
- };
1239
- }
1240
-
1241
- /**
1242
- * Converts `set` to an array of its values.
1243
- *
1244
- * @private
1245
- * @param {Object} set The set to convert.
1246
- * @returns {Array} Returns the values.
1247
- */
1248
- function setToArray(set) {
1249
- var index = -1,
1250
- result = Array(set.size);
1251
-
1252
- set.forEach(function(value) {
1253
- result[++index] = value;
1254
- });
1255
- return result;
1256
- }
1257
-
1258
- /** Used for built-in method references. */
1259
- var arrayProto = Array.prototype,
1260
- funcProto = Function.prototype,
1261
- objectProto = Object.prototype;
1262
-
1263
- /** Used to detect overreaching core-js shims. */
1264
- var coreJsData = root['__core-js_shared__'];
1265
-
1266
- /** Used to detect methods masquerading as native. */
1267
- var maskSrcKey = (function() {
1268
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
1269
- return uid ? ('Symbol(src)_1.' + uid) : '';
1270
- }());
1271
-
1272
- /** Used to resolve the decompiled source of functions. */
1273
- var funcToString = funcProto.toString;
1274
-
1275
- /** Used to check objects for own properties. */
1276
- var hasOwnProperty = objectProto.hasOwnProperty;
1277
-
1278
- /**
1279
- * Used to resolve the
1280
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
1281
- * of values.
1282
- */
1283
- var objectToString = objectProto.toString;
1284
-
1285
- /** Used to detect if a method is native. */
1286
- var reIsNative = RegExp('^' +
1287
- funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
1288
- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
1289
- );
1290
-
1291
- /** Built-in value references. */
1292
- var Buffer = moduleExports ? root.Buffer : undefined,
1293
- Symbol = root.Symbol,
1294
- Uint8Array = root.Uint8Array,
1295
- getPrototype = overArg(Object.getPrototypeOf, Object),
1296
- objectCreate = Object.create,
1297
- propertyIsEnumerable = objectProto.propertyIsEnumerable,
1298
- splice = arrayProto.splice;
1299
-
1300
- /* Built-in method references for those with the same name as other `lodash` methods. */
1301
- var nativeGetSymbols = Object.getOwnPropertySymbols,
1302
- nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
1303
- nativeKeys = overArg(Object.keys, Object);
1304
-
1305
- /* Built-in method references that are verified to be native. */
1306
- var DataView = getNative(root, 'DataView'),
1307
- Map = getNative(root, 'Map'),
1308
- Promise = getNative(root, 'Promise'),
1309
- Set = getNative(root, 'Set'),
1310
- WeakMap = getNative(root, 'WeakMap'),
1311
- nativeCreate = getNative(Object, 'create');
1312
-
1313
- /** Used to detect maps, sets, and weakmaps. */
1314
- var dataViewCtorString = toSource(DataView),
1315
- mapCtorString = toSource(Map),
1316
- promiseCtorString = toSource(Promise),
1317
- setCtorString = toSource(Set),
1318
- weakMapCtorString = toSource(WeakMap);
1319
-
1320
- /** Used to convert symbols to primitives and strings. */
1321
- var symbolProto = Symbol ? Symbol.prototype : undefined,
1322
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
1323
-
1324
- /**
1325
- * Creates a hash object.
1326
- *
1327
- * @private
1328
- * @constructor
1329
- * @param {Array} [entries] The key-value pairs to cache.
1330
- */
1331
- function Hash(entries) {
1332
- var index = -1,
1333
- length = entries ? entries.length : 0;
1334
-
1335
- this.clear();
1336
- while (++index < length) {
1337
- var entry = entries[index];
1338
- this.set(entry[0], entry[1]);
1339
- }
1340
- }
1341
-
1342
- /**
1343
- * Removes all key-value entries from the hash.
1344
- *
1345
- * @private
1346
- * @name clear
1347
- * @memberOf Hash
1348
- */
1349
- function hashClear() {
1350
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
1351
- }
1352
-
1353
- /**
1354
- * Removes `key` and its value from the hash.
1355
- *
1356
- * @private
1357
- * @name delete
1358
- * @memberOf Hash
1359
- * @param {Object} hash The hash to modify.
1360
- * @param {string} key The key of the value to remove.
1361
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1362
- */
1363
- function hashDelete(key) {
1364
- return this.has(key) && delete this.__data__[key];
1365
- }
1366
-
1367
- /**
1368
- * Gets the hash value for `key`.
1369
- *
1370
- * @private
1371
- * @name get
1372
- * @memberOf Hash
1373
- * @param {string} key The key of the value to get.
1374
- * @returns {*} Returns the entry value.
1375
- */
1376
- function hashGet(key) {
1377
- var data = this.__data__;
1378
- if (nativeCreate) {
1379
- var result = data[key];
1380
- return result === HASH_UNDEFINED ? undefined : result;
1381
- }
1382
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
1383
- }
1384
-
1385
- /**
1386
- * Checks if a hash value for `key` exists.
1387
- *
1388
- * @private
1389
- * @name has
1390
- * @memberOf Hash
1391
- * @param {string} key The key of the entry to check.
1392
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1393
- */
1394
- function hashHas(key) {
1395
- var data = this.__data__;
1396
- return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
1397
- }
1398
-
1399
- /**
1400
- * Sets the hash `key` to `value`.
1401
- *
1402
- * @private
1403
- * @name set
1404
- * @memberOf Hash
1405
- * @param {string} key The key of the value to set.
1406
- * @param {*} value The value to set.
1407
- * @returns {Object} Returns the hash instance.
1408
- */
1409
- function hashSet(key, value) {
1410
- var data = this.__data__;
1411
- data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
1412
- return this;
1413
- }
1414
-
1415
- // Add methods to `Hash`.
1416
- Hash.prototype.clear = hashClear;
1417
- Hash.prototype['delete'] = hashDelete;
1418
- Hash.prototype.get = hashGet;
1419
- Hash.prototype.has = hashHas;
1420
- Hash.prototype.set = hashSet;
1421
-
1422
- /**
1423
- * Creates an list cache object.
1424
- *
1425
- * @private
1426
- * @constructor
1427
- * @param {Array} [entries] The key-value pairs to cache.
1428
- */
1429
- function ListCache(entries) {
1430
- var index = -1,
1431
- length = entries ? entries.length : 0;
1432
-
1433
- this.clear();
1434
- while (++index < length) {
1435
- var entry = entries[index];
1436
- this.set(entry[0], entry[1]);
1437
- }
1438
- }
1439
-
1440
- /**
1441
- * Removes all key-value entries from the list cache.
1442
- *
1443
- * @private
1444
- * @name clear
1445
- * @memberOf ListCache
1446
- */
1447
- function listCacheClear() {
1448
- this.__data__ = [];
1449
- }
1450
-
1451
- /**
1452
- * Removes `key` and its value from the list cache.
1453
- *
1454
- * @private
1455
- * @name delete
1456
- * @memberOf ListCache
1457
- * @param {string} key The key of the value to remove.
1458
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1459
- */
1460
- function listCacheDelete(key) {
1461
- var data = this.__data__,
1462
- index = assocIndexOf(data, key);
1463
-
1464
- if (index < 0) {
1465
- return false;
1466
- }
1467
- var lastIndex = data.length - 1;
1468
- if (index == lastIndex) {
1469
- data.pop();
1470
- } else {
1471
- splice.call(data, index, 1);
1472
- }
1473
- return true;
1474
- }
1475
-
1476
- /**
1477
- * Gets the list cache value for `key`.
1478
- *
1479
- * @private
1480
- * @name get
1481
- * @memberOf ListCache
1482
- * @param {string} key The key of the value to get.
1483
- * @returns {*} Returns the entry value.
1484
- */
1485
- function listCacheGet(key) {
1486
- var data = this.__data__,
1487
- index = assocIndexOf(data, key);
1488
-
1489
- return index < 0 ? undefined : data[index][1];
1490
- }
1491
-
1492
- /**
1493
- * Checks if a list cache value for `key` exists.
1494
- *
1495
- * @private
1496
- * @name has
1497
- * @memberOf ListCache
1498
- * @param {string} key The key of the entry to check.
1499
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1500
- */
1501
- function listCacheHas(key) {
1502
- return assocIndexOf(this.__data__, key) > -1;
1503
- }
1504
-
1505
- /**
1506
- * Sets the list cache `key` to `value`.
1507
- *
1508
- * @private
1509
- * @name set
1510
- * @memberOf ListCache
1511
- * @param {string} key The key of the value to set.
1512
- * @param {*} value The value to set.
1513
- * @returns {Object} Returns the list cache instance.
1514
- */
1515
- function listCacheSet(key, value) {
1516
- var data = this.__data__,
1517
- index = assocIndexOf(data, key);
1518
-
1519
- if (index < 0) {
1520
- data.push([key, value]);
1521
- } else {
1522
- data[index][1] = value;
1523
- }
1524
- return this;
1525
- }
1526
-
1527
- // Add methods to `ListCache`.
1528
- ListCache.prototype.clear = listCacheClear;
1529
- ListCache.prototype['delete'] = listCacheDelete;
1530
- ListCache.prototype.get = listCacheGet;
1531
- ListCache.prototype.has = listCacheHas;
1532
- ListCache.prototype.set = listCacheSet;
1533
-
1534
- /**
1535
- * Creates a map cache object to store key-value pairs.
1536
- *
1537
- * @private
1538
- * @constructor
1539
- * @param {Array} [entries] The key-value pairs to cache.
1540
- */
1541
- function MapCache(entries) {
1542
- var index = -1,
1543
- length = entries ? entries.length : 0;
1544
-
1545
- this.clear();
1546
- while (++index < length) {
1547
- var entry = entries[index];
1548
- this.set(entry[0], entry[1]);
1549
- }
1550
- }
1551
-
1552
- /**
1553
- * Removes all key-value entries from the map.
1554
- *
1555
- * @private
1556
- * @name clear
1557
- * @memberOf MapCache
1558
- */
1559
- function mapCacheClear() {
1560
- this.__data__ = {
1561
- 'hash': new Hash,
1562
- 'map': new (Map || ListCache),
1563
- 'string': new Hash
1564
- };
1565
- }
1566
-
1567
- /**
1568
- * Removes `key` and its value from the map.
1569
- *
1570
- * @private
1571
- * @name delete
1572
- * @memberOf MapCache
1573
- * @param {string} key The key of the value to remove.
1574
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1575
- */
1576
- function mapCacheDelete(key) {
1577
- return getMapData(this, key)['delete'](key);
1578
- }
1579
-
1580
- /**
1581
- * Gets the map value for `key`.
1582
- *
1583
- * @private
1584
- * @name get
1585
- * @memberOf MapCache
1586
- * @param {string} key The key of the value to get.
1587
- * @returns {*} Returns the entry value.
1588
- */
1589
- function mapCacheGet(key) {
1590
- return getMapData(this, key).get(key);
1591
- }
1592
-
1593
- /**
1594
- * Checks if a map value for `key` exists.
1595
- *
1596
- * @private
1597
- * @name has
1598
- * @memberOf MapCache
1599
- * @param {string} key The key of the entry to check.
1600
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1601
- */
1602
- function mapCacheHas(key) {
1603
- return getMapData(this, key).has(key);
1604
- }
1605
-
1606
- /**
1607
- * Sets the map `key` to `value`.
1608
- *
1609
- * @private
1610
- * @name set
1611
- * @memberOf MapCache
1612
- * @param {string} key The key of the value to set.
1613
- * @param {*} value The value to set.
1614
- * @returns {Object} Returns the map cache instance.
1615
- */
1616
- function mapCacheSet(key, value) {
1617
- getMapData(this, key).set(key, value);
1618
- return this;
1619
- }
1620
-
1621
- // Add methods to `MapCache`.
1622
- MapCache.prototype.clear = mapCacheClear;
1623
- MapCache.prototype['delete'] = mapCacheDelete;
1624
- MapCache.prototype.get = mapCacheGet;
1625
- MapCache.prototype.has = mapCacheHas;
1626
- MapCache.prototype.set = mapCacheSet;
1627
-
1628
- /**
1629
- * Creates a stack cache object to store key-value pairs.
1630
- *
1631
- * @private
1632
- * @constructor
1633
- * @param {Array} [entries] The key-value pairs to cache.
1634
- */
1635
- function Stack(entries) {
1636
- this.__data__ = new ListCache(entries);
1637
- }
1638
-
1639
- /**
1640
- * Removes all key-value entries from the stack.
1641
- *
1642
- * @private
1643
- * @name clear
1644
- * @memberOf Stack
1645
- */
1646
- function stackClear() {
1647
- this.__data__ = new ListCache;
1648
- }
1649
-
1650
- /**
1651
- * Removes `key` and its value from the stack.
1652
- *
1653
- * @private
1654
- * @name delete
1655
- * @memberOf Stack
1656
- * @param {string} key The key of the value to remove.
1657
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
1658
- */
1659
- function stackDelete(key) {
1660
- return this.__data__['delete'](key);
1661
- }
1662
-
1663
- /**
1664
- * Gets the stack value for `key`.
1665
- *
1666
- * @private
1667
- * @name get
1668
- * @memberOf Stack
1669
- * @param {string} key The key of the value to get.
1670
- * @returns {*} Returns the entry value.
1671
- */
1672
- function stackGet(key) {
1673
- return this.__data__.get(key);
1674
- }
1675
-
1676
- /**
1677
- * Checks if a stack value for `key` exists.
1678
- *
1679
- * @private
1680
- * @name has
1681
- * @memberOf Stack
1682
- * @param {string} key The key of the entry to check.
1683
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
1684
- */
1685
- function stackHas(key) {
1686
- return this.__data__.has(key);
1687
- }
1688
-
1689
- /**
1690
- * Sets the stack `key` to `value`.
1691
- *
1692
- * @private
1693
- * @name set
1694
- * @memberOf Stack
1695
- * @param {string} key The key of the value to set.
1696
- * @param {*} value The value to set.
1697
- * @returns {Object} Returns the stack cache instance.
1698
- */
1699
- function stackSet(key, value) {
1700
- var cache = this.__data__;
1701
- if (cache instanceof ListCache) {
1702
- var pairs = cache.__data__;
1703
- if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
1704
- pairs.push([key, value]);
1705
- return this;
1706
- }
1707
- cache = this.__data__ = new MapCache(pairs);
1708
- }
1709
- cache.set(key, value);
1710
- return this;
1711
- }
1712
-
1713
- // Add methods to `Stack`.
1714
- Stack.prototype.clear = stackClear;
1715
- Stack.prototype['delete'] = stackDelete;
1716
- Stack.prototype.get = stackGet;
1717
- Stack.prototype.has = stackHas;
1718
- Stack.prototype.set = stackSet;
1719
-
1720
- /**
1721
- * Creates an array of the enumerable property names of the array-like `value`.
1722
- *
1723
- * @private
1724
- * @param {*} value The value to query.
1725
- * @param {boolean} inherited Specify returning inherited property names.
1726
- * @returns {Array} Returns the array of property names.
1727
- */
1728
- function arrayLikeKeys(value, inherited) {
1729
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
1730
- // Safari 9 makes `arguments.length` enumerable in strict mode.
1731
- var result = (isArray(value) || isArguments(value))
1732
- ? baseTimes(value.length, String)
1733
- : [];
1734
-
1735
- var length = result.length,
1736
- skipIndexes = !!length;
1737
-
1738
- for (var key in value) {
1739
- if ((inherited || hasOwnProperty.call(value, key)) &&
1740
- !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
1741
- result.push(key);
1742
- }
1743
- }
1744
- return result;
1745
- }
1746
-
1747
- /**
1748
- * Assigns `value` to `key` of `object` if the existing value is not equivalent
1749
- * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
1750
- * for equality comparisons.
1751
- *
1752
- * @private
1753
- * @param {Object} object The object to modify.
1754
- * @param {string} key The key of the property to assign.
1755
- * @param {*} value The value to assign.
1756
- */
1757
- function assignValue(object, key, value) {
1758
- var objValue = object[key];
1759
- if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
1760
- (value === undefined && !(key in object))) {
1761
- object[key] = value;
1762
- }
1763
- }
1764
-
1765
- /**
1766
- * Gets the index at which the `key` is found in `array` of key-value pairs.
1767
- *
1768
- * @private
1769
- * @param {Array} array The array to inspect.
1770
- * @param {*} key The key to search for.
1771
- * @returns {number} Returns the index of the matched value, else `-1`.
1772
- */
1773
- function assocIndexOf(array, key) {
1774
- var length = array.length;
1775
- while (length--) {
1776
- if (eq(array[length][0], key)) {
1777
- return length;
1778
- }
1779
- }
1780
- return -1;
1781
- }
1782
-
1783
- /**
1784
- * The base implementation of `_.assign` without support for multiple sources
1785
- * or `customizer` functions.
1786
- *
1787
- * @private
1788
- * @param {Object} object The destination object.
1789
- * @param {Object} source The source object.
1790
- * @returns {Object} Returns `object`.
1791
- */
1792
- function baseAssign(object, source) {
1793
- return object && copyObject(source, keys(source), object);
1794
- }
1795
-
1796
- /**
1797
- * The base implementation of `_.clone` and `_.cloneDeep` which tracks
1798
- * traversed objects.
1799
- *
1800
- * @private
1801
- * @param {*} value The value to clone.
1802
- * @param {boolean} [isDeep] Specify a deep clone.
1803
- * @param {boolean} [isFull] Specify a clone including symbols.
1804
- * @param {Function} [customizer] The function to customize cloning.
1805
- * @param {string} [key] The key of `value`.
1806
- * @param {Object} [object] The parent object of `value`.
1807
- * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
1808
- * @returns {*} Returns the cloned value.
1809
- */
1810
- function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
1811
- var result;
1812
- if (customizer) {
1813
- result = object ? customizer(value, key, object, stack) : customizer(value);
1814
- }
1815
- if (result !== undefined) {
1816
- return result;
1817
- }
1818
- if (!isObject(value)) {
1819
- return value;
1820
- }
1821
- var isArr = isArray(value);
1822
- if (isArr) {
1823
- result = initCloneArray(value);
1824
- if (!isDeep) {
1825
- return copyArray(value, result);
1826
- }
1827
- } else {
1828
- var tag = getTag(value),
1829
- isFunc = tag == funcTag || tag == genTag;
1830
-
1831
- if (isBuffer(value)) {
1832
- return cloneBuffer(value, isDeep);
1833
- }
1834
- if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
1835
- if (isHostObject(value)) {
1836
- return object ? value : {};
1837
- }
1838
- result = initCloneObject(isFunc ? {} : value);
1839
- if (!isDeep) {
1840
- return copySymbols(value, baseAssign(result, value));
1841
- }
1842
- } else {
1843
- if (!cloneableTags[tag]) {
1844
- return object ? value : {};
1845
- }
1846
- result = initCloneByTag(value, tag, baseClone, isDeep);
1847
- }
1848
- }
1849
- // Check for circular references and return its corresponding clone.
1850
- stack || (stack = new Stack);
1851
- var stacked = stack.get(value);
1852
- if (stacked) {
1853
- return stacked;
1854
- }
1855
- stack.set(value, result);
1856
-
1857
- if (!isArr) {
1858
- var props = isFull ? getAllKeys(value) : keys(value);
1859
- }
1860
- arrayEach(props || value, function(subValue, key) {
1861
- if (props) {
1862
- key = subValue;
1863
- subValue = value[key];
1864
- }
1865
- // Recursively populate clone (susceptible to call stack limits).
1866
- assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
1867
- });
1868
- return result;
1869
- }
1870
-
1871
- /**
1872
- * The base implementation of `_.create` without support for assigning
1873
- * properties to the created object.
1874
- *
1875
- * @private
1876
- * @param {Object} prototype The object to inherit from.
1877
- * @returns {Object} Returns the new object.
1878
- */
1879
- function baseCreate(proto) {
1880
- return isObject(proto) ? objectCreate(proto) : {};
1881
- }
1882
-
1883
- /**
1884
- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
1885
- * `keysFunc` and `symbolsFunc` to get the enumerable property names and
1886
- * symbols of `object`.
1887
- *
1888
- * @private
1889
- * @param {Object} object The object to query.
1890
- * @param {Function} keysFunc The function to get the keys of `object`.
1891
- * @param {Function} symbolsFunc The function to get the symbols of `object`.
1892
- * @returns {Array} Returns the array of property names and symbols.
1893
- */
1894
- function baseGetAllKeys(object, keysFunc, symbolsFunc) {
1895
- var result = keysFunc(object);
1896
- return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
1897
- }
1898
-
1899
- /**
1900
- * The base implementation of `getTag`.
1901
- *
1902
- * @private
1903
- * @param {*} value The value to query.
1904
- * @returns {string} Returns the `toStringTag`.
1905
- */
1906
- function baseGetTag(value) {
1907
- return objectToString.call(value);
1908
- }
1909
-
1910
- /**
1911
- * The base implementation of `_.isNative` without bad shim checks.
1912
- *
1913
- * @private
1914
- * @param {*} value The value to check.
1915
- * @returns {boolean} Returns `true` if `value` is a native function,
1916
- * else `false`.
1917
- */
1918
- function baseIsNative(value) {
1919
- if (!isObject(value) || isMasked(value)) {
1920
- return false;
1921
- }
1922
- var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
1923
- return pattern.test(toSource(value));
1924
- }
1925
-
1926
- /**
1927
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
1928
- *
1929
- * @private
1930
- * @param {Object} object The object to query.
1931
- * @returns {Array} Returns the array of property names.
1932
- */
1933
- function baseKeys(object) {
1934
- if (!isPrototype(object)) {
1935
- return nativeKeys(object);
1936
- }
1937
- var result = [];
1938
- for (var key in Object(object)) {
1939
- if (hasOwnProperty.call(object, key) && key != 'constructor') {
1940
- result.push(key);
1941
- }
1942
- }
1943
- return result;
1944
- }
1945
-
1946
- /**
1947
- * Creates a clone of `buffer`.
1948
- *
1949
- * @private
1950
- * @param {Buffer} buffer The buffer to clone.
1951
- * @param {boolean} [isDeep] Specify a deep clone.
1952
- * @returns {Buffer} Returns the cloned buffer.
1953
- */
1954
- function cloneBuffer(buffer, isDeep) {
1955
- if (isDeep) {
1956
- return buffer.slice();
1957
- }
1958
- var result = new buffer.constructor(buffer.length);
1959
- buffer.copy(result);
1960
- return result;
1961
- }
1962
-
1963
- /**
1964
- * Creates a clone of `arrayBuffer`.
1965
- *
1966
- * @private
1967
- * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
1968
- * @returns {ArrayBuffer} Returns the cloned array buffer.
1969
- */
1970
- function cloneArrayBuffer(arrayBuffer) {
1971
- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
1972
- new Uint8Array(result).set(new Uint8Array(arrayBuffer));
1973
- return result;
1974
- }
1975
-
1976
- /**
1977
- * Creates a clone of `dataView`.
1978
- *
1979
- * @private
1980
- * @param {Object} dataView The data view to clone.
1981
- * @param {boolean} [isDeep] Specify a deep clone.
1982
- * @returns {Object} Returns the cloned data view.
1983
- */
1984
- function cloneDataView(dataView, isDeep) {
1985
- var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
1986
- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
1987
- }
1988
-
1989
- /**
1990
- * Creates a clone of `map`.
1991
- *
1992
- * @private
1993
- * @param {Object} map The map to clone.
1994
- * @param {Function} cloneFunc The function to clone values.
1995
- * @param {boolean} [isDeep] Specify a deep clone.
1996
- * @returns {Object} Returns the cloned map.
1997
- */
1998
- function cloneMap(map, isDeep, cloneFunc) {
1999
- var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
2000
- return arrayReduce(array, addMapEntry, new map.constructor);
2001
- }
2002
-
2003
- /**
2004
- * Creates a clone of `regexp`.
2005
- *
2006
- * @private
2007
- * @param {Object} regexp The regexp to clone.
2008
- * @returns {Object} Returns the cloned regexp.
2009
- */
2010
- function cloneRegExp(regexp) {
2011
- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
2012
- result.lastIndex = regexp.lastIndex;
2013
- return result;
2014
- }
2015
-
2016
- /**
2017
- * Creates a clone of `set`.
2018
- *
2019
- * @private
2020
- * @param {Object} set The set to clone.
2021
- * @param {Function} cloneFunc The function to clone values.
2022
- * @param {boolean} [isDeep] Specify a deep clone.
2023
- * @returns {Object} Returns the cloned set.
2024
- */
2025
- function cloneSet(set, isDeep, cloneFunc) {
2026
- var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
2027
- return arrayReduce(array, addSetEntry, new set.constructor);
2028
- }
2029
-
2030
- /**
2031
- * Creates a clone of the `symbol` object.
2032
- *
2033
- * @private
2034
- * @param {Object} symbol The symbol object to clone.
2035
- * @returns {Object} Returns the cloned symbol object.
2036
- */
2037
- function cloneSymbol(symbol) {
2038
- return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
2039
- }
2040
-
2041
- /**
2042
- * Creates a clone of `typedArray`.
2043
- *
2044
- * @private
2045
- * @param {Object} typedArray The typed array to clone.
2046
- * @param {boolean} [isDeep] Specify a deep clone.
2047
- * @returns {Object} Returns the cloned typed array.
2048
- */
2049
- function cloneTypedArray(typedArray, isDeep) {
2050
- var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
2051
- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
2052
- }
2053
-
2054
- /**
2055
- * Copies the values of `source` to `array`.
2056
- *
2057
- * @private
2058
- * @param {Array} source The array to copy values from.
2059
- * @param {Array} [array=[]] The array to copy values to.
2060
- * @returns {Array} Returns `array`.
2061
- */
2062
- function copyArray(source, array) {
2063
- var index = -1,
2064
- length = source.length;
2065
-
2066
- array || (array = Array(length));
2067
- while (++index < length) {
2068
- array[index] = source[index];
2069
- }
2070
- return array;
2071
- }
2072
-
2073
- /**
2074
- * Copies properties of `source` to `object`.
2075
- *
2076
- * @private
2077
- * @param {Object} source The object to copy properties from.
2078
- * @param {Array} props The property identifiers to copy.
2079
- * @param {Object} [object={}] The object to copy properties to.
2080
- * @param {Function} [customizer] The function to customize copied values.
2081
- * @returns {Object} Returns `object`.
2082
- */
2083
- function copyObject(source, props, object, customizer) {
2084
- object || (object = {});
2085
-
2086
- var index = -1,
2087
- length = props.length;
2088
-
2089
- while (++index < length) {
2090
- var key = props[index];
2091
-
2092
- var newValue = customizer
2093
- ? customizer(object[key], source[key], key, object, source)
2094
- : undefined;
2095
-
2096
- assignValue(object, key, newValue === undefined ? source[key] : newValue);
2097
- }
2098
- return object;
2099
- }
2100
-
2101
- /**
2102
- * Copies own symbol properties of `source` to `object`.
2103
- *
2104
- * @private
2105
- * @param {Object} source The object to copy symbols from.
2106
- * @param {Object} [object={}] The object to copy symbols to.
2107
- * @returns {Object} Returns `object`.
2108
- */
2109
- function copySymbols(source, object) {
2110
- return copyObject(source, getSymbols(source), object);
2111
- }
2112
-
2113
- /**
2114
- * Creates an array of own enumerable property names and symbols of `object`.
2115
- *
2116
- * @private
2117
- * @param {Object} object The object to query.
2118
- * @returns {Array} Returns the array of property names and symbols.
2119
- */
2120
- function getAllKeys(object) {
2121
- return baseGetAllKeys(object, keys, getSymbols);
2122
- }
2123
-
2124
- /**
2125
- * Gets the data for `map`.
2126
- *
2127
- * @private
2128
- * @param {Object} map The map to query.
2129
- * @param {string} key The reference key.
2130
- * @returns {*} Returns the map data.
2131
- */
2132
- function getMapData(map, key) {
2133
- var data = map.__data__;
2134
- return isKeyable(key)
2135
- ? data[typeof key == 'string' ? 'string' : 'hash']
2136
- : data.map;
2137
- }
2138
-
2139
- /**
2140
- * Gets the native function at `key` of `object`.
2141
- *
2142
- * @private
2143
- * @param {Object} object The object to query.
2144
- * @param {string} key The key of the method to get.
2145
- * @returns {*} Returns the function if it's native, else `undefined`.
2146
- */
2147
- function getNative(object, key) {
2148
- var value = getValue(object, key);
2149
- return baseIsNative(value) ? value : undefined;
2150
- }
2151
-
2152
- /**
2153
- * Creates an array of the own enumerable symbol properties of `object`.
2154
- *
2155
- * @private
2156
- * @param {Object} object The object to query.
2157
- * @returns {Array} Returns the array of symbols.
2158
- */
2159
- var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
2160
-
2161
- /**
2162
- * Gets the `toStringTag` of `value`.
2163
- *
2164
- * @private
2165
- * @param {*} value The value to query.
2166
- * @returns {string} Returns the `toStringTag`.
2167
- */
2168
- var getTag = baseGetTag;
2169
-
2170
- // Fallback for data views, maps, sets, and weak maps in IE 11,
2171
- // for data views in Edge < 14, and promises in Node.js.
2172
- if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
2173
- (Map && getTag(new Map) != mapTag) ||
2174
- (Promise && getTag(Promise.resolve()) != promiseTag) ||
2175
- (Set && getTag(new Set) != setTag) ||
2176
- (WeakMap && getTag(new WeakMap) != weakMapTag)) {
2177
- getTag = function(value) {
2178
- var result = objectToString.call(value),
2179
- Ctor = result == objectTag ? value.constructor : undefined,
2180
- ctorString = Ctor ? toSource(Ctor) : undefined;
2181
-
2182
- if (ctorString) {
2183
- switch (ctorString) {
2184
- case dataViewCtorString: return dataViewTag;
2185
- case mapCtorString: return mapTag;
2186
- case promiseCtorString: return promiseTag;
2187
- case setCtorString: return setTag;
2188
- case weakMapCtorString: return weakMapTag;
2189
- }
2190
- }
2191
- return result;
2192
- };
2193
- }
2194
-
2195
- /**
2196
- * Initializes an array clone.
2197
- *
2198
- * @private
2199
- * @param {Array} array The array to clone.
2200
- * @returns {Array} Returns the initialized clone.
2201
- */
2202
- function initCloneArray(array) {
2203
- var length = array.length,
2204
- result = array.constructor(length);
2205
-
2206
- // Add properties assigned by `RegExp#exec`.
2207
- if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
2208
- result.index = array.index;
2209
- result.input = array.input;
2210
- }
2211
- return result;
2212
- }
2213
-
2214
- /**
2215
- * Initializes an object clone.
2216
- *
2217
- * @private
2218
- * @param {Object} object The object to clone.
2219
- * @returns {Object} Returns the initialized clone.
2220
- */
2221
- function initCloneObject(object) {
2222
- return (typeof object.constructor == 'function' && !isPrototype(object))
2223
- ? baseCreate(getPrototype(object))
2224
- : {};
2225
- }
2226
-
2227
- /**
2228
- * Initializes an object clone based on its `toStringTag`.
2229
- *
2230
- * **Note:** This function only supports cloning values with tags of
2231
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
2232
- *
2233
- * @private
2234
- * @param {Object} object The object to clone.
2235
- * @param {string} tag The `toStringTag` of the object to clone.
2236
- * @param {Function} cloneFunc The function to clone values.
2237
- * @param {boolean} [isDeep] Specify a deep clone.
2238
- * @returns {Object} Returns the initialized clone.
2239
- */
2240
- function initCloneByTag(object, tag, cloneFunc, isDeep) {
2241
- var Ctor = object.constructor;
2242
- switch (tag) {
2243
- case arrayBufferTag:
2244
- return cloneArrayBuffer(object);
2245
-
2246
- case boolTag:
2247
- case dateTag:
2248
- return new Ctor(+object);
2249
-
2250
- case dataViewTag:
2251
- return cloneDataView(object, isDeep);
2252
-
2253
- case float32Tag: case float64Tag:
2254
- case int8Tag: case int16Tag: case int32Tag:
2255
- case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
2256
- return cloneTypedArray(object, isDeep);
2257
-
2258
- case mapTag:
2259
- return cloneMap(object, isDeep, cloneFunc);
2260
-
2261
- case numberTag:
2262
- case stringTag:
2263
- return new Ctor(object);
2264
-
2265
- case regexpTag:
2266
- return cloneRegExp(object);
2267
-
2268
- case setTag:
2269
- return cloneSet(object, isDeep, cloneFunc);
2270
-
2271
- case symbolTag:
2272
- return cloneSymbol(object);
2273
- }
2274
- }
2275
-
2276
- /**
2277
- * Checks if `value` is a valid array-like index.
2278
- *
2279
- * @private
2280
- * @param {*} value The value to check.
2281
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
2282
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
2283
- */
2284
- function isIndex(value, length) {
2285
- length = length == null ? MAX_SAFE_INTEGER : length;
2286
- return !!length &&
2287
- (typeof value == 'number' || reIsUint.test(value)) &&
2288
- (value > -1 && value % 1 == 0 && value < length);
2289
- }
2290
-
2291
- /**
2292
- * Checks if `value` is suitable for use as unique object key.
2293
- *
2294
- * @private
2295
- * @param {*} value The value to check.
2296
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
2297
- */
2298
- function isKeyable(value) {
2299
- var type = typeof value;
2300
- return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
2301
- ? (value !== '__proto__')
2302
- : (value === null);
2303
- }
2304
-
2305
- /**
2306
- * Checks if `func` has its source masked.
2307
- *
2308
- * @private
2309
- * @param {Function} func The function to check.
2310
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
2311
- */
2312
- function isMasked(func) {
2313
- return !!maskSrcKey && (maskSrcKey in func);
2314
- }
2315
-
2316
- /**
2317
- * Checks if `value` is likely a prototype object.
2318
- *
2319
- * @private
2320
- * @param {*} value The value to check.
2321
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
2322
- */
2323
- function isPrototype(value) {
2324
- var Ctor = value && value.constructor,
2325
- proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
2326
-
2327
- return value === proto;
2328
- }
2329
-
2330
- /**
2331
- * Converts `func` to its source code.
2332
- *
2333
- * @private
2334
- * @param {Function} func The function to process.
2335
- * @returns {string} Returns the source code.
2336
- */
2337
- function toSource(func) {
2338
- if (func != null) {
2339
- try {
2340
- return funcToString.call(func);
2341
- } catch (e) {}
2342
- try {
2343
- return (func + '');
2344
- } catch (e) {}
2345
- }
2346
- return '';
2347
- }
2348
-
2349
- /**
2350
- * This method is like `_.clone` except that it recursively clones `value`.
2351
- *
2352
- * @static
2353
- * @memberOf _
2354
- * @since 1.0.0
2355
- * @category Lang
2356
- * @param {*} value The value to recursively clone.
2357
- * @returns {*} Returns the deep cloned value.
2358
- * @see _.clone
2359
- * @example
2360
- *
2361
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
2362
- *
2363
- * var deep = _.cloneDeep(objects);
2364
- * console.log(deep[0] === objects[0]);
2365
- * // => false
2366
- */
2367
- function cloneDeep(value) {
2368
- return baseClone(value, true, true);
2369
- }
2370
-
2371
- /**
2372
- * Performs a
2373
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2374
- * comparison between two values to determine if they are equivalent.
2375
- *
2376
- * @static
2377
- * @memberOf _
2378
- * @since 4.0.0
2379
- * @category Lang
2380
- * @param {*} value The value to compare.
2381
- * @param {*} other The other value to compare.
2382
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2383
- * @example
2384
- *
2385
- * var object = { 'a': 1 };
2386
- * var other = { 'a': 1 };
2387
- *
2388
- * _.eq(object, object);
2389
- * // => true
2390
- *
2391
- * _.eq(object, other);
2392
- * // => false
2393
- *
2394
- * _.eq('a', 'a');
2395
- * // => true
2396
- *
2397
- * _.eq('a', Object('a'));
2398
- * // => false
2399
- *
2400
- * _.eq(NaN, NaN);
2401
- * // => true
2402
- */
2403
- function eq(value, other) {
2404
- return value === other || (value !== value && other !== other);
2405
- }
2406
-
2407
- /**
2408
- * Checks if `value` is likely an `arguments` object.
2409
- *
2410
- * @static
2411
- * @memberOf _
2412
- * @since 0.1.0
2413
- * @category Lang
2414
- * @param {*} value The value to check.
2415
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
2416
- * else `false`.
2417
- * @example
2418
- *
2419
- * _.isArguments(function() { return arguments; }());
2420
- * // => true
2421
- *
2422
- * _.isArguments([1, 2, 3]);
2423
- * // => false
2424
- */
2425
- function isArguments(value) {
2426
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
2427
- return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
2428
- (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
2429
- }
2430
-
2431
- /**
2432
- * Checks if `value` is classified as an `Array` object.
2433
- *
2434
- * @static
2435
- * @memberOf _
2436
- * @since 0.1.0
2437
- * @category Lang
2438
- * @param {*} value The value to check.
2439
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
2440
- * @example
2441
- *
2442
- * _.isArray([1, 2, 3]);
2443
- * // => true
2444
- *
2445
- * _.isArray(document.body.children);
2446
- * // => false
2447
- *
2448
- * _.isArray('abc');
2449
- * // => false
2450
- *
2451
- * _.isArray(_.noop);
2452
- * // => false
2453
- */
2454
- var isArray = Array.isArray;
2455
-
2456
- /**
2457
- * Checks if `value` is array-like. A value is considered array-like if it's
2458
- * not a function and has a `value.length` that's an integer greater than or
2459
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
2460
- *
2461
- * @static
2462
- * @memberOf _
2463
- * @since 4.0.0
2464
- * @category Lang
2465
- * @param {*} value The value to check.
2466
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
2467
- * @example
2468
- *
2469
- * _.isArrayLike([1, 2, 3]);
2470
- * // => true
2471
- *
2472
- * _.isArrayLike(document.body.children);
2473
- * // => true
2474
- *
2475
- * _.isArrayLike('abc');
2476
- * // => true
2477
- *
2478
- * _.isArrayLike(_.noop);
2479
- * // => false
2480
- */
2481
- function isArrayLike(value) {
2482
- return value != null && isLength(value.length) && !isFunction(value);
2483
- }
2484
-
2485
- /**
2486
- * This method is like `_.isArrayLike` except that it also checks if `value`
2487
- * is an object.
2488
- *
2489
- * @static
2490
- * @memberOf _
2491
- * @since 4.0.0
2492
- * @category Lang
2493
- * @param {*} value The value to check.
2494
- * @returns {boolean} Returns `true` if `value` is an array-like object,
2495
- * else `false`.
2496
- * @example
2497
- *
2498
- * _.isArrayLikeObject([1, 2, 3]);
2499
- * // => true
2500
- *
2501
- * _.isArrayLikeObject(document.body.children);
2502
- * // => true
2503
- *
2504
- * _.isArrayLikeObject('abc');
2505
- * // => false
2506
- *
2507
- * _.isArrayLikeObject(_.noop);
2508
- * // => false
2509
- */
2510
- function isArrayLikeObject(value) {
2511
- return isObjectLike(value) && isArrayLike(value);
2512
- }
2513
-
2514
- /**
2515
- * Checks if `value` is a buffer.
2516
- *
2517
- * @static
2518
- * @memberOf _
2519
- * @since 4.3.0
2520
- * @category Lang
2521
- * @param {*} value The value to check.
2522
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
2523
- * @example
2524
- *
2525
- * _.isBuffer(new Buffer(2));
2526
- * // => true
2527
- *
2528
- * _.isBuffer(new Uint8Array(2));
2529
- * // => false
2530
- */
2531
- var isBuffer = nativeIsBuffer || stubFalse;
2532
-
2533
- /**
2534
- * Checks if `value` is classified as a `Function` object.
2535
- *
2536
- * @static
2537
- * @memberOf _
2538
- * @since 0.1.0
2539
- * @category Lang
2540
- * @param {*} value The value to check.
2541
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
2542
- * @example
2543
- *
2544
- * _.isFunction(_);
2545
- * // => true
2546
- *
2547
- * _.isFunction(/abc/);
2548
- * // => false
2549
- */
2550
- function isFunction(value) {
2551
- // The use of `Object#toString` avoids issues with the `typeof` operator
2552
- // in Safari 8-9 which returns 'object' for typed array and other constructors.
2553
- var tag = isObject(value) ? objectToString.call(value) : '';
2554
- return tag == funcTag || tag == genTag;
2555
- }
2556
-
2557
- /**
2558
- * Checks if `value` is a valid array-like length.
2559
- *
2560
- * **Note:** This method is loosely based on
2561
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
2562
- *
2563
- * @static
2564
- * @memberOf _
2565
- * @since 4.0.0
2566
- * @category Lang
2567
- * @param {*} value The value to check.
2568
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
2569
- * @example
2570
- *
2571
- * _.isLength(3);
2572
- * // => true
2573
- *
2574
- * _.isLength(Number.MIN_VALUE);
2575
- * // => false
2576
- *
2577
- * _.isLength(Infinity);
2578
- * // => false
2579
- *
2580
- * _.isLength('3');
2581
- * // => false
2582
- */
2583
- function isLength(value) {
2584
- return typeof value == 'number' &&
2585
- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
2586
- }
2587
-
2588
- /**
2589
- * Checks if `value` is the
2590
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
2591
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
2592
- *
2593
- * @static
2594
- * @memberOf _
2595
- * @since 0.1.0
2596
- * @category Lang
2597
- * @param {*} value The value to check.
2598
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
2599
- * @example
2600
- *
2601
- * _.isObject({});
2602
- * // => true
2603
- *
2604
- * _.isObject([1, 2, 3]);
2605
- * // => true
2606
- *
2607
- * _.isObject(_.noop);
2608
- * // => true
2609
- *
2610
- * _.isObject(null);
2611
- * // => false
2612
- */
2613
- function isObject(value) {
2614
- var type = typeof value;
2615
- return !!value && (type == 'object' || type == 'function');
2616
- }
2617
-
2618
- /**
2619
- * Checks if `value` is object-like. A value is object-like if it's not `null`
2620
- * and has a `typeof` result of "object".
2621
- *
2622
- * @static
2623
- * @memberOf _
2624
- * @since 4.0.0
2625
- * @category Lang
2626
- * @param {*} value The value to check.
2627
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
2628
- * @example
2629
- *
2630
- * _.isObjectLike({});
2631
- * // => true
2632
- *
2633
- * _.isObjectLike([1, 2, 3]);
2634
- * // => true
2635
- *
2636
- * _.isObjectLike(_.noop);
2637
- * // => false
2638
- *
2639
- * _.isObjectLike(null);
2640
- * // => false
2641
- */
2642
- function isObjectLike(value) {
2643
- return !!value && typeof value == 'object';
2644
- }
2645
-
2646
- /**
2647
- * Creates an array of the own enumerable property names of `object`.
2648
- *
2649
- * **Note:** Non-object values are coerced to objects. See the
2650
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
2651
- * for more details.
2652
- *
2653
- * @static
2654
- * @since 0.1.0
2655
- * @memberOf _
2656
- * @category Object
2657
- * @param {Object} object The object to query.
2658
- * @returns {Array} Returns the array of property names.
2659
- * @example
2660
- *
2661
- * function Foo() {
2662
- * this.a = 1;
2663
- * this.b = 2;
2664
- * }
2665
- *
2666
- * Foo.prototype.c = 3;
2667
- *
2668
- * _.keys(new Foo);
2669
- * // => ['a', 'b'] (iteration order is not guaranteed)
2670
- *
2671
- * _.keys('hi');
2672
- * // => ['0', '1']
2673
- */
2674
- function keys(object) {
2675
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
2676
- }
2677
-
2678
- /**
2679
- * This method returns a new empty array.
2680
- *
2681
- * @static
2682
- * @memberOf _
2683
- * @since 4.13.0
2684
- * @category Util
2685
- * @returns {Array} Returns the new empty array.
2686
- * @example
2687
- *
2688
- * var arrays = _.times(2, _.stubArray);
2689
- *
2690
- * console.log(arrays);
2691
- * // => [[], []]
2692
- *
2693
- * console.log(arrays[0] === arrays[1]);
2694
- * // => false
2695
- */
2696
- function stubArray() {
2697
- return [];
2698
- }
2699
-
2700
- /**
2701
- * This method returns `false`.
2702
- *
2703
- * @static
2704
- * @memberOf _
2705
- * @since 4.13.0
2706
- * @category Util
2707
- * @returns {boolean} Returns `false`.
2708
- * @example
2709
- *
2710
- * _.times(2, _.stubFalse);
2711
- * // => [false, false]
2712
- */
2713
- function stubFalse() {
2714
- return false;
2715
- }
2716
-
2717
- module.exports = cloneDeep;
2718
- });
2719
-
2720
- /**
2721
- * @name string-left-right
2722
- * @fileoverview Looks up the first non-whitespace character to the left/right of a given index
2723
- * @version 4.0.16
2724
- * @author Roy Revelt, Codsen Ltd
2725
- * @license MIT
2726
- * {@link https://codsen.com/os/string-left-right/}
2727
- */
2728
- const RAWNBSP = "\u00A0";
2729
- function rightMain({
2730
- str,
2731
- idx = 0,
2732
- stopAtNewlines = false,
2733
- stopAtRawNbsp = false
2734
- }) {
2735
- if (typeof str !== "string" || !str.length) {
2736
- return null;
2737
- }
2738
- if (!idx || typeof idx !== "number") {
2739
- idx = 0;
2740
- }
2741
- if (!str[idx + 1]) {
2742
- return null;
2743
- }
2744
- if (
2745
- str[idx + 1] && (
2746
- str[idx + 1].trim() ||
2747
- stopAtNewlines &&
2748
- "\n\r".includes(str[idx + 1]) ||
2749
- stopAtRawNbsp &&
2750
- str[idx + 1] === RAWNBSP)) {
2751
- return idx + 1;
2752
- }
2753
- if (
2754
- str[idx + 2] && (
2755
- str[idx + 2].trim() ||
2756
- stopAtNewlines &&
2757
- "\n\r".includes(str[idx + 2]) ||
2758
- stopAtRawNbsp &&
2759
- str[idx + 2] === RAWNBSP)) {
2760
- return idx + 2;
2761
- }
2762
- for (let i = idx + 1, len = str.length; i < len; i++) {
2763
- if (
2764
- str[i].trim() ||
2765
- stopAtNewlines &&
2766
- "\n\r".includes(str[i]) ||
2767
- stopAtRawNbsp &&
2768
- str[i] === RAWNBSP) {
2769
- return i;
2770
- }
2771
- }
2772
- return null;
2773
- }
2774
- function right(str, idx = 0) {
2775
- return rightMain({
2776
- str,
2777
- idx,
2778
- stopAtNewlines: false,
2779
- stopAtRawNbsp: false
2780
- });
2781
- }
2782
- function leftMain({
2783
- str,
2784
- idx,
2785
- stopAtNewlines,
2786
- stopAtRawNbsp
2787
- }) {
2788
- if (typeof str !== "string" || !str.length) {
2789
- return null;
2790
- }
2791
- if (!idx || typeof idx !== "number") {
2792
- idx = 0;
2793
- }
2794
- if (idx < 1) {
2795
- return null;
2796
- }
2797
- if (
2798
- str[~-idx] && (
2799
- str[~-idx].trim() ||
2800
- stopAtNewlines &&
2801
- "\n\r".includes(str[~-idx]) ||
2802
- stopAtRawNbsp &&
2803
- str[~-idx] === RAWNBSP)) {
2804
- return ~-idx;
2805
- }
2806
- if (
2807
- str[idx - 2] && (
2808
- str[idx - 2].trim() ||
2809
- stopAtNewlines &&
2810
- "\n\r".includes(str[idx - 2]) ||
2811
- stopAtRawNbsp &&
2812
- str[idx - 2] === RAWNBSP)) {
2813
- return idx - 2;
2814
- }
2815
- for (let i = idx; i--;) {
2816
- if (str[i] && (
2817
- str[i].trim() ||
2818
- stopAtNewlines &&
2819
- "\n\r".includes(str[i]) ||
2820
- stopAtRawNbsp &&
2821
- str[i] === RAWNBSP)) {
2822
- return i;
2823
- }
2824
- }
2825
- return null;
2826
- }
2827
- function left(str, idx = 0) {
2828
- return leftMain({
2829
- str,
2830
- idx,
2831
- stopAtNewlines: false,
2832
- stopAtRawNbsp: false
2833
- });
2834
- }
2835
-
2836
- var version$1 = "4.1.10";
2837
-
2838
- const version = version$1;
2839
- const finalIndexesToDelete = new Ranges({ limitToBeAddedWhitespace: true });
2840
- const defaults = {
2841
- lineLengthLimit: 500,
2842
- removeIndentations: true,
2843
- removeLineBreaks: false,
2844
- removeHTMLComments: false,
2845
- removeCSSComments: true,
2846
- reportProgressFunc: null,
2847
- reportProgressFuncFrom: 0,
2848
- reportProgressFuncTo: 100,
2849
- breakToTheLeftOf: [
2850
- "</td",
2851
- "<html",
2852
- "</html",
2853
- "<head",
2854
- "</head",
2855
- "<meta",
2856
- "<link",
2857
- "<table",
2858
- "<script",
2859
- "</script",
2860
- "<!DOCTYPE",
2861
- "<style",
2862
- "</style",
2863
- "<title",
2864
- "<body",
2865
- "@media",
2866
- "</body",
2867
- "<!--[if",
2868
- "<!--<![endif",
2869
- "<![endif]",
2870
- ],
2871
- mindTheInlineTags: [
2872
- "a",
2873
- "abbr",
2874
- "acronym",
2875
- "audio",
2876
- "b",
2877
- "bdi",
2878
- "bdo",
2879
- "big",
2880
- "br",
2881
- "button",
2882
- "canvas",
2883
- "cite",
2884
- "code",
2885
- "data",
2886
- "datalist",
2887
- "del",
2888
- "dfn",
2889
- "em",
2890
- "embed",
2891
- "i",
2892
- "iframe",
2893
- "img",
2894
- "input",
2895
- "ins",
2896
- "kbd",
2897
- "label",
2898
- "map",
2899
- "mark",
2900
- "meter",
2901
- "noscript",
2902
- "object",
2903
- "output",
2904
- "picture",
2905
- "progress",
2906
- "q",
2907
- "ruby",
2908
- "s",
2909
- "samp",
2910
- "script",
2911
- "select",
2912
- "slot",
2913
- "small",
2914
- "span",
2915
- "strong",
2916
- "sub",
2917
- "sup",
2918
- "svg",
2919
- "template",
2920
- "textarea",
2921
- "time",
2922
- "u",
2923
- "tt",
2924
- "var",
2925
- "video",
2926
- "wbr",
2927
- ],
2928
- };
2929
- const applicableOpts = {
2930
- removeHTMLComments: false,
2931
- removeCSSComments: false,
2932
- };
2933
- function isStr(something) {
2934
- return typeof something === "string";
2935
- }
2936
- function isLetter(something) {
2937
- return (typeof something === "string" &&
2938
- something.toUpperCase() !== something.toLowerCase());
2939
- }
2940
- /**
2941
- * Minifies HTML/CSS: valid or broken, pure or mixed with other languages
2942
- */
2943
- function crush(str, originalOpts) {
2944
- const start = Date.now();
2945
- // insurance:
2946
- if (!isStr(str)) {
2947
- if (str === undefined) {
2948
- throw new Error("html-crush: [THROW_ID_01] the first input argument is completely missing! It should be given as string.");
2949
- }
2950
- else {
2951
- throw new Error(`html-crush: [THROW_ID_02] the first input argument must be string! It was given as "${typeof str}", equal to:\n${JSON.stringify(str, null, 4)}`);
2952
- }
2953
- }
2954
- if (originalOpts && typeof originalOpts !== "object") {
2955
- throw new Error(`html-crush: [THROW_ID_03] the second input argument, options object, should be a plain object but it was given as type ${typeof originalOpts}, equal to ${JSON.stringify(originalOpts, null, 4)}`);
2956
- }
2957
- if (originalOpts &&
2958
- Array.isArray(originalOpts.breakToTheLeftOf) &&
2959
- originalOpts.breakToTheLeftOf.length) {
2960
- for (let z = 0, len = originalOpts.breakToTheLeftOf.length; z < len; z++) {
2961
- if (!isStr(originalOpts.breakToTheLeftOf[z])) {
2962
- throw new TypeError(`html-crush: [THROW_ID_05] the opts.breakToTheLeftOf array contains non-string elements! For example, element at index ${z} is of a type "${typeof originalOpts
2963
- .breakToTheLeftOf[z]}" and is equal to:\n${JSON.stringify(originalOpts.breakToTheLeftOf[z], null, 4)}`);
2964
- }
2965
- }
2966
- }
2967
- const opts = { ...defaults, ...originalOpts };
2968
- // normalize the opts.removeHTMLComments
2969
- if (typeof opts.removeHTMLComments === "boolean") {
2970
- opts.removeHTMLComments = opts.removeHTMLComments ? 1 : 0;
2971
- }
2972
- let breakToTheLeftOfFirstLetters = "";
2973
- if (Array.isArray(opts.breakToTheLeftOf) && opts.breakToTheLeftOf.length) {
2974
- breakToTheLeftOfFirstLetters = [
2975
- ...new Set(opts.breakToTheLeftOf.map((val) => val[0])),
2976
- ].join("");
2977
- }
2978
- // console.log(
2979
- // `0187 ${`\u001b[${33}m${`breakToTheLeftOfFirstLetters`}\u001b[${39}m`} = ${JSON.stringify(
2980
- // breakToTheLeftOfFirstLetters,
2981
- // null,
2982
- // 4
2983
- // )}`
2984
- // );
2985
- //
2986
- // console.log("\n");
2987
- // console.log(
2988
- // `0196 ${`\u001b[${33}m${`██ ██ ██`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
2989
- // opts,
2990
- // null,
2991
- // 4
2992
- // )}`
2993
- // );
2994
- let lastLinebreak = null;
2995
- let whitespaceStartedAt = null;
2996
- let nonWhitespaceCharMet = false;
2997
- let countCharactersPerLine = 0;
2998
- // new characters-per-line counter
2999
- let cpl = 0;
3000
- let withinStyleTag = false;
3001
- let withinHTMLConditional = false; // <!--[if lte mso 11]> etc
3002
- let withinInlineStyle = null;
3003
- let styleCommentStartedAt = null;
3004
- let htmlCommentStartedAt = null;
3005
- let scriptStartedAt = null;
3006
- // main do nothing switch, used to skip chunks of code and perform no action
3007
- let doNothing;
3008
- // we use staging "from" and "to" to preemptively mark the chunks
3009
- // of whitespace that will be either: a) replaced with a space; or
3010
- // b) replaced with linebreak. If opts.removeLineBreaks is on,
3011
- // if we need to break where the particular whitespace chunk is
3012
- // located, we replace it with line break. Otherwise, if
3013
- // the next chunk of characters that follows it fits on one line,
3014
- // we replace it with a single space.
3015
- let stageFrom = null;
3016
- let stageTo = null;
3017
- let stageAdd = null;
3018
- let tagName = null;
3019
- let tagNameStartsAt = null;
3020
- let leftTagName = null;
3021
- const CHARS_BREAK_ON_THE_RIGHT_OF_THEM = `>};`;
3022
- const CHARS_BREAK_ON_THE_LEFT_OF_THEM = `<`;
3023
- const CHARS_DONT_BREAK_ON_THE_LEFT_OF_THEM = `!`;
3024
- const DELETE_TIGHTLY_IF_ON_LEFT_IS = `>`;
3025
- const DELETE_TIGHTLY_IF_ON_RIGHT_IS = `<`;
3026
- const set = `{},:;<>~+`;
3027
- const DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS = set;
3028
- const DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS = set;
3029
- // the first non-whitespace character turns this flag off:
3030
- let beginningOfAFile = true;
3031
- // it will be used to trim start of the file.
3032
- const len = str.length;
3033
- const midLen = Math.floor(len / 2);
3034
- const leavePercForLastStage = 0.01; // in range of [0, 1]
3035
- // ceil - total range which is allocated to the main processing
3036
- let ceil;
3037
- if (opts.reportProgressFunc) {
3038
- ceil = Math.floor(opts.reportProgressFuncTo -
3039
- (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) *
3040
- leavePercForLastStage -
3041
- opts.reportProgressFuncFrom);
3042
- }
3043
- // one more round to collapse the whitespace to:
3044
- // 1. Tackle indentations
3045
- // 2. Remove excessive whitespace between strings on each line (not touching indentations)
3046
- // progress-wise, 98% will be allocated to loop, rest 2% - to range applies and
3047
- // final return clauses
3048
- let currentPercentageDone;
3049
- let lastPercentage = 0;
3050
- let lineEnding = `\n`;
3051
- if (str.includes(`\r\n`)) {
3052
- lineEnding = `\r\n`;
3053
- }
3054
- else if (str.includes(`\r`)) {
3055
- lineEnding = `\r`;
3056
- }
3057
- if (len) {
3058
- for (let i = 0; i < len; i++) {
3059
- //
3060
- //
3061
- //
3062
- //
3063
- // TOP
3064
- //
3065
- //
3066
- //
3067
- //
3068
- // Logging:
3069
- // ███████████████████████████████████████
3070
- // Report the progress. We'll allocate 98% of the progress bar to this stage
3071
- if (opts.reportProgressFunc) {
3072
- if (len > 1000 && len < 2000) {
3073
- if (i === midLen) {
3074
- opts.reportProgressFunc(Math.floor((opts.reportProgressFuncTo - opts.reportProgressFuncFrom) / 2));
3075
- }
3076
- }
3077
- else if (len >= 2000) {
3078
- // defaults:
3079
- // opts.reportProgressFuncFrom = 0
3080
- // opts.reportProgressFuncTo = 100
3081
- currentPercentageDone =
3082
- opts.reportProgressFuncFrom + Math.floor((i / len) * (ceil || 1));
3083
- if (currentPercentageDone !== lastPercentage) {
3084
- lastPercentage = currentPercentageDone;
3085
- opts.reportProgressFunc(currentPercentageDone);
3086
- }
3087
- }
3088
- }
3089
- // count characters-per-line
3090
- cpl++;
3091
- // turn off doNothing if marker passed
3092
- // ███████████████████████████████████████
3093
- if (doNothing && typeof doNothing === "number" && i >= doNothing) {
3094
- doNothing = undefined;
3095
- }
3096
- // catch ending of </script...
3097
- // ███████████████████████████████████████
3098
- if (scriptStartedAt !== null &&
3099
- str.startsWith("</script", i) &&
3100
- !isLetter(str[i + 8])) {
3101
- // 1. if there is a line break, chunk of whitespace and </script>,
3102
- // delete that chunk of whitespace, leave line break.
3103
- // If there's non-whitespace character, chunk of whitespace and </script>,
3104
- // delete that chunk of whitespace.
3105
- // Basically, traverse backwards from "<" of "</script>", stop either
3106
- // at first line break or non-whitespace character.
3107
- if ((opts.removeIndentations || opts.removeLineBreaks) &&
3108
- i > 0 &&
3109
- str[~-i] &&
3110
- !str[~-i].trim()) {
3111
- // march backwards
3112
- for (let y = i; y--;) {
3113
- if (str[y] === "\n" || str[y] === "\r" || str[y].trim()) {
3114
- if (y + 1 < i) {
3115
- finalIndexesToDelete.push(y + 1, i);
3116
- }
3117
- break;
3118
- }
3119
- }
3120
- }
3121
- // 2.
3122
- scriptStartedAt = null;
3123
- doNothing = false;
3124
- i += 8;
3125
- continue;
3126
- }
3127
- // catch start of <script...
3128
- // ███████████████████████████████████████
3129
- if (!doNothing &&
3130
- !withinStyleTag &&
3131
- str.startsWith("<script", i) &&
3132
- !isLetter(str[i + 7])) {
3133
- scriptStartedAt = i;
3134
- doNothing = true;
3135
- let whatToInsert = "";
3136
- if ((opts.removeLineBreaks || opts.removeIndentations) &&
3137
- whitespaceStartedAt !== null) {
3138
- if (whitespaceStartedAt > 0) {
3139
- whatToInsert = lineEnding;
3140
- }
3141
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToInsert);
3142
- }
3143
- whitespaceStartedAt = null;
3144
- lastLinebreak = null;
3145
- }
3146
- //
3147
- //
3148
- //
3149
- //
3150
- //
3151
- //
3152
- //
3153
- //
3154
- // MIDDLE
3155
- //
3156
- //
3157
- //
3158
- //
3159
- //
3160
- //
3161
- //
3162
- //
3163
- // catch ending of the tag's name
3164
- // ███████████████████████████████████████
3165
- if (tagNameStartsAt !== null &&
3166
- tagName === null &&
3167
- !/\w/.test(str[i]) // not a letter
3168
- ) {
3169
- tagName = str.slice(tagNameStartsAt, i);
3170
- // check for inner tag whitespace
3171
- const idxOnTheRight = right(str, ~-i);
3172
- if (typeof idxOnTheRight === "number" &&
3173
- str[idxOnTheRight] === ">" &&
3174
- !str[i].trim() &&
3175
- right(str, i)) {
3176
- finalIndexesToDelete.push(i, right(str, i));
3177
- }
3178
- else if (idxOnTheRight &&
3179
- str[idxOnTheRight] === "/" &&
3180
- str[right(str, idxOnTheRight)] === ">") {
3181
- // if there's a space in front of "/>"
3182
- if (!str[i].trim() && right(str, i)) {
3183
- finalIndexesToDelete.push(i, right(str, i));
3184
- }
3185
- // if there's space between slash and bracket
3186
- if (str[idxOnTheRight + 1] !== ">" && right(str, idxOnTheRight + 1)) {
3187
- finalIndexesToDelete.push(idxOnTheRight + 1, right(str, idxOnTheRight + 1));
3188
- }
3189
- }
3190
- }
3191
- // catch a tag's opening bracket
3192
- // ███████████████████████████████████████
3193
- if (!doNothing &&
3194
- !withinStyleTag &&
3195
- !withinInlineStyle &&
3196
- str[~-i] === "<" &&
3197
- tagNameStartsAt === null) {
3198
- if (/\w/.test(str[i])) {
3199
- tagNameStartsAt = i;
3200
- }
3201
- else if (str[right(str, ~-i)] === "/" &&
3202
- /\w/.test(str[right(str, right(str, ~-i))] || "")) {
3203
- tagNameStartsAt = right(str, right(str, ~-i));
3204
- }
3205
- }
3206
- // catch an end of CSS comments
3207
- // ███████████████████████████████████████
3208
- if (!doNothing &&
3209
- (withinStyleTag || withinInlineStyle) &&
3210
- styleCommentStartedAt !== null &&
3211
- str[i] === "*" &&
3212
- str[i + 1] === "/") {
3213
- // stage:
3214
- [stageFrom, stageTo] = expander({
3215
- str,
3216
- from: styleCommentStartedAt,
3217
- to: i + 2,
3218
- ifLeftSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS ,
3219
- ifRightSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS ,
3220
- });
3221
- // reset marker:
3222
- styleCommentStartedAt = null;
3223
- if (stageFrom != null) {
3224
- finalIndexesToDelete.push(stageFrom, stageTo);
3225
- }
3226
- else {
3227
- countCharactersPerLine += 1;
3228
- i += 1;
3229
- }
3230
- // console.log(`0796 CONTINUE`);
3231
- // continue;
3232
- doNothing = i + 2;
3233
- }
3234
- // catch a start of CSS comments
3235
- // ███████████████████████████████████████
3236
- if (!doNothing &&
3237
- (withinStyleTag || withinInlineStyle) &&
3238
- styleCommentStartedAt === null &&
3239
- str[i] === "/" &&
3240
- str[i + 1] === "*") {
3241
- // independently of options settings, mark the options setting
3242
- // "removeCSSComments" as applicable:
3243
- if (!applicableOpts.removeCSSComments) {
3244
- applicableOpts.removeCSSComments = true;
3245
- }
3246
- if (opts.removeCSSComments) {
3247
- styleCommentStartedAt = i;
3248
- }
3249
- }
3250
- // catch an ending of mso conditional tags
3251
- // ███████████████████████████████████████
3252
- if (withinHTMLConditional && str.startsWith("![endif", i + 1)) {
3253
- withinHTMLConditional = false;
3254
- }
3255
- // catch an end of HTML comment
3256
- // ███████████████████████████████████████
3257
- if (!doNothing &&
3258
- !withinStyleTag &&
3259
- !withinInlineStyle &&
3260
- htmlCommentStartedAt !== null) {
3261
- let distanceFromHereToCommentEnding;
3262
- if (str.startsWith("-->", i)) {
3263
- distanceFromHereToCommentEnding = 3;
3264
- }
3265
- else if (str[i] === ">" && str[i - 1] === "]") {
3266
- distanceFromHereToCommentEnding = 1;
3267
- }
3268
- if (distanceFromHereToCommentEnding) {
3269
- // stage:
3270
- [stageFrom, stageTo] = expander({
3271
- str,
3272
- from: htmlCommentStartedAt,
3273
- to: i + distanceFromHereToCommentEnding,
3274
- });
3275
- // reset marker:
3276
- htmlCommentStartedAt = null;
3277
- if (stageFrom != null) {
3278
- // it depends is there any character allowance left from the
3279
- // line length limit or not
3280
- if (opts.lineLengthLimit &&
3281
- cpl - (stageTo - stageFrom) >= opts.lineLengthLimit) {
3282
- finalIndexesToDelete.push(stageFrom, stageTo, lineEnding);
3283
- // Currently we're not on the bracket ">" of the comment
3284
- // closing "-->", we're at the start of it, that first
3285
- // dash. This means, we'll still traverse to the end
3286
- // of this comment tag, before the actual "reset" should
3287
- // happen.
3288
- // Luckily we know how many characters are there left
3289
- // to traverse until the comment's ending is reached -
3290
- // "distanceFromHereToCommentEnding".
3291
- cpl = -distanceFromHereToCommentEnding;
3292
- // here we've reset cpl to some negative value, like -3
3293
- }
3294
- else {
3295
- // we have some character length allowance left so
3296
- // let's just delete the comment and reduce the cpl
3297
- // by that length
3298
- finalIndexesToDelete.push(stageFrom, stageTo);
3299
- cpl -= stageTo - stageFrom;
3300
- }
3301
- // finalIndexesToDelete.push(i + 1, i + 1, "\n");
3302
- // console.log(`1485 PUSH [${i + 1}, ${i + 1}, "\\n"]`);
3303
- // countCharactersPerLine = 0;
3304
- }
3305
- else {
3306
- countCharactersPerLine += distanceFromHereToCommentEnding - 1;
3307
- i += distanceFromHereToCommentEnding - 1;
3308
- }
3309
- // console.log(`0796 CONTINUE`);
3310
- // continue;
3311
- doNothing = i + distanceFromHereToCommentEnding;
3312
- }
3313
- }
3314
- // catch a start of HTML comment
3315
- // ███████████████████████████████████████
3316
- if (!doNothing &&
3317
- !withinStyleTag &&
3318
- !withinInlineStyle &&
3319
- str.startsWith("<!--", i) &&
3320
- htmlCommentStartedAt === null) {
3321
- // detect outlook conditionals
3322
- if (str.startsWith("[if", i + 4)) {
3323
- if (!withinHTMLConditional) {
3324
- withinHTMLConditional = true;
3325
- }
3326
- // skip the second counterpart, "<!-->" of "<!--[if !mso]><!-->"
3327
- // the plan is to not set the "htmlCommentStartedAt" at all if deletion
3328
- // is not needed
3329
- if (opts.removeHTMLComments === 2) {
3330
- htmlCommentStartedAt = i;
3331
- }
3332
- }
3333
- else if (
3334
- // setting is either 1 or 2 (delete text comments only or any comments):
3335
- opts.removeHTMLComments &&
3336
- // prevent the "not" type tails' "<!--" of "<!--<![endif]-->" from
3337
- // accidentally triggering the clauses
3338
- (!withinHTMLConditional || opts.removeHTMLComments === 2)) {
3339
- htmlCommentStartedAt = i;
3340
- }
3341
- // independently of options settings, mark the options setting
3342
- // "removeHTMLComments" as applicable:
3343
- if (!applicableOpts.removeHTMLComments) {
3344
- applicableOpts.removeHTMLComments = true;
3345
- }
3346
- // opts.removeHTMLComments: 0|1|2
3347
- }
3348
- // catch style tag
3349
- // ███████████████████████████████████████
3350
- if (!doNothing &&
3351
- withinStyleTag &&
3352
- styleCommentStartedAt === null &&
3353
- str.startsWith("</style", i) &&
3354
- !isLetter(str[i + 7])) {
3355
- withinStyleTag = false;
3356
- }
3357
- else if (!doNothing &&
3358
- !withinStyleTag &&
3359
- styleCommentStartedAt === null &&
3360
- str.startsWith("<style", i) &&
3361
- !isLetter(str[i + 6])) {
3362
- withinStyleTag = true;
3363
- // if opts.breakToTheLeftOf have "<style" among them, break to the
3364
- // right of this tag as well
3365
- if ((opts.removeLineBreaks || opts.removeIndentations) &&
3366
- opts.breakToTheLeftOf.includes("<style") &&
3367
- str.startsWith(` type="text/css">`, i + 6) &&
3368
- str[i + 24]) {
3369
- finalIndexesToDelete.push(i + 23, i + 23, lineEnding);
3370
- }
3371
- }
3372
- // catch start of inline styles
3373
- // ███████████████████████████████████████
3374
- if (!doNothing &&
3375
- !withinInlineStyle &&
3376
- `"'`.includes(str[i]) &&
3377
- str.endsWith("style=", i)) {
3378
- withinInlineStyle = i;
3379
- }
3380
- // catch whitespace
3381
- // ███████████████████████████████████████
3382
- if (!doNothing && !str[i].trim()) {
3383
- // if whitespace
3384
- if (whitespaceStartedAt === null) {
3385
- whitespaceStartedAt = i;
3386
- }
3387
- }
3388
- else if (!doNothing &&
3389
- !((withinStyleTag || withinInlineStyle) &&
3390
- styleCommentStartedAt !== null)) {
3391
- // catch the ending of a whitespace chunk
3392
- // console.log(`0912`);
3393
- if (whitespaceStartedAt !== null) {
3394
- if (opts.removeLineBreaks) {
3395
- countCharactersPerLine += 1;
3396
- }
3397
- if (beginningOfAFile) {
3398
- beginningOfAFile = false;
3399
- if (opts.removeIndentations || opts.removeLineBreaks) {
3400
- finalIndexesToDelete.push(0, i);
3401
- }
3402
- }
3403
- else {
3404
- // so it's not beginning of a file
3405
- // this is the most important area of the program - catching normal
3406
- // whitespace chunks
3407
- // ===================================================================
3408
- // ██ CASE 1. Remove indentations only.
3409
- if (opts.removeIndentations && !opts.removeLineBreaks) {
3410
- if (!nonWhitespaceCharMet &&
3411
- lastLinebreak !== null &&
3412
- i > lastLinebreak) {
3413
- finalIndexesToDelete.push(lastLinebreak + 1, i);
3414
- }
3415
- else if (whitespaceStartedAt + 1 < i) {
3416
- // we'll try to recycle some spaces, either at the
3417
- // beginning (preferable) or ending (at least) of the
3418
- // whitespace chunk, instead of wiping whole whitespace
3419
- // chunk and adding single space again.
3420
- // first, crop tight around the conditional comments
3421
- if (
3422
- // imagine <!--[if mso]>
3423
- str.endsWith("]>", whitespaceStartedAt) ||
3424
- // imagine <!--[if !mso]><!-->...<
3425
- // ^
3426
- // |
3427
- // our "whitespaceStartedAt"
3428
- str.endsWith("-->", whitespaceStartedAt) ||
3429
- // imagine closing counterparts, .../>...<![endif]-->
3430
- str.startsWith("<![", i) ||
3431
- // imagine other type of closing counterpart, .../>...<!--<![
3432
- str.startsWith("<!--<![", i)) {
3433
- // push the whole whitespace chunk
3434
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3435
- }
3436
- else if (str[whitespaceStartedAt] === " ") {
3437
- finalIndexesToDelete.push(whitespaceStartedAt + 1, i);
3438
- }
3439
- else if (str[~-i] === " ") {
3440
- finalIndexesToDelete.push(whitespaceStartedAt, ~-i);
3441
- }
3442
- else {
3443
- finalIndexesToDelete.push(whitespaceStartedAt, i, " ");
3444
- }
3445
- }
3446
- }
3447
- // ===================================================================
3448
- // ██ CASE 2. Remove linebreaks (includes indentation removal by definition).
3449
- if (opts.removeLineBreaks || withinInlineStyle) {
3450
- //
3451
- // ██ CASE 2-1 - special break points from opts.breakToTheLeftOf
3452
- if (breakToTheLeftOfFirstLetters.includes(str[i]) &&
3453
- matchRightIncl(str, i, opts.breakToTheLeftOf)) {
3454
- // maybe there was just single line break?
3455
- if (
3456
- // CR or LF endings
3457
- !(`\r\n`.includes(str[~-i]) && whitespaceStartedAt === ~-i) &&
3458
- // CRLF endings
3459
- !(str[~-i] === "\n" &&
3460
- str[i - 2] === "\r" &&
3461
- whitespaceStartedAt === i - 2)) {
3462
- finalIndexesToDelete.push(whitespaceStartedAt, i, lineEnding);
3463
- }
3464
- stageFrom = null;
3465
- stageTo = null;
3466
- stageAdd = null;
3467
- whitespaceStartedAt = null;
3468
- countCharactersPerLine = 1;
3469
- continue;
3470
- }
3471
- // ██ CASE 2-2 - rest of whitespace chunk removal clauses
3472
- let whatToAdd = " ";
3473
- // skip for inline tags and also inline comparisons vs. numbers
3474
- // for example "something < 2" or "zzz > 1"
3475
- if (
3476
- // (
3477
- str[i] === "<" &&
3478
- matchRight(str, i, opts.mindTheInlineTags, {
3479
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3480
- })
3481
- // ) ||
3482
- // ("<>".includes(str[i]) &&
3483
- // ("0123456789".includes(str[right(str, i)]) ||
3484
- // "0123456789".includes(str[left(str, i)])))
3485
- ) ;
3486
- else if ((str[~-whitespaceStartedAt] &&
3487
- DELETE_TIGHTLY_IF_ON_LEFT_IS.includes(str[~-whitespaceStartedAt]) &&
3488
- DELETE_TIGHTLY_IF_ON_RIGHT_IS.includes(str[i])) ||
3489
- ((withinStyleTag || withinInlineStyle) &&
3490
- styleCommentStartedAt === null &&
3491
- (DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS.includes(str[~-whitespaceStartedAt]) ||
3492
- DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS.includes(str[i]))) ||
3493
- (str.startsWith("!important", i) && !withinHTMLConditional) ||
3494
- (withinInlineStyle &&
3495
- (str[~-whitespaceStartedAt] === "'" ||
3496
- str[~-whitespaceStartedAt] === '"')) ||
3497
- (str[~-whitespaceStartedAt] === "}" &&
3498
- str.startsWith("</style", i)) ||
3499
- (str[i] === ">" &&
3500
- (`'"`.includes(str[left(str, i)]) ||
3501
- str[right(str, i)] === "<")) ||
3502
- (str[i] === "/" && str[right(str, i)] === ">")) {
3503
- whatToAdd = "";
3504
- if (str[i] === "/" &&
3505
- str[i + 1] === ">" &&
3506
- right(str, i) &&
3507
- right(str, i) > i + 1) {
3508
- // delete whitespace between / and >
3509
- finalIndexesToDelete.push(i + 1, right(str, i));
3510
- countCharactersPerLine -= right(str, i) - i + 1;
3511
- }
3512
- }
3513
- if (whatToAdd && whatToAdd.length) {
3514
- countCharactersPerLine += 1;
3515
- }
3516
- // TWO CASES:
3517
- if (!opts.lineLengthLimit) {
3518
- // 2-1: Line-length limiting is off (easy)
3519
- // We skip the stage part, the whitespace chunks to straight to
3520
- // finalIndexesToDelete ranges array.
3521
- // but ensure that we're not replacing a single space with a single space
3522
- if (!(i === whitespaceStartedAt + 1 &&
3523
- // str[whitespaceStartedAt] === " " &&
3524
- whatToAdd === " ")) {
3525
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToAdd);
3526
- }
3527
- }
3528
- else {
3529
- // 2-2: Line-length limiting is on (not that easy)
3530
- // maybe we are already beyond the limit?
3531
- if (countCharactersPerLine >= opts.lineLengthLimit ||
3532
- !str[i + 1] ||
3533
- str[i] === ">" ||
3534
- (str[i] === "/" && str[i + 1] === ">")) {
3535
- if (countCharactersPerLine > opts.lineLengthLimit ||
3536
- (countCharactersPerLine === opts.lineLengthLimit &&
3537
- str[i + 1] &&
3538
- str[i + 1].trim() &&
3539
- !CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3540
- !CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i + 1]))) {
3541
- whatToAdd = lineEnding;
3542
- countCharactersPerLine = 1;
3543
- }
3544
- // replace the whitespace only in two cases:
3545
- // 1) if line length limit would otherwise be exceeded
3546
- // 2) if this replacement reduces the file length. For example,
3547
- // don't replace the linebreak with a space. But do delete
3548
- // linebreak like it happens between tags.
3549
- if (countCharactersPerLine > opts.lineLengthLimit ||
3550
- !(whatToAdd === " " && i === whitespaceStartedAt + 1)) {
3551
- finalIndexesToDelete.push(whitespaceStartedAt, i, whatToAdd);
3552
- lastLinebreak = null;
3553
- }
3554
- stageFrom = null;
3555
- stageTo = null;
3556
- stageAdd = null;
3557
- }
3558
- else if (stageFrom === null ||
3559
- whitespaceStartedAt < stageFrom) {
3560
- // only submit the range if it's bigger
3561
- stageFrom = whitespaceStartedAt;
3562
- stageTo = i;
3563
- stageAdd = whatToAdd;
3564
- }
3565
- }
3566
- }
3567
- // ===================================================================
3568
- }
3569
- // finally, toggle the marker:
3570
- whitespaceStartedAt = null;
3571
- // toggle nonWhitespaceCharMet
3572
- if (!nonWhitespaceCharMet) {
3573
- nonWhitespaceCharMet = true;
3574
- }
3575
- // continue;
3576
- }
3577
- else {
3578
- // 1. case when first character in string is not whitespace:
3579
- if (beginningOfAFile) {
3580
- beginningOfAFile = false;
3581
- }
3582
- // 2. tend count if linebreak removal is on:
3583
- if (opts.removeLineBreaks) {
3584
- // there was no whitespace gap and linebreak removal is on, so just
3585
- // increment the count
3586
- countCharactersPerLine += 1;
3587
- }
3588
- }
3589
- // ===================================================================
3590
- // ██ EXTRAS:
3591
- // toggle nonWhitespaceCharMet
3592
- if (!nonWhitespaceCharMet) {
3593
- nonWhitespaceCharMet = true;
3594
- }
3595
- }
3596
- // catch the characters, suitable for a break
3597
- if (!doNothing &&
3598
- !beginningOfAFile &&
3599
- i !== 0 &&
3600
- opts.removeLineBreaks &&
3601
- (opts.lineLengthLimit || breakToTheLeftOfFirstLetters) &&
3602
- !str.startsWith("</a", i)) {
3603
- if (breakToTheLeftOfFirstLetters &&
3604
- matchRightIncl(str, i, opts.breakToTheLeftOf) &&
3605
- str.slice(0, i).trim() &&
3606
- (!str.startsWith("<![endif]", i) || !matchLeft(str, i, "<!--"))) {
3607
- finalIndexesToDelete.push(i, i, lineEnding);
3608
- stageFrom = null;
3609
- stageTo = null;
3610
- stageAdd = null;
3611
- countCharactersPerLine = 1;
3612
- continue;
3613
- }
3614
- else if (opts.lineLengthLimit &&
3615
- countCharactersPerLine <= opts.lineLengthLimit) {
3616
- if (!str[i + 1] ||
3617
- (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3618
- !CHARS_DONT_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i])) ||
3619
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) ||
3620
- !str[i].trim()) {
3621
- // 1. release stage contents - now they'll be definitely deleted
3622
- // =============================================================
3623
- if (stageFrom !== null &&
3624
- stageTo !== null &&
3625
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3626
- let whatToAdd = stageAdd;
3627
- // if we are not on breaking point, last "stageAdd" needs to be
3628
- // amended into linebreak because otherwise we'll exceed the
3629
- // character limit
3630
- if (str[i].trim() &&
3631
- str[i + 1] &&
3632
- str[i + 1].trim() &&
3633
- countCharactersPerLine + (stageAdd ? stageAdd.length : 0) >
3634
- opts.lineLengthLimit) {
3635
- whatToAdd = lineEnding;
3636
- }
3637
- // if line is beyond the line length limit or whitespace is not
3638
- // a single space, staged to be replaced with single space,
3639
- // tackle this whitespace
3640
- if (countCharactersPerLine + (whatToAdd ? whatToAdd.length : 0) >
3641
- opts.lineLengthLimit ||
3642
- !(whatToAdd === " " &&
3643
- stageTo === stageFrom + 1 &&
3644
- str[stageFrom] === " ")) {
3645
- // push this range only if it's not between curlies, } and {
3646
- if (!(str[~-stageFrom] === "}" && str[stageTo] === "{")) {
3647
- finalIndexesToDelete.push(stageFrom, stageTo, whatToAdd);
3648
- lastLinebreak = null;
3649
- } // else {
3650
- // console.log(
3651
- // `1419 didn't push because whitespace is between curlies`
3652
- // );
3653
- // }
3654
- }
3655
- else {
3656
- countCharactersPerLine -= lastLinebreak || 0;
3657
- }
3658
- }
3659
- // 2. put this current place into stage
3660
- // =============================================================
3661
- if (str[i].trim() &&
3662
- (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) ||
3663
- (str[~-i] &&
3664
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[~-i]))) &&
3665
- isStr(leftTagName) &&
3666
- (!tagName || !opts.mindTheInlineTags.includes(tagName)) &&
3667
- !(str[i] === "<" &&
3668
- matchRight(str, i, opts.mindTheInlineTags, {
3669
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3670
- })) &&
3671
- !(str[i] === "<" &&
3672
- matchRight(str, i, opts.mindTheInlineTags, {
3673
- trimCharsBeforeMatching: "/",
3674
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3675
- }))) {
3676
- stageFrom = i;
3677
- stageTo = i;
3678
- stageAdd = null;
3679
- }
3680
- else if (styleCommentStartedAt === null &&
3681
- stageFrom !== null &&
3682
- (withinInlineStyle ||
3683
- !opts.mindTheInlineTags ||
3684
- !Array.isArray(opts.mindTheInlineTags) ||
3685
- (Array.isArray(opts.mindTheInlineTags.length) &&
3686
- !opts.mindTheInlineTags.length) ||
3687
- !isStr(tagName) ||
3688
- (Array.isArray(opts.mindTheInlineTags) &&
3689
- opts.mindTheInlineTags.length &&
3690
- isStr(tagName) &&
3691
- !opts.mindTheInlineTags.includes(tagName))) &&
3692
- !(str[i] === "<" &&
3693
- matchRight(str, i, opts.mindTheInlineTags, {
3694
- trimCharsBeforeMatching: "/",
3695
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3696
- }))) {
3697
- stageFrom = null;
3698
- stageTo = null;
3699
- stageAdd = null;
3700
- // if (str[i] === "\n" || str[i] === "\r") {
3701
- // countCharactersPerLine -= lastLinebreak;
3702
- // console.log(
3703
- // `1449 SET countCharactersPerLine = ${countCharactersPerLine}`
3704
- // );
3705
- // }
3706
- }
3707
- }
3708
- }
3709
- else if (opts.lineLengthLimit) {
3710
- // countCharactersPerLine > opts.lineLengthLimit
3711
- // LIMIT HAS BEEN EXCEEDED!
3712
- // WE NEED TO BREAK RIGHT HERE
3713
- if (CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3714
- !(str[i] === "<" &&
3715
- matchRight(str, i, opts.mindTheInlineTags, {
3716
- trimCharsBeforeMatching: "/",
3717
- cb: (nextChar) => !nextChar || !/\w/.test(nextChar), // not a letter
3718
- }))) {
3719
- // ██ 1.
3720
- //
3721
- // if really exceeded, not on limit, commit stage which will shorten
3722
- // the string and maybe we'll be within the limit range again
3723
- if (stageFrom !== null &&
3724
- stageTo !== null &&
3725
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3726
- // case in test 02.11.09
3727
- // We might have passed some tabs for example, which should be
3728
- // deleted what might put line length back within limit. Or not.
3729
- //
3730
- const whatToAddLength = stageAdd && stageAdd.length ? stageAdd.length : 0;
3731
- // Currently, countCharactersPerLine > opts.lineLengthLimit
3732
- // But, will it still be true if we compensate for what's in stage?
3733
- if (countCharactersPerLine -
3734
- (stageTo - stageFrom - whatToAddLength) -
3735
- 1 >
3736
- opts.lineLengthLimit) ;
3737
- else {
3738
- // So,
3739
- // countCharactersPerLine -
3740
- // (stageTo - stageFrom - whatToAddLength) - 1 <=
3741
- // opts.lineLengthLimit
3742
- // don't break at stage, just apply its contents and we're good
3743
- finalIndexesToDelete.push(stageFrom, stageTo, stageAdd);
3744
- // We're not done yet. We are currently located on a potential
3745
- // break point,
3746
- // countCharactersPerLine -
3747
- // (stageTo - stageFrom - whatToAddLength) - 1 ===
3748
- // opts.lineLengthLimit ?
3749
- if (countCharactersPerLine -
3750
- (stageTo - stageFrom - whatToAddLength) -
3751
- 1 ===
3752
- opts.lineLengthLimit) {
3753
- finalIndexesToDelete.push(i, i, lineEnding);
3754
- countCharactersPerLine = 0;
3755
- }
3756
- // reset
3757
- stageFrom = null;
3758
- stageTo = null;
3759
- stageAdd = null;
3760
- }
3761
- }
3762
- else {
3763
- //
3764
- finalIndexesToDelete.push(i, i, lineEnding);
3765
- countCharactersPerLine = 0;
3766
- }
3767
- }
3768
- else if (str[i + 1] &&
3769
- CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3770
- isStr(tagName) &&
3771
- Array.isArray(opts.mindTheInlineTags) &&
3772
- opts.mindTheInlineTags.length &&
3773
- !opts.mindTheInlineTags.includes(tagName)) {
3774
- // ██ 2.
3775
- //
3776
- if (stageFrom !== null &&
3777
- stageTo !== null &&
3778
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) ;
3779
- else {
3780
- //
3781
- finalIndexesToDelete.push(i + 1, i + 1, lineEnding);
3782
- countCharactersPerLine = 0;
3783
- }
3784
- }
3785
- else if (!str[i].trim()) ;
3786
- else if (!str[i + 1]) {
3787
- // ██ 4.
3788
- //
3789
- // if we reached the end of string, check what's in stage
3790
- if (stageFrom !== null &&
3791
- stageTo !== null &&
3792
- (stageFrom !== stageTo || (stageAdd && stageAdd.length))) {
3793
- finalIndexesToDelete.push(stageFrom, stageTo, lineEnding);
3794
- }
3795
- }
3796
- }
3797
- }
3798
- // catch any character beyond the line length limit:
3799
- if (!doNothing &&
3800
- !beginningOfAFile &&
3801
- opts.removeLineBreaks &&
3802
- opts.lineLengthLimit &&
3803
- countCharactersPerLine >= opts.lineLengthLimit &&
3804
- stageFrom !== null &&
3805
- stageTo !== null &&
3806
- !CHARS_BREAK_ON_THE_RIGHT_OF_THEM.includes(str[i]) &&
3807
- !CHARS_BREAK_ON_THE_LEFT_OF_THEM.includes(str[i]) &&
3808
- !"/".includes(str[i])) {
3809
- // two possible cases:
3810
- // 1. we hit the line length limit and we can break afterwards
3811
- // 2. we can't break afterwards, and there might be stage present
3812
- if (!(countCharactersPerLine === opts.lineLengthLimit &&
3813
- str[i + 1] &&
3814
- !str[i + 1].trim())) {
3815
- //
3816
- let whatToAdd = lineEnding;
3817
- if (str[i + 1] &&
3818
- !str[i + 1].trim() &&
3819
- countCharactersPerLine === opts.lineLengthLimit) {
3820
- whatToAdd = stageAdd;
3821
- }
3822
- // final correction - we might need to extend stageFrom to include
3823
- // all whitespace on the left if whatToAdd is a line break
3824
- if (whatToAdd === lineEnding &&
3825
- !str[~-stageFrom].trim() &&
3826
- left(str, stageFrom)) {
3827
- stageFrom = left(str, stageFrom) + 1;
3828
- }
3829
- finalIndexesToDelete.push(stageFrom, stageTo, whatToAdd);
3830
- countCharactersPerLine = i - stageTo;
3831
- if (str[i].length) {
3832
- countCharactersPerLine += 1;
3833
- }
3834
- stageFrom = null;
3835
- stageTo = null;
3836
- stageAdd = null;
3837
- }
3838
- }
3839
- // catch line breaks
3840
- // ███████████████████████████████████████
3841
- if ((!doNothing && str[i] === "\n") ||
3842
- (str[i] === "\r" &&
3843
- (!str[i + 1] || (str[i + 1] && str[i + 1] !== "\n")))) {
3844
- // =======================================================================
3845
- // mark this
3846
- lastLinebreak = i;
3847
- // =======================================================================
3848
- // reset nonWhitespaceCharMet
3849
- if (nonWhitespaceCharMet) {
3850
- nonWhitespaceCharMet = false;
3851
- }
3852
- // =======================================================================
3853
- // delete trailing whitespace on each line OR empty lines
3854
- if (!opts.removeLineBreaks &&
3855
- whitespaceStartedAt !== null &&
3856
- whitespaceStartedAt < i &&
3857
- str[i + 1] &&
3858
- str[i + 1] !== "\r" &&
3859
- str[i + 1] !== "\n") {
3860
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3861
- }
3862
- }
3863
- // catch the EOF
3864
- // ███████████████████████████████████████
3865
- if (!str[i + 1]) {
3866
- if (withinStyleTag && styleCommentStartedAt !== null) {
3867
- finalIndexesToDelete.push(...expander({
3868
- str,
3869
- from: styleCommentStartedAt,
3870
- to: i,
3871
- ifLeftSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_LEFT_IS ,
3872
- ifRightSideIncludesThisThenCropTightly: DELETE_IN_STYLE_TIGHTLY_IF_ON_RIGHT_IS ,
3873
- }));
3874
- }
3875
- else if (whitespaceStartedAt && str[i] !== "\n" && str[i] !== "\r") {
3876
- // catch trailing whitespace at the end of the string which is not legit
3877
- // trailing linebreak
3878
- finalIndexesToDelete.push(whitespaceStartedAt, i + 1);
3879
- }
3880
- else if (whitespaceStartedAt &&
3881
- ((str[i] === "\r" && str[i + 1] === "\n") ||
3882
- (str[i] === "\n" && str[i - 1] !== "\r"))) {
3883
- finalIndexesToDelete.push(whitespaceStartedAt, i);
3884
- }
3885
- }
3886
- //
3887
- //
3888
- //
3889
- //
3890
- //
3891
- //
3892
- //
3893
- //
3894
- //
3895
- // BOTTOM
3896
- //
3897
- //
3898
- //
3899
- //
3900
- //
3901
- //
3902
- //
3903
- //
3904
- // catch end of inline styles
3905
- // ███████████████████████████████████████
3906
- if (!doNothing &&
3907
- withinInlineStyle &&
3908
- withinInlineStyle < i &&
3909
- str[withinInlineStyle] === str[i]) {
3910
- withinInlineStyle = null;
3911
- }
3912
- // catch <pre...>
3913
- // ███████████████████████████████████████
3914
- if (!doNothing &&
3915
- !withinStyleTag &&
3916
- str.startsWith("<pre", i) &&
3917
- !isLetter(str[i + 4])) {
3918
- const locationOfClosingPre = str.indexOf("</pre", i + 5);
3919
- if (locationOfClosingPre > 0) {
3920
- doNothing = locationOfClosingPre;
3921
- }
3922
- }
3923
- // catch <code...>
3924
- // ███████████████████████████████████████
3925
- if (!doNothing &&
3926
- !withinStyleTag &&
3927
- str.startsWith("<code", i) &&
3928
- !isLetter(str[i + 5])) {
3929
- const locationOfClosingCode = str.indexOf("</code", i + 5);
3930
- if (locationOfClosingCode > 0) {
3931
- doNothing = locationOfClosingCode;
3932
- }
3933
- }
3934
- // catch start of <![CDATA[
3935
- // ███████████████████████████████████████
3936
- if (!doNothing && str.startsWith("<![CDATA[", i)) {
3937
- const locationOfClosingCData = str.indexOf("]]>", i + 9);
3938
- if (locationOfClosingCData > 0) {
3939
- doNothing = locationOfClosingCData;
3940
- }
3941
- }
3942
- // catch tag's closing bracket
3943
- // ███████████████████████████████████████
3944
- if (!doNothing &&
3945
- !withinStyleTag &&
3946
- !withinInlineStyle &&
3947
- tagNameStartsAt !== null &&
3948
- str[i] === ">") {
3949
- // if another tag starts on the right, hand over the name:
3950
- if (str[right(str, i)] === "<") {
3951
- leftTagName = tagName;
3952
- }
3953
- tagNameStartsAt = null;
3954
- tagName = null;
3955
- }
3956
- // catch tag's opening bracket
3957
- // ███████████████████████████████████████
3958
- if (str[i] === "<" && leftTagName !== null) {
3959
- // reset it after use
3960
- leftTagName = null;
3961
- }
3962
- //
3963
- //
3964
- //
3965
- // end of the loop
3966
- }
3967
- if (finalIndexesToDelete.current()) {
3968
- const ranges = finalIndexesToDelete.current();
3969
- finalIndexesToDelete.wipe();
3970
- const startingPercentageDone = opts.reportProgressFuncTo -
3971
- (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) *
3972
- leavePercForLastStage;
3973
- const res = rApply(str, ranges, (applyPercDone) => {
3974
- // allocate remaining "leavePercForLastStage" percentage of the total
3975
- // progress reporting to this stage:
3976
- if (opts.reportProgressFunc && len >= 2000) {
3977
- currentPercentageDone = Math.floor(startingPercentageDone +
3978
- (opts.reportProgressFuncTo - startingPercentageDone) *
3979
- (applyPercDone / 100));
3980
- if (currentPercentageDone !== lastPercentage) {
3981
- lastPercentage = currentPercentageDone;
3982
- opts.reportProgressFunc(currentPercentageDone);
3983
- }
3984
- }
3985
- });
3986
- const resLen = res.length;
3987
- return {
3988
- log: {
3989
- timeTakenInMilliseconds: Date.now() - start,
3990
- originalLength: len,
3991
- cleanedLength: resLen,
3992
- bytesSaved: Math.max(len - resLen, 0),
3993
- percentageReducedOfOriginal: len
3994
- ? Math.round((Math.max(len - resLen, 0) * 100) / len)
3995
- : 0,
3996
- },
3997
- ranges,
3998
- applicableOpts,
3999
- result: res,
4000
- };
4001
- }
4002
- }
4003
- // ELSE - return the original input string
4004
- return {
4005
- log: {
4006
- timeTakenInMilliseconds: Date.now() - start,
4007
- originalLength: len,
4008
- cleanedLength: len,
4009
- bytesSaved: 0,
4010
- percentageReducedOfOriginal: 0,
4011
- },
4012
- applicableOpts,
4013
- ranges: null,
4014
- result: str,
4015
- };
4016
- }
4017
-
4018
- exports.crush = crush;
4019
- exports.defaults = defaults;
4020
- exports.version = version;
4021
-
4022
- Object.defineProperty(exports, '__esModule', { value: true });
4023
-
4024
- })));