@meng-xi/vite-plugin 0.0.9 → 0.1.1

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 (105) hide show
  1. package/README-en.md +467 -269
  2. package/README.md +451 -254
  3. package/dist/common/format/index.cjs +1 -0
  4. package/dist/common/format/index.d.cts +156 -0
  5. package/dist/common/format/index.d.mts +156 -0
  6. package/dist/common/format/index.d.ts +156 -0
  7. package/dist/common/format/index.mjs +1 -0
  8. package/dist/common/fs/index.cjs +1 -0
  9. package/dist/common/fs/index.d.cts +150 -0
  10. package/dist/common/fs/index.d.mts +150 -0
  11. package/dist/common/fs/index.d.ts +150 -0
  12. package/dist/common/fs/index.mjs +1 -0
  13. package/dist/common/html/index.cjs +2 -0
  14. package/dist/common/html/index.d.cts +109 -0
  15. package/dist/common/html/index.d.mts +109 -0
  16. package/dist/common/html/index.d.ts +109 -0
  17. package/dist/common/html/index.mjs +2 -0
  18. package/dist/common/index.cjs +1 -1
  19. package/dist/common/index.d.cts +7 -318
  20. package/dist/common/index.d.mts +7 -318
  21. package/dist/common/index.d.ts +7 -318
  22. package/dist/common/index.mjs +1 -1
  23. package/dist/common/object/index.cjs +1 -0
  24. package/dist/common/object/index.d.cts +30 -0
  25. package/dist/common/object/index.d.mts +30 -0
  26. package/dist/common/object/index.d.ts +30 -0
  27. package/dist/common/object/index.mjs +1 -0
  28. package/dist/common/script/index.cjs +1 -0
  29. package/dist/common/script/index.d.cts +54 -0
  30. package/dist/common/script/index.d.mts +54 -0
  31. package/dist/common/script/index.d.ts +54 -0
  32. package/dist/common/script/index.mjs +1 -0
  33. package/dist/common/validation/index.cjs +1 -0
  34. package/dist/common/validation/index.d.cts +93 -0
  35. package/dist/common/validation/index.d.mts +93 -0
  36. package/dist/common/validation/index.d.ts +93 -0
  37. package/dist/common/validation/index.mjs +1 -0
  38. package/dist/factory/index.cjs +1 -1
  39. package/dist/factory/index.d.cts +1 -1
  40. package/dist/factory/index.d.mts +1 -1
  41. package/dist/factory/index.d.ts +1 -1
  42. package/dist/factory/index.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +15 -3
  45. package/dist/index.d.mts +15 -3
  46. package/dist/index.d.ts +15 -3
  47. package/dist/index.mjs +1 -1
  48. package/dist/plugins/buildProgress/index.cjs +2 -0
  49. package/dist/plugins/buildProgress/index.d.cts +187 -0
  50. package/dist/plugins/buildProgress/index.d.mts +187 -0
  51. package/dist/plugins/buildProgress/index.d.ts +187 -0
  52. package/dist/plugins/buildProgress/index.mjs +2 -0
  53. package/dist/plugins/copyFile/index.cjs +1 -0
  54. package/dist/plugins/copyFile/index.d.cts +78 -0
  55. package/dist/plugins/copyFile/index.d.mts +78 -0
  56. package/dist/plugins/copyFile/index.d.ts +78 -0
  57. package/dist/plugins/copyFile/index.mjs +1 -0
  58. package/dist/plugins/faviconManager/index.cjs +1 -0
  59. package/dist/plugins/faviconManager/index.d.cts +143 -0
  60. package/dist/plugins/faviconManager/index.d.mts +143 -0
  61. package/dist/plugins/faviconManager/index.d.ts +143 -0
  62. package/dist/plugins/faviconManager/index.mjs +1 -0
  63. package/dist/plugins/generateRouter/index.cjs +35 -0
  64. package/dist/plugins/generateRouter/index.d.cts +215 -0
  65. package/dist/plugins/generateRouter/index.d.mts +215 -0
  66. package/dist/plugins/generateRouter/index.d.ts +215 -0
  67. package/dist/plugins/generateRouter/index.mjs +35 -0
  68. package/dist/plugins/generateVersion/index.cjs +1 -0
  69. package/dist/plugins/generateVersion/index.d.cts +184 -0
  70. package/dist/plugins/generateVersion/index.d.mts +184 -0
  71. package/dist/plugins/generateVersion/index.d.ts +184 -0
  72. package/dist/plugins/generateVersion/index.mjs +1 -0
  73. package/dist/plugins/htmlInject/index.cjs +7 -0
  74. package/dist/plugins/htmlInject/index.d.cts +278 -0
  75. package/dist/plugins/htmlInject/index.d.mts +278 -0
  76. package/dist/plugins/htmlInject/index.d.ts +278 -0
  77. package/dist/plugins/htmlInject/index.mjs +7 -0
  78. package/dist/plugins/index.cjs +1 -1
  79. package/dist/plugins/index.d.cts +10 -1520
  80. package/dist/plugins/index.d.mts +10 -1520
  81. package/dist/plugins/index.d.ts +10 -1520
  82. package/dist/plugins/index.mjs +1 -1
  83. package/dist/plugins/loadingManager/index.cjs +487 -0
  84. package/dist/plugins/loadingManager/index.d.cts +769 -0
  85. package/dist/plugins/loadingManager/index.d.mts +769 -0
  86. package/dist/plugins/loadingManager/index.d.ts +769 -0
  87. package/dist/plugins/loadingManager/index.mjs +487 -0
  88. package/dist/plugins/versionUpdateChecker/index.cjs +185 -0
  89. package/dist/plugins/versionUpdateChecker/index.d.cts +200 -0
  90. package/dist/plugins/versionUpdateChecker/index.d.mts +200 -0
  91. package/dist/plugins/versionUpdateChecker/index.d.ts +200 -0
  92. package/dist/plugins/versionUpdateChecker/index.mjs +185 -0
  93. package/dist/shared/vite-plugin.Bcg6RW2N.cjs +3 -0
  94. package/dist/shared/{vite-plugin.CiHfwMiN.d.cts → vite-plugin.DRRlWY8P.d.cts} +50 -0
  95. package/dist/shared/{vite-plugin.CiHfwMiN.d.mts → vite-plugin.DRRlWY8P.d.mts} +50 -0
  96. package/dist/shared/{vite-plugin.CiHfwMiN.d.ts → vite-plugin.DRRlWY8P.d.ts} +50 -0
  97. package/dist/shared/{vite-plugin.B88RyRN8.mjs → vite-plugin.DcExl6jd.mjs} +2 -2
  98. package/package.json +72 -2
  99. package/dist/shared/vite-plugin.BI4kA-bR.mjs +0 -526
  100. package/dist/shared/vite-plugin.Ba9646wL.cjs +0 -1
  101. package/dist/shared/vite-plugin.C3ejdBNf.mjs +0 -1
  102. package/dist/shared/vite-plugin.CawoITTT.cjs +0 -1
  103. package/dist/shared/vite-plugin.CsdNNQ-4.cjs +0 -526
  104. package/dist/shared/vite-plugin.DSb6XzBn.mjs +0 -1
  105. package/dist/shared/vite-plugin.IGZeStMa.cjs +0 -3
