Update package dependencies and remove unused files from node_modules

This commit is contained in:
becarta
2025-05-16 00:25:30 +02:00
parent 04584e9c98
commit 969d9c0af3
250 changed files with 47796 additions and 47121 deletions

1125
node_modules/vite/LICENSE.md generated vendored

File diff suppressed because it is too large Load Diff

20
node_modules/vite/bin/vite.js generated vendored
View File

@@ -1,16 +1,11 @@
#!/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 })
})
} catch (e) {}
}
global.__vite_start_time = performance.now()
@@ -46,19 +41,6 @@ if (debugIndex > 0) {
}
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')
}

23
node_modules/vite/client.d.ts generated vendored
View File

@@ -102,14 +102,6 @@ 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' {
@@ -255,21 +247,6 @@ declare module '*?inline' {
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
}

View File

@@ -56,19 +56,13 @@ class HMRContext {
decline() {
}
invalidate(message) {
const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
this.hmrClient.notifyListeners("vite:invalidate", {
path: this.ownerPath,
message,
firstInvalidatedBy
});
this.send("vite:invalidate", {
path: this.ownerPath,
message,
firstInvalidatedBy
message
});
this.send("vite:invalidate", { path: this.ownerPath, message });
this.hmrClient.logger.debug(
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
);
}
on(event, cb) {
@@ -97,7 +91,9 @@ class HMRContext {
removeFromMap(this.newListeners);
}
send(event, data) {
this.hmrClient.send({ type: "custom", event, data });
this.hmrClient.messenger.send(
JSON.stringify({ type: "custom", event, data })
);
}
acceptDeps(deps, callback = () => {
}) {
@@ -112,10 +108,25 @@ class HMRContext {
this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
}
}
class HMRMessenger {
constructor(connection) {
this.connection = connection;
this.queue = [];
}
send(message) {
this.queue.push(message);
this.flush();
}
flush() {
if (this.connection.isReady()) {
this.queue.forEach((msg) => this.connection.send(msg));
this.queue = [];
}
}
}
class HMRClient {
constructor(logger, transport, importUpdatedModule) {
constructor(logger, connection, importUpdatedModule) {
this.logger = logger;
this.transport = transport;
this.importUpdatedModule = importUpdatedModule;
this.hotModulesMap = /* @__PURE__ */ new Map();
this.disposeMap = /* @__PURE__ */ new Map();
@@ -125,6 +136,7 @@ class HMRClient {
this.ctxToListenersMap = /* @__PURE__ */ new Map();
this.updateQueue = [];
this.pendingUpdateQueue = false;
this.messenger = new HMRMessenger(connection);
}
async notifyListeners(event, data) {
const cbs = this.customListenersMap.get(event);
@@ -132,11 +144,6 @@ class HMRClient {
await Promise.allSettled(cbs.map((cb) => cb(data)));
}
}
send(payload) {
this.transport.send(payload).catch((err) => {
this.logger.error(err);
});
}
clear() {
this.hotModulesMap.clear();
this.disposeMap.clear();
@@ -147,7 +154,7 @@ class HMRClient {
}
// After an HMR update, some modules are no longer imported on the page
// but they may have left behind side effects that need to be cleaned up
// (e.g. style injections)
// (.e.g style injections)
async prunePaths(paths) {
await Promise.all(
paths.map((path) => {
@@ -163,11 +170,11 @@ class HMRClient {
});
}
warnFailedUpdate(err, path) {
if (!(err instanceof Error) || !err.message.includes("fetch")) {
if (!err.message.includes("fetch")) {
this.logger.error(err);
}
this.logger.error(
`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
/**
@@ -187,7 +194,7 @@ class HMRClient {
}
}
async fetchUpdate(update) {
const { path, acceptedPath, firstInvalidatedBy } = update;
const { path, acceptedPath } = update;
const mod = this.hotModulesMap.get(path);
if (!mod) {
return;
@@ -207,317 +214,14 @@ class HMRClient {
}
}
return () => {
try {
this.currentFirstInvalidatedBy = firstInvalidatedBy;
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map(
(dep) => dep === acceptedPath ? fetchedModule : void 0
)
);
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
} finally {
this.currentFirstInvalidatedBy = void 0;
}
};
}
}
/* @ts-self-types="./index.d.ts" */
let urlAlphabet =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
let nanoid = (size = 21) => {
let id = '';
let i = size | 0;
while (i--) {
id += urlAlphabet[(Math.random() * 64) | 0];
}
return id
};
typeof process !== "undefined" && process.platform === "win32";
function promiseWithResolvers() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
}
function reviveInvokeError(e) {
const error = new Error(e.message || "Unknown invoke error");
Object.assign(error, e, {
// pass the whole error instead of just the stacktrace
// so that it gets formatted nicely with console.log
runnerError: new Error("RunnerError")
});
return error;
}
const createInvokeableTransport = (transport) => {
if (transport.invoke) {
return {
...transport,
async invoke(name, data) {
const result = await transport.invoke({
type: "custom",
event: "vite:invoke",
data: {
id: "send",
name,
data
}
});
if ("error" in result) {
throw reviveInvokeError(result.error);
}
return result.result;
}
};
}
if (!transport.send || !transport.connect) {
throw new Error(
"transport must implement send and connect when invoke is not implemented"
);
}
const rpcPromises = /* @__PURE__ */ new Map();
return {
...transport,
connect({ onMessage, onDisconnection }) {
return transport.connect({
onMessage(payload) {
if (payload.type === "custom" && payload.event === "vite:invoke") {
const data = payload.data;
if (data.id.startsWith("response:")) {
const invokeId = data.id.slice("response:".length);
const promise = rpcPromises.get(invokeId);
if (!promise) return;
if (promise.timeoutId) clearTimeout(promise.timeoutId);
rpcPromises.delete(invokeId);
const { error, result } = data.data;
if (error) {
promise.reject(error);
} else {
promise.resolve(result);
}
return;
}
}
onMessage(payload);
},
onDisconnection
});
},
disconnect() {
rpcPromises.forEach((promise) => {
promise.reject(
new Error(
`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`
)
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
});
rpcPromises.clear();
return transport.disconnect?.();
},
send(data) {
return transport.send(data);
},
async invoke(name, data) {
const promiseId = nanoid();
const wrappedData = {
type: "custom",
event: "vite:invoke",
data: {
name,
id: `send:${promiseId}`,
data
}
};
const sendPromise = transport.send(wrappedData);
const { promise, resolve, reject } = promiseWithResolvers();
const timeout = transport.timeout ?? 6e4;
let timeoutId;
if (timeout > 0) {
timeoutId = setTimeout(() => {
rpcPromises.delete(promiseId);
reject(
new Error(
`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`
)
);
}, timeout);
timeoutId?.unref?.();
}
rpcPromises.set(promiseId, { resolve, reject, name, timeoutId });
if (sendPromise) {
sendPromise.catch((err) => {
clearTimeout(timeoutId);
rpcPromises.delete(promiseId);
reject(err);
});
}
try {
return await promise;
} catch (err) {
throw reviveInvokeError(err);
}
}
};
};
const normalizeModuleRunnerTransport = (transport) => {
const invokeableTransport = createInvokeableTransport(transport);
let isConnected = !invokeableTransport.connect;
let connectingPromise;
return {
...transport,
...invokeableTransport.connect ? {
async connect(onMessage) {
if (isConnected) return;
if (connectingPromise) {
await connectingPromise;
return;
}
const maybePromise = invokeableTransport.connect({
onMessage: onMessage ?? (() => {
}),
onDisconnection() {
isConnected = false;
}
});
if (maybePromise) {
connectingPromise = maybePromise;
await connectingPromise;
connectingPromise = void 0;
}
isConnected = true;
}
} : {},
...invokeableTransport.disconnect ? {
async disconnect() {
if (!isConnected) return;
if (connectingPromise) {
await connectingPromise;
}
isConnected = false;
await invokeableTransport.disconnect();
}
} : {},
async send(data) {
if (!invokeableTransport.send) return;
if (!isConnected) {
if (connectingPromise) {
await connectingPromise;
} else {
throw new Error("send was called before connect");
}
}
await invokeableTransport.send(data);
},
async invoke(name, data) {
if (!isConnected) {
if (connectingPromise) {
await connectingPromise;
} else {
throw new Error("invoke was called before connect");
}
}
return invokeableTransport.invoke(name, data);
}
};
};
const createWebSocketModuleRunnerTransport = (options) => {
const pingInterval = options.pingInterval ?? 3e4;
let ws;
let pingIntervalId;
return {
async connect({ onMessage, onDisconnection }) {
const socket = options.createConnection();
socket.addEventListener("message", async ({ data }) => {
onMessage(JSON.parse(data));
});
let isOpened = socket.readyState === socket.OPEN;
if (!isOpened) {
await new Promise((resolve, reject) => {
socket.addEventListener(
"open",
() => {
isOpened = true;
resolve();
},
{ once: true }
);
socket.addEventListener("close", async () => {
if (!isOpened) {
reject(new Error("WebSocket closed without opened."));
return;
}
onMessage({
type: "custom",
event: "vite:ws:disconnect",
data: { webSocket: socket }
});
onDisconnection();
});
});
}
onMessage({
type: "custom",
event: "vite:ws:connect",
data: { webSocket: socket }
});
ws = socket;
pingIntervalId = setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send(JSON.stringify({ type: "ping" }));
}
}, pingInterval);
},
disconnect() {
clearInterval(pingIntervalId);
ws?.close();
},
send(data) {
ws.send(JSON.stringify(data));
}
};
};
function createHMRHandler(handler) {
const queue = new Queue();
return (payload) => queue.enqueue(() => handler(payload));
}
class Queue {
constructor() {
this.queue = [];
this.pending = false;
}
enqueue(promise) {
return new Promise((resolve, reject) => {
this.queue.push({
promise,
resolve,
reject
});
this.dequeue();
});
}
dequeue() {
if (this.pending) {
return false;
}
const item = this.queue.shift();
if (!item) {
return false;
}
this.pending = true;
item.promise().then(item.resolve).catch(item.reject).finally(() => {
this.pending = false;
this.dequeue();
});
return true;
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`[vite] hot updated: ${loggedPath}`);
};
}
}
@@ -757,21 +461,23 @@ class ErrorOverlay extends HTMLElement {
fileRE.lastIndex = 0;
while (match = fileRE.exec(text)) {
const { 0: file, index } = match;
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement("a");
link.textContent = file;
link.className = "file-link";
link.onclick = () => {
fetch(
new URL(
`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url
)
);
};
el.appendChild(link);
curIndex += frag.length + file.length;
if (index != null) {
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement("a");
link.textContent = file;
link.className = "file-link";
link.onclick = () => {
fetch(
new URL(
`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url
)
);
};
el.appendChild(link);
curIndex += frag.length + file.length;
}
}
}
}
@@ -794,68 +500,69 @@ const hmrPort = __HMR_PORT__;
const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
const directSocketHost = __HMR_DIRECT_TARGET__;
const base = __BASE__ || "/";
const hmrTimeout = __HMR_TIMEOUT__;
const wsToken = __WS_TOKEN__;
const transport = normalizeModuleRunnerTransport(
(() => {
let wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () => new WebSocket(
`${socketProtocol}://${socketHost}?token=${wsToken}`,
"vite-hmr"
),
pingInterval: hmrTimeout
});
return {
async connect(handlers) {
try {
await wsTransport.connect(handlers);
} catch (e) {
if (!hmrPort) {
wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () => new WebSocket(
`${socketProtocol}://${directSocketHost}?token=${wsToken}`,
"vite-hmr"
),
pingInterval: hmrTimeout
});
try {
await wsTransport.connect(handlers);
console.info(
"[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error."
);
} catch (e2) {
if (e2 instanceof Error && e2.message.includes("WebSocket closed without opened.")) {
const currentScriptHostURL = new URL(import.meta.url);
const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
console.error(
`[vite] failed to connect to websocket.
let socket;
try {
let fallback;
if (!hmrPort) {
fallback = () => {
socket = setupWebSocket(socketProtocol, directSocketHost, () => {
const currentScriptHostURL = new URL(import.meta.url);
const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
console.error(
`[vite] failed to connect to websocket.
your current setup:
(browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)
(browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)
Check out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .`
);
}
}
return;
}
console.error(`[vite] failed to connect to websocket (${e}). `);
throw e;
}
},
async disconnect() {
await wsTransport.disconnect();
},
send(data) {
wsTransport.send(data);
}
);
});
socket.addEventListener(
"open",
() => {
console.info(
"[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error."
);
},
{ once: true }
);
};
})()
);
let willUnload = false;
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
willUnload = true;
}
socket = setupWebSocket(socketProtocol, socketHost, fallback);
} catch (error) {
console.error(`[vite] failed to connect to websocket (${error}). `);
}
function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) {
const socket2 = new WebSocket(
`${protocol}://${hostAndPath}?token=${wsToken}`,
"vite-hmr"
);
let isOpened = false;
socket2.addEventListener(
"open",
() => {
isOpened = true;
notifyListeners("vite:ws:connect", { webSocket: socket2 });
},
{ once: true }
);
socket2.addEventListener("message", async ({ data }) => {
handleMessage(JSON.parse(data));
});
socket2.addEventListener("close", async ({ wasClean }) => {
if (wasClean) return;
if (!isOpened && onCloseWithoutOpen) {
onCloseWithoutOpen();
return;
}
notifyListeners("vite:ws:disconnect", { webSocket: socket2 });
if (hasDocument) {
console.log(`[vite] server connection lost. Polling for restart...`);
await waitForSuccessfulPing(protocol, hostAndPath);
location.reload();
}
});
return socket2;
}
function cleanUrl(pathname) {
const url = new URL(pathname, "http://vite.dev");
@@ -878,11 +585,11 @@ const debounceReload = (time) => {
};
const pageReload = debounceReload(50);
const hmrClient = new HMRClient(
console,
{
error: (err) => console.error("[vite]", err),
debug: (...msg) => console.debug("[vite]", ...msg)
isReady: () => socket && socket.readyState === 1,
send: (message) => socket.send(message)
},
transport,
async function importUpdatedModule({
acceptedPath,
timestamp,
@@ -905,14 +612,19 @@ const hmrClient = new HMRClient(
return await importPromise;
}
);
transport.connect(createHMRHandler(handleMessage));
async function handleMessage(payload) {
switch (payload.type) {
case "connected":
console.debug(`[vite] connected.`);
hmrClient.messenger.flush();
setInterval(() => {
if (socket.readyState === socket.OPEN) {
socket.send('{"type":"ping"}');
}
}, __HMR_TIMEOUT__);
break;
case "update":
await hmrClient.notifyListeners("vite:beforeUpdate", payload);
notifyListeners("vite:beforeUpdate", payload);
if (hasDocument) {
if (isFirstUpdate && hasErrorOverlay()) {
location.reload();
@@ -955,24 +667,14 @@ async function handleMessage(payload) {
});
})
);
await hmrClient.notifyListeners("vite:afterUpdate", payload);
notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
await hmrClient.notifyListeners(payload.event, payload.data);
if (payload.event === "vite:ws:disconnect") {
if (hasDocument && !willUnload) {
console.log(`[vite] server connection lost. Polling for restart...`);
const socket = payload.data.webSocket;
const url = new URL(socket.url);
url.search = "";
await waitForSuccessfulPing(url.href);
location.reload();
}
}
notifyListeners(payload.event, payload.data);
break;
}
case "full-reload":
await hmrClient.notifyListeners("vite:beforeFullReload", payload);
notifyListeners("vite:beforeFullReload", payload);
if (hasDocument) {
if (payload.path && payload.path.endsWith(".html")) {
const pagePath = decodeURI(location.pathname);
@@ -987,11 +689,11 @@ async function handleMessage(payload) {
}
break;
case "prune":
await hmrClient.notifyListeners("vite:beforePrune", payload);
notifyListeners("vite:beforePrune", payload);
await hmrClient.prunePaths(payload.paths);
break;
case "error": {
await hmrClient.notifyListeners("vite:error", payload);
notifyListeners("vite:error", payload);
if (hasDocument) {
const err = payload.err;
if (enableOverlay) {
@@ -1006,23 +708,20 @@ ${err.stack}`
}
break;
}
case "ping":
break;
default: {
const check = payload;
return check;
}
}
}
function notifyListeners(event, data) {
hmrClient.notifyListeners(event, data);
}
const enableOverlay = __HMR_ENABLE_OVERLAY__;
const hasDocument = "document" in globalThis;
function createErrorOverlay(err) {
clearErrorOverlay();
const { customElements } = globalThis;
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId);
document.body.appendChild(new ErrorOverlayConstructor(err));
}
document.body.appendChild(new ErrorOverlay(err));
}
function clearErrorOverlay() {
document.querySelectorAll(overlayId).forEach((n) => n.close());
@@ -1030,27 +729,23 @@ function clearErrorOverlay() {
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length;
}
async function waitForSuccessfulPing(socketUrl, ms = 1e3) {
async function ping() {
const socket = new WebSocket(socketUrl, "vite-ping");
return new Promise((resolve) => {
function onOpen() {
resolve(true);
close();
}
function onError() {
resolve(false);
close();
}
function close() {
socket.removeEventListener("open", onOpen);
socket.removeEventListener("error", onError);
socket.close();
}
socket.addEventListener("open", onOpen);
socket.addEventListener("error", onError);
});
}
async function waitForSuccessfulPing(socketProtocol2, hostAndPath, ms = 1e3) {
const pingHostProtocol = socketProtocol2 === "wss" ? "https" : "http";
const ping = async () => {
try {
await fetch(`${pingHostProtocol}://${hostAndPath}`, {
mode: "no-cors",
headers: {
// Custom headers won't be included in a request with no-cors so (ab)use one of the
// safelisted headers to identify the ping request
Accept: "text/x-vite-ping"
}
});
return true;
} catch {
}
return false;
};
if (await ping()) {
return;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,11 +1,19 @@
import { Q as commonjsGlobal, P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import require$$0$2 from 'fs';
import { D as commonjsGlobal, C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import require$$0__default from 'fs';
import require$$0 from 'postcss';
import require$$0$1 from 'path';
import require$$3 from 'crypto';
import require$$1 from 'util';
import { l as lib } from './dep-3RmXg9uo.js';
import require$$0$2 from 'util';
import { l as lib } from './dep-IQS-Za7F.js';
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
@@ -388,6 +396,9 @@ var localsConvention = {};
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
@@ -722,7 +733,7 @@ function baseToString(value) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
@@ -737,7 +748,7 @@ function baseToString(value) {
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (false && end >= length) ? array : baseSlice(array, start, end);
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
@@ -1459,7 +1470,7 @@ function requireWasmHash () {
// 64 is the maximum chunk size for every possible wasm hash implementation
// 4 is the maximum number of bytes per char for string encoding (max is utf-8)
// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
class WasmHash {
/**
@@ -2024,17 +2035,12 @@ function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
digestType === "base49" ||
digestType === "base52" ||
digestType === "base58" ||
digestType === "base62" ||
digestType === "base64safe"
digestType === "base62"
) {
return encodeBufferToBase(
hash.digest(),
digestType === "base64safe" ? 64 : digestType.substr(4),
maxLength
);
return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
} else {
return hash.digest(digestType || "hex").substr(0, maxLength);
}
return hash.digest(digestType || "hex").substr(0, maxLength);
}
var getHashDigest_1 = getHashDigest$1;
@@ -2090,10 +2096,9 @@ function interpolateName$1(loaderContext, name, options = {}) {
directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
}
if (directory.length <= 1) {
if (directory.length === 1) {
directory = "";
} else {
// directory.length > 1
} else if (directory.length > 1) {
folder = path$1.basename(directory);
}
}
@@ -2116,7 +2121,7 @@ function interpolateName$1(loaderContext, name, options = {}) {
// `hash` and `contenthash` are same in `loader-utils` context
// let's keep `hash` for backward compatibility
.replace(
/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
(all, hashType, digestType, maxLength) =>
getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
);
@@ -2645,9 +2650,6 @@ types.UNIVERSAL = UNIVERSAL;
_proto.prepend = function prepend(selector) {
selector.parent = this;
this.nodes.unshift(selector);
for (var id in this.indexes) {
this.indexes[id]++;
}
return this;
};
_proto.at = function at(index) {
@@ -2684,39 +2686,29 @@ types.UNIVERSAL = UNIVERSAL;
return this.removeAll();
};
_proto.insertAfter = function insertAfter(oldNode, newNode) {
var _this$nodes;
newNode.parent = this;
var oldIndex = this.index(oldNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
resetNode.push(arguments[i]);
}
(_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
this.nodes.splice(oldIndex + 1, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex < index) {
this.indexes[id] = index + arguments.length - 1;
if (oldIndex <= index) {
this.indexes[id] = index + 1;
}
}
return this;
};
_proto.insertBefore = function insertBefore(oldNode, newNode) {
var _this$nodes2;
newNode.parent = this;
var oldIndex = this.index(oldNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
resetNode.push(arguments[i]);
}
(_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
this.nodes.splice(oldIndex, 0, newNode);
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= oldIndex) {
this.indexes[id] = index + arguments.length - 1;
if (index <= oldIndex) {
this.indexes[id] = index + 1;
}
}
return this;
@@ -2742,7 +2734,7 @@ types.UNIVERSAL = UNIVERSAL;
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
@@ -3410,7 +3402,7 @@ var attribute$1 = {};
* For Node.js, simply re-export the core `util.deprecate` function.
*/
var node = require$$1.deprecate;
var node = require$$0$2.deprecate;
(function (exports) {
@@ -4760,7 +4752,7 @@ tokenTypes.combinator = combinator$1;
}
// We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
if (nodes.length > 0) {
var last = this.current.last;
@@ -5639,40 +5631,8 @@ const selectorParser$1 = distExports;
const valueParser = lib;
const { extractICSS } = src$4;
const IGNORE_FILE_MARKER = "cssmodules-pure-no-check";
const IGNORE_NEXT_LINE_MARKER = "cssmodules-pure-ignore";
const isSpacing = (node) => node.type === "combinator" && node.value === " ";
const isPureCheckDisabled = (root) => {
for (const node of root.nodes) {
if (node.type !== "comment") {
return false;
}
if (node.text.trim().startsWith(IGNORE_FILE_MARKER)) {
return true;
}
}
return false;
};
function getIgnoreComment(node) {
if (!node.parent) {
return;
}
const indexInParent = node.parent.index(node);
for (let i = indexInParent - 1; i >= 0; i--) {
const prevNode = node.parent.nodes[i];
if (prevNode.type === "comment") {
if (prevNode.text.trimStart().startsWith(IGNORE_NEXT_LINE_MARKER)) {
return prevNode;
}
} else {
break;
}
}
}
function normalizeNodeArray(nodes) {
const array = [];
@@ -5692,8 +5652,6 @@ function normalizeNodeArray(nodes) {
return array;
}
const isPureSelectorSymbol = Symbol("is-pure-selector");
function localizeNode(rule, mode, localAliasMap) {
const transform = (node, context) => {
if (context.ignoreNextSpacing && !isSpacing(node)) {
@@ -5901,7 +5859,7 @@ function localizeNode(rule, mode, localAliasMap) {
}
case "nesting": {
if (node.value === "&") {
context.hasLocals = rule.parent[isPureSelectorSymbol];
context.hasLocals = true;
}
}
}
@@ -6007,7 +5965,7 @@ function localizeDeclarationValues(localize, declaration, context) {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: localize,
localizeNextItem: localize && !context.global,
localAliasMap: context.localAliasMap,
};
nodes[index] = localizeDeclNode(node, subContext);
@@ -6016,20 +5974,24 @@ function localizeDeclarationValues(localize, declaration, context) {
declaration.value = valueNodes.toString();
}
// letter
// An uppercase letter or a lowercase letter.
//
// ident-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
//
// ident code point
// An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
function localizeDeclaration(declaration, context) {
const isAnimation = /animation$/i.test(declaration.prop);
// We don't validate `hex digits`, because we don't need it, it is work of linters.
const validIdent =
/^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
if (isAnimation) {
// letter
// An uppercase letter or a lowercase letter.
//
// ident-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
//
// ident code point
// An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
/*
// We don't validate `hex digits`, because we don't need it, it is work of linters.
const validIdent =
/^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
/*
The spec defines some keywords that you can use to describe properties such as the timing
function. These are still valid animation names, so as long as there is a property that accepts
a keyword, it is given priority. Only when all the properties that can take a keyword are
@@ -6040,43 +6002,38 @@ const validIdent =
The animation will repeat an infinite number of times from the first argument, and will have an
animation name of infinite from the second.
*/
const animationKeywords = {
// animation-direction
$normal: 1,
$reverse: 1,
$alternate: 1,
"$alternate-reverse": 1,
// animation-fill-mode
$forwards: 1,
$backwards: 1,
$both: 1,
// animation-iteration-count
$infinite: 1,
// animation-play-state
$paused: 1,
$running: 1,
// animation-timing-function
$ease: 1,
"$ease-in": 1,
"$ease-out": 1,
"$ease-in-out": 1,
$linear: 1,
"$step-end": 1,
"$step-start": 1,
// Special
$none: Infinity, // No matter how many times you write none, it will never be an animation name
// Global values
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
$revert: Infinity,
"$revert-layer": Infinity,
};
function localizeDeclaration(declaration, context) {
const isAnimation = /animation(-name)?$/i.test(declaration.prop);
if (isAnimation) {
const animationKeywords = {
// animation-direction
$normal: 1,
$reverse: 1,
$alternate: 1,
"$alternate-reverse": 1,
// animation-fill-mode
$forwards: 1,
$backwards: 1,
$both: 1,
// animation-iteration-count
$infinite: 1,
// animation-play-state
$paused: 1,
$running: 1,
// animation-timing-function
$ease: 1,
"$ease-in": 1,
"$ease-out": 1,
"$ease-in-out": 1,
$linear: 1,
"$step-end": 1,
"$step-start": 1,
// Special
$none: Infinity, // No matter how many times you write none, it will never be an animation name
// Global values
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
$revert: Infinity,
"$revert-layer": Infinity,
};
let parsedAnimationKeywords = {};
const valueNodes = valueParser(declaration.value).walk((node) => {
// If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
@@ -6084,28 +6041,9 @@ function localizeDeclaration(declaration, context) {
parsedAnimationKeywords = {};
return;
} else if (
node.type === "function" &&
node.value.toLowerCase() === "local" &&
node.nodes.length === 1
) {
node.type = "word";
node.value = node.nodes[0].value;
return localizeDeclNode(node, {
options: context.options,
global: context.global,
localizeNextItem: true,
localAliasMap: context.localAliasMap,
});
} else if (node.type === "function") {
// replace `animation: global(example)` with `animation-name: example`
if (node.value.toLowerCase() === "global" && node.nodes.length === 1) {
node.type = "word";
node.value = node.nodes[0].value;
}
// Do not handle nested functions
}
// Do not handle nested functions
else if (node.type === "function") {
return false;
}
// Ignore all except word
@@ -6132,12 +6070,14 @@ function localizeDeclaration(declaration, context) {
}
}
return localizeDeclNode(node, {
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: shouldParseAnimationName && !context.global,
localAliasMap: context.localAliasMap,
});
};
return localizeDeclNode(node, subContext);
});
declaration.value = valueNodes.toString();
@@ -6145,35 +6085,19 @@ function localizeDeclaration(declaration, context) {
return;
}
if (/url\(/i.test(declaration.value)) {
const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
if (isAnimationName) {
return localizeDeclarationValues(true, declaration, context);
}
const hasUrl = /url\(/i.test(declaration.value);
if (hasUrl) {
return localizeDeclarationValues(false, declaration, context);
}
}
const isPureSelector = (context, rule) => {
if (!rule.parent || rule.type === "root") {
return !context.hasPureGlobals;
}
if (rule.type === "rule" && rule[isPureSelectorSymbol]) {
return rule[isPureSelectorSymbol] || isPureSelector(context, rule.parent);
}
return !context.hasPureGlobals || isPureSelector(context, rule.parent);
};
const isNodeWithoutDeclarations = (rule) => {
if (rule.nodes.length > 0) {
return !rule.nodes.every(
(item) =>
item.type === "rule" ||
(item.type === "atrule" && !isNodeWithoutDeclarations(item))
);
}
return true;
};
src$2.exports = (options = {}) => {
if (
options &&
@@ -6198,7 +6122,6 @@ src$2.exports = (options = {}) => {
return {
Once(root) {
const { icssImports } = extractICSS(root, false);
const enforcePureMode = pureMode && !isPureCheckDisabled(root);
Object.keys(icssImports).forEach((key) => {
Object.keys(icssImports[key]).forEach((prop) => {
@@ -6218,15 +6141,10 @@ src$2.exports = (options = {}) => {
let globalKeyframes = globalMode;
if (globalMatch) {
if (enforcePureMode) {
const ignoreComment = getIgnoreComment(atRule);
if (!ignoreComment) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
} else {
ignoreComment.remove();
}
if (pureMode) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
}
atRule.params = globalMatch[1];
globalKeyframes = true;
@@ -6250,14 +6168,6 @@ src$2.exports = (options = {}) => {
});
} else if (/scope$/i.test(atRule.name)) {
if (atRule.params) {
const ignoreComment = pureMode
? getIgnoreComment(atRule)
: undefined;
if (ignoreComment) {
ignoreComment.remove();
}
atRule.params = atRule.params
.split("to")
.map((item) => {
@@ -6271,11 +6181,7 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
if (
enforcePureMode &&
context.hasPureGlobals &&
!ignoreComment
) {
if (pureMode && context.hasPureGlobals) {
throw atRule.error(
'Selector in at-rule"' +
selector +
@@ -6326,28 +6232,13 @@ src$2.exports = (options = {}) => {
context.options = options;
context.localAliasMap = localAliasMap;
const ignoreComment = enforcePureMode
? getIgnoreComment(rule)
: undefined;
const isNotPure = enforcePureMode && !isPureSelector(context, rule);
if (
isNotPure &&
isNodeWithoutDeclarations(rule) &&
!ignoreComment
) {
if (pureMode && context.hasPureGlobals) {
throw rule.error(
'Selector "' +
rule.selector +
'" is not pure ' +
"(pure selectors must contain at least one local class or id)"
);
} else if (ignoreComment) {
ignoreComment.remove();
}
if (pureMode) {
rule[isPureSelectorSymbol] = !isNotPure;
}
rule.selector = context.selector;
@@ -7086,7 +6977,7 @@ function makePlugin(opts) {
};
}
var _fs = require$$0$2;
var _fs = require$$0__default;
var _fs2 = fs;

View File

@@ -1,10 +1,16 @@
import { P as getDefaultExportFromCjs } from './dep-DBxKXgDP.js';
import { C as getDefaultExportFromCjs } from './dep-C6uTJdX2.js';
import require$$0 from 'path';
import { l as lib } from './dep-3RmXg9uo.js';
import require$$0__default from 'fs';
import { l as lib } from './dep-IQS-Za7F.js';
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __require = __cjs_createRequire(import.meta.url);
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
@@ -184,6 +190,160 @@ var applyStyles$1 = function applyStyles(bundle, styles) {
});
};
var readCache$1 = {exports: {}};
var pify$2 = {exports: {}};
var processFn = function (fn, P, opts) {
return function () {
var that = this;
var args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P(function (resolve, reject) {
args.push(function (err, result) {
if (err) {
reject(err);
} else if (opts.multiArgs) {
var results = new Array(arguments.length - 1);
for (var i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
fn.apply(that, args);
});
};
};
var pify$1 = pify$2.exports = function (obj, P, opts) {
if (typeof P !== 'function') {
opts = P;
P = Promise;
}
opts = opts || {};
opts.exclude = opts.exclude || [/.+Sync$/];
var filter = function (key) {
var match = function (pattern) {
return typeof pattern === 'string' ? key === pattern : pattern.test(key);
};
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
var ret = typeof obj === 'function' ? function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, P, opts).apply(this, arguments);
} : {};
return Object.keys(obj).reduce(function (ret, key) {
var x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
return ret;
}, ret);
};
pify$1.all = pify$1;
var pifyExports = pify$2.exports;
var fs = require$$0__default;
var path$3 = require$$0;
var pify = pifyExports;
var stat = pify(fs.stat);
var readFile = pify(fs.readFile);
var resolve = path$3.resolve;
var cache = Object.create(null);
function convert(content, encoding) {
if (Buffer.isEncoding(encoding)) {
return content.toString(encoding);
}
return content;
}
readCache$1.exports = function (path, encoding) {
path = resolve(path);
return stat(path).then(function (stats) {
var item = cache[path];
if (item && item.mtime.getTime() === stats.mtime.getTime()) {
return convert(item.content, encoding);
}
return readFile(path).then(function (data) {
cache[path] = {
mtime: stats.mtime,
content: data
};
return convert(data, encoding);
});
}).catch(function (err) {
cache[path] = null;
return Promise.reject(err);
});
};
readCache$1.exports.sync = function (path, encoding) {
path = resolve(path);
try {
var stats = fs.statSync(path);
var item = cache[path];
if (item && item.mtime.getTime() === stats.mtime.getTime()) {
return convert(item.content, encoding);
}
var data = fs.readFileSync(path);
cache[path] = {
mtime: stats.mtime,
content: data
};
return convert(data, encoding);
} catch (err) {
cache[path] = null;
throw err;
}
};
readCache$1.exports.get = function (path, encoding) {
path = resolve(path);
if (cache[path]) {
return convert(cache[path].content, encoding);
}
return null;
};
readCache$1.exports.clear = function () {
cache = Object.create(null);
};
var readCacheExports = readCache$1.exports;
const anyDataURLRegexp = /^data:text\/css(?:;(base64|plain))?,/i;
const base64DataURLRegexp = /^data:text\/css;base64,/i;
const plainDataURLRegexp = /^data:text\/css;plain,/i;
@@ -212,6 +372,17 @@ var dataUrl = {
contents,
};
const readCache = readCacheExports;
const dataURL$1 = dataUrl;
var loadContent$1 = function loadContent(filename) {
if (dataURL$1.isValid(filename)) {
return dataURL$1.contents(filename)
}
return readCache(filename, "utf-8")
};
// external tooling
const valueParser = lib;
@@ -749,7 +920,7 @@ const path = require$$0;
const applyConditions = applyConditions$1;
const applyRaws = applyRaws$1;
const applyStyles = applyStyles$1;
const loadContent = () => "";
const loadContent = loadContent$1;
const parseStyles = parseStyles_1;
const resolveId = (id) => id;

View File

@@ -1,3 +1,11 @@
import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
import { dirname as __cjs_dirname } from 'node:path';
import { createRequire as __cjs_createRequire } from 'node:module';
const __filename = __cjs_fileURLToPath(import.meta.url);
const __dirname = __cjs_dirname(__filename);
const require = __cjs_createRequire(import.meta.url);
const __require = require;
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);

124
node_modules/vite/dist/node/cli.js generated vendored
View File

@@ -2,22 +2,23 @@ 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 { B as colors, v as createLogger, r as resolveConfig } from './chunks/dep-C6uTJdX2.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 'tty';
import 'path';
import 'esbuild';
import 'fs';
import 'fdir';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'url';
@@ -26,26 +27,22 @@ 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 'module';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'node:buffer';
import 'rollup/parseAst';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'assert';
import 'node:querystring';
import 'node:zlib';
function toArr(any) {
@@ -693,7 +690,7 @@ const filterDuplicateOptions = (options) => {
}
}
};
function cleanGlobalCLIOptions(options) {
function cleanOptions(options) {
const ret = { ...options };
delete ret["--"];
delete ret.c;
@@ -702,27 +699,16 @@ function cleanGlobalCLIOptions(options) {
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) => {
@@ -739,34 +725,29 @@ const convertBase = (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`);
}).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).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; });
const { createServer } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.F; });
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
optimizeDeps: { force: options.force },
server: cleanOptions(options)
});
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(
@@ -778,7 +759,7 @@ cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--
`
${colors.green(
`${colors.bold("VITE")} v${VERSION}`
)}${modeString} ${startupDurationString}
)} ${startupDurationString}
`,
{
clear: !hasExistingLogs
@@ -840,56 +821,44 @@ cli.command("build [root]", "build for production").option("--target <target>",
).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:
).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).action(async (root, options) => {
filterDuplicateOptions(options);
const { build } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.G; });
const buildOptions = cleanOptions(options);
try {
await build({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions
});
} 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));
}
{ 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(
});
cli.command("optimize [root]", "pre-bundle dependencies").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; });
const { optimizeDeps } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.E; });
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode
},
@@ -909,13 +878,12 @@ ${e.stack}`),
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; });
const { preview } = await import('./chunks/dep-C6uTJdX2.js').then(function (n) { return n.H; });
try {
const server = await preview({
root,
base: options.base,
configFile: options.config,
configLoader: options.configLoader,
logLevel: options.logLevel,
mode: options.mode,
build: {

View File

@@ -5,35 +5,6 @@ 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",
@@ -42,25 +13,23 @@ const DEFAULT_MAIN_FIELDS = [
// 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",
// support import.meta.url
"edge88",
"firefox78",
"chrome87",
"safari14"
];
const DEFAULT_EXTENSIONS = [
".mjs",
".js",
".mts",
".ts",
".jsx",
".tsx",
".json"
];
const DEFAULT_CONFIG_FILES = [
"vite.config.js",
"vite.config.mjs",
@@ -98,8 +67,6 @@ const KNOWN_ASSET_TYPES = [
"ico",
"webp",
"avif",
"cur",
"jxl",
// media
"mp4",
"webm",
@@ -123,8 +90,7 @@ const KNOWN_ASSET_TYPES = [
"txt"
];
const DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`,
"i"
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`
);
const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
const loopbackHosts = /* @__PURE__ */ new Set([
@@ -143,7 +109,5 @@ 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 };
export { CLIENT_DIR, CLIENT_ENTRY, CLIENT_PUBLIC_PATH, CSS_LANGS_RE, DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_DEV_PORT, DEFAULT_EXTENSIONS, DEFAULT_MAIN_FIELDS, DEFAULT_PREVIEW_PORT, DEP_VERSION_RE, ENV_ENTRY, ENV_PUBLIC_PATH, ESBUILD_MODULES_TARGET, FS_PREFIX, JS_TYPES_RE, KNOWN_ASSET_TYPES, METADATA_FILENAME, OPTIMIZABLE_ENTRY_RE, SPECIAL_QUERY_RE, VERSION, VITE_PACKAGE_DIR, defaultAllowedOrigins, loopbackHosts, wildcardHosts };

2447
node_modules/vite/dist/node/index.d.ts generated vendored

File diff suppressed because it is too large Load Diff

171
node_modules/vite/dist/node/index.js generated vendored
View File

@@ -1,24 +1,26 @@
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';
import { i as isInNodeModules, a as arraify } from './chunks/dep-C6uTJdX2.js';
export { b as build, g as buildErrorMessage, k as createFilter, v as createLogger, c as createServer, d as defineConfig, h as fetchModule, f as formatPostcssSourceMap, y as isFileLoadingAllowed, x as isFileServingAllowed, l as loadConfigFromFile, z as loadEnv, j as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, e as preprocessCSS, p as preview, r as resolveConfig, A as resolveEnvPrefix, q as rollupVersion, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-C6uTJdX2.js';
export { VERSION as version } from './constants.js';
export { version as esbuildVersion } from 'esbuild';
import 'node:fs';
import 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import { ViteRuntime, ESModulesRunner } from 'vite/runtime';
import 'node:fs/promises';
import 'node:path';
import 'node:url';
import 'node:util';
import 'node:perf_hooks';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'tty';
import 'path';
import 'fs';
import 'fdir';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'node:child_process';
import 'node:http';
import 'node:https';
import 'tty';
import 'util';
import 'net';
import 'events';
@@ -28,25 +30,21 @@ 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 'module';
import 'node:assert';
import 'node:v8';
import 'node:worker_threads';
import 'https';
import 'tls';
import 'node:buffer';
import 'querystring';
import 'node:readline';
import 'zlib';
import 'buffer';
import 'https';
import 'tls';
import 'node:net';
import 'assert';
import 'node:querystring';
import 'node:zlib';
const CSS_LANGS_RE = (
@@ -105,7 +103,7 @@ function splitVendorChunkPlugin() {
const cache = new SplitVendorChunkCache();
caches.push(cache);
const build = config.build ?? {};
const format = output.format;
const format = output?.format;
if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
return splitVendorChunk({ cache });
}
@@ -113,7 +111,7 @@ function splitVendorChunkPlugin() {
return {
name: "vite:split-vendor-chunk",
config(config) {
let outputs = config.build?.rollupOptions?.output;
let outputs = config?.build?.rollupOptions?.output;
if (outputs) {
outputs = arraify(outputs);
for (const output of outputs) {
@@ -153,42 +151,111 @@ function splitVendorChunkPlugin() {
};
}
function createFetchableDevEnvironment(name, config, context) {
if (typeof Request === "undefined" || typeof Response === "undefined") {
throw new TypeError(
"FetchableDevEnvironment requires a global `Request` and `Response` object."
);
class ServerHMRBroadcasterClient {
constructor(hmrChannel) {
this.hmrChannel = hmrChannel;
}
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."
send(...args) {
let payload;
if (typeof args[0] === "string") {
payload = {
type: "custom",
event: args[0],
data: args[1]
};
} else {
payload = args[0];
}
if (payload.type !== "custom") {
throw new Error(
"Cannot send non-custom events from the client to the server."
);
}
const response = await this._handleRequest(request);
if (!(response instanceof Response)) {
throw new TypeError(
"FetchableDevEnvironment `context.handleRequest` must return a `Response` object."
this.hmrChannel.send(payload);
}
}
class ServerHMRConnector {
handlers = [];
hmrChannel;
hmrClient;
connected = false;
constructor(server) {
const hmrChannel = server.hot?.channels.find(
(c) => c.name === "ssr"
);
if (!hmrChannel) {
throw new Error(
"Your version of Vite doesn't support HMR during SSR. Please, use Vite 5.1 or higher."
);
}
return response;
this.hmrClient = new ServerHMRBroadcasterClient(hmrChannel);
hmrChannel.api.outsideEmitter.on("send", (payload) => {
this.handlers.forEach((listener) => listener(payload));
});
this.hmrChannel = hmrChannel;
}
isReady() {
return this.connected;
}
send(message) {
const payload = JSON.parse(message);
this.hmrChannel.api.innerEmitter.emit(
payload.event,
payload.data,
this.hmrClient
);
}
onUpdate(handler) {
this.handlers.push(handler);
handler({ type: "connected" });
this.connected = true;
}
}
export { DevEnvironment, createFetchableDevEnvironment, isCSSRequest, isFetchableDevEnvironment, splitVendorChunk, splitVendorChunkPlugin };
function createHMROptions(server, options) {
if (server.config.server.hmr === false || options.hmr === false) {
return false;
}
const connection = new ServerHMRConnector(server);
return {
connection,
logger: options.hmr?.logger
};
}
const prepareStackTrace = {
retrieveFile(id) {
if (existsSync(id)) {
return readFileSync(id, "utf-8");
}
}
};
function resolveSourceMapOptions(options) {
if (options.sourcemapInterceptor != null) {
if (options.sourcemapInterceptor === "prepareStackTrace") {
return prepareStackTrace;
}
if (typeof options.sourcemapInterceptor === "object") {
return { ...prepareStackTrace, ...options.sourcemapInterceptor };
}
return options.sourcemapInterceptor;
}
if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) {
return "node";
}
return prepareStackTrace;
}
async function createViteRuntime(server, options = {}) {
const hmr = createHMROptions(server, options);
return new ViteRuntime(
{
...options,
root: server.config.root,
fetchModule: server.ssrFetchModule,
hmr,
sourcemapInterceptor: resolveSourceMapOptions(options)
},
options.runner || new ESModulesRunner()
);
}
export { ServerHMRConnector, createViteRuntime, isCSSRequest, splitVendorChunk, splitVendorChunkPlugin };

View File

@@ -1,290 +0,0 @@
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 };

View File

@@ -1,87 +0,0 @@
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 };

63
node_modules/vite/dist/node/runtime.d.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import { V as ViteRuntimeOptions, b as ViteModuleRunner, M as ModuleCacheMap, c as HMRClient, R as ResolvedResult, d as ViteRuntimeModuleContext } from './types.d-aGj9QkWt.js';
export { a as FetchFunction, F as FetchResult, e as HMRConnection, H as HMRLogger, g as HMRRuntimeConnection, f as ModuleCache, S as SSRImportMetadata, h as ViteRuntimeImportMeta, s as ssrDynamicImportKey, i as ssrExportAllKey, j as ssrImportKey, k as ssrImportMetaKey, l as ssrModuleExportsKey } from './types.d-aGj9QkWt.js';
import '../../types/hot.js';
import '../../types/hmrPayload.js';
import '../../types/customEvent.js';
interface ViteRuntimeDebugger {
(formatter: unknown, ...args: unknown[]): void;
}
declare class ViteRuntime {
options: ViteRuntimeOptions;
runner: ViteModuleRunner;
private debug?;
/**
* Holds the cache of modules
* Keys of the map are ids
*/
moduleCache: ModuleCacheMap;
hmrClient?: HMRClient;
entrypoints: Set<string>;
private idToUrlMap;
private fileToIdMap;
private envProxy;
private _destroyed;
private _resetSourceMapSupport?;
constructor(options: ViteRuntimeOptions, runner: ViteModuleRunner, debug?: ViteRuntimeDebugger | undefined);
/**
* URL to execute. Accepts file path, server path or id relative to the root.
*/
executeUrl<T = any>(url: string): Promise<T>;
/**
* Entrypoint URL to execute. Accepts file path, server path or id relative to the root.
* In the case of a full reload triggered by HMR, this is the module that will be reloaded.
* If this method is called multiple times, all entrypoints will be reloaded one at a time.
*/
executeEntrypoint<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.
*/
destroy(): Promise<void>;
/**
* Returns `true` if the runtime has been destroyed by calling `destroy()` method.
*/
isDestroyed(): boolean;
private invalidateFiles;
private normalizeEntryUrl;
private processImport;
private cachedRequest;
private cachedModule;
protected directRequest(id: string, fetchResult: ResolvedResult, _callstack: string[]): Promise<any>;
}
declare class ESModulesRunner implements ViteModuleRunner {
runViteModule(context: ViteRuntimeModuleContext, code: string): Promise<any>;
runExternalModule(filepath: string): Promise<any>;
}
export { ESModulesRunner, ModuleCacheMap, ResolvedResult, ViteModuleRunner, ViteRuntime, ViteRuntimeModuleContext, ViteRuntimeOptions };

File diff suppressed because it is too large Load Diff

281
node_modules/vite/dist/node/types.d-aGj9QkWt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,281 @@
import { ModuleNamespace, ViteHotContext } from '../../types/hot.js';
import { Update, HMRPayload } from '../../types/hmrPayload.js';
import { InferCustomEventPayload } from '../../types/customEvent.js';
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;
}
interface HMRConnection {
/**
* Checked before sending messages to the client.
*/
isReady(): boolean;
/**
* Send message to the client.
*/
send(messages: string): void;
}
declare class HMRMessenger {
private connection;
constructor(connection: HMRConnection);
private queue;
send(message: string): void;
flush(): void;
}
declare class HMRClient {
logger: HMRLogger;
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>;
messenger: HMRMessenger;
constructor(logger: HMRLogger, connection: HMRConnection, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<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 SSRImportBaseMetadata extends DefineImportMetadata {
isDynamicImport?: boolean;
}
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;
}
declare class ModuleCacheMap extends Map<string, ModuleCache> {
private root;
constructor(root: string, entries?: [string, ModuleCache][]);
normalize(fsPath: string): string;
/**
* Assign partial data to the map
*/
update(fsPath: string, mod: ModuleCache): this;
setByModuleId(modulePath: string, mod: ModuleCache): this;
set(fsPath: string, mod: ModuleCache): this;
getByModuleId(modulePath: string): ModuleCache;
get(fsPath: string): ModuleCache;
deleteByModuleId(modulePath: string): boolean;
delete(fsPath: string): boolean;
invalidate(id: string): void;
isImported({ importedId, importedBy, }: {
importedId: string;
importedBy: string;
}, seen?: Set<string>): boolean;
/**
* Invalidate modules that dependent on the given modules, up to the main entry
*/
invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/**
* Invalidate dependency modules of the given modules, down to the bottom-level dependencies
*/
invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
getSourceMap(moduleId: string): null | DecodedMap;
}
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 RetrieveFileHandler {
(path: string): string | null | undefined | false;
}
interface RetrieveSourceMapHandler {
(path: string): null | {
url: string;
map: any;
};
}
interface InterceptorOptions {
retrieveFile?: RetrieveFileHandler;
retrieveSourceMap?: RetrieveSourceMapHandler;
}
interface SSRImportMetadata extends SSRImportBaseMetadata {
entrypoint?: boolean;
}
interface HMRRuntimeConnection extends HMRConnection {
/**
* Configure how HMR is handled when this connection triggers an update.
* This method expects that connection will start listening for HMR updates and call this callback when it's received.
*/
onUpdate(callback: (payload: HMRPayload) => void): void;
}
interface ViteRuntimeImportMeta extends ImportMeta {
url: string;
env: ImportMetaEnv;
hot?: ViteHotContext;
[key: string]: any;
}
interface ViteRuntimeModuleContext {
[ssrModuleExportsKey]: Record<string, any>;
[ssrImportKey]: (id: string, metadata?: DefineImportMetadata) => Promise<any>;
[ssrDynamicImportKey]: (id: string, options?: ImportCallOptions) => Promise<any>;
[ssrExportAllKey]: (obj: any) => void;
[ssrImportMetaKey]: ViteRuntimeImportMeta;
}
interface ViteModuleRunner {
/**
* Run code that was transformed by Vite.
* @param context Function context
* @param code Transformed code
* @param id ID that was used to fetch the module
*/
runViteModule(context: ViteRuntimeModuleContext, code: string, id: string): Promise<any>;
/**
* Run externalized module.
* @param file File URL to the external module
*/
runExternalModule(file: string): Promise<any>;
}
interface ModuleCache {
promise?: Promise<any>;
exports?: any;
evaluated?: boolean;
map?: DecodedMap;
meta?: FetchResult;
/**
* Module ids that imports this module
*/
importers?: Set<string>;
imports?: Set<string>;
}
type FetchResult = ExternalFetchResult | ViteFetchResult;
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 runtime
*/
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 runtime
* 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
*/
file: string | null;
}
type ResolvedResult = (ExternalFetchResult | ViteFetchResult) & {
id: string;
};
/**
* @experimental
*/
type FetchFunction = (id: string, importer?: string) => Promise<FetchResult>;
interface ViteRuntimeOptions {
/**
* Root of the project
*/
root: string;
/**
* A method to get the information about the module.
* For SSR, Vite exposes `server.ssrFetchModule` function that you can use here.
* For other runtime use cases, Vite also exposes `fetchModule` from its main entry point.
*/
fetchModule: FetchFunction;
/**
* Custom environment variables available on `import.meta.env`. This doesn't modify the actual `process.env`.
*/
environmentVariables?: Record<string, any>;
/**
* 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.
*/
hmr?: false | {
/**
* Configure how HMR communicates between the client and the server.
*/
connection: HMRRuntimeConnection;
/**
* Configure HMR logger.
*/
logger?: false | HMRLogger;
};
/**
* Custom module cache. If not provided, creates a separate module cache for each ViteRuntime instance.
*/
moduleCache?: ModuleCacheMap;
}
interface ImportMetaEnv {
[key: string]: any;
BASE_URL: string;
MODE: string;
DEV: boolean;
PROD: boolean;
SSR: boolean;
}
export { type FetchResult as F, type HMRLogger as H, ModuleCacheMap as M, type ResolvedResult as R, type SSRImportMetadata as S, type ViteRuntimeOptions as V, type FetchFunction as a, type ViteModuleRunner as b, HMRClient as c, type ViteRuntimeModuleContext as d, type HMRConnection as e, type ModuleCache as f, type HMRRuntimeConnection as g, type ViteRuntimeImportMeta as h, ssrExportAllKey as i, ssrImportKey as j, ssrImportMetaKey as k, ssrModuleExportsKey as l, ssrDynamicImportKey as s };

42
node_modules/vite/index.cjs generated vendored
View File

@@ -1,6 +1,3 @@
const description =
' See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.'
warnCjsUsage()
// type utils
@@ -20,47 +17,12 @@ const asyncFunctions = [
'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) =>
@@ -77,7 +39,9 @@ function warnCjsUsage() {
}
const yellow = (str) => `\u001b[33m${str}\u001b[39m`
console.warn(
yellow("The CJS build of Vite's Node API is deprecated." + description),
yellow(
`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.`,
),
)
if (process.env.VITE_CJS_TRACE) {
const e = {}

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

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

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

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

View File

@@ -1,7 +0,0 @@
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.

View File

@@ -1,91 +0,0 @@
<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

@@ -1,3 +0,0 @@
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;

View File

@@ -1,19 +0,0 @@
"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

@@ -1,12 +0,0 @@
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

@@ -1,27 +0,0 @@
"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

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

View File

@@ -1,13 +0,0 @@
"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

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

View File

@@ -1,11 +0,0 @@
"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

@@ -1,3 +0,0 @@
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

@@ -1,57 +0,0 @@
"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

@@ -1,5 +0,0 @@
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

@@ -1,35 +0,0 @@
"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

@@ -1,5 +0,0 @@
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

@@ -1,36 +0,0 @@
"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

@@ -1,3 +0,0 @@
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

@@ -1,37 +0,0 @@
"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

@@ -1,3 +0,0 @@
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

@@ -1,33 +0,0 @@
"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

@@ -1,5 +0,0 @@
/// <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

@@ -1,67 +0,0 @@
"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

@@ -1,5 +0,0 @@
/// <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

@@ -1,40 +0,0 @@
"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

@@ -1,15 +0,0 @@
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 {};

View File

@@ -1,23 +0,0 @@
"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

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

View File

@@ -1,9 +0,0 @@
"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

@@ -1,18 +0,0 @@
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;
}

View File

@@ -1,125 +0,0 @@
"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

@@ -1,9 +0,0 @@
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

@@ -1,23 +0,0 @@
"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

@@ -1,41 +0,0 @@
/// <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

@@ -1,136 +0,0 @@
"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;

View File

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

View File

@@ -1,20 +0,0 @@
"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

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

View File

@@ -1,54 +0,0 @@
"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;

View File

@@ -1,60 +0,0 @@
/// <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 : [];

View File

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

View File

@@ -1,9 +0,0 @@
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;

View File

@@ -1,36 +0,0 @@
"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;

View File

@@ -1,90 +0,0 @@
{
"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
}
}
}

View File

@@ -1,21 +0,0 @@
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.

View File

@@ -1,738 +0,0 @@
<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).

View File

@@ -1,17 +0,0 @@
'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

@@ -1,179 +0,0 @@
'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;
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,341 +0,0 @@
'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;

View File

@@ -1,391 +0,0 @@
'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;

View File

@@ -1,72 +0,0 @@
/*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;
};

View File

@@ -1,83 +0,0 @@
{
"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"
]
}
}

View File

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

143
node_modules/vite/package.json generated vendored
View File

@@ -1,6 +1,6 @@
{
"name": "vite",
"version": "6.3.5",
"version": "5.4.19",
"type": "module",
"license": "MIT",
"author": "Evan You",
@@ -20,45 +20,45 @@
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"module-sync": "./dist/node/index.js",
"import": "./dist/node/index.js",
"require": "./index.cjs"
"import": {
"types": "./dist/node/index.d.ts",
"default": "./dist/node/index.js"
},
"require": {
"types": "./index.d.cts",
"default": "./index.cjs"
}
},
"./client": {
"types": "./client.d.ts"
},
"./module-runner": "./dist/node/module-runner.js",
"./runtime": {
"types": "./dist/node/runtime.d.ts",
"import": "./dist/node/runtime.js"
},
"./dist/client/*": "./dist/client/*",
"./types/*": {
"types": "./types/*"
},
"./types/internal/*": null,
"./package.json": "./package.json"
},
"typesVersions": {
"*": {
"module-runner": [
"dist/node/module-runner.d.ts"
"runtime": [
"dist/node/runtime.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"
"node": "^18.0.0 || >=20.0.0"
},
"repository": {
"type": "git",
@@ -72,95 +72,88 @@
"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"
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
"rollup": "^4.20.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"devDependencies": {
"@ampproject/remapping": "^2.3.0",
"@babel/parser": "^7.27.0",
"@babel/parser": "^7.25.6",
"@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-alias": "^5.1.0",
"@rollup/plugin-commonjs": "^26.0.1",
"@rollup/plugin-dynamic-import-vars": "^2.1.2",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "16.0.1",
"@rollup/pluginutils": "^5.1.4",
"@rollup/plugin-node-resolve": "15.2.3",
"@rollup/pluginutils": "^5.1.0",
"@types/escape-html": "^1.0.4",
"@types/pnpapi": "^0.0.5",
"artichokie": "^0.3.1",
"artichokie": "^0.2.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",
"cross-spawn": "^7.0.3",
"debug": "^4.3.6",
"dep-types": "link:./src/types",
"dotenv": "^16.5.0",
"dotenv-expand": "^12.0.2",
"es-module-lexer": "^1.6.0",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"es-module-lexer": "^1.5.4",
"escape-html": "^1.0.3",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
"fast-glob": "^3.3.2",
"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",
"launch-editor-middleware": "^2.9.1",
"lightningcss": "^1.26.0",
"magic-string": "^0.30.11",
"micromatch": "^4.0.8",
"mlly": "^1.7.1",
"mrmime": "^2.0.0",
"open": "^8.4.2",
"parse5": "^7.1.2",
"pathe": "^1.1.2",
"periscopic": "^4.0.2",
"picocolors": "^1.1.1",
"picocolors": "^1.0.1",
"picomatch": "^2.3.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",
"postcss-load-config": "^4.0.2",
"postcss-modules": "^6.0.0",
"resolve.exports": "^2.0.2",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-esbuild": "^6.1.1",
"rollup-plugin-license": "^3.5.2",
"sass": "^1.77.8",
"sass-embedded": "^1.77.8",
"sirv": "^2.0.4",
"source-map-support": "^0.5.21",
"strip-literal": "^3.0.0",
"terser": "^5.39.0",
"tsconfck": "^3.1.5",
"tslib": "^2.8.1",
"strip-ansi": "^7.1.0",
"strip-literal": "^2.1.0",
"tsconfck": "^3.1.4",
"tslib": "^2.7.0",
"types": "link:./types",
"ufo": "^1.6.1",
"ws": "^8.18.1"
"ufo": "^1.5.4",
"ws": "^8.18.0"
},
"peerDependencies": {
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"jiti": ">=1.21.0",
"@types/node": "^18.0.0 || >=20.0.0",
"less": "*",
"lightningcss": "^1.21.0",
"sass": "*",
"sass-embedded": "*",
"stylus": "*",
"sugarss": "*",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
"terser": "^5.4.0"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"jiti": {
"optional": true
},
"sass": {
"optional": true
},
@@ -181,23 +174,17 @@
},
"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": "rimraf dist && run-s build-bundle 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": "run-s build-types-temp build-types-roll build-types-check",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp -p src/node",
"build-types-roll": "rollup --config rollup.dts.config.ts --configPlugin esbuild && rimraf temp",
"build-types-check": "tsc --project tsconfig.check.json",
"typecheck": "tsc --noEmit && tsc --noEmit -p src/node",
"typecheck": "tsc --noEmit",
"lint": "eslint --cache --ext .ts src/**",
"format": "prettier --write --cache --parser typescript \"src/**/*.ts\""
}

View File

@@ -30,16 +30,10 @@ export interface WebSocketConnectionPayload {
export interface InvalidatePayload {
path: string
message: string | undefined
firstInvalidatedBy: string
}
/**
* provides types for payloads of built-in Vite events
* provides types for 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 & {})

View File

@@ -1,8 +1,5 @@
/** @deprecated use HotPayload */
export type HMRPayload = HotPayload
export type HotPayload =
export type HMRPayload =
| ConnectedPayload
| PingPayload
| UpdatePayload
| FullReloadPayload
| CustomPayload
@@ -13,10 +10,6 @@ export interface ConnectedPayload {
type: 'connected'
}
export interface PingPayload {
type: 'ping'
}
export interface UpdatePayload {
type: 'update'
updates: Update[]
@@ -32,9 +25,7 @@ export interface Update {
/** @internal */
isWithinCircularImport?: boolean
/** @internal */
firstInvalidatedBy?: string
/** @internal */
invalidates?: string[]
ssrInvalidates?: string[]
}
export interface PrunePayload {

11
node_modules/vite/types/hot.d.ts generated vendored
View File

@@ -1,4 +1,4 @@
import type { CustomEventName, InferCustomEventPayload } from './customEvent'
import type { InferCustomEventPayload } from './customEvent'
export type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: 'Module'
@@ -24,16 +24,13 @@ export interface ViteHotContext {
prune(cb: (data: any) => void): void
invalidate(message?: string): void
on<T extends CustomEventName>(
on<T extends string>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
off<T extends CustomEventName>(
off<T extends string>(
event: T,
cb: (payload: InferCustomEventPayload<T>) => void,
): void
send<T extends CustomEventName>(
event: T,
data?: InferCustomEventPayload<T>,
): void
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
}

View File

@@ -2,17 +2,8 @@
// 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
[key: string]: any
BASE_URL: string
MODE: string
DEV: boolean

View File

@@ -1,63 +0,0 @@
/* 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

@@ -1,18 +0,0 @@
/* 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'
>

View File

@@ -3,33 +3,8 @@ export interface ChunkMetadata {
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
}
}