@kevairy/template 0.1.4 → 0.1.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kevairy/template",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Project template consumed by @kevairy/cli",
5
5
  "keywords": [
6
6
  "vue",
package/template/.env CHANGED
@@ -1,8 +1,5 @@
1
1
  # 【通用】环境变量
2
2
 
3
- # 版本号
4
- VITE_VERSION = 0.1.0
5
-
6
3
  # 端口号
7
4
  VITE_PORT = 3006
8
5
 
@@ -6,7 +6,7 @@ VITE_BASE_URL = /
6
6
  # API 地址前缀
7
7
  VITE_API_URL = /api/
8
8
 
9
- # CI 可注入 Git SHA / 发布编号;留空时自动使用构建时间。
9
+ # CI 可注入唯一构建编号;留空时自动生成 UTC 时间 + Git 提交 + 随机后缀。
10
10
  VITE_BUILD_ID =
11
11
 
12
12
  # true 生成 hidden sourcemap;上传诊断平台后必须从静态部署目录删除 .map 文件。
@@ -20,3 +20,15 @@ __RUN_COMMAND__ typecheck
20
20
  __RUN_COMMAND__ test
21
21
  __RUN_COMMAND__ build
22
22
  ```
23
+
24
+ ## 版本与构建
25
+
26
+ 发布版本由项目根目录 package.json 的 version 管理。每次执行构建命令会自动生成独立的构建编号、UTC 构建时间、Git 提交和未提交状态,不修改版本文件。
27
+
28
+ 浏览器控制台在生产环境也会显示一次构建信息;dist/version.json 和错误诊断使用相同的发布版本与构建编号。没有 Git 也可以正常构建,无法确认的提交和工作区状态标为 null。
29
+
30
+ CI 可以通过 VITE_BUILD_ID 覆盖构建编号(应保证每次构建唯一),通过进程环境变量 BUILD_GIT_COMMIT 和 BUILD_GIT_DIRTY 注入提交与工作区状态。BUILD_GIT_DIRTY 仅接受 true 或 false;只注入提交时,工作区状态标为未知。
31
+
32
+ 部署时将 version.json 与同一批静态资源一起发布,并对该文件配置 Cache-Control: no-store。浏览器输出代表当前页面已加载的版本,服务器的 version.json 代表服务器当前提供的版本。
33
+
34
+ 准备正式发布时再升级 package.json 的 version,例如运行 npm version patch --no-git-tag-version;自动构建编号不参与本地存储版本迁移。
@@ -17,7 +17,7 @@
17
17
  "@vueuse/core": "13.9.0",
18
18
  "@wangeditor/editor": "5.1.23",
19
19
  "@wangeditor/editor-for-vue": "5.1.12",
20
- "axios": "1.19.0",
20
+ "axios": "1.21.1",
21
21
  "driver.js": "1.9.0",
22
22
  "echarts": "6.1.0",
23
23
  "element-plus": "2.14.4",
@@ -29,8 +29,8 @@
29
29
  "pinia-plugin-persistedstate": "4.7.1",
30
30
  "qrcode.vue": "3.10.0",
31
31
  "tailwindcss": "4.3.3",
32
- "vue": "3.5.41",
33
- "vue-i18n": "11.4.8",
32
+ "vue": "3.5.45",
33
+ "vue-i18n": "11.4.18",
34
34
  "vue-router": "4.6.4",
35
35
  "xgplayer": "3.0.26"
36
36
  },
@@ -65,7 +65,7 @@
65
65
  "@playwright/test": "1.62.1",
66
66
  "@types/node": "24.13.3",
67
67
  "@vitejs/plugin-vue": "6.0.8",
68
- "@vue/compiler-sfc": "3.5.41",
68
+ "@vue/compiler-sfc": "3.5.45",
69
69
  "@vue/test-utils": "2.4.11",
70
70
  "happy-dom": "20.11.2",
71
71
  "rollup-plugin-visualizer": "5.14.0",
@@ -74,7 +74,7 @@
74
74
  "unplugin-auto-import": "20.3.0",
75
75
  "unplugin-element-plus": "0.10.0",
76
76
  "unplugin-vue-components": "29.2.0",
77
- "vite": "7.3.6",
77
+ "vite": "7.3.8",
78
78
  "vitest": "4.1.10",
79
79
  "vue-demi": "0.14.10",
80
80
  "vue-img-cutter": "3.1.1",
@@ -0,0 +1,76 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { readFileSync } from 'node:fs'
4
+ import path from 'node:path'
5
+ import type { Plugin } from 'vite'
6
+ import type { BuildInfo } from '../src/types/build-info'
7
+
8
+ interface BuildInfoOptions {
9
+ root: string
10
+ mode: string
11
+ buildId?: string
12
+ gitCommit?: string
13
+ gitDirty?: string
14
+ }
15
+
16
+ function readGit(root: string, args: string[]): string | null {
17
+ try {
18
+ return execFileSync('git', args, {
19
+ cwd: root,
20
+ encoding: 'utf8',
21
+ stdio: ['ignore', 'pipe', 'ignore'],
22
+ timeout: 3000
23
+ }).trim()
24
+ } catch {
25
+ return null
26
+ }
27
+ }
28
+
29
+ export function createBuildInfo(options: BuildInfoOptions): BuildInfo {
30
+ const { version } = JSON.parse(readFileSync(path.join(options.root, 'package.json'), 'utf8'))
31
+ if (typeof version !== 'string' || !version.trim()) {
32
+ throw new Error('package.json 必须包含非空的 version 字段')
33
+ }
34
+
35
+ const gitCommit = options.gitCommit?.trim() || readGit(options.root, ['rev-parse', 'HEAD'])
36
+ // CI 指定提交时,不把构建机工作区状态误当成该提交的状态。
37
+ const status = options.gitCommit?.trim()
38
+ ? null
39
+ : readGit(options.root, ['status', '--porcelain', '--untracked-files=normal'])
40
+ if (options.gitDirty && !['true', 'false'].includes(options.gitDirty)) {
41
+ throw new Error('BUILD_GIT_DIRTY 只允许 true 或 false')
42
+ }
43
+ const gitDirty = options.gitDirty
44
+ ? options.gitDirty === 'true'
45
+ : status === null
46
+ ? null
47
+ : status.length > 0
48
+ const builtAt = new Date().toISOString()
49
+ const timestamp = builtAt.replace(/[-:.]/g, '')
50
+ const buildId =
51
+ options.buildId?.trim() ||
52
+ `${timestamp}-${gitCommit?.slice(0, 12) || 'nogit'}${gitDirty ? '-dirty' : ''}-${randomUUID().slice(0, 8)}`
53
+
54
+ return { version, buildId, gitCommit, gitDirty, builtAt, mode: options.mode }
55
+ }
56
+
57
+ /** 常量与静态清单复用同一份快照,不在输出阶段重新生成编号。 */
58
+ export function buildInfoPlugin(info: BuildInfo): Plugin {
59
+ return {
60
+ name: 'app-build-info',
61
+ config: () => ({
62
+ define: {
63
+ __APP_VERSION__: JSON.stringify(info.version),
64
+ __BUILD_ID__: JSON.stringify(info.buildId),
65
+ __BUILD_INFO__: JSON.stringify(info)
66
+ }
67
+ }),
68
+ generateBundle() {
69
+ this.emitFile({
70
+ type: 'asset',
71
+ fileName: 'version.json',
72
+ source: `${JSON.stringify(info, null, 2)}\n`
73
+ })
74
+ }
75
+ }
76
+ }
@@ -31,3 +31,4 @@ declare module 'qrcode.vue' {
31
31
  // 全局变量声明
32
32
  declare const __APP_VERSION__: string // 版本号
33
33
  declare const __BUILD_ID__: string // 每次构建的唯一标识,可由 CI 注入
34
+ declare const __BUILD_INFO__: Readonly<import('./types/build-info').BuildInfo>
@@ -0,0 +1,11 @@
1
+ /** 当前页面所加载产物的构建信息,所有字段均可公开。 */
2
+ export interface BuildInfo {
3
+ version: string
4
+ buildId: string
5
+ gitCommit: string | null
6
+ /** null 表示无法确认工作区状态(例如没有 Git 或由 CI 仅注入提交号)。 */
7
+ gitDirty: boolean | null
8
+ builtAt: string
9
+ /** Vite 构建模式,不代表实际部署环境。 */
10
+ mode: string
11
+ }
@@ -199,8 +199,6 @@ export interface SystemConfig {
199
199
  export interface EnvConfig {
200
200
  // 环境名称
201
201
  NODE_ENV: string
202
- // 应用版本
203
- VITE_VERSION: string
204
202
  // 应用端口
205
203
  VITE_PORT: string
206
204
  // 应用基础路径
@@ -1,9 +1,65 @@
1
- import AppConfig from '@/config'
1
+ const info = __BUILD_INFO__
2
+ const builtAt = Object.fromEntries(
3
+ new Intl.DateTimeFormat('zh-CN', {
4
+ year: 'numeric',
5
+ month: '2-digit',
6
+ day: '2-digit',
7
+ hour: '2-digit',
8
+ minute: '2-digit',
9
+ second: '2-digit',
10
+ hourCycle: 'h23',
11
+ timeZoneName: 'shortOffset'
12
+ })
13
+ .formatToParts(new Date(info.builtAt))
14
+ .map(({ type, value }) => [type, value])
15
+ )
16
+ const localBuildTime = [
17
+ `${builtAt.year}-${builtAt.month}-${builtAt.day}`,
18
+ `${builtAt.hour}:${builtAt.minute}:${builtAt.second}`,
19
+ builtAt.timeZoneName
20
+ ].join(' ')
21
+ const font = 'font-family:ui-monospace,SFMono-Regular,Consolas,monospace;'
22
+ const badge = `${font}padding:5px 10px;font-size:12px;line-height:2;font-weight:600;`
23
+ const labelStyle = `${font}color:#7b8798;line-height:1.9;`
24
+ const valueStyle = `${font}color:inherit;line-height:1.9;`
25
+ const workspace =
26
+ info.gitDirty === null
27
+ ? { text: 'Unknown · 无法确认', color: '#7b8798' }
28
+ : info.gitDirty
29
+ ? { text: 'Dirty · 有未提交改动', color: '#d97706' }
30
+ : { text: 'Clean · 无未提交改动', color: '#16a34a' }
2
31
 
3
- const banner = [
4
- `%c${AppConfig.systemInfo.name}%c ${AppConfig.systemInfo.description ?? ''}`,
5
- 'padding:4px 8px;border-radius:6px 0 0 6px;background:#1e40af;color:#fff;font-weight:600',
6
- 'padding:4px 8px;border-radius:0 6px 6px 0;background:#dbeafe;color:#1e3a8a;font-weight:500'
7
- ] as const
32
+ const rows = [
33
+ { label: 'Build ID', value: info.buildId, style: valueStyle },
34
+ { label: 'Commit', value: info.gitCommit?.slice(0, 12) ?? 'Unavailable', style: valueStyle },
35
+ {
36
+ label: 'Built at',
37
+ value: localBuildTime,
38
+ style: valueStyle
39
+ },
40
+ {
41
+ label: 'Workspace',
42
+ value: workspace.text,
43
+ style: `${font}color:${workspace.color};line-height:1.9;`
44
+ }
45
+ ]
8
46
 
9
- console.info(...banner)
47
+ const details = rows.map(({ label }) => `%c ${label.padEnd(11)}%c%s`).join('\n')
48
+
49
+ // 只有启动信息通过绑定调用保留;业务 console.info 仍由生产构建移除。
50
+ const printBuildInfo = console.info.bind(console)
51
+ printBuildInfo(
52
+ `%cBuild Info%c v%s %c %s %c\n\n${details}\n\n%c Details %c%o`,
53
+ `${badge}background:#2563eb;color:#fff;border-radius:6px 0 0 6px;`,
54
+ `${badge}background:#dbeafe;color:#1e40af;border-radius:0 6px 6px 0;`,
55
+ info.version,
56
+ `${badge}background:#e2e8f0;color:#334155;border-radius:6px;margin-left:8px;`,
57
+ info.mode.toUpperCase(),
58
+ '',
59
+ ...rows.flatMap(({ value, style }) => [labelStyle, style, value]),
60
+ labelStyle,
61
+ valueStyle,
62
+ info
63
+ )
64
+
65
+ export {}
@@ -0,0 +1,151 @@
1
+ // @vitest-environment node
2
+ import { execFileSync } from 'node:child_process'
3
+ import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { runInNewContext } from 'node:vm'
8
+ import { build } from 'vite'
9
+ import { afterEach, describe, expect, it, vi } from 'vitest'
10
+ import { buildInfoPlugin, createBuildInfo } from '../../../scripts/build-info'
11
+
12
+ const directories: string[] = []
13
+ const git = (root: string, ...args: string[]) =>
14
+ execFileSync('git', args, {
15
+ cwd: root,
16
+ encoding: 'utf8',
17
+ stdio: ['ignore', 'pipe', 'pipe']
18
+ }).trim()
19
+
20
+ async function fixture(withGit = false) {
21
+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'kevairy-build-info-')))
22
+ directories.push(root)
23
+ await writeFile(path.join(root, 'package.json'), JSON.stringify({ version: '1.2.3' }))
24
+ if (withGit) {
25
+ git(root, 'init')
26
+ git(root, 'add', 'package.json')
27
+ git(
28
+ root,
29
+ '-c',
30
+ 'user.name=Build Test',
31
+ '-c',
32
+ 'user.email=build-test@example.invalid',
33
+ '-c',
34
+ 'commit.gpgsign=false',
35
+ '-c',
36
+ 'core.hooksPath=/dev/null',
37
+ 'commit',
38
+ '-m',
39
+ 'Initial fixture'
40
+ )
41
+ }
42
+ return root
43
+ }
44
+
45
+ afterEach(async () => {
46
+ vi.useRealTimers()
47
+ await Promise.all(directories.splice(0).map((root) => rm(root, { recursive: true, force: true })))
48
+ })
49
+
50
+ describe('build identity', () => {
51
+ it('uses the project version and creates distinct IDs even within the same millisecond', async () => {
52
+ const root = await fixture()
53
+ vi.useFakeTimers()
54
+ vi.setSystemTime(new Date('2026-11-11T07:30:00.000Z'))
55
+ const first = createBuildInfo({ root, mode: 'production' })
56
+ const second = createBuildInfo({ root, mode: 'production' })
57
+ expect(first).toMatchObject({
58
+ version: '1.2.3',
59
+ builtAt: '2026-11-11T07:30:00.000Z',
60
+ gitCommit: null,
61
+ gitDirty: null,
62
+ mode: 'production'
63
+ })
64
+ expect(first.buildId).toMatch(/^20261111T073000000Z-nogit-[a-f0-9]{8}$/)
65
+ expect(second.buildId).not.toBe(first.buildId)
66
+ expect(JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')).version).toBe(
67
+ '1.2.3'
68
+ )
69
+ })
70
+
71
+ it('records clean commits and detects both tracked and untracked changes', async () => {
72
+ const root = await fixture(true)
73
+ const clean = createBuildInfo({ root, mode: 'production' })
74
+ expect(clean.gitCommit).toBe(git(root, 'rev-parse', 'HEAD'))
75
+ expect(clean.gitDirty).toBe(false)
76
+ await writeFile(path.join(root, 'new-file.txt'), 'Untracked change')
77
+ expect(createBuildInfo({ root, mode: 'production' }).gitDirty).toBe(true)
78
+ await rm(path.join(root, 'new-file.txt'))
79
+ await writeFile(path.join(root, 'package.json'), JSON.stringify({ version: '1.2.4' }))
80
+ const dirty = createBuildInfo({ root, mode: 'production' })
81
+ expect(dirty.gitDirty).toBe(true)
82
+ expect(dirty.buildId).toContain('-dirty-')
83
+ expect(dirty.version).toBe('1.2.4')
84
+ expect(dirty.gitCommit).toBe(clean.gitCommit)
85
+ })
86
+
87
+ it('handles a repository without a first commit and supports CI overrides', async () => {
88
+ const root = await fixture()
89
+ git(root, 'init')
90
+ expect(createBuildInfo({ root, mode: 'production' })).toMatchObject({
91
+ gitCommit: null,
92
+ gitDirty: true
93
+ })
94
+ const options = { root, mode: 'staging', buildId: 'pipeline-123', gitCommit: 'a'.repeat(40) }
95
+ expect(createBuildInfo(options)).toMatchObject({
96
+ buildId: 'pipeline-123',
97
+ gitCommit: 'a'.repeat(40),
98
+ gitDirty: null,
99
+ mode: 'staging'
100
+ })
101
+ expect(createBuildInfo({ ...options, gitDirty: 'false' }).gitDirty).toBe(false)
102
+ expect(() => createBuildInfo({ ...options, gitDirty: 'invalid' })).toThrow('BUILD_GIT_DIRTY')
103
+ })
104
+
105
+ it('keeps the startup identity in minified production JS and matches version.json', async () => {
106
+ const root = await fixture()
107
+ const consolePath = fileURLToPath(new URL('../../../src/utils/sys/console.ts', import.meta.url))
108
+ await writeFile(
109
+ path.join(root, 'index.html'),
110
+ '<script type="module" src="/entry.ts"></script>'
111
+ )
112
+ await writeFile(
113
+ path.join(root, 'entry.ts'),
114
+ `
115
+ import ${JSON.stringify(consolePath)}
116
+ console.info('business-log-must-be-removed')
117
+ globalThis.diagnosticIdentity = [__APP_VERSION__, __BUILD_ID__]
118
+ `
119
+ )
120
+ await writeFile(
121
+ path.join(root, 'config.ts'),
122
+ `
123
+ export default { systemInfo: { name: 'Fixture App', description: 'Test' } }
124
+ `
125
+ )
126
+ const info = createBuildInfo({ root, mode: 'production' })
127
+ const result = await build({
128
+ root,
129
+ configFile: false,
130
+ logLevel: 'silent',
131
+ base: '/admin/',
132
+ plugins: [buildInfoPlugin(info)],
133
+ resolve: { alias: { '@/config': path.join(root, 'config.ts') } },
134
+ esbuild: { pure: ['console.log', 'console.debug', 'console.info'], drop: ['debugger'] },
135
+ build: { write: false, modulePreload: false, minify: 'esbuild' }
136
+ })
137
+ if (Array.isArray(result) || !('output' in result)) throw new Error('Expected one build output')
138
+ const manifest = result.output.find((item) => item.fileName === 'version.json')
139
+ if (!manifest || manifest.type !== 'asset') throw new Error('Missing version.json')
140
+ expect(JSON.parse(String(manifest.source))).toEqual(info)
141
+ const entry = result.output.find((item) => item.type === 'chunk' && item.isEntry)
142
+ if (!entry || entry.type !== 'chunk') throw new Error('Missing entry JS')
143
+ const log = vi.fn()
144
+ const context = { console: { info: log }, diagnosticIdentity: [] }
145
+ runInNewContext(entry.code, context)
146
+ expect(log).toHaveBeenCalledTimes(1)
147
+ expect(log.mock.calls[0].at(-1)).toEqual(info)
148
+ expect(context.diagnosticIdentity).toEqual([info.version, info.buildId])
149
+ expect(entry.code).not.toContain('business-log-must-be-removed')
150
+ })
151
+ })
@@ -23,6 +23,13 @@
23
23
  "@styles/*": ["src/assets/styles/*"]