package/README-en.md CHANGED
@@ -15,7 +15,8 @@
15
15
 
16
16
  ## Features
17
17
 
18
- - **Ready to Use** - Provides 6 practical plugins covering build progress display, file copying, router generation, version management, icon injection, and global Loading state management
18
+ - **Ready to Use** - Provides 8 practical plugins covering build progress display, file copying, router generation, version management, version update checking, HTML injection, icon injection, and global Loading state
19
+ management
19
20
  - **Plugin Development Framework** - Exports core components like BasePlugin, Logger, Validator for building custom Vite plugins
20
21
  - **Complete Lifecycle** - Supports initialization, config resolution, destroy lifecycle management with automatic hook composition
21
22
  - **Type Safe** - Complete TypeScript type definitions with configuration validators ensuring parameter correctness
@@ -46,7 +47,7 @@ pnpm add @meng-xi/vite-plugin -D
46
47
 
47
48
  ```typescript
48
49
  import { defineConfig } from 'vite'
49
- import { buildProgress, copyFile, generateRouter, generateVersion, injectIco, injectLoading } from '@meng-xi/vite-plugin'
50
+ import { buildProgress, copyFile, generateRouter, generateVersion, versionUpdateChecker, htmlInject, faviconManager, loadingManager } from '@meng-xi/vite-plugin'
50
51
 
51
52
  export default defineConfig({
52
53
  plugins: [
@@ -71,11 +72,25 @@ export default defineConfig({
71
72
  outputType: 'both'
72
73
  }),
73
74
 
75
+ // Version update checker (works with generateVersion)
76
+ versionUpdateChecker(),
77
+
78
+ // HTML content injection
79
+ htmlInject({
80
+ rules: [
81
+ {
82
+ id: 'meta-description',
83
+ content: '<meta name="description" content="My App">',
84
+ position: 'head-end'
85
+ }
86
+ ]
87
+ }),
88
+
74
89
  // Inject website icon (supports string shorthand)
75
- injectIco('/assets'),
90
+ faviconManager('/assets'),
76
91
 
77
- // Inject global Loading
78
- injectLoading({
92
+ // Global Loading state management
93
+ loadingManager({
79
94
  defaultVisible: true,
80
95
  autoHideOn: 'DOMContentLoaded'
81
96
  })
@@ -97,238 +112,18 @@ const routerPlugin = generateRouter({ watch: true }) as PluginWithInstance<Gener
97
112
  console.log(routerPlugin.pluginInstance?.options)
98
113
  ```
99
114
 
