first commit

This commit is contained in:
becarta
2025-05-16 00:17:42 +02:00
parent ea5c866137
commit bacf566ec9
6020 changed files with 1715262 additions and 0 deletions

2406
node_modules/vite/LICENSE.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

20
node_modules/vite/README.md generated vendored Normal file
View File

@@ -0,0 +1,20 @@
# vite ⚡
> Next Generation Frontend Tooling
- 💡 Instant Server Start
- ⚡️ Lightning Fast HMR
- 🛠️ Rich Features
- 📦 Optimized Build
- 🔩 Universal Plugin Interface
- 🔑 Fully Typed APIs
Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts:
- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vite.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement).
- A [build command](https://vite.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production.
In addition, Vite is highly extensible via its [Plugin API](https://vite.dev/guide/api-plugin.html) and [JavaScript API](https://vite.dev/guide/api-javascript.html) with full typing support.
[Read the Docs to Learn More](https://vite.dev).

95
node_modules/vite/bin/openChrome.applescript generated vendored Normal file
View File

@@ -0,0 +1,95 @@
(*
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
*)
property targetTab: null
property targetTabIndex: -1
property targetWindow: null
property theProgram: "Google Chrome"
on run argv
set theURL to item 1 of argv
-- Allow requested program to be optional,
-- default to Google Chrome
if (count of argv) > 1 then
set theProgram to item 2 of argv
end if
using terms from application "Google Chrome"
tell application theProgram
if (count every window) = 0 then
make new window
end if
-- 1: Looking for tab running debugger
-- then, Reload debugging tab if found
-- then return
set found to my lookupTabWithUrl(theURL)
if found then
set targetWindow's active tab index to targetTabIndex
tell targetTab to reload
tell targetWindow to activate
set index of targetWindow to 1
return
end if
-- 2: Looking for Empty tab
-- In case debugging tab was not found
-- We try to find an empty tab instead
set found to my lookupTabWithUrl("chrome://newtab/")
if found then
set targetWindow's active tab index to targetTabIndex
set URL of targetTab to theURL
tell targetWindow to activate
return
end if
-- 3: Create new tab
-- both debugging and empty tab were not found
-- make a new tab with url
tell window 1
activate
make new tab with properties {URL:theURL}
end tell
end tell
end using terms from
end run
-- Function:
-- Lookup tab with given url
-- if found, store tab, index, and window in properties
-- (properties were declared on top of file)
on lookupTabWithUrl(lookupUrl)
using terms from application "Google Chrome"
tell application theProgram
-- Find a tab with the given url
set found to false
set theTabIndex to -1
repeat with theWindow in every window
set theTabIndex to 0
repeat with theTab in every tab of theWindow
set theTabIndex to theTabIndex + 1
if (theTab's URL as string) contains lookupUrl then
-- assign tab, tab index, and window to properties
set targetTab to theTab
set targetTabIndex to theTabIndex
set targetWindow to theWindow
set found to true
exit repeat
end if
end repeat
if found then
exit repeat
end if
end repeat
end tell
end using terms from
return found
end lookupTabWithUrl

79
node_modules/vite/bin/vite.js generated vendored Executable file
View File

@@ -0,0 +1,79 @@
#!/usr/bin/env node
import { performance } from 'node:perf_hooks'
import module from 'node:module'
if (!import.meta.url.includes('node_modules')) {
try {
// only available as dev dependency
await import('source-map-support').then((r) => r.default.install())
} catch {}
process.on('unhandledRejection', (err) => {
throw new Error('UNHANDLED PROMISE REJECTION', { cause: err })
})
}
global.__vite_start_time = performance.now()
// check debug mode first before requiring the CLI.
const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
const filterIndex = process.argv.findIndex((arg) =>
/^(?:-f|--filter)$/.test(arg),
)
const profileIndex = process.argv.indexOf('--profile')
if (debugIndex > 0) {
let value = process.argv[debugIndex + 1]
if (!value || value.startsWith('-')) {
value = 'vite:*'
} else {
// support debugging multiple flags with comma-separated list
value = value
.split(',')
.map((v) => `vite:${v}`)
.join(',')
}
process.env.DEBUG = `${
process.env.DEBUG ? process.env.DEBUG + ',' : ''
}${value}`
if (filterIndex > 0) {
const filter = process.argv[filterIndex + 1]
if (filter && !filter.startsWith('-')) {
process.env.VITE_DEBUG_FILTER = filter
}
}
}
function start() {
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists
module.enableCompileCache?.()
// flush the cache after 10s because the cache is not flushed until process end
// for dev server, the cache is never flushed unless manually flushed because the process.exit is called
// also flushing the cache in SIGINT handler seems to cause the process to hang
setTimeout(() => {
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists
module.flushCompileCache?.()
} catch {}
}, 10 * 1000).unref()
} catch {}
return import('../dist/node/cli.js')
}
if (profileIndex > 0) {
process.argv.splice(profileIndex, 1)
const next = process.argv[profileIndex]
if (next && !next.startsWith('-')) {
process.argv.splice(profileIndex, 1)
}
const inspector = await import('node:inspector').then((r) => r.default)
const session = (global.__vite_profile_session = new inspector.Session())
session.connect()
session.post('Profiler.enable', () => {
session.post('Profiler.start', start)
})
} else {
start()
}

279
node_modules/vite/client.d.ts generated vendored Normal file
View File

@@ -0,0 +1,279 @@
/// <reference path="./types/importMeta.d.ts" />
// CSS modules
type CSSModuleClasses = { readonly [key: string]: string }
declare module '*.module.css' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.scss' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.sass' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.less' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.styl' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.stylus' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.pcss' {
const classes: CSSModuleClasses
export default classes
}
declare module '*.module.sss' {
const classes: CSSModuleClasses
export default classes
}
// CSS
declare module '*.css' {}
declare module '*.scss' {}
declare module '*.sass' {}
declare module '*.less' {}
declare module '*.styl' {}
declare module '*.stylus' {}
declare module '*.pcss' {}
declare module '*.sss' {}
// Built-in asset types
// see `src/node/constants.ts`
// images
declare module '*.apng' {
const src: string
export default src
}
declare module '*.bmp' {
const src: string
export default src
}
declare module '*.png' {
const src: string
export default src
}
declare module '*.jpg' {
const src: string
export default src
}
declare module '*.jpeg' {
const src: string
export default src
}
declare module '*.jfif' {
const src: string
export default src
}
declare module '*.pjpeg' {
const src: string
export default src
}
declare module '*.pjp' {
const src: string
export default src
}
declare module '*.gif' {
const src: string
export default src
}
declare module '*.svg' {
const src: string
export default src
}
declare module '*.ico' {
const src: string
export default src
}
declare module '*.webp' {
const src: string
export default src
}
declare module '*.avif' {
const src: string
export default src
}
declare module '*.cur' {
const src: string
export default src
}
declare module '*.jxl' {
const src: string
export default src
}
// media
declare module '*.mp4' {
const src: string
export default src
}
declare module '*.webm' {
const src: string
export default src
}
declare module '*.ogg' {
const src: string
export default src
}
declare module '*.mp3' {
const src: string
export default src
}
declare module '*.wav' {
const src: string
export default src
}
declare module '*.flac' {
const src: string
export default src
}
declare module '*.aac' {
const src: string
export default src
}
declare module '*.opus' {
const src: string
export default src
}
declare module '*.mov' {
const src: string
export default src
}
declare module '*.m4a' {
const src: string
export default src
}
declare module '*.vtt' {
const src: string
export default src
}
// fonts
declare module '*.woff' {
const src: string
export default src
}
declare module '*.woff2' {
const src: string
export default src
}
declare module '*.eot' {
const src: string
export default src
}
declare module '*.ttf' {
const src: string
export default src
}
declare module '*.otf' {
const src: string
export default src
}
// other
declare module '*.webmanifest' {
const src: string
export default src
}
declare module '*.pdf' {
const src: string
export default src
}
declare module '*.txt' {
const src: string
export default src
}
// wasm?init
declare module '*.wasm?init' {
const initWasm: (
options?: WebAssembly.Imports,
) => Promise<WebAssembly.Instance>
export default initWasm
}
// web worker
declare module '*?worker' {
const workerConstructor: {
new (options?: { name?: string }): Worker
}
export default workerConstructor
}
declare module '*?worker&inline' {
const workerConstructor: {
new (options?: { name?: string }): Worker
}
export default workerConstructor
}
declare module '*?worker&url' {
const src: string
export default src
}
declare module '*?sharedworker' {
const sharedWorkerConstructor: {
new (options?: { name?: string }): SharedWorker
}
export default sharedWorkerConstructor
}
declare module '*?sharedworker&inline' {
const sharedWorkerConstructor: {
new (options?: { name?: string }): SharedWorker
}
export default sharedWorkerConstructor
}
declare module '*?sharedworker&url' {
const src: string
export default src
}
declare module '*?raw' {
const src: string
export default src
}
declare module '*?url' {
const src: string
export default src
}
declare module '*?inline' {
const src: string
export default src
}
declare module '*?no-inline' {
const src: string
export default src
}
declare module '*?url&inline' {
const src: string
export default src
}
declare module '*?url&no-inline' {
const src: string
export default src
}
declare interface VitePreloadErrorEvent extends Event {
payload: Error
}
declare interface WindowEventMap {
'vite:preloadError': VitePreloadErrorEvent
}

1134
node_modules/vite/dist/client/client.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

24
node_modules/vite/dist/client/env.mjs generated vendored Normal file
View File

@@ -0,0 +1,24 @@
const context = (() => {
if (typeof globalThis !== "undefined") {
return globalThis;
} else if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
return window;
} else {
return Function("return this")();
}
})();
const defines = __DEFINES__;
Object.keys(defines).forEach((key) => {
const segments = key.split(".");
let target = context;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
if (i === segments.length - 1) {
target[segment] = defines[key];
} else {
target = target[segment] || (target[segment] = {});
}
}
});

3986
node_modules/vite/dist/node-cjs/publicUtils.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

553
node_modules/vite/dist/node/chunks/dep-3RmXg9uo.js generated vendored Normal file
View File

