'use strict'; var fs$r = require('fs'); var path$t = require('path'); var require$$0$b = require('events'); var require$$0$6 = require('util'); var require$$0$a = require('stream'); var require$$0$5 = require('os'); var perf_hooks = require('perf_hooks'); var require$$0$8 = require('url'); var require$$1 = require('crypto'); var require$$0$7 = require('module'); var esbuild = require('esbuild'); var require$$1$1 = require('worker_threads'); var require$$5 = require('assert'); var require$$1$4 = require('child_process'); var readline = require('readline'); var require$$0$9 = require('zlib'); var resolve$4 = require('resolve'); var qs = require('querystring'); var require$$0$4 = require('tty'); var require$$3 = require('net'); var require$$1$2 = require('http'); var require$$0$c = require('buffer'); var require$$1$3 = require('https'); var require$$4 = require('tls'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { for (var k in e) { n[k] = e[k]; } } n["default"] = e; return n; } var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$r); var fs__namespace = /*#__PURE__*/_interopNamespace(fs$r); var path__default = /*#__PURE__*/_interopDefaultLegacy(path$t); var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$b); var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6); var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$a); var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5); var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8); var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1); var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7); var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$1); var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5); var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4); var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline); var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9); var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4); var qs__namespace = /*#__PURE__*/_interopNamespace(qs); var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3); var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2); var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$c); var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3); var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var a = Object.defineProperty({}, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } function commonjsRequire (path) { 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.'); } var ansiStyles$2 = {exports: {}}; var colorName$1 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords$1 = colorName$1; // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords$1 = {}; for (const key of Object.keys(cssKeywords$1)) { reverseKeywords$1[cssKeywords$1[key]] = key; } const convert$3 = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; var conversions$5 = convert$3; // Hide .channels and .labels properties for (const model of Object.keys(convert$3)) { if (!('channels' in convert$3[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert$3[model])) { throw new Error('missing channel labels property: ' + model); } if (convert$3[model].labels.length !== convert$3[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert$3[model]; delete convert$3[model].channels; delete convert$3[model].labels; Object.defineProperty(convert$3[model], 'channels', {value: channels}); Object.defineProperty(convert$3[model], 'labels', {value: labels}); } convert$3.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert$3.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert$3.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert$3.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert$3.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance$1(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert$3.rgb.keyword = function (rgb) { const reversed = reverseKeywords$1[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords$1)) { const value = cssKeywords$1[keyword]; // Compute comparative distance const distance = comparativeDistance$1(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert$3.keyword.rgb = function (keyword) { return cssKeywords$1[keyword]; }; convert$3.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert$3.rgb.lab = function (rgb) { const xyz = convert$3.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$3.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert$3.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert$3.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert$3.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert$3.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert$3.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert$3.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert$3.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$3.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert$3.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert$3.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert$3.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert$3.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert$3.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert$3.rgb.ansi16(convert$3.hsv.rgb(args), args[2]); }; convert$3.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert$3.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert$3.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert$3.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$3.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert$3.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert$3.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert$3.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert$3.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert$3.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert$3.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert$3.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert$3.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert$3.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert$3.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert$3.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert$3.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert$3.gray.hsv = convert$3.gray.hsl; convert$3.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert$3.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert$3.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert$3.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$3.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; const conversions$4 = conversions$5; /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$1() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions$4); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$1(fromModel) { const graph = buildGraph$1(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions$4[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$1(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$1(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions$4[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$1(conversions$4[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$3 = function (fromModel) { const graph = deriveBFS$1(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$1(toModel, graph); } return conversion; }; const conversions$3 = conversions$5; const route$2 = route$3; const convert$2 = {}; const models$1 = Object.keys(conversions$3); function wrapRaw$1(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$1(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$1.forEach(fromModel => { convert$2[fromModel] = {}; Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$3[fromModel].channels}); Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$3[fromModel].labels}); const routes = route$2(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert$2[fromModel][toModel] = wrapRounded$1(fn); convert$2[fromModel][toModel].raw = wrapRaw$1(fn); }); }); var colorConvert$1 = convert$2; (function (module) { const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = colorConvert$1; } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }(ansiStyles$2)); var hasFlag$3 = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; const os$5 = require$$0__default$1; const tty = require$$0__default; const hasFlag$2 = hasFlag$3; const {env: env$2} = process; let forceColor$1; if (hasFlag$2('no-color') || hasFlag$2('no-colors') || hasFlag$2('color=false') || hasFlag$2('color=never')) { forceColor$1 = 0; } else if (hasFlag$2('color') || hasFlag$2('colors') || hasFlag$2('color=true') || hasFlag$2('color=always')) { forceColor$1 = 1; } if ('FORCE_COLOR' in env$2) { if (env$2.FORCE_COLOR === 'true') { forceColor$1 = 1; } else if (env$2.FORCE_COLOR === 'false') { forceColor$1 = 0; } else { forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); } } function translateLevel$1(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$1(haveStream, streamIsTTY) { if (forceColor$1 === 0) { return 0; } if (hasFlag$2('color=16m') || hasFlag$2('color=full') || hasFlag$2('color=truecolor')) { return 3; } if (hasFlag$2('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor$1 === undefined) { return 0; } const min = forceColor$1 || 0; if (env$2.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os$5.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$2) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$2) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; } if (env$2.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$2) { const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$2.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$2.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { return 1; } if ('COLORTERM' in env$2) { return 1; } return min; } function getSupportLevel$1(stream) { const level = supportsColor$1(stream, stream && stream.isTTY); return translateLevel$1(level); } var supportsColor_1$1 = { supportsColor: getSupportLevel$1, stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) }; const stringReplaceAll$1 = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; var util$9 = { stringReplaceAll: stringReplaceAll$1, stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 }; const 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; const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$1 = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape$2(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES$1.get(c) || c; } function parseArguments$1(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX$1))) { results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$2(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle$1(style) { STYLE_REGEX$1.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$1.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$1(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$1(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } var templates$1 = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape$2(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); styles.push({inverse, styles: parseStyle$1(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMessage); } return chunks.join(''); }; const ansiStyles$1 = ansiStyles$2.exports; const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1; const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = util$9; const {isArray: isArray$4} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles$1)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto$1 = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { if (isArray$4(arguments_[0]) && isArray$4(arguments_[0].raw)) { // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` return applyStyle(builder, chalkTag(builder, ...arguments_)); } // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto$1); builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!isArray$4(firstString) || !isArray$4(firstString.raw)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = templates$1; } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk$2 = Chalk(); // eslint-disable-line new-cap chalk$2.supportsColor = stdoutColor; chalk$2.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk$2.stderr.supportsColor = stderrColor; var source = chalk$2; var src$2 = {exports: {}}; var browser$1 = {exports: {}}; /** * Helpers. */ var s$1 = 1000; var m$1 = s$1 * 60; var h$1 = m$1 * 60; var d$1 = h$1 * 24; var w = d$1 * 7; var y$1 = d$1 * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ var ms$1 = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$m(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong$1(val) : fmtShort$1(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse$m(str) { str = String(str); if (str.length > 100) { return; } 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( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y$1; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d$1; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h$1; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m$1; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s$1; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort$1(ms) { var msAbs = Math.abs(ms); if (msAbs >= d$1) { return Math.round(ms / d$1) + 'd'; } if (msAbs >= h$1) { return Math.round(ms / h$1) + 'h'; } if (msAbs >= m$1) { return Math.round(ms / m$1) + 'm'; } if (msAbs >= s$1) { return Math.round(ms / s$1) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong$1(ms) { var msAbs = Math.abs(ms); if (msAbs >= d$1) { return plural$1(ms, msAbs, d$1, 'day'); } if (msAbs >= h$1) { return plural$1(ms, msAbs, h$1, 'hour'); } if (msAbs >= m$1) { return plural$1(ms, msAbs, m$1, 'minute'); } if (msAbs >= s$1) { return plural$1(ms, msAbs, s$1, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural$1(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = ms$1; createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } var common$e = setup; /* eslint-env browser */ (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = common$e(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; }(browser$1, browser$1.exports)); var node$1 = {exports: {}}; /** * Module dependencies. */ (function (module, exports) { const tty = require$$0__default; const util = require$$0__default$2; /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = common$e(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; }(node$1, node$1.exports)); /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { src$2.exports = browser$1.exports; } else { src$2.exports = node$1.exports; } var debug$f = src$2.exports; const DEFAULT_MAIN_FIELDS = [ 'module', 'jsnext:main', 'jsnext' ]; const DEFAULT_EXTENSIONS = [ '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json' ]; const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/; const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/; /** * Prefix for resolved fs paths, since windows paths may not be valid as URLs. */ const FS_PREFIX = `/@fs/`; /** * Prefix for resolved Ids that are not valid browser import specifiers */ const VALID_ID_PREFIX = `/@id/`; /** * Some Rollup plugins use ids that starts with the null byte \0 to avoid * collisions, but it is not permitted in import URLs so we have to replace * them. */ const NULL_BYTE_PLACEHOLDER = `__x00__`; const CLIENT_PUBLIC_PATH = `/@vite/client`; const ENV_PUBLIC_PATH = `/@vite/env`; // eslint-disable-next-line node/no-missing-require const CLIENT_ENTRY = require.resolve('vite/dist/client/client.mjs'); // eslint-disable-next-line node/no-missing-require const ENV_ENTRY = require.resolve('vite/dist/client/env.mjs'); const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY); // ** READ THIS ** before editing `KNOWN_ASSET_TYPES`. // If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it // to the TypeScript declaration file `packages/vite/client.d.ts`. const KNOWN_ASSET_TYPES = [ // images 'png', 'jpe?g', 'gif', 'svg', 'ico', 'webp', 'avif', // media 'mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac', // fonts 'woff2?', 'eot', 'ttf', 'otf', // other 'wasm', 'webmanifest', 'pdf' ]; const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`); const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/; const {builtinModules} = require$$0__default$3; const ignoreList = [ 'sys' ]; // eslint-disable-next-line node/no-deprecated-api var builtinModules_1 = (builtinModules || Object.keys(process.binding('natives'))) .filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !ignoreList.includes(x)) .sort(); var charToInteger$1 = {}; var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; for (var i$2 = 0; i$2 < chars$2.length; i$2++) { charToInteger$1[chars$2.charCodeAt(i$2)] = i$2; } function decode(mappings) { var decoded = []; var line = []; var segment = [ 0, 0, 0, 0, 0, ]; var j = 0; for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) { var c = mappings.charCodeAt(i); if (c === 44) { // "," segmentify(line, segment, j); j = 0; } else if (c === 59) { // ";" segmentify(line, segment, j); j = 0; decoded.push(line); line = []; segment[0] = 0; } else { var integer = charToInteger$1[c]; if (integer === undefined) { throw new Error('Invalid character (' + String.fromCharCode(c) + ')'); } var hasContinuationBit = integer & 32; integer &= 31; value += integer << shift; if (hasContinuationBit) { shift += 5; } else { var shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = value === 0 ? -0x80000000 : -value; } segment[j] += value; j++; value = shift = 0; // reset } } } segmentify(line, segment, j); decoded.push(line); return decoded; } function segmentify(line, segment, j) { // This looks ugly, but we're creating specialized arrays with a specific // length. This is much faster than creating a new array (which v8 expands to // a capacity of 17 after pushing the first item), or slicing out a subarray // (which is slow). Length 4 is assumed to be the most frequent, followed by // length 5 (since not everything will have an associated name), followed by // length 1 (it's probably rare for a source substring to not have an // associated segment data). if (j === 4) line.push([segment[0], segment[1], segment[2], segment[3]]); else if (j === 5) line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]); else if (j === 1) line.push([segment[0]]); } function encode$1(decoded) { var sourceFileIndex = 0; // second field var sourceCodeLine = 0; // third field var sourceCodeColumn = 0; // fourth field var nameIndex = 0; // fifth field var mappings = ''; for (var i = 0; i < decoded.length; i++) { var line = decoded[i]; if (i > 0) mappings += ';'; if (line.length === 0) continue; var generatedCodeColumn = 0; // first field var lineMappings = []; for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { var segment = line_1[_i]; var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn); generatedCodeColumn = segment[0]; if (segment.length > 1) { segmentMappings += encodeInteger$1(segment[1] - sourceFileIndex) + encodeInteger$1(segment[2] - sourceCodeLine) + encodeInteger$1(segment[3] - sourceCodeColumn); sourceFileIndex = segment[1]; sourceCodeLine = segment[2]; sourceCodeColumn = segment[3]; } if (segment.length === 5) { segmentMappings += encodeInteger$1(segment[4] - nameIndex); nameIndex = segment[4]; } lineMappings.push(segmentMappings); } mappings += lineMappings.join(','); } return mappings; } function encodeInteger$1(num) { var result = ''; num = num < 0 ? (-num << 1) | 1 : num << 1; do { var clamped = num & 31; num >>>= 5; if (num > 0) { clamped |= 32; } result += chars$2[clamped]; } while (num > 0); return result; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Creates a brand new (prototype-less) object with the enumerable-own * properties of `target`. Any enumerable-own properties from `source` which * are not present on `target` will be copied as well. */ function defaults(target, source) { return Object.assign(Object.create(null), source, target); } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object. * * Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON * representations of either type. */ function decodeSourceMap(map) { if (typeof map === 'string') { map = JSON.parse(map); } let { mappings } = map; if (typeof mappings === 'string') { mappings = sortMappings(decode(mappings), true); } else { // Clone the Line so that we can sort it. We don't want to mutate an array // that we don't own directly. mappings = sortMappings(mappings, false); } return defaults({ mappings }, map); } function firstUnsortedSegmentLine(mappings) { for (let i = 0; i < mappings.length; i++) { const segments = mappings[i]; for (let j = 1; j < segments.length; j++) { if (segments[j][0] < segments[j - 1][0]) { return i; } } } return mappings.length; } function sortMappings(mappings, owned) { const unosrtedIndex = firstUnsortedSegmentLine(mappings); if (unosrtedIndex === mappings.length) return mappings; if (!owned) mappings = mappings.slice(); for (let i = unosrtedIndex; i < mappings.length; i++) { mappings[i] = sortSegments(mappings[i], owned); } return mappings; } function sortSegments(segments, owned) { if (!owned) segments = segments.slice(); return segments.sort(segmentComparator); } function segmentComparator(a, b) { return a[0] - b[0]; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A "leaf" node in the sourcemap tree, representing an original, unmodified * source file. Recursive segment tracing ends at the `OriginalSource`. */ class OriginalSource { constructor(filename, content) { this.filename = filename; this.content = content; } /** * Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`, * meaning this line/column location originated from this source file. */ traceSegment(line, column, name) { return { column, line, name, source: this }; } } /* istanbul ignore next */ const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL); // Matches "..", which must be preceeded by "/" or the start of the string, and // must be followed by a "/". We do not eat the following "/", so that the next // iteration can match on it. const parentRegex = /(^|\/)\.\.(?=\/|$)/g; function isAbsoluteUrl(url) { try { return !!new Url$1(url); } catch (e) { return false; } } /** * Creates a directory name that is guaranteed to not be in `str`. */ function uniqInStr(str) { let uniq = String(Math.random()).slice(2); while (str.indexOf(uniq) > -1) { /* istanbul ignore next */ uniq += uniq; } return uniq; } /** * Removes the filename from the path (everything trailing the last "/"). This * is only safe to call on a path, never call with an absolute or protocol * relative URL. */ function stripPathFilename(path) { path = normalizePath$5(path); const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } /** * Normalizes a protocol-relative URL, but keeps it protocol relative by * stripping out the protocl before returning it. */ function normalizeProtocolRelative(input, absoluteBase) { const { href, protocol } = new Url$1(input, absoluteBase); return href.slice(protocol.length); } /** * Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can * be normalized absolutely). */ function normalizeSimplePath(input) { const { href } = new Url$1(input, 'https://foo.com/'); return href.slice('https://foo.com/'.length); } /** * Normalizes a path, ensuring that excess ".."s are preserved for relative * paths in the output. * * If the input is absolute, this will return an absolutey normalized path, but * it will not have a leading "/". * * If the input has a leading "..", the output will have a leading "..". * * If the input has a leading ".", the output will not have a leading "." * unless there are too many ".."s, in which case there will be a leading "..". */ function normalizePath$5(input) { // If there are no ".."s, we can treat this as if it were an absolute path. // The return won't be an absolute path, so it's easy. if (!parentRegex.test(input)) return normalizeSimplePath(input); // We already found one "..". Let's see how many there are. let total = 1; while (parentRegex.test(input)) total++; // If there are ".."s, we need to prefix the the path with the same number of // unique directories. This is to ensure that we "remember" how many parent // directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.." // must keep 1. const uniqDirectory = `z${uniqInStr(input)}/`; // uniqDirectory is just a "z", followed by numbers, followed by a "/". So // generating a runtime regex from it is safe. We'll use this search regex to // strip out our uniq directory names and insert any needed ".."s. const search = new RegExp(`^(?:${uniqDirectory})*`); // Now we can resolve the total path. If there are excess ".."s, they will // eliminate one or more of the unique directories we prefix with. const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input); // We can now count the number of unique directories that were eliminated. If // there were 3, and 1 was eliminated, we know we only need to add 1 "..". If // 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated, // then we need 3, etc. This replace is guranteed to match (it may match 0 or // more times), and we can count the total match to see how many were eliminated. return relative.replace(search, (all) => { const leftover = all.length / uniqDirectory.length; return '../'.repeat(total - leftover); }); } /** * Attempts to resolve `input` URL relative to `base`. */ function resolve$3(input, base) { if (!base) base = ''; // Absolute URLs are very easy to resolve right. if (isAbsoluteUrl(input)) return new Url$1(input).href; if (base) { // Absolute URLs are easy... if (isAbsoluteUrl(base)) return new Url$1(input, base).href; // If base is protocol relative, we'll resolve with it but keep the result // protocol relative. if (base.startsWith('//')) return normalizeProtocolRelative(input, `https:${base}`); } // Normalize input, but keep it protocol relative. We know base doesn't supply // a protocol, because that would have been handled above. if (input.startsWith('//')) return normalizeProtocolRelative(input, 'https://foo.com/'); // We now know that base (if there is one) and input are paths. We've handled // both absolute and protocol-relative variations above. // Absolute paths don't need any special handling, because they cannot have // extra "." or ".."s. That'll all be stripped away. Input takes priority here, // because if input is an absolute path, base path won't affect it in any way. if (input.startsWith('/')) return '/' + normalizeSimplePath(input); // Since input and base are paths, we need to join them to do any further // processing. Paths are joined at the directory level, so we need to remove // the base's filename before joining. We also know that input does not have a // leading slash, and that the stripped base will have a trailing slash if // there are any directories (or it'll be empty). const joined = stripPathFilename(base) + input; // If base is an absolute path, then input will be relative to it. if (base.startsWith('/')) return '/' + normalizeSimplePath(joined); // We now know both base (if there is one) and input are relative paths. const relative = normalizePath$5(joined); // If base started with a leading ".", or there is no base and input started // with a ".", then we need to ensure that the relative path starts with a // ".". We don't know if relative starts with a "..", though, so check before // prepending. if ((base || input).startsWith('.') && !relative.startsWith('.')) { return './' + relative; } return relative; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function resolve$1$1(input, base) { // The base is always treated as a directory, if it's not empty. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 if (base && !base.endsWith('/')) base += '/'; return resolve$3(input, base); } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A binary search implementation that returns the index if a match is found, * or the negated index of where the `needle` should be inserted. * * The `comparator` callback receives both the `item` under comparison and the * needle we are searching for. It must return `0` if the `item` is a match, * any negative number if `item` is too small (and we must search after it), or * any positive number if the `item` is too large (and we must search before * it). * * If no match is found, a negated index of where to insert the `needle` is * returned. This negated index is guaranteed to be less than 0. To insert an * item, negate it (again) and splice: * * ```js * const array = [1, 3]; * const needle = 2; * const index = binarySearch(array, needle, (item, needle) => item - needle); * * assert.equal(index, -2); * assert.equal(~index, 1); * array.splice(~index, 0, needle); * assert.deepEqual(array, [1, 2, 3]); * ``` */ function binarySearch$2(haystack, needle, comparator, low, high) { low = Math.max(low, 0); while (low <= high) { const mid = low + ((high - low) >> 1); const cmp = comparator(haystack[mid], needle); if (cmp === 0) { return mid; } if (cmp < 0) { low = mid + 1; } else { high = mid - 1; } } return ~low; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * FastStringArray acts like a `Set` (allowing only one occurrence of a string * `key`), but provides the index of the `key` in the backing array. * * This is designed to allow synchronizing a second array with the contents of * the backing array, like how `sourcesContent[i]` is the source content * associated with `source[i]`, and there are never duplicates. */ class FastStringArray { constructor() { this.indexes = Object.create(null); this.array = []; } /** * Puts `key` into the backing array, if it is not already present. Returns * the index of the `key` in the backing array. */ put(key) { const { array, indexes } = this; // The key may or may not be present. If it is present, it's a number. let index = indexes[key]; // If it's not yet present, we need to insert it and track the index in the // indexes. if (index === undefined) { index = indexes[key] = array.length; array.push(key); } return index; } } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * SourceMapTree represents a single sourcemap, with the ability to trace * mappings into its child nodes (which may themselves be SourceMapTrees). */ class SourceMapTree { constructor(map, sources) { this.map = map; this.sources = sources; this.lastLine = 0; this.lastColumn = 0; this.lastIndex = 0; } /** * traceMappings is only called on the root level SourceMapTree, and begins * the process of resolving each mapping in terms of the original source * files. */ traceMappings() { const mappings = []; const names = new FastStringArray(); const sources = new FastStringArray(); const sourcesContent = []; const { mappings: rootMappings, names: rootNames } = this.map; for (let i = 0; i < rootMappings.length; i++) { const segments = rootMappings[i]; const tracedSegments = []; let lastTraced = undefined; for (let j = 0; j < segments.length; j++) { const segment = segments[j]; // 1-length segments only move the current generated column, there's no // source information to gather from it. if (segment.length === 1) continue; const source = this.sources[segment[1]]; const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); if (!traced) continue; // So we traced a segment down into its original source file. Now push a // new segment pointing to this location. const { column, line, name } = traced; const { content, filename } = traced.source; // Store the source location, and ensure we keep sourcesContent up to // date with the sources array. const sourceIndex = sources.put(filename); sourcesContent[sourceIndex] = content; if (lastTraced && lastTraced[1] === sourceIndex && lastTraced[2] === line && lastTraced[3] === column) { // This is a duplicate mapping pointing at the exact same starting point in the source file. // It doesn't provide any new information, and only bloats the sourcemap. continue; } // This looks like unnecessary duplication, but it noticeably increases // performance. If we were to push the nameIndex onto length-4 array, v8 // would internally allocate 22 slots! That's 68 wasted bytes! Array // literals have the same capacity as their length, saving memory. if (name) { lastTraced = [segment[0], sourceIndex, line, column, names.put(name)]; } else { lastTraced = [segment[0], sourceIndex, line, column]; } tracedSegments.push(lastTraced); } mappings.push(tracedSegments); } // TODO: Make all sources relative to the sourceRoot. return defaults({ mappings, names: names.array, sources: sources.array, sourcesContent, }, this.map); } /** * traceSegment is only called on children SourceMapTrees. It recurses down * into its own child SourceMapTrees, until we find the original source map. */ traceSegment(line, column, name) { const { mappings, names } = this.map; // It's common for parent sourcemaps to have pointers to lines that have no // mapping (like a "//# sourceMappingURL=") at the end of the child file. if (line >= mappings.length) return null; const segments = mappings[line]; if (segments.length === 0) return null; let low = 0; let high = segments.length - 1; if (line === this.lastLine) { if (column >= this.lastColumn) { low = this.lastIndex; } else { high = this.lastIndex; } } let index = binarySearch$2(segments, column, segmentComparator$1, low, high); this.lastLine = line; this.lastColumn = column; if (index === -1) { this.lastIndex = index; return null; // we come before any mapped segment } // If we can't find a segment that lines up to this column, we use the // segment before. if (index < 0) { index = ~index - 1; } this.lastIndex = index; const segment = segments[index]; // 1-length segments only move the current generated column, there's no // source information to gather from it. if (segment.length === 1) return null; const source = this.sources[segment[1]]; // So now we can recurse down, until we hit the original source file. return source.traceSegment(segment[2], segment[3], // A child map's recorded name for this segment takes precedence over the // parent's mapped name. Imagine a mangler changing the name over, etc. segment.length === 5 ? names[segment[4]] : name); } } function segmentComparator$1(segment, column) { return segment[0] - column; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Removes the filename from a path. */ function stripFilename(path) { if (!path) return ''; const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function asArray(value) { if (Array.isArray(value)) return value; return [value]; } /** * Recursively builds a tree structure out of sourcemap files, with each node * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of * `OriginalSource`s and `SourceMapTree`s. * * Every sourcemap is composed of a collection of source files and mappings * into locations of those source files. When we generate a `SourceMapTree` for * the sourcemap, we attempt to load each source file's own sourcemap. If it * does not have an associated sourcemap, it is considered an original, * unmodified source file. */ function buildSourceMapTree(input, loader, relativeRoot) { const maps = asArray(input).map(decodeSourceMap); const map = maps.pop(); for (let i = 0; i < maps.length; i++) { if (maps[i].sources.length !== 1) { throw new Error(`Transformation map ${i} must have exactly one source file.\n` + 'Did you specify these with the most recent transformation maps first?'); } } const { sourceRoot, sources, sourcesContent } = map; const children = sources.map((sourceFile, i) => { // Each source file is loaded relative to the sourcemap's own sourceRoot, // which is itself relative to the sourcemap's parent. const uri = resolve$1$1(sourceFile || '', resolve$1$1(sourceRoot || '', stripFilename(relativeRoot))); // Use the provided loader callback to retrieve the file's sourcemap. // TODO: We should eventually support async loading of sourcemap files. const sourceMap = loader(uri); // If there is no sourcemap, then it is an unmodified source file. if (!sourceMap) { // The source file's actual contents must be included in the sourcemap // (done when generating the sourcemap) for it to be included as a // sourceContent in the output sourcemap. const sourceContent = sourcesContent ? sourcesContent[i] : null; return new OriginalSource(uri, sourceContent); } // Else, it's a real sourcemap, and we need to recurse into it to load its // source files. return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri); }); let tree = new SourceMapTree(map, children); for (let i = maps.length - 1; i >= 0; i--) { tree = new SourceMapTree(maps[i], [tree]); } return tree; } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A SourceMap v3 compatible sourcemap, which only includes fields that were * provided to it. */ class SourceMap$1 { constructor(map, options) { this.version = 3; // SourceMap spec says this should be first. if ('file' in map) this.file = map.file; this.mappings = options.decodedMappings ? map.mappings : encode$1(map.mappings); this.names = map.names; // TODO: We first need to make all source URIs relative to the sourceRoot // before we can support a sourceRoot. // if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot; this.sources = map.sources; if (!options.excludeContent && 'sourcesContent' in map) { this.sourcesContent = map.sourcesContent; } } toString() { return JSON.stringify(this); } } /** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Traces through all the mappings in the root sourcemap, through the sources * (and their sourcemaps), all the way back to the original source location. * * `loader` will be called every time we encounter a source file. If it returns * a sourcemap, we will recurse into that sourcemap to continue the trace. If * it returns a falsey value, that source file is treated as an original, * unmodified source file. * * Pass `excludeContent` to exclude any self-containing source file content * from the output sourcemap. * * Pass `decodedMappings` to receive a SourceMap with decoded (instead of * VLQ encoded) mappings. */ function remapping(input, loader, options) { const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; const graph = buildSourceMapTree(input, loader); return new SourceMap$1(graph.traceMappings(), opts); } function slash$3(p) { return p.replace(/\\/g, '/'); } // Strip valid id prefix. This is prepended to resolved Ids that are // not valid browser import specifiers by the importAnalysis plugin. function unwrapId$1(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id; } const flattenId = (id) => id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.]/g, '_'); const normalizeId$1 = (id) => id.replace(/(\s*>\s*)/g, ' > '); function isBuiltin(id) { const deepMatch = id.match(deepImportRE); id = deepMatch ? deepMatch[1] || deepMatch[2] : id; return builtinModules_1.includes(id); } const bareImportRE = /^[\w@](?!.*:\/\/)/; const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; let isRunningWithYarnPnp; try { isRunningWithYarnPnp = Boolean(require('pnpapi')); } catch { } const ssrExtensions = ['.js', '.cjs', '.json', '.node']; function resolveFrom$3(id, basedir, preserveSymlinks = false, ssr = false) { return resolve__default.sync(id, { basedir, extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS, // necessary to work with pnpm preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false }); } /** * like `resolveFrom` but supports resolving `>` path in `id`, * for example: `foo > bar > baz` */ function nestedResolveFrom(id, basedir, preserveSymlinks = false) { const pkgs = id.split('>').map((pkg) => pkg.trim()); try { for (const pkg of pkgs) { basedir = resolveFrom$3(pkg, basedir, preserveSymlinks); } } catch { } return basedir; } // set in bin/vite.js const filter$1 = process.env.VITE_DEBUG_FILTER; const DEBUG$1 = process.env.DEBUG; function createDebugger(namespace, options = {}) { const log = debug$f(namespace); const { onlyWhenFocused } = options; const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; return (msg, ...args) => { if (filter$1 && !msg.includes(filter$1)) { return; } if (onlyWhenFocused && !(DEBUG$1 === null || DEBUG$1 === void 0 ? void 0 : DEBUG$1.includes(focus))) { return; } log(msg, ...args); }; } const isWindows$4 = require$$0__default$1.platform() === 'win32'; const VOLUME_RE = /^[A-Z]:/i; function normalizePath$4(id) { return path__default.posix.normalize(isWindows$4 ? slash$3(id) : id); } function fsPathFromId(id) { const fsPath = normalizePath$4(id.slice(FS_PREFIX.length)); return fsPath.startsWith('/') || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`; } function ensureVolumeInPath(file) { return isWindows$4 ? path__default.resolve(file) : file; } const queryRE = /\?.*$/s; const hashRE = /#.*$/s; const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, ''); const externalRE = /^(https?:)?\/\//; const isExternalUrl = (url) => externalRE.test(url); const dataUrlRE = /^\s*data:/i; const isDataUrl = (url) => dataUrlRE.test(url); const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/; const isJSRequest = (url) => { url = cleanUrl(url); if (knownJsSrcRE.test(url)) { return true; } if (!path__default.extname(url) && !url.endsWith('/')) { return true; } return false; }; const importQueryRE = /(\?|&)import=?(?:&|$)/; const internalPrefixes = [ FS_PREFIX, VALID_ID_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH ]; const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); const trailingSeparatorRE = /[\?&]$/; const isImportRequest = (url) => importQueryRE.test(url); const isInternalRequest = (url) => InternalPrefixRE.test(url); function removeImportQuery(url) { return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); } function injectQuery(url, queryToInject) { // encode percents for consistent behavior with pathToFileURL // see #2614 for details let resolvedUrl = new require$$0$8.URL(url.replace(/%/g, '%25'), 'relative:///'); if (resolvedUrl.protocol !== 'relative:') { resolvedUrl = require$$0$8.pathToFileURL(url); } let { protocol, pathname, search, hash } = resolvedUrl; if (protocol === 'file:') { pathname = pathname.slice(1); } pathname = decodeURIComponent(pathname); return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; } const timestampRE = /\bt=\d{13}&?\b/; function removeTimestampQuery(url) { return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); } async function asyncReplace(input, re, replacer) { let match; let remaining = input; let rewritten = ''; while ((match = re.exec(remaining))) { rewritten += remaining.slice(0, match.index); rewritten += await replacer(match); remaining = remaining.slice(match.index + match[0].length); } rewritten += remaining; return rewritten; } function timeFrom(start, subtract = 0) { const time = perf_hooks.performance.now() - start - subtract; const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' '); if (time < 10) { return source.green(timeString); } else if (time < 50) { return source.yellow(timeString); } else { return source.red(timeString); } } /** * pretty url for logging. */ function prettifyUrl(url, root) { url = removeTimestampQuery(url); const isAbsoluteFile = url.startsWith(root); if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); const seg = file.split('/'); const npmIndex = seg.indexOf(`node_modules`); const isSourceMap = file.endsWith('.map'); if (npmIndex > 0) { file = seg[npmIndex + 1]; if (file.startsWith('@')) { file = `${file}/${seg[npmIndex + 2]}`; } file = `npm: ${source.dim(file)}${isSourceMap ? ` (source map)` : ``}`; } return source.dim(file); } else { return source.dim(url); } } function isObject$3(value) { return Object.prototype.toString.call(value) === '[object Object]'; } function isDefined(value) { return value != null; } function lookupFile(dir, formats, pathOnly = false) { for (const format of formats) { const fullPath = path__default.join(dir, format); if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) { return pathOnly ? fullPath : fs__default.readFileSync(fullPath, 'utf-8'); } } const parentDir = path__default.dirname(dir); if (parentDir !== dir) { return lookupFile(parentDir, formats, pathOnly); } } const splitRE = /\r?\n/; const range$1 = 2; function pad$1(source, n = 2) { const lines = source.split(splitRE); return lines.map((l) => ` `.repeat(n) + l).join(`\n`); } function posToNumber(source, pos) { if (typeof pos === 'number') return pos; const lines = source.split(splitRE); const { line, column } = pos; let start = 0; for (let i = 0; i < line - 1; i++) { start += lines[i].length + 1; } return start + column; } function numberToPos(source, offset) { if (typeof offset !== 'number') return offset; if (offset > source.length) { throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); } const lines = source.split(splitRE); let counted = 0; let line = 0; let column = 0; for (; line < lines.length; line++) { const lineLength = lines[line].length + 1; if (counted + lineLength >= offset) { column = offset - counted + 1; break; } counted += lineLength; } return { line: line + 1, column }; } function generateCodeFrame(source, start = 0, end) { start = posToNumber(source, start); end = end || start; const lines = source.split(splitRE); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (let j = i - range$1; j <= i + range$1 || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { // push underline const pad = start - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start); res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + '^'.repeat(length)); } count += lineLength + 1; } } break; } } return res.join('\n'); } function writeFile(filename, content) { const dir = path__default.dirname(filename); if (!fs__default.existsSync(dir)) { fs__default.mkdirSync(dir, { recursive: true }); } fs__default.writeFileSync(filename, content); } /** * Use instead of fs.existsSync(filename) * #2051 if we don't have read permission on a directory, existsSync() still * works and will result in massively slow subsequent checks (which are * unnecessary in the first place) */ function isFileReadable(filename) { try { fs__default.accessSync(filename, fs__default.constants.R_OK); return true; } catch { return false; } } /** * Delete every file and subdirectory. **The given directory must exist.** * Pass an optional `skip` array to preserve files in the root directory. */ function emptyDir(dir, skip) { for (const file of fs__default.readdirSync(dir)) { if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) { continue; } const abs = path__default.resolve(dir, file); // baseline is Node 12 so can't use rmSync :( if (fs__default.lstatSync(abs).isDirectory()) { emptyDir(abs); fs__default.rmdirSync(abs); } else { fs__default.unlinkSync(abs); } } } function copyDir(srcDir, destDir) { fs__default.mkdirSync(destDir, { recursive: true }); for (const file of fs__default.readdirSync(srcDir)) { const srcFile = path__default.resolve(srcDir, file); if (srcFile === destDir) { continue; } const destFile = path__default.resolve(destDir, file); const stat = fs__default.statSync(srcFile); if (stat.isDirectory()) { copyDir(srcFile, destFile); } else { fs__default.copyFileSync(srcFile, destFile); } } } function ensureLeadingSlash(path) { return !path.startsWith('/') ? '/' + path : path; } function ensureWatchedFile(watcher, file, root) { if (file && // only need to watch if out of root !file.startsWith(root + '/') && // some rollup plugins use null bytes for private resolved Ids !file.includes('\0') && fs__default.existsSync(file)) { // resolve file to normalized system path watcher.add(path__default.resolve(file)); } } const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; async function processSrcSet(srcs, replacer) { const imageCandidates = srcs .split(',') .map((s) => { const [url, descriptor] = s .replace(escapedSpaceCharacters, ' ') .trim() .split(' ', 2); return { url, descriptor }; }) .filter(({ url }) => !!url); const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => { return { url: await replacer({ url, descriptor }), descriptor }; })); const url = ret.reduce((prev, { url, descriptor }, index) => { descriptor = descriptor || ''; return (prev += url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); }, ''); return url; } // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 const nullSourceMap = { names: [], sources: [], mappings: '', version: 3 }; function combineSourcemaps(filename, sourcemapList) { if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) { return { ...nullSourceMap }; } // We don't declare type here so we can convert/fake/map as RawSourceMap let map; //: SourceMap let mapIndex = 1; const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; if (useArrayInterface) { map = remapping(sourcemapList, () => null, true); } else { map = remapping(sourcemapList[0], function loader(sourcefile) { if (sourcefile === filename && sourcemapList[mapIndex]) { return sourcemapList[mapIndex++]; } else { return { ...nullSourceMap }; } }, true); } if (!map.file) { delete map.file; } return map; } function unique(arr) { return Array.from(new Set(arr)); } function resolveHostname(optionsHost) { let host; if (optionsHost === undefined || optionsHost === false || optionsHost === 'localhost') { // Use a secure default host = '127.0.0.1'; } else if (optionsHost === true) { // If passed --host in the CLI without arguments host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) } else { host = optionsHost; } // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1' const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') || host === '0.0.0.0' || host === '::' || host === undefined ? 'localhost' : host; return { host, name }; } function arraify(target) { return Array.isArray(target) ? target : [target]; } function toUpperCaseDriveLetter(pathName) { return pathName.replace(/^\w:/, (letter) => letter.toUpperCase()); } const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm; const singlelineCommentsRE = /\/\/.*/g; /** * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. * * @param file File path to import. */ const dynamicImport = new Function('file', 'return import(file)'); /* eslint no-console: 0 */ const LogLevels = { silent: 0, error: 1, warn: 2, info: 3 }; let lastType; let lastMsg; let sameCount = 0; function clearScreen() { const repeatCount = process.stdout.rows - 2; const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; console.log(blank); readline__default.cursorTo(process.stdout, 0, 0); readline__default.clearScreenDown(process.stdout); } function createLogger(level = 'info', options = {}) { if (options.customLogger) { return options.customLogger; } const loggedErrors = new WeakSet(); const { prefix = '[vite]', allowClearScreen = true } = options; const thresh = LogLevels[level]; const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI ? clearScreen : () => { }; function output(type, msg, options = {}) { if (thresh >= LogLevels[type]) { const method = type === 'info' ? 'log' : type; const format = () => { if (options.timestamp) { const tag = type === 'info' ? source.cyan.bold(prefix) : type === 'warn' ? source.yellow.bold(prefix) : source.red.bold(prefix); return `${source.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`; } else { return msg; } }; if (options.error) { loggedErrors.add(options.error); } if (type === lastType && msg === lastMsg) { sameCount++; clear(); console[method](format(), source.yellow(`(x${sameCount + 1})`)); } else { sameCount = 0; lastMsg = msg; lastType = type; if (options.clear) { clear(); } console[method](format()); } } } const warnedMessages = new Set(); const logger = { hasWarned: false, info(msg, opts) { output('info', msg, opts); }, warn(msg, opts) { logger.hasWarned = true; output('warn', msg, opts); }, warnOnce(msg, opts) { if (warnedMessages.has(msg)) return; logger.hasWarned = true; output('warn', msg, opts); warnedMessages.add(msg); }, error(msg, opts) { logger.hasWarned = true; output('error', msg, opts); }, clearScreen(type) { if (thresh >= LogLevels[type]) { clear(); } }, hasErrorLogged(error) { return loggedErrors.has(error); } }; return logger; } function printHttpServerUrls(server, config) { const address = server.address(); const isAddressInfo = (x) => x === null || x === void 0 ? void 0 : x.address; if (isAddressInfo(address)) { const hostname = resolveHostname(config.server.host); const protocol = config.server.https ? 'https' : 'http'; printServerUrls(hostname, protocol, address.port, config.base, config.logger.info); } } function printServerUrls(hostname, protocol, port, base, info) { if (hostname.host === '127.0.0.1') { const url = `${protocol}://${hostname.name}:${source.bold(port)}${base}`; info(` > Local: ${source.cyan(url)}`); if (hostname.name !== '127.0.0.1') { info(` > Network: ${source.dim('use `--host` to expose')}`); } } else { Object.values(require$$0__default$1.networkInterfaces()) .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : []) .filter((detail) => detail && detail.address && detail.family === 'IPv4') .map((detail) => { const type = detail.address.includes('127.0.0.1') ? 'Local: ' : 'Network: '; const host = detail.address.replace('127.0.0.1', hostname.name); const url = `${protocol}://${host}:${source.bold(port)}${base}`; return ` > ${type} ${source.cyan(url)}`; }) .forEach((msg) => info(msg)); } } const writeColors = { [0 /* JS */]: source.cyan, [1 /* CSS */]: source.magenta, [2 /* ASSET */]: source.green, [3 /* HTML */]: source.blue, [4 /* SOURCE_MAP */]: source.gray }; function buildReporterPlugin(config) { const compress = require$$0$6.promisify(require$$0$9.gzip); const chunkLimit = config.build.chunkSizeWarningLimit; function isLarge(code) { // bail out on particularly large chunks return code.length / 1024 > chunkLimit; } async function getCompressedSize(code) { if (config.build.ssr || !config.build.reportCompressedSize || config.build.brotliSize === false) { return ''; } return ` / gzip: ${((await compress(typeof code === 'string' ? code : Buffer.from(code))) .length / 1024).toFixed(2)} KiB`; } function printFileInfo(filePath, content, type, maxLength, compressedSize = '') { const outDir = normalizePath$4(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/'; const kibs = content.length / 1024; const sizeColor = kibs > chunkLimit ? source.yellow : source.dim; config.logger.info(`${source.gray(source.white.dim(outDir))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`); } const tty = process.stdout.isTTY && !process.env.CI; const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; let hasTransformed = false; let hasRenderedChunk = false; let transformedCount = 0; let chunkCount = 0; const logTransform = throttle((id) => { writeLine(`transforming (${transformedCount}) ${source.dim(path__default.relative(config.root, id))}`); }); return { name: 'vite:reporter', transform(_, id) { transformedCount++; if (shouldLogInfo) { if (!tty) { if (!hasTransformed) { config.logger.info(`transforming...`); } } else { if (id.includes(`?`)) return; logTransform(id); } hasTransformed = true; } return null; }, buildEnd() { if (shouldLogInfo) { if (tty) { process.stdout.clearLine(0); process.stdout.cursorTo(0); } config.logger.info(`${source.green(`✓`)} ${transformedCount} modules transformed.`); } }, renderStart() { chunkCount = 0; }, renderChunk() { chunkCount++; if (shouldLogInfo) { if (!tty) { if (!hasRenderedChunk) { config.logger.info('rendering chunks...'); } } else { writeLine(`rendering chunks (${chunkCount})...`); } hasRenderedChunk = true; } return null; }, generateBundle() { if (shouldLogInfo && tty) { process.stdout.clearLine(0); process.stdout.cursorTo(0); } }, async writeBundle(_, output) { let hasLargeChunks = false; if (shouldLogInfo) { let longest = 0; for (const file in output) { const l = output[file].fileName.length; if (l > longest) longest = l; } // large chunks are deferred to be logged at the end so they are more // visible. const deferredLogs = []; await Promise.all(Object.keys(output).map(async (file) => { const chunk = output[file]; if (chunk.type === 'chunk') { const log = async () => { printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code)); if (chunk.map) { printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest); } }; if (isLarge(chunk.code)) { hasLargeChunks = true; deferredLogs.push(log); } else { await log(); } } else if (chunk.source) { const isCSS = chunk.fileName.endsWith('.css'); printFileInfo(chunk.fileName, chunk.source, isCSS ? 1 /* CSS */ : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined); } })); await Promise.all(deferredLogs.map((l) => l())); } else { hasLargeChunks = Object.keys(output).some((file) => { const chunk = output[file]; return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit; }); } if (hasLargeChunks && config.build.minify && !config.build.lib && !config.build.ssr) { config.logger.warn(source.yellow(`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` + `- Using dynamic import() to code-split the application\n` + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); } } }; } function writeLine(output) { process.stdout.clearLine(0); process.stdout.cursorTo(0); if (output.length < process.stdout.columns) { process.stdout.write(output); } else { process.stdout.write(output.substring(0, process.stdout.columns - 1)); } } function throttle(fn) { let timerHandle = null; return (...args) => { if (timerHandle) return; fn(...args); timerHandle = setTimeout(() => { timerHandle = null; }, 100); }; } var charToInteger = {}; var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; for (var i$1 = 0; i$1 < chars$1.length; i$1++) { charToInteger[chars$1.charCodeAt(i$1)] = i$1; } function encode(decoded) { var sourceFileIndex = 0; // second field var sourceCodeLine = 0; // third field var sourceCodeColumn = 0; // fourth field var nameIndex = 0; // fifth field var mappings = ''; for (var i = 0; i < decoded.length; i++) { var line = decoded[i]; if (i > 0) mappings += ';'; if (line.length === 0) continue; var generatedCodeColumn = 0; // first field var lineMappings = []; for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { var segment = line_1[_i]; var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); generatedCodeColumn = segment[0]; if (segment.length > 1) { segmentMappings += encodeInteger(segment[1] - sourceFileIndex) + encodeInteger(segment[2] - sourceCodeLine) + encodeInteger(segment[3] - sourceCodeColumn); sourceFileIndex = segment[1]; sourceCodeLine = segment[2]; sourceCodeColumn = segment[3]; } if (segment.length === 5) { segmentMappings += encodeInteger(segment[4] - nameIndex); nameIndex = segment[4]; } lineMappings.push(segmentMappings); } mappings += lineMappings.join(','); } return mappings; } function encodeInteger(num) { var result = ''; num = num < 0 ? (-num << 1) | 1 : num << 1; do { var clamped = num & 31; num >>>= 5; if (num > 0) { clamped |= 32; } result += chars$1[clamped]; } while (num > 0); return result; } var BitSet = function BitSet(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; }; BitSet.prototype.add = function add (n) { this.bits[n >> 5] |= 1 << (n & 31); }; BitSet.prototype.has = function has (n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); }; var Chunk = function Chunk(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; // we make these non-enumerable, for sanity while debugging Object.defineProperties(this, { previous: { writable: true, value: null }, next: { writable: true, value: null } }); }; Chunk.prototype.appendLeft = function appendLeft (content) { this.outro += content; }; Chunk.prototype.appendRight = function appendRight (content) { this.intro = this.intro + content; }; Chunk.prototype.clone = function clone () { var chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; }; Chunk.prototype.contains = function contains (index) { return this.start < index && index < this.end; }; Chunk.prototype.eachNext = function eachNext (fn) { var chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } }; Chunk.prototype.eachPrevious = function eachPrevious (fn) { var chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } }; Chunk.prototype.edit = function edit (content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; }; Chunk.prototype.prependLeft = function prependLeft (content) { this.outro = content + this.outro; }; Chunk.prototype.prependRight = function prependRight (content) { this.intro = content + this.intro; }; Chunk.prototype.split = function split (index) { var sliceIndex = index - this.start; var originalBefore = this.original.slice(0, sliceIndex); var originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; var newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) { newChunk.next.previous = newChunk; } newChunk.previous = this; this.next = newChunk; return newChunk; }; Chunk.prototype.toString = function toString () { return this.intro + this.content + this.outro; }; Chunk.prototype.trimEnd = function trimEnd (rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } var trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } } }; Chunk.prototype.trimStart = function trimStart (rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } var trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.end - trimmed.length); this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } } }; var btoa$1 = function () { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; if (typeof window !== 'undefined' && typeof window.btoa === 'function') { btoa$1 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; } else if (typeof Buffer === 'function') { btoa$1 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; } var SourceMap = function SourceMap(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode(properties.mappings); }; SourceMap.prototype.toString = function toString () { return JSON.stringify(this); }; SourceMap.prototype.toUrl = function toUrl () { return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); }; function guessIndent(code) { var lines = code.split('\n'); var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple var min = spaced.reduce(function (previous, current) { var numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath(from, to) { var fromParts = from.split(/[/\\]/); var toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { var i = fromParts.length; while (i--) { fromParts[i] = '..'; } } return fromParts.concat(toParts).join('/'); } var toString$2 = Object.prototype.toString; function isObject$2(thing) { return toString$2.call(thing) === '[object Object]'; } function getLocator(source) { var originalLines = source.split('\n'); var lineOffsets = []; for (var i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { var i = 0; var j = lineOffsets.length; while (i < j) { var m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } var line = i - 1; var column = index - lineOffsets[line]; return { line: line, column: column }; }; } var Mappings = function Mappings(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; }; Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { if (content.length) { var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } else if (this.pending) { this.rawSegments.push(this.pending); } this.advance(content); this.pending = null; }; Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { var originalCharIndex = chunk.start; var first = true; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; }; Mappings.prototype.advance = function advance (str) { if (!str) { return; } var lines = str.split('\n'); if (lines.length > 1) { for (var i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; }; var n = '\n'; var warned$1 = { insertLeft: false, insertRight: false, storeName: false }; var MagicString = function MagicString(string, options) { if ( options === void 0 ) options = {}; var chunk = new Chunk(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: guessIndent(string) } }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; }; MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { this.sourcemapLocations.add(char); }; MagicString.prototype.append = function append (content) { if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } this.outro += content; return this; }; MagicString.prototype.appendLeft = function appendLeft (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; }; MagicString.prototype.appendRight = function appendRight (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; }; MagicString.prototype.clone = function clone () { var cloned = new MagicString(this.original, { filename: this.filename }); var originalChunk = this.firstChunk; var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; var nextOriginalChunk = originalChunk.next; var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; }; MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { var this$1$1 = this; options = options || {}; var sourceIndex = 0; var names = Object.keys(this.storedNames); var mappings = new Mappings(options.hires); var locate = getLocator(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext(function (chunk) { var loc = locate(chunk.start); if (chunk.intro.length) { mappings.advance(chunk.intro); } if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1 ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); } if (chunk.outro.length) { mappings.advance(chunk.outro); } }); return { file: options.file ? options.file.split(/[/\\]/).pop() : null, sources: [options.source ? getRelativePath(options.file || '', options.source) : null], sourcesContent: options.includeContent ? [this.original] : [null], names: names, mappings: mappings.raw }; }; MagicString.prototype.generateMap = function generateMap (options) { return new SourceMap(this.generateDecodedMap(options)); }; MagicString.prototype.getIndentString = function getIndentString () { return this.indentStr === null ? '\t' : this.indentStr; }; MagicString.prototype.indent = function indent (indentStr, options) { var pattern = /^[^\r\n]/gm; if (isObject$2(indentStr)) { options = indentStr; indentStr = undefined; } indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; if (indentStr === '') { return this; } // noop options = options || {}; // Process exclusion ranges var isExcluded = {}; if (options.exclude) { var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach(function (exclusion) { for (var i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } var shouldIndentNextCharacter = options.indentStart !== false; var replacer = function (match) { if (shouldIndentNextCharacter) { return ("" + indentStr + match); } shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); var charIndex = 0; var chunk = this.firstChunk; while (chunk) { var end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { var char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; }; MagicString.prototype.insert = function insert () { throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'); }; MagicString.prototype.insertLeft = function insertLeft (index, content) { if (!warned$1.insertLeft) { console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console warned$1.insertLeft = true; } return this.appendLeft(index, content); }; MagicString.prototype.insertRight = function insertRight (index, content) { if (!warned$1.insertRight) { console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console warned$1.insertRight = true; } return this.prependRight(index, content); }; MagicString.prototype.move = function move (start, end, index) { if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } this._split(start); this._split(end); this._split(index); var first = this.byStart[start]; var last = this.byEnd[end]; var oldLeft = first.previous; var oldRight = last.next; var newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) { return this; } var newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) { oldLeft.next = oldRight; } if (oldRight) { oldRight.previous = oldLeft; } if (newLeft) { newLeft.next = first; } if (newRight) { newRight.previous = last; } if (!first.previous) { this.firstChunk = last.next; } if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) { this.firstChunk = first; } if (!newRight) { this.lastChunk = last; } return this; }; MagicString.prototype.overwrite = function overwrite (start, end, content, options) { if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } if (end > this.original.length) { throw new Error('end is out of bounds'); } if (start === end) { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); } this._split(start); this._split(end); if (options === true) { if (!warned$1.storeName) { console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console warned$1.storeName = true; } options = { storeName: true }; } var storeName = options !== undefined ? options.storeName : false; var contentOnly = options !== undefined ? options.contentOnly : false; if (storeName) { var original = this.original.slice(start, end); this.storedNames[original] = true; } var first = this.byStart[start]; var last = this.byEnd[end]; if (first) { if (end > first.end && first.next !== this.byStart[first.end]) { throw new Error('Cannot overwrite across a split point'); } first.edit(content, storeName, contentOnly); if (first !== last) { var chunk = first.next; while (chunk !== last) { chunk.edit('', false); chunk = chunk.next; } chunk.edit('', false); } } else { // must be inserting at the end var newChunk = new Chunk(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; }; MagicString.prototype.prepend = function prepend (content) { if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } this.intro = content + this.intro; return this; }; MagicString.prototype.prependLeft = function prependLeft (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; }; MagicString.prototype.prependRight = function prependRight (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; }; MagicString.prototype.remove = function remove (start, end) { while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } if (start === end) { return this; } if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } if (start > end) { throw new Error('end must be greater than start'); } this._split(start); this._split(end); var chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; }; MagicString.prototype.lastChar = function lastChar () { if (this.outro.length) { return this.outro[this.outro.length - 1]; } var chunk = this.lastChunk; do { if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; } if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; } if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; } } while (chunk = chunk.previous); if (this.intro.length) { return this.intro[this.intro.length - 1]; } return ''; }; MagicString.prototype.lastLine = function lastLine () { var lineIndex = this.outro.lastIndexOf(n); if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); } var lineStr = this.outro; var chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n); if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; } lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n); if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; } lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n); if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; } lineStr = chunk.intro + lineStr; } } while (chunk = chunk.previous); lineIndex = this.intro.lastIndexOf(n); if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; } return this.intro + lineStr; }; MagicString.prototype.slice = function slice (start, end) { if ( start === void 0 ) start = 0; if ( end === void 0 ) end = this.original.length; while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } var result = ''; // find start chunk var chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } var startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } var containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } var sliceStart = startChunk === chunk ? start - chunk.start : 0; var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; }; // TODO deprecate this? not really very useful MagicString.prototype.snip = function snip (start, end) { var clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; }; MagicString.prototype._split = function _split (index) { if (this.byStart[index] || this.byEnd[index]) { return; } var chunk = this.lastSearchedChunk; var searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) { return this._splitChunk(chunk, index); } chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } }; MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) var loc = getLocator(this.original)(index); throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") ); } var newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) { this.lastChunk = newChunk; } this.lastSearchedChunk = chunk; return true; }; MagicString.prototype.toString = function toString () { var str = this.intro; var chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; }; MagicString.prototype.isEmpty = function isEmpty () { var chunk = this.firstChunk; do { if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) { return false; } } while (chunk = chunk.next); return true; }; MagicString.prototype.length = function length () { var chunk = this.firstChunk; var length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while (chunk = chunk.next); return length; }; MagicString.prototype.trimLines = function trimLines () { return this.trim('[\\r\\n]'); }; MagicString.prototype.trim = function trim (charType) { return this.trimStart(charType).trimEnd(charType); }; MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { var rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } var chunk = this.lastChunk; do { var end = chunk.end; var aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) { return true; } chunk = chunk.previous; } while (chunk); return false; }; MagicString.prototype.trimEnd = function trimEnd (charType) { this.trimEndAborted(charType); return this; }; MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { var rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } var chunk = this.firstChunk; do { var end = chunk.end; var aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) { return true; } chunk = chunk.next; } while (chunk); return false; }; MagicString.prototype.trimStart = function trimStart (charType) { this.trimStartAborted(charType); return this; }; /** * @param typeMap [Object] Map of MIME type -> Array[extensions] * @param ... */ function Mime$1() { this._types = Object.create(null); this._extensions = Object.create(null); for (let i = 0; i < arguments.length; i++) { this.define(arguments[i]); } this.define = this.define.bind(this); this.getType = this.getType.bind(this); this.getExtension = this.getExtension.bind(this); } /** * Define mimetype -> extension mappings. Each key is a mime-type that maps * to an array of extensions associated with the type. The first extension is * used as the default extension for the type. * * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); * * If a type declares an extension that has already been defined, an error will * be thrown. To suppress this error and force the extension to be associated * with the new type, pass `force`=true. Alternatively, you may prefix the * extension with "*" to map the type to extension, without mapping the * extension to the type. * * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); * * * @param map (Object) type definitions * @param force (Boolean) if true, force overriding of existing definitions */ Mime$1.prototype.define = function(typeMap, force) { for (let type in typeMap) { let extensions = typeMap[type].map(function(t) { return t.toLowerCase(); }); type = type.toLowerCase(); for (let i = 0; i < extensions.length; i++) { const ext = extensions[i]; // '*' prefix = not the preferred type for this extension. So fixup the // extension, and skip it. if (ext[0] === '*') { continue; } if (!force && (ext in this._types)) { throw new Error( 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".' ); } this._types[ext] = type; } // Use first extension as default if (force || !this._extensions[type]) { const ext = extensions[0]; this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); } } }; /** * Lookup a mime type based on extension */ Mime$1.prototype.getType = function(path) { path = String(path); let last = path.replace(/^.*[/\\]/, '').toLowerCase(); let ext = last.replace(/^.*\./, '').toLowerCase(); let hasPath = last.length < path.length; let hasDot = ext.length < last.length - 1; return (hasDot || !hasPath) && this._types[ext] || null; }; /** * Return file extension associated with a mime type */ Mime$1.prototype.getExtension = function(type) { type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; return type && this._extensions[type.toLowerCase()] || null; }; var Mime_1 = Mime$1; var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; let Mime = Mime_1; var lite = new Mime(standard); const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g; // urls in JS must be quoted as strings, so when replacing them we need // a different regex const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g; const rawRE = /(\?|&)raw(?:&|$)/; const urlRE = /(\?|&)url(?:&|$)/; const chunkToEmittedAssetsMap = new WeakMap(); const assetCache = new WeakMap(); const assetHashToFilenameMap = new WeakMap(); // save hashes of the files that has been emitted in build watch const emittedHashMap = new WeakMap(); /** * Also supports loading plain strings with import text from './foo.txt?raw' */ function assetPlugin(config) { // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined assetHashToFilenameMap.set(config, new Map()); return { name: 'vite:asset', buildStart() { assetCache.set(config, new Map()); emittedHashMap.set(config, new Set()); }, resolveId(id) { if (!config.assetsInclude(cleanUrl(id))) { return; } // imports to absolute urls pointing to files in /public // will fail to resolve in the main resolver. handle them here. const publicFile = checkPublicFile(id, config); if (publicFile) { return id; } }, async load(id) { if (id.startsWith('\0')) { // Rollup convention, this id should be handled by the // plugin that marked it with \0 return; } // raw requests, read from disk if (rawRE.test(id)) { const file = checkPublicFile(id, config) || cleanUrl(id); // raw query, read file and return as string return `export default ${JSON.stringify(await fs$r.promises.readFile(file, 'utf-8'))}`; } if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { return; } id = id.replace(urlRE, '$1').replace(/[\?&]$/, ''); const url = await fileToUrl(id, config, this); return `export default ${JSON.stringify(url)}`; }, renderChunk(code, chunk) { let match; let s; while ((match = assetUrlQuotedRE.exec(code))) { s = s || (s = new MagicString(code)); const [full, hash, postfix = ''] = match; // some internal plugins may still need to emit chunks (e.g. worker) so // fallback to this.getFileName for that. const file = getAssetFilename(hash, config) || this.getFileName(hash); registerAssetToChunk(chunk, file); const outputFilepath = config.base + file + postfix; s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath)); } if (s) { return { code: s.toString(), map: config.build.sourcemap ? s.generateMap({ hires: true }) : null }; } else { return null; } }, generateBundle(_, bundle) { // do not emit assets for SSR build if (config.command === 'build' && config.build.ssr) { for (const file in bundle) { if (bundle[file].type === 'asset' && !file.includes('ssr-manifest.json')) { delete bundle[file]; } } } } }; } function registerAssetToChunk(chunk, file) { let emitted = chunkToEmittedAssetsMap.get(chunk); if (!emitted) { emitted = new Set(); chunkToEmittedAssetsMap.set(chunk, emitted); } emitted.add(cleanUrl(file)); } function checkPublicFile(url, { publicDir }) { // note if the file is in /public, the resolver would have returned it // as-is so it's not going to be a fully resolved path. if (!publicDir || !url.startsWith('/')) { return; } const publicFile = path__default.join(publicDir, cleanUrl(url)); if (fs__default.existsSync(publicFile)) { return publicFile; } else { return; } } function fileToUrl(id, config, ctx) { if (config.command === 'serve') { return fileToDevUrl(id, config); } else { return fileToBuiltUrl(id, config, ctx); } } function fileToDevUrl(id, config) { var _a, _b; let rtn; if (checkPublicFile(id, config)) { // in public dir, keep the url as-is rtn = id; } else if (id.startsWith(config.root)) { // in project root, infer short public path rtn = '/' + path__default.posix.relative(config.root, id); } else { // outside of project root, use absolute fs path // (this is special handled by the serve static middleware rtn = path__default.posix.join(FS_PREFIX + id); } const origin = (_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : ''; return origin + config.base + rtn.replace(/^\//, ''); } function getAssetFilename(hash, config) { var _a; return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash); } /** * converts the source filepath of the asset to the output filename based on the assetFileNames option. \ * this function imitates the behavior of rollup.js. \ * https://rollupjs.org/guide/en/#outputassetfilenames * * @example * ```ts * const content = Buffer.from('text'); * const fileName = assetFileNamesToFileName( * 'assets/[name].[hash][extname]', * '/path/to/file.txt', * getAssetHash(content), * content * ) * // fileName: 'assets/file.982d9e3e.txt' * ``` * * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'` * @param file filepath of the asset * @param contentHash hash of the asset. used for `'[hash]'` placeholder * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function * @returns output filename */ function assetFileNamesToFileName(assetFileNames, file, contentHash, content) { const basename = path__default.basename(file); // placeholders for `assetFileNames` // `hash` is slightly different from the rollup's one const extname = path__default.extname(basename); const ext = extname.substr(1); const name = basename.slice(0, -extname.length); const hash = contentHash; if (typeof assetFileNames === 'function') { assetFileNames = assetFileNames({ name: file, source: content, type: 'asset' }); if (typeof assetFileNames !== 'string') { throw new TypeError('assetFileNames must return a string'); } } else if (typeof assetFileNames !== 'string') { throw new TypeError('assetFileNames must be a string or a function'); } const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => { switch (placeholder) { case '[ext]': return ext; case '[extname]': return extname; case '[hash]': return hash; case '[name]': return name; } throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`); }); return fileName; } /** * Register an asset to be emitted as part of the bundle (if necessary) * and returns the resolved public URL */ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { var _a, _b, _c; if (!skipPublicCheck && checkPublicFile(id, config)) { return config.base + id.slice(1); } const cache = assetCache.get(config); const cached = cache.get(id); if (cached) { return cached; } const file = cleanUrl(id); const content = await fs$r.promises.readFile(file); let url; if (config.build.lib || (!file.endsWith('.svg') && content.length < Number(config.build.assetsInlineLimit))) { // base64 inlined as a string url = `data:${lite.getType(file)};base64,${content.toString('base64')}`; } else { // emit as asset // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code // that uses runtime url sniffing and it can be verbose when targeting // non-module format. It also fails to cascade the asset content change // into the chunk's hash, so we have to do our own content hashing here. // https://bundlers.tooling.report/hashing/asset-cascade/ // https://github.com/rollup/rollup/issues/3415 const map = assetHashToFilenameMap.get(config); const contentHash = getAssetHash(content); const { search, hash } = require$$0$8.parse(id); const postfix = (search || '') + (hash || ''); const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output; const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c : // defaults to '/[name].[hash][extname]' // slightly different from rollup's one ('assets/[name]-[hash][extname]') path__default.posix.join(config.build.assetsDir, '[name].[hash][extname]'); const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content); if (!map.has(contentHash)) { map.set(contentHash, fileName); } const emittedSet = emittedHashMap.get(config); if (!emittedSet.has(contentHash)) { const name = normalizePath$4(path__default.relative(config.root, file)); pluginContext.emitFile({ name, fileName, type: 'asset', source: content }); emittedSet.add(contentHash); } url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; } cache.set(id, url); return url; } function getAssetHash(content) { return require$$1.createHash('sha256').update(content).digest('hex').slice(0, 8); } async function urlToBuiltUrl(url, importer, config, pluginContext) { if (checkPublicFile(url, config)) { return config.base + url.slice(1); } const file = url.startsWith('/') ? path__default.join(config.root, url) : path__default.join(path__default.dirname(importer), url); return fileToBuiltUrl(file, config, pluginContext, // skip public check since we just did it above true); } var tasks = {}; var utils$k = {}; var array$1 = {}; Object.defineProperty(array$1, "__esModule", { value: true }); array$1.splitWhen = array$1.flatten = void 0; function flatten$1(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } array$1.flatten = flatten$1; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } array$1.splitWhen = splitWhen; var errno$1 = {}; Object.defineProperty(errno$1, "__esModule", { value: true }); errno$1.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } errno$1.isEnoentCodeError = isEnoentCodeError; var fs$q = {}; Object.defineProperty(fs$q, "__esModule", { value: true }); fs$q.createDirentFromStats = void 0; class DirentFromStats$1 { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats$1(name, stats) { return new DirentFromStats$1(name, stats); } fs$q.createDirentFromStats = createDirentFromStats$1; var path$s = {}; Object.defineProperty(path$s, "__esModule", { value: true }); path$s.removeLeadingDotSegment = path$s.escape = path$s.makeAbsolute = path$s.unixify = void 0; const path$r = path__default; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } path$s.unixify = unixify; function makeAbsolute(cwd, filepath) { return path$r.resolve(cwd, filepath); } path$s.makeAbsolute = makeAbsolute; function escape$1(pattern) { return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$s.escape = escape$1; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } path$s.removeLeadingDotSegment = removeLeadingDotSegment; var pattern$1 = {}; /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob$1 = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = isExtglob$1; var chars = { '{': '}', '(': ')', '[': ']'}; var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; var isGlob$2 = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var regex = strictRegex; var match; // optionally relax regex if (options && options.strict === false) { regex = relaxedRegex; } while ((match = regex.exec(str))) { if (match[2]) return true; var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, // set the index to the next closing character var open = match[1]; var close = open ? chars[open] : null; if (open && close) { var n = str.indexOf(close, idx); if (n !== -1) { idx = n + 1; } } str = str.slice(idx); } return false; }; var isGlob$1 = isGlob$2; var pathPosixDirname = path__default.posix.dirname; var isWin32 = require$$0__default$1.platform() === 'win32'; var slash$2 = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby$2 = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ var globParent$2 = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash$2) < 0) { str = str.replace(backslash, slash$2); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash$2; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob$1(str) || globby$2.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; var utils$j = {}; (function (exports) { exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { let ele = arr[i]; Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); } return result; }; flat(args); return result; }; }(utils$j)); const utils$i = utils$j; var stringify$7 = (ast, options = {}) => { let stringify = (node, parent = {}) => { let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (let child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ var isNumber$2 = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber$1 = isNumber$2; const toRegexRange$1 = (min, max, options) => { if (isNumber$1(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber$1(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { return toRegexRange$1.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange$1.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange$1.cache = {}; toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange$1; /*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ const util$8 = require$$0__default$2; const toRegexRange = toRegexRange_1; const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify$6 = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util$8.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify$6(start, end, options) === false; let format = options.transform || transform(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill$2 = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill$2(start, end, 1, { transform: step }); } if (isObject$1(step)) { return fill$2(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject$1(step)) return invalidStep(step, opts); return fill$2(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; var fillRange = fill$2; const fill$1 = fillRange; const utils$h = utils$j; const compile$1 = (ast, options = {}) => { let walk = (node, parent = {}) => { let invalidBlock = utils$h.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let invalid = invalidBlock === true || invalidNode === true; let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { return prefix + node.value; } if (node.type === 'open') { return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils$h.reduce(node.nodes); let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (let child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; var compile_1 = compile$1; const fill = fillRange; const stringify$5 = stringify$7; const utils$g = utils$j; const append$1 = (queue = '', stash = '', enclose = false) => { let result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash; } for (let item of queue) { if (Array.isArray(item)) { for (let value of item) { result.push(append$1(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); } } } return utils$g.flatten(result); }; const expand$3 = (ast, options = {}) => { let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; let walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append$1(q.pop(), stringify$5(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append$1(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { let args = utils$g.reduce(node.nodes); if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify$5(node, options); } q.push(append$1(q.pop(), range)); node.nodes = []; return; } let enclose = utils$g.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append$1(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append$1(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils$g.flatten(walk(ast)); }; var expand_1 = expand$3; var constants$6 = { MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; const stringify$4 = stringify$7; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants$6; /** * parse */ const parse$l = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } let opts = options || {}; let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } let ast = { type: 'root', input, nodes: [] }; let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; let length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES$1) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES$1) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { let open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE$1) { depth++; let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; let brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE$1) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } let type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA$1 && depth > 0) { if (block.ranges > 0) { block.ranges = 0; let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify$4(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) let parent = stack[stack.length - 1]; let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; var parse_1$2 = parse$l; const stringify$3 = stringify$7; const compile = compile_1; const expand$2 = expand_1; const parse$k = parse_1$2; /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces$2 = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (let pattern of input) { let result = braces$2.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces$2.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces$2.parse = (input, options = {}) => parse$k(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify$3(braces$2.parse(input, options), options); } return stringify$3(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces$2.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces$2.parse(input, options); } let result = expand$2(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces$2.compile(input, options) : braces$2.expand(input, options); }; /** * Expose "braces" */ var braces_1 = braces$2; var utils$f = {}; const path$q = path__default; const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR$1 = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR: STAR$1, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$1 = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; var constants$5 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path$q.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; (function (exports) { const path = path__default; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$5; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; }(utils$f)); const utils$e = utils$f; const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = constants$5; const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$1 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$e.removeBackslashes(glob); if (base && backslashes === true) { base = utils$e.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1 = scan$1; const constants$4 = constants$5; const utils$d = utils$f; /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$4; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; return value; }; /** * Create the message for a syntax error */ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$j = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils$d.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$4.globChars(win32); const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$d.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { output = token.close = `)${rest})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$d.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils$d.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) { continue; } const escaped = utils$d.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils$d.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); state.output = utils$d.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils$d.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils$d.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$j.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils$d.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$4.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils$d.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$1 = parse$j; const path$p = path__default; const scan = scan_1; const parse$i = parse_1$1; const utils$c = utils$f; const constants$3 = constants$5; const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch$4 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$4(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils$c.isWindows(options); const regex = isState ? picomatch$4.compileRe(glob, options) : picomatch$4.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch$4.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils$c.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch$4.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch$4.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options); return regex.test(path$p.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch$4.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options)); return parse$i(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch$4.scan = (input, options) => scan(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch$4.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch$4.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch$4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse$i.fastpaths(input, options); } if (!parsed.output) { parsed = parse$i(input, options); } return picomatch$4.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch$4.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch$4.constants = constants$3; /** * Expose "picomatch" */ var picomatch_1 = picomatch$4; var picomatch$3 = picomatch_1; const util$7 = require$$0__default$2; const braces$1 = braces_1; const picomatch$2 = picomatch$3; const utils$b = utils$f; const isEmptyString = val => val === '' || val === './'; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array} `list` List of strings to match. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch$1 = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch$1.match = micromatch$1; /** * Returns a matcher function from the given glob `pattern` and `options`. * The returned function takes a string to match as its only argument and returns * true if the string is a match. * * ```js * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `[options]` See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); /** * Backwards compatibility */ micromatch$1.any = micromatch$1.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. * @param {String|Array} `patterns` One or more glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array} Returns an array of strings that **do not match** the given patterns. * @api public */ micromatch$1.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = micromatch$1(list, patterns, { ...options, onResult }); for (let item of items) { if (!matches.includes(item)) { result.add(item); } } return [...result]; }; /** * Returns true if the given `string` contains the given pattern. Similar * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js * var mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. * @param {String|Array} `patterns` Glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any of the patterns matches any part of `str`. * @api public */ micromatch$1.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$7.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch$1.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); }; /** * Filter the keys of the given object with the given `glob` pattern * and `options`. Does not attempt to match nested keys. If you need this feature, * use [glob-object][] instead. * * ```js * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ micromatch$1.matchKeys = (obj, patterns, options) => { if (!utils$b.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch$1(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` * @api public */ micromatch$1.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch$2(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` * @api public */ micromatch$1.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch$2(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$7.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch$2(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch$1.capture = (glob, input, options) => { let posix = utils$b.isWindows(options); let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch$1.scan = (...args) => picomatch$2.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch$1.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces$1(String(pattern), options)) { res.push(picomatch$2.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. * @return {Array} * @api public */ micromatch$1.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { return [pattern]; } return braces$1(pattern, options); }; /** * Expand braces */ micromatch$1.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch$1.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ var micromatch_1 = micromatch$1; Object.defineProperty(pattern$1, "__esModule", { value: true }); pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; const path$o = path__default; const globParent$1 = globParent$2; const micromatch = micromatch_1; const GLOBSTAR$2 = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } pattern$1.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { return true; } return false; } pattern$1.isDynamicPattern = isDynamicPattern; function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } pattern$1.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } pattern$1.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } pattern$1.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } pattern$1.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } pattern$1.getNegativePatterns = getNegativePatterns; function getPositivePatterns$1(patterns) { return patterns.filter(isPositivePattern); } pattern$1.getPositivePatterns = getPositivePatterns$1; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent$1(pattern, { flipBackslashes: false }); } pattern$1.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR$2); } pattern$1.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR$2); } pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path$o.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { return micromatch.braces(pattern, { expand: true, nodupes: true }); } pattern$1.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } pattern$1.getPatternParts = getPatternParts; function makeRe$1(pattern, options) { return micromatch.makeRe(pattern, options); } pattern$1.makeRe = makeRe$1; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe$1(pattern, options)); } pattern$1.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } pattern$1.matchAny = matchAny; var stream$7 = {}; /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0__default$4; const PassThrough$1 = Stream.PassThrough; const slice$1 = Array.prototype.slice; var merge2_1 = merge2$2; function merge2$2 () { const streamsQueue = []; const args = slice$1.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough$1(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough$1(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } Object.defineProperty(stream$7, "__esModule", { value: true }); stream$7.merge = void 0; const merge2$1 = merge2_1; function merge$1(streams) { const mergedStream = merge2$1(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } stream$7.merge = merge$1; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } var string$2 = {}; Object.defineProperty(string$2, "__esModule", { value: true }); string$2.isEmpty = string$2.isString = void 0; function isString$1(input) { return typeof input === 'string'; } string$2.isString = isString$1; function isEmpty(input) { return input === ''; } string$2.isEmpty = isEmpty; Object.defineProperty(utils$k, "__esModule", { value: true }); utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0; const array = array$1; utils$k.array = array; const errno = errno$1; utils$k.errno = errno; const fs$p = fs$q; utils$k.fs = fs$p; const path$n = path$s; utils$k.path = path$n; const pattern = pattern$1; utils$k.pattern = pattern; const stream$6 = stream$7; utils$k.stream = stream$6; const string$1 = string$2; utils$k.string = string$1; Object.defineProperty(tasks, "__esModule", { value: true }); tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; const utils$a = utils$k; function generate(patterns, settings) { const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } tasks.generate = generate; /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } tasks.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils$a.pattern.getPositivePatterns(patterns); } tasks.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils$a.pattern.convertToPositivePattern); return positive; } tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils$a.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) }; } tasks.convertPatternGroupToTask = convertPatternGroupToTask; var async$6 = {}; var stream$5 = {}; var out$3 = {}; var async$5 = {}; Object.defineProperty(async$5, "__esModule", { value: true }); async$5.read = void 0; function read$3(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback$2(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback$2(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback$2(callback, statError); return; } callSuccessCallback$2(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback$2(callback, stat); }); }); } async$5.read = read$3; function callFailureCallback$2(callback, error) { callback(error); } function callSuccessCallback$2(callback, result) { callback(null, result); } var sync$b = {}; Object.defineProperty(sync$b, "__esModule", { value: true }); sync$b.read = void 0; function read$2(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } sync$b.read = read$2; var settings$3 = {}; var fs$o = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = fs__default; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; }(fs$o)); Object.defineProperty(settings$3, "__esModule", { value: true }); const fs$n = fs$o; class Settings$2 { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs$n.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$3.default = Settings$2; Object.defineProperty(out$3, "__esModule", { value: true }); out$3.statSync = out$3.stat = out$3.Settings = void 0; const async$4 = async$5; const sync$a = sync$b; const settings_1$3 = settings$3; out$3.Settings = settings_1$3.default; function stat$4(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback); return; } async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); } out$3.stat = stat$4; function statSync(path, optionsOrSettings) { const settings = getSettings$2(optionsOrSettings); return sync$a.read(path, settings); } out$3.statSync = statSync; function getSettings$2(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$3.default) { return settingsOrOptions; } return new settings_1$3.default(settingsOrOptions); } var out$2 = {}; var async$3 = {}; var async$2 = {}; var out$1 = {}; var async$1 = {}; /*! queue-microtask. MIT License. Feross Aboukhadijeh */ let promise$1; var queueMicrotask_1 = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) // reuse resolved promise, and allocate it lazily : cb => (promise$1 || (promise$1 = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)); /*! run-parallel. MIT License. Feross Aboukhadijeh */ var runParallel_1 = runParallel; const queueMicrotask$1 = queueMicrotask_1; function runParallel (tasks, cb) { let results, pending, keys; let isSync = true; if (Array.isArray(tasks)) { results = []; pending = tasks.length; } else { keys = Object.keys(tasks); results = {}; pending = keys.length; } function done (err) { function end () { if (cb) cb(err, results); cb = null; } if (isSync) queueMicrotask$1(end); else end(); } function each (i, err, result) { results[i] = result; if (--pending === 0 || err) { done(err); } } if (!pending) { // empty done(null); } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result); }); }); } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result); }); }); } isSync = false; } var constants$2 = {}; Object.defineProperty(constants$2, "__esModule", { value: true }); constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; var utils$9 = {}; var fs$m = {}; Object.defineProperty(fs$m, "__esModule", { value: true }); fs$m.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } fs$m.createDirentFromStats = createDirentFromStats; Object.defineProperty(utils$9, "__esModule", { value: true }); utils$9.fs = void 0; const fs$l = fs$m; utils$9.fs = fs$l; var common$d = {}; Object.defineProperty(common$d, "__esModule", { value: true }); common$d.joinPathSegments = void 0; function joinPathSegments$1(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$d.joinPathSegments = joinPathSegments$1; Object.defineProperty(async$1, "__esModule", { value: true }); async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0; const fsStat$5 = out$3; const rpl = runParallel_1; const constants_1$1 = constants$2; const utils$8 = utils$9; const common$c = common$d; function read$1(directory, settings, callback) { if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes$1(directory, settings, callback); return; } readdir$3(directory, settings, callback); } async$1.read = read$1; function readdirWithFileTypes$1(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common$c.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback$1(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, rplEntries); }); }); } async$1.readdirWithFileTypes = readdirWithFileTypes$1; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir$3(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const tasks = names.map((name) => { const path = common$c.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils$8.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, entries); }); }); } async$1.readdir = readdir$3; function callFailureCallback$1(callback, error) { callback(error); } function callSuccessCallback$1(callback, result) { callback(null, result); } var sync$9 = {}; Object.defineProperty(sync$9, "__esModule", { value: true }); sync$9.readdir = sync$9.readdirWithFileTypes = sync$9.read = void 0; const fsStat$4 = out$3; const constants_1 = constants$2; const utils$7 = utils$9; const common$b = common$d; function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir$2(directory, settings); } sync$9.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common$b.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } sync$9.readdirWithFileTypes = readdirWithFileTypes; function readdir$2(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common$b.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils$7.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } sync$9.readdir = readdir$2; var settings$2 = {}; var fs$k = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = fs__default; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; }(fs$k)); Object.defineProperty(settings$2, "__esModule", { value: true }); const path$m = path__default; const fsStat$3 = out$3; const fs$j = fs$k; class Settings$1 { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs$j.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$m.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat$3.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$2.default = Settings$1; Object.defineProperty(out$1, "__esModule", { value: true }); out$1.Settings = out$1.scandirSync = out$1.scandir = void 0; const async = async$1; const sync$8 = sync$9; const settings_1$2 = settings$2; out$1.Settings = settings_1$2.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings$1(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); } out$1.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings$1(optionsOrSettings); return sync$8.read(path, settings); } out$1.scandirSync = scandirSync; function getSettings$1(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$2.default) { return settingsOrOptions; } return new settings_1$2.default(settingsOrOptions); } var queue = {exports: {}}; function reusify$1 (Constructor) { var head = new Constructor(); var tail = head; function get () { var current = head; if (current.next) { head = current.next; } else { head = new Constructor(); tail = head; } current.next = null; return current } function release (obj) { tail.next = obj; tail = obj; } return { get: get, release: release } } var reusify_1 = reusify$1; /* eslint-disable no-var */ var reusify = reusify_1; function fastqueue (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } if (concurrency < 1) { throw new Error('fastqueue concurrency must be greater than 1') } var cache = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self = { push: push, drain: noop$3, saturated: noop$3, pause: pause, paused: false, concurrency: concurrency, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop$3, kill: kill, killAndDrain: killAndDrain, error: error }; return self function running () { return _running } function pause () { self.paused = true; } function length () { var current = queueHead; var counter = 0; while (current) { current = current.next; counter++; } return counter } function getQueue () { var current = queueHead; var tasks = []; while (current) { tasks.push(current.value); current = current.next; } return tasks } function resume () { if (!self.paused) return self.paused = false; for (var i = 0; i < self.concurrency; i++) { _running++; release(); } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$3; current.errorHandler = errorHandler; if (_running === self.concurrency || self.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$3; if (_running === self.concurrency || self.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release (holder) { if (holder) { cache.release(holder); } var next = queueHead; if (next) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self.empty(); } } else { _running--; } } else if (--_running === 0) { self.drain(); } } function kill () { queueHead = null; queueTail = null; self.drain = noop$3; } function killAndDrain () { queueHead = null; queueTail = null; self.drain(); self.drain = noop$3; } function error (handler) { errorHandler = handler; } } function noop$3 () {} function Task () { this.value = null; this.callback = noop$3; this.next = null; this.release = noop$3; this.context = null; this.errorHandler = null; var self = this; this.worked = function worked (err, result) { var callback = self.callback; var errorHandler = self.errorHandler; var val = self.value; self.value = null; self.callback = noop$3; if (self.errorHandler) { errorHandler(err, val); } callback.call(self.context, err, result); self.release(self); }; } function queueAsPromised (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res); }, cb); } var queue = fastqueue(context, asyncWrapper, concurrency); var pushCb = queue.push; var unshiftCb = queue.unshift; queue.push = push; queue.unshift = unshift; queue.drained = drained; return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$3); return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$3); return p } function drained () { var previousDrain = queue.drain; var p = new Promise(function (resolve) { queue.drain = function () { previousDrain(); resolve(); }; }); return p } } queue.exports = fastqueue; queue.exports.promise = queueAsPromised; var common$a = {}; Object.defineProperty(common$a, "__esModule", { value: true }); common$a.joinPathSegments = common$a.replacePathSegmentSeparator = common$a.isAppliedFilter = common$a.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } common$a.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } common$a.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } common$a.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$a.joinPathSegments = joinPathSegments; var reader$1 = {}; Object.defineProperty(reader$1, "__esModule", { value: true }); const common$9 = common$a; class Reader$1 { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common$9.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } } reader$1.default = Reader$1; Object.defineProperty(async$2, "__esModule", { value: true }); const events_1 = require$$0__default$5; const fsScandir$2 = out$1; const fastq = queue.exports; const common$8 = common$a; const reader_1$3 = reader$1; class AsyncReader extends reader_1$3.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir$2.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common$8.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common$8.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$8.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common$8.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } async$2.default = AsyncReader; Object.defineProperty(async$3, "__esModule", { value: true }); const async_1$3 = async$2; class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$3.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } async$3.default = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } var stream$4 = {}; Object.defineProperty(stream$4, "__esModule", { value: true }); const stream_1$5 = require$$0__default$4; const async_1$2 = async$2; class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$2.default(this._root, this._settings); this._stream = new stream_1$5.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } stream$4.default = StreamProvider; var sync$7 = {}; var sync$6 = {}; Object.defineProperty(sync$6, "__esModule", { value: true }); const fsScandir$1 = out$1; const common$7 = common$a; const reader_1$2 = reader$1; class SyncReader extends reader_1$2.default { constructor() { super(...arguments); this._scandir = fsScandir$1.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common$7.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common$7.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$7.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common$7.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } sync$6.default = SyncReader; Object.defineProperty(sync$7, "__esModule", { value: true }); const sync_1$3 = sync$6; class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1$3.default(this._root, this._settings); } read() { return this._reader.read(); } } sync$7.default = SyncProvider; var settings$1 = {}; Object.defineProperty(settings$1, "__esModule", { value: true }); const path$l = path__default; const fsScandir = out$1; class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$l.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$1.default = Settings; Object.defineProperty(out$2, "__esModule", { value: true }); out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0; const async_1$1 = async$3; const stream_1$4 = stream$4; const sync_1$2 = sync$7; const settings_1$1 = settings$1; out$2.Settings = settings_1$1.default; function walk$3(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } out$2.walk = walk$3; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1$2.default(directory, settings); return provider.read(); } out$2.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1$4.default(directory, settings); return provider.read(); } out$2.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$1.default) { return settingsOrOptions; } return new settings_1$1.default(settingsOrOptions); } var reader = {}; Object.defineProperty(reader, "__esModule", { value: true }); const path$k = path__default; const fsStat$2 = out$3; const utils$6 = utils$k; class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat$2.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path$k.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils$6.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } reader.default = Reader; Object.defineProperty(stream$5, "__esModule", { value: true }); const stream_1$3 = require$$0__default$4; const fsStat$1 = out$3; const fsWalk$1 = out$2; const reader_1$1 = reader; class ReaderStream extends reader_1$1.default { constructor() { super(...arguments); this._walkStream = fsWalk$1.walkStream; this._stat = fsStat$1.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1$3.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } stream$5.default = ReaderStream; var provider = {}; var deep = {}; var partial = {}; var matcher = {}; Object.defineProperty(matcher, "__esModule", { value: true }); const utils$5 = utils$k; class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { /** * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). * So, before expand patterns with brace expansion into separated patterns. */ const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns); for (const pattern of patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); } } matcher.default = Matcher; Object.defineProperty(partial, "__esModule", { value: true }); const matcher_1 = matcher; class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } partial.default = PartialMatcher; Object.defineProperty(deep, "__esModule", { value: true }); const utils$4 = utils$k; const partial_1 = partial; class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils$4.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils$4.pattern.matchAny(entryPath, patternsRe); } } deep.default = DeepFilter; var entry$1 = {}; Object.defineProperty(entry$1, "__esModule", { value: true }); const utils$3 = utils$k; class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { if (this._settings.unique && this._isDuplicateEntry(entry)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { return false; } const filepath = this._settings.baseNameMatch ? entry.name : entry.path; const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); if (this._settings.unique && isMatched) { this._createIndexRecord(entry); } return isMatched; } _isDuplicateEntry(entry) { return this.index.has(entry.path); } _createIndexRecord(entry) { this.index.set(entry.path, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); return utils$3.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(entryPath, patternsRe) { const filepath = utils$3.path.removeLeadingDotSegment(entryPath); return utils$3.pattern.matchAny(filepath, patternsRe); } } entry$1.default = EntryFilter; var error$4 = {}; Object.defineProperty(error$4, "__esModule", { value: true }); const utils$2 = utils$k; class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } error$4.default = ErrorFilter; var entry = {}; Object.defineProperty(entry, "__esModule", { value: true }); const utils$1 = utils$k; class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils$1.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } entry.default = EntryTransformer; Object.defineProperty(provider, "__esModule", { value: true }); const path$j = path__default; const deep_1 = deep; const entry_1 = entry$1; const error_1 = error$4; const entry_2 = entry; class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path$j.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } provider.default = Provider; Object.defineProperty(async$6, "__esModule", { value: true }); const stream_1$2 = stream$5; const provider_1$2 = provider; class ProviderAsync extends provider_1$2.default { constructor() { super(...arguments); this._reader = new stream_1$2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = []; return new Promise((resolve, reject) => { const stream = this.api(root, task, options); stream.once('error', reject); stream.on('data', (entry) => entries.push(options.transform(entry))); stream.once('end', () => resolve(entries)); }); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } async$6.default = ProviderAsync; var stream$3 = {}; Object.defineProperty(stream$3, "__esModule", { value: true }); const stream_1$1 = require$$0__default$4; const stream_2 = stream$5; const provider_1$1 = provider; class ProviderStream extends provider_1$1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } stream$3.default = ProviderStream; var sync$5 = {}; var sync$4 = {}; Object.defineProperty(sync$4, "__esModule", { value: true }); const fsStat = out$3; const fsWalk = out$2; const reader_1 = reader; class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } sync$4.default = ReaderSync; Object.defineProperty(sync$5, "__esModule", { value: true }); const sync_1$1 = sync$4; const provider_1 = provider; class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1$1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } sync$5.default = ProviderSync; var settings = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = fs__default; const os = require$$0__default$1; /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports.default = Settings; }(settings)); const taskManager = tasks; const async_1 = async$6; const stream_1 = stream$3; const sync_1 = sync$5; const settings_1 = settings; const utils = utils$k; async function FastGlob(source, options) { assertPatternsInput$1(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { function sync(source, options) { assertPatternsInput$1(source); const works = getWorks(source, sync_1.default, options); return utils.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput$1(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput$1(source); const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput$1(source); const settings = new settings_1.default(options); return utils.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput$1(source); return utils.path.escape(source); } FastGlob.escapePath = escapePath; })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput$1(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } var out = FastGlob; var dist$2 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0; const path = path__default; const fs = fs__default; const os = require$$0__default$1; const fsReadFileAsync = fs.promises.readFile; function getDefaultSearchPlaces(name) { return [ 'package.json', `.${name}rc.json`, `.${name}rc.js`, `${name}.config.js`, `.${name}rc.cjs`, `${name}.config.cjs`, ]; } function getSearchPaths(startDir, stopDir) { return startDir .split(path.sep) .reduceRight((acc, _, ind, arr) => { const currentPath = arr.slice(0, ind + 1).join(path.sep); if (!acc.passedStopDir) acc.searchPlaces.push(currentPath || path.sep); if (currentPath === stopDir) acc.passedStopDir = true; return acc; }, { searchPlaces: [], passedStopDir: false }).searchPlaces; } exports.defaultLoaders = Object.freeze({ '.js': eval('require'), '.json': eval('require'), '.cjs': eval('require'), noExt(_, content) { return JSON.parse(content); }, }); function getExtDesc(ext) { return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`; } function getOptions(name, options = {}) { const conf = { stopDir: os.homedir(), searchPlaces: getDefaultSearchPlaces(name), ignoreEmptySearchPlaces: true, transform: (x) => x, packageProp: [name], ...options, loaders: { ...exports.defaultLoaders, ...options.loaders }, }; conf.searchPlaces.forEach(place => { const key = path.extname(place) || 'noExt'; const loader = conf.loaders[key]; if (!loader) { throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`); } if (typeof loader !== 'function') { throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`); } }); return conf; } function getPackageProp(props, obj) { if (typeof props === 'string' && props in obj) return obj[props]; return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null); } function getSearchItems(searchPlaces, searchPaths) { return searchPaths.reduce((acc, searchPath) => { searchPlaces.forEach(fileName => acc.push({ fileName, filepath: path.join(searchPath, fileName), loaderKey: path.extname(fileName) || 'noExt', })); return acc; }, []); } function validateFilePath(filepath) { if (!filepath) throw new Error('load must pass a non-empty string'); } function validateLoader(loader, ext) { if (!loader) throw new Error(`No loader specified for extension "${ext}"`); if (typeof loader !== 'function') throw new Error('loader is not a function'); } function lilconfig(name, options) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); return { async search(searchFrom = process.cwd()) { const searchPaths = getSearchPaths(searchFrom, stopDir); const result = { config: null, filepath: '', }; const searchItems = getSearchItems(searchPlaces, searchPaths); for (const { fileName, filepath, loaderKey } of searchItems) { try { await fs.promises.access(filepath); } catch (_a) { continue; } const content = String(await fsReadFileAsync(filepath)); const loader = loaders[loaderKey]; if (fileName === 'package.json') { const pkg = loader(filepath, content); const maybeConfig = getPackageProp(packageProp, pkg); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break; } continue; } const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = undefined; } else { validateLoader(loader, loaderKey); result.config = loader(filepath, content); } result.filepath = filepath; break; } if (result.filepath === '' && result.config === null) return transform(null); return transform(result); }, async load(filepath) { validateFilePath(filepath); const { base, ext } = path.parse(filepath); const loaderKey = ext || 'noExt'; const loader = loaders[loaderKey]; validateLoader(loader, loaderKey); const content = String(await fsReadFileAsync(filepath)); if (base === 'package.json') { const pkg = await loader(filepath, content); return transform({ config: getPackageProp(packageProp, pkg), filepath, }); } const result = { config: null, filepath, }; const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) return transform({ config: undefined, filepath, isEmpty: true, }); result.config = isEmpty ? undefined : await loader(filepath, content); return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); }, }; } exports.lilconfig = lilconfig; function lilconfigSync(name, options) { const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options); return { search(searchFrom = process.cwd()) { const searchPaths = getSearchPaths(searchFrom, stopDir); const result = { config: null, filepath: '', }; const searchItems = getSearchItems(searchPlaces, searchPaths); for (const { fileName, filepath, loaderKey } of searchItems) { try { fs.accessSync(filepath); } catch (_a) { continue; } const loader = loaders[loaderKey]; const content = String(fs.readFileSync(filepath)); if (fileName === 'package.json') { const pkg = loader(filepath, content); const maybeConfig = getPackageProp(packageProp, pkg); if (maybeConfig != null) { result.config = maybeConfig; result.filepath = filepath; break; } continue; } const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) continue; if (isEmpty) { result.isEmpty = true; result.config = undefined; } else { validateLoader(loader, loaderKey); result.config = loader(filepath, content); } result.filepath = filepath; break; } if (result.filepath === '' && result.config === null) return transform(null); return transform(result); }, load(filepath) { validateFilePath(filepath); const { base, ext } = path.parse(filepath); const loaderKey = ext || 'noExt'; const loader = loaders[loaderKey]; validateLoader(loader, loaderKey); const content = String(fs.readFileSync(filepath)); if (base === 'package.json') { const pkg = loader(filepath, content); return transform({ config: getPackageProp(packageProp, pkg), filepath, }); } const result = { config: null, filepath, }; const isEmpty = content.trim() === ''; if (isEmpty && ignoreEmptySearchPlaces) return transform({ filepath, config: undefined, isEmpty: true, }); result.config = isEmpty ? undefined : loader(filepath, content); return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result); }, }; } exports.lilconfigSync = lilconfigSync; }(dist$2)); var dist$1 = {}; var parseCst$1 = {}; var PlainValueEc8e588e = {}; const Char = { ANCHOR: '&', COMMENT: '#', TAG: '!', DIRECTIVES_END: '-', DOCUMENT_END: '.' }; const Type = { ALIAS: 'ALIAS', BLANK_LINE: 'BLANK_LINE', BLOCK_FOLDED: 'BLOCK_FOLDED', BLOCK_LITERAL: 'BLOCK_LITERAL', COMMENT: 'COMMENT', DIRECTIVE: 'DIRECTIVE', DOCUMENT: 'DOCUMENT', FLOW_MAP: 'FLOW_MAP', FLOW_SEQ: 'FLOW_SEQ', MAP: 'MAP', MAP_KEY: 'MAP_KEY', MAP_VALUE: 'MAP_VALUE', PLAIN: 'PLAIN', QUOTE_DOUBLE: 'QUOTE_DOUBLE', QUOTE_SINGLE: 'QUOTE_SINGLE', SEQ: 'SEQ', SEQ_ITEM: 'SEQ_ITEM' }; const defaultTagPrefix = 'tag:yaml.org,2002:'; const defaultTags = { MAP: 'tag:yaml.org,2002:map', SEQ: 'tag:yaml.org,2002:seq', STR: 'tag:yaml.org,2002:str' }; function findLineStarts(src) { const ls = [0]; let offset = src.indexOf('\n'); while (offset !== -1) { offset += 1; ls.push(offset); offset = src.indexOf('\n', offset); } return ls; } function getSrcInfo(cst) { let lineStarts, src; if (typeof cst === 'string') { lineStarts = findLineStarts(cst); src = cst; } else { if (Array.isArray(cst)) cst = cst[0]; if (cst && cst.context) { if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); lineStarts = cst.lineStarts; src = cst.context.src; } } return { lineStarts, src }; } /** * @typedef {Object} LinePos - One-indexed position in the source * @property {number} line * @property {number} col */ /** * Determine the line/col position matching a character offset. * * Accepts a source string or a CST document as the second parameter. With * the latter, starting indices for lines are cached in the document as * `lineStarts: number[]`. * * Returns a one-indexed `{ line, col }` location if found, or * `undefined` otherwise. * * @param {number} offset * @param {string|Document|Document[]} cst * @returns {?LinePos} */ function getLinePos(offset, cst) { if (typeof offset !== 'number' || offset < 0) return null; const { lineStarts, src } = getSrcInfo(cst); if (!lineStarts || !src || offset > src.length) return null; for (let i = 0; i < lineStarts.length; ++i) { const start = lineStarts[i]; if (offset < start) { return { line: i, col: offset - lineStarts[i - 1] + 1 }; } if (offset === start) return { line: i + 1, col: 1 }; } const line = lineStarts.length; return { line, col: offset - lineStarts[line - 1] + 1 }; } /** * Get a specified line from the source. * * Accepts a source string or a CST document as the second parameter. With * the latter, starting indices for lines are cached in the document as * `lineStarts: number[]`. * * Returns the line as a string if found, or `null` otherwise. * * @param {number} line One-indexed line number * @param {string|Document|Document[]} cst * @returns {?string} */ function getLine(line, cst) { const { lineStarts, src } = getSrcInfo(cst); if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; const start = lineStarts[line - 1]; let end = lineStarts[line]; // undefined for last line; that's ok for slice() while (end && end > start && src[end - 1] === '\n') --end; return src.slice(start, end); } /** * Pretty-print the starting line from the source indicated by the range `pos` * * Trims output to `maxWidth` chars while keeping the starting column visible, * using `…` at either end to indicate dropped characters. * * Returns a two-line string (or `null`) with `\n` as separator; the second line * will hold appropriately indented `^` marks indicating the column range. * * @param {Object} pos * @param {LinePos} pos.start * @param {LinePos} [pos.end] * @param {string|Document|Document[]*} cst * @param {number} [maxWidth=80] * @returns {?string} */ function getPrettyContext({ start, end }, cst, maxWidth = 80) { let src = getLine(start.line, cst); if (!src) return null; let { col } = start; if (src.length > maxWidth) { if (col <= maxWidth - 10) { src = src.substr(0, maxWidth - 1) + '…'; } else { const halfWidth = Math.round(maxWidth / 2); if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; col -= src.length - maxWidth; src = '…' + src.substr(1 - maxWidth); } } let errLen = 1; let errEnd = ''; if (end) { if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { errLen = end.col - start.col; } else { errLen = Math.min(src.length + 1, maxWidth) - col; errEnd = '…'; } } const offset = col > 1 ? ' '.repeat(col - 1) : ''; const err = '^'.repeat(errLen); return `${src}\n${offset}${err}${errEnd}`; } class Range { static copy(orig) { return new Range(orig.start, orig.end); } constructor(start, end) { this.start = start; this.end = end || start; } isEmpty() { return typeof this.start !== 'number' || !this.end || this.end <= this.start; } /** * Set `origStart` and `origEnd` to point to the original source range for * this node, which may differ due to dropped CR characters. * * @param {number[]} cr - Positions of dropped CR characters * @param {number} offset - Starting index of `cr` from the last call * @returns {number} - The next offset, matching the one found for `origStart` */ setOrigRange(cr, offset) { const { start, end } = this; if (cr.length === 0 || end <= cr[0]) { this.origStart = start; this.origEnd = end; return offset; } let i = offset; while (i < cr.length) { if (cr[i] > start) break;else ++i; } this.origStart = start + i; const nextOffset = i; while (i < cr.length) { // if end was at \n, it should now be at \r if (cr[i] >= end) break;else ++i; } this.origEnd = end + i; return nextOffset; } } /** Root class of all nodes */ class Node$2 { static addStringTerminator(src, offset, str) { if (str[str.length - 1] === '\n') return str; const next = Node$2.endOfWhiteSpace(src, offset); return next >= src.length || src[next] === '\n' ? str + '\n' : str; } // ^(---|...) static atDocumentBoundary(src, offset, sep) { const ch0 = src[offset]; if (!ch0) return true; const prev = src[offset - 1]; if (prev && prev !== '\n') return false; if (sep) { if (ch0 !== sep) return false; } else { if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; } const ch1 = src[offset + 1]; const ch2 = src[offset + 2]; if (ch1 !== ch0 || ch2 !== ch0) return false; const ch3 = src[offset + 3]; return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; } static endOfIdentifier(src, offset) { let ch = src[offset]; const isVerbatim = ch === '<'; const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; if (isVerbatim && ch === '>') offset += 1; return offset; } static endOfIndent(src, offset) { let ch = src[offset]; while (ch === ' ') ch = src[offset += 1]; return offset; } static endOfLine(src, offset) { let ch = src[offset]; while (ch && ch !== '\n') ch = src[offset += 1]; return offset; } static endOfWhiteSpace(src, offset) { let ch = src[offset]; while (ch === '\t' || ch === ' ') ch = src[offset += 1]; return offset; } static startOfLine(src, offset) { let ch = src[offset - 1]; if (ch === '\n') return offset; while (ch && ch !== '\n') ch = src[offset -= 1]; return offset + 1; } /** * End of indentation, or null if the line's indent level is not more * than `indent` * * @param {string} src * @param {number} indent * @param {number} lineStart * @returns {?number} */ static endOfBlockIndent(src, indent, lineStart) { const inEnd = Node$2.endOfIndent(src, lineStart); if (inEnd > lineStart + indent) { return inEnd; } else { const wsEnd = Node$2.endOfWhiteSpace(src, inEnd); const ch = src[wsEnd]; if (!ch || ch === '\n') return wsEnd; } return null; } static atBlank(src, offset, endAsBlank) { const ch = src[offset]; return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; } static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { if (!ch || indentDiff < 0) return false; if (indentDiff > 0) return true; return indicatorAsIndent && ch === '-'; } // should be at line or string end, or at next non-whitespace char static normalizeOffset(src, offset) { const ch = src[offset]; return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset); } // fold single newline into space, multiple newlines to N - 1 newlines // presumes src[offset] === '\n' static foldNewline(src, offset, indent) { let inCount = 0; let error = false; let fold = ''; let ch = src[offset + 1]; while (ch === ' ' || ch === '\t' || ch === '\n') { switch (ch) { case '\n': inCount = 0; offset += 1; fold += '\n'; break; case '\t': if (inCount <= indent) error = true; offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1; break; case ' ': inCount += 1; offset += 1; break; } ch = src[offset + 1]; } if (!fold) fold = ' '; if (ch && inCount <= indent) error = true; return { fold, offset, error }; } constructor(type, props, context) { Object.defineProperty(this, 'context', { value: context || null, writable: true }); this.error = null; this.range = null; this.valueRange = null; this.props = props || []; this.type = type; this.value = null; } getPropValue(idx, key, skipKey) { if (!this.context) return null; const { src } = this.context; const prop = this.props[idx]; return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; } get anchor() { for (let i = 0; i < this.props.length; ++i) { const anchor = this.getPropValue(i, Char.ANCHOR, true); if (anchor != null) return anchor; } return null; } get comment() { const comments = []; for (let i = 0; i < this.props.length; ++i) { const comment = this.getPropValue(i, Char.COMMENT, true); if (comment != null) comments.push(comment); } return comments.length > 0 ? comments.join('\n') : null; } commentHasRequiredWhitespace(start) { const { src } = this.context; if (this.header && start === this.header.end) return false; if (!this.valueRange) return false; const { end } = this.valueRange; return start !== end || Node$2.atBlank(src, end - 1); } get hasComment() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] === Char.COMMENT) return true; } } return false; } get hasProps() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] !== Char.COMMENT) return true; } } return false; } get includesTrailingLines() { return false; } get jsonLike() { const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; return jsonLikeTypes.indexOf(this.type) !== -1; } get rangeAsLinePos() { if (!this.range || !this.context) return undefined; const start = getLinePos(this.range.start, this.context.root); if (!start) return undefined; const end = getLinePos(this.range.end, this.context.root); return { start, end }; } get rawValue() { if (!this.valueRange || !this.context) return null; const { start, end } = this.valueRange; return this.context.src.slice(start, end); } get tag() { for (let i = 0; i < this.props.length; ++i) { const tag = this.getPropValue(i, Char.TAG, false); if (tag != null) { if (tag[1] === '<') { return { verbatim: tag.slice(2, -1) }; } else { // eslint-disable-next-line no-unused-vars const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); return { handle, suffix }; } } } return null; } get valueRangeContainsNewline() { if (!this.valueRange || !this.context) return false; const { start, end } = this.valueRange; const { src } = this.context; for (let i = start; i < end; ++i) { if (src[i] === '\n') return true; } return false; } parseComment(start) { const { src } = this.context; if (src[start] === Char.COMMENT) { const end = Node$2.endOfLine(src, start + 1); const commentRange = new Range(start, end); this.props.push(commentRange); return end; } return start; } /** * Populates the `origStart` and `origEnd` values of all ranges for this * node. Extended by child classes to handle descendant nodes. * * @param {number[]} cr - Positions of dropped CR characters * @param {number} offset - Starting index of `cr` from the last call * @returns {number} - The next offset, matching the one found for `origStart` */ setOrigRanges(cr, offset) { if (this.range) offset = this.range.setOrigRange(cr, offset); if (this.valueRange) this.valueRange.setOrigRange(cr, offset); this.props.forEach(prop => prop.setOrigRange(cr, offset)); return offset; } toString() { const { context: { src }, range, value } = this; if (value != null) return value; const str = src.slice(range.start, range.end); return Node$2.addStringTerminator(src, range.end, str); } } class YAMLError extends Error { constructor(name, source, message) { if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`); super(); this.name = name; this.message = message; this.source = source; } makePretty() { if (!this.source) return; this.nodeType = this.source.type; const cst = this.source.context && this.source.context.root; if (typeof this.offset === 'number') { this.range = new Range(this.offset, this.offset + 1); const start = cst && getLinePos(this.offset, cst); if (start) { const end = { line: start.line, col: start.col + 1 }; this.linePos = { start, end }; } delete this.offset; } else { this.range = this.source.range; this.linePos = this.source.rangeAsLinePos; } if (this.linePos) { const { line, col } = this.linePos.start; this.message += ` at line ${line}, column ${col}`; const ctx = cst && getPrettyContext(this.linePos, cst); if (ctx) this.message += `:\n\n${ctx}\n`; } delete this.source; } } class YAMLReferenceError extends YAMLError { constructor(source, message) { super('YAMLReferenceError', source, message); } } class YAMLSemanticError extends YAMLError { constructor(source, message) { super('YAMLSemanticError', source, message); } } class YAMLSyntaxError extends YAMLError { constructor(source, message) { super('YAMLSyntaxError', source, message); } } class YAMLWarning extends YAMLError { constructor(source, message) { super('YAMLWarning', source, message); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class PlainValue$6 extends Node$2 { static endOfLine(src, start, inFlow) { let ch = src[start]; let offset = start; while (ch && ch !== '\n') { if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; const next = src[offset + 1]; if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; if ((ch === ' ' || ch === '\t') && next === '#') break; offset += 1; ch = next; } return offset; } get strValue() { if (!this.valueRange || !this.context) return null; let { start, end } = this.valueRange; const { src } = this.context; let ch = src[end - 1]; while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; let str = ''; for (let i = start; i < end; ++i) { const ch = src[i]; if (ch === '\n') { const { fold, offset } = Node$2.foldNewline(src, i, -1); str += fold; i = offset; } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (i < end && (next === ' ' || next === '\t')) { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } const ch0 = src[start]; switch (ch0) { case '\t': { const msg = 'Plain value cannot start with a tab character'; const errors = [new YAMLSemanticError(this, msg)]; return { errors, str }; } case '@': case '`': { const msg = `Plain value cannot start with reserved character ${ch0}`; const errors = [new YAMLSemanticError(this, msg)]; return { errors, str }; } default: return str; } } parseBlockValue(start) { const { indent, inFlow, src } = this.context; let offset = start; let valueEnd = start; for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { if (Node$2.atDocumentBoundary(src, offset + 1)) break; const end = Node$2.endOfBlockIndent(src, indent, offset + 1); if (end === null || src[end] === '#') break; if (src[end] === '\n') { offset = end; } else { valueEnd = PlainValue$6.endOfLine(src, end, inFlow); offset = valueEnd; } } if (this.valueRange.isEmpty()) this.valueRange.start = start; this.valueRange.end = valueEnd; return valueEnd; } /** * Parses a plain value from the source * * Accepted forms are: * ``` * #comment * * first line * * first line #comment * * first line * block * lines * * #comment * block * lines * ``` * where block lines are empty or have an indent level greater than `indent`. * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar, may be `\n` */ parse(context, start) { this.context = context; const { inFlow, src } = context; let offset = start; const ch = src[offset]; if (ch && ch !== '#' && ch !== '\n') { offset = PlainValue$6.endOfLine(src, start, inFlow); } this.valueRange = new Range(start, offset); offset = Node$2.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); if (!this.hasComment || this.valueRange.isEmpty()) { offset = this.parseBlockValue(offset); } return offset; } } PlainValueEc8e588e.Char = Char; PlainValueEc8e588e.Node = Node$2; PlainValueEc8e588e.PlainValue = PlainValue$6; PlainValueEc8e588e.Range = Range; PlainValueEc8e588e.Type = Type; PlainValueEc8e588e.YAMLError = YAMLError; PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError; PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError; PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError; PlainValueEc8e588e.YAMLWarning = YAMLWarning; PlainValueEc8e588e._defineProperty = _defineProperty; PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix; PlainValueEc8e588e.defaultTags = defaultTags; var PlainValue$5 = PlainValueEc8e588e; class BlankLine extends PlainValue$5.Node { constructor() { super(PlainValue$5.Type.BLANK_LINE); } /* istanbul ignore next */ get includesTrailingLines() { // This is never called from anywhere, but if it were, // this is the value it should return. return true; } /** * Parses a blank line from the source * * @param {ParseContext} context * @param {number} start - Index of first \n character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; this.range = new PlainValue$5.Range(start, start + 1); return start + 1; } } class CollectionItem extends PlainValue$5.Node { constructor(type, props) { super(type, props); this.node = null; } get includesTrailingLines() { return !!this.node && this.node.includesTrailingLines; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; let { atLineStart, lineStart } = context; if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); const indent = atLineStart ? start - lineStart : context.indent; let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); let ch = src[offset]; const inlineComment = ch === '#'; const comments = []; let blankLine = null; while (ch === '\n' || ch === '#') { if (ch === '#') { const end = PlainValue$5.Node.endOfLine(src, offset + 1); comments.push(new PlainValue$5.Range(offset, end)); offset = end; } else { atLineStart = true; lineStart = offset + 1; const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); if (src[wsEnd] === '\n' && comments.length === 0) { blankLine = new BlankLine(); lineStart = blankLine.parse({ src }, lineStart); } offset = PlainValue$5.Node.endOfIndent(src, lineStart); } ch = src[offset]; } if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) { this.node = parseNode({ atLineStart, inCollection: false, indent, lineStart, parent: this }, offset); } else if (ch && lineStart > start + 1) { offset = lineStart - 1; } if (this.node) { if (blankLine) { // Only blank lines preceding non-empty nodes are captured. Note that // this means that collection item range start indices do not always // increase monotonically. -- eemeli/yaml#126 const items = context.parent.items || context.parent.contents; if (items) items.push(blankLine); } if (comments.length) Array.prototype.push.apply(this.props, comments); offset = this.node.range.end; } else { if (inlineComment) { const c = comments[0]; this.props.push(c); offset = c.end; } else { offset = PlainValue$5.Node.endOfLine(src, start + 1); } } const end = this.node ? this.node.valueRange.end : offset; this.valueRange = new PlainValue$5.Range(start, end); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); return this.node ? this.node.setOrigRanges(cr, offset) : offset; } toString() { const { context: { src }, node, range, value } = this; if (value != null) return value; const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); return PlainValue$5.Node.addStringTerminator(src, range.end, str); } } class Comment extends PlainValue$5.Node { constructor() { super(PlainValue$5.Type.COMMENT); } /** * Parses a comment line from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const offset = this.parseComment(start); this.range = new PlainValue$5.Range(start, offset); return offset; } } function grabCollectionEndComments(node) { let cnode = node; while (cnode instanceof CollectionItem) cnode = cnode.node; if (!(cnode instanceof Collection$1)) return null; const len = cnode.items.length; let ci = -1; for (let i = len - 1; i >= 0; --i) { const n = cnode.items[i]; if (n.type === PlainValue$5.Type.COMMENT) { // Keep sufficiently indented comments with preceding node const { indent, lineStart } = n.context; if (indent > 0 && n.range.start >= lineStart + indent) break; ci = i; } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break; } if (ci === -1) return null; const ca = cnode.items.splice(ci, len - ci); const prevEnd = ca[0].range.start; while (true) { cnode.range.end = prevEnd; if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; if (cnode === node) break; cnode = cnode.context.parent; } return ca; } class Collection$1 extends PlainValue$5.Node { static nextContentHasIndent(src, offset, indent) { const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1; offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); const ch = src[offset]; if (!ch) return false; if (offset >= lineStart + indent) return true; if (ch !== '#' && ch !== '\n') return false; return Collection$1.nextContentHasIndent(src, offset, indent); } constructor(firstItem) { super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP); for (let i = firstItem.props.length - 1; i >= 0; --i) { if (firstItem.props[i].start < firstItem.context.lineStart) { // props on previous line are assumed by the collection this.props = firstItem.props.slice(0, i + 1); firstItem.props = firstItem.props.slice(i + 1); const itemRange = firstItem.props[0] || firstItem.valueRange; firstItem.range.start = itemRange.start; break; } } this.items = [firstItem]; const ec = grabCollectionEndComments(firstItem); if (ec) Array.prototype.push.apply(this.items, ec); } get includesTrailingLines() { return this.items.length > 0; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; // It's easier to recalculate lineStart here rather than tracking down the // last context from which to read it -- eemeli/yaml#2 let lineStart = PlainValue$5.Node.startOfLine(src, start); const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling // -- eemeli/yaml#17 firstItem.context.parent = this; this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange); const indent = firstItem.range.start - firstItem.context.lineStart; let offset = start; offset = PlainValue$5.Node.normalizeOffset(src, offset); let ch = src[offset]; let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset; let prevIncludesTrailingLines = false; while (ch) { while (ch === '\n' || ch === '#') { if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); this.valueRange.end = offset; if (offset >= src.length) { ch = null; break; } this.items.push(blankLine); offset -= 1; // blankLine.parse() consumes terminal newline } else if (ch === '#') { if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) { return offset; } const comment = new Comment(); offset = comment.parse({ indent, lineStart, src }, offset); this.items.push(comment); this.valueRange.end = offset; if (offset >= src.length) { ch = null; break; } } lineStart = offset + 1; offset = PlainValue$5.Node.endOfIndent(src, lineStart); if (PlainValue$5.Node.atBlank(src, offset)) { const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset); const next = src[wsEnd]; if (!next || next === '\n' || next === '#') { offset = wsEnd; } } ch = src[offset]; atLineStart = true; } if (!ch) { break; } if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { if (offset < lineStart + indent) { if (lineStart > start) offset = lineStart; break; } else if (!this.error) { const msg = 'All collection items must start at the same column'; this.error = new PlainValue$5.YAMLSyntaxError(this, msg); } } if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) { if (ch !== '-') { if (lineStart > start) offset = lineStart; break; } } else if (ch === '-' && !this.error) { // map key may start with -, as long as it's followed by a non-whitespace char const next = src[offset + 1]; if (!next || next === '\n' || next === '\t' || next === ' ') { const msg = 'A collection cannot be both a mapping and a sequence'; this.error = new PlainValue$5.YAMLSyntaxError(this, msg); } } const node = parseNode({ atLineStart, inCollection: true, indent, lineStart, parent: this }, offset); if (!node) return offset; // at next document start this.items.push(node); this.valueRange.end = node.valueRange.end; offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); ch = src[offset]; atLineStart = false; prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range // has advanced to check the current line's indentation level // -- eemeli/yaml#10 & eemeli/yaml#38 if (ch) { let ls = offset - 1; let prev = src[ls]; while (prev === ' ' || prev === '\t') prev = src[--ls]; if (prev === '\n') { lineStart = ls + 1; atLineStart = true; } } const ec = grabCollectionEndComments(node); if (ec) Array.prototype.push.apply(this.items, ec); } return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.items.forEach(node => { offset = node.setOrigRanges(cr, offset); }); return offset; } toString() { const { context: { src }, items, range, value } = this; if (value != null) return value; let str = src.slice(range.start, items[0].range.start) + String(items[0]); for (let i = 1; i < items.length; ++i) { const item = items[i]; const { atLineStart, indent } = item.context; if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; str += String(item); } return PlainValue$5.Node.addStringTerminator(src, range.end, str); } } class Directive extends PlainValue$5.Node { constructor() { super(PlainValue$5.Type.DIRECTIVE); this.name = null; } get parameters() { const raw = this.rawValue; return raw ? raw.trim().split(/[ \t]+/) : []; } parseName(start) { const { src } = this.context; let offset = start; let ch = src[offset]; while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; this.name = src.slice(start, offset); return offset; } parseParameters(start) { const { src } = this.context; let offset = start; let ch = src[offset]; while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; this.valueRange = new PlainValue$5.Range(start, offset); return offset; } parse(context, start) { this.context = context; let offset = this.parseName(start + 1); offset = this.parseParameters(offset); offset = this.parseComment(offset); this.range = new PlainValue$5.Range(start, offset); return offset; } } class Document$3 extends PlainValue$5.Node { static startCommentOrEndBlankLine(src, start) { const offset = PlainValue$5.Node.endOfWhiteSpace(src, start); const ch = src[offset]; return ch === '#' || ch === '\n' ? offset : start; } constructor() { super(PlainValue$5.Type.DOCUMENT); this.directives = null; this.contents = null; this.directivesEndMarker = null; this.documentEndMarker = null; } parseDirectives(start) { const { src } = this.context; this.directives = []; let atLineStart = true; let hasDirectives = false; let offset = start; while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) { offset = Document$3.startCommentOrEndBlankLine(src, offset); switch (src[offset]) { case '\n': if (atLineStart) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); if (offset < src.length) { this.directives.push(blankLine); } } else { offset += 1; atLineStart = true; } break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.directives.push(comment); atLineStart = false; } break; case '%': { const directive = new Directive(); offset = directive.parse({ parent: this, src }, offset); this.directives.push(directive); hasDirectives = true; atLineStart = false; } break; default: if (hasDirectives) { this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); } else if (this.directives.length > 0) { this.contents = this.directives; this.directives = []; } return offset; } } if (src[offset]) { this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3); return offset + 3; } if (hasDirectives) { this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line'); } else if (this.directives.length > 0) { this.contents = this.directives; this.directives = []; } return offset; } parseContents(start) { const { parseNode, src } = this.context; if (!this.contents) this.contents = []; let lineStart = start; while (src[lineStart - 1] === '-') lineStart -= 1; let offset = PlainValue$5.Node.endOfWhiteSpace(src, start); let atLineStart = lineStart === start; this.valueRange = new PlainValue$5.Range(offset); while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) { switch (src[offset]) { case '\n': if (atLineStart) { const blankLine = new BlankLine(); offset = blankLine.parse({ src }, offset); if (offset < src.length) { this.contents.push(blankLine); } } else { offset += 1; atLineStart = true; } lineStart = offset; break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.contents.push(comment); atLineStart = false; } break; default: { const iEnd = PlainValue$5.Node.endOfIndent(src, offset); const context = { atLineStart, indent: -1, inFlow: false, inCollection: false, lineStart, parent: this }; const node = parseNode(context, iEnd); if (!node) return this.valueRange.end = iEnd; // at next document start this.contents.push(node); offset = node.range.end; atLineStart = false; const ec = grabCollectionEndComments(node); if (ec) Array.prototype.push.apply(this.contents, ec); } } offset = Document$3.startCommentOrEndBlankLine(src, offset); } this.valueRange.end = offset; if (src[offset]) { this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3); offset += 3; if (src[offset]) { offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); if (src[offset] === '#') { const comment = new Comment(); offset = comment.parse({ src }, offset); this.contents.push(comment); } switch (src[offset]) { case '\n': offset += 1; break; case undefined: break; default: this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); } } } return offset; } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { context.root = this; this.context = context; const { src } = context; let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM offset = this.parseDirectives(offset); offset = this.parseContents(offset); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.directives.forEach(node => { offset = node.setOrigRanges(cr, offset); }); if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); this.contents.forEach(node => { offset = node.setOrigRanges(cr, offset); }); if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); return offset; } toString() { const { contents, directives, value } = this; if (value != null) return value; let str = directives.join(''); if (contents.length > 0) { if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n'; str += contents.join(''); } if (str[str.length - 1] !== '\n') str += '\n'; return str; } } class Alias$1 extends PlainValue$5.Node { /** * Parses an *alias from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1); this.valueRange = new PlainValue$5.Range(start + 1, offset); offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } const Chomp = { CLIP: 'CLIP', KEEP: 'KEEP', STRIP: 'STRIP' }; class BlockValue extends PlainValue$5.Node { constructor(type, props) { super(type, props); this.blockIndent = null; this.chomping = Chomp.CLIP; this.header = null; } get includesTrailingLines() { return this.chomping === Chomp.KEEP; } get strValue() { if (!this.valueRange || !this.context) return null; let { start, end } = this.valueRange; const { indent, src } = this.context; if (this.valueRange.isEmpty()) return ''; let lastNewLine = null; let ch = src[end - 1]; while (ch === '\n' || ch === '\t' || ch === ' ') { end -= 1; if (end <= start) { if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens } if (ch === '\n') lastNewLine = end; ch = src[end - 1]; } let keepStart = end + 1; if (lastNewLine) { if (this.chomping === Chomp.KEEP) { keepStart = lastNewLine; end = this.valueRange.end; } else { end = lastNewLine; } } const bi = indent + this.blockIndent; const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED; let atStart = true; let str = ''; let sep = ''; let prevMoreIndented = false; for (let i = start; i < end; ++i) { for (let j = 0; j < bi; ++j) { if (src[i] !== ' ') break; i += 1; } const ch = src[i]; if (ch === '\n') { if (sep === '\n') str += '\n';else sep = '\n'; } else { const lineEnd = PlainValue$5.Node.endOfLine(src, i); const line = src.slice(i, lineEnd); i = lineEnd; if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') sep = lineEnd < end && src[lineEnd] || ''; prevMoreIndented = true; } else { str += sep + line; sep = folded && i < keepStart ? ' ' : '\n'; prevMoreIndented = false; } if (atStart && line !== '') atStart = false; } } return this.chomping === Chomp.STRIP ? str : str + '\n'; } parseBlockHeader(start) { const { src } = this.context; let offset = start + 1; let bi = ''; while (true) { const ch = src[offset]; switch (ch) { case '-': this.chomping = Chomp.STRIP; break; case '+': this.chomping = Chomp.KEEP; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': bi += ch; break; default: this.blockIndent = Number(bi) || null; this.header = new PlainValue$5.Range(start, offset); return offset; } offset += 1; } } parseBlockValue(start) { const { indent, src } = this.context; const explicit = !!this.blockIndent; let offset = start; let valueEnd = start; let minBlockIndent = 1; for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { offset += 1; if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break; const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab? if (end === null) break; const ch = src[end]; const lineIndent = end - (offset + indent); if (!this.blockIndent) { // no explicit block indent, none yet detected if (src[end] !== '\n') { // first line with non-whitespace content if (lineIndent < minBlockIndent) { const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; this.error = new PlainValue$5.YAMLSemanticError(this, msg); } this.blockIndent = lineIndent; } else if (lineIndent > minBlockIndent) { // empty line with more whitespace minBlockIndent = lineIndent; } } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { if (src[end] === '#') break; if (!this.error) { const src = explicit ? 'explicit indentation indicator' : 'first line'; const msg = `Block scalars must not be less indented than their ${src}`; this.error = new PlainValue$5.YAMLSemanticError(this, msg); } } if (src[end] === '\n') { offset = end; } else { offset = valueEnd = PlainValue$5.Node.endOfLine(src, end); } } if (this.chomping !== Chomp.KEEP) { offset = src[valueEnd] ? valueEnd + 1 : valueEnd; } this.valueRange = new PlainValue$5.Range(start + 1, offset); return offset; } /** * Parses a block value from the source * * Accepted forms are: * ``` * BS * block * lines * * BS #comment * block * lines * ``` * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines * are empty or have an indent level greater than `indent`. * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this block */ parse(context, start) { this.context = context; const { src } = context; let offset = this.parseBlockHeader(start); offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); offset = this.parseBlockValue(offset); return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); return this.header ? this.header.setOrigRange(cr, offset) : offset; } } class FlowCollection extends PlainValue$5.Node { constructor(type, props) { super(type, props); this.items = null; } prevNodeIsJsonLike(idx = this.items.length) { const node = this.items[idx - 1]; return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); } /** * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this */ parse(context, start) { this.context = context; const { parseNode, src } = context; let { indent, lineStart } = context; let char = src[start]; // { or [ this.items = [{ char, offset: start }]; let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1); char = src[offset]; while (char && char !== ']' && char !== '}') { switch (char) { case '\n': { lineStart = offset + 1; const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart); if (src[wsEnd] === '\n') { const blankLine = new BlankLine(); lineStart = blankLine.parse({ src }, lineStart); this.items.push(blankLine); } offset = PlainValue$5.Node.endOfIndent(src, lineStart); if (offset <= lineStart + indent) { char = src[offset]; if (offset < lineStart + indent || char !== ']' && char !== '}') { const msg = 'Insufficient indentation in flow collection'; this.error = new PlainValue$5.YAMLSemanticError(this, msg); } } } break; case ',': { this.items.push({ char, offset }); offset += 1; } break; case '#': { const comment = new Comment(); offset = comment.parse({ src }, offset); this.items.push(comment); } break; case '?': case ':': { const next = src[offset + 1]; if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace char === ':' && this.prevNodeIsJsonLike()) { this.items.push({ char, offset }); offset += 1; break; } } // fallthrough default: { const node = parseNode({ atLineStart: false, inCollection: false, inFlow: true, indent: -1, lineStart, parent: this }, offset); if (!node) { // at next document start this.valueRange = new PlainValue$5.Range(start, offset); return offset; } this.items.push(node); offset = PlainValue$5.Node.normalizeOffset(src, node.range.end); } } offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); char = src[offset]; } this.valueRange = new PlainValue$5.Range(start, offset + 1); if (char) { this.items.push({ char, offset }); offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1); offset = this.parseComment(offset); } return offset; } setOrigRanges(cr, offset) { offset = super.setOrigRanges(cr, offset); this.items.forEach(node => { if (node instanceof PlainValue$5.Node) { offset = node.setOrigRanges(cr, offset); } else if (cr.length === 0) { node.origOffset = node.offset; } else { let i = offset; while (i < cr.length) { if (cr[i] > node.offset) break;else ++i; } node.origOffset = node.offset + i; offset = i; } }); return offset; } toString() { const { context: { src }, items, range, value } = this; if (value != null) return value; const nodes = items.filter(item => item instanceof PlainValue$5.Node); let str = ''; let prevEnd = range.start; nodes.forEach(node => { const prefix = src.slice(prevEnd, node.range.start); prevEnd = node.range.end; str += prefix + String(node); if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { // Comment range does not include the terminal newline, but its // stringified value does. Without this fix, newlines at comment ends // get duplicated. prevEnd += 1; } }); str += src.slice(prevEnd, range.end); return PlainValue$5.Node.addStringTerminator(src, range.end, str); } } class QuoteDouble extends PlainValue$5.Node { static endOfQuote(src, offset) { let ch = src[offset]; while (ch && ch !== '"') { offset += ch === '\\' ? 2 : 1; ch = src[offset]; } return offset + 1; } /** * @returns {string | { str: string, errors: YAMLSyntaxError[] }} */ get strValue() { if (!this.valueRange || !this.context) return null; const errors = []; const { start, end } = this.valueRange; const { indent, src } = this.context; if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by // escaped backslashes; also, this should be faster. let str = ''; for (let i = start + 1; i < end - 1; ++i) { const ch = src[i]; if (ch === '\n') { if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); const { fold, offset, error } = PlainValue$5.Node.foldNewline(src, i, indent); str += fold; i = offset; if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); } else if (ch === '\\') { i += 1; switch (src[i]) { case '0': str += '\0'; break; // null character case 'a': str += '\x07'; break; // bell character case 'b': str += '\b'; break; // backspace case 'e': str += '\x1b'; break; // escape character case 'f': str += '\f'; break; // form feed case 'n': str += '\n'; break; // line feed case 'r': str += '\r'; break; // carriage return case 't': str += '\t'; break; // horizontal tab case 'v': str += '\v'; break; // vertical tab case 'N': str += '\u0085'; break; // Unicode next line case '_': str += '\u00a0'; break; // Unicode non-breaking space case 'L': str += '\u2028'; break; // Unicode line separator case 'P': str += '\u2029'; break; // Unicode paragraph separator case ' ': str += ' '; break; case '"': str += '"'; break; case '/': str += '/'; break; case '\\': str += '\\'; break; case '\t': str += '\t'; break; case 'x': str += this.parseCharCode(i + 1, 2, errors); i += 2; break; case 'u': str += this.parseCharCode(i + 1, 4, errors); i += 4; break; case 'U': str += this.parseCharCode(i + 1, 8, errors); i += 8; break; case '\n': // skip escaped newlines, but still trim the following line while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; break; default: errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); str += '\\' + src[i]; } } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (next === ' ' || next === '\t') { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } return errors.length > 0 ? { errors, str } : str; } parseCharCode(offset, length, errors) { const { src } = this.context; const cc = src.substr(offset, length); const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); const code = ok ? parseInt(cc, 16) : NaN; if (isNaN(code)) { errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); return src.substr(offset - 2, length + 2); } return String.fromCodePoint(code); } /** * Parses a "double quoted" value from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = QuoteDouble.endOfQuote(src, start + 1); this.valueRange = new PlainValue$5.Range(start, offset); offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } class QuoteSingle extends PlainValue$5.Node { static endOfQuote(src, offset) { let ch = src[offset]; while (ch) { if (ch === "'") { if (src[offset + 1] !== "'") break; ch = src[offset += 2]; } else { ch = src[offset += 1]; } } return offset + 1; } /** * @returns {string | { str: string, errors: YAMLSyntaxError[] }} */ get strValue() { if (!this.valueRange || !this.context) return null; const errors = []; const { start, end } = this.valueRange; const { indent, src } = this.context; if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote")); let str = ''; for (let i = start + 1; i < end - 1; ++i) { const ch = src[i]; if (ch === '\n') { if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); const { fold, offset, error } = PlainValue$5.Node.foldNewline(src, i, indent); str += fold; i = offset; if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); } else if (ch === "'") { str += ch; i += 1; if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); } else if (ch === ' ' || ch === '\t') { // trim trailing whitespace const wsStart = i; let next = src[i + 1]; while (next === ' ' || next === '\t') { i += 1; next = src[i + 1]; } if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; } else { str += ch; } } return errors.length > 0 ? { errors, str } : str; } /** * Parses a 'single quoted' value from the source * * @param {ParseContext} context * @param {number} start - Index of first character * @returns {number} - Index of the character after this scalar */ parse(context, start) { this.context = context; const { src } = context; let offset = QuoteSingle.endOfQuote(src, start + 1); this.valueRange = new PlainValue$5.Range(start, offset); offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); offset = this.parseComment(offset); return offset; } } function createNewNode(type, props) { switch (type) { case PlainValue$5.Type.ALIAS: return new Alias$1(type, props); case PlainValue$5.Type.BLOCK_FOLDED: case PlainValue$5.Type.BLOCK_LITERAL: return new BlockValue(type, props); case PlainValue$5.Type.FLOW_MAP: case PlainValue$5.Type.FLOW_SEQ: return new FlowCollection(type, props); case PlainValue$5.Type.MAP_KEY: case PlainValue$5.Type.MAP_VALUE: case PlainValue$5.Type.SEQ_ITEM: return new CollectionItem(type, props); case PlainValue$5.Type.COMMENT: case PlainValue$5.Type.PLAIN: return new PlainValue$5.PlainValue(type, props); case PlainValue$5.Type.QUOTE_DOUBLE: return new QuoteDouble(type, props); case PlainValue$5.Type.QUOTE_SINGLE: return new QuoteSingle(type, props); /* istanbul ignore next */ default: return null; // should never happen } } /** * @param {boolean} atLineStart - Node starts at beginning of line * @param {boolean} inFlow - true if currently in a flow context * @param {boolean} inCollection - true if currently in a collection context * @param {number} indent - Current level of indentation * @param {number} lineStart - Start of the current line * @param {Node} parent - The parent of the node * @param {string} src - Source of the YAML document */ class ParseContext { static parseType(src, offset, inFlow) { switch (src[offset]) { case '*': return PlainValue$5.Type.ALIAS; case '>': return PlainValue$5.Type.BLOCK_FOLDED; case '|': return PlainValue$5.Type.BLOCK_LITERAL; case '{': return PlainValue$5.Type.FLOW_MAP; case '[': return PlainValue$5.Type.FLOW_SEQ; case '?': return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN; case ':': return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN; case '-': return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN; case '"': return PlainValue$5.Type.QUOTE_DOUBLE; case "'": return PlainValue$5.Type.QUOTE_SINGLE; default: return PlainValue$5.Type.PLAIN; } } constructor(orig = {}, { atLineStart, inCollection, inFlow, indent, lineStart, parent } = {}) { PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => { if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null; const context = new ParseContext(this, overlay); const { props, type, valueStart } = context.parseProps(start); const node = createNewNode(type, props); let offset = node.parse(context, valueStart); node.range = new PlainValue$5.Range(start, offset); /* istanbul ignore if */ if (offset <= start) { // This should never happen, but if it does, let's make sure to at least // step one character forward to avoid a busy loop. node.error = new Error(`Node#parse consumed no characters`); node.error.parseEnd = offset; node.error.source = node; node.range.end = start + 1; } if (context.nodeStartsCollection(node)) { if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) { node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); } const collection = new Collection$1(node); offset = collection.parse(new ParseContext(context), offset); collection.range = new PlainValue$5.Range(start, offset); return collection; } return node; }); this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; this.indent = indent != null ? indent : orig.indent; this.lineStart = lineStart != null ? lineStart : orig.lineStart; this.parent = parent != null ? parent : orig.parent || {}; this.root = orig.root; this.src = orig.src; } nodeStartsCollection(node) { const { inCollection, inFlow, src } = this; if (inCollection || inFlow) return false; if (node instanceof CollectionItem) return true; // check for implicit key let offset = node.range.end; if (src[offset] === '\n' || src[offset - 1] === '\n') return false; offset = PlainValue$5.Node.endOfWhiteSpace(src, offset); return src[offset] === ':'; } // Anchor and tag are before type, which determines the node implementation // class; hence this intermediate step. parseProps(offset) { const { inFlow, parent, src } = this; const props = []; let lineHasProps = false; offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset); let ch = src[offset]; while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') { if (ch === '\n') { let inEnd = offset; let lineStart; do { lineStart = inEnd + 1; inEnd = PlainValue$5.Node.endOfIndent(src, lineStart); } while (src[inEnd] === '\n'); const indentDiff = inEnd - (lineStart + this.indent); const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart; if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; this.atLineStart = true; this.lineStart = lineStart; lineHasProps = false; offset = inEnd; } else if (ch === PlainValue$5.Char.COMMENT) { const end = PlainValue$5.Node.endOfLine(src, offset + 1); props.push(new PlainValue$5.Range(offset, end)); offset = end; } else { let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1); if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { // Let's presume we're dealing with a YAML 1.0 domain tag here, rather // than an empty but 'foo.bar' private-tagged node in a flow collection // followed without whitespace by a plain string starting with a year // or date divided by something. end = PlainValue$5.Node.endOfIdentifier(src, end + 5); } props.push(new PlainValue$5.Range(offset, end)); lineHasProps = true; offset = PlainValue$5.Node.endOfWhiteSpace(src, end); } ch = src[offset]; } // '- &a : b' has an anchor on an empty node if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1; const type = ParseContext.parseType(src, offset, inFlow); return { props, type, valueStart: offset }; } /** * Parses a node from the source * @param {ParseContext} overlay * @param {number} start - Index of first non-whitespace character for the node * @returns {?Node} - null if at a document boundary */ } // Published as 'yaml/parse-cst' function parse$h(src) { const cr = []; if (src.indexOf('\r') !== -1) { src = src.replace(/\r\n?/g, (match, offset) => { if (match.length > 1) cr.push(offset); return '\n'; }); } const documents = []; let offset = 0; do { const doc = new Document$3(); const context = new ParseContext({ src }); offset = doc.parse(context, offset); documents.push(doc); } while (offset < src.length); documents.setOrigRanges = () => { if (cr.length === 0) return false; for (let i = 1; i < cr.length; ++i) cr[i] -= i; let crOffset = 0; for (let i = 0; i < documents.length; ++i) { crOffset = documents[i].setOrigRanges(cr, crOffset); } cr.splice(0, cr.length); return true; }; documents.toString = () => documents.join('...\n'); return documents; } parseCst$1.parse = parse$h; var Document9b4560a1 = {}; var resolveSeqD03cb037 = {}; var PlainValue$4 = PlainValueEc8e588e; function addCommentBefore(str, indent, comment) { if (!comment) return str; const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); return `#${cc}\n${indent}${str}`; } function addComment(str, indent, comment) { return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); } class Node$1 {} function toJSON(value, arg, ctx) { if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); if (value && typeof value.toJSON === 'function') { const anchor = ctx && ctx.anchors && ctx.anchors.get(value); if (anchor) ctx.onCreate = res => { anchor.res = res; delete ctx.onCreate; }; const res = value.toJSON(arg, ctx); if (anchor && ctx.onCreate) ctx.onCreate(res); return res; } if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); return value; } class Scalar extends Node$1 { constructor(value) { super(); this.value = value; } toJSON(arg, ctx) { return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); } toString() { return String(this.value); } } function collectionFromPath(schema, path, value) { let v = value; for (let i = path.length - 1; i >= 0; --i) { const k = path[i]; if (Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; v = a; } else { const o = {}; Object.defineProperty(o, k, { value: v, writable: true, enumerable: true, configurable: true }); v = o; } } return schema.createNode(v, false); } // null, undefined, or an empty non-string iterable (e.g. []) const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; class Collection extends Node$1 { constructor(schema) { super(); PlainValue$4._defineProperty(this, "items", []); this.schema = schema; } addIn(path, value) { if (isEmptyPath(path)) this.add(value);else { const [key, ...rest] = path; const node = this.get(key, true); if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } deleteIn([key, ...rest]) { if (rest.length === 0) return this.delete(key); const node = this.get(key, true); if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } getIn([key, ...rest], keepScalar) { const node = this.get(key, true); if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; } hasAllNullValues() { return this.items.every(node => { if (!node || node.type !== 'PAIR') return false; const n = node.value; return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; }); } hasIn([key, ...rest]) { if (rest.length === 0) return this.has(key); const node = this.get(key, true); return node instanceof Collection ? node.hasIn(rest) : false; } setIn([key, ...rest], value) { if (rest.length === 0) { this.set(key, value); } else { const node = this.get(key, true); if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } // overridden in implementations /* istanbul ignore next */ toJSON() { return null; } toString(ctx, { blockItem, flowChars, isMap, itemIndent }, onComment, onChompKeep) { const { indent, indentStep, stringify } = ctx; const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow; if (inFlow) itemIndent += indentStep; const allNullValues = isMap && this.hasAllNullValues(); ctx = Object.assign({}, ctx, { allNullValues, indent: itemIndent, inFlow, type: null }); let chompKeep = false; let hasItemWithNewLine = false; const nodes = this.items.reduce((nodes, item, i) => { let comment; if (item) { if (!chompKeep && item.spaceBefore) nodes.push({ type: 'comment', str: '' }); if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { nodes.push({ type: 'comment', str: `#${line}` }); }); if (item.comment) comment = item.comment; if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; } chompKeep = false; let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; if (inFlow && i < this.items.length - 1) str += ','; str = addComment(str, itemIndent, comment); if (chompKeep && (comment || inFlow)) chompKeep = false; nodes.push({ type: 'item', str }); return nodes; }, []); let str; if (nodes.length === 0) { str = flowChars.start + flowChars.end; } else if (inFlow) { const { start, end } = flowChars; const strings = nodes.map(n => n.str); if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { str = start; for (const s of strings) { str += s ? `\n${indentStep}${indent}${s}` : '\n'; } str += `\n${indent}${end}`; } else { str = `${start} ${strings.join(' ')} ${end}`; } } else { const strings = nodes.map(blockItem); str = strings.shift(); for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; } if (this.comment) { str += '\n' + this.comment.replace(/^/gm, `${indent}#`); if (onComment) onComment(); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } } PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); function asItemIndex(key) { let idx = key instanceof Scalar ? key.value : key; if (idx && typeof idx === 'string') idx = Number(idx); return Number.isInteger(idx) && idx >= 0 ? idx : null; } class YAMLSeq extends Collection { add(value) { this.items.push(value); } delete(key) { const idx = asItemIndex(key); if (typeof idx !== 'number') return false; const del = this.items.splice(idx, 1); return del.length > 0; } get(key, keepScalar) { const idx = asItemIndex(key); if (typeof idx !== 'number') return undefined; const it = this.items[idx]; return !keepScalar && it instanceof Scalar ? it.value : it; } has(key) { const idx = asItemIndex(key); return typeof idx === 'number' && idx < this.items.length; } set(key, value) { const idx = asItemIndex(key); if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); this.items[idx] = value; } toJSON(_, ctx) { const seq = []; if (ctx && ctx.onCreate) ctx.onCreate(seq); let i = 0; for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); return seq; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); return super.toString(ctx, { blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, flowChars: { start: '[', end: ']' }, isMap: false, itemIndent: (ctx.indent || '') + ' ' }, onComment, onChompKeep); } } const stringifyKey = (key, jsKey, ctx) => { if (jsKey === null) return ''; if (typeof jsKey !== 'object') return String(jsKey); if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({ anchors: Object.create(null), doc: ctx.doc, indent: '', indentStep: ctx.indentStep, inFlow: true, inStringifyKey: true, stringify: ctx.stringify }); return JSON.stringify(jsKey); }; class Pair extends Node$1 { constructor(key, value = null) { super(); this.key = key; this.value = value; this.type = Pair.Type.PAIR; } get commentBefore() { return this.key instanceof Node$1 ? this.key.commentBefore : undefined; } set commentBefore(cb) { if (this.key == null) this.key = new Scalar(null); if (this.key instanceof Node$1) this.key.commentBefore = cb;else { const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; throw new Error(msg); } } addToJSMap(ctx, map) { const key = toJSON(this.key, '', ctx); if (map instanceof Map) { const value = toJSON(this.value, key, ctx); map.set(key, value); } else if (map instanceof Set) { map.add(key); } else { const stringKey = stringifyKey(this.key, key, ctx); const value = toJSON(this.value, stringKey, ctx); if (stringKey in map) Object.defineProperty(map, stringKey, { value, writable: true, enumerable: true, configurable: true });else map[stringKey] = value; } return map; } toJSON(_, ctx) { const pair = ctx && ctx.mapAsMap ? new Map() : {}; return this.addToJSMap(ctx, pair); } toString(ctx, onComment, onChompKeep) { if (!ctx || !ctx.doc) return JSON.stringify(this); const { indent: indentSize, indentSeq, simpleKeys } = ctx.doc.options; let { key, value } = this; let keyComment = key instanceof Node$1 && key.comment; if (simpleKeys) { if (keyComment) { throw new Error('With simple keys, key nodes cannot have comments'); } if (key instanceof Collection) { const msg = 'With simple keys, collection cannot be used as a key value'; throw new Error(msg); } } let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object')); const { doc, indent, indentStep, stringify } = ctx; ctx = Object.assign({}, ctx, { implicitKey: !explicitKey, indent: indent + indentStep }); let chompKeep = false; let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); str = addComment(str, ctx.indent, keyComment); if (!explicitKey && str.length > 1024) { if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters'); explicitKey = true; } if (ctx.allNullValues && !simpleKeys) { if (this.comment) { str = addComment(str, ctx.indent, this.comment); if (onComment) onComment(); } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); return ctx.inFlow && !explicitKey ? str : `? ${str}`; } str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; if (this.comment) { // expected (but not strictly required) to be a single-line comment str = addComment(str, ctx.indent, this.comment); if (onComment) onComment(); } let vcb = ''; let valueComment = null; if (value instanceof Node$1) { if (value.spaceBefore) vcb = '\n'; if (value.commentBefore) { const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); vcb += `\n${cs}`; } valueComment = value.comment; } else if (value && typeof value === 'object') { value = doc.schema.createNode(value, true); } ctx.implicitKey = false; if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; chompKeep = false; if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { // If indentSeq === false, consider '- ' as part of indentation where possible ctx.indent = ctx.indent.substr(2); } const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); let ws = ' '; if (vcb || this.comment) { ws = `${vcb}\n${ctx.indent}`; } else if (!explicitKey && value instanceof Collection) { const flow = valueStr[0] === '[' || valueStr[0] === '{'; if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; } else if (valueStr[0] === '\n') ws = ''; if (chompKeep && !valueComment && onChompKeep) onChompKeep(); return addComment(str + ws + valueStr, ctx.indent, valueComment); } } PlainValue$4._defineProperty(Pair, "Type", { PAIR: 'PAIR', MERGE_PAIR: 'MERGE_PAIR' }); const getAliasCount = (node, anchors) => { if (node instanceof Alias) { const anchor = anchors.get(node.source); return anchor.count * anchor.aliasCount; } else if (node instanceof Collection) { let count = 0; for (const item of node.items) { const c = getAliasCount(item, anchors); if (c > count) count = c; } return count; } else if (node instanceof Pair) { const kc = getAliasCount(node.key, anchors); const vc = getAliasCount(node.value, anchors); return Math.max(kc, vc); } return 1; }; class Alias extends Node$1 { static stringify({ range, source }, { anchors, doc, implicitKey, inStringifyKey }) { let anchor = Object.keys(anchors).find(a => anchors[a] === source); if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; throw new Error(`${msg} [${range}]`); } constructor(source) { super(); this.source = source; this.type = PlainValue$4.Type.ALIAS; } set tag(t) { throw new Error('Alias nodes cannot have tags'); } toJSON(arg, ctx) { if (!ctx) return toJSON(this.source, arg, ctx); const { anchors, maxAliasCount } = ctx; const anchor = anchors.get(this.source); /* istanbul ignore if */ if (!anchor || anchor.res === undefined) { const msg = 'This should not happen: Alias anchor was not resolved?'; if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); } if (maxAliasCount >= 0) { anchor.count += 1; if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); if (anchor.count * anchor.aliasCount > maxAliasCount) { const msg = 'Excessive alias count indicates a resource exhaustion attack'; if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); } } return anchor.res; } // Only called when stringifying an alias mapping key while constructing // Object output. toString(ctx) { return Alias.stringify(this, ctx); } } PlainValue$4._defineProperty(Alias, "default", true); function findPair(items, key) { const k = key instanceof Scalar ? key.value : key; for (const it of items) { if (it instanceof Pair) { if (it.key === key || it.key === k) return it; if (it.key && it.key.value === k) return it; } } return undefined; } class YAMLMap extends Collection { add(pair, overwrite) { if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); const prev = findPair(this.items, pair.key); const sortEntries = this.schema && this.schema.sortMapEntries; if (prev) { if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); } else if (sortEntries) { const i = this.items.findIndex(item => sortEntries(pair, item) < 0); if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); } else { this.items.push(pair); } } delete(key) { const it = findPair(this.items, key); if (!it) return false; const del = this.items.splice(this.items.indexOf(it), 1); return del.length > 0; } get(key, keepScalar) { const it = findPair(this.items, key); const node = it && it.value; return !keepScalar && node instanceof Scalar ? node.value : node; } has(key) { return !!findPair(this.items, key); } set(key, value) { this.add(new Pair(key, value), true); } /** * @param {*} arg ignored * @param {*} ctx Conversion context, originally set in Document#toJSON() * @param {Class} Type If set, forces the returned collection type * @returns {*} Instance of Type, Map, or Object */ toJSON(_, ctx, Type) { const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; if (ctx && ctx.onCreate) ctx.onCreate(map); for (const item of this.items) item.addToJSMap(ctx, map); return map; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); for (const item of this.items) { if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); } return super.toString(ctx, { blockItem: n => n.str, flowChars: { start: '{', end: '}' }, isMap: true, itemIndent: ctx.indent || '' }, onComment, onChompKeep); } } const MERGE_KEY = '<<'; class Merge extends Pair { constructor(pair) { if (pair instanceof Pair) { let seq = pair.value; if (!(seq instanceof YAMLSeq)) { seq = new YAMLSeq(); seq.items.push(pair.value); seq.range = pair.value.range; } super(pair.key, seq); this.range = pair.range; } else { super(new Scalar(MERGE_KEY), new YAMLSeq()); } this.type = Pair.Type.MERGE_PAIR; } // If the value associated with a merge key is a single mapping node, each of // its key/value pairs is inserted into the current mapping, unless the key // already exists in it. If the value associated with the merge key is a // sequence, then this sequence is expected to contain mapping nodes and each // of these nodes is merged in turn according to its order in the sequence. // Keys in mapping nodes earlier in the sequence override keys specified in // later mapping nodes. -- http://yaml.org/type/merge.html addToJSMap(ctx, map) { for (const { source } of this.value.items) { if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); const srcMap = source.toJSON(null, ctx, Map); for (const [key, value] of srcMap) { if (map instanceof Map) { if (!map.has(key)) map.set(key, value); } else if (map instanceof Set) { map.add(key); } else if (!Object.prototype.hasOwnProperty.call(map, key)) { Object.defineProperty(map, key, { value, writable: true, enumerable: true, configurable: true }); } } } return map; } toString(ctx, onComment) { const seq = this.value; if (seq.items.length > 1) return super.toString(ctx, onComment); this.value = seq.items[0]; const str = super.toString(ctx, onComment); this.value = seq; return str; } } const binaryOptions = { defaultType: PlainValue$4.Type.BLOCK_LITERAL, lineWidth: 76 }; const boolOptions = { trueStr: 'true', falseStr: 'false' }; const intOptions = { asBigInt: false }; const nullOptions = { nullStr: 'null' }; const strOptions = { defaultType: PlainValue$4.Type.PLAIN, doubleQuoted: { jsonEncoding: false, minMultiLineLength: 40 }, fold: { lineWidth: 80, minContentWidth: 20 } }; function resolveScalar(str, tags, scalarFallback) { for (const { format, test, resolve } of tags) { if (test) { const match = str.match(test); if (match) { let res = resolve.apply(null, match); if (!(res instanceof Scalar)) res = new Scalar(res); if (format) res.format = format; return res; } } } if (scalarFallback) str = scalarFallback(str); return new Scalar(str); } const FOLD_FLOW = 'flow'; const FOLD_BLOCK = 'block'; const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line // returns index of last newline in more-indented block const consumeMoreIndentedLines = (text, i) => { let ch = text[i + 1]; while (ch === ' ' || ch === '\t') { do { ch = text[i += 1]; } while (ch && ch !== '\n'); ch = text[i + 1]; } return i; }; /** * Tries to keep input at up to `lineWidth` characters, splitting only on spaces * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are * terminated with `\n` and started with `indent`. * * @param {string} text * @param {string} indent * @param {string} [mode='flow'] `'block'` prevents more-indented lines * from being folded; `'quoted'` allows for `\` escapes, including escaped * newlines * @param {Object} options * @param {number} [options.indentAtStart] Accounts for leading contents on * the first line, defaulting to `indent.length` * @param {number} [options.lineWidth=80] * @param {number} [options.minContentWidth=20] Allow highly indented lines to * stretch the line width or indent content from the start * @param {function} options.onFold Called once if the text is folded * @param {function} options.onFold Called once if any line of text exceeds * lineWidth characters */ function foldFlowLines(text, indent, mode, { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow }) { if (!lineWidth || lineWidth < 0) return text; const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); if (text.length <= endStep) return text; const folds = []; const escapedFolds = {}; let end = lineWidth - indent.length; if (typeof indentAtStart === 'number') { if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart; } let split = undefined; let prev = undefined; let overflow = false; let i = -1; let escStart = -1; let escEnd = -1; if (mode === FOLD_BLOCK) { i = consumeMoreIndentedLines(text, i); if (i !== -1) end = i + endStep; } for (let ch; ch = text[i += 1];) { if (mode === FOLD_QUOTED && ch === '\\') { escStart = i; switch (text[i + 1]) { case 'x': i += 3; break; case 'u': i += 5; break; case 'U': i += 9; break; default: i += 1; } escEnd = i; } if (ch === '\n') { if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); end = i + endStep; split = undefined; } else { if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { // space surrounded by non-space can be replaced with newline + indent const next = text[i + 1]; if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; } if (i >= end) { if (split) { folds.push(split); end = split + endStep; split = undefined; } else if (mode === FOLD_QUOTED) { // white-space collected at end may stretch past lineWidth while (prev === ' ' || prev === '\t') { prev = ch; ch = text[i += 1]; overflow = true; } // Account for newline escape, but don't break preceding escape const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string if (escapedFolds[j]) return text; folds.push(j); escapedFolds[j] = true; end = j + endStep; split = undefined; } else { overflow = true; } } } prev = ch; } if (overflow && onOverflow) onOverflow(); if (folds.length === 0) return text; if (onFold) onFold(); let res = text.slice(0, folds[0]); for (let i = 0; i < folds.length; ++i) { const fold = folds[i]; const end = folds[i + 1] || text.length; if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else { if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; res += `\n${indent}${text.slice(fold + 1, end)}`; } } return res; } const getFoldOptions = ({ indentAtStart }) => indentAtStart ? Object.assign({ indentAtStart }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will // presume that's starting a new document. const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str); function lineLengthOverLimit(str, lineWidth, indentLength) { if (!lineWidth || lineWidth < 0) return false; const limit = lineWidth - indentLength; const strLen = str.length; if (strLen <= limit) return false; for (let i = 0, start = 0; i < strLen; ++i) { if (str[i] === '\n') { if (i - start > limit) return true; start = i + 1; if (strLen - start <= limit) return false; } } return true; } function doubleQuotedString(value, ctx) { const { implicitKey } = ctx; const { jsonEncoding, minMultiLineLength } = strOptions.doubleQuoted; const json = JSON.stringify(value); if (jsonEncoding) return json; const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); let str = ''; let start = 0; for (let i = 0, ch = json[i]; ch; ch = json[++i]) { if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { // space before newline needs to be escaped to not be folded str += json.slice(start, i) + '\\ '; i += 1; start = i; ch = '\\'; } if (ch === '\\') switch (json[i + 1]) { case 'u': { str += json.slice(start, i); const code = json.substr(i + 2, 4); switch (code) { case '0000': str += '\\0'; break; case '0007': str += '\\a'; break; case '000b': str += '\\v'; break; case '001b': str += '\\e'; break; case '0085': str += '\\N'; break; case '00a0': str += '\\_'; break; case '2028': str += '\\L'; break; case '2029': str += '\\P'; break; default: if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); } i += 5; start = i + 1; } break; case 'n': if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { i += 1; } else { // folding will eat first newline str += json.slice(start, i) + '\n\n'; while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { str += '\n'; i += 2; } str += indent; // space after newline needs to be escaped to not be folded if (json[i + 2] === ' ') str += '\\'; i += 1; start = i + 1; } break; default: i += 1; } } str = start ? str + json.slice(start) : json; return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); } function singleQuotedString(value, ctx) { if (ctx.implicitKey) { if (/\n/.test(value)) return doubleQuotedString(value, ctx); } else { // single quoted string can't have leading or trailing whitespace around newline if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); } const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); } function blockString({ comment, type, value }, ctx, onComment, onChompKeep) { // 1. Block can't end in whitespace unless the last line is non-empty. // 2. Strings consisting of only whitespace are best rendered explicitly. if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { return doubleQuotedString(value, ctx); } const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); const indentSize = indent ? '2' : '1'; // root is at -1 const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length); let header = literal ? '|' : '>'; if (!value) return header + '\n'; let wsStart = ''; let wsEnd = ''; value = value.replace(/[\n\t ]*$/, ws => { const n = ws.indexOf('\n'); if (n === -1) { header += '-'; // strip } else if (value === ws || n !== ws.length - 1) { header += '+'; // keep if (onChompKeep) onChompKeep(); } wsEnd = ws.replace(/\n$/, ''); return ''; }).replace(/^[\n ]*/, ws => { if (ws.indexOf(' ') !== -1) header += indentSize; const m = ws.match(/ +$/); if (m) { wsStart = ws.slice(0, -m[0].length); return m[0]; } else { wsStart = ws; return ''; } }); if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); if (comment) { header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); if (onComment) onComment(); } if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; if (literal) { value = value.replace(/\n+/g, `$&${indent}`); return `${header}\n${indent}${wsStart}${value}${wsEnd}`; } value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded // ^ ind.line ^ empty ^ capture next empty lines only at end of indent .replace(/\n+/g, `$&${indent}`); const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); return `${header}\n${indent}${body}`; } function plainString(item, ctx, onComment, onChompKeep) { const { comment, type, value } = item; const { actualString, implicitKey, indent, inFlow } = ctx; if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { return doubleQuotedString(value, ctx); } if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { // not allowed: // - empty string, '-' or '?' // - start with an indicator character (except [?:-]) or /[?-] / // - '\n ', ': ' or ' \n' anywhere // - '#' not preceded by a non-space char // - end with ' ' or ':' return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); } if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) { // Where allowed & type not set explicitly, prefer block style for multiline strings return blockString(item, ctx, onComment, onChompKeep); } if (indent === '' && containsDocumentMarker(value)) { ctx.forceBlockIndent = true; return blockString(item, ctx, onComment, onChompKeep); } const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), // and others in v1.1. if (actualString) { const { tags } = ctx.doc.schema; const resolved = resolveScalar(str, tags, tags.scalarFallback).value; if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); } const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { if (onComment) onComment(); return addCommentBefore(body, indent, comment); } return body; } function stringifyString(item, ctx, onComment, onChompKeep) { const { defaultType } = strOptions; const { implicitKey, inFlow } = ctx; let { type, value } = item; if (typeof value !== 'string') { value = String(value); item = Object.assign({}, item, { value }); } const _stringify = _type => { switch (_type) { case PlainValue$4.Type.BLOCK_FOLDED: case PlainValue$4.Type.BLOCK_LITERAL: return blockString(item, ctx, onComment, onChompKeep); case PlainValue$4.Type.QUOTE_DOUBLE: return doubleQuotedString(value, ctx); case PlainValue$4.Type.QUOTE_SINGLE: return singleQuotedString(value, ctx); case PlainValue$4.Type.PLAIN: return plainString(item, ctx, onComment, onChompKeep); default: return null; } }; if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { // force double quotes on control characters type = PlainValue$4.Type.QUOTE_DOUBLE; } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) { // should not happen; blocks are not valid inside flow containers type = PlainValue$4.Type.QUOTE_DOUBLE; } let res = _stringify(type); if (res === null) { res = _stringify(defaultType); if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); } return res; } function stringifyNumber({ format, minFractionDigits, tag, value }) { if (typeof value === 'bigint') return String(value); if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; let n = JSON.stringify(value); if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { let i = n.indexOf('.'); if (i < 0) { i = n.length; n += '.'; } let d = minFractionDigits - (n.length - i - 1); while (d-- > 0) n += '0'; } return n; } function checkFlowCollectionEnd(errors, cst) { let char, name; switch (cst.type) { case PlainValue$4.Type.FLOW_MAP: char = '}'; name = 'flow map'; break; case PlainValue$4.Type.FLOW_SEQ: char = ']'; name = 'flow sequence'; break; default: errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?')); return; } let lastItem; for (let i = cst.items.length - 1; i >= 0; --i) { const item = cst.items[i]; if (!item || item.type !== PlainValue$4.Type.COMMENT) { lastItem = item; break; } } if (lastItem && lastItem.char !== char) { const msg = `Expected ${name} to end with ${char}`; let err; if (typeof lastItem.offset === 'number') { err = new PlainValue$4.YAMLSemanticError(cst, msg); err.offset = lastItem.offset + 1; } else { err = new PlainValue$4.YAMLSemanticError(lastItem, msg); if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; } errors.push(err); } } function checkFlowCommentSpace(errors, comment) { const prev = comment.context.src[comment.range.start - 1]; if (prev !== '\n' && prev !== '\t' && prev !== ' ') { const msg = 'Comments must be separated from other tokens by white space characters'; errors.push(new PlainValue$4.YAMLSemanticError(comment, msg)); } } function getLongKeyError(source, key) { const sk = String(key); const k = sk.substr(0, 8) + '...' + sk.substr(-8); return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`); } function resolveComments(collection, comments) { for (const { afterKey, before, comment } of comments) { let item = collection.items[before]; if (!item) { if (comment !== undefined) { if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; } } else { if (afterKey && item.value) item = item.value; if (comment === undefined) { if (afterKey || !item.commentBefore) item.spaceBefore = true; } else { if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; } } } } // on error, will return { str: string, errors: Error[] } function resolveString(doc, node) { const res = node.strValue; if (!res) return ''; if (typeof res === 'string') return res; res.errors.forEach(error => { if (!error.source) error.source = node; doc.errors.push(error); }); return res.str; } function resolveTagHandle(doc, node) { const { handle, suffix } = node.tag; let prefix = doc.tagPrefixes.find(p => p.handle === handle); if (!prefix) { const dtp = doc.getDefaults().tagPrefixes; if (dtp) prefix = dtp.find(p => p.handle === handle); if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); } if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); if (handle === '!' && (doc.version || doc.options.version) === '1.0') { if (suffix[0] === '^') { doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); return suffix; } if (/[:/]/.test(suffix)) { // word/foo -> tag:word.yaml.org,2002:foo const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; } } return prefix.prefix + decodeURIComponent(suffix); } function resolveTagName(doc, node) { const { tag, type } = node; let nonSpecific = false; if (tag) { const { handle, suffix, verbatim } = tag; if (verbatim) { if (verbatim !== '!' && verbatim !== '!!') return verbatim; const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); } else if (handle === '!' && !suffix) { nonSpecific = true; } else { try { return resolveTagHandle(doc, node); } catch (error) { doc.errors.push(error); } } } switch (type) { case PlainValue$4.Type.BLOCK_FOLDED: case PlainValue$4.Type.BLOCK_LITERAL: case PlainValue$4.Type.QUOTE_DOUBLE: case PlainValue$4.Type.QUOTE_SINGLE: return PlainValue$4.defaultTags.STR; case PlainValue$4.Type.FLOW_MAP: case PlainValue$4.Type.MAP: return PlainValue$4.defaultTags.MAP; case PlainValue$4.Type.FLOW_SEQ: case PlainValue$4.Type.SEQ: return PlainValue$4.defaultTags.SEQ; case PlainValue$4.Type.PLAIN: return nonSpecific ? PlainValue$4.defaultTags.STR : null; default: return null; } } function resolveByTagName(doc, node, tagName) { const { tags } = doc.schema; const matchWithTest = []; for (const tag of tags) { if (tag.tag === tagName) { if (tag.test) matchWithTest.push(tag);else { const res = tag.resolve(doc, node); return res instanceof Collection ? res : new Scalar(res); } } } const str = resolveString(doc, node); if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); return null; } function getFallbackTagName({ type }) { switch (type) { case PlainValue$4.Type.FLOW_MAP: case PlainValue$4.Type.MAP: return PlainValue$4.defaultTags.MAP; case PlainValue$4.Type.FLOW_SEQ: case PlainValue$4.Type.SEQ: return PlainValue$4.defaultTags.SEQ; default: return PlainValue$4.defaultTags.STR; } } function resolveTag(doc, node, tagName) { try { const res = resolveByTagName(doc, node, tagName); if (res) { if (tagName && node.tag) res.tag = tagName; return res; } } catch (error) { /* istanbul ignore if */ if (!error.source) error.source = node; doc.errors.push(error); return null; } try { const fallback = getFallbackTagName(node); if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg)); const res = resolveByTagName(doc, node, fallback); res.tag = tagName; return res; } catch (error) { const refError = new PlainValue$4.YAMLReferenceError(node, error.message); refError.stack = error.stack; doc.errors.push(refError); return null; } } const isCollectionItem = node => { if (!node) return false; const { type } = node; return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM; }; function resolveNodeProps(errors, node) { const comments = { before: [], after: [] }; let hasAnchor = false; let hasTag = false; const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; for (const { start, end } of props) { switch (node.context.src[start]) { case PlainValue$4.Char.COMMENT: { if (!node.commentHasRequiredWhitespace(start)) { const msg = 'Comments must be separated from other tokens by white space characters'; errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); } const { header, valueRange } = node; const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; cc.push(node.context.src.slice(start + 1, end)); break; } // Actual anchor & tag resolution is handled by schema, here we just complain case PlainValue$4.Char.ANCHOR: if (hasAnchor) { const msg = 'A node can have at most one anchor'; errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); } hasAnchor = true; break; case PlainValue$4.Char.TAG: if (hasTag) { const msg = 'A node can have at most one tag'; errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); } hasTag = true; break; } } return { comments, hasAnchor, hasTag }; } function resolveNodeValue(doc, node) { const { anchors, errors, schema } = doc; if (node.type === PlainValue$4.Type.ALIAS) { const name = node.rawValue; const src = anchors.getNode(name); if (!src) { const msg = `Aliased anchor not found: ${name}`; errors.push(new PlainValue$4.YAMLReferenceError(node, msg)); return null; } // Lazy resolution for circular references const res = new Alias(src); anchors._cstAliases.push(res); return res; } const tagName = resolveTagName(doc, node); if (tagName) return resolveTag(doc, node, tagName); if (node.type !== PlainValue$4.Type.PLAIN) { const msg = `Failed to resolve ${node.type} node here`; errors.push(new PlainValue$4.YAMLSyntaxError(node, msg)); return null; } try { const str = resolveString(doc, node); return resolveScalar(str, schema.tags, schema.tags.scalarFallback); } catch (error) { if (!error.source) error.source = node; errors.push(error); return null; } } // sets node.resolved on success function resolveNode(doc, node) { if (!node) return null; if (node.error) doc.errors.push(node.error); const { comments, hasAnchor, hasTag } = resolveNodeProps(doc.errors, node); if (hasAnchor) { const { anchors } = doc; const name = node.anchor; const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor // name have already been resolved, so it may safely be renamed. if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as // anchors need to be available during resolution to allow for // circular references. anchors.map[name] = node; } if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) { const msg = 'An alias node must not specify any properties'; doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg)); } const res = resolveNodeValue(doc, node); if (res) { res.range = [node.range.start, node.range.end]; if (doc.options.keepCstNodes) res.cstNode = node; if (doc.options.keepNodeTypes) res.type = node.type; const cb = comments.before.join('\n'); if (cb) { res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; } const ca = comments.after.join('\n'); if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; } return node.resolved = res; } function resolveMap(doc, cst) { if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) { const msg = `A ${cst.type} node cannot be resolved as a mapping`; doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); return null; } const { comments, items } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); const map = new YAMLMap(); map.items = items; resolveComments(map, comments); let hasCollectionKey = false; for (let i = 0; i < items.length; ++i) { const { key: iKey } = items[i]; if (iKey instanceof Collection) hasCollectionKey = true; if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { items[i] = new Merge(items[i]); const sources = items[i].value.items; let error = null; sources.some(node => { if (node instanceof Alias) { // During parsing, alias sources are CST nodes; to account for // circular references their resolved values can't be used here. const { type } = node.source; if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false; return error = 'Merge nodes aliases can only point to maps'; } return error = 'Merge nodes can only have Alias nodes as values'; }); if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error)); } else { for (let j = i + 1; j < items.length; ++j) { const { key: jKey } = items[j]; if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { const msg = `Map keys must be unique; "${iKey}" is repeated`; doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg)); break; } } } } if (hasCollectionKey && !doc.options.mapAsMap) { const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); } cst.resolved = map; return map; } const valueHasPairComment = ({ context: { lineStart, node, src }, props }) => { if (props.length === 0) return false; const { start } = props[0]; if (node && start > node.valueRange.start) return false; if (src[start] !== PlainValue$4.Char.COMMENT) return false; for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; return true; }; function resolvePairComment(item, pair) { if (!valueHasPairComment(item)) return; const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true); let found = false; const cb = pair.value.commentBefore; if (cb && cb.startsWith(comment)) { pair.value.commentBefore = cb.substr(comment.length + 1); found = true; } else { const cc = pair.value.comment; if (!item.node && cc && cc.startsWith(comment)) { pair.value.comment = cc.substr(comment.length + 1); found = true; } } if (found) pair.comment = comment; } function resolveBlockMapItems(doc, cst) { const comments = []; const items = []; let key = undefined; let keyStart = null; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; switch (item.type) { case PlainValue$4.Type.BLANK_LINE: comments.push({ afterKey: !!key, before: items.length }); break; case PlainValue$4.Type.COMMENT: comments.push({ afterKey: !!key, before: items.length, comment: item.comment }); break; case PlainValue$4.Type.MAP_KEY: if (key !== undefined) items.push(new Pair(key)); if (item.error) doc.errors.push(item.error); key = resolveNode(doc, item.node); keyStart = null; break; case PlainValue$4.Type.MAP_VALUE: { if (key === undefined) key = null; if (item.error) doc.errors.push(item.error); if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) { const msg = 'Nested mappings are not allowed in compact mappings'; doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg)); } let valueNode = item.node; if (!valueNode && item.props.length > 0) { // Comments on an empty mapping value need to be preserved, so we // need to construct a minimal empty node here to use instead of the // missing `item.node`. -- eemeli/yaml#19 valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []); valueNode.context = { parent: item, src: item.context.src }; const pos = item.range.start + 1; valueNode.range = { start: pos, end: pos }; valueNode.valueRange = { start: pos, end: pos }; if (typeof item.range.origStart === 'number') { const origPos = item.range.origStart + 1; valueNode.range.origStart = valueNode.range.origEnd = origPos; valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; } } const pair = new Pair(key, resolveNode(doc, valueNode)); resolvePairComment(item, pair); items.push(pair); if (key && typeof keyStart === 'number') { if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); } key = undefined; keyStart = null; } break; default: if (key !== undefined) items.push(new Pair(key)); key = resolveNode(doc, item); keyStart = item.range.start; if (item.error) doc.errors.push(item.error); next: for (let j = i + 1;; ++j) { const nextItem = cst.items[j]; switch (nextItem && nextItem.type) { case PlainValue$4.Type.BLANK_LINE: case PlainValue$4.Type.COMMENT: continue next; case PlainValue$4.Type.MAP_VALUE: break next; default: { const msg = 'Implicit map keys need to be followed by map values'; doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); break next; } } } if (item.valueRangeContainsNewline) { const msg = 'Implicit map keys need to be on a single line'; doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); } } } if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } function resolveFlowMapItems(doc, cst) { const comments = []; const items = []; let key = undefined; let explicitKey = false; let next = '{'; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; if (typeof item.char === 'string') { const { char, offset } = item; if (char === '?' && key === undefined && !explicitKey) { explicitKey = true; next = ':'; continue; } if (char === ':') { if (key === undefined) key = null; if (next === ':') { next = ','; continue; } } else { if (explicitKey) { if (key === undefined && char !== ',') key = null; explicitKey = false; } if (key !== undefined) { items.push(new Pair(key)); key = undefined; if (char === ',') { next = ':'; continue; } } } if (char === '}') { if (i === cst.items.length - 1) continue; } else if (char === next) { next = ':'; continue; } const msg = `Flow map contains an unexpected ${char}`; const err = new PlainValue$4.YAMLSyntaxError(cst, msg); err.offset = offset; doc.errors.push(err); } else if (item.type === PlainValue$4.Type.BLANK_LINE) { comments.push({ afterKey: !!key, before: items.length }); } else if (item.type === PlainValue$4.Type.COMMENT) { checkFlowCommentSpace(doc.errors, item); comments.push({ afterKey: !!key, before: items.length, comment: item.comment }); } else if (key === undefined) { if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map')); key = resolveNode(doc, item); } else { if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); items.push(new Pair(key, resolveNode(doc, item))); key = undefined; explicitKey = false; } } checkFlowCollectionEnd(doc.errors, cst); if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } function resolveSeq$3(doc, cst) { if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) { const msg = `A ${cst.type} node cannot be resolved as a sequence`; doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg)); return null; } const { comments, items } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); const seq = new YAMLSeq(); seq.items = items; resolveComments(seq, comments); if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn)); } cst.resolved = seq; return seq; } function resolveBlockSeqItems(doc, cst) { const comments = []; const items = []; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; switch (item.type) { case PlainValue$4.Type.BLANK_LINE: comments.push({ before: items.length }); break; case PlainValue$4.Type.COMMENT: comments.push({ comment: item.comment, before: items.length }); break; case PlainValue$4.Type.SEQ_ITEM: if (item.error) doc.errors.push(item.error); items.push(resolveNode(doc, item.node)); if (item.hasProps) { const msg = 'Sequence items cannot have tags or anchors before the - indicator'; doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); } break; default: if (item.error) doc.errors.push(item.error); doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); } } return { comments, items }; } function resolveFlowSeqItems(doc, cst) { const comments = []; const items = []; let explicitKey = false; let key = undefined; let keyStart = null; let next = '['; let prevItem = null; for (let i = 0; i < cst.items.length; ++i) { const item = cst.items[i]; if (typeof item.char === 'string') { const { char, offset } = item; if (char !== ':' && (explicitKey || key !== undefined)) { if (explicitKey && key === undefined) key = next ? items.pop() : null; items.push(new Pair(key)); explicitKey = false; key = undefined; keyStart = null; } if (char === next) { next = null; } else if (!next && char === '?') { explicitKey = true; } else if (next !== '[' && char === ':' && key === undefined) { if (next === ',') { key = items.pop(); if (key instanceof Pair) { const msg = 'Chaining flow sequence pairs is invalid'; const err = new PlainValue$4.YAMLSemanticError(cst, msg); err.offset = offset; doc.errors.push(err); } if (!explicitKey && typeof keyStart === 'number') { const keyEnd = item.range ? item.range.start : item.offset; if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); const { src } = prevItem.context; for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg)); break; } } } else { key = null; } keyStart = null; explicitKey = false; next = null; } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { const msg = `Flow sequence contains an unexpected ${char}`; const err = new PlainValue$4.YAMLSyntaxError(cst, msg); err.offset = offset; doc.errors.push(err); } } else if (item.type === PlainValue$4.Type.BLANK_LINE) { comments.push({ before: items.length }); } else if (item.type === PlainValue$4.Type.COMMENT) { checkFlowCommentSpace(doc.errors, item); comments.push({ comment: item.comment, before: items.length }); } else { if (next) { const msg = `Expected a ${next} in flow sequence`; doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg)); } const value = resolveNode(doc, item); if (key === undefined) { items.push(value); prevItem = item; } else { items.push(new Pair(key, value)); key = undefined; } keyStart = item.range.start; next = ','; } } checkFlowCollectionEnd(doc.errors, cst); if (key !== undefined) items.push(new Pair(key)); return { comments, items }; } resolveSeqD03cb037.Alias = Alias; resolveSeqD03cb037.Collection = Collection; resolveSeqD03cb037.Merge = Merge; resolveSeqD03cb037.Node = Node$1; resolveSeqD03cb037.Pair = Pair; resolveSeqD03cb037.Scalar = Scalar; resolveSeqD03cb037.YAMLMap = YAMLMap; resolveSeqD03cb037.YAMLSeq = YAMLSeq; resolveSeqD03cb037.addComment = addComment; resolveSeqD03cb037.binaryOptions = binaryOptions; resolveSeqD03cb037.boolOptions = boolOptions; resolveSeqD03cb037.findPair = findPair; resolveSeqD03cb037.intOptions = intOptions; resolveSeqD03cb037.isEmptyPath = isEmptyPath; resolveSeqD03cb037.nullOptions = nullOptions; resolveSeqD03cb037.resolveMap = resolveMap; resolveSeqD03cb037.resolveNode = resolveNode; resolveSeqD03cb037.resolveSeq = resolveSeq$3; resolveSeqD03cb037.resolveString = resolveString; resolveSeqD03cb037.strOptions = strOptions; resolveSeqD03cb037.stringifyNumber = stringifyNumber; resolveSeqD03cb037.stringifyString = stringifyString; resolveSeqD03cb037.toJSON = toJSON; var Schema88e323a7 = {}; var warnings1000a372 = {}; var PlainValue$3 = PlainValueEc8e588e; var resolveSeq$2 = resolveSeqD03cb037; /* global atob, btoa, Buffer */ const binary = { identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array default: false, tag: 'tag:yaml.org,2002:binary', /** * Returns a Buffer in node and an Uint8Array in browsers * * To use the resulting buffer as an image, you'll want to do something like: * * const blob = new Blob([buffer], { type: 'image/jpeg' }) * document.querySelector('#photo').src = URL.createObjectURL(blob) */ resolve: (doc, node) => { const src = resolveSeq$2.resolveString(doc, node); if (typeof Buffer === 'function') { return Buffer.from(src, 'base64'); } else if (typeof atob === 'function') { // On IE 11, atob() can't handle newlines const str = atob(src.replace(/[\n\r]/g, '')); const buffer = new Uint8Array(str.length); for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); return buffer; } else { const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg)); return null; } }, options: resolveSeq$2.binaryOptions, stringify: ({ comment, type, value }, ctx, onComment, onChompKeep) => { let src; if (typeof Buffer === 'function') { src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); } else if (typeof btoa === 'function') { let s = ''; for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); src = btoa(s); } else { throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); } if (!type) type = resolveSeq$2.binaryOptions.defaultType; if (type === PlainValue$3.Type.QUOTE_DOUBLE) { value = src; } else { const { lineWidth } = resolveSeq$2.binaryOptions; const n = Math.ceil(src.length / lineWidth); const lines = new Array(n); for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { lines[i] = src.substr(o, lineWidth); } value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' '); } return resolveSeq$2.stringifyString({ comment, type, value }, ctx, onComment, onChompKeep); } }; function parsePairs(doc, cst) { const seq = resolveSeq$2.resolveSeq(doc, cst); for (let i = 0; i < seq.items.length; ++i) { let item = seq.items[i]; if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) { if (item.items.length > 1) { const msg = 'Each pair must have its own sequence indicator'; throw new PlainValue$3.YAMLSemanticError(cst, msg); } const pair = item.items[0] || new resolveSeq$2.Pair(); if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; item = pair; } seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item); } return seq; } function createPairs(schema, iterable, ctx) { const pairs = new resolveSeq$2.YAMLSeq(schema); pairs.tag = 'tag:yaml.org,2002:pairs'; for (const it of iterable) { let key, value; if (Array.isArray(it)) { if (it.length === 2) { key = it[0]; value = it[1]; } else throw new TypeError(`Expected [key, value] tuple: ${it}`); } else if (it && it instanceof Object) { const keys = Object.keys(it); if (keys.length === 1) { key = keys[0]; value = it[key]; } else throw new TypeError(`Expected { key: value } tuple: ${it}`); } else { key = it; } const pair = schema.createPair(key, value, ctx); pairs.items.push(pair); } return pairs; } const pairs = { default: false, tag: 'tag:yaml.org,2002:pairs', resolve: parsePairs, createNode: createPairs }; class YAMLOMap extends resolveSeq$2.YAMLSeq { constructor() { super(); PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this)); PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this)); PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this)); PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this)); PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this)); this.tag = YAMLOMap.tag; } toJSON(_, ctx) { const map = new Map(); if (ctx && ctx.onCreate) ctx.onCreate(map); for (const pair of this.items) { let key, value; if (pair instanceof resolveSeq$2.Pair) { key = resolveSeq$2.toJSON(pair.key, '', ctx); value = resolveSeq$2.toJSON(pair.value, key, ctx); } else { key = resolveSeq$2.toJSON(pair, '', ctx); } if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); map.set(key, value); } return map; } } PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); function parseOMap(doc, cst) { const pairs = parsePairs(doc, cst); const seenKeys = []; for (const { key } of pairs.items) { if (key instanceof resolveSeq$2.Scalar) { if (seenKeys.includes(key.value)) { const msg = 'Ordered maps must not include duplicate keys'; throw new PlainValue$3.YAMLSemanticError(cst, msg); } else { seenKeys.push(key.value); } } } return Object.assign(new YAMLOMap(), pairs); } function createOMap(schema, iterable, ctx) { const pairs = createPairs(schema, iterable, ctx); const omap = new YAMLOMap(); omap.items = pairs.items; return omap; } const omap = { identify: value => value instanceof Map, nodeClass: YAMLOMap, default: false, tag: 'tag:yaml.org,2002:omap', resolve: parseOMap, createNode: createOMap }; class YAMLSet extends resolveSeq$2.YAMLMap { constructor() { super(); this.tag = YAMLSet.tag; } add(key) { const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key); const prev = resolveSeq$2.findPair(this.items, pair.key); if (!prev) this.items.push(pair); } get(key, keepPair) { const pair = resolveSeq$2.findPair(this.items, key); return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair; } set(key, value) { if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); const prev = resolveSeq$2.findPair(this.items, key); if (prev && !value) { this.items.splice(this.items.indexOf(prev), 1); } else if (!prev && value) { this.items.push(new resolveSeq$2.Pair(key)); } } toJSON(_, ctx) { return super.toJSON(_, ctx, Set); } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); } } PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); function parseSet(doc, cst) { const map = resolveSeq$2.resolveMap(doc, cst); if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values'); return Object.assign(new YAMLSet(), map); } function createSet(schema, iterable, ctx) { const set = new YAMLSet(); for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); return set; } const set = { identify: value => value instanceof Set, nodeClass: YAMLSet, default: false, tag: 'tag:yaml.org,2002:set', resolve: parseSet, createNode: createSet }; const parseSexagesimal = (sign, parts) => { const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); return sign === '-' ? -n : n; }; // hhhh:mm:ss.sss const stringifySexagesimal = ({ value }) => { if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value); let sign = ''; if (value < 0) { sign = '-'; value = Math.abs(value); } const parts = [value % 60]; // seconds, including ms if (value < 60) { parts.unshift(0); // at least one : is required } else { value = Math.round((value - parts[0]) / 60); parts.unshift(value % 60); // minutes if (value >= 60) { value = Math.round((value - parts[0]) / 60); parts.unshift(value); // hours } } return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error ; }; const intTime = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:int', format: 'TIME', test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), stringify: stringifySexagesimal }; const floatTime = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'TIME', test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), stringify: stringifySexagesimal }; const timestamp = { identify: value => value instanceof Date, default: true, tag: 'tag:yaml.org,2002:timestamp', // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part // may be omitted altogether, resulting in a date format. In such a case, the time part is // assumed to be 00:00:00Z (start of day, UTC). test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 ')?' + ')$'), resolve: (str, year, month, day, hour, minute, second, millisec, tz) => { if (millisec) millisec = (millisec + '00').substr(1, 3); let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); if (tz && tz !== 'Z') { let d = parseSexagesimal(tz[0], tz.slice(1)); if (Math.abs(d) < 30) d *= 60; date -= 60000 * d; } return new Date(date); }, stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') }; /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ function shouldWarn(deprecation) { const env = typeof process !== 'undefined' && process.env || {}; if (deprecation) { if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; return !env.YAML_SILENCE_DEPRECATION_WARNINGS; } if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; return !env.YAML_SILENCE_WARNINGS; } function warn(warning, type) { if (shouldWarn(false)) { const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to // https://github.com/facebook/jest/issues/2549 if (emit) emit(warning, type);else { // eslint-disable-next-line no-console console.warn(type ? `${type}: ${warning}` : warning); } } } function warnFileDeprecation(filename) { if (shouldWarn(true)) { const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); } } const warned = {}; function warnOptionDeprecation(name, alternative) { if (!warned[name] && shouldWarn(true)) { warned[name] = true; let msg = `The option '${name}' will be removed in a future release`; msg += alternative ? `, use '${alternative}' instead.` : '.'; warn(msg, 'DeprecationWarning'); } } warnings1000a372.binary = binary; warnings1000a372.floatTime = floatTime; warnings1000a372.intTime = intTime; warnings1000a372.omap = omap; warnings1000a372.pairs = pairs; warnings1000a372.set = set; warnings1000a372.timestamp = timestamp; warnings1000a372.warn = warn; warnings1000a372.warnFileDeprecation = warnFileDeprecation; warnings1000a372.warnOptionDeprecation = warnOptionDeprecation; var PlainValue$2 = PlainValueEc8e588e; var resolveSeq$1 = resolveSeqD03cb037; var warnings$1 = warnings1000a372; function createMap(schema, obj, ctx) { const map = new resolveSeq$1.YAMLMap(schema); if (obj instanceof Map) { for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); } else if (obj && typeof obj === 'object') { for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); } if (typeof schema.sortMapEntries === 'function') { map.items.sort(schema.sortMapEntries); } return map; } const map$1 = { createNode: createMap, default: true, nodeClass: resolveSeq$1.YAMLMap, tag: 'tag:yaml.org,2002:map', resolve: resolveSeq$1.resolveMap }; function createSeq(schema, obj, ctx) { const seq = new resolveSeq$1.YAMLSeq(schema); if (obj && obj[Symbol.iterator]) { for (const it of obj) { const v = schema.createNode(it, ctx.wrapScalars, null, ctx); seq.items.push(v); } } return seq; } const seq = { createNode: createSeq, default: true, nodeClass: resolveSeq$1.YAMLSeq, tag: 'tag:yaml.org,2002:seq', resolve: resolveSeq$1.resolveSeq }; const string = { identify: value => typeof value === 'string', default: true, tag: 'tag:yaml.org,2002:str', resolve: resolveSeq$1.resolveString, stringify(item, ctx, onComment, onChompKeep) { ctx = Object.assign({ actualString: true }, ctx); return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep); }, options: resolveSeq$1.strOptions }; const failsafe = [map$1, seq, string]; /* global BigInt */ const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); function intStringify$1(node, radix, prefix) { const { value } = node; if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix); return resolveSeq$1.stringifyNumber(node); } const nullObj = { identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => null, options: resolveSeq$1.nullOptions, stringify: () => resolveSeq$1.nullOptions.nullStr }; const boolObj = { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, resolve: str => str[0] === 't' || str[0] === 'T', options: resolveSeq$1.boolOptions, stringify: ({ value }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr }; const octObj = { identify: value => intIdentify$2(value) && value >= 0, default: true, tag: 'tag:yaml.org,2002:int', format: 'OCT', test: /^0o([0-7]+)$/, resolve: (str, oct) => intResolve$1(str, oct, 8), options: resolveSeq$1.intOptions, stringify: node => intStringify$1(node, 8, '0o') }; const intObj = { identify: intIdentify$2, default: true, tag: 'tag:yaml.org,2002:int', test: /^[-+]?[0-9]+$/, resolve: str => intResolve$1(str, str, 10), options: resolveSeq$1.intOptions, stringify: resolveSeq$1.stringifyNumber }; const hexObj = { identify: value => intIdentify$2(value) && value >= 0, default: true, tag: 'tag:yaml.org,2002:int', format: 'HEX', test: /^0x([0-9a-fA-F]+)$/, resolve: (str, hex) => intResolve$1(str, hex, 16), options: resolveSeq$1.intOptions, stringify: node => intStringify$1(node, 16, '0x') }; const nanObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^(?:[-+]?\.inf|(\.nan))$/i, resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: resolveSeq$1.stringifyNumber }; const expObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'EXP', test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, resolve: str => parseFloat(str), stringify: ({ value }) => Number(value).toExponential() }; const floatObj = { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, resolve(str, frac1, frac2) { const frac = frac1 || frac2; const node = new resolveSeq$1.Scalar(parseFloat(str)); if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; return node; }, stringify: resolveSeq$1.stringifyNumber }; const core$2 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); /* global BigInt */ const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); const stringifyJSON = ({ value }) => JSON.stringify(value); const json = [map$1, seq, { identify: value => typeof value === 'string', default: true, tag: 'tag:yaml.org,2002:str', resolve: resolveSeq$1.resolveString, stringify: stringifyJSON }, { identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^null$/, resolve: () => null, stringify: stringifyJSON }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^true|false$/, resolve: str => str === 'true', stringify: stringifyJSON }, { identify: intIdentify$1, default: true, tag: 'tag:yaml.org,2002:int', test: /^-?(?:0|[1-9][0-9]*)$/, resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, resolve: str => parseFloat(str), stringify: stringifyJSON }]; json.scalarFallback = str => { throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); }; /* global BigInt */ const boolStringify = ({ value }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr; const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); function intResolve(sign, src, radix) { let str = src.replace(/_/g, ''); if (resolveSeq$1.intOptions.asBigInt) { switch (radix) { case 2: str = `0b${str}`; break; case 8: str = `0o${str}`; break; case 16: str = `0x${str}`; break; } const n = BigInt(str); return sign === '-' ? BigInt(-1) * n : n; } const n = parseInt(str, radix); return sign === '-' ? -1 * n : n; } function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value)) { const str = value.toString(radix); return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; } return resolveSeq$1.stringifyNumber(node); } const yaml11 = failsafe.concat([{ identify: value => value == null, createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null, default: true, tag: 'tag:yaml.org,2002:null', test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => null, options: resolveSeq$1.nullOptions, stringify: () => resolveSeq$1.nullOptions.nullStr }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, resolve: () => true, options: resolveSeq$1.boolOptions, stringify: boolStringify }, { identify: value => typeof value === 'boolean', default: true, tag: 'tag:yaml.org,2002:bool', test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, resolve: () => false, options: resolveSeq$1.boolOptions, stringify: boolStringify }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'BIN', test: /^([-+]?)0b([0-1_]+)$/, resolve: (str, sign, bin) => intResolve(sign, bin, 2), stringify: node => intStringify(node, 2, '0b') }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'OCT', test: /^([-+]?)0([0-7_]+)$/, resolve: (str, sign, oct) => intResolve(sign, oct, 8), stringify: node => intStringify(node, 8, '0') }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', test: /^([-+]?)([0-9][0-9_]*)$/, resolve: (str, sign, abs) => intResolve(sign, abs, 10), stringify: resolveSeq$1.stringifyNumber }, { identify: intIdentify, default: true, tag: 'tag:yaml.org,2002:int', format: 'HEX', test: /^([-+]?)0x([0-9a-fA-F_]+)$/, resolve: (str, sign, hex) => intResolve(sign, hex, 16), stringify: node => intStringify(node, 16, '0x') }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^(?:[-+]?\.inf|(\.nan))$/i, resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: resolveSeq$1.stringifyNumber }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', format: 'EXP', test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, resolve: str => parseFloat(str.replace(/_/g, '')), stringify: ({ value }) => Number(value).toExponential() }, { identify: value => typeof value === 'number', default: true, tag: 'tag:yaml.org,2002:float', test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, resolve(str, frac) { const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, ''))); if (frac) { const f = frac.replace(/_/g, ''); if (f[f.length - 1] === '0') node.minFractionDigits = f.length; } return node; }, stringify: resolveSeq$1.stringifyNumber }], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp); const schemas = { core: core$2, failsafe, json, yaml11 }; const tags = { binary: warnings$1.binary, bool: boolObj, float: floatObj, floatExp: expObj, floatNaN: nanObj, floatTime: warnings$1.floatTime, int: intObj, intHex: hexObj, intOct: octObj, intTime: warnings$1.intTime, map: map$1, null: nullObj, omap: warnings$1.omap, pairs: warnings$1.pairs, seq, set: warnings$1.set, timestamp: warnings$1.timestamp }; function findTagObject(value, tagName, tags) { if (tagName) { const match = tags.filter(t => t.tag === tagName); const tagObj = match.find(t => !t.format) || match[0]; if (!tagObj) throw new Error(`Tag ${tagName} not found`); return tagObj; } // TODO: deprecate/remove class check return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); } function createNode$1(value, tagName, ctx) { if (value instanceof resolveSeq$1.Node) return value; const { defaultPrefix, onTagObj, prevObjects, schema, wrapScalars } = ctx; if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); let tagObj = findTagObject(value, tagName, schema.tags); if (!tagObj) { if (typeof value.toJSON === 'function') value = value.toJSON(); if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value; tagObj = value instanceof Map ? map$1 : value[Symbol.iterator] ? seq : map$1; } if (onTagObj) { onTagObj(tagObj); delete ctx.onTagObj; } // Detect duplicate references to the same object & use Alias nodes for all // after first. The `obj` wrapper allows for circular references to resolve. const obj = { value: undefined, node: undefined }; if (value && typeof value === 'object' && prevObjects) { const prev = prevObjects.get(value); if (prev) { const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller ctx.aliasNodes.push(alias); // defined along with prevObjects return alias; } obj.value = value; prevObjects.set(value, obj); } obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value; if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName; return obj.node; } function getSchemaTags(schemas, knownTags, customTags, schemaId) { let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' if (!tags) { const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); } if (Array.isArray(customTags)) { for (const tag of customTags) tags = tags.concat(tag); } else if (typeof customTags === 'function') { tags = customTags(tags.slice()); } for (let i = 0; i < tags.length; ++i) { const tag = tags[i]; if (typeof tag === 'string') { const tagObj = knownTags[tag]; if (!tagObj) { const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); } tags[i] = tagObj; } } return tags; } const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; class Schema$2 { // TODO: remove in v2 // TODO: remove in v2 constructor({ customTags, merge, schema, sortMapEntries, tags: deprecatedCustomTags }) { this.merge = !!merge; this.name = schema; this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags'); this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); } createNode(value, wrapScalars, tagName, ctx) { const baseCtx = { defaultPrefix: Schema$2.defaultPrefix, schema: this, wrapScalars }; const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; return createNode$1(value, tagName, createCtx); } createPair(key, value, ctx) { if (!ctx) ctx = { wrapScalars: true }; const k = this.createNode(key, ctx.wrapScalars, null, ctx); const v = this.createNode(value, ctx.wrapScalars, null, ctx); return new resolveSeq$1.Pair(k, v); } } PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix); PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags); Schema88e323a7.Schema = Schema$2; var PlainValue$1 = PlainValueEc8e588e; var resolveSeq = resolveSeqD03cb037; var Schema$1 = Schema88e323a7; const defaultOptions$1 = { anchorPrefix: 'a', customTags: null, indent: 2, indentSeq: true, keepCstNodes: false, keepNodeTypes: true, keepBlobsInJSON: true, mapAsMap: false, maxAliasCount: 100, prettyErrors: false, // TODO Set true in v2 simpleKeys: false, version: '1.2' }; const scalarOptions = { get binary() { return resolveSeq.binaryOptions; }, set binary(opt) { Object.assign(resolveSeq.binaryOptions, opt); }, get bool() { return resolveSeq.boolOptions; }, set bool(opt) { Object.assign(resolveSeq.boolOptions, opt); }, get int() { return resolveSeq.intOptions; }, set int(opt) { Object.assign(resolveSeq.intOptions, opt); }, get null() { return resolveSeq.nullOptions; }, set null(opt) { Object.assign(resolveSeq.nullOptions, opt); }, get str() { return resolveSeq.strOptions; }, set str(opt) { Object.assign(resolveSeq.strOptions, opt); } }; const documentOptions = { '1.0': { schema: 'yaml-1.1', merge: true, tagPrefixes: [{ handle: '!', prefix: PlainValue$1.defaultTagPrefix }, { handle: '!!', prefix: 'tag:private.yaml.org,2002:' }] }, 1.1: { schema: 'yaml-1.1', merge: true, tagPrefixes: [{ handle: '!', prefix: '!' }, { handle: '!!', prefix: PlainValue$1.defaultTagPrefix }] }, 1.2: { schema: 'core', merge: false, tagPrefixes: [{ handle: '!', prefix: '!' }, { handle: '!!', prefix: PlainValue$1.defaultTagPrefix }] } }; function stringifyTag(doc, tag) { if ((doc.version || doc.options.version) === '1.0') { const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); if (priv) return '!' + priv[1]; const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; } let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); if (!p) { const dtp = doc.getDefaults().tagPrefixes; p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); } if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ '!': '%21', ',': '%2C', '[': '%5B', ']': '%5D', '{': '%7B', '}': '%7D' })[ch]); return p.handle + suffix; } function getTagObject(tags, item) { if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; if (item.tag) { const match = tags.filter(t => t.tag === item.tag); if (match.length > 0) return match.find(t => t.format === item.format) || match[0]; } let tagObj, obj; if (item instanceof resolveSeq.Scalar) { obj = item.value; // TODO: deprecate/remove class check const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format); } else { obj = item; tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass); } if (!tagObj) { const name = obj && obj.constructor ? obj.constructor.name : typeof obj; throw new Error(`Tag not resolved for ${name} value`); } return tagObj; } // needs to be called before value stringifier to allow for circular anchor refs function stringifyProps(node, tagObj, { anchors, doc }) { const props = []; const anchor = doc.anchors.getName(node); if (anchor) { anchors[anchor] = node; props.push(`&${anchor}`); } if (node.tag) { props.push(stringifyTag(doc, node.tag)); } else if (!tagObj.default) { props.push(stringifyTag(doc, tagObj.tag)); } return props.join(' '); } function stringify$2(item, ctx, onComment, onChompKeep) { const { anchors, schema } = ctx.doc; let tagObj; if (!(item instanceof resolveSeq.Node)) { const createCtx = { aliasNodes: [], onTagObj: o => tagObj = o, prevObjects: new Map() }; item = schema.createNode(item, true, null, createCtx); for (const alias of createCtx.aliasNodes) { alias.source = alias.source.node; let name = anchors.getName(alias.source); if (!name) { name = anchors.newName(); anchors.map[name] = alias.source; } } } if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); if (!tagObj) tagObj = getTagObject(schema.tags, item); const props = stringifyProps(item, tagObj, ctx); if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); if (!props) return str; return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; } class Anchors { static validAnchorNode(node) { return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; } constructor(prefix) { PlainValue$1._defineProperty(this, "map", Object.create(null)); this.prefix = prefix; } createAlias(node, name) { this.setAnchor(node, name); return new resolveSeq.Alias(node); } createMergePair(...sources) { const merge = new resolveSeq.Merge(); merge.value.items = sources.map(s => { if (s instanceof resolveSeq.Alias) { if (s.source instanceof resolveSeq.YAMLMap) return s; } else if (s instanceof resolveSeq.YAMLMap) { return this.createAlias(s); } throw new Error('Merge sources must be Map nodes or their Aliases'); }); return merge; } getName(node) { const { map } = this; return Object.keys(map).find(a => map[a] === node); } getNames() { return Object.keys(this.map); } getNode(name) { return this.map[name]; } newName(prefix) { if (!prefix) prefix = this.prefix; const names = Object.keys(this.map); for (let i = 1; true; ++i) { const name = `${prefix}${i}`; if (!names.includes(name)) return name; } } // During parsing, map & aliases contain CST nodes resolveNodes() { const { map, _cstAliases } = this; Object.keys(map).forEach(a => { map[a] = map[a].resolved; }); _cstAliases.forEach(a => { a.source = a.source.resolved; }); delete this._cstAliases; } setAnchor(node, name) { if (node != null && !Anchors.validAnchorNode(node)) { throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); } if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { throw new Error('Anchor names must not contain whitespace or control characters'); } const { map } = this; const prev = node && Object.keys(map).find(a => map[a] === node); if (prev) { if (!name) { return prev; } else if (prev !== name) { delete map[prev]; map[name] = node; } } else { if (!name) { if (!node) return null; name = this.newName(); } map[name] = node; } return name; } } const visit$1 = (node, tags) => { if (node && typeof node === 'object') { const { tag } = node; if (node instanceof resolveSeq.Collection) { if (tag) tags[tag] = true; node.items.forEach(n => visit$1(n, tags)); } else if (node instanceof resolveSeq.Pair) { visit$1(node.key, tags); visit$1(node.value, tags); } else if (node instanceof resolveSeq.Scalar) { if (tag) tags[tag] = true; } } return tags; }; const listTagNames = node => Object.keys(visit$1(node, {})); function parseContents(doc, contents) { const comments = { before: [], after: [] }; let body = undefined; let spaceBefore = false; for (const node of contents) { if (node.valueRange) { if (body !== undefined) { const msg = 'Document contains trailing content not separated by a ... or --- line'; doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg)); break; } const res = resolveSeq.resolveNode(doc, node); if (spaceBefore) { res.spaceBefore = true; spaceBefore = false; } body = res; } else if (node.comment !== null) { const cc = body === undefined ? comments.before : comments.after; cc.push(node.comment); } else if (node.type === PlainValue$1.Type.BLANK_LINE) { spaceBefore = true; if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { // space-separated comments at start are parsed as document comments doc.commentBefore = comments.before.join('\n'); comments.before = []; } } } doc.contents = body || null; if (!body) { doc.comment = comments.before.concat(comments.after).join('\n') || null; } else { const cb = comments.before.join('\n'); if (cb) { const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; } doc.comment = comments.after.join('\n') || null; } } function resolveTagDirective({ tagPrefixes }, directive) { const [handle, prefix] = directive.parameters; if (!handle || !prefix) { const msg = 'Insufficient parameters given for %TAG directive'; throw new PlainValue$1.YAMLSemanticError(directive, msg); } if (tagPrefixes.some(p => p.handle === handle)) { const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; throw new PlainValue$1.YAMLSemanticError(directive, msg); } return { handle, prefix }; } function resolveYamlDirective(doc, directive) { let [version] = directive.parameters; if (directive.name === 'YAML:1.0') version = '1.0'; if (!version) { const msg = 'Insufficient parameters given for %YAML directive'; throw new PlainValue$1.YAMLSemanticError(directive, msg); } if (!documentOptions[version]) { const v0 = doc.version || doc.options.version; const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); } return version; } function parseDirectives(doc, directives, prevDoc) { const directiveComments = []; let hasDirectives = false; for (const directive of directives) { const { comment, name } = directive; switch (name) { case 'TAG': try { doc.tagPrefixes.push(resolveTagDirective(doc, directive)); } catch (error) { doc.errors.push(error); } hasDirectives = true; break; case 'YAML': case 'YAML:1.0': if (doc.version) { const msg = 'The %YAML directive must only be given at most once per document.'; doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg)); } try { doc.version = resolveYamlDirective(doc, directive); } catch (error) { doc.errors.push(error); } hasDirectives = true; break; default: if (name) { const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg)); } } if (comment) directiveComments.push(comment); } if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { const copyTagPrefix = ({ handle, prefix }) => ({ handle, prefix }); doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); doc.version = prevDoc.version; } doc.commentBefore = directiveComments.join('\n') || null; } function assertCollection(contents) { if (contents instanceof resolveSeq.Collection) return true; throw new Error('Expected a YAML collection as document contents'); } class Document$2 { constructor(options) { this.anchors = new Anchors(options.anchorPrefix); this.commentBefore = null; this.comment = null; this.contents = null; this.directivesEndMarker = null; this.errors = []; this.options = options; this.schema = null; this.tagPrefixes = []; this.version = null; this.warnings = []; } add(value) { assertCollection(this.contents); return this.contents.add(value); } addIn(path, value) { assertCollection(this.contents); this.contents.addIn(path, value); } delete(key) { assertCollection(this.contents); return this.contents.delete(key); } deleteIn(path) { if (resolveSeq.isEmptyPath(path)) { if (this.contents == null) return false; this.contents = null; return true; } assertCollection(this.contents); return this.contents.deleteIn(path); } getDefaults() { return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {}; } get(key, keepScalar) { return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; } getIn(path, keepScalar) { if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; } has(key) { return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; } hasIn(path) { if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; } set(key, value) { assertCollection(this.contents); this.contents.set(key, value); } setIn(path, value) { if (resolveSeq.isEmptyPath(path)) this.contents = value;else { assertCollection(this.contents); this.contents.setIn(path, value); } } setSchema(id, customTags) { if (!id && !customTags && this.schema) return; if (typeof id === 'number') id = id.toFixed(1); if (id === '1.0' || id === '1.1' || id === '1.2') { if (this.version) this.version = id;else this.options.version = id; delete this.options.schema; } else if (id && typeof id === 'string') { this.options.schema = id; } if (Array.isArray(customTags)) this.options.customTags = customTags; const opt = Object.assign({}, this.getDefaults(), this.options); this.schema = new Schema$1.Schema(opt); } parse(node, prevDoc) { if (this.options.keepCstNodes) this.cstNode = node; if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; const { directives = [], contents = [], directivesEndMarker, error, valueRange } = node; if (error) { if (!error.source) error.source = this; this.errors.push(error); } parseDirectives(this, directives, prevDoc); if (directivesEndMarker) this.directivesEndMarker = true; this.range = valueRange ? [valueRange.start, valueRange.end] : null; this.setSchema(); this.anchors._cstAliases = []; parseContents(this, contents); this.anchors.resolveNodes(); if (this.options.prettyErrors) { for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty(); for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty(); } return this; } listNonDefaultTags() { return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0); } setTagPrefix(handle, prefix) { if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); if (prefix) { const prev = this.tagPrefixes.find(p => p.handle === handle); if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ handle, prefix }); } else { this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); } } toJSON(arg, onAnchor) { const { keepBlobsInJSON, mapAsMap, maxAliasCount } = this.options; const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); const ctx = { doc: this, indentStep: ' ', keep, mapAsMap: keep && !!mapAsMap, maxAliasCount, stringify: stringify$2 // Requiring directly in Pair would create circular dependencies }; const anchorNames = Object.keys(this.anchors.map); if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { alias: [], aliasCount: 0, count: 1 }])); const res = resolveSeq.toJSON(this.contents, arg, ctx); if (typeof onAnchor === 'function' && ctx.anchors) for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); return res; } toString() { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); const indentSize = this.options.indent; if (!Number.isInteger(indentSize) || indentSize <= 0) { const s = JSON.stringify(indentSize); throw new Error(`"indent" option must be a positive integer, not ${s}`); } this.setSchema(); const lines = []; let hasDirectives = false; if (this.version) { let vd = '%YAML 1.2'; if (this.schema.name === 'yaml-1.1') { if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; } lines.push(vd); hasDirectives = true; } const tagNames = this.listNonDefaultTags(); this.tagPrefixes.forEach(({ handle, prefix }) => { if (tagNames.some(t => t.indexOf(prefix) === 0)) { lines.push(`%TAG ${handle} ${prefix}`); hasDirectives = true; } }); if (hasDirectives || this.directivesEndMarker) lines.push('---'); if (this.commentBefore) { if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); lines.unshift(this.commentBefore.replace(/^/gm, '#')); } const ctx = { anchors: Object.create(null), doc: this, indent: '', indentStep: ' '.repeat(indentSize), stringify: stringify$2 // Requiring directly in nodes would create circular dependencies }; let chompKeep = false; let contentComment = null; if (this.contents) { if (this.contents instanceof resolveSeq.Node) { if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment ctx.forceBlockIndent = !!this.comment; contentComment = this.contents.comment; } const onChompKeep = contentComment ? null : () => chompKeep = true; const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep); lines.push(resolveSeq.addComment(body, '', contentComment)); } else if (this.contents !== undefined) { lines.push(stringify$2(this.contents, ctx)); } if (this.comment) { if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); lines.push(this.comment.replace(/^/gm, '#')); } return lines.join('\n') + '\n'; } } PlainValue$1._defineProperty(Document$2, "defaults", documentOptions); Document9b4560a1.Document = Document$2; Document9b4560a1.defaultOptions = defaultOptions$1; Document9b4560a1.scalarOptions = scalarOptions; var parseCst = parseCst$1; var Document$1 = Document9b4560a1; var Schema = Schema88e323a7; var PlainValue = PlainValueEc8e588e; var warnings = warnings1000a372; function createNode(value, wrapScalars = true, tag) { if (tag === undefined && typeof wrapScalars === 'string') { tag = wrapScalars; wrapScalars = true; } const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); const schema = new Schema.Schema(options); return schema.createNode(value, wrapScalars, tag); } class Document extends Document$1.Document { constructor(options) { super(Object.assign({}, Document$1.defaultOptions, options)); } } function parseAllDocuments(src, options) { const stream = []; let prev; for (const cstDoc of parseCst.parse(src)) { const doc = new Document(options); doc.parse(cstDoc, prev); stream.push(doc); prev = doc; } return stream; } function parseDocument(src, options) { const cst = parseCst.parse(src); const doc = new Document(options).parse(cst[0]); if (cst.length > 1) { const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); } return doc; } function parse$g(src, options) { const doc = parseDocument(src, options); doc.warnings.forEach(warning => warnings.warn(warning)); if (doc.errors.length > 0) throw doc.errors[0]; return doc.toJSON(); } function stringify$1(value, options) { const doc = new Document(options); doc.contents = value; return String(doc); } const YAML = { createNode, defaultOptions: Document$1.defaultOptions, Document, parse: parse$g, parseAllDocuments, parseCST: parseCst.parse, parseDocument, scalarOptions: Document$1.scalarOptions, stringify: stringify$1 }; dist$1.YAML = YAML; var yaml$1 = dist$1.YAML; var importCwd = {exports: {}}; var importFrom$1 = {exports: {}}; var resolveFrom$2 = {exports: {}}; const path$i = path__default; const Module = require$$0__default$3; const fs$i = fs__default; const resolveFrom$1 = (fromDirectory, moduleId, silent) => { if (typeof fromDirectory !== 'string') { throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``); } if (typeof moduleId !== 'string') { throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``); } try { fromDirectory = fs$i.realpathSync(fromDirectory); } catch (error) { if (error.code === 'ENOENT') { fromDirectory = path$i.resolve(fromDirectory); } else if (silent) { return; } else { throw error; } } const fromFile = path$i.join(fromDirectory, 'noop.js'); const resolveFileName = () => Module._resolveFilename(moduleId, { id: fromFile, filename: fromFile, paths: Module._nodeModulePaths(fromDirectory) }); if (silent) { try { return resolveFileName(); } catch (error) { return; } } return resolveFileName(); }; resolveFrom$2.exports = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId); resolveFrom$2.exports.silent = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId, true); const resolveFrom = resolveFrom$2.exports; importFrom$1.exports = (fromDirectory, moduleId) => eval('require')(resolveFrom(fromDirectory, moduleId)); importFrom$1.exports.silent = (fromDirectory, moduleId) => { try { return eval('require')(resolveFrom(fromDirectory, moduleId)); } catch (_) {} }; const importFrom = importFrom$1.exports; importCwd.exports = moduleId => importFrom(process.cwd(), moduleId); importCwd.exports.silent = moduleId => importFrom.silent(process.cwd(), moduleId); const req$1 = importCwd.exports; /** * Load Options * * @private * @method options * * @param {Object} config PostCSS Config * * @return {Object} options PostCSS Options */ const options = (config, file) => { if (config.parser && typeof config.parser === 'string') { try { config.parser = req$1(config.parser); } catch (err) { throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`) } } if (config.syntax && typeof config.syntax === 'string') { try { config.syntax = req$1(config.syntax); } catch (err) { throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`) } } if (config.stringifier && typeof config.stringifier === 'string') { try { config.stringifier = req$1(config.stringifier); } catch (err) { throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`) } } if (config.plugins) { delete config.plugins; } return config }; var options_1 = options; const req = importCwd.exports; /** * Plugin Loader * * @private * @method load * * @param {String} plugin PostCSS Plugin Name * @param {Object} options PostCSS Plugin Options * * @return {Function} PostCSS Plugin */ const load$1 = (plugin, options, file) => { try { if ( options === null || options === undefined || Object.keys(options).length === 0 ) { return req(plugin) } else { return req(plugin)(options) } } catch (err) { throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`) } }; /** * Load Plugins * * @private * @method plugins * * @param {Object} config PostCSS Config Plugins * * @return {Array} plugins PostCSS Plugins */ const plugins = (config, file) => { let plugins = []; if (Array.isArray(config.plugins)) { plugins = config.plugins.filter(Boolean); } else { plugins = Object.keys(config.plugins) .filter((plugin) => { return config.plugins[plugin] !== false ? plugin : '' }) .map((plugin) => { return load$1(plugin, config.plugins[plugin], file) }); } if (plugins.length && plugins.length > 0) { plugins.forEach((plugin, i) => { if (plugin.default) { plugin = plugin.default; } if (plugin.postcss === true) { plugin = plugin(); } else if (plugin.postcss) { plugin = plugin.postcss; } if ( // eslint-disable-next-line !( (typeof plugin === 'object' && Array.isArray(plugin.plugins)) || (typeof plugin === 'object' && plugin.postcssPlugin) || (typeof plugin === 'function') ) ) { throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`) } }); } return plugins }; var plugins_1 = plugins; const resolve$2 = path__default.resolve; const config$1 = dist$2; const yaml = yaml$1; const loadOptions = options_1; const loadPlugins = plugins_1; /* istanbul ignore next */ const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj }; /** * Process the result from cosmiconfig * * @param {Object} ctx Config Context * @param {Object} result Cosmiconfig result * * @return {Object} PostCSS Config */ const processResult = (ctx, result) => { const file = result.filepath || ''; let config = interopRequireDefault(result.config).default || {}; if (typeof config === 'function') { config = config(ctx); } else { config = Object.assign({}, config, ctx); } if (!config.plugins) { config.plugins = []; } return { plugins: loadPlugins(config, file), options: loadOptions(config, file), file: file } }; /** * Builds the Config Context * * @param {Object} ctx Config Context * * @return {Object} Config Context */ const createContext = (ctx) => { /** * @type {Object} * * @prop {String} cwd=process.cwd() Config search start location * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined` */ ctx = Object.assign({ cwd: process.cwd(), env: process.env.NODE_ENV }, ctx); if (!ctx.env) { process.env.NODE_ENV = 'development'; } return ctx }; const addTypeScriptLoader = (options = {}, loader) => { const moduleName = 'postcss'; return { ...options, searchPlaces: [ ...(options.searchPlaces || []), 'package.json', `.${moduleName}rc`, `.${moduleName}rc.json`, `.${moduleName}rc.yaml`, `.${moduleName}rc.yml`, `.${moduleName}rc.ts`, `.${moduleName}rc.js`, `.${moduleName}rc.cjs`, `${moduleName}.config.ts`, `${moduleName}.config.js`, `${moduleName}.config.cjs` ], loaders: { ...options.loaders, '.yaml': (filepath, content) => yaml.parse(content), '.yml': (filepath, content) => yaml.parse(content), '.ts': loader } } }; const withTypeScriptLoader = (rcFunc) => { return (ctx, path, options) => { return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => { let registerer = { enabled () {} }; try { // Register TypeScript compiler instance registerer = require('ts-node').register(); return commonjsRequire(configFile) } catch (err) { if (err.code === 'MODULE_NOT_FOUND') { throw new Error( `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}` ) } throw err } finally { registerer.enabled(false); } })) } }; /** * Load Config * * @method rc * * @param {Object} ctx Config Context * @param {String} path Config Path * @param {Object} options Config Options * * @return {Promise} config PostCSS Config */ const rc = withTypeScriptLoader((ctx, path, options) => { /** * @type {Object} The full Config Context */ ctx = createContext(ctx); /** * @type {String} `process.cwd()` */ path = path ? resolve$2(path) : process.cwd(); return config$1.lilconfig('postcss', options) .search(path) .then((result) => { if (!result) { throw new Error(`No PostCSS Config found in: ${path}`) } return processResult(ctx, result) }) }); rc.sync = withTypeScriptLoader((ctx, path, options) => { /** * @type {Object} The full Config Context */ ctx = createContext(ctx); /** * @type {String} `process.cwd()` */ path = path ? resolve$2(path) : process.cwd(); const result = config$1.lilconfigSync('postcss', options).search(path); if (!result) { throw new Error(`No PostCSS Config found in: ${path}`) } return processResult(ctx, result) }); /** * Autoload Config for PostCSS * * @author Michael Ciniawsky @michael-ciniawsky * @license MIT * * @module postcss-load-config * @version 2.1.0 * * @requires comsiconfig * @requires ./options * @requires ./plugins */ var src$1 = rc; // Helper since Typescript can't detect readonly arrays with Array.isArray function isArray$3(arg) { return Array.isArray(arg); } function ensureArray$1(thing) { if (isArray$3(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePath$3 = function normalizePath(filename) { return filename.split(path$t.win32.sep).join(path$t.posix.sep); }; function getMatcherString$1(id, resolutionBase) { if (resolutionBase === false || path$t.isAbsolute(id) || id.startsWith('*')) { return id; } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath$3(path$t.resolve(resolutionBase || '')) // escape all possible (posix + win) path characters that might interfere with regex .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); // Note that we use posix.join because: // 1. the basePath has been normalized to use / // 2. the incoming glob (id) matcher, also uses / // otherwise Node will force backslash (\) on windows return path$t.posix.join(basePath, id); } const createFilter$1 = function createFilter(include, exclude, options) { const resolutionBase = options && options.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { // this refactor is a tad overly verbose but makes for easy debugging const pattern = getMatcherString$1(id, resolutionBase); const fn = picomatch$3(pattern, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray$1(include).map(getMatcher); const excludeMatchers = ensureArray$1(exclude).map(getMatcher); return function result(id) { if (typeof id !== 'string') return false; if (/\0/.test(id)) return false; const pathId = normalizePath$3(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher = excludeMatchers[i]; if (matcher.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher = includeMatchers[i]; if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; const reservedWords$2 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; const forbiddenIdentifiers$1 = new Set(`${reservedWords$2} ${builtins$1}`.split(' ')); forbiddenIdentifiers$1.add(''); const makeLegalIdentifier$1 = function makeLegalIdentifier(str) { let identifier = str .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) .replace(/[^$_a-zA-Z0-9]/g, '_'); if (/\d/.test(identifier[0]) || forbiddenIdentifiers$1.has(identifier)) { identifier = `_${identifier}`; } return identifier || '_'; }; function stringify(obj) { return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); } function serializeArray(arr, indent, baseIndent) { let output = '['; const separator = indent ? `\n${baseIndent}${indent}` : ''; for (let i = 0; i < arr.length; i++) { const key = arr[i]; output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ''}]`; } function serializeObject(obj, indent, baseIndent) { let output = '{'; const separator = indent ? `\n${baseIndent}${indent}` : ''; const entries = Object.entries(obj); for (let i = 0; i < entries.length; i++) { const [key, value] = entries[i]; const stringKey = makeLegalIdentifier$1(key) === key ? key : stringify(key); output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`; } return `${output}${indent ? `\n${baseIndent}` : ''}}`; } function serialize(obj, indent, baseIndent) { if (obj === Infinity) return 'Infinity'; if (obj === -Infinity) return '-Infinity'; if (obj === 0 && 1 / obj === -Infinity) return '-0'; if (obj instanceof Date) return `new Date(${obj.getTime()})`; if (obj instanceof RegExp) return obj.toString(); if (obj !== obj) return 'NaN'; // eslint-disable-line no-self-compare if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent); if (obj === null) return 'null'; if (typeof obj === 'object') return serializeObject(obj, indent, baseIndent); return stringify(obj); } const dataToEsm = function dataToEsm(data, options = {}) { const t = options.compact ? '' : 'indent' in options ? options.indent : '\t'; const _ = options.compact ? '' : ' '; const n = options.compact ? '' : '\n'; const declarationType = options.preferConst ? 'const' : 'var'; if (options.namedExports === false || typeof data !== 'object' || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) { const code = serialize(data, options.compact ? null : t, ''); const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape return `export default${magic}${code};`; } let namedExportCode = ''; const defaultExportRows = []; for (const [key, value] of Object.entries(data)) { if (key === makeLegalIdentifier$1(key)) { if (options.objectShorthand) defaultExportRows.push(key); else defaultExportRows.push(`${key}:${_}${key}`); namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; } else { defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); } } return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; }; const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`; const cssLangRE = new RegExp(cssLangs); const cssModuleRE = new RegExp(`\\.module${cssLangs}`); const directRequestRE = /(\?|&)direct\b/; const commonjsProxyRE = /\?commonjs-proxy/; const inlineRE = /(\?|&)inline\b/; const usedRE = /(\?|&)used\b/; const isCSSRequest = (request) => cssLangRE.test(request); const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request); const isDirectRequest = (request) => directRequestRE.test(request); const cssModulesCache = new WeakMap(); const chunkToEmittedCssFileMap = new WeakMap(); const removedPureCssFilesCache = new WeakMap(); const postcssConfigCache = new WeakMap(); /** * Plugin applied before user plugins */ function cssPlugin(config) { let server; let moduleCache; const resolveUrl = config.createResolver({ preferRelative: true, tryIndex: false, extensions: [] }); const atImportResolvers = createCSSResolvers(config); return { name: 'vite:css', configureServer(_server) { server = _server; }, buildStart() { // Ensure a new cache for every build (i.e. rebuilding in watch mode) moduleCache = new Map(); cssModulesCache.set(config, moduleCache); removedPureCssFilesCache.set(config, new Map()); }, async transform(raw, id) { if (!isCSSRequest(id) || commonjsProxyRE.test(id)) { return; } const urlReplacer = async (url, importer) => { if (checkPublicFile(url, config)) { return config.base + url.slice(1); } const resolved = await resolveUrl(url, importer); if (resolved) { return fileToUrl(resolved, config, this); } return url; }; const { code: css, modules, deps } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server); if (modules) { moduleCache.set(id, modules); } // track deps for build watch mode if (config.command === 'build' && config.build.watch && deps) { for (const file of deps) { this.addWatchFile(file); } } // dev if (server) { // server only logic for handling CSS @import dependency hmr const { moduleGraph } = server; const thisModule = moduleGraph.getModuleById(id); if (thisModule) { // CSS modules cannot self-accept since it exports values const isSelfAccepting = !modules && !inlineRE.test(id); if (deps) { // record deps in the module graph so edits to @import css can trigger // main import to hot update const depModules = new Set(); for (const file of deps) { depModules.add(isCSSRequest(file) ? moduleGraph.createFileOnlyEntry(file) : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace(config.base, '/'))); } moduleGraph.updateModuleInfo(thisModule, depModules, // The root CSS proxy module is self-accepting and should not // have an explicit accept list new Set(), isSelfAccepting); for (const file of deps) { this.addWatchFile(file); } } else { thisModule.isSelfAccepting = isSelfAccepting; } } } return { code: css, // TODO CSS source map map: { mappings: '' } }; } }; } /** * Plugin applied after user plugins */ function cssPostPlugin(config) { // styles initialization in buildStart causes a styling loss in watch const styles = new Map(); let pureCssChunks; // when there are multiple rollup outputs and extracting CSS, only emit once, // since output formats have no effect on the generated CSS. let outputToExtractedCSSMap; let hasEmitted = false; return { name: 'vite:css-post', buildStart() { // Ensure new caches for every build (i.e. rebuilding in watch mode) pureCssChunks = new Set(); outputToExtractedCSSMap = new Map(); hasEmitted = false; }, async transform(css, id, ssr) { if (!isCSSRequest(id) || commonjsProxyRE.test(id)) { return; } const inlined = inlineRE.test(id); const modules = cssModulesCache.get(config).get(id); const modulesCode = modules && dataToEsm(modules, { namedExports: true, preferConst: true }); if (config.command === 'serve') { if (isDirectCSSRequest(id)) { return css; } else { // server only if (ssr) { return modulesCode || `export default ${JSON.stringify(css)}`; } if (inlined) { return `export default ${JSON.stringify(css)}`; } return [ `import { updateStyle, removeStyle } from ${JSON.stringify(path__default.posix.join(config.base, CLIENT_PUBLIC_PATH))}`, `const id = ${JSON.stringify(id)}`, `const css = ${JSON.stringify(css)}`, `updateStyle(id, css)`, // css modules exports change on edit so it can't self accept `${modulesCode || `import.meta.hot.accept()\nexport default css`}`, `import.meta.hot.prune(() => removeStyle(id))` ].join('\n'); } } // build CSS handling ---------------------------------------------------- // record css if (!inlined) { styles.set(id, css); } return { code: modulesCode || (usedRE.test(id) ? `export default ${JSON.stringify(inlined ? await minifyCSS(css, config) : css)}` : `export default ''`), map: { mappings: '' }, // avoid the css module from being tree-shaken so that we can retrieve // it in renderChunk() moduleSideEffects: inlined ? false : 'no-treeshake' }; }, async renderChunk(code, chunk, opts) { let chunkCSS = ''; let isPureCssChunk = true; const ids = Object.keys(chunk.modules); for (const id of ids) { if (!isCSSRequest(id) || cssModuleRE.test(id) || commonjsProxyRE.test(id)) { isPureCssChunk = false; } if (styles.has(id)) { chunkCSS += styles.get(id); } } if (!chunkCSS) { return null; } // resolve asset URL placeholders to their built file URLs and perform // minification if necessary const processChunkCSS = async (css, { inlined, minify }) => { // replace asset url references with resolved url. const isRelativeBase = config.base === '' || config.base.startsWith('.'); css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => { const filename = getAssetFilename(fileHash, config) + postfix; registerAssetToChunk(chunk, filename); if (!isRelativeBase || inlined) { // absolute base or relative base but inlined (injected as style tag into // index.html) use the base as-is return config.base + filename; } else { // relative base + extracted CSS - asset file will be in the same dir return `./${path__default.posix.basename(filename)}`; } }); // only external @imports should exist at this point - and they need to // be hoisted to the top of the CSS chunk per spec (#1845) if (css.includes('@import')) { css = await hoistAtImports(css); } if (minify && config.build.minify) { css = await minifyCSS(css, config); } return css; }; if (config.build.cssCodeSplit) { if (isPureCssChunk) { // this is a shared CSS-only chunk that is empty. pureCssChunks.add(chunk.fileName); } if (opts.format === 'es' || opts.format === 'cjs') { chunkCSS = await processChunkCSS(chunkCSS, { inlined: false, minify: true }); // emit corresponding css file const fileHandle = this.emitFile({ name: chunk.name + '.css', type: 'asset', source: chunkCSS }); chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)])); } else if (!config.build.ssr) { // legacy build, inline css chunkCSS = await processChunkCSS(chunkCSS, { inlined: true, minify: true }); const style = `__vite_style__`; const injectCode = `var ${style} = document.createElement('style');` + `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` + `document.head.appendChild(${style});`; if (config.build.sourcemap) { const s = new MagicString(code); s.prepend(injectCode); return { code: s.toString(), map: s.generateMap({ hires: true }) }; } else { return { code: injectCode + code }; } } } else { // non-split extracted CSS will be minified together chunkCSS = await processChunkCSS(chunkCSS, { inlined: false, minify: false }); outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS); } return null; }, async generateBundle(opts, bundle) { // remove empty css chunks and their imports if (pureCssChunks.size) { const emptyChunkFiles = [...pureCssChunks] .map((file) => path__default.basename(file)) .join('|') .replace(/\./g, '\\.'); const emptyChunkRE = new RegExp(opts.format === 'es' ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?` : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g'); for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === 'chunk') { // remove pure css chunk from other chunk's imports, // and also register the emitted CSS files under the importer // chunks instead. chunk.imports = chunk.imports.filter((file) => { if (pureCssChunks.has(file)) { const css = chunkToEmittedCssFileMap.get(bundle[file]); if (css) { let existing = chunkToEmittedCssFileMap.get(chunk); if (!existing) { existing = new Set(); } css.forEach((file) => existing.add(file)); chunkToEmittedCssFileMap.set(chunk, existing); } return false; } return true; }); chunk.code = chunk.code.replace(emptyChunkRE, // remove css import while preserving source map location (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`); } } const removedPureCssFiles = removedPureCssFilesCache.get(config); pureCssChunks.forEach((fileName) => { removedPureCssFiles.set(fileName, bundle[fileName]); delete bundle[fileName]; }); } let extractedCss = outputToExtractedCSSMap.get(opts); if (extractedCss && !hasEmitted) { hasEmitted = true; // minify css if (config.build.minify) { extractedCss = await minifyCSS(extractedCss, config); } this.emitFile({ name: 'style.css', type: 'asset', source: extractedCss }); } } }; } function createCSSResolvers(config) { let cssResolve; let sassResolve; let lessResolve; return { get css() { return (cssResolve || (cssResolve = config.createResolver({ extensions: ['.css'], mainFields: ['style'], tryIndex: false, preferRelative: true }))); }, get sass() { return (sassResolve || (sassResolve = config.createResolver({ extensions: ['.scss', '.sass', '.css'], mainFields: ['sass', 'style'], tryIndex: true, tryPrefix: '_', preferRelative: true }))); }, get less() { return (lessResolve || (lessResolve = config.createResolver({ extensions: ['.less', '.css'], mainFields: ['less', 'style'], tryIndex: false, preferRelative: true }))); } }; } function getCssResolversKeys(resolvers) { return Object.keys(resolvers); } async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) { var _a; const { modules: modulesOptions, preprocessorOptions } = config.css || {}; const isModule = modulesOptions !== false && cssModuleRE.test(id); // although at serve time it can work without processing, we do need to // crawl them in order to register watch dependencies. const needInlineImport = code.includes('@import'); const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code); const postcssConfig = await resolvePostcssConfig(config); const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1]; // 1. plain css that needs no processing if (lang === 'css' && !postcssConfig && !isModule && !needInlineImport && !hasUrl) { return { code }; } let map; let modules; const deps = new Set(); // 2. pre-processors: sass etc. if (isPreProcessor(lang)) { const preProcessor = preProcessors[lang]; let opts = (preprocessorOptions && preprocessorOptions[lang]) || {}; // support @import from node dependencies by default switch (lang) { case "scss" /* scss */: case "sass" /* sass */: opts = { includePaths: ['node_modules'], alias: config.resolve.alias, ...opts }; break; case "less" /* less */: case "styl" /* styl */: case "stylus" /* stylus */: opts = { paths: ['node_modules'], alias: config.resolve.alias, ...opts }; } // important: set this for relative import resolving opts.filename = cleanUrl(id); const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers); if (preprocessResult.errors.length) { throw preprocessResult.errors[0]; } code = preprocessResult.code; map = preprocessResult.map; if (preprocessResult.deps) { preprocessResult.deps.forEach((dep) => { // sometimes sass registers the file itself as a dep if (normalizePath$4(dep) !== normalizePath$4(opts.filename)) { deps.add(dep); } }); } } // 3. postcss const postcssOptions = (postcssConfig && postcssConfig.options) || {}; const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : []; if (needInlineImport) { postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-e39b05d6.js'); }).then(function (n) { return n.index; })).default({ async resolve(id, basedir) { const resolved = await atImportResolvers.css(id, path__default.join(basedir, '*')); if (resolved) { return path__default.resolve(resolved); } return id; } })); } postcssPlugins.push(UrlRewritePostcssPlugin({ replacer: urlReplacer })); if (isModule) { postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-c98c5b6d.js'); }).then(function (n) { return n.index; })).default({ ...modulesOptions, getJSON(cssFileName, _modules, outputFileName) { modules = _modules; if (modulesOptions && typeof modulesOptions.getJSON === 'function') { modulesOptions.getJSON(cssFileName, _modules, outputFileName); } }, async resolve(id) { for (const key of getCssResolversKeys(atImportResolvers)) { const resolved = await atImportResolvers[key](id); if (resolved) { return path__default.resolve(resolved); } } return id; } })); } if (!postcssPlugins.length) { return { code, map }; } // postcss is an unbundled dep and should be lazy imported const postcssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })) .default(postcssPlugins) .process(code, { ...postcssOptions, to: id, from: id, map: { inline: false, annotation: false, prev: map } }); // record CSS dependencies from @imports for (const message of postcssResult.messages) { if (message.type === 'dependency') { deps.add(message.file); } else if (message.type === 'dir-dependency') { // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies const { dir, glob: globPattern = '**' } = message; const pattern = normalizePath$4(path__default.resolve(path__default.dirname(id), dir)) + `/` + globPattern; const files = out.sync(pattern, { ignore: ['**/node_modules/**'] }); for (let i = 0; i < files.length; i++) { deps.add(files[i]); } if (server) { // register glob importers so we can trigger updates on file add/remove if (!(id in server._globImporters)) { server._globImporters[id] = { module: server.moduleGraph.getModuleById(id), importGlobs: [] }; } server._globImporters[id].importGlobs.push({ base: config.root, pattern }); } } else if (message.type === 'warning') { let msg = `[vite:css] ${message.text}`; if (message.line && message.column) { msg += `\n${generateCodeFrame(code, { line: message.line, column: message.column })}`; } config.logger.warn(source.yellow(msg)); } } return { ast: postcssResult, code: postcssResult.css, map: postcssResult.map, modules, deps }; } async function resolvePostcssConfig(config) { var _a; let result = postcssConfigCache.get(config); if (result !== undefined) { return result; } // inline postcss config via vite config const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss; if (isObject$3(inlineOptions)) { const options = { ...inlineOptions }; delete options.plugins; result = { options, plugins: inlineOptions.plugins || [] }; } else { try { const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root; // @ts-ignore result = await src$1({}, searchPath); } catch (e) { if (!/No PostCSS Config found/.test(e.message)) { throw e; } result = null; } } postcssConfigCache.set(config, result); return result; } // https://drafts.csswg.org/css-syntax-3/#identifier-code-point const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/; const cssImageSetRE = /image-set\(([^)]+)\)/; const UrlRewritePostcssPlugin = (opts) => { if (!opts) { throw new Error('base or replace is required'); } return { postcssPlugin: 'vite-url-rewrite', Once(root) { const promises = []; root.walkDecls((declaration) => { const isCssUrl = cssUrlRE.test(declaration.value); const isCssImageSet = cssImageSetRE.test(declaration.value); if (isCssUrl || isCssImageSet) { const replacerForDeclaration = (rawUrl) => { var _a; const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file; return opts.replacer(rawUrl, importer); }; const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet; promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => { declaration.value = url; })); } }); if (promises.length) { return Promise.all(promises); } } }; }; UrlRewritePostcssPlugin.postcss = true; function rewriteCssUrls(css, replacer) { return asyncReplace(css, cssUrlRE, async (match) => { const [matched, rawUrl] = match; return await doUrlReplace(rawUrl, matched, replacer); }); } function rewriteCssImageSet(css, replacer) { return asyncReplace(css, cssImageSetRE, async (match) => { const [matched, rawUrl] = match; const url = await processSrcSet(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer)); return `image-set(${url})`; }); } async function doUrlReplace(rawUrl, matched, replacer) { let wrap = ''; const first = rawUrl[0]; if (first === `"` || first === `'`) { wrap = first; rawUrl = rawUrl.slice(1, -1); } if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) { return matched; } return `url(${wrap}${await replacer(rawUrl)}${wrap})`; } async function minifyCSS(css, config) { const { code, warnings } = await esbuild.transform(css, { loader: 'css', minify: true, target: config.build.cssTarget || undefined }); if (warnings.length) { const msgs = await esbuild.formatMessages(warnings, { kind: 'warning' }); config.logger.warn(source.yellow(`warnings when minifying css:\n${msgs.join('\n')}`)); } return code; } // #1845 // CSS @import can only appear at top of the file. We need to hoist all @import // to top when multiple files are concatenated. async function hoistAtImports(css) { const postcss = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); }); return (await postcss.default([AtImportHoistPlugin]).process(css)).css; } const AtImportHoistPlugin = () => { return { postcssPlugin: 'vite-hoist-at-imports', Once(root) { const imports = []; root.walkAtRules((rule) => { if (rule.name === 'import') { // record in reverse so that can simply prepend to preserve order imports.unshift(rule); } }); imports.forEach((i) => root.prepend(i)); } }; }; AtImportHoistPlugin.postcss = true; const loadedPreprocessors = {}; function loadPreprocessor(lang, root) { var _a, _b; if (lang in loadedPreprocessors) { return loadedPreprocessors[lang]; } try { // Search for the preprocessor in the root directory first, and fall back // to the default require paths. const fallbackPaths = ((_b = (_a = require.resolve).paths) === null || _b === void 0 ? void 0 : _b.call(_a, lang)) || []; const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] }); return (loadedPreprocessors[lang] = require(resolved)); } catch (e) { throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`); } } // .scss/.sass processor const scss = async (source, root, options, resolvers) => { const render = loadPreprocessor("sass" /* sass */, root).render; const internalImporter = (url, importer, done) => { resolvers.sass(url, importer).then((resolved) => { if (resolved) { rebaseUrls(resolved, options.filename, options.alias) .then(done) .catch(done); } else { done(null); } }); }; const importer = [internalImporter]; if (options.importer) { Array.isArray(options.importer) ? importer.push(...options.importer) : importer.push(options.importer); } const finalOptions = { ...options, data: await getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, importer }; try { const result = await new Promise((resolve, reject) => { render(finalOptions, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); const deps = result.stats.includedFiles; return { code: result.css.toString(), errors: [], deps }; } catch (e) { // normalize SASS error e.id = e.file; e.frame = e.formatted; return { code: '', errors: [e], deps: [] }; } }; const sass = (source, root, options, aliasResolver) => scss(source, root, { ...options, indentedSyntax: true }, aliasResolver); /** * relative url() inside \@imported sass and less files must be rebased to use * root file as base. */ async function rebaseUrls(file, rootFile, alias) { file = path__default.resolve(file); // ensure os-specific flashes // in the same dir, no need to rebase const fileDir = path__default.dirname(file); const rootDir = path__default.dirname(rootFile); if (fileDir === rootDir) { return { file }; } // no url() const content = fs__default.readFileSync(file, 'utf-8'); if (!cssUrlRE.test(content)) { return { file }; } const rebased = await rewriteCssUrls(content, (url) => { if (url.startsWith('/')) return url; // match alias, no need to rewrite for (const { find } of alias) { const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url); if (matches) { return url; } } const absolute = path__default.resolve(fileDir, url); const relative = path__default.relative(rootDir, absolute); return normalizePath$4(relative); }); return { file, contents: rebased }; } // .less const less = async (source, root, options, resolvers) => { const nodeLess = loadPreprocessor("less" /* less */, root); const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers); source = await getSource(source, options.filename, options.additionalData); let result; try { result = await nodeLess.render(source, { ...options, plugins: [viteResolverPlugin, ...(options.plugins || [])] }); } catch (e) { const error = e; // normalize error info const normalizedError = new Error(error.message || error.type); normalizedError.loc = { file: error.filename || options.filename, line: error.line, column: error.column }; return { code: '', errors: [normalizedError], deps: [] }; } return { code: result.css.toString(), deps: result.imports, errors: [] }; }; /** * Less manager, lazy initialized */ let ViteLessManager; function createViteLessPlugin(less, rootFile, alias, resolvers) { if (!ViteLessManager) { ViteLessManager = class ViteManager extends less.FileManager { constructor(rootFile, resolvers, alias) { super(); this.rootFile = rootFile; this.resolvers = resolvers; this.alias = alias; } supports() { return true; } supportsSync() { return false; } async loadFile(filename, dir, opts, env) { const resolved = await this.resolvers.less(filename, path__default.join(dir, '*')); if (resolved) { const result = await rebaseUrls(resolved, this.rootFile, this.alias); let contents; if (result && 'contents' in result) { contents = result.contents; } else { contents = fs__default.readFileSync(resolved, 'utf-8'); } return { filename: path__default.resolve(resolved), contents }; } else { return super.loadFile(filename, dir, opts, env); } } }; } return { install(_, pluginManager) { pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias)); }, minVersion: [3, 0, 0] }; } // .styl const styl = async (source, root, options) => { var _a; const nodeStylus = loadPreprocessor("stylus" /* stylus */, root); // Get source with preprocessor options.additionalData. Make sure a new line separator // is added to avoid any render error, as added stylus content may not have semi-colon separators source = await getSource(source, options.filename, options.additionalData, '\n'); // Get preprocessor options.imports dependencies as stylus // does not return them with its builtin `.deps()` method const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path__default.resolve(dep)); try { const ref = nodeStylus(source, options); // if (map) ref.set('sourcemap', { inline: false, comment: false }) const result = ref.render(); // Concat imports deps with computed deps const deps = [...ref.deps(), ...importsDeps]; return { code: result, errors: [], deps }; } catch (e) { return { code: '', errors: [e], deps: [] }; } }; function getSource(source, filename, additionalData, sep = '') { if (!additionalData) return source; if (typeof additionalData === 'function') { return additionalData(source, filename); } return additionalData + sep + source; } const preProcessors = Object.freeze({ ["less" /* less */]: less, ["sass" /* sass */]: sass, ["scss" /* scss */]: scss, ["styl" /* styl */]: styl, ["stylus" /* stylus */]: styl }); function isPreProcessor(lang) { return lang && lang in preProcessors; } /* es-module-lexer 0.9.2 */ const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$f(E,g="@"){if(!B)return init.then(()=>parse$f(E));const I=E.length+1,w=(B.__heap_base.value||B.__heap_base)+4*I-B.memory.buffer.byteLength;w>0&&B.memory.grow(Math.ceil(w/65536));const D=B.sa(I-1);if((A?C:Q)(E,new Uint16Array(B.memory.buffer,D,I)),!B.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,B.e()).split("\n").length}:${B.e()-E.lastIndexOf("\n",B.e()-1)}`),{idx:B.e()});const k=[],L=[];for(;B.ri();){const A=B.is(),Q=B.ie(),C=B.ai(),g=B.id(),I=B.ss(),w=B.se();let D;B.ip()&&(D=o(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),k.push({n:D,s:A,e:Q,ss:I,se:w,d:g,a:C});}for(;B.re();){const A=E.slice(B.es(),B.ee()),Q=A[0];L.push('"'===Q||"'"===Q?o(A):A);}function o(A){try{return (0, eval)(A)}catch(A){}}return [k,L,!!B.f()]}function Q(A,Q){const C=A.length;let B=0;for(;B>>8;}}function C(A,Q){const C=A.length;let B=0;for(;BA.charCodeAt(0)))).then(WebAssembly.instantiate).then(({exports:A})=>{B=A;});var E; async function transformImportGlob(source, pos, importer, importIndex, root, normalizeUrl, preload = true) { const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager'; const isEagerDefault = isEager && source.slice(pos + 21, pos + 28) === 'Default'; const err = (msg) => { const e = new Error(`Invalid glob import syntax: ${msg}`); e.pos = pos; return e; }; importer = cleanUrl(importer); const importerBasename = path__default.basename(importer); let [pattern, endIndex] = lexGlobPattern(source, pos); if (!pattern.startsWith('.') && !pattern.startsWith('/')) { throw err(`pattern must start with "." or "/" (relative to project root)`); } let base; let parentDepth = 0; const isAbsolute = pattern.startsWith('/'); if (isAbsolute) { base = path__default.resolve(root); pattern = pattern.slice(1); } else { base = path__default.dirname(importer); while (pattern.startsWith('../')) { pattern = pattern.slice(3); base = path__default.resolve(base, '../'); parentDepth++; } if (pattern.startsWith('./')) { pattern = pattern.slice(2); } } const files = out.sync(pattern, { cwd: base, ignore: ['**/node_modules/**'] }); const imports = []; let importsString = ``; let entries = ``; for (let i = 0; i < files.length; i++) { // skip importer itself if (files[i] === importerBasename) continue; const file = isAbsolute ? `/${files[i]}` : parentDepth ? `${'../'.repeat(parentDepth)}${files[i]}` : `./${files[i]}`; let importee = file; if (normalizeUrl) { [importee] = await normalizeUrl(file, pos); } imports.push(importee); const identifier = `__glob_${importIndex}_${i}`; if (isEager) { importsString += `import ${isEagerDefault ? `` : `* as `}${identifier} from ${JSON.stringify(importee)};`; entries += ` ${JSON.stringify(file)}: ${identifier},`; } else { let imp = `import(${JSON.stringify(importee)})`; if (!normalizeUrl && preload) { imp = `(${isModernFlag}` + `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` + `: ${imp})`; } entries += ` ${JSON.stringify(file)}: () => ${imp},`; } } return { imports, importsString, exp: `{${entries}}`, endIndex, isEager, pattern, base }; } function lexGlobPattern(code, pos) { let state = 0 /* inCall */; let pattern = ''; let i = code.indexOf(`(`, pos) + 1; outer: for (; i < code.length; i++) { const char = code.charAt(i); switch (state) { case 0 /* inCall */: if (char === `'`) { state = 1 /* inSingleQuoteString */; } else if (char === `"`) { state = 2 /* inDoubleQuoteString */; } else if (char === '`') { state = 3 /* inTemplateString */; } else if (/\s/.test(char)) { continue; } else { error$3(i); } break; case 1 /* inSingleQuoteString */: if (char === `'`) { break outer; } else { pattern += char; } break; case 2 /* inDoubleQuoteString */: if (char === `"`) { break outer; } else { pattern += char; } break; case 3 /* inTemplateString */: if (char === '`') { break outer; } else { pattern += char; } break; default: throw new Error('unknown import.meta.glob lexer state'); } } return [pattern, code.indexOf(`)`, i) + 1]; } function error$3(pos) { const err = new Error(`import.meta.glob() can only accept string literals.`); err.pos = pos; throw err; } /** * A flag for injected helpers. This flag will be set to `false` if the output * target is not native es - so that injected helper logic can be conditionally * dropped. */ const isModernFlag = `__VITE_IS_MODERN__`; const preloadMethod = `__vitePreload`; const preloadMarker = `__VITE_PRELOAD__`; const preloadBaseMarker = `__VITE_PRELOAD_BASE__`; const preloadHelperId = 'vite/preload-helper'; const preloadMarkerRE = new RegExp(`"${preloadMarker}"`, 'g'); /** * Helper for preloading CSS and direct imports of async chunks in parallel to * the async chunk itself. */ function detectScriptRel() { // @ts-ignore const relList = document.createElement('link').relList; // @ts-ignore return relList && relList.supports && relList.supports('modulepreload') ? 'modulepreload' : 'preload'; } function preload(baseModule, deps) { // @ts-ignore if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) { return baseModule(); } return Promise.all(deps.map((dep) => { // @ts-ignore dep = `${base}${dep}`; // @ts-ignore if (dep in seen) return; // @ts-ignore seen[dep] = true; const isCss = dep.endsWith('.css'); const cssSelector = isCss ? '[rel="stylesheet"]' : ''; // @ts-ignore check if the file is already preloaded by SSR markup if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) { return; } // @ts-ignore const link = document.createElement('link'); // @ts-ignore link.rel = isCss ? 'stylesheet' : scriptRel; if (!isCss) { link.as = 'script'; link.crossOrigin = ''; } link.href = dep; // @ts-ignore document.head.appendChild(link); if (isCss) { return new Promise((res, rej) => { link.addEventListener('load', res); link.addEventListener('error', rej); }); } })).then(() => baseModule()); } /** * Build only. During serve this is performed as part of ./importAnalysis. */ function buildImportAnalysisPlugin(config) { const ssr = !!config.build.ssr; const insertPreload = !(ssr || !!config.build.lib); const scriptRel = config.build.polyfillModulePreload ? `'modulepreload'` : `(${detectScriptRel.toString()})()`; const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`; return { name: 'vite:build-import-analysis', resolveId(id) { if (id === preloadHelperId) { return id; } }, load(id) { if (id === preloadHelperId) { return preloadCode.replace(preloadBaseMarker, config.base); } }, async transform(source, importer) { if (importer.includes('node_modules') && !source.includes('import.meta.glob')) { return; } await init; let imports = []; try { imports = parse$f(source)[0]; } catch (e) { this.error(e, e.idx); } if (!imports.length) { return null; } let s; const str = () => s || (s = new MagicString(source)); let needPreloadHelper = false; for (let index = 0; index < imports.length; index++) { const { s: start, e: end, ss: expStart, n: specifier, d: dynamicIndex } = imports[index]; // import.meta.glob if (source.slice(start, end) === 'import.meta' && source.slice(end, end + 5) === '.glob') { const { importsString, exp, endIndex, isEager } = await transformImportGlob(source, start, importer, index, config.root, undefined, insertPreload); str().prepend(importsString); str().overwrite(expStart, endIndex, exp); if (!isEager) { needPreloadHelper = true; } continue; } if (dynamicIndex > -1 && insertPreload) { needPreloadHelper = true; const dynamicEnd = source.indexOf(`)`, end) + 1; const original = source.slice(dynamicIndex, dynamicEnd); const replacement = `${preloadMethod}(() => ${original},${isModernFlag}?"${preloadMarker}":void 0)`; str().overwrite(dynamicIndex, dynamicEnd, replacement); } // Differentiate CSS imports that use the default export from those that // do not by injecting a ?used query - this allows us to avoid including // the CSS string when unnecessary (esbuild has trouble treeshaking // them) if (specifier && isCSSRequest(specifier) && source.slice(expStart, start).includes('from') && // edge case for package names ending with .css (e.g normalize.css) !(bareImportRE.test(specifier) && !specifier.includes('/'))) { const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`); str().overwrite(start, end, dynamicIndex > -1 ? `'${url}'` : url); } } if (needPreloadHelper && insertPreload && !source.includes(`const ${preloadMethod} =`)) { str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`); } if (s) { return { code: s.toString(), map: config.build.sourcemap ? s.generateMap({ hires: true }) : null }; } }, renderChunk(code, _, { format }) { // make sure we only perform the preload logic in modern builds. if (code.indexOf(isModernFlag) > -1) { const re = new RegExp(isModernFlag, 'g'); const isModern = String(format === 'es'); if (config.build.sourcemap) { const s = new MagicString(code); let match; while ((match = re.exec(code))) { s.overwrite(match.index, match.index + isModernFlag.length, isModern); } return { code: s.toString(), map: s.generateMap({ hires: true }) }; } else { return code.replace(re, isModern); } } return null; }, generateBundle({ format }, bundle) { if (format !== 'es' || ssr) { return; } for (const file in bundle) { const chunk = bundle[file]; // can't use chunk.dynamicImports.length here since some modules e.g. // dynamic import to constant json may get inlined. if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) { const code = chunk.code; let imports; try { imports = parse$f(code)[0].filter((i) => i.d > -1); } catch (e) { this.error(e, e.idx); } if (imports.length) { const s = new MagicString(code); for (let index = 0; index < imports.length; index++) { const { s: start, e: end, d: dynamicIndex } = imports[index]; // check the chunk being imported const url = code.slice(start, end); const deps = new Set(); let hasRemovedPureCssChunk = false; if (url[0] === `"` && url[url.length - 1] === `"`) { const ownerFilename = chunk.fileName; // literal import - trace direct imports and add to deps const analyzed = new Set(); const addDeps = (filename) => { if (filename === ownerFilename) return; if (analyzed.has(filename)) return; analyzed.add(filename); const chunk = bundle[filename]; if (chunk) { deps.add(chunk.fileName); const cssFiles = chunkToEmittedCssFileMap.get(chunk); if (cssFiles) { cssFiles.forEach((file) => { deps.add(file); }); } chunk.imports.forEach(addDeps); } else { const removedPureCssFiles = removedPureCssFilesCache.get(config); const chunk = removedPureCssFiles.get(filename); if (chunk) { const cssFiles = chunkToEmittedCssFileMap.get(chunk); if (cssFiles && cssFiles.size > 0) { cssFiles.forEach((file) => { deps.add(file); }); hasRemovedPureCssChunk = true; } s.overwrite(dynamicIndex, end + 1, 'Promise.resolve({})'); } } }; const normalizedFile = path__default.posix.join(path__default.posix.dirname(chunk.fileName), url.slice(1, -1)); addDeps(normalizedFile); } let markPos = code.indexOf(preloadMarker, end); // fix issue #3051 if (markPos === -1 && imports.length === 1) { markPos = code.indexOf(preloadMarker); } if (markPos > 0) { s.overwrite(markPos - 1, markPos + preloadMarker.length + 1, // the dep list includes the main chunk, so only need to // preload when there are actual other deps. deps.size > 1 || // main chunk is removed (hasRemovedPureCssChunk && deps.size > 0) ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]` : `[]`); } } chunk.code = s.toString(); // TODO source map } // there may still be markers due to inlined dynamic imports, remove // all the markers regardless chunk.code = chunk.code.replace(preloadMarkerRE, 'void 0'); } } } }; } const modulePreloadPolyfillId = 'vite/modulepreload-polyfill'; function modulePreloadPolyfillPlugin(config) { const skip = config.build.ssr; let polyfillString; return { name: 'vite:modulepreload-polyfill', resolveId(id) { if (id === modulePreloadPolyfillId) { return id; } }, load(id) { if (id === modulePreloadPolyfillId) { if (skip) { return ''; } if (!polyfillString) { polyfillString = `const p = ${polyfill.toString()};` + `${isModernFlag}&&p();`; } return polyfillString; } } }; } function polyfill() { const relList = document.createElement('link').relList; if (relList && relList.supports && relList.supports('modulepreload')) { return; } for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { processPreload(link); } new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type !== 'childList') { continue; } for (const node of mutation.addedNodes) { if (node.tagName === 'LINK' && node.rel === 'modulepreload') processPreload(node); } } }).observe(document, { childList: true, subtree: true }); function getFetchOpts(script) { const fetchOpts = {}; if (script.integrity) fetchOpts.integrity = script.integrity; if (script.referrerpolicy) fetchOpts.referrerPolicy = script.referrerpolicy; if (script.crossorigin === 'use-credentials') fetchOpts.credentials = 'include'; else if (script.crossorigin === 'anonymous') fetchOpts.credentials = 'omit'; else fetchOpts.credentials = 'same-origin'; return fetchOpts; } function processPreload(link) { if (link.ep) // ep marker = processed return; link.ep = true; // prepopulate the load record const fetchOpts = getFetchOpts(link); fetch(link.href, fetchOpts); } } const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/; const isHTMLProxy = (id) => htmlProxyRE.test(id); // HTML Proxy Caches are stored by config -> filePath -> index const htmlProxyMap = new WeakMap(); function htmlInlineScriptProxyPlugin(config) { return { name: 'vite:html-inline-script-proxy', resolveId(id) { if (htmlProxyRE.test(id)) { return id; } }, buildStart() { htmlProxyMap.set(config, new Map()); }, load(id) { const proxyMatch = id.match(htmlProxyRE); if (proxyMatch) { const index = Number(proxyMatch[1]); const file = cleanUrl(id); const url = file.replace(config.root, ''); const result = htmlProxyMap.get(config).get(url)[index]; if (result) { return result; } else { throw new Error(`No matching HTML proxy module found from ${id}`); } } } }; } /** Add script to cache */ function addToHTMLProxyCache(config, filePath, index, code) { if (!htmlProxyMap.get(config)) { htmlProxyMap.set(config, new Map()); } if (!htmlProxyMap.get(config).get(filePath)) { htmlProxyMap.get(config).set(filePath, []); } htmlProxyMap.get(config).get(filePath)[index] = code; } // this extends the config in @vue/compiler-sfc with const assetAttrsConfig = { link: ['href'], video: ['src', 'poster'], source: ['src', 'srcset'], img: ['src', 'srcset'], image: ['xlink:href', 'href'], use: ['xlink:href', 'href'] }; const isAsyncScriptMap = new WeakMap(); async function traverseHtml(html, filePath, visitor) { // lazy load compiler const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-66b16601.js'); }).then(function (n) { return n.compilerDom_cjs; }); // @vue/compiler-core doesn't like lowercase doctypes html = html.replace(/ url.startsWith('#') || isExternalUrl(url) || isDataUrl(url) || checkPublicFile(url, config); return { name: 'vite:build-html', buildStart() { isAsyncScriptMap.set(config, new Map()); }, async transform(html, id) { if (id.endsWith('.html')) { const publicPath = `/${slash$3(path__default.relative(config.root, id))}`; // pre-transform html = await applyHtmlTransforms(html, preHooks, { path: publicPath, filename: id }); let js = ''; const s = new MagicString(html); const assetUrls = []; let inlineModuleIndex = -1; let everyScriptIsAsync = true; let someScriptsAreAsync = false; let someScriptsAreDefer = false; await traverseHtml(html, id, (node) => { if (node.type !== 1 /* ELEMENT */) { return; } let shouldRemove = false; // script tags if (node.tag === 'script') { const { src, isModule, isAsync } = getScriptInfo(node); const url = src && src.value && src.value.content; if (url && checkPublicFile(url, config)) { // referencing public dir url, prefix with base s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`); } if (isModule) { inlineModuleIndex++; if (url && !isExcludedUrl(url)) { // const filePath = id.replace(config.root, ''); addToHTMLProxyCache(config, filePath, inlineModuleIndex, contents); js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; shouldRemove = true; } everyScriptIsAsync && (everyScriptIsAsync = isAsync); someScriptsAreAsync || (someScriptsAreAsync = isAsync); someScriptsAreDefer || (someScriptsAreDefer = !isAsync); } } // For asset references in index.html, also generate an import // statement for each - this will be handled by the asset plugin const assetAttrs = assetAttrsConfig[node.tag]; if (assetAttrs) { for (const p of node.props) { if (p.type === 6 /* ATTRIBUTE */ && p.value && assetAttrs.includes(p.name)) { const url = p.value.content; if (!isExcludedUrl(url)) { if (node.tag === 'link' && isCSSRequest(url)) { // CSS references, convert to import js += `\nimport ${JSON.stringify(url)}`; shouldRemove = true; } else { assetUrls.push(p); } } else if (checkPublicFile(url, config)) { s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`); } } } } if (shouldRemove) { // remove the script tag from the html. we are going to inject new // ones in the end. s.remove(node.loc.start.offset, node.loc.end.offset); } }); isAsyncScriptMap.get(config).set(id, everyScriptIsAsync); if (someScriptsAreAsync && someScriptsAreDefer) { config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`); } // for each encountered asset url, rewrite original html so that it // references the post-build location. for (const attr of assetUrls) { const value = attr.value; try { const url = attr.name === 'srcset' ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this)) : await urlToBuiltUrl(value.content, id, config, this); s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`); } catch (e) { // #1885 preload may be pointing to urls that do not exist // locally on disk if (e.code !== 'ENOENT') { throw e; } } } processedHtml.set(id, s.toString()); // inject module preload polyfill only when configured and needed if (config.build.polyfillModulePreload && (someScriptsAreAsync || someScriptsAreDefer)) { js = `import "${modulePreloadPolyfillId}";\n${js}`; } return js; } }, async generateBundle(options, bundle) { const analyzedChunk = new Map(); const getImportedChunks = (chunk, seen = new Set()) => { const chunks = []; chunk.imports.forEach((file) => { const importee = bundle[file]; if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) { seen.add(file); // post-order traversal chunks.push(...getImportedChunks(importee, seen)); chunks.push(importee); } }); return chunks; }; const toScriptTag = (chunk, isAsync) => ({ tag: 'script', attrs: { ...(isAsync ? { async: true } : {}), type: 'module', crossorigin: true, src: toPublicPath(chunk.fileName, config) } }); const toPreloadTag = (chunk) => ({ tag: 'link', attrs: { rel: 'modulepreload', href: toPublicPath(chunk.fileName, config) } }); const getCssTagsForChunk = (chunk, seen = new Set()) => { const tags = []; if (!analyzedChunk.has(chunk)) { analyzedChunk.set(chunk, 1); chunk.imports.forEach((file) => { const importee = bundle[file]; if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') { tags.push(...getCssTagsForChunk(importee, seen)); } }); } const cssFiles = chunkToEmittedCssFileMap.get(chunk); if (cssFiles) { cssFiles.forEach((file) => { if (!seen.has(file)) { seen.add(file); tags.push({ tag: 'link', attrs: { rel: 'stylesheet', href: toPublicPath(file, config) } }); } }); } return tags; }; for (const [id, html] of processedHtml) { const isAsync = isAsyncScriptMap.get(config).get(id); // resolve asset url references let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { return config.base + getAssetFilename(fileHash, config) + postfix; }); // find corresponding entry chunk const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' && chunk.isEntry && chunk.facadeModuleId === id); let canInlineEntry = false; // inject chunk asset links if (chunk) { // an entry chunk can be inlined if // - it's an ES module (e.g. not generated by the legacy plugin) // - it contains no meaningful code other than import statements if (options.format === 'es' && isEntirelyImport(chunk.code)) { canInlineEntry = true; } // when not inlined, inject `); } } // elements with [href/src] attrs const assetAttrs = assetAttrsConfig[node.tag]; if (assetAttrs) { for (const p of node.props) { if (p.type === 6 /* ATTRIBUTE */ && p.value && assetAttrs.includes(p.name)) { processNodeUrl(p, s, config, htmlPath, originalUrl); } } } }); html = s.toString(); return { html, tags: [ { tag: 'script', attrs: { type: 'module', src: path__default.posix.join(base, CLIENT_PUBLIC_PATH) }, injectTo: 'head-prepend' } ] }; }; function indexHtmlMiddleware(server) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return async function viteIndexHtmlMiddleware(req, res, next) { if (res.writableEnded) { return next(); } const url = req.url && cleanUrl(req.url); // spa-fallback always redirects to /index.html if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') { const filename = getHtmlFilename(url, server); if (fs__default.existsSync(filename)) { try { let html = fs__default.readFileSync(filename, 'utf-8'); html = await server.transformIndexHtml(url, html, req.originalUrl); return send$1(req, res, html, 'html'); } catch (e) { return next(e); } } } next(); }; } const logTime = createDebugger('vite:time'); function timeMiddleware(root) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function viteTimeMiddleware(req, res, next) { const start = perf_hooks.performance.now(); const end = res.end; res.end = (...args) => { logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); // @ts-ignore return end.call(res, ...args); }; next(); }; } class ModuleNode { constructor(url) { /** * Resolved file system path + query */ this.id = null; this.file = null; this.importers = new Set(); this.importedModules = new Set(); this.acceptedHmrDeps = new Set(); this.isSelfAccepting = false; this.transformResult = null; this.ssrTransformResult = null; this.ssrModule = null; this.lastHMRTimestamp = 0; this.url = url; this.type = isDirectCSSRequest(url) ? 'css' : 'js'; } } function invalidateSSRModule(mod, seen) { if (seen.has(mod)) { return; } seen.add(mod); mod.ssrModule = null; mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)); } class ModuleGraph { constructor(container) { this.urlToModuleMap = new Map(); this.idToModuleMap = new Map(); // a single file may corresponds to multiple modules with different queries this.fileToModulesMap = new Map(); this.safeModulesPath = new Set(); this.container = container; } async getModuleByUrl(rawUrl) { const [url] = await this.resolveUrl(rawUrl); return this.urlToModuleMap.get(url); } getModuleById(id) { return this.idToModuleMap.get(removeTimestampQuery(id)); } getModulesByFile(file) { return this.fileToModulesMap.get(file); } onFileChange(file) { const mods = this.getModulesByFile(file); if (mods) { const seen = new Set(); mods.forEach((mod) => { this.invalidateModule(mod, seen); }); } } invalidateModule(mod, seen = new Set()) { mod.transformResult = null; mod.ssrTransformResult = null; invalidateSSRModule(mod, seen); } invalidateAll() { const seen = new Set(); this.idToModuleMap.forEach((mod) => { this.invalidateModule(mod, seen); }); } /** * Update the module graph based on a module's updated imports information * If there are dependencies that no longer have any importers, they are * returned as a Set. */ async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) { mod.isSelfAccepting = isSelfAccepting; const prevImports = mod.importedModules; const nextImports = (mod.importedModules = new Set()); let noLongerImported; // update import graph for (const imported of importedModules) { const dep = typeof imported === 'string' ? await this.ensureEntryFromUrl(imported) : imported; dep.importers.add(mod); nextImports.add(dep); } // remove the importer from deps that were imported but no longer are. prevImports.forEach((dep) => { if (!nextImports.has(dep)) { dep.importers.delete(mod); if (!dep.importers.size) { (noLongerImported || (noLongerImported = new Set())).add(dep); } } }); // update accepted hmr deps const deps = (mod.acceptedHmrDeps = new Set()); for (const accepted of acceptedModules) { const dep = typeof accepted === 'string' ? await this.ensureEntryFromUrl(accepted) : accepted; deps.add(dep); } return noLongerImported; } async ensureEntryFromUrl(rawUrl) { const [url, resolvedId] = await this.resolveUrl(rawUrl); let mod = this.urlToModuleMap.get(url); if (!mod) { mod = new ModuleNode(url); this.urlToModuleMap.set(url, mod); mod.id = resolvedId; this.idToModuleMap.set(resolvedId, mod); const file = (mod.file = cleanUrl(resolvedId)); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } fileMappedModules.add(mod); } return mod; } // some deps, like a css file referenced via @import, don't have its own // url because they are inlined into the main css import. But they still // need to be represented in the module graph so that they can trigger // hmr in the importing css file. createFileOnlyEntry(file) { file = normalizePath$4(file); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } const url = `${FS_PREFIX}${file}`; for (const m of fileMappedModules) { if (m.url === url || m.id === file) { return m; } } const mod = new ModuleNode(url); mod.file = file; fileMappedModules.add(mod); return mod; } // for incoming urls, it is important to: // 1. remove the HMR timestamp query (?t=xxxx) // 2. resolve its extension so that urls with or without extension all map to // the same module async resolveUrl(url) { var _a; url = removeImportQuery(removeTimestampQuery(url)); const resolvedId = ((_a = (await this.container.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url; const ext = path$t.extname(cleanUrl(resolvedId)); const { pathname, search, hash } = require$$0$8.parse(url); if (ext && !pathname.endsWith(ext)) { url = pathname + ext + (search || '') + (hash || ''); } return [url, resolvedId]; } } const debugHmr = createDebugger('vite:hmr'); const normalizedClientDir = normalizePath$4(CLIENT_DIR); function getShortName(file, root) { return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file; } async function handleHMRUpdate(file, server) { const { ws, config, moduleGraph } = server; const shortFile = getShortName(file, config.root); const isConfig = file === config.configFile; const isConfigDependency = config.configFileDependencies.some((name) => file === path__default.resolve(name)); const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env'); if (isConfig || isConfigDependency || isEnv) { // auto restart server debugHmr(`[config change] ${source.dim(shortFile)}`); config.logger.info(source.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true }); await restartServer(server); return; } debugHmr(`[file change] ${source.dim(shortFile)}`); // (dev only) the client itself cannot be hot updated. if (file.startsWith(normalizedClientDir)) { ws.send({ type: 'full-reload', path: '*' }); return; } const mods = moduleGraph.getModulesByFile(file); // check if any plugin wants to perform custom HMR handling const timestamp = Date.now(); const hmrContext = { file, timestamp, modules: mods ? [...mods] : [], read: () => readModifiedFile(file), server }; for (const plugin of config.plugins) { if (plugin.handleHotUpdate) { const filteredModules = await plugin.handleHotUpdate(hmrContext); if (filteredModules) { hmrContext.modules = filteredModules; } } } if (!hmrContext.modules.length) { // html file cannot be hot updated if (file.endsWith('.html')) { config.logger.info(source.green(`page reload `) + source.dim(shortFile), { clear: true, timestamp: true }); ws.send({ type: 'full-reload', path: config.server.middlewareMode ? '*' : '/' + normalizePath$4(path__default.relative(config.root, file)) }); } else { // loaded but not in the module graph, probably not js debugHmr(`[no modules matched] ${source.dim(shortFile)}`); } return; } updateModules(shortFile, hmrContext.modules, timestamp, server); } function updateModules(file, modules, timestamp, { config, ws }) { const updates = []; const invalidatedModules = new Set(); let needFullReload = false; for (const mod of modules) { invalidate(mod, timestamp, invalidatedModules); if (needFullReload) { continue; } const boundaries = new Set(); const hasDeadEnd = propagateUpdate(mod, boundaries); if (hasDeadEnd) { needFullReload = true; continue; } updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({ type: `${boundary.type}-update`, timestamp, path: boundary.url, acceptedPath: acceptedVia.url }))); } if (needFullReload) { config.logger.info(source.green(`page reload `) + source.dim(file), { clear: true, timestamp: true }); ws.send({ type: 'full-reload' }); } else { config.logger.info(updates .map(({ path }) => source.green(`hmr update `) + source.dim(path)) .join('\n'), { clear: true, timestamp: true }); ws.send({ type: 'update', updates }); } } async function handleFileAddUnlink(file, server, isUnlink = false) { var _a; const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])]; if (isUnlink && file in server._globImporters) { delete server._globImporters[file]; } else { for (const i in server._globImporters) { const { module, importGlobs } = server._globImporters[i]; for (const { base, pattern } of importGlobs) { if (minimatch_1(file, pattern) || minimatch_1(path__default.relative(base, file), pattern)) { modules.push(module); // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()` // calls get fresh glob import results with(out) the newly added(/removed) `file`. server.moduleGraph.onFileChange(module.file); break; } } } } if (modules.length > 0) { updateModules(getShortName(file, server.config.root), modules, Date.now(), server); } } function propagateUpdate(node, boundaries, currentChain = [node]) { if (node.isSelfAccepting) { boundaries.add({ boundary: node, acceptedVia: node }); // additionally check for CSS importers, since a PostCSS plugin like // Tailwind JIT may register any file as a dependency to a CSS file. for (const importer of node.importers) { if (isCSSRequest(importer.url) && !currentChain.includes(importer)) { propagateUpdate(importer, boundaries, currentChain.concat(importer)); } } return false; } if (!node.importers.size) { return true; } // #3716, #3913 // For a non-CSS file, if all of its importers are CSS files (registered via // PostCSS plugins) it should be considered a dead end and force full reload. if (!isCSSRequest(node.url) && [...node.importers].every((i) => isCSSRequest(i.url))) { return true; } for (const importer of node.importers) { const subChain = currentChain.concat(importer); if (importer.acceptedHmrDeps.has(node)) { boundaries.add({ boundary: importer, acceptedVia: node }); continue; } if (currentChain.includes(importer)) { // circular deps is considered dead end return true; } if (propagateUpdate(importer, boundaries, subChain)) { return true; } } return false; } function invalidate(mod, timestamp, seen) { if (seen.has(mod)) { return; } seen.add(mod); mod.lastHMRTimestamp = timestamp; mod.transformResult = null; mod.ssrModule = null; mod.ssrTransformResult = null; mod.importers.forEach((importer) => { if (!importer.acceptedHmrDeps.has(mod)) { invalidate(importer, timestamp, seen); } }); } function handlePrunedModules(mods, { ws }) { // update the disposed modules' hmr timestamp // since if it's re-imported, it should re-apply side effects // and without the timestamp the browser will not re-import it! const t = Date.now(); mods.forEach((mod) => { mod.lastHMRTimestamp = t; debugHmr(`[dispose] ${source.dim(mod.file)}`); }); ws.send({ type: 'prune', paths: [...mods].map((m) => m.url) }); } /** * Lex import.meta.hot.accept() for accepted deps. * Since hot.accept() can only accept string literals or array of string * literals, we don't really need a heavy @babel/parse call on the entire source. * * @returns selfAccepts */ function lexAcceptedHmrDeps(code, start, urls) { let state = 0 /* inCall */; // the state can only be 2 levels deep so no need for a stack let prevState = 0 /* inCall */; let currentDep = ''; function addDep(index) { urls.add({ url: currentDep, start: index - currentDep.length - 1, end: index + 1 }); currentDep = ''; } for (let i = start; i < code.length; i++) { const char = code.charAt(i); switch (state) { case 0 /* inCall */: case 4 /* inArray */: if (char === `'`) { prevState = state; state = 1 /* inSingleQuoteString */; } else if (char === `"`) { prevState = state; state = 2 /* inDoubleQuoteString */; } else if (char === '`') { prevState = state; state = 3 /* inTemplateString */; } else if (/\s/.test(char)) { continue; } else { if (state === 0 /* inCall */) { if (char === `[`) { state = 4 /* inArray */; } else { // reaching here means the first arg is neither a string literal // nor an Array literal (direct callback) or there is no arg // in both case this indicates a self-accepting module return true; // done } } else if (state === 4 /* inArray */) { if (char === `]`) { return false; // done } else if (char === ',') { continue; } else { error$1(i); } } } break; case 1 /* inSingleQuoteString */: if (char === `'`) { addDep(i); if (prevState === 0 /* inCall */) { // accept('foo', ...) return false; } else { state = prevState; } } else { currentDep += char; } break; case 2 /* inDoubleQuoteString */: if (char === `"`) { addDep(i); if (prevState === 0 /* inCall */) { // accept('foo', ...) return false; } else { state = prevState; } } else { currentDep += char; } break; case 3 /* inTemplateString */: if (char === '`') { addDep(i); if (prevState === 0 /* inCall */) { // accept('foo', ...) return false; } else { state = prevState; } } else if (char === '$' && code.charAt(i + 1) === '{') { error$1(i); } else { currentDep += char; } break; default: throw new Error('unknown import.meta.hot lexer state'); } } return false; } function error$1(pos) { const err = new Error(`import.meta.accept() can only accept string literals or an ` + `Array of string literals.`); err.pos = pos; throw err; } // vitejs/vite#610 when hot-reloading Vue files, we read immediately on file // change event and sometimes this can be too early and get an empty buffer. // Poll until the file's modified time has changed before reading again. async function readModifiedFile(file) { const content = fs__default.readFileSync(file, 'utf-8'); if (!content) { const mtime = fs__default.statSync(file).mtimeMs; await new Promise((r) => { let n = 0; const poll = async () => { n++; const newMtime = fs__default.statSync(file).mtimeMs; if (newMtime !== mtime || n > 10) { r(0); } else { setTimeout(poll, 10); } }; setTimeout(poll, 10); }); return fs__default.readFileSync(file, 'utf-8'); } else { return content; } } async function restartServer(server) { // @ts-ignore global.__vite_start_time = perf_hooks.performance.now(); const { port } = server.config.server; await server.close(); let newServer = null; try { newServer = await createServer(server.config.inlineConfig); } catch (err) { server.config.logger.error(err.message, { timestamp: true }); return; } for (const key in newServer) { if (key !== 'app') { // @ts-ignore server[key] = newServer[key]; } } if (!server.config.server.middlewareMode) { await server.listen(port, true); } else { server.config.logger.info('server restarted.', { timestamp: true }); } } var isWsl$2 = {exports: {}}; const fs$7 = fs__default; let isDocker$2; function hasDockerEnv() { try { fs$7.statSync('/.dockerenv'); return true; } catch (_) { return false; } } function hasDockerCGroup() { try { return fs$7.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); } catch (_) { return false; } } var isDocker_1 = () => { if (isDocker$2 === undefined) { isDocker$2 = hasDockerEnv() || hasDockerCGroup(); } return isDocker$2; }; const os$4 = require$$0__default$1; const fs$6 = fs__default; const isDocker$1 = isDocker_1; const isWsl$1 = () => { if (process.platform !== 'linux') { return false; } if (os$4.release().toLowerCase().includes('microsoft')) { if (isDocker$1()) { return false; } return true; } try { return fs$6.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? !isDocker$1() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { isWsl$2.exports = isWsl$1; } else { isWsl$2.exports = isWsl$1(); } var defineLazyProp = (object, propertyName, fn) => { const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); Object.defineProperty(object, propertyName, { configurable: true, enumerable: true, get() { const result = fn(); define(result); return result; }, set(value) { define(value); } }); return object; }; const path$9 = path__default; const childProcess$3 = require$$1__default$4; const {promises: fs$5, constants: fsConstants} = fs__default; const isWsl = isWsl$2.exports; const isDocker = isDocker_1; const defineLazyProperty = defineLazyProp; // Path to included `xdg-open`. const localXdgOpenPath = path$9.join(__dirname, 'xdg-open'); const {platform, arch} = process; /** Get the mount point for fixed drives in WSL. @inner @returns {string} The mount point. */ const getWslDrivesMountPoint = (() => { // Default value for "root" param // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config const defaultMountPoint = '/mnt/'; let mountPoint; return async function () { if (mountPoint) { // Return memoized mount point value return mountPoint; } const configFilePath = '/etc/wsl.conf'; let isConfigFileExists = false; try { await fs$5.access(configFilePath, fsConstants.F_OK); isConfigFileExists = true; } catch {} if (!isConfigFileExists) { return defaultMountPoint; } const configContent = await fs$5.readFile(configFilePath, {encoding: 'utf8'}); const configMountPoint = /(?.*)/g.exec(configContent); if (!configMountPoint) { return defaultMountPoint; } mountPoint = configMountPoint.groups.mountPoint.trim(); mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; return mountPoint; }; })(); const pTryEach = async (array, mapper) => { let latestError; for (const item of array) { try { return await mapper(item); // eslint-disable-line no-await-in-loop } catch (error) { latestError = error; } } throw latestError; }; const open = async (target, options) => { if (typeof target !== 'string') { throw new TypeError('Expected a `target`'); } options = { wait: false, background: false, newInstance: false, allowNonzeroExitCode: false, ...options }; if (Array.isArray(options.app)) { return pTryEach(options.app, singleApp => open(target, { ...options, app: singleApp })); } let {name: app, arguments: appArguments = []} = options.app || {}; appArguments = [...appArguments]; if (Array.isArray(app)) { return pTryEach(app, appName => open(target, { ...options, app: { name: appName, arguments: appArguments } })); } let command; const cliArguments = []; const childProcessOptions = {}; if (platform === 'darwin') { command = 'open'; if (options.wait) { cliArguments.push('--wait-apps'); } if (options.background) { cliArguments.push('--background'); } if (options.newInstance) { cliArguments.push('--new'); } if (app) { cliArguments.push('-a', app); } } else if (platform === 'win32' || (isWsl && !isDocker())) { const mountPoint = await getWslDrivesMountPoint(); command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; cliArguments.push( '-NoProfile', '-NonInteractive', '–ExecutionPolicy', 'Bypass', '-EncodedCommand' ); if (!isWsl) { childProcessOptions.windowsVerbatimArguments = true; } const encodedArguments = ['Start']; if (options.wait) { encodedArguments.push('-Wait'); } if (app) { // Double quote with double quotes to ensure the inner quotes are passed through. // Inner quotes are delimited for PowerShell interpretation with backticks. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); appArguments.unshift(target); } else { encodedArguments.push(`"${target}"`); } if (appArguments.length > 0) { appArguments = appArguments.map(arg => `"\`"${arg}\`""`); encodedArguments.push(appArguments.join(',')); } // Using Base64-encoded command, accepted by PowerShell, to allow special characters. target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); } else { if (app) { command = app; } else { // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. const isBundled = !__dirname || __dirname === '/'; // Check if local `xdg-open` exists and is executable. let exeLocalXdgOpen = false; try { await fs$5.access(localXdgOpenPath, fsConstants.X_OK); exeLocalXdgOpen = true; } catch {} const useSystemXdgOpen = process.versions.electron || platform === 'android' || isBundled || !exeLocalXdgOpen; command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; } if (appArguments.length > 0) { cliArguments.push(...appArguments); } if (!options.wait) { // `xdg-open` will block the process unless stdio is ignored // and it's detached from the parent even if it's unref'd. childProcessOptions.stdio = 'ignore'; childProcessOptions.detached = true; } } cliArguments.push(target); if (platform === 'darwin' && appArguments.length > 0) { cliArguments.push('--args', ...appArguments); } const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions); if (options.wait) { return new Promise((resolve, reject) => { subprocess.once('error', reject); subprocess.once('close', exitCode => { if (options.allowNonzeroExitCode && exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; } resolve(subprocess); }); }); } subprocess.unref(); return subprocess; }; function detectArchBinary(binary) { if (typeof binary === 'string' || Array.isArray(binary)) { return binary; } const {[arch]: archBinary} = binary; if (!archBinary) { throw new Error(`${arch} is not supported`); } return archBinary; } function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { if (wsl && isWsl) { return detectArchBinary(wsl); } if (!platformBinary) { throw new Error(`${platform} is not supported`); } return detectArchBinary(platformBinary); } const apps = {}; defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ darwin: 'google chrome', win32: 'chrome', linux: ['google-chrome', 'google-chrome-stable'] }, { wsl: { ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] } })); defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ darwin: 'firefox', win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', linux: 'firefox' }, { wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' })); defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ darwin: 'microsoft edge', win32: 'msedge', linux: 'microsoft-edge' }, { wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' })); open.apps = apps; var open_1 = open; var execa$2 = {exports: {}}; var crossSpawn$1 = {exports: {}}; var windows$1 = isexe$3; isexe$3.sync = sync$2; var fs$4 = fs__default; function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT; if (!pathext) { return true } pathext = pathext.split(';'); if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase(); if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat$1 (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe$3 (path, options, cb) { fs$4.stat(path, function (er, stat) { cb(er, er ? false : checkStat$1(stat, path, options)); }); } function sync$2 (path, options) { return checkStat$1(fs$4.statSync(path), path, options) } var mode = isexe$2; isexe$2.sync = sync$1; var fs$3 = fs__default; function isexe$2 (path, options, cb) { fs$3.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)); }); } function sync$1 (path, options) { return checkStat(fs$3.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode; var uid = stat.uid; var gid = stat.gid; var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid(); var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid(); var u = parseInt('100', 8); var g = parseInt('010', 8); var o = parseInt('001', 8); var ug = u | g; var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0; return ret } var core$1; if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { core$1 = windows$1; } else { core$1 = mode; } var isexe_1 = isexe$1; isexe$1.sync = sync; function isexe$1 (path, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe$1(path, options || {}, function (er, is) { if (er) { reject(er); } else { resolve(is); } }); }) } core$1(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null; is = false; } } cb(er, is); }); } function sync (path, options) { // my kingdom for a filtered catch try { return core$1.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path$8 = path__default; const COLON = isWindows ? ';' : ':'; const isexe = isexe_1; const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON; // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows ? pathExtExe.split(colon) : ['']; if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which$1 = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$8.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }); }); return cb ? step(0).then(res => cb(null, res), cb) : step(0) }; const whichSync = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$8.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j]; try { const is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) }; var which_1 = which$1; which$1.sync = whichSync; var pathKey$1 = {exports: {}}; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; pathKey$1.exports = pathKey; // TODO: Remove this for the next major release pathKey$1.exports.default = pathKey; const path$7 = path__default; const which = which_1; const getPathKey = pathKey$1.exports; function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path$7.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path$7.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand$1(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } var resolveCommand_1 = resolveCommand$1; var _escape = {}; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(\\*)"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(\\*)$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } _escape.command = escapeCommand; _escape.argument = escapeArgument; var shebangRegex$1 = /^#!(.*)/; const shebangRegex = shebangRegex$1; var shebangCommand$1 = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; const fs$2 = fs__default; const shebangCommand = shebangCommand$1; function readShebang$1(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs$2.openSync(command, 'r'); fs$2.readSync(fd, buffer, 0, size, 0); fs$2.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } var readShebang_1 = readShebang$1; const path$6 = path__default; const resolveCommand = resolveCommand_1; const escape = _escape; const readShebang = readShebang_1; const isWin$2 = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin$2) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path$6.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse$4(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } var parse_1 = parse$4; const isWin$1 = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin$1) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin$1 && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin$1 && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } var enoent$1 = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; const cp = require$$1__default$4; const parse$3 = parse_1; const enoent = enoent$1; function spawn(command, args, options) { // Parse the arguments const parsed = parse$3(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse$3(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } crossSpawn$1.exports = spawn; crossSpawn$1.exports.spawn = spawn; crossSpawn$1.exports.sync = spawnSync; crossSpawn$1.exports._parse = parse$3; crossSpawn$1.exports._enoent = enoent; var stripFinalNewline$1 = input => { const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); if (input[input.length - 1] === LF) { input = input.slice(0, input.length - 1); } if (input[input.length - 1] === CR) { input = input.slice(0, input.length - 1); } return input; }; var npmRunPath$1 = {exports: {}}; (function (module) { const path = path__default; const pathKey = pathKey$1.exports; const npmRunPath = options => { options = { cwd: process.cwd(), path: process.env[pathKey()], execPath: process.execPath, ...options }; let previous; let cwdPath = path.resolve(options.cwd); const result = []; while (previous !== cwdPath) { result.push(path.join(cwdPath, 'node_modules/.bin')); previous = cwdPath; cwdPath = path.resolve(cwdPath, '..'); } // Ensure the running `node` binary is used const execPathDir = path.resolve(options.cwd, options.execPath, '..'); result.push(execPathDir); return result.concat(options.path).join(path.delimiter); }; module.exports = npmRunPath; // TODO: Remove this for the next major release module.exports.default = npmRunPath; module.exports.env = options => { options = { env: process.env, ...options }; const env = {...options.env}; const path = pathKey({env}); options.path = env[path]; env[path] = module.exports(options); return env; }; }(npmRunPath$1)); var onetime$2 = {exports: {}}; var mimicFn$2 = {exports: {}}; const mimicFn$1 = (to, from) => { for (const prop of Reflect.ownKeys(from)) { Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); } return to; }; mimicFn$2.exports = mimicFn$1; // TODO: Remove this for the next major release mimicFn$2.exports.default = mimicFn$1; const mimicFn = mimicFn$2.exports; const calledFunctions = new WeakMap(); const onetime$1 = (function_, options = {}) => { if (typeof function_ !== 'function') { throw new TypeError('Expected a function'); } let returnValue; let callCount = 0; const functionName = function_.displayName || function_.name || ''; const onetime = function (...arguments_) { calledFunctions.set(onetime, ++callCount); if (callCount === 1) { returnValue = function_.apply(this, arguments_); function_ = null; } else if (options.throw === true) { throw new Error(`Function \`${functionName}\` can only be called once`); } return returnValue; }; mimicFn(onetime, function_); calledFunctions.set(onetime, callCount); return onetime; }; onetime$2.exports = onetime$1; // TODO: Remove this for the next major release onetime$2.exports.default = onetime$1; onetime$2.exports.callCount = function_ => { if (!calledFunctions.has(function_)) { throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); } return calledFunctions.get(function_); }; var main$2 = {}; var signals$2 = {}; var core = {}; Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0; const SIGNALS=[ { name:"SIGHUP", number:1, action:"terminate", description:"Terminal closed", standard:"posix"}, { name:"SIGINT", number:2, action:"terminate", description:"User interruption with CTRL-C", standard:"ansi"}, { name:"SIGQUIT", number:3, action:"core", description:"User interruption with CTRL-\\", standard:"posix"}, { name:"SIGILL", number:4, action:"core", description:"Invalid machine instruction", standard:"ansi"}, { name:"SIGTRAP", number:5, action:"core", description:"Debugger breakpoint", standard:"posix"}, { name:"SIGABRT", number:6, action:"core", description:"Aborted", standard:"ansi"}, { name:"SIGIOT", number:6, action:"core", description:"Aborted", standard:"bsd"}, { name:"SIGBUS", number:7, action:"core", description: "Bus error due to misaligned, non-existing address or paging error", standard:"bsd"}, { name:"SIGEMT", number:7, action:"terminate", description:"Command should be emulated but is not implemented", standard:"other"}, { name:"SIGFPE", number:8, action:"core", description:"Floating point arithmetic error", standard:"ansi"}, { name:"SIGKILL", number:9, action:"terminate", description:"Forced termination", standard:"posix", forced:true}, { name:"SIGUSR1", number:10, action:"terminate", description:"Application-specific signal", standard:"posix"}, { name:"SIGSEGV", number:11, action:"core", description:"Segmentation fault", standard:"ansi"}, { name:"SIGUSR2", number:12, action:"terminate", description:"Application-specific signal", standard:"posix"}, { name:"SIGPIPE", number:13, action:"terminate", description:"Broken pipe or socket", standard:"posix"}, { name:"SIGALRM", number:14, action:"terminate", description:"Timeout or timer", standard:"posix"}, { name:"SIGTERM", number:15, action:"terminate", description:"Termination", standard:"ansi"}, { name:"SIGSTKFLT", number:16, action:"terminate", description:"Stack is empty or overflowed", standard:"other"}, { name:"SIGCHLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"posix"}, { name:"SIGCLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"other"}, { name:"SIGCONT", number:18, action:"unpause", description:"Unpaused", standard:"posix", forced:true}, { name:"SIGSTOP", number:19, action:"pause", description:"Paused", standard:"posix", forced:true}, { name:"SIGTSTP", number:20, action:"pause", description:"Paused using CTRL-Z or \"suspend\"", standard:"posix"}, { name:"SIGTTIN", number:21, action:"pause", description:"Background process cannot read terminal input", standard:"posix"}, { name:"SIGBREAK", number:21, action:"terminate", description:"User interruption with CTRL-BREAK", standard:"other"}, { name:"SIGTTOU", number:22, action:"pause", description:"Background process cannot write to terminal output", standard:"posix"}, { name:"SIGURG", number:23, action:"ignore", description:"Socket received out-of-band data", standard:"bsd"}, { name:"SIGXCPU", number:24, action:"core", description:"Process timed out", standard:"bsd"}, { name:"SIGXFSZ", number:25, action:"core", description:"File too big", standard:"bsd"}, { name:"SIGVTALRM", number:26, action:"terminate", description:"Timeout or timer", standard:"bsd"}, { name:"SIGPROF", number:27, action:"terminate", description:"Timeout or timer", standard:"bsd"}, { name:"SIGWINCH", number:28, action:"ignore", description:"Terminal window size changed", standard:"bsd"}, { name:"SIGIO", number:29, action:"terminate", description:"I/O is available", standard:"other"}, { name:"SIGPOLL", number:29, action:"terminate", description:"Watched event", standard:"other"}, { name:"SIGINFO", number:29, action:"ignore", description:"Request for process information", standard:"other"}, { name:"SIGPWR", number:30, action:"terminate", description:"Device running out of power", standard:"systemv"}, { name:"SIGSYS", number:31, action:"core", description:"Invalid system call", standard:"other"}, { name:"SIGUNUSED", number:31, action:"terminate", description:"Invalid system call", standard:"other"}];core.SIGNALS=SIGNALS; var realtime = {}; Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0; const getRealtimeSignals=function(){ const length=SIGRTMAX-SIGRTMIN+1; return Array.from({length},getRealtimeSignal); };realtime.getRealtimeSignals=getRealtimeSignals; const getRealtimeSignal=function(value,index){ return { name:`SIGRT${index+1}`, number:SIGRTMIN+index, action:"terminate", description:"Application-specific signal (realtime)", standard:"posix"}; }; const SIGRTMIN=34; const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX; Object.defineProperty(signals$2,"__esModule",{value:true});signals$2.getSignals=void 0;var _os$1=require$$0__default$1; var _core=core; var _realtime$1=realtime; const getSignals=function(){ const realtimeSignals=(0, _realtime$1.getRealtimeSignals)(); const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); return signals; };signals$2.getSignals=getSignals; const normalizeSignal=function({ name, number:defaultNumber, description, action, forced=false, standard}) { const{ signals:{[name]:constantSignal}}= _os$1.constants; const supported=constantSignal!==undefined; const number=supported?constantSignal:defaultNumber; return {name,number,description,supported,action,forced,standard}; }; Object.defineProperty(main$2,"__esModule",{value:true});main$2.signalsByNumber=main$2.signalsByName=void 0;var _os=require$$0__default$1; var _signals=signals$2; var _realtime=realtime; const getSignalsByName=function(){ const signals=(0, _signals.getSignals)(); return signals.reduce(getSignalByName,{}); }; const getSignalByName=function( signalByNameMemo, {name,number,description,supported,action,forced,standard}) { return { ...signalByNameMemo, [name]:{name,number,description,supported,action,forced,standard}}; }; const signalsByName$1=getSignalsByName();main$2.signalsByName=signalsByName$1; const getSignalsByNumber=function(){ const signals=(0, _signals.getSignals)(); const length=_realtime.SIGRTMAX+1; const signalsA=Array.from({length},(value,number)=> getSignalByNumber(number,signals)); return Object.assign({},...signalsA); }; const getSignalByNumber=function(number,signals){ const signal=findSignalByNumber(number,signals); if(signal===undefined){ return {}; } const{name,description,supported,action,forced,standard}=signal; return { [number]:{ name, number, description, supported, action, forced, standard}}; }; const findSignalByNumber=function(number,signals){ const signal=signals.find(({name})=>_os.constants.signals[name]===number); if(signal!==undefined){ return signal; } return signals.find(signalA=>signalA.number===number); }; const signalsByNumber=getSignalsByNumber();main$2.signalsByNumber=signalsByNumber; const {signalsByName} = main$2; const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { if (timedOut) { return `timed out after ${timeout} milliseconds`; } if (isCanceled) { return 'was canceled'; } if (errorCode !== undefined) { return `failed with ${errorCode}`; } if (signal !== undefined) { return `was killed with ${signal} (${signalDescription})`; } if (exitCode !== undefined) { return `failed with exit code ${exitCode}`; } return 'failed'; }; const makeError$1 = ({ stdout, stderr, all, error, signal, exitCode, command, escapedCommand, timedOut, isCanceled, killed, parsed: {options: {timeout}} }) => { // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. // We normalize them to `undefined` exitCode = exitCode === null ? undefined : exitCode; signal = signal === null ? undefined : signal; const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; const errorCode = error && error.code; const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); const execaMessage = `Command ${prefix}: ${command}`; const isError = Object.prototype.toString.call(error) === '[object Error]'; const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); if (isError) { error.originalMessage = error.message; error.message = message; } else { error = new Error(message); } error.shortMessage = shortMessage; error.command = command; error.escapedCommand = escapedCommand; error.exitCode = exitCode; error.signal = signal; error.signalDescription = signalDescription; error.stdout = stdout; error.stderr = stderr; if (all !== undefined) { error.all = all; } if ('bufferedData' in error) { delete error.bufferedData; } error.failed = true; error.timedOut = Boolean(timedOut); error.isCanceled = isCanceled; error.killed = killed && !timedOut; return error; }; var error = makeError$1; var stdio = {exports: {}}; const aliases = ['stdin', 'stdout', 'stderr']; const hasAlias = options => aliases.some(alias => options[alias] !== undefined); const normalizeStdio$1 = options => { if (!options) { return; } const {stdio} = options; if (stdio === undefined) { return aliases.map(alias => options[alias]); } if (hasAlias(options)) { throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); } if (typeof stdio === 'string') { return stdio; } if (!Array.isArray(stdio)) { throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); } const length = Math.max(stdio.length, aliases.length); return Array.from({length}, (value, index) => stdio[index]); }; stdio.exports = normalizeStdio$1; // `ipc` is pushed unless it is already present stdio.exports.node = options => { const stdio = normalizeStdio$1(options); if (stdio === 'ipc') { return 'ipc'; } if (stdio === undefined || typeof stdio === 'string') { return [stdio, stdio, stdio, 'ipc']; } if (stdio.includes('ipc')) { return stdio; } return [...stdio, 'ipc']; }; var signalExit = {exports: {}}; var signals$1 = {exports: {}}; (function (module) { // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM' ]; if (process.platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ); } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ); } }(signals$1)); // Note: since nyc uses this module to output coverage, any lines // that are in the direct sync flow of nyc's outputCoverage are // ignored, since we can never get coverage for them. // grab a reference to node's real process object right away var process$1 = commonjsGlobal.process; // some kind of non-node environment, just no-op if (typeof process$1 !== 'object' || !process$1) { signalExit.exports = () => {}; } else { var assert = require$$5__default; var signals = signals$1.exports; var isWin = /^win/i.test(process$1.platform); var EE = require$$0__default$5; /* istanbul ignore if */ if (typeof EE !== 'function') { EE = EE.EventEmitter; } var emitter; if (process$1.__signal_exit_emitter__) { emitter = process$1.__signal_exit_emitter__; } else { emitter = process$1.__signal_exit_emitter__ = new EE(); emitter.count = 0; emitter.emitted = {}; } // Because this emitter is a global, we have to check to see if a // previous version of this library failed to enable infinite listeners. // I know what you're about to say. But literally everything about // signal-exit is a compromise with evil. Get used to it. if (!emitter.infinite) { emitter.setMaxListeners(Infinity); emitter.infinite = true; } signalExit.exports = function (cb, opts) { if (commonjsGlobal.process !== process$1) { return } assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); if (loaded === false) { load(); } var ev = 'exit'; if (opts && opts.alwaysLast) { ev = 'afterexit'; } var remove = function () { emitter.removeListener(ev, cb); if (emitter.listeners('exit').length === 0 && emitter.listeners('afterexit').length === 0) { unload(); } }; emitter.on(ev, cb); return remove }; var unload = function unload () { if (!loaded || commonjsGlobal.process !== process$1) { return } loaded = false; signals.forEach(function (sig) { try { process$1.removeListener(sig, sigListeners[sig]); } catch (er) {} }); process$1.emit = originalProcessEmit; process$1.reallyExit = originalProcessReallyExit; emitter.count -= 1; }; signalExit.exports.unload = unload; var emit = function emit (event, code, signal) { if (emitter.emitted[event]) { return } emitter.emitted[event] = true; emitter.emit(event, code, signal); }; // { : , ... } var sigListeners = {}; signals.forEach(function (sig) { sigListeners[sig] = function listener () { if (process$1 !== commonjsGlobal.process) { return } // If there are no other listeners, an exit is coming! // Simplest way: remove us and then re-send the signal. // We know that this will kill the process, so we can // safely emit now. var listeners = process$1.listeners(sig); if (listeners.length === emitter.count) { unload(); emit('exit', null, sig); /* istanbul ignore next */ emit('afterexit', null, sig); /* istanbul ignore next */ if (isWin && sig === 'SIGHUP') { // "SIGHUP" throws an `ENOSYS` error on Windows, // so use a supported signal instead sig = 'SIGINT'; } process$1.kill(process$1.pid, sig); } }; }); signalExit.exports.signals = function () { return signals }; var loaded = false; var load = function load () { if (loaded || process$1 !== commonjsGlobal.process) { return } loaded = true; // This is the number of onSignalExit's that are in play. // It's important so that we can count the correct number of // listeners on signals, and don't wait for the other one to // handle it instead of us. emitter.count += 1; signals = signals.filter(function (sig) { try { process$1.on(sig, sigListeners[sig]); return true } catch (er) { return false } }); process$1.emit = processEmit; process$1.reallyExit = processReallyExit; }; signalExit.exports.load = load; var originalProcessReallyExit = process$1.reallyExit; var processReallyExit = function processReallyExit (code) { if (process$1 !== commonjsGlobal.process) { return } process$1.exitCode = code || 0; emit('exit', process$1.exitCode, null); /* istanbul ignore next */ emit('afterexit', process$1.exitCode, null); /* istanbul ignore next */ originalProcessReallyExit.call(process$1, process$1.exitCode); }; var originalProcessEmit = process$1.emit; var processEmit = function processEmit (ev, arg) { if (ev === 'exit' && process$1 === commonjsGlobal.process) { if (arg !== undefined) { process$1.exitCode = arg; } var ret = originalProcessEmit.apply(this, arguments); emit('exit', process$1.exitCode, null); /* istanbul ignore next */ emit('afterexit', process$1.exitCode, null); return ret } else { return originalProcessEmit.apply(this, arguments) } }; } const os$3 = require$$0__default$1; const onExit = signalExit.exports; const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => { const killResult = kill(signal); setKillTimeout(kill, signal, options, killResult); return killResult; }; const setKillTimeout = (kill, signal, options, killResult) => { if (!shouldForceKill(signal, options, killResult)) { return; } const timeout = getForceKillAfterTimeout(options); const t = setTimeout(() => { kill('SIGKILL'); }, timeout); // Guarded because there's no `.unref()` when `execa` is used in the renderer // process in Electron. This cannot be tested since we don't run tests in // Electron. // istanbul ignore else if (t.unref) { t.unref(); } }; const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; }; const isSigterm = signal => { return signal === os$3.constants.signals.SIGTERM || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); }; const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { if (forceKillAfterTimeout === true) { return DEFAULT_FORCE_KILL_TIMEOUT; } if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); } return forceKillAfterTimeout; }; // `childProcess.cancel()` const spawnedCancel$1 = (spawned, context) => { const killResult = spawned.kill(); if (killResult) { context.isCanceled = true; } }; const timeoutKill = (spawned, signal, reject) => { spawned.kill(signal); reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); }; // `timeout` option handling const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { if (timeout === 0 || timeout === undefined) { return spawnedPromise; } let timeoutId; const timeoutPromise = new Promise((resolve, reject) => { timeoutId = setTimeout(() => { timeoutKill(spawned, killSignal, reject); }, timeout); }); const safeSpawnedPromise = spawnedPromise.finally(() => { clearTimeout(timeoutId); }); return Promise.race([timeoutPromise, safeSpawnedPromise]); }; const validateTimeout$1 = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); } }; // `cleanup` option handling const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => { if (!cleanup || detached) { return timedPromise; } const removeExitHandler = onExit(() => { spawned.kill(); }); return timedPromise.finally(() => { removeExitHandler(); }); }; var kill = { spawnedKill: spawnedKill$1, spawnedCancel: spawnedCancel$1, setupTimeout: setupTimeout$1, validateTimeout: validateTimeout$1, setExitHandler: setExitHandler$1 }; const isStream$1 = stream => stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; isStream$1.writable = stream => isStream$1(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; isStream$1.readable = stream => isStream$1(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; isStream$1.duplex = stream => isStream$1.writable(stream) && isStream$1.readable(stream); isStream$1.transform = stream => isStream$1.duplex(stream) && typeof stream._transform === 'function'; var isStream_1 = isStream$1; var getStream$2 = {exports: {}}; const {PassThrough: PassThroughStream} = require$$0__default$4; var bufferStream$1 = options => { options = {...options}; const {array} = options; let {encoding} = options; const isBuffer = encoding === 'buffer'; let objectMode = false; if (array) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || 'utf8'; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({objectMode}); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on('data', chunk => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); }; stream.getBufferedLength = () => length; return stream; }; const {constants: BufferConstants} = require$$0__default$8; const stream$1 = require$$0__default$4; const {promisify} = require$$0__default$2; const bufferStream = bufferStream$1; const streamPipelinePromisified = promisify(stream$1.pipeline); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream$1(inputStream, options) { if (!inputStream) { throw new Error('Expected a stream'); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; const stream = bufferStream(options); await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } reject(error); }; (async () => { try { await streamPipelinePromisified(inputStream, stream); resolve(); } catch (error) { rejectPromise(error); } })(); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } getStream$2.exports = getStream$1; getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'}); getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true}); getStream$2.exports.MaxBufferError = MaxBufferError; const { PassThrough } = require$$0__default$4; var mergeStream$1 = function (/*streams...*/) { var sources = []; var output = new PassThrough({objectMode: true}); output.setMaxListeners(0); output.add = add; output.isEmpty = isEmpty; output.on('unpipe', remove); Array.prototype.slice.call(arguments).forEach(add); return output function add (source) { if (Array.isArray(source)) { source.forEach(add); return this } sources.push(source); source.once('end', remove.bind(null, source)); source.once('error', output.emit.bind(output, 'error')); source.pipe(output, {end: false}); return this } function isEmpty () { return sources.length == 0; } function remove (source) { sources = sources.filter(function (it) { return it !== source }); if (!sources.length && output.readable) { output.end(); } } }; const isStream = isStream_1; const getStream = getStream$2.exports; const mergeStream = mergeStream$1; // `input` option const handleInput$1 = (spawned, input) => { // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 if (input === undefined || spawned.stdin === undefined) { return; } if (isStream(input)) { input.pipe(spawned.stdin); } else { spawned.stdin.end(input); } }; // `all` interleaves `stdout` and `stderr` const makeAllStream$1 = (spawned, {all}) => { if (!all || (!spawned.stdout && !spawned.stderr)) { return; } const mixed = mergeStream(); if (spawned.stdout) { mixed.add(spawned.stdout); } if (spawned.stderr) { mixed.add(spawned.stderr); } return mixed; }; // On failure, `result.stdout|stderr|all` should contain the currently buffered stream const getBufferedData = async (stream, streamPromise) => { if (!stream) { return; } stream.destroy(); try { return await streamPromise; } catch (error) { return error.bufferedData; } }; const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { if (!stream || !buffer) { return; } if (encoding) { return getStream(stream, {encoding, maxBuffer}); } return getStream.buffer(stream, {maxBuffer}); }; // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); try { return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); } catch (error) { return Promise.all([ {error, signal: error.signal, timedOut: error.timedOut}, getBufferedData(stdout, stdoutPromise), getBufferedData(stderr, stderrPromise), getBufferedData(all, allPromise) ]); } }; const validateInputSync$1 = ({input}) => { if (isStream(input)) { throw new TypeError('The `input` option cannot be a stream in sync mode'); } }; var stream = { handleInput: handleInput$1, makeAllStream: makeAllStream$1, getSpawnedResult: getSpawnedResult$1, validateInputSync: validateInputSync$1 }; const nativePromisePrototype = (async () => {})().constructor.prototype; const descriptors = ['then', 'catch', 'finally'].map(property => [ property, Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) ]); // The return value is a mixin of `childProcess` and `Promise` const mergePromise$1 = (spawned, promise) => { for (const [property, descriptor] of descriptors) { // Starting the main `promise` is deferred to avoid consuming streams const value = typeof promise === 'function' ? (...args) => Reflect.apply(descriptor.value, promise(), args) : descriptor.value.bind(promise); Reflect.defineProperty(spawned, property, {...descriptor, value}); } return spawned; }; // Use promises instead of `child_process` events const getSpawnedPromise$1 = spawned => { return new Promise((resolve, reject) => { spawned.on('exit', (exitCode, signal) => { resolve({exitCode, signal}); }); spawned.on('error', error => { reject(error); }); if (spawned.stdin) { spawned.stdin.on('error', error => { reject(error); }); } }); }; var promise = { mergePromise: mergePromise$1, getSpawnedPromise: getSpawnedPromise$1 }; const normalizeArgs = (file, args = []) => { if (!Array.isArray(args)) { return [file]; } return [file, ...args]; }; const NO_ESCAPE_REGEXP = /^[\w.-]+$/; const DOUBLE_QUOTES_REGEXP = /"/g; const escapeArg = arg => { if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { return arg; } return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`; }; const joinCommand$1 = (file, args) => { return normalizeArgs(file, args).join(' '); }; const getEscapedCommand$1 = (file, args) => { return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); }; const SPACES_REGEXP = / +/g; // Handle `execa.command()` const parseCommand$1 = command => { const tokens = []; for (const token of command.trim().split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens[tokens.length - 1]; if (previousToken && previousToken.endsWith('\\')) { // Merge previous token with current one tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; } else { tokens.push(token); } } return tokens; }; var command = { joinCommand: joinCommand$1, getEscapedCommand: getEscapedCommand$1, parseCommand: parseCommand$1 }; const path$5 = path__default; const childProcess$2 = require$$1__default$4; const crossSpawn = crossSpawn$1.exports; const stripFinalNewline = stripFinalNewline$1; const npmRunPath = npmRunPath$1.exports; const onetime = onetime$2.exports; const makeError = error; const normalizeStdio = stdio.exports; const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill; const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream; const {mergePromise, getSpawnedPromise} = promise; const {joinCommand, parseCommand, getEscapedCommand} = command; const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { const env = extendEnv ? {...process.env, ...envOption} : envOption; if (preferLocal) { return npmRunPath.env({env, cwd: localDir, execPath}); } return env; }; const handleArguments = (file, args, options = {}) => { const parsed = crossSpawn._parse(file, args, options); file = parsed.command; args = parsed.args; options = parsed.options; options = { maxBuffer: DEFAULT_MAX_BUFFER, buffer: true, stripFinalNewline: true, extendEnv: true, preferLocal: false, localDir: options.cwd || process.cwd(), execPath: process.execPath, encoding: 'utf8', reject: true, cleanup: true, all: false, windowsHide: true, ...options }; options.env = getEnv(options); options.stdio = normalizeStdio(options); if (process.platform === 'win32' && path$5.basename(file, '.exe') === 'cmd') { // #116 args.unshift('/q'); } return {file, args, options, parsed}; }; const handleOutput = (options, value, error) => { if (typeof value !== 'string' && !Buffer.isBuffer(value)) { // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` return error === undefined ? undefined : ''; } if (options.stripFinalNewline) { return stripFinalNewline(value); } return value; }; const execa = (file, args, options) => { const parsed = handleArguments(file, args, options); const command = joinCommand(file, args); const escapedCommand = getEscapedCommand(file, args); validateTimeout(parsed.options); let spawned; try { spawned = childProcess$2.spawn(parsed.file, parsed.args, parsed.options); } catch (error) { // Ensure the returned error is always both a promise and a child process const dummySpawned = new childProcess$2.ChildProcess(); const errorPromise = Promise.reject(makeError({ error, stdout: '', stderr: '', all: '', command, escapedCommand, parsed, timedOut: false, isCanceled: false, killed: false })); return mergePromise(dummySpawned, errorPromise); } const spawnedPromise = getSpawnedPromise(spawned); const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); const processDone = setExitHandler(spawned, parsed.options, timedPromise); const context = {isCanceled: false}; spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); spawned.cancel = spawnedCancel.bind(null, spawned, context); const handlePromise = async () => { const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); const stdout = handleOutput(parsed.options, stdoutResult); const stderr = handleOutput(parsed.options, stderrResult); const all = handleOutput(parsed.options, allResult); if (error || exitCode !== 0 || signal !== null) { const returnedError = makeError({ error, exitCode, signal, stdout, stderr, all, command, escapedCommand, parsed, timedOut, isCanceled: context.isCanceled, killed: spawned.killed }); if (!parsed.options.reject) { return returnedError; } throw returnedError; } return { command, escapedCommand, exitCode: 0, stdout, stderr, all, failed: false, timedOut: false, isCanceled: false, killed: false }; }; const handlePromiseOnce = onetime(handlePromise); handleInput(spawned, parsed.options.input); spawned.all = makeAllStream(spawned, parsed.options); return mergePromise(spawned, handlePromiseOnce); }; execa$2.exports = execa; execa$2.exports.sync = (file, args, options) => { const parsed = handleArguments(file, args, options); const command = joinCommand(file, args); const escapedCommand = getEscapedCommand(file, args); validateInputSync(parsed.options); let result; try { result = childProcess$2.spawnSync(parsed.file, parsed.args, parsed.options); } catch (error) { throw makeError({ error, stdout: '', stderr: '', all: '', command, escapedCommand, parsed, timedOut: false, isCanceled: false, killed: false }); } const stdout = handleOutput(parsed.options, result.stdout, result.error); const stderr = handleOutput(parsed.options, result.stderr, result.error); if (result.error || result.status !== 0 || result.signal !== null) { const error = makeError({ stdout, stderr, error: result.error, signal: result.signal, exitCode: result.status, command, escapedCommand, parsed, timedOut: result.error && result.error.code === 'ETIMEDOUT', isCanceled: false, killed: result.signal !== null }); if (!parsed.options.reject) { return error; } throw error; } return { command, escapedCommand, exitCode: 0, stdout, stderr, failed: false, timedOut: false, isCanceled: false, killed: false }; }; execa$2.exports.command = (command, options) => { const [file, ...args] = parseCommand(command); return execa(file, args, options); }; execa$2.exports.commandSync = (command, options) => { const [file, ...args] = parseCommand(command); return execa.sync(file, args, options); }; execa$2.exports.node = (scriptPath, args, options = {}) => { if (args && !Array.isArray(args) && typeof args === 'object') { options = args; args = []; } const stdio = normalizeStdio.node(options); const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); const { nodePath = process.execPath, nodeOptions = defaultExecArgv } = options; return execa( nodePath, [ ...nodeOptions, scriptPath, ...(Array.isArray(args) ? args : []) ], { ...options, stdin: undefined, stdout: undefined, stderr: undefined, stdio, shell: false } ); }; var execa$1 = execa$2.exports; /** * The following is modified based on source found in * https://github.com/facebook/create-react-app * * MIT Licensed * Copyright (c) 2015-present, Facebook, Inc. * https://github.com/facebook/create-react-app/blob/master/LICENSE * */ // https://github.com/sindresorhus/open#app const OSX_CHROME = 'google chrome'; /** * Reads the BROWSER environment variable and decides what to do with it. * Returns true if it opened a browser or ran a node.js script, otherwise false. */ function openBrowser(url, opt, logger) { // The browser executable to open. // See https://github.com/sindresorhus/open#app for documentation. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; if (browser.toLowerCase().endsWith('.js')) { return executeNodeScript(browser, url, logger); } else if (browser.toLowerCase() !== 'none') { return startBrowserProcess(browser, url); } return false; } function executeNodeScript(scriptPath, url, logger) { const extraArgs = process.argv.slice(2); const child = execa$1('node', [scriptPath, ...extraArgs, url], { stdio: 'inherit' }); child.on('close', (code) => { if (code !== 0) { logger.error(source.red(`\nThe script specified as BROWSER environment variable failed.\n\n${source.cyan(scriptPath)} exited with code ${code}.`), { error: null }); } }); return true; } function startBrowserProcess(browser, url) { // If we're on OS X, the user hasn't specifically // requested a different browser, we can try opening // Chrome with AppleScript. This lets us reuse an // existing tab when possible instead of creating a new one. const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME); if (shouldTryOpenChromeWithAppleScript) { try { // Try our best to reuse existing tab // on OS X Google Chrome with AppleScript require$$1$4.execSync('ps cax | grep "Google Chrome"'); require$$1$4.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', { cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')), stdio: 'ignore' }); return true; } catch (err) { // Ignore errors } } // Another special case: on OS X, check if BROWSER has been set to "open". // In this case, instead of passing the string `open` to `open` function (which won't work), // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 if (process.platform === 'darwin' && browser === 'open') { browser = undefined; } // Fallback to open // (It will always open new tab) try { const options = browser ? { app: { name: browser } } : {}; open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. return true; } catch (err) { return false; } } var chalk$1 = {exports: {}}; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var ansiStyles = {exports: {}}; var conversions$2 = {exports: {}}; var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ var cssKeywords = colorName; // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in cssKeywords) { if (cssKeywords.hasOwnProperty(key)) { reverseKeywords[cssKeywords[key]] = key; } } var convert$1 = conversions$2.exports = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; // hide .channels and .labels properties for (var model in convert$1) { if (convert$1.hasOwnProperty(model)) { if (!('channels' in convert$1[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert$1[model])) { throw new Error('missing channel labels property: ' + model); } if (convert$1[model].labels.length !== convert$1[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert$1[model].channels; var labels = convert$1[model].labels; delete convert$1[model].channels; delete convert$1[model].labels; Object.defineProperty(convert$1[model], 'channels', {value: channels}); Object.defineProperty(convert$1[model], 'labels', {value: labels}); } } convert$1.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert$1.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert$1.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert$1.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert$1.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return ( Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2) ); } convert$1.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in cssKeywords) { if (cssKeywords.hasOwnProperty(keyword)) { var value = cssKeywords[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert$1.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert$1.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert$1.rgb.lab = function (rgb) { var xyz = convert$1.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert$1.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert$1.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert$1.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - (s * f)); var t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert$1.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert$1.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert$1.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // assume sRGB r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert$1.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert$1.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert$1.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert$1.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert$1.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert$1.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); }; convert$1.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } var ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert$1.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = ((color & 1) * mult) * 255; var g = (((color >> 1) & 1) * mult) * 255; var b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert$1.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert$1.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = (integer >> 16) & 0xFF; var g = (integer >> 8) & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert$1.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = (max - min); var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert$1.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert$1.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert$1.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = (h % 1) * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert$1.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert$1.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert$1.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert$1.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert$1.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert$1.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert$1.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert$1.gray.hsl = convert$1.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert$1.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert$1.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert$1.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert$1.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; var conversions$1 = conversions$2.exports; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions$1); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions$1[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions$1[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions$1[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$1 = function (fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; var conversions = conversions$2.exports; var route = route$1; var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); var colorConvert = convert; (function (module) { const colorConvert$1 = colorConvert; const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert$1, arguments); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert$1, arguments); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert$1, arguments); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert$1)) { if (typeof colorConvert$1[key] !== 'object') { continue; } const suite = colorConvert$1[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }(ansiStyles)); var hasFlag$1 = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; const os$2 = require$$0__default$1; const hasFlag = hasFlag$1; const env = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env) { forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = os$2.release().split('.'); if ( Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } if (env.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape$1(c) { if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape$1(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; (function (module) { const escapeStringRegexp$1 = escapeStringRegexp; const ansiStyles$1 = ansiStyles.exports; const stdoutColor = supportsColor_1.stdout; const template = templates; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles$1.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles$1)) { ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles$1[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.color.close), 'g'); for (const model of Object.keys(ansiStyles$1.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$1.color.close, closeRe: ansiStyles$1.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$1.bgColor.close, closeRe: ansiStyles$1.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function () { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles$1.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles$1.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles$1.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return template(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }(chalk$1)); var shellQuote$1 = {}; shellQuote$1.quote = function (xs) { return xs.map(function (s) { if (s && typeof s === 'object') { return s.op.replace(/(.)/g, '\\$1'); } else if (/["\s]/.test(s) && !/'/.test(s)) { return "'" + s.replace(/(['\\])/g, '\\$1') + "'"; } else if (/["'\s]/.test(s)) { return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; } else { return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2'); } }).join(' '); }; // '<(' is process substitution operator and // can be parsed the same as control operator var CONTROL = '(?:' + [ '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]' ].join('|') + ')'; var META = '|&;()<> \\t'; var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+'; var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; var TOKEN = ''; for (var i = 0; i < 4; i++) { TOKEN += (Math.pow(16,8)*Math.random()).toString(16); } shellQuote$1.parse = function (s, env, opts) { var mapped = parse$2(s, env, opts); if (typeof env !== 'function') return mapped; return mapped.reduce(function (acc, s) { if (typeof s === 'object') return acc.concat(s); var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); if (xs.length === 1) return acc.concat(xs[0]); return acc.concat(xs.filter(Boolean).map(function (x) { if (RegExp('^' + TOKEN).test(x)) { return JSON.parse(x.split(TOKEN)[1]); } else return x; })); }, []); }; function parse$2 (s, env, opts) { var chunker = new RegExp([ '(' + CONTROL + ')', // control chars '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*' ].join('|'), 'g'); var match = s.match(chunker).filter(Boolean); var commented = false; if (!match) return []; if (!env) env = {}; if (!opts) opts = {}; return match.map(function (s, j) { if (commented) { return; } if (RegExp('^' + CONTROL + '$').test(s)) { return { op: s }; } // Hand-written scanner/parser for Bash quoting rules: // // 1. inside single quotes, all characters are printed literally. // 2. inside double quotes, all characters are printed literally // except variables prefixed by '$' and backslashes followed by // either a double quote or another backslash. // 3. outside of any quotes, backslashes are treated as escape // characters and not printed (unless they are themselves escaped) // 4. quote context can switch mid-token if there is no whitespace // between the two quote contexts (e.g. all'one'"token" parses as // "allonetoken") var SQ = "'"; var DQ = '"'; var DS = '$'; var BS = opts.escape || '\\'; var quote = false; var esc = false; var out = ''; var isGlob = false; for (var i = 0, len = s.length; i < len; i++) { var c = s.charAt(i); isGlob = isGlob || (!quote && (c === '*' || c === '?')); if (esc) { out += c; esc = false; } else if (quote) { if (c === quote) { quote = false; } else if (quote == SQ) { out += c; } else { // Double quote if (c === BS) { i += 1; c = s.charAt(i); if (c === DQ || c === BS || c === DS) { out += c; } else { out += BS + c; } } else if (c === DS) { out += parseEnvVar(); } else { out += c; } } } else if (c === DQ || c === SQ) { quote = c; } else if (RegExp('^' + CONTROL + '$').test(c)) { return { op: s }; } else if (RegExp('^#$').test(c)) { commented = true; if (out.length){ return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; } return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; } else if (c === BS) { esc = true; } else if (c === DS) { out += parseEnvVar(); } else out += c; } if (isGlob) return {op: 'glob', pattern: out}; return out; function parseEnvVar() { i += 1; var varend, varname; //debugger if (s.charAt(i) === '{') { i += 1; if (s.charAt(i) === '}') { throw new Error("Bad substitution: " + s.substr(i - 2, 3)); } varend = s.indexOf('}', i); if (varend < 0) { throw new Error("Bad substitution: " + s.substr(i)); } varname = s.substr(i, varend - i); i = varend; } else if (/[*@#?$!_\-]/.test(s.charAt(i))) { varname = s.charAt(i); i += 1; } else { varend = s.substr(i).match(/[^\w\d_]/); if (!varend) { varname = s.substr(i); i = s.length; } else { varname = s.substr(i, varend.index); i += varend.index - 1; } } return getVar(null, '', varname); } }) // finalize parsed aruments .reduce(function(prev, arg){ if (arg === undefined){ return prev; } return prev.concat(arg); },[]); function getVar (_, pre, key) { var r = typeof env === 'function' ? env(key) : env[key]; if (r === undefined && key != '') r = ''; else if (r === undefined) r = '$'; if (typeof r === 'object') { return pre + TOKEN + JSON.stringify(r) + TOKEN; } else return pre + r; } } var osx = { '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets', '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl', '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text': '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl', '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code', '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron': 'code-insiders', '/Applications/AppCode.app/Contents/MacOS/appcode': '/Applications/AppCode.app/Contents/MacOS/appcode', '/Applications/CLion.app/Contents/MacOS/clion': '/Applications/CLion.app/Contents/MacOS/clion', '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea': '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea', '/Applications/PhpStorm.app/Contents/MacOS/phpstorm': '/Applications/PhpStorm.app/Contents/MacOS/phpstorm', '/Applications/PyCharm.app/Contents/MacOS/pycharm': '/Applications/PyCharm.app/Contents/MacOS/pycharm', '/Applications/PyCharm CE.app/Contents/MacOS/pycharm': '/Applications/PyCharm CE.app/Contents/MacOS/pycharm', '/Applications/RubyMine.app/Contents/MacOS/rubymine': '/Applications/RubyMine.app/Contents/MacOS/rubymine', '/Applications/WebStorm.app/Contents/MacOS/webstorm': '/Applications/WebStorm.app/Contents/MacOS/webstorm' }; var linux = { atom: 'atom', Brackets: 'brackets', code: 'code', emacs: 'emacs', 'idea.sh': 'idea', 'phpstorm.sh': 'phpstorm', 'pycharm.sh': 'pycharm', 'rubymine.sh': 'rubymine', sublime_text: 'subl', vim: 'vim', 'webstorm.sh': 'webstorm' }; var windows = [ 'Brackets.exe', 'Code.exe', 'atom.exe', 'sublime_text.exe', 'notepad++.exe', 'clion.exe', 'clion64.exe', 'idea.exe', 'idea64.exe', 'phpstorm.exe', 'phpstorm64.exe', 'pycharm.exe', 'pycharm64.exe', 'rubymine.exe', 'rubymine64.exe', 'webstorm.exe', 'webstorm64.exe' ]; const path$4 = path__default; const shellQuote = shellQuote$1; const childProcess$1 = require$$1__default$4; // Map from full process name to binary that starts the process // We can't just re-use full process name, because it will spawn a new instance // of the app every time const COMMON_EDITORS_OSX = osx; const COMMON_EDITORS_LINUX = linux; const COMMON_EDITORS_WIN = windows; var guess = function guessEditor (specifiedEditor) { if (specifiedEditor) { return shellQuote.parse(specifiedEditor) } // We can find out which editor is currently running by: // `ps x` on macOS and Linux // `Get-Process` on Windows try { if (process.platform === 'darwin') { const output = childProcess$1.execSync('ps x').toString(); const processNames = Object.keys(COMMON_EDITORS_OSX); for (let i = 0; i < processNames.length; i++) { const processName = processNames[i]; if (output.indexOf(processName) !== -1) { return [COMMON_EDITORS_OSX[processName]] } } } else if (process.platform === 'win32') { const output = childProcess$1 .execSync('powershell -Command "Get-Process | Select-Object Path"', { stdio: ['pipe', 'pipe', 'ignore'] }) .toString(); const runningProcesses = output.split('\r\n'); for (let i = 0; i < runningProcesses.length; i++) { // `Get-Process` sometimes returns empty lines if (!runningProcesses[i]) { continue } const fullProcessPath = runningProcesses[i].trim(); const shortProcessName = path$4.basename(fullProcessPath); if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) { return [fullProcessPath] } } } else if (process.platform === 'linux') { // --no-heading No header line // x List all processes owned by you // -o comm Need only names column const output = childProcess$1 .execSync('ps x --no-heading -o comm --sort=comm') .toString(); const processNames = Object.keys(COMMON_EDITORS_LINUX); for (let i = 0; i < processNames.length; i++) { const processName = processNames[i]; if (output.indexOf(processName) !== -1) { return [COMMON_EDITORS_LINUX[processName]] } } } } catch (error) { // Ignore... } // Last resort, use old skool env vars if (process.env.VISUAL) { return [process.env.VISUAL] } else if (process.env.EDITOR) { return [process.env.EDITOR] } return [null] }; const path$3 = path__default; // normalize file/line numbers into command line args for specific editors var getArgs = function getArgumentsForPosition ( editor, fileName, lineNumber, columnNumber = 1 ) { const editorBasename = path$3.basename(editor).replace(/\.(exe|cmd|bat)$/i, ''); switch (editorBasename) { case 'atom': case 'Atom': case 'Atom Beta': case 'subl': case 'sublime': case 'sublime_text': case 'wstorm': case 'charm': return [`${fileName}:${lineNumber}:${columnNumber}`] case 'notepad++': return ['-n' + lineNumber, fileName] case 'vim': case 'mvim': return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName] case 'joe': return ['+' + `${lineNumber}`, fileName] case 'emacs': case 'emacsclient': return [`+${lineNumber}:${columnNumber}`, fileName] case 'rmate': case 'mate': case 'mine': return ['--line', lineNumber, fileName] case 'code': case 'code-insiders': case 'Code': return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`] case 'appcode': case 'clion': case 'clion64': case 'idea': case 'idea64': case 'phpstorm': case 'phpstorm64': case 'pycharm': case 'pycharm64': case 'rubymine': case 'rubymine64': case 'webstorm': case 'webstorm64': return ['--line', lineNumber, fileName] } // For all others, drop the lineNumber until we have // a mapping above, since providing the lineNumber incorrectly // can result in errors or confusing behavior. return [fileName] }; /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file at * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE * * Modified by Yuxi Evan You */ const fs$1 = fs__default; const os$1 = require$$0__default$1; const path$2 = path__default; const chalk = chalk$1.exports; const childProcess = require$$1__default$4; const guessEditor = guess; const getArgumentsForPosition = getArgs; function wrapErrorCallback (cb) { return (fileName, errorMessage) => { console.log(); console.log( chalk.red('Could not open ' + path$2.basename(fileName) + ' in the editor.') ); if (errorMessage) { if (errorMessage[errorMessage.length - 1] !== '.') { errorMessage += '.'; } console.log( chalk.red('The editor process exited with an error: ' + errorMessage) ); } console.log(); if (cb) cb(fileName, errorMessage); } } function isTerminalEditor (editor) { switch (editor) { case 'vim': case 'emacs': case 'nano': return true } return false } const positionRE = /:(\d+)(:(\d+))?$/; function parseFile (file) { const fileName = file.replace(positionRE, ''); const match = file.match(positionRE); const lineNumber = match && match[1]; const columnNumber = match && match[3]; return { fileName, lineNumber, columnNumber } } let _childProcess = null; function launchEditor (file, specifiedEditor, onErrorCallback) { const parsed = parseFile(file); let { fileName } = parsed; const { lineNumber, columnNumber } = parsed; if (!fs$1.existsSync(fileName)) { return } if (typeof specifiedEditor === 'function') { onErrorCallback = specifiedEditor; specifiedEditor = undefined; } onErrorCallback = wrapErrorCallback(onErrorCallback); const [editor, ...args] = guessEditor(specifiedEditor); if (!editor) { onErrorCallback(fileName, null); return } if ( process.platform === 'linux' && fileName.startsWith('/mnt/') && /Microsoft/i.test(os$1.release()) ) { // Assume WSL / "Bash on Ubuntu on Windows" is being used, and // that the file exists on the Windows file system. // `os.release()` is "4.4.0-43-Microsoft" in the current release // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 // When a Windows editor is specified, interop functionality can // handle the path translation, but only if a relative path is used. fileName = path$2.relative('', fileName); } if (lineNumber) { const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber); args.push.apply(args, extraArgs); } else { args.push(fileName); } if (_childProcess && isTerminalEditor(editor)) { // There's an existing editor process already and it's attached // to the terminal, so go kill it. Otherwise two separate editor // instances attach to the stdin/stdout which gets confusing. _childProcess.kill('SIGKILL'); } if (process.platform === 'win32') { // On Windows, launch the editor in a shell because spawn can only // launch .exe files. _childProcess = childProcess.spawn( 'cmd.exe', ['/C', editor].concat(args), { stdio: 'inherit' } ); } else { _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' }); } _childProcess.on('exit', function (errorCode) { _childProcess = null; if (errorCode) { onErrorCallback(fileName, '(code ' + errorCode + ')'); } }); _childProcess.on('error', function (error) { onErrorCallback(fileName, error.message); }); } var launchEditor_1 = launchEditor; const url = require$$0__default$6; const path$1 = path__default; const launch = launchEditor_1; var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => { if (typeof specifiedEditor === 'function') { onErrorCallback = specifiedEditor; specifiedEditor = undefined; } if (typeof srcRoot === 'function') { onErrorCallback = srcRoot; srcRoot = undefined; } srcRoot = srcRoot || process.cwd(); return function launchEditorMiddleware (req, res, next) { const { file } = url.parse(req.url, true).query || {}; if (!file) { res.statusCode = 500; res.end(`launch-editor-middleware: required query param "file" is missing.`); } else { launch(path$1.resolve(srcRoot, file), specifiedEditor, onErrorCallback); res.end(); } } }; const externalTypes = [ 'css', // supported pre-processor types 'less', 'sass', 'scss', 'styl', 'stylus', 'pcss', 'postcss', // known SFC types 'vue', 'svelte', 'marko', 'astro', // JSX/TSX may be configured to be compiled differently from how esbuild // handles it by default, so exclude them as well 'jsx', 'tsx', ...KNOWN_ASSET_TYPES ]; function esbuildDepPlugin(qualified, exportsData, config, ssr) { // default resolver which prefers ESM const _resolve = config.createResolver({ asSrc: false }); // cjs resolver that prefers Node const _resolveRequire = config.createResolver({ asSrc: false, isRequire: true }); const resolve = (id, importer, kind, resolveDir) => { let _importer; // explicit resolveDir - this is passed only during yarn pnp resolve for // entries if (resolveDir) { _importer = normalizePath$4(path__default.join(resolveDir, '*')); } else { // map importer ids to file paths for correct resolution _importer = importer in qualified ? qualified[importer] : importer; } const resolver = kind.startsWith('require') ? _resolveRequire : _resolve; return resolver(id, _importer, undefined, ssr); }; return { name: 'vite:dep-pre-bundle', setup(build) { // externalize assets and commonly known non-js file types build.onResolve({ filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`) }, async ({ path: id, importer, kind }) => { const resolved = await resolve(id, importer, kind); if (resolved) { return { path: resolved, external: true }; } }); function resolveEntry(id) { const flatId = flattenId(id); if (flatId in qualified) { return { path: flatId, namespace: 'dep' }; } } build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { // ensure esbuild uses our resolved entries let entry; // if this is an entry, return entry namespace resolve result if (!importer) { if ((entry = resolveEntry(id))) return entry; // check if this is aliased to an entry - also return entry namespace const aliased = await _resolve(id, undefined, true); if (aliased && (entry = resolveEntry(aliased))) { return entry; } } // use vite's own resolver const resolved = await resolve(id, importer, kind); if (resolved) { if (resolved.startsWith(browserExternalId)) { return { path: id, namespace: 'browser-external' }; } if (isExternalUrl(resolved)) { return { path: resolved, external: true }; } return { path: path__default.resolve(resolved) }; } }); // For entry files, we'll read it ourselves and construct a proxy module // to retain the entry's raw id instead of file path so that esbuild // outputs desired output file structure. // It is necessary to do the re-exporting to separate the virtual proxy // module from the actual module since the actual module may get // referenced via relative imports - if we don't separate the proxy and // the actual module, esbuild will create duplicated copies of the same // module! const root = path__default.resolve(config.root); build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => { const entryFile = qualified[id]; let relativePath = normalizePath$4(path__default.relative(root, entryFile)); if (!relativePath.startsWith('./') && !relativePath.startsWith('../') && relativePath !== '.') { relativePath = `./${relativePath}`; } let contents = ''; const data = exportsData[id]; const [imports, exports] = data; if (!imports.length && !exports.length) { // cjs contents += `export default require("${relativePath}");`; } else { if (exports.includes('default')) { contents += `import d from "${relativePath}";export default d;`; } if (data.hasReExports || exports.length > 1 || exports[0] !== 'default') { contents += `\nexport * from "${relativePath}"`; } } let ext = path__default.extname(entryFile).slice(1); if (ext === 'mjs') ext = 'js'; return { loader: ext, contents, resolveDir: root }; }); build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => { return { contents: `export default new Proxy({}, { get() { throw new Error('Module "${id}" has been externalized for ` + `browser compatibility and cannot be accessed in client code.') } })` }; }); // yarn 2 pnp compat if (isRunningWithYarnPnp) { build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({ // pass along resolveDir for entries path: await resolve(path, importer, kind, resolveDir) })); build.onLoad({ filter: /.*/ }, async (args) => ({ contents: await require('fs').promises.readFile(args.path), loader: 'default' })); } } }; } const debug$3 = createDebugger('vite:deps'); async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started ssr) { var _a, _b, _c, _d; config = { ...config, command: 'build' }; const { root, logger, cacheDir } = config; const log = asCommand ? logger.info : debug$3; if (!cacheDir) { log(`No cache directory. Skipping.`); return null; } const dataPath = path__default.join(cacheDir, '_metadata.json'); const mainHash = getDepHash(root, config); const data = { hash: mainHash, browserHash: mainHash, optimized: {} }; if (!force) { let prevData; try { prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8')); } catch (e) { } // hash is consistent, no need to re-bundle if (prevData && prevData.hash === data.hash) { log('Hash is consistent. Skipping. Use --force to override.'); return prevData; } } if (fs__default.existsSync(cacheDir)) { emptyDir(cacheDir); } else { fs__default.mkdirSync(cacheDir, { recursive: true }); } // a hint for Node.js // all files in the cache directory should be recognized as ES modules writeFile(path__default.resolve(cacheDir, 'package.json'), JSON.stringify({ type: 'module' })); let deps, missing; if (!newDeps) { ({ deps, missing } = await scanImports(config)); } else { deps = newDeps; missing = {}; } // update browser hash data.browserHash = require$$1.createHash('sha256') .update(data.hash + JSON.stringify(deps)) .digest('hex') .substr(0, 8); const missingIds = Object.keys(missing); if (missingIds.length) { throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`) .join(`\n `)}\n\nAre they installed?`); } const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include; if (include) { const resolve = config.createResolver({ asSrc: false }); for (const id of include) { // normalize 'foo >bar` as 'foo > bar' to prevent same id being added // and for pretty printing const normalizedId = normalizeId$1(id); if (!deps[normalizedId]) { const entry = await resolve(id); if (entry) { deps[normalizedId] = entry; } else { throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`); } } } } const qualifiedIds = Object.keys(deps); if (!qualifiedIds.length) { writeFile(dataPath, JSON.stringify(data, null, 2)); log(`No dependencies to bundle. Skipping.\n\n\n`); return data; } const total = qualifiedIds.length; const maxListed = 5; const listed = Math.min(total, maxListed); const extra = Math.max(0, total - maxListed); const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) + (extra > 0 ? `\n (...and ${extra} more)` : ``)); if (!asCommand) { if (!newDeps) { // This is auto run on server start - let the user know that we are // pre-optimizing deps logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`)); logger.info(`(this will be run only when your dependencies or config have changed)`); } } else { logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`)); } // esbuild generates nested directory output with lowest common ancestor base // this is unpredictable and makes it difficult to analyze entry / output // mapping. So what we do here is: // 1. flatten all ids to eliminate slash // 2. in the plugin, read the entry ourselves as virtual files to retain the // path. const flatIdDeps = {}; const idToExports = {}; const flatIdToExports = {}; const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {}; await init; for (const id in deps) { const flatId = flattenId(id); const filePath = (flatIdDeps[flatId] = deps[id]); const entryContent = fs__default.readFileSync(filePath, 'utf-8'); let exportsData; try { exportsData = parse$f(entryContent); } catch { debug$3(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`); const transformed = await transformWithEsbuild(entryContent, filePath, { loader: 'jsx' }); // Ensure that optimization won't fail by defaulting '.js' to the JSX parser. // This is useful for packages such as Gatsby. esbuildOptions.loader = { '.js': 'jsx', ...esbuildOptions.loader }; exportsData = parse$f(transformed.code); } for (const { ss, se } of exportsData[0]) { const exp = entryContent.slice(ss, se); if (/export\s+\*\s+from/.test(exp)) { exportsData.hasReExports = true; } } idToExports[id] = exportsData; flatIdToExports[flatId] = exportsData; } const define = { 'process.env.NODE_ENV': JSON.stringify(config.mode) }; for (const key in config.define) { const value = config.define[key]; define[key] = typeof value === 'string' ? value : JSON.stringify(value); } const start = perf_hooks.performance.now(); const result = await esbuild.build({ absWorkingDir: process.cwd(), entryPoints: Object.keys(flatIdDeps), bundle: true, format: 'esm', target: config.build.target || undefined, external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude, logLevel: 'error', splitting: true, sourcemap: true, outdir: cacheDir, ignoreAnnotations: true, metafile: true, define, plugins: [ ...plugins, esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr) ], ...esbuildOptions }); const meta = result.metafile; // the paths in `meta.outputs` are relative to `process.cwd()` const cacheDirOutputPath = path__default.relative(process.cwd(), cacheDir); for (const id in deps) { const entry = deps[id]; data.optimized[id] = { file: normalizePath$4(path__default.resolve(cacheDir, flattenId(id) + '.js')), src: entry, needsInterop: needsInterop(id, idToExports[id], meta.outputs, cacheDirOutputPath) }; } writeFile(dataPath, JSON.stringify(data, null, 2)); debug$3(`deps bundled in ${(perf_hooks.performance.now() - start).toFixed(2)}ms`); return data; } // https://github.com/vitejs/vite/issues/1724#issuecomment-767619642 // a list of modules that pretends to be ESM but still uses `require`. // this causes esbuild to wrap them as CJS even when its entry appears to be ESM. const KNOWN_INTEROP_IDS = new Set(['moment']); function needsInterop(id, exportsData, outputs, cacheDirOutputPath) { if (KNOWN_INTEROP_IDS.has(id)) { return true; } const [imports, exports] = exportsData; // entry has no ESM syntax - likely CJS or UMD if (!exports.length && !imports.length) { return true; } // if a peer dependency used require() on a ESM dependency, esbuild turns the // ESM dependency's entry chunk into a single default export... detect // such cases by checking exports mismatch, and force interop. const flatId = flattenId(id) + '.js'; let generatedExports; for (const output in outputs) { if (normalizePath$4(output) === normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) { generatedExports = outputs[output].exports; break; } } if (!generatedExports || (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) { return true; } return false; } function isSingleDefaultExport(exports) { return exports.length === 1 && exports[0] === 'default'; } const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']; function getDepHash(root, config) { var _a, _b; let content = lookupFile(root, lockfileFormats) || ''; // also take config into account // only a subset of config options that can affect dep optimization content += JSON.stringify({ mode: config.mode, root: config.root, resolve: config.resolve, assetsInclude: config.assetsInclude, plugins: config.plugins.map((p) => p.name), optimizeDeps: { include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include, exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude } }, (_, value) => { if (typeof value === 'function' || value instanceof RegExp) { return value.toString(); } return value; }); return require$$1.createHash('sha256').update(content).digest('hex').substr(0, 8); } var index$1 = { __proto__: null, optimizeDeps: optimizeDeps }; var sourceMapGenerator = {}; var base64Vlq = {}; var base64$1 = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ base64$1.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ base64$1.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var base64 = base64$1; // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ base64Vlq.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; var util$5 = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ (function (exports) { /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || urlRegexp.test(aPath); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; // aStr2 !== null } if (aStr2 === null) { return -1; // aStr1 !== null } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /** * Strip any JSON XSSI avoidance prefix from the string (as documented * in the source maps specification), and then parse the string as * JSON. */ function parseSourceMapInput(str) { return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); } exports.parseSourceMapInput = parseSourceMapInput; /** * Compute the URL of a source given the the source root, the source's * URL, and the source map's URL. */ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ''; if (sourceRoot) { // This follows what Chrome does. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { sourceRoot += '/'; } // The spec says: // Line 4: An optional source root, useful for relocating source // files on a server or removing repeated values in the // “sources” entry. This value is prepended to the individual // entries in the “source” field. sourceURL = sourceRoot + sourceURL; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter. This mode is still somewhat supported, which is why // this code block is conditional. However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec. This block is basically the equivalent of: // new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: // If the sources are not absolute URLs after prepending of the // “sourceRoot”, the sources are resolved relative to the // SourceMap (like resolving script src in a html document). if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { // Strip the last path component, but keep the "/". var index = parsed.path.lastIndexOf('/'); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; }(util$5)); var arraySet = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util$4 = util$5; var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet$2() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet$2(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet$2.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet$2.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util$4.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util$4.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet$2.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet$2.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; arraySet.ArraySet = ArraySet$2; var mappingList = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util$3 = util$5; /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList$1() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList$1.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList$1.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList$1.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util$3.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; mappingList.MappingList = MappingList$1; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ$1 = base64Vlq; var util$2 = util$5; var ArraySet$1 = arraySet.ArraySet; var MappingList = mappingList.MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator$1(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util$2.getArg(aArgs, 'file', null); this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet$1(); this._names = new ArraySet$1(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator$1.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator$1.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator$1({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util$2.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util$2.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator$1.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util$2.getArg(aArgs, 'generated'); var original = util$2.getArg(aArgs, 'original', null); var source = util$2.getArg(aArgs, 'source', null); var name = util$2.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator$1.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util$2.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util$2.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util$2.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator$1.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util$2.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet$1(); var newNames = new ArraySet$1(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util$2.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util$2.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util$2.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util$2.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator$1.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator$1.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = ''; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ$1.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ$1.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ$1.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ$1.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ$1.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator$1.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util$2.relative(aSourceRoot, source); } var key = util$2.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator$1.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator$1.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$1; var sourceMapConsumer = {}; var binarySearch$1 = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ (function (exports) { /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; }(binarySearch$1)); var quickSort$1 = {}; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ quickSort$1.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util$1 = util$5; var binarySearch = binarySearch$1; var ArraySet = arraySet.ArraySet; var base64VLQ = base64Vlq; var quickSort = quickSort$1.quickSort; function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util$1.parseSourceMapInput(aSourceMap); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); } SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer$1.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer$1.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { configurable: true, enumerable: true, get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer$1.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { configurable: true, enumerable: true, get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer$1.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer$1.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer$1.GENERATED_ORDER = 1; SourceMapConsumer$1.ORIGINAL_ORDER = 2; SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer$1.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer$1.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer$1.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL); return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number is 1-based. * - column: Optional. the column number in the original source. * The column number is 0-based. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ SourceMapConsumer$1.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util$1.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util$1.getArg(aArgs, 'source'), originalLine: line, originalColumn: util$1.getArg(aArgs, 'column', 0) }; needle.source = this._findSourceIndex(needle.source); if (needle.source < 0) { return []; } var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util$1.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util$1.getArg(mapping, 'generatedLine', null), column: util$1.getArg(mapping, 'generatedColumn', null), lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util$1.getArg(mapping, 'generatedLine', null), column: util$1.getArg(mapping, 'generatedColumn', null), lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The first parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * The second parameter, if given, is a string whose value is the URL * at which the source map was found. This URL is used to compute the * sources array. * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util$1.parseSourceMapInput(aSourceMap); } var version = util$1.getArg(sourceMap, 'version'); var sources = util$1.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util$1.getArg(sourceMap, 'names', []); var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null); var mappings = util$1.getArg(sourceMap, 'mappings'); var file = util$1.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } if (sourceRoot) { sourceRoot = util$1.normalize(sourceRoot); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util$1.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) ? util$1.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function (s) { return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; /** * Utility function to find the index of a source. Returns -1 if not * found. */ BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util$1.relative(this.sourceRoot, relativeSource); } if (this._sources.has(relativeSource)) { return this._sources.indexOf(relativeSource); } // Maybe aSource is an absolute URL as returned by |sources|. In // this case we can't simply undo the transform. var i; for (i = 0; i < this._absoluteSources.length; ++i) { if (this._absoluteSources[i] == aSource) { return i; } } return -1; }; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @param String aSourceMapURL * The URL at which the source map can be found (optional) * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc._sourceMapURL = aSourceMapURL; smc._absoluteSources = smc._sources.toArray().map(function (s) { return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); }); // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util$1.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._absoluteSources.slice(); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util$1.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. The line number * is 1-based. * - column: The column number in the generated source. The column * number is 0-based. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. The * line number is 1-based. * - column: The column number in the original source, or null. The * column number is 0-based. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util$1.getArg(aArgs, 'line'), generatedColumn: util$1.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util$1.compareByGeneratedPositionsDeflated, util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util$1.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); } var name = util$1.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util$1.getArg(mapping, 'originalLine', null), column: util$1.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } var index = this._findSourceIndex(aSource); if (index >= 0) { return this.sourcesContent[index]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util$1.relative(this.sourceRoot, relativeSource); } var url; if (this.sourceRoot != null && (url = util$1.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) { return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + relativeSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number * is 1-based. * - column: The column number in the original source. The column * number is 0-based. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util$1.getArg(aArgs, 'source'); source = this._findSourceIndex(source); if (source < 0) { return { line: null, column: null, lastColumn: null }; } var needle = { source: source, originalLine: util$1.getArg(aArgs, 'line'), originalColumn: util$1.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util$1.compareByOriginalPositions, util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util$1.getArg(mapping, 'generatedLine', null), column: util$1.getArg(mapping, 'generatedColumn', null), lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The first parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * The second parameter, if given, is a string whose value is the URL * at which the source map was found. This URL is used to compute the * sources array. * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = util$1.parseSourceMapInput(aSourceMap); } var version = util$1.getArg(sourceMap, 'version'); var sections = util$1.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util$1.getArg(s, 'offset'); var offsetLine = util$1.getArg(offset, 'line'); var offsetColumn = util$1.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. The line number * is 1-based. * - column: The column number in the generated source. The column * number is 0-based. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. The * line number is 1-based. * - column: The column number in the original source, or null. The * column number is 0-based. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util$1.getArg(aArgs, 'line'), generatedColumn: util$1.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. The line number * is 1-based. * - column: The column number in the original source. The column * number is 0-based. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. The * line number is 1-based. * - column: The column number in the generated source, or null. * The column number is 0-based. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); this._sources.add(source); source = this._sources.indexOf(source); var name = null; if (mapping.name) { name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); } // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util$1.compareByOriginalPositions); }; sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer; /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; var util = util$5; // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex] || ''; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex] || ''; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; let offset; try { new Function('throw new Error(1)')(); } catch (e) { // in Node 12, stack traces account for the function wrapper. // in Node 13 and later, the function wrapper adds two lines, // which must be subtracted to generate a valid mapping const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]); offset = match ? +match[1] - 1 : 0; } function ssrRewriteStacktrace(stack, moduleGraph) { return stack .split('\n') .map((line) => { return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => { var _a; if (!url) return input; const mod = moduleGraph.urlToModuleMap.get(url); const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map; if (!rawSourceMap) { return input; } const consumer = new SourceMapConsumer(rawSourceMap); const pos = consumer.originalPositionFor({ line: Number(line) - offset, column: Number(column), bias: SourceMapConsumer.LEAST_UPPER_BOUND }); if (!pos.source) { return input; } const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`; if (!varName || varName === 'eval') { return ` at ${source}`; } else { return ` at ${varName} (${source})`; } }); }) .join('\n'); } function rebindErrorStacktrace(e, stacktrace) { const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack'); if (configurable) { Object.defineProperty(e, 'stack', { value: stacktrace, enumerable: true, configurable: true, writable: true }); } else if (writable) { e.stack = stacktrace; } } const pendingModules = new Map(); const pendingImports = new Map(); async function ssrLoadModule(url, server, context = { global }, urlStack = []) { url = unwrapId$1(url); // when we instantiate multiple dependency modules in parallel, they may // point to shared modules. We need to avoid duplicate instantiation attempts // by register every module as pending synchronously so that all subsequent // request to that module are simply waiting on the same promise. const pending = pendingModules.get(url); if (pending) { return pending; } const modulePromise = instantiateModule(url, server, context, urlStack); pendingModules.set(url, modulePromise); modulePromise .catch(() => { pendingImports.delete(url); }) .finally(() => { pendingModules.delete(url); }); return modulePromise; } async function instantiateModule(url, server, context = { global }, urlStack = []) { const { moduleGraph } = server; const mod = await moduleGraph.ensureEntryFromUrl(url); if (mod.ssrModule) { return mod.ssrModule; } const result = mod.ssrTransformResult || (await transformRequest(url, server, { ssr: true })); if (!result) { // TODO more info? is this even necessary? throw new Error(`failed to load module for ssr: ${url}`); } const ssrModule = { [Symbol.toStringTag]: 'Module' }; Object.defineProperty(ssrModule, '__esModule', { value: true }); // Tolerate circular imports by ensuring the module can be // referenced before it's been instantiated. mod.ssrModule = ssrModule; const ssrImportMeta = { // The filesystem URL, matching native Node.js modules url: require$$0$8.pathToFileURL(mod.file).toString(), }; urlStack = urlStack.concat(url); const isCircular = (url) => urlStack.includes(url); // Since dynamic imports can happen in parallel, we need to // account for multiple pending deps and duplicate imports. const pendingDeps = []; const ssrImport = async (dep) => { var _a, _b; if (dep[0] !== '.' && dep[0] !== '/') { return nodeRequire(dep, mod.file, server.config.root, !!server.config.resolve.preserveSymlinks); } dep = unwrapId$1(dep); if (!isCircular(dep) && !((_a = pendingImports.get(dep)) === null || _a === void 0 ? void 0 : _a.some(isCircular))) { pendingDeps.push(dep); if (pendingDeps.length === 1) { pendingImports.set(url, pendingDeps); } await ssrLoadModule(dep, server, context, urlStack); if (pendingDeps.length === 1) { pendingImports.delete(url); } else { pendingDeps.splice(pendingDeps.indexOf(dep), 1); } } return (_b = moduleGraph.urlToModuleMap.get(dep)) === null || _b === void 0 ? void 0 : _b.ssrModule; }; const ssrDynamicImport = (dep) => { // #3087 dynamic import vars is ignored at rewrite import path, // so here need process relative path if (dep[0] === '.') { dep = path__default.posix.resolve(path__default.dirname(url), dep); } return ssrImport(dep); }; function ssrExportAll(sourceModule) { for (const key in sourceModule) { if (key !== 'default') { Object.defineProperty(ssrModule, key, { enumerable: true, configurable: true, get() { return sourceModule[key]; } }); } } } try { // eslint-disable-next-line @typescript-eslint/no-empty-function const AsyncFunction = async function () { }.constructor; const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`); await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll); } catch (e) { const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); rebindErrorStacktrace(e, stacktrace); server.config.logger.error(`Error when evaluating SSR module ${url}:\n${stacktrace}`, { timestamp: true, clear: server.config.clearScreen, error: e }); throw e; } return Object.freeze(ssrModule); } function nodeRequire(id, importer, root, preserveSymlinks) { const mod = require(resolve(id, importer, root, preserveSymlinks)); const defaultExport = mod.__esModule ? mod.default : mod; // rollup-style default import interop for cjs return new Proxy(mod, { get(mod, prop) { if (prop === 'default') return defaultExport; return mod[prop]; } }); } const resolveCache = new Map(); function resolve(id, importer, root, preserveSymlinks) { const key = id + importer + root; const cached = resolveCache.get(key); if (cached) { return cached; } const resolveDir = importer && fs__default.existsSync(cleanUrl(importer)) ? path__default.dirname(importer) : root; const resolved = resolveFrom$3(id, resolveDir, preserveSymlinks, true); resolveCache.set(key, resolved); return resolved; } /** * The amount to wait for requests to register newly found dependencies before triggering * a re-bundle + page reload */ const debounceMs = 100; function createMissingImporterRegisterFn(server) { const { logger } = server.config; let knownOptimized = server._optimizeDepsMetadata.optimized; let currentMissing = {}; let handle; let pendingResolve = null; async function rerun(ssr) { const newDeps = currentMissing; currentMissing = {}; logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), { timestamp: true }); for (const id in knownOptimized) { newDeps[id] = knownOptimized[id].src; } try { // Nullify previous metadata so that the resolver won't // resolve to optimized files during the optimizer re-run server._isRunningOptimizer = true; server._optimizeDepsMetadata = null; const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps, ssr)); knownOptimized = newData.optimized; // update ssr externals server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized)); logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true }); } catch (e) { logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e }); } finally { server._isRunningOptimizer = false; pendingResolve && pendingResolve(); server._pendingReload = pendingResolve = null; } // Cached transform results have stale imports (resolved to // old locations) so they need to be invalidated before the page is // reloaded. server.moduleGraph.invalidateAll(); server.ws.send({ type: 'full-reload', path: '*' }); } return function registerMissingImport(id, resolved, ssr) { if (!knownOptimized[id]) { currentMissing[id] = resolved; if (handle) clearTimeout(handle); handle = setTimeout(() => rerun(ssr), debounceMs); server._pendingReload = new Promise((r) => { pendingResolve = r; }); } }; } // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 const ROOT_FILES = [ // '.git', // https://pnpm.js.org/workspaces/ 'pnpm-workspace.yaml' // https://rushjs.io/pages/advanced/config_files/ // 'rush.json', // https://nx.dev/latest/react/getting-started/nx-setup // 'workspace.json', // 'nx.json' ]; // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it function hasWorkspacePackageJSON(root) { const path = path$t.join(root, 'package.json'); if (!isFileReadable(path)) { return false; } const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {}; return !!content.workspaces; } function hasRootFile(root) { return ROOT_FILES.some((file) => fs__default.existsSync(path$t.join(root, file))); } function hasPackageJSON(root) { const path = path$t.join(root, 'package.json'); return fs__default.existsSync(path); } /** * Search up for the nearest `package.json` */ function searchForPackageRoot(current, root = current) { if (hasPackageJSON(current)) return current; const dir = path$t.dirname(current); // reach the fs root if (!dir || dir === current) return root; return searchForPackageRoot(dir, root); } /** * Search up for the nearest workspace root */ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { if (hasRootFile(current)) return current; if (hasWorkspacePackageJSON(current)) return current; const dir = path$t.dirname(current); // reach the fs root if (!dir || dir === current) return root; return searchForWorkspaceRoot(dir, root); } async function createServer(inlineConfig = {}) { const config = await resolveConfig(inlineConfig, 'serve', 'development'); const root = config.root; const serverConfig = config.server; const httpsOptions = await resolveHttpsConfig(config); let { middlewareMode } = serverConfig; if (middlewareMode === true) { middlewareMode = 'ssr'; } const middlewares = connect(); const httpServer = middlewareMode ? null : await resolveHttpServer(serverConfig, middlewares, httpsOptions); const ws = createWebSocketServer(httpServer, config, httpsOptions); const { ignored = [], ...watchOptions } = serverConfig.watch || {}; const watcher = chokidar.watch(path__default.resolve(root), { ignored: [ '**/node_modules/**', '**/.git/**', ...(Array.isArray(ignored) ? ignored : [ignored]) ], ignoreInitial: true, ignorePermissionErrors: true, disableGlobbing: true, ...watchOptions }); const plugins = config.plugins; const container = await createPluginContainer(config, watcher); const moduleGraph = new ModuleGraph(container); const closeHttpServer = createServerCloseFn(httpServer); // eslint-disable-next-line prefer-const let exitProcess; const server = { config, middlewares, get app() { config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`); return middlewares; }, httpServer, watcher, pluginContainer: container, ws, moduleGraph, transformWithEsbuild, transformRequest(url, options) { return transformRequest(url, server, options); }, transformIndexHtml: null, ssrLoadModule(url) { if (!server._ssrExternals) { server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata ? Object.keys(server._optimizeDepsMetadata.optimized) : []); } return ssrLoadModule(url, server); }, ssrFixStacktrace(e) { if (e.stack) { const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); rebindErrorStacktrace(e, stacktrace); } }, listen(port, isRestart) { return startServer(server, port, isRestart); }, async close() { process.off('SIGTERM', exitProcess); if (!middlewareMode && process.env.CI !== 'true') { process.stdin.off('end', exitProcess); } await Promise.all([ watcher.close(), ws.close(), container.close(), closeHttpServer() ]); }, printUrls() { if (httpServer) { printHttpServerUrls(httpServer, config); } else { throw new Error('cannot print server URLs in middleware mode.'); } }, _optimizeDepsMetadata: null, _ssrExternals: null, _globImporters: Object.create(null), _isRunningOptimizer: false, _registerMissingImport: null, _pendingReload: null, _pendingRequests: Object.create(null) }; server.transformIndexHtml = createDevHtmlTransformFn(server); exitProcess = async () => { try { await server.close(); } finally { process.exit(0); } }; process.once('SIGTERM', exitProcess); if (!middlewareMode && process.env.CI !== 'true') { process.stdin.on('end', exitProcess); } watcher.on('change', async (file) => { file = normalizePath$4(file); // invalidate module graph cache on file change moduleGraph.onFileChange(file); if (serverConfig.hmr !== false) { try { await handleHMRUpdate(file, server); } catch (err) { ws.send({ type: 'error', err: prepareError(err) }); } } }); watcher.on('add', (file) => { handleFileAddUnlink(normalizePath$4(file), server); }); watcher.on('unlink', (file) => { handleFileAddUnlink(normalizePath$4(file), server, true); }); if (!middlewareMode && httpServer) { httpServer.once('listening', () => { // update actual port since this may be different from initial value serverConfig.port = httpServer.address().port; }); } // apply server configuration hooks from plugins const postHooks = []; for (const plugin of plugins) { if (plugin.configureServer) { postHooks.push(await plugin.configureServer(server)); } } // Internal middlewares ------------------------------------------------------ // request timer if (process.env.DEBUG) { middlewares.use(timeMiddleware(root)); } // cors (enabled by default) const { cors } = serverConfig; if (cors !== false) { middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); } // proxy const { proxy } = serverConfig; if (proxy) { middlewares.use(proxyMiddleware(httpServer, config)); } // base if (config.base !== '/') { middlewares.use(baseMiddleware(server)); } // open in editor support middlewares.use('/__open-in-editor', launchEditorMiddleware()); // hmr reconnect ping // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) { res.end('pong'); }); // serve static files under /public // this applies before the transform middleware so that these files are served // as-is without transforms. if (config.publicDir) { middlewares.use(servePublicMiddleware(config.publicDir)); } // main transform middleware middlewares.use(transformMiddleware(server)); // serve static files middlewares.use(serveRawFsMiddleware(server)); middlewares.use(serveStaticMiddleware(root, server)); // spa fallback if (!middlewareMode || middlewareMode === 'html') { middlewares.use(spaFallbackMiddleware(root)); } // run post config hooks // This is applied before the html middleware so that user middleware can // serve custom content instead of index.html. postHooks.forEach((fn) => fn && fn()); if (!middlewareMode || middlewareMode === 'html') { // transform index.html middlewares.use(indexHtmlMiddleware(server)); // handle 404s // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` middlewares.use(function vite404Middleware(_, res) { res.statusCode = 404; res.end(); }); } // error handler middlewares.use(errorMiddleware(server, !!middlewareMode)); const runOptimize = async () => { if (config.cacheDir) { server._isRunningOptimizer = true; try { server._optimizeDepsMetadata = await optimizeDeps(config); } finally { server._isRunningOptimizer = false; } server._registerMissingImport = createMissingImporterRegisterFn(server); } }; if (!middlewareMode && httpServer) { let isOptimized = false; // overwrite listen to run optimizer before server start const listen = httpServer.listen.bind(httpServer); httpServer.listen = (async (port, ...args) => { if (!isOptimized) { try { await container.buildStart({}); await runOptimize(); isOptimized = true; } catch (e) { httpServer.emit('error', e); return; } } return listen(port, ...args); }); } else { await container.buildStart({}); await runOptimize(); } return server; } async function startServer(server, inlinePort, isRestart = false) { const httpServer = server.httpServer; if (!httpServer) { throw new Error('Cannot call server.listen in middleware mode.'); } const options = server.config.server; const port = inlinePort || options.port || 3000; const hostname = resolveHostname(options.host); const protocol = options.https ? 'https' : 'http'; const info = server.config.logger.info; const base = server.config.base; const serverPort = await httpServerStart(httpServer, { port, strictPort: options.strictPort, host: hostname.host, logger: server.config.logger }); // @ts-ignore const profileSession = global.__vite_profile_session; if (profileSession) { profileSession.post('Profiler.stop', (err, { profile }) => { // Write profile to disk, upload, etc. if (!err) { const outPath = path__default.resolve('./vite-profile.cpuprofile'); fs__default.writeFileSync(outPath, JSON.stringify(profile)); info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`)); } else { throw err; } }); } if (options.open && !isRestart) { const path = typeof options.open === 'string' ? options.open : base; openBrowser(path.startsWith('http') ? path : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger); } return server; } function createServerCloseFn(server) { if (!server) { return () => { }; } let hasListened = false; const openSockets = new Set(); server.on('connection', (socket) => { openSockets.add(socket); socket.on('close', () => { openSockets.delete(socket); }); }); server.once('listening', () => { hasListened = true; }); return () => new Promise((resolve, reject) => { openSockets.forEach((s) => s.destroy()); if (hasListened) { server.close((err) => { if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); } function resolvedAllowDir(root, dir) { return ensureLeadingSlash(normalizePath$4(path__default.resolve(root, dir))); } function resolveServerOptions(root, raw) { var _a, _b; const server = raw || {}; let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow; if (!allowDirs) { allowDirs = [searchForWorkspaceRoot(root)]; } allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); // only push client dir when vite itself is outside-of-root const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) { allowDirs.push(resolvedClientDir); } server.fs = { // TODO: make strict by default strict: (_b = server.fs) === null || _b === void 0 ? void 0 : _b.strict, allow: allowDirs }; return server; } var index = { __proto__: null, createServer: createServer, resolveServerOptions: resolveServerOptions, searchForWorkspaceRoot: searchForWorkspaceRoot }; const noop = () => null; function matches(pattern, importee) { if (pattern instanceof RegExp) { return pattern.test(importee); } if (importee.length < pattern.length) { return false; } if (importee === pattern) { return true; } const importeeStartsWithKey = importee.indexOf(pattern) === 0; const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/'; return importeeStartsWithKey && importeeHasSlashAfterKey; } function normalizeId(id) { return id; } function getEntries({ entries }) { if (!entries) { return []; } if (Array.isArray(entries)) { return entries; } return Object.entries(entries).map(([key, value]) => { return { find: key, replacement: value }; }); } function getCustomResolver({ customResolver }, options) { if (typeof customResolver === 'function') { return customResolver; } if (customResolver && typeof customResolver.resolveId === 'function') { return customResolver.resolveId; } if (typeof options.customResolver === 'function') { return options.customResolver; } if (options.customResolver && typeof options.customResolver.resolveId === 'function') { return options.customResolver.resolveId; } return null; } function alias(options = {}) { const entries = getEntries(options); if (entries.length === 0) { return { name: 'alias', resolveId: noop }; } return { name: 'alias', buildStart(inputOptions) { return Promise.all([...entries, options].map(({ customResolver }) => customResolver && typeof customResolver === 'object' && typeof customResolver.buildStart === 'function' && customResolver.buildStart.call(this, inputOptions))).then(() => { // enforce void return value }); }, resolveId(importee, importer) { const importeeId = normalizeId(importee); const importerId = normalizeId(importer); // First match is supposed to be the correct one const matchedEntry = entries.find((entry) => matches(entry.find, importeeId)); if (!matchedEntry || !importerId) { return null; } const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement)); const customResolver = getCustomResolver(matchedEntry, options); if (customResolver) { return customResolver.call(this, updatedId, importerId, {}); } return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => { let finalResult = resolved; if (!finalResult) { finalResult = { id: updatedId }; } return finalResult; }); } }; } /** * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js * * This source code is licensed under the MIT license found in the * LICENSE file at * https://github.com/rollup/plugins/blob/master/LICENSE */ // Custom json filter for vite const jsonExtRE = /\.json($|\?)(?!commonjs-(proxy|external))/; function jsonPlugin(options = {}, isBuild) { return { name: 'vite:json', transform(json, id) { if (!jsonExtRE.test(id)) return null; if (SPECIAL_QUERY_RE.test(id)) return null; try { if (options.stringify) { if (isBuild) { return { // during build, parse then double-stringify to remove all // unnecessary whitespaces to reduce bundle size. code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`, map: { mappings: '' } }; } else { return `export default JSON.parse(${JSON.stringify(json)})`; } } const parsed = JSON.parse(json); return { code: dataToEsm(parsed, { preferConst: true, namedExports: options.namedExports }), map: { mappings: '' } }; } catch (e) { const errorMessageList = /[\d]+/.exec(e.message); const position = errorMessageList && parseInt(errorMessageList[0], 10); const msg = position ? `, invalid JSON syntax found at line ${position}` : `.`; this.error(`Failed to parse JSON file` + msg, e.idx); } } }; } const isDebug = !!process.env.DEBUG; const debug$2 = createDebugger('vite:import-analysis'); const clientDir = normalizePath$4(CLIENT_DIR); const skipRE = /\.(map|json)$/; const canSkip = (id) => skipRE.test(id) || isDirectCSSRequest(id); function isExplicitImportRequired(url) { return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url); } function markExplicitImport(url) { if (isExplicitImportRequired(url)) { return injectQuery(url, 'import'); } return url; } /** * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. * * - Imports are resolved to ensure they exist on disk * * - Lexes HMR accept calls and updates import relationships in the module graph * * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to * absolute file paths, e.g. * * ```js * import 'foo' * ``` * is rewritten to * ```js * import '/@fs//project/node_modules/foo/dist/foo.js' * ``` * * - CSS imports are appended with `.js` since both the js module and the actual * css (referenced via ) may go through the transform pipeline: * * ```js * import './style.css' * ``` * is rewritten to * ```js * import './style.css.js' * ``` */ function importAnalysisPlugin(config) { const { root, base } = config; const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH); let server; return { name: 'vite:import-analysis', configureServer(_server) { server = _server; }, async transform(source$1, importer, ssr) { const prettyImporter = prettifyUrl(importer, root); if (canSkip(importer)) { isDebug && debug$2(source.dim(`[skipped] ${prettyImporter}`)); return null; } const start = perf_hooks.performance.now(); await init; let imports = []; // strip UTF-8 BOM if (source$1.charCodeAt(0) === 0xfeff) { source$1 = source$1.slice(1); } try { imports = parse$f(source$1)[0]; } catch (e) { const isVue = importer.endsWith('.vue'); const maybeJSX = !isVue && isJSRequest(importer); const msg = isVue ? `Install @vitejs/plugin-vue to handle .vue files.` : maybeJSX ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`; this.error(`Failed to parse source for import analysis because the content ` + `contains invalid JS syntax. ` + msg, e.idx); } if (!imports.length) { isDebug && debug$2(`${timeFrom(start)} ${source.dim(`[no imports] ${prettyImporter}`)}`); return source$1; } let hasHMR = false; let isSelfAccepting = false; let hasEnv = false; let needQueryInjectHelper = false; let s; const str = () => s || (s = new MagicString(source$1)); // vite-only server context const { moduleGraph } = server; // since we are already in the transform phase of the importer, it must // have been loaded so its entry is guaranteed in the module graph. const importerModule = moduleGraph.getModuleById(importer); const importedUrls = new Set(); const staticImportedUrls = new Set(); const acceptedUrls = new Set(); const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url); const normalizeUrl = async (url, pos) => { if (base !== '/' && url.startsWith(base)) { url = url.replace(base, '/'); } const resolved = await this.resolve(url, importer); if (!resolved) { this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importer)}". Does the file exist?`, pos); } const isRelative = url.startsWith('.'); const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer); // normalize all imports into resolved URLs // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` if (resolved.id.startsWith(root + '/')) { // in root: infer short absolute path from root url = resolved.id.slice(root.length); } else if (fs__default.existsSync(cleanUrl(resolved.id))) { // exists but out of root: rewrite to absolute /@fs/ paths url = path__default.posix.join(FS_PREFIX + resolved.id); } else { url = resolved.id; } if (isExternalUrl(url)) { return [url, url]; } // if the resolved id is not a valid browser import specifier, // prefix it to make it valid. We will strip this before feeding it // back into the transform pipeline if (!url.startsWith('.') && !url.startsWith('/')) { url = VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER); } // make the URL browser-valid if not SSR if (!ssr) { // mark non-js/css imports with `?import` url = markExplicitImport(url); // for relative js/css imports, or self-module virtual imports // (e.g. vue blocks), inherit importer's version query // do not do this for unknown type imports, otherwise the appended // query can break 3rd party plugin's extension checks. if ((isRelative || isSelfImport) && !/[\?&]import=?\b/.test(url)) { const versionMatch = importer.match(DEP_VERSION_RE); if (versionMatch) { url = injectQuery(url, versionMatch[1]); } } // check if the dep has been hmr updated. If yes, we need to attach // its last updated timestamp to force the browser to fetch the most // up-to-date version of this module. try { const depModule = await moduleGraph.ensureEntryFromUrl(url); if (depModule.lastHMRTimestamp > 0) { url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`); } } catch (e) { // it's possible that the dep fails to resolve (non-existent import) // attach location to the missing import e.pos = pos; throw e; } // prepend base (dev base is guaranteed to have ending slash) url = base + url.replace(/^\//, ''); } return [url, resolved.id]; }; for (let index = 0; index < imports.length; index++) { const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, // #2083 User may use escape path, // so use imports[index].n to get the unescaped string // @ts-ignore n: specifier } = imports[index]; const rawUrl = source$1.slice(start, end); // check import.meta usage if (rawUrl === 'import.meta') { const prop = source$1.slice(end, end + 4); if (prop === '.hot') { hasHMR = true; if (source$1.slice(end + 4, end + 11) === '.accept') { // further analyze accepted modules if (lexAcceptedHmrDeps(source$1, source$1.indexOf('(', end + 11) + 1, acceptedUrls)) { isSelfAccepting = true; } } } else if (prop === '.env') { hasEnv = true; } else if (prop === '.glo' && source$1[end + 4] === 'b') { // transform import.meta.glob() // e.g. `import.meta.glob('glob:./dir/*.js')` const { imports, importsString, exp, endIndex, base, pattern, isEager } = await transformImportGlob(source$1, start, importer, index, root, normalizeUrl); str().prepend(importsString); str().overwrite(expStart, endIndex, exp); imports.forEach((url) => { url = url.replace(base, '/'); importedUrls.add(url); if (isEager) staticImportedUrls.add(url); }); if (!(importerModule.file in server._globImporters)) { server._globImporters[importerModule.file] = { module: importerModule, importGlobs: [] }; } server._globImporters[importerModule.file].importGlobs.push({ base, pattern }); } continue; } const isDynamicImport = dynamicIndex >= 0; // static import or valid string in dynamic import // If resolvable, let's resolve it if (specifier) { // skip external / data uri if (isExternalUrl(specifier) || isDataUrl(specifier)) { continue; } // skip ssr external if (ssr) { if (server._ssrExternals && shouldExternalizeForSSR(specifier, server._ssrExternals)) { continue; } if (isBuiltin(specifier)) { continue; } } // skip client if (specifier === clientPublicPath) { continue; } // warn imports to non-asset /public files if (specifier.startsWith('/') && !config.assetsInclude(cleanUrl(specifier)) && !specifier.endsWith('.json') && checkPublicFile(specifier, config)) { throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` + `JS/CSS files inside /public are copied as-is on build and ` + `can only be referenced via