100
- ### Developing Custom Plugins
101
-
102
- ```typescript
103
- import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
104
- import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
105
- import type { Plugin } from 'vite'
106
-
107
- interface MyPluginOptions extends BasePluginOptions {
108
- path: string
109
- }
110
-
111
- class MyPlugin extends BasePlugin<MyPluginOptions> {
112
- protected getDefaultOptions() {
113
- return { path: './default' }
114
- }
115
-
116
- protected validateOptions(): void {
117
- this.validator.field('path').required().string().validate()
118
- }
119
-
120
- protected getPluginName(): string {
121
- return 'my-plugin'
122
- }
123
-
124
- protected addPluginHooks(plugin: Plugin): void {
125
- plugin.buildStart = () => {
126
- this.logger.info(`Plugin started with path: ${this.options.path}`)
127
- }
128
- }
129
-
130
- protected destroy(): void {
131
- super.destroy()
132
- // Custom cleanup logic, e.g. close connections, stop watchers
133
- }
134
- }
135
-
136
- // Basic usage
137
- export const myPlugin = createPluginFactory(MyPlugin)
138
-
139
- // With normalizer (supports shorthand string config)
140
- export const myPluginWithNormalizer = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
141
- // Usage with shorthand: myPluginWithNormalizer('./custom-path')
142
- ```
143
-
144
- ## Plugin Development Framework
145
-
146
- ### BasePlugin Core Concepts
147
-
148
- `BasePlugin` is the base class for all plugins, providing complete lifecycle management and development conventions:
149
-
150
- #### Lifecycle
151
-
152
- | Phase | Method | Description |
153
- | ----------------- | ------------------ | -------------------------------------------------------------- |
154
- | Initialization | `constructor` | Merge options, initialize logger and validator |
155
- | Config Resolution | `onConfigResolved` | Called when Vite config is resolved |
156
- | Hook Registration | `addPluginHooks` | Register Vite plugin hooks |
157
- | Destroy | `destroy` | Automatically called during `closeBundle` for resource cleanup |
158
-
159
- #### Automatic Hook Composition
160
-
161
- The `toPlugin()` method automatically composes the following hooks:
162
-
163
- - **configResolved** - Base class `onConfigResolved` runs first, then subclass hook
164
- - **closeBundle** - Subclass hook runs first, then base class `destroy`
165
-
166
- > Subclasses don't need to manually register `closeBundle` hooks for cleanup — just override the `destroy()` method.
167
-
168
- #### Required Methods
169
-
170
- | Method | Description |
171
- | ------------------------ | --------------------- |
172
- | `getPluginName()` | Return plugin name |
173
- | `addPluginHooks(plugin)` | Add Vite plugin hooks |
174
-
175
- #### Optional Methods
176
-
177
- | Method | Default Behavior | Description |
178
- | -------------------------- | ----------------- | ------------------------------------------- |
179
- | `getDefaultOptions()` | Returns `{}` | Provide plugin default options |
180
- | `validateOptions()` | No validation | Validate configuration parameters |
181
- | `getEnforce()` | `undefined` | Plugin execution order (`'pre'` / `'post'`) |
182
- | `onConfigResolved(config)` | Store config | Config resolved callback |
183
- | `destroy()` | Unregister logger | Cleanup logic when plugin is destroyed |
184
-
185
- #### Built-in Properties
186
-
187
- | Property | Type | Description |
188
- | ------------ | ------------------------ | ----------------------------- |
189
- | `options` | `Required<T>` | Merged complete configuration |
190
- | `logger` | `PluginLogger` | Plugin logger |
191
- | `validator` | `Validator<T>` | Configuration validator |
192
- | `viteConfig` | `ResolvedConfig \| null` | Resolved Vite configuration |
193
-
194
- #### Error Handling Strategy
195
-
196
- Control error behavior via the `errorStrategy` configuration option:
197
-
198
- - `'throw'` (default) - Log error and throw exception, halting the build
199
- - `'log'` - Log error but don't throw, continue execution
200
- - `'ignore'` - Log error but don't throw, continue execution
201
-
202
- Wrap error-prone operations with `safeExecute` / `safeExecuteSync`:
203
-
204
- ```typescript
205
- // Async safe execution
206
- const result = await this.safeExecute(async () => {
207
- return await someAsyncOperation()
208
- }, 'Execute async operation')
209
-
210
- // Sync safe execution
211
- const value = this.safeExecuteSync(() => {
212
- return someSyncOperation()
213
- }, 'Execute sync operation')
214
- ```
215
-
216
- ### createPluginFactory
217
-
218
- Create plugin factory functions with optional normalizer support:
219
-
220
- ```typescript
221
- // Basic usage
222
- const myPlugin = createPluginFactory(MyPlugin)
223
-
224
- // With normalizer (supports shorthand string config)
225
- const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
226
-
227
- // Usage with shorthand
228
- myPlugin('./custom-path')
229
- ```
230
-
231
- ### Validator
232
-
233
- Fluent configuration validator with chainable API:
234
-
235
- ```typescript
236
- import { Validator } from '@meng-xi/vite-plugin/common'
237
-
238
- const validator = new Validator(options)
239
- validator
240
- .field('sourceDir')
241
- .required()
242
- .string()
243
- .field('targetDir')
244
- .required()
245
- .string()
246
- .field('overwrite')
247
- .boolean()
248
- .default(true)
249
- .field('port')
250
- .number()
251
- .field('list')
252
- .array()
253
- .field('config')
254
- .object()
255
- .field('name')
256
- .custom(val => val.length > 0, 'name cannot be empty')
257
- .validate()
258
- ```
259
-
260
- | Method | Description |
261
- | ------------ | --------------------------------------------------------------- |
262
- | `field()` | Specify the field to validate |
263
- | `required()` | Mark field as required |
264
- | `string()` | Validate field value is a string type |
265
- | `boolean()` | Validate field value is a boolean type |
266
- | `number()` | Validate field value is a number type |
267
- | `array()` | Validate field value is an array type |
268
- | `object()` | Validate field value is an object type |
269
- | `default()` | Set default value for field (only when value is undefined/null) |
270
- | `custom()` | Validate field value with a custom function |
271
- | `validate()` | Execute validation, throws error on failure |
272
-
273
- ### Logger
274
-
275
- Global singleton log manager providing independent log control for each plugin:
276
-
277
- ```typescript
278
- import { Logger } from '@meng-xi/vite-plugin/logger'
279
-
280
- // Create logger (usually called automatically by BasePlugin)
281
- Logger.create({ name: 'my-plugin', enabled: true })
282
-
283
- // Unregister plugin log config (automatically called on plugin destroy)
284
- Logger.unregister('my-plugin')
285
-
286
- // Destroy singleton (for test scenarios)
287
- Logger.destroy()
288
- ```
289
-
290
- Log output format:
291
-
292
- ```
293
- ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
294
- ✅ [@meng-xi/vite-plugin:my-plugin] Success message
295
- ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
296
- ❌ [@meng-xi/vite-plugin:my-plugin] Error message
297
- ```
298
-
299
- ### Common Utilities
300
-
301
- Exported via `@meng-xi/vite-plugin/common`, reusable in custom plugins:
302
-
303
- ```typescript
304
- import { deepMerge, formatDate, parseTemplate, toCamelCase, toPascalCase, stripJsonComments, generateRandomHash, Validator } from '@meng-xi/vite-plugin/common'
305
- import { readFileContent, writeFileContent, fileExists, copySourceToTarget } from '@meng-xi/vite-plugin/common'
306
- ```
307
-
308
- | Function | Description |
309
- | ---------------------- | --------------------------------------------------------------- |
310
- | `deepMerge()` | Deep merge objects (undefined skipped, arrays overwritten) |
311
- | `formatDate()` | Format date with `{YYYY}`, `{MM}`, `{DD}` etc. placeholders |
312
- | `parseTemplate()` | Parse template string, replace placeholders |
313
- | `toCamelCase()` | Convert to camelCase |
314
- | `toPascalCase()` | Convert to PascalCase |
315
- | `stripJsonComments()` | Remove comments from JSON string |
316
- | `generateRandomHash()` | Generate random hash string (1-64 characters) |
317
- | `readFileContent()` | Async read file content |
318
- | `writeFileContent()` | Async write file content |
319
- | `fileExists()` | Async check if file exists |
320
- | `copySourceToTarget()` | Copy files or directories with incremental copy and concurrency |
321
-
322
115
  ## Built-in Plugins
323
116
 