24
24
  }
25
25
  },
26
- "include": ["src/**/*", "src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
26
+ "include": [
27
+ "src/**/*",
28
+ "src/**/*.ts",
29
+ "src/**/*.d.ts",
30
+ "src/**/*.tsx",
31
+ "src/**/*.vue",
32
+ "scripts/**/*.ts"
33
+ ],
27
34
  "exclude": ["node_modules", "dist", "**/*.js"]
28
35
  }
@@ -1,4 +1,4 @@
1
- import { defineConfig, loadEnv } from 'vite'
1
+ import { defineConfig, loadEnv, type ConfigEnv } from 'vite'
2
2
  import vue from '@vitejs/plugin-vue'
3
3
  import path from 'path'
4
4
  import { fileURLToPath } from 'url'
@@ -6,12 +6,22 @@ import Components from 'unplugin-vue-components/vite'
6
6
  import AutoImport from 'unplugin-auto-import/vite'
7
7
  import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
8
8
  import tailwindcss from '@tailwindcss/vite'
9
+ import { buildInfoPlugin, createBuildInfo } from './scripts/build-info'
9
10
  // import { visualizer } from 'rollup-plugin-visualizer'
10
11
 
11
- export default ({ mode }: { mode: string }) => {
12
- const root = process.cwd()
12
+ export default ({ mode, isPreview }: ConfigEnv) => {
13
+ const root = fileURLToPath(new URL('.', import.meta.url))
13
14
  const env = loadEnv(mode, root)
14
- const { VITE_VERSION, VITE_PORT, VITE_BASE_URL, VITE_API_URL, VITE_API_PROXY_URL } = env
15
+ const { VITE_PORT, VITE_BASE_URL, VITE_API_URL, VITE_API_PROXY_URL } = env
16
+ const buildInfo = isPreview
17
+ ? undefined
18
+ : createBuildInfo({
19
+ root,
20
+ mode,
21
+ buildId: env.VITE_BUILD_ID,
22
+ gitCommit: process.env.BUILD_GIT_COMMIT,
23
+ gitDirty: process.env.BUILD_GIT_DIRTY
24
+ })
15
25
  const proxy = VITE_API_PROXY_URL
16
26
  ? {
17
27
  '/api': {
@@ -24,13 +34,9 @@ export default ({ mode }: { mode: string }) => {
24
34
  : undefined
25
35
 
26
36
  console.log(`🚀 API_URL = ${VITE_API_URL}`)
27
- console.log(`🚀 VERSION = ${VITE_VERSION}`)
37
+ if (buildInfo) console.log(`🚀 VERSION = ${buildInfo.version} / BUILD = ${buildInfo.buildId}`)
28
38
 
29
39
  return defineConfig({
30
- define: {
31
- __APP_VERSION__: JSON.stringify(VITE_VERSION),
32
- __BUILD_ID__: JSON.stringify(env.VITE_BUILD_ID || new Date().toISOString())
33
- },
34
40
  base: VITE_BASE_URL,
35
41
  server: {
36
42
  port: Number(VITE_PORT),
@@ -67,6 +73,7 @@ export default ({ mode }: { mode: string }) => {
67
73
  }
68
74
  },
69
75
  plugins: [
76
+ ...(buildInfo ? [buildInfoPlugin(buildInfo)] : []),
70
77
  vue(),
71
78
  tailwindcss(),
72
79
  // 自动按需导入 API