• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import path$b from 'path';
2import require$$0$3, { realpathSync as realpathSync$1, statSync, Stats } from 'fs';
3import { URL as URL$1, fileURLToPath, pathToFileURL } from 'url';
4import process$2 from 'node:process';
5import stream, { PassThrough } from 'node:stream';
6import require$$0$2 from 'os';
7import tty$1 from 'tty';
8import require$$0$5 from 'events';
9import require$$0$4, { format as format$2, inspect as inspect$1 } from 'util';
10import require$$1 from 'stream';
11import path$c from 'node:path';
12import { pathToFileURL as pathToFileURL$1 } from 'node:url';
13import assert$2 from 'assert';
14import fs$a from 'node:fs';
15import { EventEmitter as EventEmitter$1 } from 'node:events';
16import process$1 from 'process';
17
18var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
19
20function getAugmentedNamespace(n) {
21	if (n.__esModule) return n;
22	var a = Object.defineProperty({}, '__esModule', {value: true});
23	Object.keys(n).forEach(function (k) {
24		var d = Object.getOwnPropertyDescriptor(n, k);
25		Object.defineProperty(a, k, d.get ? d : {
26			enumerable: true,
27			get: function () {
28				return n[k];
29			}
30		});
31	});
32	return a;
33}
34
35function commonjsRequire (path) {
36	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
37}
38
39var ansiStyles$2 = {exports: {}};
40
41var colorName$1 = {
42	"aliceblue": [240, 248, 255],
43	"antiquewhite": [250, 235, 215],
44	"aqua": [0, 255, 255],
45	"aquamarine": [127, 255, 212],
46	"azure": [240, 255, 255],
47	"beige": [245, 245, 220],
48	"bisque": [255, 228, 196],
49	"black": [0, 0, 0],
50	"blanchedalmond": [255, 235, 205],
51	"blue": [0, 0, 255],
52	"blueviolet": [138, 43, 226],
53	"brown": [165, 42, 42],
54	"burlywood": [222, 184, 135],
55	"cadetblue": [95, 158, 160],
56	"chartreuse": [127, 255, 0],
57	"chocolate": [210, 105, 30],
58	"coral": [255, 127, 80],
59	"cornflowerblue": [100, 149, 237],
60	"cornsilk": [255, 248, 220],
61	"crimson": [220, 20, 60],
62	"cyan": [0, 255, 255],
63	"darkblue": [0, 0, 139],
64	"darkcyan": [0, 139, 139],
65	"darkgoldenrod": [184, 134, 11],
66	"darkgray": [169, 169, 169],
67	"darkgreen": [0, 100, 0],
68	"darkgrey": [169, 169, 169],
69	"darkkhaki": [189, 183, 107],
70	"darkmagenta": [139, 0, 139],
71	"darkolivegreen": [85, 107, 47],
72	"darkorange": [255, 140, 0],
73	"darkorchid": [153, 50, 204],
74	"darkred": [139, 0, 0],
75	"darksalmon": [233, 150, 122],
76	"darkseagreen": [143, 188, 143],
77	"darkslateblue": [72, 61, 139],
78	"darkslategray": [47, 79, 79],
79	"darkslategrey": [47, 79, 79],
80	"darkturquoise": [0, 206, 209],
81	"darkviolet": [148, 0, 211],
82	"deeppink": [255, 20, 147],
83	"deepskyblue": [0, 191, 255],
84	"dimgray": [105, 105, 105],
85	"dimgrey": [105, 105, 105],
86	"dodgerblue": [30, 144, 255],
87	"firebrick": [178, 34, 34],
88	"floralwhite": [255, 250, 240],
89	"forestgreen": [34, 139, 34],
90	"fuchsia": [255, 0, 255],
91	"gainsboro": [220, 220, 220],
92	"ghostwhite": [248, 248, 255],
93	"gold": [255, 215, 0],
94	"goldenrod": [218, 165, 32],
95	"gray": [128, 128, 128],
96	"green": [0, 128, 0],
97	"greenyellow": [173, 255, 47],
98	"grey": [128, 128, 128],
99	"honeydew": [240, 255, 240],
100	"hotpink": [255, 105, 180],
101	"indianred": [205, 92, 92],
102	"indigo": [75, 0, 130],
103	"ivory": [255, 255, 240],
104	"khaki": [240, 230, 140],
105	"lavender": [230, 230, 250],
106	"lavenderblush": [255, 240, 245],
107	"lawngreen": [124, 252, 0],
108	"lemonchiffon": [255, 250, 205],
109	"lightblue": [173, 216, 230],
110	"lightcoral": [240, 128, 128],
111	"lightcyan": [224, 255, 255],
112	"lightgoldenrodyellow": [250, 250, 210],
113	"lightgray": [211, 211, 211],
114	"lightgreen": [144, 238, 144],
115	"lightgrey": [211, 211, 211],
116	"lightpink": [255, 182, 193],
117	"lightsalmon": [255, 160, 122],
118	"lightseagreen": [32, 178, 170],
119	"lightskyblue": [135, 206, 250],
120	"lightslategray": [119, 136, 153],
121	"lightslategrey": [119, 136, 153],
122	"lightsteelblue": [176, 196, 222],
123	"lightyellow": [255, 255, 224],
124	"lime": [0, 255, 0],
125	"limegreen": [50, 205, 50],
126	"linen": [250, 240, 230],
127	"magenta": [255, 0, 255],
128	"maroon": [128, 0, 0],
129	"mediumaquamarine": [102, 205, 170],
130	"mediumblue": [0, 0, 205],
131	"mediumorchid": [186, 85, 211],
132	"mediumpurple": [147, 112, 219],
133	"mediumseagreen": [60, 179, 113],
134	"mediumslateblue": [123, 104, 238],
135	"mediumspringgreen": [0, 250, 154],
136	"mediumturquoise": [72, 209, 204],
137	"mediumvioletred": [199, 21, 133],
138	"midnightblue": [25, 25, 112],
139	"mintcream": [245, 255, 250],
140	"mistyrose": [255, 228, 225],
141	"moccasin": [255, 228, 181],
142	"navajowhite": [255, 222, 173],
143	"navy": [0, 0, 128],
144	"oldlace": [253, 245, 230],
145	"olive": [128, 128, 0],
146	"olivedrab": [107, 142, 35],
147	"orange": [255, 165, 0],
148	"orangered": [255, 69, 0],
149	"orchid": [218, 112, 214],
150	"palegoldenrod": [238, 232, 170],
151	"palegreen": [152, 251, 152],
152	"paleturquoise": [175, 238, 238],
153	"palevioletred": [219, 112, 147],
154	"papayawhip": [255, 239, 213],
155	"peachpuff": [255, 218, 185],
156	"peru": [205, 133, 63],
157	"pink": [255, 192, 203],
158	"plum": [221, 160, 221],
159	"powderblue": [176, 224, 230],
160	"purple": [128, 0, 128],
161	"rebeccapurple": [102, 51, 153],
162	"red": [255, 0, 0],
163	"rosybrown": [188, 143, 143],
164	"royalblue": [65, 105, 225],
165	"saddlebrown": [139, 69, 19],
166	"salmon": [250, 128, 114],
167	"sandybrown": [244, 164, 96],
168	"seagreen": [46, 139, 87],
169	"seashell": [255, 245, 238],
170	"sienna": [160, 82, 45],
171	"silver": [192, 192, 192],
172	"skyblue": [135, 206, 235],
173	"slateblue": [106, 90, 205],
174	"slategray": [112, 128, 144],
175	"slategrey": [112, 128, 144],
176	"snow": [255, 250, 250],
177	"springgreen": [0, 255, 127],
178	"steelblue": [70, 130, 180],
179	"tan": [210, 180, 140],
180	"teal": [0, 128, 128],
181	"thistle": [216, 191, 216],
182	"tomato": [255, 99, 71],
183	"turquoise": [64, 224, 208],
184	"violet": [238, 130, 238],
185	"wheat": [245, 222, 179],
186	"white": [255, 255, 255],
187	"whitesmoke": [245, 245, 245],
188	"yellow": [255, 255, 0],
189	"yellowgreen": [154, 205, 50]
190};
191
192/* MIT license */
193
194/* eslint-disable no-mixed-operators */
195const cssKeywords$1 = colorName$1;
196
197// NOTE: conversions should only return primitive values (i.e. arrays, or
198//       values that give correct `typeof` results).
199//       do not use box values types (i.e. Number(), String(), etc.)
200
201const reverseKeywords$1 = {};
202for (const key of Object.keys(cssKeywords$1)) {
203	reverseKeywords$1[cssKeywords$1[key]] = key;
204}
205
206const convert$4 = {
207	rgb: {channels: 3, labels: 'rgb'},
208	hsl: {channels: 3, labels: 'hsl'},
209	hsv: {channels: 3, labels: 'hsv'},
210	hwb: {channels: 3, labels: 'hwb'},
211	cmyk: {channels: 4, labels: 'cmyk'},
212	xyz: {channels: 3, labels: 'xyz'},
213	lab: {channels: 3, labels: 'lab'},
214	lch: {channels: 3, labels: 'lch'},
215	hex: {channels: 1, labels: ['hex']},
216	keyword: {channels: 1, labels: ['keyword']},
217	ansi16: {channels: 1, labels: ['ansi16']},
218	ansi256: {channels: 1, labels: ['ansi256']},
219	hcg: {channels: 3, labels: ['h', 'c', 'g']},
220	apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
221	gray: {channels: 1, labels: ['gray']}
222};
223
224var conversions$5 = convert$4;
225
226// Hide .channels and .labels properties
227for (const model of Object.keys(convert$4)) {
228	if (!('channels' in convert$4[model])) {
229		throw new Error('missing channels property: ' + model);
230	}
231
232	if (!('labels' in convert$4[model])) {
233		throw new Error('missing channel labels property: ' + model);
234	}
235
236	if (convert$4[model].labels.length !== convert$4[model].channels) {
237		throw new Error('channel and label counts mismatch: ' + model);
238	}
239
240	const {channels, labels} = convert$4[model];
241	delete convert$4[model].channels;
242	delete convert$4[model].labels;
243	Object.defineProperty(convert$4[model], 'channels', {value: channels});
244	Object.defineProperty(convert$4[model], 'labels', {value: labels});
245}
246
247convert$4.rgb.hsl = function (rgb) {
248	const r = rgb[0] / 255;
249	const g = rgb[1] / 255;
250	const b = rgb[2] / 255;
251	const min = Math.min(r, g, b);
252	const max = Math.max(r, g, b);
253	const delta = max - min;
254	let h;
255	let s;
256
257	if (max === min) {
258		h = 0;
259	} else if (r === max) {
260		h = (g - b) / delta;
261	} else if (g === max) {
262		h = 2 + (b - r) / delta;
263	} else if (b === max) {
264		h = 4 + (r - g) / delta;
265	}
266
267	h = Math.min(h * 60, 360);
268
269	if (h < 0) {
270		h += 360;
271	}
272
273	const l = (min + max) / 2;
274
275	if (max === min) {
276		s = 0;
277	} else if (l <= 0.5) {
278		s = delta / (max + min);
279	} else {
280		s = delta / (2 - max - min);
281	}
282
283	return [h, s * 100, l * 100];
284};
285
286convert$4.rgb.hsv = function (rgb) {
287	let rdif;
288	let gdif;
289	let bdif;
290	let h;
291	let s;
292
293	const r = rgb[0] / 255;
294	const g = rgb[1] / 255;
295	const b = rgb[2] / 255;
296	const v = Math.max(r, g, b);
297	const diff = v - Math.min(r, g, b);
298	const diffc = function (c) {
299		return (v - c) / 6 / diff + 1 / 2;
300	};
301
302	if (diff === 0) {
303		h = 0;
304		s = 0;
305	} else {
306		s = diff / v;
307		rdif = diffc(r);
308		gdif = diffc(g);
309		bdif = diffc(b);
310
311		if (r === v) {
312			h = bdif - gdif;
313		} else if (g === v) {
314			h = (1 / 3) + rdif - bdif;
315		} else if (b === v) {
316			h = (2 / 3) + gdif - rdif;
317		}
318
319		if (h < 0) {
320			h += 1;
321		} else if (h > 1) {
322			h -= 1;
323		}
324	}
325
326	return [
327		h * 360,
328		s * 100,
329		v * 100
330	];
331};
332
333convert$4.rgb.hwb = function (rgb) {
334	const r = rgb[0];
335	const g = rgb[1];
336	let b = rgb[2];
337	const h = convert$4.rgb.hsl(rgb)[0];
338	const w = 1 / 255 * Math.min(r, Math.min(g, b));
339
340	b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
341
342	return [h, w * 100, b * 100];
343};
344
345convert$4.rgb.cmyk = function (rgb) {
346	const r = rgb[0] / 255;
347	const g = rgb[1] / 255;
348	const b = rgb[2] / 255;
349
350	const k = Math.min(1 - r, 1 - g, 1 - b);
351	const c = (1 - r - k) / (1 - k) || 0;
352	const m = (1 - g - k) / (1 - k) || 0;
353	const y = (1 - b - k) / (1 - k) || 0;
354
355	return [c * 100, m * 100, y * 100, k * 100];
356};
357
358function comparativeDistance$1(x, y) {
359	/*
360		See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
361	*/
362	return (
363		((x[0] - y[0]) ** 2) +
364		((x[1] - y[1]) ** 2) +
365		((x[2] - y[2]) ** 2)
366	);
367}
368
369convert$4.rgb.keyword = function (rgb) {
370	const reversed = reverseKeywords$1[rgb];
371	if (reversed) {
372		return reversed;
373	}
374
375	let currentClosestDistance = Infinity;
376	let currentClosestKeyword;
377
378	for (const keyword of Object.keys(cssKeywords$1)) {
379		const value = cssKeywords$1[keyword];
380
381		// Compute comparative distance
382		const distance = comparativeDistance$1(rgb, value);
383
384		// Check if its less, if so set as closest
385		if (distance < currentClosestDistance) {
386			currentClosestDistance = distance;
387			currentClosestKeyword = keyword;
388		}
389	}
390
391	return currentClosestKeyword;
392};
393
394convert$4.keyword.rgb = function (keyword) {
395	return cssKeywords$1[keyword];
396};
397
398convert$4.rgb.xyz = function (rgb) {
399	let r = rgb[0] / 255;
400	let g = rgb[1] / 255;
401	let b = rgb[2] / 255;
402
403	// Assume sRGB
404	r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
405	g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
406	b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
407
408	const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
409	const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
410	const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
411
412	return [x * 100, y * 100, z * 100];
413};
414
415convert$4.rgb.lab = function (rgb) {
416	const xyz = convert$4.rgb.xyz(rgb);
417	let x = xyz[0];
418	let y = xyz[1];
419	let z = xyz[2];
420
421	x /= 95.047;
422	y /= 100;
423	z /= 108.883;
424
425	x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
426	y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
427	z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
428
429	const l = (116 * y) - 16;
430	const a = 500 * (x - y);
431	const b = 200 * (y - z);
432
433	return [l, a, b];
434};
435
436convert$4.hsl.rgb = function (hsl) {
437	const h = hsl[0] / 360;
438	const s = hsl[1] / 100;
439	const l = hsl[2] / 100;
440	let t2;
441	let t3;
442	let val;
443
444	if (s === 0) {
445		val = l * 255;
446		return [val, val, val];
447	}
448
449	if (l < 0.5) {
450		t2 = l * (1 + s);
451	} else {
452		t2 = l + s - l * s;
453	}
454
455	const t1 = 2 * l - t2;
456
457	const rgb = [0, 0, 0];
458	for (let i = 0; i < 3; i++) {
459		t3 = h + 1 / 3 * -(i - 1);
460		if (t3 < 0) {
461			t3++;
462		}
463
464		if (t3 > 1) {
465			t3--;
466		}
467
468		if (6 * t3 < 1) {
469			val = t1 + (t2 - t1) * 6 * t3;
470		} else if (2 * t3 < 1) {
471			val = t2;
472		} else if (3 * t3 < 2) {
473			val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
474		} else {
475			val = t1;
476		}
477
478		rgb[i] = val * 255;
479	}
480
481	return rgb;
482};
483
484convert$4.hsl.hsv = function (hsl) {
485	const h = hsl[0];
486	let s = hsl[1] / 100;
487	let l = hsl[2] / 100;
488	let smin = s;
489	const lmin = Math.max(l, 0.01);
490
491	l *= 2;
492	s *= (l <= 1) ? l : 2 - l;
493	smin *= lmin <= 1 ? lmin : 2 - lmin;
494	const v = (l + s) / 2;
495	const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
496
497	return [h, sv * 100, v * 100];
498};
499
500convert$4.hsv.rgb = function (hsv) {
501	const h = hsv[0] / 60;
502	const s = hsv[1] / 100;
503	let v = hsv[2] / 100;
504	const hi = Math.floor(h) % 6;
505
506	const f = h - Math.floor(h);
507	const p = 255 * v * (1 - s);
508	const q = 255 * v * (1 - (s * f));
509	const t = 255 * v * (1 - (s * (1 - f)));
510	v *= 255;
511
512	switch (hi) {
513		case 0:
514			return [v, t, p];
515		case 1:
516			return [q, v, p];
517		case 2:
518			return [p, v, t];
519		case 3:
520			return [p, q, v];
521		case 4:
522			return [t, p, v];
523		case 5:
524			return [v, p, q];
525	}
526};
527
528convert$4.hsv.hsl = function (hsv) {
529	const h = hsv[0];
530	const s = hsv[1] / 100;
531	const v = hsv[2] / 100;
532	const vmin = Math.max(v, 0.01);
533	let sl;
534	let l;
535
536	l = (2 - s) * v;
537	const lmin = (2 - s) * vmin;
538	sl = s * vmin;
539	sl /= (lmin <= 1) ? lmin : 2 - lmin;
540	sl = sl || 0;
541	l /= 2;
542
543	return [h, sl * 100, l * 100];
544};
545
546// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
547convert$4.hwb.rgb = function (hwb) {
548	const h = hwb[0] / 360;
549	let wh = hwb[1] / 100;
550	let bl = hwb[2] / 100;
551	const ratio = wh + bl;
552	let f;
553
554	// Wh + bl cant be > 1
555	if (ratio > 1) {
556		wh /= ratio;
557		bl /= ratio;
558	}
559
560	const i = Math.floor(6 * h);
561	const v = 1 - bl;
562	f = 6 * h - i;
563
564	if ((i & 0x01) !== 0) {
565		f = 1 - f;
566	}
567
568	const n = wh + f * (v - wh); // Linear interpolation
569
570	let r;
571	let g;
572	let b;
573	/* eslint-disable max-statements-per-line,no-multi-spaces */
574	switch (i) {
575		default:
576		case 6:
577		case 0: r = v;  g = n;  b = wh; break;
578		case 1: r = n;  g = v;  b = wh; break;
579		case 2: r = wh; g = v;  b = n; break;
580		case 3: r = wh; g = n;  b = v; break;
581		case 4: r = n;  g = wh; b = v; break;
582		case 5: r = v;  g = wh; b = n; break;
583	}
584	/* eslint-enable max-statements-per-line,no-multi-spaces */
585
586	return [r * 255, g * 255, b * 255];
587};
588
589convert$4.cmyk.rgb = function (cmyk) {
590	const c = cmyk[0] / 100;
591	const m = cmyk[1] / 100;
592	const y = cmyk[2] / 100;
593	const k = cmyk[3] / 100;
594
595	const r = 1 - Math.min(1, c * (1 - k) + k);
596	const g = 1 - Math.min(1, m * (1 - k) + k);
597	const b = 1 - Math.min(1, y * (1 - k) + k);
598
599	return [r * 255, g * 255, b * 255];
600};
601
602convert$4.xyz.rgb = function (xyz) {
603	const x = xyz[0] / 100;
604	const y = xyz[1] / 100;
605	const z = xyz[2] / 100;
606	let r;
607	let g;
608	let b;
609
610	r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
611	g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
612	b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
613
614	// Assume sRGB
615	r = r > 0.0031308
616		? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
617		: r * 12.92;
618
619	g = g > 0.0031308
620		? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
621		: g * 12.92;
622
623	b = b > 0.0031308
624		? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
625		: b * 12.92;
626
627	r = Math.min(Math.max(0, r), 1);
628	g = Math.min(Math.max(0, g), 1);
629	b = Math.min(Math.max(0, b), 1);
630
631	return [r * 255, g * 255, b * 255];
632};
633
634convert$4.xyz.lab = function (xyz) {
635	let x = xyz[0];
636	let y = xyz[1];
637	let z = xyz[2];
638
639	x /= 95.047;
640	y /= 100;
641	z /= 108.883;
642
643	x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
644	y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
645	z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
646
647	const l = (116 * y) - 16;
648	const a = 500 * (x - y);
649	const b = 200 * (y - z);
650
651	return [l, a, b];
652};
653
654convert$4.lab.xyz = function (lab) {
655	const l = lab[0];
656	const a = lab[1];
657	const b = lab[2];
658	let x;
659	let y;
660	let z;
661
662	y = (l + 16) / 116;
663	x = a / 500 + y;
664	z = y - b / 200;
665
666	const y2 = y ** 3;
667	const x2 = x ** 3;
668	const z2 = z ** 3;
669	y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
670	x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
671	z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
672
673	x *= 95.047;
674	y *= 100;
675	z *= 108.883;
676
677	return [x, y, z];
678};
679
680convert$4.lab.lch = function (lab) {
681	const l = lab[0];
682	const a = lab[1];
683	const b = lab[2];
684	let h;
685
686	const hr = Math.atan2(b, a);
687	h = hr * 360 / 2 / Math.PI;
688
689	if (h < 0) {
690		h += 360;
691	}
692
693	const c = Math.sqrt(a * a + b * b);
694
695	return [l, c, h];
696};
697
698convert$4.lch.lab = function (lch) {
699	const l = lch[0];
700	const c = lch[1];
701	const h = lch[2];
702
703	const hr = h / 360 * 2 * Math.PI;
704	const a = c * Math.cos(hr);
705	const b = c * Math.sin(hr);
706
707	return [l, a, b];
708};
709
710convert$4.rgb.ansi16 = function (args, saturation = null) {
711	const [r, g, b] = args;
712	let value = saturation === null ? convert$4.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
713
714	value = Math.round(value / 50);
715
716	if (value === 0) {
717		return 30;
718	}
719
720	let ansi = 30
721		+ ((Math.round(b / 255) << 2)
722		| (Math.round(g / 255) << 1)
723		| Math.round(r / 255));
724
725	if (value === 2) {
726		ansi += 60;
727	}
728
729	return ansi;
730};
731
732convert$4.hsv.ansi16 = function (args) {
733	// Optimization here; we already know the value and don't need to get
734	// it converted for us.
735	return convert$4.rgb.ansi16(convert$4.hsv.rgb(args), args[2]);
736};
737
738convert$4.rgb.ansi256 = function (args) {
739	const r = args[0];
740	const g = args[1];
741	const b = args[2];
742
743	// We use the extended greyscale palette here, with the exception of
744	// black and white. normal palette only has 4 greyscale shades.
745	if (r === g && g === b) {
746		if (r < 8) {
747			return 16;
748		}
749
750		if (r > 248) {
751			return 231;
752		}
753
754		return Math.round(((r - 8) / 247) * 24) + 232;
755	}
756
757	const ansi = 16
758		+ (36 * Math.round(r / 255 * 5))
759		+ (6 * Math.round(g / 255 * 5))
760		+ Math.round(b / 255 * 5);
761
762	return ansi;
763};
764
765convert$4.ansi16.rgb = function (args) {
766	let color = args % 10;
767
768	// Handle greyscale
769	if (color === 0 || color === 7) {
770		if (args > 50) {
771			color += 3.5;
772		}
773
774		color = color / 10.5 * 255;
775
776		return [color, color, color];
777	}
778
779	const mult = (~~(args > 50) + 1) * 0.5;
780	const r = ((color & 1) * mult) * 255;
781	const g = (((color >> 1) & 1) * mult) * 255;
782	const b = (((color >> 2) & 1) * mult) * 255;
783
784	return [r, g, b];
785};
786
787convert$4.ansi256.rgb = function (args) {
788	// Handle greyscale
789	if (args >= 232) {
790		const c = (args - 232) * 10 + 8;
791		return [c, c, c];
792	}
793
794	args -= 16;
795
796	let rem;
797	const r = Math.floor(args / 36) / 5 * 255;
798	const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
799	const b = (rem % 6) / 5 * 255;
800
801	return [r, g, b];
802};
803
804convert$4.rgb.hex = function (args) {
805	const integer = ((Math.round(args[0]) & 0xFF) << 16)
806		+ ((Math.round(args[1]) & 0xFF) << 8)
807		+ (Math.round(args[2]) & 0xFF);
808
809	const string = integer.toString(16).toUpperCase();
810	return '000000'.substring(string.length) + string;
811};
812
813convert$4.hex.rgb = function (args) {
814	const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
815	if (!match) {
816		return [0, 0, 0];
817	}
818
819	let colorString = match[0];
820
821	if (match[0].length === 3) {
822		colorString = colorString.split('').map(char => {
823			return char + char;
824		}).join('');
825	}
826
827	const integer = parseInt(colorString, 16);
828	const r = (integer >> 16) & 0xFF;
829	const g = (integer >> 8) & 0xFF;
830	const b = integer & 0xFF;
831
832	return [r, g, b];
833};
834
835convert$4.rgb.hcg = function (rgb) {
836	const r = rgb[0] / 255;
837	const g = rgb[1] / 255;
838	const b = rgb[2] / 255;
839	const max = Math.max(Math.max(r, g), b);
840	const min = Math.min(Math.min(r, g), b);
841	const chroma = (max - min);
842	let grayscale;
843	let hue;
844
845	if (chroma < 1) {
846		grayscale = min / (1 - chroma);
847	} else {
848		grayscale = 0;
849	}
850
851	if (chroma <= 0) {
852		hue = 0;
853	} else
854	if (max === r) {
855		hue = ((g - b) / chroma) % 6;
856	} else
857	if (max === g) {
858		hue = 2 + (b - r) / chroma;
859	} else {
860		hue = 4 + (r - g) / chroma;
861	}
862
863	hue /= 6;
864	hue %= 1;
865
866	return [hue * 360, chroma * 100, grayscale * 100];
867};
868
869convert$4.hsl.hcg = function (hsl) {
870	const s = hsl[1] / 100;
871	const l = hsl[2] / 100;
872
873	const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
874
875	let f = 0;
876	if (c < 1.0) {
877		f = (l - 0.5 * c) / (1.0 - c);
878	}
879
880	return [hsl[0], c * 100, f * 100];
881};
882
883convert$4.hsv.hcg = function (hsv) {
884	const s = hsv[1] / 100;
885	const v = hsv[2] / 100;
886
887	const c = s * v;
888	let f = 0;
889
890	if (c < 1.0) {
891		f = (v - c) / (1 - c);
892	}
893
894	return [hsv[0], c * 100, f * 100];
895};
896
897convert$4.hcg.rgb = function (hcg) {
898	const h = hcg[0] / 360;
899	const c = hcg[1] / 100;
900	const g = hcg[2] / 100;
901
902	if (c === 0.0) {
903		return [g * 255, g * 255, g * 255];
904	}
905
906	const pure = [0, 0, 0];
907	const hi = (h % 1) * 6;
908	const v = hi % 1;
909	const w = 1 - v;
910	let mg = 0;
911
912	/* eslint-disable max-statements-per-line */
913	switch (Math.floor(hi)) {
914		case 0:
915			pure[0] = 1; pure[1] = v; pure[2] = 0; break;
916		case 1:
917			pure[0] = w; pure[1] = 1; pure[2] = 0; break;
918		case 2:
919			pure[0] = 0; pure[1] = 1; pure[2] = v; break;
920		case 3:
921			pure[0] = 0; pure[1] = w; pure[2] = 1; break;
922		case 4:
923			pure[0] = v; pure[1] = 0; pure[2] = 1; break;
924		default:
925			pure[0] = 1; pure[1] = 0; pure[2] = w;
926	}
927	/* eslint-enable max-statements-per-line */
928
929	mg = (1.0 - c) * g;
930
931	return [
932		(c * pure[0] + mg) * 255,
933		(c * pure[1] + mg) * 255,
934		(c * pure[2] + mg) * 255
935	];
936};
937
938convert$4.hcg.hsv = function (hcg) {
939	const c = hcg[1] / 100;
940	const g = hcg[2] / 100;
941
942	const v = c + g * (1.0 - c);
943	let f = 0;
944
945	if (v > 0.0) {
946		f = c / v;
947	}
948
949	return [hcg[0], f * 100, v * 100];
950};
951
952convert$4.hcg.hsl = function (hcg) {
953	const c = hcg[1] / 100;
954	const g = hcg[2] / 100;
955
956	const l = g * (1.0 - c) + 0.5 * c;
957	let s = 0;
958
959	if (l > 0.0 && l < 0.5) {
960		s = c / (2 * l);
961	} else
962	if (l >= 0.5 && l < 1.0) {
963		s = c / (2 * (1 - l));
964	}
965
966	return [hcg[0], s * 100, l * 100];
967};
968
969convert$4.hcg.hwb = function (hcg) {
970	const c = hcg[1] / 100;
971	const g = hcg[2] / 100;
972	const v = c + g * (1.0 - c);
973	return [hcg[0], (v - c) * 100, (1 - v) * 100];
974};
975
976convert$4.hwb.hcg = function (hwb) {
977	const w = hwb[1] / 100;
978	const b = hwb[2] / 100;
979	const v = 1 - b;
980	const c = v - w;
981	let g = 0;
982
983	if (c < 1) {
984		g = (v - c) / (1 - c);
985	}
986
987	return [hwb[0], c * 100, g * 100];
988};
989
990convert$4.apple.rgb = function (apple) {
991	return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
992};
993
994convert$4.rgb.apple = function (rgb) {
995	return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
996};
997
998convert$4.gray.rgb = function (args) {
999	return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
1000};
1001
1002convert$4.gray.hsl = function (args) {
1003	return [0, 0, args[0]];
1004};
1005
1006convert$4.gray.hsv = convert$4.gray.hsl;
1007
1008convert$4.gray.hwb = function (gray) {
1009	return [0, 100, gray[0]];
1010};
1011
1012convert$4.gray.cmyk = function (gray) {
1013	return [0, 0, 0, gray[0]];
1014};
1015
1016convert$4.gray.lab = function (gray) {
1017	return [gray[0], 0, 0];
1018};
1019
1020convert$4.gray.hex = function (gray) {
1021	const val = Math.round(gray[0] / 100 * 255) & 0xFF;
1022	const integer = (val << 16) + (val << 8) + val;
1023
1024	const string = integer.toString(16).toUpperCase();
1025	return '000000'.substring(string.length) + string;
1026};
1027
1028convert$4.rgb.gray = function (rgb) {
1029	const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1030	return [val / 255 * 100];
1031};
1032
1033const conversions$4 = conversions$5;
1034
1035/*
1036	This function routes a model to all other models.
1037
1038	all functions that are routed have a property `.conversion` attached
1039	to the returned synthetic function. This property is an array
1040	of strings, each with the steps in between the 'from' and 'to'
1041	color models (inclusive).
1042
1043	conversions that are not possible simply are not included.
1044*/
1045
1046function buildGraph$1() {
1047	const graph = {};
1048	// https://jsperf.com/object-keys-vs-for-in-with-closure/3
1049	const models = Object.keys(conversions$4);
1050
1051	for (let len = models.length, i = 0; i < len; i++) {
1052		graph[models[i]] = {
1053			// http://jsperf.com/1-vs-infinity
1054			// micro-opt, but this is simple.
1055			distance: -1,
1056			parent: null
1057		};
1058	}
1059
1060	return graph;
1061}
1062
1063// https://en.wikipedia.org/wiki/Breadth-first_search
1064function deriveBFS$1(fromModel) {
1065	const graph = buildGraph$1();
1066	const queue = [fromModel]; // Unshift -> queue -> pop
1067
1068	graph[fromModel].distance = 0;
1069
1070	while (queue.length) {
1071		const current = queue.pop();
1072		const adjacents = Object.keys(conversions$4[current]);
1073
1074		for (let len = adjacents.length, i = 0; i < len; i++) {
1075			const adjacent = adjacents[i];
1076			const node = graph[adjacent];
1077
1078			if (node.distance === -1) {
1079				node.distance = graph[current].distance + 1;
1080				node.parent = current;
1081				queue.unshift(adjacent);
1082			}
1083		}
1084	}
1085
1086	return graph;
1087}
1088
1089function link$2(from, to) {
1090	return function (args) {
1091		return to(from(args));
1092	};
1093}
1094
1095function wrapConversion$1(toModel, graph) {
1096	const path = [graph[toModel].parent, toModel];
1097	let fn = conversions$4[graph[toModel].parent][toModel];
1098
1099	let cur = graph[toModel].parent;
1100	while (graph[cur].parent) {
1101		path.unshift(graph[cur].parent);
1102		fn = link$2(conversions$4[graph[cur].parent][cur], fn);
1103		cur = graph[cur].parent;
1104	}
1105
1106	fn.conversion = path;
1107	return fn;
1108}
1109
1110var route$3 = function (fromModel) {
1111	const graph = deriveBFS$1(fromModel);
1112	const conversion = {};
1113
1114	const models = Object.keys(graph);
1115	for (let len = models.length, i = 0; i < len; i++) {
1116		const toModel = models[i];
1117		const node = graph[toModel];
1118
1119		if (node.parent === null) {
1120			// No possible conversion, or this node is the source model.
1121			continue;
1122		}
1123
1124		conversion[toModel] = wrapConversion$1(toModel, graph);
1125	}
1126
1127	return conversion;
1128};
1129
1130const conversions$3 = conversions$5;
1131const route$2 = route$3;
1132
1133const convert$3 = {};
1134
1135const models$1 = Object.keys(conversions$3);
1136
1137function wrapRaw$1(fn) {
1138	const wrappedFn = function (...args) {
1139		const arg0 = args[0];
1140		if (arg0 === undefined || arg0 === null) {
1141			return arg0;
1142		}
1143
1144		if (arg0.length > 1) {
1145			args = arg0;
1146		}
1147
1148		return fn(args);
1149	};
1150
1151	// Preserve .conversion property if there is one
1152	if ('conversion' in fn) {
1153		wrappedFn.conversion = fn.conversion;
1154	}
1155
1156	return wrappedFn;
1157}
1158
1159function wrapRounded$1(fn) {
1160	const wrappedFn = function (...args) {
1161		const arg0 = args[0];
1162
1163		if (arg0 === undefined || arg0 === null) {
1164			return arg0;
1165		}
1166
1167		if (arg0.length > 1) {
1168			args = arg0;
1169		}
1170
1171		const result = fn(args);
1172
1173		// We're assuming the result is an array here.
1174		// see notice in conversions.js; don't use box types
1175		// in conversion functions.
1176		if (typeof result === 'object') {
1177			for (let len = result.length, i = 0; i < len; i++) {
1178				result[i] = Math.round(result[i]);
1179			}
1180		}
1181
1182		return result;
1183	};
1184
1185	// Preserve .conversion property if there is one
1186	if ('conversion' in fn) {
1187		wrappedFn.conversion = fn.conversion;
1188	}
1189
1190	return wrappedFn;
1191}
1192
1193models$1.forEach(fromModel => {
1194	convert$3[fromModel] = {};
1195
1196	Object.defineProperty(convert$3[fromModel], 'channels', {value: conversions$3[fromModel].channels});
1197	Object.defineProperty(convert$3[fromModel], 'labels', {value: conversions$3[fromModel].labels});
1198
1199	const routes = route$2(fromModel);
1200	const routeModels = Object.keys(routes);
1201
1202	routeModels.forEach(toModel => {
1203		const fn = routes[toModel];
1204
1205		convert$3[fromModel][toModel] = wrapRounded$1(fn);
1206		convert$3[fromModel][toModel].raw = wrapRaw$1(fn);
1207	});
1208});
1209
1210var colorConvert$1 = convert$3;
1211
1212(function (module) {
1213
1214const wrapAnsi16 = (fn, offset) => (...args) => {
1215	const code = fn(...args);
1216	return `\u001B[${code + offset}m`;
1217};
1218
1219const wrapAnsi256 = (fn, offset) => (...args) => {
1220	const code = fn(...args);
1221	return `\u001B[${38 + offset};5;${code}m`;
1222};
1223
1224const wrapAnsi16m = (fn, offset) => (...args) => {
1225	const rgb = fn(...args);
1226	return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
1227};
1228
1229const ansi2ansi = n => n;
1230const rgb2rgb = (r, g, b) => [r, g, b];
1231
1232const setLazyProperty = (object, property, get) => {
1233	Object.defineProperty(object, property, {
1234		get: () => {
1235			const value = get();
1236
1237			Object.defineProperty(object, property, {
1238				value,
1239				enumerable: true,
1240				configurable: true
1241			});
1242
1243			return value;
1244		},
1245		enumerable: true,
1246		configurable: true
1247	});
1248};
1249
1250/** @type {typeof import('color-convert')} */
1251let colorConvert;
1252const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
1253	if (colorConvert === undefined) {
1254		colorConvert = colorConvert$1;
1255	}
1256
1257	const offset = isBackground ? 10 : 0;
1258	const styles = {};
1259
1260	for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
1261		const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
1262		if (sourceSpace === targetSpace) {
1263			styles[name] = wrap(identity, offset);
1264		} else if (typeof suite === 'object') {
1265			styles[name] = wrap(suite[targetSpace], offset);
1266		}
1267	}
1268
1269	return styles;
1270};
1271
1272function assembleStyles() {
1273	const codes = new Map();
1274	const styles = {
1275		modifier: {
1276			reset: [0, 0],
1277			// 21 isn't widely supported and 22 does the same thing
1278			bold: [1, 22],
1279			dim: [2, 22],
1280			italic: [3, 23],
1281			underline: [4, 24],
1282			inverse: [7, 27],
1283			hidden: [8, 28],
1284			strikethrough: [9, 29]
1285		},
1286		color: {
1287			black: [30, 39],
1288			red: [31, 39],
1289			green: [32, 39],
1290			yellow: [33, 39],
1291			blue: [34, 39],
1292			magenta: [35, 39],
1293			cyan: [36, 39],
1294			white: [37, 39],
1295
1296			// Bright color
1297			blackBright: [90, 39],
1298			redBright: [91, 39],
1299			greenBright: [92, 39],
1300			yellowBright: [93, 39],
1301			blueBright: [94, 39],
1302			magentaBright: [95, 39],
1303			cyanBright: [96, 39],
1304			whiteBright: [97, 39]
1305		},
1306		bgColor: {
1307			bgBlack: [40, 49],
1308			bgRed: [41, 49],
1309			bgGreen: [42, 49],
1310			bgYellow: [43, 49],
1311			bgBlue: [44, 49],
1312			bgMagenta: [45, 49],
1313			bgCyan: [46, 49],
1314			bgWhite: [47, 49],
1315
1316			// Bright color
1317			bgBlackBright: [100, 49],
1318			bgRedBright: [101, 49],
1319			bgGreenBright: [102, 49],
1320			bgYellowBright: [103, 49],
1321			bgBlueBright: [104, 49],
1322			bgMagentaBright: [105, 49],
1323			bgCyanBright: [106, 49],
1324			bgWhiteBright: [107, 49]
1325		}
1326	};
1327
1328	// Alias bright black as gray (and grey)
1329	styles.color.gray = styles.color.blackBright;
1330	styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
1331	styles.color.grey = styles.color.blackBright;
1332	styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
1333
1334	for (const [groupName, group] of Object.entries(styles)) {
1335		for (const [styleName, style] of Object.entries(group)) {
1336			styles[styleName] = {
1337				open: `\u001B[${style[0]}m`,
1338				close: `\u001B[${style[1]}m`
1339			};
1340
1341			group[styleName] = styles[styleName];
1342
1343			codes.set(style[0], style[1]);
1344		}
1345
1346		Object.defineProperty(styles, groupName, {
1347			value: group,
1348			enumerable: false
1349		});
1350	}
1351
1352	Object.defineProperty(styles, 'codes', {
1353		value: codes,
1354		enumerable: false
1355	});
1356
1357	styles.color.close = '\u001B[39m';
1358	styles.bgColor.close = '\u001B[49m';
1359
1360	setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
1361	setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
1362	setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
1363	setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
1364	setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
1365	setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
1366
1367	return styles;
1368}
1369
1370// Make the export immutable
1371Object.defineProperty(module, 'exports', {
1372	enumerable: true,
1373	get: assembleStyles
1374});
1375}(ansiStyles$2));
1376
1377var hasFlag$4 = (flag, argv = process.argv) => {
1378	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
1379	const position = argv.indexOf(prefix + flag);
1380	const terminatorPosition = argv.indexOf('--');
1381	return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1382};
1383
1384const os$2 = require$$0$2;
1385const tty = tty$1;
1386const hasFlag$3 = hasFlag$4;
1387
1388const {env: env$2} = process;
1389
1390let forceColor$1;
1391if (hasFlag$3('no-color') ||
1392	hasFlag$3('no-colors') ||
1393	hasFlag$3('color=false') ||
1394	hasFlag$3('color=never')) {
1395	forceColor$1 = 0;
1396} else if (hasFlag$3('color') ||
1397	hasFlag$3('colors') ||
1398	hasFlag$3('color=true') ||
1399	hasFlag$3('color=always')) {
1400	forceColor$1 = 1;
1401}
1402
1403if ('FORCE_COLOR' in env$2) {
1404	if (env$2.FORCE_COLOR === 'true') {
1405		forceColor$1 = 1;
1406	} else if (env$2.FORCE_COLOR === 'false') {
1407		forceColor$1 = 0;
1408	} else {
1409		forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3);
1410	}
1411}
1412
1413function translateLevel$2(level) {
1414	if (level === 0) {
1415		return false;
1416	}
1417
1418	return {
1419		level,
1420		hasBasic: true,
1421		has256: level >= 2,
1422		has16m: level >= 3
1423	};
1424}
1425
1426function supportsColor$2(haveStream, streamIsTTY) {
1427	if (forceColor$1 === 0) {
1428		return 0;
1429	}
1430
1431	if (hasFlag$3('color=16m') ||
1432		hasFlag$3('color=full') ||
1433		hasFlag$3('color=truecolor')) {
1434		return 3;
1435	}
1436
1437	if (hasFlag$3('color=256')) {
1438		return 2;
1439	}
1440
1441	if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
1442		return 0;
1443	}
1444
1445	const min = forceColor$1 || 0;
1446
1447	if (env$2.TERM === 'dumb') {
1448		return min;
1449	}
1450
1451	if (process.platform === 'win32') {
1452		// Windows 10 build 10586 is the first Windows release that supports 256 colors.
1453		// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
1454		const osRelease = os$2.release().split('.');
1455		if (
1456			Number(osRelease[0]) >= 10 &&
1457			Number(osRelease[2]) >= 10586
1458		) {
1459			return Number(osRelease[2]) >= 14931 ? 3 : 2;
1460		}
1461
1462		return 1;
1463	}
1464
1465	if ('CI' in env$2) {
1466		if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
1467			return 1;
1468		}
1469
1470		return min;
1471	}
1472
1473	if ('TEAMCITY_VERSION' in env$2) {
1474		return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
1475	}
1476
1477	if (env$2.COLORTERM === 'truecolor') {
1478		return 3;
1479	}
1480
1481	if ('TERM_PROGRAM' in env$2) {
1482		const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
1483
1484		switch (env$2.TERM_PROGRAM) {
1485			case 'iTerm.app':
1486				return version >= 3 ? 3 : 2;
1487			case 'Apple_Terminal':
1488				return 2;
1489			// No default
1490		}
1491	}
1492
1493	if (/-256(color)?$/i.test(env$2.TERM)) {
1494		return 2;
1495	}
1496
1497	if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
1498		return 1;
1499	}
1500
1501	if ('COLORTERM' in env$2) {
1502		return 1;
1503	}
1504
1505	return min;
1506}
1507
1508function getSupportLevel$1(stream) {
1509	const level = supportsColor$2(stream, stream && stream.isTTY);
1510	return translateLevel$2(level);
1511}
1512
1513var supportsColor_1$1 = {
1514	supportsColor: getSupportLevel$1,
1515	stdout: translateLevel$2(supportsColor$2(true, tty.isatty(1))),
1516	stderr: translateLevel$2(supportsColor$2(true, tty.isatty(2)))
1517};
1518
1519const stringReplaceAll$1 = (string, substring, replacer) => {
1520	let index = string.indexOf(substring);
1521	if (index === -1) {
1522		return string;
1523	}
1524
1525	const substringLength = substring.length;
1526	let endIndex = 0;
1527	let returnValue = '';
1528	do {
1529		returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
1530		endIndex = index + substringLength;
1531		index = string.indexOf(substring, endIndex);
1532	} while (index !== -1);
1533
1534	returnValue += string.substr(endIndex);
1535	return returnValue;
1536};
1537
1538const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
1539	let endIndex = 0;
1540	let returnValue = '';
1541	do {
1542		const gotCR = string[index - 1] === '\r';
1543		returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
1544		endIndex = index + 1;
1545		index = string.indexOf('\n', endIndex);
1546	} while (index !== -1);
1547
1548	returnValue += string.substr(endIndex);
1549	return returnValue;
1550};
1551
1552var util$4 = {
1553	stringReplaceAll: stringReplaceAll$1,
1554	stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
1555};
1556
1557const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
1558const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
1559const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
1560const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
1561
1562const ESCAPES$1 = new Map([
1563	['n', '\n'],
1564	['r', '\r'],
1565	['t', '\t'],
1566	['b', '\b'],
1567	['f', '\f'],
1568	['v', '\v'],
1569	['0', '\0'],
1570	['\\', '\\'],
1571	['e', '\u001B'],
1572	['a', '\u0007']
1573]);
1574
1575function unescape$1(c) {
1576	const u = c[0] === 'u';
1577	const bracket = c[1] === '{';
1578
1579	if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
1580		return String.fromCharCode(parseInt(c.slice(1), 16));
1581	}
1582
1583	if (u && bracket) {
1584		return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
1585	}
1586
1587	return ESCAPES$1.get(c) || c;
1588}
1589
1590function parseArguments$1(name, arguments_) {
1591	const results = [];
1592	const chunks = arguments_.trim().split(/\s*,\s*/g);
1593	let matches;
1594
1595	for (const chunk of chunks) {
1596		const number = Number(chunk);
1597		if (!Number.isNaN(number)) {
1598			results.push(number);
1599		} else if ((matches = chunk.match(STRING_REGEX$1))) {
1600			results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
1601		} else {
1602			throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
1603		}
1604	}
1605
1606	return results;
1607}
1608
1609function parseStyle$1(style) {
1610	STYLE_REGEX$1.lastIndex = 0;
1611
1612	const results = [];
1613	let matches;
1614
1615	while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
1616		const name = matches[1];
1617
1618		if (matches[2]) {
1619			const args = parseArguments$1(name, matches[2]);
1620			results.push([name].concat(args));
1621		} else {
1622			results.push([name]);
1623		}
1624	}
1625
1626	return results;
1627}
1628
1629function buildStyle$1(chalk, styles) {
1630	const enabled = {};
1631
1632	for (const layer of styles) {
1633		for (const style of layer.styles) {
1634			enabled[style[0]] = layer.inverse ? null : style.slice(1);
1635		}
1636	}
1637
1638	let current = chalk;
1639	for (const [styleName, styles] of Object.entries(enabled)) {
1640		if (!Array.isArray(styles)) {
1641			continue;
1642		}
1643
1644		if (!(styleName in current)) {
1645			throw new Error(`Unknown Chalk style: ${styleName}`);
1646		}
1647
1648		current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
1649	}
1650
1651	return current;
1652}
1653
1654var templates$1 = (chalk, temporary) => {
1655	const styles = [];
1656	const chunks = [];
1657	let chunk = [];
1658
1659	// eslint-disable-next-line max-params
1660	temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
1661		if (escapeCharacter) {
1662			chunk.push(unescape$1(escapeCharacter));
1663		} else if (style) {
1664			const string = chunk.join('');
1665			chunk = [];
1666			chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
1667			styles.push({inverse, styles: parseStyle$1(style)});
1668		} else if (close) {
1669			if (styles.length === 0) {
1670				throw new Error('Found extraneous } in Chalk template literal');
1671			}
1672
1673			chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
1674			chunk = [];
1675			styles.pop();
1676		} else {
1677			chunk.push(character);
1678		}
1679	});
1680
1681	chunks.push(chunk.join(''));
1682
1683	if (styles.length > 0) {
1684		const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
1685		throw new Error(errMessage);
1686	}
1687
1688	return chunks.join('');
1689};
1690
1691const ansiStyles$1 = ansiStyles$2.exports;
1692const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1;
1693const {
1694	stringReplaceAll,
1695	stringEncaseCRLFWithFirstIndex
1696} = util$4;
1697
1698const {isArray: isArray$2} = Array;
1699
1700// `supportsColor.level` → `ansiStyles.color[name]` mapping
1701const levelMapping = [
1702	'ansi',
1703	'ansi',
1704	'ansi256',
1705	'ansi16m'
1706];
1707
1708const styles = Object.create(null);
1709
1710const applyOptions = (object, options = {}) => {
1711	if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
1712		throw new Error('The `level` option should be an integer from 0 to 3');
1713	}
1714
1715	// Detect level if not set manually
1716	const colorLevel = stdoutColor ? stdoutColor.level : 0;
1717	object.level = options.level === undefined ? colorLevel : options.level;
1718};
1719
1720class ChalkClass {
1721	constructor(options) {
1722		// eslint-disable-next-line no-constructor-return
1723		return chalkFactory(options);
1724	}
1725}
1726
1727const chalkFactory = options => {
1728	const chalk = {};
1729	applyOptions(chalk, options);
1730
1731	chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
1732
1733	Object.setPrototypeOf(chalk, Chalk.prototype);
1734	Object.setPrototypeOf(chalk.template, chalk);
1735
1736	chalk.template.constructor = () => {
1737		throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
1738	};
1739
1740	chalk.template.Instance = ChalkClass;
1741
1742	return chalk.template;
1743};
1744
1745function Chalk(options) {
1746	return chalkFactory(options);
1747}
1748
1749for (const [styleName, style] of Object.entries(ansiStyles$1)) {
1750	styles[styleName] = {
1751		get() {
1752			const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
1753			Object.defineProperty(this, styleName, {value: builder});
1754			return builder;
1755		}
1756	};
1757}
1758
1759styles.visible = {
1760	get() {
1761		const builder = createBuilder(this, this._styler, true);
1762		Object.defineProperty(this, 'visible', {value: builder});
1763		return builder;
1764	}
1765};
1766
1767const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
1768
1769for (const model of usedModels) {
1770	styles[model] = {
1771		get() {
1772			const {level} = this;
1773			return function (...arguments_) {
1774				const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
1775				return createBuilder(this, styler, this._isEmpty);
1776			};
1777		}
1778	};
1779}
1780
1781for (const model of usedModels) {
1782	const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
1783	styles[bgModel] = {
1784		get() {
1785			const {level} = this;
1786			return function (...arguments_) {
1787				const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
1788				return createBuilder(this, styler, this._isEmpty);
1789			};
1790		}
1791	};
1792}
1793
1794const proto = Object.defineProperties(() => {}, {
1795	...styles,
1796	level: {
1797		enumerable: true,
1798		get() {
1799			return this._generator.level;
1800		},
1801		set(level) {
1802			this._generator.level = level;
1803		}
1804	}
1805});
1806
1807const createStyler = (open, close, parent) => {
1808	let openAll;
1809	let closeAll;
1810	if (parent === undefined) {
1811		openAll = open;
1812		closeAll = close;
1813	} else {
1814		openAll = parent.openAll + open;
1815		closeAll = close + parent.closeAll;
1816	}
1817
1818	return {
1819		open,
1820		close,
1821		openAll,
1822		closeAll,
1823		parent
1824	};
1825};
1826
1827const createBuilder = (self, _styler, _isEmpty) => {
1828	const builder = (...arguments_) => {
1829		if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
1830			// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
1831			return applyStyle(builder, chalkTag(builder, ...arguments_));
1832		}
1833
1834		// Single argument is hot path, implicit coercion is faster than anything
1835		// eslint-disable-next-line no-implicit-coercion
1836		return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
1837	};
1838
1839	// We alter the prototype because we must return a function, but there is
1840	// no way to create a function with a different prototype
1841	Object.setPrototypeOf(builder, proto);
1842
1843	builder._generator = self;
1844	builder._styler = _styler;
1845	builder._isEmpty = _isEmpty;
1846
1847	return builder;
1848};
1849
1850const applyStyle = (self, string) => {
1851	if (self.level <= 0 || !string) {
1852		return self._isEmpty ? '' : string;
1853	}
1854
1855	let styler = self._styler;
1856
1857	if (styler === undefined) {
1858		return string;
1859	}
1860
1861	const {openAll, closeAll} = styler;
1862	if (string.indexOf('\u001B') !== -1) {
1863		while (styler !== undefined) {
1864			// Replace any instances already present with a re-opening code
1865			// otherwise only the part of the string until said closing code
1866			// will be colored, and the rest will simply be 'plain'.
1867			string = stringReplaceAll(string, styler.close, styler.open);
1868
1869			styler = styler.parent;
1870		}
1871	}
1872
1873	// We can move both next actions out of loop, because remaining actions in loop won't have
1874	// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
1875	// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
1876	const lfIndex = string.indexOf('\n');
1877	if (lfIndex !== -1) {
1878		string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
1879	}
1880
1881	return openAll + string + closeAll;
1882};
1883
1884let template;
1885const chalkTag = (chalk, ...strings) => {
1886	const [firstString] = strings;
1887
1888	if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
1889		// If chalk() was called by itself or with a string,
1890		// return the string itself as a string.
1891		return strings.join(' ');
1892	}
1893
1894	const arguments_ = strings.slice(1);
1895	const parts = [firstString.raw[0]];
1896
1897	for (let i = 1; i < firstString.length; i++) {
1898		parts.push(
1899			String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
1900			String(firstString.raw[i])
1901		);
1902	}
1903
1904	if (template === undefined) {
1905		template = templates$1;
1906	}
1907
1908	return template(chalk, parts.join(''));
1909};
1910
1911Object.defineProperties(Chalk.prototype, styles);
1912
1913const chalk$1 = Chalk(); // eslint-disable-line new-cap
1914chalk$1.supportsColor = stdoutColor;
1915chalk$1.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
1916chalk$1.stderr.supportsColor = stderrColor;
1917
1918var source$1 = chalk$1;
1919
1920var chokidar = {};
1921
1922var utils$7 = {};
1923
1924const path$a = path$b;
1925const WIN_SLASH = '\\\\/';
1926const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1927
1928/**
1929 * Posix glob regex
1930 */
1931
1932const DOT_LITERAL = '\\.';
1933const PLUS_LITERAL = '\\+';
1934const QMARK_LITERAL = '\\?';
1935const SLASH_LITERAL = '\\/';
1936const ONE_CHAR = '(?=.)';
1937const QMARK = '[^/]';
1938const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
1939const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
1940const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
1941const NO_DOT = `(?!${DOT_LITERAL})`;
1942const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
1943const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
1944const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
1945const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
1946const STAR$1 = `${QMARK}*?`;
1947
1948const POSIX_CHARS = {
1949  DOT_LITERAL,
1950  PLUS_LITERAL,
1951  QMARK_LITERAL,
1952  SLASH_LITERAL,
1953  ONE_CHAR,
1954  QMARK,
1955  END_ANCHOR,
1956  DOTS_SLASH,
1957  NO_DOT,
1958  NO_DOTS,
1959  NO_DOT_SLASH,
1960  NO_DOTS_SLASH,
1961  QMARK_NO_DOT,
1962  STAR: STAR$1,
1963  START_ANCHOR
1964};
1965
1966/**
1967 * Windows glob regex
1968 */
1969
1970const WINDOWS_CHARS = {
1971  ...POSIX_CHARS,
1972
1973  SLASH_LITERAL: `[${WIN_SLASH}]`,
1974  QMARK: WIN_NO_SLASH,
1975  STAR: `${WIN_NO_SLASH}*?`,
1976  DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
1977  NO_DOT: `(?!${DOT_LITERAL})`,
1978  NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1979  NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
1980  NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1981  QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
1982  START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
1983  END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
1984};
1985
1986/**
1987 * POSIX Bracket Regex
1988 */
1989
1990const POSIX_REGEX_SOURCE$1 = {
1991  alnum: 'a-zA-Z0-9',
1992  alpha: 'a-zA-Z',
1993  ascii: '\\x00-\\x7F',
1994  blank: ' \\t',
1995  cntrl: '\\x00-\\x1F\\x7F',
1996  digit: '0-9',
1997  graph: '\\x21-\\x7E',
1998  lower: 'a-z',
1999  print: '\\x20-\\x7E ',
2000  punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
2001  space: ' \\t\\r\\n\\v\\f',
2002  upper: 'A-Z',
2003  word: 'A-Za-z0-9_',
2004  xdigit: 'A-Fa-f0-9'
2005};
2006
2007var constants$5 = {
2008  MAX_LENGTH: 1024 * 64,
2009  POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
2010
2011  // regular expressions
2012  REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
2013  REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
2014  REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
2015  REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
2016  REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
2017  REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2018
2019  // Replace globs with equivalent patterns to reduce parsing time.
2020  REPLACEMENTS: {
2021    '***': '*',
2022    '**/**': '**',
2023    '**/**/**': '**'
2024  },
2025
2026  // Digits
2027  CHAR_0: 48, /* 0 */
2028  CHAR_9: 57, /* 9 */
2029
2030  // Alphabet chars.
2031  CHAR_UPPERCASE_A: 65, /* A */
2032  CHAR_LOWERCASE_A: 97, /* a */
2033  CHAR_UPPERCASE_Z: 90, /* Z */
2034  CHAR_LOWERCASE_Z: 122, /* z */
2035
2036  CHAR_LEFT_PARENTHESES: 40, /* ( */
2037  CHAR_RIGHT_PARENTHESES: 41, /* ) */
2038
2039  CHAR_ASTERISK: 42, /* * */
2040
2041  // Non-alphabetic chars.
2042  CHAR_AMPERSAND: 38, /* & */
2043  CHAR_AT: 64, /* @ */
2044  CHAR_BACKWARD_SLASH: 92, /* \ */
2045  CHAR_CARRIAGE_RETURN: 13, /* \r */
2046  CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
2047  CHAR_COLON: 58, /* : */
2048  CHAR_COMMA: 44, /* , */
2049  CHAR_DOT: 46, /* . */
2050  CHAR_DOUBLE_QUOTE: 34, /* " */
2051  CHAR_EQUAL: 61, /* = */
2052  CHAR_EXCLAMATION_MARK: 33, /* ! */
2053  CHAR_FORM_FEED: 12, /* \f */
2054  CHAR_FORWARD_SLASH: 47, /* / */
2055  CHAR_GRAVE_ACCENT: 96, /* ` */
2056  CHAR_HASH: 35, /* # */
2057  CHAR_HYPHEN_MINUS: 45, /* - */
2058  CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
2059  CHAR_LEFT_CURLY_BRACE: 123, /* { */
2060  CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
2061  CHAR_LINE_FEED: 10, /* \n */
2062  CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
2063  CHAR_PERCENT: 37, /* % */
2064  CHAR_PLUS: 43, /* + */
2065  CHAR_QUESTION_MARK: 63, /* ? */
2066  CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
2067  CHAR_RIGHT_CURLY_BRACE: 125, /* } */
2068  CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
2069  CHAR_SEMICOLON: 59, /* ; */
2070  CHAR_SINGLE_QUOTE: 39, /* ' */
2071  CHAR_SPACE: 32, /*   */
2072  CHAR_TAB: 9, /* \t */
2073  CHAR_UNDERSCORE: 95, /* _ */
2074  CHAR_VERTICAL_LINE: 124, /* | */
2075  CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
2076
2077  SEP: path$a.sep,
2078
2079  /**
2080   * Create EXTGLOB_CHARS
2081   */
2082
2083  extglobChars(chars) {
2084    return {
2085      '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
2086      '?': { type: 'qmark', open: '(?:', close: ')?' },
2087      '+': { type: 'plus', open: '(?:', close: ')+' },
2088      '*': { type: 'star', open: '(?:', close: ')*' },
2089      '@': { type: 'at', open: '(?:', close: ')' }
2090    };
2091  },
2092
2093  /**
2094   * Create GLOB_CHARS
2095   */
2096
2097  globChars(win32) {
2098    return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
2099  }
2100};
2101
2102(function (exports) {
2103
2104const path = path$b;
2105const win32 = process.platform === 'win32';
2106const {
2107  REGEX_BACKSLASH,
2108  REGEX_REMOVE_BACKSLASH,
2109  REGEX_SPECIAL_CHARS,
2110  REGEX_SPECIAL_CHARS_GLOBAL
2111} = constants$5;
2112
2113exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
2114exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
2115exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
2116exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
2117exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
2118
2119exports.removeBackslashes = str => {
2120  return str.replace(REGEX_REMOVE_BACKSLASH, match => {
2121    return match === '\\' ? '' : match;
2122  });
2123};
2124
2125exports.supportsLookbehinds = () => {
2126  const segs = process.version.slice(1).split('.').map(Number);
2127  if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
2128    return true;
2129  }
2130  return false;
2131};
2132
2133exports.isWindows = options => {
2134  if (options && typeof options.windows === 'boolean') {
2135    return options.windows;
2136  }
2137  return win32 === true || path.sep === '\\';
2138};
2139
2140exports.escapeLast = (input, char, lastIdx) => {
2141  const idx = input.lastIndexOf(char, lastIdx);
2142  if (idx === -1) return input;
2143  if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
2144  return `${input.slice(0, idx)}\\${input.slice(idx)}`;
2145};
2146
2147exports.removePrefix = (input, state = {}) => {
2148  let output = input;
2149  if (output.startsWith('./')) {
2150    output = output.slice(2);
2151    state.prefix = './';
2152  }
2153  return output;
2154};
2155
2156exports.wrapOutput = (input, state = {}, options = {}) => {
2157  const prepend = options.contains ? '' : '^';
2158  const append = options.contains ? '' : '$';
2159
2160  let output = `${prepend}(?:${input})${append}`;
2161  if (state.negated === true) {
2162    output = `(?:^(?!${output}).*$)`;
2163  }
2164  return output;
2165};
2166}(utils$7));
2167
2168const utils$6 = utils$7;
2169const {
2170  CHAR_ASTERISK: CHAR_ASTERISK$1,             /* * */
2171  CHAR_AT,                   /* @ */
2172  CHAR_BACKWARD_SLASH,       /* \ */
2173  CHAR_COMMA: CHAR_COMMA$2,                /* , */
2174  CHAR_DOT: CHAR_DOT$1,                  /* . */
2175  CHAR_EXCLAMATION_MARK,     /* ! */
2176  CHAR_FORWARD_SLASH,        /* / */
2177  CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,     /* { */
2178  CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,     /* ( */
2179  CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2,  /* [ */
2180  CHAR_PLUS,                 /* + */
2181  CHAR_QUESTION_MARK,        /* ? */
2182  CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,    /* } */
2183  CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,    /* ) */
2184  CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2  /* ] */
2185} = constants$5;
2186
2187const isPathSeparator = code => {
2188  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
2189};
2190
2191const depth = token => {
2192  if (token.isPrefix !== true) {
2193    token.depth = token.isGlobstar ? Infinity : 1;
2194  }
2195};
2196
2197/**
2198 * Quickly scans a glob pattern and returns an object with a handful of
2199 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
2200 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
2201 *
2202 * ```js
2203 * const pm = require('picomatch');
2204 * console.log(pm.scan('foo/bar/*.js'));
2205 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
2206 * ```
2207 * @param {String} `str`
2208 * @param {Object} `options`
2209 * @return {Object} Returns an object with tokens and regex source string.
2210 * @api public
2211 */
2212
2213const scan$1 = (input, options) => {
2214  const opts = options || {};
2215
2216  const length = input.length - 1;
2217  const scanToEnd = opts.parts === true || opts.scanToEnd === true;
2218  const slashes = [];
2219  const tokens = [];
2220  const parts = [];
2221
2222  let str = input;
2223  let index = -1;
2224  let start = 0;
2225  let lastIndex = 0;
2226  let isBrace = false;
2227  let isBracket = false;
2228  let isGlob = false;
2229  let isExtglob = false;
2230  let isGlobstar = false;
2231  let braceEscaped = false;
2232  let backslashes = false;
2233  let negated = false;
2234  let finished = false;
2235  let braces = 0;
2236  let prev;
2237  let code;
2238  let token = { value: '', depth: 0, isGlob: false };
2239
2240  const eos = () => index >= length;
2241  const peek = () => str.charCodeAt(index + 1);
2242  const advance = () => {
2243    prev = code;
2244    return str.charCodeAt(++index);
2245  };
2246
2247  while (index < length) {
2248    code = advance();
2249    let next;
2250
2251    if (code === CHAR_BACKWARD_SLASH) {
2252      backslashes = token.backslashes = true;
2253      code = advance();
2254
2255      if (code === CHAR_LEFT_CURLY_BRACE$1) {
2256        braceEscaped = true;
2257      }
2258      continue;
2259    }
2260
2261    if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
2262      braces++;
2263
2264      while (eos() !== true && (code = advance())) {
2265        if (code === CHAR_BACKWARD_SLASH) {
2266          backslashes = token.backslashes = true;
2267          advance();
2268          continue;
2269        }
2270
2271        if (code === CHAR_LEFT_CURLY_BRACE$1) {
2272          braces++;
2273          continue;
2274        }
2275
2276        if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
2277          isBrace = token.isBrace = true;
2278          isGlob = token.isGlob = true;
2279          finished = true;
2280
2281          if (scanToEnd === true) {
2282            continue;
2283          }
2284
2285          break;
2286        }
2287
2288        if (braceEscaped !== true && code === CHAR_COMMA$2) {
2289          isBrace = token.isBrace = true;
2290          isGlob = token.isGlob = true;
2291          finished = true;
2292
2293          if (scanToEnd === true) {
2294            continue;
2295          }
2296
2297          break;
2298        }
2299
2300        if (code === CHAR_RIGHT_CURLY_BRACE$1) {
2301          braces--;
2302
2303          if (braces === 0) {
2304            braceEscaped = false;
2305            isBrace = token.isBrace = true;
2306            finished = true;
2307            break;
2308          }
2309        }
2310      }
2311
2312      if (scanToEnd === true) {
2313        continue;
2314      }
2315
2316      break;
2317    }
2318
2319    if (code === CHAR_FORWARD_SLASH) {
2320      slashes.push(index);
2321      tokens.push(token);
2322      token = { value: '', depth: 0, isGlob: false };
2323
2324      if (finished === true) continue;
2325      if (prev === CHAR_DOT$1 && index === (start + 1)) {
2326        start += 2;
2327        continue;
2328      }
2329
2330      lastIndex = index + 1;
2331      continue;
2332    }
2333
2334    if (opts.noext !== true) {
2335      const isExtglobChar = code === CHAR_PLUS
2336        || code === CHAR_AT
2337        || code === CHAR_ASTERISK$1
2338        || code === CHAR_QUESTION_MARK
2339        || code === CHAR_EXCLAMATION_MARK;
2340
2341      if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
2342        isGlob = token.isGlob = true;
2343        isExtglob = token.isExtglob = true;
2344        finished = true;
2345
2346        if (scanToEnd === true) {
2347          while (eos() !== true && (code = advance())) {
2348            if (code === CHAR_BACKWARD_SLASH) {
2349              backslashes = token.backslashes = true;
2350              code = advance();
2351              continue;
2352            }
2353
2354            if (code === CHAR_RIGHT_PARENTHESES$1) {
2355              isGlob = token.isGlob = true;
2356              finished = true;
2357              break;
2358            }
2359          }
2360          continue;
2361        }
2362        break;
2363      }
2364    }
2365
2366    if (code === CHAR_ASTERISK$1) {
2367      if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true;
2368      isGlob = token.isGlob = true;
2369      finished = true;
2370
2371      if (scanToEnd === true) {
2372        continue;
2373      }
2374      break;
2375    }
2376
2377    if (code === CHAR_QUESTION_MARK) {
2378      isGlob = token.isGlob = true;
2379      finished = true;
2380
2381      if (scanToEnd === true) {
2382        continue;
2383      }
2384      break;
2385    }
2386
2387    if (code === CHAR_LEFT_SQUARE_BRACKET$2) {
2388      while (eos() !== true && (next = advance())) {
2389        if (next === CHAR_BACKWARD_SLASH) {
2390          backslashes = token.backslashes = true;
2391          advance();
2392          continue;
2393        }
2394
2395        if (next === CHAR_RIGHT_SQUARE_BRACKET$2) {
2396          isBracket = token.isBracket = true;
2397          isGlob = token.isGlob = true;
2398          finished = true;
2399
2400          if (scanToEnd === true) {
2401            continue;
2402          }
2403          break;
2404        }
2405      }
2406    }
2407
2408    if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
2409      negated = token.negated = true;
2410      start++;
2411      continue;
2412    }
2413
2414    if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
2415      isGlob = token.isGlob = true;
2416
2417      if (scanToEnd === true) {
2418        while (eos() !== true && (code = advance())) {
2419          if (code === CHAR_LEFT_PARENTHESES$1) {
2420            backslashes = token.backslashes = true;
2421            code = advance();
2422            continue;
2423          }
2424
2425          if (code === CHAR_RIGHT_PARENTHESES$1) {
2426            finished = true;
2427            break;
2428          }
2429        }
2430        continue;
2431      }
2432      break;
2433    }
2434
2435    if (isGlob === true) {
2436      finished = true;
2437
2438      if (scanToEnd === true) {
2439        continue;
2440      }
2441
2442      break;
2443    }
2444  }
2445
2446  if (opts.noext === true) {
2447    isExtglob = false;
2448    isGlob = false;
2449  }
2450
2451  let base = str;
2452  let prefix = '';
2453  let glob = '';
2454
2455  if (start > 0) {
2456    prefix = str.slice(0, start);
2457    str = str.slice(start);
2458    lastIndex -= start;
2459  }
2460
2461  if (base && isGlob === true && lastIndex > 0) {
2462    base = str.slice(0, lastIndex);
2463    glob = str.slice(lastIndex);
2464  } else if (isGlob === true) {
2465    base = '';
2466    glob = str;
2467  } else {
2468    base = str;
2469  }
2470
2471  if (base && base !== '' && base !== '/' && base !== str) {
2472    if (isPathSeparator(base.charCodeAt(base.length - 1))) {
2473      base = base.slice(0, -1);
2474    }
2475  }
2476
2477  if (opts.unescape === true) {
2478    if (glob) glob = utils$6.removeBackslashes(glob);
2479
2480    if (base && backslashes === true) {
2481      base = utils$6.removeBackslashes(base);
2482    }
2483  }
2484
2485  const state = {
2486    prefix,
2487    input,
2488    start,
2489    base,
2490    glob,
2491    isBrace,
2492    isBracket,
2493    isGlob,
2494    isExtglob,
2495    isGlobstar,
2496    negated
2497  };
2498
2499  if (opts.tokens === true) {
2500    state.maxDepth = 0;
2501    if (!isPathSeparator(code)) {
2502      tokens.push(token);
2503    }
2504    state.tokens = tokens;
2505  }
2506
2507  if (opts.parts === true || opts.tokens === true) {
2508    let prevIndex;
2509
2510    for (let idx = 0; idx < slashes.length; idx++) {
2511      const n = prevIndex ? prevIndex + 1 : start;
2512      const i = slashes[idx];
2513      const value = input.slice(n, i);
2514      if (opts.tokens) {
2515        if (idx === 0 && start !== 0) {
2516          tokens[idx].isPrefix = true;
2517          tokens[idx].value = prefix;
2518        } else {
2519          tokens[idx].value = value;
2520        }
2521        depth(tokens[idx]);
2522        state.maxDepth += tokens[idx].depth;
2523      }
2524      if (idx !== 0 || value !== '') {
2525        parts.push(value);
2526      }
2527      prevIndex = i;
2528    }
2529
2530    if (prevIndex && prevIndex + 1 < input.length) {
2531      const value = input.slice(prevIndex + 1);
2532      parts.push(value);
2533
2534      if (opts.tokens) {
2535        tokens[tokens.length - 1].value = value;
2536        depth(tokens[tokens.length - 1]);
2537        state.maxDepth += tokens[tokens.length - 1].depth;
2538      }
2539    }
2540
2541    state.slashes = slashes;
2542    state.parts = parts;
2543  }
2544
2545  return state;
2546};
2547
2548var scan_1 = scan$1;
2549
2550const constants$4 = constants$5;
2551const utils$5 = utils$7;
2552
2553/**
2554 * Constants
2555 */
2556
2557const {
2558  MAX_LENGTH: MAX_LENGTH$4,
2559  POSIX_REGEX_SOURCE,
2560  REGEX_NON_SPECIAL_CHARS,
2561  REGEX_SPECIAL_CHARS_BACKREF,
2562  REPLACEMENTS
2563} = constants$4;
2564
2565/**
2566 * Helpers
2567 */
2568
2569const expandRange = (args, options) => {
2570  if (typeof options.expandRange === 'function') {
2571    return options.expandRange(...args, options);
2572  }
2573
2574  args.sort();
2575  const value = `[${args.join('-')}]`;
2576
2577  try {
2578    /* eslint-disable-next-line no-new */
2579    new RegExp(value);
2580  } catch (ex) {
2581    return args.map(v => utils$5.escapeRegex(v)).join('..');
2582  }
2583
2584  return value;
2585};
2586
2587/**
2588 * Create the message for a syntax error
2589 */
2590
2591const syntaxError$1 = (type, char) => {
2592  return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
2593};
2594
2595/**
2596 * Parse the given input string.
2597 * @param {String} input
2598 * @param {Object} options
2599 * @return {Object}
2600 */
2601
2602const parse$e = (input, options) => {
2603  if (typeof input !== 'string') {
2604    throw new TypeError('Expected a string');
2605  }
2606
2607  input = REPLACEMENTS[input] || input;
2608
2609  const opts = { ...options };
2610  const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$4, opts.maxLength) : MAX_LENGTH$4;
2611
2612  let len = input.length;
2613  if (len > max) {
2614    throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
2615  }
2616
2617  const bos = { type: 'bos', value: '', output: opts.prepend || '' };
2618  const tokens = [bos];
2619
2620  const capture = opts.capture ? '' : '?:';
2621  const win32 = utils$5.isWindows(options);
2622
2623  // create constants based on platform, for windows or posix
2624  const PLATFORM_CHARS = constants$4.globChars(win32);
2625  const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS);
2626
2627  const {
2628    DOT_LITERAL,
2629    PLUS_LITERAL,
2630    SLASH_LITERAL,
2631    ONE_CHAR,
2632    DOTS_SLASH,
2633    NO_DOT,
2634    NO_DOT_SLASH,
2635    NO_DOTS_SLASH,
2636    QMARK,
2637    QMARK_NO_DOT,
2638    STAR,
2639    START_ANCHOR
2640  } = PLATFORM_CHARS;
2641
2642  const globstar = (opts) => {
2643    return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
2644  };
2645
2646  const nodot = opts.dot ? '' : NO_DOT;
2647  const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
2648  let star = opts.bash === true ? globstar(opts) : STAR;
2649
2650  if (opts.capture) {
2651    star = `(${star})`;
2652  }
2653
2654  // minimatch options support
2655  if (typeof opts.noext === 'boolean') {
2656    opts.noextglob = opts.noext;
2657  }
2658
2659  const state = {
2660    input,
2661    index: -1,
2662    start: 0,
2663    dot: opts.dot === true,
2664    consumed: '',
2665    output: '',
2666    prefix: '',
2667    backtrack: false,
2668    negated: false,
2669    brackets: 0,
2670    braces: 0,
2671    parens: 0,
2672    quotes: 0,
2673    globstar: false,
2674    tokens
2675  };
2676
2677  input = utils$5.removePrefix(input, state);
2678  len = input.length;
2679
2680  const extglobs = [];
2681  const braces = [];
2682  const stack = [];
2683  let prev = bos;
2684  let value;
2685
2686  /**
2687   * Tokenizing helpers
2688   */
2689
2690  const eos = () => state.index === len - 1;
2691  const peek = state.peek = (n = 1) => input[state.index + n];
2692  const advance = state.advance = () => input[++state.index];
2693  const remaining = () => input.slice(state.index + 1);
2694  const consume = (value = '', num = 0) => {
2695    state.consumed += value;
2696    state.index += num;
2697  };
2698  const append = token => {
2699    state.output += token.output != null ? token.output : token.value;
2700    consume(token.value);
2701  };
2702
2703  const negate = () => {
2704    let count = 1;
2705
2706    while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
2707      advance();
2708      state.start++;
2709      count++;
2710    }
2711
2712    if (count % 2 === 0) {
2713      return false;
2714    }
2715
2716    state.negated = true;
2717    state.start++;
2718    return true;
2719  };
2720
2721  const increment = type => {
2722    state[type]++;
2723    stack.push(type);
2724  };
2725
2726  const decrement = type => {
2727    state[type]--;
2728    stack.pop();
2729  };
2730
2731  /**
2732   * Push tokens onto the tokens array. This helper speeds up
2733   * tokenizing by 1) helping us avoid backtracking as much as possible,
2734   * and 2) helping us avoid creating extra tokens when consecutive
2735   * characters are plain text. This improves performance and simplifies
2736   * lookbehinds.
2737   */
2738
2739  const push = tok => {
2740    if (prev.type === 'globstar') {
2741      const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
2742      const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
2743
2744      if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
2745        state.output = state.output.slice(0, -prev.output.length);
2746        prev.type = 'star';
2747        prev.value = '*';
2748        prev.output = star;
2749        state.output += prev.output;
2750      }
2751    }
2752
2753    if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
2754      extglobs[extglobs.length - 1].inner += tok.value;
2755    }
2756
2757    if (tok.value || tok.output) append(tok);
2758    if (prev && prev.type === 'text' && tok.type === 'text') {
2759      prev.value += tok.value;
2760      prev.output = (prev.output || '') + tok.value;
2761      return;
2762    }
2763
2764    tok.prev = prev;
2765    tokens.push(tok);
2766    prev = tok;
2767  };
2768
2769  const extglobOpen = (type, value) => {
2770    const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
2771
2772    token.prev = prev;
2773    token.parens = state.parens;
2774    token.output = state.output;
2775    const output = (opts.capture ? '(' : '') + token.open;
2776
2777    increment('parens');
2778    push({ type, value, output: state.output ? '' : ONE_CHAR });
2779    push({ type: 'paren', extglob: true, value: advance(), output });
2780    extglobs.push(token);
2781  };
2782
2783  const extglobClose = token => {
2784    let output = token.close + (opts.capture ? ')' : '');
2785
2786    if (token.type === 'negate') {
2787      let extglobStar = star;
2788
2789      if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
2790        extglobStar = globstar(opts);
2791      }
2792
2793      if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
2794        output = token.close = `)$))${extglobStar}`;
2795      }
2796
2797      if (token.prev.type === 'bos' && eos()) {
2798        state.negatedExtglob = true;
2799      }
2800    }
2801
2802    push({ type: 'paren', extglob: true, value, output });
2803    decrement('parens');
2804  };
2805
2806  /**
2807   * Fast paths
2808   */
2809
2810  if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
2811    let backslashes = false;
2812
2813    let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
2814      if (first === '\\') {
2815        backslashes = true;
2816        return m;
2817      }
2818
2819      if (first === '?') {
2820        if (esc) {
2821          return esc + first + (rest ? QMARK.repeat(rest.length) : '');
2822        }
2823        if (index === 0) {
2824          return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
2825        }
2826        return QMARK.repeat(chars.length);
2827      }
2828
2829      if (first === '.') {
2830        return DOT_LITERAL.repeat(chars.length);
2831      }
2832
2833      if (first === '*') {
2834        if (esc) {
2835          return esc + first + (rest ? star : '');
2836        }
2837        return star;
2838      }
2839      return esc ? m : `\\${m}`;
2840    });
2841
2842    if (backslashes === true) {
2843      if (opts.unescape === true) {
2844        output = output.replace(/\\/g, '');
2845      } else {
2846        output = output.replace(/\\+/g, m => {
2847          return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
2848        });
2849      }
2850    }
2851
2852    if (output === input && opts.contains === true) {
2853      state.output = input;
2854      return state;
2855    }
2856
2857    state.output = utils$5.wrapOutput(output, state, options);
2858    return state;
2859  }
2860
2861  /**
2862   * Tokenize input until we reach end-of-string
2863   */
2864
2865  while (!eos()) {
2866    value = advance();
2867
2868    if (value === '\u0000') {
2869      continue;
2870    }
2871
2872    /**
2873     * Escaped characters
2874     */
2875
2876    if (value === '\\') {
2877      const next = peek();
2878
2879      if (next === '/' && opts.bash !== true) {
2880        continue;
2881      }
2882
2883      if (next === '.' || next === ';') {
2884        continue;
2885      }
2886
2887      if (!next) {
2888        value += '\\';
2889        push({ type: 'text', value });
2890        continue;
2891      }
2892
2893      // collapse slashes to reduce potential for exploits
2894      const match = /^\\+/.exec(remaining());
2895      let slashes = 0;
2896
2897      if (match && match[0].length > 2) {
2898        slashes = match[0].length;
2899        state.index += slashes;
2900        if (slashes % 2 !== 0) {
2901          value += '\\';
2902        }
2903      }
2904
2905      if (opts.unescape === true) {
2906        value = advance() || '';
2907      } else {
2908        value += advance() || '';
2909      }
2910
2911      if (state.brackets === 0) {
2912        push({ type: 'text', value });
2913        continue;
2914      }
2915    }
2916
2917    /**
2918     * If we're inside a regex character class, continue
2919     * until we reach the closing bracket.
2920     */
2921
2922    if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
2923      if (opts.posix !== false && value === ':') {
2924        const inner = prev.value.slice(1);
2925        if (inner.includes('[')) {
2926          prev.posix = true;
2927
2928          if (inner.includes(':')) {
2929            const idx = prev.value.lastIndexOf('[');
2930            const pre = prev.value.slice(0, idx);
2931            const rest = prev.value.slice(idx + 2);
2932            const posix = POSIX_REGEX_SOURCE[rest];
2933            if (posix) {
2934              prev.value = pre + posix;
2935              state.backtrack = true;
2936              advance();
2937
2938              if (!bos.output && tokens.indexOf(prev) === 1) {
2939                bos.output = ONE_CHAR;
2940              }
2941              continue;
2942            }
2943          }
2944        }
2945      }
2946
2947      if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
2948        value = `\\${value}`;
2949      }
2950
2951      if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
2952        value = `\\${value}`;
2953      }
2954
2955      if (opts.posix === true && value === '!' && prev.value === '[') {
2956        value = '^';
2957      }
2958
2959      prev.value += value;
2960      append({ value });
2961      continue;
2962    }
2963
2964    /**
2965     * If we're inside a quoted string, continue
2966     * until we reach the closing double quote.
2967     */
2968
2969    if (state.quotes === 1 && value !== '"') {
2970      value = utils$5.escapeRegex(value);
2971      prev.value += value;
2972      append({ value });
2973      continue;
2974    }
2975
2976    /**
2977     * Double quotes
2978     */
2979
2980    if (value === '"') {
2981      state.quotes = state.quotes === 1 ? 0 : 1;
2982      if (opts.keepQuotes === true) {
2983        push({ type: 'text', value });
2984      }
2985      continue;
2986    }
2987
2988    /**
2989     * Parentheses
2990     */
2991
2992    if (value === '(') {
2993      increment('parens');
2994      push({ type: 'paren', value });
2995      continue;
2996    }
2997
2998    if (value === ')') {
2999      if (state.parens === 0 && opts.strictBrackets === true) {
3000        throw new SyntaxError(syntaxError$1('opening', '('));
3001      }
3002
3003      const extglob = extglobs[extglobs.length - 1];
3004      if (extglob && state.parens === extglob.parens + 1) {
3005        extglobClose(extglobs.pop());
3006        continue;
3007      }
3008
3009      push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
3010      decrement('parens');
3011      continue;
3012    }
3013
3014    /**
3015     * Square brackets
3016     */
3017
3018    if (value === '[') {
3019      if (opts.nobracket === true || !remaining().includes(']')) {
3020        if (opts.nobracket !== true && opts.strictBrackets === true) {
3021          throw new SyntaxError(syntaxError$1('closing', ']'));
3022        }
3023
3024        value = `\\${value}`;
3025      } else {
3026        increment('brackets');
3027      }
3028
3029      push({ type: 'bracket', value });
3030      continue;
3031    }
3032
3033    if (value === ']') {
3034      if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
3035        push({ type: 'text', value, output: `\\${value}` });
3036        continue;
3037      }
3038
3039      if (state.brackets === 0) {
3040        if (opts.strictBrackets === true) {
3041          throw new SyntaxError(syntaxError$1('opening', '['));
3042        }
3043
3044        push({ type: 'text', value, output: `\\${value}` });
3045        continue;
3046      }
3047
3048      decrement('brackets');
3049
3050      const prevValue = prev.value.slice(1);
3051      if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
3052        value = `/${value}`;
3053      }
3054
3055      prev.value += value;
3056      append({ value });
3057
3058      // when literal brackets are explicitly disabled
3059      // assume we should match with a regex character class
3060      if (opts.literalBrackets === false || utils$5.hasRegexChars(prevValue)) {
3061        continue;
3062      }
3063
3064      const escaped = utils$5.escapeRegex(prev.value);
3065      state.output = state.output.slice(0, -prev.value.length);
3066
3067      // when literal brackets are explicitly enabled
3068      // assume we should escape the brackets to match literal characters
3069      if (opts.literalBrackets === true) {
3070        state.output += escaped;
3071        prev.value = escaped;
3072        continue;
3073      }
3074
3075      // when the user specifies nothing, try to match both
3076      prev.value = `(${capture}${escaped}|${prev.value})`;
3077      state.output += prev.value;
3078      continue;
3079    }
3080
3081    /**
3082     * Braces
3083     */
3084
3085    if (value === '{' && opts.nobrace !== true) {
3086      increment('braces');
3087
3088      const open = {
3089        type: 'brace',
3090        value,
3091        output: '(',
3092        outputIndex: state.output.length,
3093        tokensIndex: state.tokens.length
3094      };
3095
3096      braces.push(open);
3097      push(open);
3098      continue;
3099    }
3100
3101    if (value === '}') {
3102      const brace = braces[braces.length - 1];
3103
3104      if (opts.nobrace === true || !brace) {
3105        push({ type: 'text', value, output: value });
3106        continue;
3107      }
3108
3109      let output = ')';
3110
3111      if (brace.dots === true) {
3112        const arr = tokens.slice();
3113        const range = [];
3114
3115        for (let i = arr.length - 1; i >= 0; i--) {
3116          tokens.pop();
3117          if (arr[i].type === 'brace') {
3118            break;
3119          }
3120          if (arr[i].type !== 'dots') {
3121            range.unshift(arr[i].value);
3122          }
3123        }
3124
3125        output = expandRange(range, opts);
3126        state.backtrack = true;
3127      }
3128
3129      if (brace.comma !== true && brace.dots !== true) {
3130        const out = state.output.slice(0, brace.outputIndex);
3131        const toks = state.tokens.slice(brace.tokensIndex);
3132        brace.value = brace.output = '\\{';
3133        value = output = '\\}';
3134        state.output = out;
3135        for (const t of toks) {
3136          state.output += (t.output || t.value);
3137        }
3138      }
3139
3140      push({ type: 'brace', value, output });
3141      decrement('braces');
3142      braces.pop();
3143      continue;
3144    }
3145
3146    /**
3147     * Pipes
3148     */
3149
3150    if (value === '|') {
3151      if (extglobs.length > 0) {
3152        extglobs[extglobs.length - 1].conditions++;
3153      }
3154      push({ type: 'text', value });
3155      continue;
3156    }
3157
3158    /**
3159     * Commas
3160     */
3161
3162    if (value === ',') {
3163      let output = value;
3164
3165      const brace = braces[braces.length - 1];
3166      if (brace && stack[stack.length - 1] === 'braces') {
3167        brace.comma = true;
3168        output = '|';
3169      }
3170
3171      push({ type: 'comma', value, output });
3172      continue;
3173    }
3174
3175    /**
3176     * Slashes
3177     */
3178
3179    if (value === '/') {
3180      // if the beginning of the glob is "./", advance the start
3181      // to the current index, and don't add the "./" characters
3182      // to the state. This greatly simplifies lookbehinds when
3183      // checking for BOS characters like "!" and "." (not "./")
3184      if (prev.type === 'dot' && state.index === state.start + 1) {
3185        state.start = state.index + 1;
3186        state.consumed = '';
3187        state.output = '';
3188        tokens.pop();
3189        prev = bos; // reset "prev" to the first token
3190        continue;
3191      }
3192
3193      push({ type: 'slash', value, output: SLASH_LITERAL });
3194      continue;
3195    }
3196
3197    /**
3198     * Dots
3199     */
3200
3201    if (value === '.') {
3202      if (state.braces > 0 && prev.type === 'dot') {
3203        if (prev.value === '.') prev.output = DOT_LITERAL;
3204        const brace = braces[braces.length - 1];
3205        prev.type = 'dots';
3206        prev.output += value;
3207        prev.value += value;
3208        brace.dots = true;
3209        continue;
3210      }
3211
3212      if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
3213        push({ type: 'text', value, output: DOT_LITERAL });
3214        continue;
3215      }
3216
3217      push({ type: 'dot', value, output: DOT_LITERAL });
3218      continue;
3219    }
3220
3221    /**
3222     * Question marks
3223     */
3224
3225    if (value === '?') {
3226      const isGroup = prev && prev.value === '(';
3227      if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3228        extglobOpen('qmark', value);
3229        continue;
3230      }
3231
3232      if (prev && prev.type === 'paren') {
3233        const next = peek();
3234        let output = value;
3235
3236        if (next === '<' && !utils$5.supportsLookbehinds()) {
3237          throw new Error('Node.js v10 or higher is required for regex lookbehinds');
3238        }
3239
3240        if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
3241          output = `\\${value}`;
3242        }
3243
3244        push({ type: 'text', value, output });
3245        continue;
3246      }
3247
3248      if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
3249        push({ type: 'qmark', value, output: QMARK_NO_DOT });
3250        continue;
3251      }
3252
3253      push({ type: 'qmark', value, output: QMARK });
3254      continue;
3255    }
3256
3257    /**
3258     * Exclamation
3259     */
3260
3261    if (value === '!') {
3262      if (opts.noextglob !== true && peek() === '(') {
3263        if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
3264          extglobOpen('negate', value);
3265          continue;
3266        }
3267      }
3268
3269      if (opts.nonegate !== true && state.index === 0) {
3270        negate();
3271        continue;
3272      }
3273    }
3274
3275    /**
3276     * Plus
3277     */
3278
3279    if (value === '+') {
3280      if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3281        extglobOpen('plus', value);
3282        continue;
3283      }
3284
3285      if ((prev && prev.value === '(') || opts.regex === false) {
3286        push({ type: 'plus', value, output: PLUS_LITERAL });
3287        continue;
3288      }
3289
3290      if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
3291        push({ type: 'plus', value });
3292        continue;
3293      }
3294
3295      push({ type: 'plus', value: PLUS_LITERAL });
3296      continue;
3297    }
3298
3299    /**
3300     * Plain text
3301     */
3302
3303    if (value === '@') {
3304      if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3305        push({ type: 'at', extglob: true, value, output: '' });
3306        continue;
3307      }
3308
3309      push({ type: 'text', value });
3310      continue;
3311    }
3312
3313    /**
3314     * Plain text
3315     */
3316
3317    if (value !== '*') {
3318      if (value === '$' || value === '^') {
3319        value = `\\${value}`;
3320      }
3321
3322      const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
3323      if (match) {
3324        value += match[0];
3325        state.index += match[0].length;
3326      }
3327
3328      push({ type: 'text', value });
3329      continue;
3330    }
3331
3332    /**
3333     * Stars
3334     */
3335
3336    if (prev && (prev.type === 'globstar' || prev.star === true)) {
3337      prev.type = 'star';
3338      prev.star = true;
3339      prev.value += value;
3340      prev.output = star;
3341      state.backtrack = true;
3342      state.globstar = true;
3343      consume(value);
3344      continue;
3345    }
3346
3347    let rest = remaining();
3348    if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
3349      extglobOpen('star', value);
3350      continue;
3351    }
3352
3353    if (prev.type === 'star') {
3354      if (opts.noglobstar === true) {
3355        consume(value);
3356        continue;
3357      }
3358
3359      const prior = prev.prev;
3360      const before = prior.prev;
3361      const isStart = prior.type === 'slash' || prior.type === 'bos';
3362      const afterStar = before && (before.type === 'star' || before.type === 'globstar');
3363
3364      if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
3365        push({ type: 'star', value, output: '' });
3366        continue;
3367      }
3368
3369      const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
3370      const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
3371      if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
3372        push({ type: 'star', value, output: '' });
3373        continue;
3374      }
3375
3376      // strip consecutive `/**/`
3377      while (rest.slice(0, 3) === '/**') {
3378        const after = input[state.index + 4];
3379        if (after && after !== '/') {
3380          break;
3381        }
3382        rest = rest.slice(3);
3383        consume('/**', 3);
3384      }
3385
3386      if (prior.type === 'bos' && eos()) {
3387        prev.type = 'globstar';
3388        prev.value += value;
3389        prev.output = globstar(opts);
3390        state.output = prev.output;
3391        state.globstar = true;
3392        consume(value);
3393        continue;
3394      }
3395
3396      if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
3397        state.output = state.output.slice(0, -(prior.output + prev.output).length);
3398        prior.output = `(?:${prior.output}`;
3399
3400        prev.type = 'globstar';
3401        prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
3402        prev.value += value;
3403        state.globstar = true;
3404        state.output += prior.output + prev.output;
3405        consume(value);
3406        continue;
3407      }
3408
3409      if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
3410        const end = rest[1] !== void 0 ? '|$' : '';
3411
3412        state.output = state.output.slice(0, -(prior.output + prev.output).length);
3413        prior.output = `(?:${prior.output}`;
3414
3415        prev.type = 'globstar';
3416        prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
3417        prev.value += value;
3418
3419        state.output += prior.output + prev.output;
3420        state.globstar = true;
3421
3422        consume(value + advance());
3423
3424        push({ type: 'slash', value: '/', output: '' });
3425        continue;
3426      }
3427
3428      if (prior.type === 'bos' && rest[0] === '/') {
3429        prev.type = 'globstar';
3430        prev.value += value;
3431        prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
3432        state.output = prev.output;
3433        state.globstar = true;
3434        consume(value + advance());
3435        push({ type: 'slash', value: '/', output: '' });
3436        continue;
3437      }
3438
3439      // remove single star from output
3440      state.output = state.output.slice(0, -prev.output.length);
3441
3442      // reset previous token to globstar
3443      prev.type = 'globstar';
3444      prev.output = globstar(opts);
3445      prev.value += value;
3446
3447      // reset output with globstar
3448      state.output += prev.output;
3449      state.globstar = true;
3450      consume(value);
3451      continue;
3452    }
3453
3454    const token = { type: 'star', value, output: star };
3455
3456    if (opts.bash === true) {
3457      token.output = '.*?';
3458      if (prev.type === 'bos' || prev.type === 'slash') {
3459        token.output = nodot + token.output;
3460      }
3461      push(token);
3462      continue;
3463    }
3464
3465    if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
3466      token.output = value;
3467      push(token);
3468      continue;
3469    }
3470
3471    if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
3472      if (prev.type === 'dot') {
3473        state.output += NO_DOT_SLASH;
3474        prev.output += NO_DOT_SLASH;
3475
3476      } else if (opts.dot === true) {
3477        state.output += NO_DOTS_SLASH;
3478        prev.output += NO_DOTS_SLASH;
3479
3480      } else {
3481        state.output += nodot;
3482        prev.output += nodot;
3483      }
3484
3485      if (peek() !== '*') {
3486        state.output += ONE_CHAR;
3487        prev.output += ONE_CHAR;
3488      }
3489    }
3490
3491    push(token);
3492  }
3493
3494  while (state.brackets > 0) {
3495    if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));
3496    state.output = utils$5.escapeLast(state.output, '[');
3497    decrement('brackets');
3498  }
3499
3500  while (state.parens > 0) {
3501    if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));
3502    state.output = utils$5.escapeLast(state.output, '(');
3503    decrement('parens');
3504  }
3505
3506  while (state.braces > 0) {
3507    if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));
3508    state.output = utils$5.escapeLast(state.output, '{');
3509    decrement('braces');
3510  }
3511
3512  if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
3513    push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
3514  }
3515
3516  // rebuild the output if we had to backtrack at any point
3517  if (state.backtrack === true) {
3518    state.output = '';
3519
3520    for (const token of state.tokens) {
3521      state.output += token.output != null ? token.output : token.value;
3522
3523      if (token.suffix) {
3524        state.output += token.suffix;
3525      }
3526    }
3527  }
3528
3529  return state;
3530};
3531
3532/**
3533 * Fast paths for creating regular expressions for common glob patterns.
3534 * This can significantly speed up processing and has very little downside
3535 * impact when none of the fast paths match.
3536 */
3537
3538parse$e.fastpaths = (input, options) => {
3539  const opts = { ...options };
3540  const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$4, opts.maxLength) : MAX_LENGTH$4;
3541  const len = input.length;
3542  if (len > max) {
3543    throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
3544  }
3545
3546  input = REPLACEMENTS[input] || input;
3547  const win32 = utils$5.isWindows(options);
3548
3549  // create constants based on platform, for windows or posix
3550  const {
3551    DOT_LITERAL,
3552    SLASH_LITERAL,
3553    ONE_CHAR,
3554    DOTS_SLASH,
3555    NO_DOT,
3556    NO_DOTS,
3557    NO_DOTS_SLASH,
3558    STAR,
3559    START_ANCHOR
3560  } = constants$4.globChars(win32);
3561
3562  const nodot = opts.dot ? NO_DOTS : NO_DOT;
3563  const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
3564  const capture = opts.capture ? '' : '?:';
3565  const state = { negated: false, prefix: '' };
3566  let star = opts.bash === true ? '.*?' : STAR;
3567
3568  if (opts.capture) {
3569    star = `(${star})`;
3570  }
3571
3572  const globstar = (opts) => {
3573    if (opts.noglobstar === true) return star;
3574    return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
3575  };
3576
3577  const create = str => {
3578    switch (str) {
3579      case '*':
3580        return `${nodot}${ONE_CHAR}${star}`;
3581
3582      case '.*':
3583        return `${DOT_LITERAL}${ONE_CHAR}${star}`;
3584
3585      case '*.*':
3586        return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
3587
3588      case '*/*':
3589        return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
3590
3591      case '**':
3592        return nodot + globstar(opts);
3593
3594      case '**/*':
3595        return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
3596
3597      case '**/*.*':
3598        return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
3599
3600      case '**/.*':
3601        return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
3602
3603      default: {
3604        const match = /^(.*?)\.(\w+)$/.exec(str);
3605        if (!match) return;
3606
3607        const source = create(match[1]);
3608        if (!source) return;
3609
3610        return source + DOT_LITERAL + match[2];
3611      }
3612    }
3613  };
3614
3615  const output = utils$5.removePrefix(input, state);
3616  let source = create(output);
3617
3618  if (source && opts.strictSlashes !== true) {
3619    source += `${SLASH_LITERAL}?`;
3620  }
3621
3622  return source;
3623};
3624
3625var parse_1$2 = parse$e;
3626
3627const path$9 = path$b;
3628const scan = scan_1;
3629const parse$d = parse_1$2;
3630const utils$4 = utils$7;
3631const constants$3 = constants$5;
3632const isObject$3 = val => val && typeof val === 'object' && !Array.isArray(val);
3633
3634/**
3635 * Creates a matcher function from one or more glob patterns. The
3636 * returned function takes a string to match as its first argument,
3637 * and returns true if the string is a match. The returned matcher
3638 * function also takes a boolean as the second argument that, when true,
3639 * returns an object with additional information.
3640 *
3641 * ```js
3642 * const picomatch = require('picomatch');
3643 * // picomatch(glob[, options]);
3644 *
3645 * const isMatch = picomatch('*.!(*a)');
3646 * console.log(isMatch('a.a')); //=> false
3647 * console.log(isMatch('a.b')); //=> true
3648 * ```
3649 * @name picomatch
3650 * @param {String|Array} `globs` One or more glob patterns.
3651 * @param {Object=} `options`
3652 * @return {Function=} Returns a matcher function.
3653 * @api public
3654 */
3655
3656const picomatch$3 = (glob, options, returnState = false) => {
3657  if (Array.isArray(glob)) {
3658    const fns = glob.map(input => picomatch$3(input, options, returnState));
3659    const arrayMatcher = str => {
3660      for (const isMatch of fns) {
3661        const state = isMatch(str);
3662        if (state) return state;
3663      }
3664      return false;
3665    };
3666    return arrayMatcher;
3667  }
3668
3669  const isState = isObject$3(glob) && glob.tokens && glob.input;
3670
3671  if (glob === '' || (typeof glob !== 'string' && !isState)) {
3672    throw new TypeError('Expected pattern to be a non-empty string');
3673  }
3674
3675  const opts = options || {};
3676  const posix = utils$4.isWindows(options);
3677  const regex = isState
3678    ? picomatch$3.compileRe(glob, options)
3679    : picomatch$3.makeRe(glob, options, false, true);
3680
3681  const state = regex.state;
3682  delete regex.state;
3683
3684  let isIgnored = () => false;
3685  if (opts.ignore) {
3686    const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
3687    isIgnored = picomatch$3(opts.ignore, ignoreOpts, returnState);
3688  }
3689
3690  const matcher = (input, returnObject = false) => {
3691    const { isMatch, match, output } = picomatch$3.test(input, regex, options, { glob, posix });
3692    const result = { glob, state, regex, posix, input, output, match, isMatch };
3693
3694    if (typeof opts.onResult === 'function') {
3695      opts.onResult(result);
3696    }
3697
3698    if (isMatch === false) {
3699      result.isMatch = false;
3700      return returnObject ? result : false;
3701    }
3702
3703    if (isIgnored(input)) {
3704      if (typeof opts.onIgnore === 'function') {
3705        opts.onIgnore(result);
3706      }
3707      result.isMatch = false;
3708      return returnObject ? result : false;
3709    }
3710
3711    if (typeof opts.onMatch === 'function') {
3712      opts.onMatch(result);
3713    }
3714    return returnObject ? result : true;
3715  };
3716
3717  if (returnState) {
3718    matcher.state = state;
3719  }
3720
3721  return matcher;
3722};
3723
3724/**
3725 * Test `input` with the given `regex`. This is used by the main
3726 * `picomatch()` function to test the input string.
3727 *
3728 * ```js
3729 * const picomatch = require('picomatch');
3730 * // picomatch.test(input, regex[, options]);
3731 *
3732 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
3733 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
3734 * ```
3735 * @param {String} `input` String to test.
3736 * @param {RegExp} `regex`
3737 * @return {Object} Returns an object with matching info.
3738 * @api public
3739 */
3740
3741picomatch$3.test = (input, regex, options, { glob, posix } = {}) => {
3742  if (typeof input !== 'string') {
3743    throw new TypeError('Expected input to be a string');
3744  }
3745
3746  if (input === '') {
3747    return { isMatch: false, output: '' };
3748  }
3749
3750  const opts = options || {};
3751  const format = opts.format || (posix ? utils$4.toPosixSlashes : null);
3752  let match = input === glob;
3753  let output = (match && format) ? format(input) : input;
3754
3755  if (match === false) {
3756    output = format ? format(input) : input;
3757    match = output === glob;
3758  }
3759
3760  if (match === false || opts.capture === true) {
3761    if (opts.matchBase === true || opts.basename === true) {
3762      match = picomatch$3.matchBase(input, regex, options, posix);
3763    } else {
3764      match = regex.exec(output);
3765    }
3766  }
3767
3768  return { isMatch: Boolean(match), match, output };
3769};
3770
3771/**
3772 * Match the basename of a filepath.
3773 *
3774 * ```js
3775 * const picomatch = require('picomatch');
3776 * // picomatch.matchBase(input, glob[, options]);
3777 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
3778 * ```
3779 * @param {String} `input` String to test.
3780 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
3781 * @return {Boolean}
3782 * @api public
3783 */
3784
3785picomatch$3.matchBase = (input, glob, options, posix = utils$4.isWindows(options)) => {
3786  const regex = glob instanceof RegExp ? glob : picomatch$3.makeRe(glob, options);
3787  return regex.test(path$9.basename(input));
3788};
3789
3790/**
3791 * Returns true if **any** of the given glob `patterns` match the specified `string`.
3792 *
3793 * ```js
3794 * const picomatch = require('picomatch');
3795 * // picomatch.isMatch(string, patterns[, options]);
3796 *
3797 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
3798 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
3799 * ```
3800 * @param {String|Array} str The string to test.
3801 * @param {String|Array} patterns One or more glob patterns to use for matching.
3802 * @param {Object} [options] See available [options](#options).
3803 * @return {Boolean} Returns true if any patterns match `str`
3804 * @api public
3805 */
3806
3807picomatch$3.isMatch = (str, patterns, options) => picomatch$3(patterns, options)(str);
3808
3809/**
3810 * Parse a glob pattern to create the source string for a regular
3811 * expression.
3812 *
3813 * ```js
3814 * const picomatch = require('picomatch');
3815 * const result = picomatch.parse(pattern[, options]);
3816 * ```
3817 * @param {String} `pattern`
3818 * @param {Object} `options`
3819 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
3820 * @api public
3821 */
3822
3823picomatch$3.parse = (pattern, options) => {
3824  if (Array.isArray(pattern)) return pattern.map(p => picomatch$3.parse(p, options));
3825  return parse$d(pattern, { ...options, fastpaths: false });
3826};
3827
3828/**
3829 * Scan a glob pattern to separate the pattern into segments.
3830 *
3831 * ```js
3832 * const picomatch = require('picomatch');
3833 * // picomatch.scan(input[, options]);
3834 *
3835 * const result = picomatch.scan('!./foo/*.js');
3836 * console.log(result);
3837 * { prefix: '!./',
3838 *   input: '!./foo/*.js',
3839 *   start: 3,
3840 *   base: 'foo',
3841 *   glob: '*.js',
3842 *   isBrace: false,
3843 *   isBracket: false,
3844 *   isGlob: true,
3845 *   isExtglob: false,
3846 *   isGlobstar: false,
3847 *   negated: true }
3848 * ```
3849 * @param {String} `input` Glob pattern to scan.
3850 * @param {Object} `options`
3851 * @return {Object} Returns an object with
3852 * @api public
3853 */
3854
3855picomatch$3.scan = (input, options) => scan(input, options);
3856
3857/**
3858 * Create a regular expression from a parsed glob pattern.
3859 *
3860 * ```js
3861 * const picomatch = require('picomatch');
3862 * const state = picomatch.parse('*.js');
3863 * // picomatch.compileRe(state[, options]);
3864 *
3865 * console.log(picomatch.compileRe(state));
3866 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3867 * ```
3868 * @param {String} `state` The object returned from the `.parse` method.
3869 * @param {Object} `options`
3870 * @return {RegExp} Returns a regex created from the given pattern.
3871 * @api public
3872 */
3873
3874picomatch$3.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
3875  if (returnOutput === true) {
3876    return parsed.output;
3877  }
3878
3879  const opts = options || {};
3880  const prepend = opts.contains ? '' : '^';
3881  const append = opts.contains ? '' : '$';
3882
3883  let source = `${prepend}(?:${parsed.output})${append}`;
3884  if (parsed && parsed.negated === true) {
3885    source = `^(?!${source}).*$`;
3886  }
3887
3888  const regex = picomatch$3.toRegex(source, options);
3889  if (returnState === true) {
3890    regex.state = parsed;
3891  }
3892
3893  return regex;
3894};
3895
3896picomatch$3.makeRe = (input, options, returnOutput = false, returnState = false) => {
3897  if (!input || typeof input !== 'string') {
3898    throw new TypeError('Expected a non-empty string');
3899  }
3900
3901  const opts = options || {};
3902  let parsed = { negated: false, fastpaths: true };
3903  let prefix = '';
3904  let output;
3905
3906  if (input.startsWith('./')) {
3907    input = input.slice(2);
3908    prefix = parsed.prefix = './';
3909  }
3910
3911  if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
3912    output = parse$d.fastpaths(input, options);
3913  }
3914
3915  if (output === undefined) {
3916    parsed = parse$d(input, options);
3917    parsed.prefix = prefix + (parsed.prefix || '');
3918  } else {
3919    parsed.output = output;
3920  }
3921
3922  return picomatch$3.compileRe(parsed, options, returnOutput, returnState);
3923};
3924
3925/**
3926 * Create a regular expression from the given regex source string.
3927 *
3928 * ```js
3929 * const picomatch = require('picomatch');
3930 * // picomatch.toRegex(source[, options]);
3931 *
3932 * const { output } = picomatch.parse('*.js');
3933 * console.log(picomatch.toRegex(output));
3934 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3935 * ```
3936 * @param {String} `source` Regular expression source string.
3937 * @param {Object} `options`
3938 * @return {RegExp}
3939 * @api public
3940 */
3941
3942picomatch$3.toRegex = (source, options) => {
3943  try {
3944    const opts = options || {};
3945    return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
3946  } catch (err) {
3947    if (options && options.debug === true) throw err;
3948    return /$^/;
3949  }
3950};
3951
3952/**
3953 * Picomatch constants.
3954 * @return {Object}
3955 */
3956
3957picomatch$3.constants = constants$3;
3958
3959/**
3960 * Expose "picomatch"
3961 */
3962
3963var picomatch_1 = picomatch$3;
3964
3965var picomatch$2 = picomatch_1;
3966
3967const fs$9 = require$$0$3;
3968const { Readable } = require$$1;
3969const sysPath$3 = path$b;
3970const { promisify: promisify$3 } = require$$0$4;
3971const picomatch$1 = picomatch$2;
3972
3973const readdir$1 = promisify$3(fs$9.readdir);
3974const stat$3 = promisify$3(fs$9.stat);
3975const lstat$2 = promisify$3(fs$9.lstat);
3976const realpath$2 = promisify$3(fs$9.realpath);
3977
3978/**
3979 * @typedef {Object} EntryInfo
3980 * @property {String} path
3981 * @property {String} fullPath
3982 * @property {fs.Stats=} stats
3983 * @property {fs.Dirent=} dirent
3984 * @property {String} basename
3985 */
3986
3987const BANG$2 = '!';
3988const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
3989const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
3990const FILE_TYPE = 'files';
3991const DIR_TYPE = 'directories';
3992const FILE_DIR_TYPE = 'files_directories';
3993const EVERYTHING_TYPE = 'all';
3994const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
3995
3996const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
3997const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
3998const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
3999
4000const normalizeFilter = filter => {
4001  if (filter === undefined) return;
4002  if (typeof filter === 'function') return filter;
4003
4004  if (typeof filter === 'string') {
4005    const glob = picomatch$1(filter.trim());
4006    return entry => glob(entry.basename);
4007  }
4008
4009  if (Array.isArray(filter)) {
4010    const positive = [];
4011    const negative = [];
4012    for (const item of filter) {
4013      const trimmed = item.trim();
4014      if (trimmed.charAt(0) === BANG$2) {
4015        negative.push(picomatch$1(trimmed.slice(1)));
4016      } else {
4017        positive.push(picomatch$1(trimmed));
4018      }
4019    }
4020
4021    if (negative.length > 0) {
4022      if (positive.length > 0) {
4023        return entry =>
4024          positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
4025      }
4026      return entry => !negative.some(f => f(entry.basename));
4027    }
4028    return entry => positive.some(f => f(entry.basename));
4029  }
4030};
4031
4032class ReaddirpStream extends Readable {
4033  static get defaultOptions() {
4034    return {
4035      root: '.',
4036      /* eslint-disable no-unused-vars */
4037      fileFilter: (path) => true,
4038      directoryFilter: (path) => true,
4039      /* eslint-enable no-unused-vars */
4040      type: FILE_TYPE,
4041      lstat: false,
4042      depth: 2147483648,
4043      alwaysStat: false
4044    };
4045  }
4046
4047  constructor(options = {}) {
4048    super({
4049      objectMode: true,
4050      autoDestroy: true,
4051      highWaterMark: options.highWaterMark || 4096
4052    });
4053    const opts = { ...ReaddirpStream.defaultOptions, ...options };
4054    const { root, type } = opts;
4055
4056    this._fileFilter = normalizeFilter(opts.fileFilter);
4057    this._directoryFilter = normalizeFilter(opts.directoryFilter);
4058
4059    const statMethod = opts.lstat ? lstat$2 : stat$3;
4060    // Use bigint stats if it's windows and stat() supports options (node 10+).
4061    if (wantBigintFsStats) {
4062      this._stat = path => statMethod(path, { bigint: true });
4063    } else {
4064      this._stat = statMethod;
4065    }
4066
4067    this._maxDepth = opts.depth;
4068    this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
4069    this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
4070    this._wantsEverything = type === EVERYTHING_TYPE;
4071    this._root = sysPath$3.resolve(root);
4072    this._isDirent = ('Dirent' in fs$9) && !opts.alwaysStat;
4073    this._statsProp = this._isDirent ? 'dirent' : 'stats';
4074    this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
4075
4076    // Launch stream with one parent, the root dir.
4077    this.parents = [this._exploreDir(root, 1)];
4078    this.reading = false;
4079    this.parent = undefined;
4080  }
4081
4082  async _read(batch) {
4083    if (this.reading) return;
4084    this.reading = true;
4085
4086    try {
4087      while (!this.destroyed && batch > 0) {
4088        const { path, depth, files = [] } = this.parent || {};
4089
4090        if (files.length > 0) {
4091          const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
4092          for (const entry of await Promise.all(slice)) {
4093            if (this.destroyed) return;
4094
4095            const entryType = await this._getEntryType(entry);
4096            if (entryType === 'directory' && this._directoryFilter(entry)) {
4097              if (depth <= this._maxDepth) {
4098                this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
4099              }
4100
4101              if (this._wantsDir) {
4102                this.push(entry);
4103                batch--;
4104              }
4105            } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
4106              if (this._wantsFile) {
4107                this.push(entry);
4108                batch--;
4109              }
4110            }
4111          }
4112        } else {
4113          const parent = this.parents.pop();
4114          if (!parent) {
4115            this.push(null);
4116            break;
4117          }
4118          this.parent = await parent;
4119          if (this.destroyed) return;
4120        }
4121      }
4122    } catch (error) {
4123      this.destroy(error);
4124    } finally {
4125      this.reading = false;
4126    }
4127  }
4128
4129  async _exploreDir(path, depth) {
4130    let files;
4131    try {
4132      files = await readdir$1(path, this._rdOptions);
4133    } catch (error) {
4134      this._onError(error);
4135    }
4136    return { files, depth, path };
4137  }
4138
4139  async _formatEntry(dirent, path) {
4140    let entry;
4141    try {
4142      const basename = this._isDirent ? dirent.name : dirent;
4143      const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
4144      entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
4145      entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
4146    } catch (err) {
4147      this._onError(err);
4148    }
4149    return entry;
4150  }
4151
4152  _onError(err) {
4153    if (isNormalFlowError(err) && !this.destroyed) {
4154      this.emit('warn', err);
4155    } else {
4156      this.destroy(err);
4157    }
4158  }
4159
4160  async _getEntryType(entry) {
4161    // entry may be undefined, because a warning or an error were emitted
4162    // and the statsProp is undefined
4163    const stats = entry && entry[this._statsProp];
4164    if (!stats) {
4165      return;
4166    }
4167    if (stats.isFile()) {
4168      return 'file';
4169    }
4170    if (stats.isDirectory()) {
4171      return 'directory';
4172    }
4173    if (stats && stats.isSymbolicLink()) {
4174      const full = entry.fullPath;
4175      try {
4176        const entryRealPath = await realpath$2(full);
4177        const entryRealPathStats = await lstat$2(entryRealPath);
4178        if (entryRealPathStats.isFile()) {
4179          return 'file';
4180        }
4181        if (entryRealPathStats.isDirectory()) {
4182          const len = entryRealPath.length;
4183          if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
4184            const recursiveError = new Error(
4185              `Circular symlink detected: "${full}" points to "${entryRealPath}"`
4186            );
4187            recursiveError.code = RECURSIVE_ERROR_CODE;
4188            return this._onError(recursiveError);
4189          }
4190          return 'directory';
4191        }
4192      } catch (error) {
4193        this._onError(error);
4194      }
4195    }
4196  }
4197
4198  _includeAsFile(entry) {
4199    const stats = entry && entry[this._statsProp];
4200
4201    return stats && this._wantsEverything && !stats.isDirectory();
4202  }
4203}
4204
4205/**
4206 * @typedef {Object} ReaddirpArguments
4207 * @property {Function=} fileFilter
4208 * @property {Function=} directoryFilter
4209 * @property {String=} type
4210 * @property {Number=} depth
4211 * @property {String=} root
4212 * @property {Boolean=} lstat
4213 * @property {Boolean=} bigint
4214 */
4215
4216/**
4217 * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
4218 * @param {String} root Root directory
4219 * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
4220 */
4221const readdirp$1 = (root, options = {}) => {
4222  let type = options.entryType || options.type;
4223  if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
4224  if (type) options.type = type;
4225  if (!root) {
4226    throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
4227  } else if (typeof root !== 'string') {
4228    throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
4229  } else if (type && !ALL_TYPES.includes(type)) {
4230    throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
4231  }
4232
4233  options.root = root;
4234  return new ReaddirpStream(options);
4235};
4236
4237const readdirpPromise = (root, options = {}) => {
4238  return new Promise((resolve, reject) => {
4239    const files = [];
4240    readdirp$1(root, options)
4241      .on('data', entry => files.push(entry))
4242      .on('end', () => resolve(files))
4243      .on('error', error => reject(error));
4244  });
4245};
4246
4247readdirp$1.promise = readdirpPromise;
4248readdirp$1.ReaddirpStream = ReaddirpStream;
4249readdirp$1.default = readdirp$1;
4250
4251var readdirp_1 = readdirp$1;
4252
4253var anymatch$2 = {exports: {}};
4254
4255/*!
4256 * normalize-path <https://github.com/jonschlinkert/normalize-path>
4257 *
4258 * Copyright (c) 2014-2018, Jon Schlinkert.
4259 * Released under the MIT License.
4260 */
4261
4262var normalizePath$2 = function(path, stripTrailing) {
4263  if (typeof path !== 'string') {
4264    throw new TypeError('expected path to be a string');
4265  }
4266
4267  if (path === '\\' || path === '/') return '/';
4268
4269  var len = path.length;
4270  if (len <= 1) return path;
4271
4272  // ensure that win32 namespaces has two leading slashes, so that the path is
4273  // handled properly by the win32 version of path.parse() after being normalized
4274  // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
4275  var prefix = '';
4276  if (len > 4 && path[3] === '\\') {
4277    var ch = path[2];
4278    if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
4279      path = path.slice(2);
4280      prefix = '//';
4281    }
4282  }
4283
4284  var segs = path.split(/[/\\]+/);
4285  if (stripTrailing !== false && segs[segs.length - 1] === '') {
4286    segs.pop();
4287  }
4288  return prefix + segs.join('/');
4289};
4290
4291Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
4292
4293const picomatch = picomatch$2;
4294const normalizePath$1 = normalizePath$2;
4295
4296/**
4297 * @typedef {(testString: string) => boolean} AnymatchFn
4298 * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
4299 * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
4300 */
4301const BANG$1 = '!';
4302const DEFAULT_OPTIONS = {returnIndex: false};
4303const arrify$1 = (item) => Array.isArray(item) ? item : [item];
4304
4305/**
4306 * @param {AnymatchPattern} matcher
4307 * @param {object} options
4308 * @returns {AnymatchFn}
4309 */
4310const createPattern = (matcher, options) => {
4311  if (typeof matcher === 'function') {
4312    return matcher;
4313  }
4314  if (typeof matcher === 'string') {
4315    const glob = picomatch(matcher, options);
4316    return (string) => matcher === string || glob(string);
4317  }
4318  if (matcher instanceof RegExp) {
4319    return (string) => matcher.test(string);
4320  }
4321  return (string) => false;
4322};
4323
4324/**
4325 * @param {Array<Function>} patterns
4326 * @param {Array<Function>} negPatterns
4327 * @param {String|Array} args
4328 * @param {Boolean} returnIndex
4329 * @returns {boolean|number}
4330 */
4331const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
4332  const isList = Array.isArray(args);
4333  const _path = isList ? args[0] : args;
4334  if (!isList && typeof _path !== 'string') {
4335    throw new TypeError('anymatch: second argument must be a string: got ' +
4336      Object.prototype.toString.call(_path))
4337  }
4338  const path = normalizePath$1(_path);
4339
4340  for (let index = 0; index < negPatterns.length; index++) {
4341    const nglob = negPatterns[index];
4342    if (nglob(path)) {
4343      return returnIndex ? -1 : false;
4344    }
4345  }
4346
4347  const applied = isList && [path].concat(args.slice(1));
4348  for (let index = 0; index < patterns.length; index++) {
4349    const pattern = patterns[index];
4350    if (isList ? pattern(...applied) : pattern(path)) {
4351      return returnIndex ? index : true;
4352    }
4353  }
4354
4355  return returnIndex ? -1 : false;
4356};
4357
4358/**
4359 * @param {AnymatchMatcher} matchers
4360 * @param {Array|string} testString
4361 * @param {object} options
4362 * @returns {boolean|number|Function}
4363 */
4364const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
4365  if (matchers == null) {
4366    throw new TypeError('anymatch: specify first argument');
4367  }
4368  const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
4369  const returnIndex = opts.returnIndex || false;
4370
4371  // Early cache for matchers.
4372  const mtchers = arrify$1(matchers);
4373  const negatedGlobs = mtchers
4374    .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
4375    .map(item => item.slice(1))
4376    .map(item => picomatch(item, opts));
4377  const patterns = mtchers
4378    .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
4379    .map(matcher => createPattern(matcher, opts));
4380
4381  if (testString == null) {
4382    return (testString, ri = false) => {
4383      const returnIndex = typeof ri === 'boolean' ? ri : false;
4384      return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
4385    }
4386  }
4387
4388  return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
4389};
4390
4391anymatch$1.default = anymatch$1;
4392anymatch$2.exports = anymatch$1;
4393
4394/*!
4395 * is-extglob <https://github.com/jonschlinkert/is-extglob>
4396 *
4397 * Copyright (c) 2014-2016, Jon Schlinkert.
4398 * Licensed under the MIT License.
4399 */
4400
4401var isExtglob$1 = function isExtglob(str) {
4402  if (typeof str !== 'string' || str === '') {
4403    return false;
4404  }
4405
4406  var match;
4407  while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
4408    if (match[2]) return true;
4409    str = str.slice(match.index + match[0].length);
4410  }
4411
4412  return false;
4413};
4414
4415/*!
4416 * is-glob <https://github.com/jonschlinkert/is-glob>
4417 *
4418 * Copyright (c) 2014-2017, Jon Schlinkert.
4419 * Released under the MIT License.
4420 */
4421
4422var isExtglob = isExtglob$1;
4423var chars$1 = { '{': '}', '(': ')', '[': ']'};
4424var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
4425var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
4426
4427var isGlob$2 = function isGlob(str, options) {
4428  if (typeof str !== 'string' || str === '') {
4429    return false;
4430  }
4431
4432  if (isExtglob(str)) {
4433    return true;
4434  }
4435
4436  var regex = strictRegex;
4437  var match;
4438
4439  // optionally relax regex
4440  if (options && options.strict === false) {
4441    regex = relaxedRegex;
4442  }
4443
4444  while ((match = regex.exec(str))) {
4445    if (match[2]) return true;
4446    var idx = match.index + match[0].length;
4447
4448    // if an open bracket/brace/paren is escaped,
4449    // set the index to the next closing character
4450    var open = match[1];
4451    var close = open ? chars$1[open] : null;
4452    if (open && close) {
4453      var n = str.indexOf(close, idx);
4454      if (n !== -1) {
4455        idx = n + 1;
4456      }
4457    }
4458
4459    str = str.slice(idx);
4460  }
4461  return false;
4462};
4463
4464var isGlob$1 = isGlob$2;
4465var pathPosixDirname = path$b.posix.dirname;
4466var isWin32 = require$$0$2.platform() === 'win32';
4467
4468var slash = '/';
4469var backslash = /\\/g;
4470var enclosure = /[\{\[].*[\}\]]$/;
4471var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
4472var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
4473
4474/**
4475 * @param {string} str
4476 * @param {Object} opts
4477 * @param {boolean} [opts.flipBackslashes=true]
4478 * @returns {string}
4479 */
4480var globParent$1 = function globParent(str, opts) {
4481  var options = Object.assign({ flipBackslashes: true }, opts);
4482
4483  // flip windows path separators
4484  if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
4485    str = str.replace(backslash, slash);
4486  }
4487
4488  // special case for strings ending in enclosure containing path separator
4489  if (enclosure.test(str)) {
4490    str += slash;
4491  }
4492
4493  // preserves full path in case of trailing path separator
4494  str += 'a';
4495
4496  // remove path parts that are globby
4497  do {
4498    str = pathPosixDirname(str);
4499  } while (isGlob$1(str) || globby.test(str));
4500
4501  // remove escape chars and return result
4502  return str.replace(escaped, '$1');
4503};
4504
4505var utils$3 = {};
4506
4507(function (exports) {
4508
4509exports.isInteger = num => {
4510  if (typeof num === 'number') {
4511    return Number.isInteger(num);
4512  }
4513  if (typeof num === 'string' && num.trim() !== '') {
4514    return Number.isInteger(Number(num));
4515  }
4516  return false;
4517};
4518
4519/**
4520 * Find a node of the given type
4521 */
4522
4523exports.find = (node, type) => node.nodes.find(node => node.type === type);
4524
4525/**
4526 * Find a node of the given type
4527 */
4528
4529exports.exceedsLimit = (min, max, step = 1, limit) => {
4530  if (limit === false) return false;
4531  if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
4532  return ((Number(max) - Number(min)) / Number(step)) >= limit;
4533};
4534
4535/**
4536 * Escape the given node with '\\' before node.value
4537 */
4538
4539exports.escapeNode = (block, n = 0, type) => {
4540  let node = block.nodes[n];
4541  if (!node) return;
4542
4543  if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
4544    if (node.escaped !== true) {
4545      node.value = '\\' + node.value;
4546      node.escaped = true;
4547    }
4548  }
4549};
4550
4551/**
4552 * Returns true if the given brace node should be enclosed in literal braces
4553 */
4554
4555exports.encloseBrace = node => {
4556  if (node.type !== 'brace') return false;
4557  if ((node.commas >> 0 + node.ranges >> 0) === 0) {
4558    node.invalid = true;
4559    return true;
4560  }
4561  return false;
4562};
4563
4564/**
4565 * Returns true if a brace node is invalid.
4566 */
4567
4568exports.isInvalidBrace = block => {
4569  if (block.type !== 'brace') return false;
4570  if (block.invalid === true || block.dollar) return true;
4571  if ((block.commas >> 0 + block.ranges >> 0) === 0) {
4572    block.invalid = true;
4573    return true;
4574  }
4575  if (block.open !== true || block.close !== true) {
4576    block.invalid = true;
4577    return true;
4578  }
4579  return false;
4580};
4581
4582/**
4583 * Returns true if a node is an open or close node
4584 */
4585
4586exports.isOpenOrClose = node => {
4587  if (node.type === 'open' || node.type === 'close') {
4588    return true;
4589  }
4590  return node.open === true || node.close === true;
4591};
4592
4593/**
4594 * Reduce an array of text nodes.
4595 */
4596
4597exports.reduce = nodes => nodes.reduce((acc, node) => {
4598  if (node.type === 'text') acc.push(node.value);
4599  if (node.type === 'range') node.type = 'text';
4600  return acc;
4601}, []);
4602
4603/**
4604 * Flatten an array
4605 */
4606
4607exports.flatten = (...args) => {
4608  const result = [];
4609  const flat = arr => {
4610    for (let i = 0; i < arr.length; i++) {
4611      let ele = arr[i];
4612      Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
4613    }
4614    return result;
4615  };
4616  flat(args);
4617  return result;
4618};
4619}(utils$3));
4620
4621const utils$2 = utils$3;
4622
4623var stringify$6 = (ast, options = {}) => {
4624  let stringify = (node, parent = {}) => {
4625    let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
4626    let invalidNode = node.invalid === true && options.escapeInvalid === true;
4627    let output = '';
4628
4629    if (node.value) {
4630      if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
4631        return '\\' + node.value;
4632      }
4633      return node.value;
4634    }
4635
4636    if (node.value) {
4637      return node.value;
4638    }
4639
4640    if (node.nodes) {
4641      for (let child of node.nodes) {
4642        output += stringify(child);
4643      }
4644    }
4645    return output;
4646  };
4647
4648  return stringify(ast);
4649};
4650
4651/*!
4652 * is-number <https://github.com/jonschlinkert/is-number>
4653 *
4654 * Copyright (c) 2014-present, Jon Schlinkert.
4655 * Released under the MIT License.
4656 */
4657
4658var isNumber$3 = function(num) {
4659  if (typeof num === 'number') {
4660    return num - num === 0;
4661  }
4662  if (typeof num === 'string' && num.trim() !== '') {
4663    return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
4664  }
4665  return false;
4666};
4667
4668/*!
4669 * to-regex-range <https://github.com/micromatch/to-regex-range>
4670 *
4671 * Copyright (c) 2015-present, Jon Schlinkert.
4672 * Released under the MIT License.
4673 */
4674
4675const isNumber$2 = isNumber$3;
4676
4677const toRegexRange$1 = (min, max, options) => {
4678  if (isNumber$2(min) === false) {
4679    throw new TypeError('toRegexRange: expected the first argument to be a number');
4680  }
4681
4682  if (max === void 0 || min === max) {
4683    return String(min);
4684  }
4685
4686  if (isNumber$2(max) === false) {
4687    throw new TypeError('toRegexRange: expected the second argument to be a number.');
4688  }
4689
4690  let opts = { relaxZeros: true, ...options };
4691  if (typeof opts.strictZeros === 'boolean') {
4692    opts.relaxZeros = opts.strictZeros === false;
4693  }
4694
4695  let relax = String(opts.relaxZeros);
4696  let shorthand = String(opts.shorthand);
4697  let capture = String(opts.capture);
4698  let wrap = String(opts.wrap);
4699  let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
4700
4701  if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
4702    return toRegexRange$1.cache[cacheKey].result;
4703  }
4704
4705  let a = Math.min(min, max);
4706  let b = Math.max(min, max);
4707
4708  if (Math.abs(a - b) === 1) {
4709    let result = min + '|' + max;
4710    if (opts.capture) {
4711      return `(${result})`;
4712    }
4713    if (opts.wrap === false) {
4714      return result;
4715    }
4716    return `(?:${result})`;
4717  }
4718
4719  let isPadded = hasPadding(min) || hasPadding(max);
4720  let state = { min, max, a, b };
4721  let positives = [];
4722  let negatives = [];
4723
4724  if (isPadded) {
4725    state.isPadded = isPadded;
4726    state.maxLen = String(state.max).length;
4727  }
4728
4729  if (a < 0) {
4730    let newMin = b < 0 ? Math.abs(b) : 1;
4731    negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
4732    a = state.a = 0;
4733  }
4734
4735  if (b >= 0) {
4736    positives = splitToPatterns(a, b, state, opts);
4737  }
4738
4739  state.negatives = negatives;
4740  state.positives = positives;
4741  state.result = collatePatterns(negatives, positives);
4742
4743  if (opts.capture === true) {
4744    state.result = `(${state.result})`;
4745  } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
4746    state.result = `(?:${state.result})`;
4747  }
4748
4749  toRegexRange$1.cache[cacheKey] = state;
4750  return state.result;
4751};
4752
4753function collatePatterns(neg, pos, options) {
4754  let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
4755  let onlyPositive = filterPatterns(pos, neg, '', false) || [];
4756  let intersected = filterPatterns(neg, pos, '-?', true) || [];
4757  let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
4758  return subpatterns.join('|');
4759}
4760
4761function splitToRanges(min, max) {
4762  let nines = 1;
4763  let zeros = 1;
4764
4765  let stop = countNines(min, nines);
4766  let stops = new Set([max]);
4767
4768  while (min <= stop && stop <= max) {
4769    stops.add(stop);
4770    nines += 1;
4771    stop = countNines(min, nines);
4772  }
4773
4774  stop = countZeros(max + 1, zeros) - 1;
4775
4776  while (min < stop && stop <= max) {
4777    stops.add(stop);
4778    zeros += 1;
4779    stop = countZeros(max + 1, zeros) - 1;
4780  }
4781
4782  stops = [...stops];
4783  stops.sort(compare$c);
4784  return stops;
4785}
4786
4787/**
4788 * Convert a range to a regex pattern
4789 * @param {Number} `start`
4790 * @param {Number} `stop`
4791 * @return {String}
4792 */
4793
4794function rangeToPattern(start, stop, options) {
4795  if (start === stop) {
4796    return { pattern: start, count: [], digits: 0 };
4797  }
4798
4799  let zipped = zip(start, stop);
4800  let digits = zipped.length;
4801  let pattern = '';
4802  let count = 0;
4803
4804  for (let i = 0; i < digits; i++) {
4805    let [startDigit, stopDigit] = zipped[i];
4806
4807    if (startDigit === stopDigit) {
4808      pattern += startDigit;
4809
4810    } else if (startDigit !== '0' || stopDigit !== '9') {
4811      pattern += toCharacterClass(startDigit, stopDigit);
4812
4813    } else {
4814      count++;
4815    }
4816  }
4817
4818  if (count) {
4819    pattern += options.shorthand === true ? '\\d' : '[0-9]';
4820  }
4821
4822  return { pattern, count: [count], digits };
4823}
4824
4825function splitToPatterns(min, max, tok, options) {
4826  let ranges = splitToRanges(min, max);
4827  let tokens = [];
4828  let start = min;
4829  let prev;
4830
4831  for (let i = 0; i < ranges.length; i++) {
4832    let max = ranges[i];
4833    let obj = rangeToPattern(String(start), String(max), options);
4834    let zeros = '';
4835
4836    if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
4837      if (prev.count.length > 1) {
4838        prev.count.pop();
4839      }
4840
4841      prev.count.push(obj.count[0]);
4842      prev.string = prev.pattern + toQuantifier(prev.count);
4843      start = max + 1;
4844      continue;
4845    }
4846
4847    if (tok.isPadded) {
4848      zeros = padZeros(max, tok, options);
4849    }
4850
4851    obj.string = zeros + obj.pattern + toQuantifier(obj.count);
4852    tokens.push(obj);
4853    start = max + 1;
4854    prev = obj;
4855  }
4856
4857  return tokens;
4858}
4859
4860function filterPatterns(arr, comparison, prefix, intersection, options) {
4861  let result = [];
4862
4863  for (let ele of arr) {
4864    let { string } = ele;
4865
4866    // only push if _both_ are negative...
4867    if (!intersection && !contains(comparison, 'string', string)) {
4868      result.push(prefix + string);
4869    }
4870
4871    // or _both_ are positive
4872    if (intersection && contains(comparison, 'string', string)) {
4873      result.push(prefix + string);
4874    }
4875  }
4876  return result;
4877}
4878
4879/**
4880 * Zip strings
4881 */
4882
4883function zip(a, b) {
4884  let arr = [];
4885  for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
4886  return arr;
4887}
4888
4889function compare$c(a, b) {
4890  return a > b ? 1 : b > a ? -1 : 0;
4891}
4892
4893function contains(arr, key, val) {
4894  return arr.some(ele => ele[key] === val);
4895}
4896
4897function countNines(min, len) {
4898  return Number(String(min).slice(0, -len) + '9'.repeat(len));
4899}
4900
4901function countZeros(integer, zeros) {
4902  return integer - (integer % Math.pow(10, zeros));
4903}
4904
4905function toQuantifier(digits) {
4906  let [start = 0, stop = ''] = digits;
4907  if (stop || start > 1) {
4908    return `{${start + (stop ? ',' + stop : '')}}`;
4909  }
4910  return '';
4911}
4912
4913function toCharacterClass(a, b, options) {
4914  return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
4915}
4916
4917function hasPadding(str) {
4918  return /^-?(0+)\d/.test(str);
4919}
4920
4921function padZeros(value, tok, options) {
4922  if (!tok.isPadded) {
4923    return value;
4924  }
4925
4926  let diff = Math.abs(tok.maxLen - String(value).length);
4927  let relax = options.relaxZeros !== false;
4928
4929  switch (diff) {
4930    case 0:
4931      return '';
4932    case 1:
4933      return relax ? '0?' : '0';
4934    case 2:
4935      return relax ? '0{0,2}' : '00';
4936    default: {
4937      return relax ? `0{0,${diff}}` : `0{${diff}}`;
4938    }
4939  }
4940}
4941
4942/**
4943 * Cache
4944 */
4945
4946toRegexRange$1.cache = {};
4947toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
4948
4949/**
4950 * Expose `toRegexRange`
4951 */
4952
4953var toRegexRange_1 = toRegexRange$1;
4954
4955/*!
4956 * fill-range <https://github.com/jonschlinkert/fill-range>
4957 *
4958 * Copyright (c) 2014-present, Jon Schlinkert.
4959 * Licensed under the MIT License.
4960 */
4961
4962const util$3 = require$$0$4;
4963const toRegexRange = toRegexRange_1;
4964
4965const isObject$2 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
4966
4967const transform$3 = toNumber => {
4968  return value => toNumber === true ? Number(value) : String(value);
4969};
4970
4971const isValidValue = value => {
4972  return typeof value === 'number' || (typeof value === 'string' && value !== '');
4973};
4974
4975const isNumber$1 = num => Number.isInteger(+num);
4976
4977const zeros = input => {
4978  let value = `${input}`;
4979  let index = -1;
4980  if (value[0] === '-') value = value.slice(1);
4981  if (value === '0') return false;
4982  while (value[++index] === '0');
4983  return index > 0;
4984};
4985
4986const stringify$5 = (start, end, options) => {
4987  if (typeof start === 'string' || typeof end === 'string') {
4988    return true;
4989  }
4990  return options.stringify === true;
4991};
4992
4993const pad = (input, maxLength, toNumber) => {
4994  if (maxLength > 0) {
4995    let dash = input[0] === '-' ? '-' : '';
4996    if (dash) input = input.slice(1);
4997    input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
4998  }
4999  if (toNumber === false) {
5000    return String(input);
5001  }
5002  return input;
5003};
5004
5005const toMaxLen = (input, maxLength) => {
5006  let negative = input[0] === '-' ? '-' : '';
5007  if (negative) {
5008    input = input.slice(1);
5009    maxLength--;
5010  }
5011  while (input.length < maxLength) input = '0' + input;
5012  return negative ? ('-' + input) : input;
5013};
5014
5015const toSequence = (parts, options) => {
5016  parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
5017  parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
5018
5019  let prefix = options.capture ? '' : '?:';
5020  let positives = '';
5021  let negatives = '';
5022  let result;
5023
5024  if (parts.positives.length) {
5025    positives = parts.positives.join('|');
5026  }
5027
5028  if (parts.negatives.length) {
5029    negatives = `-(${prefix}${parts.negatives.join('|')})`;
5030  }
5031
5032  if (positives && negatives) {
5033    result = `${positives}|${negatives}`;
5034  } else {
5035    result = positives || negatives;
5036  }
5037
5038  if (options.wrap) {
5039    return `(${prefix}${result})`;
5040  }
5041
5042  return result;
5043};
5044
5045const toRange = (a, b, isNumbers, options) => {
5046  if (isNumbers) {
5047    return toRegexRange(a, b, { wrap: false, ...options });
5048  }
5049
5050  let start = String.fromCharCode(a);
5051  if (a === b) return start;
5052
5053  let stop = String.fromCharCode(b);
5054  return `[${start}-${stop}]`;
5055};
5056
5057const toRegex = (start, end, options) => {
5058  if (Array.isArray(start)) {
5059    let wrap = options.wrap === true;
5060    let prefix = options.capture ? '' : '?:';
5061    return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
5062  }
5063  return toRegexRange(start, end, options);
5064};
5065
5066const rangeError = (...args) => {
5067  return new RangeError('Invalid range arguments: ' + util$3.inspect(...args));
5068};
5069
5070const invalidRange = (start, end, options) => {
5071  if (options.strictRanges === true) throw rangeError([start, end]);
5072  return [];
5073};
5074
5075const invalidStep = (step, options) => {
5076  if (options.strictRanges === true) {
5077    throw new TypeError(`Expected step "${step}" to be a number`);
5078  }
5079  return [];
5080};
5081
5082const fillNumbers = (start, end, step = 1, options = {}) => {
5083  let a = Number(start);
5084  let b = Number(end);
5085
5086  if (!Number.isInteger(a) || !Number.isInteger(b)) {
5087    if (options.strictRanges === true) throw rangeError([start, end]);
5088    return [];
5089  }
5090
5091  // fix negative zero
5092  if (a === 0) a = 0;
5093  if (b === 0) b = 0;
5094
5095  let descending = a > b;
5096  let startString = String(start);
5097  let endString = String(end);
5098  let stepString = String(step);
5099  step = Math.max(Math.abs(step), 1);
5100
5101  let padded = zeros(startString) || zeros(endString) || zeros(stepString);
5102  let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
5103  let toNumber = padded === false && stringify$5(start, end, options) === false;
5104  let format = options.transform || transform$3(toNumber);
5105
5106  if (options.toRegex && step === 1) {
5107    return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
5108  }
5109
5110  let parts = { negatives: [], positives: [] };
5111  let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
5112  let range = [];
5113  let index = 0;
5114
5115  while (descending ? a >= b : a <= b) {
5116    if (options.toRegex === true && step > 1) {
5117      push(a);
5118    } else {
5119      range.push(pad(format(a, index), maxLen, toNumber));
5120    }
5121    a = descending ? a - step : a + step;
5122    index++;
5123  }
5124
5125  if (options.toRegex === true) {
5126    return step > 1
5127      ? toSequence(parts, options)
5128      : toRegex(range, null, { wrap: false, ...options });
5129  }
5130
5131  return range;
5132};
5133
5134const fillLetters = (start, end, step = 1, options = {}) => {
5135  if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
5136    return invalidRange(start, end, options);
5137  }
5138
5139
5140  let format = options.transform || (val => String.fromCharCode(val));
5141  let a = `${start}`.charCodeAt(0);
5142  let b = `${end}`.charCodeAt(0);
5143
5144  let descending = a > b;
5145  let min = Math.min(a, b);
5146  let max = Math.max(a, b);
5147
5148  if (options.toRegex && step === 1) {
5149    return toRange(min, max, false, options);
5150  }
5151
5152  let range = [];
5153  let index = 0;
5154
5155  while (descending ? a >= b : a <= b) {
5156    range.push(format(a, index));
5157    a = descending ? a - step : a + step;
5158    index++;
5159  }
5160
5161  if (options.toRegex === true) {
5162    return toRegex(range, null, { wrap: false, options });
5163  }
5164
5165  return range;
5166};
5167
5168const fill$2 = (start, end, step, options = {}) => {
5169  if (end == null && isValidValue(start)) {
5170    return [start];
5171  }
5172
5173  if (!isValidValue(start) || !isValidValue(end)) {
5174    return invalidRange(start, end, options);
5175  }
5176
5177  if (typeof step === 'function') {
5178    return fill$2(start, end, 1, { transform: step });
5179  }
5180
5181  if (isObject$2(step)) {
5182    return fill$2(start, end, 0, step);
5183  }
5184
5185  let opts = { ...options };
5186  if (opts.capture === true) opts.wrap = true;
5187  step = step || opts.step || 1;
5188
5189  if (!isNumber$1(step)) {
5190    if (step != null && !isObject$2(step)) return invalidStep(step, opts);
5191    return fill$2(start, end, 1, step);
5192  }
5193
5194  if (isNumber$1(start) && isNumber$1(end)) {
5195    return fillNumbers(start, end, step, opts);
5196  }
5197
5198  return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
5199};
5200
5201var fillRange = fill$2;
5202
5203const fill$1 = fillRange;
5204const utils$1 = utils$3;
5205
5206const compile$1 = (ast, options = {}) => {
5207  let walk = (node, parent = {}) => {
5208    let invalidBlock = utils$1.isInvalidBrace(parent);
5209    let invalidNode = node.invalid === true && options.escapeInvalid === true;
5210    let invalid = invalidBlock === true || invalidNode === true;
5211    let prefix = options.escapeInvalid === true ? '\\' : '';
5212    let output = '';
5213
5214    if (node.isOpen === true) {
5215      return prefix + node.value;
5216    }
5217    if (node.isClose === true) {
5218      return prefix + node.value;
5219    }
5220
5221    if (node.type === 'open') {
5222      return invalid ? (prefix + node.value) : '(';
5223    }
5224
5225    if (node.type === 'close') {
5226      return invalid ? (prefix + node.value) : ')';
5227    }
5228
5229    if (node.type === 'comma') {
5230      return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
5231    }
5232
5233    if (node.value) {
5234      return node.value;
5235    }
5236
5237    if (node.nodes && node.ranges > 0) {
5238      let args = utils$1.reduce(node.nodes);
5239      let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
5240
5241      if (range.length !== 0) {
5242        return args.length > 1 && range.length > 1 ? `(${range})` : range;
5243      }
5244    }
5245
5246    if (node.nodes) {
5247      for (let child of node.nodes) {
5248        output += walk(child, node);
5249      }
5250    }
5251    return output;
5252  };
5253
5254  return walk(ast);
5255};
5256
5257var compile_1 = compile$1;
5258
5259const fill = fillRange;
5260const stringify$4 = stringify$6;
5261const utils = utils$3;
5262
5263const append = (queue = '', stash = '', enclose = false) => {
5264  let result = [];
5265
5266  queue = [].concat(queue);
5267  stash = [].concat(stash);
5268
5269  if (!stash.length) return queue;
5270  if (!queue.length) {
5271    return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
5272  }
5273
5274  for (let item of queue) {
5275    if (Array.isArray(item)) {
5276      for (let value of item) {
5277        result.push(append(value, stash, enclose));
5278      }
5279    } else {
5280      for (let ele of stash) {
5281        if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
5282        result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
5283      }
5284    }
5285  }
5286  return utils.flatten(result);
5287};
5288
5289const expand$4 = (ast, options = {}) => {
5290  let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
5291
5292  let walk = (node, parent = {}) => {
5293    node.queue = [];
5294
5295    let p = parent;
5296    let q = parent.queue;
5297
5298    while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
5299      p = p.parent;
5300      q = p.queue;
5301    }
5302
5303    if (node.invalid || node.dollar) {
5304      q.push(append(q.pop(), stringify$4(node, options)));
5305      return;
5306    }
5307
5308    if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
5309      q.push(append(q.pop(), ['{}']));
5310      return;
5311    }
5312
5313    if (node.nodes && node.ranges > 0) {
5314      let args = utils.reduce(node.nodes);
5315
5316      if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
5317        throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
5318      }
5319
5320      let range = fill(...args, options);
5321      if (range.length === 0) {
5322        range = stringify$4(node, options);
5323      }
5324
5325      q.push(append(q.pop(), range));
5326      node.nodes = [];
5327      return;
5328    }
5329
5330    let enclose = utils.encloseBrace(node);
5331    let queue = node.queue;
5332    let block = node;
5333
5334    while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
5335      block = block.parent;
5336      queue = block.queue;
5337    }
5338
5339    for (let i = 0; i < node.nodes.length; i++) {
5340      let child = node.nodes[i];
5341
5342      if (child.type === 'comma' && node.type === 'brace') {
5343        if (i === 1) queue.push('');
5344        queue.push('');
5345        continue;
5346      }
5347
5348      if (child.type === 'close') {
5349        q.push(append(q.pop(), queue, enclose));
5350        continue;
5351      }
5352
5353      if (child.value && child.type !== 'open') {
5354        queue.push(append(queue.pop(), child.value));
5355        continue;
5356      }
5357
5358      if (child.nodes) {
5359        walk(child, node);
5360      }
5361    }
5362
5363    return queue;
5364  };
5365
5366  return utils.flatten(walk(ast));
5367};
5368
5369var expand_1 = expand$4;
5370
5371var constants$2 = {
5372  MAX_LENGTH: 1024 * 64,
5373
5374  // Digits
5375  CHAR_0: '0', /* 0 */
5376  CHAR_9: '9', /* 9 */
5377
5378  // Alphabet chars.
5379  CHAR_UPPERCASE_A: 'A', /* A */
5380  CHAR_LOWERCASE_A: 'a', /* a */
5381  CHAR_UPPERCASE_Z: 'Z', /* Z */
5382  CHAR_LOWERCASE_Z: 'z', /* z */
5383
5384  CHAR_LEFT_PARENTHESES: '(', /* ( */
5385  CHAR_RIGHT_PARENTHESES: ')', /* ) */
5386
5387  CHAR_ASTERISK: '*', /* * */
5388
5389  // Non-alphabetic chars.
5390  CHAR_AMPERSAND: '&', /* & */
5391  CHAR_AT: '@', /* @ */
5392  CHAR_BACKSLASH: '\\', /* \ */
5393  CHAR_BACKTICK: '`', /* ` */
5394  CHAR_CARRIAGE_RETURN: '\r', /* \r */
5395  CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
5396  CHAR_COLON: ':', /* : */
5397  CHAR_COMMA: ',', /* , */
5398  CHAR_DOLLAR: '$', /* . */
5399  CHAR_DOT: '.', /* . */
5400  CHAR_DOUBLE_QUOTE: '"', /* " */
5401  CHAR_EQUAL: '=', /* = */
5402  CHAR_EXCLAMATION_MARK: '!', /* ! */
5403  CHAR_FORM_FEED: '\f', /* \f */
5404  CHAR_FORWARD_SLASH: '/', /* / */
5405  CHAR_HASH: '#', /* # */
5406  CHAR_HYPHEN_MINUS: '-', /* - */
5407  CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
5408  CHAR_LEFT_CURLY_BRACE: '{', /* { */
5409  CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
5410  CHAR_LINE_FEED: '\n', /* \n */
5411  CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
5412  CHAR_PERCENT: '%', /* % */
5413  CHAR_PLUS: '+', /* + */
5414  CHAR_QUESTION_MARK: '?', /* ? */
5415  CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
5416  CHAR_RIGHT_CURLY_BRACE: '}', /* } */
5417  CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
5418  CHAR_SEMICOLON: ';', /* ; */
5419  CHAR_SINGLE_QUOTE: '\'', /* ' */
5420  CHAR_SPACE: ' ', /*   */
5421  CHAR_TAB: '\t', /* \t */
5422  CHAR_UNDERSCORE: '_', /* _ */
5423  CHAR_VERTICAL_LINE: '|', /* | */
5424  CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
5425};
5426
5427const stringify$3 = stringify$6;
5428
5429/**
5430 * Constants
5431 */
5432
5433const {
5434  MAX_LENGTH: MAX_LENGTH$3,
5435  CHAR_BACKSLASH, /* \ */
5436  CHAR_BACKTICK, /* ` */
5437  CHAR_COMMA: CHAR_COMMA$1, /* , */
5438  CHAR_DOT, /* . */
5439  CHAR_LEFT_PARENTHESES, /* ( */
5440  CHAR_RIGHT_PARENTHESES, /* ) */
5441  CHAR_LEFT_CURLY_BRACE, /* { */
5442  CHAR_RIGHT_CURLY_BRACE, /* } */
5443  CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
5444  CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */
5445  CHAR_DOUBLE_QUOTE: CHAR_DOUBLE_QUOTE$1, /* " */
5446  CHAR_SINGLE_QUOTE: CHAR_SINGLE_QUOTE$1, /* ' */
5447  CHAR_NO_BREAK_SPACE,
5448  CHAR_ZERO_WIDTH_NOBREAK_SPACE
5449} = constants$2;
5450
5451/**
5452 * parse
5453 */
5454
5455const parse$c = (input, options = {}) => {
5456  if (typeof input !== 'string') {
5457    throw new TypeError('Expected a string');
5458  }
5459
5460  let opts = options || {};
5461  let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
5462  if (input.length > max) {
5463    throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
5464  }
5465
5466  let ast = { type: 'root', input, nodes: [] };
5467  let stack = [ast];
5468  let block = ast;
5469  let prev = ast;
5470  let brackets = 0;
5471  let length = input.length;
5472  let index = 0;
5473  let depth = 0;
5474  let value;
5475
5476  /**
5477   * Helpers
5478   */
5479
5480  const advance = () => input[index++];
5481  const push = node => {
5482    if (node.type === 'text' && prev.type === 'dot') {
5483      prev.type = 'text';
5484    }
5485
5486    if (prev && prev.type === 'text' && node.type === 'text') {
5487      prev.value += node.value;
5488      return;
5489    }
5490
5491    block.nodes.push(node);
5492    node.parent = block;
5493    node.prev = prev;
5494    prev = node;
5495    return node;
5496  };
5497
5498  push({ type: 'bos' });
5499
5500  while (index < length) {
5501    block = stack[stack.length - 1];
5502    value = advance();
5503
5504    /**
5505     * Invalid chars
5506     */
5507
5508    if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
5509      continue;
5510    }
5511
5512    /**
5513     * Escaped chars
5514     */
5515
5516    if (value === CHAR_BACKSLASH) {
5517      push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
5518      continue;
5519    }
5520
5521    /**
5522     * Right square bracket (literal): ']'
5523     */
5524
5525    if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
5526      push({ type: 'text', value: '\\' + value });
5527      continue;
5528    }
5529
5530    /**
5531     * Left square bracket: '['
5532     */
5533
5534    if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
5535      brackets++;
5536      let next;
5537
5538      while (index < length && (next = advance())) {
5539        value += next;
5540
5541        if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
5542          brackets++;
5543          continue;
5544        }
5545
5546        if (next === CHAR_BACKSLASH) {
5547          value += advance();
5548          continue;
5549        }
5550
5551        if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
5552          brackets--;
5553
5554          if (brackets === 0) {
5555            break;
5556          }
5557        }
5558      }
5559
5560      push({ type: 'text', value });
5561      continue;
5562    }
5563
5564    /**
5565     * Parentheses
5566     */
5567
5568    if (value === CHAR_LEFT_PARENTHESES) {
5569      block = push({ type: 'paren', nodes: [] });
5570      stack.push(block);
5571      push({ type: 'text', value });
5572      continue;
5573    }
5574
5575    if (value === CHAR_RIGHT_PARENTHESES) {
5576      if (block.type !== 'paren') {
5577        push({ type: 'text', value });
5578        continue;
5579      }
5580      block = stack.pop();
5581      push({ type: 'text', value });
5582      block = stack[stack.length - 1];
5583      continue;
5584    }
5585
5586    /**
5587     * Quotes: '|"|`
5588     */
5589
5590    if (value === CHAR_DOUBLE_QUOTE$1 || value === CHAR_SINGLE_QUOTE$1 || value === CHAR_BACKTICK) {
5591      let open = value;
5592      let next;
5593
5594      if (options.keepQuotes !== true) {
5595        value = '';
5596      }
5597
5598      while (index < length && (next = advance())) {
5599        if (next === CHAR_BACKSLASH) {
5600          value += next + advance();
5601          continue;
5602        }
5603
5604        if (next === open) {
5605          if (options.keepQuotes === true) value += next;
5606          break;
5607        }
5608
5609        value += next;
5610      }
5611
5612      push({ type: 'text', value });
5613      continue;
5614    }
5615
5616    /**
5617     * Left curly brace: '{'
5618     */
5619
5620    if (value === CHAR_LEFT_CURLY_BRACE) {
5621      depth++;
5622
5623      let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
5624      let brace = {
5625        type: 'brace',
5626        open: true,
5627        close: false,
5628        dollar,
5629        depth,
5630        commas: 0,
5631        ranges: 0,
5632        nodes: []
5633      };
5634
5635      block = push(brace);
5636      stack.push(block);
5637      push({ type: 'open', value });
5638      continue;
5639    }
5640
5641    /**
5642     * Right curly brace: '}'
5643     */
5644
5645    if (value === CHAR_RIGHT_CURLY_BRACE) {
5646      if (block.type !== 'brace') {
5647        push({ type: 'text', value });
5648        continue;
5649      }
5650
5651      let type = 'close';
5652      block = stack.pop();
5653      block.close = true;
5654
5655      push({ type, value });
5656      depth--;
5657
5658      block = stack[stack.length - 1];
5659      continue;
5660    }
5661
5662    /**
5663     * Comma: ','
5664     */
5665
5666    if (value === CHAR_COMMA$1 && depth > 0) {
5667      if (block.ranges > 0) {
5668        block.ranges = 0;
5669        let open = block.nodes.shift();
5670        block.nodes = [open, { type: 'text', value: stringify$3(block) }];
5671      }
5672
5673      push({ type: 'comma', value });
5674      block.commas++;
5675      continue;
5676    }
5677
5678    /**
5679     * Dot: '.'
5680     */
5681
5682    if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
5683      let siblings = block.nodes;
5684
5685      if (depth === 0 || siblings.length === 0) {
5686        push({ type: 'text', value });
5687        continue;
5688      }
5689
5690      if (prev.type === 'dot') {
5691        block.range = [];
5692        prev.value += value;
5693        prev.type = 'range';
5694
5695        if (block.nodes.length !== 3 && block.nodes.length !== 5) {
5696          block.invalid = true;
5697          block.ranges = 0;
5698          prev.type = 'text';
5699          continue;
5700        }
5701
5702        block.ranges++;
5703        block.args = [];
5704        continue;
5705      }
5706
5707      if (prev.type === 'range') {
5708        siblings.pop();
5709
5710        let before = siblings[siblings.length - 1];
5711        before.value += prev.value + value;
5712        prev = before;
5713        block.ranges--;
5714        continue;
5715      }
5716
5717      push({ type: 'dot', value });
5718      continue;
5719    }
5720
5721    /**
5722     * Text
5723     */
5724
5725    push({ type: 'text', value });
5726  }
5727
5728  // Mark imbalanced braces and brackets as invalid
5729  do {
5730    block = stack.pop();
5731
5732    if (block.type !== 'root') {
5733      block.nodes.forEach(node => {
5734        if (!node.nodes) {
5735          if (node.type === 'open') node.isOpen = true;
5736          if (node.type === 'close') node.isClose = true;
5737          if (!node.nodes) node.type = 'text';
5738          node.invalid = true;
5739        }
5740      });
5741
5742      // get the location of the block on parent.nodes (block's siblings)
5743      let parent = stack[stack.length - 1];
5744      let index = parent.nodes.indexOf(block);
5745      // replace the (invalid) block with it's nodes
5746      parent.nodes.splice(index, 1, ...block.nodes);
5747    }
5748  } while (stack.length > 0);
5749
5750  push({ type: 'eos' });
5751  return ast;
5752};
5753
5754var parse_1$1 = parse$c;
5755
5756const stringify$2 = stringify$6;
5757const compile = compile_1;
5758const expand$3 = expand_1;
5759const parse$b = parse_1$1;
5760
5761/**
5762 * Expand the given pattern or create a regex-compatible string.
5763 *
5764 * ```js
5765 * const braces = require('braces');
5766 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
5767 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
5768 * ```
5769 * @param {String} `str`
5770 * @param {Object} `options`
5771 * @return {String}
5772 * @api public
5773 */
5774
5775const braces$1 = (input, options = {}) => {
5776  let output = [];
5777
5778  if (Array.isArray(input)) {
5779    for (let pattern of input) {
5780      let result = braces$1.create(pattern, options);
5781      if (Array.isArray(result)) {
5782        output.push(...result);
5783      } else {
5784        output.push(result);
5785      }
5786    }
5787  } else {
5788    output = [].concat(braces$1.create(input, options));
5789  }
5790
5791  if (options && options.expand === true && options.nodupes === true) {
5792    output = [...new Set(output)];
5793  }
5794  return output;
5795};
5796
5797/**
5798 * Parse the given `str` with the given `options`.
5799 *
5800 * ```js
5801 * // braces.parse(pattern, [, options]);
5802 * const ast = braces.parse('a/{b,c}/d');
5803 * console.log(ast);
5804 * ```
5805 * @param {String} pattern Brace pattern to parse
5806 * @param {Object} options
5807 * @return {Object} Returns an AST
5808 * @api public
5809 */
5810
5811braces$1.parse = (input, options = {}) => parse$b(input, options);
5812
5813/**
5814 * Creates a braces string from an AST, or an AST node.
5815 *
5816 * ```js
5817 * const braces = require('braces');
5818 * let ast = braces.parse('foo/{a,b}/bar');
5819 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
5820 * ```
5821 * @param {String} `input` Brace pattern or AST.
5822 * @param {Object} `options`
5823 * @return {Array} Returns an array of expanded values.
5824 * @api public
5825 */
5826
5827braces$1.stringify = (input, options = {}) => {
5828  if (typeof input === 'string') {
5829    return stringify$2(braces$1.parse(input, options), options);
5830  }
5831  return stringify$2(input, options);
5832};
5833
5834/**
5835 * Compiles a brace pattern into a regex-compatible, optimized string.
5836 * This method is called by the main [braces](#braces) function by default.
5837 *
5838 * ```js
5839 * const braces = require('braces');
5840 * console.log(braces.compile('a/{b,c}/d'));
5841 * //=> ['a/(b|c)/d']
5842 * ```
5843 * @param {String} `input` Brace pattern or AST.
5844 * @param {Object} `options`
5845 * @return {Array} Returns an array of expanded values.
5846 * @api public
5847 */
5848
5849braces$1.compile = (input, options = {}) => {
5850  if (typeof input === 'string') {
5851    input = braces$1.parse(input, options);
5852  }
5853  return compile(input, options);
5854};
5855
5856/**
5857 * Expands a brace pattern into an array. This method is called by the
5858 * main [braces](#braces) function when `options.expand` is true. Before
5859 * using this method it's recommended that you read the [performance notes](#performance))
5860 * and advantages of using [.compile](#compile) instead.
5861 *
5862 * ```js
5863 * const braces = require('braces');
5864 * console.log(braces.expand('a/{b,c}/d'));
5865 * //=> ['a/b/d', 'a/c/d'];
5866 * ```
5867 * @param {String} `pattern` Brace pattern
5868 * @param {Object} `options`
5869 * @return {Array} Returns an array of expanded values.
5870 * @api public
5871 */
5872
5873braces$1.expand = (input, options = {}) => {
5874  if (typeof input === 'string') {
5875    input = braces$1.parse(input, options);
5876  }
5877
5878  let result = expand$3(input, options);
5879
5880  // filter out empty strings if specified
5881  if (options.noempty === true) {
5882    result = result.filter(Boolean);
5883  }
5884
5885  // filter out duplicates if specified
5886  if (options.nodupes === true) {
5887    result = [...new Set(result)];
5888  }
5889
5890  return result;
5891};
5892
5893/**
5894 * Processes a brace pattern and returns either an expanded array
5895 * (if `options.expand` is true), a highly optimized regex-compatible string.
5896 * This method is called by the main [braces](#braces) function.
5897 *
5898 * ```js
5899 * const braces = require('braces');
5900 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
5901 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
5902 * ```
5903 * @param {String} `pattern` Brace pattern
5904 * @param {Object} `options`
5905 * @return {Array} Returns an array of expanded values.
5906 * @api public
5907 */
5908
5909braces$1.create = (input, options = {}) => {
5910  if (input === '' || input.length < 3) {
5911    return [input];
5912  }
5913
5914 return options.expand !== true
5915    ? braces$1.compile(input, options)
5916    : braces$1.expand(input, options);
5917};
5918
5919/**
5920 * Expose "braces"
5921 */
5922
5923var braces_1 = braces$1;
5924
5925var require$$0$1 = [
5926	"3dm",
5927	"3ds",
5928	"3g2",
5929	"3gp",
5930	"7z",
5931	"a",
5932	"aac",
5933	"adp",
5934	"ai",
5935	"aif",
5936	"aiff",
5937	"alz",
5938	"ape",
5939	"apk",
5940	"appimage",
5941	"ar",
5942	"arj",
5943	"asf",
5944	"au",
5945	"avi",
5946	"bak",
5947	"baml",
5948	"bh",
5949	"bin",
5950	"bk",
5951	"bmp",
5952	"btif",
5953	"bz2",
5954	"bzip2",
5955	"cab",
5956	"caf",
5957	"cgm",
5958	"class",
5959	"cmx",
5960	"cpio",
5961	"cr2",
5962	"cur",
5963	"dat",
5964	"dcm",
5965	"deb",
5966	"dex",
5967	"djvu",
5968	"dll",
5969	"dmg",
5970	"dng",
5971	"doc",
5972	"docm",
5973	"docx",
5974	"dot",
5975	"dotm",
5976	"dra",
5977	"DS_Store",
5978	"dsk",
5979	"dts",
5980	"dtshd",
5981	"dvb",
5982	"dwg",
5983	"dxf",
5984	"ecelp4800",
5985	"ecelp7470",
5986	"ecelp9600",
5987	"egg",
5988	"eol",
5989	"eot",
5990	"epub",
5991	"exe",
5992	"f4v",
5993	"fbs",
5994	"fh",
5995	"fla",
5996	"flac",
5997	"flatpak",
5998	"fli",
5999	"flv",
6000	"fpx",
6001	"fst",
6002	"fvt",
6003	"g3",
6004	"gh",
6005	"gif",
6006	"graffle",
6007	"gz",
6008	"gzip",
6009	"h261",
6010	"h263",
6011	"h264",
6012	"icns",
6013	"ico",
6014	"ief",
6015	"img",
6016	"ipa",
6017	"iso",
6018	"jar",
6019	"jpeg",
6020	"jpg",
6021	"jpgv",
6022	"jpm",
6023	"jxr",
6024	"key",
6025	"ktx",
6026	"lha",
6027	"lib",
6028	"lvp",
6029	"lz",
6030	"lzh",
6031	"lzma",
6032	"lzo",
6033	"m3u",
6034	"m4a",
6035	"m4v",
6036	"mar",
6037	"mdi",
6038	"mht",
6039	"mid",
6040	"midi",
6041	"mj2",
6042	"mka",
6043	"mkv",
6044	"mmr",
6045	"mng",
6046	"mobi",
6047	"mov",
6048	"movie",
6049	"mp3",
6050	"mp4",
6051	"mp4a",
6052	"mpeg",
6053	"mpg",
6054	"mpga",
6055	"mxu",
6056	"nef",
6057	"npx",
6058	"numbers",
6059	"nupkg",
6060	"o",
6061	"odp",
6062	"ods",
6063	"odt",
6064	"oga",
6065	"ogg",
6066	"ogv",
6067	"otf",
6068	"ott",
6069	"pages",
6070	"pbm",
6071	"pcx",
6072	"pdb",
6073	"pdf",
6074	"pea",
6075	"pgm",
6076	"pic",
6077	"png",
6078	"pnm",
6079	"pot",
6080	"potm",
6081	"potx",
6082	"ppa",
6083	"ppam",
6084	"ppm",
6085	"pps",
6086	"ppsm",
6087	"ppsx",
6088	"ppt",
6089	"pptm",
6090	"pptx",
6091	"psd",
6092	"pya",
6093	"pyc",
6094	"pyo",
6095	"pyv",
6096	"qt",
6097	"rar",
6098	"ras",
6099	"raw",
6100	"resources",
6101	"rgb",
6102	"rip",
6103	"rlc",
6104	"rmf",
6105	"rmvb",
6106	"rpm",
6107	"rtf",
6108	"rz",
6109	"s3m",
6110	"s7z",
6111	"scpt",
6112	"sgi",
6113	"shar",
6114	"snap",
6115	"sil",
6116	"sketch",
6117	"slk",
6118	"smv",
6119	"snk",
6120	"so",
6121	"stl",
6122	"suo",
6123	"sub",
6124	"swf",
6125	"tar",
6126	"tbz",
6127	"tbz2",
6128	"tga",
6129	"tgz",
6130	"thmx",
6131	"tif",
6132	"tiff",
6133	"tlz",
6134	"ttc",
6135	"ttf",
6136	"txz",
6137	"udf",
6138	"uvh",
6139	"uvi",
6140	"uvm",
6141	"uvp",
6142	"uvs",
6143	"uvu",
6144	"viv",
6145	"vob",
6146	"war",
6147	"wav",
6148	"wax",
6149	"wbmp",
6150	"wdp",
6151	"weba",
6152	"webm",
6153	"webp",
6154	"whl",
6155	"wim",
6156	"wm",
6157	"wma",
6158	"wmv",
6159	"wmx",
6160	"woff",
6161	"woff2",
6162	"wrm",
6163	"wvx",
6164	"xbm",
6165	"xif",
6166	"xla",
6167	"xlam",
6168	"xls",
6169	"xlsb",
6170	"xlsm",
6171	"xlsx",
6172	"xlt",
6173	"xltm",
6174	"xltx",
6175	"xm",
6176	"xmind",
6177	"xpi",
6178	"xpm",
6179	"xwd",
6180	"xz",
6181	"z",
6182	"zip",
6183	"zipx"
6184];
6185
6186var binaryExtensions$1 = require$$0$1;
6187
6188const path$8 = path$b;
6189const binaryExtensions = binaryExtensions$1;
6190
6191const extensions = new Set(binaryExtensions);
6192
6193var isBinaryPath$1 = filePath => extensions.has(path$8.extname(filePath).slice(1).toLowerCase());
6194
6195var constants$1 = {};
6196
6197(function (exports) {
6198
6199const {sep} = path$b;
6200const {platform} = process;
6201const os = require$$0$2;
6202
6203exports.EV_ALL = 'all';
6204exports.EV_READY = 'ready';
6205exports.EV_ADD = 'add';
6206exports.EV_CHANGE = 'change';
6207exports.EV_ADD_DIR = 'addDir';
6208exports.EV_UNLINK = 'unlink';
6209exports.EV_UNLINK_DIR = 'unlinkDir';
6210exports.EV_RAW = 'raw';
6211exports.EV_ERROR = 'error';
6212
6213exports.STR_DATA = 'data';
6214exports.STR_END = 'end';
6215exports.STR_CLOSE = 'close';
6216
6217exports.FSEVENT_CREATED = 'created';
6218exports.FSEVENT_MODIFIED = 'modified';
6219exports.FSEVENT_DELETED = 'deleted';
6220exports.FSEVENT_MOVED = 'moved';
6221exports.FSEVENT_CLONED = 'cloned';
6222exports.FSEVENT_UNKNOWN = 'unknown';
6223exports.FSEVENT_TYPE_FILE = 'file';
6224exports.FSEVENT_TYPE_DIRECTORY = 'directory';
6225exports.FSEVENT_TYPE_SYMLINK = 'symlink';
6226
6227exports.KEY_LISTENERS = 'listeners';
6228exports.KEY_ERR = 'errHandlers';
6229exports.KEY_RAW = 'rawEmitters';
6230exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
6231
6232exports.DOT_SLASH = `.${sep}`;
6233
6234exports.BACK_SLASH_RE = /\\/g;
6235exports.DOUBLE_SLASH_RE = /\/\//;
6236exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
6237exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
6238exports.REPLACER_RE = /^\.[/\\]/;
6239
6240exports.SLASH = '/';
6241exports.SLASH_SLASH = '//';
6242exports.BRACE_START = '{';
6243exports.BANG = '!';
6244exports.ONE_DOT = '.';
6245exports.TWO_DOTS = '..';
6246exports.STAR = '*';
6247exports.GLOBSTAR = '**';
6248exports.ROOT_GLOBSTAR = '/**/*';
6249exports.SLASH_GLOBSTAR = '/**';
6250exports.DIR_SUFFIX = 'Dir';
6251exports.ANYMATCH_OPTS = {dot: true};
6252exports.STRING_TYPE = 'string';
6253exports.FUNCTION_TYPE = 'function';
6254exports.EMPTY_STR = '';
6255exports.EMPTY_FN = () => {};
6256exports.IDENTITY_FN = val => val;
6257
6258exports.isWindows = platform === 'win32';
6259exports.isMacos = platform === 'darwin';
6260exports.isLinux = platform === 'linux';
6261exports.isIBMi = os.type() === 'OS400';
6262}(constants$1));
6263
6264const fs$8 = require$$0$3;
6265const sysPath$2 = path$b;
6266const { promisify: promisify$2 } = require$$0$4;
6267const isBinaryPath = isBinaryPath$1;
6268const {
6269  isWindows: isWindows$3,
6270  isLinux,
6271  EMPTY_FN: EMPTY_FN$2,
6272  EMPTY_STR: EMPTY_STR$1,
6273  KEY_LISTENERS,
6274  KEY_ERR,
6275  KEY_RAW,
6276  HANDLER_KEYS,
6277  EV_CHANGE: EV_CHANGE$2,
6278  EV_ADD: EV_ADD$2,
6279  EV_ADD_DIR: EV_ADD_DIR$2,
6280  EV_ERROR: EV_ERROR$2,
6281  STR_DATA: STR_DATA$1,
6282  STR_END: STR_END$2,
6283  BRACE_START: BRACE_START$1,
6284  STAR
6285} = constants$1;
6286
6287const THROTTLE_MODE_WATCH = 'watch';
6288
6289const open = promisify$2(fs$8.open);
6290const stat$2 = promisify$2(fs$8.stat);
6291const lstat$1 = promisify$2(fs$8.lstat);
6292const close = promisify$2(fs$8.close);
6293const fsrealpath = promisify$2(fs$8.realpath);
6294
6295const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
6296
6297// TODO: emit errors properly. Example: EMFILE on Macos.
6298const foreach = (val, fn) => {
6299  if (val instanceof Set) {
6300    val.forEach(fn);
6301  } else {
6302    fn(val);
6303  }
6304};
6305
6306const addAndConvert = (main, prop, item) => {
6307  let container = main[prop];
6308  if (!(container instanceof Set)) {
6309    main[prop] = container = new Set([container]);
6310  }
6311  container.add(item);
6312};
6313
6314const clearItem = cont => key => {
6315  const set = cont[key];
6316  if (set instanceof Set) {
6317    set.clear();
6318  } else {
6319    delete cont[key];
6320  }
6321};
6322
6323const delFromSet = (main, prop, item) => {
6324  const container = main[prop];
6325  if (container instanceof Set) {
6326    container.delete(item);
6327  } else if (container === item) {
6328    delete main[prop];
6329  }
6330};
6331
6332const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
6333
6334/**
6335 * @typedef {String} Path
6336 */
6337
6338// fs_watch helpers
6339
6340// object to hold per-process fs_watch instances
6341// (may be shared across chokidar FSWatcher instances)
6342
6343/**
6344 * @typedef {Object} FsWatchContainer
6345 * @property {Set} listeners
6346 * @property {Set} errHandlers
6347 * @property {Set} rawEmitters
6348 * @property {fs.FSWatcher=} watcher
6349 * @property {Boolean=} watcherUnusable
6350 */
6351
6352/**
6353 * @type {Map<String,FsWatchContainer>}
6354 */
6355const FsWatchInstances = new Map();
6356
6357/**
6358 * Instantiates the fs_watch interface
6359 * @param {String} path to be watched
6360 * @param {Object} options to be passed to fs_watch
6361 * @param {Function} listener main event handler
6362 * @param {Function} errHandler emits info about errors
6363 * @param {Function} emitRaw emits raw event data
6364 * @returns {fs.FSWatcher} new fsevents instance
6365 */
6366function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
6367  const handleEvent = (rawEvent, evPath) => {
6368    listener(path);
6369    emitRaw(rawEvent, evPath, {watchedPath: path});
6370
6371    // emit based on events occurring for files from a directory's watcher in
6372    // case the file's watcher misses it (and rely on throttling to de-dupe)
6373    if (evPath && path !== evPath) {
6374      fsWatchBroadcast(
6375        sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
6376      );
6377    }
6378  };
6379  try {
6380    return fs$8.watch(path, options, handleEvent);
6381  } catch (error) {
6382    errHandler(error);
6383  }
6384}
6385
6386/**
6387 * Helper for passing fs_watch event data to a collection of listeners
6388 * @param {Path} fullPath absolute path bound to fs_watch instance
6389 * @param {String} type listener type
6390 * @param {*=} val1 arguments to be passed to listeners
6391 * @param {*=} val2
6392 * @param {*=} val3
6393 */
6394const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
6395  const cont = FsWatchInstances.get(fullPath);
6396  if (!cont) return;
6397  foreach(cont[type], (listener) => {
6398    listener(val1, val2, val3);
6399  });
6400};
6401
6402/**
6403 * Instantiates the fs_watch interface or binds listeners
6404 * to an existing one covering the same file system entry
6405 * @param {String} path
6406 * @param {String} fullPath absolute path
6407 * @param {Object} options to be passed to fs_watch
6408 * @param {Object} handlers container for event listener functions
6409 */
6410const setFsWatchListener = (path, fullPath, options, handlers) => {
6411  const {listener, errHandler, rawEmitter} = handlers;
6412  let cont = FsWatchInstances.get(fullPath);
6413
6414  /** @type {fs.FSWatcher=} */
6415  let watcher;
6416  if (!options.persistent) {
6417    watcher = createFsWatchInstance(
6418      path, options, listener, errHandler, rawEmitter
6419    );
6420    return watcher.close.bind(watcher);
6421  }
6422  if (cont) {
6423    addAndConvert(cont, KEY_LISTENERS, listener);
6424    addAndConvert(cont, KEY_ERR, errHandler);
6425    addAndConvert(cont, KEY_RAW, rawEmitter);
6426  } else {
6427    watcher = createFsWatchInstance(
6428      path,
6429      options,
6430      fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
6431      errHandler, // no need to use broadcast here
6432      fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
6433    );
6434    if (!watcher) return;
6435    watcher.on(EV_ERROR$2, async (error) => {
6436      const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
6437      cont.watcherUnusable = true; // documented since Node 10.4.1
6438      // Workaround for https://github.com/joyent/node/issues/4337
6439      if (isWindows$3 && error.code === 'EPERM') {
6440        try {
6441          const fd = await open(path, 'r');
6442          await close(fd);
6443          broadcastErr(error);
6444        } catch (err) {}
6445      } else {
6446        broadcastErr(error);
6447      }
6448    });
6449    cont = {
6450      listeners: listener,
6451      errHandlers: errHandler,
6452      rawEmitters: rawEmitter,
6453      watcher
6454    };
6455    FsWatchInstances.set(fullPath, cont);
6456  }
6457  // const index = cont.listeners.indexOf(listener);
6458
6459  // removes this instance's listeners and closes the underlying fs_watch
6460  // instance if there are no more listeners left
6461  return () => {
6462    delFromSet(cont, KEY_LISTENERS, listener);
6463    delFromSet(cont, KEY_ERR, errHandler);
6464    delFromSet(cont, KEY_RAW, rawEmitter);
6465    if (isEmptySet(cont.listeners)) {
6466      // Check to protect against issue gh-730.
6467      // if (cont.watcherUnusable) {
6468      cont.watcher.close();
6469      // }
6470      FsWatchInstances.delete(fullPath);
6471      HANDLER_KEYS.forEach(clearItem(cont));
6472      cont.watcher = undefined;
6473      Object.freeze(cont);
6474    }
6475  };
6476};
6477
6478// fs_watchFile helpers
6479
6480// object to hold per-process fs_watchFile instances
6481// (may be shared across chokidar FSWatcher instances)
6482const FsWatchFileInstances = new Map();
6483
6484/**
6485 * Instantiates the fs_watchFile interface or binds listeners
6486 * to an existing one covering the same file system entry
6487 * @param {String} path to be watched
6488 * @param {String} fullPath absolute path
6489 * @param {Object} options options to be passed to fs_watchFile
6490 * @param {Object} handlers container for event listener functions
6491 * @returns {Function} closer
6492 */
6493const setFsWatchFileListener = (path, fullPath, options, handlers) => {
6494  const {listener, rawEmitter} = handlers;
6495  let cont = FsWatchFileInstances.get(fullPath);
6496
6497  const copts = cont && cont.options;
6498  if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
6499    fs$8.unwatchFile(fullPath);
6500    cont = undefined;
6501  }
6502
6503  /* eslint-enable no-unused-vars, prefer-destructuring */
6504
6505  if (cont) {
6506    addAndConvert(cont, KEY_LISTENERS, listener);
6507    addAndConvert(cont, KEY_RAW, rawEmitter);
6508  } else {
6509    // TODO
6510    // listeners.add(listener);
6511    // rawEmitters.add(rawEmitter);
6512    cont = {
6513      listeners: listener,
6514      rawEmitters: rawEmitter,
6515      options,
6516      watcher: fs$8.watchFile(fullPath, options, (curr, prev) => {
6517        foreach(cont.rawEmitters, (rawEmitter) => {
6518          rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
6519        });
6520        const currmtime = curr.mtimeMs;
6521        if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
6522          foreach(cont.listeners, (listener) => listener(path, curr));
6523        }
6524      })
6525    };
6526    FsWatchFileInstances.set(fullPath, cont);
6527  }
6528  // const index = cont.listeners.indexOf(listener);
6529
6530  // Removes this instance's listeners and closes the underlying fs_watchFile
6531  // instance if there are no more listeners left.
6532  return () => {
6533    delFromSet(cont, KEY_LISTENERS, listener);
6534    delFromSet(cont, KEY_RAW, rawEmitter);
6535    if (isEmptySet(cont.listeners)) {
6536      FsWatchFileInstances.delete(fullPath);
6537      fs$8.unwatchFile(fullPath);
6538      cont.options = cont.watcher = undefined;
6539      Object.freeze(cont);
6540    }
6541  };
6542};
6543
6544/**
6545 * @mixin
6546 */
6547class NodeFsHandler$1 {
6548
6549/**
6550 * @param {import("../index").FSWatcher} fsW
6551 */
6552constructor(fsW) {
6553  this.fsw = fsW;
6554  this._boundHandleError = (error) => fsW._handleError(error);
6555}
6556
6557/**
6558 * Watch file for changes with fs_watchFile or fs_watch.
6559 * @param {String} path to file or dir
6560 * @param {Function} listener on fs change
6561 * @returns {Function} closer for the watcher instance
6562 */
6563_watchWithNodeFs(path, listener) {
6564  const opts = this.fsw.options;
6565  const directory = sysPath$2.dirname(path);
6566  const basename = sysPath$2.basename(path);
6567  const parent = this.fsw._getWatchedDir(directory);
6568  parent.add(basename);
6569  const absolutePath = sysPath$2.resolve(path);
6570  const options = {persistent: opts.persistent};
6571  if (!listener) listener = EMPTY_FN$2;
6572
6573  let closer;
6574  if (opts.usePolling) {
6575    options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
6576      opts.binaryInterval : opts.interval;
6577    closer = setFsWatchFileListener(path, absolutePath, options, {
6578      listener,
6579      rawEmitter: this.fsw._emitRaw
6580    });
6581  } else {
6582    closer = setFsWatchListener(path, absolutePath, options, {
6583      listener,
6584      errHandler: this._boundHandleError,
6585      rawEmitter: this.fsw._emitRaw
6586    });
6587  }
6588  return closer;
6589}
6590
6591/**
6592 * Watch a file and emit add event if warranted.
6593 * @param {Path} file Path
6594 * @param {fs.Stats} stats result of fs_stat
6595 * @param {Boolean} initialAdd was the file added at watch instantiation?
6596 * @returns {Function} closer for the watcher instance
6597 */
6598_handleFile(file, stats, initialAdd) {
6599  if (this.fsw.closed) {
6600    return;
6601  }
6602  const dirname = sysPath$2.dirname(file);
6603  const basename = sysPath$2.basename(file);
6604  const parent = this.fsw._getWatchedDir(dirname);
6605  // stats is always present
6606  let prevStats = stats;
6607
6608  // if the file is already being watched, do nothing
6609  if (parent.has(basename)) return;
6610
6611  const listener = async (path, newStats) => {
6612    if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
6613    if (!newStats || newStats.mtimeMs === 0) {
6614      try {
6615        const newStats = await stat$2(file);
6616        if (this.fsw.closed) return;
6617        // Check that change event was not fired because of changed only accessTime.
6618        const at = newStats.atimeMs;
6619        const mt = newStats.mtimeMs;
6620        if (!at || at <= mt || mt !== prevStats.mtimeMs) {
6621          this.fsw._emit(EV_CHANGE$2, file, newStats);
6622        }
6623        if (isLinux && prevStats.ino !== newStats.ino) {
6624          this.fsw._closeFile(path);
6625          prevStats = newStats;
6626          this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
6627        } else {
6628          prevStats = newStats;
6629        }
6630      } catch (error) {
6631        // Fix issues where mtime is null but file is still present
6632        this.fsw._remove(dirname, basename);
6633      }
6634      // add is about to be emitted if file not already tracked in parent
6635    } else if (parent.has(basename)) {
6636      // Check that change event was not fired because of changed only accessTime.
6637      const at = newStats.atimeMs;
6638      const mt = newStats.mtimeMs;
6639      if (!at || at <= mt || mt !== prevStats.mtimeMs) {
6640        this.fsw._emit(EV_CHANGE$2, file, newStats);
6641      }
6642      prevStats = newStats;
6643    }
6644  };
6645  // kick off the watcher
6646  const closer = this._watchWithNodeFs(file, listener);
6647
6648  // emit an add event if we're supposed to
6649  if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
6650    if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
6651    this.fsw._emit(EV_ADD$2, file, stats);
6652  }
6653
6654  return closer;
6655}
6656
6657/**
6658 * Handle symlinks encountered while reading a dir.
6659 * @param {Object} entry returned by readdirp
6660 * @param {String} directory path of dir being read
6661 * @param {String} path of this item
6662 * @param {String} item basename of this item
6663 * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
6664 */
6665async _handleSymlink(entry, directory, path, item) {
6666  if (this.fsw.closed) {
6667    return;
6668  }
6669  const full = entry.fullPath;
6670  const dir = this.fsw._getWatchedDir(directory);
6671
6672  if (!this.fsw.options.followSymlinks) {
6673    // watch symlink directly (don't follow) and detect changes
6674    this.fsw._incrReadyCount();
6675    const linkPath = await fsrealpath(path);
6676    if (this.fsw.closed) return;
6677    if (dir.has(item)) {
6678      if (this.fsw._symlinkPaths.get(full) !== linkPath) {
6679        this.fsw._symlinkPaths.set(full, linkPath);
6680        this.fsw._emit(EV_CHANGE$2, path, entry.stats);
6681      }
6682    } else {
6683      dir.add(item);
6684      this.fsw._symlinkPaths.set(full, linkPath);
6685      this.fsw._emit(EV_ADD$2, path, entry.stats);
6686    }
6687    this.fsw._emitReady();
6688    return true;
6689  }
6690
6691  // don't follow the same symlink more than once
6692  if (this.fsw._symlinkPaths.has(full)) {
6693    return true;
6694  }
6695
6696  this.fsw._symlinkPaths.set(full, true);
6697}
6698
6699_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
6700  // Normalize the directory name on Windows
6701  directory = sysPath$2.join(directory, EMPTY_STR$1);
6702
6703  if (!wh.hasGlob) {
6704    throttler = this.fsw._throttle('readdir', directory, 1000);
6705    if (!throttler) return;
6706  }
6707
6708  const previous = this.fsw._getWatchedDir(wh.path);
6709  const current = new Set();
6710
6711  let stream = this.fsw._readdirp(directory, {
6712    fileFilter: entry => wh.filterPath(entry),
6713    directoryFilter: entry => wh.filterDir(entry),
6714    depth: 0
6715  }).on(STR_DATA$1, async (entry) => {
6716    if (this.fsw.closed) {
6717      stream = undefined;
6718      return;
6719    }
6720    const item = entry.path;
6721    let path = sysPath$2.join(directory, item);
6722    current.add(item);
6723
6724    if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
6725      return;
6726    }
6727
6728    if (this.fsw.closed) {
6729      stream = undefined;
6730      return;
6731    }
6732    // Files that present in current directory snapshot
6733    // but absent in previous are added to watch list and
6734    // emit `add` event.
6735    if (item === target || !target && !previous.has(item)) {
6736      this.fsw._incrReadyCount();
6737
6738      // ensure relativeness of path is preserved in case of watcher reuse
6739      path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
6740
6741      this._addToNodeFs(path, initialAdd, wh, depth + 1);
6742    }
6743  }).on(EV_ERROR$2, this._boundHandleError);
6744
6745  return new Promise(resolve =>
6746    stream.once(STR_END$2, () => {
6747      if (this.fsw.closed) {
6748        stream = undefined;
6749        return;
6750      }
6751      const wasThrottled = throttler ? throttler.clear() : false;
6752
6753      resolve();
6754
6755      // Files that absent in current directory snapshot
6756      // but present in previous emit `remove` event
6757      // and are removed from @watched[directory].
6758      previous.getChildren().filter((item) => {
6759        return item !== directory &&
6760          !current.has(item) &&
6761          // in case of intersecting globs;
6762          // a path may have been filtered out of this readdir, but
6763          // shouldn't be removed because it matches a different glob
6764          (!wh.hasGlob || wh.filterPath({
6765            fullPath: sysPath$2.resolve(directory, item)
6766          }));
6767      }).forEach((item) => {
6768        this.fsw._remove(directory, item);
6769      });
6770
6771      stream = undefined;
6772
6773      // one more time for any missed in case changes came in extremely quickly
6774      if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
6775    })
6776  );
6777}
6778
6779/**
6780 * Read directory to add / remove files from `@watched` list and re-read it on change.
6781 * @param {String} dir fs path
6782 * @param {fs.Stats} stats
6783 * @param {Boolean} initialAdd
6784 * @param {Number} depth relative to user-supplied path
6785 * @param {String} target child path targeted for watch
6786 * @param {Object} wh Common watch helpers for this path
6787 * @param {String} realpath
6788 * @returns {Promise<Function>} closer for the watcher instance.
6789 */
6790async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
6791  const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
6792  const tracked = parentDir.has(sysPath$2.basename(dir));
6793  if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
6794    if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
6795  }
6796
6797  // ensure dir is tracked (harmless if redundant)
6798  parentDir.add(sysPath$2.basename(dir));
6799  this.fsw._getWatchedDir(dir);
6800  let throttler;
6801  let closer;
6802
6803  const oDepth = this.fsw.options.depth;
6804  if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
6805    if (!target) {
6806      await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
6807      if (this.fsw.closed) return;
6808    }
6809
6810    closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
6811      // if current directory is removed, do nothing
6812      if (stats && stats.mtimeMs === 0) return;
6813
6814      this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
6815    });
6816  }
6817  return closer;
6818}
6819
6820/**
6821 * Handle added file, directory, or glob pattern.
6822 * Delegates call to _handleFile / _handleDir after checks.
6823 * @param {String} path to file or ir
6824 * @param {Boolean} initialAdd was the file added at watch instantiation?
6825 * @param {Object} priorWh depth relative to user-supplied path
6826 * @param {Number} depth Child path actually targeted for watch
6827 * @param {String=} target Child path actually targeted for watch
6828 * @returns {Promise}
6829 */
6830async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
6831  const ready = this.fsw._emitReady;
6832  if (this.fsw._isIgnored(path) || this.fsw.closed) {
6833    ready();
6834    return false;
6835  }
6836
6837  const wh = this.fsw._getWatchHelpers(path, depth);
6838  if (!wh.hasGlob && priorWh) {
6839    wh.hasGlob = priorWh.hasGlob;
6840    wh.globFilter = priorWh.globFilter;
6841    wh.filterPath = entry => priorWh.filterPath(entry);
6842    wh.filterDir = entry => priorWh.filterDir(entry);
6843  }
6844
6845  // evaluate what is at the path we're being asked to watch
6846  try {
6847    const stats = await statMethods$1[wh.statMethod](wh.watchPath);
6848    if (this.fsw.closed) return;
6849    if (this.fsw._isIgnored(wh.watchPath, stats)) {
6850      ready();
6851      return false;
6852    }
6853
6854    const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
6855    let closer;
6856    if (stats.isDirectory()) {
6857      const absPath = sysPath$2.resolve(path);
6858      const targetPath = follow ? await fsrealpath(path) : path;
6859      if (this.fsw.closed) return;
6860      closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
6861      if (this.fsw.closed) return;
6862      // preserve this symlink's target path
6863      if (absPath !== targetPath && targetPath !== undefined) {
6864        this.fsw._symlinkPaths.set(absPath, targetPath);
6865      }
6866    } else if (stats.isSymbolicLink()) {
6867      const targetPath = follow ? await fsrealpath(path) : path;
6868      if (this.fsw.closed) return;
6869      const parent = sysPath$2.dirname(wh.watchPath);
6870      this.fsw._getWatchedDir(parent).add(wh.watchPath);
6871      this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
6872      closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
6873      if (this.fsw.closed) return;
6874
6875      // preserve this symlink's target path
6876      if (targetPath !== undefined) {
6877        this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
6878      }
6879    } else {
6880      closer = this._handleFile(wh.watchPath, stats, initialAdd);
6881    }
6882    ready();
6883
6884    this.fsw._addPathCloser(path, closer);
6885    return false;
6886
6887  } catch (error) {
6888    if (this.fsw._handleError(error)) {
6889      ready();
6890      return path;
6891    }
6892  }
6893}
6894
6895}
6896
6897var nodefsHandler = NodeFsHandler$1;
6898
6899var fseventsHandler = {exports: {}};
6900
6901const fs$7 = require$$0$3;
6902const sysPath$1 = path$b;
6903const { promisify: promisify$1 } = require$$0$4;
6904
6905let fsevents;
6906try {
6907  fsevents = undefined;
6908} catch (error) {
6909  if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
6910}
6911
6912if (fsevents) {
6913  // TODO: real check
6914  const mtch = process.version.match(/v(\d+)\.(\d+)/);
6915  if (mtch && mtch[1] && mtch[2]) {
6916    const maj = Number.parseInt(mtch[1], 10);
6917    const min = Number.parseInt(mtch[2], 10);
6918    if (maj === 8 && min < 16) {
6919      fsevents = undefined;
6920    }
6921  }
6922}
6923
6924const {
6925  EV_ADD: EV_ADD$1,
6926  EV_CHANGE: EV_CHANGE$1,
6927  EV_ADD_DIR: EV_ADD_DIR$1,
6928  EV_UNLINK: EV_UNLINK$1,
6929  EV_ERROR: EV_ERROR$1,
6930  STR_DATA,
6931  STR_END: STR_END$1,
6932  FSEVENT_CREATED,
6933  FSEVENT_MODIFIED,
6934  FSEVENT_DELETED,
6935  FSEVENT_MOVED,
6936  // FSEVENT_CLONED,
6937  FSEVENT_UNKNOWN,
6938  FSEVENT_TYPE_FILE,
6939  FSEVENT_TYPE_DIRECTORY,
6940  FSEVENT_TYPE_SYMLINK,
6941
6942  ROOT_GLOBSTAR,
6943  DIR_SUFFIX,
6944  DOT_SLASH,
6945  FUNCTION_TYPE: FUNCTION_TYPE$1,
6946  EMPTY_FN: EMPTY_FN$1,
6947  IDENTITY_FN
6948} = constants$1;
6949
6950const Depth = (value) => isNaN(value) ? {} : {depth: value};
6951
6952const stat$1 = promisify$1(fs$7.stat);
6953const lstat = promisify$1(fs$7.lstat);
6954const realpath$1 = promisify$1(fs$7.realpath);
6955
6956const statMethods = { stat: stat$1, lstat };
6957
6958/**
6959 * @typedef {String} Path
6960 */
6961
6962/**
6963 * @typedef {Object} FsEventsWatchContainer
6964 * @property {Set<Function>} listeners
6965 * @property {Function} rawEmitter
6966 * @property {{stop: Function}} watcher
6967 */
6968
6969// fsevents instance helper functions
6970/**
6971 * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
6972 * @type {Map<Path,FsEventsWatchContainer>}
6973 */
6974const FSEventsWatchers = new Map();
6975
6976// Threshold of duplicate path prefixes at which to start
6977// consolidating going forward
6978const consolidateThreshhold = 10;
6979
6980const wrongEventFlags = new Set([
6981  69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
6982]);
6983
6984/**
6985 * Instantiates the fsevents interface
6986 * @param {Path} path path to be watched
6987 * @param {Function} callback called when fsevents is bound and ready
6988 * @returns {{stop: Function}} new fsevents instance
6989 */
6990const createFSEventsInstance = (path, callback) => {
6991  const stop = fsevents.watch(path, callback);
6992  return {stop};
6993};
6994
6995/**
6996 * Instantiates the fsevents interface or binds listeners to an existing one covering
6997 * the same file tree.
6998 * @param {Path} path           - to be watched
6999 * @param {Path} realPath       - real path for symlinks
7000 * @param {Function} listener   - called when fsevents emits events
7001 * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
7002 * @returns {Function} closer
7003 */
7004function setFSEventsListener(path, realPath, listener, rawEmitter) {
7005  let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
7006
7007  const parentPath = sysPath$1.dirname(watchPath);
7008  let cont = FSEventsWatchers.get(watchPath);
7009
7010  // If we've accumulated a substantial number of paths that
7011  // could have been consolidated by watching one directory
7012  // above the current one, create a watcher on the parent
7013  // path instead, so that we do consolidate going forward.
7014  if (couldConsolidate(parentPath)) {
7015    watchPath = parentPath;
7016  }
7017
7018  const resolvedPath = sysPath$1.resolve(path);
7019  const hasSymlink = resolvedPath !== realPath;
7020
7021  const filteredListener = (fullPath, flags, info) => {
7022    if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
7023    if (
7024      fullPath === resolvedPath ||
7025      !fullPath.indexOf(resolvedPath + sysPath$1.sep)
7026    ) listener(fullPath, flags, info);
7027  };
7028
7029  // check if there is already a watcher on a parent path
7030  // modifies `watchPath` to the parent path when it finds a match
7031  let watchedParent = false;
7032  for (const watchedPath of FSEventsWatchers.keys()) {
7033    if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
7034      watchPath = watchedPath;
7035      cont = FSEventsWatchers.get(watchPath);
7036      watchedParent = true;
7037      break;
7038    }
7039  }
7040
7041  if (cont || watchedParent) {
7042    cont.listeners.add(filteredListener);
7043  } else {
7044    cont = {
7045      listeners: new Set([filteredListener]),
7046      rawEmitter,
7047      watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
7048        if (!cont.listeners.size) return;
7049        const info = fsevents.getInfo(fullPath, flags);
7050        cont.listeners.forEach(list => {
7051          list(fullPath, flags, info);
7052        });
7053
7054        cont.rawEmitter(info.event, fullPath, info);
7055      })
7056    };
7057    FSEventsWatchers.set(watchPath, cont);
7058  }
7059
7060  // removes this instance's listeners and closes the underlying fsevents
7061  // instance if there are no more listeners left
7062  return () => {
7063    const lst = cont.listeners;
7064
7065    lst.delete(filteredListener);
7066    if (!lst.size) {
7067      FSEventsWatchers.delete(watchPath);
7068      if (cont.watcher) return cont.watcher.stop().then(() => {
7069        cont.rawEmitter = cont.watcher = undefined;
7070        Object.freeze(cont);
7071      });
7072    }
7073  };
7074}
7075
7076// Decide whether or not we should start a new higher-level
7077// parent watcher
7078const couldConsolidate = (path) => {
7079  let count = 0;
7080  for (const watchPath of FSEventsWatchers.keys()) {
7081    if (watchPath.indexOf(path) === 0) {
7082      count++;
7083      if (count >= consolidateThreshhold) {
7084        return true;
7085      }
7086    }
7087  }
7088
7089  return false;
7090};
7091
7092// returns boolean indicating whether fsevents can be used
7093const canUse = () => fsevents && FSEventsWatchers.size < 128;
7094
7095// determines subdirectory traversal levels from root to path
7096const calcDepth = (path, root) => {
7097  let i = 0;
7098  while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
7099  return i;
7100};
7101
7102// returns boolean indicating whether the fsevents' event info has the same type
7103// as the one returned by fs.stat
7104const sameTypes = (info, stats) => (
7105  info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
7106  info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
7107  info.type === FSEVENT_TYPE_FILE && stats.isFile()
7108);
7109
7110/**
7111 * @mixin
7112 */
7113class FsEventsHandler$1 {
7114
7115/**
7116 * @param {import('../index').FSWatcher} fsw
7117 */
7118constructor(fsw) {
7119  this.fsw = fsw;
7120}
7121checkIgnored(path, stats) {
7122  const ipaths = this.fsw._ignoredPaths;
7123  if (this.fsw._isIgnored(path, stats)) {
7124    ipaths.add(path);
7125    if (stats && stats.isDirectory()) {
7126      ipaths.add(path + ROOT_GLOBSTAR);
7127    }
7128    return true;
7129  }
7130
7131  ipaths.delete(path);
7132  ipaths.delete(path + ROOT_GLOBSTAR);
7133}
7134
7135addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
7136  const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
7137  this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
7138}
7139
7140async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
7141  try {
7142    const stats = await stat$1(path);
7143    if (this.fsw.closed) return;
7144    if (sameTypes(info, stats)) {
7145      this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7146    } else {
7147      this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
7148    }
7149  } catch (error) {
7150    if (error.code === 'EACCES') {
7151      this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7152    } else {
7153      this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
7154    }
7155  }
7156}
7157
7158handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
7159  if (this.fsw.closed || this.checkIgnored(path)) return;
7160
7161  if (event === EV_UNLINK$1) {
7162    const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
7163    // suppress unlink events on never before seen files
7164    if (isDirectory || watchedDir.has(item)) {
7165      this.fsw._remove(parent, item, isDirectory);
7166    }
7167  } else {
7168    if (event === EV_ADD$1) {
7169      // track new directories
7170      if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
7171
7172      if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
7173        // push symlinks back to the top of the stack to get handled
7174        const curDepth = opts.depth === undefined ?
7175          undefined : calcDepth(fullPath, realPath) + 1;
7176        return this._addToFsEvents(path, false, true, curDepth);
7177      }
7178
7179      // track new paths
7180      // (other than symlinks being followed, which will be tracked soon)
7181      this.fsw._getWatchedDir(parent).add(item);
7182    }
7183    /**
7184     * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
7185     */
7186    const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
7187    this.fsw._emit(eventName, path);
7188    if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
7189  }
7190}
7191
7192/**
7193 * Handle symlinks encountered during directory scan
7194 * @param {String} watchPath  - file/dir path to be watched with fsevents
7195 * @param {String} realPath   - real path (in case of symlinks)
7196 * @param {Function} transform  - path transformer
7197 * @param {Function} globFilter - path filter in case a glob pattern was provided
7198 * @returns {Function} closer for the watcher instance
7199*/
7200_watchWithFsEvents(watchPath, realPath, transform, globFilter) {
7201  if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
7202  const opts = this.fsw.options;
7203  const watchCallback = async (fullPath, flags, info) => {
7204    if (this.fsw.closed) return;
7205    if (
7206      opts.depth !== undefined &&
7207      calcDepth(fullPath, realPath) > opts.depth
7208    ) return;
7209    const path = transform(sysPath$1.join(
7210      watchPath, sysPath$1.relative(watchPath, fullPath)
7211    ));
7212    if (globFilter && !globFilter(path)) return;
7213    // ensure directories are tracked
7214    const parent = sysPath$1.dirname(path);
7215    const item = sysPath$1.basename(path);
7216    const watchedDir = this.fsw._getWatchedDir(
7217      info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
7218    );
7219
7220    // correct for wrong events emitted
7221    if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
7222      if (typeof opts.ignored === FUNCTION_TYPE$1) {
7223        let stats;
7224        try {
7225          stats = await stat$1(path);
7226        } catch (error) {}
7227        if (this.fsw.closed) return;
7228        if (this.checkIgnored(path, stats)) return;
7229        if (sameTypes(info, stats)) {
7230          this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7231        } else {
7232          this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
7233        }
7234      } else {
7235        this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7236      }
7237    } else {
7238      switch (info.event) {
7239      case FSEVENT_CREATED:
7240      case FSEVENT_MODIFIED:
7241        return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7242      case FSEVENT_DELETED:
7243      case FSEVENT_MOVED:
7244        return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
7245      }
7246    }
7247  };
7248
7249  const closer = setFSEventsListener(
7250    watchPath,
7251    realPath,
7252    watchCallback,
7253    this.fsw._emitRaw
7254  );
7255
7256  this.fsw._emitReady();
7257  return closer;
7258}
7259
7260/**
7261 * Handle symlinks encountered during directory scan
7262 * @param {String} linkPath path to symlink
7263 * @param {String} fullPath absolute path to the symlink
7264 * @param {Function} transform pre-existing path transformer
7265 * @param {Number} curDepth level of subdirectories traversed to where symlink is
7266 * @returns {Promise<void>}
7267 */
7268async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
7269  // don't follow the same symlink more than once
7270  if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
7271
7272  this.fsw._symlinkPaths.set(fullPath, true);
7273  this.fsw._incrReadyCount();
7274
7275  try {
7276    const linkTarget = await realpath$1(linkPath);
7277    if (this.fsw.closed) return;
7278    if (this.fsw._isIgnored(linkTarget)) {
7279      return this.fsw._emitReady();
7280    }
7281
7282    this.fsw._incrReadyCount();
7283
7284    // add the linkTarget for watching with a wrapper for transform
7285    // that causes emitted paths to incorporate the link's path
7286    this._addToFsEvents(linkTarget || linkPath, (path) => {
7287      let aliasedPath = linkPath;
7288      if (linkTarget && linkTarget !== DOT_SLASH) {
7289        aliasedPath = path.replace(linkTarget, linkPath);
7290      } else if (path !== DOT_SLASH) {
7291        aliasedPath = sysPath$1.join(linkPath, path);
7292      }
7293      return transform(aliasedPath);
7294    }, false, curDepth);
7295  } catch(error) {
7296    if (this.fsw._handleError(error)) {
7297      return this.fsw._emitReady();
7298    }
7299  }
7300}
7301
7302/**
7303 *
7304 * @param {Path} newPath
7305 * @param {fs.Stats} stats
7306 */
7307emitAdd(newPath, stats, processPath, opts, forceAdd) {
7308  const pp = processPath(newPath);
7309  const isDir = stats.isDirectory();
7310  const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
7311  const base = sysPath$1.basename(pp);
7312
7313  // ensure empty dirs get tracked
7314  if (isDir) this.fsw._getWatchedDir(pp);
7315  if (dirObj.has(base)) return;
7316  dirObj.add(base);
7317
7318  if (!opts.ignoreInitial || forceAdd === true) {
7319    this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
7320  }
7321}
7322
7323initWatch(realPath, path, wh, processPath) {
7324  if (this.fsw.closed) return;
7325  const closer = this._watchWithFsEvents(
7326    wh.watchPath,
7327    sysPath$1.resolve(realPath || wh.watchPath),
7328    processPath,
7329    wh.globFilter
7330  );
7331  this.fsw._addPathCloser(path, closer);
7332}
7333
7334/**
7335 * Handle added path with fsevents
7336 * @param {String} path file/dir path or glob pattern
7337 * @param {Function|Boolean=} transform converts working path to what the user expects
7338 * @param {Boolean=} forceAdd ensure add is emitted
7339 * @param {Number=} priorDepth Level of subdirectories already traversed.
7340 * @returns {Promise<void>}
7341 */
7342async _addToFsEvents(path, transform, forceAdd, priorDepth) {
7343  if (this.fsw.closed) {
7344    return;
7345  }
7346  const opts = this.fsw.options;
7347  const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
7348
7349  const wh = this.fsw._getWatchHelpers(path);
7350
7351  // evaluate what is at the path we're being asked to watch
7352  try {
7353    const stats = await statMethods[wh.statMethod](wh.watchPath);
7354    if (this.fsw.closed) return;
7355    if (this.fsw._isIgnored(wh.watchPath, stats)) {
7356      throw null;
7357    }
7358    if (stats.isDirectory()) {
7359      // emit addDir unless this is a glob parent
7360      if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
7361
7362      // don't recurse further if it would exceed depth setting
7363      if (priorDepth && priorDepth > opts.depth) return;
7364
7365      // scan the contents of the dir
7366      this.fsw._readdirp(wh.watchPath, {
7367        fileFilter: entry => wh.filterPath(entry),
7368        directoryFilter: entry => wh.filterDir(entry),
7369        ...Depth(opts.depth - (priorDepth || 0))
7370      }).on(STR_DATA, (entry) => {
7371        // need to check filterPath on dirs b/c filterDir is less restrictive
7372        if (this.fsw.closed) {
7373          return;
7374        }
7375        if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
7376
7377        const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
7378        const {fullPath} = entry;
7379
7380        if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
7381          // preserve the current depth here since it can't be derived from
7382          // real paths past the symlink
7383          const curDepth = opts.depth === undefined ?
7384            undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
7385
7386          this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
7387        } else {
7388          this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
7389        }
7390      }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
7391        this.fsw._emitReady();
7392      });
7393    } else {
7394      this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
7395      this.fsw._emitReady();
7396    }
7397  } catch (error) {
7398    if (!error || this.fsw._handleError(error)) {
7399      // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
7400      this.fsw._emitReady();
7401      this.fsw._emitReady();
7402    }
7403  }
7404
7405  if (opts.persistent && forceAdd !== true) {
7406    if (typeof transform === FUNCTION_TYPE$1) {
7407      // realpath has already been resolved
7408      this.initWatch(undefined, path, wh, processPath);
7409    } else {
7410      let realPath;
7411      try {
7412        realPath = await realpath$1(wh.watchPath);
7413      } catch (e) {}
7414      this.initWatch(realPath, path, wh, processPath);
7415    }
7416  }
7417}
7418
7419}
7420
7421fseventsHandler.exports = FsEventsHandler$1;
7422fseventsHandler.exports.canUse = canUse;
7423
7424const { EventEmitter } = require$$0$5;
7425const fs$6 = require$$0$3;
7426const sysPath = path$b;
7427const { promisify } = require$$0$4;
7428const readdirp = readdirp_1;
7429const anymatch = anymatch$2.exports.default;
7430const globParent = globParent$1;
7431const isGlob = isGlob$2;
7432const braces = braces_1;
7433const normalizePath = normalizePath$2;
7434
7435const NodeFsHandler = nodefsHandler;
7436const FsEventsHandler = fseventsHandler.exports;
7437const {
7438  EV_ALL,
7439  EV_READY,
7440  EV_ADD,
7441  EV_CHANGE,
7442  EV_UNLINK,
7443  EV_ADD_DIR,
7444  EV_UNLINK_DIR,
7445  EV_RAW,
7446  EV_ERROR,
7447
7448  STR_CLOSE,
7449  STR_END,
7450
7451  BACK_SLASH_RE,
7452  DOUBLE_SLASH_RE,
7453  SLASH_OR_BACK_SLASH_RE,
7454  DOT_RE,
7455  REPLACER_RE,
7456
7457  SLASH: SLASH$1,
7458  SLASH_SLASH,
7459  BRACE_START,
7460  BANG,
7461  ONE_DOT,
7462  TWO_DOTS,
7463  GLOBSTAR: GLOBSTAR$1,
7464  SLASH_GLOBSTAR,
7465  ANYMATCH_OPTS,
7466  STRING_TYPE,
7467  FUNCTION_TYPE,
7468  EMPTY_STR,
7469  EMPTY_FN,
7470
7471  isWindows: isWindows$2,
7472  isMacos,
7473  isIBMi
7474} = constants$1;
7475
7476const stat = promisify(fs$6.stat);
7477const readdir = promisify(fs$6.readdir);
7478
7479/**
7480 * @typedef {String} Path
7481 * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
7482 * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
7483 */
7484
7485/**
7486 *
7487 * @typedef {Object} WatchHelpers
7488 * @property {Boolean} followSymlinks
7489 * @property {'stat'|'lstat'} statMethod
7490 * @property {Path} path
7491 * @property {Path} watchPath
7492 * @property {Function} entryPath
7493 * @property {Boolean} hasGlob
7494 * @property {Object} globFilter
7495 * @property {Function} filterPath
7496 * @property {Function} filterDir
7497 */
7498
7499const arrify = (value = []) => Array.isArray(value) ? value : [value];
7500const flatten$1 = (list, result = []) => {
7501  list.forEach(item => {
7502    if (Array.isArray(item)) {
7503      flatten$1(item, result);
7504    } else {
7505      result.push(item);
7506    }
7507  });
7508  return result;
7509};
7510
7511const unifyPaths = (paths_) => {
7512  /**
7513   * @type {Array<String>}
7514   */
7515  const paths = flatten$1(arrify(paths_));
7516  if (!paths.every(p => typeof p === STRING_TYPE)) {
7517    throw new TypeError(`Non-string provided as watch path: ${paths}`);
7518  }
7519  return paths.map(normalizePathToUnix);
7520};
7521
7522// If SLASH_SLASH occurs at the beginning of path, it is not replaced
7523//     because "//StoragePC/DrivePool/Movies" is a valid network path
7524const toUnix = (string) => {
7525  let str = string.replace(BACK_SLASH_RE, SLASH$1);
7526  let prepend = false;
7527  if (str.startsWith(SLASH_SLASH)) {
7528    prepend = true;
7529  }
7530  while (str.match(DOUBLE_SLASH_RE)) {
7531    str = str.replace(DOUBLE_SLASH_RE, SLASH$1);
7532  }
7533  if (prepend) {
7534    str = SLASH$1 + str;
7535  }
7536  return str;
7537};
7538
7539// Our version of upath.normalize
7540// TODO: this is not equal to path-normalize module - investigate why
7541const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
7542
7543const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
7544  if (typeof path !== STRING_TYPE) return path;
7545  return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
7546};
7547
7548const getAbsolutePath = (path, cwd) => {
7549  if (sysPath.isAbsolute(path)) {
7550    return path;
7551  }
7552  if (path.startsWith(BANG)) {
7553    return BANG + sysPath.join(cwd, path.slice(1));
7554  }
7555  return sysPath.join(cwd, path);
7556};
7557
7558const undef = (opts, key) => opts[key] === undefined;
7559
7560/**
7561 * Directory entry.
7562 * @property {Path} path
7563 * @property {Set<Path>} items
7564 */
7565class DirEntry {
7566  /**
7567   * @param {Path} dir
7568   * @param {Function} removeWatcher
7569   */
7570  constructor(dir, removeWatcher) {
7571    this.path = dir;
7572    this._removeWatcher = removeWatcher;
7573    /** @type {Set<Path>} */
7574    this.items = new Set();
7575  }
7576
7577  add(item) {
7578    const {items} = this;
7579    if (!items) return;
7580    if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
7581  }
7582
7583  async remove(item) {
7584    const {items} = this;
7585    if (!items) return;
7586    items.delete(item);
7587    if (items.size > 0) return;
7588
7589    const dir = this.path;
7590    try {
7591      await readdir(dir);
7592    } catch (err) {
7593      if (this._removeWatcher) {
7594        this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
7595      }
7596    }
7597  }
7598
7599  has(item) {
7600    const {items} = this;
7601    if (!items) return;
7602    return items.has(item);
7603  }
7604
7605  /**
7606   * @returns {Array<String>}
7607   */
7608  getChildren() {
7609    const {items} = this;
7610    if (!items) return;
7611    return [...items.values()];
7612  }
7613
7614  dispose() {
7615    this.items.clear();
7616    delete this.path;
7617    delete this._removeWatcher;
7618    delete this.items;
7619    Object.freeze(this);
7620  }
7621}
7622
7623const STAT_METHOD_F = 'stat';
7624const STAT_METHOD_L = 'lstat';
7625class WatchHelper {
7626  constructor(path, watchPath, follow, fsw) {
7627    this.fsw = fsw;
7628    this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
7629    this.watchPath = watchPath;
7630    this.fullWatchPath = sysPath.resolve(watchPath);
7631    this.hasGlob = watchPath !== path;
7632    /** @type {object|boolean} */
7633    if (path === EMPTY_STR) this.hasGlob = false;
7634    this.globSymlink = this.hasGlob && follow ? undefined : false;
7635    this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
7636    this.dirParts = this.getDirParts(path);
7637    this.dirParts.forEach((parts) => {
7638      if (parts.length > 1) parts.pop();
7639    });
7640    this.followSymlinks = follow;
7641    this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
7642  }
7643
7644  checkGlobSymlink(entry) {
7645    // only need to resolve once
7646    // first entry should always have entry.parentDir === EMPTY_STR
7647    if (this.globSymlink === undefined) {
7648      this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
7649        false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
7650    }
7651
7652    if (this.globSymlink) {
7653      return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
7654    }
7655
7656    return entry.fullPath;
7657  }
7658
7659  entryPath(entry) {
7660    return sysPath.join(this.watchPath,
7661      sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
7662    );
7663  }
7664
7665  filterPath(entry) {
7666    const {stats} = entry;
7667    if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
7668    const resolvedPath = this.entryPath(entry);
7669    const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
7670      this.globFilter(resolvedPath) : true;
7671    return matchesGlob &&
7672      this.fsw._isntIgnored(resolvedPath, stats) &&
7673      this.fsw._hasReadPermissions(stats);
7674  }
7675
7676  getDirParts(path) {
7677    if (!this.hasGlob) return [];
7678    const parts = [];
7679    const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
7680    expandedPath.forEach((path) => {
7681      parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
7682    });
7683    return parts;
7684  }
7685
7686  filterDir(entry) {
7687    if (this.hasGlob) {
7688      const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
7689      let globstar = false;
7690      this.unmatchedGlob = !this.dirParts.some((parts) => {
7691        return parts.every((part, i) => {
7692          if (part === GLOBSTAR$1) globstar = true;
7693          return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
7694        });
7695      });
7696    }
7697    return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
7698  }
7699}
7700
7701/**
7702 * Watches files & directories for changes. Emitted events:
7703 * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
7704 *
7705 *     new FSWatcher()
7706 *       .add(directories)
7707 *       .on('add', path => log('File', path, 'was added'))
7708 */
7709class FSWatcher extends EventEmitter {
7710// Not indenting methods for history sake; for now.
7711constructor(_opts) {
7712  super();
7713
7714  const opts = {};
7715  if (_opts) Object.assign(opts, _opts); // for frozen objects
7716
7717  /** @type {Map<String, DirEntry>} */
7718  this._watched = new Map();
7719  /** @type {Map<String, Array>} */
7720  this._closers = new Map();
7721  /** @type {Set<String>} */
7722  this._ignoredPaths = new Set();
7723
7724  /** @type {Map<ThrottleType, Map>} */
7725  this._throttled = new Map();
7726
7727  /** @type {Map<Path, String|Boolean>} */
7728  this._symlinkPaths = new Map();
7729
7730  this._streams = new Set();
7731  this.closed = false;
7732
7733  // Set up default options.
7734  if (undef(opts, 'persistent')) opts.persistent = true;
7735  if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
7736  if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
7737  if (undef(opts, 'interval')) opts.interval = 100;
7738  if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
7739  if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
7740  opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
7741
7742  // Enable fsevents on OS X when polling isn't explicitly enabled.
7743  if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
7744
7745  // If we can't use fsevents, ensure the options reflect it's disabled.
7746  const canUseFsEvents = FsEventsHandler.canUse();
7747  if (!canUseFsEvents) opts.useFsEvents = false;
7748
7749  // Use polling on Mac if not using fsevents.
7750  // Other platforms use non-polling fs_watch.
7751  if (undef(opts, 'usePolling') && !opts.useFsEvents) {
7752    opts.usePolling = isMacos;
7753  }
7754
7755  // Always default to polling on IBM i because fs.watch() is not available on IBM i.
7756  if(isIBMi) {
7757    opts.usePolling = true;
7758  }
7759
7760  // Global override (useful for end-developers that need to force polling for all
7761  // instances of chokidar, regardless of usage/dependency depth)
7762  const envPoll = process.env.CHOKIDAR_USEPOLLING;
7763  if (envPoll !== undefined) {
7764    const envLower = envPoll.toLowerCase();
7765
7766    if (envLower === 'false' || envLower === '0') {
7767      opts.usePolling = false;
7768    } else if (envLower === 'true' || envLower === '1') {
7769      opts.usePolling = true;
7770    } else {
7771      opts.usePolling = !!envLower;
7772    }
7773  }
7774  const envInterval = process.env.CHOKIDAR_INTERVAL;
7775  if (envInterval) {
7776    opts.interval = Number.parseInt(envInterval, 10);
7777  }
7778
7779  // Editor atomic write normalization enabled by default with fs.watch
7780  if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
7781  if (opts.atomic) this._pendingUnlinks = new Map();
7782
7783  if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
7784
7785  if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
7786  if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
7787  const awf = opts.awaitWriteFinish;
7788  if (awf) {
7789    if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
7790    if (!awf.pollInterval) awf.pollInterval = 100;
7791    this._pendingWrites = new Map();
7792  }
7793  if (opts.ignored) opts.ignored = arrify(opts.ignored);
7794
7795  let readyCalls = 0;
7796  this._emitReady = () => {
7797    readyCalls++;
7798    if (readyCalls >= this._readyCount) {
7799      this._emitReady = EMPTY_FN;
7800      this._readyEmitted = true;
7801      // use process.nextTick to allow time for listener to be bound
7802      process.nextTick(() => this.emit(EV_READY));
7803    }
7804  };
7805  this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
7806  this._readyEmitted = false;
7807  this.options = opts;
7808
7809  // Initialize with proper watcher.
7810  if (opts.useFsEvents) {
7811    this._fsEventsHandler = new FsEventsHandler(this);
7812  } else {
7813    this._nodeFsHandler = new NodeFsHandler(this);
7814  }
7815
7816  // You’re frozen when your heart’s not open.
7817  Object.freeze(opts);
7818}
7819
7820// Public methods
7821
7822/**
7823 * Adds paths to be watched on an existing FSWatcher instance
7824 * @param {Path|Array<Path>} paths_
7825 * @param {String=} _origAdd private; for handling non-existent paths to be watched
7826 * @param {Boolean=} _internal private; indicates a non-user add
7827 * @returns {FSWatcher} for chaining
7828 */
7829add(paths_, _origAdd, _internal) {
7830  const {cwd, disableGlobbing} = this.options;
7831  this.closed = false;
7832  let paths = unifyPaths(paths_);
7833  if (cwd) {
7834    paths = paths.map((path) => {
7835      const absPath = getAbsolutePath(path, cwd);
7836
7837      // Check `path` instead of `absPath` because the cwd portion can't be a glob
7838      if (disableGlobbing || !isGlob(path)) {
7839        return absPath;
7840      }
7841      return normalizePath(absPath);
7842    });
7843  }
7844
7845  // set aside negated glob strings
7846  paths = paths.filter((path) => {
7847    if (path.startsWith(BANG)) {
7848      this._ignoredPaths.add(path.slice(1));
7849      return false;
7850    }
7851
7852    // if a path is being added that was previously ignored, stop ignoring it
7853    this._ignoredPaths.delete(path);
7854    this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
7855
7856    // reset the cached userIgnored anymatch fn
7857    // to make ignoredPaths changes effective
7858    this._userIgnored = undefined;
7859
7860    return true;
7861  });
7862
7863  if (this.options.useFsEvents && this._fsEventsHandler) {
7864    if (!this._readyCount) this._readyCount = paths.length;
7865    if (this.options.persistent) this._readyCount *= 2;
7866    paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
7867  } else {
7868    if (!this._readyCount) this._readyCount = 0;
7869    this._readyCount += paths.length;
7870    Promise.all(
7871      paths.map(async path => {
7872        const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
7873        if (res) this._emitReady();
7874        return res;
7875      })
7876    ).then(results => {
7877      if (this.closed) return;
7878      results.filter(item => item).forEach(item => {
7879        this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
7880      });
7881    });
7882  }
7883
7884  return this;
7885}
7886
7887/**
7888 * Close watchers or start ignoring events from specified paths.
7889 * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
7890 * @returns {FSWatcher} for chaining
7891*/
7892unwatch(paths_) {
7893  if (this.closed) return this;
7894  const paths = unifyPaths(paths_);
7895  const {cwd} = this.options;
7896
7897  paths.forEach((path) => {
7898    // convert to absolute path unless relative path already matches
7899    if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
7900      if (cwd) path = sysPath.join(cwd, path);
7901      path = sysPath.resolve(path);
7902    }
7903
7904    this._closePath(path);
7905
7906    this._ignoredPaths.add(path);
7907    if (this._watched.has(path)) {
7908      this._ignoredPaths.add(path + SLASH_GLOBSTAR);
7909    }
7910
7911    // reset the cached userIgnored anymatch fn
7912    // to make ignoredPaths changes effective
7913    this._userIgnored = undefined;
7914  });
7915
7916  return this;
7917}
7918
7919/**
7920 * Close watchers and remove all listeners from watched paths.
7921 * @returns {Promise<void>}.
7922*/
7923close() {
7924  if (this.closed) return this._closePromise;
7925  this.closed = true;
7926
7927  // Memory management.
7928  this.removeAllListeners();
7929  const closers = [];
7930  this._closers.forEach(closerList => closerList.forEach(closer => {
7931    const promise = closer();
7932    if (promise instanceof Promise) closers.push(promise);
7933  }));
7934  this._streams.forEach(stream => stream.destroy());
7935  this._userIgnored = undefined;
7936  this._readyCount = 0;
7937  this._readyEmitted = false;
7938  this._watched.forEach(dirent => dirent.dispose());
7939  ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
7940    this[`_${key}`].clear();
7941  });
7942
7943  this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
7944  return this._closePromise;
7945}
7946
7947/**
7948 * Expose list of watched paths
7949 * @returns {Object} for chaining
7950*/
7951getWatched() {
7952  const watchList = {};
7953  this._watched.forEach((entry, dir) => {
7954    const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
7955    watchList[key || ONE_DOT] = entry.getChildren().sort();
7956  });
7957  return watchList;
7958}
7959
7960emitWithAll(event, args) {
7961  this.emit(...args);
7962  if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
7963}
7964
7965// Common helpers
7966// --------------
7967
7968/**
7969 * Normalize and emit events.
7970 * Calling _emit DOES NOT MEAN emit() would be called!
7971 * @param {EventName} event Type of event
7972 * @param {Path} path File or directory path
7973 * @param {*=} val1 arguments to be passed with event
7974 * @param {*=} val2
7975 * @param {*=} val3
7976 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
7977 */
7978async _emit(event, path, val1, val2, val3) {
7979  if (this.closed) return;
7980
7981  const opts = this.options;
7982  if (isWindows$2) path = sysPath.normalize(path);
7983  if (opts.cwd) path = sysPath.relative(opts.cwd, path);
7984  /** @type Array<any> */
7985  const args = [event, path];
7986  if (val3 !== undefined) args.push(val1, val2, val3);
7987  else if (val2 !== undefined) args.push(val1, val2);
7988  else if (val1 !== undefined) args.push(val1);
7989
7990  const awf = opts.awaitWriteFinish;
7991  let pw;
7992  if (awf && (pw = this._pendingWrites.get(path))) {
7993    pw.lastChange = new Date();
7994    return this;
7995  }
7996
7997  if (opts.atomic) {
7998    if (event === EV_UNLINK) {
7999      this._pendingUnlinks.set(path, args);
8000      setTimeout(() => {
8001        this._pendingUnlinks.forEach((entry, path) => {
8002          this.emit(...entry);
8003          this.emit(EV_ALL, ...entry);
8004          this._pendingUnlinks.delete(path);
8005        });
8006      }, typeof opts.atomic === 'number' ? opts.atomic : 100);
8007      return this;
8008    }
8009    if (event === EV_ADD && this._pendingUnlinks.has(path)) {
8010      event = args[0] = EV_CHANGE;
8011      this._pendingUnlinks.delete(path);
8012    }
8013  }
8014
8015  if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
8016    const awfEmit = (err, stats) => {
8017      if (err) {
8018        event = args[0] = EV_ERROR;
8019        args[1] = err;
8020        this.emitWithAll(event, args);
8021      } else if (stats) {
8022        // if stats doesn't exist the file must have been deleted
8023        if (args.length > 2) {
8024          args[2] = stats;
8025        } else {
8026          args.push(stats);
8027        }
8028        this.emitWithAll(event, args);
8029      }
8030    };
8031
8032    this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
8033    return this;
8034  }
8035
8036  if (event === EV_CHANGE) {
8037    const isThrottled = !this._throttle(EV_CHANGE, path, 50);
8038    if (isThrottled) return this;
8039  }
8040
8041  if (opts.alwaysStat && val1 === undefined &&
8042    (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
8043  ) {
8044    const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
8045    let stats;
8046    try {
8047      stats = await stat(fullPath);
8048    } catch (err) {}
8049    // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
8050    if (!stats || this.closed) return;
8051    args.push(stats);
8052  }
8053  this.emitWithAll(event, args);
8054
8055  return this;
8056}
8057
8058/**
8059 * Common handler for errors
8060 * @param {Error} error
8061 * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
8062 */
8063_handleError(error) {
8064  const code = error && error.code;
8065  if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
8066    (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
8067  ) {
8068    this.emit(EV_ERROR, error);
8069  }
8070  return error || this.closed;
8071}
8072
8073/**
8074 * Helper utility for throttling
8075 * @param {ThrottleType} actionType type being throttled
8076 * @param {Path} path being acted upon
8077 * @param {Number} timeout duration of time to suppress duplicate actions
8078 * @returns {Object|false} tracking object or false if action should be suppressed
8079 */
8080_throttle(actionType, path, timeout) {
8081  if (!this._throttled.has(actionType)) {
8082    this._throttled.set(actionType, new Map());
8083  }
8084
8085  /** @type {Map<Path, Object>} */
8086  const action = this._throttled.get(actionType);
8087  /** @type {Object} */
8088  const actionPath = action.get(path);
8089
8090  if (actionPath) {
8091    actionPath.count++;
8092    return false;
8093  }
8094
8095  let timeoutObject;
8096  const clear = () => {
8097    const item = action.get(path);
8098    const count = item ? item.count : 0;
8099    action.delete(path);
8100    clearTimeout(timeoutObject);
8101    if (item) clearTimeout(item.timeoutObject);
8102    return count;
8103  };
8104  timeoutObject = setTimeout(clear, timeout);
8105  const thr = {timeoutObject, clear, count: 0};
8106  action.set(path, thr);
8107  return thr;
8108}
8109
8110_incrReadyCount() {
8111  return this._readyCount++;
8112}
8113
8114/**
8115 * Awaits write operation to finish.
8116 * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
8117 * @param {Path} path being acted upon
8118 * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
8119 * @param {EventName} event
8120 * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
8121 */
8122_awaitWriteFinish(path, threshold, event, awfEmit) {
8123  let timeoutHandler;
8124
8125  let fullPath = path;
8126  if (this.options.cwd && !sysPath.isAbsolute(path)) {
8127    fullPath = sysPath.join(this.options.cwd, path);
8128  }
8129
8130  const now = new Date();
8131
8132  const awaitWriteFinish = (prevStat) => {
8133    fs$6.stat(fullPath, (err, curStat) => {
8134      if (err || !this._pendingWrites.has(path)) {
8135        if (err && err.code !== 'ENOENT') awfEmit(err);
8136        return;
8137      }
8138
8139      const now = Number(new Date());
8140
8141      if (prevStat && curStat.size !== prevStat.size) {
8142        this._pendingWrites.get(path).lastChange = now;
8143      }
8144      const pw = this._pendingWrites.get(path);
8145      const df = now - pw.lastChange;
8146
8147      if (df >= threshold) {
8148        this._pendingWrites.delete(path);
8149        awfEmit(undefined, curStat);
8150      } else {
8151        timeoutHandler = setTimeout(
8152          awaitWriteFinish,
8153          this.options.awaitWriteFinish.pollInterval,
8154          curStat
8155        );
8156      }
8157    });
8158  };
8159
8160  if (!this._pendingWrites.has(path)) {
8161    this._pendingWrites.set(path, {
8162      lastChange: now,
8163      cancelWait: () => {
8164        this._pendingWrites.delete(path);
8165        clearTimeout(timeoutHandler);
8166        return event;
8167      }
8168    });
8169    timeoutHandler = setTimeout(
8170      awaitWriteFinish,
8171      this.options.awaitWriteFinish.pollInterval
8172    );
8173  }
8174}
8175
8176_getGlobIgnored() {
8177  return [...this._ignoredPaths.values()];
8178}
8179
8180/**
8181 * Determines whether user has asked to ignore this path.
8182 * @param {Path} path filepath or dir
8183 * @param {fs.Stats=} stats result of fs.stat
8184 * @returns {Boolean}
8185 */
8186_isIgnored(path, stats) {
8187  if (this.options.atomic && DOT_RE.test(path)) return true;
8188  if (!this._userIgnored) {
8189    const {cwd} = this.options;
8190    const ign = this.options.ignored;
8191
8192    const ignored = ign && ign.map(normalizeIgnored(cwd));
8193    const paths = arrify(ignored)
8194      .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
8195      .map((path) => path + SLASH_GLOBSTAR);
8196    const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
8197    this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
8198  }
8199
8200  return this._userIgnored([path, stats]);
8201}
8202
8203_isntIgnored(path, stat) {
8204  return !this._isIgnored(path, stat);
8205}
8206
8207/**
8208 * Provides a set of common helpers and properties relating to symlink and glob handling.
8209 * @param {Path} path file, directory, or glob pattern being watched
8210 * @param {Number=} depth at any depth > 0, this isn't a glob
8211 * @returns {WatchHelper} object containing helpers for this path
8212 */
8213_getWatchHelpers(path, depth) {
8214  const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
8215  const follow = this.options.followSymlinks;
8216
8217  return new WatchHelper(path, watchPath, follow, this);
8218}
8219
8220// Directory helpers
8221// -----------------
8222
8223/**
8224 * Provides directory tracking objects
8225 * @param {String} directory path of the directory
8226 * @returns {DirEntry} the directory's tracking object
8227 */
8228_getWatchedDir(directory) {
8229  if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
8230  const dir = sysPath.resolve(directory);
8231  if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
8232  return this._watched.get(dir);
8233}
8234
8235// File helpers
8236// ------------
8237
8238/**
8239 * Check for read permissions.
8240 * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
8241 * @param {fs.Stats} stats - object, result of fs_stat
8242 * @returns {Boolean} indicates whether the file can be read
8243*/
8244_hasReadPermissions(stats) {
8245  if (this.options.ignorePermissionErrors) return true;
8246
8247  // stats.mode may be bigint
8248  const md = stats && Number.parseInt(stats.mode, 10);
8249  const st = md & 0o777;
8250  const it = Number.parseInt(st.toString(8)[0], 10);
8251  return Boolean(4 & it);
8252}
8253
8254/**
8255 * Handles emitting unlink events for
8256 * files and directories, and via recursion, for
8257 * files and directories within directories that are unlinked
8258 * @param {String} directory within which the following item is located
8259 * @param {String} item      base path of item/directory
8260 * @returns {void}
8261*/
8262_remove(directory, item, isDirectory) {
8263  // if what is being deleted is a directory, get that directory's paths
8264  // for recursive deleting and cleaning of watched object
8265  // if it is not a directory, nestedDirectoryChildren will be empty array
8266  const path = sysPath.join(directory, item);
8267  const fullPath = sysPath.resolve(path);
8268  isDirectory = isDirectory != null
8269    ? isDirectory
8270    : this._watched.has(path) || this._watched.has(fullPath);
8271
8272  // prevent duplicate handling in case of arriving here nearly simultaneously
8273  // via multiple paths (such as _handleFile and _handleDir)
8274  if (!this._throttle('remove', path, 100)) return;
8275
8276  // if the only watched file is removed, watch for its return
8277  if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
8278    this.add(directory, item, true);
8279  }
8280
8281  // This will create a new entry in the watched object in either case
8282  // so we got to do the directory check beforehand
8283  const wp = this._getWatchedDir(path);
8284  const nestedDirectoryChildren = wp.getChildren();
8285
8286  // Recursively remove children directories / files.
8287  nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
8288
8289  // Check if item was on the watched list and remove it
8290  const parent = this._getWatchedDir(directory);
8291  const wasTracked = parent.has(item);
8292  parent.remove(item);
8293
8294  // Fixes issue #1042 -> Relative paths were detected and added as symlinks
8295  // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
8296  // but never removed from the map in case the path was deleted.
8297  // This leads to an incorrect state if the path was recreated:
8298  // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
8299  if (this._symlinkPaths.has(fullPath)) {
8300    this._symlinkPaths.delete(fullPath);
8301  }
8302
8303  // If we wait for this file to be fully written, cancel the wait.
8304  let relPath = path;
8305  if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
8306  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
8307    const event = this._pendingWrites.get(relPath).cancelWait();
8308    if (event === EV_ADD) return;
8309  }
8310
8311  // The Entry will either be a directory that just got removed
8312  // or a bogus entry to a file, in either case we have to remove it
8313  this._watched.delete(path);
8314  this._watched.delete(fullPath);
8315  const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
8316  if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
8317
8318  // Avoid conflicts if we later create another file with the same name
8319  if (!this.options.useFsEvents) {
8320    this._closePath(path);
8321  }
8322}
8323
8324/**
8325 * Closes all watchers for a path
8326 * @param {Path} path
8327 */
8328_closePath(path) {
8329  this._closeFile(path);
8330  const dir = sysPath.dirname(path);
8331  this._getWatchedDir(dir).remove(sysPath.basename(path));
8332}
8333
8334/**
8335 * Closes only file-specific watchers
8336 * @param {Path} path
8337 */
8338_closeFile(path) {
8339  const closers = this._closers.get(path);
8340  if (!closers) return;
8341  closers.forEach(closer => closer());
8342  this._closers.delete(path);
8343}
8344
8345/**
8346 *
8347 * @param {Path} path
8348 * @param {Function} closer
8349 */
8350_addPathCloser(path, closer) {
8351  if (!closer) return;
8352  let list = this._closers.get(path);
8353  if (!list) {
8354    list = [];
8355    this._closers.set(path, list);
8356  }
8357  list.push(closer);
8358}
8359
8360_readdirp(root, opts) {
8361  if (this.closed) return;
8362  const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
8363  let stream = readdirp(root, options);
8364  this._streams.add(stream);
8365  stream.once(STR_CLOSE, () => {
8366    stream = undefined;
8367  });
8368  stream.once(STR_END, () => {
8369    if (stream) {
8370      this._streams.delete(stream);
8371      stream = undefined;
8372    }
8373  });
8374  return stream;
8375}
8376
8377}
8378
8379// Export FSWatcher class
8380chokidar.FSWatcher = FSWatcher;
8381
8382/**
8383 * Instantiates watcher with paths to be tracked.
8384 * @param {String|Array<String>} paths file/directory paths and/or globs
8385 * @param {Object=} options chokidar opts
8386 * @returns an instance of FSWatcher for chaining.
8387 */
8388const watch = (paths, options) => {
8389  const watcher = new FSWatcher(options);
8390  watcher.add(paths);
8391  return watcher;
8392};
8393
8394chokidar.watch = watch;
8395
8396/**
8397 * @typedef {import('vfile').VFile} VFile
8398 * @typedef {import('vfile-message').VFileMessage} VFileMessage
8399 *
8400 * @typedef Statistics
8401 * @property {number} fatal Fatal errors (`fatal: true`)
8402 * @property {number} warn warning errors (`fatal: false`)
8403 * @property {number} info informational messages (`fatal: null|undefined`)
8404 * @property {number} nonfatal warning + info
8405 * @property {number} total nonfatal + fatal
8406 */
8407
8408/**
8409 * Get stats for a file, list of files, or list of messages.
8410 *
8411 * @param {Array.<VFile|VFileMessage>|VFile|VFileMessage} [value]
8412 * @returns {Statistics}
8413 */
8414function statistics(value) {
8415  var result = {true: 0, false: 0, null: 0};
8416
8417  if (value) {
8418    if (Array.isArray(value)) {
8419      list(value);
8420    } else {
8421      one(value);
8422    }
8423  }
8424
8425  return {
8426    fatal: result.true,
8427    nonfatal: result.false + result.null,
8428    warn: result.false,
8429    info: result.null,
8430    total: result.true + result.false + result.null
8431  }
8432
8433  /**
8434   * @param {Array.<VFile|VFileMessage>} value
8435   * @returns {void}
8436   */
8437  function list(value) {
8438    var index = -1;
8439
8440    while (++index < value.length) {
8441      one(value[index]);
8442    }
8443  }
8444
8445  /**
8446   * @param {VFile|VFileMessage} value
8447   * @returns {void}
8448   */
8449  function one(value) {
8450    if ('messages' in value) return list(value.messages)
8451
8452    result[
8453      value.fatal === undefined || value.fatal === null
8454        ? null
8455        : Boolean(value.fatal)
8456    ]++;
8457  }
8458}
8459
8460/**
8461 * @typedef {(error?: Error|null|undefined, ...output: any[]) => void} Callback
8462 * @typedef {(...input: any[]) => any} Middleware
8463 *
8464 * @typedef {(...input: any[]) => void} Run Call all middleware.
8465 * @typedef {(fn: Middleware) => Pipeline} Use Add `fn` (middleware) to the list.
8466 * @typedef {{run: Run, use: Use}} Pipeline
8467 */
8468
8469/**
8470 * Create new middleware.
8471 *
8472 * @returns {Pipeline}
8473 */
8474function trough() {
8475  /** @type {Middleware[]} */
8476  const fns = [];
8477  /** @type {Pipeline} */
8478  const pipeline = {run, use};
8479
8480  return pipeline
8481
8482  /** @type {Run} */
8483  function run(...values) {
8484    let middlewareIndex = -1;
8485    /** @type {Callback} */
8486    const callback = values.pop();
8487
8488    if (typeof callback !== 'function') {
8489      throw new TypeError('Expected function as last argument, not ' + callback)
8490    }
8491
8492    next(null, ...values);
8493
8494    /**
8495     * Run the next `fn`, or we’re done.
8496     *
8497     * @param {Error|null|undefined} error
8498     * @param {any[]} output
8499     */
8500    function next(error, ...output) {
8501      const fn = fns[++middlewareIndex];
8502      let index = -1;
8503
8504      if (error) {
8505        callback(error);
8506        return
8507      }
8508
8509      // Copy non-nullish input into values.
8510      while (++index < values.length) {
8511        if (output[index] === null || output[index] === undefined) {
8512          output[index] = values[index];
8513        }
8514      }
8515
8516      // Save the newly created `output` for the next call.
8517      values = output;
8518
8519      // Next or done.
8520      if (fn) {
8521        wrap(fn, next)(...output);
8522      } else {
8523        callback(null, ...output);
8524      }
8525    }
8526  }
8527
8528  /** @type {Use} */
8529  function use(middelware) {
8530    if (typeof middelware !== 'function') {
8531      throw new TypeError(
8532        'Expected `middelware` to be a function, not ' + middelware
8533      )
8534    }
8535
8536    fns.push(middelware);
8537    return pipeline
8538  }
8539}
8540
8541/**
8542 * Wrap `middleware`.
8543 * Can be sync or async; return a promise, receive a callback, or return new
8544 * values and errors.
8545 *
8546 * @param {Middleware} middleware
8547 * @param {Callback} callback
8548 */
8549function wrap(middleware, callback) {
8550  /** @type {boolean} */
8551  let called;
8552
8553  return wrapped
8554
8555  /**
8556   * Call `middleware`.
8557   * @param {any[]} parameters
8558   * @returns {void}
8559   */
8560  function wrapped(...parameters) {
8561    const fnExpectsCallback = middleware.length > parameters.length;
8562    /** @type {any} */
8563    let result;
8564
8565    if (fnExpectsCallback) {
8566      parameters.push(done);
8567    }
8568
8569    try {
8570      result = middleware(...parameters);
8571    } catch (error) {
8572      /** @type {Error} */
8573      const exception = error;
8574
8575      // Well, this is quite the pickle.
8576      // `middleware` received a callback and called it synchronously, but that
8577      // threw an error.
8578      // The only thing left to do is to throw the thing instead.
8579      if (fnExpectsCallback && called) {
8580        throw exception
8581      }
8582
8583      return done(exception)
8584    }
8585
8586    if (!fnExpectsCallback) {
8587      if (result instanceof Promise) {
8588        result.then(then, done);
8589      } else if (result instanceof Error) {
8590        done(result);
8591      } else {
8592        then(result);
8593      }
8594    }
8595  }
8596
8597  /**
8598   * Call `callback`, only once.
8599   * @type {Callback}
8600   */
8601  function done(error, ...output) {
8602    if (!called) {
8603      called = true;
8604      callback(error, ...output);
8605    }
8606  }
8607
8608  /**
8609   * Call `done` with one value.
8610   *
8611   * @param {any} [value]
8612   */
8613  function then(value) {
8614    done(null, value);
8615  }
8616}
8617
8618/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
8619function isNothing(subject) {
8620  return (typeof subject === 'undefined') || (subject === null);
8621}
8622
8623
8624function isObject$1(subject) {
8625  return (typeof subject === 'object') && (subject !== null);
8626}
8627
8628
8629function toArray(sequence) {
8630  if (Array.isArray(sequence)) return sequence;
8631  else if (isNothing(sequence)) return [];
8632
8633  return [ sequence ];
8634}
8635
8636
8637function extend$2(target, source) {
8638  var index, length, key, sourceKeys;
8639
8640  if (source) {
8641    sourceKeys = Object.keys(source);
8642
8643    for (index = 0, length = sourceKeys.length; index < length; index += 1) {
8644      key = sourceKeys[index];
8645      target[key] = source[key];
8646    }
8647  }
8648
8649  return target;
8650}
8651
8652
8653function repeat$1(string, count) {
8654  var result = '', cycle;
8655
8656  for (cycle = 0; cycle < count; cycle += 1) {
8657    result += string;
8658  }
8659
8660  return result;
8661}
8662
8663
8664function isNegativeZero(number) {
8665  return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
8666}
8667
8668
8669var isNothing_1      = isNothing;
8670var isObject_1       = isObject$1;
8671var toArray_1        = toArray;
8672var repeat_1         = repeat$1;
8673var isNegativeZero_1 = isNegativeZero;
8674var extend_1         = extend$2;
8675
8676var common$4 = {
8677	isNothing: isNothing_1,
8678	isObject: isObject_1,
8679	toArray: toArray_1,
8680	repeat: repeat_1,
8681	isNegativeZero: isNegativeZero_1,
8682	extend: extend_1
8683};
8684
8685// YAML error class. http://stackoverflow.com/questions/8458984
8686
8687
8688function formatError(exception, compact) {
8689  var where = '', message = exception.reason || '(unknown reason)';
8690
8691  if (!exception.mark) return message;
8692
8693  if (exception.mark.name) {
8694    where += 'in "' + exception.mark.name + '" ';
8695  }
8696
8697  where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
8698
8699  if (!compact && exception.mark.snippet) {
8700    where += '\n\n' + exception.mark.snippet;
8701  }
8702
8703  return message + ' ' + where;
8704}
8705
8706
8707function YAMLException$1(reason, mark) {
8708  // Super constructor
8709  Error.call(this);
8710
8711  this.name = 'YAMLException';
8712  this.reason = reason;
8713  this.mark = mark;
8714  this.message = formatError(this, false);
8715
8716  // Include stack trace in error object
8717  if (Error.captureStackTrace) {
8718    // Chrome and NodeJS
8719    Error.captureStackTrace(this, this.constructor);
8720  } else {
8721    // FF, IE 10+ and Safari 6+. Fallback for others
8722    this.stack = (new Error()).stack || '';
8723  }
8724}
8725
8726
8727// Inherit from Error
8728YAMLException$1.prototype = Object.create(Error.prototype);
8729YAMLException$1.prototype.constructor = YAMLException$1;
8730
8731
8732YAMLException$1.prototype.toString = function toString(compact) {
8733  return this.name + ': ' + formatError(this, compact);
8734};
8735
8736
8737var exception = YAMLException$1;
8738
8739// get snippet for a single line, respecting maxLength
8740function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
8741  var head = '';
8742  var tail = '';
8743  var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
8744
8745  if (position - lineStart > maxHalfLength) {
8746    head = ' ... ';
8747    lineStart = position - maxHalfLength + head.length;
8748  }
8749
8750  if (lineEnd - position > maxHalfLength) {
8751    tail = ' ...';
8752    lineEnd = position + maxHalfLength - tail.length;
8753  }
8754
8755  return {
8756    str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
8757    pos: position - lineStart + head.length // relative position
8758  };
8759}
8760
8761
8762function padStart(string, max) {
8763  return common$4.repeat(' ', max - string.length) + string;
8764}
8765
8766
8767function makeSnippet(mark, options) {
8768  options = Object.create(options || null);
8769
8770  if (!mark.buffer) return null;
8771
8772  if (!options.maxLength) options.maxLength = 79;
8773  if (typeof options.indent      !== 'number') options.indent      = 1;
8774  if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
8775  if (typeof options.linesAfter  !== 'number') options.linesAfter  = 2;
8776
8777  var re = /\r?\n|\r|\0/g;
8778  var lineStarts = [ 0 ];
8779  var lineEnds = [];
8780  var match;
8781  var foundLineNo = -1;
8782
8783  while ((match = re.exec(mark.buffer))) {
8784    lineEnds.push(match.index);
8785    lineStarts.push(match.index + match[0].length);
8786
8787    if (mark.position <= match.index && foundLineNo < 0) {
8788      foundLineNo = lineStarts.length - 2;
8789    }
8790  }
8791
8792  if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
8793
8794  var result = '', i, line;
8795  var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
8796  var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
8797
8798  for (i = 1; i <= options.linesBefore; i++) {
8799    if (foundLineNo - i < 0) break;
8800    line = getLine(
8801      mark.buffer,
8802      lineStarts[foundLineNo - i],
8803      lineEnds[foundLineNo - i],
8804      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
8805      maxLineLength
8806    );
8807    result = common$4.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
8808      ' | ' + line.str + '\n' + result;
8809  }
8810
8811  line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
8812  result += common$4.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
8813    ' | ' + line.str + '\n';
8814  result += common$4.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
8815
8816  for (i = 1; i <= options.linesAfter; i++) {
8817    if (foundLineNo + i >= lineEnds.length) break;
8818    line = getLine(
8819      mark.buffer,
8820      lineStarts[foundLineNo + i],
8821      lineEnds[foundLineNo + i],
8822      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
8823      maxLineLength
8824    );
8825    result += common$4.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
8826      ' | ' + line.str + '\n';
8827  }
8828
8829  return result.replace(/\n$/, '');
8830}
8831
8832
8833var snippet = makeSnippet;
8834
8835var TYPE_CONSTRUCTOR_OPTIONS = [
8836  'kind',
8837  'multi',
8838  'resolve',
8839  'construct',
8840  'instanceOf',
8841  'predicate',
8842  'represent',
8843  'representName',
8844  'defaultStyle',
8845  'styleAliases'
8846];
8847
8848var YAML_NODE_KINDS = [
8849  'scalar',
8850  'sequence',
8851  'mapping'
8852];
8853
8854function compileStyleAliases(map) {
8855  var result = {};
8856
8857  if (map !== null) {
8858    Object.keys(map).forEach(function (style) {
8859      map[style].forEach(function (alias) {
8860        result[String(alias)] = style;
8861      });
8862    });
8863  }
8864
8865  return result;
8866}
8867
8868function Type$1(tag, options) {
8869  options = options || {};
8870
8871  Object.keys(options).forEach(function (name) {
8872    if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
8873      throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
8874    }
8875  });
8876
8877  // TODO: Add tag format check.
8878  this.options       = options; // keep original options in case user wants to extend this type later
8879  this.tag           = tag;
8880  this.kind          = options['kind']          || null;
8881  this.resolve       = options['resolve']       || function () { return true; };
8882  this.construct     = options['construct']     || function (data) { return data; };
8883  this.instanceOf    = options['instanceOf']    || null;
8884  this.predicate     = options['predicate']     || null;
8885  this.represent     = options['represent']     || null;
8886  this.representName = options['representName'] || null;
8887  this.defaultStyle  = options['defaultStyle']  || null;
8888  this.multi         = options['multi']         || false;
8889  this.styleAliases  = compileStyleAliases(options['styleAliases'] || null);
8890
8891  if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
8892    throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
8893  }
8894}
8895
8896var type$1 = Type$1;
8897
8898/*eslint-disable max-len*/
8899
8900
8901
8902
8903
8904function compileList(schema, name) {
8905  var result = [];
8906
8907  schema[name].forEach(function (currentType) {
8908    var newIndex = result.length;
8909
8910    result.forEach(function (previousType, previousIndex) {
8911      if (previousType.tag === currentType.tag &&
8912          previousType.kind === currentType.kind &&
8913          previousType.multi === currentType.multi) {
8914
8915        newIndex = previousIndex;
8916      }
8917    });
8918
8919    result[newIndex] = currentType;
8920  });
8921
8922  return result;
8923}
8924
8925
8926function compileMap(/* lists... */) {
8927  var result = {
8928        scalar: {},
8929        sequence: {},
8930        mapping: {},
8931        fallback: {},
8932        multi: {
8933          scalar: [],
8934          sequence: [],
8935          mapping: [],
8936          fallback: []
8937        }
8938      }, index, length;
8939
8940  function collectType(type) {
8941    if (type.multi) {
8942      result.multi[type.kind].push(type);
8943      result.multi['fallback'].push(type);
8944    } else {
8945      result[type.kind][type.tag] = result['fallback'][type.tag] = type;
8946    }
8947  }
8948
8949  for (index = 0, length = arguments.length; index < length; index += 1) {
8950    arguments[index].forEach(collectType);
8951  }
8952  return result;
8953}
8954
8955
8956function Schema$1(definition) {
8957  return this.extend(definition);
8958}
8959
8960
8961Schema$1.prototype.extend = function extend(definition) {
8962  var implicit = [];
8963  var explicit = [];
8964
8965  if (definition instanceof type$1) {
8966    // Schema.extend(type)
8967    explicit.push(definition);
8968
8969  } else if (Array.isArray(definition)) {
8970    // Schema.extend([ type1, type2, ... ])
8971    explicit = explicit.concat(definition);
8972
8973  } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
8974    // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
8975    if (definition.implicit) implicit = implicit.concat(definition.implicit);
8976    if (definition.explicit) explicit = explicit.concat(definition.explicit);
8977
8978  } else {
8979    throw new exception('Schema.extend argument should be a Type, [ Type ], ' +
8980      'or a schema definition ({ implicit: [...], explicit: [...] })');
8981  }
8982
8983  implicit.forEach(function (type$1$1) {
8984    if (!(type$1$1 instanceof type$1)) {
8985      throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
8986    }
8987
8988    if (type$1$1.loadKind && type$1$1.loadKind !== 'scalar') {
8989      throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
8990    }
8991
8992    if (type$1$1.multi) {
8993      throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
8994    }
8995  });
8996
8997  explicit.forEach(function (type$1$1) {
8998    if (!(type$1$1 instanceof type$1)) {
8999      throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');
9000    }
9001  });
9002
9003  var result = Object.create(Schema$1.prototype);
9004
9005  result.implicit = (this.implicit || []).concat(implicit);
9006  result.explicit = (this.explicit || []).concat(explicit);
9007
9008  result.compiledImplicit = compileList(result, 'implicit');
9009  result.compiledExplicit = compileList(result, 'explicit');
9010  result.compiledTypeMap  = compileMap(result.compiledImplicit, result.compiledExplicit);
9011
9012  return result;
9013};
9014
9015
9016var schema$1 = Schema$1;
9017
9018var str = new type$1('tag:yaml.org,2002:str', {
9019  kind: 'scalar',
9020  construct: function (data) { return data !== null ? data : ''; }
9021});
9022
9023var seq = new type$1('tag:yaml.org,2002:seq', {
9024  kind: 'sequence',
9025  construct: function (data) { return data !== null ? data : []; }
9026});
9027
9028var map$3 = new type$1('tag:yaml.org,2002:map', {
9029  kind: 'mapping',
9030  construct: function (data) { return data !== null ? data : {}; }
9031});
9032
9033var failsafe = new schema$1({
9034  explicit: [
9035    str,
9036    seq,
9037    map$3
9038  ]
9039});
9040
9041function resolveYamlNull(data) {
9042  if (data === null) return true;
9043
9044  var max = data.length;
9045
9046  return (max === 1 && data === '~') ||
9047         (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
9048}
9049
9050function constructYamlNull() {
9051  return null;
9052}
9053
9054function isNull(object) {
9055  return object === null;
9056}
9057
9058var _null = new type$1('tag:yaml.org,2002:null', {
9059  kind: 'scalar',
9060  resolve: resolveYamlNull,
9061  construct: constructYamlNull,
9062  predicate: isNull,
9063  represent: {
9064    canonical: function () { return '~';    },
9065    lowercase: function () { return 'null'; },
9066    uppercase: function () { return 'NULL'; },
9067    camelcase: function () { return 'Null'; },
9068    empty:     function () { return '';     }
9069  },
9070  defaultStyle: 'lowercase'
9071});
9072
9073function resolveYamlBoolean(data) {
9074  if (data === null) return false;
9075
9076  var max = data.length;
9077
9078  return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
9079         (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
9080}
9081
9082function constructYamlBoolean(data) {
9083  return data === 'true' ||
9084         data === 'True' ||
9085         data === 'TRUE';
9086}
9087
9088function isBoolean(object) {
9089  return Object.prototype.toString.call(object) === '[object Boolean]';
9090}
9091
9092var bool = new type$1('tag:yaml.org,2002:bool', {
9093  kind: 'scalar',
9094  resolve: resolveYamlBoolean,
9095  construct: constructYamlBoolean,
9096  predicate: isBoolean,
9097  represent: {
9098    lowercase: function (object) { return object ? 'true' : 'false'; },
9099    uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
9100    camelcase: function (object) { return object ? 'True' : 'False'; }
9101  },
9102  defaultStyle: 'lowercase'
9103});
9104
9105function isHexCode(c) {
9106  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
9107         ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
9108         ((0x61/* a */ <= c) && (c <= 0x66/* f */));
9109}
9110
9111function isOctCode(c) {
9112  return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
9113}
9114
9115function isDecCode(c) {
9116  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
9117}
9118
9119function resolveYamlInteger(data) {
9120  if (data === null) return false;
9121
9122  var max = data.length,
9123      index = 0,
9124      hasDigits = false,
9125      ch;
9126
9127  if (!max) return false;
9128
9129  ch = data[index];
9130
9131  // sign
9132  if (ch === '-' || ch === '+') {
9133    ch = data[++index];
9134  }
9135
9136  if (ch === '0') {
9137    // 0
9138    if (index + 1 === max) return true;
9139    ch = data[++index];
9140
9141    // base 2, base 8, base 16
9142
9143    if (ch === 'b') {
9144      // base 2
9145      index++;
9146
9147      for (; index < max; index++) {
9148        ch = data[index];
9149        if (ch === '_') continue;
9150        if (ch !== '0' && ch !== '1') return false;
9151        hasDigits = true;
9152      }
9153      return hasDigits && ch !== '_';
9154    }
9155
9156
9157    if (ch === 'x') {
9158      // base 16
9159      index++;
9160
9161      for (; index < max; index++) {
9162        ch = data[index];
9163        if (ch === '_') continue;
9164        if (!isHexCode(data.charCodeAt(index))) return false;
9165        hasDigits = true;
9166      }
9167      return hasDigits && ch !== '_';
9168    }
9169
9170
9171    if (ch === 'o') {
9172      // base 8
9173      index++;
9174
9175      for (; index < max; index++) {
9176        ch = data[index];
9177        if (ch === '_') continue;
9178        if (!isOctCode(data.charCodeAt(index))) return false;
9179        hasDigits = true;
9180      }
9181      return hasDigits && ch !== '_';
9182    }
9183  }
9184
9185  // base 10 (except 0)
9186
9187  // value should not start with `_`;
9188  if (ch === '_') return false;
9189
9190  for (; index < max; index++) {
9191    ch = data[index];
9192    if (ch === '_') continue;
9193    if (!isDecCode(data.charCodeAt(index))) {
9194      return false;
9195    }
9196    hasDigits = true;
9197  }
9198
9199  // Should have digits and should not end with `_`
9200  if (!hasDigits || ch === '_') return false;
9201
9202  return true;
9203}
9204
9205function constructYamlInteger(data) {
9206  var value = data, sign = 1, ch;
9207
9208  if (value.indexOf('_') !== -1) {
9209    value = value.replace(/_/g, '');
9210  }
9211
9212  ch = value[0];
9213
9214  if (ch === '-' || ch === '+') {
9215    if (ch === '-') sign = -1;
9216    value = value.slice(1);
9217    ch = value[0];
9218  }
9219
9220  if (value === '0') return 0;
9221
9222  if (ch === '0') {
9223    if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
9224    if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
9225    if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
9226  }
9227
9228  return sign * parseInt(value, 10);
9229}
9230
9231function isInteger(object) {
9232  return (Object.prototype.toString.call(object)) === '[object Number]' &&
9233         (object % 1 === 0 && !common$4.isNegativeZero(object));
9234}
9235
9236var int = new type$1('tag:yaml.org,2002:int', {
9237  kind: 'scalar',
9238  resolve: resolveYamlInteger,
9239  construct: constructYamlInteger,
9240  predicate: isInteger,
9241  represent: {
9242    binary:      function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
9243    octal:       function (obj) { return obj >= 0 ? '0o'  + obj.toString(8) : '-0o'  + obj.toString(8).slice(1); },
9244    decimal:     function (obj) { return obj.toString(10); },
9245    /* eslint-disable max-len */
9246    hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() :  '-0x' + obj.toString(16).toUpperCase().slice(1); }
9247  },
9248  defaultStyle: 'decimal',
9249  styleAliases: {
9250    binary:      [ 2,  'bin' ],
9251    octal:       [ 8,  'oct' ],
9252    decimal:     [ 10, 'dec' ],
9253    hexadecimal: [ 16, 'hex' ]
9254  }
9255});
9256
9257var YAML_FLOAT_PATTERN = new RegExp(
9258  // 2.5e4, 2.5 and integers
9259  '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
9260  // .2e4, .2
9261  // special case, seems not from spec
9262  '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
9263  // .inf
9264  '|[-+]?\\.(?:inf|Inf|INF)' +
9265  // .nan
9266  '|\\.(?:nan|NaN|NAN))$');
9267
9268function resolveYamlFloat(data) {
9269  if (data === null) return false;
9270
9271  if (!YAML_FLOAT_PATTERN.test(data) ||
9272      // Quick hack to not allow integers end with `_`
9273      // Probably should update regexp & check speed
9274      data[data.length - 1] === '_') {
9275    return false;
9276  }
9277
9278  return true;
9279}
9280
9281function constructYamlFloat(data) {
9282  var value, sign;
9283
9284  value  = data.replace(/_/g, '').toLowerCase();
9285  sign   = value[0] === '-' ? -1 : 1;
9286
9287  if ('+-'.indexOf(value[0]) >= 0) {
9288    value = value.slice(1);
9289  }
9290
9291  if (value === '.inf') {
9292    return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
9293
9294  } else if (value === '.nan') {
9295    return NaN;
9296  }
9297  return sign * parseFloat(value, 10);
9298}
9299
9300
9301var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
9302
9303function representYamlFloat(object, style) {
9304  var res;
9305
9306  if (isNaN(object)) {
9307    switch (style) {
9308      case 'lowercase': return '.nan';
9309      case 'uppercase': return '.NAN';
9310      case 'camelcase': return '.NaN';
9311    }
9312  } else if (Number.POSITIVE_INFINITY === object) {
9313    switch (style) {
9314      case 'lowercase': return '.inf';
9315      case 'uppercase': return '.INF';
9316      case 'camelcase': return '.Inf';
9317    }
9318  } else if (Number.NEGATIVE_INFINITY === object) {
9319    switch (style) {
9320      case 'lowercase': return '-.inf';
9321      case 'uppercase': return '-.INF';
9322      case 'camelcase': return '-.Inf';
9323    }
9324  } else if (common$4.isNegativeZero(object)) {
9325    return '-0.0';
9326  }
9327
9328  res = object.toString(10);
9329
9330  // JS stringifier can build scientific format without dots: 5e-100,
9331  // while YAML requres dot: 5.e-100. Fix it with simple hack
9332
9333  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
9334}
9335
9336function isFloat(object) {
9337  return (Object.prototype.toString.call(object) === '[object Number]') &&
9338         (object % 1 !== 0 || common$4.isNegativeZero(object));
9339}
9340
9341var float = new type$1('tag:yaml.org,2002:float', {
9342  kind: 'scalar',
9343  resolve: resolveYamlFloat,
9344  construct: constructYamlFloat,
9345  predicate: isFloat,
9346  represent: representYamlFloat,
9347  defaultStyle: 'lowercase'
9348});
9349
9350var json = failsafe.extend({
9351  implicit: [
9352    _null,
9353    bool,
9354    int,
9355    float
9356  ]
9357});
9358
9359var core = json;
9360
9361var YAML_DATE_REGEXP = new RegExp(
9362  '^([0-9][0-9][0-9][0-9])'          + // [1] year
9363  '-([0-9][0-9])'                    + // [2] month
9364  '-([0-9][0-9])$');                   // [3] day
9365
9366var YAML_TIMESTAMP_REGEXP = new RegExp(
9367  '^([0-9][0-9][0-9][0-9])'          + // [1] year
9368  '-([0-9][0-9]?)'                   + // [2] month
9369  '-([0-9][0-9]?)'                   + // [3] day
9370  '(?:[Tt]|[ \\t]+)'                 + // ...
9371  '([0-9][0-9]?)'                    + // [4] hour
9372  ':([0-9][0-9])'                    + // [5] minute
9373  ':([0-9][0-9])'                    + // [6] second
9374  '(?:\\.([0-9]*))?'                 + // [7] fraction
9375  '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
9376  '(?::([0-9][0-9]))?))?$');           // [11] tz_minute
9377
9378function resolveYamlTimestamp(data) {
9379  if (data === null) return false;
9380  if (YAML_DATE_REGEXP.exec(data) !== null) return true;
9381  if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
9382  return false;
9383}
9384
9385function constructYamlTimestamp(data) {
9386  var match, year, month, day, hour, minute, second, fraction = 0,
9387      delta = null, tz_hour, tz_minute, date;
9388
9389  match = YAML_DATE_REGEXP.exec(data);
9390  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
9391
9392  if (match === null) throw new Error('Date resolve error');
9393
9394  // match: [1] year [2] month [3] day
9395
9396  year = +(match[1]);
9397  month = +(match[2]) - 1; // JS month starts with 0
9398  day = +(match[3]);
9399
9400  if (!match[4]) { // no hour
9401    return new Date(Date.UTC(year, month, day));
9402  }
9403
9404  // match: [4] hour [5] minute [6] second [7] fraction
9405
9406  hour = +(match[4]);
9407  minute = +(match[5]);
9408  second = +(match[6]);
9409
9410  if (match[7]) {
9411    fraction = match[7].slice(0, 3);
9412    while (fraction.length < 3) { // milli-seconds
9413      fraction += '0';
9414    }
9415    fraction = +fraction;
9416  }
9417
9418  // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
9419
9420  if (match[9]) {
9421    tz_hour = +(match[10]);
9422    tz_minute = +(match[11] || 0);
9423    delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
9424    if (match[9] === '-') delta = -delta;
9425  }
9426
9427  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
9428
9429  if (delta) date.setTime(date.getTime() - delta);
9430
9431  return date;
9432}
9433
9434function representYamlTimestamp(object /*, style*/) {
9435  return object.toISOString();
9436}
9437
9438var timestamp = new type$1('tag:yaml.org,2002:timestamp', {
9439  kind: 'scalar',
9440  resolve: resolveYamlTimestamp,
9441  construct: constructYamlTimestamp,
9442  instanceOf: Date,
9443  represent: representYamlTimestamp
9444});
9445
9446function resolveYamlMerge(data) {
9447  return data === '<<' || data === null;
9448}
9449
9450var merge$1 = new type$1('tag:yaml.org,2002:merge', {
9451  kind: 'scalar',
9452  resolve: resolveYamlMerge
9453});
9454
9455/*eslint-disable no-bitwise*/
9456
9457
9458
9459
9460
9461// [ 64, 65, 66 ] -> [ padding, CR, LF ]
9462var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
9463
9464
9465function resolveYamlBinary(data) {
9466  if (data === null) return false;
9467
9468  var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
9469
9470  // Convert one by one.
9471  for (idx = 0; idx < max; idx++) {
9472    code = map.indexOf(data.charAt(idx));
9473
9474    // Skip CR/LF
9475    if (code > 64) continue;
9476
9477    // Fail on illegal characters
9478    if (code < 0) return false;
9479
9480    bitlen += 6;
9481  }
9482
9483  // If there are any bits left, source was corrupted
9484  return (bitlen % 8) === 0;
9485}
9486
9487function constructYamlBinary(data) {
9488  var idx, tailbits,
9489      input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
9490      max = input.length,
9491      map = BASE64_MAP,
9492      bits = 0,
9493      result = [];
9494
9495  // Collect by 6*4 bits (3 bytes)
9496
9497  for (idx = 0; idx < max; idx++) {
9498    if ((idx % 4 === 0) && idx) {
9499      result.push((bits >> 16) & 0xFF);
9500      result.push((bits >> 8) & 0xFF);
9501      result.push(bits & 0xFF);
9502    }
9503
9504    bits = (bits << 6) | map.indexOf(input.charAt(idx));
9505  }
9506
9507  // Dump tail
9508
9509  tailbits = (max % 4) * 6;
9510
9511  if (tailbits === 0) {
9512    result.push((bits >> 16) & 0xFF);
9513    result.push((bits >> 8) & 0xFF);
9514    result.push(bits & 0xFF);
9515  } else if (tailbits === 18) {
9516    result.push((bits >> 10) & 0xFF);
9517    result.push((bits >> 2) & 0xFF);
9518  } else if (tailbits === 12) {
9519    result.push((bits >> 4) & 0xFF);
9520  }
9521
9522  return new Uint8Array(result);
9523}
9524
9525function representYamlBinary(object /*, style*/) {
9526  var result = '', bits = 0, idx, tail,
9527      max = object.length,
9528      map = BASE64_MAP;
9529
9530  // Convert every three bytes to 4 ASCII characters.
9531
9532  for (idx = 0; idx < max; idx++) {
9533    if ((idx % 3 === 0) && idx) {
9534      result += map[(bits >> 18) & 0x3F];
9535      result += map[(bits >> 12) & 0x3F];
9536      result += map[(bits >> 6) & 0x3F];
9537      result += map[bits & 0x3F];
9538    }
9539
9540    bits = (bits << 8) + object[idx];
9541  }
9542
9543  // Dump tail
9544
9545  tail = max % 3;
9546
9547  if (tail === 0) {
9548    result += map[(bits >> 18) & 0x3F];
9549    result += map[(bits >> 12) & 0x3F];
9550    result += map[(bits >> 6) & 0x3F];
9551    result += map[bits & 0x3F];
9552  } else if (tail === 2) {
9553    result += map[(bits >> 10) & 0x3F];
9554    result += map[(bits >> 4) & 0x3F];
9555    result += map[(bits << 2) & 0x3F];
9556    result += map[64];
9557  } else if (tail === 1) {
9558    result += map[(bits >> 2) & 0x3F];
9559    result += map[(bits << 4) & 0x3F];
9560    result += map[64];
9561    result += map[64];
9562  }
9563
9564  return result;
9565}
9566
9567function isBinary(obj) {
9568  return Object.prototype.toString.call(obj) ===  '[object Uint8Array]';
9569}
9570
9571var binary = new type$1('tag:yaml.org,2002:binary', {
9572  kind: 'scalar',
9573  resolve: resolveYamlBinary,
9574  construct: constructYamlBinary,
9575  predicate: isBinary,
9576  represent: representYamlBinary
9577});
9578
9579var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
9580var _toString$2       = Object.prototype.toString;
9581
9582function resolveYamlOmap(data) {
9583  if (data === null) return true;
9584
9585  var objectKeys = [], index, length, pair, pairKey, pairHasKey,
9586      object = data;
9587
9588  for (index = 0, length = object.length; index < length; index += 1) {
9589    pair = object[index];
9590    pairHasKey = false;
9591
9592    if (_toString$2.call(pair) !== '[object Object]') return false;
9593
9594    for (pairKey in pair) {
9595      if (_hasOwnProperty$3.call(pair, pairKey)) {
9596        if (!pairHasKey) pairHasKey = true;
9597        else return false;
9598      }
9599    }
9600
9601    if (!pairHasKey) return false;
9602
9603    if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
9604    else return false;
9605  }
9606
9607  return true;
9608}
9609
9610function constructYamlOmap(data) {
9611  return data !== null ? data : [];
9612}
9613
9614var omap = new type$1('tag:yaml.org,2002:omap', {
9615  kind: 'sequence',
9616  resolve: resolveYamlOmap,
9617  construct: constructYamlOmap
9618});
9619
9620var _toString$1 = Object.prototype.toString;
9621
9622function resolveYamlPairs(data) {
9623  if (data === null) return true;
9624
9625  var index, length, pair, keys, result,
9626      object = data;
9627
9628  result = new Array(object.length);
9629
9630  for (index = 0, length = object.length; index < length; index += 1) {
9631    pair = object[index];
9632
9633    if (_toString$1.call(pair) !== '[object Object]') return false;
9634
9635    keys = Object.keys(pair);
9636
9637    if (keys.length !== 1) return false;
9638
9639    result[index] = [ keys[0], pair[keys[0]] ];
9640  }
9641
9642  return true;
9643}
9644
9645function constructYamlPairs(data) {
9646  if (data === null) return [];
9647
9648  var index, length, pair, keys, result,
9649      object = data;
9650
9651  result = new Array(object.length);
9652
9653  for (index = 0, length = object.length; index < length; index += 1) {
9654    pair = object[index];
9655
9656    keys = Object.keys(pair);
9657
9658    result[index] = [ keys[0], pair[keys[0]] ];
9659  }
9660
9661  return result;
9662}
9663
9664var pairs = new type$1('tag:yaml.org,2002:pairs', {
9665  kind: 'sequence',
9666  resolve: resolveYamlPairs,
9667  construct: constructYamlPairs
9668});
9669
9670var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
9671
9672function resolveYamlSet(data) {
9673  if (data === null) return true;
9674
9675  var key, object = data;
9676
9677  for (key in object) {
9678    if (_hasOwnProperty$2.call(object, key)) {
9679      if (object[key] !== null) return false;
9680    }
9681  }
9682
9683  return true;
9684}
9685
9686function constructYamlSet(data) {
9687  return data !== null ? data : {};
9688}
9689
9690var set = new type$1('tag:yaml.org,2002:set', {
9691  kind: 'mapping',
9692  resolve: resolveYamlSet,
9693  construct: constructYamlSet
9694});
9695
9696var _default$1 = core.extend({
9697  implicit: [
9698    timestamp,
9699    merge$1
9700  ],
9701  explicit: [
9702    binary,
9703    omap,
9704    pairs,
9705    set
9706  ]
9707});
9708
9709/*eslint-disable max-len,no-use-before-define*/
9710
9711
9712
9713
9714
9715
9716
9717var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
9718
9719
9720var CONTEXT_FLOW_IN   = 1;
9721var CONTEXT_FLOW_OUT  = 2;
9722var CONTEXT_BLOCK_IN  = 3;
9723var CONTEXT_BLOCK_OUT = 4;
9724
9725
9726var CHOMPING_CLIP  = 1;
9727var CHOMPING_STRIP = 2;
9728var CHOMPING_KEEP  = 3;
9729
9730
9731var PATTERN_NON_PRINTABLE         = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
9732var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
9733var PATTERN_FLOW_INDICATORS       = /[,\[\]\{\}]/;
9734var PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\-]+!)$/i;
9735var PATTERN_TAG_URI               = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
9736
9737
9738function _class(obj) { return Object.prototype.toString.call(obj); }
9739
9740function is_EOL(c) {
9741  return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
9742}
9743
9744function is_WHITE_SPACE(c) {
9745  return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
9746}
9747
9748function is_WS_OR_EOL(c) {
9749  return (c === 0x09/* Tab */) ||
9750         (c === 0x20/* Space */) ||
9751         (c === 0x0A/* LF */) ||
9752         (c === 0x0D/* CR */);
9753}
9754
9755function is_FLOW_INDICATOR(c) {
9756  return c === 0x2C/* , */ ||
9757         c === 0x5B/* [ */ ||
9758         c === 0x5D/* ] */ ||
9759         c === 0x7B/* { */ ||
9760         c === 0x7D/* } */;
9761}
9762
9763function fromHexCode(c) {
9764  var lc;
9765
9766  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
9767    return c - 0x30;
9768  }
9769
9770  /*eslint-disable no-bitwise*/
9771  lc = c | 0x20;
9772
9773  if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
9774    return lc - 0x61 + 10;
9775  }
9776
9777  return -1;
9778}
9779
9780function escapedHexLen(c) {
9781  if (c === 0x78/* x */) { return 2; }
9782  if (c === 0x75/* u */) { return 4; }
9783  if (c === 0x55/* U */) { return 8; }
9784  return 0;
9785}
9786
9787function fromDecimalCode(c) {
9788  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
9789    return c - 0x30;
9790  }
9791
9792  return -1;
9793}
9794
9795function simpleEscapeSequence(c) {
9796  /* eslint-disable indent */
9797  return (c === 0x30/* 0 */) ? '\x00' :
9798        (c === 0x61/* a */) ? '\x07' :
9799        (c === 0x62/* b */) ? '\x08' :
9800        (c === 0x74/* t */) ? '\x09' :
9801        (c === 0x09/* Tab */) ? '\x09' :
9802        (c === 0x6E/* n */) ? '\x0A' :
9803        (c === 0x76/* v */) ? '\x0B' :
9804        (c === 0x66/* f */) ? '\x0C' :
9805        (c === 0x72/* r */) ? '\x0D' :
9806        (c === 0x65/* e */) ? '\x1B' :
9807        (c === 0x20/* Space */) ? ' ' :
9808        (c === 0x22/* " */) ? '\x22' :
9809        (c === 0x2F/* / */) ? '/' :
9810        (c === 0x5C/* \ */) ? '\x5C' :
9811        (c === 0x4E/* N */) ? '\x85' :
9812        (c === 0x5F/* _ */) ? '\xA0' :
9813        (c === 0x4C/* L */) ? '\u2028' :
9814        (c === 0x50/* P */) ? '\u2029' : '';
9815}
9816
9817function charFromCodepoint(c) {
9818  if (c <= 0xFFFF) {
9819    return String.fromCharCode(c);
9820  }
9821  // Encode UTF-16 surrogate pair
9822  // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
9823  return String.fromCharCode(
9824    ((c - 0x010000) >> 10) + 0xD800,
9825    ((c - 0x010000) & 0x03FF) + 0xDC00
9826  );
9827}
9828
9829var simpleEscapeCheck = new Array(256); // integer, for fast access
9830var simpleEscapeMap = new Array(256);
9831for (var i = 0; i < 256; i++) {
9832  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
9833  simpleEscapeMap[i] = simpleEscapeSequence(i);
9834}
9835
9836
9837function State$1(input, options) {
9838  this.input = input;
9839
9840  this.filename  = options['filename']  || null;
9841  this.schema    = options['schema']    || _default$1;
9842  this.onWarning = options['onWarning'] || null;
9843  // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
9844  // if such documents have no explicit %YAML directive
9845  this.legacy    = options['legacy']    || false;
9846
9847  this.json      = options['json']      || false;
9848  this.listener  = options['listener']  || null;
9849
9850  this.implicitTypes = this.schema.compiledImplicit;
9851  this.typeMap       = this.schema.compiledTypeMap;
9852
9853  this.length     = input.length;
9854  this.position   = 0;
9855  this.line       = 0;
9856  this.lineStart  = 0;
9857  this.lineIndent = 0;
9858
9859  // position of first leading tab in the current line,
9860  // used to make sure there are no tabs in the indentation
9861  this.firstTabInLine = -1;
9862
9863  this.documents = [];
9864
9865  /*
9866  this.version;
9867  this.checkLineBreaks;
9868  this.tagMap;
9869  this.anchorMap;
9870  this.tag;
9871  this.anchor;
9872  this.kind;
9873  this.result;*/
9874
9875}
9876
9877
9878function generateError(state, message) {
9879  var mark = {
9880    name:     state.filename,
9881    buffer:   state.input.slice(0, -1), // omit trailing \0
9882    position: state.position,
9883    line:     state.line,
9884    column:   state.position - state.lineStart
9885  };
9886
9887  mark.snippet = snippet(mark);
9888
9889  return new exception(message, mark);
9890}
9891
9892function throwError$1(state, message) {
9893  throw generateError(state, message);
9894}
9895
9896function throwWarning(state, message) {
9897  if (state.onWarning) {
9898    state.onWarning.call(null, generateError(state, message));
9899  }
9900}
9901
9902
9903var directiveHandlers = {
9904
9905  YAML: function handleYamlDirective(state, name, args) {
9906
9907    var match, major, minor;
9908
9909    if (state.version !== null) {
9910      throwError$1(state, 'duplication of %YAML directive');
9911    }
9912
9913    if (args.length !== 1) {
9914      throwError$1(state, 'YAML directive accepts exactly one argument');
9915    }
9916
9917    match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
9918
9919    if (match === null) {
9920      throwError$1(state, 'ill-formed argument of the YAML directive');
9921    }
9922
9923    major = parseInt(match[1], 10);
9924    minor = parseInt(match[2], 10);
9925
9926    if (major !== 1) {
9927      throwError$1(state, 'unacceptable YAML version of the document');
9928    }
9929
9930    state.version = args[0];
9931    state.checkLineBreaks = (minor < 2);
9932
9933    if (minor !== 1 && minor !== 2) {
9934      throwWarning(state, 'unsupported YAML version of the document');
9935    }
9936  },
9937
9938  TAG: function handleTagDirective(state, name, args) {
9939
9940    var handle, prefix;
9941
9942    if (args.length !== 2) {
9943      throwError$1(state, 'TAG directive accepts exactly two arguments');
9944    }
9945
9946    handle = args[0];
9947    prefix = args[1];
9948
9949    if (!PATTERN_TAG_HANDLE.test(handle)) {
9950      throwError$1(state, 'ill-formed tag handle (first argument) of the TAG directive');
9951    }
9952
9953    if (_hasOwnProperty$1.call(state.tagMap, handle)) {
9954      throwError$1(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
9955    }
9956
9957    if (!PATTERN_TAG_URI.test(prefix)) {
9958      throwError$1(state, 'ill-formed tag prefix (second argument) of the TAG directive');
9959    }
9960
9961    try {
9962      prefix = decodeURIComponent(prefix);
9963    } catch (err) {
9964      throwError$1(state, 'tag prefix is malformed: ' + prefix);
9965    }
9966
9967    state.tagMap[handle] = prefix;
9968  }
9969};
9970
9971
9972function captureSegment(state, start, end, checkJson) {
9973  var _position, _length, _character, _result;
9974
9975  if (start < end) {
9976    _result = state.input.slice(start, end);
9977
9978    if (checkJson) {
9979      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
9980        _character = _result.charCodeAt(_position);
9981        if (!(_character === 0x09 ||
9982              (0x20 <= _character && _character <= 0x10FFFF))) {
9983          throwError$1(state, 'expected valid JSON character');
9984        }
9985      }
9986    } else if (PATTERN_NON_PRINTABLE.test(_result)) {
9987      throwError$1(state, 'the stream contains non-printable characters');
9988    }
9989
9990    state.result += _result;
9991  }
9992}
9993
9994function mergeMappings(state, destination, source, overridableKeys) {
9995  var sourceKeys, key, index, quantity;
9996
9997  if (!common$4.isObject(source)) {
9998    throwError$1(state, 'cannot merge mappings; the provided source object is unacceptable');
9999  }
10000
10001  sourceKeys = Object.keys(source);
10002
10003  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
10004    key = sourceKeys[index];
10005
10006    if (!_hasOwnProperty$1.call(destination, key)) {
10007      destination[key] = source[key];
10008      overridableKeys[key] = true;
10009    }
10010  }
10011}
10012
10013function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
10014  startLine, startLineStart, startPos) {
10015
10016  var index, quantity;
10017
10018  // The output is a plain object here, so keys can only be strings.
10019  // We need to convert keyNode to a string, but doing so can hang the process
10020  // (deeply nested arrays that explode exponentially using aliases).
10021  if (Array.isArray(keyNode)) {
10022    keyNode = Array.prototype.slice.call(keyNode);
10023
10024    for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
10025      if (Array.isArray(keyNode[index])) {
10026        throwError$1(state, 'nested arrays are not supported inside keys');
10027      }
10028
10029      if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
10030        keyNode[index] = '[object Object]';
10031      }
10032    }
10033  }
10034
10035  // Avoid code execution in load() via toString property
10036  // (still use its own toString for arrays, timestamps,
10037  // and whatever user schema extensions happen to have @@toStringTag)
10038  if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
10039    keyNode = '[object Object]';
10040  }
10041
10042
10043  keyNode = String(keyNode);
10044
10045  if (_result === null) {
10046    _result = {};
10047  }
10048
10049  if (keyTag === 'tag:yaml.org,2002:merge') {
10050    if (Array.isArray(valueNode)) {
10051      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
10052        mergeMappings(state, _result, valueNode[index], overridableKeys);
10053      }
10054    } else {
10055      mergeMappings(state, _result, valueNode, overridableKeys);
10056    }
10057  } else {
10058    if (!state.json &&
10059        !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
10060        _hasOwnProperty$1.call(_result, keyNode)) {
10061      state.line = startLine || state.line;
10062      state.lineStart = startLineStart || state.lineStart;
10063      state.position = startPos || state.position;
10064      throwError$1(state, 'duplicated mapping key');
10065    }
10066
10067    // used for this specific key only because Object.defineProperty is slow
10068    if (keyNode === '__proto__') {
10069      Object.defineProperty(_result, keyNode, {
10070        configurable: true,
10071        enumerable: true,
10072        writable: true,
10073        value: valueNode
10074      });
10075    } else {
10076      _result[keyNode] = valueNode;
10077    }
10078    delete overridableKeys[keyNode];
10079  }
10080
10081  return _result;
10082}
10083
10084function readLineBreak(state) {
10085  var ch;
10086
10087  ch = state.input.charCodeAt(state.position);
10088
10089  if (ch === 0x0A/* LF */) {
10090    state.position++;
10091  } else if (ch === 0x0D/* CR */) {
10092    state.position++;
10093    if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
10094      state.position++;
10095    }
10096  } else {
10097    throwError$1(state, 'a line break is expected');
10098  }
10099
10100  state.line += 1;
10101  state.lineStart = state.position;
10102  state.firstTabInLine = -1;
10103}
10104
10105function skipSeparationSpace(state, allowComments, checkIndent) {
10106  var lineBreaks = 0,
10107      ch = state.input.charCodeAt(state.position);
10108
10109  while (ch !== 0) {
10110    while (is_WHITE_SPACE(ch)) {
10111      if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
10112        state.firstTabInLine = state.position;
10113      }
10114      ch = state.input.charCodeAt(++state.position);
10115    }
10116
10117    if (allowComments && ch === 0x23/* # */) {
10118      do {
10119        ch = state.input.charCodeAt(++state.position);
10120      } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
10121    }
10122
10123    if (is_EOL(ch)) {
10124      readLineBreak(state);
10125
10126      ch = state.input.charCodeAt(state.position);
10127      lineBreaks++;
10128      state.lineIndent = 0;
10129
10130      while (ch === 0x20/* Space */) {
10131        state.lineIndent++;
10132        ch = state.input.charCodeAt(++state.position);
10133      }
10134    } else {
10135      break;
10136    }
10137  }
10138
10139  if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
10140    throwWarning(state, 'deficient indentation');
10141  }
10142
10143  return lineBreaks;
10144}
10145
10146function testDocumentSeparator(state) {
10147  var _position = state.position,
10148      ch;
10149
10150  ch = state.input.charCodeAt(_position);
10151
10152  // Condition state.position === state.lineStart is tested
10153  // in parent on each call, for efficiency. No needs to test here again.
10154  if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
10155      ch === state.input.charCodeAt(_position + 1) &&
10156      ch === state.input.charCodeAt(_position + 2)) {
10157
10158    _position += 3;
10159
10160    ch = state.input.charCodeAt(_position);
10161
10162    if (ch === 0 || is_WS_OR_EOL(ch)) {
10163      return true;
10164    }
10165  }
10166
10167  return false;
10168}
10169
10170function writeFoldedLines(state, count) {
10171  if (count === 1) {
10172    state.result += ' ';
10173  } else if (count > 1) {
10174    state.result += common$4.repeat('\n', count - 1);
10175  }
10176}
10177
10178
10179function readPlainScalar(state, nodeIndent, withinFlowCollection) {
10180  var preceding,
10181      following,
10182      captureStart,
10183      captureEnd,
10184      hasPendingContent,
10185      _line,
10186      _lineStart,
10187      _lineIndent,
10188      _kind = state.kind,
10189      _result = state.result,
10190      ch;
10191
10192  ch = state.input.charCodeAt(state.position);
10193
10194  if (is_WS_OR_EOL(ch)      ||
10195      is_FLOW_INDICATOR(ch) ||
10196      ch === 0x23/* # */    ||
10197      ch === 0x26/* & */    ||
10198      ch === 0x2A/* * */    ||
10199      ch === 0x21/* ! */    ||
10200      ch === 0x7C/* | */    ||
10201      ch === 0x3E/* > */    ||
10202      ch === 0x27/* ' */    ||
10203      ch === 0x22/* " */    ||
10204      ch === 0x25/* % */    ||
10205      ch === 0x40/* @ */    ||
10206      ch === 0x60/* ` */) {
10207    return false;
10208  }
10209
10210  if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
10211    following = state.input.charCodeAt(state.position + 1);
10212
10213    if (is_WS_OR_EOL(following) ||
10214        withinFlowCollection && is_FLOW_INDICATOR(following)) {
10215      return false;
10216    }
10217  }
10218
10219  state.kind = 'scalar';
10220  state.result = '';
10221  captureStart = captureEnd = state.position;
10222  hasPendingContent = false;
10223
10224  while (ch !== 0) {
10225    if (ch === 0x3A/* : */) {
10226      following = state.input.charCodeAt(state.position + 1);
10227
10228      if (is_WS_OR_EOL(following) ||
10229          withinFlowCollection && is_FLOW_INDICATOR(following)) {
10230        break;
10231      }
10232
10233    } else if (ch === 0x23/* # */) {
10234      preceding = state.input.charCodeAt(state.position - 1);
10235
10236      if (is_WS_OR_EOL(preceding)) {
10237        break;
10238      }
10239
10240    } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
10241               withinFlowCollection && is_FLOW_INDICATOR(ch)) {
10242      break;
10243
10244    } else if (is_EOL(ch)) {
10245      _line = state.line;
10246      _lineStart = state.lineStart;
10247      _lineIndent = state.lineIndent;
10248      skipSeparationSpace(state, false, -1);
10249
10250      if (state.lineIndent >= nodeIndent) {
10251        hasPendingContent = true;
10252        ch = state.input.charCodeAt(state.position);
10253        continue;
10254      } else {
10255        state.position = captureEnd;
10256        state.line = _line;
10257        state.lineStart = _lineStart;
10258        state.lineIndent = _lineIndent;
10259        break;
10260      }
10261    }
10262
10263    if (hasPendingContent) {
10264      captureSegment(state, captureStart, captureEnd, false);
10265      writeFoldedLines(state, state.line - _line);
10266      captureStart = captureEnd = state.position;
10267      hasPendingContent = false;
10268    }
10269
10270    if (!is_WHITE_SPACE(ch)) {
10271      captureEnd = state.position + 1;
10272    }
10273
10274    ch = state.input.charCodeAt(++state.position);
10275  }
10276
10277  captureSegment(state, captureStart, captureEnd, false);
10278
10279  if (state.result) {
10280    return true;
10281  }
10282
10283  state.kind = _kind;
10284  state.result = _result;
10285  return false;
10286}
10287
10288function readSingleQuotedScalar(state, nodeIndent) {
10289  var ch,
10290      captureStart, captureEnd;
10291
10292  ch = state.input.charCodeAt(state.position);
10293
10294  if (ch !== 0x27/* ' */) {
10295    return false;
10296  }
10297
10298  state.kind = 'scalar';
10299  state.result = '';
10300  state.position++;
10301  captureStart = captureEnd = state.position;
10302
10303  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
10304    if (ch === 0x27/* ' */) {
10305      captureSegment(state, captureStart, state.position, true);
10306      ch = state.input.charCodeAt(++state.position);
10307
10308      if (ch === 0x27/* ' */) {
10309        captureStart = state.position;
10310        state.position++;
10311        captureEnd = state.position;
10312      } else {
10313        return true;
10314      }
10315
10316    } else if (is_EOL(ch)) {
10317      captureSegment(state, captureStart, captureEnd, true);
10318      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
10319      captureStart = captureEnd = state.position;
10320
10321    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
10322      throwError$1(state, 'unexpected end of the document within a single quoted scalar');
10323
10324    } else {
10325      state.position++;
10326      captureEnd = state.position;
10327    }
10328  }
10329
10330  throwError$1(state, 'unexpected end of the stream within a single quoted scalar');
10331}
10332
10333function readDoubleQuotedScalar(state, nodeIndent) {
10334  var captureStart,
10335      captureEnd,
10336      hexLength,
10337      hexResult,
10338      tmp,
10339      ch;
10340
10341  ch = state.input.charCodeAt(state.position);
10342
10343  if (ch !== 0x22/* " */) {
10344    return false;
10345  }
10346
10347  state.kind = 'scalar';
10348  state.result = '';
10349  state.position++;
10350  captureStart = captureEnd = state.position;
10351
10352  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
10353    if (ch === 0x22/* " */) {
10354      captureSegment(state, captureStart, state.position, true);
10355      state.position++;
10356      return true;
10357
10358    } else if (ch === 0x5C/* \ */) {
10359      captureSegment(state, captureStart, state.position, true);
10360      ch = state.input.charCodeAt(++state.position);
10361
10362      if (is_EOL(ch)) {
10363        skipSeparationSpace(state, false, nodeIndent);
10364
10365        // TODO: rework to inline fn with no type cast?
10366      } else if (ch < 256 && simpleEscapeCheck[ch]) {
10367        state.result += simpleEscapeMap[ch];
10368        state.position++;
10369
10370      } else if ((tmp = escapedHexLen(ch)) > 0) {
10371        hexLength = tmp;
10372        hexResult = 0;
10373
10374        for (; hexLength > 0; hexLength--) {
10375          ch = state.input.charCodeAt(++state.position);
10376
10377          if ((tmp = fromHexCode(ch)) >= 0) {
10378            hexResult = (hexResult << 4) + tmp;
10379
10380          } else {
10381            throwError$1(state, 'expected hexadecimal character');
10382          }
10383        }
10384
10385        state.result += charFromCodepoint(hexResult);
10386
10387        state.position++;
10388
10389      } else {
10390        throwError$1(state, 'unknown escape sequence');
10391      }
10392
10393      captureStart = captureEnd = state.position;
10394
10395    } else if (is_EOL(ch)) {
10396      captureSegment(state, captureStart, captureEnd, true);
10397      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
10398      captureStart = captureEnd = state.position;
10399
10400    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
10401      throwError$1(state, 'unexpected end of the document within a double quoted scalar');
10402
10403    } else {
10404      state.position++;
10405      captureEnd = state.position;
10406    }
10407  }
10408
10409  throwError$1(state, 'unexpected end of the stream within a double quoted scalar');
10410}
10411
10412function readFlowCollection(state, nodeIndent) {
10413  var readNext = true,
10414      _line,
10415      _lineStart,
10416      _pos,
10417      _tag     = state.tag,
10418      _result,
10419      _anchor  = state.anchor,
10420      following,
10421      terminator,
10422      isPair,
10423      isExplicitPair,
10424      isMapping,
10425      overridableKeys = Object.create(null),
10426      keyNode,
10427      keyTag,
10428      valueNode,
10429      ch;
10430
10431  ch = state.input.charCodeAt(state.position);
10432
10433  if (ch === 0x5B/* [ */) {
10434    terminator = 0x5D;/* ] */
10435    isMapping = false;
10436    _result = [];
10437  } else if (ch === 0x7B/* { */) {
10438    terminator = 0x7D;/* } */
10439    isMapping = true;
10440    _result = {};
10441  } else {
10442    return false;
10443  }
10444
10445  if (state.anchor !== null) {
10446    state.anchorMap[state.anchor] = _result;
10447  }
10448
10449  ch = state.input.charCodeAt(++state.position);
10450
10451  while (ch !== 0) {
10452    skipSeparationSpace(state, true, nodeIndent);
10453
10454    ch = state.input.charCodeAt(state.position);
10455
10456    if (ch === terminator) {
10457      state.position++;
10458      state.tag = _tag;
10459      state.anchor = _anchor;
10460      state.kind = isMapping ? 'mapping' : 'sequence';
10461      state.result = _result;
10462      return true;
10463    } else if (!readNext) {
10464      throwError$1(state, 'missed comma between flow collection entries');
10465    } else if (ch === 0x2C/* , */) {
10466      // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
10467      throwError$1(state, "expected the node content, but found ','");
10468    }
10469
10470    keyTag = keyNode = valueNode = null;
10471    isPair = isExplicitPair = false;
10472
10473    if (ch === 0x3F/* ? */) {
10474      following = state.input.charCodeAt(state.position + 1);
10475
10476      if (is_WS_OR_EOL(following)) {
10477        isPair = isExplicitPair = true;
10478        state.position++;
10479        skipSeparationSpace(state, true, nodeIndent);
10480      }
10481    }
10482
10483    _line = state.line; // Save the current line.
10484    _lineStart = state.lineStart;
10485    _pos = state.position;
10486    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
10487    keyTag = state.tag;
10488    keyNode = state.result;
10489    skipSeparationSpace(state, true, nodeIndent);
10490
10491    ch = state.input.charCodeAt(state.position);
10492
10493    if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
10494      isPair = true;
10495      ch = state.input.charCodeAt(++state.position);
10496      skipSeparationSpace(state, true, nodeIndent);
10497      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
10498      valueNode = state.result;
10499    }
10500
10501    if (isMapping) {
10502      storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
10503    } else if (isPair) {
10504      _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
10505    } else {
10506      _result.push(keyNode);
10507    }
10508
10509    skipSeparationSpace(state, true, nodeIndent);
10510
10511    ch = state.input.charCodeAt(state.position);
10512
10513    if (ch === 0x2C/* , */) {
10514      readNext = true;
10515      ch = state.input.charCodeAt(++state.position);
10516    } else {
10517      readNext = false;
10518    }
10519  }
10520
10521  throwError$1(state, 'unexpected end of the stream within a flow collection');
10522}
10523
10524function readBlockScalar(state, nodeIndent) {
10525  var captureStart,
10526      folding,
10527      chomping       = CHOMPING_CLIP,
10528      didReadContent = false,
10529      detectedIndent = false,
10530      textIndent     = nodeIndent,
10531      emptyLines     = 0,
10532      atMoreIndented = false,
10533      tmp,
10534      ch;
10535
10536  ch = state.input.charCodeAt(state.position);
10537
10538  if (ch === 0x7C/* | */) {
10539    folding = false;
10540  } else if (ch === 0x3E/* > */) {
10541    folding = true;
10542  } else {
10543    return false;
10544  }
10545
10546  state.kind = 'scalar';
10547  state.result = '';
10548
10549  while (ch !== 0) {
10550    ch = state.input.charCodeAt(++state.position);
10551
10552    if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
10553      if (CHOMPING_CLIP === chomping) {
10554        chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
10555      } else {
10556        throwError$1(state, 'repeat of a chomping mode identifier');
10557      }
10558
10559    } else if ((tmp = fromDecimalCode(ch)) >= 0) {
10560      if (tmp === 0) {
10561        throwError$1(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
10562      } else if (!detectedIndent) {
10563        textIndent = nodeIndent + tmp - 1;
10564        detectedIndent = true;
10565      } else {
10566        throwError$1(state, 'repeat of an indentation width identifier');
10567      }
10568
10569    } else {
10570      break;
10571    }
10572  }
10573
10574  if (is_WHITE_SPACE(ch)) {
10575    do { ch = state.input.charCodeAt(++state.position); }
10576    while (is_WHITE_SPACE(ch));
10577
10578    if (ch === 0x23/* # */) {
10579      do { ch = state.input.charCodeAt(++state.position); }
10580      while (!is_EOL(ch) && (ch !== 0));
10581    }
10582  }
10583
10584  while (ch !== 0) {
10585    readLineBreak(state);
10586    state.lineIndent = 0;
10587
10588    ch = state.input.charCodeAt(state.position);
10589
10590    while ((!detectedIndent || state.lineIndent < textIndent) &&
10591           (ch === 0x20/* Space */)) {
10592      state.lineIndent++;
10593      ch = state.input.charCodeAt(++state.position);
10594    }
10595
10596    if (!detectedIndent && state.lineIndent > textIndent) {
10597      textIndent = state.lineIndent;
10598    }
10599
10600    if (is_EOL(ch)) {
10601      emptyLines++;
10602      continue;
10603    }
10604
10605    // End of the scalar.
10606    if (state.lineIndent < textIndent) {
10607
10608      // Perform the chomping.
10609      if (chomping === CHOMPING_KEEP) {
10610        state.result += common$4.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
10611      } else if (chomping === CHOMPING_CLIP) {
10612        if (didReadContent) { // i.e. only if the scalar is not empty.
10613          state.result += '\n';
10614        }
10615      }
10616
10617      // Break this `while` cycle and go to the funciton's epilogue.
10618      break;
10619    }
10620
10621    // Folded style: use fancy rules to handle line breaks.
10622    if (folding) {
10623
10624      // Lines starting with white space characters (more-indented lines) are not folded.
10625      if (is_WHITE_SPACE(ch)) {
10626        atMoreIndented = true;
10627        // except for the first content line (cf. Example 8.1)
10628        state.result += common$4.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
10629
10630      // End of more-indented block.
10631      } else if (atMoreIndented) {
10632        atMoreIndented = false;
10633        state.result += common$4.repeat('\n', emptyLines + 1);
10634
10635      // Just one line break - perceive as the same line.
10636      } else if (emptyLines === 0) {
10637        if (didReadContent) { // i.e. only if we have already read some scalar content.
10638          state.result += ' ';
10639        }
10640
10641      // Several line breaks - perceive as different lines.
10642      } else {
10643        state.result += common$4.repeat('\n', emptyLines);
10644      }
10645
10646    // Literal style: just add exact number of line breaks between content lines.
10647    } else {
10648      // Keep all line breaks except the header line break.
10649      state.result += common$4.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
10650    }
10651
10652    didReadContent = true;
10653    detectedIndent = true;
10654    emptyLines = 0;
10655    captureStart = state.position;
10656
10657    while (!is_EOL(ch) && (ch !== 0)) {
10658      ch = state.input.charCodeAt(++state.position);
10659    }
10660
10661    captureSegment(state, captureStart, state.position, false);
10662  }
10663
10664  return true;
10665}
10666
10667function readBlockSequence(state, nodeIndent) {
10668  var _line,
10669      _tag      = state.tag,
10670      _anchor   = state.anchor,
10671      _result   = [],
10672      following,
10673      detected  = false,
10674      ch;
10675
10676  // there is a leading tab before this token, so it can't be a block sequence/mapping;
10677  // it can still be flow sequence/mapping or a scalar
10678  if (state.firstTabInLine !== -1) return false;
10679
10680  if (state.anchor !== null) {
10681    state.anchorMap[state.anchor] = _result;
10682  }
10683
10684  ch = state.input.charCodeAt(state.position);
10685
10686  while (ch !== 0) {
10687    if (state.firstTabInLine !== -1) {
10688      state.position = state.firstTabInLine;
10689      throwError$1(state, 'tab characters must not be used in indentation');
10690    }
10691
10692    if (ch !== 0x2D/* - */) {
10693      break;
10694    }
10695
10696    following = state.input.charCodeAt(state.position + 1);
10697
10698    if (!is_WS_OR_EOL(following)) {
10699      break;
10700    }
10701
10702    detected = true;
10703    state.position++;
10704
10705    if (skipSeparationSpace(state, true, -1)) {
10706      if (state.lineIndent <= nodeIndent) {
10707        _result.push(null);
10708        ch = state.input.charCodeAt(state.position);
10709        continue;
10710      }
10711    }
10712
10713    _line = state.line;
10714    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
10715    _result.push(state.result);
10716    skipSeparationSpace(state, true, -1);
10717
10718    ch = state.input.charCodeAt(state.position);
10719
10720    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
10721      throwError$1(state, 'bad indentation of a sequence entry');
10722    } else if (state.lineIndent < nodeIndent) {
10723      break;
10724    }
10725  }
10726
10727  if (detected) {
10728    state.tag = _tag;
10729    state.anchor = _anchor;
10730    state.kind = 'sequence';
10731    state.result = _result;
10732    return true;
10733  }
10734  return false;
10735}
10736
10737function readBlockMapping(state, nodeIndent, flowIndent) {
10738  var following,
10739      allowCompact,
10740      _line,
10741      _keyLine,
10742      _keyLineStart,
10743      _keyPos,
10744      _tag          = state.tag,
10745      _anchor       = state.anchor,
10746      _result       = {},
10747      overridableKeys = Object.create(null),
10748      keyTag        = null,
10749      keyNode       = null,
10750      valueNode     = null,
10751      atExplicitKey = false,
10752      detected      = false,
10753      ch;
10754
10755  // there is a leading tab before this token, so it can't be a block sequence/mapping;
10756  // it can still be flow sequence/mapping or a scalar
10757  if (state.firstTabInLine !== -1) return false;
10758
10759  if (state.anchor !== null) {
10760    state.anchorMap[state.anchor] = _result;
10761  }
10762
10763  ch = state.input.charCodeAt(state.position);
10764
10765  while (ch !== 0) {
10766    if (!atExplicitKey && state.firstTabInLine !== -1) {
10767      state.position = state.firstTabInLine;
10768      throwError$1(state, 'tab characters must not be used in indentation');
10769    }
10770
10771    following = state.input.charCodeAt(state.position + 1);
10772    _line = state.line; // Save the current line.
10773
10774    //
10775    // Explicit notation case. There are two separate blocks:
10776    // first for the key (denoted by "?") and second for the value (denoted by ":")
10777    //
10778    if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
10779
10780      if (ch === 0x3F/* ? */) {
10781        if (atExplicitKey) {
10782          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
10783          keyTag = keyNode = valueNode = null;
10784        }
10785
10786        detected = true;
10787        atExplicitKey = true;
10788        allowCompact = true;
10789
10790      } else if (atExplicitKey) {
10791        // i.e. 0x3A/* : */ === character after the explicit key.
10792        atExplicitKey = false;
10793        allowCompact = true;
10794
10795      } else {
10796        throwError$1(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
10797      }
10798
10799      state.position += 1;
10800      ch = following;
10801
10802    //
10803    // Implicit notation case. Flow-style node as the key first, then ":", and the value.
10804    //
10805    } else {
10806      _keyLine = state.line;
10807      _keyLineStart = state.lineStart;
10808      _keyPos = state.position;
10809
10810      if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
10811        // Neither implicit nor explicit notation.
10812        // Reading is done. Go to the epilogue.
10813        break;
10814      }
10815
10816      if (state.line === _line) {
10817        ch = state.input.charCodeAt(state.position);
10818
10819        while (is_WHITE_SPACE(ch)) {
10820          ch = state.input.charCodeAt(++state.position);
10821        }
10822
10823        if (ch === 0x3A/* : */) {
10824          ch = state.input.charCodeAt(++state.position);
10825
10826          if (!is_WS_OR_EOL(ch)) {
10827            throwError$1(state, 'a whitespace character is expected after the key-value separator within a block mapping');
10828          }
10829
10830          if (atExplicitKey) {
10831            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
10832            keyTag = keyNode = valueNode = null;
10833          }
10834
10835          detected = true;
10836          atExplicitKey = false;
10837          allowCompact = false;
10838          keyTag = state.tag;
10839          keyNode = state.result;
10840
10841        } else if (detected) {
10842          throwError$1(state, 'can not read an implicit mapping pair; a colon is missed');
10843
10844        } else {
10845          state.tag = _tag;
10846          state.anchor = _anchor;
10847          return true; // Keep the result of `composeNode`.
10848        }
10849
10850      } else if (detected) {
10851        throwError$1(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
10852
10853      } else {
10854        state.tag = _tag;
10855        state.anchor = _anchor;
10856        return true; // Keep the result of `composeNode`.
10857      }
10858    }
10859
10860    //
10861    // Common reading code for both explicit and implicit notations.
10862    //
10863    if (state.line === _line || state.lineIndent > nodeIndent) {
10864      if (atExplicitKey) {
10865        _keyLine = state.line;
10866        _keyLineStart = state.lineStart;
10867        _keyPos = state.position;
10868      }
10869
10870      if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
10871        if (atExplicitKey) {
10872          keyNode = state.result;
10873        } else {
10874          valueNode = state.result;
10875        }
10876      }
10877
10878      if (!atExplicitKey) {
10879        storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
10880        keyTag = keyNode = valueNode = null;
10881      }
10882
10883      skipSeparationSpace(state, true, -1);
10884      ch = state.input.charCodeAt(state.position);
10885    }
10886
10887    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
10888      throwError$1(state, 'bad indentation of a mapping entry');
10889    } else if (state.lineIndent < nodeIndent) {
10890      break;
10891    }
10892  }
10893
10894  //
10895  // Epilogue.
10896  //
10897
10898  // Special case: last mapping's node contains only the key in explicit notation.
10899  if (atExplicitKey) {
10900    storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
10901  }
10902
10903  // Expose the resulting mapping.
10904  if (detected) {
10905    state.tag = _tag;
10906    state.anchor = _anchor;
10907    state.kind = 'mapping';
10908    state.result = _result;
10909  }
10910
10911  return detected;
10912}
10913
10914function readTagProperty(state) {
10915  var _position,
10916      isVerbatim = false,
10917      isNamed    = false,
10918      tagHandle,
10919      tagName,
10920      ch;
10921
10922  ch = state.input.charCodeAt(state.position);
10923
10924  if (ch !== 0x21/* ! */) return false;
10925
10926  if (state.tag !== null) {
10927    throwError$1(state, 'duplication of a tag property');
10928  }
10929
10930  ch = state.input.charCodeAt(++state.position);
10931
10932  if (ch === 0x3C/* < */) {
10933    isVerbatim = true;
10934    ch = state.input.charCodeAt(++state.position);
10935
10936  } else if (ch === 0x21/* ! */) {
10937    isNamed = true;
10938    tagHandle = '!!';
10939    ch = state.input.charCodeAt(++state.position);
10940
10941  } else {
10942    tagHandle = '!';
10943  }
10944
10945  _position = state.position;
10946
10947  if (isVerbatim) {
10948    do { ch = state.input.charCodeAt(++state.position); }
10949    while (ch !== 0 && ch !== 0x3E/* > */);
10950
10951    if (state.position < state.length) {
10952      tagName = state.input.slice(_position, state.position);
10953      ch = state.input.charCodeAt(++state.position);
10954    } else {
10955      throwError$1(state, 'unexpected end of the stream within a verbatim tag');
10956    }
10957  } else {
10958    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
10959
10960      if (ch === 0x21/* ! */) {
10961        if (!isNamed) {
10962          tagHandle = state.input.slice(_position - 1, state.position + 1);
10963
10964          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
10965            throwError$1(state, 'named tag handle cannot contain such characters');
10966          }
10967
10968          isNamed = true;
10969          _position = state.position + 1;
10970        } else {
10971          throwError$1(state, 'tag suffix cannot contain exclamation marks');
10972        }
10973      }
10974
10975      ch = state.input.charCodeAt(++state.position);
10976    }
10977
10978    tagName = state.input.slice(_position, state.position);
10979
10980    if (PATTERN_FLOW_INDICATORS.test(tagName)) {
10981      throwError$1(state, 'tag suffix cannot contain flow indicator characters');
10982    }
10983  }
10984
10985  if (tagName && !PATTERN_TAG_URI.test(tagName)) {
10986    throwError$1(state, 'tag name cannot contain such characters: ' + tagName);
10987  }
10988
10989  try {
10990    tagName = decodeURIComponent(tagName);
10991  } catch (err) {
10992    throwError$1(state, 'tag name is malformed: ' + tagName);
10993  }
10994
10995  if (isVerbatim) {
10996    state.tag = tagName;
10997
10998  } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
10999    state.tag = state.tagMap[tagHandle] + tagName;
11000
11001  } else if (tagHandle === '!') {
11002    state.tag = '!' + tagName;
11003
11004  } else if (tagHandle === '!!') {
11005    state.tag = 'tag:yaml.org,2002:' + tagName;
11006
11007  } else {
11008    throwError$1(state, 'undeclared tag handle "' + tagHandle + '"');
11009  }
11010
11011  return true;
11012}
11013
11014function readAnchorProperty(state) {
11015  var _position,
11016      ch;
11017
11018  ch = state.input.charCodeAt(state.position);
11019
11020  if (ch !== 0x26/* & */) return false;
11021
11022  if (state.anchor !== null) {
11023    throwError$1(state, 'duplication of an anchor property');
11024  }
11025
11026  ch = state.input.charCodeAt(++state.position);
11027  _position = state.position;
11028
11029  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
11030    ch = state.input.charCodeAt(++state.position);
11031  }
11032
11033  if (state.position === _position) {
11034    throwError$1(state, 'name of an anchor node must contain at least one character');
11035  }
11036
11037  state.anchor = state.input.slice(_position, state.position);
11038  return true;
11039}
11040
11041function readAlias(state) {
11042  var _position, alias,
11043      ch;
11044
11045  ch = state.input.charCodeAt(state.position);
11046
11047  if (ch !== 0x2A/* * */) return false;
11048
11049  ch = state.input.charCodeAt(++state.position);
11050  _position = state.position;
11051
11052  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
11053    ch = state.input.charCodeAt(++state.position);
11054  }
11055
11056  if (state.position === _position) {
11057    throwError$1(state, 'name of an alias node must contain at least one character');
11058  }
11059
11060  alias = state.input.slice(_position, state.position);
11061
11062  if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
11063    throwError$1(state, 'unidentified alias "' + alias + '"');
11064  }
11065
11066  state.result = state.anchorMap[alias];
11067  skipSeparationSpace(state, true, -1);
11068  return true;
11069}
11070
11071function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
11072  var allowBlockStyles,
11073      allowBlockScalars,
11074      allowBlockCollections,
11075      indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
11076      atNewLine  = false,
11077      hasContent = false,
11078      typeIndex,
11079      typeQuantity,
11080      typeList,
11081      type,
11082      flowIndent,
11083      blockIndent;
11084
11085  if (state.listener !== null) {
11086    state.listener('open', state);
11087  }
11088
11089  state.tag    = null;
11090  state.anchor = null;
11091  state.kind   = null;
11092  state.result = null;
11093
11094  allowBlockStyles = allowBlockScalars = allowBlockCollections =
11095    CONTEXT_BLOCK_OUT === nodeContext ||
11096    CONTEXT_BLOCK_IN  === nodeContext;
11097
11098  if (allowToSeek) {
11099    if (skipSeparationSpace(state, true, -1)) {
11100      atNewLine = true;
11101
11102      if (state.lineIndent > parentIndent) {
11103        indentStatus = 1;
11104      } else if (state.lineIndent === parentIndent) {
11105        indentStatus = 0;
11106      } else if (state.lineIndent < parentIndent) {
11107        indentStatus = -1;
11108      }
11109    }
11110  }
11111
11112  if (indentStatus === 1) {
11113    while (readTagProperty(state) || readAnchorProperty(state)) {
11114      if (skipSeparationSpace(state, true, -1)) {
11115        atNewLine = true;
11116        allowBlockCollections = allowBlockStyles;
11117
11118        if (state.lineIndent > parentIndent) {
11119          indentStatus = 1;
11120        } else if (state.lineIndent === parentIndent) {
11121          indentStatus = 0;
11122        } else if (state.lineIndent < parentIndent) {
11123          indentStatus = -1;
11124        }
11125      } else {
11126        allowBlockCollections = false;
11127      }
11128    }
11129  }
11130
11131  if (allowBlockCollections) {
11132    allowBlockCollections = atNewLine || allowCompact;
11133  }
11134
11135  if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
11136    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
11137      flowIndent = parentIndent;
11138    } else {
11139      flowIndent = parentIndent + 1;
11140    }
11141
11142    blockIndent = state.position - state.lineStart;
11143
11144    if (indentStatus === 1) {
11145      if (allowBlockCollections &&
11146          (readBlockSequence(state, blockIndent) ||
11147           readBlockMapping(state, blockIndent, flowIndent)) ||
11148          readFlowCollection(state, flowIndent)) {
11149        hasContent = true;
11150      } else {
11151        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
11152            readSingleQuotedScalar(state, flowIndent) ||
11153            readDoubleQuotedScalar(state, flowIndent)) {
11154          hasContent = true;
11155
11156        } else if (readAlias(state)) {
11157          hasContent = true;
11158
11159          if (state.tag !== null || state.anchor !== null) {
11160            throwError$1(state, 'alias node should not have any properties');
11161          }
11162
11163        } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
11164          hasContent = true;
11165
11166          if (state.tag === null) {
11167            state.tag = '?';
11168          }
11169        }
11170
11171        if (state.anchor !== null) {
11172          state.anchorMap[state.anchor] = state.result;
11173        }
11174      }
11175    } else if (indentStatus === 0) {
11176      // Special case: block sequences are allowed to have same indentation level as the parent.
11177      // http://www.yaml.org/spec/1.2/spec.html#id2799784
11178      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
11179    }
11180  }
11181
11182  if (state.tag === null) {
11183    if (state.anchor !== null) {
11184      state.anchorMap[state.anchor] = state.result;
11185    }
11186
11187  } else if (state.tag === '?') {
11188    // Implicit resolving is not allowed for non-scalar types, and '?'
11189    // non-specific tag is only automatically assigned to plain scalars.
11190    //
11191    // We only need to check kind conformity in case user explicitly assigns '?'
11192    // tag, for example like this: "!<?> [0]"
11193    //
11194    if (state.result !== null && state.kind !== 'scalar') {
11195      throwError$1(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
11196    }
11197
11198    for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
11199      type = state.implicitTypes[typeIndex];
11200
11201      if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
11202        state.result = type.construct(state.result);
11203        state.tag = type.tag;
11204        if (state.anchor !== null) {
11205          state.anchorMap[state.anchor] = state.result;
11206        }
11207        break;
11208      }
11209    }
11210  } else if (state.tag !== '!') {
11211    if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
11212      type = state.typeMap[state.kind || 'fallback'][state.tag];
11213    } else {
11214      // looking for multi type
11215      type = null;
11216      typeList = state.typeMap.multi[state.kind || 'fallback'];
11217
11218      for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
11219        if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
11220          type = typeList[typeIndex];
11221          break;
11222        }
11223      }
11224    }
11225
11226    if (!type) {
11227      throwError$1(state, 'unknown tag !<' + state.tag + '>');
11228    }
11229
11230    if (state.result !== null && type.kind !== state.kind) {
11231      throwError$1(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
11232    }
11233
11234    if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
11235      throwError$1(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
11236    } else {
11237      state.result = type.construct(state.result, state.tag);
11238      if (state.anchor !== null) {
11239        state.anchorMap[state.anchor] = state.result;
11240      }
11241    }
11242  }
11243
11244  if (state.listener !== null) {
11245    state.listener('close', state);
11246  }
11247  return state.tag !== null ||  state.anchor !== null || hasContent;
11248}
11249
11250function readDocument(state) {
11251  var documentStart = state.position,
11252      _position,
11253      directiveName,
11254      directiveArgs,
11255      hasDirectives = false,
11256      ch;
11257
11258  state.version = null;
11259  state.checkLineBreaks = state.legacy;
11260  state.tagMap = Object.create(null);
11261  state.anchorMap = Object.create(null);
11262
11263  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
11264    skipSeparationSpace(state, true, -1);
11265
11266    ch = state.input.charCodeAt(state.position);
11267
11268    if (state.lineIndent > 0 || ch !== 0x25/* % */) {
11269      break;
11270    }
11271
11272    hasDirectives = true;
11273    ch = state.input.charCodeAt(++state.position);
11274    _position = state.position;
11275
11276    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
11277      ch = state.input.charCodeAt(++state.position);
11278    }
11279
11280    directiveName = state.input.slice(_position, state.position);
11281    directiveArgs = [];
11282
11283    if (directiveName.length < 1) {
11284      throwError$1(state, 'directive name must not be less than one character in length');
11285    }
11286
11287    while (ch !== 0) {
11288      while (is_WHITE_SPACE(ch)) {
11289        ch = state.input.charCodeAt(++state.position);
11290      }
11291
11292      if (ch === 0x23/* # */) {
11293        do { ch = state.input.charCodeAt(++state.position); }
11294        while (ch !== 0 && !is_EOL(ch));
11295        break;
11296      }
11297
11298      if (is_EOL(ch)) break;
11299
11300      _position = state.position;
11301
11302      while (ch !== 0 && !is_WS_OR_EOL(ch)) {
11303        ch = state.input.charCodeAt(++state.position);
11304      }
11305
11306      directiveArgs.push(state.input.slice(_position, state.position));
11307    }
11308
11309    if (ch !== 0) readLineBreak(state);
11310
11311    if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
11312      directiveHandlers[directiveName](state, directiveName, directiveArgs);
11313    } else {
11314      throwWarning(state, 'unknown document directive "' + directiveName + '"');
11315    }
11316  }
11317
11318  skipSeparationSpace(state, true, -1);
11319
11320  if (state.lineIndent === 0 &&
11321      state.input.charCodeAt(state.position)     === 0x2D/* - */ &&
11322      state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
11323      state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
11324    state.position += 3;
11325    skipSeparationSpace(state, true, -1);
11326
11327  } else if (hasDirectives) {
11328    throwError$1(state, 'directives end mark is expected');
11329  }
11330
11331  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
11332  skipSeparationSpace(state, true, -1);
11333
11334  if (state.checkLineBreaks &&
11335      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
11336    throwWarning(state, 'non-ASCII line breaks are interpreted as content');
11337  }
11338
11339  state.documents.push(state.result);
11340
11341  if (state.position === state.lineStart && testDocumentSeparator(state)) {
11342
11343    if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
11344      state.position += 3;
11345      skipSeparationSpace(state, true, -1);
11346    }
11347    return;
11348  }
11349
11350  if (state.position < (state.length - 1)) {
11351    throwError$1(state, 'end of the stream or a document separator is expected');
11352  } else {
11353    return;
11354  }
11355}
11356
11357
11358function loadDocuments(input, options) {
11359  input = String(input);
11360  options = options || {};
11361
11362  if (input.length !== 0) {
11363
11364    // Add tailing `\n` if not exists
11365    if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
11366        input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
11367      input += '\n';
11368    }
11369
11370    // Strip BOM
11371    if (input.charCodeAt(0) === 0xFEFF) {
11372      input = input.slice(1);
11373    }
11374  }
11375
11376  var state = new State$1(input, options);
11377
11378  var nullpos = input.indexOf('\0');
11379
11380  if (nullpos !== -1) {
11381    state.position = nullpos;
11382    throwError$1(state, 'null byte is not allowed in input');
11383  }
11384
11385  // Use 0 as string terminator. That significantly simplifies bounds check.
11386  state.input += '\0';
11387
11388  while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
11389    state.lineIndent += 1;
11390    state.position += 1;
11391  }
11392
11393  while (state.position < (state.length - 1)) {
11394    readDocument(state);
11395  }
11396
11397  return state.documents;
11398}
11399
11400
11401function loadAll$1(input, iterator, options) {
11402  if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
11403    options = iterator;
11404    iterator = null;
11405  }
11406
11407  var documents = loadDocuments(input, options);
11408
11409  if (typeof iterator !== 'function') {
11410    return documents;
11411  }
11412
11413  for (var index = 0, length = documents.length; index < length; index += 1) {
11414    iterator(documents[index]);
11415  }
11416}
11417
11418
11419function load$1(input, options) {
11420  var documents = loadDocuments(input, options);
11421
11422  if (documents.length === 0) {
11423    /*eslint-disable no-undefined*/
11424    return undefined;
11425  } else if (documents.length === 1) {
11426    return documents[0];
11427  }
11428  throw new exception('expected a single document in the stream, but found more');
11429}
11430
11431
11432var loadAll_1 = loadAll$1;
11433var load_1    = load$1;
11434
11435var loader = {
11436	loadAll: loadAll_1,
11437	load: load_1
11438};
11439
11440/*eslint-disable no-use-before-define*/
11441
11442
11443
11444
11445
11446var _toString       = Object.prototype.toString;
11447var _hasOwnProperty = Object.prototype.hasOwnProperty;
11448
11449var CHAR_BOM                  = 0xFEFF;
11450var CHAR_TAB                  = 0x09; /* Tab */
11451var CHAR_LINE_FEED            = 0x0A; /* LF */
11452var CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */
11453var CHAR_SPACE                = 0x20; /* Space */
11454var CHAR_EXCLAMATION          = 0x21; /* ! */
11455var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
11456var CHAR_SHARP                = 0x23; /* # */
11457var CHAR_PERCENT              = 0x25; /* % */
11458var CHAR_AMPERSAND            = 0x26; /* & */
11459var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
11460var CHAR_ASTERISK             = 0x2A; /* * */
11461var CHAR_COMMA                = 0x2C; /* , */
11462var CHAR_MINUS                = 0x2D; /* - */
11463var CHAR_COLON                = 0x3A; /* : */
11464var CHAR_EQUALS               = 0x3D; /* = */
11465var CHAR_GREATER_THAN         = 0x3E; /* > */
11466var CHAR_QUESTION             = 0x3F; /* ? */
11467var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
11468var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
11469var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
11470var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
11471var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
11472var CHAR_VERTICAL_LINE        = 0x7C; /* | */
11473var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */
11474
11475var ESCAPE_SEQUENCES = {};
11476
11477ESCAPE_SEQUENCES[0x00]   = '\\0';
11478ESCAPE_SEQUENCES[0x07]   = '\\a';
11479ESCAPE_SEQUENCES[0x08]   = '\\b';
11480ESCAPE_SEQUENCES[0x09]   = '\\t';
11481ESCAPE_SEQUENCES[0x0A]   = '\\n';
11482ESCAPE_SEQUENCES[0x0B]   = '\\v';
11483ESCAPE_SEQUENCES[0x0C]   = '\\f';
11484ESCAPE_SEQUENCES[0x0D]   = '\\r';
11485ESCAPE_SEQUENCES[0x1B]   = '\\e';
11486ESCAPE_SEQUENCES[0x22]   = '\\"';
11487ESCAPE_SEQUENCES[0x5C]   = '\\\\';
11488ESCAPE_SEQUENCES[0x85]   = '\\N';
11489ESCAPE_SEQUENCES[0xA0]   = '\\_';
11490ESCAPE_SEQUENCES[0x2028] = '\\L';
11491ESCAPE_SEQUENCES[0x2029] = '\\P';
11492
11493var DEPRECATED_BOOLEANS_SYNTAX = [
11494  'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
11495  'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
11496];
11497
11498var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
11499
11500function compileStyleMap(schema, map) {
11501  var result, keys, index, length, tag, style, type;
11502
11503  if (map === null) return {};
11504
11505  result = {};
11506  keys = Object.keys(map);
11507
11508  for (index = 0, length = keys.length; index < length; index += 1) {
11509    tag = keys[index];
11510    style = String(map[tag]);
11511
11512    if (tag.slice(0, 2) === '!!') {
11513      tag = 'tag:yaml.org,2002:' + tag.slice(2);
11514    }
11515    type = schema.compiledTypeMap['fallback'][tag];
11516
11517    if (type && _hasOwnProperty.call(type.styleAliases, style)) {
11518      style = type.styleAliases[style];
11519    }
11520
11521    result[tag] = style;
11522  }
11523
11524  return result;
11525}
11526
11527function encodeHex(character) {
11528  var string, handle, length;
11529
11530  string = character.toString(16).toUpperCase();
11531
11532  if (character <= 0xFF) {
11533    handle = 'x';
11534    length = 2;
11535  } else if (character <= 0xFFFF) {
11536    handle = 'u';
11537    length = 4;
11538  } else if (character <= 0xFFFFFFFF) {
11539    handle = 'U';
11540    length = 8;
11541  } else {
11542    throw new exception('code point within a string may not be greater than 0xFFFFFFFF');
11543  }
11544
11545  return '\\' + handle + common$4.repeat('0', length - string.length) + string;
11546}
11547
11548
11549var QUOTING_TYPE_SINGLE = 1,
11550    QUOTING_TYPE_DOUBLE = 2;
11551
11552function State(options) {
11553  this.schema        = options['schema'] || _default$1;
11554  this.indent        = Math.max(1, (options['indent'] || 2));
11555  this.noArrayIndent = options['noArrayIndent'] || false;
11556  this.skipInvalid   = options['skipInvalid'] || false;
11557  this.flowLevel     = (common$4.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
11558  this.styleMap      = compileStyleMap(this.schema, options['styles'] || null);
11559  this.sortKeys      = options['sortKeys'] || false;
11560  this.lineWidth     = options['lineWidth'] || 80;
11561  this.noRefs        = options['noRefs'] || false;
11562  this.noCompatMode  = options['noCompatMode'] || false;
11563  this.condenseFlow  = options['condenseFlow'] || false;
11564  this.quotingType   = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
11565  this.forceQuotes   = options['forceQuotes'] || false;
11566  this.replacer      = typeof options['replacer'] === 'function' ? options['replacer'] : null;
11567
11568  this.implicitTypes = this.schema.compiledImplicit;
11569  this.explicitTypes = this.schema.compiledExplicit;
11570
11571  this.tag = null;
11572  this.result = '';
11573
11574  this.duplicates = [];
11575  this.usedDuplicates = null;
11576}
11577
11578// Indents every line in a string. Empty lines (\n only) are not indented.
11579function indentString(string, spaces) {
11580  var ind = common$4.repeat(' ', spaces),
11581      position = 0,
11582      next = -1,
11583      result = '',
11584      line,
11585      length = string.length;
11586
11587  while (position < length) {
11588    next = string.indexOf('\n', position);
11589    if (next === -1) {
11590      line = string.slice(position);
11591      position = length;
11592    } else {
11593      line = string.slice(position, next + 1);
11594      position = next + 1;
11595    }
11596
11597    if (line.length && line !== '\n') result += ind;
11598
11599    result += line;
11600  }
11601
11602  return result;
11603}
11604
11605function generateNextLine(state, level) {
11606  return '\n' + common$4.repeat(' ', state.indent * level);
11607}
11608
11609function testImplicitResolving(state, str) {
11610  var index, length, type;
11611
11612  for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
11613    type = state.implicitTypes[index];
11614
11615    if (type.resolve(str)) {
11616      return true;
11617    }
11618  }
11619
11620  return false;
11621}
11622
11623// [33] s-white ::= s-space | s-tab
11624function isWhitespace(c) {
11625  return c === CHAR_SPACE || c === CHAR_TAB;
11626}
11627
11628// Returns true if the character can be printed without escaping.
11629// From YAML 1.2: "any allowed characters known to be non-printable
11630// should also be escaped. [However,] This isn’t mandatory"
11631// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
11632function isPrintable(c) {
11633  return  (0x00020 <= c && c <= 0x00007E)
11634      || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
11635      || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
11636      ||  (0x10000 <= c && c <= 0x10FFFF);
11637}
11638
11639// [34] ns-char ::= nb-char - s-white
11640// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
11641// [26] b-char  ::= b-line-feed | b-carriage-return
11642// Including s-white (for some reason, examples doesn't match specs in this aspect)
11643// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
11644function isNsCharOrWhitespace(c) {
11645  return isPrintable(c)
11646    && c !== CHAR_BOM
11647    // - b-char
11648    && c !== CHAR_CARRIAGE_RETURN
11649    && c !== CHAR_LINE_FEED;
11650}
11651
11652// [127]  ns-plain-safe(c) ::= c = flow-out  ⇒ ns-plain-safe-out
11653//                             c = flow-in   ⇒ ns-plain-safe-in
11654//                             c = block-key ⇒ ns-plain-safe-out
11655//                             c = flow-key  ⇒ ns-plain-safe-in
11656// [128] ns-plain-safe-out ::= ns-char
11657// [129]  ns-plain-safe-in ::= ns-char - c-flow-indicator
11658// [130]  ns-plain-char(c) ::=  ( ns-plain-safe(c) - “:” - “#” )
11659//                            | ( /* An ns-char preceding */ “#” )
11660//                            | ( “:” /* Followed by an ns-plain-safe(c) */ )
11661function isPlainSafe(c, prev, inblock) {
11662  var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
11663  var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
11664  return (
11665    // ns-plain-safe
11666    inblock ? // c = flow-in
11667      cIsNsCharOrWhitespace
11668      : cIsNsCharOrWhitespace
11669        // - c-flow-indicator
11670        && c !== CHAR_COMMA
11671        && c !== CHAR_LEFT_SQUARE_BRACKET
11672        && c !== CHAR_RIGHT_SQUARE_BRACKET
11673        && c !== CHAR_LEFT_CURLY_BRACKET
11674        && c !== CHAR_RIGHT_CURLY_BRACKET
11675  )
11676    // ns-plain-char
11677    && c !== CHAR_SHARP // false on '#'
11678    && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
11679    || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
11680    || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
11681}
11682
11683// Simplified test for values allowed as the first character in plain style.
11684function isPlainSafeFirst(c) {
11685  // Uses a subset of ns-char - c-indicator
11686  // where ns-char = nb-char - s-white.
11687  // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
11688  return isPrintable(c) && c !== CHAR_BOM
11689    && !isWhitespace(c) // - s-white
11690    // - (c-indicator ::=
11691    // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
11692    && c !== CHAR_MINUS
11693    && c !== CHAR_QUESTION
11694    && c !== CHAR_COLON
11695    && c !== CHAR_COMMA
11696    && c !== CHAR_LEFT_SQUARE_BRACKET
11697    && c !== CHAR_RIGHT_SQUARE_BRACKET
11698    && c !== CHAR_LEFT_CURLY_BRACKET
11699    && c !== CHAR_RIGHT_CURLY_BRACKET
11700    // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
11701    && c !== CHAR_SHARP
11702    && c !== CHAR_AMPERSAND
11703    && c !== CHAR_ASTERISK
11704    && c !== CHAR_EXCLAMATION
11705    && c !== CHAR_VERTICAL_LINE
11706    && c !== CHAR_EQUALS
11707    && c !== CHAR_GREATER_THAN
11708    && c !== CHAR_SINGLE_QUOTE
11709    && c !== CHAR_DOUBLE_QUOTE
11710    // | “%” | “@” | “`”)
11711    && c !== CHAR_PERCENT
11712    && c !== CHAR_COMMERCIAL_AT
11713    && c !== CHAR_GRAVE_ACCENT;
11714}
11715
11716// Simplified test for values allowed as the last character in plain style.
11717function isPlainSafeLast(c) {
11718  // just not whitespace or colon, it will be checked to be plain character later
11719  return !isWhitespace(c) && c !== CHAR_COLON;
11720}
11721
11722// Same as 'string'.codePointAt(pos), but works in older browsers.
11723function codePointAt(string, pos) {
11724  var first = string.charCodeAt(pos), second;
11725  if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
11726    second = string.charCodeAt(pos + 1);
11727    if (second >= 0xDC00 && second <= 0xDFFF) {
11728      // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
11729      return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
11730    }
11731  }
11732  return first;
11733}
11734
11735// Determines whether block indentation indicator is required.
11736function needIndentIndicator(string) {
11737  var leadingSpaceRe = /^\n* /;
11738  return leadingSpaceRe.test(string);
11739}
11740
11741var STYLE_PLAIN   = 1,
11742    STYLE_SINGLE  = 2,
11743    STYLE_LITERAL = 3,
11744    STYLE_FOLDED  = 4,
11745    STYLE_DOUBLE  = 5;
11746
11747// Determines which scalar styles are possible and returns the preferred style.
11748// lineWidth = -1 => no limit.
11749// Pre-conditions: str.length > 0.
11750// Post-conditions:
11751//    STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
11752//    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
11753//    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
11754function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
11755  testAmbiguousType, quotingType, forceQuotes, inblock) {
11756
11757  var i;
11758  var char = 0;
11759  var prevChar = null;
11760  var hasLineBreak = false;
11761  var hasFoldableLine = false; // only checked if shouldTrackWidth
11762  var shouldTrackWidth = lineWidth !== -1;
11763  var previousLineBreak = -1; // count the first line correctly
11764  var plain = isPlainSafeFirst(codePointAt(string, 0))
11765          && isPlainSafeLast(codePointAt(string, string.length - 1));
11766
11767  if (singleLineOnly || forceQuotes) {
11768    // Case: no block styles.
11769    // Check for disallowed characters to rule out plain and single.
11770    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
11771      char = codePointAt(string, i);
11772      if (!isPrintable(char)) {
11773        return STYLE_DOUBLE;
11774      }
11775      plain = plain && isPlainSafe(char, prevChar, inblock);
11776      prevChar = char;
11777    }
11778  } else {
11779    // Case: block styles permitted.
11780    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
11781      char = codePointAt(string, i);
11782      if (char === CHAR_LINE_FEED) {
11783        hasLineBreak = true;
11784        // Check if any line can be folded.
11785        if (shouldTrackWidth) {
11786          hasFoldableLine = hasFoldableLine ||
11787            // Foldable line = too long, and not more-indented.
11788            (i - previousLineBreak - 1 > lineWidth &&
11789             string[previousLineBreak + 1] !== ' ');
11790          previousLineBreak = i;
11791        }
11792      } else if (!isPrintable(char)) {
11793        return STYLE_DOUBLE;
11794      }
11795      plain = plain && isPlainSafe(char, prevChar, inblock);
11796      prevChar = char;
11797    }
11798    // in case the end is missing a \n
11799    hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
11800      (i - previousLineBreak - 1 > lineWidth &&
11801       string[previousLineBreak + 1] !== ' '));
11802  }
11803  // Although every style can represent \n without escaping, prefer block styles
11804  // for multiline, since they're more readable and they don't add empty lines.
11805  // Also prefer folding a super-long line.
11806  if (!hasLineBreak && !hasFoldableLine) {
11807    // Strings interpretable as another type have to be quoted;
11808    // e.g. the string 'true' vs. the boolean true.
11809    if (plain && !forceQuotes && !testAmbiguousType(string)) {
11810      return STYLE_PLAIN;
11811    }
11812    return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
11813  }
11814  // Edge case: block indentation indicator can only have one digit.
11815  if (indentPerLevel > 9 && needIndentIndicator(string)) {
11816    return STYLE_DOUBLE;
11817  }
11818  // At this point we know block styles are valid.
11819  // Prefer literal style unless we want to fold.
11820  if (!forceQuotes) {
11821    return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
11822  }
11823  return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
11824}
11825
11826// Note: line breaking/folding is implemented for only the folded style.
11827// NB. We drop the last trailing newline (if any) of a returned block scalar
11828//  since the dumper adds its own newline. This always works:
11829//    • No ending newline => unaffected; already using strip "-" chomping.
11830//    • Ending newline    => removed then restored.
11831//  Importantly, this keeps the "+" chomp indicator from gaining an extra line.
11832function writeScalar(state, string, level, iskey, inblock) {
11833  state.dump = (function () {
11834    if (string.length === 0) {
11835      return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
11836    }
11837    if (!state.noCompatMode) {
11838      if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
11839        return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
11840      }
11841    }
11842
11843    var indent = state.indent * Math.max(1, level); // no 0-indent scalars
11844    // As indentation gets deeper, let the width decrease monotonically
11845    // to the lower bound min(state.lineWidth, 40).
11846    // Note that this implies
11847    //  state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
11848    //  state.lineWidth > 40 + state.indent: width decreases until the lower bound.
11849    // This behaves better than a constant minimum width which disallows narrower options,
11850    // or an indent threshold which causes the width to suddenly increase.
11851    var lineWidth = state.lineWidth === -1
11852      ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
11853
11854    // Without knowing if keys are implicit/explicit, assume implicit for safety.
11855    var singleLineOnly = iskey
11856      // No block styles in flow mode.
11857      || (state.flowLevel > -1 && level >= state.flowLevel);
11858    function testAmbiguity(string) {
11859      return testImplicitResolving(state, string);
11860    }
11861
11862    switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
11863      testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
11864
11865      case STYLE_PLAIN:
11866        return string;
11867      case STYLE_SINGLE:
11868        return "'" + string.replace(/'/g, "''") + "'";
11869      case STYLE_LITERAL:
11870        return '|' + blockHeader(string, state.indent)
11871          + dropEndingNewline(indentString(string, indent));
11872      case STYLE_FOLDED:
11873        return '>' + blockHeader(string, state.indent)
11874          + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
11875      case STYLE_DOUBLE:
11876        return '"' + escapeString(string) + '"';
11877      default:
11878        throw new exception('impossible error: invalid scalar style');
11879    }
11880  }());
11881}
11882
11883// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
11884function blockHeader(string, indentPerLevel) {
11885  var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
11886
11887  // note the special case: the string '\n' counts as a "trailing" empty line.
11888  var clip =          string[string.length - 1] === '\n';
11889  var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
11890  var chomp = keep ? '+' : (clip ? '' : '-');
11891
11892  return indentIndicator + chomp + '\n';
11893}
11894
11895// (See the note for writeScalar.)
11896function dropEndingNewline(string) {
11897  return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
11898}
11899
11900// Note: a long line without a suitable break point will exceed the width limit.
11901// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
11902function foldString(string, width) {
11903  // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
11904  // unless they're before or after a more-indented line, or at the very
11905  // beginning or end, in which case $k$ maps to $k$.
11906  // Therefore, parse each chunk as newline(s) followed by a content line.
11907  var lineRe = /(\n+)([^\n]*)/g;
11908
11909  // first line (possibly an empty line)
11910  var result = (function () {
11911    var nextLF = string.indexOf('\n');
11912    nextLF = nextLF !== -1 ? nextLF : string.length;
11913    lineRe.lastIndex = nextLF;
11914    return foldLine(string.slice(0, nextLF), width);
11915  }());
11916  // If we haven't reached the first content line yet, don't add an extra \n.
11917  var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
11918  var moreIndented;
11919
11920  // rest of the lines
11921  var match;
11922  while ((match = lineRe.exec(string))) {
11923    var prefix = match[1], line = match[2];
11924    moreIndented = (line[0] === ' ');
11925    result += prefix
11926      + (!prevMoreIndented && !moreIndented && line !== ''
11927        ? '\n' : '')
11928      + foldLine(line, width);
11929    prevMoreIndented = moreIndented;
11930  }
11931
11932  return result;
11933}
11934
11935// Greedy line breaking.
11936// Picks the longest line under the limit each time,
11937// otherwise settles for the shortest line over the limit.
11938// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
11939function foldLine(line, width) {
11940  if (line === '' || line[0] === ' ') return line;
11941
11942  // Since a more-indented line adds a \n, breaks can't be followed by a space.
11943  var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
11944  var match;
11945  // start is an inclusive index. end, curr, and next are exclusive.
11946  var start = 0, end, curr = 0, next = 0;
11947  var result = '';
11948
11949  // Invariants: 0 <= start <= length-1.
11950  //   0 <= curr <= next <= max(0, length-2). curr - start <= width.
11951  // Inside the loop:
11952  //   A match implies length >= 2, so curr and next are <= length-2.
11953  while ((match = breakRe.exec(line))) {
11954    next = match.index;
11955    // maintain invariant: curr - start <= width
11956    if (next - start > width) {
11957      end = (curr > start) ? curr : next; // derive end <= length-2
11958      result += '\n' + line.slice(start, end);
11959      // skip the space that was output as \n
11960      start = end + 1;                    // derive start <= length-1
11961    }
11962    curr = next;
11963  }
11964
11965  // By the invariants, start <= length-1, so there is something left over.
11966  // It is either the whole string or a part starting from non-whitespace.
11967  result += '\n';
11968  // Insert a break if the remainder is too long and there is a break available.
11969  if (line.length - start > width && curr > start) {
11970    result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
11971  } else {
11972    result += line.slice(start);
11973  }
11974
11975  return result.slice(1); // drop extra \n joiner
11976}
11977
11978// Escapes a double-quoted string.
11979function escapeString(string) {
11980  var result = '';
11981  var char = 0;
11982  var escapeSeq;
11983
11984  for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
11985    char = codePointAt(string, i);
11986    escapeSeq = ESCAPE_SEQUENCES[char];
11987
11988    if (!escapeSeq && isPrintable(char)) {
11989      result += string[i];
11990      if (char >= 0x10000) result += string[i + 1];
11991    } else {
11992      result += escapeSeq || encodeHex(char);
11993    }
11994  }
11995
11996  return result;
11997}
11998
11999function writeFlowSequence(state, level, object) {
12000  var _result = '',
12001      _tag    = state.tag,
12002      index,
12003      length,
12004      value;
12005
12006  for (index = 0, length = object.length; index < length; index += 1) {
12007    value = object[index];
12008
12009    if (state.replacer) {
12010      value = state.replacer.call(object, String(index), value);
12011    }
12012
12013    // Write only valid elements, put null instead of invalid elements.
12014    if (writeNode(state, level, value, false, false) ||
12015        (typeof value === 'undefined' &&
12016         writeNode(state, level, null, false, false))) {
12017
12018      if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
12019      _result += state.dump;
12020    }
12021  }
12022
12023  state.tag = _tag;
12024  state.dump = '[' + _result + ']';
12025}
12026
12027function writeBlockSequence(state, level, object, compact) {
12028  var _result = '',
12029      _tag    = state.tag,
12030      index,
12031      length,
12032      value;
12033
12034  for (index = 0, length = object.length; index < length; index += 1) {
12035    value = object[index];
12036
12037    if (state.replacer) {
12038      value = state.replacer.call(object, String(index), value);
12039    }
12040
12041    // Write only valid elements, put null instead of invalid elements.
12042    if (writeNode(state, level + 1, value, true, true, false, true) ||
12043        (typeof value === 'undefined' &&
12044         writeNode(state, level + 1, null, true, true, false, true))) {
12045
12046      if (!compact || _result !== '') {
12047        _result += generateNextLine(state, level);
12048      }
12049
12050      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
12051        _result += '-';
12052      } else {
12053        _result += '- ';
12054      }
12055
12056      _result += state.dump;
12057    }
12058  }
12059
12060  state.tag = _tag;
12061  state.dump = _result || '[]'; // Empty sequence if no valid values.
12062}
12063
12064function writeFlowMapping(state, level, object) {
12065  var _result       = '',
12066      _tag          = state.tag,
12067      objectKeyList = Object.keys(object),
12068      index,
12069      length,
12070      objectKey,
12071      objectValue,
12072      pairBuffer;
12073
12074  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
12075
12076    pairBuffer = '';
12077    if (_result !== '') pairBuffer += ', ';
12078
12079    if (state.condenseFlow) pairBuffer += '"';
12080
12081    objectKey = objectKeyList[index];
12082    objectValue = object[objectKey];
12083
12084    if (state.replacer) {
12085      objectValue = state.replacer.call(object, objectKey, objectValue);
12086    }
12087
12088    if (!writeNode(state, level, objectKey, false, false)) {
12089      continue; // Skip this pair because of invalid key;
12090    }
12091
12092    if (state.dump.length > 1024) pairBuffer += '? ';
12093
12094    pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
12095
12096    if (!writeNode(state, level, objectValue, false, false)) {
12097      continue; // Skip this pair because of invalid value.
12098    }
12099
12100    pairBuffer += state.dump;
12101
12102    // Both key and value are valid.
12103    _result += pairBuffer;
12104  }
12105
12106  state.tag = _tag;
12107  state.dump = '{' + _result + '}';
12108}
12109
12110function writeBlockMapping(state, level, object, compact) {
12111  var _result       = '',
12112      _tag          = state.tag,
12113      objectKeyList = Object.keys(object),
12114      index,
12115      length,
12116      objectKey,
12117      objectValue,
12118      explicitPair,
12119      pairBuffer;
12120
12121  // Allow sorting keys so that the output file is deterministic
12122  if (state.sortKeys === true) {
12123    // Default sorting
12124    objectKeyList.sort();
12125  } else if (typeof state.sortKeys === 'function') {
12126    // Custom sort function
12127    objectKeyList.sort(state.sortKeys);
12128  } else if (state.sortKeys) {
12129    // Something is wrong
12130    throw new exception('sortKeys must be a boolean or a function');
12131  }
12132
12133  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
12134    pairBuffer = '';
12135
12136    if (!compact || _result !== '') {
12137      pairBuffer += generateNextLine(state, level);
12138    }
12139
12140    objectKey = objectKeyList[index];
12141    objectValue = object[objectKey];
12142
12143    if (state.replacer) {
12144      objectValue = state.replacer.call(object, objectKey, objectValue);
12145    }
12146
12147    if (!writeNode(state, level + 1, objectKey, true, true, true)) {
12148      continue; // Skip this pair because of invalid key.
12149    }
12150
12151    explicitPair = (state.tag !== null && state.tag !== '?') ||
12152                   (state.dump && state.dump.length > 1024);
12153
12154    if (explicitPair) {
12155      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
12156        pairBuffer += '?';
12157      } else {
12158        pairBuffer += '? ';
12159      }
12160    }
12161
12162    pairBuffer += state.dump;
12163
12164    if (explicitPair) {
12165      pairBuffer += generateNextLine(state, level);
12166    }
12167
12168    if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
12169      continue; // Skip this pair because of invalid value.
12170    }
12171
12172    if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
12173      pairBuffer += ':';
12174    } else {
12175      pairBuffer += ': ';
12176    }
12177
12178    pairBuffer += state.dump;
12179
12180    // Both key and value are valid.
12181    _result += pairBuffer;
12182  }
12183
12184  state.tag = _tag;
12185  state.dump = _result || '{}'; // Empty mapping if no valid pairs.
12186}
12187
12188function detectType(state, object, explicit) {
12189  var _result, typeList, index, length, type, style;
12190
12191  typeList = explicit ? state.explicitTypes : state.implicitTypes;
12192
12193  for (index = 0, length = typeList.length; index < length; index += 1) {
12194    type = typeList[index];
12195
12196    if ((type.instanceOf  || type.predicate) &&
12197        (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
12198        (!type.predicate  || type.predicate(object))) {
12199
12200      if (explicit) {
12201        if (type.multi && type.representName) {
12202          state.tag = type.representName(object);
12203        } else {
12204          state.tag = type.tag;
12205        }
12206      } else {
12207        state.tag = '?';
12208      }
12209
12210      if (type.represent) {
12211        style = state.styleMap[type.tag] || type.defaultStyle;
12212
12213        if (_toString.call(type.represent) === '[object Function]') {
12214          _result = type.represent(object, style);
12215        } else if (_hasOwnProperty.call(type.represent, style)) {
12216          _result = type.represent[style](object, style);
12217        } else {
12218          throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
12219        }
12220
12221        state.dump = _result;
12222      }
12223
12224      return true;
12225    }
12226  }
12227
12228  return false;
12229}
12230
12231// Serializes `object` and writes it to global `result`.
12232// Returns true on success, or false on invalid object.
12233//
12234function writeNode(state, level, object, block, compact, iskey, isblockseq) {
12235  state.tag = null;
12236  state.dump = object;
12237
12238  if (!detectType(state, object, false)) {
12239    detectType(state, object, true);
12240  }
12241
12242  var type = _toString.call(state.dump);
12243  var inblock = block;
12244  var tagStr;
12245
12246  if (block) {
12247    block = (state.flowLevel < 0 || state.flowLevel > level);
12248  }
12249
12250  var objectOrArray = type === '[object Object]' || type === '[object Array]',
12251      duplicateIndex,
12252      duplicate;
12253
12254  if (objectOrArray) {
12255    duplicateIndex = state.duplicates.indexOf(object);
12256    duplicate = duplicateIndex !== -1;
12257  }
12258
12259  if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
12260    compact = false;
12261  }
12262
12263  if (duplicate && state.usedDuplicates[duplicateIndex]) {
12264    state.dump = '*ref_' + duplicateIndex;
12265  } else {
12266    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
12267      state.usedDuplicates[duplicateIndex] = true;
12268    }
12269    if (type === '[object Object]') {
12270      if (block && (Object.keys(state.dump).length !== 0)) {
12271        writeBlockMapping(state, level, state.dump, compact);
12272        if (duplicate) {
12273          state.dump = '&ref_' + duplicateIndex + state.dump;
12274        }
12275      } else {
12276        writeFlowMapping(state, level, state.dump);
12277        if (duplicate) {
12278          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
12279        }
12280      }
12281    } else if (type === '[object Array]') {
12282      if (block && (state.dump.length !== 0)) {
12283        if (state.noArrayIndent && !isblockseq && level > 0) {
12284          writeBlockSequence(state, level - 1, state.dump, compact);
12285        } else {
12286          writeBlockSequence(state, level, state.dump, compact);
12287        }
12288        if (duplicate) {
12289          state.dump = '&ref_' + duplicateIndex + state.dump;
12290        }
12291      } else {
12292        writeFlowSequence(state, level, state.dump);
12293        if (duplicate) {
12294          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
12295        }
12296      }
12297    } else if (type === '[object String]') {
12298      if (state.tag !== '?') {
12299        writeScalar(state, state.dump, level, iskey, inblock);
12300      }
12301    } else if (type === '[object Undefined]') {
12302      return false;
12303    } else {
12304      if (state.skipInvalid) return false;
12305      throw new exception('unacceptable kind of an object to dump ' + type);
12306    }
12307
12308    if (state.tag !== null && state.tag !== '?') {
12309      // Need to encode all characters except those allowed by the spec:
12310      //
12311      // [35] ns-dec-digit    ::=  [#x30-#x39] /* 0-9 */
12312      // [36] ns-hex-digit    ::=  ns-dec-digit
12313      //                         | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
12314      // [37] ns-ascii-letter ::=  [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
12315      // [38] ns-word-char    ::=  ns-dec-digit | ns-ascii-letter | “-”
12316      // [39] ns-uri-char     ::=  “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
12317      //                         | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
12318      //                         | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
12319      //
12320      // Also need to encode '!' because it has special meaning (end of tag prefix).
12321      //
12322      tagStr = encodeURI(
12323        state.tag[0] === '!' ? state.tag.slice(1) : state.tag
12324      ).replace(/!/g, '%21');
12325
12326      if (state.tag[0] === '!') {
12327        tagStr = '!' + tagStr;
12328      } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
12329        tagStr = '!!' + tagStr.slice(18);
12330      } else {
12331        tagStr = '!<' + tagStr + '>';
12332      }
12333
12334      state.dump = tagStr + ' ' + state.dump;
12335    }
12336  }
12337
12338  return true;
12339}
12340
12341function getDuplicateReferences(object, state) {
12342  var objects = [],
12343      duplicatesIndexes = [],
12344      index,
12345      length;
12346
12347  inspectNode(object, objects, duplicatesIndexes);
12348
12349  for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
12350    state.duplicates.push(objects[duplicatesIndexes[index]]);
12351  }
12352  state.usedDuplicates = new Array(length);
12353}
12354
12355function inspectNode(object, objects, duplicatesIndexes) {
12356  var objectKeyList,
12357      index,
12358      length;
12359
12360  if (object !== null && typeof object === 'object') {
12361    index = objects.indexOf(object);
12362    if (index !== -1) {
12363      if (duplicatesIndexes.indexOf(index) === -1) {
12364        duplicatesIndexes.push(index);
12365      }
12366    } else {
12367      objects.push(object);
12368
12369      if (Array.isArray(object)) {
12370        for (index = 0, length = object.length; index < length; index += 1) {
12371          inspectNode(object[index], objects, duplicatesIndexes);
12372        }
12373      } else {
12374        objectKeyList = Object.keys(object);
12375
12376        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
12377          inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
12378        }
12379      }
12380    }
12381  }
12382}
12383
12384function dump$1(input, options) {
12385  options = options || {};
12386
12387  var state = new State(options);
12388
12389  if (!state.noRefs) getDuplicateReferences(input, state);
12390
12391  var value = input;
12392
12393  if (state.replacer) {
12394    value = state.replacer.call({ '': value }, '', value);
12395  }
12396
12397  if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
12398
12399  return '';
12400}
12401
12402var dump_1 = dump$1;
12403
12404var dumper = {
12405	dump: dump_1
12406};
12407
12408function renamed(from, to) {
12409  return function () {
12410    throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
12411      'Use yaml.' + to + ' instead, which is now safe by default.');
12412  };
12413}
12414
12415
12416var Type                = type$1;
12417var Schema              = schema$1;
12418var FAILSAFE_SCHEMA     = failsafe;
12419var JSON_SCHEMA         = json;
12420var CORE_SCHEMA         = core;
12421var DEFAULT_SCHEMA      = _default$1;
12422var load                = loader.load;
12423var loadAll             = loader.loadAll;
12424var dump                = dumper.dump;
12425var YAMLException       = exception;
12426
12427// Re-export all types in case user wants to create custom schema
12428var types$1 = {
12429  binary:    binary,
12430  float:     float,
12431  map:       map$3,
12432  null:      _null,
12433  pairs:     pairs,
12434  set:       set,
12435  timestamp: timestamp,
12436  bool:      bool,
12437  int:       int,
12438  merge:     merge$1,
12439  omap:      omap,
12440  seq:       seq,
12441  str:       str
12442};
12443
12444// Removed functions from JS-YAML 3.0.x
12445var safeLoad            = renamed('safeLoad', 'load');
12446var safeLoadAll         = renamed('safeLoadAll', 'loadAll');
12447var safeDump            = renamed('safeDump', 'dump');
12448
12449var jsYaml = {
12450	Type: Type,
12451	Schema: Schema,
12452	FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,
12453	JSON_SCHEMA: JSON_SCHEMA,
12454	CORE_SCHEMA: CORE_SCHEMA,
12455	DEFAULT_SCHEMA: DEFAULT_SCHEMA,
12456	load: load,
12457	loadAll: loadAll,
12458	dump: dump,
12459	YAMLException: YAMLException,
12460	types: types$1,
12461	safeLoad: safeLoad,
12462	safeLoadAll: safeLoadAll,
12463	safeDump: safeDump
12464};
12465
12466var isArrayish$2 = function isArrayish(obj) {
12467	if (!obj) {
12468		return false;
12469	}
12470
12471	return obj instanceof Array || Array.isArray(obj) ||
12472		(obj.length >= 0 && obj.splice instanceof Function);
12473};
12474
12475var util$2 = require$$0$4;
12476var isArrayish$1 = isArrayish$2;
12477
12478var errorEx$1 = function errorEx(name, properties) {
12479	if (!name || name.constructor !== String) {
12480		properties = name || {};
12481		name = Error.name;
12482	}
12483
12484	var errorExError = function ErrorEXError(message) {
12485		if (!this) {
12486			return new ErrorEXError(message);
12487		}
12488
12489		message = message instanceof Error
12490			? message.message
12491			: (message || this.message);
12492
12493		Error.call(this, message);
12494		Error.captureStackTrace(this, errorExError);
12495
12496		this.name = name;
12497
12498		Object.defineProperty(this, 'message', {
12499			configurable: true,
12500			enumerable: false,
12501			get: function () {
12502				var newMessage = message.split(/\r?\n/g);
12503
12504				for (var key in properties) {
12505					if (!properties.hasOwnProperty(key)) {
12506						continue;
12507					}
12508
12509					var modifier = properties[key];
12510
12511					if ('message' in modifier) {
12512						newMessage = modifier.message(this[key], newMessage) || newMessage;
12513						if (!isArrayish$1(newMessage)) {
12514							newMessage = [newMessage];
12515						}
12516					}
12517				}
12518
12519				return newMessage.join('\n');
12520			},
12521			set: function (v) {
12522				message = v;
12523			}
12524		});
12525
12526		var overwrittenStack = null;
12527
12528		var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
12529		var stackGetter = stackDescriptor.get;
12530		var stackValue = stackDescriptor.value;
12531		delete stackDescriptor.value;
12532		delete stackDescriptor.writable;
12533
12534		stackDescriptor.set = function (newstack) {
12535			overwrittenStack = newstack;
12536		};
12537
12538		stackDescriptor.get = function () {
12539			var stack = (overwrittenStack || ((stackGetter)
12540				? stackGetter.call(this)
12541				: stackValue)).split(/\r?\n+/g);
12542
12543			// starting in Node 7, the stack builder caches the message.
12544			// just replace it.
12545			if (!overwrittenStack) {
12546				stack[0] = this.name + ': ' + this.message;
12547			}
12548
12549			var lineCount = 1;
12550			for (var key in properties) {
12551				if (!properties.hasOwnProperty(key)) {
12552					continue;
12553				}
12554
12555				var modifier = properties[key];
12556
12557				if ('line' in modifier) {
12558					var line = modifier.line(this[key]);
12559					if (line) {
12560						stack.splice(lineCount++, 0, '    ' + line);
12561					}
12562				}
12563
12564				if ('stack' in modifier) {
12565					modifier.stack(this[key], stack);
12566				}
12567			}
12568
12569			return stack.join('\n');
12570		};
12571
12572		Object.defineProperty(this, 'stack', stackDescriptor);
12573	};
12574
12575	if (Object.setPrototypeOf) {
12576		Object.setPrototypeOf(errorExError.prototype, Error.prototype);
12577		Object.setPrototypeOf(errorExError, Error);
12578	} else {
12579		util$2.inherits(errorExError, Error);
12580	}
12581
12582	return errorExError;
12583};
12584
12585errorEx$1.append = function (str, def) {
12586	return {
12587		message: function (v, message) {
12588			v = v || def;
12589
12590			if (v) {
12591				message[0] += ' ' + str.replace('%s', v.toString());
12592			}
12593
12594			return message;
12595		}
12596	};
12597};
12598
12599errorEx$1.line = function (str, def) {
12600	return {
12601		line: function (v) {
12602			v = v || def;
12603
12604			if (v) {
12605				return str.replace('%s', v.toString());
12606			}
12607
12608			return null;
12609		}
12610	};
12611};
12612
12613var errorEx_1 = errorEx$1;
12614
12615const hexify = char => {
12616  const h = char.charCodeAt(0).toString(16).toUpperCase();
12617  return '0x' + (h.length % 2 ? '0' : '') + h
12618};
12619
12620const parseError = (e, txt, context) => {
12621  if (!txt) {
12622    return {
12623      message: e.message + ' while parsing empty string',
12624      position: 0,
12625    }
12626  }
12627  const badToken = e.message.match(/^Unexpected token (.) .*position\s+(\d+)/i);
12628  const errIdx = badToken ? +badToken[2]
12629    : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1
12630    : null;
12631
12632  const msg = badToken ? e.message.replace(/^Unexpected token ./, `Unexpected token ${
12633      JSON.stringify(badToken[1])
12634    } (${hexify(badToken[1])})`)
12635    : e.message;
12636
12637  if (errIdx !== null && errIdx !== undefined) {
12638    const start = errIdx <= context ? 0
12639      : errIdx - context;
12640
12641    const end = errIdx + context >= txt.length ? txt.length
12642      : errIdx + context;
12643
12644    const slice = (start === 0 ? '' : '...') +
12645      txt.slice(start, end) +
12646      (end === txt.length ? '' : '...');
12647
12648    const near = txt === slice ? '' : 'near ';
12649
12650    return {
12651      message: msg + ` while parsing ${near}${JSON.stringify(slice)}`,
12652      position: errIdx,
12653    }
12654  } else {
12655    return {
12656      message: msg + ` while parsing '${txt.slice(0, context * 2)}'`,
12657      position: 0,
12658    }
12659  }
12660};
12661
12662class JSONParseError extends SyntaxError {
12663  constructor (er, txt, context, caller) {
12664    context = context || 20;
12665    const metadata = parseError(er, txt, context);
12666    super(metadata.message);
12667    Object.assign(this, metadata);
12668    this.code = 'EJSONPARSE';
12669    this.systemError = er;
12670    Error.captureStackTrace(this, caller || this.constructor);
12671  }
12672  get name () { return this.constructor.name }
12673  set name (n) {}
12674  get [Symbol.toStringTag] () { return this.constructor.name }
12675}
12676
12677const kIndent = Symbol.for('indent');
12678const kNewline = Symbol.for('newline');
12679// only respect indentation if we got a line break, otherwise squash it
12680// things other than objects and arrays aren't indented, so ignore those
12681// Important: in both of these regexps, the $1 capture group is the newline
12682// or undefined, and the $2 capture group is the indent, or undefined.
12683const formatRE = /^\s*[{\[]((?:\r?\n)+)([\s\t]*)/;
12684const emptyRE = /^(?:\{\}|\[\])((?:\r?\n)+)?$/;
12685
12686const parseJson$1 = (txt, reviver, context) => {
12687  const parseText = stripBOM(txt);
12688  context = context || 20;
12689  try {
12690    // get the indentation so that we can save it back nicely
12691    // if the file starts with {" then we have an indent of '', ie, none
12692    // otherwise, pick the indentation of the next line after the first \n
12693    // If the pattern doesn't match, then it means no indentation.
12694    // JSON.stringify ignores symbols, so this is reasonably safe.
12695    // if the string is '{}' or '[]', then use the default 2-space indent.
12696    const [, newline = '\n', indent = '  '] = parseText.match(emptyRE) ||
12697      parseText.match(formatRE) ||
12698      [, '', ''];
12699
12700    const result = JSON.parse(parseText, reviver);
12701    if (result && typeof result === 'object') {
12702      result[kNewline] = newline;
12703      result[kIndent] = indent;
12704    }
12705    return result
12706  } catch (e) {
12707    if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) {
12708      const isEmptyArray = Array.isArray(txt) && txt.length === 0;
12709      throw Object.assign(new TypeError(
12710        `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}`
12711      ), {
12712        code: 'EJSONPARSE',
12713        systemError: e,
12714      })
12715    }
12716
12717    throw new JSONParseError(e, parseText, context, parseJson$1)
12718  }
12719};
12720
12721// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
12722// because the buffer-to-string conversion in `fs.readFileSync()`
12723// translates it to FEFF, the UTF-16 BOM.
12724const stripBOM = txt => String(txt).replace(/^\uFEFF/, '');
12725
12726var jsonParseEvenBetterErrors = parseJson$1;
12727parseJson$1.JSONParseError = JSONParseError;
12728
12729parseJson$1.noExceptions = (txt, reviver) => {
12730  try {
12731    return JSON.parse(stripBOM(txt), reviver)
12732  } catch (e) {}
12733};
12734
12735var LF = '\n';
12736var CR = '\r';
12737var LinesAndColumns$1 = (function () {
12738    function LinesAndColumns(string) {
12739        this.string = string;
12740        var offsets = [0];
12741        for (var offset = 0; offset < string.length;) {
12742            switch (string[offset]) {
12743                case LF:
12744                    offset += LF.length;
12745                    offsets.push(offset);
12746                    break;
12747                case CR:
12748                    offset += CR.length;
12749                    if (string[offset] === LF) {
12750                        offset += LF.length;
12751                    }
12752                    offsets.push(offset);
12753                    break;
12754                default:
12755                    offset++;
12756                    break;
12757            }
12758        }
12759        this.offsets = offsets;
12760    }
12761    LinesAndColumns.prototype.locationForIndex = function (index) {
12762        if (index < 0 || index > this.string.length) {
12763            return null;
12764        }
12765        var line = 0;
12766        var offsets = this.offsets;
12767        while (offsets[line + 1] <= index) {
12768            line++;
12769        }
12770        var column = index - offsets[line];
12771        return { line: line, column: column };
12772    };
12773    LinesAndColumns.prototype.indexForLocation = function (location) {
12774        var line = location.line, column = location.column;
12775        if (line < 0 || line >= this.offsets.length) {
12776            return null;
12777        }
12778        if (column < 0 || column > this.lengthOfLine(line)) {
12779            return null;
12780        }
12781        return this.offsets[line] + column;
12782    };
12783    LinesAndColumns.prototype.lengthOfLine = function (line) {
12784        var offset = this.offsets[line];
12785        var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
12786        return nextOffset - offset;
12787    };
12788    return LinesAndColumns;
12789}());
12790
12791var dist = /*#__PURE__*/Object.freeze({
12792	__proto__: null,
12793	'default': LinesAndColumns$1
12794});
12795
12796var require$$2 = /*@__PURE__*/getAugmentedNamespace(dist);
12797
12798var lib$4 = {};
12799
12800var lib$3 = {};
12801
12802var jsTokens = {};
12803
12804// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
12805// License: MIT. (See LICENSE.)
12806
12807Object.defineProperty(jsTokens, "__esModule", {
12808  value: true
12809});
12810
12811// This regex comes from regex.coffee, and is inserted here by generate-index.js
12812// (run `npm run build`).
12813jsTokens.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
12814
12815jsTokens.matchToToken = function(match) {
12816  var token = {type: "invalid", value: match[0], closed: undefined};
12817       if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]);
12818  else if (match[ 5]) token.type = "comment";
12819  else if (match[ 6]) token.type = "comment", token.closed = !!match[7];
12820  else if (match[ 8]) token.type = "regex";
12821  else if (match[ 9]) token.type = "number";
12822  else if (match[10]) token.type = "name";
12823  else if (match[11]) token.type = "punctuator";
12824  else if (match[12]) token.type = "whitespace";
12825  return token
12826};
12827
12828var lib$2 = {};
12829
12830var identifier = {};
12831
12832Object.defineProperty(identifier, "__esModule", {
12833  value: true
12834});
12835identifier.isIdentifierStart = isIdentifierStart;
12836identifier.isIdentifierChar = isIdentifierChar;
12837identifier.isIdentifierName = isIdentifierName;
12838let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
12839let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
12840const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
12841const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
12842nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
12843const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
12844const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
12845
12846function isInAstralSet(code, set) {
12847  let pos = 0x10000;
12848
12849  for (let i = 0, length = set.length; i < length; i += 2) {
12850    pos += set[i];
12851    if (pos > code) return false;
12852    pos += set[i + 1];
12853    if (pos >= code) return true;
12854  }
12855
12856  return false;
12857}
12858
12859function isIdentifierStart(code) {
12860  if (code < 65) return code === 36;
12861  if (code <= 90) return true;
12862  if (code < 97) return code === 95;
12863  if (code <= 122) return true;
12864
12865  if (code <= 0xffff) {
12866    return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
12867  }
12868
12869  return isInAstralSet(code, astralIdentifierStartCodes);
12870}
12871
12872function isIdentifierChar(code) {
12873  if (code < 48) return code === 36;
12874  if (code < 58) return true;
12875  if (code < 65) return false;
12876  if (code <= 90) return true;
12877  if (code < 97) return code === 95;
12878  if (code <= 122) return true;
12879
12880  if (code <= 0xffff) {
12881    return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
12882  }
12883
12884  return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
12885}
12886
12887function isIdentifierName(name) {
12888  let isFirst = true;
12889
12890  for (let i = 0; i < name.length; i++) {
12891    let cp = name.charCodeAt(i);
12892
12893    if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {
12894      const trail = name.charCodeAt(++i);
12895
12896      if ((trail & 0xfc00) === 0xdc00) {
12897        cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
12898      }
12899    }
12900
12901    if (isFirst) {
12902      isFirst = false;
12903
12904      if (!isIdentifierStart(cp)) {
12905        return false;
12906      }
12907    } else if (!isIdentifierChar(cp)) {
12908      return false;
12909    }
12910  }
12911
12912  return !isFirst;
12913}
12914
12915var keyword = {};
12916
12917Object.defineProperty(keyword, "__esModule", {
12918  value: true
12919});
12920keyword.isReservedWord = isReservedWord;
12921keyword.isStrictReservedWord = isStrictReservedWord;
12922keyword.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
12923keyword.isStrictBindReservedWord = isStrictBindReservedWord;
12924keyword.isKeyword = isKeyword;
12925const reservedWords = {
12926  keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
12927  strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
12928  strictBind: ["eval", "arguments"]
12929};
12930const keywords$1 = new Set(reservedWords.keyword);
12931const reservedWordsStrictSet = new Set(reservedWords.strict);
12932const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
12933
12934function isReservedWord(word, inModule) {
12935  return inModule && word === "await" || word === "enum";
12936}
12937
12938function isStrictReservedWord(word, inModule) {
12939  return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
12940}
12941
12942function isStrictBindOnlyReservedWord(word) {
12943  return reservedWordsStrictBindSet.has(word);
12944}
12945
12946function isStrictBindReservedWord(word, inModule) {
12947  return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
12948}
12949
12950function isKeyword(word) {
12951  return keywords$1.has(word);
12952}
12953
12954(function (exports) {
12955
12956Object.defineProperty(exports, "__esModule", {
12957  value: true
12958});
12959Object.defineProperty(exports, "isIdentifierName", {
12960  enumerable: true,
12961  get: function () {
12962    return _identifier.isIdentifierName;
12963  }
12964});
12965Object.defineProperty(exports, "isIdentifierChar", {
12966  enumerable: true,
12967  get: function () {
12968    return _identifier.isIdentifierChar;
12969  }
12970});
12971Object.defineProperty(exports, "isIdentifierStart", {
12972  enumerable: true,
12973  get: function () {
12974    return _identifier.isIdentifierStart;
12975  }
12976});
12977Object.defineProperty(exports, "isReservedWord", {
12978  enumerable: true,
12979  get: function () {
12980    return _keyword.isReservedWord;
12981  }
12982});
12983Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
12984  enumerable: true,
12985  get: function () {
12986    return _keyword.isStrictBindOnlyReservedWord;
12987  }
12988});
12989Object.defineProperty(exports, "isStrictBindReservedWord", {
12990  enumerable: true,
12991  get: function () {
12992    return _keyword.isStrictBindReservedWord;
12993  }
12994});
12995Object.defineProperty(exports, "isStrictReservedWord", {
12996  enumerable: true,
12997  get: function () {
12998    return _keyword.isStrictReservedWord;
12999  }
13000});
13001Object.defineProperty(exports, "isKeyword", {
13002  enumerable: true,
13003  get: function () {
13004    return _keyword.isKeyword;
13005  }
13006});
13007
13008var _identifier = identifier;
13009
13010var _keyword = keyword;
13011}(lib$2));
13012
13013var chalk = {exports: {}};
13014
13015var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
13016
13017var escapeStringRegexp$1 = function (str) {
13018	if (typeof str !== 'string') {
13019		throw new TypeError('Expected a string');
13020	}
13021
13022	return str.replace(matchOperatorsRe, '\\$&');
13023};
13024
13025var ansiStyles = {exports: {}};
13026
13027var conversions$2 = {exports: {}};
13028
13029var colorName = {
13030	"aliceblue": [240, 248, 255],
13031	"antiquewhite": [250, 235, 215],
13032	"aqua": [0, 255, 255],
13033	"aquamarine": [127, 255, 212],
13034	"azure": [240, 255, 255],
13035	"beige": [245, 245, 220],
13036	"bisque": [255, 228, 196],
13037	"black": [0, 0, 0],
13038	"blanchedalmond": [255, 235, 205],
13039	"blue": [0, 0, 255],
13040	"blueviolet": [138, 43, 226],
13041	"brown": [165, 42, 42],
13042	"burlywood": [222, 184, 135],
13043	"cadetblue": [95, 158, 160],
13044	"chartreuse": [127, 255, 0],
13045	"chocolate": [210, 105, 30],
13046	"coral": [255, 127, 80],
13047	"cornflowerblue": [100, 149, 237],
13048	"cornsilk": [255, 248, 220],
13049	"crimson": [220, 20, 60],
13050	"cyan": [0, 255, 255],
13051	"darkblue": [0, 0, 139],
13052	"darkcyan": [0, 139, 139],
13053	"darkgoldenrod": [184, 134, 11],
13054	"darkgray": [169, 169, 169],
13055	"darkgreen": [0, 100, 0],
13056	"darkgrey": [169, 169, 169],
13057	"darkkhaki": [189, 183, 107],
13058	"darkmagenta": [139, 0, 139],
13059	"darkolivegreen": [85, 107, 47],
13060	"darkorange": [255, 140, 0],
13061	"darkorchid": [153, 50, 204],
13062	"darkred": [139, 0, 0],
13063	"darksalmon": [233, 150, 122],
13064	"darkseagreen": [143, 188, 143],
13065	"darkslateblue": [72, 61, 139],
13066	"darkslategray": [47, 79, 79],
13067	"darkslategrey": [47, 79, 79],
13068	"darkturquoise": [0, 206, 209],
13069	"darkviolet": [148, 0, 211],
13070	"deeppink": [255, 20, 147],
13071	"deepskyblue": [0, 191, 255],
13072	"dimgray": [105, 105, 105],
13073	"dimgrey": [105, 105, 105],
13074	"dodgerblue": [30, 144, 255],
13075	"firebrick": [178, 34, 34],
13076	"floralwhite": [255, 250, 240],
13077	"forestgreen": [34, 139, 34],
13078	"fuchsia": [255, 0, 255],
13079	"gainsboro": [220, 220, 220],
13080	"ghostwhite": [248, 248, 255],
13081	"gold": [255, 215, 0],
13082	"goldenrod": [218, 165, 32],
13083	"gray": [128, 128, 128],
13084	"green": [0, 128, 0],
13085	"greenyellow": [173, 255, 47],
13086	"grey": [128, 128, 128],
13087	"honeydew": [240, 255, 240],
13088	"hotpink": [255, 105, 180],
13089	"indianred": [205, 92, 92],
13090	"indigo": [75, 0, 130],
13091	"ivory": [255, 255, 240],
13092	"khaki": [240, 230, 140],
13093	"lavender": [230, 230, 250],
13094	"lavenderblush": [255, 240, 245],
13095	"lawngreen": [124, 252, 0],
13096	"lemonchiffon": [255, 250, 205],
13097	"lightblue": [173, 216, 230],
13098	"lightcoral": [240, 128, 128],
13099	"lightcyan": [224, 255, 255],
13100	"lightgoldenrodyellow": [250, 250, 210],
13101	"lightgray": [211, 211, 211],
13102	"lightgreen": [144, 238, 144],
13103	"lightgrey": [211, 211, 211],
13104	"lightpink": [255, 182, 193],
13105	"lightsalmon": [255, 160, 122],
13106	"lightseagreen": [32, 178, 170],
13107	"lightskyblue": [135, 206, 250],
13108	"lightslategray": [119, 136, 153],
13109	"lightslategrey": [119, 136, 153],
13110	"lightsteelblue": [176, 196, 222],
13111	"lightyellow": [255, 255, 224],
13112	"lime": [0, 255, 0],
13113	"limegreen": [50, 205, 50],
13114	"linen": [250, 240, 230],
13115	"magenta": [255, 0, 255],
13116	"maroon": [128, 0, 0],
13117	"mediumaquamarine": [102, 205, 170],
13118	"mediumblue": [0, 0, 205],
13119	"mediumorchid": [186, 85, 211],
13120	"mediumpurple": [147, 112, 219],
13121	"mediumseagreen": [60, 179, 113],
13122	"mediumslateblue": [123, 104, 238],
13123	"mediumspringgreen": [0, 250, 154],
13124	"mediumturquoise": [72, 209, 204],
13125	"mediumvioletred": [199, 21, 133],
13126	"midnightblue": [25, 25, 112],
13127	"mintcream": [245, 255, 250],
13128	"mistyrose": [255, 228, 225],
13129	"moccasin": [255, 228, 181],
13130	"navajowhite": [255, 222, 173],
13131	"navy": [0, 0, 128],
13132	"oldlace": [253, 245, 230],
13133	"olive": [128, 128, 0],
13134	"olivedrab": [107, 142, 35],
13135	"orange": [255, 165, 0],
13136	"orangered": [255, 69, 0],
13137	"orchid": [218, 112, 214],
13138	"palegoldenrod": [238, 232, 170],
13139	"palegreen": [152, 251, 152],
13140	"paleturquoise": [175, 238, 238],
13141	"palevioletred": [219, 112, 147],
13142	"papayawhip": [255, 239, 213],
13143	"peachpuff": [255, 218, 185],
13144	"peru": [205, 133, 63],
13145	"pink": [255, 192, 203],
13146	"plum": [221, 160, 221],
13147	"powderblue": [176, 224, 230],
13148	"purple": [128, 0, 128],
13149	"rebeccapurple": [102, 51, 153],
13150	"red": [255, 0, 0],
13151	"rosybrown": [188, 143, 143],
13152	"royalblue": [65, 105, 225],
13153	"saddlebrown": [139, 69, 19],
13154	"salmon": [250, 128, 114],
13155	"sandybrown": [244, 164, 96],
13156	"seagreen": [46, 139, 87],
13157	"seashell": [255, 245, 238],
13158	"sienna": [160, 82, 45],
13159	"silver": [192, 192, 192],
13160	"skyblue": [135, 206, 235],
13161	"slateblue": [106, 90, 205],
13162	"slategray": [112, 128, 144],
13163	"slategrey": [112, 128, 144],
13164	"snow": [255, 250, 250],
13165	"springgreen": [0, 255, 127],
13166	"steelblue": [70, 130, 180],
13167	"tan": [210, 180, 140],
13168	"teal": [0, 128, 128],
13169	"thistle": [216, 191, 216],
13170	"tomato": [255, 99, 71],
13171	"turquoise": [64, 224, 208],
13172	"violet": [238, 130, 238],
13173	"wheat": [245, 222, 179],
13174	"white": [255, 255, 255],
13175	"whitesmoke": [245, 245, 245],
13176	"yellow": [255, 255, 0],
13177	"yellowgreen": [154, 205, 50]
13178};
13179
13180/* MIT license */
13181
13182var cssKeywords = colorName;
13183
13184// NOTE: conversions should only return primitive values (i.e. arrays, or
13185//       values that give correct `typeof` results).
13186//       do not use box values types (i.e. Number(), String(), etc.)
13187
13188var reverseKeywords = {};
13189for (var key$1 in cssKeywords) {
13190	if (cssKeywords.hasOwnProperty(key$1)) {
13191		reverseKeywords[cssKeywords[key$1]] = key$1;
13192	}
13193}
13194
13195var convert$2 = conversions$2.exports = {
13196	rgb: {channels: 3, labels: 'rgb'},
13197	hsl: {channels: 3, labels: 'hsl'},
13198	hsv: {channels: 3, labels: 'hsv'},
13199	hwb: {channels: 3, labels: 'hwb'},
13200	cmyk: {channels: 4, labels: 'cmyk'},
13201	xyz: {channels: 3, labels: 'xyz'},
13202	lab: {channels: 3, labels: 'lab'},
13203	lch: {channels: 3, labels: 'lch'},
13204	hex: {channels: 1, labels: ['hex']},
13205	keyword: {channels: 1, labels: ['keyword']},
13206	ansi16: {channels: 1, labels: ['ansi16']},
13207	ansi256: {channels: 1, labels: ['ansi256']},
13208	hcg: {channels: 3, labels: ['h', 'c', 'g']},
13209	apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
13210	gray: {channels: 1, labels: ['gray']}
13211};
13212
13213// hide .channels and .labels properties
13214for (var model in convert$2) {
13215	if (convert$2.hasOwnProperty(model)) {
13216		if (!('channels' in convert$2[model])) {
13217			throw new Error('missing channels property: ' + model);
13218		}
13219
13220		if (!('labels' in convert$2[model])) {
13221			throw new Error('missing channel labels property: ' + model);
13222		}
13223
13224		if (convert$2[model].labels.length !== convert$2[model].channels) {
13225			throw new Error('channel and label counts mismatch: ' + model);
13226		}
13227
13228		var channels = convert$2[model].channels;
13229		var labels$1 = convert$2[model].labels;
13230		delete convert$2[model].channels;
13231		delete convert$2[model].labels;
13232		Object.defineProperty(convert$2[model], 'channels', {value: channels});
13233		Object.defineProperty(convert$2[model], 'labels', {value: labels$1});
13234	}
13235}
13236
13237convert$2.rgb.hsl = function (rgb) {
13238	var r = rgb[0] / 255;
13239	var g = rgb[1] / 255;
13240	var b = rgb[2] / 255;
13241	var min = Math.min(r, g, b);
13242	var max = Math.max(r, g, b);
13243	var delta = max - min;
13244	var h;
13245	var s;
13246	var l;
13247
13248	if (max === min) {
13249		h = 0;
13250	} else if (r === max) {
13251		h = (g - b) / delta;
13252	} else if (g === max) {
13253		h = 2 + (b - r) / delta;
13254	} else if (b === max) {
13255		h = 4 + (r - g) / delta;
13256	}
13257
13258	h = Math.min(h * 60, 360);
13259
13260	if (h < 0) {
13261		h += 360;
13262	}
13263
13264	l = (min + max) / 2;
13265
13266	if (max === min) {
13267		s = 0;
13268	} else if (l <= 0.5) {
13269		s = delta / (max + min);
13270	} else {
13271		s = delta / (2 - max - min);
13272	}
13273
13274	return [h, s * 100, l * 100];
13275};
13276
13277convert$2.rgb.hsv = function (rgb) {
13278	var rdif;
13279	var gdif;
13280	var bdif;
13281	var h;
13282	var s;
13283
13284	var r = rgb[0] / 255;
13285	var g = rgb[1] / 255;
13286	var b = rgb[2] / 255;
13287	var v = Math.max(r, g, b);
13288	var diff = v - Math.min(r, g, b);
13289	var diffc = function (c) {
13290		return (v - c) / 6 / diff + 1 / 2;
13291	};
13292
13293	if (diff === 0) {
13294		h = s = 0;
13295	} else {
13296		s = diff / v;
13297		rdif = diffc(r);
13298		gdif = diffc(g);
13299		bdif = diffc(b);
13300
13301		if (r === v) {
13302			h = bdif - gdif;
13303		} else if (g === v) {
13304			h = (1 / 3) + rdif - bdif;
13305		} else if (b === v) {
13306			h = (2 / 3) + gdif - rdif;
13307		}
13308		if (h < 0) {
13309			h += 1;
13310		} else if (h > 1) {
13311			h -= 1;
13312		}
13313	}
13314
13315	return [
13316		h * 360,
13317		s * 100,
13318		v * 100
13319	];
13320};
13321
13322convert$2.rgb.hwb = function (rgb) {
13323	var r = rgb[0];
13324	var g = rgb[1];
13325	var b = rgb[2];
13326	var h = convert$2.rgb.hsl(rgb)[0];
13327	var w = 1 / 255 * Math.min(r, Math.min(g, b));
13328
13329	b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
13330
13331	return [h, w * 100, b * 100];
13332};
13333
13334convert$2.rgb.cmyk = function (rgb) {
13335	var r = rgb[0] / 255;
13336	var g = rgb[1] / 255;
13337	var b = rgb[2] / 255;
13338	var c;
13339	var m;
13340	var y;
13341	var k;
13342
13343	k = Math.min(1 - r, 1 - g, 1 - b);
13344	c = (1 - r - k) / (1 - k) || 0;
13345	m = (1 - g - k) / (1 - k) || 0;
13346	y = (1 - b - k) / (1 - k) || 0;
13347
13348	return [c * 100, m * 100, y * 100, k * 100];
13349};
13350
13351/**
13352 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
13353 * */
13354function comparativeDistance(x, y) {
13355	return (
13356		Math.pow(x[0] - y[0], 2) +
13357		Math.pow(x[1] - y[1], 2) +
13358		Math.pow(x[2] - y[2], 2)
13359	);
13360}
13361
13362convert$2.rgb.keyword = function (rgb) {
13363	var reversed = reverseKeywords[rgb];
13364	if (reversed) {
13365		return reversed;
13366	}
13367
13368	var currentClosestDistance = Infinity;
13369	var currentClosestKeyword;
13370
13371	for (var keyword in cssKeywords) {
13372		if (cssKeywords.hasOwnProperty(keyword)) {
13373			var value = cssKeywords[keyword];
13374
13375			// Compute comparative distance
13376			var distance = comparativeDistance(rgb, value);
13377
13378			// Check if its less, if so set as closest
13379			if (distance < currentClosestDistance) {
13380				currentClosestDistance = distance;
13381				currentClosestKeyword = keyword;
13382			}
13383		}
13384	}
13385
13386	return currentClosestKeyword;
13387};
13388
13389convert$2.keyword.rgb = function (keyword) {
13390	return cssKeywords[keyword];
13391};
13392
13393convert$2.rgb.xyz = function (rgb) {
13394	var r = rgb[0] / 255;
13395	var g = rgb[1] / 255;
13396	var b = rgb[2] / 255;
13397
13398	// assume sRGB
13399	r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
13400	g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
13401	b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
13402
13403	var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
13404	var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
13405	var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
13406
13407	return [x * 100, y * 100, z * 100];
13408};
13409
13410convert$2.rgb.lab = function (rgb) {
13411	var xyz = convert$2.rgb.xyz(rgb);
13412	var x = xyz[0];
13413	var y = xyz[1];
13414	var z = xyz[2];
13415	var l;
13416	var a;
13417	var b;
13418
13419	x /= 95.047;
13420	y /= 100;
13421	z /= 108.883;
13422
13423	x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
13424	y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
13425	z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
13426
13427	l = (116 * y) - 16;
13428	a = 500 * (x - y);
13429	b = 200 * (y - z);
13430
13431	return [l, a, b];
13432};
13433
13434convert$2.hsl.rgb = function (hsl) {
13435	var h = hsl[0] / 360;
13436	var s = hsl[1] / 100;
13437	var l = hsl[2] / 100;
13438	var t1;
13439	var t2;
13440	var t3;
13441	var rgb;
13442	var val;
13443
13444	if (s === 0) {
13445		val = l * 255;
13446		return [val, val, val];
13447	}
13448
13449	if (l < 0.5) {
13450		t2 = l * (1 + s);
13451	} else {
13452		t2 = l + s - l * s;
13453	}
13454
13455	t1 = 2 * l - t2;
13456
13457	rgb = [0, 0, 0];
13458	for (var i = 0; i < 3; i++) {
13459		t3 = h + 1 / 3 * -(i - 1);
13460		if (t3 < 0) {
13461			t3++;
13462		}
13463		if (t3 > 1) {
13464			t3--;
13465		}
13466
13467		if (6 * t3 < 1) {
13468			val = t1 + (t2 - t1) * 6 * t3;
13469		} else if (2 * t3 < 1) {
13470			val = t2;
13471		} else if (3 * t3 < 2) {
13472			val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
13473		} else {
13474			val = t1;
13475		}
13476
13477		rgb[i] = val * 255;
13478	}
13479
13480	return rgb;
13481};
13482
13483convert$2.hsl.hsv = function (hsl) {
13484	var h = hsl[0];
13485	var s = hsl[1] / 100;
13486	var l = hsl[2] / 100;
13487	var smin = s;
13488	var lmin = Math.max(l, 0.01);
13489	var sv;
13490	var v;
13491
13492	l *= 2;
13493	s *= (l <= 1) ? l : 2 - l;
13494	smin *= lmin <= 1 ? lmin : 2 - lmin;
13495	v = (l + s) / 2;
13496	sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
13497
13498	return [h, sv * 100, v * 100];
13499};
13500
13501convert$2.hsv.rgb = function (hsv) {
13502	var h = hsv[0] / 60;
13503	var s = hsv[1] / 100;
13504	var v = hsv[2] / 100;
13505	var hi = Math.floor(h) % 6;
13506
13507	var f = h - Math.floor(h);
13508	var p = 255 * v * (1 - s);
13509	var q = 255 * v * (1 - (s * f));
13510	var t = 255 * v * (1 - (s * (1 - f)));
13511	v *= 255;
13512
13513	switch (hi) {
13514		case 0:
13515			return [v, t, p];
13516		case 1:
13517			return [q, v, p];
13518		case 2:
13519			return [p, v, t];
13520		case 3:
13521			return [p, q, v];
13522		case 4:
13523			return [t, p, v];
13524		case 5:
13525			return [v, p, q];
13526	}
13527};
13528
13529convert$2.hsv.hsl = function (hsv) {
13530	var h = hsv[0];
13531	var s = hsv[1] / 100;
13532	var v = hsv[2] / 100;
13533	var vmin = Math.max(v, 0.01);
13534	var lmin;
13535	var sl;
13536	var l;
13537
13538	l = (2 - s) * v;
13539	lmin = (2 - s) * vmin;
13540	sl = s * vmin;
13541	sl /= (lmin <= 1) ? lmin : 2 - lmin;
13542	sl = sl || 0;
13543	l /= 2;
13544
13545	return [h, sl * 100, l * 100];
13546};
13547
13548// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
13549convert$2.hwb.rgb = function (hwb) {
13550	var h = hwb[0] / 360;
13551	var wh = hwb[1] / 100;
13552	var bl = hwb[2] / 100;
13553	var ratio = wh + bl;
13554	var i;
13555	var v;
13556	var f;
13557	var n;
13558
13559	// wh + bl cant be > 1
13560	if (ratio > 1) {
13561		wh /= ratio;
13562		bl /= ratio;
13563	}
13564
13565	i = Math.floor(6 * h);
13566	v = 1 - bl;
13567	f = 6 * h - i;
13568
13569	if ((i & 0x01) !== 0) {
13570		f = 1 - f;
13571	}
13572
13573	n = wh + f * (v - wh); // linear interpolation
13574
13575	var r;
13576	var g;
13577	var b;
13578	switch (i) {
13579		default:
13580		case 6:
13581		case 0: r = v; g = n; b = wh; break;
13582		case 1: r = n; g = v; b = wh; break;
13583		case 2: r = wh; g = v; b = n; break;
13584		case 3: r = wh; g = n; b = v; break;
13585		case 4: r = n; g = wh; b = v; break;
13586		case 5: r = v; g = wh; b = n; break;
13587	}
13588
13589	return [r * 255, g * 255, b * 255];
13590};
13591
13592convert$2.cmyk.rgb = function (cmyk) {
13593	var c = cmyk[0] / 100;
13594	var m = cmyk[1] / 100;
13595	var y = cmyk[2] / 100;
13596	var k = cmyk[3] / 100;
13597	var r;
13598	var g;
13599	var b;
13600
13601	r = 1 - Math.min(1, c * (1 - k) + k);
13602	g = 1 - Math.min(1, m * (1 - k) + k);
13603	b = 1 - Math.min(1, y * (1 - k) + k);
13604
13605	return [r * 255, g * 255, b * 255];
13606};
13607
13608convert$2.xyz.rgb = function (xyz) {
13609	var x = xyz[0] / 100;
13610	var y = xyz[1] / 100;
13611	var z = xyz[2] / 100;
13612	var r;
13613	var g;
13614	var b;
13615
13616	r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
13617	g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
13618	b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
13619
13620	// assume sRGB
13621	r = r > 0.0031308
13622		? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
13623		: r * 12.92;
13624
13625	g = g > 0.0031308
13626		? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
13627		: g * 12.92;
13628
13629	b = b > 0.0031308
13630		? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
13631		: b * 12.92;
13632
13633	r = Math.min(Math.max(0, r), 1);
13634	g = Math.min(Math.max(0, g), 1);
13635	b = Math.min(Math.max(0, b), 1);
13636
13637	return [r * 255, g * 255, b * 255];
13638};
13639
13640convert$2.xyz.lab = function (xyz) {
13641	var x = xyz[0];
13642	var y = xyz[1];
13643	var z = xyz[2];
13644	var l;
13645	var a;
13646	var b;
13647
13648	x /= 95.047;
13649	y /= 100;
13650	z /= 108.883;
13651
13652	x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
13653	y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
13654	z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
13655
13656	l = (116 * y) - 16;
13657	a = 500 * (x - y);
13658	b = 200 * (y - z);
13659
13660	return [l, a, b];
13661};
13662
13663convert$2.lab.xyz = function (lab) {
13664	var l = lab[0];
13665	var a = lab[1];
13666	var b = lab[2];
13667	var x;
13668	var y;
13669	var z;
13670
13671	y = (l + 16) / 116;
13672	x = a / 500 + y;
13673	z = y - b / 200;
13674
13675	var y2 = Math.pow(y, 3);
13676	var x2 = Math.pow(x, 3);
13677	var z2 = Math.pow(z, 3);
13678	y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
13679	x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
13680	z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
13681
13682	x *= 95.047;
13683	y *= 100;
13684	z *= 108.883;
13685
13686	return [x, y, z];
13687};
13688
13689convert$2.lab.lch = function (lab) {
13690	var l = lab[0];
13691	var a = lab[1];
13692	var b = lab[2];
13693	var hr;
13694	var h;
13695	var c;
13696
13697	hr = Math.atan2(b, a);
13698	h = hr * 360 / 2 / Math.PI;
13699
13700	if (h < 0) {
13701		h += 360;
13702	}
13703
13704	c = Math.sqrt(a * a + b * b);
13705
13706	return [l, c, h];
13707};
13708
13709convert$2.lch.lab = function (lch) {
13710	var l = lch[0];
13711	var c = lch[1];
13712	var h = lch[2];
13713	var a;
13714	var b;
13715	var hr;
13716
13717	hr = h / 360 * 2 * Math.PI;
13718	a = c * Math.cos(hr);
13719	b = c * Math.sin(hr);
13720
13721	return [l, a, b];
13722};
13723
13724convert$2.rgb.ansi16 = function (args) {
13725	var r = args[0];
13726	var g = args[1];
13727	var b = args[2];
13728	var value = 1 in arguments ? arguments[1] : convert$2.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
13729
13730	value = Math.round(value / 50);
13731
13732	if (value === 0) {
13733		return 30;
13734	}
13735
13736	var ansi = 30
13737		+ ((Math.round(b / 255) << 2)
13738		| (Math.round(g / 255) << 1)
13739		| Math.round(r / 255));
13740
13741	if (value === 2) {
13742		ansi += 60;
13743	}
13744
13745	return ansi;
13746};
13747
13748convert$2.hsv.ansi16 = function (args) {
13749	// optimization here; we already know the value and don't need to get
13750	// it converted for us.
13751	return convert$2.rgb.ansi16(convert$2.hsv.rgb(args), args[2]);
13752};
13753
13754convert$2.rgb.ansi256 = function (args) {
13755	var r = args[0];
13756	var g = args[1];
13757	var b = args[2];
13758
13759	// we use the extended greyscale palette here, with the exception of
13760	// black and white. normal palette only has 4 greyscale shades.
13761	if (r === g && g === b) {
13762		if (r < 8) {
13763			return 16;
13764		}
13765
13766		if (r > 248) {
13767			return 231;
13768		}
13769
13770		return Math.round(((r - 8) / 247) * 24) + 232;
13771	}
13772
13773	var ansi = 16
13774		+ (36 * Math.round(r / 255 * 5))
13775		+ (6 * Math.round(g / 255 * 5))
13776		+ Math.round(b / 255 * 5);
13777
13778	return ansi;
13779};
13780
13781convert$2.ansi16.rgb = function (args) {
13782	var color = args % 10;
13783
13784	// handle greyscale
13785	if (color === 0 || color === 7) {
13786		if (args > 50) {
13787			color += 3.5;
13788		}
13789
13790		color = color / 10.5 * 255;
13791
13792		return [color, color, color];
13793	}
13794
13795	var mult = (~~(args > 50) + 1) * 0.5;
13796	var r = ((color & 1) * mult) * 255;
13797	var g = (((color >> 1) & 1) * mult) * 255;
13798	var b = (((color >> 2) & 1) * mult) * 255;
13799
13800	return [r, g, b];
13801};
13802
13803convert$2.ansi256.rgb = function (args) {
13804	// handle greyscale
13805	if (args >= 232) {
13806		var c = (args - 232) * 10 + 8;
13807		return [c, c, c];
13808	}
13809
13810	args -= 16;
13811
13812	var rem;
13813	var r = Math.floor(args / 36) / 5 * 255;
13814	var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
13815	var b = (rem % 6) / 5 * 255;
13816
13817	return [r, g, b];
13818};
13819
13820convert$2.rgb.hex = function (args) {
13821	var integer = ((Math.round(args[0]) & 0xFF) << 16)
13822		+ ((Math.round(args[1]) & 0xFF) << 8)
13823		+ (Math.round(args[2]) & 0xFF);
13824
13825	var string = integer.toString(16).toUpperCase();
13826	return '000000'.substring(string.length) + string;
13827};
13828
13829convert$2.hex.rgb = function (args) {
13830	var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
13831	if (!match) {
13832		return [0, 0, 0];
13833	}
13834
13835	var colorString = match[0];
13836
13837	if (match[0].length === 3) {
13838		colorString = colorString.split('').map(function (char) {
13839			return char + char;
13840		}).join('');
13841	}
13842
13843	var integer = parseInt(colorString, 16);
13844	var r = (integer >> 16) & 0xFF;
13845	var g = (integer >> 8) & 0xFF;
13846	var b = integer & 0xFF;
13847
13848	return [r, g, b];
13849};
13850
13851convert$2.rgb.hcg = function (rgb) {
13852	var r = rgb[0] / 255;
13853	var g = rgb[1] / 255;
13854	var b = rgb[2] / 255;
13855	var max = Math.max(Math.max(r, g), b);
13856	var min = Math.min(Math.min(r, g), b);
13857	var chroma = (max - min);
13858	var grayscale;
13859	var hue;
13860
13861	if (chroma < 1) {
13862		grayscale = min / (1 - chroma);
13863	} else {
13864		grayscale = 0;
13865	}
13866
13867	if (chroma <= 0) {
13868		hue = 0;
13869	} else
13870	if (max === r) {
13871		hue = ((g - b) / chroma) % 6;
13872	} else
13873	if (max === g) {
13874		hue = 2 + (b - r) / chroma;
13875	} else {
13876		hue = 4 + (r - g) / chroma + 4;
13877	}
13878
13879	hue /= 6;
13880	hue %= 1;
13881
13882	return [hue * 360, chroma * 100, grayscale * 100];
13883};
13884
13885convert$2.hsl.hcg = function (hsl) {
13886	var s = hsl[1] / 100;
13887	var l = hsl[2] / 100;
13888	var c = 1;
13889	var f = 0;
13890
13891	if (l < 0.5) {
13892		c = 2.0 * s * l;
13893	} else {
13894		c = 2.0 * s * (1.0 - l);
13895	}
13896
13897	if (c < 1.0) {
13898		f = (l - 0.5 * c) / (1.0 - c);
13899	}
13900
13901	return [hsl[0], c * 100, f * 100];
13902};
13903
13904convert$2.hsv.hcg = function (hsv) {
13905	var s = hsv[1] / 100;
13906	var v = hsv[2] / 100;
13907
13908	var c = s * v;
13909	var f = 0;
13910
13911	if (c < 1.0) {
13912		f = (v - c) / (1 - c);
13913	}
13914
13915	return [hsv[0], c * 100, f * 100];
13916};
13917
13918convert$2.hcg.rgb = function (hcg) {
13919	var h = hcg[0] / 360;
13920	var c = hcg[1] / 100;
13921	var g = hcg[2] / 100;
13922
13923	if (c === 0.0) {
13924		return [g * 255, g * 255, g * 255];
13925	}
13926
13927	var pure = [0, 0, 0];
13928	var hi = (h % 1) * 6;
13929	var v = hi % 1;
13930	var w = 1 - v;
13931	var mg = 0;
13932
13933	switch (Math.floor(hi)) {
13934		case 0:
13935			pure[0] = 1; pure[1] = v; pure[2] = 0; break;
13936		case 1:
13937			pure[0] = w; pure[1] = 1; pure[2] = 0; break;
13938		case 2:
13939			pure[0] = 0; pure[1] = 1; pure[2] = v; break;
13940		case 3:
13941			pure[0] = 0; pure[1] = w; pure[2] = 1; break;
13942		case 4:
13943			pure[0] = v; pure[1] = 0; pure[2] = 1; break;
13944		default:
13945			pure[0] = 1; pure[1] = 0; pure[2] = w;
13946	}
13947
13948	mg = (1.0 - c) * g;
13949
13950	return [
13951		(c * pure[0] + mg) * 255,
13952		(c * pure[1] + mg) * 255,
13953		(c * pure[2] + mg) * 255
13954	];
13955};
13956
13957convert$2.hcg.hsv = function (hcg) {
13958	var c = hcg[1] / 100;
13959	var g = hcg[2] / 100;
13960
13961	var v = c + g * (1.0 - c);
13962	var f = 0;
13963
13964	if (v > 0.0) {
13965		f = c / v;
13966	}
13967
13968	return [hcg[0], f * 100, v * 100];
13969};
13970
13971convert$2.hcg.hsl = function (hcg) {
13972	var c = hcg[1] / 100;
13973	var g = hcg[2] / 100;
13974
13975	var l = g * (1.0 - c) + 0.5 * c;
13976	var s = 0;
13977
13978	if (l > 0.0 && l < 0.5) {
13979		s = c / (2 * l);
13980	} else
13981	if (l >= 0.5 && l < 1.0) {
13982		s = c / (2 * (1 - l));
13983	}
13984
13985	return [hcg[0], s * 100, l * 100];
13986};
13987
13988convert$2.hcg.hwb = function (hcg) {
13989	var c = hcg[1] / 100;
13990	var g = hcg[2] / 100;
13991	var v = c + g * (1.0 - c);
13992	return [hcg[0], (v - c) * 100, (1 - v) * 100];
13993};
13994
13995convert$2.hwb.hcg = function (hwb) {
13996	var w = hwb[1] / 100;
13997	var b = hwb[2] / 100;
13998	var v = 1 - b;
13999	var c = v - w;
14000	var g = 0;
14001
14002	if (c < 1) {
14003		g = (v - c) / (1 - c);
14004	}
14005
14006	return [hwb[0], c * 100, g * 100];
14007};
14008
14009convert$2.apple.rgb = function (apple) {
14010	return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
14011};
14012
14013convert$2.rgb.apple = function (rgb) {
14014	return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
14015};
14016
14017convert$2.gray.rgb = function (args) {
14018	return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
14019};
14020
14021convert$2.gray.hsl = convert$2.gray.hsv = function (args) {
14022	return [0, 0, args[0]];
14023};
14024
14025convert$2.gray.hwb = function (gray) {
14026	return [0, 100, gray[0]];
14027};
14028
14029convert$2.gray.cmyk = function (gray) {
14030	return [0, 0, 0, gray[0]];
14031};
14032
14033convert$2.gray.lab = function (gray) {
14034	return [gray[0], 0, 0];
14035};
14036
14037convert$2.gray.hex = function (gray) {
14038	var val = Math.round(gray[0] / 100 * 255) & 0xFF;
14039	var integer = (val << 16) + (val << 8) + val;
14040
14041	var string = integer.toString(16).toUpperCase();
14042	return '000000'.substring(string.length) + string;
14043};
14044
14045convert$2.rgb.gray = function (rgb) {
14046	var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
14047	return [val / 255 * 100];
14048};
14049
14050var conversions$1 = conversions$2.exports;
14051
14052/*
14053	this function routes a model to all other models.
14054
14055	all functions that are routed have a property `.conversion` attached
14056	to the returned synthetic function. This property is an array
14057	of strings, each with the steps in between the 'from' and 'to'
14058	color models (inclusive).
14059
14060	conversions that are not possible simply are not included.
14061*/
14062
14063function buildGraph() {
14064	var graph = {};
14065	// https://jsperf.com/object-keys-vs-for-in-with-closure/3
14066	var models = Object.keys(conversions$1);
14067
14068	for (var len = models.length, i = 0; i < len; i++) {
14069		graph[models[i]] = {
14070			// http://jsperf.com/1-vs-infinity
14071			// micro-opt, but this is simple.
14072			distance: -1,
14073			parent: null
14074		};
14075	}
14076
14077	return graph;
14078}
14079
14080// https://en.wikipedia.org/wiki/Breadth-first_search
14081function deriveBFS(fromModel) {
14082	var graph = buildGraph();
14083	var queue = [fromModel]; // unshift -> queue -> pop
14084
14085	graph[fromModel].distance = 0;
14086
14087	while (queue.length) {
14088		var current = queue.pop();
14089		var adjacents = Object.keys(conversions$1[current]);
14090
14091		for (var len = adjacents.length, i = 0; i < len; i++) {
14092			var adjacent = adjacents[i];
14093			var node = graph[adjacent];
14094
14095			if (node.distance === -1) {
14096				node.distance = graph[current].distance + 1;
14097				node.parent = current;
14098				queue.unshift(adjacent);
14099			}
14100		}
14101	}
14102
14103	return graph;
14104}
14105
14106function link$1(from, to) {
14107	return function (args) {
14108		return to(from(args));
14109	};
14110}
14111
14112function wrapConversion(toModel, graph) {
14113	var path = [graph[toModel].parent, toModel];
14114	var fn = conversions$1[graph[toModel].parent][toModel];
14115
14116	var cur = graph[toModel].parent;
14117	while (graph[cur].parent) {
14118		path.unshift(graph[cur].parent);
14119		fn = link$1(conversions$1[graph[cur].parent][cur], fn);
14120		cur = graph[cur].parent;
14121	}
14122
14123	fn.conversion = path;
14124	return fn;
14125}
14126
14127var route$1 = function (fromModel) {
14128	var graph = deriveBFS(fromModel);
14129	var conversion = {};
14130
14131	var models = Object.keys(graph);
14132	for (var len = models.length, i = 0; i < len; i++) {
14133		var toModel = models[i];
14134		var node = graph[toModel];
14135
14136		if (node.parent === null) {
14137			// no possible conversion, or this node is the source model.
14138			continue;
14139		}
14140
14141		conversion[toModel] = wrapConversion(toModel, graph);
14142	}
14143
14144	return conversion;
14145};
14146
14147var conversions = conversions$2.exports;
14148var route = route$1;
14149
14150var convert$1 = {};
14151
14152var models = Object.keys(conversions);
14153
14154function wrapRaw(fn) {
14155	var wrappedFn = function (args) {
14156		if (args === undefined || args === null) {
14157			return args;
14158		}
14159
14160		if (arguments.length > 1) {
14161			args = Array.prototype.slice.call(arguments);
14162		}
14163
14164		return fn(args);
14165	};
14166
14167	// preserve .conversion property if there is one
14168	if ('conversion' in fn) {
14169		wrappedFn.conversion = fn.conversion;
14170	}
14171
14172	return wrappedFn;
14173}
14174
14175function wrapRounded(fn) {
14176	var wrappedFn = function (args) {
14177		if (args === undefined || args === null) {
14178			return args;
14179		}
14180
14181		if (arguments.length > 1) {
14182			args = Array.prototype.slice.call(arguments);
14183		}
14184
14185		var result = fn(args);
14186
14187		// we're assuming the result is an array here.
14188		// see notice in conversions.js; don't use box types
14189		// in conversion functions.
14190		if (typeof result === 'object') {
14191			for (var len = result.length, i = 0; i < len; i++) {
14192				result[i] = Math.round(result[i]);
14193			}
14194		}
14195
14196		return result;
14197	};
14198
14199	// preserve .conversion property if there is one
14200	if ('conversion' in fn) {
14201		wrappedFn.conversion = fn.conversion;
14202	}
14203
14204	return wrappedFn;
14205}
14206
14207models.forEach(function (fromModel) {
14208	convert$1[fromModel] = {};
14209
14210	Object.defineProperty(convert$1[fromModel], 'channels', {value: conversions[fromModel].channels});
14211	Object.defineProperty(convert$1[fromModel], 'labels', {value: conversions[fromModel].labels});
14212
14213	var routes = route(fromModel);
14214	var routeModels = Object.keys(routes);
14215
14216	routeModels.forEach(function (toModel) {
14217		var fn = routes[toModel];
14218
14219		convert$1[fromModel][toModel] = wrapRounded(fn);
14220		convert$1[fromModel][toModel].raw = wrapRaw(fn);
14221	});
14222});
14223
14224var colorConvert = convert$1;
14225
14226(function (module) {
14227const colorConvert$1 = colorConvert;
14228
14229const wrapAnsi16 = (fn, offset) => function () {
14230	const code = fn.apply(colorConvert$1, arguments);
14231	return `\u001B[${code + offset}m`;
14232};
14233
14234const wrapAnsi256 = (fn, offset) => function () {
14235	const code = fn.apply(colorConvert$1, arguments);
14236	return `\u001B[${38 + offset};5;${code}m`;
14237};
14238
14239const wrapAnsi16m = (fn, offset) => function () {
14240	const rgb = fn.apply(colorConvert$1, arguments);
14241	return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
14242};
14243
14244function assembleStyles() {
14245	const codes = new Map();
14246	const styles = {
14247		modifier: {
14248			reset: [0, 0],
14249			// 21 isn't widely supported and 22 does the same thing
14250			bold: [1, 22],
14251			dim: [2, 22],
14252			italic: [3, 23],
14253			underline: [4, 24],
14254			inverse: [7, 27],
14255			hidden: [8, 28],
14256			strikethrough: [9, 29]
14257		},
14258		color: {
14259			black: [30, 39],
14260			red: [31, 39],
14261			green: [32, 39],
14262			yellow: [33, 39],
14263			blue: [34, 39],
14264			magenta: [35, 39],
14265			cyan: [36, 39],
14266			white: [37, 39],
14267			gray: [90, 39],
14268
14269			// Bright color
14270			redBright: [91, 39],
14271			greenBright: [92, 39],
14272			yellowBright: [93, 39],
14273			blueBright: [94, 39],
14274			magentaBright: [95, 39],
14275			cyanBright: [96, 39],
14276			whiteBright: [97, 39]
14277		},
14278		bgColor: {
14279			bgBlack: [40, 49],
14280			bgRed: [41, 49],
14281			bgGreen: [42, 49],
14282			bgYellow: [43, 49],
14283			bgBlue: [44, 49],
14284			bgMagenta: [45, 49],
14285			bgCyan: [46, 49],
14286			bgWhite: [47, 49],
14287
14288			// Bright color
14289			bgBlackBright: [100, 49],
14290			bgRedBright: [101, 49],
14291			bgGreenBright: [102, 49],
14292			bgYellowBright: [103, 49],
14293			bgBlueBright: [104, 49],
14294			bgMagentaBright: [105, 49],
14295			bgCyanBright: [106, 49],
14296			bgWhiteBright: [107, 49]
14297		}
14298	};
14299
14300	// Fix humans
14301	styles.color.grey = styles.color.gray;
14302
14303	for (const groupName of Object.keys(styles)) {
14304		const group = styles[groupName];
14305
14306		for (const styleName of Object.keys(group)) {
14307			const style = group[styleName];
14308
14309			styles[styleName] = {
14310				open: `\u001B[${style[0]}m`,
14311				close: `\u001B[${style[1]}m`
14312			};
14313
14314			group[styleName] = styles[styleName];
14315
14316			codes.set(style[0], style[1]);
14317		}
14318
14319		Object.defineProperty(styles, groupName, {
14320			value: group,
14321			enumerable: false
14322		});
14323
14324		Object.defineProperty(styles, 'codes', {
14325			value: codes,
14326			enumerable: false
14327		});
14328	}
14329
14330	const ansi2ansi = n => n;
14331	const rgb2rgb = (r, g, b) => [r, g, b];
14332
14333	styles.color.close = '\u001B[39m';
14334	styles.bgColor.close = '\u001B[49m';
14335
14336	styles.color.ansi = {
14337		ansi: wrapAnsi16(ansi2ansi, 0)
14338	};
14339	styles.color.ansi256 = {
14340		ansi256: wrapAnsi256(ansi2ansi, 0)
14341	};
14342	styles.color.ansi16m = {
14343		rgb: wrapAnsi16m(rgb2rgb, 0)
14344	};
14345
14346	styles.bgColor.ansi = {
14347		ansi: wrapAnsi16(ansi2ansi, 10)
14348	};
14349	styles.bgColor.ansi256 = {
14350		ansi256: wrapAnsi256(ansi2ansi, 10)
14351	};
14352	styles.bgColor.ansi16m = {
14353		rgb: wrapAnsi16m(rgb2rgb, 10)
14354	};
14355
14356	for (let key of Object.keys(colorConvert$1)) {
14357		if (typeof colorConvert$1[key] !== 'object') {
14358			continue;
14359		}
14360
14361		const suite = colorConvert$1[key];
14362
14363		if (key === 'ansi16') {
14364			key = 'ansi';
14365		}
14366
14367		if ('ansi16' in suite) {
14368			styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
14369			styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
14370		}
14371
14372		if ('ansi256' in suite) {
14373			styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
14374			styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
14375		}
14376
14377		if ('rgb' in suite) {
14378			styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
14379			styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
14380		}
14381	}
14382
14383	return styles;
14384}
14385
14386// Make the export immutable
14387Object.defineProperty(module, 'exports', {
14388	enumerable: true,
14389	get: assembleStyles
14390});
14391}(ansiStyles));
14392
14393var hasFlag$2 = (flag, argv) => {
14394	argv = argv || process.argv;
14395	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
14396	const pos = argv.indexOf(prefix + flag);
14397	const terminatorPos = argv.indexOf('--');
14398	return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
14399};
14400
14401const os$1 = require$$0$2;
14402const hasFlag$1 = hasFlag$2;
14403
14404const env$1 = process.env;
14405
14406let forceColor;
14407if (hasFlag$1('no-color') ||
14408	hasFlag$1('no-colors') ||
14409	hasFlag$1('color=false')) {
14410	forceColor = false;
14411} else if (hasFlag$1('color') ||
14412	hasFlag$1('colors') ||
14413	hasFlag$1('color=true') ||
14414	hasFlag$1('color=always')) {
14415	forceColor = true;
14416}
14417if ('FORCE_COLOR' in env$1) {
14418	forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0;
14419}
14420
14421function translateLevel$1(level) {
14422	if (level === 0) {
14423		return false;
14424	}
14425
14426	return {
14427		level,
14428		hasBasic: true,
14429		has256: level >= 2,
14430		has16m: level >= 3
14431	};
14432}
14433
14434function supportsColor$1(stream) {
14435	if (forceColor === false) {
14436		return 0;
14437	}
14438
14439	if (hasFlag$1('color=16m') ||
14440		hasFlag$1('color=full') ||
14441		hasFlag$1('color=truecolor')) {
14442		return 3;
14443	}
14444
14445	if (hasFlag$1('color=256')) {
14446		return 2;
14447	}
14448
14449	if (stream && !stream.isTTY && forceColor !== true) {
14450		return 0;
14451	}
14452
14453	const min = forceColor ? 1 : 0;
14454
14455	if (process.platform === 'win32') {
14456		// Node.js 7.5.0 is the first version of Node.js to include a patch to
14457		// libuv that enables 256 color output on Windows. Anything earlier and it
14458		// won't work. However, here we target Node.js 8 at minimum as it is an LTS
14459		// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
14460		// release that supports 256 colors. Windows 10 build 14931 is the first release
14461		// that supports 16m/TrueColor.
14462		const osRelease = os$1.release().split('.');
14463		if (
14464			Number(process.versions.node.split('.')[0]) >= 8 &&
14465			Number(osRelease[0]) >= 10 &&
14466			Number(osRelease[2]) >= 10586
14467		) {
14468			return Number(osRelease[2]) >= 14931 ? 3 : 2;
14469		}
14470
14471		return 1;
14472	}
14473
14474	if ('CI' in env$1) {
14475		if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
14476			return 1;
14477		}
14478
14479		return min;
14480	}
14481
14482	if ('TEAMCITY_VERSION' in env$1) {
14483		return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
14484	}
14485
14486	if (env$1.COLORTERM === 'truecolor') {
14487		return 3;
14488	}
14489
14490	if ('TERM_PROGRAM' in env$1) {
14491		const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
14492
14493		switch (env$1.TERM_PROGRAM) {
14494			case 'iTerm.app':
14495				return version >= 3 ? 3 : 2;
14496			case 'Apple_Terminal':
14497				return 2;
14498			// No default
14499		}
14500	}
14501
14502	if (/-256(color)?$/i.test(env$1.TERM)) {
14503		return 2;
14504	}
14505
14506	if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
14507		return 1;
14508	}
14509
14510	if ('COLORTERM' in env$1) {
14511		return 1;
14512	}
14513
14514	if (env$1.TERM === 'dumb') {
14515		return min;
14516	}
14517
14518	return min;
14519}
14520
14521function getSupportLevel(stream) {
14522	const level = supportsColor$1(stream);
14523	return translateLevel$1(level);
14524}
14525
14526var supportsColor_1 = {
14527	supportsColor: getSupportLevel,
14528	stdout: getSupportLevel(process.stdout),
14529	stderr: getSupportLevel(process.stderr)
14530};
14531
14532const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
14533const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
14534const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
14535const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
14536
14537const ESCAPES = new Map([
14538	['n', '\n'],
14539	['r', '\r'],
14540	['t', '\t'],
14541	['b', '\b'],
14542	['f', '\f'],
14543	['v', '\v'],
14544	['0', '\0'],
14545	['\\', '\\'],
14546	['e', '\u001B'],
14547	['a', '\u0007']
14548]);
14549
14550function unescape(c) {
14551	if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
14552		return String.fromCharCode(parseInt(c.slice(1), 16));
14553	}
14554
14555	return ESCAPES.get(c) || c;
14556}
14557
14558function parseArguments(name, args) {
14559	const results = [];
14560	const chunks = args.trim().split(/\s*,\s*/g);
14561	let matches;
14562
14563	for (const chunk of chunks) {
14564		if (!isNaN(chunk)) {
14565			results.push(Number(chunk));
14566		} else if ((matches = chunk.match(STRING_REGEX))) {
14567			results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
14568		} else {
14569			throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
14570		}
14571	}
14572
14573	return results;
14574}
14575
14576function parseStyle(style) {
14577	STYLE_REGEX.lastIndex = 0;
14578
14579	const results = [];
14580	let matches;
14581
14582	while ((matches = STYLE_REGEX.exec(style)) !== null) {
14583		const name = matches[1];
14584
14585		if (matches[2]) {
14586			const args = parseArguments(name, matches[2]);
14587			results.push([name].concat(args));
14588		} else {
14589			results.push([name]);
14590		}
14591	}
14592
14593	return results;
14594}
14595
14596function buildStyle(chalk, styles) {
14597	const enabled = {};
14598
14599	for (const layer of styles) {
14600		for (const style of layer.styles) {
14601			enabled[style[0]] = layer.inverse ? null : style.slice(1);
14602		}
14603	}
14604
14605	let current = chalk;
14606	for (const styleName of Object.keys(enabled)) {
14607		if (Array.isArray(enabled[styleName])) {
14608			if (!(styleName in current)) {
14609				throw new Error(`Unknown Chalk style: ${styleName}`);
14610			}
14611
14612			if (enabled[styleName].length > 0) {
14613				current = current[styleName].apply(current, enabled[styleName]);
14614			} else {
14615				current = current[styleName];
14616			}
14617		}
14618	}
14619
14620	return current;
14621}
14622
14623var templates = (chalk, tmp) => {
14624	const styles = [];
14625	const chunks = [];
14626	let chunk = [];
14627
14628	// eslint-disable-next-line max-params
14629	tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
14630		if (escapeChar) {
14631			chunk.push(unescape(escapeChar));
14632		} else if (style) {
14633			const str = chunk.join('');
14634			chunk = [];
14635			chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
14636			styles.push({inverse, styles: parseStyle(style)});
14637		} else if (close) {
14638			if (styles.length === 0) {
14639				throw new Error('Found extraneous } in Chalk template literal');
14640			}
14641
14642			chunks.push(buildStyle(chalk, styles)(chunk.join('')));
14643			chunk = [];
14644			styles.pop();
14645		} else {
14646			chunk.push(chr);
14647		}
14648	});
14649
14650	chunks.push(chunk.join(''));
14651
14652	if (styles.length > 0) {
14653		const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
14654		throw new Error(errMsg);
14655	}
14656
14657	return chunks.join('');
14658};
14659
14660(function (module) {
14661const escapeStringRegexp = escapeStringRegexp$1;
14662const ansiStyles$1 = ansiStyles.exports;
14663const stdoutColor = supportsColor_1.stdout;
14664
14665const template = templates;
14666
14667const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
14668
14669// `supportsColor.level` → `ansiStyles.color[name]` mapping
14670const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
14671
14672// `color-convert` models to exclude from the Chalk API due to conflicts and such
14673const skipModels = new Set(['gray']);
14674
14675const styles = Object.create(null);
14676
14677function applyOptions(obj, options) {
14678	options = options || {};
14679
14680	// Detect level if not set manually
14681	const scLevel = stdoutColor ? stdoutColor.level : 0;
14682	obj.level = options.level === undefined ? scLevel : options.level;
14683	obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
14684}
14685
14686function Chalk(options) {
14687	// We check for this.template here since calling `chalk.constructor()`
14688	// by itself will have a `this` of a previously constructed chalk object
14689	if (!this || !(this instanceof Chalk) || this.template) {
14690		const chalk = {};
14691		applyOptions(chalk, options);
14692
14693		chalk.template = function () {
14694			const args = [].slice.call(arguments);
14695			return chalkTag.apply(null, [chalk.template].concat(args));
14696		};
14697
14698		Object.setPrototypeOf(chalk, Chalk.prototype);
14699		Object.setPrototypeOf(chalk.template, chalk);
14700
14701		chalk.template.constructor = Chalk;
14702
14703		return chalk.template;
14704	}
14705
14706	applyOptions(this, options);
14707}
14708
14709// Use bright blue on Windows as the normal blue color is illegible
14710if (isSimpleWindowsTerm) {
14711	ansiStyles$1.blue.open = '\u001B[94m';
14712}
14713
14714for (const key of Object.keys(ansiStyles$1)) {
14715	ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles$1[key].close), 'g');
14716
14717	styles[key] = {
14718		get() {
14719			const codes = ansiStyles$1[key];
14720			return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
14721		}
14722	};
14723}
14724
14725styles.visible = {
14726	get() {
14727		return build.call(this, this._styles || [], true, 'visible');
14728	}
14729};
14730
14731ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles$1.color.close), 'g');
14732for (const model of Object.keys(ansiStyles$1.color.ansi)) {
14733	if (skipModels.has(model)) {
14734		continue;
14735	}
14736
14737	styles[model] = {
14738		get() {
14739			const level = this.level;
14740			return function () {
14741				const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments);
14742				const codes = {
14743					open,
14744					close: ansiStyles$1.color.close,
14745					closeRe: ansiStyles$1.color.closeRe
14746				};
14747				return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
14748			};
14749		}
14750	};
14751}
14752
14753ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles$1.bgColor.close), 'g');
14754for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) {
14755	if (skipModels.has(model)) {
14756		continue;
14757	}
14758
14759	const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
14760	styles[bgModel] = {
14761		get() {
14762			const level = this.level;
14763			return function () {
14764				const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments);
14765				const codes = {
14766					open,
14767					close: ansiStyles$1.bgColor.close,
14768					closeRe: ansiStyles$1.bgColor.closeRe
14769				};
14770				return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
14771			};
14772		}
14773	};
14774}
14775
14776const proto = Object.defineProperties(() => {}, styles);
14777
14778function build(_styles, _empty, key) {
14779	const builder = function () {
14780		return applyStyle.apply(builder, arguments);
14781	};
14782
14783	builder._styles = _styles;
14784	builder._empty = _empty;
14785
14786	const self = this;
14787
14788	Object.defineProperty(builder, 'level', {
14789		enumerable: true,
14790		get() {
14791			return self.level;
14792		},
14793		set(level) {
14794			self.level = level;
14795		}
14796	});
14797
14798	Object.defineProperty(builder, 'enabled', {
14799		enumerable: true,
14800		get() {
14801			return self.enabled;
14802		},
14803		set(enabled) {
14804			self.enabled = enabled;
14805		}
14806	});
14807
14808	// See below for fix regarding invisible grey/dim combination on Windows
14809	builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
14810
14811	// `__proto__` is used because we must return a function, but there is
14812	// no way to create a function with a different prototype
14813	builder.__proto__ = proto; // eslint-disable-line no-proto
14814
14815	return builder;
14816}
14817
14818function applyStyle() {
14819	// Support varags, but simply cast to string in case there's only one arg
14820	const args = arguments;
14821	const argsLen = args.length;
14822	let str = String(arguments[0]);
14823
14824	if (argsLen === 0) {
14825		return '';
14826	}
14827
14828	if (argsLen > 1) {
14829		// Don't slice `arguments`, it prevents V8 optimizations
14830		for (let a = 1; a < argsLen; a++) {
14831			str += ' ' + args[a];
14832		}
14833	}
14834
14835	if (!this.enabled || this.level <= 0 || !str) {
14836		return this._empty ? '' : str;
14837	}
14838
14839	// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
14840	// see https://github.com/chalk/chalk/issues/58
14841	// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
14842	const originalDim = ansiStyles$1.dim.open;
14843	if (isSimpleWindowsTerm && this.hasGrey) {
14844		ansiStyles$1.dim.open = '';
14845	}
14846
14847	for (const code of this._styles.slice().reverse()) {
14848		// Replace any instances already present with a re-opening code
14849		// otherwise only the part of the string until said closing code
14850		// will be colored, and the rest will simply be 'plain'.
14851		str = code.open + str.replace(code.closeRe, code.open) + code.close;
14852
14853		// Close the styling before a linebreak and reopen
14854		// after next line to fix a bleed issue on macOS
14855		// https://github.com/chalk/chalk/pull/92
14856		str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
14857	}
14858
14859	// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
14860	ansiStyles$1.dim.open = originalDim;
14861
14862	return str;
14863}
14864
14865function chalkTag(chalk, strings) {
14866	if (!Array.isArray(strings)) {
14867		// If chalk() was called by itself or with a string,
14868		// return the string itself as a string.
14869		return [].slice.call(arguments, 1).join(' ');
14870	}
14871
14872	const args = [].slice.call(arguments, 2);
14873	const parts = [strings.raw[0]];
14874
14875	for (let i = 1; i < strings.length; i++) {
14876		parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
14877		parts.push(String(strings.raw[i]));
14878	}
14879
14880	return template(chalk, parts.join(''));
14881}
14882
14883Object.defineProperties(Chalk.prototype, styles);
14884
14885module.exports = Chalk(); // eslint-disable-line new-cap
14886module.exports.supportsColor = stdoutColor;
14887module.exports.default = module.exports; // For TypeScript
14888}(chalk));
14889
14890Object.defineProperty(lib$3, "__esModule", {
14891  value: true
14892});
14893lib$3.shouldHighlight = shouldHighlight;
14894lib$3.getChalk = getChalk;
14895lib$3.default = highlight;
14896
14897var _jsTokens = jsTokens;
14898
14899var _helperValidatorIdentifier = lib$2;
14900
14901var _chalk = chalk.exports;
14902
14903const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
14904
14905function getDefs$1(chalk) {
14906  return {
14907    keyword: chalk.cyan,
14908    capitalized: chalk.yellow,
14909    jsxIdentifier: chalk.yellow,
14910    punctuator: chalk.yellow,
14911    number: chalk.magenta,
14912    string: chalk.green,
14913    regex: chalk.magenta,
14914    comment: chalk.grey,
14915    invalid: chalk.white.bgRed.bold
14916  };
14917}
14918
14919const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
14920const BRACKET = /^[()[\]{}]$/;
14921let tokenize;
14922{
14923  const JSX_TAG = /^[a-z][\w-]*$/i;
14924
14925  const getTokenType = function (token, offset, text) {
14926    if (token.type === "name") {
14927      if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isStrictReservedWord)(token.value, true) || sometimesKeywords.has(token.value)) {
14928        return "keyword";
14929      }
14930
14931      if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
14932        return "jsxIdentifier";
14933      }
14934
14935      if (token.value[0] !== token.value[0].toLowerCase()) {
14936        return "capitalized";
14937      }
14938    }
14939
14940    if (token.type === "punctuator" && BRACKET.test(token.value)) {
14941      return "bracket";
14942    }
14943
14944    if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
14945      return "punctuator";
14946    }
14947
14948    return token.type;
14949  };
14950
14951  tokenize = function* (text) {
14952    let match;
14953
14954    while (match = _jsTokens.default.exec(text)) {
14955      const token = _jsTokens.matchToToken(match);
14956
14957      yield {
14958        type: getTokenType(token, match.index, text),
14959        value: token.value
14960      };
14961    }
14962  };
14963}
14964
14965function highlightTokens(defs, text) {
14966  let highlighted = "";
14967
14968  for (const {
14969    type,
14970    value
14971  } of tokenize(text)) {
14972    const colorize = defs[type];
14973
14974    if (colorize) {
14975      highlighted += value.split(NEWLINE$1).map(str => colorize(str)).join("\n");
14976    } else {
14977      highlighted += value;
14978    }
14979  }
14980
14981  return highlighted;
14982}
14983
14984function shouldHighlight(options) {
14985  return !!_chalk.supportsColor || options.forceColor;
14986}
14987
14988function getChalk(options) {
14989  return options.forceColor ? new _chalk.constructor({
14990    enabled: true,
14991    level: 1
14992  }) : _chalk;
14993}
14994
14995function highlight(code, options = {}) {
14996  if (shouldHighlight(options)) {
14997    const chalk = getChalk(options);
14998    const defs = getDefs$1(chalk);
14999    return highlightTokens(defs, code);
15000  } else {
15001    return code;
15002  }
15003}
15004
15005Object.defineProperty(lib$4, "__esModule", {
15006  value: true
15007});
15008lib$4.codeFrameColumns = codeFrameColumns$1;
15009lib$4.default = _default;
15010
15011var _highlight = lib$3;
15012
15013let deprecationWarningShown = false;
15014
15015function getDefs(chalk) {
15016  return {
15017    gutter: chalk.grey,
15018    marker: chalk.red.bold,
15019    message: chalk.red.bold
15020  };
15021}
15022
15023const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
15024
15025function getMarkerLines(loc, source, opts) {
15026  const startLoc = Object.assign({
15027    column: 0,
15028    line: -1
15029  }, loc.start);
15030  const endLoc = Object.assign({}, startLoc, loc.end);
15031  const {
15032    linesAbove = 2,
15033    linesBelow = 3
15034  } = opts || {};
15035  const startLine = startLoc.line;
15036  const startColumn = startLoc.column;
15037  const endLine = endLoc.line;
15038  const endColumn = endLoc.column;
15039  let start = Math.max(startLine - (linesAbove + 1), 0);
15040  let end = Math.min(source.length, endLine + linesBelow);
15041
15042  if (startLine === -1) {
15043    start = 0;
15044  }
15045
15046  if (endLine === -1) {
15047    end = source.length;
15048  }
15049
15050  const lineDiff = endLine - startLine;
15051  const markerLines = {};
15052
15053  if (lineDiff) {
15054    for (let i = 0; i <= lineDiff; i++) {
15055      const lineNumber = i + startLine;
15056
15057      if (!startColumn) {
15058        markerLines[lineNumber] = true;
15059      } else if (i === 0) {
15060        const sourceLength = source[lineNumber - 1].length;
15061        markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
15062      } else if (i === lineDiff) {
15063        markerLines[lineNumber] = [0, endColumn];
15064      } else {
15065        const sourceLength = source[lineNumber - i].length;
15066        markerLines[lineNumber] = [0, sourceLength];
15067      }
15068    }
15069  } else {
15070    if (startColumn === endColumn) {
15071      if (startColumn) {
15072        markerLines[startLine] = [startColumn, 0];
15073      } else {
15074        markerLines[startLine] = true;
15075      }
15076    } else {
15077      markerLines[startLine] = [startColumn, endColumn - startColumn];
15078    }
15079  }
15080
15081  return {
15082    start,
15083    end,
15084    markerLines
15085  };
15086}
15087
15088function codeFrameColumns$1(rawLines, loc, opts = {}) {
15089  const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
15090  const chalk = (0, _highlight.getChalk)(opts);
15091  const defs = getDefs(chalk);
15092
15093  const maybeHighlight = (chalkFn, string) => {
15094    return highlighted ? chalkFn(string) : string;
15095  };
15096
15097  const lines = rawLines.split(NEWLINE);
15098  const {
15099    start,
15100    end,
15101    markerLines
15102  } = getMarkerLines(loc, lines, opts);
15103  const hasColumns = loc.start && typeof loc.start.column === "number";
15104  const numberMaxWidth = String(end).length;
15105  const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
15106  let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
15107    const number = start + 1 + index;
15108    const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
15109    const gutter = ` ${paddedNumber} |`;
15110    const hasMarker = markerLines[number];
15111    const lastMarkerLine = !markerLines[number + 1];
15112
15113    if (hasMarker) {
15114      let markerLine = "";
15115
15116      if (Array.isArray(hasMarker)) {
15117        const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
15118        const numberOfMarkers = hasMarker[1] || 1;
15119        markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
15120
15121        if (lastMarkerLine && opts.message) {
15122          markerLine += " " + maybeHighlight(defs.message, opts.message);
15123        }
15124      }
15125
15126      return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
15127    } else {
15128      return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`;
15129    }
15130  }).join("\n");
15131
15132  if (opts.message && !hasColumns) {
15133    frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
15134  }
15135
15136  if (highlighted) {
15137    return chalk.reset(frame);
15138  } else {
15139    return frame;
15140  }
15141}
15142
15143function _default(rawLines, lineNumber, colNumber, opts = {}) {
15144  if (!deprecationWarningShown) {
15145    deprecationWarningShown = true;
15146    const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
15147
15148    if (process.emitWarning) {
15149      process.emitWarning(message, "DeprecationWarning");
15150    } else {
15151      const deprecationError = new Error(message);
15152      deprecationError.name = "DeprecationWarning";
15153      console.warn(new Error(message));
15154    }
15155  }
15156
15157  colNumber = Math.max(colNumber, 0);
15158  const location = {
15159    start: {
15160      column: colNumber,
15161      line: lineNumber
15162    }
15163  };
15164  return codeFrameColumns$1(rawLines, location, opts);
15165}
15166
15167const errorEx = errorEx_1;
15168const fallback = jsonParseEvenBetterErrors;
15169const {default: LinesAndColumns} = require$$2;
15170const {codeFrameColumns} = lib$4;
15171
15172const JSONError = errorEx('JSONError', {
15173	fileName: errorEx.append('in %s'),
15174	codeFrame: errorEx.append('\n\n%s\n')
15175});
15176
15177const parseJson = (string, reviver, filename) => {
15178	if (typeof reviver === 'string') {
15179		filename = reviver;
15180		reviver = null;
15181	}
15182
15183	try {
15184		try {
15185			return JSON.parse(string, reviver);
15186		} catch (error) {
15187			fallback(string, reviver);
15188			throw error;
15189		}
15190	} catch (error) {
15191		error.message = error.message.replace(/\n/g, '');
15192		const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/);
15193
15194		const jsonError = new JSONError(error);
15195		if (filename) {
15196			jsonError.fileName = filename;
15197		}
15198
15199		if (indexMatch && indexMatch.length > 0) {
15200			const lines = new LinesAndColumns(string);
15201			const index = Number(indexMatch[1]);
15202			const location = lines.locationForIndex(index);
15203
15204			const codeFrame = codeFrameColumns(
15205				string,
15206				{start: {line: location.line + 1, column: location.column + 1}},
15207				{highlightCode: true}
15208			);
15209
15210			jsonError.codeFrame = codeFrame;
15211		}
15212
15213		throw jsonError;
15214	}
15215};
15216
15217parseJson.JSONError = JSONError;
15218
15219var parseJson_1 = parseJson;
15220
15221var src = {exports: {}};
15222
15223var browser = {exports: {}};
15224
15225/**
15226 * Helpers.
15227 */
15228
15229var s = 1000;
15230var m = s * 60;
15231var h = m * 60;
15232var d = h * 24;
15233var w = d * 7;
15234var y = d * 365.25;
15235
15236/**
15237 * Parse or format the given `val`.
15238 *
15239 * Options:
15240 *
15241 *  - `long` verbose formatting [false]
15242 *
15243 * @param {String|Number} val
15244 * @param {Object} [options]
15245 * @throws {Error} throw an error if val is not a non-empty string or a number
15246 * @return {String|Number}
15247 * @api public
15248 */
15249
15250var ms = function(val, options) {
15251  options = options || {};
15252  var type = typeof val;
15253  if (type === 'string' && val.length > 0) {
15254    return parse$a(val);
15255  } else if (type === 'number' && isFinite(val)) {
15256    return options.long ? fmtLong(val) : fmtShort(val);
15257  }
15258  throw new Error(
15259    'val is not a non-empty string or a valid number. val=' +
15260      JSON.stringify(val)
15261  );
15262};
15263
15264/**
15265 * Parse the given `str` and return milliseconds.
15266 *
15267 * @param {String} str
15268 * @return {Number}
15269 * @api private
15270 */
15271
15272function parse$a(str) {
15273  str = String(str);
15274  if (str.length > 100) {
15275    return;
15276  }
15277  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
15278    str
15279  );
15280  if (!match) {
15281    return;
15282  }
15283  var n = parseFloat(match[1]);
15284  var type = (match[2] || 'ms').toLowerCase();
15285  switch (type) {
15286    case 'years':
15287    case 'year':
15288    case 'yrs':
15289    case 'yr':
15290    case 'y':
15291      return n * y;
15292    case 'weeks':
15293    case 'week':
15294    case 'w':
15295      return n * w;
15296    case 'days':
15297    case 'day':
15298    case 'd':
15299      return n * d;
15300    case 'hours':
15301    case 'hour':
15302    case 'hrs':
15303    case 'hr':
15304    case 'h':
15305      return n * h;
15306    case 'minutes':
15307    case 'minute':
15308    case 'mins':
15309    case 'min':
15310    case 'm':
15311      return n * m;
15312    case 'seconds':
15313    case 'second':
15314    case 'secs':
15315    case 'sec':
15316    case 's':
15317      return n * s;
15318    case 'milliseconds':
15319    case 'millisecond':
15320    case 'msecs':
15321    case 'msec':
15322    case 'ms':
15323      return n;
15324    default:
15325      return undefined;
15326  }
15327}
15328
15329/**
15330 * Short format for `ms`.
15331 *
15332 * @param {Number} ms
15333 * @return {String}
15334 * @api private
15335 */
15336
15337function fmtShort(ms) {
15338  var msAbs = Math.abs(ms);
15339  if (msAbs >= d) {
15340    return Math.round(ms / d) + 'd';
15341  }
15342  if (msAbs >= h) {
15343    return Math.round(ms / h) + 'h';
15344  }
15345  if (msAbs >= m) {
15346    return Math.round(ms / m) + 'm';
15347  }
15348  if (msAbs >= s) {
15349    return Math.round(ms / s) + 's';
15350  }
15351  return ms + 'ms';
15352}
15353
15354/**
15355 * Long format for `ms`.
15356 *
15357 * @param {Number} ms
15358 * @return {String}
15359 * @api private
15360 */
15361
15362function fmtLong(ms) {
15363  var msAbs = Math.abs(ms);
15364  if (msAbs >= d) {
15365    return plural$1(ms, msAbs, d, 'day');
15366  }
15367  if (msAbs >= h) {
15368    return plural$1(ms, msAbs, h, 'hour');
15369  }
15370  if (msAbs >= m) {
15371    return plural$1(ms, msAbs, m, 'minute');
15372  }
15373  if (msAbs >= s) {
15374    return plural$1(ms, msAbs, s, 'second');
15375  }
15376  return ms + ' ms';
15377}
15378
15379/**
15380 * Pluralization helper.
15381 */
15382
15383function plural$1(ms, msAbs, n, name) {
15384  var isPlural = msAbs >= n * 1.5;
15385  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
15386}
15387
15388/**
15389 * This is the common logic for both the Node.js and web browser
15390 * implementations of `debug()`.
15391 */
15392
15393function setup(env) {
15394	createDebug.debug = createDebug;
15395	createDebug.default = createDebug;
15396	createDebug.coerce = coerce;
15397	createDebug.disable = disable;
15398	createDebug.enable = enable;
15399	createDebug.enabled = enabled;
15400	createDebug.humanize = ms;
15401	createDebug.destroy = destroy;
15402
15403	Object.keys(env).forEach(key => {
15404		createDebug[key] = env[key];
15405	});
15406
15407	/**
15408	* The currently active debug mode names, and names to skip.
15409	*/
15410
15411	createDebug.names = [];
15412	createDebug.skips = [];
15413
15414	/**
15415	* Map of special "%n" handling functions, for the debug "format" argument.
15416	*
15417	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
15418	*/
15419	createDebug.formatters = {};
15420
15421	/**
15422	* Selects a color for a debug namespace
15423	* @param {String} namespace The namespace string for the for the debug instance to be colored
15424	* @return {Number|String} An ANSI color code for the given namespace
15425	* @api private
15426	*/
15427	function selectColor(namespace) {
15428		let hash = 0;
15429
15430		for (let i = 0; i < namespace.length; i++) {
15431			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
15432			hash |= 0; // Convert to 32bit integer
15433		}
15434
15435		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
15436	}
15437	createDebug.selectColor = selectColor;
15438
15439	/**
15440	* Create a debugger with the given `namespace`.
15441	*
15442	* @param {String} namespace
15443	* @return {Function}
15444	* @api public
15445	*/
15446	function createDebug(namespace) {
15447		let prevTime;
15448		let enableOverride = null;
15449		let namespacesCache;
15450		let enabledCache;
15451
15452		function debug(...args) {
15453			// Disabled?
15454			if (!debug.enabled) {
15455				return;
15456			}
15457
15458			const self = debug;
15459
15460			// Set `diff` timestamp
15461			const curr = Number(new Date());
15462			const ms = curr - (prevTime || curr);
15463			self.diff = ms;
15464			self.prev = prevTime;
15465			self.curr = curr;
15466			prevTime = curr;
15467
15468			args[0] = createDebug.coerce(args[0]);
15469
15470			if (typeof args[0] !== 'string') {
15471				// Anything else let's inspect with %O
15472				args.unshift('%O');
15473			}
15474
15475			// Apply any `formatters` transformations
15476			let index = 0;
15477			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
15478				// If we encounter an escaped % then don't increase the array index
15479				if (match === '%%') {
15480					return '%';
15481				}
15482				index++;
15483				const formatter = createDebug.formatters[format];
15484				if (typeof formatter === 'function') {
15485					const val = args[index];
15486					match = formatter.call(self, val);
15487
15488					// Now we need to remove `args[index]` since it's inlined in the `format`
15489					args.splice(index, 1);
15490					index--;
15491				}
15492				return match;
15493			});
15494
15495			// Apply env-specific formatting (colors, etc.)
15496			createDebug.formatArgs.call(self, args);
15497
15498			const logFn = self.log || createDebug.log;
15499			logFn.apply(self, args);
15500		}
15501
15502		debug.namespace = namespace;
15503		debug.useColors = createDebug.useColors();
15504		debug.color = createDebug.selectColor(namespace);
15505		debug.extend = extend;
15506		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
15507
15508		Object.defineProperty(debug, 'enabled', {
15509			enumerable: true,
15510			configurable: false,
15511			get: () => {
15512				if (enableOverride !== null) {
15513					return enableOverride;
15514				}
15515				if (namespacesCache !== createDebug.namespaces) {
15516					namespacesCache = createDebug.namespaces;
15517					enabledCache = createDebug.enabled(namespace);
15518				}
15519
15520				return enabledCache;
15521			},
15522			set: v => {
15523				enableOverride = v;
15524			}
15525		});
15526
15527		// Env-specific initialization logic for debug instances
15528		if (typeof createDebug.init === 'function') {
15529			createDebug.init(debug);
15530		}
15531
15532		return debug;
15533	}
15534
15535	function extend(namespace, delimiter) {
15536		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
15537		newDebug.log = this.log;
15538		return newDebug;
15539	}
15540
15541	/**
15542	* Enables a debug mode by namespaces. This can include modes
15543	* separated by a colon and wildcards.
15544	*
15545	* @param {String} namespaces
15546	* @api public
15547	*/
15548	function enable(namespaces) {
15549		createDebug.save(namespaces);
15550		createDebug.namespaces = namespaces;
15551
15552		createDebug.names = [];
15553		createDebug.skips = [];
15554
15555		let i;
15556		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
15557		const len = split.length;
15558
15559		for (i = 0; i < len; i++) {
15560			if (!split[i]) {
15561				// ignore empty strings
15562				continue;
15563			}
15564
15565			namespaces = split[i].replace(/\*/g, '.*?');
15566
15567			if (namespaces[0] === '-') {
15568				createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
15569			} else {
15570				createDebug.names.push(new RegExp('^' + namespaces + '$'));
15571			}
15572		}
15573	}
15574
15575	/**
15576	* Disable debug output.
15577	*
15578	* @return {String} namespaces
15579	* @api public
15580	*/
15581	function disable() {
15582		const namespaces = [
15583			...createDebug.names.map(toNamespace),
15584			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
15585		].join(',');
15586		createDebug.enable('');
15587		return namespaces;
15588	}
15589
15590	/**
15591	* Returns true if the given mode name is enabled, false otherwise.
15592	*
15593	* @param {String} name
15594	* @return {Boolean}
15595	* @api public
15596	*/
15597	function enabled(name) {
15598		if (name[name.length - 1] === '*') {
15599			return true;
15600		}
15601
15602		let i;
15603		let len;
15604
15605		for (i = 0, len = createDebug.skips.length; i < len; i++) {
15606			if (createDebug.skips[i].test(name)) {
15607				return false;
15608			}
15609		}
15610
15611		for (i = 0, len = createDebug.names.length; i < len; i++) {
15612			if (createDebug.names[i].test(name)) {
15613				return true;
15614			}
15615		}
15616
15617		return false;
15618	}
15619
15620	/**
15621	* Convert regexp to namespace
15622	*
15623	* @param {RegExp} regxep
15624	* @return {String} namespace
15625	* @api private
15626	*/
15627	function toNamespace(regexp) {
15628		return regexp.toString()
15629			.substring(2, regexp.toString().length - 2)
15630			.replace(/\.\*\?$/, '*');
15631	}
15632
15633	/**
15634	* Coerce `val`.
15635	*
15636	* @param {Mixed} val
15637	* @return {Mixed}
15638	* @api private
15639	*/
15640	function coerce(val) {
15641		if (val instanceof Error) {
15642			return val.stack || val.message;
15643		}
15644		return val;
15645	}
15646
15647	/**
15648	* XXX DO NOT USE. This is a temporary stub function.
15649	* XXX It WILL be removed in the next major release.
15650	*/
15651	function destroy() {
15652		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
15653	}
15654
15655	createDebug.enable(createDebug.load());
15656
15657	return createDebug;
15658}
15659
15660var common$3 = setup;
15661
15662/* eslint-env browser */
15663
15664(function (module, exports) {
15665/**
15666 * This is the web browser implementation of `debug()`.
15667 */
15668
15669exports.formatArgs = formatArgs;
15670exports.save = save;
15671exports.load = load;
15672exports.useColors = useColors;
15673exports.storage = localstorage();
15674exports.destroy = (() => {
15675	let warned = false;
15676
15677	return () => {
15678		if (!warned) {
15679			warned = true;
15680			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
15681		}
15682	};
15683})();
15684
15685/**
15686 * Colors.
15687 */
15688
15689exports.colors = [
15690	'#0000CC',
15691	'#0000FF',
15692	'#0033CC',
15693	'#0033FF',
15694	'#0066CC',
15695	'#0066FF',
15696	'#0099CC',
15697	'#0099FF',
15698	'#00CC00',
15699	'#00CC33',
15700	'#00CC66',
15701	'#00CC99',
15702	'#00CCCC',
15703	'#00CCFF',
15704	'#3300CC',
15705	'#3300FF',
15706	'#3333CC',
15707	'#3333FF',
15708	'#3366CC',
15709	'#3366FF',
15710	'#3399CC',
15711	'#3399FF',
15712	'#33CC00',
15713	'#33CC33',
15714	'#33CC66',
15715	'#33CC99',
15716	'#33CCCC',
15717	'#33CCFF',
15718	'#6600CC',
15719	'#6600FF',
15720	'#6633CC',
15721	'#6633FF',
15722	'#66CC00',
15723	'#66CC33',
15724	'#9900CC',
15725	'#9900FF',
15726	'#9933CC',
15727	'#9933FF',
15728	'#99CC00',
15729	'#99CC33',
15730	'#CC0000',
15731	'#CC0033',
15732	'#CC0066',
15733	'#CC0099',
15734	'#CC00CC',
15735	'#CC00FF',
15736	'#CC3300',
15737	'#CC3333',
15738	'#CC3366',
15739	'#CC3399',
15740	'#CC33CC',
15741	'#CC33FF',
15742	'#CC6600',
15743	'#CC6633',
15744	'#CC9900',
15745	'#CC9933',
15746	'#CCCC00',
15747	'#CCCC33',
15748	'#FF0000',
15749	'#FF0033',
15750	'#FF0066',
15751	'#FF0099',
15752	'#FF00CC',
15753	'#FF00FF',
15754	'#FF3300',
15755	'#FF3333',
15756	'#FF3366',
15757	'#FF3399',
15758	'#FF33CC',
15759	'#FF33FF',
15760	'#FF6600',
15761	'#FF6633',
15762	'#FF9900',
15763	'#FF9933',
15764	'#FFCC00',
15765	'#FFCC33'
15766];
15767
15768/**
15769 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
15770 * and the Firebug extension (any Firefox version) are known
15771 * to support "%c" CSS customizations.
15772 *
15773 * TODO: add a `localStorage` variable to explicitly enable/disable colors
15774 */
15775
15776// eslint-disable-next-line complexity
15777function useColors() {
15778	// NB: In an Electron preload script, document will be defined but not fully
15779	// initialized. Since we know we're in Chrome, we'll just detect this case
15780	// explicitly
15781	if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
15782		return true;
15783	}
15784
15785	// Internet Explorer and Edge do not support colors.
15786	if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
15787		return false;
15788	}
15789
15790	// Is webkit? http://stackoverflow.com/a/16459606/376773
15791	// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
15792	return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
15793		// Is firebug? http://stackoverflow.com/a/398120/376773
15794		(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
15795		// Is firefox >= v31?
15796		// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
15797		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
15798		// Double check webkit in userAgent just in case we are in a worker
15799		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
15800}
15801
15802/**
15803 * Colorize log arguments if enabled.
15804 *
15805 * @api public
15806 */
15807
15808function formatArgs(args) {
15809	args[0] = (this.useColors ? '%c' : '') +
15810		this.namespace +
15811		(this.useColors ? ' %c' : ' ') +
15812		args[0] +
15813		(this.useColors ? '%c ' : ' ') +
15814		'+' + module.exports.humanize(this.diff);
15815
15816	if (!this.useColors) {
15817		return;
15818	}
15819
15820	const c = 'color: ' + this.color;
15821	args.splice(1, 0, c, 'color: inherit');
15822
15823	// The final "%c" is somewhat tricky, because there could be other
15824	// arguments passed either before or after the %c, so we need to
15825	// figure out the correct index to insert the CSS into
15826	let index = 0;
15827	let lastC = 0;
15828	args[0].replace(/%[a-zA-Z%]/g, match => {
15829		if (match === '%%') {
15830			return;
15831		}
15832		index++;
15833		if (match === '%c') {
15834			// We only are interested in the *last* %c
15835			// (the user may have provided their own)
15836			lastC = index;
15837		}
15838	});
15839
15840	args.splice(lastC, 0, c);
15841}
15842
15843/**
15844 * Invokes `console.debug()` when available.
15845 * No-op when `console.debug` is not a "function".
15846 * If `console.debug` is not available, falls back
15847 * to `console.log`.
15848 *
15849 * @api public
15850 */
15851exports.log = console.debug || console.log || (() => {});
15852
15853/**
15854 * Save `namespaces`.
15855 *
15856 * @param {String} namespaces
15857 * @api private
15858 */
15859function save(namespaces) {
15860	try {
15861		if (namespaces) {
15862			exports.storage.setItem('debug', namespaces);
15863		} else {
15864			exports.storage.removeItem('debug');
15865		}
15866	} catch (error) {
15867		// Swallow
15868		// XXX (@Qix-) should we be logging these?
15869	}
15870}
15871
15872/**
15873 * Load `namespaces`.
15874 *
15875 * @return {String} returns the previously persisted debug modes
15876 * @api private
15877 */
15878function load() {
15879	let r;
15880	try {
15881		r = exports.storage.getItem('debug');
15882	} catch (error) {
15883		// Swallow
15884		// XXX (@Qix-) should we be logging these?
15885	}
15886
15887	// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
15888	if (!r && typeof process !== 'undefined' && 'env' in process) {
15889		r = process.env.DEBUG;
15890	}
15891
15892	return r;
15893}
15894
15895/**
15896 * Localstorage attempts to return the localstorage.
15897 *
15898 * This is necessary because safari throws
15899 * when a user disables cookies/localstorage
15900 * and you attempt to access it.
15901 *
15902 * @return {LocalStorage}
15903 * @api private
15904 */
15905
15906function localstorage() {
15907	try {
15908		// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
15909		// The Browser also has localStorage in the global context.
15910		return localStorage;
15911	} catch (error) {
15912		// Swallow
15913		// XXX (@Qix-) should we be logging these?
15914	}
15915}
15916
15917module.exports = common$3(exports);
15918
15919const {formatters} = module.exports;
15920
15921/**
15922 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
15923 */
15924
15925formatters.j = function (v) {
15926	try {
15927		return JSON.stringify(v);
15928	} catch (error) {
15929		return '[UnexpectedJSONParseError]: ' + error.message;
15930	}
15931};
15932}(browser, browser.exports));
15933
15934var node = {exports: {}};
15935
15936/**
15937 * Module dependencies.
15938 */
15939
15940(function (module, exports) {
15941const tty = tty$1;
15942const util = require$$0$4;
15943
15944/**
15945 * This is the Node.js implementation of `debug()`.
15946 */
15947
15948exports.init = init;
15949exports.log = log;
15950exports.formatArgs = formatArgs;
15951exports.save = save;
15952exports.load = load;
15953exports.useColors = useColors;
15954exports.destroy = util.deprecate(
15955	() => {},
15956	'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
15957);
15958
15959/**
15960 * Colors.
15961 */
15962
15963exports.colors = [6, 2, 3, 4, 5, 1];
15964
15965try {
15966	// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
15967	// eslint-disable-next-line import/no-extraneous-dependencies
15968	const supportsColor = supportsColor_1$1;
15969
15970	if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
15971		exports.colors = [
15972			20,
15973			21,
15974			26,
15975			27,
15976			32,
15977			33,
15978			38,
15979			39,
15980			40,
15981			41,
15982			42,
15983			43,
15984			44,
15985			45,
15986			56,
15987			57,
15988			62,
15989			63,
15990			68,
15991			69,
15992			74,
15993			75,
15994			76,
15995			77,
15996			78,
15997			79,
15998			80,
15999			81,
16000			92,
16001			93,
16002			98,
16003			99,
16004			112,
16005			113,
16006			128,
16007			129,
16008			134,
16009			135,
16010			148,
16011			149,
16012			160,
16013			161,
16014			162,
16015			163,
16016			164,
16017			165,
16018			166,
16019			167,
16020			168,
16021			169,
16022			170,
16023			171,
16024			172,
16025			173,
16026			178,
16027			179,
16028			184,
16029			185,
16030			196,
16031			197,
16032			198,
16033			199,
16034			200,
16035			201,
16036			202,
16037			203,
16038			204,
16039			205,
16040			206,
16041			207,
16042			208,
16043			209,
16044			214,
16045			215,
16046			220,
16047			221
16048		];
16049	}
16050} catch (error) {
16051	// Swallow - we only care if `supports-color` is available; it doesn't have to be.
16052}
16053
16054/**
16055 * Build up the default `inspectOpts` object from the environment variables.
16056 *
16057 *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
16058 */
16059
16060exports.inspectOpts = Object.keys(process.env).filter(key => {
16061	return /^debug_/i.test(key);
16062}).reduce((obj, key) => {
16063	// Camel-case
16064	const prop = key
16065		.substring(6)
16066		.toLowerCase()
16067		.replace(/_([a-z])/g, (_, k) => {
16068			return k.toUpperCase();
16069		});
16070
16071	// Coerce string value into JS value
16072	let val = process.env[key];
16073	if (/^(yes|on|true|enabled)$/i.test(val)) {
16074		val = true;
16075	} else if (/^(no|off|false|disabled)$/i.test(val)) {
16076		val = false;
16077	} else if (val === 'null') {
16078		val = null;
16079	} else {
16080		val = Number(val);
16081	}
16082
16083	obj[prop] = val;
16084	return obj;
16085}, {});
16086
16087/**
16088 * Is stdout a TTY? Colored output is enabled when `true`.
16089 */
16090
16091function useColors() {
16092	return 'colors' in exports.inspectOpts ?
16093		Boolean(exports.inspectOpts.colors) :
16094		tty.isatty(process.stderr.fd);
16095}
16096
16097/**
16098 * Adds ANSI color escape codes if enabled.
16099 *
16100 * @api public
16101 */
16102
16103function formatArgs(args) {
16104	const {namespace: name, useColors} = this;
16105
16106	if (useColors) {
16107		const c = this.color;
16108		const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
16109		const prefix = `  ${colorCode};1m${name} \u001B[0m`;
16110
16111		args[0] = prefix + args[0].split('\n').join('\n' + prefix);
16112		args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
16113	} else {
16114		args[0] = getDate() + name + ' ' + args[0];
16115	}
16116}
16117
16118function getDate() {
16119	if (exports.inspectOpts.hideDate) {
16120		return '';
16121	}
16122	return new Date().toISOString() + ' ';
16123}
16124
16125/**
16126 * Invokes `util.format()` with the specified arguments and writes to stderr.
16127 */
16128
16129function log(...args) {
16130	return process.stderr.write(util.format(...args) + '\n');
16131}
16132
16133/**
16134 * Save `namespaces`.
16135 *
16136 * @param {String} namespaces
16137 * @api private
16138 */
16139function save(namespaces) {
16140	if (namespaces) {
16141		process.env.DEBUG = namespaces;
16142	} else {
16143		// If you set a process.env field to null or undefined, it gets cast to the
16144		// string 'null' or 'undefined'. Just delete instead.
16145		delete process.env.DEBUG;
16146	}
16147}
16148
16149/**
16150 * Load `namespaces`.
16151 *
16152 * @return {String} returns the previously persisted debug modes
16153 * @api private
16154 */
16155
16156function load() {
16157	return process.env.DEBUG;
16158}
16159
16160/**
16161 * Init logic for `debug` instances.
16162 *
16163 * Create a new `inspectOpts` object in case `useColors` is set
16164 * differently for a particular `debug` instance.
16165 */
16166
16167function init(debug) {
16168	debug.inspectOpts = {};
16169
16170	const keys = Object.keys(exports.inspectOpts);
16171	for (let i = 0; i < keys.length; i++) {
16172		debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
16173	}
16174}
16175
16176module.exports = common$3(exports);
16177
16178const {formatters} = module.exports;
16179
16180/**
16181 * Map %o to `util.inspect()`, all on a single line.
16182 */
16183
16184formatters.o = function (v) {
16185	this.inspectOpts.colors = this.useColors;
16186	return util.inspect(v, this.inspectOpts)
16187		.split('\n')
16188		.map(str => str.trim())
16189		.join(' ');
16190};
16191
16192/**
16193 * Map %O to `util.inspect()`, allowing multiple lines if needed.
16194 */
16195
16196formatters.O = function (v) {
16197	this.inspectOpts.colors = this.useColors;
16198	return util.inspect(v, this.inspectOpts);
16199};
16200}(node, node.exports));
16201
16202/**
16203 * Detect Electron renderer / nwjs process, which is node, but we should
16204 * treat as a browser.
16205 */
16206
16207if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
16208	src.exports = browser.exports;
16209} else {
16210	src.exports = node.exports;
16211}
16212
16213var createDebug = src.exports;
16214
16215var re$6 = {exports: {}};
16216
16217// Note: this is the semver.org version of the spec that it implements
16218// Not necessarily the package version of this code.
16219const SEMVER_SPEC_VERSION = '2.0.0';
16220
16221const MAX_LENGTH$2 = 256;
16222const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER ||
16223  /* istanbul ignore next */ 9007199254740991;
16224
16225// Max safe segment length for coercion.
16226const MAX_SAFE_COMPONENT_LENGTH = 16;
16227
16228var constants = {
16229  SEMVER_SPEC_VERSION,
16230  MAX_LENGTH: MAX_LENGTH$2,
16231  MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1,
16232  MAX_SAFE_COMPONENT_LENGTH
16233};
16234
16235const debug$f = (
16236  typeof process === 'object' &&
16237  process.env &&
16238  process.env.NODE_DEBUG &&
16239  /\bsemver\b/i.test(process.env.NODE_DEBUG)
16240) ? (...args) => console.error('SEMVER', ...args)
16241  : () => {};
16242
16243var debug_1 = debug$f;
16244
16245(function (module, exports) {
16246const { MAX_SAFE_COMPONENT_LENGTH } = constants;
16247const debug = debug_1;
16248exports = module.exports = {};
16249
16250// The actual regexps go on exports.re
16251const re = exports.re = [];
16252const src = exports.src = [];
16253const t = exports.t = {};
16254let R = 0;
16255
16256const createToken = (name, value, isGlobal) => {
16257  const index = R++;
16258  debug(index, value);
16259  t[name] = index;
16260  src[index] = value;
16261  re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
16262};
16263
16264// The following Regular Expressions can be used for tokenizing,
16265// validating, and parsing SemVer version strings.
16266
16267// ## Numeric Identifier
16268// A single `0`, or a non-zero digit followed by zero or more digits.
16269
16270createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
16271createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+');
16272
16273// ## Non-numeric Identifier
16274// Zero or more digits, followed by a letter or hyphen, and then zero or
16275// more letters, digits, or hyphens.
16276
16277createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*');
16278
16279// ## Main Version
16280// Three dot-separated numeric identifiers.
16281
16282createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
16283                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
16284                   `(${src[t.NUMERICIDENTIFIER]})`);
16285
16286createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
16287                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
16288                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
16289
16290// ## Pre-release Version Identifier
16291// A numeric identifier, or a non-numeric identifier.
16292
16293createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
16294}|${src[t.NONNUMERICIDENTIFIER]})`);
16295
16296createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
16297}|${src[t.NONNUMERICIDENTIFIER]})`);
16298
16299// ## Pre-release Version
16300// Hyphen, followed by one or more dot-separated pre-release version
16301// identifiers.
16302
16303createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
16304}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
16305
16306createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
16307}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
16308
16309// ## Build Metadata Identifier
16310// Any combination of digits, letters, or hyphens.
16311
16312createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+');
16313
16314// ## Build Metadata
16315// Plus sign, followed by one or more period-separated build metadata
16316// identifiers.
16317
16318createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
16319}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
16320
16321// ## Full Version String
16322// A main version, followed optionally by a pre-release version and
16323// build metadata.
16324
16325// Note that the only major, minor, patch, and pre-release sections of
16326// the version string are capturing groups.  The build metadata is not a
16327// capturing group, because it should not ever be used in version
16328// comparison.
16329
16330createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
16331}${src[t.PRERELEASE]}?${
16332  src[t.BUILD]}?`);
16333
16334createToken('FULL', `^${src[t.FULLPLAIN]}$`);
16335
16336// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
16337// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
16338// common in the npm registry.
16339createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
16340}${src[t.PRERELEASELOOSE]}?${
16341  src[t.BUILD]}?`);
16342
16343createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
16344
16345createToken('GTLT', '((?:<|>)?=?)');
16346
16347// Something like "2.*" or "1.2.x".
16348// Note that "x.x" is a valid xRange identifer, meaning "any version"
16349// Only the first item is strictly required.
16350createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
16351createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
16352
16353createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
16354                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
16355                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
16356                   `(?:${src[t.PRERELEASE]})?${
16357                     src[t.BUILD]}?` +
16358                   `)?)?`);
16359
16360createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
16361                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
16362                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
16363                        `(?:${src[t.PRERELEASELOOSE]})?${
16364                          src[t.BUILD]}?` +
16365                        `)?)?`);
16366
16367createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
16368createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
16369
16370// Coercion.
16371// Extract anything that could conceivably be a part of a valid semver
16372createToken('COERCE', `${'(^|[^\\d])' +
16373              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
16374              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
16375              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
16376              `(?:$|[^\\d])`);
16377createToken('COERCERTL', src[t.COERCE], true);
16378
16379// Tilde ranges.
16380// Meaning is "reasonably at or greater than"
16381createToken('LONETILDE', '(?:~>?)');
16382
16383createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
16384exports.tildeTrimReplace = '$1~';
16385
16386createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
16387createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
16388
16389// Caret ranges.
16390// Meaning is "at least and backwards compatible with"
16391createToken('LONECARET', '(?:\\^)');
16392
16393createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
16394exports.caretTrimReplace = '$1^';
16395
16396createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
16397createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
16398
16399// A simple gt/lt/eq thing, or just "" to indicate "any version"
16400createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
16401createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
16402
16403// An expression to strip any whitespace between the gtlt and the thing
16404// it modifies, so that `> 1.2.3` ==> `>1.2.3`
16405createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
16406}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
16407exports.comparatorTrimReplace = '$1$2$3';
16408
16409// Something like `1.2.3 - 1.2.4`
16410// Note that these all use the loose form, because they'll be
16411// checked against either the strict or loose comparator form
16412// later.
16413createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
16414                   `\\s+-\\s+` +
16415                   `(${src[t.XRANGEPLAIN]})` +
16416                   `\\s*$`);
16417
16418createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
16419                        `\\s+-\\s+` +
16420                        `(${src[t.XRANGEPLAINLOOSE]})` +
16421                        `\\s*$`);
16422
16423// Star ranges basically just allow anything at all.
16424createToken('STAR', '(<|>)?=?\\s*\\*');
16425// >=0.0.0 is like a star
16426createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$');
16427createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$');
16428}(re$6, re$6.exports));
16429
16430// parse out just the options we care about so we always get a consistent
16431// obj with keys in a consistent order.
16432const opts = ['includePrerelease', 'loose', 'rtl'];
16433const parseOptions$4 = options =>
16434  !options ? {}
16435  : typeof options !== 'object' ? { loose: true }
16436  : opts.filter(k => options[k]).reduce((options, k) => {
16437    options[k] = true;
16438    return options
16439  }, {});
16440var parseOptions_1 = parseOptions$4;
16441
16442const numeric$1 = /^[0-9]+$/;
16443const compareIdentifiers$1 = (a, b) => {
16444  const anum = numeric$1.test(a);
16445  const bnum = numeric$1.test(b);
16446
16447  if (anum && bnum) {
16448    a = +a;
16449    b = +b;
16450  }
16451
16452  return a === b ? 0
16453    : (anum && !bnum) ? -1
16454    : (bnum && !anum) ? 1
16455    : a < b ? -1
16456    : 1
16457};
16458
16459const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a);
16460
16461var identifiers = {
16462  compareIdentifiers: compareIdentifiers$1,
16463  rcompareIdentifiers
16464};
16465
16466const debug$e = debug_1;
16467const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants;
16468const { re: re$5, t: t$4 } = re$6.exports;
16469
16470const parseOptions$3 = parseOptions_1;
16471const { compareIdentifiers } = identifiers;
16472class SemVer$e {
16473  constructor (version, options) {
16474    options = parseOptions$3(options);
16475
16476    if (version instanceof SemVer$e) {
16477      if (version.loose === !!options.loose &&
16478          version.includePrerelease === !!options.includePrerelease) {
16479        return version
16480      } else {
16481        version = version.version;
16482      }
16483    } else if (typeof version !== 'string') {
16484      throw new TypeError(`Invalid Version: ${version}`)
16485    }
16486
16487    if (version.length > MAX_LENGTH$1) {
16488      throw new TypeError(
16489        `version is longer than ${MAX_LENGTH$1} characters`
16490      )
16491    }
16492
16493    debug$e('SemVer', version, options);
16494    this.options = options;
16495    this.loose = !!options.loose;
16496    // this isn't actually relevant for versions, but keep it so that we
16497    // don't run into trouble passing this.options around.
16498    this.includePrerelease = !!options.includePrerelease;
16499
16500    const m = version.trim().match(options.loose ? re$5[t$4.LOOSE] : re$5[t$4.FULL]);
16501
16502    if (!m) {
16503      throw new TypeError(`Invalid Version: ${version}`)
16504    }
16505
16506    this.raw = version;
16507
16508    // these are actually numbers
16509    this.major = +m[1];
16510    this.minor = +m[2];
16511    this.patch = +m[3];
16512
16513    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
16514      throw new TypeError('Invalid major version')
16515    }
16516
16517    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
16518      throw new TypeError('Invalid minor version')
16519    }
16520
16521    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
16522      throw new TypeError('Invalid patch version')
16523    }
16524
16525    // numberify any prerelease numeric ids
16526    if (!m[4]) {
16527      this.prerelease = [];
16528    } else {
16529      this.prerelease = m[4].split('.').map((id) => {
16530        if (/^[0-9]+$/.test(id)) {
16531          const num = +id;
16532          if (num >= 0 && num < MAX_SAFE_INTEGER) {
16533            return num
16534          }
16535        }
16536        return id
16537      });
16538    }
16539
16540    this.build = m[5] ? m[5].split('.') : [];
16541    this.format();
16542  }
16543
16544  format () {
16545    this.version = `${this.major}.${this.minor}.${this.patch}`;
16546    if (this.prerelease.length) {
16547      this.version += `-${this.prerelease.join('.')}`;
16548    }
16549    return this.version
16550  }
16551
16552  toString () {
16553    return this.version
16554  }
16555
16556  compare (other) {
16557    debug$e('SemVer.compare', this.version, this.options, other);
16558    if (!(other instanceof SemVer$e)) {
16559      if (typeof other === 'string' && other === this.version) {
16560        return 0
16561      }
16562      other = new SemVer$e(other, this.options);
16563    }
16564
16565    if (other.version === this.version) {
16566      return 0
16567    }
16568
16569    return this.compareMain(other) || this.comparePre(other)
16570  }
16571
16572  compareMain (other) {
16573    if (!(other instanceof SemVer$e)) {
16574      other = new SemVer$e(other, this.options);
16575    }
16576
16577    return (
16578      compareIdentifiers(this.major, other.major) ||
16579      compareIdentifiers(this.minor, other.minor) ||
16580      compareIdentifiers(this.patch, other.patch)
16581    )
16582  }
16583
16584  comparePre (other) {
16585    if (!(other instanceof SemVer$e)) {
16586      other = new SemVer$e(other, this.options);
16587    }
16588
16589    // NOT having a prerelease is > having one
16590    if (this.prerelease.length && !other.prerelease.length) {
16591      return -1
16592    } else if (!this.prerelease.length && other.prerelease.length) {
16593      return 1
16594    } else if (!this.prerelease.length && !other.prerelease.length) {
16595      return 0
16596    }
16597
16598    let i = 0;
16599    do {
16600      const a = this.prerelease[i];
16601      const b = other.prerelease[i];
16602      debug$e('prerelease compare', i, a, b);
16603      if (a === undefined && b === undefined) {
16604        return 0
16605      } else if (b === undefined) {
16606        return 1
16607      } else if (a === undefined) {
16608        return -1
16609      } else if (a === b) {
16610        continue
16611      } else {
16612        return compareIdentifiers(a, b)
16613      }
16614    } while (++i)
16615  }
16616
16617  compareBuild (other) {
16618    if (!(other instanceof SemVer$e)) {
16619      other = new SemVer$e(other, this.options);
16620    }
16621
16622    let i = 0;
16623    do {
16624      const a = this.build[i];
16625      const b = other.build[i];
16626      debug$e('prerelease compare', i, a, b);
16627      if (a === undefined && b === undefined) {
16628        return 0
16629      } else if (b === undefined) {
16630        return 1
16631      } else if (a === undefined) {
16632        return -1
16633      } else if (a === b) {
16634        continue
16635      } else {
16636        return compareIdentifiers(a, b)
16637      }
16638    } while (++i)
16639  }
16640
16641  // preminor will bump the version up to the next minor release, and immediately
16642  // down to pre-release. premajor and prepatch work the same way.
16643  inc (release, identifier) {
16644    switch (release) {
16645      case 'premajor':
16646        this.prerelease.length = 0;
16647        this.patch = 0;
16648        this.minor = 0;
16649        this.major++;
16650        this.inc('pre', identifier);
16651        break
16652      case 'preminor':
16653        this.prerelease.length = 0;
16654        this.patch = 0;
16655        this.minor++;
16656        this.inc('pre', identifier);
16657        break
16658      case 'prepatch':
16659        // If this is already a prerelease, it will bump to the next version
16660        // drop any prereleases that might already exist, since they are not
16661        // relevant at this point.
16662        this.prerelease.length = 0;
16663        this.inc('patch', identifier);
16664        this.inc('pre', identifier);
16665        break
16666      // If the input is a non-prerelease version, this acts the same as
16667      // prepatch.
16668      case 'prerelease':
16669        if (this.prerelease.length === 0) {
16670          this.inc('patch', identifier);
16671        }
16672        this.inc('pre', identifier);
16673        break
16674
16675      case 'major':
16676        // If this is a pre-major version, bump up to the same major version.
16677        // Otherwise increment major.
16678        // 1.0.0-5 bumps to 1.0.0
16679        // 1.1.0 bumps to 2.0.0
16680        if (
16681          this.minor !== 0 ||
16682          this.patch !== 0 ||
16683          this.prerelease.length === 0
16684        ) {
16685          this.major++;
16686        }
16687        this.minor = 0;
16688        this.patch = 0;
16689        this.prerelease = [];
16690        break
16691      case 'minor':
16692        // If this is a pre-minor version, bump up to the same minor version.
16693        // Otherwise increment minor.
16694        // 1.2.0-5 bumps to 1.2.0
16695        // 1.2.1 bumps to 1.3.0
16696        if (this.patch !== 0 || this.prerelease.length === 0) {
16697          this.minor++;
16698        }
16699        this.patch = 0;
16700        this.prerelease = [];
16701        break
16702      case 'patch':
16703        // If this is not a pre-release version, it will increment the patch.
16704        // If it is a pre-release it will bump up to the same patch version.
16705        // 1.2.0-5 patches to 1.2.0
16706        // 1.2.0 patches to 1.2.1
16707        if (this.prerelease.length === 0) {
16708          this.patch++;
16709        }
16710        this.prerelease = [];
16711        break
16712      // This probably shouldn't be used publicly.
16713      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
16714      case 'pre':
16715        if (this.prerelease.length === 0) {
16716          this.prerelease = [0];
16717        } else {
16718          let i = this.prerelease.length;
16719          while (--i >= 0) {
16720            if (typeof this.prerelease[i] === 'number') {
16721              this.prerelease[i]++;
16722              i = -2;
16723            }
16724          }
16725          if (i === -1) {
16726            // didn't increment anything
16727            this.prerelease.push(0);
16728          }
16729        }
16730        if (identifier) {
16731          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
16732          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
16733          if (this.prerelease[0] === identifier) {
16734            if (isNaN(this.prerelease[1])) {
16735              this.prerelease = [identifier, 0];
16736            }
16737          } else {
16738            this.prerelease = [identifier, 0];
16739          }
16740        }
16741        break
16742
16743      default:
16744        throw new Error(`invalid increment argument: ${release}`)
16745    }
16746    this.format();
16747    this.raw = this.version;
16748    return this
16749  }
16750}
16751
16752var semver$2 = SemVer$e;
16753
16754const {MAX_LENGTH} = constants;
16755const { re: re$4, t: t$3 } = re$6.exports;
16756const SemVer$d = semver$2;
16757
16758const parseOptions$2 = parseOptions_1;
16759const parse$9 = (version, options) => {
16760  options = parseOptions$2(options);
16761
16762  if (version instanceof SemVer$d) {
16763    return version
16764  }
16765
16766  if (typeof version !== 'string') {
16767    return null
16768  }
16769
16770  if (version.length > MAX_LENGTH) {
16771    return null
16772  }
16773
16774  const r = options.loose ? re$4[t$3.LOOSE] : re$4[t$3.FULL];
16775  if (!r.test(version)) {
16776    return null
16777  }
16778
16779  try {
16780    return new SemVer$d(version, options)
16781  } catch (er) {
16782    return null
16783  }
16784};
16785
16786var parse_1 = parse$9;
16787
16788const parse$8 = parse_1;
16789const valid$1 = (version, options) => {
16790  const v = parse$8(version, options);
16791  return v ? v.version : null
16792};
16793var valid_1 = valid$1;
16794
16795const parse$7 = parse_1;
16796const clean = (version, options) => {
16797  const s = parse$7(version.trim().replace(/^[=v]+/, ''), options);
16798  return s ? s.version : null
16799};
16800var clean_1 = clean;
16801
16802const SemVer$c = semver$2;
16803
16804const inc = (version, release, options, identifier) => {
16805  if (typeof (options) === 'string') {
16806    identifier = options;
16807    options = undefined;
16808  }
16809
16810  try {
16811    return new SemVer$c(version, options).inc(release, identifier).version
16812  } catch (er) {
16813    return null
16814  }
16815};
16816var inc_1 = inc;
16817
16818const SemVer$b = semver$2;
16819const compare$b = (a, b, loose) =>
16820  new SemVer$b(a, loose).compare(new SemVer$b(b, loose));
16821
16822var compare_1 = compare$b;
16823
16824const compare$a = compare_1;
16825const eq$2 = (a, b, loose) => compare$a(a, b, loose) === 0;
16826var eq_1 = eq$2;
16827
16828const parse$6 = parse_1;
16829const eq$1 = eq_1;
16830
16831const diff = (version1, version2) => {
16832  if (eq$1(version1, version2)) {
16833    return null
16834  } else {
16835    const v1 = parse$6(version1);
16836    const v2 = parse$6(version2);
16837    const hasPre = v1.prerelease.length || v2.prerelease.length;
16838    const prefix = hasPre ? 'pre' : '';
16839    const defaultResult = hasPre ? 'prerelease' : '';
16840    for (const key in v1) {
16841      if (key === 'major' || key === 'minor' || key === 'patch') {
16842        if (v1[key] !== v2[key]) {
16843          return prefix + key
16844        }
16845      }
16846    }
16847    return defaultResult // may be undefined
16848  }
16849};
16850var diff_1 = diff;
16851
16852const SemVer$a = semver$2;
16853const major = (a, loose) => new SemVer$a(a, loose).major;
16854var major_1 = major;
16855
16856const SemVer$9 = semver$2;
16857const minor = (a, loose) => new SemVer$9(a, loose).minor;
16858var minor_1 = minor;
16859
16860const SemVer$8 = semver$2;
16861const patch = (a, loose) => new SemVer$8(a, loose).patch;
16862var patch_1 = patch;
16863
16864const parse$5 = parse_1;
16865const prerelease = (version, options) => {
16866  const parsed = parse$5(version, options);
16867  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
16868};
16869var prerelease_1 = prerelease;
16870
16871const compare$9 = compare_1;
16872const rcompare = (a, b, loose) => compare$9(b, a, loose);
16873var rcompare_1 = rcompare;
16874
16875const compare$8 = compare_1;
16876const compareLoose = (a, b) => compare$8(a, b, true);
16877var compareLoose_1 = compareLoose;
16878
16879const SemVer$7 = semver$2;
16880const compareBuild$2 = (a, b, loose) => {
16881  const versionA = new SemVer$7(a, loose);
16882  const versionB = new SemVer$7(b, loose);
16883  return versionA.compare(versionB) || versionA.compareBuild(versionB)
16884};
16885var compareBuild_1 = compareBuild$2;
16886
16887const compareBuild$1 = compareBuild_1;
16888const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose));
16889var sort_1 = sort$1;
16890
16891const compareBuild = compareBuild_1;
16892const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
16893var rsort_1 = rsort;
16894
16895const compare$7 = compare_1;
16896const gt$3 = (a, b, loose) => compare$7(a, b, loose) > 0;
16897var gt_1 = gt$3;
16898
16899const compare$6 = compare_1;
16900const lt$2 = (a, b, loose) => compare$6(a, b, loose) < 0;
16901var lt_1 = lt$2;
16902
16903const compare$5 = compare_1;
16904const neq$1 = (a, b, loose) => compare$5(a, b, loose) !== 0;
16905var neq_1 = neq$1;
16906
16907const compare$4 = compare_1;
16908const gte$3 = (a, b, loose) => compare$4(a, b, loose) >= 0;
16909var gte_1 = gte$3;
16910
16911const compare$3 = compare_1;
16912const lte$3 = (a, b, loose) => compare$3(a, b, loose) <= 0;
16913var lte_1 = lte$3;
16914
16915const eq = eq_1;
16916const neq = neq_1;
16917const gt$2 = gt_1;
16918const gte$2 = gte_1;
16919const lt$1 = lt_1;
16920const lte$2 = lte_1;
16921
16922const cmp$1 = (a, op, b, loose) => {
16923  switch (op) {
16924    case '===':
16925      if (typeof a === 'object')
16926        a = a.version;
16927      if (typeof b === 'object')
16928        b = b.version;
16929      return a === b
16930
16931    case '!==':
16932      if (typeof a === 'object')
16933        a = a.version;
16934      if (typeof b === 'object')
16935        b = b.version;
16936      return a !== b
16937
16938    case '':
16939    case '=':
16940    case '==':
16941      return eq(a, b, loose)
16942
16943    case '!=':
16944      return neq(a, b, loose)
16945
16946    case '>':
16947      return gt$2(a, b, loose)
16948
16949    case '>=':
16950      return gte$2(a, b, loose)
16951
16952    case '<':
16953      return lt$1(a, b, loose)
16954
16955    case '<=':
16956      return lte$2(a, b, loose)
16957
16958    default:
16959      throw new TypeError(`Invalid operator: ${op}`)
16960  }
16961};
16962var cmp_1 = cmp$1;
16963
16964const SemVer$6 = semver$2;
16965const parse$4 = parse_1;
16966const {re: re$3, t: t$2} = re$6.exports;
16967
16968const coerce$I = (version, options) => {
16969  if (version instanceof SemVer$6) {
16970    return version
16971  }
16972
16973  if (typeof version === 'number') {
16974    version = String(version);
16975  }
16976
16977  if (typeof version !== 'string') {
16978    return null
16979  }
16980
16981  options = options || {};
16982
16983  let match = null;
16984  if (!options.rtl) {
16985    match = version.match(re$3[t$2.COERCE]);
16986  } else {
16987    // Find the right-most coercible string that does not share
16988    // a terminus with a more left-ward coercible string.
16989    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
16990    //
16991    // Walk through the string checking with a /g regexp
16992    // Manually set the index so as to pick up overlapping matches.
16993    // Stop when we get a match that ends at the string end, since no
16994    // coercible string can be more right-ward without the same terminus.
16995    let next;
16996    while ((next = re$3[t$2.COERCERTL].exec(version)) &&
16997        (!match || match.index + match[0].length !== version.length)
16998    ) {
16999      if (!match ||
17000            next.index + next[0].length !== match.index + match[0].length) {
17001        match = next;
17002      }
17003      re$3[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
17004    }
17005    // leave it in a clean state
17006    re$3[t$2.COERCERTL].lastIndex = -1;
17007  }
17008
17009  if (match === null)
17010    return null
17011
17012  return parse$4(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
17013};
17014var coerce_1 = coerce$I;
17015
17016var iterator = function (Yallist) {
17017  Yallist.prototype[Symbol.iterator] = function* () {
17018    for (let walker = this.head; walker; walker = walker.next) {
17019      yield walker.value;
17020    }
17021  };
17022};
17023
17024var yallist = Yallist$1;
17025
17026Yallist$1.Node = Node;
17027Yallist$1.create = Yallist$1;
17028
17029function Yallist$1 (list) {
17030  var self = this;
17031  if (!(self instanceof Yallist$1)) {
17032    self = new Yallist$1();
17033  }
17034
17035  self.tail = null;
17036  self.head = null;
17037  self.length = 0;
17038
17039  if (list && typeof list.forEach === 'function') {
17040    list.forEach(function (item) {
17041      self.push(item);
17042    });
17043  } else if (arguments.length > 0) {
17044    for (var i = 0, l = arguments.length; i < l; i++) {
17045      self.push(arguments[i]);
17046    }
17047  }
17048
17049  return self
17050}
17051
17052Yallist$1.prototype.removeNode = function (node) {
17053  if (node.list !== this) {
17054    throw new Error('removing node which does not belong to this list')
17055  }
17056
17057  var next = node.next;
17058  var prev = node.prev;
17059
17060  if (next) {
17061    next.prev = prev;
17062  }
17063
17064  if (prev) {
17065    prev.next = next;
17066  }
17067
17068  if (node === this.head) {
17069    this.head = next;
17070  }
17071  if (node === this.tail) {
17072    this.tail = prev;
17073  }
17074
17075  node.list.length--;
17076  node.next = null;
17077  node.prev = null;
17078  node.list = null;
17079
17080  return next
17081};
17082
17083Yallist$1.prototype.unshiftNode = function (node) {
17084  if (node === this.head) {
17085    return
17086  }
17087
17088  if (node.list) {
17089    node.list.removeNode(node);
17090  }
17091
17092  var head = this.head;
17093  node.list = this;
17094  node.next = head;
17095  if (head) {
17096    head.prev = node;
17097  }
17098
17099  this.head = node;
17100  if (!this.tail) {
17101    this.tail = node;
17102  }
17103  this.length++;
17104};
17105
17106Yallist$1.prototype.pushNode = function (node) {
17107  if (node === this.tail) {
17108    return
17109  }
17110
17111  if (node.list) {
17112    node.list.removeNode(node);
17113  }
17114
17115  var tail = this.tail;
17116  node.list = this;
17117  node.prev = tail;
17118  if (tail) {
17119    tail.next = node;
17120  }
17121
17122  this.tail = node;
17123  if (!this.head) {
17124    this.head = node;
17125  }
17126  this.length++;
17127};
17128
17129Yallist$1.prototype.push = function () {
17130  for (var i = 0, l = arguments.length; i < l; i++) {
17131    push$2(this, arguments[i]);
17132  }
17133  return this.length
17134};
17135
17136Yallist$1.prototype.unshift = function () {
17137  for (var i = 0, l = arguments.length; i < l; i++) {
17138    unshift(this, arguments[i]);
17139  }
17140  return this.length
17141};
17142
17143Yallist$1.prototype.pop = function () {
17144  if (!this.tail) {
17145    return undefined
17146  }
17147
17148  var res = this.tail.value;
17149  this.tail = this.tail.prev;
17150  if (this.tail) {
17151    this.tail.next = null;
17152  } else {
17153    this.head = null;
17154  }
17155  this.length--;
17156  return res
17157};
17158
17159Yallist$1.prototype.shift = function () {
17160  if (!this.head) {
17161    return undefined
17162  }
17163
17164  var res = this.head.value;
17165  this.head = this.head.next;
17166  if (this.head) {
17167    this.head.prev = null;
17168  } else {
17169    this.tail = null;
17170  }
17171  this.length--;
17172  return res
17173};
17174
17175Yallist$1.prototype.forEach = function (fn, thisp) {
17176  thisp = thisp || this;
17177  for (var walker = this.head, i = 0; walker !== null; i++) {
17178    fn.call(thisp, walker.value, i, this);
17179    walker = walker.next;
17180  }
17181};
17182
17183Yallist$1.prototype.forEachReverse = function (fn, thisp) {
17184  thisp = thisp || this;
17185  for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
17186    fn.call(thisp, walker.value, i, this);
17187    walker = walker.prev;
17188  }
17189};
17190
17191Yallist$1.prototype.get = function (n) {
17192  for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
17193    // abort out of the list early if we hit a cycle
17194    walker = walker.next;
17195  }
17196  if (i === n && walker !== null) {
17197    return walker.value
17198  }
17199};
17200
17201Yallist$1.prototype.getReverse = function (n) {
17202  for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
17203    // abort out of the list early if we hit a cycle
17204    walker = walker.prev;
17205  }
17206  if (i === n && walker !== null) {
17207    return walker.value
17208  }
17209};
17210
17211Yallist$1.prototype.map = function (fn, thisp) {
17212  thisp = thisp || this;
17213  var res = new Yallist$1();
17214  for (var walker = this.head; walker !== null;) {
17215    res.push(fn.call(thisp, walker.value, this));
17216    walker = walker.next;
17217  }
17218  return res
17219};
17220
17221Yallist$1.prototype.mapReverse = function (fn, thisp) {
17222  thisp = thisp || this;
17223  var res = new Yallist$1();
17224  for (var walker = this.tail; walker !== null;) {
17225    res.push(fn.call(thisp, walker.value, this));
17226    walker = walker.prev;
17227  }
17228  return res
17229};
17230
17231Yallist$1.prototype.reduce = function (fn, initial) {
17232  var acc;
17233  var walker = this.head;
17234  if (arguments.length > 1) {
17235    acc = initial;
17236  } else if (this.head) {
17237    walker = this.head.next;
17238    acc = this.head.value;
17239  } else {
17240    throw new TypeError('Reduce of empty list with no initial value')
17241  }
17242
17243  for (var i = 0; walker !== null; i++) {
17244    acc = fn(acc, walker.value, i);
17245    walker = walker.next;
17246  }
17247
17248  return acc
17249};
17250
17251Yallist$1.prototype.reduceReverse = function (fn, initial) {
17252  var acc;
17253  var walker = this.tail;
17254  if (arguments.length > 1) {
17255    acc = initial;
17256  } else if (this.tail) {
17257    walker = this.tail.prev;
17258    acc = this.tail.value;
17259  } else {
17260    throw new TypeError('Reduce of empty list with no initial value')
17261  }
17262
17263  for (var i = this.length - 1; walker !== null; i--) {
17264    acc = fn(acc, walker.value, i);
17265    walker = walker.prev;
17266  }
17267
17268  return acc
17269};
17270
17271Yallist$1.prototype.toArray = function () {
17272  var arr = new Array(this.length);
17273  for (var i = 0, walker = this.head; walker !== null; i++) {
17274    arr[i] = walker.value;
17275    walker = walker.next;
17276  }
17277  return arr
17278};
17279
17280Yallist$1.prototype.toArrayReverse = function () {
17281  var arr = new Array(this.length);
17282  for (var i = 0, walker = this.tail; walker !== null; i++) {
17283    arr[i] = walker.value;
17284    walker = walker.prev;
17285  }
17286  return arr
17287};
17288
17289Yallist$1.prototype.slice = function (from, to) {
17290  to = to || this.length;
17291  if (to < 0) {
17292    to += this.length;
17293  }
17294  from = from || 0;
17295  if (from < 0) {
17296    from += this.length;
17297  }
17298  var ret = new Yallist$1();
17299  if (to < from || to < 0) {
17300    return ret
17301  }
17302  if (from < 0) {
17303    from = 0;
17304  }
17305  if (to > this.length) {
17306    to = this.length;
17307  }
17308  for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
17309    walker = walker.next;
17310  }
17311  for (; walker !== null && i < to; i++, walker = walker.next) {
17312    ret.push(walker.value);
17313  }
17314  return ret
17315};
17316
17317Yallist$1.prototype.sliceReverse = function (from, to) {
17318  to = to || this.length;
17319  if (to < 0) {
17320    to += this.length;
17321  }
17322  from = from || 0;
17323  if (from < 0) {
17324    from += this.length;
17325  }
17326  var ret = new Yallist$1();
17327  if (to < from || to < 0) {
17328    return ret
17329  }
17330  if (from < 0) {
17331    from = 0;
17332  }
17333  if (to > this.length) {
17334    to = this.length;
17335  }
17336  for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
17337    walker = walker.prev;
17338  }
17339  for (; walker !== null && i > from; i--, walker = walker.prev) {
17340    ret.push(walker.value);
17341  }
17342  return ret
17343};
17344
17345Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) {
17346  if (start > this.length) {
17347    start = this.length - 1;
17348  }
17349  if (start < 0) {
17350    start = this.length + start;
17351  }
17352
17353  for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
17354    walker = walker.next;
17355  }
17356
17357  var ret = [];
17358  for (var i = 0; walker && i < deleteCount; i++) {
17359    ret.push(walker.value);
17360    walker = this.removeNode(walker);
17361  }
17362  if (walker === null) {
17363    walker = this.tail;
17364  }
17365
17366  if (walker !== this.head && walker !== this.tail) {
17367    walker = walker.prev;
17368  }
17369
17370  for (var i = 0; i < nodes.length; i++) {
17371    walker = insert(this, walker, nodes[i]);
17372  }
17373  return ret;
17374};
17375
17376Yallist$1.prototype.reverse = function () {
17377  var head = this.head;
17378  var tail = this.tail;
17379  for (var walker = head; walker !== null; walker = walker.prev) {
17380    var p = walker.prev;
17381    walker.prev = walker.next;
17382    walker.next = p;
17383  }
17384  this.head = tail;
17385  this.tail = head;
17386  return this
17387};
17388
17389function insert (self, node, value) {
17390  var inserted = node === self.head ?
17391    new Node(value, null, node, self) :
17392    new Node(value, node, node.next, self);
17393
17394  if (inserted.next === null) {
17395    self.tail = inserted;
17396  }
17397  if (inserted.prev === null) {
17398    self.head = inserted;
17399  }
17400
17401  self.length++;
17402
17403  return inserted
17404}
17405
17406function push$2 (self, item) {
17407  self.tail = new Node(item, self.tail, null, self);
17408  if (!self.head) {
17409    self.head = self.tail;
17410  }
17411  self.length++;
17412}
17413
17414function unshift (self, item) {
17415  self.head = new Node(item, null, self.head, self);
17416  if (!self.tail) {
17417    self.tail = self.head;
17418  }
17419  self.length++;
17420}
17421
17422function Node (value, prev, next, list) {
17423  if (!(this instanceof Node)) {
17424    return new Node(value, prev, next, list)
17425  }
17426
17427  this.list = list;
17428  this.value = value;
17429
17430  if (prev) {
17431    prev.next = this;
17432    this.prev = prev;
17433  } else {
17434    this.prev = null;
17435  }
17436
17437  if (next) {
17438    next.prev = this;
17439    this.next = next;
17440  } else {
17441    this.next = null;
17442  }
17443}
17444
17445try {
17446  // add if support for Symbol.iterator is present
17447  iterator(Yallist$1);
17448} catch (er) {}
17449
17450// A linked list to keep track of recently-used-ness
17451const Yallist = yallist;
17452
17453const MAX = Symbol('max');
17454const LENGTH = Symbol('length');
17455const LENGTH_CALCULATOR = Symbol('lengthCalculator');
17456const ALLOW_STALE = Symbol('allowStale');
17457const MAX_AGE = Symbol('maxAge');
17458const DISPOSE = Symbol('dispose');
17459const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
17460const LRU_LIST = Symbol('lruList');
17461const CACHE = Symbol('cache');
17462const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
17463
17464const naiveLength = () => 1;
17465
17466// lruList is a yallist where the head is the youngest
17467// item, and the tail is the oldest.  the list contains the Hit
17468// objects as the entries.
17469// Each Hit object has a reference to its Yallist.Node.  This
17470// never changes.
17471//
17472// cache is a Map (or PseudoMap) that matches the keys to
17473// the Yallist.Node object.
17474class LRUCache {
17475  constructor (options) {
17476    if (typeof options === 'number')
17477      options = { max: options };
17478
17479    if (!options)
17480      options = {};
17481
17482    if (options.max && (typeof options.max !== 'number' || options.max < 0))
17483      throw new TypeError('max must be a non-negative number')
17484    // Kind of weird to have a default max of Infinity, but oh well.
17485    this[MAX] = options.max || Infinity;
17486
17487    const lc = options.length || naiveLength;
17488    this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc;
17489    this[ALLOW_STALE] = options.stale || false;
17490    if (options.maxAge && typeof options.maxAge !== 'number')
17491      throw new TypeError('maxAge must be a number')
17492    this[MAX_AGE] = options.maxAge || 0;
17493    this[DISPOSE] = options.dispose;
17494    this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
17495    this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
17496    this.reset();
17497  }
17498
17499  // resize the cache when the max changes.
17500  set max (mL) {
17501    if (typeof mL !== 'number' || mL < 0)
17502      throw new TypeError('max must be a non-negative number')
17503
17504    this[MAX] = mL || Infinity;
17505    trim(this);
17506  }
17507  get max () {
17508    return this[MAX]
17509  }
17510
17511  set allowStale (allowStale) {
17512    this[ALLOW_STALE] = !!allowStale;
17513  }
17514  get allowStale () {
17515    return this[ALLOW_STALE]
17516  }
17517
17518  set maxAge (mA) {
17519    if (typeof mA !== 'number')
17520      throw new TypeError('maxAge must be a non-negative number')
17521
17522    this[MAX_AGE] = mA;
17523    trim(this);
17524  }
17525  get maxAge () {
17526    return this[MAX_AGE]
17527  }
17528
17529  // resize the cache when the lengthCalculator changes.
17530  set lengthCalculator (lC) {
17531    if (typeof lC !== 'function')
17532      lC = naiveLength;
17533
17534    if (lC !== this[LENGTH_CALCULATOR]) {
17535      this[LENGTH_CALCULATOR] = lC;
17536      this[LENGTH] = 0;
17537      this[LRU_LIST].forEach(hit => {
17538        hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
17539        this[LENGTH] += hit.length;
17540      });
17541    }
17542    trim(this);
17543  }
17544  get lengthCalculator () { return this[LENGTH_CALCULATOR] }
17545
17546  get length () { return this[LENGTH] }
17547  get itemCount () { return this[LRU_LIST].length }
17548
17549  rforEach (fn, thisp) {
17550    thisp = thisp || this;
17551    for (let walker = this[LRU_LIST].tail; walker !== null;) {
17552      const prev = walker.prev;
17553      forEachStep(this, fn, walker, thisp);
17554      walker = prev;
17555    }
17556  }
17557
17558  forEach (fn, thisp) {
17559    thisp = thisp || this;
17560    for (let walker = this[LRU_LIST].head; walker !== null;) {
17561      const next = walker.next;
17562      forEachStep(this, fn, walker, thisp);
17563      walker = next;
17564    }
17565  }
17566
17567  keys () {
17568    return this[LRU_LIST].toArray().map(k => k.key)
17569  }
17570
17571  values () {
17572    return this[LRU_LIST].toArray().map(k => k.value)
17573  }
17574
17575  reset () {
17576    if (this[DISPOSE] &&
17577        this[LRU_LIST] &&
17578        this[LRU_LIST].length) {
17579      this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
17580    }
17581
17582    this[CACHE] = new Map(); // hash of items by key
17583    this[LRU_LIST] = new Yallist(); // list of items in order of use recency
17584    this[LENGTH] = 0; // length of items in the list
17585  }
17586
17587  dump () {
17588    return this[LRU_LIST].map(hit =>
17589      isStale(this, hit) ? false : {
17590        k: hit.key,
17591        v: hit.value,
17592        e: hit.now + (hit.maxAge || 0)
17593      }).toArray().filter(h => h)
17594  }
17595
17596  dumpLru () {
17597    return this[LRU_LIST]
17598  }
17599
17600  set (key, value, maxAge) {
17601    maxAge = maxAge || this[MAX_AGE];
17602
17603    if (maxAge && typeof maxAge !== 'number')
17604      throw new TypeError('maxAge must be a number')
17605
17606    const now = maxAge ? Date.now() : 0;
17607    const len = this[LENGTH_CALCULATOR](value, key);
17608
17609    if (this[CACHE].has(key)) {
17610      if (len > this[MAX]) {
17611        del(this, this[CACHE].get(key));
17612        return false
17613      }
17614
17615      const node = this[CACHE].get(key);
17616      const item = node.value;
17617
17618      // dispose of the old one before overwriting
17619      // split out into 2 ifs for better coverage tracking
17620      if (this[DISPOSE]) {
17621        if (!this[NO_DISPOSE_ON_SET])
17622          this[DISPOSE](key, item.value);
17623      }
17624
17625      item.now = now;
17626      item.maxAge = maxAge;
17627      item.value = value;
17628      this[LENGTH] += len - item.length;
17629      item.length = len;
17630      this.get(key);
17631      trim(this);
17632      return true
17633    }
17634
17635    const hit = new Entry(key, value, len, now, maxAge);
17636
17637    // oversized objects fall out of cache automatically.
17638    if (hit.length > this[MAX]) {
17639      if (this[DISPOSE])
17640        this[DISPOSE](key, value);
17641
17642      return false
17643    }
17644
17645    this[LENGTH] += hit.length;
17646    this[LRU_LIST].unshift(hit);
17647    this[CACHE].set(key, this[LRU_LIST].head);
17648    trim(this);
17649    return true
17650  }
17651
17652  has (key) {
17653    if (!this[CACHE].has(key)) return false
17654    const hit = this[CACHE].get(key).value;
17655    return !isStale(this, hit)
17656  }
17657
17658  get (key) {
17659    return get(this, key, true)
17660  }
17661
17662  peek (key) {
17663    return get(this, key, false)
17664  }
17665
17666  pop () {
17667    const node = this[LRU_LIST].tail;
17668    if (!node)
17669      return null
17670
17671    del(this, node);
17672    return node.value
17673  }
17674
17675  del (key) {
17676    del(this, this[CACHE].get(key));
17677  }
17678
17679  load (arr) {
17680    // reset the cache
17681    this.reset();
17682
17683    const now = Date.now();
17684    // A previous serialized cache has the most recent items first
17685    for (let l = arr.length - 1; l >= 0; l--) {
17686      const hit = arr[l];
17687      const expiresAt = hit.e || 0;
17688      if (expiresAt === 0)
17689        // the item was created without expiration in a non aged cache
17690        this.set(hit.k, hit.v);
17691      else {
17692        const maxAge = expiresAt - now;
17693        // dont add already expired items
17694        if (maxAge > 0) {
17695          this.set(hit.k, hit.v, maxAge);
17696        }
17697      }
17698    }
17699  }
17700
17701  prune () {
17702    this[CACHE].forEach((value, key) => get(this, key, false));
17703  }
17704}
17705
17706const get = (self, key, doUse) => {
17707  const node = self[CACHE].get(key);
17708  if (node) {
17709    const hit = node.value;
17710    if (isStale(self, hit)) {
17711      del(self, node);
17712      if (!self[ALLOW_STALE])
17713        return undefined
17714    } else {
17715      if (doUse) {
17716        if (self[UPDATE_AGE_ON_GET])
17717          node.value.now = Date.now();
17718        self[LRU_LIST].unshiftNode(node);
17719      }
17720    }
17721    return hit.value
17722  }
17723};
17724
17725const isStale = (self, hit) => {
17726  if (!hit || (!hit.maxAge && !self[MAX_AGE]))
17727    return false
17728
17729  const diff = Date.now() - hit.now;
17730  return hit.maxAge ? diff > hit.maxAge
17731    : self[MAX_AGE] && (diff > self[MAX_AGE])
17732};
17733
17734const trim = self => {
17735  if (self[LENGTH] > self[MAX]) {
17736    for (let walker = self[LRU_LIST].tail;
17737      self[LENGTH] > self[MAX] && walker !== null;) {
17738      // We know that we're about to delete this one, and also
17739      // what the next least recently used key will be, so just
17740      // go ahead and set it now.
17741      const prev = walker.prev;
17742      del(self, walker);
17743      walker = prev;
17744    }
17745  }
17746};
17747
17748const del = (self, node) => {
17749  if (node) {
17750    const hit = node.value;
17751    if (self[DISPOSE])
17752      self[DISPOSE](hit.key, hit.value);
17753
17754    self[LENGTH] -= hit.length;
17755    self[CACHE].delete(hit.key);
17756    self[LRU_LIST].removeNode(node);
17757  }
17758};
17759
17760class Entry {
17761  constructor (key, value, length, now, maxAge) {
17762    this.key = key;
17763    this.value = value;
17764    this.length = length;
17765    this.now = now;
17766    this.maxAge = maxAge || 0;
17767  }
17768}
17769
17770const forEachStep = (self, fn, node, thisp) => {
17771  let hit = node.value;
17772  if (isStale(self, hit)) {
17773    del(self, node);
17774    if (!self[ALLOW_STALE])
17775      hit = undefined;
17776  }
17777  if (hit)
17778    fn.call(thisp, hit.value, hit.key, self);
17779};
17780
17781var lruCache = LRUCache;
17782
17783// hoisted class for cyclic dependency
17784class Range$a {
17785  constructor (range, options) {
17786    options = parseOptions$1(options);
17787
17788    if (range instanceof Range$a) {
17789      if (
17790        range.loose === !!options.loose &&
17791        range.includePrerelease === !!options.includePrerelease
17792      ) {
17793        return range
17794      } else {
17795        return new Range$a(range.raw, options)
17796      }
17797    }
17798
17799    if (range instanceof Comparator$2) {
17800      // just put it in the set and return
17801      this.raw = range.value;
17802      this.set = [[range]];
17803      this.format();
17804      return this
17805    }
17806
17807    this.options = options;
17808    this.loose = !!options.loose;
17809    this.includePrerelease = !!options.includePrerelease;
17810
17811    // First, split based on boolean or ||
17812    this.raw = range;
17813    this.set = range
17814      .split(/\s*\|\|\s*/)
17815      // map the range to a 2d array of comparators
17816      .map(range => this.parseRange(range.trim()))
17817      // throw out any comparator lists that are empty
17818      // this generally means that it was not a valid range, which is allowed
17819      // in loose mode, but will still throw if the WHOLE range is invalid.
17820      .filter(c => c.length);
17821
17822    if (!this.set.length) {
17823      throw new TypeError(`Invalid SemVer Range: ${range}`)
17824    }
17825
17826    // if we have any that are not the null set, throw out null sets.
17827    if (this.set.length > 1) {
17828      // keep the first one, in case they're all null sets
17829      const first = this.set[0];
17830      this.set = this.set.filter(c => !isNullSet(c[0]));
17831      if (this.set.length === 0)
17832        this.set = [first];
17833      else if (this.set.length > 1) {
17834        // if we have any that are *, then the range is just *
17835        for (const c of this.set) {
17836          if (c.length === 1 && isAny(c[0])) {
17837            this.set = [c];
17838            break
17839          }
17840        }
17841      }
17842    }
17843
17844    this.format();
17845  }
17846
17847  format () {
17848    this.range = this.set
17849      .map((comps) => {
17850        return comps.join(' ').trim()
17851      })
17852      .join('||')
17853      .trim();
17854    return this.range
17855  }
17856
17857  toString () {
17858    return this.range
17859  }
17860
17861  parseRange (range) {
17862    range = range.trim();
17863
17864    // memoize range parsing for performance.
17865    // this is a very hot path, and fully deterministic.
17866    const memoOpts = Object.keys(this.options).join(',');
17867    const memoKey = `parseRange:${memoOpts}:${range}`;
17868    const cached = cache$1.get(memoKey);
17869    if (cached)
17870      return cached
17871
17872    const loose = this.options.loose;
17873    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
17874    const hr = loose ? re$2[t$1.HYPHENRANGELOOSE] : re$2[t$1.HYPHENRANGE];
17875    range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
17876    debug$d('hyphen replace', range);
17877    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
17878    range = range.replace(re$2[t$1.COMPARATORTRIM], comparatorTrimReplace);
17879    debug$d('comparator trim', range, re$2[t$1.COMPARATORTRIM]);
17880
17881    // `~ 1.2.3` => `~1.2.3`
17882    range = range.replace(re$2[t$1.TILDETRIM], tildeTrimReplace);
17883
17884    // `^ 1.2.3` => `^1.2.3`
17885    range = range.replace(re$2[t$1.CARETTRIM], caretTrimReplace);
17886
17887    // normalize spaces
17888    range = range.split(/\s+/).join(' ');
17889
17890    // At this point, the range is completely trimmed and
17891    // ready to be split into comparators.
17892
17893    const compRe = loose ? re$2[t$1.COMPARATORLOOSE] : re$2[t$1.COMPARATOR];
17894    const rangeList = range
17895      .split(' ')
17896      .map(comp => parseComparator(comp, this.options))
17897      .join(' ')
17898      .split(/\s+/)
17899      // >=0.0.0 is equivalent to *
17900      .map(comp => replaceGTE0(comp, this.options))
17901      // in loose mode, throw out any that are not valid comparators
17902      .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
17903      .map(comp => new Comparator$2(comp, this.options));
17904
17905    // if any comparators are the null set, then replace with JUST null set
17906    // if more than one comparator, remove any * comparators
17907    // also, don't include the same comparator more than once
17908    rangeList.length;
17909    const rangeMap = new Map();
17910    for (const comp of rangeList) {
17911      if (isNullSet(comp))
17912        return [comp]
17913      rangeMap.set(comp.value, comp);
17914    }
17915    if (rangeMap.size > 1 && rangeMap.has(''))
17916      rangeMap.delete('');
17917
17918    const result = [...rangeMap.values()];
17919    cache$1.set(memoKey, result);
17920    return result
17921  }
17922
17923  intersects (range, options) {
17924    if (!(range instanceof Range$a)) {
17925      throw new TypeError('a Range is required')
17926    }
17927
17928    return this.set.some((thisComparators) => {
17929      return (
17930        isSatisfiable(thisComparators, options) &&
17931        range.set.some((rangeComparators) => {
17932          return (
17933            isSatisfiable(rangeComparators, options) &&
17934            thisComparators.every((thisComparator) => {
17935              return rangeComparators.every((rangeComparator) => {
17936                return thisComparator.intersects(rangeComparator, options)
17937              })
17938            })
17939          )
17940        })
17941      )
17942    })
17943  }
17944
17945  // if ANY of the sets match ALL of its comparators, then pass
17946  test (version) {
17947    if (!version) {
17948      return false
17949    }
17950
17951    if (typeof version === 'string') {
17952      try {
17953        version = new SemVer$5(version, this.options);
17954      } catch (er) {
17955        return false
17956      }
17957    }
17958
17959    for (let i = 0; i < this.set.length; i++) {
17960      if (testSet(this.set[i], version, this.options)) {
17961        return true
17962      }
17963    }
17964    return false
17965  }
17966}
17967var range$1 = Range$a;
17968
17969const LRU = lruCache;
17970const cache$1 = new LRU({ max: 1000 });
17971
17972const parseOptions$1 = parseOptions_1;
17973const Comparator$2 = comparator$1;
17974const debug$d = debug_1;
17975const SemVer$5 = semver$2;
17976const {
17977  re: re$2,
17978  t: t$1,
17979  comparatorTrimReplace,
17980  tildeTrimReplace,
17981  caretTrimReplace
17982} = re$6.exports;
17983
17984const isNullSet = c => c.value === '<0.0.0-0';
17985const isAny = c => c.value === '';
17986
17987// take a set of comparators and determine whether there
17988// exists a version which can satisfy it
17989const isSatisfiable = (comparators, options) => {
17990  let result = true;
17991  const remainingComparators = comparators.slice();
17992  let testComparator = remainingComparators.pop();
17993
17994  while (result && remainingComparators.length) {
17995    result = remainingComparators.every((otherComparator) => {
17996      return testComparator.intersects(otherComparator, options)
17997    });
17998
17999    testComparator = remainingComparators.pop();
18000  }
18001
18002  return result
18003};
18004
18005// comprised of xranges, tildes, stars, and gtlt's at this point.
18006// already replaced the hyphen ranges
18007// turn into a set of JUST comparators.
18008const parseComparator = (comp, options) => {
18009  debug$d('comp', comp, options);
18010  comp = replaceCarets(comp, options);
18011  debug$d('caret', comp);
18012  comp = replaceTildes(comp, options);
18013  debug$d('tildes', comp);
18014  comp = replaceXRanges(comp, options);
18015  debug$d('xrange', comp);
18016  comp = replaceStars(comp, options);
18017  debug$d('stars', comp);
18018  return comp
18019};
18020
18021const isX = id => !id || id.toLowerCase() === 'x' || id === '*';
18022
18023// ~, ~> --> * (any, kinda silly)
18024// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
18025// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
18026// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
18027// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
18028// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
18029const replaceTildes = (comp, options) =>
18030  comp.trim().split(/\s+/).map((comp) => {
18031    return replaceTilde(comp, options)
18032  }).join(' ');
18033
18034const replaceTilde = (comp, options) => {
18035  const r = options.loose ? re$2[t$1.TILDELOOSE] : re$2[t$1.TILDE];
18036  return comp.replace(r, (_, M, m, p, pr) => {
18037    debug$d('tilde', comp, _, M, m, p, pr);
18038    let ret;
18039
18040    if (isX(M)) {
18041      ret = '';
18042    } else if (isX(m)) {
18043      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
18044    } else if (isX(p)) {
18045      // ~1.2 == >=1.2.0 <1.3.0-0
18046      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
18047    } else if (pr) {
18048      debug$d('replaceTilde pr', pr);
18049      ret = `>=${M}.${m}.${p}-${pr
18050      } <${M}.${+m + 1}.0-0`;
18051    } else {
18052      // ~1.2.3 == >=1.2.3 <1.3.0-0
18053      ret = `>=${M}.${m}.${p
18054      } <${M}.${+m + 1}.0-0`;
18055    }
18056
18057    debug$d('tilde return', ret);
18058    return ret
18059  })
18060};
18061
18062// ^ --> * (any, kinda silly)
18063// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
18064// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
18065// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
18066// ^1.2.3 --> >=1.2.3 <2.0.0-0
18067// ^1.2.0 --> >=1.2.0 <2.0.0-0
18068const replaceCarets = (comp, options) =>
18069  comp.trim().split(/\s+/).map((comp) => {
18070    return replaceCaret(comp, options)
18071  }).join(' ');
18072
18073const replaceCaret = (comp, options) => {
18074  debug$d('caret', comp, options);
18075  const r = options.loose ? re$2[t$1.CARETLOOSE] : re$2[t$1.CARET];
18076  const z = options.includePrerelease ? '-0' : '';
18077  return comp.replace(r, (_, M, m, p, pr) => {
18078    debug$d('caret', comp, _, M, m, p, pr);
18079    let ret;
18080
18081    if (isX(M)) {
18082      ret = '';
18083    } else if (isX(m)) {
18084      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
18085    } else if (isX(p)) {
18086      if (M === '0') {
18087        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
18088      } else {
18089        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
18090      }
18091    } else if (pr) {
18092      debug$d('replaceCaret pr', pr);
18093      if (M === '0') {
18094        if (m === '0') {
18095          ret = `>=${M}.${m}.${p}-${pr
18096          } <${M}.${m}.${+p + 1}-0`;
18097        } else {
18098          ret = `>=${M}.${m}.${p}-${pr
18099          } <${M}.${+m + 1}.0-0`;
18100        }
18101      } else {
18102        ret = `>=${M}.${m}.${p}-${pr
18103        } <${+M + 1}.0.0-0`;
18104      }
18105    } else {
18106      debug$d('no pr');
18107      if (M === '0') {
18108        if (m === '0') {
18109          ret = `>=${M}.${m}.${p
18110          }${z} <${M}.${m}.${+p + 1}-0`;
18111        } else {
18112          ret = `>=${M}.${m}.${p
18113          }${z} <${M}.${+m + 1}.0-0`;
18114        }
18115      } else {
18116        ret = `>=${M}.${m}.${p
18117        } <${+M + 1}.0.0-0`;
18118      }
18119    }
18120
18121    debug$d('caret return', ret);
18122    return ret
18123  })
18124};
18125
18126const replaceXRanges = (comp, options) => {
18127  debug$d('replaceXRanges', comp, options);
18128  return comp.split(/\s+/).map((comp) => {
18129    return replaceXRange(comp, options)
18130  }).join(' ')
18131};
18132
18133const replaceXRange = (comp, options) => {
18134  comp = comp.trim();
18135  const r = options.loose ? re$2[t$1.XRANGELOOSE] : re$2[t$1.XRANGE];
18136  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
18137    debug$d('xRange', comp, ret, gtlt, M, m, p, pr);
18138    const xM = isX(M);
18139    const xm = xM || isX(m);
18140    const xp = xm || isX(p);
18141    const anyX = xp;
18142
18143    if (gtlt === '=' && anyX) {
18144      gtlt = '';
18145    }
18146
18147    // if we're including prereleases in the match, then we need
18148    // to fix this to -0, the lowest possible prerelease value
18149    pr = options.includePrerelease ? '-0' : '';
18150
18151    if (xM) {
18152      if (gtlt === '>' || gtlt === '<') {
18153        // nothing is allowed
18154        ret = '<0.0.0-0';
18155      } else {
18156        // nothing is forbidden
18157        ret = '*';
18158      }
18159    } else if (gtlt && anyX) {
18160      // we know patch is an x, because we have any x at all.
18161      // replace X with 0
18162      if (xm) {
18163        m = 0;
18164      }
18165      p = 0;
18166
18167      if (gtlt === '>') {
18168        // >1 => >=2.0.0
18169        // >1.2 => >=1.3.0
18170        gtlt = '>=';
18171        if (xm) {
18172          M = +M + 1;
18173          m = 0;
18174          p = 0;
18175        } else {
18176          m = +m + 1;
18177          p = 0;
18178        }
18179      } else if (gtlt === '<=') {
18180        // <=0.7.x is actually <0.8.0, since any 0.7.x should
18181        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
18182        gtlt = '<';
18183        if (xm) {
18184          M = +M + 1;
18185        } else {
18186          m = +m + 1;
18187        }
18188      }
18189
18190      if (gtlt === '<')
18191        pr = '-0';
18192
18193      ret = `${gtlt + M}.${m}.${p}${pr}`;
18194    } else if (xm) {
18195      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
18196    } else if (xp) {
18197      ret = `>=${M}.${m}.0${pr
18198      } <${M}.${+m + 1}.0-0`;
18199    }
18200
18201    debug$d('xRange return', ret);
18202
18203    return ret
18204  })
18205};
18206
18207// Because * is AND-ed with everything else in the comparator,
18208// and '' means "any version", just remove the *s entirely.
18209const replaceStars = (comp, options) => {
18210  debug$d('replaceStars', comp, options);
18211  // Looseness is ignored here.  star is always as loose as it gets!
18212  return comp.trim().replace(re$2[t$1.STAR], '')
18213};
18214
18215const replaceGTE0 = (comp, options) => {
18216  debug$d('replaceGTE0', comp, options);
18217  return comp.trim()
18218    .replace(re$2[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '')
18219};
18220
18221// This function is passed to string.replace(re[t.HYPHENRANGE])
18222// M, m, patch, prerelease, build
18223// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
18224// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
18225// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
18226const hyphenReplace = incPr => ($0,
18227  from, fM, fm, fp, fpr, fb,
18228  to, tM, tm, tp, tpr, tb) => {
18229  if (isX(fM)) {
18230    from = '';
18231  } else if (isX(fm)) {
18232    from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
18233  } else if (isX(fp)) {
18234    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
18235  } else if (fpr) {
18236    from = `>=${from}`;
18237  } else {
18238    from = `>=${from}${incPr ? '-0' : ''}`;
18239  }
18240
18241  if (isX(tM)) {
18242    to = '';
18243  } else if (isX(tm)) {
18244    to = `<${+tM + 1}.0.0-0`;
18245  } else if (isX(tp)) {
18246    to = `<${tM}.${+tm + 1}.0-0`;
18247  } else if (tpr) {
18248    to = `<=${tM}.${tm}.${tp}-${tpr}`;
18249  } else if (incPr) {
18250    to = `<${tM}.${tm}.${+tp + 1}-0`;
18251  } else {
18252    to = `<=${to}`;
18253  }
18254
18255  return (`${from} ${to}`).trim()
18256};
18257
18258const testSet = (set, version, options) => {
18259  for (let i = 0; i < set.length; i++) {
18260    if (!set[i].test(version)) {
18261      return false
18262    }
18263  }
18264
18265  if (version.prerelease.length && !options.includePrerelease) {
18266    // Find the set of versions that are allowed to have prereleases
18267    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
18268    // That should allow `1.2.3-pr.2` to pass.
18269    // However, `1.2.4-alpha.notready` should NOT be allowed,
18270    // even though it's within the range set by the comparators.
18271    for (let i = 0; i < set.length; i++) {
18272      debug$d(set[i].semver);
18273      if (set[i].semver === Comparator$2.ANY) {
18274        continue
18275      }
18276
18277      if (set[i].semver.prerelease.length > 0) {
18278        const allowed = set[i].semver;
18279        if (allowed.major === version.major &&
18280            allowed.minor === version.minor &&
18281            allowed.patch === version.patch) {
18282          return true
18283        }
18284      }
18285    }
18286
18287    // Version has a -pre, but it's not one of the ones we like.
18288    return false
18289  }
18290
18291  return true
18292};
18293
18294const ANY$2 = Symbol('SemVer ANY');
18295// hoisted class for cyclic dependency
18296class Comparator$1 {
18297  static get ANY () {
18298    return ANY$2
18299  }
18300  constructor (comp, options) {
18301    options = parseOptions(options);
18302
18303    if (comp instanceof Comparator$1) {
18304      if (comp.loose === !!options.loose) {
18305        return comp
18306      } else {
18307        comp = comp.value;
18308      }
18309    }
18310
18311    debug$c('comparator', comp, options);
18312    this.options = options;
18313    this.loose = !!options.loose;
18314    this.parse(comp);
18315
18316    if (this.semver === ANY$2) {
18317      this.value = '';
18318    } else {
18319      this.value = this.operator + this.semver.version;
18320    }
18321
18322    debug$c('comp', this);
18323  }
18324
18325  parse (comp) {
18326    const r = this.options.loose ? re$1[t.COMPARATORLOOSE] : re$1[t.COMPARATOR];
18327    const m = comp.match(r);
18328
18329    if (!m) {
18330      throw new TypeError(`Invalid comparator: ${comp}`)
18331    }
18332
18333    this.operator = m[1] !== undefined ? m[1] : '';
18334    if (this.operator === '=') {
18335      this.operator = '';
18336    }
18337
18338    // if it literally is just '>' or '' then allow anything.
18339    if (!m[2]) {
18340      this.semver = ANY$2;
18341    } else {
18342      this.semver = new SemVer$4(m[2], this.options.loose);
18343    }
18344  }
18345
18346  toString () {
18347    return this.value
18348  }
18349
18350  test (version) {
18351    debug$c('Comparator.test', version, this.options.loose);
18352
18353    if (this.semver === ANY$2 || version === ANY$2) {
18354      return true
18355    }
18356
18357    if (typeof version === 'string') {
18358      try {
18359        version = new SemVer$4(version, this.options);
18360      } catch (er) {
18361        return false
18362      }
18363    }
18364
18365    return cmp(version, this.operator, this.semver, this.options)
18366  }
18367
18368  intersects (comp, options) {
18369    if (!(comp instanceof Comparator$1)) {
18370      throw new TypeError('a Comparator is required')
18371    }
18372
18373    if (!options || typeof options !== 'object') {
18374      options = {
18375        loose: !!options,
18376        includePrerelease: false
18377      };
18378    }
18379
18380    if (this.operator === '') {
18381      if (this.value === '') {
18382        return true
18383      }
18384      return new Range$9(comp.value, options).test(this.value)
18385    } else if (comp.operator === '') {
18386      if (comp.value === '') {
18387        return true
18388      }
18389      return new Range$9(this.value, options).test(comp.semver)
18390    }
18391
18392    const sameDirectionIncreasing =
18393      (this.operator === '>=' || this.operator === '>') &&
18394      (comp.operator === '>=' || comp.operator === '>');
18395    const sameDirectionDecreasing =
18396      (this.operator === '<=' || this.operator === '<') &&
18397      (comp.operator === '<=' || comp.operator === '<');
18398    const sameSemVer = this.semver.version === comp.semver.version;
18399    const differentDirectionsInclusive =
18400      (this.operator === '>=' || this.operator === '<=') &&
18401      (comp.operator === '>=' || comp.operator === '<=');
18402    const oppositeDirectionsLessThan =
18403      cmp(this.semver, '<', comp.semver, options) &&
18404      (this.operator === '>=' || this.operator === '>') &&
18405        (comp.operator === '<=' || comp.operator === '<');
18406    const oppositeDirectionsGreaterThan =
18407      cmp(this.semver, '>', comp.semver, options) &&
18408      (this.operator === '<=' || this.operator === '<') &&
18409        (comp.operator === '>=' || comp.operator === '>');
18410
18411    return (
18412      sameDirectionIncreasing ||
18413      sameDirectionDecreasing ||
18414      (sameSemVer && differentDirectionsInclusive) ||
18415      oppositeDirectionsLessThan ||
18416      oppositeDirectionsGreaterThan
18417    )
18418  }
18419}
18420
18421var comparator$1 = Comparator$1;
18422
18423const parseOptions = parseOptions_1;
18424const {re: re$1, t} = re$6.exports;
18425const cmp = cmp_1;
18426const debug$c = debug_1;
18427const SemVer$4 = semver$2;
18428const Range$9 = range$1;
18429
18430const Range$8 = range$1;
18431const satisfies$3 = (version, range, options) => {
18432  try {
18433    range = new Range$8(range, options);
18434  } catch (er) {
18435    return false
18436  }
18437  return range.test(version)
18438};
18439var satisfies_1 = satisfies$3;
18440
18441const Range$7 = range$1;
18442
18443// Mostly just for testing and legacy API reasons
18444const toComparators = (range, options) =>
18445  new Range$7(range, options).set
18446    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
18447
18448var toComparators_1 = toComparators;
18449
18450const SemVer$3 = semver$2;
18451const Range$6 = range$1;
18452
18453const maxSatisfying = (versions, range, options) => {
18454  let max = null;
18455  let maxSV = null;
18456  let rangeObj = null;
18457  try {
18458    rangeObj = new Range$6(range, options);
18459  } catch (er) {
18460    return null
18461  }
18462  versions.forEach((v) => {
18463    if (rangeObj.test(v)) {
18464      // satisfies(v, range, options)
18465      if (!max || maxSV.compare(v) === -1) {
18466        // compare(max, v, true)
18467        max = v;
18468        maxSV = new SemVer$3(max, options);
18469      }
18470    }
18471  });
18472  return max
18473};
18474var maxSatisfying_1 = maxSatisfying;
18475
18476const SemVer$2 = semver$2;
18477const Range$5 = range$1;
18478const minSatisfying = (versions, range, options) => {
18479  let min = null;
18480  let minSV = null;
18481  let rangeObj = null;
18482  try {
18483    rangeObj = new Range$5(range, options);
18484  } catch (er) {
18485    return null
18486  }
18487  versions.forEach((v) => {
18488    if (rangeObj.test(v)) {
18489      // satisfies(v, range, options)
18490      if (!min || minSV.compare(v) === 1) {
18491        // compare(min, v, true)
18492        min = v;
18493        minSV = new SemVer$2(min, options);
18494      }
18495    }
18496  });
18497  return min
18498};
18499var minSatisfying_1 = minSatisfying;
18500
18501const SemVer$1 = semver$2;
18502const Range$4 = range$1;
18503const gt$1 = gt_1;
18504
18505const minVersion = (range, loose) => {
18506  range = new Range$4(range, loose);
18507
18508  let minver = new SemVer$1('0.0.0');
18509  if (range.test(minver)) {
18510    return minver
18511  }
18512
18513  minver = new SemVer$1('0.0.0-0');
18514  if (range.test(minver)) {
18515    return minver
18516  }
18517
18518  minver = null;
18519  for (let i = 0; i < range.set.length; ++i) {
18520    const comparators = range.set[i];
18521
18522    let setMin = null;
18523    comparators.forEach((comparator) => {
18524      // Clone to avoid manipulating the comparator's semver object.
18525      const compver = new SemVer$1(comparator.semver.version);
18526      switch (comparator.operator) {
18527        case '>':
18528          if (compver.prerelease.length === 0) {
18529            compver.patch++;
18530          } else {
18531            compver.prerelease.push(0);
18532          }
18533          compver.raw = compver.format();
18534          /* fallthrough */
18535        case '':
18536        case '>=':
18537          if (!setMin || gt$1(compver, setMin)) {
18538            setMin = compver;
18539          }
18540          break
18541        case '<':
18542        case '<=':
18543          /* Ignore maximum versions */
18544          break
18545        /* istanbul ignore next */
18546        default:
18547          throw new Error(`Unexpected operation: ${comparator.operator}`)
18548      }
18549    });
18550    if (setMin && (!minver || gt$1(minver, setMin)))
18551      minver = setMin;
18552  }
18553
18554  if (minver && range.test(minver)) {
18555    return minver
18556  }
18557
18558  return null
18559};
18560var minVersion_1 = minVersion;
18561
18562const Range$3 = range$1;
18563const validRange = (range, options) => {
18564  try {
18565    // Return '*' instead of '' so that truthiness works.
18566    // This will throw if it's invalid anyway
18567    return new Range$3(range, options).range || '*'
18568  } catch (er) {
18569    return null
18570  }
18571};
18572var valid = validRange;
18573
18574const SemVer = semver$2;
18575const Comparator = comparator$1;
18576const {ANY: ANY$1} = Comparator;
18577const Range$2 = range$1;
18578const satisfies$2 = satisfies_1;
18579const gt = gt_1;
18580const lt = lt_1;
18581const lte$1 = lte_1;
18582const gte$1 = gte_1;
18583
18584const outside$2 = (version, range, hilo, options) => {
18585  version = new SemVer(version, options);
18586  range = new Range$2(range, options);
18587
18588  let gtfn, ltefn, ltfn, comp, ecomp;
18589  switch (hilo) {
18590    case '>':
18591      gtfn = gt;
18592      ltefn = lte$1;
18593      ltfn = lt;
18594      comp = '>';
18595      ecomp = '>=';
18596      break
18597    case '<':
18598      gtfn = lt;
18599      ltefn = gte$1;
18600      ltfn = gt;
18601      comp = '<';
18602      ecomp = '<=';
18603      break
18604    default:
18605      throw new TypeError('Must provide a hilo val of "<" or ">"')
18606  }
18607
18608  // If it satisfies the range it is not outside
18609  if (satisfies$2(version, range, options)) {
18610    return false
18611  }
18612
18613  // From now on, variable terms are as if we're in "gtr" mode.
18614  // but note that everything is flipped for the "ltr" function.
18615
18616  for (let i = 0; i < range.set.length; ++i) {
18617    const comparators = range.set[i];
18618
18619    let high = null;
18620    let low = null;
18621
18622    comparators.forEach((comparator) => {
18623      if (comparator.semver === ANY$1) {
18624        comparator = new Comparator('>=0.0.0');
18625      }
18626      high = high || comparator;
18627      low = low || comparator;
18628      if (gtfn(comparator.semver, high.semver, options)) {
18629        high = comparator;
18630      } else if (ltfn(comparator.semver, low.semver, options)) {
18631        low = comparator;
18632      }
18633    });
18634
18635    // If the edge version comparator has a operator then our version
18636    // isn't outside it
18637    if (high.operator === comp || high.operator === ecomp) {
18638      return false
18639    }
18640
18641    // If the lowest version comparator has an operator and our version
18642    // is less than it then it isn't higher than the range
18643    if ((!low.operator || low.operator === comp) &&
18644        ltefn(version, low.semver)) {
18645      return false
18646    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
18647      return false
18648    }
18649  }
18650  return true
18651};
18652
18653var outside_1 = outside$2;
18654
18655// Determine if version is greater than all the versions possible in the range.
18656const outside$1 = outside_1;
18657const gtr = (version, range, options) => outside$1(version, range, '>', options);
18658var gtr_1 = gtr;
18659
18660const outside = outside_1;
18661// Determine if version is less than all the versions possible in the range
18662const ltr = (version, range, options) => outside(version, range, '<', options);
18663var ltr_1 = ltr;
18664
18665const Range$1 = range$1;
18666const intersects = (r1, r2, options) => {
18667  r1 = new Range$1(r1, options);
18668  r2 = new Range$1(r2, options);
18669  return r1.intersects(r2)
18670};
18671var intersects_1 = intersects;
18672
18673// given a set of versions and a range, create a "simplified" range
18674// that includes the same versions that the original range does
18675// If the original range is shorter than the simplified one, return that.
18676const satisfies$1 = satisfies_1;
18677const compare$2 = compare_1;
18678var simplify = (versions, range, options) => {
18679  const set = [];
18680  let min = null;
18681  let prev = null;
18682  const v = versions.sort((a, b) => compare$2(a, b, options));
18683  for (const version of v) {
18684    const included = satisfies$1(version, range, options);
18685    if (included) {
18686      prev = version;
18687      if (!min)
18688        min = version;
18689    } else {
18690      if (prev) {
18691        set.push([min, prev]);
18692      }
18693      prev = null;
18694      min = null;
18695    }
18696  }
18697  if (min)
18698    set.push([min, null]);
18699
18700  const ranges = [];
18701  for (const [min, max] of set) {
18702    if (min === max)
18703      ranges.push(min);
18704    else if (!max && min === v[0])
18705      ranges.push('*');
18706    else if (!max)
18707      ranges.push(`>=${min}`);
18708    else if (min === v[0])
18709      ranges.push(`<=${max}`);
18710    else
18711      ranges.push(`${min} - ${max}`);
18712  }
18713  const simplified = ranges.join(' || ');
18714  const original = typeof range.raw === 'string' ? range.raw : String(range);
18715  return simplified.length < original.length ? simplified : range
18716};
18717
18718const Range = range$1;
18719const { ANY } = comparator$1;
18720const satisfies = satisfies_1;
18721const compare$1 = compare_1;
18722
18723// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
18724// - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
18725//
18726// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
18727// - If c is only the ANY comparator
18728//   - If C is only the ANY comparator, return true
18729//   - Else return false
18730// - Let EQ be the set of = comparators in c
18731// - If EQ is more than one, return true (null set)
18732// - Let GT be the highest > or >= comparator in c
18733// - Let LT be the lowest < or <= comparator in c
18734// - If GT and LT, and GT.semver > LT.semver, return true (null set)
18735// - If EQ
18736//   - If GT, and EQ does not satisfy GT, return true (null set)
18737//   - If LT, and EQ does not satisfy LT, return true (null set)
18738//   - If EQ satisfies every C, return true
18739//   - Else return false
18740// - If GT
18741//   - If GT.semver is lower than any > or >= comp in C, return false
18742//   - If GT is >=, and GT.semver does not satisfy every C, return false
18743// - If LT
18744//   - If LT.semver is greater than any < or <= comp in C, return false
18745//   - If LT is <=, and LT.semver does not satisfy every C, return false
18746// - If any C is a = range, and GT or LT are set, return false
18747// - Else return true
18748
18749const subset = (sub, dom, options) => {
18750  if (sub === dom)
18751    return true
18752
18753  sub = new Range(sub, options);
18754  dom = new Range(dom, options);
18755  let sawNonNull = false;
18756
18757  OUTER: for (const simpleSub of sub.set) {
18758    for (const simpleDom of dom.set) {
18759      const isSub = simpleSubset(simpleSub, simpleDom, options);
18760      sawNonNull = sawNonNull || isSub !== null;
18761      if (isSub)
18762        continue OUTER
18763    }
18764    // the null set is a subset of everything, but null simple ranges in
18765    // a complex range should be ignored.  so if we saw a non-null range,
18766    // then we know this isn't a subset, but if EVERY simple range was null,
18767    // then it is a subset.
18768    if (sawNonNull)
18769      return false
18770  }
18771  return true
18772};
18773
18774const simpleSubset = (sub, dom, options) => {
18775  if (sub === dom)
18776    return true
18777
18778  if (sub.length === 1 && sub[0].semver === ANY)
18779    return dom.length === 1 && dom[0].semver === ANY
18780
18781  const eqSet = new Set();
18782  let gt, lt;
18783  for (const c of sub) {
18784    if (c.operator === '>' || c.operator === '>=')
18785      gt = higherGT(gt, c, options);
18786    else if (c.operator === '<' || c.operator === '<=')
18787      lt = lowerLT(lt, c, options);
18788    else
18789      eqSet.add(c.semver);
18790  }
18791
18792  if (eqSet.size > 1)
18793    return null
18794
18795  let gtltComp;
18796  if (gt && lt) {
18797    gtltComp = compare$1(gt.semver, lt.semver, options);
18798    if (gtltComp > 0)
18799      return null
18800    else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
18801      return null
18802  }
18803
18804  // will iterate one or zero times
18805  for (const eq of eqSet) {
18806    if (gt && !satisfies(eq, String(gt), options))
18807      return null
18808
18809    if (lt && !satisfies(eq, String(lt), options))
18810      return null
18811
18812    for (const c of dom) {
18813      if (!satisfies(eq, String(c), options))
18814        return false
18815    }
18816
18817    return true
18818  }
18819
18820  let higher, lower;
18821  let hasDomLT, hasDomGT;
18822  for (const c of dom) {
18823    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
18824    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
18825    if (gt) {
18826      if (c.operator === '>' || c.operator === '>=') {
18827        higher = higherGT(gt, c, options);
18828        if (higher === c && higher !== gt)
18829          return false
18830      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
18831        return false
18832    }
18833    if (lt) {
18834      if (c.operator === '<' || c.operator === '<=') {
18835        lower = lowerLT(lt, c, options);
18836        if (lower === c && lower !== lt)
18837          return false
18838      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
18839        return false
18840    }
18841    if (!c.operator && (lt || gt) && gtltComp !== 0)
18842      return false
18843  }
18844
18845  // if there was a < or >, and nothing in the dom, then must be false
18846  // UNLESS it was limited by another range in the other direction.
18847  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
18848  if (gt && hasDomLT && !lt && gtltComp !== 0)
18849    return false
18850
18851  if (lt && hasDomGT && !gt && gtltComp !== 0)
18852    return false
18853
18854  return true
18855};
18856
18857// >=1.2.3 is lower than >1.2.3
18858const higherGT = (a, b, options) => {
18859  if (!a)
18860    return b
18861  const comp = compare$1(a.semver, b.semver, options);
18862  return comp > 0 ? a
18863    : comp < 0 ? b
18864    : b.operator === '>' && a.operator === '>=' ? b
18865    : a
18866};
18867
18868// <=1.2.3 is higher than <1.2.3
18869const lowerLT = (a, b, options) => {
18870  if (!a)
18871    return b
18872  const comp = compare$1(a.semver, b.semver, options);
18873  return comp < 0 ? a
18874    : comp > 0 ? b
18875    : b.operator === '<' && a.operator === '<=' ? b
18876    : a
18877};
18878
18879var subset_1 = subset;
18880
18881// just pre-load all the stuff that index.js lazily exports
18882const internalRe = re$6.exports;
18883var semver$1 = {
18884  re: internalRe.re,
18885  src: internalRe.src,
18886  tokens: internalRe.t,
18887  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
18888  SemVer: semver$2,
18889  compareIdentifiers: identifiers.compareIdentifiers,
18890  rcompareIdentifiers: identifiers.rcompareIdentifiers,
18891  parse: parse_1,
18892  valid: valid_1,
18893  clean: clean_1,
18894  inc: inc_1,
18895  diff: diff_1,
18896  major: major_1,
18897  minor: minor_1,
18898  patch: patch_1,
18899  prerelease: prerelease_1,
18900  compare: compare_1,
18901  rcompare: rcompare_1,
18902  compareLoose: compareLoose_1,
18903  compareBuild: compareBuild_1,
18904  sort: sort_1,
18905  rsort: rsort_1,
18906  gt: gt_1,
18907  lt: lt_1,
18908  eq: eq_1,
18909  neq: neq_1,
18910  gte: gte_1,
18911  lte: lte_1,
18912  cmp: cmp_1,
18913  coerce: coerce_1,
18914  Comparator: comparator$1,
18915  Range: range$1,
18916  satisfies: satisfies_1,
18917  toComparators: toComparators_1,
18918  maxSatisfying: maxSatisfying_1,
18919  minSatisfying: minSatisfying_1,
18920  minVersion: minVersion_1,
18921  validRange: valid,
18922  outside: outside_1,
18923  gtr: gtr_1,
18924  ltr: ltr_1,
18925  intersects: intersects_1,
18926  simplifyRange: simplify,
18927  subset: subset_1,
18928};
18929
18930var semver = semver$1;
18931
18932var builtins = function ({
18933  version = process.version,
18934  experimental = false
18935} = {}) {
18936  var coreModules = [
18937    'assert',
18938    'buffer',
18939    'child_process',
18940    'cluster',
18941    'console',
18942    'constants',
18943    'crypto',
18944    'dgram',
18945    'dns',
18946    'domain',
18947    'events',
18948    'fs',
18949    'http',
18950    'https',
18951    'module',
18952    'net',
18953    'os',
18954    'path',
18955    'punycode',
18956    'querystring',
18957    'readline',
18958    'repl',
18959    'stream',
18960    'string_decoder',
18961    'sys',
18962    'timers',
18963    'tls',
18964    'tty',
18965    'url',
18966    'util',
18967    'vm',
18968    'zlib'
18969  ];
18970
18971  if (semver.lt(version, '6.0.0')) coreModules.push('freelist');
18972  if (semver.gte(version, '1.0.0')) coreModules.push('v8');
18973  if (semver.gte(version, '1.1.0')) coreModules.push('process');
18974  if (semver.gte(version, '8.0.0')) coreModules.push('inspector');
18975  if (semver.gte(version, '8.1.0')) coreModules.push('async_hooks');
18976  if (semver.gte(version, '8.4.0')) coreModules.push('http2');
18977  if (semver.gte(version, '8.5.0')) coreModules.push('perf_hooks');
18978  if (semver.gte(version, '10.0.0')) coreModules.push('trace_events');
18979
18980  if (
18981    semver.gte(version, '10.5.0') &&
18982    (experimental || semver.gte(version, '12.0.0'))
18983  ) {
18984    coreModules.push('worker_threads');
18985  }
18986  if (semver.gte(version, '12.16.0') && experimental) {
18987    coreModules.push('wasi');
18988  }
18989
18990  return coreModules
18991};
18992
18993// Manually “tree shaken” from:
18994
18995const reader = {read: read$3};
18996var packageJsonReader = reader;
18997
18998/**
18999 * @param {string} jsonPath
19000 * @returns {{string: string}}
19001 */
19002function read$3(jsonPath) {
19003  return find$1(path$b.dirname(jsonPath))
19004}
19005
19006/**
19007 * @param {string} dir
19008 * @returns {{string: string}}
19009 */
19010function find$1(dir) {
19011  try {
19012    const string = require$$0$3.readFileSync(
19013      path$b.toNamespacedPath(path$b.join(dir, 'package.json')),
19014      'utf8'
19015    );
19016    return {string}
19017  } catch (error) {
19018    if (error.code === 'ENOENT') {
19019      const parent = path$b.dirname(dir);
19020      if (dir !== parent) return find$1(parent)
19021      return {string: undefined}
19022      // Throw all other errors.
19023      /* c8 ignore next 4 */
19024    }
19025
19026    throw error
19027  }
19028}
19029
19030// Manually “tree shaken” from:
19031
19032const isWindows$1 = process.platform === 'win32';
19033
19034const own$e = {}.hasOwnProperty;
19035
19036const codes = {};
19037
19038/**
19039 * @typedef {(...args: unknown[]) => string} MessageFunction
19040 */
19041
19042/** @type {Map<string, MessageFunction|string>} */
19043const messages = new Map();
19044const nodeInternalPrefix = '__node_internal_';
19045/** @type {number} */
19046let userStackTraceLimit;
19047
19048codes.ERR_INVALID_MODULE_SPECIFIER = createError(
19049  'ERR_INVALID_MODULE_SPECIFIER',
19050  /**
19051   * @param {string} request
19052   * @param {string} reason
19053   * @param {string} [base]
19054   */
19055  (request, reason, base = undefined) => {
19056    return `Invalid module "${request}" ${reason}${
19057      base ? ` imported from ${base}` : ''
19058    }`
19059  },
19060  TypeError
19061);
19062
19063codes.ERR_INVALID_PACKAGE_CONFIG = createError(
19064  'ERR_INVALID_PACKAGE_CONFIG',
19065  /**
19066   * @param {string} path
19067   * @param {string} [base]
19068   * @param {string} [message]
19069   */
19070  (path, base, message) => {
19071    return `Invalid package config ${path}${
19072      base ? ` while importing ${base}` : ''
19073    }${message ? `. ${message}` : ''}`
19074  },
19075  Error
19076);
19077
19078codes.ERR_INVALID_PACKAGE_TARGET = createError(
19079  'ERR_INVALID_PACKAGE_TARGET',
19080  /**
19081   * @param {string} pkgPath
19082   * @param {string} key
19083   * @param {unknown} target
19084   * @param {boolean} [isImport=false]
19085   * @param {string} [base]
19086   */
19087  (pkgPath, key, target, isImport = false, base = undefined) => {
19088    const relError =
19089      typeof target === 'string' &&
19090      !isImport &&
19091      target.length > 0 &&
19092      !target.startsWith('./');
19093    if (key === '.') {
19094      assert$2(isImport === false);
19095      return (
19096        `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
19097        `in the package config ${pkgPath}package.json${
19098          base ? ` imported from ${base}` : ''
19099        }${relError ? '; targets must start with "./"' : ''}`
19100      )
19101    }
19102
19103    return `Invalid "${
19104      isImport ? 'imports' : 'exports'
19105    }" target ${JSON.stringify(
19106      target
19107    )} defined for '${key}' in the package config ${pkgPath}package.json${
19108      base ? ` imported from ${base}` : ''
19109    }${relError ? '; targets must start with "./"' : ''}`
19110  },
19111  Error
19112);
19113
19114codes.ERR_MODULE_NOT_FOUND = createError(
19115  'ERR_MODULE_NOT_FOUND',
19116  /**
19117   * @param {string} path
19118   * @param {string} base
19119   * @param {string} [type]
19120   */
19121  (path, base, type = 'package') => {
19122    return `Cannot find ${type} '${path}' imported from ${base}`
19123  },
19124  Error
19125);
19126
19127codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
19128  'ERR_PACKAGE_IMPORT_NOT_DEFINED',
19129  /**
19130   * @param {string} specifier
19131   * @param {string} packagePath
19132   * @param {string} base
19133   */
19134  (specifier, packagePath, base) => {
19135    return `Package import specifier "${specifier}" is not defined${
19136      packagePath ? ` in package ${packagePath}package.json` : ''
19137    } imported from ${base}`
19138  },
19139  TypeError
19140);
19141
19142codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
19143  'ERR_PACKAGE_PATH_NOT_EXPORTED',
19144  /**
19145   * @param {string} pkgPath
19146   * @param {string} subpath
19147   * @param {string} [base]
19148   */
19149  (pkgPath, subpath, base = undefined) => {
19150    if (subpath === '.')
19151      return `No "exports" main defined in ${pkgPath}package.json${
19152        base ? ` imported from ${base}` : ''
19153      }`
19154    return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
19155      base ? ` imported from ${base}` : ''
19156    }`
19157  },
19158  Error
19159);
19160
19161codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
19162  'ERR_UNSUPPORTED_DIR_IMPORT',
19163  "Directory import '%s' is not supported " +
19164    'resolving ES modules imported from %s',
19165  Error
19166);
19167
19168codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
19169  'ERR_UNKNOWN_FILE_EXTENSION',
19170  'Unknown file extension "%s" for %s',
19171  TypeError
19172);
19173
19174codes.ERR_INVALID_ARG_VALUE = createError(
19175  'ERR_INVALID_ARG_VALUE',
19176  /**
19177   * @param {string} name
19178   * @param {unknown} value
19179   * @param {string} [reason='is invalid']
19180   */
19181  (name, value, reason = 'is invalid') => {
19182    let inspected = inspect$1(value);
19183
19184    if (inspected.length > 128) {
19185      inspected = `${inspected.slice(0, 128)}...`;
19186    }
19187
19188    const type = name.includes('.') ? 'property' : 'argument';
19189
19190    return `The ${type} '${name}' ${reason}. Received ${inspected}`
19191  },
19192  TypeError
19193  // Note: extra classes have been shaken out.
19194  // , RangeError
19195);
19196
19197codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError(
19198  'ERR_UNSUPPORTED_ESM_URL_SCHEME',
19199  /**
19200   * @param {URL} url
19201   */
19202  (url) => {
19203    let message =
19204      'Only file and data URLs are supported by the default ESM loader';
19205
19206    if (isWindows$1 && url.protocol.length === 2) {
19207      message += '. On Windows, absolute paths must be valid file:// URLs';
19208    }
19209
19210    message += `. Received protocol '${url.protocol}'`;
19211    return message
19212  },
19213  Error
19214);
19215
19216/**
19217 * Utility function for registering the error codes. Only used here. Exported
19218 * *only* to allow for testing.
19219 * @param {string} sym
19220 * @param {MessageFunction|string} value
19221 * @param {ErrorConstructor} def
19222 * @returns {new (...args: unknown[]) => Error}
19223 */
19224function createError(sym, value, def) {
19225  // Special case for SystemError that formats the error message differently
19226  // The SystemErrors only have SystemError as their base classes.
19227  messages.set(sym, value);
19228
19229  return makeNodeErrorWithCode(def, sym)
19230}
19231
19232/**
19233 * @param {ErrorConstructor} Base
19234 * @param {string} key
19235 * @returns {ErrorConstructor}
19236 */
19237function makeNodeErrorWithCode(Base, key) {
19238  // @ts-expect-error It’s a Node error.
19239  return NodeError
19240  /**
19241   * @param {unknown[]} args
19242   */
19243  function NodeError(...args) {
19244    const limit = Error.stackTraceLimit;
19245    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
19246    const error = new Base();
19247    // Reset the limit and setting the name property.
19248    if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
19249    const message = getMessage(key, args, error);
19250    Object.defineProperty(error, 'message', {
19251      value: message,
19252      enumerable: false,
19253      writable: true,
19254      configurable: true
19255    });
19256    Object.defineProperty(error, 'toString', {
19257      /** @this {Error} */
19258      value() {
19259        return `${this.name} [${key}]: ${this.message}`
19260      },
19261      enumerable: false,
19262      writable: true,
19263      configurable: true
19264    });
19265    addCodeToName(error, Base.name, key);
19266    // @ts-expect-error It’s a Node error.
19267    error.code = key;
19268    return error
19269  }
19270}
19271
19272const addCodeToName = hideStackFrames(
19273  /**
19274   * @param {Error} error
19275   * @param {string} name
19276   * @param {string} code
19277   * @returns {void}
19278   */
19279  function (error, name, code) {
19280    // Set the stack
19281    error = captureLargerStackTrace(error);
19282    // Add the error code to the name to include it in the stack trace.
19283    error.name = `${name} [${code}]`;
19284    // Access the stack to generate the error message including the error code
19285    // from the name.
19286    error.stack; // eslint-disable-line no-unused-expressions
19287    // Reset the name to the actual name.
19288    if (name === 'SystemError') {
19289      Object.defineProperty(error, 'name', {
19290        value: name,
19291        enumerable: false,
19292        writable: true,
19293        configurable: true
19294      });
19295    } else {
19296      delete error.name;
19297    }
19298  }
19299);
19300
19301/**
19302 * @returns {boolean}
19303 */
19304function isErrorStackTraceLimitWritable() {
19305  const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
19306  if (desc === undefined) {
19307    return Object.isExtensible(Error)
19308  }
19309
19310  return own$e.call(desc, 'writable') ? desc.writable : desc.set !== undefined
19311}
19312
19313/**
19314 * This function removes unnecessary frames from Node.js core errors.
19315 * @template {(...args: unknown[]) => unknown} T
19316 * @type {(fn: T) => T}
19317 */
19318function hideStackFrames(fn) {
19319  // We rename the functions that will be hidden to cut off the stacktrace
19320  // at the outermost one
19321  const hidden = nodeInternalPrefix + fn.name;
19322  Object.defineProperty(fn, 'name', {value: hidden});
19323  return fn
19324}
19325
19326const captureLargerStackTrace = hideStackFrames(
19327  /**
19328   * @param {Error} error
19329   * @returns {Error}
19330   */
19331  function (error) {
19332    const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
19333    if (stackTraceLimitIsWritable) {
19334      userStackTraceLimit = Error.stackTraceLimit;
19335      Error.stackTraceLimit = Number.POSITIVE_INFINITY;
19336    }
19337
19338    Error.captureStackTrace(error);
19339
19340    // Reset the limit
19341    if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
19342
19343    return error
19344  }
19345);
19346
19347/**
19348 * @param {string} key
19349 * @param {unknown[]} args
19350 * @param {Error} self
19351 * @returns {string}
19352 */
19353function getMessage(key, args, self) {
19354  const message = messages.get(key);
19355
19356  if (typeof message === 'function') {
19357    assert$2(
19358      message.length <= args.length, // Default options do not count.
19359      `Code: ${key}; The provided arguments length (${args.length}) does not ` +
19360        `match the required ones (${message.length}).`
19361    );
19362    return Reflect.apply(message, self, args)
19363  }
19364
19365  const expectedLength = (message.match(/%[dfijoOs]/g) || []).length;
19366  assert$2(
19367    expectedLength === args.length,
19368    `Code: ${key}; The provided arguments length (${args.length}) does not ` +
19369      `match the required ones (${expectedLength}).`
19370  );
19371  if (args.length === 0) return message
19372
19373  args.unshift(message);
19374  return Reflect.apply(format$2, null, args)
19375}
19376
19377// Manually “tree shaken” from:
19378
19379const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
19380
19381const extensionFormatMap = {
19382  __proto__: null,
19383  '.cjs': 'commonjs',
19384  '.js': 'module',
19385  '.mjs': 'module'
19386};
19387
19388/**
19389 * @param {string} url
19390 * @returns {{format: string|null}}
19391 */
19392function defaultGetFormat(url) {
19393  if (url.startsWith('node:')) {
19394    return {format: 'builtin'}
19395  }
19396
19397  const parsed = new URL$1(url);
19398
19399  if (parsed.protocol === 'data:') {
19400    const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
19401      parsed.pathname
19402    ) || [null, null];
19403    const format = mime === 'text/javascript' ? 'module' : null;
19404    return {format}
19405  }
19406
19407  if (parsed.protocol === 'file:') {
19408    const ext = path$b.extname(parsed.pathname);
19409    /** @type {string} */
19410    let format;
19411    if (ext === '.js') {
19412      format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
19413    } else {
19414      format = extensionFormatMap[ext];
19415    }
19416
19417    if (!format) {
19418      throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url))
19419    }
19420
19421    return {format: format || null}
19422  }
19423
19424  return {format: null}
19425}
19426
19427// Manually “tree shaken” from:
19428
19429const listOfBuiltins = builtins();
19430
19431const {
19432  ERR_INVALID_MODULE_SPECIFIER,
19433  ERR_INVALID_PACKAGE_CONFIG,
19434  ERR_INVALID_PACKAGE_TARGET,
19435  ERR_MODULE_NOT_FOUND,
19436  ERR_PACKAGE_IMPORT_NOT_DEFINED,
19437  ERR_PACKAGE_PATH_NOT_EXPORTED,
19438  ERR_UNSUPPORTED_DIR_IMPORT,
19439  ERR_UNSUPPORTED_ESM_URL_SCHEME,
19440  ERR_INVALID_ARG_VALUE
19441} = codes;
19442
19443const own$d = {}.hasOwnProperty;
19444
19445const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);
19446const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
19447
19448const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
19449const patternRegEx = /\*/g;
19450const encodedSepRegEx = /%2f|%2c/i;
19451/** @type {Set<string>} */
19452const emittedPackageWarnings = new Set();
19453/** @type {Map<string, PackageConfig>} */
19454const packageJsonCache = new Map();
19455
19456/**
19457 * @param {string} match
19458 * @param {URL} pjsonUrl
19459 * @param {boolean} isExports
19460 * @param {URL} base
19461 * @returns {void}
19462 */
19463function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
19464  const pjsonPath = fileURLToPath(pjsonUrl);
19465
19466  if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
19467  emittedPackageWarnings.add(pjsonPath + '|' + match);
19468  process.emitWarning(
19469    `Use of deprecated folder mapping "${match}" in the ${
19470      isExports ? '"exports"' : '"imports"'
19471    } field module resolution of the package at ${pjsonPath}${
19472      base ? ` imported from ${fileURLToPath(base)}` : ''
19473    }.\n` +
19474      `Update this package.json to use a subpath pattern like "${match}*".`,
19475    'DeprecationWarning',
19476    'DEP0148'
19477  );
19478}
19479
19480/**
19481 * @param {URL} url
19482 * @param {URL} packageJsonUrl
19483 * @param {URL} base
19484 * @param {unknown} [main]
19485 * @returns {void}
19486 */
19487function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
19488  const {format} = defaultGetFormat(url.href);
19489  if (format !== 'module') return
19490  const path = fileURLToPath(url.href);
19491  const pkgPath = fileURLToPath(new URL$1('.', packageJsonUrl));
19492  const basePath = fileURLToPath(base);
19493  if (main)
19494    process.emitWarning(
19495      `Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` +
19496        `excluding the full filename and extension to the resolved file at "${path.slice(
19497          pkgPath.length
19498        )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` +
19499        'deprecated for ES modules.',
19500      'DeprecationWarning',
19501      'DEP0151'
19502    );
19503  else
19504    process.emitWarning(
19505      `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(
19506        pkgPath.length
19507      )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
19508      'DeprecationWarning',
19509      'DEP0151'
19510    );
19511}
19512
19513/**
19514 * @param {string[]} [conditions]
19515 * @returns {Set<string>}
19516 */
19517function getConditionsSet(conditions) {
19518  if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) {
19519    if (!Array.isArray(conditions)) {
19520      throw new ERR_INVALID_ARG_VALUE(
19521        'conditions',
19522        conditions,
19523        'expected an array'
19524      )
19525    }
19526
19527    return new Set(conditions)
19528  }
19529
19530  return DEFAULT_CONDITIONS_SET
19531}
19532
19533/**
19534 * @param {string} path
19535 * @returns {Stats}
19536 */
19537function tryStatSync(path) {
19538  // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
19539  try {
19540    return statSync(path)
19541  } catch {
19542    return new Stats()
19543  }
19544}
19545
19546/**
19547 * @param {string} path
19548 * @param {string|URL} specifier Note: `specifier` is actually optional, not base.
19549 * @param {URL} [base]
19550 * @returns {PackageConfig}
19551 */
19552function getPackageConfig(path, specifier, base) {
19553  const existing = packageJsonCache.get(path);
19554  if (existing !== undefined) {
19555    return existing
19556  }
19557
19558  const source = packageJsonReader.read(path).string;
19559
19560  if (source === undefined) {
19561    /** @type {PackageConfig} */
19562    const packageConfig = {
19563      pjsonPath: path,
19564      exists: false,
19565      main: undefined,
19566      name: undefined,
19567      type: 'none',
19568      exports: undefined,
19569      imports: undefined
19570    };
19571    packageJsonCache.set(path, packageConfig);
19572    return packageConfig
19573  }
19574
19575  /** @type {Object.<string, unknown>} */
19576  let packageJson;
19577  try {
19578    packageJson = JSON.parse(source);
19579  } catch (error) {
19580    throw new ERR_INVALID_PACKAGE_CONFIG(
19581      path,
19582      (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
19583      error.message
19584    )
19585  }
19586
19587  const {exports, imports, main, name, type} = packageJson;
19588
19589  /** @type {PackageConfig} */
19590  const packageConfig = {
19591    pjsonPath: path,
19592    exists: true,
19593    main: typeof main === 'string' ? main : undefined,
19594    name: typeof name === 'string' ? name : undefined,
19595    type: type === 'module' || type === 'commonjs' ? type : 'none',
19596    // @ts-expect-error Assume `Object.<string, unknown>`.
19597    exports,
19598    // @ts-expect-error Assume `Object.<string, unknown>`.
19599    imports: imports && typeof imports === 'object' ? imports : undefined
19600  };
19601  packageJsonCache.set(path, packageConfig);
19602  return packageConfig
19603}
19604
19605/**
19606 * @param {URL|string} resolved
19607 * @returns {PackageConfig}
19608 */
19609function getPackageScopeConfig(resolved) {
19610  let packageJsonUrl = new URL$1('./package.json', resolved);
19611
19612  while (true) {
19613    const packageJsonPath = packageJsonUrl.pathname;
19614
19615    if (packageJsonPath.endsWith('node_modules/package.json')) break
19616
19617    const packageConfig = getPackageConfig(
19618      fileURLToPath(packageJsonUrl),
19619      resolved
19620    );
19621    if (packageConfig.exists) return packageConfig
19622
19623    const lastPackageJsonUrl = packageJsonUrl;
19624    packageJsonUrl = new URL$1('../package.json', packageJsonUrl);
19625
19626    // Terminates at root where ../package.json equals ../../package.json
19627    // (can't just check "/package.json" for Windows support).
19628    if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break
19629  }
19630
19631  const packageJsonPath = fileURLToPath(packageJsonUrl);
19632  /** @type {PackageConfig} */
19633  const packageConfig = {
19634    pjsonPath: packageJsonPath,
19635    exists: false,
19636    main: undefined,
19637    name: undefined,
19638    type: 'none',
19639    exports: undefined,
19640    imports: undefined
19641  };
19642  packageJsonCache.set(packageJsonPath, packageConfig);
19643  return packageConfig
19644}
19645
19646/**
19647 * Legacy CommonJS main resolution:
19648 * 1. let M = pkg_url + (json main field)
19649 * 2. TRY(M, M.js, M.json, M.node)
19650 * 3. TRY(M/index.js, M/index.json, M/index.node)
19651 * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
19652 * 5. NOT_FOUND
19653 *
19654 * @param {URL} url
19655 * @returns {boolean}
19656 */
19657function fileExists(url) {
19658  return tryStatSync(fileURLToPath(url)).isFile()
19659}
19660
19661/**
19662 * @param {URL} packageJsonUrl
19663 * @param {PackageConfig} packageConfig
19664 * @param {URL} base
19665 * @returns {URL}
19666 */
19667function legacyMainResolve(packageJsonUrl, packageConfig, base) {
19668  /** @type {URL} */
19669  let guess;
19670  if (packageConfig.main !== undefined) {
19671    guess = new URL$1(`./${packageConfig.main}`, packageJsonUrl);
19672    // Note: fs check redundances will be handled by Descriptor cache here.
19673    if (fileExists(guess)) return guess
19674
19675    const tries = [
19676      `./${packageConfig.main}.js`,
19677      `./${packageConfig.main}.json`,
19678      `./${packageConfig.main}.node`,
19679      `./${packageConfig.main}/index.js`,
19680      `./${packageConfig.main}/index.json`,
19681      `./${packageConfig.main}/index.node`
19682    ];
19683    let i = -1;
19684
19685    while (++i < tries.length) {
19686      guess = new URL$1(tries[i], packageJsonUrl);
19687      if (fileExists(guess)) break
19688      guess = undefined;
19689    }
19690
19691    if (guess) {
19692      emitLegacyIndexDeprecation(
19693        guess,
19694        packageJsonUrl,
19695        base,
19696        packageConfig.main
19697      );
19698      return guess
19699    }
19700    // Fallthrough.
19701  }
19702
19703  const tries = ['./index.js', './index.json', './index.node'];
19704  let i = -1;
19705
19706  while (++i < tries.length) {
19707    guess = new URL$1(tries[i], packageJsonUrl);
19708    if (fileExists(guess)) break
19709    guess = undefined;
19710  }
19711
19712  if (guess) {
19713    emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
19714    return guess
19715  }
19716
19717  // Not found.
19718  throw new ERR_MODULE_NOT_FOUND(
19719    fileURLToPath(new URL$1('.', packageJsonUrl)),
19720    fileURLToPath(base)
19721  )
19722}
19723
19724/**
19725 * @param {URL} resolved
19726 * @param {URL} base
19727 * @returns {URL}
19728 */
19729function finalizeResolution(resolved, base) {
19730  if (encodedSepRegEx.test(resolved.pathname))
19731    throw new ERR_INVALID_MODULE_SPECIFIER(
19732      resolved.pathname,
19733      'must not include encoded "/" or "\\" characters',
19734      fileURLToPath(base)
19735    )
19736
19737  const path = fileURLToPath(resolved);
19738
19739  const stats = tryStatSync(path.endsWith('/') ? path.slice(-1) : path);
19740
19741  if (stats.isDirectory()) {
19742    const error = new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base));
19743    // @ts-expect-error Add this for `import.meta.resolve`.
19744    error.url = String(resolved);
19745    throw error
19746  }
19747
19748  if (!stats.isFile()) {
19749    throw new ERR_MODULE_NOT_FOUND(
19750      path || resolved.pathname,
19751      base && fileURLToPath(base),
19752      'module'
19753    )
19754  }
19755
19756  return resolved
19757}
19758
19759/**
19760 * @param {string} specifier
19761 * @param {URL?} packageJsonUrl
19762 * @param {URL} base
19763 * @returns {never}
19764 */
19765function throwImportNotDefined(specifier, packageJsonUrl, base) {
19766  throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(
19767    specifier,
19768    packageJsonUrl && fileURLToPath(new URL$1('.', packageJsonUrl)),
19769    fileURLToPath(base)
19770  )
19771}
19772
19773/**
19774 * @param {string} subpath
19775 * @param {URL} packageJsonUrl
19776 * @param {URL} base
19777 * @returns {never}
19778 */
19779function throwExportsNotFound(subpath, packageJsonUrl, base) {
19780  throw new ERR_PACKAGE_PATH_NOT_EXPORTED(
19781    fileURLToPath(new URL$1('.', packageJsonUrl)),
19782    subpath,
19783    base && fileURLToPath(base)
19784  )
19785}
19786
19787/**
19788 * @param {string} subpath
19789 * @param {URL} packageJsonUrl
19790 * @param {boolean} internal
19791 * @param {URL} [base]
19792 * @returns {never}
19793 */
19794function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) {
19795  const reason = `request is not a valid subpath for the "${
19796    internal ? 'imports' : 'exports'
19797  }" resolution of ${fileURLToPath(packageJsonUrl)}`;
19798
19799  throw new ERR_INVALID_MODULE_SPECIFIER(
19800    subpath,
19801    reason,
19802    base && fileURLToPath(base)
19803  )
19804}
19805
19806/**
19807 * @param {string} subpath
19808 * @param {unknown} target
19809 * @param {URL} packageJsonUrl
19810 * @param {boolean} internal
19811 * @param {URL} [base]
19812 * @returns {never}
19813 */
19814function throwInvalidPackageTarget(
19815  subpath,
19816  target,
19817  packageJsonUrl,
19818  internal,
19819  base
19820) {
19821  target =
19822    typeof target === 'object' && target !== null
19823      ? JSON.stringify(target, null, '')
19824      : `${target}`;
19825
19826  throw new ERR_INVALID_PACKAGE_TARGET(
19827    fileURLToPath(new URL$1('.', packageJsonUrl)),
19828    subpath,
19829    target,
19830    internal,
19831    base && fileURLToPath(base)
19832  )
19833}
19834
19835/**
19836 * @param {string} target
19837 * @param {string} subpath
19838 * @param {string} match
19839 * @param {URL} packageJsonUrl
19840 * @param {URL} base
19841 * @param {boolean} pattern
19842 * @param {boolean} internal
19843 * @param {Set<string>} conditions
19844 * @returns {URL}
19845 */
19846function resolvePackageTargetString(
19847  target,
19848  subpath,
19849  match,
19850  packageJsonUrl,
19851  base,
19852  pattern,
19853  internal,
19854  conditions
19855) {
19856  if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
19857    throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
19858
19859  if (!target.startsWith('./')) {
19860    if (internal && !target.startsWith('../') && !target.startsWith('/')) {
19861      let isURL = false;
19862
19863      try {
19864        new URL$1(target);
19865        isURL = true;
19866      } catch {}
19867
19868      if (!isURL) {
19869        const exportTarget = pattern
19870          ? target.replace(patternRegEx, subpath)
19871          : target + subpath;
19872
19873        return packageResolve(exportTarget, packageJsonUrl, conditions)
19874      }
19875    }
19876
19877    throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
19878  }
19879
19880  if (invalidSegmentRegEx.test(target.slice(2)))
19881    throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
19882
19883  const resolved = new URL$1(target, packageJsonUrl);
19884  const resolvedPath = resolved.pathname;
19885  const packagePath = new URL$1('.', packageJsonUrl).pathname;
19886
19887  if (!resolvedPath.startsWith(packagePath))
19888    throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
19889
19890  if (subpath === '') return resolved
19891
19892  if (invalidSegmentRegEx.test(subpath))
19893    throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base);
19894
19895  if (pattern) return new URL$1(resolved.href.replace(patternRegEx, subpath))
19896  return new URL$1(subpath, resolved)
19897}
19898
19899/**
19900 * @param {string} key
19901 * @returns {boolean}
19902 */
19903function isArrayIndex(key) {
19904  const keyNumber = Number(key);
19905  if (`${keyNumber}` !== key) return false
19906  return keyNumber >= 0 && keyNumber < 0xffff_ffff
19907}
19908
19909/**
19910 * @param {URL} packageJsonUrl
19911 * @param {unknown} target
19912 * @param {string} subpath
19913 * @param {string} packageSubpath
19914 * @param {URL} base
19915 * @param {boolean} pattern
19916 * @param {boolean} internal
19917 * @param {Set<string>} conditions
19918 * @returns {URL}
19919 */
19920function resolvePackageTarget(
19921  packageJsonUrl,
19922  target,
19923  subpath,
19924  packageSubpath,
19925  base,
19926  pattern,
19927  internal,
19928  conditions
19929) {
19930  if (typeof target === 'string') {
19931    return resolvePackageTargetString(
19932      target,
19933      subpath,
19934      packageSubpath,
19935      packageJsonUrl,
19936      base,
19937      pattern,
19938      internal,
19939      conditions
19940    )
19941  }
19942
19943  if (Array.isArray(target)) {
19944    /** @type {unknown[]} */
19945    const targetList = target;
19946    if (targetList.length === 0) return null
19947
19948    /** @type {Error} */
19949    let lastException;
19950    let i = -1;
19951
19952    while (++i < targetList.length) {
19953      const targetItem = targetList[i];
19954      /** @type {URL} */
19955      let resolved;
19956      try {
19957        resolved = resolvePackageTarget(
19958          packageJsonUrl,
19959          targetItem,
19960          subpath,
19961          packageSubpath,
19962          base,
19963          pattern,
19964          internal,
19965          conditions
19966        );
19967      } catch (error) {
19968        lastException = error;
19969        if (error.code === 'ERR_INVALID_PACKAGE_TARGET') continue
19970        throw error
19971      }
19972
19973      if (resolved === undefined) continue
19974
19975      if (resolved === null) {
19976        lastException = null;
19977        continue
19978      }
19979
19980      return resolved
19981    }
19982
19983    if (lastException === undefined || lastException === null) {
19984      // @ts-expect-error The diff between `undefined` and `null` seems to be
19985      // intentional
19986      return lastException
19987    }
19988
19989    throw lastException
19990  }
19991
19992  if (typeof target === 'object' && target !== null) {
19993    const keys = Object.getOwnPropertyNames(target);
19994    let i = -1;
19995
19996    while (++i < keys.length) {
19997      const key = keys[i];
19998      if (isArrayIndex(key)) {
19999        throw new ERR_INVALID_PACKAGE_CONFIG(
20000          fileURLToPath(packageJsonUrl),
20001          base,
20002          '"exports" cannot contain numeric property keys.'
20003        )
20004      }
20005    }
20006
20007    i = -1;
20008
20009    while (++i < keys.length) {
20010      const key = keys[i];
20011      if (key === 'default' || (conditions && conditions.has(key))) {
20012        /** @type {unknown} */
20013        const conditionalTarget = target[key];
20014        const resolved = resolvePackageTarget(
20015          packageJsonUrl,
20016          conditionalTarget,
20017          subpath,
20018          packageSubpath,
20019          base,
20020          pattern,
20021          internal,
20022          conditions
20023        );
20024        if (resolved === undefined) continue
20025        return resolved
20026      }
20027    }
20028
20029    return undefined
20030  }
20031
20032  if (target === null) {
20033    return null
20034  }
20035
20036  throwInvalidPackageTarget(
20037    packageSubpath,
20038    target,
20039    packageJsonUrl,
20040    internal,
20041    base
20042  );
20043}
20044
20045/**
20046 * @param {unknown} exports
20047 * @param {URL} packageJsonUrl
20048 * @param {URL} base
20049 * @returns {boolean}
20050 */
20051function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
20052  if (typeof exports === 'string' || Array.isArray(exports)) return true
20053  if (typeof exports !== 'object' || exports === null) return false
20054
20055  const keys = Object.getOwnPropertyNames(exports);
20056  let isConditionalSugar = false;
20057  let i = 0;
20058  let j = -1;
20059  while (++j < keys.length) {
20060    const key = keys[j];
20061    const curIsConditionalSugar = key === '' || key[0] !== '.';
20062    if (i++ === 0) {
20063      isConditionalSugar = curIsConditionalSugar;
20064    } else if (isConditionalSugar !== curIsConditionalSugar) {
20065      throw new ERR_INVALID_PACKAGE_CONFIG(
20066        fileURLToPath(packageJsonUrl),
20067        base,
20068        '"exports" cannot contain some keys starting with \'.\' and some not.' +
20069          ' The exports object must either be an object of package subpath keys' +
20070          ' or an object of main entry condition name keys only.'
20071      )
20072    }
20073  }
20074
20075  return isConditionalSugar
20076}
20077
20078/**
20079 * @param {URL} packageJsonUrl
20080 * @param {string} packageSubpath
20081 * @param {Object.<string, unknown>} packageConfig
20082 * @param {URL} base
20083 * @param {Set<string>} conditions
20084 * @returns {ResolveObject}
20085 */
20086function packageExportsResolve(
20087  packageJsonUrl,
20088  packageSubpath,
20089  packageConfig,
20090  base,
20091  conditions
20092) {
20093  let exports = packageConfig.exports;
20094  if (isConditionalExportsMainSugar(exports, packageJsonUrl, base))
20095    exports = {'.': exports};
20096
20097  if (own$d.call(exports, packageSubpath)) {
20098    const target = exports[packageSubpath];
20099    const resolved = resolvePackageTarget(
20100      packageJsonUrl,
20101      target,
20102      '',
20103      packageSubpath,
20104      base,
20105      false,
20106      false,
20107      conditions
20108    );
20109    if (resolved === null || resolved === undefined)
20110      throwExportsNotFound(packageSubpath, packageJsonUrl, base);
20111    return {resolved, exact: true}
20112  }
20113
20114  let bestMatch = '';
20115  const keys = Object.getOwnPropertyNames(exports);
20116  let i = -1;
20117
20118  while (++i < keys.length) {
20119    const key = keys[i];
20120    if (
20121      key[key.length - 1] === '*' &&
20122      packageSubpath.startsWith(key.slice(0, -1)) &&
20123      packageSubpath.length >= key.length &&
20124      key.length > bestMatch.length
20125    ) {
20126      bestMatch = key;
20127    } else if (
20128      key[key.length - 1] === '/' &&
20129      packageSubpath.startsWith(key) &&
20130      key.length > bestMatch.length
20131    ) {
20132      bestMatch = key;
20133    }
20134  }
20135
20136  if (bestMatch) {
20137    const target = exports[bestMatch];
20138    const pattern = bestMatch[bestMatch.length - 1] === '*';
20139    const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0));
20140    const resolved = resolvePackageTarget(
20141      packageJsonUrl,
20142      target,
20143      subpath,
20144      bestMatch,
20145      base,
20146      pattern,
20147      false,
20148      conditions
20149    );
20150    if (resolved === null || resolved === undefined)
20151      throwExportsNotFound(packageSubpath, packageJsonUrl, base);
20152    if (!pattern)
20153      emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base);
20154    return {resolved, exact: pattern}
20155  }
20156
20157  throwExportsNotFound(packageSubpath, packageJsonUrl, base);
20158}
20159
20160/**
20161 * @param {string} name
20162 * @param {URL} base
20163 * @param {Set<string>} [conditions]
20164 * @returns {ResolveObject}
20165 */
20166function packageImportsResolve(name, base, conditions) {
20167  if (name === '#' || name.startsWith('#/')) {
20168    const reason = 'is not a valid internal imports specifier name';
20169    throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base))
20170  }
20171
20172  /** @type {URL} */
20173  let packageJsonUrl;
20174
20175  const packageConfig = getPackageScopeConfig(base);
20176
20177  if (packageConfig.exists) {
20178    packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
20179    const imports = packageConfig.imports;
20180    if (imports) {
20181      if (own$d.call(imports, name)) {
20182        const resolved = resolvePackageTarget(
20183          packageJsonUrl,
20184          imports[name],
20185          '',
20186          name,
20187          base,
20188          false,
20189          true,
20190          conditions
20191        );
20192        if (resolved !== null) return {resolved, exact: true}
20193      } else {
20194        let bestMatch = '';
20195        const keys = Object.getOwnPropertyNames(imports);
20196        let i = -1;
20197
20198        while (++i < keys.length) {
20199          const key = keys[i];
20200
20201          if (
20202            key[key.length - 1] === '*' &&
20203            name.startsWith(key.slice(0, -1)) &&
20204            name.length >= key.length &&
20205            key.length > bestMatch.length
20206          ) {
20207            bestMatch = key;
20208          } else if (
20209            key[key.length - 1] === '/' &&
20210            name.startsWith(key) &&
20211            key.length > bestMatch.length
20212          ) {
20213            bestMatch = key;
20214          }
20215        }
20216
20217        if (bestMatch) {
20218          const target = imports[bestMatch];
20219          const pattern = bestMatch[bestMatch.length - 1] === '*';
20220          const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0));
20221          const resolved = resolvePackageTarget(
20222            packageJsonUrl,
20223            target,
20224            subpath,
20225            bestMatch,
20226            base,
20227            pattern,
20228            true,
20229            conditions
20230          );
20231          if (resolved !== null) {
20232            if (!pattern)
20233              emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base);
20234            return {resolved, exact: pattern}
20235          }
20236        }
20237      }
20238    }
20239  }
20240
20241  throwImportNotDefined(name, packageJsonUrl, base);
20242}
20243
20244/**
20245 * @param {string} url
20246 * @returns {PackageType}
20247 */
20248function getPackageType(url) {
20249  const packageConfig = getPackageScopeConfig(url);
20250  return packageConfig.type
20251}
20252
20253/**
20254 * @param {string} specifier
20255 * @param {URL} base
20256 */
20257function parsePackageName(specifier, base) {
20258  let separatorIndex = specifier.indexOf('/');
20259  let validPackageName = true;
20260  let isScoped = false;
20261  if (specifier[0] === '@') {
20262    isScoped = true;
20263    if (separatorIndex === -1 || specifier.length === 0) {
20264      validPackageName = false;
20265    } else {
20266      separatorIndex = specifier.indexOf('/', separatorIndex + 1);
20267    }
20268  }
20269
20270  const packageName =
20271    separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
20272
20273  // Package name cannot have leading . and cannot have percent-encoding or
20274  // separators.
20275  let i = -1;
20276  while (++i < packageName.length) {
20277    if (packageName[i] === '%' || packageName[i] === '\\') {
20278      validPackageName = false;
20279      break
20280    }
20281  }
20282
20283  if (!validPackageName) {
20284    throw new ERR_INVALID_MODULE_SPECIFIER(
20285      specifier,
20286      'is not a valid package name',
20287      fileURLToPath(base)
20288    )
20289  }
20290
20291  const packageSubpath =
20292    '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
20293
20294  return {packageName, packageSubpath, isScoped}
20295}
20296
20297/**
20298 * @param {string} specifier
20299 * @param {URL} base
20300 * @param {Set<string>} conditions
20301 * @returns {URL}
20302 */
20303function packageResolve(specifier, base, conditions) {
20304  const {packageName, packageSubpath, isScoped} = parsePackageName(
20305    specifier,
20306    base
20307  );
20308
20309  // ResolveSelf
20310  const packageConfig = getPackageScopeConfig(base);
20311
20312  // Can’t test.
20313  /* c8 ignore next 16 */
20314  if (packageConfig.exists) {
20315    const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
20316    if (
20317      packageConfig.name === packageName &&
20318      packageConfig.exports !== undefined &&
20319      packageConfig.exports !== null
20320    ) {
20321      return packageExportsResolve(
20322        packageJsonUrl,
20323        packageSubpath,
20324        packageConfig,
20325        base,
20326        conditions
20327      ).resolved
20328    }
20329  }
20330
20331  let packageJsonUrl = new URL$1(
20332    './node_modules/' + packageName + '/package.json',
20333    base
20334  );
20335  let packageJsonPath = fileURLToPath(packageJsonUrl);
20336  /** @type {string} */
20337  let lastPath;
20338  do {
20339    const stat = tryStatSync(packageJsonPath.slice(0, -13));
20340    if (!stat.isDirectory()) {
20341      lastPath = packageJsonPath;
20342      packageJsonUrl = new URL$1(
20343        (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
20344          packageName +
20345          '/package.json',
20346        packageJsonUrl
20347      );
20348      packageJsonPath = fileURLToPath(packageJsonUrl);
20349      continue
20350    }
20351
20352    // Package match.
20353    const packageConfig = getPackageConfig(packageJsonPath, specifier, base);
20354    if (packageConfig.exports !== undefined && packageConfig.exports !== null)
20355      return packageExportsResolve(
20356        packageJsonUrl,
20357        packageSubpath,
20358        packageConfig,
20359        base,
20360        conditions
20361      ).resolved
20362    if (packageSubpath === '.')
20363      return legacyMainResolve(packageJsonUrl, packageConfig, base)
20364    return new URL$1(packageSubpath, packageJsonUrl)
20365    // Cross-platform root check.
20366  } while (packageJsonPath.length !== lastPath.length)
20367
20368  throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base))
20369}
20370
20371/**
20372 * @param {string} specifier
20373 * @returns {boolean}
20374 */
20375function isRelativeSpecifier(specifier) {
20376  if (specifier[0] === '.') {
20377    if (specifier.length === 1 || specifier[1] === '/') return true
20378    if (
20379      specifier[1] === '.' &&
20380      (specifier.length === 2 || specifier[2] === '/')
20381    ) {
20382      return true
20383    }
20384  }
20385
20386  return false
20387}
20388
20389/**
20390 * @param {string} specifier
20391 * @returns {boolean}
20392 */
20393function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
20394  if (specifier === '') return false
20395  if (specifier[0] === '/') return true
20396  return isRelativeSpecifier(specifier)
20397}
20398
20399/**
20400 * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
20401 * sync and slightly lower-level than `resolve`).
20402 *
20403 *
20404 *
20405 * @param {string} specifier
20406 * @param {URL} base
20407 * @param {Set<string>} [conditions]
20408 * @returns {URL}
20409 */
20410function moduleResolve(specifier, base, conditions) {
20411  // Order swapped from spec for minor perf gain.
20412  // Ok since relative URLs cannot parse as URLs.
20413  /** @type {URL} */
20414  let resolved;
20415
20416  if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
20417    resolved = new URL$1(specifier, base);
20418  } else if (specifier[0] === '#') {
20419({resolved} = packageImportsResolve(specifier, base, conditions));
20420  } else {
20421    try {
20422      resolved = new URL$1(specifier);
20423    } catch {
20424      resolved = packageResolve(specifier, base, conditions);
20425    }
20426  }
20427
20428  return finalizeResolution(resolved, base)
20429}
20430
20431/**
20432 * @param {string} specifier
20433 * @param {{parentURL?: string, conditions?: string[]}} context
20434 * @returns {{url: string}}
20435 */
20436function defaultResolve(specifier, context = {}) {
20437  const {parentURL} = context;
20438  /** @type {URL} */
20439  let parsed;
20440
20441  try {
20442    parsed = new URL$1(specifier);
20443    if (parsed.protocol === 'data:') {
20444      return {url: specifier}
20445    }
20446  } catch {}
20447
20448  if (parsed && parsed.protocol === 'node:') return {url: specifier}
20449  if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:')
20450    throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed)
20451
20452  if (listOfBuiltins.includes(specifier)) {
20453    return {url: 'node:' + specifier}
20454  }
20455
20456  if (parentURL.startsWith('data:')) {
20457    // This is gonna blow up, we want the error
20458    new URL$1(specifier, parentURL);
20459  }
20460
20461  const conditions = getConditionsSet(context.conditions);
20462  let url = moduleResolve(specifier, new URL$1(parentURL), conditions);
20463
20464  const urlPath = fileURLToPath(url);
20465  const real = realpathSync$1(urlPath);
20466  const old = url;
20467  url = pathToFileURL(real + (urlPath.endsWith(path$b.sep) ? '/' : ''));
20468  url.search = old.search;
20469  url.hash = old.hash;
20470
20471  return {url: `${url}`}
20472}
20473
20474/**
20475 * Provides a module-relative resolution function scoped to each module,
20476 * returning the URL string.
20477 * `import.meta.resolve` also accepts a second argument which is the parent
20478 * module from which to resolve from.
20479 *
20480 * This function is asynchronous because the ES module resolver in Node.js is
20481 * allowed to be asynchronous.
20482 *
20483 * @param {string} specifier The module specifier to resolve relative to parent.
20484 * @param {string} parent The absolute parent module URL to resolve from.
20485 *   You should pass `import.meta.url` or something else
20486 * @returns {Promise<string>}
20487 */
20488async function resolve(specifier, parent) {
20489  if (!parent) {
20490    throw new Error(
20491      'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'
20492    )
20493  }
20494
20495  try {
20496    return defaultResolve(specifier, {parentURL: parent}).url
20497  } catch (error) {
20498    return error.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
20499      ? error.url
20500      : Promise.reject(error)
20501  }
20502}
20503
20504var libnpmconfig = {};
20505
20506class FiggyPudding {
20507  constructor (specs, opts, providers) {
20508    this.__specs = specs || {};
20509    Object.keys(this.__specs).forEach(alias => {
20510      if (typeof this.__specs[alias] === 'string') {
20511        const key = this.__specs[alias];
20512        const realSpec = this.__specs[key];
20513        if (realSpec) {
20514          const aliasArr = realSpec.aliases || [];
20515          aliasArr.push(alias, key);
20516          realSpec.aliases = [...(new Set(aliasArr))];
20517          this.__specs[alias] = realSpec;
20518        } else {
20519          throw new Error(`Alias refers to invalid key: ${key} -> ${alias}`)
20520        }
20521      }
20522    });
20523    this.__opts = opts || {};
20524    this.__providers = reverse((providers).filter(
20525      x => x != null && typeof x === 'object'
20526    ));
20527    this.__isFiggyPudding = true;
20528  }
20529  get (key) {
20530    return pudGet(this, key, true)
20531  }
20532  get [Symbol.toStringTag] () { return 'FiggyPudding' }
20533  forEach (fn, thisArg = this) {
20534    for (let [key, value] of this.entries()) {
20535      fn.call(thisArg, value, key, this);
20536    }
20537  }
20538  toJSON () {
20539    const obj = {};
20540    this.forEach((val, key) => {
20541      obj[key] = val;
20542    });
20543    return obj
20544  }
20545  * entries (_matcher) {
20546    for (let key of Object.keys(this.__specs)) {
20547      yield [key, this.get(key)];
20548    }
20549    const matcher = _matcher || this.__opts.other;
20550    if (matcher) {
20551      const seen = new Set();
20552      for (let p of this.__providers) {
20553        const iter = p.entries ? p.entries(matcher) : entries(p);
20554        for (let [key, val] of iter) {
20555          if (matcher(key) && !seen.has(key)) {
20556            seen.add(key);
20557            yield [key, val];
20558          }
20559        }
20560      }
20561    }
20562  }
20563  * [Symbol.iterator] () {
20564    for (let [key, value] of this.entries()) {
20565      yield [key, value];
20566    }
20567  }
20568  * keys () {
20569    for (let [key] of this.entries()) {
20570      yield key;
20571    }
20572  }
20573  * values () {
20574    for (let [, value] of this.entries()) {
20575      yield value;
20576    }
20577  }
20578  concat (...moreConfig) {
20579    return new Proxy(new FiggyPudding(
20580      this.__specs,
20581      this.__opts,
20582      reverse(this.__providers).concat(moreConfig)
20583    ), proxyHandler)
20584  }
20585}
20586try {
20587  const util = require$$0$4;
20588  FiggyPudding.prototype[util.inspect.custom] = function (depth, opts) {
20589    return (
20590      this[Symbol.toStringTag] + ' '
20591    ) + util.inspect(this.toJSON(), opts)
20592  };
20593} catch (e) {}
20594
20595function BadKeyError (key) {
20596  throw Object.assign(new Error(
20597    `invalid config key requested: ${key}`
20598  ), {code: 'EBADKEY'})
20599}
20600
20601function pudGet (pud, key, validate) {
20602  let spec = pud.__specs[key];
20603  if (validate && !spec && (!pud.__opts.other || !pud.__opts.other(key))) {
20604    BadKeyError(key);
20605  } else {
20606    if (!spec) { spec = {}; }
20607    let ret;
20608    for (let p of pud.__providers) {
20609      ret = tryGet(key, p);
20610      if (ret === undefined && spec.aliases && spec.aliases.length) {
20611        for (let alias of spec.aliases) {
20612          if (alias === key) { continue }
20613          ret = tryGet(alias, p);
20614          if (ret !== undefined) {
20615            break
20616          }
20617        }
20618      }
20619      if (ret !== undefined) {
20620        break
20621      }
20622    }
20623    if (ret === undefined && spec.default !== undefined) {
20624      if (typeof spec.default === 'function') {
20625        return spec.default(pud)
20626      } else {
20627        return spec.default
20628      }
20629    } else {
20630      return ret
20631    }
20632  }
20633}
20634
20635function tryGet (key, p) {
20636  let ret;
20637  if (p.__isFiggyPudding) {
20638    ret = pudGet(p, key, false);
20639  } else if (typeof p.get === 'function') {
20640    ret = p.get(key);
20641  } else {
20642    ret = p[key];
20643  }
20644  return ret
20645}
20646
20647const proxyHandler = {
20648  has (obj, prop) {
20649    return prop in obj.__specs && pudGet(obj, prop, false) !== undefined
20650  },
20651  ownKeys (obj) {
20652    return Object.keys(obj.__specs)
20653  },
20654  get (obj, prop) {
20655    if (
20656      typeof prop === 'symbol' ||
20657      prop.slice(0, 2) === '__' ||
20658      prop in FiggyPudding.prototype
20659    ) {
20660      return obj[prop]
20661    }
20662    return obj.get(prop)
20663  },
20664  set (obj, prop, value) {
20665    if (
20666      typeof prop === 'symbol' ||
20667      prop.slice(0, 2) === '__'
20668    ) {
20669      obj[prop] = value;
20670      return true
20671    } else {
20672      throw new Error('figgyPudding options cannot be modified. Use .concat() instead.')
20673    }
20674  },
20675  deleteProperty () {
20676    throw new Error('figgyPudding options cannot be deleted. Use .concat() and shadow them instead.')
20677  }
20678};
20679
20680var figgyPudding_1 = figgyPudding$1;
20681function figgyPudding$1 (specs, opts) {
20682  function factory (...providers) {
20683    return new Proxy(new FiggyPudding(
20684      specs,
20685      opts,
20686      providers
20687    ), proxyHandler)
20688  }
20689  return factory
20690}
20691
20692function reverse (arr) {
20693  const ret = [];
20694  arr.forEach(x => ret.unshift(x));
20695  return ret
20696}
20697
20698function entries (obj) {
20699  return Object.keys(obj).map(k => [k, obj[k]])
20700}
20701
20702var findUp$1 = {exports: {}};
20703
20704var locatePath$1 = {exports: {}};
20705
20706var pathExists$1 = {exports: {}};
20707
20708const fs$5 = require$$0$3;
20709
20710pathExists$1.exports = fp => new Promise(resolve => {
20711	fs$5.access(fp, err => {
20712		resolve(!err);
20713	});
20714});
20715
20716pathExists$1.exports.sync = fp => {
20717	try {
20718		fs$5.accessSync(fp);
20719		return true;
20720	} catch (err) {
20721		return false;
20722	}
20723};
20724
20725var pLimit$2 = {exports: {}};
20726
20727var pTry$2 = {exports: {}};
20728
20729const pTry$1 = (fn, ...arguments_) => new Promise(resolve => {
20730	resolve(fn(...arguments_));
20731});
20732
20733pTry$2.exports = pTry$1;
20734// TODO: remove this in the next major version
20735pTry$2.exports.default = pTry$1;
20736
20737const pTry = pTry$2.exports;
20738
20739const pLimit$1 = concurrency => {
20740	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
20741		return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
20742	}
20743
20744	const queue = [];
20745	let activeCount = 0;
20746
20747	const next = () => {
20748		activeCount--;
20749
20750		if (queue.length > 0) {
20751			queue.shift()();
20752		}
20753	};
20754
20755	const run = (fn, resolve, ...args) => {
20756		activeCount++;
20757
20758		const result = pTry(fn, ...args);
20759
20760		resolve(result);
20761
20762		result.then(next, next);
20763	};
20764
20765	const enqueue = (fn, resolve, ...args) => {
20766		if (activeCount < concurrency) {
20767			run(fn, resolve, ...args);
20768		} else {
20769			queue.push(run.bind(null, fn, resolve, ...args));
20770		}
20771	};
20772
20773	const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
20774	Object.defineProperties(generator, {
20775		activeCount: {
20776			get: () => activeCount
20777		},
20778		pendingCount: {
20779			get: () => queue.length
20780		},
20781		clearQueue: {
20782			value: () => {
20783				queue.length = 0;
20784			}
20785		}
20786	});
20787
20788	return generator;
20789};
20790
20791pLimit$2.exports = pLimit$1;
20792pLimit$2.exports.default = pLimit$1;
20793
20794const pLimit = pLimit$2.exports;
20795
20796class EndError extends Error {
20797	constructor(value) {
20798		super();
20799		this.value = value;
20800	}
20801}
20802
20803// The input can also be a promise, so we `Promise.resolve()` it
20804const testElement = (el, tester) => Promise.resolve(el).then(tester);
20805
20806// The input can also be a promise, so we `Promise.all()` them both
20807const finder$1 = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
20808
20809var pLocate$1 = (iterable, tester, opts) => {
20810	opts = Object.assign({
20811		concurrency: Infinity,
20812		preserveOrder: true
20813	}, opts);
20814
20815	const limit = pLimit(opts.concurrency);
20816
20817	// Start all the promises concurrently with optional limit
20818	const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);
20819
20820	// Check the promises either serially or concurrently
20821	const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
20822
20823	return Promise.all(items.map(el => checkLimit(finder$1, el)))
20824		.then(() => {})
20825		.catch(err => err instanceof EndError ? err.value : Promise.reject(err));
20826};
20827
20828const path$7 = path$b;
20829const pathExists = pathExists$1.exports;
20830const pLocate = pLocate$1;
20831
20832locatePath$1.exports = (iterable, options) => {
20833	options = Object.assign({
20834		cwd: process.cwd()
20835	}, options);
20836
20837	return pLocate(iterable, el => pathExists(path$7.resolve(options.cwd, el)), options);
20838};
20839
20840locatePath$1.exports.sync = (iterable, options) => {
20841	options = Object.assign({
20842		cwd: process.cwd()
20843	}, options);
20844
20845	for (const el of iterable) {
20846		if (pathExists.sync(path$7.resolve(options.cwd, el))) {
20847			return el;
20848		}
20849	}
20850};
20851
20852const path$6 = path$b;
20853const locatePath = locatePath$1.exports;
20854
20855findUp$1.exports = (filename, opts = {}) => {
20856	const startDir = path$6.resolve(opts.cwd || '');
20857	const {root} = path$6.parse(startDir);
20858
20859	const filenames = [].concat(filename);
20860
20861	return new Promise(resolve => {
20862		(function find(dir) {
20863			locatePath(filenames, {cwd: dir}).then(file => {
20864				if (file) {
20865					resolve(path$6.join(dir, file));
20866				} else if (dir === root) {
20867					resolve(null);
20868				} else {
20869					find(path$6.dirname(dir));
20870				}
20871			});
20872		})(startDir);
20873	});
20874};
20875
20876findUp$1.exports.sync = (filename, opts = {}) => {
20877	let dir = path$6.resolve(opts.cwd || '');
20878	const {root} = path$6.parse(dir);
20879
20880	const filenames = [].concat(filename);
20881
20882	// eslint-disable-next-line no-constant-condition
20883	while (true) {
20884		const file = locatePath.sync(filenames, {cwd: dir});
20885
20886		if (file) {
20887			return path$6.join(dir, file);
20888		}
20889
20890		if (dir === root) {
20891			return null;
20892		}
20893
20894		dir = path$6.dirname(dir);
20895	}
20896};
20897
20898var ini$1 = {};
20899
20900ini$1.parse = ini$1.decode = decode;
20901
20902ini$1.stringify = ini$1.encode = encode$1;
20903
20904ini$1.safe = safe$1;
20905ini$1.unsafe = unsafe$1;
20906
20907var eol$1 = typeof process !== 'undefined' &&
20908  process.platform === 'win32' ? '\r\n' : '\n';
20909
20910function encode$1 (obj, opt) {
20911  var children = [];
20912  var out = '';
20913
20914  if (typeof opt === 'string') {
20915    opt = {
20916      section: opt,
20917      whitespace: false,
20918    };
20919  } else {
20920    opt = opt || {};
20921    opt.whitespace = opt.whitespace === true;
20922  }
20923
20924  var separator = opt.whitespace ? ' = ' : '=';
20925
20926  Object.keys(obj).forEach(function (k, _, __) {
20927    var val = obj[k];
20928    if (val && Array.isArray(val)) {
20929      val.forEach(function (item) {
20930        out += safe$1(k + '[]') + separator + safe$1(item) + '\n';
20931      });
20932    } else if (val && typeof val === 'object')
20933      children.push(k);
20934    else
20935      out += safe$1(k) + separator + safe$1(val) + eol$1;
20936  });
20937
20938  if (opt.section && out.length)
20939    out = '[' + safe$1(opt.section) + ']' + eol$1 + out;
20940
20941  children.forEach(function (k, _, __) {
20942    var nk = dotSplit(k).join('\\.');
20943    var section = (opt.section ? opt.section + '.' : '') + nk;
20944    var child = encode$1(obj[k], {
20945      section: section,
20946      whitespace: opt.whitespace,
20947    });
20948    if (out.length && child.length)
20949      out += eol$1;
20950
20951    out += child;
20952  });
20953
20954  return out
20955}
20956
20957function dotSplit (str) {
20958  return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
20959    .replace(/\\\./g, '\u0001')
20960    .split(/\./).map(function (part) {
20961      return part.replace(/\1/g, '\\.')
20962        .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001')
20963    })
20964}
20965
20966function decode (str) {
20967  var out = {};
20968  var p = out;
20969  var section = null;
20970  //          section     |key      = value
20971  var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
20972  var lines = str.split(/[\r\n]+/g);
20973
20974  lines.forEach(function (line, _, __) {
20975    if (!line || line.match(/^\s*[;#]/))
20976      return
20977    var match = line.match(re);
20978    if (!match)
20979      return
20980    if (match[1] !== undefined) {
20981      section = unsafe$1(match[1]);
20982      if (section === '__proto__') {
20983        // not allowed
20984        // keep parsing the section, but don't attach it.
20985        p = {};
20986        return
20987      }
20988      p = out[section] = out[section] || {};
20989      return
20990    }
20991    var key = unsafe$1(match[2]);
20992    if (key === '__proto__')
20993      return
20994    var value = match[3] ? unsafe$1(match[4]) : true;
20995    switch (value) {
20996      case 'true':
20997      case 'false':
20998      case 'null': value = JSON.parse(value);
20999    }
21000
21001    // Convert keys with '[]' suffix to an array
21002    if (key.length > 2 && key.slice(-2) === '[]') {
21003      key = key.substring(0, key.length - 2);
21004      if (key === '__proto__')
21005        return
21006      if (!p[key])
21007        p[key] = [];
21008      else if (!Array.isArray(p[key]))
21009        p[key] = [p[key]];
21010    }
21011
21012    // safeguard against resetting a previously defined
21013    // array by accidentally forgetting the brackets
21014    if (Array.isArray(p[key]))
21015      p[key].push(value);
21016    else
21017      p[key] = value;
21018  });
21019
21020  // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
21021  // use a filter to return the keys that have to be deleted.
21022  Object.keys(out).filter(function (k, _, __) {
21023    if (!out[k] ||
21024      typeof out[k] !== 'object' ||
21025      Array.isArray(out[k]))
21026      return false
21027
21028    // see if the parent section is also an object.
21029    // if so, add it to that, and mark this one for deletion
21030    var parts = dotSplit(k);
21031    var p = out;
21032    var l = parts.pop();
21033    var nl = l.replace(/\\\./g, '.');
21034    parts.forEach(function (part, _, __) {
21035      if (part === '__proto__')
21036        return
21037      if (!p[part] || typeof p[part] !== 'object')
21038        p[part] = {};
21039      p = p[part];
21040    });
21041    if (p === out && nl === l)
21042      return false
21043
21044    p[nl] = out[k];
21045    return true
21046  }).forEach(function (del, _, __) {
21047    delete out[del];
21048  });
21049
21050  return out
21051}
21052
21053function isQuoted (val) {
21054  return (val.charAt(0) === '"' && val.slice(-1) === '"') ||
21055    (val.charAt(0) === "'" && val.slice(-1) === "'")
21056}
21057
21058function safe$1 (val) {
21059  return (typeof val !== 'string' ||
21060    val.match(/[=\r\n]/) ||
21061    val.match(/^\[/) ||
21062    (val.length > 1 &&
21063     isQuoted(val)) ||
21064    val !== val.trim())
21065    ? JSON.stringify(val)
21066    : val.replace(/;/g, '\\;').replace(/#/g, '\\#')
21067}
21068
21069function unsafe$1 (val, doUnesc) {
21070  val = (val || '').trim();
21071  if (isQuoted(val)) {
21072    // remove the single quotes before calling JSON.parse
21073    if (val.charAt(0) === "'")
21074      val = val.substr(1, val.length - 2);
21075
21076    try {
21077      val = JSON.parse(val);
21078    } catch (_) {}
21079  } else {
21080    // walk the val to find the first not-escaped ; character
21081    var esc = false;
21082    var unesc = '';
21083    for (var i = 0, l = val.length; i < l; i++) {
21084      var c = val.charAt(i);
21085      if (esc) {
21086        if ('\\;#'.indexOf(c) !== -1)
21087          unesc += c;
21088        else
21089          unesc += '\\' + c;
21090
21091        esc = false;
21092      } else if (';#'.indexOf(c) !== -1)
21093        break
21094      else if (c === '\\')
21095        esc = true;
21096      else
21097        unesc += c;
21098    }
21099    if (esc)
21100      unesc += '\\';
21101
21102    return unesc.trim()
21103  }
21104  return val
21105}
21106
21107const fs$4 = require$$0$3;
21108const figgyPudding = figgyPudding_1;
21109const findUp = findUp$1.exports;
21110const ini = ini$1;
21111const os = require$$0$2;
21112const path$5 = path$b;
21113
21114const NpmConfig = figgyPudding({}, {
21115  // Open up the pudding object.
21116  other () { return true }
21117});
21118
21119const ConfigOpts = figgyPudding({
21120  cache: { default: path$5.join(os.homedir(), '.npm') },
21121  configNames: { default: ['npmrc', '.npmrc'] },
21122  envPrefix: { default: /^npm_config_/i },
21123  cwd: { default: () => process.cwd() },
21124  globalconfig: {
21125    default: () => path$5.join(getGlobalPrefix(), 'etc', 'npmrc')
21126  },
21127  userconfig: { default: path$5.join(os.homedir(), '.npmrc') }
21128});
21129
21130libnpmconfig.read = getNpmConfig;
21131function getNpmConfig (_opts, _builtin) {
21132  const builtin = ConfigOpts(_builtin);
21133  const env = {};
21134  for (let key of Object.keys(process.env)) {
21135    if (!key.match(builtin.envPrefix)) continue
21136    const newKey = key.toLowerCase()
21137      .replace(builtin.envPrefix, '')
21138      .replace(/(?!^)_/g, '-');
21139    env[newKey] = process.env[key];
21140  }
21141  const cli = NpmConfig(_opts);
21142  const userConfPath = (
21143    builtin.userconfig ||
21144    cli.userconfig ||
21145    env.userconfig
21146  );
21147  const user = userConfPath && maybeReadIni(userConfPath);
21148  const globalConfPath = (
21149    builtin.globalconfig ||
21150    cli.globalconfig ||
21151    env.globalconfig
21152  );
21153  const global = globalConfPath && maybeReadIni(globalConfPath);
21154  const projConfPath = findUp.sync(builtin.configNames, { cwd: builtin.cwd });
21155  let proj = {};
21156  if (projConfPath && projConfPath !== userConfPath) {
21157    proj = maybeReadIni(projConfPath);
21158  }
21159  const newOpts = NpmConfig(builtin, global, user, proj, env, cli);
21160  if (newOpts.cache) {
21161    return newOpts.concat({
21162      cache: path$5.resolve(
21163        (
21164          (cli.cache || env.cache)
21165            ? builtin.cwd
21166            : proj.cache
21167              ? path$5.dirname(projConfPath)
21168              : user.cache
21169                ? path$5.dirname(userConfPath)
21170                : global.cache
21171                  ? path$5.dirname(globalConfPath)
21172                  : path$5.dirname(userConfPath)
21173        ),
21174        newOpts.cache
21175      )
21176    })
21177  } else {
21178    return newOpts
21179  }
21180}
21181
21182function maybeReadIni (f) {
21183  let txt;
21184  try {
21185    txt = fs$4.readFileSync(f, 'utf8');
21186  } catch (err) {
21187    if (err.code === 'ENOENT') {
21188      return ''
21189    } else {
21190      throw err
21191    }
21192  }
21193  return ini.parse(txt)
21194}
21195
21196function getGlobalPrefix () {
21197  if (process.env.PREFIX) {
21198    return process.env.PREFIX
21199  } else if (process.platform === 'win32') {
21200    // c:\node\node.exe --> prefix=c:\node\
21201    return path$5.dirname(process.execPath)
21202  } else {
21203    // /usr/local/bin/node --> prefix=/usr/local
21204    let pref = path$5.dirname(path$5.dirname(process.execPath));
21205    // destdir only is respected on Unix
21206    if (process.env.DESTDIR) {
21207      pref = path$5.join(process.env.DESTDIR, pref);
21208    }
21209    return pref
21210  }
21211}
21212
21213/**
21214 * @typedef ResolveOptions
21215 * @property {string} [prefix]
21216 * @property {string|string[]} [cwd]
21217 * @property {boolean} [global]
21218 */
21219
21220const electron = process.versions.electron !== undefined;
21221const windows = process.platform === 'win32';
21222
21223const argv = process.argv[1] || /* c8 ignore next */ '';
21224const nvm = process.env.NVM_BIN;
21225const appData = process.env.APPDATA;
21226
21227/* c8 ignore next */
21228const globalsLibrary = windows ? '' : 'lib';
21229
21230/** @type {{prefix?: string}} */
21231let builtinNpmConfig;
21232
21233// The prefix config defaults to the location where node is installed.
21234// On Windows, this is in a place called `%AppData%`, which we have to
21235// pass to `libnpmconfig` explicitly:
21236/* c8 ignore next 4 */
21237if (windows && appData) {
21238  builtinNpmConfig = {prefix: path$b.join(appData, 'npm')};
21239}
21240
21241/**
21242 * Note: `libnpmconfig` uses `figgy-pudding` which is slated for archival.
21243 * Either `libnpmconfig` will switch to an alternative or we’ll have to.
21244 * @type {string}
21245 */
21246let npmPrefix = libnpmconfig.read(null, builtinNpmConfig).prefix;
21247
21248// If there is no prefix defined, use the defaults
21249// See: <https://github.com/eush77/npm-prefix/blob/master/index.js>
21250/* c8 ignore next 5 */
21251if (!npmPrefix) {
21252  npmPrefix = windows
21253    ? path$b.dirname(process.execPath)
21254    : path$b.resolve(process.execPath, '../..');
21255}
21256
21257const globalsDefault = electron || argv.indexOf(npmPrefix) === 0;
21258let globalDir = path$b.resolve(npmPrefix, globalsLibrary, 'node_modules');
21259
21260// If we’re in Electron, we’re running in a modified Node that cannot really
21261// install global node modules.
21262// To find the actual modules, the user has to set `prefix` somewhere in an
21263// `.npmrc` (which is picked up by `libnpmconfig`).
21264// Most people don’t do that, and some use NVM instead to manage different
21265// versions of Node.
21266// Luckily NVM leaks some environment variables that we can pick up on to try
21267// and detect the actual modules.
21268/* c8 ignore next 3 */
21269if (electron && nvm && !require$$0$3.existsSync(globalDir)) {
21270  globalDir = path$b.resolve(nvm, '..', globalsLibrary, 'node_modules');
21271}
21272
21273/**
21274 *  Load the plugin found using `resolvePlugin`.
21275 *
21276 * @param {string} name The name to import.
21277 * @param {LoadOptions} [options]
21278 * @returns {Promise<unknown>}
21279 */
21280async function loadPlugin(name, options = {}) {
21281  const {key = 'default', ...rest} = options;
21282  const fp = await resolvePlugin(name, rest);
21283  /** @type {Object.<string, unknown>} */
21284  // Bug with coverage on Node@12.
21285  /* c8 ignore next 3 */
21286  const mod = await import(pathToFileURL(fp).href);
21287  return key === false ? mod : mod[key]
21288}
21289
21290/**
21291 * Find a plugin.
21292 *
21293 * See also:
21294 * *   https://docs.npmjs.com/files/folders#node-modules
21295 * *   https://github.com/sindresorhus/resolve-from
21296 *
21297 * Uses the standard node module loading strategy to find `$name` in each given
21298 * `cwd` (and optionally the global `node_modules` directory).
21299 *
21300 * If a prefix is given and `$name` is not a path, `$prefix-$name` is also
21301 * searched (preferring these over non-prefixed modules).
21302 *
21303 * @param {string} name
21304 * @param {ResolveOptions} [options]
21305 * @returns {Promise.<string>}
21306 */
21307async function resolvePlugin(name, options = {}) {
21308  const prefix = options.prefix
21309    ? options.prefix +
21310      (options.prefix.charAt(options.prefix.length - 1) === '-' ? '' : '-')
21311    : undefined;
21312  const cwd = options.cwd;
21313  const globals =
21314    options.global === undefined || options.global === null
21315      ? globalsDefault
21316      : options.global;
21317  const sources = Array.isArray(cwd) ? cwd.concat() : [cwd || process.cwd()];
21318  /** @type {string} */
21319  let plugin;
21320  /** @type {Error} */
21321  let lastError;
21322
21323  // Non-path.
21324  if (name.charAt(0) !== '.') {
21325    if (globals) {
21326      sources.push(globalDir);
21327    }
21328
21329    let scope = '';
21330
21331    // Unprefix module.
21332    if (prefix) {
21333      // Scope?
21334      if (name.charAt(0) === '@') {
21335        const slash = name.indexOf('/');
21336
21337        // Let’s keep the algorithm simple.
21338        // No need to care if this is a “valid” scope (I think?).
21339        // But we do check for the slash.
21340        if (slash !== -1) {
21341          scope = name.slice(0, slash + 1);
21342          name = name.slice(slash + 1);
21343        }
21344      }
21345
21346      if (name.slice(0, prefix.length) !== prefix) {
21347        plugin = scope + prefix + name;
21348      }
21349
21350      name = scope + name;
21351    }
21352  }
21353
21354  let index = -1;
21355  /** @type {string} */
21356  let fp;
21357
21358  while (++index < sources.length) {
21359    fp = plugin && (await attempt(sources[index], plugin));
21360    if (fp) return fp
21361
21362    fp = await attempt(sources[index], name);
21363    if (fp) return fp
21364  }
21365
21366  // There’s always an error.
21367  // Bug with coverage on Node@12.
21368  /* c8 ignore next 8 */
21369  throw lastError
21370
21371  /**
21372   * @param {string} base
21373   * @param {string} name
21374   * @returns {Promise<string>}
21375   */
21376  async function attempt(base, name) {
21377    try {
21378      // `import-meta-resolve` resolves from files, whereas `load-plugin` works
21379      // on folders, which is why we add a `/` at the end.
21380      return fileURLToPath(
21381        await resolve(name, pathToFileURL(base).href + '/')
21382      )
21383      // Bug with coverage on Node@12.
21384      /* c8 ignore next 1 */
21385    } catch (error) {
21386      lastError = error;
21387    }
21388  }
21389}
21390
21391function isPlainObject$1(value) {
21392	if (Object.prototype.toString.call(value) !== '[object Object]') {
21393		return false;
21394	}
21395
21396	const prototype = Object.getPrototypeOf(value);
21397	return prototype === null || prototype === Object.prototype;
21398}
21399
21400var format$1 = {exports: {}};
21401
21402(function (module) {
21403(function() {
21404
21405  //// Export the API
21406  var namespace;
21407
21408  // CommonJS / Node module
21409  {
21410    namespace = module.exports = format;
21411  }
21412
21413  namespace.format = format;
21414  namespace.vsprintf = vsprintf;
21415
21416  if (typeof console !== 'undefined' && typeof console.log === 'function') {
21417    namespace.printf = printf;
21418  }
21419
21420  function printf(/* ... */) {
21421    console.log(format.apply(null, arguments));
21422  }
21423
21424  function vsprintf(fmt, replacements) {
21425    return format.apply(null, [fmt].concat(replacements));
21426  }
21427
21428  function format(fmt) {
21429    var argIndex = 1 // skip initial format argument
21430      , args = [].slice.call(arguments)
21431      , i = 0
21432      , n = fmt.length
21433      , result = ''
21434      , c
21435      , escaped = false
21436      , arg
21437      , tmp
21438      , leadingZero = false
21439      , precision
21440      , nextArg = function() { return args[argIndex++]; }
21441      , slurpNumber = function() {
21442          var digits = '';
21443          while (/\d/.test(fmt[i])) {
21444            digits += fmt[i++];
21445            c = fmt[i];
21446          }
21447          return digits.length > 0 ? parseInt(digits) : null;
21448        }
21449      ;
21450    for (; i < n; ++i) {
21451      c = fmt[i];
21452      if (escaped) {
21453        escaped = false;
21454        if (c == '.') {
21455          leadingZero = false;
21456          c = fmt[++i];
21457        }
21458        else if (c == '0' && fmt[i + 1] == '.') {
21459          leadingZero = true;
21460          i += 2;
21461          c = fmt[i];
21462        }
21463        else {
21464          leadingZero = true;
21465        }
21466        precision = slurpNumber();
21467        switch (c) {
21468        case 'b': // number in binary
21469          result += parseInt(nextArg(), 10).toString(2);
21470          break;
21471        case 'c': // character
21472          arg = nextArg();
21473          if (typeof arg === 'string' || arg instanceof String)
21474            result += arg;
21475          else
21476            result += String.fromCharCode(parseInt(arg, 10));
21477          break;
21478        case 'd': // number in decimal
21479          result += parseInt(nextArg(), 10);
21480          break;
21481        case 'f': // floating point number
21482          tmp = String(parseFloat(nextArg()).toFixed(precision || 6));
21483          result += leadingZero ? tmp : tmp.replace(/^0/, '');
21484          break;
21485        case 'j': // JSON
21486          result += JSON.stringify(nextArg());
21487          break;
21488        case 'o': // number in octal
21489          result += '0' + parseInt(nextArg(), 10).toString(8);
21490          break;
21491        case 's': // string
21492          result += nextArg();
21493          break;
21494        case 'x': // lowercase hexadecimal
21495          result += '0x' + parseInt(nextArg(), 10).toString(16);
21496          break;
21497        case 'X': // uppercase hexadecimal
21498          result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase();
21499          break;
21500        default:
21501          result += c;
21502          break;
21503        }
21504      } else if (c === '%') {
21505        escaped = true;
21506      } else {
21507        result += c;
21508      }
21509    }
21510    return result;
21511  }
21512
21513}());
21514}(format$1));
21515
21516var formatter = format$1.exports;
21517
21518// @ts-ignore
21519
21520var fault = Object.assign(create$1(Error), {
21521  eval: create$1(EvalError),
21522  range: create$1(RangeError),
21523  reference: create$1(ReferenceError),
21524  syntax: create$1(SyntaxError),
21525  type: create$1(TypeError),
21526  uri: create$1(URIError)
21527});
21528
21529/**
21530 * Create a new `EConstructor`, with the formatted `format` as a first argument.
21531 *
21532 * @template {Error} Fault
21533 * @template {new (reason: string) => Fault} Class
21534 * @param {Class} Constructor
21535 */
21536function create$1(Constructor) {
21537  /** @type {string} */
21538  // @ts-ignore
21539  FormattedError.displayName = Constructor.displayName || Constructor.name;
21540
21541  return FormattedError
21542
21543  /**
21544   * @param {string} [format]
21545   * @param {...unknown} values
21546   * @returns {Fault}
21547   */
21548  function FormattedError(format, ...values) {
21549    /** @type {string} */
21550    var reason = format ? formatter(format, ...values) : format;
21551    return new Constructor(reason)
21552  }
21553}
21554
21555const debug$b = createDebug('unified-engine:find-up');
21556
21557/**
21558 * @template Value
21559 */
21560class FindUp {
21561  /**
21562   * @callback Create
21563   * @param {Buffer} buf
21564   * @param {string} filePath
21565   * @returns {Promise<Value|undefined>|Value|undefined}
21566   */
21567
21568  /**
21569   * @callback Callback
21570   * @param {Error|null} error
21571   * @param {Value} [result]
21572   * @returns {void}
21573   */
21574
21575  /**
21576   * @typedef Options
21577   * @property {string} cwd
21578   * @property {string|undefined} filePath
21579   * @property {boolean|undefined} [detect]
21580   * @property {string[]} names
21581   * @property {Create} create
21582   */
21583
21584  /**
21585   * @param {Options} options
21586   */
21587  constructor(options) {
21588    /** @type {Record<string, Callback[]|undefined|Error|Value>} */
21589    this.cache = {};
21590    /** @type {string} */
21591    this.cwd = options.cwd;
21592    /** @type {boolean|undefined} */
21593    this.detect = options.detect;
21594    /** @type {string[]} */
21595    this.names = options.names;
21596    /** @type {Create} */
21597    this.create = options.create;
21598
21599    /** @type {string|undefined} */
21600    this.givenFilePath = options.filePath
21601      ? path$c.resolve(options.cwd, options.filePath)
21602      : undefined;
21603
21604    /* eslint-disable no-unused-expressions */
21605    /** @type {Error|Value|Callback[]|undefined} */
21606    this.givenFile;
21607    /* eslint-enable no-unused-expressions */
21608  }
21609
21610  /**
21611   * @param {string} filePath
21612   * @param {Callback} callback
21613   */
21614  load(filePath, callback) {
21615    const self = this;
21616    const givenFile = this.givenFile;
21617    const {givenFilePath} = this;
21618
21619    if (givenFilePath) {
21620      if (givenFile) {
21621        apply(callback, givenFile);
21622      } else {
21623        const cbs = [callback];
21624        this.givenFile = cbs;
21625        debug$b('Checking given file `%s`', givenFilePath);
21626        fs$a.readFile(givenFilePath, (error, buf) => {
21627          if (error) {
21628            /** @type {NodeJS.ErrnoException} */
21629            const result = fault(
21630              'Cannot read given file `%s`\n%s',
21631              path$c.relative(this.cwd, givenFilePath),
21632              error.stack
21633            );
21634            result.code = 'ENOENT';
21635            result.path = error.path;
21636            result.syscall = error.syscall;
21637            loaded(result);
21638          } else {
21639            wrap(this.create, (error, /** @type {Value} */ result) => {
21640              if (error) {
21641                debug$b(error.message);
21642                loaded(
21643                  fault(
21644                    'Cannot parse given file `%s`\n%s',
21645                    path$c.relative(this.cwd, givenFilePath),
21646                    error.stack
21647                  )
21648                );
21649              } else {
21650                debug$b('Read given file `%s`', givenFilePath);
21651                loaded(result);
21652              }
21653            })(buf, givenFilePath);
21654          }
21655
21656          /** @param {Error|Value} result */
21657          function loaded(result) {
21658            self.givenFile = result;
21659            applyAll(cbs, result);
21660          }
21661        });
21662      }
21663
21664      return
21665    }
21666
21667    if (!this.detect) {
21668      return callback(null)
21669    }
21670
21671    filePath = path$c.resolve(this.cwd, filePath);
21672    const parent = path$c.dirname(filePath);
21673
21674    if (parent in this.cache) {
21675      apply(callback, this.cache[parent]);
21676    } else {
21677      this.cache[parent] = [callback];
21678      find(parent);
21679    }
21680
21681    /**
21682     * @param {string} directory
21683     */
21684    function find(directory) {
21685      let index = -1;
21686
21687      next();
21688
21689      function next() {
21690        // Try to read the next file.
21691        // We do not use `readdir` because on huge directories, that could be
21692        // *very* slow.
21693        if (++index < self.names.length) {
21694          fs$a.readFile(path$c.join(directory, self.names[index]), done);
21695        } else {
21696          const parent = path$c.dirname(directory);
21697
21698          if (directory === parent) {
21699            debug$b('No files found for `%s`', filePath);
21700            found(null);
21701          } else if (parent in self.cache) {
21702            apply(found, self.cache[parent]);
21703          } else {
21704            self.cache[parent] = [found];
21705            find(parent);
21706          }
21707        }
21708      }
21709
21710      /**
21711       * @param {NodeJS.ErrnoException|null} error
21712       * @param {Buffer} [buf]
21713       * @returns {void}
21714       */
21715      function done(error, buf) {
21716        const fp = path$c.join(directory, self.names[index]);
21717
21718        if (error) {
21719          // Hard to test.
21720          /* c8 ignore next 13 */
21721          if (error.code === 'ENOENT') {
21722            return next()
21723          }
21724
21725          debug$b(error.message);
21726          return found(
21727            fault(
21728              'Cannot read file `%s`\n%s',
21729              path$c.relative(self.cwd, fp),
21730              error.message
21731            )
21732          )
21733        }
21734
21735        wrap(self.create, (error, /** @type {Value} */ result) => {
21736          if (error) {
21737            found(
21738              fault(
21739                'Cannot parse file `%s`\n%s',
21740                path$c.relative(self.cwd, fp),
21741                error.message
21742              )
21743            );
21744          } else if (result) {
21745            debug$b('Read file `%s`', fp);
21746            found(null, result);
21747          } else {
21748            next();
21749          }
21750        })(buf, fp);
21751      }
21752
21753      /**
21754       * @param {Error|null} error
21755       * @param {Value} [result]
21756       * @returns {void}
21757       */
21758      function found(error, result) {
21759        /** @type {Callback[]} */
21760        // @ts-expect-error: always a list if found.
21761        const cbs = self.cache[directory];
21762        self.cache[directory] = error || result;
21763        applyAll(cbs, error || result);
21764      }
21765    }
21766
21767    /**
21768     * @param {Callback[]} cbs
21769     * @param {Value|Error|undefined} result
21770     */
21771    function applyAll(cbs, result) {
21772      let index = cbs.length;
21773
21774      while (index--) {
21775        apply(cbs[index], result);
21776      }
21777    }
21778
21779    /**
21780     * @param {Callback} cb
21781     * @param {Value|Error|Callback[]|undefined} result
21782     */
21783    function apply(cb, result) {
21784      if (Array.isArray(result)) {
21785        result.push(cb);
21786      } else if (result instanceof Error) {
21787        cb(result);
21788      } else {
21789        cb(null, result);
21790      }
21791    }
21792  }
21793}
21794
21795/**
21796 * @typedef {import('unified').Plugin<unknown[]>} Plugin
21797 * @typedef {import('unified').PluginTuple<unknown[]>} PluginTuple
21798 * @typedef {import('unified').PluggableList} PluggableList
21799 *
21800 * @typedef {Record<string, unknown>} Settings
21801 *
21802 * @typedef {Record<string, Settings|null|undefined>} PluginIdObject
21803 * @typedef {Array<string|[string, ...unknown[]]>} PluginIdList
21804 *
21805 * @typedef Preset
21806 * @property {Settings} [settings]
21807 * @property {PluggableList|PluginIdObject|PluginIdList|undefined} [plugins]
21808 *
21809 * @typedef Config
21810 * @property {Settings} [settings]
21811 * @property {Array<PluginTuple>} [plugins]
21812 *
21813 * @callback ConfigTransform
21814 * @param {any} config
21815 * @param {string} filePath
21816 * @returns {Preset}
21817 *
21818 * @callback Loader
21819 * @param {Buffer} buf
21820 * @param {string} filePath
21821 * @returns {Promise<Preset|undefined>}
21822 *
21823 * @callback Callback
21824 * @param {Error|null} error
21825 * @param {Config} [result]
21826 * @returns {void}
21827 */
21828
21829const debug$a = createDebug('unified-engine:configuration');
21830
21831const own$c = {}.hasOwnProperty;
21832
21833/** @type {Record<string, Loader>} */
21834const loaders = {
21835  '.json': loadJson,
21836  '.cjs': loadScriptOrModule,
21837  '.mjs': loadScriptOrModule,
21838  '.js': loadScriptOrModule,
21839  '.yaml': loadYaml,
21840  '.yml': loadYaml
21841};
21842
21843const defaultLoader = loadJson;
21844
21845/**
21846 * @typedef Options
21847 * @property {string} cwd
21848 * @property {string} [packageField]
21849 * @property {string} [pluginPrefix]
21850 * @property {string} [rcName]
21851 * @property {string} [rcPath]
21852 * @property {boolean} [detectConfig]
21853 * @property {ConfigTransform} [configTransform]
21854 * @property {Preset} [defaultConfig]
21855 * @property {Preset['settings']} [settings]
21856 * @property {Preset['plugins']} [plugins]
21857 */
21858
21859class Configuration {
21860  /**
21861   * @param {Options} options
21862   */
21863  constructor(options) {
21864    /** @type {string[]} */
21865    const names = [];
21866
21867    /** @type {string} */
21868    this.cwd = options.cwd;
21869    /** @type {string|undefined} */
21870    this.packageField = options.packageField;
21871    /** @type {string|undefined} */
21872    this.pluginPrefix = options.pluginPrefix;
21873    /** @type {ConfigTransform|undefined} */
21874    this.configTransform = options.configTransform;
21875    /** @type {Preset|undefined} */
21876    this.defaultConfig = options.defaultConfig;
21877
21878    if (options.rcName) {
21879      names.push(
21880        options.rcName,
21881        options.rcName + '.js',
21882        options.rcName + '.yml',
21883        options.rcName + '.yaml'
21884      );
21885      debug$a('Looking for `%s` configuration files', names);
21886    }
21887
21888    if (options.packageField) {
21889      names.push('package.json');
21890      debug$a(
21891        'Looking for `%s` fields in `package.json` files',
21892        options.packageField
21893      );
21894    }
21895
21896    /** @type {Preset} */
21897    this.given = {settings: options.settings, plugins: options.plugins};
21898    this.create = this.create.bind(this);
21899
21900    /** @type {FindUp<Config>} */
21901    this.findUp = new FindUp({
21902      cwd: options.cwd,
21903      filePath: options.rcPath,
21904      detect: options.detectConfig,
21905      names,
21906      create: this.create
21907    });
21908  }
21909
21910  /**
21911   * @param {string} filePath
21912   * @param {Callback} callback
21913   * @returns {void}
21914   */
21915  load(filePath, callback) {
21916    this.findUp.load(
21917      filePath || path$c.resolve(this.cwd, 'stdin.js'),
21918      (error, file) => {
21919        if (error || file) {
21920          return callback(error, file)
21921        }
21922
21923        this.create(undefined, undefined).then((result) => {
21924          callback(null, result);
21925        }, callback);
21926      }
21927    );
21928  }
21929
21930  /**
21931   * @param {Buffer|undefined} buf
21932   * @param {string|undefined} filePath
21933   * @returns {Promise<Config|undefined>}
21934   */
21935  async create(buf, filePath) {
21936    const options = {prefix: this.pluginPrefix, cwd: this.cwd};
21937    const result = {settings: {}, plugins: []};
21938    const extname = filePath ? path$c.extname(filePath) : undefined;
21939    const loader =
21940      extname && extname in loaders ? loaders[extname] : defaultLoader;
21941    /** @type {Preset|undefined} */
21942    let value;
21943
21944    if (filePath && buf) {
21945      value = await loader.call(this, buf, filePath);
21946
21947      if (this.configTransform && value !== undefined) {
21948        value = this.configTransform(value, filePath);
21949      }
21950    }
21951
21952    // Exit if we did find a `package.json`, but it does not have configuration.
21953    if (
21954      filePath &&
21955      value === undefined &&
21956      path$c.basename(filePath) === 'package.json'
21957    ) {
21958      return
21959    }
21960
21961    if (value === undefined) {
21962      if (this.defaultConfig) {
21963        await merge(
21964          result,
21965          this.defaultConfig,
21966          Object.assign({}, options, {root: this.cwd})
21967        );
21968      }
21969    } else {
21970      await merge(
21971        result,
21972        value,
21973        // @ts-expect-error: `value` can only exist if w/ `filePath`.
21974        Object.assign({}, options, {root: path$c.dirname(filePath)})
21975      );
21976    }
21977
21978    await merge(
21979      result,
21980      this.given,
21981      Object.assign({}, options, {root: this.cwd})
21982    );
21983
21984    // C8 bug on Node@12
21985    /* c8 ignore next 2 */
21986    return result
21987  }
21988}
21989
21990/** @type {Loader} */
21991async function loadScriptOrModule(_, filePath) {
21992  // C8 bug on Node@12
21993  /* c8 ignore next 4 */
21994  // @ts-expect-error: Assume it matches config.
21995  // type-coverage:ignore-next-line
21996  return loadFromAbsolutePath(filePath, this.cwd)
21997}
21998
21999/** @type {Loader} */
22000async function loadYaml(buf, filePath) {
22001  // C8 bug on Node@12
22002  /* c8 ignore next 4 */
22003  // @ts-expect-error: Assume it matches config.
22004  return jsYaml.load(String(buf), {filename: path$c.basename(filePath)})
22005}
22006
22007/** @type {Loader} */
22008async function loadJson(buf, filePath) {
22009  /** @type {Record<string, unknown>} */
22010  const result = parseJson_1(String(buf), filePath);
22011
22012  // C8 bug on Node@12
22013  /* c8 ignore next 8 */
22014  // @ts-expect-error: Assume it matches config.
22015  return path$c.basename(filePath) === 'package.json'
22016    ? // @ts-expect-error: `this` is the configuration context, TS doesn’t like
22017      // `this` on callbacks.
22018      // type-coverage:ignore-next-line
22019      result[this.packageField]
22020    : result
22021}
22022
22023/**
22024 * @param {Required<Config>} target
22025 * @param {Preset} raw
22026 * @param {{root: string, prefix: string|undefined}} options
22027 * @returns {Promise<Config>}
22028 */
22029async function merge(target, raw, options) {
22030  if (typeof raw === 'object' && raw !== null) {
22031    await addPreset(raw);
22032  } else {
22033    throw new Error('Expected preset, not `' + raw + '`')
22034  }
22035
22036  // C8 bug on Node@12
22037  /* c8 ignore next 6 */
22038  return target
22039
22040  /**
22041   * @param {Preset} result
22042   */
22043  async function addPreset(result) {
22044    const plugins = result.plugins;
22045
22046    if (plugins === null || plugins === undefined) ; else if (typeof plugins === 'object' && plugins !== null) {
22047      await (Array.isArray(plugins) ? addEach(plugins) : addIn(plugins));
22048    } else {
22049      throw new Error(
22050        'Expected a list or object of plugins, not `' + plugins + '`'
22051      )
22052    }
22053
22054    target.settings = Object.assign({}, target.settings, result.settings);
22055    // C8 bug on Node@12
22056    /* c8 ignore next 6 */
22057  }
22058
22059  /**
22060   * @param {PluginIdList|PluggableList} result
22061   */
22062  async function addEach(result) {
22063    let index = -1;
22064
22065    while (++index < result.length) {
22066      const value = result[index];
22067
22068      // Keep order sequential instead of parallel.
22069      /* eslint-disable no-await-in-loop */
22070      // @ts-expect-error: Spreading is fine.
22071      // type-coverage:ignore-next-line
22072      await (Array.isArray(value) ? use(...value) : use(value, undefined));
22073      /* eslint-enable no-await-in-loop */
22074    }
22075    // C8 bug on Node@12
22076    /* c8 ignore next 6 */
22077  }
22078
22079  /**
22080   * @param {PluginIdObject} result
22081   */
22082  async function addIn(result) {
22083    /** @type {string} */
22084    let key;
22085
22086    for (key in result) {
22087      if (own$c.call(result, key)) {
22088        // Keep order sequential instead of parallel.
22089        // eslint-disable-next-line no-await-in-loop
22090        await use(key, result[key]);
22091      }
22092    }
22093    // C8 bug on Node@12
22094    /* c8 ignore next 7 */
22095  }
22096
22097  /**
22098   * @param {string|Plugin|Preset} usable
22099   * @param {Settings|null|undefined} value
22100   */
22101  async function use(usable, value) {
22102    if (typeof usable === 'string') {
22103      await addModule(usable, value);
22104    } else if (typeof usable === 'function') {
22105      addPlugin(usable, value);
22106    } else {
22107      await merge(target, usable, options);
22108    }
22109    // C8 bug on Node@12
22110    /* c8 ignore next 7 */
22111  }
22112
22113  /**
22114   * @param {string} id
22115   * @param {Settings|null|undefined} value
22116   */
22117  async function addModule(id, value) {
22118    /** @type {string} */
22119    let fp;
22120
22121    try {
22122      fp = await resolvePlugin(id, {
22123        cwd: options.root,
22124        prefix: options.prefix
22125      });
22126    } catch (error) {
22127      addPlugin(() => {
22128        throw fault('Could not find module `%s`\n%s', id, error.stack)
22129      }, value);
22130      return
22131    }
22132
22133    const result = await loadFromAbsolutePath(fp, options.root);
22134
22135    try {
22136      if (typeof result === 'function') {
22137        addPlugin(result, value);
22138      } else {
22139        await merge(
22140          target,
22141          result,
22142          Object.assign({}, options, {root: path$c.dirname(fp)})
22143        );
22144      }
22145    } catch {
22146      throw fault(
22147        'Error: Expected preset or plugin, not %s, at `%s`',
22148        result,
22149        path$c.relative(options.root, fp)
22150      )
22151    }
22152    // C8 bug on Node@12
22153    /* c8 ignore next 8 */
22154  }
22155
22156  /**
22157   * @param {Plugin} plugin
22158   * @param {Settings|null|undefined} value
22159   * @returns {void}
22160   */
22161  function addPlugin(plugin, value) {
22162    const entry = find(target.plugins, plugin);
22163
22164    if (value === null) {
22165      value = undefined;
22166    }
22167
22168    if (entry) {
22169      reconfigure(entry, value);
22170    } else {
22171      target.plugins.push([plugin, value]);
22172    }
22173  }
22174}
22175
22176/**
22177 * @param {PluginTuple} entry
22178 * @param {Settings|undefined} value
22179 * @returns {void}
22180 */
22181function reconfigure(entry, value) {
22182  if (isPlainObject$1(entry[1]) && isPlainObject$1(value)) {
22183    value = Object.assign({}, entry[1], value);
22184  }
22185
22186  entry[1] = value;
22187}
22188
22189/**
22190 * @param {Array<PluginTuple>} entries
22191 * @param {Plugin} plugin
22192 * @returns {PluginTuple|undefined}
22193 */
22194function find(entries, plugin) {
22195  let index = -1;
22196
22197  while (++index < entries.length) {
22198    const entry = entries[index];
22199    if (entry[0] === plugin) {
22200      return entry
22201    }
22202  }
22203}
22204
22205/**
22206 * @param {string} fp
22207 * @param {string} base
22208 * @returns {Promise<Plugin|Preset>}
22209 */
22210async function loadFromAbsolutePath(fp, base) {
22211  try {
22212    /** @type {{default?: unknown}} */
22213    const result = await import(pathToFileURL$1(fp).href);
22214
22215    if (!('default' in result)) {
22216      throw new Error(
22217        'Expected a plugin or preset exported as the default export'
22218      )
22219    }
22220
22221    // @ts-expect-error: assume plugin/preset.
22222    return result.default
22223    // C8 bug on Node@12
22224    /* c8 ignore next 4 */
22225  } catch (error) {
22226    throw fault('Cannot import `%s`\n%s', path$c.relative(base, fp), error.stack)
22227  }
22228}
22229
22230/**
22231 * @typedef {import('./index.js').Settings} Settings
22232 */
22233
22234/**
22235 * @param {Context} context
22236 * @param {Settings} settings
22237 */
22238function configure$3(context, settings) {
22239  context.configuration = new Configuration(settings);
22240}
22241
22242// A simple implementation of make-array
22243function makeArray (subject) {
22244  return Array.isArray(subject)
22245    ? subject
22246    : [subject]
22247}
22248
22249const EMPTY = '';
22250const SPACE = ' ';
22251const ESCAPE = '\\';
22252const REGEX_TEST_BLANK_LINE = /^\s+$/;
22253const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
22254const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
22255const REGEX_SPLITALL_CRLF = /\r?\n/g;
22256// /foo,
22257// ./foo,
22258// ../foo,
22259// .
22260// ..
22261const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
22262
22263const SLASH = '/';
22264const KEY_IGNORE = typeof Symbol !== 'undefined'
22265  ? Symbol.for('node-ignore')
22266  /* istanbul ignore next */
22267  : 'node-ignore';
22268
22269const define = (object, key, value) =>
22270  Object.defineProperty(object, key, {value});
22271
22272const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
22273
22274// Sanitize the range of a regular expression
22275// The cases are complicated, see test cases for details
22276const sanitizeRange = range => range.replace(
22277  REGEX_REGEXP_RANGE,
22278  (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
22279    ? match
22280    // Invalid range (out of order) which is ok for gitignore rules but
22281    //   fatal for JavaScript regular expression, so eliminate it.
22282    : EMPTY
22283);
22284
22285// See fixtures #59
22286const cleanRangeBackSlash = slashes => {
22287  const {length} = slashes;
22288  return slashes.slice(0, length - length % 2)
22289};
22290
22291// > If the pattern ends with a slash,
22292// > it is removed for the purpose of the following description,
22293// > but it would only find a match with a directory.
22294// > In other words, foo/ will match a directory foo and paths underneath it,
22295// > but will not match a regular file or a symbolic link foo
22296// >  (this is consistent with the way how pathspec works in general in Git).
22297// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
22298// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
22299//      you could use option `mark: true` with `glob`
22300
22301// '`foo/`' should not continue with the '`..`'
22302const REPLACERS = [
22303
22304  // > Trailing spaces are ignored unless they are quoted with backslash ("\")
22305  [
22306    // (a\ ) -> (a )
22307    // (a  ) -> (a)
22308    // (a \ ) -> (a  )
22309    /\\?\s+$/,
22310    match => match.indexOf('\\') === 0
22311      ? SPACE
22312      : EMPTY
22313  ],
22314
22315  // replace (\ ) with ' '
22316  [
22317    /\\\s/g,
22318    () => SPACE
22319  ],
22320
22321  // Escape metacharacters
22322  // which is written down by users but means special for regular expressions.
22323
22324  // > There are 12 characters with special meanings:
22325  // > - the backslash \,
22326  // > - the caret ^,
22327  // > - the dollar sign $,
22328  // > - the period or dot .,
22329  // > - the vertical bar or pipe symbol |,
22330  // > - the question mark ?,
22331  // > - the asterisk or star *,
22332  // > - the plus sign +,
22333  // > - the opening parenthesis (,
22334  // > - the closing parenthesis ),
22335  // > - and the opening square bracket [,
22336  // > - the opening curly brace {,
22337  // > These special characters are often called "metacharacters".
22338  [
22339    /[\\$.|*+(){^]/g,
22340    match => `\\${match}`
22341  ],
22342
22343  [
22344    // > a question mark (?) matches a single character
22345    /(?!\\)\?/g,
22346    () => '[^/]'
22347  ],
22348
22349  // leading slash
22350  [
22351
22352    // > A leading slash matches the beginning of the pathname.
22353    // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
22354    // A leading slash matches the beginning of the pathname
22355    /^\//,
22356    () => '^'
22357  ],
22358
22359  // replace special metacharacter slash after the leading slash
22360  [
22361    /\//g,
22362    () => '\\/'
22363  ],
22364
22365  [
22366    // > A leading "**" followed by a slash means match in all directories.
22367    // > For example, "**/foo" matches file or directory "foo" anywhere,
22368    // > the same as pattern "foo".
22369    // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
22370    // >   under directory "foo".
22371    // Notice that the '*'s have been replaced as '\\*'
22372    /^\^*\\\*\\\*\\\//,
22373
22374    // '**/foo' <-> 'foo'
22375    () => '^(?:.*\\/)?'
22376  ],
22377
22378  // starting
22379  [
22380    // there will be no leading '/'
22381    //   (which has been replaced by section "leading slash")
22382    // If starts with '**', adding a '^' to the regular expression also works
22383    /^(?=[^^])/,
22384    function startingReplacer () {
22385      // If has a slash `/` at the beginning or middle
22386      return !/\/(?!$)/.test(this)
22387        // > Prior to 2.22.1
22388        // > If the pattern does not contain a slash /,
22389        // >   Git treats it as a shell glob pattern
22390        // Actually, if there is only a trailing slash,
22391        //   git also treats it as a shell glob pattern
22392
22393        // After 2.22.1 (compatible but clearer)
22394        // > If there is a separator at the beginning or middle (or both)
22395        // > of the pattern, then the pattern is relative to the directory
22396        // > level of the particular .gitignore file itself.
22397        // > Otherwise the pattern may also match at any level below
22398        // > the .gitignore level.
22399        ? '(?:^|\\/)'
22400
22401        // > Otherwise, Git treats the pattern as a shell glob suitable for
22402        // >   consumption by fnmatch(3)
22403        : '^'
22404    }
22405  ],
22406
22407  // two globstars
22408  [
22409    // Use lookahead assertions so that we could match more than one `'/**'`
22410    /\\\/\\\*\\\*(?=\\\/|$)/g,
22411
22412    // Zero, one or several directories
22413    // should not use '*', or it will be replaced by the next replacer
22414
22415    // Check if it is not the last `'/**'`
22416    (_, index, str) => index + 6 < str.length
22417
22418      // case: /**/
22419      // > A slash followed by two consecutive asterisks then a slash matches
22420      // >   zero or more directories.
22421      // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
22422      // '/**/'
22423      ? '(?:\\/[^\\/]+)*'
22424
22425      // case: /**
22426      // > A trailing `"/**"` matches everything inside.
22427
22428      // #21: everything inside but it should not include the current folder
22429      : '\\/.+'
22430  ],
22431
22432  // intermediate wildcards
22433  [
22434    // Never replace escaped '*'
22435    // ignore rule '\*' will match the path '*'
22436
22437    // 'abc.*/' -> go
22438    // 'abc.*'  -> skip this rule
22439    /(^|[^\\]+)\\\*(?=.+)/g,
22440
22441    // '*.js' matches '.js'
22442    // '*.js' doesn't match 'abc'
22443    (_, p1) => `${p1}[^\\/]*`
22444  ],
22445
22446  [
22447    // unescape, revert step 3 except for back slash
22448    // For example, if a user escape a '\\*',
22449    // after step 3, the result will be '\\\\\\*'
22450    /\\\\\\(?=[$.|*+(){^])/g,
22451    () => ESCAPE
22452  ],
22453
22454  [
22455    // '\\\\' -> '\\'
22456    /\\\\/g,
22457    () => ESCAPE
22458  ],
22459
22460  [
22461    // > The range notation, e.g. [a-zA-Z],
22462    // > can be used to match one of the characters in a range.
22463
22464    // `\` is escaped by step 3
22465    /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
22466    (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE
22467      // '\\[bar]' -> '\\\\[bar\\]'
22468      ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
22469      : close === ']'
22470        ? endEscape.length % 2 === 0
22471          // A normal case, and it is a range notation
22472          // '[bar]'
22473          // '[bar\\\\]'
22474          ? `[${sanitizeRange(range)}${endEscape}]`
22475          // Invalid range notaton
22476          // '[bar\\]' -> '[bar\\\\]'
22477          : '[]'
22478        : '[]'
22479  ],
22480
22481  // ending
22482  [
22483    // 'js' will not match 'js.'
22484    // 'ab' will not match 'abc'
22485    /(?:[^*])$/,
22486
22487    // WTF!
22488    // https://git-scm.com/docs/gitignore
22489    // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
22490    // which re-fixes #24, #38
22491
22492    // > If there is a separator at the end of the pattern then the pattern
22493    // > will only match directories, otherwise the pattern can match both
22494    // > files and directories.
22495
22496    // 'js*' will not match 'a.js'
22497    // 'js/' will not match 'a.js'
22498    // 'js' will match 'a.js' and 'a.js/'
22499    match => /\/$/.test(match)
22500      // foo/ will not match 'foo'
22501      ? `${match}$`
22502      // foo matches 'foo' and 'foo/'
22503      : `${match}(?=$|\\/$)`
22504  ],
22505
22506  // trailing wildcard
22507  [
22508    /(\^|\\\/)?\\\*$/,
22509    (_, p1) => {
22510      const prefix = p1
22511        // '\^':
22512        // '/*' does not match EMPTY
22513        // '/*' does not match everything
22514
22515        // '\\\/':
22516        // 'abc/*' does not match 'abc/'
22517        ? `${p1}[^/]+`
22518
22519        // 'a*' matches 'a'
22520        // 'a*' matches 'aa'
22521        : '[^/]*';
22522
22523      return `${prefix}(?=$|\\/$)`
22524    }
22525  ],
22526];
22527
22528// A simple cache, because an ignore rule only has only one certain meaning
22529const regexCache = Object.create(null);
22530
22531// @param {pattern}
22532const makeRegex = (pattern, negative, ignorecase) => {
22533  const r = regexCache[pattern];
22534  if (r) {
22535    return r
22536  }
22537
22538  // const replacers = negative
22539  //   ? NEGATIVE_REPLACERS
22540  //   : POSITIVE_REPLACERS
22541
22542  const source = REPLACERS.reduce(
22543    (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
22544    pattern
22545  );
22546
22547  return regexCache[pattern] = ignorecase
22548    ? new RegExp(source, 'i')
22549    : new RegExp(source)
22550};
22551
22552const isString = subject => typeof subject === 'string';
22553
22554// > A blank line matches no files, so it can serve as a separator for readability.
22555const checkPattern = pattern => pattern
22556  && isString(pattern)
22557  && !REGEX_TEST_BLANK_LINE.test(pattern)
22558
22559  // > A line starting with # serves as a comment.
22560  && pattern.indexOf('#') !== 0;
22561
22562const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
22563
22564class IgnoreRule {
22565  constructor (
22566    origin,
22567    pattern,
22568    negative,
22569    regex
22570  ) {
22571    this.origin = origin;
22572    this.pattern = pattern;
22573    this.negative = negative;
22574    this.regex = regex;
22575  }
22576}
22577
22578const createRule = (pattern, ignorecase) => {
22579  const origin = pattern;
22580  let negative = false;
22581
22582  // > An optional prefix "!" which negates the pattern;
22583  if (pattern.indexOf('!') === 0) {
22584    negative = true;
22585    pattern = pattern.substr(1);
22586  }
22587
22588  pattern = pattern
22589  // > Put a backslash ("\") in front of the first "!" for patterns that
22590  // >   begin with a literal "!", for example, `"\!important!.txt"`.
22591  .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
22592  // > Put a backslash ("\") in front of the first hash for patterns that
22593  // >   begin with a hash.
22594  .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
22595
22596  const regex = makeRegex(pattern, negative, ignorecase);
22597
22598  return new IgnoreRule(
22599    origin,
22600    pattern,
22601    negative,
22602    regex
22603  )
22604};
22605
22606const throwError = (message, Ctor) => {
22607  throw new Ctor(message)
22608};
22609
22610const checkPath = (path, originalPath, doThrow) => {
22611  if (!isString(path)) {
22612    return doThrow(
22613      `path must be a string, but got \`${originalPath}\``,
22614      TypeError
22615    )
22616  }
22617
22618  // We don't know if we should ignore EMPTY, so throw
22619  if (!path) {
22620    return doThrow(`path must not be empty`, TypeError)
22621  }
22622
22623  // Check if it is a relative path
22624  if (checkPath.isNotRelative(path)) {
22625    const r = '`path.relative()`d';
22626    return doThrow(
22627      `path should be a ${r} string, but got "${originalPath}"`,
22628      RangeError
22629    )
22630  }
22631
22632  return true
22633};
22634
22635const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
22636
22637checkPath.isNotRelative = isNotRelative;
22638checkPath.convert = p => p;
22639
22640class Ignore$1 {
22641  constructor ({
22642    ignorecase = true
22643  } = {}) {
22644    this._rules = [];
22645    this._ignorecase = ignorecase;
22646    define(this, KEY_IGNORE, true);
22647    this._initCache();
22648  }
22649
22650  _initCache () {
22651    this._ignoreCache = Object.create(null);
22652    this._testCache = Object.create(null);
22653  }
22654
22655  _addPattern (pattern) {
22656    // #32
22657    if (pattern && pattern[KEY_IGNORE]) {
22658      this._rules = this._rules.concat(pattern._rules);
22659      this._added = true;
22660      return
22661    }
22662
22663    if (checkPattern(pattern)) {
22664      const rule = createRule(pattern, this._ignorecase);
22665      this._added = true;
22666      this._rules.push(rule);
22667    }
22668  }
22669
22670  // @param {Array<string> | string | Ignore} pattern
22671  add (pattern) {
22672    this._added = false;
22673
22674    makeArray(
22675      isString(pattern)
22676        ? splitPattern(pattern)
22677        : pattern
22678    ).forEach(this._addPattern, this);
22679
22680    // Some rules have just added to the ignore,
22681    // making the behavior changed.
22682    if (this._added) {
22683      this._initCache();
22684    }
22685
22686    return this
22687  }
22688
22689  // legacy
22690  addPattern (pattern) {
22691    return this.add(pattern)
22692  }
22693
22694  //          |           ignored : unignored
22695  // negative |   0:0   |   0:1   |   1:0   |   1:1
22696  // -------- | ------- | ------- | ------- | --------
22697  //     0    |  TEST   |  TEST   |  SKIP   |    X
22698  //     1    |  TESTIF |  SKIP   |  TEST   |    X
22699
22700  // - SKIP: always skip
22701  // - TEST: always test
22702  // - TESTIF: only test if checkUnignored
22703  // - X: that never happen
22704
22705  // @param {boolean} whether should check if the path is unignored,
22706  //   setting `checkUnignored` to `false` could reduce additional
22707  //   path matching.
22708
22709  // @returns {TestResult} true if a file is ignored
22710  _testOne (path, checkUnignored) {
22711    let ignored = false;
22712    let unignored = false;
22713
22714    this._rules.forEach(rule => {
22715      const {negative} = rule;
22716      if (
22717        unignored === negative && ignored !== unignored
22718        || negative && !ignored && !unignored && !checkUnignored
22719      ) {
22720        return
22721      }
22722
22723      const matched = rule.regex.test(path);
22724
22725      if (matched) {
22726        ignored = !negative;
22727        unignored = negative;
22728      }
22729    });
22730
22731    return {
22732      ignored,
22733      unignored
22734    }
22735  }
22736
22737  // @returns {TestResult}
22738  _test (originalPath, cache, checkUnignored, slices) {
22739    const path = originalPath
22740      // Supports nullable path
22741      && checkPath.convert(originalPath);
22742
22743    checkPath(path, originalPath, throwError);
22744
22745    return this._t(path, cache, checkUnignored, slices)
22746  }
22747
22748  _t (path, cache, checkUnignored, slices) {
22749    if (path in cache) {
22750      return cache[path]
22751    }
22752
22753    if (!slices) {
22754      // path/to/a.js
22755      // ['path', 'to', 'a.js']
22756      slices = path.split(SLASH);
22757    }
22758
22759    slices.pop();
22760
22761    // If the path has no parent directory, just test it
22762    if (!slices.length) {
22763      return cache[path] = this._testOne(path, checkUnignored)
22764    }
22765
22766    const parent = this._t(
22767      slices.join(SLASH) + SLASH,
22768      cache,
22769      checkUnignored,
22770      slices
22771    );
22772
22773    // If the path contains a parent directory, check the parent first
22774    return cache[path] = parent.ignored
22775      // > It is not possible to re-include a file if a parent directory of
22776      // >   that file is excluded.
22777      ? parent
22778      : this._testOne(path, checkUnignored)
22779  }
22780
22781  ignores (path) {
22782    return this._test(path, this._ignoreCache, false).ignored
22783  }
22784
22785  createFilter () {
22786    return path => !this.ignores(path)
22787  }
22788
22789  filter (paths) {
22790    return makeArray(paths).filter(this.createFilter())
22791  }
22792
22793  // @returns {TestResult}
22794  test (path) {
22795    return this._test(path, this._testCache, true)
22796  }
22797}
22798
22799const factory$1 = options => new Ignore$1(options);
22800
22801const returnFalse = () => false;
22802
22803const isPathValid = path =>
22804  checkPath(path && checkPath.convert(path), path, returnFalse);
22805
22806factory$1.isPathValid = isPathValid;
22807
22808// Fixes typescript
22809factory$1.default = factory$1;
22810
22811var ignore = factory$1;
22812
22813// Windows
22814// --------------------------------------------------------------
22815/* istanbul ignore if  */
22816if (
22817  // Detect `process` so that it can run in browsers.
22818  typeof process !== 'undefined'
22819  && (
22820    process.env && process.env.IGNORE_TEST_WIN32
22821    || process.platform === 'win32'
22822  )
22823) {
22824  /* eslint no-control-regex: "off" */
22825  const makePosix = str => /^\\\\\?\\/.test(str)
22826  || /["<>|\u0000-\u001F]+/u.test(str)
22827    ? str
22828    : str.replace(/\\/g, '/');
22829
22830  checkPath.convert = makePosix;
22831
22832  // 'C:\\foo'     <- 'C:\\foo' has been converted to 'C:/'
22833  // 'd:\\foo'
22834  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
22835  checkPath.isNotRelative = path =>
22836    REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)
22837    || isNotRelative(path);
22838}
22839
22840/**
22841 * @typedef {import('ignore').Ignore & {filePath: string}} IgnoreConfig
22842 *
22843 * @typedef {'cwd'|'dir'} ResolveFrom
22844 *
22845 * @typedef Options
22846 * @property {string} cwd
22847 * @property {boolean|undefined} detectIgnore
22848 * @property {string|undefined} ignoreName
22849 * @property {string|undefined} ignorePath
22850 * @property {ResolveFrom|undefined} ignorePathResolveFrom
22851 *
22852 * @callback Callback
22853 * @param {Error|null} error
22854 * @param {boolean|undefined} [result]
22855 */
22856
22857class Ignore {
22858  /**
22859   * @param {Options} options
22860   */
22861  constructor(options) {
22862    /** @type {string} */
22863    this.cwd = options.cwd;
22864    /** @type {ResolveFrom|undefined} */
22865    this.ignorePathResolveFrom = options.ignorePathResolveFrom;
22866
22867    /** @type {FindUp<IgnoreConfig>} */
22868    this.findUp = new FindUp({
22869      cwd: options.cwd,
22870      filePath: options.ignorePath,
22871      detect: options.detectIgnore,
22872      names: options.ignoreName ? [options.ignoreName] : [],
22873      create
22874    });
22875  }
22876
22877  /**
22878   * @param {string} filePath
22879   * @param {Callback} callback
22880   */
22881  check(filePath, callback) {
22882    this.findUp.load(filePath, (error, ignoreSet) => {
22883      if (error) {
22884        callback(error);
22885      } else if (ignoreSet) {
22886        const normal = path$c.relative(
22887          path$c.resolve(
22888            this.cwd,
22889            this.ignorePathResolveFrom === 'cwd' ? '.' : ignoreSet.filePath
22890          ),
22891          path$c.resolve(this.cwd, filePath)
22892        );
22893
22894        if (
22895          normal === '' ||
22896          normal === '..' ||
22897          normal.charAt(0) === path$c.sep ||
22898          normal.slice(0, 3) === '..' + path$c.sep
22899        ) {
22900          callback(null, false);
22901        } else {
22902          callback(null, ignoreSet.ignores(normal));
22903        }
22904      } else {
22905        callback(null, false);
22906      }
22907    });
22908  }
22909}
22910
22911/**
22912 * @param {Buffer} buf
22913 * @param {string} filePath
22914 * @returns {IgnoreConfig}
22915 */
22916function create(buf, filePath) {
22917  /** @type {IgnoreConfig} */
22918  return Object.assign(ignore().add(String(buf)), {
22919    filePath: path$c.dirname(filePath)
22920  })
22921}
22922
22923var old$1 = {};
22924
22925// Copyright Joyent, Inc. and other Node contributors.
22926//
22927// Permission is hereby granted, free of charge, to any person obtaining a
22928// copy of this software and associated documentation files (the
22929// "Software"), to deal in the Software without restriction, including
22930// without limitation the rights to use, copy, modify, merge, publish,
22931// distribute, sublicense, and/or sell copies of the Software, and to permit
22932// persons to whom the Software is furnished to do so, subject to the
22933// following conditions:
22934//
22935// The above copyright notice and this permission notice shall be included
22936// in all copies or substantial portions of the Software.
22937//
22938// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22939// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22940// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22941// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22942// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22943// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22944// USE OR OTHER DEALINGS IN THE SOFTWARE.
22945
22946var pathModule = path$b;
22947var isWindows = process.platform === 'win32';
22948var fs$3 = require$$0$3;
22949
22950// JavaScript implementation of realpath, ported from node pre-v6
22951
22952var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
22953
22954function rethrow() {
22955  // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
22956  // is fairly slow to generate.
22957  var callback;
22958  if (DEBUG) {
22959    var backtrace = new Error;
22960    callback = debugCallback;
22961  } else
22962    callback = missingCallback;
22963
22964  return callback;
22965
22966  function debugCallback(err) {
22967    if (err) {
22968      backtrace.message = err.message;
22969      err = backtrace;
22970      missingCallback(err);
22971    }
22972  }
22973
22974  function missingCallback(err) {
22975    if (err) {
22976      if (process.throwDeprecation)
22977        throw err;  // Forgot a callback but don't know where? Use NODE_DEBUG=fs
22978      else if (!process.noDeprecation) {
22979        var msg = 'fs: missing callback ' + (err.stack || err.message);
22980        if (process.traceDeprecation)
22981          console.trace(msg);
22982        else
22983          console.error(msg);
22984      }
22985    }
22986  }
22987}
22988
22989function maybeCallback(cb) {
22990  return typeof cb === 'function' ? cb : rethrow();
22991}
22992
22993pathModule.normalize;
22994
22995// Regexp that finds the next partion of a (partial) path
22996// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
22997if (isWindows) {
22998  var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
22999} else {
23000  var nextPartRe = /(.*?)(?:[\/]+|$)/g;
23001}
23002
23003// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
23004if (isWindows) {
23005  var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
23006} else {
23007  var splitRootRe = /^[\/]*/;
23008}
23009
23010old$1.realpathSync = function realpathSync(p, cache) {
23011  // make p is absolute
23012  p = pathModule.resolve(p);
23013
23014  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
23015    return cache[p];
23016  }
23017
23018  var original = p,
23019      seenLinks = {},
23020      knownHard = {};
23021
23022  // current character position in p
23023  var pos;
23024  // the partial path so far, including a trailing slash if any
23025  var current;
23026  // the partial path without a trailing slash (except when pointing at a root)
23027  var base;
23028  // the partial path scanned in the previous round, with slash
23029  var previous;
23030
23031  start();
23032
23033  function start() {
23034    // Skip over roots
23035    var m = splitRootRe.exec(p);
23036    pos = m[0].length;
23037    current = m[0];
23038    base = m[0];
23039    previous = '';
23040
23041    // On windows, check that the root exists. On unix there is no need.
23042    if (isWindows && !knownHard[base]) {
23043      fs$3.lstatSync(base);
23044      knownHard[base] = true;
23045    }
23046  }
23047
23048  // walk down the path, swapping out linked pathparts for their real
23049  // values
23050  // NB: p.length changes.
23051  while (pos < p.length) {
23052    // find the next part
23053    nextPartRe.lastIndex = pos;
23054    var result = nextPartRe.exec(p);
23055    previous = current;
23056    current += result[0];
23057    base = previous + result[1];
23058    pos = nextPartRe.lastIndex;
23059
23060    // continue if not a symlink
23061    if (knownHard[base] || (cache && cache[base] === base)) {
23062      continue;
23063    }
23064
23065    var resolvedLink;
23066    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
23067      // some known symbolic link.  no need to stat again.
23068      resolvedLink = cache[base];
23069    } else {
23070      var stat = fs$3.lstatSync(base);
23071      if (!stat.isSymbolicLink()) {
23072        knownHard[base] = true;
23073        if (cache) cache[base] = base;
23074        continue;
23075      }
23076
23077      // read the link if it wasn't read before
23078      // dev/ino always return 0 on windows, so skip the check.
23079      var linkTarget = null;
23080      if (!isWindows) {
23081        var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
23082        if (seenLinks.hasOwnProperty(id)) {
23083          linkTarget = seenLinks[id];
23084        }
23085      }
23086      if (linkTarget === null) {
23087        fs$3.statSync(base);
23088        linkTarget = fs$3.readlinkSync(base);
23089      }
23090      resolvedLink = pathModule.resolve(previous, linkTarget);
23091      // track this, if given a cache.
23092      if (cache) cache[base] = resolvedLink;
23093      if (!isWindows) seenLinks[id] = linkTarget;
23094    }
23095
23096    // resolve the link, then start over
23097    p = pathModule.resolve(resolvedLink, p.slice(pos));
23098    start();
23099  }
23100
23101  if (cache) cache[original] = p;
23102
23103  return p;
23104};
23105
23106
23107old$1.realpath = function realpath(p, cache, cb) {
23108  if (typeof cb !== 'function') {
23109    cb = maybeCallback(cache);
23110    cache = null;
23111  }
23112
23113  // make p is absolute
23114  p = pathModule.resolve(p);
23115
23116  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
23117    return process.nextTick(cb.bind(null, null, cache[p]));
23118  }
23119
23120  var original = p,
23121      seenLinks = {},
23122      knownHard = {};
23123
23124  // current character position in p
23125  var pos;
23126  // the partial path so far, including a trailing slash if any
23127  var current;
23128  // the partial path without a trailing slash (except when pointing at a root)
23129  var base;
23130  // the partial path scanned in the previous round, with slash
23131  var previous;
23132
23133  start();
23134
23135  function start() {
23136    // Skip over roots
23137    var m = splitRootRe.exec(p);
23138    pos = m[0].length;
23139    current = m[0];
23140    base = m[0];
23141    previous = '';
23142
23143    // On windows, check that the root exists. On unix there is no need.
23144    if (isWindows && !knownHard[base]) {
23145      fs$3.lstat(base, function(err) {
23146        if (err) return cb(err);
23147        knownHard[base] = true;
23148        LOOP();
23149      });
23150    } else {
23151      process.nextTick(LOOP);
23152    }
23153  }
23154
23155  // walk down the path, swapping out linked pathparts for their real
23156  // values
23157  function LOOP() {
23158    // stop if scanned past end of path
23159    if (pos >= p.length) {
23160      if (cache) cache[original] = p;
23161      return cb(null, p);
23162    }
23163
23164    // find the next part
23165    nextPartRe.lastIndex = pos;
23166    var result = nextPartRe.exec(p);
23167    previous = current;
23168    current += result[0];
23169    base = previous + result[1];
23170    pos = nextPartRe.lastIndex;
23171
23172    // continue if not a symlink
23173    if (knownHard[base] || (cache && cache[base] === base)) {
23174      return process.nextTick(LOOP);
23175    }
23176
23177    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
23178      // known symbolic link.  no need to stat again.
23179      return gotResolvedLink(cache[base]);
23180    }
23181
23182    return fs$3.lstat(base, gotStat);
23183  }
23184
23185  function gotStat(err, stat) {
23186    if (err) return cb(err);
23187
23188    // if not a symlink, skip to the next path part
23189    if (!stat.isSymbolicLink()) {
23190      knownHard[base] = true;
23191      if (cache) cache[base] = base;
23192      return process.nextTick(LOOP);
23193    }
23194
23195    // stat & read the link if not read before
23196    // call gotTarget as soon as the link target is known
23197    // dev/ino always return 0 on windows, so skip the check.
23198    if (!isWindows) {
23199      var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
23200      if (seenLinks.hasOwnProperty(id)) {
23201        return gotTarget(null, seenLinks[id], base);
23202      }
23203    }
23204    fs$3.stat(base, function(err) {
23205      if (err) return cb(err);
23206
23207      fs$3.readlink(base, function(err, target) {
23208        if (!isWindows) seenLinks[id] = target;
23209        gotTarget(err, target);
23210      });
23211    });
23212  }
23213
23214  function gotTarget(err, target, base) {
23215    if (err) return cb(err);
23216
23217    var resolvedLink = pathModule.resolve(previous, target);
23218    if (cache) cache[base] = resolvedLink;
23219    gotResolvedLink(resolvedLink);
23220  }
23221
23222  function gotResolvedLink(resolvedLink) {
23223    // resolve the link, then start over
23224    p = pathModule.resolve(resolvedLink, p.slice(pos));
23225    start();
23226  }
23227};
23228
23229var fs_realpath = realpath;
23230realpath.realpath = realpath;
23231realpath.sync = realpathSync;
23232realpath.realpathSync = realpathSync;
23233realpath.monkeypatch = monkeypatch;
23234realpath.unmonkeypatch = unmonkeypatch;
23235
23236var fs$2 = require$$0$3;
23237var origRealpath = fs$2.realpath;
23238var origRealpathSync = fs$2.realpathSync;
23239
23240var version$2 = process.version;
23241var ok$1 = /^v[0-5]\./.test(version$2);
23242var old = old$1;
23243
23244function newError (er) {
23245  return er && er.syscall === 'realpath' && (
23246    er.code === 'ELOOP' ||
23247    er.code === 'ENOMEM' ||
23248    er.code === 'ENAMETOOLONG'
23249  )
23250}
23251
23252function realpath (p, cache, cb) {
23253  if (ok$1) {
23254    return origRealpath(p, cache, cb)
23255  }
23256
23257  if (typeof cache === 'function') {
23258    cb = cache;
23259    cache = null;
23260  }
23261  origRealpath(p, cache, function (er, result) {
23262    if (newError(er)) {
23263      old.realpath(p, cache, cb);
23264    } else {
23265      cb(er, result);
23266    }
23267  });
23268}
23269
23270function realpathSync (p, cache) {
23271  if (ok$1) {
23272    return origRealpathSync(p, cache)
23273  }
23274
23275  try {
23276    return origRealpathSync(p, cache)
23277  } catch (er) {
23278    if (newError(er)) {
23279      return old.realpathSync(p, cache)
23280    } else {
23281      throw er
23282    }
23283  }
23284}
23285
23286function monkeypatch () {
23287  fs$2.realpath = realpath;
23288  fs$2.realpathSync = realpathSync;
23289}
23290
23291function unmonkeypatch () {
23292  fs$2.realpath = origRealpath;
23293  fs$2.realpathSync = origRealpathSync;
23294}
23295
23296var concatMap$1 = function (xs, fn) {
23297    var res = [];
23298    for (var i = 0; i < xs.length; i++) {
23299        var x = fn(xs[i], i);
23300        if (isArray$1(x)) res.push.apply(res, x);
23301        else res.push(x);
23302    }
23303    return res;
23304};
23305
23306var isArray$1 = Array.isArray || function (xs) {
23307    return Object.prototype.toString.call(xs) === '[object Array]';
23308};
23309
23310var balancedMatch = balanced$1;
23311function balanced$1(a, b, str) {
23312  if (a instanceof RegExp) a = maybeMatch(a, str);
23313  if (b instanceof RegExp) b = maybeMatch(b, str);
23314
23315  var r = range(a, b, str);
23316
23317  return r && {
23318    start: r[0],
23319    end: r[1],
23320    pre: str.slice(0, r[0]),
23321    body: str.slice(r[0] + a.length, r[1]),
23322    post: str.slice(r[1] + b.length)
23323  };
23324}
23325
23326function maybeMatch(reg, str) {
23327  var m = str.match(reg);
23328  return m ? m[0] : null;
23329}
23330
23331balanced$1.range = range;
23332function range(a, b, str) {
23333  var begs, beg, left, right, result;
23334  var ai = str.indexOf(a);
23335  var bi = str.indexOf(b, ai + 1);
23336  var i = ai;
23337
23338  if (ai >= 0 && bi > 0) {
23339    begs = [];
23340    left = str.length;
23341
23342    while (i >= 0 && !result) {
23343      if (i == ai) {
23344        begs.push(i);
23345        ai = str.indexOf(a, i + 1);
23346      } else if (begs.length == 1) {
23347        result = [ begs.pop(), bi ];
23348      } else {
23349        beg = begs.pop();
23350        if (beg < left) {
23351          left = beg;
23352          right = bi;
23353        }
23354
23355        bi = str.indexOf(b, i + 1);
23356      }
23357
23358      i = ai < bi && ai >= 0 ? ai : bi;
23359    }
23360
23361    if (begs.length) {
23362      result = [ left, right ];
23363    }
23364  }
23365
23366  return result;
23367}
23368
23369var concatMap = concatMap$1;
23370var balanced = balancedMatch;
23371
23372var braceExpansion = expandTop;
23373
23374var escSlash = '\0SLASH'+Math.random()+'\0';
23375var escOpen = '\0OPEN'+Math.random()+'\0';
23376var escClose = '\0CLOSE'+Math.random()+'\0';
23377var escComma = '\0COMMA'+Math.random()+'\0';
23378var escPeriod = '\0PERIOD'+Math.random()+'\0';
23379
23380function numeric(str) {
23381  return parseInt(str, 10) == str
23382    ? parseInt(str, 10)
23383    : str.charCodeAt(0);
23384}
23385
23386function escapeBraces(str) {
23387  return str.split('\\\\').join(escSlash)
23388            .split('\\{').join(escOpen)
23389            .split('\\}').join(escClose)
23390            .split('\\,').join(escComma)
23391            .split('\\.').join(escPeriod);
23392}
23393
23394function unescapeBraces(str) {
23395  return str.split(escSlash).join('\\')
23396            .split(escOpen).join('{')
23397            .split(escClose).join('}')
23398            .split(escComma).join(',')
23399            .split(escPeriod).join('.');
23400}
23401
23402
23403// Basically just str.split(","), but handling cases
23404// where we have nested braced sections, which should be
23405// treated as individual members, like {a,{b,c},d}
23406function parseCommaParts(str) {
23407  if (!str)
23408    return [''];
23409
23410  var parts = [];
23411  var m = balanced('{', '}', str);
23412
23413  if (!m)
23414    return str.split(',');
23415
23416  var pre = m.pre;
23417  var body = m.body;
23418  var post = m.post;
23419  var p = pre.split(',');
23420
23421  p[p.length-1] += '{' + body + '}';
23422  var postParts = parseCommaParts(post);
23423  if (post.length) {
23424    p[p.length-1] += postParts.shift();
23425    p.push.apply(p, postParts);
23426  }
23427
23428  parts.push.apply(parts, p);
23429
23430  return parts;
23431}
23432
23433function expandTop(str) {
23434  if (!str)
23435    return [];
23436
23437  // I don't know why Bash 4.3 does this, but it does.
23438  // Anything starting with {} will have the first two bytes preserved
23439  // but *only* at the top level, so {},a}b will not expand to anything,
23440  // but a{},b}c will be expanded to [a}c,abc].
23441  // One could argue that this is a bug in Bash, but since the goal of
23442  // this module is to match Bash's rules, we escape a leading {}
23443  if (str.substr(0, 2) === '{}') {
23444    str = '\\{\\}' + str.substr(2);
23445  }
23446
23447  return expand$2(escapeBraces(str), true).map(unescapeBraces);
23448}
23449
23450function embrace(str) {
23451  return '{' + str + '}';
23452}
23453function isPadded(el) {
23454  return /^-?0\d/.test(el);
23455}
23456
23457function lte(i, y) {
23458  return i <= y;
23459}
23460function gte(i, y) {
23461  return i >= y;
23462}
23463
23464function expand$2(str, isTop) {
23465  var expansions = [];
23466
23467  var m = balanced('{', '}', str);
23468  if (!m || /\$$/.test(m.pre)) return [str];
23469
23470  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
23471  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
23472  var isSequence = isNumericSequence || isAlphaSequence;
23473  var isOptions = m.body.indexOf(',') >= 0;
23474  if (!isSequence && !isOptions) {
23475    // {a},b}
23476    if (m.post.match(/,.*\}/)) {
23477      str = m.pre + '{' + m.body + escClose + m.post;
23478      return expand$2(str);
23479    }
23480    return [str];
23481  }
23482
23483  var n;
23484  if (isSequence) {
23485    n = m.body.split(/\.\./);
23486  } else {
23487    n = parseCommaParts(m.body);
23488    if (n.length === 1) {
23489      // x{{a,b}}y ==> x{a}y x{b}y
23490      n = expand$2(n[0], false).map(embrace);
23491      if (n.length === 1) {
23492        var post = m.post.length
23493          ? expand$2(m.post, false)
23494          : [''];
23495        return post.map(function(p) {
23496          return m.pre + n[0] + p;
23497        });
23498      }
23499    }
23500  }
23501
23502  // at this point, n is the parts, and we know it's not a comma set
23503  // with a single entry.
23504
23505  // no need to expand pre, since it is guaranteed to be free of brace-sets
23506  var pre = m.pre;
23507  var post = m.post.length
23508    ? expand$2(m.post, false)
23509    : [''];
23510
23511  var N;
23512
23513  if (isSequence) {
23514    var x = numeric(n[0]);
23515    var y = numeric(n[1]);
23516    var width = Math.max(n[0].length, n[1].length);
23517    var incr = n.length == 3
23518      ? Math.abs(numeric(n[2]))
23519      : 1;
23520    var test = lte;
23521    var reverse = y < x;
23522    if (reverse) {
23523      incr *= -1;
23524      test = gte;
23525    }
23526    var pad = n.some(isPadded);
23527
23528    N = [];
23529
23530    for (var i = x; test(i, y); i += incr) {
23531      var c;
23532      if (isAlphaSequence) {
23533        c = String.fromCharCode(i);
23534        if (c === '\\')
23535          c = '';
23536      } else {
23537        c = String(i);
23538        if (pad) {
23539          var need = width - c.length;
23540          if (need > 0) {
23541            var z = new Array(need + 1).join('0');
23542            if (i < 0)
23543              c = '-' + z + c.slice(1);
23544            else
23545              c = z + c;
23546          }
23547        }
23548      }
23549      N.push(c);
23550    }
23551  } else {
23552    N = concatMap(n, function(el) { return expand$2(el, false) });
23553  }
23554
23555  for (var j = 0; j < N.length; j++) {
23556    for (var k = 0; k < post.length; k++) {
23557      var expansion = pre + N[j] + post[k];
23558      if (!isTop || isSequence || expansion)
23559        expansions.push(expansion);
23560    }
23561  }
23562
23563  return expansions;
23564}
23565
23566var minimatch_1 = minimatch$3;
23567minimatch$3.Minimatch = Minimatch$1;
23568
23569var path$4 = { sep: '/' };
23570try {
23571  path$4 = path$b;
23572} catch (er) {}
23573
23574var GLOBSTAR = minimatch$3.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
23575var expand$1 = braceExpansion;
23576
23577var plTypes = {
23578  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
23579  '?': { open: '(?:', close: ')?' },
23580  '+': { open: '(?:', close: ')+' },
23581  '*': { open: '(?:', close: ')*' },
23582  '@': { open: '(?:', close: ')' }
23583};
23584
23585// any single thing other than /
23586// don't need to escape / when using new RegExp()
23587var qmark = '[^/]';
23588
23589// * => any number of characters
23590var star = qmark + '*?';
23591
23592// ** when dots are allowed.  Anything goes, except .. and .
23593// not (^ or / followed by one or two dots followed by $ or /),
23594// followed by anything, any number of times.
23595var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
23596
23597// not a ^ or / followed by a dot,
23598// followed by anything, any number of times.
23599var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
23600
23601// characters that need to be escaped in RegExp.
23602var reSpecials = charSet('().*{}+?[]^$\\!');
23603
23604// "abc" -> { a:true, b:true, c:true }
23605function charSet (s) {
23606  return s.split('').reduce(function (set, c) {
23607    set[c] = true;
23608    return set
23609  }, {})
23610}
23611
23612// normalizes slashes.
23613var slashSplit = /\/+/;
23614
23615minimatch$3.filter = filter;
23616function filter (pattern, options) {
23617  options = options || {};
23618  return function (p, i, list) {
23619    return minimatch$3(p, pattern, options)
23620  }
23621}
23622
23623function ext (a, b) {
23624  a = a || {};
23625  b = b || {};
23626  var t = {};
23627  Object.keys(b).forEach(function (k) {
23628    t[k] = b[k];
23629  });
23630  Object.keys(a).forEach(function (k) {
23631    t[k] = a[k];
23632  });
23633  return t
23634}
23635
23636minimatch$3.defaults = function (def) {
23637  if (!def || !Object.keys(def).length) return minimatch$3
23638
23639  var orig = minimatch$3;
23640
23641  var m = function minimatch (p, pattern, options) {
23642    return orig.minimatch(p, pattern, ext(def, options))
23643  };
23644
23645  m.Minimatch = function Minimatch (pattern, options) {
23646    return new orig.Minimatch(pattern, ext(def, options))
23647  };
23648
23649  return m
23650};
23651
23652Minimatch$1.defaults = function (def) {
23653  if (!def || !Object.keys(def).length) return Minimatch$1
23654  return minimatch$3.defaults(def).Minimatch
23655};
23656
23657function minimatch$3 (p, pattern, options) {
23658  if (typeof pattern !== 'string') {
23659    throw new TypeError('glob pattern string required')
23660  }
23661
23662  if (!options) options = {};
23663
23664  // shortcut: comments match nothing.
23665  if (!options.nocomment && pattern.charAt(0) === '#') {
23666    return false
23667  }
23668
23669  // "" only matches ""
23670  if (pattern.trim() === '') return p === ''
23671
23672  return new Minimatch$1(pattern, options).match(p)
23673}
23674
23675function Minimatch$1 (pattern, options) {
23676  if (!(this instanceof Minimatch$1)) {
23677    return new Minimatch$1(pattern, options)
23678  }
23679
23680  if (typeof pattern !== 'string') {
23681    throw new TypeError('glob pattern string required')
23682  }
23683
23684  if (!options) options = {};
23685  pattern = pattern.trim();
23686
23687  // windows support: need to use /, not \
23688  if (path$4.sep !== '/') {
23689    pattern = pattern.split(path$4.sep).join('/');
23690  }
23691
23692  this.options = options;
23693  this.set = [];
23694  this.pattern = pattern;
23695  this.regexp = null;
23696  this.negate = false;
23697  this.comment = false;
23698  this.empty = false;
23699
23700  // make the set of regexps etc.
23701  this.make();
23702}
23703
23704Minimatch$1.prototype.debug = function () {};
23705
23706Minimatch$1.prototype.make = make;
23707function make () {
23708  // don't do it more than once.
23709  if (this._made) return
23710
23711  var pattern = this.pattern;
23712  var options = this.options;
23713
23714  // empty patterns and comments match nothing.
23715  if (!options.nocomment && pattern.charAt(0) === '#') {
23716    this.comment = true;
23717    return
23718  }
23719  if (!pattern) {
23720    this.empty = true;
23721    return
23722  }
23723
23724  // step 1: figure out negation, etc.
23725  this.parseNegate();
23726
23727  // step 2: expand braces
23728  var set = this.globSet = this.braceExpand();
23729
23730  if (options.debug) this.debug = console.error;
23731
23732  this.debug(this.pattern, set);
23733
23734  // step 3: now we have a set, so turn each one into a series of path-portion
23735  // matching patterns.
23736  // These will be regexps, except in the case of "**", which is
23737  // set to the GLOBSTAR object for globstar behavior,
23738  // and will not contain any / characters
23739  set = this.globParts = set.map(function (s) {
23740    return s.split(slashSplit)
23741  });
23742
23743  this.debug(this.pattern, set);
23744
23745  // glob --> regexps
23746  set = set.map(function (s, si, set) {
23747    return s.map(this.parse, this)
23748  }, this);
23749
23750  this.debug(this.pattern, set);
23751
23752  // filter out everything that didn't compile properly.
23753  set = set.filter(function (s) {
23754    return s.indexOf(false) === -1
23755  });
23756
23757  this.debug(this.pattern, set);
23758
23759  this.set = set;
23760}
23761
23762Minimatch$1.prototype.parseNegate = parseNegate;
23763function parseNegate () {
23764  var pattern = this.pattern;
23765  var negate = false;
23766  var options = this.options;
23767  var negateOffset = 0;
23768
23769  if (options.nonegate) return
23770
23771  for (var i = 0, l = pattern.length
23772    ; i < l && pattern.charAt(i) === '!'
23773    ; i++) {
23774    negate = !negate;
23775    negateOffset++;
23776  }
23777
23778  if (negateOffset) this.pattern = pattern.substr(negateOffset);
23779  this.negate = negate;
23780}
23781
23782// Brace expansion:
23783// a{b,c}d -> abd acd
23784// a{b,}c -> abc ac
23785// a{0..3}d -> a0d a1d a2d a3d
23786// a{b,c{d,e}f}g -> abg acdfg acefg
23787// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
23788//
23789// Invalid sets are not expanded.
23790// a{2..}b -> a{2..}b
23791// a{b}c -> a{b}c
23792minimatch$3.braceExpand = function (pattern, options) {
23793  return braceExpand(pattern, options)
23794};
23795
23796Minimatch$1.prototype.braceExpand = braceExpand;
23797
23798function braceExpand (pattern, options) {
23799  if (!options) {
23800    if (this instanceof Minimatch$1) {
23801      options = this.options;
23802    } else {
23803      options = {};
23804    }
23805  }
23806
23807  pattern = typeof pattern === 'undefined'
23808    ? this.pattern : pattern;
23809
23810  if (typeof pattern === 'undefined') {
23811    throw new TypeError('undefined pattern')
23812  }
23813
23814  if (options.nobrace ||
23815    !pattern.match(/\{.*\}/)) {
23816    // shortcut. no need to expand.
23817    return [pattern]
23818  }
23819
23820  return expand$1(pattern)
23821}
23822
23823// parse a component of the expanded set.
23824// At this point, no pattern may contain "/" in it
23825// so we're going to return a 2d array, where each entry is the full
23826// pattern, split on '/', and then turned into a regular expression.
23827// A regexp is made at the end which joins each array with an
23828// escaped /, and another full one which joins each regexp with |.
23829//
23830// Following the lead of Bash 4.1, note that "**" only has special meaning
23831// when it is the *only* thing in a path portion.  Otherwise, any series
23832// of * is equivalent to a single *.  Globstar behavior is enabled by
23833// default, and can be disabled by setting options.noglobstar.
23834Minimatch$1.prototype.parse = parse$3;
23835var SUBPARSE = {};
23836function parse$3 (pattern, isSub) {
23837  if (pattern.length > 1024 * 64) {
23838    throw new TypeError('pattern is too long')
23839  }
23840
23841  var options = this.options;
23842
23843  // shortcuts
23844  if (!options.noglobstar && pattern === '**') return GLOBSTAR
23845  if (pattern === '') return ''
23846
23847  var re = '';
23848  var hasMagic = !!options.nocase;
23849  var escaping = false;
23850  // ? => one single character
23851  var patternListStack = [];
23852  var negativeLists = [];
23853  var stateChar;
23854  var inClass = false;
23855  var reClassStart = -1;
23856  var classStart = -1;
23857  // . and .. never match anything that doesn't start with .,
23858  // even when options.dot is set.
23859  var patternStart = pattern.charAt(0) === '.' ? '' // anything
23860  // not (start or / followed by . or .. followed by / or end)
23861  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
23862  : '(?!\\.)';
23863  var self = this;
23864
23865  function clearStateChar () {
23866    if (stateChar) {
23867      // we had some state-tracking character
23868      // that wasn't consumed by this pass.
23869      switch (stateChar) {
23870        case '*':
23871          re += star;
23872          hasMagic = true;
23873        break
23874        case '?':
23875          re += qmark;
23876          hasMagic = true;
23877        break
23878        default:
23879          re += '\\' + stateChar;
23880        break
23881      }
23882      self.debug('clearStateChar %j %j', stateChar, re);
23883      stateChar = false;
23884    }
23885  }
23886
23887  for (var i = 0, len = pattern.length, c
23888    ; (i < len) && (c = pattern.charAt(i))
23889    ; i++) {
23890    this.debug('%s\t%s %s %j', pattern, i, re, c);
23891
23892    // skip over any that are escaped.
23893    if (escaping && reSpecials[c]) {
23894      re += '\\' + c;
23895      escaping = false;
23896      continue
23897    }
23898
23899    switch (c) {
23900      case '/':
23901        // completely not allowed, even escaped.
23902        // Should already be path-split by now.
23903        return false
23904
23905      case '\\':
23906        clearStateChar();
23907        escaping = true;
23908      continue
23909
23910      // the various stateChar values
23911      // for the "extglob" stuff.
23912      case '?':
23913      case '*':
23914      case '+':
23915      case '@':
23916      case '!':
23917        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
23918
23919        // all of those are literals inside a class, except that
23920        // the glob [!a] means [^a] in regexp
23921        if (inClass) {
23922          this.debug('  in class');
23923          if (c === '!' && i === classStart + 1) c = '^';
23924          re += c;
23925          continue
23926        }
23927
23928        // if we already have a stateChar, then it means
23929        // that there was something like ** or +? in there.
23930        // Handle the stateChar, then proceed with this one.
23931        self.debug('call clearStateChar %j', stateChar);
23932        clearStateChar();
23933        stateChar = c;
23934        // if extglob is disabled, then +(asdf|foo) isn't a thing.
23935        // just clear the statechar *now*, rather than even diving into
23936        // the patternList stuff.
23937        if (options.noext) clearStateChar();
23938      continue
23939
23940      case '(':
23941        if (inClass) {
23942          re += '(';
23943          continue
23944        }
23945
23946        if (!stateChar) {
23947          re += '\\(';
23948          continue
23949        }
23950
23951        patternListStack.push({
23952          type: stateChar,
23953          start: i - 1,
23954          reStart: re.length,
23955          open: plTypes[stateChar].open,
23956          close: plTypes[stateChar].close
23957        });
23958        // negation is (?:(?!js)[^/]*)
23959        re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
23960        this.debug('plType %j %j', stateChar, re);
23961        stateChar = false;
23962      continue
23963
23964      case ')':
23965        if (inClass || !patternListStack.length) {
23966          re += '\\)';
23967          continue
23968        }
23969
23970        clearStateChar();
23971        hasMagic = true;
23972        var pl = patternListStack.pop();
23973        // negation is (?:(?!js)[^/]*)
23974        // The others are (?:<pattern>)<type>
23975        re += pl.close;
23976        if (pl.type === '!') {
23977          negativeLists.push(pl);
23978        }
23979        pl.reEnd = re.length;
23980      continue
23981
23982      case '|':
23983        if (inClass || !patternListStack.length || escaping) {
23984          re += '\\|';
23985          escaping = false;
23986          continue
23987        }
23988
23989        clearStateChar();
23990        re += '|';
23991      continue
23992
23993      // these are mostly the same in regexp and glob
23994      case '[':
23995        // swallow any state-tracking char before the [
23996        clearStateChar();
23997
23998        if (inClass) {
23999          re += '\\' + c;
24000          continue
24001        }
24002
24003        inClass = true;
24004        classStart = i;
24005        reClassStart = re.length;
24006        re += c;
24007      continue
24008
24009      case ']':
24010        //  a right bracket shall lose its special
24011        //  meaning and represent itself in
24012        //  a bracket expression if it occurs
24013        //  first in the list.  -- POSIX.2 2.8.3.2
24014        if (i === classStart + 1 || !inClass) {
24015          re += '\\' + c;
24016          escaping = false;
24017          continue
24018        }
24019
24020        // handle the case where we left a class open.
24021        // "[z-a]" is valid, equivalent to "\[z-a\]"
24022        if (inClass) {
24023          // split where the last [ was, make sure we don't have
24024          // an invalid re. if so, re-walk the contents of the
24025          // would-be class to re-translate any characters that
24026          // were passed through as-is
24027          // TODO: It would probably be faster to determine this
24028          // without a try/catch and a new RegExp, but it's tricky
24029          // to do safely.  For now, this is safe and works.
24030          var cs = pattern.substring(classStart + 1, i);
24031          try {
24032            RegExp('[' + cs + ']');
24033          } catch (er) {
24034            // not a valid class!
24035            var sp = this.parse(cs, SUBPARSE);
24036            re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
24037            hasMagic = hasMagic || sp[1];
24038            inClass = false;
24039            continue
24040          }
24041        }
24042
24043        // finish up the class.
24044        hasMagic = true;
24045        inClass = false;
24046        re += c;
24047      continue
24048
24049      default:
24050        // swallow any state char that wasn't consumed
24051        clearStateChar();
24052
24053        if (escaping) {
24054          // no need
24055          escaping = false;
24056        } else if (reSpecials[c]
24057          && !(c === '^' && inClass)) {
24058          re += '\\';
24059        }
24060
24061        re += c;
24062
24063    } // switch
24064  } // for
24065
24066  // handle the case where we left a class open.
24067  // "[abc" is valid, equivalent to "\[abc"
24068  if (inClass) {
24069    // split where the last [ was, and escape it
24070    // this is a huge pita.  We now have to re-walk
24071    // the contents of the would-be class to re-translate
24072    // any characters that were passed through as-is
24073    cs = pattern.substr(classStart + 1);
24074    sp = this.parse(cs, SUBPARSE);
24075    re = re.substr(0, reClassStart) + '\\[' + sp[0];
24076    hasMagic = hasMagic || sp[1];
24077  }
24078
24079  // handle the case where we had a +( thing at the *end*
24080  // of the pattern.
24081  // each pattern list stack adds 3 chars, and we need to go through
24082  // and escape any | chars that were passed through as-is for the regexp.
24083  // Go through and escape them, taking care not to double-escape any
24084  // | chars that were already escaped.
24085  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
24086    var tail = re.slice(pl.reStart + pl.open.length);
24087    this.debug('setting tail', re, pl);
24088    // maybe some even number of \, then maybe 1 \, followed by a |
24089    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
24090      if (!$2) {
24091        // the | isn't already escaped, so escape it.
24092        $2 = '\\';
24093      }
24094
24095      // need to escape all those slashes *again*, without escaping the
24096      // one that we need for escaping the | character.  As it works out,
24097      // escaping an even number of slashes can be done by simply repeating
24098      // it exactly after itself.  That's why this trick works.
24099      //
24100      // I am sorry that you have to see this.
24101      return $1 + $1 + $2 + '|'
24102    });
24103
24104    this.debug('tail=%j\n   %s', tail, tail, pl, re);
24105    var t = pl.type === '*' ? star
24106      : pl.type === '?' ? qmark
24107      : '\\' + pl.type;
24108
24109    hasMagic = true;
24110    re = re.slice(0, pl.reStart) + t + '\\(' + tail;
24111  }
24112
24113  // handle trailing things that only matter at the very end.
24114  clearStateChar();
24115  if (escaping) {
24116    // trailing \\
24117    re += '\\\\';
24118  }
24119
24120  // only need to apply the nodot start if the re starts with
24121  // something that could conceivably capture a dot
24122  var addPatternStart = false;
24123  switch (re.charAt(0)) {
24124    case '.':
24125    case '[':
24126    case '(': addPatternStart = true;
24127  }
24128
24129  // Hack to work around lack of negative lookbehind in JS
24130  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
24131  // like 'a.xyz.yz' doesn't match.  So, the first negative
24132  // lookahead, has to look ALL the way ahead, to the end of
24133  // the pattern.
24134  for (var n = negativeLists.length - 1; n > -1; n--) {
24135    var nl = negativeLists[n];
24136
24137    var nlBefore = re.slice(0, nl.reStart);
24138    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
24139    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
24140    var nlAfter = re.slice(nl.reEnd);
24141
24142    nlLast += nlAfter;
24143
24144    // Handle nested stuff like *(*.js|!(*.json)), where open parens
24145    // mean that we should *not* include the ) in the bit that is considered
24146    // "after" the negated section.
24147    var openParensBefore = nlBefore.split('(').length - 1;
24148    var cleanAfter = nlAfter;
24149    for (i = 0; i < openParensBefore; i++) {
24150      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
24151    }
24152    nlAfter = cleanAfter;
24153
24154    var dollar = '';
24155    if (nlAfter === '' && isSub !== SUBPARSE) {
24156      dollar = '$';
24157    }
24158    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
24159    re = newRe;
24160  }
24161
24162  // if the re is not "" at this point, then we need to make sure
24163  // it doesn't match against an empty path part.
24164  // Otherwise a/* will match a/, which it should not.
24165  if (re !== '' && hasMagic) {
24166    re = '(?=.)' + re;
24167  }
24168
24169  if (addPatternStart) {
24170    re = patternStart + re;
24171  }
24172
24173  // parsing just a piece of a larger pattern.
24174  if (isSub === SUBPARSE) {
24175    return [re, hasMagic]
24176  }
24177
24178  // skip the regexp for non-magical patterns
24179  // unescape anything in it, though, so that it'll be
24180  // an exact match against a file etc.
24181  if (!hasMagic) {
24182    return globUnescape(pattern)
24183  }
24184
24185  var flags = options.nocase ? 'i' : '';
24186  try {
24187    var regExp = new RegExp('^' + re + '$', flags);
24188  } catch (er) {
24189    // If it was an invalid regular expression, then it can't match
24190    // anything.  This trick looks for a character after the end of
24191    // the string, which is of course impossible, except in multi-line
24192    // mode, but it's not a /m regex.
24193    return new RegExp('$.')
24194  }
24195
24196  regExp._glob = pattern;
24197  regExp._src = re;
24198
24199  return regExp
24200}
24201
24202minimatch$3.makeRe = function (pattern, options) {
24203  return new Minimatch$1(pattern, options || {}).makeRe()
24204};
24205
24206Minimatch$1.prototype.makeRe = makeRe;
24207function makeRe () {
24208  if (this.regexp || this.regexp === false) return this.regexp
24209
24210  // at this point, this.set is a 2d array of partial
24211  // pattern strings, or "**".
24212  //
24213  // It's better to use .match().  This function shouldn't
24214  // be used, really, but it's pretty convenient sometimes,
24215  // when you just want to work with a regex.
24216  var set = this.set;
24217
24218  if (!set.length) {
24219    this.regexp = false;
24220    return this.regexp
24221  }
24222  var options = this.options;
24223
24224  var twoStar = options.noglobstar ? star
24225    : options.dot ? twoStarDot
24226    : twoStarNoDot;
24227  var flags = options.nocase ? 'i' : '';
24228
24229  var re = set.map(function (pattern) {
24230    return pattern.map(function (p) {
24231      return (p === GLOBSTAR) ? twoStar
24232      : (typeof p === 'string') ? regExpEscape(p)
24233      : p._src
24234    }).join('\\\/')
24235  }).join('|');
24236
24237  // must match entire pattern
24238  // ending in a * or ** will make it less strict.
24239  re = '^(?:' + re + ')$';
24240
24241  // can match anything, as long as it's not this.
24242  if (this.negate) re = '^(?!' + re + ').*$';
24243
24244  try {
24245    this.regexp = new RegExp(re, flags);
24246  } catch (ex) {
24247    this.regexp = false;
24248  }
24249  return this.regexp
24250}
24251
24252minimatch$3.match = function (list, pattern, options) {
24253  options = options || {};
24254  var mm = new Minimatch$1(pattern, options);
24255  list = list.filter(function (f) {
24256    return mm.match(f)
24257  });
24258  if (mm.options.nonull && !list.length) {
24259    list.push(pattern);
24260  }
24261  return list
24262};
24263
24264Minimatch$1.prototype.match = match;
24265function match (f, partial) {
24266  this.debug('match', f, this.pattern);
24267  // short-circuit in the case of busted things.
24268  // comments, etc.
24269  if (this.comment) return false
24270  if (this.empty) return f === ''
24271
24272  if (f === '/' && partial) return true
24273
24274  var options = this.options;
24275
24276  // windows: need to use /, not \
24277  if (path$4.sep !== '/') {
24278    f = f.split(path$4.sep).join('/');
24279  }
24280
24281  // treat the test path as a set of pathparts.
24282  f = f.split(slashSplit);
24283  this.debug(this.pattern, 'split', f);
24284
24285  // just ONE of the pattern sets in this.set needs to match
24286  // in order for it to be valid.  If negating, then just one
24287  // match means that we have failed.
24288  // Either way, return on the first hit.
24289
24290  var set = this.set;
24291  this.debug(this.pattern, 'set', set);
24292
24293  // Find the basename of the path by looking for the last non-empty segment
24294  var filename;
24295  var i;
24296  for (i = f.length - 1; i >= 0; i--) {
24297    filename = f[i];
24298    if (filename) break
24299  }
24300
24301  for (i = 0; i < set.length; i++) {
24302    var pattern = set[i];
24303    var file = f;
24304    if (options.matchBase && pattern.length === 1) {
24305      file = [filename];
24306    }
24307    var hit = this.matchOne(file, pattern, partial);
24308    if (hit) {
24309      if (options.flipNegate) return true
24310      return !this.negate
24311    }
24312  }
24313
24314  // didn't get any hits.  this is success if it's a negative
24315  // pattern, failure otherwise.
24316  if (options.flipNegate) return false
24317  return this.negate
24318}
24319
24320// set partial to true to test if, for example,
24321// "/a/b" matches the start of "/*/b/*/d"
24322// Partial means, if you run out of file before you run
24323// out of pattern, then that's fine, as long as all
24324// the parts match.
24325Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
24326  var options = this.options;
24327
24328  this.debug('matchOne',
24329    { 'this': this, file: file, pattern: pattern });
24330
24331  this.debug('matchOne', file.length, pattern.length);
24332
24333  for (var fi = 0,
24334      pi = 0,
24335      fl = file.length,
24336      pl = pattern.length
24337      ; (fi < fl) && (pi < pl)
24338      ; fi++, pi++) {
24339    this.debug('matchOne loop');
24340    var p = pattern[pi];
24341    var f = file[fi];
24342
24343    this.debug(pattern, p, f);
24344
24345    // should be impossible.
24346    // some invalid regexp stuff in the set.
24347    if (p === false) return false
24348
24349    if (p === GLOBSTAR) {
24350      this.debug('GLOBSTAR', [pattern, p, f]);
24351
24352      // "**"
24353      // a/**/b/**/c would match the following:
24354      // a/b/x/y/z/c
24355      // a/x/y/z/b/c
24356      // a/b/x/b/x/c
24357      // a/b/c
24358      // To do this, take the rest of the pattern after
24359      // the **, and see if it would match the file remainder.
24360      // If so, return success.
24361      // If not, the ** "swallows" a segment, and try again.
24362      // This is recursively awful.
24363      //
24364      // a/**/b/**/c matching a/b/x/y/z/c
24365      // - a matches a
24366      // - doublestar
24367      //   - matchOne(b/x/y/z/c, b/**/c)
24368      //     - b matches b
24369      //     - doublestar
24370      //       - matchOne(x/y/z/c, c) -> no
24371      //       - matchOne(y/z/c, c) -> no
24372      //       - matchOne(z/c, c) -> no
24373      //       - matchOne(c, c) yes, hit
24374      var fr = fi;
24375      var pr = pi + 1;
24376      if (pr === pl) {
24377        this.debug('** at the end');
24378        // a ** at the end will just swallow the rest.
24379        // We have found a match.
24380        // however, it will not swallow /.x, unless
24381        // options.dot is set.
24382        // . and .. are *never* matched by **, for explosively
24383        // exponential reasons.
24384        for (; fi < fl; fi++) {
24385          if (file[fi] === '.' || file[fi] === '..' ||
24386            (!options.dot && file[fi].charAt(0) === '.')) return false
24387        }
24388        return true
24389      }
24390
24391      // ok, let's see if we can swallow whatever we can.
24392      while (fr < fl) {
24393        var swallowee = file[fr];
24394
24395        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
24396
24397        // XXX remove this slice.  Just pass the start index.
24398        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
24399          this.debug('globstar found match!', fr, fl, swallowee);
24400          // found a match.
24401          return true
24402        } else {
24403          // can't swallow "." or ".." ever.
24404          // can only swallow ".foo" when explicitly asked.
24405          if (swallowee === '.' || swallowee === '..' ||
24406            (!options.dot && swallowee.charAt(0) === '.')) {
24407            this.debug('dot detected!', file, fr, pattern, pr);
24408            break
24409          }
24410
24411          // ** swallows a segment, and continue.
24412          this.debug('globstar swallow a segment, and continue');
24413          fr++;
24414        }
24415      }
24416
24417      // no match was found.
24418      // However, in partial mode, we can't say this is necessarily over.
24419      // If there's more *pattern* left, then
24420      if (partial) {
24421        // ran out of file
24422        this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
24423        if (fr === fl) return true
24424      }
24425      return false
24426    }
24427
24428    // something other than **
24429    // non-magic patterns just have to match exactly
24430    // patterns with magic have been turned into regexps.
24431    var hit;
24432    if (typeof p === 'string') {
24433      if (options.nocase) {
24434        hit = f.toLowerCase() === p.toLowerCase();
24435      } else {
24436        hit = f === p;
24437      }
24438      this.debug('string match', p, f, hit);
24439    } else {
24440      hit = f.match(p);
24441      this.debug('pattern match', p, f, hit);
24442    }
24443
24444    if (!hit) return false
24445  }
24446
24447  // Note: ending in / means that we'll get a final ""
24448  // at the end of the pattern.  This can only match a
24449  // corresponding "" at the end of the file.
24450  // If the file ends in /, then it can only match a
24451  // a pattern that ends in /, unless the pattern just
24452  // doesn't have any more for it. But, a/b/ should *not*
24453  // match "a/b/*", even though "" matches against the
24454  // [^/]*? pattern, except in partial mode, where it might
24455  // simply not be reached yet.
24456  // However, a/b/ should still satisfy a/*
24457
24458  // now either we fell off the end of the pattern, or we're done.
24459  if (fi === fl && pi === pl) {
24460    // ran out of pattern and filename at the same time.
24461    // an exact hit!
24462    return true
24463  } else if (fi === fl) {
24464    // ran out of file, but still had pattern left.
24465    // this is ok if we're doing the match as part of
24466    // a glob fs traversal.
24467    return partial
24468  } else if (pi === pl) {
24469    // ran out of pattern, still have file left.
24470    // this is only acceptable if we're on the very last
24471    // empty segment of a file with a trailing slash.
24472    // a/* should match a/b/
24473    var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
24474    return emptyFileEnd
24475  }
24476
24477  // should be unreachable.
24478  throw new Error('wtf?')
24479};
24480
24481// replace stuff like \* with *
24482function globUnescape (s) {
24483  return s.replace(/\\(.)/g, '$1')
24484}
24485
24486function regExpEscape (s) {
24487  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
24488}
24489
24490var inherits$2 = {exports: {}};
24491
24492var inherits_browser = {exports: {}};
24493
24494if (typeof Object.create === 'function') {
24495  // implementation from standard node.js 'util' module
24496  inherits_browser.exports = function inherits(ctor, superCtor) {
24497    if (superCtor) {
24498      ctor.super_ = superCtor;
24499      ctor.prototype = Object.create(superCtor.prototype, {
24500        constructor: {
24501          value: ctor,
24502          enumerable: false,
24503          writable: true,
24504          configurable: true
24505        }
24506      });
24507    }
24508  };
24509} else {
24510  // old school shim for old browsers
24511  inherits_browser.exports = function inherits(ctor, superCtor) {
24512    if (superCtor) {
24513      ctor.super_ = superCtor;
24514      var TempCtor = function () {};
24515      TempCtor.prototype = superCtor.prototype;
24516      ctor.prototype = new TempCtor();
24517      ctor.prototype.constructor = ctor;
24518    }
24519  };
24520}
24521
24522try {
24523  var util$1 = require$$0$4;
24524  /* istanbul ignore next */
24525  if (typeof util$1.inherits !== 'function') throw '';
24526  inherits$2.exports = util$1.inherits;
24527} catch (e) {
24528  /* istanbul ignore next */
24529  inherits$2.exports = inherits_browser.exports;
24530}
24531
24532var pathIsAbsolute = {exports: {}};
24533
24534function posix(path) {
24535	return path.charAt(0) === '/';
24536}
24537
24538function win32(path) {
24539	// https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
24540	var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
24541	var result = splitDeviceRe.exec(path);
24542	var device = result[1] || '';
24543	var isUnc = Boolean(device && device.charAt(1) !== ':');
24544
24545	// UNC paths are always absolute
24546	return Boolean(result[2] || isUnc);
24547}
24548
24549pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix;
24550pathIsAbsolute.exports.posix = posix;
24551pathIsAbsolute.exports.win32 = win32;
24552
24553var common$2 = {};
24554
24555common$2.alphasort = alphasort;
24556common$2.alphasorti = alphasorti;
24557common$2.setopts = setopts$2;
24558common$2.ownProp = ownProp$2;
24559common$2.makeAbs = makeAbs;
24560common$2.finish = finish;
24561common$2.mark = mark;
24562common$2.isIgnored = isIgnored$2;
24563common$2.childrenIgnored = childrenIgnored$2;
24564
24565function ownProp$2 (obj, field) {
24566  return Object.prototype.hasOwnProperty.call(obj, field)
24567}
24568
24569var path$3 = path$b;
24570var minimatch$2 = minimatch_1;
24571var isAbsolute$2 = pathIsAbsolute.exports;
24572var Minimatch = minimatch$2.Minimatch;
24573
24574function alphasorti (a, b) {
24575  return a.toLowerCase().localeCompare(b.toLowerCase())
24576}
24577
24578function alphasort (a, b) {
24579  return a.localeCompare(b)
24580}
24581
24582function setupIgnores (self, options) {
24583  self.ignore = options.ignore || [];
24584
24585  if (!Array.isArray(self.ignore))
24586    self.ignore = [self.ignore];
24587
24588  if (self.ignore.length) {
24589    self.ignore = self.ignore.map(ignoreMap);
24590  }
24591}
24592
24593// ignore patterns are always in dot:true mode.
24594function ignoreMap (pattern) {
24595  var gmatcher = null;
24596  if (pattern.slice(-3) === '/**') {
24597    var gpattern = pattern.replace(/(\/\*\*)+$/, '');
24598    gmatcher = new Minimatch(gpattern, { dot: true });
24599  }
24600
24601  return {
24602    matcher: new Minimatch(pattern, { dot: true }),
24603    gmatcher: gmatcher
24604  }
24605}
24606
24607function setopts$2 (self, pattern, options) {
24608  if (!options)
24609    options = {};
24610
24611  // base-matching: just use globstar for that.
24612  if (options.matchBase && -1 === pattern.indexOf("/")) {
24613    if (options.noglobstar) {
24614      throw new Error("base matching requires globstar")
24615    }
24616    pattern = "**/" + pattern;
24617  }
24618
24619  self.silent = !!options.silent;
24620  self.pattern = pattern;
24621  self.strict = options.strict !== false;
24622  self.realpath = !!options.realpath;
24623  self.realpathCache = options.realpathCache || Object.create(null);
24624  self.follow = !!options.follow;
24625  self.dot = !!options.dot;
24626  self.mark = !!options.mark;
24627  self.nodir = !!options.nodir;
24628  if (self.nodir)
24629    self.mark = true;
24630  self.sync = !!options.sync;
24631  self.nounique = !!options.nounique;
24632  self.nonull = !!options.nonull;
24633  self.nosort = !!options.nosort;
24634  self.nocase = !!options.nocase;
24635  self.stat = !!options.stat;
24636  self.noprocess = !!options.noprocess;
24637  self.absolute = !!options.absolute;
24638
24639  self.maxLength = options.maxLength || Infinity;
24640  self.cache = options.cache || Object.create(null);
24641  self.statCache = options.statCache || Object.create(null);
24642  self.symlinks = options.symlinks || Object.create(null);
24643
24644  setupIgnores(self, options);
24645
24646  self.changedCwd = false;
24647  var cwd = process.cwd();
24648  if (!ownProp$2(options, "cwd"))
24649    self.cwd = cwd;
24650  else {
24651    self.cwd = path$3.resolve(options.cwd);
24652    self.changedCwd = self.cwd !== cwd;
24653  }
24654
24655  self.root = options.root || path$3.resolve(self.cwd, "/");
24656  self.root = path$3.resolve(self.root);
24657  if (process.platform === "win32")
24658    self.root = self.root.replace(/\\/g, "/");
24659
24660  // TODO: is an absolute `cwd` supposed to be resolved against `root`?
24661  // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
24662  self.cwdAbs = isAbsolute$2(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
24663  if (process.platform === "win32")
24664    self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
24665  self.nomount = !!options.nomount;
24666
24667  // disable comments and negation in Minimatch.
24668  // Note that they are not supported in Glob itself anyway.
24669  options.nonegate = true;
24670  options.nocomment = true;
24671
24672  self.minimatch = new Minimatch(pattern, options);
24673  self.options = self.minimatch.options;
24674}
24675
24676function finish (self) {
24677  var nou = self.nounique;
24678  var all = nou ? [] : Object.create(null);
24679
24680  for (var i = 0, l = self.matches.length; i < l; i ++) {
24681    var matches = self.matches[i];
24682    if (!matches || Object.keys(matches).length === 0) {
24683      if (self.nonull) {
24684        // do like the shell, and spit out the literal glob
24685        var literal = self.minimatch.globSet[i];
24686        if (nou)
24687          all.push(literal);
24688        else
24689          all[literal] = true;
24690      }
24691    } else {
24692      // had matches
24693      var m = Object.keys(matches);
24694      if (nou)
24695        all.push.apply(all, m);
24696      else
24697        m.forEach(function (m) {
24698          all[m] = true;
24699        });
24700    }
24701  }
24702
24703  if (!nou)
24704    all = Object.keys(all);
24705
24706  if (!self.nosort)
24707    all = all.sort(self.nocase ? alphasorti : alphasort);
24708
24709  // at *some* point we statted all of these
24710  if (self.mark) {
24711    for (var i = 0; i < all.length; i++) {
24712      all[i] = self._mark(all[i]);
24713    }
24714    if (self.nodir) {
24715      all = all.filter(function (e) {
24716        var notDir = !(/\/$/.test(e));
24717        var c = self.cache[e] || self.cache[makeAbs(self, e)];
24718        if (notDir && c)
24719          notDir = c !== 'DIR' && !Array.isArray(c);
24720        return notDir
24721      });
24722    }
24723  }
24724
24725  if (self.ignore.length)
24726    all = all.filter(function(m) {
24727      return !isIgnored$2(self, m)
24728    });
24729
24730  self.found = all;
24731}
24732
24733function mark (self, p) {
24734  var abs = makeAbs(self, p);
24735  var c = self.cache[abs];
24736  var m = p;
24737  if (c) {
24738    var isDir = c === 'DIR' || Array.isArray(c);
24739    var slash = p.slice(-1) === '/';
24740
24741    if (isDir && !slash)
24742      m += '/';
24743    else if (!isDir && slash)
24744      m = m.slice(0, -1);
24745
24746    if (m !== p) {
24747      var mabs = makeAbs(self, m);
24748      self.statCache[mabs] = self.statCache[abs];
24749      self.cache[mabs] = self.cache[abs];
24750    }
24751  }
24752
24753  return m
24754}
24755
24756// lotta situps...
24757function makeAbs (self, f) {
24758  var abs = f;
24759  if (f.charAt(0) === '/') {
24760    abs = path$3.join(self.root, f);
24761  } else if (isAbsolute$2(f) || f === '') {
24762    abs = f;
24763  } else if (self.changedCwd) {
24764    abs = path$3.resolve(self.cwd, f);
24765  } else {
24766    abs = path$3.resolve(f);
24767  }
24768
24769  if (process.platform === 'win32')
24770    abs = abs.replace(/\\/g, '/');
24771
24772  return abs
24773}
24774
24775
24776// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
24777// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
24778function isIgnored$2 (self, path) {
24779  if (!self.ignore.length)
24780    return false
24781
24782  return self.ignore.some(function(item) {
24783    return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
24784  })
24785}
24786
24787function childrenIgnored$2 (self, path) {
24788  if (!self.ignore.length)
24789    return false
24790
24791  return self.ignore.some(function(item) {
24792    return !!(item.gmatcher && item.gmatcher.match(path))
24793  })
24794}
24795
24796var sync$1 = globSync$1;
24797globSync$1.GlobSync = GlobSync$1;
24798
24799var fs$1 = require$$0$3;
24800var rp$1 = fs_realpath;
24801var minimatch$1 = minimatch_1;
24802var path$2 = path$b;
24803var assert$1 = assert$2;
24804var isAbsolute$1 = pathIsAbsolute.exports;
24805var common$1 = common$2;
24806common$1.alphasort;
24807common$1.alphasorti;
24808var setopts$1 = common$1.setopts;
24809var ownProp$1 = common$1.ownProp;
24810var childrenIgnored$1 = common$1.childrenIgnored;
24811var isIgnored$1 = common$1.isIgnored;
24812
24813function globSync$1 (pattern, options) {
24814  if (typeof options === 'function' || arguments.length === 3)
24815    throw new TypeError('callback provided to sync glob\n'+
24816                        'See: https://github.com/isaacs/node-glob/issues/167')
24817
24818  return new GlobSync$1(pattern, options).found
24819}
24820
24821function GlobSync$1 (pattern, options) {
24822  if (!pattern)
24823    throw new Error('must provide pattern')
24824
24825  if (typeof options === 'function' || arguments.length === 3)
24826    throw new TypeError('callback provided to sync glob\n'+
24827                        'See: https://github.com/isaacs/node-glob/issues/167')
24828
24829  if (!(this instanceof GlobSync$1))
24830    return new GlobSync$1(pattern, options)
24831
24832  setopts$1(this, pattern, options);
24833
24834  if (this.noprocess)
24835    return this
24836
24837  var n = this.minimatch.set.length;
24838  this.matches = new Array(n);
24839  for (var i = 0; i < n; i ++) {
24840    this._process(this.minimatch.set[i], i, false);
24841  }
24842  this._finish();
24843}
24844
24845GlobSync$1.prototype._finish = function () {
24846  assert$1(this instanceof GlobSync$1);
24847  if (this.realpath) {
24848    var self = this;
24849    this.matches.forEach(function (matchset, index) {
24850      var set = self.matches[index] = Object.create(null);
24851      for (var p in matchset) {
24852        try {
24853          p = self._makeAbs(p);
24854          var real = rp$1.realpathSync(p, self.realpathCache);
24855          set[real] = true;
24856        } catch (er) {
24857          if (er.syscall === 'stat')
24858            set[self._makeAbs(p)] = true;
24859          else
24860            throw er
24861        }
24862      }
24863    });
24864  }
24865  common$1.finish(this);
24866};
24867
24868
24869GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
24870  assert$1(this instanceof GlobSync$1);
24871
24872  // Get the first [n] parts of pattern that are all strings.
24873  var n = 0;
24874  while (typeof pattern[n] === 'string') {
24875    n ++;
24876  }
24877  // now n is the index of the first one that is *not* a string.
24878
24879  // See if there's anything else
24880  var prefix;
24881  switch (n) {
24882    // if not, then this is rather simple
24883    case pattern.length:
24884      this._processSimple(pattern.join('/'), index);
24885      return
24886
24887    case 0:
24888      // pattern *starts* with some non-trivial item.
24889      // going to readdir(cwd), but not include the prefix in matches.
24890      prefix = null;
24891      break
24892
24893    default:
24894      // pattern has some string bits in the front.
24895      // whatever it starts with, whether that's 'absolute' like /foo/bar,
24896      // or 'relative' like '../baz'
24897      prefix = pattern.slice(0, n).join('/');
24898      break
24899  }
24900
24901  var remain = pattern.slice(n);
24902
24903  // get the list of entries.
24904  var read;
24905  if (prefix === null)
24906    read = '.';
24907  else if (isAbsolute$1(prefix) || isAbsolute$1(pattern.join('/'))) {
24908    if (!prefix || !isAbsolute$1(prefix))
24909      prefix = '/' + prefix;
24910    read = prefix;
24911  } else
24912    read = prefix;
24913
24914  var abs = this._makeAbs(read);
24915
24916  //if ignored, skip processing
24917  if (childrenIgnored$1(this, read))
24918    return
24919
24920  var isGlobStar = remain[0] === minimatch$1.GLOBSTAR;
24921  if (isGlobStar)
24922    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
24923  else
24924    this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
24925};
24926
24927
24928GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
24929  var entries = this._readdir(abs, inGlobStar);
24930
24931  // if the abs isn't a dir, then nothing can match!
24932  if (!entries)
24933    return
24934
24935  // It will only match dot entries if it starts with a dot, or if
24936  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
24937  var pn = remain[0];
24938  var negate = !!this.minimatch.negate;
24939  var rawGlob = pn._glob;
24940  var dotOk = this.dot || rawGlob.charAt(0) === '.';
24941
24942  var matchedEntries = [];
24943  for (var i = 0; i < entries.length; i++) {
24944    var e = entries[i];
24945    if (e.charAt(0) !== '.' || dotOk) {
24946      var m;
24947      if (negate && !prefix) {
24948        m = !e.match(pn);
24949      } else {
24950        m = e.match(pn);
24951      }
24952      if (m)
24953        matchedEntries.push(e);
24954    }
24955  }
24956
24957  var len = matchedEntries.length;
24958  // If there are no matched entries, then nothing matches.
24959  if (len === 0)
24960    return
24961
24962  // if this is the last remaining pattern bit, then no need for
24963  // an additional stat *unless* the user has specified mark or
24964  // stat explicitly.  We know they exist, since readdir returned
24965  // them.
24966
24967  if (remain.length === 1 && !this.mark && !this.stat) {
24968    if (!this.matches[index])
24969      this.matches[index] = Object.create(null);
24970
24971    for (var i = 0; i < len; i ++) {
24972      var e = matchedEntries[i];
24973      if (prefix) {
24974        if (prefix.slice(-1) !== '/')
24975          e = prefix + '/' + e;
24976        else
24977          e = prefix + e;
24978      }
24979
24980      if (e.charAt(0) === '/' && !this.nomount) {
24981        e = path$2.join(this.root, e);
24982      }
24983      this._emitMatch(index, e);
24984    }
24985    // This was the last one, and no stats were needed
24986    return
24987  }
24988
24989  // now test all matched entries as stand-ins for that part
24990  // of the pattern.
24991  remain.shift();
24992  for (var i = 0; i < len; i ++) {
24993    var e = matchedEntries[i];
24994    var newPattern;
24995    if (prefix)
24996      newPattern = [prefix, e];
24997    else
24998      newPattern = [e];
24999    this._process(newPattern.concat(remain), index, inGlobStar);
25000  }
25001};
25002
25003
25004GlobSync$1.prototype._emitMatch = function (index, e) {
25005  if (isIgnored$1(this, e))
25006    return
25007
25008  var abs = this._makeAbs(e);
25009
25010  if (this.mark)
25011    e = this._mark(e);
25012
25013  if (this.absolute) {
25014    e = abs;
25015  }
25016
25017  if (this.matches[index][e])
25018    return
25019
25020  if (this.nodir) {
25021    var c = this.cache[abs];
25022    if (c === 'DIR' || Array.isArray(c))
25023      return
25024  }
25025
25026  this.matches[index][e] = true;
25027
25028  if (this.stat)
25029    this._stat(e);
25030};
25031
25032
25033GlobSync$1.prototype._readdirInGlobStar = function (abs) {
25034  // follow all symlinked directories forever
25035  // just proceed as if this is a non-globstar situation
25036  if (this.follow)
25037    return this._readdir(abs, false)
25038
25039  var entries;
25040  var lstat;
25041  try {
25042    lstat = fs$1.lstatSync(abs);
25043  } catch (er) {
25044    if (er.code === 'ENOENT') {
25045      // lstat failed, doesn't exist
25046      return null
25047    }
25048  }
25049
25050  var isSym = lstat && lstat.isSymbolicLink();
25051  this.symlinks[abs] = isSym;
25052
25053  // If it's not a symlink or a dir, then it's definitely a regular file.
25054  // don't bother doing a readdir in that case.
25055  if (!isSym && lstat && !lstat.isDirectory())
25056    this.cache[abs] = 'FILE';
25057  else
25058    entries = this._readdir(abs, false);
25059
25060  return entries
25061};
25062
25063GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
25064
25065  if (inGlobStar && !ownProp$1(this.symlinks, abs))
25066    return this._readdirInGlobStar(abs)
25067
25068  if (ownProp$1(this.cache, abs)) {
25069    var c = this.cache[abs];
25070    if (!c || c === 'FILE')
25071      return null
25072
25073    if (Array.isArray(c))
25074      return c
25075  }
25076
25077  try {
25078    return this._readdirEntries(abs, fs$1.readdirSync(abs))
25079  } catch (er) {
25080    this._readdirError(abs, er);
25081    return null
25082  }
25083};
25084
25085GlobSync$1.prototype._readdirEntries = function (abs, entries) {
25086  // if we haven't asked to stat everything, then just
25087  // assume that everything in there exists, so we can avoid
25088  // having to stat it a second time.
25089  if (!this.mark && !this.stat) {
25090    for (var i = 0; i < entries.length; i ++) {
25091      var e = entries[i];
25092      if (abs === '/')
25093        e = abs + e;
25094      else
25095        e = abs + '/' + e;
25096      this.cache[e] = true;
25097    }
25098  }
25099
25100  this.cache[abs] = entries;
25101
25102  // mark and cache dir-ness
25103  return entries
25104};
25105
25106GlobSync$1.prototype._readdirError = function (f, er) {
25107  // handle errors, and cache the information
25108  switch (er.code) {
25109    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
25110    case 'ENOTDIR': // totally normal. means it *does* exist.
25111      var abs = this._makeAbs(f);
25112      this.cache[abs] = 'FILE';
25113      if (abs === this.cwdAbs) {
25114        var error = new Error(er.code + ' invalid cwd ' + this.cwd);
25115        error.path = this.cwd;
25116        error.code = er.code;
25117        throw error
25118      }
25119      break
25120
25121    case 'ENOENT': // not terribly unusual
25122    case 'ELOOP':
25123    case 'ENAMETOOLONG':
25124    case 'UNKNOWN':
25125      this.cache[this._makeAbs(f)] = false;
25126      break
25127
25128    default: // some unusual error.  Treat as failure.
25129      this.cache[this._makeAbs(f)] = false;
25130      if (this.strict)
25131        throw er
25132      if (!this.silent)
25133        console.error('glob error', er);
25134      break
25135  }
25136};
25137
25138GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
25139
25140  var entries = this._readdir(abs, inGlobStar);
25141
25142  // no entries means not a dir, so it can never have matches
25143  // foo.txt/** doesn't match foo.txt
25144  if (!entries)
25145    return
25146
25147  // test without the globstar, and with every child both below
25148  // and replacing the globstar.
25149  var remainWithoutGlobStar = remain.slice(1);
25150  var gspref = prefix ? [ prefix ] : [];
25151  var noGlobStar = gspref.concat(remainWithoutGlobStar);
25152
25153  // the noGlobStar pattern exits the inGlobStar state
25154  this._process(noGlobStar, index, false);
25155
25156  var len = entries.length;
25157  var isSym = this.symlinks[abs];
25158
25159  // If it's a symlink, and we're in a globstar, then stop
25160  if (isSym && inGlobStar)
25161    return
25162
25163  for (var i = 0; i < len; i++) {
25164    var e = entries[i];
25165    if (e.charAt(0) === '.' && !this.dot)
25166      continue
25167
25168    // these two cases enter the inGlobStar state
25169    var instead = gspref.concat(entries[i], remainWithoutGlobStar);
25170    this._process(instead, index, true);
25171
25172    var below = gspref.concat(entries[i], remain);
25173    this._process(below, index, true);
25174  }
25175};
25176
25177GlobSync$1.prototype._processSimple = function (prefix, index) {
25178  // XXX review this.  Shouldn't it be doing the mounting etc
25179  // before doing stat?  kinda weird?
25180  var exists = this._stat(prefix);
25181
25182  if (!this.matches[index])
25183    this.matches[index] = Object.create(null);
25184
25185  // If it doesn't exist, then just mark the lack of results
25186  if (!exists)
25187    return
25188
25189  if (prefix && isAbsolute$1(prefix) && !this.nomount) {
25190    var trail = /[\/\\]$/.test(prefix);
25191    if (prefix.charAt(0) === '/') {
25192      prefix = path$2.join(this.root, prefix);
25193    } else {
25194      prefix = path$2.resolve(this.root, prefix);
25195      if (trail)
25196        prefix += '/';
25197    }
25198  }
25199
25200  if (process.platform === 'win32')
25201    prefix = prefix.replace(/\\/g, '/');
25202
25203  // Mark this as a match
25204  this._emitMatch(index, prefix);
25205};
25206
25207// Returns either 'DIR', 'FILE', or false
25208GlobSync$1.prototype._stat = function (f) {
25209  var abs = this._makeAbs(f);
25210  var needDir = f.slice(-1) === '/';
25211
25212  if (f.length > this.maxLength)
25213    return false
25214
25215  if (!this.stat && ownProp$1(this.cache, abs)) {
25216    var c = this.cache[abs];
25217
25218    if (Array.isArray(c))
25219      c = 'DIR';
25220
25221    // It exists, but maybe not how we need it
25222    if (!needDir || c === 'DIR')
25223      return c
25224
25225    if (needDir && c === 'FILE')
25226      return false
25227
25228    // otherwise we have to stat, because maybe c=true
25229    // if we know it exists, but not what it is.
25230  }
25231  var stat = this.statCache[abs];
25232  if (!stat) {
25233    var lstat;
25234    try {
25235      lstat = fs$1.lstatSync(abs);
25236    } catch (er) {
25237      if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
25238        this.statCache[abs] = false;
25239        return false
25240      }
25241    }
25242
25243    if (lstat && lstat.isSymbolicLink()) {
25244      try {
25245        stat = fs$1.statSync(abs);
25246      } catch (er) {
25247        stat = lstat;
25248      }
25249    } else {
25250      stat = lstat;
25251    }
25252  }
25253
25254  this.statCache[abs] = stat;
25255
25256  var c = true;
25257  if (stat)
25258    c = stat.isDirectory() ? 'DIR' : 'FILE';
25259
25260  this.cache[abs] = this.cache[abs] || c;
25261
25262  if (needDir && c === 'FILE')
25263    return false
25264
25265  return c
25266};
25267
25268GlobSync$1.prototype._mark = function (p) {
25269  return common$1.mark(this, p)
25270};
25271
25272GlobSync$1.prototype._makeAbs = function (f) {
25273  return common$1.makeAbs(this, f)
25274};
25275
25276// Returns a wrapper function that returns a wrapped callback
25277// The wrapper function should do some stuff, and return a
25278// presumably different callback function.
25279// This makes sure that own properties are retained, so that
25280// decorations and such are not lost along the way.
25281var wrappy_1 = wrappy$2;
25282function wrappy$2 (fn, cb) {
25283  if (fn && cb) return wrappy$2(fn)(cb)
25284
25285  if (typeof fn !== 'function')
25286    throw new TypeError('need wrapper function')
25287
25288  Object.keys(fn).forEach(function (k) {
25289    wrapper[k] = fn[k];
25290  });
25291
25292  return wrapper
25293
25294  function wrapper() {
25295    var args = new Array(arguments.length);
25296    for (var i = 0; i < args.length; i++) {
25297      args[i] = arguments[i];
25298    }
25299    var ret = fn.apply(this, args);
25300    var cb = args[args.length-1];
25301    if (typeof ret === 'function' && ret !== cb) {
25302      Object.keys(cb).forEach(function (k) {
25303        ret[k] = cb[k];
25304      });
25305    }
25306    return ret
25307  }
25308}
25309
25310var once$3 = {exports: {}};
25311
25312var wrappy$1 = wrappy_1;
25313once$3.exports = wrappy$1(once$2);
25314once$3.exports.strict = wrappy$1(onceStrict);
25315
25316once$2.proto = once$2(function () {
25317  Object.defineProperty(Function.prototype, 'once', {
25318    value: function () {
25319      return once$2(this)
25320    },
25321    configurable: true
25322  });
25323
25324  Object.defineProperty(Function.prototype, 'onceStrict', {
25325    value: function () {
25326      return onceStrict(this)
25327    },
25328    configurable: true
25329  });
25330});
25331
25332function once$2 (fn) {
25333  var f = function () {
25334    if (f.called) return f.value
25335    f.called = true;
25336    return f.value = fn.apply(this, arguments)
25337  };
25338  f.called = false;
25339  return f
25340}
25341
25342function onceStrict (fn) {
25343  var f = function () {
25344    if (f.called)
25345      throw new Error(f.onceError)
25346    f.called = true;
25347    return f.value = fn.apply(this, arguments)
25348  };
25349  var name = fn.name || 'Function wrapped with `once`';
25350  f.onceError = name + " shouldn't be called more than once";
25351  f.called = false;
25352  return f
25353}
25354
25355var wrappy = wrappy_1;
25356var reqs = Object.create(null);
25357var once$1 = once$3.exports;
25358
25359var inflight_1 = wrappy(inflight$1);
25360
25361function inflight$1 (key, cb) {
25362  if (reqs[key]) {
25363    reqs[key].push(cb);
25364    return null
25365  } else {
25366    reqs[key] = [cb];
25367    return makeres(key)
25368  }
25369}
25370
25371function makeres (key) {
25372  return once$1(function RES () {
25373    var cbs = reqs[key];
25374    var len = cbs.length;
25375    var args = slice$1(arguments);
25376
25377    // XXX It's somewhat ambiguous whether a new callback added in this
25378    // pass should be queued for later execution if something in the
25379    // list of callbacks throws, or if it should just be discarded.
25380    // However, it's such an edge case that it hardly matters, and either
25381    // choice is likely as surprising as the other.
25382    // As it happens, we do go ahead and schedule it for later execution.
25383    try {
25384      for (var i = 0; i < len; i++) {
25385        cbs[i].apply(null, args);
25386      }
25387    } finally {
25388      if (cbs.length > len) {
25389        // added more in the interim.
25390        // de-zalgo, just in case, but don't call again.
25391        cbs.splice(0, len);
25392        process.nextTick(function () {
25393          RES.apply(null, args);
25394        });
25395      } else {
25396        delete reqs[key];
25397      }
25398    }
25399  })
25400}
25401
25402function slice$1 (args) {
25403  var length = args.length;
25404  var array = [];
25405
25406  for (var i = 0; i < length; i++) array[i] = args[i];
25407  return array
25408}
25409
25410// Approach:
25411//
25412// 1. Get the minimatch set
25413// 2. For each pattern in the set, PROCESS(pattern, false)
25414// 3. Store matches per-set, then uniq them
25415//
25416// PROCESS(pattern, inGlobStar)
25417// Get the first [n] items from pattern that are all strings
25418// Join these together.  This is PREFIX.
25419//   If there is no more remaining, then stat(PREFIX) and
25420//   add to matches if it succeeds.  END.
25421//
25422// If inGlobStar and PREFIX is symlink and points to dir
25423//   set ENTRIES = []
25424// else readdir(PREFIX) as ENTRIES
25425//   If fail, END
25426//
25427// with ENTRIES
25428//   If pattern[n] is GLOBSTAR
25429//     // handle the case where the globstar match is empty
25430//     // by pruning it out, and testing the resulting pattern
25431//     PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
25432//     // handle other cases.
25433//     for ENTRY in ENTRIES (not dotfiles)
25434//       // attach globstar + tail onto the entry
25435//       // Mark that this entry is a globstar match
25436//       PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
25437//
25438//   else // not globstar
25439//     for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
25440//       Test ENTRY against pattern[n]
25441//       If fails, continue
25442//       If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
25443//
25444// Caveat:
25445//   Cache all stats and readdirs results to minimize syscall.  Since all
25446//   we ever care about is existence and directory-ness, we can just keep
25447//   `true` for files, and [children,...] for directories, or `false` for
25448//   things that don't exist.
25449
25450var glob_1 = glob;
25451
25452var fs = require$$0$3;
25453var rp = fs_realpath;
25454var minimatch = minimatch_1;
25455var inherits$1 = inherits$2.exports;
25456var EE = require$$0$5.EventEmitter;
25457var path$1 = path$b;
25458var assert = assert$2;
25459var isAbsolute = pathIsAbsolute.exports;
25460var globSync = sync$1;
25461var common = common$2;
25462common.alphasort;
25463common.alphasorti;
25464var setopts = common.setopts;
25465var ownProp = common.ownProp;
25466var inflight = inflight_1;
25467var childrenIgnored = common.childrenIgnored;
25468var isIgnored = common.isIgnored;
25469
25470var once = once$3.exports;
25471
25472function glob (pattern, options, cb) {
25473  if (typeof options === 'function') cb = options, options = {};
25474  if (!options) options = {};
25475
25476  if (options.sync) {
25477    if (cb)
25478      throw new TypeError('callback provided to sync glob')
25479    return globSync(pattern, options)
25480  }
25481
25482  return new Glob(pattern, options, cb)
25483}
25484
25485glob.sync = globSync;
25486var GlobSync = glob.GlobSync = globSync.GlobSync;
25487
25488// old api surface
25489glob.glob = glob;
25490
25491function extend$1 (origin, add) {
25492  if (add === null || typeof add !== 'object') {
25493    return origin
25494  }
25495
25496  var keys = Object.keys(add);
25497  var i = keys.length;
25498  while (i--) {
25499    origin[keys[i]] = add[keys[i]];
25500  }
25501  return origin
25502}
25503
25504glob.hasMagic = function (pattern, options_) {
25505  var options = extend$1({}, options_);
25506  options.noprocess = true;
25507
25508  var g = new Glob(pattern, options);
25509  var set = g.minimatch.set;
25510
25511  if (!pattern)
25512    return false
25513
25514  if (set.length > 1)
25515    return true
25516
25517  for (var j = 0; j < set[0].length; j++) {
25518    if (typeof set[0][j] !== 'string')
25519      return true
25520  }
25521
25522  return false
25523};
25524
25525glob.Glob = Glob;
25526inherits$1(Glob, EE);
25527function Glob (pattern, options, cb) {
25528  if (typeof options === 'function') {
25529    cb = options;
25530    options = null;
25531  }
25532
25533  if (options && options.sync) {
25534    if (cb)
25535      throw new TypeError('callback provided to sync glob')
25536    return new GlobSync(pattern, options)
25537  }
25538
25539  if (!(this instanceof Glob))
25540    return new Glob(pattern, options, cb)
25541
25542  setopts(this, pattern, options);
25543  this._didRealPath = false;
25544
25545  // process each pattern in the minimatch set
25546  var n = this.minimatch.set.length;
25547
25548  // The matches are stored as {<filename>: true,...} so that
25549  // duplicates are automagically pruned.
25550  // Later, we do an Object.keys() on these.
25551  // Keep them as a list so we can fill in when nonull is set.
25552  this.matches = new Array(n);
25553
25554  if (typeof cb === 'function') {
25555    cb = once(cb);
25556    this.on('error', cb);
25557    this.on('end', function (matches) {
25558      cb(null, matches);
25559    });
25560  }
25561
25562  var self = this;
25563  this._processing = 0;
25564
25565  this._emitQueue = [];
25566  this._processQueue = [];
25567  this.paused = false;
25568
25569  if (this.noprocess)
25570    return this
25571
25572  if (n === 0)
25573    return done()
25574
25575  var sync = true;
25576  for (var i = 0; i < n; i ++) {
25577    this._process(this.minimatch.set[i], i, false, done);
25578  }
25579  sync = false;
25580
25581  function done () {
25582    --self._processing;
25583    if (self._processing <= 0) {
25584      if (sync) {
25585        process.nextTick(function () {
25586          self._finish();
25587        });
25588      } else {
25589        self._finish();
25590      }
25591    }
25592  }
25593}
25594
25595Glob.prototype._finish = function () {
25596  assert(this instanceof Glob);
25597  if (this.aborted)
25598    return
25599
25600  if (this.realpath && !this._didRealpath)
25601    return this._realpath()
25602
25603  common.finish(this);
25604  this.emit('end', this.found);
25605};
25606
25607Glob.prototype._realpath = function () {
25608  if (this._didRealpath)
25609    return
25610
25611  this._didRealpath = true;
25612
25613  var n = this.matches.length;
25614  if (n === 0)
25615    return this._finish()
25616
25617  var self = this;
25618  for (var i = 0; i < this.matches.length; i++)
25619    this._realpathSet(i, next);
25620
25621  function next () {
25622    if (--n === 0)
25623      self._finish();
25624  }
25625};
25626
25627Glob.prototype._realpathSet = function (index, cb) {
25628  var matchset = this.matches[index];
25629  if (!matchset)
25630    return cb()
25631
25632  var found = Object.keys(matchset);
25633  var self = this;
25634  var n = found.length;
25635
25636  if (n === 0)
25637    return cb()
25638
25639  var set = this.matches[index] = Object.create(null);
25640  found.forEach(function (p, i) {
25641    // If there's a problem with the stat, then it means that
25642    // one or more of the links in the realpath couldn't be
25643    // resolved.  just return the abs value in that case.
25644    p = self._makeAbs(p);
25645    rp.realpath(p, self.realpathCache, function (er, real) {
25646      if (!er)
25647        set[real] = true;
25648      else if (er.syscall === 'stat')
25649        set[p] = true;
25650      else
25651        self.emit('error', er); // srsly wtf right here
25652
25653      if (--n === 0) {
25654        self.matches[index] = set;
25655        cb();
25656      }
25657    });
25658  });
25659};
25660
25661Glob.prototype._mark = function (p) {
25662  return common.mark(this, p)
25663};
25664
25665Glob.prototype._makeAbs = function (f) {
25666  return common.makeAbs(this, f)
25667};
25668
25669Glob.prototype.abort = function () {
25670  this.aborted = true;
25671  this.emit('abort');
25672};
25673
25674Glob.prototype.pause = function () {
25675  if (!this.paused) {
25676    this.paused = true;
25677    this.emit('pause');
25678  }
25679};
25680
25681Glob.prototype.resume = function () {
25682  if (this.paused) {
25683    this.emit('resume');
25684    this.paused = false;
25685    if (this._emitQueue.length) {
25686      var eq = this._emitQueue.slice(0);
25687      this._emitQueue.length = 0;
25688      for (var i = 0; i < eq.length; i ++) {
25689        var e = eq[i];
25690        this._emitMatch(e[0], e[1]);
25691      }
25692    }
25693    if (this._processQueue.length) {
25694      var pq = this._processQueue.slice(0);
25695      this._processQueue.length = 0;
25696      for (var i = 0; i < pq.length; i ++) {
25697        var p = pq[i];
25698        this._processing--;
25699        this._process(p[0], p[1], p[2], p[3]);
25700      }
25701    }
25702  }
25703};
25704
25705Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
25706  assert(this instanceof Glob);
25707  assert(typeof cb === 'function');
25708
25709  if (this.aborted)
25710    return
25711
25712  this._processing++;
25713  if (this.paused) {
25714    this._processQueue.push([pattern, index, inGlobStar, cb]);
25715    return
25716  }
25717
25718  //console.error('PROCESS %d', this._processing, pattern)
25719
25720  // Get the first [n] parts of pattern that are all strings.
25721  var n = 0;
25722  while (typeof pattern[n] === 'string') {
25723    n ++;
25724  }
25725  // now n is the index of the first one that is *not* a string.
25726
25727  // see if there's anything else
25728  var prefix;
25729  switch (n) {
25730    // if not, then this is rather simple
25731    case pattern.length:
25732      this._processSimple(pattern.join('/'), index, cb);
25733      return
25734
25735    case 0:
25736      // pattern *starts* with some non-trivial item.
25737      // going to readdir(cwd), but not include the prefix in matches.
25738      prefix = null;
25739      break
25740
25741    default:
25742      // pattern has some string bits in the front.
25743      // whatever it starts with, whether that's 'absolute' like /foo/bar,
25744      // or 'relative' like '../baz'
25745      prefix = pattern.slice(0, n).join('/');
25746      break
25747  }
25748
25749  var remain = pattern.slice(n);
25750
25751  // get the list of entries.
25752  var read;
25753  if (prefix === null)
25754    read = '.';
25755  else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
25756    if (!prefix || !isAbsolute(prefix))
25757      prefix = '/' + prefix;
25758    read = prefix;
25759  } else
25760    read = prefix;
25761
25762  var abs = this._makeAbs(read);
25763
25764  //if ignored, skip _processing
25765  if (childrenIgnored(this, read))
25766    return cb()
25767
25768  var isGlobStar = remain[0] === minimatch.GLOBSTAR;
25769  if (isGlobStar)
25770    this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
25771  else
25772    this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
25773};
25774
25775Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
25776  var self = this;
25777  this._readdir(abs, inGlobStar, function (er, entries) {
25778    return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
25779  });
25780};
25781
25782Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
25783
25784  // if the abs isn't a dir, then nothing can match!
25785  if (!entries)
25786    return cb()
25787
25788  // It will only match dot entries if it starts with a dot, or if
25789  // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
25790  var pn = remain[0];
25791  var negate = !!this.minimatch.negate;
25792  var rawGlob = pn._glob;
25793  var dotOk = this.dot || rawGlob.charAt(0) === '.';
25794
25795  var matchedEntries = [];
25796  for (var i = 0; i < entries.length; i++) {
25797    var e = entries[i];
25798    if (e.charAt(0) !== '.' || dotOk) {
25799      var m;
25800      if (negate && !prefix) {
25801        m = !e.match(pn);
25802      } else {
25803        m = e.match(pn);
25804      }
25805      if (m)
25806        matchedEntries.push(e);
25807    }
25808  }
25809
25810  //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
25811
25812  var len = matchedEntries.length;
25813  // If there are no matched entries, then nothing matches.
25814  if (len === 0)
25815    return cb()
25816
25817  // if this is the last remaining pattern bit, then no need for
25818  // an additional stat *unless* the user has specified mark or
25819  // stat explicitly.  We know they exist, since readdir returned
25820  // them.
25821
25822  if (remain.length === 1 && !this.mark && !this.stat) {
25823    if (!this.matches[index])
25824      this.matches[index] = Object.create(null);
25825
25826    for (var i = 0; i < len; i ++) {
25827      var e = matchedEntries[i];
25828      if (prefix) {
25829        if (prefix !== '/')
25830          e = prefix + '/' + e;
25831        else
25832          e = prefix + e;
25833      }
25834
25835      if (e.charAt(0) === '/' && !this.nomount) {
25836        e = path$1.join(this.root, e);
25837      }
25838      this._emitMatch(index, e);
25839    }
25840    // This was the last one, and no stats were needed
25841    return cb()
25842  }
25843
25844  // now test all matched entries as stand-ins for that part
25845  // of the pattern.
25846  remain.shift();
25847  for (var i = 0; i < len; i ++) {
25848    var e = matchedEntries[i];
25849    if (prefix) {
25850      if (prefix !== '/')
25851        e = prefix + '/' + e;
25852      else
25853        e = prefix + e;
25854    }
25855    this._process([e].concat(remain), index, inGlobStar, cb);
25856  }
25857  cb();
25858};
25859
25860Glob.prototype._emitMatch = function (index, e) {
25861  if (this.aborted)
25862    return
25863
25864  if (isIgnored(this, e))
25865    return
25866
25867  if (this.paused) {
25868    this._emitQueue.push([index, e]);
25869    return
25870  }
25871
25872  var abs = isAbsolute(e) ? e : this._makeAbs(e);
25873
25874  if (this.mark)
25875    e = this._mark(e);
25876
25877  if (this.absolute)
25878    e = abs;
25879
25880  if (this.matches[index][e])
25881    return
25882
25883  if (this.nodir) {
25884    var c = this.cache[abs];
25885    if (c === 'DIR' || Array.isArray(c))
25886      return
25887  }
25888
25889  this.matches[index][e] = true;
25890
25891  var st = this.statCache[abs];
25892  if (st)
25893    this.emit('stat', e, st);
25894
25895  this.emit('match', e);
25896};
25897
25898Glob.prototype._readdirInGlobStar = function (abs, cb) {
25899  if (this.aborted)
25900    return
25901
25902  // follow all symlinked directories forever
25903  // just proceed as if this is a non-globstar situation
25904  if (this.follow)
25905    return this._readdir(abs, false, cb)
25906
25907  var lstatkey = 'lstat\0' + abs;
25908  var self = this;
25909  var lstatcb = inflight(lstatkey, lstatcb_);
25910
25911  if (lstatcb)
25912    fs.lstat(abs, lstatcb);
25913
25914  function lstatcb_ (er, lstat) {
25915    if (er && er.code === 'ENOENT')
25916      return cb()
25917
25918    var isSym = lstat && lstat.isSymbolicLink();
25919    self.symlinks[abs] = isSym;
25920
25921    // If it's not a symlink or a dir, then it's definitely a regular file.
25922    // don't bother doing a readdir in that case.
25923    if (!isSym && lstat && !lstat.isDirectory()) {
25924      self.cache[abs] = 'FILE';
25925      cb();
25926    } else
25927      self._readdir(abs, false, cb);
25928  }
25929};
25930
25931Glob.prototype._readdir = function (abs, inGlobStar, cb) {
25932  if (this.aborted)
25933    return
25934
25935  cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
25936  if (!cb)
25937    return
25938
25939  //console.error('RD %j %j', +inGlobStar, abs)
25940  if (inGlobStar && !ownProp(this.symlinks, abs))
25941    return this._readdirInGlobStar(abs, cb)
25942
25943  if (ownProp(this.cache, abs)) {
25944    var c = this.cache[abs];
25945    if (!c || c === 'FILE')
25946      return cb()
25947
25948    if (Array.isArray(c))
25949      return cb(null, c)
25950  }
25951  fs.readdir(abs, readdirCb(this, abs, cb));
25952};
25953
25954function readdirCb (self, abs, cb) {
25955  return function (er, entries) {
25956    if (er)
25957      self._readdirError(abs, er, cb);
25958    else
25959      self._readdirEntries(abs, entries, cb);
25960  }
25961}
25962
25963Glob.prototype._readdirEntries = function (abs, entries, cb) {
25964  if (this.aborted)
25965    return
25966
25967  // if we haven't asked to stat everything, then just
25968  // assume that everything in there exists, so we can avoid
25969  // having to stat it a second time.
25970  if (!this.mark && !this.stat) {
25971    for (var i = 0; i < entries.length; i ++) {
25972      var e = entries[i];
25973      if (abs === '/')
25974        e = abs + e;
25975      else
25976        e = abs + '/' + e;
25977      this.cache[e] = true;
25978    }
25979  }
25980
25981  this.cache[abs] = entries;
25982  return cb(null, entries)
25983};
25984
25985Glob.prototype._readdirError = function (f, er, cb) {
25986  if (this.aborted)
25987    return
25988
25989  // handle errors, and cache the information
25990  switch (er.code) {
25991    case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
25992    case 'ENOTDIR': // totally normal. means it *does* exist.
25993      var abs = this._makeAbs(f);
25994      this.cache[abs] = 'FILE';
25995      if (abs === this.cwdAbs) {
25996        var error = new Error(er.code + ' invalid cwd ' + this.cwd);
25997        error.path = this.cwd;
25998        error.code = er.code;
25999        this.emit('error', error);
26000        this.abort();
26001      }
26002      break
26003
26004    case 'ENOENT': // not terribly unusual
26005    case 'ELOOP':
26006    case 'ENAMETOOLONG':
26007    case 'UNKNOWN':
26008      this.cache[this._makeAbs(f)] = false;
26009      break
26010
26011    default: // some unusual error.  Treat as failure.
26012      this.cache[this._makeAbs(f)] = false;
26013      if (this.strict) {
26014        this.emit('error', er);
26015        // If the error is handled, then we abort
26016        // if not, we threw out of here
26017        this.abort();
26018      }
26019      if (!this.silent)
26020        console.error('glob error', er);
26021      break
26022  }
26023
26024  return cb()
26025};
26026
26027Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
26028  var self = this;
26029  this._readdir(abs, inGlobStar, function (er, entries) {
26030    self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
26031  });
26032};
26033
26034
26035Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
26036  //console.error('pgs2', prefix, remain[0], entries)
26037
26038  // no entries means not a dir, so it can never have matches
26039  // foo.txt/** doesn't match foo.txt
26040  if (!entries)
26041    return cb()
26042
26043  // test without the globstar, and with every child both below
26044  // and replacing the globstar.
26045  var remainWithoutGlobStar = remain.slice(1);
26046  var gspref = prefix ? [ prefix ] : [];
26047  var noGlobStar = gspref.concat(remainWithoutGlobStar);
26048
26049  // the noGlobStar pattern exits the inGlobStar state
26050  this._process(noGlobStar, index, false, cb);
26051
26052  var isSym = this.symlinks[abs];
26053  var len = entries.length;
26054
26055  // If it's a symlink, and we're in a globstar, then stop
26056  if (isSym && inGlobStar)
26057    return cb()
26058
26059  for (var i = 0; i < len; i++) {
26060    var e = entries[i];
26061    if (e.charAt(0) === '.' && !this.dot)
26062      continue
26063
26064    // these two cases enter the inGlobStar state
26065    var instead = gspref.concat(entries[i], remainWithoutGlobStar);
26066    this._process(instead, index, true, cb);
26067
26068    var below = gspref.concat(entries[i], remain);
26069    this._process(below, index, true, cb);
26070  }
26071
26072  cb();
26073};
26074
26075Glob.prototype._processSimple = function (prefix, index, cb) {
26076  // XXX review this.  Shouldn't it be doing the mounting etc
26077  // before doing stat?  kinda weird?
26078  var self = this;
26079  this._stat(prefix, function (er, exists) {
26080    self._processSimple2(prefix, index, er, exists, cb);
26081  });
26082};
26083Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
26084
26085  //console.error('ps2', prefix, exists)
26086
26087  if (!this.matches[index])
26088    this.matches[index] = Object.create(null);
26089
26090  // If it doesn't exist, then just mark the lack of results
26091  if (!exists)
26092    return cb()
26093
26094  if (prefix && isAbsolute(prefix) && !this.nomount) {
26095    var trail = /[\/\\]$/.test(prefix);
26096    if (prefix.charAt(0) === '/') {
26097      prefix = path$1.join(this.root, prefix);
26098    } else {
26099      prefix = path$1.resolve(this.root, prefix);
26100      if (trail)
26101        prefix += '/';
26102    }
26103  }
26104
26105  if (process.platform === 'win32')
26106    prefix = prefix.replace(/\\/g, '/');
26107
26108  // Mark this as a match
26109  this._emitMatch(index, prefix);
26110  cb();
26111};
26112
26113// Returns either 'DIR', 'FILE', or false
26114Glob.prototype._stat = function (f, cb) {
26115  var abs = this._makeAbs(f);
26116  var needDir = f.slice(-1) === '/';
26117
26118  if (f.length > this.maxLength)
26119    return cb()
26120
26121  if (!this.stat && ownProp(this.cache, abs)) {
26122    var c = this.cache[abs];
26123
26124    if (Array.isArray(c))
26125      c = 'DIR';
26126
26127    // It exists, but maybe not how we need it
26128    if (!needDir || c === 'DIR')
26129      return cb(null, c)
26130
26131    if (needDir && c === 'FILE')
26132      return cb()
26133
26134    // otherwise we have to stat, because maybe c=true
26135    // if we know it exists, but not what it is.
26136  }
26137  var stat = this.statCache[abs];
26138  if (stat !== undefined) {
26139    if (stat === false)
26140      return cb(null, stat)
26141    else {
26142      var type = stat.isDirectory() ? 'DIR' : 'FILE';
26143      if (needDir && type === 'FILE')
26144        return cb()
26145      else
26146        return cb(null, type, stat)
26147    }
26148  }
26149
26150  var self = this;
26151  var statcb = inflight('stat\0' + abs, lstatcb_);
26152  if (statcb)
26153    fs.lstat(abs, statcb);
26154
26155  function lstatcb_ (er, lstat) {
26156    if (lstat && lstat.isSymbolicLink()) {
26157      // If it's a symlink, then treat it as the target, unless
26158      // the target does not exist, then treat it as a file.
26159      return fs.stat(abs, function (er, stat) {
26160        if (er)
26161          self._stat2(f, abs, null, lstat, cb);
26162        else
26163          self._stat2(f, abs, er, stat, cb);
26164      })
26165    } else {
26166      self._stat2(f, abs, er, lstat, cb);
26167    }
26168  }
26169};
26170
26171Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
26172  if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
26173    this.statCache[abs] = false;
26174    return cb()
26175  }
26176
26177  var needDir = f.slice(-1) === '/';
26178  this.statCache[abs] = stat;
26179
26180  if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
26181    return cb(null, false, stat)
26182
26183  var c = true;
26184  if (stat)
26185    c = stat.isDirectory() ? 'DIR' : 'FILE';
26186  this.cache[abs] = this.cache[abs] || c;
26187
26188  if (needDir && c === 'FILE')
26189    return cb()
26190
26191  return cb(null, c, stat)
26192};
26193
26194/*!
26195 * Determine if an object is a Buffer
26196 *
26197 * @author   Feross Aboukhadijeh <https://feross.org>
26198 * @license  MIT
26199 */
26200
26201var isBuffer = function isBuffer (obj) {
26202  return obj != null && obj.constructor != null &&
26203    typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
26204};
26205
26206const proc$1 = process;
26207
26208var own$b = {}.hasOwnProperty;
26209
26210/**
26211 * @typedef {import('unist').Node} Node
26212 * @typedef {import('unist').Position} Position
26213 * @typedef {import('unist').Point} Point
26214 */
26215
26216/**
26217 * Stringify one point, a position (start and end points), or a node’s
26218 * positional information.
26219 *
26220 * @param {Node|Position|Point} [value]
26221 * @returns {string}
26222 */
26223function stringifyPosition$1(value) {
26224  // Nothing.
26225  if (!value || typeof value !== 'object') {
26226    return ''
26227  }
26228
26229  // Node.
26230  if (own$b.call(value, 'position') || own$b.call(value, 'type')) {
26231    // @ts-ignore looks like a node.
26232    return position(value.position)
26233  }
26234
26235  // Position.
26236  if (own$b.call(value, 'start') || own$b.call(value, 'end')) {
26237    // @ts-ignore looks like a position.
26238    return position(value)
26239  }
26240
26241  // Point.
26242  if (own$b.call(value, 'line') || own$b.call(value, 'column')) {
26243    // @ts-ignore looks like a point.
26244    return point$1(value)
26245  }
26246
26247  // ?
26248  return ''
26249}
26250
26251/**
26252 * @param {Point} point
26253 * @returns {string}
26254 */
26255function point$1(point) {
26256  return index$1(point && point.line) + ':' + index$1(point && point.column)
26257}
26258
26259/**
26260 * @param {Position} pos
26261 * @returns {string}
26262 */
26263function position(pos) {
26264  return point$1(pos && pos.start) + '-' + point$1(pos && pos.end)
26265}
26266
26267/**
26268 * @param {number} value
26269 * @returns {number}
26270 */
26271function index$1(value) {
26272  return value && typeof value === 'number' ? value : 1
26273}
26274
26275/**
26276 * @typedef {import('unist').Node} Node
26277 * @typedef {import('unist').Position} Position
26278 * @typedef {import('unist').Point} Point
26279 */
26280
26281class VFileMessage extends Error {
26282  /**
26283   * Constructor of a message for `reason` at `place` from `origin`.
26284   * When an error is passed in as `reason`, copies the `stack`.
26285   *
26286   * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.
26287   * @param {Node|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).
26288   * @param {string} [origin] Place in code the message originates from (`string`, optional).
26289   */
26290  constructor(reason, place, origin) {
26291    /** @type {[string?, string?]} */
26292    var parts = [null, null];
26293    /** @type {Position} */
26294    var position = {
26295      start: {line: null, column: null},
26296      end: {line: null, column: null}
26297    };
26298    /** @type {number} */
26299    var index;
26300
26301    super();
26302
26303    if (typeof place === 'string') {
26304      origin = place;
26305      place = null;
26306    }
26307
26308    if (typeof origin === 'string') {
26309      index = origin.indexOf(':');
26310
26311      if (index === -1) {
26312        parts[1] = origin;
26313      } else {
26314        parts[0] = origin.slice(0, index);
26315        parts[1] = origin.slice(index + 1);
26316      }
26317    }
26318
26319    if (place) {
26320      // Node.
26321      if ('type' in place || 'position' in place) {
26322        if (place.position) {
26323          position = place.position;
26324        }
26325      }
26326      // Position.
26327      else if ('start' in place || 'end' in place) {
26328        // @ts-ignore Looks like a position.
26329        position = place;
26330      }
26331      // Point.
26332      else if ('line' in place || 'column' in place) {
26333        // @ts-ignore Looks like a point.
26334        position.start = place;
26335      }
26336    }
26337
26338    // Fields from `Error`
26339    this.name = stringifyPosition$1(place) || '1:1';
26340    this.message = typeof reason === 'object' ? reason.message : reason;
26341    this.stack = typeof reason === 'object' ? reason.stack : '';
26342
26343    /**
26344     * Reason for message.
26345     * @type {string}
26346     */
26347    this.reason = this.message;
26348    /**
26349     * Starting line of error.
26350     * @type {number?}
26351     */
26352    this.line = position.start.line;
26353    /**
26354     * Starting column of error.
26355     * @type {number?}
26356     */
26357    this.column = position.start.column;
26358    /**
26359     * Namespace of warning.
26360     * @type {string?}
26361     */
26362    this.source = parts[0];
26363    /**
26364     * Category of message.
26365     * @type {string?}
26366     */
26367    this.ruleId = parts[1];
26368    /**
26369     * Full range information, when available.
26370     * Has start and end properties, both set to an object with line and column, set to number?.
26371     * @type {Position?}
26372     */
26373    this.position = position;
26374
26375    // The following fields are “well known”.
26376    // Not standard.
26377    // Feel free to add other non-standard fields to your messages.
26378
26379    /* eslint-disable no-unused-expressions */
26380    /**
26381     * You may add a file property with a path of a file (used throughout the VFile ecosystem).
26382     * @type {string?}
26383     */
26384    this.file;
26385    /**
26386     * If true, marks associated file as no longer processable.
26387     * @type {boolean?}
26388     */
26389    this.fatal;
26390    /**
26391     * You may add a url property with a link to documentation for the message.
26392     * @type {string?}
26393     */
26394    this.url;
26395    /**
26396     * You may add a note property with a long form description of the message (supported by vfile-reporter).
26397     * @type {string?}
26398     */
26399    this.note;
26400    /* eslint-enable no-unused-expressions */
26401  }
26402}
26403
26404VFileMessage.prototype.file = '';
26405VFileMessage.prototype.name = '';
26406VFileMessage.prototype.reason = '';
26407VFileMessage.prototype.message = '';
26408VFileMessage.prototype.stack = '';
26409VFileMessage.prototype.fatal = null;
26410VFileMessage.prototype.column = null;
26411VFileMessage.prototype.line = null;
26412VFileMessage.prototype.source = null;
26413VFileMessage.prototype.ruleId = null;
26414VFileMessage.prototype.position = null;
26415
26416/**
26417 * @typedef {import('unist').Node} Node
26418 * @typedef {import('unist').Position} Position
26419 * @typedef {import('unist').Point} Point
26420 *
26421 * @typedef {'ascii'|'utf8'|'utf-8'|'utf16le'|'ucs2'|'ucs-2'|'base64'|'latin1'|'binary'|'hex'} BufferEncoding
26422 *   Encodings supported by the buffer class.
26423 *   This is a copy of the typing from Node, copied to prevent Node globals from
26424 *   being needed.
26425 *   Copied from: <https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a2bc1d8/types/node/globals.d.ts#L174>
26426 *
26427 * @typedef {string|Uint8Array} VFileValue Contents of the file.
26428 *   Can either be text, or a Buffer like structure.
26429 *   This does not directly use type `Buffer`, because it can also be used in a
26430 *   browser context.
26431 *   Instead this leverages `Uint8Array` which is the base type for `Buffer`,
26432 *   and a native JavaScript construct.
26433 *
26434 * @typedef {VFileValue|VFileOptions|VFile} VFileCompatible Things that can be
26435 *   passed to the constructor.
26436 *
26437 * @typedef VFileCoreOptions
26438 * @property {VFileValue} [value]
26439 * @property {string} [cwd]
26440 * @property {Array.<string>} [history]
26441 * @property {string} [path]
26442 * @property {string} [basename]
26443 * @property {string} [stem]
26444 * @property {string} [extname]
26445 * @property {string} [dirname]
26446 * @property {Object.<string, unknown>} [data]
26447 *
26448 * @typedef {{[key: string]: unknown} & VFileCoreOptions} VFileOptions
26449 *   Configuration: a bunch of keys that will be shallow copied over to the new
26450 *   file.
26451 *
26452 * @typedef {Object.<string, unknown>} VFileReporterSettings
26453 * @typedef {<T = VFileReporterSettings>(files: VFile[], options: T) => string} VFileReporter
26454 */
26455
26456// Order of setting (least specific to most), we need this because otherwise
26457// `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a
26458// stem can be set.
26459var order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname'];
26460
26461class VFile {
26462  /**
26463   * Create a new virtual file.
26464   *
26465   * If `options` is `string` or `Buffer`, treats it as `{value: options}`.
26466   * If `options` is a `VFile`, shallow copies its data over to the new file.
26467   * All other given fields are set on the newly created `VFile`.
26468   *
26469   * Path related properties are set in the following order (least specific to
26470   * most specific): `history`, `path`, `basename`, `stem`, `extname`,
26471   * `dirname`.
26472   *
26473   * It’s not possible to set either `dirname` or `extname` without setting
26474   * either `history`, `path`, `basename`, or `stem` as well.
26475   *
26476   * @param {VFileCompatible} [value]
26477   */
26478  constructor(value) {
26479    var index = -1;
26480    /** @type {VFileOptions} */
26481    var options;
26482    /** @type {string} */
26483    var prop;
26484
26485    if (!value) {
26486      options = {};
26487    } else if (typeof value === 'string' || isBuffer(value)) {
26488      // @ts-ignore Looks like a buffer.
26489      options = {value};
26490    } else {
26491      // @ts-ignore Looks like file or options.
26492      options = value;
26493    }
26494
26495    /**
26496     * Place to store custom information.
26497     * It’s OK to store custom data directly on the file, moving it to `data`
26498     * gives a little more privacy.
26499     * @type {Object.<string, unknown>}
26500     */
26501    this.data = {};
26502
26503    /**
26504     * List of messages associated with the file.
26505     * @type {Array.<VFileMessage>}
26506     */
26507    this.messages = [];
26508
26509    /**
26510     * List of file paths the file moved between.
26511     * @type {Array.<string>}
26512     */
26513    this.history = [];
26514
26515    /**
26516     * Base of `path`.
26517     * Defaults to `process.cwd()` (`/` in browsers).
26518     * @type {string}
26519     */
26520    this.cwd = proc$1.cwd();
26521
26522    /* eslint-disable no-unused-expressions */
26523    /**
26524     * Raw value.
26525     * @type {VFileValue}
26526     */
26527    this.value;
26528
26529    // The below are non-standard, they are “well-known”.
26530    // As in, used in several tools.
26531
26532    /**
26533     * Whether a file was saved to disk.
26534     * This is used by vfile reporters.
26535     * @type {boolean}
26536     */
26537    this.stored;
26538
26539    /**
26540     * Sometimes files have a non-string representation.
26541     * This can be stored in the `result` field.
26542     * One example is when turning markdown into React nodes.
26543     * This is used by unified to store non-string results.
26544     * @type {unknown}
26545     */
26546    this.result;
26547    /* eslint-enable no-unused-expressions */
26548
26549    // Set path related properties in the correct order.
26550    while (++index < order.length) {
26551      prop = order[index];
26552
26553      // Note: we specifically use `in` instead of `hasOwnProperty` to accept
26554      // `vfile`s too.
26555      if (prop in options && options[prop] !== undefined) {
26556        this[prop] = prop === 'history' ? options[prop].concat() : options[prop];
26557      }
26558    }
26559
26560    // Set non-path related properties.
26561    for (prop in options) {
26562      if (!order.includes(prop)) {
26563        this[prop] = options[prop];
26564      }
26565    }
26566  }
26567
26568  /**
26569   * Access full path (`~/index.min.js`).
26570   */
26571  get path() {
26572    return this.history[this.history.length - 1]
26573  }
26574
26575  /**
26576   * Set full path (`~/index.min.js`).
26577   * Cannot be nullified.
26578   */
26579  set path(path) {
26580    assertNonEmpty(path, 'path');
26581
26582    if (this.path !== path) {
26583      this.history.push(path);
26584    }
26585  }
26586
26587  /**
26588   * Access parent path (`~`).
26589   */
26590  get dirname() {
26591    return typeof this.path === 'string' ? path$b.dirname(this.path) : undefined
26592  }
26593
26594  /**
26595   * Set parent path (`~`).
26596   * Cannot be set if there's no `path` yet.
26597   */
26598  set dirname(dirname) {
26599    assertPath(this.path, 'dirname');
26600    this.path = path$b.join(dirname || '', this.basename);
26601  }
26602
26603  /**
26604   * Access basename (including extname) (`index.min.js`).
26605   */
26606  get basename() {
26607    return typeof this.path === 'string' ? path$b.basename(this.path) : undefined
26608  }
26609
26610  /**
26611   * Set basename (`index.min.js`).
26612   * Cannot contain path separators.
26613   * Cannot be nullified either (use `file.path = file.dirname` instead).
26614   */
26615  set basename(basename) {
26616    assertNonEmpty(basename, 'basename');
26617    assertPart(basename, 'basename');
26618    this.path = path$b.join(this.dirname || '', basename);
26619  }
26620
26621  /**
26622   * Access extname (including dot) (`.js`).
26623   */
26624  get extname() {
26625    return typeof this.path === 'string' ? path$b.extname(this.path) : undefined
26626  }
26627
26628  /**
26629   * Set extname (including dot) (`.js`).
26630   * Cannot be set if there's no `path` yet and cannot contain path separators.
26631   */
26632  set extname(extname) {
26633    assertPart(extname, 'extname');
26634    assertPath(this.path, 'extname');
26635
26636    if (extname) {
26637      if (extname.charCodeAt(0) !== 46 /* `.` */) {
26638        throw new Error('`extname` must start with `.`')
26639      }
26640
26641      if (extname.includes('.', 1)) {
26642        throw new Error('`extname` cannot contain multiple dots')
26643      }
26644    }
26645
26646    this.path = path$b.join(this.dirname, this.stem + (extname || ''));
26647  }
26648
26649  /**
26650   * Access stem (w/o extname) (`index.min`).
26651   */
26652  get stem() {
26653    return typeof this.path === 'string'
26654      ? path$b.basename(this.path, this.extname)
26655      : undefined
26656  }
26657
26658  /**
26659   * Set stem (w/o extname) (`index.min`).
26660   * Cannot be nullified, and cannot contain path separators.
26661   */
26662  set stem(stem) {
26663    assertNonEmpty(stem, 'stem');
26664    assertPart(stem, 'stem');
26665    this.path = path$b.join(this.dirname || '', stem + (this.extname || ''));
26666  }
26667
26668  /**
26669   * Serialize the file.
26670   *
26671   * @param {BufferEncoding} [encoding='utf8'] If `file.value` is a buffer, `encoding` is used to serialize buffers.
26672   * @returns {string}
26673   */
26674  toString(encoding) {
26675    // @ts-ignore string’s don’t accept the parameter, but buffers do.
26676    return (this.value || '').toString(encoding)
26677  }
26678
26679  /**
26680   * Create a message and associates it w/ the file.
26681   *
26682   * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.
26683   * @param {Node|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).
26684   * @param {string} [origin] Place in code the message originates from (`string`, optional).
26685   * @returns {VFileMessage}
26686   */
26687  message(reason, place, origin) {
26688    var message = new VFileMessage(reason, place, origin);
26689
26690    if (this.path) {
26691      message.name = this.path + ':' + message.name;
26692      message.file = this.path;
26693    }
26694
26695    message.fatal = false;
26696
26697    this.messages.push(message);
26698
26699    return message
26700  }
26701
26702  /**
26703   * Info: create a message, associate it with the file, and mark the fatality
26704   * as `null`.
26705   * Calls `message()` internally.
26706   *
26707   * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.
26708   * @param {Node|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).
26709   * @param {string} [origin] Place in code the message originates from (`string`, optional).
26710   * @returns {VFileMessage}
26711   */
26712  info(reason, place, origin) {
26713    var message = this.message(reason, place, origin);
26714
26715    message.fatal = null;
26716
26717    return message
26718  }
26719
26720  /**
26721   * Fail: create a message, associate it with the file, mark the fatality as
26722   * `true`.
26723   * Note: fatal errors mean a file is no longer processable.
26724   * Calls `message()` internally.
26725   *
26726   * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.
26727   * @param {Node|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).
26728   * @param {string} [origin] Place in code the message originates from (`string`, optional).
26729   * @returns {never}
26730   */
26731  fail(reason, place, origin) {
26732    var message = this.message(reason, place, origin);
26733
26734    message.fatal = true;
26735
26736    throw message
26737  }
26738}
26739
26740/**
26741 * Assert that `part` is not a path (as in, does not contain `path.sep`).
26742 *
26743 * @param {string} part
26744 * @param {string} name
26745 * @returns {void}
26746 */
26747function assertPart(part, name) {
26748  if (part && part.includes(path$b.sep)) {
26749    throw new Error(
26750      '`' + name + '` cannot be a path: did not expect `' + path$b.sep + '`'
26751    )
26752  }
26753}
26754
26755/**
26756 * Assert that `part` is not empty.
26757 *
26758 * @param {string} part
26759 * @param {string} name
26760 * @returns {void}
26761 */
26762function assertNonEmpty(part, name) {
26763  if (!part) {
26764    throw new Error('`' + name + '` cannot be empty')
26765  }
26766}
26767
26768/**
26769 * Assert `path` exists.
26770 *
26771 * @param {string} path
26772 * @param {string} name
26773 * @returns {void}
26774 */
26775function assertPath(path, name) {
26776  if (!path) {
26777    throw new Error('Setting `' + name + '` requires `path` to be set too')
26778  }
26779}
26780
26781/**
26782 * @typedef {import('vfile').VFileValue} Value
26783 * @typedef {import('vfile').VFileOptions} Options
26784 * @typedef {import('vfile').BufferEncoding} BufferEncoding
26785 *
26786 * @typedef {number|string} Mode
26787 * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, flag?: string}} ReadOptions
26788 * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, mode: Mode?, flag?: string}} WriteOptions
26789 *
26790 * @typedef {string|Uint8Array} Path Path of the file.
26791 * @typedef {Path|URL|Options|VFile} Compatible Things that can be
26792 *   passed to the function.
26793 */
26794
26795/**
26796 * Create a virtual file from a description.
26797 * If `options` is a string or a buffer, it’s used as the path.
26798 * If it’s a VFile itself, it’s returned instead.
26799 * In all other cases, the options are passed through to `vfile()`.
26800 *
26801 * @param {Compatible} [options]
26802 * @returns {VFile}
26803 */
26804function toVFile(options) {
26805  if (typeof options === 'string' || isBuffer(options)) {
26806    options = {path: String(options)};
26807  } else if (options instanceof URL$1) {
26808    options = {path: fileURLToPath(options)};
26809  }
26810
26811  return looksLikeAVFile$1(options) ? options : new VFile(options)
26812}
26813
26814/**
26815 * Create a virtual file and read it in, synchronously.
26816 *
26817 * @param {Compatible} description
26818 * @param {ReadOptions} [options]
26819 * @returns {VFile}
26820 */
26821function readSync(description, options) {
26822  var file = toVFile(description);
26823  file.value = require$$0$3.readFileSync(path$b.resolve(file.cwd, file.path), options);
26824  return file
26825}
26826
26827/**
26828 * Create a virtual file and write it in, synchronously.
26829 *
26830 * @param {Compatible} description
26831 * @param {WriteOptions} [options]
26832 * @returns {VFile}
26833 */
26834function writeSync(description, options) {
26835  var file = toVFile(description);
26836  require$$0$3.writeFileSync(path$b.resolve(file.cwd, file.path), file.value || '', options);
26837  return file
26838}
26839
26840const read$2 =
26841  /**
26842   * @type {{
26843   *   (description: Compatible, options: ReadOptions, callback: Callback): void
26844   *   (description: Compatible, callback: Callback): void
26845   *   (description: Compatible, options?: ReadOptions): Promise<VFile>
26846   * }}
26847   */
26848  (
26849    /**
26850     * Create a virtual file and read it in, asynchronously.
26851     *
26852     * @param {Compatible} description
26853     * @param {ReadOptions} [options]
26854     * @param {Callback} [callback]
26855     */
26856    function (description, options, callback) {
26857      var file = toVFile(description);
26858
26859      if (!callback && typeof options === 'function') {
26860        callback = options;
26861        options = null;
26862      }
26863
26864      if (!callback) {
26865        return new Promise(executor)
26866      }
26867
26868      executor(resolve, callback);
26869
26870      /**
26871       * @param {VFile} result
26872       */
26873      function resolve(result) {
26874        callback(null, result);
26875      }
26876
26877      /**
26878       * @param {(x: VFile) => void} resolve
26879       * @param {(x: Error, y?: VFile) => void} reject
26880       */
26881      function executor(resolve, reject) {
26882        /** @type {string} */
26883        var fp;
26884
26885        try {
26886          fp = path$b.resolve(file.cwd, file.path);
26887        } catch (error) {
26888          return reject(error)
26889        }
26890
26891        require$$0$3.readFile(fp, options, done);
26892
26893        /**
26894         * @param {Error} error
26895         * @param {Value} result
26896         */
26897        function done(error, result) {
26898          if (error) {
26899            reject(error);
26900          } else {
26901            file.value = result;
26902            resolve(file);
26903          }
26904        }
26905      }
26906    }
26907  );
26908
26909const write =
26910  /**
26911   * @type {{
26912   *   (description: Compatible, options: WriteOptions, callback: Callback): void
26913   *   (description: Compatible, callback: Callback): void
26914   *   (description: Compatible, options?: WriteOptions): Promise<VFile>
26915   * }}
26916   */
26917  (
26918    /**
26919     * Create a virtual file and write it in, asynchronously.
26920     *
26921     * @param {Compatible} description
26922     * @param {WriteOptions} [options]
26923     * @param {Callback} [callback]
26924     */
26925    function (description, options, callback) {
26926      var file = toVFile(description);
26927
26928      // Weird, right? Otherwise `fs` doesn’t accept it.
26929      if (!callback && typeof options === 'function') {
26930        callback = options;
26931        options = undefined;
26932      }
26933
26934      if (!callback) {
26935        return new Promise(executor)
26936      }
26937
26938      executor(resolve, callback);
26939
26940      /**
26941       * @param {VFile} result
26942       */
26943      function resolve(result) {
26944        callback(null, result);
26945      }
26946
26947      /**
26948       * @param {(x: VFile) => void} resolve
26949       * @param {(x: Error, y?: VFile) => void} reject
26950       */
26951      function executor(resolve, reject) {
26952        /** @type {string} */
26953        var fp;
26954
26955        try {
26956          fp = path$b.resolve(file.cwd, file.path);
26957        } catch (error) {
26958          return reject(error)
26959        }
26960
26961        require$$0$3.writeFile(fp, file.value || '', options, done);
26962
26963        /**
26964         * @param {Error} error
26965         */
26966        function done(error) {
26967          if (error) {
26968            reject(error);
26969          } else {
26970            resolve(file);
26971          }
26972        }
26973      }
26974    }
26975  );
26976
26977/**
26978 * @param {Compatible} value
26979 * @returns {value is VFile}
26980 */
26981function looksLikeAVFile$1(value) {
26982  return (
26983    value &&
26984    typeof value === 'object' &&
26985    'message' in value &&
26986    'messages' in value
26987  )
26988}
26989
26990toVFile.readSync = readSync;
26991toVFile.writeSync = writeSync;
26992toVFile.read = read$2;
26993toVFile.write = write;
26994
26995/**
26996 * @typedef {import('fs').Stats} Stats
26997 * @typedef {import('vfile').VFile} VFile
26998 * @typedef {import('./ignore.js').Ignore} Ignore
26999 * @typedef {import('ignore').Ignore} GitIgnore
27000 *
27001 * @typedef Options
27002 * @property {string} cwd
27003 * @property {Array.<string>} extensions
27004 * @property {boolean|undefined} silentlyIgnore
27005 * @property {Array.<string>} ignorePatterns
27006 * @property {Ignore} ignore
27007 *
27008 * @typedef SearchResults
27009 * @property {fs.Stats|undefined} stats
27010 * @property {boolean|undefined} ignored
27011 *
27012 * @typedef Result
27013 * @property {Array.<string|VFile>} input
27014 * @property {VFile[]} output
27015 *
27016 * @typedef CleanResult
27017 * @property {boolean} oneFileMode
27018 * @property {VFile[]} files
27019 *
27020 * @callback Callback
27021 * @param {Error|null} error
27022 * @param {CleanResult} [result]
27023 */
27024
27025/**
27026 * Search `patterns`, a mix of globs, paths, and files.
27027 *
27028 * @param {Array.<string|VFile>} input
27029 * @param {Options} options
27030 * @param {Callback} callback
27031 */
27032function finder(input, options, callback) {
27033  expand(input, options, (error, result) => {
27034    // Glob errors are unusual.
27035    // other errors are on the vfile results.
27036    /* c8 ignore next 2 */
27037    if (error || !result) {
27038      callback(error);
27039    } else {
27040      callback(null, {oneFileMode: oneFileMode(result), files: result.output});
27041    }
27042  });
27043}
27044
27045/**
27046 * Expand the given glob patterns, search given and found directories, and map
27047 * to vfiles.
27048 *
27049 * @param {Array.<string|VFile>} input
27050 * @param {Options} options
27051 * @param {(error: Error|null, result?: Result) => void} next
27052 */
27053function expand(input, options, next) {
27054  /** @type {Array.<string|VFile>} */
27055  let paths = [];
27056  let actual = 0;
27057  let expected = 0;
27058  let index = -1;
27059  /** @type {boolean|undefined} */
27060  let failed;
27061
27062  while (++index < input.length) {
27063    let file = input[index];
27064    if (typeof file === 'string') {
27065      if (glob_1.hasMagic(file)) {
27066        expected++;
27067        glob_1(file, {cwd: options.cwd}, (error, files) => {
27068          // Glob errors are unusual.
27069          /* c8 ignore next 3 */
27070          if (failed) {
27071            return
27072          }
27073
27074          // Glob errors are unusual.
27075          /* c8 ignore next 4 */
27076          if (error) {
27077            failed = true;
27078            done1(error);
27079          } else {
27080            actual++;
27081            paths = paths.concat(files);
27082
27083            if (actual === expected) {
27084              search$1(paths, options, done1);
27085            }
27086          }
27087        });
27088      } else {
27089        // `relative` to make the paths canonical.
27090        file =
27091          path$c.relative(options.cwd, path$c.resolve(options.cwd, file)) || '.';
27092        paths.push(file);
27093      }
27094    } else {
27095      const fp = file.path ? path$c.relative(options.cwd, file.path) : options.cwd;
27096      file.cwd = options.cwd;
27097      file.path = fp;
27098      file.history = [fp];
27099      paths.push(file);
27100    }
27101  }
27102
27103  if (!expected) {
27104    search$1(paths, options, done1);
27105  }
27106
27107  /**
27108   * @param {Error|null} error
27109   * @param {Array<VFile>} [files]
27110   */
27111  function done1(error, files) {
27112    // `search` currently does not give errors.
27113    /* c8 ignore next 2 */
27114    if (error || !files) {
27115      next(error);
27116    } else {
27117      next(null, {input: paths, output: files});
27118    }
27119  }
27120}
27121
27122/**
27123 * Search `paths`.
27124 *
27125 * @param {Array.<string|VFile>} input
27126 * @param {Options & {nested?: boolean}} options
27127 * @param {(error: Error|null, files: Array.<VFile>) => void} next
27128 */
27129function search$1(input, options, next) {
27130  const extraIgnore = ignore().add(options.ignorePatterns);
27131  let expected = 0;
27132  let actual = 0;
27133  let index = -1;
27134  /** @type {Array.<VFile>} */
27135  let files = [];
27136
27137  while (++index < input.length) {
27138    each(input[index]);
27139  }
27140
27141  if (!expected) {
27142    next(null, files);
27143  }
27144
27145  /**
27146   * @param {string|VFile} file
27147   */
27148  function each(file) {
27149    const ext = typeof file === 'string' ? path$c.extname(file) : file.extname;
27150
27151    // Normalise globs.
27152    if (typeof file === 'string') {
27153      file = file.split('/').join(path$c.sep);
27154    }
27155
27156    const part = base$1(file);
27157
27158    if (options.nested && (part.charAt(0) === '.' || part === 'node_modules')) {
27159      return
27160    }
27161
27162    expected++;
27163
27164    statAndIgnore(
27165      file,
27166      Object.assign({}, options, {extraIgnore}),
27167      (error, result) => {
27168        const ignored = result && result.ignored;
27169        const dir = result && result.stats && result.stats.isDirectory();
27170
27171        if (ignored && (options.nested || options.silentlyIgnore)) {
27172          return one(null, [])
27173        }
27174
27175        if (!ignored && dir) {
27176          return fs$a.readdir(
27177            path$c.resolve(options.cwd, filePath(file)),
27178            (error, basenames) => {
27179              // Should not happen often: the directory is `stat`ed first, which was ok,
27180              // but reading it is not.
27181              /* c8 ignore next 9 */
27182              if (error) {
27183                const otherFile = toVFile(filePath(file));
27184                otherFile.cwd = options.cwd;
27185
27186                try {
27187                  otherFile.fail('Cannot read directory');
27188                } catch {}
27189
27190                one(null, [otherFile]);
27191              } else {
27192                search$1(
27193                  basenames.map((name) => path$c.join(filePath(file), name)),
27194                  Object.assign({}, options, {nested: true}),
27195                  one
27196                );
27197              }
27198            }
27199          )
27200        }
27201
27202        if (
27203          !dir &&
27204          options.nested &&
27205          options.extensions.length > 0 &&
27206          !options.extensions.includes(ext)
27207        ) {
27208          return one(null, [])
27209        }
27210
27211        file = toVFile(file);
27212        file.cwd = options.cwd;
27213
27214        if (ignored) {
27215          try {
27216            file.fail('Cannot process specified file: it’s ignored');
27217            // C8 bug on Node@12
27218            /* c8 ignore next 1 */
27219          } catch {}
27220        }
27221
27222        if (error && error.code === 'ENOENT') {
27223          try {
27224            file.fail(
27225              error.syscall === 'stat' ? 'No such file or directory' : error
27226            );
27227            // C8 bug on Node@12
27228            /* c8 ignore next 1 */
27229          } catch {}
27230        }
27231
27232        one(null, [file]);
27233      }
27234    );
27235
27236    /**
27237     * Error is never given. Always given `results`.
27238     *
27239     * @param {Error|null} _
27240     * @param {Array.<VFile>} results
27241     */
27242    function one(_, results) {
27243      /* istanbul ignore else - Always given. */
27244      if (results) {
27245        files = files.concat(results);
27246      }
27247
27248      actual++;
27249
27250      if (actual === expected) {
27251        next(null, files);
27252      }
27253    }
27254  }
27255}
27256
27257/**
27258 * @param {VFile|string} file
27259 * @param {Options & {extraIgnore: GitIgnore}} options
27260 * @param {(error: NodeJS.ErrnoException|null, result?: SearchResults) => void} callback
27261 */
27262function statAndIgnore(file, options, callback) {
27263  const fp = path$c.resolve(options.cwd, filePath(file));
27264  const normal = path$c.relative(options.cwd, fp);
27265  let expected = 1;
27266  let actual = 0;
27267  /** @type {Stats|undefined} */
27268  let stats;
27269  /** @type {boolean|undefined} */
27270  let ignored;
27271
27272  if (typeof file === 'string' || !file.value) {
27273    expected++;
27274    fs$a.stat(fp, (error, value) => {
27275      stats = value;
27276      onStartOrCheck(error);
27277    });
27278  }
27279
27280  options.ignore.check(fp, (error, value) => {
27281    ignored = value;
27282    onStartOrCheck(error);
27283  });
27284
27285  /**
27286   * @param {Error|null} error
27287   */
27288  function onStartOrCheck(error) {
27289    actual++;
27290
27291    if (error) {
27292      callback(error);
27293      actual = -1;
27294    } else if (actual === expected) {
27295      callback(null, {
27296        stats,
27297        ignored:
27298          ignored ||
27299          (normal === '' ||
27300          normal === '..' ||
27301          normal.charAt(0) === path$c.sep ||
27302          normal.slice(0, 3) === '..' + path$c.sep
27303            ? false
27304            : options.extraIgnore.ignores(normal))
27305      });
27306    }
27307  }
27308}
27309
27310/**
27311 * @param {string|VFile} file
27312 * @returns {string}
27313 */
27314function base$1(file) {
27315  return typeof file === 'string' ? path$c.basename(file) : file.basename
27316}
27317
27318/**
27319 * @param {string|VFile} file
27320 * @returns {string}
27321 */
27322function filePath(file) {
27323  return typeof file === 'string' ? file : file.path
27324}
27325
27326/**
27327 * @param {Result} result
27328 * @returns {boolean}
27329 */
27330function oneFileMode(result) {
27331  return (
27332    result.output.length === 1 &&
27333    result.input.length === 1 &&
27334    result.output[0].path === result.input[0]
27335  )
27336}
27337
27338/**
27339 * @typedef {import('vfile').VFile} VFile
27340 * @typedef {import('trough').Callback} Callback
27341 * @typedef {import('./index.js').Settings} Settings
27342 * @typedef {import('./index.js').Configuration} Configuration
27343 */
27344
27345/**
27346 * @param {Context} context
27347 * @param {Settings} settings
27348 * @param {Callback} next
27349 */
27350function fileSystem$1(context, settings, next) {
27351  if (context.files.length === 0) {
27352    next();
27353  } else {
27354    finder(
27355      context.files,
27356      {
27357        cwd: settings.cwd,
27358        extensions: settings.extensions,
27359        silentlyIgnore: settings.silentlyIgnore,
27360        ignorePatterns: settings.ignorePatterns,
27361        ignore: new Ignore({
27362          cwd: settings.cwd,
27363          detectIgnore: settings.detectIgnore,
27364          ignoreName: settings.ignoreName,
27365          ignorePath: settings.ignorePath,
27366          ignorePathResolveFrom: settings.ignorePathResolveFrom
27367        })
27368      },
27369      (error, result) => {
27370        // Glob errors typically don’t occur.
27371        /* c8 ignore next 4 */
27372        if (!result) {
27373          next(error);
27374          return
27375        }
27376
27377        const output = result.files;
27378
27379        // Sort alphabetically.
27380        // Everything is unique so we do not care about cases where left and right
27381        // are equal.
27382        output.sort(sortAlphabetically);
27383
27384        // Mark as given.
27385        // This allows outputting files, which can be pretty dangerous, so it’s
27386        // “hidden”.
27387        let index = -1;
27388        while (++index < output.length) {
27389          output[index].data.unifiedEngineGiven = true;
27390        }
27391
27392        context.files = output;
27393
27394        // If `out` was not set, detect it based on whether one file was given.
27395        if (settings.out === null || settings.out === undefined) {
27396          settings.out = result.oneFileMode;
27397        }
27398
27399        next(error);
27400      }
27401    );
27402  }
27403
27404  /**
27405   * @param {VFile} left
27406   * @param {VFile} right
27407   * @returns {number}
27408   */
27409  function sortAlphabetically(left, right) {
27410    return left.path < right.path ? -1 : 1
27411  }
27412}
27413
27414/* eslint-disable node/no-deprecated-api */
27415
27416var toString$2 = Object.prototype.toString;
27417
27418var isModern = (
27419  typeof Buffer !== 'undefined' &&
27420  typeof Buffer.alloc === 'function' &&
27421  typeof Buffer.allocUnsafe === 'function' &&
27422  typeof Buffer.from === 'function'
27423);
27424
27425function isArrayBuffer (input) {
27426  return toString$2.call(input).slice(8, -1) === 'ArrayBuffer'
27427}
27428
27429function fromArrayBuffer (obj, byteOffset, length) {
27430  byteOffset >>>= 0;
27431
27432  var maxLength = obj.byteLength - byteOffset;
27433
27434  if (maxLength < 0) {
27435    throw new RangeError("'offset' is out of bounds")
27436  }
27437
27438  if (length === undefined) {
27439    length = maxLength;
27440  } else {
27441    length >>>= 0;
27442
27443    if (length > maxLength) {
27444      throw new RangeError("'length' is out of bounds")
27445    }
27446  }
27447
27448  return isModern
27449    ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
27450    : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
27451}
27452
27453function fromString (string, encoding) {
27454  if (typeof encoding !== 'string' || encoding === '') {
27455    encoding = 'utf8';
27456  }
27457
27458  if (!Buffer.isEncoding(encoding)) {
27459    throw new TypeError('"encoding" must be a valid string encoding')
27460  }
27461
27462  return isModern
27463    ? Buffer.from(string, encoding)
27464    : new Buffer(string, encoding)
27465}
27466
27467function bufferFrom$1 (value, encodingOrOffset, length) {
27468  if (typeof value === 'number') {
27469    throw new TypeError('"value" argument must not be a number')
27470  }
27471
27472  if (isArrayBuffer(value)) {
27473    return fromArrayBuffer(value, encodingOrOffset, length)
27474  }
27475
27476  if (typeof value === 'string') {
27477    return fromString(value, encodingOrOffset)
27478  }
27479
27480  return isModern
27481    ? Buffer.from(value)
27482    : new Buffer(value)
27483}
27484
27485var bufferFrom_1 = bufferFrom$1;
27486
27487var typedarray = {};
27488
27489(function (exports) {
27490var undefined$1 = (void 0); // Paranoia
27491
27492// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
27493// create, and consume so much memory, that the browser appears frozen.
27494var MAX_ARRAY_LENGTH = 1e5;
27495
27496// Approximations of internal ECMAScript conversion functions
27497var ECMAScript = (function() {
27498  // Stash a copy in case other scripts modify these
27499  var opts = Object.prototype.toString,
27500      ophop = Object.prototype.hasOwnProperty;
27501
27502  return {
27503    // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
27504    Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
27505    HasProperty: function(o, p) { return p in o; },
27506    HasOwnProperty: function(o, p) { return ophop.call(o, p); },
27507    IsCallable: function(o) { return typeof o === 'function'; },
27508    ToInt32: function(v) { return v >> 0; },
27509    ToUint32: function(v) { return v >>> 0; }
27510  };
27511}());
27512
27513// Snapshot intrinsics
27514var LN2 = Math.LN2,
27515    abs = Math.abs,
27516    floor = Math.floor,
27517    log = Math.log,
27518    min = Math.min,
27519    pow = Math.pow,
27520    round = Math.round;
27521
27522// ES5: lock down object properties
27523function configureProperties(obj) {
27524  if (getOwnPropNames && defineProp) {
27525    var props = getOwnPropNames(obj), i;
27526    for (i = 0; i < props.length; i += 1) {
27527      defineProp(obj, props[i], {
27528        value: obj[props[i]],
27529        writable: false,
27530        enumerable: false,
27531        configurable: false
27532      });
27533    }
27534  }
27535}
27536
27537// emulate ES5 getter/setter API using legacy APIs
27538// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
27539// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
27540// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
27541var defineProp;
27542if (Object.defineProperty && (function() {
27543      try {
27544        Object.defineProperty({}, 'x', {});
27545        return true;
27546      } catch (e) {
27547        return false;
27548      }
27549    })()) {
27550  defineProp = Object.defineProperty;
27551} else {
27552  defineProp = function(o, p, desc) {
27553    if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
27554    if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
27555    if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
27556    if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
27557    return o;
27558  };
27559}
27560
27561var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
27562  if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
27563  var props = [], p;
27564  for (p in o) {
27565    if (ECMAScript.HasOwnProperty(o, p)) {
27566      props.push(p);
27567    }
27568  }
27569  return props;
27570};
27571
27572// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
27573// for index in 0 ... obj.length
27574function makeArrayAccessors(obj) {
27575  if (!defineProp) { return; }
27576
27577  if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
27578
27579  function makeArrayAccessor(index) {
27580    defineProp(obj, index, {
27581      'get': function() { return obj._getter(index); },
27582      'set': function(v) { obj._setter(index, v); },
27583      enumerable: true,
27584      configurable: false
27585    });
27586  }
27587
27588  var i;
27589  for (i = 0; i < obj.length; i += 1) {
27590    makeArrayAccessor(i);
27591  }
27592}
27593
27594// Internal conversion functions:
27595//    pack<Type>()   - take a number (interpreted as Type), output a byte array
27596//    unpack<Type>() - take a byte array, output a Type-like number
27597
27598function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
27599function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
27600
27601function packI8(n) { return [n & 0xff]; }
27602function unpackI8(bytes) { return as_signed(bytes[0], 8); }
27603
27604function packU8(n) { return [n & 0xff]; }
27605function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
27606
27607function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
27608
27609function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
27610function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
27611
27612function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
27613function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
27614
27615function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
27616function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
27617
27618function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
27619function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
27620
27621function packIEEE754(v, ebits, fbits) {
27622
27623  var bias = (1 << (ebits - 1)) - 1,
27624      s, e, f, i, bits, str, bytes;
27625
27626  function roundToEven(n) {
27627    var w = floor(n), f = n - w;
27628    if (f < 0.5)
27629      return w;
27630    if (f > 0.5)
27631      return w + 1;
27632    return w % 2 ? w + 1 : w;
27633  }
27634
27635  // Compute sign, exponent, fraction
27636  if (v !== v) {
27637    // NaN
27638    // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
27639    e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
27640  } else if (v === Infinity || v === -Infinity) {
27641    e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
27642  } else if (v === 0) {
27643    e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
27644  } else {
27645    s = v < 0;
27646    v = abs(v);
27647
27648    if (v >= pow(2, 1 - bias)) {
27649      e = min(floor(log(v) / LN2), 1023);
27650      f = roundToEven(v / pow(2, e) * pow(2, fbits));
27651      if (f / pow(2, fbits) >= 2) {
27652        e = e + 1;
27653        f = 1;
27654      }
27655      if (e > bias) {
27656        // Overflow
27657        e = (1 << ebits) - 1;
27658        f = 0;
27659      } else {
27660        // Normalized
27661        e = e + bias;
27662        f = f - pow(2, fbits);
27663      }
27664    } else {
27665      // Denormalized
27666      e = 0;
27667      f = roundToEven(v / pow(2, 1 - bias - fbits));
27668    }
27669  }
27670
27671  // Pack sign, exponent, fraction
27672  bits = [];
27673  for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
27674  for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
27675  bits.push(s ? 1 : 0);
27676  bits.reverse();
27677  str = bits.join('');
27678
27679  // Bits to bytes
27680  bytes = [];
27681  while (str.length) {
27682    bytes.push(parseInt(str.substring(0, 8), 2));
27683    str = str.substring(8);
27684  }
27685  return bytes;
27686}
27687
27688function unpackIEEE754(bytes, ebits, fbits) {
27689
27690  // Bytes to bits
27691  var bits = [], i, j, b, str,
27692      bias, s, e, f;
27693
27694  for (i = bytes.length; i; i -= 1) {
27695    b = bytes[i - 1];
27696    for (j = 8; j; j -= 1) {
27697      bits.push(b % 2 ? 1 : 0); b = b >> 1;
27698    }
27699  }
27700  bits.reverse();
27701  str = bits.join('');
27702
27703  // Unpack sign, exponent, fraction
27704  bias = (1 << (ebits - 1)) - 1;
27705  s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
27706  e = parseInt(str.substring(1, 1 + ebits), 2);
27707  f = parseInt(str.substring(1 + ebits), 2);
27708
27709  // Produce number
27710  if (e === (1 << ebits) - 1) {
27711    return f !== 0 ? NaN : s * Infinity;
27712  } else if (e > 0) {
27713    // Normalized
27714    return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
27715  } else if (f !== 0) {
27716    // Denormalized
27717    return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
27718  } else {
27719    return s < 0 ? -0 : 0;
27720  }
27721}
27722
27723function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
27724function packF64(v) { return packIEEE754(v, 11, 52); }
27725function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
27726function packF32(v) { return packIEEE754(v, 8, 23); }
27727
27728
27729//
27730// 3 The ArrayBuffer Type
27731//
27732
27733(function() {
27734
27735  /** @constructor */
27736  var ArrayBuffer = function ArrayBuffer(length) {
27737    length = ECMAScript.ToInt32(length);
27738    if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
27739
27740    this.byteLength = length;
27741    this._bytes = [];
27742    this._bytes.length = length;
27743
27744    var i;
27745    for (i = 0; i < this.byteLength; i += 1) {
27746      this._bytes[i] = 0;
27747    }
27748
27749    configureProperties(this);
27750  };
27751
27752  exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
27753
27754  //
27755  // 4 The ArrayBufferView Type
27756  //
27757
27758  // NOTE: this constructor is not exported
27759  /** @constructor */
27760  var ArrayBufferView = function ArrayBufferView() {
27761    //this.buffer = null;
27762    //this.byteOffset = 0;
27763    //this.byteLength = 0;
27764  };
27765
27766  //
27767  // 5 The Typed Array View Types
27768  //
27769
27770  function makeConstructor(bytesPerElement, pack, unpack) {
27771    // Each TypedArray type requires a distinct constructor instance with
27772    // identical logic, which this produces.
27773
27774    var ctor;
27775    ctor = function(buffer, byteOffset, length) {
27776      var array, sequence, i, s;
27777
27778      if (!arguments.length || typeof arguments[0] === 'number') {
27779        // Constructor(unsigned long length)
27780        this.length = ECMAScript.ToInt32(arguments[0]);
27781        if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
27782
27783        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
27784        this.buffer = new ArrayBuffer(this.byteLength);
27785        this.byteOffset = 0;
27786      } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
27787        // Constructor(TypedArray array)
27788        array = arguments[0];
27789
27790        this.length = array.length;
27791        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
27792        this.buffer = new ArrayBuffer(this.byteLength);
27793        this.byteOffset = 0;
27794
27795        for (i = 0; i < this.length; i += 1) {
27796          this._setter(i, array._getter(i));
27797        }
27798      } else if (typeof arguments[0] === 'object' &&
27799                 !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
27800        // Constructor(sequence<type> array)
27801        sequence = arguments[0];
27802
27803        this.length = ECMAScript.ToUint32(sequence.length);
27804        this.byteLength = this.length * this.BYTES_PER_ELEMENT;
27805        this.buffer = new ArrayBuffer(this.byteLength);
27806        this.byteOffset = 0;
27807
27808        for (i = 0; i < this.length; i += 1) {
27809          s = sequence[i];
27810          this._setter(i, Number(s));
27811        }
27812      } else if (typeof arguments[0] === 'object' &&
27813                 (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
27814        // Constructor(ArrayBuffer buffer,
27815        //             optional unsigned long byteOffset, optional unsigned long length)
27816        this.buffer = buffer;
27817
27818        this.byteOffset = ECMAScript.ToUint32(byteOffset);
27819        if (this.byteOffset > this.buffer.byteLength) {
27820          throw new RangeError("byteOffset out of range");
27821        }
27822
27823        if (this.byteOffset % this.BYTES_PER_ELEMENT) {
27824          // The given byteOffset must be a multiple of the element
27825          // size of the specific type, otherwise an exception is raised.
27826          throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
27827        }
27828
27829        if (arguments.length < 3) {
27830          this.byteLength = this.buffer.byteLength - this.byteOffset;
27831
27832          if (this.byteLength % this.BYTES_PER_ELEMENT) {
27833            throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
27834          }
27835          this.length = this.byteLength / this.BYTES_PER_ELEMENT;
27836        } else {
27837          this.length = ECMAScript.ToUint32(length);
27838          this.byteLength = this.length * this.BYTES_PER_ELEMENT;
27839        }
27840
27841        if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
27842          throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
27843        }
27844      } else {
27845        throw new TypeError("Unexpected argument type(s)");
27846      }
27847
27848      this.constructor = ctor;
27849
27850      configureProperties(this);
27851      makeArrayAccessors(this);
27852    };
27853
27854    ctor.prototype = new ArrayBufferView();
27855    ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
27856    ctor.prototype._pack = pack;
27857    ctor.prototype._unpack = unpack;
27858    ctor.BYTES_PER_ELEMENT = bytesPerElement;
27859
27860    // getter type (unsigned long index);
27861    ctor.prototype._getter = function(index) {
27862      if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
27863
27864      index = ECMAScript.ToUint32(index);
27865      if (index >= this.length) {
27866        return undefined$1;
27867      }
27868
27869      var bytes = [], i, o;
27870      for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
27871           i < this.BYTES_PER_ELEMENT;
27872           i += 1, o += 1) {
27873        bytes.push(this.buffer._bytes[o]);
27874      }
27875      return this._unpack(bytes);
27876    };
27877
27878    // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
27879    ctor.prototype.get = ctor.prototype._getter;
27880
27881    // setter void (unsigned long index, type value);
27882    ctor.prototype._setter = function(index, value) {
27883      if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
27884
27885      index = ECMAScript.ToUint32(index);
27886      if (index >= this.length) {
27887        return undefined$1;
27888      }
27889
27890      var bytes = this._pack(value), i, o;
27891      for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
27892           i < this.BYTES_PER_ELEMENT;
27893           i += 1, o += 1) {
27894        this.buffer._bytes[o] = bytes[i];
27895      }
27896    };
27897
27898    // void set(TypedArray array, optional unsigned long offset);
27899    // void set(sequence<type> array, optional unsigned long offset);
27900    ctor.prototype.set = function(index, value) {
27901      if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
27902      var array, sequence, offset, len,
27903          i, s, d,
27904          byteOffset, byteLength, tmp;
27905
27906      if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
27907        // void set(TypedArray array, optional unsigned long offset);
27908        array = arguments[0];
27909        offset = ECMAScript.ToUint32(arguments[1]);
27910
27911        if (offset + array.length > this.length) {
27912          throw new RangeError("Offset plus length of array is out of range");
27913        }
27914
27915        byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
27916        byteLength = array.length * this.BYTES_PER_ELEMENT;
27917
27918        if (array.buffer === this.buffer) {
27919          tmp = [];
27920          for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
27921            tmp[i] = array.buffer._bytes[s];
27922          }
27923          for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
27924            this.buffer._bytes[d] = tmp[i];
27925          }
27926        } else {
27927          for (i = 0, s = array.byteOffset, d = byteOffset;
27928               i < byteLength; i += 1, s += 1, d += 1) {
27929            this.buffer._bytes[d] = array.buffer._bytes[s];
27930          }
27931        }
27932      } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
27933        // void set(sequence<type> array, optional unsigned long offset);
27934        sequence = arguments[0];
27935        len = ECMAScript.ToUint32(sequence.length);
27936        offset = ECMAScript.ToUint32(arguments[1]);
27937
27938        if (offset + len > this.length) {
27939          throw new RangeError("Offset plus length of array is out of range");
27940        }
27941
27942        for (i = 0; i < len; i += 1) {
27943          s = sequence[i];
27944          this._setter(offset + i, Number(s));
27945        }
27946      } else {
27947        throw new TypeError("Unexpected argument type(s)");
27948      }
27949    };
27950
27951    // TypedArray subarray(long begin, optional long end);
27952    ctor.prototype.subarray = function(start, end) {
27953      function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
27954
27955      start = ECMAScript.ToInt32(start);
27956      end = ECMAScript.ToInt32(end);
27957
27958      if (arguments.length < 1) { start = 0; }
27959      if (arguments.length < 2) { end = this.length; }
27960
27961      if (start < 0) { start = this.length + start; }
27962      if (end < 0) { end = this.length + end; }
27963
27964      start = clamp(start, 0, this.length);
27965      end = clamp(end, 0, this.length);
27966
27967      var len = end - start;
27968      if (len < 0) {
27969        len = 0;
27970      }
27971
27972      return new this.constructor(
27973        this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
27974    };
27975
27976    return ctor;
27977  }
27978
27979  var Int8Array = makeConstructor(1, packI8, unpackI8);
27980  var Uint8Array = makeConstructor(1, packU8, unpackU8);
27981  var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
27982  var Int16Array = makeConstructor(2, packI16, unpackI16);
27983  var Uint16Array = makeConstructor(2, packU16, unpackU16);
27984  var Int32Array = makeConstructor(4, packI32, unpackI32);
27985  var Uint32Array = makeConstructor(4, packU32, unpackU32);
27986  var Float32Array = makeConstructor(4, packF32, unpackF32);
27987  var Float64Array = makeConstructor(8, packF64, unpackF64);
27988
27989  exports.Int8Array = exports.Int8Array || Int8Array;
27990  exports.Uint8Array = exports.Uint8Array || Uint8Array;
27991  exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
27992  exports.Int16Array = exports.Int16Array || Int16Array;
27993  exports.Uint16Array = exports.Uint16Array || Uint16Array;
27994  exports.Int32Array = exports.Int32Array || Int32Array;
27995  exports.Uint32Array = exports.Uint32Array || Uint32Array;
27996  exports.Float32Array = exports.Float32Array || Float32Array;
27997  exports.Float64Array = exports.Float64Array || Float64Array;
27998}());
27999
28000//
28001// 6 The DataView View Type
28002//
28003
28004(function() {
28005  function r(array, index) {
28006    return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
28007  }
28008
28009  var IS_BIG_ENDIAN = (function() {
28010    var u16array = new(exports.Uint16Array)([0x1234]),
28011        u8array = new(exports.Uint8Array)(u16array.buffer);
28012    return r(u8array, 0) === 0x12;
28013  }());
28014
28015  // Constructor(ArrayBuffer buffer,
28016  //             optional unsigned long byteOffset,
28017  //             optional unsigned long byteLength)
28018  /** @constructor */
28019  var DataView = function DataView(buffer, byteOffset, byteLength) {
28020    if (arguments.length === 0) {
28021      buffer = new exports.ArrayBuffer(0);
28022    } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
28023      throw new TypeError("TypeError");
28024    }
28025
28026    this.buffer = buffer || new exports.ArrayBuffer(0);
28027
28028    this.byteOffset = ECMAScript.ToUint32(byteOffset);
28029    if (this.byteOffset > this.buffer.byteLength) {
28030      throw new RangeError("byteOffset out of range");
28031    }
28032
28033    if (arguments.length < 3) {
28034      this.byteLength = this.buffer.byteLength - this.byteOffset;
28035    } else {
28036      this.byteLength = ECMAScript.ToUint32(byteLength);
28037    }
28038
28039    if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
28040      throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
28041    }
28042
28043    configureProperties(this);
28044  };
28045
28046  function makeGetter(arrayType) {
28047    return function(byteOffset, littleEndian) {
28048
28049      byteOffset = ECMAScript.ToUint32(byteOffset);
28050
28051      if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
28052        throw new RangeError("Array index out of range");
28053      }
28054      byteOffset += this.byteOffset;
28055
28056      var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
28057          bytes = [], i;
28058      for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
28059        bytes.push(r(uint8Array, i));
28060      }
28061
28062      if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
28063        bytes.reverse();
28064      }
28065
28066      return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0);
28067    };
28068  }
28069
28070  DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
28071  DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
28072  DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
28073  DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
28074  DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
28075  DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
28076  DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
28077  DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
28078
28079  function makeSetter(arrayType) {
28080    return function(byteOffset, value, littleEndian) {
28081
28082      byteOffset = ECMAScript.ToUint32(byteOffset);
28083      if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
28084        throw new RangeError("Array index out of range");
28085      }
28086
28087      // Get bytes
28088      var typeArray = new arrayType([value]),
28089          byteArray = new exports.Uint8Array(typeArray.buffer),
28090          bytes = [], i, byteView;
28091
28092      for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
28093        bytes.push(r(byteArray, i));
28094      }
28095
28096      // Flip if necessary
28097      if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
28098        bytes.reverse();
28099      }
28100
28101      // Write them
28102      byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
28103      byteView.set(bytes);
28104    };
28105  }
28106
28107  DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
28108  DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
28109  DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
28110  DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
28111  DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
28112  DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
28113  DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
28114  DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
28115
28116  exports.DataView = exports.DataView || DataView;
28117
28118}());
28119}(typedarray));
28120
28121var Writable = require$$1.Writable;
28122var inherits = inherits$2.exports;
28123var bufferFrom = bufferFrom_1;
28124
28125if (typeof Uint8Array === 'undefined') {
28126  var U8 = typedarray.Uint8Array;
28127} else {
28128  var U8 = Uint8Array;
28129}
28130
28131function ConcatStream(opts, cb) {
28132  if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
28133
28134  if (typeof opts === 'function') {
28135    cb = opts;
28136    opts = {};
28137  }
28138  if (!opts) opts = {};
28139
28140  var encoding = opts.encoding;
28141  var shouldInferEncoding = false;
28142
28143  if (!encoding) {
28144    shouldInferEncoding = true;
28145  } else {
28146    encoding =  String(encoding).toLowerCase();
28147    if (encoding === 'u8' || encoding === 'uint8') {
28148      encoding = 'uint8array';
28149    }
28150  }
28151
28152  Writable.call(this, { objectMode: true });
28153
28154  this.encoding = encoding;
28155  this.shouldInferEncoding = shouldInferEncoding;
28156
28157  if (cb) this.on('finish', function () { cb(this.getBody()); });
28158  this.body = [];
28159}
28160
28161var concatStream = ConcatStream;
28162inherits(ConcatStream, Writable);
28163
28164ConcatStream.prototype._write = function(chunk, enc, next) {
28165  this.body.push(chunk);
28166  next();
28167};
28168
28169ConcatStream.prototype.inferEncoding = function (buff) {
28170  var firstBuffer = buff === undefined ? this.body[0] : buff;
28171  if (Buffer.isBuffer(firstBuffer)) return 'buffer'
28172  if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
28173  if (Array.isArray(firstBuffer)) return 'array'
28174  if (typeof firstBuffer === 'string') return 'string'
28175  if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
28176  return 'buffer'
28177};
28178
28179ConcatStream.prototype.getBody = function () {
28180  if (!this.encoding && this.body.length === 0) return []
28181  if (this.shouldInferEncoding) this.encoding = this.inferEncoding();
28182  if (this.encoding === 'array') return arrayConcat(this.body)
28183  if (this.encoding === 'string') return stringConcat(this.body)
28184  if (this.encoding === 'buffer') return bufferConcat(this.body)
28185  if (this.encoding === 'uint8array') return u8Concat(this.body)
28186  return this.body
28187};
28188
28189function isArrayish (arr) {
28190  return /Array\]$/.test(Object.prototype.toString.call(arr))
28191}
28192
28193function isBufferish (p) {
28194  return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
28195}
28196
28197function stringConcat (parts) {
28198  var strings = [];
28199  for (var i = 0; i < parts.length; i++) {
28200    var p = parts[i];
28201    if (typeof p === 'string') {
28202      strings.push(p);
28203    } else if (Buffer.isBuffer(p)) {
28204      strings.push(p);
28205    } else if (isBufferish(p)) {
28206      strings.push(bufferFrom(p));
28207    } else {
28208      strings.push(bufferFrom(String(p)));
28209    }
28210  }
28211  if (Buffer.isBuffer(parts[0])) {
28212    strings = Buffer.concat(strings);
28213    strings = strings.toString('utf8');
28214  } else {
28215    strings = strings.join('');
28216  }
28217  return strings
28218}
28219
28220function bufferConcat (parts) {
28221  var bufs = [];
28222  for (var i = 0; i < parts.length; i++) {
28223    var p = parts[i];
28224    if (Buffer.isBuffer(p)) {
28225      bufs.push(p);
28226    } else if (isBufferish(p)) {
28227      bufs.push(bufferFrom(p));
28228    } else {
28229      bufs.push(bufferFrom(String(p)));
28230    }
28231  }
28232  return Buffer.concat(bufs)
28233}
28234
28235function arrayConcat (parts) {
28236  var res = [];
28237  for (var i = 0; i < parts.length; i++) {
28238    res.push.apply(res, parts[i]);
28239  }
28240  return res
28241}
28242
28243function u8Concat (parts) {
28244  var len = 0;
28245  for (var i = 0; i < parts.length; i++) {
28246    if (typeof parts[i] === 'string') {
28247      parts[i] = bufferFrom(parts[i]);
28248    }
28249    len += parts[i].length;
28250  }
28251  var u8 = new U8(len);
28252  for (var i = 0, offset = 0; i < parts.length; i++) {
28253    var part = parts[i];
28254    for (var j = 0; j < part.length; j++) {
28255      u8[offset++] = part[j];
28256    }
28257  }
28258  return u8
28259}
28260
28261/**
28262 * @typedef {import('vfile').VFile} VFile
28263 * @typedef {import('trough').Callback} Callback
28264 * @typedef {import('./index.js').Settings} Settings
28265 */
28266
28267const debug$9 = createDebug('unified-engine:file-set-pipeline:stdin');
28268
28269/**
28270 * @param {Context} context
28271 * @param {Settings} settings
28272 * @param {Callback} next
28273 */
28274function stdin(context, settings, next) {
28275  if (settings.files && settings.files.length > 0) {
28276    debug$9('Ignoring `streamIn`');
28277
28278    /** @type {Error|undefined} */
28279    let error;
28280
28281    if (settings.filePath) {
28282      error = new Error(
28283        'Do not pass both `--file-path` and real files.\nDid you mean to pass stdin instead of files?'
28284      );
28285    }
28286
28287    next(error);
28288
28289    return
28290  }
28291
28292  // @ts-expect-error: does exist on `stdin`.
28293  if (settings.streamIn.isTTY) {
28294    debug$9('Cannot read from `tty` stream');
28295    next(new Error('No input'));
28296
28297    return
28298  }
28299
28300  debug$9('Reading from `streamIn`');
28301
28302  settings.streamIn.pipe(
28303    concatStream({encoding: 'string'}, (value) => {
28304      const file = toVFile(settings.filePath);
28305
28306      debug$9('Read from `streamIn`');
28307
28308      file.cwd = settings.cwd;
28309      file.value = value;
28310      file.data.unifiedEngineGiven = true;
28311      file.data.unifiedEngineStreamIn = true;
28312
28313      context.files = [file];
28314
28315      // If `out` was not set, set `out`.
28316      settings.out =
28317        settings.out === null || settings.out === undefined
28318          ? true
28319          : settings.out;
28320
28321      next();
28322    })
28323  );
28324}
28325
28326/**
28327 * @typedef {import('vfile').VFile} VFile
28328 * @typedef {import('trough').Pipeline} Pipeline
28329 */
28330
28331class FileSet extends EventEmitter$1 {
28332  /**
28333   * FileSet constructor.
28334   * A FileSet is created to process multiple files through unified processors.
28335   * This set, containing all files, is exposed to plugins as an argument to the
28336   * attacher.
28337   */
28338  constructor() {
28339    super();
28340
28341    /** @type {Array.<VFile>} */
28342    this.files = [];
28343    /** @type {string[]} */
28344    this.origins = [];
28345    /** @type {Completer[]} */
28346    this.plugins = [];
28347    /** @type {number} */
28348    this.expected = 0;
28349    /** @type {number} */
28350    this.actual = 0;
28351    /** @type {Pipeline} */
28352    this.pipeline = trough();
28353
28354    // Called when a single file has completed it’s pipeline, triggering `done`
28355    // when all files are complete.
28356    this.on('one', () => {
28357      this.actual++;
28358
28359      if (this.actual >= this.expected) {
28360        this.emit('done');
28361      }
28362    });
28363  }
28364
28365  /**
28366   * Access the files in a set.
28367   */
28368  valueOf() {
28369    return this.files
28370  }
28371
28372  /**
28373   * Attach middleware to the pipeline on `fileSet`.
28374   *
28375   * @param {Completer} plugin
28376   */
28377  use(plugin) {
28378    const pipeline = this.pipeline;
28379    let duplicate = false;
28380
28381    if (plugin && plugin.pluginId) {
28382      duplicate = this.plugins.some((fn) => fn.pluginId === plugin.pluginId);
28383    }
28384
28385    if (!duplicate && this.plugins.includes(plugin)) {
28386      duplicate = true;
28387    }
28388
28389    if (!duplicate) {
28390      this.plugins.push(plugin);
28391      pipeline.use(plugin);
28392    }
28393
28394    return this
28395  }
28396
28397  /**
28398   * Add a file to be processed.
28399   * The given file is processed like other files with a few differences:
28400   *
28401   * *   Ignored when their file path is already added
28402   * *   Never written to the file system or streamOut
28403   * *   Not reported for
28404   *
28405   * @param {string|VFile} file
28406   */
28407  add(file) {
28408    if (typeof file === 'string') {
28409      file = toVFile(file);
28410    }
28411
28412    // Prevent files from being added multiple times.
28413    if (this.origins.includes(file.history[0])) {
28414      return this
28415    }
28416
28417    this.origins.push(file.history[0]);
28418
28419    // Add.
28420    this.valueOf().push(file);
28421    this.expected++;
28422
28423    // Force an asynchronous operation.
28424    // This ensures that files which fall through the file pipeline immediately
28425    // (such as, when already fatally failed) still queue up correctly.
28426    setImmediate(() => {
28427      this.emit('add', file);
28428    });
28429
28430    return this
28431  }
28432}
28433
28434/**
28435 * @typedef {import('vfile').VFile} VFile
28436 * @typedef {import('trough').Callback} Callback
28437 * @typedef {import('./index.js').Context} Context
28438 */
28439
28440const debug$8 = createDebug('unified-engine:file-pipeline:read');
28441
28442/**
28443 * Fill a file with its value when not already filled.
28444 *
28445 * @param {Context} context
28446 * @param {VFile} file
28447 * @param {Callback} next
28448 */
28449function read$1(context, file, next) {
28450  let filePath = file.path;
28451
28452  if (file.value || file.data.unifiedEngineStreamIn) {
28453    debug$8('Not reading file `%s` with `value`', filePath);
28454    next();
28455  } else if (statistics(file).fatal) {
28456    debug$8('Not reading failed file `%s`', filePath);
28457    next();
28458  } else {
28459    filePath = path$c.resolve(context.settings.cwd, filePath);
28460
28461    debug$8('Reading `%s` in `%s`', filePath, 'utf8');
28462    fs$a.readFile(filePath, 'utf8', (error, value) => {
28463      debug$8('Read `%s` (error: %s)', filePath, error);
28464
28465      file.value = value || '';
28466
28467      next(error);
28468    });
28469  }
28470}
28471
28472/**
28473 * Has own property.
28474 *
28475 * @type {Function}
28476 */
28477
28478var has = Object.prototype.hasOwnProperty;
28479
28480/**
28481 * To string.
28482 *
28483 * @type {Function}
28484 */
28485
28486var toString$1 = Object.prototype.toString;
28487
28488/**
28489 * Test whether a value is "empty".
28490 *
28491 * @param {Mixed} val
28492 * @return {Boolean}
28493 */
28494
28495function isEmpty(val) {
28496  // Null and Undefined...
28497  if (val == null) return true
28498
28499  // Booleans...
28500  if ('boolean' == typeof val) return false
28501
28502  // Numbers...
28503  if ('number' == typeof val) return val === 0
28504
28505  // Strings...
28506  if ('string' == typeof val) return val.length === 0
28507
28508  // Functions...
28509  if ('function' == typeof val) return val.length === 0
28510
28511  // Arrays...
28512  if (Array.isArray(val)) return val.length === 0
28513
28514  // Errors...
28515  if (val instanceof Error) return val.message === ''
28516
28517  // Objects...
28518  if (val.toString == toString$1) {
28519    switch (val.toString()) {
28520
28521      // Maps, Sets, Files and Errors...
28522      case '[object File]':
28523      case '[object Map]':
28524      case '[object Set]': {
28525        return val.size === 0
28526      }
28527
28528      // Plain objects...
28529      case '[object Object]': {
28530        for (var key in val) {
28531          if (has.call(val, key)) return false
28532        }
28533
28534        return true
28535      }
28536    }
28537  }
28538
28539  // Anything else...
28540  return false
28541}
28542
28543/**
28544 * Export `isEmpty`.
28545 *
28546 * @type {Function}
28547 */
28548
28549var lib$1 = isEmpty;
28550
28551/**
28552 * @typedef {import('vfile').VFile} VFile
28553 * @typedef {import('trough').Callback} Callback
28554 * @typedef {import('./index.js').Context} Context
28555 */
28556
28557const debug$7 = createDebug('unified-engine:file-pipeline:configure');
28558
28559/**
28560 * Collect configuration for a file based on the context.
28561 *
28562 * @param {Context} context
28563 * @param {VFile} file
28564 * @param {Callback} next
28565 */
28566function configure$2(context, file, next) {
28567  if (statistics(file).fatal) {
28568    return next()
28569  }
28570
28571  context.configuration.load(file.path, (error, configuration) => {
28572    let index = -1;
28573
28574    if (!configuration) {
28575      return next(error)
28576    }
28577
28578    // Could be missing if a `configTransform` returns weird things.
28579    /* c8 ignore next 1 */
28580    const plugins = configuration.plugins || [];
28581
28582    // Store configuration on the context object.
28583    debug$7('Using settings `%j`', configuration.settings);
28584    context.processor.data('settings', configuration.settings);
28585
28586    debug$7('Using `%d` plugins', plugins.length);
28587
28588    while (++index < plugins.length) {
28589      const plugin = plugins[index][0];
28590      let options = plugins[index][1];
28591
28592      if (options === false) {
28593        continue
28594      }
28595
28596      // Allow for default arguments in es2020.
28597      /* c8 ignore next 6 */
28598      if (
28599        options === null ||
28600        (typeof options === 'object' && lib$1(options))
28601      ) {
28602        options = undefined;
28603      }
28604
28605      debug$7(
28606        'Using plugin `%s`, with options `%j`',
28607        // @ts-expect-error: `displayName` sure can exist on functions.
28608        plugin.displayName || plugin.name || 'function',
28609        options
28610      );
28611
28612      try {
28613        context.processor.use(plugin, options, context.fileSet);
28614        /* Should not happen anymore! */
28615        /* c8 ignore next 3 */
28616      } catch (error_) {
28617        return next(error_)
28618      }
28619    }
28620
28621    next();
28622  });
28623}
28624
28625/**
28626 * @typedef {import('vfile').VFile} VFile
28627 * @typedef {import('./index.js').Context} Context
28628 */
28629
28630const debug$6 = createDebug('unified-engine:file-pipeline:parse');
28631
28632/**
28633 * Fill a file with a tree.
28634 *
28635 * @param {Context} context
28636 * @param {VFile} file
28637 */
28638function parse$2(context, file) {
28639  if (statistics(file).fatal) {
28640    return
28641  }
28642
28643  if (context.settings.treeIn) {
28644    debug$6('Not parsing already parsed document');
28645
28646    try {
28647      context.tree = parseJson_1(file.toString());
28648    } catch (error) {
28649      const message = file.message(
28650        new Error('Cannot read file as JSON\n' + error.message)
28651      );
28652      message.fatal = true;
28653    }
28654
28655    // Add the preferred extension to ensure the file, when serialized, is
28656    // correctly recognised.
28657    // Only add it if there is a path — not if the file is for example stdin.
28658    if (file.path) {
28659      file.extname = context.settings.extensions[0];
28660    }
28661
28662    file.value = '';
28663
28664    return
28665  }
28666
28667  debug$6('Parsing `%s`', file.path);
28668
28669  context.tree = context.processor.parse(file);
28670
28671  debug$6('Parsed document');
28672}
28673
28674/**
28675 * @typedef {import('vfile').VFile} VFile
28676 * @typedef {import('trough').Callback} Callback
28677 * @typedef {import('./index.js').Context} Context
28678 */
28679
28680const debug$5 = createDebug('unified-engine:file-pipeline:transform');
28681
28682/**
28683 * Transform the tree associated with a file with configured plugins.
28684 *
28685 * @param {Context} context
28686 * @param {VFile} file
28687 * @param {Callback} next
28688 */
28689function transform$2(context, file, next) {
28690  if (statistics(file).fatal) {
28691    next();
28692  } else {
28693    debug$5('Transforming document `%s`', file.path);
28694    // @ts-expect-error: `tree` is defined at this point.
28695    context.processor.run(context.tree, file, (error, node) => {
28696      debug$5('Transformed document (error: %s)', error);
28697      context.tree = node;
28698      next(error);
28699    });
28700  }
28701}
28702
28703/**
28704 * @typedef {import('vfile').VFile} VFile
28705 * @typedef {import('trough').Callback} Callback
28706 * @typedef {import('./index.js').Context} Context
28707 */
28708
28709const debug$4 = createDebug('unified-engine:file-pipeline:queue');
28710
28711const own$a = {}.hasOwnProperty;
28712
28713/**
28714 * Queue all files which came this far.
28715 * When the last file gets here, run the file-set pipeline and flush the queue.
28716 *
28717 * @param {Context} context
28718 * @param {VFile} file
28719 * @param {Callback} next
28720 */
28721function queue(context, file, next) {
28722  let origin = file.history[0];
28723  // @ts-expect-error: store a completion map on the `fileSet`.
28724  let map = context.fileSet.complete;
28725  let complete = true;
28726
28727  if (!map) {
28728    map = {};
28729    // @ts-expect-error: store a completion map on the `fileSet`.
28730    context.fileSet.complete = map;
28731  }
28732
28733  debug$4('Queueing `%s`', origin);
28734
28735  map[origin] = next;
28736
28737  const files = context.fileSet.valueOf();
28738  let index = -1;
28739  while (++index < files.length) {
28740    each(files[index]);
28741  }
28742
28743  if (!complete) {
28744    debug$4('Not flushing: some files cannot be flushed');
28745    return
28746  }
28747
28748  // @ts-expect-error: Reset map.
28749  context.fileSet.complete = {};
28750  context.fileSet.pipeline.run(context.fileSet, done);
28751
28752  /**
28753   * @param {VFile} file
28754   */
28755  function each(file) {
28756    const key = file.history[0];
28757
28758    if (statistics(file).fatal) {
28759      return
28760    }
28761
28762    if (typeof map[key] === 'function') {
28763      debug$4('`%s` can be flushed', key);
28764    } else {
28765      debug$4('Interupting flush: `%s` is not finished', key);
28766      complete = false;
28767    }
28768  }
28769
28770  /**
28771   * @param {Error|Null} error
28772   */
28773  function done(error) {
28774    debug$4('Flushing: all files can be flushed');
28775
28776    // Flush.
28777    for (origin in map) {
28778      if (own$a.call(map, origin)) {
28779        map[origin](error);
28780      }
28781    }
28782  }
28783}
28784
28785var own$9 = {}.hasOwnProperty;
28786
28787var bold = ansiColor(1, 22);
28788var dim = ansiColor(2, 22);
28789var yellow = ansiColor(33, 39);
28790var green = ansiColor(32, 39);
28791
28792// ANSI color regex.
28793/* eslint-disable-next-line no-control-regex */
28794var colorExpression = /(?:(?:\u001B\[)|\u009B)(?:\d{1,3})?(?:(?:;\d{0,3})*)?[A-M|f-m]|\u001B[A-M]/g;
28795
28796/**
28797 * Inspects a node, without using color.
28798 *
28799 * @param {unknown} node
28800 * @param {InspectOptions} [options]
28801 * @returns {string}
28802 */
28803function inspectNoColor(node, options) {
28804  return inspectColor(node, options).replace(colorExpression, '')
28805}
28806
28807/**
28808 * Inspects a node, using color.
28809 *
28810 * @param {unknown} tree
28811 * @param {InspectOptions} [options]
28812 * @returns {string}
28813 */
28814function inspectColor(tree, options) {
28815  var positions =
28816    !options ||
28817    options.showPositions === null ||
28818    options.showPositions === undefined
28819      ? true
28820      : options.showPositions;
28821
28822  return inspectValue(tree)
28823
28824  /**
28825   * @param {unknown} node
28826   * @returns {string}
28827   */
28828  function inspectValue(node) {
28829    if (node && typeof node === 'object' && 'length' in node) {
28830      // @ts-ignore looks like a list of nodes.
28831      return inspectNodes(node)
28832    }
28833
28834    // @ts-ignore looks like a single node.
28835    if (node && node.type) {
28836      // @ts-ignore looks like a single node.
28837      return inspectTree(node)
28838    }
28839
28840    return inspectNonTree(node)
28841  }
28842
28843  /**
28844   * @param {unknown} value
28845   * @returns {string}
28846   */
28847  function inspectNonTree(value) {
28848    return JSON.stringify(value)
28849  }
28850
28851  /**
28852   * @param {Node[]} nodes
28853   * @returns {string}
28854   */
28855  function inspectNodes(nodes) {
28856    /** @type {Array.<string>} */
28857    var result = [];
28858    var index = -1;
28859
28860    while (++index < nodes.length) {
28861      result.push(
28862        dim((index < nodes.length - 1 ? '├' : '└') + '─' + index) +
28863          ' ' +
28864          indent(
28865            inspectValue(nodes[index]),
28866            (index < nodes.length - 1 ? dim('│') : ' ') + '   ',
28867            true
28868          )
28869      );
28870    }
28871
28872    return result.join('\n')
28873  }
28874
28875  /**
28876   * @param {Object.<string, unknown>} object
28877   * @returns {string}
28878   */
28879  function inspectFields(object) {
28880    /** @type {Array.<string>} */
28881    var result = [];
28882    /** @type {string} */
28883    var key;
28884    /** @type {unknown} */
28885    var value;
28886    /** @type {string} */
28887    var formatted;
28888
28889    for (key in object) {
28890      /* c8 ignore next 1 */
28891      if (!own$9.call(object, key)) continue
28892
28893      value = object[key];
28894
28895      if (
28896        value === undefined ||
28897        // Standard keys defined by unist that we format differently.
28898        // <https://github.com/syntax-tree/unist>
28899        key === 'type' ||
28900        key === 'value' ||
28901        key === 'children' ||
28902        key === 'position' ||
28903        // Ignore `name` (from xast) and `tagName` (from `hast`) when string.
28904        (typeof value === 'string' && (key === 'name' || key === 'tagName'))
28905      ) {
28906        continue
28907      }
28908
28909      // A single node.
28910      if (
28911        value &&
28912        typeof value === 'object' &&
28913        // @ts-ignore looks like a node.
28914        value.type &&
28915        key !== 'data' &&
28916        key !== 'attributes' &&
28917        key !== 'properties'
28918      ) {
28919        // @ts-ignore looks like a node.
28920        formatted = inspectTree(value);
28921      }
28922      // A list of nodes.
28923      else if (
28924        value &&
28925        typeof value === 'object' &&
28926        'length' in value &&
28927        value[0] &&
28928        value[0].type
28929      ) {
28930        // @ts-ignore looks like a list of nodes.
28931        formatted = '\n' + inspectNodes(value);
28932      } else {
28933        formatted = inspectNonTree(value);
28934      }
28935
28936      result.push(
28937        key + dim(':') + (/\s/.test(formatted.charAt(0)) ? '' : ' ') + formatted
28938      );
28939    }
28940
28941    return indent(
28942      result.join('\n'),
28943      // @ts-ignore looks like a parent node.
28944      (object.children && object.children.length > 0 ? dim('│') : ' ') + ' '
28945    )
28946  }
28947
28948  /**
28949   * @param {Node} node
28950   * @returns {string}
28951   */
28952  function inspectTree(node) {
28953    var result = [formatNode(node)];
28954    var fields = inspectFields(node);
28955    // @ts-ignore looks like a parent.
28956    var content = inspectNodes(node.children || []);
28957    if (fields) result.push(fields);
28958    if (content) result.push(content);
28959    return result.join('\n')
28960  }
28961
28962  /**
28963   * Colored node formatter.
28964   *
28965   * @param {Node} node
28966   * @returns {string}
28967   */
28968  function formatNode(node) {
28969    var result = [bold(node.type)];
28970    var kind = node.tagName || node.name;
28971    var position = positions ? stringifyPosition(node.position) : '';
28972
28973    if (typeof kind === 'string') {
28974      result.push('<', kind, '>');
28975    }
28976
28977    if (node.children) {
28978      // @ts-ignore looks like a parent.
28979      result.push(dim('['), yellow(node.children.length), dim(']'));
28980    } else if (typeof node.value === 'string') {
28981      result.push(' ', green(inspectNonTree(node.value)));
28982    }
28983
28984    if (position) {
28985      result.push(' ', dim('('), position, dim(')'));
28986    }
28987
28988    return result.join('')
28989  }
28990}
28991
28992/**
28993 * @param {string} value
28994 * @param {string} indentation
28995 * @param {boolean} [ignoreFirst=false]
28996 * @returns {string}
28997 */
28998function indent(value, indentation, ignoreFirst) {
28999  var lines = value.split('\n');
29000  var index = ignoreFirst ? 0 : -1;
29001
29002  if (!value) return value
29003
29004  while (++index < lines.length) {
29005    lines[index] = indentation + lines[index];
29006  }
29007
29008  return lines.join('\n')
29009}
29010
29011/**
29012 * @param {Position} value
29013 * @returns {string}
29014 */
29015function stringifyPosition(value) {
29016  /** @type {Position} */
29017  // @ts-ignore
29018  var position = value || {};
29019  /** @type {Array.<string>} */
29020  var result = [];
29021  /** @type {Array.<string>} */
29022  var positions = [];
29023  /** @type {Array.<string>} */
29024  var offsets = [];
29025
29026  point(position.start);
29027  point(position.end);
29028
29029  if (positions.length > 0) result.push(positions.join('-'));
29030  if (offsets.length > 0) result.push(offsets.join('-'));
29031
29032  return result.join(', ')
29033
29034  /**
29035   * @param {Point} value
29036   */
29037  function point(value) {
29038    if (value) {
29039      positions.push((value.line || 1) + ':' + (value.column || 1));
29040
29041      if ('offset' in value) {
29042        offsets.push(String(value.offset || 0));
29043      }
29044    }
29045  }
29046}
29047
29048/**
29049 * Factory to wrap values in ANSI colours.
29050 *
29051 * @param {number} open
29052 * @param {number} close
29053 * @returns {function(string): string}
29054 */
29055function ansiColor(open, close) {
29056  return color
29057
29058  /**
29059   * @param {string} value
29060   * @returns {string}
29061   */
29062  function color(value) {
29063    return '\u001B[' + open + 'm' + value + '\u001B[' + close + 'm'
29064  }
29065}
29066
29067/**
29068 * @typedef {import('vfile').VFile} VFile
29069 * @typedef {import('./index.js').Context} Context
29070 */
29071
29072const debug$3 = createDebug('unified-engine:file-pipeline:stringify');
29073
29074/**
29075 * Stringify a tree.
29076 *
29077 * @param {Context} context
29078 * @param {VFile} file
29079 */
29080function stringify$1(context, file) {
29081  /** @type {unknown} */
29082  let value;
29083
29084  if (statistics(file).fatal) {
29085    debug$3('Not compiling failed document');
29086    return
29087  }
29088
29089  if (
29090    !context.settings.output &&
29091    !context.settings.out &&
29092    !context.settings.alwaysStringify
29093  ) {
29094    debug$3('Not compiling document without output settings');
29095    return
29096  }
29097
29098  debug$3('Compiling `%s`', file.path);
29099
29100  if (context.settings.inspect) {
29101    // Add a `txt` extension if there is a path.
29102    if (file.path) {
29103      file.extname = '.txt';
29104    }
29105
29106    value =
29107      (context.settings.color ? inspectColor : inspectNoColor)(context.tree) +
29108      '\n';
29109  } else if (context.settings.treeOut) {
29110    // Add a `json` extension to ensure the file is correctly seen as JSON.
29111    // Only add it if there is a path — not if the file is for example stdin.
29112    if (file.path) {
29113      file.extname = '.json';
29114    }
29115
29116    // Add the line feed to create a valid UNIX file.
29117    value = JSON.stringify(context.tree, null, 2) + '\n';
29118  } else {
29119    // @ts-expect-error: `tree` is defined if we came this far.
29120    value = context.processor.stringify(context.tree, file);
29121  }
29122
29123  if (value === undefined || value === null) ; else if (typeof value === 'string' || isBuffer(value)) {
29124    // @ts-expect-error: `isBuffer` checks buffer.
29125    file.value = value;
29126  } else {
29127    file.result = value;
29128  }
29129
29130  debug$3('Serialized document');
29131}
29132
29133/**
29134 * @typedef {import('vfile').VFile} VFile
29135 * @typedef {import('trough').Callback} Callback
29136 * @typedef {import('./index.js').Context} Context
29137 */
29138
29139const debug$2 = createDebug('unified-engine:file-pipeline:copy');
29140
29141/**
29142 * Move a file.
29143 *
29144 * @param {Context} context
29145 * @param {VFile} file
29146 * @param {Callback} next
29147 */
29148function copy(context, file, next) {
29149  const output = context.settings.output;
29150  const currentPath = file.path;
29151
29152  if (typeof output !== 'string') {
29153    debug$2('Not copying');
29154    next();
29155    return
29156  }
29157
29158  const outpath = path$c.resolve(context.settings.cwd, output);
29159
29160  debug$2('Copying `%s`', currentPath);
29161
29162  fs$a.stat(outpath, (error, stats) => {
29163    if (error) {
29164      if (
29165        error.code !== 'ENOENT' ||
29166        output.charAt(output.length - 1) === path$c.sep
29167      ) {
29168        return next(
29169          new Error('Cannot read output directory. Error:\n' + error.message)
29170        )
29171      }
29172
29173      // This is either given an error, or the parent exists which is a directory,
29174      // but we should keep the basename of the given file.
29175      fs$a.stat(path$c.dirname(outpath), (error) => {
29176        if (error) {
29177          next(
29178            new Error('Cannot read parent directory. Error:\n' + error.message)
29179          );
29180        } else {
29181          done(false);
29182        }
29183      });
29184    } else {
29185      done(stats.isDirectory());
29186    }
29187  });
29188
29189  /**
29190   * @param {boolean} directory
29191   */
29192  function done(directory) {
29193    if (!directory && context.fileSet.expected > 1) {
29194      return next(
29195        new Error('Cannot write multiple files to single output: ' + outpath)
29196      )
29197    }
29198
29199    file[directory ? 'dirname' : 'path'] = path$c.relative(file.cwd, outpath);
29200
29201    debug$2('Copying document from %s to %s', currentPath, file.path);
29202
29203    next();
29204  }
29205}
29206
29207/**
29208 * @typedef {import('vfile').VFile} VFile
29209 * @typedef {import('trough').Callback} Callback
29210 * @typedef {import('./index.js').Context} Context
29211 */
29212
29213const debug$1 = createDebug('unified-engine:file-pipeline:stdout');
29214
29215/**
29216 * Write a virtual file to `streamOut`.
29217 * Ignored when `output` is given, more than one file was processed, or `out`
29218 * is false.
29219 *
29220 * @param {Context} context
29221 * @param {VFile} file
29222 * @param {Callback} next
29223 */
29224function stdout(context, file, next) {
29225  if (!file.data.unifiedEngineGiven) {
29226    debug$1('Ignoring programmatically added file');
29227    next();
29228  } else if (
29229    statistics(file).fatal ||
29230    context.settings.output ||
29231    !context.settings.out
29232  ) {
29233    debug$1('Ignoring writing to `streamOut`');
29234    next();
29235  } else {
29236    debug$1('Writing document to `streamOut`');
29237    context.settings.streamOut.write(file.toString(), next);
29238  }
29239}
29240
29241/**
29242 * @typedef {import('vfile').VFile} VFile
29243 * @typedef {import('trough').Callback} Callback
29244 * @typedef {import('./index.js').Context} Context
29245 */
29246
29247const debug = createDebug('unified-engine:file-pipeline:file-system');
29248
29249/**
29250 * Write a virtual file to the file-system.
29251 * Ignored when `output` is not given.
29252 *
29253 * @param {Context} context
29254 * @param {VFile} file
29255 * @param {Callback} next
29256 */
29257function fileSystem(context, file, next) {
29258  if (!context.settings.output) {
29259    debug('Ignoring writing to file-system');
29260    return next()
29261  }
29262
29263  if (!file.data.unifiedEngineGiven) {
29264    debug('Ignoring programmatically added file');
29265    return next()
29266  }
29267
29268  let destinationPath = file.path;
29269
29270  if (!destinationPath) {
29271    debug('Cannot write file without a `destinationPath`');
29272    return next(new Error('Cannot write file without an output path'))
29273  }
29274
29275  if (statistics(file).fatal) {
29276    debug('Cannot write file with a fatal error');
29277    return next()
29278  }
29279
29280  destinationPath = path$c.resolve(context.settings.cwd, destinationPath);
29281  debug('Writing document to `%s`', destinationPath);
29282
29283  file.stored = true;
29284  fs$a.writeFile(destinationPath, file.toString(), next);
29285}
29286
29287/**
29288 * @typedef {import('trough').Pipeline} Pipeline
29289 * @typedef {import('vfile').VFile} VFile
29290 * @typedef {import('vfile-message').VFileMessage} VFileMessage
29291 * @typedef {import('unist').Node} Node
29292 * @typedef {import('unified').Processor} Processor
29293 * @typedef {import('../file-set.js').FileSet} FileSet
29294 * @typedef {import('../configuration.js').Configuration} Configuration
29295 * @typedef {import('../index.js').Settings} Settings
29296 */
29297
29298// This pipeline ensures each of the pipes always runs: even if the read pipe
29299// fails, queue and write run.
29300const filePipeline = trough()
29301  .use(chunk(trough().use(read$1).use(configure$2).use(parse$2).use(transform$2)))
29302  .use(chunk(trough().use(queue)))
29303  .use(chunk(trough().use(stringify$1).use(copy).use(stdout).use(fileSystem)));
29304
29305/**
29306 * Factory to run a pipe.
29307 * Wraps a pipe to trigger an error on the `file` in `context`, but still call
29308 * `next`.
29309 *
29310 * @param {Pipeline} pipe
29311 */
29312function chunk(pipe) {
29313  return run
29314
29315  /**
29316   * Run the bound pipe and handle any errors.
29317   *
29318   * @param {Context} context
29319   * @param {VFile} file
29320   * @param {() => void} next
29321   */
29322  function run(context, file, next) {
29323    pipe.run(context, file, (/** @type {VFileMessage|null} */ error) => {
29324      const messages = file.messages;
29325
29326      if (error) {
29327        const index = messages.indexOf(error);
29328
29329        if (index === -1) {
29330          Object.assign(file.message(error), {fatal: true});
29331        } else {
29332          messages[index].fatal = true;
29333        }
29334      }
29335
29336      next();
29337    });
29338  }
29339}
29340
29341/**
29342 * @typedef {import('vfile').VFile} VFile
29343 * @typedef {import('trough').Callback} Callback
29344 * @typedef {import('./index.js').Settings} Settings
29345 * @typedef {import('./index.js').Configuration} Configuration
29346 */
29347
29348/**
29349 * Transform all files.
29350 *
29351 * @param {Context} context
29352 * @param {Settings} settings
29353 * @param {Callback} next
29354 */
29355function transform$1(context, settings, next) {
29356  const fileSet = new FileSet();
29357
29358  context.fileSet = fileSet;
29359
29360  fileSet.on('add', (/** @type {VFile} */ file) => {
29361    filePipeline.run(
29362      {
29363        configuration: context.configuration,
29364        // Needed `any`s
29365        // type-coverage:ignore-next-line
29366        processor: settings.processor(),
29367        fileSet,
29368        settings
29369      },
29370      file,
29371      (/** @type {Error|null} */ error) => {
29372        // Does not occur as all failures in `filePipeLine` are failed on each
29373        // file.
29374        // Still, just to ensure things work in the future, we add an extra check.
29375        /* c8 ignore next 4 */
29376        if (error) {
29377          Object.assign(file.message(error), {fatal: true});
29378        }
29379
29380        fileSet.emit('one', file);
29381      }
29382    );
29383  });
29384
29385  fileSet.on('done', next);
29386
29387  if (context.files.length === 0) {
29388    next();
29389  } else {
29390    let index = -1;
29391    while (++index < context.files.length) {
29392      fileSet.add(context.files[index]);
29393    }
29394  }
29395}
29396
29397function hasFlag(flag, argv = process$1.argv) {
29398	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
29399	const position = argv.indexOf(prefix + flag);
29400	const terminatorPosition = argv.indexOf('--');
29401	return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
29402}
29403
29404const {env} = process$1;
29405
29406let flagForceColor;
29407if (hasFlag('no-color') ||
29408	hasFlag('no-colors') ||
29409	hasFlag('color=false') ||
29410	hasFlag('color=never')) {
29411	flagForceColor = 0;
29412} else if (hasFlag('color') ||
29413	hasFlag('colors') ||
29414	hasFlag('color=true') ||
29415	hasFlag('color=always')) {
29416	flagForceColor = 1;
29417}
29418
29419function envForceColor() {
29420	if ('FORCE_COLOR' in env) {
29421		if (env.FORCE_COLOR === 'true') {
29422			return 1;
29423		}
29424
29425		if (env.FORCE_COLOR === 'false') {
29426			return 0;
29427		}
29428
29429		return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
29430	}
29431}
29432
29433function translateLevel(level) {
29434	if (level === 0) {
29435		return false;
29436	}
29437
29438	return {
29439		level,
29440		hasBasic: true,
29441		has256: level >= 2,
29442		has16m: level >= 3
29443	};
29444}
29445
29446function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
29447	const noFlagForceColor = envForceColor();
29448	if (noFlagForceColor !== undefined) {
29449		flagForceColor = noFlagForceColor;
29450	}
29451
29452	const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
29453
29454	if (forceColor === 0) {
29455		return 0;
29456	}
29457
29458	if (sniffFlags) {
29459		if (hasFlag('color=16m') ||
29460			hasFlag('color=full') ||
29461			hasFlag('color=truecolor')) {
29462			return 3;
29463		}
29464
29465		if (hasFlag('color=256')) {
29466			return 2;
29467		}
29468	}
29469
29470	if (haveStream && !streamIsTTY && forceColor === undefined) {
29471		return 0;
29472	}
29473
29474	const min = forceColor || 0;
29475
29476	if (env.TERM === 'dumb') {
29477		return min;
29478	}
29479
29480	if (process$1.platform === 'win32') {
29481		// Windows 10 build 10586 is the first Windows release that supports 256 colors.
29482		// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
29483		const osRelease = require$$0$2.release().split('.');
29484		if (
29485			Number(osRelease[0]) >= 10 &&
29486			Number(osRelease[2]) >= 10586
29487		) {
29488			return Number(osRelease[2]) >= 14931 ? 3 : 2;
29489		}
29490
29491		return 1;
29492	}
29493
29494	if ('CI' in env) {
29495		if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
29496			return 1;
29497		}
29498
29499		return min;
29500	}
29501
29502	if ('TEAMCITY_VERSION' in env) {
29503		return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
29504	}
29505
29506	if (env.COLORTERM === 'truecolor') {
29507		return 3;
29508	}
29509
29510	if ('TERM_PROGRAM' in env) {
29511		const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
29512
29513		switch (env.TERM_PROGRAM) {
29514			case 'iTerm.app':
29515				return version >= 3 ? 3 : 2;
29516			case 'Apple_Terminal':
29517				return 2;
29518			// No default
29519		}
29520	}
29521
29522	if (/-256(color)?$/i.test(env.TERM)) {
29523		return 2;
29524	}
29525
29526	if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
29527		return 1;
29528	}
29529
29530	if ('COLORTERM' in env) {
29531		return 1;
29532	}
29533
29534	return min;
29535}
29536
29537function createSupportsColor(stream, options = {}) {
29538	const level = _supportsColor(stream, {
29539		streamIsTTY: stream && stream.isTTY,
29540		...options
29541	});
29542
29543	return translateLevel(level);
29544}
29545
29546const supportsColor = {
29547	stdout: createSupportsColor({isTTY: tty$1.isatty(1)}),
29548	stderr: createSupportsColor({isTTY: tty$1.isatty(2)})
29549};
29550
29551function ansiRegex({onlyFirst = false} = {}) {
29552	const pattern = [
29553		'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
29554		'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
29555	].join('|');
29556
29557	return new RegExp(pattern, onlyFirst ? undefined : 'g');
29558}
29559
29560function stripAnsi(string) {
29561	if (typeof string !== 'string') {
29562		throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
29563	}
29564
29565	return string.replace(ansiRegex(), '');
29566}
29567
29568/* eslint-disable yoda */
29569
29570function isFullwidthCodePoint(codePoint) {
29571	if (!Number.isInteger(codePoint)) {
29572		return false;
29573	}
29574
29575	// Code points are derived from:
29576	// https://unicode.org/Public/UNIDATA/EastAsianWidth.txt
29577	return codePoint >= 0x1100 && (
29578		codePoint <= 0x115F || // Hangul Jamo
29579		codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
29580		codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
29581		// CJK Radicals Supplement .. Enclosed CJK Letters and Months
29582		(0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) ||
29583		// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
29584		(0x3250 <= codePoint && codePoint <= 0x4DBF) ||
29585		// CJK Unified Ideographs .. Yi Radicals
29586		(0x4E00 <= codePoint && codePoint <= 0xA4C6) ||
29587		// Hangul Jamo Extended-A
29588		(0xA960 <= codePoint && codePoint <= 0xA97C) ||
29589		// Hangul Syllables
29590		(0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
29591		// CJK Compatibility Ideographs
29592		(0xF900 <= codePoint && codePoint <= 0xFAFF) ||
29593		// Vertical Forms
29594		(0xFE10 <= codePoint && codePoint <= 0xFE19) ||
29595		// CJK Compatibility Forms .. Small Form Variants
29596		(0xFE30 <= codePoint && codePoint <= 0xFE6B) ||
29597		// Halfwidth and Fullwidth Forms
29598		(0xFF01 <= codePoint && codePoint <= 0xFF60) ||
29599		(0xFFE0 <= codePoint && codePoint <= 0xFFE6) ||
29600		// Kana Supplement
29601		(0x1B000 <= codePoint && codePoint <= 0x1B001) ||
29602		// Enclosed Ideographic Supplement
29603		(0x1F200 <= codePoint && codePoint <= 0x1F251) ||
29604		// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
29605		(0x20000 <= codePoint && codePoint <= 0x3FFFD)
29606	);
29607}
29608
29609var emojiRegex = function () {
29610  // https://mths.be/emoji
29611  return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
29612};
29613
29614function stringWidth(string) {
29615	if (typeof string !== 'string' || string.length === 0) {
29616		return 0;
29617	}
29618
29619	string = stripAnsi(string);
29620
29621	if (string.length === 0) {
29622		return 0;
29623	}
29624
29625	string = string.replace(emojiRegex(), '  ');
29626
29627	let width = 0;
29628
29629	for (let index = 0; index < string.length; index++) {
29630		const codePoint = string.codePointAt(index);
29631
29632		// Ignore control characters
29633		if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {
29634			continue;
29635		}
29636
29637		// Ignore combining characters
29638		if (codePoint >= 0x300 && codePoint <= 0x36F) {
29639			continue;
29640		}
29641
29642		// Surrogates
29643		if (codePoint > 0xFFFF) {
29644			index++;
29645		}
29646
29647		width += isFullwidthCodePoint(codePoint) ? 2 : 1;
29648	}
29649
29650	return width;
29651}
29652
29653/*!
29654 * repeat-string <https://github.com/jonschlinkert/repeat-string>
29655 *
29656 * Copyright (c) 2014-2015, Jon Schlinkert.
29657 * Licensed under the MIT License.
29658 */
29659
29660/**
29661 * Results cache
29662 */
29663
29664var res = '';
29665var cache;
29666
29667/**
29668 * Expose `repeat`
29669 */
29670
29671var repeatString = repeat;
29672
29673/**
29674 * Repeat the given `string` the specified `number`
29675 * of times.
29676 *
29677 * **Example:**
29678 *
29679 * ```js
29680 * var repeat = require('repeat-string');
29681 * repeat('A', 5);
29682 * //=> AAAAA
29683 * ```
29684 *
29685 * @param {String} `string` The string to repeat
29686 * @param {Number} `number` The number of times to repeat the string
29687 * @return {String} Repeated string
29688 * @api public
29689 */
29690
29691function repeat(str, num) {
29692  if (typeof str !== 'string') {
29693    throw new TypeError('expected a string');
29694  }
29695
29696  // cover common, quick use cases
29697  if (num === 1) return str;
29698  if (num === 2) return str + str;
29699
29700  var max = str.length * num;
29701  if (cache !== str || typeof cache === 'undefined') {
29702    cache = str;
29703    res = '';
29704  } else if (res.length >= max) {
29705    return res.substr(0, max);
29706  }
29707
29708  while (max > res.length && num > 1) {
29709    if (num & 1) {
29710      res += str;
29711    }
29712
29713    num >>= 1;
29714    str += str;
29715  }
29716
29717  res += str;
29718  res = res.substr(0, max);
29719  return res;
29720}
29721
29722/**
29723 * @typedef {import('vfile').VFile} VFile
29724 * @typedef {import('vfile-message').VFileMessage} VFileMessage
29725 */
29726
29727var severities = {true: 2, false: 1, null: 0, undefined: 0};
29728
29729/**
29730 * @template {VFile} F
29731 * @param {F} file
29732 * @returns {F}
29733 */
29734function sort(file) {
29735  file.messages.sort(comparator);
29736  return file
29737}
29738
29739/**
29740 * @param {VFileMessage} a
29741 * @param {VFileMessage} b
29742 * @returns {number}
29743 */
29744function comparator(a, b) {
29745  return (
29746    check$1(a, b, 'line') ||
29747    check$1(a, b, 'column') ||
29748    severities[b.fatal] - severities[a.fatal] ||
29749    compare(a, b, 'source') ||
29750    compare(a, b, 'ruleId') ||
29751    compare(a, b, 'reason') ||
29752    0
29753  )
29754}
29755
29756/**
29757 * @param {VFileMessage} a
29758 * @param {VFileMessage} b
29759 * @param {string} property
29760 * @returns {number}
29761 */
29762function check$1(a, b, property) {
29763  return (a[property] || 0) - (b[property] || 0)
29764}
29765
29766/**
29767 * @param {VFileMessage} a
29768 * @param {VFileMessage} b
29769 * @param {string} property
29770 * @returns {number}
29771 */
29772function compare(a, b, property) {
29773  return String(a[property] || '').localeCompare(b[property] || '')
29774}
29775
29776/**
29777 * @typedef {import('vfile').VFile} VFile
29778 * @typedef {import('vfile-message').VFileMessage} VFileMessage
29779 * @typedef {import('vfile-statistics').Statistics} Statistics
29780 *
29781 * @typedef Options
29782 * @property {boolean} [color]
29783 * @property {boolean} [silent=false]
29784 * @property {boolean} [quiet=false]
29785 * @property {boolean} [verbose=false]
29786 * @property {string} [defaultName='<stdin>']
29787 *
29788 * @typedef _Row
29789 * @property {string} place
29790 * @property {string} label
29791 * @property {string} reason
29792 * @property {string} ruleId
29793 * @property {string} source
29794 *
29795 * @typedef _FileRow
29796 * @property {'file'} type
29797 * @property {VFile} file
29798 * @property {Statistics} stats
29799 *
29800 * @typedef {{[x: string]: number}} _Sizes
29801 *
29802 * @typedef _Info
29803 * @property {Array.<_FileRow|_Row>} rows
29804 * @property {Statistics} stats
29805 * @property {_Sizes} sizes
29806 */
29807
29808var own$8 = {}.hasOwnProperty;
29809
29810// @ts-ignore Types are incorrect.
29811var supported = supportsColor.stderr.hasBasic;
29812
29813// `log-symbols` without chalk, ignored for Windows:
29814/* c8 ignore next 4 */
29815var chars =
29816  process.platform === 'win32'
29817    ? {error: '×', warning: '‼'}
29818    : {error: '✖', warning: '⚠'};
29819
29820var labels = {true: 'error', false: 'warning', null: 'info', undefined: 'info'};
29821
29822/**
29823 * Report a file’s messages.
29824 *
29825 * @param {Error|VFile|Array.<VFile>} [files]
29826 * @param {Options} [options]
29827 * @returns {string}
29828 */
29829function reporter$1(files, options = {}) {
29830  /** @type {boolean} */
29831  var one;
29832
29833  if (!files) {
29834    return ''
29835  }
29836
29837  // Error.
29838  if ('name' in files && 'message' in files) {
29839    return String(files.stack || files)
29840  }
29841
29842  // One file.
29843  if (!Array.isArray(files)) {
29844    one = true;
29845    files = [files];
29846  }
29847
29848  return format(transform(files, options), one, options)
29849}
29850
29851/**
29852 * @param {Array.<VFile>} files
29853 * @param {Options} options
29854 * @returns {_Info}
29855 */
29856function transform(files, options) {
29857  var index = -1;
29858  /** @type {Array.<_FileRow|_Row>} */
29859  var rows = [];
29860  /** @type {Array.<VFileMessage>} */
29861  var all = [];
29862  /** @type {number} */
29863  var offset;
29864  /** @type {_Sizes} */
29865  var sizes = {};
29866  /** @type {Array.<VFileMessage>} */
29867  var messages;
29868  /** @type {VFileMessage} */
29869  var message;
29870  /** @type {_Row} */
29871  var row;
29872  /** @type {Array.<_Row>} */
29873  var messageRows;
29874  /** @type {string} */
29875  var key;
29876
29877  while (++index < files.length) {
29878    // @ts-ignore it works fine.
29879    messages = sort({messages: [...files[index].messages]}).messages;
29880    messageRows = [];
29881    offset = -1;
29882
29883    while (++offset < messages.length) {
29884      message = messages[offset];
29885
29886      if (!options.silent || message.fatal) {
29887        all.push(message);
29888
29889        row = {
29890          place: stringifyPosition$1(
29891            message.position.end.line && message.position.end.column
29892              ? message.position
29893              : message.position.start
29894          ),
29895          label: labels[message.fatal],
29896          reason:
29897            (message.stack || message.message) +
29898            (options.verbose && message.note ? '\n' + message.note : ''),
29899          ruleId: message.ruleId || '',
29900          source: message.source || ''
29901        };
29902
29903        for (key in row) {
29904          if (own$8.call(row, key)) {
29905            sizes[key] = Math.max(size$1(row[key]), sizes[key] || 0);
29906          }
29907        }
29908
29909        messageRows.push(row);
29910      }
29911    }
29912
29913    if ((!options.quiet && !options.silent) || messageRows.length > 0) {
29914      rows.push(
29915        {type: 'file', file: files[index], stats: statistics(messages)},
29916        ...messageRows
29917      );
29918    }
29919  }
29920
29921  return {rows, stats: statistics(all), sizes}
29922}
29923
29924/**
29925 * @param {_Info} map
29926 * @param {boolean} one
29927 * @param {Options} options
29928 */
29929function format(map, one, options) {
29930  /** @type {boolean} */
29931  var enabled =
29932    options.color === undefined || options.color === null
29933      ? supported
29934      : options.color;
29935  /** @type {Array.<string>} */
29936  var lines = [];
29937  var index = -1;
29938  /** @type {Statistics} */
29939  var stats;
29940  /** @type {_FileRow|_Row} */
29941  var row;
29942  /** @type {string} */
29943  var line;
29944  /** @type {string} */
29945  var reason;
29946  /** @type {string} */
29947  var rest;
29948  /** @type {RegExpMatchArray} */
29949  var match;
29950
29951  while (++index < map.rows.length) {
29952    row = map.rows[index];
29953
29954    if ('type' in row) {
29955      stats = row.stats;
29956      line = row.file.history[0] || options.defaultName || '<stdin>';
29957
29958      line =
29959        one && !options.defaultName && !row.file.history[0]
29960          ? ''
29961          : (enabled
29962              ? '\u001B[4m' /* Underline. */ +
29963                (stats.fatal
29964                  ? '\u001B[31m' /* Red. */
29965                  : stats.total
29966                  ? '\u001B[33m' /* Yellow. */
29967                  : '\u001B[32m') /* Green. */ +
29968                line +
29969                '\u001B[39m\u001B[24m'
29970              : line) +
29971            (row.file.stored && row.file.path !== row.file.history[0]
29972              ? ' > ' + row.file.path
29973              : '');
29974
29975      if (!stats.total) {
29976        line =
29977          (line ? line + ': ' : '') +
29978          (row.file.stored
29979            ? enabled
29980              ? '\u001B[33mwritten\u001B[39m' /* Yellow. */
29981              : 'written'
29982            : 'no issues found');
29983      }
29984
29985      if (line) {
29986        if (index && !('type' in map.rows[index - 1])) {
29987          lines.push('');
29988        }
29989
29990        lines.push(line);
29991      }
29992    } else {
29993      reason = row.reason;
29994      match = /\r?\n|\r/.exec(reason);
29995
29996      if (match) {
29997        rest = reason.slice(match.index);
29998        reason = reason.slice(0, match.index);
29999      } else {
30000        rest = '';
30001      }
30002
30003      lines.push(
30004        (
30005          '  ' +
30006          repeatString(' ', map.sizes.place - size$1(row.place)) +
30007          row.place +
30008          '  ' +
30009          (enabled
30010            ? (row.label === 'error'
30011                ? '\u001B[31m' /* Red. */
30012                : '\u001B[33m') /* Yellow. */ +
30013              row.label +
30014              '\u001B[39m'
30015            : row.label) +
30016          repeatString(' ', map.sizes.label - size$1(row.label)) +
30017          '  ' +
30018          reason +
30019          repeatString(' ', map.sizes.reason - size$1(reason)) +
30020          '  ' +
30021          row.ruleId +
30022          repeatString(' ', map.sizes.ruleId - size$1(row.ruleId)) +
30023          '  ' +
30024          (row.source || '')
30025        ).replace(/ +$/, '') + rest
30026      );
30027    }
30028  }
30029
30030  stats = map.stats;
30031
30032  if (stats.fatal || stats.warn) {
30033    line = '';
30034
30035    if (stats.fatal) {
30036      line =
30037        (enabled
30038          ? '\u001B[31m' /* Red. */ + chars.error + '\u001B[39m'
30039          : chars.error) +
30040        ' ' +
30041        stats.fatal +
30042        ' ' +
30043        (labels.true + (stats.fatal === 1 ? '' : 's'));
30044    }
30045
30046    if (stats.warn) {
30047      line =
30048        (line ? line + ', ' : '') +
30049        (enabled
30050          ? '\u001B[33m' /* Yellow. */ + chars.warning + '\u001B[39m'
30051          : chars.warning) +
30052        ' ' +
30053        stats.warn +
30054        ' ' +
30055        (labels.false + (stats.warn === 1 ? '' : 's'));
30056    }
30057
30058    if (stats.total !== stats.fatal && stats.total !== stats.warn) {
30059      line = stats.total + ' messages (' + line + ')';
30060    }
30061
30062    lines.push('', line);
30063  }
30064
30065  return lines.join('\n')
30066}
30067
30068/**
30069 * Get the length of `value`, ignoring ANSI sequences.
30070 *
30071 * @param {string} value
30072 * @returns {number}
30073 */
30074function size$1(value) {
30075  var match = /\r?\n|\r/.exec(value);
30076  return stringWidth(match ? value.slice(0, match.index) : value)
30077}
30078
30079/**
30080 * @typedef {import('vfile').VFile} VFile
30081 * @typedef {import('../index.js').VFileReporter} VFileReporter
30082 * @typedef {import('./index.js').Settings} Settings
30083 * @typedef {import('./index.js').Configuration} Configuration
30084 */
30085
30086/**
30087 * @typedef Context
30088 * @property {Array.<VFile>} files
30089 * @property {Configuration} [configuration]
30090 */
30091
30092/**
30093 * @param {Context} context
30094 * @param {Settings} settings
30095 */
30096async function log(context, settings) {
30097  /** @type {VFileReporter} */
30098  let func = reporter$1;
30099
30100  if (typeof settings.reporter === 'string') {
30101    try {
30102      // @ts-expect-error: Assume loaded value is a vfile reporter.
30103      func = await loadPlugin(settings.reporter, {
30104        cwd: settings.cwd,
30105        prefix: 'vfile-reporter'
30106      });
30107    } catch {
30108      throw new Error('Could not find reporter `' + settings.reporter + '`')
30109    }
30110  } else if (settings.reporter) {
30111    func = settings.reporter;
30112  }
30113
30114  let diagnostics = func(
30115    context.files.filter((file) => file.data.unifiedEngineGiven),
30116    Object.assign({}, settings.reporterOptions, {
30117      quiet: settings.quiet,
30118      silent: settings.silent,
30119      color: settings.color
30120    })
30121  );
30122
30123  if (diagnostics) {
30124    if (diagnostics.charAt(diagnostics.length - 1) !== '\n') {
30125      diagnostics += '\n';
30126    }
30127
30128    return new Promise((resolve) => {
30129      settings.streamError.write(diagnostics, resolve);
30130    })
30131  }
30132}
30133
30134/**
30135 * @typedef {import('vfile').VFile} VFile
30136 * @typedef {import('../configuration.js').Configuration} Configuration
30137 * @typedef {import('../index.js').Settings} Settings
30138 */
30139
30140const fileSetPipeline = trough()
30141  .use(configure$3)
30142  .use(fileSystem$1)
30143  .use(stdin)
30144  .use(transform$1)
30145  .use(log);
30146
30147/**
30148 * @typedef {import('vfile').VFile} VFile
30149 * @typedef {import('unified').Processor<any, any, any, any>} Processor
30150 * @typedef {import('./file-set.js').FileSet} FileSet
30151 * @typedef {import('./file-set.js').Completer} Completer
30152 * @typedef {import('./ignore.js').ResolveFrom} ResolveFrom
30153 * @typedef {import('./configuration.js').ConfigTransform} ConfigTransform
30154 * @typedef {import('./configuration.js').Preset} Preset
30155 *
30156 * @typedef VFileReporterFields
30157 * @property {boolean} [color]
30158 * @property {boolean} [quiet]
30159 * @property {boolean} [silent]
30160 *
30161 * @typedef {{[key: string]: unknown} & VFileReporterFields} VFileReporterOptions
30162 *
30163 * @callback VFileReporter
30164 * @param {VFile[]} files
30165 * @param {VFileReporterOptions} options
30166 * @returns {string}
30167 *
30168 * @typedef Settings
30169 * @property {Options['processor']} processor
30170 * @property {Exclude<Options['cwd'], undefined>} cwd
30171 * @property {Exclude<Options['files'], undefined>} files
30172 * @property {Exclude<Options['extensions'], undefined>} extensions
30173 * @property {Exclude<Options['streamIn'], undefined>} streamIn
30174 * @property {Options['filePath']} filePath
30175 * @property {Exclude<Options['streamOut'], undefined>} streamOut
30176 * @property {Exclude<Options['streamError'], undefined>} streamError
30177 * @property {Options['out']} out
30178 * @property {Options['output']} output
30179 * @property {Options['alwaysStringify']} alwaysStringify
30180 * @property {Options['tree']} tree
30181 * @property {Options['treeIn']} treeIn
30182 * @property {Options['treeOut']} treeOut
30183 * @property {Options['inspect']} inspect
30184 * @property {Options['rcName']} rcName
30185 * @property {Options['packageField']} packageField
30186 * @property {Options['detectConfig']} detectConfig
30187 * @property {Options['rcPath']} rcPath
30188 * @property {Exclude<Options['settings'], undefined>} settings
30189 * @property {Options['ignoreName']} ignoreName
30190 * @property {Options['detectIgnore']} detectIgnore
30191 * @property {Options['ignorePath']} ignorePath
30192 * @property {Options['ignorePathResolveFrom']} ignorePathResolveFrom
30193 * @property {Exclude<Options['ignorePatterns'], undefined>} ignorePatterns
30194 * @property {Options['silentlyIgnore']} silentlyIgnore
30195 * @property {Options['plugins']} plugins
30196 * @property {Options['pluginPrefix']} pluginPrefix
30197 * @property {Options['configTransform']} configTransform
30198 * @property {Options['defaultConfig']} defaultConfig
30199 * @property {Options['reporter']} reporter
30200 * @property {Options['reporterOptions']} reporterOptions
30201 * @property {Options['color']} color
30202 * @property {Options['silent']} silent
30203 * @property {Options['quiet']} quiet
30204 * @property {Options['frail']} frail
30205 *
30206 * @typedef Options
30207 *   Options for unified engine
30208 * @property {() => Processor} processor
30209 *   Unified processor to transform files
30210 * @property {string} [cwd]
30211 *   Directory to search files in, load plugins from, and more.
30212 *   Defaults to `process.cwd()`.
30213 * @property {Array<string|VFile>} [files]
30214 *   Paths or globs to files and directories, or virtual files, to process.
30215 * @property {string[]} [extensions]
30216 *   If `files` matches directories, include `files` with `extensions`
30217 * @property {NodeJS.ReadableStream} [streamIn]
30218 *   Stream to read from if no files are found or given.
30219 *   Defaults to `process.stdin`.
30220 * @property {string} [filePath]
30221 *   File path to process the given file on `streamIn` as.
30222 * @property {NodeJS.WritableStream} [streamOut]
30223 *   Stream to write processed files to.
30224 *   Defaults to `process.stdout`.
30225 * @property {NodeJS.WritableStream} [streamError]
30226 *   Stream to write the report (if any) to.
30227 *   Defaults to `process.stderr`.
30228 * @property {boolean} [out=false]
30229 *   Whether to write the processed file to `streamOut`
30230 * @property {boolean|string} [output=false]
30231 *   Whether to write successfully processed files, and where to.
30232 *
30233 *   * When `true`, overwrites the given files
30234 *   * When `false`, does not write to the file system
30235 *   * When pointing to an existing directory, files are written to that
30236 *     directory and keep their original basenames
30237 *   * When the parent directory of the given path exists and one file is
30238 *     processed, the file is written to the given path
30239 * @property {boolean} [alwaysStringify=false]
30240 *   Whether to always serialize successfully processed files.
30241 * @property {boolean} [tree=false]
30242 *   Whether to treat both input and output as a syntax tree.
30243 * @property {boolean} [treeIn]
30244 *   Whether to treat input as a syntax tree.
30245 *   Defaults to `options.tree`.
30246 * @property {boolean} [treeOut]
30247 *   Whether to treat output as a syntax tree.
30248 *   Defaults to `options.tree`.
30249 * @property {boolean} [inspect=false]
30250 *   Whether to output a formatted syntax tree.
30251 * @property {string} [rcName]
30252 *   Name of configuration files to load.
30253 * @property {string} [packageField]
30254 *   Property at which configuration can be found in `package.json` files
30255 * @property {boolean} [detectConfig]
30256 *   Whether to search for configuration files.
30257 *   Defaults to `true` if `rcName` or `packageField` are given
30258 * @property {string} [rcPath]
30259 *   Filepath to a configuration file to load.
30260 * @property {Preset['settings']} [settings]
30261 *   Configuration for the parser and compiler of the processor.
30262 * @property {string} [ignoreName]
30263 *   Name of ignore files to load.
30264 * @property {boolean} [detectIgnore]
30265 *   Whether to search for ignore files.
30266 *   Defaults to `true` if `ignoreName` is given.
30267 * @property {string} [ignorePath]
30268 *   Filepath to an ignore file to load.
30269 * @property {ResolveFrom} [ignorePathResolveFrom]
30270 *   Resolve patterns in `ignorePath` from the current working
30271 *   directory (`'cwd'`) or the ignore file’s directory (`'dir'`, default).
30272 * @property {string[]} [ignorePatterns]
30273 *   Patterns to ignore in addition to ignore files
30274 * @property {boolean} [silentlyIgnore=false]
30275 *   Skip given files if they are ignored.
30276 * @property {Preset['plugins']} [plugins]
30277 *   Plugins to use.
30278 * @property {string} [pluginPrefix]
30279 *   Prefix to use when searching for plugins
30280 * @property {ConfigTransform} [configTransform]
30281 *   Transform config files from a different schema.
30282 * @property {Preset} [defaultConfig]
30283 *   Default configuration to use if no config file is given or found.
30284 * @property {VFileReporter|string} [reporter]
30285 *   Reporter to use
30286 *   Defaults to `vfile-reporter`
30287 * @property {VFileReporterOptions} [reporterOptions]
30288 *   Config to pass to the used reporter.
30289 * @property {VFileReporterOptions['color']} [color=false]
30290 *   Whether to report with ANSI color sequences.
30291 * @property {VFileReporterOptions['silent']} [silent=false]
30292 *   Report only fatal errors
30293 * @property {VFileReporterOptions['quiet']} [quiet=false]
30294 *   Do not report successful files
30295 * @property {boolean} [frail=false]
30296 *   Call back with an unsuccessful (`1`) code on warnings as well as errors
30297 *
30298 * @typedef Context
30299 *   Processing context.
30300 * @property {VFile[]} [files]
30301 *   Processed files.
30302 * @property {FileSet} [fileSet]
30303 *   Internally used information
30304 *
30305 * @callback Callback
30306 *   Callback called when processing according to options is complete.
30307 *   Invoked with either a fatal error if processing went horribly wrong
30308 *   (probably due to incorrect configuration), or a status code and the
30309 *   processing context.
30310 * @param {Error|null} error
30311 * @param {0|1} [status]
30312 * @param {Context} [context]
30313 * @returns {void}
30314 */
30315
30316/**
30317 * Run the file set pipeline once.
30318 * `callback` is called with a fatal error, or with a status code (`0` on
30319 * success, `1` on failure).
30320 *
30321 * @param {Options} options
30322 * @param {Callback} callback
30323 */
30324function engine(options, callback) {
30325  /** @type {Settings} */
30326  const settings = {};
30327  /** @type {NodeJS.ReadStream} */
30328  // @ts-expect-error: `PassThrough` sure is readable.
30329  let stdin = new PassThrough();
30330
30331  try {
30332    stdin = process$2.stdin;
30333    // Obscure bug in Node (seen on Windows).
30334    // See: <https://github.com/nodejs/node/blob/f856234/lib/internal/process/stdio.js#L82>,
30335    // <https://github.com/AtomLinter/linter-markdown/pull/85>.
30336    /* c8 ignore next 1 */
30337  } catch {}
30338
30339  if (!callback) {
30340    throw new Error('Missing `callback`')
30341  }
30342
30343  // Needed `any`s
30344  // type-coverage:ignore-next-line
30345  if (!options || !options.processor) {
30346    return next(new Error('Missing `processor`'))
30347  }
30348
30349  // Processor.
30350  // Needed `any`s
30351  // type-coverage:ignore-next-line
30352  settings.processor = options.processor;
30353
30354  // Path to run as.
30355  settings.cwd = options.cwd || process$2.cwd();
30356
30357  // Input.
30358  settings.files = options.files || [];
30359  settings.extensions = (options.extensions || []).map((ext) =>
30360    ext.charAt(0) === '.' ? ext : '.' + ext
30361  );
30362
30363  settings.filePath = options.filePath;
30364  settings.streamIn = options.streamIn || stdin;
30365
30366  // Output.
30367  settings.streamOut = options.streamOut || process$2.stdout;
30368  settings.streamError = options.streamError || process$2.stderr;
30369  settings.alwaysStringify = options.alwaysStringify;
30370  settings.output = options.output;
30371  settings.out = options.out;
30372
30373  // Null overwrites config settings, `undefined` does not.
30374  if (settings.output === null || settings.output === undefined) {
30375    settings.output = undefined;
30376  }
30377
30378  if (settings.output && settings.out) {
30379    return next(new Error('Cannot accept both `output` and `out`'))
30380  }
30381
30382  // Process phase management.
30383  const tree = options.tree || false;
30384
30385  settings.treeIn = options.treeIn;
30386  settings.treeOut = options.treeOut;
30387  settings.inspect = options.inspect;
30388
30389  if (settings.treeIn === null || settings.treeIn === undefined) {
30390    settings.treeIn = tree;
30391  }
30392
30393  if (settings.treeOut === null || settings.treeOut === undefined) {
30394    settings.treeOut = tree;
30395  }
30396
30397  // Configuration.
30398  const detectConfig = options.detectConfig;
30399  const hasConfig = Boolean(options.rcName || options.packageField);
30400
30401  if (detectConfig && !hasConfig) {
30402    return next(
30403      new Error('Missing `rcName` or `packageField` with `detectConfig`')
30404    )
30405  }
30406
30407  settings.detectConfig =
30408    detectConfig === null || detectConfig === undefined
30409      ? hasConfig
30410      : detectConfig;
30411  settings.rcName = options.rcName;
30412  settings.rcPath = options.rcPath;
30413  settings.packageField = options.packageField;
30414  settings.settings = options.settings || {};
30415  settings.configTransform = options.configTransform;
30416  settings.defaultConfig = options.defaultConfig;
30417
30418  // Ignore.
30419  const detectIgnore = options.detectIgnore;
30420  const hasIgnore = Boolean(options.ignoreName);
30421
30422  settings.detectIgnore =
30423    detectIgnore === null || detectIgnore === undefined
30424      ? hasIgnore
30425      : detectIgnore;
30426  settings.ignoreName = options.ignoreName;
30427  settings.ignorePath = options.ignorePath;
30428  settings.ignorePathResolveFrom = options.ignorePathResolveFrom || 'dir';
30429  settings.ignorePatterns = options.ignorePatterns || [];
30430  settings.silentlyIgnore = Boolean(options.silentlyIgnore);
30431
30432  if (detectIgnore && !hasIgnore) {
30433    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
30434  }
30435
30436  // Plugins.
30437  settings.pluginPrefix = options.pluginPrefix;
30438  settings.plugins = options.plugins || [];
30439
30440  // Reporting.
30441  settings.reporter = options.reporter;
30442  settings.reporterOptions = options.reporterOptions;
30443  settings.color = options.color || false;
30444  settings.silent = options.silent;
30445  settings.quiet = options.quiet;
30446  settings.frail = options.frail;
30447
30448  // Process.
30449  fileSetPipeline.run({files: options.files || []}, settings, next);
30450
30451  /**
30452   * @param {Error|null} error
30453   * @param {Context} [context]
30454   */
30455  function next(error, context) {
30456    const stats = statistics((context || {}).files);
30457    const failed = Boolean(
30458      settings.frail ? stats.fatal || stats.warn : stats.fatal
30459    );
30460
30461    if (error) {
30462      callback(error);
30463    } else {
30464      callback(null, failed ? 1 : 0, context);
30465    }
30466  }
30467}
30468
30469var textTable = function (rows_, opts) {
30470    if (!opts) opts = {};
30471    var hsep = opts.hsep === undefined ? '  ' : opts.hsep;
30472    var align = opts.align || [];
30473    var stringLength = opts.stringLength
30474        || function (s) { return String(s).length; }
30475    ;
30476
30477    var dotsizes = reduce(rows_, function (acc, row) {
30478        forEach(row, function (c, ix) {
30479            var n = dotindex(c);
30480            if (!acc[ix] || n > acc[ix]) acc[ix] = n;
30481        });
30482        return acc;
30483    }, []);
30484
30485    var rows = map$2(rows_, function (row) {
30486        return map$2(row, function (c_, ix) {
30487            var c = String(c_);
30488            if (align[ix] === '.') {
30489                var index = dotindex(c);
30490                var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2)
30491                    - (stringLength(c) - index)
30492                ;
30493                return c + Array(size).join(' ');
30494            }
30495            else return c;
30496        });
30497    });
30498
30499    var sizes = reduce(rows, function (acc, row) {
30500        forEach(row, function (c, ix) {
30501            var n = stringLength(c);
30502            if (!acc[ix] || n > acc[ix]) acc[ix] = n;
30503        });
30504        return acc;
30505    }, []);
30506
30507    return map$2(rows, function (row) {
30508        return map$2(row, function (c, ix) {
30509            var n = (sizes[ix] - stringLength(c)) || 0;
30510            var s = Array(Math.max(n + 1, 1)).join(' ');
30511            if (align[ix] === 'r' || align[ix] === '.') {
30512                return s + c;
30513            }
30514            if (align[ix] === 'c') {
30515                return Array(Math.ceil(n / 2 + 1)).join(' ')
30516                    + c + Array(Math.floor(n / 2 + 1)).join(' ')
30517                ;
30518            }
30519
30520            return c + s;
30521        }).join(hsep).replace(/\s+$/, '');
30522    }).join('\n');
30523};
30524
30525function dotindex (c) {
30526    var m = /\.[^.]*$/.exec(c);
30527    return m ? m.index + 1 : c.length;
30528}
30529
30530function reduce (xs, f, init) {
30531    if (xs.reduce) return xs.reduce(f, init);
30532    var i = 0;
30533    var acc = arguments.length >= 3 ? init : xs[i++];
30534    for (; i < xs.length; i++) {
30535        f(acc, xs[i], i);
30536    }
30537    return acc;
30538}
30539
30540function forEach (xs, f) {
30541    if (xs.forEach) return xs.forEach(f);
30542    for (var i = 0; i < xs.length; i++) {
30543        f.call(xs, xs[i], i);
30544    }
30545}
30546
30547function map$2 (xs, f) {
30548    if (xs.map) return xs.map(f);
30549    var res = [];
30550    for (var i = 0; i < xs.length; i++) {
30551        res.push(f.call(xs, xs[i], i));
30552    }
30553    return res;
30554}
30555
30556var camelcase$1 = {exports: {}};
30557
30558const preserveCamelCase = (string, locale) => {
30559	let isLastCharLower = false;
30560	let isLastCharUpper = false;
30561	let isLastLastCharUpper = false;
30562
30563	for (let i = 0; i < string.length; i++) {
30564		const character = string[i];
30565
30566		if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
30567			string = string.slice(0, i) + '-' + string.slice(i);
30568			isLastCharLower = false;
30569			isLastLastCharUpper = isLastCharUpper;
30570			isLastCharUpper = true;
30571			i++;
30572		} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
30573			string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
30574			isLastLastCharUpper = isLastCharUpper;
30575			isLastCharUpper = false;
30576			isLastCharLower = true;
30577		} else {
30578			isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
30579			isLastLastCharUpper = isLastCharUpper;
30580			isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
30581		}
30582	}
30583
30584	return string;
30585};
30586
30587const preserveConsecutiveUppercase = input => {
30588	return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
30589};
30590
30591const postProcess = (input, options) => {
30592	return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale))
30593		.replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
30594};
30595
30596const camelCase = (input, options) => {
30597	if (!(typeof input === 'string' || Array.isArray(input))) {
30598		throw new TypeError('Expected the input to be `string | string[]`');
30599	}
30600
30601	options = {
30602		pascalCase: false,
30603		preserveConsecutiveUppercase: false,
30604		...options
30605	};
30606
30607	if (Array.isArray(input)) {
30608		input = input.map(x => x.trim())
30609			.filter(x => x.length)
30610			.join('-');
30611	} else {
30612		input = input.trim();
30613	}
30614
30615	if (input.length === 0) {
30616		return '';
30617	}
30618
30619	if (input.length === 1) {
30620		return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
30621	}
30622
30623	const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
30624
30625	if (hasUpperCase) {
30626		input = preserveCamelCase(input, options.locale);
30627	}
30628
30629	input = input.replace(/^[_.\- ]+/, '');
30630
30631	if (options.preserveConsecutiveUppercase) {
30632		input = preserveConsecutiveUppercase(input);
30633	} else {
30634		input = input.toLocaleLowerCase();
30635	}
30636
30637	if (options.pascalCase) {
30638		input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
30639	}
30640
30641	return postProcess(input, options);
30642};
30643
30644camelcase$1.exports = camelCase;
30645// TODO: Remove this for the next major release
30646camelcase$1.exports.default = camelCase;
30647
30648var camelcase = camelcase$1.exports;
30649
30650var minimist = function (args, opts) {
30651    if (!opts) opts = {};
30652
30653    var flags = { bools : {}, strings : {}, unknownFn: null };
30654
30655    if (typeof opts['unknown'] === 'function') {
30656        flags.unknownFn = opts['unknown'];
30657    }
30658
30659    if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
30660      flags.allBools = true;
30661    } else {
30662      [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
30663          flags.bools[key] = true;
30664      });
30665    }
30666
30667    var aliases = {};
30668    Object.keys(opts.alias || {}).forEach(function (key) {
30669        aliases[key] = [].concat(opts.alias[key]);
30670        aliases[key].forEach(function (x) {
30671            aliases[x] = [key].concat(aliases[key].filter(function (y) {
30672                return x !== y;
30673            }));
30674        });
30675    });
30676
30677    [].concat(opts.string).filter(Boolean).forEach(function (key) {
30678        flags.strings[key] = true;
30679        if (aliases[key]) {
30680            flags.strings[aliases[key]] = true;
30681        }
30682     });
30683
30684    var defaults = opts['default'] || {};
30685
30686    var argv = { _ : [] };
30687    Object.keys(flags.bools).forEach(function (key) {
30688        setArg(key, defaults[key] === undefined ? false : defaults[key]);
30689    });
30690
30691    var notFlags = [];
30692
30693    if (args.indexOf('--') !== -1) {
30694        notFlags = args.slice(args.indexOf('--')+1);
30695        args = args.slice(0, args.indexOf('--'));
30696    }
30697
30698    function argDefined(key, arg) {
30699        return (flags.allBools && /^--[^=]+$/.test(arg)) ||
30700            flags.strings[key] || flags.bools[key] || aliases[key];
30701    }
30702
30703    function setArg (key, val, arg) {
30704        if (arg && flags.unknownFn && !argDefined(key, arg)) {
30705            if (flags.unknownFn(arg) === false) return;
30706        }
30707
30708        var value = !flags.strings[key] && isNumber(val)
30709            ? Number(val) : val
30710        ;
30711        setKey(argv, key.split('.'), value);
30712
30713        (aliases[key] || []).forEach(function (x) {
30714            setKey(argv, x.split('.'), value);
30715        });
30716    }
30717
30718    function setKey (obj, keys, value) {
30719        var o = obj;
30720        for (var i = 0; i < keys.length-1; i++) {
30721            var key = keys[i];
30722            if (key === '__proto__') return;
30723            if (o[key] === undefined) o[key] = {};
30724            if (o[key] === Object.prototype || o[key] === Number.prototype
30725                || o[key] === String.prototype) o[key] = {};
30726            if (o[key] === Array.prototype) o[key] = [];
30727            o = o[key];
30728        }
30729
30730        var key = keys[keys.length - 1];
30731        if (key === '__proto__') return;
30732        if (o === Object.prototype || o === Number.prototype
30733            || o === String.prototype) o = {};
30734        if (o === Array.prototype) o = [];
30735        if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
30736            o[key] = value;
30737        }
30738        else if (Array.isArray(o[key])) {
30739            o[key].push(value);
30740        }
30741        else {
30742            o[key] = [ o[key], value ];
30743        }
30744    }
30745
30746    function aliasIsBoolean(key) {
30747      return aliases[key].some(function (x) {
30748          return flags.bools[x];
30749      });
30750    }
30751
30752    for (var i = 0; i < args.length; i++) {
30753        var arg = args[i];
30754
30755        if (/^--.+=/.test(arg)) {
30756            // Using [\s\S] instead of . because js doesn't support the
30757            // 'dotall' regex modifier. See:
30758            // http://stackoverflow.com/a/1068308/13216
30759            var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
30760            var key = m[1];
30761            var value = m[2];
30762            if (flags.bools[key]) {
30763                value = value !== 'false';
30764            }
30765            setArg(key, value, arg);
30766        }
30767        else if (/^--no-.+/.test(arg)) {
30768            var key = arg.match(/^--no-(.+)/)[1];
30769            setArg(key, false, arg);
30770        }
30771        else if (/^--.+/.test(arg)) {
30772            var key = arg.match(/^--(.+)/)[1];
30773            var next = args[i + 1];
30774            if (next !== undefined && !/^-/.test(next)
30775            && !flags.bools[key]
30776            && !flags.allBools
30777            && (aliases[key] ? !aliasIsBoolean(key) : true)) {
30778                setArg(key, next, arg);
30779                i++;
30780            }
30781            else if (/^(true|false)$/.test(next)) {
30782                setArg(key, next === 'true', arg);
30783                i++;
30784            }
30785            else {
30786                setArg(key, flags.strings[key] ? '' : true, arg);
30787            }
30788        }
30789        else if (/^-[^-]+/.test(arg)) {
30790            var letters = arg.slice(1,-1).split('');
30791
30792            var broken = false;
30793            for (var j = 0; j < letters.length; j++) {
30794                var next = arg.slice(j+2);
30795
30796                if (next === '-') {
30797                    setArg(letters[j], next, arg);
30798                    continue;
30799                }
30800
30801                if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
30802                    setArg(letters[j], next.split('=')[1], arg);
30803                    broken = true;
30804                    break;
30805                }
30806
30807                if (/[A-Za-z]/.test(letters[j])
30808                && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
30809                    setArg(letters[j], next, arg);
30810                    broken = true;
30811                    break;
30812                }
30813
30814                if (letters[j+1] && letters[j+1].match(/\W/)) {
30815                    setArg(letters[j], arg.slice(j+2), arg);
30816                    broken = true;
30817                    break;
30818                }
30819                else {
30820                    setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
30821                }
30822            }
30823
30824            var key = arg.slice(-1)[0];
30825            if (!broken && key !== '-') {
30826                if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
30827                && !flags.bools[key]
30828                && (aliases[key] ? !aliasIsBoolean(key) : true)) {
30829                    setArg(key, args[i+1], arg);
30830                    i++;
30831                }
30832                else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
30833                    setArg(key, args[i+1] === 'true', arg);
30834                    i++;
30835                }
30836                else {
30837                    setArg(key, flags.strings[key] ? '' : true, arg);
30838                }
30839            }
30840        }
30841        else {
30842            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
30843                argv._.push(
30844                    flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
30845                );
30846            }
30847            if (opts.stopEarly) {
30848                argv._.push.apply(argv._, args.slice(i + 1));
30849                break;
30850            }
30851        }
30852    }
30853
30854    Object.keys(defaults).forEach(function (key) {
30855        if (!hasKey(argv, key.split('.'))) {
30856            setKey(argv, key.split('.'), defaults[key]);
30857
30858            (aliases[key] || []).forEach(function (x) {
30859                setKey(argv, x.split('.'), defaults[key]);
30860            });
30861        }
30862    });
30863
30864    if (opts['--']) {
30865        argv['--'] = new Array();
30866        notFlags.forEach(function(key) {
30867            argv['--'].push(key);
30868        });
30869    }
30870    else {
30871        notFlags.forEach(function(key) {
30872            argv._.push(key);
30873        });
30874    }
30875
30876    return argv;
30877};
30878
30879function hasKey (obj, keys) {
30880    var o = obj;
30881    keys.slice(0,-1).forEach(function (key) {
30882        o = (o[key] || {});
30883    });
30884
30885    var key = keys[keys.length - 1];
30886    return key in o;
30887}
30888
30889function isNumber (x) {
30890    if (typeof x === 'number') return true;
30891    if (/^0x[0-9a-f]+$/i.test(x)) return true;
30892    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
30893}
30894
30895// This is a generated file. Do not edit.
30896var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
30897var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
30898var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
30899
30900var unicode = {
30901	Space_Separator: Space_Separator,
30902	ID_Start: ID_Start,
30903	ID_Continue: ID_Continue
30904};
30905
30906var util = {
30907    isSpaceSeparator (c) {
30908        return typeof c === 'string' && unicode.Space_Separator.test(c)
30909    },
30910
30911    isIdStartChar (c) {
30912        return typeof c === 'string' && (
30913            (c >= 'a' && c <= 'z') ||
30914        (c >= 'A' && c <= 'Z') ||
30915        (c === '$') || (c === '_') ||
30916        unicode.ID_Start.test(c)
30917        )
30918    },
30919
30920    isIdContinueChar (c) {
30921        return typeof c === 'string' && (
30922            (c >= 'a' && c <= 'z') ||
30923        (c >= 'A' && c <= 'Z') ||
30924        (c >= '0' && c <= '9') ||
30925        (c === '$') || (c === '_') ||
30926        (c === '\u200C') || (c === '\u200D') ||
30927        unicode.ID_Continue.test(c)
30928        )
30929    },
30930
30931    isDigit (c) {
30932        return typeof c === 'string' && /[0-9]/.test(c)
30933    },
30934
30935    isHexDigit (c) {
30936        return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
30937    },
30938};
30939
30940let source;
30941let parseState;
30942let stack;
30943let pos;
30944let line;
30945let column;
30946let token;
30947let key;
30948let root$1;
30949
30950var parse$1 = function parse (text, reviver) {
30951    source = String(text);
30952    parseState = 'start';
30953    stack = [];
30954    pos = 0;
30955    line = 1;
30956    column = 0;
30957    token = undefined;
30958    key = undefined;
30959    root$1 = undefined;
30960
30961    do {
30962        token = lex();
30963
30964        // This code is unreachable.
30965        // if (!parseStates[parseState]) {
30966        //     throw invalidParseState()
30967        // }
30968
30969        parseStates[parseState]();
30970    } while (token.type !== 'eof')
30971
30972    if (typeof reviver === 'function') {
30973        return internalize({'': root$1}, '', reviver)
30974    }
30975
30976    return root$1
30977};
30978
30979function internalize (holder, name, reviver) {
30980    const value = holder[name];
30981    if (value != null && typeof value === 'object') {
30982        for (const key in value) {
30983            const replacement = internalize(value, key, reviver);
30984            if (replacement === undefined) {
30985                delete value[key];
30986            } else {
30987                value[key] = replacement;
30988            }
30989        }
30990    }
30991
30992    return reviver.call(holder, name, value)
30993}
30994
30995let lexState;
30996let buffer;
30997let doubleQuote;
30998let sign;
30999let c;
31000
31001function lex () {
31002    lexState = 'default';
31003    buffer = '';
31004    doubleQuote = false;
31005    sign = 1;
31006
31007    for (;;) {
31008        c = peek();
31009
31010        // This code is unreachable.
31011        // if (!lexStates[lexState]) {
31012        //     throw invalidLexState(lexState)
31013        // }
31014
31015        const token = lexStates[lexState]();
31016        if (token) {
31017            return token
31018        }
31019    }
31020}
31021
31022function peek () {
31023    if (source[pos]) {
31024        return String.fromCodePoint(source.codePointAt(pos))
31025    }
31026}
31027
31028function read () {
31029    const c = peek();
31030
31031    if (c === '\n') {
31032        line++;
31033        column = 0;
31034    } else if (c) {
31035        column += c.length;
31036    } else {
31037        column++;
31038    }
31039
31040    if (c) {
31041        pos += c.length;
31042    }
31043
31044    return c
31045}
31046
31047const lexStates = {
31048    default () {
31049        switch (c) {
31050        case '\t':
31051        case '\v':
31052        case '\f':
31053        case ' ':
31054        case '\u00A0':
31055        case '\uFEFF':
31056        case '\n':
31057        case '\r':
31058        case '\u2028':
31059        case '\u2029':
31060            read();
31061            return
31062
31063        case '/':
31064            read();
31065            lexState = 'comment';
31066            return
31067
31068        case undefined:
31069            read();
31070            return newToken('eof')
31071        }
31072
31073        if (util.isSpaceSeparator(c)) {
31074            read();
31075            return
31076        }
31077
31078        // This code is unreachable.
31079        // if (!lexStates[parseState]) {
31080        //     throw invalidLexState(parseState)
31081        // }
31082
31083        return lexStates[parseState]()
31084    },
31085
31086    comment () {
31087        switch (c) {
31088        case '*':
31089            read();
31090            lexState = 'multiLineComment';
31091            return
31092
31093        case '/':
31094            read();
31095            lexState = 'singleLineComment';
31096            return
31097        }
31098
31099        throw invalidChar(read())
31100    },
31101
31102    multiLineComment () {
31103        switch (c) {
31104        case '*':
31105            read();
31106            lexState = 'multiLineCommentAsterisk';
31107            return
31108
31109        case undefined:
31110            throw invalidChar(read())
31111        }
31112
31113        read();
31114    },
31115
31116    multiLineCommentAsterisk () {
31117        switch (c) {
31118        case '*':
31119            read();
31120            return
31121
31122        case '/':
31123            read();
31124            lexState = 'default';
31125            return
31126
31127        case undefined:
31128            throw invalidChar(read())
31129        }
31130
31131        read();
31132        lexState = 'multiLineComment';
31133    },
31134
31135    singleLineComment () {
31136        switch (c) {
31137        case '\n':
31138        case '\r':
31139        case '\u2028':
31140        case '\u2029':
31141            read();
31142            lexState = 'default';
31143            return
31144
31145        case undefined:
31146            read();
31147            return newToken('eof')
31148        }
31149
31150        read();
31151    },
31152
31153    value () {
31154        switch (c) {
31155        case '{':
31156        case '[':
31157            return newToken('punctuator', read())
31158
31159        case 'n':
31160            read();
31161            literal('ull');
31162            return newToken('null', null)
31163
31164        case 't':
31165            read();
31166            literal('rue');
31167            return newToken('boolean', true)
31168
31169        case 'f':
31170            read();
31171            literal('alse');
31172            return newToken('boolean', false)
31173
31174        case '-':
31175        case '+':
31176            if (read() === '-') {
31177                sign = -1;
31178            }
31179
31180            lexState = 'sign';
31181            return
31182
31183        case '.':
31184            buffer = read();
31185            lexState = 'decimalPointLeading';
31186            return
31187
31188        case '0':
31189            buffer = read();
31190            lexState = 'zero';
31191            return
31192
31193        case '1':
31194        case '2':
31195        case '3':
31196        case '4':
31197        case '5':
31198        case '6':
31199        case '7':
31200        case '8':
31201        case '9':
31202            buffer = read();
31203            lexState = 'decimalInteger';
31204            return
31205
31206        case 'I':
31207            read();
31208            literal('nfinity');
31209            return newToken('numeric', Infinity)
31210
31211        case 'N':
31212            read();
31213            literal('aN');
31214            return newToken('numeric', NaN)
31215
31216        case '"':
31217        case "'":
31218            doubleQuote = (read() === '"');
31219            buffer = '';
31220            lexState = 'string';
31221            return
31222        }
31223
31224        throw invalidChar(read())
31225    },
31226
31227    identifierNameStartEscape () {
31228        if (c !== 'u') {
31229            throw invalidChar(read())
31230        }
31231
31232        read();
31233        const u = unicodeEscape();
31234        switch (u) {
31235        case '$':
31236        case '_':
31237            break
31238
31239        default:
31240            if (!util.isIdStartChar(u)) {
31241                throw invalidIdentifier()
31242            }
31243
31244            break
31245        }
31246
31247        buffer += u;
31248        lexState = 'identifierName';
31249    },
31250
31251    identifierName () {
31252        switch (c) {
31253        case '$':
31254        case '_':
31255        case '\u200C':
31256        case '\u200D':
31257            buffer += read();
31258            return
31259
31260        case '\\':
31261            read();
31262            lexState = 'identifierNameEscape';
31263            return
31264        }
31265
31266        if (util.isIdContinueChar(c)) {
31267            buffer += read();
31268            return
31269        }
31270
31271        return newToken('identifier', buffer)
31272    },
31273
31274    identifierNameEscape () {
31275        if (c !== 'u') {
31276            throw invalidChar(read())
31277        }
31278
31279        read();
31280        const u = unicodeEscape();
31281        switch (u) {
31282        case '$':
31283        case '_':
31284        case '\u200C':
31285        case '\u200D':
31286            break
31287
31288        default:
31289            if (!util.isIdContinueChar(u)) {
31290                throw invalidIdentifier()
31291            }
31292
31293            break
31294        }
31295
31296        buffer += u;
31297        lexState = 'identifierName';
31298    },
31299
31300    sign () {
31301        switch (c) {
31302        case '.':
31303            buffer = read();
31304            lexState = 'decimalPointLeading';
31305            return
31306
31307        case '0':
31308            buffer = read();
31309            lexState = 'zero';
31310            return
31311
31312        case '1':
31313        case '2':
31314        case '3':
31315        case '4':
31316        case '5':
31317        case '6':
31318        case '7':
31319        case '8':
31320        case '9':
31321            buffer = read();
31322            lexState = 'decimalInteger';
31323            return
31324
31325        case 'I':
31326            read();
31327            literal('nfinity');
31328            return newToken('numeric', sign * Infinity)
31329
31330        case 'N':
31331            read();
31332            literal('aN');
31333            return newToken('numeric', NaN)
31334        }
31335
31336        throw invalidChar(read())
31337    },
31338
31339    zero () {
31340        switch (c) {
31341        case '.':
31342            buffer += read();
31343            lexState = 'decimalPoint';
31344            return
31345
31346        case 'e':
31347        case 'E':
31348            buffer += read();
31349            lexState = 'decimalExponent';
31350            return
31351
31352        case 'x':
31353        case 'X':
31354            buffer += read();
31355            lexState = 'hexadecimal';
31356            return
31357        }
31358
31359        return newToken('numeric', sign * 0)
31360    },
31361
31362    decimalInteger () {
31363        switch (c) {
31364        case '.':
31365            buffer += read();
31366            lexState = 'decimalPoint';
31367            return
31368
31369        case 'e':
31370        case 'E':
31371            buffer += read();
31372            lexState = 'decimalExponent';
31373            return
31374        }
31375
31376        if (util.isDigit(c)) {
31377            buffer += read();
31378            return
31379        }
31380
31381        return newToken('numeric', sign * Number(buffer))
31382    },
31383
31384    decimalPointLeading () {
31385        if (util.isDigit(c)) {
31386            buffer += read();
31387            lexState = 'decimalFraction';
31388            return
31389        }
31390
31391        throw invalidChar(read())
31392    },
31393
31394    decimalPoint () {
31395        switch (c) {
31396        case 'e':
31397        case 'E':
31398            buffer += read();
31399            lexState = 'decimalExponent';
31400            return
31401        }
31402
31403        if (util.isDigit(c)) {
31404            buffer += read();
31405            lexState = 'decimalFraction';
31406            return
31407        }
31408
31409        return newToken('numeric', sign * Number(buffer))
31410    },
31411
31412    decimalFraction () {
31413        switch (c) {
31414        case 'e':
31415        case 'E':
31416            buffer += read();
31417            lexState = 'decimalExponent';
31418            return
31419        }
31420
31421        if (util.isDigit(c)) {
31422            buffer += read();
31423            return
31424        }
31425
31426        return newToken('numeric', sign * Number(buffer))
31427    },
31428
31429    decimalExponent () {
31430        switch (c) {
31431        case '+':
31432        case '-':
31433            buffer += read();
31434            lexState = 'decimalExponentSign';
31435            return
31436        }
31437
31438        if (util.isDigit(c)) {
31439            buffer += read();
31440            lexState = 'decimalExponentInteger';
31441            return
31442        }
31443
31444        throw invalidChar(read())
31445    },
31446
31447    decimalExponentSign () {
31448        if (util.isDigit(c)) {
31449            buffer += read();
31450            lexState = 'decimalExponentInteger';
31451            return
31452        }
31453
31454        throw invalidChar(read())
31455    },
31456
31457    decimalExponentInteger () {
31458        if (util.isDigit(c)) {
31459            buffer += read();
31460            return
31461        }
31462
31463        return newToken('numeric', sign * Number(buffer))
31464    },
31465
31466    hexadecimal () {
31467        if (util.isHexDigit(c)) {
31468            buffer += read();
31469            lexState = 'hexadecimalInteger';
31470            return
31471        }
31472
31473        throw invalidChar(read())
31474    },
31475
31476    hexadecimalInteger () {
31477        if (util.isHexDigit(c)) {
31478            buffer += read();
31479            return
31480        }
31481
31482        return newToken('numeric', sign * Number(buffer))
31483    },
31484
31485    string () {
31486        switch (c) {
31487        case '\\':
31488            read();
31489            buffer += escape();
31490            return
31491
31492        case '"':
31493            if (doubleQuote) {
31494                read();
31495                return newToken('string', buffer)
31496            }
31497
31498            buffer += read();
31499            return
31500
31501        case "'":
31502            if (!doubleQuote) {
31503                read();
31504                return newToken('string', buffer)
31505            }
31506
31507            buffer += read();
31508            return
31509
31510        case '\n':
31511        case '\r':
31512            throw invalidChar(read())
31513
31514        case '\u2028':
31515        case '\u2029':
31516            separatorChar(c);
31517            break
31518
31519        case undefined:
31520            throw invalidChar(read())
31521        }
31522
31523        buffer += read();
31524    },
31525
31526    start () {
31527        switch (c) {
31528        case '{':
31529        case '[':
31530            return newToken('punctuator', read())
31531
31532        // This code is unreachable since the default lexState handles eof.
31533        // case undefined:
31534        //     return newToken('eof')
31535        }
31536
31537        lexState = 'value';
31538    },
31539
31540    beforePropertyName () {
31541        switch (c) {
31542        case '$':
31543        case '_':
31544            buffer = read();
31545            lexState = 'identifierName';
31546            return
31547
31548        case '\\':
31549            read();
31550            lexState = 'identifierNameStartEscape';
31551            return
31552
31553        case '}':
31554            return newToken('punctuator', read())
31555
31556        case '"':
31557        case "'":
31558            doubleQuote = (read() === '"');
31559            lexState = 'string';
31560            return
31561        }
31562
31563        if (util.isIdStartChar(c)) {
31564            buffer += read();
31565            lexState = 'identifierName';
31566            return
31567        }
31568
31569        throw invalidChar(read())
31570    },
31571
31572    afterPropertyName () {
31573        if (c === ':') {
31574            return newToken('punctuator', read())
31575        }
31576
31577        throw invalidChar(read())
31578    },
31579
31580    beforePropertyValue () {
31581        lexState = 'value';
31582    },
31583
31584    afterPropertyValue () {
31585        switch (c) {
31586        case ',':
31587        case '}':
31588            return newToken('punctuator', read())
31589        }
31590
31591        throw invalidChar(read())
31592    },
31593
31594    beforeArrayValue () {
31595        if (c === ']') {
31596            return newToken('punctuator', read())
31597        }
31598
31599        lexState = 'value';
31600    },
31601
31602    afterArrayValue () {
31603        switch (c) {
31604        case ',':
31605        case ']':
31606            return newToken('punctuator', read())
31607        }
31608
31609        throw invalidChar(read())
31610    },
31611
31612    end () {
31613        // This code is unreachable since it's handled by the default lexState.
31614        // if (c === undefined) {
31615        //     read()
31616        //     return newToken('eof')
31617        // }
31618
31619        throw invalidChar(read())
31620    },
31621};
31622
31623function newToken (type, value) {
31624    return {
31625        type,
31626        value,
31627        line,
31628        column,
31629    }
31630}
31631
31632function literal (s) {
31633    for (const c of s) {
31634        const p = peek();
31635
31636        if (p !== c) {
31637            throw invalidChar(read())
31638        }
31639
31640        read();
31641    }
31642}
31643
31644function escape () {
31645    const c = peek();
31646    switch (c) {
31647    case 'b':
31648        read();
31649        return '\b'
31650
31651    case 'f':
31652        read();
31653        return '\f'
31654
31655    case 'n':
31656        read();
31657        return '\n'
31658
31659    case 'r':
31660        read();
31661        return '\r'
31662
31663    case 't':
31664        read();
31665        return '\t'
31666
31667    case 'v':
31668        read();
31669        return '\v'
31670
31671    case '0':
31672        read();
31673        if (util.isDigit(peek())) {
31674            throw invalidChar(read())
31675        }
31676
31677        return '\0'
31678
31679    case 'x':
31680        read();
31681        return hexEscape()
31682
31683    case 'u':
31684        read();
31685        return unicodeEscape()
31686
31687    case '\n':
31688    case '\u2028':
31689    case '\u2029':
31690        read();
31691        return ''
31692
31693    case '\r':
31694        read();
31695        if (peek() === '\n') {
31696            read();
31697        }
31698
31699        return ''
31700
31701    case '1':
31702    case '2':
31703    case '3':
31704    case '4':
31705    case '5':
31706    case '6':
31707    case '7':
31708    case '8':
31709    case '9':
31710        throw invalidChar(read())
31711
31712    case undefined:
31713        throw invalidChar(read())
31714    }
31715
31716    return read()
31717}
31718
31719function hexEscape () {
31720    let buffer = '';
31721    let c = peek();
31722
31723    if (!util.isHexDigit(c)) {
31724        throw invalidChar(read())
31725    }
31726
31727    buffer += read();
31728
31729    c = peek();
31730    if (!util.isHexDigit(c)) {
31731        throw invalidChar(read())
31732    }
31733
31734    buffer += read();
31735
31736    return String.fromCodePoint(parseInt(buffer, 16))
31737}
31738
31739function unicodeEscape () {
31740    let buffer = '';
31741    let count = 4;
31742
31743    while (count-- > 0) {
31744        const c = peek();
31745        if (!util.isHexDigit(c)) {
31746            throw invalidChar(read())
31747        }
31748
31749        buffer += read();
31750    }
31751
31752    return String.fromCodePoint(parseInt(buffer, 16))
31753}
31754
31755const parseStates = {
31756    start () {
31757        if (token.type === 'eof') {
31758            throw invalidEOF()
31759        }
31760
31761        push$1();
31762    },
31763
31764    beforePropertyName () {
31765        switch (token.type) {
31766        case 'identifier':
31767        case 'string':
31768            key = token.value;
31769            parseState = 'afterPropertyName';
31770            return
31771
31772        case 'punctuator':
31773            // This code is unreachable since it's handled by the lexState.
31774            // if (token.value !== '}') {
31775            //     throw invalidToken()
31776            // }
31777
31778            pop();
31779            return
31780
31781        case 'eof':
31782            throw invalidEOF()
31783        }
31784
31785        // This code is unreachable since it's handled by the lexState.
31786        // throw invalidToken()
31787    },
31788
31789    afterPropertyName () {
31790        // This code is unreachable since it's handled by the lexState.
31791        // if (token.type !== 'punctuator' || token.value !== ':') {
31792        //     throw invalidToken()
31793        // }
31794
31795        if (token.type === 'eof') {
31796            throw invalidEOF()
31797        }
31798
31799        parseState = 'beforePropertyValue';
31800    },
31801
31802    beforePropertyValue () {
31803        if (token.type === 'eof') {
31804            throw invalidEOF()
31805        }
31806
31807        push$1();
31808    },
31809
31810    beforeArrayValue () {
31811        if (token.type === 'eof') {
31812            throw invalidEOF()
31813        }
31814
31815        if (token.type === 'punctuator' && token.value === ']') {
31816            pop();
31817            return
31818        }
31819
31820        push$1();
31821    },
31822
31823    afterPropertyValue () {
31824        // This code is unreachable since it's handled by the lexState.
31825        // if (token.type !== 'punctuator') {
31826        //     throw invalidToken()
31827        // }
31828
31829        if (token.type === 'eof') {
31830            throw invalidEOF()
31831        }
31832
31833        switch (token.value) {
31834        case ',':
31835            parseState = 'beforePropertyName';
31836            return
31837
31838        case '}':
31839            pop();
31840        }
31841
31842        // This code is unreachable since it's handled by the lexState.
31843        // throw invalidToken()
31844    },
31845
31846    afterArrayValue () {
31847        // This code is unreachable since it's handled by the lexState.
31848        // if (token.type !== 'punctuator') {
31849        //     throw invalidToken()
31850        // }
31851
31852        if (token.type === 'eof') {
31853            throw invalidEOF()
31854        }
31855
31856        switch (token.value) {
31857        case ',':
31858            parseState = 'beforeArrayValue';
31859            return
31860
31861        case ']':
31862            pop();
31863        }
31864
31865        // This code is unreachable since it's handled by the lexState.
31866        // throw invalidToken()
31867    },
31868
31869    end () {
31870        // This code is unreachable since it's handled by the lexState.
31871        // if (token.type !== 'eof') {
31872        //     throw invalidToken()
31873        // }
31874    },
31875};
31876
31877function push$1 () {
31878    let value;
31879
31880    switch (token.type) {
31881    case 'punctuator':
31882        switch (token.value) {
31883        case '{':
31884            value = {};
31885            break
31886
31887        case '[':
31888            value = [];
31889            break
31890        }
31891
31892        break
31893
31894    case 'null':
31895    case 'boolean':
31896    case 'numeric':
31897    case 'string':
31898        value = token.value;
31899        break
31900
31901    // This code is unreachable.
31902    // default:
31903    //     throw invalidToken()
31904    }
31905
31906    if (root$1 === undefined) {
31907        root$1 = value;
31908    } else {
31909        const parent = stack[stack.length - 1];
31910        if (Array.isArray(parent)) {
31911            parent.push(value);
31912        } else {
31913            parent[key] = value;
31914        }
31915    }
31916
31917    if (value !== null && typeof value === 'object') {
31918        stack.push(value);
31919
31920        if (Array.isArray(value)) {
31921            parseState = 'beforeArrayValue';
31922        } else {
31923            parseState = 'beforePropertyName';
31924        }
31925    } else {
31926        const current = stack[stack.length - 1];
31927        if (current == null) {
31928            parseState = 'end';
31929        } else if (Array.isArray(current)) {
31930            parseState = 'afterArrayValue';
31931        } else {
31932            parseState = 'afterPropertyValue';
31933        }
31934    }
31935}
31936
31937function pop () {
31938    stack.pop();
31939
31940    const current = stack[stack.length - 1];
31941    if (current == null) {
31942        parseState = 'end';
31943    } else if (Array.isArray(current)) {
31944        parseState = 'afterArrayValue';
31945    } else {
31946        parseState = 'afterPropertyValue';
31947    }
31948}
31949
31950// This code is unreachable.
31951// function invalidParseState () {
31952//     return new Error(`JSON5: invalid parse state '${parseState}'`)
31953// }
31954
31955// This code is unreachable.
31956// function invalidLexState (state) {
31957//     return new Error(`JSON5: invalid lex state '${state}'`)
31958// }
31959
31960function invalidChar (c) {
31961    if (c === undefined) {
31962        return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
31963    }
31964
31965    return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
31966}
31967
31968function invalidEOF () {
31969    return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
31970}
31971
31972// This code is unreachable.
31973// function invalidToken () {
31974//     if (token.type === 'eof') {
31975//         return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
31976//     }
31977
31978//     const c = String.fromCodePoint(token.value.codePointAt(0))
31979//     return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
31980// }
31981
31982function invalidIdentifier () {
31983    column -= 5;
31984    return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
31985}
31986
31987function separatorChar (c) {
31988    console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
31989}
31990
31991function formatChar (c) {
31992    const replacements = {
31993        "'": "\\'",
31994        '"': '\\"',
31995        '\\': '\\\\',
31996        '\b': '\\b',
31997        '\f': '\\f',
31998        '\n': '\\n',
31999        '\r': '\\r',
32000        '\t': '\\t',
32001        '\v': '\\v',
32002        '\0': '\\0',
32003        '\u2028': '\\u2028',
32004        '\u2029': '\\u2029',
32005    };
32006
32007    if (replacements[c]) {
32008        return replacements[c]
32009    }
32010
32011    if (c < ' ') {
32012        const hexString = c.charCodeAt(0).toString(16);
32013        return '\\x' + ('00' + hexString).substring(hexString.length)
32014    }
32015
32016    return c
32017}
32018
32019function syntaxError (message) {
32020    const err = new SyntaxError(message);
32021    err.lineNumber = line;
32022    err.columnNumber = column;
32023    return err
32024}
32025
32026var stringify = function stringify (value, replacer, space) {
32027    const stack = [];
32028    let indent = '';
32029    let propertyList;
32030    let replacerFunc;
32031    let gap = '';
32032    let quote;
32033
32034    if (
32035        replacer != null &&
32036        typeof replacer === 'object' &&
32037        !Array.isArray(replacer)
32038    ) {
32039        space = replacer.space;
32040        quote = replacer.quote;
32041        replacer = replacer.replacer;
32042    }
32043
32044    if (typeof replacer === 'function') {
32045        replacerFunc = replacer;
32046    } else if (Array.isArray(replacer)) {
32047        propertyList = [];
32048        for (const v of replacer) {
32049            let item;
32050
32051            if (typeof v === 'string') {
32052                item = v;
32053            } else if (
32054                typeof v === 'number' ||
32055                v instanceof String ||
32056                v instanceof Number
32057            ) {
32058                item = String(v);
32059            }
32060
32061            if (item !== undefined && propertyList.indexOf(item) < 0) {
32062                propertyList.push(item);
32063            }
32064        }
32065    }
32066
32067    if (space instanceof Number) {
32068        space = Number(space);
32069    } else if (space instanceof String) {
32070        space = String(space);
32071    }
32072
32073    if (typeof space === 'number') {
32074        if (space > 0) {
32075            space = Math.min(10, Math.floor(space));
32076            gap = '          '.substr(0, space);
32077        }
32078    } else if (typeof space === 'string') {
32079        gap = space.substr(0, 10);
32080    }
32081
32082    return serializeProperty('', {'': value})
32083
32084    function serializeProperty (key, holder) {
32085        let value = holder[key];
32086        if (value != null) {
32087            if (typeof value.toJSON5 === 'function') {
32088                value = value.toJSON5(key);
32089            } else if (typeof value.toJSON === 'function') {
32090                value = value.toJSON(key);
32091            }
32092        }
32093
32094        if (replacerFunc) {
32095            value = replacerFunc.call(holder, key, value);
32096        }
32097
32098        if (value instanceof Number) {
32099            value = Number(value);
32100        } else if (value instanceof String) {
32101            value = String(value);
32102        } else if (value instanceof Boolean) {
32103            value = value.valueOf();
32104        }
32105
32106        switch (value) {
32107        case null: return 'null'
32108        case true: return 'true'
32109        case false: return 'false'
32110        }
32111
32112        if (typeof value === 'string') {
32113            return quoteString(value)
32114        }
32115
32116        if (typeof value === 'number') {
32117            return String(value)
32118        }
32119
32120        if (typeof value === 'object') {
32121            return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
32122        }
32123
32124        return undefined
32125    }
32126
32127    function quoteString (value) {
32128        const quotes = {
32129            "'": 0.1,
32130            '"': 0.2,
32131        };
32132
32133        const replacements = {
32134            "'": "\\'",
32135            '"': '\\"',
32136            '\\': '\\\\',
32137            '\b': '\\b',
32138            '\f': '\\f',
32139            '\n': '\\n',
32140            '\r': '\\r',
32141            '\t': '\\t',
32142            '\v': '\\v',
32143            '\0': '\\0',
32144            '\u2028': '\\u2028',
32145            '\u2029': '\\u2029',
32146        };
32147
32148        let product = '';
32149
32150        for (let i = 0; i < value.length; i++) {
32151            const c = value[i];
32152            switch (c) {
32153            case "'":
32154            case '"':
32155                quotes[c]++;
32156                product += c;
32157                continue
32158
32159            case '\0':
32160                if (util.isDigit(value[i + 1])) {
32161                    product += '\\x00';
32162                    continue
32163                }
32164            }
32165
32166            if (replacements[c]) {
32167                product += replacements[c];
32168                continue
32169            }
32170
32171            if (c < ' ') {
32172                let hexString = c.charCodeAt(0).toString(16);
32173                product += '\\x' + ('00' + hexString).substring(hexString.length);
32174                continue
32175            }
32176
32177            product += c;
32178        }
32179
32180        const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
32181
32182        product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
32183
32184        return quoteChar + product + quoteChar
32185    }
32186
32187    function serializeObject (value) {
32188        if (stack.indexOf(value) >= 0) {
32189            throw TypeError('Converting circular structure to JSON5')
32190        }
32191
32192        stack.push(value);
32193
32194        let stepback = indent;
32195        indent = indent + gap;
32196
32197        let keys = propertyList || Object.keys(value);
32198        let partial = [];
32199        for (const key of keys) {
32200            const propertyString = serializeProperty(key, value);
32201            if (propertyString !== undefined) {
32202                let member = serializeKey(key) + ':';
32203                if (gap !== '') {
32204                    member += ' ';
32205                }
32206                member += propertyString;
32207                partial.push(member);
32208            }
32209        }
32210
32211        let final;
32212        if (partial.length === 0) {
32213            final = '{}';
32214        } else {
32215            let properties;
32216            if (gap === '') {
32217                properties = partial.join(',');
32218                final = '{' + properties + '}';
32219            } else {
32220                let separator = ',\n' + indent;
32221                properties = partial.join(separator);
32222                final = '{\n' + indent + properties + ',\n' + stepback + '}';
32223            }
32224        }
32225
32226        stack.pop();
32227        indent = stepback;
32228        return final
32229    }
32230
32231    function serializeKey (key) {
32232        if (key.length === 0) {
32233            return quoteString(key)
32234        }
32235
32236        const firstChar = String.fromCodePoint(key.codePointAt(0));
32237        if (!util.isIdStartChar(firstChar)) {
32238            return quoteString(key)
32239        }
32240
32241        for (let i = firstChar.length; i < key.length; i++) {
32242            if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
32243                return quoteString(key)
32244            }
32245        }
32246
32247        return key
32248    }
32249
32250    function serializeArray (value) {
32251        if (stack.indexOf(value) >= 0) {
32252            throw TypeError('Converting circular structure to JSON5')
32253        }
32254
32255        stack.push(value);
32256
32257        let stepback = indent;
32258        indent = indent + gap;
32259
32260        let partial = [];
32261        for (let i = 0; i < value.length; i++) {
32262            const propertyString = serializeProperty(String(i), value);
32263            partial.push((propertyString !== undefined) ? propertyString : 'null');
32264        }
32265
32266        let final;
32267        if (partial.length === 0) {
32268            final = '[]';
32269        } else {
32270            if (gap === '') {
32271                let properties = partial.join(',');
32272                final = '[' + properties + ']';
32273            } else {
32274                let separator = ',\n' + indent;
32275                let properties = partial.join(separator);
32276                final = '[\n' + indent + properties + ',\n' + stepback + ']';
32277            }
32278        }
32279
32280        stack.pop();
32281        indent = stepback;
32282        return final
32283    }
32284};
32285
32286const JSON5 = {
32287    parse: parse$1,
32288    stringify,
32289};
32290
32291var lib = JSON5;
32292
32293/**
32294 * @typedef Option
32295 * @property {'boolean'|'string'} [type='string']
32296 * @property {string} long
32297 * @property {string} description
32298 * @property {string} [value]
32299 * @property {string} [short]
32300 * @property {boolean|string} [default='']
32301 * @property {boolean} [truelike=false]
32302 */
32303
32304/** @type {Option[]} */
32305const schema = [
32306  {
32307    long: 'help',
32308    description: 'output usage information',
32309    short: 'h',
32310    type: 'boolean',
32311    default: false
32312  },
32313  {
32314    long: 'version',
32315    description: 'output version number',
32316    short: 'v',
32317    type: 'boolean',
32318    default: false
32319  },
32320  {
32321    long: 'output',
32322    description: 'specify output location',
32323    short: 'o',
32324    value: '[path]'
32325  },
32326  {
32327    long: 'rc-path',
32328    description: 'specify configuration file',
32329    short: 'r',
32330    type: 'string',
32331    value: '<path>'
32332  },
32333  {
32334    long: 'ignore-path',
32335    description: 'specify ignore file',
32336    short: 'i',
32337    type: 'string',
32338    value: '<path>'
32339  },
32340  {
32341    long: 'setting',
32342    description: 'specify settings',
32343    short: 's',
32344    type: 'string',
32345    value: '<settings>'
32346  },
32347  {
32348    long: 'ext',
32349    description: 'specify extensions',
32350    short: 'e',
32351    type: 'string',
32352    value: '<extensions>'
32353  },
32354  {
32355    long: 'use',
32356    description: 'use plugins',
32357    short: 'u',
32358    type: 'string',
32359    value: '<plugins>'
32360  },
32361  {
32362    long: 'watch',
32363    description: 'watch for changes and reprocess',
32364    short: 'w',
32365    type: 'boolean',
32366    default: false
32367  },
32368  {
32369    long: 'quiet',
32370    description: 'output only warnings and errors',
32371    short: 'q',
32372    type: 'boolean',
32373    default: false
32374  },
32375  {
32376    long: 'silent',
32377    description: 'output only errors',
32378    short: 'S',
32379    type: 'boolean',
32380    default: false
32381  },
32382  {
32383    long: 'frail',
32384    description: 'exit with 1 on warnings',
32385    short: 'f',
32386    type: 'boolean',
32387    default: false
32388  },
32389  {
32390    long: 'tree',
32391    description: 'specify input and output as syntax tree',
32392    short: 't',
32393    type: 'boolean',
32394    default: false
32395  },
32396  {
32397    long: 'report',
32398    description: 'specify reporter',
32399    type: 'string',
32400    value: '<reporter>'
32401  },
32402  {
32403    long: 'file-path',
32404    description: 'specify path to process as',
32405    type: 'string',
32406    value: '<path>'
32407  },
32408  {
32409    long: 'ignore-path-resolve-from',
32410    description: 'resolve patterns in `ignore-path` from its directory or cwd',
32411    type: 'string',
32412    value: 'dir|cwd',
32413    default: 'dir'
32414  },
32415  {
32416    long: 'ignore-pattern',
32417    description: 'specify ignore patterns',
32418    type: 'string',
32419    value: '<globs>'
32420  },
32421  {
32422    long: 'silently-ignore',
32423    description: 'do not fail when given ignored files',
32424    type: 'boolean'
32425  },
32426  {
32427    long: 'tree-in',
32428    description: 'specify input as syntax tree',
32429    type: 'boolean'
32430  },
32431  {
32432    long: 'tree-out',
32433    description: 'output syntax tree',
32434    type: 'boolean'
32435  },
32436  {
32437    long: 'inspect',
32438    description: 'output formatted syntax tree',
32439    type: 'boolean'
32440  },
32441  {
32442    long: 'stdout',
32443    description: 'specify writing to stdout',
32444    type: 'boolean',
32445    truelike: true
32446  },
32447  {
32448    long: 'color',
32449    description: 'specify color in report',
32450    type: 'boolean',
32451    default: true
32452  },
32453  {
32454    long: 'config',
32455    description: 'search for configuration files',
32456    type: 'boolean',
32457    default: true
32458  },
32459  {
32460    long: 'ignore',
32461    description: 'search for ignore files',
32462    type: 'boolean',
32463    default: true
32464  }
32465];
32466
32467/**
32468 * @typedef {import('unified-engine').Options} EngineOptions
32469 * @typedef {import('./schema.js').Option} Option
32470 *
32471 * @typedef {Required<
32472 *   Pick<
32473 *     EngineOptions,
32474 *     | 'extensions'
32475 *     | 'ignoreName'
32476 *     | 'packageField'
32477 *     | 'pluginPrefix'
32478 *     | 'processor'
32479 *     | 'rcName'
32480 *   >
32481 * >} RequiredEngineOptions
32482 *
32483 * @typedef ArgsOptionsFields
32484 * @property {string} name
32485 *   Name of executable
32486 * @property {string} description
32487 *   Description of executable
32488 * @property {string} version
32489 *   Version (semver) of executable
32490 *
32491 * @typedef {RequiredEngineOptions & Pick<EngineOptions, 'cwd'> & ArgsOptionsFields} Options
32492 */
32493
32494const own$7 = {}.hasOwnProperty;
32495
32496/**
32497 * Schema for `minimist`.
32498 */
32499const minischema = {
32500  unknown: handleUnknownArgument,
32501  /** @type {Record<string, string|boolean|null>} */
32502  default: {},
32503  /** @type {Record<string, string>} */
32504  alias: {},
32505  /** @type {string[]} */
32506  string: [],
32507  /** @type {string[]} */
32508  boolean: []
32509};
32510
32511let index = -1;
32512while (++index < schema.length) {
32513  addEach(schema[index]);
32514}
32515
32516/**
32517 * Parse CLI options.
32518 *
32519 * @param {string[]} flags
32520 * @param {Options} configuration
32521 */
32522function options(flags, configuration) {
32523  const extension = configuration.extensions[0];
32524  const name = configuration.name;
32525  const config = toCamelCase(minimist(flags, minischema));
32526  let index = -1;
32527
32528  while (++index < schema.length) {
32529    const option = schema[index];
32530    if (option.type === 'string' && config[option.long] === '') {
32531      throw fault('Missing value:%s', inspect(option).join(' '))
32532    }
32533  }
32534
32535  const ext = commaSeparated(/** @type {string} */ (config.ext));
32536  const report = reporter(/** @type {string} */ (config.report));
32537  const help = [
32538    inspectAll(schema),
32539    '',
32540    'Examples:',
32541    '',
32542    '  # Process `input.' + extension + '`',
32543    '  $ ' + name + ' input.' + extension + ' -o output.' + extension,
32544    '',
32545    '  # Pipe',
32546    '  $ ' + name + ' < input.' + extension + ' > output.' + extension,
32547    '',
32548    '  # Rewrite all applicable files',
32549    '  $ ' + name + ' . -o'
32550  ].join('\n');
32551
32552  return {
32553    helpMessage: help,
32554    cwd: configuration.cwd,
32555    processor: configuration.processor,
32556    help: config.help,
32557    version: config.version,
32558    files: config._,
32559    filePath: config.filePath,
32560    watch: config.watch,
32561    extensions: ext.length === 0 ? configuration.extensions : ext,
32562    output: config.output,
32563    out: config.stdout,
32564    tree: config.tree,
32565    treeIn: config.treeIn,
32566    treeOut: config.treeOut,
32567    inspect: config.inspect,
32568    rcName: configuration.rcName,
32569    packageField: configuration.packageField,
32570    rcPath: config.rcPath,
32571    detectConfig: config.config,
32572    settings: /** @type {Record<string, unknown>} */ (
32573      settings(/** @type {string} */ (config.setting))
32574    ),
32575    ignoreName: configuration.ignoreName,
32576    ignorePath: config.ignorePath,
32577    ignorePathResolveFrom: config.ignorePathResolveFrom,
32578    ignorePatterns: commaSeparated(
32579      /** @type {string} */ (config.ignorePattern)
32580    ),
32581    silentlyIgnore: config.silentlyIgnore,
32582    detectIgnore: config.ignore,
32583    pluginPrefix: configuration.pluginPrefix,
32584    plugins: plugins$2(/** @type {string} */ (config.use)),
32585    reporter: report[0],
32586    reporterOptions: report[1],
32587    color: config.color,
32588    silent: config.silent,
32589    quiet: config.quiet,
32590    frail: config.frail
32591  }
32592}
32593
32594/**
32595 * @param {Option} option
32596 */
32597function addEach(option) {
32598  const value = option.default;
32599
32600  minischema.default[option.long] = value === undefined ? null : value;
32601
32602  if (option.type && option.type in minischema) {
32603    minischema[option.type].push(option.long);
32604  }
32605
32606  if (option.short) {
32607    minischema.alias[option.short] = option.long;
32608  }
32609}
32610
32611/**
32612 * Parse `extensions`.
32613 *
32614 * @param {string[]|string|null|undefined} value
32615 * @returns {string[]}
32616 */
32617function commaSeparated(value) {
32618  return flatten(normalize(value).map((d) => splitList(d)))
32619}
32620
32621/**
32622 * Parse `plugins`.
32623 *
32624 * @param {string[]|string|null|undefined} value
32625 * @returns {Record<string, Record<string, unknown>|undefined>}
32626 */
32627function plugins$2(value) {
32628  const normalized = normalize(value).map((d) => splitOptions(d));
32629  let index = -1;
32630  /** @type {Record<string, Record<string, unknown>|undefined>} */
32631  const result = {};
32632
32633  while (++index < normalized.length) {
32634    const value = normalized[index];
32635    result[value[0]] = value[1] ? parseConfig(value[1], {}) : undefined;
32636  }
32637
32638  return result
32639}
32640
32641/**
32642 * Parse `reporter`: only one is accepted.
32643 *
32644 * @param {string[]|string|null|undefined} value
32645 * @returns {[string|undefined, Record<string, unknown>|undefined]}
32646 */
32647function reporter(value) {
32648  const all = normalize(value)
32649    .map((d) => splitOptions(d))
32650    .map(
32651      /**
32652       * @returns {[string, Record<string, unknown>|undefined]}
32653       */
32654      (value) => [value[0], value[1] ? parseConfig(value[1], {}) : undefined]
32655    );
32656
32657  return all[all.length - 1] || []
32658}
32659
32660/**
32661 * Parse `settings`.
32662 *
32663 * @param {string[]|string|null|undefined} value
32664 * @returns {Record<string, unknown>}
32665 */
32666function settings(value) {
32667  const normalized = normalize(value);
32668  let index = -1;
32669  /** @type {Record<string, unknown>} */
32670  const cache = {};
32671
32672  while (++index < normalized.length) {
32673    parseConfig(normalized[index], cache);
32674  }
32675
32676  return cache
32677}
32678
32679/**
32680 * Parse configuration.
32681 *
32682 * @param {string} value
32683 * @param {Record<string, unknown>} cache
32684 * @returns {Record<string, unknown>}
32685 */
32686function parseConfig(value, cache) {
32687  /** @type {Record<string, unknown>} */
32688  let flags;
32689  /** @type {string} */
32690  let flag;
32691
32692  try {
32693    flags = toCamelCase(parseJSON(value));
32694  } catch (error) {
32695    throw fault(
32696      'Cannot parse `%s` as JSON: %s',
32697      value,
32698      // Fix position
32699      error.message.replace(/at(?= position)/, 'around')
32700    )
32701  }
32702
32703  for (flag in flags) {
32704    if (own$7.call(flags, flag)) {
32705      cache[flag] = flags[flag];
32706    }
32707  }
32708
32709  return cache
32710}
32711
32712/**
32713 * Handle an unknown flag.
32714 *
32715 * @param {string} flag
32716 * @returns {boolean}
32717 */
32718function handleUnknownArgument(flag) {
32719  // Not a glob.
32720  if (flag.charAt(0) === '-') {
32721    // Long options, always unknown.
32722    if (flag.charAt(1) === '-') {
32723      throw fault(
32724        'Unknown option `%s`, expected:\n%s',
32725        flag,
32726        inspectAll(schema)
32727      )
32728    }
32729
32730    // Short options, can be grouped.
32731    const found = flag.slice(1).split('');
32732    const known = schema.filter((d) => d.short);
32733    const knownKeys = new Set(known.map((d) => d.short));
32734    let index = -1;
32735
32736    while (++index < found.length) {
32737      const key = found[index];
32738      if (!knownKeys.has(key)) {
32739        throw fault(
32740          'Unknown short option `-%s`, expected:\n%s',
32741          key,
32742          inspectAll(known)
32743        )
32744      }
32745    }
32746  }
32747
32748  return true
32749}
32750
32751/**
32752 * Inspect all `options`.
32753 *
32754 * @param {Option[]} options
32755 * @returns {string}
32756 */
32757function inspectAll(options) {
32758  return textTable(options.map((d) => inspect(d)))
32759}
32760
32761/**
32762 * Inspect one `option`.
32763 *
32764 * @param {Option} option
32765 * @returns {string[]}
32766 */
32767function inspect(option) {
32768  let description = option.description;
32769  let long = option.long;
32770
32771  if (option.default === true || option.truelike) {
32772    description += ' (on by default)';
32773    long = '[no-]' + long;
32774  }
32775
32776  return [
32777    '',
32778    option.short ? '-' + option.short : '',
32779    '--' + long + (option.value ? ' ' + option.value : ''),
32780    description
32781  ]
32782}
32783
32784/**
32785 * Normalize `value`.
32786 *
32787 * @param {string[]|string|null|undefined} value
32788 * @returns {string[]}
32789 */
32790function normalize(value) {
32791  if (!value) {
32792    return []
32793  }
32794
32795  if (typeof value === 'string') {
32796    return [value]
32797  }
32798
32799  return flatten(value.map((d) => normalize(d)))
32800}
32801
32802/**
32803 * Flatten `values`.
32804 *
32805 * @param {string|string[]|string[][]} values
32806 * @returns {string[]}
32807 */
32808function flatten(values) {
32809  // @ts-expect-error: TS is wrong.
32810  return values.flat()
32811}
32812
32813/**
32814 * @param {string} value
32815 * @returns {string[]}
32816 */
32817function splitOptions(value) {
32818  return value.split('=')
32819}
32820
32821/**
32822 * @param {string} value
32823 * @returns {string[]}
32824 */
32825function splitList(value) {
32826  return value.split(',')
32827}
32828
32829/**
32830 * Transform the keys on an object to camel-case, recursivly.
32831 *
32832 * @param {Record<string, unknown>} object
32833 * @returns {Record<string, unknown>}
32834 */
32835function toCamelCase(object) {
32836  /** @type {Record<string, unknown>} */
32837  const result = {};
32838  /** @type {string} */
32839  let key;
32840
32841  for (key in object) {
32842    if (own$7.call(object, key)) {
32843      let value = object[key];
32844
32845      if (value && typeof value === 'object' && !Array.isArray(value)) {
32846        // @ts-expect-error: looks like an object.
32847        value = toCamelCase(value);
32848      }
32849
32850      result[camelcase(key)] = value;
32851    }
32852  }
32853
32854  return result
32855}
32856
32857/**
32858 * Parse a (lazy?) JSON config.
32859 *
32860 * @param {string} value
32861 * @returns {Record<string, unknown>}
32862 */
32863function parseJSON(value) {
32864  return lib.parse('{' + value + '}')
32865}
32866
32867/**
32868 * @typedef {import('unified-engine').Options} EngineOptions
32869 * @typedef {import('unified-engine').Context} EngineContext
32870 * @typedef {import('unified-engine').Callback} EngineCallback
32871 * @typedef {import('./options.js').Options} Options
32872 */
32873
32874// Fake TTY stream.
32875const ttyStream = Object.assign(new stream.Readable(), {isTTY: true});
32876
32877// Exit, lazily, with the correct exit status code.
32878let exitStatus = 0;
32879
32880process$2.on('exit', onexit);
32881
32882// Handle uncaught errors, such as from unexpected async behaviour.
32883process$2.on('uncaughtException', fail);
32884
32885/**
32886 * Start the CLI.
32887 *
32888 * @param {Options} cliConfig
32889 */
32890function args(cliConfig) {
32891  /** @type {EngineOptions & {help: boolean, helpMessage: string, watch: boolean, version: boolean}} */
32892  let config;
32893  /** @type {chokidar.FSWatcher|undefined} */
32894  let watcher;
32895  /** @type {boolean|string|undefined} */
32896  let output;
32897
32898  try {
32899    // @ts-expect-error: Close enough.
32900    config = options(process$2.argv.slice(2), cliConfig);
32901  } catch (error) {
32902    return fail(error, true)
32903  }
32904
32905  if (config.help) {
32906    process$2.stdout.write(
32907      [
32908        'Usage: ' + cliConfig.name + ' [options] [path | glob ...]',
32909        '',
32910        '  ' + cliConfig.description,
32911        '',
32912        'Options:',
32913        '',
32914        config.helpMessage,
32915        ''
32916      ].join('\n'),
32917      noop$1
32918    );
32919
32920    return
32921  }
32922
32923  if (config.version) {
32924    process$2.stdout.write(cliConfig.version + '\n', noop$1);
32925
32926    return
32927  }
32928
32929  // Modify `config` for watching.
32930  if (config.watch) {
32931    output = config.output;
32932
32933    // Do not read from stdin(4).
32934    config.streamIn = ttyStream;
32935
32936    // Do not write to stdout(4).
32937    config.out = false;
32938
32939    process$2.stderr.write(
32940      source$1.bold('Watching...') + ' (press CTRL+C to exit)\n',
32941      noop$1
32942    );
32943
32944    // Prevent infinite loop if set to regeneration.
32945    if (output === true) {
32946      config.output = false;
32947
32948      process$2.stderr.write(
32949        source$1.yellow('Note') + ': Ignoring `--output` until exit.\n',
32950        noop$1
32951      );
32952    }
32953  }
32954
32955  // Initial run.
32956  engine(config, done);
32957
32958  /**
32959   * Handle complete run.
32960   *
32961   * @type {EngineCallback}
32962   */
32963  function done(error, code, context) {
32964    if (error) {
32965      clean();
32966      fail(error);
32967    } else {
32968      exitStatus = code || 0;
32969
32970      if (config.watch && !watcher && context) {
32971        subscribe(context);
32972      }
32973    }
32974  }
32975
32976  // Clean the watcher.
32977  function clean() {
32978    if (watcher) {
32979      watcher.close();
32980      watcher = undefined;
32981    }
32982  }
32983
32984  /**
32985   * Subscribe a chokidar watcher to all processed files.
32986   *
32987   * @param {EngineContext} context
32988   */
32989  function subscribe(context) {
32990    watcher = chokidar
32991      // @ts-expect-error: `fileSet` is available.
32992      .watch(context.fileSet.origins, {cwd: config.cwd, ignoreInitial: true})
32993      .on('error', done)
32994      .on('change', (filePath) => {
32995        config.files = [filePath];
32996        engine(config, done);
32997      });
32998
32999    process$2.on('SIGINT', onsigint);
33000
33001    /**
33002     * Handle a SIGINT.
33003     */
33004    function onsigint() {
33005      // Hide the `^C` in terminal.
33006      process$2.stderr.write('\n', noop$1);
33007
33008      clean();
33009
33010      // Do another process if `output` specified regeneration.
33011      if (output === true) {
33012        config.output = output;
33013        config.watch = false;
33014        engine(config, done);
33015      }
33016    }
33017  }
33018}
33019
33020/**
33021 * Print an error, optionally with stack.
33022 *
33023 * @param {Error} error
33024 * @param {boolean} [pretty=false]
33025 */
33026function fail(error, pretty) {
33027  // Old versions of Node
33028  /* c8 ignore next 1 */
33029  const message = String((pretty ? error : error.stack) || error);
33030
33031  exitStatus = 1;
33032
33033  process$2.stderr.write(message.trim() + '\n', noop$1);
33034}
33035
33036function onexit() {
33037  /* eslint-disable unicorn/no-process-exit */
33038  process$2.exit(exitStatus);
33039  /* eslint-enable unicorn/no-process-exit */
33040}
33041
33042function noop$1() {}
33043
33044var require$$0 = [
33045	"md",
33046	"markdown",
33047	"mdown",
33048	"mkdn",
33049	"mkd",
33050	"mdwn",
33051	"mkdown",
33052	"ron"
33053];
33054
33055var markdownExtensions = require$$0;
33056
33057/**
33058 * Throw a given error.
33059 *
33060 * @param {Error | null | undefined} [error]
33061 */
33062function bail(error) {
33063  if (error) {
33064    throw error
33065  }
33066}
33067
33068var hasOwn = Object.prototype.hasOwnProperty;
33069var toStr = Object.prototype.toString;
33070var defineProperty = Object.defineProperty;
33071var gOPD = Object.getOwnPropertyDescriptor;
33072
33073var isArray = function isArray(arr) {
33074	if (typeof Array.isArray === 'function') {
33075		return Array.isArray(arr);
33076	}
33077
33078	return toStr.call(arr) === '[object Array]';
33079};
33080
33081var isPlainObject = function isPlainObject(obj) {
33082	if (!obj || toStr.call(obj) !== '[object Object]') {
33083		return false;
33084	}
33085
33086	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
33087	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
33088	// Not own constructor property must be Object
33089	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
33090		return false;
33091	}
33092
33093	// Own properties are enumerated firstly, so to speed up,
33094	// if last one is own, then all properties are own.
33095	var key;
33096	for (key in obj) { /**/ }
33097
33098	return typeof key === 'undefined' || hasOwn.call(obj, key);
33099};
33100
33101// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
33102var setProperty = function setProperty(target, options) {
33103	if (defineProperty && options.name === '__proto__') {
33104		defineProperty(target, options.name, {
33105			enumerable: true,
33106			configurable: true,
33107			value: options.newValue,
33108			writable: true
33109		});
33110	} else {
33111		target[options.name] = options.newValue;
33112	}
33113};
33114
33115// Return undefined instead of __proto__ if '__proto__' is not an own property
33116var getProperty = function getProperty(obj, name) {
33117	if (name === '__proto__') {
33118		if (!hasOwn.call(obj, name)) {
33119			return void 0;
33120		} else if (gOPD) {
33121			// In early versions of node, obj['__proto__'] is buggy when obj has
33122			// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
33123			return gOPD(obj, name).value;
33124		}
33125	}
33126
33127	return obj[name];
33128};
33129
33130var extend = function extend() {
33131	var options, name, src, copy, copyIsArray, clone;
33132	var target = arguments[0];
33133	var i = 1;
33134	var length = arguments.length;
33135	var deep = false;
33136
33137	// Handle a deep copy situation
33138	if (typeof target === 'boolean') {
33139		deep = target;
33140		target = arguments[1] || {};
33141		// skip the boolean and the target
33142		i = 2;
33143	}
33144	if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
33145		target = {};
33146	}
33147
33148	for (; i < length; ++i) {
33149		options = arguments[i];
33150		// Only deal with non-null/undefined values
33151		if (options != null) {
33152			// Extend the base object
33153			for (name in options) {
33154				src = getProperty(target, name);
33155				copy = getProperty(options, name);
33156
33157				// Prevent never-ending loop
33158				if (target !== copy) {
33159					// Recurse if we're merging plain objects or arrays
33160					if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
33161						if (copyIsArray) {
33162							copyIsArray = false;
33163							clone = src && isArray(src) ? src : [];
33164						} else {
33165							clone = src && isPlainObject(src) ? src : {};
33166						}
33167
33168						// Never move original objects, clone them
33169						setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
33170
33171					// Don't bring in undefined values
33172					} else if (typeof copy !== 'undefined') {
33173						setProperty(target, { name: name, newValue: copy });
33174					}
33175				}
33176			}
33177		}
33178	}
33179
33180	// Return the modified object
33181	return target;
33182};
33183
33184/**
33185 * @typedef {import('unist').Node} Node
33186 * @typedef {import('vfile').VFileCompatible} VFileCompatible
33187 * @typedef {import('vfile').VFileValue} VFileValue
33188 * @typedef {import('..').Processor} Processor
33189 * @typedef {import('..').Plugin} Plugin
33190 * @typedef {import('..').Preset} Preset
33191 * @typedef {import('..').Pluggable} Pluggable
33192 * @typedef {import('..').PluggableList} PluggableList
33193 * @typedef {import('..').Transformer} Transformer
33194 * @typedef {import('..').Parser} Parser
33195 * @typedef {import('..').Compiler} Compiler
33196 * @typedef {import('..').RunCallback} RunCallback
33197 * @typedef {import('..').ProcessCallback} ProcessCallback
33198 *
33199 * @typedef Context
33200 * @property {Node} tree
33201 * @property {VFile} file
33202 */
33203
33204// Expose a frozen processor.
33205const unified = base().freeze();
33206
33207const own$6 = {}.hasOwnProperty;
33208
33209// Function to create the first processor.
33210/**
33211 * @returns {Processor}
33212 */
33213function base() {
33214  const transformers = trough();
33215  /** @type {Processor['attachers']} */
33216  const attachers = [];
33217  /** @type {Record<string, unknown>} */
33218  let namespace = {};
33219  /** @type {boolean|undefined} */
33220  let frozen;
33221  let freezeIndex = -1;
33222
33223  // Data management.
33224  // @ts-expect-error: overloads are handled.
33225  processor.data = data;
33226  processor.Parser = undefined;
33227  processor.Compiler = undefined;
33228
33229  // Lock.
33230  processor.freeze = freeze;
33231
33232  // Plugins.
33233  processor.attachers = attachers;
33234  // @ts-expect-error: overloads are handled.
33235  processor.use = use;
33236
33237  // API.
33238  processor.parse = parse;
33239  processor.stringify = stringify;
33240  // @ts-expect-error: overloads are handled.
33241  processor.run = run;
33242  processor.runSync = runSync;
33243  // @ts-expect-error: overloads are handled.
33244  processor.process = process;
33245  processor.processSync = processSync;
33246
33247  // Expose.
33248  return processor
33249
33250  // Create a new processor based on the processor in the current scope.
33251  /** @type {Processor} */
33252  function processor() {
33253    const destination = base();
33254    let index = -1;
33255
33256    while (++index < attachers.length) {
33257      destination.use(...attachers[index]);
33258    }
33259
33260    destination.data(extend(true, {}, namespace));
33261
33262    return destination
33263  }
33264
33265  /**
33266   * @param {string|Record<string, unknown>} [key]
33267   * @param {unknown} [value]
33268   * @returns {unknown}
33269   */
33270  function data(key, value) {
33271    if (typeof key === 'string') {
33272      // Set `key`.
33273      if (arguments.length === 2) {
33274        assertUnfrozen('data', frozen);
33275        namespace[key] = value;
33276        return processor
33277      }
33278
33279      // Get `key`.
33280      return (own$6.call(namespace, key) && namespace[key]) || null
33281    }
33282
33283    // Set space.
33284    if (key) {
33285      assertUnfrozen('data', frozen);
33286      namespace = key;
33287      return processor
33288    }
33289
33290    // Get space.
33291    return namespace
33292  }
33293
33294  /** @type {Processor['freeze']} */
33295  function freeze() {
33296    if (frozen) {
33297      return processor
33298    }
33299
33300    while (++freezeIndex < attachers.length) {
33301      const [attacher, ...options] = attachers[freezeIndex];
33302
33303      if (options[0] === false) {
33304        continue
33305      }
33306
33307      if (options[0] === true) {
33308        options[1] = undefined;
33309      }
33310
33311      /** @type {Transformer|void} */
33312      const transformer = attacher.call(processor, ...options);
33313
33314      if (typeof transformer === 'function') {
33315        transformers.use(transformer);
33316      }
33317    }
33318
33319    frozen = true;
33320    freezeIndex = Number.POSITIVE_INFINITY;
33321
33322    return processor
33323  }
33324
33325  /**
33326   * @param {Pluggable|null|undefined} [value]
33327   * @param {...unknown} options
33328   * @returns {Processor}
33329   */
33330  function use(value, ...options) {
33331    /** @type {Record<string, unknown>|undefined} */
33332    let settings;
33333
33334    assertUnfrozen('use', frozen);
33335
33336    if (value === null || value === undefined) ; else if (typeof value === 'function') {
33337      addPlugin(value, ...options);
33338    } else if (typeof value === 'object') {
33339      if (Array.isArray(value)) {
33340        addList(value);
33341      } else {
33342        addPreset(value);
33343      }
33344    } else {
33345      throw new TypeError('Expected usable value, not `' + value + '`')
33346    }
33347
33348    if (settings) {
33349      namespace.settings = Object.assign(namespace.settings || {}, settings);
33350    }
33351
33352    return processor
33353
33354    /**
33355     * @param {import('..').Pluggable<unknown[]>} value
33356     * @returns {void}
33357     */
33358    function add(value) {
33359      if (typeof value === 'function') {
33360        addPlugin(value);
33361      } else if (typeof value === 'object') {
33362        if (Array.isArray(value)) {
33363          const [plugin, ...options] = value;
33364          addPlugin(plugin, ...options);
33365        } else {
33366          addPreset(value);
33367        }
33368      } else {
33369        throw new TypeError('Expected usable value, not `' + value + '`')
33370      }
33371    }
33372
33373    /**
33374     * @param {Preset} result
33375     * @returns {void}
33376     */
33377    function addPreset(result) {
33378      addList(result.plugins);
33379
33380      if (result.settings) {
33381        settings = Object.assign(settings || {}, result.settings);
33382      }
33383    }
33384
33385    /**
33386     * @param {PluggableList|null|undefined} [plugins]
33387     * @returns {void}
33388     */
33389    function addList(plugins) {
33390      let index = -1;
33391
33392      if (plugins === null || plugins === undefined) ; else if (Array.isArray(plugins)) {
33393        while (++index < plugins.length) {
33394          const thing = plugins[index];
33395          add(thing);
33396        }
33397      } else {
33398        throw new TypeError('Expected a list of plugins, not `' + plugins + '`')
33399      }
33400    }
33401
33402    /**
33403     * @param {Plugin} plugin
33404     * @param {...unknown} [value]
33405     * @returns {void}
33406     */
33407    function addPlugin(plugin, value) {
33408      let index = -1;
33409      /** @type {Processor['attachers'][number]|undefined} */
33410      let entry;
33411
33412      while (++index < attachers.length) {
33413        if (attachers[index][0] === plugin) {
33414          entry = attachers[index];
33415          break
33416        }
33417      }
33418
33419      if (entry) {
33420        if (isPlainObject$1(entry[1]) && isPlainObject$1(value)) {
33421          value = extend(true, entry[1], value);
33422        }
33423
33424        entry[1] = value;
33425      } else {
33426        // @ts-expect-error: fine.
33427        attachers.push([...arguments]);
33428      }
33429    }
33430  }
33431
33432  /** @type {Processor['parse']} */
33433  function parse(doc) {
33434    processor.freeze();
33435    const file = vfile(doc);
33436    const Parser = processor.Parser;
33437    assertParser('parse', Parser);
33438
33439    if (newable(Parser, 'parse')) {
33440      // @ts-expect-error: `newable` checks this.
33441      return new Parser(String(file), file).parse()
33442    }
33443
33444    // @ts-expect-error: `newable` checks this.
33445    return Parser(String(file), file) // eslint-disable-line new-cap
33446  }
33447
33448  /** @type {Processor['stringify']} */
33449  function stringify(node, doc) {
33450    processor.freeze();
33451    const file = vfile(doc);
33452    const Compiler = processor.Compiler;
33453    assertCompiler('stringify', Compiler);
33454    assertNode(node);
33455
33456    if (newable(Compiler, 'compile')) {
33457      // @ts-expect-error: `newable` checks this.
33458      return new Compiler(node, file).compile()
33459    }
33460
33461    // @ts-expect-error: `newable` checks this.
33462    return Compiler(node, file) // eslint-disable-line new-cap
33463  }
33464
33465  /**
33466   * @param {Node} node
33467   * @param {VFileCompatible|RunCallback} [doc]
33468   * @param {RunCallback} [callback]
33469   * @returns {Promise<Node>|void}
33470   */
33471  function run(node, doc, callback) {
33472    assertNode(node);
33473    processor.freeze();
33474
33475    if (!callback && typeof doc === 'function') {
33476      callback = doc;
33477      doc = undefined;
33478    }
33479
33480    if (!callback) {
33481      return new Promise(executor)
33482    }
33483
33484    executor(null, callback);
33485
33486    /**
33487     * @param {null|((node: Node) => void)} resolve
33488     * @param {(error: Error) => void} reject
33489     * @returns {void}
33490     */
33491    function executor(resolve, reject) {
33492      // @ts-expect-error: `doc` can’t be a callback anymore, we checked.
33493      transformers.run(node, vfile(doc), done);
33494
33495      /**
33496       * @param {Error|null} error
33497       * @param {Node} tree
33498       * @param {VFile} file
33499       * @returns {void}
33500       */
33501      function done(error, tree, file) {
33502        tree = tree || node;
33503        if (error) {
33504          reject(error);
33505        } else if (resolve) {
33506          resolve(tree);
33507        } else {
33508          // @ts-expect-error: `callback` is defined if `resolve` is not.
33509          callback(null, tree, file);
33510        }
33511      }
33512    }
33513  }
33514
33515  /** @type {Processor['runSync']} */
33516  function runSync(node, file) {
33517    /** @type {Node|undefined} */
33518    let result;
33519    /** @type {boolean|undefined} */
33520    let complete;
33521
33522    processor.run(node, file, done);
33523
33524    assertDone('runSync', 'run', complete);
33525
33526    // @ts-expect-error: we either bailed on an error or have a tree.
33527    return result
33528
33529    /**
33530     * @param {Error|null} [error]
33531     * @param {Node} [tree]
33532     * @returns {void}
33533     */
33534    function done(error, tree) {
33535      bail(error);
33536      result = tree;
33537      complete = true;
33538    }
33539  }
33540
33541  /**
33542   * @param {VFileCompatible} doc
33543   * @param {ProcessCallback} [callback]
33544   * @returns {Promise<VFile>|undefined}
33545   */
33546  function process(doc, callback) {
33547    processor.freeze();
33548    assertParser('process', processor.Parser);
33549    assertCompiler('process', processor.Compiler);
33550
33551    if (!callback) {
33552      return new Promise(executor)
33553    }
33554
33555    executor(null, callback);
33556
33557    /**
33558     * @param {null|((file: VFile) => void)} resolve
33559     * @param {(error?: Error|null|undefined) => void} reject
33560     * @returns {void}
33561     */
33562    function executor(resolve, reject) {
33563      const file = vfile(doc);
33564
33565      processor.run(processor.parse(file), file, (error, tree, file) => {
33566        if (error || !tree || !file) {
33567          done(error);
33568        } else {
33569          /** @type {unknown} */
33570          const result = processor.stringify(tree, file);
33571
33572          if (result === undefined || result === null) ; else if (looksLikeAVFileValue(result)) {
33573            file.value = result;
33574          } else {
33575            file.result = result;
33576          }
33577
33578          done(error, file);
33579        }
33580      });
33581
33582      /**
33583       * @param {Error|null|undefined} [error]
33584       * @param {VFile|undefined} [file]
33585       * @returns {void}
33586       */
33587      function done(error, file) {
33588        if (error || !file) {
33589          reject(error);
33590        } else if (resolve) {
33591          resolve(file);
33592        } else {
33593          // @ts-expect-error: `callback` is defined if `resolve` is not.
33594          callback(null, file);
33595        }
33596      }
33597    }
33598  }
33599
33600  /** @type {Processor['processSync']} */
33601  function processSync(doc) {
33602    /** @type {boolean|undefined} */
33603    let complete;
33604
33605    processor.freeze();
33606    assertParser('processSync', processor.Parser);
33607    assertCompiler('processSync', processor.Compiler);
33608
33609    const file = vfile(doc);
33610
33611    processor.process(file, done);
33612
33613    assertDone('processSync', 'process', complete);
33614
33615    return file
33616
33617    /**
33618     * @param {Error|null|undefined} [error]
33619     * @returns {void}
33620     */
33621    function done(error) {
33622      complete = true;
33623      bail(error);
33624    }
33625  }
33626}
33627
33628/**
33629 * Check if `value` is a constructor.
33630 *
33631 * @param {unknown} value
33632 * @param {string} name
33633 * @returns {boolean}
33634 */
33635function newable(value, name) {
33636  return (
33637    typeof value === 'function' &&
33638    // Prototypes do exist.
33639    // type-coverage:ignore-next-line
33640    value.prototype &&
33641    // A function with keys in its prototype is probably a constructor.
33642    // Classes’ prototype methods are not enumerable, so we check if some value
33643    // exists in the prototype.
33644    // type-coverage:ignore-next-line
33645    (keys(value.prototype) || name in value.prototype)
33646  )
33647}
33648
33649/**
33650 * Check if `value` is an object with keys.
33651 *
33652 * @param {Record<string, unknown>} value
33653 * @returns {boolean}
33654 */
33655function keys(value) {
33656  /** @type {string} */
33657  let key;
33658
33659  for (key in value) {
33660    if (own$6.call(value, key)) {
33661      return true
33662    }
33663  }
33664
33665  return false
33666}
33667
33668/**
33669 * Assert a parser is available.
33670 *
33671 * @param {string} name
33672 * @param {unknown} value
33673 * @returns {asserts value is Parser}
33674 */
33675function assertParser(name, value) {
33676  if (typeof value !== 'function') {
33677    throw new TypeError('Cannot `' + name + '` without `Parser`')
33678  }
33679}
33680
33681/**
33682 * Assert a compiler is available.
33683 *
33684 * @param {string} name
33685 * @param {unknown} value
33686 * @returns {asserts value is Compiler}
33687 */
33688function assertCompiler(name, value) {
33689  if (typeof value !== 'function') {
33690    throw new TypeError('Cannot `' + name + '` without `Compiler`')
33691  }
33692}
33693
33694/**
33695 * Assert the processor is not frozen.
33696 *
33697 * @param {string} name
33698 * @param {unknown} frozen
33699 * @returns {asserts frozen is false}
33700 */
33701function assertUnfrozen(name, frozen) {
33702  if (frozen) {
33703    throw new Error(
33704      'Cannot call `' +
33705        name +
33706        '` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.'
33707    )
33708  }
33709}
33710
33711/**
33712 * Assert `node` is a unist node.
33713 *
33714 * @param {unknown} node
33715 * @returns {asserts node is Node}
33716 */
33717function assertNode(node) {
33718  // `isPlainObj` unfortunately uses `any` instead of `unknown`.
33719  // type-coverage:ignore-next-line
33720  if (!isPlainObject$1(node) || typeof node.type !== 'string') {
33721    throw new TypeError('Expected node, got `' + node + '`')
33722    // Fine.
33723  }
33724}
33725
33726/**
33727 * Assert that `complete` is `true`.
33728 *
33729 * @param {string} name
33730 * @param {string} asyncName
33731 * @param {unknown} complete
33732 * @returns {asserts complete is true}
33733 */
33734function assertDone(name, asyncName, complete) {
33735  if (!complete) {
33736    throw new Error(
33737      '`' + name + '` finished async. Use `' + asyncName + '` instead'
33738    )
33739  }
33740}
33741
33742/**
33743 * @param {VFileCompatible} [value]
33744 * @returns {VFile}
33745 */
33746function vfile(value) {
33747  return looksLikeAVFile(value) ? value : new VFile(value)
33748}
33749
33750/**
33751 * @param {VFileCompatible} [value]
33752 * @returns {value is VFile}
33753 */
33754function looksLikeAVFile(value) {
33755  return Boolean(
33756    value &&
33757      typeof value === 'object' &&
33758      'message' in value &&
33759      'messages' in value
33760  )
33761}
33762
33763/**
33764 * @param {unknown} [value]
33765 * @returns {value is VFileValue}
33766 */
33767function looksLikeAVFileValue(value) {
33768  return typeof value === 'string' || isBuffer(value)
33769}
33770
33771/**
33772 * @typedef Options
33773 * @property {boolean} [includeImageAlt=true]
33774 */
33775
33776/**
33777 * Get the text content of a node.
33778 * Prefer the node’s plain-text fields, otherwise serialize its children,
33779 * and if the given value is an array, serialize the nodes in it.
33780 *
33781 * @param {unknown} node
33782 * @param {Options} [options]
33783 * @returns {string}
33784 */
33785function toString(node, options) {
33786  var {includeImageAlt = true} = options || {};
33787  return one(node, includeImageAlt)
33788}
33789
33790/**
33791 * @param {unknown} node
33792 * @param {boolean} includeImageAlt
33793 * @returns {string}
33794 */
33795function one(node, includeImageAlt) {
33796  return (
33797    (node &&
33798      typeof node === 'object' &&
33799      // @ts-ignore looks like a literal.
33800      (node.value ||
33801        // @ts-ignore looks like an image.
33802        (includeImageAlt ? node.alt : '') ||
33803        // @ts-ignore looks like a parent.
33804        ('children' in node && all(node.children, includeImageAlt)) ||
33805        (Array.isArray(node) && all(node, includeImageAlt)))) ||
33806    ''
33807  )
33808}
33809
33810/**
33811 * @param {Array.<unknown>} values
33812 * @param {boolean} includeImageAlt
33813 * @returns {string}
33814 */
33815function all(values, includeImageAlt) {
33816  /** @type {Array.<string>} */
33817  var result = [];
33818  var index = -1;
33819
33820  while (++index < values.length) {
33821    result[index] = one(values[index], includeImageAlt);
33822  }
33823
33824  return result.join('')
33825}
33826
33827/**
33828 * Like `Array#splice`, but smarter for giant arrays.
33829 *
33830 * `Array#splice` takes all items to be inserted as individual argument which
33831 * causes a stack overflow in V8 when trying to insert 100k items for instance.
33832 *
33833 * Otherwise, this does not return the removed items, and takes `items` as an
33834 * array instead of rest parameters.
33835 *
33836 * @template {unknown} T
33837 * @param {T[]} list
33838 * @param {number} start
33839 * @param {number} remove
33840 * @param {T[]} items
33841 * @returns {void}
33842 */
33843function splice(list, start, remove, items) {
33844  const end = list.length;
33845  let chunkStart = 0;
33846  /** @type {unknown[]} */
33847
33848  let parameters; // Make start between zero and `end` (included).
33849
33850  if (start < 0) {
33851    start = -start > end ? 0 : end + start;
33852  } else {
33853    start = start > end ? end : start;
33854  }
33855
33856  remove = remove > 0 ? remove : 0; // No need to chunk the items if there’s only a couple (10k) items.
33857
33858  if (items.length < 10000) {
33859    parameters = Array.from(items);
33860    parameters.unshift(start, remove) // @ts-expect-error Hush, it’s fine.
33861    ;[].splice.apply(list, parameters);
33862  } else {
33863    // Delete `remove` items starting from `start`
33864    if (remove) [].splice.apply(list, [start, remove]); // Insert the items in chunks to not cause stack overflows.
33865
33866    while (chunkStart < items.length) {
33867      parameters = items.slice(chunkStart, chunkStart + 10000);
33868      parameters.unshift(start, 0) // @ts-expect-error Hush, it’s fine.
33869      ;[].splice.apply(list, parameters);
33870      chunkStart += 10000;
33871      start += 10000;
33872    }
33873  }
33874}
33875/**
33876 * Append `items` (an array) at the end of `list` (another array).
33877 * When `list` was empty, returns `items` instead.
33878 *
33879 * This prevents a potentially expensive operation when `list` is empty,
33880 * and adds items in batches to prevent V8 from hanging.
33881 *
33882 * @template {unknown} T
33883 * @param {T[]} list
33884 * @param {T[]} items
33885 * @returns {T[]}
33886 */
33887
33888function push(list, items) {
33889  if (list.length > 0) {
33890    splice(list, list.length, 0, items);
33891    return list
33892  }
33893
33894  return items
33895}
33896
33897/**
33898 * @typedef {import('micromark-util-types').NormalizedExtension} NormalizedExtension
33899 * @typedef {import('micromark-util-types').Extension} Extension
33900 * @typedef {import('micromark-util-types').Construct} Construct
33901 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
33902 */
33903
33904const hasOwnProperty = {}.hasOwnProperty;
33905
33906/**
33907 * Combine several syntax extensions into one.
33908 *
33909 * @param {Extension[]} extensions List of syntax extensions.
33910 * @returns {NormalizedExtension} A single combined extension.
33911 */
33912function combineExtensions(extensions) {
33913  /** @type {NormalizedExtension} */
33914  const all = {};
33915  let index = -1;
33916
33917  while (++index < extensions.length) {
33918    syntaxExtension(all, extensions[index]);
33919  }
33920
33921  return all
33922}
33923
33924/**
33925 * Merge `extension` into `all`.
33926 *
33927 * @param {NormalizedExtension} all Extension to merge into.
33928 * @param {Extension} extension Extension to merge.
33929 * @returns {void}
33930 */
33931function syntaxExtension(all, extension) {
33932  /** @type {string} */
33933  let hook;
33934
33935  for (hook in extension) {
33936    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined;
33937    const left = maybe || (all[hook] = {});
33938    const right = extension[hook];
33939    /** @type {string} */
33940    let code;
33941
33942    for (code in right) {
33943      if (!hasOwnProperty.call(left, code)) left[code] = [];
33944      const value = right[code];
33945      constructs(
33946        // @ts-expect-error Looks like a list.
33947        left[code],
33948        Array.isArray(value) ? value : value ? [value] : []
33949      );
33950    }
33951  }
33952}
33953
33954/**
33955 * Merge `list` into `existing` (both lists of constructs).
33956 * Mutates `existing`.
33957 *
33958 * @param {unknown[]} existing
33959 * @param {unknown[]} list
33960 * @returns {void}
33961 */
33962function constructs(existing, list) {
33963  let index = -1;
33964  /** @type {unknown[]} */
33965  const before = [];
33966
33967  while (++index < list.length) {
33968(list[index].add === 'after' ? existing : before).push(list[index]);
33969  }
33970
33971  splice(existing, 0, 0, before);
33972}
33973
33974/**
33975 * Combine several HTML extensions into one.
33976 *
33977 * @param {HtmlExtension[]} htmlExtensions List of HTML extensions.
33978 * @returns {HtmlExtension} A single combined extension.
33979 */
33980function combineHtmlExtensions(htmlExtensions) {
33981  /** @type {HtmlExtension} */
33982  const handlers = {};
33983  let index = -1;
33984
33985  while (++index < htmlExtensions.length) {
33986    htmlExtension(handlers, htmlExtensions[index]);
33987  }
33988
33989  return handlers
33990}
33991
33992/**
33993 * Merge `extension` into `all`.
33994 *
33995 * @param {HtmlExtension} all Extension to merge into.
33996 * @param {HtmlExtension} extension Extension to merge.
33997 * @returns {void}
33998 */
33999function htmlExtension(all, extension) {
34000  /** @type {string} */
34001  let hook;
34002
34003  for (hook in extension) {
34004    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined;
34005    const left = maybe || (all[hook] = {});
34006    const right = extension[hook];
34007    /** @type {string} */
34008    let type;
34009
34010    if (right) {
34011      for (type in right) {
34012        left[type] = right[type];
34013      }
34014    }
34015  }
34016}
34017
34018// This module is generated by `script/`.
34019//
34020// CommonMark handles attention (emphasis, strong) markers based on what comes
34021// before or after them.
34022// One such difference is if those characters are Unicode punctuation.
34023// This script is generated from the Unicode data.
34024const unicodePunctuationRegex =
34025  /[!-/:-@[-`{-~\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/;
34026
34027/**
34028 * @typedef {import('micromark-util-types').Code} Code
34029 */
34030/**
34031 * Check whether the character code represents an ASCII alpha (`a` through `z`,
34032 * case insensitive).
34033 *
34034 * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.
34035 *
34036 * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)
34037 * to U+005A (`Z`).
34038 *
34039 * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)
34040 * to U+007A (`z`).
34041 */
34042
34043const asciiAlpha = regexCheck(/[A-Za-z]/);
34044/**
34045 * Check whether the character code represents an ASCII digit (`0` through `9`).
34046 *
34047 * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to
34048 * U+0039 (`9`).
34049 */
34050
34051const asciiDigit = regexCheck(/\d/);
34052/**
34053 * Check whether the character code represents an ASCII hex digit (`a` through
34054 * `f`, case insensitive, or `0` through `9`).
34055 *
34056 * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex
34057 * digit, or an ASCII lower hex digit.
34058 *
34059 * An **ASCII upper hex digit** is a character in the inclusive range U+0041
34060 * (`A`) to U+0046 (`F`).
34061 *
34062 * An **ASCII lower hex digit** is a character in the inclusive range U+0061
34063 * (`a`) to U+0066 (`f`).
34064 */
34065
34066const asciiHexDigit = regexCheck(/[\dA-Fa-f]/);
34067/**
34068 * Check whether the character code represents an ASCII alphanumeric (`a`
34069 * through `z`, case insensitive, or `0` through `9`).
34070 *
34071 * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha
34072 * (see `asciiAlpha`).
34073 */
34074
34075const asciiAlphanumeric = regexCheck(/[\dA-Za-z]/);
34076/**
34077 * Check whether the character code represents ASCII punctuation.
34078 *
34079 * An **ASCII punctuation** is a character in the inclusive ranges U+0021
34080 * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT
34081 * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT
34082 * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).
34083 */
34084
34085const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);
34086/**
34087 * Check whether the character code represents an ASCII atext.
34088 *
34089 * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in
34090 * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),
34091 * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F
34092 * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E
34093 * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE
34094 * (`{`) to U+007E TILDE (`~`).
34095 *
34096 * See:
34097 * **\[RFC5322]**:
34098 * [Internet Message Format](https://tools.ietf.org/html/rfc5322).
34099 * P. Resnick.
34100 * IETF.
34101 */
34102
34103const asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/);
34104/**
34105 * Check whether a character code is an ASCII control character.
34106 *
34107 * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)
34108 * to U+001F (US), or U+007F (DEL).
34109 *
34110 * @param {Code} code
34111 * @returns {code is number}
34112 */
34113
34114function asciiControl(code) {
34115  return (
34116    // Special whitespace codes (which have negative values), C0 and Control
34117    // character DEL
34118    code !== null && (code < 32 || code === 127)
34119  )
34120}
34121/**
34122 * Check whether a character code is a markdown line ending (see
34123 * `markdownLineEnding`) or markdown space (see `markdownSpace`).
34124 *
34125 * @param {Code} code
34126 * @returns {code is number}
34127 */
34128
34129function markdownLineEndingOrSpace(code) {
34130  return code !== null && (code < 0 || code === 32)
34131}
34132/**
34133 * Check whether a character code is a markdown line ending.
34134 *
34135 * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN
34136 * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).
34137 *
34138 * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE
34139 * RETURN (CR) are replaced by these virtual characters depending on whether
34140 * they occurred together.
34141 *
34142 * @param {Code} code
34143 * @returns {code is number}
34144 */
34145
34146function markdownLineEnding(code) {
34147  return code !== null && code < -2
34148}
34149/**
34150 * Check whether a character code is a markdown space.
34151 *
34152 * A **markdown space** is the concrete character U+0020 SPACE (SP) and the
34153 * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).
34154 *
34155 * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is
34156 * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL
34157 * SPACE (VS) characters, depending on the column at which the tab occurred.
34158 *
34159 * @param {Code} code
34160 * @returns {code is number}
34161 */
34162
34163function markdownSpace(code) {
34164  return code === -2 || code === -1 || code === 32
34165}
34166/**
34167 * Check whether the character code represents Unicode whitespace.
34168 *
34169 * Note that this does handle micromark specific markdown whitespace characters.
34170 * See `markdownLineEndingOrSpace` to check that.
34171 *
34172 * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,
34173 * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),
34174 * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**).
34175 *
34176 * See:
34177 * **\[UNICODE]**:
34178 * [The Unicode Standard](https://www.unicode.org/versions/).
34179 * Unicode Consortium.
34180 */
34181
34182const unicodeWhitespace = regexCheck(/\s/);
34183/**
34184 * Check whether the character code represents Unicode punctuation.
34185 *
34186 * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,
34187 * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`
34188 * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`
34189 * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII
34190 * punctuation (see `asciiPunctuation`).
34191 *
34192 * See:
34193 * **\[UNICODE]**:
34194 * [The Unicode Standard](https://www.unicode.org/versions/).
34195 * Unicode Consortium.
34196 */
34197// Size note: removing ASCII from the regex and using `asciiPunctuation` here
34198// In fact adds to the bundle size.
34199
34200const unicodePunctuation = regexCheck(unicodePunctuationRegex);
34201/**
34202 * Create a code check from a regex.
34203 *
34204 * @param {RegExp} regex
34205 * @returns {(code: Code) => code is number}
34206 */
34207
34208function regexCheck(regex) {
34209  return check
34210  /**
34211   * Check whether a code matches the bound regex.
34212   *
34213   * @param {Code} code Character code
34214   * @returns {code is number} Whether the character code matches the bound regex
34215   */
34216
34217  function check(code) {
34218    return code !== null && regex.test(String.fromCharCode(code))
34219  }
34220}
34221
34222/**
34223 * @typedef {import('micromark-util-types').Effects} Effects
34224 * @typedef {import('micromark-util-types').State} State
34225 */
34226/**
34227 * @param {Effects} effects
34228 * @param {State} ok
34229 * @param {string} type
34230 * @param {number} [max=Infinity]
34231 * @returns {State}
34232 */
34233
34234function factorySpace(effects, ok, type, max) {
34235  const limit = max ? max - 1 : Number.POSITIVE_INFINITY;
34236  let size = 0;
34237  return start
34238  /** @type {State} */
34239
34240  function start(code) {
34241    if (markdownSpace(code)) {
34242      effects.enter(type);
34243      return prefix(code)
34244    }
34245
34246    return ok(code)
34247  }
34248  /** @type {State} */
34249
34250  function prefix(code) {
34251    if (markdownSpace(code) && size++ < limit) {
34252      effects.consume(code);
34253      return prefix
34254    }
34255
34256    effects.exit(type);
34257    return ok(code)
34258  }
34259}
34260
34261/**
34262 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
34263 * @typedef {import('micromark-util-types').Initializer} Initializer
34264 * @typedef {import('micromark-util-types').Token} Token
34265 * @typedef {import('micromark-util-types').State} State
34266 */
34267
34268/** @type {InitialConstruct} */
34269const content$1 = {
34270  tokenize: initializeContent
34271};
34272/** @type {Initializer} */
34273
34274function initializeContent(effects) {
34275  const contentStart = effects.attempt(
34276    this.parser.constructs.contentInitial,
34277    afterContentStartConstruct,
34278    paragraphInitial
34279  );
34280  /** @type {Token} */
34281
34282  let previous;
34283  return contentStart
34284  /** @type {State} */
34285
34286  function afterContentStartConstruct(code) {
34287    if (code === null) {
34288      effects.consume(code);
34289      return
34290    }
34291
34292    effects.enter('lineEnding');
34293    effects.consume(code);
34294    effects.exit('lineEnding');
34295    return factorySpace(effects, contentStart, 'linePrefix')
34296  }
34297  /** @type {State} */
34298
34299  function paragraphInitial(code) {
34300    effects.enter('paragraph');
34301    return lineStart(code)
34302  }
34303  /** @type {State} */
34304
34305  function lineStart(code) {
34306    const token = effects.enter('chunkText', {
34307      contentType: 'text',
34308      previous
34309    });
34310
34311    if (previous) {
34312      previous.next = token;
34313    }
34314
34315    previous = token;
34316    return data(code)
34317  }
34318  /** @type {State} */
34319
34320  function data(code) {
34321    if (code === null) {
34322      effects.exit('chunkText');
34323      effects.exit('paragraph');
34324      effects.consume(code);
34325      return
34326    }
34327
34328    if (markdownLineEnding(code)) {
34329      effects.consume(code);
34330      effects.exit('chunkText');
34331      return lineStart
34332    } // Data.
34333
34334    effects.consume(code);
34335    return data
34336  }
34337}
34338
34339/**
34340 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
34341 * @typedef {import('micromark-util-types').Initializer} Initializer
34342 * @typedef {import('micromark-util-types').Construct} Construct
34343 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
34344 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
34345 * @typedef {import('micromark-util-types').Token} Token
34346 * @typedef {import('micromark-util-types').State} State
34347 * @typedef {import('micromark-util-types').Point} Point
34348 */
34349/** @type {InitialConstruct} */
34350
34351const document$2 = {
34352  tokenize: initializeDocument
34353};
34354/** @type {Construct} */
34355
34356const containerConstruct = {
34357  tokenize: tokenizeContainer
34358};
34359/** @type {Initializer} */
34360
34361function initializeDocument(effects) {
34362  const self = this;
34363  /** @type {StackItem[]} */
34364
34365  const stack = [];
34366  let continued = 0;
34367  /** @type {TokenizeContext|undefined} */
34368
34369  let childFlow;
34370  /** @type {Token|undefined} */
34371
34372  let childToken;
34373  /** @type {number} */
34374
34375  let lineStartOffset;
34376  return start
34377  /** @type {State} */
34378
34379  function start(code) {
34380    // First we iterate through the open blocks, starting with the root
34381    // document, and descending through last children down to the last open
34382    // block.
34383    // Each block imposes a condition that the line must satisfy if the block is
34384    // to remain open.
34385    // For example, a block quote requires a `>` character.
34386    // A paragraph requires a non-blank line.
34387    // In this phase we may match all or just some of the open blocks.
34388    // But we cannot close unmatched blocks yet, because we may have a lazy
34389    // continuation line.
34390    if (continued < stack.length) {
34391      const item = stack[continued];
34392      self.containerState = item[1];
34393      return effects.attempt(
34394        item[0].continuation,
34395        documentContinue,
34396        checkNewContainers
34397      )(code)
34398    } // Done.
34399
34400    return checkNewContainers(code)
34401  }
34402  /** @type {State} */
34403
34404  function documentContinue(code) {
34405    if (self.containerState._closeFlow) closeFlow();
34406    continued++;
34407    return start(code)
34408  }
34409  /** @type {State} */
34410
34411  function checkNewContainers(code) {
34412    // Next, after consuming the continuation markers for existing blocks, we
34413    // look for new block starts (e.g. `>` for a block quote).
34414    // If we encounter a new block start, we close any blocks unmatched in
34415    // step 1 before creating the new block as a child of the last matched
34416    // block.
34417    if (continued === stack.length) {
34418      // No need to `check` whether there’s a container, of `exitContainers`
34419      // would be moot.
34420      // We can instead immediately `attempt` to parse one.
34421      if (!childFlow) {
34422        return documentContinued(code)
34423      } // If we have concrete content, such as block HTML or fenced code,
34424      // we can’t have containers “pierce” into them, so we can immediately
34425      // start.
34426
34427      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
34428        return flowStart(code)
34429      } // If we do have flow, it could still be a blank line,
34430      // but we’d be interrupting it w/ a new container if there’s a current
34431      // construct.
34432
34433      self.interrupt = Boolean(childFlow.currentConstruct);
34434    } // Check if there is a new container.
34435
34436    self.containerState = {};
34437    return effects.check(
34438      containerConstruct,
34439      thereIsANewContainer,
34440      thereIsNoNewContainer
34441    )(code)
34442  }
34443  /** @type {State} */
34444
34445  function thereIsANewContainer(code) {
34446    if (childFlow) closeFlow();
34447    exitContainers(continued);
34448    return documentContinued(code)
34449  }
34450  /** @type {State} */
34451
34452  function thereIsNoNewContainer(code) {
34453    self.parser.lazy[self.now().line] = continued !== stack.length;
34454    lineStartOffset = self.now().offset;
34455    return flowStart(code)
34456  }
34457  /** @type {State} */
34458
34459  function documentContinued(code) {
34460    // Try new containers.
34461    self.containerState = {};
34462    return effects.attempt(
34463      containerConstruct,
34464      containerContinue,
34465      flowStart
34466    )(code)
34467  }
34468  /** @type {State} */
34469
34470  function containerContinue(code) {
34471    continued++;
34472    stack.push([self.currentConstruct, self.containerState]); // Try another.
34473
34474    return documentContinued(code)
34475  }
34476  /** @type {State} */
34477
34478  function flowStart(code) {
34479    if (code === null) {
34480      if (childFlow) closeFlow();
34481      exitContainers(0);
34482      effects.consume(code);
34483      return
34484    }
34485
34486    childFlow = childFlow || self.parser.flow(self.now());
34487    effects.enter('chunkFlow', {
34488      contentType: 'flow',
34489      previous: childToken,
34490      _tokenizer: childFlow
34491    });
34492    return flowContinue(code)
34493  }
34494  /** @type {State} */
34495
34496  function flowContinue(code) {
34497    if (code === null) {
34498      writeToChild(effects.exit('chunkFlow'), true);
34499      exitContainers(0);
34500      effects.consume(code);
34501      return
34502    }
34503
34504    if (markdownLineEnding(code)) {
34505      effects.consume(code);
34506      writeToChild(effects.exit('chunkFlow')); // Get ready for the next line.
34507
34508      continued = 0;
34509      self.interrupt = undefined;
34510      return start
34511    }
34512
34513    effects.consume(code);
34514    return flowContinue
34515  }
34516  /**
34517   * @param {Token} token
34518   * @param {boolean} [eof]
34519   * @returns {void}
34520   */
34521
34522  function writeToChild(token, eof) {
34523    const stream = self.sliceStream(token);
34524    if (eof) stream.push(null);
34525    token.previous = childToken;
34526    if (childToken) childToken.next = token;
34527    childToken = token;
34528    childFlow.defineSkip(token.start);
34529    childFlow.write(stream); // Alright, so we just added a lazy line:
34530    //
34531    // ```markdown
34532    // > a
34533    // b.
34534    //
34535    // Or:
34536    //
34537    // > ~~~c
34538    // d
34539    //
34540    // Or:
34541    //
34542    // > | e |
34543    // f
34544    // ```
34545    //
34546    // The construct in the second example (fenced code) does not accept lazy
34547    // lines, so it marked itself as done at the end of its first line, and
34548    // then the content construct parses `d`.
34549    // Most constructs in markdown match on the first line: if the first line
34550    // forms a construct, a non-lazy line can’t “unmake” it.
34551    //
34552    // The construct in the third example is potentially a GFM table, and
34553    // those are *weird*.
34554    // It *could* be a table, from the first line, if the following line
34555    // matches a condition.
34556    // In this case, that second line is lazy, which “unmakes” the first line
34557    // and turns the whole into one content block.
34558    //
34559    // We’ve now parsed the non-lazy and the lazy line, and can figure out
34560    // whether the lazy line started a new flow block.
34561    // If it did, we exit the current containers between the two flow blocks.
34562
34563    if (self.parser.lazy[token.start.line]) {
34564      let index = childFlow.events.length;
34565
34566      while (index--) {
34567        if (
34568          // The token starts before the line ending…
34569          childFlow.events[index][1].start.offset < lineStartOffset &&
34570          (!childFlow.events[index][1].end || // …or ends after it.
34571            childFlow.events[index][1].end.offset > lineStartOffset)
34572        ) {
34573          // Exit: there’s still something open, which means it’s a lazy line
34574          // part of something.
34575          return
34576        }
34577      }
34578
34579      const indexBeforeExits = self.events.length;
34580      let indexBeforeFlow = indexBeforeExits;
34581      /** @type {boolean|undefined} */
34582
34583      let seen;
34584      /** @type {Point|undefined} */
34585
34586      let point; // Find the previous chunk (the one before the lazy line).
34587
34588      while (indexBeforeFlow--) {
34589        if (
34590          self.events[indexBeforeFlow][0] === 'exit' &&
34591          self.events[indexBeforeFlow][1].type === 'chunkFlow'
34592        ) {
34593          if (seen) {
34594            point = self.events[indexBeforeFlow][1].end;
34595            break
34596          }
34597
34598          seen = true;
34599        }
34600      }
34601
34602      exitContainers(continued); // Fix positions.
34603
34604      index = indexBeforeExits;
34605
34606      while (index < self.events.length) {
34607        self.events[index][1].end = Object.assign({}, point);
34608        index++;
34609      } // Inject the exits earlier (they’re still also at the end).
34610
34611      splice(
34612        self.events,
34613        indexBeforeFlow + 1,
34614        0,
34615        self.events.slice(indexBeforeExits)
34616      ); // Discard the duplicate exits.
34617
34618      self.events.length = index;
34619    }
34620  }
34621  /**
34622   * @param {number} size
34623   * @returns {void}
34624   */
34625
34626  function exitContainers(size) {
34627    let index = stack.length; // Exit open containers.
34628
34629    while (index-- > size) {
34630      const entry = stack[index];
34631      self.containerState = entry[1];
34632      entry[0].exit.call(self, effects);
34633    }
34634
34635    stack.length = size;
34636  }
34637
34638  function closeFlow() {
34639    childFlow.write([null]);
34640    childToken = undefined;
34641    childFlow = undefined;
34642    self.containerState._closeFlow = undefined;
34643  }
34644}
34645/** @type {Tokenizer} */
34646
34647function tokenizeContainer(effects, ok, nok) {
34648  return factorySpace(
34649    effects,
34650    effects.attempt(this.parser.constructs.document, ok, nok),
34651    'linePrefix',
34652    this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4
34653  )
34654}
34655
34656/**
34657 * @typedef {import('micromark-util-types').Code} Code
34658 */
34659
34660/**
34661 * Classify whether a character code represents whitespace, punctuation, or
34662 * something else.
34663 *
34664 * Used for attention (emphasis, strong), whose sequences can open or close
34665 * based on the class of surrounding characters.
34666 *
34667 * Note that eof (`null`) is seen as whitespace.
34668 *
34669 * @param {Code} code
34670 * @returns {number|undefined}
34671 */
34672function classifyCharacter(code) {
34673  if (
34674    code === null ||
34675    markdownLineEndingOrSpace(code) ||
34676    unicodeWhitespace(code)
34677  ) {
34678    return 1
34679  }
34680
34681  if (unicodePunctuation(code)) {
34682    return 2
34683  }
34684}
34685
34686/**
34687 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
34688 * @typedef {import('micromark-util-types').Event} Event
34689 * @typedef {import('micromark-util-types').Resolver} Resolver
34690 */
34691
34692/**
34693 * Call all `resolveAll`s.
34694 *
34695 * @param {{resolveAll?: Resolver}[]} constructs
34696 * @param {Event[]} events
34697 * @param {TokenizeContext} context
34698 * @returns {Event[]}
34699 */
34700function resolveAll(constructs, events, context) {
34701  /** @type {Resolver[]} */
34702  const called = [];
34703  let index = -1;
34704
34705  while (++index < constructs.length) {
34706    const resolve = constructs[index].resolveAll;
34707
34708    if (resolve && !called.includes(resolve)) {
34709      events = resolve(events, context);
34710      called.push(resolve);
34711    }
34712  }
34713
34714  return events
34715}
34716
34717/**
34718 * @typedef {import('micromark-util-types').Construct} Construct
34719 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
34720 * @typedef {import('micromark-util-types').Resolver} Resolver
34721 * @typedef {import('micromark-util-types').State} State
34722 * @typedef {import('micromark-util-types').Token} Token
34723 * @typedef {import('micromark-util-types').Event} Event
34724 * @typedef {import('micromark-util-types').Code} Code
34725 * @typedef {import('micromark-util-types').Point} Point
34726 */
34727
34728/** @type {Construct} */
34729const attention = {
34730  name: 'attention',
34731  tokenize: tokenizeAttention,
34732  resolveAll: resolveAllAttention
34733};
34734/**
34735 * Take all events and resolve attention to emphasis or strong.
34736 *
34737 * @type {Resolver}
34738 */
34739
34740function resolveAllAttention(events, context) {
34741  let index = -1;
34742  /** @type {number} */
34743
34744  let open;
34745  /** @type {Token} */
34746
34747  let group;
34748  /** @type {Token} */
34749
34750  let text;
34751  /** @type {Token} */
34752
34753  let openingSequence;
34754  /** @type {Token} */
34755
34756  let closingSequence;
34757  /** @type {number} */
34758
34759  let use;
34760  /** @type {Event[]} */
34761
34762  let nextEvents;
34763  /** @type {number} */
34764
34765  let offset; // Walk through all events.
34766  //
34767  // Note: performance of this is fine on an mb of normal markdown, but it’s
34768  // a bottleneck for malicious stuff.
34769
34770  while (++index < events.length) {
34771    // Find a token that can close.
34772    if (
34773      events[index][0] === 'enter' &&
34774      events[index][1].type === 'attentionSequence' &&
34775      events[index][1]._close
34776    ) {
34777      open = index; // Now walk back to find an opener.
34778
34779      while (open--) {
34780        // Find a token that can open the closer.
34781        if (
34782          events[open][0] === 'exit' &&
34783          events[open][1].type === 'attentionSequence' &&
34784          events[open][1]._open && // If the markers are the same:
34785          context.sliceSerialize(events[open][1]).charCodeAt(0) ===
34786            context.sliceSerialize(events[index][1]).charCodeAt(0)
34787        ) {
34788          // If the opening can close or the closing can open,
34789          // and the close size *is not* a multiple of three,
34790          // but the sum of the opening and closing size *is* multiple of three,
34791          // then don’t match.
34792          if (
34793            (events[open][1]._close || events[index][1]._open) &&
34794            (events[index][1].end.offset - events[index][1].start.offset) % 3 &&
34795            !(
34796              (events[open][1].end.offset -
34797                events[open][1].start.offset +
34798                events[index][1].end.offset -
34799                events[index][1].start.offset) %
34800              3
34801            )
34802          ) {
34803            continue
34804          } // Number of markers to use from the sequence.
34805
34806          use =
34807            events[open][1].end.offset - events[open][1].start.offset > 1 &&
34808            events[index][1].end.offset - events[index][1].start.offset > 1
34809              ? 2
34810              : 1;
34811          const start = Object.assign({}, events[open][1].end);
34812          const end = Object.assign({}, events[index][1].start);
34813          movePoint(start, -use);
34814          movePoint(end, use);
34815          openingSequence = {
34816            type: use > 1 ? 'strongSequence' : 'emphasisSequence',
34817            start,
34818            end: Object.assign({}, events[open][1].end)
34819          };
34820          closingSequence = {
34821            type: use > 1 ? 'strongSequence' : 'emphasisSequence',
34822            start: Object.assign({}, events[index][1].start),
34823            end
34824          };
34825          text = {
34826            type: use > 1 ? 'strongText' : 'emphasisText',
34827            start: Object.assign({}, events[open][1].end),
34828            end: Object.assign({}, events[index][1].start)
34829          };
34830          group = {
34831            type: use > 1 ? 'strong' : 'emphasis',
34832            start: Object.assign({}, openingSequence.start),
34833            end: Object.assign({}, closingSequence.end)
34834          };
34835          events[open][1].end = Object.assign({}, openingSequence.start);
34836          events[index][1].start = Object.assign({}, closingSequence.end);
34837          nextEvents = []; // If there are more markers in the opening, add them before.
34838
34839          if (events[open][1].end.offset - events[open][1].start.offset) {
34840            nextEvents = push(nextEvents, [
34841              ['enter', events[open][1], context],
34842              ['exit', events[open][1], context]
34843            ]);
34844          } // Opening.
34845
34846          nextEvents = push(nextEvents, [
34847            ['enter', group, context],
34848            ['enter', openingSequence, context],
34849            ['exit', openingSequence, context],
34850            ['enter', text, context]
34851          ]); // Between.
34852
34853          nextEvents = push(
34854            nextEvents,
34855            resolveAll(
34856              context.parser.constructs.insideSpan.null,
34857              events.slice(open + 1, index),
34858              context
34859            )
34860          ); // Closing.
34861
34862          nextEvents = push(nextEvents, [
34863            ['exit', text, context],
34864            ['enter', closingSequence, context],
34865            ['exit', closingSequence, context],
34866            ['exit', group, context]
34867          ]); // If there are more markers in the closing, add them after.
34868
34869          if (events[index][1].end.offset - events[index][1].start.offset) {
34870            offset = 2;
34871            nextEvents = push(nextEvents, [
34872              ['enter', events[index][1], context],
34873              ['exit', events[index][1], context]
34874            ]);
34875          } else {
34876            offset = 0;
34877          }
34878
34879          splice(events, open - 1, index - open + 3, nextEvents);
34880          index = open + nextEvents.length - offset - 2;
34881          break
34882        }
34883      }
34884    }
34885  } // Remove remaining sequences.
34886
34887  index = -1;
34888
34889  while (++index < events.length) {
34890    if (events[index][1].type === 'attentionSequence') {
34891      events[index][1].type = 'data';
34892    }
34893  }
34894
34895  return events
34896}
34897/** @type {Tokenizer} */
34898
34899function tokenizeAttention(effects, ok) {
34900  const before = classifyCharacter(this.previous);
34901  /** @type {NonNullable<Code>} */
34902
34903  let marker;
34904  return start
34905  /** @type {State} */
34906
34907  function start(code) {
34908    effects.enter('attentionSequence');
34909    marker = code;
34910    return sequence(code)
34911  }
34912  /** @type {State} */
34913
34914  function sequence(code) {
34915    if (code === marker) {
34916      effects.consume(code);
34917      return sequence
34918    }
34919
34920    const token = effects.exit('attentionSequence');
34921    const after = classifyCharacter(code);
34922    const open = !after || (after === 2 && before);
34923    const close = !before || (before === 2 && after);
34924    token._open = Boolean(marker === 42 ? open : open && (before || !close));
34925    token._close = Boolean(marker === 42 ? close : close && (after || !open));
34926    return ok(code)
34927  }
34928}
34929/**
34930 * Move a point a bit.
34931 *
34932 * Note: `move` only works inside lines! It’s not possible to move past other
34933 * chunks (replacement characters, tabs, or line endings).
34934 *
34935 * @param {Point} point
34936 * @param {number} offset
34937 * @returns {void}
34938 */
34939
34940function movePoint(point, offset) {
34941  point.column += offset;
34942  point.offset += offset;
34943  point._bufferIndex += offset;
34944}
34945
34946/**
34947 * @typedef {import('micromark-util-types').Construct} Construct
34948 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
34949 * @typedef {import('micromark-util-types').State} State
34950 */
34951
34952/** @type {Construct} */
34953const autolink = {
34954  name: 'autolink',
34955  tokenize: tokenizeAutolink
34956};
34957/** @type {Tokenizer} */
34958
34959function tokenizeAutolink(effects, ok, nok) {
34960  let size = 1;
34961  return start
34962  /** @type {State} */
34963
34964  function start(code) {
34965    effects.enter('autolink');
34966    effects.enter('autolinkMarker');
34967    effects.consume(code);
34968    effects.exit('autolinkMarker');
34969    effects.enter('autolinkProtocol');
34970    return open
34971  }
34972  /** @type {State} */
34973
34974  function open(code) {
34975    if (asciiAlpha(code)) {
34976      effects.consume(code);
34977      return schemeOrEmailAtext
34978    }
34979
34980    return asciiAtext(code) ? emailAtext(code) : nok(code)
34981  }
34982  /** @type {State} */
34983
34984  function schemeOrEmailAtext(code) {
34985    return code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)
34986      ? schemeInsideOrEmailAtext(code)
34987      : emailAtext(code)
34988  }
34989  /** @type {State} */
34990
34991  function schemeInsideOrEmailAtext(code) {
34992    if (code === 58) {
34993      effects.consume(code);
34994      return urlInside
34995    }
34996
34997    if (
34998      (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) &&
34999      size++ < 32
35000    ) {
35001      effects.consume(code);
35002      return schemeInsideOrEmailAtext
35003    }
35004
35005    return emailAtext(code)
35006  }
35007  /** @type {State} */
35008
35009  function urlInside(code) {
35010    if (code === 62) {
35011      effects.exit('autolinkProtocol');
35012      return end(code)
35013    }
35014
35015    if (code === null || code === 32 || code === 60 || asciiControl(code)) {
35016      return nok(code)
35017    }
35018
35019    effects.consume(code);
35020    return urlInside
35021  }
35022  /** @type {State} */
35023
35024  function emailAtext(code) {
35025    if (code === 64) {
35026      effects.consume(code);
35027      size = 0;
35028      return emailAtSignOrDot
35029    }
35030
35031    if (asciiAtext(code)) {
35032      effects.consume(code);
35033      return emailAtext
35034    }
35035
35036    return nok(code)
35037  }
35038  /** @type {State} */
35039
35040  function emailAtSignOrDot(code) {
35041    return asciiAlphanumeric(code) ? emailLabel(code) : nok(code)
35042  }
35043  /** @type {State} */
35044
35045  function emailLabel(code) {
35046    if (code === 46) {
35047      effects.consume(code);
35048      size = 0;
35049      return emailAtSignOrDot
35050    }
35051
35052    if (code === 62) {
35053      // Exit, then change the type.
35054      effects.exit('autolinkProtocol').type = 'autolinkEmail';
35055      return end(code)
35056    }
35057
35058    return emailValue(code)
35059  }
35060  /** @type {State} */
35061
35062  function emailValue(code) {
35063    if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) {
35064      effects.consume(code);
35065      return code === 45 ? emailValue : emailLabel
35066    }
35067
35068    return nok(code)
35069  }
35070  /** @type {State} */
35071
35072  function end(code) {
35073    effects.enter('autolinkMarker');
35074    effects.consume(code);
35075    effects.exit('autolinkMarker');
35076    effects.exit('autolink');
35077    return ok
35078  }
35079}
35080
35081/**
35082 * @typedef {import('micromark-util-types').Construct} Construct
35083 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
35084 * @typedef {import('micromark-util-types').State} State
35085 */
35086
35087/** @type {Construct} */
35088const blankLine = {
35089  tokenize: tokenizeBlankLine,
35090  partial: true
35091};
35092/** @type {Tokenizer} */
35093
35094function tokenizeBlankLine(effects, ok, nok) {
35095  return factorySpace(effects, afterWhitespace, 'linePrefix')
35096  /** @type {State} */
35097
35098  function afterWhitespace(code) {
35099    return code === null || markdownLineEnding(code) ? ok(code) : nok(code)
35100  }
35101}
35102
35103/**
35104 * @typedef {import('micromark-util-types').Construct} Construct
35105 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
35106 * @typedef {import('micromark-util-types').Exiter} Exiter
35107 * @typedef {import('micromark-util-types').State} State
35108 */
35109
35110/** @type {Construct} */
35111const blockQuote = {
35112  name: 'blockQuote',
35113  tokenize: tokenizeBlockQuoteStart,
35114  continuation: {
35115    tokenize: tokenizeBlockQuoteContinuation
35116  },
35117  exit: exit$1
35118};
35119/** @type {Tokenizer} */
35120
35121function tokenizeBlockQuoteStart(effects, ok, nok) {
35122  const self = this;
35123  return start
35124  /** @type {State} */
35125
35126  function start(code) {
35127    if (code === 62) {
35128      const state = self.containerState;
35129
35130      if (!state.open) {
35131        effects.enter('blockQuote', {
35132          _container: true
35133        });
35134        state.open = true;
35135      }
35136
35137      effects.enter('blockQuotePrefix');
35138      effects.enter('blockQuoteMarker');
35139      effects.consume(code);
35140      effects.exit('blockQuoteMarker');
35141      return after
35142    }
35143
35144    return nok(code)
35145  }
35146  /** @type {State} */
35147
35148  function after(code) {
35149    if (markdownSpace(code)) {
35150      effects.enter('blockQuotePrefixWhitespace');
35151      effects.consume(code);
35152      effects.exit('blockQuotePrefixWhitespace');
35153      effects.exit('blockQuotePrefix');
35154      return ok
35155    }
35156
35157    effects.exit('blockQuotePrefix');
35158    return ok(code)
35159  }
35160}
35161/** @type {Tokenizer} */
35162
35163function tokenizeBlockQuoteContinuation(effects, ok, nok) {
35164  return factorySpace(
35165    effects,
35166    effects.attempt(blockQuote, ok, nok),
35167    'linePrefix',
35168    this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4
35169  )
35170}
35171/** @type {Exiter} */
35172
35173function exit$1(effects) {
35174  effects.exit('blockQuote');
35175}
35176
35177/**
35178 * @typedef {import('micromark-util-types').Construct} Construct
35179 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
35180 * @typedef {import('micromark-util-types').State} State
35181 */
35182
35183/** @type {Construct} */
35184const characterEscape$1 = {
35185  name: 'characterEscape',
35186  tokenize: tokenizeCharacterEscape
35187};
35188/** @type {Tokenizer} */
35189
35190function tokenizeCharacterEscape(effects, ok, nok) {
35191  return start
35192  /** @type {State} */
35193
35194  function start(code) {
35195    effects.enter('characterEscape');
35196    effects.enter('escapeMarker');
35197    effects.consume(code);
35198    effects.exit('escapeMarker');
35199    return open
35200  }
35201  /** @type {State} */
35202
35203  function open(code) {
35204    if (asciiPunctuation(code)) {
35205      effects.enter('characterEscapeValue');
35206      effects.consume(code);
35207      effects.exit('characterEscapeValue');
35208      effects.exit('characterEscape');
35209      return ok
35210    }
35211
35212    return nok(code)
35213  }
35214}
35215
35216var characterEntities = {
35217  AEli: 'Æ',
35218  AElig: 'Æ',
35219  AM: '&',
35220  AMP: '&',
35221  Aacut: 'Á',
35222  Aacute: 'Á',
35223  Abreve: 'Ă',
35224  Acir: 'Â',
35225  Acirc: 'Â',
35226  Acy: 'А',
35227  Afr: '��',
35228  Agrav: 'À',
35229  Agrave: 'À',
35230  Alpha: 'Α',
35231  Amacr: 'Ā',
35232  And: '⩓',
35233  Aogon: 'Ą',
35234  Aopf: '��',
35235  ApplyFunction: '⁡',
35236  Arin: 'Å',
35237  Aring: 'Å',
35238  Ascr: '��',
35239  Assign: '≔',
35240  Atild: 'Ã',
35241  Atilde: 'Ã',
35242  Aum: 'Ä',
35243  Auml: 'Ä',
35244  Backslash: '∖',
35245  Barv: '⫧',
35246  Barwed: '⌆',
35247  Bcy: 'Б',
35248  Because: '∵',
35249  Bernoullis: 'ℬ',
35250  Beta: 'Β',
35251  Bfr: '��',
35252  Bopf: '��',
35253  Breve: '˘',
35254  Bscr: 'ℬ',
35255  Bumpeq: '≎',
35256  CHcy: 'Ч',
35257  COP: '©',
35258  COPY: '©',
35259  Cacute: 'Ć',
35260  Cap: '⋒',
35261  CapitalDifferentialD: 'ⅅ',
35262  Cayleys: 'ℭ',
35263  Ccaron: 'Č',
35264  Ccedi: 'Ç',
35265  Ccedil: 'Ç',
35266  Ccirc: 'Ĉ',
35267  Cconint: '∰',
35268  Cdot: 'Ċ',
35269  Cedilla: '¸',
35270  CenterDot: '·',
35271  Cfr: 'ℭ',
35272  Chi: 'Χ',
35273  CircleDot: '⊙',
35274  CircleMinus: '⊖',
35275  CirclePlus: '⊕',
35276  CircleTimes: '⊗',
35277  ClockwiseContourIntegral: '∲',
35278  CloseCurlyDoubleQuote: '”',
35279  CloseCurlyQuote: '’',
35280  Colon: '∷',
35281  Colone: '⩴',
35282  Congruent: '≡',
35283  Conint: '∯',
35284  ContourIntegral: '∮',
35285  Copf: 'ℂ',
35286  Coproduct: '∐',
35287  CounterClockwiseContourIntegral: '∳',
35288  Cross: '⨯',
35289  Cscr: '��',
35290  Cup: '⋓',
35291  CupCap: '≍',
35292  DD: 'ⅅ',
35293  DDotrahd: '⤑',
35294  DJcy: 'Ђ',
35295  DScy: 'Ѕ',
35296  DZcy: 'Џ',
35297  Dagger: '‡',
35298  Darr: '↡',
35299  Dashv: '⫤',
35300  Dcaron: 'Ď',
35301  Dcy: 'Д',
35302  Del: '∇',
35303  Delta: 'Δ',
35304  Dfr: '��',
35305  DiacriticalAcute: '´',
35306  DiacriticalDot: '˙',
35307  DiacriticalDoubleAcute: '˝',
35308  DiacriticalGrave: '`',
35309  DiacriticalTilde: '˜',
35310  Diamond: '⋄',
35311  DifferentialD: 'ⅆ',
35312  Dopf: '��',
35313  Dot: '¨',
35314  DotDot: '⃜',
35315  DotEqual: '≐',
35316  DoubleContourIntegral: '∯',
35317  DoubleDot: '¨',
35318  DoubleDownArrow: '⇓',
35319  DoubleLeftArrow: '⇐',
35320  DoubleLeftRightArrow: '⇔',
35321  DoubleLeftTee: '⫤',
35322  DoubleLongLeftArrow: '⟸',
35323  DoubleLongLeftRightArrow: '⟺',
35324  DoubleLongRightArrow: '⟹',
35325  DoubleRightArrow: '⇒',
35326  DoubleRightTee: '⊨',
35327  DoubleUpArrow: '⇑',
35328  DoubleUpDownArrow: '⇕',
35329  DoubleVerticalBar: '∥',
35330  DownArrow: '↓',
35331  DownArrowBar: '⤓',
35332  DownArrowUpArrow: '⇵',
35333  DownBreve: '̑',
35334  DownLeftRightVector: '⥐',
35335  DownLeftTeeVector: '⥞',
35336  DownLeftVector: '↽',
35337  DownLeftVectorBar: '⥖',
35338  DownRightTeeVector: '⥟',
35339  DownRightVector: '⇁',
35340  DownRightVectorBar: '⥗',
35341  DownTee: '⊤',
35342  DownTeeArrow: '↧',
35343  Downarrow: '⇓',
35344  Dscr: '��',
35345  Dstrok: 'Đ',
35346  ENG: 'Ŋ',
35347  ET: 'Ð',
35348  ETH: 'Ð',
35349  Eacut: 'É',
35350  Eacute: 'É',
35351  Ecaron: 'Ě',
35352  Ecir: 'Ê',
35353  Ecirc: 'Ê',
35354  Ecy: 'Э',
35355  Edot: 'Ė',
35356  Efr: '��',
35357  Egrav: 'È',
35358  Egrave: 'È',
35359  Element: '∈',
35360  Emacr: 'Ē',
35361  EmptySmallSquare: '◻',
35362  EmptyVerySmallSquare: '▫',
35363  Eogon: 'Ę',
35364  Eopf: '��',
35365  Epsilon: 'Ε',
35366  Equal: '⩵',
35367  EqualTilde: '≂',
35368  Equilibrium: '⇌',
35369  Escr: 'ℰ',
35370  Esim: '⩳',
35371  Eta: 'Η',
35372  Eum: 'Ë',
35373  Euml: 'Ë',
35374  Exists: '∃',
35375  ExponentialE: 'ⅇ',
35376  Fcy: 'Ф',
35377  Ffr: '��',
35378  FilledSmallSquare: '◼',
35379  FilledVerySmallSquare: '▪',
35380  Fopf: '��',
35381  ForAll: '∀',
35382  Fouriertrf: 'ℱ',
35383  Fscr: 'ℱ',
35384  GJcy: 'Ѓ',
35385  G: '>',
35386  GT: '>',
35387  Gamma: 'Γ',
35388  Gammad: 'Ϝ',
35389  Gbreve: 'Ğ',
35390  Gcedil: 'Ģ',
35391  Gcirc: 'Ĝ',
35392  Gcy: 'Г',
35393  Gdot: 'Ġ',
35394  Gfr: '��',
35395  Gg: '⋙',
35396  Gopf: '��',
35397  GreaterEqual: '≥',
35398  GreaterEqualLess: '⋛',
35399  GreaterFullEqual: '≧',
35400  GreaterGreater: '⪢',
35401  GreaterLess: '≷',
35402  GreaterSlantEqual: '⩾',
35403  GreaterTilde: '≳',
35404  Gscr: '��',
35405  Gt: '≫',
35406  HARDcy: 'Ъ',
35407  Hacek: 'ˇ',
35408  Hat: '^',
35409  Hcirc: 'Ĥ',
35410  Hfr: 'ℌ',
35411  HilbertSpace: 'ℋ',
35412  Hopf: 'ℍ',
35413  HorizontalLine: '─',
35414  Hscr: 'ℋ',
35415  Hstrok: 'Ħ',
35416  HumpDownHump: '≎',
35417  HumpEqual: '≏',
35418  IEcy: 'Е',
35419  IJlig: 'IJ',
35420  IOcy: 'Ё',
35421  Iacut: 'Í',
35422  Iacute: 'Í',
35423  Icir: 'Î',
35424  Icirc: 'Î',
35425  Icy: 'И',
35426  Idot: 'İ',
35427  Ifr: 'ℑ',
35428  Igrav: 'Ì',
35429  Igrave: 'Ì',
35430  Im: 'ℑ',
35431  Imacr: 'Ī',
35432  ImaginaryI: 'ⅈ',
35433  Implies: '⇒',
35434  Int: '∬',
35435  Integral: '∫',
35436  Intersection: '⋂',
35437  InvisibleComma: '⁣',
35438  InvisibleTimes: '⁢',
35439  Iogon: 'Į',
35440  Iopf: '��',
35441  Iota: 'Ι',
35442  Iscr: 'ℐ',
35443  Itilde: 'Ĩ',
35444  Iukcy: 'І',
35445  Ium: 'Ï',
35446  Iuml: 'Ï',
35447  Jcirc: 'Ĵ',
35448  Jcy: 'Й',
35449  Jfr: '��',
35450  Jopf: '��',
35451  Jscr: '��',
35452  Jsercy: 'Ј',
35453  Jukcy: 'Є',
35454  KHcy: 'Х',
35455  KJcy: 'Ќ',
35456  Kappa: 'Κ',
35457  Kcedil: 'Ķ',
35458  Kcy: 'К',
35459  Kfr: '��',
35460  Kopf: '��',
35461  Kscr: '��',
35462  LJcy: 'Љ',
35463  L: '<',
35464  LT: '<',
35465  Lacute: 'Ĺ',
35466  Lambda: 'Λ',
35467  Lang: '⟪',
35468  Laplacetrf: 'ℒ',
35469  Larr: '↞',
35470  Lcaron: 'Ľ',
35471  Lcedil: 'Ļ',
35472  Lcy: 'Л',
35473  LeftAngleBracket: '⟨',
35474  LeftArrow: '←',
35475  LeftArrowBar: '⇤',
35476  LeftArrowRightArrow: '⇆',
35477  LeftCeiling: '⌈',
35478  LeftDoubleBracket: '⟦',
35479  LeftDownTeeVector: '⥡',
35480  LeftDownVector: '⇃',
35481  LeftDownVectorBar: '⥙',
35482  LeftFloor: '⌊',
35483  LeftRightArrow: '↔',
35484  LeftRightVector: '⥎',
35485  LeftTee: '⊣',
35486  LeftTeeArrow: '↤',
35487  LeftTeeVector: '⥚',
35488  LeftTriangle: '⊲',
35489  LeftTriangleBar: '⧏',
35490  LeftTriangleEqual: '⊴',
35491  LeftUpDownVector: '⥑',
35492  LeftUpTeeVector: '⥠',
35493  LeftUpVector: '↿',
35494  LeftUpVectorBar: '⥘',
35495  LeftVector: '↼',
35496  LeftVectorBar: '⥒',
35497  Leftarrow: '⇐',
35498  Leftrightarrow: '⇔',
35499  LessEqualGreater: '⋚',
35500  LessFullEqual: '≦',
35501  LessGreater: '≶',
35502  LessLess: '⪡',
35503  LessSlantEqual: '⩽',
35504  LessTilde: '≲',
35505  Lfr: '��',
35506  Ll: '⋘',
35507  Lleftarrow: '⇚',
35508  Lmidot: 'Ŀ',
35509  LongLeftArrow: '⟵',
35510  LongLeftRightArrow: '⟷',
35511  LongRightArrow: '⟶',
35512  Longleftarrow: '⟸',
35513  Longleftrightarrow: '⟺',
35514  Longrightarrow: '⟹',
35515  Lopf: '��',
35516  LowerLeftArrow: '↙',
35517  LowerRightArrow: '↘',
35518  Lscr: 'ℒ',
35519  Lsh: '↰',
35520  Lstrok: 'Ł',
35521  Lt: '≪',
35522  Map: '⤅',
35523  Mcy: 'М',
35524  MediumSpace: ' ',
35525  Mellintrf: 'ℳ',
35526  Mfr: '��',
35527  MinusPlus: '∓',
35528  Mopf: '��',
35529  Mscr: 'ℳ',
35530  Mu: 'Μ',
35531  NJcy: 'Њ',
35532  Nacute: 'Ń',
35533  Ncaron: 'Ň',
35534  Ncedil: 'Ņ',
35535  Ncy: 'Н',
35536  NegativeMediumSpace: '​',
35537  NegativeThickSpace: '​',
35538  NegativeThinSpace: '​',
35539  NegativeVeryThinSpace: '​',
35540  NestedGreaterGreater: '≫',
35541  NestedLessLess: '≪',
35542  NewLine: '\n',
35543  Nfr: '��',
35544  NoBreak: '⁠',
35545  NonBreakingSpace: ' ',
35546  Nopf: 'ℕ',
35547  Not: '⫬',
35548  NotCongruent: '≢',
35549  NotCupCap: '≭',
35550  NotDoubleVerticalBar: '∦',
35551  NotElement: '∉',
35552  NotEqual: '≠',
35553  NotEqualTilde: '≂̸',
35554  NotExists: '∄',
35555  NotGreater: '≯',
35556  NotGreaterEqual: '≱',
35557  NotGreaterFullEqual: '≧̸',
35558  NotGreaterGreater: '≫̸',
35559  NotGreaterLess: '≹',
35560  NotGreaterSlantEqual: '⩾̸',
35561  NotGreaterTilde: '≵',
35562  NotHumpDownHump: '≎̸',
35563  NotHumpEqual: '≏̸',
35564  NotLeftTriangle: '⋪',
35565  NotLeftTriangleBar: '⧏̸',
35566  NotLeftTriangleEqual: '⋬',
35567  NotLess: '≮',
35568  NotLessEqual: '≰',
35569  NotLessGreater: '≸',
35570  NotLessLess: '≪̸',
35571  NotLessSlantEqual: '⩽̸',
35572  NotLessTilde: '≴',
35573  NotNestedGreaterGreater: '⪢̸',
35574  NotNestedLessLess: '⪡̸',
35575  NotPrecedes: '⊀',
35576  NotPrecedesEqual: '⪯̸',
35577  NotPrecedesSlantEqual: '⋠',
35578  NotReverseElement: '∌',
35579  NotRightTriangle: '⋫',
35580  NotRightTriangleBar: '⧐̸',
35581  NotRightTriangleEqual: '⋭',
35582  NotSquareSubset: '⊏̸',
35583  NotSquareSubsetEqual: '⋢',
35584  NotSquareSuperset: '⊐̸',
35585  NotSquareSupersetEqual: '⋣',
35586  NotSubset: '⊂⃒',
35587  NotSubsetEqual: '⊈',
35588  NotSucceeds: '⊁',
35589  NotSucceedsEqual: '⪰̸',
35590  NotSucceedsSlantEqual: '⋡',
35591  NotSucceedsTilde: '≿̸',
35592  NotSuperset: '⊃⃒',
35593  NotSupersetEqual: '⊉',
35594  NotTilde: '≁',
35595  NotTildeEqual: '≄',
35596  NotTildeFullEqual: '≇',
35597  NotTildeTilde: '≉',
35598  NotVerticalBar: '∤',
35599  Nscr: '��',
35600  Ntild: 'Ñ',
35601  Ntilde: 'Ñ',
35602  Nu: 'Ν',
35603  OElig: 'Œ',
35604  Oacut: 'Ó',
35605  Oacute: 'Ó',
35606  Ocir: 'Ô',
35607  Ocirc: 'Ô',
35608  Ocy: 'О',
35609  Odblac: 'Ő',
35610  Ofr: '��',
35611  Ograv: 'Ò',
35612  Ograve: 'Ò',
35613  Omacr: 'Ō',
35614  Omega: 'Ω',
35615  Omicron: 'Ο',
35616  Oopf: '��',
35617  OpenCurlyDoubleQuote: '“',
35618  OpenCurlyQuote: '‘',
35619  Or: '⩔',
35620  Oscr: '��',
35621  Oslas: 'Ø',
35622  Oslash: 'Ø',
35623  Otild: 'Õ',
35624  Otilde: 'Õ',
35625  Otimes: '⨷',
35626  Oum: 'Ö',
35627  Ouml: 'Ö',
35628  OverBar: '‾',
35629  OverBrace: '⏞',
35630  OverBracket: '⎴',
35631  OverParenthesis: '⏜',
35632  PartialD: '∂',
35633  Pcy: 'П',
35634  Pfr: '��',
35635  Phi: 'Φ',
35636  Pi: 'Π',
35637  PlusMinus: '±',
35638  Poincareplane: 'ℌ',
35639  Popf: 'ℙ',
35640  Pr: '⪻',
35641  Precedes: '≺',
35642  PrecedesEqual: '⪯',
35643  PrecedesSlantEqual: '≼',
35644  PrecedesTilde: '≾',
35645  Prime: '″',
35646  Product: '∏',
35647  Proportion: '∷',
35648  Proportional: '∝',
35649  Pscr: '��',
35650  Psi: 'Ψ',
35651  QUO: '"',
35652  QUOT: '"',
35653  Qfr: '��',
35654  Qopf: 'ℚ',
35655  Qscr: '��',
35656  RBarr: '⤐',
35657  RE: '®',
35658  REG: '®',
35659  Racute: 'Ŕ',
35660  Rang: '⟫',
35661  Rarr: '↠',
35662  Rarrtl: '⤖',
35663  Rcaron: 'Ř',
35664  Rcedil: 'Ŗ',
35665  Rcy: 'Р',
35666  Re: 'ℜ',
35667  ReverseElement: '∋',
35668  ReverseEquilibrium: '⇋',
35669  ReverseUpEquilibrium: '⥯',
35670  Rfr: 'ℜ',
35671  Rho: 'Ρ',
35672  RightAngleBracket: '⟩',
35673  RightArrow: '→',
35674  RightArrowBar: '⇥',
35675  RightArrowLeftArrow: '⇄',
35676  RightCeiling: '⌉',
35677  RightDoubleBracket: '⟧',
35678  RightDownTeeVector: '⥝',
35679  RightDownVector: '⇂',
35680  RightDownVectorBar: '⥕',
35681  RightFloor: '⌋',
35682  RightTee: '⊢',
35683  RightTeeArrow: '↦',
35684  RightTeeVector: '⥛',
35685  RightTriangle: '⊳',
35686  RightTriangleBar: '⧐',
35687  RightTriangleEqual: '⊵',
35688  RightUpDownVector: '⥏',
35689  RightUpTeeVector: '⥜',
35690  RightUpVector: '↾',
35691  RightUpVectorBar: '⥔',
35692  RightVector: '⇀',
35693  RightVectorBar: '⥓',
35694  Rightarrow: '⇒',
35695  Ropf: 'ℝ',
35696  RoundImplies: '⥰',
35697  Rrightarrow: '⇛',
35698  Rscr: 'ℛ',
35699  Rsh: '↱',
35700  RuleDelayed: '⧴',
35701  SHCHcy: 'Щ',
35702  SHcy: 'Ш',
35703  SOFTcy: 'Ь',
35704  Sacute: 'Ś',
35705  Sc: '⪼',
35706  Scaron: 'Š',
35707  Scedil: 'Ş',
35708  Scirc: 'Ŝ',
35709  Scy: 'С',
35710  Sfr: '��',
35711  ShortDownArrow: '↓',
35712  ShortLeftArrow: '←',
35713  ShortRightArrow: '→',
35714  ShortUpArrow: '↑',
35715  Sigma: 'Σ',
35716  SmallCircle: '∘',
35717  Sopf: '��',
35718  Sqrt: '√',
35719  Square: '□',
35720  SquareIntersection: '⊓',
35721  SquareSubset: '⊏',
35722  SquareSubsetEqual: '⊑',
35723  SquareSuperset: '⊐',
35724  SquareSupersetEqual: '⊒',
35725  SquareUnion: '⊔',
35726  Sscr: '��',
35727  Star: '⋆',
35728  Sub: '⋐',
35729  Subset: '⋐',
35730  SubsetEqual: '⊆',
35731  Succeeds: '≻',
35732  SucceedsEqual: '⪰',
35733  SucceedsSlantEqual: '≽',
35734  SucceedsTilde: '≿',
35735  SuchThat: '∋',
35736  Sum: '∑',
35737  Sup: '⋑',
35738  Superset: '⊃',
35739  SupersetEqual: '⊇',
35740  Supset: '⋑',
35741  THOR: 'Þ',
35742  THORN: 'Þ',
35743  TRADE: '™',
35744  TSHcy: 'Ћ',
35745  TScy: 'Ц',
35746  Tab: '\t',
35747  Tau: 'Τ',
35748  Tcaron: 'Ť',
35749  Tcedil: 'Ţ',
35750  Tcy: 'Т',
35751  Tfr: '��',
35752  Therefore: '∴',
35753  Theta: 'Θ',
35754  ThickSpace: '  ',
35755  ThinSpace: ' ',
35756  Tilde: '∼',
35757  TildeEqual: '≃',
35758  TildeFullEqual: '≅',
35759  TildeTilde: '≈',
35760  Topf: '��',
35761  TripleDot: '⃛',
35762  Tscr: '��',
35763  Tstrok: 'Ŧ',
35764  Uacut: 'Ú',
35765  Uacute: 'Ú',
35766  Uarr: '↟',
35767  Uarrocir: '⥉',
35768  Ubrcy: 'Ў',
35769  Ubreve: 'Ŭ',
35770  Ucir: 'Û',
35771  Ucirc: 'Û',
35772  Ucy: 'У',
35773  Udblac: 'Ű',
35774  Ufr: '��',
35775  Ugrav: 'Ù',
35776  Ugrave: 'Ù',
35777  Umacr: 'Ū',
35778  UnderBar: '_',
35779  UnderBrace: '⏟',
35780  UnderBracket: '⎵',
35781  UnderParenthesis: '⏝',
35782  Union: '⋃',
35783  UnionPlus: '⊎',
35784  Uogon: 'Ų',
35785  Uopf: '��',
35786  UpArrow: '↑',
35787  UpArrowBar: '⤒',
35788  UpArrowDownArrow: '⇅',
35789  UpDownArrow: '↕',
35790  UpEquilibrium: '⥮',
35791  UpTee: '⊥',
35792  UpTeeArrow: '↥',
35793  Uparrow: '⇑',
35794  Updownarrow: '⇕',
35795  UpperLeftArrow: '↖',
35796  UpperRightArrow: '↗',
35797  Upsi: 'ϒ',
35798  Upsilon: 'Υ',
35799  Uring: 'Ů',
35800  Uscr: '��',
35801  Utilde: 'Ũ',
35802  Uum: 'Ü',
35803  Uuml: 'Ü',
35804  VDash: '⊫',
35805  Vbar: '⫫',
35806  Vcy: 'В',
35807  Vdash: '⊩',
35808  Vdashl: '⫦',
35809  Vee: '⋁',
35810  Verbar: '‖',
35811  Vert: '‖',
35812  VerticalBar: '∣',
35813  VerticalLine: '|',
35814  VerticalSeparator: '❘',
35815  VerticalTilde: '≀',
35816  VeryThinSpace: ' ',
35817  Vfr: '��',
35818  Vopf: '��',
35819  Vscr: '��',
35820  Vvdash: '⊪',
35821  Wcirc: 'Ŵ',
35822  Wedge: '⋀',
35823  Wfr: '��',
35824  Wopf: '��',
35825  Wscr: '��',
35826  Xfr: '��',
35827  Xi: 'Ξ',
35828  Xopf: '��',
35829  Xscr: '��',
35830  YAcy: 'Я',
35831  YIcy: 'Ї',
35832  YUcy: 'Ю',
35833  Yacut: 'Ý',
35834  Yacute: 'Ý',
35835  Ycirc: 'Ŷ',
35836  Ycy: 'Ы',
35837  Yfr: '��',
35838  Yopf: '��',
35839  Yscr: '��',
35840  Yuml: 'Ÿ',
35841  ZHcy: 'Ж',
35842  Zacute: 'Ź',
35843  Zcaron: 'Ž',
35844  Zcy: 'З',
35845  Zdot: 'Ż',
35846  ZeroWidthSpace: '​',
35847  Zeta: 'Ζ',
35848  Zfr: 'ℨ',
35849  Zopf: 'ℤ',
35850  Zscr: '��',
35851  aacut: 'á',
35852  aacute: 'á',
35853  abreve: 'ă',
35854  ac: '∾',
35855  acE: '∾̳',
35856  acd: '∿',
35857  acir: 'â',
35858  acirc: 'â',
35859  acut: '´',
35860  acute: '´',
35861  acy: 'а',
35862  aeli: 'æ',
35863  aelig: 'æ',
35864  af: '⁡',
35865  afr: '��',
35866  agrav: 'à',
35867  agrave: 'à',
35868  alefsym: 'ℵ',
35869  aleph: 'ℵ',
35870  alpha: 'α',
35871  amacr: 'ā',
35872  amalg: '⨿',
35873  am: '&',
35874  amp: '&',
35875  and: '∧',
35876  andand: '⩕',
35877  andd: '⩜',
35878  andslope: '⩘',
35879  andv: '⩚',
35880  ang: '∠',
35881  ange: '⦤',
35882  angle: '∠',
35883  angmsd: '∡',
35884  angmsdaa: '⦨',
35885  angmsdab: '⦩',
35886  angmsdac: '⦪',
35887  angmsdad: '⦫',
35888  angmsdae: '⦬',
35889  angmsdaf: '⦭',
35890  angmsdag: '⦮',
35891  angmsdah: '⦯',
35892  angrt: '∟',
35893  angrtvb: '⊾',
35894  angrtvbd: '⦝',
35895  angsph: '∢',
35896  angst: 'Å',
35897  angzarr: '⍼',
35898  aogon: 'ą',
35899  aopf: '��',
35900  ap: '≈',
35901  apE: '⩰',
35902  apacir: '⩯',
35903  ape: '≊',
35904  apid: '≋',
35905  apos: "'",
35906  approx: '≈',
35907  approxeq: '≊',
35908  arin: 'å',
35909  aring: 'å',
35910  ascr: '��',
35911  ast: '*',
35912  asymp: '≈',
35913  asympeq: '≍',
35914  atild: 'ã',
35915  atilde: 'ã',
35916  aum: 'ä',
35917  auml: 'ä',
35918  awconint: '∳',
35919  awint: '⨑',
35920  bNot: '⫭',
35921  backcong: '≌',
35922  backepsilon: '϶',
35923  backprime: '‵',
35924  backsim: '∽',
35925  backsimeq: '⋍',
35926  barvee: '⊽',
35927  barwed: '⌅',
35928  barwedge: '⌅',
35929  bbrk: '⎵',
35930  bbrktbrk: '⎶',
35931  bcong: '≌',
35932  bcy: 'б',
35933  bdquo: '„',
35934  becaus: '∵',
35935  because: '∵',
35936  bemptyv: '⦰',
35937  bepsi: '϶',
35938  bernou: 'ℬ',
35939  beta: 'β',
35940  beth: 'ℶ',
35941  between: '≬',
35942  bfr: '��',
35943  bigcap: '⋂',
35944  bigcirc: '◯',
35945  bigcup: '⋃',
35946  bigodot: '⨀',
35947  bigoplus: '⨁',
35948  bigotimes: '⨂',
35949  bigsqcup: '⨆',
35950  bigstar: '★',
35951  bigtriangledown: '▽',
35952  bigtriangleup: '△',
35953  biguplus: '⨄',
35954  bigvee: '⋁',
35955  bigwedge: '⋀',
35956  bkarow: '⤍',
35957  blacklozenge: '⧫',
35958  blacksquare: '▪',
35959  blacktriangle: '▴',
35960  blacktriangledown: '▾',
35961  blacktriangleleft: '◂',
35962  blacktriangleright: '▸',
35963  blank: '␣',
35964  blk12: '▒',
35965  blk14: '░',
35966  blk34: '▓',
35967  block: '█',
35968  bne: '=⃥',
35969  bnequiv: '≡⃥',
35970  bnot: '⌐',
35971  bopf: '��',
35972  bot: '⊥',
35973  bottom: '⊥',
35974  bowtie: '⋈',
35975  boxDL: '╗',
35976  boxDR: '╔',
35977  boxDl: '╖',
35978  boxDr: '╓',
35979  boxH: '═',
35980  boxHD: '╦',
35981  boxHU: '╩',
35982  boxHd: '╤',
35983  boxHu: '╧',
35984  boxUL: '╝',
35985  boxUR: '╚',
35986  boxUl: '╜',
35987  boxUr: '╙',
35988  boxV: '║',
35989  boxVH: '╬',
35990  boxVL: '╣',
35991  boxVR: '╠',
35992  boxVh: '╫',
35993  boxVl: '╢',
35994  boxVr: '╟',
35995  boxbox: '⧉',
35996  boxdL: '╕',
35997  boxdR: '╒',
35998  boxdl: '┐',
35999  boxdr: '┌',
36000  boxh: '─',
36001  boxhD: '╥',
36002  boxhU: '╨',
36003  boxhd: '┬',
36004  boxhu: '┴',
36005  boxminus: '⊟',
36006  boxplus: '⊞',
36007  boxtimes: '⊠',
36008  boxuL: '╛',
36009  boxuR: '╘',
36010  boxul: '┘',
36011  boxur: '└',
36012  boxv: '│',
36013  boxvH: '╪',
36014  boxvL: '╡',
36015  boxvR: '╞',
36016  boxvh: '┼',
36017  boxvl: '┤',
36018  boxvr: '├',
36019  bprime: '‵',
36020  breve: '˘',
36021  brvba: '¦',
36022  brvbar: '¦',
36023  bscr: '��',
36024  bsemi: '⁏',
36025  bsim: '∽',
36026  bsime: '⋍',
36027  bsol: '\\',
36028  bsolb: '⧅',
36029  bsolhsub: '⟈',
36030  bull: '•',
36031  bullet: '•',
36032  bump: '≎',
36033  bumpE: '⪮',
36034  bumpe: '≏',
36035  bumpeq: '≏',
36036  cacute: 'ć',
36037  cap: '∩',
36038  capand: '⩄',
36039  capbrcup: '⩉',
36040  capcap: '⩋',
36041  capcup: '⩇',
36042  capdot: '⩀',
36043  caps: '∩︀',
36044  caret: '⁁',
36045  caron: 'ˇ',
36046  ccaps: '⩍',
36047  ccaron: 'č',
36048  ccedi: 'ç',
36049  ccedil: 'ç',
36050  ccirc: 'ĉ',
36051  ccups: '⩌',
36052  ccupssm: '⩐',
36053  cdot: 'ċ',
36054  cedi: '¸',
36055  cedil: '¸',
36056  cemptyv: '⦲',
36057  cen: '¢',
36058  cent: '¢',
36059  centerdot: '·',
36060  cfr: '��',
36061  chcy: 'ч',
36062  check: '✓',
36063  checkmark: '✓',
36064  chi: 'χ',
36065  cir: '○',
36066  cirE: '⧃',
36067  circ: 'ˆ',
36068  circeq: '≗',
36069  circlearrowleft: '↺',
36070  circlearrowright: '↻',
36071  circledR: '®',
36072  circledS: 'Ⓢ',
36073  circledast: '⊛',
36074  circledcirc: '⊚',
36075  circleddash: '⊝',
36076  cire: '≗',
36077  cirfnint: '⨐',
36078  cirmid: '⫯',
36079  cirscir: '⧂',
36080  clubs: '♣',
36081  clubsuit: '♣',
36082  colon: ':',
36083  colone: '≔',
36084  coloneq: '≔',
36085  comma: ',',
36086  commat: '@',
36087  comp: '∁',
36088  compfn: '∘',
36089  complement: '∁',
36090  complexes: 'ℂ',
36091  cong: '≅',
36092  congdot: '⩭',
36093  conint: '∮',
36094  copf: '��',
36095  coprod: '∐',
36096  cop: '©',
36097  copy: '©',
36098  copysr: '℗',
36099  crarr: '↵',
36100  cross: '✗',
36101  cscr: '��',
36102  csub: '⫏',
36103  csube: '⫑',
36104  csup: '⫐',
36105  csupe: '⫒',
36106  ctdot: '⋯',
36107  cudarrl: '⤸',
36108  cudarrr: '⤵',
36109  cuepr: '⋞',
36110  cuesc: '⋟',
36111  cularr: '↶',
36112  cularrp: '⤽',
36113  cup: '∪',
36114  cupbrcap: '⩈',
36115  cupcap: '⩆',
36116  cupcup: '⩊',
36117  cupdot: '⊍',
36118  cupor: '⩅',
36119  cups: '∪︀',
36120  curarr: '↷',
36121  curarrm: '⤼',
36122  curlyeqprec: '⋞',
36123  curlyeqsucc: '⋟',
36124  curlyvee: '⋎',
36125  curlywedge: '⋏',
36126  curre: '¤',
36127  curren: '¤',
36128  curvearrowleft: '↶',
36129  curvearrowright: '↷',
36130  cuvee: '⋎',
36131  cuwed: '⋏',
36132  cwconint: '∲',
36133  cwint: '∱',
36134  cylcty: '⌭',
36135  dArr: '⇓',
36136  dHar: '⥥',
36137  dagger: '†',
36138  daleth: 'ℸ',
36139  darr: '↓',
36140  dash: '‐',
36141  dashv: '⊣',
36142  dbkarow: '⤏',
36143  dblac: '˝',
36144  dcaron: 'ď',
36145  dcy: 'д',
36146  dd: 'ⅆ',
36147  ddagger: '‡',
36148  ddarr: '⇊',
36149  ddotseq: '⩷',
36150  de: '°',
36151  deg: '°',
36152  delta: 'δ',
36153  demptyv: '⦱',
36154  dfisht: '⥿',
36155  dfr: '��',
36156  dharl: '⇃',
36157  dharr: '⇂',
36158  diam: '⋄',
36159  diamond: '⋄',
36160  diamondsuit: '♦',
36161  diams: '♦',
36162  die: '¨',
36163  digamma: 'ϝ',
36164  disin: '⋲',
36165  div: '÷',
36166  divid: '÷',
36167  divide: '÷',
36168  divideontimes: '⋇',
36169  divonx: '⋇',
36170  djcy: 'ђ',
36171  dlcorn: '⌞',
36172  dlcrop: '⌍',
36173  dollar: '$',
36174  dopf: '��',
36175  dot: '˙',
36176  doteq: '≐',
36177  doteqdot: '≑',
36178  dotminus: '∸',
36179  dotplus: '∔',
36180  dotsquare: '⊡',
36181  doublebarwedge: '⌆',
36182  downarrow: '↓',
36183  downdownarrows: '⇊',
36184  downharpoonleft: '⇃',
36185  downharpoonright: '⇂',
36186  drbkarow: '⤐',
36187  drcorn: '⌟',
36188  drcrop: '⌌',
36189  dscr: '��',
36190  dscy: 'ѕ',
36191  dsol: '⧶',
36192  dstrok: 'đ',
36193  dtdot: '⋱',
36194  dtri: '▿',
36195  dtrif: '▾',
36196  duarr: '⇵',
36197  duhar: '⥯',
36198  dwangle: '⦦',
36199  dzcy: 'џ',
36200  dzigrarr: '⟿',
36201  eDDot: '⩷',
36202  eDot: '≑',
36203  eacut: 'é',
36204  eacute: 'é',
36205  easter: '⩮',
36206  ecaron: 'ě',
36207  ecir: 'ê',
36208  ecirc: 'ê',
36209  ecolon: '≕',
36210  ecy: 'э',
36211  edot: 'ė',
36212  ee: 'ⅇ',
36213  efDot: '≒',
36214  efr: '��',
36215  eg: '⪚',
36216  egrav: 'è',
36217  egrave: 'è',
36218  egs: '⪖',
36219  egsdot: '⪘',
36220  el: '⪙',
36221  elinters: '⏧',
36222  ell: 'ℓ',
36223  els: '⪕',
36224  elsdot: '⪗',
36225  emacr: 'ē',
36226  empty: '∅',
36227  emptyset: '∅',
36228  emptyv: '∅',
36229  emsp13: ' ',
36230  emsp14: ' ',
36231  emsp: ' ',
36232  eng: 'ŋ',
36233  ensp: ' ',
36234  eogon: 'ę',
36235  eopf: '��',
36236  epar: '⋕',
36237  eparsl: '⧣',
36238  eplus: '⩱',
36239  epsi: 'ε',
36240  epsilon: 'ε',
36241  epsiv: 'ϵ',
36242  eqcirc: '≖',
36243  eqcolon: '≕',
36244  eqsim: '≂',
36245  eqslantgtr: '⪖',
36246  eqslantless: '⪕',
36247  equals: '=',
36248  equest: '≟',
36249  equiv: '≡',
36250  equivDD: '⩸',
36251  eqvparsl: '⧥',
36252  erDot: '≓',
36253  erarr: '⥱',
36254  escr: 'ℯ',
36255  esdot: '≐',
36256  esim: '≂',
36257  eta: 'η',
36258  et: 'ð',
36259  eth: 'ð',
36260  eum: 'ë',
36261  euml: 'ë',
36262  euro: '€',
36263  excl: '!',
36264  exist: '∃',
36265  expectation: 'ℰ',
36266  exponentiale: 'ⅇ',
36267  fallingdotseq: '≒',
36268  fcy: 'ф',
36269  female: '♀',
36270  ffilig: 'ffi',
36271  fflig: 'ff',
36272  ffllig: 'ffl',
36273  ffr: '��',
36274  filig: 'fi',
36275  fjlig: 'fj',
36276  flat: '♭',
36277  fllig: 'fl',
36278  fltns: '▱',
36279  fnof: 'ƒ',
36280  fopf: '��',
36281  forall: '∀',
36282  fork: '⋔',
36283  forkv: '⫙',
36284  fpartint: '⨍',
36285  frac1: '¼',
36286  frac12: '½',
36287  frac13: '⅓',
36288  frac14: '¼',
36289  frac15: '⅕',
36290  frac16: '⅙',
36291  frac18: '⅛',
36292  frac23: '⅔',
36293  frac25: '⅖',
36294  frac3: '¾',
36295  frac34: '¾',
36296  frac35: '⅗',
36297  frac38: '⅜',
36298  frac45: '⅘',
36299  frac56: '⅚',
36300  frac58: '⅝',
36301  frac78: '⅞',
36302  frasl: '⁄',
36303  frown: '⌢',
36304  fscr: '��',
36305  gE: '≧',
36306  gEl: '⪌',
36307  gacute: 'ǵ',
36308  gamma: 'γ',
36309  gammad: 'ϝ',
36310  gap: '⪆',
36311  gbreve: 'ğ',
36312  gcirc: 'ĝ',
36313  gcy: 'г',
36314  gdot: 'ġ',
36315  ge: '≥',
36316  gel: '⋛',
36317  geq: '≥',
36318  geqq: '≧',
36319  geqslant: '⩾',
36320  ges: '⩾',
36321  gescc: '⪩',
36322  gesdot: '⪀',
36323  gesdoto: '⪂',
36324  gesdotol: '⪄',
36325  gesl: '⋛︀',
36326  gesles: '⪔',
36327  gfr: '��',
36328  gg: '≫',
36329  ggg: '⋙',
36330  gimel: 'ℷ',
36331  gjcy: 'ѓ',
36332  gl: '≷',
36333  glE: '⪒',
36334  gla: '⪥',
36335  glj: '⪤',
36336  gnE: '≩',
36337  gnap: '⪊',
36338  gnapprox: '⪊',
36339  gne: '⪈',
36340  gneq: '⪈',
36341  gneqq: '≩',
36342  gnsim: '⋧',
36343  gopf: '��',
36344  grave: '`',
36345  gscr: 'ℊ',
36346  gsim: '≳',
36347  gsime: '⪎',
36348  gsiml: '⪐',
36349  g: '>',
36350  gt: '>',
36351  gtcc: '⪧',
36352  gtcir: '⩺',
36353  gtdot: '⋗',
36354  gtlPar: '⦕',
36355  gtquest: '⩼',
36356  gtrapprox: '⪆',
36357  gtrarr: '⥸',
36358  gtrdot: '⋗',
36359  gtreqless: '⋛',
36360  gtreqqless: '⪌',
36361  gtrless: '≷',
36362  gtrsim: '≳',
36363  gvertneqq: '≩︀',
36364  gvnE: '≩︀',
36365  hArr: '⇔',
36366  hairsp: ' ',
36367  half: '½',
36368  hamilt: 'ℋ',
36369  hardcy: 'ъ',
36370  harr: '↔',
36371  harrcir: '⥈',
36372  harrw: '↭',
36373  hbar: 'ℏ',
36374  hcirc: 'ĥ',
36375  hearts: '♥',
36376  heartsuit: '♥',
36377  hellip: '…',
36378  hercon: '⊹',
36379  hfr: '��',
36380  hksearow: '⤥',
36381  hkswarow: '⤦',
36382  hoarr: '⇿',
36383  homtht: '∻',
36384  hookleftarrow: '↩',
36385  hookrightarrow: '↪',
36386  hopf: '��',
36387  horbar: '―',
36388  hscr: '��',
36389  hslash: 'ℏ',
36390  hstrok: 'ħ',
36391  hybull: '⁃',
36392  hyphen: '‐',
36393  iacut: 'í',
36394  iacute: 'í',
36395  ic: '⁣',
36396  icir: 'î',
36397  icirc: 'î',
36398  icy: 'и',
36399  iecy: 'е',
36400  iexc: '¡',
36401  iexcl: '¡',
36402  iff: '⇔',
36403  ifr: '��',
36404  igrav: 'ì',
36405  igrave: 'ì',
36406  ii: 'ⅈ',
36407  iiiint: '⨌',
36408  iiint: '∭',
36409  iinfin: '⧜',
36410  iiota: '℩',
36411  ijlig: 'ij',
36412  imacr: 'ī',
36413  image: 'ℑ',
36414  imagline: 'ℐ',
36415  imagpart: 'ℑ',
36416  imath: 'ı',
36417  imof: '⊷',
36418  imped: 'Ƶ',
36419  in: '∈',
36420  incare: '℅',
36421  infin: '∞',
36422  infintie: '⧝',
36423  inodot: 'ı',
36424  int: '∫',
36425  intcal: '⊺',
36426  integers: 'ℤ',
36427  intercal: '⊺',
36428  intlarhk: '⨗',
36429  intprod: '⨼',
36430  iocy: 'ё',
36431  iogon: 'į',
36432  iopf: '��',
36433  iota: 'ι',
36434  iprod: '⨼',
36435  iques: '¿',
36436  iquest: '¿',
36437  iscr: '��',
36438  isin: '∈',
36439  isinE: '⋹',
36440  isindot: '⋵',
36441  isins: '⋴',
36442  isinsv: '⋳',
36443  isinv: '∈',
36444  it: '⁢',
36445  itilde: 'ĩ',
36446  iukcy: 'і',
36447  ium: 'ï',
36448  iuml: 'ï',
36449  jcirc: 'ĵ',
36450  jcy: 'й',
36451  jfr: '��',
36452  jmath: 'ȷ',
36453  jopf: '��',
36454  jscr: '��',
36455  jsercy: 'ј',
36456  jukcy: 'є',
36457  kappa: 'κ',
36458  kappav: 'ϰ',
36459  kcedil: 'ķ',
36460  kcy: 'к',
36461  kfr: '��',
36462  kgreen: 'ĸ',
36463  khcy: 'х',
36464  kjcy: 'ќ',
36465  kopf: '��',
36466  kscr: '��',
36467  lAarr: '⇚',
36468  lArr: '⇐',
36469  lAtail: '⤛',
36470  lBarr: '⤎',
36471  lE: '≦',
36472  lEg: '⪋',
36473  lHar: '⥢',
36474  lacute: 'ĺ',
36475  laemptyv: '⦴',
36476  lagran: 'ℒ',
36477  lambda: 'λ',
36478  lang: '⟨',
36479  langd: '⦑',
36480  langle: '⟨',
36481  lap: '⪅',
36482  laqu: '«',
36483  laquo: '«',
36484  larr: '←',
36485  larrb: '⇤',
36486  larrbfs: '⤟',
36487  larrfs: '⤝',
36488  larrhk: '↩',
36489  larrlp: '↫',
36490  larrpl: '⤹',
36491  larrsim: '⥳',
36492  larrtl: '↢',
36493  lat: '⪫',
36494  latail: '⤙',
36495  late: '⪭',
36496  lates: '⪭︀',
36497  lbarr: '⤌',
36498  lbbrk: '❲',
36499  lbrace: '{',
36500  lbrack: '[',
36501  lbrke: '⦋',
36502  lbrksld: '⦏',
36503  lbrkslu: '⦍',
36504  lcaron: 'ľ',
36505  lcedil: 'ļ',
36506  lceil: '⌈',
36507  lcub: '{',
36508  lcy: 'л',
36509  ldca: '⤶',
36510  ldquo: '“',
36511  ldquor: '„',
36512  ldrdhar: '⥧',
36513  ldrushar: '⥋',
36514  ldsh: '↲',
36515  le: '≤',
36516  leftarrow: '←',
36517  leftarrowtail: '↢',
36518  leftharpoondown: '↽',
36519  leftharpoonup: '↼',
36520  leftleftarrows: '⇇',
36521  leftrightarrow: '↔',
36522  leftrightarrows: '⇆',
36523  leftrightharpoons: '⇋',
36524  leftrightsquigarrow: '↭',
36525  leftthreetimes: '⋋',
36526  leg: '⋚',
36527  leq: '≤',
36528  leqq: '≦',
36529  leqslant: '⩽',
36530  les: '⩽',
36531  lescc: '⪨',
36532  lesdot: '⩿',
36533  lesdoto: '⪁',
36534  lesdotor: '⪃',
36535  lesg: '⋚︀',
36536  lesges: '⪓',
36537  lessapprox: '⪅',
36538  lessdot: '⋖',
36539  lesseqgtr: '⋚',
36540  lesseqqgtr: '⪋',
36541  lessgtr: '≶',
36542  lesssim: '≲',
36543  lfisht: '⥼',
36544  lfloor: '⌊',
36545  lfr: '��',
36546  lg: '≶',
36547  lgE: '⪑',
36548  lhard: '↽',
36549  lharu: '↼',
36550  lharul: '⥪',
36551  lhblk: '▄',
36552  ljcy: 'љ',
36553  ll: '≪',
36554  llarr: '⇇',
36555  llcorner: '⌞',
36556  llhard: '⥫',
36557  lltri: '◺',
36558  lmidot: 'ŀ',
36559  lmoust: '⎰',
36560  lmoustache: '⎰',
36561  lnE: '≨',
36562  lnap: '⪉',
36563  lnapprox: '⪉',
36564  lne: '⪇',
36565  lneq: '⪇',
36566  lneqq: '≨',
36567  lnsim: '⋦',
36568  loang: '⟬',
36569  loarr: '⇽',
36570  lobrk: '⟦',
36571  longleftarrow: '⟵',
36572  longleftrightarrow: '⟷',
36573  longmapsto: '⟼',
36574  longrightarrow: '⟶',
36575  looparrowleft: '↫',
36576  looparrowright: '↬',
36577  lopar: '⦅',
36578  lopf: '��',
36579  loplus: '⨭',
36580  lotimes: '⨴',
36581  lowast: '∗',
36582  lowbar: '_',
36583  loz: '◊',
36584  lozenge: '◊',
36585  lozf: '⧫',
36586  lpar: '(',
36587  lparlt: '⦓',
36588  lrarr: '⇆',
36589  lrcorner: '⌟',
36590  lrhar: '⇋',
36591  lrhard: '⥭',
36592  lrm: '‎',
36593  lrtri: '⊿',
36594  lsaquo: '‹',
36595  lscr: '��',
36596  lsh: '↰',
36597  lsim: '≲',
36598  lsime: '⪍',
36599  lsimg: '⪏',
36600  lsqb: '[',
36601  lsquo: '‘',
36602  lsquor: '‚',
36603  lstrok: 'ł',
36604  l: '<',
36605  lt: '<',
36606  ltcc: '⪦',
36607  ltcir: '⩹',
36608  ltdot: '⋖',
36609  lthree: '⋋',
36610  ltimes: '⋉',
36611  ltlarr: '⥶',
36612  ltquest: '⩻',
36613  ltrPar: '⦖',
36614  ltri: '◃',
36615  ltrie: '⊴',
36616  ltrif: '◂',
36617  lurdshar: '⥊',
36618  luruhar: '⥦',
36619  lvertneqq: '≨︀',
36620  lvnE: '≨︀',
36621  mDDot: '∺',
36622  mac: '¯',
36623  macr: '¯',
36624  male: '♂',
36625  malt: '✠',
36626  maltese: '✠',
36627  map: '↦',
36628  mapsto: '↦',
36629  mapstodown: '↧',
36630  mapstoleft: '↤',
36631  mapstoup: '↥',
36632  marker: '▮',
36633  mcomma: '⨩',
36634  mcy: 'м',
36635  mdash: '—',
36636  measuredangle: '∡',
36637  mfr: '��',
36638  mho: '℧',
36639  micr: 'µ',
36640  micro: 'µ',
36641  mid: '∣',
36642  midast: '*',
36643  midcir: '⫰',
36644  middo: '·',
36645  middot: '·',
36646  minus: '−',
36647  minusb: '⊟',
36648  minusd: '∸',
36649  minusdu: '⨪',
36650  mlcp: '⫛',
36651  mldr: '…',
36652  mnplus: '∓',
36653  models: '⊧',
36654  mopf: '��',
36655  mp: '∓',
36656  mscr: '��',
36657  mstpos: '∾',
36658  mu: 'μ',
36659  multimap: '⊸',
36660  mumap: '⊸',
36661  nGg: '⋙̸',
36662  nGt: '≫⃒',
36663  nGtv: '≫̸',
36664  nLeftarrow: '⇍',
36665  nLeftrightarrow: '⇎',
36666  nLl: '⋘̸',
36667  nLt: '≪⃒',
36668  nLtv: '≪̸',
36669  nRightarrow: '⇏',
36670  nVDash: '⊯',
36671  nVdash: '⊮',
36672  nabla: '∇',
36673  nacute: 'ń',
36674  nang: '∠⃒',
36675  nap: '≉',
36676  napE: '⩰̸',
36677  napid: '≋̸',
36678  napos: 'ʼn',
36679  napprox: '≉',
36680  natur: '♮',
36681  natural: '♮',
36682  naturals: 'ℕ',
36683  nbs: ' ',
36684  nbsp: ' ',
36685  nbump: '≎̸',
36686  nbumpe: '≏̸',
36687  ncap: '⩃',
36688  ncaron: 'ň',
36689  ncedil: 'ņ',
36690  ncong: '≇',
36691  ncongdot: '⩭̸',
36692  ncup: '⩂',
36693  ncy: 'н',
36694  ndash: '–',
36695  ne: '≠',
36696  neArr: '⇗',
36697  nearhk: '⤤',
36698  nearr: '↗',
36699  nearrow: '↗',
36700  nedot: '≐̸',
36701  nequiv: '≢',
36702  nesear: '⤨',
36703  nesim: '≂̸',
36704  nexist: '∄',
36705  nexists: '∄',
36706  nfr: '��',
36707  ngE: '≧̸',
36708  nge: '≱',
36709  ngeq: '≱',
36710  ngeqq: '≧̸',
36711  ngeqslant: '⩾̸',
36712  nges: '⩾̸',
36713  ngsim: '≵',
36714  ngt: '≯',
36715  ngtr: '≯',
36716  nhArr: '⇎',
36717  nharr: '↮',
36718  nhpar: '⫲',
36719  ni: '∋',
36720  nis: '⋼',
36721  nisd: '⋺',
36722  niv: '∋',
36723  njcy: 'њ',
36724  nlArr: '⇍',
36725  nlE: '≦̸',
36726  nlarr: '↚',
36727  nldr: '‥',
36728  nle: '≰',
36729  nleftarrow: '↚',
36730  nleftrightarrow: '↮',
36731  nleq: '≰',
36732  nleqq: '≦̸',
36733  nleqslant: '⩽̸',
36734  nles: '⩽̸',
36735  nless: '≮',
36736  nlsim: '≴',
36737  nlt: '≮',
36738  nltri: '⋪',
36739  nltrie: '⋬',
36740  nmid: '∤',
36741  nopf: '��',
36742  no: '¬',
36743  not: '¬',
36744  notin: '∉',
36745  notinE: '⋹̸',
36746  notindot: '⋵̸',
36747  notinva: '∉',
36748  notinvb: '⋷',
36749  notinvc: '⋶',
36750  notni: '∌',
36751  notniva: '∌',
36752  notnivb: '⋾',
36753  notnivc: '⋽',
36754  npar: '∦',
36755  nparallel: '∦',
36756  nparsl: '⫽⃥',
36757  npart: '∂̸',
36758  npolint: '⨔',
36759  npr: '⊀',
36760  nprcue: '⋠',
36761  npre: '⪯̸',
36762  nprec: '⊀',
36763  npreceq: '⪯̸',
36764  nrArr: '⇏',
36765  nrarr: '↛',
36766  nrarrc: '⤳̸',
36767  nrarrw: '↝̸',
36768  nrightarrow: '↛',
36769  nrtri: '⋫',
36770  nrtrie: '⋭',
36771  nsc: '⊁',
36772  nsccue: '⋡',
36773  nsce: '⪰̸',
36774  nscr: '��',
36775  nshortmid: '∤',
36776  nshortparallel: '∦',
36777  nsim: '≁',
36778  nsime: '≄',
36779  nsimeq: '≄',
36780  nsmid: '∤',
36781  nspar: '∦',
36782  nsqsube: '⋢',
36783  nsqsupe: '⋣',
36784  nsub: '⊄',
36785  nsubE: '⫅̸',
36786  nsube: '⊈',
36787  nsubset: '⊂⃒',
36788  nsubseteq: '⊈',
36789  nsubseteqq: '⫅̸',
36790  nsucc: '⊁',
36791  nsucceq: '⪰̸',
36792  nsup: '⊅',
36793  nsupE: '⫆̸',
36794  nsupe: '⊉',
36795  nsupset: '⊃⃒',
36796  nsupseteq: '⊉',
36797  nsupseteqq: '⫆̸',
36798  ntgl: '≹',
36799  ntild: 'ñ',
36800  ntilde: 'ñ',
36801  ntlg: '≸',
36802  ntriangleleft: '⋪',
36803  ntrianglelefteq: '⋬',
36804  ntriangleright: '⋫',
36805  ntrianglerighteq: '⋭',
36806  nu: 'ν',
36807  num: '#',
36808  numero: '№',
36809  numsp: ' ',
36810  nvDash: '⊭',
36811  nvHarr: '⤄',
36812  nvap: '≍⃒',
36813  nvdash: '⊬',
36814  nvge: '≥⃒',
36815  nvgt: '>⃒',
36816  nvinfin: '⧞',
36817  nvlArr: '⤂',
36818  nvle: '≤⃒',
36819  nvlt: '<⃒',
36820  nvltrie: '⊴⃒',
36821  nvrArr: '⤃',
36822  nvrtrie: '⊵⃒',
36823  nvsim: '∼⃒',
36824  nwArr: '⇖',
36825  nwarhk: '⤣',
36826  nwarr: '↖',
36827  nwarrow: '↖',
36828  nwnear: '⤧',
36829  oS: 'Ⓢ',
36830  oacut: 'ó',
36831  oacute: 'ó',
36832  oast: '⊛',
36833  ocir: 'ô',
36834  ocirc: 'ô',
36835  ocy: 'о',
36836  odash: '⊝',
36837  odblac: 'ő',
36838  odiv: '⨸',
36839  odot: '⊙',
36840  odsold: '⦼',
36841  oelig: 'œ',
36842  ofcir: '⦿',
36843  ofr: '��',
36844  ogon: '˛',
36845  ograv: 'ò',
36846  ograve: 'ò',
36847  ogt: '⧁',
36848  ohbar: '⦵',
36849  ohm: 'Ω',
36850  oint: '∮',
36851  olarr: '↺',
36852  olcir: '⦾',
36853  olcross: '⦻',
36854  oline: '‾',
36855  olt: '⧀',
36856  omacr: 'ō',
36857  omega: 'ω',
36858  omicron: 'ο',
36859  omid: '⦶',
36860  ominus: '⊖',
36861  oopf: '��',
36862  opar: '⦷',
36863  operp: '⦹',
36864  oplus: '⊕',
36865  or: '∨',
36866  orarr: '↻',
36867  ord: 'º',
36868  order: 'ℴ',
36869  orderof: 'ℴ',
36870  ordf: 'ª',
36871  ordm: 'º',
36872  origof: '⊶',
36873  oror: '⩖',
36874  orslope: '⩗',
36875  orv: '⩛',
36876  oscr: 'ℴ',
36877  oslas: 'ø',
36878  oslash: 'ø',
36879  osol: '⊘',
36880  otild: 'õ',
36881  otilde: 'õ',
36882  otimes: '⊗',
36883  otimesas: '⨶',
36884  oum: 'ö',
36885  ouml: 'ö',
36886  ovbar: '⌽',
36887  par: '¶',
36888  para: '¶',
36889  parallel: '∥',
36890  parsim: '⫳',
36891  parsl: '⫽',
36892  part: '∂',
36893  pcy: 'п',
36894  percnt: '%',
36895  period: '.',
36896  permil: '‰',
36897  perp: '⊥',
36898  pertenk: '‱',
36899  pfr: '��',
36900  phi: 'φ',
36901  phiv: 'ϕ',
36902  phmmat: 'ℳ',
36903  phone: '☎',
36904  pi: 'π',
36905  pitchfork: '⋔',
36906  piv: 'ϖ',
36907  planck: 'ℏ',
36908  planckh: 'ℎ',
36909  plankv: 'ℏ',
36910  plus: '+',
36911  plusacir: '⨣',
36912  plusb: '⊞',
36913  pluscir: '⨢',
36914  plusdo: '∔',
36915  plusdu: '⨥',
36916  pluse: '⩲',
36917  plusm: '±',
36918  plusmn: '±',
36919  plussim: '⨦',
36920  plustwo: '⨧',
36921  pm: '±',
36922  pointint: '⨕',
36923  popf: '��',
36924  poun: '£',
36925  pound: '£',
36926  pr: '≺',
36927  prE: '⪳',
36928  prap: '⪷',
36929  prcue: '≼',
36930  pre: '⪯',
36931  prec: '≺',
36932  precapprox: '⪷',
36933  preccurlyeq: '≼',
36934  preceq: '⪯',
36935  precnapprox: '⪹',
36936  precneqq: '⪵',
36937  precnsim: '⋨',
36938  precsim: '≾',
36939  prime: '′',
36940  primes: 'ℙ',
36941  prnE: '⪵',
36942  prnap: '⪹',
36943  prnsim: '⋨',
36944  prod: '∏',
36945  profalar: '⌮',
36946  profline: '⌒',
36947  profsurf: '⌓',
36948  prop: '∝',
36949  propto: '∝',
36950  prsim: '≾',
36951  prurel: '⊰',
36952  pscr: '��',
36953  psi: 'ψ',
36954  puncsp: ' ',
36955  qfr: '��',
36956  qint: '⨌',
36957  qopf: '��',
36958  qprime: '⁗',
36959  qscr: '��',
36960  quaternions: 'ℍ',
36961  quatint: '⨖',
36962  quest: '?',
36963  questeq: '≟',
36964  quo: '"',
36965  quot: '"',
36966  rAarr: '⇛',
36967  rArr: '⇒',
36968  rAtail: '⤜',
36969  rBarr: '⤏',
36970  rHar: '⥤',
36971  race: '∽̱',
36972  racute: 'ŕ',
36973  radic: '√',
36974  raemptyv: '⦳',
36975  rang: '⟩',
36976  rangd: '⦒',
36977  range: '⦥',
36978  rangle: '⟩',
36979  raqu: '»',
36980  raquo: '»',
36981  rarr: '→',
36982  rarrap: '⥵',
36983  rarrb: '⇥',
36984  rarrbfs: '⤠',
36985  rarrc: '⤳',
36986  rarrfs: '⤞',
36987  rarrhk: '↪',
36988  rarrlp: '↬',
36989  rarrpl: '⥅',
36990  rarrsim: '⥴',
36991  rarrtl: '↣',
36992  rarrw: '↝',
36993  ratail: '⤚',
36994  ratio: '∶',
36995  rationals: 'ℚ',
36996  rbarr: '⤍',
36997  rbbrk: '❳',
36998  rbrace: '}',
36999  rbrack: ']',
37000  rbrke: '⦌',
37001  rbrksld: '⦎',
37002  rbrkslu: '⦐',
37003  rcaron: 'ř',
37004  rcedil: 'ŗ',
37005  rceil: '⌉',
37006  rcub: '}',
37007  rcy: 'р',
37008  rdca: '⤷',
37009  rdldhar: '⥩',
37010  rdquo: '”',
37011  rdquor: '”',
37012  rdsh: '↳',
37013  real: 'ℜ',
37014  realine: 'ℛ',
37015  realpart: 'ℜ',
37016  reals: 'ℝ',
37017  rect: '▭',
37018  re: '®',
37019  reg: '®',
37020  rfisht: '⥽',
37021  rfloor: '⌋',
37022  rfr: '��',
37023  rhard: '⇁',
37024  rharu: '⇀',
37025  rharul: '⥬',
37026  rho: 'ρ',
37027  rhov: 'ϱ',
37028  rightarrow: '→',
37029  rightarrowtail: '↣',
37030  rightharpoondown: '⇁',
37031  rightharpoonup: '⇀',
37032  rightleftarrows: '⇄',
37033  rightleftharpoons: '⇌',
37034  rightrightarrows: '⇉',
37035  rightsquigarrow: '↝',
37036  rightthreetimes: '⋌',
37037  ring: '˚',
37038  risingdotseq: '≓',
37039  rlarr: '⇄',
37040  rlhar: '⇌',
37041  rlm: '‏',
37042  rmoust: '⎱',
37043  rmoustache: '⎱',
37044  rnmid: '⫮',
37045  roang: '⟭',
37046  roarr: '⇾',
37047  robrk: '⟧',
37048  ropar: '⦆',
37049  ropf: '��',
37050  roplus: '⨮',
37051  rotimes: '⨵',
37052  rpar: ')',
37053  rpargt: '⦔',
37054  rppolint: '⨒',
37055  rrarr: '⇉',
37056  rsaquo: '›',
37057  rscr: '��',
37058  rsh: '↱',
37059  rsqb: ']',
37060  rsquo: '’',
37061  rsquor: '’',
37062  rthree: '⋌',
37063  rtimes: '⋊',
37064  rtri: '▹',
37065  rtrie: '⊵',
37066  rtrif: '▸',
37067  rtriltri: '⧎',
37068  ruluhar: '⥨',
37069  rx: '℞',
37070  sacute: 'ś',
37071  sbquo: '‚',
37072  sc: '≻',
37073  scE: '⪴',
37074  scap: '⪸',
37075  scaron: 'š',
37076  sccue: '≽',
37077  sce: '⪰',
37078  scedil: 'ş',
37079  scirc: 'ŝ',
37080  scnE: '⪶',
37081  scnap: '⪺',
37082  scnsim: '⋩',
37083  scpolint: '⨓',
37084  scsim: '≿',
37085  scy: 'с',
37086  sdot: '⋅',
37087  sdotb: '⊡',
37088  sdote: '⩦',
37089  seArr: '⇘',
37090  searhk: '⤥',
37091  searr: '↘',
37092  searrow: '↘',
37093  sec: '§',
37094  sect: '§',
37095  semi: ';',
37096  seswar: '⤩',
37097  setminus: '∖',
37098  setmn: '∖',
37099  sext: '✶',
37100  sfr: '��',
37101  sfrown: '⌢',
37102  sharp: '♯',
37103  shchcy: 'щ',
37104  shcy: 'ш',
37105  shortmid: '∣',
37106  shortparallel: '∥',
37107  sh: '­',
37108  shy: '­',
37109  sigma: 'σ',
37110  sigmaf: 'ς',
37111  sigmav: 'ς',
37112  sim: '∼',
37113  simdot: '⩪',
37114  sime: '≃',
37115  simeq: '≃',
37116  simg: '⪞',
37117  simgE: '⪠',
37118  siml: '⪝',
37119  simlE: '⪟',
37120  simne: '≆',
37121  simplus: '⨤',
37122  simrarr: '⥲',
37123  slarr: '←',
37124  smallsetminus: '∖',
37125  smashp: '⨳',
37126  smeparsl: '⧤',
37127  smid: '∣',
37128  smile: '⌣',
37129  smt: '⪪',
37130  smte: '⪬',
37131  smtes: '⪬︀',
37132  softcy: 'ь',
37133  sol: '/',
37134  solb: '⧄',
37135  solbar: '⌿',
37136  sopf: '��',
37137  spades: '♠',
37138  spadesuit: '♠',
37139  spar: '∥',
37140  sqcap: '⊓',
37141  sqcaps: '⊓︀',
37142  sqcup: '⊔',
37143  sqcups: '⊔︀',
37144  sqsub: '⊏',
37145  sqsube: '⊑',
37146  sqsubset: '⊏',
37147  sqsubseteq: '⊑',
37148  sqsup: '⊐',
37149  sqsupe: '⊒',
37150  sqsupset: '⊐',
37151  sqsupseteq: '⊒',
37152  squ: '□',
37153  square: '□',
37154  squarf: '▪',
37155  squf: '▪',
37156  srarr: '→',
37157  sscr: '��',
37158  ssetmn: '∖',
37159  ssmile: '⌣',
37160  sstarf: '⋆',
37161  star: '☆',
37162  starf: '★',
37163  straightepsilon: 'ϵ',
37164  straightphi: 'ϕ',
37165  strns: '¯',
37166  sub: '⊂',
37167  subE: '⫅',
37168  subdot: '⪽',
37169  sube: '⊆',
37170  subedot: '⫃',
37171  submult: '⫁',
37172  subnE: '⫋',
37173  subne: '⊊',
37174  subplus: '⪿',
37175  subrarr: '⥹',
37176  subset: '⊂',
37177  subseteq: '⊆',
37178  subseteqq: '⫅',
37179  subsetneq: '⊊',
37180  subsetneqq: '⫋',
37181  subsim: '⫇',
37182  subsub: '⫕',
37183  subsup: '⫓',
37184  succ: '≻',
37185  succapprox: '⪸',
37186  succcurlyeq: '≽',
37187  succeq: '⪰',
37188  succnapprox: '⪺',
37189  succneqq: '⪶',
37190  succnsim: '⋩',
37191  succsim: '≿',
37192  sum: '∑',
37193  sung: '♪',
37194  sup: '⊃',
37195  sup1: '¹',
37196  sup2: '²',
37197  sup3: '³',
37198  supE: '⫆',
37199  supdot: '⪾',
37200  supdsub: '⫘',
37201  supe: '⊇',
37202  supedot: '⫄',
37203  suphsol: '⟉',
37204  suphsub: '⫗',
37205  suplarr: '⥻',
37206  supmult: '⫂',
37207  supnE: '⫌',
37208  supne: '⊋',
37209  supplus: '⫀',
37210  supset: '⊃',
37211  supseteq: '⊇',
37212  supseteqq: '⫆',
37213  supsetneq: '⊋',
37214  supsetneqq: '⫌',
37215  supsim: '⫈',
37216  supsub: '⫔',
37217  supsup: '⫖',
37218  swArr: '⇙',
37219  swarhk: '⤦',
37220  swarr: '↙',
37221  swarrow: '↙',
37222  swnwar: '⤪',
37223  szli: 'ß',
37224  szlig: 'ß',
37225  target: '⌖',
37226  tau: 'τ',
37227  tbrk: '⎴',
37228  tcaron: 'ť',
37229  tcedil: 'ţ',
37230  tcy: 'т',
37231  tdot: '⃛',
37232  telrec: '⌕',
37233  tfr: '��',
37234  there4: '∴',
37235  therefore: '∴',
37236  theta: 'θ',
37237  thetasym: 'ϑ',
37238  thetav: 'ϑ',
37239  thickapprox: '≈',
37240  thicksim: '∼',
37241  thinsp: ' ',
37242  thkap: '≈',
37243  thksim: '∼',
37244  thor: 'þ',
37245  thorn: 'þ',
37246  tilde: '˜',
37247  time: '×',
37248  times: '×',
37249  timesb: '⊠',
37250  timesbar: '⨱',
37251  timesd: '⨰',
37252  tint: '∭',
37253  toea: '⤨',
37254  top: '⊤',
37255  topbot: '⌶',
37256  topcir: '⫱',
37257  topf: '��',
37258  topfork: '⫚',
37259  tosa: '⤩',
37260  tprime: '‴',
37261  trade: '™',
37262  triangle: '▵',
37263  triangledown: '▿',
37264  triangleleft: '◃',
37265  trianglelefteq: '⊴',
37266  triangleq: '≜',
37267  triangleright: '▹',
37268  trianglerighteq: '⊵',
37269  tridot: '◬',
37270  trie: '≜',
37271  triminus: '⨺',
37272  triplus: '⨹',
37273  trisb: '⧍',
37274  tritime: '⨻',
37275  trpezium: '⏢',
37276  tscr: '��',
37277  tscy: 'ц',
37278  tshcy: 'ћ',
37279  tstrok: 'ŧ',
37280  twixt: '≬',
37281  twoheadleftarrow: '↞',
37282  twoheadrightarrow: '↠',
37283  uArr: '⇑',
37284  uHar: '⥣',
37285  uacut: 'ú',
37286  uacute: 'ú',
37287  uarr: '↑',
37288  ubrcy: 'ў',
37289  ubreve: 'ŭ',
37290  ucir: 'û',
37291  ucirc: 'û',
37292  ucy: 'у',
37293  udarr: '⇅',
37294  udblac: 'ű',
37295  udhar: '⥮',
37296  ufisht: '⥾',
37297  ufr: '��',
37298  ugrav: 'ù',
37299  ugrave: 'ù',
37300  uharl: '↿',
37301  uharr: '↾',
37302  uhblk: '▀',
37303  ulcorn: '⌜',
37304  ulcorner: '⌜',
37305  ulcrop: '⌏',
37306  ultri: '◸',
37307  umacr: 'ū',
37308  um: '¨',
37309  uml: '¨',
37310  uogon: 'ų',
37311  uopf: '��',
37312  uparrow: '↑',
37313  updownarrow: '↕',
37314  upharpoonleft: '↿',
37315  upharpoonright: '↾',
37316  uplus: '⊎',
37317  upsi: 'υ',
37318  upsih: 'ϒ',
37319  upsilon: 'υ',
37320  upuparrows: '⇈',
37321  urcorn: '⌝',
37322  urcorner: '⌝',
37323  urcrop: '⌎',
37324  uring: 'ů',
37325  urtri: '◹',
37326  uscr: '��',
37327  utdot: '⋰',
37328  utilde: 'ũ',
37329  utri: '▵',
37330  utrif: '▴',
37331  uuarr: '⇈',
37332  uum: 'ü',
37333  uuml: 'ü',
37334  uwangle: '⦧',
37335  vArr: '⇕',
37336  vBar: '⫨',
37337  vBarv: '⫩',
37338  vDash: '⊨',
37339  vangrt: '⦜',
37340  varepsilon: 'ϵ',
37341  varkappa: 'ϰ',
37342  varnothing: '∅',
37343  varphi: 'ϕ',
37344  varpi: 'ϖ',
37345  varpropto: '∝',
37346  varr: '↕',
37347  varrho: 'ϱ',
37348  varsigma: 'ς',
37349  varsubsetneq: '⊊︀',
37350  varsubsetneqq: '⫋︀',
37351  varsupsetneq: '⊋︀',
37352  varsupsetneqq: '⫌︀',
37353  vartheta: 'ϑ',
37354  vartriangleleft: '⊲',
37355  vartriangleright: '⊳',
37356  vcy: 'в',
37357  vdash: '⊢',
37358  vee: '∨',
37359  veebar: '⊻',
37360  veeeq: '≚',
37361  vellip: '⋮',
37362  verbar: '|',
37363  vert: '|',
37364  vfr: '��',
37365  vltri: '⊲',
37366  vnsub: '⊂⃒',
37367  vnsup: '⊃⃒',
37368  vopf: '��',
37369  vprop: '∝',
37370  vrtri: '⊳',
37371  vscr: '��',
37372  vsubnE: '⫋︀',
37373  vsubne: '⊊︀',
37374  vsupnE: '⫌︀',
37375  vsupne: '⊋︀',
37376  vzigzag: '⦚',
37377  wcirc: 'ŵ',
37378  wedbar: '⩟',
37379  wedge: '∧',
37380  wedgeq: '≙',
37381  weierp: '℘',
37382  wfr: '��',
37383  wopf: '��',
37384  wp: '℘',
37385  wr: '≀',
37386  wreath: '≀',
37387  wscr: '��',
37388  xcap: '⋂',
37389  xcirc: '◯',
37390  xcup: '⋃',
37391  xdtri: '▽',
37392  xfr: '��',
37393  xhArr: '⟺',
37394  xharr: '⟷',
37395  xi: 'ξ',
37396  xlArr: '⟸',
37397  xlarr: '⟵',
37398  xmap: '⟼',
37399  xnis: '⋻',
37400  xodot: '⨀',
37401  xopf: '��',
37402  xoplus: '⨁',
37403  xotime: '⨂',
37404  xrArr: '⟹',
37405  xrarr: '⟶',
37406  xscr: '��',
37407  xsqcup: '⨆',
37408  xuplus: '⨄',
37409  xutri: '△',
37410  xvee: '⋁',
37411  xwedge: '⋀',
37412  yacut: 'ý',
37413  yacute: 'ý',
37414  yacy: 'я',
37415  ycirc: 'ŷ',
37416  ycy: 'ы',
37417  ye: '¥',
37418  yen: '¥',
37419  yfr: '��',
37420  yicy: 'ї',
37421  yopf: '��',
37422  yscr: '��',
37423  yucy: 'ю',
37424  yum: 'ÿ',
37425  yuml: 'ÿ',
37426  zacute: 'ź',
37427  zcaron: 'ž',
37428  zcy: 'з',
37429  zdot: 'ż',
37430  zeetrf: 'ℨ',
37431  zeta: 'ζ',
37432  zfr: '��',
37433  zhcy: 'ж',
37434  zigrarr: '⇝',
37435  zopf: '��',
37436  zscr: '��',
37437  zwj: '‍',
37438  zwnj: '‌'
37439};
37440
37441var own$5 = {}.hasOwnProperty;
37442
37443/**
37444 * @param {string} characters
37445 * @returns {string|false}
37446 */
37447function decodeEntity(characters) {
37448  return own$5.call(characterEntities, characters)
37449    ? characterEntities[characters]
37450    : false
37451}
37452
37453/**
37454 * @typedef {import('micromark-util-types').Construct} Construct
37455 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
37456 * @typedef {import('micromark-util-types').Token} Token
37457 * @typedef {import('micromark-util-types').State} State
37458 * @typedef {import('micromark-util-types').Code} Code
37459 */
37460
37461/** @type {Construct} */
37462const characterReference$1 = {
37463  name: 'characterReference',
37464  tokenize: tokenizeCharacterReference
37465};
37466/** @type {Tokenizer} */
37467
37468function tokenizeCharacterReference(effects, ok, nok) {
37469  const self = this;
37470  let size = 0;
37471  /** @type {number} */
37472
37473  let max;
37474  /** @type {(code: Code) => code is number} */
37475
37476  let test;
37477  return start
37478  /** @type {State} */
37479
37480  function start(code) {
37481    effects.enter('characterReference');
37482    effects.enter('characterReferenceMarker');
37483    effects.consume(code);
37484    effects.exit('characterReferenceMarker');
37485    return open
37486  }
37487  /** @type {State} */
37488
37489  function open(code) {
37490    if (code === 35) {
37491      effects.enter('characterReferenceMarkerNumeric');
37492      effects.consume(code);
37493      effects.exit('characterReferenceMarkerNumeric');
37494      return numeric
37495    }
37496
37497    effects.enter('characterReferenceValue');
37498    max = 31;
37499    test = asciiAlphanumeric;
37500    return value(code)
37501  }
37502  /** @type {State} */
37503
37504  function numeric(code) {
37505    if (code === 88 || code === 120) {
37506      effects.enter('characterReferenceMarkerHexadecimal');
37507      effects.consume(code);
37508      effects.exit('characterReferenceMarkerHexadecimal');
37509      effects.enter('characterReferenceValue');
37510      max = 6;
37511      test = asciiHexDigit;
37512      return value
37513    }
37514
37515    effects.enter('characterReferenceValue');
37516    max = 7;
37517    test = asciiDigit;
37518    return value(code)
37519  }
37520  /** @type {State} */
37521
37522  function value(code) {
37523    /** @type {Token} */
37524    let token;
37525
37526    if (code === 59 && size) {
37527      token = effects.exit('characterReferenceValue');
37528
37529      if (
37530        test === asciiAlphanumeric &&
37531        !decodeEntity(self.sliceSerialize(token))
37532      ) {
37533        return nok(code)
37534      }
37535
37536      effects.enter('characterReferenceMarker');
37537      effects.consume(code);
37538      effects.exit('characterReferenceMarker');
37539      effects.exit('characterReference');
37540      return ok
37541    }
37542
37543    if (test(code) && size++ < max) {
37544      effects.consume(code);
37545      return value
37546    }
37547
37548    return nok(code)
37549  }
37550}
37551
37552/**
37553 * @typedef {import('micromark-util-types').Construct} Construct
37554 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
37555 * @typedef {import('micromark-util-types').State} State
37556 * @typedef {import('micromark-util-types').Code} Code
37557 */
37558
37559/** @type {Construct} */
37560const codeFenced = {
37561  name: 'codeFenced',
37562  tokenize: tokenizeCodeFenced,
37563  concrete: true
37564};
37565/** @type {Tokenizer} */
37566
37567function tokenizeCodeFenced(effects, ok, nok) {
37568  const self = this;
37569  /** @type {Construct} */
37570
37571  const closingFenceConstruct = {
37572    tokenize: tokenizeClosingFence,
37573    partial: true
37574  };
37575  /** @type {Construct} */
37576
37577  const nonLazyLine = {
37578    tokenize: tokenizeNonLazyLine,
37579    partial: true
37580  };
37581  const tail = this.events[this.events.length - 1];
37582  const initialPrefix =
37583    tail && tail[1].type === 'linePrefix'
37584      ? tail[2].sliceSerialize(tail[1], true).length
37585      : 0;
37586  let sizeOpen = 0;
37587  /** @type {NonNullable<Code>} */
37588
37589  let marker;
37590  return start
37591  /** @type {State} */
37592
37593  function start(code) {
37594    effects.enter('codeFenced');
37595    effects.enter('codeFencedFence');
37596    effects.enter('codeFencedFenceSequence');
37597    marker = code;
37598    return sequenceOpen(code)
37599  }
37600  /** @type {State} */
37601
37602  function sequenceOpen(code) {
37603    if (code === marker) {
37604      effects.consume(code);
37605      sizeOpen++;
37606      return sequenceOpen
37607    }
37608
37609    effects.exit('codeFencedFenceSequence');
37610    return sizeOpen < 3
37611      ? nok(code)
37612      : factorySpace(effects, infoOpen, 'whitespace')(code)
37613  }
37614  /** @type {State} */
37615
37616  function infoOpen(code) {
37617    if (code === null || markdownLineEnding(code)) {
37618      return openAfter(code)
37619    }
37620
37621    effects.enter('codeFencedFenceInfo');
37622    effects.enter('chunkString', {
37623      contentType: 'string'
37624    });
37625    return info(code)
37626  }
37627  /** @type {State} */
37628
37629  function info(code) {
37630    if (code === null || markdownLineEndingOrSpace(code)) {
37631      effects.exit('chunkString');
37632      effects.exit('codeFencedFenceInfo');
37633      return factorySpace(effects, infoAfter, 'whitespace')(code)
37634    }
37635
37636    if (code === 96 && code === marker) return nok(code)
37637    effects.consume(code);
37638    return info
37639  }
37640  /** @type {State} */
37641
37642  function infoAfter(code) {
37643    if (code === null || markdownLineEnding(code)) {
37644      return openAfter(code)
37645    }
37646
37647    effects.enter('codeFencedFenceMeta');
37648    effects.enter('chunkString', {
37649      contentType: 'string'
37650    });
37651    return meta(code)
37652  }
37653  /** @type {State} */
37654
37655  function meta(code) {
37656    if (code === null || markdownLineEnding(code)) {
37657      effects.exit('chunkString');
37658      effects.exit('codeFencedFenceMeta');
37659      return openAfter(code)
37660    }
37661
37662    if (code === 96 && code === marker) return nok(code)
37663    effects.consume(code);
37664    return meta
37665  }
37666  /** @type {State} */
37667
37668  function openAfter(code) {
37669    effects.exit('codeFencedFence');
37670    return self.interrupt ? ok(code) : contentStart(code)
37671  }
37672  /** @type {State} */
37673
37674  function contentStart(code) {
37675    if (code === null) {
37676      return after(code)
37677    }
37678
37679    if (markdownLineEnding(code)) {
37680      return effects.attempt(
37681        nonLazyLine,
37682        effects.attempt(
37683          closingFenceConstruct,
37684          after,
37685          initialPrefix
37686            ? factorySpace(
37687                effects,
37688                contentStart,
37689                'linePrefix',
37690                initialPrefix + 1
37691              )
37692            : contentStart
37693        ),
37694        after
37695      )(code)
37696    }
37697
37698    effects.enter('codeFlowValue');
37699    return contentContinue(code)
37700  }
37701  /** @type {State} */
37702
37703  function contentContinue(code) {
37704    if (code === null || markdownLineEnding(code)) {
37705      effects.exit('codeFlowValue');
37706      return contentStart(code)
37707    }
37708
37709    effects.consume(code);
37710    return contentContinue
37711  }
37712  /** @type {State} */
37713
37714  function after(code) {
37715    effects.exit('codeFenced');
37716    return ok(code)
37717  }
37718  /** @type {Tokenizer} */
37719
37720  function tokenizeNonLazyLine(effects, ok, nok) {
37721    const self = this;
37722    return start
37723    /** @type {State} */
37724
37725    function start(code) {
37726      effects.enter('lineEnding');
37727      effects.consume(code);
37728      effects.exit('lineEnding');
37729      return lineStart
37730    }
37731    /** @type {State} */
37732
37733    function lineStart(code) {
37734      return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
37735    }
37736  }
37737  /** @type {Tokenizer} */
37738
37739  function tokenizeClosingFence(effects, ok, nok) {
37740    let size = 0;
37741    return factorySpace(
37742      effects,
37743      closingSequenceStart,
37744      'linePrefix',
37745      this.parser.constructs.disable.null.includes('codeIndented')
37746        ? undefined
37747        : 4
37748    )
37749    /** @type {State} */
37750
37751    function closingSequenceStart(code) {
37752      effects.enter('codeFencedFence');
37753      effects.enter('codeFencedFenceSequence');
37754      return closingSequence(code)
37755    }
37756    /** @type {State} */
37757
37758    function closingSequence(code) {
37759      if (code === marker) {
37760        effects.consume(code);
37761        size++;
37762        return closingSequence
37763      }
37764
37765      if (size < sizeOpen) return nok(code)
37766      effects.exit('codeFencedFenceSequence');
37767      return factorySpace(effects, closingSequenceEnd, 'whitespace')(code)
37768    }
37769    /** @type {State} */
37770
37771    function closingSequenceEnd(code) {
37772      if (code === null || markdownLineEnding(code)) {
37773        effects.exit('codeFencedFence');
37774        return ok(code)
37775      }
37776
37777      return nok(code)
37778    }
37779  }
37780}
37781
37782/**
37783 * @typedef {import('micromark-util-types').Construct} Construct
37784 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
37785 * @typedef {import('micromark-util-types').Resolver} Resolver
37786 * @typedef {import('micromark-util-types').Token} Token
37787 * @typedef {import('micromark-util-types').State} State
37788 */
37789
37790/** @type {Construct} */
37791const codeIndented = {
37792  name: 'codeIndented',
37793  tokenize: tokenizeCodeIndented
37794};
37795/** @type {Construct} */
37796
37797const indentedContent = {
37798  tokenize: tokenizeIndentedContent,
37799  partial: true
37800};
37801/** @type {Tokenizer} */
37802
37803function tokenizeCodeIndented(effects, ok, nok) {
37804  const self = this;
37805  return start
37806  /** @type {State} */
37807
37808  function start(code) {
37809    effects.enter('codeIndented');
37810    return factorySpace(effects, afterStartPrefix, 'linePrefix', 4 + 1)(code)
37811  }
37812  /** @type {State} */
37813
37814  function afterStartPrefix(code) {
37815    const tail = self.events[self.events.length - 1];
37816    return tail &&
37817      tail[1].type === 'linePrefix' &&
37818      tail[2].sliceSerialize(tail[1], true).length >= 4
37819      ? afterPrefix(code)
37820      : nok(code)
37821  }
37822  /** @type {State} */
37823
37824  function afterPrefix(code) {
37825    if (code === null) {
37826      return after(code)
37827    }
37828
37829    if (markdownLineEnding(code)) {
37830      return effects.attempt(indentedContent, afterPrefix, after)(code)
37831    }
37832
37833    effects.enter('codeFlowValue');
37834    return content(code)
37835  }
37836  /** @type {State} */
37837
37838  function content(code) {
37839    if (code === null || markdownLineEnding(code)) {
37840      effects.exit('codeFlowValue');
37841      return afterPrefix(code)
37842    }
37843
37844    effects.consume(code);
37845    return content
37846  }
37847  /** @type {State} */
37848
37849  function after(code) {
37850    effects.exit('codeIndented');
37851    return ok(code)
37852  }
37853}
37854/** @type {Tokenizer} */
37855
37856function tokenizeIndentedContent(effects, ok, nok) {
37857  const self = this;
37858  return start
37859  /** @type {State} */
37860
37861  function start(code) {
37862    // If this is a lazy line, it can’t be code.
37863    if (self.parser.lazy[self.now().line]) {
37864      return nok(code)
37865    }
37866
37867    if (markdownLineEnding(code)) {
37868      effects.enter('lineEnding');
37869      effects.consume(code);
37870      effects.exit('lineEnding');
37871      return start
37872    }
37873
37874    return factorySpace(effects, afterPrefix, 'linePrefix', 4 + 1)(code)
37875  }
37876  /** @type {State} */
37877
37878  function afterPrefix(code) {
37879    const tail = self.events[self.events.length - 1];
37880    return tail &&
37881      tail[1].type === 'linePrefix' &&
37882      tail[2].sliceSerialize(tail[1], true).length >= 4
37883      ? ok(code)
37884      : markdownLineEnding(code)
37885      ? start(code)
37886      : nok(code)
37887  }
37888}
37889
37890/**
37891 * @typedef {import('micromark-util-types').Construct} Construct
37892 * @typedef {import('micromark-util-types').Resolver} Resolver
37893 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
37894 * @typedef {import('micromark-util-types').Previous} Previous
37895 * @typedef {import('micromark-util-types').Token} Token
37896 * @typedef {import('micromark-util-types').State} State
37897 */
37898
37899/** @type {Construct} */
37900const codeText = {
37901  name: 'codeText',
37902  tokenize: tokenizeCodeText,
37903  resolve: resolveCodeText,
37904  previous: previous$1
37905};
37906/** @type {Resolver} */
37907
37908function resolveCodeText(events) {
37909  let tailExitIndex = events.length - 4;
37910  let headEnterIndex = 3;
37911  /** @type {number} */
37912
37913  let index;
37914  /** @type {number|undefined} */
37915
37916  let enter; // If we start and end with an EOL or a space.
37917
37918  if (
37919    (events[headEnterIndex][1].type === 'lineEnding' ||
37920      events[headEnterIndex][1].type === 'space') &&
37921    (events[tailExitIndex][1].type === 'lineEnding' ||
37922      events[tailExitIndex][1].type === 'space')
37923  ) {
37924    index = headEnterIndex; // And we have data.
37925
37926    while (++index < tailExitIndex) {
37927      if (events[index][1].type === 'codeTextData') {
37928        // Then we have padding.
37929        events[headEnterIndex][1].type = 'codeTextPadding';
37930        events[tailExitIndex][1].type = 'codeTextPadding';
37931        headEnterIndex += 2;
37932        tailExitIndex -= 2;
37933        break
37934      }
37935    }
37936  } // Merge adjacent spaces and data.
37937
37938  index = headEnterIndex - 1;
37939  tailExitIndex++;
37940
37941  while (++index <= tailExitIndex) {
37942    if (enter === undefined) {
37943      if (index !== tailExitIndex && events[index][1].type !== 'lineEnding') {
37944        enter = index;
37945      }
37946    } else if (
37947      index === tailExitIndex ||
37948      events[index][1].type === 'lineEnding'
37949    ) {
37950      events[enter][1].type = 'codeTextData';
37951
37952      if (index !== enter + 2) {
37953        events[enter][1].end = events[index - 1][1].end;
37954        events.splice(enter + 2, index - enter - 2);
37955        tailExitIndex -= index - enter - 2;
37956        index = enter + 2;
37957      }
37958
37959      enter = undefined;
37960    }
37961  }
37962
37963  return events
37964}
37965/** @type {Previous} */
37966
37967function previous$1(code) {
37968  // If there is a previous code, there will always be a tail.
37969  return (
37970    code !== 96 ||
37971    this.events[this.events.length - 1][1].type === 'characterEscape'
37972  )
37973}
37974/** @type {Tokenizer} */
37975
37976function tokenizeCodeText(effects, ok, nok) {
37977  let sizeOpen = 0;
37978  /** @type {number} */
37979
37980  let size;
37981  /** @type {Token} */
37982
37983  let token;
37984  return start
37985  /** @type {State} */
37986
37987  function start(code) {
37988    effects.enter('codeText');
37989    effects.enter('codeTextSequence');
37990    return openingSequence(code)
37991  }
37992  /** @type {State} */
37993
37994  function openingSequence(code) {
37995    if (code === 96) {
37996      effects.consume(code);
37997      sizeOpen++;
37998      return openingSequence
37999    }
38000
38001    effects.exit('codeTextSequence');
38002    return gap(code)
38003  }
38004  /** @type {State} */
38005
38006  function gap(code) {
38007    // EOF.
38008    if (code === null) {
38009      return nok(code)
38010    } // Closing fence?
38011    // Could also be data.
38012
38013    if (code === 96) {
38014      token = effects.enter('codeTextSequence');
38015      size = 0;
38016      return closingSequence(code)
38017    } // Tabs don’t work, and virtual spaces don’t make sense.
38018
38019    if (code === 32) {
38020      effects.enter('space');
38021      effects.consume(code);
38022      effects.exit('space');
38023      return gap
38024    }
38025
38026    if (markdownLineEnding(code)) {
38027      effects.enter('lineEnding');
38028      effects.consume(code);
38029      effects.exit('lineEnding');
38030      return gap
38031    } // Data.
38032
38033    effects.enter('codeTextData');
38034    return data(code)
38035  } // In code.
38036
38037  /** @type {State} */
38038
38039  function data(code) {
38040    if (
38041      code === null ||
38042      code === 32 ||
38043      code === 96 ||
38044      markdownLineEnding(code)
38045    ) {
38046      effects.exit('codeTextData');
38047      return gap(code)
38048    }
38049
38050    effects.consume(code);
38051    return data
38052  } // Closing fence.
38053
38054  /** @type {State} */
38055
38056  function closingSequence(code) {
38057    // More.
38058    if (code === 96) {
38059      effects.consume(code);
38060      size++;
38061      return closingSequence
38062    } // Done!
38063
38064    if (size === sizeOpen) {
38065      effects.exit('codeTextSequence');
38066      effects.exit('codeText');
38067      return ok(code)
38068    } // More or less accents: mark as data.
38069
38070    token.type = 'codeTextData';
38071    return data(code)
38072  }
38073}
38074
38075/**
38076 * @typedef {import('micromark-util-types').Token} Token
38077 * @typedef {import('micromark-util-types').Chunk} Chunk
38078 * @typedef {import('micromark-util-types').Event} Event
38079 */
38080
38081/**
38082 * Tokenize subcontent.
38083 *
38084 * @param {Event[]} events
38085 * @returns {boolean}
38086 */
38087function subtokenize(events) {
38088  /** @type {Record<string, number>} */
38089  const jumps = {};
38090  let index = -1;
38091  /** @type {Event} */
38092
38093  let event;
38094  /** @type {number|undefined} */
38095
38096  let lineIndex;
38097  /** @type {number} */
38098
38099  let otherIndex;
38100  /** @type {Event} */
38101
38102  let otherEvent;
38103  /** @type {Event[]} */
38104
38105  let parameters;
38106  /** @type {Event[]} */
38107
38108  let subevents;
38109  /** @type {boolean|undefined} */
38110
38111  let more;
38112
38113  while (++index < events.length) {
38114    while (index in jumps) {
38115      index = jumps[index];
38116    }
38117
38118    event = events[index]; // Add a hook for the GFM tasklist extension, which needs to know if text
38119    // is in the first content of a list item.
38120
38121    if (
38122      index &&
38123      event[1].type === 'chunkFlow' &&
38124      events[index - 1][1].type === 'listItemPrefix'
38125    ) {
38126      subevents = event[1]._tokenizer.events;
38127      otherIndex = 0;
38128
38129      if (
38130        otherIndex < subevents.length &&
38131        subevents[otherIndex][1].type === 'lineEndingBlank'
38132      ) {
38133        otherIndex += 2;
38134      }
38135
38136      if (
38137        otherIndex < subevents.length &&
38138        subevents[otherIndex][1].type === 'content'
38139      ) {
38140        while (++otherIndex < subevents.length) {
38141          if (subevents[otherIndex][1].type === 'content') {
38142            break
38143          }
38144
38145          if (subevents[otherIndex][1].type === 'chunkText') {
38146            subevents[otherIndex][1]._isInFirstContentOfListItem = true;
38147            otherIndex++;
38148          }
38149        }
38150      }
38151    } // Enter.
38152
38153    if (event[0] === 'enter') {
38154      if (event[1].contentType) {
38155        Object.assign(jumps, subcontent(events, index));
38156        index = jumps[index];
38157        more = true;
38158      }
38159    } // Exit.
38160    else if (event[1]._container) {
38161      otherIndex = index;
38162      lineIndex = undefined;
38163
38164      while (otherIndex--) {
38165        otherEvent = events[otherIndex];
38166
38167        if (
38168          otherEvent[1].type === 'lineEnding' ||
38169          otherEvent[1].type === 'lineEndingBlank'
38170        ) {
38171          if (otherEvent[0] === 'enter') {
38172            if (lineIndex) {
38173              events[lineIndex][1].type = 'lineEndingBlank';
38174            }
38175
38176            otherEvent[1].type = 'lineEnding';
38177            lineIndex = otherIndex;
38178          }
38179        } else {
38180          break
38181        }
38182      }
38183
38184      if (lineIndex) {
38185        // Fix position.
38186        event[1].end = Object.assign({}, events[lineIndex][1].start); // Switch container exit w/ line endings.
38187
38188        parameters = events.slice(lineIndex, index);
38189        parameters.unshift(event);
38190        splice(events, lineIndex, index - lineIndex + 1, parameters);
38191      }
38192    }
38193  }
38194
38195  return !more
38196}
38197/**
38198 * Tokenize embedded tokens.
38199 *
38200 * @param {Event[]} events
38201 * @param {number} eventIndex
38202 * @returns {Record<string, number>}
38203 */
38204
38205function subcontent(events, eventIndex) {
38206  const token = events[eventIndex][1];
38207  const context = events[eventIndex][2];
38208  let startPosition = eventIndex - 1;
38209  /** @type {number[]} */
38210
38211  const startPositions = [];
38212  const tokenizer =
38213    token._tokenizer || context.parser[token.contentType](token.start);
38214  const childEvents = tokenizer.events;
38215  /** @type {[number, number][]} */
38216
38217  const jumps = [];
38218  /** @type {Record<string, number>} */
38219
38220  const gaps = {};
38221  /** @type {Chunk[]} */
38222
38223  let stream;
38224  /** @type {Token|undefined} */
38225
38226  let previous;
38227  let index = -1;
38228  /** @type {Token|undefined} */
38229
38230  let current = token;
38231  let adjust = 0;
38232  let start = 0;
38233  const breaks = [start]; // Loop forward through the linked tokens to pass them in order to the
38234  // subtokenizer.
38235
38236  while (current) {
38237    // Find the position of the event for this token.
38238    while (events[++startPosition][1] !== current) {
38239      // Empty.
38240    }
38241
38242    startPositions.push(startPosition);
38243
38244    if (!current._tokenizer) {
38245      stream = context.sliceStream(current);
38246
38247      if (!current.next) {
38248        stream.push(null);
38249      }
38250
38251      if (previous) {
38252        tokenizer.defineSkip(current.start);
38253      }
38254
38255      if (current._isInFirstContentOfListItem) {
38256        tokenizer._gfmTasklistFirstContentOfListItem = true;
38257      }
38258
38259      tokenizer.write(stream);
38260
38261      if (current._isInFirstContentOfListItem) {
38262        tokenizer._gfmTasklistFirstContentOfListItem = undefined;
38263      }
38264    } // Unravel the next token.
38265
38266    previous = current;
38267    current = current.next;
38268  } // Now, loop back through all events (and linked tokens), to figure out which
38269  // parts belong where.
38270
38271  current = token;
38272
38273  while (++index < childEvents.length) {
38274    if (
38275      // Find a void token that includes a break.
38276      childEvents[index][0] === 'exit' &&
38277      childEvents[index - 1][0] === 'enter' &&
38278      childEvents[index][1].type === childEvents[index - 1][1].type &&
38279      childEvents[index][1].start.line !== childEvents[index][1].end.line
38280    ) {
38281      start = index + 1;
38282      breaks.push(start); // Help GC.
38283
38284      current._tokenizer = undefined;
38285      current.previous = undefined;
38286      current = current.next;
38287    }
38288  } // Help GC.
38289
38290  tokenizer.events = []; // If there’s one more token (which is the cases for lines that end in an
38291  // EOF), that’s perfect: the last point we found starts it.
38292  // If there isn’t then make sure any remaining content is added to it.
38293
38294  if (current) {
38295    // Help GC.
38296    current._tokenizer = undefined;
38297    current.previous = undefined;
38298  } else {
38299    breaks.pop();
38300  } // Now splice the events from the subtokenizer into the current events,
38301  // moving back to front so that splice indices aren’t affected.
38302
38303  index = breaks.length;
38304
38305  while (index--) {
38306    const slice = childEvents.slice(breaks[index], breaks[index + 1]);
38307    const start = startPositions.pop();
38308    jumps.unshift([start, start + slice.length - 1]);
38309    splice(events, start, 2, slice);
38310  }
38311
38312  index = -1;
38313
38314  while (++index < jumps.length) {
38315    gaps[adjust + jumps[index][0]] = adjust + jumps[index][1];
38316    adjust += jumps[index][1] - jumps[index][0] - 1;
38317  }
38318
38319  return gaps
38320}
38321
38322/**
38323 * @typedef {import('micromark-util-types').Construct} Construct
38324 * @typedef {import('micromark-util-types').Resolver} Resolver
38325 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
38326 * @typedef {import('micromark-util-types').Token} Token
38327 * @typedef {import('micromark-util-types').State} State
38328 */
38329
38330/**
38331 * No name because it must not be turned off.
38332 * @type {Construct}
38333 */
38334const content = {
38335  tokenize: tokenizeContent,
38336  resolve: resolveContent
38337};
38338/** @type {Construct} */
38339
38340const continuationConstruct = {
38341  tokenize: tokenizeContinuation,
38342  partial: true
38343};
38344/**
38345 * Content is transparent: it’s parsed right now. That way, definitions are also
38346 * parsed right now: before text in paragraphs (specifically, media) are parsed.
38347 *
38348 * @type {Resolver}
38349 */
38350
38351function resolveContent(events) {
38352  subtokenize(events);
38353  return events
38354}
38355/** @type {Tokenizer} */
38356
38357function tokenizeContent(effects, ok) {
38358  /** @type {Token} */
38359  let previous;
38360  return start
38361  /** @type {State} */
38362
38363  function start(code) {
38364    effects.enter('content');
38365    previous = effects.enter('chunkContent', {
38366      contentType: 'content'
38367    });
38368    return data(code)
38369  }
38370  /** @type {State} */
38371
38372  function data(code) {
38373    if (code === null) {
38374      return contentEnd(code)
38375    }
38376
38377    if (markdownLineEnding(code)) {
38378      return effects.check(
38379        continuationConstruct,
38380        contentContinue,
38381        contentEnd
38382      )(code)
38383    } // Data.
38384
38385    effects.consume(code);
38386    return data
38387  }
38388  /** @type {State} */
38389
38390  function contentEnd(code) {
38391    effects.exit('chunkContent');
38392    effects.exit('content');
38393    return ok(code)
38394  }
38395  /** @type {State} */
38396
38397  function contentContinue(code) {
38398    effects.consume(code);
38399    effects.exit('chunkContent');
38400    previous.next = effects.enter('chunkContent', {
38401      contentType: 'content',
38402      previous
38403    });
38404    previous = previous.next;
38405    return data
38406  }
38407}
38408/** @type {Tokenizer} */
38409
38410function tokenizeContinuation(effects, ok, nok) {
38411  const self = this;
38412  return startLookahead
38413  /** @type {State} */
38414
38415  function startLookahead(code) {
38416    effects.exit('chunkContent');
38417    effects.enter('lineEnding');
38418    effects.consume(code);
38419    effects.exit('lineEnding');
38420    return factorySpace(effects, prefixed, 'linePrefix')
38421  }
38422  /** @type {State} */
38423
38424  function prefixed(code) {
38425    if (code === null || markdownLineEnding(code)) {
38426      return nok(code)
38427    }
38428
38429    const tail = self.events[self.events.length - 1];
38430
38431    if (
38432      !self.parser.constructs.disable.null.includes('codeIndented') &&
38433      tail &&
38434      tail[1].type === 'linePrefix' &&
38435      tail[2].sliceSerialize(tail[1], true).length >= 4
38436    ) {
38437      return ok(code)
38438    }
38439
38440    return effects.interrupt(self.parser.constructs.flow, nok, ok)(code)
38441  }
38442}
38443
38444/**
38445 * @typedef {import('micromark-util-types').Effects} Effects
38446 * @typedef {import('micromark-util-types').State} State
38447 */
38448
38449/**
38450 * @param {Effects} effects
38451 * @param {State} ok
38452 * @param {State} nok
38453 * @param {string} type
38454 * @param {string} literalType
38455 * @param {string} literalMarkerType
38456 * @param {string} rawType
38457 * @param {string} stringType
38458 * @param {number} [max=Infinity]
38459 * @returns {State}
38460 */
38461// eslint-disable-next-line max-params
38462function factoryDestination(
38463  effects,
38464  ok,
38465  nok,
38466  type,
38467  literalType,
38468  literalMarkerType,
38469  rawType,
38470  stringType,
38471  max
38472) {
38473  const limit = max || Number.POSITIVE_INFINITY;
38474  let balance = 0;
38475  return start
38476  /** @type {State} */
38477
38478  function start(code) {
38479    if (code === 60) {
38480      effects.enter(type);
38481      effects.enter(literalType);
38482      effects.enter(literalMarkerType);
38483      effects.consume(code);
38484      effects.exit(literalMarkerType);
38485      return destinationEnclosedBefore
38486    }
38487
38488    if (code === null || code === 41 || asciiControl(code)) {
38489      return nok(code)
38490    }
38491
38492    effects.enter(type);
38493    effects.enter(rawType);
38494    effects.enter(stringType);
38495    effects.enter('chunkString', {
38496      contentType: 'string'
38497    });
38498    return destinationRaw(code)
38499  }
38500  /** @type {State} */
38501
38502  function destinationEnclosedBefore(code) {
38503    if (code === 62) {
38504      effects.enter(literalMarkerType);
38505      effects.consume(code);
38506      effects.exit(literalMarkerType);
38507      effects.exit(literalType);
38508      effects.exit(type);
38509      return ok
38510    }
38511
38512    effects.enter(stringType);
38513    effects.enter('chunkString', {
38514      contentType: 'string'
38515    });
38516    return destinationEnclosed(code)
38517  }
38518  /** @type {State} */
38519
38520  function destinationEnclosed(code) {
38521    if (code === 62) {
38522      effects.exit('chunkString');
38523      effects.exit(stringType);
38524      return destinationEnclosedBefore(code)
38525    }
38526
38527    if (code === null || code === 60 || markdownLineEnding(code)) {
38528      return nok(code)
38529    }
38530
38531    effects.consume(code);
38532    return code === 92 ? destinationEnclosedEscape : destinationEnclosed
38533  }
38534  /** @type {State} */
38535
38536  function destinationEnclosedEscape(code) {
38537    if (code === 60 || code === 62 || code === 92) {
38538      effects.consume(code);
38539      return destinationEnclosed
38540    }
38541
38542    return destinationEnclosed(code)
38543  }
38544  /** @type {State} */
38545
38546  function destinationRaw(code) {
38547    if (code === 40) {
38548      if (++balance > limit) return nok(code)
38549      effects.consume(code);
38550      return destinationRaw
38551    }
38552
38553    if (code === 41) {
38554      if (!balance--) {
38555        effects.exit('chunkString');
38556        effects.exit(stringType);
38557        effects.exit(rawType);
38558        effects.exit(type);
38559        return ok(code)
38560      }
38561
38562      effects.consume(code);
38563      return destinationRaw
38564    }
38565
38566    if (code === null || markdownLineEndingOrSpace(code)) {
38567      if (balance) return nok(code)
38568      effects.exit('chunkString');
38569      effects.exit(stringType);
38570      effects.exit(rawType);
38571      effects.exit(type);
38572      return ok(code)
38573    }
38574
38575    if (asciiControl(code)) return nok(code)
38576    effects.consume(code);
38577    return code === 92 ? destinationRawEscape : destinationRaw
38578  }
38579  /** @type {State} */
38580
38581  function destinationRawEscape(code) {
38582    if (code === 40 || code === 41 || code === 92) {
38583      effects.consume(code);
38584      return destinationRaw
38585    }
38586
38587    return destinationRaw(code)
38588  }
38589}
38590
38591/**
38592 * @typedef {import('micromark-util-types').Effects} Effects
38593 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
38594 * @typedef {import('micromark-util-types').State} State
38595 */
38596
38597/**
38598 * @this {TokenizeContext}
38599 * @param {Effects} effects
38600 * @param {State} ok
38601 * @param {State} nok
38602 * @param {string} type
38603 * @param {string} markerType
38604 * @param {string} stringType
38605 * @returns {State}
38606 */
38607// eslint-disable-next-line max-params
38608function factoryLabel(effects, ok, nok, type, markerType, stringType) {
38609  const self = this;
38610  let size = 0;
38611  /** @type {boolean} */
38612
38613  let data;
38614  return start
38615  /** @type {State} */
38616
38617  function start(code) {
38618    effects.enter(type);
38619    effects.enter(markerType);
38620    effects.consume(code);
38621    effects.exit(markerType);
38622    effects.enter(stringType);
38623    return atBreak
38624  }
38625  /** @type {State} */
38626
38627  function atBreak(code) {
38628    if (
38629      code === null ||
38630      code === 91 ||
38631      (code === 93 && !data) ||
38632      /* Hidden footnotes hook */
38633
38634      /* c8 ignore next 3 */
38635      (code === 94 &&
38636        !size &&
38637        '_hiddenFootnoteSupport' in self.parser.constructs) ||
38638      size > 999
38639    ) {
38640      return nok(code)
38641    }
38642
38643    if (code === 93) {
38644      effects.exit(stringType);
38645      effects.enter(markerType);
38646      effects.consume(code);
38647      effects.exit(markerType);
38648      effects.exit(type);
38649      return ok
38650    }
38651
38652    if (markdownLineEnding(code)) {
38653      effects.enter('lineEnding');
38654      effects.consume(code);
38655      effects.exit('lineEnding');
38656      return atBreak
38657    }
38658
38659    effects.enter('chunkString', {
38660      contentType: 'string'
38661    });
38662    return label(code)
38663  }
38664  /** @type {State} */
38665
38666  function label(code) {
38667    if (
38668      code === null ||
38669      code === 91 ||
38670      code === 93 ||
38671      markdownLineEnding(code) ||
38672      size++ > 999
38673    ) {
38674      effects.exit('chunkString');
38675      return atBreak(code)
38676    }
38677
38678    effects.consume(code);
38679    data = data || !markdownSpace(code);
38680    return code === 92 ? labelEscape : label
38681  }
38682  /** @type {State} */
38683
38684  function labelEscape(code) {
38685    if (code === 91 || code === 92 || code === 93) {
38686      effects.consume(code);
38687      size++;
38688      return label
38689    }
38690
38691    return label(code)
38692  }
38693}
38694
38695/**
38696 * @typedef {import('micromark-util-types').Effects} Effects
38697 * @typedef {import('micromark-util-types').State} State
38698 * @typedef {import('micromark-util-types').Code} Code
38699 */
38700
38701/**
38702 * @param {Effects} effects
38703 * @param {State} ok
38704 * @param {State} nok
38705 * @param {string} type
38706 * @param {string} markerType
38707 * @param {string} stringType
38708 * @returns {State}
38709 */
38710// eslint-disable-next-line max-params
38711function factoryTitle(effects, ok, nok, type, markerType, stringType) {
38712  /** @type {NonNullable<Code>} */
38713  let marker;
38714  return start
38715  /** @type {State} */
38716
38717  function start(code) {
38718    effects.enter(type);
38719    effects.enter(markerType);
38720    effects.consume(code);
38721    effects.exit(markerType);
38722    marker = code === 40 ? 41 : code;
38723    return atFirstTitleBreak
38724  }
38725  /** @type {State} */
38726
38727  function atFirstTitleBreak(code) {
38728    if (code === marker) {
38729      effects.enter(markerType);
38730      effects.consume(code);
38731      effects.exit(markerType);
38732      effects.exit(type);
38733      return ok
38734    }
38735
38736    effects.enter(stringType);
38737    return atTitleBreak(code)
38738  }
38739  /** @type {State} */
38740
38741  function atTitleBreak(code) {
38742    if (code === marker) {
38743      effects.exit(stringType);
38744      return atFirstTitleBreak(marker)
38745    }
38746
38747    if (code === null) {
38748      return nok(code)
38749    } // Note: blank lines can’t exist in content.
38750
38751    if (markdownLineEnding(code)) {
38752      effects.enter('lineEnding');
38753      effects.consume(code);
38754      effects.exit('lineEnding');
38755      return factorySpace(effects, atTitleBreak, 'linePrefix')
38756    }
38757
38758    effects.enter('chunkString', {
38759      contentType: 'string'
38760    });
38761    return title(code)
38762  }
38763  /** @type {State} */
38764
38765  function title(code) {
38766    if (code === marker || code === null || markdownLineEnding(code)) {
38767      effects.exit('chunkString');
38768      return atTitleBreak(code)
38769    }
38770
38771    effects.consume(code);
38772    return code === 92 ? titleEscape : title
38773  }
38774  /** @type {State} */
38775
38776  function titleEscape(code) {
38777    if (code === marker || code === 92) {
38778      effects.consume(code);
38779      return title
38780    }
38781
38782    return title(code)
38783  }
38784}
38785
38786/**
38787 * @typedef {import('micromark-util-types').Effects} Effects
38788 * @typedef {import('micromark-util-types').State} State
38789 */
38790
38791/**
38792 * @param {Effects} effects
38793 * @param {State} ok
38794 */
38795function factoryWhitespace(effects, ok) {
38796  /** @type {boolean} */
38797  let seen;
38798  return start
38799  /** @type {State} */
38800
38801  function start(code) {
38802    if (markdownLineEnding(code)) {
38803      effects.enter('lineEnding');
38804      effects.consume(code);
38805      effects.exit('lineEnding');
38806      seen = true;
38807      return start
38808    }
38809
38810    if (markdownSpace(code)) {
38811      return factorySpace(
38812        effects,
38813        start,
38814        seen ? 'linePrefix' : 'lineSuffix'
38815      )(code)
38816    }
38817
38818    return ok(code)
38819  }
38820}
38821
38822/**
38823 * Normalize an identifier (such as used in definitions).
38824 *
38825 * @param {string} value
38826 * @returns {string}
38827 */
38828function normalizeIdentifier(value) {
38829  return (
38830    value // Collapse Markdown whitespace.
38831      .replace(/[\t\n\r ]+/g, ' ') // Trim.
38832      .replace(/^ | $/g, '') // Some characters are considered “uppercase”, but if their lowercase
38833      // counterpart is uppercased will result in a different uppercase
38834      // character.
38835      // Hence, to get that form, we perform both lower- and uppercase.
38836      // Upper case makes sure keys will not interact with default prototypal
38837      // methods: no method is uppercase.
38838      .toLowerCase()
38839      .toUpperCase()
38840  )
38841}
38842
38843/**
38844 * @typedef {import('micromark-util-types').Construct} Construct
38845 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
38846 * @typedef {import('micromark-util-types').State} State
38847 */
38848
38849/** @type {Construct} */
38850const definition$1 = {
38851  name: 'definition',
38852  tokenize: tokenizeDefinition
38853};
38854/** @type {Construct} */
38855
38856const titleConstruct = {
38857  tokenize: tokenizeTitle,
38858  partial: true
38859};
38860/** @type {Tokenizer} */
38861
38862function tokenizeDefinition(effects, ok, nok) {
38863  const self = this;
38864  /** @type {string} */
38865
38866  let identifier;
38867  return start
38868  /** @type {State} */
38869
38870  function start(code) {
38871    effects.enter('definition');
38872    return factoryLabel.call(
38873      self,
38874      effects,
38875      labelAfter,
38876      nok,
38877      'definitionLabel',
38878      'definitionLabelMarker',
38879      'definitionLabelString'
38880    )(code)
38881  }
38882  /** @type {State} */
38883
38884  function labelAfter(code) {
38885    identifier = normalizeIdentifier(
38886      self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1)
38887    );
38888
38889    if (code === 58) {
38890      effects.enter('definitionMarker');
38891      effects.consume(code);
38892      effects.exit('definitionMarker'); // Note: blank lines can’t exist in content.
38893
38894      return factoryWhitespace(
38895        effects,
38896        factoryDestination(
38897          effects,
38898          effects.attempt(
38899            titleConstruct,
38900            factorySpace(effects, after, 'whitespace'),
38901            factorySpace(effects, after, 'whitespace')
38902          ),
38903          nok,
38904          'definitionDestination',
38905          'definitionDestinationLiteral',
38906          'definitionDestinationLiteralMarker',
38907          'definitionDestinationRaw',
38908          'definitionDestinationString'
38909        )
38910      )
38911    }
38912
38913    return nok(code)
38914  }
38915  /** @type {State} */
38916
38917  function after(code) {
38918    if (code === null || markdownLineEnding(code)) {
38919      effects.exit('definition');
38920
38921      if (!self.parser.defined.includes(identifier)) {
38922        self.parser.defined.push(identifier);
38923      }
38924
38925      return ok(code)
38926    }
38927
38928    return nok(code)
38929  }
38930}
38931/** @type {Tokenizer} */
38932
38933function tokenizeTitle(effects, ok, nok) {
38934  return start
38935  /** @type {State} */
38936
38937  function start(code) {
38938    return markdownLineEndingOrSpace(code)
38939      ? factoryWhitespace(effects, before)(code)
38940      : nok(code)
38941  }
38942  /** @type {State} */
38943
38944  function before(code) {
38945    if (code === 34 || code === 39 || code === 40) {
38946      return factoryTitle(
38947        effects,
38948        factorySpace(effects, after, 'whitespace'),
38949        nok,
38950        'definitionTitle',
38951        'definitionTitleMarker',
38952        'definitionTitleString'
38953      )(code)
38954    }
38955
38956    return nok(code)
38957  }
38958  /** @type {State} */
38959
38960  function after(code) {
38961    return code === null || markdownLineEnding(code) ? ok(code) : nok(code)
38962  }
38963}
38964
38965/**
38966 * @typedef {import('micromark-util-types').Construct} Construct
38967 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
38968 * @typedef {import('micromark-util-types').State} State
38969 */
38970
38971/** @type {Construct} */
38972const hardBreakEscape = {
38973  name: 'hardBreakEscape',
38974  tokenize: tokenizeHardBreakEscape
38975};
38976/** @type {Tokenizer} */
38977
38978function tokenizeHardBreakEscape(effects, ok, nok) {
38979  return start
38980  /** @type {State} */
38981
38982  function start(code) {
38983    effects.enter('hardBreakEscape');
38984    effects.enter('escapeMarker');
38985    effects.consume(code);
38986    return open
38987  }
38988  /** @type {State} */
38989
38990  function open(code) {
38991    if (markdownLineEnding(code)) {
38992      effects.exit('escapeMarker');
38993      effects.exit('hardBreakEscape');
38994      return ok(code)
38995    }
38996
38997    return nok(code)
38998  }
38999}
39000
39001/**
39002 * @typedef {import('micromark-util-types').Construct} Construct
39003 * @typedef {import('micromark-util-types').Resolver} Resolver
39004 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
39005 * @typedef {import('micromark-util-types').Token} Token
39006 * @typedef {import('micromark-util-types').State} State
39007 */
39008
39009/** @type {Construct} */
39010const headingAtx = {
39011  name: 'headingAtx',
39012  tokenize: tokenizeHeadingAtx,
39013  resolve: resolveHeadingAtx
39014};
39015/** @type {Resolver} */
39016
39017function resolveHeadingAtx(events, context) {
39018  let contentEnd = events.length - 2;
39019  let contentStart = 3;
39020  /** @type {Token} */
39021
39022  let content;
39023  /** @type {Token} */
39024
39025  let text; // Prefix whitespace, part of the opening.
39026
39027  if (events[contentStart][1].type === 'whitespace') {
39028    contentStart += 2;
39029  } // Suffix whitespace, part of the closing.
39030
39031  if (
39032    contentEnd - 2 > contentStart &&
39033    events[contentEnd][1].type === 'whitespace'
39034  ) {
39035    contentEnd -= 2;
39036  }
39037
39038  if (
39039    events[contentEnd][1].type === 'atxHeadingSequence' &&
39040    (contentStart === contentEnd - 1 ||
39041      (contentEnd - 4 > contentStart &&
39042        events[contentEnd - 2][1].type === 'whitespace'))
39043  ) {
39044    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;
39045  }
39046
39047  if (contentEnd > contentStart) {
39048    content = {
39049      type: 'atxHeadingText',
39050      start: events[contentStart][1].start,
39051      end: events[contentEnd][1].end
39052    };
39053    text = {
39054      type: 'chunkText',
39055      start: events[contentStart][1].start,
39056      end: events[contentEnd][1].end,
39057      // @ts-expect-error Constants are fine to assign.
39058      contentType: 'text'
39059    };
39060    splice(events, contentStart, contentEnd - contentStart + 1, [
39061      ['enter', content, context],
39062      ['enter', text, context],
39063      ['exit', text, context],
39064      ['exit', content, context]
39065    ]);
39066  }
39067
39068  return events
39069}
39070/** @type {Tokenizer} */
39071
39072function tokenizeHeadingAtx(effects, ok, nok) {
39073  const self = this;
39074  let size = 0;
39075  return start
39076  /** @type {State} */
39077
39078  function start(code) {
39079    effects.enter('atxHeading');
39080    effects.enter('atxHeadingSequence');
39081    return fenceOpenInside(code)
39082  }
39083  /** @type {State} */
39084
39085  function fenceOpenInside(code) {
39086    if (code === 35 && size++ < 6) {
39087      effects.consume(code);
39088      return fenceOpenInside
39089    }
39090
39091    if (code === null || markdownLineEndingOrSpace(code)) {
39092      effects.exit('atxHeadingSequence');
39093      return self.interrupt ? ok(code) : headingBreak(code)
39094    }
39095
39096    return nok(code)
39097  }
39098  /** @type {State} */
39099
39100  function headingBreak(code) {
39101    if (code === 35) {
39102      effects.enter('atxHeadingSequence');
39103      return sequence(code)
39104    }
39105
39106    if (code === null || markdownLineEnding(code)) {
39107      effects.exit('atxHeading');
39108      return ok(code)
39109    }
39110
39111    if (markdownSpace(code)) {
39112      return factorySpace(effects, headingBreak, 'whitespace')(code)
39113    }
39114
39115    effects.enter('atxHeadingText');
39116    return data(code)
39117  }
39118  /** @type {State} */
39119
39120  function sequence(code) {
39121    if (code === 35) {
39122      effects.consume(code);
39123      return sequence
39124    }
39125
39126    effects.exit('atxHeadingSequence');
39127    return headingBreak(code)
39128  }
39129  /** @type {State} */
39130
39131  function data(code) {
39132    if (code === null || code === 35 || markdownLineEndingOrSpace(code)) {
39133      effects.exit('atxHeadingText');
39134      return headingBreak(code)
39135    }
39136
39137    effects.consume(code);
39138    return data
39139  }
39140}
39141
39142/**
39143 * List of lowercase HTML tag names which when parsing HTML (flow), result
39144 * in more relaxed rules (condition 6): because they are known blocks, the
39145 * HTML-like syntax doesn’t have to be strictly parsed.
39146 * For tag names not in this list, a more strict algorithm (condition 7) is used
39147 * to detect whether the HTML-like syntax is seen as HTML (flow) or not.
39148 *
39149 * This is copied from:
39150 * <https://spec.commonmark.org/0.29/#html-blocks>.
39151 */
39152const htmlBlockNames = [
39153  'address',
39154  'article',
39155  'aside',
39156  'base',
39157  'basefont',
39158  'blockquote',
39159  'body',
39160  'caption',
39161  'center',
39162  'col',
39163  'colgroup',
39164  'dd',
39165  'details',
39166  'dialog',
39167  'dir',
39168  'div',
39169  'dl',
39170  'dt',
39171  'fieldset',
39172  'figcaption',
39173  'figure',
39174  'footer',
39175  'form',
39176  'frame',
39177  'frameset',
39178  'h1',
39179  'h2',
39180  'h3',
39181  'h4',
39182  'h5',
39183  'h6',
39184  'head',
39185  'header',
39186  'hr',
39187  'html',
39188  'iframe',
39189  'legend',
39190  'li',
39191  'link',
39192  'main',
39193  'menu',
39194  'menuitem',
39195  'nav',
39196  'noframes',
39197  'ol',
39198  'optgroup',
39199  'option',
39200  'p',
39201  'param',
39202  'section',
39203  'source',
39204  'summary',
39205  'table',
39206  'tbody',
39207  'td',
39208  'tfoot',
39209  'th',
39210  'thead',
39211  'title',
39212  'tr',
39213  'track',
39214  'ul'
39215];
39216
39217/**
39218 * List of lowercase HTML tag names which when parsing HTML (flow), result in
39219 * HTML that can include lines w/o exiting, until a closing tag also in this
39220 * list is found (condition 1).
39221 *
39222 * This module is copied from:
39223 * <https://spec.commonmark.org/0.29/#html-blocks>.
39224 *
39225 * Note that `textarea` is not available in `CommonMark@0.29` but has been
39226 * merged to the primary branch and is slated to be released in the next release
39227 * of CommonMark.
39228 */
39229const htmlRawNames = ['pre', 'script', 'style', 'textarea'];
39230
39231/**
39232 * @typedef {import('micromark-util-types').Construct} Construct
39233 * @typedef {import('micromark-util-types').Resolver} Resolver
39234 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
39235 * @typedef {import('micromark-util-types').State} State
39236 * @typedef {import('micromark-util-types').Code} Code
39237 */
39238/** @type {Construct} */
39239
39240const htmlFlow = {
39241  name: 'htmlFlow',
39242  tokenize: tokenizeHtmlFlow,
39243  resolveTo: resolveToHtmlFlow,
39244  concrete: true
39245};
39246/** @type {Construct} */
39247
39248const nextBlankConstruct = {
39249  tokenize: tokenizeNextBlank,
39250  partial: true
39251};
39252/** @type {Resolver} */
39253
39254function resolveToHtmlFlow(events) {
39255  let index = events.length;
39256
39257  while (index--) {
39258    if (events[index][0] === 'enter' && events[index][1].type === 'htmlFlow') {
39259      break
39260    }
39261  }
39262
39263  if (index > 1 && events[index - 2][1].type === 'linePrefix') {
39264    // Add the prefix start to the HTML token.
39265    events[index][1].start = events[index - 2][1].start; // Add the prefix start to the HTML line token.
39266
39267    events[index + 1][1].start = events[index - 2][1].start; // Remove the line prefix.
39268
39269    events.splice(index - 2, 2);
39270  }
39271
39272  return events
39273}
39274/** @type {Tokenizer} */
39275
39276function tokenizeHtmlFlow(effects, ok, nok) {
39277  const self = this;
39278  /** @type {number} */
39279
39280  let kind;
39281  /** @type {boolean} */
39282
39283  let startTag;
39284  /** @type {string} */
39285
39286  let buffer;
39287  /** @type {number} */
39288
39289  let index;
39290  /** @type {Code} */
39291
39292  let marker;
39293  return start
39294  /** @type {State} */
39295
39296  function start(code) {
39297    effects.enter('htmlFlow');
39298    effects.enter('htmlFlowData');
39299    effects.consume(code);
39300    return open
39301  }
39302  /** @type {State} */
39303
39304  function open(code) {
39305    if (code === 33) {
39306      effects.consume(code);
39307      return declarationStart
39308    }
39309
39310    if (code === 47) {
39311      effects.consume(code);
39312      return tagCloseStart
39313    }
39314
39315    if (code === 63) {
39316      effects.consume(code);
39317      kind = 3; // While we’re in an instruction instead of a declaration, we’re on a `?`
39318      // right now, so we do need to search for `>`, similar to declarations.
39319
39320      return self.interrupt ? ok : continuationDeclarationInside
39321    }
39322
39323    if (asciiAlpha(code)) {
39324      effects.consume(code);
39325      buffer = String.fromCharCode(code);
39326      startTag = true;
39327      return tagName
39328    }
39329
39330    return nok(code)
39331  }
39332  /** @type {State} */
39333
39334  function declarationStart(code) {
39335    if (code === 45) {
39336      effects.consume(code);
39337      kind = 2;
39338      return commentOpenInside
39339    }
39340
39341    if (code === 91) {
39342      effects.consume(code);
39343      kind = 5;
39344      buffer = 'CDATA[';
39345      index = 0;
39346      return cdataOpenInside
39347    }
39348
39349    if (asciiAlpha(code)) {
39350      effects.consume(code);
39351      kind = 4;
39352      return self.interrupt ? ok : continuationDeclarationInside
39353    }
39354
39355    return nok(code)
39356  }
39357  /** @type {State} */
39358
39359  function commentOpenInside(code) {
39360    if (code === 45) {
39361      effects.consume(code);
39362      return self.interrupt ? ok : continuationDeclarationInside
39363    }
39364
39365    return nok(code)
39366  }
39367  /** @type {State} */
39368
39369  function cdataOpenInside(code) {
39370    if (code === buffer.charCodeAt(index++)) {
39371      effects.consume(code);
39372      return index === buffer.length
39373        ? self.interrupt
39374          ? ok
39375          : continuation
39376        : cdataOpenInside
39377    }
39378
39379    return nok(code)
39380  }
39381  /** @type {State} */
39382
39383  function tagCloseStart(code) {
39384    if (asciiAlpha(code)) {
39385      effects.consume(code);
39386      buffer = String.fromCharCode(code);
39387      return tagName
39388    }
39389
39390    return nok(code)
39391  }
39392  /** @type {State} */
39393
39394  function tagName(code) {
39395    if (
39396      code === null ||
39397      code === 47 ||
39398      code === 62 ||
39399      markdownLineEndingOrSpace(code)
39400    ) {
39401      if (
39402        code !== 47 &&
39403        startTag &&
39404        htmlRawNames.includes(buffer.toLowerCase())
39405      ) {
39406        kind = 1;
39407        return self.interrupt ? ok(code) : continuation(code)
39408      }
39409
39410      if (htmlBlockNames.includes(buffer.toLowerCase())) {
39411        kind = 6;
39412
39413        if (code === 47) {
39414          effects.consume(code);
39415          return basicSelfClosing
39416        }
39417
39418        return self.interrupt ? ok(code) : continuation(code)
39419      }
39420
39421      kind = 7; // Do not support complete HTML when interrupting
39422
39423      return self.interrupt && !self.parser.lazy[self.now().line]
39424        ? nok(code)
39425        : startTag
39426        ? completeAttributeNameBefore(code)
39427        : completeClosingTagAfter(code)
39428    }
39429
39430    if (code === 45 || asciiAlphanumeric(code)) {
39431      effects.consume(code);
39432      buffer += String.fromCharCode(code);
39433      return tagName
39434    }
39435
39436    return nok(code)
39437  }
39438  /** @type {State} */
39439
39440  function basicSelfClosing(code) {
39441    if (code === 62) {
39442      effects.consume(code);
39443      return self.interrupt ? ok : continuation
39444    }
39445
39446    return nok(code)
39447  }
39448  /** @type {State} */
39449
39450  function completeClosingTagAfter(code) {
39451    if (markdownSpace(code)) {
39452      effects.consume(code);
39453      return completeClosingTagAfter
39454    }
39455
39456    return completeEnd(code)
39457  }
39458  /** @type {State} */
39459
39460  function completeAttributeNameBefore(code) {
39461    if (code === 47) {
39462      effects.consume(code);
39463      return completeEnd
39464    }
39465
39466    if (code === 58 || code === 95 || asciiAlpha(code)) {
39467      effects.consume(code);
39468      return completeAttributeName
39469    }
39470
39471    if (markdownSpace(code)) {
39472      effects.consume(code);
39473      return completeAttributeNameBefore
39474    }
39475
39476    return completeEnd(code)
39477  }
39478  /** @type {State} */
39479
39480  function completeAttributeName(code) {
39481    if (
39482      code === 45 ||
39483      code === 46 ||
39484      code === 58 ||
39485      code === 95 ||
39486      asciiAlphanumeric(code)
39487    ) {
39488      effects.consume(code);
39489      return completeAttributeName
39490    }
39491
39492    return completeAttributeNameAfter(code)
39493  }
39494  /** @type {State} */
39495
39496  function completeAttributeNameAfter(code) {
39497    if (code === 61) {
39498      effects.consume(code);
39499      return completeAttributeValueBefore
39500    }
39501
39502    if (markdownSpace(code)) {
39503      effects.consume(code);
39504      return completeAttributeNameAfter
39505    }
39506
39507    return completeAttributeNameBefore(code)
39508  }
39509  /** @type {State} */
39510
39511  function completeAttributeValueBefore(code) {
39512    if (
39513      code === null ||
39514      code === 60 ||
39515      code === 61 ||
39516      code === 62 ||
39517      code === 96
39518    ) {
39519      return nok(code)
39520    }
39521
39522    if (code === 34 || code === 39) {
39523      effects.consume(code);
39524      marker = code;
39525      return completeAttributeValueQuoted
39526    }
39527
39528    if (markdownSpace(code)) {
39529      effects.consume(code);
39530      return completeAttributeValueBefore
39531    }
39532
39533    marker = null;
39534    return completeAttributeValueUnquoted(code)
39535  }
39536  /** @type {State} */
39537
39538  function completeAttributeValueQuoted(code) {
39539    if (code === null || markdownLineEnding(code)) {
39540      return nok(code)
39541    }
39542
39543    if (code === marker) {
39544      effects.consume(code);
39545      return completeAttributeValueQuotedAfter
39546    }
39547
39548    effects.consume(code);
39549    return completeAttributeValueQuoted
39550  }
39551  /** @type {State} */
39552
39553  function completeAttributeValueUnquoted(code) {
39554    if (
39555      code === null ||
39556      code === 34 ||
39557      code === 39 ||
39558      code === 60 ||
39559      code === 61 ||
39560      code === 62 ||
39561      code === 96 ||
39562      markdownLineEndingOrSpace(code)
39563    ) {
39564      return completeAttributeNameAfter(code)
39565    }
39566
39567    effects.consume(code);
39568    return completeAttributeValueUnquoted
39569  }
39570  /** @type {State} */
39571
39572  function completeAttributeValueQuotedAfter(code) {
39573    if (code === 47 || code === 62 || markdownSpace(code)) {
39574      return completeAttributeNameBefore(code)
39575    }
39576
39577    return nok(code)
39578  }
39579  /** @type {State} */
39580
39581  function completeEnd(code) {
39582    if (code === 62) {
39583      effects.consume(code);
39584      return completeAfter
39585    }
39586
39587    return nok(code)
39588  }
39589  /** @type {State} */
39590
39591  function completeAfter(code) {
39592    if (markdownSpace(code)) {
39593      effects.consume(code);
39594      return completeAfter
39595    }
39596
39597    return code === null || markdownLineEnding(code)
39598      ? continuation(code)
39599      : nok(code)
39600  }
39601  /** @type {State} */
39602
39603  function continuation(code) {
39604    if (code === 45 && kind === 2) {
39605      effects.consume(code);
39606      return continuationCommentInside
39607    }
39608
39609    if (code === 60 && kind === 1) {
39610      effects.consume(code);
39611      return continuationRawTagOpen
39612    }
39613
39614    if (code === 62 && kind === 4) {
39615      effects.consume(code);
39616      return continuationClose
39617    }
39618
39619    if (code === 63 && kind === 3) {
39620      effects.consume(code);
39621      return continuationDeclarationInside
39622    }
39623
39624    if (code === 93 && kind === 5) {
39625      effects.consume(code);
39626      return continuationCharacterDataInside
39627    }
39628
39629    if (markdownLineEnding(code) && (kind === 6 || kind === 7)) {
39630      return effects.check(
39631        nextBlankConstruct,
39632        continuationClose,
39633        continuationAtLineEnding
39634      )(code)
39635    }
39636
39637    if (code === null || markdownLineEnding(code)) {
39638      return continuationAtLineEnding(code)
39639    }
39640
39641    effects.consume(code);
39642    return continuation
39643  }
39644  /** @type {State} */
39645
39646  function continuationAtLineEnding(code) {
39647    effects.exit('htmlFlowData');
39648    return htmlContinueStart(code)
39649  }
39650  /** @type {State} */
39651
39652  function htmlContinueStart(code) {
39653    if (code === null) {
39654      return done(code)
39655    }
39656
39657    if (markdownLineEnding(code)) {
39658      return effects.attempt(
39659        {
39660          tokenize: htmlLineEnd,
39661          partial: true
39662        },
39663        htmlContinueStart,
39664        done
39665      )(code)
39666    }
39667
39668    effects.enter('htmlFlowData');
39669    return continuation(code)
39670  }
39671  /** @type {Tokenizer} */
39672
39673  function htmlLineEnd(effects, ok, nok) {
39674    return start
39675    /** @type {State} */
39676
39677    function start(code) {
39678      effects.enter('lineEnding');
39679      effects.consume(code);
39680      effects.exit('lineEnding');
39681      return lineStart
39682    }
39683    /** @type {State} */
39684
39685    function lineStart(code) {
39686      return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
39687    }
39688  }
39689  /** @type {State} */
39690
39691  function continuationCommentInside(code) {
39692    if (code === 45) {
39693      effects.consume(code);
39694      return continuationDeclarationInside
39695    }
39696
39697    return continuation(code)
39698  }
39699  /** @type {State} */
39700
39701  function continuationRawTagOpen(code) {
39702    if (code === 47) {
39703      effects.consume(code);
39704      buffer = '';
39705      return continuationRawEndTag
39706    }
39707
39708    return continuation(code)
39709  }
39710  /** @type {State} */
39711
39712  function continuationRawEndTag(code) {
39713    if (code === 62 && htmlRawNames.includes(buffer.toLowerCase())) {
39714      effects.consume(code);
39715      return continuationClose
39716    }
39717
39718    if (asciiAlpha(code) && buffer.length < 8) {
39719      effects.consume(code);
39720      buffer += String.fromCharCode(code);
39721      return continuationRawEndTag
39722    }
39723
39724    return continuation(code)
39725  }
39726  /** @type {State} */
39727
39728  function continuationCharacterDataInside(code) {
39729    if (code === 93) {
39730      effects.consume(code);
39731      return continuationDeclarationInside
39732    }
39733
39734    return continuation(code)
39735  }
39736  /** @type {State} */
39737
39738  function continuationDeclarationInside(code) {
39739    if (code === 62) {
39740      effects.consume(code);
39741      return continuationClose
39742    }
39743
39744    return continuation(code)
39745  }
39746  /** @type {State} */
39747
39748  function continuationClose(code) {
39749    if (code === null || markdownLineEnding(code)) {
39750      effects.exit('htmlFlowData');
39751      return done(code)
39752    }
39753
39754    effects.consume(code);
39755    return continuationClose
39756  }
39757  /** @type {State} */
39758
39759  function done(code) {
39760    effects.exit('htmlFlow');
39761    return ok(code)
39762  }
39763}
39764/** @type {Tokenizer} */
39765
39766function tokenizeNextBlank(effects, ok, nok) {
39767  return start
39768  /** @type {State} */
39769
39770  function start(code) {
39771    effects.exit('htmlFlowData');
39772    effects.enter('lineEndingBlank');
39773    effects.consume(code);
39774    effects.exit('lineEndingBlank');
39775    return effects.attempt(blankLine, ok, nok)
39776  }
39777}
39778
39779/**
39780 * @typedef {import('micromark-util-types').Construct} Construct
39781 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
39782 * @typedef {import('micromark-util-types').State} State
39783 * @typedef {import('micromark-util-types').Code} Code
39784 */
39785
39786/** @type {Construct} */
39787const htmlText = {
39788  name: 'htmlText',
39789  tokenize: tokenizeHtmlText
39790};
39791/** @type {Tokenizer} */
39792
39793function tokenizeHtmlText(effects, ok, nok) {
39794  const self = this;
39795  /** @type {NonNullable<Code>|undefined} */
39796
39797  let marker;
39798  /** @type {string} */
39799
39800  let buffer;
39801  /** @type {number} */
39802
39803  let index;
39804  /** @type {State} */
39805
39806  let returnState;
39807  return start
39808  /** @type {State} */
39809
39810  function start(code) {
39811    effects.enter('htmlText');
39812    effects.enter('htmlTextData');
39813    effects.consume(code);
39814    return open
39815  }
39816  /** @type {State} */
39817
39818  function open(code) {
39819    if (code === 33) {
39820      effects.consume(code);
39821      return declarationOpen
39822    }
39823
39824    if (code === 47) {
39825      effects.consume(code);
39826      return tagCloseStart
39827    }
39828
39829    if (code === 63) {
39830      effects.consume(code);
39831      return instruction
39832    }
39833
39834    if (asciiAlpha(code)) {
39835      effects.consume(code);
39836      return tagOpen
39837    }
39838
39839    return nok(code)
39840  }
39841  /** @type {State} */
39842
39843  function declarationOpen(code) {
39844    if (code === 45) {
39845      effects.consume(code);
39846      return commentOpen
39847    }
39848
39849    if (code === 91) {
39850      effects.consume(code);
39851      buffer = 'CDATA[';
39852      index = 0;
39853      return cdataOpen
39854    }
39855
39856    if (asciiAlpha(code)) {
39857      effects.consume(code);
39858      return declaration
39859    }
39860
39861    return nok(code)
39862  }
39863  /** @type {State} */
39864
39865  function commentOpen(code) {
39866    if (code === 45) {
39867      effects.consume(code);
39868      return commentStart
39869    }
39870
39871    return nok(code)
39872  }
39873  /** @type {State} */
39874
39875  function commentStart(code) {
39876    if (code === null || code === 62) {
39877      return nok(code)
39878    }
39879
39880    if (code === 45) {
39881      effects.consume(code);
39882      return commentStartDash
39883    }
39884
39885    return comment(code)
39886  }
39887  /** @type {State} */
39888
39889  function commentStartDash(code) {
39890    if (code === null || code === 62) {
39891      return nok(code)
39892    }
39893
39894    return comment(code)
39895  }
39896  /** @type {State} */
39897
39898  function comment(code) {
39899    if (code === null) {
39900      return nok(code)
39901    }
39902
39903    if (code === 45) {
39904      effects.consume(code);
39905      return commentClose
39906    }
39907
39908    if (markdownLineEnding(code)) {
39909      returnState = comment;
39910      return atLineEnding(code)
39911    }
39912
39913    effects.consume(code);
39914    return comment
39915  }
39916  /** @type {State} */
39917
39918  function commentClose(code) {
39919    if (code === 45) {
39920      effects.consume(code);
39921      return end
39922    }
39923
39924    return comment(code)
39925  }
39926  /** @type {State} */
39927
39928  function cdataOpen(code) {
39929    if (code === buffer.charCodeAt(index++)) {
39930      effects.consume(code);
39931      return index === buffer.length ? cdata : cdataOpen
39932    }
39933
39934    return nok(code)
39935  }
39936  /** @type {State} */
39937
39938  function cdata(code) {
39939    if (code === null) {
39940      return nok(code)
39941    }
39942
39943    if (code === 93) {
39944      effects.consume(code);
39945      return cdataClose
39946    }
39947
39948    if (markdownLineEnding(code)) {
39949      returnState = cdata;
39950      return atLineEnding(code)
39951    }
39952
39953    effects.consume(code);
39954    return cdata
39955  }
39956  /** @type {State} */
39957
39958  function cdataClose(code) {
39959    if (code === 93) {
39960      effects.consume(code);
39961      return cdataEnd
39962    }
39963
39964    return cdata(code)
39965  }
39966  /** @type {State} */
39967
39968  function cdataEnd(code) {
39969    if (code === 62) {
39970      return end(code)
39971    }
39972
39973    if (code === 93) {
39974      effects.consume(code);
39975      return cdataEnd
39976    }
39977
39978    return cdata(code)
39979  }
39980  /** @type {State} */
39981
39982  function declaration(code) {
39983    if (code === null || code === 62) {
39984      return end(code)
39985    }
39986
39987    if (markdownLineEnding(code)) {
39988      returnState = declaration;
39989      return atLineEnding(code)
39990    }
39991
39992    effects.consume(code);
39993    return declaration
39994  }
39995  /** @type {State} */
39996
39997  function instruction(code) {
39998    if (code === null) {
39999      return nok(code)
40000    }
40001
40002    if (code === 63) {
40003      effects.consume(code);
40004      return instructionClose
40005    }
40006
40007    if (markdownLineEnding(code)) {
40008      returnState = instruction;
40009      return atLineEnding(code)
40010    }
40011
40012    effects.consume(code);
40013    return instruction
40014  }
40015  /** @type {State} */
40016
40017  function instructionClose(code) {
40018    return code === 62 ? end(code) : instruction(code)
40019  }
40020  /** @type {State} */
40021
40022  function tagCloseStart(code) {
40023    if (asciiAlpha(code)) {
40024      effects.consume(code);
40025      return tagClose
40026    }
40027
40028    return nok(code)
40029  }
40030  /** @type {State} */
40031
40032  function tagClose(code) {
40033    if (code === 45 || asciiAlphanumeric(code)) {
40034      effects.consume(code);
40035      return tagClose
40036    }
40037
40038    return tagCloseBetween(code)
40039  }
40040  /** @type {State} */
40041
40042  function tagCloseBetween(code) {
40043    if (markdownLineEnding(code)) {
40044      returnState = tagCloseBetween;
40045      return atLineEnding(code)
40046    }
40047
40048    if (markdownSpace(code)) {
40049      effects.consume(code);
40050      return tagCloseBetween
40051    }
40052
40053    return end(code)
40054  }
40055  /** @type {State} */
40056
40057  function tagOpen(code) {
40058    if (code === 45 || asciiAlphanumeric(code)) {
40059      effects.consume(code);
40060      return tagOpen
40061    }
40062
40063    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {
40064      return tagOpenBetween(code)
40065    }
40066
40067    return nok(code)
40068  }
40069  /** @type {State} */
40070
40071  function tagOpenBetween(code) {
40072    if (code === 47) {
40073      effects.consume(code);
40074      return end
40075    }
40076
40077    if (code === 58 || code === 95 || asciiAlpha(code)) {
40078      effects.consume(code);
40079      return tagOpenAttributeName
40080    }
40081
40082    if (markdownLineEnding(code)) {
40083      returnState = tagOpenBetween;
40084      return atLineEnding(code)
40085    }
40086
40087    if (markdownSpace(code)) {
40088      effects.consume(code);
40089      return tagOpenBetween
40090    }
40091
40092    return end(code)
40093  }
40094  /** @type {State} */
40095
40096  function tagOpenAttributeName(code) {
40097    if (
40098      code === 45 ||
40099      code === 46 ||
40100      code === 58 ||
40101      code === 95 ||
40102      asciiAlphanumeric(code)
40103    ) {
40104      effects.consume(code);
40105      return tagOpenAttributeName
40106    }
40107
40108    return tagOpenAttributeNameAfter(code)
40109  }
40110  /** @type {State} */
40111
40112  function tagOpenAttributeNameAfter(code) {
40113    if (code === 61) {
40114      effects.consume(code);
40115      return tagOpenAttributeValueBefore
40116    }
40117
40118    if (markdownLineEnding(code)) {
40119      returnState = tagOpenAttributeNameAfter;
40120      return atLineEnding(code)
40121    }
40122
40123    if (markdownSpace(code)) {
40124      effects.consume(code);
40125      return tagOpenAttributeNameAfter
40126    }
40127
40128    return tagOpenBetween(code)
40129  }
40130  /** @type {State} */
40131
40132  function tagOpenAttributeValueBefore(code) {
40133    if (
40134      code === null ||
40135      code === 60 ||
40136      code === 61 ||
40137      code === 62 ||
40138      code === 96
40139    ) {
40140      return nok(code)
40141    }
40142
40143    if (code === 34 || code === 39) {
40144      effects.consume(code);
40145      marker = code;
40146      return tagOpenAttributeValueQuoted
40147    }
40148
40149    if (markdownLineEnding(code)) {
40150      returnState = tagOpenAttributeValueBefore;
40151      return atLineEnding(code)
40152    }
40153
40154    if (markdownSpace(code)) {
40155      effects.consume(code);
40156      return tagOpenAttributeValueBefore
40157    }
40158
40159    effects.consume(code);
40160    marker = undefined;
40161    return tagOpenAttributeValueUnquoted
40162  }
40163  /** @type {State} */
40164
40165  function tagOpenAttributeValueQuoted(code) {
40166    if (code === marker) {
40167      effects.consume(code);
40168      return tagOpenAttributeValueQuotedAfter
40169    }
40170
40171    if (code === null) {
40172      return nok(code)
40173    }
40174
40175    if (markdownLineEnding(code)) {
40176      returnState = tagOpenAttributeValueQuoted;
40177      return atLineEnding(code)
40178    }
40179
40180    effects.consume(code);
40181    return tagOpenAttributeValueQuoted
40182  }
40183  /** @type {State} */
40184
40185  function tagOpenAttributeValueQuotedAfter(code) {
40186    if (code === 62 || code === 47 || markdownLineEndingOrSpace(code)) {
40187      return tagOpenBetween(code)
40188    }
40189
40190    return nok(code)
40191  }
40192  /** @type {State} */
40193
40194  function tagOpenAttributeValueUnquoted(code) {
40195    if (
40196      code === null ||
40197      code === 34 ||
40198      code === 39 ||
40199      code === 60 ||
40200      code === 61 ||
40201      code === 96
40202    ) {
40203      return nok(code)
40204    }
40205
40206    if (code === 62 || markdownLineEndingOrSpace(code)) {
40207      return tagOpenBetween(code)
40208    }
40209
40210    effects.consume(code);
40211    return tagOpenAttributeValueUnquoted
40212  } // We can’t have blank lines in content, so no need to worry about empty
40213  // tokens.
40214
40215  /** @type {State} */
40216
40217  function atLineEnding(code) {
40218    effects.exit('htmlTextData');
40219    effects.enter('lineEnding');
40220    effects.consume(code);
40221    effects.exit('lineEnding');
40222    return factorySpace(
40223      effects,
40224      afterPrefix,
40225      'linePrefix',
40226      self.parser.constructs.disable.null.includes('codeIndented')
40227        ? undefined
40228        : 4
40229    )
40230  }
40231  /** @type {State} */
40232
40233  function afterPrefix(code) {
40234    effects.enter('htmlTextData');
40235    return returnState(code)
40236  }
40237  /** @type {State} */
40238
40239  function end(code) {
40240    if (code === 62) {
40241      effects.consume(code);
40242      effects.exit('htmlTextData');
40243      effects.exit('htmlText');
40244      return ok
40245    }
40246
40247    return nok(code)
40248  }
40249}
40250
40251/**
40252 * @typedef {import('micromark-util-types').Construct} Construct
40253 * @typedef {import('micromark-util-types').Resolver} Resolver
40254 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40255 * @typedef {import('micromark-util-types').Event} Event
40256 * @typedef {import('micromark-util-types').Token} Token
40257 * @typedef {import('micromark-util-types').State} State
40258 * @typedef {import('micromark-util-types').Code} Code
40259 */
40260
40261/** @type {Construct} */
40262const labelEnd = {
40263  name: 'labelEnd',
40264  tokenize: tokenizeLabelEnd,
40265  resolveTo: resolveToLabelEnd,
40266  resolveAll: resolveAllLabelEnd
40267};
40268/** @type {Construct} */
40269
40270const resourceConstruct = {
40271  tokenize: tokenizeResource
40272};
40273/** @type {Construct} */
40274
40275const fullReferenceConstruct = {
40276  tokenize: tokenizeFullReference
40277};
40278/** @type {Construct} */
40279
40280const collapsedReferenceConstruct = {
40281  tokenize: tokenizeCollapsedReference
40282};
40283/** @type {Resolver} */
40284
40285function resolveAllLabelEnd(events) {
40286  let index = -1;
40287  /** @type {Token} */
40288
40289  let token;
40290
40291  while (++index < events.length) {
40292    token = events[index][1];
40293
40294    if (
40295      token.type === 'labelImage' ||
40296      token.type === 'labelLink' ||
40297      token.type === 'labelEnd'
40298    ) {
40299      // Remove the marker.
40300      events.splice(index + 1, token.type === 'labelImage' ? 4 : 2);
40301      token.type = 'data';
40302      index++;
40303    }
40304  }
40305
40306  return events
40307}
40308/** @type {Resolver} */
40309
40310function resolveToLabelEnd(events, context) {
40311  let index = events.length;
40312  let offset = 0;
40313  /** @type {Token} */
40314
40315  let token;
40316  /** @type {number|undefined} */
40317
40318  let open;
40319  /** @type {number|undefined} */
40320
40321  let close;
40322  /** @type {Event[]} */
40323
40324  let media; // Find an opening.
40325
40326  while (index--) {
40327    token = events[index][1];
40328
40329    if (open) {
40330      // If we see another link, or inactive link label, we’ve been here before.
40331      if (
40332        token.type === 'link' ||
40333        (token.type === 'labelLink' && token._inactive)
40334      ) {
40335        break
40336      } // Mark other link openings as inactive, as we can’t have links in
40337      // links.
40338
40339      if (events[index][0] === 'enter' && token.type === 'labelLink') {
40340        token._inactive = true;
40341      }
40342    } else if (close) {
40343      if (
40344        events[index][0] === 'enter' &&
40345        (token.type === 'labelImage' || token.type === 'labelLink') &&
40346        !token._balanced
40347      ) {
40348        open = index;
40349
40350        if (token.type !== 'labelLink') {
40351          offset = 2;
40352          break
40353        }
40354      }
40355    } else if (token.type === 'labelEnd') {
40356      close = index;
40357    }
40358  }
40359
40360  const group = {
40361    type: events[open][1].type === 'labelLink' ? 'link' : 'image',
40362    start: Object.assign({}, events[open][1].start),
40363    end: Object.assign({}, events[events.length - 1][1].end)
40364  };
40365  const label = {
40366    type: 'label',
40367    start: Object.assign({}, events[open][1].start),
40368    end: Object.assign({}, events[close][1].end)
40369  };
40370  const text = {
40371    type: 'labelText',
40372    start: Object.assign({}, events[open + offset + 2][1].end),
40373    end: Object.assign({}, events[close - 2][1].start)
40374  };
40375  media = [
40376    ['enter', group, context],
40377    ['enter', label, context]
40378  ]; // Opening marker.
40379
40380  media = push(media, events.slice(open + 1, open + offset + 3)); // Text open.
40381
40382  media = push(media, [['enter', text, context]]); // Between.
40383
40384  media = push(
40385    media,
40386    resolveAll(
40387      context.parser.constructs.insideSpan.null,
40388      events.slice(open + offset + 4, close - 3),
40389      context
40390    )
40391  ); // Text close, marker close, label close.
40392
40393  media = push(media, [
40394    ['exit', text, context],
40395    events[close - 2],
40396    events[close - 1],
40397    ['exit', label, context]
40398  ]); // Reference, resource, or so.
40399
40400  media = push(media, events.slice(close + 1)); // Media close.
40401
40402  media = push(media, [['exit', group, context]]);
40403  splice(events, open, events.length, media);
40404  return events
40405}
40406/** @type {Tokenizer} */
40407
40408function tokenizeLabelEnd(effects, ok, nok) {
40409  const self = this;
40410  let index = self.events.length;
40411  /** @type {Token} */
40412
40413  let labelStart;
40414  /** @type {boolean} */
40415
40416  let defined; // Find an opening.
40417
40418  while (index--) {
40419    if (
40420      (self.events[index][1].type === 'labelImage' ||
40421        self.events[index][1].type === 'labelLink') &&
40422      !self.events[index][1]._balanced
40423    ) {
40424      labelStart = self.events[index][1];
40425      break
40426    }
40427  }
40428
40429  return start
40430  /** @type {State} */
40431
40432  function start(code) {
40433    if (!labelStart) {
40434      return nok(code)
40435    } // It’s a balanced bracket, but contains a link.
40436
40437    if (labelStart._inactive) return balanced(code)
40438    defined = self.parser.defined.includes(
40439      normalizeIdentifier(
40440        self.sliceSerialize({
40441          start: labelStart.end,
40442          end: self.now()
40443        })
40444      )
40445    );
40446    effects.enter('labelEnd');
40447    effects.enter('labelMarker');
40448    effects.consume(code);
40449    effects.exit('labelMarker');
40450    effects.exit('labelEnd');
40451    return afterLabelEnd
40452  }
40453  /** @type {State} */
40454
40455  function afterLabelEnd(code) {
40456    // Resource: `[asd](fgh)`.
40457    if (code === 40) {
40458      return effects.attempt(
40459        resourceConstruct,
40460        ok,
40461        defined ? ok : balanced
40462      )(code)
40463    } // Collapsed (`[asd][]`) or full (`[asd][fgh]`) reference?
40464
40465    if (code === 91) {
40466      return effects.attempt(
40467        fullReferenceConstruct,
40468        ok,
40469        defined
40470          ? effects.attempt(collapsedReferenceConstruct, ok, balanced)
40471          : balanced
40472      )(code)
40473    } // Shortcut reference: `[asd]`?
40474
40475    return defined ? ok(code) : balanced(code)
40476  }
40477  /** @type {State} */
40478
40479  function balanced(code) {
40480    labelStart._balanced = true;
40481    return nok(code)
40482  }
40483}
40484/** @type {Tokenizer} */
40485
40486function tokenizeResource(effects, ok, nok) {
40487  return start
40488  /** @type {State} */
40489
40490  function start(code) {
40491    effects.enter('resource');
40492    effects.enter('resourceMarker');
40493    effects.consume(code);
40494    effects.exit('resourceMarker');
40495    return factoryWhitespace(effects, open)
40496  }
40497  /** @type {State} */
40498
40499  function open(code) {
40500    if (code === 41) {
40501      return end(code)
40502    }
40503
40504    return factoryDestination(
40505      effects,
40506      destinationAfter,
40507      nok,
40508      'resourceDestination',
40509      'resourceDestinationLiteral',
40510      'resourceDestinationLiteralMarker',
40511      'resourceDestinationRaw',
40512      'resourceDestinationString',
40513      3
40514    )(code)
40515  }
40516  /** @type {State} */
40517
40518  function destinationAfter(code) {
40519    return markdownLineEndingOrSpace(code)
40520      ? factoryWhitespace(effects, between)(code)
40521      : end(code)
40522  }
40523  /** @type {State} */
40524
40525  function between(code) {
40526    if (code === 34 || code === 39 || code === 40) {
40527      return factoryTitle(
40528        effects,
40529        factoryWhitespace(effects, end),
40530        nok,
40531        'resourceTitle',
40532        'resourceTitleMarker',
40533        'resourceTitleString'
40534      )(code)
40535    }
40536
40537    return end(code)
40538  }
40539  /** @type {State} */
40540
40541  function end(code) {
40542    if (code === 41) {
40543      effects.enter('resourceMarker');
40544      effects.consume(code);
40545      effects.exit('resourceMarker');
40546      effects.exit('resource');
40547      return ok
40548    }
40549
40550    return nok(code)
40551  }
40552}
40553/** @type {Tokenizer} */
40554
40555function tokenizeFullReference(effects, ok, nok) {
40556  const self = this;
40557  return start
40558  /** @type {State} */
40559
40560  function start(code) {
40561    return factoryLabel.call(
40562      self,
40563      effects,
40564      afterLabel,
40565      nok,
40566      'reference',
40567      'referenceMarker',
40568      'referenceString'
40569    )(code)
40570  }
40571  /** @type {State} */
40572
40573  function afterLabel(code) {
40574    return self.parser.defined.includes(
40575      normalizeIdentifier(
40576        self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1)
40577      )
40578    )
40579      ? ok(code)
40580      : nok(code)
40581  }
40582}
40583/** @type {Tokenizer} */
40584
40585function tokenizeCollapsedReference(effects, ok, nok) {
40586  return start
40587  /** @type {State} */
40588
40589  function start(code) {
40590    effects.enter('reference');
40591    effects.enter('referenceMarker');
40592    effects.consume(code);
40593    effects.exit('referenceMarker');
40594    return open
40595  }
40596  /** @type {State} */
40597
40598  function open(code) {
40599    if (code === 93) {
40600      effects.enter('referenceMarker');
40601      effects.consume(code);
40602      effects.exit('referenceMarker');
40603      effects.exit('reference');
40604      return ok
40605    }
40606
40607    return nok(code)
40608  }
40609}
40610
40611/**
40612 * @typedef {import('micromark-util-types').Construct} Construct
40613 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40614 * @typedef {import('micromark-util-types').State} State
40615 */
40616/** @type {Construct} */
40617
40618const labelStartImage = {
40619  name: 'labelStartImage',
40620  tokenize: tokenizeLabelStartImage,
40621  resolveAll: labelEnd.resolveAll
40622};
40623/** @type {Tokenizer} */
40624
40625function tokenizeLabelStartImage(effects, ok, nok) {
40626  const self = this;
40627  return start
40628  /** @type {State} */
40629
40630  function start(code) {
40631    effects.enter('labelImage');
40632    effects.enter('labelImageMarker');
40633    effects.consume(code);
40634    effects.exit('labelImageMarker');
40635    return open
40636  }
40637  /** @type {State} */
40638
40639  function open(code) {
40640    if (code === 91) {
40641      effects.enter('labelMarker');
40642      effects.consume(code);
40643      effects.exit('labelMarker');
40644      effects.exit('labelImage');
40645      return after
40646    }
40647
40648    return nok(code)
40649  }
40650  /** @type {State} */
40651
40652  function after(code) {
40653    /* Hidden footnotes hook */
40654
40655    /* c8 ignore next 3 */
40656    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs
40657      ? nok(code)
40658      : ok(code)
40659  }
40660}
40661
40662/**
40663 * @typedef {import('micromark-util-types').Construct} Construct
40664 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40665 * @typedef {import('micromark-util-types').State} State
40666 */
40667/** @type {Construct} */
40668
40669const labelStartLink = {
40670  name: 'labelStartLink',
40671  tokenize: tokenizeLabelStartLink,
40672  resolveAll: labelEnd.resolveAll
40673};
40674/** @type {Tokenizer} */
40675
40676function tokenizeLabelStartLink(effects, ok, nok) {
40677  const self = this;
40678  return start
40679  /** @type {State} */
40680
40681  function start(code) {
40682    effects.enter('labelLink');
40683    effects.enter('labelMarker');
40684    effects.consume(code);
40685    effects.exit('labelMarker');
40686    effects.exit('labelLink');
40687    return after
40688  }
40689  /** @type {State} */
40690
40691  function after(code) {
40692    /* Hidden footnotes hook. */
40693
40694    /* c8 ignore next 3 */
40695    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs
40696      ? nok(code)
40697      : ok(code)
40698  }
40699}
40700
40701/**
40702 * @typedef {import('micromark-util-types').Construct} Construct
40703 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40704 * @typedef {import('micromark-util-types').State} State
40705 */
40706
40707/** @type {Construct} */
40708const lineEnding = {
40709  name: 'lineEnding',
40710  tokenize: tokenizeLineEnding
40711};
40712/** @type {Tokenizer} */
40713
40714function tokenizeLineEnding(effects, ok) {
40715  return start
40716  /** @type {State} */
40717
40718  function start(code) {
40719    effects.enter('lineEnding');
40720    effects.consume(code);
40721    effects.exit('lineEnding');
40722    return factorySpace(effects, ok, 'linePrefix')
40723  }
40724}
40725
40726/**
40727 * @typedef {import('micromark-util-types').Construct} Construct
40728 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40729 * @typedef {import('micromark-util-types').State} State
40730 * @typedef {import('micromark-util-types').Code} Code
40731 */
40732
40733/** @type {Construct} */
40734const thematicBreak$1 = {
40735  name: 'thematicBreak',
40736  tokenize: tokenizeThematicBreak
40737};
40738/** @type {Tokenizer} */
40739
40740function tokenizeThematicBreak(effects, ok, nok) {
40741  let size = 0;
40742  /** @type {NonNullable<Code>} */
40743
40744  let marker;
40745  return start
40746  /** @type {State} */
40747
40748  function start(code) {
40749    effects.enter('thematicBreak');
40750    marker = code;
40751    return atBreak(code)
40752  }
40753  /** @type {State} */
40754
40755  function atBreak(code) {
40756    if (code === marker) {
40757      effects.enter('thematicBreakSequence');
40758      return sequence(code)
40759    }
40760
40761    if (markdownSpace(code)) {
40762      return factorySpace(effects, atBreak, 'whitespace')(code)
40763    }
40764
40765    if (size < 3 || (code !== null && !markdownLineEnding(code))) {
40766      return nok(code)
40767    }
40768
40769    effects.exit('thematicBreak');
40770    return ok(code)
40771  }
40772  /** @type {State} */
40773
40774  function sequence(code) {
40775    if (code === marker) {
40776      effects.consume(code);
40777      size++;
40778      return sequence
40779    }
40780
40781    effects.exit('thematicBreakSequence');
40782    return atBreak(code)
40783  }
40784}
40785
40786/**
40787 * @typedef {import('micromark-util-types').Construct} Construct
40788 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
40789 * @typedef {import('micromark-util-types').Exiter} Exiter
40790 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
40791 * @typedef {import('micromark-util-types').State} State
40792 * @typedef {import('micromark-util-types').Code} Code
40793 */
40794/** @type {Construct} */
40795
40796const list$1 = {
40797  name: 'list',
40798  tokenize: tokenizeListStart,
40799  continuation: {
40800    tokenize: tokenizeListContinuation
40801  },
40802  exit: tokenizeListEnd
40803};
40804/** @type {Construct} */
40805
40806const listItemPrefixWhitespaceConstruct = {
40807  tokenize: tokenizeListItemPrefixWhitespace,
40808  partial: true
40809};
40810/** @type {Construct} */
40811
40812const indentConstruct = {
40813  tokenize: tokenizeIndent,
40814  partial: true
40815};
40816/**
40817 * @type {Tokenizer}
40818 * @this {TokenizeContextWithState}
40819 */
40820
40821function tokenizeListStart(effects, ok, nok) {
40822  const self = this;
40823  const tail = self.events[self.events.length - 1];
40824  let initialSize =
40825    tail && tail[1].type === 'linePrefix'
40826      ? tail[2].sliceSerialize(tail[1], true).length
40827      : 0;
40828  let size = 0;
40829  return start
40830  /** @type {State} */
40831
40832  function start(code) {
40833    const kind =
40834      self.containerState.type ||
40835      (code === 42 || code === 43 || code === 45
40836        ? 'listUnordered'
40837        : 'listOrdered');
40838
40839    if (
40840      kind === 'listUnordered'
40841        ? !self.containerState.marker || code === self.containerState.marker
40842        : asciiDigit(code)
40843    ) {
40844      if (!self.containerState.type) {
40845        self.containerState.type = kind;
40846        effects.enter(kind, {
40847          _container: true
40848        });
40849      }
40850
40851      if (kind === 'listUnordered') {
40852        effects.enter('listItemPrefix');
40853        return code === 42 || code === 45
40854          ? effects.check(thematicBreak$1, nok, atMarker)(code)
40855          : atMarker(code)
40856      }
40857
40858      if (!self.interrupt || code === 49) {
40859        effects.enter('listItemPrefix');
40860        effects.enter('listItemValue');
40861        return inside(code)
40862      }
40863    }
40864
40865    return nok(code)
40866  }
40867  /** @type {State} */
40868
40869  function inside(code) {
40870    if (asciiDigit(code) && ++size < 10) {
40871      effects.consume(code);
40872      return inside
40873    }
40874
40875    if (
40876      (!self.interrupt || size < 2) &&
40877      (self.containerState.marker
40878        ? code === self.containerState.marker
40879        : code === 41 || code === 46)
40880    ) {
40881      effects.exit('listItemValue');
40882      return atMarker(code)
40883    }
40884
40885    return nok(code)
40886  }
40887  /**
40888   * @type {State}
40889   **/
40890
40891  function atMarker(code) {
40892    effects.enter('listItemMarker');
40893    effects.consume(code);
40894    effects.exit('listItemMarker');
40895    self.containerState.marker = self.containerState.marker || code;
40896    return effects.check(
40897      blankLine, // Can’t be empty when interrupting.
40898      self.interrupt ? nok : onBlank,
40899      effects.attempt(
40900        listItemPrefixWhitespaceConstruct,
40901        endOfPrefix,
40902        otherPrefix
40903      )
40904    )
40905  }
40906  /** @type {State} */
40907
40908  function onBlank(code) {
40909    self.containerState.initialBlankLine = true;
40910    initialSize++;
40911    return endOfPrefix(code)
40912  }
40913  /** @type {State} */
40914
40915  function otherPrefix(code) {
40916    if (markdownSpace(code)) {
40917      effects.enter('listItemPrefixWhitespace');
40918      effects.consume(code);
40919      effects.exit('listItemPrefixWhitespace');
40920      return endOfPrefix
40921    }
40922
40923    return nok(code)
40924  }
40925  /** @type {State} */
40926
40927  function endOfPrefix(code) {
40928    self.containerState.size =
40929      initialSize +
40930      self.sliceSerialize(effects.exit('listItemPrefix'), true).length;
40931    return ok(code)
40932  }
40933}
40934/**
40935 * @type {Tokenizer}
40936 * @this {TokenizeContextWithState}
40937 */
40938
40939function tokenizeListContinuation(effects, ok, nok) {
40940  const self = this;
40941  self.containerState._closeFlow = undefined;
40942  return effects.check(blankLine, onBlank, notBlank)
40943  /** @type {State} */
40944
40945  function onBlank(code) {
40946    self.containerState.furtherBlankLines =
40947      self.containerState.furtherBlankLines ||
40948      self.containerState.initialBlankLine; // We have a blank line.
40949    // Still, try to consume at most the items size.
40950
40951    return factorySpace(
40952      effects,
40953      ok,
40954      'listItemIndent',
40955      self.containerState.size + 1
40956    )(code)
40957  }
40958  /** @type {State} */
40959
40960  function notBlank(code) {
40961    if (self.containerState.furtherBlankLines || !markdownSpace(code)) {
40962      self.containerState.furtherBlankLines = undefined;
40963      self.containerState.initialBlankLine = undefined;
40964      return notInCurrentItem(code)
40965    }
40966
40967    self.containerState.furtherBlankLines = undefined;
40968    self.containerState.initialBlankLine = undefined;
40969    return effects.attempt(indentConstruct, ok, notInCurrentItem)(code)
40970  }
40971  /** @type {State} */
40972
40973  function notInCurrentItem(code) {
40974    // While we do continue, we signal that the flow should be closed.
40975    self.containerState._closeFlow = true; // As we’re closing flow, we’re no longer interrupting.
40976
40977    self.interrupt = undefined;
40978    return factorySpace(
40979      effects,
40980      effects.attempt(list$1, ok, nok),
40981      'linePrefix',
40982      self.parser.constructs.disable.null.includes('codeIndented')
40983        ? undefined
40984        : 4
40985    )(code)
40986  }
40987}
40988/**
40989 * @type {Tokenizer}
40990 * @this {TokenizeContextWithState}
40991 */
40992
40993function tokenizeIndent(effects, ok, nok) {
40994  const self = this;
40995  return factorySpace(
40996    effects,
40997    afterPrefix,
40998    'listItemIndent',
40999    self.containerState.size + 1
41000  )
41001  /** @type {State} */
41002
41003  function afterPrefix(code) {
41004    const tail = self.events[self.events.length - 1];
41005    return tail &&
41006      tail[1].type === 'listItemIndent' &&
41007      tail[2].sliceSerialize(tail[1], true).length === self.containerState.size
41008      ? ok(code)
41009      : nok(code)
41010  }
41011}
41012/**
41013 * @type {Exiter}
41014 * @this {TokenizeContextWithState}
41015 */
41016
41017function tokenizeListEnd(effects) {
41018  effects.exit(this.containerState.type);
41019}
41020/**
41021 * @type {Tokenizer}
41022 * @this {TokenizeContextWithState}
41023 */
41024
41025function tokenizeListItemPrefixWhitespace(effects, ok, nok) {
41026  const self = this;
41027  return factorySpace(
41028    effects,
41029    afterPrefix,
41030    'listItemPrefixWhitespace',
41031    self.parser.constructs.disable.null.includes('codeIndented')
41032      ? undefined
41033      : 4 + 1
41034  )
41035  /** @type {State} */
41036
41037  function afterPrefix(code) {
41038    const tail = self.events[self.events.length - 1];
41039    return !markdownSpace(code) &&
41040      tail &&
41041      tail[1].type === 'listItemPrefixWhitespace'
41042      ? ok(code)
41043      : nok(code)
41044  }
41045}
41046
41047/**
41048 * @typedef {import('micromark-util-types').Construct} Construct
41049 * @typedef {import('micromark-util-types').Resolver} Resolver
41050 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
41051 * @typedef {import('micromark-util-types').State} State
41052 * @typedef {import('micromark-util-types').Code} Code
41053 */
41054
41055/** @type {Construct} */
41056const setextUnderline = {
41057  name: 'setextUnderline',
41058  tokenize: tokenizeSetextUnderline,
41059  resolveTo: resolveToSetextUnderline
41060};
41061/** @type {Resolver} */
41062
41063function resolveToSetextUnderline(events, context) {
41064  let index = events.length;
41065  /** @type {number|undefined} */
41066
41067  let content;
41068  /** @type {number|undefined} */
41069
41070  let text;
41071  /** @type {number|undefined} */
41072
41073  let definition; // Find the opening of the content.
41074  // It’ll always exist: we don’t tokenize if it isn’t there.
41075
41076  while (index--) {
41077    if (events[index][0] === 'enter') {
41078      if (events[index][1].type === 'content') {
41079        content = index;
41080        break
41081      }
41082
41083      if (events[index][1].type === 'paragraph') {
41084        text = index;
41085      }
41086    } // Exit
41087    else {
41088      if (events[index][1].type === 'content') {
41089        // Remove the content end (if needed we’ll add it later)
41090        events.splice(index, 1);
41091      }
41092
41093      if (!definition && events[index][1].type === 'definition') {
41094        definition = index;
41095      }
41096    }
41097  }
41098
41099  const heading = {
41100    type: 'setextHeading',
41101    start: Object.assign({}, events[text][1].start),
41102    end: Object.assign({}, events[events.length - 1][1].end)
41103  }; // Change the paragraph to setext heading text.
41104
41105  events[text][1].type = 'setextHeadingText'; // If we have definitions in the content, we’ll keep on having content,
41106  // but we need move it.
41107
41108  if (definition) {
41109    events.splice(text, 0, ['enter', heading, context]);
41110    events.splice(definition + 1, 0, ['exit', events[content][1], context]);
41111    events[content][1].end = Object.assign({}, events[definition][1].end);
41112  } else {
41113    events[content][1] = heading;
41114  } // Add the heading exit at the end.
41115
41116  events.push(['exit', heading, context]);
41117  return events
41118}
41119/** @type {Tokenizer} */
41120
41121function tokenizeSetextUnderline(effects, ok, nok) {
41122  const self = this;
41123  let index = self.events.length;
41124  /** @type {NonNullable<Code>} */
41125
41126  let marker;
41127  /** @type {boolean} */
41128
41129  let paragraph; // Find an opening.
41130
41131  while (index--) {
41132    // Skip enter/exit of line ending, line prefix, and content.
41133    // We can now either have a definition or a paragraph.
41134    if (
41135      self.events[index][1].type !== 'lineEnding' &&
41136      self.events[index][1].type !== 'linePrefix' &&
41137      self.events[index][1].type !== 'content'
41138    ) {
41139      paragraph = self.events[index][1].type === 'paragraph';
41140      break
41141    }
41142  }
41143
41144  return start
41145  /** @type {State} */
41146
41147  function start(code) {
41148    if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph)) {
41149      effects.enter('setextHeadingLine');
41150      effects.enter('setextHeadingLineSequence');
41151      marker = code;
41152      return closingSequence(code)
41153    }
41154
41155    return nok(code)
41156  }
41157  /** @type {State} */
41158
41159  function closingSequence(code) {
41160    if (code === marker) {
41161      effects.consume(code);
41162      return closingSequence
41163    }
41164
41165    effects.exit('setextHeadingLineSequence');
41166    return factorySpace(effects, closingSequenceEnd, 'lineSuffix')(code)
41167  }
41168  /** @type {State} */
41169
41170  function closingSequenceEnd(code) {
41171    if (code === null || markdownLineEnding(code)) {
41172      effects.exit('setextHeadingLine');
41173      return ok(code)
41174    }
41175
41176    return nok(code)
41177  }
41178}
41179
41180/**
41181 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
41182 * @typedef {import('micromark-util-types').Initializer} Initializer
41183 * @typedef {import('micromark-util-types').State} State
41184 */
41185
41186/** @type {InitialConstruct} */
41187const flow$1 = {
41188  tokenize: initializeFlow
41189};
41190/** @type {Initializer} */
41191
41192function initializeFlow(effects) {
41193  const self = this;
41194  const initial = effects.attempt(
41195    // Try to parse a blank line.
41196    blankLine,
41197    atBlankEnding, // Try to parse initial flow (essentially, only code).
41198    effects.attempt(
41199      this.parser.constructs.flowInitial,
41200      afterConstruct,
41201      factorySpace(
41202        effects,
41203        effects.attempt(
41204          this.parser.constructs.flow,
41205          afterConstruct,
41206          effects.attempt(content, afterConstruct)
41207        ),
41208        'linePrefix'
41209      )
41210    )
41211  );
41212  return initial
41213  /** @type {State} */
41214
41215  function atBlankEnding(code) {
41216    if (code === null) {
41217      effects.consume(code);
41218      return
41219    }
41220
41221    effects.enter('lineEndingBlank');
41222    effects.consume(code);
41223    effects.exit('lineEndingBlank');
41224    self.currentConstruct = undefined;
41225    return initial
41226  }
41227  /** @type {State} */
41228
41229  function afterConstruct(code) {
41230    if (code === null) {
41231      effects.consume(code);
41232      return
41233    }
41234
41235    effects.enter('lineEnding');
41236    effects.consume(code);
41237    effects.exit('lineEnding');
41238    self.currentConstruct = undefined;
41239    return initial
41240  }
41241}
41242
41243/**
41244 * @typedef {import('micromark-util-types').Resolver} Resolver
41245 * @typedef {import('micromark-util-types').Initializer} Initializer
41246 * @typedef {import('micromark-util-types').Construct} Construct
41247 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
41248 * @typedef {import('micromark-util-types').State} State
41249 * @typedef {import('micromark-util-types').Code} Code
41250 */
41251const resolver = {
41252  resolveAll: createResolver()
41253};
41254const string$1 = initializeFactory('string');
41255const text$3 = initializeFactory('text');
41256/**
41257 * @param {'string'|'text'} field
41258 * @returns {InitialConstruct}
41259 */
41260
41261function initializeFactory(field) {
41262  return {
41263    tokenize: initializeText,
41264    resolveAll: createResolver(
41265      field === 'text' ? resolveAllLineSuffixes : undefined
41266    )
41267  }
41268  /** @type {Initializer} */
41269
41270  function initializeText(effects) {
41271    const self = this;
41272    const constructs = this.parser.constructs[field];
41273    const text = effects.attempt(constructs, start, notText);
41274    return start
41275    /** @type {State} */
41276
41277    function start(code) {
41278      return atBreak(code) ? text(code) : notText(code)
41279    }
41280    /** @type {State} */
41281
41282    function notText(code) {
41283      if (code === null) {
41284        effects.consume(code);
41285        return
41286      }
41287
41288      effects.enter('data');
41289      effects.consume(code);
41290      return data
41291    }
41292    /** @type {State} */
41293
41294    function data(code) {
41295      if (atBreak(code)) {
41296        effects.exit('data');
41297        return text(code)
41298      } // Data.
41299
41300      effects.consume(code);
41301      return data
41302    }
41303    /**
41304     * @param {Code} code
41305     * @returns {boolean}
41306     */
41307
41308    function atBreak(code) {
41309      if (code === null) {
41310        return true
41311      }
41312
41313      const list = constructs[code];
41314      let index = -1;
41315
41316      if (list) {
41317        while (++index < list.length) {
41318          const item = list[index];
41319
41320          if (!item.previous || item.previous.call(self, self.previous)) {
41321            return true
41322          }
41323        }
41324      }
41325
41326      return false
41327    }
41328  }
41329}
41330/**
41331 * @param {Resolver} [extraResolver]
41332 * @returns {Resolver}
41333 */
41334
41335function createResolver(extraResolver) {
41336  return resolveAllText
41337  /** @type {Resolver} */
41338
41339  function resolveAllText(events, context) {
41340    let index = -1;
41341    /** @type {number|undefined} */
41342
41343    let enter; // A rather boring computation (to merge adjacent `data` events) which
41344    // improves mm performance by 29%.
41345
41346    while (++index <= events.length) {
41347      if (enter === undefined) {
41348        if (events[index] && events[index][1].type === 'data') {
41349          enter = index;
41350          index++;
41351        }
41352      } else if (!events[index] || events[index][1].type !== 'data') {
41353        // Don’t do anything if there is one data token.
41354        if (index !== enter + 2) {
41355          events[enter][1].end = events[index - 1][1].end;
41356          events.splice(enter + 2, index - enter - 2);
41357          index = enter + 2;
41358        }
41359
41360        enter = undefined;
41361      }
41362    }
41363
41364    return extraResolver ? extraResolver(events, context) : events
41365  }
41366}
41367/**
41368 * A rather ugly set of instructions which again looks at chunks in the input
41369 * stream.
41370 * The reason to do this here is that it is *much* faster to parse in reverse.
41371 * And that we can’t hook into `null` to split the line suffix before an EOF.
41372 * To do: figure out if we can make this into a clean utility, or even in core.
41373 * As it will be useful for GFMs literal autolink extension (and maybe even
41374 * tables?)
41375 *
41376 * @type {Resolver}
41377 */
41378
41379function resolveAllLineSuffixes(events, context) {
41380  let eventIndex = -1;
41381
41382  while (++eventIndex <= events.length) {
41383    if (
41384      (eventIndex === events.length ||
41385        events[eventIndex][1].type === 'lineEnding') &&
41386      events[eventIndex - 1][1].type === 'data'
41387    ) {
41388      const data = events[eventIndex - 1][1];
41389      const chunks = context.sliceStream(data);
41390      let index = chunks.length;
41391      let bufferIndex = -1;
41392      let size = 0;
41393      /** @type {boolean|undefined} */
41394
41395      let tabs;
41396
41397      while (index--) {
41398        const chunk = chunks[index];
41399
41400        if (typeof chunk === 'string') {
41401          bufferIndex = chunk.length;
41402
41403          while (chunk.charCodeAt(bufferIndex - 1) === 32) {
41404            size++;
41405            bufferIndex--;
41406          }
41407
41408          if (bufferIndex) break
41409          bufferIndex = -1;
41410        } // Number
41411        else if (chunk === -2) {
41412          tabs = true;
41413          size++;
41414        } else if (chunk === -1) ; else {
41415          // Replacement character, exit.
41416          index++;
41417          break
41418        }
41419      }
41420
41421      if (size) {
41422        const token = {
41423          type:
41424            eventIndex === events.length || tabs || size < 2
41425              ? 'lineSuffix'
41426              : 'hardBreakTrailing',
41427          start: {
41428            line: data.end.line,
41429            column: data.end.column - size,
41430            offset: data.end.offset - size,
41431            _index: data.start._index + index,
41432            _bufferIndex: index
41433              ? bufferIndex
41434              : data.start._bufferIndex + bufferIndex
41435          },
41436          end: Object.assign({}, data.end)
41437        };
41438        data.end = Object.assign({}, token.start);
41439
41440        if (data.start.offset === data.end.offset) {
41441          Object.assign(data, token);
41442        } else {
41443          events.splice(
41444            eventIndex,
41445            0,
41446            ['enter', token, context],
41447            ['exit', token, context]
41448          );
41449          eventIndex += 2;
41450        }
41451      }
41452
41453      eventIndex++;
41454    }
41455  }
41456
41457  return events
41458}
41459
41460/**
41461 * @typedef {import('micromark-util-types').Code} Code
41462 * @typedef {import('micromark-util-types').Chunk} Chunk
41463 * @typedef {import('micromark-util-types').Point} Point
41464 * @typedef {import('micromark-util-types').Token} Token
41465 * @typedef {import('micromark-util-types').Effects} Effects
41466 * @typedef {import('micromark-util-types').State} State
41467 * @typedef {import('micromark-util-types').Construct} Construct
41468 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
41469 * @typedef {import('micromark-util-types').ConstructRecord} ConstructRecord
41470 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
41471 * @typedef {import('micromark-util-types').ParseContext} ParseContext
41472 */
41473
41474/**
41475 * Create a tokenizer.
41476 * Tokenizers deal with one type of data (e.g., containers, flow, text).
41477 * The parser is the object dealing with it all.
41478 * `initialize` works like other constructs, except that only its `tokenize`
41479 * function is used, in which case it doesn’t receive an `ok` or `nok`.
41480 * `from` can be given to set the point before the first character, although
41481 * when further lines are indented, they must be set with `defineSkip`.
41482 *
41483 * @param {ParseContext} parser
41484 * @param {InitialConstruct} initialize
41485 * @param {Omit<Point, '_index'|'_bufferIndex'>} [from]
41486 * @returns {TokenizeContext}
41487 */
41488function createTokenizer(parser, initialize, from) {
41489  /** @type {Point} */
41490  let point = Object.assign(
41491    from
41492      ? Object.assign({}, from)
41493      : {
41494          line: 1,
41495          column: 1,
41496          offset: 0
41497        },
41498    {
41499      _index: 0,
41500      _bufferIndex: -1
41501    }
41502  );
41503  /** @type {Record<string, number>} */
41504
41505  const columnStart = {};
41506  /** @type {Construct[]} */
41507
41508  const resolveAllConstructs = [];
41509  /** @type {Chunk[]} */
41510
41511  let chunks = [];
41512  /** @type {Token[]} */
41513
41514  let stack = [];
41515  /**
41516   * Tools used for tokenizing.
41517   *
41518   * @type {Effects}
41519   */
41520
41521  const effects = {
41522    consume,
41523    enter,
41524    exit,
41525    attempt: constructFactory(onsuccessfulconstruct),
41526    check: constructFactory(onsuccessfulcheck),
41527    interrupt: constructFactory(onsuccessfulcheck, {
41528      interrupt: true
41529    })
41530  };
41531  /**
41532   * State and tools for resolving and serializing.
41533   *
41534   * @type {TokenizeContext}
41535   */
41536
41537  const context = {
41538    previous: null,
41539    code: null,
41540    containerState: {},
41541    events: [],
41542    parser,
41543    sliceStream,
41544    sliceSerialize,
41545    now,
41546    defineSkip,
41547    write
41548  };
41549  /**
41550   * The state function.
41551   *
41552   * @type {State|void}
41553   */
41554
41555  let state = initialize.tokenize.call(context, effects);
41556
41557  if (initialize.resolveAll) {
41558    resolveAllConstructs.push(initialize);
41559  }
41560
41561  return context
41562  /** @type {TokenizeContext['write']} */
41563
41564  function write(slice) {
41565    chunks = push(chunks, slice);
41566    main(); // Exit if we’re not done, resolve might change stuff.
41567
41568    if (chunks[chunks.length - 1] !== null) {
41569      return []
41570    }
41571
41572    addResult(initialize, 0); // Otherwise, resolve, and exit.
41573
41574    context.events = resolveAll(resolveAllConstructs, context.events, context);
41575    return context.events
41576  } //
41577  // Tools.
41578  //
41579
41580  /** @type {TokenizeContext['sliceSerialize']} */
41581
41582  function sliceSerialize(token, expandTabs) {
41583    return serializeChunks(sliceStream(token), expandTabs)
41584  }
41585  /** @type {TokenizeContext['sliceStream']} */
41586
41587  function sliceStream(token) {
41588    return sliceChunks(chunks, token)
41589  }
41590  /** @type {TokenizeContext['now']} */
41591
41592  function now() {
41593    return Object.assign({}, point)
41594  }
41595  /** @type {TokenizeContext['defineSkip']} */
41596
41597  function defineSkip(value) {
41598    columnStart[value.line] = value.column;
41599    accountForPotentialSkip();
41600  } //
41601  // State management.
41602  //
41603
41604  /**
41605   * Main loop (note that `_index` and `_bufferIndex` in `point` are modified by
41606   * `consume`).
41607   * Here is where we walk through the chunks, which either include strings of
41608   * several characters, or numerical character codes.
41609   * The reason to do this in a loop instead of a call is so the stack can
41610   * drain.
41611   *
41612   * @returns {void}
41613   */
41614
41615  function main() {
41616    /** @type {number} */
41617    let chunkIndex;
41618
41619    while (point._index < chunks.length) {
41620      const chunk = chunks[point._index]; // If we’re in a buffer chunk, loop through it.
41621
41622      if (typeof chunk === 'string') {
41623        chunkIndex = point._index;
41624
41625        if (point._bufferIndex < 0) {
41626          point._bufferIndex = 0;
41627        }
41628
41629        while (
41630          point._index === chunkIndex &&
41631          point._bufferIndex < chunk.length
41632        ) {
41633          go(chunk.charCodeAt(point._bufferIndex));
41634        }
41635      } else {
41636        go(chunk);
41637      }
41638    }
41639  }
41640  /**
41641   * Deal with one code.
41642   *
41643   * @param {Code} code
41644   * @returns {void}
41645   */
41646
41647  function go(code) {
41648    state = state(code);
41649  }
41650  /** @type {Effects['consume']} */
41651
41652  function consume(code) {
41653    if (markdownLineEnding(code)) {
41654      point.line++;
41655      point.column = 1;
41656      point.offset += code === -3 ? 2 : 1;
41657      accountForPotentialSkip();
41658    } else if (code !== -1) {
41659      point.column++;
41660      point.offset++;
41661    } // Not in a string chunk.
41662
41663    if (point._bufferIndex < 0) {
41664      point._index++;
41665    } else {
41666      point._bufferIndex++; // At end of string chunk.
41667      // @ts-expect-error Points w/ non-negative `_bufferIndex` reference
41668      // strings.
41669
41670      if (point._bufferIndex === chunks[point._index].length) {
41671        point._bufferIndex = -1;
41672        point._index++;
41673      }
41674    } // Expose the previous character.
41675
41676    context.previous = code; // Mark as consumed.
41677  }
41678  /** @type {Effects['enter']} */
41679
41680  function enter(type, fields) {
41681    /** @type {Token} */
41682    // @ts-expect-error Patch instead of assign required fields to help GC.
41683    const token = fields || {};
41684    token.type = type;
41685    token.start = now();
41686    context.events.push(['enter', token, context]);
41687    stack.push(token);
41688    return token
41689  }
41690  /** @type {Effects['exit']} */
41691
41692  function exit(type) {
41693    const token = stack.pop();
41694    token.end = now();
41695    context.events.push(['exit', token, context]);
41696    return token
41697  }
41698  /**
41699   * Use results.
41700   *
41701   * @type {ReturnHandle}
41702   */
41703
41704  function onsuccessfulconstruct(construct, info) {
41705    addResult(construct, info.from);
41706  }
41707  /**
41708   * Discard results.
41709   *
41710   * @type {ReturnHandle}
41711   */
41712
41713  function onsuccessfulcheck(_, info) {
41714    info.restore();
41715  }
41716  /**
41717   * Factory to attempt/check/interrupt.
41718   *
41719   * @param {ReturnHandle} onreturn
41720   * @param {Record<string, unknown>} [fields]
41721   */
41722
41723  function constructFactory(onreturn, fields) {
41724    return hook
41725    /**
41726     * Handle either an object mapping codes to constructs, a list of
41727     * constructs, or a single construct.
41728     *
41729     * @param {Construct|Construct[]|ConstructRecord} constructs
41730     * @param {State} returnState
41731     * @param {State} [bogusState]
41732     * @returns {State}
41733     */
41734
41735    function hook(constructs, returnState, bogusState) {
41736      /** @type {Construct[]} */
41737      let listOfConstructs;
41738      /** @type {number} */
41739
41740      let constructIndex;
41741      /** @type {Construct} */
41742
41743      let currentConstruct;
41744      /** @type {Info} */
41745
41746      let info;
41747      return Array.isArray(constructs)
41748        ? /* c8 ignore next 1 */
41749          handleListOfConstructs(constructs)
41750        : 'tokenize' in constructs // @ts-expect-error Looks like a construct.
41751        ? handleListOfConstructs([constructs])
41752        : handleMapOfConstructs(constructs)
41753      /**
41754       * Handle a list of construct.
41755       *
41756       * @param {ConstructRecord} map
41757       * @returns {State}
41758       */
41759
41760      function handleMapOfConstructs(map) {
41761        return start
41762        /** @type {State} */
41763
41764        function start(code) {
41765          const def = code !== null && map[code];
41766          const all = code !== null && map.null;
41767          const list = [
41768            // To do: add more extension tests.
41769
41770            /* c8 ignore next 2 */
41771            ...(Array.isArray(def) ? def : def ? [def] : []),
41772            ...(Array.isArray(all) ? all : all ? [all] : [])
41773          ];
41774          return handleListOfConstructs(list)(code)
41775        }
41776      }
41777      /**
41778       * Handle a list of construct.
41779       *
41780       * @param {Construct[]} list
41781       * @returns {State}
41782       */
41783
41784      function handleListOfConstructs(list) {
41785        listOfConstructs = list;
41786        constructIndex = 0;
41787
41788        if (list.length === 0) {
41789          return bogusState
41790        }
41791
41792        return handleConstruct(list[constructIndex])
41793      }
41794      /**
41795       * Handle a single construct.
41796       *
41797       * @param {Construct} construct
41798       * @returns {State}
41799       */
41800
41801      function handleConstruct(construct) {
41802        return start
41803        /** @type {State} */
41804
41805        function start(code) {
41806          // To do: not needed to store if there is no bogus state, probably?
41807          // Currently doesn’t work because `inspect` in document does a check
41808          // w/o a bogus, which doesn’t make sense. But it does seem to help perf
41809          // by not storing.
41810          info = store();
41811          currentConstruct = construct;
41812
41813          if (!construct.partial) {
41814            context.currentConstruct = construct;
41815          }
41816
41817          if (
41818            construct.name &&
41819            context.parser.constructs.disable.null.includes(construct.name)
41820          ) {
41821            return nok()
41822          }
41823
41824          return construct.tokenize.call(
41825            // If we do have fields, create an object w/ `context` as its
41826            // prototype.
41827            // This allows a “live binding”, which is needed for `interrupt`.
41828            fields ? Object.assign(Object.create(context), fields) : context,
41829            effects,
41830            ok,
41831            nok
41832          )(code)
41833        }
41834      }
41835      /** @type {State} */
41836
41837      function ok(code) {
41838        onreturn(currentConstruct, info);
41839        return returnState
41840      }
41841      /** @type {State} */
41842
41843      function nok(code) {
41844        info.restore();
41845
41846        if (++constructIndex < listOfConstructs.length) {
41847          return handleConstruct(listOfConstructs[constructIndex])
41848        }
41849
41850        return bogusState
41851      }
41852    }
41853  }
41854  /**
41855   * @param {Construct} construct
41856   * @param {number} from
41857   * @returns {void}
41858   */
41859
41860  function addResult(construct, from) {
41861    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {
41862      resolveAllConstructs.push(construct);
41863    }
41864
41865    if (construct.resolve) {
41866      splice(
41867        context.events,
41868        from,
41869        context.events.length - from,
41870        construct.resolve(context.events.slice(from), context)
41871      );
41872    }
41873
41874    if (construct.resolveTo) {
41875      context.events = construct.resolveTo(context.events, context);
41876    }
41877  }
41878  /**
41879   * Store state.
41880   *
41881   * @returns {Info}
41882   */
41883
41884  function store() {
41885    const startPoint = now();
41886    const startPrevious = context.previous;
41887    const startCurrentConstruct = context.currentConstruct;
41888    const startEventsIndex = context.events.length;
41889    const startStack = Array.from(stack);
41890    return {
41891      restore,
41892      from: startEventsIndex
41893    }
41894    /**
41895     * Restore state.
41896     *
41897     * @returns {void}
41898     */
41899
41900    function restore() {
41901      point = startPoint;
41902      context.previous = startPrevious;
41903      context.currentConstruct = startCurrentConstruct;
41904      context.events.length = startEventsIndex;
41905      stack = startStack;
41906      accountForPotentialSkip();
41907    }
41908  }
41909  /**
41910   * Move the current point a bit forward in the line when it’s on a column
41911   * skip.
41912   *
41913   * @returns {void}
41914   */
41915
41916  function accountForPotentialSkip() {
41917    if (point.line in columnStart && point.column < 2) {
41918      point.column = columnStart[point.line];
41919      point.offset += columnStart[point.line] - 1;
41920    }
41921  }
41922}
41923/**
41924 * Get the chunks from a slice of chunks in the range of a token.
41925 *
41926 * @param {Chunk[]} chunks
41927 * @param {Pick<Token, 'start'|'end'>} token
41928 * @returns {Chunk[]}
41929 */
41930
41931function sliceChunks(chunks, token) {
41932  const startIndex = token.start._index;
41933  const startBufferIndex = token.start._bufferIndex;
41934  const endIndex = token.end._index;
41935  const endBufferIndex = token.end._bufferIndex;
41936  /** @type {Chunk[]} */
41937
41938  let view;
41939
41940  if (startIndex === endIndex) {
41941    // @ts-expect-error `_bufferIndex` is used on string chunks.
41942    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
41943  } else {
41944    view = chunks.slice(startIndex, endIndex);
41945
41946    if (startBufferIndex > -1) {
41947      // @ts-expect-error `_bufferIndex` is used on string chunks.
41948      view[0] = view[0].slice(startBufferIndex);
41949    }
41950
41951    if (endBufferIndex > 0) {
41952      // @ts-expect-error `_bufferIndex` is used on string chunks.
41953      view.push(chunks[endIndex].slice(0, endBufferIndex));
41954    }
41955  }
41956
41957  return view
41958}
41959/**
41960 * Get the string value of a slice of chunks.
41961 *
41962 * @param {Chunk[]} chunks
41963 * @param {boolean} [expandTabs=false]
41964 * @returns {string}
41965 */
41966
41967function serializeChunks(chunks, expandTabs) {
41968  let index = -1;
41969  /** @type {string[]} */
41970
41971  const result = [];
41972  /** @type {boolean|undefined} */
41973
41974  let atTab;
41975
41976  while (++index < chunks.length) {
41977    const chunk = chunks[index];
41978    /** @type {string} */
41979
41980    let value;
41981
41982    if (typeof chunk === 'string') {
41983      value = chunk;
41984    } else
41985      switch (chunk) {
41986        case -5: {
41987          value = '\r';
41988          break
41989        }
41990
41991        case -4: {
41992          value = '\n';
41993          break
41994        }
41995
41996        case -3: {
41997          value = '\r' + '\n';
41998          break
41999        }
42000
42001        case -2: {
42002          value = expandTabs ? ' ' : '\t';
42003          break
42004        }
42005
42006        case -1: {
42007          if (!expandTabs && atTab) continue
42008          value = ' ';
42009          break
42010        }
42011
42012        default: {
42013          // Currently only replacement character.
42014          value = String.fromCharCode(chunk);
42015        }
42016      }
42017
42018    atTab = chunk === -2;
42019    result.push(value);
42020  }
42021
42022  return result.join('')
42023}
42024
42025/**
42026 * @typedef {import('micromark-util-types').Extension} Extension
42027 */
42028/** @type {Extension['document']} */
42029
42030const document$1 = {
42031  [42]: list$1,
42032  [43]: list$1,
42033  [45]: list$1,
42034  [48]: list$1,
42035  [49]: list$1,
42036  [50]: list$1,
42037  [51]: list$1,
42038  [52]: list$1,
42039  [53]: list$1,
42040  [54]: list$1,
42041  [55]: list$1,
42042  [56]: list$1,
42043  [57]: list$1,
42044  [62]: blockQuote
42045};
42046/** @type {Extension['contentInitial']} */
42047
42048const contentInitial = {
42049  [91]: definition$1
42050};
42051/** @type {Extension['flowInitial']} */
42052
42053const flowInitial = {
42054  [-2]: codeIndented,
42055  [-1]: codeIndented,
42056  [32]: codeIndented
42057};
42058/** @type {Extension['flow']} */
42059
42060const flow = {
42061  [35]: headingAtx,
42062  [42]: thematicBreak$1,
42063  [45]: [setextUnderline, thematicBreak$1],
42064  [60]: htmlFlow,
42065  [61]: setextUnderline,
42066  [95]: thematicBreak$1,
42067  [96]: codeFenced,
42068  [126]: codeFenced
42069};
42070/** @type {Extension['string']} */
42071
42072const string = {
42073  [38]: characterReference$1,
42074  [92]: characterEscape$1
42075};
42076/** @type {Extension['text']} */
42077
42078const text$2 = {
42079  [-5]: lineEnding,
42080  [-4]: lineEnding,
42081  [-3]: lineEnding,
42082  [33]: labelStartImage,
42083  [38]: characterReference$1,
42084  [42]: attention,
42085  [60]: [autolink, htmlText],
42086  [91]: labelStartLink,
42087  [92]: [hardBreakEscape, characterEscape$1],
42088  [93]: labelEnd,
42089  [95]: attention,
42090  [96]: codeText
42091};
42092/** @type {Extension['insideSpan']} */
42093
42094const insideSpan = {
42095  null: [attention, resolver]
42096};
42097/** @type {Extension['disable']} */
42098
42099const disable = {
42100  null: []
42101};
42102
42103var defaultConstructs = /*#__PURE__*/Object.freeze({
42104	__proto__: null,
42105	document: document$1,
42106	contentInitial: contentInitial,
42107	flowInitial: flowInitial,
42108	flow: flow,
42109	string: string,
42110	text: text$2,
42111	insideSpan: insideSpan,
42112	disable: disable
42113});
42114
42115/**
42116 * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct
42117 * @typedef {import('micromark-util-types').FullNormalizedExtension} FullNormalizedExtension
42118 * @typedef {import('micromark-util-types').ParseOptions} ParseOptions
42119 * @typedef {import('micromark-util-types').ParseContext} ParseContext
42120 * @typedef {import('micromark-util-types').Create} Create
42121 */
42122/**
42123 * @param {ParseOptions} [options]
42124 * @returns {ParseContext}
42125 */
42126
42127function parse(options = {}) {
42128  /** @type {FullNormalizedExtension} */
42129  // @ts-expect-error `defaultConstructs` is full, so the result will be too.
42130  const constructs = combineExtensions(
42131    // @ts-expect-error Same as above.
42132    [defaultConstructs].concat(options.extensions || [])
42133  );
42134  /** @type {ParseContext} */
42135
42136  const parser = {
42137    defined: [],
42138    lazy: {},
42139    constructs,
42140    content: create(content$1),
42141    document: create(document$2),
42142    flow: create(flow$1),
42143    string: create(string$1),
42144    text: create(text$3)
42145  };
42146  return parser
42147  /**
42148   * @param {InitialConstruct} initial
42149   */
42150
42151  function create(initial) {
42152    return creator
42153    /** @type {Create} */
42154
42155    function creator(from) {
42156      return createTokenizer(parser, initial, from)
42157    }
42158  }
42159}
42160
42161/**
42162 * @typedef {import('micromark-util-types').Encoding} Encoding
42163 * @typedef {import('micromark-util-types').Value} Value
42164 * @typedef {import('micromark-util-types').Chunk} Chunk
42165 * @typedef {import('micromark-util-types').Code} Code
42166 */
42167
42168/**
42169 * @callback Preprocessor
42170 * @param {Value} value
42171 * @param {Encoding} [encoding]
42172 * @param {boolean} [end=false]
42173 * @returns {Chunk[]}
42174 */
42175const search = /[\0\t\n\r]/g;
42176/**
42177 * @returns {Preprocessor}
42178 */
42179
42180function preprocess() {
42181  let column = 1;
42182  let buffer = '';
42183  /** @type {boolean|undefined} */
42184
42185  let start = true;
42186  /** @type {boolean|undefined} */
42187
42188  let atCarriageReturn;
42189  return preprocessor
42190  /** @type {Preprocessor} */
42191
42192  function preprocessor(value, encoding, end) {
42193    /** @type {Chunk[]} */
42194    const chunks = [];
42195    /** @type {RegExpMatchArray|null} */
42196
42197    let match;
42198    /** @type {number} */
42199
42200    let next;
42201    /** @type {number} */
42202
42203    let startPosition;
42204    /** @type {number} */
42205
42206    let endPosition;
42207    /** @type {Code} */
42208
42209    let code; // @ts-expect-error `Buffer` does allow an encoding.
42210
42211    value = buffer + value.toString(encoding);
42212    startPosition = 0;
42213    buffer = '';
42214
42215    if (start) {
42216      if (value.charCodeAt(0) === 65279) {
42217        startPosition++;
42218      }
42219
42220      start = undefined;
42221    }
42222
42223    while (startPosition < value.length) {
42224      search.lastIndex = startPosition;
42225      match = search.exec(value);
42226      endPosition =
42227        match && match.index !== undefined ? match.index : value.length;
42228      code = value.charCodeAt(endPosition);
42229
42230      if (!match) {
42231        buffer = value.slice(startPosition);
42232        break
42233      }
42234
42235      if (code === 10 && startPosition === endPosition && atCarriageReturn) {
42236        chunks.push(-3);
42237        atCarriageReturn = undefined;
42238      } else {
42239        if (atCarriageReturn) {
42240          chunks.push(-5);
42241          atCarriageReturn = undefined;
42242        }
42243
42244        if (startPosition < endPosition) {
42245          chunks.push(value.slice(startPosition, endPosition));
42246          column += endPosition - startPosition;
42247        }
42248
42249        switch (code) {
42250          case 0: {
42251            chunks.push(65533);
42252            column++;
42253            break
42254          }
42255
42256          case 9: {
42257            next = Math.ceil(column / 4) * 4;
42258            chunks.push(-2);
42259
42260            while (column++ < next) chunks.push(-1);
42261
42262            break
42263          }
42264
42265          case 10: {
42266            chunks.push(-4);
42267            column = 1;
42268            break
42269          }
42270
42271          default: {
42272            atCarriageReturn = true;
42273            column = 1;
42274          }
42275        }
42276      }
42277
42278      startPosition = endPosition + 1;
42279    }
42280
42281    if (end) {
42282      if (atCarriageReturn) chunks.push(-5);
42283      if (buffer) chunks.push(buffer);
42284      chunks.push(null);
42285    }
42286
42287    return chunks
42288  }
42289}
42290
42291/**
42292 * @typedef {import('micromark-util-types').Event} Event
42293 */
42294/**
42295 * @param {Event[]} events
42296 * @returns {Event[]}
42297 */
42298
42299function postprocess(events) {
42300  while (!subtokenize(events)) {
42301    // Empty
42302  }
42303
42304  return events
42305}
42306
42307/**
42308 * Turn the number (in string form as either hexa- or plain decimal) coming from
42309 * a numeric character reference into a character.
42310 *
42311 * @param {string} value
42312 *   Value to decode.
42313 * @param {number} base
42314 *   Numeric base.
42315 * @returns {string}
42316 */
42317function decodeNumericCharacterReference(value, base) {
42318  const code = Number.parseInt(value, base);
42319
42320  if (
42321    // C0 except for HT, LF, FF, CR, space
42322    code < 9 ||
42323    code === 11 ||
42324    (code > 13 && code < 32) || // Control character (DEL) of the basic block and C1 controls.
42325    (code > 126 && code < 160) || // Lone high surrogates and low surrogates.
42326    (code > 55295 && code < 57344) || // Noncharacters.
42327    (code > 64975 && code < 65008) ||
42328    (code & 65535) === 65535 ||
42329    (code & 65535) === 65534 || // Out of range
42330    code > 1114111
42331  ) {
42332    return '\uFFFD'
42333  }
42334
42335  return String.fromCharCode(code)
42336}
42337
42338/**
42339 * @typedef {import('micromark-util-types').Encoding} Encoding
42340 * @typedef {import('micromark-util-types').Event} Event
42341 * @typedef {import('micromark-util-types').ParseOptions} ParseOptions
42342 * @typedef {import('micromark-util-types').Token} Token
42343 * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext
42344 * @typedef {import('micromark-util-types').Value} Value
42345 * @typedef {Root|Root['children'][number]} Node
42346 * @typedef {import('unist').Parent} Parent
42347 * @typedef {import('unist').Point} Point
42348 * @typedef {import('mdast').Break} Break
42349 * @typedef {import('mdast').Blockquote} Blockquote
42350 * @typedef {import('mdast').Code} Code
42351 * @typedef {import('mdast').Definition} Definition
42352 * @typedef {import('mdast').Emphasis} Emphasis
42353 * @typedef {import('mdast').Heading} Heading
42354 * @typedef {import('mdast').HTML} HTML
42355 * @typedef {import('mdast').Image} Image
42356 * @typedef {import('mdast').InlineCode} InlineCode
42357 * @typedef {import('mdast').Link} Link
42358 * @typedef {import('mdast').List} List
42359 * @typedef {import('mdast').ListItem} ListItem
42360 * @typedef {import('mdast').Paragraph} Paragraph
42361 * @typedef {import('mdast').Root} Root
42362 * @typedef {import('mdast').Strong} Strong
42363 * @typedef {import('mdast').Text} Text
42364 * @typedef {import('mdast').ThematicBreak} ThematicBreak
42365 */
42366const own$4 = {}.hasOwnProperty;
42367/**
42368 * @param value Markdown to parse (`string` or `Buffer`).
42369 * @param [encoding] Character encoding to understand `value` as when it’s a `Buffer` (`string`, default: `'utf8'`).
42370 * @param [options] Configuration
42371 */
42372
42373const fromMarkdown =
42374  /**
42375   * @type {(
42376   *   ((value: Value, encoding: Encoding, options?: Options) => Root) &
42377   *   ((value: Value, options?: Options) => Root)
42378   * )}
42379   */
42380
42381  /**
42382   * @param {Value} value
42383   * @param {Encoding} [encoding]
42384   * @param {Options} [options]
42385   * @returns {Root}
42386   */
42387  function (value, encoding, options) {
42388    if (typeof encoding !== 'string') {
42389      options = encoding;
42390      encoding = undefined;
42391    }
42392
42393    return compiler(options)(
42394      postprocess(
42395        parse(options).document().write(preprocess()(value, encoding, true))
42396      )
42397    )
42398  };
42399/**
42400 * Note this compiler only understand complete buffering, not streaming.
42401 *
42402 * @param {Options} [options]
42403 */
42404
42405function compiler(options = {}) {
42406  /** @type {NormalizedExtension} */
42407  // @ts-expect-error: our base has all required fields, so the result will too.
42408  const config = configure$1(
42409    {
42410      transforms: [],
42411      canContainEols: [
42412        'emphasis',
42413        'fragment',
42414        'heading',
42415        'paragraph',
42416        'strong'
42417      ],
42418      enter: {
42419        autolink: opener(link),
42420        autolinkProtocol: onenterdata,
42421        autolinkEmail: onenterdata,
42422        atxHeading: opener(heading),
42423        blockQuote: opener(blockQuote),
42424        characterEscape: onenterdata,
42425        characterReference: onenterdata,
42426        codeFenced: opener(codeFlow),
42427        codeFencedFenceInfo: buffer,
42428        codeFencedFenceMeta: buffer,
42429        codeIndented: opener(codeFlow, buffer),
42430        codeText: opener(codeText, buffer),
42431        codeTextData: onenterdata,
42432        data: onenterdata,
42433        codeFlowValue: onenterdata,
42434        definition: opener(definition),
42435        definitionDestinationString: buffer,
42436        definitionLabelString: buffer,
42437        definitionTitleString: buffer,
42438        emphasis: opener(emphasis),
42439        hardBreakEscape: opener(hardBreak),
42440        hardBreakTrailing: opener(hardBreak),
42441        htmlFlow: opener(html, buffer),
42442        htmlFlowData: onenterdata,
42443        htmlText: opener(html, buffer),
42444        htmlTextData: onenterdata,
42445        image: opener(image),
42446        label: buffer,
42447        link: opener(link),
42448        listItem: opener(listItem),
42449        listItemValue: onenterlistitemvalue,
42450        listOrdered: opener(list, onenterlistordered),
42451        listUnordered: opener(list),
42452        paragraph: opener(paragraph),
42453        reference: onenterreference,
42454        referenceString: buffer,
42455        resourceDestinationString: buffer,
42456        resourceTitleString: buffer,
42457        setextHeading: opener(heading),
42458        strong: opener(strong),
42459        thematicBreak: opener(thematicBreak)
42460      },
42461      exit: {
42462        atxHeading: closer(),
42463        atxHeadingSequence: onexitatxheadingsequence,
42464        autolink: closer(),
42465        autolinkEmail: onexitautolinkemail,
42466        autolinkProtocol: onexitautolinkprotocol,
42467        blockQuote: closer(),
42468        characterEscapeValue: onexitdata,
42469        characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
42470        characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
42471        characterReferenceValue: onexitcharacterreferencevalue,
42472        codeFenced: closer(onexitcodefenced),
42473        codeFencedFence: onexitcodefencedfence,
42474        codeFencedFenceInfo: onexitcodefencedfenceinfo,
42475        codeFencedFenceMeta: onexitcodefencedfencemeta,
42476        codeFlowValue: onexitdata,
42477        codeIndented: closer(onexitcodeindented),
42478        codeText: closer(onexitcodetext),
42479        codeTextData: onexitdata,
42480        data: onexitdata,
42481        definition: closer(),
42482        definitionDestinationString: onexitdefinitiondestinationstring,
42483        definitionLabelString: onexitdefinitionlabelstring,
42484        definitionTitleString: onexitdefinitiontitlestring,
42485        emphasis: closer(),
42486        hardBreakEscape: closer(onexithardbreak),
42487        hardBreakTrailing: closer(onexithardbreak),
42488        htmlFlow: closer(onexithtmlflow),
42489        htmlFlowData: onexitdata,
42490        htmlText: closer(onexithtmltext),
42491        htmlTextData: onexitdata,
42492        image: closer(onexitimage),
42493        label: onexitlabel,
42494        labelText: onexitlabeltext,
42495        lineEnding: onexitlineending,
42496        link: closer(onexitlink),
42497        listItem: closer(),
42498        listOrdered: closer(),
42499        listUnordered: closer(),
42500        paragraph: closer(),
42501        referenceString: onexitreferencestring,
42502        resourceDestinationString: onexitresourcedestinationstring,
42503        resourceTitleString: onexitresourcetitlestring,
42504        resource: onexitresource,
42505        setextHeading: closer(onexitsetextheading),
42506        setextHeadingLineSequence: onexitsetextheadinglinesequence,
42507        setextHeadingText: onexitsetextheadingtext,
42508        strong: closer(),
42509        thematicBreak: closer()
42510      }
42511    },
42512    options.mdastExtensions || []
42513  );
42514  /** @type {CompileData} */
42515
42516  const data = {};
42517  return compile
42518  /**
42519   * @param {Array.<Event>} events
42520   * @returns {Root}
42521   */
42522
42523  function compile(events) {
42524    /** @type {Root} */
42525    let tree = {
42526      type: 'root',
42527      children: []
42528    };
42529    /** @type {CompileContext['stack']} */
42530
42531    const stack = [tree];
42532    /** @type {CompileContext['tokenStack']} */
42533
42534    const tokenStack = [];
42535    /** @type {Array.<number>} */
42536
42537    const listStack = [];
42538    /** @type {Omit<CompileContext, 'sliceSerialize'>} */
42539
42540    const context = {
42541      stack,
42542      tokenStack,
42543      config,
42544      enter,
42545      exit,
42546      buffer,
42547      resume,
42548      setData,
42549      getData
42550    };
42551    let index = -1;
42552
42553    while (++index < events.length) {
42554      // We preprocess lists to add `listItem` tokens, and to infer whether
42555      // items the list itself are spread out.
42556      if (
42557        events[index][1].type === 'listOrdered' ||
42558        events[index][1].type === 'listUnordered'
42559      ) {
42560        if (events[index][0] === 'enter') {
42561          listStack.push(index);
42562        } else {
42563          const tail = listStack.pop();
42564          index = prepareList(events, tail, index);
42565        }
42566      }
42567    }
42568
42569    index = -1;
42570
42571    while (++index < events.length) {
42572      const handler = config[events[index][0]];
42573
42574      if (own$4.call(handler, events[index][1].type)) {
42575        handler[events[index][1].type].call(
42576          Object.assign(
42577            {
42578              sliceSerialize: events[index][2].sliceSerialize
42579            },
42580            context
42581          ),
42582          events[index][1]
42583        );
42584      }
42585    }
42586
42587    if (tokenStack.length > 0) {
42588      throw new Error(
42589        'Cannot close document, a token (`' +
42590          tokenStack[tokenStack.length - 1].type +
42591          '`, ' +
42592          stringifyPosition$1({
42593            start: tokenStack[tokenStack.length - 1].start,
42594            end: tokenStack[tokenStack.length - 1].end
42595          }) +
42596          ') is still open'
42597      )
42598    } // Figure out `root` position.
42599
42600    tree.position = {
42601      start: point(
42602        events.length > 0
42603          ? events[0][1].start
42604          : {
42605              line: 1,
42606              column: 1,
42607              offset: 0
42608            }
42609      ),
42610      end: point(
42611        events.length > 0
42612          ? events[events.length - 2][1].end
42613          : {
42614              line: 1,
42615              column: 1,
42616              offset: 0
42617            }
42618      )
42619    };
42620    index = -1;
42621
42622    while (++index < config.transforms.length) {
42623      tree = config.transforms[index](tree) || tree;
42624    }
42625
42626    return tree
42627  }
42628  /**
42629   * @param {Array.<Event>} events
42630   * @param {number} start
42631   * @param {number} length
42632   * @returns {number}
42633   */
42634
42635  function prepareList(events, start, length) {
42636    let index = start - 1;
42637    let containerBalance = -1;
42638    let listSpread = false;
42639    /** @type {Token|undefined} */
42640
42641    let listItem;
42642    /** @type {number|undefined} */
42643
42644    let lineIndex;
42645    /** @type {number|undefined} */
42646
42647    let firstBlankLineIndex;
42648    /** @type {boolean|undefined} */
42649
42650    let atMarker;
42651
42652    while (++index <= length) {
42653      const event = events[index];
42654
42655      if (
42656        event[1].type === 'listUnordered' ||
42657        event[1].type === 'listOrdered' ||
42658        event[1].type === 'blockQuote'
42659      ) {
42660        if (event[0] === 'enter') {
42661          containerBalance++;
42662        } else {
42663          containerBalance--;
42664        }
42665
42666        atMarker = undefined;
42667      } else if (event[1].type === 'lineEndingBlank') {
42668        if (event[0] === 'enter') {
42669          if (
42670            listItem &&
42671            !atMarker &&
42672            !containerBalance &&
42673            !firstBlankLineIndex
42674          ) {
42675            firstBlankLineIndex = index;
42676          }
42677
42678          atMarker = undefined;
42679        }
42680      } else if (
42681        event[1].type === 'linePrefix' ||
42682        event[1].type === 'listItemValue' ||
42683        event[1].type === 'listItemMarker' ||
42684        event[1].type === 'listItemPrefix' ||
42685        event[1].type === 'listItemPrefixWhitespace'
42686      ) ; else {
42687        atMarker = undefined;
42688      }
42689
42690      if (
42691        (!containerBalance &&
42692          event[0] === 'enter' &&
42693          event[1].type === 'listItemPrefix') ||
42694        (containerBalance === -1 &&
42695          event[0] === 'exit' &&
42696          (event[1].type === 'listUnordered' ||
42697            event[1].type === 'listOrdered'))
42698      ) {
42699        if (listItem) {
42700          let tailIndex = index;
42701          lineIndex = undefined;
42702
42703          while (tailIndex--) {
42704            const tailEvent = events[tailIndex];
42705
42706            if (
42707              tailEvent[1].type === 'lineEnding' ||
42708              tailEvent[1].type === 'lineEndingBlank'
42709            ) {
42710              if (tailEvent[0] === 'exit') continue
42711
42712              if (lineIndex) {
42713                events[lineIndex][1].type = 'lineEndingBlank';
42714                listSpread = true;
42715              }
42716
42717              tailEvent[1].type = 'lineEnding';
42718              lineIndex = tailIndex;
42719            } else if (
42720              tailEvent[1].type === 'linePrefix' ||
42721              tailEvent[1].type === 'blockQuotePrefix' ||
42722              tailEvent[1].type === 'blockQuotePrefixWhitespace' ||
42723              tailEvent[1].type === 'blockQuoteMarker' ||
42724              tailEvent[1].type === 'listItemIndent'
42725            ) ; else {
42726              break
42727            }
42728          }
42729
42730          if (
42731            firstBlankLineIndex &&
42732            (!lineIndex || firstBlankLineIndex < lineIndex)
42733          ) {
42734            // @ts-expect-error Patched.
42735            listItem._spread = true;
42736          } // Fix position.
42737
42738          listItem.end = Object.assign(
42739            {},
42740            lineIndex ? events[lineIndex][1].start : event[1].end
42741          );
42742          events.splice(lineIndex || index, 0, ['exit', listItem, event[2]]);
42743          index++;
42744          length++;
42745        } // Create a new list item.
42746
42747        if (event[1].type === 'listItemPrefix') {
42748          listItem = {
42749            type: 'listItem',
42750            // @ts-expect-error Patched
42751            _spread: false,
42752            start: Object.assign({}, event[1].start)
42753          }; // @ts-expect-error: `listItem` is most definitely defined, TS...
42754
42755          events.splice(index, 0, ['enter', listItem, event[2]]);
42756          index++;
42757          length++;
42758          firstBlankLineIndex = undefined;
42759          atMarker = true;
42760        }
42761      }
42762    } // @ts-expect-error Patched.
42763
42764    events[start][1]._spread = listSpread;
42765    return length
42766  }
42767  /**
42768   * @type {CompileContext['setData']}
42769   * @param [value]
42770   */
42771
42772  function setData(key, value) {
42773    data[key] = value;
42774  }
42775  /**
42776   * @type {CompileContext['getData']}
42777   * @template {string} K
42778   * @param {K} key
42779   * @returns {CompileData[K]}
42780   */
42781
42782  function getData(key) {
42783    return data[key]
42784  }
42785  /**
42786   * @param {Point} d
42787   * @returns {Point}
42788   */
42789
42790  function point(d) {
42791    return {
42792      line: d.line,
42793      column: d.column,
42794      offset: d.offset
42795    }
42796  }
42797  /**
42798   * @param {(token: Token) => Node} create
42799   * @param {Handle} [and]
42800   * @returns {Handle}
42801   */
42802
42803  function opener(create, and) {
42804    return open
42805    /**
42806     * @this {CompileContext}
42807     * @param {Token} token
42808     * @returns {void}
42809     */
42810
42811    function open(token) {
42812      enter.call(this, create(token), token);
42813      if (and) and.call(this, token);
42814    }
42815  }
42816  /** @type {CompileContext['buffer']} */
42817
42818  function buffer() {
42819    // @ts-expect-error: Custom node type to collect text.
42820    this.stack.push({
42821      type: 'fragment',
42822      children: []
42823    });
42824  }
42825  /**
42826   * @type {CompileContext['enter']}
42827   * @template {Node} N
42828   * @this {CompileContext}
42829   * @param {N} node
42830   * @param {Token} token
42831   * @returns {N}
42832   */
42833
42834  function enter(node, token) {
42835    /** @type {Parent} */
42836    // @ts-expect-error: Assume parent.
42837    const parent = this.stack[this.stack.length - 1];
42838    parent.children.push(node);
42839    this.stack.push(node);
42840    this.tokenStack.push(token); // @ts-expect-error: `end` will be patched later.
42841
42842    node.position = {
42843      start: point(token.start)
42844    };
42845    return node
42846  }
42847  /**
42848   * @param {Handle} [and]
42849   * @returns {Handle}
42850   */
42851
42852  function closer(and) {
42853    return close
42854    /**
42855     * @this {CompileContext}
42856     * @param {Token} token
42857     * @returns {void}
42858     */
42859
42860    function close(token) {
42861      if (and) and.call(this, token);
42862      exit.call(this, token);
42863    }
42864  }
42865  /** @type {CompileContext['exit']} */
42866
42867  function exit(token) {
42868    const node = this.stack.pop();
42869    const open = this.tokenStack.pop();
42870
42871    if (!open) {
42872      throw new Error(
42873        'Cannot close `' +
42874          token.type +
42875          '` (' +
42876          stringifyPosition$1({
42877            start: token.start,
42878            end: token.end
42879          }) +
42880          '): it’s not open'
42881      )
42882    } else if (open.type !== token.type) {
42883      throw new Error(
42884        'Cannot close `' +
42885          token.type +
42886          '` (' +
42887          stringifyPosition$1({
42888            start: token.start,
42889            end: token.end
42890          }) +
42891          '): a different token (`' +
42892          open.type +
42893          '`, ' +
42894          stringifyPosition$1({
42895            start: open.start,
42896            end: open.end
42897          }) +
42898          ') is open'
42899      )
42900    }
42901
42902    node.position.end = point(token.end);
42903    return node
42904  }
42905  /**
42906   * @this {CompileContext}
42907   * @returns {string}
42908   */
42909
42910  function resume() {
42911    return toString(this.stack.pop())
42912  } //
42913  // Handlers.
42914  //
42915
42916  /** @type {Handle} */
42917
42918  function onenterlistordered() {
42919    setData('expectingFirstListItemValue', true);
42920  }
42921  /** @type {Handle} */
42922
42923  function onenterlistitemvalue(token) {
42924    if (getData('expectingFirstListItemValue')) {
42925      this.stack[this.stack.length - 2].start = Number.parseInt(
42926        this.sliceSerialize(token),
42927        10
42928      );
42929      setData('expectingFirstListItemValue');
42930    }
42931  }
42932  /** @type {Handle} */
42933
42934  function onexitcodefencedfenceinfo() {
42935    const data = this.resume();
42936    this.stack[this.stack.length - 1].lang = data;
42937  }
42938  /** @type {Handle} */
42939
42940  function onexitcodefencedfencemeta() {
42941    const data = this.resume();
42942    this.stack[this.stack.length - 1].meta = data;
42943  }
42944  /** @type {Handle} */
42945
42946  function onexitcodefencedfence() {
42947    // Exit if this is the closing fence.
42948    if (getData('flowCodeInside')) return
42949    this.buffer();
42950    setData('flowCodeInside', true);
42951  }
42952  /** @type {Handle} */
42953
42954  function onexitcodefenced() {
42955    const data = this.resume();
42956    this.stack[this.stack.length - 1].value = data.replace(
42957      /^(\r?\n|\r)|(\r?\n|\r)$/g,
42958      ''
42959    );
42960    setData('flowCodeInside');
42961  }
42962  /** @type {Handle} */
42963
42964  function onexitcodeindented() {
42965    const data = this.resume();
42966    this.stack[this.stack.length - 1].value = data.replace(/(\r?\n|\r)$/g, '');
42967  }
42968  /** @type {Handle} */
42969
42970  function onexitdefinitionlabelstring(token) {
42971    // Discard label, use the source content instead.
42972    const label = this.resume();
42973    this.stack[this.stack.length - 1].label = label;
42974    this.stack[this.stack.length - 1].identifier = normalizeIdentifier(
42975      this.sliceSerialize(token)
42976    ).toLowerCase();
42977  }
42978  /** @type {Handle} */
42979
42980  function onexitdefinitiontitlestring() {
42981    const data = this.resume();
42982    this.stack[this.stack.length - 1].title = data;
42983  }
42984  /** @type {Handle} */
42985
42986  function onexitdefinitiondestinationstring() {
42987    const data = this.resume();
42988    this.stack[this.stack.length - 1].url = data;
42989  }
42990  /** @type {Handle} */
42991
42992  function onexitatxheadingsequence(token) {
42993    if (!this.stack[this.stack.length - 1].depth) {
42994      this.stack[this.stack.length - 1].depth =
42995        this.sliceSerialize(token).length;
42996    }
42997  }
42998  /** @type {Handle} */
42999
43000  function onexitsetextheadingtext() {
43001    setData('setextHeadingSlurpLineEnding', true);
43002  }
43003  /** @type {Handle} */
43004
43005  function onexitsetextheadinglinesequence(token) {
43006    this.stack[this.stack.length - 1].depth =
43007      this.sliceSerialize(token).charCodeAt(0) === 61 ? 1 : 2;
43008  }
43009  /** @type {Handle} */
43010
43011  function onexitsetextheading() {
43012    setData('setextHeadingSlurpLineEnding');
43013  }
43014  /** @type {Handle} */
43015
43016  function onenterdata(token) {
43017    /** @type {Parent} */
43018    // @ts-expect-error: assume parent.
43019    const parent = this.stack[this.stack.length - 1];
43020    /** @type {Node} */
43021    // @ts-expect-error: assume child.
43022
43023    let tail = parent.children[parent.children.length - 1];
43024
43025    if (!tail || tail.type !== 'text') {
43026      // Add a new text node.
43027      tail = text(); // @ts-expect-error: we’ll add `end` later.
43028
43029      tail.position = {
43030        start: point(token.start)
43031      };
43032      parent.children.push(tail);
43033    }
43034
43035    this.stack.push(tail);
43036  }
43037  /** @type {Handle} */
43038
43039  function onexitdata(token) {
43040    const tail = this.stack.pop();
43041    tail.value += this.sliceSerialize(token);
43042    tail.position.end = point(token.end);
43043  }
43044  /** @type {Handle} */
43045
43046  function onexitlineending(token) {
43047    /** @type {Parent} */
43048    // @ts-expect-error: supposed to be a parent.
43049    const context = this.stack[this.stack.length - 1];
43050
43051    // If we’re at a hard break, include the line ending in there.
43052    if (getData('atHardBreak')) {
43053      const tail = context.children[context.children.length - 1];
43054      tail.position.end = point(token.end);
43055      setData('atHardBreak');
43056      return
43057    }
43058
43059    if (
43060      !getData('setextHeadingSlurpLineEnding') &&
43061      config.canContainEols.includes(context.type)
43062    ) {
43063      onenterdata.call(this, token);
43064      onexitdata.call(this, token);
43065    }
43066  }
43067  /** @type {Handle} */
43068
43069  function onexithardbreak() {
43070    setData('atHardBreak', true);
43071  }
43072  /** @type {Handle} */
43073
43074  function onexithtmlflow() {
43075    const data = this.resume();
43076    this.stack[this.stack.length - 1].value = data;
43077  }
43078  /** @type {Handle} */
43079
43080  function onexithtmltext() {
43081    const data = this.resume();
43082    this.stack[this.stack.length - 1].value = data;
43083  }
43084  /** @type {Handle} */
43085
43086  function onexitcodetext() {
43087    const data = this.resume();
43088    this.stack[this.stack.length - 1].value = data;
43089  }
43090  /** @type {Handle} */
43091
43092  function onexitlink() {
43093    const context = this.stack[this.stack.length - 1]; // To do: clean.
43094
43095    if (getData('inReference')) {
43096      context.type += 'Reference';
43097      context.referenceType = getData('referenceType') || 'shortcut';
43098      delete context.url;
43099      delete context.title;
43100    } else {
43101      delete context.identifier;
43102      delete context.label;
43103      delete context.referenceType;
43104    }
43105
43106    setData('referenceType');
43107  }
43108  /** @type {Handle} */
43109
43110  function onexitimage() {
43111    const context = this.stack[this.stack.length - 1]; // To do: clean.
43112
43113    if (getData('inReference')) {
43114      context.type += 'Reference';
43115      context.referenceType = getData('referenceType') || 'shortcut';
43116      delete context.url;
43117      delete context.title;
43118    } else {
43119      delete context.identifier;
43120      delete context.label;
43121      delete context.referenceType;
43122    }
43123
43124    setData('referenceType');
43125  }
43126  /** @type {Handle} */
43127
43128  function onexitlabeltext(token) {
43129    this.stack[this.stack.length - 2].identifier = normalizeIdentifier(
43130      this.sliceSerialize(token)
43131    ).toLowerCase();
43132  }
43133  /** @type {Handle} */
43134
43135  function onexitlabel() {
43136    const fragment = this.stack[this.stack.length - 1];
43137    const value = this.resume();
43138    this.stack[this.stack.length - 1].label = value; // Assume a reference.
43139
43140    setData('inReference', true);
43141
43142    if (this.stack[this.stack.length - 1].type === 'link') {
43143      this.stack[this.stack.length - 1].children = fragment.children;
43144    } else {
43145      this.stack[this.stack.length - 1].alt = value;
43146    }
43147  }
43148  /** @type {Handle} */
43149
43150  function onexitresourcedestinationstring() {
43151    const data = this.resume();
43152    this.stack[this.stack.length - 1].url = data;
43153  }
43154  /** @type {Handle} */
43155
43156  function onexitresourcetitlestring() {
43157    const data = this.resume();
43158    this.stack[this.stack.length - 1].title = data;
43159  }
43160  /** @type {Handle} */
43161
43162  function onexitresource() {
43163    setData('inReference');
43164  }
43165  /** @type {Handle} */
43166
43167  function onenterreference() {
43168    setData('referenceType', 'collapsed');
43169  }
43170  /** @type {Handle} */
43171
43172  function onexitreferencestring(token) {
43173    const label = this.resume();
43174    this.stack[this.stack.length - 1].label = label;
43175    this.stack[this.stack.length - 1].identifier = normalizeIdentifier(
43176      this.sliceSerialize(token)
43177    ).toLowerCase();
43178    setData('referenceType', 'full');
43179  }
43180  /** @type {Handle} */
43181
43182  function onexitcharacterreferencemarker(token) {
43183    setData('characterReferenceType', token.type);
43184  }
43185  /** @type {Handle} */
43186
43187  function onexitcharacterreferencevalue(token) {
43188    const data = this.sliceSerialize(token);
43189    const type = getData('characterReferenceType');
43190    /** @type {string} */
43191
43192    let value;
43193
43194    if (type) {
43195      value = decodeNumericCharacterReference(
43196        data,
43197        type === 'characterReferenceMarkerNumeric' ? 10 : 16
43198      );
43199      setData('characterReferenceType');
43200    } else {
43201      // @ts-expect-error `decodeEntity` can return false for invalid named
43202      // character references, but everything we’ve tokenized is valid.
43203      value = decodeEntity(data);
43204    }
43205
43206    const tail = this.stack.pop();
43207    tail.value += value;
43208    tail.position.end = point(token.end);
43209  }
43210  /** @type {Handle} */
43211
43212  function onexitautolinkprotocol(token) {
43213    onexitdata.call(this, token);
43214    this.stack[this.stack.length - 1].url = this.sliceSerialize(token);
43215  }
43216  /** @type {Handle} */
43217
43218  function onexitautolinkemail(token) {
43219    onexitdata.call(this, token);
43220    this.stack[this.stack.length - 1].url =
43221      'mailto:' + this.sliceSerialize(token);
43222  } //
43223  // Creaters.
43224  //
43225
43226  /** @returns {Blockquote} */
43227
43228  function blockQuote() {
43229    return {
43230      type: 'blockquote',
43231      children: []
43232    }
43233  }
43234  /** @returns {Code} */
43235
43236  function codeFlow() {
43237    // @ts-expect-error: we’ve always used `null`.
43238    return {
43239      type: 'code',
43240      lang: null,
43241      meta: null,
43242      value: ''
43243    }
43244  }
43245  /** @returns {InlineCode} */
43246
43247  function codeText() {
43248    return {
43249      type: 'inlineCode',
43250      value: ''
43251    }
43252  }
43253  /** @returns {Definition} */
43254
43255  function definition() {
43256    return {
43257      type: 'definition',
43258      identifier: '',
43259      // @ts-expect-error: we’ve always used `null`.
43260      label: null,
43261      // @ts-expect-error: we’ve always used `null`.
43262      title: null,
43263      url: ''
43264    }
43265  }
43266  /** @returns {Emphasis} */
43267
43268  function emphasis() {
43269    return {
43270      type: 'emphasis',
43271      children: []
43272    }
43273  }
43274  /** @returns {Heading} */
43275
43276  function heading() {
43277    // @ts-expect-error `depth` will be set later.
43278    return {
43279      type: 'heading',
43280      depth: undefined,
43281      children: []
43282    }
43283  }
43284  /** @returns {Break} */
43285
43286  function hardBreak() {
43287    return {
43288      type: 'break'
43289    }
43290  }
43291  /** @returns {HTML} */
43292
43293  function html() {
43294    return {
43295      type: 'html',
43296      value: ''
43297    }
43298  }
43299  /** @returns {Image} */
43300
43301  function image() {
43302    // @ts-expect-error: we’ve always used `null`.
43303    return {
43304      type: 'image',
43305      title: null,
43306      url: '',
43307      alt: null
43308    }
43309  }
43310  /** @returns {Link} */
43311
43312  function link() {
43313    // @ts-expect-error: we’ve always used `null`.
43314    return {
43315      type: 'link',
43316      title: null,
43317      url: '',
43318      children: []
43319    }
43320  }
43321  /**
43322   * @param {Token} token
43323   * @returns {List}
43324   */
43325
43326  function list(token) {
43327    return {
43328      type: 'list',
43329      ordered: token.type === 'listOrdered',
43330      // @ts-expect-error: we’ve always used `null`.
43331      start: null,
43332      // @ts-expect-error Patched.
43333      spread: token._spread,
43334      children: []
43335    }
43336  }
43337  /**
43338   * @param {Token} token
43339   * @returns {ListItem}
43340   */
43341
43342  function listItem(token) {
43343    return {
43344      type: 'listItem',
43345      // @ts-expect-error Patched.
43346      spread: token._spread,
43347      // @ts-expect-error: we’ve always used `null`.
43348      checked: null,
43349      children: []
43350    }
43351  }
43352  /** @returns {Paragraph} */
43353
43354  function paragraph() {
43355    return {
43356      type: 'paragraph',
43357      children: []
43358    }
43359  }
43360  /** @returns {Strong} */
43361
43362  function strong() {
43363    return {
43364      type: 'strong',
43365      children: []
43366    }
43367  }
43368  /** @returns {Text} */
43369
43370  function text() {
43371    return {
43372      type: 'text',
43373      value: ''
43374    }
43375  }
43376  /** @returns {ThematicBreak} */
43377
43378  function thematicBreak() {
43379    return {
43380      type: 'thematicBreak'
43381    }
43382  }
43383}
43384/**
43385 * @param {Extension} combined
43386 * @param {Array.<Extension|Array.<Extension>>} extensions
43387 * @returns {Extension}
43388 */
43389
43390function configure$1(combined, extensions) {
43391  let index = -1;
43392
43393  while (++index < extensions.length) {
43394    const value = extensions[index];
43395
43396    if (Array.isArray(value)) {
43397      configure$1(combined, value);
43398    } else {
43399      extension(combined, value);
43400    }
43401  }
43402
43403  return combined
43404}
43405/**
43406 * @param {Extension} combined
43407 * @param {Extension} extension
43408 * @returns {void}
43409 */
43410
43411function extension(combined, extension) {
43412  /** @type {string} */
43413  let key;
43414
43415  for (key in extension) {
43416    if (own$4.call(extension, key)) {
43417      const list = key === 'canContainEols' || key === 'transforms';
43418      const maybe = own$4.call(combined, key) ? combined[key] : undefined;
43419      /* c8 ignore next */
43420
43421      const left = maybe || (combined[key] = list ? [] : {});
43422      const right = extension[key];
43423
43424      if (right) {
43425        if (list) {
43426          // @ts-expect-error: `left` is an array.
43427          combined[key] = [...left, ...right];
43428        } else {
43429          Object.assign(left, right);
43430        }
43431      }
43432    }
43433  }
43434}
43435
43436/**
43437 * @typedef {import('mdast').Root} Root
43438 * @typedef {import('mdast-util-from-markdown').Options} Options
43439 */
43440
43441/** @type {import('unified').Plugin<[Options?] | void[], string, Root>} */
43442function remarkParse(options) {
43443  /** @type {import('unified').ParserFunction<Root>} */
43444  const parser = (doc) => {
43445    // Assume options.
43446    const settings = /** @type {Options} */ (this.data('settings'));
43447
43448    return fromMarkdown(
43449      doc,
43450      Object.assign({}, settings, options, {
43451        // Note: these options are not in the readme.
43452        // The goal is for them to be set by plugins on `data` instead of being
43453        // passed by users.
43454        extensions: this.data('micromarkExtensions') || [],
43455        mdastExtensions: this.data('fromMarkdownExtensions') || []
43456      })
43457    )
43458  };
43459
43460  Object.assign(this, {Parser: parser});
43461}
43462
43463var own$3 = {}.hasOwnProperty;
43464
43465/**
43466 * @callback Handler
43467 * @param {...unknown} value
43468 * @return {unknown}
43469 *
43470 * @typedef {Record<string, Handler>} Handlers
43471 *
43472 * @typedef {Object} Options
43473 * @property {Handler} [unknown]
43474 * @property {Handler} [invalid]
43475 * @property {Handlers} [handlers]
43476 */
43477
43478/**
43479 * Handle values based on a property.
43480 *
43481 * @param {string} key
43482 * @param {Options} [options]
43483 */
43484function zwitch(key, options) {
43485  var settings = options || {};
43486
43487  /**
43488   * Handle one value.
43489   * Based on the bound `key`, a respective handler will be called.
43490   * If `value` is not an object, or doesn’t have a `key` property, the special
43491   * “invalid” handler will be called.
43492   * If `value` has an unknown `key`, the special “unknown” handler will be
43493   * called.
43494   *
43495   * All arguments, and the context object, are passed through to the handler,
43496   * and it’s result is returned.
43497   *
43498   * @param {...unknown} [value]
43499   * @this {unknown}
43500   * @returns {unknown}
43501   * @property {Handler} invalid
43502   * @property {Handler} unknown
43503   * @property {Handlers} handlers
43504   */
43505  function one(value) {
43506    var fn = one.invalid;
43507    var handlers = one.handlers;
43508
43509    if (value && own$3.call(value, key)) {
43510      fn = own$3.call(handlers, value[key]) ? handlers[value[key]] : one.unknown;
43511    }
43512
43513    if (fn) {
43514      return fn.apply(this, arguments)
43515    }
43516  }
43517
43518  one.handlers = settings.handlers || {};
43519  one.invalid = settings.invalid;
43520  one.unknown = settings.unknown;
43521
43522  return one
43523}
43524
43525/**
43526 * @typedef {import('./types.js').Options} Options
43527 * @typedef {import('./types.js').Context} Context
43528 */
43529
43530/**
43531 * @param {Context} base
43532 * @param {Options} extension
43533 * @returns {Context}
43534 */
43535function configure(base, extension) {
43536  let index = -1;
43537  /** @type {string} */
43538  let key;
43539
43540  // First do subextensions.
43541  if (extension.extensions) {
43542    while (++index < extension.extensions.length) {
43543      configure(base, extension.extensions[index]);
43544    }
43545  }
43546
43547  for (key in extension) {
43548    if (key === 'extensions') ; else if (key === 'unsafe' || key === 'join') {
43549      /* c8 ignore next 2 */
43550      // @ts-expect-error: hush.
43551      base[key] = [...(base[key] || []), ...(extension[key] || [])];
43552    } else if (key === 'handlers') {
43553      base[key] = Object.assign(base[key], extension[key] || {});
43554    } else {
43555      // @ts-expect-error: hush.
43556      base.options[key] = extension[key];
43557    }
43558  }
43559
43560  return base
43561}
43562
43563/**
43564 * @typedef {import('../types.js').Node} Node
43565 * @typedef {import('../types.js').Parent} Parent
43566 * @typedef {import('../types.js').Join} Join
43567 * @typedef {import('../types.js').Context} Context
43568 */
43569
43570/**
43571 * @param {Parent} parent
43572 * @param {Context} context
43573 * @returns {string}
43574 */
43575function containerFlow(parent, context) {
43576  const children = parent.children || [];
43577  /** @type {Array.<string>} */
43578  const results = [];
43579  let index = -1;
43580
43581  while (++index < children.length) {
43582    const child = children[index];
43583
43584    results.push(
43585      context.handle(child, parent, context, {before: '\n', after: '\n'})
43586    );
43587
43588    if (index < children.length - 1) {
43589      results.push(between(child, children[index + 1]));
43590    }
43591  }
43592
43593  return results.join('')
43594
43595  /**
43596   * @param {Node} left
43597   * @param {Node} right
43598   * @returns {string}
43599   */
43600  function between(left, right) {
43601    let index = context.join.length;
43602    /** @type {ReturnType<Join>} */
43603    let result;
43604
43605    while (index--) {
43606      result = context.join[index](left, right, parent, context);
43607
43608      if (result === true || result === 1) {
43609        break
43610      }
43611
43612      if (typeof result === 'number') {
43613        return '\n'.repeat(1 + result)
43614      }
43615
43616      if (result === false) {
43617        return '\n\n<!---->\n\n'
43618      }
43619    }
43620
43621    return '\n\n'
43622  }
43623}
43624
43625/**
43626 * @callback Map
43627 * @param {string} value
43628 * @param {number} line
43629 * @param {boolean} blank
43630 * @returns {string}
43631 */
43632
43633const eol = /\r?\n|\r/g;
43634
43635/**
43636 * @param {string} value
43637 * @param {Map} map
43638 * @returns {string}
43639 */
43640function indentLines(value, map) {
43641  /** @type {Array.<string>} */
43642  const result = [];
43643  let start = 0;
43644  let line = 0;
43645  /** @type {RegExpExecArray|null} */
43646  let match;
43647
43648  while ((match = eol.exec(value))) {
43649    one(value.slice(start, match.index));
43650    result.push(match[0]);
43651    start = match.index + match[0].length;
43652    line++;
43653  }
43654
43655  one(value.slice(start));
43656
43657  return result.join('')
43658
43659  /**
43660   * @param {string} value
43661   */
43662  function one(value) {
43663    result.push(map(value, line, !value));
43664  }
43665}
43666
43667/**
43668 * @typedef {import('mdast').Blockquote} Blockquote
43669 * @typedef {import('../types.js').Handle} Handle
43670 * @typedef {import('../util/indent-lines.js').Map} Map
43671 */
43672
43673/**
43674 * @type {Handle}
43675 * @param {Blockquote} node
43676 */
43677function blockquote(node, _, context) {
43678  const exit = context.enter('blockquote');
43679  const value = indentLines(containerFlow(node, context), map$1);
43680  exit();
43681  return value
43682}
43683
43684/** @type {Map} */
43685function map$1(line, _, blank) {
43686  return '>' + (blank ? '' : ' ') + line
43687}
43688
43689/**
43690 * @typedef {import('../types.js').Unsafe} Unsafe
43691 */
43692
43693/**
43694 * @param {Array.<string>} stack
43695 * @param {Unsafe} pattern
43696 * @returns {boolean}
43697 */
43698function patternInScope(stack, pattern) {
43699  return (
43700    listInScope(stack, pattern.inConstruct, true) &&
43701    !listInScope(stack, pattern.notInConstruct, false)
43702  )
43703}
43704
43705/**
43706 * @param {Array.<string>} stack
43707 * @param {Unsafe['inConstruct']} list
43708 * @param {boolean} none
43709 * @returns {boolean}
43710 */
43711function listInScope(stack, list, none) {
43712  if (!list) {
43713    return none
43714  }
43715
43716  if (typeof list === 'string') {
43717    list = [list];
43718  }
43719
43720  let index = -1;
43721
43722  while (++index < list.length) {
43723    if (stack.includes(list[index])) {
43724      return true
43725    }
43726  }
43727
43728  return false
43729}
43730
43731/**
43732 * @typedef {import('../types.js').Handle} Handle
43733 * @typedef {import('mdast').Break} Break
43734 */
43735
43736/**
43737 * @type {Handle}
43738 * @param {Break} _
43739 */
43740function hardBreak(_, _1, context, safe) {
43741  let index = -1;
43742
43743  while (++index < context.unsafe.length) {
43744    // If we can’t put eols in this construct (setext headings, tables), use a
43745    // space instead.
43746    if (
43747      context.unsafe[index].character === '\n' &&
43748      patternInScope(context.stack, context.unsafe[index])
43749    ) {
43750      return /[ \t]/.test(safe.before) ? '' : ' '
43751    }
43752  }
43753
43754  return '\\\n'
43755}
43756
43757/**
43758 * Get the count of the longest repeating streak of `character` in `value`.
43759 *
43760 * @param {string} value Content.
43761 * @param {string} character Single character to look for
43762 * @returns {number} Count of most frequent adjacent `character`s in `value`
43763 */
43764function longestStreak(value, character) {
43765  var source = String(value);
43766  var index = source.indexOf(character);
43767  var expected = index;
43768  var count = 0;
43769  var max = 0;
43770
43771  if (typeof character !== 'string' || character.length !== 1) {
43772    throw new Error('Expected character')
43773  }
43774
43775  while (index !== -1) {
43776    if (index === expected) {
43777      if (++count > max) {
43778        max = count;
43779      }
43780    } else {
43781      count = 1;
43782    }
43783
43784    expected = index + 1;
43785    index = source.indexOf(character, expected);
43786  }
43787
43788  return max
43789}
43790
43791/**
43792 * @typedef {import('mdast').Code} Code
43793 * @typedef {import('../types.js').Context} Context
43794 */
43795
43796/**
43797 * @param {Code} node
43798 * @param {Context} context
43799 * @returns {boolean}
43800 */
43801function formatCodeAsIndented(node, context) {
43802  return Boolean(
43803    !context.options.fences &&
43804      node.value &&
43805      // If there’s no info…
43806      !node.lang &&
43807      // And there’s a non-whitespace character…
43808      /[^ \r\n]/.test(node.value) &&
43809      // And the value doesn’t start or end in a blank…
43810      !/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(node.value)
43811  )
43812}
43813
43814/**
43815 * @typedef {import('../types.js').Context} Context
43816 * @typedef {import('../types.js').Options} Options
43817 */
43818
43819/**
43820 * @param {Context} context
43821 * @returns {Exclude<Options['fence'], undefined>}
43822 */
43823function checkFence(context) {
43824  const marker = context.options.fence || '`';
43825
43826  if (marker !== '`' && marker !== '~') {
43827    throw new Error(
43828      'Cannot serialize code with `' +
43829        marker +
43830        '` for `options.fence`, expected `` ` `` or `~`'
43831    )
43832  }
43833
43834  return marker
43835}
43836
43837/**
43838 * @typedef {import('../types.js').Unsafe} Unsafe
43839 */
43840
43841/**
43842 * @param {Unsafe} pattern
43843 * @returns {RegExp}
43844 */
43845function patternCompile(pattern) {
43846  if (!pattern._compiled) {
43847    const before =
43848      (pattern.atBreak ? '[\\r\\n][\\t ]*' : '') +
43849      (pattern.before ? '(?:' + pattern.before + ')' : '');
43850
43851    pattern._compiled = new RegExp(
43852      (before ? '(' + before + ')' : '') +
43853        (/[|\\{}()[\]^$+*?.-]/.test(pattern.character) ? '\\' : '') +
43854        pattern.character +
43855        (pattern.after ? '(?:' + pattern.after + ')' : ''),
43856      'g'
43857    );
43858  }
43859
43860  return pattern._compiled
43861}
43862
43863/**
43864 * @typedef {import('../types.js').Context} Context
43865 * @typedef {import('../types.js').SafeOptions} SafeOptions
43866 */
43867
43868/**
43869 * @param {Context} context
43870 * @param {string|null|undefined} input
43871 * @param {SafeOptions & {encode?: Array.<string>}} config
43872 * @returns {string}
43873 */
43874function safe(context, input, config) {
43875  const value = (config.before || '') + (input || '') + (config.after || '');
43876  /** @type {Array.<number>} */
43877  const positions = [];
43878  /** @type {Array.<string>} */
43879  const result = [];
43880  /** @type {Record<number, {before: boolean, after: boolean}>} */
43881  const infos = {};
43882  let index = -1;
43883
43884  while (++index < context.unsafe.length) {
43885    const pattern = context.unsafe[index];
43886
43887    if (!patternInScope(context.stack, pattern)) {
43888      continue
43889    }
43890
43891    const expression = patternCompile(pattern);
43892    /** @type {RegExpExecArray|null} */
43893    let match;
43894
43895    while ((match = expression.exec(value))) {
43896      const before = 'before' in pattern || Boolean(pattern.atBreak);
43897      const after = 'after' in pattern;
43898      const position = match.index + (before ? match[1].length : 0);
43899
43900      if (positions.includes(position)) {
43901        if (infos[position].before && !before) {
43902          infos[position].before = false;
43903        }
43904
43905        if (infos[position].after && !after) {
43906          infos[position].after = false;
43907        }
43908      } else {
43909        positions.push(position);
43910        infos[position] = {before, after};
43911      }
43912    }
43913  }
43914
43915  positions.sort(numerical);
43916
43917  let start = config.before ? config.before.length : 0;
43918  const end = value.length - (config.after ? config.after.length : 0);
43919  index = -1;
43920
43921  while (++index < positions.length) {
43922    const position = positions[index];
43923
43924    // Character before or after matched:
43925    if (position < start || position >= end) {
43926      continue
43927    }
43928
43929    // If this character is supposed to be escaped because it has a condition on
43930    // the next character, and the next character is definitly being escaped,
43931    // then skip this escape.
43932    if (
43933      position + 1 < end &&
43934      positions[index + 1] === position + 1 &&
43935      infos[position].after &&
43936      !infos[position + 1].before &&
43937      !infos[position + 1].after
43938    ) {
43939      continue
43940    }
43941
43942    if (start !== position) {
43943      // If we have to use a character reference, an ampersand would be more
43944      // correct, but as backslashes only care about punctuation, either will
43945      // do the trick
43946      result.push(escapeBackslashes(value.slice(start, position), '\\'));
43947    }
43948
43949    start = position;
43950
43951    if (
43952      /[!-/:-@[-`{-~]/.test(value.charAt(position)) &&
43953      (!config.encode || !config.encode.includes(value.charAt(position)))
43954    ) {
43955      // Character escape.
43956      result.push('\\');
43957    } else {
43958      // Character reference.
43959      result.push(
43960        '&#x' + value.charCodeAt(position).toString(16).toUpperCase() + ';'
43961      );
43962      start++;
43963    }
43964  }
43965
43966  result.push(escapeBackslashes(value.slice(start, end), config.after));
43967
43968  return result.join('')
43969}
43970
43971/**
43972 * @param {number} a
43973 * @param {number} b
43974 * @returns {number}
43975 */
43976function numerical(a, b) {
43977  return a - b
43978}
43979
43980/**
43981 * @param {string} value
43982 * @param {string} after
43983 * @returns {string}
43984 */
43985function escapeBackslashes(value, after) {
43986  const expression = /\\(?=[!-/:-@[-`{-~])/g;
43987  /** @type {Array.<number>} */
43988  const positions = [];
43989  /** @type {Array.<string>} */
43990  const results = [];
43991  const whole = value + after;
43992  let index = -1;
43993  let start = 0;
43994  /** @type {RegExpExecArray|null} */
43995  let match;
43996
43997  while ((match = expression.exec(whole))) {
43998    positions.push(match.index);
43999  }
44000
44001  while (++index < positions.length) {
44002    if (start !== positions[index]) {
44003      results.push(value.slice(start, positions[index]));
44004    }
44005
44006    results.push('\\');
44007    start = positions[index];
44008  }
44009
44010  results.push(value.slice(start));
44011
44012  return results.join('')
44013}
44014
44015/**
44016 * @typedef {import('mdast').Code} Code
44017 * @typedef {import('../types.js').Handle} Handle
44018 * @typedef {import('../types.js').Exit} Exit
44019 * @typedef {import('../util/indent-lines.js').Map} Map
44020 */
44021
44022/**
44023 * @type {Handle}
44024 * @param {Code} node
44025 */
44026function code$1(node, _, context) {
44027  const marker = checkFence(context);
44028  const raw = node.value || '';
44029  const suffix = marker === '`' ? 'GraveAccent' : 'Tilde';
44030  /** @type {string} */
44031  let value;
44032  /** @type {Exit} */
44033  let exit;
44034
44035  if (formatCodeAsIndented(node, context)) {
44036    exit = context.enter('codeIndented');
44037    value = indentLines(raw, map);
44038  } else {
44039    const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3));
44040    /** @type {Exit} */
44041    let subexit;
44042    exit = context.enter('codeFenced');
44043    value = sequence;
44044
44045    if (node.lang) {
44046      subexit = context.enter('codeFencedLang' + suffix);
44047      value += safe(context, node.lang, {
44048        before: '`',
44049        after: ' ',
44050        encode: ['`']
44051      });
44052      subexit();
44053    }
44054
44055    if (node.lang && node.meta) {
44056      subexit = context.enter('codeFencedMeta' + suffix);
44057      value +=
44058        ' ' +
44059        safe(context, node.meta, {
44060          before: ' ',
44061          after: '\n',
44062          encode: ['`']
44063        });
44064      subexit();
44065    }
44066
44067    value += '\n';
44068
44069    if (raw) {
44070      value += raw + '\n';
44071    }
44072
44073    value += sequence;
44074  }
44075
44076  exit();
44077  return value
44078}
44079
44080/** @type {Map} */
44081function map(line, _, blank) {
44082  return (blank ? '' : '    ') + line
44083}
44084
44085/**
44086 * @typedef {import('mdast').Association} Association
44087 */
44088
44089const characterEscape = /\\([!-/:-@[-`{-~])/g;
44090const characterReference = /&(#(\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;
44091
44092/**
44093 * The `label` of an association is the string value: character escapes and
44094 * references work, and casing is intact.
44095 * The `identifier` is used to match one association to another: controversially,
44096 * character escapes and references don’t work in this matching: `&copy;` does
44097 * not match `©`, and `\+` does not match `+`.
44098 * But casing is ignored (and whitespace) is trimmed and collapsed: ` A\nb`
44099 * matches `a b`.
44100 * So, we do prefer the label when figuring out how we’re going to serialize:
44101 * it has whitespace, casing, and we can ignore most useless character escapes
44102 * and all character references.
44103 *
44104 * @param {Association} node
44105 * @returns {string}
44106 */
44107function association(node) {
44108  if (node.label || !node.identifier) {
44109    return node.label || ''
44110  }
44111
44112  return node.identifier
44113    .replace(characterEscape, '$1')
44114    .replace(characterReference, decodeIfPossible)
44115}
44116
44117/**
44118 * @param {string} $0
44119 * @param {string} $1
44120 * @returns {string}
44121 */
44122function decodeIfPossible($0, $1) {
44123  return decodeEntity($1) || $0
44124}
44125
44126/**
44127 * @typedef {import('../types.js').Context} Context
44128 * @typedef {import('../types.js').Options} Options
44129 */
44130
44131/**
44132 * @param {Context} context
44133 * @returns {Exclude<Options['quote'], undefined>}
44134 */
44135function checkQuote(context) {
44136  const marker = context.options.quote || '"';
44137
44138  if (marker !== '"' && marker !== "'") {
44139    throw new Error(
44140      'Cannot serialize title with `' +
44141        marker +
44142        '` for `options.quote`, expected `"`, or `\'`'
44143    )
44144  }
44145
44146  return marker
44147}
44148
44149/**
44150 * @typedef {import('mdast').Definition} Definition
44151 * @typedef {import('../types.js').Handle} Handle
44152 */
44153
44154/**
44155 * @type {Handle}
44156 * @param {Definition} node
44157 */
44158function definition(node, _, context) {
44159  const marker = checkQuote(context);
44160  const suffix = marker === '"' ? 'Quote' : 'Apostrophe';
44161  const exit = context.enter('definition');
44162  let subexit = context.enter('label');
44163  let value =
44164    '[' + safe(context, association(node), {before: '[', after: ']'}) + ']: ';
44165
44166  subexit();
44167
44168  if (
44169    // If there’s no url, or…
44170    !node.url ||
44171    // If there’s whitespace, enclosed is prettier.
44172    /[ \t\r\n]/.test(node.url)
44173  ) {
44174    subexit = context.enter('destinationLiteral');
44175    value += '<' + safe(context, node.url, {before: '<', after: '>'}) + '>';
44176  } else {
44177    // No whitespace, raw is prettier.
44178    subexit = context.enter('destinationRaw');
44179    value += safe(context, node.url, {before: ' ', after: ' '});
44180  }
44181
44182  subexit();
44183
44184  if (node.title) {
44185    subexit = context.enter('title' + suffix);
44186    value +=
44187      ' ' +
44188      marker +
44189      safe(context, node.title, {before: marker, after: marker}) +
44190      marker;
44191    subexit();
44192  }
44193
44194  exit();
44195
44196  return value
44197}
44198
44199/**
44200 * @typedef {import('../types.js').Context} Context
44201 * @typedef {import('../types.js').Options} Options
44202 */
44203
44204/**
44205 * @param {Context} context
44206 * @returns {Exclude<Options['emphasis'], undefined>}
44207 */
44208function checkEmphasis(context) {
44209  const marker = context.options.emphasis || '*';
44210
44211  if (marker !== '*' && marker !== '_') {
44212    throw new Error(
44213      'Cannot serialize emphasis with `' +
44214        marker +
44215        '` for `options.emphasis`, expected `*`, or `_`'
44216    )
44217  }
44218
44219  return marker
44220}
44221
44222/**
44223 * @typedef {import('../types.js').Node} Node
44224 * @typedef {import('../types.js').Parent} Parent
44225 * @typedef {import('../types.js').SafeOptions} SafeOptions
44226 * @typedef {import('../types.js').Context} Context
44227 */
44228
44229/**
44230 * @param {Parent} parent
44231 * @param {Context} context
44232 * @param {SafeOptions} safeOptions
44233 * @returns {string}
44234 */
44235function containerPhrasing(parent, context, safeOptions) {
44236  const children = parent.children || [];
44237  /** @type {Array.<string>} */
44238  const results = [];
44239  let index = -1;
44240  let before = safeOptions.before;
44241
44242  while (++index < children.length) {
44243    const child = children[index];
44244    /** @type {string} */
44245    let after;
44246
44247    if (index + 1 < children.length) {
44248      // @ts-expect-error: hush, it’s actually a `zwitch`.
44249      let handle = context.handle.handlers[children[index + 1].type];
44250      if (handle && handle.peek) handle = handle.peek;
44251      after = handle
44252        ? handle(children[index + 1], parent, context, {
44253            before: '',
44254            after: ''
44255          }).charAt(0)
44256        : '';
44257    } else {
44258      after = safeOptions.after;
44259    }
44260
44261    // In some cases, html (text) can be found in phrasing right after an eol.
44262    // When we’d serialize that, in most cases that would be seen as html
44263    // (flow).
44264    // As we can’t escape or so to prevent it from happening, we take a somewhat
44265    // reasonable approach: replace that eol with a space.
44266    // See: <https://github.com/syntax-tree/mdast-util-to-markdown/issues/15>
44267    if (
44268      results.length > 0 &&
44269      (before === '\r' || before === '\n') &&
44270      child.type === 'html'
44271    ) {
44272      results[results.length - 1] = results[results.length - 1].replace(
44273        /(\r?\n|\r)$/,
44274        ' '
44275      );
44276      before = ' ';
44277    }
44278
44279    results.push(context.handle(child, parent, context, {before, after}));
44280
44281    before = results[results.length - 1].slice(-1);
44282  }
44283
44284  return results.join('')
44285}
44286
44287/**
44288 * @typedef {import('mdast').Emphasis} Emphasis
44289 * @typedef {import('../types.js').Handle} Handle
44290 */
44291
44292emphasis.peek = emphasisPeek;
44293
44294// To do: there are cases where emphasis cannot “form” depending on the
44295// previous or next character of sequences.
44296// There’s no way around that though, except for injecting zero-width stuff.
44297// Do we need to safeguard against that?
44298/**
44299 * @type {Handle}
44300 * @param {Emphasis} node
44301 */
44302function emphasis(node, _, context) {
44303  const marker = checkEmphasis(context);
44304  const exit = context.enter('emphasis');
44305  const value = containerPhrasing(node, context, {
44306    before: marker,
44307    after: marker
44308  });
44309  exit();
44310  return marker + value + marker
44311}
44312
44313/**
44314 * @type {Handle}
44315 * @param {Emphasis} _
44316 */
44317function emphasisPeek(_, _1, context) {
44318  return context.options.emphasis || '*'
44319}
44320
44321/**
44322 * @typedef {import('mdast').Heading} Heading
44323 * @typedef {import('../types.js').Context} Context
44324 */
44325
44326/**
44327 * @param {Heading} node
44328 * @param {Context} context
44329 * @returns {boolean}
44330 */
44331function formatHeadingAsSetext(node, context) {
44332  return Boolean(
44333    context.options.setext && (!node.depth || node.depth < 3) && toString(node)
44334  )
44335}
44336
44337/**
44338 * @typedef {import('mdast').Heading} Heading
44339 * @typedef {import('../types.js').Handle} Handle
44340 * @typedef {import('../types.js').Exit} Exit
44341 */
44342
44343/**
44344 * @type {Handle}
44345 * @param {Heading} node
44346 */
44347function heading(node, _, context) {
44348  const rank = Math.max(Math.min(6, node.depth || 1), 1);
44349  /** @type {Exit} */
44350  let exit;
44351  /** @type {Exit} */
44352  let subexit;
44353  /** @type {string} */
44354  let value;
44355
44356  if (formatHeadingAsSetext(node, context)) {
44357    exit = context.enter('headingSetext');
44358    subexit = context.enter('phrasing');
44359    value = containerPhrasing(node, context, {before: '\n', after: '\n'});
44360    subexit();
44361    exit();
44362
44363    return (
44364      value +
44365      '\n' +
44366      (rank === 1 ? '=' : '-').repeat(
44367        // The whole size…
44368        value.length -
44369          // Minus the position of the character after the last EOL (or
44370          // 0 if there is none)…
44371          (Math.max(value.lastIndexOf('\r'), value.lastIndexOf('\n')) + 1)
44372      )
44373    )
44374  }
44375
44376  const sequence = '#'.repeat(rank);
44377  exit = context.enter('headingAtx');
44378  subexit = context.enter('phrasing');
44379  value = containerPhrasing(node, context, {before: '# ', after: '\n'});
44380  value = value ? sequence + ' ' + value : sequence;
44381  if (context.options.closeAtx) {
44382    value += ' ' + sequence;
44383  }
44384
44385  subexit();
44386  exit();
44387
44388  return value
44389}
44390
44391/**
44392 * @typedef {import('mdast').HTML} HTML
44393 * @typedef {import('../types.js').Handle} Handle
44394 */
44395
44396html.peek = htmlPeek;
44397
44398/**
44399 * @type {Handle}
44400 * @param {HTML} node
44401 */
44402function html(node) {
44403  return node.value || ''
44404}
44405
44406/**
44407 * @type {Handle}
44408 */
44409function htmlPeek() {
44410  return '<'
44411}
44412
44413/**
44414 * @typedef {import('mdast').Image} Image
44415 * @typedef {import('../types.js').Handle} Handle
44416 */
44417
44418image.peek = imagePeek;
44419
44420/**
44421 * @type {Handle}
44422 * @param {Image} node
44423 */
44424function image(node, _, context) {
44425  const quote = checkQuote(context);
44426  const suffix = quote === '"' ? 'Quote' : 'Apostrophe';
44427  const exit = context.enter('image');
44428  let subexit = context.enter('label');
44429  let value = '![' + safe(context, node.alt, {before: '[', after: ']'}) + '](';
44430
44431  subexit();
44432
44433  if (
44434    // If there’s no url but there is a title…
44435    (!node.url && node.title) ||
44436    // Or if there’s markdown whitespace or an eol, enclose.
44437    /[ \t\r\n]/.test(node.url)
44438  ) {
44439    subexit = context.enter('destinationLiteral');
44440    value += '<' + safe(context, node.url, {before: '<', after: '>'}) + '>';
44441  } else {
44442    // No whitespace, raw is prettier.
44443    subexit = context.enter('destinationRaw');
44444    value += safe(context, node.url, {
44445      before: '(',
44446      after: node.title ? ' ' : ')'
44447    });
44448  }
44449
44450  subexit();
44451
44452  if (node.title) {
44453    subexit = context.enter('title' + suffix);
44454    value +=
44455      ' ' +
44456      quote +
44457      safe(context, node.title, {before: quote, after: quote}) +
44458      quote;
44459    subexit();
44460  }
44461
44462  value += ')';
44463  exit();
44464
44465  return value
44466}
44467
44468/**
44469 * @type {Handle}
44470 */
44471function imagePeek() {
44472  return '!'
44473}
44474
44475/**
44476 * @typedef {import('mdast').ImageReference} ImageReference
44477 * @typedef {import('../types.js').Handle} Handle
44478 */
44479
44480imageReference.peek = imageReferencePeek;
44481
44482/**
44483 * @type {Handle}
44484 * @param {ImageReference} node
44485 */
44486function imageReference(node, _, context) {
44487  const type = node.referenceType;
44488  const exit = context.enter('imageReference');
44489  let subexit = context.enter('label');
44490  const alt = safe(context, node.alt, {before: '[', after: ']'});
44491  let value = '![' + alt + ']';
44492
44493  subexit();
44494  // Hide the fact that we’re in phrasing, because escapes don’t work.
44495  const stack = context.stack;
44496  context.stack = [];
44497  subexit = context.enter('reference');
44498  const reference = safe(context, association(node), {before: '[', after: ']'});
44499  subexit();
44500  context.stack = stack;
44501  exit();
44502
44503  if (type === 'full' || !alt || alt !== reference) {
44504    value += '[' + reference + ']';
44505  } else if (type !== 'shortcut') {
44506    value += '[]';
44507  }
44508
44509  return value
44510}
44511
44512/**
44513 * @type {Handle}
44514 */
44515function imageReferencePeek() {
44516  return '!'
44517}
44518
44519/**
44520 * @typedef {import('mdast').InlineCode} InlineCode
44521 * @typedef {import('../types.js').Handle} Handle
44522 */
44523
44524inlineCode.peek = inlineCodePeek;
44525
44526/**
44527 * @type {Handle}
44528 * @param {InlineCode} node
44529 */
44530function inlineCode(node, _, context) {
44531  let value = node.value || '';
44532  let sequence = '`';
44533  let index = -1;
44534
44535  // If there is a single grave accent on its own in the code, use a fence of
44536  // two.
44537  // If there are two in a row, use one.
44538  while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {
44539    sequence += '`';
44540  }
44541
44542  // If this is not just spaces or eols (tabs don’t count), and either the
44543  // first or last character are a space, eol, or tick, then pad with spaces.
44544  if (
44545    /[^ \r\n]/.test(value) &&
44546    ((/^[ \r\n]/.test(value) && /[ \r\n]$/.test(value)) || /^`|`$/.test(value))
44547  ) {
44548    value = ' ' + value + ' ';
44549  }
44550
44551  // We have a potential problem: certain characters after eols could result in
44552  // blocks being seen.
44553  // For example, if someone injected the string `'\n# b'`, then that would
44554  // result in an ATX heading.
44555  // We can’t escape characters in `inlineCode`, but because eols are
44556  // transformed to spaces when going from markdown to HTML anyway, we can swap
44557  // them out.
44558  while (++index < context.unsafe.length) {
44559    const pattern = context.unsafe[index];
44560    const expression = patternCompile(pattern);
44561    /** @type {RegExpExecArray|null} */
44562    let match;
44563
44564    // Only look for `atBreak`s.
44565    // Btw: note that `atBreak` patterns will always start the regex at LF or
44566    // CR.
44567    if (!pattern.atBreak) continue
44568
44569    while ((match = expression.exec(value))) {
44570      let position = match.index;
44571
44572      // Support CRLF (patterns only look for one of the characters).
44573      if (
44574        value.charCodeAt(position) === 10 /* `\n` */ &&
44575        value.charCodeAt(position - 1) === 13 /* `\r` */
44576      ) {
44577        position--;
44578      }
44579
44580      value = value.slice(0, position) + ' ' + value.slice(match.index + 1);
44581    }
44582  }
44583
44584  return sequence + value + sequence
44585}
44586
44587/**
44588 * @type {Handle}
44589 */
44590function inlineCodePeek() {
44591  return '`'
44592}
44593
44594/**
44595 * @typedef {import('mdast').Link} Link
44596 * @typedef {import('../types.js').Context} Context
44597 */
44598
44599/**
44600 * @param {Link} node
44601 * @param {Context} context
44602 * @returns {boolean}
44603 */
44604function formatLinkAsAutolink(node, context) {
44605  const raw = toString(node);
44606
44607  return Boolean(
44608    !context.options.resourceLink &&
44609      // If there’s a url…
44610      node.url &&
44611      // And there’s a no title…
44612      !node.title &&
44613      // And the content of `node` is a single text node…
44614      node.children &&
44615      node.children.length === 1 &&
44616      node.children[0].type === 'text' &&
44617      // And if the url is the same as the content…
44618      (raw === node.url || 'mailto:' + raw === node.url) &&
44619      // And that starts w/ a protocol…
44620      /^[a-z][a-z+.-]+:/i.test(node.url) &&
44621      // And that doesn’t contain ASCII control codes (character escapes and
44622      // references don’t work) or angle brackets…
44623      !/[\0- <>\u007F]/.test(node.url)
44624  )
44625}
44626
44627/**
44628 * @typedef {import('mdast').Link} Link
44629 * @typedef {import('../types.js').Handle} Handle
44630 * @typedef {import('../types.js').Exit} Exit
44631 */
44632
44633link.peek = linkPeek;
44634
44635/**
44636 * @type {Handle}
44637 * @param {Link} node
44638 */
44639function link(node, _, context) {
44640  const quote = checkQuote(context);
44641  const suffix = quote === '"' ? 'Quote' : 'Apostrophe';
44642  /** @type {Exit} */
44643  let exit;
44644  /** @type {Exit} */
44645  let subexit;
44646  /** @type {string} */
44647  let value;
44648
44649  if (formatLinkAsAutolink(node, context)) {
44650    // Hide the fact that we’re in phrasing, because escapes don’t work.
44651    const stack = context.stack;
44652    context.stack = [];
44653    exit = context.enter('autolink');
44654    value =
44655      '<' + containerPhrasing(node, context, {before: '<', after: '>'}) + '>';
44656    exit();
44657    context.stack = stack;
44658    return value
44659  }
44660
44661  exit = context.enter('link');
44662  subexit = context.enter('label');
44663  value =
44664    '[' + containerPhrasing(node, context, {before: '[', after: ']'}) + '](';
44665  subexit();
44666
44667  if (
44668    // If there’s no url but there is a title…
44669    (!node.url && node.title) ||
44670    // Or if there’s markdown whitespace or an eol, enclose.
44671    /[ \t\r\n]/.test(node.url)
44672  ) {
44673    subexit = context.enter('destinationLiteral');
44674    value += '<' + safe(context, node.url, {before: '<', after: '>'}) + '>';
44675  } else {
44676    // No whitespace, raw is prettier.
44677    subexit = context.enter('destinationRaw');
44678    value += safe(context, node.url, {
44679      before: '(',
44680      after: node.title ? ' ' : ')'
44681    });
44682  }
44683
44684  subexit();
44685
44686  if (node.title) {
44687    subexit = context.enter('title' + suffix);
44688    value +=
44689      ' ' +
44690      quote +
44691      safe(context, node.title, {before: quote, after: quote}) +
44692      quote;
44693    subexit();
44694  }
44695
44696  value += ')';
44697
44698  exit();
44699  return value
44700}
44701
44702/**
44703 * @type {Handle}
44704 * @param {Link} node
44705 */
44706function linkPeek(node, _, context) {
44707  return formatLinkAsAutolink(node, context) ? '<' : '['
44708}
44709
44710/**
44711 * @typedef {import('mdast').LinkReference} LinkReference
44712 * @typedef {import('../types.js').Handle} Handle
44713 */
44714
44715linkReference.peek = linkReferencePeek;
44716
44717/**
44718 * @type {Handle}
44719 * @param {LinkReference} node
44720 */
44721function linkReference(node, _, context) {
44722  const type = node.referenceType;
44723  const exit = context.enter('linkReference');
44724  let subexit = context.enter('label');
44725  const text = containerPhrasing(node, context, {before: '[', after: ']'});
44726  let value = '[' + text + ']';
44727
44728  subexit();
44729  // Hide the fact that we’re in phrasing, because escapes don’t work.
44730  const stack = context.stack;
44731  context.stack = [];
44732  subexit = context.enter('reference');
44733  const reference = safe(context, association(node), {before: '[', after: ']'});
44734  subexit();
44735  context.stack = stack;
44736  exit();
44737
44738  if (type === 'full' || !text || text !== reference) {
44739    value += '[' + reference + ']';
44740  } else if (type !== 'shortcut') {
44741    value += '[]';
44742  }
44743
44744  return value
44745}
44746
44747/**
44748 * @type {Handle}
44749 */
44750function linkReferencePeek() {
44751  return '['
44752}
44753
44754/**
44755 * @typedef {import('mdast').List} List
44756 * @typedef {import('../types.js').Handle} Handle
44757 */
44758
44759/**
44760 * @type {Handle}
44761 * @param {List} node
44762 */
44763function list(node, _, context) {
44764  const exit = context.enter('list');
44765  const value = containerFlow(node, context);
44766  exit();
44767  return value
44768}
44769
44770/**
44771 * @typedef {import('../types.js').Context} Context
44772 * @typedef {import('../types.js').Options} Options
44773 */
44774
44775/**
44776 * @param {Context} context
44777 * @returns {Exclude<Options['bullet'], undefined>}
44778 */
44779function checkBullet(context) {
44780  const marker = context.options.bullet || '*';
44781
44782  if (marker !== '*' && marker !== '+' && marker !== '-') {
44783    throw new Error(
44784      'Cannot serialize items with `' +
44785        marker +
44786        '` for `options.bullet`, expected `*`, `+`, or `-`'
44787    )
44788  }
44789
44790  return marker
44791}
44792
44793/**
44794 * @typedef {import('../types.js').Context} Context
44795 * @typedef {import('../types.js').Options} Options
44796 */
44797
44798/**
44799 * @param {Context} context
44800 * @returns {Exclude<Options['listItemIndent'], undefined>}
44801 */
44802function checkListItemIndent(context) {
44803  const style = context.options.listItemIndent || 'tab';
44804
44805  // To do: remove in a major.
44806  // @ts-expect-error: deprecated.
44807  if (style === 1 || style === '1') {
44808    return 'one'
44809  }
44810
44811  if (style !== 'tab' && style !== 'one' && style !== 'mixed') {
44812    throw new Error(
44813      'Cannot serialize items with `' +
44814        style +
44815        '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'
44816    )
44817  }
44818
44819  return style
44820}
44821
44822/**
44823 * @typedef {import('mdast').ListItem} ListItem
44824 * @typedef {import('mdast').List} List
44825 * @typedef {import('../util/indent-lines.js').Map} Map
44826 * @typedef {import('../types.js').Options} Options
44827 * @typedef {import('../types.js').Handle} Handle
44828 */
44829
44830/**
44831 * @type {Handle}
44832 * @param {ListItem} node
44833 */
44834function listItem(node, parent, context) {
44835  const listItemIndent = checkListItemIndent(context);
44836  /** @type {string} */
44837  let bullet = checkBullet(context);
44838
44839  if (parent && parent.type === 'list' && parent.ordered) {
44840    bullet =
44841      (typeof parent.start === 'number' && parent.start > -1
44842        ? parent.start
44843        : 1) +
44844      (context.options.incrementListMarker === false
44845        ? 0
44846        : parent.children.indexOf(node)) +
44847      '.';
44848  }
44849
44850  let size = bullet.length + 1;
44851
44852  if (
44853    listItemIndent === 'tab' ||
44854    (listItemIndent === 'mixed' &&
44855      ((parent && 'spread' in parent && parent.spread) || node.spread))
44856  ) {
44857    size = Math.ceil(size / 4) * 4;
44858  }
44859
44860  const exit = context.enter('listItem');
44861  const value = indentLines(containerFlow(node, context), map);
44862  exit();
44863
44864  return value
44865
44866  /** @type {Map} */
44867  function map(line, index, blank) {
44868    if (index) {
44869      return (blank ? '' : ' '.repeat(size)) + line
44870    }
44871
44872    return (blank ? bullet : bullet + ' '.repeat(size - bullet.length)) + line
44873  }
44874}
44875
44876/**
44877 * @typedef {import('mdast').Paragraph} Paragraph
44878 * @typedef {import('../types.js').Handle} Handle
44879 */
44880
44881/**
44882 * @type {Handle}
44883 * @param {Paragraph} node
44884 */
44885function paragraph(node, _, context) {
44886  const exit = context.enter('paragraph');
44887  const subexit = context.enter('phrasing');
44888  const value = containerPhrasing(node, context, {before: '\n', after: '\n'});
44889  subexit();
44890  exit();
44891  return value
44892}
44893
44894/**
44895 * @typedef {import('mdast').Root} Root
44896 * @typedef {import('../types.js').Handle} Handle
44897 */
44898
44899/**
44900 * @type {Handle}
44901 * @param {Root} node
44902 */
44903function root(node, _, context) {
44904  return containerFlow(node, context)
44905}
44906
44907/**
44908 * @typedef {import('../types.js').Context} Context
44909 * @typedef {import('../types.js').Options} Options
44910 */
44911
44912/**
44913 * @param {Context} context
44914 * @returns {Exclude<Options['strong'], undefined>}
44915 */
44916function checkStrong(context) {
44917  const marker = context.options.strong || '*';
44918
44919  if (marker !== '*' && marker !== '_') {
44920    throw new Error(
44921      'Cannot serialize strong with `' +
44922        marker +
44923        '` for `options.strong`, expected `*`, or `_`'
44924    )
44925  }
44926
44927  return marker
44928}
44929
44930/**
44931 * @typedef {import('mdast').Strong} Strong
44932 * @typedef {import('../types.js').Handle} Handle
44933 */
44934
44935strong.peek = strongPeek;
44936
44937// To do: there are cases where emphasis cannot “form” depending on the
44938// previous or next character of sequences.
44939// There’s no way around that though, except for injecting zero-width stuff.
44940// Do we need to safeguard against that?
44941/**
44942 * @type {Handle}
44943 * @param {Strong} node
44944 */
44945function strong(node, _, context) {
44946  const marker = checkStrong(context);
44947  const exit = context.enter('strong');
44948  const value = containerPhrasing(node, context, {
44949    before: marker,
44950    after: marker
44951  });
44952  exit();
44953  return marker + marker + value + marker + marker
44954}
44955
44956/**
44957 * @type {Handle}
44958 * @param {Strong} _
44959 */
44960function strongPeek(_, _1, context) {
44961  return context.options.strong || '*'
44962}
44963
44964/**
44965 * @typedef {import('mdast').Text} Text
44966 * @typedef {import('../types.js').Handle} Handle
44967 */
44968
44969/**
44970 * @type {Handle}
44971 * @param {Text} node
44972 */
44973function text$1(node, _, context, safeOptions) {
44974  return safe(context, node.value, safeOptions)
44975}
44976
44977/**
44978 * @typedef {import('../types.js').Context} Context
44979 * @typedef {import('../types.js').Options} Options
44980 */
44981
44982/**
44983 * @param {Context} context
44984 * @returns {Exclude<Options['ruleRepetition'], undefined>}
44985 */
44986function checkRuleRepetition(context) {
44987  const repetition = context.options.ruleRepetition || 3;
44988
44989  if (repetition < 3) {
44990    throw new Error(
44991      'Cannot serialize rules with repetition `' +
44992        repetition +
44993        '` for `options.ruleRepetition`, expected `3` or more'
44994    )
44995  }
44996
44997  return repetition
44998}
44999
45000/**
45001 * @typedef {import('../types.js').Context} Context
45002 * @typedef {import('../types.js').Options} Options
45003 */
45004
45005/**
45006 * @param {Context} context
45007 * @returns {Exclude<Options['rule'], undefined>}
45008 */
45009function checkRule(context) {
45010  const marker = context.options.rule || '*';
45011
45012  if (marker !== '*' && marker !== '-' && marker !== '_') {
45013    throw new Error(
45014      'Cannot serialize rules with `' +
45015        marker +
45016        '` for `options.rule`, expected `*`, `-`, or `_`'
45017    )
45018  }
45019
45020  return marker
45021}
45022
45023/**
45024 * @typedef {import('../types.js').Handle} Handle
45025 * @typedef {import('mdast').ThematicBreak} ThematicBreak
45026 */
45027
45028/**
45029 * @type {Handle}
45030 * @param {ThematicBreak} _
45031 */
45032function thematicBreak(_, _1, context) {
45033  const value = (
45034    checkRule(context) + (context.options.ruleSpaces ? ' ' : '')
45035  ).repeat(checkRuleRepetition(context));
45036
45037  return context.options.ruleSpaces ? value.slice(0, -1) : value
45038}
45039
45040const handle = {
45041  blockquote,
45042  break: hardBreak,
45043  code: code$1,
45044  definition,
45045  emphasis,
45046  hardBreak,
45047  heading,
45048  html,
45049  image,
45050  imageReference,
45051  inlineCode,
45052  link,
45053  linkReference,
45054  list,
45055  listItem,
45056  paragraph,
45057  root,
45058  strong,
45059  text: text$1,
45060  thematicBreak
45061};
45062
45063/**
45064 * @typedef {import('./types.js').Join} Join
45065 */
45066
45067/** @type {Array.<Join>} */
45068const join = [joinDefaults];
45069
45070/** @type {Join} */
45071function joinDefaults(left, right, parent, context) {
45072  if (
45073    // Two lists with the same marker.
45074    (right.type === 'list' &&
45075      right.type === left.type &&
45076      Boolean(left.ordered) === Boolean(right.ordered)) ||
45077    // Indented code after list or another indented code.
45078    (right.type === 'code' &&
45079      formatCodeAsIndented(right, context) &&
45080      (left.type === 'list' ||
45081        (left.type === right.type && formatCodeAsIndented(left, context))))
45082  ) {
45083    return false
45084  }
45085
45086  // Join children of a list or an item.
45087  // In which case, `parent` has a `spread` field.
45088  if ('spread' in parent && typeof parent.spread === 'boolean') {
45089    if (
45090      left.type === 'paragraph' &&
45091      // Two paragraphs.
45092      (left.type === right.type ||
45093        right.type === 'definition' ||
45094        // Paragraph followed by a setext heading.
45095        (right.type === 'heading' && formatHeadingAsSetext(right, context)))
45096    ) {
45097      return
45098    }
45099
45100    return parent.spread ? 1 : 0
45101  }
45102}
45103
45104/**
45105 * @typedef {import('./types.js').Unsafe} Unsafe
45106 */
45107
45108/** @type {Array.<Unsafe>} */
45109const unsafe = [
45110  {
45111    character: '\t',
45112    inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde']
45113  },
45114  {
45115    character: '\r',
45116    inConstruct: [
45117      'codeFencedLangGraveAccent',
45118      'codeFencedLangTilde',
45119      'codeFencedMetaGraveAccent',
45120      'codeFencedMetaTilde',
45121      'destinationLiteral',
45122      'headingAtx'
45123    ]
45124  },
45125  {
45126    character: '\n',
45127    inConstruct: [
45128      'codeFencedLangGraveAccent',
45129      'codeFencedLangTilde',
45130      'codeFencedMetaGraveAccent',
45131      'codeFencedMetaTilde',
45132      'destinationLiteral',
45133      'headingAtx'
45134    ]
45135  },
45136  {
45137    character: ' ',
45138    inConstruct: ['codeFencedLangGraveAccent', 'codeFencedLangTilde']
45139  },
45140  // An exclamation mark can start an image, if it is followed by a link or
45141  // a link reference.
45142  {character: '!', after: '\\[', inConstruct: 'phrasing'},
45143  // A quote can break out of a title.
45144  {character: '"', inConstruct: 'titleQuote'},
45145  // A number sign could start an ATX heading if it starts a line.
45146  {atBreak: true, character: '#'},
45147  {character: '#', inConstruct: 'headingAtx', after: '(?:[\r\n]|$)'},
45148  // Dollar sign and percentage are not used in markdown.
45149  // An ampersand could start a character reference.
45150  {character: '&', after: '[#A-Za-z]', inConstruct: 'phrasing'},
45151  // An apostrophe can break out of a title.
45152  {character: "'", inConstruct: 'titleApostrophe'},
45153  // A left paren could break out of a destination raw.
45154  {character: '(', inConstruct: 'destinationRaw'},
45155  {before: '\\]', character: '(', inConstruct: 'phrasing'},
45156  // A right paren could start a list item or break out of a destination
45157  // raw.
45158  {atBreak: true, before: '\\d+', character: ')'},
45159  {character: ')', inConstruct: 'destinationRaw'},
45160  // An asterisk can start thematic breaks, list items, emphasis, strong.
45161  {atBreak: true, character: '*'},
45162  {character: '*', inConstruct: 'phrasing'},
45163  // A plus sign could start a list item.
45164  {atBreak: true, character: '+'},
45165  // A dash can start thematic breaks, list items, and setext heading
45166  // underlines.
45167  {atBreak: true, character: '-'},
45168  // A dot could start a list item.
45169  {atBreak: true, before: '\\d+', character: '.', after: '(?:[ \t\r\n]|$)'},
45170  // Slash, colon, and semicolon are not used in markdown for constructs.
45171  // A less than can start html (flow or text) or an autolink.
45172  // HTML could start with an exclamation mark (declaration, cdata, comment),
45173  // slash (closing tag), question mark (instruction), or a letter (tag).
45174  // An autolink also starts with a letter.
45175  // Finally, it could break out of a destination literal.
45176  {atBreak: true, character: '<', after: '[!/?A-Za-z]'},
45177  {character: '<', after: '[!/?A-Za-z]', inConstruct: 'phrasing'},
45178  {character: '<', inConstruct: 'destinationLiteral'},
45179  // An equals to can start setext heading underlines.
45180  {atBreak: true, character: '='},
45181  // A greater than can start block quotes and it can break out of a
45182  // destination literal.
45183  {atBreak: true, character: '>'},
45184  {character: '>', inConstruct: 'destinationLiteral'},
45185  // Question mark and at sign are not used in markdown for constructs.
45186  // A left bracket can start definitions, references, labels,
45187  {atBreak: true, character: '['},
45188  {character: '[', inConstruct: ['phrasing', 'label', 'reference']},
45189  // A backslash can start an escape (when followed by punctuation) or a
45190  // hard break (when followed by an eol).
45191  // Note: typical escapes are handled in `safe`!
45192  {character: '\\', after: '[\\r\\n]', inConstruct: 'phrasing'},
45193  // A right bracket can exit labels.
45194  {
45195    character: ']',
45196    inConstruct: ['label', 'reference']
45197  },
45198  // Caret is not used in markdown for constructs.
45199  // An underscore can start emphasis, strong, or a thematic break.
45200  {atBreak: true, character: '_'},
45201  {before: '[^A-Za-z]', character: '_', inConstruct: 'phrasing'},
45202  {character: '_', after: '[^A-Za-z]', inConstruct: 'phrasing'},
45203  // A grave accent can start code (fenced or text), or it can break out of
45204  // a grave accent code fence.
45205  {atBreak: true, character: '`'},
45206  {
45207    character: '`',
45208    inConstruct: [
45209      'codeFencedLangGraveAccent',
45210      'codeFencedMetaGraveAccent',
45211      'phrasing'
45212    ]
45213  },
45214  // Left brace, vertical bar, right brace are not used in markdown for
45215  // constructs.
45216  // A tilde can start code (fenced).
45217  {atBreak: true, character: '~'}
45218];
45219
45220/**
45221 * @typedef {import('./types.js').Node} Node
45222 * @typedef {import('./types.js').Options} Options
45223 * @typedef {import('./types.js').Context} Context
45224 * @typedef {import('./types.js').Handle} Handle
45225 * @typedef {import('./types.js').Join} Join
45226 * @typedef {import('./types.js').Unsafe} Unsafe
45227 */
45228
45229/**
45230 * @param {Node} tree
45231 * @param {Options} [options]
45232 * @returns {string}
45233 */
45234function toMarkdown(tree, options = {}) {
45235  /** @type {Context} */
45236  // @ts-expect-error: we’ll add `handle` later.
45237  const context = {
45238    enter,
45239    stack: [],
45240    unsafe: [],
45241    join: [],
45242    handlers: {},
45243    options: {}
45244  };
45245
45246  configure(context, {unsafe, join, handlers: handle});
45247  configure(context, options);
45248
45249  if (context.options.tightDefinitions) {
45250    configure(context, {join: [joinDefinition]});
45251  }
45252
45253  /** @type {Handle} */
45254  context.handle = zwitch('type', {
45255    invalid,
45256    // @ts-expect-error: hush.
45257    unknown,
45258    // @ts-expect-error: hush.
45259    handlers: context.handlers
45260  });
45261
45262  let result = context.handle(tree, null, context, {before: '\n', after: '\n'});
45263
45264  if (
45265    result &&
45266    result.charCodeAt(result.length - 1) !== 10 &&
45267    result.charCodeAt(result.length - 1) !== 13
45268  ) {
45269    result += '\n';
45270  }
45271
45272  return result
45273
45274  /** @type {Context['enter']} */
45275  function enter(name) {
45276    context.stack.push(name);
45277    return exit
45278
45279    function exit() {
45280      context.stack.pop();
45281    }
45282  }
45283}
45284
45285/**
45286 * @type {Handle}
45287 * @param {unknown} value
45288 */
45289function invalid(value) {
45290  throw new Error('Cannot handle value `' + value + '`, expected node')
45291}
45292
45293/**
45294 * @type {Handle}
45295 * @param {Node} node
45296 */
45297function unknown(node) {
45298  throw new Error('Cannot handle unknown node `' + node.type + '`')
45299}
45300
45301/** @type {Join} */
45302function joinDefinition(left, right) {
45303  // No blank line between adjacent definitions.
45304  if (left.type === 'definition' && left.type === right.type) {
45305    return 0
45306  }
45307}
45308
45309/**
45310 * @typedef {import('mdast').Root|import('mdast').Content} Node
45311 * @typedef {import('mdast-util-to-markdown').Options} Options
45312 */
45313
45314/** @type {import('unified').Plugin<[Options]|void[], Node, string>} */
45315function remarkStringify(options) {
45316  /** @type {import('unified').CompilerFunction<Node, string>} */
45317  const compiler = (tree) => {
45318    // Assume options.
45319    const settings = /** @type {Options} */ (this.data('settings'));
45320
45321    return toMarkdown(
45322      tree,
45323      Object.assign({}, settings, options, {
45324        // Note: this option is not in the readme.
45325        // The goal is for it to be set by plugins on `data` instead of being
45326        // passed by users.
45327        extensions: this.data('toMarkdownExtensions') || []
45328      })
45329    )
45330  };
45331
45332  Object.assign(this, {Compiler: compiler});
45333}
45334
45335const remark = unified().use(remarkParse).use(remarkStringify).freeze();
45336
45337const name$1 = "remark";
45338const version$1 = "14.0.1";
45339const description$1 = "Markdown processor powered by plugins part of the unified collective";
45340const license = "MIT";
45341const keywords = [
45342	"unified",
45343	"remark",
45344	"markdown",
45345	"mdast",
45346	"abstract",
45347	"syntax",
45348	"tree",
45349	"ast",
45350	"parse",
45351	"stringify",
45352	"serialize",
45353	"compile",
45354	"process"
45355];
45356const homepage = "https://remark.js.org";
45357const repository = "https://github.com/remarkjs/remark/tree/main/packages/remark";
45358const bugs = "https://github.com/remarkjs/remark/issues";
45359const funding = {
45360	type: "opencollective",
45361	url: "https://opencollective.com/unified"
45362};
45363const author = "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)";
45364const contributors = [
45365	"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
45366];
45367const sideEffects = false;
45368const type = "module";
45369const main$1 = "index.js";
45370const types = "index.d.ts";
45371const files = [
45372	"index.d.ts",
45373	"index.js"
45374];
45375const dependencies$1 = {
45376	"@types/mdast": "^3.0.0",
45377	"remark-parse": "^10.0.0",
45378	"remark-stringify": "^10.0.0",
45379	unified: "^10.0.0"
45380};
45381const scripts$1 = {
45382	test: "node --conditions development test.js",
45383	build: "rimraf \"*.d.ts\" && tsc && type-coverage"
45384};
45385const xo = false;
45386const typeCoverage = {
45387	atLeast: 100,
45388	detail: true,
45389	strict: true,
45390	ignoreCatch: true
45391};
45392var proc = {
45393	name: name$1,
45394	version: version$1,
45395	description: description$1,
45396	license: license,
45397	keywords: keywords,
45398	homepage: homepage,
45399	repository: repository,
45400	bugs: bugs,
45401	funding: funding,
45402	author: author,
45403	contributors: contributors,
45404	sideEffects: sideEffects,
45405	type: type,
45406	main: main$1,
45407	types: types,
45408	files: files,
45409	dependencies: dependencies$1,
45410	scripts: scripts$1,
45411	xo: xo,
45412	typeCoverage: typeCoverage
45413};
45414
45415const name = "node-lint-md-cli-rollup";
45416const description = "remark packaged for Node.js Markdown linting";
45417const version = "2.0.2";
45418const devDependencies = {
45419	"@rollup/plugin-commonjs": "^20.0.0",
45420	"@rollup/plugin-json": "^4.1.0",
45421	"@rollup/plugin-node-resolve": "^13.0.4",
45422	rollup: "^2.52.7",
45423	shx: "^0.3.3"
45424};
45425const dependencies = {
45426	"markdown-extensions": "^1.1.1",
45427	remark: "^14.0.0",
45428	"remark-gfm": "^2.0.0",
45429	"remark-preset-lint-node": "^3.0.0",
45430	"unified-args": "^9.0.0"
45431};
45432const main = "dist/index.js";
45433const scripts = {
45434	build: "npx rollup -c",
45435	"build-node": "npm run build && npx shx cp dist/index.mjs ../lint-md.mjs"
45436};
45437var cli = {
45438	name: name,
45439	description: description,
45440	version: version,
45441	devDependencies: devDependencies,
45442	dependencies: dependencies,
45443	main: main,
45444	scripts: scripts
45445};
45446
45447/**
45448 * @typedef {import('unist').Point} Point
45449 * @typedef {import('vfile').VFile} VFile
45450 *
45451 * @typedef {Pick<Point, 'line'|'column'>} PositionalPoint
45452 * @typedef {Required<Point>} FullPoint
45453 * @typedef {NonNullable<Point['offset']>} Offset
45454 */
45455
45456/**
45457 * Get transform functions for the given `document`.
45458 *
45459 * @param {string|Uint8Array|VFile} file
45460 */
45461function location(file) {
45462  var value = String(file);
45463  /** @type {Array.<number>} */
45464  var indices = [];
45465  var search = /\r?\n|\r/g;
45466
45467  while (search.test(value)) {
45468    indices.push(search.lastIndex);
45469  }
45470
45471  indices.push(value.length + 1);
45472
45473  return {toPoint, toOffset}
45474
45475  /**
45476   * Get the line and column-based `point` for `offset` in the bound indices.
45477   * Returns a point with `undefined` values when given invalid or out of bounds
45478   * input.
45479   *
45480   * @param {Offset} offset
45481   * @returns {FullPoint}
45482   */
45483  function toPoint(offset) {
45484    var index = -1;
45485
45486    if (offset > -1 && offset < indices[indices.length - 1]) {
45487      while (++index < indices.length) {
45488        if (indices[index] > offset) {
45489          return {
45490            line: index + 1,
45491            column: offset - (indices[index - 1] || 0) + 1,
45492            offset
45493          }
45494        }
45495      }
45496    }
45497
45498    return {line: undefined, column: undefined, offset: undefined}
45499  }
45500
45501  /**
45502   * Get the `offset` for a line and column-based `point` in the bound indices.
45503   * Returns `-1` when given invalid or out of bounds input.
45504   *
45505   * @param {PositionalPoint} point
45506   * @returns {Offset}
45507   */
45508  function toOffset(point) {
45509    var line = point && point.line;
45510    var column = point && point.column;
45511    /** @type {number} */
45512    var offset;
45513
45514    if (
45515      typeof line === 'number' &&
45516      typeof column === 'number' &&
45517      !Number.isNaN(line) &&
45518      !Number.isNaN(column) &&
45519      line - 1 in indices
45520    ) {
45521      offset = (indices[line - 2] || 0) + column - 1 || 0;
45522    }
45523
45524    return offset > -1 && offset < indices[indices.length - 1] ? offset : -1
45525  }
45526}
45527
45528/**
45529 * @typedef {import('unist').Node} Node
45530 * @typedef {import('unist').Parent} Parent
45531 *
45532 * @typedef {string} Type
45533 * @typedef {Object<string, unknown>} Props
45534 *
45535 * @typedef {null|undefined|Type|Props|TestFunctionAnything|Array.<Type|Props|TestFunctionAnything>} Test
45536 */
45537
45538const convert =
45539  /**
45540   * @type {(
45541   *   (<T extends Node>(test: T['type']|Partial<T>|TestFunctionPredicate<T>) => AssertPredicate<T>) &
45542   *   ((test?: Test) => AssertAnything)
45543   * )}
45544   */
45545  (
45546    /**
45547     * Generate an assertion from a check.
45548     * @param {Test} [test]
45549     * When nullish, checks if `node` is a `Node`.
45550     * When `string`, works like passing `function (node) {return node.type === test}`.
45551     * When `function` checks if function passed the node is true.
45552     * When `object`, checks that all keys in test are in node, and that they have (strictly) equal values.
45553     * When `array`, checks any one of the subtests pass.
45554     * @returns {AssertAnything}
45555     */
45556    function (test) {
45557      if (test === undefined || test === null) {
45558        return ok
45559      }
45560
45561      if (typeof test === 'string') {
45562        return typeFactory(test)
45563      }
45564
45565      if (typeof test === 'object') {
45566        return Array.isArray(test) ? anyFactory(test) : propsFactory(test)
45567      }
45568
45569      if (typeof test === 'function') {
45570        return castFactory(test)
45571      }
45572
45573      throw new Error('Expected function, string, or object as test')
45574    }
45575  );
45576/**
45577 * @param {Array.<Type|Props|TestFunctionAnything>} tests
45578 * @returns {AssertAnything}
45579 */
45580function anyFactory(tests) {
45581  /** @type {Array.<AssertAnything>} */
45582  const checks = [];
45583  let index = -1;
45584
45585  while (++index < tests.length) {
45586    checks[index] = convert(tests[index]);
45587  }
45588
45589  return castFactory(any)
45590
45591  /**
45592   * @this {unknown}
45593   * @param {unknown[]} parameters
45594   * @returns {boolean}
45595   */
45596  function any(...parameters) {
45597    let index = -1;
45598
45599    while (++index < checks.length) {
45600      if (checks[index].call(this, ...parameters)) return true
45601    }
45602
45603    return false
45604  }
45605}
45606
45607/**
45608 * Utility to assert each property in `test` is represented in `node`, and each
45609 * values are strictly equal.
45610 *
45611 * @param {Props} check
45612 * @returns {AssertAnything}
45613 */
45614function propsFactory(check) {
45615  return castFactory(all)
45616
45617  /**
45618   * @param {Node} node
45619   * @returns {boolean}
45620   */
45621  function all(node) {
45622    /** @type {string} */
45623    let key;
45624
45625    for (key in check) {
45626      // @ts-expect-error: hush, it sure works as an index.
45627      if (node[key] !== check[key]) return false
45628    }
45629
45630    return true
45631  }
45632}
45633
45634/**
45635 * Utility to convert a string into a function which checks a given node’s type
45636 * for said string.
45637 *
45638 * @param {Type} check
45639 * @returns {AssertAnything}
45640 */
45641function typeFactory(check) {
45642  return castFactory(type)
45643
45644  /**
45645   * @param {Node} node
45646   */
45647  function type(node) {
45648    return node && node.type === check
45649  }
45650}
45651
45652/**
45653 * Utility to convert a string into a function which checks a given node’s type
45654 * for said string.
45655 * @param {TestFunctionAnything} check
45656 * @returns {AssertAnything}
45657 */
45658function castFactory(check) {
45659  return assertion
45660
45661  /**
45662   * @this {unknown}
45663   * @param {Array.<unknown>} parameters
45664   * @returns {boolean}
45665   */
45666  function assertion(...parameters) {
45667    // @ts-expect-error: spreading is fine.
45668    return Boolean(check.call(this, ...parameters))
45669  }
45670}
45671
45672// Utility to return true.
45673function ok() {
45674  return true
45675}
45676
45677/**
45678 * @param {string} d
45679 * @returns {string}
45680 */
45681function color$2(d) {
45682  return '\u001B[33m' + d + '\u001B[39m'
45683}
45684
45685/**
45686 * @typedef {import('unist').Node} Node
45687 * @typedef {import('unist').Parent} Parent
45688 * @typedef {import('unist-util-is').Test} Test
45689 */
45690
45691/**
45692 * Continue traversing as normal
45693 */
45694const CONTINUE$2 = true;
45695/**
45696 * Do not traverse this node’s children
45697 */
45698const SKIP$2 = 'skip';
45699/**
45700 * Stop traversing immediately
45701 */
45702const EXIT$2 = false;
45703
45704const visitParents$2 =
45705  /**
45706   * @type {(
45707   *   (<T extends Node>(tree: Node, test: T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>|Array.<T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>>, visitor: Visitor<T>, reverse?: boolean) => void) &
45708   *   ((tree: Node, test: Test, visitor: Visitor<Node>, reverse?: boolean) => void) &
45709   *   ((tree: Node, visitor: Visitor<Node>, reverse?: boolean) => void)
45710   * )}
45711   */
45712  (
45713    /**
45714     * Visit children of tree which pass a test
45715     *
45716     * @param {Node} tree Abstract syntax tree to walk
45717     * @param {Test} test test Test node
45718     * @param {Visitor<Node>} visitor Function to run for each node
45719     * @param {boolean} [reverse] Fisit the tree in reverse, defaults to false
45720     */
45721    function (tree, test, visitor, reverse) {
45722      if (typeof test === 'function' && typeof visitor !== 'function') {
45723        reverse = visitor;
45724        // @ts-ignore no visitor given, so `visitor` is test.
45725        visitor = test;
45726        test = null;
45727      }
45728
45729      var is = convert(test);
45730      var step = reverse ? -1 : 1;
45731
45732      factory(tree, null, [])();
45733
45734      /**
45735       * @param {Node} node
45736       * @param {number?} index
45737       * @param {Array.<Parent>} parents
45738       */
45739      function factory(node, index, parents) {
45740        /** @type {Object.<string, unknown>} */
45741        var value = typeof node === 'object' && node !== null ? node : {};
45742        /** @type {string} */
45743        var name;
45744
45745        if (typeof value.type === 'string') {
45746          name =
45747            typeof value.tagName === 'string'
45748              ? value.tagName
45749              : typeof value.name === 'string'
45750              ? value.name
45751              : undefined;
45752
45753          Object.defineProperty(visit, 'name', {
45754            value:
45755              'node (' +
45756              color$2(value.type + (name ? '<' + name + '>' : '')) +
45757              ')'
45758          });
45759        }
45760
45761        return visit
45762
45763        function visit() {
45764          /** @type {ActionTuple} */
45765          var result = [];
45766          /** @type {ActionTuple} */
45767          var subresult;
45768          /** @type {number} */
45769          var offset;
45770          /** @type {Array.<Parent>} */
45771          var grandparents;
45772
45773          if (!test || is(node, index, parents[parents.length - 1] || null)) {
45774            result = toResult$2(visitor(node, parents));
45775
45776            if (result[0] === EXIT$2) {
45777              return result
45778            }
45779          }
45780
45781          if (node.children && result[0] !== SKIP$2) {
45782            // @ts-ignore looks like a parent.
45783            offset = (reverse ? node.children.length : -1) + step;
45784            // @ts-ignore looks like a parent.
45785            grandparents = parents.concat(node);
45786
45787            // @ts-ignore looks like a parent.
45788            while (offset > -1 && offset < node.children.length) {
45789              subresult = factory(node.children[offset], offset, grandparents)();
45790
45791              if (subresult[0] === EXIT$2) {
45792                return subresult
45793              }
45794
45795              offset =
45796                typeof subresult[1] === 'number' ? subresult[1] : offset + step;
45797            }
45798          }
45799
45800          return result
45801        }
45802      }
45803    }
45804  );
45805
45806/**
45807 * @param {VisitorResult} value
45808 * @returns {ActionTuple}
45809 */
45810function toResult$2(value) {
45811  if (Array.isArray(value)) {
45812    return value
45813  }
45814
45815  if (typeof value === 'number') {
45816    return [CONTINUE$2, value]
45817  }
45818
45819  return [value]
45820}
45821
45822/**
45823 * @typedef {import('unist').Node} Node
45824 * @typedef {import('unist').Parent} Parent
45825 * @typedef {import('unist-util-is').Test} Test
45826 * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult
45827 */
45828
45829const visit$1 =
45830  /**
45831   * @type {(
45832   *   (<T extends Node>(tree: Node, test: T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>|Array.<T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>>, visitor: Visitor<T>, reverse?: boolean) => void) &
45833   *   ((tree: Node, test: Test, visitor: Visitor<Node>, reverse?: boolean) => void) &
45834   *   ((tree: Node, visitor: Visitor<Node>, reverse?: boolean) => void)
45835   * )}
45836   */
45837  (
45838    /**
45839     * Visit children of tree which pass a test
45840     *
45841     * @param {Node} tree Abstract syntax tree to walk
45842     * @param {Test} test test Test node
45843     * @param {Visitor<Node>} visitor Function to run for each node
45844     * @param {boolean} [reverse] Fisit the tree in reverse, defaults to false
45845     */
45846    function (tree, test, visitor, reverse) {
45847      if (typeof test === 'function' && typeof visitor !== 'function') {
45848        reverse = visitor;
45849        visitor = test;
45850        test = null;
45851      }
45852
45853      visitParents$2(tree, test, overload, reverse);
45854
45855      /**
45856       * @param {Node} node
45857       * @param {Array.<Parent>} parents
45858       */
45859      function overload(node, parents) {
45860        var parent = parents[parents.length - 1];
45861        return visitor(
45862          node,
45863          parent ? parent.children.indexOf(node) : null,
45864          parent
45865        )
45866      }
45867    }
45868  );
45869
45870/**
45871 * @typedef {import('unist').Node} Node
45872 * @typedef {import('unist').Parent} Parent
45873 * @typedef {import('unist').Point} Point
45874 * @typedef {import('unist-util-is').Test} Test
45875 * @typedef {import('vfile').VFile} VFile
45876 * @typedef {import('vfile-message').VFileMessage} VFileMessage
45877 *
45878 * @typedef {OptionsWithoutReset|OptionsWithReset} Options
45879 * @typedef {OptionsBaseFields & OptionsWithoutResetFields} OptionsWithoutReset
45880 * @typedef {OptionsBaseFields & OptionsWithResetFields} OptionsWithReset
45881 *
45882 * @typedef OptionsWithoutResetFields
45883 * @property {false} [reset]
45884 *   Whether to treat all messages as turned off initially.
45885 * @property {string[]} [disable]
45886 *   List of `ruleId`s to turn off.
45887 *
45888 * @typedef OptionsWithResetFields
45889 * @property {true} reset
45890 *   Whether to treat all messages as turned off initially.
45891 * @property {string[]} [enable]
45892 *   List of `ruleId`s to initially turn on.
45893 *
45894 * @typedef OptionsBaseFields
45895 * @property {string} name
45896 *   Name of markers that can control the message sources.
45897 *
45898 *   For example, `{name: 'alpha'}` controls `alpha` markers:
45899 *
45900 *   ```html
45901 *   <!--alpha ignore-->
45902 *   ```
45903 * @property {MarkerParser} marker
45904 *   Parse a possible marker to a comment marker object (Marker).
45905 *   If the marker isn't a marker, should return `null`.
45906 * @property {Test} [test]
45907 *   Test for possible markers
45908 * @property {string[]} [known]
45909 *   List of allowed `ruleId`s. When given a warning is shown
45910 *   when someone tries to control an unknown rule.
45911 *
45912 *   For example, `{name: 'alpha', known: ['bravo']}` results in a warning if
45913 *   `charlie` is configured:
45914 *
45915 *   ```html
45916 *   <!--alpha ignore charlie-->
45917 *   ```
45918 * @property {string|string[]} [source]
45919 *   Sources that can be controlled with `name` markers.
45920 *   Defaults to `name`.
45921 *
45922 * @callback MarkerParser
45923 *   Parse a possible comment marker node to a Marker.
45924 * @param {Node} node
45925 *   Node to parse
45926 *
45927 * @typedef Marker
45928 *   A comment marker.
45929 * @property {string} name
45930 *   Name of marker.
45931 * @property {string} attributes
45932 *   Value after name.
45933 * @property {Record<string, string|number|boolean>} parameters
45934 *   Parsed attributes.
45935 * @property {Node} node
45936 *   Reference to given node.
45937 *
45938 * @typedef Mark
45939 * @property {Point|undefined} point
45940 * @property {boolean} state
45941 */
45942
45943const own$2 = {}.hasOwnProperty;
45944
45945/**
45946 * @type {import('unified').Plugin<[Options]>}
45947 * @returns {(tree: Node, file: VFile) => void}
45948 */
45949function messageControl(options) {
45950  if (!options || typeof options !== 'object' || !options.name) {
45951    throw new Error(
45952      'Expected `name` in `options`, got `' + (options || {}).name + '`'
45953    )
45954  }
45955
45956  if (!options.marker) {
45957    throw new Error(
45958      'Expected `marker` in `options`, got `' + options.marker + '`'
45959    )
45960  }
45961
45962  const enable = 'enable' in options && options.enable ? options.enable : [];
45963  const disable = 'disable' in options && options.disable ? options.disable : [];
45964  let reset = options.reset;
45965  const sources =
45966    typeof options.source === 'string'
45967      ? [options.source]
45968      : options.source || [options.name];
45969
45970  return transformer
45971
45972  /**
45973   * @param {Node} tree
45974   * @param {VFile} file
45975   */
45976  function transformer(tree, file) {
45977    const toOffset = location(file).toOffset;
45978    const initial = !reset;
45979    const gaps = detectGaps(tree, file);
45980    /** @type {Record<string, Mark[]>} */
45981    const scope = {};
45982    /** @type {Mark[]} */
45983    const globals = [];
45984
45985    visit$1(tree, options.test, visitor);
45986
45987    file.messages = file.messages.filter((m) => filter(m));
45988
45989    /**
45990     * @param {Node} node
45991     * @param {number|null} position
45992     * @param {Parent|null} parent
45993     */
45994    function visitor(node, position, parent) {
45995      /** @type {Marker|null} */
45996      const mark = options.marker(node);
45997
45998      if (!mark || mark.name !== options.name) {
45999        return
46000      }
46001
46002      const ruleIds = mark.attributes.split(/\s/g);
46003      const point = mark.node.position && mark.node.position.start;
46004      const next =
46005        (parent && position !== null && parent.children[position + 1]) ||
46006        undefined;
46007      const tail = (next && next.position && next.position.end) || undefined;
46008      let index = -1;
46009
46010      /** @type {string} */
46011      // @ts-expect-error: we’ll check for unknown values next.
46012      const verb = ruleIds.shift();
46013
46014      if (verb !== 'enable' && verb !== 'disable' && verb !== 'ignore') {
46015        file.fail(
46016          'Unknown keyword `' +
46017            verb +
46018            '`: expected ' +
46019            "`'enable'`, `'disable'`, or `'ignore'`",
46020          mark.node
46021        );
46022      }
46023
46024      // Apply to all rules.
46025      if (ruleIds.length > 0) {
46026        while (++index < ruleIds.length) {
46027          const ruleId = ruleIds[index];
46028
46029          if (isKnown(ruleId, verb, mark.node)) {
46030            toggle(point, verb === 'enable', ruleId);
46031
46032            if (verb === 'ignore') {
46033              toggle(tail, true, ruleId);
46034            }
46035          }
46036        }
46037      } else if (verb === 'ignore') {
46038        toggle(point, false);
46039        toggle(tail, true);
46040      } else {
46041        toggle(point, verb === 'enable');
46042        reset = verb !== 'enable';
46043      }
46044    }
46045
46046    /**
46047     * @param {VFileMessage} message
46048     * @returns {boolean}
46049     */
46050    function filter(message) {
46051      let gapIndex = gaps.length;
46052
46053      // Keep messages from a different source.
46054      if (!message.source || !sources.includes(message.source)) {
46055        return true
46056      }
46057
46058      // We only ignore messages if they‘re disabled, *not* when they’re not in
46059      // the document.
46060      if (!message.line) {
46061        message.line = 1;
46062      }
46063
46064      if (!message.column) {
46065        message.column = 1;
46066      }
46067
46068      // Check whether the warning is inside a gap.
46069      // @ts-expect-error: we just normalized `null` to `number`s.
46070      const offset = toOffset(message);
46071
46072      while (gapIndex--) {
46073        if (gaps[gapIndex][0] <= offset && gaps[gapIndex][1] > offset) {
46074          return false
46075        }
46076      }
46077
46078      // Check whether allowed by specific and global states.
46079      return (
46080        (!message.ruleId ||
46081          check(message, scope[message.ruleId], message.ruleId)) &&
46082        check(message, globals)
46083      )
46084    }
46085
46086    /**
46087     * Helper to check (and possibly warn) if a `ruleId` is unknown.
46088     *
46089     * @param {string} ruleId
46090     * @param {string} verb
46091     * @param {Node} node
46092     * @returns {boolean}
46093     */
46094    function isKnown(ruleId, verb, node) {
46095      const result = options.known ? options.known.includes(ruleId) : true;
46096
46097      if (!result) {
46098        file.message(
46099          'Unknown rule: cannot ' + verb + " `'" + ruleId + "'`",
46100          node
46101        );
46102      }
46103
46104      return result
46105    }
46106
46107    /**
46108     * Get the latest state of a rule.
46109     * When without `ruleId`, gets global state.
46110     *
46111     * @param {string|undefined} ruleId
46112     * @returns {boolean}
46113     */
46114    function getState(ruleId) {
46115      const ranges = ruleId ? scope[ruleId] : globals;
46116
46117      if (ranges && ranges.length > 0) {
46118        return ranges[ranges.length - 1].state
46119      }
46120
46121      if (!ruleId) {
46122        return !reset
46123      }
46124
46125      return reset ? enable.includes(ruleId) : !disable.includes(ruleId)
46126    }
46127
46128    /**
46129     * Handle a rule.
46130     *
46131     * @param {Point|undefined} point
46132     * @param {boolean} state
46133     * @param {string|undefined} [ruleId]
46134     * @returns {void}
46135     */
46136    function toggle(point, state, ruleId) {
46137      let markers = ruleId ? scope[ruleId] : globals;
46138
46139      if (!markers) {
46140        markers = [];
46141        scope[String(ruleId)] = markers;
46142      }
46143
46144      const previousState = getState(ruleId);
46145
46146      if (state !== previousState) {
46147        markers.push({state, point});
46148      }
46149
46150      // Toggle all known rules.
46151      if (!ruleId) {
46152        for (ruleId in scope) {
46153          if (own$2.call(scope, ruleId)) {
46154            toggle(point, state, ruleId);
46155          }
46156        }
46157      }
46158    }
46159
46160    /**
46161     * Check all `ranges` for `message`.
46162     *
46163     * @param {VFileMessage} message
46164     * @param {Mark[]|undefined} ranges
46165     * @param {string|undefined} [ruleId]
46166     * @returns {boolean}
46167     */
46168    function check(message, ranges, ruleId) {
46169      if (ranges && ranges.length > 0) {
46170        // Check the state at the message’s position.
46171        let index = ranges.length;
46172
46173        while (index--) {
46174          const range = ranges[index];
46175
46176          if (
46177            message.line &&
46178            message.column &&
46179            range.point &&
46180            range.point.line &&
46181            range.point.column &&
46182            (range.point.line < message.line ||
46183              (range.point.line === message.line &&
46184                range.point.column <= message.column))
46185          ) {
46186            return range.state === true
46187          }
46188        }
46189      }
46190
46191      // The first marker ocurred after the first message, so we check the
46192      // initial state.
46193      if (!ruleId) {
46194        return Boolean(initial || reset)
46195      }
46196
46197      return reset ? enable.includes(ruleId) : !disable.includes(ruleId)
46198    }
46199  }
46200}
46201
46202/**
46203 * Detect gaps in `tree`.
46204 *
46205 * @param {Node} tree
46206 * @param {VFile} file
46207 */
46208function detectGaps(tree, file) {
46209  /** @type {Node[]} */
46210  // @ts-expect-error: fine.
46211  const children = tree.children || [];
46212  const lastNode = children[children.length - 1];
46213  /** @type {[number, number][]} */
46214  const gaps = [];
46215  let offset = 0;
46216  /** @type {boolean|undefined} */
46217  let gap;
46218
46219  // Find all gaps.
46220  visit$1(tree, one);
46221
46222  // Get the end of the document.
46223  // This detects if the last node was the last node.
46224  // If not, there’s an extra gap between the last node and the end of the
46225  // document.
46226  if (
46227    lastNode &&
46228    lastNode.position &&
46229    lastNode.position.end &&
46230    offset === lastNode.position.end.offset &&
46231    file.toString().slice(offset).trim() !== ''
46232  ) {
46233    update();
46234
46235    update(
46236      tree &&
46237        tree.position &&
46238        tree.position.end &&
46239        tree.position.end.offset &&
46240        tree.position.end.offset - 1
46241    );
46242  }
46243
46244  return gaps
46245
46246  /**
46247   * @param {Node} node
46248   */
46249  function one(node) {
46250    update(node.position && node.position.start && node.position.start.offset);
46251
46252    if (!('children' in node)) {
46253      update(node.position && node.position.end && node.position.end.offset);
46254    }
46255  }
46256
46257  /**
46258   * Detect a new position.
46259   *
46260   * @param {number|undefined} [latest]
46261   * @returns {void}
46262   */
46263  function update(latest) {
46264    if (latest === null || latest === undefined) {
46265      gap = true;
46266    } else if (offset < latest) {
46267      if (gap) {
46268        gaps.push([offset, latest]);
46269        gap = undefined;
46270      }
46271
46272      offset = latest;
46273    }
46274  }
46275}
46276
46277/**
46278 * @typedef {string|number|boolean} MarkerParameterValue
46279 * @typedef {Object.<string, MarkerParameterValue>} MarkerParameters
46280 *
46281 * @typedef HtmlNode
46282 * @property {'html'} type
46283 * @property {string} value
46284 *
46285 * @typedef CommentNode
46286 * @property {'comment'} type
46287 * @property {string} value
46288 *
46289 * @typedef Marker
46290 * @property {string} name
46291 * @property {string} attributes
46292 * @property {MarkerParameters|null} parameters
46293 * @property {HtmlNode|CommentNode} node
46294 */
46295
46296var commentExpression = /\s*([a-zA-Z\d-]+)(\s+([\s\S]*))?\s*/;
46297
46298var markerExpression = new RegExp(
46299  '(\\s*<!--' + commentExpression.source + '-->\\s*)'
46300);
46301
46302/**
46303 * Parse a comment marker.
46304 * @param {unknown} node
46305 * @returns {Marker|null}
46306 */
46307function commentMarker(node) {
46308  /** @type {RegExpMatchArray} */
46309  var match;
46310  /** @type {number} */
46311  var offset;
46312  /** @type {MarkerParameters} */
46313  var parameters;
46314
46315  if (
46316    node &&
46317    typeof node === 'object' &&
46318    // @ts-ignore hush
46319    (node.type === 'html' || node.type === 'comment')
46320  ) {
46321    // @ts-ignore hush
46322    match = node.value.match(
46323      // @ts-ignore hush
46324      node.type === 'comment' ? commentExpression : markerExpression
46325    );
46326
46327    // @ts-ignore hush
46328    if (match && match[0].length === node.value.length) {
46329      // @ts-ignore hush
46330      offset = node.type === 'comment' ? 1 : 2;
46331      parameters = parseParameters(match[offset + 1] || '');
46332
46333      if (parameters) {
46334        return {
46335          name: match[offset],
46336          attributes: match[offset + 2] || '',
46337          parameters,
46338          // @ts-ignore hush
46339          node
46340        }
46341      }
46342    }
46343  }
46344
46345  return null
46346}
46347
46348/**
46349 * Parse `value` into an object.
46350 *
46351 * @param {string} value
46352 * @returns {MarkerParameters|null}
46353 */
46354function parseParameters(value) {
46355  /** @type {MarkerParameters} */
46356  var parameters = {};
46357
46358  return value
46359    .replace(
46360      /\s+([-\w]+)(?:=(?:"((?:\\[\s\S]|[^"])+)"|'((?:\\[\s\S]|[^'])+)'|((?:\\[\s\S]|[^"'\s])+)))?/gi,
46361      replacer
46362    )
46363    .replace(/\s+/g, '')
46364    ? null
46365    : parameters
46366
46367  /**
46368   * @param {string} _
46369   * @param {string} $1
46370   * @param {string} $2
46371   * @param {string} $3
46372   * @param {string} $4
46373   */
46374  // eslint-disable-next-line max-params
46375  function replacer(_, $1, $2, $3, $4) {
46376    /** @type {MarkerParameterValue} */
46377    var value = $2 || $3 || $4 || '';
46378
46379    if (value === 'true' || value === '') {
46380      value = true;
46381    } else if (value === 'false') {
46382      value = false;
46383    } else if (!Number.isNaN(Number(value))) {
46384      value = Number(value);
46385    }
46386
46387    parameters[$1] = value;
46388
46389    return ''
46390  }
46391}
46392
46393/**
46394 * @typedef {import('mdast').Root} Root
46395 * @typedef {import('vfile').VFile} VFile
46396 * @typedef {import('unified-message-control')} MessageControl
46397 * @typedef {Omit<import('unified-message-control').OptionsWithoutReset, 'marker'>|Omit<import('unified-message-control').OptionsWithReset, 'marker'>} Options
46398 */
46399
46400const test = [
46401  'html', // Comments are `html` nodes in mdast.
46402  'comment' // In MDX, comments have their own node.
46403];
46404
46405/**
46406 * Plugin to enable, disable, and ignore messages.
46407 *
46408 * @type {import('unified').Plugin<[Options], Root>}
46409 * @returns {(node: Root, file: VFile) => void}
46410 */
46411function remarkMessageControl(options) {
46412  return messageControl(
46413    Object.assign({marker: commentMarker, test}, options)
46414  )
46415}
46416
46417/**
46418 * @typedef {import('mdast').Root} Root
46419 */
46420
46421/**
46422 * The core plugin for `remark-lint`.
46423 * This adds support for ignoring stuff from messages (`<!--lint ignore-->`).
46424 * All rules are in their own packages and presets.
46425 *
46426 * @type {import('unified').Plugin<void[], Root>}
46427 */
46428function remarkLint() {
46429  this.use(lintMessageControl);
46430}
46431
46432/** @type {import('unified').Plugin<void[], Root>} */
46433function lintMessageControl() {
46434  return remarkMessageControl({name: 'lint', source: 'remark-lint'})
46435}
46436
46437/**
46438 * @typedef {import('unist').Node} Node
46439 * @typedef {import('vfile').VFile} VFile
46440 *
46441 * @typedef {0|1|2} Severity
46442 * @typedef {'warn'|'on'|'off'|'error'} Label
46443 * @typedef {[Severity, ...unknown[]]} SeverityTuple
46444 *
46445 * @callback Rule
46446 * @param {Node} tree
46447 * @param {VFile} file
46448 * @param {unknown} options
46449 * @returns {void}
46450 */
46451
46452const primitives$G = new Set(['string', 'number', 'boolean']);
46453
46454/**
46455 * @param {string} id
46456 * @param {Rule} rule
46457 */
46458function lintRule$G(id, rule) {
46459  const parts = id.split(':');
46460  // Possibly useful if externalised later.
46461  /* c8 ignore next */
46462  const source = parts[1] ? parts[0] : undefined;
46463  const ruleId = parts[1];
46464
46465  Object.defineProperty(plugin, 'name', {value: id});
46466
46467  return plugin
46468
46469  /** @type {import('unified').Plugin<[unknown]|void[]>} */
46470  function plugin(raw) {
46471    const [severity, options] = coerce$H(ruleId, raw);
46472
46473    if (!severity) return
46474
46475    const fatal = severity === 2;
46476
46477    return (tree, file, next) => {
46478      let index = file.messages.length - 1;
46479
46480      wrap(rule, (error) => {
46481        const messages = file.messages;
46482
46483        // Add the error, if not already properly added.
46484        // Only happens for incorrect plugins.
46485        /* c8 ignore next 6 */
46486        // @ts-expect-error: errors could be `messages`.
46487        if (error && !messages.includes(error)) {
46488          try {
46489            file.fail(error);
46490          } catch {}
46491        }
46492
46493        while (++index < messages.length) {
46494          Object.assign(messages[index], {ruleId, source, fatal});
46495        }
46496
46497        next();
46498      })(tree, file, options);
46499    }
46500  }
46501}
46502
46503/**
46504 * Coerce a value to a severity--options tuple.
46505 *
46506 * @param {string} name
46507 * @param {unknown} value
46508 * @returns {SeverityTuple}
46509 */
46510function coerce$H(name, value) {
46511  /** @type {unknown[]} */
46512  let result;
46513
46514  if (typeof value === 'boolean') {
46515    result = [value];
46516  } else if (value === null || value === undefined) {
46517    result = [1];
46518  } else if (
46519    Array.isArray(value) &&
46520    // `isArray(unknown)` is turned into `any[]`:
46521    // type-coverage:ignore-next-line
46522    primitives$G.has(typeof value[0])
46523  ) {
46524    // `isArray(unknown)` is turned into `any[]`:
46525    // type-coverage:ignore-next-line
46526    result = [...value];
46527  } else {
46528    result = [1, value];
46529  }
46530
46531  let level = result[0];
46532
46533  if (typeof level === 'boolean') {
46534    level = level ? 1 : 0;
46535  } else if (typeof level === 'string') {
46536    if (level === 'off') {
46537      level = 0;
46538    } else if (level === 'on' || level === 'warn') {
46539      level = 1;
46540    } else if (level === 'error') {
46541      level = 2;
46542    } else {
46543      level = 1;
46544      result = [level, result];
46545    }
46546  }
46547
46548  if (typeof level !== 'number' || level < 0 || level > 2) {
46549    throw new Error(
46550      'Incorrect severity `' +
46551        level +
46552        '` for `' +
46553        name +
46554        '`, ' +
46555        'expected 0, 1, or 2'
46556    )
46557  }
46558
46559  result[0] = level;
46560
46561  // @ts-expect-error: it’s now a valid tuple.
46562  return result
46563}
46564
46565/**
46566 * @author Titus Wormer
46567 * @copyright 2015 Titus Wormer
46568 * @license MIT
46569 * @module final-newline
46570 * @fileoverview
46571 *   Warn when a line feed at the end of a file is missing.
46572 *   Empty files are allowed.
46573 *
46574 *   See [StackExchange](https://unix.stackexchange.com/questions/18743) for why.
46575 *
46576 *   ## Fix
46577 *
46578 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
46579 *   always adds a final line feed to files.
46580 *
46581 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
46582 *   on how to automatically fix warnings for this rule.
46583 *
46584 *   ## Example
46585 *
46586 *   ##### `ok.md`
46587 *
46588 *   ###### In
46589 *
46590 *   Note: `␊` represents LF.
46591 *
46592 *   ```markdown
46593 *   Alpha␊
46594 *   ```
46595 *
46596 *   ###### Out
46597 *
46598 *   No messages.
46599 *
46600 *   ##### `not-ok.md`
46601 *
46602 *   ###### In
46603 *
46604 *   Note: The below file does not have a final newline.
46605 *
46606 *   ```markdown
46607 *   Bravo
46608 *   ```
46609 *
46610 *   ###### Out
46611 *
46612 *   ```text
46613 *   1:1: Missing newline character at end of file
46614 *   ```
46615 */
46616
46617const remarkLintFinalNewline = lintRule$G(
46618  'remark-lint:final-newline',
46619  /** @type {import('unified-lint-rule').Rule<Root, void>} */
46620  (_, file) => {
46621    const value = String(file);
46622    const last = value.length - 1;
46623
46624    if (last > -1 && value.charAt(last) !== '\n') {
46625      file.message('Missing newline character at end of file');
46626    }
46627  }
46628);
46629
46630var remarkLintFinalNewline$1 = remarkLintFinalNewline;
46631
46632/**
46633 * @typedef {import('unist').Node} Node
46634 * @typedef {import('vfile').VFile} VFile
46635 *
46636 * @typedef {0|1|2} Severity
46637 * @typedef {'warn'|'on'|'off'|'error'} Label
46638 * @typedef {[Severity, ...unknown[]]} SeverityTuple
46639 *
46640 * @callback Rule
46641 * @param {Node} tree
46642 * @param {VFile} file
46643 * @param {unknown} options
46644 * @returns {void}
46645 */
46646
46647const primitives$F = new Set(['string', 'number', 'boolean']);
46648
46649/**
46650 * @param {string} id
46651 * @param {Rule} rule
46652 */
46653function lintRule$F(id, rule) {
46654  const parts = id.split(':');
46655  // Possibly useful if externalised later.
46656  /* c8 ignore next */
46657  const source = parts[1] ? parts[0] : undefined;
46658  const ruleId = parts[1];
46659
46660  Object.defineProperty(plugin, 'name', {value: id});
46661
46662  return plugin
46663
46664  /** @type {import('unified').Plugin<[unknown]|void[]>} */
46665  function plugin(raw) {
46666    const [severity, options] = coerce$G(ruleId, raw);
46667
46668    if (!severity) return
46669
46670    const fatal = severity === 2;
46671
46672    return (tree, file, next) => {
46673      let index = file.messages.length - 1;
46674
46675      wrap(rule, (error) => {
46676        const messages = file.messages;
46677
46678        // Add the error, if not already properly added.
46679        // Only happens for incorrect plugins.
46680        /* c8 ignore next 6 */
46681        // @ts-expect-error: errors could be `messages`.
46682        if (error && !messages.includes(error)) {
46683          try {
46684            file.fail(error);
46685          } catch {}
46686        }
46687
46688        while (++index < messages.length) {
46689          Object.assign(messages[index], {ruleId, source, fatal});
46690        }
46691
46692        next();
46693      })(tree, file, options);
46694    }
46695  }
46696}
46697
46698/**
46699 * Coerce a value to a severity--options tuple.
46700 *
46701 * @param {string} name
46702 * @param {unknown} value
46703 * @returns {SeverityTuple}
46704 */
46705function coerce$G(name, value) {
46706  /** @type {unknown[]} */
46707  let result;
46708
46709  if (typeof value === 'boolean') {
46710    result = [value];
46711  } else if (value === null || value === undefined) {
46712    result = [1];
46713  } else if (
46714    Array.isArray(value) &&
46715    // `isArray(unknown)` is turned into `any[]`:
46716    // type-coverage:ignore-next-line
46717    primitives$F.has(typeof value[0])
46718  ) {
46719    // `isArray(unknown)` is turned into `any[]`:
46720    // type-coverage:ignore-next-line
46721    result = [...value];
46722  } else {
46723    result = [1, value];
46724  }
46725
46726  let level = result[0];
46727
46728  if (typeof level === 'boolean') {
46729    level = level ? 1 : 0;
46730  } else if (typeof level === 'string') {
46731    if (level === 'off') {
46732      level = 0;
46733    } else if (level === 'on' || level === 'warn') {
46734      level = 1;
46735    } else if (level === 'error') {
46736      level = 2;
46737    } else {
46738      level = 1;
46739      result = [level, result];
46740    }
46741  }
46742
46743  if (typeof level !== 'number' || level < 0 || level > 2) {
46744    throw new Error(
46745      'Incorrect severity `' +
46746        level +
46747        '` for `' +
46748        name +
46749        '`, ' +
46750        'expected 0, 1, or 2'
46751    )
46752  }
46753
46754  result[0] = level;
46755
46756  // @ts-expect-error: it’s now a valid tuple.
46757  return result
46758}
46759
46760var pluralize = {exports: {}};
46761
46762/* global define */
46763
46764(function (module, exports) {
46765(function (root, pluralize) {
46766  /* istanbul ignore else */
46767  if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
46768    // Node.
46769    module.exports = pluralize();
46770  } else {
46771    // Browser global.
46772    root.pluralize = pluralize();
46773  }
46774})(commonjsGlobal, function () {
46775  // Rule storage - pluralize and singularize need to be run sequentially,
46776  // while other rules can be optimized using an object for instant lookups.
46777  var pluralRules = [];
46778  var singularRules = [];
46779  var uncountables = {};
46780  var irregularPlurals = {};
46781  var irregularSingles = {};
46782
46783  /**
46784   * Sanitize a pluralization rule to a usable regular expression.
46785   *
46786   * @param  {(RegExp|string)} rule
46787   * @return {RegExp}
46788   */
46789  function sanitizeRule (rule) {
46790    if (typeof rule === 'string') {
46791      return new RegExp('^' + rule + '$', 'i');
46792    }
46793
46794    return rule;
46795  }
46796
46797  /**
46798   * Pass in a word token to produce a function that can replicate the case on
46799   * another word.
46800   *
46801   * @param  {string}   word
46802   * @param  {string}   token
46803   * @return {Function}
46804   */
46805  function restoreCase (word, token) {
46806    // Tokens are an exact match.
46807    if (word === token) return token;
46808
46809    // Lower cased words. E.g. "hello".
46810    if (word === word.toLowerCase()) return token.toLowerCase();
46811
46812    // Upper cased words. E.g. "WHISKY".
46813    if (word === word.toUpperCase()) return token.toUpperCase();
46814
46815    // Title cased words. E.g. "Title".
46816    if (word[0] === word[0].toUpperCase()) {
46817      return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
46818    }
46819
46820    // Lower cased words. E.g. "test".
46821    return token.toLowerCase();
46822  }
46823
46824  /**
46825   * Interpolate a regexp string.
46826   *
46827   * @param  {string} str
46828   * @param  {Array}  args
46829   * @return {string}
46830   */
46831  function interpolate (str, args) {
46832    return str.replace(/\$(\d{1,2})/g, function (match, index) {
46833      return args[index] || '';
46834    });
46835  }
46836
46837  /**
46838   * Replace a word using a rule.
46839   *
46840   * @param  {string} word
46841   * @param  {Array}  rule
46842   * @return {string}
46843   */
46844  function replace (word, rule) {
46845    return word.replace(rule[0], function (match, index) {
46846      var result = interpolate(rule[1], arguments);
46847
46848      if (match === '') {
46849        return restoreCase(word[index - 1], result);
46850      }
46851
46852      return restoreCase(match, result);
46853    });
46854  }
46855
46856  /**
46857   * Sanitize a word by passing in the word and sanitization rules.
46858   *
46859   * @param  {string}   token
46860   * @param  {string}   word
46861   * @param  {Array}    rules
46862   * @return {string}
46863   */
46864  function sanitizeWord (token, word, rules) {
46865    // Empty string or doesn't need fixing.
46866    if (!token.length || uncountables.hasOwnProperty(token)) {
46867      return word;
46868    }
46869
46870    var len = rules.length;
46871
46872    // Iterate over the sanitization rules and use the first one to match.
46873    while (len--) {
46874      var rule = rules[len];
46875
46876      if (rule[0].test(word)) return replace(word, rule);
46877    }
46878
46879    return word;
46880  }
46881
46882  /**
46883   * Replace a word with the updated word.
46884   *
46885   * @param  {Object}   replaceMap
46886   * @param  {Object}   keepMap
46887   * @param  {Array}    rules
46888   * @return {Function}
46889   */
46890  function replaceWord (replaceMap, keepMap, rules) {
46891    return function (word) {
46892      // Get the correct token and case restoration functions.
46893      var token = word.toLowerCase();
46894
46895      // Check against the keep object map.
46896      if (keepMap.hasOwnProperty(token)) {
46897        return restoreCase(word, token);
46898      }
46899
46900      // Check against the replacement map for a direct word replacement.
46901      if (replaceMap.hasOwnProperty(token)) {
46902        return restoreCase(word, replaceMap[token]);
46903      }
46904
46905      // Run all the rules against the word.
46906      return sanitizeWord(token, word, rules);
46907    };
46908  }
46909
46910  /**
46911   * Check if a word is part of the map.
46912   */
46913  function checkWord (replaceMap, keepMap, rules, bool) {
46914    return function (word) {
46915      var token = word.toLowerCase();
46916
46917      if (keepMap.hasOwnProperty(token)) return true;
46918      if (replaceMap.hasOwnProperty(token)) return false;
46919
46920      return sanitizeWord(token, token, rules) === token;
46921    };
46922  }
46923
46924  /**
46925   * Pluralize or singularize a word based on the passed in count.
46926   *
46927   * @param  {string}  word      The word to pluralize
46928   * @param  {number}  count     How many of the word exist
46929   * @param  {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks)
46930   * @return {string}
46931   */
46932  function pluralize (word, count, inclusive) {
46933    var pluralized = count === 1
46934      ? pluralize.singular(word) : pluralize.plural(word);
46935
46936    return (inclusive ? count + ' ' : '') + pluralized;
46937  }
46938
46939  /**
46940   * Pluralize a word.
46941   *
46942   * @type {Function}
46943   */
46944  pluralize.plural = replaceWord(
46945    irregularSingles, irregularPlurals, pluralRules
46946  );
46947
46948  /**
46949   * Check if a word is plural.
46950   *
46951   * @type {Function}
46952   */
46953  pluralize.isPlural = checkWord(
46954    irregularSingles, irregularPlurals, pluralRules
46955  );
46956
46957  /**
46958   * Singularize a word.
46959   *
46960   * @type {Function}
46961   */
46962  pluralize.singular = replaceWord(
46963    irregularPlurals, irregularSingles, singularRules
46964  );
46965
46966  /**
46967   * Check if a word is singular.
46968   *
46969   * @type {Function}
46970   */
46971  pluralize.isSingular = checkWord(
46972    irregularPlurals, irregularSingles, singularRules
46973  );
46974
46975  /**
46976   * Add a pluralization rule to the collection.
46977   *
46978   * @param {(string|RegExp)} rule
46979   * @param {string}          replacement
46980   */
46981  pluralize.addPluralRule = function (rule, replacement) {
46982    pluralRules.push([sanitizeRule(rule), replacement]);
46983  };
46984
46985  /**
46986   * Add a singularization rule to the collection.
46987   *
46988   * @param {(string|RegExp)} rule
46989   * @param {string}          replacement
46990   */
46991  pluralize.addSingularRule = function (rule, replacement) {
46992    singularRules.push([sanitizeRule(rule), replacement]);
46993  };
46994
46995  /**
46996   * Add an uncountable word rule.
46997   *
46998   * @param {(string|RegExp)} word
46999   */
47000  pluralize.addUncountableRule = function (word) {
47001    if (typeof word === 'string') {
47002      uncountables[word.toLowerCase()] = true;
47003      return;
47004    }
47005
47006    // Set singular and plural references for the word.
47007    pluralize.addPluralRule(word, '$0');
47008    pluralize.addSingularRule(word, '$0');
47009  };
47010
47011  /**
47012   * Add an irregular word definition.
47013   *
47014   * @param {string} single
47015   * @param {string} plural
47016   */
47017  pluralize.addIrregularRule = function (single, plural) {
47018    plural = plural.toLowerCase();
47019    single = single.toLowerCase();
47020
47021    irregularSingles[single] = plural;
47022    irregularPlurals[plural] = single;
47023  };
47024
47025  /**
47026   * Irregular rules.
47027   */
47028  [
47029    // Pronouns.
47030    ['I', 'we'],
47031    ['me', 'us'],
47032    ['he', 'they'],
47033    ['she', 'they'],
47034    ['them', 'them'],
47035    ['myself', 'ourselves'],
47036    ['yourself', 'yourselves'],
47037    ['itself', 'themselves'],
47038    ['herself', 'themselves'],
47039    ['himself', 'themselves'],
47040    ['themself', 'themselves'],
47041    ['is', 'are'],
47042    ['was', 'were'],
47043    ['has', 'have'],
47044    ['this', 'these'],
47045    ['that', 'those'],
47046    // Words ending in with a consonant and `o`.
47047    ['echo', 'echoes'],
47048    ['dingo', 'dingoes'],
47049    ['volcano', 'volcanoes'],
47050    ['tornado', 'tornadoes'],
47051    ['torpedo', 'torpedoes'],
47052    // Ends with `us`.
47053    ['genus', 'genera'],
47054    ['viscus', 'viscera'],
47055    // Ends with `ma`.
47056    ['stigma', 'stigmata'],
47057    ['stoma', 'stomata'],
47058    ['dogma', 'dogmata'],
47059    ['lemma', 'lemmata'],
47060    ['schema', 'schemata'],
47061    ['anathema', 'anathemata'],
47062    // Other irregular rules.
47063    ['ox', 'oxen'],
47064    ['axe', 'axes'],
47065    ['die', 'dice'],
47066    ['yes', 'yeses'],
47067    ['foot', 'feet'],
47068    ['eave', 'eaves'],
47069    ['goose', 'geese'],
47070    ['tooth', 'teeth'],
47071    ['quiz', 'quizzes'],
47072    ['human', 'humans'],
47073    ['proof', 'proofs'],
47074    ['carve', 'carves'],
47075    ['valve', 'valves'],
47076    ['looey', 'looies'],
47077    ['thief', 'thieves'],
47078    ['groove', 'grooves'],
47079    ['pickaxe', 'pickaxes'],
47080    ['passerby', 'passersby']
47081  ].forEach(function (rule) {
47082    return pluralize.addIrregularRule(rule[0], rule[1]);
47083  });
47084
47085  /**
47086   * Pluralization rules.
47087   */
47088  [
47089    [/s?$/i, 's'],
47090    [/[^\u0000-\u007F]$/i, '$0'],
47091    [/([^aeiou]ese)$/i, '$1'],
47092    [/(ax|test)is$/i, '$1es'],
47093    [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],
47094    [/(e[mn]u)s?$/i, '$1s'],
47095    [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],
47096    [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
47097    [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
47098    [/(seraph|cherub)(?:im)?$/i, '$1im'],
47099    [/(her|at|gr)o$/i, '$1oes'],
47100    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
47101    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
47102    [/sis$/i, 'ses'],
47103    [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
47104    [/([^aeiouy]|qu)y$/i, '$1ies'],
47105    [/([^ch][ieo][ln])ey$/i, '$1ies'],
47106    [/(x|ch|ss|sh|zz)$/i, '$1es'],
47107    [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
47108    [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],
47109    [/(pe)(?:rson|ople)$/i, '$1ople'],
47110    [/(child)(?:ren)?$/i, '$1ren'],
47111    [/eaux$/i, '$0'],
47112    [/m[ae]n$/i, 'men'],
47113    ['thou', 'you']
47114  ].forEach(function (rule) {
47115    return pluralize.addPluralRule(rule[0], rule[1]);
47116  });
47117
47118  /**
47119   * Singularization rules.
47120   */
47121  [
47122    [/s$/i, ''],
47123    [/(ss)$/i, '$1'],
47124    [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
47125    [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
47126    [/ies$/i, 'y'],
47127    [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],
47128    [/\b(mon|smil)ies$/i, '$1ey'],
47129    [/\b((?:tit)?m|l)ice$/i, '$1ouse'],
47130    [/(seraph|cherub)im$/i, '$1'],
47131    [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'],
47132    [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'],
47133    [/(movie|twelve|abuse|e[mn]u)s$/i, '$1'],
47134    [/(test)(?:is|es)$/i, '$1is'],
47135    [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
47136    [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
47137    [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
47138    [/(alumn|alg|vertebr)ae$/i, '$1a'],
47139    [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
47140    [/(matr|append)ices$/i, '$1ix'],
47141    [/(pe)(rson|ople)$/i, '$1rson'],
47142    [/(child)ren$/i, '$1'],
47143    [/(eau)x?$/i, '$1'],
47144    [/men$/i, 'man']
47145  ].forEach(function (rule) {
47146    return pluralize.addSingularRule(rule[0], rule[1]);
47147  });
47148
47149  /**
47150   * Uncountable rules.
47151   */
47152  [
47153    // Singular words with no plurals.
47154    'adulthood',
47155    'advice',
47156    'agenda',
47157    'aid',
47158    'aircraft',
47159    'alcohol',
47160    'ammo',
47161    'analytics',
47162    'anime',
47163    'athletics',
47164    'audio',
47165    'bison',
47166    'blood',
47167    'bream',
47168    'buffalo',
47169    'butter',
47170    'carp',
47171    'cash',
47172    'chassis',
47173    'chess',
47174    'clothing',
47175    'cod',
47176    'commerce',
47177    'cooperation',
47178    'corps',
47179    'debris',
47180    'diabetes',
47181    'digestion',
47182    'elk',
47183    'energy',
47184    'equipment',
47185    'excretion',
47186    'expertise',
47187    'firmware',
47188    'flounder',
47189    'fun',
47190    'gallows',
47191    'garbage',
47192    'graffiti',
47193    'hardware',
47194    'headquarters',
47195    'health',
47196    'herpes',
47197    'highjinks',
47198    'homework',
47199    'housework',
47200    'information',
47201    'jeans',
47202    'justice',
47203    'kudos',
47204    'labour',
47205    'literature',
47206    'machinery',
47207    'mackerel',
47208    'mail',
47209    'media',
47210    'mews',
47211    'moose',
47212    'music',
47213    'mud',
47214    'manga',
47215    'news',
47216    'only',
47217    'personnel',
47218    'pike',
47219    'plankton',
47220    'pliers',
47221    'police',
47222    'pollution',
47223    'premises',
47224    'rain',
47225    'research',
47226    'rice',
47227    'salmon',
47228    'scissors',
47229    'series',
47230    'sewage',
47231    'shambles',
47232    'shrimp',
47233    'software',
47234    'species',
47235    'staff',
47236    'swine',
47237    'tennis',
47238    'traffic',
47239    'transportation',
47240    'trout',
47241    'tuna',
47242    'wealth',
47243    'welfare',
47244    'whiting',
47245    'wildebeest',
47246    'wildlife',
47247    'you',
47248    /pok[eé]mon$/i,
47249    // Regexes.
47250    /[^aeiou]ese$/i, // "chinese", "japanese"
47251    /deer$/i, // "deer", "reindeer"
47252    /fish$/i, // "fish", "blowfish", "angelfish"
47253    /measles$/i,
47254    /o[iu]s$/i, // "carnivorous"
47255    /pox$/i, // "chickpox", "smallpox"
47256    /sheep$/i
47257  ].forEach(pluralize.addUncountableRule);
47258
47259  return pluralize;
47260});
47261}(pluralize));
47262
47263var plural = pluralize.exports;
47264
47265/**
47266 * @param {string} d
47267 * @returns {string}
47268 */
47269function color$1(d) {
47270  return '\u001B[33m' + d + '\u001B[39m'
47271}
47272
47273/**
47274 * @typedef {import('unist').Node} Node
47275 * @typedef {import('unist').Parent} Parent
47276 * @typedef {import('unist-util-is').Test} Test
47277 */
47278
47279/**
47280 * Continue traversing as normal
47281 */
47282const CONTINUE$1 = true;
47283/**
47284 * Do not traverse this node’s children
47285 */
47286const SKIP$1 = 'skip';
47287/**
47288 * Stop traversing immediately
47289 */
47290const EXIT$1 = false;
47291
47292/**
47293 * Visit children of tree which pass a test
47294 *
47295 * @param tree Abstract syntax tree to walk
47296 * @param test Test node, optional
47297 * @param visitor Function to run for each node
47298 * @param reverse Visit the tree in reverse order, defaults to false
47299 */
47300const visitParents$1 =
47301  /**
47302   * @type {(
47303   *   (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: Visitor<import('./complex-types').Matches<import('./complex-types').InclusiveDescendant<Tree>, Check>>, reverse?: boolean) => void) &
47304   *   (<Tree extends Node>(tree: Tree, visitor: Visitor<import('./complex-types').InclusiveDescendant<Tree>>, reverse?: boolean) => void)
47305   * )}
47306   */
47307  (
47308    /**
47309     * @param {Node} tree
47310     * @param {Test} test
47311     * @param {Visitor<Node>} visitor
47312     * @param {boolean} [reverse]
47313     */
47314    function (tree, test, visitor, reverse) {
47315      if (typeof test === 'function' && typeof visitor !== 'function') {
47316        reverse = visitor;
47317        // @ts-expect-error no visitor given, so `visitor` is test.
47318        visitor = test;
47319        test = null;
47320      }
47321
47322      const is = convert(test);
47323      const step = reverse ? -1 : 1;
47324
47325      factory(tree, null, [])();
47326
47327      /**
47328       * @param {Node} node
47329       * @param {number?} index
47330       * @param {Array.<Parent>} parents
47331       */
47332      function factory(node, index, parents) {
47333        /** @type {Object.<string, unknown>} */
47334        // @ts-expect-error: hush
47335        const value = typeof node === 'object' && node !== null ? node : {};
47336        /** @type {string|undefined} */
47337        let name;
47338
47339        if (typeof value.type === 'string') {
47340          name =
47341            typeof value.tagName === 'string'
47342              ? value.tagName
47343              : typeof value.name === 'string'
47344              ? value.name
47345              : undefined;
47346
47347          Object.defineProperty(visit, 'name', {
47348            value:
47349              'node (' +
47350              color$1(value.type + (name ? '<' + name + '>' : '')) +
47351              ')'
47352          });
47353        }
47354
47355        return visit
47356
47357        function visit() {
47358          /** @type {ActionTuple} */
47359          let result = [];
47360          /** @type {ActionTuple} */
47361          let subresult;
47362          /** @type {number} */
47363          let offset;
47364          /** @type {Array.<Parent>} */
47365          let grandparents;
47366
47367          if (!test || is(node, index, parents[parents.length - 1] || null)) {
47368            result = toResult$1(visitor(node, parents));
47369
47370            if (result[0] === EXIT$1) {
47371              return result
47372            }
47373          }
47374
47375          // @ts-expect-error looks like a parent.
47376          if (node.children && result[0] !== SKIP$1) {
47377            // @ts-expect-error looks like a parent.
47378            offset = (reverse ? node.children.length : -1) + step;
47379            // @ts-expect-error looks like a parent.
47380            grandparents = parents.concat(node);
47381
47382            // @ts-expect-error looks like a parent.
47383            while (offset > -1 && offset < node.children.length) {
47384              // @ts-expect-error looks like a parent.
47385              subresult = factory(node.children[offset], offset, grandparents)();
47386
47387              if (subresult[0] === EXIT$1) {
47388                return subresult
47389              }
47390
47391              offset =
47392                typeof subresult[1] === 'number' ? subresult[1] : offset + step;
47393            }
47394          }
47395
47396          return result
47397        }
47398      }
47399    }
47400  );
47401
47402/**
47403 * @param {VisitorResult} value
47404 * @returns {ActionTuple}
47405 */
47406function toResult$1(value) {
47407  if (Array.isArray(value)) {
47408    return value
47409  }
47410
47411  if (typeof value === 'number') {
47412    return [CONTINUE$1, value]
47413  }
47414
47415  return [value]
47416}
47417
47418/**
47419 * @typedef {import('unist').Node} Node
47420 * @typedef {import('unist').Parent} Parent
47421 * @typedef {import('unist-util-is').Test} Test
47422 * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult
47423 */
47424
47425/**
47426 * Visit children of tree which pass a test
47427 *
47428 * @param tree Abstract syntax tree to walk
47429 * @param test Test, optional
47430 * @param visitor Function to run for each node
47431 * @param reverse Fisit the tree in reverse, defaults to false
47432 */
47433const visit =
47434  /**
47435   * @type {(
47436   *   (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: Visitor<import('unist-util-visit-parents/complex-types').Matches<import('unist-util-visit-parents/complex-types').InclusiveDescendant<Tree>, Check>>, reverse?: boolean) => void) &
47437   *   (<Tree extends Node>(tree: Tree, visitor: Visitor<import('unist-util-visit-parents/complex-types').InclusiveDescendant<Tree>>, reverse?: boolean) => void)
47438   * )}
47439   */
47440  (
47441    /**
47442     * @param {Node} tree
47443     * @param {Test} test
47444     * @param {Visitor<Node>} visitor
47445     * @param {boolean} [reverse]
47446     */
47447    function (tree, test, visitor, reverse) {
47448      if (typeof test === 'function' && typeof visitor !== 'function') {
47449        reverse = visitor;
47450        visitor = test;
47451        test = null;
47452      }
47453
47454      visitParents$1(tree, test, overload, reverse);
47455
47456      /**
47457       * @param {Node} node
47458       * @param {Array.<Parent>} parents
47459       */
47460      function overload(node, parents) {
47461        const parent = parents[parents.length - 1];
47462        return visitor(
47463          node,
47464          parent ? parent.children.indexOf(node) : null,
47465          parent
47466        )
47467      }
47468    }
47469  );
47470
47471/**
47472 * @author Titus Wormer
47473 * @copyright 2015 Titus Wormer
47474 * @license MIT
47475 * @module list-item-bullet-indent
47476 * @fileoverview
47477 *   Warn when list item bullets are indented.
47478 *
47479 *   ## Fix
47480 *
47481 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
47482 *   removes all indentation before bullets.
47483 *
47484 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
47485 *   on how to automatically fix warnings for this rule.
47486 *
47487 * @example
47488 *   {"name": "ok.md"}
47489 *
47490 *   Paragraph.
47491 *
47492 *   * List item
47493 *   * List item
47494 *
47495 * @example
47496 *   {"name": "not-ok.md", "label": "input"}
47497 *
47498 *   Paragraph.
47499 *
47500 *   ·* List item
47501 *   ·* List item
47502 *
47503 * @example
47504 *   {"name": "not-ok.md", "label": "output"}
47505 *
47506 *   3:2: Incorrect indentation before bullet: remove 1 space
47507 *   4:2: Incorrect indentation before bullet: remove 1 space
47508 */
47509
47510const remarkLintListItemBulletIndent = lintRule$F(
47511  'remark-lint:list-item-bullet-indent',
47512  /** @type {import('unified-lint-rule').Rule<Root, void>} */
47513  (tree, file) => {
47514    visit(tree, 'list', (list, _, grandparent) => {
47515      let index = -1;
47516
47517      while (++index < list.children.length) {
47518        const item = list.children[index];
47519
47520        if (
47521          grandparent &&
47522          grandparent.type === 'root' &&
47523          grandparent.position &&
47524          typeof grandparent.position.start.column === 'number' &&
47525          item.position &&
47526          typeof item.position.start.column === 'number'
47527        ) {
47528          const indent =
47529            item.position.start.column - grandparent.position.start.column;
47530
47531          if (indent) {
47532            file.message(
47533              'Incorrect indentation before bullet: remove ' +
47534                indent +
47535                ' ' +
47536                plural('space', indent),
47537              item.position.start
47538            );
47539          }
47540        }
47541      }
47542    });
47543  }
47544);
47545
47546var remarkLintListItemBulletIndent$1 = remarkLintListItemBulletIndent;
47547
47548/**
47549 * @typedef {import('unist').Node} Node
47550 * @typedef {import('vfile').VFile} VFile
47551 *
47552 * @typedef {0|1|2} Severity
47553 * @typedef {'warn'|'on'|'off'|'error'} Label
47554 * @typedef {[Severity, ...unknown[]]} SeverityTuple
47555 *
47556 * @callback Rule
47557 * @param {Node} tree
47558 * @param {VFile} file
47559 * @param {unknown} options
47560 * @returns {void}
47561 */
47562
47563const primitives$E = new Set(['string', 'number', 'boolean']);
47564
47565/**
47566 * @param {string} id
47567 * @param {Rule} rule
47568 */
47569function lintRule$E(id, rule) {
47570  const parts = id.split(':');
47571  // Possibly useful if externalised later.
47572  /* c8 ignore next */
47573  const source = parts[1] ? parts[0] : undefined;
47574  const ruleId = parts[1];
47575
47576  Object.defineProperty(plugin, 'name', {value: id});
47577
47578  return plugin
47579
47580  /** @type {import('unified').Plugin<[unknown]|void[]>} */
47581  function plugin(raw) {
47582    const [severity, options] = coerce$F(ruleId, raw);
47583
47584    if (!severity) return
47585
47586    const fatal = severity === 2;
47587
47588    return (tree, file, next) => {
47589      let index = file.messages.length - 1;
47590
47591      wrap(rule, (error) => {
47592        const messages = file.messages;
47593
47594        // Add the error, if not already properly added.
47595        // Only happens for incorrect plugins.
47596        /* c8 ignore next 6 */
47597        // @ts-expect-error: errors could be `messages`.
47598        if (error && !messages.includes(error)) {
47599          try {
47600            file.fail(error);
47601          } catch {}
47602        }
47603
47604        while (++index < messages.length) {
47605          Object.assign(messages[index], {ruleId, source, fatal});
47606        }
47607
47608        next();
47609      })(tree, file, options);
47610    }
47611  }
47612}
47613
47614/**
47615 * Coerce a value to a severity--options tuple.
47616 *
47617 * @param {string} name
47618 * @param {unknown} value
47619 * @returns {SeverityTuple}
47620 */
47621function coerce$F(name, value) {
47622  /** @type {unknown[]} */
47623  let result;
47624
47625  if (typeof value === 'boolean') {
47626    result = [value];
47627  } else if (value === null || value === undefined) {
47628    result = [1];
47629  } else if (
47630    Array.isArray(value) &&
47631    // `isArray(unknown)` is turned into `any[]`:
47632    // type-coverage:ignore-next-line
47633    primitives$E.has(typeof value[0])
47634  ) {
47635    // `isArray(unknown)` is turned into `any[]`:
47636    // type-coverage:ignore-next-line
47637    result = [...value];
47638  } else {
47639    result = [1, value];
47640  }
47641
47642  let level = result[0];
47643
47644  if (typeof level === 'boolean') {
47645    level = level ? 1 : 0;
47646  } else if (typeof level === 'string') {
47647    if (level === 'off') {
47648      level = 0;
47649    } else if (level === 'on' || level === 'warn') {
47650      level = 1;
47651    } else if (level === 'error') {
47652      level = 2;
47653    } else {
47654      level = 1;
47655      result = [level, result];
47656    }
47657  }
47658
47659  if (typeof level !== 'number' || level < 0 || level > 2) {
47660    throw new Error(
47661      'Incorrect severity `' +
47662        level +
47663        '` for `' +
47664        name +
47665        '`, ' +
47666        'expected 0, 1, or 2'
47667    )
47668  }
47669
47670  result[0] = level;
47671
47672  // @ts-expect-error: it’s now a valid tuple.
47673  return result
47674}
47675
47676/**
47677 * @typedef {import('unist').Position} Position
47678 * @typedef {import('unist').Point} Point
47679 *
47680 * @typedef {Partial<Point>} PointLike
47681 *
47682 * @typedef {Object} PositionLike
47683 * @property {PointLike} [start]
47684 * @property {PointLike} [end]
47685 *
47686 * @typedef {Object} NodeLike
47687 * @property {PositionLike} [position]
47688 */
47689
47690var pointStart = point('start');
47691var pointEnd = point('end');
47692
47693/**
47694 * Get the positional info of `node`.
47695 *
47696 * @param {'start'|'end'} type
47697 */
47698function point(type) {
47699  return point
47700
47701  /**
47702   * Get the positional info of `node`.
47703   *
47704   * @param {NodeLike} [node]
47705   * @returns {Point}
47706   */
47707  function point(node) {
47708    /** @type {Point} */
47709    // @ts-ignore looks like a point
47710    var point = (node && node.position && node.position[type]) || {};
47711
47712    return {
47713      line: point.line || null,
47714      column: point.column || null,
47715      offset: point.offset > -1 ? point.offset : null
47716    }
47717  }
47718}
47719
47720/**
47721 * @typedef {Object} PointLike
47722 * @property {number} [line]
47723 * @property {number} [column]
47724 * @property {number} [offset]
47725 *
47726 * @typedef {Object} PositionLike
47727 * @property {PointLike} [start]
47728 * @property {PointLike} [end]
47729 *
47730 * @typedef {Object} NodeLike
47731 * @property {PositionLike} [position]
47732 */
47733
47734/**
47735 * Check if `node` is *generated*.
47736 *
47737 * @param {NodeLike} [node]
47738 * @returns {boolean}
47739 */
47740function generated(node) {
47741  return (
47742    !node ||
47743    !node.position ||
47744    !node.position.start ||
47745    !node.position.start.line ||
47746    !node.position.start.column ||
47747    !node.position.end ||
47748    !node.position.end.line ||
47749    !node.position.end.column
47750  )
47751}
47752
47753/**
47754 * @author Titus Wormer
47755 * @copyright 2015 Titus Wormer
47756 * @license MIT
47757 * @module list-item-indent
47758 * @fileoverview
47759 *   Warn when the spacing between a list item’s bullet and its content violates
47760 *   a given style.
47761 *
47762 *   Options: `'tab-size'`, `'mixed'`, or `'space'`, default: `'tab-size'`.
47763 *
47764 *   ## Fix
47765 *
47766 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
47767 *   uses `'tab-size'` (named `'tab'` there) by default to ensure Markdown is
47768 *   seen the same way across vendors.
47769 *   This can be configured with the
47770 *   [`listItemIndent`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionslistitemindent)
47771 *   option.
47772 *   This rule’s `'space'` option is named `'1'` there.
47773 *
47774 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
47775 *   on how to automatically fix warnings for this rule.
47776 *
47777 * @example
47778 *   {"name": "ok.md"}
47779 *
47780 *   *···List
47781 *   ····item.
47782 *
47783 *   Paragraph.
47784 *
47785 *   11.·List
47786 *   ····item.
47787 *
47788 *   Paragraph.
47789 *
47790 *   *···List
47791 *   ····item.
47792 *
47793 *   *···List
47794 *   ····item.
47795 *
47796 * @example
47797 *   {"name": "ok.md", "setting": "mixed"}
47798 *
47799 *   *·List item.
47800 *
47801 *   Paragraph.
47802 *
47803 *   11.·List item
47804 *
47805 *   Paragraph.
47806 *
47807 *   *···List
47808 *   ····item.
47809 *
47810 *   *···List
47811 *   ····item.
47812 *
47813 * @example
47814 *   {"name": "ok.md", "setting": "space"}
47815 *
47816 *   *·List item.
47817 *
47818 *   Paragraph.
47819 *
47820 *   11.·List item
47821 *
47822 *   Paragraph.
47823 *
47824 *   *·List
47825 *   ··item.
47826 *
47827 *   *·List
47828 *   ··item.
47829 *
47830 * @example
47831 *   {"name": "not-ok.md", "setting": "space", "label": "input"}
47832 *
47833 *   *···List
47834 *   ····item.
47835 *
47836 * @example
47837 *   {"name": "not-ok.md", "setting": "space", "label": "output"}
47838 *
47839 *    1:5: Incorrect list-item indent: remove 2 spaces
47840 *
47841 * @example
47842 *   {"name": "not-ok.md", "setting": "tab-size", "label": "input"}
47843 *
47844 *   *·List
47845 *   ··item.
47846 *
47847 * @example
47848 *   {"name": "not-ok.md", "setting": "tab-size", "label": "output"}
47849 *
47850 *    1:3: Incorrect list-item indent: add 2 spaces
47851 *
47852 * @example
47853 *   {"name": "not-ok.md", "setting": "mixed", "label": "input"}
47854 *
47855 *   *···List item.
47856 *
47857 * @example
47858 *   {"name": "not-ok.md", "setting": "mixed", "label": "output"}
47859 *
47860 *    1:5: Incorrect list-item indent: remove 2 spaces
47861 *
47862 * @example
47863 *   {"name": "not-ok.md", "setting": "��", "label": "output", "positionless": true}
47864 *
47865 *    1:1: Incorrect list-item indent style `��`: use either `'tab-size'`, `'space'`, or `'mixed'`
47866 */
47867
47868const remarkLintListItemIndent = lintRule$E(
47869  'remark-lint:list-item-indent',
47870  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
47871  (tree, file, option = 'tab-size') => {
47872    const value = String(file);
47873
47874    if (option !== 'tab-size' && option !== 'space' && option !== 'mixed') {
47875      file.fail(
47876        'Incorrect list-item indent style `' +
47877          option +
47878          "`: use either `'tab-size'`, `'space'`, or `'mixed'`"
47879      );
47880    }
47881
47882    visit(tree, 'list', (node) => {
47883      if (generated(node)) return
47884
47885      const spread = node.spread;
47886      let index = -1;
47887
47888      while (++index < node.children.length) {
47889        const item = node.children[index];
47890        const head = item.children[0];
47891        const final = pointStart(head);
47892
47893        const marker = value
47894          .slice(pointStart(item).offset, final.offset)
47895          .replace(/\[[x ]?]\s*$/i, '');
47896
47897        const bulletSize = marker.replace(/\s+$/, '').length;
47898
47899        const style =
47900          option === 'tab-size' || (option === 'mixed' && spread)
47901            ? Math.ceil(bulletSize / 4) * 4
47902            : bulletSize + 1;
47903
47904        if (marker.length !== style) {
47905          const diff = style - marker.length;
47906          const abs = Math.abs(diff);
47907
47908          file.message(
47909            'Incorrect list-item indent: ' +
47910              (diff > 0 ? 'add' : 'remove') +
47911              ' ' +
47912              abs +
47913              ' ' +
47914              plural('space', abs),
47915            final
47916          );
47917        }
47918      }
47919    });
47920  }
47921);
47922
47923var remarkLintListItemIndent$1 = remarkLintListItemIndent;
47924
47925/**
47926 * @typedef {import('unist').Node} Node
47927 * @typedef {import('vfile').VFile} VFile
47928 *
47929 * @typedef {0|1|2} Severity
47930 * @typedef {'warn'|'on'|'off'|'error'} Label
47931 * @typedef {[Severity, ...unknown[]]} SeverityTuple
47932 *
47933 * @callback Rule
47934 * @param {Node} tree
47935 * @param {VFile} file
47936 * @param {unknown} options
47937 * @returns {void}
47938 */
47939
47940const primitives$D = new Set(['string', 'number', 'boolean']);
47941
47942/**
47943 * @param {string} id
47944 * @param {Rule} rule
47945 */
47946function lintRule$D(id, rule) {
47947  const parts = id.split(':');
47948  // Possibly useful if externalised later.
47949  /* c8 ignore next */
47950  const source = parts[1] ? parts[0] : undefined;
47951  const ruleId = parts[1];
47952
47953  Object.defineProperty(plugin, 'name', {value: id});
47954
47955  return plugin
47956
47957  /** @type {import('unified').Plugin<[unknown]|void[]>} */
47958  function plugin(raw) {
47959    const [severity, options] = coerce$E(ruleId, raw);
47960
47961    if (!severity) return
47962
47963    const fatal = severity === 2;
47964
47965    return (tree, file, next) => {
47966      let index = file.messages.length - 1;
47967
47968      wrap(rule, (error) => {
47969        const messages = file.messages;
47970
47971        // Add the error, if not already properly added.
47972        // Only happens for incorrect plugins.
47973        /* c8 ignore next 6 */
47974        // @ts-expect-error: errors could be `messages`.
47975        if (error && !messages.includes(error)) {
47976          try {
47977            file.fail(error);
47978          } catch {}
47979        }
47980
47981        while (++index < messages.length) {
47982          Object.assign(messages[index], {ruleId, source, fatal});
47983        }
47984
47985        next();
47986      })(tree, file, options);
47987    }
47988  }
47989}
47990
47991/**
47992 * Coerce a value to a severity--options tuple.
47993 *
47994 * @param {string} name
47995 * @param {unknown} value
47996 * @returns {SeverityTuple}
47997 */
47998function coerce$E(name, value) {
47999  /** @type {unknown[]} */
48000  let result;
48001
48002  if (typeof value === 'boolean') {
48003    result = [value];
48004  } else if (value === null || value === undefined) {
48005    result = [1];
48006  } else if (
48007    Array.isArray(value) &&
48008    // `isArray(unknown)` is turned into `any[]`:
48009    // type-coverage:ignore-next-line
48010    primitives$D.has(typeof value[0])
48011  ) {
48012    // `isArray(unknown)` is turned into `any[]`:
48013    // type-coverage:ignore-next-line
48014    result = [...value];
48015  } else {
48016    result = [1, value];
48017  }
48018
48019  let level = result[0];
48020
48021  if (typeof level === 'boolean') {
48022    level = level ? 1 : 0;
48023  } else if (typeof level === 'string') {
48024    if (level === 'off') {
48025      level = 0;
48026    } else if (level === 'on' || level === 'warn') {
48027      level = 1;
48028    } else if (level === 'error') {
48029      level = 2;
48030    } else {
48031      level = 1;
48032      result = [level, result];
48033    }
48034  }
48035
48036  if (typeof level !== 'number' || level < 0 || level > 2) {
48037    throw new Error(
48038      'Incorrect severity `' +
48039        level +
48040        '` for `' +
48041        name +
48042        '`, ' +
48043        'expected 0, 1, or 2'
48044    )
48045  }
48046
48047  result[0] = level;
48048
48049  // @ts-expect-error: it’s now a valid tuple.
48050  return result
48051}
48052
48053/**
48054 * @author Titus Wormer
48055 * @copyright 2015 Titus Wormer
48056 * @license MIT
48057 * @module no-auto-link-without-protocol
48058 * @fileoverview
48059 *   Warn for autolinks without protocol.
48060 *   Autolinks are URLs enclosed in `<` (less than) and `>` (greater than)
48061 *   characters.
48062 *
48063 *   ## Fix
48064 *
48065 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
48066 *   adds a protocol where needed.
48067 *
48068 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
48069 *   on how to automatically fix warnings for this rule.
48070 *
48071 * @example
48072 *   {"name": "ok.md"}
48073 *
48074 *   <http://www.example.com>
48075 *   <mailto:foo@bar.com>
48076 *
48077 *   Most Markdown vendors don’t recognize the following as a link:
48078 *   <www.example.com>
48079 *
48080 * @example
48081 *   {"name": "not-ok.md", "label": "input"}
48082 *
48083 *   <foo@bar.com>
48084 *
48085 * @example
48086 *   {"name": "not-ok.md", "label": "output"}
48087 *
48088 *   1:1-1:14: All automatic links must start with a protocol
48089 */
48090
48091// Protocol expression.
48092// See: <https://en.wikipedia.org/wiki/URI_scheme#Generic_syntax>.
48093const protocol = /^[a-z][a-z+.-]+:\/?/i;
48094
48095const remarkLintNoAutoLinkWithoutProtocol = lintRule$D(
48096  'remark-lint:no-auto-link-without-protocol',
48097  /** @type {import('unified-lint-rule').Rule<Root, void>} */
48098  (tree, file) => {
48099    visit(tree, 'link', (node) => {
48100      if (
48101        !generated(node) &&
48102        pointStart(node).column === pointStart(node.children[0]).column - 1 &&
48103        pointEnd(node).column ===
48104          pointEnd(node.children[node.children.length - 1]).column + 1 &&
48105        !protocol.test(toString(node))
48106      ) {
48107        file.message('All automatic links must start with a protocol', node);
48108      }
48109    });
48110  }
48111);
48112
48113var remarkLintNoAutoLinkWithoutProtocol$1 = remarkLintNoAutoLinkWithoutProtocol;
48114
48115/**
48116 * @typedef {import('unist').Node} Node
48117 * @typedef {import('vfile').VFile} VFile
48118 *
48119 * @typedef {0|1|2} Severity
48120 * @typedef {'warn'|'on'|'off'|'error'} Label
48121 * @typedef {[Severity, ...unknown[]]} SeverityTuple
48122 *
48123 * @callback Rule
48124 * @param {Node} tree
48125 * @param {VFile} file
48126 * @param {unknown} options
48127 * @returns {void}
48128 */
48129
48130const primitives$C = new Set(['string', 'number', 'boolean']);
48131
48132/**
48133 * @param {string} id
48134 * @param {Rule} rule
48135 */
48136function lintRule$C(id, rule) {
48137  const parts = id.split(':');
48138  // Possibly useful if externalised later.
48139  /* c8 ignore next */
48140  const source = parts[1] ? parts[0] : undefined;
48141  const ruleId = parts[1];
48142
48143  Object.defineProperty(plugin, 'name', {value: id});
48144
48145  return plugin
48146
48147  /** @type {import('unified').Plugin<[unknown]|void[]>} */
48148  function plugin(raw) {
48149    const [severity, options] = coerce$D(ruleId, raw);
48150
48151    if (!severity) return
48152
48153    const fatal = severity === 2;
48154
48155    return (tree, file, next) => {
48156      let index = file.messages.length - 1;
48157
48158      wrap(rule, (error) => {
48159        const messages = file.messages;
48160
48161        // Add the error, if not already properly added.
48162        // Only happens for incorrect plugins.
48163        /* c8 ignore next 6 */
48164        // @ts-expect-error: errors could be `messages`.
48165        if (error && !messages.includes(error)) {
48166          try {
48167            file.fail(error);
48168          } catch {}
48169        }
48170
48171        while (++index < messages.length) {
48172          Object.assign(messages[index], {ruleId, source, fatal});
48173        }
48174
48175        next();
48176      })(tree, file, options);
48177    }
48178  }
48179}
48180
48181/**
48182 * Coerce a value to a severity--options tuple.
48183 *
48184 * @param {string} name
48185 * @param {unknown} value
48186 * @returns {SeverityTuple}
48187 */
48188function coerce$D(name, value) {
48189  /** @type {unknown[]} */
48190  let result;
48191
48192  if (typeof value === 'boolean') {
48193    result = [value];
48194  } else if (value === null || value === undefined) {
48195    result = [1];
48196  } else if (
48197    Array.isArray(value) &&
48198    // `isArray(unknown)` is turned into `any[]`:
48199    // type-coverage:ignore-next-line
48200    primitives$C.has(typeof value[0])
48201  ) {
48202    // `isArray(unknown)` is turned into `any[]`:
48203    // type-coverage:ignore-next-line
48204    result = [...value];
48205  } else {
48206    result = [1, value];
48207  }
48208
48209  let level = result[0];
48210
48211  if (typeof level === 'boolean') {
48212    level = level ? 1 : 0;
48213  } else if (typeof level === 'string') {
48214    if (level === 'off') {
48215      level = 0;
48216    } else if (level === 'on' || level === 'warn') {
48217      level = 1;
48218    } else if (level === 'error') {
48219      level = 2;
48220    } else {
48221      level = 1;
48222      result = [level, result];
48223    }
48224  }
48225
48226  if (typeof level !== 'number' || level < 0 || level > 2) {
48227    throw new Error(
48228      'Incorrect severity `' +
48229        level +
48230        '` for `' +
48231        name +
48232        '`, ' +
48233        'expected 0, 1, or 2'
48234    )
48235  }
48236
48237  result[0] = level;
48238
48239  // @ts-expect-error: it’s now a valid tuple.
48240  return result
48241}
48242
48243/**
48244 * @author Titus Wormer
48245 * @copyright 2015 Titus Wormer
48246 * @license MIT
48247 * @module no-blockquote-without-marker
48248 * @fileoverview
48249 *   Warn when blank lines without `>` (greater than) markers are found in a
48250 *   block quote.
48251 *
48252 *   ## Fix
48253 *
48254 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
48255 *   adds markers to every line in a block quote.
48256 *
48257 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
48258 *   on how to automatically fix warnings for this rule.
48259 *
48260 * @example
48261 *   {"name": "ok.md"}
48262 *
48263 *   > Foo…
48264 *   > …bar…
48265 *   > …baz.
48266 *
48267 * @example
48268 *   {"name": "ok-tabs.md"}
48269 *
48270 *   >»Foo…
48271 *   >»…bar…
48272 *   >»…baz.
48273 *
48274 * @example
48275 *   {"name": "not-ok.md", "label": "input"}
48276 *
48277 *   > Foo…
48278 *   …bar…
48279 *   > …baz.
48280 *
48281 * @example
48282 *   {"name": "not-ok.md", "label": "output"}
48283 *
48284 *   2:1: Missing marker in block quote
48285 *
48286 * @example
48287 *   {"name": "not-ok-tabs.md", "label": "input"}
48288 *
48289 *   >»Foo…
48290 *   »…bar…
48291 *   …baz.
48292 *
48293 * @example
48294 *   {"name": "not-ok-tabs.md", "label": "output"}
48295 *
48296 *   2:1: Missing marker in block quote
48297 *   3:1: Missing marker in block quote
48298 */
48299
48300const remarkLintNoBlockquoteWithoutMarker = lintRule$C(
48301  'remark-lint:no-blockquote-without-marker',
48302  /** @type {import('unified-lint-rule').Rule<Root, void>} */
48303  (tree, file) => {
48304    const value = String(file);
48305    const loc = location(file);
48306
48307    visit(tree, 'blockquote', (node) => {
48308      let index = -1;
48309
48310      while (++index < node.children.length) {
48311        const child = node.children[index];
48312
48313        if (child.type === 'paragraph' && !generated(child)) {
48314          const end = pointEnd(child).line;
48315          const column = pointStart(child).column;
48316          let line = pointStart(child).line;
48317
48318          // Skip past the first line.
48319          while (++line <= end) {
48320            const offset = loc.toOffset({line, column});
48321
48322            if (/>[\t ]+$/.test(value.slice(offset - 5, offset))) {
48323              continue
48324            }
48325
48326            // Roughly here.
48327            file.message('Missing marker in block quote', {
48328              line,
48329              column: column - 2
48330            });
48331          }
48332        }
48333      }
48334    });
48335  }
48336);
48337
48338var remarkLintNoBlockquoteWithoutMarker$1 = remarkLintNoBlockquoteWithoutMarker;
48339
48340/**
48341 * @typedef {import('unist').Node} Node
48342 * @typedef {import('vfile').VFile} VFile
48343 *
48344 * @typedef {0|1|2} Severity
48345 * @typedef {'warn'|'on'|'off'|'error'} Label
48346 * @typedef {[Severity, ...unknown[]]} SeverityTuple
48347 *
48348 * @callback Rule
48349 * @param {Node} tree
48350 * @param {VFile} file
48351 * @param {unknown} options
48352 * @returns {void}
48353 */
48354
48355const primitives$B = new Set(['string', 'number', 'boolean']);
48356
48357/**
48358 * @param {string} id
48359 * @param {Rule} rule
48360 */
48361function lintRule$B(id, rule) {
48362  const parts = id.split(':');
48363  // Possibly useful if externalised later.
48364  /* c8 ignore next */
48365  const source = parts[1] ? parts[0] : undefined;
48366  const ruleId = parts[1];
48367
48368  Object.defineProperty(plugin, 'name', {value: id});
48369
48370  return plugin
48371
48372  /** @type {import('unified').Plugin<[unknown]|void[]>} */
48373  function plugin(raw) {
48374    const [severity, options] = coerce$C(ruleId, raw);
48375
48376    if (!severity) return
48377
48378    const fatal = severity === 2;
48379
48380    return (tree, file, next) => {
48381      let index = file.messages.length - 1;
48382
48383      wrap(rule, (error) => {
48384        const messages = file.messages;
48385
48386        // Add the error, if not already properly added.
48387        // Only happens for incorrect plugins.
48388        /* c8 ignore next 6 */
48389        // @ts-expect-error: errors could be `messages`.
48390        if (error && !messages.includes(error)) {
48391          try {
48392            file.fail(error);
48393          } catch {}
48394        }
48395
48396        while (++index < messages.length) {
48397          Object.assign(messages[index], {ruleId, source, fatal});
48398        }
48399
48400        next();
48401      })(tree, file, options);
48402    }
48403  }
48404}
48405
48406/**
48407 * Coerce a value to a severity--options tuple.
48408 *
48409 * @param {string} name
48410 * @param {unknown} value
48411 * @returns {SeverityTuple}
48412 */
48413function coerce$C(name, value) {
48414  /** @type {unknown[]} */
48415  let result;
48416
48417  if (typeof value === 'boolean') {
48418    result = [value];
48419  } else if (value === null || value === undefined) {
48420    result = [1];
48421  } else if (
48422    Array.isArray(value) &&
48423    // `isArray(unknown)` is turned into `any[]`:
48424    // type-coverage:ignore-next-line
48425    primitives$B.has(typeof value[0])
48426  ) {
48427    // `isArray(unknown)` is turned into `any[]`:
48428    // type-coverage:ignore-next-line
48429    result = [...value];
48430  } else {
48431    result = [1, value];
48432  }
48433
48434  let level = result[0];
48435
48436  if (typeof level === 'boolean') {
48437    level = level ? 1 : 0;
48438  } else if (typeof level === 'string') {
48439    if (level === 'off') {
48440      level = 0;
48441    } else if (level === 'on' || level === 'warn') {
48442      level = 1;
48443    } else if (level === 'error') {
48444      level = 2;
48445    } else {
48446      level = 1;
48447      result = [level, result];
48448    }
48449  }
48450
48451  if (typeof level !== 'number' || level < 0 || level > 2) {
48452    throw new Error(
48453      'Incorrect severity `' +
48454        level +
48455        '` for `' +
48456        name +
48457        '`, ' +
48458        'expected 0, 1, or 2'
48459    )
48460  }
48461
48462  result[0] = level;
48463
48464  // @ts-expect-error: it’s now a valid tuple.
48465  return result
48466}
48467
48468/**
48469 * @author Titus Wormer
48470 * @copyright 2015 Titus Wormer
48471 * @license MIT
48472 * @module no-literal-urls
48473 * @fileoverview
48474 *   Warn for literal URLs in text.
48475 *   URLs are treated as links in some Markdown vendors, but not in others.
48476 *   To make sure they are always linked, wrap them in `<` (less than) and `>`
48477 *   (greater than).
48478 *
48479 *   ## Fix
48480 *
48481 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
48482 *   never creates literal URLs and always uses `<` (less than) and `>`
48483 *   (greater than).
48484 *
48485 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
48486 *   on how to automatically fix warnings for this rule.
48487 *
48488 * @example
48489 *   {"name": "ok.md"}
48490 *
48491 *   <http://foo.bar/baz>
48492 *
48493 * @example
48494 *   {"name": "not-ok.md", "label": "input", "gfm": true}
48495 *
48496 *   http://foo.bar/baz
48497 *
48498 * @example
48499 *   {"name": "not-ok.md", "label": "output", "gfm": true}
48500 *
48501 *   1:1-1:19: Don’t use literal URLs without angle brackets
48502 */
48503
48504const remarkLintNoLiteralUrls = lintRule$B(
48505  'remark-lint:no-literal-urls',
48506  /** @type {import('unified-lint-rule').Rule<Root, void>} */
48507  (tree, file) => {
48508    visit(tree, 'link', (node) => {
48509      const value = toString(node);
48510
48511      if (
48512        !generated(node) &&
48513        pointStart(node).column === pointStart(node.children[0]).column &&
48514        pointEnd(node).column ===
48515          pointEnd(node.children[node.children.length - 1]).column &&
48516        (node.url === 'mailto:' + value || node.url === value)
48517      ) {
48518        file.message('Don’t use literal URLs without angle brackets', node);
48519      }
48520    });
48521  }
48522);
48523
48524var remarkLintNoLiteralUrls$1 = remarkLintNoLiteralUrls;
48525
48526/**
48527 * @typedef {import('unist').Node} Node
48528 * @typedef {import('vfile').VFile} VFile
48529 *
48530 * @typedef {0|1|2} Severity
48531 * @typedef {'warn'|'on'|'off'|'error'} Label
48532 * @typedef {[Severity, ...unknown[]]} SeverityTuple
48533 *
48534 * @callback Rule
48535 * @param {Node} tree
48536 * @param {VFile} file
48537 * @param {unknown} options
48538 * @returns {void}
48539 */
48540
48541const primitives$A = new Set(['string', 'number', 'boolean']);
48542
48543/**
48544 * @param {string} id
48545 * @param {Rule} rule
48546 */
48547function lintRule$A(id, rule) {
48548  const parts = id.split(':');
48549  // Possibly useful if externalised later.
48550  /* c8 ignore next */
48551  const source = parts[1] ? parts[0] : undefined;
48552  const ruleId = parts[1];
48553
48554  Object.defineProperty(plugin, 'name', {value: id});
48555
48556  return plugin
48557
48558  /** @type {import('unified').Plugin<[unknown]|void[]>} */
48559  function plugin(raw) {
48560    const [severity, options] = coerce$B(ruleId, raw);
48561
48562    if (!severity) return
48563
48564    const fatal = severity === 2;
48565
48566    return (tree, file, next) => {
48567      let index = file.messages.length - 1;
48568
48569      wrap(rule, (error) => {
48570        const messages = file.messages;
48571
48572        // Add the error, if not already properly added.
48573        // Only happens for incorrect plugins.
48574        /* c8 ignore next 6 */
48575        // @ts-expect-error: errors could be `messages`.
48576        if (error && !messages.includes(error)) {
48577          try {
48578            file.fail(error);
48579          } catch {}
48580        }
48581
48582        while (++index < messages.length) {
48583          Object.assign(messages[index], {ruleId, source, fatal});
48584        }
48585
48586        next();
48587      })(tree, file, options);
48588    }
48589  }
48590}
48591
48592/**
48593 * Coerce a value to a severity--options tuple.
48594 *
48595 * @param {string} name
48596 * @param {unknown} value
48597 * @returns {SeverityTuple}
48598 */
48599function coerce$B(name, value) {
48600  /** @type {unknown[]} */
48601  let result;
48602
48603  if (typeof value === 'boolean') {
48604    result = [value];
48605  } else if (value === null || value === undefined) {
48606    result = [1];
48607  } else if (
48608    Array.isArray(value) &&
48609    // `isArray(unknown)` is turned into `any[]`:
48610    // type-coverage:ignore-next-line
48611    primitives$A.has(typeof value[0])
48612  ) {
48613    // `isArray(unknown)` is turned into `any[]`:
48614    // type-coverage:ignore-next-line
48615    result = [...value];
48616  } else {
48617    result = [1, value];
48618  }
48619
48620  let level = result[0];
48621
48622  if (typeof level === 'boolean') {
48623    level = level ? 1 : 0;
48624  } else if (typeof level === 'string') {
48625    if (level === 'off') {
48626      level = 0;
48627    } else if (level === 'on' || level === 'warn') {
48628      level = 1;
48629    } else if (level === 'error') {
48630      level = 2;
48631    } else {
48632      level = 1;
48633      result = [level, result];
48634    }
48635  }
48636
48637  if (typeof level !== 'number' || level < 0 || level > 2) {
48638    throw new Error(
48639      'Incorrect severity `' +
48640        level +
48641        '` for `' +
48642        name +
48643        '`, ' +
48644        'expected 0, 1, or 2'
48645    )
48646  }
48647
48648  result[0] = level;
48649
48650  // @ts-expect-error: it’s now a valid tuple.
48651  return result
48652}
48653
48654/**
48655 * @author Titus Wormer
48656 * @copyright 2015 Titus Wormer
48657 * @license MIT
48658 * @module ordered-list-marker-style
48659 * @fileoverview
48660 *   Warn when the list item marker style of ordered lists violate a given style.
48661 *
48662 *   Options: `'consistent'`, `'.'`, or `')'`, default: `'consistent'`.
48663 *
48664 *   `'consistent'` detects the first used list style and warns when subsequent
48665 *   lists use different styles.
48666 *
48667 * @example
48668 *   {"name": "ok.md"}
48669 *
48670 *   1.  Foo
48671 *
48672 *
48673 *   1.  Bar
48674 *
48675 *   Unordered lists are not affected by this rule.
48676 *
48677 *   * Foo
48678 *
48679 * @example
48680 *   {"name": "ok.md", "setting": "."}
48681 *
48682 *   1.  Foo
48683 *
48684 *   2.  Bar
48685 *
48686 * @example
48687 *   {"name": "ok.md", "setting": ")"}
48688 *
48689 *   1)  Foo
48690 *
48691 *   2)  Bar
48692 *
48693 * @example
48694 *   {"name": "not-ok.md", "label": "input"}
48695 *
48696 *   1.  Foo
48697 *
48698 *   2)  Bar
48699 *
48700 * @example
48701 *   {"name": "not-ok.md", "label": "output"}
48702 *
48703 *   3:1-3:8: Marker style should be `.`
48704 *
48705 * @example
48706 *   {"name": "not-ok.md", "label": "output", "setting": "��", "positionless": true}
48707 *
48708 *   1:1: Incorrect ordered list item marker style `��`: use either `'.'` or `')'`
48709 */
48710
48711const remarkLintOrderedListMarkerStyle = lintRule$A(
48712  'remark-lint:ordered-list-marker-style',
48713  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
48714  (tree, file, option = 'consistent') => {
48715    const value = String(file);
48716
48717    if (option !== 'consistent' && option !== '.' && option !== ')') {
48718      file.fail(
48719        'Incorrect ordered list item marker style `' +
48720          option +
48721          "`: use either `'.'` or `')'`"
48722      );
48723    }
48724
48725    visit(tree, 'list', (node) => {
48726      let index = -1;
48727
48728      if (!node.ordered) return
48729
48730      while (++index < node.children.length) {
48731        const child = node.children[index];
48732
48733        if (!generated(child)) {
48734          const marker = /** @type {Marker} */ (
48735            value
48736              .slice(
48737                pointStart(child).offset,
48738                pointStart(child.children[0]).offset
48739              )
48740              .replace(/\s|\d/g, '')
48741              .replace(/\[[x ]?]\s*$/i, '')
48742          );
48743
48744          if (option === 'consistent') {
48745            option = marker;
48746          } else if (marker !== option) {
48747            file.message('Marker style should be `' + option + '`', child);
48748          }
48749        }
48750      }
48751    });
48752  }
48753);
48754
48755var remarkLintOrderedListMarkerStyle$1 = remarkLintOrderedListMarkerStyle;
48756
48757/**
48758 * @typedef {import('unist').Node} Node
48759 * @typedef {import('vfile').VFile} VFile
48760 *
48761 * @typedef {0|1|2} Severity
48762 * @typedef {'warn'|'on'|'off'|'error'} Label
48763 * @typedef {[Severity, ...unknown[]]} SeverityTuple
48764 *
48765 * @callback Rule
48766 * @param {Node} tree
48767 * @param {VFile} file
48768 * @param {unknown} options
48769 * @returns {void}
48770 */
48771
48772const primitives$z = new Set(['string', 'number', 'boolean']);
48773
48774/**
48775 * @param {string} id
48776 * @param {Rule} rule
48777 */
48778function lintRule$z(id, rule) {
48779  const parts = id.split(':');
48780  // Possibly useful if externalised later.
48781  /* c8 ignore next */
48782  const source = parts[1] ? parts[0] : undefined;
48783  const ruleId = parts[1];
48784
48785  Object.defineProperty(plugin, 'name', {value: id});
48786
48787  return plugin
48788
48789  /** @type {import('unified').Plugin<[unknown]|void[]>} */
48790  function plugin(raw) {
48791    const [severity, options] = coerce$A(ruleId, raw);
48792
48793    if (!severity) return
48794
48795    const fatal = severity === 2;
48796
48797    return (tree, file, next) => {
48798      let index = file.messages.length - 1;
48799
48800      wrap(rule, (error) => {
48801        const messages = file.messages;
48802
48803        // Add the error, if not already properly added.
48804        // Only happens for incorrect plugins.
48805        /* c8 ignore next 6 */
48806        // @ts-expect-error: errors could be `messages`.
48807        if (error && !messages.includes(error)) {
48808          try {
48809            file.fail(error);
48810          } catch {}
48811        }
48812
48813        while (++index < messages.length) {
48814          Object.assign(messages[index], {ruleId, source, fatal});
48815        }
48816
48817        next();
48818      })(tree, file, options);
48819    }
48820  }
48821}
48822
48823/**
48824 * Coerce a value to a severity--options tuple.
48825 *
48826 * @param {string} name
48827 * @param {unknown} value
48828 * @returns {SeverityTuple}
48829 */
48830function coerce$A(name, value) {
48831  /** @type {unknown[]} */
48832  let result;
48833
48834  if (typeof value === 'boolean') {
48835    result = [value];
48836  } else if (value === null || value === undefined) {
48837    result = [1];
48838  } else if (
48839    Array.isArray(value) &&
48840    // `isArray(unknown)` is turned into `any[]`:
48841    // type-coverage:ignore-next-line
48842    primitives$z.has(typeof value[0])
48843  ) {
48844    // `isArray(unknown)` is turned into `any[]`:
48845    // type-coverage:ignore-next-line
48846    result = [...value];
48847  } else {
48848    result = [1, value];
48849  }
48850
48851  let level = result[0];
48852
48853  if (typeof level === 'boolean') {
48854    level = level ? 1 : 0;
48855  } else if (typeof level === 'string') {
48856    if (level === 'off') {
48857      level = 0;
48858    } else if (level === 'on' || level === 'warn') {
48859      level = 1;
48860    } else if (level === 'error') {
48861      level = 2;
48862    } else {
48863      level = 1;
48864      result = [level, result];
48865    }
48866  }
48867
48868  if (typeof level !== 'number' || level < 0 || level > 2) {
48869    throw new Error(
48870      'Incorrect severity `' +
48871        level +
48872        '` for `' +
48873        name +
48874        '`, ' +
48875        'expected 0, 1, or 2'
48876    )
48877  }
48878
48879  result[0] = level;
48880
48881  // @ts-expect-error: it’s now a valid tuple.
48882  return result
48883}
48884
48885/**
48886 * @author Titus Wormer
48887 * @copyright 2015 Titus Wormer
48888 * @license MIT
48889 * @module hard-break-spaces
48890 * @fileoverview
48891 *   Warn when too many spaces are used to create a hard break.
48892 *
48893 * @example
48894 *   {"name": "ok.md"}
48895 *
48896 *   Lorem ipsum··
48897 *   dolor sit amet
48898 *
48899 * @example
48900 *   {"name": "not-ok.md", "label": "input"}
48901 *
48902 *   Lorem ipsum···
48903 *   dolor sit amet.
48904 *
48905 * @example
48906 *   {"name": "not-ok.md", "label": "output"}
48907 *
48908 *   1:12-2:1: Use two spaces for hard line breaks
48909 */
48910
48911const remarkLintHardBreakSpaces = lintRule$z(
48912  'remark-lint:hard-break-spaces',
48913  /** @type {import('unified-lint-rule').Rule<Root, void>} */
48914  (tree, file) => {
48915    const value = String(file);
48916
48917    visit(tree, 'break', (node) => {
48918      if (!generated(node)) {
48919        const slice = value
48920          .slice(pointStart(node).offset, pointEnd(node).offset)
48921          .split('\n', 1)[0]
48922          .replace(/\r$/, '');
48923
48924        if (slice.length > 2) {
48925          file.message('Use two spaces for hard line breaks', node);
48926        }
48927      }
48928    });
48929  }
48930);
48931
48932var remarkLintHardBreakSpaces$1 = remarkLintHardBreakSpaces;
48933
48934/**
48935 * @typedef {import('unist').Node} Node
48936 * @typedef {import('vfile').VFile} VFile
48937 *
48938 * @typedef {0|1|2} Severity
48939 * @typedef {'warn'|'on'|'off'|'error'} Label
48940 * @typedef {[Severity, ...unknown[]]} SeverityTuple
48941 *
48942 * @callback Rule
48943 * @param {Node} tree
48944 * @param {VFile} file
48945 * @param {unknown} options
48946 * @returns {void}
48947 */
48948
48949const primitives$y = new Set(['string', 'number', 'boolean']);
48950
48951/**
48952 * @param {string} id
48953 * @param {Rule} rule
48954 */
48955function lintRule$y(id, rule) {
48956  const parts = id.split(':');
48957  // Possibly useful if externalised later.
48958  /* c8 ignore next */
48959  const source = parts[1] ? parts[0] : undefined;
48960  const ruleId = parts[1];
48961
48962  Object.defineProperty(plugin, 'name', {value: id});
48963
48964  return plugin
48965
48966  /** @type {import('unified').Plugin<[unknown]|void[]>} */
48967  function plugin(raw) {
48968    const [severity, options] = coerce$z(ruleId, raw);
48969
48970    if (!severity) return
48971
48972    const fatal = severity === 2;
48973
48974    return (tree, file, next) => {
48975      let index = file.messages.length - 1;
48976
48977      wrap(rule, (error) => {
48978        const messages = file.messages;
48979
48980        // Add the error, if not already properly added.
48981        // Only happens for incorrect plugins.
48982        /* c8 ignore next 6 */
48983        // @ts-expect-error: errors could be `messages`.
48984        if (error && !messages.includes(error)) {
48985          try {
48986            file.fail(error);
48987          } catch {}
48988        }
48989
48990        while (++index < messages.length) {
48991          Object.assign(messages[index], {ruleId, source, fatal});
48992        }
48993
48994        next();
48995      })(tree, file, options);
48996    }
48997  }
48998}
48999
49000/**
49001 * Coerce a value to a severity--options tuple.
49002 *
49003 * @param {string} name
49004 * @param {unknown} value
49005 * @returns {SeverityTuple}
49006 */
49007function coerce$z(name, value) {
49008  /** @type {unknown[]} */
49009  let result;
49010
49011  if (typeof value === 'boolean') {
49012    result = [value];
49013  } else if (value === null || value === undefined) {
49014    result = [1];
49015  } else if (
49016    Array.isArray(value) &&
49017    // `isArray(unknown)` is turned into `any[]`:
49018    // type-coverage:ignore-next-line
49019    primitives$y.has(typeof value[0])
49020  ) {
49021    // `isArray(unknown)` is turned into `any[]`:
49022    // type-coverage:ignore-next-line
49023    result = [...value];
49024  } else {
49025    result = [1, value];
49026  }
49027
49028  let level = result[0];
49029
49030  if (typeof level === 'boolean') {
49031    level = level ? 1 : 0;
49032  } else if (typeof level === 'string') {
49033    if (level === 'off') {
49034      level = 0;
49035    } else if (level === 'on' || level === 'warn') {
49036      level = 1;
49037    } else if (level === 'error') {
49038      level = 2;
49039    } else {
49040      level = 1;
49041      result = [level, result];
49042    }
49043  }
49044
49045  if (typeof level !== 'number' || level < 0 || level > 2) {
49046    throw new Error(
49047      'Incorrect severity `' +
49048        level +
49049        '` for `' +
49050        name +
49051        '`, ' +
49052        'expected 0, 1, or 2'
49053    )
49054  }
49055
49056  result[0] = level;
49057
49058  // @ts-expect-error: it’s now a valid tuple.
49059  return result
49060}
49061
49062/**
49063 * @author Titus Wormer
49064 * @copyright 2015 Titus Wormer
49065 * @license MIT
49066 * @module no-duplicate-definitions
49067 * @fileoverview
49068 *   Warn when duplicate definitions are found.
49069 *
49070 * @example
49071 *   {"name": "ok.md"}
49072 *
49073 *   [foo]: bar
49074 *   [baz]: qux
49075 *
49076 * @example
49077 *   {"name": "not-ok.md", "label": "input"}
49078 *
49079 *   [foo]: bar
49080 *   [foo]: qux
49081 *
49082 * @example
49083 *   {"name": "not-ok.md", "label": "output"}
49084 *
49085 *   2:1-2:11: Do not use definitions with the same identifier (1:1)
49086 */
49087
49088const remarkLintNoDuplicateDefinitions = lintRule$y(
49089  'remark-lint:no-duplicate-definitions',
49090  /** @type {import('unified-lint-rule').Rule<Root, void>} */
49091  (tree, file) => {
49092    /** @type {Record<string, string>} */
49093    const map = Object.create(null);
49094
49095    visit(tree, (node) => {
49096      if (
49097        (node.type === 'definition' || node.type === 'footnoteDefinition') &&
49098        !generated(node)
49099      ) {
49100        const identifier = node.identifier;
49101        const duplicate = map[identifier];
49102
49103        if (duplicate) {
49104          file.message(
49105            'Do not use definitions with the same identifier (' +
49106              duplicate +
49107              ')',
49108            node
49109          );
49110        }
49111
49112        map[identifier] = stringifyPosition$1(pointStart(node));
49113      }
49114    });
49115  }
49116);
49117
49118var remarkLintNoDuplicateDefinitions$1 = remarkLintNoDuplicateDefinitions;
49119
49120/**
49121 * @typedef {import('unist').Node} Node
49122 * @typedef {import('vfile').VFile} VFile
49123 *
49124 * @typedef {0|1|2} Severity
49125 * @typedef {'warn'|'on'|'off'|'error'} Label
49126 * @typedef {[Severity, ...unknown[]]} SeverityTuple
49127 *
49128 * @callback Rule
49129 * @param {Node} tree
49130 * @param {VFile} file
49131 * @param {unknown} options
49132 * @returns {void}
49133 */
49134
49135const primitives$x = new Set(['string', 'number', 'boolean']);
49136
49137/**
49138 * @param {string} id
49139 * @param {Rule} rule
49140 */
49141function lintRule$x(id, rule) {
49142  const parts = id.split(':');
49143  // Possibly useful if externalised later.
49144  /* c8 ignore next */
49145  const source = parts[1] ? parts[0] : undefined;
49146  const ruleId = parts[1];
49147
49148  Object.defineProperty(plugin, 'name', {value: id});
49149
49150  return plugin
49151
49152  /** @type {import('unified').Plugin<[unknown]|void[]>} */
49153  function plugin(raw) {
49154    const [severity, options] = coerce$y(ruleId, raw);
49155
49156    if (!severity) return
49157
49158    const fatal = severity === 2;
49159
49160    return (tree, file, next) => {
49161      let index = file.messages.length - 1;
49162
49163      wrap(rule, (error) => {
49164        const messages = file.messages;
49165
49166        // Add the error, if not already properly added.
49167        // Only happens for incorrect plugins.
49168        /* c8 ignore next 6 */
49169        // @ts-expect-error: errors could be `messages`.
49170        if (error && !messages.includes(error)) {
49171          try {
49172            file.fail(error);
49173          } catch {}
49174        }
49175
49176        while (++index < messages.length) {
49177          Object.assign(messages[index], {ruleId, source, fatal});
49178        }
49179
49180        next();
49181      })(tree, file, options);
49182    }
49183  }
49184}
49185
49186/**
49187 * Coerce a value to a severity--options tuple.
49188 *
49189 * @param {string} name
49190 * @param {unknown} value
49191 * @returns {SeverityTuple}
49192 */
49193function coerce$y(name, value) {
49194  /** @type {unknown[]} */
49195  let result;
49196
49197  if (typeof value === 'boolean') {
49198    result = [value];
49199  } else if (value === null || value === undefined) {
49200    result = [1];
49201  } else if (
49202    Array.isArray(value) &&
49203    // `isArray(unknown)` is turned into `any[]`:
49204    // type-coverage:ignore-next-line
49205    primitives$x.has(typeof value[0])
49206  ) {
49207    // `isArray(unknown)` is turned into `any[]`:
49208    // type-coverage:ignore-next-line
49209    result = [...value];
49210  } else {
49211    result = [1, value];
49212  }
49213
49214  let level = result[0];
49215
49216  if (typeof level === 'boolean') {
49217    level = level ? 1 : 0;
49218  } else if (typeof level === 'string') {
49219    if (level === 'off') {
49220      level = 0;
49221    } else if (level === 'on' || level === 'warn') {
49222      level = 1;
49223    } else if (level === 'error') {
49224      level = 2;
49225    } else {
49226      level = 1;
49227      result = [level, result];
49228    }
49229  }
49230
49231  if (typeof level !== 'number' || level < 0 || level > 2) {
49232    throw new Error(
49233      'Incorrect severity `' +
49234        level +
49235        '` for `' +
49236        name +
49237        '`, ' +
49238        'expected 0, 1, or 2'
49239    )
49240  }
49241
49242  result[0] = level;
49243
49244  // @ts-expect-error: it’s now a valid tuple.
49245  return result
49246}
49247
49248/**
49249 * @typedef {import('mdast').Heading} Heading
49250 * @typedef {'atx'|'atx-closed'|'setext'} Style
49251 */
49252
49253/**
49254 * @param {Heading} node
49255 * @param {Style} [relative]
49256 * @returns {Style|null}
49257 */
49258function headingStyle(node, relative) {
49259  var last = node.children[node.children.length - 1];
49260  var depth = node.depth;
49261  var pos = node && node.position && node.position.end;
49262  var final = last && last.position && last.position.end;
49263
49264  if (!pos) {
49265    return null
49266  }
49267
49268  // This can only occur for `'atx'` and `'atx-closed'` headings.
49269  // This might incorrectly match `'atx'` headings with lots of trailing white
49270  // space as an `'atx-closed'` heading.
49271  if (!last) {
49272    if (pos.column - 1 <= depth * 2) {
49273      return consolidate(depth, relative)
49274    }
49275
49276    return 'atx-closed'
49277  }
49278
49279  if (final.line + 1 === pos.line) {
49280    return 'setext'
49281  }
49282
49283  if (final.column + depth < pos.column) {
49284    return 'atx-closed'
49285  }
49286
49287  return consolidate(depth, relative)
49288}
49289
49290/**
49291 * Get the probable style of an atx-heading, depending on preferred style.
49292 *
49293 * @param {number} depth
49294 * @param {Style} relative
49295 * @returns {Style|null}
49296 */
49297function consolidate(depth, relative) {
49298  return depth < 3
49299    ? 'atx'
49300    : relative === 'atx' || relative === 'setext'
49301    ? relative
49302    : null
49303}
49304
49305/**
49306 * @author Titus Wormer
49307 * @copyright 2015 Titus Wormer
49308 * @license MIT
49309 * @module no-heading-content-indent
49310 * @fileoverview
49311 *   Warn when content of headings is indented.
49312 *
49313 *   ## Fix
49314 *
49315 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
49316 *   removes all unneeded padding around content in headings.
49317 *
49318 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
49319 *   on how to automatically fix warnings for this rule.
49320 *
49321 * @example
49322 *   {"name": "ok.md"}
49323 *
49324 *   #·Foo
49325 *
49326 *   ## Bar·##
49327 *
49328 *     ##·Baz
49329 *
49330 *   Setext headings are not affected.
49331 *
49332 *   Baz
49333 *   ===
49334 *
49335 * @example
49336 *   {"name": "not-ok.md", "label": "input"}
49337 *
49338 *   #··Foo
49339 *
49340 *   ## Bar··##
49341 *
49342 *     ##··Baz
49343 *
49344 * @example
49345 *   {"name": "not-ok.md", "label": "output"}
49346 *
49347 *   1:4: Remove 1 space before this heading’s content
49348 *   3:7: Remove 1 space after this heading’s content
49349 *   5:7: Remove 1 space before this heading’s content
49350 *
49351 * @example
49352 *   {"name": "empty-heading.md"}
49353 *
49354 *   #··
49355 */
49356
49357const remarkLintNoHeadingContentIndent = lintRule$x(
49358  'remark-lint:no-heading-content-indent',
49359  /** @type {import('unified-lint-rule').Rule<Root, void>} */
49360  (tree, file) => {
49361    visit(tree, 'heading', (node) => {
49362      if (generated(node)) {
49363        return
49364      }
49365
49366      const type = headingStyle(node, 'atx');
49367
49368      if (type === 'atx' || type === 'atx-closed') {
49369        const head = pointStart(node.children[0]).column;
49370
49371        // Ignore empty headings.
49372        if (!head) {
49373          return
49374        }
49375
49376        const diff = head - pointStart(node).column - 1 - node.depth;
49377
49378        if (diff) {
49379          file.message(
49380            'Remove ' +
49381              Math.abs(diff) +
49382              ' ' +
49383              plural('space', Math.abs(diff)) +
49384              ' before this heading’s content',
49385            pointStart(node.children[0])
49386          );
49387        }
49388      }
49389
49390      // Closed ATX headings always must have a space between their content and
49391      // the final hashes, thus, there is no `add x spaces`.
49392      if (type === 'atx-closed') {
49393        const final = pointEnd(node.children[node.children.length - 1]);
49394        const diff = pointEnd(node).column - final.column - 1 - node.depth;
49395
49396        if (diff) {
49397          file.message(
49398            'Remove ' +
49399              diff +
49400              ' ' +
49401              plural('space', diff) +
49402              ' after this heading’s content',
49403            final
49404          );
49405        }
49406      }
49407    });
49408  }
49409);
49410
49411var remarkLintNoHeadingContentIndent$1 = remarkLintNoHeadingContentIndent;
49412
49413/**
49414 * @typedef {import('unist').Node} Node
49415 * @typedef {import('vfile').VFile} VFile
49416 *
49417 * @typedef {0|1|2} Severity
49418 * @typedef {'warn'|'on'|'off'|'error'} Label
49419 * @typedef {[Severity, ...unknown[]]} SeverityTuple
49420 *
49421 * @callback Rule
49422 * @param {Node} tree
49423 * @param {VFile} file
49424 * @param {unknown} options
49425 * @returns {void}
49426 */
49427
49428const primitives$w = new Set(['string', 'number', 'boolean']);
49429
49430/**
49431 * @param {string} id
49432 * @param {Rule} rule
49433 */
49434function lintRule$w(id, rule) {
49435  const parts = id.split(':');
49436  // Possibly useful if externalised later.
49437  /* c8 ignore next */
49438  const source = parts[1] ? parts[0] : undefined;
49439  const ruleId = parts[1];
49440
49441  Object.defineProperty(plugin, 'name', {value: id});
49442
49443  return plugin
49444
49445  /** @type {import('unified').Plugin<[unknown]|void[]>} */
49446  function plugin(raw) {
49447    const [severity, options] = coerce$x(ruleId, raw);
49448
49449    if (!severity) return
49450
49451    const fatal = severity === 2;
49452
49453    return (tree, file, next) => {
49454      let index = file.messages.length - 1;
49455
49456      wrap(rule, (error) => {
49457        const messages = file.messages;
49458
49459        // Add the error, if not already properly added.
49460        // Only happens for incorrect plugins.
49461        /* c8 ignore next 6 */
49462        // @ts-expect-error: errors could be `messages`.
49463        if (error && !messages.includes(error)) {
49464          try {
49465            file.fail(error);
49466          } catch {}
49467        }
49468
49469        while (++index < messages.length) {
49470          Object.assign(messages[index], {ruleId, source, fatal});
49471        }
49472
49473        next();
49474      })(tree, file, options);
49475    }
49476  }
49477}
49478
49479/**
49480 * Coerce a value to a severity--options tuple.
49481 *
49482 * @param {string} name
49483 * @param {unknown} value
49484 * @returns {SeverityTuple}
49485 */
49486function coerce$x(name, value) {
49487  /** @type {unknown[]} */
49488  let result;
49489
49490  if (typeof value === 'boolean') {
49491    result = [value];
49492  } else if (value === null || value === undefined) {
49493    result = [1];
49494  } else if (
49495    Array.isArray(value) &&
49496    // `isArray(unknown)` is turned into `any[]`:
49497    // type-coverage:ignore-next-line
49498    primitives$w.has(typeof value[0])
49499  ) {
49500    // `isArray(unknown)` is turned into `any[]`:
49501    // type-coverage:ignore-next-line
49502    result = [...value];
49503  } else {
49504    result = [1, value];
49505  }
49506
49507  let level = result[0];
49508
49509  if (typeof level === 'boolean') {
49510    level = level ? 1 : 0;
49511  } else if (typeof level === 'string') {
49512    if (level === 'off') {
49513      level = 0;
49514    } else if (level === 'on' || level === 'warn') {
49515      level = 1;
49516    } else if (level === 'error') {
49517      level = 2;
49518    } else {
49519      level = 1;
49520      result = [level, result];
49521    }
49522  }
49523
49524  if (typeof level !== 'number' || level < 0 || level > 2) {
49525    throw new Error(
49526      'Incorrect severity `' +
49527        level +
49528        '` for `' +
49529        name +
49530        '`, ' +
49531        'expected 0, 1, or 2'
49532    )
49533  }
49534
49535  result[0] = level;
49536
49537  // @ts-expect-error: it’s now a valid tuple.
49538  return result
49539}
49540
49541/**
49542 * @author Titus Wormer
49543 * @copyright 2015 Titus Wormer
49544 * @license MIT
49545 * @module no-inline-padding
49546 * @fileoverview
49547 *   Warn when phrasing content is padded with spaces between their markers and
49548 *   content.
49549 *
49550 *   Warns for emphasis, strong, delete, image, and link.
49551 *
49552 * @example
49553 *   {"name": "ok.md"}
49554 *
49555 *   Alpha [bravo](http://echo.fox/trot)
49556 *
49557 * @example
49558 *   {"name": "not-ok.md", "label": "input"}
49559 *
49560 *   Alpha [ bravo ](http://echo.fox/trot)
49561 *
49562 * @example
49563 *   {"name": "not-ok.md", "label": "output"}
49564 *
49565 *   1:7-1:38: Don’t pad `link` with inner spaces
49566 */
49567
49568const remarkLintNoInlinePadding = lintRule$w(
49569  'remark-lint:no-inline-padding',
49570  /** @type {import('unified-lint-rule').Rule<Root, void>} */
49571  (tree, file) => {
49572    // Note: `emphasis`, `strong`, `delete` (GFM) can’t have padding anymore
49573    // since CM.
49574    visit(tree, (node) => {
49575      if (
49576        (node.type === 'link' || node.type === 'linkReference') &&
49577        !generated(node)
49578      ) {
49579        const value = toString(node);
49580
49581        if (value.charAt(0) === ' ' || value.charAt(value.length - 1) === ' ') {
49582          file.message('Don’t pad `' + node.type + '` with inner spaces', node);
49583        }
49584      }
49585    });
49586  }
49587);
49588
49589var remarkLintNoInlinePadding$1 = remarkLintNoInlinePadding;
49590
49591/**
49592 * @typedef {import('unist').Node} Node
49593 * @typedef {import('vfile').VFile} VFile
49594 *
49595 * @typedef {0|1|2} Severity
49596 * @typedef {'warn'|'on'|'off'|'error'} Label
49597 * @typedef {[Severity, ...unknown[]]} SeverityTuple
49598 *
49599 * @callback Rule
49600 * @param {Node} tree
49601 * @param {VFile} file
49602 * @param {unknown} options
49603 * @returns {void}
49604 */
49605
49606const primitives$v = new Set(['string', 'number', 'boolean']);
49607
49608/**
49609 * @param {string} id
49610 * @param {Rule} rule
49611 */
49612function lintRule$v(id, rule) {
49613  const parts = id.split(':');
49614  // Possibly useful if externalised later.
49615  /* c8 ignore next */
49616  const source = parts[1] ? parts[0] : undefined;
49617  const ruleId = parts[1];
49618
49619  Object.defineProperty(plugin, 'name', {value: id});
49620
49621  return plugin
49622
49623  /** @type {import('unified').Plugin<[unknown]|void[]>} */
49624  function plugin(raw) {
49625    const [severity, options] = coerce$w(ruleId, raw);
49626
49627    if (!severity) return
49628
49629    const fatal = severity === 2;
49630
49631    return (tree, file, next) => {
49632      let index = file.messages.length - 1;
49633
49634      wrap(rule, (error) => {
49635        const messages = file.messages;
49636
49637        // Add the error, if not already properly added.
49638        // Only happens for incorrect plugins.
49639        /* c8 ignore next 6 */
49640        // @ts-expect-error: errors could be `messages`.
49641        if (error && !messages.includes(error)) {
49642          try {
49643            file.fail(error);
49644          } catch {}
49645        }
49646
49647        while (++index < messages.length) {
49648          Object.assign(messages[index], {ruleId, source, fatal});
49649        }
49650
49651        next();
49652      })(tree, file, options);
49653    }
49654  }
49655}
49656
49657/**
49658 * Coerce a value to a severity--options tuple.
49659 *
49660 * @param {string} name
49661 * @param {unknown} value
49662 * @returns {SeverityTuple}
49663 */
49664function coerce$w(name, value) {
49665  /** @type {unknown[]} */
49666  let result;
49667
49668  if (typeof value === 'boolean') {
49669    result = [value];
49670  } else if (value === null || value === undefined) {
49671    result = [1];
49672  } else if (
49673    Array.isArray(value) &&
49674    // `isArray(unknown)` is turned into `any[]`:
49675    // type-coverage:ignore-next-line
49676    primitives$v.has(typeof value[0])
49677  ) {
49678    // `isArray(unknown)` is turned into `any[]`:
49679    // type-coverage:ignore-next-line
49680    result = [...value];
49681  } else {
49682    result = [1, value];
49683  }
49684
49685  let level = result[0];
49686
49687  if (typeof level === 'boolean') {
49688    level = level ? 1 : 0;
49689  } else if (typeof level === 'string') {
49690    if (level === 'off') {
49691      level = 0;
49692    } else if (level === 'on' || level === 'warn') {
49693      level = 1;
49694    } else if (level === 'error') {
49695      level = 2;
49696    } else {
49697      level = 1;
49698      result = [level, result];
49699    }
49700  }
49701
49702  if (typeof level !== 'number' || level < 0 || level > 2) {
49703    throw new Error(
49704      'Incorrect severity `' +
49705        level +
49706        '` for `' +
49707        name +
49708        '`, ' +
49709        'expected 0, 1, or 2'
49710    )
49711  }
49712
49713  result[0] = level;
49714
49715  // @ts-expect-error: it’s now a valid tuple.
49716  return result
49717}
49718
49719/**
49720 * @author Titus Wormer
49721 * @copyright 2015 Titus Wormer
49722 * @license MIT
49723 * @module no-shortcut-reference-image
49724 * @fileoverview
49725 *   Warn when shortcut reference images are used.
49726 *
49727 *   Shortcut references render as images when a definition is found, and as
49728 *   plain text without definition.
49729 *   Sometimes, you don’t intend to create an image from the reference, but this
49730 *   rule still warns anyway.
49731 *   In that case, you can escape the reference like so: `!\[foo]`.
49732 *
49733 * @example
49734 *   {"name": "ok.md"}
49735 *
49736 *   ![foo][]
49737 *
49738 *   [foo]: http://foo.bar/baz.png
49739 *
49740 * @example
49741 *   {"name": "not-ok.md", "label": "input"}
49742 *
49743 *   ![foo]
49744 *
49745 *   [foo]: http://foo.bar/baz.png
49746 *
49747 * @example
49748 *   {"name": "not-ok.md", "label": "output"}
49749 *
49750 *   1:1-1:7: Use the trailing [] on reference images
49751 */
49752
49753const remarkLintNoShortcutReferenceImage = lintRule$v(
49754  'remark-lint:no-shortcut-reference-image',
49755  /** @type {import('unified-lint-rule').Rule<Root, void>} */
49756  (tree, file) => {
49757    visit(tree, 'imageReference', (node) => {
49758      if (!generated(node) && node.referenceType === 'shortcut') {
49759        file.message('Use the trailing [] on reference images', node);
49760      }
49761    });
49762  }
49763);
49764
49765var remarkLintNoShortcutReferenceImage$1 = remarkLintNoShortcutReferenceImage;
49766
49767/**
49768 * @typedef {import('unist').Node} Node
49769 * @typedef {import('vfile').VFile} VFile
49770 *
49771 * @typedef {0|1|2} Severity
49772 * @typedef {'warn'|'on'|'off'|'error'} Label
49773 * @typedef {[Severity, ...unknown[]]} SeverityTuple
49774 *
49775 * @callback Rule
49776 * @param {Node} tree
49777 * @param {VFile} file
49778 * @param {unknown} options
49779 * @returns {void}
49780 */
49781
49782const primitives$u = new Set(['string', 'number', 'boolean']);
49783
49784/**
49785 * @param {string} id
49786 * @param {Rule} rule
49787 */
49788function lintRule$u(id, rule) {
49789  const parts = id.split(':');
49790  // Possibly useful if externalised later.
49791  /* c8 ignore next */
49792  const source = parts[1] ? parts[0] : undefined;
49793  const ruleId = parts[1];
49794
49795  Object.defineProperty(plugin, 'name', {value: id});
49796
49797  return plugin
49798
49799  /** @type {import('unified').Plugin<[unknown]|void[]>} */
49800  function plugin(raw) {
49801    const [severity, options] = coerce$v(ruleId, raw);
49802
49803    if (!severity) return
49804
49805    const fatal = severity === 2;
49806
49807    return (tree, file, next) => {
49808      let index = file.messages.length - 1;
49809
49810      wrap(rule, (error) => {
49811        const messages = file.messages;
49812
49813        // Add the error, if not already properly added.
49814        // Only happens for incorrect plugins.
49815        /* c8 ignore next 6 */
49816        // @ts-expect-error: errors could be `messages`.
49817        if (error && !messages.includes(error)) {
49818          try {
49819            file.fail(error);
49820          } catch {}
49821        }
49822
49823        while (++index < messages.length) {
49824          Object.assign(messages[index], {ruleId, source, fatal});
49825        }
49826
49827        next();
49828      })(tree, file, options);
49829    }
49830  }
49831}
49832
49833/**
49834 * Coerce a value to a severity--options tuple.
49835 *
49836 * @param {string} name
49837 * @param {unknown} value
49838 * @returns {SeverityTuple}
49839 */
49840function coerce$v(name, value) {
49841  /** @type {unknown[]} */
49842  let result;
49843
49844  if (typeof value === 'boolean') {
49845    result = [value];
49846  } else if (value === null || value === undefined) {
49847    result = [1];
49848  } else if (
49849    Array.isArray(value) &&
49850    // `isArray(unknown)` is turned into `any[]`:
49851    // type-coverage:ignore-next-line
49852    primitives$u.has(typeof value[0])
49853  ) {
49854    // `isArray(unknown)` is turned into `any[]`:
49855    // type-coverage:ignore-next-line
49856    result = [...value];
49857  } else {
49858    result = [1, value];
49859  }
49860
49861  let level = result[0];
49862
49863  if (typeof level === 'boolean') {
49864    level = level ? 1 : 0;
49865  } else if (typeof level === 'string') {
49866    if (level === 'off') {
49867      level = 0;
49868    } else if (level === 'on' || level === 'warn') {
49869      level = 1;
49870    } else if (level === 'error') {
49871      level = 2;
49872    } else {
49873      level = 1;
49874      result = [level, result];
49875    }
49876  }
49877
49878  if (typeof level !== 'number' || level < 0 || level > 2) {
49879    throw new Error(
49880      'Incorrect severity `' +
49881        level +
49882        '` for `' +
49883        name +
49884        '`, ' +
49885        'expected 0, 1, or 2'
49886    )
49887  }
49888
49889  result[0] = level;
49890
49891  // @ts-expect-error: it’s now a valid tuple.
49892  return result
49893}
49894
49895/**
49896 * @author Titus Wormer
49897 * @copyright 2015 Titus Wormer
49898 * @license MIT
49899 * @module no-shortcut-reference-link
49900 * @fileoverview
49901 *   Warn when shortcut reference links are used.
49902 *
49903 *   Shortcut references render as links when a definition is found, and as
49904 *   plain text without definition.
49905 *   Sometimes, you don’t intend to create a link from the reference, but this
49906 *   rule still warns anyway.
49907 *   In that case, you can escape the reference like so: `\[foo]`.
49908 *
49909 * @example
49910 *   {"name": "ok.md"}
49911 *
49912 *   [foo][]
49913 *
49914 *   [foo]: http://foo.bar/baz
49915 *
49916 * @example
49917 *   {"name": "not-ok.md", "label": "input"}
49918 *
49919 *   [foo]
49920 *
49921 *   [foo]: http://foo.bar/baz
49922 *
49923 * @example
49924 *   {"name": "not-ok.md", "label": "output"}
49925 *
49926 *   1:1-1:6: Use the trailing `[]` on reference links
49927 */
49928
49929const remarkLintNoShortcutReferenceLink = lintRule$u(
49930  'remark-lint:no-shortcut-reference-link',
49931  /** @type {import('unified-lint-rule').Rule<Root, void>} */
49932  (tree, file) => {
49933    visit(tree, 'linkReference', (node) => {
49934      if (!generated(node) && node.referenceType === 'shortcut') {
49935        file.message('Use the trailing `[]` on reference links', node);
49936      }
49937    });
49938  }
49939);
49940
49941var remarkLintNoShortcutReferenceLink$1 = remarkLintNoShortcutReferenceLink;
49942
49943/**
49944 * @typedef {import('unist').Node} Node
49945 * @typedef {import('vfile').VFile} VFile
49946 *
49947 * @typedef {0|1|2} Severity
49948 * @typedef {'warn'|'on'|'off'|'error'} Label
49949 * @typedef {[Severity, ...unknown[]]} SeverityTuple
49950 *
49951 * @callback Rule
49952 * @param {Node} tree
49953 * @param {VFile} file
49954 * @param {unknown} options
49955 * @returns {void}
49956 */
49957
49958const primitives$t = new Set(['string', 'number', 'boolean']);
49959
49960/**
49961 * @param {string} id
49962 * @param {Rule} rule
49963 */
49964function lintRule$t(id, rule) {
49965  const parts = id.split(':');
49966  // Possibly useful if externalised later.
49967  /* c8 ignore next */
49968  const source = parts[1] ? parts[0] : undefined;
49969  const ruleId = parts[1];
49970
49971  Object.defineProperty(plugin, 'name', {value: id});
49972
49973  return plugin
49974
49975  /** @type {import('unified').Plugin<[unknown]|void[]>} */
49976  function plugin(raw) {
49977    const [severity, options] = coerce$u(ruleId, raw);
49978
49979    if (!severity) return
49980
49981    const fatal = severity === 2;
49982
49983    return (tree, file, next) => {
49984      let index = file.messages.length - 1;
49985
49986      wrap(rule, (error) => {
49987        const messages = file.messages;
49988
49989        // Add the error, if not already properly added.
49990        // Only happens for incorrect plugins.
49991        /* c8 ignore next 6 */
49992        // @ts-expect-error: errors could be `messages`.
49993        if (error && !messages.includes(error)) {
49994          try {
49995            file.fail(error);
49996          } catch {}
49997        }
49998
49999        while (++index < messages.length) {
50000          Object.assign(messages[index], {ruleId, source, fatal});
50001        }
50002
50003        next();
50004      })(tree, file, options);
50005    }
50006  }
50007}
50008
50009/**
50010 * Coerce a value to a severity--options tuple.
50011 *
50012 * @param {string} name
50013 * @param {unknown} value
50014 * @returns {SeverityTuple}
50015 */
50016function coerce$u(name, value) {
50017  /** @type {unknown[]} */
50018  let result;
50019
50020  if (typeof value === 'boolean') {
50021    result = [value];
50022  } else if (value === null || value === undefined) {
50023    result = [1];
50024  } else if (
50025    Array.isArray(value) &&
50026    // `isArray(unknown)` is turned into `any[]`:
50027    // type-coverage:ignore-next-line
50028    primitives$t.has(typeof value[0])
50029  ) {
50030    // `isArray(unknown)` is turned into `any[]`:
50031    // type-coverage:ignore-next-line
50032    result = [...value];
50033  } else {
50034    result = [1, value];
50035  }
50036
50037  let level = result[0];
50038
50039  if (typeof level === 'boolean') {
50040    level = level ? 1 : 0;
50041  } else if (typeof level === 'string') {
50042    if (level === 'off') {
50043      level = 0;
50044    } else if (level === 'on' || level === 'warn') {
50045      level = 1;
50046    } else if (level === 'error') {
50047      level = 2;
50048    } else {
50049      level = 1;
50050      result = [level, result];
50051    }
50052  }
50053
50054  if (typeof level !== 'number' || level < 0 || level > 2) {
50055    throw new Error(
50056      'Incorrect severity `' +
50057        level +
50058        '` for `' +
50059        name +
50060        '`, ' +
50061        'expected 0, 1, or 2'
50062    )
50063  }
50064
50065  result[0] = level;
50066
50067  // @ts-expect-error: it’s now a valid tuple.
50068  return result
50069}
50070
50071/**
50072 * @author Titus Wormer
50073 * @copyright 2016 Titus Wormer
50074 * @license MIT
50075 * @module no-undefined-references
50076 * @fileoverview
50077 *   Warn when references to undefined definitions are found.
50078 *
50079 *   Options: `Object`, optional.
50080 *
50081 *   The object can have an `allow` field, set to an array of strings that may
50082 *   appear between `[` and `]`, but that should not be treated as link
50083 *   identifiers.
50084 *
50085 * @example
50086 *   {"name": "ok.md"}
50087 *
50088 *   [foo][]
50089 *
50090 *   Just a [ bracket.
50091 *
50092 *   Typically, you’d want to use escapes (with a backslash: \\) to escape what
50093 *   could turn into a \[reference otherwise].
50094 *
50095 *   Just two braces can’t link: [].
50096 *
50097 *   [foo]: https://example.com
50098 *
50099 * @example
50100 *   {"name": "ok-allow.md", "setting": {"allow": ["...", "…"]}}
50101 *
50102 *   > Eliding a portion of a quoted passage […] is acceptable.
50103 *
50104 * @example
50105 *   {"name": "not-ok.md", "label": "input"}
50106 *
50107 *   [bar]
50108 *
50109 *   [baz][]
50110 *
50111 *   [text][qux]
50112 *
50113 *   Spread [over
50114 *   lines][]
50115 *
50116 *   > in [a
50117 *   > block quote][]
50118 *
50119 *   [asd][a
50120 *
50121 *   Can include [*emphasis*].
50122 *
50123 *   Multiple pairs: [a][b][c].
50124 *
50125 * @example
50126 *   {"name": "not-ok.md", "label": "output"}
50127 *
50128 *   1:1-1:6: Found reference to undefined definition
50129 *   3:1-3:8: Found reference to undefined definition
50130 *   5:1-5:12: Found reference to undefined definition
50131 *   7:8-8:9: Found reference to undefined definition
50132 *   10:6-11:17: Found reference to undefined definition
50133 *   13:1-13:6: Found reference to undefined definition
50134 *   15:13-15:25: Found reference to undefined definition
50135 *   17:17-17:23: Found reference to undefined definition
50136 *   17:23-17:26: Found reference to undefined definition
50137 */
50138
50139const remarkLintNoUndefinedReferences = lintRule$t(
50140  'remark-lint:no-undefined-references',
50141  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
50142  (tree, file, option = {}) => {
50143    const contents = String(file);
50144    const loc = location(file);
50145    const lineEnding = /(\r?\n|\r)[\t ]*(>[\t ]*)*/g;
50146    const allow = new Set(
50147      (option.allow || []).map((d) => normalizeIdentifier(d))
50148    );
50149    /** @type {Record<string, boolean>} */
50150    const map = Object.create(null);
50151
50152    visit(tree, (node) => {
50153      if (
50154        (node.type === 'definition' || node.type === 'footnoteDefinition') &&
50155        !generated(node)
50156      ) {
50157        map[normalizeIdentifier(node.identifier)] = true;
50158      }
50159    });
50160
50161    visit(tree, (node) => {
50162      // CM specifiers that references only form when defined.
50163      // Still, they could be added by plugins, so let’s keep it.
50164      /* c8 ignore next 10 */
50165      if (
50166        (node.type === 'imageReference' ||
50167          node.type === 'linkReference' ||
50168          node.type === 'footnoteReference') &&
50169        !generated(node) &&
50170        !(normalizeIdentifier(node.identifier) in map) &&
50171        !allow.has(normalizeIdentifier(node.identifier))
50172      ) {
50173        file.message('Found reference to undefined definition', node);
50174      }
50175
50176      if (node.type === 'paragraph' || node.type === 'heading') {
50177        findInPhrasing(node);
50178      }
50179    });
50180
50181    /**
50182     * @param {Heading|Paragraph} node
50183     */
50184    function findInPhrasing(node) {
50185      /** @type {Range[]} */
50186      let ranges = [];
50187
50188      visit(node, (child) => {
50189        // Ignore the node itself.
50190        if (child === node) return
50191
50192        // Can’t have links in links, so reset ranges.
50193        if (child.type === 'link' || child.type === 'linkReference') {
50194          ranges = [];
50195          return SKIP$1
50196        }
50197
50198        // Enter non-text.
50199        if (child.type !== 'text') return
50200
50201        const start = pointStart(child).offset;
50202        const end = pointEnd(child).offset;
50203
50204        // Bail if there’s no positional info.
50205        if (typeof start !== 'number' || typeof end !== 'number') {
50206          return EXIT$1
50207        }
50208
50209        const source = contents.slice(start, end);
50210        /** @type {Array.<[number, string]>} */
50211        const lines = [[start, '']];
50212        let last = 0;
50213
50214        lineEnding.lastIndex = 0;
50215        let match = lineEnding.exec(source);
50216
50217        while (match) {
50218          const index = match.index;
50219          lines[lines.length - 1][1] = source.slice(last, index);
50220          last = index + match[0].length;
50221          lines.push([start + last, '']);
50222          match = lineEnding.exec(source);
50223        }
50224
50225        lines[lines.length - 1][1] = source.slice(last);
50226        let lineIndex = -1;
50227
50228        while (++lineIndex < lines.length) {
50229          const line = lines[lineIndex][1];
50230          let index = 0;
50231
50232          while (index < line.length) {
50233            const code = line.charCodeAt(index);
50234
50235            // Skip past escaped brackets.
50236            if (code === 92) {
50237              const next = line.charCodeAt(index + 1);
50238              index++;
50239
50240              if (next === 91 || next === 93) {
50241                index++;
50242              }
50243            }
50244            // Opening bracket.
50245            else if (code === 91) {
50246              ranges.push([lines[lineIndex][0] + index]);
50247              index++;
50248            }
50249            // Close bracket.
50250            else if (code === 93) {
50251              // No opening.
50252              if (ranges.length === 0) {
50253                index++;
50254              } else if (line.charCodeAt(index + 1) === 91) {
50255                index++;
50256
50257                // Collapsed or full.
50258                let range = ranges.pop();
50259
50260                // Range should always exist.
50261                // eslint-disable-next-line max-depth
50262                if (range) {
50263                  range.push(lines[lineIndex][0] + index);
50264
50265                  // This is the end of a reference already.
50266                  // eslint-disable-next-line max-depth
50267                  if (range.length === 4) {
50268                    handleRange(range);
50269                    range = [];
50270                  }
50271
50272                  range.push(lines[lineIndex][0] + index);
50273                  ranges.push(range);
50274                  index++;
50275                }
50276              } else {
50277                index++;
50278
50279                // Shortcut or typical end of a reference.
50280                const range = ranges.pop();
50281
50282                // Range should always exist.
50283                // eslint-disable-next-line max-depth
50284                if (range) {
50285                  range.push(lines[lineIndex][0] + index);
50286                  handleRange(range);
50287                }
50288              }
50289            }
50290            // Anything else.
50291            else {
50292              index++;
50293            }
50294          }
50295        }
50296      });
50297
50298      let index = -1;
50299
50300      while (++index < ranges.length) {
50301        handleRange(ranges[index]);
50302      }
50303
50304      return SKIP$1
50305
50306      /**
50307       * @param {Range} range
50308       */
50309      function handleRange(range) {
50310        if (range.length === 1) return
50311        if (range.length === 3) range.length = 2;
50312
50313        // No need to warn for just `[]`.
50314        if (range.length === 2 && range[0] + 2 === range[1]) return
50315
50316        const offset = range.length === 4 && range[2] + 2 !== range[3] ? 2 : 0;
50317        const id = contents
50318          .slice(range[0 + offset] + 1, range[1 + offset] - 1)
50319          .replace(lineEnding, ' ');
50320        const pos = {
50321          start: loc.toPoint(range[0]),
50322          end: loc.toPoint(range[range.length - 1])
50323        };
50324
50325        if (
50326          !generated({position: pos}) &&
50327          !(normalizeIdentifier(id) in map) &&
50328          !allow.has(normalizeIdentifier(id))
50329        ) {
50330          file.message('Found reference to undefined definition', pos);
50331        }
50332      }
50333    }
50334  }
50335);
50336
50337var remarkLintNoUndefinedReferences$1 = remarkLintNoUndefinedReferences;
50338
50339/**
50340 * @typedef {import('unist').Node} Node
50341 * @typedef {import('vfile').VFile} VFile
50342 *
50343 * @typedef {0|1|2} Severity
50344 * @typedef {'warn'|'on'|'off'|'error'} Label
50345 * @typedef {[Severity, ...unknown[]]} SeverityTuple
50346 *
50347 * @callback Rule
50348 * @param {Node} tree
50349 * @param {VFile} file
50350 * @param {unknown} options
50351 * @returns {void}
50352 */
50353
50354const primitives$s = new Set(['string', 'number', 'boolean']);
50355
50356/**
50357 * @param {string} id
50358 * @param {Rule} rule
50359 */
50360function lintRule$s(id, rule) {
50361  const parts = id.split(':');
50362  // Possibly useful if externalised later.
50363  /* c8 ignore next */
50364  const source = parts[1] ? parts[0] : undefined;
50365  const ruleId = parts[1];
50366
50367  Object.defineProperty(plugin, 'name', {value: id});
50368
50369  return plugin
50370
50371  /** @type {import('unified').Plugin<[unknown]|void[]>} */
50372  function plugin(raw) {
50373    const [severity, options] = coerce$t(ruleId, raw);
50374
50375    if (!severity) return
50376
50377    const fatal = severity === 2;
50378
50379    return (tree, file, next) => {
50380      let index = file.messages.length - 1;
50381
50382      wrap(rule, (error) => {
50383        const messages = file.messages;
50384
50385        // Add the error, if not already properly added.
50386        // Only happens for incorrect plugins.
50387        /* c8 ignore next 6 */
50388        // @ts-expect-error: errors could be `messages`.
50389        if (error && !messages.includes(error)) {
50390          try {
50391            file.fail(error);
50392          } catch {}
50393        }
50394
50395        while (++index < messages.length) {
50396          Object.assign(messages[index], {ruleId, source, fatal});
50397        }
50398
50399        next();
50400      })(tree, file, options);
50401    }
50402  }
50403}
50404
50405/**
50406 * Coerce a value to a severity--options tuple.
50407 *
50408 * @param {string} name
50409 * @param {unknown} value
50410 * @returns {SeverityTuple}
50411 */
50412function coerce$t(name, value) {
50413  /** @type {unknown[]} */
50414  let result;
50415
50416  if (typeof value === 'boolean') {
50417    result = [value];
50418  } else if (value === null || value === undefined) {
50419    result = [1];
50420  } else if (
50421    Array.isArray(value) &&
50422    // `isArray(unknown)` is turned into `any[]`:
50423    // type-coverage:ignore-next-line
50424    primitives$s.has(typeof value[0])
50425  ) {
50426    // `isArray(unknown)` is turned into `any[]`:
50427    // type-coverage:ignore-next-line
50428    result = [...value];
50429  } else {
50430    result = [1, value];
50431  }
50432
50433  let level = result[0];
50434
50435  if (typeof level === 'boolean') {
50436    level = level ? 1 : 0;
50437  } else if (typeof level === 'string') {
50438    if (level === 'off') {
50439      level = 0;
50440    } else if (level === 'on' || level === 'warn') {
50441      level = 1;
50442    } else if (level === 'error') {
50443      level = 2;
50444    } else {
50445      level = 1;
50446      result = [level, result];
50447    }
50448  }
50449
50450  if (typeof level !== 'number' || level < 0 || level > 2) {
50451    throw new Error(
50452      'Incorrect severity `' +
50453        level +
50454        '` for `' +
50455        name +
50456        '`, ' +
50457        'expected 0, 1, or 2'
50458    )
50459  }
50460
50461  result[0] = level;
50462
50463  // @ts-expect-error: it’s now a valid tuple.
50464  return result
50465}
50466
50467/**
50468 * @author Titus Wormer
50469 * @copyright 2016 Titus Wormer
50470 * @license MIT
50471 * @module no-unused-definitions
50472 * @fileoverview
50473 *   Warn when unused definitions are found.
50474 *
50475 * @example
50476 *   {"name": "ok.md"}
50477 *
50478 *   [foo][]
50479 *
50480 *   [foo]: https://example.com
50481 *
50482 * @example
50483 *   {"name": "not-ok.md", "label": "input"}
50484 *
50485 *   [bar]: https://example.com
50486 *
50487 * @example
50488 *   {"name": "not-ok.md", "label": "output"}
50489 *
50490 *   1:1-1:27: Found unused definition
50491 */
50492
50493const own$1 = {}.hasOwnProperty;
50494
50495const remarkLintNoUnusedDefinitions = lintRule$s(
50496  'remark-lint:no-unused-definitions',
50497  /** @type {import('unified-lint-rule').Rule<Root, void>} */
50498  (tree, file) => {
50499    /** @type {Record<string, {node: DefinitionContent, used: boolean}>} */
50500    const map = Object.create(null);
50501
50502    visit(tree, (node) => {
50503      if (
50504        (node.type === 'definition' || node.type === 'footnoteDefinition') &&
50505        !generated(node)
50506      ) {
50507        map[node.identifier.toUpperCase()] = {node, used: false};
50508      }
50509    });
50510
50511    visit(tree, (node) => {
50512      if (
50513        node.type === 'imageReference' ||
50514        node.type === 'linkReference' ||
50515        node.type === 'footnoteReference'
50516      ) {
50517        const info = map[node.identifier.toUpperCase()];
50518
50519        if (!generated(node) && info) {
50520          info.used = true;
50521        }
50522      }
50523    });
50524
50525    /** @type {string} */
50526    let identifier;
50527
50528    for (identifier in map) {
50529      if (own$1.call(map, identifier)) {
50530        const entry = map[identifier];
50531
50532        if (!entry.used) {
50533          file.message('Found unused definition', entry.node);
50534        }
50535      }
50536    }
50537  }
50538);
50539
50540var remarkLintNoUnusedDefinitions$1 = remarkLintNoUnusedDefinitions;
50541
50542/**
50543 * @fileoverview
50544 *   remark preset to configure `remark-lint` with settings that prevent
50545 *   mistakes or stuff that fails across vendors.
50546 */
50547
50548const plugins$1 = [
50549  remarkLint,
50550  // Unix compatibility.
50551  remarkLintFinalNewline$1,
50552  // Rendering across vendors differs greatly if using other styles.
50553  remarkLintListItemBulletIndent$1,
50554  [remarkLintListItemIndent$1, 'tab-size'],
50555  // Differs or unsupported across vendors.
50556  remarkLintNoAutoLinkWithoutProtocol$1,
50557  remarkLintNoBlockquoteWithoutMarker$1,
50558  remarkLintNoLiteralUrls$1,
50559  [remarkLintOrderedListMarkerStyle$1, '.'],
50560  // Mistakes.
50561  remarkLintHardBreakSpaces$1,
50562  remarkLintNoDuplicateDefinitions$1,
50563  remarkLintNoHeadingContentIndent$1,
50564  remarkLintNoInlinePadding$1,
50565  remarkLintNoShortcutReferenceImage$1,
50566  remarkLintNoShortcutReferenceLink$1,
50567  remarkLintNoUndefinedReferences$1,
50568  remarkLintNoUnusedDefinitions$1
50569];
50570
50571const remarkPresetLintRecommended = {plugins: plugins$1};
50572
50573var remarkPresetLintRecommended$1 = remarkPresetLintRecommended;
50574
50575/**
50576 * @typedef {import('unist').Node} Node
50577 * @typedef {import('vfile').VFile} VFile
50578 *
50579 * @typedef {0|1|2} Severity
50580 * @typedef {'warn'|'on'|'off'|'error'} Label
50581 * @typedef {[Severity, ...unknown[]]} SeverityTuple
50582 *
50583 * @callback Rule
50584 * @param {Node} tree
50585 * @param {VFile} file
50586 * @param {unknown} options
50587 * @returns {void}
50588 */
50589
50590const primitives$r = new Set(['string', 'number', 'boolean']);
50591
50592/**
50593 * @param {string} id
50594 * @param {Rule} rule
50595 */
50596function lintRule$r(id, rule) {
50597  const parts = id.split(':');
50598  // Possibly useful if externalised later.
50599  /* c8 ignore next */
50600  const source = parts[1] ? parts[0] : undefined;
50601  const ruleId = parts[1];
50602
50603  Object.defineProperty(plugin, 'name', {value: id});
50604
50605  return plugin
50606
50607  /** @type {import('unified').Plugin<[unknown]|void[]>} */
50608  function plugin(raw) {
50609    const [severity, options] = coerce$s(ruleId, raw);
50610
50611    if (!severity) return
50612
50613    const fatal = severity === 2;
50614
50615    return (tree, file, next) => {
50616      let index = file.messages.length - 1;
50617
50618      wrap(rule, (error) => {
50619        const messages = file.messages;
50620
50621        // Add the error, if not already properly added.
50622        // Only happens for incorrect plugins.
50623        /* c8 ignore next 6 */
50624        // @ts-expect-error: errors could be `messages`.
50625        if (error && !messages.includes(error)) {
50626          try {
50627            file.fail(error);
50628          } catch {}
50629        }
50630
50631        while (++index < messages.length) {
50632          Object.assign(messages[index], {ruleId, source, fatal});
50633        }
50634
50635        next();
50636      })(tree, file, options);
50637    }
50638  }
50639}
50640
50641/**
50642 * Coerce a value to a severity--options tuple.
50643 *
50644 * @param {string} name
50645 * @param {unknown} value
50646 * @returns {SeverityTuple}
50647 */
50648function coerce$s(name, value) {
50649  /** @type {unknown[]} */
50650  let result;
50651
50652  if (typeof value === 'boolean') {
50653    result = [value];
50654  } else if (value === null || value === undefined) {
50655    result = [1];
50656  } else if (
50657    Array.isArray(value) &&
50658    // `isArray(unknown)` is turned into `any[]`:
50659    // type-coverage:ignore-next-line
50660    primitives$r.has(typeof value[0])
50661  ) {
50662    // `isArray(unknown)` is turned into `any[]`:
50663    // type-coverage:ignore-next-line
50664    result = [...value];
50665  } else {
50666    result = [1, value];
50667  }
50668
50669  let level = result[0];
50670
50671  if (typeof level === 'boolean') {
50672    level = level ? 1 : 0;
50673  } else if (typeof level === 'string') {
50674    if (level === 'off') {
50675      level = 0;
50676    } else if (level === 'on' || level === 'warn') {
50677      level = 1;
50678    } else if (level === 'error') {
50679      level = 2;
50680    } else {
50681      level = 1;
50682      result = [level, result];
50683    }
50684  }
50685
50686  if (typeof level !== 'number' || level < 0 || level > 2) {
50687    throw new Error(
50688      'Incorrect severity `' +
50689        level +
50690        '` for `' +
50691        name +
50692        '`, ' +
50693        'expected 0, 1, or 2'
50694    )
50695  }
50696
50697  result[0] = level;
50698
50699  // @ts-expect-error: it’s now a valid tuple.
50700  return result
50701}
50702
50703/**
50704 * @author Titus Wormer
50705 * @copyright 2015 Titus Wormer
50706 * @license MIT
50707 * @module blockquote-indentation
50708 * @fileoverview
50709 *   Warn when block quotes are indented too much or too little.
50710 *
50711 *   Options: `number` or `'consistent'`, default: `'consistent'`.
50712 *
50713 *   `'consistent'` detects the first used indentation and will warn when
50714 *   other block quotes use a different indentation.
50715 *
50716 * @example
50717 *   {"name": "ok.md", "setting": 4}
50718 *
50719 *   >   Hello
50720 *
50721 *   Paragraph.
50722 *
50723 *   >   World
50724 * @example
50725 *   {"name": "ok.md", "setting": 2}
50726 *
50727 *   > Hello
50728 *
50729 *   Paragraph.
50730 *
50731 *   > World
50732 *
50733 * @example
50734 *   {"name": "not-ok.md", "label": "input"}
50735 *
50736 *   >  Hello
50737 *
50738 *   Paragraph.
50739 *
50740 *   >   World
50741 *
50742 *   Paragraph.
50743 *
50744 *   > World
50745 *
50746 * @example
50747 *   {"name": "not-ok.md", "label": "output"}
50748 *
50749 *   5:5: Remove 1 space between block quote and content
50750 *   9:3: Add 1 space between block quote and content
50751 */
50752
50753const remarkLintBlockquoteIndentation = lintRule$r(
50754  'remark-lint:blockquote-indentation',
50755  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
50756  (tree, file, option = 'consistent') => {
50757    visit(tree, 'blockquote', (node) => {
50758      if (generated(node) || node.children.length === 0) {
50759        return
50760      }
50761
50762      if (option === 'consistent') {
50763        option = check(node);
50764      } else {
50765        const diff = option - check(node);
50766
50767        if (diff !== 0) {
50768          const abs = Math.abs(diff);
50769
50770          file.message(
50771            (diff > 0 ? 'Add' : 'Remove') +
50772              ' ' +
50773              abs +
50774              ' ' +
50775              plural('space', abs) +
50776              ' between block quote and content',
50777            pointStart(node.children[0])
50778          );
50779        }
50780      }
50781    });
50782  }
50783);
50784
50785var remarkLintBlockquoteIndentation$1 = remarkLintBlockquoteIndentation;
50786
50787/**
50788 * @param {Blockquote} node
50789 * @returns {number}
50790 */
50791function check(node) {
50792  return pointStart(node.children[0]).column - pointStart(node).column
50793}
50794
50795/**
50796 * @typedef {import('unist').Node} Node
50797 * @typedef {import('vfile').VFile} VFile
50798 *
50799 * @typedef {0|1|2} Severity
50800 * @typedef {'warn'|'on'|'off'|'error'} Label
50801 * @typedef {[Severity, ...unknown[]]} SeverityTuple
50802 *
50803 * @callback Rule
50804 * @param {Node} tree
50805 * @param {VFile} file
50806 * @param {unknown} options
50807 * @returns {void}
50808 */
50809
50810const primitives$q = new Set(['string', 'number', 'boolean']);
50811
50812/**
50813 * @param {string} id
50814 * @param {Rule} rule
50815 */
50816function lintRule$q(id, rule) {
50817  const parts = id.split(':');
50818  // Possibly useful if externalised later.
50819  /* c8 ignore next */
50820  const source = parts[1] ? parts[0] : undefined;
50821  const ruleId = parts[1];
50822
50823  Object.defineProperty(plugin, 'name', {value: id});
50824
50825  return plugin
50826
50827  /** @type {import('unified').Plugin<[unknown]|void[]>} */
50828  function plugin(raw) {
50829    const [severity, options] = coerce$r(ruleId, raw);
50830
50831    if (!severity) return
50832
50833    const fatal = severity === 2;
50834
50835    return (tree, file, next) => {
50836      let index = file.messages.length - 1;
50837
50838      wrap(rule, (error) => {
50839        const messages = file.messages;
50840
50841        // Add the error, if not already properly added.
50842        // Only happens for incorrect plugins.
50843        /* c8 ignore next 6 */
50844        // @ts-expect-error: errors could be `messages`.
50845        if (error && !messages.includes(error)) {
50846          try {
50847            file.fail(error);
50848          } catch {}
50849        }
50850
50851        while (++index < messages.length) {
50852          Object.assign(messages[index], {ruleId, source, fatal});
50853        }
50854
50855        next();
50856      })(tree, file, options);
50857    }
50858  }
50859}
50860
50861/**
50862 * Coerce a value to a severity--options tuple.
50863 *
50864 * @param {string} name
50865 * @param {unknown} value
50866 * @returns {SeverityTuple}
50867 */
50868function coerce$r(name, value) {
50869  /** @type {unknown[]} */
50870  let result;
50871
50872  if (typeof value === 'boolean') {
50873    result = [value];
50874  } else if (value === null || value === undefined) {
50875    result = [1];
50876  } else if (
50877    Array.isArray(value) &&
50878    // `isArray(unknown)` is turned into `any[]`:
50879    // type-coverage:ignore-next-line
50880    primitives$q.has(typeof value[0])
50881  ) {
50882    // `isArray(unknown)` is turned into `any[]`:
50883    // type-coverage:ignore-next-line
50884    result = [...value];
50885  } else {
50886    result = [1, value];
50887  }
50888
50889  let level = result[0];
50890
50891  if (typeof level === 'boolean') {
50892    level = level ? 1 : 0;
50893  } else if (typeof level === 'string') {
50894    if (level === 'off') {
50895      level = 0;
50896    } else if (level === 'on' || level === 'warn') {
50897      level = 1;
50898    } else if (level === 'error') {
50899      level = 2;
50900    } else {
50901      level = 1;
50902      result = [level, result];
50903    }
50904  }
50905
50906  if (typeof level !== 'number' || level < 0 || level > 2) {
50907    throw new Error(
50908      'Incorrect severity `' +
50909        level +
50910        '` for `' +
50911        name +
50912        '`, ' +
50913        'expected 0, 1, or 2'
50914    )
50915  }
50916
50917  result[0] = level;
50918
50919  // @ts-expect-error: it’s now a valid tuple.
50920  return result
50921}
50922
50923/**
50924 * @author Titus Wormer
50925 * @copyright 2015 Titus Wormer
50926 * @license MIT
50927 * @module checkbox-character-style
50928 * @fileoverview
50929 *   Warn when list item checkboxes violate a given style.
50930 *
50931 *   Options: `Object` or `'consistent'`, default: `'consistent'`.
50932 *
50933 *   `'consistent'` detects the first used checked and unchecked checkbox
50934 *   styles and warns when subsequent checkboxes use different styles.
50935 *
50936 *   Styles can also be passed in like so:
50937 *
50938 *   ```js
50939 *   {checked: 'x', unchecked: ' '}
50940 *   ```
50941 *
50942 *   ## Fix
50943 *
50944 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
50945 *   formats checked checkboxes using `x` (lowercase X) and unchecked checkboxes
50946 *   as `·` (a single space).
50947 *
50948 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
50949 *   on how to automatically fix warnings for this rule.
50950 *
50951 * @example
50952 *   {"name": "ok.md", "setting": {"checked": "x"}, "gfm": true}
50953 *
50954 *   - [x] List item
50955 *   - [x] List item
50956 *
50957 * @example
50958 *   {"name": "ok.md", "setting": {"checked": "X"}, "gfm": true}
50959 *
50960 *   - [X] List item
50961 *   - [X] List item
50962 *
50963 * @example
50964 *   {"name": "ok.md", "setting": {"unchecked": " "}, "gfm": true}
50965 *
50966 *   - [ ] List item
50967 *   - [ ] List item
50968 *   - [ ]··
50969 *   - [ ]
50970 *
50971 * @example
50972 *   {"name": "ok.md", "setting": {"unchecked": "\t"}, "gfm": true}
50973 *
50974 *   - [»] List item
50975 *   - [»] List item
50976 *
50977 * @example
50978 *   {"name": "not-ok.md", "label": "input", "gfm": true}
50979 *
50980 *   - [x] List item
50981 *   - [X] List item
50982 *   - [ ] List item
50983 *   - [»] List item
50984 *
50985 * @example
50986 *   {"name": "not-ok.md", "label": "output", "gfm": true}
50987 *
50988 *   2:5: Checked checkboxes should use `x` as a marker
50989 *   4:5: Unchecked checkboxes should use ` ` as a marker
50990 *
50991 * @example
50992 *   {"setting": {"unchecked": "��"}, "name": "not-ok.md", "label": "output", "positionless": true, "gfm": true}
50993 *
50994 *   1:1: Incorrect unchecked checkbox marker `��`: use either `'\t'`, or `' '`
50995 *
50996 * @example
50997 *   {"setting": {"checked": "��"}, "name": "not-ok.md", "label": "output", "positionless": true, "gfm": true}
50998 *
50999 *   1:1: Incorrect checked checkbox marker `��`: use either `'x'`, or `'X'`
51000 */
51001
51002const remarkLintCheckboxCharacterStyle = lintRule$q(
51003  'remark-lint:checkbox-character-style',
51004  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
51005  (tree, file, option = 'consistent') => {
51006    const value = String(file);
51007    /** @type {'x'|'X'|'consistent'} */
51008    let checked = 'consistent';
51009    /** @type {' '|'\x09'|'consistent'} */
51010    let unchecked = 'consistent';
51011
51012    if (typeof option === 'object') {
51013      checked = option.checked || 'consistent';
51014      unchecked = option.unchecked || 'consistent';
51015    }
51016
51017    if (unchecked !== 'consistent' && unchecked !== ' ' && unchecked !== '\t') {
51018      file.fail(
51019        'Incorrect unchecked checkbox marker `' +
51020          unchecked +
51021          "`: use either `'\\t'`, or `' '`"
51022      );
51023    }
51024
51025    if (checked !== 'consistent' && checked !== 'x' && checked !== 'X') {
51026      file.fail(
51027        'Incorrect checked checkbox marker `' +
51028          checked +
51029          "`: use either `'x'`, or `'X'`"
51030      );
51031    }
51032
51033    visit(tree, 'listItem', (node) => {
51034      const head = node.children[0];
51035      const point = pointStart(head);
51036
51037      // Exit early for items without checkbox.
51038      // A list item cannot be checked and empty, according to GFM.
51039      if (
51040        typeof node.checked !== 'boolean' ||
51041        !head ||
51042        typeof point.offset !== 'number'
51043      ) {
51044        return
51045      }
51046
51047      // Move back to before `] `.
51048      point.offset -= 2;
51049      point.column -= 2;
51050
51051      // Assume we start with a checkbox, because well, `checked` is set.
51052      const match = /\[([\t Xx])]/.exec(
51053        value.slice(point.offset - 2, point.offset + 1)
51054      );
51055
51056      // Failsafe to make sure we don‘t crash if there actually isn’t a checkbox.
51057      /* c8 ignore next */
51058      if (!match) return
51059
51060      const style = node.checked ? checked : unchecked;
51061
51062      if (style === 'consistent') {
51063        if (node.checked) {
51064          // @ts-expect-error: valid marker.
51065          checked = match[1];
51066        } else {
51067          // @ts-expect-error: valid marker.
51068          unchecked = match[1];
51069        }
51070      } else if (match[1] !== style) {
51071        file.message(
51072          (node.checked ? 'Checked' : 'Unchecked') +
51073            ' checkboxes should use `' +
51074            style +
51075            '` as a marker',
51076          point
51077        );
51078      }
51079    });
51080  }
51081);
51082
51083var remarkLintCheckboxCharacterStyle$1 = remarkLintCheckboxCharacterStyle;
51084
51085/**
51086 * @typedef {import('unist').Node} Node
51087 * @typedef {import('vfile').VFile} VFile
51088 *
51089 * @typedef {0|1|2} Severity
51090 * @typedef {'warn'|'on'|'off'|'error'} Label
51091 * @typedef {[Severity, ...unknown[]]} SeverityTuple
51092 *
51093 * @callback Rule
51094 * @param {Node} tree
51095 * @param {VFile} file
51096 * @param {unknown} options
51097 * @returns {void}
51098 */
51099
51100const primitives$p = new Set(['string', 'number', 'boolean']);
51101
51102/**
51103 * @param {string} id
51104 * @param {Rule} rule
51105 */
51106function lintRule$p(id, rule) {
51107  const parts = id.split(':');
51108  // Possibly useful if externalised later.
51109  /* c8 ignore next */
51110  const source = parts[1] ? parts[0] : undefined;
51111  const ruleId = parts[1];
51112
51113  Object.defineProperty(plugin, 'name', {value: id});
51114
51115  return plugin
51116
51117  /** @type {import('unified').Plugin<[unknown]|void[]>} */
51118  function plugin(raw) {
51119    const [severity, options] = coerce$q(ruleId, raw);
51120
51121    if (!severity) return
51122
51123    const fatal = severity === 2;
51124
51125    return (tree, file, next) => {
51126      let index = file.messages.length - 1;
51127
51128      wrap(rule, (error) => {
51129        const messages = file.messages;
51130
51131        // Add the error, if not already properly added.
51132        // Only happens for incorrect plugins.
51133        /* c8 ignore next 6 */
51134        // @ts-expect-error: errors could be `messages`.
51135        if (error && !messages.includes(error)) {
51136          try {
51137            file.fail(error);
51138          } catch {}
51139        }
51140
51141        while (++index < messages.length) {
51142          Object.assign(messages[index], {ruleId, source, fatal});
51143        }
51144
51145        next();
51146      })(tree, file, options);
51147    }
51148  }
51149}
51150
51151/**
51152 * Coerce a value to a severity--options tuple.
51153 *
51154 * @param {string} name
51155 * @param {unknown} value
51156 * @returns {SeverityTuple}
51157 */
51158function coerce$q(name, value) {
51159  /** @type {unknown[]} */
51160  let result;
51161
51162  if (typeof value === 'boolean') {
51163    result = [value];
51164  } else if (value === null || value === undefined) {
51165    result = [1];
51166  } else if (
51167    Array.isArray(value) &&
51168    // `isArray(unknown)` is turned into `any[]`:
51169    // type-coverage:ignore-next-line
51170    primitives$p.has(typeof value[0])
51171  ) {
51172    // `isArray(unknown)` is turned into `any[]`:
51173    // type-coverage:ignore-next-line
51174    result = [...value];
51175  } else {
51176    result = [1, value];
51177  }
51178
51179  let level = result[0];
51180
51181  if (typeof level === 'boolean') {
51182    level = level ? 1 : 0;
51183  } else if (typeof level === 'string') {
51184    if (level === 'off') {
51185      level = 0;
51186    } else if (level === 'on' || level === 'warn') {
51187      level = 1;
51188    } else if (level === 'error') {
51189      level = 2;
51190    } else {
51191      level = 1;
51192      result = [level, result];
51193    }
51194  }
51195
51196  if (typeof level !== 'number' || level < 0 || level > 2) {
51197    throw new Error(
51198      'Incorrect severity `' +
51199        level +
51200        '` for `' +
51201        name +
51202        '`, ' +
51203        'expected 0, 1, or 2'
51204    )
51205  }
51206
51207  result[0] = level;
51208
51209  // @ts-expect-error: it’s now a valid tuple.
51210  return result
51211}
51212
51213/**
51214 * @author Titus Wormer
51215 * @copyright 2015 Titus Wormer
51216 * @license MIT
51217 * @module checkbox-content-indent
51218 * @fileoverview
51219 *   Warn when list item checkboxes are followed by too much whitespace.
51220 *
51221 * @example
51222 *   {"name": "ok.md", "gfm": true}
51223 *
51224 *   - [ ] List item
51225 *   +  [x] List Item
51226 *   *   [X] List item
51227 *   -    [ ] List item
51228 *
51229 * @example
51230 *   {"name": "not-ok.md", "label": "input", "gfm": true}
51231 *
51232 *   - [ ] List item
51233 *   + [x]  List item
51234 *   * [X]   List item
51235 *   - [ ]    List item
51236 *
51237 * @example
51238 *   {"name": "not-ok.md", "label": "output", "gfm": true}
51239 *
51240 *   2:7-2:8: Checkboxes should be followed by a single character
51241 *   3:7-3:9: Checkboxes should be followed by a single character
51242 *   4:7-4:10: Checkboxes should be followed by a single character
51243 */
51244
51245const remarkLintCheckboxContentIndent = lintRule$p(
51246  'remark-lint:checkbox-content-indent',
51247  /** @type {import('unified-lint-rule').Rule<Root, void>} */
51248  (tree, file) => {
51249    const value = String(file);
51250    const loc = location(file);
51251
51252    visit(tree, 'listItem', (node) => {
51253      const head = node.children[0];
51254      const point = pointStart(head);
51255
51256      // Exit early for items without checkbox.
51257      // A list item cannot be checked and empty, according to GFM.
51258      if (
51259        typeof node.checked !== 'boolean' ||
51260        !head ||
51261        typeof point.offset !== 'number'
51262      ) {
51263        return
51264      }
51265
51266      // Assume we start with a checkbox, because well, `checked` is set.
51267      const match = /\[([\t xX])]/.exec(
51268        value.slice(point.offset - 4, point.offset + 1)
51269      );
51270
51271      // Failsafe to make sure we don‘t crash if there actually isn’t a checkbox.
51272      /* c8 ignore next */
51273      if (!match) return
51274
51275      // Move past checkbox.
51276      const initial = point.offset;
51277      let final = initial;
51278
51279      while (/[\t ]/.test(value.charAt(final))) final++;
51280
51281      if (final - initial > 0) {
51282        file.message('Checkboxes should be followed by a single character', {
51283          start: loc.toPoint(initial),
51284          end: loc.toPoint(final)
51285        });
51286      }
51287    });
51288  }
51289);
51290
51291var remarkLintCheckboxContentIndent$1 = remarkLintCheckboxContentIndent;
51292
51293/**
51294 * @typedef {import('unist').Node} Node
51295 * @typedef {import('vfile').VFile} VFile
51296 *
51297 * @typedef {0|1|2} Severity
51298 * @typedef {'warn'|'on'|'off'|'error'} Label
51299 * @typedef {[Severity, ...unknown[]]} SeverityTuple
51300 *
51301 * @callback Rule
51302 * @param {Node} tree
51303 * @param {VFile} file
51304 * @param {unknown} options
51305 * @returns {void}
51306 */
51307
51308const primitives$o = new Set(['string', 'number', 'boolean']);
51309
51310/**
51311 * @param {string} id
51312 * @param {Rule} rule
51313 */
51314function lintRule$o(id, rule) {
51315  const parts = id.split(':');
51316  // Possibly useful if externalised later.
51317  /* c8 ignore next */
51318  const source = parts[1] ? parts[0] : undefined;
51319  const ruleId = parts[1];
51320
51321  Object.defineProperty(plugin, 'name', {value: id});
51322
51323  return plugin
51324
51325  /** @type {import('unified').Plugin<[unknown]|void[]>} */
51326  function plugin(raw) {
51327    const [severity, options] = coerce$p(ruleId, raw);
51328
51329    if (!severity) return
51330
51331    const fatal = severity === 2;
51332
51333    return (tree, file, next) => {
51334      let index = file.messages.length - 1;
51335
51336      wrap(rule, (error) => {
51337        const messages = file.messages;
51338
51339        // Add the error, if not already properly added.
51340        // Only happens for incorrect plugins.
51341        /* c8 ignore next 6 */
51342        // @ts-expect-error: errors could be `messages`.
51343        if (error && !messages.includes(error)) {
51344          try {
51345            file.fail(error);
51346          } catch {}
51347        }
51348
51349        while (++index < messages.length) {
51350          Object.assign(messages[index], {ruleId, source, fatal});
51351        }
51352
51353        next();
51354      })(tree, file, options);
51355    }
51356  }
51357}
51358
51359/**
51360 * Coerce a value to a severity--options tuple.
51361 *
51362 * @param {string} name
51363 * @param {unknown} value
51364 * @returns {SeverityTuple}
51365 */
51366function coerce$p(name, value) {
51367  /** @type {unknown[]} */
51368  let result;
51369
51370  if (typeof value === 'boolean') {
51371    result = [value];
51372  } else if (value === null || value === undefined) {
51373    result = [1];
51374  } else if (
51375    Array.isArray(value) &&
51376    // `isArray(unknown)` is turned into `any[]`:
51377    // type-coverage:ignore-next-line
51378    primitives$o.has(typeof value[0])
51379  ) {
51380    // `isArray(unknown)` is turned into `any[]`:
51381    // type-coverage:ignore-next-line
51382    result = [...value];
51383  } else {
51384    result = [1, value];
51385  }
51386
51387  let level = result[0];
51388
51389  if (typeof level === 'boolean') {
51390    level = level ? 1 : 0;
51391  } else if (typeof level === 'string') {
51392    if (level === 'off') {
51393      level = 0;
51394    } else if (level === 'on' || level === 'warn') {
51395      level = 1;
51396    } else if (level === 'error') {
51397      level = 2;
51398    } else {
51399      level = 1;
51400      result = [level, result];
51401    }
51402  }
51403
51404  if (typeof level !== 'number' || level < 0 || level > 2) {
51405    throw new Error(
51406      'Incorrect severity `' +
51407        level +
51408        '` for `' +
51409        name +
51410        '`, ' +
51411        'expected 0, 1, or 2'
51412    )
51413  }
51414
51415  result[0] = level;
51416
51417  // @ts-expect-error: it’s now a valid tuple.
51418  return result
51419}
51420
51421/**
51422 * @author Titus Wormer
51423 * @copyright 2015 Titus Wormer
51424 * @license MIT
51425 * @module code-block-style
51426 * @fileoverview
51427 *   Warn when code blocks do not adhere to a given style.
51428 *
51429 *   Options: `'consistent'`, `'fenced'`, or `'indented'`, default: `'consistent'`.
51430 *
51431 *   `'consistent'` detects the first used code block style and warns when
51432 *   subsequent code blocks uses different styles.
51433 *
51434 *   ## Fix
51435 *
51436 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
51437 *   formats code blocks using a fence if they have a language flag and
51438 *   indentation if not.
51439 *   Pass
51440 *   [`fences: true`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsfences)
51441 *   to always use fences for code blocks.
51442 *
51443 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
51444 *   on how to automatically fix warnings for this rule.
51445 *
51446 * @example
51447 *   {"setting": "indented", "name": "ok.md"}
51448 *
51449 *       alpha()
51450 *
51451 *   Paragraph.
51452 *
51453 *       bravo()
51454 *
51455 * @example
51456 *   {"setting": "indented", "name": "not-ok.md", "label": "input"}
51457 *
51458 *   ```
51459 *   alpha()
51460 *   ```
51461 *
51462 *   Paragraph.
51463 *
51464 *   ```
51465 *   bravo()
51466 *   ```
51467 *
51468 * @example
51469 *   {"setting": "indented", "name": "not-ok.md", "label": "output"}
51470 *
51471 *   1:1-3:4: Code blocks should be indented
51472 *   7:1-9:4: Code blocks should be indented
51473 *
51474 * @example
51475 *   {"setting": "fenced", "name": "ok.md"}
51476 *
51477 *   ```
51478 *   alpha()
51479 *   ```
51480 *
51481 *   Paragraph.
51482 *
51483 *   ```
51484 *   bravo()
51485 *   ```
51486 *
51487 * @example
51488 *   {"setting": "fenced", "name": "not-ok-fenced.md", "label": "input"}
51489 *
51490 *       alpha()
51491 *
51492 *   Paragraph.
51493 *
51494 *       bravo()
51495 *
51496 * @example
51497 *   {"setting": "fenced", "name": "not-ok-fenced.md", "label": "output"}
51498 *
51499 *   1:1-1:12: Code blocks should be fenced
51500 *   5:1-5:12: Code blocks should be fenced
51501 *
51502 * @example
51503 *   {"name": "not-ok-consistent.md", "label": "input"}
51504 *
51505 *       alpha()
51506 *
51507 *   Paragraph.
51508 *
51509 *   ```
51510 *   bravo()
51511 *   ```
51512 *
51513 * @example
51514 *   {"name": "not-ok-consistent.md", "label": "output"}
51515 *
51516 *   5:1-7:4: Code blocks should be indented
51517 *
51518 * @example
51519 *   {"setting": "��", "name": "not-ok-incorrect.md", "label": "output", "positionless": true}
51520 *
51521 *   1:1: Incorrect code block style `��`: use either `'consistent'`, `'fenced'`, or `'indented'`
51522 */
51523
51524const remarkLintCodeBlockStyle = lintRule$o(
51525  'remark-lint:code-block-style',
51526  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
51527  (tree, file, option = 'consistent') => {
51528    const value = String(file);
51529
51530    if (
51531      option !== 'consistent' &&
51532      option !== 'fenced' &&
51533      option !== 'indented'
51534    ) {
51535      file.fail(
51536        'Incorrect code block style `' +
51537          option +
51538          "`: use either `'consistent'`, `'fenced'`, or `'indented'`"
51539      );
51540    }
51541
51542    visit(tree, 'code', (node) => {
51543      if (generated(node)) {
51544        return
51545      }
51546
51547      const initial = pointStart(node).offset;
51548      const final = pointEnd(node).offset;
51549
51550      const current =
51551        node.lang || /^\s*([~`])\1{2,}/.test(value.slice(initial, final))
51552          ? 'fenced'
51553          : 'indented';
51554
51555      if (option === 'consistent') {
51556        option = current;
51557      } else if (option !== current) {
51558        file.message('Code blocks should be ' + option, node);
51559      }
51560    });
51561  }
51562);
51563
51564var remarkLintCodeBlockStyle$1 = remarkLintCodeBlockStyle;
51565
51566/**
51567 * @typedef {import('unist').Node} Node
51568 * @typedef {import('vfile').VFile} VFile
51569 *
51570 * @typedef {0|1|2} Severity
51571 * @typedef {'warn'|'on'|'off'|'error'} Label
51572 * @typedef {[Severity, ...unknown[]]} SeverityTuple
51573 *
51574 * @callback Rule
51575 * @param {Node} tree
51576 * @param {VFile} file
51577 * @param {unknown} options
51578 * @returns {void}
51579 */
51580
51581const primitives$n = new Set(['string', 'number', 'boolean']);
51582
51583/**
51584 * @param {string} id
51585 * @param {Rule} rule
51586 */
51587function lintRule$n(id, rule) {
51588  const parts = id.split(':');
51589  // Possibly useful if externalised later.
51590  /* c8 ignore next */
51591  const source = parts[1] ? parts[0] : undefined;
51592  const ruleId = parts[1];
51593
51594  Object.defineProperty(plugin, 'name', {value: id});
51595
51596  return plugin
51597
51598  /** @type {import('unified').Plugin<[unknown]|void[]>} */
51599  function plugin(raw) {
51600    const [severity, options] = coerce$o(ruleId, raw);
51601
51602    if (!severity) return
51603
51604    const fatal = severity === 2;
51605
51606    return (tree, file, next) => {
51607      let index = file.messages.length - 1;
51608
51609      wrap(rule, (error) => {
51610        const messages = file.messages;
51611
51612        // Add the error, if not already properly added.
51613        // Only happens for incorrect plugins.
51614        /* c8 ignore next 6 */
51615        // @ts-expect-error: errors could be `messages`.
51616        if (error && !messages.includes(error)) {
51617          try {
51618            file.fail(error);
51619          } catch {}
51620        }
51621
51622        while (++index < messages.length) {
51623          Object.assign(messages[index], {ruleId, source, fatal});
51624        }
51625
51626        next();
51627      })(tree, file, options);
51628    }
51629  }
51630}
51631
51632/**
51633 * Coerce a value to a severity--options tuple.
51634 *
51635 * @param {string} name
51636 * @param {unknown} value
51637 * @returns {SeverityTuple}
51638 */
51639function coerce$o(name, value) {
51640  /** @type {unknown[]} */
51641  let result;
51642
51643  if (typeof value === 'boolean') {
51644    result = [value];
51645  } else if (value === null || value === undefined) {
51646    result = [1];
51647  } else if (
51648    Array.isArray(value) &&
51649    // `isArray(unknown)` is turned into `any[]`:
51650    // type-coverage:ignore-next-line
51651    primitives$n.has(typeof value[0])
51652  ) {
51653    // `isArray(unknown)` is turned into `any[]`:
51654    // type-coverage:ignore-next-line
51655    result = [...value];
51656  } else {
51657    result = [1, value];
51658  }
51659
51660  let level = result[0];
51661
51662  if (typeof level === 'boolean') {
51663    level = level ? 1 : 0;
51664  } else if (typeof level === 'string') {
51665    if (level === 'off') {
51666      level = 0;
51667    } else if (level === 'on' || level === 'warn') {
51668      level = 1;
51669    } else if (level === 'error') {
51670      level = 2;
51671    } else {
51672      level = 1;
51673      result = [level, result];
51674    }
51675  }
51676
51677  if (typeof level !== 'number' || level < 0 || level > 2) {
51678    throw new Error(
51679      'Incorrect severity `' +
51680        level +
51681        '` for `' +
51682        name +
51683        '`, ' +
51684        'expected 0, 1, or 2'
51685    )
51686  }
51687
51688  result[0] = level;
51689
51690  // @ts-expect-error: it’s now a valid tuple.
51691  return result
51692}
51693
51694/**
51695 * @author Titus Wormer
51696 * @copyright 2015 Titus Wormer
51697 * @license MIT
51698 * @module definition-spacing
51699 * @fileoverview
51700 *   Warn when consecutive whitespace is used in a definition.
51701 *
51702 * @example
51703 *   {"name": "ok.md"}
51704 *
51705 *   [example domain]: http://example.com "Example Domain"
51706 *
51707 * @example
51708 *   {"name": "not-ok.md", "label": "input"}
51709 *
51710 *   [example····domain]: http://example.com "Example Domain"
51711 *
51712 * @example
51713 *   {"name": "not-ok.md", "label": "output"}
51714 *
51715 *   1:1-1:57: Do not use consecutive whitespace in definition labels
51716 */
51717
51718const label = /^\s*\[((?:\\[\s\S]|[^[\]])+)]/;
51719
51720const remarkLintDefinitionSpacing = lintRule$n(
51721  'remark-lint:definition-spacing',
51722  /** @type {import('unified-lint-rule').Rule<Root, void>} */
51723  (tree, file) => {
51724    const value = String(file);
51725
51726    visit(tree, (node) => {
51727      if (node.type === 'definition' || node.type === 'footnoteDefinition') {
51728        const start = pointStart(node).offset;
51729        const end = pointEnd(node).offset;
51730
51731        if (typeof start === 'number' && typeof end === 'number') {
51732          const match = value.slice(start, end).match(label);
51733
51734          if (match && /[ \t\n]{2,}/.test(match[1])) {
51735            file.message(
51736              'Do not use consecutive whitespace in definition labels',
51737              node
51738            );
51739          }
51740        }
51741      }
51742    });
51743  }
51744);
51745
51746var remarkLintDefinitionSpacing$1 = remarkLintDefinitionSpacing;
51747
51748/**
51749 * @typedef {import('unist').Node} Node
51750 * @typedef {import('vfile').VFile} VFile
51751 *
51752 * @typedef {0|1|2} Severity
51753 * @typedef {'warn'|'on'|'off'|'error'} Label
51754 * @typedef {[Severity, ...unknown[]]} SeverityTuple
51755 *
51756 * @callback Rule
51757 * @param {Node} tree
51758 * @param {VFile} file
51759 * @param {unknown} options
51760 * @returns {void}
51761 */
51762
51763const primitives$m = new Set(['string', 'number', 'boolean']);
51764
51765/**
51766 * @param {string} id
51767 * @param {Rule} rule
51768 */
51769function lintRule$m(id, rule) {
51770  const parts = id.split(':');
51771  // Possibly useful if externalised later.
51772  /* c8 ignore next */
51773  const source = parts[1] ? parts[0] : undefined;
51774  const ruleId = parts[1];
51775
51776  Object.defineProperty(plugin, 'name', {value: id});
51777
51778  return plugin
51779
51780  /** @type {import('unified').Plugin<[unknown]|void[]>} */
51781  function plugin(raw) {
51782    const [severity, options] = coerce$n(ruleId, raw);
51783
51784    if (!severity) return
51785
51786    const fatal = severity === 2;
51787
51788    return (tree, file, next) => {
51789      let index = file.messages.length - 1;
51790
51791      wrap(rule, (error) => {
51792        const messages = file.messages;
51793
51794        // Add the error, if not already properly added.
51795        // Only happens for incorrect plugins.
51796        /* c8 ignore next 6 */
51797        // @ts-expect-error: errors could be `messages`.
51798        if (error && !messages.includes(error)) {
51799          try {
51800            file.fail(error);
51801          } catch {}
51802        }
51803
51804        while (++index < messages.length) {
51805          Object.assign(messages[index], {ruleId, source, fatal});
51806        }
51807
51808        next();
51809      })(tree, file, options);
51810    }
51811  }
51812}
51813
51814/**
51815 * Coerce a value to a severity--options tuple.
51816 *
51817 * @param {string} name
51818 * @param {unknown} value
51819 * @returns {SeverityTuple}
51820 */
51821function coerce$n(name, value) {
51822  /** @type {unknown[]} */
51823  let result;
51824
51825  if (typeof value === 'boolean') {
51826    result = [value];
51827  } else if (value === null || value === undefined) {
51828    result = [1];
51829  } else if (
51830    Array.isArray(value) &&
51831    // `isArray(unknown)` is turned into `any[]`:
51832    // type-coverage:ignore-next-line
51833    primitives$m.has(typeof value[0])
51834  ) {
51835    // `isArray(unknown)` is turned into `any[]`:
51836    // type-coverage:ignore-next-line
51837    result = [...value];
51838  } else {
51839    result = [1, value];
51840  }
51841
51842  let level = result[0];
51843
51844  if (typeof level === 'boolean') {
51845    level = level ? 1 : 0;
51846  } else if (typeof level === 'string') {
51847    if (level === 'off') {
51848      level = 0;
51849    } else if (level === 'on' || level === 'warn') {
51850      level = 1;
51851    } else if (level === 'error') {
51852      level = 2;
51853    } else {
51854      level = 1;
51855      result = [level, result];
51856    }
51857  }
51858
51859  if (typeof level !== 'number' || level < 0 || level > 2) {
51860    throw new Error(
51861      'Incorrect severity `' +
51862        level +
51863        '` for `' +
51864        name +
51865        '`, ' +
51866        'expected 0, 1, or 2'
51867    )
51868  }
51869
51870  result[0] = level;
51871
51872  // @ts-expect-error: it’s now a valid tuple.
51873  return result
51874}
51875
51876/**
51877 * @author Titus Wormer
51878 * @copyright 2015 Titus Wormer
51879 * @license MIT
51880 * @module fenced-code-flag
51881 * @fileoverview
51882 *   Check fenced code block flags.
51883 *
51884 *   Options: `Array.<string>` or `Object`, optional.
51885 *
51886 *   Providing an array is as passing `{flags: Array}`.
51887 *
51888 *   The object can have an array of `'flags'` which are allowed: other flags
51889 *   will not be allowed.
51890 *   An `allowEmpty` field (`boolean`, default: `false`) can be set to allow
51891 *   code blocks without language flags.
51892 *
51893 * @example
51894 *   {"name": "ok.md"}
51895 *
51896 *   ```alpha
51897 *   bravo()
51898 *   ```
51899 *
51900 * @example
51901 *   {"name": "not-ok.md", "label": "input"}
51902 *
51903 *   ```
51904 *   alpha()
51905 *   ```
51906 *
51907 * @example
51908 *   {"name": "not-ok.md", "label": "output"}
51909 *
51910 *   1:1-3:4: Missing code language flag
51911 *
51912 * @example
51913 *   {"name": "ok.md", "setting": {"allowEmpty": true}}
51914 *
51915 *   ```
51916 *   alpha()
51917 *   ```
51918 *
51919 * @example
51920 *   {"name": "not-ok.md", "setting": {"allowEmpty": false}, "label": "input"}
51921 *
51922 *   ```
51923 *   alpha()
51924 *   ```
51925 *
51926 * @example
51927 *   {"name": "not-ok.md", "setting": {"allowEmpty": false}, "label": "output"}
51928 *
51929 *   1:1-3:4: Missing code language flag
51930 *
51931 * @example
51932 *   {"name": "ok.md", "setting": ["alpha"]}
51933 *
51934 *   ```alpha
51935 *   bravo()
51936 *   ```
51937 *
51938 * @example
51939 *   {"name": "ok.md", "setting": {"flags":["alpha"]}}
51940 *
51941 *   ```alpha
51942 *   bravo()
51943 *   ```
51944 *
51945 * @example
51946 *   {"name": "not-ok.md", "setting": ["charlie"], "label": "input"}
51947 *
51948 *   ```alpha
51949 *   bravo()
51950 *   ```
51951 *
51952 * @example
51953 *   {"name": "not-ok.md", "setting": ["charlie"], "label": "output"}
51954 *
51955 *   1:1-3:4: Incorrect code language flag
51956 */
51957
51958const fence = /^ {0,3}([~`])\1{2,}/;
51959
51960const remarkLintFencedCodeFlag = lintRule$m(
51961  'remark-lint:fenced-code-flag',
51962  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
51963  (tree, file, option) => {
51964    const value = String(file);
51965    let allowEmpty = false;
51966    /** @type {string[]} */
51967    let allowed = [];
51968
51969    if (typeof option === 'object') {
51970      if (Array.isArray(option)) {
51971        allowed = option;
51972      } else {
51973        allowEmpty = Boolean(option.allowEmpty);
51974
51975        if (option.flags) {
51976          allowed = option.flags;
51977        }
51978      }
51979    }
51980
51981    visit(tree, 'code', (node) => {
51982      if (!generated(node)) {
51983        if (node.lang) {
51984          if (allowed.length > 0 && !allowed.includes(node.lang)) {
51985            file.message('Incorrect code language flag', node);
51986          }
51987        } else {
51988          const slice = value.slice(
51989            pointStart(node).offset,
51990            pointEnd(node).offset
51991          );
51992
51993          if (!allowEmpty && fence.test(slice)) {
51994            file.message('Missing code language flag', node);
51995          }
51996        }
51997      }
51998    });
51999  }
52000);
52001
52002var remarkLintFencedCodeFlag$1 = remarkLintFencedCodeFlag;
52003
52004/**
52005 * @typedef {import('unist').Node} Node
52006 * @typedef {import('vfile').VFile} VFile
52007 *
52008 * @typedef {0|1|2} Severity
52009 * @typedef {'warn'|'on'|'off'|'error'} Label
52010 * @typedef {[Severity, ...unknown[]]} SeverityTuple
52011 *
52012 * @callback Rule
52013 * @param {Node} tree
52014 * @param {VFile} file
52015 * @param {unknown} options
52016 * @returns {void}
52017 */
52018
52019const primitives$l = new Set(['string', 'number', 'boolean']);
52020
52021/**
52022 * @param {string} id
52023 * @param {Rule} rule
52024 */
52025function lintRule$l(id, rule) {
52026  const parts = id.split(':');
52027  // Possibly useful if externalised later.
52028  /* c8 ignore next */
52029  const source = parts[1] ? parts[0] : undefined;
52030  const ruleId = parts[1];
52031
52032  Object.defineProperty(plugin, 'name', {value: id});
52033
52034  return plugin
52035
52036  /** @type {import('unified').Plugin<[unknown]|void[]>} */
52037  function plugin(raw) {
52038    const [severity, options] = coerce$m(ruleId, raw);
52039
52040    if (!severity) return
52041
52042    const fatal = severity === 2;
52043
52044    return (tree, file, next) => {
52045      let index = file.messages.length - 1;
52046
52047      wrap(rule, (error) => {
52048        const messages = file.messages;
52049
52050        // Add the error, if not already properly added.
52051        // Only happens for incorrect plugins.
52052        /* c8 ignore next 6 */
52053        // @ts-expect-error: errors could be `messages`.
52054        if (error && !messages.includes(error)) {
52055          try {
52056            file.fail(error);
52057          } catch {}
52058        }
52059
52060        while (++index < messages.length) {
52061          Object.assign(messages[index], {ruleId, source, fatal});
52062        }
52063
52064        next();
52065      })(tree, file, options);
52066    }
52067  }
52068}
52069
52070/**
52071 * Coerce a value to a severity--options tuple.
52072 *
52073 * @param {string} name
52074 * @param {unknown} value
52075 * @returns {SeverityTuple}
52076 */
52077function coerce$m(name, value) {
52078  /** @type {unknown[]} */
52079  let result;
52080
52081  if (typeof value === 'boolean') {
52082    result = [value];
52083  } else if (value === null || value === undefined) {
52084    result = [1];
52085  } else if (
52086    Array.isArray(value) &&
52087    // `isArray(unknown)` is turned into `any[]`:
52088    // type-coverage:ignore-next-line
52089    primitives$l.has(typeof value[0])
52090  ) {
52091    // `isArray(unknown)` is turned into `any[]`:
52092    // type-coverage:ignore-next-line
52093    result = [...value];
52094  } else {
52095    result = [1, value];
52096  }
52097
52098  let level = result[0];
52099
52100  if (typeof level === 'boolean') {
52101    level = level ? 1 : 0;
52102  } else if (typeof level === 'string') {
52103    if (level === 'off') {
52104      level = 0;
52105    } else if (level === 'on' || level === 'warn') {
52106      level = 1;
52107    } else if (level === 'error') {
52108      level = 2;
52109    } else {
52110      level = 1;
52111      result = [level, result];
52112    }
52113  }
52114
52115  if (typeof level !== 'number' || level < 0 || level > 2) {
52116    throw new Error(
52117      'Incorrect severity `' +
52118        level +
52119        '` for `' +
52120        name +
52121        '`, ' +
52122        'expected 0, 1, or 2'
52123    )
52124  }
52125
52126  result[0] = level;
52127
52128  // @ts-expect-error: it’s now a valid tuple.
52129  return result
52130}
52131
52132/**
52133 * @author Titus Wormer
52134 * @copyright 2015 Titus Wormer
52135 * @license MIT
52136 * @module fenced-code-marker
52137 * @fileoverview
52138 *   Warn for violating fenced code markers.
52139 *
52140 *   Options: `` '`' ``, `'~'`, or `'consistent'`, default: `'consistent'`.
52141 *
52142 *   `'consistent'` detects the first used fenced code marker style and warns
52143 *   when subsequent fenced code blocks use different styles.
52144 *
52145 *   ## Fix
52146 *
52147 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
52148 *   formats fences using ``'`'`` (grave accent) by default.
52149 *   Pass
52150 *   [`fence: '~'`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsfence)
52151 *   to use `~` (tilde) instead.
52152 *
52153 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
52154 *   on how to automatically fix warnings for this rule.
52155 *
52156 * @example
52157 *   {"name": "ok.md"}
52158 *
52159 *   Indented code blocks are not affected by this rule:
52160 *
52161 *       bravo()
52162 *
52163 * @example
52164 *   {"name": "ok.md", "setting": "`"}
52165 *
52166 *   ```alpha
52167 *   bravo()
52168 *   ```
52169 *
52170 *   ```
52171 *   charlie()
52172 *   ```
52173 *
52174 * @example
52175 *   {"name": "ok.md", "setting": "~"}
52176 *
52177 *   ~~~alpha
52178 *   bravo()
52179 *   ~~~
52180 *
52181 *   ~~~
52182 *   charlie()
52183 *   ~~~
52184 *
52185 * @example
52186 *   {"name": "not-ok-consistent-tick.md", "label": "input"}
52187 *
52188 *   ```alpha
52189 *   bravo()
52190 *   ```
52191 *
52192 *   ~~~
52193 *   charlie()
52194 *   ~~~
52195 *
52196 * @example
52197 *   {"name": "not-ok-consistent-tick.md", "label": "output"}
52198 *
52199 *   5:1-7:4: Fenced code should use `` ` `` as a marker
52200 *
52201 * @example
52202 *   {"name": "not-ok-consistent-tilde.md", "label": "input"}
52203 *
52204 *   ~~~alpha
52205 *   bravo()
52206 *   ~~~
52207 *
52208 *   ```
52209 *   charlie()
52210 *   ```
52211 *
52212 * @example
52213 *   {"name": "not-ok-consistent-tilde.md", "label": "output"}
52214 *
52215 *   5:1-7:4: Fenced code should use `~` as a marker
52216 *
52217 * @example
52218 *   {"name": "not-ok-incorrect.md", "setting": "��", "label": "output", "positionless": true}
52219 *
52220 *   1:1: Incorrect fenced code marker `��`: use either `'consistent'`, `` '`' ``, or `'~'`
52221 */
52222
52223const remarkLintFencedCodeMarker = lintRule$l(
52224  'remark-lint:fenced-code-marker',
52225  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
52226  (tree, file, option = 'consistent') => {
52227    const contents = String(file);
52228
52229    if (option !== 'consistent' && option !== '~' && option !== '`') {
52230      file.fail(
52231        'Incorrect fenced code marker `' +
52232          option +
52233          "`: use either `'consistent'`, `` '`' ``, or `'~'`"
52234      );
52235    }
52236
52237    visit(tree, 'code', (node) => {
52238      const start = pointStart(node).offset;
52239
52240      if (typeof start === 'number') {
52241        const marker = contents
52242          .slice(start, start + 4)
52243          .replace(/^\s+/, '')
52244          .charAt(0);
52245
52246        // Ignore unfenced code blocks.
52247        if (marker === '~' || marker === '`') {
52248          if (option === 'consistent') {
52249            option = marker;
52250          } else if (marker !== option) {
52251            file.message(
52252              'Fenced code should use `' +
52253                (option === '~' ? option : '` ` `') +
52254                '` as a marker',
52255              node
52256            );
52257          }
52258        }
52259      }
52260    });
52261  }
52262);
52263
52264var remarkLintFencedCodeMarker$1 = remarkLintFencedCodeMarker;
52265
52266/**
52267 * @typedef {import('unist').Node} Node
52268 * @typedef {import('vfile').VFile} VFile
52269 *
52270 * @typedef {0|1|2} Severity
52271 * @typedef {'warn'|'on'|'off'|'error'} Label
52272 * @typedef {[Severity, ...unknown[]]} SeverityTuple
52273 *
52274 * @callback Rule
52275 * @param {Node} tree
52276 * @param {VFile} file
52277 * @param {unknown} options
52278 * @returns {void}
52279 */
52280
52281const primitives$k = new Set(['string', 'number', 'boolean']);
52282
52283/**
52284 * @param {string} id
52285 * @param {Rule} rule
52286 */
52287function lintRule$k(id, rule) {
52288  const parts = id.split(':');
52289  // Possibly useful if externalised later.
52290  /* c8 ignore next */
52291  const source = parts[1] ? parts[0] : undefined;
52292  const ruleId = parts[1];
52293
52294  Object.defineProperty(plugin, 'name', {value: id});
52295
52296  return plugin
52297
52298  /** @type {import('unified').Plugin<[unknown]|void[]>} */
52299  function plugin(raw) {
52300    const [severity, options] = coerce$l(ruleId, raw);
52301
52302    if (!severity) return
52303
52304    const fatal = severity === 2;
52305
52306    return (tree, file, next) => {
52307      let index = file.messages.length - 1;
52308
52309      wrap(rule, (error) => {
52310        const messages = file.messages;
52311
52312        // Add the error, if not already properly added.
52313        // Only happens for incorrect plugins.
52314        /* c8 ignore next 6 */
52315        // @ts-expect-error: errors could be `messages`.
52316        if (error && !messages.includes(error)) {
52317          try {
52318            file.fail(error);
52319          } catch {}
52320        }
52321
52322        while (++index < messages.length) {
52323          Object.assign(messages[index], {ruleId, source, fatal});
52324        }
52325
52326        next();
52327      })(tree, file, options);
52328    }
52329  }
52330}
52331
52332/**
52333 * Coerce a value to a severity--options tuple.
52334 *
52335 * @param {string} name
52336 * @param {unknown} value
52337 * @returns {SeverityTuple}
52338 */
52339function coerce$l(name, value) {
52340  /** @type {unknown[]} */
52341  let result;
52342
52343  if (typeof value === 'boolean') {
52344    result = [value];
52345  } else if (value === null || value === undefined) {
52346    result = [1];
52347  } else if (
52348    Array.isArray(value) &&
52349    // `isArray(unknown)` is turned into `any[]`:
52350    // type-coverage:ignore-next-line
52351    primitives$k.has(typeof value[0])
52352  ) {
52353    // `isArray(unknown)` is turned into `any[]`:
52354    // type-coverage:ignore-next-line
52355    result = [...value];
52356  } else {
52357    result = [1, value];
52358  }
52359
52360  let level = result[0];
52361
52362  if (typeof level === 'boolean') {
52363    level = level ? 1 : 0;
52364  } else if (typeof level === 'string') {
52365    if (level === 'off') {
52366      level = 0;
52367    } else if (level === 'on' || level === 'warn') {
52368      level = 1;
52369    } else if (level === 'error') {
52370      level = 2;
52371    } else {
52372      level = 1;
52373      result = [level, result];
52374    }
52375  }
52376
52377  if (typeof level !== 'number' || level < 0 || level > 2) {
52378    throw new Error(
52379      'Incorrect severity `' +
52380        level +
52381        '` for `' +
52382        name +
52383        '`, ' +
52384        'expected 0, 1, or 2'
52385    )
52386  }
52387
52388  result[0] = level;
52389
52390  // @ts-expect-error: it’s now a valid tuple.
52391  return result
52392}
52393
52394/**
52395 * @author Titus Wormer
52396 * @copyright 2015 Titus Wormer
52397 * @license MIT
52398 * @module file-extension
52399 * @fileoverview
52400 *   Warn when the file extension differ from the preferred extension.
52401 *
52402 *   Does not warn when given documents have no file extensions (such as
52403 *   `AUTHORS` or `LICENSE`).
52404 *
52405 *   Options: `string`, default: `'md'` — Expected file extension.
52406 *
52407 * @example
52408 *   {"name": "readme.md"}
52409 *
52410 * @example
52411 *   {"name": "readme"}
52412 *
52413 * @example
52414 *   {"name": "readme.mkd", "label": "output", "positionless": true}
52415 *
52416 *   1:1: Incorrect extension: use `md`
52417 *
52418 * @example
52419 *   {"name": "readme.mkd", "setting": "mkd"}
52420 */
52421
52422const remarkLintFileExtension = lintRule$k(
52423  'remark-lint:file-extension',
52424  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
52425  (_, file, option = 'md') => {
52426    const ext = file.extname;
52427
52428    if (ext && ext.slice(1) !== option) {
52429      file.message('Incorrect extension: use `' + option + '`');
52430    }
52431  }
52432);
52433
52434var remarkLintFileExtension$1 = remarkLintFileExtension;
52435
52436/**
52437 * @typedef {import('unist').Node} Node
52438 * @typedef {import('vfile').VFile} VFile
52439 *
52440 * @typedef {0|1|2} Severity
52441 * @typedef {'warn'|'on'|'off'|'error'} Label
52442 * @typedef {[Severity, ...unknown[]]} SeverityTuple
52443 *
52444 * @callback Rule
52445 * @param {Node} tree
52446 * @param {VFile} file
52447 * @param {unknown} options
52448 * @returns {void}
52449 */
52450
52451const primitives$j = new Set(['string', 'number', 'boolean']);
52452
52453/**
52454 * @param {string} id
52455 * @param {Rule} rule
52456 */
52457function lintRule$j(id, rule) {
52458  const parts = id.split(':');
52459  // Possibly useful if externalised later.
52460  /* c8 ignore next */
52461  const source = parts[1] ? parts[0] : undefined;
52462  const ruleId = parts[1];
52463
52464  Object.defineProperty(plugin, 'name', {value: id});
52465
52466  return plugin
52467
52468  /** @type {import('unified').Plugin<[unknown]|void[]>} */
52469  function plugin(raw) {
52470    const [severity, options] = coerce$k(ruleId, raw);
52471
52472    if (!severity) return
52473
52474    const fatal = severity === 2;
52475
52476    return (tree, file, next) => {
52477      let index = file.messages.length - 1;
52478
52479      wrap(rule, (error) => {
52480        const messages = file.messages;
52481
52482        // Add the error, if not already properly added.
52483        // Only happens for incorrect plugins.
52484        /* c8 ignore next 6 */
52485        // @ts-expect-error: errors could be `messages`.
52486        if (error && !messages.includes(error)) {
52487          try {
52488            file.fail(error);
52489          } catch {}
52490        }
52491
52492        while (++index < messages.length) {
52493          Object.assign(messages[index], {ruleId, source, fatal});
52494        }
52495
52496        next();
52497      })(tree, file, options);
52498    }
52499  }
52500}
52501
52502/**
52503 * Coerce a value to a severity--options tuple.
52504 *
52505 * @param {string} name
52506 * @param {unknown} value
52507 * @returns {SeverityTuple}
52508 */
52509function coerce$k(name, value) {
52510  /** @type {unknown[]} */
52511  let result;
52512
52513  if (typeof value === 'boolean') {
52514    result = [value];
52515  } else if (value === null || value === undefined) {
52516    result = [1];
52517  } else if (
52518    Array.isArray(value) &&
52519    // `isArray(unknown)` is turned into `any[]`:
52520    // type-coverage:ignore-next-line
52521    primitives$j.has(typeof value[0])
52522  ) {
52523    // `isArray(unknown)` is turned into `any[]`:
52524    // type-coverage:ignore-next-line
52525    result = [...value];
52526  } else {
52527    result = [1, value];
52528  }
52529
52530  let level = result[0];
52531
52532  if (typeof level === 'boolean') {
52533    level = level ? 1 : 0;
52534  } else if (typeof level === 'string') {
52535    if (level === 'off') {
52536      level = 0;
52537    } else if (level === 'on' || level === 'warn') {
52538      level = 1;
52539    } else if (level === 'error') {
52540      level = 2;
52541    } else {
52542      level = 1;
52543      result = [level, result];
52544    }
52545  }
52546
52547  if (typeof level !== 'number' || level < 0 || level > 2) {
52548    throw new Error(
52549      'Incorrect severity `' +
52550        level +
52551        '` for `' +
52552        name +
52553        '`, ' +
52554        'expected 0, 1, or 2'
52555    )
52556  }
52557
52558  result[0] = level;
52559
52560  // @ts-expect-error: it’s now a valid tuple.
52561  return result
52562}
52563
52564/**
52565 * @author Titus Wormer
52566 * @copyright 2015 Titus Wormer
52567 * @license MIT
52568 * @module final-definition
52569 * @fileoverview
52570 *   Warn when definitions are placed somewhere other than at the end of
52571 *   the file.
52572 *
52573 * @example
52574 *   {"name": "ok.md"}
52575 *
52576 *   Paragraph.
52577 *
52578 *   [example]: http://example.com "Example Domain"
52579 *
52580 * @example
52581 *   {"name": "not-ok.md", "label": "input"}
52582 *
52583 *   Paragraph.
52584 *
52585 *   [example]: http://example.com "Example Domain"
52586 *
52587 *   Another paragraph.
52588 *
52589 * @example
52590 *   {"name": "not-ok.md", "label": "output"}
52591 *
52592 *   3:1-3:47: Move definitions to the end of the file (after the node at line `5`)
52593 *
52594 * @example
52595 *   {"name": "ok-comments.md"}
52596 *
52597 *   Paragraph.
52598 *
52599 *   [example-1]: http://example.com/one/
52600 *
52601 *   <!-- Comments are fine between and after definitions -->
52602 *
52603 *   [example-2]: http://example.com/two/
52604 */
52605
52606const remarkLintFinalDefinition = lintRule$j(
52607  'remark-lint:final-definition',
52608  /** @type {import('unified-lint-rule').Rule<Root, void>} */
52609  (tree, file) => {
52610    let last = 0;
52611
52612    visit(
52613      tree,
52614      (node) => {
52615        // Ignore generated and HTML comment nodes.
52616        if (
52617          node.type === 'root' ||
52618          generated(node) ||
52619          (node.type === 'html' && /^\s*<!--/.test(node.value))
52620        ) {
52621          return
52622        }
52623
52624        const line = pointStart(node).line;
52625
52626        if (node.type === 'definition') {
52627          if (last && last > line) {
52628            file.message(
52629              'Move definitions to the end of the file (after the node at line `' +
52630                last +
52631                '`)',
52632              node
52633            );
52634          }
52635        } else if (last === 0) {
52636          last = line;
52637        }
52638      },
52639      true
52640    );
52641  }
52642);
52643
52644var remarkLintFinalDefinition$1 = remarkLintFinalDefinition;
52645
52646/**
52647 * @typedef {import('unist').Node} Node
52648 * @typedef {import('vfile').VFile} VFile
52649 *
52650 * @typedef {0|1|2} Severity
52651 * @typedef {'warn'|'on'|'off'|'error'} Label
52652 * @typedef {[Severity, ...unknown[]]} SeverityTuple
52653 *
52654 * @callback Rule
52655 * @param {Node} tree
52656 * @param {VFile} file
52657 * @param {unknown} options
52658 * @returns {void}
52659 */
52660
52661const primitives$i = new Set(['string', 'number', 'boolean']);
52662
52663/**
52664 * @param {string} id
52665 * @param {Rule} rule
52666 */
52667function lintRule$i(id, rule) {
52668  const parts = id.split(':');
52669  // Possibly useful if externalised later.
52670  /* c8 ignore next */
52671  const source = parts[1] ? parts[0] : undefined;
52672  const ruleId = parts[1];
52673
52674  Object.defineProperty(plugin, 'name', {value: id});
52675
52676  return plugin
52677
52678  /** @type {import('unified').Plugin<[unknown]|void[]>} */
52679  function plugin(raw) {
52680    const [severity, options] = coerce$j(ruleId, raw);
52681
52682    if (!severity) return
52683
52684    const fatal = severity === 2;
52685
52686    return (tree, file, next) => {
52687      let index = file.messages.length - 1;
52688
52689      wrap(rule, (error) => {
52690        const messages = file.messages;
52691
52692        // Add the error, if not already properly added.
52693        // Only happens for incorrect plugins.
52694        /* c8 ignore next 6 */
52695        // @ts-expect-error: errors could be `messages`.
52696        if (error && !messages.includes(error)) {
52697          try {
52698            file.fail(error);
52699          } catch {}
52700        }
52701
52702        while (++index < messages.length) {
52703          Object.assign(messages[index], {ruleId, source, fatal});
52704        }
52705
52706        next();
52707      })(tree, file, options);
52708    }
52709  }
52710}
52711
52712/**
52713 * Coerce a value to a severity--options tuple.
52714 *
52715 * @param {string} name
52716 * @param {unknown} value
52717 * @returns {SeverityTuple}
52718 */
52719function coerce$j(name, value) {
52720  /** @type {unknown[]} */
52721  let result;
52722
52723  if (typeof value === 'boolean') {
52724    result = [value];
52725  } else if (value === null || value === undefined) {
52726    result = [1];
52727  } else if (
52728    Array.isArray(value) &&
52729    // `isArray(unknown)` is turned into `any[]`:
52730    // type-coverage:ignore-next-line
52731    primitives$i.has(typeof value[0])
52732  ) {
52733    // `isArray(unknown)` is turned into `any[]`:
52734    // type-coverage:ignore-next-line
52735    result = [...value];
52736  } else {
52737    result = [1, value];
52738  }
52739
52740  let level = result[0];
52741
52742  if (typeof level === 'boolean') {
52743    level = level ? 1 : 0;
52744  } else if (typeof level === 'string') {
52745    if (level === 'off') {
52746      level = 0;
52747    } else if (level === 'on' || level === 'warn') {
52748      level = 1;
52749    } else if (level === 'error') {
52750      level = 2;
52751    } else {
52752      level = 1;
52753      result = [level, result];
52754    }
52755  }
52756
52757  if (typeof level !== 'number' || level < 0 || level > 2) {
52758    throw new Error(
52759      'Incorrect severity `' +
52760        level +
52761        '` for `' +
52762        name +
52763        '`, ' +
52764        'expected 0, 1, or 2'
52765    )
52766  }
52767
52768  result[0] = level;
52769
52770  // @ts-expect-error: it’s now a valid tuple.
52771  return result
52772}
52773
52774/**
52775 * @author Titus Wormer
52776 * @copyright 2015 Titus Wormer
52777 * @license MIT
52778 * @module first-heading-level
52779 * @fileoverview
52780 *   Warn when the first heading has a level other than a specified value.
52781 *
52782 *   Options: `number`, default: `1`.
52783 *
52784 * @example
52785 *   {"name": "ok.md"}
52786 *
52787 *   # The default is to expect a level one heading
52788 *
52789 * @example
52790 *   {"name": "ok-html.md"}
52791 *
52792 *   <h1>An HTML heading is also seen by this rule.</h1>
52793 *
52794 * @example
52795 *   {"name": "ok-delayed.md"}
52796 *
52797 *   You can use markdown content before the heading.
52798 *
52799 *   <div>Or non-heading HTML</div>
52800 *
52801 *   <h1>So the first heading, be it HTML or markdown, is checked</h1>
52802 *
52803 * @example
52804 *   {"name": "not-ok.md", "label": "input"}
52805 *
52806 *   ## Bravo
52807 *
52808 *   Paragraph.
52809 *
52810 * @example
52811 *   {"name": "not-ok.md", "label": "output"}
52812 *
52813 *   1:1-1:9: First heading level should be `1`
52814 *
52815 * @example
52816 *   {"name": "not-ok-html.md", "label": "input"}
52817 *
52818 *   <h2>Charlie</h2>
52819 *
52820 *   Paragraph.
52821 *
52822 * @example
52823 *   {"name": "not-ok-html.md", "label": "output"}
52824 *
52825 *   1:1-1:17: First heading level should be `1`
52826 *
52827 * @example
52828 *   {"name": "ok.md", "setting": 2}
52829 *
52830 *   ## Delta
52831 *
52832 *   Paragraph.
52833 *
52834 * @example
52835 *   {"name": "ok-html.md", "setting": 2}
52836 *
52837 *   <h2>Echo</h2>
52838 *
52839 *   Paragraph.
52840 *
52841 * @example
52842 *   {"name": "not-ok.md", "setting": 2, "label": "input"}
52843 *
52844 *   # Foxtrot
52845 *
52846 *   Paragraph.
52847 *
52848 * @example
52849 *   {"name": "not-ok.md", "setting": 2, "label": "output"}
52850 *
52851 *   1:1-1:10: First heading level should be `2`
52852 *
52853 * @example
52854 *   {"name": "not-ok-html.md", "setting": 2, "label": "input"}
52855 *
52856 *   <h1>Golf</h1>
52857 *
52858 *   Paragraph.
52859 *
52860 * @example
52861 *   {"name": "not-ok-html.md", "setting": 2, "label": "output"}
52862 *
52863 *   1:1-1:14: First heading level should be `2`
52864 */
52865
52866const re = /<h([1-6])/;
52867
52868const remarkLintFirstHeadingLevel = lintRule$i(
52869  'remark-lint:first-heading-level',
52870  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
52871  (tree, file, option = 1) => {
52872    visit(tree, (node) => {
52873      if (!generated(node)) {
52874        /** @type {Depth|undefined} */
52875        let rank;
52876
52877        if (node.type === 'heading') {
52878          rank = node.depth;
52879        } else if (node.type === 'html') {
52880          rank = infer(node);
52881        }
52882
52883        if (rank !== undefined) {
52884          if (rank !== option) {
52885            file.message('First heading level should be `' + option + '`', node);
52886          }
52887
52888          return EXIT$1
52889        }
52890      }
52891    });
52892  }
52893);
52894
52895var remarkLintFirstHeadingLevel$1 = remarkLintFirstHeadingLevel;
52896
52897/**
52898 * @param {HTML} node
52899 * @returns {Depth|undefined}
52900 */
52901function infer(node) {
52902  const results = node.value.match(re);
52903  // @ts-expect-error: can be castes fine.
52904  return results ? Number(results[1]) : undefined
52905}
52906
52907/**
52908 * @typedef {import('unist').Node} Node
52909 * @typedef {import('vfile').VFile} VFile
52910 *
52911 * @typedef {0|1|2} Severity
52912 * @typedef {'warn'|'on'|'off'|'error'} Label
52913 * @typedef {[Severity, ...unknown[]]} SeverityTuple
52914 *
52915 * @callback Rule
52916 * @param {Node} tree
52917 * @param {VFile} file
52918 * @param {unknown} options
52919 * @returns {void}
52920 */
52921
52922const primitives$h = new Set(['string', 'number', 'boolean']);
52923
52924/**
52925 * @param {string} id
52926 * @param {Rule} rule
52927 */
52928function lintRule$h(id, rule) {
52929  const parts = id.split(':');
52930  // Possibly useful if externalised later.
52931  /* c8 ignore next */
52932  const source = parts[1] ? parts[0] : undefined;
52933  const ruleId = parts[1];
52934
52935  Object.defineProperty(plugin, 'name', {value: id});
52936
52937  return plugin
52938
52939  /** @type {import('unified').Plugin<[unknown]|void[]>} */
52940  function plugin(raw) {
52941    const [severity, options] = coerce$i(ruleId, raw);
52942
52943    if (!severity) return
52944
52945    const fatal = severity === 2;
52946
52947    return (tree, file, next) => {
52948      let index = file.messages.length - 1;
52949
52950      wrap(rule, (error) => {
52951        const messages = file.messages;
52952
52953        // Add the error, if not already properly added.
52954        // Only happens for incorrect plugins.
52955        /* c8 ignore next 6 */
52956        // @ts-expect-error: errors could be `messages`.
52957        if (error && !messages.includes(error)) {
52958          try {
52959            file.fail(error);
52960          } catch {}
52961        }
52962
52963        while (++index < messages.length) {
52964          Object.assign(messages[index], {ruleId, source, fatal});
52965        }
52966
52967        next();
52968      })(tree, file, options);
52969    }
52970  }
52971}
52972
52973/**
52974 * Coerce a value to a severity--options tuple.
52975 *
52976 * @param {string} name
52977 * @param {unknown} value
52978 * @returns {SeverityTuple}
52979 */
52980function coerce$i(name, value) {
52981  /** @type {unknown[]} */
52982  let result;
52983
52984  if (typeof value === 'boolean') {
52985    result = [value];
52986  } else if (value === null || value === undefined) {
52987    result = [1];
52988  } else if (
52989    Array.isArray(value) &&
52990    // `isArray(unknown)` is turned into `any[]`:
52991    // type-coverage:ignore-next-line
52992    primitives$h.has(typeof value[0])
52993  ) {
52994    // `isArray(unknown)` is turned into `any[]`:
52995    // type-coverage:ignore-next-line
52996    result = [...value];
52997  } else {
52998    result = [1, value];
52999  }
53000
53001  let level = result[0];
53002
53003  if (typeof level === 'boolean') {
53004    level = level ? 1 : 0;
53005  } else if (typeof level === 'string') {
53006    if (level === 'off') {
53007      level = 0;
53008    } else if (level === 'on' || level === 'warn') {
53009      level = 1;
53010    } else if (level === 'error') {
53011      level = 2;
53012    } else {
53013      level = 1;
53014      result = [level, result];
53015    }
53016  }
53017
53018  if (typeof level !== 'number' || level < 0 || level > 2) {
53019    throw new Error(
53020      'Incorrect severity `' +
53021        level +
53022        '` for `' +
53023        name +
53024        '`, ' +
53025        'expected 0, 1, or 2'
53026    )
53027  }
53028
53029  result[0] = level;
53030
53031  // @ts-expect-error: it’s now a valid tuple.
53032  return result
53033}
53034
53035/**
53036 * @author Titus Wormer
53037 * @copyright 2015 Titus Wormer
53038 * @license MIT
53039 * @module heading-style
53040 * @fileoverview
53041 *   Warn when a heading does not conform to a given style.
53042 *
53043 *   Options: `'consistent'`, `'atx'`, `'atx-closed'`, or `'setext'`,
53044 *   default: `'consistent'`.
53045 *
53046 *   `'consistent'` detects the first used heading style and warns when
53047 *   subsequent headings use different styles.
53048 *
53049 *   ## Fix
53050 *
53051 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
53052 *   formats headings as ATX by default.
53053 *   This can be configured with the
53054 *   [`setext`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionssetext)
53055 *   and
53056 *   [`closeAtx`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionscloseatx)
53057 *   options.
53058 *
53059 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
53060 *   on how to automatically fix warnings for this rule.
53061 *
53062 * @example
53063 *   {"name": "ok.md", "setting": "atx"}
53064 *
53065 *   # Alpha
53066 *
53067 *   ## Bravo
53068 *
53069 *   ### Charlie
53070 *
53071 * @example
53072 *   {"name": "ok.md", "setting": "atx-closed"}
53073 *
53074 *   # Delta ##
53075 *
53076 *   ## Echo ##
53077 *
53078 *   ### Foxtrot ###
53079 *
53080 * @example
53081 *   {"name": "ok.md", "setting": "setext"}
53082 *
53083 *   Golf
53084 *   ====
53085 *
53086 *   Hotel
53087 *   -----
53088 *
53089 *   ### India
53090 *
53091 * @example
53092 *   {"name": "not-ok.md", "label": "input"}
53093 *
53094 *   Juliett
53095 *   =======
53096 *
53097 *   ## Kilo
53098 *
53099 *   ### Lima ###
53100 *
53101 * @example
53102 *   {"name": "not-ok.md", "label": "output"}
53103 *
53104 *   4:1-4:8: Headings should use setext
53105 *   6:1-6:13: Headings should use setext
53106 *
53107 * @example
53108 *   {"name": "not-ok.md", "setting": "��", "label": "output", "positionless": true}
53109 *
53110 *   1:1: Incorrect heading style type `��`: use either `'consistent'`, `'atx'`, `'atx-closed'`, or `'setext'`
53111 */
53112
53113const remarkLintHeadingStyle = lintRule$h(
53114  'remark-lint:heading-style',
53115  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
53116  (tree, file, option = 'consistent') => {
53117    if (
53118      option !== 'consistent' &&
53119      option !== 'atx' &&
53120      option !== 'atx-closed' &&
53121      option !== 'setext'
53122    ) {
53123      file.fail(
53124        'Incorrect heading style type `' +
53125          option +
53126          "`: use either `'consistent'`, `'atx'`, `'atx-closed'`, or `'setext'`"
53127      );
53128    }
53129
53130    visit(tree, 'heading', (node) => {
53131      if (!generated(node)) {
53132        if (option === 'consistent') {
53133          // Funky nodes perhaps cannot be detected.
53134          /* c8 ignore next */
53135          option = headingStyle(node) || 'consistent';
53136        } else if (headingStyle(node, option) !== option) {
53137          file.message('Headings should use ' + option, node);
53138        }
53139      }
53140    });
53141  }
53142);
53143
53144var remarkLintHeadingStyle$1 = remarkLintHeadingStyle;
53145
53146/**
53147 * @typedef {import('unist').Node} Node
53148 * @typedef {import('vfile').VFile} VFile
53149 *
53150 * @typedef {0|1|2} Severity
53151 * @typedef {'warn'|'on'|'off'|'error'} Label
53152 * @typedef {[Severity, ...unknown[]]} SeverityTuple
53153 *
53154 * @callback Rule
53155 * @param {Node} tree
53156 * @param {VFile} file
53157 * @param {unknown} options
53158 * @returns {void}
53159 */
53160
53161const primitives$g = new Set(['string', 'number', 'boolean']);
53162
53163/**
53164 * @param {string} id
53165 * @param {Rule} rule
53166 */
53167function lintRule$g(id, rule) {
53168  const parts = id.split(':');
53169  // Possibly useful if externalised later.
53170  /* c8 ignore next */
53171  const source = parts[1] ? parts[0] : undefined;
53172  const ruleId = parts[1];
53173
53174  Object.defineProperty(plugin, 'name', {value: id});
53175
53176  return plugin
53177
53178  /** @type {import('unified').Plugin<[unknown]|void[]>} */
53179  function plugin(raw) {
53180    const [severity, options] = coerce$h(ruleId, raw);
53181
53182    if (!severity) return
53183
53184    const fatal = severity === 2;
53185
53186    return (tree, file, next) => {
53187      let index = file.messages.length - 1;
53188
53189      wrap(rule, (error) => {
53190        const messages = file.messages;
53191
53192        // Add the error, if not already properly added.
53193        // Only happens for incorrect plugins.
53194        /* c8 ignore next 6 */
53195        // @ts-expect-error: errors could be `messages`.
53196        if (error && !messages.includes(error)) {
53197          try {
53198            file.fail(error);
53199          } catch {}
53200        }
53201
53202        while (++index < messages.length) {
53203          Object.assign(messages[index], {ruleId, source, fatal});
53204        }
53205
53206        next();
53207      })(tree, file, options);
53208    }
53209  }
53210}
53211
53212/**
53213 * Coerce a value to a severity--options tuple.
53214 *
53215 * @param {string} name
53216 * @param {unknown} value
53217 * @returns {SeverityTuple}
53218 */
53219function coerce$h(name, value) {
53220  /** @type {unknown[]} */
53221  let result;
53222
53223  if (typeof value === 'boolean') {
53224    result = [value];
53225  } else if (value === null || value === undefined) {
53226    result = [1];
53227  } else if (
53228    Array.isArray(value) &&
53229    // `isArray(unknown)` is turned into `any[]`:
53230    // type-coverage:ignore-next-line
53231    primitives$g.has(typeof value[0])
53232  ) {
53233    // `isArray(unknown)` is turned into `any[]`:
53234    // type-coverage:ignore-next-line
53235    result = [...value];
53236  } else {
53237    result = [1, value];
53238  }
53239
53240  let level = result[0];
53241
53242  if (typeof level === 'boolean') {
53243    level = level ? 1 : 0;
53244  } else if (typeof level === 'string') {
53245    if (level === 'off') {
53246      level = 0;
53247    } else if (level === 'on' || level === 'warn') {
53248      level = 1;
53249    } else if (level === 'error') {
53250      level = 2;
53251    } else {
53252      level = 1;
53253      result = [level, result];
53254    }
53255  }
53256
53257  if (typeof level !== 'number' || level < 0 || level > 2) {
53258    throw new Error(
53259      'Incorrect severity `' +
53260        level +
53261        '` for `' +
53262        name +
53263        '`, ' +
53264        'expected 0, 1, or 2'
53265    )
53266  }
53267
53268  result[0] = level;
53269
53270  // @ts-expect-error: it’s now a valid tuple.
53271  return result
53272}
53273
53274/**
53275 * @author Titus Wormer
53276 * @copyright 2015 Titus Wormer
53277 * @license MIT
53278 * @module maximum-line-length
53279 * @fileoverview
53280 *   Warn when lines are too long.
53281 *
53282 *   Options: `number`, default: `80`.
53283 *
53284 *   Ignores nodes that cannot be wrapped, such as headings, tables, code,
53285 *   definitions, HTML, and JSX.
53286 *
53287 *   Ignores images, links, and inline code if they start before the wrap, end
53288 *   after the wrap, and there’s no whitespace after them.
53289 *
53290 * @example
53291 *   {"name": "ok.md", "positionless": true, "gfm": true}
53292 *
53293 *   This line is simply not toooooooooooooooooooooooooooooooooooooooooooo
53294 *   long.
53295 *
53296 *   This is also fine: <http://this-long-url-with-a-long-domain.co.uk/a-long-path?query=variables>
53297 *
53298 *   <http://this-link-is-fine.com>
53299 *
53300 *   `alphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJuliettKiloLimaMikeNovemberOscarPapaQuebec.romeo()`
53301 *
53302 *   [foo](http://this-long-url-with-a-long-domain-is-ok.co.uk/a-long-path?query=variables)
53303 *
53304 *   <http://this-long-url-with-a-long-domain-is-ok.co.uk/a-long-path?query=variables>
53305 *
53306 *   ![foo](http://this-long-url-with-a-long-domain-is-ok.co.uk/a-long-path?query=variables)
53307 *
53308 *   | An | exception | is | line | length | in | long | tables | because | those | can’t | just |
53309 *   | -- | --------- | -- | ---- | ------ | -- | ---- | ------ | ------- | ----- | ----- | ---- |
53310 *   | be | helped    |    |      |        |    |      |        |         |       |       | .    |
53311 *
53312 *   <a><b><i><p><q><s><u>alpha bravo charlie delta echo foxtrot golf</u></s></q></p></i></b></a>
53313 *
53314 *   The following is also fine, because there is no whitespace.
53315 *
53316 *   <http://this-long-url-with-a-long-domain-is-ok.co.uk/a-long-path?query=variables>.
53317 *
53318 *   In addition, definitions are also fine:
53319 *
53320 *   [foo]: <http://this-long-url-with-a-long-domain-is-ok.co.uk/a-long-path?query=variables>
53321 *
53322 * @example
53323 *   {"name": "not-ok.md", "setting": 80, "label": "input", "positionless": true}
53324 *
53325 *   This line is simply not tooooooooooooooooooooooooooooooooooooooooooooooooooooooo
53326 *   long.
53327 *
53328 *   Just like thiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiis one.
53329 *
53330 *   And this one is also very wrong: because the link starts aaaaaaafter the column: <http://line.com>
53331 *
53332 *   <http://this-long-url-with-a-long-domain-is-not-ok.co.uk/a-long-path?query=variables> and such.
53333 *
53334 *   And this one is also very wrong: because the code starts aaaaaaafter the column: `alpha.bravo()`
53335 *
53336 *   `alphaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJuliettKiloLimaMikeNovemberOscar.papa()` and such.
53337 *
53338 * @example
53339 *   {"name": "not-ok.md", "setting": 80, "label": "output", "positionless": true}
53340 *
53341 *   4:86: Line must be at most 80 characters
53342 *   6:99: Line must be at most 80 characters
53343 *   8:96: Line must be at most 80 characters
53344 *   10:97: Line must be at most 80 characters
53345 *   12:99: Line must be at most 80 characters
53346 *
53347 * @example
53348 *   {"name": "ok-mixed-line-endings.md", "setting": 10, "positionless": true}
53349 *
53350 *   0123456789␍␊
53351 *   0123456789␊
53352 *   01234␍␊
53353 *   01234␊
53354 *
53355 * @example
53356 *   {"name": "not-ok-mixed-line-endings.md", "setting": 10, "label": "input", "positionless": true}
53357 *
53358 *   012345678901␍␊
53359 *   012345678901␊
53360 *   01234567890␍␊
53361 *   01234567890␊
53362 *
53363 * @example
53364 *   {"name": "not-ok-mixed-line-endings.md", "setting": 10, "label": "output", "positionless": true}
53365 *
53366 *   1:13: Line must be at most 10 characters
53367 *   2:13: Line must be at most 10 characters
53368 *   3:12: Line must be at most 10 characters
53369 *   4:12: Line must be at most 10 characters
53370 */
53371
53372const remarkLintMaximumLineLength = lintRule$g(
53373  'remark-lint:maximum-line-length',
53374  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
53375  (tree, file, option = 80) => {
53376    const value = String(file);
53377    const lines = value.split(/\r?\n/);
53378
53379    visit(tree, (node) => {
53380      if (
53381        (node.type === 'heading' ||
53382          node.type === 'table' ||
53383          node.type === 'code' ||
53384          node.type === 'definition' ||
53385          node.type === 'html' ||
53386          // @ts-expect-error: JSX is from MDX: <https://github.com/mdx-js/specification>.
53387          node.type === 'jsx' ||
53388          node.type === 'yaml' ||
53389          // @ts-expect-error: TOML is from frontmatter.
53390          node.type === 'toml') &&
53391        !generated(node)
53392      ) {
53393        allowList(pointStart(node).line - 1, pointEnd(node).line);
53394      }
53395    });
53396
53397    // Finally, allow some inline spans, but only if they occur at or after
53398    // the wrap.
53399    // However, when they do, and there’s whitespace after it, they are not
53400    // allowed.
53401    visit(tree, (node, pos, parent_) => {
53402      const parent = /** @type {Parent} */ (parent_);
53403
53404      if (
53405        (node.type === 'link' ||
53406          node.type === 'image' ||
53407          node.type === 'inlineCode') &&
53408        !generated(node) &&
53409        parent &&
53410        typeof pos === 'number'
53411      ) {
53412        const initial = pointStart(node);
53413        const final = pointEnd(node);
53414
53415        // Not allowing when starting after the border, or ending before it.
53416        if (initial.column > option || final.column < option) {
53417          return
53418        }
53419
53420        const next = parent.children[pos + 1];
53421
53422        // Not allowing when there’s whitespace after the link.
53423        if (
53424          next &&
53425          pointStart(next).line === initial.line &&
53426          (!('value' in next) || /^(.+?[ \t].+?)/.test(next.value))
53427        ) {
53428          return
53429        }
53430
53431        allowList(initial.line - 1, final.line);
53432      }
53433    });
53434
53435    // Iterate over every line, and warn for violating lines.
53436    let index = -1;
53437
53438    while (++index < lines.length) {
53439      const lineLength = lines[index].length;
53440
53441      if (lineLength > option) {
53442        file.message('Line must be at most ' + option + ' characters', {
53443          line: index + 1,
53444          column: lineLength + 1
53445        });
53446      }
53447    }
53448
53449    /**
53450     * Allowlist from `initial` to `final`, zero-based.
53451     *
53452     * @param {number} initial
53453     * @param {number} final
53454     */
53455    function allowList(initial, final) {
53456      while (initial < final) {
53457        lines[initial++] = '';
53458      }
53459    }
53460  }
53461);
53462
53463var remarkLintMaximumLineLength$1 = remarkLintMaximumLineLength;
53464
53465/**
53466 * @typedef {import('unist').Node} Node
53467 * @typedef {import('vfile').VFile} VFile
53468 *
53469 * @typedef {0|1|2} Severity
53470 * @typedef {'warn'|'on'|'off'|'error'} Label
53471 * @typedef {[Severity, ...unknown[]]} SeverityTuple
53472 *
53473 * @callback Rule
53474 * @param {Node} tree
53475 * @param {VFile} file
53476 * @param {unknown} options
53477 * @returns {void}
53478 */
53479
53480const primitives$f = new Set(['string', 'number', 'boolean']);
53481
53482/**
53483 * @param {string} id
53484 * @param {Rule} rule
53485 */
53486function lintRule$f(id, rule) {
53487  const parts = id.split(':');
53488  // Possibly useful if externalised later.
53489  /* c8 ignore next */
53490  const source = parts[1] ? parts[0] : undefined;
53491  const ruleId = parts[1];
53492
53493  Object.defineProperty(plugin, 'name', {value: id});
53494
53495  return plugin
53496
53497  /** @type {import('unified').Plugin<[unknown]|void[]>} */
53498  function plugin(raw) {
53499    const [severity, options] = coerce$g(ruleId, raw);
53500
53501    if (!severity) return
53502
53503    const fatal = severity === 2;
53504
53505    return (tree, file, next) => {
53506      let index = file.messages.length - 1;
53507
53508      wrap(rule, (error) => {
53509        const messages = file.messages;
53510
53511        // Add the error, if not already properly added.
53512        // Only happens for incorrect plugins.
53513        /* c8 ignore next 6 */
53514        // @ts-expect-error: errors could be `messages`.
53515        if (error && !messages.includes(error)) {
53516          try {
53517            file.fail(error);
53518          } catch {}
53519        }
53520
53521        while (++index < messages.length) {
53522          Object.assign(messages[index], {ruleId, source, fatal});
53523        }
53524
53525        next();
53526      })(tree, file, options);
53527    }
53528  }
53529}
53530
53531/**
53532 * Coerce a value to a severity--options tuple.
53533 *
53534 * @param {string} name
53535 * @param {unknown} value
53536 * @returns {SeverityTuple}
53537 */
53538function coerce$g(name, value) {
53539  /** @type {unknown[]} */
53540  let result;
53541
53542  if (typeof value === 'boolean') {
53543    result = [value];
53544  } else if (value === null || value === undefined) {
53545    result = [1];
53546  } else if (
53547    Array.isArray(value) &&
53548    // `isArray(unknown)` is turned into `any[]`:
53549    // type-coverage:ignore-next-line
53550    primitives$f.has(typeof value[0])
53551  ) {
53552    // `isArray(unknown)` is turned into `any[]`:
53553    // type-coverage:ignore-next-line
53554    result = [...value];
53555  } else {
53556    result = [1, value];
53557  }
53558
53559  let level = result[0];
53560
53561  if (typeof level === 'boolean') {
53562    level = level ? 1 : 0;
53563  } else if (typeof level === 'string') {
53564    if (level === 'off') {
53565      level = 0;
53566    } else if (level === 'on' || level === 'warn') {
53567      level = 1;
53568    } else if (level === 'error') {
53569      level = 2;
53570    } else {
53571      level = 1;
53572      result = [level, result];
53573    }
53574  }
53575
53576  if (typeof level !== 'number' || level < 0 || level > 2) {
53577    throw new Error(
53578      'Incorrect severity `' +
53579        level +
53580        '` for `' +
53581        name +
53582        '`, ' +
53583        'expected 0, 1, or 2'
53584    )
53585  }
53586
53587  result[0] = level;
53588
53589  // @ts-expect-error: it’s now a valid tuple.
53590  return result
53591}
53592
53593/**
53594 * @author Titus Wormer
53595 * @copyright 2015 Titus Wormer
53596 * @license MIT
53597 * @module no-consecutive-blank-lines
53598 * @fileoverview
53599 *   Warn for too many consecutive blank lines.
53600 *   Knows about the extra line needed between a list and indented code, and two
53601 *   lists.
53602 *
53603 *   ## Fix
53604 *
53605 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
53606 *   always uses one blank line between blocks if possible, or two lines when
53607 *   needed.
53608 *
53609 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
53610 *   on how to automatically fix warnings for this rule.
53611 *
53612 * @example
53613 *   {"name": "ok.md"}
53614 *
53615 *   Foo…
53616 *   ␊
53617 *   …Bar.
53618 *
53619 * @example
53620 *   {"name": "empty-document.md"}
53621 *
53622 * @example
53623 *   {"name": "not-ok.md", "label": "input"}
53624 *
53625 *   Foo…
53626 *   ␊
53627 *   ␊
53628 *   …Bar
53629 *   ␊
53630 *   ␊
53631 *
53632 * @example
53633 *   {"name": "not-ok.md", "label": "output"}
53634 *
53635 *   4:1: Remove 1 line before node
53636 *   4:5: Remove 2 lines after node
53637 */
53638
53639const remarkLintNoConsecutiveBlankLines = lintRule$f(
53640  'remark-lint:no-consecutive-blank-lines',
53641  /** @type {import('unified-lint-rule').Rule<Root, void>} */
53642  (tree, file) => {
53643    visit(tree, (node) => {
53644      if (!generated(node) && 'children' in node) {
53645        const head = node.children[0];
53646
53647        if (head && !generated(head)) {
53648          // Compare parent and first child.
53649          compare(pointStart(node), pointStart(head), 0);
53650
53651          // Compare between each child.
53652          let index = -1;
53653
53654          while (++index < node.children.length) {
53655            const previous = node.children[index - 1];
53656            const child = node.children[index];
53657
53658            if (previous && !generated(previous) && !generated(child)) {
53659              compare(pointEnd(previous), pointStart(child), 2);
53660            }
53661          }
53662
53663          const tail = node.children[node.children.length - 1];
53664
53665          // Compare parent and last child.
53666          if (tail !== head && !generated(tail)) {
53667            compare(pointEnd(node), pointEnd(tail), 1);
53668          }
53669        }
53670      }
53671    });
53672
53673    /**
53674     * Compare the difference between `start` and `end`, and warn when that
53675     * difference exceeds `max`.
53676     *
53677     * @param {Point} start
53678     * @param {Point} end
53679     * @param {0|1|2} max
53680     */
53681    function compare(start, end, max) {
53682      const diff = end.line - start.line;
53683      const lines = Math.abs(diff) - max;
53684
53685      if (lines > 0) {
53686        file.message(
53687          'Remove ' +
53688            lines +
53689            ' ' +
53690            plural('line', Math.abs(lines)) +
53691            ' ' +
53692            (diff > 0 ? 'before' : 'after') +
53693            ' node',
53694          end
53695        );
53696      }
53697    }
53698  }
53699);
53700
53701var remarkLintNoConsecutiveBlankLines$1 = remarkLintNoConsecutiveBlankLines;
53702
53703/**
53704 * @typedef {import('unist').Node} Node
53705 * @typedef {import('vfile').VFile} VFile
53706 *
53707 * @typedef {0|1|2} Severity
53708 * @typedef {'warn'|'on'|'off'|'error'} Label
53709 * @typedef {[Severity, ...unknown[]]} SeverityTuple
53710 *
53711 * @callback Rule
53712 * @param {Node} tree
53713 * @param {VFile} file
53714 * @param {unknown} options
53715 * @returns {void}
53716 */
53717
53718const primitives$e = new Set(['string', 'number', 'boolean']);
53719
53720/**
53721 * @param {string} id
53722 * @param {Rule} rule
53723 */
53724function lintRule$e(id, rule) {
53725  const parts = id.split(':');
53726  // Possibly useful if externalised later.
53727  /* c8 ignore next */
53728  const source = parts[1] ? parts[0] : undefined;
53729  const ruleId = parts[1];
53730
53731  Object.defineProperty(plugin, 'name', {value: id});
53732
53733  return plugin
53734
53735  /** @type {import('unified').Plugin<[unknown]|void[]>} */
53736  function plugin(raw) {
53737    const [severity, options] = coerce$f(ruleId, raw);
53738
53739    if (!severity) return
53740
53741    const fatal = severity === 2;
53742
53743    return (tree, file, next) => {
53744      let index = file.messages.length - 1;
53745
53746      wrap(rule, (error) => {
53747        const messages = file.messages;
53748
53749        // Add the error, if not already properly added.
53750        // Only happens for incorrect plugins.
53751        /* c8 ignore next 6 */
53752        // @ts-expect-error: errors could be `messages`.
53753        if (error && !messages.includes(error)) {
53754          try {
53755            file.fail(error);
53756          } catch {}
53757        }
53758
53759        while (++index < messages.length) {
53760          Object.assign(messages[index], {ruleId, source, fatal});
53761        }
53762
53763        next();
53764      })(tree, file, options);
53765    }
53766  }
53767}
53768
53769/**
53770 * Coerce a value to a severity--options tuple.
53771 *
53772 * @param {string} name
53773 * @param {unknown} value
53774 * @returns {SeverityTuple}
53775 */
53776function coerce$f(name, value) {
53777  /** @type {unknown[]} */
53778  let result;
53779
53780  if (typeof value === 'boolean') {
53781    result = [value];
53782  } else if (value === null || value === undefined) {
53783    result = [1];
53784  } else if (
53785    Array.isArray(value) &&
53786    // `isArray(unknown)` is turned into `any[]`:
53787    // type-coverage:ignore-next-line
53788    primitives$e.has(typeof value[0])
53789  ) {
53790    // `isArray(unknown)` is turned into `any[]`:
53791    // type-coverage:ignore-next-line
53792    result = [...value];
53793  } else {
53794    result = [1, value];
53795  }
53796
53797  let level = result[0];
53798
53799  if (typeof level === 'boolean') {
53800    level = level ? 1 : 0;
53801  } else if (typeof level === 'string') {
53802    if (level === 'off') {
53803      level = 0;
53804    } else if (level === 'on' || level === 'warn') {
53805      level = 1;
53806    } else if (level === 'error') {
53807      level = 2;
53808    } else {
53809      level = 1;
53810      result = [level, result];
53811    }
53812  }
53813
53814  if (typeof level !== 'number' || level < 0 || level > 2) {
53815    throw new Error(
53816      'Incorrect severity `' +
53817        level +
53818        '` for `' +
53819        name +
53820        '`, ' +
53821        'expected 0, 1, or 2'
53822    )
53823  }
53824
53825  result[0] = level;
53826
53827  // @ts-expect-error: it’s now a valid tuple.
53828  return result
53829}
53830
53831/**
53832 * @author Titus Wormer
53833 * @copyright 2015 Titus Wormer
53834 * @license MIT
53835 * @module no-file-name-articles
53836 * @fileoverview
53837 *   Warn when file names start with an article.
53838 *
53839 * @example
53840 *   {"name": "title.md"}
53841 *
53842 * @example
53843 *   {"name": "a-title.md", "label": "output", "positionless": true}
53844 *
53845 *   1:1: Do not start file names with `a`
53846 *
53847 * @example
53848 *   {"name": "the-title.md", "label": "output", "positionless": true}
53849 *
53850 *   1:1: Do not start file names with `the`
53851 *
53852 * @example
53853 *   {"name": "teh-title.md", "label": "output", "positionless": true}
53854 *
53855 *   1:1: Do not start file names with `teh`
53856 *
53857 * @example
53858 *   {"name": "an-article.md", "label": "output", "positionless": true}
53859 *
53860 *   1:1: Do not start file names with `an`
53861 */
53862
53863const remarkLintNoFileNameArticles = lintRule$e(
53864  'remark-lint:no-file-name-articles',
53865  /** @type {import('unified-lint-rule').Rule<Root, void>} */
53866  (_, file) => {
53867    const match = file.stem && file.stem.match(/^(the|teh|an?)\b/i);
53868
53869    if (match) {
53870      file.message('Do not start file names with `' + match[0] + '`');
53871    }
53872  }
53873);
53874
53875var remarkLintNoFileNameArticles$1 = remarkLintNoFileNameArticles;
53876
53877/**
53878 * @typedef {import('unist').Node} Node
53879 * @typedef {import('vfile').VFile} VFile
53880 *
53881 * @typedef {0|1|2} Severity
53882 * @typedef {'warn'|'on'|'off'|'error'} Label
53883 * @typedef {[Severity, ...unknown[]]} SeverityTuple
53884 *
53885 * @callback Rule
53886 * @param {Node} tree
53887 * @param {VFile} file
53888 * @param {unknown} options
53889 * @returns {void}
53890 */
53891
53892const primitives$d = new Set(['string', 'number', 'boolean']);
53893
53894/**
53895 * @param {string} id
53896 * @param {Rule} rule
53897 */
53898function lintRule$d(id, rule) {
53899  const parts = id.split(':');
53900  // Possibly useful if externalised later.
53901  /* c8 ignore next */
53902  const source = parts[1] ? parts[0] : undefined;
53903  const ruleId = parts[1];
53904
53905  Object.defineProperty(plugin, 'name', {value: id});
53906
53907  return plugin
53908
53909  /** @type {import('unified').Plugin<[unknown]|void[]>} */
53910  function plugin(raw) {
53911    const [severity, options] = coerce$e(ruleId, raw);
53912
53913    if (!severity) return
53914
53915    const fatal = severity === 2;
53916
53917    return (tree, file, next) => {
53918      let index = file.messages.length - 1;
53919
53920      wrap(rule, (error) => {
53921        const messages = file.messages;
53922
53923        // Add the error, if not already properly added.
53924        // Only happens for incorrect plugins.
53925        /* c8 ignore next 6 */
53926        // @ts-expect-error: errors could be `messages`.
53927        if (error && !messages.includes(error)) {
53928          try {
53929            file.fail(error);
53930          } catch {}
53931        }
53932
53933        while (++index < messages.length) {
53934          Object.assign(messages[index], {ruleId, source, fatal});
53935        }
53936
53937        next();
53938      })(tree, file, options);
53939    }
53940  }
53941}
53942
53943/**
53944 * Coerce a value to a severity--options tuple.
53945 *
53946 * @param {string} name
53947 * @param {unknown} value
53948 * @returns {SeverityTuple}
53949 */
53950function coerce$e(name, value) {
53951  /** @type {unknown[]} */
53952  let result;
53953
53954  if (typeof value === 'boolean') {
53955    result = [value];
53956  } else if (value === null || value === undefined) {
53957    result = [1];
53958  } else if (
53959    Array.isArray(value) &&
53960    // `isArray(unknown)` is turned into `any[]`:
53961    // type-coverage:ignore-next-line
53962    primitives$d.has(typeof value[0])
53963  ) {
53964    // `isArray(unknown)` is turned into `any[]`:
53965    // type-coverage:ignore-next-line
53966    result = [...value];
53967  } else {
53968    result = [1, value];
53969  }
53970
53971  let level = result[0];
53972
53973  if (typeof level === 'boolean') {
53974    level = level ? 1 : 0;
53975  } else if (typeof level === 'string') {
53976    if (level === 'off') {
53977      level = 0;
53978    } else if (level === 'on' || level === 'warn') {
53979      level = 1;
53980    } else if (level === 'error') {
53981      level = 2;
53982    } else {
53983      level = 1;
53984      result = [level, result];
53985    }
53986  }
53987
53988  if (typeof level !== 'number' || level < 0 || level > 2) {
53989    throw new Error(
53990      'Incorrect severity `' +
53991        level +
53992        '` for `' +
53993        name +
53994        '`, ' +
53995        'expected 0, 1, or 2'
53996    )
53997  }
53998
53999  result[0] = level;
54000
54001  // @ts-expect-error: it’s now a valid tuple.
54002  return result
54003}
54004
54005/**
54006 * @author Titus Wormer
54007 * @copyright 2015 Titus Wormer
54008 * @license MIT
54009 * @module no-file-name-consecutive-dashes
54010 * @fileoverview
54011 *   Warn when file names contain consecutive dashes.
54012 *
54013 * @example
54014 *   {"name": "plug-ins.md"}
54015 *
54016 * @example
54017 *   {"name": "plug--ins.md", "label": "output", "positionless": true}
54018 *
54019 *   1:1: Do not use consecutive dashes in a file name
54020 */
54021
54022const remarkLintNoFileNameConsecutiveDashes = lintRule$d(
54023  'remark-lint:no-file-name-consecutive-dashes',
54024  /** @type {import('unified-lint-rule').Rule<Root, void>} */
54025  (_, file) => {
54026    if (file.stem && /-{2,}/.test(file.stem)) {
54027      file.message('Do not use consecutive dashes in a file name');
54028    }
54029  }
54030);
54031
54032var remarkLintNoFileNameConsecutiveDashes$1 = remarkLintNoFileNameConsecutiveDashes;
54033
54034/**
54035 * @typedef {import('unist').Node} Node
54036 * @typedef {import('vfile').VFile} VFile
54037 *
54038 * @typedef {0|1|2} Severity
54039 * @typedef {'warn'|'on'|'off'|'error'} Label
54040 * @typedef {[Severity, ...unknown[]]} SeverityTuple
54041 *
54042 * @callback Rule
54043 * @param {Node} tree
54044 * @param {VFile} file
54045 * @param {unknown} options
54046 * @returns {void}
54047 */
54048
54049const primitives$c = new Set(['string', 'number', 'boolean']);
54050
54051/**
54052 * @param {string} id
54053 * @param {Rule} rule
54054 */
54055function lintRule$c(id, rule) {
54056  const parts = id.split(':');
54057  // Possibly useful if externalised later.
54058  /* c8 ignore next */
54059  const source = parts[1] ? parts[0] : undefined;
54060  const ruleId = parts[1];
54061
54062  Object.defineProperty(plugin, 'name', {value: id});
54063
54064  return plugin
54065
54066  /** @type {import('unified').Plugin<[unknown]|void[]>} */
54067  function plugin(raw) {
54068    const [severity, options] = coerce$d(ruleId, raw);
54069
54070    if (!severity) return
54071
54072    const fatal = severity === 2;
54073
54074    return (tree, file, next) => {
54075      let index = file.messages.length - 1;
54076
54077      wrap(rule, (error) => {
54078        const messages = file.messages;
54079
54080        // Add the error, if not already properly added.
54081        // Only happens for incorrect plugins.
54082        /* c8 ignore next 6 */
54083        // @ts-expect-error: errors could be `messages`.
54084        if (error && !messages.includes(error)) {
54085          try {
54086            file.fail(error);
54087          } catch {}
54088        }
54089
54090        while (++index < messages.length) {
54091          Object.assign(messages[index], {ruleId, source, fatal});
54092        }
54093
54094        next();
54095      })(tree, file, options);
54096    }
54097  }
54098}
54099
54100/**
54101 * Coerce a value to a severity--options tuple.
54102 *
54103 * @param {string} name
54104 * @param {unknown} value
54105 * @returns {SeverityTuple}
54106 */
54107function coerce$d(name, value) {
54108  /** @type {unknown[]} */
54109  let result;
54110
54111  if (typeof value === 'boolean') {
54112    result = [value];
54113  } else if (value === null || value === undefined) {
54114    result = [1];
54115  } else if (
54116    Array.isArray(value) &&
54117    // `isArray(unknown)` is turned into `any[]`:
54118    // type-coverage:ignore-next-line
54119    primitives$c.has(typeof value[0])
54120  ) {
54121    // `isArray(unknown)` is turned into `any[]`:
54122    // type-coverage:ignore-next-line
54123    result = [...value];
54124  } else {
54125    result = [1, value];
54126  }
54127
54128  let level = result[0];
54129
54130  if (typeof level === 'boolean') {
54131    level = level ? 1 : 0;
54132  } else if (typeof level === 'string') {
54133    if (level === 'off') {
54134      level = 0;
54135    } else if (level === 'on' || level === 'warn') {
54136      level = 1;
54137    } else if (level === 'error') {
54138      level = 2;
54139    } else {
54140      level = 1;
54141      result = [level, result];
54142    }
54143  }
54144
54145  if (typeof level !== 'number' || level < 0 || level > 2) {
54146    throw new Error(
54147      'Incorrect severity `' +
54148        level +
54149        '` for `' +
54150        name +
54151        '`, ' +
54152        'expected 0, 1, or 2'
54153    )
54154  }
54155
54156  result[0] = level;
54157
54158  // @ts-expect-error: it’s now a valid tuple.
54159  return result
54160}
54161
54162/**
54163 * @author Titus Wormer
54164 * @copyright 2015 Titus Wormer
54165 * @license MIT
54166 * @module no-file-name-outer-dashes
54167 * @fileoverview
54168 *   Warn when file names contain initial or final dashes (hyphen-minus, `-`).
54169 *
54170 * @example
54171 *   {"name": "readme.md"}
54172 *
54173 * @example
54174 *   {"name": "-readme.md", "label": "output", "positionless": true}
54175 *
54176 *   1:1: Do not use initial or final dashes in a file name
54177 *
54178 * @example
54179 *   {"name": "readme-.md", "label": "output", "positionless": true}
54180 *
54181 *   1:1: Do not use initial or final dashes in a file name
54182 */
54183
54184const remarkLintNofileNameOuterDashes = lintRule$c(
54185  'remark-lint:no-file-name-outer-dashes',
54186  /** @type {import('unified-lint-rule').Rule<Root, void>} */
54187  (_, file) => {
54188    if (file.stem && /^-|-$/.test(file.stem)) {
54189      file.message('Do not use initial or final dashes in a file name');
54190    }
54191  }
54192);
54193
54194var remarkLintNofileNameOuterDashes$1 = remarkLintNofileNameOuterDashes;
54195
54196/**
54197 * @typedef {import('unist').Node} Node
54198 * @typedef {import('vfile').VFile} VFile
54199 *
54200 * @typedef {0|1|2} Severity
54201 * @typedef {'warn'|'on'|'off'|'error'} Label
54202 * @typedef {[Severity, ...unknown[]]} SeverityTuple
54203 *
54204 * @callback Rule
54205 * @param {Node} tree
54206 * @param {VFile} file
54207 * @param {unknown} options
54208 * @returns {void}
54209 */
54210
54211const primitives$b = new Set(['string', 'number', 'boolean']);
54212
54213/**
54214 * @param {string} id
54215 * @param {Rule} rule
54216 */
54217function lintRule$b(id, rule) {
54218  const parts = id.split(':');
54219  // Possibly useful if externalised later.
54220  /* c8 ignore next */
54221  const source = parts[1] ? parts[0] : undefined;
54222  const ruleId = parts[1];
54223
54224  Object.defineProperty(plugin, 'name', {value: id});
54225
54226  return plugin
54227
54228  /** @type {import('unified').Plugin<[unknown]|void[]>} */
54229  function plugin(raw) {
54230    const [severity, options] = coerce$c(ruleId, raw);
54231
54232    if (!severity) return
54233
54234    const fatal = severity === 2;
54235
54236    return (tree, file, next) => {
54237      let index = file.messages.length - 1;
54238
54239      wrap(rule, (error) => {
54240        const messages = file.messages;
54241
54242        // Add the error, if not already properly added.
54243        // Only happens for incorrect plugins.
54244        /* c8 ignore next 6 */
54245        // @ts-expect-error: errors could be `messages`.
54246        if (error && !messages.includes(error)) {
54247          try {
54248            file.fail(error);
54249          } catch {}
54250        }
54251
54252        while (++index < messages.length) {
54253          Object.assign(messages[index], {ruleId, source, fatal});
54254        }
54255
54256        next();
54257      })(tree, file, options);
54258    }
54259  }
54260}
54261
54262/**
54263 * Coerce a value to a severity--options tuple.
54264 *
54265 * @param {string} name
54266 * @param {unknown} value
54267 * @returns {SeverityTuple}
54268 */
54269function coerce$c(name, value) {
54270  /** @type {unknown[]} */
54271  let result;
54272
54273  if (typeof value === 'boolean') {
54274    result = [value];
54275  } else if (value === null || value === undefined) {
54276    result = [1];
54277  } else if (
54278    Array.isArray(value) &&
54279    // `isArray(unknown)` is turned into `any[]`:
54280    // type-coverage:ignore-next-line
54281    primitives$b.has(typeof value[0])
54282  ) {
54283    // `isArray(unknown)` is turned into `any[]`:
54284    // type-coverage:ignore-next-line
54285    result = [...value];
54286  } else {
54287    result = [1, value];
54288  }
54289
54290  let level = result[0];
54291
54292  if (typeof level === 'boolean') {
54293    level = level ? 1 : 0;
54294  } else if (typeof level === 'string') {
54295    if (level === 'off') {
54296      level = 0;
54297    } else if (level === 'on' || level === 'warn') {
54298      level = 1;
54299    } else if (level === 'error') {
54300      level = 2;
54301    } else {
54302      level = 1;
54303      result = [level, result];
54304    }
54305  }
54306
54307  if (typeof level !== 'number' || level < 0 || level > 2) {
54308    throw new Error(
54309      'Incorrect severity `' +
54310        level +
54311        '` for `' +
54312        name +
54313        '`, ' +
54314        'expected 0, 1, or 2'
54315    )
54316  }
54317
54318  result[0] = level;
54319
54320  // @ts-expect-error: it’s now a valid tuple.
54321  return result
54322}
54323
54324/**
54325 * @author Titus Wormer
54326 * @copyright 2015 Titus Wormer
54327 * @license MIT
54328 * @module no-heading-indent
54329 * @fileoverview
54330 *   Warn when a heading is indented.
54331 *
54332 *   ## Fix
54333 *
54334 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
54335 *   removes all unneeded indentation before headings.
54336 *
54337 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
54338 *   on how to automatically fix warnings for this rule.
54339 *
54340 * @example
54341 *   {"name": "ok.md"}
54342 *
54343 *   #·Hello world
54344 *
54345 *   Foo
54346 *   -----
54347 *
54348 *   #·Hello world·#
54349 *
54350 *   Bar
54351 *   =====
54352 *
54353 * @example
54354 *   {"name": "not-ok.md", "label": "input"}
54355 *
54356 *   ···# Hello world
54357 *
54358 *   ·Foo
54359 *   -----
54360 *
54361 *   ·# Hello world #
54362 *
54363 *   ···Bar
54364 *   =====
54365 *
54366 * @example
54367 *   {"name": "not-ok.md", "label": "output"}
54368 *
54369 *   1:4: Remove 3 spaces before this heading
54370 *   3:2: Remove 1 space before this heading
54371 *   6:2: Remove 1 space before this heading
54372 *   8:4: Remove 3 spaces before this heading
54373 */
54374
54375const remarkLintNoHeadingIndent = lintRule$b(
54376  'remark-lint:no-heading-indent',
54377  /** @type {import('unified-lint-rule').Rule<Root, void>} */
54378  (tree, file) => {
54379    visit(tree, 'heading', (node, _, parent) => {
54380      // Note: it’s rather complex to detect what the expected indent is in block
54381      // quotes and lists, so let’s only do directly in root for now.
54382      if (generated(node) || (parent && parent.type !== 'root')) {
54383        return
54384      }
54385
54386      const diff = pointStart(node).column - 1;
54387
54388      if (diff) {
54389        file.message(
54390          'Remove ' +
54391            diff +
54392            ' ' +
54393            plural('space', diff) +
54394            ' before this heading',
54395          pointStart(node)
54396        );
54397      }
54398    });
54399  }
54400);
54401
54402var remarkLintNoHeadingIndent$1 = remarkLintNoHeadingIndent;
54403
54404/**
54405 * @typedef {import('unist').Node} Node
54406 * @typedef {import('vfile').VFile} VFile
54407 *
54408 * @typedef {0|1|2} Severity
54409 * @typedef {'warn'|'on'|'off'|'error'} Label
54410 * @typedef {[Severity, ...unknown[]]} SeverityTuple
54411 *
54412 * @callback Rule
54413 * @param {Node} tree
54414 * @param {VFile} file
54415 * @param {unknown} options
54416 * @returns {void}
54417 */
54418
54419const primitives$a = new Set(['string', 'number', 'boolean']);
54420
54421/**
54422 * @param {string} id
54423 * @param {Rule} rule
54424 */
54425function lintRule$a(id, rule) {
54426  const parts = id.split(':');
54427  // Possibly useful if externalised later.
54428  /* c8 ignore next */
54429  const source = parts[1] ? parts[0] : undefined;
54430  const ruleId = parts[1];
54431
54432  Object.defineProperty(plugin, 'name', {value: id});
54433
54434  return plugin
54435
54436  /** @type {import('unified').Plugin<[unknown]|void[]>} */
54437  function plugin(raw) {
54438    const [severity, options] = coerce$b(ruleId, raw);
54439
54440    if (!severity) return
54441
54442    const fatal = severity === 2;
54443
54444    return (tree, file, next) => {
54445      let index = file.messages.length - 1;
54446
54447      wrap(rule, (error) => {
54448        const messages = file.messages;
54449
54450        // Add the error, if not already properly added.
54451        // Only happens for incorrect plugins.
54452        /* c8 ignore next 6 */
54453        // @ts-expect-error: errors could be `messages`.
54454        if (error && !messages.includes(error)) {
54455          try {
54456            file.fail(error);
54457          } catch {}
54458        }
54459
54460        while (++index < messages.length) {
54461          Object.assign(messages[index], {ruleId, source, fatal});
54462        }
54463
54464        next();
54465      })(tree, file, options);
54466    }
54467  }
54468}
54469
54470/**
54471 * Coerce a value to a severity--options tuple.
54472 *
54473 * @param {string} name
54474 * @param {unknown} value
54475 * @returns {SeverityTuple}
54476 */
54477function coerce$b(name, value) {
54478  /** @type {unknown[]} */
54479  let result;
54480
54481  if (typeof value === 'boolean') {
54482    result = [value];
54483  } else if (value === null || value === undefined) {
54484    result = [1];
54485  } else if (
54486    Array.isArray(value) &&
54487    // `isArray(unknown)` is turned into `any[]`:
54488    // type-coverage:ignore-next-line
54489    primitives$a.has(typeof value[0])
54490  ) {
54491    // `isArray(unknown)` is turned into `any[]`:
54492    // type-coverage:ignore-next-line
54493    result = [...value];
54494  } else {
54495    result = [1, value];
54496  }
54497
54498  let level = result[0];
54499
54500  if (typeof level === 'boolean') {
54501    level = level ? 1 : 0;
54502  } else if (typeof level === 'string') {
54503    if (level === 'off') {
54504      level = 0;
54505    } else if (level === 'on' || level === 'warn') {
54506      level = 1;
54507    } else if (level === 'error') {
54508      level = 2;
54509    } else {
54510      level = 1;
54511      result = [level, result];
54512    }
54513  }
54514
54515  if (typeof level !== 'number' || level < 0 || level > 2) {
54516    throw new Error(
54517      'Incorrect severity `' +
54518        level +
54519        '` for `' +
54520        name +
54521        '`, ' +
54522        'expected 0, 1, or 2'
54523    )
54524  }
54525
54526  result[0] = level;
54527
54528  // @ts-expect-error: it’s now a valid tuple.
54529  return result
54530}
54531
54532/**
54533 * @author Titus Wormer
54534 * @copyright 2015 Titus Wormer
54535 * @license MIT
54536 * @module no-multiple-toplevel-headings
54537 * @fileoverview
54538 *   Warn when multiple top level headings are used.
54539 *
54540 *   Options: `number`, default: `1`.
54541 *
54542 * @example
54543 *   {"name": "ok.md", "setting": 1}
54544 *
54545 *   # Foo
54546 *
54547 *   ## Bar
54548 *
54549 * @example
54550 *   {"name": "not-ok.md", "setting": 1, "label": "input"}
54551 *
54552 *   # Foo
54553 *
54554 *   # Bar
54555 *
54556 * @example
54557 *   {"name": "not-ok.md", "setting": 1, "label": "output"}
54558 *
54559 *   3:1-3:6: Don’t use multiple top level headings (1:1)
54560 */
54561
54562const remarkLintNoMultipleToplevelHeadings = lintRule$a(
54563  'remark-lint:no-multiple-toplevel-headings',
54564  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
54565  (tree, file, option = 1) => {
54566    /** @type {string|undefined} */
54567    let duplicate;
54568
54569    visit(tree, 'heading', (node) => {
54570      if (!generated(node) && node.depth === option) {
54571        if (duplicate) {
54572          file.message(
54573            'Don’t use multiple top level headings (' + duplicate + ')',
54574            node
54575          );
54576        } else {
54577          duplicate = stringifyPosition$1(pointStart(node));
54578        }
54579      }
54580    });
54581  }
54582);
54583
54584var remarkLintNoMultipleToplevelHeadings$1 = remarkLintNoMultipleToplevelHeadings;
54585
54586/**
54587 * @typedef {import('unist').Node} Node
54588 * @typedef {import('vfile').VFile} VFile
54589 *
54590 * @typedef {0|1|2} Severity
54591 * @typedef {'warn'|'on'|'off'|'error'} Label
54592 * @typedef {[Severity, ...unknown[]]} SeverityTuple
54593 *
54594 * @callback Rule
54595 * @param {Node} tree
54596 * @param {VFile} file
54597 * @param {unknown} options
54598 * @returns {void}
54599 */
54600
54601const primitives$9 = new Set(['string', 'number', 'boolean']);
54602
54603/**
54604 * @param {string} id
54605 * @param {Rule} rule
54606 */
54607function lintRule$9(id, rule) {
54608  const parts = id.split(':');
54609  // Possibly useful if externalised later.
54610  /* c8 ignore next */
54611  const source = parts[1] ? parts[0] : undefined;
54612  const ruleId = parts[1];
54613
54614  Object.defineProperty(plugin, 'name', {value: id});
54615
54616  return plugin
54617
54618  /** @type {import('unified').Plugin<[unknown]|void[]>} */
54619  function plugin(raw) {
54620    const [severity, options] = coerce$a(ruleId, raw);
54621
54622    if (!severity) return
54623
54624    const fatal = severity === 2;
54625
54626    return (tree, file, next) => {
54627      let index = file.messages.length - 1;
54628
54629      wrap(rule, (error) => {
54630        const messages = file.messages;
54631
54632        // Add the error, if not already properly added.
54633        // Only happens for incorrect plugins.
54634        /* c8 ignore next 6 */
54635        // @ts-expect-error: errors could be `messages`.
54636        if (error && !messages.includes(error)) {
54637          try {
54638            file.fail(error);
54639          } catch {}
54640        }
54641
54642        while (++index < messages.length) {
54643          Object.assign(messages[index], {ruleId, source, fatal});
54644        }
54645
54646        next();
54647      })(tree, file, options);
54648    }
54649  }
54650}
54651
54652/**
54653 * Coerce a value to a severity--options tuple.
54654 *
54655 * @param {string} name
54656 * @param {unknown} value
54657 * @returns {SeverityTuple}
54658 */
54659function coerce$a(name, value) {
54660  /** @type {unknown[]} */
54661  let result;
54662
54663  if (typeof value === 'boolean') {
54664    result = [value];
54665  } else if (value === null || value === undefined) {
54666    result = [1];
54667  } else if (
54668    Array.isArray(value) &&
54669    // `isArray(unknown)` is turned into `any[]`:
54670    // type-coverage:ignore-next-line
54671    primitives$9.has(typeof value[0])
54672  ) {
54673    // `isArray(unknown)` is turned into `any[]`:
54674    // type-coverage:ignore-next-line
54675    result = [...value];
54676  } else {
54677    result = [1, value];
54678  }
54679
54680  let level = result[0];
54681
54682  if (typeof level === 'boolean') {
54683    level = level ? 1 : 0;
54684  } else if (typeof level === 'string') {
54685    if (level === 'off') {
54686      level = 0;
54687    } else if (level === 'on' || level === 'warn') {
54688      level = 1;
54689    } else if (level === 'error') {
54690      level = 2;
54691    } else {
54692      level = 1;
54693      result = [level, result];
54694    }
54695  }
54696
54697  if (typeof level !== 'number' || level < 0 || level > 2) {
54698    throw new Error(
54699      'Incorrect severity `' +
54700        level +
54701        '` for `' +
54702        name +
54703        '`, ' +
54704        'expected 0, 1, or 2'
54705    )
54706  }
54707
54708  result[0] = level;
54709
54710  // @ts-expect-error: it’s now a valid tuple.
54711  return result
54712}
54713
54714/**
54715 * @author Titus Wormer
54716 * @copyright 2015 Titus Wormer
54717 * @license MIT
54718 * @module no-shell-dollars
54719 * @fileoverview
54720 *   Warn when shell code is prefixed by `$` (dollar sign) characters.
54721 *
54722 *   Ignores indented code blocks and fenced code blocks without language flag.
54723 *
54724 * @example
54725 *   {"name": "ok.md"}
54726 *
54727 *   ```bash
54728 *   echo a
54729 *   ```
54730 *
54731 *   ```sh
54732 *   echo a
54733 *   echo a > file
54734 *   ```
54735 *
54736 *   ```zsh
54737 *   $ echo a
54738 *   a
54739 *   $ echo a > file
54740 *   ```
54741 *
54742 *   Some empty code:
54743 *
54744 *   ```command
54745 *   ```
54746 *
54747 *   It’s fine to use dollars in non-shell code.
54748 *
54749 *   ```js
54750 *   $('div').remove()
54751 *   ```
54752 *
54753 * @example
54754 *   {"name": "not-ok.md", "label": "input"}
54755 *
54756 *   ```sh
54757 *   $ echo a
54758 *   ```
54759 *
54760 *   ```bash
54761 *   $ echo a
54762 *   $ echo a > file
54763 *   ```
54764 *
54765 * @example
54766 *   {"name": "not-ok.md", "label": "output"}
54767 *
54768 *   1:1-3:4: Do not use dollar signs before shell commands
54769 *   5:1-8:4: Do not use dollar signs before shell commands
54770 */
54771
54772// List of shell script file extensions (also used as code flags for syntax
54773// highlighting on GitHub):
54774// See: <https://github.com/github/linguist/blob/40992ba/lib/linguist/languages.yml#L4984>
54775const flags = new Set([
54776  'sh',
54777  'bash',
54778  'bats',
54779  'cgi',
54780  'command',
54781  'fcgi',
54782  'ksh',
54783  'tmux',
54784  'tool',
54785  'zsh'
54786]);
54787
54788const remarkLintNoShellDollars = lintRule$9(
54789  'remark-lint:no-shell-dollars',
54790  /** @type {import('unified-lint-rule').Rule<Root, void>} */
54791  (tree, file) => {
54792    visit(tree, 'code', (node) => {
54793      // Check both known shell code and unknown code.
54794      if (!generated(node) && node.lang && flags.has(node.lang)) {
54795        const lines = node.value
54796          .split('\n')
54797          .filter((line) => line.trim().length > 0);
54798        let index = -1;
54799
54800        if (lines.length === 0) {
54801          return
54802        }
54803
54804        while (++index < lines.length) {
54805          const line = lines[index];
54806
54807          if (line.trim() && !/^\s*\$\s*/.test(line)) {
54808            return
54809          }
54810        }
54811
54812        file.message('Do not use dollar signs before shell commands', node);
54813      }
54814    });
54815  }
54816);
54817
54818var remarkLintNoShellDollars$1 = remarkLintNoShellDollars;
54819
54820/**
54821 * @typedef {import('unist').Node} Node
54822 * @typedef {import('vfile').VFile} VFile
54823 *
54824 * @typedef {0|1|2} Severity
54825 * @typedef {'warn'|'on'|'off'|'error'} Label
54826 * @typedef {[Severity, ...unknown[]]} SeverityTuple
54827 *
54828 * @callback Rule
54829 * @param {Node} tree
54830 * @param {VFile} file
54831 * @param {unknown} options
54832 * @returns {void}
54833 */
54834
54835const primitives$8 = new Set(['string', 'number', 'boolean']);
54836
54837/**
54838 * @param {string} id
54839 * @param {Rule} rule
54840 */
54841function lintRule$8(id, rule) {
54842  const parts = id.split(':');
54843  // Possibly useful if externalised later.
54844  /* c8 ignore next */
54845  const source = parts[1] ? parts[0] : undefined;
54846  const ruleId = parts[1];
54847
54848  Object.defineProperty(plugin, 'name', {value: id});
54849
54850  return plugin
54851
54852  /** @type {import('unified').Plugin<[unknown]|void[]>} */
54853  function plugin(raw) {
54854    const [severity, options] = coerce$9(ruleId, raw);
54855
54856    if (!severity) return
54857
54858    const fatal = severity === 2;
54859
54860    return (tree, file, next) => {
54861      let index = file.messages.length - 1;
54862
54863      wrap(rule, (error) => {
54864        const messages = file.messages;
54865
54866        // Add the error, if not already properly added.
54867        // Only happens for incorrect plugins.
54868        /* c8 ignore next 6 */
54869        // @ts-expect-error: errors could be `messages`.
54870        if (error && !messages.includes(error)) {
54871          try {
54872            file.fail(error);
54873          } catch {}
54874        }
54875
54876        while (++index < messages.length) {
54877          Object.assign(messages[index], {ruleId, source, fatal});
54878        }
54879
54880        next();
54881      })(tree, file, options);
54882    }
54883  }
54884}
54885
54886/**
54887 * Coerce a value to a severity--options tuple.
54888 *
54889 * @param {string} name
54890 * @param {unknown} value
54891 * @returns {SeverityTuple}
54892 */
54893function coerce$9(name, value) {
54894  /** @type {unknown[]} */
54895  let result;
54896
54897  if (typeof value === 'boolean') {
54898    result = [value];
54899  } else if (value === null || value === undefined) {
54900    result = [1];
54901  } else if (
54902    Array.isArray(value) &&
54903    // `isArray(unknown)` is turned into `any[]`:
54904    // type-coverage:ignore-next-line
54905    primitives$8.has(typeof value[0])
54906  ) {
54907    // `isArray(unknown)` is turned into `any[]`:
54908    // type-coverage:ignore-next-line
54909    result = [...value];
54910  } else {
54911    result = [1, value];
54912  }
54913
54914  let level = result[0];
54915
54916  if (typeof level === 'boolean') {
54917    level = level ? 1 : 0;
54918  } else if (typeof level === 'string') {
54919    if (level === 'off') {
54920      level = 0;
54921    } else if (level === 'on' || level === 'warn') {
54922      level = 1;
54923    } else if (level === 'error') {
54924      level = 2;
54925    } else {
54926      level = 1;
54927      result = [level, result];
54928    }
54929  }
54930
54931  if (typeof level !== 'number' || level < 0 || level > 2) {
54932    throw new Error(
54933      'Incorrect severity `' +
54934        level +
54935        '` for `' +
54936        name +
54937        '`, ' +
54938        'expected 0, 1, or 2'
54939    )
54940  }
54941
54942  result[0] = level;
54943
54944  // @ts-expect-error: it’s now a valid tuple.
54945  return result
54946}
54947
54948/**
54949 * @author Titus Wormer
54950 * @copyright 2015 Titus Wormer
54951 * @license MIT
54952 * @module no-table-indentation
54953 * @fileoverview
54954 *   Warn when tables are indented.
54955 *
54956 *   ## Fix
54957 *
54958 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
54959 *   removes all unneeded indentation before tables.
54960 *
54961 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
54962 *   on how to automatically fix warnings for this rule.
54963 *
54964 * @example
54965 *   {"name": "ok.md", "gfm": true}
54966 *
54967 *   Paragraph.
54968 *
54969 *   | A     | B     |
54970 *   | ----- | ----- |
54971 *   | Alpha | Bravo |
54972 *
54973 * @example
54974 *   {"name": "not-ok.md", "label": "input", "gfm": true}
54975 *
54976 *   Paragraph.
54977 *
54978 *   ···| A     | B     |
54979 *   ···| ----- | ----- |
54980 *   ···| Alpha | Bravo |
54981 *
54982 * @example
54983 *   {"name": "not-ok.md", "label": "output", "gfm": true}
54984 *
54985 *   3:4: Do not indent table rows
54986 *   4:4: Do not indent table rows
54987 *   5:4: Do not indent table rows
54988 *
54989 * @example
54990 *   {"name": "not-ok-blockquote.md", "label": "input", "gfm": true}
54991 *
54992 *   >··| A |
54993 *   >·| - |
54994 *
54995 * @example
54996 *   {"name": "not-ok-blockquote.md", "label": "output", "gfm": true}
54997 *
54998 *   1:4: Do not indent table rows
54999 *
55000 * @example
55001 *   {"name": "not-ok-list.md", "label": "input", "gfm": true}
55002 *
55003 *   -···paragraph
55004 *
55005 *   ·····| A |
55006 *   ····| - |
55007 *
55008 * @example
55009 *   {"name": "not-ok-list.md", "label": "output", "gfm": true}
55010 *
55011 *   3:6: Do not indent table rows
55012 */
55013
55014const remarkLintNoTableIndentation = lintRule$8(
55015  'remark-lint:no-table-indentation',
55016  /** @type {import('unified-lint-rule').Rule<Root, void>} */
55017  (tree, file) => {
55018    const value = String(file);
55019    const loc = location(value);
55020
55021    visit(tree, 'table', (node, _, parent) => {
55022      const end = pointEnd(node).line;
55023      let line = pointStart(node).line;
55024      let column = 0;
55025
55026      if (parent && parent.type === 'root') {
55027        column = 1;
55028      } else if (parent && parent.type === 'blockquote') {
55029        column = pointStart(parent).column + 2;
55030      } else if (parent && parent.type === 'listItem') {
55031        column = pointStart(parent.children[0]).column;
55032
55033        // Skip past the first line if we’re the first child of a list item.
55034        /* c8 ignore next 3 */
55035        if (parent.children[0] === node) {
55036          line++;
55037        }
55038      }
55039
55040      // In a parent we don’t know, exit.
55041      if (!column || !line) {
55042        return
55043      }
55044
55045      while (line <= end) {
55046        let offset = loc.toOffset({line, column});
55047        const lineColumn = offset;
55048
55049        while (/[ \t]/.test(value.charAt(offset - 1))) {
55050          offset--;
55051        }
55052
55053        if (!offset || /[\r\n>]/.test(value.charAt(offset - 1))) {
55054          offset = lineColumn;
55055
55056          while (/[ \t]/.test(value.charAt(offset))) {
55057            offset++;
55058          }
55059
55060          if (lineColumn !== offset) {
55061            file.message('Do not indent table rows', loc.toPoint(offset));
55062          }
55063        }
55064
55065        line++;
55066      }
55067
55068      return SKIP$1
55069    });
55070  }
55071);
55072
55073var remarkLintNoTableIndentation$1 = remarkLintNoTableIndentation;
55074
55075/**
55076 * @typedef {import('unist').Node} Node
55077 * @typedef {import('vfile').VFile} VFile
55078 *
55079 * @typedef {0|1|2} Severity
55080 * @typedef {'warn'|'on'|'off'|'error'} Label
55081 * @typedef {[Severity, ...unknown[]]} SeverityTuple
55082 *
55083 * @callback Rule
55084 * @param {Node} tree
55085 * @param {VFile} file
55086 * @param {unknown} options
55087 * @returns {void}
55088 */
55089
55090const primitives$7 = new Set(['string', 'number', 'boolean']);
55091
55092/**
55093 * @param {string} id
55094 * @param {Rule} rule
55095 */
55096function lintRule$7(id, rule) {
55097  const parts = id.split(':');
55098  // Possibly useful if externalised later.
55099  /* c8 ignore next */
55100  const source = parts[1] ? parts[0] : undefined;
55101  const ruleId = parts[1];
55102
55103  Object.defineProperty(plugin, 'name', {value: id});
55104
55105  return plugin
55106
55107  /** @type {import('unified').Plugin<[unknown]|void[]>} */
55108  function plugin(raw) {
55109    const [severity, options] = coerce$8(ruleId, raw);
55110
55111    if (!severity) return
55112
55113    const fatal = severity === 2;
55114
55115    return (tree, file, next) => {
55116      let index = file.messages.length - 1;
55117
55118      wrap(rule, (error) => {
55119        const messages = file.messages;
55120
55121        // Add the error, if not already properly added.
55122        // Only happens for incorrect plugins.
55123        /* c8 ignore next 6 */
55124        // @ts-expect-error: errors could be `messages`.
55125        if (error && !messages.includes(error)) {
55126          try {
55127            file.fail(error);
55128          } catch {}
55129        }
55130
55131        while (++index < messages.length) {
55132          Object.assign(messages[index], {ruleId, source, fatal});
55133        }
55134
55135        next();
55136      })(tree, file, options);
55137    }
55138  }
55139}
55140
55141/**
55142 * Coerce a value to a severity--options tuple.
55143 *
55144 * @param {string} name
55145 * @param {unknown} value
55146 * @returns {SeverityTuple}
55147 */
55148function coerce$8(name, value) {
55149  /** @type {unknown[]} */
55150  let result;
55151
55152  if (typeof value === 'boolean') {
55153    result = [value];
55154  } else if (value === null || value === undefined) {
55155    result = [1];
55156  } else if (
55157    Array.isArray(value) &&
55158    // `isArray(unknown)` is turned into `any[]`:
55159    // type-coverage:ignore-next-line
55160    primitives$7.has(typeof value[0])
55161  ) {
55162    // `isArray(unknown)` is turned into `any[]`:
55163    // type-coverage:ignore-next-line
55164    result = [...value];
55165  } else {
55166    result = [1, value];
55167  }
55168
55169  let level = result[0];
55170
55171  if (typeof level === 'boolean') {
55172    level = level ? 1 : 0;
55173  } else if (typeof level === 'string') {
55174    if (level === 'off') {
55175      level = 0;
55176    } else if (level === 'on' || level === 'warn') {
55177      level = 1;
55178    } else if (level === 'error') {
55179      level = 2;
55180    } else {
55181      level = 1;
55182      result = [level, result];
55183    }
55184  }
55185
55186  if (typeof level !== 'number' || level < 0 || level > 2) {
55187    throw new Error(
55188      'Incorrect severity `' +
55189        level +
55190        '` for `' +
55191        name +
55192        '`, ' +
55193        'expected 0, 1, or 2'
55194    )
55195  }
55196
55197  result[0] = level;
55198
55199  // @ts-expect-error: it’s now a valid tuple.
55200  return result
55201}
55202
55203/**
55204 * @author Titus Wormer
55205 * @copyright 2015 Titus Wormer
55206 * @license MIT
55207 * @module no-tabs
55208 * @fileoverview
55209 *   Warn when hard tabs (`\t`) are used instead of spaces.
55210 *
55211 *   ## Fix
55212 *
55213 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
55214 *   uses spaces where tabs are used for indentation, but retains tabs used in
55215 *   content.
55216 *
55217 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
55218 *   on how to automatically fix warnings for this rule.
55219 *
55220 * @example
55221 *   {"name": "ok.md"}
55222 *
55223 *   Foo Bar
55224 *
55225 *   ····Foo
55226 *
55227 * @example
55228 *   {"name": "not-ok.md", "label": "input", "positionless": true}
55229 *
55230 *   »Here's one before a code block.
55231 *
55232 *   Here's a tab:», and here is another:».
55233 *
55234 *   And this is in `inline»code`.
55235 *
55236 *   >»This is in a block quote.
55237 *
55238 *   *»And…
55239 *
55240 *   »1.»in a list.
55241 *
55242 *   And this is a tab as the last character.»
55243 *
55244 * @example
55245 *   {"name": "not-ok.md", "label": "output"}
55246 *
55247 *   1:1: Use spaces instead of tabs
55248 *   3:14: Use spaces instead of tabs
55249 *   3:37: Use spaces instead of tabs
55250 *   5:23: Use spaces instead of tabs
55251 *   7:2: Use spaces instead of tabs
55252 *   9:2: Use spaces instead of tabs
55253 *   11:1: Use spaces instead of tabs
55254 *   11:4: Use spaces instead of tabs
55255 *   13:41: Use spaces instead of tabs
55256 */
55257
55258const remarkLintNoTabs = lintRule$7(
55259  'remark-lint:no-tabs',
55260  /** @type {import('unified-lint-rule').Rule<Root, void>} */
55261  (_, file) => {
55262    const value = String(file);
55263    const toPoint = location(file).toPoint;
55264    let index = value.indexOf('\t');
55265
55266    while (index !== -1) {
55267      file.message('Use spaces instead of tabs', toPoint(index));
55268      index = value.indexOf('\t', index + 1);
55269    }
55270  }
55271);
55272
55273var remarkLintNoTabs$1 = remarkLintNoTabs;
55274
55275/**
55276 * An Array.prototype.slice.call(arguments) alternative
55277 *
55278 * @param {Object} args something with a length
55279 * @param {Number} slice
55280 * @param {Number} sliceEnd
55281 * @api public
55282 */
55283
55284var sliced$1 = function (args, slice, sliceEnd) {
55285  var ret = [];
55286  var len = args.length;
55287
55288  if (0 === len) return ret;
55289
55290  var start = slice < 0
55291    ? Math.max(0, slice + len)
55292    : slice || 0;
55293
55294  if (sliceEnd !== undefined) {
55295    len = sliceEnd < 0
55296      ? sliceEnd + len
55297      : sliceEnd;
55298  }
55299
55300  while (len-- > start) {
55301    ret[len - start] = args[len];
55302  }
55303
55304  return ret;
55305};
55306
55307/**
55308 * slice() reference.
55309 */
55310
55311var slice = Array.prototype.slice;
55312
55313/**
55314 * Expose `co`.
55315 */
55316
55317var co_1 = co$1;
55318
55319/**
55320 * Wrap the given generator `fn` and
55321 * return a thunk.
55322 *
55323 * @param {Function} fn
55324 * @return {Function}
55325 * @api public
55326 */
55327
55328function co$1(fn) {
55329  var isGenFun = isGeneratorFunction(fn);
55330
55331  return function (done) {
55332    var ctx = this;
55333
55334    // in toThunk() below we invoke co()
55335    // with a generator, so optimize for
55336    // this case
55337    var gen = fn;
55338
55339    // we only need to parse the arguments
55340    // if gen is a generator function.
55341    if (isGenFun) {
55342      var args = slice.call(arguments), len = args.length;
55343      var hasCallback = len && 'function' == typeof args[len - 1];
55344      done = hasCallback ? args.pop() : error;
55345      gen = fn.apply(this, args);
55346    } else {
55347      done = done || error;
55348    }
55349
55350    next();
55351
55352    // #92
55353    // wrap the callback in a setImmediate
55354    // so that any of its errors aren't caught by `co`
55355    function exit(err, res) {
55356      setImmediate(function(){
55357        done.call(ctx, err, res);
55358      });
55359    }
55360
55361    function next(err, res) {
55362      var ret;
55363
55364      // multiple args
55365      if (arguments.length > 2) res = slice.call(arguments, 1);
55366
55367      // error
55368      if (err) {
55369        try {
55370          ret = gen.throw(err);
55371        } catch (e) {
55372          return exit(e);
55373        }
55374      }
55375
55376      // ok
55377      if (!err) {
55378        try {
55379          ret = gen.next(res);
55380        } catch (e) {
55381          return exit(e);
55382        }
55383      }
55384
55385      // done
55386      if (ret.done) return exit(null, ret.value);
55387
55388      // normalize
55389      ret.value = toThunk(ret.value, ctx);
55390
55391      // run
55392      if ('function' == typeof ret.value) {
55393        var called = false;
55394        try {
55395          ret.value.call(ctx, function(){
55396            if (called) return;
55397            called = true;
55398            next.apply(ctx, arguments);
55399          });
55400        } catch (e) {
55401          setImmediate(function(){
55402            if (called) return;
55403            called = true;
55404            next(e);
55405          });
55406        }
55407        return;
55408      }
55409
55410      // invalid
55411      next(new TypeError('You may only yield a function, promise, generator, array, or object, '
55412        + 'but the following was passed: "' + String(ret.value) + '"'));
55413    }
55414  }
55415}
55416
55417/**
55418 * Convert `obj` into a normalized thunk.
55419 *
55420 * @param {Mixed} obj
55421 * @param {Mixed} ctx
55422 * @return {Function}
55423 * @api private
55424 */
55425
55426function toThunk(obj, ctx) {
55427
55428  if (isGeneratorFunction(obj)) {
55429    return co$1(obj.call(ctx));
55430  }
55431
55432  if (isGenerator(obj)) {
55433    return co$1(obj);
55434  }
55435
55436  if (isPromise(obj)) {
55437    return promiseToThunk(obj);
55438  }
55439
55440  if ('function' == typeof obj) {
55441    return obj;
55442  }
55443
55444  if (isObject(obj) || Array.isArray(obj)) {
55445    return objectToThunk.call(ctx, obj);
55446  }
55447
55448  return obj;
55449}
55450
55451/**
55452 * Convert an object of yieldables to a thunk.
55453 *
55454 * @param {Object} obj
55455 * @return {Function}
55456 * @api private
55457 */
55458
55459function objectToThunk(obj){
55460  var ctx = this;
55461  var isArray = Array.isArray(obj);
55462
55463  return function(done){
55464    var keys = Object.keys(obj);
55465    var pending = keys.length;
55466    var results = isArray
55467      ? new Array(pending) // predefine the array length
55468      : new obj.constructor();
55469    var finished;
55470
55471    if (!pending) {
55472      setImmediate(function(){
55473        done(null, results);
55474      });
55475      return;
55476    }
55477
55478    // prepopulate object keys to preserve key ordering
55479    if (!isArray) {
55480      for (var i = 0; i < pending; i++) {
55481        results[keys[i]] = undefined;
55482      }
55483    }
55484
55485    for (var i = 0; i < keys.length; i++) {
55486      run(obj[keys[i]], keys[i]);
55487    }
55488
55489    function run(fn, key) {
55490      if (finished) return;
55491      try {
55492        fn = toThunk(fn, ctx);
55493
55494        if ('function' != typeof fn) {
55495          results[key] = fn;
55496          return --pending || done(null, results);
55497        }
55498
55499        fn.call(ctx, function(err, res){
55500          if (finished) return;
55501
55502          if (err) {
55503            finished = true;
55504            return done(err);
55505          }
55506
55507          results[key] = res;
55508          --pending || done(null, results);
55509        });
55510      } catch (err) {
55511        finished = true;
55512        done(err);
55513      }
55514    }
55515  }
55516}
55517
55518/**
55519 * Convert `promise` to a thunk.
55520 *
55521 * @param {Object} promise
55522 * @return {Function}
55523 * @api private
55524 */
55525
55526function promiseToThunk(promise) {
55527  return function(fn){
55528    promise.then(function(res) {
55529      fn(null, res);
55530    }, fn);
55531  }
55532}
55533
55534/**
55535 * Check if `obj` is a promise.
55536 *
55537 * @param {Object} obj
55538 * @return {Boolean}
55539 * @api private
55540 */
55541
55542function isPromise(obj) {
55543  return obj && 'function' == typeof obj.then;
55544}
55545
55546/**
55547 * Check if `obj` is a generator.
55548 *
55549 * @param {Mixed} obj
55550 * @return {Boolean}
55551 * @api private
55552 */
55553
55554function isGenerator(obj) {
55555  return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw;
55556}
55557
55558/**
55559 * Check if `obj` is a generator function.
55560 *
55561 * @param {Mixed} obj
55562 * @return {Boolean}
55563 * @api private
55564 */
55565
55566function isGeneratorFunction(obj) {
55567  return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name;
55568}
55569
55570/**
55571 * Check for plain object.
55572 *
55573 * @param {Mixed} val
55574 * @return {Boolean}
55575 * @api private
55576 */
55577
55578function isObject(val) {
55579  return val && Object == val.constructor;
55580}
55581
55582/**
55583 * Throw `err` in a new stack.
55584 *
55585 * This is used when co() is invoked
55586 * without supplying a callback, which
55587 * should only be for demonstrational
55588 * purposes.
55589 *
55590 * @param {Error} err
55591 * @api private
55592 */
55593
55594function error(err) {
55595  if (!err) return;
55596  setImmediate(function(){
55597    throw err;
55598  });
55599}
55600
55601/**
55602 * Module Dependencies
55603 */
55604
55605var sliced = sliced$1;
55606var noop = function(){};
55607var co = co_1;
55608
55609/**
55610 * Export `wrapped`
55611 */
55612
55613var wrapped_1 = wrapped$1;
55614
55615/**
55616 * Wrap a function to support
55617 * sync, async, and gen functions.
55618 *
55619 * @param {Function} fn
55620 * @return {Function}
55621 * @api public
55622 */
55623
55624function wrapped$1(fn) {
55625  function wrap() {
55626    var args = sliced(arguments);
55627    var last = args[args.length - 1];
55628    var ctx = this;
55629
55630    // done
55631    var done = typeof last == 'function' ? args.pop() : noop;
55632
55633    // nothing
55634    if (!fn) {
55635      return done.apply(ctx, [null].concat(args));
55636    }
55637
55638    // generator
55639    if (generator(fn)) {
55640      return co(fn).apply(ctx, args.concat(done));
55641    }
55642
55643    // async
55644    if (fn.length > args.length) {
55645      // NOTE: this only handles uncaught synchronous errors
55646      try {
55647        return fn.apply(ctx, args.concat(done));
55648      } catch (e) {
55649        return done(e);
55650      }
55651    }
55652
55653    // sync
55654    return sync(fn, done).apply(ctx, args);
55655  }
55656
55657  return wrap;
55658}
55659
55660/**
55661 * Wrap a synchronous function execution.
55662 *
55663 * @param {Function} fn
55664 * @param {Function} done
55665 * @return {Function}
55666 * @api private
55667 */
55668
55669function sync(fn, done) {
55670  return function () {
55671    var ret;
55672
55673    try {
55674      ret = fn.apply(this, arguments);
55675    } catch (err) {
55676      return done(err);
55677    }
55678
55679    if (promise(ret)) {
55680      ret.then(function (value) { done(null, value); }, done);
55681    } else {
55682      ret instanceof Error ? done(ret) : done(null, ret);
55683    }
55684  }
55685}
55686
55687/**
55688 * Is `value` a generator?
55689 *
55690 * @param {Mixed} value
55691 * @return {Boolean}
55692 * @api private
55693 */
55694
55695function generator(value) {
55696  return value
55697    && value.constructor
55698    && 'GeneratorFunction' == value.constructor.name;
55699}
55700
55701
55702/**
55703 * Is `value` a promise?
55704 *
55705 * @param {Mixed} value
55706 * @return {Boolean}
55707 * @api private
55708 */
55709
55710function promise(value) {
55711  return value && 'function' == typeof value.then;
55712}
55713
55714var wrapped = wrapped_1;
55715
55716var unifiedLintRule = factory;
55717
55718function factory(id, rule) {
55719  var parts = id.split(':');
55720  var source = parts[0];
55721  var ruleId = parts[1];
55722  var fn = wrapped(rule);
55723
55724  /* istanbul ignore if - possibly useful if externalised later. */
55725  if (!ruleId) {
55726    ruleId = source;
55727    source = null;
55728  }
55729
55730  attacher.displayName = id;
55731
55732  return attacher
55733
55734  function attacher(raw) {
55735    var config = coerce$7(ruleId, raw);
55736    var severity = config[0];
55737    var options = config[1];
55738    var fatal = severity === 2;
55739
55740    return severity ? transformer : undefined
55741
55742    function transformer(tree, file, next) {
55743      var index = file.messages.length;
55744
55745      fn(tree, file, options, done);
55746
55747      function done(err) {
55748        var messages = file.messages;
55749        var message;
55750
55751        // Add the error, if not already properly added.
55752        /* istanbul ignore if - only happens for incorrect plugins */
55753        if (err && messages.indexOf(err) === -1) {
55754          try {
55755            file.fail(err);
55756          } catch (_) {}
55757        }
55758
55759        while (index < messages.length) {
55760          message = messages[index];
55761          message.ruleId = ruleId;
55762          message.source = source;
55763          message.fatal = fatal;
55764
55765          index++;
55766        }
55767
55768        next();
55769      }
55770    }
55771  }
55772}
55773
55774// Coerce a value to a severity--options tuple.
55775function coerce$7(name, value) {
55776  var def = 1;
55777  var result;
55778  var level;
55779
55780  /* istanbul ignore if - Handled by unified in v6.0.0 */
55781  if (typeof value === 'boolean') {
55782    result = [value];
55783  } else if (value == null) {
55784    result = [def];
55785  } else if (
55786    typeof value === 'object' &&
55787    (typeof value[0] === 'number' ||
55788      typeof value[0] === 'boolean' ||
55789      typeof value[0] === 'string')
55790  ) {
55791    result = value.concat();
55792  } else {
55793    result = [1, value];
55794  }
55795
55796  level = result[0];
55797
55798  if (typeof level === 'boolean') {
55799    level = level ? 1 : 0;
55800  } else if (typeof level === 'string') {
55801    if (level === 'off') {
55802      level = 0;
55803    } else if (level === 'on' || level === 'warn') {
55804      level = 1;
55805    } else if (level === 'error') {
55806      level = 2;
55807    } else {
55808      level = 1;
55809      result = [level, result];
55810    }
55811  }
55812
55813  if (level < 0 || level > 2) {
55814    throw new Error(
55815      'Incorrect severity `' +
55816        level +
55817        '` for `' +
55818        name +
55819        '`, ' +
55820        'expected 0, 1, or 2'
55821    )
55822  }
55823
55824  result[0] = level;
55825
55826  return result
55827}
55828
55829var rule = unifiedLintRule;
55830
55831var remarkLintNoTrailingSpaces = rule('remark-lint:no-trailing-spaces', noTrailingSpaces);
55832
55833/**
55834 * Lines that are just space characters are not present in
55835 * the AST, which is why we loop through lines manually.
55836 */
55837
55838function noTrailingSpaces(ast, file) {
55839  var lines = file.toString().split(/\r?\n/);
55840  for (var i = 0; i < lines.length; i++) {
55841    var currentLine = lines[i];
55842    var lineIndex = i + 1;
55843    if (/\s$/.test(currentLine)) {
55844      file.message('Remove trailing whitespace', {
55845        position: {
55846          start: { line: lineIndex, column: currentLine.length + 1 },
55847          end: { line: lineIndex }
55848        }
55849      });
55850    }
55851  }
55852}
55853
55854/**
55855 * @typedef {import('unist').Node} Node
55856 * @typedef {import('vfile').VFile} VFile
55857 *
55858 * @typedef {0|1|2} Severity
55859 * @typedef {'warn'|'on'|'off'|'error'} Label
55860 * @typedef {[Severity, ...unknown[]]} SeverityTuple
55861 *
55862 * @callback Rule
55863 * @param {Node} tree
55864 * @param {VFile} file
55865 * @param {unknown} options
55866 * @returns {void}
55867 */
55868
55869const primitives$6 = new Set(['string', 'number', 'boolean']);
55870
55871/**
55872 * @param {string} id
55873 * @param {Rule} rule
55874 */
55875function lintRule$6(id, rule) {
55876  const parts = id.split(':');
55877  // Possibly useful if externalised later.
55878  /* c8 ignore next */
55879  const source = parts[1] ? parts[0] : undefined;
55880  const ruleId = parts[1];
55881
55882  Object.defineProperty(plugin, 'name', {value: id});
55883
55884  return plugin
55885
55886  /** @type {import('unified').Plugin<[unknown]|void[]>} */
55887  function plugin(raw) {
55888    const [severity, options] = coerce$6(ruleId, raw);
55889
55890    if (!severity) return
55891
55892    const fatal = severity === 2;
55893
55894    return (tree, file, next) => {
55895      let index = file.messages.length - 1;
55896
55897      wrap(rule, (error) => {
55898        const messages = file.messages;
55899
55900        // Add the error, if not already properly added.
55901        // Only happens for incorrect plugins.
55902        /* c8 ignore next 6 */
55903        // @ts-expect-error: errors could be `messages`.
55904        if (error && !messages.includes(error)) {
55905          try {
55906            file.fail(error);
55907          } catch {}
55908        }
55909
55910        while (++index < messages.length) {
55911          Object.assign(messages[index], {ruleId, source, fatal});
55912        }
55913
55914        next();
55915      })(tree, file, options);
55916    }
55917  }
55918}
55919
55920/**
55921 * Coerce a value to a severity--options tuple.
55922 *
55923 * @param {string} name
55924 * @param {unknown} value
55925 * @returns {SeverityTuple}
55926 */
55927function coerce$6(name, value) {
55928  /** @type {unknown[]} */
55929  let result;
55930
55931  if (typeof value === 'boolean') {
55932    result = [value];
55933  } else if (value === null || value === undefined) {
55934    result = [1];
55935  } else if (
55936    Array.isArray(value) &&
55937    // `isArray(unknown)` is turned into `any[]`:
55938    // type-coverage:ignore-next-line
55939    primitives$6.has(typeof value[0])
55940  ) {
55941    // `isArray(unknown)` is turned into `any[]`:
55942    // type-coverage:ignore-next-line
55943    result = [...value];
55944  } else {
55945    result = [1, value];
55946  }
55947
55948  let level = result[0];
55949
55950  if (typeof level === 'boolean') {
55951    level = level ? 1 : 0;
55952  } else if (typeof level === 'string') {
55953    if (level === 'off') {
55954      level = 0;
55955    } else if (level === 'on' || level === 'warn') {
55956      level = 1;
55957    } else if (level === 'error') {
55958      level = 2;
55959    } else {
55960      level = 1;
55961      result = [level, result];
55962    }
55963  }
55964
55965  if (typeof level !== 'number' || level < 0 || level > 2) {
55966    throw new Error(
55967      'Incorrect severity `' +
55968        level +
55969        '` for `' +
55970        name +
55971        '`, ' +
55972        'expected 0, 1, or 2'
55973    )
55974  }
55975
55976  result[0] = level;
55977
55978  // @ts-expect-error: it’s now a valid tuple.
55979  return result
55980}
55981
55982function* getLinksRecursively(node) {
55983  if (node.url) {
55984    yield node;
55985  }
55986  for (const child of node.children || []) {
55987    yield* getLinksRecursively(child);
55988  }
55989}
55990
55991function validateLinks(tree, vfile) {
55992  const currentFileURL = pathToFileURL(path$b.join(vfile.cwd, vfile.path));
55993  let previousDefinitionLabel;
55994  for (const node of getLinksRecursively(tree)) {
55995    if (node.url[0] !== "#") {
55996      const targetURL = new URL(node.url, currentFileURL);
55997      if (targetURL.protocol === "file:" && !require$$0$3.existsSync(targetURL)) {
55998        vfile.message("Broken link", node);
55999      } else if (targetURL.pathname === currentFileURL.pathname) {
56000        const expected = node.url.includes("#")
56001          ? node.url.slice(node.url.indexOf("#"))
56002          : "#";
56003        vfile.message(
56004          `Self-reference must start with hash (expected "${expected}", got "${node.url}")`,
56005          node
56006        );
56007      }
56008    }
56009    if (node.type === "definition") {
56010      if (previousDefinitionLabel && previousDefinitionLabel > node.label) {
56011        vfile.message(
56012          `Unordered reference ("${node.label}" should be before "${previousDefinitionLabel}")`,
56013          node
56014        );
56015      }
56016      previousDefinitionLabel = node.label;
56017    }
56018  }
56019}
56020
56021const remarkLintNodejsLinks = lintRule$6(
56022  "remark-lint:nodejs-links",
56023  validateLinks
56024);
56025
56026const allowedKeys = [
56027  "added",
56028  "napiVersion",
56029  "deprecated",
56030  "removed",
56031  "changes",
56032];
56033const changesExpectedKeys = ["version", "pr-url", "description"];
56034const VERSION_PLACEHOLDER = "REPLACEME";
56035const MAX_SAFE_SEMVER_VERSION = parse_1(
56036  Array.from({ length: 3 }, () => Number.MAX_SAFE_INTEGER).join(".")
56037);
56038const validVersionNumberRegex = /^v\d+\.\d+\.\d+$/;
56039const prUrlRegex = new RegExp("^https://github.com/nodejs/node/pull/\\d+$");
56040const privatePRUrl = "https://github.com/nodejs-private/node-private/pull/";
56041
56042let releasedVersions;
56043let invalidVersionMessage = "version(s) must respect the pattern `vx.x.x` or";
56044if (process.env.NODE_RELEASED_VERSIONS) {
56045  console.log("Using release list from env...");
56046  releasedVersions = process.env.NODE_RELEASED_VERSIONS.split(",").map(
56047    (v) => `v${v}`
56048  );
56049  invalidVersionMessage = `version not listed in the changelogs, `;
56050}
56051invalidVersionMessage += `use the placeholder \`${VERSION_PLACEHOLDER}\``;
56052
56053const kContainsIllegalKey = Symbol("illegal key");
56054const kWrongKeyOrder = Symbol("Wrong key order");
56055function unorderedKeys(meta) {
56056  const keys = Object.keys(meta);
56057  let previousKeyIndex = -1;
56058  for (const key of keys) {
56059    const keyIndex = allowedKeys.indexOf(key);
56060    if (keyIndex <= previousKeyIndex) {
56061      return keyIndex === -1 ? kContainsIllegalKey : kWrongKeyOrder;
56062    }
56063    previousKeyIndex = keyIndex;
56064  }
56065}
56066
56067function containsInvalidVersionNumber(version) {
56068  if (Array.isArray(version)) {
56069    return version.some(containsInvalidVersionNumber);
56070  }
56071
56072  if (version === undefined || version === VERSION_PLACEHOLDER) return false;
56073
56074  if (
56075    releasedVersions &&
56076    // Always ignore 0.0.x and 0.1.x release numbers:
56077    (version[1] !== "0" || (version[3] !== "0" && version[3] !== "1"))
56078  )
56079    return !releasedVersions.includes(version);
56080
56081  return !validVersionNumberRegex.test(version);
56082}
56083const getValidSemver = (version) =>
56084  version === VERSION_PLACEHOLDER ? MAX_SAFE_SEMVER_VERSION : version;
56085function areVersionsUnordered(versions) {
56086  if (!Array.isArray(versions)) return false;
56087
56088  for (let index = 1; index < versions.length; index++) {
56089    if (
56090      lt_1(
56091        getValidSemver(versions[index - 1]),
56092        getValidSemver(versions[index])
56093      )
56094    ) {
56095      return true;
56096    }
56097  }
56098}
56099
56100function invalidChangesKeys(change) {
56101  const keys = Object.keys(change);
56102  const { length } = keys;
56103  if (length !== changesExpectedKeys.length) return true;
56104  for (let index = 0; index < length; index++) {
56105    if (keys[index] !== changesExpectedKeys[index]) return true;
56106  }
56107}
56108function validateSecurityChange(file, node, change, index) {
56109  if ("commit" in change) {
56110    if (typeof change.commit !== "string" || isNaN(`0x${change.commit}`)) {
56111      file.message(
56112        `changes[${index}]: Ill-formed security change commit ID`,
56113        node
56114      );
56115    }
56116
56117    if (Object.keys(change)[1] === "commit") {
56118      change = { ...change };
56119      delete change.commit;
56120    }
56121  }
56122  if (invalidChangesKeys(change)) {
56123    const securityChangeExpectedKeys = [...changesExpectedKeys];
56124    securityChangeExpectedKeys[0] += "[, commit]";
56125    file.message(
56126      `changes[${index}]: Invalid keys. Expected keys are: ` +
56127        securityChangeExpectedKeys.join(", "),
56128      node
56129    );
56130  }
56131}
56132function validateChanges(file, node, changes) {
56133  if (!Array.isArray(changes))
56134    return file.message("`changes` must be a YAML list", node);
56135
56136  const changesVersions = [];
56137  for (let index = 0; index < changes.length; index++) {
56138    const change = changes[index];
56139
56140    const isAncient =
56141      typeof change.version === "string" && change.version.startsWith("v0.");
56142    const isSecurityChange =
56143      !isAncient &&
56144      typeof change["pr-url"] === "string" &&
56145      change["pr-url"].startsWith(privatePRUrl);
56146
56147    if (isSecurityChange) {
56148      validateSecurityChange(file, node, change, index);
56149    } else if (!isAncient && invalidChangesKeys(change)) {
56150      file.message(
56151        `changes[${index}]: Invalid keys. Expected keys are: ` +
56152          changesExpectedKeys.join(", "),
56153        node
56154      );
56155    }
56156
56157    if (containsInvalidVersionNumber(change.version)) {
56158      file.message(`changes[${index}]: ${invalidVersionMessage}`, node);
56159    } else if (areVersionsUnordered(change.version)) {
56160      file.message(`changes[${index}]: list of versions is not in order`, node);
56161    }
56162
56163    if (!isAncient && !isSecurityChange && !prUrlRegex.test(change["pr-url"])) {
56164      file.message(
56165        `changes[${index}]: PR-URL does not match the expected pattern`,
56166        node
56167      );
56168    }
56169
56170    if (typeof change.description !== "string" || !change.description.length) {
56171      file.message(
56172        `changes[${index}]: must contain a non-empty description`,
56173        node
56174      );
56175    } else if (!change.description.endsWith(".")) {
56176      file.message(
56177        `changes[${index}]: description must end with a period`,
56178        node
56179      );
56180    }
56181
56182    changesVersions.push(
56183      Array.isArray(change.version) ? change.version[0] : change.version
56184    );
56185  }
56186
56187  if (areVersionsUnordered(changesVersions)) {
56188    file.message("Items in `changes` list are not in order", node);
56189  }
56190}
56191
56192function validateMeta(node, file, meta) {
56193  switch (unorderedKeys(meta)) {
56194    case kContainsIllegalKey:
56195      file.message(
56196        "YAML dictionary contains illegal keys. Accepted values are: " +
56197          allowedKeys.join(", "),
56198        node
56199      );
56200      break;
56201
56202    case kWrongKeyOrder:
56203      file.message(
56204        "YAML dictionary keys should be in this order: " +
56205          allowedKeys.join(", "),
56206        node
56207      );
56208      break;
56209  }
56210
56211  if (containsInvalidVersionNumber(meta.added)) {
56212    file.message(`Invalid \`added\` value: ${invalidVersionMessage}`, node);
56213  } else if (areVersionsUnordered(meta.added)) {
56214    file.message("Versions in `added` list are not in order", node);
56215  }
56216
56217  if (containsInvalidVersionNumber(meta.deprecated)) {
56218    file.message(
56219      `Invalid \`deprecated\` value: ${invalidVersionMessage}`,
56220      node
56221    );
56222  } else if (areVersionsUnordered(meta.deprecated)) {
56223    file.message("Versions in `deprecated` list are not in order", node);
56224  }
56225
56226  if (containsInvalidVersionNumber(meta.removed)) {
56227    file.message(`Invalid \`removed\` value: ${invalidVersionMessage}`, node);
56228  } else if (areVersionsUnordered(meta.removed)) {
56229    file.message("Versions in `removed` list are not in order", node);
56230  }
56231
56232  if ("changes" in meta) {
56233    validateChanges(file, node, meta.changes);
56234  }
56235}
56236
56237function validateYAMLComments(tree, file) {
56238  visit(tree, "html", function visitor(node) {
56239    if (node.value.startsWith("<!--YAML\n"))
56240      file.message(
56241        "Expected `<!-- YAML`, found `<!--YAML`. Please add a space",
56242        node
56243      );
56244    if (!node.value.startsWith("<!-- YAML\n")) return;
56245    try {
56246      const meta = jsYaml.load("#" + node.value.slice(0, -"-->".length));
56247
56248      validateMeta(node, file, meta);
56249    } catch (e) {
56250      file.message(e, node);
56251    }
56252  });
56253}
56254
56255const remarkLintNodejsYamlComments = lintRule$6(
56256  "remark-lint:nodejs-yaml-comments",
56257  validateYAMLComments
56258);
56259
56260function escapeStringRegexp(string) {
56261	if (typeof string !== 'string') {
56262		throw new TypeError('Expected a string');
56263	}
56264
56265	// Escape characters with special meaning either inside or outside character sets.
56266	// Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
56267	return string
56268		.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
56269		.replace(/-/g, '\\x2d');
56270}
56271
56272/**
56273 * @typedef {import('unist').Node} Node
56274 * @typedef {import('vfile').VFile} VFile
56275 *
56276 * @typedef {0|1|2} Severity
56277 * @typedef {'warn'|'on'|'off'|'error'} Label
56278 * @typedef {[Severity, ...unknown[]]} SeverityTuple
56279 *
56280 * @callback Rule
56281 * @param {Node} tree
56282 * @param {VFile} file
56283 * @param {unknown} options
56284 * @returns {void}
56285 */
56286
56287const primitives$5 = new Set(['string', 'number', 'boolean']);
56288
56289/**
56290 * @param {string} id
56291 * @param {Rule} rule
56292 */
56293function lintRule$5(id, rule) {
56294  const parts = id.split(':');
56295  // Possibly useful if externalised later.
56296  /* c8 ignore next */
56297  const source = parts[1] ? parts[0] : undefined;
56298  const ruleId = parts[1];
56299
56300  Object.defineProperty(plugin, 'name', {value: id});
56301
56302  return plugin
56303
56304  /** @type {import('unified').Plugin<[unknown]|void[]>} */
56305  function plugin(raw) {
56306    const [severity, options] = coerce$5(ruleId, raw);
56307
56308    if (!severity) return
56309
56310    const fatal = severity === 2;
56311
56312    return (tree, file, next) => {
56313      let index = file.messages.length - 1;
56314
56315      wrap(rule, (error) => {
56316        const messages = file.messages;
56317
56318        // Add the error, if not already properly added.
56319        // Only happens for incorrect plugins.
56320        /* c8 ignore next 6 */
56321        // @ts-expect-error: errors could be `messages`.
56322        if (error && !messages.includes(error)) {
56323          try {
56324            file.fail(error);
56325          } catch {}
56326        }
56327
56328        while (++index < messages.length) {
56329          Object.assign(messages[index], {ruleId, source, fatal});
56330        }
56331
56332        next();
56333      })(tree, file, options);
56334    }
56335  }
56336}
56337
56338/**
56339 * Coerce a value to a severity--options tuple.
56340 *
56341 * @param {string} name
56342 * @param {unknown} value
56343 * @returns {SeverityTuple}
56344 */
56345function coerce$5(name, value) {
56346  /** @type {unknown[]} */
56347  let result;
56348
56349  if (typeof value === 'boolean') {
56350    result = [value];
56351  } else if (value === null || value === undefined) {
56352    result = [1];
56353  } else if (
56354    Array.isArray(value) &&
56355    // `isArray(unknown)` is turned into `any[]`:
56356    // type-coverage:ignore-next-line
56357    primitives$5.has(typeof value[0])
56358  ) {
56359    // `isArray(unknown)` is turned into `any[]`:
56360    // type-coverage:ignore-next-line
56361    result = [...value];
56362  } else {
56363    result = [1, value];
56364  }
56365
56366  let level = result[0];
56367
56368  if (typeof level === 'boolean') {
56369    level = level ? 1 : 0;
56370  } else if (typeof level === 'string') {
56371    if (level === 'off') {
56372      level = 0;
56373    } else if (level === 'on' || level === 'warn') {
56374      level = 1;
56375    } else if (level === 'error') {
56376      level = 2;
56377    } else {
56378      level = 1;
56379      result = [level, result];
56380    }
56381  }
56382
56383  if (typeof level !== 'number' || level < 0 || level > 2) {
56384    throw new Error(
56385      'Incorrect severity `' +
56386        level +
56387        '` for `' +
56388        name +
56389        '`, ' +
56390        'expected 0, 1, or 2'
56391    )
56392  }
56393
56394  result[0] = level;
56395
56396  // @ts-expect-error: it’s now a valid tuple.
56397  return result
56398}
56399
56400const remarkLintProhibitedStrings = lintRule$5('remark-lint:prohibited-strings', prohibitedStrings);
56401
56402function testProhibited (val, content) {
56403  let regexpFlags = 'g';
56404  let no = val.no;
56405
56406  if (!no) {
56407    no = escapeStringRegexp(val.yes);
56408    regexpFlags += 'i';
56409  }
56410
56411  let regexpString = '(?<!\\.|@[a-zA-Z0-9/-]*)';
56412
56413  const ignoreNextTo = val.ignoreNextTo ? escapeStringRegexp(val.ignoreNextTo) : '';
56414  const replaceCaptureGroups = !!val.replaceCaptureGroups;
56415
56416  // If it starts with a letter, make sure it is a word break.
56417  if (/^\b/.test(no)) {
56418    regexpString += '\\b';
56419  }
56420  if (ignoreNextTo) {
56421    regexpString += `(?<!${ignoreNextTo})`;
56422  }
56423
56424  regexpString += `(${no})`;
56425
56426  if (ignoreNextTo) {
56427    regexpString += `(?!${ignoreNextTo})`;
56428  }
56429
56430  // If it ends with a letter, make sure it is a word break.
56431  if (/\b$/.test(no)) {
56432    regexpString += '\\b';
56433  }
56434  regexpString += '(?!\\.\\w)';
56435  const re = new RegExp(regexpString, regexpFlags);
56436
56437  const results = [];
56438  let result = re.exec(content);
56439  while (result) {
56440    if (result[1] !== val.yes) {
56441      let yes = val.yes;
56442      if (replaceCaptureGroups) {
56443        yes = result[1].replace(new RegExp(no), yes);
56444      }
56445      results.push({ result: result[1], index: result.index, yes: yes });
56446    }
56447    result = re.exec(content);
56448  }
56449
56450  return results
56451}
56452
56453function prohibitedStrings (ast, file, strings) {
56454  const myLocation = location(file);
56455
56456  visit(ast, 'text', checkText);
56457
56458  function checkText (node) {
56459    const content = node.value;
56460    const initial = pointStart(node).offset;
56461
56462    strings.forEach((val) => {
56463      const results = testProhibited(val, content);
56464      if (results.length) {
56465        results.forEach(({ result, index, yes }) => {
56466          const message = val.yes ? `Use "${yes}" instead of "${result}"` : `Do not use "${result}"`;
56467          file.message(message, {
56468            start: myLocation.toPoint(initial + index),
56469            end: myLocation.toPoint(initial + index + [...result].length)
56470          });
56471        });
56472      }
56473    });
56474  }
56475}
56476
56477/**
56478 * @typedef {import('unist').Node} Node
56479 * @typedef {import('vfile').VFile} VFile
56480 *
56481 * @typedef {0|1|2} Severity
56482 * @typedef {'warn'|'on'|'off'|'error'} Label
56483 * @typedef {[Severity, ...unknown[]]} SeverityTuple
56484 *
56485 * @callback Rule
56486 * @param {Node} tree
56487 * @param {VFile} file
56488 * @param {unknown} options
56489 * @returns {void}
56490 */
56491
56492const primitives$4 = new Set(['string', 'number', 'boolean']);
56493
56494/**
56495 * @param {string} id
56496 * @param {Rule} rule
56497 */
56498function lintRule$4(id, rule) {
56499  const parts = id.split(':');
56500  // Possibly useful if externalised later.
56501  /* c8 ignore next */
56502  const source = parts[1] ? parts[0] : undefined;
56503  const ruleId = parts[1];
56504
56505  Object.defineProperty(plugin, 'name', {value: id});
56506
56507  return plugin
56508
56509  /** @type {import('unified').Plugin<[unknown]|void[]>} */
56510  function plugin(raw) {
56511    const [severity, options] = coerce$4(ruleId, raw);
56512
56513    if (!severity) return
56514
56515    const fatal = severity === 2;
56516
56517    return (tree, file, next) => {
56518      let index = file.messages.length - 1;
56519
56520      wrap(rule, (error) => {
56521        const messages = file.messages;
56522
56523        // Add the error, if not already properly added.
56524        // Only happens for incorrect plugins.
56525        /* c8 ignore next 6 */
56526        // @ts-expect-error: errors could be `messages`.
56527        if (error && !messages.includes(error)) {
56528          try {
56529            file.fail(error);
56530          } catch {}
56531        }
56532
56533        while (++index < messages.length) {
56534          Object.assign(messages[index], {ruleId, source, fatal});
56535        }
56536
56537        next();
56538      })(tree, file, options);
56539    }
56540  }
56541}
56542
56543/**
56544 * Coerce a value to a severity--options tuple.
56545 *
56546 * @param {string} name
56547 * @param {unknown} value
56548 * @returns {SeverityTuple}
56549 */
56550function coerce$4(name, value) {
56551  /** @type {unknown[]} */
56552  let result;
56553
56554  if (typeof value === 'boolean') {
56555    result = [value];
56556  } else if (value === null || value === undefined) {
56557    result = [1];
56558  } else if (
56559    Array.isArray(value) &&
56560    // `isArray(unknown)` is turned into `any[]`:
56561    // type-coverage:ignore-next-line
56562    primitives$4.has(typeof value[0])
56563  ) {
56564    // `isArray(unknown)` is turned into `any[]`:
56565    // type-coverage:ignore-next-line
56566    result = [...value];
56567  } else {
56568    result = [1, value];
56569  }
56570
56571  let level = result[0];
56572
56573  if (typeof level === 'boolean') {
56574    level = level ? 1 : 0;
56575  } else if (typeof level === 'string') {
56576    if (level === 'off') {
56577      level = 0;
56578    } else if (level === 'on' || level === 'warn') {
56579      level = 1;
56580    } else if (level === 'error') {
56581      level = 2;
56582    } else {
56583      level = 1;
56584      result = [level, result];
56585    }
56586  }
56587
56588  if (typeof level !== 'number' || level < 0 || level > 2) {
56589    throw new Error(
56590      'Incorrect severity `' +
56591        level +
56592        '` for `' +
56593        name +
56594        '`, ' +
56595        'expected 0, 1, or 2'
56596    )
56597  }
56598
56599  result[0] = level;
56600
56601  // @ts-expect-error: it’s now a valid tuple.
56602  return result
56603}
56604
56605/**
56606 * @author Titus Wormer
56607 * @copyright 2015 Titus Wormer
56608 * @license MIT
56609 * @module rule-style
56610 * @fileoverview
56611 *   Warn when the thematic breaks (horizontal rules) violate a given or
56612 *   detected style.
56613 *
56614 *   Options: `string`, either a corect thematic breaks such as `***`, or
56615 *   `'consistent'`, default: `'consistent'`.
56616 *
56617 *   `'consistent'` detects the first used thematic break style and warns when
56618 *   subsequent rules use different styles.
56619 *
56620 *   ## Fix
56621 *
56622 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
56623 *   has three settings that define how rules are created:
56624 *
56625 *   *   [`rule`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsrule)
56626 *       (default: `*`) — Marker to use
56627 *   *   [`ruleRepetition`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsrulerepetition)
56628 *       (default: `3`) — Number of markers to use
56629 *   *   [`ruleSpaces`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsrulespaces)
56630 *       (default: `true`) — Whether to pad markers with spaces
56631 *
56632 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
56633 *   on how to automatically fix warnings for this rule.
56634 *
56635 * @example
56636 *   {"name": "ok.md", "setting": "* * *"}
56637 *
56638 *   * * *
56639 *
56640 *   * * *
56641 *
56642 * @example
56643 *   {"name": "ok.md", "setting": "_______"}
56644 *
56645 *   _______
56646 *
56647 *   _______
56648 *
56649 * @example
56650 *   {"name": "not-ok.md", "label": "input"}
56651 *
56652 *   ***
56653 *
56654 *   * * *
56655 *
56656 * @example
56657 *   {"name": "not-ok.md", "label": "output"}
56658 *
56659 *   3:1-3:6: Rules should use `***`
56660 *
56661 * @example
56662 *   {"name": "not-ok.md", "label": "output", "setting": "��", "positionless": true}
56663 *
56664 *   1:1: Incorrect preferred rule style: provide a correct markdown rule or `'consistent'`
56665 */
56666
56667const remarkLintRuleStyle = lintRule$4(
56668  'remark-lint:rule-style',
56669  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
56670  (tree, file, option = 'consistent') => {
56671    const value = String(file);
56672
56673    if (option !== 'consistent' && /[^-_* ]/.test(option)) {
56674      file.fail(
56675        "Incorrect preferred rule style: provide a correct markdown rule or `'consistent'`"
56676      );
56677    }
56678
56679    visit(tree, 'thematicBreak', (node) => {
56680      const initial = pointStart(node).offset;
56681      const final = pointEnd(node).offset;
56682
56683      if (typeof initial === 'number' && typeof final === 'number') {
56684        const rule = value.slice(initial, final);
56685
56686        if (option === 'consistent') {
56687          option = rule;
56688        } else if (rule !== option) {
56689          file.message('Rules should use `' + option + '`', node);
56690        }
56691      }
56692    });
56693  }
56694);
56695
56696var remarkLintRuleStyle$1 = remarkLintRuleStyle;
56697
56698/**
56699 * @typedef {import('unist').Node} Node
56700 * @typedef {import('vfile').VFile} VFile
56701 *
56702 * @typedef {0|1|2} Severity
56703 * @typedef {'warn'|'on'|'off'|'error'} Label
56704 * @typedef {[Severity, ...unknown[]]} SeverityTuple
56705 *
56706 * @callback Rule
56707 * @param {Node} tree
56708 * @param {VFile} file
56709 * @param {unknown} options
56710 * @returns {void}
56711 */
56712
56713const primitives$3 = new Set(['string', 'number', 'boolean']);
56714
56715/**
56716 * @param {string} id
56717 * @param {Rule} rule
56718 */
56719function lintRule$3(id, rule) {
56720  const parts = id.split(':');
56721  // Possibly useful if externalised later.
56722  /* c8 ignore next */
56723  const source = parts[1] ? parts[0] : undefined;
56724  const ruleId = parts[1];
56725
56726  Object.defineProperty(plugin, 'name', {value: id});
56727
56728  return plugin
56729
56730  /** @type {import('unified').Plugin<[unknown]|void[]>} */
56731  function plugin(raw) {
56732    const [severity, options] = coerce$3(ruleId, raw);
56733
56734    if (!severity) return
56735
56736    const fatal = severity === 2;
56737
56738    return (tree, file, next) => {
56739      let index = file.messages.length - 1;
56740
56741      wrap(rule, (error) => {
56742        const messages = file.messages;
56743
56744        // Add the error, if not already properly added.
56745        // Only happens for incorrect plugins.
56746        /* c8 ignore next 6 */
56747        // @ts-expect-error: errors could be `messages`.
56748        if (error && !messages.includes(error)) {
56749          try {
56750            file.fail(error);
56751          } catch {}
56752        }
56753
56754        while (++index < messages.length) {
56755          Object.assign(messages[index], {ruleId, source, fatal});
56756        }
56757
56758        next();
56759      })(tree, file, options);
56760    }
56761  }
56762}
56763
56764/**
56765 * Coerce a value to a severity--options tuple.
56766 *
56767 * @param {string} name
56768 * @param {unknown} value
56769 * @returns {SeverityTuple}
56770 */
56771function coerce$3(name, value) {
56772  /** @type {unknown[]} */
56773  let result;
56774
56775  if (typeof value === 'boolean') {
56776    result = [value];
56777  } else if (value === null || value === undefined) {
56778    result = [1];
56779  } else if (
56780    Array.isArray(value) &&
56781    // `isArray(unknown)` is turned into `any[]`:
56782    // type-coverage:ignore-next-line
56783    primitives$3.has(typeof value[0])
56784  ) {
56785    // `isArray(unknown)` is turned into `any[]`:
56786    // type-coverage:ignore-next-line
56787    result = [...value];
56788  } else {
56789    result = [1, value];
56790  }
56791
56792  let level = result[0];
56793
56794  if (typeof level === 'boolean') {
56795    level = level ? 1 : 0;
56796  } else if (typeof level === 'string') {
56797    if (level === 'off') {
56798      level = 0;
56799    } else if (level === 'on' || level === 'warn') {
56800      level = 1;
56801    } else if (level === 'error') {
56802      level = 2;
56803    } else {
56804      level = 1;
56805      result = [level, result];
56806    }
56807  }
56808
56809  if (typeof level !== 'number' || level < 0 || level > 2) {
56810    throw new Error(
56811      'Incorrect severity `' +
56812        level +
56813        '` for `' +
56814        name +
56815        '`, ' +
56816        'expected 0, 1, or 2'
56817    )
56818  }
56819
56820  result[0] = level;
56821
56822  // @ts-expect-error: it’s now a valid tuple.
56823  return result
56824}
56825
56826/**
56827 * @author Titus Wormer
56828 * @copyright 2015 Titus Wormer
56829 * @license MIT
56830 * @module strong-marker
56831 * @fileoverview
56832 *   Warn for violating importance (strong) markers.
56833 *
56834 *   Options: `'consistent'`, `'*'`, or `'_'`, default: `'consistent'`.
56835 *
56836 *   `'consistent'` detects the first used importance style and warns when
56837 *   subsequent importance sequences use different styles.
56838 *
56839 *   ## Fix
56840 *
56841 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
56842 *   formats importance using an `*` (asterisk) by default.
56843 *   Pass
56844 *   [`strong: '_'`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsstrong)
56845 *   to use `_` (underscore) instead.
56846 *
56847 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
56848 *   on how to automatically fix warnings for this rule.
56849 *
56850 * @example
56851 *   {"name": "ok.md"}
56852 *
56853 *   **foo** and **bar**.
56854 *
56855 * @example
56856 *   {"name": "also-ok.md"}
56857 *
56858 *   __foo__ and __bar__.
56859 *
56860 * @example
56861 *   {"name": "ok.md", "setting": "*"}
56862 *
56863 *   **foo**.
56864 *
56865 * @example
56866 *   {"name": "ok.md", "setting": "_"}
56867 *
56868 *   __foo__.
56869 *
56870 * @example
56871 *   {"name": "not-ok.md", "label": "input"}
56872 *
56873 *   **foo** and __bar__.
56874 *
56875 * @example
56876 *   {"name": "not-ok.md", "label": "output"}
56877 *
56878 *   1:13-1:20: Strong should use `*` as a marker
56879 *
56880 * @example
56881 *   {"name": "not-ok.md", "label": "output", "setting": "��", "positionless": true}
56882 *
56883 *   1:1: Incorrect strong marker `��`: use either `'consistent'`, `'*'`, or `'_'`
56884 */
56885
56886const remarkLintStrongMarker = lintRule$3(
56887  'remark-lint:strong-marker',
56888  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
56889  (tree, file, option = 'consistent') => {
56890    const value = String(file);
56891
56892    if (option !== '*' && option !== '_' && option !== 'consistent') {
56893      file.fail(
56894        'Incorrect strong marker `' +
56895          option +
56896          "`: use either `'consistent'`, `'*'`, or `'_'`"
56897      );
56898    }
56899
56900    visit(tree, 'strong', (node) => {
56901      const start = pointStart(node).offset;
56902
56903      if (typeof start === 'number') {
56904        const marker = /** @type {Marker} */ (value.charAt(start));
56905
56906        if (option === 'consistent') {
56907          option = marker;
56908        } else if (marker !== option) {
56909          file.message('Strong should use `' + option + '` as a marker', node);
56910        }
56911      }
56912    });
56913  }
56914);
56915
56916var remarkLintStrongMarker$1 = remarkLintStrongMarker;
56917
56918/**
56919 * @typedef {import('unist').Node} Node
56920 * @typedef {import('vfile').VFile} VFile
56921 *
56922 * @typedef {0|1|2} Severity
56923 * @typedef {'warn'|'on'|'off'|'error'} Label
56924 * @typedef {[Severity, ...unknown[]]} SeverityTuple
56925 *
56926 * @callback Rule
56927 * @param {Node} tree
56928 * @param {VFile} file
56929 * @param {unknown} options
56930 * @returns {void}
56931 */
56932
56933const primitives$2 = new Set(['string', 'number', 'boolean']);
56934
56935/**
56936 * @param {string} id
56937 * @param {Rule} rule
56938 */
56939function lintRule$2(id, rule) {
56940  const parts = id.split(':');
56941  // Possibly useful if externalised later.
56942  /* c8 ignore next */
56943  const source = parts[1] ? parts[0] : undefined;
56944  const ruleId = parts[1];
56945
56946  Object.defineProperty(plugin, 'name', {value: id});
56947
56948  return plugin
56949
56950  /** @type {import('unified').Plugin<[unknown]|void[]>} */
56951  function plugin(raw) {
56952    const [severity, options] = coerce$2(ruleId, raw);
56953
56954    if (!severity) return
56955
56956    const fatal = severity === 2;
56957
56958    return (tree, file, next) => {
56959      let index = file.messages.length - 1;
56960
56961      wrap(rule, (error) => {
56962        const messages = file.messages;
56963
56964        // Add the error, if not already properly added.
56965        // Only happens for incorrect plugins.
56966        /* c8 ignore next 6 */
56967        // @ts-expect-error: errors could be `messages`.
56968        if (error && !messages.includes(error)) {
56969          try {
56970            file.fail(error);
56971          } catch {}
56972        }
56973
56974        while (++index < messages.length) {
56975          Object.assign(messages[index], {ruleId, source, fatal});
56976        }
56977
56978        next();
56979      })(tree, file, options);
56980    }
56981  }
56982}
56983
56984/**
56985 * Coerce a value to a severity--options tuple.
56986 *
56987 * @param {string} name
56988 * @param {unknown} value
56989 * @returns {SeverityTuple}
56990 */
56991function coerce$2(name, value) {
56992  /** @type {unknown[]} */
56993  let result;
56994
56995  if (typeof value === 'boolean') {
56996    result = [value];
56997  } else if (value === null || value === undefined) {
56998    result = [1];
56999  } else if (
57000    Array.isArray(value) &&
57001    // `isArray(unknown)` is turned into `any[]`:
57002    // type-coverage:ignore-next-line
57003    primitives$2.has(typeof value[0])
57004  ) {
57005    // `isArray(unknown)` is turned into `any[]`:
57006    // type-coverage:ignore-next-line
57007    result = [...value];
57008  } else {
57009    result = [1, value];
57010  }
57011
57012  let level = result[0];
57013
57014  if (typeof level === 'boolean') {
57015    level = level ? 1 : 0;
57016  } else if (typeof level === 'string') {
57017    if (level === 'off') {
57018      level = 0;
57019    } else if (level === 'on' || level === 'warn') {
57020      level = 1;
57021    } else if (level === 'error') {
57022      level = 2;
57023    } else {
57024      level = 1;
57025      result = [level, result];
57026    }
57027  }
57028
57029  if (typeof level !== 'number' || level < 0 || level > 2) {
57030    throw new Error(
57031      'Incorrect severity `' +
57032        level +
57033        '` for `' +
57034        name +
57035        '`, ' +
57036        'expected 0, 1, or 2'
57037    )
57038  }
57039
57040  result[0] = level;
57041
57042  // @ts-expect-error: it’s now a valid tuple.
57043  return result
57044}
57045
57046/**
57047 * @author Titus Wormer
57048 * @copyright 2015 Titus Wormer
57049 * @license MIT
57050 * @module table-cell-padding
57051 * @fileoverview
57052 *   Warn when table cells are incorrectly padded.
57053 *
57054 *   Options: `'consistent'`, `'padded'`, or `'compact'`, default: `'consistent'`.
57055 *
57056 *   `'consistent'` detects the first used cell padding style and warns when
57057 *   subsequent cells use different styles.
57058 *
57059 *   ## Fix
57060 *
57061 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
57062 *   formats tables with padding by default.
57063 *   Pass
57064 *   [`spacedTable: false`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsspacedtable)
57065 *   to not use padding.
57066 *
57067 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
57068 *   on how to automatically fix warnings for this rule.
57069 *
57070 * @example
57071 *   {"name": "ok.md", "setting": "padded", "gfm": true}
57072 *
57073 *   | A     | B     |
57074 *   | ----- | ----- |
57075 *   | Alpha | Bravo |
57076 *
57077 * @example
57078 *   {"name": "not-ok.md", "label": "input", "setting": "padded", "gfm": true}
57079 *
57080 *   | A    |    B |
57081 *   | :----|----: |
57082 *   | Alpha|Bravo |
57083 *
57084 *   | C      |    D |
57085 *   | :----- | ---: |
57086 *   |Charlie | Delta|
57087 *
57088 *   Too much padding isn’t good either:
57089 *
57090 *   | E     | F        |   G    |      H |
57091 *   | :---- | -------- | :----: | -----: |
57092 *   | Echo  | Foxtrot  |  Golf  |  Hotel |
57093 *
57094 * @example
57095 *   {"name": "not-ok.md", "label": "output", "setting": "padded", "gfm": true}
57096 *
57097 *   3:8: Cell should be padded
57098 *   3:9: Cell should be padded
57099 *   7:2: Cell should be padded
57100 *   7:17: Cell should be padded
57101 *   13:9: Cell should be padded with 1 space, not 2
57102 *   13:20: Cell should be padded with 1 space, not 2
57103 *   13:21: Cell should be padded with 1 space, not 2
57104 *   13:29: Cell should be padded with 1 space, not 2
57105 *   13:30: Cell should be padded with 1 space, not 2
57106 *
57107 * @example
57108 *   {"name": "ok.md", "setting": "compact", "gfm": true}
57109 *
57110 *   |A    |B    |
57111 *   |-----|-----|
57112 *   |Alpha|Bravo|
57113 *
57114 * @example
57115 *   {"name": "not-ok.md", "label": "input", "setting": "compact", "gfm": true}
57116 *
57117 *   |   A    | B    |
57118 *   |   -----| -----|
57119 *   |   Alpha| Bravo|
57120 *
57121 *   |C      |     D|
57122 *   |:------|-----:|
57123 *   |Charlie|Delta |
57124 *
57125 * @example
57126 *   {"name": "not-ok.md", "label": "output", "setting": "compact", "gfm": true}
57127 *
57128 *   3:2: Cell should be compact
57129 *   3:11: Cell should be compact
57130 *   7:16: Cell should be compact
57131 *
57132 * @example
57133 *   {"name": "ok-padded.md", "setting": "consistent", "gfm": true}
57134 *
57135 *   | A     | B     |
57136 *   | ----- | ----- |
57137 *   | Alpha | Bravo |
57138 *
57139 *   | C       | D     |
57140 *   | ------- | ----- |
57141 *   | Charlie | Delta |
57142 *
57143 * @example
57144 *   {"name": "not-ok-padded.md", "label": "input", "setting": "consistent", "gfm": true}
57145 *
57146 *   | A     | B     |
57147 *   | ----- | ----- |
57148 *   | Alpha | Bravo |
57149 *
57150 *   | C      |     D |
57151 *   | :----- | ----: |
57152 *   |Charlie | Delta |
57153 *
57154 * @example
57155 *   {"name": "not-ok-padded.md", "label": "output", "setting": "consistent", "gfm": true}
57156 *
57157 *   7:2: Cell should be padded
57158 *
57159 * @example
57160 *   {"name": "ok-compact.md", "setting": "consistent", "gfm": true}
57161 *
57162 *   |A    |B    |
57163 *   |-----|-----|
57164 *   |Alpha|Bravo|
57165 *
57166 *   |C      |D    |
57167 *   |-------|-----|
57168 *   |Charlie|Delta|
57169 *
57170 * @example
57171 *   {"name": "not-ok-compact.md", "label": "input", "setting": "consistent", "gfm": true}
57172 *
57173 *   |A    |B    |
57174 *   |-----|-----|
57175 *   |Alpha|Bravo|
57176 *
57177 *   |C      |     D|
57178 *   |:------|-----:|
57179 *   |Charlie|Delta |
57180 *
57181 * @example
57182 *   {"name": "not-ok-compact.md", "label": "output", "setting": "consistent", "gfm": true}
57183 *
57184 *   7:16: Cell should be compact
57185 *
57186 * @example
57187 *   {"name": "not-ok.md", "label": "output", "setting": "��", "positionless": true, "gfm": true}
57188 *
57189 *   1:1: Incorrect table cell padding style `��`, expected `'padded'`, `'compact'`, or `'consistent'`
57190 *
57191 * @example
57192 *   {"name": "empty.md", "label": "input", "setting": "padded", "gfm": true}
57193 *
57194 *   <!-- Empty cells are OK, but those surrounding them may not be. -->
57195 *
57196 *   |        | Alpha | Bravo|
57197 *   | ------ | ----- | ---: |
57198 *   | Charlie|       |  Echo|
57199 *
57200 * @example
57201 *   {"name": "empty.md", "label": "output", "setting": "padded", "gfm": true}
57202 *
57203 *   3:25: Cell should be padded
57204 *   5:10: Cell should be padded
57205 *   5:25: Cell should be padded
57206 *
57207 * @example
57208 *   {"name": "missing-body.md", "setting": "padded", "gfm": true}
57209 *
57210 *   <!-- Missing cells are fine as well. -->
57211 *
57212 *   | Alpha | Bravo   | Charlie |
57213 *   | ----- | ------- | ------- |
57214 *   | Delta |
57215 *   | Echo  | Foxtrot |
57216 */
57217
57218const remarkLintTableCellPadding = lintRule$2(
57219  'remark-lint:table-cell-padding',
57220  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
57221  (tree, file, option = 'consistent') => {
57222    if (
57223      option !== 'padded' &&
57224      option !== 'compact' &&
57225      option !== 'consistent'
57226    ) {
57227      file.fail(
57228        'Incorrect table cell padding style `' +
57229          option +
57230          "`, expected `'padded'`, `'compact'`, or `'consistent'`"
57231      );
57232    }
57233
57234    visit(tree, 'table', (node) => {
57235      const rows = node.children;
57236      // To do: fix types to always have `align` defined.
57237      /* c8 ignore next */
57238      const align = node.align || [];
57239      /** @type {number[]} */
57240      const sizes = Array.from({length: align.length});
57241      /** @type {Entry[]} */
57242      const entries = [];
57243      let index = -1;
57244
57245      // Check rows.
57246      while (++index < rows.length) {
57247        const row = rows[index];
57248        let column = -1;
57249
57250        // Check fences (before, between, and after cells).
57251        while (++column < row.children.length) {
57252          const cell = row.children[column];
57253
57254          if (cell.children.length > 0) {
57255            const cellStart = pointStart(cell).offset;
57256            const cellEnd = pointEnd(cell).offset;
57257            const contentStart = pointStart(cell.children[0]).offset;
57258            const contentEnd = pointEnd(
57259              cell.children[cell.children.length - 1]
57260            ).offset;
57261
57262            if (
57263              typeof cellStart !== 'number' ||
57264              typeof cellEnd !== 'number' ||
57265              typeof contentStart !== 'number' ||
57266              typeof contentEnd !== 'number'
57267            ) {
57268              continue
57269            }
57270
57271            entries.push({
57272              node: cell,
57273              start: contentStart - cellStart - (column ? 0 : 1),
57274              end: cellEnd - contentEnd - 1,
57275              column
57276            });
57277
57278            // Detect max space per column.
57279            sizes[column] = Math.max(
57280              sizes[column] || 0,
57281              contentEnd - contentStart
57282            );
57283          }
57284        }
57285      }
57286
57287      const style =
57288        option === 'consistent'
57289          ? entries[0] && (!entries[0].start || !entries[0].end)
57290            ? 0
57291            : 1
57292          : option === 'padded'
57293          ? 1
57294          : 0;
57295
57296      index = -1;
57297
57298      while (++index < entries.length) {
57299        checkSide('start', entries[index], style, sizes);
57300        checkSide('end', entries[index], style, sizes);
57301      }
57302
57303      return SKIP$1
57304    });
57305
57306    /**
57307     * @param {'start'|'end'} side
57308     * @param {Entry} entry
57309     * @param {0|1} style
57310     * @param {number[]} sizes
57311     */
57312    function checkSide(side, entry, style, sizes) {
57313      const cell = entry.node;
57314      const column = entry.column;
57315      const spacing = entry[side];
57316
57317      if (spacing === undefined || spacing === style) {
57318        return
57319      }
57320
57321      let reason = 'Cell should be ';
57322
57323      if (style === 0) {
57324        // Ignore every cell except the biggest in the column.
57325        if (size(cell) < sizes[column]) {
57326          return
57327        }
57328
57329        reason += 'compact';
57330      } else {
57331        reason += 'padded';
57332
57333        if (spacing > style) {
57334          // May be right or center aligned.
57335          if (size(cell) < sizes[column]) {
57336            return
57337          }
57338
57339          reason += ' with 1 space, not ' + spacing;
57340        }
57341      }
57342
57343      /** @type {Point} */
57344      let point;
57345
57346      if (side === 'start') {
57347        point = pointStart(cell);
57348        if (!column) {
57349          point.column++;
57350
57351          if (typeof point.offset === 'number') {
57352            point.offset++;
57353          }
57354        }
57355      } else {
57356        point = pointEnd(cell);
57357        point.column--;
57358
57359        if (typeof point.offset === 'number') {
57360          point.offset--;
57361        }
57362      }
57363
57364      file.message(reason, point);
57365    }
57366  }
57367);
57368
57369var remarkLintTableCellPadding$1 = remarkLintTableCellPadding;
57370
57371/**
57372 * @param {TableCell} node
57373 * @returns {number}
57374 */
57375function size(node) {
57376  const head = pointStart(node.children[0]).offset;
57377  const tail = pointEnd(node.children[node.children.length - 1]).offset;
57378  // Only called when we’re sure offsets exist.
57379  /* c8 ignore next */
57380  return typeof head === 'number' && typeof tail === 'number' ? tail - head : 0
57381}
57382
57383/**
57384 * @typedef {import('unist').Node} Node
57385 * @typedef {import('vfile').VFile} VFile
57386 *
57387 * @typedef {0|1|2} Severity
57388 * @typedef {'warn'|'on'|'off'|'error'} Label
57389 * @typedef {[Severity, ...unknown[]]} SeverityTuple
57390 *
57391 * @callback Rule
57392 * @param {Node} tree
57393 * @param {VFile} file
57394 * @param {unknown} options
57395 * @returns {void}
57396 */
57397
57398const primitives$1 = new Set(['string', 'number', 'boolean']);
57399
57400/**
57401 * @param {string} id
57402 * @param {Rule} rule
57403 */
57404function lintRule$1(id, rule) {
57405  const parts = id.split(':');
57406  // Possibly useful if externalised later.
57407  /* c8 ignore next */
57408  const source = parts[1] ? parts[0] : undefined;
57409  const ruleId = parts[1];
57410
57411  Object.defineProperty(plugin, 'name', {value: id});
57412
57413  return plugin
57414
57415  /** @type {import('unified').Plugin<[unknown]|void[]>} */
57416  function plugin(raw) {
57417    const [severity, options] = coerce$1(ruleId, raw);
57418
57419    if (!severity) return
57420
57421    const fatal = severity === 2;
57422
57423    return (tree, file, next) => {
57424      let index = file.messages.length - 1;
57425
57426      wrap(rule, (error) => {
57427        const messages = file.messages;
57428
57429        // Add the error, if not already properly added.
57430        // Only happens for incorrect plugins.
57431        /* c8 ignore next 6 */
57432        // @ts-expect-error: errors could be `messages`.
57433        if (error && !messages.includes(error)) {
57434          try {
57435            file.fail(error);
57436          } catch {}
57437        }
57438
57439        while (++index < messages.length) {
57440          Object.assign(messages[index], {ruleId, source, fatal});
57441        }
57442
57443        next();
57444      })(tree, file, options);
57445    }
57446  }
57447}
57448
57449/**
57450 * Coerce a value to a severity--options tuple.
57451 *
57452 * @param {string} name
57453 * @param {unknown} value
57454 * @returns {SeverityTuple}
57455 */
57456function coerce$1(name, value) {
57457  /** @type {unknown[]} */
57458  let result;
57459
57460  if (typeof value === 'boolean') {
57461    result = [value];
57462  } else if (value === null || value === undefined) {
57463    result = [1];
57464  } else if (
57465    Array.isArray(value) &&
57466    // `isArray(unknown)` is turned into `any[]`:
57467    // type-coverage:ignore-next-line
57468    primitives$1.has(typeof value[0])
57469  ) {
57470    // `isArray(unknown)` is turned into `any[]`:
57471    // type-coverage:ignore-next-line
57472    result = [...value];
57473  } else {
57474    result = [1, value];
57475  }
57476
57477  let level = result[0];
57478
57479  if (typeof level === 'boolean') {
57480    level = level ? 1 : 0;
57481  } else if (typeof level === 'string') {
57482    if (level === 'off') {
57483      level = 0;
57484    } else if (level === 'on' || level === 'warn') {
57485      level = 1;
57486    } else if (level === 'error') {
57487      level = 2;
57488    } else {
57489      level = 1;
57490      result = [level, result];
57491    }
57492  }
57493
57494  if (typeof level !== 'number' || level < 0 || level > 2) {
57495    throw new Error(
57496      'Incorrect severity `' +
57497        level +
57498        '` for `' +
57499        name +
57500        '`, ' +
57501        'expected 0, 1, or 2'
57502    )
57503  }
57504
57505  result[0] = level;
57506
57507  // @ts-expect-error: it’s now a valid tuple.
57508  return result
57509}
57510
57511/**
57512 * @author Titus Wormer
57513 * @copyright 2015 Titus Wormer
57514 * @license MIT
57515 * @module table-pipes
57516 * @fileoverview
57517 *   Warn when table rows are not fenced with pipes.
57518 *
57519 *   ## Fix
57520 *
57521 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
57522 *   creates fenced rows with initial and final pipes by default.
57523 *
57524 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
57525 *   on how to automatically fix warnings for this rule.
57526 *
57527 * @example
57528 *   {"name": "ok.md", "gfm": true}
57529 *
57530 *   | A     | B     |
57531 *   | ----- | ----- |
57532 *   | Alpha | Bravo |
57533 *
57534 * @example
57535 *   {"name": "not-ok.md", "label": "input", "gfm": true}
57536 *
57537 *   A     | B
57538 *   ----- | -----
57539 *   Alpha | Bravo
57540 *
57541 * @example
57542 *   {"name": "not-ok.md", "label": "output", "gfm": true}
57543 *
57544 *   1:1: Missing initial pipe in table fence
57545 *   1:10: Missing final pipe in table fence
57546 *   3:1: Missing initial pipe in table fence
57547 *   3:14: Missing final pipe in table fence
57548 */
57549
57550const reasonStart = 'Missing initial pipe in table fence';
57551const reasonEnd = 'Missing final pipe in table fence';
57552
57553const remarkLintTablePipes = lintRule$1(
57554  'remark-lint:table-pipes',
57555  /** @type {import('unified-lint-rule').Rule<Root, void>} */
57556  (tree, file) => {
57557    const value = String(file);
57558
57559    visit(tree, 'table', (node) => {
57560      let index = -1;
57561
57562      while (++index < node.children.length) {
57563        const row = node.children[index];
57564        const start = pointStart(row);
57565        const end = pointEnd(row);
57566
57567        if (
57568          typeof start.offset === 'number' &&
57569          value.charCodeAt(start.offset) !== 124
57570        ) {
57571          file.message(reasonStart, start);
57572        }
57573
57574        if (
57575          typeof end.offset === 'number' &&
57576          value.charCodeAt(end.offset - 1) !== 124
57577        ) {
57578          file.message(reasonEnd, end);
57579        }
57580      }
57581    });
57582  }
57583);
57584
57585var remarkLintTablePipes$1 = remarkLintTablePipes;
57586
57587/**
57588 * @typedef {import('unist').Node} Node
57589 * @typedef {import('vfile').VFile} VFile
57590 *
57591 * @typedef {0|1|2} Severity
57592 * @typedef {'warn'|'on'|'off'|'error'} Label
57593 * @typedef {[Severity, ...unknown[]]} SeverityTuple
57594 *
57595 * @callback Rule
57596 * @param {Node} tree
57597 * @param {VFile} file
57598 * @param {unknown} options
57599 * @returns {void}
57600 */
57601
57602const primitives = new Set(['string', 'number', 'boolean']);
57603
57604/**
57605 * @param {string} id
57606 * @param {Rule} rule
57607 */
57608function lintRule(id, rule) {
57609  const parts = id.split(':');
57610  // Possibly useful if externalised later.
57611  /* c8 ignore next */
57612  const source = parts[1] ? parts[0] : undefined;
57613  const ruleId = parts[1];
57614
57615  Object.defineProperty(plugin, 'name', {value: id});
57616
57617  return plugin
57618
57619  /** @type {import('unified').Plugin<[unknown]|void[]>} */
57620  function plugin(raw) {
57621    const [severity, options] = coerce(ruleId, raw);
57622
57623    if (!severity) return
57624
57625    const fatal = severity === 2;
57626
57627    return (tree, file, next) => {
57628      let index = file.messages.length - 1;
57629
57630      wrap(rule, (error) => {
57631        const messages = file.messages;
57632
57633        // Add the error, if not already properly added.
57634        // Only happens for incorrect plugins.
57635        /* c8 ignore next 6 */
57636        // @ts-expect-error: errors could be `messages`.
57637        if (error && !messages.includes(error)) {
57638          try {
57639            file.fail(error);
57640          } catch {}
57641        }
57642
57643        while (++index < messages.length) {
57644          Object.assign(messages[index], {ruleId, source, fatal});
57645        }
57646
57647        next();
57648      })(tree, file, options);
57649    }
57650  }
57651}
57652
57653/**
57654 * Coerce a value to a severity--options tuple.
57655 *
57656 * @param {string} name
57657 * @param {unknown} value
57658 * @returns {SeverityTuple}
57659 */
57660function coerce(name, value) {
57661  /** @type {unknown[]} */
57662  let result;
57663
57664  if (typeof value === 'boolean') {
57665    result = [value];
57666  } else if (value === null || value === undefined) {
57667    result = [1];
57668  } else if (
57669    Array.isArray(value) &&
57670    // `isArray(unknown)` is turned into `any[]`:
57671    // type-coverage:ignore-next-line
57672    primitives.has(typeof value[0])
57673  ) {
57674    // `isArray(unknown)` is turned into `any[]`:
57675    // type-coverage:ignore-next-line
57676    result = [...value];
57677  } else {
57678    result = [1, value];
57679  }
57680
57681  let level = result[0];
57682
57683  if (typeof level === 'boolean') {
57684    level = level ? 1 : 0;
57685  } else if (typeof level === 'string') {
57686    if (level === 'off') {
57687      level = 0;
57688    } else if (level === 'on' || level === 'warn') {
57689      level = 1;
57690    } else if (level === 'error') {
57691      level = 2;
57692    } else {
57693      level = 1;
57694      result = [level, result];
57695    }
57696  }
57697
57698  if (typeof level !== 'number' || level < 0 || level > 2) {
57699    throw new Error(
57700      'Incorrect severity `' +
57701        level +
57702        '` for `' +
57703        name +
57704        '`, ' +
57705        'expected 0, 1, or 2'
57706    )
57707  }
57708
57709  result[0] = level;
57710
57711  // @ts-expect-error: it’s now a valid tuple.
57712  return result
57713}
57714
57715/**
57716 * @author Titus Wormer
57717 * @copyright 2015 Titus Wormer
57718 * @license MIT
57719 * @module unordered-list-marker-style
57720 * @fileoverview
57721 *   Warn when the list item marker style of unordered lists violate a given
57722 *   style.
57723 *
57724 *   Options: `'consistent'`, `'-'`, `'*'`, or `'+'`, default: `'consistent'`.
57725 *
57726 *   `'consistent'` detects the first used list style and warns when subsequent
57727 *   lists use different styles.
57728 *
57729 *   ## Fix
57730 *
57731 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
57732 *   formats unordered lists using `-` (hyphen-minus) by default.
57733 *   Pass
57734 *   [`bullet: '*'` or `bullet: '+'`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionsbullet)
57735 *   to use `*` (asterisk) or `+` (plus sign) instead.
57736 *
57737 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
57738 *   on how to automatically fix warnings for this rule.
57739 *
57740 * @example
57741 *   {"name": "ok.md"}
57742 *
57743 *   By default (`'consistent'`), if the file uses only one marker,
57744 *   that’s OK.
57745 *
57746 *   * Foo
57747 *   * Bar
57748 *   * Baz
57749 *
57750 *   Ordered lists are not affected.
57751 *
57752 *   1. Foo
57753 *   2. Bar
57754 *   3. Baz
57755 *
57756 * @example
57757 *   {"name": "ok.md", "setting": "*"}
57758 *
57759 *   * Foo
57760 *
57761 * @example
57762 *   {"name": "ok.md", "setting": "-"}
57763 *
57764 *   - Foo
57765 *
57766 * @example
57767 *   {"name": "ok.md", "setting": "+"}
57768 *
57769 *   + Foo
57770 *
57771 * @example
57772 *   {"name": "not-ok.md", "label": "input"}
57773 *
57774 *   * Foo
57775 *   - Bar
57776 *   + Baz
57777 *
57778 * @example
57779 *   {"name": "not-ok.md", "label": "output"}
57780 *
57781 *   2:1-2:6: Marker style should be `*`
57782 *   3:1-3:6: Marker style should be `*`
57783 *
57784 * @example
57785 *   {"name": "not-ok.md", "label": "output", "setting": "��", "positionless": true}
57786 *
57787 *   1:1: Incorrect unordered list item marker style `��`: use either `'-'`, `'*'`, or `'+'`
57788 */
57789
57790const markers = new Set(['-', '*', '+']);
57791
57792const remarkLintUnorderedListMarkerStyle = lintRule(
57793  'remark-lint:unordered-list-marker-style',
57794  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
57795  (tree, file, option = 'consistent') => {
57796    const value = String(file);
57797
57798    if (option !== 'consistent' && !markers.has(option)) {
57799      file.fail(
57800        'Incorrect unordered list item marker style `' +
57801          option +
57802          "`: use either `'-'`, `'*'`, or `'+'`"
57803      );
57804    }
57805
57806    visit(tree, 'list', (node) => {
57807      if (node.ordered) return
57808
57809      let index = -1;
57810
57811      while (++index < node.children.length) {
57812        const child = node.children[index];
57813
57814        if (!generated(child)) {
57815          const marker = /** @type {Marker} */ (
57816            value
57817              .slice(
57818                pointStart(child).offset,
57819                pointStart(child.children[0]).offset
57820              )
57821              .replace(/\[[x ]?]\s*$/i, '')
57822              .replace(/\s/g, '')
57823          );
57824
57825          if (option === 'consistent') {
57826            option = marker;
57827          } else if (marker !== option) {
57828            file.message('Marker style should be `' + option + '`', child);
57829          }
57830        }
57831      }
57832    });
57833  }
57834);
57835
57836var remarkLintUnorderedListMarkerStyle$1 = remarkLintUnorderedListMarkerStyle;
57837
57838// @see https://github.com/nodejs/node/blob/HEAD/doc/guides/doc-style-guide.md
57839
57840// Add in rules alphabetically
57841const plugins = [
57842  // Leave preset at the top so it can be overridden
57843  remarkPresetLintRecommended$1,
57844  [remarkLintBlockquoteIndentation$1, 2],
57845  [remarkLintCheckboxCharacterStyle$1, { checked: "x", unchecked: " " }],
57846  remarkLintCheckboxContentIndent$1,
57847  [remarkLintCodeBlockStyle$1, "fenced"],
57848  remarkLintDefinitionSpacing$1,
57849  [
57850    remarkLintFencedCodeFlag$1,
57851    {
57852      flags: [
57853        "bash",
57854        "c",
57855        "cjs",
57856        "coffee",
57857        "console",
57858        "cpp",
57859        "diff",
57860        "http",
57861        "js",
57862        "json",
57863        "markdown",
57864        "mjs",
57865        "powershell",
57866        "r",
57867        "text",
57868      ],
57869    },
57870  ],
57871  [remarkLintFencedCodeMarker$1, "`"],
57872  [remarkLintFileExtension$1, "md"],
57873  remarkLintFinalDefinition$1,
57874  [remarkLintFirstHeadingLevel$1, 1],
57875  [remarkLintHeadingStyle$1, "atx"],
57876  [remarkLintListItemIndent$1, "space"],
57877  remarkLintMaximumLineLength$1,
57878  remarkLintNoConsecutiveBlankLines$1,
57879  remarkLintNoFileNameArticles$1,
57880  remarkLintNoFileNameConsecutiveDashes$1,
57881  remarkLintNofileNameOuterDashes$1,
57882  remarkLintNoHeadingIndent$1,
57883  remarkLintNoMultipleToplevelHeadings$1,
57884  remarkLintNoShellDollars$1,
57885  remarkLintNoTableIndentation$1,
57886  remarkLintNoTabs$1,
57887  remarkLintNoTrailingSpaces,
57888  remarkLintNodejsLinks,
57889  remarkLintNodejsYamlComments,
57890  [
57891    remarkLintProhibitedStrings,
57892    [
57893      { yes: "End-of-Life" },
57894      { yes: "GitHub" },
57895      { no: "hostname", yes: "host name" },
57896      { yes: "JavaScript" },
57897      { no: "[Ll]ong[ -][Tt]erm [Ss]upport", yes: "Long Term Support" },
57898      { no: "Node", yes: "Node.js", ignoreNextTo: "-API" },
57899      { yes: "Node.js" },
57900      { no: "Node[Jj][Ss]", yes: "Node.js" },
57901      { no: "Node\\.js's?", yes: "the Node.js" },
57902      { no: "[Nn]ote that", yes: "<nothing>" },
57903      { yes: "RFC" },
57904      { no: "[Rr][Ff][Cc]\\d+", yes: "RFC <number>" },
57905      { yes: "Unix" },
57906      { yes: "V8" },
57907    ],
57908  ],
57909  remarkLintRuleStyle$1,
57910  [remarkLintStrongMarker$1, "*"],
57911  [remarkLintTableCellPadding$1, "padded"],
57912  remarkLintTablePipes$1,
57913  [remarkLintUnorderedListMarkerStyle$1, "*"],
57914];
57915
57916const remarkPresetLintNode = { plugins };
57917
57918/**
57919 * @typedef {import('micromark-util-types').Extension} Extension
57920 * @typedef {import('micromark-util-types').ConstructRecord} ConstructRecord
57921 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
57922 * @typedef {import('micromark-util-types').Previous} Previous
57923 * @typedef {import('micromark-util-types').State} State
57924 * @typedef {import('micromark-util-types').Event} Event
57925 * @typedef {import('micromark-util-types').Code} Code
57926 */
57927const www = {
57928  tokenize: tokenizeWww,
57929  partial: true
57930};
57931const domain = {
57932  tokenize: tokenizeDomain,
57933  partial: true
57934};
57935const path = {
57936  tokenize: tokenizePath,
57937  partial: true
57938};
57939const punctuation = {
57940  tokenize: tokenizePunctuation,
57941  partial: true
57942};
57943const namedCharacterReference = {
57944  tokenize: tokenizeNamedCharacterReference,
57945  partial: true
57946};
57947const wwwAutolink = {
57948  tokenize: tokenizeWwwAutolink,
57949  previous: previousWww
57950};
57951const httpAutolink = {
57952  tokenize: tokenizeHttpAutolink,
57953  previous: previousHttp
57954};
57955const emailAutolink = {
57956  tokenize: tokenizeEmailAutolink,
57957  previous: previousEmail
57958};
57959/** @type {ConstructRecord} */
57960
57961const text = {};
57962/** @type {Extension} */
57963
57964const gfmAutolinkLiteral = {
57965  text
57966};
57967let code = 48; // Add alphanumerics.
57968
57969while (code < 123) {
57970  text[code] = emailAutolink;
57971  code++;
57972  if (code === 58) code = 65;
57973  else if (code === 91) code = 97;
57974}
57975
57976text[43] = emailAutolink;
57977text[45] = emailAutolink;
57978text[46] = emailAutolink;
57979text[95] = emailAutolink;
57980text[72] = [emailAutolink, httpAutolink];
57981text[104] = [emailAutolink, httpAutolink];
57982text[87] = [emailAutolink, wwwAutolink];
57983text[119] = [emailAutolink, wwwAutolink];
57984/** @type {Tokenizer} */
57985
57986function tokenizeEmailAutolink(effects, ok, nok) {
57987  const self = this;
57988  /** @type {boolean} */
57989
57990  let hasDot;
57991  /** @type {boolean|undefined} */
57992
57993  let hasDigitInLastSegment;
57994  return start
57995  /** @type {State} */
57996
57997  function start(code) {
57998    if (
57999      !gfmAtext(code) ||
58000      !previousEmail(self.previous) ||
58001      previousUnbalanced(self.events)
58002    ) {
58003      return nok(code)
58004    }
58005
58006    effects.enter('literalAutolink');
58007    effects.enter('literalAutolinkEmail');
58008    return atext(code)
58009  }
58010  /** @type {State} */
58011
58012  function atext(code) {
58013    if (gfmAtext(code)) {
58014      effects.consume(code);
58015      return atext
58016    }
58017
58018    if (code === 64) {
58019      effects.consume(code);
58020      return label
58021    }
58022
58023    return nok(code)
58024  }
58025  /** @type {State} */
58026
58027  function label(code) {
58028    if (code === 46) {
58029      return effects.check(punctuation, done, dotContinuation)(code)
58030    }
58031
58032    if (code === 45 || code === 95) {
58033      return effects.check(punctuation, nok, dashOrUnderscoreContinuation)(code)
58034    }
58035
58036    if (asciiAlphanumeric(code)) {
58037      if (!hasDigitInLastSegment && asciiDigit(code)) {
58038        hasDigitInLastSegment = true;
58039      }
58040
58041      effects.consume(code);
58042      return label
58043    }
58044
58045    return done(code)
58046  }
58047  /** @type {State} */
58048
58049  function dotContinuation(code) {
58050    effects.consume(code);
58051    hasDot = true;
58052    hasDigitInLastSegment = undefined;
58053    return label
58054  }
58055  /** @type {State} */
58056
58057  function dashOrUnderscoreContinuation(code) {
58058    effects.consume(code);
58059    return afterDashOrUnderscore
58060  }
58061  /** @type {State} */
58062
58063  function afterDashOrUnderscore(code) {
58064    if (code === 46) {
58065      return effects.check(punctuation, nok, dotContinuation)(code)
58066    }
58067
58068    return label(code)
58069  }
58070  /** @type {State} */
58071
58072  function done(code) {
58073    if (hasDot && !hasDigitInLastSegment) {
58074      effects.exit('literalAutolinkEmail');
58075      effects.exit('literalAutolink');
58076      return ok(code)
58077    }
58078
58079    return nok(code)
58080  }
58081}
58082/** @type {Tokenizer} */
58083
58084function tokenizeWwwAutolink(effects, ok, nok) {
58085  const self = this;
58086  return start
58087  /** @type {State} */
58088
58089  function start(code) {
58090    if (
58091      (code !== 87 && code !== 119) ||
58092      !previousWww(self.previous) ||
58093      previousUnbalanced(self.events)
58094    ) {
58095      return nok(code)
58096    }
58097
58098    effects.enter('literalAutolink');
58099    effects.enter('literalAutolinkWww'); // For `www.` we check instead of attempt, because when it matches, GH
58100    // treats it as part of a domain (yes, it says a valid domain must come
58101    // after `www.`, but that’s not how it’s implemented by them).
58102
58103    return effects.check(
58104      www,
58105      effects.attempt(domain, effects.attempt(path, done), nok),
58106      nok
58107    )(code)
58108  }
58109  /** @type {State} */
58110
58111  function done(code) {
58112    effects.exit('literalAutolinkWww');
58113    effects.exit('literalAutolink');
58114    return ok(code)
58115  }
58116}
58117/** @type {Tokenizer} */
58118
58119function tokenizeHttpAutolink(effects, ok, nok) {
58120  const self = this;
58121  return start
58122  /** @type {State} */
58123
58124  function start(code) {
58125    if (
58126      (code !== 72 && code !== 104) ||
58127      !previousHttp(self.previous) ||
58128      previousUnbalanced(self.events)
58129    ) {
58130      return nok(code)
58131    }
58132
58133    effects.enter('literalAutolink');
58134    effects.enter('literalAutolinkHttp');
58135    effects.consume(code);
58136    return t1
58137  }
58138  /** @type {State} */
58139
58140  function t1(code) {
58141    if (code === 84 || code === 116) {
58142      effects.consume(code);
58143      return t2
58144    }
58145
58146    return nok(code)
58147  }
58148  /** @type {State} */
58149
58150  function t2(code) {
58151    if (code === 84 || code === 116) {
58152      effects.consume(code);
58153      return p
58154    }
58155
58156    return nok(code)
58157  }
58158  /** @type {State} */
58159
58160  function p(code) {
58161    if (code === 80 || code === 112) {
58162      effects.consume(code);
58163      return s
58164    }
58165
58166    return nok(code)
58167  }
58168  /** @type {State} */
58169
58170  function s(code) {
58171    if (code === 83 || code === 115) {
58172      effects.consume(code);
58173      return colon
58174    }
58175
58176    return colon(code)
58177  }
58178  /** @type {State} */
58179
58180  function colon(code) {
58181    if (code === 58) {
58182      effects.consume(code);
58183      return slash1
58184    }
58185
58186    return nok(code)
58187  }
58188  /** @type {State} */
58189
58190  function slash1(code) {
58191    if (code === 47) {
58192      effects.consume(code);
58193      return slash2
58194    }
58195
58196    return nok(code)
58197  }
58198  /** @type {State} */
58199
58200  function slash2(code) {
58201    if (code === 47) {
58202      effects.consume(code);
58203      return after
58204    }
58205
58206    return nok(code)
58207  }
58208  /** @type {State} */
58209
58210  function after(code) {
58211    return code === null ||
58212      asciiControl(code) ||
58213      unicodeWhitespace(code) ||
58214      unicodePunctuation(code)
58215      ? nok(code)
58216      : effects.attempt(domain, effects.attempt(path, done), nok)(code)
58217  }
58218  /** @type {State} */
58219
58220  function done(code) {
58221    effects.exit('literalAutolinkHttp');
58222    effects.exit('literalAutolink');
58223    return ok(code)
58224  }
58225}
58226/** @type {Tokenizer} */
58227
58228function tokenizeWww(effects, ok, nok) {
58229  return start
58230  /** @type {State} */
58231
58232  function start(code) {
58233    effects.consume(code);
58234    return w2
58235  }
58236  /** @type {State} */
58237
58238  function w2(code) {
58239    if (code === 87 || code === 119) {
58240      effects.consume(code);
58241      return w3
58242    }
58243
58244    return nok(code)
58245  }
58246  /** @type {State} */
58247
58248  function w3(code) {
58249    if (code === 87 || code === 119) {
58250      effects.consume(code);
58251      return dot
58252    }
58253
58254    return nok(code)
58255  }
58256  /** @type {State} */
58257
58258  function dot(code) {
58259    if (code === 46) {
58260      effects.consume(code);
58261      return after
58262    }
58263
58264    return nok(code)
58265  }
58266  /** @type {State} */
58267
58268  function after(code) {
58269    return code === null || markdownLineEnding(code) ? nok(code) : ok(code)
58270  }
58271}
58272/** @type {Tokenizer} */
58273
58274function tokenizeDomain(effects, ok, nok) {
58275  /** @type {boolean|undefined} */
58276  let hasUnderscoreInLastSegment;
58277  /** @type {boolean|undefined} */
58278
58279  let hasUnderscoreInLastLastSegment;
58280  return domain
58281  /** @type {State} */
58282
58283  function domain(code) {
58284    if (code === 38) {
58285      return effects.check(
58286        namedCharacterReference,
58287        done,
58288        punctuationContinuation
58289      )(code)
58290    }
58291
58292    if (code === 46 || code === 95) {
58293      return effects.check(punctuation, done, punctuationContinuation)(code)
58294    } // GH documents that only alphanumerics (other than `-`, `.`, and `_`) can
58295    // occur, which sounds like ASCII only, but they also support `www.點看.com`,
58296    // so that’s Unicode.
58297    // Instead of some new production for Unicode alphanumerics, markdown
58298    // already has that for Unicode punctuation and whitespace, so use those.
58299
58300    if (
58301      code === null ||
58302      asciiControl(code) ||
58303      unicodeWhitespace(code) ||
58304      (code !== 45 && unicodePunctuation(code))
58305    ) {
58306      return done(code)
58307    }
58308
58309    effects.consume(code);
58310    return domain
58311  }
58312  /** @type {State} */
58313
58314  function punctuationContinuation(code) {
58315    if (code === 46) {
58316      hasUnderscoreInLastLastSegment = hasUnderscoreInLastSegment;
58317      hasUnderscoreInLastSegment = undefined;
58318      effects.consume(code);
58319      return domain
58320    }
58321
58322    if (code === 95) hasUnderscoreInLastSegment = true;
58323    effects.consume(code);
58324    return domain
58325  }
58326  /** @type {State} */
58327
58328  function done(code) {
58329    if (!hasUnderscoreInLastLastSegment && !hasUnderscoreInLastSegment) {
58330      return ok(code)
58331    }
58332
58333    return nok(code)
58334  }
58335}
58336/** @type {Tokenizer} */
58337
58338function tokenizePath(effects, ok) {
58339  let balance = 0;
58340  return inPath
58341  /** @type {State} */
58342
58343  function inPath(code) {
58344    if (code === 38) {
58345      return effects.check(
58346        namedCharacterReference,
58347        ok,
58348        continuedPunctuation
58349      )(code)
58350    }
58351
58352    if (code === 40) {
58353      balance++;
58354    }
58355
58356    if (code === 41) {
58357      return effects.check(
58358        punctuation,
58359        parenAtPathEnd,
58360        continuedPunctuation
58361      )(code)
58362    }
58363
58364    if (pathEnd(code)) {
58365      return ok(code)
58366    }
58367
58368    if (trailingPunctuation(code)) {
58369      return effects.check(punctuation, ok, continuedPunctuation)(code)
58370    }
58371
58372    effects.consume(code);
58373    return inPath
58374  }
58375  /** @type {State} */
58376
58377  function continuedPunctuation(code) {
58378    effects.consume(code);
58379    return inPath
58380  }
58381  /** @type {State} */
58382
58383  function parenAtPathEnd(code) {
58384    balance--;
58385    return balance < 0 ? ok(code) : continuedPunctuation(code)
58386  }
58387}
58388/** @type {Tokenizer} */
58389
58390function tokenizeNamedCharacterReference(effects, ok, nok) {
58391  return start
58392  /** @type {State} */
58393
58394  function start(code) {
58395    effects.consume(code);
58396    return inside
58397  }
58398  /** @type {State} */
58399
58400  function inside(code) {
58401    if (asciiAlpha(code)) {
58402      effects.consume(code);
58403      return inside
58404    }
58405
58406    if (code === 59) {
58407      effects.consume(code);
58408      return after
58409    }
58410
58411    return nok(code)
58412  }
58413  /** @type {State} */
58414
58415  function after(code) {
58416    // If the named character reference is followed by the end of the path, it’s
58417    // not continued punctuation.
58418    return pathEnd(code) ? ok(code) : nok(code)
58419  }
58420}
58421/** @type {Tokenizer} */
58422
58423function tokenizePunctuation(effects, ok, nok) {
58424  return start
58425  /** @type {State} */
58426
58427  function start(code) {
58428    effects.consume(code);
58429    return after
58430  }
58431  /** @type {State} */
58432
58433  function after(code) {
58434    // Check the next.
58435    if (trailingPunctuation(code)) {
58436      effects.consume(code);
58437      return after
58438    } // If the punctuation marker is followed by the end of the path, it’s not
58439    // continued punctuation.
58440
58441    return pathEnd(code) ? ok(code) : nok(code)
58442  }
58443}
58444/**
58445 * @param {Code} code
58446 * @returns {boolean}
58447 */
58448
58449function trailingPunctuation(code) {
58450  return (
58451    code === 33 ||
58452    code === 34 ||
58453    code === 39 ||
58454    code === 41 ||
58455    code === 42 ||
58456    code === 44 ||
58457    code === 46 ||
58458    code === 58 ||
58459    code === 59 ||
58460    code === 60 ||
58461    code === 63 ||
58462    code === 95 ||
58463    code === 126
58464  )
58465}
58466/**
58467 * @param {Code} code
58468 * @returns {boolean}
58469 */
58470
58471function pathEnd(code) {
58472  return code === null || code === 60 || markdownLineEndingOrSpace(code)
58473}
58474/**
58475 * @param {Code} code
58476 * @returns {boolean}
58477 */
58478
58479function gfmAtext(code) {
58480  return (
58481    code === 43 ||
58482    code === 45 ||
58483    code === 46 ||
58484    code === 95 ||
58485    asciiAlphanumeric(code)
58486  )
58487}
58488/** @type {Previous} */
58489
58490function previousWww(code) {
58491  return (
58492    code === null ||
58493    code === 40 ||
58494    code === 42 ||
58495    code === 95 ||
58496    code === 126 ||
58497    markdownLineEndingOrSpace(code)
58498  )
58499}
58500/** @type {Previous} */
58501
58502function previousHttp(code) {
58503  return code === null || !asciiAlpha(code)
58504}
58505/** @type {Previous} */
58506
58507function previousEmail(code) {
58508  return code !== 47 && previousHttp(code)
58509}
58510/**
58511 * @param {Event[]} events
58512 * @returns {boolean}
58513 */
58514
58515function previousUnbalanced(events) {
58516  let index = events.length;
58517  let result = false;
58518
58519  while (index--) {
58520    const token = events[index][1];
58521
58522    if (
58523      (token.type === 'labelLink' || token.type === 'labelImage') &&
58524      !token._balanced
58525    ) {
58526      result = true;
58527      break
58528    } // @ts-expect-error If we’ve seen this token, and it was marked as not
58529    // having any unbalanced bracket before it, we can exit.
58530
58531    if (token._gfmAutolinkLiteralWalkedInto) {
58532      result = false;
58533      break
58534    }
58535  }
58536
58537  if (events.length > 0 && !result) {
58538    // @ts-expect-error Mark the last token as “walked into” w/o finding
58539    // anything.
58540    events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
58541  }
58542
58543  return result
58544}
58545
58546const characterReferences = {'"': 'quot', '&': 'amp', '<': 'lt', '>': 'gt'};
58547
58548/**
58549 * Encode only the dangerous HTML characters.
58550 *
58551 * This ensures that certain characters which have special meaning in HTML are
58552 * dealt with.
58553 * Technically, we can skip `>` and `"` in many cases, but CM includes them.
58554 *
58555 * @param {string} value
58556 * @returns {string}
58557 */
58558function encode(value) {
58559  return value.replace(/["&<>]/g, replace)
58560
58561  /**
58562   * @param {string} value
58563   * @returns {string}
58564   */
58565  function replace(value) {
58566    // @ts-expect-error Hush, it’s fine.
58567    return '&' + characterReferences[value] + ';'
58568  }
58569}
58570
58571/**
58572 * Make a value safe for injection as a URL.
58573 *
58574 * This encodes unsafe characters with percent-encoding and skips already
58575 * encoded sequences (see `normalizeUri` below).
58576 * Further unsafe characters are encoded as character references (see
58577 * `micromark-util-encode`).
58578 *
58579 * Then, a regex of allowed protocols can be given, in which case the URL is
58580 * sanitized.
58581 * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`,
58582 * or `/^https?$/i` for `img[src]`.
58583 * If the URL includes an unknown protocol (one not matched by `protocol`, such
58584 * as a dangerous example, `javascript:`), the value is ignored.
58585 *
58586 * @param {string|undefined} url
58587 * @param {RegExp} [protocol]
58588 * @returns {string}
58589 */
58590function sanitizeUri(url, protocol) {
58591  const value = encode(normalizeUri(url || ''));
58592
58593  if (!protocol) {
58594    return value
58595  }
58596
58597  const colon = value.indexOf(':');
58598  const questionMark = value.indexOf('?');
58599  const numberSign = value.indexOf('#');
58600  const slash = value.indexOf('/');
58601
58602  if (
58603    // If there is no protocol, it’s relative.
58604    colon < 0 || // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.
58605    (slash > -1 && colon > slash) ||
58606    (questionMark > -1 && colon > questionMark) ||
58607    (numberSign > -1 && colon > numberSign) || // It is a protocol, it should be allowed.
58608    protocol.test(value.slice(0, colon))
58609  ) {
58610    return value
58611  }
58612
58613  return ''
58614}
58615/**
58616 * Normalize a URL (such as used in definitions).
58617 *
58618 * Encode unsafe characters with percent-encoding, skipping already encoded
58619 * sequences.
58620 *
58621 * @param {string} value
58622 * @returns {string}
58623 */
58624
58625function normalizeUri(value) {
58626  /** @type {string[]} */
58627  const result = [];
58628  let index = -1;
58629  let start = 0;
58630  let skip = 0;
58631
58632  while (++index < value.length) {
58633    const code = value.charCodeAt(index);
58634    /** @type {string} */
58635
58636    let replace = ''; // A correct percent encoded value.
58637
58638    if (
58639      code === 37 &&
58640      asciiAlphanumeric(value.charCodeAt(index + 1)) &&
58641      asciiAlphanumeric(value.charCodeAt(index + 2))
58642    ) {
58643      skip = 2;
58644    } // ASCII.
58645    else if (code < 128) {
58646      if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) {
58647        replace = String.fromCharCode(code);
58648      }
58649    } // Astral.
58650    else if (code > 55295 && code < 57344) {
58651      const next = value.charCodeAt(index + 1); // A correct surrogate pair.
58652
58653      if (code < 56320 && next > 56319 && next < 57344) {
58654        replace = String.fromCharCode(code, next);
58655        skip = 1;
58656      } // Lone surrogate.
58657      else {
58658        replace = '\uFFFD';
58659      }
58660    } // Unicode.
58661    else {
58662      replace = String.fromCharCode(code);
58663    }
58664
58665    if (replace) {
58666      result.push(value.slice(start, index), encodeURIComponent(replace));
58667      start = index + skip + 1;
58668      replace = '';
58669    }
58670
58671    if (skip) {
58672      index += skip;
58673      skip = 0;
58674    }
58675  }
58676
58677  return result.join('') + value.slice(start)
58678}
58679
58680/**
58681 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
58682 * @typedef {import('micromark-util-types').Handle} Handle
58683 * @typedef {import('micromark-util-types').CompileContext} CompileContext
58684 * @typedef {import('micromark-util-types').Token} Token
58685 */
58686/** @type {HtmlExtension} */
58687
58688const gfmAutolinkLiteralHtml = {
58689  exit: {
58690    literalAutolinkEmail,
58691    literalAutolinkHttp,
58692    literalAutolinkWww
58693  }
58694};
58695/** @type {Handle} */
58696
58697function literalAutolinkWww(token) {
58698  anchorFromToken.call(this, token, 'http://');
58699}
58700/** @type {Handle} */
58701
58702function literalAutolinkEmail(token) {
58703  anchorFromToken.call(this, token, 'mailto:');
58704}
58705/** @type {Handle} */
58706
58707function literalAutolinkHttp(token) {
58708  anchorFromToken.call(this, token);
58709}
58710/**
58711 * @this CompileContext
58712 * @param {Token} token
58713 * @param {string} [protocol]
58714 * @returns {void}
58715 */
58716
58717function anchorFromToken(token, protocol) {
58718  const url = this.sliceSerialize(token);
58719  this.tag('<a href="' + sanitizeUri((protocol || '') + url) + '">');
58720  this.raw(this.encode(url));
58721  this.tag('</a>');
58722}
58723
58724/**
58725 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
58726 */
58727
58728/** @type {HtmlExtension} */
58729const gfmStrikethroughHtml = {
58730  enter: {
58731    strikethrough() {
58732      this.tag('<del>');
58733    }
58734  },
58735  exit: {
58736    strikethrough() {
58737      this.tag('</del>');
58738    }
58739  }
58740};
58741
58742/**
58743 * @typedef {import('micromark-util-types').Extension} Extension
58744 * @typedef {import('micromark-util-types').Resolver} Resolver
58745 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
58746 * @typedef {import('micromark-util-types').State} State
58747 * @typedef {import('micromark-util-types').Token} Token
58748 * @typedef {import('micromark-util-types').Event} Event
58749 */
58750
58751/**
58752 * @param {Options} [options]
58753 * @returns {Extension}
58754 */
58755function gfmStrikethrough(options = {}) {
58756  let single = options.singleTilde;
58757  const tokenizer = {
58758    tokenize: tokenizeStrikethrough,
58759    resolveAll: resolveAllStrikethrough
58760  };
58761
58762  if (single === null || single === undefined) {
58763    single = true;
58764  }
58765
58766  return {
58767    text: {
58768      [126]: tokenizer
58769    },
58770    insideSpan: {
58771      null: [tokenizer]
58772    }
58773  }
58774  /**
58775   * Take events and resolve strikethrough.
58776   *
58777   * @type {Resolver}
58778   */
58779
58780  function resolveAllStrikethrough(events, context) {
58781    let index = -1;
58782    /** @type {Token} */
58783
58784    let strikethrough;
58785    /** @type {Token} */
58786
58787    let text;
58788    /** @type {number} */
58789
58790    let open;
58791    /** @type {Event[]} */
58792
58793    let nextEvents; // Walk through all events.
58794
58795    while (++index < events.length) {
58796      // Find a token that can close.
58797      if (
58798        events[index][0] === 'enter' &&
58799        events[index][1].type === 'strikethroughSequenceTemporary' &&
58800        events[index][1]._close
58801      ) {
58802        open = index; // Now walk back to find an opener.
58803
58804        while (open--) {
58805          // Find a token that can open the closer.
58806          if (
58807            events[open][0] === 'exit' &&
58808            events[open][1].type === 'strikethroughSequenceTemporary' &&
58809            events[open][1]._open && // If the sizes are the same:
58810            events[index][1].end.offset - events[index][1].start.offset ===
58811              events[open][1].end.offset - events[open][1].start.offset
58812          ) {
58813            events[index][1].type = 'strikethroughSequence';
58814            events[open][1].type = 'strikethroughSequence';
58815            strikethrough = {
58816              type: 'strikethrough',
58817              start: Object.assign({}, events[open][1].start),
58818              end: Object.assign({}, events[index][1].end)
58819            };
58820            text = {
58821              type: 'strikethroughText',
58822              start: Object.assign({}, events[open][1].end),
58823              end: Object.assign({}, events[index][1].start)
58824            }; // Opening.
58825
58826            nextEvents = [
58827              ['enter', strikethrough, context],
58828              ['enter', events[open][1], context],
58829              ['exit', events[open][1], context],
58830              ['enter', text, context]
58831            ]; // Between.
58832
58833            splice(
58834              nextEvents,
58835              nextEvents.length,
58836              0,
58837              resolveAll(
58838                context.parser.constructs.insideSpan.null,
58839                events.slice(open + 1, index),
58840                context
58841              )
58842            ); // Closing.
58843
58844            splice(nextEvents, nextEvents.length, 0, [
58845              ['exit', text, context],
58846              ['enter', events[index][1], context],
58847              ['exit', events[index][1], context],
58848              ['exit', strikethrough, context]
58849            ]);
58850            splice(events, open - 1, index - open + 3, nextEvents);
58851            index = open + nextEvents.length - 2;
58852            break
58853          }
58854        }
58855      }
58856    }
58857
58858    index = -1;
58859
58860    while (++index < events.length) {
58861      if (events[index][1].type === 'strikethroughSequenceTemporary') {
58862        events[index][1].type = 'data';
58863      }
58864    }
58865
58866    return events
58867  }
58868  /** @type {Tokenizer} */
58869
58870  function tokenizeStrikethrough(effects, ok, nok) {
58871    const previous = this.previous;
58872    const events = this.events;
58873    let size = 0;
58874    return start
58875    /** @type {State} */
58876
58877    function start(code) {
58878      if (
58879        code !== 126 ||
58880        (previous === 126 &&
58881          events[events.length - 1][1].type !== 'characterEscape')
58882      ) {
58883        return nok(code)
58884      }
58885
58886      effects.enter('strikethroughSequenceTemporary');
58887      return more(code)
58888    }
58889    /** @type {State} */
58890
58891    function more(code) {
58892      const before = classifyCharacter(previous);
58893
58894      if (code === 126) {
58895        // If this is the third marker, exit.
58896        if (size > 1) return nok(code)
58897        effects.consume(code);
58898        size++;
58899        return more
58900      }
58901
58902      if (size < 2 && !single) return nok(code)
58903      const token = effects.exit('strikethroughSequenceTemporary');
58904      const after = classifyCharacter(code);
58905      token._open = !after || (after === 2 && Boolean(before));
58906      token._close = !before || (before === 2 && Boolean(after));
58907      return ok(code)
58908    }
58909  }
58910}
58911
58912/**
58913 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
58914 */
58915
58916/**
58917 * @typedef {import('./syntax.js').Align} Align
58918 */
58919const alignment = {
58920  null: '',
58921  left: ' align="left"',
58922  right: ' align="right"',
58923  center: ' align="center"'
58924};
58925/** @type {HtmlExtension} */
58926
58927const gfmTableHtml = {
58928  enter: {
58929    table(token) {
58930      this.lineEndingIfNeeded();
58931      this.tag('<table>'); // @ts-expect-error Custom.
58932
58933      this.setData('tableAlign', token._align);
58934    },
58935
58936    tableBody() {
58937      // Clear slurping line ending from the delimiter row.
58938      this.setData('slurpOneLineEnding');
58939      this.tag('<tbody>');
58940    },
58941
58942    tableData() {
58943      /** @type {string|undefined} */
58944      const align = // @ts-expect-error Custom.
58945        alignment[this.getData('tableAlign')[this.getData('tableColumn')]];
58946
58947      if (align === undefined) {
58948        // Capture results to ignore them.
58949        this.buffer();
58950      } else {
58951        this.lineEndingIfNeeded();
58952        this.tag('<td' + align + '>');
58953      }
58954    },
58955
58956    tableHead() {
58957      this.lineEndingIfNeeded();
58958      this.tag('<thead>');
58959    },
58960
58961    tableHeader() {
58962      this.lineEndingIfNeeded();
58963      this.tag(
58964        '<th' + // @ts-expect-error Custom.
58965          alignment[this.getData('tableAlign')[this.getData('tableColumn')]] +
58966          '>'
58967      );
58968    },
58969
58970    tableRow() {
58971      this.setData('tableColumn', 0);
58972      this.lineEndingIfNeeded();
58973      this.tag('<tr>');
58974    }
58975  },
58976  exit: {
58977    // Overwrite the default code text data handler to unescape escaped pipes when
58978    // they are in tables.
58979    codeTextData(token) {
58980      let value = this.sliceSerialize(token);
58981
58982      if (this.getData('tableAlign')) {
58983        value = value.replace(/\\([\\|])/g, replace$1);
58984      }
58985
58986      this.raw(this.encode(value));
58987    },
58988
58989    table() {
58990      this.setData('tableAlign'); // If there was no table body, make sure the slurping from the delimiter row
58991      // is cleared.
58992
58993      this.setData('slurpAllLineEndings');
58994      this.lineEndingIfNeeded();
58995      this.tag('</table>');
58996    },
58997
58998    tableBody() {
58999      this.lineEndingIfNeeded();
59000      this.tag('</tbody>');
59001    },
59002
59003    tableData() {
59004      /** @type {number} */
59005      // @ts-expect-error Custom.
59006      const column = this.getData('tableColumn'); // @ts-expect-error Custom.
59007
59008      if (column in this.getData('tableAlign')) {
59009        this.tag('</td>');
59010        this.setData('tableColumn', column + 1);
59011      } else {
59012        // Stop capturing.
59013        this.resume();
59014      }
59015    },
59016
59017    tableHead() {
59018      this.lineEndingIfNeeded();
59019      this.tag('</thead>');
59020      this.setData('slurpOneLineEnding', true); // Slurp the line ending from the delimiter row.
59021    },
59022
59023    tableHeader() {
59024      this.tag('</th>'); // @ts-expect-error Custom.
59025
59026      this.setData('tableColumn', this.getData('tableColumn') + 1);
59027    },
59028
59029    tableRow() {
59030      /** @type {Align[]} */
59031      // @ts-expect-error Custom.
59032      const align = this.getData('tableAlign');
59033      /** @type {number} */
59034      // @ts-expect-error Custom.
59035
59036      let column = this.getData('tableColumn');
59037
59038      while (column < align.length) {
59039        this.lineEndingIfNeeded(); // @ts-expect-error `null` is fine as an index.
59040
59041        this.tag('<td' + alignment[align[column]] + '></td>');
59042        column++;
59043      }
59044
59045      this.setData('tableColumn', column);
59046      this.lineEndingIfNeeded();
59047      this.tag('</tr>');
59048    }
59049  }
59050};
59051/**
59052 * @param {string} $0
59053 * @param {string} $1
59054 * @returns {string}
59055 */
59056
59057function replace$1($0, $1) {
59058  // Pipes work, backslashes don’t (but can’t escape pipes).
59059  return $1 === '|' ? $1 : $0
59060}
59061
59062/**
59063 * @typedef {import('micromark-util-types').Extension} Extension
59064 * @typedef {import('micromark-util-types').Resolver} Resolver
59065 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
59066 * @typedef {import('micromark-util-types').State} State
59067 * @typedef {import('micromark-util-types').Token} Token
59068 */
59069
59070/** @type {Extension} */
59071const gfmTable = {
59072  flow: {
59073    null: {
59074      tokenize: tokenizeTable,
59075      resolve: resolveTable
59076    }
59077  }
59078};
59079const setextUnderlineMini = {
59080  tokenize: tokenizeSetextUnderlineMini,
59081  partial: true
59082};
59083const nextPrefixedOrBlank = {
59084  tokenize: tokenizeNextPrefixedOrBlank,
59085  partial: true
59086};
59087/** @type {Resolver} */
59088
59089function resolveTable(events, context) {
59090  let index = -1;
59091  /** @type {Token} */
59092
59093  let token;
59094  /** @type {boolean|undefined} */
59095
59096  let inHead;
59097  /** @type {boolean|undefined} */
59098
59099  let inDelimiterRow;
59100  /** @type {boolean|undefined} */
59101
59102  let inRow;
59103  /** @type {Token} */
59104
59105  let cell;
59106  /** @type {Token} */
59107
59108  let content;
59109  /** @type {Token} */
59110
59111  let text;
59112  /** @type {number|undefined} */
59113
59114  let contentStart;
59115  /** @type {number|undefined} */
59116
59117  let contentEnd;
59118  /** @type {number|undefined} */
59119
59120  let cellStart;
59121
59122  while (++index < events.length) {
59123    token = events[index][1];
59124
59125    if (inRow) {
59126      if (token.type === 'temporaryTableCellContent') {
59127        contentStart = contentStart || index;
59128        contentEnd = index;
59129      }
59130
59131      if (
59132        // Combine separate content parts into one.
59133        (token.type === 'tableCellDivider' || token.type === 'tableRow') &&
59134        contentEnd
59135      ) {
59136        content = {
59137          type: 'tableContent',
59138          // @ts-expect-error `contentStart` is defined if `contentEnd` is too.
59139          start: events[contentStart][1].start,
59140          end: events[contentEnd][1].end
59141        };
59142        text = {
59143          type: 'chunkText',
59144          start: content.start,
59145          end: content.end,
59146          // @ts-expect-error It’s fine.
59147          contentType: 'text'
59148        };
59149        events.splice(
59150          // @ts-expect-error `contentStart` is defined if `contentEnd` is too.
59151          contentStart, // @ts-expect-error `contentStart` is defined if `contentEnd` is too.
59152          contentEnd - contentStart + 1,
59153          ['enter', content, context],
59154          ['enter', text, context],
59155          ['exit', text, context],
59156          ['exit', content, context]
59157        ); // @ts-expect-error `contentStart` is defined if `contentEnd` is too.
59158
59159        index -= contentEnd - contentStart - 3;
59160        contentStart = undefined;
59161        contentEnd = undefined;
59162      }
59163    }
59164
59165    if (
59166      events[index][0] === 'exit' &&
59167      cellStart &&
59168      cellStart + 1 < index &&
59169      (token.type === 'tableCellDivider' ||
59170        (token.type === 'tableRow' &&
59171          (cellStart + 3 < index ||
59172            events[cellStart][1].type !== 'whitespace')))
59173    ) {
59174      cell = {
59175        type: inDelimiterRow
59176          ? 'tableDelimiter'
59177          : inHead
59178          ? 'tableHeader'
59179          : 'tableData',
59180        start: events[cellStart][1].start,
59181        end: events[index][1].end
59182      };
59183      events.splice(index + (token.type === 'tableCellDivider' ? 1 : 0), 0, [
59184        'exit',
59185        cell,
59186        context
59187      ]);
59188      events.splice(cellStart, 0, ['enter', cell, context]);
59189      index += 2;
59190      cellStart = index + 1;
59191    }
59192
59193    if (token.type === 'tableRow') {
59194      inRow = events[index][0] === 'enter';
59195
59196      if (inRow) {
59197        cellStart = index + 1;
59198      }
59199    }
59200
59201    if (token.type === 'tableDelimiterRow') {
59202      inDelimiterRow = events[index][0] === 'enter';
59203
59204      if (inDelimiterRow) {
59205        cellStart = index + 1;
59206      }
59207    }
59208
59209    if (token.type === 'tableHead') {
59210      inHead = events[index][0] === 'enter';
59211    }
59212  }
59213
59214  return events
59215}
59216/** @type {Tokenizer} */
59217
59218function tokenizeTable(effects, ok, nok) {
59219  const self = this;
59220  /** @type {Align[]} */
59221
59222  const align = [];
59223  let tableHeaderCount = 0;
59224  /** @type {boolean|undefined} */
59225
59226  let seenDelimiter;
59227  /** @type {boolean|undefined} */
59228
59229  let hasDash;
59230  return start
59231  /** @type {State} */
59232
59233  function start(code) {
59234    // @ts-expect-error Custom.
59235    effects.enter('table')._align = align;
59236    effects.enter('tableHead');
59237    effects.enter('tableRow'); // If we start with a pipe, we open a cell marker.
59238
59239    if (code === 124) {
59240      return cellDividerHead(code)
59241    }
59242
59243    tableHeaderCount++;
59244    effects.enter('temporaryTableCellContent'); // Can’t be space or eols at the start of a construct, so we’re in a cell.
59245
59246    return inCellContentHead(code)
59247  }
59248  /** @type {State} */
59249
59250  function cellDividerHead(code) {
59251    effects.enter('tableCellDivider');
59252    effects.consume(code);
59253    effects.exit('tableCellDivider');
59254    seenDelimiter = true;
59255    return cellBreakHead
59256  }
59257  /** @type {State} */
59258
59259  function cellBreakHead(code) {
59260    if (code === null || markdownLineEnding(code)) {
59261      return atRowEndHead(code)
59262    }
59263
59264    if (markdownSpace(code)) {
59265      effects.enter('whitespace');
59266      effects.consume(code);
59267      return inWhitespaceHead
59268    }
59269
59270    if (seenDelimiter) {
59271      seenDelimiter = undefined;
59272      tableHeaderCount++;
59273    }
59274
59275    if (code === 124) {
59276      return cellDividerHead(code)
59277    } // Anything else is cell content.
59278
59279    effects.enter('temporaryTableCellContent');
59280    return inCellContentHead(code)
59281  }
59282  /** @type {State} */
59283
59284  function inWhitespaceHead(code) {
59285    if (markdownSpace(code)) {
59286      effects.consume(code);
59287      return inWhitespaceHead
59288    }
59289
59290    effects.exit('whitespace');
59291    return cellBreakHead(code)
59292  }
59293  /** @type {State} */
59294
59295  function inCellContentHead(code) {
59296    // EOF, whitespace, pipe
59297    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {
59298      effects.exit('temporaryTableCellContent');
59299      return cellBreakHead(code)
59300    }
59301
59302    effects.consume(code);
59303    return code === 92 ? inCellContentEscapeHead : inCellContentHead
59304  }
59305  /** @type {State} */
59306
59307  function inCellContentEscapeHead(code) {
59308    if (code === 92 || code === 124) {
59309      effects.consume(code);
59310      return inCellContentHead
59311    } // Anything else.
59312
59313    return inCellContentHead(code)
59314  }
59315  /** @type {State} */
59316
59317  function atRowEndHead(code) {
59318    if (code === null) {
59319      return nok(code)
59320    }
59321
59322    effects.exit('tableRow');
59323    effects.exit('tableHead');
59324    return effects.attempt(
59325      {
59326        tokenize: tokenizeRowEnd,
59327        partial: true
59328      },
59329      atDelimiterLineStart,
59330      nok
59331    )(code)
59332  }
59333  /** @type {State} */
59334
59335  function atDelimiterLineStart(code) {
59336    // To do: is the lazy setext thing still needed?
59337    return effects.check(
59338      setextUnderlineMini,
59339      nok, // Support an indent before the delimiter row.
59340      factorySpace(effects, rowStartDelimiter, 'linePrefix', 4)
59341    )(code)
59342  }
59343  /** @type {State} */
59344
59345  function rowStartDelimiter(code) {
59346    // If there’s another space, or we’re at the EOL/EOF, exit.
59347    if (code === null || markdownLineEndingOrSpace(code)) {
59348      return nok(code)
59349    }
59350
59351    effects.enter('tableDelimiterRow');
59352    return atDelimiterRowBreak(code)
59353  }
59354  /** @type {State} */
59355
59356  function atDelimiterRowBreak(code) {
59357    if (code === null || markdownLineEnding(code)) {
59358      return rowEndDelimiter(code)
59359    }
59360
59361    if (markdownSpace(code)) {
59362      effects.enter('whitespace');
59363      effects.consume(code);
59364      return inWhitespaceDelimiter
59365    }
59366
59367    if (code === 45) {
59368      effects.enter('tableDelimiterFiller');
59369      effects.consume(code);
59370      hasDash = true;
59371      align.push(null);
59372      return inFillerDelimiter
59373    }
59374
59375    if (code === 58) {
59376      effects.enter('tableDelimiterAlignment');
59377      effects.consume(code);
59378      effects.exit('tableDelimiterAlignment');
59379      align.push('left');
59380      return afterLeftAlignment
59381    } // If we start with a pipe, we open a cell marker.
59382
59383    if (code === 124) {
59384      effects.enter('tableCellDivider');
59385      effects.consume(code);
59386      effects.exit('tableCellDivider');
59387      return atDelimiterRowBreak
59388    }
59389
59390    return nok(code)
59391  }
59392  /** @type {State} */
59393
59394  function inWhitespaceDelimiter(code) {
59395    if (markdownSpace(code)) {
59396      effects.consume(code);
59397      return inWhitespaceDelimiter
59398    }
59399
59400    effects.exit('whitespace');
59401    return atDelimiterRowBreak(code)
59402  }
59403  /** @type {State} */
59404
59405  function inFillerDelimiter(code) {
59406    if (code === 45) {
59407      effects.consume(code);
59408      return inFillerDelimiter
59409    }
59410
59411    effects.exit('tableDelimiterFiller');
59412
59413    if (code === 58) {
59414      effects.enter('tableDelimiterAlignment');
59415      effects.consume(code);
59416      effects.exit('tableDelimiterAlignment');
59417      align[align.length - 1] =
59418        align[align.length - 1] === 'left' ? 'center' : 'right';
59419      return afterRightAlignment
59420    }
59421
59422    return atDelimiterRowBreak(code)
59423  }
59424  /** @type {State} */
59425
59426  function afterLeftAlignment(code) {
59427    if (code === 45) {
59428      effects.enter('tableDelimiterFiller');
59429      effects.consume(code);
59430      hasDash = true;
59431      return inFillerDelimiter
59432    } // Anything else is not ok.
59433
59434    return nok(code)
59435  }
59436  /** @type {State} */
59437
59438  function afterRightAlignment(code) {
59439    if (code === null || markdownLineEnding(code)) {
59440      return rowEndDelimiter(code)
59441    }
59442
59443    if (markdownSpace(code)) {
59444      effects.enter('whitespace');
59445      effects.consume(code);
59446      return inWhitespaceDelimiter
59447    } // `|`
59448
59449    if (code === 124) {
59450      effects.enter('tableCellDivider');
59451      effects.consume(code);
59452      effects.exit('tableCellDivider');
59453      return atDelimiterRowBreak
59454    }
59455
59456    return nok(code)
59457  }
59458  /** @type {State} */
59459
59460  function rowEndDelimiter(code) {
59461    effects.exit('tableDelimiterRow'); // Exit if there was no dash at all, or if the header cell count is not the
59462    // delimiter cell count.
59463
59464    if (!hasDash || tableHeaderCount !== align.length) {
59465      return nok(code)
59466    }
59467
59468    if (code === null) {
59469      return tableClose(code)
59470    }
59471
59472    return effects.check(
59473      nextPrefixedOrBlank,
59474      tableClose,
59475      effects.attempt(
59476        {
59477          tokenize: tokenizeRowEnd,
59478          partial: true
59479        },
59480        factorySpace(effects, bodyStart, 'linePrefix', 4),
59481        tableClose
59482      )
59483    )(code)
59484  }
59485  /** @type {State} */
59486
59487  function tableClose(code) {
59488    effects.exit('table');
59489    return ok(code)
59490  }
59491  /** @type {State} */
59492
59493  function bodyStart(code) {
59494    effects.enter('tableBody');
59495    return rowStartBody(code)
59496  }
59497  /** @type {State} */
59498
59499  function rowStartBody(code) {
59500    effects.enter('tableRow'); // If we start with a pipe, we open a cell marker.
59501
59502    if (code === 124) {
59503      return cellDividerBody(code)
59504    }
59505
59506    effects.enter('temporaryTableCellContent'); // Can’t be space or eols at the start of a construct, so we’re in a cell.
59507
59508    return inCellContentBody(code)
59509  }
59510  /** @type {State} */
59511
59512  function cellDividerBody(code) {
59513    effects.enter('tableCellDivider');
59514    effects.consume(code);
59515    effects.exit('tableCellDivider');
59516    return cellBreakBody
59517  }
59518  /** @type {State} */
59519
59520  function cellBreakBody(code) {
59521    if (code === null || markdownLineEnding(code)) {
59522      return atRowEndBody(code)
59523    }
59524
59525    if (markdownSpace(code)) {
59526      effects.enter('whitespace');
59527      effects.consume(code);
59528      return inWhitespaceBody
59529    } // `|`
59530
59531    if (code === 124) {
59532      return cellDividerBody(code)
59533    } // Anything else is cell content.
59534
59535    effects.enter('temporaryTableCellContent');
59536    return inCellContentBody(code)
59537  }
59538  /** @type {State} */
59539
59540  function inWhitespaceBody(code) {
59541    if (markdownSpace(code)) {
59542      effects.consume(code);
59543      return inWhitespaceBody
59544    }
59545
59546    effects.exit('whitespace');
59547    return cellBreakBody(code)
59548  }
59549  /** @type {State} */
59550
59551  function inCellContentBody(code) {
59552    // EOF, whitespace, pipe
59553    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {
59554      effects.exit('temporaryTableCellContent');
59555      return cellBreakBody(code)
59556    }
59557
59558    effects.consume(code);
59559    return code === 92 ? inCellContentEscapeBody : inCellContentBody
59560  }
59561  /** @type {State} */
59562
59563  function inCellContentEscapeBody(code) {
59564    if (code === 92 || code === 124) {
59565      effects.consume(code);
59566      return inCellContentBody
59567    } // Anything else.
59568
59569    return inCellContentBody(code)
59570  }
59571  /** @type {State} */
59572
59573  function atRowEndBody(code) {
59574    effects.exit('tableRow');
59575
59576    if (code === null) {
59577      return tableBodyClose(code)
59578    }
59579
59580    return effects.check(
59581      nextPrefixedOrBlank,
59582      tableBodyClose,
59583      effects.attempt(
59584        {
59585          tokenize: tokenizeRowEnd,
59586          partial: true
59587        },
59588        factorySpace(effects, rowStartBody, 'linePrefix', 4),
59589        tableBodyClose
59590      )
59591    )(code)
59592  }
59593  /** @type {State} */
59594
59595  function tableBodyClose(code) {
59596    effects.exit('tableBody');
59597    return tableClose(code)
59598  }
59599  /** @type {Tokenizer} */
59600
59601  function tokenizeRowEnd(effects, ok, nok) {
59602    return start
59603    /** @type {State} */
59604
59605    function start(code) {
59606      effects.enter('lineEnding');
59607      effects.consume(code);
59608      effects.exit('lineEnding');
59609      return lineStart
59610    }
59611    /** @type {State} */
59612
59613    function lineStart(code) {
59614      return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
59615    }
59616  }
59617} // Based on micromark, but that won’t work as we’re in a table, and that expects
59618// content.
59619// <https://github.com/micromark/micromark/blob/main/lib/tokenize/setext-underline.js>
59620
59621/** @type {Tokenizer} */
59622
59623function tokenizeSetextUnderlineMini(effects, ok, nok) {
59624  return start
59625  /** @type {State} */
59626
59627  function start(code) {
59628    if (code !== 45) {
59629      return nok(code)
59630    }
59631
59632    effects.enter('setextUnderline');
59633    return sequence(code)
59634  }
59635  /** @type {State} */
59636
59637  function sequence(code) {
59638    if (code === 45) {
59639      effects.consume(code);
59640      return sequence
59641    }
59642
59643    return whitespace(code)
59644  }
59645  /** @type {State} */
59646
59647  function whitespace(code) {
59648    if (code === null || markdownLineEnding(code)) {
59649      return ok(code)
59650    }
59651
59652    if (markdownSpace(code)) {
59653      effects.consume(code);
59654      return whitespace
59655    }
59656
59657    return nok(code)
59658  }
59659}
59660/** @type {Tokenizer} */
59661
59662function tokenizeNextPrefixedOrBlank(effects, ok, nok) {
59663  let size = 0;
59664  return start
59665  /** @type {State} */
59666
59667  function start(code) {
59668    // This is a check, so we don’t care about tokens, but we open a bogus one
59669    // so we’re valid.
59670    effects.enter('check'); // EOL.
59671
59672    effects.consume(code);
59673    return whitespace
59674  }
59675  /** @type {State} */
59676
59677  function whitespace(code) {
59678    if (code === -1 || code === 32) {
59679      effects.consume(code);
59680      size++;
59681      return size === 4 ? ok : whitespace
59682    } // EOF or whitespace
59683
59684    if (code === null || markdownLineEndingOrSpace(code)) {
59685      return ok(code)
59686    } // Anything else.
59687
59688    return nok(code)
59689  }
59690}
59691
59692/**
59693 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
59694 * @typedef {import('micromark-util-types').Token} Token
59695 * @typedef {import('micromark-util-types').CompileContext} CompileContext
59696 */
59697
59698/**
59699 * An opening or closing tag, followed by a case-insensitive specific tag name,
59700 * followed by HTML whitespace, a greater than, or a slash.
59701 */
59702const reFlow =
59703  /<(\/?)(iframe|noembed|noframes|plaintext|script|style|title|textarea|xmp)(?=[\t\n\f\r />])/gi;
59704
59705/**
59706 * As HTML (text) parses tags separately (and v. strictly), we don’t need to be
59707 * global.
59708 */
59709const reText = new RegExp('^' + reFlow.source, 'i');
59710
59711/** @type {HtmlExtension} */
59712const gfmTagfilterHtml = {
59713  exit: {
59714    htmlFlowData(token) {
59715      exitHtmlData.call(this, token, reFlow);
59716    },
59717    htmlTextData(token) {
59718      exitHtmlData.call(this, token, reText);
59719    }
59720  }
59721};
59722
59723/**
59724 * @this {CompileContext}
59725 * @param {Token} token
59726 * @param {RegExp} filter
59727 */
59728function exitHtmlData(token, filter) {
59729  let value = this.sliceSerialize(token);
59730
59731  if (this.options.allowDangerousHtml) {
59732    value = value.replace(filter, '&lt;$1$2');
59733  }
59734
59735  this.raw(this.encode(value));
59736}
59737
59738/**
59739 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
59740 */
59741
59742/** @type {HtmlExtension} */
59743const gfmTaskListItemHtml = {
59744  enter: {
59745    taskListCheck() {
59746      this.tag('<input ');
59747    }
59748  },
59749  exit: {
59750    taskListCheck() {
59751      this.tag('disabled="" type="checkbox">');
59752    },
59753
59754    taskListCheckValueChecked() {
59755      this.tag('checked="" ');
59756    }
59757  }
59758};
59759
59760/**
59761 * @typedef {import('micromark-util-types').Extension} Extension
59762 * @typedef {import('micromark-util-types').ConstructRecord} ConstructRecord
59763 * @typedef {import('micromark-util-types').Tokenizer} Tokenizer
59764 * @typedef {import('micromark-util-types').Previous} Previous
59765 * @typedef {import('micromark-util-types').State} State
59766 * @typedef {import('micromark-util-types').Event} Event
59767 * @typedef {import('micromark-util-types').Code} Code
59768 */
59769const tasklistCheck = {
59770  tokenize: tokenizeTasklistCheck
59771};
59772const gfmTaskListItem = {
59773  text: {
59774    [91]: tasklistCheck
59775  }
59776};
59777/** @type {Tokenizer} */
59778
59779function tokenizeTasklistCheck(effects, ok, nok) {
59780  const self = this;
59781  return open
59782  /** @type {State} */
59783
59784  function open(code) {
59785    if (
59786      // Exit if there’s stuff before.
59787      self.previous !== null || // Exit if not in the first content that is the first child of a list
59788      // item.
59789      !self._gfmTasklistFirstContentOfListItem
59790    ) {
59791      return nok(code)
59792    }
59793
59794    effects.enter('taskListCheck');
59795    effects.enter('taskListCheckMarker');
59796    effects.consume(code);
59797    effects.exit('taskListCheckMarker');
59798    return inside
59799  }
59800  /** @type {State} */
59801
59802  function inside(code) {
59803    if (markdownSpace(code)) {
59804      effects.enter('taskListCheckValueUnchecked');
59805      effects.consume(code);
59806      effects.exit('taskListCheckValueUnchecked');
59807      return close
59808    }
59809
59810    if (code === 88 || code === 120) {
59811      effects.enter('taskListCheckValueChecked');
59812      effects.consume(code);
59813      effects.exit('taskListCheckValueChecked');
59814      return close
59815    }
59816
59817    return nok(code)
59818  }
59819  /** @type {State} */
59820
59821  function close(code) {
59822    if (code === 93) {
59823      effects.enter('taskListCheckMarker');
59824      effects.consume(code);
59825      effects.exit('taskListCheckMarker');
59826      effects.exit('taskListCheck');
59827      return effects.check(
59828        {
59829          tokenize: spaceThenNonSpace
59830        },
59831        ok,
59832        nok
59833      )
59834    }
59835
59836    return nok(code)
59837  }
59838}
59839/** @type {Tokenizer} */
59840
59841function spaceThenNonSpace(effects, ok, nok) {
59842  const self = this;
59843  return factorySpace(effects, after, 'whitespace')
59844  /** @type {State} */
59845
59846  function after(code) {
59847    const tail = self.events[self.events.length - 1];
59848    return tail &&
59849      tail[1].type === 'whitespace' &&
59850      code !== null &&
59851      !markdownLineEndingOrSpace(code)
59852      ? ok(code)
59853      : nok(code)
59854  }
59855}
59856
59857/**
59858 * @typedef {import('micromark-util-types').Extension} Extension
59859 * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension
59860 * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options
59861 */
59862
59863/**
59864 * Support GFM or markdown on github.com.
59865 *
59866 * @param {Options} [options]
59867 * @returns {Extension}
59868 */
59869function gfm(options) {
59870  return combineExtensions([
59871    gfmAutolinkLiteral,
59872    gfmStrikethrough(options),
59873    gfmTable,
59874    gfmTaskListItem
59875  ])
59876}
59877
59878/** @type {HtmlExtension} */
59879combineHtmlExtensions([
59880  gfmAutolinkLiteralHtml,
59881  gfmStrikethroughHtml,
59882  gfmTableHtml,
59883  gfmTagfilterHtml,
59884  gfmTaskListItemHtml
59885]);
59886
59887/**
59888 * Get the total count of `character` in `value`.
59889 *
59890 * @param {any} value Content, coerced to string
59891 * @param {string} character Single character to look for
59892 * @return {number} Number of times `character` occurred in `value`.
59893 */
59894function ccount(value, character) {
59895  var source = String(value);
59896  var count = 0;
59897  var index;
59898
59899  if (typeof character !== 'string') {
59900    throw new Error('Expected character')
59901  }
59902
59903  index = source.indexOf(character);
59904
59905  while (index !== -1) {
59906    count++;
59907    index = source.indexOf(character, index + character.length);
59908  }
59909
59910  return count
59911}
59912
59913/**
59914 * @param {string} d
59915 * @returns {string}
59916 */
59917function color(d) {
59918  return '\u001B[33m' + d + '\u001B[39m'
59919}
59920
59921/**
59922 * @typedef {import('unist').Node} Node
59923 * @typedef {import('unist').Parent} Parent
59924 * @typedef {import('unist-util-is').Test} Test
59925 */
59926
59927/**
59928 * Continue traversing as normal
59929 */
59930const CONTINUE = true;
59931/**
59932 * Do not traverse this node’s children
59933 */
59934const SKIP = 'skip';
59935/**
59936 * Stop traversing immediately
59937 */
59938const EXIT = false;
59939
59940const visitParents =
59941  /**
59942   * @type {(
59943   *   (<T extends Node>(tree: Node, test: T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>|Array.<T['type']|Partial<T>|import('unist-util-is').TestFunctionPredicate<T>>, visitor: Visitor<T>, reverse?: boolean) => void) &
59944   *   ((tree: Node, test: Test, visitor: Visitor<Node>, reverse?: boolean) => void) &
59945   *   ((tree: Node, visitor: Visitor<Node>, reverse?: boolean) => void)
59946   * )}
59947   */
59948  (
59949    /**
59950     * Visit children of tree which pass a test
59951     *
59952     * @param {Node} tree Abstract syntax tree to walk
59953     * @param {Test} test test Test node
59954     * @param {Visitor<Node>} visitor Function to run for each node
59955     * @param {boolean} [reverse] Fisit the tree in reverse, defaults to false
59956     */
59957    function (tree, test, visitor, reverse) {
59958      if (typeof test === 'function' && typeof visitor !== 'function') {
59959        reverse = visitor;
59960        // @ts-ignore no visitor given, so `visitor` is test.
59961        visitor = test;
59962        test = null;
59963      }
59964
59965      var is = convert(test);
59966      var step = reverse ? -1 : 1;
59967
59968      factory(tree, null, [])();
59969
59970      /**
59971       * @param {Node} node
59972       * @param {number?} index
59973       * @param {Array.<Parent>} parents
59974       */
59975      function factory(node, index, parents) {
59976        /** @type {Object.<string, unknown>} */
59977        var value = typeof node === 'object' && node !== null ? node : {};
59978        /** @type {string} */
59979        var name;
59980
59981        if (typeof value.type === 'string') {
59982          name =
59983            typeof value.tagName === 'string'
59984              ? value.tagName
59985              : typeof value.name === 'string'
59986              ? value.name
59987              : undefined;
59988
59989          Object.defineProperty(visit, 'name', {
59990            value:
59991              'node (' +
59992              color(value.type + (name ? '<' + name + '>' : '')) +
59993              ')'
59994          });
59995        }
59996
59997        return visit
59998
59999        function visit() {
60000          /** @type {ActionTuple} */
60001          var result = [];
60002          /** @type {ActionTuple} */
60003          var subresult;
60004          /** @type {number} */
60005          var offset;
60006          /** @type {Array.<Parent>} */
60007          var grandparents;
60008
60009          if (!test || is(node, index, parents[parents.length - 1] || null)) {
60010            result = toResult(visitor(node, parents));
60011
60012            if (result[0] === EXIT) {
60013              return result
60014            }
60015          }
60016
60017          if (node.children && result[0] !== SKIP) {
60018            // @ts-ignore looks like a parent.
60019            offset = (reverse ? node.children.length : -1) + step;
60020            // @ts-ignore looks like a parent.
60021            grandparents = parents.concat(node);
60022
60023            // @ts-ignore looks like a parent.
60024            while (offset > -1 && offset < node.children.length) {
60025              subresult = factory(node.children[offset], offset, grandparents)();
60026
60027              if (subresult[0] === EXIT) {
60028                return subresult
60029              }
60030
60031              offset =
60032                typeof subresult[1] === 'number' ? subresult[1] : offset + step;
60033            }
60034          }
60035
60036          return result
60037        }
60038      }
60039    }
60040  );
60041
60042/**
60043 * @param {VisitorResult} value
60044 * @returns {ActionTuple}
60045 */
60046function toResult(value) {
60047  if (Array.isArray(value)) {
60048    return value
60049  }
60050
60051  if (typeof value === 'number') {
60052    return [CONTINUE, value]
60053  }
60054
60055  return [value]
60056}
60057
60058/**
60059 * @typedef Options Configuration.
60060 * @property {Test} [ignore] `unist-util-is` test used to assert parents
60061 *
60062 * @typedef {import('mdast').Root} Root
60063 * @typedef {import('mdast').Content} Content
60064 * @typedef {import('mdast').PhrasingContent} PhrasingContent
60065 * @typedef {import('mdast').Text} Text
60066 * @typedef {Content|Root} Node
60067 * @typedef {Extract<Node, import('mdast').Parent>} Parent
60068 *
60069 * @typedef {import('unist-util-visit-parents').Test} Test
60070 * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult
60071 *
60072 * @typedef RegExpMatchObject
60073 * @property {number} index
60074 * @property {string} input
60075 *
60076 * @typedef {string|RegExp} Find
60077 * @typedef {string|ReplaceFunction} Replace
60078 *
60079 * @typedef {[Find, Replace]} FindAndReplaceTuple
60080 * @typedef {Object.<string, Replace>} FindAndReplaceSchema
60081 * @typedef {Array.<FindAndReplaceTuple>} FindAndReplaceList
60082 *
60083 * @typedef {[RegExp, ReplaceFunction]} Pair
60084 * @typedef {Array.<Pair>} Pairs
60085 */
60086
60087const own = {}.hasOwnProperty;
60088
60089/**
60090 * @param tree mdast tree
60091 * @param find Value to find and remove. When `string`, escaped and made into a global `RegExp`
60092 * @param [replace] Value to insert.
60093 *   * When `string`, turned into a Text node.
60094 *   * When `Function`, called with the results of calling `RegExp.exec` as
60095 *     arguments, in which case it can return a single or a list of `Node`,
60096 *     a `string` (which is wrapped in a `Text` node), or `false` to not replace
60097 * @param [options] Configuration.
60098 */
60099const findAndReplace =
60100  /**
60101   * @type {(
60102   *   ((tree: Node, find: Find, replace?: Replace, options?: Options) => Node) &
60103   *   ((tree: Node, schema: FindAndReplaceSchema|FindAndReplaceList, options?: Options) => Node)
60104   * )}
60105   **/
60106  (
60107    /**
60108     * @param {Node} tree
60109     * @param {Find|FindAndReplaceSchema|FindAndReplaceList} find
60110     * @param {Replace|Options} [replace]
60111     * @param {Options} [options]
60112     */
60113    function (tree, find, replace, options) {
60114      /** @type {Options|undefined} */
60115      let settings;
60116      /** @type {FindAndReplaceSchema|FindAndReplaceList} */
60117      let schema;
60118
60119      if (typeof find === 'string' || find instanceof RegExp) {
60120        // @ts-expect-error don’t expect options twice.
60121        schema = [[find, replace]];
60122        settings = options;
60123      } else {
60124        schema = find;
60125        // @ts-expect-error don’t expect replace twice.
60126        settings = replace;
60127      }
60128
60129      if (!settings) {
60130        settings = {};
60131      }
60132
60133      const ignored = convert(settings.ignore || []);
60134      const pairs = toPairs(schema);
60135      let pairIndex = -1;
60136
60137      while (++pairIndex < pairs.length) {
60138        visitParents(tree, 'text', visitor);
60139      }
60140
60141      return tree
60142
60143      /** @type {import('unist-util-visit-parents').Visitor<Text>} */
60144      function visitor(node, parents) {
60145        let index = -1;
60146        /** @type {Parent|undefined} */
60147        let grandparent;
60148
60149        while (++index < parents.length) {
60150          const parent = /** @type {Parent} */ (parents[index]);
60151
60152          if (
60153            ignored(
60154              parent,
60155              // @ts-expect-error mdast vs. unist parent.
60156              grandparent ? grandparent.children.indexOf(parent) : undefined,
60157              grandparent
60158            )
60159          ) {
60160            return
60161          }
60162
60163          grandparent = parent;
60164        }
60165
60166        if (grandparent) {
60167          return handler(node, grandparent)
60168        }
60169      }
60170
60171      /**
60172       * @param {Text} node
60173       * @param {Parent} parent
60174       * @returns {VisitorResult}
60175       */
60176      function handler(node, parent) {
60177        const find = pairs[pairIndex][0];
60178        const replace = pairs[pairIndex][1];
60179        let start = 0;
60180        // @ts-expect-error: TS is wrong, some of these children can be text.
60181        let index = parent.children.indexOf(node);
60182        /** @type {Array.<PhrasingContent>} */
60183        let nodes = [];
60184        /** @type {number|undefined} */
60185        let position;
60186
60187        find.lastIndex = 0;
60188
60189        let match = find.exec(node.value);
60190
60191        while (match) {
60192          position = match.index;
60193          // @ts-expect-error this is perfectly fine, typescript.
60194          let value = replace(...match, {
60195            index: match.index,
60196            input: match.input
60197          });
60198
60199          if (typeof value === 'string') {
60200            value = value.length > 0 ? {type: 'text', value} : undefined;
60201          }
60202
60203          if (value !== false) {
60204            if (start !== position) {
60205              nodes.push({
60206                type: 'text',
60207                value: node.value.slice(start, position)
60208              });
60209            }
60210
60211            if (Array.isArray(value)) {
60212              nodes.push(...value);
60213            } else if (value) {
60214              nodes.push(value);
60215            }
60216
60217            start = position + match[0].length;
60218          }
60219
60220          if (!find.global) {
60221            break
60222          }
60223
60224          match = find.exec(node.value);
60225        }
60226
60227        if (position === undefined) {
60228          nodes = [node];
60229          index--;
60230        } else {
60231          if (start < node.value.length) {
60232            nodes.push({type: 'text', value: node.value.slice(start)});
60233          }
60234
60235          parent.children.splice(index, 1, ...nodes);
60236        }
60237
60238        return index + nodes.length + 1
60239      }
60240    }
60241  );
60242
60243/**
60244 * @param {FindAndReplaceSchema|FindAndReplaceList} schema
60245 * @returns {Pairs}
60246 */
60247function toPairs(schema) {
60248  /** @type {Pairs} */
60249  const result = [];
60250
60251  if (typeof schema !== 'object') {
60252    throw new TypeError('Expected array or object as schema')
60253  }
60254
60255  if (Array.isArray(schema)) {
60256    let index = -1;
60257
60258    while (++index < schema.length) {
60259      result.push([
60260        toExpression(schema[index][0]),
60261        toFunction(schema[index][1])
60262      ]);
60263    }
60264  } else {
60265    /** @type {string} */
60266    let key;
60267
60268    for (key in schema) {
60269      if (own.call(schema, key)) {
60270        result.push([toExpression(key), toFunction(schema[key])]);
60271      }
60272    }
60273  }
60274
60275  return result
60276}
60277
60278/**
60279 * @param {Find} find
60280 * @returns {RegExp}
60281 */
60282function toExpression(find) {
60283  return typeof find === 'string' ? new RegExp(escapeStringRegexp(find), 'g') : find
60284}
60285
60286/**
60287 * @param {Replace} replace
60288 * @returns {ReplaceFunction}
60289 */
60290function toFunction(replace) {
60291  return typeof replace === 'function' ? replace : () => replace
60292}
60293
60294/**
60295 * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
60296 * @typedef {import('mdast-util-from-markdown').Transform} FromMarkdownTransform
60297 * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
60298 * @typedef {import('mdast-util-to-markdown/lib/types.js').Options} ToMarkdownExtension
60299 * @typedef {import('mdast-util-find-and-replace').ReplaceFunction} ReplaceFunction
60300 * @typedef {import('mdast-util-find-and-replace').RegExpMatchObject} RegExpMatchObject
60301 * @typedef {import('mdast-util-find-and-replace').PhrasingContent} PhrasingContent
60302 */
60303
60304const inConstruct = 'phrasing';
60305const notInConstruct = ['autolink', 'link', 'image', 'label'];
60306
60307/** @type {FromMarkdownExtension} */
60308const gfmAutolinkLiteralFromMarkdown = {
60309  transforms: [transformGfmAutolinkLiterals],
60310  enter: {
60311    literalAutolink: enterLiteralAutolink,
60312    literalAutolinkEmail: enterLiteralAutolinkValue,
60313    literalAutolinkHttp: enterLiteralAutolinkValue,
60314    literalAutolinkWww: enterLiteralAutolinkValue
60315  },
60316  exit: {
60317    literalAutolink: exitLiteralAutolink,
60318    literalAutolinkEmail: exitLiteralAutolinkEmail,
60319    literalAutolinkHttp: exitLiteralAutolinkHttp,
60320    literalAutolinkWww: exitLiteralAutolinkWww
60321  }
60322};
60323
60324/** @type {ToMarkdownExtension} */
60325const gfmAutolinkLiteralToMarkdown = {
60326  unsafe: [
60327    {
60328      character: '@',
60329      before: '[+\\-.\\w]',
60330      after: '[\\-.\\w]',
60331      inConstruct,
60332      notInConstruct
60333    },
60334    {
60335      character: '.',
60336      before: '[Ww]',
60337      after: '[\\-.\\w]',
60338      inConstruct,
60339      notInConstruct
60340    },
60341    {character: ':', before: '[ps]', after: '\\/', inConstruct, notInConstruct}
60342  ]
60343};
60344
60345/** @type {FromMarkdownHandle} */
60346function enterLiteralAutolink(token) {
60347  // @ts-expect-error: `null` is fine.
60348  this.enter({type: 'link', title: null, url: '', children: []}, token);
60349}
60350
60351/** @type {FromMarkdownHandle} */
60352function enterLiteralAutolinkValue(token) {
60353  this.config.enter.autolinkProtocol.call(this, token);
60354}
60355
60356/** @type {FromMarkdownHandle} */
60357function exitLiteralAutolinkHttp(token) {
60358  this.config.exit.autolinkProtocol.call(this, token);
60359}
60360
60361/** @type {FromMarkdownHandle} */
60362function exitLiteralAutolinkWww(token) {
60363  this.config.exit.data.call(this, token);
60364  this.stack[this.stack.length - 1].url = 'http://' + this.sliceSerialize(token);
60365}
60366
60367/** @type {FromMarkdownHandle} */
60368function exitLiteralAutolinkEmail(token) {
60369  this.config.exit.autolinkEmail.call(this, token);
60370}
60371
60372/** @type {FromMarkdownHandle} */
60373function exitLiteralAutolink(token) {
60374  this.exit(token);
60375}
60376
60377/** @type {FromMarkdownTransform} */
60378function transformGfmAutolinkLiterals(tree) {
60379  findAndReplace(
60380    tree,
60381    [
60382      [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/i, findUrl],
60383      [/([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/, findEmail]
60384    ],
60385    {ignore: ['link', 'linkReference']}
60386  );
60387}
60388
60389/**
60390 * @type {ReplaceFunction}
60391 * @param {string} _
60392 * @param {string} protocol
60393 * @param {string} domain
60394 * @param {string} path
60395 * @param {RegExpMatchObject} match
60396 */
60397// eslint-disable-next-line max-params
60398function findUrl(_, protocol, domain, path, match) {
60399  let prefix = '';
60400
60401  // Not an expected previous character.
60402  if (!previous(match)) {
60403    return false
60404  }
60405
60406  // Treat `www` as part of the domain.
60407  if (/^w/i.test(protocol)) {
60408    domain = protocol + domain;
60409    protocol = '';
60410    prefix = 'http://';
60411  }
60412
60413  if (!isCorrectDomain(domain)) {
60414    return false
60415  }
60416
60417  const parts = splitUrl(domain + path);
60418
60419  if (!parts[0]) return false
60420
60421  /** @type {PhrasingContent} */
60422  // @ts-expect-error: `null` is fine.
60423  const result = {
60424    type: 'link',
60425    title: null,
60426    url: prefix + protocol + parts[0],
60427    children: [{type: 'text', value: protocol + parts[0]}]
60428  };
60429
60430  if (parts[1]) {
60431    return [result, {type: 'text', value: parts[1]}]
60432  }
60433
60434  return result
60435}
60436
60437/**
60438 * @type {ReplaceFunction}
60439 * @param {string} _
60440 * @param {string} atext
60441 * @param {string} label
60442 * @param {RegExpMatchObject} match
60443 */
60444function findEmail(_, atext, label, match) {
60445  // Not an expected previous character.
60446  if (!previous(match, true) || /[_-]$/.test(label)) {
60447    return false
60448  }
60449
60450  return {
60451    type: 'link',
60452    // @ts-expect-error: `null` is fine.
60453    title: null,
60454    url: 'mailto:' + atext + '@' + label,
60455    children: [{type: 'text', value: atext + '@' + label}]
60456  }
60457}
60458
60459/**
60460 * @param {string} domain
60461 * @returns {boolean}
60462 */
60463function isCorrectDomain(domain) {
60464  const parts = domain.split('.');
60465
60466  if (
60467    parts.length < 2 ||
60468    (parts[parts.length - 1] &&
60469      (/_/.test(parts[parts.length - 1]) ||
60470        !/[a-zA-Z\d]/.test(parts[parts.length - 1]))) ||
60471    (parts[parts.length - 2] &&
60472      (/_/.test(parts[parts.length - 2]) ||
60473        !/[a-zA-Z\d]/.test(parts[parts.length - 2])))
60474  ) {
60475    return false
60476  }
60477
60478  return true
60479}
60480
60481/**
60482 * @param {string} url
60483 * @returns {[string, string|undefined]}
60484 */
60485function splitUrl(url) {
60486  const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url);
60487  /** @type {number} */
60488  let closingParenIndex;
60489  /** @type {number} */
60490  let openingParens;
60491  /** @type {number} */
60492  let closingParens;
60493  /** @type {string|undefined} */
60494  let trail;
60495
60496  if (trailExec) {
60497    url = url.slice(0, trailExec.index);
60498    trail = trailExec[0];
60499    closingParenIndex = trail.indexOf(')');
60500    openingParens = ccount(url, '(');
60501    closingParens = ccount(url, ')');
60502
60503    while (closingParenIndex !== -1 && openingParens > closingParens) {
60504      url += trail.slice(0, closingParenIndex + 1);
60505      trail = trail.slice(closingParenIndex + 1);
60506      closingParenIndex = trail.indexOf(')');
60507      closingParens++;
60508    }
60509  }
60510
60511  return [url, trail]
60512}
60513
60514/**
60515 * @param {RegExpMatchObject} match
60516 * @param {boolean} [email=false]
60517 * @returns {boolean}
60518 */
60519function previous(match, email) {
60520  const code = match.input.charCodeAt(match.index - 1);
60521
60522  return (
60523    (match.index === 0 ||
60524      unicodeWhitespace(code) ||
60525      unicodePunctuation(code)) &&
60526    (!email || code !== 47)
60527  )
60528}
60529
60530/**
60531 * @typedef {import('mdast').Delete} Delete
60532 * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
60533 * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
60534 * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
60535 * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle
60536 */
60537
60538/** @type {FromMarkdownExtension} */
60539const gfmStrikethroughFromMarkdown = {
60540  canContainEols: ['delete'],
60541  enter: {strikethrough: enterStrikethrough},
60542  exit: {strikethrough: exitStrikethrough}
60543};
60544
60545/** @type {ToMarkdownExtension} */
60546const gfmStrikethroughToMarkdown = {
60547  unsafe: [{character: '~', inConstruct: 'phrasing'}],
60548  handlers: {delete: handleDelete}
60549};
60550
60551handleDelete.peek = peekDelete;
60552
60553/** @type {FromMarkdownHandle} */
60554function enterStrikethrough(token) {
60555  this.enter({type: 'delete', children: []}, token);
60556}
60557
60558/** @type {FromMarkdownHandle} */
60559function exitStrikethrough(token) {
60560  this.exit(token);
60561}
60562
60563/**
60564 * @type {ToMarkdownHandle}
60565 * @param {Delete} node
60566 */
60567function handleDelete(node, _, context) {
60568  const exit = context.enter('emphasis');
60569  const value = containerPhrasing(node, context, {before: '~', after: '~'});
60570  exit();
60571  return '~~' + value + '~~'
60572}
60573
60574/** @type {ToMarkdownHandle} */
60575function peekDelete() {
60576  return '~'
60577}
60578
60579/**
60580 * @typedef MarkdownTableOptions
60581 * @property {string|null|Array.<string|null|undefined>} [align]
60582 * @property {boolean} [padding=true]
60583 * @property {boolean} [delimiterStart=true]
60584 * @property {boolean} [delimiterStart=true]
60585 * @property {boolean} [delimiterEnd=true]
60586 * @property {boolean} [alignDelimiters=true]
60587 * @property {(value: string) => number} [stringLength]
60588 */
60589
60590/**
60591 * Create a table from a matrix of strings.
60592 *
60593 * @param {Array.<Array.<string|null|undefined>>} table
60594 * @param {MarkdownTableOptions} [options]
60595 * @returns {string}
60596 */
60597function markdownTable(table, options) {
60598  const settings = options || {};
60599  const align = (settings.align || []).concat();
60600  const stringLength = settings.stringLength || defaultStringLength;
60601  /** @type {number[]} Character codes as symbols for alignment per column. */
60602  const alignments = [];
60603  let rowIndex = -1;
60604  /** @type {string[][]} Cells per row. */
60605  const cellMatrix = [];
60606  /** @type {number[][]} Sizes of each cell per row. */
60607  const sizeMatrix = [];
60608  /** @type {number[]} */
60609  const longestCellByColumn = [];
60610  let mostCellsPerRow = 0;
60611  /** @type {number} */
60612  let columnIndex;
60613  /** @type {string[]} Cells of current row */
60614  let row;
60615  /** @type {number[]} Sizes of current row */
60616  let sizes;
60617  /** @type {number} Sizes of current cell */
60618  let size;
60619  /** @type {string} Current cell */
60620  let cell;
60621  /** @type {string[]} Chunks of current line. */
60622  let line;
60623  /** @type {string} */
60624  let before;
60625  /** @type {string} */
60626  let after;
60627  /** @type {number} */
60628  let code;
60629
60630  // This is a superfluous loop if we don’t align delimiters, but otherwise we’d
60631  // do superfluous work when aligning, so optimize for aligning.
60632  while (++rowIndex < table.length) {
60633    columnIndex = -1;
60634    row = [];
60635    sizes = [];
60636
60637    if (table[rowIndex].length > mostCellsPerRow) {
60638      mostCellsPerRow = table[rowIndex].length;
60639    }
60640
60641    while (++columnIndex < table[rowIndex].length) {
60642      cell = serialize(table[rowIndex][columnIndex]);
60643
60644      if (settings.alignDelimiters !== false) {
60645        size = stringLength(cell);
60646        sizes[columnIndex] = size;
60647
60648        if (
60649          longestCellByColumn[columnIndex] === undefined ||
60650          size > longestCellByColumn[columnIndex]
60651        ) {
60652          longestCellByColumn[columnIndex] = size;
60653        }
60654      }
60655
60656      row.push(cell);
60657    }
60658
60659    cellMatrix[rowIndex] = row;
60660    sizeMatrix[rowIndex] = sizes;
60661  }
60662
60663  // Figure out which alignments to use.
60664  columnIndex = -1;
60665
60666  if (typeof align === 'object' && 'length' in align) {
60667    while (++columnIndex < mostCellsPerRow) {
60668      alignments[columnIndex] = toAlignment(align[columnIndex]);
60669    }
60670  } else {
60671    code = toAlignment(align);
60672
60673    while (++columnIndex < mostCellsPerRow) {
60674      alignments[columnIndex] = code;
60675    }
60676  }
60677
60678  // Inject the alignment row.
60679  columnIndex = -1;
60680  row = [];
60681  sizes = [];
60682
60683  while (++columnIndex < mostCellsPerRow) {
60684    code = alignments[columnIndex];
60685    before = '';
60686    after = '';
60687
60688    if (code === 99 /* `c` */) {
60689      before = ':';
60690      after = ':';
60691    } else if (code === 108 /* `l` */) {
60692      before = ':';
60693    } else if (code === 114 /* `r` */) {
60694      after = ':';
60695    }
60696
60697    // There *must* be at least one hyphen-minus in each alignment cell.
60698    size =
60699      settings.alignDelimiters === false
60700        ? 1
60701        : Math.max(
60702            1,
60703            longestCellByColumn[columnIndex] - before.length - after.length
60704          );
60705
60706    cell = before + '-'.repeat(size) + after;
60707
60708    if (settings.alignDelimiters !== false) {
60709      size = before.length + size + after.length;
60710
60711      if (size > longestCellByColumn[columnIndex]) {
60712        longestCellByColumn[columnIndex] = size;
60713      }
60714
60715      sizes[columnIndex] = size;
60716    }
60717
60718    row[columnIndex] = cell;
60719  }
60720
60721  // Inject the alignment row.
60722  cellMatrix.splice(1, 0, row);
60723  sizeMatrix.splice(1, 0, sizes);
60724
60725  rowIndex = -1;
60726  /** @type {string[]} */
60727  const lines = [];
60728
60729  while (++rowIndex < cellMatrix.length) {
60730    row = cellMatrix[rowIndex];
60731    sizes = sizeMatrix[rowIndex];
60732    columnIndex = -1;
60733    line = [];
60734
60735    while (++columnIndex < mostCellsPerRow) {
60736      cell = row[columnIndex] || '';
60737      before = '';
60738      after = '';
60739
60740      if (settings.alignDelimiters !== false) {
60741        size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0);
60742        code = alignments[columnIndex];
60743
60744        if (code === 114 /* `r` */) {
60745          before = ' '.repeat(size);
60746        } else if (code === 99 /* `c` */) {
60747          if (size % 2) {
60748            before = ' '.repeat(size / 2 + 0.5);
60749            after = ' '.repeat(size / 2 - 0.5);
60750          } else {
60751            before = ' '.repeat(size / 2);
60752            after = before;
60753          }
60754        } else {
60755          after = ' '.repeat(size);
60756        }
60757      }
60758
60759      if (settings.delimiterStart !== false && !columnIndex) {
60760        line.push('|');
60761      }
60762
60763      if (
60764        settings.padding !== false &&
60765        // Don’t add the opening space if we’re not aligning and the cell is
60766        // empty: there will be a closing space.
60767        !(settings.alignDelimiters === false && cell === '') &&
60768        (settings.delimiterStart !== false || columnIndex)
60769      ) {
60770        line.push(' ');
60771      }
60772
60773      if (settings.alignDelimiters !== false) {
60774        line.push(before);
60775      }
60776
60777      line.push(cell);
60778
60779      if (settings.alignDelimiters !== false) {
60780        line.push(after);
60781      }
60782
60783      if (settings.padding !== false) {
60784        line.push(' ');
60785      }
60786
60787      if (
60788        settings.delimiterEnd !== false ||
60789        columnIndex !== mostCellsPerRow - 1
60790      ) {
60791        line.push('|');
60792      }
60793    }
60794
60795    lines.push(
60796      settings.delimiterEnd === false
60797        ? line.join('').replace(/ +$/, '')
60798        : line.join('')
60799    );
60800  }
60801
60802  return lines.join('\n')
60803}
60804
60805/**
60806 * @param {string|null|undefined} [value]
60807 * @returns {string}
60808 */
60809function serialize(value) {
60810  return value === null || value === undefined ? '' : String(value)
60811}
60812
60813/**
60814 * @param {string} value
60815 * @returns {number}
60816 */
60817function defaultStringLength(value) {
60818  return value.length
60819}
60820
60821/**
60822 * @param {string|null|undefined} value
60823 * @returns {number}
60824 */
60825function toAlignment(value) {
60826  const code = typeof value === 'string' ? value.charCodeAt(0) : 0;
60827
60828  return code === 67 /* `C` */ || code === 99 /* `c` */
60829    ? 99 /* `c` */
60830    : code === 76 /* `L` */ || code === 108 /* `l` */
60831    ? 108 /* `l` */
60832    : code === 82 /* `R` */ || code === 114 /* `r` */
60833    ? 114 /* `r` */
60834    : 0
60835}
60836
60837/**
60838 * @typedef {import('mdast').AlignType} AlignType
60839 * @typedef {import('mdast').Table} Table
60840 * @typedef {import('mdast').TableRow} TableRow
60841 * @typedef {import('mdast').TableCell} TableCell
60842 * @typedef {import('mdast').InlineCode} InlineCode
60843 * @typedef {import('markdown-table').MarkdownTableOptions} MarkdownTableOptions
60844 * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
60845 * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
60846 * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
60847 * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle
60848 * @typedef {import('mdast-util-to-markdown').Context} ToMarkdownContext
60849 *
60850 * @typedef Options
60851 * @property {boolean} [tableCellPadding=true]
60852 * @property {boolean} [tablePipeAlign=true]
60853 * @property {MarkdownTableOptions['stringLength']} [stringLength]
60854 */
60855
60856/** @type {FromMarkdownExtension} */
60857const gfmTableFromMarkdown = {
60858  enter: {
60859    table: enterTable,
60860    tableData: enterCell,
60861    tableHeader: enterCell,
60862    tableRow: enterRow
60863  },
60864  exit: {
60865    codeText: exitCodeText,
60866    table: exitTable,
60867    tableData: exit,
60868    tableHeader: exit,
60869    tableRow: exit
60870  }
60871};
60872
60873/** @type {FromMarkdownHandle} */
60874function enterTable(token) {
60875  /** @type {AlignType[]} */
60876  // @ts-expect-error: `align` is custom.
60877  const align = token._align;
60878  this.enter({type: 'table', align, children: []}, token);
60879  this.setData('inTable', true);
60880}
60881
60882/** @type {FromMarkdownHandle} */
60883function exitTable(token) {
60884  this.exit(token);
60885  this.setData('inTable');
60886}
60887
60888/** @type {FromMarkdownHandle} */
60889function enterRow(token) {
60890  this.enter({type: 'tableRow', children: []}, token);
60891}
60892
60893/** @type {FromMarkdownHandle} */
60894function exit(token) {
60895  this.exit(token);
60896}
60897
60898/** @type {FromMarkdownHandle} */
60899function enterCell(token) {
60900  this.enter({type: 'tableCell', children: []}, token);
60901}
60902
60903// Overwrite the default code text data handler to unescape escaped pipes when
60904// they are in tables.
60905/** @type {FromMarkdownHandle} */
60906function exitCodeText(token) {
60907  let value = this.resume();
60908
60909  if (this.getData('inTable')) {
60910    value = value.replace(/\\([\\|])/g, replace);
60911  }
60912
60913  const node = /** @type {InlineCode} */ (this.stack[this.stack.length - 1]);
60914  node.value = value;
60915  this.exit(token);
60916}
60917
60918/**
60919 * @param {string} $0
60920 * @param {string} $1
60921 * @returns {string}
60922 */
60923function replace($0, $1) {
60924  // Pipes work, backslashes don’t (but can’t escape pipes).
60925  return $1 === '|' ? $1 : $0
60926}
60927
60928/**
60929 * @param {Options} [options]
60930 * @returns {ToMarkdownExtension}
60931 */
60932function gfmTableToMarkdown(options) {
60933  const settings = options || {};
60934  const padding = settings.tableCellPadding;
60935  const alignDelimiters = settings.tablePipeAlign;
60936  const stringLength = settings.stringLength;
60937  const around = padding ? ' ' : '|';
60938
60939  return {
60940    unsafe: [
60941      {character: '\r', inConstruct: 'tableCell'},
60942      {character: '\n', inConstruct: 'tableCell'},
60943      // A pipe, when followed by a tab or space (padding), or a dash or colon
60944      // (unpadded delimiter row), could result in a table.
60945      {atBreak: true, character: '|', after: '[\t :-]'},
60946      // A pipe in a cell must be encoded.
60947      {character: '|', inConstruct: 'tableCell'},
60948      // A colon must be followed by a dash, in which case it could start a
60949      // delimiter row.
60950      {atBreak: true, character: ':', after: '-'},
60951      // A delimiter row can also start with a dash, when followed by more
60952      // dashes, a colon, or a pipe.
60953      // This is a stricter version than the built in check for lists, thematic
60954      // breaks, and setex heading underlines though:
60955      // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>
60956      {atBreak: true, character: '-', after: '[:|-]'}
60957    ],
60958    handlers: {
60959      table: handleTable,
60960      tableRow: handleTableRow,
60961      tableCell: handleTableCell,
60962      inlineCode: inlineCodeWithTable
60963    }
60964  }
60965
60966  /**
60967   * @type {ToMarkdownHandle}
60968   * @param {Table} node
60969   */
60970  function handleTable(node, _, context) {
60971    // @ts-expect-error: fixed in `markdown-table@3.0.1`.
60972    return serializeData(handleTableAsData(node, context), node.align)
60973  }
60974
60975  /**
60976   * This function isn’t really used normally, because we handle rows at the
60977   * table level.
60978   * But, if someone passes in a table row, this ensures we make somewhat sense.
60979   *
60980   * @type {ToMarkdownHandle}
60981   * @param {TableRow} node
60982   */
60983  function handleTableRow(node, _, context) {
60984    const row = handleTableRowAsData(node, context);
60985    // `markdown-table` will always add an align row
60986    const value = serializeData([row]);
60987    return value.slice(0, value.indexOf('\n'))
60988  }
60989
60990  /**
60991   * @type {ToMarkdownHandle}
60992   * @param {TableCell} node
60993   */
60994  function handleTableCell(node, _, context) {
60995    const exit = context.enter('tableCell');
60996    const subexit = context.enter('phrasing');
60997    const value = containerPhrasing(node, context, {
60998      before: around,
60999      after: around
61000    });
61001    subexit();
61002    exit();
61003    return value
61004  }
61005
61006  /**
61007   * @param {Array.<Array.<string>>} matrix
61008   * @param {Array.<string>} [align]
61009   */
61010  function serializeData(matrix, align) {
61011    return markdownTable(matrix, {
61012      align,
61013      alignDelimiters,
61014      padding,
61015      stringLength
61016    })
61017  }
61018
61019  /**
61020   * @param {Table} node
61021   * @param {ToMarkdownContext} context
61022   */
61023  function handleTableAsData(node, context) {
61024    const children = node.children;
61025    let index = -1;
61026    /** @type {Array.<Array.<string>>} */
61027    const result = [];
61028    const subexit = context.enter('table');
61029
61030    while (++index < children.length) {
61031      result[index] = handleTableRowAsData(children[index], context);
61032    }
61033
61034    subexit();
61035
61036    return result
61037  }
61038
61039  /**
61040   * @param {TableRow} node
61041   * @param {ToMarkdownContext} context
61042   */
61043  function handleTableRowAsData(node, context) {
61044    const children = node.children;
61045    let index = -1;
61046    /** @type {Array.<string>} */
61047    const result = [];
61048    const subexit = context.enter('tableRow');
61049
61050    while (++index < children.length) {
61051      result[index] = handleTableCell(children[index], node, context);
61052    }
61053
61054    subexit();
61055
61056    return result
61057  }
61058
61059  /**
61060   * @type {ToMarkdownHandle}
61061   * @param {InlineCode} node
61062   */
61063  function inlineCodeWithTable(node, parent, context) {
61064    let value = inlineCode(node, parent, context);
61065
61066    if (context.stack.includes('tableCell')) {
61067      value = value.replace(/\|/g, '\\$&');
61068    }
61069
61070    return value
61071  }
61072}
61073
61074/**
61075 * @typedef {import('mdast').ListItem} ListItem
61076 * @typedef {import('mdast').Paragraph} Paragraph
61077 * @typedef {import('mdast').BlockContent} BlockContent
61078 * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
61079 * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
61080 * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
61081 * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle
61082 */
61083
61084/** @type {FromMarkdownExtension} */
61085const gfmTaskListItemFromMarkdown = {
61086  exit: {
61087    taskListCheckValueChecked: exitCheck,
61088    taskListCheckValueUnchecked: exitCheck,
61089    paragraph: exitParagraphWithTaskListItem
61090  }
61091};
61092
61093/** @type {ToMarkdownExtension} */
61094const gfmTaskListItemToMarkdown = {
61095  unsafe: [{atBreak: true, character: '-', after: '[:|-]'}],
61096  handlers: {listItem: listItemWithTaskListItem}
61097};
61098
61099/** @type {FromMarkdownHandle} */
61100function exitCheck(token) {
61101  // We’re always in a paragraph, in a list item.
61102  this.stack[this.stack.length - 2].checked =
61103    token.type === 'taskListCheckValueChecked';
61104}
61105
61106/** @type {FromMarkdownHandle} */
61107function exitParagraphWithTaskListItem(token) {
61108  const parent = this.stack[this.stack.length - 2];
61109  /** @type {Paragraph} */
61110  // @ts-expect-error: must be true.
61111  const node = this.stack[this.stack.length - 1];
61112  /** @type {BlockContent[]} */
61113  // @ts-expect-error: check whether `parent` is a `listItem` later.
61114  const siblings = parent.children;
61115  const head = node.children[0];
61116  let index = -1;
61117  /** @type {Paragraph|undefined} */
61118  let firstParaghraph;
61119
61120  if (
61121    parent &&
61122    parent.type === 'listItem' &&
61123    typeof parent.checked === 'boolean' &&
61124    head &&
61125    head.type === 'text'
61126  ) {
61127    while (++index < siblings.length) {
61128      const sibling = siblings[index];
61129      if (sibling.type === 'paragraph') {
61130        firstParaghraph = sibling;
61131        break
61132      }
61133    }
61134
61135    if (firstParaghraph === node) {
61136      // Must start with a space or a tab.
61137      head.value = head.value.slice(1);
61138
61139      if (head.value.length === 0) {
61140        node.children.shift();
61141      } else {
61142        // @ts-expect-error: must be true.
61143        head.position.start.column++;
61144        // @ts-expect-error: must be true.
61145        head.position.start.offset++;
61146        // @ts-expect-error: must be true.
61147        node.position.start = Object.assign({}, head.position.start);
61148      }
61149    }
61150  }
61151
61152  this.exit(token);
61153}
61154
61155/**
61156 * @type {ToMarkdownHandle}
61157 * @param {ListItem} node
61158 */
61159function listItemWithTaskListItem(node, parent, context) {
61160  const head = node.children[0];
61161  let value = listItem(node, parent, context);
61162
61163  if (typeof node.checked === 'boolean' && head && head.type === 'paragraph') {
61164    value = value.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/, check);
61165  }
61166
61167  return value
61168
61169  /**
61170   * @param {string} $0
61171   * @returns {string}
61172   */
61173  function check($0) {
61174    return $0 + '[' + (node.checked ? 'x' : ' ') + '] '
61175  }
61176}
61177
61178/**
61179 * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
61180 * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
61181 *
61182 * @typedef {import('mdast-util-gfm-table').Options} Options
61183 */
61184
61185/**
61186 * @type {Array.<FromMarkdownExtension>}
61187 */
61188const gfmFromMarkdown = [
61189  gfmAutolinkLiteralFromMarkdown,
61190  gfmStrikethroughFromMarkdown,
61191  gfmTableFromMarkdown,
61192  gfmTaskListItemFromMarkdown
61193];
61194
61195/**
61196 * @param {Options} [options]
61197 * @returns {ToMarkdownExtension}
61198 */
61199function gfmToMarkdown(options) {
61200  return {
61201    extensions: [
61202      gfmAutolinkLiteralToMarkdown,
61203      gfmStrikethroughToMarkdown,
61204      gfmTableToMarkdown(options),
61205      gfmTaskListItemToMarkdown
61206    ]
61207  }
61208}
61209
61210/**
61211 * @typedef {import('mdast').Root} Root
61212 * @typedef {import('micromark-extension-gfm').Options & import('mdast-util-gfm').Options} Options
61213 */
61214
61215/**
61216 * Plugin to support GitHub Flavored Markdown (GFM).
61217 *
61218 * @type {import('unified').Plugin<[Options?]|void[], Root>}
61219 */
61220function remarkGfm(options = {}) {
61221  const data = this.data();
61222
61223  add('micromarkExtensions', gfm(options));
61224  add('fromMarkdownExtensions', gfmFromMarkdown);
61225  add('toMarkdownExtensions', gfmToMarkdown(options));
61226
61227  /**
61228   * @param {string} field
61229   * @param {unknown} value
61230   */
61231  function add(field, value) {
61232    const list = /** @type {unknown[]} */ (
61233      // Other extensions
61234      /* c8 ignore next 2 */
61235      data[field] ? data[field] : (data[field] = [])
61236    );
61237
61238    list.push(value);
61239  }
61240}
61241
61242// To aid in future maintenance, this layout closely matches remark-cli/cli.js.
61243
61244args({
61245  processor: remark().use(remarkGfm).use(remarkPresetLintNode),
61246  name: proc.name,
61247  description: cli.description,
61248  version: [
61249    proc.name + ': ' + proc.version,
61250    cli.name + ': ' + cli.version,
61251  ].join(', '),
61252  pluginPrefix: proc.name,
61253  presetPrefix: proc.name + '-preset',
61254  packageField: proc.name + 'Config',
61255  rcName: '.' + proc.name + 'rc',
61256  ignoreName: '.' + proc.name + 'ignore',
61257  extensions: markdownExtensions,
61258  detectConfig: false,
61259});
61260