324
- | Plugin | Description |
325
- | --------------- | ----------------------------------------------------------------------------------------- |
326
- | buildProgress | Real-time build progress bar in terminal, supports bar / spinner / minimal |
327
- | copyFile | Copy files or directories after build, supports incremental copying |
328
- | generateRouter | Auto-generate router config from pages.json (uni-app) |
329
- | generateVersion | Auto-generate version numbers, supports file output and global variable injection |
330
- | injectIco | Inject website icon links into HTML files, supports string shorthand config |
331
- | injectLoading | Inject global Loading state management with request interception and white-screen Loading |
117
+ | Plugin | Description |
118
+ | -------------------- | ----------------------------------------------------------------------------------------------------------------- |
119
+ | buildProgress | Real-time build progress bar in terminal, supports bar / spinner / minimal |
120
+ | copyFile | Copy files or directories after build, supports incremental copying |
121
+ | generateRouter | Auto-generate router config from pages.json (uni-app) |
122
+ | generateVersion | Auto-generate version numbers, supports file output and global variable injection |
123
+ | versionUpdateChecker | Runtime version update checking with multiple prompt styles and custom callbacks |
124
+ | htmlInject | HTML content injection with multiple positions, conditional injection, template variables, and security filtering |
125
+ | faviconManager | Manage website favicon links injection into HTML files, supports string shorthand config |
126
+ | loadingManager | Global Loading state management with request interception and white-screen Loading |
332
127
 
333
128
  ### buildProgress
334
129
 
