feature: vor und nachteile

This commit is contained in:
Hikyu
2026-05-31 13:54:31 +02:00
parent 552a947a1c
commit e3dad17446
23270 changed files with 3024794 additions and 200 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-PRESENT Anthony Fu<https://github.com/antfu>
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.
+430
View File
@@ -0,0 +1,430 @@
# unplugin-vue-components
[![NPM version](https://img.shields.io/npm/v/unplugin-vue-components?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-vue-components)
On-demand components auto importing for Vue.
###### Features
- 💚 Supports both Vue 2 and Vue 3 out-of-the-box.
- ✨ Supports both components and directives.
- ⚡️ Supports Vite, Webpack, Rspack, Vue CLI, Rollup, esbuild and more, powered by <a href="https://github.com/unjs/unplugin">unplugin</a>.
- 🏝 Tree-shakable, only registers the components you use.
- 🪐 Folder names as namespaces.
- 🦾 Full TypeScript support.
- 🌈 [Built-in resolvers](#importing-from-ui-libraries) for popular UI libraries.
- 😃 Works perfectly with [unplugin-icons](https://github.com/antfu/unplugin-icons).
<br>
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
<br>
## Installation
```bash
npm i unplugin-vue-components -D
```
> **`vite-plugin-components` has been renamed to `unplugin-vue-components`**, see the [migration guide](#migrate-from-vite-plugin-components).
<details>
<summary>Vite</summary><br>
```ts
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Components({ /* options */ }),
],
})
```
<br></details>
<details>
<summary>Rollup</summary><br>
```ts
// rollup.config.js
import Components from 'unplugin-vue-components/rollup'
export default {
plugins: [
Components({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Webpack</summary><br>
```ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Rspack</summary><br>
```ts
// rspack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/rspack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Nuxt</summary><br>
You might not need this plugin for Nuxt. Use [`@nuxt/components`](https://github.com/nuxt/components) instead.
<br></details>
<details>
<summary>Vue CLI</summary><br>
```ts
// vue.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack').default({ /* options */ }),
],
}
```
You can also rename the Vue configuration file to `vue.config.mjs` and use static import syntax (you should use latest `@vue/cli-service ^5.0.8`):
```ts
// vue.config.mjs
import Components from 'unplugin-vue-components/webpack'
export default {
configureWebpack: {
plugins: [
Components({ /* options */ }),
],
},
}
```
<br></details>
<details>
<summary>esbuild</summary><br>
```ts
// esbuild.config.js
import { build } from 'esbuild'
import Components from 'unplugin-vue-components/esbuild'
build({
/* ... */
plugins: [
Components({
/* options */
}),
],
})
```
<br></details>
## Usage
Use components in templates as you would usually do, it will import components on demand, and there is no `import` and `component registration` required anymore! If you register the parent component asynchronously (or lazy route), the auto-imported components will be code-split along with their parent.
It will automatically turn this
```html
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
```
into this
```html
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
import HelloWorld from './src/components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld,
},
}
</script>
```
> **Note**
> By default this plugin will import components in the `src/components` path. You can customize it using the `dirs` option.
## TypeScript
To get TypeScript support for auto-imported components, there is [a PR](https://github.com/vuejs/core/pull/3399) to Vue 3 extending the interface of global components. Currently, [Volar](https://github.com/johnsoncodehk/volar) has supported this usage already. If you are using Volar, you can change the config as following to get the support.
```ts
Components({
dts: true, // enabled by default if `typescript` is installed
})
```
Once the setup is done, a `components.d.ts` will be generated and updates automatically with the type definitions. Feel free to commit it into git or not as you want.
> **Make sure you also add `components.d.ts` to your `tsconfig.json` under `include`.**
## Importing from UI Libraries
We have several built-in resolvers for popular UI libraries like **Vuetify**, **Ant Design Vue**, and **Element Plus**, where you can enable them by:
Supported Resolvers:
- [Ant Design Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/antdv.ts)
- [Arco Design Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/arco.ts)
- [BootstrapVue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/bootstrap-vue.ts)
- [Element Plus](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/element-plus.ts)
- [Element UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/element-ui.ts)
- [Headless UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/headless-ui.ts)
- [IDux](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/idux.ts)
- [Inkline](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/inkline.ts)
- [Ionic](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/ionic.ts)
- [Naive UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/naive-ui.ts)
- [Prime Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/prime-vue.ts)
- [Quasar](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/quasar.ts)
- [TDesign](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/tdesign.ts)
- [Vant](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vant.ts)
- [`@vant/auto-import-resolver`](https://github.com/youzan/vant/blob/main/packages/vant-auto-import-resolver/README.md) - Vant's own auto-import resolver
- [Varlet UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/varlet-ui.ts)
- [`@varlet/import-resolver`](https://github.com/varletjs/varlet/blob/dev/packages/varlet-import-resolver/README.md) - Varlet's own auto-import resolver
- [VEUI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/veui.ts)
- [View UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/view-ui.ts)
- [Vuetify](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vuetify.ts) &mdash; Prefer first-party plugins when possible: [v3 + vite](https://www.npmjs.com/package/vite-plugin-vuetify), [v3 + webpack](https://www.npmjs.com/package/webpack-plugin-vuetify), [v2 + webpack](https://npmjs.com/package/vuetify-loader)
- [VueUse Components](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vueuse.ts)
- [VueUse Directives](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vueuse-directive.ts)
- [Dev UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/devui.ts)
```ts
import {
AntDesignVueResolver,
ElementPlusResolver,
VantResolver,
} from 'unplugin-vue-components/resolvers'
// vite.config.js
import Components from 'unplugin-vue-components/vite'
// your plugin installation
Components({
resolvers: [
AntDesignVueResolver(),
ElementPlusResolver(),
VantResolver(),
],
})
```
You can also write your own resolver quickly:
```ts
Components({
resolvers: [
// example of importing Vant
(componentName) => {
// where `componentName` is always CapitalCase
if (componentName.startsWith('Van'))
return { name: componentName.slice(3), from: 'vant' }
},
],
})
```
> [We no longer accept new resolvers](./src/core/resolvers/_READ_BEFORE_CONTRIBUTE.md).
## Types for global registered components
Some libraries might register some global components for you to use anywhere (e.g. Vue Router provides `<RouterLink>` and `<RouterView>`). Since they are global available, there is no need for this plugin to import them. However, those are commonly not TypeScript friendly, and you might need to register their types manually.
Thus `unplugin-vue-components` provided a way to only register types for global components.
```ts
Components({
dts: true,
types: [{
from: 'vue-router',
names: ['RouterLink', 'RouterView'],
}],
})
```
So the `RouterLink` and `RouterView` will be presented in `components.d.ts`.
By default, `unplugin-vue-components` detects supported libraries automatically (e.g. `vue-router`) when they are installed in the workspace. If you want to disable it completely, you can pass an empty array to it:
```ts
Components({
// Disable type only registration
types: [],
})
```
## Migrate from `vite-plugin-components`
`package.json`
```diff
{
"devDependencies": {
- "vite-plugin-components": "*",
+ "unplugin-vue-components": "^0.14.0",
}
}
```
`vite.config.js`
```diff
- import Components, { ElementPlusResolver } from 'vite-plugin-components'
+ import Components from 'unplugin-vue-components/vite'
+ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default {
plugins: [
/* ... */
Components({
/* ... */
// `customComponentsResolvers` has renamed to `resolver`
- customComponentsResolvers: [
+ resolvers: [
ElementPlusResolver(),
],
// `globalComponentsDeclaration` has renamed to `dts`
- globalComponentsDeclaration: true,
+ dts: true,
// `customLoaderMatcher` is depreacted, use `include` instead
- customLoaderMatcher: id => id.endsWith('.md'),
+ include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
}),
],
}
```
## Configuration
The following show the default values of the configuration
```ts
Components({
// relative paths to the directory to search for components.
dirs: ['src/components'],
// valid file extensions for components.
extensions: ['vue'],
// Glob patterns to match file names to be detected as components.
// When specified, the `dirs`, `extensions`, and `directoryAsNamespace` options will be ignored.
// If you want to exclude components being registered, use negative globs with leading `!`.
globs: ['src/components/*.{vue}'],
// search for subdirectories
deep: true,
// resolvers for custom components
resolvers: [],
// generate `components.d.ts` global declarations,
// also accepts a path for custom filename
// default: `true` if package typescript is installed
dts: false,
// Allow subdirectories as namespace prefix for components.
directoryAsNamespace: false,
// Collapse same prefixes (camel-sensitive) of folders and components
// to prevent duplication inside namespaced component name.
// works when `directoryAsNamespace: true`
collapseSamePrefixes: false,
// Subdirectory paths for ignoring namespace prefixes.
// works when `directoryAsNamespace: true`
globalNamespaces: [],
// auto import for directives
// default: `true` for Vue 3, `false` for Vue 2
// Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
// To install Babel, run: `npm install -D @babel/parser`
directives: true,
// Transform path before resolving
importPathTransform: v => v,
// Allow for components to override other components with the same name
allowOverrides: false,
// Filters for transforming targets (components to insert the auto import)
// Note these are NOT about including/excluding components registered - use `globs` or `excludeNames` for that
include: [/\.vue$/, /\.vue\?vue/],
exclude: [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],
// Filters for component names that will not be imported
// Use for globally imported async components or other conflicts that the plugin cannot detect
excludeNames: [/^Async.+/],
// Vue version of project. It will detect automatically if not specified.
// Acceptable value: 2 | 2.7 | 3
version: 2.7,
// Only provide types of components in library (registered globally)
types: []
})
```
## Example
[Vitesse](https://github.com/antfu/vitesse) starter template.
## Thanks
Thanks to [@brattonross](https://github.com/brattonross), this project is heavily inspired by [vite-plugin-voie](https://github.com/vamplate/vite-plugin-voie).
## License
[MIT](./LICENSE) License © 2020-PRESENT [Anthony Fu](https://github.com/antfu)
@@ -0,0 +1,10 @@
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
export {
__require
};
@@ -0,0 +1,753 @@
import {
DIRECTIVE_IMPORT_PREFIX,
DISABLE_COMMENT,
getNameFromFilePath,
getTransformedPath,
isExclude,
matchGlobs,
normalizeComponentInfo,
parseId,
pascalCase,
resolveAlias,
shouldTransform,
stringifyComponentImport
} from "./chunk-X53Y3GEO.js";
// src/core/unplugin.ts
import { existsSync as existsSync2 } from "node:fs";
import process2 from "node:process";
import { createFilter } from "@rollup/pluginutils";
import chokidar from "chokidar";
import { createUnplugin } from "unplugin";
// src/core/context.ts
import { relative as relative2 } from "node:path";
import process from "node:process";
import { slash as slash3, throttle, toArray as toArray2 } from "@antfu/utils";
import Debug5 from "debug";
// src/core/declaration.ts
import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile as writeFile_ } from "node:fs/promises";
import { dirname, isAbsolute, relative } from "node:path";
import { notNullish as notNullish2, slash } from "@antfu/utils";
// src/core/type-imports/detect.ts
import { notNullish } from "@antfu/utils";
import { isPackageExists } from "local-pkg";
// src/core/type-imports/index.ts
var TypeImportPresets = [
{
from: "vue-router",
names: [
"RouterView",
"RouterLink"
]
},
{
from: "vue-starport",
names: [
"Starport",
"StarportCarrier"
]
}
];
// src/core/type-imports/detect.ts
function detectTypeImports() {
return TypeImportPresets.map((i) => isPackageExists(i.from) ? i : void 0).filter(notNullish);
}
function resolveTypeImports(imports) {
return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
}
// src/core/declaration.ts
var multilineCommentsRE = /\/\*.*?\*\//gs;
var singlelineCommentsRE = /\/\/.*$/gm;
function extractImports(code) {
return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
}
function parseDeclaration(code) {
if (!code)
return;
code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const imports = {
component: {},
directive: {}
};
const componentDeclaration = /export\s+interface\s+GlobalComponents\s*\{.*?\}/s.exec(code)?.[0];
if (componentDeclaration)
imports.component = extractImports(componentDeclaration);
const directiveDeclaration = /export\s+interface\s+ComponentCustomProperties\s*\{.*?\}/s.exec(code)?.[0];
if (directiveDeclaration)
imports.directive = extractImports(directiveDeclaration);
return imports;
}
function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
if (!name)
return void 0;
path = getTransformedPath(path, importPathTransform);
const related = isAbsolute(path) ? `./${relative(dirname(filepath), path)}` : path;
const entry = `typeof import('${slash(related)}')['${importName || "default"}']`;
return [name, entry];
}
function stringifyComponentsInfo(filepath, components, importPathTransform) {
return Object.fromEntries(
components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(notNullish2)
);
}
function getDeclarationImports(ctx, filepath) {
const component = stringifyComponentsInfo(filepath, [
...Object.values({
...ctx.componentNameMap,
...ctx.componentCustomMap
}),
...resolveTypeImports(ctx.options.types)
], ctx.options.importPathTransform);
const directive = stringifyComponentsInfo(
filepath,
Object.values(ctx.directiveCustomMap),
ctx.options.importPathTransform
);
if (Object.keys(component).length + Object.keys(directive).length === 0)
return;
return { component, directive };
}
function stringifyDeclarationImports(imports) {
return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`;
return `${name}: ${v}`;
});
}
function getDeclaration(ctx, filepath, originalImports) {
const imports = getDeclarationImports(ctx, filepath);
if (!imports)
return;
const declarations = {
component: stringifyDeclarationImports({ ...originalImports?.component, ...imports.component }),
directive: stringifyDeclarationImports({ ...originalImports?.directive, ...imports.directive })
};
let code = `/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
/* prettier-ignore */
declare module 'vue' {`;
if (Object.keys(declarations.component).length > 0) {
code += `
export interface GlobalComponents {
${declarations.component.join("\n ")}
}`;
}
if (Object.keys(declarations.directive).length > 0) {
code += `
export interface ComponentCustomProperties {
${declarations.directive.join("\n ")}
}`;
}
code += "\n}\n";
return code;
}
async function writeFile(filePath, content) {
await mkdir(dirname(filePath), { recursive: true });
return await writeFile_(filePath, content, "utf-8");
}
async function writeDeclaration(ctx, filepath, removeUnused = false) {
const originalContent = existsSync(filepath) ? await readFile(filepath, "utf-8") : "";
const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
const code = getDeclaration(ctx, filepath, originalImports);
if (!code)
return;
if (code !== originalContent)
await writeFile(filepath, code);
}
// src/core/fs/glob.ts
import Debug from "debug";
import fg from "fast-glob";
var debug = Debug("unplugin-vue-components:glob");
function searchComponents(ctx) {
debug(`started with: [${ctx.options.globs.join(", ")}]`);
const root = ctx.root;
const files = fg.sync(ctx.options.globs, {
ignore: ["node_modules"],
onlyFiles: true,
cwd: root,
absolute: true
});
if (!files.length && !ctx.options.resolvers?.length)
console.warn("[unplugin-vue-components] no components found");
debug(`${files.length} components found.`);
ctx.addComponents(files);
}
// src/core/options.ts
import { join, resolve } from "node:path";
import { slash as slash2, toArray } from "@antfu/utils";
import { getPackageInfoSync, isPackageExists as isPackageExists2 } from "local-pkg";
var defaultOptions = {
dirs: "src/components",
extensions: "vue",
deep: true,
dts: isPackageExists2("typescript"),
directoryAsNamespace: false,
collapseSamePrefixes: false,
globalNamespaces: [],
resolvers: [],
importPathTransform: (v) => v,
allowOverrides: false
};
function normalizeResolvers(resolvers) {
return toArray(resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
}
function resolveGlobsExclude(root, glob) {
const excludeReg = /^!/;
return `${excludeReg.test(glob) ? "!" : ""}${resolve(root, glob.replace(excludeReg, ""))}`;
}
function resolveOptions(options, root) {
const resolved = Object.assign({}, defaultOptions, options);
resolved.resolvers = normalizeResolvers(resolved.resolvers);
resolved.extensions = toArray(resolved.extensions);
if (resolved.globs) {
resolved.globs = toArray(resolved.globs).map((glob) => slash2(resolveGlobsExclude(root, glob)));
resolved.resolvedDirs = [];
} else {
const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
resolved.dirs = toArray(resolved.dirs);
resolved.resolvedDirs = resolved.dirs.map((i) => slash2(resolveGlobsExclude(root, i)));
resolved.globs = resolved.resolvedDirs.map(
(i) => resolved.deep ? slash2(join(i, `**/*.${extsGlob}`)) : slash2(join(i, `*.${extsGlob}`))
);
if (!resolved.extensions.length)
throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
}
resolved.dts = !resolved.dts ? false : resolve(
root,
typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
);
if (!resolved.types && resolved.dts)
resolved.types = detectTypeImports();
resolved.types = resolved.types || [];
resolved.root = root;
resolved.version = resolved.version ?? getVueVersion(root);
if (resolved.version < 2 || resolved.version >= 4)
throw new Error(`[unplugin-vue-components] unsupported version: ${resolved.version}`);
resolved.transformer = options.transformer || `vue${Math.trunc(resolved.version)}`;
resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : resolved.version >= 3;
return resolved;
}
function getVueVersion(root) {
const raw = getPackageInfoSync("vue", { paths: [join(root, "/")] })?.version || "3";
const version = +raw.split(".").slice(0, 2).join(".");
if (version === 2.7)
return 2.7;
else if (version < 2.7)
return 2;
return 3;
}
// src/core/transformer.ts
import Debug4 from "debug";
import MagicString from "magic-string";
// src/core/transforms/component.ts
import Debug2 from "debug";
var debug2 = Debug2("unplugin-vue-components:transform:component");
function resolveVue2(code, s) {
const results = [];
for (const match of code.matchAll(/\b(_c|h)\(\s*['"](.+?)["']([,)])/g)) {
const [full, renderFunctionName, matchedName, append] = match;
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + full.length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
});
}
}
return results;
}
function resolveVue3(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveComponent\d*\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
async function transformComponent(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
for (const { rawName, replace } of results) {
debug2(`| ${rawName}`);
const name = pascalCase(rawName);
ctx.updateUsageMap(sfcPath, [name]);
const component = await ctx.findComponent(name, "component", [sfcPath]);
if (component) {
const varName = `__unplugin_components_${no}`;
s.prepend(`${stringifyComponentImport({ ...component, as: varName }, ctx)};
`);
no += 1;
replace(varName);
}
}
debug2(`^ (${no})`);
}
// src/core/transforms/directive/index.ts
import Debug3 from "debug";
// src/core/transforms/directive/vue2.ts
import { importModule, isPackageExists as isPackageExists3 } from "local-pkg";
function getRenderFnStart(program) {
const renderFn = program.body.find(
(node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
);
const start = renderFn?.declarations[0].init?.body?.start;
if (start === null || start === void 0)
throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
return start + 1;
}
async function resolveVue22(code, s) {
if (!isPackageExists3("@babel/parser"))
throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
const { parse } = await importModule("@babel/parser");
const { program } = parse(code, {
sourceType: "module"
});
const nodes = [];
const { walk } = await import("./src-QRDHCXVL.js");
walk(program, {
enter(node) {
if (node.type === "CallExpression")
nodes.push(node);
}
});
if (nodes.length === 0)
return [];
let _renderStart;
const getRenderStart = () => {
if (_renderStart !== void 0)
return _renderStart;
return _renderStart = getRenderFnStart(program);
};
const results = [];
for (const node of nodes) {
const { callee, arguments: args } = node;
if (callee.type !== "Identifier" || callee.name !== "_c" || args[1]?.type !== "ObjectExpression")
continue;
const directives = args[1].properties.find(
(property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
)?.value;
if (!directives || directives.type !== "ArrayExpression")
continue;
for (const directive of directives.elements) {
if (directive?.type !== "ObjectExpression")
continue;
const nameNode = directive.properties.find(
(p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
)?.value;
if (nameNode?.type !== "StringLiteral")
continue;
const name = nameNode.value;
if (!name || name.startsWith("_"))
continue;
results.push({
rawName: name,
replace: (resolved) => {
s.prependLeft(getRenderStart(), `
this.$options.directives["${name}"] = ${resolved};`);
}
});
}
}
return results;
}
// src/core/transforms/directive/vue3.ts
function resolveVue32(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
// src/core/transforms/directive/index.ts
var debug3 = Debug3("unplugin-vue-components:transform:directive");
async function transformDirective(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
for (const { rawName, replace } of results) {
debug3(`| ${rawName}`);
const name = `${DIRECTIVE_IMPORT_PREFIX}${pascalCase(rawName)}`;
ctx.updateUsageMap(sfcPath, [name]);
const directive = await ctx.findComponent(name, "directive", [sfcPath]);
if (!directive)
continue;
const varName = `__unplugin_directives_${no}`;
s.prepend(`${stringifyComponentImport({ ...directive, as: varName }, ctx)};
`);
no += 1;
replace(varName);
}
debug3(`^ (${no})`);
}
// src/core/transformer.ts
var debug4 = Debug4("unplugin-vue-components:transformer");
function transformer(ctx, transformer2) {
return async (code, id, path) => {
ctx.searchGlob();
const sfcPath = ctx.normalizePath(path);
debug4(sfcPath);
const s = new MagicString(code);
await transformComponent(code, transformer2, s, ctx, sfcPath);
if (ctx.options.directives)
await transformDirective(code, transformer2, s, ctx, sfcPath);
s.prepend(DISABLE_COMMENT);
const result = { code: s.toString() };
if (ctx.sourcemap)
result.map = s.generateMap({ source: id, includeContent: true, hires: "boundary" });
return result;
};
}
// src/core/context.ts
var debug5 = {
components: Debug5("unplugin-vue-components:context:components"),
search: Debug5("unplugin-vue-components:context:search"),
hmr: Debug5("unplugin-vue-components:context:hmr"),
declaration: Debug5("unplugin-vue-components:declaration"),
env: Debug5("unplugin-vue-components:env")
};
var Context = class {
constructor(rawOptions) {
this.rawOptions = rawOptions;
this.options = resolveOptions(rawOptions, this.root);
this.generateDeclaration = throttle(500, this._generateDeclaration.bind(this), { noLeading: false });
this.setTransformer(this.options.transformer);
}
options;
transformer = void 0;
_componentPaths = /* @__PURE__ */ new Set();
_componentNameMap = {};
_componentUsageMap = {};
_componentCustomMap = {};
_directiveCustomMap = {};
_server;
root = process.cwd();
sourcemap = true;
alias = {};
setRoot(root) {
if (this.root === root)
return;
debug5.env("root", root);
this.root = root;
this.options = resolveOptions(this.rawOptions, this.root);
}
setTransformer(name) {
debug5.env("transformer", name);
this.transformer = transformer(this, name || "vue3");
}
transform(code, id) {
const { path, query } = parseId(id);
return this.transformer(code, id, path, query);
}
setupViteServer(server) {
if (this._server === server)
return;
this._server = server;
this.setupWatcher(server.watcher);
}
setupWatcher(watcher) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.removeComponents(path);
this.onUpdate(path);
});
watcher.on("add", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.addComponents(path);
this.onUpdate(path);
});
}
/**
* start watcher for webpack
*/
setupWatcherWebpack(watcher, emitUpdate) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.removeComponents(path);
emitUpdate(path, "unlink");
});
watcher.on("add", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.addComponents(path);
emitUpdate(path, "add");
});
}
/**
* Record the usage of components
* @param path
* @param paths paths of used components
*/
updateUsageMap(path, paths) {
if (!this._componentUsageMap[path])
this._componentUsageMap[path] = /* @__PURE__ */ new Set();
paths.forEach((p) => {
this._componentUsageMap[path].add(p);
});
}
addComponents(paths) {
debug5.components("add", paths);
const size = this._componentPaths.size;
toArray2(paths).forEach((p) => this._componentPaths.add(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
addCustomComponents(info) {
if (info.as)
this._componentCustomMap[info.as] = info;
}
addCustomDirectives(info) {
if (info.as)
this._directiveCustomMap[info.as] = info;
}
removeComponents(paths) {
debug5.components("remove", paths);
const size = this._componentPaths.size;
toArray2(paths).forEach((p) => this._componentPaths.delete(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
onUpdate(path) {
this.generateDeclaration();
if (!this._server)
return;
const payload = {
type: "update",
updates: []
};
const timestamp = +/* @__PURE__ */ new Date();
const name = pascalCase(getNameFromFilePath(path, this.options));
Object.entries(this._componentUsageMap).forEach(([key, values]) => {
if (values.has(name)) {
const r = `/${slash3(relative2(this.root, key))}`;
payload.updates.push({
acceptedPath: r,
path: r,
timestamp,
type: "js-update"
});
}
});
if (payload.updates.length)
this._server.ws.send(payload);
}
updateComponentNameMap() {
this._componentNameMap = {};
Array.from(this._componentPaths).forEach((path) => {
const name = pascalCase(getNameFromFilePath(path, this.options));
if (isExclude(name, this.options.excludeNames)) {
debug5.components("exclude", name);
return;
}
if (this._componentNameMap[name] && !this.options.allowOverrides) {
console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
return;
}
this._componentNameMap[name] = {
as: name,
from: path
};
});
}
async findComponent(name, type, excludePaths = []) {
let info = this._componentNameMap[name];
if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
return info;
for (const resolver of this.options.resolvers) {
if (resolver.type !== type)
continue;
const result = await resolver.resolve(type === "directive" ? name.slice(DIRECTIVE_IMPORT_PREFIX.length) : name);
if (!result)
continue;
if (typeof result === "string") {
info = {
as: name,
from: result
};
} else {
info = {
as: name,
...normalizeComponentInfo(result)
};
}
if (type === "component")
this.addCustomComponents(info);
else if (type === "directive")
this.addCustomDirectives(info);
return info;
}
return void 0;
}
normalizePath(path) {
return resolveAlias(path, this.viteConfig?.resolve?.alias || this.viteConfig?.alias || []);
}
relative(path) {
if (path.startsWith("/") && !path.startsWith(this.root))
return slash3(path.slice(1));
return slash3(relative2(this.root, path));
}
_searched = false;
/**
* This search for components in with the given options.
* Will be called multiple times to ensure file loaded,
* should normally run only once.
*/
searchGlob() {
if (this._searched)
return;
searchComponents(this);
debug5.search(this._componentNameMap);
this._searched = true;
}
_generateDeclaration(removeUnused = !this._server) {
if (!this.options.dts)
return;
debug5.declaration("generating");
return writeDeclaration(this, this.options.dts, removeUnused);
}
generateDeclaration;
get componentNameMap() {
return this._componentNameMap;
}
get componentCustomMap() {
return this._componentCustomMap;
}
get directiveCustomMap() {
return this._directiveCustomMap;
}
};
// src/core/unplugin.ts
var PLUGIN_NAME = "unplugin:webpack";
var unplugin_default = createUnplugin((options = {}) => {
const filter = createFilter(
options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
);
const ctx = new Context(options);
const api = {
async findComponent(name, filename) {
return await ctx.findComponent(name, "component", filename ? [filename] : []);
},
stringifyImport(info) {
return stringifyComponentImport(info, ctx);
}
};
return {
name: "unplugin-vue-components",
enforce: "post",
api,
transformInclude(id) {
return filter(id);
},
async transform(code, id) {
if (!shouldTransform(code))
return null;
try {
const result = await ctx.transform(code, id);
ctx.generateDeclaration();
return result;
} catch (e) {
this.error(e);
}
},
vite: {
configResolved(config) {
ctx.setRoot(config.root);
ctx.sourcemap = true;
if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
ctx.setTransformer("vue2");
if (ctx.options.dts) {
ctx.searchGlob();
if (!existsSync2(ctx.options.dts))
ctx.generateDeclaration();
}
if (config.build.watch && config.command === "build")
ctx.setupWatcher(chokidar.watch(ctx.options.globs));
},
configureServer(server) {
ctx.setupViteServer(server);
}
},
webpack(compiler) {
let watcher;
let fileDepQueue = [];
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
if (!watcher && compiler.watching) {
watcher = compiler.watching;
ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path, type) => {
fileDepQueue.push({ path, type });
process2.nextTick(() => {
watcher.invalidate();
});
});
}
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (fileDepQueue.length) {
fileDepQueue.forEach(({ path, type }) => {
if (type === "unlink")
compilation.fileDependencies.delete(path);
else
compilation.fileDependencies.add(path);
});
fileDepQueue = [];
}
});
}
};
});
export {
unplugin_default
};
@@ -0,0 +1,207 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/utils.ts
var _path = require('path');
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _utils = require('@antfu/utils');
var _localpkg = require('local-pkg');
var _minimatch = require('minimatch');
// src/core/constants.ts
var DISABLE_COMMENT = "/* unplugin-vue-components disabled */";
var DIRECTIVE_IMPORT_PREFIX = "v";
// src/core/utils.ts
var isSSR = Boolean(_process2.default.env.SSR || _process2.default.env.SSG || _process2.default.env.VITE_SSR || _process2.default.env.VITE_SSG);
function pascalCase(str) {
return capitalize(camelCase(str));
}
function camelCase(str) {
return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
}
function kebabCase(key) {
const result = key.replace(/([A-Z])/g, " $1").trim();
return result.split(" ").join("-").toLowerCase();
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function parseId(id) {
const index = id.indexOf("?");
if (index < 0) {
return { path: id, query: {} };
} else {
const query = Object.fromEntries(new URLSearchParams(id.slice(index)));
return {
path: id.slice(0, index),
query
};
}
}
function isEmpty(value) {
if (!value || value === null || value === void 0 || Array.isArray(value) && Object.keys(value).length <= 0)
return true;
else
return false;
}
function matchGlobs(filepath, globs) {
for (const glob of globs) {
const isNegated = glob.startsWith("!");
const match = _minimatch.minimatch.call(void 0, _utils.slash.call(void 0, filepath), isNegated ? glob.slice(1) : glob);
if (match)
return !isNegated;
}
return false;
}
function getTransformedPath(path, importPathTransform) {
if (importPathTransform) {
const result = importPathTransform(path);
if (result != null)
path = result;
}
return path;
}
function stringifyImport(info) {
if (typeof info === "string")
return `import '${info}'`;
if (!info.as)
return `import '${info.from}'`;
else if (info.name)
return `import { ${info.name} as ${info.as} } from '${info.from}'`;
else
return `import ${info.as} from '${info.from}'`;
}
function normalizeComponentInfo(info) {
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return info;
}
function stringifyComponentImport({ as: name, from: path, name: importName, sideEffects }, ctx) {
path = getTransformedPath(path, ctx.options.importPathTransform);
const imports = [
stringifyImport({ as: name, from: path, name: importName })
];
if (sideEffects)
_utils.toArray.call(void 0, sideEffects).forEach((i) => imports.push(stringifyImport(i)));
return imports.join(";");
}
function getNameFromFilePath(filePath, options) {
const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options;
const parsedFilePath = _path.parse.call(void 0, _utils.slash.call(void 0, filePath));
let strippedPath = "";
for (const dir of resolvedDirs) {
if (parsedFilePath.dir.startsWith(dir)) {
strippedPath = parsedFilePath.dir.slice(dir.length);
break;
}
}
let folders = strippedPath.slice(1).split("/").filter(Boolean);
let filename = parsedFilePath.name;
if (filename === "index" && !directoryAsNamespace) {
if (isEmpty(folders))
folders = parsedFilePath.dir.slice(root.length + 1).split("/").filter(Boolean);
filename = `${folders.slice(-1)[0]}`;
return filename;
}
if (directoryAsNamespace) {
if (globalNamespaces.some((name) => folders.includes(name)))
folders = folders.filter((f) => !globalNamespaces.includes(f));
folders = folders.map((f) => f.replace(/[^a-z0-9\-]/gi, ""));
if (filename.toLowerCase() === "index")
filename = "";
if (!isEmpty(folders)) {
let namespaced = [...folders, filename];
if (collapseSamePrefixes) {
const collapsed = [];
for (const fileOrFolderName of namespaced) {
let cumulativePrefix = "";
let didCollapse = false;
const pascalCasedName = pascalCase(fileOrFolderName);
for (const parentFolder of [...collapsed].reverse()) {
cumulativePrefix = `${parentFolder}${cumulativePrefix}`;
if (pascalCasedName.startsWith(cumulativePrefix)) {
const collapseSamePrefix = pascalCasedName.slice(cumulativePrefix.length);
collapsed.push(collapseSamePrefix);
didCollapse = true;
break;
}
}
if (!didCollapse)
collapsed.push(pascalCasedName);
}
namespaced = collapsed;
}
filename = namespaced.filter(Boolean).join("-");
}
return filename;
}
return filename;
}
function resolveAlias(filepath, alias) {
const result = filepath;
if (Array.isArray(alias)) {
for (const { find, replacement } of alias)
result.replace(find, replacement);
}
return result;
}
async function getPkgVersion(pkgName, defaultVersion) {
try {
const isExist = _localpkg.isPackageExists.call(void 0, pkgName);
if (isExist) {
const pkg = await _localpkg.getPackageInfo.call(void 0, pkgName);
return _nullishCoalesce(_optionalChain([pkg, 'optionalAccess', _2 => _2.version]), () => ( defaultVersion));
} else {
return defaultVersion;
}
} catch (err) {
console.error(err);
return defaultVersion;
}
}
function shouldTransform(code) {
if (code.includes(DISABLE_COMMENT))
return false;
return true;
}
function isExclude(name, exclude) {
if (!exclude)
return false;
if (typeof exclude === "string")
return name === exclude;
if (exclude instanceof RegExp)
return !!name.match(exclude);
if (Array.isArray(exclude)) {
for (const item of exclude) {
if (name === item || name.match(item))
return true;
}
}
return false;
}
exports.DISABLE_COMMENT = DISABLE_COMMENT; exports.DIRECTIVE_IMPORT_PREFIX = DIRECTIVE_IMPORT_PREFIX; exports.isSSR = isSSR; exports.pascalCase = pascalCase; exports.camelCase = camelCase; exports.kebabCase = kebabCase; exports.parseId = parseId; exports.matchGlobs = matchGlobs; exports.getTransformedPath = getTransformedPath; exports.normalizeComponentInfo = normalizeComponentInfo; exports.stringifyComponentImport = stringifyComponentImport; exports.getNameFromFilePath = getNameFromFilePath; exports.resolveAlias = resolveAlias; exports.getPkgVersion = getPkgVersion; exports.shouldTransform = shouldTransform; exports.isExclude = isExclude;
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
exports.__require = __require;
@@ -0,0 +1,753 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
var _chunkMU27IQTBcjs = require('./chunk-MU27IQTB.cjs');
// src/core/unplugin.ts
var _fs = require('fs');
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _pluginutils = require('@rollup/pluginutils');
var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
var _unplugin = require('unplugin');
// src/core/context.ts
var _path = require('path');
var _utils = require('@antfu/utils');
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
// src/core/declaration.ts
var _promises = require('fs/promises');
// src/core/type-imports/detect.ts
var _localpkg = require('local-pkg');
// src/core/type-imports/index.ts
var TypeImportPresets = [
{
from: "vue-router",
names: [
"RouterView",
"RouterLink"
]
},
{
from: "vue-starport",
names: [
"Starport",
"StarportCarrier"
]
}
];
// src/core/type-imports/detect.ts
function detectTypeImports() {
return TypeImportPresets.map((i) => _localpkg.isPackageExists.call(void 0, i.from) ? i : void 0).filter(_utils.notNullish);
}
function resolveTypeImports(imports) {
return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
}
// src/core/declaration.ts
var multilineCommentsRE = /\/\*.*?\*\//gs;
var singlelineCommentsRE = /\/\/.*$/gm;
function extractImports(code) {
return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
}
function parseDeclaration(code) {
if (!code)
return;
code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const imports = {
component: {},
directive: {}
};
const componentDeclaration = _optionalChain([/export\s+interface\s+GlobalComponents\s*\{.*?\}/s, 'access', _ => _.exec, 'call', _2 => _2(code), 'optionalAccess', _3 => _3[0]]);
if (componentDeclaration)
imports.component = extractImports(componentDeclaration);
const directiveDeclaration = _optionalChain([/export\s+interface\s+ComponentCustomProperties\s*\{.*?\}/s, 'access', _4 => _4.exec, 'call', _5 => _5(code), 'optionalAccess', _6 => _6[0]]);
if (directiveDeclaration)
imports.directive = extractImports(directiveDeclaration);
return imports;
}
function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
if (!name)
return void 0;
path = _chunkMU27IQTBcjs.getTransformedPath.call(void 0, path, importPathTransform);
const related = _path.isAbsolute.call(void 0, path) ? `./${_path.relative.call(void 0, _path.dirname.call(void 0, filepath), path)}` : path;
const entry = `typeof import('${_utils.slash.call(void 0, related)}')['${importName || "default"}']`;
return [name, entry];
}
function stringifyComponentsInfo(filepath, components, importPathTransform) {
return Object.fromEntries(
components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(_utils.notNullish)
);
}
function getDeclarationImports(ctx, filepath) {
const component = stringifyComponentsInfo(filepath, [
...Object.values({
...ctx.componentNameMap,
...ctx.componentCustomMap
}),
...resolveTypeImports(ctx.options.types)
], ctx.options.importPathTransform);
const directive = stringifyComponentsInfo(
filepath,
Object.values(ctx.directiveCustomMap),
ctx.options.importPathTransform
);
if (Object.keys(component).length + Object.keys(directive).length === 0)
return;
return { component, directive };
}
function stringifyDeclarationImports(imports) {
return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`;
return `${name}: ${v}`;
});
}
function getDeclaration(ctx, filepath, originalImports) {
const imports = getDeclarationImports(ctx, filepath);
if (!imports)
return;
const declarations = {
component: stringifyDeclarationImports({ ..._optionalChain([originalImports, 'optionalAccess', _7 => _7.component]), ...imports.component }),
directive: stringifyDeclarationImports({ ..._optionalChain([originalImports, 'optionalAccess', _8 => _8.directive]), ...imports.directive })
};
let code = `/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
/* prettier-ignore */
declare module 'vue' {`;
if (Object.keys(declarations.component).length > 0) {
code += `
export interface GlobalComponents {
${declarations.component.join("\n ")}
}`;
}
if (Object.keys(declarations.directive).length > 0) {
code += `
export interface ComponentCustomProperties {
${declarations.directive.join("\n ")}
}`;
}
code += "\n}\n";
return code;
}
async function writeFile(filePath, content) {
await _promises.mkdir.call(void 0, _path.dirname.call(void 0, filePath), { recursive: true });
return await _promises.writeFile.call(void 0, filePath, content, "utf-8");
}
async function writeDeclaration(ctx, filepath, removeUnused = false) {
const originalContent = _fs.existsSync.call(void 0, filepath) ? await _promises.readFile.call(void 0, filepath, "utf-8") : "";
const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
const code = getDeclaration(ctx, filepath, originalImports);
if (!code)
return;
if (code !== originalContent)
await writeFile(filepath, code);
}
// src/core/fs/glob.ts
var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
var debug = _debug2.default.call(void 0, "unplugin-vue-components:glob");
function searchComponents(ctx) {
debug(`started with: [${ctx.options.globs.join(", ")}]`);
const root = ctx.root;
const files = _fastglob2.default.sync(ctx.options.globs, {
ignore: ["node_modules"],
onlyFiles: true,
cwd: root,
absolute: true
});
if (!files.length && !_optionalChain([ctx, 'access', _9 => _9.options, 'access', _10 => _10.resolvers, 'optionalAccess', _11 => _11.length]))
console.warn("[unplugin-vue-components] no components found");
debug(`${files.length} components found.`);
ctx.addComponents(files);
}
// src/core/options.ts
var defaultOptions = {
dirs: "src/components",
extensions: "vue",
deep: true,
dts: _localpkg.isPackageExists.call(void 0, "typescript"),
directoryAsNamespace: false,
collapseSamePrefixes: false,
globalNamespaces: [],
resolvers: [],
importPathTransform: (v) => v,
allowOverrides: false
};
function normalizeResolvers(resolvers) {
return _utils.toArray.call(void 0, resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
}
function resolveGlobsExclude(root, glob) {
const excludeReg = /^!/;
return `${excludeReg.test(glob) ? "!" : ""}${_path.resolve.call(void 0, root, glob.replace(excludeReg, ""))}`;
}
function resolveOptions(options, root) {
const resolved = Object.assign({}, defaultOptions, options);
resolved.resolvers = normalizeResolvers(resolved.resolvers);
resolved.extensions = _utils.toArray.call(void 0, resolved.extensions);
if (resolved.globs) {
resolved.globs = _utils.toArray.call(void 0, resolved.globs).map((glob) => _utils.slash.call(void 0, resolveGlobsExclude(root, glob)));
resolved.resolvedDirs = [];
} else {
const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
resolved.dirs = _utils.toArray.call(void 0, resolved.dirs);
resolved.resolvedDirs = resolved.dirs.map((i) => _utils.slash.call(void 0, resolveGlobsExclude(root, i)));
resolved.globs = resolved.resolvedDirs.map(
(i) => resolved.deep ? _utils.slash.call(void 0, _path.join.call(void 0, i, `**/*.${extsGlob}`)) : _utils.slash.call(void 0, _path.join.call(void 0, i, `*.${extsGlob}`))
);
if (!resolved.extensions.length)
throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
}
resolved.dts = !resolved.dts ? false : _path.resolve.call(void 0,
root,
typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
);
if (!resolved.types && resolved.dts)
resolved.types = detectTypeImports();
resolved.types = resolved.types || [];
resolved.root = root;
resolved.version = _nullishCoalesce(resolved.version, () => ( getVueVersion(root)));
if (resolved.version < 2 || resolved.version >= 4)
throw new Error(`[unplugin-vue-components] unsupported version: ${resolved.version}`);
resolved.transformer = options.transformer || `vue${Math.trunc(resolved.version)}`;
resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : resolved.version >= 3;
return resolved;
}
function getVueVersion(root) {
const raw = _optionalChain([_localpkg.getPackageInfoSync.call(void 0, "vue", { paths: [_path.join.call(void 0, root, "/")] }), 'optionalAccess', _12 => _12.version]) || "3";
const version = +raw.split(".").slice(0, 2).join(".");
if (version === 2.7)
return 2.7;
else if (version < 2.7)
return 2;
return 3;
}
// src/core/transformer.ts
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
// src/core/transforms/component.ts
var debug2 = _debug2.default.call(void 0, "unplugin-vue-components:transform:component");
function resolveVue2(code, s) {
const results = [];
for (const match of code.matchAll(/\b(_c|h)\(\s*['"](.+?)["']([,)])/g)) {
const [full, renderFunctionName, matchedName, append] = match;
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + full.length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
});
}
}
return results;
}
function resolveVue3(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveComponent\d*\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
async function transformComponent(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
for (const { rawName, replace } of results) {
debug2(`| ${rawName}`);
const name = _chunkMU27IQTBcjs.pascalCase.call(void 0, rawName);
ctx.updateUsageMap(sfcPath, [name]);
const component = await ctx.findComponent(name, "component", [sfcPath]);
if (component) {
const varName = `__unplugin_components_${no}`;
s.prepend(`${_chunkMU27IQTBcjs.stringifyComponentImport.call(void 0, { ...component, as: varName }, ctx)};
`);
no += 1;
replace(varName);
}
}
debug2(`^ (${no})`);
}
// src/core/transforms/directive/index.ts
// src/core/transforms/directive/vue2.ts
function getRenderFnStart(program) {
const renderFn = program.body.find(
(node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
);
const start = _optionalChain([renderFn, 'optionalAccess', _13 => _13.declarations, 'access', _14 => _14[0], 'access', _15 => _15.init, 'optionalAccess', _16 => _16.body, 'optionalAccess', _17 => _17.start]);
if (start === null || start === void 0)
throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
return start + 1;
}
async function resolveVue22(code, s) {
if (!_localpkg.isPackageExists.call(void 0, "@babel/parser"))
throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
const { parse } = await _localpkg.importModule.call(void 0, "@babel/parser");
const { program } = parse(code, {
sourceType: "module"
});
const nodes = [];
const { walk } = await Promise.resolve().then(() => _interopRequireWildcard(require("./src-KNP44FKK.cjs")));
walk(program, {
enter(node) {
if (node.type === "CallExpression")
nodes.push(node);
}
});
if (nodes.length === 0)
return [];
let _renderStart;
const getRenderStart = () => {
if (_renderStart !== void 0)
return _renderStart;
return _renderStart = getRenderFnStart(program);
};
const results = [];
for (const node of nodes) {
const { callee, arguments: args } = node;
if (callee.type !== "Identifier" || callee.name !== "_c" || _optionalChain([args, 'access', _18 => _18[1], 'optionalAccess', _19 => _19.type]) !== "ObjectExpression")
continue;
const directives = _optionalChain([args, 'access', _20 => _20[1], 'access', _21 => _21.properties, 'access', _22 => _22.find, 'call', _23 => _23(
(property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
), 'optionalAccess', _24 => _24.value]);
if (!directives || directives.type !== "ArrayExpression")
continue;
for (const directive of directives.elements) {
if (_optionalChain([directive, 'optionalAccess', _25 => _25.type]) !== "ObjectExpression")
continue;
const nameNode = _optionalChain([directive, 'access', _26 => _26.properties, 'access', _27 => _27.find, 'call', _28 => _28(
(p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
), 'optionalAccess', _29 => _29.value]);
if (_optionalChain([nameNode, 'optionalAccess', _30 => _30.type]) !== "StringLiteral")
continue;
const name = nameNode.value;
if (!name || name.startsWith("_"))
continue;
results.push({
rawName: name,
replace: (resolved) => {
s.prependLeft(getRenderStart(), `
this.$options.directives["${name}"] = ${resolved};`);
}
});
}
}
return results;
}
// src/core/transforms/directive/vue3.ts
function resolveVue32(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
// src/core/transforms/directive/index.ts
var debug3 = _debug2.default.call(void 0, "unplugin-vue-components:transform:directive");
async function transformDirective(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
for (const { rawName, replace } of results) {
debug3(`| ${rawName}`);
const name = `${_chunkMU27IQTBcjs.DIRECTIVE_IMPORT_PREFIX}${_chunkMU27IQTBcjs.pascalCase.call(void 0, rawName)}`;
ctx.updateUsageMap(sfcPath, [name]);
const directive = await ctx.findComponent(name, "directive", [sfcPath]);
if (!directive)
continue;
const varName = `__unplugin_directives_${no}`;
s.prepend(`${_chunkMU27IQTBcjs.stringifyComponentImport.call(void 0, { ...directive, as: varName }, ctx)};
`);
no += 1;
replace(varName);
}
debug3(`^ (${no})`);
}
// src/core/transformer.ts
var debug4 = _debug2.default.call(void 0, "unplugin-vue-components:transformer");
function transformer(ctx, transformer2) {
return async (code, id, path) => {
ctx.searchGlob();
const sfcPath = ctx.normalizePath(path);
debug4(sfcPath);
const s = new (0, _magicstring2.default)(code);
await transformComponent(code, transformer2, s, ctx, sfcPath);
if (ctx.options.directives)
await transformDirective(code, transformer2, s, ctx, sfcPath);
s.prepend(_chunkMU27IQTBcjs.DISABLE_COMMENT);
const result = { code: s.toString() };
if (ctx.sourcemap)
result.map = s.generateMap({ source: id, includeContent: true, hires: "boundary" });
return result;
};
}
// src/core/context.ts
var debug5 = {
components: _debug2.default.call(void 0, "unplugin-vue-components:context:components"),
search: _debug2.default.call(void 0, "unplugin-vue-components:context:search"),
hmr: _debug2.default.call(void 0, "unplugin-vue-components:context:hmr"),
declaration: _debug2.default.call(void 0, "unplugin-vue-components:declaration"),
env: _debug2.default.call(void 0, "unplugin-vue-components:env")
};
var Context = (_class = class {
constructor(rawOptions) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);_class.prototype.__init7.call(this);_class.prototype.__init8.call(this);_class.prototype.__init9.call(this);_class.prototype.__init10.call(this);
this.rawOptions = rawOptions;
this.options = resolveOptions(rawOptions, this.root);
this.generateDeclaration = _utils.throttle.call(void 0, 500, this._generateDeclaration.bind(this), { noLeading: false });
this.setTransformer(this.options.transformer);
}
__init() {this.transformer = void 0}
__init2() {this._componentPaths = /* @__PURE__ */ new Set()}
__init3() {this._componentNameMap = {}}
__init4() {this._componentUsageMap = {}}
__init5() {this._componentCustomMap = {}}
__init6() {this._directiveCustomMap = {}}
__init7() {this.root = _process2.default.cwd()}
__init8() {this.sourcemap = true}
__init9() {this.alias = {}}
setRoot(root) {
if (this.root === root)
return;
debug5.env("root", root);
this.root = root;
this.options = resolveOptions(this.rawOptions, this.root);
}
setTransformer(name) {
debug5.env("transformer", name);
this.transformer = transformer(this, name || "vue3");
}
transform(code, id) {
const { path, query } = _chunkMU27IQTBcjs.parseId.call(void 0, id);
return this.transformer(code, id, path, query);
}
setupViteServer(server) {
if (this._server === server)
return;
this._server = server;
this.setupWatcher(server.watcher);
}
setupWatcher(watcher) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!_chunkMU27IQTBcjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.removeComponents(path);
this.onUpdate(path);
});
watcher.on("add", (path) => {
if (!_chunkMU27IQTBcjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.addComponents(path);
this.onUpdate(path);
});
}
/**
* start watcher for webpack
*/
setupWatcherWebpack(watcher, emitUpdate) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!_chunkMU27IQTBcjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.removeComponents(path);
emitUpdate(path, "unlink");
});
watcher.on("add", (path) => {
if (!_chunkMU27IQTBcjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.addComponents(path);
emitUpdate(path, "add");
});
}
/**
* Record the usage of components
* @param path
* @param paths paths of used components
*/
updateUsageMap(path, paths) {
if (!this._componentUsageMap[path])
this._componentUsageMap[path] = /* @__PURE__ */ new Set();
paths.forEach((p) => {
this._componentUsageMap[path].add(p);
});
}
addComponents(paths) {
debug5.components("add", paths);
const size = this._componentPaths.size;
_utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.add(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
addCustomComponents(info) {
if (info.as)
this._componentCustomMap[info.as] = info;
}
addCustomDirectives(info) {
if (info.as)
this._directiveCustomMap[info.as] = info;
}
removeComponents(paths) {
debug5.components("remove", paths);
const size = this._componentPaths.size;
_utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.delete(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
onUpdate(path) {
this.generateDeclaration();
if (!this._server)
return;
const payload = {
type: "update",
updates: []
};
const timestamp = +/* @__PURE__ */ new Date();
const name = _chunkMU27IQTBcjs.pascalCase.call(void 0, _chunkMU27IQTBcjs.getNameFromFilePath.call(void 0, path, this.options));
Object.entries(this._componentUsageMap).forEach(([key, values]) => {
if (values.has(name)) {
const r = `/${_utils.slash.call(void 0, _path.relative.call(void 0, this.root, key))}`;
payload.updates.push({
acceptedPath: r,
path: r,
timestamp,
type: "js-update"
});
}
});
if (payload.updates.length)
this._server.ws.send(payload);
}
updateComponentNameMap() {
this._componentNameMap = {};
Array.from(this._componentPaths).forEach((path) => {
const name = _chunkMU27IQTBcjs.pascalCase.call(void 0, _chunkMU27IQTBcjs.getNameFromFilePath.call(void 0, path, this.options));
if (_chunkMU27IQTBcjs.isExclude.call(void 0, name, this.options.excludeNames)) {
debug5.components("exclude", name);
return;
}
if (this._componentNameMap[name] && !this.options.allowOverrides) {
console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
return;
}
this._componentNameMap[name] = {
as: name,
from: path
};
});
}
async findComponent(name, type, excludePaths = []) {
let info = this._componentNameMap[name];
if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
return info;
for (const resolver of this.options.resolvers) {
if (resolver.type !== type)
continue;
const result = await resolver.resolve(type === "directive" ? name.slice(_chunkMU27IQTBcjs.DIRECTIVE_IMPORT_PREFIX.length) : name);
if (!result)
continue;
if (typeof result === "string") {
info = {
as: name,
from: result
};
} else {
info = {
as: name,
..._chunkMU27IQTBcjs.normalizeComponentInfo.call(void 0, result)
};
}
if (type === "component")
this.addCustomComponents(info);
else if (type === "directive")
this.addCustomDirectives(info);
return info;
}
return void 0;
}
normalizePath(path) {
return _chunkMU27IQTBcjs.resolveAlias.call(void 0, path, _optionalChain([this, 'access', _31 => _31.viteConfig, 'optionalAccess', _32 => _32.resolve, 'optionalAccess', _33 => _33.alias]) || _optionalChain([this, 'access', _34 => _34.viteConfig, 'optionalAccess', _35 => _35.alias]) || []);
}
relative(path) {
if (path.startsWith("/") && !path.startsWith(this.root))
return _utils.slash.call(void 0, path.slice(1));
return _utils.slash.call(void 0, _path.relative.call(void 0, this.root, path));
}
__init10() {this._searched = false}
/**
* This search for components in with the given options.
* Will be called multiple times to ensure file loaded,
* should normally run only once.
*/
searchGlob() {
if (this._searched)
return;
searchComponents(this);
debug5.search(this._componentNameMap);
this._searched = true;
}
_generateDeclaration(removeUnused = !this._server) {
if (!this.options.dts)
return;
debug5.declaration("generating");
return writeDeclaration(this, this.options.dts, removeUnused);
}
get componentNameMap() {
return this._componentNameMap;
}
get componentCustomMap() {
return this._componentCustomMap;
}
get directiveCustomMap() {
return this._directiveCustomMap;
}
}, _class);
// src/core/unplugin.ts
var PLUGIN_NAME = "unplugin:webpack";
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options = {}) => {
const filter = _pluginutils.createFilter.call(void 0,
options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
);
const ctx = new Context(options);
const api = {
async findComponent(name, filename) {
return await ctx.findComponent(name, "component", filename ? [filename] : []);
},
stringifyImport(info) {
return _chunkMU27IQTBcjs.stringifyComponentImport.call(void 0, info, ctx);
}
};
return {
name: "unplugin-vue-components",
enforce: "post",
api,
transformInclude(id) {
return filter(id);
},
async transform(code, id) {
if (!_chunkMU27IQTBcjs.shouldTransform.call(void 0, code))
return null;
try {
const result = await ctx.transform(code, id);
ctx.generateDeclaration();
return result;
} catch (e) {
this.error(e);
}
},
vite: {
configResolved(config) {
ctx.setRoot(config.root);
ctx.sourcemap = true;
if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
ctx.setTransformer("vue2");
if (ctx.options.dts) {
ctx.searchGlob();
if (!_fs.existsSync.call(void 0, ctx.options.dts))
ctx.generateDeclaration();
}
if (config.build.watch && config.command === "build")
ctx.setupWatcher(_chokidar2.default.watch(ctx.options.globs));
},
configureServer(server) {
ctx.setupViteServer(server);
}
},
webpack(compiler) {
let watcher;
let fileDepQueue = [];
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
if (!watcher && compiler.watching) {
watcher = compiler.watching;
ctx.setupWatcherWebpack(_chokidar2.default.watch(ctx.options.globs), (path, type) => {
fileDepQueue.push({ path, type });
_process2.default.nextTick(() => {
watcher.invalidate();
});
});
}
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (fileDepQueue.length) {
fileDepQueue.forEach(({ path, type }) => {
if (type === "unlink")
compilation.fileDependencies.delete(path);
else
compilation.fileDependencies.add(path);
});
fileDepQueue = [];
}
});
}
};
});
exports.unplugin_default = unplugin_default;
@@ -0,0 +1,207 @@
// src/core/utils.ts
import { parse } from "node:path";
import process from "node:process";
import { slash, toArray } from "@antfu/utils";
import {
getPackageInfo,
isPackageExists
} from "local-pkg";
import { minimatch } from "minimatch";
// src/core/constants.ts
var DISABLE_COMMENT = "/* unplugin-vue-components disabled */";
var DIRECTIVE_IMPORT_PREFIX = "v";
// src/core/utils.ts
var isSSR = Boolean(process.env.SSR || process.env.SSG || process.env.VITE_SSR || process.env.VITE_SSG);
function pascalCase(str) {
return capitalize(camelCase(str));
}
function camelCase(str) {
return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
}
function kebabCase(key) {
const result = key.replace(/([A-Z])/g, " $1").trim();
return result.split(" ").join("-").toLowerCase();
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function parseId(id) {
const index = id.indexOf("?");
if (index < 0) {
return { path: id, query: {} };
} else {
const query = Object.fromEntries(new URLSearchParams(id.slice(index)));
return {
path: id.slice(0, index),
query
};
}
}
function isEmpty(value) {
if (!value || value === null || value === void 0 || Array.isArray(value) && Object.keys(value).length <= 0)
return true;
else
return false;
}
function matchGlobs(filepath, globs) {
for (const glob of globs) {
const isNegated = glob.startsWith("!");
const match = minimatch(slash(filepath), isNegated ? glob.slice(1) : glob);
if (match)
return !isNegated;
}
return false;
}
function getTransformedPath(path, importPathTransform) {
if (importPathTransform) {
const result = importPathTransform(path);
if (result != null)
path = result;
}
return path;
}
function stringifyImport(info) {
if (typeof info === "string")
return `import '${info}'`;
if (!info.as)
return `import '${info.from}'`;
else if (info.name)
return `import { ${info.name} as ${info.as} } from '${info.from}'`;
else
return `import ${info.as} from '${info.from}'`;
}
function normalizeComponentInfo(info) {
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return info;
}
function stringifyComponentImport({ as: name, from: path, name: importName, sideEffects }, ctx) {
path = getTransformedPath(path, ctx.options.importPathTransform);
const imports = [
stringifyImport({ as: name, from: path, name: importName })
];
if (sideEffects)
toArray(sideEffects).forEach((i) => imports.push(stringifyImport(i)));
return imports.join(";");
}
function getNameFromFilePath(filePath, options) {
const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options;
const parsedFilePath = parse(slash(filePath));
let strippedPath = "";
for (const dir of resolvedDirs) {
if (parsedFilePath.dir.startsWith(dir)) {
strippedPath = parsedFilePath.dir.slice(dir.length);
break;
}
}
let folders = strippedPath.slice(1).split("/").filter(Boolean);
let filename = parsedFilePath.name;
if (filename === "index" && !directoryAsNamespace) {
if (isEmpty(folders))
folders = parsedFilePath.dir.slice(root.length + 1).split("/").filter(Boolean);
filename = `${folders.slice(-1)[0]}`;
return filename;
}
if (directoryAsNamespace) {
if (globalNamespaces.some((name) => folders.includes(name)))
folders = folders.filter((f) => !globalNamespaces.includes(f));
folders = folders.map((f) => f.replace(/[^a-z0-9\-]/gi, ""));
if (filename.toLowerCase() === "index")
filename = "";
if (!isEmpty(folders)) {
let namespaced = [...folders, filename];
if (collapseSamePrefixes) {
const collapsed = [];
for (const fileOrFolderName of namespaced) {
let cumulativePrefix = "";
let didCollapse = false;
const pascalCasedName = pascalCase(fileOrFolderName);
for (const parentFolder of [...collapsed].reverse()) {
cumulativePrefix = `${parentFolder}${cumulativePrefix}`;
if (pascalCasedName.startsWith(cumulativePrefix)) {
const collapseSamePrefix = pascalCasedName.slice(cumulativePrefix.length);
collapsed.push(collapseSamePrefix);
didCollapse = true;
break;
}
}
if (!didCollapse)
collapsed.push(pascalCasedName);
}
namespaced = collapsed;
}
filename = namespaced.filter(Boolean).join("-");
}
return filename;
}
return filename;
}
function resolveAlias(filepath, alias) {
const result = filepath;
if (Array.isArray(alias)) {
for (const { find, replacement } of alias)
result.replace(find, replacement);
}
return result;
}
async function getPkgVersion(pkgName, defaultVersion) {
try {
const isExist = isPackageExists(pkgName);
if (isExist) {
const pkg = await getPackageInfo(pkgName);
return pkg?.version ?? defaultVersion;
} else {
return defaultVersion;
}
} catch (err) {
console.error(err);
return defaultVersion;
}
}
function shouldTransform(code) {
if (code.includes(DISABLE_COMMENT))
return false;
return true;
}
function isExclude(name, exclude) {
if (!exclude)
return false;
if (typeof exclude === "string")
return name === exclude;
if (exclude instanceof RegExp)
return !!name.match(exclude);
if (Array.isArray(exclude)) {
for (const item of exclude) {
if (name === item || name.match(item))
return true;
}
}
return false;
}
export {
DISABLE_COMMENT,
DIRECTIVE_IMPORT_PREFIX,
isSSR,
pascalCase,
camelCase,
kebabCase,
parseId,
matchGlobs,
getTransformedPath,
normalizeComponentInfo,
stringifyComponentImport,
getNameFromFilePath,
resolveAlias,
getPkgVersion,
shouldTransform,
isExclude
};
@@ -0,0 +1 @@
"use strict";
+12
View File
@@ -0,0 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/esbuild.ts
var esbuild_default = _chunkUDMRZUV6cjs.unplugin_default.esbuild;
exports.default = esbuild_default;
@@ -0,0 +1,9 @@
import * as esbuild from 'esbuild';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => esbuild.Plugin;
export { _default as default };
+9
View File
@@ -0,0 +1,9 @@
import * as esbuild from 'esbuild';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => esbuild.Plugin;
export { _default as default };
+12
View File
@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/esbuild.ts
var esbuild_default = unplugin_default.esbuild;
export {
esbuild_default as default
};
+16
View File
@@ -0,0 +1,16 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
var _chunkMU27IQTBcjs = require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
exports.camelCase = _chunkMU27IQTBcjs.camelCase; exports.default = _chunkUDMRZUV6cjs.unplugin_default; exports.kebabCase = _chunkMU27IQTBcjs.kebabCase; exports.pascalCase = _chunkMU27IQTBcjs.pascalCase;
+13
View File
@@ -0,0 +1,13 @@
import * as unplugin from 'unplugin';
import { Options } from './types.cjs';
export { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
declare function pascalCase(str: string): string;
declare function camelCase(str: string): string;
declare function kebabCase(key: string): string;
export { Options, camelCase, _default as default, kebabCase, pascalCase };
+13
View File
@@ -0,0 +1,13 @@
import * as unplugin from 'unplugin';
import { Options } from './types.js';
export { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
declare function pascalCase(str: string): string;
declare function camelCase(str: string): string;
declare function kebabCase(key: string): string;
export { Options, camelCase, _default as default, kebabCase, pascalCase };
+16
View File
@@ -0,0 +1,16 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import {
camelCase,
kebabCase,
pascalCase
} from "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
export {
camelCase,
unplugin_default as default,
kebabCase,
pascalCase
};
+18
View File
@@ -0,0 +1,18 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/nuxt.ts
var _kit = require('@nuxt/kit');
var nuxt_default = _kit.defineNuxtModule.call(void 0, {
setup(options) {
_kit.addWebpackPlugin.call(void 0, _chunkUDMRZUV6cjs.unplugin_default.webpack(options));
_kit.addVitePlugin.call(void 0, _chunkUDMRZUV6cjs.unplugin_default.vite(options));
}
});
exports.default = nuxt_default;
+9
View File
@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
export { _default as default };
+9
View File
@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
export { _default as default };
+18
View File
@@ -0,0 +1,18 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/nuxt.ts
import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
var nuxt_default = defineNuxtModule({
setup(options) {
addWebpackPlugin(unplugin_default.webpack(options));
addVitePlugin(unplugin_default.vite(options));
}
});
export {
nuxt_default as default
};
File diff suppressed because it is too large Load Diff
+554
View File
@@ -0,0 +1,554 @@
import { ComponentResolver, ComponentResolveResult } from './types.cjs';
import { FilterPattern } from '@rollup/pluginutils';
import '@antfu/utils';
import 'unplugin';
interface AntDesignVueResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less' | 'css-in-js';
/**
* resolve `ant-design-vue' icons
*
* requires package `@ant-design/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
/**
* use commonjs build default false
*/
cjs?: boolean;
/**
* rename package
*
* @default 'ant-design-vue'
*/
packageName?: string;
/**
* customize prefix of component
* @default 'A'
*/
prefix?: string;
}
/**
* Resolver for Ant Design Vue
*
* Requires ant-design-vue@v2.2.0-beta.6 or later
*
* See https://github.com/antfu/unplugin-vue-components/issues/26#issuecomment-789767941 for more details
*
* @author @yangss3
* @link https://antdv.com/
*/
declare function AntDesignVueResolver(options?: AntDesignVueResolverOptions): ComponentResolver;
type DisallowResolveIconOption = undefined | false | {
enable: false;
};
type AllowResolveIconOption = true | {
enable: true;
iconPrefix?: string;
};
type ResolveIconsOption = DisallowResolveIconOption | AllowResolveIconOption;
interface ArcoResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string | RegExp | (string | RegExp)[];
/**
* import style css or less with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* resolve icons
*
* @default false
*/
resolveIcons?: ResolveIconsOption;
/**
* Control style automatic import
*
* @default true
*/
sideEffect?: boolean;
}
/**
* Resolver for Arco Design Vue
*
* Requires arco-design/web-vue@2.11.0 or later
*
* @author @flsion
* @link https://arco.design/ for arco-design
*
*/
declare function ArcoResolver(options?: ArcoResolverOptions): ComponentResolver;
interface BootstrapVueResolverOptions {
/**
* Auto import for directives.
*
* @default true
*/
directives?: boolean;
}
/**
* Resolver for BootstrapVue
*
* @link https://github.com/bootstrap-vue/bootstrap-vue
*/
declare function BootstrapVueResolver(_options?: BootstrapVueResolverOptions): ComponentResolver[];
/**
* Resolver for BootstrapVueNext
*
* @link https://github.com/bootstrap-vue/bootstrap-vue-next
*
* @deprecated use `import { BootstrapVueNextResolver } from 'bootstrap-vue-next'` instead
*/
declare function BootstrapVueNextResolver(_options?: BootstrapVueResolverOptions): Array<ComponentResolver>;
/**
* Resolver for legacy BootstrapVue3 apps
*
* @deprecated use BootstrapVueNextResolver with https://github.com/bootstrap-vue/bootstrap-vue-next
* @link https://www.npmjs.com/package/bootstrap-vue-3
*/
declare function BootstrapVue3Resolver(_options?: BootstrapVueResolverOptions): Array<ComponentResolver>;
interface DevResolverOptions {
/**
* bring in components and styles
*
* @default true
*/
importStyle?: boolean;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* use umd lib file
*/
ssr?: boolean;
}
declare function DevUiResolver(options?: DevResolverOptions): ComponentResolver[];
interface ElementPlusResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* use commonjs lib & source css or scss for ssr
*/
ssr?: boolean;
/**
* specify element-plus version to load style
*
* @default installed version
*/
version?: string;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
/**
* a list of component names that have no styles, so resolving their styles file should be prevented
*/
noStylesComponents?: string[];
/**
* nightly version
*/
nightly?: boolean;
}
/**
* Resolver for Element Plus
*
* See https://github.com/antfu/vite-plugin-components/pull/28 for more details
* See https://github.com/antfu/vite-plugin-components/issues/117 for more details
*
* @author @develar @nabaonan @sxzz
* @link https://element-plus.org/ for element-plus
*
*/
declare function ElementPlusResolver(options?: ElementPlusResolverOptions): ComponentResolver[];
interface ElementUiResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
}
/**
* Resolver for Element-UI
* @link https://element.eleme.cn/#/zh-CN
* @version @element-ui ^2.15.3, @vue ^2.6.14
* @author @nabaonan
*/
declare function ElementUiResolver(options?: ElementUiResolverOptions): ComponentResolver;
interface HeadlessUiResolverOptions {
/**
* prefix for headless ui components used in templates
*
* @default ""
*/
prefix?: string;
}
/**
* Resolver for headlessui
*
* @link https://github.com/tailwindlabs/headlessui
*/
declare function HeadlessUiResolver(options?: HeadlessUiResolverOptions): ComponentResolver;
interface IduxResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*/
importStyle?: 'css' | 'less';
/**
* theme for import style
*
* @default 'default' for 1.x version
*/
importStyleTheme?: string;
/**
* The scope of the packages.
*
* @default '@idux'
*/
scope?: string;
/**
* specify idux version to load style
*
* @default installed version
*/
version?: string;
}
/**
* Resolver for `@idux/cdk`, `@idux/components` and ``@idux/pro``
*
* @link https://idux.site
*/
declare function IduxResolver(options?: IduxResolverOptions): ComponentResolver;
/**
* Resolver for Inkline
*
* @author @alexgrozav
* @link https://github.com/inkline/inkline
*/
declare function InklineResolver(): ComponentResolver;
/**
* source: https://github.com/nuxt-modules/ionic/blob/main/src/imports.ts
* @author @danielroe
*/
declare const IonicBuiltInComponents: string[];
/**
* Resolver for ionic framework
*
* @author @mathsgod @reslear
* @link https://ionicframework.com/
*/
declare function IonicResolver(): ComponentResolver;
interface LayuiVueResolverOptions {
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css';
/**
* resolve '@layui/layui-vue' icons
* requires package `@layui/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* exclude components that do not require automatic import
*
*/
exclude?: FilterPattern;
}
/**
* Resolver for layui-vue
*
* @link http://www.layui-vue.com/ for layui-vue
*
*/
declare function LayuiVueResolver(options?: LayuiVueResolverOptions): ComponentResolver;
/**
* Resolver for Naive UI
*
* @author @antfu
* @link https://www.naiveui.com/
*/
declare function NaiveUiResolver(): ComponentResolver;
interface PrimeVueResolverOptions {
/**
* import style along with components
*
* @default true
*/
importStyle?: boolean;
/**
* import `primeicons' icons
*
* requires package `primeicons`
*
* @default true
*/
importIcons?: boolean;
/**
* imports a free theme - set theme name here (e.g. saga-blue)
*
* @default ''
*/
importTheme?: string;
/**
* prefix for components (e.g. 'P' to resolve Menu from PMenu)
*
* @default ''
*/
prefix?: string;
}
/**
* Resolver for PrimeVue - If you're using a component with the same tag as an native HTML element (e.g. button) the component must be in uppercase
*
* @link https://github.com/primefaces/primevue
*/
declare function PrimeVueResolver(options?: PrimeVueResolverOptions): ComponentResolver;
/**
* Resolver for Quasar
*
* @link https://github.com/quasarframework/quasar
*/
declare function QuasarResolver(): ComponentResolver;
interface TDesignResolverOptions {
/**
* select the specified library
* @default 'vue'
*/
library?: 'vue' | 'vue-next' | 'react' | 'mobile-vue' | 'mobile-react';
/**
* resolve `tdesign-icons'
* @default false
*/
resolveIcons?: boolean;
/**
* whether to import ESM version
* @default false
*/
esm?: boolean;
/**
* exclude component name, if match do not resolve the name
*
*/
exclude?: FilterPattern;
}
declare function TDesignResolver(options?: TDesignResolverOptions): ComponentResolver;
interface VantResolverOptions {
/**
* import style css or less along with components
*
* @default true
*/
importStyle?: boolean | 'css' | 'less';
}
/**
* Resolver for Vant
*
* @link https://github.com/youzan/vant
*/
declare function VantResolver(options?: VantResolverOptions): ComponentResolver;
interface VarletUIResolverOptions {
/**
* support vue version
* vue3 use @varlet/ui, vue2 use @varlet-vue2/ui
*
* @default 'vue3'
*/
version?: 'vue3' | 'vue2';
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* style entry file extname
*
* @default '.mjs'
*/
styleExtname?: string;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* compatible with unplugin-auto-import
*
* @default false
*/
autoImport?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
}
declare function getResolved(name: string, options: VarletUIResolverOptions): ComponentResolveResult;
/**
* Resolver for VarletUI
*
* @link https://github.com/varletjs/varlet
* @link https://github.com/varletjs/varlet-vue2
*/
declare function VarletUIResolver(options?: VarletUIResolverOptions): ComponentResolver[];
interface VeuiPeerConfig {
/**
* The package name of the peer module.
*/
package: string;
/**
* The directory path of the peer module.
* @default 'components'
*/
path?: string;
/**
* The file name template for the peer module.
* @default '{module}.css'
*/
fileName?: `${string}{module}${string}`;
/**
* The text transform to be applied to the '{module}' part of the file name.
* @default 'kebab-case'
*/
transform?: 'kebab-case' | 'camelCase' | 'PascalCase' | false;
}
type SupportedLocale = 'en-US' | 'zh-Hans';
interface VeuiResolverOptions {
/**
* The alias of 'veui` package.
* @default 'veui'
*/
alias?: string;
/**
* Peer modules to be injected.
*/
modules?: VeuiPeerConfig[];
/**
* Locale modules to be injected.
* @default 'zh-Hans'
*/
locale?: SupportedLocale | SupportedLocale[] | false;
/**
* Global modules to be injected to all components.
* @default []
*/
global?: string[];
}
/**
* Resolver for VEUI
*
* @link https://github.com/ecomfe/veui
*/
declare function VeuiResolver(options?: VeuiResolverOptions): ComponentResolver;
/**
* Resolver for View UI
* @requires @originjs/vite-plugin-commonjs
* @author @nabaonan
* @link https://www.iviewui.com/
* @description has known problems list below
* - select component render error PR: https://github.com/view-design/ViewUI/pull/944, choose can't display value,because click option trigger twice,at second time,select value turn into undefined.
* - scroll component has a template syntax called lang='html',it is require html-loader,but vite plugin not support yet,remove it can run. relate pr: https://github.com/view-design/ViewUI/pull/985
*/
declare function ViewUiResolver(): ComponentResolver;
/**
* Resolver for Vuetify
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function VuetifyResolver(): ComponentResolver;
/**
* Resolver for Vuetify 3 Beta
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function Vuetify3Resolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseComponentsResolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseDirectiveResolver(): ComponentResolver;
export { type AllowResolveIconOption, AntDesignVueResolver, type AntDesignVueResolverOptions, ArcoResolver, type ArcoResolverOptions, BootstrapVue3Resolver, BootstrapVueNextResolver, BootstrapVueResolver, type BootstrapVueResolverOptions, type DevResolverOptions, DevUiResolver, type DisallowResolveIconOption, ElementPlusResolver, type ElementPlusResolverOptions, ElementUiResolver, type ElementUiResolverOptions, HeadlessUiResolver, type HeadlessUiResolverOptions, IduxResolver, type IduxResolverOptions, InklineResolver, IonicBuiltInComponents, IonicResolver, LayuiVueResolver, type LayuiVueResolverOptions, NaiveUiResolver, PrimeVueResolver, type PrimeVueResolverOptions, QuasarResolver, type ResolveIconsOption, TDesignResolver, type TDesignResolverOptions, VantResolver, type VantResolverOptions, VarletUIResolver, type VarletUIResolverOptions, VeuiResolver, type VeuiResolverOptions, ViewUiResolver, VueUseComponentsResolver, VueUseDirectiveResolver, Vuetify3Resolver, VuetifyResolver, getResolved };
+554
View File
@@ -0,0 +1,554 @@
import { ComponentResolver, ComponentResolveResult } from './types.js';
import { FilterPattern } from '@rollup/pluginutils';
import '@antfu/utils';
import 'unplugin';
interface AntDesignVueResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less' | 'css-in-js';
/**
* resolve `ant-design-vue' icons
*
* requires package `@ant-design/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
/**
* use commonjs build default false
*/
cjs?: boolean;
/**
* rename package
*
* @default 'ant-design-vue'
*/
packageName?: string;
/**
* customize prefix of component
* @default 'A'
*/
prefix?: string;
}
/**
* Resolver for Ant Design Vue
*
* Requires ant-design-vue@v2.2.0-beta.6 or later
*
* See https://github.com/antfu/unplugin-vue-components/issues/26#issuecomment-789767941 for more details
*
* @author @yangss3
* @link https://antdv.com/
*/
declare function AntDesignVueResolver(options?: AntDesignVueResolverOptions): ComponentResolver;
type DisallowResolveIconOption = undefined | false | {
enable: false;
};
type AllowResolveIconOption = true | {
enable: true;
iconPrefix?: string;
};
type ResolveIconsOption = DisallowResolveIconOption | AllowResolveIconOption;
interface ArcoResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string | RegExp | (string | RegExp)[];
/**
* import style css or less with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* resolve icons
*
* @default false
*/
resolveIcons?: ResolveIconsOption;
/**
* Control style automatic import
*
* @default true
*/
sideEffect?: boolean;
}
/**
* Resolver for Arco Design Vue
*
* Requires arco-design/web-vue@2.11.0 or later
*
* @author @flsion
* @link https://arco.design/ for arco-design
*
*/
declare function ArcoResolver(options?: ArcoResolverOptions): ComponentResolver;
interface BootstrapVueResolverOptions {
/**
* Auto import for directives.
*
* @default true
*/
directives?: boolean;
}
/**
* Resolver for BootstrapVue
*
* @link https://github.com/bootstrap-vue/bootstrap-vue
*/
declare function BootstrapVueResolver(_options?: BootstrapVueResolverOptions): ComponentResolver[];
/**
* Resolver for BootstrapVueNext
*
* @link https://github.com/bootstrap-vue/bootstrap-vue-next
*
* @deprecated use `import { BootstrapVueNextResolver } from 'bootstrap-vue-next'` instead
*/
declare function BootstrapVueNextResolver(_options?: BootstrapVueResolverOptions): Array<ComponentResolver>;
/**
* Resolver for legacy BootstrapVue3 apps
*
* @deprecated use BootstrapVueNextResolver with https://github.com/bootstrap-vue/bootstrap-vue-next
* @link https://www.npmjs.com/package/bootstrap-vue-3
*/
declare function BootstrapVue3Resolver(_options?: BootstrapVueResolverOptions): Array<ComponentResolver>;
interface DevResolverOptions {
/**
* bring in components and styles
*
* @default true
*/
importStyle?: boolean;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* use umd lib file
*/
ssr?: boolean;
}
declare function DevUiResolver(options?: DevResolverOptions): ComponentResolver[];
interface ElementPlusResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* use commonjs lib & source css or scss for ssr
*/
ssr?: boolean;
/**
* specify element-plus version to load style
*
* @default installed version
*/
version?: string;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
/**
* a list of component names that have no styles, so resolving their styles file should be prevented
*/
noStylesComponents?: string[];
/**
* nightly version
*/
nightly?: boolean;
}
/**
* Resolver for Element Plus
*
* See https://github.com/antfu/vite-plugin-components/pull/28 for more details
* See https://github.com/antfu/vite-plugin-components/issues/117 for more details
*
* @author @develar @nabaonan @sxzz
* @link https://element-plus.org/ for element-plus
*
*/
declare function ElementPlusResolver(options?: ElementPlusResolverOptions): ComponentResolver[];
interface ElementUiResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
}
/**
* Resolver for Element-UI
* @link https://element.eleme.cn/#/zh-CN
* @version @element-ui ^2.15.3, @vue ^2.6.14
* @author @nabaonan
*/
declare function ElementUiResolver(options?: ElementUiResolverOptions): ComponentResolver;
interface HeadlessUiResolverOptions {
/**
* prefix for headless ui components used in templates
*
* @default ""
*/
prefix?: string;
}
/**
* Resolver for headlessui
*
* @link https://github.com/tailwindlabs/headlessui
*/
declare function HeadlessUiResolver(options?: HeadlessUiResolverOptions): ComponentResolver;
interface IduxResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*/
importStyle?: 'css' | 'less';
/**
* theme for import style
*
* @default 'default' for 1.x version
*/
importStyleTheme?: string;
/**
* The scope of the packages.
*
* @default '@idux'
*/
scope?: string;
/**
* specify idux version to load style
*
* @default installed version
*/
version?: string;
}
/**
* Resolver for `@idux/cdk`, `@idux/components` and ``@idux/pro``
*
* @link https://idux.site
*/
declare function IduxResolver(options?: IduxResolverOptions): ComponentResolver;
/**
* Resolver for Inkline
*
* @author @alexgrozav
* @link https://github.com/inkline/inkline
*/
declare function InklineResolver(): ComponentResolver;
/**
* source: https://github.com/nuxt-modules/ionic/blob/main/src/imports.ts
* @author @danielroe
*/
declare const IonicBuiltInComponents: string[];
/**
* Resolver for ionic framework
*
* @author @mathsgod @reslear
* @link https://ionicframework.com/
*/
declare function IonicResolver(): ComponentResolver;
interface LayuiVueResolverOptions {
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css';
/**
* resolve '@layui/layui-vue' icons
* requires package `@layui/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* exclude components that do not require automatic import
*
*/
exclude?: FilterPattern;
}
/**
* Resolver for layui-vue
*
* @link http://www.layui-vue.com/ for layui-vue
*
*/
declare function LayuiVueResolver(options?: LayuiVueResolverOptions): ComponentResolver;
/**
* Resolver for Naive UI
*
* @author @antfu
* @link https://www.naiveui.com/
*/
declare function NaiveUiResolver(): ComponentResolver;
interface PrimeVueResolverOptions {
/**
* import style along with components
*
* @default true
*/
importStyle?: boolean;
/**
* import `primeicons' icons
*
* requires package `primeicons`
*
* @default true
*/
importIcons?: boolean;
/**
* imports a free theme - set theme name here (e.g. saga-blue)
*
* @default ''
*/
importTheme?: string;
/**
* prefix for components (e.g. 'P' to resolve Menu from PMenu)
*
* @default ''
*/
prefix?: string;
}
/**
* Resolver for PrimeVue - If you're using a component with the same tag as an native HTML element (e.g. button) the component must be in uppercase
*
* @link https://github.com/primefaces/primevue
*/
declare function PrimeVueResolver(options?: PrimeVueResolverOptions): ComponentResolver;
/**
* Resolver for Quasar
*
* @link https://github.com/quasarframework/quasar
*/
declare function QuasarResolver(): ComponentResolver;
interface TDesignResolverOptions {
/**
* select the specified library
* @default 'vue'
*/
library?: 'vue' | 'vue-next' | 'react' | 'mobile-vue' | 'mobile-react';
/**
* resolve `tdesign-icons'
* @default false
*/
resolveIcons?: boolean;
/**
* whether to import ESM version
* @default false
*/
esm?: boolean;
/**
* exclude component name, if match do not resolve the name
*
*/
exclude?: FilterPattern;
}
declare function TDesignResolver(options?: TDesignResolverOptions): ComponentResolver;
interface VantResolverOptions {
/**
* import style css or less along with components
*
* @default true
*/
importStyle?: boolean | 'css' | 'less';
}
/**
* Resolver for Vant
*
* @link https://github.com/youzan/vant
*/
declare function VantResolver(options?: VantResolverOptions): ComponentResolver;
interface VarletUIResolverOptions {
/**
* support vue version
* vue3 use @varlet/ui, vue2 use @varlet-vue2/ui
*
* @default 'vue3'
*/
version?: 'vue3' | 'vue2';
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* style entry file extname
*
* @default '.mjs'
*/
styleExtname?: string;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* compatible with unplugin-auto-import
*
* @default false
*/
autoImport?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
}
declare function getResolved(name: string, options: VarletUIResolverOptions): ComponentResolveResult;
/**
* Resolver for VarletUI
*
* @link https://github.com/varletjs/varlet
* @link https://github.com/varletjs/varlet-vue2
*/
declare function VarletUIResolver(options?: VarletUIResolverOptions): ComponentResolver[];
interface VeuiPeerConfig {
/**
* The package name of the peer module.
*/
package: string;
/**
* The directory path of the peer module.
* @default 'components'
*/
path?: string;
/**
* The file name template for the peer module.
* @default '{module}.css'
*/
fileName?: `${string}{module}${string}`;
/**
* The text transform to be applied to the '{module}' part of the file name.
* @default 'kebab-case'
*/
transform?: 'kebab-case' | 'camelCase' | 'PascalCase' | false;
}
type SupportedLocale = 'en-US' | 'zh-Hans';
interface VeuiResolverOptions {
/**
* The alias of 'veui` package.
* @default 'veui'
*/
alias?: string;
/**
* Peer modules to be injected.
*/
modules?: VeuiPeerConfig[];
/**
* Locale modules to be injected.
* @default 'zh-Hans'
*/
locale?: SupportedLocale | SupportedLocale[] | false;
/**
* Global modules to be injected to all components.
* @default []
*/
global?: string[];
}
/**
* Resolver for VEUI
*
* @link https://github.com/ecomfe/veui
*/
declare function VeuiResolver(options?: VeuiResolverOptions): ComponentResolver;
/**
* Resolver for View UI
* @requires @originjs/vite-plugin-commonjs
* @author @nabaonan
* @link https://www.iviewui.com/
* @description has known problems list below
* - select component render error PR: https://github.com/view-design/ViewUI/pull/944, choose can't display value,because click option trigger twice,at second time,select value turn into undefined.
* - scroll component has a template syntax called lang='html',it is require html-loader,but vite plugin not support yet,remove it can run. relate pr: https://github.com/view-design/ViewUI/pull/985
*/
declare function ViewUiResolver(): ComponentResolver;
/**
* Resolver for Vuetify
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function VuetifyResolver(): ComponentResolver;
/**
* Resolver for Vuetify 3 Beta
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function Vuetify3Resolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseComponentsResolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseDirectiveResolver(): ComponentResolver;
export { type AllowResolveIconOption, AntDesignVueResolver, type AntDesignVueResolverOptions, ArcoResolver, type ArcoResolverOptions, BootstrapVue3Resolver, BootstrapVueNextResolver, BootstrapVueResolver, type BootstrapVueResolverOptions, type DevResolverOptions, DevUiResolver, type DisallowResolveIconOption, ElementPlusResolver, type ElementPlusResolverOptions, ElementUiResolver, type ElementUiResolverOptions, HeadlessUiResolver, type HeadlessUiResolverOptions, IduxResolver, type IduxResolverOptions, InklineResolver, IonicBuiltInComponents, IonicResolver, LayuiVueResolver, type LayuiVueResolverOptions, NaiveUiResolver, PrimeVueResolver, type PrimeVueResolverOptions, QuasarResolver, type ResolveIconsOption, TDesignResolver, type TDesignResolverOptions, VantResolver, type VantResolverOptions, VarletUIResolver, type VarletUIResolverOptions, VeuiResolver, type VeuiResolverOptions, ViewUiResolver, VueUseComponentsResolver, VueUseDirectiveResolver, Vuetify3Resolver, VuetifyResolver, getResolved };
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/rollup.ts
var rollup_default = _chunkUDMRZUV6cjs.unplugin_default.rollup;
exports.default = rollup_default;
+9
View File
@@ -0,0 +1,9 @@
import * as rollup from 'rollup';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => rollup.Plugin<any> | rollup.Plugin<any>[];
export { _default as default };
+9
View File
@@ -0,0 +1,9 @@
import * as rollup from 'rollup';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => rollup.Plugin<any> | rollup.Plugin<any>[];
export { _default as default };
+12
View File
@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/rollup.ts
var rollup_default = unplugin_default.rollup;
export {
rollup_default as default
};
+12
View File
@@ -0,0 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/rspack.ts
var rspack_default = _chunkUDMRZUV6cjs.unplugin_default.rspack;
exports.default = rspack_default;
+8
View File
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => RspackPluginInstance;
export { _default as default };
+8
View File
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => RspackPluginInstance;
export { _default as default };
+12
View File
@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/rspack.ts
var rspack_default = unplugin_default.rspack;
export {
rspack_default as default
};
@@ -0,0 +1,262 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-OBGZSXTJ.cjs');
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
var WalkerBase = class {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== void 0) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
var SyncWalker = class extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
function isNode(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/async.js
var AsyncWalker = class extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode2(item)) {
if (!await this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode2(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
function isNode2(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}
exports.asyncWalk = asyncWalk; exports.walk = walk;
+262
View File
@@ -0,0 +1,262 @@
import "./chunk-3RG5ZIWI.js";
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
var WalkerBase = class {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== void 0) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
var SyncWalker = class extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
function isNode(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/async.js
var AsyncWalker = class extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode2(item)) {
if (!await this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode2(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
};
function isNode2(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}
export {
asyncWalk,
walk
};
+1
View File
@@ -0,0 +1 @@
"use strict";require('./chunk-ZBPRDZS4.cjs');
+172
View File
@@ -0,0 +1,172 @@
import { Awaitable } from '@antfu/utils';
import { FilterPattern } from '@rollup/pluginutils';
import { TransformResult } from 'unplugin';
interface ImportInfoLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportInfo {
as?: string;
name?: string;
from: string;
}
type SideEffectsInfo = (ImportInfo | string)[] | ImportInfo | string | undefined;
interface ComponentInfo extends ImportInfo {
sideEffects?: SideEffectsInfo;
}
type ComponentResolveResult = Awaitable<string | ComponentInfo | null | undefined | void>;
type ComponentResolverFunction = (name: string) => ComponentResolveResult;
interface ComponentResolverObject {
type: 'component' | 'directive';
resolve: ComponentResolverFunction;
}
type ComponentResolver = ComponentResolverFunction | ComponentResolverObject;
type Matcher = (id: string) => boolean | null | undefined;
type Transformer = (code: string, id: string, path: string, query: Record<string, string>) => Awaitable<TransformResult | null>;
type SupportedTransformer = 'vue3' | 'vue2';
interface PublicPluginAPI {
/**
* Resolves a component using the configured resolvers.
*/
findComponent: (name: string, filename?: string) => Promise<ComponentInfo | undefined>;
/**
* Obtain an import statement for a resolved component.
*/
stringifyImport: (info: ComponentInfo) => string;
}
/**
* Plugin options.
*/
interface Options {
/**
* RegExp or glob to match files to be transformed
*/
include?: FilterPattern;
/**
* RegExp or glob to match files to NOT be transformed
*/
exclude?: FilterPattern;
/**
* RegExp or string to match component names that will NOT be imported
*/
excludeNames?: FilterPattern;
/**
* Relative paths to the directory to search for components.
* @default 'src/components'
*/
dirs?: string | string[];
/**
* Valid file extensions for components.
* @default ['vue']
*/
extensions?: string | string[];
/**
* Glob patterns to match file names to be detected as components.
*
* When specified, the `dirs`, `extensions`, and `directoryAsNamespace` options will be ignored.
*/
globs?: string | string[];
/**
* Search for subdirectories
* @default true
*/
deep?: boolean;
/**
* Allow subdirectories as namespace prefix for components
* @default false
*/
directoryAsNamespace?: boolean;
/**
* Collapse same prefixes (camel-sensitive) of folders and components
* to prevent duplication inside namespaced component name.
*
* Works when `directoryAsNamespace: true`
* @default false
*/
collapseSamePrefixes?: boolean;
/**
* Subdirectory paths for ignoring namespace prefixes
*
* Works when `directoryAsNamespace: true`
* @default "[]"
*/
globalNamespaces?: string[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: (ComponentResolver | ComponentResolver[])[];
/**
* Apply custom transform over the path for importing
*/
importPathTransform?: (path: string) => string | undefined;
/**
* Transformer to apply
*
* @default 'vue3'
*/
transformer?: SupportedTransformer;
/**
* Generate TypeScript declaration for global components
*
* Accept boolean or a path related to project root
*
* @see https://github.com/vuejs/core/pull/3399
* @see https://github.com/johnsoncodehk/volar#using
* @default true
*/
dts?: boolean | string;
/**
* Do not emit warning on component overriding
*
* @default false
*/
allowOverrides?: boolean;
/**
* auto import for directives.
*
* default: `true` for Vue 3, `false` for Vue 2
*
* Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
* To install Babel, run: `npm install -D @babel/parser`
* @default undefined
*/
directives?: boolean;
/**
* Only provide types of components in library (registered globally)
*/
types?: TypeImport[];
/**
* Vue version of project. It will detect automatically if not specified.
*/
version?: 2 | 2.7 | 3;
}
type ResolvedOptions = Omit<Required<Options>, 'resolvers' | 'extensions' | 'dirs' | 'globalComponentsDeclaration'> & {
resolvers: ComponentResolverObject[];
extensions: string[];
dirs: string[];
resolvedDirs: string[];
globs: string[];
dts: string | false;
root: string;
};
type ComponentsImportMap = Record<string, string[] | undefined>;
interface TypeImport {
from: string;
names: string[];
}
export type { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, Options, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport };
+172
View File
@@ -0,0 +1,172 @@
import { Awaitable } from '@antfu/utils';
import { FilterPattern } from '@rollup/pluginutils';
import { TransformResult } from 'unplugin';
interface ImportInfoLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportInfo {
as?: string;
name?: string;
from: string;
}
type SideEffectsInfo = (ImportInfo | string)[] | ImportInfo | string | undefined;
interface ComponentInfo extends ImportInfo {
sideEffects?: SideEffectsInfo;
}
type ComponentResolveResult = Awaitable<string | ComponentInfo | null | undefined | void>;
type ComponentResolverFunction = (name: string) => ComponentResolveResult;
interface ComponentResolverObject {
type: 'component' | 'directive';
resolve: ComponentResolverFunction;
}
type ComponentResolver = ComponentResolverFunction | ComponentResolverObject;
type Matcher = (id: string) => boolean | null | undefined;
type Transformer = (code: string, id: string, path: string, query: Record<string, string>) => Awaitable<TransformResult | null>;
type SupportedTransformer = 'vue3' | 'vue2';
interface PublicPluginAPI {
/**
* Resolves a component using the configured resolvers.
*/
findComponent: (name: string, filename?: string) => Promise<ComponentInfo | undefined>;
/**
* Obtain an import statement for a resolved component.
*/
stringifyImport: (info: ComponentInfo) => string;
}
/**
* Plugin options.
*/
interface Options {
/**
* RegExp or glob to match files to be transformed
*/
include?: FilterPattern;
/**
* RegExp or glob to match files to NOT be transformed
*/
exclude?: FilterPattern;
/**
* RegExp or string to match component names that will NOT be imported
*/
excludeNames?: FilterPattern;
/**
* Relative paths to the directory to search for components.
* @default 'src/components'
*/
dirs?: string | string[];
/**
* Valid file extensions for components.
* @default ['vue']
*/
extensions?: string | string[];
/**
* Glob patterns to match file names to be detected as components.
*
* When specified, the `dirs`, `extensions`, and `directoryAsNamespace` options will be ignored.
*/
globs?: string | string[];
/**
* Search for subdirectories
* @default true
*/
deep?: boolean;
/**
* Allow subdirectories as namespace prefix for components
* @default false
*/
directoryAsNamespace?: boolean;
/**
* Collapse same prefixes (camel-sensitive) of folders and components
* to prevent duplication inside namespaced component name.
*
* Works when `directoryAsNamespace: true`
* @default false
*/
collapseSamePrefixes?: boolean;
/**
* Subdirectory paths for ignoring namespace prefixes
*
* Works when `directoryAsNamespace: true`
* @default "[]"
*/
globalNamespaces?: string[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: (ComponentResolver | ComponentResolver[])[];
/**
* Apply custom transform over the path for importing
*/
importPathTransform?: (path: string) => string | undefined;
/**
* Transformer to apply
*
* @default 'vue3'
*/
transformer?: SupportedTransformer;
/**
* Generate TypeScript declaration for global components
*
* Accept boolean or a path related to project root
*
* @see https://github.com/vuejs/core/pull/3399
* @see https://github.com/johnsoncodehk/volar#using
* @default true
*/
dts?: boolean | string;
/**
* Do not emit warning on component overriding
*
* @default false
*/
allowOverrides?: boolean;
/**
* auto import for directives.
*
* default: `true` for Vue 3, `false` for Vue 2
*
* Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
* To install Babel, run: `npm install -D @babel/parser`
* @default undefined
*/
directives?: boolean;
/**
* Only provide types of components in library (registered globally)
*/
types?: TypeImport[];
/**
* Vue version of project. It will detect automatically if not specified.
*/
version?: 2 | 2.7 | 3;
}
type ResolvedOptions = Omit<Required<Options>, 'resolvers' | 'extensions' | 'dirs' | 'globalComponentsDeclaration'> & {
resolvers: ComponentResolverObject[];
extensions: string[];
dirs: string[];
resolvedDirs: string[];
globs: string[];
dts: string | false;
root: string;
};
type ComponentsImportMap = Record<string, string[] | undefined>;
interface TypeImport {
from: string;
names: string[];
}
export type { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, Options, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport };
+1
View File
@@ -0,0 +1 @@
import "./chunk-6F4PWJZI.js";
+12
View File
@@ -0,0 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/vite.ts
var vite_default = _chunkUDMRZUV6cjs.unplugin_default.vite;
exports.default = vite_default;
+11
View File
@@ -0,0 +1,11 @@
import { Plugin } from 'vite';
import { Options, PublicPluginAPI } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options?: Options | undefined) => Plugin & {
api: PublicPluginAPI;
};
export { _default as default };
+11
View File
@@ -0,0 +1,11 @@
import { Plugin } from 'vite';
import { Options, PublicPluginAPI } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options?: Options | undefined) => Plugin & {
api: PublicPluginAPI;
};
export { _default as default };
+12
View File
@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/vite.ts
var vite_default = unplugin_default.vite;
export {
vite_default as default
};
+12
View File
@@ -0,0 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUDMRZUV6cjs = require('./chunk-UDMRZUV6.cjs');
require('./chunk-MU27IQTB.cjs');
require('./chunk-OBGZSXTJ.cjs');
require('./chunk-ZBPRDZS4.cjs');
// src/webpack.ts
var webpack_default = _chunkUDMRZUV6cjs.unplugin_default.webpack;
exports.default = webpack_default;
@@ -0,0 +1,9 @@
import * as webpack from 'webpack';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => webpack.WebpackPluginInstance;
export { _default as default };
+9
View File
@@ -0,0 +1,9 @@
import * as webpack from 'webpack';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unplugin';
declare const _default: (options: Options) => webpack.WebpackPluginInstance;
export { _default as default };
+12
View File
@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-5PFDJXKB.js";
import "./chunk-X53Y3GEO.js";
import "./chunk-3RG5ZIWI.js";
import "./chunk-6F4PWJZI.js";
// src/webpack.ts
var webpack_default = unplugin_default.webpack;
export {
webpack_default as default
};
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker
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.
@@ -0,0 +1,308 @@
# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar)
> Minimal and efficient cross-platform file watching library
[![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar)
## Why?
Node.js `fs.watch`:
* Doesn't report filenames on MacOS.
* Doesn't report events at all when using editors like Sublime on MacOS.
* Often reports events twice.
* Emits most changes as `rename`.
* Does not provide an easy way to recursively watch file trees.
* Does not support recursive watching on Linux.
Node.js `fs.watchFile`:
* Almost as bad at event handling.
* Also does not provide any recursive watching.
* Results in high CPU utilization.
Chokidar resolves these problems.
Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in
[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
[gulp](https://github.com/gulpjs/gulp/),
[karma](https://karma-runner.github.io/),
[PM2](https://github.com/Unitech/PM2),
[browserify](http://browserify.org/),
[webpack](https://webpack.github.io/),
[BrowserSync](https://www.browsersync.io/),
and [many others](https://www.npmjs.com/browse/depended/chokidar).
It has proven itself in production environments.
Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/)
## How?
Chokidar does still rely on the Node.js core `fs` module, but when using
`fs.watch` and `fs.watchFile` for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
On MacOS, chokidar by default uses a native extension exposing the Darwin
`FSEvents` API. This provides very efficient recursive watching compared with
implementations like `kqueue` available on most \*nix platforms. Chokidar still
does have to do some work to normalize the events received that way as well.
On most other platforms, the `fs.watch`-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed.
## Getting started
Install with npm:
```sh
npm install chokidar
```
Then `require` and use it in your code:
```javascript
const chokidar = require('chokidar');
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
```
## API
```javascript
// Example of a more typical implementation structure
// Initialize watcher.
const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', path => log(`File ${path} has been added`))
.on('change', path => log(`File ${path} has been changed`))
.on('unlink', path => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', path => log(`Directory ${path} has been added`))
.on('unlinkDir', path => log(`Directory ${path} has been removed`))
.on('error', error => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => { // internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
// Get list of actual paths being watched on the filesystem
var watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file*');
// Stop watching.
// The method is async!
watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
ignored: '*.txt',
ignoreInitial: false,
followSymlinks: true,
cwd: '.',
disableGlobbing: false,
usePolling: false,
interval: 100,
binaryInterval: 300,
alwaysStat: false,
depth: 99,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
},
ignorePermissionErrors: false,
atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
});
```
`chokidar.watch(paths, [options])`
* `paths` (string or array of strings). Paths to files, dirs to be watched
recursively, or glob patterns.
- Note: globs must not contain windows separators (`\`),
because that's how they work by the standard —
you'll need to replace them with forward slashes (`/`).
- Note 2: for additional glob documentation, check out low-level
library: [picomatch](https://github.com/micromatch/picomatch).
* `options` (object) Options object as defined below:
#### Persistence
* `persistent` (default: `true`). Indicates whether the process
should continue to run as long as files are being watched. If set to
`false` when using `fsevents` to watch, no more events will be emitted
after `ready`, even if the process continues to run.
#### Path filtering
* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
Defines files/paths to be ignored. The whole relative or absolute path is
tested, not just filename. If a function with two arguments is provided, it
gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object of that path).
* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the `ready` event).
* `followSymlinks` (default: `true`). When `false`, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.
* `cwd` (no default). The base directory from which watch `paths` are to be
derived. Paths emitted with events will be relative to this.
* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
literal path names, even if they look like globs.
#### Performance
* `usePolling` (default: `false`).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to `false`. It is
typically necessary to **set this to `true` to successfully watch files over
a network**, and it may be necessary to successfully watch files in other
non-standard situations. Setting to `true` explicitly on MacOS overrides the
`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.
* _Polling-specific settings_ (effective when `usePolling: true`)
* `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.
* `binaryInterval` (default: `300`). Interval of file system
polling for binary files.
([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
* `useFsEvents` (default: `true` on MacOS). Whether to use the
`fsevents` watching interface if available. When set to `true` explicitly
and `fsevents` is available this supercedes the `usePolling` setting. When
set to `false` on MacOS, `usePolling: true` becomes the default.
* `alwaysStat` (default: `false`). If relying upon the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object that may get passed with `add`, `addDir`, and `change` events, set
this to `true` to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.
* `depth` (default: `undefined`). If set, limits how many levels of
subdirectories will be traversed.
* `awaitWriteFinish` (default: `false`).
By default, the `add` event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some `change`
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
holding its `add` and `change` events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
* *`options.awaitWriteFinish` can be set to an object in order to adjust
timing params:*
* `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.
* `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
#### Errors
* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to `EPERM`
or `EACCES` with this set to `true`, the errors will be suppressed silently.
* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a `change` event
rather than `unlink` then `add`. If the default of 100 ms does not work well
for you, you can override it by setting `atomic` to a custom value, in
milliseconds.
### Methods & Events
`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
* `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
Takes an array of strings or just one string.
* `.on(event, callback)`: Listen for an FS event.
Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
`raw`, `error`.
Additionally `all` is available which gets emitted with the underlying event
name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
Takes an array of strings or just one string.
* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
* `.getWatched()`: Returns an object representing all the paths on the file
system being watched by this `FSWatcher` instance. The object's keys are all the
directories (using absolute paths unless the `cwd` option was used), and the
values are arrays of the names of the items contained in each directory.
## CLI
If you need a CLI interface for your file watching, check out
[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to
execute a command on each change, or get a stdio stream of change events.
## Install Troubleshooting
* `npm WARN optional dep failed, continuing fsevents@n.n.n`
* This message is normal part of how `npm` handles optional dependencies and is
not indicative of a problem. Even if accompanied by other related error messages,
Chokidar should function properly.
* `TypeError: fsevents is not a constructor`
* Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar.
* Chokidar is producing `ENOSP` error on Linux, like this:
* `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
`Error: watch /home/ ENOSPC`
* This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal:
`echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`
## Changelog
For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md).
- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks.
- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement.
- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method.
- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions.
- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%.
- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher.
- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes.
- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
## Also
Why was chokidar named this way? What's the meaning behind it?
>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India.
## License
MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.
@@ -0,0 +1,973 @@
'use strict';
const { EventEmitter } = require('events');
const fs = require('fs');
const sysPath = require('path');
const { promisify } = require('util');
const readdirp = require('readdirp');
const anymatch = require('anymatch').default;
const globParent = require('glob-parent');
const isGlob = require('is-glob');
const braces = require('braces');
const normalizePath = require('normalize-path');
const NodeFsHandler = require('./lib/nodefs-handler');
const FsEventsHandler = require('./lib/fsevents-handler');
const {
EV_ALL,
EV_READY,
EV_ADD,
EV_CHANGE,
EV_UNLINK,
EV_ADD_DIR,
EV_UNLINK_DIR,
EV_RAW,
EV_ERROR,
STR_CLOSE,
STR_END,
BACK_SLASH_RE,
DOUBLE_SLASH_RE,
SLASH_OR_BACK_SLASH_RE,
DOT_RE,
REPLACER_RE,
SLASH,
SLASH_SLASH,
BRACE_START,
BANG,
ONE_DOT,
TWO_DOTS,
GLOBSTAR,
SLASH_GLOBSTAR,
ANYMATCH_OPTS,
STRING_TYPE,
FUNCTION_TYPE,
EMPTY_STR,
EMPTY_FN,
isWindows,
isMacos,
isIBMi
} = require('./lib/constants');
const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);
/**
* @typedef {String} Path
* @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
* @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
*/
/**
*
* @typedef {Object} WatchHelpers
* @property {Boolean} followSymlinks
* @property {'stat'|'lstat'} statMethod
* @property {Path} path
* @property {Path} watchPath
* @property {Function} entryPath
* @property {Boolean} hasGlob
* @property {Object} globFilter
* @property {Function} filterPath
* @property {Function} filterDir
*/
const arrify = (value = []) => Array.isArray(value) ? value : [value];
const flatten = (list, result = []) => {
list.forEach(item => {
if (Array.isArray(item)) {
flatten(item, result);
} else {
result.push(item);
}
});
return result;
};
const unifyPaths = (paths_) => {
/**
* @type {Array<String>}
*/
const paths = flatten(arrify(paths_));
if (!paths.every(p => typeof p === STRING_TYPE)) {
throw new TypeError(`Non-string provided as watch path: ${paths}`);
}
return paths.map(normalizePathToUnix);
};
// If SLASH_SLASH occurs at the beginning of path, it is not replaced
// because "//StoragePC/DrivePool/Movies" is a valid network path
const toUnix = (string) => {
let str = string.replace(BACK_SLASH_RE, SLASH);
let prepend = false;
if (str.startsWith(SLASH_SLASH)) {
prepend = true;
}
while (str.match(DOUBLE_SLASH_RE)) {
str = str.replace(DOUBLE_SLASH_RE, SLASH);
}
if (prepend) {
str = SLASH + str;
}
return str;
};
// Our version of upath.normalize
// TODO: this is not equal to path-normalize module - investigate why
const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
if (typeof path !== STRING_TYPE) return path;
return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
};
const getAbsolutePath = (path, cwd) => {
if (sysPath.isAbsolute(path)) {
return path;
}
if (path.startsWith(BANG)) {
return BANG + sysPath.join(cwd, path.slice(1));
}
return sysPath.join(cwd, path);
};
const undef = (opts, key) => opts[key] === undefined;
/**
* Directory entry.
* @property {Path} path
* @property {Set<Path>} items
*/
class DirEntry {
/**
* @param {Path} dir
* @param {Function} removeWatcher
*/
constructor(dir, removeWatcher) {
this.path = dir;
this._removeWatcher = removeWatcher;
/** @type {Set<Path>} */
this.items = new Set();
}
add(item) {
const {items} = this;
if (!items) return;
if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
}
async remove(item) {
const {items} = this;
if (!items) return;
items.delete(item);
if (items.size > 0) return;
const dir = this.path;
try {
await readdir(dir);
} catch (err) {
if (this._removeWatcher) {
this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
}
}
}
has(item) {
const {items} = this;
if (!items) return;
return items.has(item);
}
/**
* @returns {Array<String>}
*/
getChildren() {
const {items} = this;
if (!items) return;
return [...items.values()];
}
dispose() {
this.items.clear();
delete this.path;
delete this._removeWatcher;
delete this.items;
Object.freeze(this);
}
}
const STAT_METHOD_F = 'stat';
const STAT_METHOD_L = 'lstat';
class WatchHelper {
constructor(path, watchPath, follow, fsw) {
this.fsw = fsw;
this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
this.watchPath = watchPath;
this.fullWatchPath = sysPath.resolve(watchPath);
this.hasGlob = watchPath !== path;
/** @type {object|boolean} */
if (path === EMPTY_STR) this.hasGlob = false;
this.globSymlink = this.hasGlob && follow ? undefined : false;
this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
this.dirParts = this.getDirParts(path);
this.dirParts.forEach((parts) => {
if (parts.length > 1) parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
checkGlobSymlink(entry) {
// only need to resolve once
// first entry should always have entry.parentDir === EMPTY_STR
if (this.globSymlink === undefined) {
this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
}
if (this.globSymlink) {
return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
}
return entry.fullPath;
}
entryPath(entry) {
return sysPath.join(this.watchPath,
sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
);
}
filterPath(entry) {
const {stats} = entry;
if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
const resolvedPath = this.entryPath(entry);
const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
this.globFilter(resolvedPath) : true;
return matchesGlob &&
this.fsw._isntIgnored(resolvedPath, stats) &&
this.fsw._hasReadPermissions(stats);
}
getDirParts(path) {
if (!this.hasGlob) return [];
const parts = [];
const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
expandedPath.forEach((path) => {
parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
});
return parts;
}
filterDir(entry) {
if (this.hasGlob) {
const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
let globstar = false;
this.unmatchedGlob = !this.dirParts.some((parts) => {
return parts.every((part, i) => {
if (part === GLOBSTAR) globstar = true;
return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
});
});
}
return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
}
}
/**
* Watches files & directories for changes. Emitted events:
* `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
*
* new FSWatcher()
* .add(directories)
* .on('add', path => log('File', path, 'was added'))
*/
class FSWatcher extends EventEmitter {
// Not indenting methods for history sake; for now.
constructor(_opts) {
super();
const opts = {};
if (_opts) Object.assign(opts, _opts); // for frozen objects
/** @type {Map<String, DirEntry>} */
this._watched = new Map();
/** @type {Map<String, Array>} */
this._closers = new Map();
/** @type {Set<String>} */
this._ignoredPaths = new Set();
/** @type {Map<ThrottleType, Map>} */
this._throttled = new Map();
/** @type {Map<Path, String|Boolean>} */
this._symlinkPaths = new Map();
this._streams = new Set();
this.closed = false;
// Set up default options.
if (undef(opts, 'persistent')) opts.persistent = true;
if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
if (undef(opts, 'interval')) opts.interval = 100;
if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
// Enable fsevents on OS X when polling isn't explicitly enabled.
if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
// If we can't use fsevents, ensure the options reflect it's disabled.
const canUseFsEvents = FsEventsHandler.canUse();
if (!canUseFsEvents) opts.useFsEvents = false;
// Use polling on Mac if not using fsevents.
// Other platforms use non-polling fs_watch.
if (undef(opts, 'usePolling') && !opts.useFsEvents) {
opts.usePolling = isMacos;
}
// Always default to polling on IBM i because fs.watch() is not available on IBM i.
if(isIBMi) {
opts.usePolling = true;
}
// Global override (useful for end-developers that need to force polling for all
// instances of chokidar, regardless of usage/dependency depth)
const envPoll = process.env.CHOKIDAR_USEPOLLING;
if (envPoll !== undefined) {
const envLower = envPoll.toLowerCase();
if (envLower === 'false' || envLower === '0') {
opts.usePolling = false;
} else if (envLower === 'true' || envLower === '1') {
opts.usePolling = true;
} else {
opts.usePolling = !!envLower;
}
}
const envInterval = process.env.CHOKIDAR_INTERVAL;
if (envInterval) {
opts.interval = Number.parseInt(envInterval, 10);
}
// Editor atomic write normalization enabled by default with fs.watch
if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
if (opts.atomic) this._pendingUnlinks = new Map();
if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
const awf = opts.awaitWriteFinish;
if (awf) {
if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
if (!awf.pollInterval) awf.pollInterval = 100;
this._pendingWrites = new Map();
}
if (opts.ignored) opts.ignored = arrify(opts.ignored);
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
// use process.nextTick to allow time for listener to be bound
process.nextTick(() => this.emit(EV_READY));
}
};
this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
this._readyEmitted = false;
this.options = opts;
// Initialize with proper watcher.
if (opts.useFsEvents) {
this._fsEventsHandler = new FsEventsHandler(this);
} else {
this._nodeFsHandler = new NodeFsHandler(this);
}
// You’re frozen when your heart’s not open.
Object.freeze(opts);
}
// Public methods
/**
* Adds paths to be watched on an existing FSWatcher instance
* @param {Path|Array<Path>} paths_
* @param {String=} _origAdd private; for handling non-existent paths to be watched
* @param {Boolean=} _internal private; indicates a non-user add
* @returns {FSWatcher} for chaining
*/
add(paths_, _origAdd, _internal) {
const {cwd, disableGlobbing} = this.options;
this.closed = false;
let paths = unifyPaths(paths_);
if (cwd) {
paths = paths.map((path) => {
const absPath = getAbsolutePath(path, cwd);
// Check `path` instead of `absPath` because the cwd portion can't be a glob
if (disableGlobbing || !isGlob(path)) {
return absPath;
}
return normalizePath(absPath);
});
}
// set aside negated glob strings
paths = paths.filter((path) => {
if (path.startsWith(BANG)) {
this._ignoredPaths.add(path.slice(1));
return false;
}
// if a path is being added that was previously ignored, stop ignoring it
this._ignoredPaths.delete(path);
this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
// reset the cached userIgnored anymatch fn
// to make ignoredPaths changes effective
this._userIgnored = undefined;
return true;
});
if (this.options.useFsEvents && this._fsEventsHandler) {
if (!this._readyCount) this._readyCount = paths.length;
if (this.options.persistent) this._readyCount += paths.length;
paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
} else {
if (!this._readyCount) this._readyCount = 0;
this._readyCount += paths.length;
Promise.all(
paths.map(async path => {
const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
if (res) this._emitReady();
return res;
})
).then(results => {
if (this.closed) return;
results.filter(item => item).forEach(item => {
this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
});
});
}
return this;
}
/**
* Close watchers or start ignoring events from specified paths.
* @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
* @returns {FSWatcher} for chaining
*/
unwatch(paths_) {
if (this.closed) return this;
const paths = unifyPaths(paths_);
const {cwd} = this.options;
paths.forEach((path) => {
// convert to absolute path unless relative path already matches
if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
if (cwd) path = sysPath.join(cwd, path);
path = sysPath.resolve(path);
}
this._closePath(path);
this._ignoredPaths.add(path);
if (this._watched.has(path)) {
this._ignoredPaths.add(path + SLASH_GLOBSTAR);
}
// reset the cached userIgnored anymatch fn
// to make ignoredPaths changes effective
this._userIgnored = undefined;
});
return this;
}
/**
* Close watchers and remove all listeners from watched paths.
* @returns {Promise<void>}.
*/
close() {
if (this.closed) return this._closePromise;
this.closed = true;
// Memory management.
this.removeAllListeners();
const closers = [];
this._closers.forEach(closerList => closerList.forEach(closer => {
const promise = closer();
if (promise instanceof Promise) closers.push(promise);
}));
this._streams.forEach(stream => stream.destroy());
this._userIgnored = undefined;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach(dirent => dirent.dispose());
['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
this[`_${key}`].clear();
});
this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
return this._closePromise;
}
/**
* Expose list of watched paths
* @returns {Object} for chaining
*/
getWatched() {
const watchList = {};
this._watched.forEach((entry, dir) => {
const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
watchList[key || ONE_DOT] = entry.getChildren().sort();
});
return watchList;
}
emitWithAll(event, args) {
this.emit(...args);
if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
}
// Common helpers
// --------------
/**
* Normalize and emit events.
* Calling _emit DOES NOT MEAN emit() would be called!
* @param {EventName} event Type of event
* @param {Path} path File or directory path
* @param {*=} val1 arguments to be passed with event
* @param {*=} val2
* @param {*=} val3
* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
async _emit(event, path, val1, val2, val3) {
if (this.closed) return;
const opts = this.options;
if (isWindows) path = sysPath.normalize(path);
if (opts.cwd) path = sysPath.relative(opts.cwd, path);
/** @type Array<any> */
const args = [event, path];
if (val3 !== undefined) args.push(val1, val2, val3);
else if (val2 !== undefined) args.push(val1, val2);
else if (val1 !== undefined) args.push(val1);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path))) {
pw.lastChange = new Date();
return this;
}
if (opts.atomic) {
if (event === EV_UNLINK) {
this._pendingUnlinks.set(path, args);
setTimeout(() => {
this._pendingUnlinks.forEach((entry, path) => {
this.emit(...entry);
this.emit(EV_ALL, ...entry);
this._pendingUnlinks.delete(path);
});
}, typeof opts.atomic === 'number' ? opts.atomic : 100);
return this;
}
if (event === EV_ADD && this._pendingUnlinks.has(path)) {
event = args[0] = EV_CHANGE;
this._pendingUnlinks.delete(path);
}
}
if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
const awfEmit = (err, stats) => {
if (err) {
event = args[0] = EV_ERROR;
args[1] = err;
this.emitWithAll(event, args);
} else if (stats) {
// if stats doesn't exist the file must have been deleted
if (args.length > 2) {
args[2] = stats;
} else {
args.push(stats);
}
this.emitWithAll(event, args);
}
};
this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EV_CHANGE) {
const isThrottled = !this._throttle(EV_CHANGE, path, 50);
if (isThrottled) return this;
}
if (opts.alwaysStat && val1 === undefined &&
(event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
) {
const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
let stats;
try {
stats = await stat(fullPath);
} catch (err) {}
// Suppress event when fs_stat fails, to avoid sending undefined 'stat'
if (!stats || this.closed) return;
args.push(stats);
}
this.emitWithAll(event, args);
return this;
}
/**
* Common handler for errors
* @param {Error} error
* @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
_handleError(error) {
const code = error && error.code;
if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
(!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
) {
this.emit(EV_ERROR, error);
}
return error || this.closed;
}
/**
* Helper utility for throttling
* @param {ThrottleType} actionType type being throttled
* @param {Path} path being acted upon
* @param {Number} timeout duration of time to suppress duplicate actions
* @returns {Object|false} tracking object or false if action should be suppressed
*/
_throttle(actionType, path, timeout) {
if (!this._throttled.has(actionType)) {
this._throttled.set(actionType, new Map());
}
/** @type {Map<Path, Object>} */
const action = this._throttled.get(actionType);
/** @type {Object} */
const actionPath = action.get(path);
if (actionPath) {
actionPath.count++;
return false;
}
let timeoutObject;
const clear = () => {
const item = action.get(path);
const count = item ? item.count : 0;
action.delete(path);
clearTimeout(timeoutObject);
if (item) clearTimeout(item.timeoutObject);
return count;
};
timeoutObject = setTimeout(clear, timeout);
const thr = {timeoutObject, clear, count: 0};
action.set(path, thr);
return thr;
}
_incrReadyCount() {
return this._readyCount++;
}
/**
* Awaits write operation to finish.
* Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
* @param {Path} path being acted upon
* @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
* @param {EventName} event
* @param {Function} awfEmit Callback to be called when ready for event to be emitted.
*/
_awaitWriteFinish(path, threshold, event, awfEmit) {
let timeoutHandler;
let fullPath = path;
if (this.options.cwd && !sysPath.isAbsolute(path)) {
fullPath = sysPath.join(this.options.cwd, path);
}
const now = new Date();
const awaitWriteFinish = (prevStat) => {
fs.stat(fullPath, (err, curStat) => {
if (err || !this._pendingWrites.has(path)) {
if (err && err.code !== 'ENOENT') awfEmit(err);
return;
}
const now = Number(new Date());
if (prevStat && curStat.size !== prevStat.size) {
this._pendingWrites.get(path).lastChange = now;
}
const pw = this._pendingWrites.get(path);
const df = now - pw.lastChange;
if (df >= threshold) {
this._pendingWrites.delete(path);
awfEmit(undefined, curStat);
} else {
timeoutHandler = setTimeout(
awaitWriteFinish,
this.options.awaitWriteFinish.pollInterval,
curStat
);
}
});
};
if (!this._pendingWrites.has(path)) {
this._pendingWrites.set(path, {
lastChange: now,
cancelWait: () => {
this._pendingWrites.delete(path);
clearTimeout(timeoutHandler);
return event;
}
});
timeoutHandler = setTimeout(
awaitWriteFinish,
this.options.awaitWriteFinish.pollInterval
);
}
}
_getGlobIgnored() {
return [...this._ignoredPaths.values()];
}
/**
* Determines whether user has asked to ignore this path.
* @param {Path} path filepath or dir
* @param {fs.Stats=} stats result of fs.stat
* @returns {Boolean}
*/
_isIgnored(path, stats) {
if (this.options.atomic && DOT_RE.test(path)) return true;
if (!this._userIgnored) {
const {cwd} = this.options;
const ign = this.options.ignored;
const ignored = ign && ign.map(normalizeIgnored(cwd));
const paths = arrify(ignored)
.filter((path) => typeof path === STRING_TYPE && !isGlob(path))
.map((path) => path + SLASH_GLOBSTAR);
const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
}
return this._userIgnored([path, stats]);
}
_isntIgnored(path, stat) {
return !this._isIgnored(path, stat);
}
/**
* Provides a set of common helpers and properties relating to symlink and glob handling.
* @param {Path} path file, directory, or glob pattern being watched
* @param {Number=} depth at any depth > 0, this isn't a glob
* @returns {WatchHelper} object containing helpers for this path
*/
_getWatchHelpers(path, depth) {
const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
const follow = this.options.followSymlinks;
return new WatchHelper(path, watchPath, follow, this);
}
// Directory helpers
// -----------------
/**
* Provides directory tracking objects
* @param {String} directory path of the directory
* @returns {DirEntry} the directory's tracking object
*/
_getWatchedDir(directory) {
if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
const dir = sysPath.resolve(directory);
if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
return this._watched.get(dir);
}
// File helpers
// ------------
/**
* Check for read permissions.
* Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
* @param {fs.Stats} stats - object, result of fs_stat
* @returns {Boolean} indicates whether the file can be read
*/
_hasReadPermissions(stats) {
if (this.options.ignorePermissionErrors) return true;
// stats.mode may be bigint
const md = stats && Number.parseInt(stats.mode, 10);
const st = md & 0o777;
const it = Number.parseInt(st.toString(8)[0], 10);
return Boolean(4 & it);
}
/**
* Handles emitting unlink events for
* files and directories, and via recursion, for
* files and directories within directories that are unlinked
* @param {String} directory within which the following item is located
* @param {String} item base path of item/directory
* @returns {void}
*/
_remove(directory, item, isDirectory) {
// if what is being deleted is a directory, get that directory's paths
// for recursive deleting and cleaning of watched object
// if it is not a directory, nestedDirectoryChildren will be empty array
const path = sysPath.join(directory, item);
const fullPath = sysPath.resolve(path);
isDirectory = isDirectory != null
? isDirectory
: this._watched.has(path) || this._watched.has(fullPath);
// prevent duplicate handling in case of arriving here nearly simultaneously
// via multiple paths (such as _handleFile and _handleDir)
if (!this._throttle('remove', path, 100)) return;
// if the only watched file is removed, watch for its return
if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
this.add(directory, item, true);
}
// This will create a new entry in the watched object in either case
// so we got to do the directory check beforehand
const wp = this._getWatchedDir(path);
const nestedDirectoryChildren = wp.getChildren();
// Recursively remove children directories / files.
nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
// Check if item was on the watched list and remove it
const parent = this._getWatchedDir(directory);
const wasTracked = parent.has(item);
parent.remove(item);
// Fixes issue #1042 -> Relative paths were detected and added as symlinks
// (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
// but never removed from the map in case the path was deleted.
// This leads to an incorrect state if the path was recreated:
// https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
if (this._symlinkPaths.has(fullPath)) {
this._symlinkPaths.delete(fullPath);
}
// If we wait for this file to be fully written, cancel the wait.
let relPath = path;
if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
const event = this._pendingWrites.get(relPath).cancelWait();
if (event === EV_ADD) return;
}
// The Entry will either be a directory that just got removed
// or a bogus entry to a file, in either case we have to remove it
this._watched.delete(path);
this._watched.delete(fullPath);
const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
// Avoid conflicts if we later create another file with the same name
if (!this.options.useFsEvents) {
this._closePath(path);
}
}
/**
* Closes all watchers for a path
* @param {Path} path
*/
_closePath(path) {
this._closeFile(path)
const dir = sysPath.dirname(path);
this._getWatchedDir(dir).remove(sysPath.basename(path));
}
/**
* Closes only file-specific watchers
* @param {Path} path
*/
_closeFile(path) {
const closers = this._closers.get(path);
if (!closers) return;
closers.forEach(closer => closer());
this._closers.delete(path);
}
/**
*
* @param {Path} path
* @param {Function} closer
*/
_addPathCloser(path, closer) {
if (!closer) return;
let list = this._closers.get(path);
if (!list) {
list = [];
this._closers.set(path, list);
}
list.push(closer);
}
_readdirp(root, opts) {
if (this.closed) return;
const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
let stream = readdirp(root, options);
this._streams.add(stream);
stream.once(STR_CLOSE, () => {
stream = undefined;
});
stream.once(STR_END, () => {
if (stream) {
this._streams.delete(stream);
stream = undefined;
}
});
return stream;
}
}
// Export FSWatcher class
exports.FSWatcher = FSWatcher;
/**
* Instantiates watcher with paths to be tracked.
* @param {String|Array<String>} paths file/directory paths and/or globs
* @param {Object=} options chokidar opts
* @returns an instance of FSWatcher for chaining.
*/
const watch = (paths, options) => {
const watcher = new FSWatcher(options);
watcher.add(paths);
return watcher;
};
exports.watch = watch;
@@ -0,0 +1,66 @@
'use strict';
const {sep} = require('path');
const {platform} = process;
const os = require('os');
exports.EV_ALL = 'all';
exports.EV_READY = 'ready';
exports.EV_ADD = 'add';
exports.EV_CHANGE = 'change';
exports.EV_ADD_DIR = 'addDir';
exports.EV_UNLINK = 'unlink';
exports.EV_UNLINK_DIR = 'unlinkDir';
exports.EV_RAW = 'raw';
exports.EV_ERROR = 'error';
exports.STR_DATA = 'data';
exports.STR_END = 'end';
exports.STR_CLOSE = 'close';
exports.FSEVENT_CREATED = 'created';
exports.FSEVENT_MODIFIED = 'modified';
exports.FSEVENT_DELETED = 'deleted';
exports.FSEVENT_MOVED = 'moved';
exports.FSEVENT_CLONED = 'cloned';
exports.FSEVENT_UNKNOWN = 'unknown';
exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
exports.FSEVENT_TYPE_FILE = 'file';
exports.FSEVENT_TYPE_DIRECTORY = 'directory';
exports.FSEVENT_TYPE_SYMLINK = 'symlink';
exports.KEY_LISTENERS = 'listeners';
exports.KEY_ERR = 'errHandlers';
exports.KEY_RAW = 'rawEmitters';
exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
exports.DOT_SLASH = `.${sep}`;
exports.BACK_SLASH_RE = /\\/g;
exports.DOUBLE_SLASH_RE = /\/\//;
exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
exports.REPLACER_RE = /^\.[/\\]/;
exports.SLASH = '/';
exports.SLASH_SLASH = '//';
exports.BRACE_START = '{';
exports.BANG = '!';
exports.ONE_DOT = '.';
exports.TWO_DOTS = '..';
exports.STAR = '*';
exports.GLOBSTAR = '**';
exports.ROOT_GLOBSTAR = '/**/*';
exports.SLASH_GLOBSTAR = '/**';
exports.DIR_SUFFIX = 'Dir';
exports.ANYMATCH_OPTS = {dot: true};
exports.STRING_TYPE = 'string';
exports.FUNCTION_TYPE = 'function';
exports.EMPTY_STR = '';
exports.EMPTY_FN = () => {};
exports.IDENTITY_FN = val => val;
exports.isWindows = platform === 'win32';
exports.isMacos = platform === 'darwin';
exports.isLinux = platform === 'linux';
exports.isIBMi = os.type() === 'OS400';
@@ -0,0 +1,526 @@
'use strict';
const fs = require('fs');
const sysPath = require('path');
const { promisify } = require('util');
let fsevents;
try {
fsevents = require('fsevents');
} catch (error) {
if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
}
if (fsevents) {
// TODO: real check
const mtch = process.version.match(/v(\d+)\.(\d+)/);
if (mtch && mtch[1] && mtch[2]) {
const maj = Number.parseInt(mtch[1], 10);
const min = Number.parseInt(mtch[2], 10);
if (maj === 8 && min < 16) {
fsevents = undefined;
}
}
}
const {
EV_ADD,
EV_CHANGE,
EV_ADD_DIR,
EV_UNLINK,
EV_ERROR,
STR_DATA,
STR_END,
FSEVENT_CREATED,
FSEVENT_MODIFIED,
FSEVENT_DELETED,
FSEVENT_MOVED,
// FSEVENT_CLONED,
FSEVENT_UNKNOWN,
FSEVENT_FLAG_MUST_SCAN_SUBDIRS,
FSEVENT_TYPE_FILE,
FSEVENT_TYPE_DIRECTORY,
FSEVENT_TYPE_SYMLINK,
ROOT_GLOBSTAR,
DIR_SUFFIX,
DOT_SLASH,
FUNCTION_TYPE,
EMPTY_FN,
IDENTITY_FN
} = require('./constants');
const Depth = (value) => isNaN(value) ? {} : {depth: value};
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const realpath = promisify(fs.realpath);
const statMethods = { stat, lstat };
/**
* @typedef {String} Path
*/
/**
* @typedef {Object} FsEventsWatchContainer
* @property {Set<Function>} listeners
* @property {Function} rawEmitter
* @property {{stop: Function}} watcher
*/
// fsevents instance helper functions
/**
* Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
* @type {Map<Path,FsEventsWatchContainer>}
*/
const FSEventsWatchers = new Map();
// Threshold of duplicate path prefixes at which to start
// consolidating going forward
const consolidateThreshhold = 10;
const wrongEventFlags = new Set([
69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
]);
/**
* Instantiates the fsevents interface
* @param {Path} path path to be watched
* @param {Function} callback called when fsevents is bound and ready
* @returns {{stop: Function}} new fsevents instance
*/
const createFSEventsInstance = (path, callback) => {
const stop = fsevents.watch(path, callback);
return {stop};
};
/**
* Instantiates the fsevents interface or binds listeners to an existing one covering
* the same file tree.
* @param {Path} path - to be watched
* @param {Path} realPath - real path for symlinks
* @param {Function} listener - called when fsevents emits events
* @param {Function} rawEmitter - passes data to listeners of the 'raw' event
* @returns {Function} closer
*/
function setFSEventsListener(path, realPath, listener, rawEmitter) {
let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath;
const parentPath = sysPath.dirname(watchPath);
let cont = FSEventsWatchers.get(watchPath);
// If we've accumulated a substantial number of paths that
// could have been consolidated by watching one directory
// above the current one, create a watcher on the parent
// path instead, so that we do consolidate going forward.
if (couldConsolidate(parentPath)) {
watchPath = parentPath;
}
const resolvedPath = sysPath.resolve(path);
const hasSymlink = resolvedPath !== realPath;
const filteredListener = (fullPath, flags, info) => {
if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
if (
fullPath === resolvedPath ||
!fullPath.indexOf(resolvedPath + sysPath.sep)
) listener(fullPath, flags, info);
};
// check if there is already a watcher on a parent path
// modifies `watchPath` to the parent path when it finds a match
let watchedParent = false;
for (const watchedPath of FSEventsWatchers.keys()) {
if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {
watchPath = watchedPath;
cont = FSEventsWatchers.get(watchPath);
watchedParent = true;
break;
}
}
if (cont || watchedParent) {
cont.listeners.add(filteredListener);
} else {
cont = {
listeners: new Set([filteredListener]),
rawEmitter,
watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
if (!cont.listeners.size) return;
if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
const info = fsevents.getInfo(fullPath, flags);
cont.listeners.forEach(list => {
list(fullPath, flags, info);
});
cont.rawEmitter(info.event, fullPath, info);
})
};
FSEventsWatchers.set(watchPath, cont);
}
// removes this instance's listeners and closes the underlying fsevents
// instance if there are no more listeners left
return () => {
const lst = cont.listeners;
lst.delete(filteredListener);
if (!lst.size) {
FSEventsWatchers.delete(watchPath);
if (cont.watcher) return cont.watcher.stop().then(() => {
cont.rawEmitter = cont.watcher = undefined;
Object.freeze(cont);
});
}
};
}
// Decide whether or not we should start a new higher-level
// parent watcher
const couldConsolidate = (path) => {
let count = 0;
for (const watchPath of FSEventsWatchers.keys()) {
if (watchPath.indexOf(path) === 0) {
count++;
if (count >= consolidateThreshhold) {
return true;
}
}
}
return false;
};
// returns boolean indicating whether fsevents can be used
const canUse = () => fsevents && FSEventsWatchers.size < 128;
// determines subdirectory traversal levels from root to path
const calcDepth = (path, root) => {
let i = 0;
while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++;
return i;
};
// returns boolean indicating whether the fsevents' event info has the same type
// as the one returned by fs.stat
const sameTypes = (info, stats) => (
info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
info.type === FSEVENT_TYPE_FILE && stats.isFile()
)
/**
* @mixin
*/
class FsEventsHandler {
/**
* @param {import('../index').FSWatcher} fsw
*/
constructor(fsw) {
this.fsw = fsw;
}
checkIgnored(path, stats) {
const ipaths = this.fsw._ignoredPaths;
if (this.fsw._isIgnored(path, stats)) {
ipaths.add(path);
if (stats && stats.isDirectory()) {
ipaths.add(path + ROOT_GLOBSTAR);
}
return true;
}
ipaths.delete(path);
ipaths.delete(path + ROOT_GLOBSTAR);
}
addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
try {
const stats = await stat(path)
if (this.fsw.closed) return;
if (sameTypes(info, stats)) {
this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} catch (error) {
if (error.code === 'EACCES') {
this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
}
}
handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
if (this.fsw.closed || this.checkIgnored(path)) return;
if (event === EV_UNLINK) {
const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY
// suppress unlink events on never before seen files
if (isDirectory || watchedDir.has(item)) {
this.fsw._remove(parent, item, isDirectory);
}
} else {
if (event === EV_ADD) {
// track new directories
if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
// push symlinks back to the top of the stack to get handled
const curDepth = opts.depth === undefined ?
undefined : calcDepth(fullPath, realPath) + 1;
return this._addToFsEvents(path, false, true, curDepth);
}
// track new paths
// (other than symlinks being followed, which will be tracked soon)
this.fsw._getWatchedDir(parent).add(item);
}
/**
* @type {'add'|'addDir'|'unlink'|'unlinkDir'}
*/
const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
this.fsw._emit(eventName, path);
if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
}
}
/**
* Handle symlinks encountered during directory scan
* @param {String} watchPath - file/dir path to be watched with fsevents
* @param {String} realPath - real path (in case of symlinks)
* @param {Function} transform - path transformer
* @param {Function} globFilter - path filter in case a glob pattern was provided
* @returns {Function} closer for the watcher instance
*/
_watchWithFsEvents(watchPath, realPath, transform, globFilter) {
if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
const opts = this.fsw.options;
const watchCallback = async (fullPath, flags, info) => {
if (this.fsw.closed) return;
if (
opts.depth !== undefined &&
calcDepth(fullPath, realPath) > opts.depth
) return;
const path = transform(sysPath.join(
watchPath, sysPath.relative(watchPath, fullPath)
));
if (globFilter && !globFilter(path)) return;
// ensure directories are tracked
const parent = sysPath.dirname(path);
const item = sysPath.basename(path);
const watchedDir = this.fsw._getWatchedDir(
info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
);
// correct for wrong events emitted
if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
if (typeof opts.ignored === FUNCTION_TYPE) {
let stats;
try {
stats = await stat(path);
} catch (error) {}
if (this.fsw.closed) return;
if (this.checkIgnored(path, stats)) return;
if (sameTypes(info, stats)) {
this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} else {
this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} else {
switch (info.event) {
case FSEVENT_CREATED:
case FSEVENT_MODIFIED:
return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
case FSEVENT_DELETED:
case FSEVENT_MOVED:
return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
}
}
};
const closer = setFSEventsListener(
watchPath,
realPath,
watchCallback,
this.fsw._emitRaw
);
this.fsw._emitReady();
return closer;
}
/**
* Handle symlinks encountered during directory scan
* @param {String} linkPath path to symlink
* @param {String} fullPath absolute path to the symlink
* @param {Function} transform pre-existing path transformer
* @param {Number} curDepth level of subdirectories traversed to where symlink is
* @returns {Promise<void>}
*/
async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
// don't follow the same symlink more than once
if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
this.fsw._symlinkPaths.set(fullPath, true);
this.fsw._incrReadyCount();
try {
const linkTarget = await realpath(linkPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(linkTarget)) {
return this.fsw._emitReady();
}
this.fsw._incrReadyCount();
// add the linkTarget for watching with a wrapper for transform
// that causes emitted paths to incorporate the link's path
this._addToFsEvents(linkTarget || linkPath, (path) => {
let aliasedPath = linkPath;
if (linkTarget && linkTarget !== DOT_SLASH) {
aliasedPath = path.replace(linkTarget, linkPath);
} else if (path !== DOT_SLASH) {
aliasedPath = sysPath.join(linkPath, path);
}
return transform(aliasedPath);
}, false, curDepth);
} catch(error) {
if (this.fsw._handleError(error)) {
return this.fsw._emitReady();
}
}
}
/**
*
* @param {Path} newPath
* @param {fs.Stats} stats
*/
emitAdd(newPath, stats, processPath, opts, forceAdd) {
const pp = processPath(newPath);
const isDir = stats.isDirectory();
const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp));
const base = sysPath.basename(pp);
// ensure empty dirs get tracked
if (isDir) this.fsw._getWatchedDir(pp);
if (dirObj.has(base)) return;
dirObj.add(base);
if (!opts.ignoreInitial || forceAdd === true) {
this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats);
}
}
initWatch(realPath, path, wh, processPath) {
if (this.fsw.closed) return;
const closer = this._watchWithFsEvents(
wh.watchPath,
sysPath.resolve(realPath || wh.watchPath),
processPath,
wh.globFilter
);
this.fsw._addPathCloser(path, closer);
}
/**
* Handle added path with fsevents
* @param {String} path file/dir path or glob pattern
* @param {Function|Boolean=} transform converts working path to what the user expects
* @param {Boolean=} forceAdd ensure add is emitted
* @param {Number=} priorDepth Level of subdirectories already traversed.
* @returns {Promise<void>}
*/
async _addToFsEvents(path, transform, forceAdd, priorDepth) {
if (this.fsw.closed) {
return;
}
const opts = this.fsw.options;
const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
const wh = this.fsw._getWatchHelpers(path);
// evaluate what is at the path we're being asked to watch
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
throw null;
}
if (stats.isDirectory()) {
// emit addDir unless this is a glob parent
if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
// don't recurse further if it would exceed depth setting
if (priorDepth && priorDepth > opts.depth) return;
// scan the contents of the dir
this.fsw._readdirp(wh.watchPath, {
fileFilter: entry => wh.filterPath(entry),
directoryFilter: entry => wh.filterDir(entry),
...Depth(opts.depth - (priorDepth || 0))
}).on(STR_DATA, (entry) => {
// need to check filterPath on dirs b/c filterDir is less restrictive
if (this.fsw.closed) {
return;
}
if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
const joinedPath = sysPath.join(wh.watchPath, entry.path);
const {fullPath} = entry;
if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
// preserve the current depth here since it can't be derived from
// real paths past the symlink
const curDepth = opts.depth === undefined ?
undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1;
this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
} else {
this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
}
}).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
this.fsw._emitReady();
});
} else {
this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
this.fsw._emitReady();
}
} catch (error) {
if (!error || this.fsw._handleError(error)) {
// TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
this.fsw._emitReady();
this.fsw._emitReady();
}
}
if (opts.persistent && forceAdd !== true) {
if (typeof transform === FUNCTION_TYPE) {
// realpath has already been resolved
this.initWatch(undefined, path, wh, processPath);
} else {
let realPath;
try {
realPath = await realpath(wh.watchPath);
} catch (e) {}
this.initWatch(realPath, path, wh, processPath);
}
}
}
}
module.exports = FsEventsHandler;
module.exports.canUse = canUse;
@@ -0,0 +1,654 @@
'use strict';
const fs = require('fs');
const sysPath = require('path');
const { promisify } = require('util');
const isBinaryPath = require('is-binary-path');
const {
isWindows,
isLinux,
EMPTY_FN,
EMPTY_STR,
KEY_LISTENERS,
KEY_ERR,
KEY_RAW,
HANDLER_KEYS,
EV_CHANGE,
EV_ADD,
EV_ADD_DIR,
EV_ERROR,
STR_DATA,
STR_END,
BRACE_START,
STAR
} = require('./constants');
const THROTTLE_MODE_WATCH = 'watch';
const open = promisify(fs.open);
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const close = promisify(fs.close);
const fsrealpath = promisify(fs.realpath);
const statMethods = { lstat, stat };
// TODO: emit errors properly. Example: EMFILE on Macos.
const foreach = (val, fn) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
};
const addAndConvert = (main, prop, item) => {
let container = main[prop];
if (!(container instanceof Set)) {
main[prop] = container = new Set([container]);
}
container.add(item);
};
const clearItem = cont => key => {
const set = cont[key];
if (set instanceof Set) {
set.clear();
} else {
delete cont[key];
}
};
const delFromSet = (main, prop, item) => {
const container = main[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main[prop];
}
};
const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
/**
* @typedef {String} Path
*/
// fs_watch helpers
// object to hold per-process fs_watch instances
// (may be shared across chokidar FSWatcher instances)
/**
* @typedef {Object} FsWatchContainer
* @property {Set} listeners
* @property {Set} errHandlers
* @property {Set} rawEmitters
* @property {fs.FSWatcher=} watcher
* @property {Boolean=} watcherUnusable
*/
/**
* @type {Map<String,FsWatchContainer>}
*/
const FsWatchInstances = new Map();
/**
* Instantiates the fs_watch interface
* @param {String} path to be watched
* @param {Object} options to be passed to fs_watch
* @param {Function} listener main event handler
* @param {Function} errHandler emits info about errors
* @param {Function} emitRaw emits raw event data
* @returns {fs.FSWatcher} new fsevents instance
*/
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path);
emitRaw(rawEvent, evPath, {watchedPath: path});
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (and rely on throttling to de-dupe)
if (evPath && path !== evPath) {
fsWatchBroadcast(
sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
);
}
};
try {
return fs.watch(path, options, handleEvent);
} catch (error) {
errHandler(error);
}
}
/**
* Helper for passing fs_watch event data to a collection of listeners
* @param {Path} fullPath absolute path bound to fs_watch instance
* @param {String} type listener type
* @param {*=} val1 arguments to be passed to listeners
* @param {*=} val2
* @param {*=} val3
*/
const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[type], (listener) => {
listener(val1, val2, val3);
});
};
/**
* Instantiates the fs_watch interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path
* @param {String} fullPath absolute path
* @param {Object} options to be passed to fs_watch
* @param {Object} handlers container for event listener functions
*/
const setFsWatchListener = (path, fullPath, options, handlers) => {
const {listener, errHandler, rawEmitter} = handlers;
let cont = FsWatchInstances.get(fullPath);
/** @type {fs.FSWatcher=} */
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(
path, options, listener, errHandler, rawEmitter
);
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(
path,
options,
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
errHandler, // no need to use broadcast here
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
);
if (!watcher) return;
watcher.on(EV_ERROR, async (error) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
cont.watcherUnusable = true; // documented since Node 10.4.1
// Workaround for https://github.com/joyent/node/issues/4337
if (isWindows && error.code === 'EPERM') {
try {
const fd = await open(path, 'r');
await close(fd);
broadcastErr(error);
} catch (err) {}
} else {
broadcastErr(error);
}
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// removes this instance's listeners and closes the underlying fs_watch
// instance if there are no more listeners left
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
// Check to protect against issue gh-730.
// if (cont.watcherUnusable) {
cont.watcher.close();
// }
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = undefined;
Object.freeze(cont);
}
};
};
// fs_watchFile helpers
// object to hold per-process fs_watchFile instances
// (may be shared across chokidar FSWatcher instances)
const FsWatchFileInstances = new Map();
/**
* Instantiates the fs_watchFile interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path to be watched
* @param {String} fullPath absolute path
* @param {Object} options options to be passed to fs_watchFile
* @param {Object} handlers container for event listener functions
* @returns {Function} closer
*/
const setFsWatchFileListener = (path, fullPath, options, handlers) => {
const {listener, rawEmitter} = handlers;
let cont = FsWatchFileInstances.get(fullPath);
/* eslint-disable no-unused-vars, prefer-destructuring */
let listeners = new Set();
let rawEmitters = new Set();
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
// "Upgrade" the watcher to persistence or a quicker interval.
// This creates some unlikely edge case issues if the user mixes
// settings in a very weird way, but solving for those cases
// doesn't seem worthwhile for the added complexity.
listeners = cont.listeners;
rawEmitters = cont.rawEmitters;
fs.unwatchFile(fullPath);
cont = undefined;
}
/* eslint-enable no-unused-vars, prefer-destructuring */
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
// TODO
// listeners.add(listener);
// rawEmitters.add(rawEmitter);
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: fs.watchFile(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter) => {
rawEmitter(EV_CHANGE, fullPath, {curr, prev});
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener) => listener(path, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// Removes this instance's listeners and closes the underlying fs_watchFile
// instance if there are no more listeners left.
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
fs.unwatchFile(fullPath);
cont.options = cont.watcher = undefined;
Object.freeze(cont);
}
};
};
/**
* @mixin
*/
class NodeFsHandler {
/**
* @param {import("../index").FSWatcher} fsW
*/
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error) => fsW._handleError(error);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param {String} path to file or dir
* @param {Function} listener on fs change
* @returns {Function} closer for the watcher instance
*/
_watchWithNodeFs(path, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path);
const basename = sysPath.basename(path);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename);
const absolutePath = sysPath.resolve(path);
const options = {persistent: opts.persistent};
if (!listener) listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @param {Path} file Path
* @param {fs.Stats} stats result of fs_stat
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @returns {Function} closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname = sysPath.dirname(file);
const basename = sysPath.basename(file);
const parent = this.fsw._getWatchedDir(dirname);
// stats is always present
let prevStats = stats;
// if the file is already being watched, do nothing
if (parent.has(basename)) return;
const listener = async (path, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats = await stat(file);
if (this.fsw.closed) return;
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
if (isLinux && prevStats.ino !== newStats.ino) {
this.fsw._closeFile(path)
prevStats = newStats;
this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
} else {
prevStats = newStats;
}
} catch (error) {
// Fix issues where mtime is null but file is still present
this.fsw._remove(dirname, basename);
}
// add is about to be emitted if file not already tracked in parent
} else if (parent.has(basename)) {
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
prevStats = newStats;
}
}
// kick off the watcher
const closer = this._watchWithNodeFs(file, listener);
// emit an add event if we're supposed to
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV_ADD, file, 0)) return;
this.fsw._emit(EV_ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param {Object} entry returned by readdirp
* @param {String} directory path of dir being read
* @param {String} path of this item
* @param {String} item basename of this item
* @returns {Promise<Boolean>} true if no more processing is needed for this entry.
*/
async _handleSymlink(entry, directory, path, item) {
if (this.fsw.closed) {
return;
}
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
// watch symlink directly (don't follow) and detect changes
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_CHANGE, path, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_ADD, path, entry.stats);
}
this.fsw._emitReady();
return true;
}
// don't follow the same symlink more than once
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
// Normalize the directory name on Windows
directory = sysPath.join(directory, EMPTY_STR);
if (!wh.hasGlob) {
throttler = this.fsw._throttle('readdir', directory, 1000);
if (!throttler) return;
}
const previous = this.fsw._getWatchedDir(wh.path);
const current = new Set();
let stream = this.fsw._readdirp(directory, {
fileFilter: entry => wh.filterPath(entry),
directoryFilter: entry => wh.filterDir(entry),
depth: 0
}).on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const item = entry.path;
let path = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
return;
}
if (this.fsw.closed) {
stream = undefined;
return;
}
// Files that present in current directory snapshot
// but absent in previous are added to watch list and
// emit `add` event.
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
// ensure relativeness of path is preserved in case of watcher reuse
path = sysPath.join(dir, sysPath.relative(dir, path));
this._addToNodeFs(path, initialAdd, wh, depth + 1);
}
}).on(EV_ERROR, this._boundHandleError);
return new Promise(resolve =>
stream.once(STR_END, () => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve();
// Files that absent in current directory snapshot
// but present in previous emit `remove` event
// and are removed from @watched[directory].
previous.getChildren().filter((item) => {
return item !== directory &&
!current.has(item) &&
// in case of intersecting globs;
// a path may have been filtered out of this readdir, but
// shouldn't be removed because it matches a different glob
(!wh.hasGlob || wh.filterPath({
fullPath: sysPath.resolve(directory, item)
}));
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream = undefined;
// one more time for any missed in case changes came in extremely quickly
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
})
);
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param {String} dir fs path
* @param {fs.Stats} stats
* @param {Boolean} initialAdd
* @param {Number} depth relative to user-supplied path
* @param {String} target child path targeted for watch
* @param {Object} wh Common watch helpers for this path
* @param {String} realpath
* @returns {Promise<Function>} closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
}
// ensure dir is tracked (harmless if redundant)
parentDir.add(sysPath.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
// if current directory is removed, do nothing
if (stats && stats.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param {String} path to file or ir
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @param {Object} priorWh depth relative to user-supplied path
* @param {Number} depth Child path actually targeted for watch
* @param {String=} target Child path actually targeted for watch
* @returns {Promise}
*/
async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path, depth);
if (!wh.hasGlob && priorWh) {
wh.hasGlob = priorWh.hasGlob;
wh.globFilter = priorWh.globFilter;
wh.filterPath = entry => priorWh.filterPath(entry);
wh.filterDir = entry => priorWh.filterDir(entry);
}
// evaluate what is at the path we're being asked to watch
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path);
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (absPath !== targetPath && targetPath !== undefined) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
const parent = sysPath.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV_ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (targetPath !== undefined) {
this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
this.fsw._addPathCloser(path, closer);
return false;
} catch (error) {
if (this.fsw._handleError(error)) {
ready();
return path;
}
}
}
}
module.exports = NodeFsHandler;
@@ -0,0 +1,70 @@
{
"name": "chokidar",
"description": "Minimal and efficient cross-platform file watching library",
"version": "3.6.0",
"homepage": "https://github.com/paulmillr/chokidar",
"author": "Paul Miller (https://paulmillr.com)",
"contributors": [
"Paul Miller (https://paulmillr.com)",
"Elan Shanker"
],
"engines": {
"node": ">= 8.10.0"
},
"main": "index.js",
"types": "./types/index.d.ts",
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
},
"devDependencies": {
"@types/node": "^14",
"chai": "^4.3",
"dtslint": "^3.3.0",
"eslint": "^7.0.0",
"mocha": "^7.0.0",
"rimraf": "^3.0.0",
"sinon": "^9.0.1",
"sinon-chai": "^3.3.0",
"typescript": "^4.4.3",
"upath": "^1.2.0"
},
"files": [
"index.js",
"lib/*.js",
"types/index.d.ts"
],
"repository": {
"type": "git",
"url": "git+https://github.com/paulmillr/chokidar.git"
},
"bugs": {
"url": "https://github.com/paulmillr/chokidar/issues"
},
"license": "MIT",
"scripts": {
"dtslint": "dtslint types",
"lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .",
"build": "npm ls",
"mocha": "mocha --exit --timeout 90000",
"test": "npm run lint && npm run mocha"
},
"keywords": [
"fs",
"watch",
"watchFile",
"watcher",
"watching",
"file",
"fsevents"
],
"funding": "https://paulmillr.com/funding/"
}
@@ -0,0 +1,192 @@
// TypeScript Version: 3.0
/// <reference types="node" />
import * as fs from "fs";
import { EventEmitter } from "events";
import { Matcher } from 'anymatch';
export class FSWatcher extends EventEmitter implements fs.FSWatcher {
options: WatchOptions;
/**
* Constructs a new FSWatcher instance with optional WatchOptions parameter.
*/
constructor(options?: WatchOptions);
/**
* Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
* string.
*/
add(paths: string | ReadonlyArray<string>): this;
/**
* Stop watching files, directories, or glob patterns. Takes an array of strings or just one
* string.
*/
unwatch(paths: string | ReadonlyArray<string>): this;
/**
* Returns an object representing all the paths on the file system being watched by this
* `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
* the `cwd` option was used), and the values are arrays of the names of the items contained in
* each directory.
*/
getWatched(): {
[directory: string]: string[];
};
/**
* Removes all listeners from watched files.
*/
close(): Promise<void>;
on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this;
on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this;
/**
* Error occurred
*/
on(event: 'error', listener: (error: Error) => void): this;
/**
* Exposes the native Node `fs.FSWatcher events`
*/
on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this;
/**
* Fires when the initial scan is complete
*/
on(event: 'ready', listener: () => void): this;
on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
ref(): this;
unref(): this;
}
export interface WatchOptions {
/**
* Indicates whether the process should continue to run as long as files are being watched. If
* set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
* even if the process continues to run.
*/
persistent?: boolean;
/**
* ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
* be ignored. The whole relative or absolute path is tested, not just filename. If a function
* with two arguments is provided, it gets called twice per path - once with a single argument
* (the path), second time with two arguments (the path and the
* [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
*/
ignored?: Matcher;
/**
* If set to `false` then `add`/`addDir` events are also emitted for matching paths while
* instantiating the watching as chokidar discovers these file paths (before the `ready` event).
*/
ignoreInitial?: boolean;
/**
* When `false`, only the symlinks themselves will be watched for changes instead of following
* the link references and bubbling events through the link's path.
*/
followSymlinks?: boolean;
/**
* The base directory from which watch `paths` are to be derived. Paths emitted with events will
* be relative to this.
*/
cwd?: string;
/**
* If set to true then the strings passed to .watch() and .add() are treated as literal path
* names, even if they look like globs. Default: false.
*/
disableGlobbing?: boolean;
/**
* Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
* utilization, consider setting this to `false`. It is typically necessary to **set this to
* `true` to successfully watch files over a network**, and it may be necessary to successfully
* watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
* the `useFsEvents` default.
*/
usePolling?: boolean;
/**
* Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
* and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on
* OS X, `usePolling: true` becomes the default.
*/
useFsEvents?: boolean;
/**
* If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
* may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
* provided even in cases where it wasn't already available from the underlying watch events.
*/
alwaysStat?: boolean;
/**
* If set, limits how many levels of subdirectories will be traversed.
*/
depth?: number;
/**
* Interval of file system polling.
*/
interval?: number;
/**
* Interval of file system polling for binary files. ([see list of binary extensions](https://gi
* thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
*/
binaryInterval?: number;
/**
* Indicates whether to watch files that don't have read permissions if possible. If watching
* fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
* silently.
*/
ignorePermissionErrors?: boolean;
/**
* `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts
* that occur when using editors that use "atomic writes" instead of writing directly to the
* source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
* event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
* you can override it by setting `atomic` to a custom value, in milliseconds.
*/
atomic?: boolean | number;
/**
* can be set to an object in order to adjust timing params:
*/
awaitWriteFinish?: AwaitWriteFinishOptions | boolean;
}
export interface AwaitWriteFinishOptions {
/**
* Amount of time in milliseconds for a file size to remain constant before emitting its event.
*/
stabilityThreshold?: number;
/**
* File size polling interval.
*/
pollInterval?: number;
}
/**
* produces an instance of `FSWatcher`.
*/
export function watch(
paths: string | ReadonlyArray<string>,
options?: WatchOptions
): FSWatcher;
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.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.
@@ -0,0 +1,122 @@
# readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp)
Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**.
```sh
npm install readdirp
```
```javascript
const readdirp = require('readdirp');
// Use streams to achieve small RAM & CPU footprint.
// 1) Streams example with for-await.
for await (const entry of readdirp('.')) {
const {path} = entry;
console.log(`${JSON.stringify({path})}`);
}
// 2) Streams example, non for-await.
// Print out all JS files along with their size within the current folder & subfolders.
readdirp('.', {fileFilter: '*.js', alwaysStat: true})
.on('data', (entry) => {
const {path, stats: {size}} = entry;
console.log(`${JSON.stringify({path, size})}`);
})
// Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted
.on('warn', error => console.error('non-fatal error', error))
.on('error', error => console.error('fatal error', error))
.on('end', () => console.log('done'));
// 3) Promise example. More RAM and CPU than streams / for-await.
const files = await readdirp.promise('.');
console.log(files.map(file => file.path));
// Other options.
readdirp('test', {
fileFilter: '*.js',
directoryFilter: ['!.git', '!*modules']
// directoryFilter: (di) => di.basename.length === 9
type: 'files_directories',
depth: 1
});
```
For more examples, check out `examples` directory.
## API
`const stream = readdirp(root[, options])` — **Stream API**
- Reads given root recursively and returns a `stream` of [entry infos](#entryinfo)
- Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`).
- `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir.
- `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user.
- `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed.
- `on('end')` — we are done. Called when all entries were found and no more will be emitted.
- `on('close')` — stream is destroyed via `stream.destroy()`.
Could be useful if you want to manually abort even on a non fatal error.
At that point the stream is no longer `readable` and no more entries, warning or errors are emitted
- To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html)
or the [stream-handbook](https://github.com/substack/stream-handbook)
`const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo).
First argument is awalys `root`, path in which to start reading and recursing into subdirectories.
### options
- `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings.
- **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
- **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more
information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files.
- **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown.
`['*.json', '*.js']` includes all JavaScript and Json files.
`['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'.
- Directories that do not pass a filter will not be recursed into.
- `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into.
- `depth: 5`: depth at which to stop recursing even if more subdirectories are found
- `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes.
- `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0.
- `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat`
### `EntryInfo`
Has the following properties:
- `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root)
- `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found
- `basename: 'react.js'`: name of the file/directory
- `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false`
- `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true`
## Changelog
- 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks.
Before, it could have entered infinite loop.
- 3.4 (Mar 19, 2020) adds support for directory-based symlinks.
- 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping.
- 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic.
- 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions".
- 3.0 brings huge performance improvements and stream backpressure support.
- Upgrading 2.x to 3.x:
- Signature changed from `readdirp(options)` to `readdirp(root, options)`
- Replaced callback API with promise API.
- Renamed `entryType` option to `type`
- Renamed `entryType: 'both'` to `'files_directories'`
- `EntryInfo`
- Renamed `stat` to `stats`
- Emitted only when `alwaysStat: true`
- `dirent` is emitted instead of `stats` by default with `alwaysStat: false`
- Renamed `name` to `basename`
- Removed `parentDir` and `fullParentDir` properties
- Supported node.js versions:
- 3.x: node 8+
- 2.x: node 0.6+
## License
Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (<https://paulmillr.com>)
MIT License, see [LICENSE](LICENSE) file.
@@ -0,0 +1,43 @@
// TypeScript Version: 3.2
/// <reference types="node" lib="esnext" />
import * as fs from 'fs';
import { Readable } from 'stream';
declare namespace readdir {
interface EntryInfo {
path: string;
fullPath: string;
basename: string;
stats?: fs.Stats;
dirent?: fs.Dirent;
}
interface ReaddirpOptions {
root?: string;
fileFilter?: string | string[] | ((entry: EntryInfo) => boolean);
directoryFilter?: string | string[] | ((entry: EntryInfo) => boolean);
type?: 'files' | 'directories' | 'files_directories' | 'all';
lstat?: boolean;
depth?: number;
alwaysStat?: boolean;
}
interface ReaddirpStream extends Readable, AsyncIterable<EntryInfo> {
read(): EntryInfo;
[Symbol.asyncIterator](): AsyncIterableIterator<EntryInfo>;
}
function promise(
root: string,
options?: ReaddirpOptions
): Promise<EntryInfo[]>;
}
declare function readdir(
root: string,
options?: readdir.ReaddirpOptions
): readdir.ReaddirpStream;
export = readdir;
@@ -0,0 +1,287 @@
'use strict';
const fs = require('fs');
const { Readable } = require('stream');
const sysPath = require('path');
const { promisify } = require('util');
const picomatch = require('picomatch');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const realpath = promisify(fs.realpath);
/**
* @typedef {Object} EntryInfo
* @property {String} path
* @property {String} fullPath
* @property {fs.Stats=} stats
* @property {fs.Dirent=} dirent
* @property {String} basename
*/
const BANG = '!';
const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
const FILE_TYPE = 'files';
const DIR_TYPE = 'directories';
const FILE_DIR_TYPE = 'files_directories';
const EVERYTHING_TYPE = 'all';
const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
const normalizeFilter = filter => {
if (filter === undefined) return;
if (typeof filter === 'function') return filter;
if (typeof filter === 'string') {
const glob = picomatch(filter.trim());
return entry => glob(entry.basename);
}
if (Array.isArray(filter)) {
const positive = [];
const negative = [];
for (const item of filter) {
const trimmed = item.trim();
if (trimmed.charAt(0) === BANG) {
negative.push(picomatch(trimmed.slice(1)));
} else {
positive.push(picomatch(trimmed));
}
}
if (negative.length > 0) {
if (positive.length > 0) {
return entry =>
positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
}
return entry => !negative.some(f => f(entry.basename));
}
return entry => positive.some(f => f(entry.basename));
}
};
class ReaddirpStream extends Readable {
static get defaultOptions() {
return {
root: '.',
/* eslint-disable no-unused-vars */
fileFilter: (path) => true,
directoryFilter: (path) => true,
/* eslint-enable no-unused-vars */
type: FILE_TYPE,
lstat: false,
depth: 2147483648,
alwaysStat: false
};
}
constructor(options = {}) {
super({
objectMode: true,
autoDestroy: true,
highWaterMark: options.highWaterMark || 4096
});
const opts = { ...ReaddirpStream.defaultOptions, ...options };
const { root, type } = opts;
this._fileFilter = normalizeFilter(opts.fileFilter);
this._directoryFilter = normalizeFilter(opts.directoryFilter);
const statMethod = opts.lstat ? lstat : stat;
// Use bigint stats if it's windows and stat() supports options (node 10+).
if (wantBigintFsStats) {
this._stat = path => statMethod(path, { bigint: true });
} else {
this._stat = statMethod;
}
this._maxDepth = opts.depth;
this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
this._wantsEverything = type === EVERYTHING_TYPE;
this._root = sysPath.resolve(root);
this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;
this._statsProp = this._isDirent ? 'dirent' : 'stats';
this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
// Launch stream with one parent, the root dir.
this.parents = [this._exploreDir(root, 1)];
this.reading = false;
this.parent = undefined;
}
async _read(batch) {
if (this.reading) return;
this.reading = true;
try {
while (!this.destroyed && batch > 0) {
const { path, depth, files = [] } = this.parent || {};
if (files.length > 0) {
const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
for (const entry of await Promise.all(slice)) {
if (this.destroyed) return;
const entryType = await this._getEntryType(entry);
if (entryType === 'directory' && this._directoryFilter(entry)) {
if (depth <= this._maxDepth) {
this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
}
if (this._wantsDir) {
this.push(entry);
batch--;
}
} else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
if (this._wantsFile) {
this.push(entry);
batch--;
}
}
}
} else {
const parent = this.parents.pop();
if (!parent) {
this.push(null);
break;
}
this.parent = await parent;
if (this.destroyed) return;
}
}
} catch (error) {
this.destroy(error);
} finally {
this.reading = false;
}
}
async _exploreDir(path, depth) {
let files;
try {
files = await readdir(path, this._rdOptions);
} catch (error) {
this._onError(error);
}
return { files, depth, path };
}
async _formatEntry(dirent, path) {
let entry;
try {
const basename = this._isDirent ? dirent.name : dirent;
const fullPath = sysPath.resolve(sysPath.join(path, basename));
entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename };
entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
} catch (err) {
this._onError(err);
}
return entry;
}
_onError(err) {
if (isNormalFlowError(err) && !this.destroyed) {
this.emit('warn', err);
} else {
this.destroy(err);
}
}
async _getEntryType(entry) {
// entry may be undefined, because a warning or an error were emitted
// and the statsProp is undefined
const stats = entry && entry[this._statsProp];
if (!stats) {
return;
}
if (stats.isFile()) {
return 'file';
}
if (stats.isDirectory()) {
return 'directory';
}
if (stats && stats.isSymbolicLink()) {
const full = entry.fullPath;
try {
const entryRealPath = await realpath(full);
const entryRealPathStats = await lstat(entryRealPath);
if (entryRealPathStats.isFile()) {
return 'file';
}
if (entryRealPathStats.isDirectory()) {
const len = entryRealPath.length;
if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) {
const recursiveError = new Error(
`Circular symlink detected: "${full}" points to "${entryRealPath}"`
);
recursiveError.code = RECURSIVE_ERROR_CODE;
return this._onError(recursiveError);
}
return 'directory';
}
} catch (error) {
this._onError(error);
}
}
}
_includeAsFile(entry) {
const stats = entry && entry[this._statsProp];
return stats && this._wantsEverything && !stats.isDirectory();
}
}
/**
* @typedef {Object} ReaddirpArguments
* @property {Function=} fileFilter
* @property {Function=} directoryFilter
* @property {String=} type
* @property {Number=} depth
* @property {String=} root
* @property {Boolean=} lstat
* @property {Boolean=} bigint
*/
/**
* Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
* @param {String} root Root directory
* @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
*/
const readdirp = (root, options = {}) => {
let type = options.entryType || options.type;
if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
if (type) options.type = type;
if (!root) {
throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
} else if (typeof root !== 'string') {
throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
} else if (type && !ALL_TYPES.includes(type)) {
throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
}
options.root = root;
return new ReaddirpStream(options);
};
const readdirpPromise = (root, options = {}) => {
return new Promise((resolve, reject) => {
const files = [];
readdirp(root, options)
.on('data', entry => files.push(entry))
.on('end', () => resolve(files))
.on('error', error => reject(error));
});
};
readdirp.promise = readdirpPromise;
readdirp.ReaddirpStream = ReaddirpStream;
readdirp.default = readdirp;
module.exports = readdirp;
@@ -0,0 +1,122 @@
{
"name": "readdirp",
"description": "Recursive version of fs.readdir with streaming API.",
"version": "3.6.0",
"homepage": "https://github.com/paulmillr/readdirp",
"repository": {
"type": "git",
"url": "git://github.com/paulmillr/readdirp.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/paulmillr/readdirp/issues"
},
"author": "Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)",
"contributors": [
"Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)",
"Paul Miller (https://paulmillr.com)"
],
"main": "index.js",
"engines": {
"node": ">=8.10.0"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"recursive",
"fs",
"stream",
"streams",
"readdir",
"filesystem",
"find",
"filter"
],
"scripts": {
"dtslint": "dtslint",
"nyc": "nyc",
"mocha": "mocha --exit",
"lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .",
"test": "npm run lint && nyc npm run mocha"
},
"dependencies": {
"picomatch": "^2.2.1"
},
"devDependencies": {
"@types/node": "^14",
"chai": "^4.2",
"chai-subset": "^1.6",
"dtslint": "^3.3.0",
"eslint": "^7.0.0",
"mocha": "^7.1.1",
"nyc": "^15.0.0",
"rimraf": "^3.0.0",
"typescript": "^4.0.3"
},
"nyc": {
"reporter": [
"html",
"text"
]
},
"eslintConfig": {
"root": true,
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "script"
},
"env": {
"node": true,
"es6": true
},
"rules": {
"array-callback-return": "error",
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"no-else-return": [
"error",
{
"allowElseIf": false
}
],
"no-lonely-if": "error",
"no-var": "error",
"object-shorthand": "error",
"prefer-arrow-callback": [
"error",
{
"allowNamedFunctions": true
}
],
"prefer-const": [
"error",
{
"ignoreReadBeforeAssign": true
}
],
"prefer-destructuring": [
"error",
{
"object": true,
"array": false
}
],
"prefer-spread": "error",
"prefer-template": "error",
"radix": "error",
"semi": "error",
"strict": "error",
"quotes": [
"error",
"single"
]
}
}
}
+130
View File
@@ -0,0 +1,130 @@
{
"name": "unplugin-vue-components",
"type": "module",
"version": "0.28.0",
"packageManager": "pnpm@9.15.0",
"description": "Components auto importing for Vue",
"author": "antfu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/unplugin/unplugin-vue-components#readme",
"repository": {
"type": "git",
"url": "https://github.com/unplugin/unplugin-vue-components.git"
},
"bugs": "https://github.com/unplugin/unplugin-vue-components/issues",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./nuxt": {
"import": "./dist/nuxt.js",
"require": "./dist/nuxt.cjs"
},
"./resolvers": {
"import": "./dist/resolvers.js",
"require": "./dist/resolvers.cjs"
},
"./rollup": {
"import": "./dist/rollup.js",
"require": "./dist/rollup.cjs"
},
"./types": {
"import": "./dist/types.js",
"require": "./dist/types.cjs"
},
"./vite": {
"import": "./dist/vite.js",
"require": "./dist/vite.cjs"
},
"./webpack": {
"import": "./dist/webpack.js",
"require": "./dist/webpack.cjs"
},
"./rspack": {
"import": "./dist/rspack.js",
"require": "./dist/rspack.cjs"
},
"./esbuild": {
"import": "./dist/esbuild.js",
"require": "./dist/esbuild.cjs"
},
"./*": "./*"
},
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "index.d.ts",
"typesVersions": {
"*": {
"*": [
"./dist/*"
]
}
},
"files": [
"dist"
],
"engines": {
"node": ">=14"
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch src",
"example:build": "npm -C examples/vite-vue3 run build",
"example:dev": "npm -C examples/vite-vue3 run dev",
"prepublishOnly": "npm run build",
"lint": "eslint .",
"release": "bumpp && npm publish",
"test": "vitest",
"test:update": "vitest --u"
},
"peerDependencies": {
"@babel/parser": "^7.15.8",
"@nuxt/kit": "^3.2.2",
"vue": "2 || 3"
},
"peerDependenciesMeta": {
"@babel/parser": {
"optional": true
},
"@nuxt/kit": {
"optional": true
}
},
"dependencies": {
"@antfu/utils": "^0.7.10",
"@rollup/pluginutils": "^5.1.4",
"chokidar": "^3.6.0",
"debug": "^4.4.0",
"fast-glob": "^3.3.2",
"local-pkg": "^0.5.1",
"magic-string": "^0.30.15",
"minimatch": "^9.0.5",
"mlly": "^1.7.3",
"unplugin": "^2.1.0"
},
"devDependencies": {
"@antfu/eslint-config": "^3.12.0",
"@babel/parser": "^7.26.3",
"@babel/types": "^7.26.3",
"@nuxt/kit": "^3.14.1592",
"@types/debug": "^4.1.12",
"@types/minimatch": "^5.1.2",
"@types/node": "^22.10.2",
"bumpp": "^9.9.1",
"compare-versions": "^6.1.1",
"element-plus": "^2.9.1",
"eslint": "^9.17.0",
"eslint-plugin-format": "^0.1.3",
"esno": "^4.8.0",
"estree-walker": "^3.0.3",
"pathe": "^1.1.2",
"rollup": "^4.28.1",
"tsup": "^8.3.5",
"typescript": "~5.6.3",
"vite": "^6.0.3",
"vitest": "^2.1.8",
"vue": "3.2.45"
}
}