initial commit
This commit is contained in:
21
node_modules/unimport/LICENSE
generated
vendored
Normal file
21
node_modules/unimport/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 - UnJS
|
||||
|
||||
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.
|
||||
292
node_modules/unimport/README.md
generated
vendored
Normal file
292
node_modules/unimport/README.md
generated
vendored
Normal file
@@ -0,0 +1,292 @@
|
||||
# unimport
|
||||
|
||||
[![npm version][npm-version-src]][npm-version-href]
|
||||
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
||||
[![Github Actions][github-actions-src]][github-actions-href]
|
||||
[![Codecov][codecov-src]][codecov-href]
|
||||
|
||||
> Unified utils for auto importing APIs in modules
|
||||
|
||||
## Features
|
||||
|
||||
- Auto import register APIs for Vite, Webpack or esbuild powered by [unplugin](https://github.com/unjs/unplugin)
|
||||
- TypeScript declaration file generation
|
||||
- Auto import for custom APIs defined under specific directories
|
||||
- Auto import for Vue template
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
# npm
|
||||
npm install unimport
|
||||
|
||||
# yarn
|
||||
yarn add unimport
|
||||
|
||||
# pnpm
|
||||
pnpm install unimport
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Plugin Usage
|
||||
|
||||
Powered by [unplugin](https://github.com/unjs/unplugin), `unimport` provides a plugin interface for bundlers.
|
||||
|
||||
#### Vite / Rollup
|
||||
|
||||
```ts
|
||||
// vite.config.js / rollup.config.js
|
||||
import Unimport from 'unimport/unplugin'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
Unimport.vite({ /* plugin options */ })
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Webpack
|
||||
|
||||
```ts
|
||||
// webpack.config.js
|
||||
import Unimport from 'unimport/unplugin'
|
||||
|
||||
module.exports = {
|
||||
plugins: [
|
||||
Unimport.webpack({ /* plugin options */ })
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic Usage
|
||||
|
||||
```js
|
||||
// ESM
|
||||
import { createUnimport } from 'unimport'
|
||||
|
||||
// CommonJS
|
||||
const { createUnimport } = require('unimport')
|
||||
```
|
||||
|
||||
```js
|
||||
const { injectImports } = createUnimport({
|
||||
imports: [{ name: 'fooBar', from: 'test-id' }]
|
||||
})
|
||||
|
||||
// { code: "import { fooBar } from 'test-id';console.log(fooBar())" }
|
||||
console.log(injectImports('console.log(fooBar())'))
|
||||
```
|
||||
|
||||
## Configurations
|
||||
|
||||
### Imports Item
|
||||
|
||||
###### Named import
|
||||
|
||||
```ts
|
||||
imports: [
|
||||
{ name: 'ref', from: 'vue' },
|
||||
{ name: 'useState', as: 'useSignal', from: 'react' },
|
||||
]
|
||||
```
|
||||
|
||||
Will be injected as:
|
||||
|
||||
```ts
|
||||
import { ref } from 'vue'
|
||||
import { useState as useSignal } from 'react'
|
||||
```
|
||||
|
||||
###### Default import
|
||||
|
||||
```ts
|
||||
imports: [
|
||||
{ name: 'default', as: '_', from: 'lodash' }
|
||||
]
|
||||
```
|
||||
|
||||
Will be injected as:
|
||||
|
||||
```ts
|
||||
import _ from 'lodash'
|
||||
```
|
||||
|
||||
###### Custom Presets
|
||||
|
||||
Presets are provides as a shorthand for declaring imports from the same package:
|
||||
|
||||
```ts
|
||||
presets: [
|
||||
{
|
||||
from: 'vue',
|
||||
imports: [
|
||||
'ref',
|
||||
'reactive',
|
||||
// ...
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Will be equivalent as:
|
||||
|
||||
```ts
|
||||
imports: [
|
||||
{ name: 'ref', from: 'vue' },
|
||||
{ name: 'reactive', from: 'vue' },
|
||||
// ...
|
||||
]
|
||||
```
|
||||
|
||||
###### Built-in Presets
|
||||
|
||||
`unimport` also provides some builtin presets for common libraries:
|
||||
|
||||
```ts
|
||||
presets: [
|
||||
'vue',
|
||||
'pinia',
|
||||
'vue-i18n',
|
||||
// ...
|
||||
]
|
||||
```
|
||||
|
||||
You can check out [`src/presets`](./src/presets/) for all the options available or refer to the type declaration.
|
||||
|
||||
###### Exports Auto Scan
|
||||
|
||||
Since `unimport` v0.7.0, we also support auto scanning the examples from a local installed package, for example:
|
||||
|
||||
```ts
|
||||
presets: [
|
||||
{
|
||||
package: 'h3',
|
||||
ignore: ['isStream', /^[A-Z]/, /^[a-z]*$/, r => r.length > 8]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
This will be expanded into:
|
||||
|
||||
```ts
|
||||
imports: [
|
||||
{
|
||||
"from": "h3",
|
||||
"name": "appendHeader",
|
||||
},
|
||||
{
|
||||
"from": "h3",
|
||||
"name": "appendHeaders",
|
||||
},
|
||||
{
|
||||
"from": "h3",
|
||||
"name": "appendResponseHeader",
|
||||
},
|
||||
// ...
|
||||
]
|
||||
```
|
||||
|
||||
The `ignore` option is used to filter out the exports, it can be a string, regex or a function that returns a boolean.
|
||||
|
||||
By default, the result is strongly cached by the version of the package. You can disable this by setting `cache: false`.
|
||||
|
||||
### Type Declarations
|
||||
|
||||
```ts
|
||||
Unimport.vite({
|
||||
dts: true // or a path to generated file
|
||||
})
|
||||
```
|
||||
|
||||
### Directory Auto Import
|
||||
|
||||
```ts
|
||||
{
|
||||
dirs: [
|
||||
'./composables/*'
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Named exports for modules under `./composables/*` will be registered for auto imports.
|
||||
|
||||
### Opt-out Auto Import
|
||||
|
||||
You can opt-out auto import for specific modules by adding a comment:
|
||||
|
||||
```ts
|
||||
// @unimport-disable
|
||||
```
|
||||
|
||||
It's can be customized by setting `commentsDisable`:
|
||||
|
||||
```ts
|
||||
Unimport.vite({
|
||||
commentsDisable: [
|
||||
'@unimport-disable',
|
||||
'@custom-imports-disable',
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
### Vue Template Auto Import
|
||||
|
||||
In Vue's template, the usage of API is in a different context than plain modules. Thus some custom transformations are required. To enable it, set `addons.vueTemplate` to `true`:
|
||||
|
||||
```ts
|
||||
Unimport.vite({
|
||||
addons: {
|
||||
vueTemplate: true
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Caveats
|
||||
|
||||
When auto-import a ref, inline operations won't be auto-unwrapped.
|
||||
|
||||
```ts
|
||||
export const counter = ref(0)
|
||||
```
|
||||
|
||||
```html
|
||||
<template>
|
||||
<!-- this is ok -->
|
||||
<div>{{ counter }}</div>
|
||||
|
||||
<!-- counter here is a ref, this won't work, volar will throw -->
|
||||
<div>{{ counter + 1 }}</div>
|
||||
|
||||
<!-- use this instead -->
|
||||
<div>{{ counter.value + 1 }}</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
We recommend using [Volar](https://github.com/johnsoncodehk/volar) for type checking, which will help you to identify the misusage.
|
||||
|
||||
## 💻 Development
|
||||
|
||||
- Clone this repository
|
||||
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10)
|
||||
- Install dependencies using `pnpm install`
|
||||
- Run interactive tests using `pnpm dev`
|
||||
|
||||
## License
|
||||
|
||||
Made with 💛
|
||||
|
||||
Published under [MIT License](./LICENSE).
|
||||
|
||||
<!-- Badges -->
|
||||
[npm-version-src]: https://img.shields.io/npm/v/unimport?style=flat-square
|
||||
[npm-version-href]: https://npmjs.com/package/unimport
|
||||
|
||||
[npm-downloads-src]: https://img.shields.io/npm/dm/unimport?style=flat-square
|
||||
[npm-downloads-href]: https://npmjs.com/package/unimport
|
||||
|
||||
[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/unimport/ci/main?style=flat-square
|
||||
[github-actions-href]: https://github.com/unjs/unimport/actions?query=workflow%3Aci
|
||||
|
||||
[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/unimport/main?style=flat-square
|
||||
[codecov-href]: https://codecov.io/gh/unjs/unimport
|
||||
11
node_modules/unimport/dist/addons.cjs
generated
vendored
Normal file
11
node_modules/unimport/dist/addons.cjs
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
const vueTemplate = require('./shared/unimport.7b88c06e.cjs');
|
||||
require('pathe');
|
||||
require('mlly');
|
||||
require('magic-string');
|
||||
require('strip-literal');
|
||||
|
||||
|
||||
|
||||
exports.vueTemplateAddon = vueTemplate.vueTemplateAddon;
|
||||
6
node_modules/unimport/dist/addons.d.ts
generated
vendored
Normal file
6
node_modules/unimport/dist/addons.d.ts
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
import { m as Addon } from './types-0d3b142b.js';
|
||||
import 'magic-string';
|
||||
|
||||
declare const vueTemplateAddon: () => Addon;
|
||||
|
||||
export { vueTemplateAddon };
|
||||
5
node_modules/unimport/dist/addons.mjs
generated
vendored
Normal file
5
node_modules/unimport/dist/addons.mjs
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
export { v as vueTemplateAddon } from './shared/unimport.bbd7571a.mjs';
|
||||
import 'pathe';
|
||||
import 'mlly';
|
||||
import 'magic-string';
|
||||
import 'strip-literal';
|
||||
59
node_modules/unimport/dist/index.cjs
generated
vendored
Normal file
59
node_modules/unimport/dist/index.cjs
generated
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
const context = require('./shared/unimport.e56b747d.cjs');
|
||||
const vueTemplate = require('./shared/unimport.7b88c06e.cjs');
|
||||
require('fs');
|
||||
require('fast-glob');
|
||||
require('pathe');
|
||||
require('mlly');
|
||||
require('scule');
|
||||
require('local-pkg');
|
||||
require('os');
|
||||
require('pkg-types');
|
||||
require('magic-string');
|
||||
require('strip-literal');
|
||||
|
||||
async function installGlobalAutoImports(imports, options = {}) {
|
||||
const {
|
||||
globalObject = globalThis,
|
||||
overrides = false
|
||||
} = options;
|
||||
imports = Array.isArray(imports) ? imports : await imports.getImports();
|
||||
await Promise.all(
|
||||
imports.map(async (i) => {
|
||||
if (i.disabled) {
|
||||
return;
|
||||
}
|
||||
const as = i.as || i.name;
|
||||
if (overrides || !(as in globalObject)) {
|
||||
const module = await import(i.from);
|
||||
globalObject[as] = module[i.name];
|
||||
}
|
||||
})
|
||||
);
|
||||
return globalObject;
|
||||
}
|
||||
|
||||
exports.builtinPresets = context.builtinPresets;
|
||||
exports.createUnimport = context.createUnimport;
|
||||
exports.resolveBuiltinPresets = context.resolveBuiltinPresets;
|
||||
exports.resolvePreset = context.resolvePreset;
|
||||
exports.scanDirExports = context.scanDirExports;
|
||||
exports.scanExports = context.scanExports;
|
||||
exports.addImportToCode = vueTemplate.addImportToCode;
|
||||
exports.dedupeImports = vueTemplate.dedupeImports;
|
||||
exports.defineUnimportPreset = vueTemplate.defineUnimportPreset;
|
||||
exports.excludeRE = vueTemplate.excludeRE;
|
||||
exports.getMagicString = vueTemplate.getMagicString;
|
||||
exports.getString = vueTemplate.getString;
|
||||
exports.importAsRE = vueTemplate.importAsRE;
|
||||
exports.matchRE = vueTemplate.matchRE;
|
||||
exports.normalizeImports = vueTemplate.normalizeImports;
|
||||
exports.resolveIdAbsolute = vueTemplate.resolveIdAbsolute;
|
||||
exports.separatorRE = vueTemplate.separatorRE;
|
||||
exports.stripCommentsAndStrings = vueTemplate.stripCommentsAndStrings;
|
||||
exports.toExports = vueTemplate.toExports;
|
||||
exports.toImports = vueTemplate.toImports;
|
||||
exports.toTypeDeclarationFile = vueTemplate.toTypeDeclarationFile;
|
||||
exports.toTypeDeclarationItems = vueTemplate.toTypeDeclarationItems;
|
||||
exports.installGlobalAutoImports = installGlobalAutoImports;
|
||||
51
node_modules/unimport/dist/index.d.ts
generated
vendored
Normal file
51
node_modules/unimport/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
import { P as Preset, I as Import, B as BuiltinPresetName, a as InlinePreset, T as TypeDeclarationOptions, b as ImportInjectionResult, S as ScanDirExportsOptions, U as UnimportOptions, c as Thenable, d as InjectImportsOptions, e as InstallGlobalOptions } from './types-0d3b142b.js';
|
||||
export { m as Addon, A as AddonsOptions, B as BuiltinPresetName, I as Import, h as ImportCommon, b as ImportInjectionResult, g as ImportName, d as InjectImportsOptions, a as InlinePreset, e as InstallGlobalOptions, M as ModuleId, j as PackagePreset, l as PathFromResolver, P as Preset, i as PresetImport, S as ScanDirExportsOptions, c as Thenable, T as TypeDeclarationOptions, k as UnimportContext, U as UnimportOptions, f as builtinPresets } from './types-0d3b142b.js';
|
||||
import MagicString from 'magic-string';
|
||||
import * as mlly from 'mlly';
|
||||
|
||||
declare function resolvePreset(preset: Preset): Promise<Import[]>;
|
||||
declare function resolveBuiltinPresets(presets: (BuiltinPresetName | Preset)[]): Promise<Import[]>;
|
||||
|
||||
declare const excludeRE: RegExp[];
|
||||
declare const importAsRE: RegExp;
|
||||
declare const separatorRE: RegExp;
|
||||
/** | |
|
||||
* destructing case&ternary non-call | id |
|
||||
* ↓ ↓ ↓ | |*/
|
||||
declare const matchRE: RegExp;
|
||||
declare function stripCommentsAndStrings(code: string): string;
|
||||
declare function defineUnimportPreset(preset: InlinePreset): InlinePreset;
|
||||
declare function toImports(imports: Import[], isCJS?: boolean): string;
|
||||
declare function dedupeImports(imports: Import[], warn: (msg: string) => void): Import[];
|
||||
declare function toExports(imports: Import[], fileDir?: string): string;
|
||||
declare function toTypeDeclarationItems(imports: Import[], options?: TypeDeclarationOptions): string[];
|
||||
declare function toTypeDeclarationFile(imports: Import[], options?: TypeDeclarationOptions): string;
|
||||
declare function getString(code: string | MagicString): string;
|
||||
declare function getMagicString(code: string | MagicString): MagicString;
|
||||
declare function addImportToCode(code: string | MagicString, imports: Import[], isCJS?: boolean, mergeExisting?: boolean): ImportInjectionResult;
|
||||
declare function normalizeImports(imports: Import[]): Import[];
|
||||
declare function resolveIdAbsolute(id: string, parentId?: string): Promise<any>;
|
||||
|
||||
declare function scanDirExports(dir: string | string[], options?: ScanDirExportsOptions): Promise<Import[]>;
|
||||
declare function scanExports(filepath: string): Promise<Import[]>;
|
||||
|
||||
type Unimport = ReturnType<typeof createUnimport>;
|
||||
declare function createUnimport(opts: Partial<UnimportOptions>): {
|
||||
clearDynamicImports: () => void;
|
||||
modifyDynamicImports: (fn: (imports: Import[]) => Thenable<void | Import[]>) => Promise<void>;
|
||||
getImports: () => Promise<Import[]>;
|
||||
detectImports: (code: string | MagicString) => Promise<{
|
||||
s: MagicString;
|
||||
strippedCode: string;
|
||||
isCJSContext: boolean;
|
||||
matchedImports: Import[];
|
||||
}>;
|
||||
injectImports: (code: string | MagicString, id?: string, options?: InjectImportsOptions) => Promise<ImportInjectionResult>;
|
||||
toExports: (filepath?: string) => Promise<string>;
|
||||
parseVirtualImports: (code: string) => mlly.ParsedStaticImport[];
|
||||
generateTypeDeclarations: (options?: TypeDeclarationOptions) => Promise<string>;
|
||||
};
|
||||
|
||||
declare function installGlobalAutoImports(imports: Import[] | Unimport, options?: InstallGlobalOptions): Promise<any>;
|
||||
|
||||
export { Unimport, addImportToCode, createUnimport, dedupeImports, defineUnimportPreset, excludeRE, getMagicString, getString, importAsRE, installGlobalAutoImports, matchRE, normalizeImports, resolveBuiltinPresets, resolveIdAbsolute, resolvePreset, scanDirExports, scanExports, separatorRE, stripCommentsAndStrings, toExports, toImports, toTypeDeclarationFile, toTypeDeclarationItems };
|
||||
35
node_modules/unimport/dist/index.mjs
generated
vendored
Normal file
35
node_modules/unimport/dist/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
export { b as builtinPresets, d as createUnimport, a as resolveBuiltinPresets, r as resolvePreset, s as scanDirExports, c as scanExports } from './shared/unimport.1330341c.mjs';
|
||||
export { k as addImportToCode, b as dedupeImports, d as defineUnimportPreset, e as excludeRE, j as getMagicString, h as getString, i as importAsRE, m as matchRE, n as normalizeImports, r as resolveIdAbsolute, s as separatorRE, a as stripCommentsAndStrings, c as toExports, t as toImports, g as toTypeDeclarationFile, f as toTypeDeclarationItems } from './shared/unimport.bbd7571a.mjs';
|
||||
import 'fs';
|
||||
import 'fast-glob';
|
||||
import 'pathe';
|
||||
import 'mlly';
|
||||
import 'scule';
|
||||
import 'local-pkg';
|
||||
import 'os';
|
||||
import 'pkg-types';
|
||||
import 'magic-string';
|
||||
import 'strip-literal';
|
||||
|
||||
async function installGlobalAutoImports(imports, options = {}) {
|
||||
const {
|
||||
globalObject = globalThis,
|
||||
overrides = false
|
||||
} = options;
|
||||
imports = Array.isArray(imports) ? imports : await imports.getImports();
|
||||
await Promise.all(
|
||||
imports.map(async (i) => {
|
||||
if (i.disabled) {
|
||||
return;
|
||||
}
|
||||
const as = i.as || i.name;
|
||||
if (overrides || !(as in globalObject)) {
|
||||
const module = await import(i.from);
|
||||
globalObject[as] = module[i.name];
|
||||
}
|
||||
})
|
||||
);
|
||||
return globalObject;
|
||||
}
|
||||
|
||||
export { installGlobalAutoImports };
|
||||
841
node_modules/unimport/dist/shared/unimport.1330341c.mjs
generated
vendored
Normal file
841
node_modules/unimport/dist/shared/unimport.1330341c.mjs
generated
vendored
Normal file
@@ -0,0 +1,841 @@
|
||||
import { readFileSync, existsSync, promises, accessSync, constants } from 'fs';
|
||||
import fg from 'fast-glob';
|
||||
import { join, dirname, normalize, parse } from 'pathe';
|
||||
import { resolveModuleExportNames, findExports, findStaticImports, parseStaticImport, detectSyntax } from 'mlly';
|
||||
import { camelCase } from 'scule';
|
||||
import { d as defineUnimportPreset, v as vueTemplateAddon, n as normalizeImports, b as dedupeImports, c as toExports, j as getMagicString, a as stripCommentsAndStrings, m as matchRE, e as excludeRE, s as separatorRE, i as importAsRE, k as addImportToCode, g as toTypeDeclarationFile } from './unimport.bbd7571a.mjs';
|
||||
import { resolveModule } from 'local-pkg';
|
||||
import os from 'os';
|
||||
import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
|
||||
|
||||
const pinia = defineUnimportPreset({
|
||||
from: "pinia",
|
||||
imports: [
|
||||
"acceptHMRUpdate",
|
||||
"createPinia",
|
||||
"defineStore",
|
||||
"getActivePinia",
|
||||
"mapActions",
|
||||
"mapGetters",
|
||||
"mapState",
|
||||
"mapStores",
|
||||
"mapWritableState",
|
||||
"setActivePinia",
|
||||
"setMapStoreSuffix",
|
||||
"storeToRefs"
|
||||
]
|
||||
});
|
||||
|
||||
const preact = defineUnimportPreset({
|
||||
from: "preact",
|
||||
imports: [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
});
|
||||
|
||||
const quasar = defineUnimportPreset({
|
||||
from: "quasar",
|
||||
imports: [
|
||||
"useQuasar",
|
||||
"useDialogPluginComponent",
|
||||
"useFormChild",
|
||||
"useMeta"
|
||||
]
|
||||
});
|
||||
|
||||
const react = defineUnimportPreset({
|
||||
from: "react",
|
||||
imports: [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
});
|
||||
|
||||
const ReactRouterHooks = [
|
||||
"useOutletContext",
|
||||
"useHref",
|
||||
"useInRouterContext",
|
||||
"useLocation",
|
||||
"useNavigationType",
|
||||
"useNavigate",
|
||||
"useOutlet",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRoutes"
|
||||
];
|
||||
const reactRouter = defineUnimportPreset({
|
||||
from: "react-router",
|
||||
imports: [
|
||||
...ReactRouterHooks
|
||||
]
|
||||
});
|
||||
|
||||
const reactRouterDom = defineUnimportPreset({
|
||||
from: "react-router-dom",
|
||||
imports: [
|
||||
...ReactRouterHooks,
|
||||
"useLinkClickHandler",
|
||||
"useSearchParams",
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Routes"
|
||||
]
|
||||
});
|
||||
|
||||
const svelteAnimate = defineUnimportPreset({
|
||||
from: "svelte/animate",
|
||||
imports: [
|
||||
"flip"
|
||||
]
|
||||
});
|
||||
const svelteEasing = defineUnimportPreset({
|
||||
from: "svelte/easing",
|
||||
imports: [
|
||||
"back",
|
||||
"bounce",
|
||||
"circ",
|
||||
"cubic",
|
||||
"elastic",
|
||||
"expo",
|
||||
"quad",
|
||||
"quart",
|
||||
"quint",
|
||||
"sine"
|
||||
].reduce((acc, e) => {
|
||||
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
|
||||
return acc;
|
||||
}, ["linear"])
|
||||
});
|
||||
const svelteStore = defineUnimportPreset({
|
||||
from: "svelte/store",
|
||||
imports: [
|
||||
"writable",
|
||||
"readable",
|
||||
"derived",
|
||||
"get"
|
||||
]
|
||||
});
|
||||
const svelteMotion = defineUnimportPreset({
|
||||
from: "svelte/motion",
|
||||
imports: [
|
||||
"tweened",
|
||||
"spring"
|
||||
]
|
||||
});
|
||||
const svelteTransition = defineUnimportPreset({
|
||||
from: "svelte/transition",
|
||||
imports: [
|
||||
"fade",
|
||||
"blur",
|
||||
"fly",
|
||||
"slide",
|
||||
"scale",
|
||||
"draw",
|
||||
"crossfade"
|
||||
]
|
||||
});
|
||||
const svelte = defineUnimportPreset({
|
||||
from: "svelte",
|
||||
imports: [
|
||||
"onMount",
|
||||
"beforeUpdate",
|
||||
"afterUpdate",
|
||||
"onDestroy",
|
||||
"tick",
|
||||
"setContext",
|
||||
"getContext",
|
||||
"hasContext",
|
||||
"getAllContexts",
|
||||
"createEventDispatcher"
|
||||
]
|
||||
});
|
||||
|
||||
const veeValidate = defineUnimportPreset({
|
||||
from: "vee-validate",
|
||||
imports: [
|
||||
"validate",
|
||||
"defineRule",
|
||||
"configure",
|
||||
"useField",
|
||||
"useForm",
|
||||
"useFieldArray",
|
||||
"useResetForm",
|
||||
"useIsFieldDirty",
|
||||
"useIsFieldTouched",
|
||||
"useIsFieldValid",
|
||||
"useIsSubmitting",
|
||||
"useValidateField",
|
||||
"useIsFormDirty",
|
||||
"useIsFormTouched",
|
||||
"useIsFormValid",
|
||||
"useValidateForm",
|
||||
"useSubmitCount",
|
||||
"useFieldValue",
|
||||
"useFormValues",
|
||||
"useFormErrors",
|
||||
"useFieldError",
|
||||
"useSubmitForm",
|
||||
"FormContextKey",
|
||||
"FieldContextKey"
|
||||
]
|
||||
});
|
||||
|
||||
const vitepress = defineUnimportPreset({
|
||||
from: "vitepress",
|
||||
imports: [
|
||||
"useData",
|
||||
"useRoute",
|
||||
"useRouter",
|
||||
"withBase"
|
||||
]
|
||||
});
|
||||
|
||||
const CommonCompositionAPI = [
|
||||
"onActivated",
|
||||
"onBeforeMount",
|
||||
"onBeforeUnmount",
|
||||
"onBeforeUpdate",
|
||||
"onErrorCaptured",
|
||||
"onDeactivated",
|
||||
"onMounted",
|
||||
"onServerPrefetch",
|
||||
"onUnmounted",
|
||||
"onUpdated",
|
||||
"useAttrs",
|
||||
"useSlots",
|
||||
"computed",
|
||||
"customRef",
|
||||
"isReadonly",
|
||||
"isRef",
|
||||
"markRaw",
|
||||
"reactive",
|
||||
"readonly",
|
||||
"ref",
|
||||
"shallowReactive",
|
||||
"shallowReadonly",
|
||||
"shallowRef",
|
||||
"triggerRef",
|
||||
"toRaw",
|
||||
"toRef",
|
||||
"toRefs",
|
||||
"unref",
|
||||
"watch",
|
||||
"watchEffect",
|
||||
"defineComponent",
|
||||
"defineAsyncComponent",
|
||||
"getCurrentInstance",
|
||||
"h",
|
||||
"inject",
|
||||
"nextTick",
|
||||
"provide",
|
||||
"useCssModule",
|
||||
"createApp",
|
||||
"effectScope",
|
||||
"EffectScope",
|
||||
"getCurrentScope",
|
||||
"onScopeDispose"
|
||||
];
|
||||
const vue = defineUnimportPreset({
|
||||
from: "vue",
|
||||
imports: [
|
||||
...CommonCompositionAPI,
|
||||
"onRenderTracked",
|
||||
"onRenderTriggered",
|
||||
"resolveComponent",
|
||||
"useCssVars"
|
||||
]
|
||||
});
|
||||
|
||||
const vueMacros = defineUnimportPreset({
|
||||
from: "vue/macros",
|
||||
imports: [
|
||||
"$",
|
||||
"$$",
|
||||
"$ref",
|
||||
"$shallowRef",
|
||||
"$toRef",
|
||||
"$customRef",
|
||||
"$computed"
|
||||
]
|
||||
});
|
||||
|
||||
const vueDemi = defineUnimportPreset({
|
||||
from: "vue-demi",
|
||||
imports: CommonCompositionAPI
|
||||
});
|
||||
|
||||
const vueI18n = defineUnimportPreset({
|
||||
from: "vue-i18n",
|
||||
imports: [
|
||||
"useI18n"
|
||||
]
|
||||
});
|
||||
|
||||
const vueRouter = defineUnimportPreset({
|
||||
from: "vue-router",
|
||||
imports: [
|
||||
"useRouter",
|
||||
"useRoute"
|
||||
]
|
||||
});
|
||||
|
||||
const vueCompositionApi = defineUnimportPreset({
|
||||
from: "@vue/composition-api",
|
||||
imports: CommonCompositionAPI
|
||||
});
|
||||
|
||||
let _cache;
|
||||
const vueuseCore = () => {
|
||||
const excluded = ["toRefs", "utils"];
|
||||
if (!_cache) {
|
||||
try {
|
||||
const corePath = resolveModule("@vueuse/core") || process.cwd();
|
||||
const path = resolveModule("@vueuse/core/indexes.json") || resolveModule("@vueuse/metadata/index.json") || resolveModule("@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
const indexesJson = JSON.parse(readFileSync(path, "utf-8"));
|
||||
_cache = defineUnimportPreset({
|
||||
from: "@vueuse/core",
|
||||
imports: indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).map((i) => i.name).filter((i) => i && i.length >= 4 && !excluded.includes(i))
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
|
||||
}
|
||||
}
|
||||
return _cache;
|
||||
};
|
||||
|
||||
const vueuseHead = defineUnimportPreset({
|
||||
from: "@vueuse/head",
|
||||
imports: [
|
||||
"useHead"
|
||||
]
|
||||
});
|
||||
|
||||
const vuex = defineUnimportPreset({
|
||||
from: "vuex",
|
||||
imports: [
|
||||
"createStore",
|
||||
"createLogger",
|
||||
"mapState",
|
||||
"mapGetters",
|
||||
"mapActions",
|
||||
"mapMutations",
|
||||
"createNamespacedHelpers",
|
||||
"useStore"
|
||||
]
|
||||
});
|
||||
|
||||
const vitest = defineUnimportPreset({
|
||||
from: "vitest",
|
||||
imports: [
|
||||
"suite",
|
||||
"test",
|
||||
"describe",
|
||||
"it",
|
||||
"chai",
|
||||
"expect",
|
||||
"assert",
|
||||
"vitest",
|
||||
"vi",
|
||||
"beforeAll",
|
||||
"afterAll",
|
||||
"beforeEach",
|
||||
"afterEach"
|
||||
]
|
||||
});
|
||||
|
||||
const uniApp = defineUnimportPreset({
|
||||
from: "@dcloudio/uni-app",
|
||||
imports: [
|
||||
"onAddToFavorites",
|
||||
"onBackPress",
|
||||
"onError",
|
||||
"onHide",
|
||||
"onLaunch",
|
||||
"onLoad",
|
||||
"onNavigationBarButtonTap",
|
||||
"onNavigationBarSearchInputChanged",
|
||||
"onNavigationBarSearchInputClicked",
|
||||
"onNavigationBarSearchInputConfirmed",
|
||||
"onNavigationBarSearchInputFocusChanged",
|
||||
"onPageNotFound",
|
||||
"onPageScroll",
|
||||
"onPullDownRefresh",
|
||||
"onReachBottom",
|
||||
"onReady",
|
||||
"onResize",
|
||||
"onShareAppMessage",
|
||||
"onShareTimeline",
|
||||
"onShow",
|
||||
"onTabItemTap",
|
||||
"onThemeChange",
|
||||
"onUnhandledRejection",
|
||||
"onUnload"
|
||||
]
|
||||
});
|
||||
|
||||
const solidCore = defineUnimportPreset({
|
||||
from: "solid-js",
|
||||
imports: [
|
||||
"createSignal",
|
||||
"createEffect",
|
||||
"createMemo",
|
||||
"createResource",
|
||||
"onMount",
|
||||
"onCleanup",
|
||||
"onError",
|
||||
"untrack",
|
||||
"batch",
|
||||
"on",
|
||||
"createRoot",
|
||||
"mergeProps",
|
||||
"splitProps",
|
||||
"useTransition",
|
||||
"observable",
|
||||
"mapArray",
|
||||
"indexArray",
|
||||
"createContext",
|
||||
"useContext",
|
||||
"children",
|
||||
"lazy",
|
||||
"createDeferred",
|
||||
"createRenderEffect",
|
||||
"createSelector",
|
||||
"For",
|
||||
"Show",
|
||||
"Switch",
|
||||
"Match",
|
||||
"Index",
|
||||
"ErrorBoundary",
|
||||
"Suspense",
|
||||
"SuspenseList"
|
||||
]
|
||||
});
|
||||
const solidStore = defineUnimportPreset({
|
||||
from: "solid-js/store",
|
||||
imports: [
|
||||
"createStore",
|
||||
"produce",
|
||||
"reconcile",
|
||||
"createMutable"
|
||||
]
|
||||
});
|
||||
const solidWeb = defineUnimportPreset({
|
||||
from: "solid-js/web",
|
||||
imports: [
|
||||
"Dynamic",
|
||||
"hydrate",
|
||||
"render",
|
||||
"renderToString",
|
||||
"renderToStringAsync",
|
||||
"renderToStream",
|
||||
"isServer",
|
||||
"Portal"
|
||||
]
|
||||
});
|
||||
const solid = defineUnimportPreset({
|
||||
from: "solid-js",
|
||||
imports: [
|
||||
solidCore,
|
||||
solidStore,
|
||||
solidWeb
|
||||
]
|
||||
});
|
||||
|
||||
const solidAppRouter = defineUnimportPreset({
|
||||
from: "solid-app-router",
|
||||
imports: [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
});
|
||||
|
||||
const builtinPresets = {
|
||||
"@vue/composition-api": vueCompositionApi,
|
||||
"@vueuse/core": vueuseCore,
|
||||
"@vueuse/head": vueuseHead,
|
||||
pinia,
|
||||
preact,
|
||||
quasar,
|
||||
react,
|
||||
"react-router": reactRouter,
|
||||
"react-router-dom": reactRouterDom,
|
||||
svelte,
|
||||
"svelte/animate": svelteAnimate,
|
||||
"svelte/easing": svelteEasing,
|
||||
"svelte/motion": svelteMotion,
|
||||
"svelte/store": svelteStore,
|
||||
"svelte/transition": svelteTransition,
|
||||
"vee-validate": veeValidate,
|
||||
vitepress,
|
||||
"vue-demi": vueDemi,
|
||||
"vue-i18n": vueI18n,
|
||||
"vue-router": vueRouter,
|
||||
vue,
|
||||
"vue/macros": vueMacros,
|
||||
vuex,
|
||||
vitest,
|
||||
"uni-app": uniApp,
|
||||
"solid-js": solid,
|
||||
"solid-app-router": solidAppRouter
|
||||
};
|
||||
|
||||
const CACHE_PATH = /* @__PURE__ */ join(os.tmpdir(), "unimport");
|
||||
let CACHE_WRITEABLE;
|
||||
async function resolvePackagePreset(preset) {
|
||||
const scanned = await extractExports(preset.package, preset.url, preset.cache);
|
||||
const filtered = scanned.filter((name) => {
|
||||
for (const item of preset.ignore || []) {
|
||||
if (typeof item === "string" && item === name) {
|
||||
return false;
|
||||
}
|
||||
if (item instanceof RegExp && item.test(name)) {
|
||||
return false;
|
||||
}
|
||||
if (typeof item === "function" && item(name) === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return filtered.map((name) => ({
|
||||
from: preset.package,
|
||||
name
|
||||
}));
|
||||
}
|
||||
async function extractExports(name, url, cache = true) {
|
||||
const packageJsonPath = await resolvePackageJSON(name, { url });
|
||||
const packageJson = await readPackageJSON(packageJsonPath);
|
||||
const version = packageJson.version;
|
||||
const cachePath = join(CACHE_PATH, name + "@" + version, "exports.json");
|
||||
if (cache && CACHE_WRITEABLE === void 0) {
|
||||
try {
|
||||
CACHE_WRITEABLE = isWritable(CACHE_PATH);
|
||||
} catch {
|
||||
CACHE_WRITEABLE = false;
|
||||
}
|
||||
}
|
||||
const useCache = cache && version && CACHE_WRITEABLE;
|
||||
if (useCache && existsSync(cachePath)) {
|
||||
return JSON.parse(await promises.readFile(cachePath, "utf-8"));
|
||||
}
|
||||
const scanned = await resolveModuleExportNames(name, { url });
|
||||
if (useCache) {
|
||||
await promises.mkdir(dirname(cachePath), { recursive: true });
|
||||
await promises.writeFile(cachePath, JSON.stringify(scanned), "utf-8");
|
||||
}
|
||||
return scanned;
|
||||
}
|
||||
function isWritable(filename) {
|
||||
try {
|
||||
accessSync(filename, constants.W_OK);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const commonProps = ["from", "priority", "disabled"];
|
||||
async function resolvePreset(preset) {
|
||||
const imports = [];
|
||||
if ("package" in preset) {
|
||||
return await resolvePackagePreset(preset);
|
||||
}
|
||||
const common = {};
|
||||
commonProps.forEach((i) => {
|
||||
if (i in preset) {
|
||||
common[i] = preset[i];
|
||||
}
|
||||
});
|
||||
for (const _import of preset.imports) {
|
||||
if (typeof _import === "string") {
|
||||
imports.push({ ...common, name: _import, as: _import });
|
||||
} else if (Array.isArray(_import)) {
|
||||
imports.push({ ...common, name: _import[0], as: _import[1] || _import[0], from: _import[2] || preset.from });
|
||||
} else if (_import.imports) {
|
||||
imports.push(...await resolvePreset(_import));
|
||||
} else {
|
||||
imports.push({ ...common, ..._import });
|
||||
}
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
async function resolveBuiltinPresets(presets) {
|
||||
const resolved = await Promise.all(presets.map(async (p) => {
|
||||
let preset = typeof p === "string" ? builtinPresets[p] : p;
|
||||
if (typeof preset === "function") {
|
||||
preset = preset();
|
||||
}
|
||||
return await resolvePreset(preset);
|
||||
}));
|
||||
return resolved.flat();
|
||||
}
|
||||
|
||||
async function scanDirExports(dir, options) {
|
||||
const dirs = (Array.isArray(dir) ? dir : [dir]).map((d) => normalize(d));
|
||||
const fileFilter = options?.fileFilter || (() => true);
|
||||
const filePatterns = options?.filePatterns || ["*.{ts,js,mjs,cjs,mts,cts}"];
|
||||
const result = await Promise.all(
|
||||
dirs.map(
|
||||
async (i) => await fg(
|
||||
[i, ...filePatterns.map((p) => join(i, p))],
|
||||
{
|
||||
absolute: true,
|
||||
cwd: options?.cwd || process.cwd(),
|
||||
onlyFiles: true,
|
||||
followSymbolicLinks: true
|
||||
}
|
||||
).then(
|
||||
(r) => r.map((f) => normalize(f)).sort()
|
||||
)
|
||||
)
|
||||
);
|
||||
const files = Array.from(new Set(result.flat())).filter(fileFilter);
|
||||
const fileExports = await Promise.all(files.map(scanExports));
|
||||
return fileExports.flat();
|
||||
}
|
||||
async function scanExports(filepath) {
|
||||
const imports = [];
|
||||
const code = await promises.readFile(filepath, "utf-8");
|
||||
const exports = findExports(code);
|
||||
const defaultExport = exports.find((i) => i.type === "default");
|
||||
if (defaultExport) {
|
||||
let name = parse(filepath).name;
|
||||
if (name === "index") {
|
||||
name = parse(filepath.split("/").slice(0, -1).join("/")).name;
|
||||
}
|
||||
imports.push({ name: "default", as: camelCase(name), from: filepath });
|
||||
}
|
||||
for (const exp of exports) {
|
||||
if (exp.type === "named") {
|
||||
for (const name of exp.names) {
|
||||
imports.push({ name, as: name, from: filepath });
|
||||
}
|
||||
} else if (exp.type === "declaration") {
|
||||
if (exp.name) {
|
||||
imports.push({ name: exp.name, as: exp.name, from: filepath });
|
||||
}
|
||||
}
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
function createUnimport(opts) {
|
||||
let _combinedImports;
|
||||
const _map = /* @__PURE__ */ new Map();
|
||||
const addons = [];
|
||||
if (Array.isArray(opts.addons)) {
|
||||
addons.push(...opts.addons);
|
||||
} else if (opts.addons?.vueTemplate) {
|
||||
addons.push(vueTemplateAddon());
|
||||
}
|
||||
opts.addons = addons;
|
||||
opts.commentsDisable = opts.commentsDisable ?? ["@unimport-disable", "@imports-disable"];
|
||||
opts.commentsDebug = opts.commentsDebug ?? ["@unimport-debug", "@imports-debug"];
|
||||
const ctx = {
|
||||
staticImports: [...opts.imports || []].filter(Boolean),
|
||||
dynamicImports: [],
|
||||
async getImports() {
|
||||
await resolvePromise;
|
||||
return updateImports();
|
||||
},
|
||||
async getImportMap() {
|
||||
await ctx.getImports();
|
||||
return _map;
|
||||
},
|
||||
invalidate() {
|
||||
_combinedImports = void 0;
|
||||
},
|
||||
resolveId: (id, parentId) => opts.resolveId?.(id, parentId),
|
||||
addons,
|
||||
options: opts
|
||||
};
|
||||
const resolvePromise = resolveBuiltinPresets(opts.presets || []).then((r) => {
|
||||
ctx.staticImports.unshift(...r);
|
||||
_combinedImports = void 0;
|
||||
updateImports();
|
||||
});
|
||||
function updateImports() {
|
||||
if (!_combinedImports) {
|
||||
const imports = normalizeImports(dedupeImports([...ctx.staticImports, ...ctx.dynamicImports], opts.warn || console.warn)).filter((i) => !i.disabled);
|
||||
_map.clear();
|
||||
for (const _import of imports) {
|
||||
_map.set(_import.as ?? _import.name, _import);
|
||||
}
|
||||
_combinedImports = imports;
|
||||
}
|
||||
return _combinedImports;
|
||||
}
|
||||
async function modifyDynamicImports(fn) {
|
||||
const result = await fn(ctx.dynamicImports);
|
||||
if (Array.isArray(result)) {
|
||||
ctx.dynamicImports = result;
|
||||
}
|
||||
ctx.invalidate();
|
||||
}
|
||||
function clearDynamicImports() {
|
||||
ctx.dynamicImports.length = 0;
|
||||
ctx.invalidate();
|
||||
}
|
||||
async function generateTypeDeclarations(options) {
|
||||
const opts2 = {
|
||||
resolvePath: (i) => i.from.replace(/\.ts$/, ""),
|
||||
...options
|
||||
};
|
||||
let dts = toTypeDeclarationFile(await ctx.getImports(), opts2);
|
||||
for (const addon of ctx.addons) {
|
||||
dts = await addon.declaration?.call(ctx, dts, opts2) ?? dts;
|
||||
}
|
||||
return dts;
|
||||
}
|
||||
return {
|
||||
clearDynamicImports,
|
||||
modifyDynamicImports,
|
||||
getImports: () => ctx.getImports(),
|
||||
detectImports: (code) => detectImports(code, ctx),
|
||||
injectImports: (code, id, options) => injectImports(code, id, ctx, options),
|
||||
toExports: async (filepath) => toExports(await ctx.getImports(), filepath),
|
||||
parseVirtualImports: (code) => parseVirtualImports(code, ctx),
|
||||
generateTypeDeclarations
|
||||
};
|
||||
}
|
||||
function parseVirtualImports(code, ctx) {
|
||||
if (ctx.options.virtualImports?.length) {
|
||||
return findStaticImports(code).filter((i) => ctx.options.virtualImports.includes(i.specifier)).map((i) => parseStaticImport(i));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
async function detectImports(code, ctx, options) {
|
||||
const s = getMagicString(code);
|
||||
const original = s.original;
|
||||
const strippedCode = stripCommentsAndStrings(original);
|
||||
const syntax = detectSyntax(strippedCode);
|
||||
const isCJSContext = syntax.hasCJS && !syntax.hasESM;
|
||||
let matchedImports = [];
|
||||
const map = await ctx.getImportMap();
|
||||
if (options?.autoImport !== false) {
|
||||
const identifiers = new Set(
|
||||
Array.from(strippedCode.matchAll(matchRE)).map((i) => {
|
||||
if (i[1] === ".") {
|
||||
return "";
|
||||
}
|
||||
const end = strippedCode[i.index + i[0].length];
|
||||
if (end === ":" && !["?", "case"].includes(i[1].trim())) {
|
||||
return "";
|
||||
}
|
||||
return i[2];
|
||||
}).filter(Boolean)
|
||||
);
|
||||
for (const regex of excludeRE) {
|
||||
for (const match of strippedCode.matchAll(regex)) {
|
||||
const segments = [...match[1]?.split(separatorRE) || [], ...match[2]?.split(separatorRE) || []];
|
||||
for (const segment of segments) {
|
||||
const identifier = segment.replace(importAsRE, "").trim();
|
||||
identifiers.delete(identifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
matchedImports = Array.from(identifiers).map((name) => map.get(name)).filter((i) => i && !i.disabled);
|
||||
for (const addon of ctx.addons) {
|
||||
matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
|
||||
}
|
||||
}
|
||||
if (options?.transformVirtualImports !== false && options?.transformVirtualImoports !== false && ctx.options.virtualImports?.length) {
|
||||
const virtualImports = parseVirtualImports(original, ctx);
|
||||
virtualImports.forEach((i) => {
|
||||
s.remove(i.start, i.end);
|
||||
Object.entries(i.namedImports || {}).forEach(([name, as]) => {
|
||||
const original2 = map.get(name);
|
||||
if (!original2) {
|
||||
throw new Error(`[unimport] failed to find "${name}" imported from "${i.specifier}"`);
|
||||
}
|
||||
matchedImports.push({
|
||||
from: original2.from,
|
||||
name: original2.name,
|
||||
as
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
return {
|
||||
s,
|
||||
strippedCode,
|
||||
isCJSContext,
|
||||
matchedImports
|
||||
};
|
||||
}
|
||||
async function injectImports(code, id, ctx, options) {
|
||||
const s = getMagicString(code);
|
||||
if (ctx.options.commentsDisable?.some((c) => s.original.includes(c))) {
|
||||
return {
|
||||
s,
|
||||
get code() {
|
||||
return s.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
for (const addon of ctx.addons) {
|
||||
await addon.transform?.call(ctx, s, id);
|
||||
}
|
||||
const { isCJSContext, matchedImports } = await detectImports(s, ctx, options);
|
||||
const imports = await resolveImports(ctx, matchedImports, id);
|
||||
if (ctx.options.commentsDebug?.some((c) => s.original.includes(c))) {
|
||||
const log = ctx.options.debugLog || console.log;
|
||||
log(`[unimport] ${imports.length} imports detected in "${id}"${imports.length ? ": " + imports.map((i) => i.name).join(", ") : ""}`);
|
||||
}
|
||||
return addImportToCode(s, imports, isCJSContext, options?.mergeExisting);
|
||||
}
|
||||
async function resolveImports(ctx, imports, id) {
|
||||
const resolveCache = /* @__PURE__ */ new Map();
|
||||
const _imports = await Promise.all(imports.map(async (i) => {
|
||||
if (!resolveCache.has(i.from)) {
|
||||
resolveCache.set(i.from, await ctx.resolveId(i.from, id) || i.from);
|
||||
}
|
||||
const from = resolveCache.get(i.from);
|
||||
if (i.from === id || !from || from === "." || from === id) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
...i,
|
||||
from
|
||||
};
|
||||
}));
|
||||
return _imports.filter(Boolean);
|
||||
}
|
||||
|
||||
export { resolveBuiltinPresets as a, builtinPresets as b, scanExports as c, createUnimport as d, resolvePreset as r, scanDirExports as s };
|
||||
270
node_modules/unimport/dist/shared/unimport.7b88c06e.cjs
generated
vendored
Normal file
270
node_modules/unimport/dist/shared/unimport.7b88c06e.cjs
generated
vendored
Normal file
@@ -0,0 +1,270 @@
|
||||
'use strict';
|
||||
|
||||
const pathe = require('pathe');
|
||||
const mlly = require('mlly');
|
||||
const MagicString = require('magic-string');
|
||||
const stripLiteral = require('strip-literal');
|
||||
|
||||
const excludeRE = [
|
||||
/\b(import|export)\b(.+?)\bfrom\b/gs,
|
||||
/\bfunction\s*([\w_$]+?)\s*\(/gs,
|
||||
/\bclass\s*([\w_$]+?)\s*{/gs,
|
||||
/\b(?:const|let|var)\s+?(\[.*?\]|\{.*?\}|.+?)\s*?[=;\n]/gs
|
||||
];
|
||||
const importAsRE = /^.*\sas\s+/;
|
||||
const separatorRE = /[,[\]{}\n]|\bimport\b/g;
|
||||
const matchRE = /(^|\.\.\.|(?:\bcase|\?)\s+|[^\w_$\/)])([\w_$]+)\s*(?=[.()[\]}:;?+\-*&|`<>,\n]|\b(?:instanceof|in)\b|$)/g;
|
||||
const regexRE = /\/[^\s]*?(?<!\\)(?<!\[[^\]]*)\/[gimsuy]*/g;
|
||||
function stripCommentsAndStrings(code) {
|
||||
return stripLiteral.stripLiteral(code).replace(regexRE, 'new RegExp("")');
|
||||
}
|
||||
function defineUnimportPreset(preset) {
|
||||
return preset;
|
||||
}
|
||||
function toImports(imports, isCJS = false) {
|
||||
const map = toImportModuleMap(imports);
|
||||
return Object.entries(map).flatMap(([name, importSet]) => {
|
||||
const entries = [];
|
||||
const imports2 = Array.from(importSet).filter((i) => {
|
||||
if (!i.name || i.as === "") {
|
||||
entries.push(
|
||||
isCJS ? `require('${name}');` : `import '${name}';`
|
||||
);
|
||||
return false;
|
||||
} else if (i.name === "default") {
|
||||
entries.push(
|
||||
isCJS ? `const { default: ${i.as} } = require('${name}');` : `import ${i.as} from '${name}';`
|
||||
);
|
||||
return false;
|
||||
} else if (i.name === "*") {
|
||||
entries.push(
|
||||
isCJS ? `const ${i.as} = require('${name}');` : `import * as ${i.as} from '${name}';`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (imports2.length) {
|
||||
const importsAs = imports2.map((i) => stringifyImportAlias(i, isCJS));
|
||||
entries.push(
|
||||
isCJS ? `const { ${importsAs.join(", ")} } = require('${name}');` : `import { ${importsAs.join(", ")} } from '${name}';`
|
||||
);
|
||||
}
|
||||
return entries;
|
||||
}).join("\n");
|
||||
}
|
||||
function dedupeImports(imports, warn) {
|
||||
const map = /* @__PURE__ */ new Map();
|
||||
const indexToRemove = /* @__PURE__ */ new Set();
|
||||
imports.filter((i) => !i.disabled).forEach((i, idx) => {
|
||||
const name = i.as ?? i.name;
|
||||
if (!map.has(name)) {
|
||||
map.set(name, idx);
|
||||
return;
|
||||
}
|
||||
const other = imports[map.get(name)];
|
||||
if (other.from === i.from) {
|
||||
indexToRemove.add(idx);
|
||||
return;
|
||||
}
|
||||
const diff = (other.priority || 1) - (i.priority || 1);
|
||||
if (diff === 0) {
|
||||
warn(`Duplicated imports "${name}", the one from "${other.from}" has been ignored`);
|
||||
}
|
||||
if (diff <= 0) {
|
||||
indexToRemove.add(map.get(name));
|
||||
map.set(name, idx);
|
||||
} else {
|
||||
indexToRemove.add(idx);
|
||||
}
|
||||
});
|
||||
return imports.filter((_, idx) => !indexToRemove.has(idx));
|
||||
}
|
||||
function toExports(imports, fileDir) {
|
||||
const map = toImportModuleMap(imports);
|
||||
return Object.entries(map).flatMap(([name, imports2]) => {
|
||||
name = name.replace(/\.[a-z]+$/, "");
|
||||
if (fileDir && pathe.isAbsolute(name)) {
|
||||
name = pathe.relative(fileDir, name);
|
||||
if (!name.match(/^[.\/]/)) {
|
||||
name = "./" + name;
|
||||
}
|
||||
}
|
||||
const entries = [];
|
||||
const filtered = Array.from(imports2).filter((i) => {
|
||||
if (i.name === "*") {
|
||||
entries.push(`export * as ${i.as} from '${name}';`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (filtered.length) {
|
||||
entries.push(`export { ${filtered.map((i) => stringifyImportAlias(i, false)).join(", ")} } from '${name}';`);
|
||||
}
|
||||
return entries;
|
||||
}).join("\n");
|
||||
}
|
||||
function toTypeDeclarationItems(imports, options) {
|
||||
return imports.map((i) => {
|
||||
const from = options?.resolvePath?.(i) || i.from;
|
||||
return `const ${i.as}: typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}`;
|
||||
}).sort();
|
||||
}
|
||||
function toTypeDeclarationFile(imports, options) {
|
||||
const items = toTypeDeclarationItems(imports, options);
|
||||
const {
|
||||
exportHelper = true
|
||||
} = options || {};
|
||||
let declaration = "";
|
||||
if (exportHelper) {
|
||||
declaration += "export {}\n";
|
||||
}
|
||||
declaration += "declare global {\n" + items.map((i) => " " + i).join("\n") + "\n}";
|
||||
return declaration;
|
||||
}
|
||||
function stringifyImportAlias(item, isCJS = false) {
|
||||
return item.as === void 0 || item.name === item.as ? item.name : isCJS ? `${item.name}: ${item.as}` : `${item.name} as ${item.as}`;
|
||||
}
|
||||
function toImportModuleMap(imports) {
|
||||
const map = {};
|
||||
for (const _import of imports) {
|
||||
if (!map[_import.from]) {
|
||||
map[_import.from] = /* @__PURE__ */ new Set();
|
||||
}
|
||||
map[_import.from].add(_import);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
function getString(code) {
|
||||
if (typeof code === "string") {
|
||||
return code;
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
function getMagicString(code) {
|
||||
if (typeof code === "string") {
|
||||
return new MagicString(code);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
function addImportToCode(code, imports, isCJS = false, mergeExisting = false) {
|
||||
let newImports = [];
|
||||
const s = getMagicString(code);
|
||||
if (mergeExisting && !isCJS) {
|
||||
const existing = mlly.findStaticImports(s.original).map((i) => mlly.parseStaticImport(i));
|
||||
const map = /* @__PURE__ */ new Map();
|
||||
imports.forEach((i) => {
|
||||
const target = existing.find((e) => e.specifier === i.from && e.imports.startsWith("{"));
|
||||
if (!target) {
|
||||
return newImports.push(i);
|
||||
}
|
||||
if (!map.has(target)) {
|
||||
map.set(target, []);
|
||||
}
|
||||
map.get(target).push(i);
|
||||
});
|
||||
for (const [target, items] of map.entries()) {
|
||||
const strings = items.map((i) => stringifyImportAlias(i) + ", ");
|
||||
const importLength = target.code.match(/^\s*import\s*{/)?.[0]?.length;
|
||||
if (importLength) {
|
||||
s.appendLeft(target.start + importLength, " " + strings.join("").trim());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newImports = imports;
|
||||
}
|
||||
const newEntries = toImports(newImports, isCJS);
|
||||
if (newEntries) {
|
||||
s.prepend(newEntries + "\n");
|
||||
}
|
||||
return {
|
||||
s,
|
||||
get code() {
|
||||
return s.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
function normalizeImports(imports) {
|
||||
for (const _import of imports) {
|
||||
_import.as = _import.as ?? _import.name;
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
function resolveIdAbsolute(id, parentId) {
|
||||
return mlly.resolvePath(id, {
|
||||
url: parentId
|
||||
});
|
||||
}
|
||||
|
||||
const contextRE = /\b_ctx\.([\w_]+)\b/g;
|
||||
const UNREF_KEY = "_unimport_unref_";
|
||||
const vueTemplateAddon = () => ({
|
||||
async transform(s) {
|
||||
if (!s.original.includes("_ctx.")) {
|
||||
return s;
|
||||
}
|
||||
const matches = Array.from(s.original.matchAll(contextRE));
|
||||
const imports = await this.getImports();
|
||||
const targets = [];
|
||||
for (const match of matches) {
|
||||
const name = match[1];
|
||||
const item = imports.find((i) => i.as === name);
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
const start = match.index;
|
||||
const end = start + match[0].length;
|
||||
const tempName = `_unimport_${name}`;
|
||||
s.overwrite(start, end, `${UNREF_KEY}(${tempName})`);
|
||||
if (!targets.find((i) => i.as === tempName)) {
|
||||
targets.push({
|
||||
...item,
|
||||
as: tempName
|
||||
});
|
||||
}
|
||||
}
|
||||
if (targets.length) {
|
||||
targets.push({
|
||||
name: "unref",
|
||||
from: "vue",
|
||||
as: UNREF_KEY
|
||||
});
|
||||
s.prepend(toImports(targets));
|
||||
}
|
||||
return s;
|
||||
},
|
||||
async declaration(dts, options) {
|
||||
const imports = await this.getImports();
|
||||
const items = imports.map((i) => {
|
||||
const from = options?.resolvePath?.(i) || i.from;
|
||||
return `readonly ${i.as}: UnwrapRef<typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}>`;
|
||||
}).sort();
|
||||
return dts + `
|
||||
// for vue template auto import
|
||||
import { UnwrapRef } from 'vue'
|
||||
declare module 'vue' {
|
||||
interface ComponentCustomProperties {
|
||||
${items.map((i) => " " + i).join("\n")}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
exports.addImportToCode = addImportToCode;
|
||||
exports.dedupeImports = dedupeImports;
|
||||
exports.defineUnimportPreset = defineUnimportPreset;
|
||||
exports.excludeRE = excludeRE;
|
||||
exports.getMagicString = getMagicString;
|
||||
exports.getString = getString;
|
||||
exports.importAsRE = importAsRE;
|
||||
exports.matchRE = matchRE;
|
||||
exports.normalizeImports = normalizeImports;
|
||||
exports.resolveIdAbsolute = resolveIdAbsolute;
|
||||
exports.separatorRE = separatorRE;
|
||||
exports.stripCommentsAndStrings = stripCommentsAndStrings;
|
||||
exports.toExports = toExports;
|
||||
exports.toImports = toImports;
|
||||
exports.toTypeDeclarationFile = toTypeDeclarationFile;
|
||||
exports.toTypeDeclarationItems = toTypeDeclarationItems;
|
||||
exports.vueTemplateAddon = vueTemplateAddon;
|
||||
252
node_modules/unimport/dist/shared/unimport.bbd7571a.mjs
generated
vendored
Normal file
252
node_modules/unimport/dist/shared/unimport.bbd7571a.mjs
generated
vendored
Normal file
@@ -0,0 +1,252 @@
|
||||
import { isAbsolute, relative } from 'pathe';
|
||||
import { findStaticImports, parseStaticImport, resolvePath } from 'mlly';
|
||||
import MagicString from 'magic-string';
|
||||
import { stripLiteral } from 'strip-literal';
|
||||
|
||||
const excludeRE = [
|
||||
/\b(import|export)\b(.+?)\bfrom\b/gs,
|
||||
/\bfunction\s*([\w_$]+?)\s*\(/gs,
|
||||
/\bclass\s*([\w_$]+?)\s*{/gs,
|
||||
/\b(?:const|let|var)\s+?(\[.*?\]|\{.*?\}|.+?)\s*?[=;\n]/gs
|
||||
];
|
||||
const importAsRE = /^.*\sas\s+/;
|
||||
const separatorRE = /[,[\]{}\n]|\bimport\b/g;
|
||||
const matchRE = /(^|\.\.\.|(?:\bcase|\?)\s+|[^\w_$\/)])([\w_$]+)\s*(?=[.()[\]}:;?+\-*&|`<>,\n]|\b(?:instanceof|in)\b|$)/g;
|
||||
const regexRE = /\/[^\s]*?(?<!\\)(?<!\[[^\]]*)\/[gimsuy]*/g;
|
||||
function stripCommentsAndStrings(code) {
|
||||
return stripLiteral(code).replace(regexRE, 'new RegExp("")');
|
||||
}
|
||||
function defineUnimportPreset(preset) {
|
||||
return preset;
|
||||
}
|
||||
function toImports(imports, isCJS = false) {
|
||||
const map = toImportModuleMap(imports);
|
||||
return Object.entries(map).flatMap(([name, importSet]) => {
|
||||
const entries = [];
|
||||
const imports2 = Array.from(importSet).filter((i) => {
|
||||
if (!i.name || i.as === "") {
|
||||
entries.push(
|
||||
isCJS ? `require('${name}');` : `import '${name}';`
|
||||
);
|
||||
return false;
|
||||
} else if (i.name === "default") {
|
||||
entries.push(
|
||||
isCJS ? `const { default: ${i.as} } = require('${name}');` : `import ${i.as} from '${name}';`
|
||||
);
|
||||
return false;
|
||||
} else if (i.name === "*") {
|
||||
entries.push(
|
||||
isCJS ? `const ${i.as} = require('${name}');` : `import * as ${i.as} from '${name}';`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (imports2.length) {
|
||||
const importsAs = imports2.map((i) => stringifyImportAlias(i, isCJS));
|
||||
entries.push(
|
||||
isCJS ? `const { ${importsAs.join(", ")} } = require('${name}');` : `import { ${importsAs.join(", ")} } from '${name}';`
|
||||
);
|
||||
}
|
||||
return entries;
|
||||
}).join("\n");
|
||||
}
|
||||
function dedupeImports(imports, warn) {
|
||||
const map = /* @__PURE__ */ new Map();
|
||||
const indexToRemove = /* @__PURE__ */ new Set();
|
||||
imports.filter((i) => !i.disabled).forEach((i, idx) => {
|
||||
const name = i.as ?? i.name;
|
||||
if (!map.has(name)) {
|
||||
map.set(name, idx);
|
||||
return;
|
||||
}
|
||||
const other = imports[map.get(name)];
|
||||
if (other.from === i.from) {
|
||||
indexToRemove.add(idx);
|
||||
return;
|
||||
}
|
||||
const diff = (other.priority || 1) - (i.priority || 1);
|
||||
if (diff === 0) {
|
||||
warn(`Duplicated imports "${name}", the one from "${other.from}" has been ignored`);
|
||||
}
|
||||
if (diff <= 0) {
|
||||
indexToRemove.add(map.get(name));
|
||||
map.set(name, idx);
|
||||
} else {
|
||||
indexToRemove.add(idx);
|
||||
}
|
||||
});
|
||||
return imports.filter((_, idx) => !indexToRemove.has(idx));
|
||||
}
|
||||
function toExports(imports, fileDir) {
|
||||
const map = toImportModuleMap(imports);
|
||||
return Object.entries(map).flatMap(([name, imports2]) => {
|
||||
name = name.replace(/\.[a-z]+$/, "");
|
||||
if (fileDir && isAbsolute(name)) {
|
||||
name = relative(fileDir, name);
|
||||
if (!name.match(/^[.\/]/)) {
|
||||
name = "./" + name;
|
||||
}
|
||||
}
|
||||
const entries = [];
|
||||
const filtered = Array.from(imports2).filter((i) => {
|
||||
if (i.name === "*") {
|
||||
entries.push(`export * as ${i.as} from '${name}';`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (filtered.length) {
|
||||
entries.push(`export { ${filtered.map((i) => stringifyImportAlias(i, false)).join(", ")} } from '${name}';`);
|
||||
}
|
||||
return entries;
|
||||
}).join("\n");
|
||||
}
|
||||
function toTypeDeclarationItems(imports, options) {
|
||||
return imports.map((i) => {
|
||||
const from = options?.resolvePath?.(i) || i.from;
|
||||
return `const ${i.as}: typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}`;
|
||||
}).sort();
|
||||
}
|
||||
function toTypeDeclarationFile(imports, options) {
|
||||
const items = toTypeDeclarationItems(imports, options);
|
||||
const {
|
||||
exportHelper = true
|
||||
} = options || {};
|
||||
let declaration = "";
|
||||
if (exportHelper) {
|
||||
declaration += "export {}\n";
|
||||
}
|
||||
declaration += "declare global {\n" + items.map((i) => " " + i).join("\n") + "\n}";
|
||||
return declaration;
|
||||
}
|
||||
function stringifyImportAlias(item, isCJS = false) {
|
||||
return item.as === void 0 || item.name === item.as ? item.name : isCJS ? `${item.name}: ${item.as}` : `${item.name} as ${item.as}`;
|
||||
}
|
||||
function toImportModuleMap(imports) {
|
||||
const map = {};
|
||||
for (const _import of imports) {
|
||||
if (!map[_import.from]) {
|
||||
map[_import.from] = /* @__PURE__ */ new Set();
|
||||
}
|
||||
map[_import.from].add(_import);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
function getString(code) {
|
||||
if (typeof code === "string") {
|
||||
return code;
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
function getMagicString(code) {
|
||||
if (typeof code === "string") {
|
||||
return new MagicString(code);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
function addImportToCode(code, imports, isCJS = false, mergeExisting = false) {
|
||||
let newImports = [];
|
||||
const s = getMagicString(code);
|
||||
if (mergeExisting && !isCJS) {
|
||||
const existing = findStaticImports(s.original).map((i) => parseStaticImport(i));
|
||||
const map = /* @__PURE__ */ new Map();
|
||||
imports.forEach((i) => {
|
||||
const target = existing.find((e) => e.specifier === i.from && e.imports.startsWith("{"));
|
||||
if (!target) {
|
||||
return newImports.push(i);
|
||||
}
|
||||
if (!map.has(target)) {
|
||||
map.set(target, []);
|
||||
}
|
||||
map.get(target).push(i);
|
||||
});
|
||||
for (const [target, items] of map.entries()) {
|
||||
const strings = items.map((i) => stringifyImportAlias(i) + ", ");
|
||||
const importLength = target.code.match(/^\s*import\s*{/)?.[0]?.length;
|
||||
if (importLength) {
|
||||
s.appendLeft(target.start + importLength, " " + strings.join("").trim());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newImports = imports;
|
||||
}
|
||||
const newEntries = toImports(newImports, isCJS);
|
||||
if (newEntries) {
|
||||
s.prepend(newEntries + "\n");
|
||||
}
|
||||
return {
|
||||
s,
|
||||
get code() {
|
||||
return s.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
function normalizeImports(imports) {
|
||||
for (const _import of imports) {
|
||||
_import.as = _import.as ?? _import.name;
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
function resolveIdAbsolute(id, parentId) {
|
||||
return resolvePath(id, {
|
||||
url: parentId
|
||||
});
|
||||
}
|
||||
|
||||
const contextRE = /\b_ctx\.([\w_]+)\b/g;
|
||||
const UNREF_KEY = "_unimport_unref_";
|
||||
const vueTemplateAddon = () => ({
|
||||
async transform(s) {
|
||||
if (!s.original.includes("_ctx.")) {
|
||||
return s;
|
||||
}
|
||||
const matches = Array.from(s.original.matchAll(contextRE));
|
||||
const imports = await this.getImports();
|
||||
const targets = [];
|
||||
for (const match of matches) {
|
||||
const name = match[1];
|
||||
const item = imports.find((i) => i.as === name);
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
const start = match.index;
|
||||
const end = start + match[0].length;
|
||||
const tempName = `_unimport_${name}`;
|
||||
s.overwrite(start, end, `${UNREF_KEY}(${tempName})`);
|
||||
if (!targets.find((i) => i.as === tempName)) {
|
||||
targets.push({
|
||||
...item,
|
||||
as: tempName
|
||||
});
|
||||
}
|
||||
}
|
||||
if (targets.length) {
|
||||
targets.push({
|
||||
name: "unref",
|
||||
from: "vue",
|
||||
as: UNREF_KEY
|
||||
});
|
||||
s.prepend(toImports(targets));
|
||||
}
|
||||
return s;
|
||||
},
|
||||
async declaration(dts, options) {
|
||||
const imports = await this.getImports();
|
||||
const items = imports.map((i) => {
|
||||
const from = options?.resolvePath?.(i) || i.from;
|
||||
return `readonly ${i.as}: UnwrapRef<typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}>`;
|
||||
}).sort();
|
||||
return dts + `
|
||||
// for vue template auto import
|
||||
import { UnwrapRef } from 'vue'
|
||||
declare module 'vue' {
|
||||
interface ComponentCustomProperties {
|
||||
${items.map((i) => " " + i).join("\n")}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
export { stripCommentsAndStrings as a, dedupeImports as b, toExports as c, defineUnimportPreset as d, excludeRE as e, toTypeDeclarationItems as f, toTypeDeclarationFile as g, getString as h, importAsRE as i, getMagicString as j, addImportToCode as k, matchRE as m, normalizeImports as n, resolveIdAbsolute as r, separatorRE as s, toImports as t, vueTemplateAddon as v };
|
||||
848
node_modules/unimport/dist/shared/unimport.e56b747d.cjs
generated
vendored
Normal file
848
node_modules/unimport/dist/shared/unimport.e56b747d.cjs
generated
vendored
Normal file
@@ -0,0 +1,848 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const fg = require('fast-glob');
|
||||
const pathe = require('pathe');
|
||||
const mlly = require('mlly');
|
||||
const scule = require('scule');
|
||||
const vueTemplate = require('./unimport.7b88c06e.cjs');
|
||||
const localPkg = require('local-pkg');
|
||||
const os = require('os');
|
||||
const pkgTypes = require('pkg-types');
|
||||
|
||||
const pinia = vueTemplate.defineUnimportPreset({
|
||||
from: "pinia",
|
||||
imports: [
|
||||
"acceptHMRUpdate",
|
||||
"createPinia",
|
||||
"defineStore",
|
||||
"getActivePinia",
|
||||
"mapActions",
|
||||
"mapGetters",
|
||||
"mapState",
|
||||
"mapStores",
|
||||
"mapWritableState",
|
||||
"setActivePinia",
|
||||
"setMapStoreSuffix",
|
||||
"storeToRefs"
|
||||
]
|
||||
});
|
||||
|
||||
const preact = vueTemplate.defineUnimportPreset({
|
||||
from: "preact",
|
||||
imports: [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
});
|
||||
|
||||
const quasar = vueTemplate.defineUnimportPreset({
|
||||
from: "quasar",
|
||||
imports: [
|
||||
"useQuasar",
|
||||
"useDialogPluginComponent",
|
||||
"useFormChild",
|
||||
"useMeta"
|
||||
]
|
||||
});
|
||||
|
||||
const react = vueTemplate.defineUnimportPreset({
|
||||
from: "react",
|
||||
imports: [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
});
|
||||
|
||||
const ReactRouterHooks = [
|
||||
"useOutletContext",
|
||||
"useHref",
|
||||
"useInRouterContext",
|
||||
"useLocation",
|
||||
"useNavigationType",
|
||||
"useNavigate",
|
||||
"useOutlet",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRoutes"
|
||||
];
|
||||
const reactRouter = vueTemplate.defineUnimportPreset({
|
||||
from: "react-router",
|
||||
imports: [
|
||||
...ReactRouterHooks
|
||||
]
|
||||
});
|
||||
|
||||
const reactRouterDom = vueTemplate.defineUnimportPreset({
|
||||
from: "react-router-dom",
|
||||
imports: [
|
||||
...ReactRouterHooks,
|
||||
"useLinkClickHandler",
|
||||
"useSearchParams",
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Routes"
|
||||
]
|
||||
});
|
||||
|
||||
const svelteAnimate = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte/animate",
|
||||
imports: [
|
||||
"flip"
|
||||
]
|
||||
});
|
||||
const svelteEasing = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte/easing",
|
||||
imports: [
|
||||
"back",
|
||||
"bounce",
|
||||
"circ",
|
||||
"cubic",
|
||||
"elastic",
|
||||
"expo",
|
||||
"quad",
|
||||
"quart",
|
||||
"quint",
|
||||
"sine"
|
||||
].reduce((acc, e) => {
|
||||
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
|
||||
return acc;
|
||||
}, ["linear"])
|
||||
});
|
||||
const svelteStore = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte/store",
|
||||
imports: [
|
||||
"writable",
|
||||
"readable",
|
||||
"derived",
|
||||
"get"
|
||||
]
|
||||
});
|
||||
const svelteMotion = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte/motion",
|
||||
imports: [
|
||||
"tweened",
|
||||
"spring"
|
||||
]
|
||||
});
|
||||
const svelteTransition = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte/transition",
|
||||
imports: [
|
||||
"fade",
|
||||
"blur",
|
||||
"fly",
|
||||
"slide",
|
||||
"scale",
|
||||
"draw",
|
||||
"crossfade"
|
||||
]
|
||||
});
|
||||
const svelte = vueTemplate.defineUnimportPreset({
|
||||
from: "svelte",
|
||||
imports: [
|
||||
"onMount",
|
||||
"beforeUpdate",
|
||||
"afterUpdate",
|
||||
"onDestroy",
|
||||
"tick",
|
||||
"setContext",
|
||||
"getContext",
|
||||
"hasContext",
|
||||
"getAllContexts",
|
||||
"createEventDispatcher"
|
||||
]
|
||||
});
|
||||
|
||||
const veeValidate = vueTemplate.defineUnimportPreset({
|
||||
from: "vee-validate",
|
||||
imports: [
|
||||
"validate",
|
||||
"defineRule",
|
||||
"configure",
|
||||
"useField",
|
||||
"useForm",
|
||||
"useFieldArray",
|
||||
"useResetForm",
|
||||
"useIsFieldDirty",
|
||||
"useIsFieldTouched",
|
||||
"useIsFieldValid",
|
||||
"useIsSubmitting",
|
||||
"useValidateField",
|
||||
"useIsFormDirty",
|
||||
"useIsFormTouched",
|
||||
"useIsFormValid",
|
||||
"useValidateForm",
|
||||
"useSubmitCount",
|
||||
"useFieldValue",
|
||||
"useFormValues",
|
||||
"useFormErrors",
|
||||
"useFieldError",
|
||||
"useSubmitForm",
|
||||
"FormContextKey",
|
||||
"FieldContextKey"
|
||||
]
|
||||
});
|
||||
|
||||
const vitepress = vueTemplate.defineUnimportPreset({
|
||||
from: "vitepress",
|
||||
imports: [
|
||||
"useData",
|
||||
"useRoute",
|
||||
"useRouter",
|
||||
"withBase"
|
||||
]
|
||||
});
|
||||
|
||||
const CommonCompositionAPI = [
|
||||
"onActivated",
|
||||
"onBeforeMount",
|
||||
"onBeforeUnmount",
|
||||
"onBeforeUpdate",
|
||||
"onErrorCaptured",
|
||||
"onDeactivated",
|
||||
"onMounted",
|
||||
"onServerPrefetch",
|
||||
"onUnmounted",
|
||||
"onUpdated",
|
||||
"useAttrs",
|
||||
"useSlots",
|
||||
"computed",
|
||||
"customRef",
|
||||
"isReadonly",
|
||||
"isRef",
|
||||
"markRaw",
|
||||
"reactive",
|
||||
"readonly",
|
||||
"ref",
|
||||
"shallowReactive",
|
||||
"shallowReadonly",
|
||||
"shallowRef",
|
||||
"triggerRef",
|
||||
"toRaw",
|
||||
"toRef",
|
||||
"toRefs",
|
||||
"unref",
|
||||
"watch",
|
||||
"watchEffect",
|
||||
"defineComponent",
|
||||
"defineAsyncComponent",
|
||||
"getCurrentInstance",
|
||||
"h",
|
||||
"inject",
|
||||
"nextTick",
|
||||
"provide",
|
||||
"useCssModule",
|
||||
"createApp",
|
||||
"effectScope",
|
||||
"EffectScope",
|
||||
"getCurrentScope",
|
||||
"onScopeDispose"
|
||||
];
|
||||
const vue = vueTemplate.defineUnimportPreset({
|
||||
from: "vue",
|
||||
imports: [
|
||||
...CommonCompositionAPI,
|
||||
"onRenderTracked",
|
||||
"onRenderTriggered",
|
||||
"resolveComponent",
|
||||
"useCssVars"
|
||||
]
|
||||
});
|
||||
|
||||
const vueMacros = vueTemplate.defineUnimportPreset({
|
||||
from: "vue/macros",
|
||||
imports: [
|
||||
"$",
|
||||
"$$",
|
||||
"$ref",
|
||||
"$shallowRef",
|
||||
"$toRef",
|
||||
"$customRef",
|
||||
"$computed"
|
||||
]
|
||||
});
|
||||
|
||||
const vueDemi = vueTemplate.defineUnimportPreset({
|
||||
from: "vue-demi",
|
||||
imports: CommonCompositionAPI
|
||||
});
|
||||
|
||||
const vueI18n = vueTemplate.defineUnimportPreset({
|
||||
from: "vue-i18n",
|
||||
imports: [
|
||||
"useI18n"
|
||||
]
|
||||
});
|
||||
|
||||
const vueRouter = vueTemplate.defineUnimportPreset({
|
||||
from: "vue-router",
|
||||
imports: [
|
||||
"useRouter",
|
||||
"useRoute"
|
||||
]
|
||||
});
|
||||
|
||||
const vueCompositionApi = vueTemplate.defineUnimportPreset({
|
||||
from: "@vue/composition-api",
|
||||
imports: CommonCompositionAPI
|
||||
});
|
||||
|
||||
let _cache;
|
||||
const vueuseCore = () => {
|
||||
const excluded = ["toRefs", "utils"];
|
||||
if (!_cache) {
|
||||
try {
|
||||
const corePath = localPkg.resolveModule("@vueuse/core") || process.cwd();
|
||||
const path = localPkg.resolveModule("@vueuse/core/indexes.json") || localPkg.resolveModule("@vueuse/metadata/index.json") || localPkg.resolveModule("@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
const indexesJson = JSON.parse(fs.readFileSync(path, "utf-8"));
|
||||
_cache = vueTemplate.defineUnimportPreset({
|
||||
from: "@vueuse/core",
|
||||
imports: indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).map((i) => i.name).filter((i) => i && i.length >= 4 && !excluded.includes(i))
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
|
||||
}
|
||||
}
|
||||
return _cache;
|
||||
};
|
||||
|
||||
const vueuseHead = vueTemplate.defineUnimportPreset({
|
||||
from: "@vueuse/head",
|
||||
imports: [
|
||||
"useHead"
|
||||
]
|
||||
});
|
||||
|
||||
const vuex = vueTemplate.defineUnimportPreset({
|
||||
from: "vuex",
|
||||
imports: [
|
||||
"createStore",
|
||||
"createLogger",
|
||||
"mapState",
|
||||
"mapGetters",
|
||||
"mapActions",
|
||||
"mapMutations",
|
||||
"createNamespacedHelpers",
|
||||
"useStore"
|
||||
]
|
||||
});
|
||||
|
||||
const vitest = vueTemplate.defineUnimportPreset({
|
||||
from: "vitest",
|
||||
imports: [
|
||||
"suite",
|
||||
"test",
|
||||
"describe",
|
||||
"it",
|
||||
"chai",
|
||||
"expect",
|
||||
"assert",
|
||||
"vitest",
|
||||
"vi",
|
||||
"beforeAll",
|
||||
"afterAll",
|
||||
"beforeEach",
|
||||
"afterEach"
|
||||
]
|
||||
});
|
||||
|
||||
const uniApp = vueTemplate.defineUnimportPreset({
|
||||
from: "@dcloudio/uni-app",
|
||||
imports: [
|
||||
"onAddToFavorites",
|
||||
"onBackPress",
|
||||
"onError",
|
||||
"onHide",
|
||||
"onLaunch",
|
||||
"onLoad",
|
||||
"onNavigationBarButtonTap",
|
||||
"onNavigationBarSearchInputChanged",
|
||||
"onNavigationBarSearchInputClicked",
|
||||
"onNavigationBarSearchInputConfirmed",
|
||||
"onNavigationBarSearchInputFocusChanged",
|
||||
"onPageNotFound",
|
||||
"onPageScroll",
|
||||
"onPullDownRefresh",
|
||||
"onReachBottom",
|
||||
"onReady",
|
||||
"onResize",
|
||||
"onShareAppMessage",
|
||||
"onShareTimeline",
|
||||
"onShow",
|
||||
"onTabItemTap",
|
||||
"onThemeChange",
|
||||
"onUnhandledRejection",
|
||||
"onUnload"
|
||||
]
|
||||
});
|
||||
|
||||
const solidCore = vueTemplate.defineUnimportPreset({
|
||||
from: "solid-js",
|
||||
imports: [
|
||||
"createSignal",
|
||||
"createEffect",
|
||||
"createMemo",
|
||||
"createResource",
|
||||
"onMount",
|
||||
"onCleanup",
|
||||
"onError",
|
||||
"untrack",
|
||||
"batch",
|
||||
"on",
|
||||
"createRoot",
|
||||
"mergeProps",
|
||||
"splitProps",
|
||||
"useTransition",
|
||||
"observable",
|
||||
"mapArray",
|
||||
"indexArray",
|
||||
"createContext",
|
||||
"useContext",
|
||||
"children",
|
||||
"lazy",
|
||||
"createDeferred",
|
||||
"createRenderEffect",
|
||||
"createSelector",
|
||||
"For",
|
||||
"Show",
|
||||
"Switch",
|
||||
"Match",
|
||||
"Index",
|
||||
"ErrorBoundary",
|
||||
"Suspense",
|
||||
"SuspenseList"
|
||||
]
|
||||
});
|
||||
const solidStore = vueTemplate.defineUnimportPreset({
|
||||
from: "solid-js/store",
|
||||
imports: [
|
||||
"createStore",
|
||||
"produce",
|
||||
"reconcile",
|
||||
"createMutable"
|
||||
]
|
||||
});
|
||||
const solidWeb = vueTemplate.defineUnimportPreset({
|
||||
from: "solid-js/web",
|
||||
imports: [
|
||||
"Dynamic",
|
||||
"hydrate",
|
||||
"render",
|
||||
"renderToString",
|
||||
"renderToStringAsync",
|
||||
"renderToStream",
|
||||
"isServer",
|
||||
"Portal"
|
||||
]
|
||||
});
|
||||
const solid = vueTemplate.defineUnimportPreset({
|
||||
from: "solid-js",
|
||||
imports: [
|
||||
solidCore,
|
||||
solidStore,
|
||||
solidWeb
|
||||
]
|
||||
});
|
||||
|
||||
const solidAppRouter = vueTemplate.defineUnimportPreset({
|
||||
from: "solid-app-router",
|
||||
imports: [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
});
|
||||
|
||||
const builtinPresets = {
|
||||
"@vue/composition-api": vueCompositionApi,
|
||||
"@vueuse/core": vueuseCore,
|
||||
"@vueuse/head": vueuseHead,
|
||||
pinia,
|
||||
preact,
|
||||
quasar,
|
||||
react,
|
||||
"react-router": reactRouter,
|
||||
"react-router-dom": reactRouterDom,
|
||||
svelte,
|
||||
"svelte/animate": svelteAnimate,
|
||||
"svelte/easing": svelteEasing,
|
||||
"svelte/motion": svelteMotion,
|
||||
"svelte/store": svelteStore,
|
||||
"svelte/transition": svelteTransition,
|
||||
"vee-validate": veeValidate,
|
||||
vitepress,
|
||||
"vue-demi": vueDemi,
|
||||
"vue-i18n": vueI18n,
|
||||
"vue-router": vueRouter,
|
||||
vue,
|
||||
"vue/macros": vueMacros,
|
||||
vuex,
|
||||
vitest,
|
||||
"uni-app": uniApp,
|
||||
"solid-js": solid,
|
||||
"solid-app-router": solidAppRouter
|
||||
};
|
||||
|
||||
const CACHE_PATH = /* @__PURE__ */ pathe.join(os.tmpdir(), "unimport");
|
||||
let CACHE_WRITEABLE;
|
||||
async function resolvePackagePreset(preset) {
|
||||
const scanned = await extractExports(preset.package, preset.url, preset.cache);
|
||||
const filtered = scanned.filter((name) => {
|
||||
for (const item of preset.ignore || []) {
|
||||
if (typeof item === "string" && item === name) {
|
||||
return false;
|
||||
}
|
||||
if (item instanceof RegExp && item.test(name)) {
|
||||
return false;
|
||||
}
|
||||
if (typeof item === "function" && item(name) === false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return filtered.map((name) => ({
|
||||
from: preset.package,
|
||||
name
|
||||
}));
|
||||
}
|
||||
async function extractExports(name, url, cache = true) {
|
||||
const packageJsonPath = await pkgTypes.resolvePackageJSON(name, { url });
|
||||
const packageJson = await pkgTypes.readPackageJSON(packageJsonPath);
|
||||
const version = packageJson.version;
|
||||
const cachePath = pathe.join(CACHE_PATH, name + "@" + version, "exports.json");
|
||||
if (cache && CACHE_WRITEABLE === void 0) {
|
||||
try {
|
||||
CACHE_WRITEABLE = isWritable(CACHE_PATH);
|
||||
} catch {
|
||||
CACHE_WRITEABLE = false;
|
||||
}
|
||||
}
|
||||
const useCache = cache && version && CACHE_WRITEABLE;
|
||||
if (useCache && fs.existsSync(cachePath)) {
|
||||
return JSON.parse(await fs.promises.readFile(cachePath, "utf-8"));
|
||||
}
|
||||
const scanned = await mlly.resolveModuleExportNames(name, { url });
|
||||
if (useCache) {
|
||||
await fs.promises.mkdir(pathe.dirname(cachePath), { recursive: true });
|
||||
await fs.promises.writeFile(cachePath, JSON.stringify(scanned), "utf-8");
|
||||
}
|
||||
return scanned;
|
||||
}
|
||||
function isWritable(filename) {
|
||||
try {
|
||||
fs.accessSync(filename, fs.constants.W_OK);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const commonProps = ["from", "priority", "disabled"];
|
||||
async function resolvePreset(preset) {
|
||||
const imports = [];
|
||||
if ("package" in preset) {
|
||||
return await resolvePackagePreset(preset);
|
||||
}
|
||||
const common = {};
|
||||
commonProps.forEach((i) => {
|
||||
if (i in preset) {
|
||||
common[i] = preset[i];
|
||||
}
|
||||
});
|
||||
for (const _import of preset.imports) {
|
||||
if (typeof _import === "string") {
|
||||
imports.push({ ...common, name: _import, as: _import });
|
||||
} else if (Array.isArray(_import)) {
|
||||
imports.push({ ...common, name: _import[0], as: _import[1] || _import[0], from: _import[2] || preset.from });
|
||||
} else if (_import.imports) {
|
||||
imports.push(...await resolvePreset(_import));
|
||||
} else {
|
||||
imports.push({ ...common, ..._import });
|
||||
}
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
async function resolveBuiltinPresets(presets) {
|
||||
const resolved = await Promise.all(presets.map(async (p) => {
|
||||
let preset = typeof p === "string" ? builtinPresets[p] : p;
|
||||
if (typeof preset === "function") {
|
||||
preset = preset();
|
||||
}
|
||||
return await resolvePreset(preset);
|
||||
}));
|
||||
return resolved.flat();
|
||||
}
|
||||
|
||||
async function scanDirExports(dir, options) {
|
||||
const dirs = (Array.isArray(dir) ? dir : [dir]).map((d) => pathe.normalize(d));
|
||||
const fileFilter = options?.fileFilter || (() => true);
|
||||
const filePatterns = options?.filePatterns || ["*.{ts,js,mjs,cjs,mts,cts}"];
|
||||
const result = await Promise.all(
|
||||
dirs.map(
|
||||
async (i) => await fg(
|
||||
[i, ...filePatterns.map((p) => pathe.join(i, p))],
|
||||
{
|
||||
absolute: true,
|
||||
cwd: options?.cwd || process.cwd(),
|
||||
onlyFiles: true,
|
||||
followSymbolicLinks: true
|
||||
}
|
||||
).then(
|
||||
(r) => r.map((f) => pathe.normalize(f)).sort()
|
||||
)
|
||||
)
|
||||
);
|
||||
const files = Array.from(new Set(result.flat())).filter(fileFilter);
|
||||
const fileExports = await Promise.all(files.map(scanExports));
|
||||
return fileExports.flat();
|
||||
}
|
||||
async function scanExports(filepath) {
|
||||
const imports = [];
|
||||
const code = await fs.promises.readFile(filepath, "utf-8");
|
||||
const exports = mlly.findExports(code);
|
||||
const defaultExport = exports.find((i) => i.type === "default");
|
||||
if (defaultExport) {
|
||||
let name = pathe.parse(filepath).name;
|
||||
if (name === "index") {
|
||||
name = pathe.parse(filepath.split("/").slice(0, -1).join("/")).name;
|
||||
}
|
||||
imports.push({ name: "default", as: scule.camelCase(name), from: filepath });
|
||||
}
|
||||
for (const exp of exports) {
|
||||
if (exp.type === "named") {
|
||||
for (const name of exp.names) {
|
||||
imports.push({ name, as: name, from: filepath });
|
||||
}
|
||||
} else if (exp.type === "declaration") {
|
||||
if (exp.name) {
|
||||
imports.push({ name: exp.name, as: exp.name, from: filepath });
|
||||
}
|
||||
}
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
function createUnimport(opts) {
|
||||
let _combinedImports;
|
||||
const _map = /* @__PURE__ */ new Map();
|
||||
const addons = [];
|
||||
if (Array.isArray(opts.addons)) {
|
||||
addons.push(...opts.addons);
|
||||
} else if (opts.addons?.vueTemplate) {
|
||||
addons.push(vueTemplate.vueTemplateAddon());
|
||||
}
|
||||
opts.addons = addons;
|
||||
opts.commentsDisable = opts.commentsDisable ?? ["@unimport-disable", "@imports-disable"];
|
||||
opts.commentsDebug = opts.commentsDebug ?? ["@unimport-debug", "@imports-debug"];
|
||||
const ctx = {
|
||||
staticImports: [...opts.imports || []].filter(Boolean),
|
||||
dynamicImports: [],
|
||||
async getImports() {
|
||||
await resolvePromise;
|
||||
return updateImports();
|
||||
},
|
||||
async getImportMap() {
|
||||
await ctx.getImports();
|
||||
return _map;
|
||||
},
|
||||
invalidate() {
|
||||
_combinedImports = void 0;
|
||||
},
|
||||
resolveId: (id, parentId) => opts.resolveId?.(id, parentId),
|
||||
addons,
|
||||
options: opts
|
||||
};
|
||||
const resolvePromise = resolveBuiltinPresets(opts.presets || []).then((r) => {
|
||||
ctx.staticImports.unshift(...r);
|
||||
_combinedImports = void 0;
|
||||
updateImports();
|
||||
});
|
||||
function updateImports() {
|
||||
if (!_combinedImports) {
|
||||
const imports = vueTemplate.normalizeImports(vueTemplate.dedupeImports([...ctx.staticImports, ...ctx.dynamicImports], opts.warn || console.warn)).filter((i) => !i.disabled);
|
||||
_map.clear();
|
||||
for (const _import of imports) {
|
||||
_map.set(_import.as ?? _import.name, _import);
|
||||
}
|
||||
_combinedImports = imports;
|
||||
}
|
||||
return _combinedImports;
|
||||
}
|
||||
async function modifyDynamicImports(fn) {
|
||||
const result = await fn(ctx.dynamicImports);
|
||||
if (Array.isArray(result)) {
|
||||
ctx.dynamicImports = result;
|
||||
}
|
||||
ctx.invalidate();
|
||||
}
|
||||
function clearDynamicImports() {
|
||||
ctx.dynamicImports.length = 0;
|
||||
ctx.invalidate();
|
||||
}
|
||||
async function generateTypeDeclarations(options) {
|
||||
const opts2 = {
|
||||
resolvePath: (i) => i.from.replace(/\.ts$/, ""),
|
||||
...options
|
||||
};
|
||||
let dts = vueTemplate.toTypeDeclarationFile(await ctx.getImports(), opts2);
|
||||
for (const addon of ctx.addons) {
|
||||
dts = await addon.declaration?.call(ctx, dts, opts2) ?? dts;
|
||||
}
|
||||
return dts;
|
||||
}
|
||||
return {
|
||||
clearDynamicImports,
|
||||
modifyDynamicImports,
|
||||
getImports: () => ctx.getImports(),
|
||||
detectImports: (code) => detectImports(code, ctx),
|
||||
injectImports: (code, id, options) => injectImports(code, id, ctx, options),
|
||||
toExports: async (filepath) => vueTemplate.toExports(await ctx.getImports(), filepath),
|
||||
parseVirtualImports: (code) => parseVirtualImports(code, ctx),
|
||||
generateTypeDeclarations
|
||||
};
|
||||
}
|
||||
function parseVirtualImports(code, ctx) {
|
||||
if (ctx.options.virtualImports?.length) {
|
||||
return mlly.findStaticImports(code).filter((i) => ctx.options.virtualImports.includes(i.specifier)).map((i) => mlly.parseStaticImport(i));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
async function detectImports(code, ctx, options) {
|
||||
const s = vueTemplate.getMagicString(code);
|
||||
const original = s.original;
|
||||
const strippedCode = vueTemplate.stripCommentsAndStrings(original);
|
||||
const syntax = mlly.detectSyntax(strippedCode);
|
||||
const isCJSContext = syntax.hasCJS && !syntax.hasESM;
|
||||
let matchedImports = [];
|
||||
const map = await ctx.getImportMap();
|
||||
if (options?.autoImport !== false) {
|
||||
const identifiers = new Set(
|
||||
Array.from(strippedCode.matchAll(vueTemplate.matchRE)).map((i) => {
|
||||
if (i[1] === ".") {
|
||||
return "";
|
||||
}
|
||||
const end = strippedCode[i.index + i[0].length];
|
||||
if (end === ":" && !["?", "case"].includes(i[1].trim())) {
|
||||
return "";
|
||||
}
|
||||
return i[2];
|
||||
}).filter(Boolean)
|
||||
);
|
||||
for (const regex of vueTemplate.excludeRE) {
|
||||
for (const match of strippedCode.matchAll(regex)) {
|
||||
const segments = [...match[1]?.split(vueTemplate.separatorRE) || [], ...match[2]?.split(vueTemplate.separatorRE) || []];
|
||||
for (const segment of segments) {
|
||||
const identifier = segment.replace(vueTemplate.importAsRE, "").trim();
|
||||
identifiers.delete(identifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
matchedImports = Array.from(identifiers).map((name) => map.get(name)).filter((i) => i && !i.disabled);
|
||||
for (const addon of ctx.addons) {
|
||||
matchedImports = await addon.matchImports?.call(ctx, identifiers, matchedImports) || matchedImports;
|
||||
}
|
||||
}
|
||||
if (options?.transformVirtualImports !== false && options?.transformVirtualImoports !== false && ctx.options.virtualImports?.length) {
|
||||
const virtualImports = parseVirtualImports(original, ctx);
|
||||
virtualImports.forEach((i) => {
|
||||
s.remove(i.start, i.end);
|
||||
Object.entries(i.namedImports || {}).forEach(([name, as]) => {
|
||||
const original2 = map.get(name);
|
||||
if (!original2) {
|
||||
throw new Error(`[unimport] failed to find "${name}" imported from "${i.specifier}"`);
|
||||
}
|
||||
matchedImports.push({
|
||||
from: original2.from,
|
||||
name: original2.name,
|
||||
as
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
return {
|
||||
s,
|
||||
strippedCode,
|
||||
isCJSContext,
|
||||
matchedImports
|
||||
};
|
||||
}
|
||||
async function injectImports(code, id, ctx, options) {
|
||||
const s = vueTemplate.getMagicString(code);
|
||||
if (ctx.options.commentsDisable?.some((c) => s.original.includes(c))) {
|
||||
return {
|
||||
s,
|
||||
get code() {
|
||||
return s.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
for (const addon of ctx.addons) {
|
||||
await addon.transform?.call(ctx, s, id);
|
||||
}
|
||||
const { isCJSContext, matchedImports } = await detectImports(s, ctx, options);
|
||||
const imports = await resolveImports(ctx, matchedImports, id);
|
||||
if (ctx.options.commentsDebug?.some((c) => s.original.includes(c))) {
|
||||
const log = ctx.options.debugLog || console.log;
|
||||
log(`[unimport] ${imports.length} imports detected in "${id}"${imports.length ? ": " + imports.map((i) => i.name).join(", ") : ""}`);
|
||||
}
|
||||
return vueTemplate.addImportToCode(s, imports, isCJSContext, options?.mergeExisting);
|
||||
}
|
||||
async function resolveImports(ctx, imports, id) {
|
||||
const resolveCache = /* @__PURE__ */ new Map();
|
||||
const _imports = await Promise.all(imports.map(async (i) => {
|
||||
if (!resolveCache.has(i.from)) {
|
||||
resolveCache.set(i.from, await ctx.resolveId(i.from, id) || i.from);
|
||||
}
|
||||
const from = resolveCache.get(i.from);
|
||||
if (i.from === id || !from || from === "." || from === id) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
...i,
|
||||
from
|
||||
};
|
||||
}));
|
||||
return _imports.filter(Boolean);
|
||||
}
|
||||
|
||||
exports.builtinPresets = builtinPresets;
|
||||
exports.createUnimport = createUnimport;
|
||||
exports.resolveBuiltinPresets = resolveBuiltinPresets;
|
||||
exports.resolvePreset = resolvePreset;
|
||||
exports.scanDirExports = scanDirExports;
|
||||
exports.scanExports = scanExports;
|
||||
226
node_modules/unimport/dist/types-0d3b142b.d.ts
generated
vendored
Normal file
226
node_modules/unimport/dist/types-0d3b142b.d.ts
generated
vendored
Normal file
@@ -0,0 +1,226 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
declare const builtinPresets: {
|
||||
'@vue/composition-api': InlinePreset;
|
||||
'@vueuse/core': () => Preset;
|
||||
'@vueuse/head': InlinePreset;
|
||||
pinia: InlinePreset;
|
||||
preact: InlinePreset;
|
||||
quasar: InlinePreset;
|
||||
react: InlinePreset;
|
||||
'react-router': InlinePreset;
|
||||
'react-router-dom': InlinePreset;
|
||||
svelte: InlinePreset;
|
||||
'svelte/animate': InlinePreset;
|
||||
'svelte/easing': InlinePreset;
|
||||
'svelte/motion': InlinePreset;
|
||||
'svelte/store': InlinePreset;
|
||||
'svelte/transition': InlinePreset;
|
||||
'vee-validate': InlinePreset;
|
||||
vitepress: InlinePreset;
|
||||
'vue-demi': InlinePreset;
|
||||
'vue-i18n': InlinePreset;
|
||||
'vue-router': InlinePreset;
|
||||
vue: InlinePreset;
|
||||
'vue/macros': InlinePreset;
|
||||
vuex: InlinePreset;
|
||||
vitest: InlinePreset;
|
||||
'uni-app': InlinePreset;
|
||||
'solid-js': InlinePreset;
|
||||
'solid-app-router': InlinePreset;
|
||||
};
|
||||
type BuiltinPresetName = keyof typeof builtinPresets;
|
||||
|
||||
type ModuleId = string;
|
||||
type ImportName = string;
|
||||
interface ImportCommon {
|
||||
/** Module specifier to import from */
|
||||
from: ModuleId;
|
||||
/**
|
||||
* Priority of the import, if multiple imports have the same name, the one with the highest priority will be used
|
||||
* @default 1
|
||||
*/
|
||||
priority?: number;
|
||||
/** If this import is disabled */
|
||||
disabled?: boolean;
|
||||
}
|
||||
interface Import extends ImportCommon {
|
||||
/** Import name to be detected */
|
||||
name: ImportName;
|
||||
/** Import as this name */
|
||||
as?: ImportName;
|
||||
}
|
||||
type PresetImport = ImportName | [name: ImportName, as?: ImportName, from?: ModuleId] | Exclude<Import, 'from'>;
|
||||
interface InlinePreset extends ImportCommon {
|
||||
imports: (PresetImport | InlinePreset)[];
|
||||
}
|
||||
/**
|
||||
* Auto extract exports from a package for auto import
|
||||
*/
|
||||
interface PackagePreset {
|
||||
/**
|
||||
* Name of the package
|
||||
*/
|
||||
package: string;
|
||||
/**
|
||||
* Path of the importer
|
||||
* @default process.cwd()
|
||||
*/
|
||||
url?: string;
|
||||
/**
|
||||
* RegExp, string, or custom function to exclude names of the extracted imports
|
||||
*/
|
||||
ignore?: (string | RegExp | ((name: string) => boolean))[];
|
||||
/**
|
||||
* Use local cache if exits
|
||||
* @default true
|
||||
*/
|
||||
cache?: boolean;
|
||||
}
|
||||
type Preset = InlinePreset | PackagePreset;
|
||||
interface UnimportContext {
|
||||
staticImports: Import[];
|
||||
dynamicImports: Import[];
|
||||
getImports(): Promise<Import[]>;
|
||||
getImportMap(): Promise<Map<string, Import>>;
|
||||
addons: Addon[];
|
||||
invalidate(): void;
|
||||
resolveId(id: string, parentId?: string): Thenable<string | null | undefined | void>;
|
||||
options: Partial<UnimportOptions>;
|
||||
}
|
||||
interface AddonsOptions {
|
||||
/**
|
||||
* Enable auto import inside for Vue's <template>
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
vueTemplate?: boolean;
|
||||
}
|
||||
interface UnimportOptions {
|
||||
/**
|
||||
* Auto import items
|
||||
*/
|
||||
imports: Import[];
|
||||
/**
|
||||
* Auto import preset
|
||||
*/
|
||||
presets: (Preset | BuiltinPresetName)[];
|
||||
/**
|
||||
* Custom warning function
|
||||
* @default console.warn
|
||||
*/
|
||||
warn: (msg: string) => void;
|
||||
/**
|
||||
* Custom debug log function
|
||||
* @default console.log
|
||||
*/
|
||||
debugLog: (msg: string) => void;
|
||||
/**
|
||||
* Unimport Addons
|
||||
* To use built-in addons, use `addons: { vueTemplate: true }`
|
||||
*
|
||||
* Built-in addons:
|
||||
* - vueTemplate: enable auto import inside for Vue's <template>
|
||||
*
|
||||
* @default {}
|
||||
*/
|
||||
addons: AddonsOptions | Addon[];
|
||||
/**
|
||||
* Name of virtual modules that exposed all the registed auto-imports
|
||||
* @default []
|
||||
*/
|
||||
virtualImports: string[];
|
||||
/**
|
||||
* Custom resolver to auto import id
|
||||
*/
|
||||
resolveId?: (id: string, importee?: string) => Thenable<string | void>;
|
||||
/**
|
||||
* Custom magic comments to be opt-out for auto import, per file/module
|
||||
*
|
||||
* @default ['@unimport-disable', '@imports-disable']
|
||||
*/
|
||||
commentsDisable?: string[];
|
||||
/**
|
||||
* Custom magic comments to debug auto import, printed to console
|
||||
*
|
||||
* @default ['@unimport-debug', '@imports-debug']
|
||||
*/
|
||||
commentsDebug?: string[];
|
||||
}
|
||||
type PathFromResolver = (_import: Import) => string | undefined;
|
||||
interface ScanDirExportsOptions {
|
||||
/**
|
||||
* Glob patterns for matching files
|
||||
*
|
||||
* @default ['*.{ts,js,mjs,cjs,mts,cts}']
|
||||
*/
|
||||
filePatterns?: string[];
|
||||
/**
|
||||
* Custom function to filter scanned files
|
||||
*/
|
||||
fileFilter?: (file: string) => boolean;
|
||||
/**
|
||||
* Current working directory
|
||||
*
|
||||
* @default process.cwd()
|
||||
*/
|
||||
cwd?: string;
|
||||
}
|
||||
interface TypeDeclarationOptions {
|
||||
/**
|
||||
* Custom resolver for path of the import
|
||||
*/
|
||||
resolvePath?: PathFromResolver;
|
||||
/**
|
||||
* Append `export {}` to the end of the file
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
exportHelper?: boolean;
|
||||
}
|
||||
interface InjectImportsOptions {
|
||||
/**
|
||||
* Merge the existing imports
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
mergeExisting?: boolean;
|
||||
/**
|
||||
* If the module should be auto imported
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
autoImport?: boolean;
|
||||
/**
|
||||
* If the module should be transformed for virtual modules.
|
||||
* Only available when `virtualImports` is set.
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
transformVirtualImports?: boolean;
|
||||
/** @deprecated use `virtualImports` instead */
|
||||
transformVirtualImoports?: boolean;
|
||||
}
|
||||
type Thenable<T> = Promise<T> | T;
|
||||
interface Addon {
|
||||
transform?: (this: UnimportContext, code: MagicString, id: string | undefined) => Thenable<MagicString>;
|
||||
declaration?: (this: UnimportContext, dts: string, options: TypeDeclarationOptions) => Thenable<string>;
|
||||
matchImports?: (this: UnimportContext, identifiers: Set<string>, matched: Import[]) => Thenable<Import[] | void>;
|
||||
}
|
||||
interface InstallGlobalOptions {
|
||||
/**
|
||||
* @default globalThis
|
||||
*/
|
||||
globalObject?: any;
|
||||
/**
|
||||
* Overrides the existing property
|
||||
* @default false
|
||||
*/
|
||||
overrides?: boolean;
|
||||
}
|
||||
interface ImportInjectionResult {
|
||||
s: MagicString;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export { AddonsOptions as A, BuiltinPresetName as B, Import as I, ModuleId as M, Preset as P, ScanDirExportsOptions as S, TypeDeclarationOptions as T, UnimportOptions as U, InlinePreset as a, ImportInjectionResult as b, Thenable as c, InjectImportsOptions as d, InstallGlobalOptions as e, builtinPresets as f, ImportName as g, ImportCommon as h, PresetImport as i, PackagePreset as j, UnimportContext as k, PathFromResolver as l, Addon as m };
|
||||
64
node_modules/unimport/dist/unplugin.cjs
generated
vendored
Normal file
64
node_modules/unimport/dist/unplugin.cjs
generated
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
const fs = require('fs');
|
||||
const unplugin$1 = require('unplugin');
|
||||
const pluginutils = require('@rollup/pluginutils');
|
||||
const MagicString = require('magic-string');
|
||||
const context = require('./shared/unimport.e56b747d.cjs');
|
||||
require('fast-glob');
|
||||
require('pathe');
|
||||
require('mlly');
|
||||
require('scule');
|
||||
require('./shared/unimport.7b88c06e.cjs');
|
||||
require('strip-literal');
|
||||
require('local-pkg');
|
||||
require('os');
|
||||
require('pkg-types');
|
||||
|
||||
const defaultIncludes = [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/];
|
||||
const defaultExcludes = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/];
|
||||
function toArray(x) {
|
||||
return x == null ? [] : Array.isArray(x) ? x : [x];
|
||||
}
|
||||
const unplugin = unplugin$1.createUnplugin((options = {}) => {
|
||||
const ctx = context.createUnimport(options);
|
||||
const filter = pluginutils.createFilter(
|
||||
toArray(options.include || []).length ? options.include : defaultIncludes,
|
||||
options.exclude || defaultExcludes
|
||||
);
|
||||
const dts = options.dts === true ? "unimport.d.ts" : options.dts;
|
||||
return {
|
||||
name: "unimport",
|
||||
enforce: "post",
|
||||
transformInclude(id) {
|
||||
return filter(id);
|
||||
},
|
||||
async transform(code, id) {
|
||||
const s = new MagicString(code);
|
||||
await ctx.injectImports(s, id);
|
||||
if (!s.hasChanged()) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap()
|
||||
};
|
||||
},
|
||||
async buildStart() {
|
||||
if (options.dirs?.length) {
|
||||
await ctx.modifyDynamicImports(async (imports) => {
|
||||
imports.push(...await context.scanDirExports(options.dirs));
|
||||
});
|
||||
}
|
||||
if (dts) {
|
||||
return fs.promises.writeFile(dts, await ctx.generateTypeDeclarations(), "utf-8");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
exports.default = unplugin;
|
||||
exports.defaultExcludes = defaultExcludes;
|
||||
exports.defaultIncludes = defaultIncludes;
|
||||
16
node_modules/unimport/dist/unplugin.d.ts
generated
vendored
Normal file
16
node_modules/unimport/dist/unplugin.d.ts
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import * as unplugin from 'unplugin';
|
||||
import { FilterPattern } from '@rollup/pluginutils';
|
||||
import { U as UnimportOptions } from './types-0d3b142b.js';
|
||||
import 'magic-string';
|
||||
|
||||
interface UnimportPluginOptions extends UnimportOptions {
|
||||
include: FilterPattern;
|
||||
exclude: FilterPattern;
|
||||
dts: boolean | string;
|
||||
dirs: string[];
|
||||
}
|
||||
declare const defaultIncludes: RegExp[];
|
||||
declare const defaultExcludes: RegExp[];
|
||||
declare const _default: unplugin.UnpluginInstance<Partial<UnimportPluginOptions>, boolean>;
|
||||
|
||||
export { UnimportPluginOptions, _default as default, defaultExcludes, defaultIncludes };
|
||||
58
node_modules/unimport/dist/unplugin.mjs
generated
vendored
Normal file
58
node_modules/unimport/dist/unplugin.mjs
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
import { promises } from 'fs';
|
||||
import { createUnplugin } from 'unplugin';
|
||||
import { createFilter } from '@rollup/pluginutils';
|
||||
import MagicString from 'magic-string';
|
||||
import { d as createUnimport, s as scanDirExports } from './shared/unimport.1330341c.mjs';
|
||||
import 'fast-glob';
|
||||
import 'pathe';
|
||||
import 'mlly';
|
||||
import 'scule';
|
||||
import './shared/unimport.bbd7571a.mjs';
|
||||
import 'strip-literal';
|
||||
import 'local-pkg';
|
||||
import 'os';
|
||||
import 'pkg-types';
|
||||
|
||||
const defaultIncludes = [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/];
|
||||
const defaultExcludes = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/];
|
||||
function toArray(x) {
|
||||
return x == null ? [] : Array.isArray(x) ? x : [x];
|
||||
}
|
||||
const unplugin = createUnplugin((options = {}) => {
|
||||
const ctx = createUnimport(options);
|
||||
const filter = createFilter(
|
||||
toArray(options.include || []).length ? options.include : defaultIncludes,
|
||||
options.exclude || defaultExcludes
|
||||
);
|
||||
const dts = options.dts === true ? "unimport.d.ts" : options.dts;
|
||||
return {
|
||||
name: "unimport",
|
||||
enforce: "post",
|
||||
transformInclude(id) {
|
||||
return filter(id);
|
||||
},
|
||||
async transform(code, id) {
|
||||
const s = new MagicString(code);
|
||||
await ctx.injectImports(s, id);
|
||||
if (!s.hasChanged()) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap()
|
||||
};
|
||||
},
|
||||
async buildStart() {
|
||||
if (options.dirs?.length) {
|
||||
await ctx.modifyDynamicImports(async (imports) => {
|
||||
imports.push(...await scanDirExports(options.dirs));
|
||||
});
|
||||
}
|
||||
if (dts) {
|
||||
return promises.writeFile(dts, await ctx.generateTypeDeclarations(), "utf-8");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export { unplugin as default, defaultExcludes, defaultIncludes };
|
||||
7
node_modules/unimport/node_modules/magic-string/LICENSE
generated
vendored
Normal file
7
node_modules/unimport/node_modules/magic-string/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright 2018 Rich Harris
|
||||
|
||||
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.
|
||||
289
node_modules/unimport/node_modules/magic-string/README.md
generated
vendored
Normal file
289
node_modules/unimport/node_modules/magic-string/README.md
generated
vendored
Normal file
@@ -0,0 +1,289 @@
|
||||
# magic-string
|
||||
|
||||
<a href="https://travis-ci.org/Rich-Harris/magic-string">
|
||||
<img src="http://img.shields.io/travis/Rich-Harris/magic-string.svg"
|
||||
alt="build status">
|
||||
</a>
|
||||
<a href="https://npmjs.org/package/magic-string">
|
||||
<img src="https://img.shields.io/npm/v/magic-string.svg"
|
||||
alt="npm version">
|
||||
</a>
|
||||
<a href="https://github.com/Rich-Harris/magic-string/blob/master/LICENSE.md">
|
||||
<img src="https://img.shields.io/npm/l/magic-string.svg"
|
||||
alt="license">
|
||||
</a>
|
||||
|
||||
Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a [source map](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/) at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript).
|
||||
|
||||
Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps.
|
||||
|
||||
## Installation
|
||||
|
||||
magic-string works in both node.js and browser environments. For node, install with npm:
|
||||
|
||||
```bash
|
||||
npm i magic-string
|
||||
```
|
||||
|
||||
To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page:
|
||||
|
||||
```html
|
||||
<script src='magic-string.umd.js'></script>
|
||||
```
|
||||
|
||||
(It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).)
|
||||
|
||||
## Usage
|
||||
|
||||
These examples assume you're in node.js, or something similar:
|
||||
|
||||
```js
|
||||
import MagicString from 'magic-string';
|
||||
import fs from 'fs'
|
||||
|
||||
const s = new MagicString('problems = 99');
|
||||
|
||||
s.update(0, 8, 'answer');
|
||||
s.toString(); // 'answer = 99'
|
||||
|
||||
s.update(11, 13, '42'); // character indices always refer to the original string
|
||||
s.toString(); // 'answer = 42'
|
||||
|
||||
s.prepend('var ').append(';'); // most methods are chainable
|
||||
s.toString(); // 'var answer = 42;'
|
||||
|
||||
const map = s.generateMap({
|
||||
source: 'source.js',
|
||||
file: 'converted.js.map',
|
||||
includeContent: true
|
||||
}); // generates a v3 sourcemap
|
||||
|
||||
fs.writeFileSync('converted.js', s.toString());
|
||||
fs.writeFileSync('converted.js.map', map.toString());
|
||||
```
|
||||
|
||||
You can pass an options argument:
|
||||
|
||||
```js
|
||||
const s = new MagicString(someCode, {
|
||||
// both these options will be used if you later
|
||||
// call `bundle.addSource( s )` - see below
|
||||
filename: 'foo.js',
|
||||
indentExclusionRanges: [/*...*/]
|
||||
});
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
### s.addSourcemapLocation( index )
|
||||
|
||||
Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below).
|
||||
|
||||
### s.append( content )
|
||||
|
||||
Appends the specified content to the end of the string. Returns `this`.
|
||||
|
||||
### s.appendLeft( index, content )
|
||||
|
||||
Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`.
|
||||
|
||||
### s.appendRight( index, content )
|
||||
|
||||
Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`.
|
||||
|
||||
### s.clone()
|
||||
|
||||
Does what you'd expect.
|
||||
|
||||
### s.generateDecodedMap( options )
|
||||
|
||||
Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
|
||||
|
||||
### s.generateMap( options )
|
||||
|
||||
Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional:
|
||||
|
||||
* `file` - the filename where you plan to write the sourcemap
|
||||
* `source` - the filename of the file containing the original source
|
||||
* `includeContent` - whether to include the original content in the map's `sourcesContent` array
|
||||
* `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. If sourcemap locations have been specified with `s.addSourceMapLocation()`, they will be used here.
|
||||
|
||||
The returned sourcemap has two (non-enumerable) methods attached for convenience:
|
||||
|
||||
* `toString` - returns the equivalent of `JSON.stringify(map)`
|
||||
* `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
|
||||
|
||||
```js
|
||||
code += '\n//# sourceMappingURL=' + map.toUrl();
|
||||
```
|
||||
|
||||
### s.hasChanged()
|
||||
|
||||
Indicates if the string has been changed.
|
||||
|
||||
### s.indent( prefix[, options] )
|
||||
|
||||
Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`.
|
||||
|
||||
The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings.
|
||||
|
||||
### s.insertLeft( index, content )
|
||||
|
||||
**DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead
|
||||
|
||||
### s.insertRight( index, content )
|
||||
|
||||
**DEPRECATED** since 0.17 – use `s.prependRight(...)` instead
|
||||
|
||||
### s.isEmpty()
|
||||
|
||||
Returns true if the resulting source is empty (disregarding white space).
|
||||
|
||||
### s.locate( index )
|
||||
|
||||
**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
|
||||
|
||||
### s.locateOrigin( index )
|
||||
|
||||
**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
|
||||
|
||||
### s.move( start, end, index )
|
||||
|
||||
Moves the characters from `start` and `end` to `index`. Returns `this`.
|
||||
|
||||
### s.overwrite( start, end, content[, options] )
|
||||
|
||||
Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in that range. The same restrictions as `s.remove()` apply. Returns `this`.
|
||||
|
||||
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well.
|
||||
|
||||
It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
|
||||
|
||||
### s.prepend( content )
|
||||
|
||||
Prepends the string with the specified content. Returns `this`.
|
||||
|
||||
### s.prependLeft ( index, content )
|
||||
|
||||
Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
|
||||
|
||||
### s.prependRight ( index, content )
|
||||
|
||||
Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
|
||||
|
||||
### s.replace( regexpOrString, substitution )
|
||||
|
||||
String replacement with RegExp or string. When using a RegExp, replacer function is also supported. Returns `this`.
|
||||
|
||||
```ts
|
||||
import MagicString from 'magic-string'
|
||||
|
||||
const s = new MagicString(source)
|
||||
|
||||
s.replace('foo', 'bar')
|
||||
s.replace(/foo/g, 'bar')
|
||||
s.replace(/(\w)(\d+)/g, (_, $1, $2) => $1.toUpperCase() + $2)
|
||||
```
|
||||
|
||||
The differences from [`String.replace`]((https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)):
|
||||
- It will always match against the **original string**
|
||||
- It mutates the magic string state (use `.clone()` to be immutable)
|
||||
|
||||
### s.replaceAll( regexpOrString, substitution )
|
||||
|
||||
Same as `s.replace`, but replace all matched strings instead of just one.
|
||||
If `substitution` is a regex, then it must have the global (`g`) flag set, or a `TypeError` is thrown. Matches the behavior of the bultin [`String.property.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll).
|
||||
|
||||
### s.remove( start, end )
|
||||
|
||||
Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`.
|
||||
|
||||
### s.slice( start, end )
|
||||
|
||||
Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed.
|
||||
|
||||
### s.snip( start, end )
|
||||
|
||||
Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
|
||||
|
||||
### s.toString()
|
||||
|
||||
Returns the generated string.
|
||||
|
||||
### s.trim([ charType ])
|
||||
|
||||
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`.
|
||||
|
||||
### s.trimStart([ charType ])
|
||||
|
||||
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`.
|
||||
|
||||
### s.trimEnd([ charType ])
|
||||
|
||||
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`.
|
||||
|
||||
### s.trimLines()
|
||||
|
||||
Removes empty lines from the start and end. Returns `this`.
|
||||
|
||||
### s.update( start, end, content[, options] )
|
||||
|
||||
Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`.
|
||||
|
||||
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and an `overwrite` property which defaults to `false` and determines whether anything that was appended/prepended to the range will be overwritten along with the original content.
|
||||
|
||||
`s.update(start, end, content)` is equivalent to `s.overwrite(start, end, content, { contentOnly: true })`.
|
||||
|
||||
## Bundling
|
||||
|
||||
To concatenate several sources, use `MagicString.Bundle`:
|
||||
|
||||
```js
|
||||
const bundle = new MagicString.Bundle();
|
||||
|
||||
bundle.addSource({
|
||||
filename: 'foo.js',
|
||||
content: new MagicString('var answer = 42;')
|
||||
});
|
||||
|
||||
bundle.addSource({
|
||||
filename: 'bar.js',
|
||||
content: new MagicString('console.log( answer )')
|
||||
});
|
||||
|
||||
// Advanced: a source can include an `indentExclusionRanges` property
|
||||
// alongside `filename` and `content`. This will be passed to `s.indent()`
|
||||
// - see documentation above
|
||||
|
||||
bundle.indent() // optionally, pass an indent string, otherwise it will be guessed
|
||||
.prepend('(function () {\n')
|
||||
.append('}());');
|
||||
|
||||
bundle.toString();
|
||||
// (function () {
|
||||
// var answer = 42;
|
||||
// console.log( answer );
|
||||
// }());
|
||||
|
||||
// options are as per `s.generateMap()` above
|
||||
const map = bundle.generateMap({
|
||||
file: 'bundle.js',
|
||||
includeContent: true,
|
||||
hires: true
|
||||
});
|
||||
```
|
||||
|
||||
As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself:
|
||||
|
||||
```js
|
||||
const bundle = new MagicString.Bundle();
|
||||
const source = new MagicString(someCode, {
|
||||
filename: 'foo.js'
|
||||
});
|
||||
|
||||
bundle.addSource(source);
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
1431
node_modules/unimport/node_modules/magic-string/dist/magic-string.cjs.js
generated
vendored
Normal file
1431
node_modules/unimport/node_modules/magic-string/dist/magic-string.cjs.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.cjs.js.map
generated
vendored
Normal file
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.cjs.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1425
node_modules/unimport/node_modules/magic-string/dist/magic-string.es.mjs
generated
vendored
Normal file
1425
node_modules/unimport/node_modules/magic-string/dist/magic-string.es.mjs
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.es.mjs.map
generated
vendored
Normal file
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.es.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1523
node_modules/unimport/node_modules/magic-string/dist/magic-string.umd.js
generated
vendored
Normal file
1523
node_modules/unimport/node_modules/magic-string/dist/magic-string.umd.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.umd.js.map
generated
vendored
Normal file
1
node_modules/unimport/node_modules/magic-string/dist/magic-string.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
250
node_modules/unimport/node_modules/magic-string/index.d.ts
generated
vendored
Normal file
250
node_modules/unimport/node_modules/magic-string/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,250 @@
|
||||
export interface BundleOptions {
|
||||
intro?: string;
|
||||
separator?: string;
|
||||
}
|
||||
|
||||
export interface SourceMapOptions {
|
||||
/**
|
||||
* Whether the mapping should be high-resolution.
|
||||
* Hi-res mappings map every single character, meaning (for example) your devtools will always
|
||||
* be able to pinpoint the exact location of function calls and so on.
|
||||
* With lo-res mappings, devtools may only be able to identify the correct
|
||||
* line - but they're quicker to generate and less bulky.
|
||||
* If sourcemap locations have been specified with s.addSourceMapLocation(), they will be used here.
|
||||
*/
|
||||
hires?: boolean;
|
||||
/**
|
||||
* The filename where you plan to write the sourcemap.
|
||||
*/
|
||||
file?: string;
|
||||
/**
|
||||
* The filename of the file containing the original source.
|
||||
*/
|
||||
source?: string;
|
||||
/**
|
||||
* Whether to include the original content in the map's sourcesContent array.
|
||||
*/
|
||||
includeContent?: boolean;
|
||||
}
|
||||
|
||||
export type SourceMapSegment =
|
||||
| [number]
|
||||
| [number, number, number, number]
|
||||
| [number, number, number, number, number];
|
||||
|
||||
export interface DecodedSourceMap {
|
||||
file: string;
|
||||
sources: string[];
|
||||
sourcesContent: string[];
|
||||
names: string[];
|
||||
mappings: SourceMapSegment[][];
|
||||
}
|
||||
|
||||
export class SourceMap {
|
||||
constructor(properties: DecodedSourceMap);
|
||||
|
||||
version: number;
|
||||
file: string;
|
||||
sources: string[];
|
||||
sourcesContent: string[];
|
||||
names: string[];
|
||||
mappings: string;
|
||||
|
||||
/**
|
||||
* Returns the equivalent of `JSON.stringify(map)`
|
||||
*/
|
||||
toString(): string;
|
||||
/**
|
||||
* Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
|
||||
* `generateMap(options?: SourceMapOptions): SourceMap;`
|
||||
*/
|
||||
toUrl(): string;
|
||||
}
|
||||
|
||||
export class Bundle {
|
||||
constructor(options?: BundleOptions);
|
||||
addSource(source: MagicString | { filename?: string, content: MagicString }): Bundle;
|
||||
append(str: string, options?: BundleOptions): Bundle;
|
||||
clone(): Bundle;
|
||||
generateMap(options?: SourceMapOptions): SourceMap;
|
||||
generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap;
|
||||
getIndentString(): string;
|
||||
indent(indentStr?: string): Bundle;
|
||||
indentExclusionRanges: ExclusionRange | Array<ExclusionRange>;
|
||||
prepend(str: string): Bundle;
|
||||
toString(): string;
|
||||
trimLines(): Bundle;
|
||||
trim(charType?: string): Bundle;
|
||||
trimStart(charType?: string): Bundle;
|
||||
trimEnd(charType?: string): Bundle;
|
||||
isEmpty(): boolean;
|
||||
length(): number;
|
||||
}
|
||||
|
||||
export type ExclusionRange = [ number, number ];
|
||||
|
||||
export interface MagicStringOptions {
|
||||
filename?: string,
|
||||
indentExclusionRanges?: ExclusionRange | Array<ExclusionRange>;
|
||||
}
|
||||
|
||||
export interface IndentOptions {
|
||||
exclude?: ExclusionRange | Array<ExclusionRange>;
|
||||
indentStart?: boolean;
|
||||
}
|
||||
|
||||
export interface OverwriteOptions {
|
||||
storeName?: boolean;
|
||||
contentOnly?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateOptions {
|
||||
storeName?: boolean;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
export default class MagicString {
|
||||
constructor(str: string, options?: MagicStringOptions);
|
||||
/**
|
||||
* Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
|
||||
*/
|
||||
addSourcemapLocation(char: number): void;
|
||||
/**
|
||||
* Appends the specified content to the end of the string.
|
||||
*/
|
||||
append(content: string): MagicString;
|
||||
/**
|
||||
* Appends the specified content at the index in the original string.
|
||||
* If a range *ending* with index is subsequently moved, the insert will be moved with it.
|
||||
* See also `s.prependLeft(...)`.
|
||||
*/
|
||||
appendLeft(index: number, content: string): MagicString;
|
||||
/**
|
||||
* Appends the specified content at the index in the original string.
|
||||
* If a range *starting* with index is subsequently moved, the insert will be moved with it.
|
||||
* See also `s.prependRight(...)`.
|
||||
*/
|
||||
appendRight(index: number, content: string): MagicString;
|
||||
/**
|
||||
* Does what you'd expect.
|
||||
*/
|
||||
clone(): MagicString;
|
||||
/**
|
||||
* Generates a version 3 sourcemap.
|
||||
*/
|
||||
generateMap(options?: SourceMapOptions): SourceMap;
|
||||
/**
|
||||
* Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
|
||||
* Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
|
||||
*/
|
||||
generateDecodedMap(options?: SourceMapOptions): DecodedSourceMap;
|
||||
getIndentString(): string;
|
||||
|
||||
/**
|
||||
* Prefixes each line of the string with prefix.
|
||||
* If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character.
|
||||
*/
|
||||
indent(options?: IndentOptions): MagicString;
|
||||
/**
|
||||
* Prefixes each line of the string with prefix.
|
||||
* If prefix is not supplied, the indentation will be guessed from the original content, falling back to a single tab character.
|
||||
*
|
||||
* The options argument can have an exclude property, which is an array of [start, end] character ranges.
|
||||
* These ranges will be excluded from the indentation - useful for (e.g.) multiline strings.
|
||||
*/
|
||||
indent(indentStr?: string, options?: IndentOptions): MagicString;
|
||||
indentExclusionRanges: ExclusionRange | Array<ExclusionRange>;
|
||||
|
||||
/**
|
||||
* Moves the characters from `start and `end` to `index`.
|
||||
*/
|
||||
move(start: number, end: number, index: number): MagicString;
|
||||
/**
|
||||
* Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
|
||||
* that range. The same restrictions as `s.remove()` apply.
|
||||
*
|
||||
* The fourth argument is optional. It can have a storeName property — if true, the original name will be stored
|
||||
* for later inclusion in a sourcemap's names array — and a contentOnly property which determines whether only
|
||||
* the content is overwritten, or anything that was appended/prepended to the range as well.
|
||||
*
|
||||
* It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
|
||||
*/
|
||||
overwrite(start: number, end: number, content: string, options?: boolean | OverwriteOptions): MagicString;
|
||||
/**
|
||||
* Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
|
||||
*
|
||||
* The fourth argument is optional. It can have a storeName property — if true, the original name will be stored
|
||||
* for later inclusion in a sourcemap's names array — and an overwrite property which determines whether only
|
||||
* the content is overwritten, or anything that was appended/prepended to the range as well.
|
||||
*/
|
||||
update(start: number, end: number, content: string, options?: boolean | UpdateOptions): MagicString;
|
||||
/**
|
||||
* Prepends the string with the specified content.
|
||||
*/
|
||||
prepend(content: string): MagicString;
|
||||
/**
|
||||
* Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
|
||||
*/
|
||||
prependLeft(index: number, content: string): MagicString;
|
||||
/**
|
||||
* Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
|
||||
*/
|
||||
prependRight(index: number, content: string): MagicString;
|
||||
/**
|
||||
* Removes the characters from `start` to `end` (of the original string, **not** the generated string).
|
||||
* Removing the same content twice, or making removals that partially overlap, will cause an error.
|
||||
*/
|
||||
remove(start: number, end: number): MagicString;
|
||||
/**
|
||||
* Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string.
|
||||
* Throws error if the indices are for characters that were already removed.
|
||||
*/
|
||||
slice(start: number, end: number): string;
|
||||
/**
|
||||
* Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
|
||||
*/
|
||||
snip(start: number, end: number): MagicString;
|
||||
/**
|
||||
* Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
|
||||
*/
|
||||
trim(charType?: string): MagicString;
|
||||
/**
|
||||
* Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
|
||||
*/
|
||||
trimStart(charType?: string): MagicString;
|
||||
/**
|
||||
* Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
|
||||
*/
|
||||
trimEnd(charType?: string): MagicString;
|
||||
/**
|
||||
* Removes empty lines from the start and end.
|
||||
*/
|
||||
trimLines(): MagicString;
|
||||
/**
|
||||
* String replacement with RegExp or string.
|
||||
*/
|
||||
replace(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString;
|
||||
/**
|
||||
* Same as `s.replace`, but replace all matched strings instead of just one.
|
||||
*/
|
||||
replaceAll(regex: RegExp | string, replacement: string | ((substring: string, ...args: any[]) => string)): MagicString;
|
||||
|
||||
lastChar(): string;
|
||||
lastLine(): string;
|
||||
/**
|
||||
* Returns true if the resulting source is empty (disregarding white space).
|
||||
*/
|
||||
isEmpty(): boolean;
|
||||
length(): number;
|
||||
|
||||
/**
|
||||
* Indicates if the string has been changed.
|
||||
*/
|
||||
hasChanged(): boolean;
|
||||
|
||||
original: string;
|
||||
/**
|
||||
* Returns the generated string.
|
||||
*/
|
||||
toString(): string;
|
||||
}
|
||||
64
node_modules/unimport/node_modules/magic-string/package.json
generated
vendored
Normal file
64
node_modules/unimport/node_modules/magic-string/package.json
generated
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "magic-string",
|
||||
"version": "0.27.0",
|
||||
"description": "Modify strings, generate sourcemaps",
|
||||
"keywords": [
|
||||
"string",
|
||||
"string manipulation",
|
||||
"sourcemap",
|
||||
"templating",
|
||||
"transpilation"
|
||||
],
|
||||
"repository": "https://github.com/rich-harris/magic-string",
|
||||
"license": "MIT",
|
||||
"author": "Rich Harris",
|
||||
"main": "./dist/magic-string.cjs.js",
|
||||
"module": "./dist/magic-string.es.mjs",
|
||||
"jsnext:main": "./dist/magic-string.es.mjs",
|
||||
"types": "./index.d.ts",
|
||||
"exports": {
|
||||
"./package.json": "./package.json",
|
||||
".": {
|
||||
"import": "./dist/magic-string.es.mjs",
|
||||
"require": "./dist/magic-string.cjs.js",
|
||||
"types": "./index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist/*",
|
||||
"index.d.ts",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
|
||||
"format": "prettier --single-quote --print-width 100 --use-tabs --write src/*.js src/**/*.js",
|
||||
"lint": "eslint src test",
|
||||
"prepare": "npm run build",
|
||||
"prepublishOnly": "rm -rf dist && npm test",
|
||||
"release": "bumpp -x \"npm run changelog\" --all --commit --tag --push && npm publish",
|
||||
"pretest": "npm run lint && npm run build",
|
||||
"test": "mocha",
|
||||
"bench": "npm run build && node benchmark/index.mjs",
|
||||
"watch": "rollup -cw"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@rollup/plugin-replace": "^4.0.0",
|
||||
"benchmark": "^2.1.4",
|
||||
"bumpp": "^8.2.1",
|
||||
"conventional-changelog-cli": "^2.2.2",
|
||||
"eslint": "^8.23.1",
|
||||
"mocha": "^10.0.0",
|
||||
"prettier": "^2.7.1",
|
||||
"rollup": "^2.79.1",
|
||||
"source-map-js": "^1.0.2",
|
||||
"source-map-support": "^0.5.21"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.4.13"
|
||||
}
|
||||
}
|
||||
71
node_modules/unimport/package.json
generated
vendored
Normal file
71
node_modules/unimport/package.json
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"name": "unimport",
|
||||
"version": "1.1.0",
|
||||
"description": "Unified utils for auto importing APIs in modules",
|
||||
"repository": "unjs/unimport",
|
||||
"license": "MIT",
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs",
|
||||
"types": "./dist/index.d.ts"
|
||||
},
|
||||
"./unplugin": {
|
||||
"import": "./dist/unplugin.mjs",
|
||||
"require": "./dist/unplugin.cjs",
|
||||
"types": "./dist/unplugin.d.ts"
|
||||
},
|
||||
"./addons": {
|
||||
"import": "./dist/addons.mjs",
|
||||
"require": "./dist/addons.cjs",
|
||||
"types": "./dist/addons.d.ts"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"*.d.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"dev": "vitest dev",
|
||||
"lint": "eslint --ext .ts,.js,.mjs,.cjs .",
|
||||
"prepack": "unbuild",
|
||||
"play": "pnpm -C playground run dev",
|
||||
"play:build": "pnpm -C playground run build",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"release": "pnpm run test --run && standard-version && git push --follow-tags && npm publish",
|
||||
"test": "vitest --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"@rollup/pluginutils": "^5.0.2",
|
||||
"escape-string-regexp": "^5.0.0",
|
||||
"fast-glob": "^3.2.12",
|
||||
"local-pkg": "^0.4.2",
|
||||
"magic-string": "^0.27.0",
|
||||
"mlly": "^1.0.0",
|
||||
"pathe": "^1.0.0",
|
||||
"pkg-types": "^1.0.1",
|
||||
"scule": "^1.0.0",
|
||||
"strip-literal": "^1.0.0",
|
||||
"unplugin": "^1.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nuxtjs/eslint-config-typescript": "^12.0.0",
|
||||
"@vitest/coverage-c8": "^0.26.0",
|
||||
"eslint": "^8.30.0",
|
||||
"h3": "^1.0.2",
|
||||
"jquery": "^3.6.2",
|
||||
"standard-version": "^9.5.0",
|
||||
"typescript": "^4.9.4",
|
||||
"unbuild": "^1.0.2",
|
||||
"vitest": "^0.26.0",
|
||||
"vue-tsc": "^1.0.16"
|
||||
},
|
||||
"packageManager": "pnpm@7.18.2"
|
||||
}
|
||||
3
node_modules/unimport/unplugin.d.ts
generated
vendored
Normal file
3
node_modules/unimport/unplugin.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
// redirect for TypeScript to pick it up
|
||||
export * from './dist/unplugin'
|
||||
export { default } from './dist/unplugin'
|
||||
Reference in New Issue
Block a user