@@ -470,18 +265,18 @@ generateRouter({
470
265
 
471
266
  Automatically generate version numbers during the Vite build process.
472
267
 
473
- | Option | Type | Default | Description |
474
- | ------------ | --------------------------------------------------------------------------------- | ------------------- | ------------------------------ |
475
- | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | Version format |
476
- | customFormat | `string` | - | Custom format template |
477
- | semverBase | `string` | `'1.0.0'` | Semantic version base |
478
- | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | Output type |
479
- | outputFile | `string` | `'version.json'` | Output file path |
480
- | defineName | `string` | `'__APP_VERSION__'` | Global variable name to inject |
481
- | hashLength | `number` | `8` | Hash length (1-32) |
482
- | prefix | `string` | - | Version number prefix |
483
- | suffix | `string` | - | Version number suffix |
484
- | extra | `Record<string, unknown>` | - | Extra info (JSON file only) |
268
+ | Option | Type | Default | Description |
269
+ | ------------ | --------------------------------------------------------------------------------- | ------------------- | -------------------------------- |
270
+ | format | `'timestamp'` \| `'date'` \| `'datetime'` \| `'semver'` \| `'hash'` \| `'custom'` | `'timestamp'` | Version number format |
271
+ | customFormat | `string` | - | Custom format template |
272
+ | semverBase | `string` | `'1.0.0'` | Semantic version base value |
273
+ | outputType | `'file'` \| `'define'` \| `'both'` | `'file'` | Output type |
274
+ | outputFile | `string` | `'version.json'` | Output file path |
275
+ | defineName | `string` | `'__APP_VERSION__'` | Injected global variable name |
276
+ | hashLength | `number` | `8` | Hash length (1-32) |
277
+ | prefix | `string` | - | Version number prefix |
278
+ | suffix | `string` | - | Version number suffix |
279
+ | extra | `Record<string, unknown>` | - | Additional info (JSON file only) |
485
280
 
486
281
  **customFormat placeholders:**
487
282
 
@@ -533,7 +328,166 @@ generateVersion({
533
328
  })
534
329
  ```
535
330
 
536
- ### injectIco
331
+ ### versionUpdateChecker
332
+
333
+ Periodically check for version changes at runtime and prompt users to refresh when a new version is detected. Typically used in conjunction with the `generateVersion` plugin.
334
+
335
+ **How it works:**
336
+
337
+ 1. `generateVersion` generates a version file (`version.json`) or injects a global variable at build time
338
+ 2. `versionUpdateChecker` periodically requests the version file at runtime and compares it with the current version
339
+ 3. When a version mismatch is detected, a prompt is shown to guide the user to refresh
340
+
341
+ | Option | Type | Default | Description |
342
+ | ----------------------- | ------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------ |
343
+ | versionSource | `'define'` \| `'file'` \| `'auto'` | `'auto'` | Current version source |
344
+ | defineName | `string` | `'__APP_VERSION__'` | Global variable name in define mode |
345
+ | checkUrl | `string` | `'/version.json'` | URL path for version check file |
346
+ | checkInterval | `number` | `300000` | Check interval in milliseconds (default 5 minutes) |
347
+ | checkOnVisibilityChange | `boolean` | `true` | Whether to check immediately on page visibility change |
348
+ | enableInDev | `boolean` | `false` | Whether to enable in development mode |
349
+ | promptStyle | `'modal'` \| `'banner'` \| `'toast'` | `'modal'` | Update prompt UI style |
350
+ | promptMessage | `string` | `'A new version is available. Refresh now to get the latest?'` | Prompt message text |
351
+ | refreshButtonText | `string` | `'Refresh'` | Refresh button text |
352
+ | dismissButtonText | `string` | `'Later'` | Dismiss button text |
353
+ | customPromptTemplate | `string` | - | Custom HTML template for the prompt UI |
354
+ | customStyle | `string` | - | Custom CSS style string |
355
+ | onUpdateAvailable | `string` | - | Callback when new version is found (function body string) |
356
+ | onRefresh | `string` | - | Callback when user chooses to refresh (function body string) |
357
+ | onDismiss | `string` | - | Callback when user chooses to dismiss (function body string) |
358
+
359
+ > `versionSource` explanation: `'define'` reads from global variable, `'file'` reads from version file, `'auto'` prefers define and falls back to file. Custom templates can use `{{message}}`, `{{currentVersion}}`,
360
+ > `{{newVersion}}`, `{{refreshButton}}`, `{{dismissButton}}` placeholders. Callbacks are provided as function body strings with available variables: `currentVersion`, `newVersion`.
361
+
362
+ ```typescript
363
+ // Basic usage (with generateVersion)
364
+ generateVersion({ outputType: 'both' })
365
+ versionUpdateChecker()
366
+
367
+ // Read from version file only
368
+ versionUpdateChecker({ versionSource: 'file' })
369
+
370
+ // Custom check interval and prompt style
371
+ versionUpdateChecker({
372
+ checkInterval: 60000,
373
+ promptStyle: 'banner'
374
+ })
375
+
376
+ // Toast-style prompt
377
+ versionUpdateChecker({ promptStyle: 'toast' })
378
+
379
+ // Custom prompt text
380
+ versionUpdateChecker({
381
+ promptMessage: 'System updated, refresh to experience new features',
382
+ refreshButtonText: 'Update',
383
+ dismissButtonText: 'Cancel'
384
+ })
385
+
386
+ // Custom callbacks
387
+ versionUpdateChecker({
388
+ onUpdateAvailable: 'console.log("New version:", newVersion); return true;',
389
+ onRefresh: 'console.log("User chose to refresh");',
390
+ onDismiss: 'console.log("User chose to dismiss");'
391
+ })
392
+
393
+ // Enable in development (for debugging)
394
+ versionUpdateChecker({ enableInDev: true })
395
+ ```
396
+
397
+ ### htmlInject
398
+
399
+ Inject HTML content into target files during Vite build based on configured rules, supporting multiple injection positions, conditional injection, template variable replacement, and security filtering.
400
+
401
+ **Injection positions:**
402
+
403
+ | Position | Description |
404
+ | ------------------ | ------------------------------------------ |
405
+ | `head-start` | Inject after the `<head>` tag |
406
+ | `head-end` | Inject before the `</head>` tag |
407
+ | `body-start` | Inject after the `<body>` tag |
408
+ | `body-end` | Inject before the `</body>` tag |
409
+ | `before-selector` | Inject before the selector-matched content |
410
+ | `after-selector` | Inject after the selector-matched content |
411
+ | `replace-selector` | Replace the selector-matched content |
412
+
413
+ | Option | Type | Default | Description |
414
+ | ------------ | ------------------------ | -------------- | --------------------------------- |
415
+ | targetFile | `string` | `'index.html'` | Target HTML file path or filename |
416
+ | rules | `InjectRule[]` | - | Injection rules array (required) |
417
+ | security | `SecurityConfig` | - | Security filtering configuration |
418
+ | templateVars | `Record<string, string>` | - | Global template variables |
419
+ | logInjection | `boolean` | `true` | Whether to output injection logs |
420
+
421
+ **InjectRule**
422
+
423
+ | Property | Type | Default | Description |
424
+ | -------------------- | ------------------------ | ---------- | -------------------------------------------------------- |
425
+ | id | `string` | - | Unique rule identifier for logging and debugging |
426
+ | content | `string` | - | HTML content to inject (required) |
427
+ | position | `InjectPosition` | - | Injection position (required) |
428
+ | selector | `string` | - | Selector string (required for selector positions) |
429
+ | selectorMatch | `'string'` \| `'regex'` | `'string'` | Selector match mode |
430
+ | priority | `number` | `100` | Priority, lower values execute first |
431
+ | condition | `InjectCondition` | - | Injection condition |
432
+ | templateVars | `Record<string, string>` | - | Rule-level template variables (override global) |
433
+ | allowScriptInjection | `boolean` | `false` | Whether to allow injecting scripts and dangerous content |
434
+
435
+ **InjectCondition**
436
+
437
+ | Property | Type | Default | Description |
438
+ | -------- | ------------------------------------------- | ------- | -------------------------------------- |
439
+ | type | `'env'` \| `'file-contains'` \| `'custom'` | - | Condition type (required) |
440
+ | value | `string` \| `((...args: any[]) => boolean)` | - | Condition value (required) |
441
+ | negate | `boolean` | `false` | Whether to negate the condition result |
442
+
443
+ **SecurityConfig**
444
+
445
+ | Property | Type | Default | Description |
446
+ | ------------------------ | ---------- | ------- | ------------------------------------- |
447
+ | blockDangerousTags | `boolean` | `true` | Whether to block dangerous tags |
448
+ | blockDangerousAttributes | `boolean` | `true` | Whether to block dangerous attributes |
449
+ | allowedTags | `string[]` | - | Whitelist of allowed tags |
450
+ | blockedTags | `string[]` | - | Custom blocked tags list |
451
+ | blockedAttributes | `string[]` | - | Custom blocked attributes list |
452
+
453
+ ```typescript
454
+ // Basic usage
455
+ htmlInject({
456
+ rules: [{ id: 'meta-desc', content: '<meta name="description" content="My App">', position: 'head-end' }]
457
+ })
458
+
459
+ // Conditional injection (production only)
460
+ htmlInject({
461
+ rules: [
462
+ {
463
+ id: 'analytics',
464
+ content: '<script src="/analytics.js"></script>',
465
+ position: 'body-end',
466
+ condition: { type: 'env', value: 'PRODUCTION' },
467
+ allowScriptInjection: true
468
+ }
469
+ ]
470
+ })
471
+
472
+ // Template variable replacement
473
+ htmlInject({
474
+ templateVars: { appName: 'My App', version: '1.0.0' },
475
+ rules: [{ id: 'meta', content: '<meta name="description" content="{{appName}}">', position: 'head-end' }]
476
+ })
477
+
478
+ // Selector injection
479
+ htmlInject({
480
+ rules: [{ id: 'replace-title', content: '<title>New Title</title>', position: 'replace-selector', selector: '<title>.*</title>', selectorMatch: 'regex' }]
481
+ })
482
+
483
+ // Security configuration
484
+ htmlInject({
485
+ security: { blockDangerousTags: true, allowedTags: ['iframe'] },
486
+ rules: [{ id: 'embed', content: '<iframe src="https://example.com"></iframe>', position: 'body-end' }]
487
+ })
488
+ ```
489
+
490
+ ### faviconManager
537
491
 
538
492
  Inject website icon links into the head of HTML files during the Vite build process. Supports string shorthand config.
539
493
 
@@ -567,13 +521,13 @@ Inject website icon links into the head of HTML files during the Vite build proc
567
521
 
568
522
  ```typescript
569
523
  // Use default config
570
- injectIco()
524
+ faviconManager()
571
525
 
572
526
  // String shorthand (set base path)
573
- injectIco('/assets')
527
+ faviconManager('/assets')
574
528
 
575
529
  // Custom icon array
576
- injectIco({
530
+ faviconManager({
577
531
  base: '/assets',
578
532
  icons: [
579
533
  { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' },
@@ -583,12 +537,12 @@ injectIco({
583
537
  })
584
538
 
585
539
  // Custom complete link tag
586
- injectIco({
540
+ faviconManager({
587
541
  link: '<link rel="icon" href="/favicon.svg" type="image/svg+xml" />'
588
542
  })
589
543
 
590
544
  // With file copying
591
- injectIco({
545
+ faviconManager({
592
546
  base: '/assets',
593
547
  copyOptions: {
594
548
  sourceDir: 'src/assets/icons',
@@ -597,7 +551,7 @@ injectIco({
597
551
  })
598
552
  ```
599
553
 
600
- ### injectLoading
554
+ ### loadingManager
601
555
 
602
556
  Inject global Loading state management with XHR/Fetch request interception, white-screen Loading, custom styles, and lifecycle callbacks.
603
557
 
@@ -711,30 +665,30 @@ Access via `window.__LOADING_MANAGER__`:
711
665
 
712
666
  ```typescript
713
667
  // White-screen Loading: visible on page load, auto-hide on DOMContentLoaded
714
- injectLoading({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
668
+ loadingManager({ defaultVisible: true, autoHideOn: 'DOMContentLoaded' })
715
669
 
716
670
  // White-screen Loading: auto-hide after all resources loaded
717
- injectLoading({ defaultVisible: true, autoHideOn: 'load' })
671
+ loadingManager({ defaultVisible: true, autoHideOn: 'load' })
718
672
 
719
673
  // Vue/React SPA: visible on white screen, manually hide after framework renders
720
- injectLoading({ defaultVisible: true, autoHideOn: 'manual' })
674
+ loadingManager({ defaultVisible: true, autoHideOn: 'manual' })
721
675
  // In app entry: window.__LOADING_MANAGER__.hide()
722
676
 
723
677
  // Auto-intercept all requests
724
- injectLoading({ autoBind: 'all' })
678
+ loadingManager({ autoBind: 'all' })
725
679
 
726
680
  // Custom styles + request filtering
727
- injectLoading({
681
+ loadingManager({
728
682
  style: { overlayColor: 'rgba(0,0,0,0.5)', spinnerColor: '#fff', backdropBlur: true },
729
683
  autoBind: 'fetch',
730
684
  requestFilter: { excludeUrls: [/\/api\/health/], excludeUrlPrefixes: ['http://localhost'] }
731
685
  })
732
686
 
733
687
  // Debounced hide (prevent rapid flashing)
734
- injectLoading({ debounceHide: { enabled: true, duration: 100 } })
688
+ loadingManager({ debounceHide: { enabled: true, duration: 100 } })
735
689
 
736
690
  // Lifecycle callbacks
737
- injectLoading({
691
+ loadingManager({
738
692
  callbacks: {
739
693
  onBeforeShow: 'if (shouldSkip) return false;',
740
694
  onShow: 'console.log("loading shown")',
@@ -744,45 +698,289 @@ injectLoading({
744
698
  })
745
699
 
746
700
  // Manual control
747
- injectLoading()
701
+ loadingManager()
748
702
  window.__LOADING_MANAGER__.show('Saving...')
749
703
  window.__LOADING_MANAGER__.hide()
750
704
  window.__LOADING_MANAGER__.toggle()
751
705
  window.__LOADING_MANAGER__.disablePointerEvents()
752
706
  ```
753
707
 
708
+ ## Common Utilities
709
+
710
+ Exported via `@meng-xi/vite-plugin/common`, reusable in custom plugins:
711
+
712
+ ```typescript
713
+ import { deepMerge, formatDate, parseTemplate, toCamelCase, toPascalCase, stripJsonComments, generateRandomHash, escapeHtmlAttr, Validator } from '@meng-xi/vite-plugin/common'
714
+ import { readFileContent, writeFileContent, fileExists, copySourceToTarget } from '@meng-xi/vite-plugin/common/fs'
715
+ import { injectBeforeTag, injectHtmlByPriority, injectBeforeTagWithFallback, injectHeadAndBody } from '@meng-xi/vite-plugin/common/html'
716
+ import { makeCallback, containsScriptTag, validateIdentifierName } from '@meng-xi/vite-plugin/common/script'
717
+ import { validateGlobalName, validateNoScriptInTemplate, validateCallbackFields, validateNonNegativeNumber, validateNestedDuration, validateEnumValue } from '@meng-xi/vite-plugin/common/validation'
718
+ ```
719
+
720
+ | Function | Description | Sub-path |
721
+ | ------------------------------- | ----------------------------------------------------------------------------- | ------------------- |
722
+ | `deepMerge()` | Deep merge objects (undefined skipped, arrays overwritten) | `common/object` |
723
+ | `formatDate()` | Format date with `{YYYY}`, `{MM}`, `{DD}` etc. placeholders | `common/format` |
724
+ | `parseTemplate()` | Parse template string, replace placeholders | `common/format` |
725
+ | `toCamelCase()` | Convert to camelCase | `common/format` |
726
+ | `toPascalCase()` | Convert to PascalCase | `common/format` |
727
+ | `stripJsonComments()` | Remove comments from JSON string | `common/format` |
728
+ | `generateRandomHash()` | Generate random hash string (1-64 characters) | `common/format` |
729
+ | `escapeHtmlAttr()` | Escape special characters in HTML attribute values, prevent XSS injection | `common/format` |
730
+ | `readFileContent()` | Async read file content | `common/fs` |
731
+ | `writeFileContent()` | Async write file content | `common/fs` |
732
+ | `fileExists()` | Async check if file exists | `common/fs` |
733
+ | `copySourceToTarget()` | Copy files or directories with incremental copy and concurrency | `common/fs` |
734
+ | `injectBeforeTag()` | Inject code before a specified closing HTML tag | `common/html` |
735
+ | `injectHtmlByPriority()` | Inject code into HTML by priority (`</head>` → `</body>` → `</html>`) | `common/html` |
736
+ | `injectBeforeTagWithFallback()` | Inject with fallback strategy (`</body>` → `</html>` → append) | `common/html` |
737
+ | `injectHeadAndBody()` | Dual-zone HTML injection (head + body) | `common/html` |
738
+ | `makeCallback()` | Wrap callback function body as safe function expression (with try-catch) | `common/script` |
739
+ | `containsScriptTag()` | Detect if a string contains `<script>` tags | `common/script` |
740
+ | `validateIdentifierName()` | Validate string as a legal JavaScript identifier, prevent prototype pollution | `common/script` |
741
+ | `validateGlobalName()` | Validate global variable name legality | `common/validation` |
742
+ | `validateNoScriptInTemplate()` | Validate template string does not contain script tags (XSS protection) | `common/validation` |
743
+ | `validateCallbackFields()` | Validate callback fields do not contain script tags | `common/validation` |
744
+ | `validateNonNegativeNumber()` | Validate number is non-negative | `common/validation` |
745
+ | `validateNestedDuration()` | Validate nested config duration legality | `common/validation` |
746
+ | `validateEnumValue()` | Validate string value is in allowed enum list | `common/validation` |
747
+
748
+ ## Plugin Development Framework
749
+
750
+ ### BasePlugin Core Concepts
751
+
752
+ `BasePlugin` is the base class for all plugins, providing complete lifecycle management and development conventions:
753
+
754
+ #### Lifecycle
755
+
756
+ | Phase | Method | Description |
757
+ | ----------------- | ------------------ | -------------------------------------------------------------- |
758
+ | Initialization | `constructor` | Merge options, initialize logger and validator |
759
+ | Config Resolution | `onConfigResolved` | Called when Vite config is resolved |
760
+ | Hook Registration | `addPluginHooks` | Register Vite plugin hooks |
761
+ | Destroy | `destroy` | Automatically called during `closeBundle` for resource cleanup |
762
+
763
+ #### Automatic Hook Composition
764
+
765
+ The `toPlugin()` method automatically composes the following hooks:
766
+
767
+ - **configResolved** - Base class `onConfigResolved` runs first, then subclass hook
768
+ - **closeBundle** - Subclass hook runs first, then base class `destroy`
769
+
770
+ > Subclasses don't need to manually register `closeBundle` hooks for cleanup — just override the `destroy()` method.
771
+
772
+ #### Required Methods
773
+
774
+ | Method | Description |
775
+ | ------------------------ | --------------------- |
776
+ | `getPluginName()` | Return plugin name |
777
+ | `addPluginHooks(plugin)` | Add Vite plugin hooks |
778
+
779
+ #### Optional Methods
780
+
781
+ | Method | Default Behavior | Description |
782
+ | -------------------------- | ----------------- | ------------------------------------------- |
783
+ | `getDefaultOptions()` | Returns `{}` | Provide plugin default options |
784
+ | `validateOptions()` | No validation | Validate configuration parameters |
785
+ | `getEnforce()` | `undefined` | Plugin execution order (`'pre'` / `'post'`) |
786
+ | `onConfigResolved(config)` | Store config | Config resolved callback |
787
+ | `destroy()` | Unregister logger | Cleanup logic when plugin is destroyed |
788
+
789
+ #### Built-in Properties
790
+
791
+ | Property | Type | Description |
792
+ | ------------ | ------------------------ | ----------------------------- |
793
+ | `options` | `Required<T>` | Merged complete configuration |
794
+ | `logger` | `PluginLogger` | Plugin logger |
795
+ | `validator` | `Validator<T>` | Configuration validator |
796
+ | `viteConfig` | `ResolvedConfig \| null` | Resolved Vite configuration |
797
+
798
+ #### Error Handling Strategy
799
+
800
+ Control error behavior via the `errorStrategy` configuration option:
801
+
802
+ - `'throw'` (default) - Log error and throw exception, halting the build
803
+ - `'log'` - Log error but don't throw, continue execution
804
+ - `'ignore'` - Log error but don't throw, continue execution
805
+
806
+ Wrap error-prone operations with `safeExecute` / `safeExecuteSync`:
807
+
808
+ ```typescript
809
+ // Async safe execution
810
+ const result = await this.safeExecute(async () => {
811
+ return await someAsyncOperation()
812
+ }, 'Execute async operation')
813
+
814
+ // Sync safe execution
815
+ const value = this.safeExecuteSync(() => {
816
+ return someSyncOperation()
817
+ }, 'Execute sync operation')
818
+ ```
819
+
820
+ ### createPluginFactory
821
+
822
+ Create plugin factory functions with optional normalizer support:
823
+
824
+ ```typescript
825
+ // Basic usage
826
+ const myPlugin = createPluginFactory(MyPlugin)
827
+
828
+ // With normalizer (supports shorthand string config)
829
+ const myPlugin = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
830
+
831
+ // Usage with shorthand
832
+ myPlugin('./custom-path')
833
+ ```
834
+
835
+ ### Validator
836
+
837
+ Fluent configuration validator with chainable API:
838
+
839
+ ```typescript
840
+ import { Validator } from '@meng-xi/vite-plugin/common'
841
+
842
+ const validator = new Validator(options)
843
+ validator
844
+ .field('sourceDir')
845
+ .required()
846
+ .string()
847
+ .field('targetDir')
848
+ .required()
849
+ .string()
850
+ .field('overwrite')
851
+ .boolean()
852
+ .default(true)
853
+ .field('port')
854
+ .number()
855
+ .field('list')
856
+ .array()
857
+ .field('config')
858
+ .object()
859
+ .field('name')
860
+ .custom(val => val.length > 0, 'name cannot be empty')
861
+ .validate()
862
+ ```
863
+
864
+ | Method | Description |
865
+ | ------------ | ----------------------------------------------------------------- |
866
+ | `field()` | Specify the field to validate |
867
+ | `required()` | Mark field as required |
868
+ | `string()` | Validate field value is a string type |
869
+ | `boolean()` | Validate field value is a boolean type |
870
+ | `number()` | Validate field value is a number type |
871
+ | `array()` | Validate field value is an array type |
872
+ | `object()` | Validate field value is an object type |
873
+ | `enum()` | Validate field value is in allowed enum list |
874
+ | `minValue()` | Validate number field value is not less than specified minimum |
875
+ | `maxValue()` | Validate number field value is not greater than specified maximum |
876
+ | `default()` | Set default value for field (only when value is undefined/null) |
877
+ | `custom()` | Validate field value with a custom function |
878
+ | `validate()` | Execute validation, throws error on failure |
879
+
880
+ ### Logger
881
+
882
+ Global singleton log manager providing independent log control for each plugin:
883
+
884
+ ```typescript
885
+ import { Logger } from '@meng-xi/vite-plugin/logger'
886
+
887
+ // Create logger (usually called automatically by BasePlugin)
888
+ Logger.create({ name: 'my-plugin', enabled: true })
889
+
890
+ // Unregister plugin log config (automatically called on plugin destroy)
891
+ Logger.unregister('my-plugin')
892
+
893
+ // Destroy singleton (for test scenarios)
894
+ Logger.destroy()
895
+ ```
896
+
897
+ Log output format:
898
+
899
+ ```
900
+ ℹ️ [@meng-xi/vite-plugin:my-plugin] Info message
901
+ ✅ [@meng-xi/vite-plugin:my-plugin] Success message
902
+ ⚠️ [@meng-xi/vite-plugin:my-plugin] Warning message
903
+ ❌ [@meng-xi/vite-plugin:my-plugin] Error message
904
+ ```
905
+
906
+ ### Custom Plugin Example
907
+
908
+ ```typescript
909
+ import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin'
910
+ import type { BasePluginOptions, PluginWithInstance } from '@meng-xi/vite-plugin/factory'
911
+ import type { Plugin } from 'vite'
912
+
913
+ interface MyPluginOptions extends BasePluginOptions {
914
+ path: string
915
+ }
916
+
917
+ class MyPlugin extends BasePlugin<MyPluginOptions> {
918
+ protected getDefaultOptions() {
919
+ return { path: './default' }
920
+ }
921
+
922
+ protected validateOptions(): void {
923
+ this.validator.field('path').required().string().validate()
924
+ }
925
+
926
+ protected getPluginName(): string {
927
+ return 'my-plugin'
928
+ }
929
+
930
+ protected addPluginHooks(plugin: Plugin): void {
931
+ plugin.buildStart = () => {
932
+ this.logger.info(`Plugin started with path: ${this.options.path}`)
933
+ }
934
+ }
935
+
936
+ protected destroy(): void {
937
+ super.destroy()
938
+ // Custom cleanup logic, e.g. close connections, stop watchers
939
+ }
940
+ }
941
+
942
+ // Basic usage
943
+ export const myPlugin = createPluginFactory(MyPlugin)
944
+
945
+ // With normalizer (supports shorthand string config)
946
+ export const myPluginWithNormalizer = createPluginFactory(MyPlugin, opt => (typeof opt === 'string' ? { path: opt } : opt))
947
+ // Usage with shorthand: myPluginWithNormalizer('./custom-path')
948
+ ```
949
+
754
950
  ## Sub-path Exports
755
951
 
756
952
  Support importing modules on demand to reduce bundle size:
757
953
 
758
954
  ```typescript
759
955
  // Full import
760
- import { buildProgress, copyFile, injectLoading, BasePlugin, Logger } from '@meng-xi/vite-plugin'
956
+ import { buildProgress, copyFile, htmlInject, loadingManager, BasePlugin, Logger } from '@meng-xi/vite-plugin'
761
957
 
762
958
  // Module-level import
763
959
  import { BasePlugin, createPluginFactory } from '@meng-xi/vite-plugin/factory'
764
960
  import { Logger } from '@meng-xi/vite-plugin/logger'
765
- import { buildProgress, copyFile, generateRouter, injectLoading } from '@meng-xi/vite-plugin/plugins'
961
+ import { buildProgress, copyFile, generateRouter, htmlInject, loadingManager } from '@meng-xi/vite-plugin/plugins'
766
962
  import { Validator, readFileContent, writeFileContent } from '@meng-xi/vite-plugin/common'
767
963
 
768
964
  // Type imports (on-demand type definitions from sub-paths)
769
965
  import type { PluginWithInstance, PluginFactory, BasePluginOptions } from '@meng-xi/vite-plugin/factory'
770
- import type { BuildProgressOptions, GenerateVersionOptions, InjectIcoOptions, InjectLoadingOptions, Icon } from '@meng-xi/vite-plugin/plugins'
771
- import type { DateFormatOptions } from '@meng-xi/vite-plugin/common'
966
+ import type { BuildProgressOptions, GenerateVersionOptions, VersionUpdateCheckerOptions, HtmlInjectOptions, InjectRule, FaviconManagerOptions, LoadingManagerOptions, Icon } from '@meng-xi/vite-plugin/plugins'
967
+ import type { DateFormatOptions } from '@meng-xi/vite-plugin/common/format'
968
+ import type { HtmlInjectResult, DualInjectResult } from '@meng-xi/vite-plugin/common/html'
969
+ import type { CopyOptions, CopyResult } from '@meng-xi/vite-plugin/common/fs'
772
970
  ```
773
971
 
774
972
  ## Changelog
775
973
 
776
- See [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
974
+ View [GitHub Releases](https://github.com/MengXi-Studio/vite-plugin/releases)
777
975
 
778
976
  ## Contributing
779
977
 
780
978
  Contributions are welcome! Please follow these steps:
781
979
 
782
- 1. Fork the repository
980
+ 1. Fork this project
783
981
  2. Create a feature branch: `git checkout -b feature/your-feature`
784
982
  3. Commit changes: `git commit -m "feat: your feature description"`
785
- 4. Push to branch: `git push origin feature/your-feature`
983
+ 4. Push branch: `git push origin feature/your-feature`
786
984
  5. Create a Pull Request
787
985
 
788
986
  ## License