@@ -0,0 +1,553 @@
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = "\\".charCodeAt(0);
var slash = "/".charCodeAt(0);
var comma = ",".charCodeAt(0);
var colon = ":".charCodeAt(0);
var star = "*".charCodeAt(0);
var uLower = "u".charCodeAt(0);
var uUpper = "U".charCodeAt(0);
var plus = "+".charCodeAt(0);
var isUnicodeRange = /^[a-f0-9?-]+$/i;
var parse$1 = function(input) {
var tokens = [];
var value = input;
var next,
quote,
prev,
token,
escape,
escapePos,
whitespacePos,
parenthesesOpenPos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === "div") {
prev.after = token;
prev.sourceEndIndex += token.length;
} else if (
code === comma ||
code === colon ||
(code === slash &&
value.charCodeAt(next + 1) !== star &&
(!parent ||
(parent && parent.type === "function" && parent.value !== "calc")))
) {
before = token;
} else {
tokens.push({
type: "space",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? "'" : '"';
token = {
type: "string",
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
token.sourceEndIndex = token.unclosed ? next : next + 1;
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
next = value.indexOf("*/", pos);
token = {
type: "comment",
sourceIndex: pos,
sourceEndIndex: next + 2
};
if (next === -1) {
token.unclosed = true;
next = value.length;
token.sourceEndIndex = next;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Operation within calc
} else if (
(code === slash || code === star) &&
parent &&
parent.type === "function" &&
parent.value === "calc"
) {
token = value[pos];
tokens.push({
type: "word",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token
});
pos += 1;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: "div",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token,
before: before,
after: ""
});
before = "";
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
parenthesesOpenPos = pos;
token = {
type: "function",
sourceIndex: pos - name.length,
value: name,
before: value.slice(parenthesesOpenPos + 1, next)
};
pos = next;
if (name === "url" && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(")", next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ")";
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (parenthesesOpenPos < whitespacePos) {
if (pos !== whitespacePos + 1) {
token.nodes = [
{
type: "word",
sourceIndex: pos,
sourceEndIndex: whitespacePos + 1,
value: value.slice(pos, whitespacePos + 1)
}
];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = "";
token.nodes.push({
type: "space",
sourceIndex: whitespacePos + 1,
sourceEndIndex: next,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
token.sourceEndIndex = next;
}
} else {
token.after = "";
token.nodes = [];
}
pos = next + 1;
token.sourceEndIndex = token.unclosed ? next : pos;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = "";
token.sourceEndIndex = pos + 1;
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = "";
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
parent.sourceEndIndex += after.length;
after = "";
balanced -= 1;
stack[stack.length - 1].sourceEndIndex = pos;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (
next < max &&
!(
code <= 32 ||
code === singleQuote ||
code === doubleQuote ||
code === comma ||
code === colon ||
code === slash ||
code === openParentheses ||
(code === star &&
parent &&
parent.type === "function" &&
parent.value === "calc") ||
(code === slash &&
parent.type === "function" &&
parent.value === "calc") ||
(code === closeParentheses && balanced)
)
);
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else if (
(uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
plus === token.charCodeAt(1) &&
isUnicodeRange.test(token.slice(2))
) {
tokens.push({
type: "unicode-range",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
} else {
tokens.push({
type: "word",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
stack[pos].sourceEndIndex = value.length;
}
return stack[0].nodes;
};
var walk$1 = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (
result !== false &&
node.type === "function" &&
Array.isArray(node.nodes)
) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === "word" || type === "space") {
return value;
} else if (type === "string") {
buf = node.quote || "";
return buf + value + (node.unclosed ? "" : buf);
} else if (type === "comment") {
return "/*" + value + (node.unclosed ? "" : "*/");
} else if (type === "div") {
return (node.before || "") + value + (node.after || "");
} else if (Array.isArray(node.nodes)) {
buf = stringify$1(node.nodes, custom);
if (type !== "function") {
return buf;
}
return (
value +
"(" +
(node.before || "") +
buf +
(node.after || "") +
(node.unclosed ? "" : ")")
);
}
return value;
}
function stringify$1(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = "";
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
var stringify_1 = stringify$1;
var unit;
var hasRequiredUnit;
function requireUnit () {
if (hasRequiredUnit) return unit;
hasRequiredUnit = 1;
var minus = "-".charCodeAt(0);
var plus = "+".charCodeAt(0);
var dot = ".".charCodeAt(0);
var exp = "e".charCodeAt(0);
var EXP = "E".charCodeAt(0);
// Check if three code points would start a number
// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
function likeNumber(value) {
var code = value.charCodeAt(0);
var nextCode;
if (code === plus || code === minus) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
var nextNextCode = value.charCodeAt(2);
if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
return true;
}
return false;
}
if (code === dot) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
return false;
}
if (code >= 48 && code <= 57) {
return true;
}
return false;
}
// Consume a number
// https://www.w3.org/TR/css-syntax-3/#consume-number
unit = function(value) {
var pos = 0;
var length = value.length;
var code;
var nextCode;
var nextNextCode;
if (length === 0 || !likeNumber(value)) {
return false;
}
code = value.charCodeAt(pos);
if (code === plus || code === minus) {
pos++;
}
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
if (code === dot && nextCode >= 48 && nextCode <= 57) {
pos += 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
nextNextCode = value.charCodeAt(pos + 2);
if (
(code === exp || code === EXP) &&
((nextCode >= 48 && nextCode <= 57) ||
((nextCode === plus || nextCode === minus) &&
nextNextCode >= 48 &&
nextNextCode <= 57))
) {
pos += nextCode === plus || nextCode === minus ? 3 : 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
return {
number: value.slice(0, pos),
unit: value.slice(pos)
};
};
return unit;
}
var parse = parse$1;
var walk = walk$1;
var stringify = stringify_1;
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function() {
return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
};
ValueParser.prototype.walk = function(cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = requireUnit();
ValueParser.walk = walk;
ValueParser.stringify = stringify;
var lib = ValueParser;
export { lib as l };

822
node_modules/vite/dist/node/chunks/dep-AiMcmC_f.js generated vendored Normal file
View File

@@ -0,0 +1,822 @@
import { P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import require$$0 from 'path';
import { l as lib } from './dep-3RmXg9uo.js';
import { createRequire as __cjs_createRequire } from 'node:module';
const __require = __cjs_createRequire(import.meta.url);
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
} }
}
return n;
}
var formatImportPrelude$2 = function formatImportPrelude(layer, media, supports) {
const parts = [];
if (typeof layer !== "undefined") {
let layerParams = "layer";
if (layer) {
layerParams = `layer(${layer})`;
}
parts.push(layerParams);
}
if (typeof supports !== "undefined") {
parts.push(`supports(${supports})`);
}
if (typeof media !== "undefined") {
parts.push(media);
}
return parts.join(" ")
};
const formatImportPrelude$1 = formatImportPrelude$2;
// Base64 encode an import with conditions
// The order of conditions is important and is interleaved with cascade layer declarations
// Each group of conditions and cascade layers needs to be interpreted in order
// To achieve this we create a list of base64 encoded imports, where each import contains a stylesheet with another import.
// Each import can define a single group of conditions and a single cascade layer.
var base64EncodedImport = function base64EncodedConditionalImport(prelude, conditions) {
conditions.reverse();
const first = conditions.pop();
let params = `${prelude} ${formatImportPrelude$1(
first.layer,
first.media,
first.supports,
)}`;
for (const condition of conditions) {
params = `'data:text/css;base64,${Buffer.from(`@import ${params}`).toString(
"base64",
)}' ${formatImportPrelude$1(
condition.layer,
condition.media,
condition.supports,
)}`;
}
return params
};
const base64EncodedConditionalImport = base64EncodedImport;
var applyConditions$1 = function applyConditions(bundle, atRule) {
bundle.forEach(stmt => {
if (
stmt.type === "charset" ||
stmt.type === "warning" ||
!stmt.conditions?.length
) {
return
}
if (stmt.type === "import") {
stmt.node.params = base64EncodedConditionalImport(
stmt.fullUri,
stmt.conditions,
);
return
}
const { nodes } = stmt;
const { parent } = nodes[0];
const atRules = [];
// Convert conditions to at-rules
for (const condition of stmt.conditions) {
if (typeof condition.media !== "undefined") {
const mediaNode = atRule({
name: "media",
params: condition.media,
source: parent.source,
});
atRules.push(mediaNode);
}
if (typeof condition.supports !== "undefined") {
const supportsNode = atRule({
name: "supports",
params: `(${condition.supports})`,
source: parent.source,
});
atRules.push(supportsNode);
}
if (typeof condition.layer !== "undefined") {
const layerNode = atRule({
name: "layer",
params: condition.layer,
source: parent.source,
});
atRules.push(layerNode);
}
}
// Add nodes to AST
const outerAtRule = atRules.shift();
const innerAtRule = atRules.reduce((previous, next) => {
previous.append(next);
return next
}, outerAtRule);
parent.insertBefore(nodes[0], outerAtRule);
// remove nodes
nodes.forEach(node => {
node.parent = undefined;
});
// better output
nodes[0].raws.before = nodes[0].raws.before || "\n";
// wrap new rules with media query and/or layer at rule
innerAtRule.append(nodes);
stmt.type = "nodes";
stmt.nodes = [outerAtRule];
delete stmt.node;
});
};
var applyRaws$1 = function applyRaws(bundle) {
bundle.forEach((stmt, index) => {
if (index === 0) return
if (stmt.parent) {
const { before } = stmt.parent.node.raws;
if (stmt.type === "nodes") stmt.nodes[0].raws.before = before;
else stmt.node.raws.before = before;
} else if (stmt.type === "nodes") {
stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n";
}
});
};
var applyStyles$1 = function applyStyles(bundle, styles) {
styles.nodes = [];
// Strip additional statements.
bundle.forEach(stmt => {
if (["charset", "import"].includes(stmt.type)) {
stmt.node.parent = undefined;
styles.append(stmt.node);
} else if (stmt.type === "nodes") {
stmt.nodes.forEach(node => {
node.parent = undefined;
styles.append(node);
});
}
});
};
const anyDataURLRegexp = /^data:text\/css(?:;(base64|plain))?,/i;
const base64DataURLRegexp = /^data:text\/css;base64,/i;
const plainDataURLRegexp = /^data:text\/css;plain,/i;
function isValid(url) {
return anyDataURLRegexp.test(url)
}
function contents(url) {
if (base64DataURLRegexp.test(url)) {
// "data:text/css;base64,".length === 21
return Buffer.from(url.slice(21), "base64").toString()
}
if (plainDataURLRegexp.test(url)) {
// "data:text/css;plain,".length === 20
return decodeURIComponent(url.slice(20))
}
// "data:text/css,".length === 14
return decodeURIComponent(url.slice(14))
}
var dataUrl = {
isValid,
contents,
};
// external tooling
const valueParser = lib;
// extended tooling
const { stringify } = valueParser;
var parseStatements$1 = function parseStatements(result, styles, conditions, from) {
const statements = [];
let nodes = [];
styles.each(node => {
let stmt;
if (node.type === "atrule") {
if (node.name === "import")
stmt = parseImport(result, node, conditions, from);
else if (node.name === "charset")
stmt = parseCharset(result, node, conditions, from);
}
if (stmt) {
if (nodes.length) {
statements.push({
type: "nodes",
nodes,
conditions: [...conditions],
from,
});
nodes = [];
}
statements.push(stmt);
} else nodes.push(node);
});
if (nodes.length) {
statements.push({
type: "nodes",
nodes,
conditions: [...conditions],
from,
});
}
return statements
};
function parseCharset(result, atRule, conditions, from) {
if (atRule.prev()) {
return result.warn("@charset must precede all other statements", {
node: atRule,
})
}
return {
type: "charset",
node: atRule,
conditions: [...conditions],
from,
}
}
function parseImport(result, atRule, conditions, from) {
let prev = atRule.prev();
// `@import` statements may follow other `@import` statements.
if (prev) {
do {
if (
prev.type === "comment" ||
(prev.type === "atrule" && prev.name === "import")
) {
prev = prev.prev();
continue
}
break
} while (prev)
}
// All `@import` statements may be preceded by `@charset` or `@layer` statements.
// But the `@import` statements must be consecutive.
if (prev) {
do {
if (
prev.type === "comment" ||
(prev.type === "atrule" &&
(prev.name === "charset" || (prev.name === "layer" && !prev.nodes)))
) {
prev = prev.prev();
continue
}
return result.warn(
"@import must precede all other statements (besides @charset or empty @layer)",
{ node: atRule },
)
} while (prev)
}
if (atRule.nodes) {
return result.warn(
"It looks like you didn't end your @import statement correctly. " +
"Child nodes are attached to it.",
{ node: atRule },
)
}
const params = valueParser(atRule.params).nodes;
const stmt = {
type: "import",
uri: "",
fullUri: "",
node: atRule,
conditions: [...conditions],
from,
};
let layer;
let media;
let supports;
for (let i = 0; i < params.length; i++) {
const node = params[i];
if (node.type === "space" || node.type === "comment") continue
if (node.type === "string") {
if (stmt.uri) {
return result.warn(`Multiple url's in '${atRule.toString()}'`, {
node: atRule,
})
}
if (!node.value) {
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule,
})
}
stmt.uri = node.value;
stmt.fullUri = stringify(node);
continue
}
if (node.type === "function" && /^url$/i.test(node.value)) {
if (stmt.uri) {
return result.warn(`Multiple url's in '${atRule.toString()}'`, {
node: atRule,
})
}
if (!node.nodes?.[0]?.value) {
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule,
})
}
stmt.uri = node.nodes[0].value;
stmt.fullUri = stringify(node);
continue
}
if (!stmt.uri) {
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule,
})
}
if (
(node.type === "word" || node.type === "function") &&
/^layer$/i.test(node.value)
) {
if (typeof layer !== "undefined") {
return result.warn(`Multiple layers in '${atRule.toString()}'`, {
node: atRule,
})
}
if (typeof supports !== "undefined") {
return result.warn(
`layers must be defined before support conditions in '${atRule.toString()}'`,
{
node: atRule,
},
)
}
if (node.nodes) {
layer = stringify(node.nodes);
} else {
layer = "";
}
continue
}
if (node.type === "function" && /^supports$/i.test(node.value)) {
if (typeof supports !== "undefined") {
return result.warn(
`Multiple support conditions in '${atRule.toString()}'`,
{
node: atRule,
},
)
}
supports = stringify(node.nodes);
continue
}
media = stringify(params.slice(i));
break
}
if (!stmt.uri) {
return result.warn(`Unable to find uri in '${atRule.toString()}'`, {
node: atRule,
})
}
if (
typeof media !== "undefined" ||
typeof layer !== "undefined" ||
typeof supports !== "undefined"
) {
stmt.conditions.push({
layer,
media,
supports,
});
}
return stmt
}
// builtin tooling
const path$2 = require$$0;
// placeholder tooling
let sugarss;
var processContent$1 = function processContent(
result,
content,
filename,
options,
postcss,
) {
const { plugins } = options;
const ext = path$2.extname(filename);
const parserList = [];
// SugarSS support:
if (ext === ".sss") {
if (!sugarss) {
/* c8 ignore next 3 */
try {
sugarss = __require('sugarss');
} catch {} // Ignore
}
if (sugarss)
return runPostcss(postcss, content, filename, plugins, [sugarss])
}
// Syntax support:
if (result.opts.syntax?.parse) {
parserList.push(result.opts.syntax.parse);
}
// Parser support:
if (result.opts.parser) parserList.push(result.opts.parser);
// Try the default as a last resort:
parserList.push(null);
return runPostcss(postcss, content, filename, plugins, parserList)
};
function runPostcss(postcss, content, filename, plugins, parsers, index) {
if (!index) index = 0;
return postcss(plugins)
.process(content, {
from: filename,
parser: parsers[index],
})
.catch(err => {
// If there's an error, try the next parser
index++;
// If there are no parsers left, throw it
if (index === parsers.length) throw err
return runPostcss(postcss, content, filename, plugins, parsers, index)
})
}
const path$1 = require$$0;
const dataURL = dataUrl;
const parseStatements = parseStatements$1;
const processContent = processContent$1;
const resolveId$1 = (id) => id;
const formatImportPrelude = formatImportPrelude$2;
async function parseStyles$1(
result,
styles,
options,
state,
conditions,
from,
postcss,
) {
const statements = parseStatements(result, styles, conditions, from);
for (const stmt of statements) {
if (stmt.type !== "import" || !isProcessableURL(stmt.uri)) {
continue
}
if (options.filter && !options.filter(stmt.uri)) {
// rejected by filter
continue
}
await resolveImportId(result, stmt, options, state, postcss);
}
let charset;
const imports = [];
const bundle = [];
function handleCharset(stmt) {
if (!charset) charset = stmt;
// charsets aren't case-sensitive, so convert to lower case to compare
else if (
stmt.node.params.toLowerCase() !== charset.node.params.toLowerCase()
) {
throw stmt.node.error(
`Incompatible @charset statements:
${stmt.node.params} specified in ${stmt.node.source.input.file}
${charset.node.params} specified in ${charset.node.source.input.file}`,
)
}
}
// squash statements and their children
statements.forEach(stmt => {
if (stmt.type === "charset") handleCharset(stmt);
else if (stmt.type === "import") {
if (stmt.children) {
stmt.children.forEach((child, index) => {
if (child.type === "import") imports.push(child);
else if (child.type === "charset") handleCharset(child);
else bundle.push(child);
// For better output
if (index === 0) child.parent = stmt;
});
} else imports.push(stmt);
} else if (stmt.type === "nodes") {
bundle.push(stmt);
}
});
return charset ? [charset, ...imports.concat(bundle)] : imports.concat(bundle)
}
async function resolveImportId(result, stmt, options, state, postcss) {
if (dataURL.isValid(stmt.uri)) {
// eslint-disable-next-line require-atomic-updates
stmt.children = await loadImportContent(
result,
stmt,
stmt.uri,
options,
state,
postcss,
);
return
} else if (dataURL.isValid(stmt.from.slice(-1))) {
// Data urls can't be used as a base url to resolve imports.
throw stmt.node.error(
`Unable to import '${stmt.uri}' from a stylesheet that is embedded in a data url`,
)
}
const atRule = stmt.node;
let sourceFile;
if (atRule.source?.input?.file) {
sourceFile = atRule.source.input.file;
}
const base = sourceFile
? path$1.dirname(atRule.source.input.file)
: options.root;
const paths = [await options.resolve(stmt.uri, base, options, atRule)].flat();
// Ensure that each path is absolute:
const resolved = await Promise.all(
paths.map(file => {
return !path$1.isAbsolute(file)
? resolveId$1(file)
: file
}),
);
// Add dependency messages:
resolved.forEach(file => {
result.messages.push({
type: "dependency",
plugin: "postcss-import",
file,
parent: sourceFile,
});
});
const importedContent = await Promise.all(
resolved.map(file => {
return loadImportContent(result, stmt, file, options, state, postcss)
}),
);
// Merge loaded statements
// eslint-disable-next-line require-atomic-updates
stmt.children = importedContent.flat().filter(x => !!x);
}
async function loadImportContent(
result,
stmt,
filename,
options,
state,
postcss,
) {
const atRule = stmt.node;
const { conditions, from } = stmt;
const stmtDuplicateCheckKey = conditions
.map(condition =>
formatImportPrelude(condition.layer, condition.media, condition.supports),
)
.join(":");
if (options.skipDuplicates) {
// skip files already imported at the same scope
if (state.importedFiles[filename]?.[stmtDuplicateCheckKey]) {
return
}
// save imported files to skip them next time
if (!state.importedFiles[filename]) {
state.importedFiles[filename] = {};
}
state.importedFiles[filename][stmtDuplicateCheckKey] = true;
}
if (from.includes(filename)) {
return
}
const content = await options.load(filename, options);
if (content.trim() === "" && options.warnOnEmpty) {
result.warn(`${filename} is empty`, { node: atRule });
return
}
// skip previous imported files not containing @import rules
if (
options.skipDuplicates &&
state.hashFiles[content]?.[stmtDuplicateCheckKey]
) {
return
}
const importedResult = await processContent(
result,
content,
filename,
options,
postcss,
);
const styles = importedResult.root;
result.messages = result.messages.concat(importedResult.messages);
if (options.skipDuplicates) {
const hasImport = styles.some(child => {
return child.type === "atrule" && child.name === "import"
});
if (!hasImport) {
// save hash files to skip them next time
if (!state.hashFiles[content]) {
state.hashFiles[content] = {};
}
state.hashFiles[content][stmtDuplicateCheckKey] = true;
}
}
// recursion: import @import from imported file
return parseStyles$1(
result,
styles,
options,
state,
conditions,
[...from, filename],
postcss,
)
}
function isProcessableURL(uri) {
// skip protocol base uri (protocol://url) or protocol-relative
if (/^(?:[a-z]+:)?\/\//i.test(uri)) {
return false
}
// check for fragment or query
try {
// needs a base to parse properly
const url = new URL(uri, "https://example.com");
if (url.search) {
return false
}
} catch {} // Ignore
return true
}
var parseStyles_1 = parseStyles$1;
// builtin tooling
const path = require$$0;
// internal tooling
const applyConditions = applyConditions$1;
const applyRaws = applyRaws$1;
const applyStyles = applyStyles$1;
const loadContent = () => "";
const parseStyles = parseStyles_1;
const resolveId = (id) => id;
function AtImport(options) {
options = {
root: process.cwd(),
path: [],
skipDuplicates: true,
resolve: resolveId,
load: loadContent,
plugins: [],
addModulesDirectories: [],
warnOnEmpty: true,
...options,
};
options.root = path.resolve(options.root);
// convert string to an array of a single element
if (typeof options.path === "string") options.path = [options.path];
if (!Array.isArray(options.path)) options.path = [];
options.path = options.path.map(p => path.resolve(options.root, p));
return {
postcssPlugin: "postcss-import",
async Once(styles, { result, atRule, postcss }) {
const state = {
importedFiles: {},
hashFiles: {},
};
if (styles.source?.input?.file) {
state.importedFiles[styles.source.input.file] = {};
}
if (options.plugins && !Array.isArray(options.plugins)) {
throw new Error("plugins option must be an array")
}
const bundle = await parseStyles(
result,
styles,
options,
state,
[],
[],
postcss,
);
applyRaws(bundle);
applyConditions(bundle, atRule);
applyStyles(bundle, styles);
},
}
}
AtImport.postcss = true;
var postcssImport = AtImport;
var index = /*@__PURE__*/getDefaultExportFromCjs(postcssImport);
var index$1 = /*#__PURE__*/_mergeNamespaces({
__proto__: null,
default: index
}, [postcssImport]);
export { index$1 as i };

8218
node_modules/vite/dist/node/chunks/dep-CvfTChi5.js generated vendored Normal file

File diff suppressed because one or more lines are too long

49496
node_modules/vite/dist/node/chunks/dep-DBxKXgDP.js generated vendored Normal file

File diff suppressed because one or more lines are too long

7113
node_modules/vite/dist/node/chunks/dep-SgSik2vo.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

949
node_modules/vite/dist/node/cli.js generated vendored Normal file
View File

@@ -0,0 +1,949 @@
import path from 'node:path';
import fs__default from 'node:fs';
import { performance } from 'node:perf_hooks';
import { EventEmitter } from 'events';
import { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-DBxKXgDP.js';
import { VERSION } from './constants.js';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'esbuild';
import 'path';
import 'fs';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'url';
import 'http';
import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
import 'vite/module-runner';
import 'rollup/parseAst';
import 'node:buffer';
import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'zlib';
import 'buffer';
import 'assert';
import 'node:querystring';
import 'node:zlib';
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
function mri2 (args, opts) {
args = args || [];
opts = opts || {};
var k, arr, arg, name, val, out={ _:[] };
var i=0, j=0, idx=0, len=args.length;
const alibi = opts.alias !== void 0;
const strict = opts.unknown !== void 0;
const defaults = opts.default !== void 0;
opts.alias = opts.alias || {};
opts.string = toArr(opts.string);
opts.boolean = toArr(opts.boolean);
if (alibi) {
for (k in opts.alias) {
arr = opts.alias[k] = toArr(opts.alias[k]);
for (i=0; i < arr.length; i++) {
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
}
}
}
for (i=opts.boolean.length; i-- > 0;) {
arr = opts.alias[opts.boolean[i]] || [];
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
}
for (i=opts.string.length; i-- > 0;) {
arr = opts.alias[opts.string[i]] || [];
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
}
if (defaults) {
for (k in opts.default) {
name = typeof opts.default[k];
arr = opts.alias[k] = opts.alias[k] || [];
if (opts[name] !== void 0) {
opts[name].push(k);
for (i=0; i < arr.length; i++) {
opts[name].push(arr[i]);
}
}
}
}
const keys = strict ? Object.keys(opts.alias) : [];
for (i=0; i < len; i++) {
arg = args[i];
if (arg === '--') {
out._ = out._.concat(args.slice(++i));
break;
}
for (j=0; j < arg.length; j++) {
if (arg.charCodeAt(j) !== 45) break; // "-"
}
if (j === 0) {
out._.push(arg);
} else if (arg.substring(j, j + 3) === 'no-') {
name = arg.substring(j + 3);
if (strict && !~keys.indexOf(name)) {
return opts.unknown(arg);
}
out[name] = false;
} else {
for (idx=j+1; idx < arg.length; idx++) {
if (arg.charCodeAt(idx) === 61) break; // "="
}
name = arg.substring(j, idx);
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
arr = (j === 2 ? [name] : name);
for (idx=0; idx < arr.length; idx++) {
name = arr[idx];
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
toVal(out, name, (idx + 1 < arr.length) || val, opts);
}
}
}
if (defaults) {
for (k in opts.default) {
if (out[k] === void 0) {
out[k] = opts.default[k];
}
}
}
if (alibi) {
for (k in out) {
arr = opts.alias[k] || [];
while (arr.length > 0) {
out[arr.shift()] = out[k];
}
}
}
return out;
}
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
const findAllBrackets = (v) => {
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
const res = [];
const parse = (match) => {
let variadic = false;
let value = match[1];
if (value.startsWith("...")) {
value = value.slice(3);
variadic = true;
}
return {
required: match[0].startsWith("<"),
value,
variadic
};
};
let angledMatch;
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(angledMatch));
}
let squareMatch;
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
res.push(parse(squareMatch));
}
return res;
};
const getMriOptions = (options) => {
const result = {alias: {}, boolean: []};
for (const [index, option] of options.entries()) {
if (option.names.length > 1) {
result.alias[option.names[0]] = option.names.slice(1);
}
if (option.isBoolean) {
if (option.negated) {
const hasStringTypeOption = options.some((o, i) => {
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
});
if (!hasStringTypeOption) {
result.boolean.push(option.names[0]);
}
} else {
result.boolean.push(option.names[0]);
}
}
}
return result;
};
const findLongest = (arr) => {
return arr.sort((a, b) => {
return a.length > b.length ? -1 : 1;
})[0];
};
const padRight = (str, length) => {
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
};
const camelcase = (input) => {
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
return p1 + p2.toUpperCase();
});
};
const setDotProp = (obj, keys, val) => {
let i = 0;
let length = keys.length;
let t = obj;
let x;
for (; i < length; ++i) {
x = t[keys[i]];
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
}
};
const setByType = (obj, transforms) => {
for (const key of Object.keys(transforms)) {
const transform = transforms[key];
if (transform.shouldTransform) {
obj[key] = Array.prototype.concat.call([], obj[key]);
if (typeof transform.transformFunction === "function") {
obj[key] = obj[key].map(transform.transformFunction);
}
}
}
};
const getFileName = (input) => {
const m = /([^\\\/]+)$/.exec(input);
return m ? m[1] : "";
};
const camelcaseOptionName = (name) => {
return name.split(".").map((v, i) => {
return i === 0 ? camelcase(v) : v;
}).join(".");
};
class CACError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(message).stack;
}
}
}
class Option {
constructor(rawName, description, config) {
this.rawName = rawName;
this.description = description;
this.config = Object.assign({}, config);
rawName = rawName.replace(/\.\*/g, "");
this.negated = false;
this.names = removeBrackets(rawName).split(",").map((v) => {
let name = v.trim().replace(/^-{1,2}/, "");
if (name.startsWith("no-")) {
this.negated = true;
name = name.replace(/^no-/, "");
}
return camelcaseOptionName(name);
}).sort((a, b) => a.length > b.length ? 1 : -1);
this.name = this.names[this.names.length - 1];
if (this.negated && this.config.default == null) {
this.config.default = true;
}
if (rawName.includes("<")) {
this.required = true;
} else if (rawName.includes("[")) {
this.required = false;
} else {
this.isBoolean = true;
}
}
}
const processArgs = process.argv;
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
class Command {
constructor(rawName, description, config = {}, cli) {
this.rawName = rawName;
this.description = description;
this.config = config;
this.cli = cli;
this.options = [];
this.aliasNames = [];
this.name = removeBrackets(rawName);
this.args = findAllBrackets(rawName);
this.examples = [];
}
usage(text) {
this.usageText = text;
return this;
}
allowUnknownOptions() {
this.config.allowUnknownOptions = true;
return this;
}
ignoreOptionDefaultValue() {
this.config.ignoreOptionDefaultValue = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.versionNumber = version;
this.option(customFlags, "Display version number");
return this;
}
example(example) {
this.examples.push(example);
return this;
}
option(rawName, description, config) {
const option = new Option(rawName, description, config);
this.options.push(option);
return this;
}
alias(name) {
this.aliasNames.push(name);
return this;
}
action(callback) {
this.commandAction = callback;
return this;
}
isMatched(name) {
return this.name === name || this.aliasNames.includes(name);
}
get isDefaultCommand() {
return this.name === "" || this.aliasNames.includes("!");
}
get isGlobalCommand() {
return this instanceof GlobalCommand;
}
hasOption(name) {
name = name.split(".")[0];
return this.options.find((option) => {
return option.names.includes(name);
});
}
outputHelp() {
const {name, commands} = this.cli;
const {
versionNumber,
options: globalOptions,
helpCallback
} = this.cli.globalCommand;
let sections = [
{
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
}
];
sections.push({
title: "Usage",
body: ` $ ${name} ${this.usageText || this.rawName}`
});
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
if (showCommands) {
const longestCommandName = findLongest(commands.map((command) => command.rawName));
sections.push({
title: "Commands",
body: commands.map((command) => {
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
}).join("\n")
});
sections.push({
title: `For more info, run any command with the \`--help\` flag`,
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
});
}
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
if (!this.isGlobalCommand && !this.isDefaultCommand) {
options = options.filter((option) => option.name !== "version");
}
if (options.length > 0) {
const longestOptionName = findLongest(options.map((option) => option.rawName));
sections.push({
title: "Options",
body: options.map((option) => {
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
}).join("\n")
});
}
if (this.examples.length > 0) {
sections.push({
title: "Examples",
body: this.examples.map((example) => {
if (typeof example === "function") {
return example(name);
}
return example;
}).join("\n")
});
}
if (helpCallback) {
sections = helpCallback(sections) || sections;
}
console.log(sections.map((section) => {
return section.title ? `${section.title}:
${section.body}` : section.body;
}).join("\n\n"));
}
outputVersion() {
const {name} = this.cli;
const {versionNumber} = this.cli.globalCommand;
if (versionNumber) {
console.log(`${name}/${versionNumber} ${platformInfo}`);
}
}
checkRequiredArgs() {
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
if (this.cli.args.length < minimalArgsCount) {
throw new CACError(`missing required args for command \`${this.rawName}\``);
}
}
checkUnknownOptions() {
const {options, globalCommand} = this.cli;
if (!this.config.allowUnknownOptions) {
for (const name of Object.keys(options)) {
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
}
}
}
}
checkOptionValue() {
const {options: parsedOptions, globalCommand} = this.cli;
const options = [...globalCommand.options, ...this.options];
for (const option of options) {
const value = parsedOptions[option.name.split(".")[0]];
if (option.required) {
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
if (value === true || value === false && !hasNegated) {
throw new CACError(`option \`${option.rawName}\` value is missing`);
}
}
}
}
}
class GlobalCommand extends Command {
constructor(cli) {
super("@@global@@", "", {}, cli);
}
}
var __assign = Object.assign;
class CAC extends EventEmitter {
constructor(name = "") {
super();
this.name = name;
this.commands = [];
this.rawArgs = [];
this.args = [];
this.options = {};
this.globalCommand = new GlobalCommand(this);
this.globalCommand.usage("<command> [options]");
}
usage(text) {
this.globalCommand.usage(text);
return this;
}
command(rawName, description, config) {
const command = new Command(rawName, description || "", config, this);
command.globalCommand = this.globalCommand;
this.commands.push(command);
return command;
}
option(rawName, description, config) {
this.globalCommand.option(rawName, description, config);
return this;
}
help(callback) {
this.globalCommand.option("-h, --help", "Display this message");
this.globalCommand.helpCallback = callback;
this.showHelpOnExit = true;
return this;
}
version(version, customFlags = "-v, --version") {
this.globalCommand.version(version, customFlags);
this.showVersionOnExit = true;
return this;
}
example(example) {
this.globalCommand.example(example);
return this;
}
outputHelp() {
if (this.matchedCommand) {
this.matchedCommand.outputHelp();
} else {
this.globalCommand.outputHelp();
}
}
outputVersion() {
this.globalCommand.outputVersion();
}
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
this.args = args;
this.options = options;
if (matchedCommand) {
this.matchedCommand = matchedCommand;
}
if (matchedCommandName) {
this.matchedCommandName = matchedCommandName;
}
return this;
}
unsetMatchedCommand() {
this.matchedCommand = void 0;
this.matchedCommandName = void 0;
}
parse(argv = processArgs, {
run = true
} = {}) {
this.rawArgs = argv;
if (!this.name) {
this.name = argv[1] ? getFileName(argv[1]) : "cli";
}
let shouldParse = true;
for (const command of this.commands) {
const parsed = this.mri(argv.slice(2), command);
const commandName = parsed.args[0];
if (command.isMatched(commandName)) {
shouldParse = false;
const parsedInfo = __assign(__assign({}, parsed), {
args: parsed.args.slice(1)
});
this.setParsedInfo(parsedInfo, command, commandName);
this.emit(`command:${commandName}`, command);
}
}
if (shouldParse) {
for (const command of this.commands) {
if (command.name === "") {
shouldParse = false;
const parsed = this.mri(argv.slice(2), command);
this.setParsedInfo(parsed, command);
this.emit(`command:!`, command);
}
}
}
if (shouldParse) {
const parsed = this.mri(argv.slice(2));
this.setParsedInfo(parsed);
}
if (this.options.help && this.showHelpOnExit) {
this.outputHelp();
run = false;
this.unsetMatchedCommand();
}
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
this.outputVersion();
run = false;
this.unsetMatchedCommand();
}
const parsedArgv = {args: this.args, options: this.options};
if (run) {
this.runMatchedCommand();
}
if (!this.matchedCommand && this.args[0]) {
this.emit("command:*");
}
return parsedArgv;
}
mri(argv, command) {
const cliOptions = [
...this.globalCommand.options,
...command ? command.options : []
];
const mriOptions = getMriOptions(cliOptions);
let argsAfterDoubleDashes = [];
const doubleDashesIndex = argv.indexOf("--");
if (doubleDashesIndex > -1) {
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
argv = argv.slice(0, doubleDashesIndex);
}
let parsed = mri2(argv, mriOptions);
parsed = Object.keys(parsed).reduce((res, name) => {
return __assign(__assign({}, res), {
[camelcaseOptionName(name)]: parsed[name]
});
}, {_: []});
const args = parsed._;
const options = {
"--": argsAfterDoubleDashes
};
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
let transforms = Object.create(null);
for (const cliOption of cliOptions) {
if (!ignoreDefault && cliOption.config.default !== void 0) {
for (const name of cliOption.names) {
options[name] = cliOption.config.default;
}
}
if (Array.isArray(cliOption.config.type)) {
if (transforms[cliOption.name] === void 0) {
transforms[cliOption.name] = Object.create(null);
transforms[cliOption.name]["shouldTransform"] = true;
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
}
}
}
for (const key of Object.keys(parsed)) {
if (key !== "_") {
const keys = key.split(".");
setDotProp(options, keys, parsed[key]);
setByType(options, transforms);
}
}
return {
args,
options
};
}
runMatchedCommand() {
const {args, options, matchedCommand: command} = this;
if (!command || !command.commandAction)
return;
command.checkUnknownOptions();
command.checkOptionValue();
command.checkRequiredArgs();
const actionArgs = [];
command.args.forEach((arg, index) => {
if (arg.variadic) {
actionArgs.push(args.slice(index));
} else {
actionArgs.push(args[index]);
}
});
actionArgs.push(options);
return command.commandAction.apply(this, actionArgs);
}
}
const cac = (name = "") => new CAC(name);
const cli = cac("vite");
let profileSession = global.__vite_profile_session;
let profileCount = 0;
const stopProfiler = (log) => {
if (!profileSession) return;
return new Promise((res, rej) => {
profileSession.post("Profiler.stop", (err, { profile }) => {
if (!err) {
const outPath = path.resolve(
`./vite-profile-${profileCount++}.cpuprofile`
);
fs__default.writeFileSync(outPath, JSON.stringify(profile));
log(
colors.yellow(
`CPU profile written to ${colors.white(colors.dim(outPath))}`
)
);
profileSession = void 0;
res();
} else {
rej(err);
}
});
});
};
const filterDuplicateOptions = (options) => {
for (const [key, value] of Object.entries(options)) {
if (Array.isArray(value)) {
options[key] = value[value.length - 1];
}
}
};
function cleanGlobalCLIOptions(options) {
const ret = { ...options };
delete ret["--"];
delete ret.c;
delete ret.config;
delete ret.base;
delete ret.l;
delete ret.logLevel;
delete ret.clearScreen;
delete ret.configLoader;
delete ret.d;
delete ret.debug;
delete ret.f;
delete ret.filter;
delete ret.m;
delete ret.mode;
delete ret.w;
if ("sourcemap" in ret) {
const sourcemap = ret.sourcemap;
ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
}
if ("watch" in ret) {
const watch = ret.watch;
ret.watch = watch ? {} : void 0;
}
return ret;
}
function cleanBuilderCLIOptions(options) {
const ret = { ...options };
delete ret.app;
return ret;
}
const convertHost = (v) => {
if (typeof v === "number") {
return String(v);
}
return v;
};
const convertBase = (v) => {
if (v === 0) {
return "";
}
return v;
};
cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
type: [convertBase]
}).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option(
"--configLoader <loader>",
`[string] use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`
).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--open [path]", `[boolean | string] open browser on startup`).option("--cors", `[boolean] enable CORS`).option("--strictPort", `[boolean] exit if specified port is already in use`).option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(async (root, options) => {
filterDuplicateOptions(options);
const { createServer } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.S; });
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
server: cleanGlobalCLIOptions(options),
forceOptimizeDeps: options.force
});
if (!server.httpServer) {
throw new Error("HTTP server not available");
}
await server.listen();
const info = server.config.logger.info;
const modeString = options.mode && options.mode !== "development" ? ` ${colors.bgGreen(` ${colors.bold(options.mode)} `)}` : "";
const viteStartTime = global.__vite_start_time ?? false;
const startupDurationString = viteStartTime ? colors.dim(
`ready in ${colors.reset(
colors.bold(Math.ceil(performance.now() - viteStartTime))
)} ms`
) : "";
const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
info(
`
${colors.green(
`${colors.bold("VITE")} v${VERSION}`
)}${modeString} ${startupDurationString}
`,
{
clear: !hasExistingLogs
}
);
server.printUrls();
const customShortcuts = [];
if (profileSession) {
customShortcuts.push({
key: "p",
description: "start/stop the profiler",
async action(server2) {
if (profileSession) {
await stopProfiler(server2.config.logger.info);
} else {
const inspector = await import('node:inspector').then(
(r) => r.default
);
await new Promise((res) => {
profileSession = new inspector.Session();
profileSession.connect();
profileSession.post("Profiler.enable", () => {
profileSession.post("Profiler.start", () => {
server2.config.logger.info("Profiler started");
res();
});
});
});
}
}
});
}
server.bindCLIShortcuts({ print: true, customShortcuts });
} catch (e) {
const logger = createLogger(options.logLevel);
logger.error(colors.red(`error when starting dev server:
${e.stack}`), {
error: e
});
stopProfiler(logger.info);
process.exit(1);
}
});
cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option(
"--assetsDir <dir>",
`[string] directory under outDir to place assets in (default: assets)`
).option(
"--assetsInlineLimit <number>",
`[number] static asset base64 inline threshold in bytes (default: 4096)`
).option(
"--ssr [entry]",
`[string] build specified entry for server-side rendering`
).option(
"--sourcemap [output]",
`[boolean | "inline" | "hidden"] output source maps for build (default: false)`
).option(
"--minify [minifier]",
`[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
).option("--manifest [name]", `[boolean | string] emit build manifest json`).option("--ssrManifest [name]", `[boolean | string] emit ssr manifest json`).option(
"--emptyOutDir",
`[boolean] force empty outDir when it's outside of root`
).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(
async (root, options) => {
filterDuplicateOptions(options);
const { createBuilder } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.T; });
const buildOptions = cleanGlobalCLIOptions(
cleanBuilderCLIOptions(options)
);
try {
const inlineConfig = {
root,
base: options.base,
mode: options.mode,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions,
...options.app ? { builder: {} } : {}
};
const builder = await createBuilder(inlineConfig, null);
await builder.buildApp();
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error during build:
${e.stack}`),
{ error: e }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
}
);
cli.command(
"optimize [root]",
"pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)"
).option(
"--force",
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(
async (root, options) => {
filterDuplicateOptions(options);
const { optimizeDeps } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.R; });
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode
},
"serve"
);
await optimizeDeps(config, options.force, true);
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when optimizing deps:
${e.stack}`),
{ error: e }
);
process.exit(1);
}
}
);
cli.command("preview [root]", "locally preview production build").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--open [path]", `[boolean | string] open browser on startup`).option("--outDir <dir>", `[string] output directory (default: dist)`).action(
async (root, options) => {
filterDuplicateOptions(options);
const { preview } = await import('./chunks/dep-DBxKXgDP.js').then(function (n) { return n.U; });
try {
const server = await preview({
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode,
build: {
outDir: options.outDir
},
preview: {
port: options.port,
strictPort: options.strictPort,
host: options.host,
open: options.open
}
});
server.printUrls();
server.bindCLIShortcuts({ print: true });
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when starting preview server:
${e.stack}`),
{ error: e }
);
process.exit(1);
} finally {
stopProfiler((message) => createLogger(options.logLevel).info(message));
}
}
);
cli.help();
cli.version(VERSION);
cli.parse();
export { stopProfiler };

149
node_modules/vite/dist/node/constants.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
import path, { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
const { version } = JSON.parse(
readFileSync(new URL("../../package.json", import.meta.url)).toString()
);
const ROLLUP_HOOKS = [
"options",
"buildStart",
"buildEnd",
"renderStart",
"renderError",
"renderChunk",
"writeBundle",
"generateBundle",
"banner",
"footer",
"augmentChunkHash",
"outputOptions",
"renderDynamicImport",
"resolveFileUrl",
"resolveImportMeta",
"intro",
"outro",
"closeBundle",
"closeWatcher",
"load",
"moduleParsed",
"watchChange",
"resolveDynamicImport",
"resolveId",
"shouldTransformCachedModule",
"transform",
"onLog"
];
const VERSION = version;
const DEFAULT_MAIN_FIELDS = [
"browser",
"module",
"jsnext:main",
// moment still uses this...
"jsnext"
];
const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(
DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser")
);
const DEV_PROD_CONDITION = `development|production`;
const DEFAULT_CONDITIONS = ["module", "browser", "node", DEV_PROD_CONDITION];
const DEFAULT_CLIENT_CONDITIONS = Object.freeze(
DEFAULT_CONDITIONS.filter((c) => c !== "node")
);
const DEFAULT_SERVER_CONDITIONS = Object.freeze(
DEFAULT_CONDITIONS.filter((c) => c !== "browser")
);
const ESBUILD_MODULES_TARGET = [
"es2020",
"edge88",
"firefox78",
"chrome87",
"safari14"
];
const DEFAULT_CONFIG_FILES = [
"vite.config.js",
"vite.config.mjs",
"vite.config.ts",
"vite.config.cjs",
"vite.config.mts",
"vite.config.cts"
];
const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
const FS_PREFIX = `/@fs/`;
const CLIENT_PUBLIC_PATH = `/@vite/client`;
const ENV_PUBLIC_PATH = `/@vite/env`;
const VITE_PACKAGE_DIR = resolve(
// import.meta.url is `dist/node/constants.js` after bundle
fileURLToPath(import.meta.url),
"../../.."
);
const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
const KNOWN_ASSET_TYPES = [
// images
"apng",
"bmp",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
"cur",
"jxl",
// media
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"opus",
"mov",
"m4a",
"vtt",
// fonts
"woff2?",
"eot",
"ttf",
"otf",
// other
"webmanifest",
"pdf",
"txt"
];
const DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`,
"i"
);
const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
const loopbackHosts = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"::1",
"0000:0000:0000:0000:0000:0000:0000:0001"
]);
const wildcardHosts = /* @__PURE__ */ new Set([
"0.0.0.0",
"::",
"0000:0000:0000:0000:0000:0000:0000:0000"
]);
const DEFAULT_DEV_PORT = 5173;
const DEFAULT_PREVIEW_PORT = 4173;
const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
const METADATA_FILENAME = "_metadata.json";
const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
export { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, CSS_LANGS_RE, DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE, DEFAULT_CLIENT_CONDITIONS, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_CONFIG_FILES, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_SERVER_CONDITIONS, DEFAULT_SERVER_MAIN_FIELDS, DEP_VERSION_RE, DEV_PROD_CONDITION, ENV_ENTRY, ENV_PUBLIC_PATH, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ESBUILD_MODULES_TARGET, FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES, METADATA_FILENAME, OPTIMIZABLE_ENTRY_RE, ROLLUP_HOOKS, SPECIAL_QUERY_RE, VERSION, VITE_PACKAGE_DIR, defaultAllowedOrigins, loopbackHosts, wildcardHosts };

