@meng-xi/vite-plugin 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README-en.md +150 -150
  2. package/README.md +84 -84
  3. package/dist/common/index.cjs +1 -0
  4. package/dist/common/index.d.cts +109 -0
  5. package/dist/common/index.d.mts +109 -0
  6. package/dist/common/index.d.ts +109 -0
  7. package/dist/common/index.mjs +1 -0
  8. package/dist/factory/index.cjs +1 -0
  9. package/dist/factory/index.d.cts +260 -0
  10. package/dist/factory/index.d.mts +260 -0
  11. package/dist/factory/index.d.ts +260 -0
  12. package/dist/factory/index.mjs +1 -0
  13. package/dist/index.cjs +1 -5
  14. package/dist/index.d.cts +7 -241
  15. package/dist/index.d.mts +7 -241
  16. package/dist/index.d.ts +7 -241
  17. package/dist/index.mjs +1 -5
  18. package/dist/logger/index.cjs +1 -0
  19. package/dist/logger/index.d.cts +1 -0
  20. package/dist/logger/index.d.mts +1 -0
  21. package/dist/logger/index.d.ts +1 -0
  22. package/dist/logger/index.mjs +1 -0
  23. package/dist/plugins/index.cjs +1 -0
  24. package/dist/plugins/index.d.cts +210 -0
  25. package/dist/plugins/index.d.mts +210 -0
  26. package/dist/plugins/index.d.ts +210 -0
  27. package/dist/plugins/index.mjs +1 -0
  28. package/dist/shared/vite-plugin.B3PARlU9.d.cts +119 -0
  29. package/dist/shared/vite-plugin.B3PARlU9.d.mts +119 -0
  30. package/dist/shared/vite-plugin.B3PARlU9.d.ts +119 -0
  31. package/dist/shared/vite-plugin.BT1oHRKK.cjs +1 -0
  32. package/dist/shared/vite-plugin.BTKhc7n7.cjs +3 -0
  33. package/dist/shared/vite-plugin.BZqhBDYR.mjs +1 -0
  34. package/dist/shared/vite-plugin.Bn8mcCzy.cjs +3 -0
  35. package/dist/shared/vite-plugin.CY2ydccp.mjs +3 -0
  36. package/dist/shared/vite-plugin.CiHfwMiN.d.cts +91 -0
  37. package/dist/shared/vite-plugin.CiHfwMiN.d.mts +91 -0
  38. package/dist/shared/vite-plugin.CiHfwMiN.d.ts +91 -0
  39. package/dist/shared/vite-plugin.ClHiVXD6.mjs +1 -0
  40. package/dist/shared/vite-plugin.DSRKYuae.mjs +3 -0
  41. package/dist/shared/vite-plugin.DrSzERYS.cjs +1 -0
  42. package/dist/shared/vite-plugin.UkE7CdSe.d.cts +43 -0
  43. package/dist/shared/vite-plugin.UkE7CdSe.d.mts +43 -0
  44. package/dist/shared/vite-plugin.UkE7CdSe.d.ts +43 -0
  45. package/package.json +72 -53
