This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

20
node_modules/copy-webpack-plugin/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
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.

1317
node_modules/copy-webpack-plugin/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

931
node_modules/copy-webpack-plugin/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,931 @@
"use strict";
const path = require("path");
const {
validate
} = require("schema-utils");
const serialize = require("serialize-javascript");
const normalizePath = require("normalize-path");
const globParent = require("glob-parent");
const fastGlob = require("fast-glob"); // @ts-ignore
const {
version
} = require("../package.json");
const schema = require("./options.json");
const {
readFile,
stat,
throttleAll
} = require("./utils");
const template = /\[\\*([\w:]+)\\*\]/i;
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("webpack").WebpackError} WebpackError */
/** @typedef {import("webpack").Asset} Asset */
/** @typedef {import("globby").Options} GlobbyOptions */
/** @typedef {import("globby").GlobEntry} GlobEntry */
/** @typedef {ReturnType<Compilation["getLogger"]>} WebpackLogger */
/** @typedef {ReturnType<Compilation["getCache"]>} CacheFacade */
/** @typedef {ReturnType<ReturnType<Compilation["getCache"]>["getLazyHashedEtag"]>} Etag */
/** @typedef {ReturnType<Compilation["fileSystemInfo"]["mergeSnapshots"]>} Snapshot */
/**
* @typedef {boolean} Force
*/
/**
* @typedef {Object} CopiedResult
* @property {string} sourceFilename
* @property {string} absoluteFilename
* @property {string} filename
* @property {Asset["source"]} source
* @property {Force | undefined} force
* @property {Record<string, any>} info
*/
/**
* @typedef {string} StringPattern
*/
/**
* @typedef {boolean} NoErrorOnMissing
*/
/**
* @typedef {string} Context
*/
/**
* @typedef {string} From
*/
/**
* @callback ToFunction
* @param {{ context: string, absoluteFilename?: string }} pathData
* @return {string | Promise<string>}
*/
/**
* @typedef {string | ToFunction} To
*/
/**
* @typedef {"dir" | "file" | "template"} ToType
*/
/**
* @callback TransformerFunction
* @param {Buffer} input
* @param {string} absoluteFilename
* @returns {string | Buffer | Promise<string> | Promise<Buffer>}
*/
/**
* @typedef {{ keys: { [key: string]: any } } | { keys: ((defaultCacheKeys: { [key: string]: any }, absoluteFilename: string) => Promise<{ [key: string]: any }>) }} TransformerCacheObject
*/
/**
* @typedef {Object} TransformerObject
* @property {TransformerFunction} transformer
* @property {boolean | TransformerCacheObject} [cache]
*/
/**
* @typedef {TransformerFunction | TransformerObject} Transform
*/
/**
* @callback Filter
* @param {string} filepath
* @returns {boolean | Promise<boolean>}
*/
/**
* @callback TransformAllFunction
* @param {{ data: Buffer, sourceFilename: string, absoluteFilename: string }[]} data
* @returns {string | Buffer | Promise<string> | Promise<Buffer>}
*/
/**
* @typedef { Record<string, any> | ((item: { absoluteFilename: string, sourceFilename: string, filename: string, toType: ToType }) => Record<string, any>) } Info
*/
/**
* @typedef {Object} ObjectPattern
* @property {From} from
* @property {GlobbyOptions} [globOptions]
* @property {Context} [context]
* @property {To} [to]
* @property {ToType} [toType]
* @property {Info} [info]
* @property {Filter} [filter]
* @property {Transform} [transform]
* @property {TransformAllFunction} [transformAll]
* @property {Force} [force]
* @property {number} [priority]
* @property {NoErrorOnMissing} [noErrorOnMissing]
*/
/**
* @typedef {StringPattern | ObjectPattern} Pattern
*/
/**
* @typedef {Object} AdditionalOptions
* @property {number} [concurrency]
*/
/**
* @typedef {Object} PluginOptions
* @property {Pattern[]} patterns
* @property {AdditionalOptions} [options]
*/
class CopyPlugin {
/**
* @param {PluginOptions} [options]
*/
constructor(options = {
patterns: []
}) {
validate(
/** @type {Schema} */
schema, options, {
name: "Copy Plugin",
baseDataPath: "options"
});
/**
* @private
* @type {Pattern[]}
*/
this.patterns = options.patterns;
/**
* @private
* @type {AdditionalOptions}
*/
this.options = options.options || {};
}
/**
* @private
* @param {Compilation} compilation
* @param {number} startTime
* @param {string} dependency
* @returns {Promise<Snapshot | undefined>}
*/
static async createSnapshot(compilation, startTime, dependency) {
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
compilation.fileSystemInfo.createSnapshot(startTime, [dependency], // @ts-ignore
// eslint-disable-next-line no-undefined
undefined, // eslint-disable-next-line no-undefined
undefined, null, (error, snapshot) => {
if (error) {
reject(error);
return;
}
resolve(
/** @type {Snapshot} */
snapshot);
});
});
}
/**
* @private
* @param {Compilation} compilation
* @param {Snapshot} snapshot
* @returns {Promise<boolean | undefined>}
*/
static async checkSnapshotValid(compilation, snapshot) {
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
compilation.fileSystemInfo.checkSnapshotValid(snapshot, (error, isValid) => {
if (error) {
reject(error);
return;
}
resolve(isValid);
});
});
}
/**
* @private
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {Buffer} source
* @returns {string}
*/
static getContentHash(compiler, compilation, source) {
const {
outputOptions
} = compilation;
const {
hashDigest,
hashDigestLength,
hashFunction,
hashSalt
} = outputOptions;
const hash = compiler.webpack.util.createHash(
/** @type {string} */
hashFunction);
if (hashSalt) {
hash.update(hashSalt);
}
hash.update(source);
const fullContentHash = hash.digest(hashDigest);
return fullContentHash.toString().slice(0, hashDigestLength);
}
/**
* @private
* @param {typeof import("globby").globby} globby
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {WebpackLogger} logger
* @param {CacheFacade} cache
* @param {ObjectPattern & { context: string }} inputPattern
* @param {number} index
* @returns {Promise<Array<CopiedResult | undefined> | undefined>}
*/
static async runPattern(globby, compiler, compilation, logger, cache, inputPattern, index) {
const {
RawSource
} = compiler.webpack.sources;
const pattern = { ...inputPattern
};
const originalFrom = pattern.from;
const normalizedOriginalFrom = path.normalize(originalFrom);
logger.log(`starting to process a pattern from '${normalizedOriginalFrom}' using '${pattern.context}' context`);
let absoluteFrom;
if (path.isAbsolute(normalizedOriginalFrom)) {
absoluteFrom = normalizedOriginalFrom;
} else {
absoluteFrom = path.resolve(pattern.context, normalizedOriginalFrom);
}
logger.debug(`getting stats for '${absoluteFrom}'...`);
const {
inputFileSystem
} = compiler;
let stats;
try {
stats = await stat(inputFileSystem, absoluteFrom);
} catch (error) {// Nothing
}
/**
* @type {"file" | "dir" | "glob"}
*/
let fromType;
if (stats) {
if (stats.isDirectory()) {
fromType = "dir";
logger.debug(`determined '${absoluteFrom}' is a directory`);
} else if (stats.isFile()) {
fromType = "file";
logger.debug(`determined '${absoluteFrom}' is a file`);
} else {
// Fallback
fromType = "glob";
logger.debug(`determined '${absoluteFrom}' is unknown`);
}
} else {
fromType = "glob";
logger.debug(`determined '${absoluteFrom}' is a glob`);
}
/** @type {GlobbyOptions & { objectMode: true }} */
const globOptions = { ...{
followSymbolicLinks: true
},
...(pattern.globOptions || {}),
...{
cwd: pattern.context,
objectMode: true
}
}; // @ts-ignore
globOptions.fs = inputFileSystem;
let glob;
switch (fromType) {
case "dir":
compilation.contextDependencies.add(absoluteFrom);
logger.debug(`added '${absoluteFrom}' as a context dependency`);
pattern.context = absoluteFrom;
glob = path.posix.join(fastGlob.escapePath(normalizePath(path.resolve(absoluteFrom))), "**/*");
absoluteFrom = path.join(absoluteFrom, "**/*");
if (typeof globOptions.dot === "undefined") {
globOptions.dot = true;
}
break;
case "file":
compilation.fileDependencies.add(absoluteFrom);
logger.debug(`added '${absoluteFrom}' as a file dependency`);
pattern.context = path.dirname(absoluteFrom);
glob = fastGlob.escapePath(normalizePath(path.resolve(absoluteFrom)));
if (typeof globOptions.dot === "undefined") {
globOptions.dot = true;
}
break;
case "glob":
default:
{
const contextDependencies = path.normalize(globParent(absoluteFrom));
compilation.contextDependencies.add(contextDependencies);
logger.debug(`added '${contextDependencies}' as a context dependency`);
glob = path.isAbsolute(originalFrom) ? originalFrom : path.posix.join(fastGlob.escapePath(normalizePath(path.resolve(pattern.context))), originalFrom);
}
}
logger.log(`begin globbing '${glob}'...`);
/**
* @type {GlobEntry[]}
*/
let globEntries;
try {
globEntries = await globby(glob, globOptions);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (globEntries.length === 0) {
if (pattern.noErrorOnMissing) {
logger.log(`finished to process a pattern from '${normalizedOriginalFrom}' using '${pattern.context}' context to '${pattern.to}'`);
return;
}
const missingError = new Error(`unable to locate '${glob}' glob`);
compilation.errors.push(
/** @type {WebpackError} */
missingError);
return;
}
/**
* @type {Array<CopiedResult | undefined>}
*/
let copiedResult;
try {
copiedResult = await Promise.all(globEntries.map(
/**
* @param {GlobEntry} globEntry
* @returns {Promise<CopiedResult | undefined>}
*/
async globEntry => {
// Exclude directories
if (!globEntry.dirent.isFile()) {
return;
}
if (pattern.filter) {
let isFiltered;
try {
isFiltered = await pattern.filter(globEntry.path);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (!isFiltered) {
logger.log(`skip '${globEntry.path}', because it was filtered`);
return;
}
}
const from = globEntry.path;
logger.debug(`found '${from}'`); // `globby`/`fast-glob` return the relative path when the path contains special characters on windows
const absoluteFilename = path.resolve(pattern.context, from);
const to = typeof pattern.to === "function" ? await pattern.to({
context: pattern.context,
absoluteFilename
}) : path.normalize(typeof pattern.to !== "undefined" ? pattern.to : "");
const toType = pattern.toType ? pattern.toType : template.test(to) ? "template" : path.extname(to) === "" || to.slice(-1) === path.sep ? "dir" : "file";
logger.log(`'to' option '${to}' determinated as '${toType}'`);
const relativeFrom = path.relative(pattern.context, absoluteFilename);
let filename = toType === "dir" ? path.join(to, relativeFrom) : to;
if (path.isAbsolute(filename)) {
filename = path.relative(
/** @type {string} */
compiler.options.output.path, filename);
}
logger.log(`determined that '${from}' should write to '${filename}'`);
const sourceFilename = normalizePath(path.relative(compiler.context, absoluteFilename)); // If this came from a glob or dir, add it to the file dependencies
if (fromType === "dir" || fromType === "glob") {
compilation.fileDependencies.add(absoluteFilename);
logger.debug(`added '${absoluteFilename}' as a file dependency`);
}
let cacheEntry;
logger.debug(`getting cache for '${absoluteFilename}'...`);
try {
cacheEntry = await cache.getPromise(`${sourceFilename}|${index}`, null);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
/**
* @type {Asset["source"] | undefined}
*/
let source;
if (cacheEntry) {
logger.debug(`found cache for '${absoluteFilename}'...`);
let isValidSnapshot;
logger.debug(`checking snapshot on valid for '${absoluteFilename}'...`);
try {
isValidSnapshot = await CopyPlugin.checkSnapshotValid(compilation, cacheEntry.snapshot);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (isValidSnapshot) {
logger.debug(`snapshot for '${absoluteFilename}' is valid`);
({
source
} = cacheEntry);
} else {
logger.debug(`snapshot for '${absoluteFilename}' is invalid`);
}
} else {
logger.debug(`missed cache for '${absoluteFilename}'`);
}
if (!source) {
const startTime = Date.now();
logger.debug(`reading '${absoluteFilename}'...`);
let data;
try {
data = await readFile(inputFileSystem, absoluteFilename);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
logger.debug(`read '${absoluteFilename}'`);
source = new RawSource(data);
let snapshot;
logger.debug(`creating snapshot for '${absoluteFilename}'...`);
try {
snapshot = await CopyPlugin.createSnapshot(compilation, startTime, absoluteFilename);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (snapshot) {
logger.debug(`created snapshot for '${absoluteFilename}'`);
logger.debug(`storing cache for '${absoluteFilename}'...`);
try {
await cache.storePromise(`${sourceFilename}|${index}`, null, {
source,
snapshot
});
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
logger.debug(`stored cache for '${absoluteFilename}'`);
}
}
if (pattern.transform) {
/**
* @type {TransformerObject}
*/
const transformObj = typeof pattern.transform === "function" ? {
transformer: pattern.transform
} : pattern.transform;
if (transformObj.transformer) {
logger.log(`transforming content for '${absoluteFilename}'...`);
const buffer = source.buffer();
if (transformObj.cache) {
// TODO: remove in the next major release
const hasher = compiler.webpack && compiler.webpack.util && compiler.webpack.util.createHash ? compiler.webpack.util.createHash("xxhash64") : // eslint-disable-next-line global-require
require("crypto").createHash("md4");
const defaultCacheKeys = {
version,
sourceFilename,
transform: transformObj.transformer,
contentHash: hasher.update(buffer).digest("hex"),
index
};
const cacheKeys = `transform|${serialize(typeof transformObj.cache === "boolean" ? defaultCacheKeys : typeof transformObj.cache.keys === "function" ? await transformObj.cache.keys(defaultCacheKeys, absoluteFilename) : { ...defaultCacheKeys,
...transformObj.cache.keys
})}`;
logger.debug(`getting transformation cache for '${absoluteFilename}'...`);
const cacheItem = cache.getItemCache(cacheKeys, cache.getLazyHashedEtag(source));
source = await cacheItem.getPromise();
logger.debug(source ? `found transformation cache for '${absoluteFilename}'` : `no transformation cache for '${absoluteFilename}'`);
if (!source) {
const transformed = await transformObj.transformer(buffer, absoluteFilename);
source = new RawSource(transformed);
logger.debug(`caching transformation for '${absoluteFilename}'...`);
await cacheItem.storePromise(source);
logger.debug(`cached transformation for '${absoluteFilename}'`);
}
} else {
source = new RawSource(await transformObj.transformer(buffer, absoluteFilename));
}
}
}
let info = typeof pattern.info === "undefined" ? {} : typeof pattern.info === "function" ? pattern.info({
absoluteFilename,
sourceFilename,
filename,
toType
}) || {} : pattern.info || {};
if (toType === "template") {
logger.log(`interpolating template '${filename}' for '${sourceFilename}'...`);
const contentHash = CopyPlugin.getContentHash(compiler, compilation, source.buffer());
const ext = path.extname(sourceFilename);
const base = path.basename(sourceFilename);
const name = base.slice(0, base.length - ext.length);
const data = {
filename: normalizePath(path.relative(pattern.context, absoluteFilename)),
contentHash,
chunk: {
name,
id:
/** @type {string} */
sourceFilename,
hash: contentHash
}
};
const {
path: interpolatedFilename,
info: assetInfo
} = compilation.getPathWithInfo(normalizePath(filename), data);
info = { ...info,
...assetInfo
};
filename = interpolatedFilename;
logger.log(`interpolated template '${filename}' for '${sourceFilename}'`);
} else {
filename = normalizePath(filename);
} // eslint-disable-next-line consistent-return
return {
sourceFilename,
absoluteFilename,
filename,
source,
info,
force: pattern.force
};
}));
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (copiedResult.length === 0) {
if (pattern.noErrorOnMissing) {
logger.log(`finished to process a pattern from '${normalizedOriginalFrom}' using '${pattern.context}' context to '${pattern.to}'`);
return;
}
const missingError = new Error(`unable to locate '${glob}' glob after filtering paths`);
compilation.errors.push(
/** @type {WebpackError} */
missingError);
return;
}
logger.log(`finished to process a pattern from '${normalizedOriginalFrom}' using '${pattern.context}' context`); // eslint-disable-next-line consistent-return
return copiedResult;
}
/**
* @param {Compiler} compiler
*/
apply(compiler) {
const pluginName = this.constructor.name;
compiler.hooks.thisCompilation.tap(pluginName, compilation => {
const logger = compilation.getLogger("copy-webpack-plugin");
const cache = compilation.getCache("CopyWebpackPlugin");
/**
* @type {typeof import("globby").globby}
*/
let globby;
compilation.hooks.processAssets.tapAsync({
name: "copy-webpack-plugin",
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
}, async (unusedAssets, callback) => {
if (typeof globby === "undefined") {
try {
// @ts-ignore
({
globby
} = await import("globby"));
} catch (error) {
callback(
/** @type {Error} */
error);
return;
}
}
logger.log("starting to add additional assets...");
const copiedResultMap = new Map();
/**
* @type {(() => Promise<void>)[]}
*/
const scheduledTasks = [];
this.patterns.map(
/**
* @param {Pattern} item
* @param {number} index
* @return {number}
*/
(item, index) => scheduledTasks.push(async () => {
/**
* @type {ObjectPattern}
*/
const normalizedPattern = typeof item === "string" ? {
from: item
} : { ...item
};
const context = typeof normalizedPattern.context === "undefined" ? compiler.context : path.isAbsolute(normalizedPattern.context) ? normalizedPattern.context : path.join(compiler.context, normalizedPattern.context);
normalizedPattern.context = context;
/**
* @type {Array<CopiedResult | undefined> | undefined}
*/
let copiedResult;
try {
copiedResult = await CopyPlugin.runPattern(globby, compiler, compilation, logger, cache,
/** @type {ObjectPattern & { context: string }} */
normalizedPattern, index);
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
if (!copiedResult) {
return;
}
/**
* @type {Array<CopiedResult>}
*/
let filteredCopiedResult = copiedResult.filter(
/**
* @param {CopiedResult | undefined} result
* @returns {result is CopiedResult}
*/
result => Boolean(result));
if (typeof normalizedPattern.transformAll !== "undefined") {
if (typeof normalizedPattern.to === "undefined") {
compilation.errors.push(
/** @type {WebpackError} */
new Error(`Invalid "pattern.to" for the "pattern.from": "${normalizedPattern.from}" and "pattern.transformAll" function. The "to" option must be specified.`));
return;
}
filteredCopiedResult.sort((a, b) => a.absoluteFilename > b.absoluteFilename ? 1 : a.absoluteFilename < b.absoluteFilename ? -1 : 0);
const mergedEtag = filteredCopiedResult.length === 1 ? cache.getLazyHashedEtag(filteredCopiedResult[0].source) : filteredCopiedResult.reduce(
/**
* @param {Etag} accumulator
* @param {CopiedResult} asset
* @param {number} i
* @return {Etag}
*/
// @ts-ignore
(accumulator, asset, i) => {
// eslint-disable-next-line no-param-reassign
accumulator = cache.mergeEtags(i === 1 ? cache.getLazyHashedEtag(
/** @type {CopiedResult}*/
accumulator.source) : accumulator, cache.getLazyHashedEtag(asset.source));
return accumulator;
});
const cacheItem = cache.getItemCache(`transformAll|${serialize({
version,
from: normalizedPattern.from,
to: normalizedPattern.to,
transformAll: normalizedPattern.transformAll
})}`, mergedEtag);
let transformedAsset = await cacheItem.getPromise();
if (!transformedAsset) {
transformedAsset = {
filename: normalizedPattern.to
};
try {
transformedAsset.data = await normalizedPattern.transformAll(filteredCopiedResult.map(asset => {
return {
data: asset.source.buffer(),
sourceFilename: asset.sourceFilename,
absoluteFilename: asset.absoluteFilename
};
}));
} catch (error) {
compilation.errors.push(
/** @type {WebpackError} */
error);
return;
}
const filename = typeof normalizedPattern.to === "function" ? await normalizedPattern.to({
context
}) : normalizedPattern.to;
if (template.test(filename)) {
const contentHash = CopyPlugin.getContentHash(compiler, compilation, transformedAsset.data);
const {
path: interpolatedFilename,
info: assetInfo
} = compilation.getPathWithInfo(normalizePath(filename), {
contentHash,
chunk: {
id: "unknown-copied-asset",
hash: contentHash
}
});
transformedAsset.filename = interpolatedFilename;
transformedAsset.info = assetInfo;
}
const {
RawSource
} = compiler.webpack.sources;
transformedAsset.source = new RawSource(transformedAsset.data);
transformedAsset.force = normalizedPattern.force;
await cacheItem.storePromise(transformedAsset);
}
filteredCopiedResult = [transformedAsset];
}
const priority = normalizedPattern.priority || 0;
if (!copiedResultMap.has(priority)) {
copiedResultMap.set(priority, []);
}
copiedResultMap.get(priority).push(...filteredCopiedResult);
}));
await throttleAll(this.options.concurrency || 100, scheduledTasks);
const copiedResult = [...copiedResultMap.entries()].sort((a, b) => a[0] - b[0]); // Avoid writing assets inside `p-limit`, because it creates concurrency.
// It could potentially lead to an error - 'Multiple assets emit different content to the same filename'
copiedResult.reduce((acc, val) => acc.concat(val[1]), []).filter(Boolean).forEach(
/**
* @param {CopiedResult} result
* @returns {void}
*/
result => {
const {
absoluteFilename,
sourceFilename,
filename,
source,
force
} = result;
const existingAsset = compilation.getAsset(filename);
if (existingAsset) {
if (force) {
const info = {
copied: true,
sourceFilename
};
logger.log(`force updating '${filename}' from '${absoluteFilename}' to compilation assets, because it already exists...`);
compilation.updateAsset(filename, source, { ...info,
...result.info
});
logger.log(`force updated '${filename}' from '${absoluteFilename}' to compilation assets, because it already exists`);
return;
}
logger.log(`skip adding '${filename}' from '${absoluteFilename}' to compilation assets, because it already exists`);
return;
}
const info = {
copied: true,
sourceFilename
};
logger.log(`writing '${filename}' from '${absoluteFilename}' to compilation assets...`);
compilation.emitAsset(filename, source, { ...info,
...result.info
});
logger.log(`written '${filename}' from '${absoluteFilename}' to compilation assets`);
});
logger.log("finished to adding additional assets");
callback();
});
if (compilation.hooks.statsPrinter) {
compilation.hooks.statsPrinter.tap(pluginName, stats => {
stats.hooks.print.for("asset.info.copied").tap("copy-webpack-plugin", (copied, {
green,
formatFlag
}) => copied ?
/** @type {Function} */
green(
/** @type {Function} */
formatFlag("copied")) : "");
});
}
});
}
}
module.exports = CopyPlugin;

161
node_modules/copy-webpack-plugin/dist/options.json generated vendored Normal file
View File

@@ -0,0 +1,161 @@
{
"definitions": {
"ObjectPattern": {
"type": "object",
"additionalProperties": false,
"properties": {
"from": {
"type": "string",
"description": "Glob or path from where we copy files.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#from",
"minLength": 1
},
"to": {
"anyOf": [
{
"type": "string"
},
{
"instanceof": "Function"
}
],
"description": "Output path.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#to"
},
"context": {
"type": "string",
"description": "A path that determines how to interpret the 'from' path.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#context"
},
"globOptions": {
"type": "object",
"description": "Allows to configute the glob pattern matching library used by the plugin.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#globoptions"
},
"filter": {
"instanceof": "Function",
"description": "Allows to filter copied assets.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#filter"
},
"transformAll": {
"instanceof": "Function",
"description": "Allows you to modify the contents of multiple files and save the result to one file.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#transformall"
},
"toType": {
"enum": ["dir", "file", "template"],
"description": "Determinate what is to option - directory, file or template.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#totype"
},
"force": {
"type": "boolean",
"description": "Overwrites files already in 'compilation.assets' (usually added by other plugins/loaders).",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#force"
},
"priority": {
"type": "number",
"description": "Allows to specify the priority of copying files with the same destination name.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#priority"
},
"info": {
"anyOf": [
{
"type": "object"
},
{
"instanceof": "Function"
}
],
"description": "Allows to add assets info.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#info"
},
"transform": {
"description": "Allows to modify the file contents.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#transform",
"anyOf": [
{
"instanceof": "Function"
},
{
"type": "object",
"additionalProperties": false,
"properties": {
"transformer": {
"instanceof": "Function",
"description": "Allows to modify the file contents.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#transformer"
},
"cache": {
"description": "Enables/disables and configure caching.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#cache",
"anyOf": [
{
"type": "boolean"
},
{
"type": "object",
"additionalProperties": false,
"properties": {
"keys": {
"anyOf": [
{
"type": "object",
"additionalProperties": true
},
{
"instanceof": "Function"
}
]
}
}
}
]
}
}
}
]
},
"noErrorOnMissing": {
"type": "boolean",
"description": "Doesn't generate an error on missing file(s).",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#noerroronmissing"
}
},
"required": ["from"]
},
"StringPattern": {
"type": "string",
"minLength": 1
}
},
"type": "object",
"additionalProperties": false,
"properties": {
"patterns": {
"type": "array",
"minItems": 1,
"items": {
"anyOf": [
{
"$ref": "#/definitions/StringPattern"
},
{
"$ref": "#/definitions/ObjectPattern"
}
]
}
},
"options": {
"type": "object",
"additionalProperties": false,
"properties": {
"concurrency": {
"type": "number",
"description": "Limits the number of simultaneous requests to fs.",
"link": "https://github.com/webpack-contrib/copy-webpack-plugin#concurrency"
}
}
}
},
"required": ["patterns"]
}

123
node_modules/copy-webpack-plugin/dist/utils.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
"use strict";
/** @typedef {import("webpack").Compilation["inputFileSystem"] } InputFileSystem */
/** @typedef {import("fs").Stats } Stats */
/**
* @param {InputFileSystem} inputFileSystem
* @param {string} path
* @return {Promise<undefined | Stats>}
*/
function stat(inputFileSystem, path) {
return new Promise((resolve, reject) => {
inputFileSystem.stat(path,
/**
* @param {null | undefined | NodeJS.ErrnoException} err
* @param {undefined | Stats} stats
*/
// @ts-ignore
(err, stats) => {
if (err) {
reject(err);
return;
}
resolve(stats);
});
});
}
/**
* @param {InputFileSystem} inputFileSystem
* @param {string} path
* @return {Promise<string | Buffer>}
*/
function readFile(inputFileSystem, path) {
return new Promise((resolve, reject) => {
inputFileSystem.readFile(path,
/**
* @param {null | undefined | NodeJS.ErrnoException} err
* @param {undefined | string | Buffer} data
*/
(err, data) => {
if (err) {
reject(err);
return;
}
resolve(
/** @type {string | Buffer} */
data);
});
});
}
const notSettled = Symbol(`not-settled`);
/**
* @template T
* @typedef {() => Promise<T>} Task
*/
/**
* Run tasks with limited concurency.
* @template T
* @param {number} limit - Limit of tasks that run at once.
* @param {Task<T>[]} tasks - List of tasks to run.
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
*/
function throttleAll(limit, tasks) {
if (!Number.isInteger(limit) || limit < 1) {
throw new TypeError(`Expected \`limit\` to be a finite number > 0, got \`${limit}\` (${typeof limit})`);
}
if (!Array.isArray(tasks) || !tasks.every(task => typeof task === `function`)) {
throw new TypeError(`Expected \`tasks\` to be a list of functions returning a promise`);
}
return new Promise((resolve, reject) => {
const result = Array(tasks.length).fill(notSettled);
const entries = tasks.entries();
const next = () => {
const {
done,
value
} = entries.next();
if (done) {
const isLast = !result.includes(notSettled);
if (isLast) {
resolve(
/** @type{T[]} **/
result);
}
return;
}
const [index, task] = value;
/**
* @param {T} x
*/
const onFulfilled = x => {
result[index] = x;
next();
};
task().then(onFulfilled, reject);
};
Array(limit).fill(0).forEach(next);
});
}
module.exports = {
stat,
readFile,
throttleAll
};

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) 2015, 2019 Elan Shanker, 2021 Blaine Bublitz <blaine.bublitz@gmail.com>, Eric Schoffstall <yo@contra.io> and other contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,134 @@
<p align="center">
<a href="https://gulpjs.com">
<img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png">
</a>
</p>
# glob-parent
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url]
Extract the non-magic parent path from a glob string.
## Usage
```js
var globParent = require('glob-parent');
globParent('path/to/*.js'); // 'path/to'
globParent('/root/path/to/*.js'); // '/root/path/to'
globParent('/*.js'); // '/'
globParent('*.js'); // '.'
globParent('**/*.js'); // '.'
globParent('path/{to,from}'); // 'path'
globParent('path/!(to|from)'); // 'path'
globParent('path/?(to|from)'); // 'path'
globParent('path/+(to|from)'); // 'path'
globParent('path/*(to|from)'); // 'path'
globParent('path/@(to|from)'); // 'path'
globParent('path/**/*'); // 'path'
// if provided a non-glob path, returns the nearest dir
globParent('path/foo/bar.js'); // 'path/foo'
globParent('path/foo/'); // 'path/foo'
globParent('path/foo'); // 'path' (see issue #3 for details)
```
## API
### `globParent(maybeGlobString, [options])`
Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below.
#### options
```js
{
// Disables the automatic conversion of slashes for Windows
flipBackslashes: true;
}
```
## Escaping
The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters:
- `?` (question mark) unless used as a path segment alone
- `*` (asterisk)
- `|` (pipe)
- `(` (opening parenthesis)
- `)` (closing parenthesis)
- `{` (opening curly brace)
- `}` (closing curly brace)
- `[` (opening bracket)
- `]` (closing bracket)
**Example**
```js
globParent('foo/[bar]/'); // 'foo'
globParent('foo/\\[bar]/'); // 'foo/[bar]'
```
## Limitations
### Braces & Brackets
This library attempts a quick and imperfect method of determining which path
parts have glob magic without fully parsing/lexing the pattern. There are some
advanced use cases that can trip it up, such as nested braces where the outer
pair is escaped and the inner one contains a path separator. If you find
yourself in the unlikely circumstance of being affected by this or need to
ensure higher-fidelity glob handling in your library, it is recommended that you
pre-process your input with [expand-braces] and/or [expand-brackets].
### Windows
Backslashes are not valid path separators for globs. If a path with backslashes
is provided anyway, for simple cases, glob-parent will replace the path
separator for you and return the non-glob parent path (now with
forward-slashes, which are still valid as Windows path separators).
This cannot be used in conjunction with escape characters.
```js
// BAD
globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)'
// GOOD
globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)'
```
If you are using escape characters for a pattern without path parts (i.e.
relative to `cwd`), prefix with `./` to avoid confusing glob-parent.
```js
// BAD
globParent('foo \\[bar]'); // 'foo '
globParent('foo \\[bar]*'); // 'foo '
// GOOD
globParent('./foo \\[bar]'); // 'foo [bar]'
globParent('./foo \\[bar]*'); // '.'
```
## License
ISC
<!-- prettier-ignore-start -->
[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/glob-parent
[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square
[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev
[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square
[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square
<!-- prettier-ignore-end -->
<!-- prettier-ignore-start -->
[expand-braces]: https://github.com/jonschlinkert/expand-braces
[expand-brackets]: https://github.com/jonschlinkert/expand-brackets
<!-- prettier-ignore-end -->

View File

@@ -0,0 +1,75 @@
'use strict';
var isGlob = require('is-glob');
var pathPosixDirname = require('path').posix.dirname;
var isWin32 = require('os').platform() === 'win32';
var slash = '/';
var backslash = /\\/g;
var escaped = /\\([!*?|[\](){}])/g;
/**
* @param {string} str
* @param {Object} opts
* @param {boolean} [opts.flipBackslashes=true]
*/
module.exports = function globParent(str, opts) {
var options = Object.assign({ flipBackslashes: true }, opts);
// flip windows path separators
if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
str = str.replace(backslash, slash);
}
// special case for strings ending in enclosure containing path separator
if (isEnclosure(str)) {
str += slash;
}
// preserves full path in case of trailing path separator
str += 'a';
// remove path parts that are globby
do {
str = pathPosixDirname(str);
} while (isGlobby(str));
// remove escape chars and return result
return str.replace(escaped, '$1');
};
function isEnclosure(str) {
var lastChar = str.slice(-1);
var enclosureStart;
switch (lastChar) {
case '}':
enclosureStart = '{';
break;
case ']':
enclosureStart = '[';
break;
default:
return false;
}
var foundIndex = str.indexOf(enclosureStart);
if (foundIndex < 0) {
return false;
}
return str.slice(foundIndex + 1, -1).includes(slash);
}
function isGlobby(str) {
if (/\([^()]+$/.test(str)) {
return true;
}
if (str[0] === '{' || str[0] === '[') {
return true;
}
if (/[^\\][{[]/.test(str)) {
return true;
}
return isGlob(str);
}

View File

@@ -0,0 +1,54 @@
{
"name": "glob-parent",
"version": "6.0.2",
"description": "Extract the non-magic parent path from a glob string.",
"author": "Gulp Team <team@gulpjs.com> (https://gulpjs.com/)",
"contributors": [
"Elan Shanker (https://github.com/es128)",
"Blaine Bublitz <blaine.bublitz@gmail.com>"
],
"repository": "gulpjs/glob-parent",
"license": "ISC",
"engines": {
"node": ">=10.13.0"
},
"main": "index.js",
"files": [
"LICENSE",
"index.js"
],
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "nyc mocha --async-only"
},
"dependencies": {
"is-glob": "^4.0.3"
},
"devDependencies": {
"eslint": "^7.0.0",
"eslint-config-gulp": "^5.0.0",
"expect": "^26.0.1",
"mocha": "^7.1.2",
"nyc": "^15.0.1"
},
"nyc": {
"reporter": [
"lcov",
"text-summary"
]
},
"prettier": {
"singleQuote": true
},
"keywords": [
"glob",
"parent",
"strip",
"path",
"dirname",
"directory",
"base",
"wildcard"
]
}

View File

@@ -0,0 +1,94 @@
import process from 'node:process';
import fs from 'node:fs';
import path from 'node:path';
import fastGlob from 'fast-glob';
import gitIgnore from 'ignore';
import slash from 'slash';
import {toPath, isNegativePattern} from './utilities.js';
const ignoreFilesGlobOptions = {
ignore: [
'**/node_modules',
'**/flow-typed',
'**/coverage',
'**/.git',
],
absolute: true,
dot: true,
};
export const GITIGNORE_FILES_PATTERN = '**/.gitignore';
const applyBaseToPattern = (pattern, base) => isNegativePattern(pattern)
? '!' + path.posix.join(base, pattern.slice(1))
: path.posix.join(base, pattern);
const parseIgnoreFile = (file, cwd) => {
const base = slash(path.relative(cwd, path.dirname(file.filePath)));
return file.content
.split(/\r?\n/)
.filter(line => line && !line.startsWith('#'))
.map(pattern => applyBaseToPattern(pattern, base));
};
const toRelativePath = (fileOrDirectory, cwd) => {
cwd = slash(cwd);
if (path.isAbsolute(fileOrDirectory)) {
if (slash(fileOrDirectory).startsWith(cwd)) {
return path.relative(cwd, fileOrDirectory);
}
throw new Error(`Path ${fileOrDirectory} is not in cwd ${cwd}`);
}
return fileOrDirectory;
};
const getIsIgnoredPredicate = (files, cwd) => {
const patterns = files.flatMap(file => parseIgnoreFile(file, cwd));
const ignores = gitIgnore().add(patterns);
return fileOrDirectory => {
fileOrDirectory = toPath(fileOrDirectory);
fileOrDirectory = toRelativePath(fileOrDirectory, cwd);
return fileOrDirectory ? ignores.ignores(slash(fileOrDirectory)) : false;
};
};
const normalizeOptions = (options = {}) => ({
cwd: toPath(options.cwd) || process.cwd(),
suppressErrors: Boolean(options.suppressErrors),
deep: typeof options.deep === 'number' ? options.deep : Number.POSITIVE_INFINITY,
});
export const isIgnoredByIgnoreFiles = async (patterns, options) => {
const {cwd, suppressErrors, deep} = normalizeOptions(options);
const paths = await fastGlob(patterns, {cwd, suppressErrors, deep, ...ignoreFilesGlobOptions});
const files = await Promise.all(
paths.map(async filePath => ({
filePath,
content: await fs.promises.readFile(filePath, 'utf8'),
})),
);
return getIsIgnoredPredicate(files, cwd);
};
export const isIgnoredByIgnoreFilesSync = (patterns, options) => {
const {cwd, suppressErrors, deep} = normalizeOptions(options);
const paths = fastGlob.sync(patterns, {cwd, suppressErrors, deep, ...ignoreFilesGlobOptions});
const files = paths.map(filePath => ({
filePath,
content: fs.readFileSync(filePath, 'utf8'),
}));
return getIsIgnoredPredicate(files, cwd);
};
export const isGitIgnored = options => isIgnoredByIgnoreFiles(GITIGNORE_FILES_PATTERN, options);
export const isGitIgnoredSync = options => isIgnoredByIgnoreFilesSync(GITIGNORE_FILES_PATTERN, options);

View File

@@ -0,0 +1,205 @@
import {Options as FastGlobOptions, Entry} from 'fast-glob';
export type GlobEntry = Entry;
export interface GlobTask {
readonly patterns: string[];
readonly options: Options;
}
export type ExpandDirectoriesOption =
| boolean
| readonly string[]
| {files?: readonly string[]; extensions?: readonly string[]};
type FastGlobOptionsWithoutCwd = Omit<FastGlobOptions, 'cwd'>;
export interface Options extends FastGlobOptionsWithoutCwd {
/**
If set to `true`, `globby` will automatically glob directories for you. If you define an `Array` it will only glob files that matches the patterns inside the `Array`. You can also define an `Object` with `files` and `extensions` like in the example below.
Note that if you set this option to `false`, you won't get back matched directories unless you set `onlyFiles: false`.
@default true
@example
```
import {globby} from 'globby';
const paths = await globby('images', {
expandDirectories: {
files: ['cat', 'unicorn', '*.jpg'],
extensions: ['png']
}
});
console.log(paths);
//=> ['cat.png', 'unicorn.png', 'cow.jpg', 'rainbow.jpg']
```
*/
readonly expandDirectories?: ExpandDirectoriesOption;
/**
Respect ignore patterns in `.gitignore` files that apply to the globbed files.
@default false
*/
readonly gitignore?: boolean;
/**
Glob patterns to look for ignore files, which are then used to ignore globbed files.
This is a more generic form of the `gitignore` option, allowing you to find ignore files with a [compatible syntax](http://git-scm.com/docs/gitignore). For instance, this works with Babel's `.babelignore`, Prettier's `.prettierignore`, or ESLint's `.eslintignore` files.
@default undefined
*/
readonly ignoreFiles?: string | readonly string[];
/**
The current working directory in which to search.
@default process.cwd()
*/
readonly cwd?: URL | string;
}
export interface GitignoreOptions {
readonly cwd?: URL | string;
}
export type GlobbyFilterFunction = (path: URL | string) => boolean;
/**
Find files and directories using glob patterns.
Note that glob patterns can only contain forward-slashes, not backward-slashes, so if you want to construct a glob pattern from path components, you need to use `path.posix.join()` instead of `path.join()`.
@param patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
@param options - See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3) in addition to the ones in this package.
@returns The matching paths.
@example
```
import {globby} from 'globby';
const paths = await globby(['*', '!cake']);
console.log(paths);
//=> ['unicorn', 'rainbow']
```
*/
export function globby(
patterns: string | readonly string[],
options: Options & {objectMode: true}
): Promise<GlobEntry[]>;
export function globby(
patterns: string | readonly string[],
options?: Options
): Promise<string[]>;
/**
Find files and directories using glob patterns.
Note that glob patterns can only contain forward-slashes, not backward-slashes, so if you want to construct a glob pattern from path components, you need to use `path.posix.join()` instead of `path.join()`.
@param patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
@param options - See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3) in addition to the ones in this package.
@returns The matching paths.
*/
export function globbySync(
patterns: string | readonly string[],
options: Options & {objectMode: true}
): GlobEntry[];
export function globbySync(
patterns: string | readonly string[],
options?: Options
): string[];
/**
Find files and directories using glob patterns.
Note that glob patterns can only contain forward-slashes, not backward-slashes, so if you want to construct a glob pattern from path components, you need to use `path.posix.join()` instead of `path.join()`.
@param patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
@param options - See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3) in addition to the ones in this package.
@returns The stream of matching paths.
@example
```
import {globbyStream} from 'globby';
for await (const path of globbyStream('*.tmp')) {
console.log(path);
}
```
*/
export function globbyStream(
patterns: string | readonly string[],
options?: Options
): NodeJS.ReadableStream;
/**
Note that you should avoid running the same tasks multiple times as they contain a file system cache. Instead, run this method each time to ensure file system changes are taken into consideration.
@param patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
@param options - See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3) in addition to the ones in this package.
@returns An object in the format `{pattern: string, options: object}`, which can be passed as arguments to [`fast-glob`](https://github.com/mrmlnc/fast-glob). This is useful for other globbing-related packages.
*/
export function generateGlobTasks(
patterns: string | readonly string[],
options?: Options
): Promise<GlobTask[]>;
/**
@see generateGlobTasks
@returns An object in the format `{pattern: string, options: object}`, which can be passed as arguments to [`fast-glob`](https://github.com/mrmlnc/fast-glob). This is useful for other globbing-related packages.
*/
export function generateGlobTasksSync(
patterns: string | readonly string[],
options?: Options
): GlobTask[];
/**
Note that the options affect the results.
This function is backed by [`fast-glob`](https://github.com/mrmlnc/fast-glob#isdynamicpatternpattern-options).
@param patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
@param options - See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3).
@returns Whether there are any special glob characters in the `patterns`.
*/
export function isDynamicPattern(
patterns: string | readonly string[],
options?: FastGlobOptionsWithoutCwd & {
/**
The current working directory in which to search.
@default process.cwd()
*/
readonly cwd?: URL | string;
}
): boolean;
/**
`.gitignore` files matched by the ignore config are not used for the resulting filter function.
@returns A filter function indicating whether a given path is ignored via a `.gitignore` file.
@example
```
import {isGitIgnored} from 'globby';
const isIgnored = await isGitIgnored();
console.log(isIgnored('some/file'));
```
*/
export function isGitIgnored(options?: GitignoreOptions): Promise<GlobbyFilterFunction>;
/**
@see isGitIgnored
@returns A filter function indicating whether a given path is ignored via a `.gitignore` file.
*/
export function isGitIgnoredSync(options?: GitignoreOptions): GlobbyFilterFunction;

View File

@@ -0,0 +1,229 @@
import fs from 'node:fs';
import nodePath from 'node:path';
import merge2 from 'merge2';
import fastGlob from 'fast-glob';
import dirGlob from 'dir-glob';
import {
GITIGNORE_FILES_PATTERN,
isIgnoredByIgnoreFiles,
isIgnoredByIgnoreFilesSync,
} from './ignore.js';
import {FilterStream, toPath, isNegativePattern} from './utilities.js';
const assertPatternsInput = patterns => {
if (patterns.some(pattern => typeof pattern !== 'string')) {
throw new TypeError('Patterns must be a string or an array of strings');
}
};
const toPatternsArray = patterns => {
patterns = [...new Set([patterns].flat())];
assertPatternsInput(patterns);
return patterns;
};
const checkCwdOption = options => {
if (!options.cwd) {
return;
}
let stat;
try {
stat = fs.statSync(options.cwd);
} catch {
return;
}
if (!stat.isDirectory()) {
throw new Error('The `cwd` option must be a path to a directory');
}
};
const normalizeOptions = (options = {}) => {
options = {
...options,
ignore: options.ignore || [],
expandDirectories: options.expandDirectories === undefined
? true
: options.expandDirectories,
cwd: toPath(options.cwd),
};
checkCwdOption(options);
return options;
};
const normalizeArguments = fn => async (patterns, options) => fn(toPatternsArray(patterns), normalizeOptions(options));
const normalizeArgumentsSync = fn => (patterns, options) => fn(toPatternsArray(patterns), normalizeOptions(options));
const getIgnoreFilesPatterns = options => {
const {ignoreFiles, gitignore} = options;
const patterns = ignoreFiles ? toPatternsArray(ignoreFiles) : [];
if (gitignore) {
patterns.push(GITIGNORE_FILES_PATTERN);
}
return patterns;
};
const getFilter = async options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
return createFilterFunction(
ignoreFilesPatterns.length > 0 && await isIgnoredByIgnoreFiles(ignoreFilesPatterns, options),
);
};
const getFilterSync = options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
return createFilterFunction(
ignoreFilesPatterns.length > 0 && isIgnoredByIgnoreFilesSync(ignoreFilesPatterns, options),
);
};
const createFilterFunction = isIgnored => {
const seen = new Set();
return fastGlobResult => {
const path = fastGlobResult.path || fastGlobResult;
const pathKey = nodePath.normalize(path);
const seenOrIgnored = seen.has(pathKey) || (isIgnored && isIgnored(path));
seen.add(pathKey);
return !seenOrIgnored;
};
};
const unionFastGlobResults = (results, filter) => results.flat().filter(fastGlobResult => filter(fastGlobResult));
const unionFastGlobStreams = (streams, filter) => merge2(streams).pipe(new FilterStream(fastGlobResult => filter(fastGlobResult)));
const convertNegativePatterns = (patterns, options) => {
const tasks = [];
while (patterns.length > 0) {
const index = patterns.findIndex(pattern => isNegativePattern(pattern));
if (index === -1) {
tasks.push({patterns, options});
break;
}
const ignorePattern = patterns[index].slice(1);
for (const task of tasks) {
task.options.ignore.push(ignorePattern);
}
if (index !== 0) {
tasks.push({
patterns: patterns.slice(0, index),
options: {
...options,
ignore: [
...options.ignore,
ignorePattern,
],
},
});
}
patterns = patterns.slice(index + 1);
}
return tasks;
};
const getDirGlobOptions = (options, cwd) => ({
...(cwd ? {cwd} : {}),
...(Array.isArray(options) ? {files: options} : options),
});
const generateTasks = async (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories} = options;
if (!expandDirectories) {
return globTasks;
}
const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd);
const ignoreExpandOptions = cwd ? {cwd} : undefined;
return Promise.all(
globTasks.map(async task => {
let {patterns, options} = task;
[
patterns,
options.ignore,
] = await Promise.all([
dirGlob(patterns, patternExpandOptions),
dirGlob(options.ignore, ignoreExpandOptions),
]);
return {patterns, options};
}),
);
};
const generateTasksSync = (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories} = options;
if (!expandDirectories) {
return globTasks;
}
const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd);
const ignoreExpandOptions = cwd ? {cwd} : undefined;
return globTasks.map(task => {
let {patterns, options} = task;
patterns = dirGlob.sync(patterns, patternExpandOptions);
options.ignore = dirGlob.sync(options.ignore, ignoreExpandOptions);
return {patterns, options};
});
};
export const globby = normalizeArguments(async (patterns, options) => {
const [
tasks,
filter,
] = await Promise.all([
generateTasks(patterns, options),
getFilter(options),
]);
const results = await Promise.all(tasks.map(task => fastGlob(task.patterns, task.options)));
return unionFastGlobResults(results, filter);
});
export const globbySync = normalizeArgumentsSync((patterns, options) => {
const tasks = generateTasksSync(patterns, options);
const filter = getFilterSync(options);
const results = tasks.map(task => fastGlob.sync(task.patterns, task.options));
return unionFastGlobResults(results, filter);
});
export const globbyStream = normalizeArgumentsSync((patterns, options) => {
const tasks = generateTasksSync(patterns, options);
const filter = getFilterSync(options);
const streams = tasks.map(task => fastGlob.stream(task.patterns, task.options));
return unionFastGlobStreams(streams, filter);
});
export const isDynamicPattern = normalizeArgumentsSync(
(patterns, options) => patterns.some(pattern => fastGlob.isDynamicPattern(pattern, options)),
);
export const generateGlobTasks = normalizeArguments(generateTasks);
export const generateGlobTasksSync = normalizeArgumentsSync(generateTasksSync);
export {
isGitIgnored,
isGitIgnoredSync,
} from './ignore.js';

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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

@@ -0,0 +1,96 @@
{
"name": "globby",
"version": "13.2.2",
"description": "User-friendly glob matching",
"license": "MIT",
"repository": "sindresorhus/globby",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"scripts": {
"bench": "npm update @globby/main-branch glob-stream fast-glob && node bench.js",
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts",
"ignore.js",
"utilities.js"
],
"keywords": [
"all",
"array",
"directories",
"expand",
"files",
"filesystem",
"filter",
"find",
"fnmatch",
"folders",
"fs",
"glob",
"globbing",
"globs",
"gulpfriendly",
"match",
"matcher",
"minimatch",
"multi",
"multiple",
"paths",
"pattern",
"patterns",
"traverse",
"util",
"utility",
"wildcard",
"wildcards",
"promise",
"gitignore",
"git"
],
"dependencies": {
"dir-glob": "^3.0.1",
"fast-glob": "^3.3.0",
"ignore": "^5.2.4",
"merge2": "^1.4.1",
"slash": "^4.0.0"
},
"devDependencies": {
"@globby/main-branch": "sindresorhus/globby#main",
"@types/node": "^20.3.3",
"ava": "^5.3.1",
"benchmark": "2.1.4",
"glob-stream": "^8.0.0",
"rimraf": "^5.0.1",
"tempy": "^3.0.0",
"tsd": "^0.28.1",
"typescript": "^5.1.6",
"xo": "^0.54.2"
},
"xo": {
"ignores": [
"fixtures"
],
"rules": {
"@typescript-eslint/consistent-type-definitions": "off",
"n/prefer-global/url": "off",
"@typescript-eslint/consistent-type-imports": "off"
}
},
"ava": {
"files": [
"!tests/utilities.js"
],
"workerThreads": false
}
}

View File

@@ -0,0 +1,183 @@
# globby
> User-friendly glob matching
Based on [`fast-glob`](https://github.com/mrmlnc/fast-glob) but adds a bunch of useful features.
## Features
- Promise API
- Multiple patterns
- Negated patterns: `['foo*', '!foobar']`
- Expands directories: `foo``foo/**/*`
- Supports `.gitignore` and similar ignore config files
- Supports `URL` as `cwd`
## Install
```
$ npm install globby
```
## Usage
```
├── unicorn
├── cake
└── rainbow
```
```js
import {globby} from 'globby';
const paths = await globby(['*', '!cake']);
console.log(paths);
//=> ['unicorn', 'rainbow']
```
## API
Note that glob patterns can only contain forward-slashes, not backward-slashes, so if you want to construct a glob pattern from path components, you need to use `path.posix.join()` instead of `path.join()`.
### globby(patterns, options?)
Returns a `Promise<string[]>` of matching paths.
#### patterns
Type: `string | string[]`
See supported `minimatch` [patterns](https://github.com/isaacs/minimatch#usage).
#### options
Type: `object`
See the [`fast-glob` options](https://github.com/mrmlnc/fast-glob#options-3) in addition to the ones below.
##### expandDirectories
Type: `boolean | string[] | object`\
Default: `true`
If set to `true`, `globby` will automatically glob directories for you. If you define an `Array` it will only glob files that matches the patterns inside the `Array`. You can also define an `object` with `files` and `extensions` like below:
```js
import {globby} from 'globby';
(async () => {
const paths = await globby('images', {
expandDirectories: {
files: ['cat', 'unicorn', '*.jpg'],
extensions: ['png']
}
});
console.log(paths);
//=> ['cat.png', 'unicorn.png', 'cow.jpg', 'rainbow.jpg']
})();
```
Note that if you set this option to `false`, you won't get back matched directories unless you set `onlyFiles: false`.
##### gitignore
Type: `boolean`\
Default: `false`
Respect ignore patterns in `.gitignore` files that apply to the globbed files.
##### ignoreFiles
Type: `string | string[]`\
Default: `undefined`
Glob patterns to look for ignore files, which are then used to ignore globbed files.
This is a more generic form of the `gitignore` option, allowing you to find ignore files with a [compatible syntax](http://git-scm.com/docs/gitignore). For instance, this works with Babel's `.babelignore`, Prettier's `.prettierignore`, or ESLint's `.eslintignore` files.
### globbySync(patterns, options?)
Returns `string[]` of matching paths.
### globbyStream(patterns, options?)
Returns a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) of matching paths.
Since Node.js 10, [readable streams are iterable](https://nodejs.org/api/stream.html#stream_readable_symbol_asynciterator), so you can loop over glob matches in a [`for await...of` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) like this:
```js
import {globbyStream} from 'globby';
(async () => {
for await (const path of globbyStream('*.tmp')) {
console.log(path);
}
})();
```
### generateGlobTasks(patterns, options?)
Returns an `Promise<object[]>` in the format `{patterns: string[], options: Object}`, which can be passed as arguments to [`fast-glob`](https://github.com/mrmlnc/fast-glob). This is useful for other globbing-related packages.
Note that you should avoid running the same tasks multiple times as they contain a file system cache. Instead, run this method each time to ensure file system changes are taken into consideration.
### generateGlobTasksSync(patterns, options?)
Returns an `object[]` in the format `{patterns: string[], options: Object}`, which can be passed as arguments to [`fast-glob`](https://github.com/mrmlnc/fast-glob). This is useful for other globbing-related packages.
Takes the same arguments as `generateGlobTasks`.
### isDynamicPattern(patterns, options?)
Returns a `boolean` of whether there are any special glob characters in the `patterns`.
Note that the options affect the results.
This function is backed by [`fast-glob`](https://github.com/mrmlnc/fast-glob#isdynamicpatternpattern-options).
### isGitIgnored(options?)
Returns a `Promise<(path: URL | string) => boolean>` indicating whether a given path is ignored via a `.gitignore` file.
Takes `cwd?: URL | string` as options.
```js
import {isGitIgnored} from 'globby';
const isIgnored = await isGitIgnored();
console.log(isIgnored('some/file'));
```
### isGitIgnoredSync(options?)
Returns a `(path: URL | string) => boolean` indicating whether a given path is ignored via a `.gitignore` file.
Takes `cwd?: URL | string` as options.
## Globbing patterns
Just a quick overview.
- `*` matches any number of characters, but not `/`
- `?` matches a single character, but not `/`
- `**` matches any number of characters, including `/`, as long as it's the only thing in a path part
- `{}` allows for a comma-separated list of "or" expressions
- `!` at the beginning of a pattern will negate the match
[Various patterns and expected matches.](https://github.com/sindresorhus/multimatch/blob/main/test/test.js)
## globby for enterprise
Available as part of the Tidelift Subscription.
The maintainers of globby and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-globby?utm_source=npm-globby&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [multimatch](https://github.com/sindresorhus/multimatch) - Match against a list instead of the filesystem
- [matcher](https://github.com/sindresorhus/matcher) - Simple wildcard matching
- [del](https://github.com/sindresorhus/del) - Delete files and directories
- [make-dir](https://github.com/sindresorhus/make-dir) - Make a directory and its parents if needed

View File

@@ -0,0 +1,17 @@
import {fileURLToPath} from 'node:url';
import {Transform} from 'node:stream';
export const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
export class FilterStream extends Transform {
constructor(filter) {
super({
objectMode: true,
transform(data, encoding, callback) {
callback(undefined, filter(data) ? data : undefined);
},
});
}
}
export const isNegativePattern = pattern => pattern[0] === '!';

View File

@@ -0,0 +1,23 @@
/**
Convert Windows backslash paths to slash paths: `foo\\bar` ➔ `foo/bar`.
[Forward-slash paths can be used in Windows](http://superuser.com/a/176395/6877) as long as they're not extended-length paths and don't contain any non-ascii characters.
@param path - A Windows backslash path.
@returns A path with forward slashes.
@example
```
import path from 'path';
import slash from 'slash';
const string = path.join('foo', 'bar');
// Unix => foo/bar
// Windows => foo\\bar
slash(string);
// Unix => foo/bar
// Windows => foo/bar
```
*/
export default function slash(path: string): string;

View File

@@ -0,0 +1,10 @@
export default function slash(path) {
const isExtendedLengthPath = /^\\\\\?\\/.test(path);
const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
if (isExtendedLengthPath || hasNonAscii) {
return path;
}
return path.replace(/\\/g, '/');
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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

@@ -0,0 +1,38 @@
{
"name": "slash",
"version": "4.0.0",
"description": "Convert Windows backslash paths to slash paths",
"license": "MIT",
"repository": "sindresorhus/slash",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"path",
"seperator",
"slash",
"backslash",
"windows",
"convert"
],
"devDependencies": {
"ava": "^3.15.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}

View File

@@ -0,0 +1,48 @@
# slash
> Convert Windows backslash paths to slash paths: `foo\\bar` ➔ `foo/bar`
[Forward-slash paths can be used in Windows](http://superuser.com/a/176395/6877) as long as they're not extended-length paths and don't contain any non-ascii characters.
This was created since the `path` methods in Node.js outputs `\\` paths on Windows.
## Install
```
$ npm install slash
```
## Usage
```js
import path from 'path';
import slash from 'slash';
const string = path.join('foo', 'bar');
// Unix => foo/bar
// Windows => foo\\bar
slash(string);
// Unix => foo/bar
// Windows => foo/bar
```
## API
### slash(path)
Type: `string`
Accepts a Windows backslash path and returns a path with forward slashes.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-slash?utm_source=npm-slash&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

93
node_modules/copy-webpack-plugin/package.json generated vendored Normal file
View File

@@ -0,0 +1,93 @@
{
"name": "copy-webpack-plugin",
"version": "11.0.0",
"description": "Copy files && directories with webpack",
"license": "MIT",
"repository": "webpack-contrib/copy-webpack-plugin",
"author": "Len Boyette",
"homepage": "https://github.com/webpack-contrib/copy-webpack-plugin",
"bugs": "https://github.com/webpack-contrib/copy-webpack-plugin/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/webpack"
},
"main": "dist/index.js",
"types": "types/index.d.ts",
"engines": {
"node": ">= 14.15.0"
},
"scripts": {
"start": "npm run build -- -w",
"clean": "del-cli dist types",
"prebuild": "npm run clean",
"build:types": "tsc --declaration --emitDeclarationOnly --outDir types --rootDir src && prettier \"types/**/*.ts\" --write",
"build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files",
"build": "npm-run-all -p \"build:**\"",
"commitlint": "commitlint --from=master",
"security": "npm audit --production",
"lint:prettier": "prettier --list-different .",
"lint:js": "eslint --cache .",
"lint:types": "tsc --pretty --noEmit",
"lint": "npm-run-all -l -p \"lint:**\"",
"test:only": "cross-env NODE_ENV=test jest",
"test:watch": "npm run test:only -- --watch",
"test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
"pretest": "npm run lint",
"test": "npm run test:coverage",
"prepare": "husky install && npm run build",
"release": "standard-version"
},
"files": [
"dist",
"types"
],
"peerDependencies": {
"webpack": "^5.1.0"
},
"dependencies": {
"fast-glob": "^3.2.11",
"glob-parent": "^6.0.1",
"globby": "^13.1.1",
"normalize-path": "^3.0.0",
"schema-utils": "^4.0.0",
"serialize-javascript": "^6.0.0"
},
"devDependencies": {
"@babel/cli": "^7.17.10",
"@babel/core": "^7.17.10",
"@babel/eslint-parser": "^7.16.5",
"@babel/preset-env": "^7.17.12",
"@commitlint/cli": "^17.0.0",
"@commitlint/config-conventional": "^17.0.0",
"@types/glob-parent": "^5.1.1",
"@types/normalize-path": "^3.0.0",
"@types/serialize-javascript": "^5.0.2",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^28.1.0",
"cross-env": "^7.0.3",
"del": "^6.0.0",
"del-cli": "^4.0.1",
"eslint": "^8.15.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"file-loader": "^6.2.0",
"husky": "^8.0.1",
"is-gzip": "^2.0.0",
"jest": "^28.1.0",
"lint-staged": "^12.4.1",
"memfs": "^3.4.1",
"mkdirp": "^1.0.4",
"npm-run-all": "^4.1.5",
"prettier": "^2.6.2",
"standard-version": "^9.3.1",
"typescript": "^4.6.4",
"webpack": "^5.72.1"
},
"keywords": [
"webpack",
"plugin",
"transfer",
"move",
"copy"
]
}

289
node_modules/copy-webpack-plugin/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,289 @@
export = CopyPlugin;
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("webpack").WebpackError} WebpackError */
/** @typedef {import("webpack").Asset} Asset */
/** @typedef {import("globby").Options} GlobbyOptions */
/** @typedef {import("globby").GlobEntry} GlobEntry */
/** @typedef {ReturnType<Compilation["getLogger"]>} WebpackLogger */
/** @typedef {ReturnType<Compilation["getCache"]>} CacheFacade */
/** @typedef {ReturnType<ReturnType<Compilation["getCache"]>["getLazyHashedEtag"]>} Etag */
/** @typedef {ReturnType<Compilation["fileSystemInfo"]["mergeSnapshots"]>} Snapshot */
/**
* @typedef {boolean} Force
*/
/**
* @typedef {Object} CopiedResult
* @property {string} sourceFilename
* @property {string} absoluteFilename
* @property {string} filename
* @property {Asset["source"]} source
* @property {Force | undefined} force
* @property {Record<string, any>} info
*/
/**
* @typedef {string} StringPattern
*/
/**
* @typedef {boolean} NoErrorOnMissing
*/
/**
* @typedef {string} Context
*/
/**
* @typedef {string} From
*/
/**
* @callback ToFunction
* @param {{ context: string, absoluteFilename?: string }} pathData
* @return {string | Promise<string>}
*/
/**
* @typedef {string | ToFunction} To
*/
/**
* @typedef {"dir" | "file" | "template"} ToType
*/
/**
* @callback TransformerFunction
* @param {Buffer} input
* @param {string} absoluteFilename
* @returns {string | Buffer | Promise<string> | Promise<Buffer>}
*/
/**
* @typedef {{ keys: { [key: string]: any } } | { keys: ((defaultCacheKeys: { [key: string]: any }, absoluteFilename: string) => Promise<{ [key: string]: any }>) }} TransformerCacheObject
*/
/**
* @typedef {Object} TransformerObject
* @property {TransformerFunction} transformer
* @property {boolean | TransformerCacheObject} [cache]
*/
/**
* @typedef {TransformerFunction | TransformerObject} Transform
*/
/**
* @callback Filter
* @param {string} filepath
* @returns {boolean | Promise<boolean>}
*/
/**
* @callback TransformAllFunction
* @param {{ data: Buffer, sourceFilename: string, absoluteFilename: string }[]} data
* @returns {string | Buffer | Promise<string> | Promise<Buffer>}
*/
/**
* @typedef { Record<string, any> | ((item: { absoluteFilename: string, sourceFilename: string, filename: string, toType: ToType }) => Record<string, any>) } Info
*/
/**
* @typedef {Object} ObjectPattern
* @property {From} from
* @property {GlobbyOptions} [globOptions]
* @property {Context} [context]
* @property {To} [to]
* @property {ToType} [toType]
* @property {Info} [info]
* @property {Filter} [filter]
* @property {Transform} [transform]
* @property {TransformAllFunction} [transformAll]
* @property {Force} [force]
* @property {number} [priority]
* @property {NoErrorOnMissing} [noErrorOnMissing]
*/
/**
* @typedef {StringPattern | ObjectPattern} Pattern
*/
/**
* @typedef {Object} AdditionalOptions
* @property {number} [concurrency]
*/
/**
* @typedef {Object} PluginOptions
* @property {Pattern[]} patterns
* @property {AdditionalOptions} [options]
*/
declare class CopyPlugin {
/**
* @private
* @param {Compilation} compilation
* @param {number} startTime
* @param {string} dependency
* @returns {Promise<Snapshot | undefined>}
*/
private static createSnapshot;
/**
* @private
* @param {Compilation} compilation
* @param {Snapshot} snapshot
* @returns {Promise<boolean | undefined>}
*/
private static checkSnapshotValid;
/**
* @private
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {Buffer} source
* @returns {string}
*/
private static getContentHash;
/**
* @private
* @param {typeof import("globby").globby} globby
* @param {Compiler} compiler
* @param {Compilation} compilation
* @param {WebpackLogger} logger
* @param {CacheFacade} cache
* @param {ObjectPattern & { context: string }} inputPattern
* @param {number} index
* @returns {Promise<Array<CopiedResult | undefined> | undefined>}
*/
private static runPattern;
/**
* @param {PluginOptions} [options]
*/
constructor(options?: PluginOptions | undefined);
/**
* @private
* @type {Pattern[]}
*/
private patterns;
/**
* @private
* @type {AdditionalOptions}
*/
private options;
/**
* @param {Compiler} compiler
*/
apply(compiler: Compiler): void;
}
declare namespace CopyPlugin {
export {
Schema,
Compiler,
Compilation,
WebpackError,
Asset,
GlobbyOptions,
GlobEntry,
WebpackLogger,
CacheFacade,
Etag,
Snapshot,
Force,
CopiedResult,
StringPattern,
NoErrorOnMissing,
Context,
From,
ToFunction,
To,
ToType,
TransformerFunction,
TransformerCacheObject,
TransformerObject,
Transform,
Filter,
TransformAllFunction,
Info,
ObjectPattern,
Pattern,
AdditionalOptions,
PluginOptions,
};
}
type Compiler = import("webpack").Compiler;
type PluginOptions = {
patterns: Pattern[];
options?: AdditionalOptions | undefined;
};
type Schema = import("schema-utils/declarations/validate").Schema;
type Compilation = import("webpack").Compilation;
type WebpackError = import("webpack").WebpackError;
type Asset = import("webpack").Asset;
type GlobbyOptions = import("globby").Options;
type GlobEntry = import("globby").GlobEntry;
type WebpackLogger = ReturnType<Compilation["getLogger"]>;
type CacheFacade = ReturnType<Compilation["getCache"]>;
type Etag = ReturnType<
ReturnType<Compilation["getCache"]>["getLazyHashedEtag"]
>;
type Snapshot = ReturnType<Compilation["fileSystemInfo"]["mergeSnapshots"]>;
type Force = boolean;
type CopiedResult = {
sourceFilename: string;
absoluteFilename: string;
filename: string;
source: Asset["source"];
force: Force | undefined;
info: Record<string, any>;
};
type StringPattern = string;
type NoErrorOnMissing = boolean;
type Context = string;
type From = string;
type ToFunction = (pathData: {
context: string;
absoluteFilename?: string;
}) => string | Promise<string>;
type To = string | ToFunction;
type ToType = "dir" | "file" | "template";
type TransformerFunction = (
input: Buffer,
absoluteFilename: string
) => string | Buffer | Promise<string> | Promise<Buffer>;
type TransformerCacheObject =
| {
keys: {
[key: string]: any;
};
}
| {
keys: (
defaultCacheKeys: {
[key: string]: any;
},
absoluteFilename: string
) => Promise<{
[key: string]: any;
}>;
};
type TransformerObject = {
transformer: TransformerFunction;
cache?: boolean | TransformerCacheObject | undefined;
};
type Transform = TransformerFunction | TransformerObject;
type Filter = (filepath: string) => boolean | Promise<boolean>;
type TransformAllFunction = (
data: {
data: Buffer;
sourceFilename: string;
absoluteFilename: string;
}[]
) => string | Buffer | Promise<string> | Promise<Buffer>;
type Info =
| Record<string, any>
| ((item: {
absoluteFilename: string;
sourceFilename: string;
filename: string;
toType: ToType;
}) => Record<string, any>);
type ObjectPattern = {
from: From;
globOptions?: import("globby").Options | undefined;
context?: string | undefined;
to?: To | undefined;
toType?: ToType | undefined;
info?: Info | undefined;
filter?: Filter | undefined;
transform?: Transform | undefined;
transformAll?: TransformAllFunction | undefined;
force?: boolean | undefined;
priority?: number | undefined;
noErrorOnMissing?: boolean | undefined;
};
type Pattern = StringPattern | ObjectPattern;
type AdditionalOptions = {
concurrency?: number | undefined;
};

35
node_modules/copy-webpack-plugin/types/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
export type InputFileSystem = import("webpack").Compilation["inputFileSystem"];
export type Stats = import("fs").Stats;
export type Task<T> = () => Promise<T>;
/** @typedef {import("webpack").Compilation["inputFileSystem"] } InputFileSystem */
/** @typedef {import("fs").Stats } Stats */
/**
* @param {InputFileSystem} inputFileSystem
* @param {string} path
* @return {Promise<undefined | Stats>}
*/
export function stat(
inputFileSystem: InputFileSystem,
path: string
): Promise<undefined | Stats>;
/**
* @param {InputFileSystem} inputFileSystem
* @param {string} path
* @return {Promise<string | Buffer>}
*/
export function readFile(
inputFileSystem: InputFileSystem,
path: string
): Promise<string | Buffer>;
/**
* @template T
* @typedef {() => Promise<T>} Task
*/
/**
* Run tasks with limited concurency.
* @template T
* @param {number} limit - Limit of tasks that run at once.
* @param {Task<T>[]} tasks - List of tasks to run.
* @returns {Promise<T[]>} A promise that fulfills to an array of the results
*/
export function throttleAll<T>(limit: number, tasks: Task<T>[]): Promise<T[]>;