4222
node_modules/vite/dist/node/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

194
node_modules/vite/dist/node/index.js generated vendored Normal file
View File

@@ -0,0 +1,194 @@
export { parseAst, parseAstAsync } from 'rollup/parseAst';
import { a as arraify, i as isInNodeModules, D as DevEnvironment } from './chunks/dep-DBxKXgDP.js';
export { B as BuildEnvironment, f as build, m as buildErrorMessage, g as createBuilder, F as createFilter, h as createIdResolver, I as createLogger, n as createRunnableDevEnvironment, c as createServer, y as createServerHotChannel, w as createServerModuleRunner, x as createServerModuleRunnerTransport, d as defineConfig, v as fetchModule, j as formatPostcssSourceMap, L as isFileLoadingAllowed, K as isFileServingAllowed, q as isRunnableDevEnvironment, l as loadConfigFromFile, M as loadEnv, E as mergeAlias, C as mergeConfig, z as moduleRunnerTransform, A as normalizePath, o as optimizeDeps, p as perEnvironmentPlugin, b as perEnvironmentState, k as preprocessCSS, e as preview, r as resolveConfig, N as resolveEnvPrefix, G as rollupVersion, u as runnerImport, J as searchForWorkspaceRoot, H as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-DBxKXgDP.js';
export { defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, VERSION as version } from './constants.js';
export { version as esbuildVersion } from 'esbuild';
import 'node:fs';
import 'node:path';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:perf_hooks';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'path';
import 'fs';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'events';
import 'url';
import 'http';
import 'stream';
import 'os';
import 'child_process';
import 'node:os';
import 'node:net';
import 'node:dns';
import 'vite/module-runner';
import 'node:buffer';
import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'zlib';
import 'buffer';
import 'assert';
import 'node:querystring';
import 'node:zlib';
const CSS_LANGS_RE = (
// eslint-disable-next-line regexp/no-unused-capturing-group
/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
);
const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
class SplitVendorChunkCache {
cache;
constructor() {
this.cache = /* @__PURE__ */ new Map();
}
reset() {
this.cache = /* @__PURE__ */ new Map();
}
}
function splitVendorChunk(options = {}) {
const cache = options.cache ?? new SplitVendorChunkCache();
return (id, { getModuleInfo }) => {
if (isInNodeModules(id) && !isCSSRequest(id) && staticImportedByEntry(id, getModuleInfo, cache.cache)) {
return "vendor";
}
};
}
function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
if (cache.has(id)) {
return cache.get(id);
}
if (importStack.includes(id)) {
cache.set(id, false);
return false;
}
const mod = getModuleInfo(id);
if (!mod) {
cache.set(id, false);
return false;
}
if (mod.isEntry) {
cache.set(id, true);
return true;
}
const someImporterIs = mod.importers.some(
(importer) => staticImportedByEntry(
importer,
getModuleInfo,
cache,
importStack.concat(id)
)
);
cache.set(id, someImporterIs);
return someImporterIs;
}
function splitVendorChunkPlugin() {
const caches = [];
function createSplitVendorChunk(output, config) {
const cache = new SplitVendorChunkCache();
caches.push(cache);
const build = config.build ?? {};
const format = output.format;
if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
return splitVendorChunk({ cache });
}
}
return {
name: "vite:split-vendor-chunk",
config(config) {
let outputs = config.build?.rollupOptions?.output;
if (outputs) {
outputs = arraify(outputs);
for (const output of outputs) {
const viteManualChunks = createSplitVendorChunk(output, config);
if (viteManualChunks) {
if (output.manualChunks) {
if (typeof output.manualChunks === "function") {
const userManualChunks = output.manualChunks;
output.manualChunks = (id, api) => {
return userManualChunks(id, api) ?? viteManualChunks(id, api);
};
} else {
console.warn(
"(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."
);
}
} else {
output.manualChunks = viteManualChunks;
}
}
}
} else {
return {
build: {
rollupOptions: {
output: {
manualChunks: createSplitVendorChunk({}, config)
}
}
}
};
}
},
buildStart() {
caches.forEach((cache) => cache.reset());
}
};
}
function createFetchableDevEnvironment(name, config, context) {
if (typeof Request === "undefined" || typeof Response === "undefined") {
throw new TypeError(
"FetchableDevEnvironment requires a global `Request` and `Response` object."
);
}
if (!context.handleRequest) {
throw new TypeError(
"FetchableDevEnvironment requires a `handleRequest` method during initialisation."
);
}
return new FetchableDevEnvironment(name, config, context);
}
function isFetchableDevEnvironment(environment) {
return environment instanceof FetchableDevEnvironment;
}
class FetchableDevEnvironment extends DevEnvironment {
_handleRequest;
constructor(name, config, context) {
super(name, config, context);
this._handleRequest = context.handleRequest;
}
async dispatchFetch(request) {
if (!(request instanceof Request)) {
throw new TypeError(
"FetchableDevEnvironment `dispatchFetch` must receive a `Request` object."
);
}
const response = await this._handleRequest(request);
if (!(response instanceof Response)) {
throw new TypeError(
"FetchableDevEnvironment `context.handleRequest` must return a `Response` object."
);
}
return response;
}
}
export { DevEnvironment, createFetchableDevEnvironment, isCSSRequest, isFetchableDevEnvironment, splitVendorChunk, splitVendorChunkPlugin };