@@ -0,0 +1,260 @@
1
+ import { ResolvedConfig, Plugin } from 'vite';
2
+ import { B as BasePluginOptions, O as OptionsNormalizer, P as PluginFactory } from '../shared/vite-plugin.UkE7CdSe.mjs';
3
+ import { P as PluginLogger, a as LoggerOptions } from '../shared/vite-plugin.B3PARlU9.mjs';
4
+ import { V as Validator } from '../shared/vite-plugin.CiHfwMiN.mjs';
5
+
6
+ /**
7
+ * 基础插件抽象类,提供插件开发的核心功能和生命周期管理
8
+ *
9
+ * @class BasePlugin
10
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
11
+ * @abstract
12
+ * @description 该类是所有插件的基类,提供了插件配置管理、日志记录、生命周期管理等核心功能
13
+ * @example
14
+ * ```typescript
15
+ * class MyPlugin extends BasePlugin<MyPluginOptions> {
16
+ * protected getPluginName() {
17
+ * return 'my-plugin'
18
+ * }
19
+ *
20
+ * protected addPluginHooks(plugin: Plugin) {
21
+ * // 添加插件钩子
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ declare abstract class BasePlugin<T extends BasePluginOptions = BasePluginOptions> {
27
+ /**
28
+ * 插件配置
29
+ *
30
+ * @protected
31
+ * @description 插件配置,包含插件的运行参数和选项
32
+ */
33
+ protected options: Required<T>;
34
+ /**
35
+ * 插件日志记录器
36
+ *
37
+ * @protected
38
+ * @description 插件日志记录器,用于记录插件运行时的日志信息
39
+ */
40
+ protected logger: PluginLogger;
41
+ /**
42
+ * 插件配置验证器
43
+ *
44
+ * @protected
45
+ * @description 插件配置验证器,用于验证插件配置参数是否符合要求
46
+ */
47
+ protected validator: Validator<T>;
48
+ /**
49
+ * Vite 配置
50
+ *
51
+ * @protected
52
+ * @description Vite 配置,包含 Vite 构建的运行参数和选项
53
+ */
54
+ protected viteConfig: ResolvedConfig | null;
55
+ /**
56
+ * 插件构造函数
57
+ *
58
+ * @param options 插件配置
59
+ * @param loggerConfig 日志配置,可选
60
+ *
61
+ * @protected
62
+ * @description 插件构造函数,初始化插件配置、日志记录器和验证插件参数
63
+ */
64
+ constructor(options: T, loggerConfig?: LoggerOptions);
65
+ /**
66
+ * 获取插件的默认配置选项
67
+ *
68
+ * @protected
69
+ * @abstract
70
+ * @returns {Partial<T>} 插件特定的默认配置
71
+ * @description 子类必须实现此方法,以提供插件特定的默认配置值
72
+ */
73
+ protected abstract getDefaultOptions(): Partial<T>;
74
+ /**
75
+ * 合并插件配置,将用户提供的配置与默认配置合并
76
+ *
77
+ * @protected
78
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
79
+ * @param {T} options - 用户提供的插件配置
80
+ * @returns {Required<T>} 合并后的完整插件配置,包含所有必填字段
81
+ * @description 将用户提供的配置与基础默认值、插件特定默认值进行深度合并,确保所有必填字段都有值
82
+ * @example
83
+ * ```typescript
84
+ * const userOptions = { enabled: false }
85
+ * const mergedOptions = this.mergeOptions(userOptions)
86
+ * // mergedOptions 将包含基础默认值和插件特定默认值
87
+ * ```
88
+ */
89
+ protected mergeOptions(options: T): Required<T>;
90
+ /**
91
+ * 初始化日志记录器
92
+ *
93
+ * @private
94
+ * @param {LoggerOptions} loggerConfig - 日志配置对象,可选
95
+ * @returns {PluginLogger} 插件日志代理对象,用于记录插件日志
96
+ * @description 使用单例 Logger 创建插件特定的日志代理对象
97
+ */
98
+ private initLogger;
99
+ /**
100
+ * 验证插件配置参数,确保配置符合要求
101
+ *
102
+ * @protected
103
+ * @virtual
104
+ * @returns {void} 无返回值
105
+ * @throws {Error} 如果配置参数无效,抛出包含错误信息的异常
106
+ * @description 该方法在插件初始化时被调用,用于验证插件配置的有效性。子类可以重写此方法以添加自定义验证逻辑
107
+ * @example
108
+ * ```typescript
109
+ * protected validateOptions(): void {
110
+ * if (!this.options.sourceDir) {
111
+ * throw new Error('sourceDir 是必填项')
112
+ * }
113
+ *
114
+ * if (!this.options.targetDir) {
115
+ * throw new Error('targetDir 是必填项')
116
+ * }
117
+ * }
118
+ * ```
119
+ */
120
+ protected validateOptions(): void;
121
+ /**
122
+ * 获取插件名称
123
+ *
124
+ * @protected
125
+ * @returns {string} 插件的名称,用于 Vite 插件系统识别
126
+ */
127
+ protected abstract getPluginName(): string;
128
+ /**
129
+ * 获取插件执行时机
130
+ *
131
+ * @protected
132
+ * @returns {Plugin['enforce']} 插件的执行时机,可选值为 'pre'、'post' 或 undefined
133
+ * @description 'post' 表示插件在 Vite 构建后期执行
134
+ */
135
+ protected getEnforce(): Plugin['enforce'];
136
+ /**
137
+ * 处理配置解析完成事件
138
+ *
139
+ * @param config 解析后的 Vite 配置
140
+ *
141
+ * @protected
142
+ * @description 处理 Vite 配置解析完成事件,将解析后的配置存储到插件实例中
143
+ */
144
+ protected onConfigResolved(config: ResolvedConfig): void;
145
+ /**
146
+ * 添加插件钩子到 Vite 插件对象
147
+ *
148
+ * @protected
149
+ * @abstract
150
+ * @param {Plugin} plugin - Vite 插件对象,用于添加钩子
151
+ * @returns {void} 无返回值
152
+ * @description 添加插件钩子到 Vite 插件对象,用于在构建过程中执行插件逻辑
153
+ */
154
+ protected abstract addPluginHooks(plugin: Plugin): void;
155
+ /**
156
+ * 安全执行同步函数,自动处理执行过程中可能出现的错误
157
+ *
158
+ * @protected
159
+ * @template T - 函数的返回值类型
160
+ * @param {() => T} fn - 要执行的同步函数
161
+ * @param {string} context - 执行上下文描述,用于错误日志记录
162
+ * @returns {T | undefined} 函数的执行结果,如果执行过程中发生错误,根据错误策略返回 undefined 或抛出错误
163
+ * @description 该方法封装了同步函数的执行,自动处理可能出现的错误,根据插件配置的 errorStrategy 决定如何处理错误
164
+ * @example
165
+ * ```typescript
166
+ * // 安全执行同步操作
167
+ * const result = this.safeExecuteSync(() => {
168
+ * return someSyncOperation()
169
+ * }, '执行同步操作')
170
+ *
171
+ * // 如果 someSyncOperation() 抛出错误,会根据 errorStrategy 处理
172
+ * ```
173
+ */
174
+ protected safeExecuteSync<T>(fn: () => T, context: string): T | undefined;
175
+ /**
176
+ * 安全执行异步函数,自动处理执行过程中可能出现的错误
177
+ *
178
+ * @protected
179
+ * @async
180
+ * @template T - 异步函数的返回值类型
181
+ * @param {() => Promise<T>} fn - 要执行的异步函数
182
+ * @param {string} context - 执行上下文描述,用于错误日志记录
183
+ * @returns {Promise<T | undefined>} 异步函数的执行结果,如果执行过程中发生错误,根据错误策略返回 undefined 或抛出错误
184
+ * @description 该方法封装了异步函数的执行,自动处理可能出现的错误,根据插件配置的 errorStrategy 决定如何处理错误
185
+ * @example
186
+ * ```typescript
187
+ * // 安全执行异步操作
188
+ * const result = await this.safeExecute(async () => {
189
+ * return await someAsyncOperation()
190
+ * }, '执行异步操作')
191
+ *
192
+ * // 如果 someAsyncOperation() 抛出错误,会根据 errorStrategy 处理
193
+ * ```
194
+ */
195
+ protected safeExecute<T>(fn: () => Promise<T>, context: string): Promise<T | undefined>;
196
+ /**
197
+ * 处理插件执行过程中出现的错误,根据配置的错误策略决定如何处理
198
+ *
199
+ * @protected
200
+ * @template T - 返回值类型,仅当错误策略为 'log' 或 'ignore' 时返回 undefined
201
+ * @param {unknown} error - 捕获到的错误对象
202
+ * @param {string} context - 错误发生的上下文描述,用于错误日志记录
203
+ * @returns {T | undefined} 当错误策略为 'log' 或 'ignore' 时返回 undefined,否则抛出错误
204
+ * @description 根据插件配置的 errorStrategy 处理错误:
205
+ * - 'throw': 记录错误日志并抛出错误,中断执行
206
+ * - 'log': 记录错误日志但不抛出错误,继续执行
207
+ * - 'ignore': 记录错误日志但不抛出错误,继续执行
208
+ * - 默认:记录错误日志并抛出错误
209
+ * @example
210
+ * ```typescript
211
+ * // 当 errorStrategy 为 'throw' 时
212
+ * this.handleError(new Error('测试错误'), '测试上下文') // 记录错误日志并抛出错误
213
+ *
214
+ * // 当 errorStrategy 为 'log' 时
215
+ * this.handleError(new Error('测试错误'), '测试上下文') // 记录错误日志并返回 undefined
216
+ * ```
217
+ */
218
+ protected handleError<T>(error: unknown, context: string): T | undefined;
219
+ /**
220
+ * 将插件实例转换为 Vite 插件对象,用于 Vite 构建系统
221
+ *
222
+ * @public
223
+ * @returns {Plugin} Vite 插件对象,包含插件名称、执行时机和各种钩子函数
224
+ * @description 该方法创建并返回一个符合 Vite 插件规范的对象,设置了插件的基本信息和 configResolved 钩子,然后调用 addPluginHooks 方法添加插件特定的钩子
225
+ * @example
226
+ * ```typescript
227
+ * // 创建插件实例
228
+ * const pluginInstance = new MyPlugin(options)
229
+ *
230
+ * // 转换为 Vite 插件
231
+ * const vitePlugin = pluginInstance.toPlugin()
232
+ *
233
+ * // 导出 Vite 插件
234
+ * export const myPlugin = vitePlugin
235
+ * ```
236
+ */
237
+ toPlugin(): Plugin;
238
+ }
239
+ /**
240
+ * 创建插件工厂函数,用于生成 Vite 插件实例
241
+ *
242
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
243
+ * @template P - 插件实例类型,必须继承自 BasePlugin<T>
244
+ * @template R - 原始配置类型
245
+ * @param {new (options: T, loggerConfig?: LoggerOptions) => P} PluginClass - 插件类构造函数
246
+ * @param {OptionsNormalizer<T, R>} [normalizer] - 选项标准化器,可选
247
+ * @returns {PluginFactory<T, R>} 插件工厂函数,接收插件配置并返回 Vite 插件实例
248
+ * @description 该函数创建一个插件工厂,用于生成 Vite 插件实例。工厂函数接收插件配置,支持可选的标准化器,创建插件实例,转换为 Vite 插件对象,并在插件对象上添加对原始插件实例的引用
249
+ * @example
250
+ * ```typescript
251
+ * // 基本使用
252
+ * const myPluginFactory = createPluginFactory(MyPlugin)
253
+ *
254
+ * // 带标准化器的使用(支持字符串或对象)
255
+ * const myPluginWithNormalizer = createPluginFactory(MyPlugin, (opt) => typeof opt === 'string' ? { path: opt } : opt)
256
+ * ```
257
+ */
258
+ declare function createPluginFactory<T extends BasePluginOptions, P extends BasePlugin<T>, R = T>(PluginClass: new (options: T, loggerConfig?: LoggerOptions) => P, normalizer?: OptionsNormalizer<T, R>): PluginFactory<T, R>;
259
+
260
+ export { BasePlugin, createPluginFactory };
@@ -0,0 +1,260 @@
1
+ import { ResolvedConfig, Plugin } from 'vite';
2
+ import { B as BasePluginOptions, O as OptionsNormalizer, P as PluginFactory } from '../shared/vite-plugin.UkE7CdSe.js';
3
+ import { P as PluginLogger, a as LoggerOptions } from '../shared/vite-plugin.B3PARlU9.js';
4
+ import { V as Validator } from '../shared/vite-plugin.CiHfwMiN.js';
5
+
6
+ /**
7
+ * 基础插件抽象类,提供插件开发的核心功能和生命周期管理
8
+ *
9
+ * @class BasePlugin
10
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
11
+ * @abstract
12
+ * @description 该类是所有插件的基类,提供了插件配置管理、日志记录、生命周期管理等核心功能
13
+ * @example
14
+ * ```typescript
15
+ * class MyPlugin extends BasePlugin<MyPluginOptions> {
16
+ * protected getPluginName() {
17
+ * return 'my-plugin'
18
+ * }
19
+ *
20
+ * protected addPluginHooks(plugin: Plugin) {
21
+ * // 添加插件钩子
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ declare abstract class BasePlugin<T extends BasePluginOptions = BasePluginOptions> {
27
+ /**
28
+ * 插件配置
29
+ *
30
+ * @protected
31
+ * @description 插件配置,包含插件的运行参数和选项
32
+ */
33
+ protected options: Required<T>;
34
+ /**
35
+ * 插件日志记录器
36
+ *
37
+ * @protected
38
+ * @description 插件日志记录器,用于记录插件运行时的日志信息
39
+ */
40
+ protected logger: PluginLogger;
41
+ /**
42
+ * 插件配置验证器
43
+ *
44
+ * @protected
45
+ * @description 插件配置验证器,用于验证插件配置参数是否符合要求
46
+ */
47
+ protected validator: Validator<T>;
48
+ /**
49
+ * Vite 配置
50
+ *
51
+ * @protected
52
+ * @description Vite 配置,包含 Vite 构建的运行参数和选项
53
+ */
54
+ protected viteConfig: ResolvedConfig | null;
55
+ /**
56
+ * 插件构造函数
57
+ *
58
+ * @param options 插件配置
59
+ * @param loggerConfig 日志配置,可选
60
+ *
61
+ * @protected
62
+ * @description 插件构造函数,初始化插件配置、日志记录器和验证插件参数
63
+ */
64
+ constructor(options: T, loggerConfig?: LoggerOptions);
65
+ /**
66
+ * 获取插件的默认配置选项
67
+ *
68
+ * @protected
69
+ * @abstract
70
+ * @returns {Partial<T>} 插件特定的默认配置
71
+ * @description 子类必须实现此方法,以提供插件特定的默认配置值
72
+ */
73
+ protected abstract getDefaultOptions(): Partial<T>;
74
+ /**
75
+ * 合并插件配置,将用户提供的配置与默认配置合并
76
+ *
77
+ * @protected
78
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
79
+ * @param {T} options - 用户提供的插件配置
80
+ * @returns {Required<T>} 合并后的完整插件配置,包含所有必填字段
81
+ * @description 将用户提供的配置与基础默认值、插件特定默认值进行深度合并,确保所有必填字段都有值
82
+ * @example
83
+ * ```typescript
84
+ * const userOptions = { enabled: false }
85
+ * const mergedOptions = this.mergeOptions(userOptions)
86
+ * // mergedOptions 将包含基础默认值和插件特定默认值
87
+ * ```
88
+ */
89
+ protected mergeOptions(options: T): Required<T>;
90
+ /**
91
+ * 初始化日志记录器
92
+ *
93
+ * @private
94
+ * @param {LoggerOptions} loggerConfig - 日志配置对象,可选
95
+ * @returns {PluginLogger} 插件日志代理对象,用于记录插件日志
96
+ * @description 使用单例 Logger 创建插件特定的日志代理对象
97
+ */
98
+ private initLogger;
99
+ /**
100
+ * 验证插件配置参数,确保配置符合要求
101
+ *
102
+ * @protected
103
+ * @virtual
104
+ * @returns {void} 无返回值
105
+ * @throws {Error} 如果配置参数无效,抛出包含错误信息的异常
106
+ * @description 该方法在插件初始化时被调用,用于验证插件配置的有效性。子类可以重写此方法以添加自定义验证逻辑
107
+ * @example
108
+ * ```typescript
109
+ * protected validateOptions(): void {
110
+ * if (!this.options.sourceDir) {
111
+ * throw new Error('sourceDir 是必填项')
112
+ * }
113
+ *
114
+ * if (!this.options.targetDir) {
115
+ * throw new Error('targetDir 是必填项')
116
+ * }
117
+ * }
118
+ * ```
119
+ */
120
+ protected validateOptions(): void;
121
+ /**
122
+ * 获取插件名称
123
+ *
124
+ * @protected
125
+ * @returns {string} 插件的名称,用于 Vite 插件系统识别
126
+ */
127
+ protected abstract getPluginName(): string;
128
+ /**
129
+ * 获取插件执行时机
130
+ *
131
+ * @protected
132
+ * @returns {Plugin['enforce']} 插件的执行时机,可选值为 'pre'、'post' 或 undefined
133
+ * @description 'post' 表示插件在 Vite 构建后期执行
134
+ */
135
+ protected getEnforce(): Plugin['enforce'];
136
+ /**
137
+ * 处理配置解析完成事件
138
+ *
139
+ * @param config 解析后的 Vite 配置
140
+ *
141
+ * @protected
142
+ * @description 处理 Vite 配置解析完成事件,将解析后的配置存储到插件实例中
143
+ */
144
+ protected onConfigResolved(config: ResolvedConfig): void;
145
+ /**
146
+ * 添加插件钩子到 Vite 插件对象
147
+ *
148
+ * @protected
149
+ * @abstract
150
+ * @param {Plugin} plugin - Vite 插件对象,用于添加钩子
151
+ * @returns {void} 无返回值
152
+ * @description 添加插件钩子到 Vite 插件对象,用于在构建过程中执行插件逻辑
153
+ */
154
+ protected abstract addPluginHooks(plugin: Plugin): void;
155
+ /**
156
+ * 安全执行同步函数,自动处理执行过程中可能出现的错误
157
+ *
158
+ * @protected
159
+ * @template T - 函数的返回值类型
160
+ * @param {() => T} fn - 要执行的同步函数
161
+ * @param {string} context - 执行上下文描述,用于错误日志记录
162
+ * @returns {T | undefined} 函数的执行结果,如果执行过程中发生错误,根据错误策略返回 undefined 或抛出错误
163
+ * @description 该方法封装了同步函数的执行,自动处理可能出现的错误,根据插件配置的 errorStrategy 决定如何处理错误
164
+ * @example
165
+ * ```typescript
166
+ * // 安全执行同步操作
167
+ * const result = this.safeExecuteSync(() => {
168
+ * return someSyncOperation()
169
+ * }, '执行同步操作')
170
+ *
171
+ * // 如果 someSyncOperation() 抛出错误,会根据 errorStrategy 处理
172
+ * ```
173
+ */
174
+ protected safeExecuteSync<T>(fn: () => T, context: string): T | undefined;
175
+ /**
176
+ * 安全执行异步函数,自动处理执行过程中可能出现的错误
177
+ *
178
+ * @protected
179
+ * @async
180
+ * @template T - 异步函数的返回值类型
181
+ * @param {() => Promise<T>} fn - 要执行的异步函数
182
+ * @param {string} context - 执行上下文描述,用于错误日志记录
183
+ * @returns {Promise<T | undefined>} 异步函数的执行结果,如果执行过程中发生错误,根据错误策略返回 undefined 或抛出错误
184
+ * @description 该方法封装了异步函数的执行,自动处理可能出现的错误,根据插件配置的 errorStrategy 决定如何处理错误
185
+ * @example
186
+ * ```typescript
187
+ * // 安全执行异步操作
188
+ * const result = await this.safeExecute(async () => {
189
+ * return await someAsyncOperation()
190
+ * }, '执行异步操作')
191
+ *
192
+ * // 如果 someAsyncOperation() 抛出错误,会根据 errorStrategy 处理
193
+ * ```
194
+ */
195
+ protected safeExecute<T>(fn: () => Promise<T>, context: string): Promise<T | undefined>;
196
+ /**
197
+ * 处理插件执行过程中出现的错误,根据配置的错误策略决定如何处理
198
+ *
199
+ * @protected
200
+ * @template T - 返回值类型,仅当错误策略为 'log' 或 'ignore' 时返回 undefined
201
+ * @param {unknown} error - 捕获到的错误对象
202
+ * @param {string} context - 错误发生的上下文描述,用于错误日志记录
203
+ * @returns {T | undefined} 当错误策略为 'log' 或 'ignore' 时返回 undefined,否则抛出错误
204
+ * @description 根据插件配置的 errorStrategy 处理错误:
205
+ * - 'throw': 记录错误日志并抛出错误,中断执行
206
+ * - 'log': 记录错误日志但不抛出错误,继续执行
207
+ * - 'ignore': 记录错误日志但不抛出错误,继续执行
208
+ * - 默认:记录错误日志并抛出错误
209
+ * @example
210
+ * ```typescript
211
+ * // 当 errorStrategy 为 'throw' 时
212
+ * this.handleError(new Error('测试错误'), '测试上下文') // 记录错误日志并抛出错误
213
+ *
214
+ * // 当 errorStrategy 为 'log' 时
215
+ * this.handleError(new Error('测试错误'), '测试上下文') // 记录错误日志并返回 undefined
216
+ * ```
217
+ */
218
+ protected handleError<T>(error: unknown, context: string): T | undefined;
219
+ /**
220
+ * 将插件实例转换为 Vite 插件对象,用于 Vite 构建系统
221
+ *
222
+ * @public
223
+ * @returns {Plugin} Vite 插件对象,包含插件名称、执行时机和各种钩子函数
224
+ * @description 该方法创建并返回一个符合 Vite 插件规范的对象,设置了插件的基本信息和 configResolved 钩子,然后调用 addPluginHooks 方法添加插件特定的钩子
225
+ * @example
226
+ * ```typescript
227
+ * // 创建插件实例
228
+ * const pluginInstance = new MyPlugin(options)
229
+ *
230
+ * // 转换为 Vite 插件
231
+ * const vitePlugin = pluginInstance.toPlugin()
232
+ *
233
+ * // 导出 Vite 插件
234
+ * export const myPlugin = vitePlugin
235
+ * ```
236
+ */
237
+ toPlugin(): Plugin;
238
+ }
239
+ /**
240
+ * 创建插件工厂函数,用于生成 Vite 插件实例
241
+ *
242
+ * @template T - 插件配置类型,必须继承自 BasePluginOptions
243
+ * @template P - 插件实例类型,必须继承自 BasePlugin<T>
244
+ * @template R - 原始配置类型
245
+ * @param {new (options: T, loggerConfig?: LoggerOptions) => P} PluginClass - 插件类构造函数
246
+ * @param {OptionsNormalizer<T, R>} [normalizer] - 选项标准化器,可选
247
+ * @returns {PluginFactory<T, R>} 插件工厂函数,接收插件配置并返回 Vite 插件实例
248
+ * @description 该函数创建一个插件工厂,用于生成 Vite 插件实例。工厂函数接收插件配置,支持可选的标准化器,创建插件实例,转换为 Vite 插件对象,并在插件对象上添加对原始插件实例的引用
249
+ * @example
250
+ * ```typescript
251
+ * // 基本使用
252
+ * const myPluginFactory = createPluginFactory(MyPlugin)
253
+ *
254
+ * // 带标准化器的使用(支持字符串或对象)
255
+ * const myPluginWithNormalizer = createPluginFactory(MyPlugin, (opt) => typeof opt === 'string' ? { path: opt } : opt)
256
+ * ```
257
+ */
258
+ declare function createPluginFactory<T extends BasePluginOptions, P extends BasePlugin<T>, R = T>(PluginClass: new (options: T, loggerConfig?: LoggerOptions) => P, normalizer?: OptionsNormalizer<T, R>): PluginFactory<T, R>;
259
+
260
+ export { BasePlugin, createPluginFactory };
@@ -0,0 +1 @@
1
+ export{B as BasePlugin,c as createPluginFactory}from"../shared/vite-plugin.ClHiVXD6.mjs";import"../logger/index.mjs";import"fs";import"path";import"../shared/vite-plugin.DSRKYuae.mjs";
package/dist/index.cjs CHANGED
@@ -1,5 +1 @@
1
- "use strict";const s=require("fs"),l=require("path");function _interopDefaultCompat(r){return r&&typeof r=="object"&&"default"in r?r.default:r}const s__default=_interopDefaultCompat(s),l__default=_interopDefaultCompat(l);class Logger{libName="@meng-xi/vite-plugin";name;enabled;logTypes={info:{method:console.log,icon:"",color:"",reset:""},success:{method:console.log,icon:"\u2705",color:"\x1B[32m",reset:"\x1B[0m"},warn:{method:console.warn,icon:"\u26A0\uFE0F",color:"\x1B[33m",reset:"\x1B[0m"},error:{method:console.error,icon:"\u274C",color:"\x1B[31m",reset:"\x1B[0m"}};constructor(u){this.name=u.name,this.enabled=u.enabled??!1}formatPrefix(){let u=`[${this.libName}:${this.name}]`;return u=`[${new Date().toLocaleString()}] ${u}`,u}log(u,e,t){if(!this.enabled)return;const i=this.formatPrefix(),o=this.logTypes[u],{method:n,icon:c,color:h,reset:d}=o,g=c?`${c} ${i}`:i;n("=================================="),t!=null?n(h+g+d,h+e+d,t):n(h+g+d,h+e+d),n("==================================")}success(u,e){this.log("success",u,e)}info(u,e){this.log("info",u,e)}warn(u,e){this.log("warn",u,e)}error(u,e){this.log("error",u,e)}}async function checkSourceExists(r){try{await s__default.promises.access(r,s__default.constants.F_OK)}catch(u){const e=u;throw e.code==="ENOENT"?new Error(`\u590D\u5236\u6587\u4EF6\u5931\u8D25\uFF1A\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728 - ${r}`):e.code==="EACCES"?new Error(`\u590D\u5236\u6587\u4EF6\u5931\u8D25\uFF1A\u6CA1\u6709\u6743\u9650\u8BBF\u95EE\u6E90\u6587\u4EF6 - ${r}`):new Error(`\u590D\u5236\u6587\u4EF6\u5931\u8D25\uFF1A\u68C0\u67E5\u6E90\u6587\u4EF6\u65F6\u51FA\u9519 - ${r}\uFF0C\u9519\u8BEF\uFF1A${e.message}`)}}async function ensureTargetDir(r){try{await s__default.promises.mkdir(r,{recursive:!0})}catch(u){const e=u;throw e.code==="EACCES"?new Error(`\u590D\u5236\u6587\u4EF6\u5931\u8D25\uFF1A\u6CA1\u6709\u6743\u9650\u521B\u5EFA\u76EE\u6807\u76EE\u5F55 - ${r}`):new Error(`\u590D\u5236\u6587\u4EF6\u5931\u8D25\uFF1A\u521B\u5EFA\u76EE\u6807\u76EE\u5F55\u65F6\u51FA\u9519 - ${r}\uFF0C\u9519\u8BEF\uFF1A${e.message}`)}}async function readDirRecursive(r,u){const e=await s__default.promises.readdir(r,{withFileTypes:!0});let t=[];for(const i of e){const o=l__default.join(r,i.name);if(i.isDirectory()){if(t.push(o),u){const n=await readDirRecursive(o,u);t=[...t,...n]}}else t.push(o)}return t}async function shouldUpdateFile(r,u){try{const e=await s__default.promises.stat(r),t=await s__default.promises.stat(u);return e.mtimeMs>t.mtimeMs||e.size!==t.size}catch{return!0}}async function copySourceToTarget(r,u,e){const t=Date.now(),{recursive:i,overwrite:o,incremental:n=!1}=e;let c=0,h=0,d=0;if((await s__default.promises.stat(r)).isDirectory()){await ensureTargetDir(u);const F=await readDirRecursive(r,i),C=(await Promise.all(F.map(async a=>{const E=await s__default.promises.stat(a);return{path:a,isFile:E.isFile()}}))).filter(a=>a.isFile).map(a=>a.path);for(const a of C){const E=l__default.relative(r,a),B=l__default.join(u,E);await ensureTargetDir(l__default.dirname(B));let f=o;if(!f)try{await s__default.promises.access(B,s__default.constants.F_OK),f=!1}catch{f=!0}n&&f&&(f=await shouldUpdateFile(a,B)),f?(await s__default.promises.copyFile(a,B),c++):h++}d=(await Promise.all(F.map(async a=>{const E=await s__default.promises.stat(a);return{path:a,isDirectory:E.isDirectory()}}))).filter(a=>a.isDirectory).length}else{await ensureTargetDir(l__default.dirname(u));let F=o;if(!F)try{await s__default.promises.access(u,s__default.constants.F_OK),F=!1}catch{F=!0}n&&F&&(F=await shouldUpdateFile(r,u)),F?(await s__default.promises.copyFile(r,u),c++):h++}const g=Date.now()-t;return{copiedFiles:c,skippedFiles:h,copiedDirs:d,executionTime:g}}function deepMerge(...r){const u={};for(const e of r)if(e)for(const t in e){const i=e[t],o=u[t];typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?u[t]=deepMerge(o,i):u[t]=i}return u}class Validator{options;currentField=null;errors=[];constructor(u){this.options=u}field(u){return this.currentField=u,this}required(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");return this.options[this.currentField]==null&&this.errors.push(`${this.currentField} \u662F\u5FC5\u586B\u5B57\u6BB5`),this}string(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const u=this.options[this.currentField];return u!=null&&typeof u!="string"&&this.errors.push(`${this.currentField} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u7C7B\u578B`),this}boolean(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const u=this.options[this.currentField];return u!=null&&typeof u!="boolean"&&this.errors.push(`${this.currentField} \u5FC5\u987B\u662F\u5E03\u5C14\u7C7B\u578B`),this}number(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const u=this.options[this.currentField];return u!=null&&typeof u!="number"&&this.errors.push(`${this.currentField} \u5FC5\u987B\u662F\u6570\u5B57\u7C7B\u578B`),this}array(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const u=this.options[this.currentField];return u!=null&&!Array.isArray(u)&&this.errors.push(`${this.currentField} \u5FC5\u987B\u662F\u6570\u7EC4\u7C7B\u578B`),this}object(){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const u=this.options[this.currentField];return u!=null&&typeof u!="object"&&!Array.isArray(u)&&this.errors.push(`${this.currentField} \u5FC5\u987B\u662F\u5BF9\u8C61\u7C7B\u578B`),this}default(u){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");return this.options[this.currentField]==null&&(this.options[this.currentField]=u),this}custom(u,e){if(!this.currentField)throw new Error("\u5FC5\u987B\u5148\u8C03\u7528 field() \u65B9\u6CD5\u6307\u5B9A\u8981\u9A8C\u8BC1\u7684\u5B57\u6BB5");const t=this.options[this.currentField];return t!=null&&!u(t)&&this.errors.push(e),this}validate(){if(this.errors.length>0)throw new Error(`\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25\uFF1A
2
- ${this.errors.map(u=>`- ${u}`).join(`
3
- `)}`);return this.options}}class BasePlugin{options;logger;validator;viteConfig=null;constructor(u,e){this.options=this.mergeOptions(u),this.logger=this.initLogger(e),this.validator=new Validator(this.options),this.validateOptions()}mergeOptions(u){return deepMerge({enabled:!0,verbose:!0,errorStrategy:"throw"},u)}initLogger(u){return u instanceof Logger?u:new Logger({name:this.getPluginName(),enabled:this.options.verbose,...u})}validateOptions(){}getEnforce(){}onConfigResolved(u){this.viteConfig=u,this.logger.info("\u914D\u7F6E\u89E3\u6790\u5B8C\u6210\uFF0C\u63D2\u4EF6\u5DF2\u521D\u59CB\u5316")}async safeExecute(u,e){try{return await u()}catch(t){return this.handleError(t,e)}}handleError(u,e){let t=`${e}: `;switch(u instanceof Error?t+=u.message:typeof u=="string"?t+=u:t+=String(u),this.options.errorStrategy){case"throw":throw this.logger.error(t),u;case"log":case"ignore":this.logger.error(t);return;default:throw this.logger.error(t),u}}toPlugin(){const u={name:this.getPluginName(),enforce:this.getEnforce(),configResolved:e=>{this.options.enabled&&this.onConfigResolved(e)}};return this.addPluginHooks(u),u}}function createPluginFactory(r){return u=>{const e=u,t=new r(e),i=t.toPlugin();return i.pluginInstance=t,i}}let p$1=class extends BasePlugin{validateOptions(){this.validator.field("sourceDir").required().string().custom(u=>u.trim()!=="","sourceDir \u4E0D\u80FD\u4E3A\u7A7A\u5B57\u7B26\u4E32").field("targetDir").required().string().custom(u=>u.trim()!=="","targetDir \u4E0D\u80FD\u4E3A\u7A7A\u5B57\u7B26\u4E32").field("overwrite").boolean().default(!0).field("recursive").boolean().default(!0).field("incremental").boolean().default(!0).validate()}getPluginName(){return"copy-file"}getEnforce(){return"post"}async copyFiles(){const{sourceDir:u,targetDir:e,overwrite:t=!0,recursive:i=!0,incremental:o=!0,enabled:n=!0}=this.options;if(!n){this.logger.info(`\u63D2\u4EF6\u5DF2\u7981\u7528\uFF0C\u8DF3\u8FC7\u6267\u884C\uFF1A\u4ECE ${u} \u590D\u5236\u5230 ${e}`);return}await checkSourceExists(u);const c=await copySourceToTarget(u,e,{recursive:i,overwrite:t,incremental:o});this.logger.success(`\u590D\u5236\u6587\u4EF6\u6210\u529F\uFF1A\u4ECE ${u} \u5230 ${e}`,`\u590D\u5236\u4E86 ${c.copiedFiles} \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u4E86 ${c.skippedFiles} \u4E2A\u6587\u4EF6\uFF0C\u8017\u65F6 ${c.executionTime}ms`)}addPluginHooks(u){u.writeBundle=async()=>{await this.safeExecute(()=>this.copyFiles(),"\u590D\u5236\u6587\u4EF6")}}};const copyFile=createPluginFactory(p$1);function generateIconTags(r){const u=[];if(r.link)return u.push(r.link),u;if(r.icons&&r.icons.length>0)u.push(...r.icons.map(e=>{let t=`<link rel="${e.rel}" href="${e.href}"`;return e.sizes&&(t+=` sizes="${e.sizes}"`),e.type&&(t+=` type="${e.type}"`),t+=" />",t}));else if(r.url)u.push(`<link rel="icon" href="${r.url}" />`);else{const e=r.base||"/",t=e.endsWith("/")?`${e}favicon.ico`:`${e}/favicon.ico`;u.push(`<link rel="icon" href="${t}" />`)}return u}class p extends BasePlugin{constructor(u){const e=typeof u=="string"?{base:u}:u||{};super(e)}validateOptions(){this.validator.field("base").string().default("/").field("url").string().field("link").string().field("icons").array(),this.options?.copyOptions&&(this.validator.field("copyOptions").object(),new Validator(this.options.copyOptions).field("sourceDir").required().string().field("targetDir").required().string().field("overwrite").boolean().default(!0).field("recursive").boolean().default(!0).validate()),this.validator.validate()}getPluginName(){return"inject-ico"}injectIcoTags(u){if(!this.options.enabled)return this.logger.info("\u63D2\u4EF6\u5DF2\u7981\u7528\uFF0C\u8DF3\u8FC7\u56FE\u6807\u6CE8\u5165"),u;const e=generateIconTags(this.options);if(e.length===0)return this.logger.info("\u6CA1\u6709\u751F\u6210\u56FE\u6807\u6807\u7B7E\uFF0C\u8DF3\u8FC7\u6CE8\u5165"),u;let t=u;const i=t.indexOf("</head>");if(i!==-1){const o=e.join(`
4
- `)+`
5
- `;t=t.substring(0,i)+o+t.substring(i),this.logger.success(`\u6210\u529F\u6CE8\u5165 ${e.length} \u4E2A\u56FE\u6807\u6807\u7B7E\u5230 HTML \u6587\u4EF6`),e.forEach(n=>{this.logger.info(` - ${n}`)})}else this.logger.warn("\u672A\u627E\u5230 </head> \u6807\u7B7E\uFF0C\u8DF3\u8FC7\u56FE\u6807\u6CE8\u5165");return t}async copyFiles(){if(!this.options.enabled){this.logger.info("\u63D2\u4EF6\u5DF2\u7981\u7528\uFF0C\u8DF3\u8FC7\u6587\u4EF6\u590D\u5236");return}const{copyOptions:u}=this.options;if(!u)return;const{sourceDir:e,targetDir:t,overwrite:i=!0,recursive:o=!0}=u;await checkSourceExists(e);const n=await copySourceToTarget(e,t,{recursive:o,overwrite:i,incremental:!0});this.logger.success(`\u56FE\u6807\u6587\u4EF6\u590D\u5236\u6210\u529F\uFF1A\u4ECE ${e} \u5230 ${t}`,`\u590D\u5236\u4E86 ${n.copiedFiles} \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u4E86 ${n.skippedFiles} \u4E2A\u6587\u4EF6\uFF0C\u8017\u65F6 ${n.executionTime}ms`)}addPluginHooks(u){u.transformIndexHtml=e=>this.injectIcoTags(e),u.writeBundle=async()=>{await this.safeExecute(()=>this.copyFiles(),"\u56FE\u6807\u6587\u4EF6\u590D\u5236")}}}function injectIco(r){return new p(r).toPlugin()}exports.copyFile=copyFile,exports.injectIco=injectIco;
1
+ "use strict";const index=require("./shared/vite-plugin.DrSzERYS.cjs"),validation=require("./shared/vite-plugin.BTKhc7n7.cjs"),index$1=require("./shared/vite-plugin.BT1oHRKK.cjs"),logger_index=require("./logger/index.cjs"),index$2=require("./shared/vite-plugin.Bn8mcCzy.cjs");require("fs"),require("path"),exports.checkSourceExists=index.checkSourceExists,exports.copySourceToTarget=index.copySourceToTarget,exports.ensureTargetDir=index.ensureTargetDir,exports.readDirRecursive=index.readDirRecursive,exports.readFileSync=index.readFileSync,exports.shouldUpdateFile=index.shouldUpdateFile,exports.writeFileContent=index.writeFileContent,exports.Validator=validation.Validator,exports.deepMerge=validation.deepMerge,exports.BasePlugin=index$1.BasePlugin,exports.createPluginFactory=index$1.createPluginFactory,exports.Logger=logger_index.Logger,exports.copyFile=index$2.copyFile,exports.injectIco=index$2.injectIco;