290
node_modules/vite/dist/node/module-runner.d.ts generated vendored Normal file
View File

@@ -0,0 +1,290 @@
import { ModuleNamespace, ViteHotContext } from '../../types/hot.js';
import { Update, HotPayload } from '../../types/hmrPayload.js';
import { InferCustomEventPayload } from '../../types/customEvent.js';
import { N as NormalizedModuleRunnerTransport, E as ExternalFetchResult, V as ViteFetchResult, M as ModuleRunnerTransport, F as FetchFunctionOptions, a as FetchResult } from './moduleRunnerTransport.d-DJ_mE5sf.js';
export { b as ModuleRunnerTransportHandlers, c as createWebSocketModuleRunnerTransport } from './moduleRunnerTransport.d-DJ_mE5sf.js';
interface SourceMapLike {
version: number;
mappings?: string;
names?: string[];
sources?: string[];
sourcesContent?: string[];
}
declare class DecodedMap {
map: SourceMapLike;
_encoded: string;
_decoded: undefined | number[][][];
_decodedMemo: Stats;
url: string;
version: number;
names: string[];
resolvedSources: string[];
constructor(map: SourceMapLike, from: string);
}
interface Stats {
lastKey: number;
lastNeedle: number;
lastIndex: number;
}
type CustomListenersMap = Map<string, ((data: any) => void)[]>;
interface HotModule {
id: string;
callbacks: HotCallback[];
}
interface HotCallback {
deps: string[];
fn: (modules: Array<ModuleNamespace | undefined>) => void;
}
interface HMRLogger {
error(msg: string | Error): void;
debug(...msg: unknown[]): void;
}
declare class HMRClient {
logger: HMRLogger;
private transport;
private importUpdatedModule;
hotModulesMap: Map<string, HotModule>;
disposeMap: Map<string, (data: any) => void | Promise<void>>;
pruneMap: Map<string, (data: any) => void | Promise<void>>;
dataMap: Map<string, any>;
customListenersMap: CustomListenersMap;
ctxToListenersMap: Map<string, CustomListenersMap>;
currentFirstInvalidatedBy: string | undefined;
constructor(logger: HMRLogger, transport: NormalizedModuleRunnerTransport, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<void>;
send(payload: HotPayload): void;
clear(): void;
prunePaths(paths: string[]): Promise<void>;
protected warnFailedUpdate(err: Error, path: string | string[]): void;
private updateQueue;
private pendingUpdateQueue;
/**
* buffer multiple hot updates triggered by the same src change
* so that they are invoked in the same order they were sent.
* (otherwise the order may be inconsistent because of the http request round trip)
*/
queueUpdate(payload: Update): Promise<void>;
private fetchUpdate;
}
interface DefineImportMetadata {
/**
* Imported names before being transformed to `ssrImportKey`
*
* import foo, { bar as baz, qux } from 'hello'
* => ['default', 'bar', 'qux']
*
* import * as namespace from 'world
* => undefined
*/
importedNames?: string[];
}
interface SSRImportMetadata extends DefineImportMetadata {
isDynamicImport?: boolean;
}
declare const ssrModuleExportsKey = "__vite_ssr_exports__";
declare const ssrImportKey = "__vite_ssr_import__";
declare const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
declare const ssrExportAllKey = "__vite_ssr_exportAll__";
declare const ssrImportMetaKey = "__vite_ssr_import_meta__";
interface ModuleRunnerDebugger {
(formatter: unknown, ...args: unknown[]): void;
}
declare class ModuleRunner {
options: ModuleRunnerOptions;
evaluator: ModuleEvaluator;
private debug?;
evaluatedModules: EvaluatedModules;
hmrClient?: HMRClient;
private readonly envProxy;
private readonly transport;
private readonly resetSourceMapSupport?;
private readonly concurrentModuleNodePromises;
private closed;
constructor(options: ModuleRunnerOptions, evaluator?: ModuleEvaluator, debug?: ModuleRunnerDebugger | undefined);
/**
* URL to execute. Accepts file path, server path or id relative to the root.
*/
import<T = any>(url: string): Promise<T>;
/**
* Clear all caches including HMR listeners.
*/
clearCache(): void;
/**
* Clears all caches, removes all HMR listeners, and resets source map support.
* This method doesn't stop the HMR connection.
*/
close(): Promise<void>;
/**
* Returns `true` if the runtime has been closed by calling `close()` method.
*/
isClosed(): boolean;
private processImport;
private isCircularModule;
private isCircularImport;
private cachedRequest;
private cachedModule;
private getModuleInformation;
protected directRequest(url: string, mod: EvaluatedModuleNode, _callstack: string[]): Promise<any>;
}
interface RetrieveFileHandler {
(path: string): string | null | undefined | false;
}
interface RetrieveSourceMapHandler {
(path: string): null | {
url: string;
map: any;
};
}
interface InterceptorOptions {
retrieveFile?: RetrieveFileHandler;
retrieveSourceMap?: RetrieveSourceMapHandler;
}
interface ModuleRunnerImportMeta extends ImportMeta {
url: string;
env: ImportMetaEnv;
hot?: ViteHotContext;
[key: string]: any;
}
interface ModuleRunnerContext {
[ssrModuleExportsKey]: Record<string, any>;
[ssrImportKey]: (id: string, metadata?: DefineImportMetadata) => Promise<any>;
[ssrDynamicImportKey]: (id: string, options?: ImportCallOptions) => Promise<any>;
[ssrExportAllKey]: (obj: any) => void;
[ssrImportMetaKey]: ModuleRunnerImportMeta;
}
interface ModuleEvaluator {
/**
* Number of prefixed lines in the transformed code.
*/
startOffset?: number;
/**
* Run code that was transformed by Vite.
* @param context Function context
* @param code Transformed code
* @param module The module node
*/
runInlinedModule(context: ModuleRunnerContext, code: string, module: Readonly<EvaluatedModuleNode>): Promise<any>;
/**
* Run externalized module.
* @param file File URL to the external module
*/
runExternalModule(file: string): Promise<any>;
}
type ResolvedResult = (ExternalFetchResult | ViteFetchResult) & {
url: string;
id: string;
};
type FetchFunction = (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
interface ModuleRunnerHmr {
/**
* Configure HMR logger.
*/
logger?: false | HMRLogger;
}
interface ModuleRunnerOptions {
/**
* Root of the project
* @deprecated not used and to be removed
*/
root?: string;
/**
* A set of methods to communicate with the server.
*/
transport: ModuleRunnerTransport;
/**
* Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
* Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
* You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
*/
sourcemapInterceptor?: false | 'node' | 'prepareStackTrace' | InterceptorOptions;
/**
* Disable HMR or configure HMR options.
*
* @default true
*/
hmr?: boolean | ModuleRunnerHmr;
/**
* Custom module cache. If not provided, creates a separate module cache for each ModuleRunner instance.
*/
evaluatedModules?: EvaluatedModules;
}
interface ImportMetaEnv {
[key: string]: any;
BASE_URL: string;
MODE: string;
DEV: boolean;
PROD: boolean;
SSR: boolean;
}
declare class EvaluatedModuleNode {
id: string;
url: string;
importers: Set<string>;
imports: Set<string>;
evaluated: boolean;
meta: ResolvedResult | undefined;
promise: Promise<any> | undefined;
exports: any | undefined;
file: string;
map: DecodedMap | undefined;
constructor(id: string, url: string);
}
declare class EvaluatedModules {
readonly idToModuleMap: Map<string, EvaluatedModuleNode>;
readonly fileToModulesMap: Map<string, Set<EvaluatedModuleNode>>;
readonly urlToIdModuleMap: Map<string, EvaluatedModuleNode>;
/**
* Returns the module node by the resolved module ID. Usually, module ID is
* the file system path with query and/or hash. It can also be a virtual module.
*
* Module runner graph will have 1 to 1 mapping with the server module graph.
* @param id Resolved module ID
*/
getModuleById(id: string): EvaluatedModuleNode | undefined;
/**
* Returns all modules related to the file system path. Different modules
* might have different query parameters or hash, so it's possible to have
* multiple modules for the same file.
* @param file The file system path of the module
*/
getModulesByFile(file: string): Set<EvaluatedModuleNode> | undefined;
/**
* Returns the module node by the URL that was used in the import statement.
* Unlike module graph on the server, the URL is not resolved and is used as is.
* @param url Server URL that was used in the import statement
*/
getModuleByUrl(url: string): EvaluatedModuleNode | undefined;
/**
* Ensure that module is in the graph. If the module is already in the graph,
* it will return the existing module node. Otherwise, it will create a new
* module node and add it to the graph.
* @param id Resolved module ID
* @param url URL that was used in the import statement
*/
ensureModule(id: string, url: string): EvaluatedModuleNode;
invalidateModule(node: EvaluatedModuleNode): void;
/**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* @param id Resolved module ID
*/
getModuleSourceMapById(id: string): DecodedMap | null;
clear(): void;
}
declare class ESModulesEvaluator implements ModuleEvaluator {
readonly startOffset: number;
runInlinedModule(context: ModuleRunnerContext, code: string): Promise<any>;
runExternalModule(filepath: string): Promise<any>;
}
export { ESModulesEvaluator, EvaluatedModuleNode, EvaluatedModules, FetchFunctionOptions, FetchResult, ModuleRunner, ModuleRunnerTransport, ssrDynamicImportKey, ssrExportAllKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };
export type { FetchFunction, HMRLogger, InterceptorOptions, ModuleEvaluator, ModuleRunnerContext, ModuleRunnerHmr, ModuleRunnerImportMeta, ModuleRunnerOptions, ResolvedResult, SSRImportMetadata };

1311
node_modules/vite/dist/node/module-runner.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,87 @@
import { HotPayload } from '../../types/hmrPayload.js';
interface FetchFunctionOptions {
cached?: boolean;
startOffset?: number;
}
type FetchResult = CachedFetchResult | ExternalFetchResult | ViteFetchResult;
interface CachedFetchResult {
/**
* If module cached in the runner, we can just confirm
* it wasn't invalidated on the server side.
*/
cache: true;
}
interface ExternalFetchResult {
/**
* The path to the externalized module starting with file://,
* by default this will be imported via a dynamic "import"
* instead of being transformed by vite and loaded with vite runner
*/
externalize: string;
/**
* Type of the module. Will be used to determine if import statement is correct.
* For example, if Vite needs to throw an error if variable is not actually exported
*/
type: 'module' | 'commonjs' | 'builtin' | 'network';
}
interface ViteFetchResult {
/**
* Code that will be evaluated by vite runner
* by default this will be wrapped in an async function
*/
code: string;
/**
* File path of the module on disk.
* This will be resolved as import.meta.url/filename
* Will be equal to `null` for virtual modules
*/
file: string | null;
/**
* Module ID in the server module graph.
*/
id: string;
/**
* Module URL used in the import.
*/
url: string;
/**
* Invalidate module on the client side.
*/
invalidate: boolean;
}
type InvokeMethods = {
fetchModule: (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
};
type ModuleRunnerTransportHandlers = {
onMessage: (data: HotPayload) => void;
onDisconnection: () => void;
};
/**
* "send and connect" or "invoke" must be implemented
*/
interface ModuleRunnerTransport {
connect?(handlers: ModuleRunnerTransportHandlers): Promise<void> | void;
disconnect?(): Promise<void> | void;
send?(data: HotPayload): Promise<void> | void;
invoke?(data: HotPayload): Promise<{
result: any;
} | {
error: any;
}>;
timeout?: number;
}
interface NormalizedModuleRunnerTransport {
connect?(onMessage?: (data: HotPayload) => void): Promise<void> | void;
disconnect?(): Promise<void> | void;
send(data: HotPayload): Promise<void>;
invoke<T extends keyof InvokeMethods>(name: T, data: Parameters<InvokeMethods[T]>): Promise<ReturnType<Awaited<InvokeMethods[T]>>>;
}
declare const createWebSocketModuleRunnerTransport: (options: {
createConnection: () => WebSocket;
pingInterval?: number;
}) => Required<Pick<ModuleRunnerTransport, "connect" | "disconnect" | "send">>;
export { createWebSocketModuleRunnerTransport as c };
export type { ExternalFetchResult as E, FetchFunctionOptions as F, ModuleRunnerTransport as M, NormalizedModuleRunnerTransport as N, ViteFetchResult as V, FetchResult as a, ModuleRunnerTransportHandlers as b };

96
node_modules/vite/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,96 @@
const description =
' See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.'
warnCjsUsage()
// type utils
module.exports.defineConfig = (config) => config
// proxy cjs utils (sync functions)
Object.assign(module.exports, require('./dist/node-cjs/publicUtils.cjs'))
// async functions, can be redirect from ESM build
const asyncFunctions = [
'build',
'createServer',
'preview',
'transformWithEsbuild',
'resolveConfig',
'optimizeDeps',
'formatPostcssSourceMap',
'loadConfigFromFile',
'preprocessCSS',
'createBuilder',
'runnerImport',
]
asyncFunctions.forEach((name) => {
module.exports[name] = (...args) =>
import('./dist/node/index.js').then((i) => i[name](...args))
})
// variables and sync functions that cannot be used from cjs build
const disallowedVariables = [
// was not exposed in cjs from the beginning
'parseAst',
'parseAstAsync',
'buildErrorMessage',
'sortUserPlugins',
// Environment API related variables that are too big to include in the cjs build
'DevEnvironment',
'BuildEnvironment',
'createIdResolver',
'createRunnableDevEnvironment',
// can be redirected from ESM, but doesn't make sense as it's Environment API related
'fetchModule',
'moduleRunnerTransform',
// can be exposed, but doesn't make sense as it's Environment API related
'createServerHotChannel',
'createServerModuleRunner',
'createServerModuleRunnerTransport',
'isRunnableDevEnvironment',
'createFetchableDevEnvironment',
'isFetchableDevEnvironment',
]
disallowedVariables.forEach((name) => {
Object.defineProperty(module.exports, name, {
get() {
throw new Error(
`${name} is not available in the CJS build of Vite.` + description,
)
},
})
})
function warnCjsUsage() {
if (process.env.VITE_CJS_IGNORE_WARNING) return
const logLevelIndex = process.argv.findIndex((arg) =>
/^(?:-l|--logLevel)/.test(arg),
)
if (logLevelIndex > 0) {
const logLevelValue = process.argv[logLevelIndex + 1]
if (logLevelValue === 'silent' || logLevelValue === 'error') {
return
}
if (/silent|error/.test(process.argv[logLevelIndex])) {
return
}
}
const yellow = (str) => `\u001b[33m${str}\u001b[39m`
console.warn(
yellow("The CJS build of Vite's Node API is deprecated." + description),
)
if (process.env.VITE_CJS_TRACE) {
const e = {}
const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 100
Error.captureStackTrace(e)
Error.stackTraceLimit = stackTraceLimit
console.log(
e.stack
.split('\n')
.slice(1)
.filter((line) => !line.includes('(node:'))
.join('\n'),
)
}
}

6
node_modules/vite/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
/**
* @deprecated The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.
*/
declare const module: any
export = module

1
node_modules/vite/misc/false.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default false

1
node_modules/vite/misc/true.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default true

7
node_modules/vite/node_modules/fdir/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,7 @@
Copyright 2023 Abdullah Atta
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

91
node_modules/vite/node_modules/fdir/README.md generated vendored Normal file
View File

@@ -0,0 +1,91 @@
<p align="center">
<img src="https://github.com/thecodrr/fdir/raw/master/assets/fdir.gif" width="75%"/>
<h1 align="center">The Fastest Directory Crawler & Globber for NodeJS</h1>
<p align="center">
<a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/npm/v/fdir?style=for-the-badge"/></a>
<a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/npm/dw/fdir?style=for-the-badge"/></a>
<a href="https://codeclimate.com/github/thecodrr/fdir/maintainability"><img src="https://img.shields.io/codeclimate/maintainability-percentage/thecodrr/fdir?style=for-the-badge"/></a>
<a href="https://coveralls.io/github/thecodrr/fdir?branch=master"><img src="https://img.shields.io/coveralls/github/thecodrr/fdir?style=for-the-badge"/></a>
<a href="https://www.npmjs.com/package/fdir"><img src="https://img.shields.io/bundlephobia/minzip/fdir?style=for-the-badge"/></a>
<a href="https://www.producthunt.com/posts/fdir-every-millisecond-matters"><img src="https://img.shields.io/badge/ProductHunt-Upvote-red?style=for-the-badge&logo=product-hunt"/></a>
<a href="https://dev.to/thecodrr/how-i-wrote-the-fastest-directory-crawler-ever-3p9c"><img src="https://img.shields.io/badge/dev.to-Read%20Blog-black?style=for-the-badge&logo=dev.to"/></a>
<a href="./LICENSE"><img src="https://img.shields.io/github/license/thecodrr/fdir?style=for-the-badge"/></a>
</p>
</p>
**The Fastest:** Nothing similar (in the NodeJS world) beats `fdir` in speed. It can easily crawl a directory containing **1 million files in < 1 second.**
💡 **Stupidly Easy:** `fdir` uses expressive Builder pattern to build the crawler increasing code readability.
🤖 **Zero Dependencies\*:** `fdir` only uses NodeJS `fs` & `path` modules.
🕺 **Astonishingly Small:** < 2KB in size gzipped & minified.
🖮 **Hackable:** Extending `fdir` is extremely simple now that the new Builder API is here. Feel free to experiment around.
_\* `picomatch` must be installed manually by the user to support globbing._
## 🚄 Quickstart
### Installation
You can install using `npm`:
```sh
$ npm i fdir
```
or Yarn:
```sh
$ yarn add fdir
```
### Usage
```ts
import { fdir } from "fdir";
// create the builder
const api = new fdir().withFullPaths().crawl("path/to/dir");
// get all files in a directory synchronously
const files = api.sync();
// or asynchronously
api.withPromise().then((files) => {
// do something with the result here.
});
```
## Documentation:
Documentation for all methods is available [here](/documentation.md).
## 📊 Benchmarks:
Please check the benchmark against the latest version [here](/BENCHMARKS.md).
## 🙏Used by:
`fdir` is downloaded over 200k+ times a week by projects around the world. Here's a list of some notable projects using `fdir` in production:
> Note: if you think your project should be here, feel free to open an issue. Notable is anything with a considerable amount of GitHub stars.
1. [rollup/plugins](https://github.com/rollup/plugins)
2. [SuperchupuDev/tinyglobby](https://github.com/SuperchupuDev/tinyglobby)
3. [pulumi/pulumi](https://github.com/pulumi/pulumi)
4. [dotenvx/dotenvx](https://github.com/dotenvx/dotenvx)
5. [mdn/yari](https://github.com/mdn/yari)
6. [streetwriters/notesnook](https://github.com/streetwriters/notesnook)
7. [imba/imba](https://github.com/imba/imba)
8. [moroshko/react-scanner](https://github.com/moroshko/react-scanner)
9. [netlify/build](https://github.com/netlify/build)
10. [yassinedoghri/astro-i18next](https://github.com/yassinedoghri/astro-i18next)
11. [selfrefactor/rambda](https://github.com/selfrefactor/rambda)
12. [whyboris/Video-Hub-App](https://github.com/whyboris/Video-Hub-App)
## 🦮 LICENSE
Copyright &copy; 2024 Abdullah Atta under MIT. [Read full text here.](https://github.com/thecodrr/fdir/raw/master/LICENSE)

View File

@@ -0,0 +1,3 @@
import { Output, Options, ResultCallback } from "../types";
export declare function promise<TOutput extends Output>(root: string, options: Options): Promise<TOutput>;
export declare function callback<TOutput extends Output>(root: string, options: Options, callback: ResultCallback<TOutput>): void;

19
node_modules/vite/node_modules/fdir/dist/api/async.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callback = exports.promise = void 0;
const walker_1 = require("./walker");
function promise(root, options) {
return new Promise((resolve, reject) => {
callback(root, options, (err, output) => {
if (err)
return reject(err);
resolve(output);
});
});
}
exports.promise = promise;
function callback(root, options, callback) {
let walker = new walker_1.Walker(root, options, callback);
walker.start();
}
exports.callback = callback;

View File

@@ -0,0 +1,12 @@
export declare class Counter {
private _files;
private _directories;
set files(num: number);
get files(): number;
set directories(num: number);
get directories(): number;
/**
* @deprecated use `directories` instead
*/
get dirs(): number;
}

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Counter = void 0;
class Counter {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
}
exports.Counter = Counter;

View File

@@ -0,0 +1,3 @@
import { Options } from "../../types";
export type GetArrayFunction = (paths: string[]) => string[];
export declare function build(options: Options): GetArrayFunction;

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const getArray = (paths) => {
return paths;
};
const getArrayGroup = () => {
return [""].slice(0, 0);
};
function build(options) {
return options.group ? getArrayGroup : getArray;
}
exports.build = build;

View File

@@ -0,0 +1,3 @@
import { Group, Options } from "../../types";
export type GroupFilesFunction = (groups: Group[], directory: string, files: string[]) => void;
export declare function build(options: Options): GroupFilesFunction;

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const groupFiles = (groups, directory, files) => {
groups.push({ directory, files, dir: directory });
};
const empty = () => { };
function build(options) {
return options.group ? groupFiles : empty;
}
exports.build = build;

View File

@@ -0,0 +1,3 @@
import { Output, ResultCallback, WalkerState, Options } from "../../types";
export type InvokeCallbackFunction<TOutput extends Output> = (state: WalkerState, error: Error | null, callback?: ResultCallback<TOutput>) => null | TOutput;
export declare function build<TOutput extends Output>(options: Options, isSynchronous: boolean): InvokeCallbackFunction<TOutput>;

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const onlyCountsSync = (state) => {
return state.counts;
};
const groupsSync = (state) => {
return state.groups;
};
const defaultSync = (state) => {
return state.paths;
};
const limitFilesSync = (state) => {
return state.paths.slice(0, state.options.maxFiles);
};
const onlyCountsAsync = (state, error, callback) => {
report(error, callback, state.counts, state.options.suppressErrors);
return null;
};
const defaultAsync = (state, error, callback) => {
report(error, callback, state.paths, state.options.suppressErrors);
return null;
};
const limitFilesAsync = (state, error, callback) => {
report(error, callback, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
return null;
};
const groupsAsync = (state, error, callback) => {
report(error, callback, state.groups, state.options.suppressErrors);
return null;
};
function report(error, callback, output, suppressErrors) {
if (error && !suppressErrors)
callback(error, output);
else
callback(null, output);
}
function build(options, isSynchronous) {
const { onlyCounts, group, maxFiles } = options;
if (onlyCounts)
return isSynchronous
? onlyCountsSync
: onlyCountsAsync;
else if (group)
return isSynchronous
? groupsSync
: groupsAsync;
else if (maxFiles)
return isSynchronous
? limitFilesSync
: limitFilesAsync;
else
return isSynchronous
? defaultSync
: defaultAsync;
}
exports.build = build;

View File

@@ -0,0 +1,5 @@
import { WalkerState } from "../../types";
type IsRecursiveSymlinkFunction = (state: WalkerState, path: string, resolved: string, callback: (result: boolean) => void) => void;
export declare const isRecursiveAsync: IsRecursiveSymlinkFunction;
export declare function isRecursive(state: WalkerState, path: string, resolved: string): boolean;
export {};

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRecursive = exports.isRecursiveAsync = void 0;
const path_1 = require("path");
const fs_1 = require("fs");
const isRecursiveAsync = (state, path, resolved, callback) => {
if (state.options.useRealPaths)
return callback(state.visited.has(resolved + state.options.pathSeparator));
let parent = (0, path_1.dirname)(path);
if (parent + state.options.pathSeparator === state.root || parent === path)
return callback(false);
if (state.symlinks.get(parent) === resolved)
return callback(true);
(0, fs_1.readlink)(parent, (error, resolvedParent) => {
if (error)
return (0, exports.isRecursiveAsync)(state, parent, resolved, callback);
callback(resolvedParent === resolved);
});
};
exports.isRecursiveAsync = isRecursiveAsync;
function isRecursive(state, path, resolved) {
if (state.options.useRealPaths)
return state.visited.has(resolved + state.options.pathSeparator);
let parent = (0, path_1.dirname)(path);
if (parent + state.options.pathSeparator === state.root || parent === path)
return false;
try {
const resolvedParent = state.symlinks.get(parent) || (0, fs_1.readlinkSync)(parent);
return resolvedParent === resolved;
}
catch (e) {
return isRecursive(state, parent, resolved);
}
}
exports.isRecursive = isRecursive;

View File

@@ -0,0 +1,5 @@
import { Options, PathSeparator } from "../../types";
export declare function joinPathWithBasePath(filename: string, directoryPath: string): string;
export declare function joinDirectoryPath(filename: string, directoryPath: string, separator: PathSeparator): string;
export type JoinPathFunction = (filename: string, directoryPath: string) => string;
export declare function build(root: string, options: Options): JoinPathFunction;

View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = exports.joinDirectoryPath = exports.joinPathWithBasePath = void 0;
const path_1 = require("path");
const utils_1 = require("../../utils");
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
exports.joinPathWithBasePath = joinPathWithBasePath;
function joinPathWithRelativePath(root, options) {
return function (filename, directoryPath) {
const sameRoot = directoryPath.startsWith(root);
if (sameRoot)
return directoryPath.replace(root, "") + filename;
else
return ((0, utils_1.convertSlashes)((0, path_1.relative)(root, directoryPath), options.pathSeparator) +
options.pathSeparator +
filename);
};
}
function joinPath(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
exports.joinDirectoryPath = joinDirectoryPath;
function build(root, options) {
const { relativePaths, includeBasePath } = options;
return relativePaths && root
? joinPathWithRelativePath(root, options)
: includeBasePath
? joinPathWithBasePath
: joinPath;
}
exports.build = build;

View File

@@ -0,0 +1,3 @@
import { FilterPredicate, Options } from "../../types";
export type PushDirectoryFunction = (directoryPath: string, paths: string[], filters?: FilterPredicate[]) => void;
export declare function build(root: string, options: Options): PushDirectoryFunction;

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
function pushDirectoryWithRelativePath(root) {
return function (directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function (directoryPath, paths, filters) {
const relativePath = directoryPath.substring(root.length) || ".";
if (filters.every((filter) => filter(relativePath, true))) {
paths.push(relativePath);
}
};
}
const pushDirectory = (directoryPath, paths) => {
paths.push(directoryPath || ".");
};
const pushDirectoryFilter = (directoryPath, paths, filters) => {
const path = directoryPath || ".";
if (filters.every((filter) => filter(path, true))) {
paths.push(path);
}
};
const empty = () => { };
function build(root, options) {
const { includeDirs, filters, relativePaths } = options;
if (!includeDirs)
return empty;
if (relativePaths)
return filters && filters.length
? pushDirectoryFilterWithRelativePath(root)
: pushDirectoryWithRelativePath(root);
return filters && filters.length ? pushDirectoryFilter : pushDirectory;
}
exports.build = build;

View File

@@ -0,0 +1,3 @@
import { FilterPredicate, Options, Counts } from "../../types";
export type PushFileFunction = (directoryPath: string, paths: string[], counts: Counts, filters?: FilterPredicate[]) => void;
export declare function build(options: Options): PushFileFunction;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
if (filters.every((filter) => filter(filename, false)))
counts.files++;
};
const pushFileFilter = (filename, paths, _counts, filters) => {
if (filters.every((filter) => filter(filename, false)))
paths.push(filename);
};
const pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
};
const pushFile = (filename, paths) => {
paths.push(filename);
};
const empty = () => { };
function build(options) {
const { excludeFiles, filters, onlyCounts } = options;
if (excludeFiles)
return empty;
if (filters && filters.length) {
return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
}
else if (onlyCounts) {
return pushFileCount;
}
else {
return pushFile;
}
}
exports.build = build;

View File

@@ -0,0 +1,5 @@
/// <reference types="node" />
import fs from "fs";
import { WalkerState, Options } from "../../types";
export type ResolveSymlinkFunction = (path: string, state: WalkerState, callback: (stat: fs.Stats, path: string) => void) => void;
export declare function build(options: Options, isSynchronous: boolean): ResolveSymlinkFunction | null;

View File

@@ -0,0 +1,67 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = require("path");
const resolveSymlinksAsync = function (path, state, callback) {
const { queue, options: { suppressErrors }, } = state;
queue.enqueue();
fs_1.default.realpath(path, (error, resolvedPath) => {
if (error)
return queue.dequeue(suppressErrors ? null : error, state);
fs_1.default.stat(resolvedPath, (error, stat) => {
if (error)
return queue.dequeue(suppressErrors ? null : error, state);
if (stat.isDirectory() && isRecursive(path, resolvedPath, state))
return queue.dequeue(null, state);
callback(stat, resolvedPath);
queue.dequeue(null, state);
});
});
};
const resolveSymlinks = function (path, state, callback) {
const { queue, options: { suppressErrors }, } = state;
queue.enqueue();
try {
const resolvedPath = fs_1.default.realpathSync(path);
const stat = fs_1.default.statSync(resolvedPath);
if (stat.isDirectory() && isRecursive(path, resolvedPath, state))
return;
callback(stat, resolvedPath);
}
catch (e) {
if (!suppressErrors)
throw e;
}
};
function build(options, isSynchronous) {
if (!options.resolveSymlinks || options.excludeSymlinks)
return null;
return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
exports.build = build;
function isRecursive(path, resolved, state) {
if (state.options.useRealPaths)
return isRecursiveUsingRealPaths(resolved, state);
let parent = (0, path_1.dirname)(path);
let depth = 1;
while (parent !== state.root && depth < 2) {
const resolvedPath = state.symlinks.get(parent);
const isSameRoot = !!resolvedPath &&
(resolvedPath === resolved ||
resolvedPath.startsWith(resolved) ||
resolved.startsWith(resolvedPath));
if (isSameRoot)
depth++;
else
parent = (0, path_1.dirname)(parent);
}
state.symlinks.set(path, resolved);
return depth > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}

View File

@@ -0,0 +1,5 @@
/// <reference types="node" />
import { WalkerState } from "../../types";
import fs from "fs";
export type WalkDirectoryFunction = (state: WalkerState, crawlPath: string, directoryPath: string, depth: number, callback: (entries: fs.Dirent[], directoryPath: string, depth: number) => void) => void;
export declare function build(isSynchronous: boolean): WalkDirectoryFunction;

View File

@@ -0,0 +1,40 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const fs_1 = __importDefault(require("fs"));
const readdirOpts = { withFileTypes: true };
const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback) => {
if (currentDepth < 0)
return state.queue.dequeue(null, state);
state.visited.push(crawlPath);
state.counts.directories++;
state.queue.enqueue();
// Perf: Node >= 10 introduced withFileTypes that helps us
// skip an extra fs.stat call.
fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync = (state, crawlPath, directoryPath, currentDepth, callback) => {
if (currentDepth < 0)
return;
state.visited.push(crawlPath);
state.counts.directories++;
let entries = [];
try {
entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts);
}
catch (e) {
if (!state.options.suppressErrors)
throw e;
}
callback(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
exports.build = build;

View File

@@ -0,0 +1,15 @@
import { WalkerState } from "../types";
type OnQueueEmptyCallback = (error: Error | null, output: WalkerState) => void;
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
export declare class Queue {
private readonly onQueueEmpty;
private count;
constructor(onQueueEmpty: OnQueueEmptyCallback);
enqueue(): void;
dequeue(error: Error | null, output: WalkerState): void;
}
export {};

23
node_modules/vite/node_modules/fdir/dist/api/queue.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
class Queue {
onQueueEmpty;
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
this.count++;
}
dequeue(error, output) {
if (--this.count <= 0 || error)
this.onQueueEmpty(error, output);
}
}
exports.Queue = Queue;

View File

@@ -0,0 +1,2 @@
import { Output, Options } from "../types";
export declare function sync<TOutput extends Output>(root: string, options: Options): TOutput;

9
node_modules/vite/node_modules/fdir/dist/api/sync.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sync = void 0;
const walker_1 = require("./walker");
function sync(root, options) {
const walker = new walker_1.Walker(root, options);
return walker.start();
}
exports.sync = sync;

View File

@@ -0,0 +1,18 @@
import { ResultCallback, Options } from "../types";
import { Output } from "../types";
export declare class Walker<TOutput extends Output> {
private readonly root;
private readonly isSynchronous;
private readonly state;
private readonly joinPath;
private readonly pushDirectory;
private readonly pushFile;
private readonly getArray;
private readonly groupFiles;
private readonly resolveSymlink;
private readonly walkDirectory;
private readonly callbackInvoker;
constructor(root: string, options: Options, callback?: ResultCallback<TOutput>);
start(): TOutput | null;
private walk;
}

125
node_modules/vite/node_modules/fdir/dist/api/walker.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Walker = void 0;
const path_1 = require("path");
const utils_1 = require("../utils");
const joinPath = __importStar(require("./functions/join-path"));
const pushDirectory = __importStar(require("./functions/push-directory"));
const pushFile = __importStar(require("./functions/push-file"));
const getArray = __importStar(require("./functions/get-array"));
const groupFiles = __importStar(require("./functions/group-files"));
const resolveSymlink = __importStar(require("./functions/resolve-symlink"));
const invokeCallback = __importStar(require("./functions/invoke-callback"));
const walkDirectory = __importStar(require("./functions/walk-directory"));
const queue_1 = require("./queue");
const counter_1 = require("./counter");
class Walker {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback) {
this.isSynchronous = !callback;
this.callbackInvoker = invokeCallback.build(options, this.isSynchronous);
this.root = (0, utils_1.normalizePath)(root, options);
this.state = {
root: (0, utils_1.isRootDirectory)(this.root) ? this.root : this.root.slice(0, -1),
// Perf: we explicitly tell the compiler to optimize for String arrays
paths: [""].slice(0, 0),
groups: [],
counts: new counter_1.Counter(),
options,
queue: new queue_1.Queue((error, state) => this.callbackInvoker(state, error, callback)),
symlinks: new Map(),
visited: [""].slice(0, 0),
};
/*
* Perf: We conditionally change functions according to options. This gives a slight
* performance boost. Since these functions are so small, they are automatically inlined
* by the javascript engine so there's no function call overhead (in most cases).
*/
this.joinPath = joinPath.build(this.root, options);
this.pushDirectory = pushDirectory.build(this.root, options);
this.pushFile = pushFile.build(options);
this.getArray = getArray.build(options);
this.groupFiles = groupFiles.build(options);
this.resolveSymlink = resolveSymlink.build(options, this.isSynchronous);
this.walkDirectory = walkDirectory.build(this.isSynchronous);
}
start() {
this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth) => {
const { paths, options: { filters, resolveSymlinks, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator, }, } = this.state;
if ((signal && signal.aborted) || (maxFiles && paths.length > maxFiles))
return;
this.pushDirectory(directoryPath, paths, filters);
const files = this.getArray(this.state.paths);
for (let i = 0; i < entries.length; ++i) {
const entry = entries[i];
if (entry.isFile() ||
(entry.isSymbolicLink() && !resolveSymlinks && !excludeSymlinks)) {
const filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
}
else if (entry.isDirectory()) {
let path = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path))
continue;
this.walkDirectory(this.state, path, path, depth - 1, this.walk);
}
else if (entry.isSymbolicLink() && this.resolveSymlink) {
let path = joinPath.joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path, this.state, (stat, resolvedPath) => {
if (stat.isDirectory()) {
resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
if (exclude &&
exclude(entry.name, useRealPaths ? resolvedPath : path + pathSeparator))
return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk);
}
else {
resolvedPath = useRealPaths ? resolvedPath : path;
const filename = (0, path_1.basename)(resolvedPath);
const directoryPath = (0, utils_1.normalizePath)((0, path_1.dirname)(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath);
this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
}
exports.Walker = Walker;

View File

@@ -0,0 +1,9 @@
import { Options, Output, ResultCallback } from "../types";
export declare class APIBuilder<TReturnType extends Output> {
private readonly root;
private readonly options;
constructor(root: string, options: Options);
withPromise(): Promise<TReturnType>;
withCallback(cb: ResultCallback<TReturnType>): void;
sync(): TReturnType;
}

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIBuilder = void 0;
const async_1 = require("../api/async");
const sync_1 = require("../api/sync");
class APIBuilder {
root;
options;
constructor(root, options) {
this.root = root;
this.options = options;
}
withPromise() {
return (0, async_1.promise)(this.root, this.options);
}
withCallback(cb) {
(0, async_1.callback)(this.root, this.options, cb);
}
sync() {
return (0, sync_1.sync)(this.root, this.options);
}
}
exports.APIBuilder = APIBuilder;

View File

@@ -0,0 +1,41 @@
/// <reference types="node" />
import { Output, OnlyCountsOutput, GroupOutput, PathsOutput, Options, FilterPredicate, ExcludePredicate, GlobParams } from "../types";
import { APIBuilder } from "./api-builder";
import type picomatch from "picomatch";
export declare class Builder<TReturnType extends Output = PathsOutput, TGlobFunction = typeof picomatch> {
private readonly globCache;
private options;
private globFunction?;
constructor(options?: Partial<Options<TGlobFunction>>);
group(): Builder<GroupOutput, TGlobFunction>;
withPathSeparator(separator: "/" | "\\"): this;
withBasePath(): this;
withRelativePaths(): this;
withDirs(): this;
withMaxDepth(depth: number): this;
withMaxFiles(limit: number): this;
withFullPaths(): this;
withErrors(): this;
withSymlinks({ resolvePaths }?: {
resolvePaths?: boolean | undefined;
}): this;
withAbortSignal(signal: AbortSignal): this;
normalize(): this;
filter(predicate: FilterPredicate): this;
onlyDirs(): this;
exclude(predicate: ExcludePredicate): this;
onlyCounts(): Builder<OnlyCountsOutput, TGlobFunction>;
crawl(root?: string): APIBuilder<TReturnType>;
withGlobFunction<TFunc>(fn: TFunc): Builder<TReturnType, TFunc>;
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
crawlWithOptions(root: string, options: Partial<Options<TGlobFunction>>): APIBuilder<TReturnType>;
glob(...patterns: string[]): Builder<TReturnType, TGlobFunction>;
globWithOptions(patterns: string[]): Builder<TReturnType, TGlobFunction>;
globWithOptions(patterns: string[], ...options: GlobParams<TGlobFunction>): Builder<TReturnType, TGlobFunction>;
}

View File

@@ -0,0 +1,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Builder = void 0;
const path_1 = require("path");
const api_builder_1 = require("./api-builder");
var pm = null;
/* c8 ignore next 6 */
try {
require.resolve("picomatch");
pm = require("picomatch");
}
catch (_e) {
// do nothing
}
class Builder {
globCache = {};
options = {
maxDepth: Infinity,
suppressErrors: true,
pathSeparator: path_1.sep,
filters: [],
};
globFunction;
constructor(options) {
this.options = { ...this.options, ...options };
this.globFunction = this.options.globFunction;
}
group() {
this.options.group = true;
return this;
}
withPathSeparator(separator) {
this.options.pathSeparator = separator;
return this;
}
withBasePath() {
this.options.includeBasePath = true;
return this;
}
withRelativePaths() {
this.options.relativePaths = true;
return this;
}
withDirs() {
this.options.includeDirs = true;
return this;
}
withMaxDepth(depth) {
this.options.maxDepth = depth;
return this;
}
withMaxFiles(limit) {
this.options.maxFiles = limit;
return this;
}
withFullPaths() {
this.options.resolvePaths = true;
this.options.includeBasePath = true;
return this;
}
withErrors() {
this.options.suppressErrors = false;
return this;
}
withSymlinks({ resolvePaths = true } = {}) {
this.options.resolveSymlinks = true;
this.options.useRealPaths = resolvePaths;
return this.withFullPaths();
}
withAbortSignal(signal) {
this.options.signal = signal;
return this;
}
normalize() {
this.options.normalizePath = true;
return this;
}
filter(predicate) {
this.options.filters.push(predicate);
return this;
}
onlyDirs() {
this.options.excludeFiles = true;
this.options.includeDirs = true;
return this;
}
exclude(predicate) {
this.options.exclude = predicate;
return this;
}
onlyCounts() {
this.options.onlyCounts = true;
return this;
}
crawl(root) {
return new api_builder_1.APIBuilder(root || ".", this.options);
}
withGlobFunction(fn) {
// cast this since we don't have the new type params yet
this.globFunction = fn;
return this;
}
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
/* c8 ignore next 4 */
crawlWithOptions(root, options) {
this.options = { ...this.options, ...options };
return new api_builder_1.APIBuilder(root || ".", this.options);
}
glob(...patterns) {
if (this.globFunction) {
return this.globWithOptions(patterns);
}
return this.globWithOptions(patterns, ...[{ dot: true }]);
}
globWithOptions(patterns, ...options) {
const globFn = (this.globFunction || pm);
/* c8 ignore next 5 */
if (!globFn) {
throw new Error("Please specify a glob function to use glob matching.");
}
var isMatch = this.globCache[patterns.join("\0")];
if (!isMatch) {
isMatch = globFn(patterns, ...options);
this.globCache[patterns.join("\0")] = isMatch;
}
this.options.filters.push((path) => isMatch(path));
return this;
}
}
exports.Builder = Builder;

4
node_modules/vite/node_modules/fdir/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import { Builder } from "./builder";
export { Builder as fdir };
export type Fdir = typeof Builder;
export * from "./types";

20
node_modules/vite/node_modules/fdir/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fdir = void 0;
const builder_1 = require("./builder");
Object.defineProperty(exports, "fdir", { enumerable: true, get: function () { return builder_1.Builder; } });
__exportStar(require("./types"), exports);

View File

@@ -0,0 +1,3 @@
export declare function findCommonRoots(patterns: string[]): string[];
export declare function findDirectoryPatterns(patterns: string[]): string[];
export declare function findMaxDepth(patterns: string[]): number | false;

54
node_modules/vite/node_modules/fdir/dist/optimizer.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.findMaxDepth = exports.findDirectoryPatterns = exports.findCommonRoots = void 0;
// Glob Optimizations:
// 1. Find common roots and only iterate on them
// For example:
// 1. "node_modules/**/*.ts" only requires us to search in node_modules
// folder.
// 2. Similarly, multiple glob patterns can have common deterministic roots
// The optimizer's job is to find these roots and only crawl them.
// 3. If any of the glob patterns have a globstar i.e. **/ in them, we
// should bail out.
// 2. Find out if glob is requesting only directories
// 3. Find maximum depth requested
// 4. If glob contains a root that doesn't exist, bail out
const braces_1 = require("braces");
const glob_parent_1 = __importDefault(require("glob-parent"));
function findCommonRoots(patterns) {
const allRoots = new Set();
patterns = patterns.map((p) => (p.includes("{") ? (0, braces_1.expand)(p) : p)).flat();
for (const pattern of patterns) {
const parent = (0, glob_parent_1.default)(pattern);
if (parent === ".")
return [];
allRoots.add(parent);
}
return Array.from(allRoots.values()).filter((root) => {
for (const r of allRoots) {
if (r === root)
continue;
if (root.startsWith(r))
return false;
}
return true;
});
}
exports.findCommonRoots = findCommonRoots;
function findDirectoryPatterns(patterns) {
return patterns.filter((p) => p.endsWith("/"));
}
exports.findDirectoryPatterns = findDirectoryPatterns;
function findMaxDepth(patterns) {
const isGlobstar = patterns.some((p) => p.includes("**/") || p.includes("/**") || p === "**");
if (isGlobstar)
return false;
const maxDepth = patterns.reduce((depth, p) => {
return Math.max(depth, p.split("/").filter(Boolean).length);
}, 0);
return maxDepth;
}
exports.findMaxDepth = findMaxDepth;

60
node_modules/vite/node_modules/fdir/dist/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,60 @@
/// <reference types="node" />
import { Queue } from "./api/queue";
export type Counts = {
files: number;
directories: number;
/**
* @deprecated use `directories` instead. Will be removed in v7.0.
*/
dirs: number;
};
export type Group = {
directory: string;
files: string[];
/**
* @deprecated use `directory` instead. Will be removed in v7.0.
*/
dir: string;
};
export type GroupOutput = Group[];
export type OnlyCountsOutput = Counts;
export type PathsOutput = string[];
export type Output = OnlyCountsOutput | PathsOutput | GroupOutput;
export type WalkerState = {
root: string;
paths: string[];
groups: Group[];
counts: Counts;
options: Options;
queue: Queue;
symlinks: Map<string, string>;
visited: string[];
};
export type ResultCallback<TOutput extends Output> = (error: Error | null, output: TOutput) => void;
export type FilterPredicate = (path: string, isDirectory: boolean) => boolean;
export type ExcludePredicate = (dirName: string, dirPath: string) => boolean;
export type PathSeparator = "/" | "\\";
export type Options<TGlobFunction = unknown> = {
includeBasePath?: boolean;
includeDirs?: boolean;
normalizePath?: boolean;
maxDepth: number;
maxFiles?: number;
resolvePaths?: boolean;
suppressErrors: boolean;
group?: boolean;
onlyCounts?: boolean;
filters: FilterPredicate[];
resolveSymlinks?: boolean;
useRealPaths?: boolean;
excludeFiles?: boolean;
excludeSymlinks?: boolean;
exclude?: ExcludePredicate;
relativePaths?: boolean;
pathSeparator: PathSeparator;
signal?: AbortSignal;
globFunction?: TGlobFunction;
};
export type GlobMatcher = (test: string) => boolean;
export type GlobFunction = (glob: string | string[], ...params: unknown[]) => GlobMatcher;
export type GlobParams<T> = T extends (globs: string | string[], ...params: infer TParams extends unknown[]) => GlobMatcher ? TParams : [];

2
node_modules/vite/node_modules/fdir/dist/types.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

9
node_modules/vite/node_modules/fdir/dist/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { PathSeparator } from "./types";
export declare function cleanPath(path: string): string;
export declare function convertSlashes(path: string, separator: PathSeparator): string;
export declare function isRootDirectory(path: string): boolean;
export declare function normalizePath(path: string, options: {
resolvePaths?: boolean;
normalizePath?: boolean;
pathSeparator: PathSeparator;
}): string;

36
node_modules/vite/node_modules/fdir/dist/utils.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePath = exports.isRootDirectory = exports.convertSlashes = exports.cleanPath = void 0;
const path_1 = require("path");
function cleanPath(path) {
let normalized = (0, path_1.normalize)(path);
// we have to remove the last path separator
// to account for / root path
if (normalized.length > 1 && normalized[normalized.length - 1] === path_1.sep)
normalized = normalized.substring(0, normalized.length - 1);
return normalized;
}
exports.cleanPath = cleanPath;
const SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path, separator) {
return path.replace(SLASHES_REGEX, separator);
}
exports.convertSlashes = convertSlashes;
function isRootDirectory(path) {
return path === "/" || /^[a-z]:\\$/i.test(path);
}
exports.isRootDirectory = isRootDirectory;
function normalizePath(path, options) {
const { resolvePaths, normalizePath, pathSeparator } = options;
const pathNeedsCleaning = (process.platform === "win32" && path.includes("/")) ||
path.startsWith(".");
if (resolvePaths)
path = (0, path_1.resolve)(path);
if (normalizePath || pathNeedsCleaning)
path = cleanPath(path);
if (path === ".")
return "";
const needsSeperator = path[path.length - 1] !== pathSeparator;
return convertSlashes(needsSeperator ? path + pathSeparator : path, pathSeparator);
}
exports.normalizePath = normalizePath;

90
node_modules/vite/node_modules/fdir/package.json generated vendored Normal file
View File

@@ -0,0 +1,90 @@
{
"name": "fdir",
"version": "6.4.4",
"description": "The fastest directory crawler & globbing alternative to glob, fast-glob, & tiny-glob. Crawls 1m files in < 1s",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"prepublishOnly": "npm run test && npm run build",
"build": "tsc",
"format": "prettier --write src __tests__ benchmarks",
"test": "vitest run __tests__/",
"test:coverage": "vitest run --coverage __tests__/",
"test:watch": "vitest __tests__/",
"bench": "ts-node benchmarks/benchmark.js",
"bench:glob": "ts-node benchmarks/glob-benchmark.ts",
"bench:fdir": "ts-node benchmarks/fdir-benchmark.ts",
"release": "./scripts/release.sh"
},
"repository": {
"type": "git",
"url": "git+https://github.com/thecodrr/fdir.git"
},
"keywords": [
"util",
"os",
"sys",
"fs",
"walk",
"crawler",
"directory",
"files",
"io",
"tiny-glob",
"glob",
"fast-glob",
"speed",
"javascript",
"nodejs"
],
"author": "thecodrr <thecodrr@protonmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/thecodrr/fdir/issues"
},
"homepage": "https://github.com/thecodrr/fdir#readme",
"devDependencies": {
"@types/glob": "^8.1.0",
"@types/mock-fs": "^4.13.4",
"@types/node": "^20.9.4",
"@types/picomatch": "^3.0.0",
"@types/tap": "^15.0.11",
"@vitest/coverage-v8": "^0.34.6",
"all-files-in-tree": "^1.1.2",
"benny": "^3.7.1",
"csv-to-markdown-table": "^1.3.1",
"expect": "^29.7.0",
"fast-glob": "^3.3.2",
"fdir1": "npm:fdir@1.2.0",
"fdir2": "npm:fdir@2.1.0",
"fdir3": "npm:fdir@3.4.2",
"fdir4": "npm:fdir@4.1.0",
"fdir5": "npm:fdir@5.0.0",
"fs-readdir-recursive": "^1.1.0",
"get-all-files": "^4.1.0",
"glob": "^10.3.10",
"klaw-sync": "^6.0.0",
"mock-fs": "^5.2.0",
"picomatch": "^4.0.2",
"prettier": "^3.5.3",
"recur-readdir": "0.0.1",
"recursive-files": "^1.0.2",
"recursive-fs": "^2.1.0",
"recursive-readdir": "^2.2.3",
"rrdir": "^12.1.0",
"systeminformation": "^5.21.17",
"tiny-glob": "^0.2.9",
"ts-node": "^10.9.1",
"typescript": "^5.3.2",
"vitest": "^0.34.6",
"walk-sync": "^3.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
}

21
node_modules/vite/node_modules/picomatch/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-present, Jon Schlinkert.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

738
node_modules/vite/node_modules/picomatch/README.md generated vendored Normal file
View File

@@ -0,0 +1,738 @@
<h1 align="center">Picomatch</h1>
<p align="center">
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/v/picomatch.svg" alt="version">
</a>
<a href="https://github.com/micromatch/picomatch/actions?workflow=Tests">
<img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status">
</a>
<a href="https://coveralls.io/github/micromatch/picomatch">
<img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status">
</a>
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads">
</a>
</p>
<br>
<br>
<p align="center">
<strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br>
<em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em>
</p>
<br>
<br>
## Why picomatch?
* **Lightweight** - No dependencies
* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
* **Well tested** - Thousands of unit tests
See the [library comparison](#library-comparisons) to other libraries.
<br>
<br>
## Table of Contents
<details><summary> Click to expand </summary>
- [Install](#install)
- [Usage](#usage)
- [API](#api)
* [picomatch](#picomatch)
* [.test](#test)
* [.matchBase](#matchbase)
* [.isMatch](#ismatch)
* [.parse](#parse)
* [.scan](#scan)
* [.compileRe](#compilere)
* [.makeRe](#makere)
* [.toRegex](#toregex)
- [Options](#options)
* [Picomatch options](#picomatch-options)
* [Scan Options](#scan-options)
* [Options Examples](#options-examples)
- [Globbing features](#globbing-features)
* [Basic globbing](#basic-globbing)
* [Advanced globbing](#advanced-globbing)
* [Braces](#braces)
* [Matching special characters as literals](#matching-special-characters-as-literals)
- [Library Comparisons](#library-comparisons)
- [Benchmarks](#benchmarks)
- [Philosophies](#philosophies)
- [About](#about)
* [Author](#author)
* [License](#license)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
</details>
<br>
<br>
## Install
Install with [npm](https://www.npmjs.com/):
```sh
npm install --save picomatch
```
<br>
## Usage
The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
```js
const pm = require('picomatch');
const isMatch = pm('*.js');
console.log(isMatch('abcd')); //=> false
console.log(isMatch('a.js')); //=> true
console.log(isMatch('a.md')); //=> false
console.log(isMatch('a/b.js')); //=> false
```
<br>
## API
### [picomatch](lib/picomatch.js#L31)
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.
**Params**
* `globs` **{String|Array}**: One or more glob patterns.
* `options` **{Object=}**
* `returns` **{Function=}**: Returns a matcher function.
**Example**
```js
const picomatch = require('picomatch');
// picomatch(glob[, options]);
const isMatch = picomatch('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true
```
**Example without node.js**
For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
```js
const picomatch = require('picomatch/posix');
// the same API, defaulting to posix paths
const isMatch = picomatch('a/*');
console.log(isMatch('a\\b')); //=> false
console.log(isMatch('a/b')); //=> true
// you can still configure the matcher function to accept windows paths
const isMatch = picomatch('a/*', { options: windows });
console.log(isMatch('a\\b')); //=> true
console.log(isMatch('a/b')); //=> true
```
### [.test](lib/picomatch.js#L116)
Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
**Params**
* `input` **{String}**: String to test.
* `regex` **{RegExp}**
* `returns` **{Object}**: Returns an object with matching info.
**Example**
```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' }
```
### [.matchBase](lib/picomatch.js#L160)
Match the basename of a filepath.
**Params**
* `input` **{String}**: String to test.
* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
* `returns` **{Boolean}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.matchBase(input, glob[, options]);
console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
```
### [.isMatch](lib/picomatch.js#L182)
Returns true if **any** of the given glob `patterns` match the specified `string`.
**Params**
* **{String|Array}**: str The string to test.
* **{String|Array}**: patterns One or more glob patterns to use for matching.
* **{Object}**: See available [options](#options).
* `returns` **{Boolean}**: Returns true if any patterns match `str`
**Example**
```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
```
### [.parse](lib/picomatch.js#L198)
Parse a glob pattern to create the source string for a regular expression.
**Params**
* `pattern` **{String}**
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.parse(pattern[, options]);
```
### [.scan](lib/picomatch.js#L230)
Scan a glob pattern to separate the pattern into segments.
**Params**
* `input` **{String}**: Glob pattern to scan.
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with
**Example**
```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 }
```
### [.compileRe](lib/picomatch.js#L244)
Compile a regular expression from the `state` object returned by the
[parse()](#parse) method.
**Params**
* `state` **{Object}**
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* `returns` **{RegExp}**
### [.makeRe](lib/picomatch.js#L285)
Create a regular expression from a parsed glob pattern.
**Params**
* `state` **{String}**: The object returned from the `.parse` method.
* `options` **{Object}**
* `returnOutput` **{Boolean}**: 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.
* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* `returns` **{RegExp}**: Returns a regex created from the given pattern.
**Example**
```js
const picomatch = require('picomatch');
const state = picomatch.parse('*.js');
// picomatch.compileRe(state[, options]);
console.log(picomatch.compileRe(state));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.toRegex](lib/picomatch.js#L320)
Create a regular expression from the given regex source string.
**Params**
* `source` **{String}**: Regular expression source string.
* `options` **{Object}**
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.toRegex(source[, options]);
const { output } = picomatch.parse('*.js');
console.log(picomatch.toRegex(output));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
<br>
## Options
### Picomatch options
The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` |
| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. |
| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
| `matchBase` | `boolean` | `false` | Alias for `basename` |
| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. |
| `noext` | `boolean` | `false` | Alias for `noextglob` |
| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. |
| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself |
| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. |
| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. |
### Scan Options
In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.scan('!./foo/*.js', { tokens: true });
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,
// maxDepth: 2,
// tokens: [
// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
// { value: 'foo', depth: 1, isGlob: false },
// { value: '*.js', depth: 1, isGlob: true }
// ],
// slashes: [ 2, 6 ],
// parts: [ 'foo', '*.js' ]
// }
```
<br>
### Options Examples
#### options.expandRange
**Type**: `function`
**Default**: `undefined`
Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
**Example**
The following example shows how to create a glob that matches a folder
```js
const fill = require('fill-range');
const regex = pm.makeRe('foo/{01..25}/bar', {
expandRange(a, b) {
return `(${fill(a, b, { toRegex: true })})`;
}
});
console.log(regex);
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false
```
#### options.format
**Type**: `function`
**Default**: `undefined`
Custom function for formatting strings before they're matched.
**Example**
```js
// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')); //=> true
```
#### options.onMatch
```js
const onMatch = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onMatch });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onIgnore
```js
const onIgnore = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onResult
```js
const onResult = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
<br>
<br>
## Globbing features
* [Basic globbing](#basic-globbing) (Wildcard matching)
* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
### Basic globbing
| **Character** | **Description** |
| --- | --- |
| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
#### Matching behavior vs. Bash
Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
<br>
### Advanced globbing
* [extglobs](#extglobs)
* [POSIX brackets](#posix-brackets)
* [Braces](#brace-expansion)
#### Extglobs
| **Pattern** | **Description** |
| --- | --- |
| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
| `!(pattern)` | Match _anything but_ `pattern` |
**Examples**
```js
const pm = require('picomatch');
// *(pattern) matches ZERO or more of "pattern"
console.log(pm.isMatch('a', 'a*(z)')); // true
console.log(pm.isMatch('az', 'a*(z)')); // true
console.log(pm.isMatch('azzz', 'a*(z)')); // true
// +(pattern) matches ONE or more of "pattern"
console.log(pm.isMatch('a', 'a+(z)')); // false
console.log(pm.isMatch('az', 'a+(z)')); // true
console.log(pm.isMatch('azzz', 'a+(z)')); // true
// supports multiple extglobs
console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
// supports nested extglobs
console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
```
#### POSIX brackets
POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
**Enable POSIX bracket support**
```js
console.log(pm.makeRe('[[:word:]]+', { posix: true }));
//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
```
**Supported POSIX classes**
The following named POSIX bracket expressions are supported:
* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
### Braces
Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces.
### Matching special characters as literals
If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
**Special Characters**
Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
To match any of the following characters as literals: `$^*+?()[]
Examples:
```js
console.log(pm.makeRe('foo/bar \\(1\\)'));
console.log(pm.makeRe('foo/bar \\(1\\)'));
```
<br>
<br>
## Library Comparisons
The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
| File system operations | - | - | - | - | - | - | - |
<br>
<br>
## Benchmarks
Performance comparison of picomatch and minimatch.
_(Pay special attention to the last three benchmarks. Minimatch freezes on long ranges.)_
```
# .makeRe star (*)
picomatch x 4,449,159 ops/sec ±0.24% (97 runs sampled)
minimatch x 632,772 ops/sec ±0.14% (98 runs sampled)
# .makeRe star; dot=true (*)
picomatch x 3,500,079 ops/sec ±0.26% (99 runs sampled)
minimatch x 564,916 ops/sec ±0.23% (96 runs sampled)
# .makeRe globstar (**)
picomatch x 3,261,000 ops/sec ±0.27% (98 runs sampled)
minimatch x 1,664,766 ops/sec ±0.20% (100 runs sampled)
# .makeRe globstars (**/**/**)
picomatch x 3,284,469 ops/sec ±0.18% (97 runs sampled)
minimatch x 1,435,880 ops/sec ±0.34% (95 runs sampled)
# .makeRe with leading star (*.txt)
picomatch x 3,100,197 ops/sec ±0.35% (99 runs sampled)
minimatch x 428,347 ops/sec ±0.42% (94 runs sampled)
# .makeRe - basic braces ({a,b,c}*.txt)
picomatch x 443,578 ops/sec ±1.33% (89 runs sampled)
minimatch x 107,143 ops/sec ±0.35% (94 runs sampled)
# .makeRe - short ranges ({a..z}*.txt)
picomatch x 415,484 ops/sec ±0.76% (96 runs sampled)
minimatch x 14,299 ops/sec ±0.26% (96 runs sampled)
# .makeRe - medium ranges ({1..100000}*.txt)
picomatch x 395,020 ops/sec ±0.87% (89 runs sampled)
minimatch x 2 ops/sec ±4.59% (10 runs sampled)
# .makeRe - long ranges ({1..10000000}*.txt)
picomatch x 400,036 ops/sec ±0.83% (90 runs sampled)
minimatch (FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory)
```
<br>
<br>
## Philosophies
The goal of this library is to be blazing fast, without compromising on accuracy.
**Accuracy**
The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
**Performance**
Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
<br>
<br>
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

17
node_modules/vite/node_modules/picomatch/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
'use strict';
const pico = require('./lib/picomatch');
const utils = require('./lib/utils');
function picomatch(glob, options, returnState = false) {
// default to os.platform()
if (options && (options.windows === null || options.windows === undefined)) {
// don't mutate the original options object
options = { ...options, windows: utils.isWindows() };
}
return pico(glob, options, returnState);
}
Object.assign(picomatch, pico);
module.exports = picomatch;

View File

@@ -0,0 +1,179 @@
'use strict';
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 = `${QMARK}*?`;
const SEP = '/';
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,
START_ANCHOR,
SEP
};
/**
* 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}]|$)`,
SEP: '\\'
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE = {
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'
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// 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 */
/**
* 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;
}
};

1085
node_modules/vite/node_modules/picomatch/lib/parse.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,341 @@
'use strict';
const scan = require('./scan');
const parse = require('./parse');
const utils = require('./utils');
const constants = require('./constants');
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 = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map(input => picomatch(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 = opts.windows;
const regex = isState
? picomatch.compileRe(glob, options)
: picomatch.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(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.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.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.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.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.matchBase = (input, glob, options) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(utils.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.isMatch = (str, patterns, options) => picomatch(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.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
return parse(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.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.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.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.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.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse(input, options);
}
return picomatch.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.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.constants = constants;
/**
* Expose "picomatch"
*/
module.exports = picomatch;

391
node_modules/vite/node_modules/picomatch/lib/scan.js generated vendored Normal file
View File

@@ -0,0 +1,391 @@
'use strict';
const utils = require('./utils');
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 /* ] */
} = require('./constants');
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 = (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.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.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;
};
module.exports = scan;

72
node_modules/vite/node_modules/picomatch/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1,72 @@
/*global navigator*/
'use strict';
const {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require('./constants');
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.isWindows = () => {
if (typeof navigator !== 'undefined' && navigator.platform) {
const platform = navigator.platform.toLowerCase();
return platform === 'win32' || platform === 'windows';
}
if (typeof process !== 'undefined' && process.platform) {
return process.platform === 'win32';
}
return false;
};
exports.removeBackslashes = str => {
return str.replace(REGEX_REMOVE_BACKSLASH, match => {
return match === '\\' ? '' : match;
});
};
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;
};
exports.basename = (path, { windows } = {}) => {
const segs = path.split(windows ? /[\\/]/ : '/');
const last = segs[segs.length - 1];
if (last === '') {
return segs[segs.length - 2];
}
return last;
};

83
node_modules/vite/node_modules/picomatch/package.json generated vendored Normal file
View File

@@ -0,0 +1,83 @@
{
"name": "picomatch",
"description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.",
"version": "4.0.2",
"homepage": "https://github.com/micromatch/picomatch",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"funding": "https://github.com/sponsors/jonschlinkert",
"repository": "micromatch/picomatch",
"bugs": {
"url": "https://github.com/micromatch/picomatch/issues"
},
"license": "MIT",
"files": [
"index.js",
"posix.js",
"lib"
],
"sideEffects": false,
"main": "index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .",
"mocha": "mocha --reporter dot",
"test": "npm run lint && npm run mocha",
"test:ci": "npm run test:cover",
"test:cover": "nyc npm run mocha"
},
"devDependencies": {
"eslint": "^8.57.0",
"fill-range": "^7.0.1",
"gulp-format-md": "^2.0.0",
"mocha": "^10.4.0",
"nyc": "^15.1.0",
"time-require": "github:jonschlinkert/time-require"
},
"keywords": [
"glob",
"match",
"picomatch"
],
"nyc": {
"reporter": [
"html",
"lcov",
"text-summary"
]
},
"verb": {
"toc": {
"render": true,
"method": "preWrite",
"maxdepth": 3
},
"layout": "empty",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"related": {
"list": [
"braces",
"micromatch"
]
},
"reflinks": [
"braces",
"expand-brackets",
"extglob",
"fill-range",
"micromatch",
"minimatch",
"nanomatch",
"picomatch"
]
}
}

3
node_modules/vite/node_modules/picomatch/posix.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
'use strict';
module.exports = require('./lib/picomatch');

204
node_modules/vite/package.json generated vendored Normal file
View File

@@ -0,0 +1,204 @@
{
"name": "vite",
"version": "6.3.5",
"type": "module",
"license": "MIT",
"author": "Evan You",
"description": "Native-ESM powered web dev build tool",
"bin": {
"vite": "bin/vite.js"
},
"keywords": [
"frontend",
"framework",
"hmr",
"dev-server",
"build-tool",
"vite"
],
"main": "./dist/node/index.js",
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"module-sync": "./dist/node/index.js",
"import": "./dist/node/index.js",
"require": "./index.cjs"
},
"./client": {
"types": "./client.d.ts"
},
"./module-runner": "./dist/node/module-runner.js",
"./dist/client/*": "./dist/client/*",
"./types/*": {
"types": "./types/*"
},
"./types/internal/*": null,
"./package.json": "./package.json"
},
"typesVersions": {
"*": {
"module-runner": [
"dist/node/module-runner.d.ts"
]
}
},
"imports": {
"#module-sync-enabled": {
"module-sync": "./misc/true.js",
"default": "./misc/false.js"
}
},
"files": [
"bin",
"dist",
"misc/**/*.js",
"client.d.ts",
"index.cjs",
"index.d.cts",
"types"
],
"engines": {
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite.git",
"directory": "packages/vite"
},
"bugs": {
"url": "https://github.com/vitejs/vite/issues"
},
"homepage": "https://vite.dev",
"funding": "https://github.com/vitejs/vite?sponsor=1",
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
"picomatch": "^4.0.2",
"postcss": "^8.5.3",
"rollup": "^4.34.9",
"tinyglobby": "^0.2.13"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"devDependencies": {
"@ampproject/remapping": "^2.3.0",
"@babel/parser": "^7.27.0",
"@jridgewell/trace-mapping": "^0.3.25",
"@polka/compression": "^1.0.0-next.25",
"@rollup/plugin-alias": "^5.1.1",
"@rollup/plugin-commonjs": "^28.0.3",
"@rollup/plugin-dynamic-import-vars": "2.1.4",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "16.0.1",
"@rollup/pluginutils": "^5.1.4",
"@types/escape-html": "^1.0.4",
"@types/pnpapi": "^0.0.5",
"artichokie": "^0.3.1",
"cac": "^6.7.14",
"chokidar": "^3.6.0",
"connect": "^3.7.0",
"convert-source-map": "^2.0.0",
"cors": "^2.8.5",
"cross-spawn": "^7.0.6",
"debug": "^4.4.0",
"dep-types": "link:./src/types",
"dotenv": "^16.5.0",
"dotenv-expand": "^12.0.2",
"es-module-lexer": "^1.6.0",
"escape-html": "^1.0.3",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
"http-proxy": "^1.18.1",
"launch-editor-middleware": "^2.10.0",
"lightningcss": "^1.29.3",
"magic-string": "^0.30.17",
"mlly": "^1.7.4",
"mrmime": "^2.0.1",
"nanoid": "^5.1.5",
"open": "^10.1.1",
"parse5": "^7.2.1",
"pathe": "^2.0.3",
"periscopic": "^4.0.2",
"picocolors": "^1.1.1",
"postcss-import": "^16.1.0",
"postcss-load-config": "^6.0.1",
"postcss-modules": "^6.0.1",
"resolve.exports": "^2.0.3",
"rollup-plugin-dts": "^6.2.1",
"rollup-plugin-esbuild": "^6.2.1",
"rollup-plugin-license": "^3.6.0",
"sass": "^1.86.3",
"sass-embedded": "^1.86.3",
"sirv": "^3.0.1",
"source-map-support": "^0.5.21",
"strip-literal": "^3.0.0",
"terser": "^5.39.0",
"tsconfck": "^3.1.5",
"tslib": "^2.8.1",
"types": "link:./types",
"ufo": "^1.6.1",
"ws": "^8.18.1"
},
"peerDependencies": {
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"jiti": ">=1.21.0",
"less": "*",
"lightningcss": "^1.21.0",
"sass": "*",
"sass-embedded": "*",
"stylus": "*",
"sugarss": "*",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"jiti": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"stylus": {
"optional": true
},
"less": {
"optional": true
},
"sugarss": {
"optional": true
},
"lightningcss": {
"optional": true
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
},
"scripts": {
"dev": "tsx scripts/dev.ts",
"build": "premove dist && pnpm build-bundle && pnpm build-types",
"build-bundle": "rollup --config rollup.config.ts --configPlugin esbuild",
"build-types": "pnpm build-types-temp && pnpm build-types-roll && pnpm build-types-check",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp -p src/node/tsconfig.build.json",
"build-types-roll": "rollup --config rollup.dts.config.ts --configPlugin esbuild && premove temp",
"build-types-check": "tsc --project tsconfig.check.json",
"typecheck": "tsc --noEmit && tsc --noEmit -p src/node",
"lint": "eslint --cache --ext .ts src/**",
"format": "prettier --write --cache --parser typescript \"src/**/*.ts\""
}
}

45
node_modules/vite/types/customEvent.d.ts generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import type {
ErrorPayload,
FullReloadPayload,
PrunePayload,
UpdatePayload,
} from './hmrPayload'
export interface CustomEventMap {
'vite:beforeUpdate': UpdatePayload
'vite:afterUpdate': UpdatePayload
'vite:beforePrune': PrunePayload
'vite:beforeFullReload': FullReloadPayload
'vite:error': ErrorPayload
'vite:invalidate': InvalidatePayload
'vite:ws:connect': WebSocketConnectionPayload
'vite:ws:disconnect': WebSocketConnectionPayload
}
export interface WebSocketConnectionPayload {
/**
* @experimental
* We expose this instance experimentally to see potential usage.
* This might be removed in the future if we didn't find reasonable use cases.
* If you find this useful, please open an issue with details so we can discuss and make it stable API.
*/
// eslint-disable-next-line n/no-unsupported-features/node-builtins
webSocket: WebSocket
}
export interface InvalidatePayload {
path: string
message: string | undefined
firstInvalidatedBy: string
}
/**
* provides types for payloads of built-in Vite events
*/
export type InferCustomEventPayload<T extends string> =
T extends keyof CustomEventMap ? CustomEventMap[T] : any
/**
* provides types for names of built-in Vite events
*/
export type CustomEventName = keyof CustomEventMap | (string & {})

74
node_modules/vite/types/hmrPayload.d.ts generated vendored Normal file
View File

@@ -0,0 +1,74 @@
/** @deprecated use HotPayload */
export type HMRPayload = HotPayload
export type HotPayload =
| ConnectedPayload
| PingPayload
| UpdatePayload
| FullReloadPayload
| CustomPayload
| ErrorPayload
| PrunePayload
export interface ConnectedPayload {
type: 'connected'
}
export interface PingPayload {
type: 'ping'
}
export interface UpdatePayload {
type: 'update'
updates: Update[]
}
export interface Update {
type: 'js-update' | 'css-update'
path: string
acceptedPath: string
timestamp: number
/** @internal */
explicitImportRequired?: boolean
/** @internal */
isWithinCircularImport?: boolean
/** @internal */
firstInvalidatedBy?: string
/** @internal */
invalidates?: string[]
}
export interface PrunePayload {
type: 'prune'
paths: string[]
}
export interface FullReloadPayload {
type: 'full-reload'
path?: string
/** @internal */
triggeredBy?: string
}
export interface CustomPayload {
type: 'custom'
event: string
data?: any
}
export interface ErrorPayload {
type: 'error'
err: {
[name: string]: any
message: string
stack: string
id?: string
frame?: string
plugin?: string
pluginCode?: string
loc?: {
file?: string
line: number
column: number
}
}
}

39
node_modules/vite/types/hot.d.ts generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import type { CustomEventName, InferCustomEventPayload } from './customEvent'
export type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: 'Module'
}
export interface ViteHotContext {
readonly data: any
accept(): void
accept(cb: (mod: ModuleNamespace | undefined) => void): void
accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
accept(
deps: readonly string[],
cb: (mods: Array<ModuleNamespace | undefined>) => void,
): void
acceptExports(
exportNames: string | readonly string[],
cb?: (mod: ModuleNamespace | undefined) => void,
): void
dispose(cb: (data: any) => void): void
prune(cb: (data: any) => void): void
invalidate(message?: string): void
on<T extends CustomEventName>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
off<T extends CustomEventName>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
send<T extends CustomEventName>(
event: T,
data?: InferCustomEventPayload<T>,
): void
}

5
node_modules/vite/types/import-meta.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
/// <reference path="./importMeta.d.ts" />
// https://github.com/microsoft/TypeScript/issues/45096
// TypeScript has a bug that makes <reference types="vite/types/importMeta" />
// not possible in userland. This file provides a workaround for now.

75
node_modules/vite/types/importGlob.d.ts generated vendored Normal file
View File

@@ -0,0 +1,75 @@
export interface ImportGlobOptions<
Eager extends boolean,
AsType extends string,
> {
/**
* Import type for the import url.
*
* @deprecated Use `query` instead, e.g. `as: 'url'` -> `query: '?url', import: 'default'`
*/
as?: AsType
/**
* Import as static or dynamic
*
* @default false
*/
eager?: Eager
/**
* Import only the specific named export. Set to `default` to import the default export.
*/
import?: string
/**
* Custom queries
*/
query?: string | Record<string, string | number | boolean>
/**
* Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance.
*
* @default false
*/
exhaustive?: boolean
}
export type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>
export interface KnownAsTypeMap {
raw: string
url: string
worker: Worker
}
export interface ImportGlobFunction {
/**
* Import a list of files with a glob pattern.
*
* Overload 1: No generic provided, infer the type from `eager` and `as`
*/
<
Eager extends boolean,
As extends string,
T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown,
>(
glob: string | string[],
options?: ImportGlobOptions<Eager, As>,
): (Eager extends true ? true : false) extends true
? Record<string, T>
: Record<string, () => Promise<T>>
/**
* Import a list of files with a glob pattern.
*
* Overload 2: Module generic provided, infer the type from `eager: false`
*/
<M>(
glob: string | string[],
options?: ImportGlobOptions<false, string>,
): Record<string, () => Promise<M>>
/**
* Import a list of files with a glob pattern.
*
* Overload 3: Module generic provided, infer the type from `eager: true`
*/
<M>(
glob: string | string[],
options: ImportGlobOptions<true, string>,
): Record<string, M>
}

31
node_modules/vite/types/importMeta.d.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
// This file is an augmentation to the built-in ImportMeta interface
// Thus cannot contain any top-level imports
// <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
// This is tested in `packages/vite/src/node/__tests_dts__/typeOptions.ts`
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- to allow extending by users
interface ViteTypeOptions {
// strictImportMetaEnv: unknown
}
type ImportMetaEnvFallbackKey =
'strictImportMetaEnv' extends keyof ViteTypeOptions ? never : string
interface ImportMetaEnv {
[key: ImportMetaEnvFallbackKey]: any
BASE_URL: string
MODE: string
DEV: boolean
PROD: boolean
SSR: boolean
}
interface ImportMeta {
url: string
readonly hot?: import('./hot').ViteHotContext
readonly env: ImportMetaEnv
glob: import('./importGlob').ImportGlobFunction
}

View File

@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore `sass` may not be installed
import type DartSass from 'sass'
// @ts-ignore `sass-embedded` may not be installed
import type SassEmbedded from 'sass-embedded'
// @ts-ignore `less` may not be installed
import type Less from 'less'
// @ts-ignore `stylus` may not be installed
import type Stylus from 'stylus'
/* eslint-enable @typescript-eslint/ban-ts-comment */
// https://github.com/type-challenges/type-challenges/issues/29285
type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false
type DartSassLegacyStringOptionsAsync = DartSass.LegacyStringOptions<'async'>
type SassEmbeddedLegacyStringOptionsAsync =
SassEmbedded.LegacyStringOptions<'async'>
type SassLegacyStringOptionsAsync =
IsAny<DartSassLegacyStringOptionsAsync> extends false
? DartSassLegacyStringOptionsAsync
: SassEmbeddedLegacyStringOptionsAsync
export type SassLegacyPreprocessBaseOptions = Omit<
SassLegacyStringOptionsAsync,
| 'data'
| 'file'
| 'outFile'
| 'sourceMap'
| 'omitSourceMapUrl'
| 'sourceMapEmbed'
| 'sourceMapRoot'
>
type DartSassStringOptionsAsync = DartSass.StringOptions<'async'>
type SassEmbeddedStringOptionsAsync = SassEmbedded.StringOptions<'async'>
type SassStringOptionsAsync =
IsAny<DartSassStringOptionsAsync> extends false
? DartSassStringOptionsAsync
: SassEmbeddedStringOptionsAsync
export type SassModernPreprocessBaseOptions = Omit<
SassStringOptionsAsync,
'url' | 'sourceMap'
>
export type LessPreprocessorBaseOptions = Omit<
Less.Options,
'sourceMap' | 'filename'
>
export type StylusPreprocessorBaseOptions = Omit<
Stylus.RenderOptions,
'filename'
> & { define?: Record<string, any> }
declare global {
// LESS' types somewhat references this which doesn't make sense in Node,
// so we have to shim it
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface HTMLLinkElement {}
}

View File

@@ -0,0 +1,18 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore `lightningcss` may not be installed
import type Lightningcss from 'lightningcss'
/* eslint-enable @typescript-eslint/ban-ts-comment */
export type LightningCSSOptions = Omit<
Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>,
| 'filename'
| 'resolver'
| 'minify'
| 'sourceMap'
| 'analyzeDependencies'
// properties not overridden by Vite, but does not make sense to set by end users
| 'inputSourceMap'
| 'projectRoot'
>

35
node_modules/vite/types/metadata.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
export interface ChunkMetadata {
importedAssets: Set<string>
importedCss: Set<string>
}
export interface CustomPluginOptionsVite {
/**
* If this is a CSS Rollup module, you can scope to its importer's exports
* so that if those exports are treeshaken away, the CSS module will also
* be treeshaken.
*
* The "importerId" must import the CSS Rollup module statically.
*
* Example config if the CSS id is `/src/App.vue?vue&type=style&lang.css`:
* ```js
* cssScopeTo: ['/src/App.vue', 'default']
* ```
*
* @experimental
*/
cssScopeTo?: readonly [importerId: string, exportName: string | undefined]
/** @deprecated no-op since Vite 6.1 */
lang?: string
}
declare module 'rollup' {
export interface RenderedChunk {
viteMetadata?: ChunkMetadata
}
export interface CustomPluginOptions {
vite?: CustomPluginOptionsVite
}
}

4
node_modules/vite/types/package.json generated vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"//": "this file is here to make typescript happy when moduleResolution=node16+",
"version": "0.0.0"
}