vite-plugin-version-info 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 lightrain
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # vite-plugin-version-info
2
+
3
+ A Vite plugin that injects version metadata into your app at build time. Useful for displaying neat version strings and commit timestamps in your UI or console.
4
+
5
+ [**npm**](https://www.npmjs.com/package/vite-plugin-version-info) • [**Repository**](https://codeberg.org/lightrain/vite-plugin-version-info) • [**Issues**](https://codeberg.org/lightrain/vite-plugin-version-info/issues)
6
+
7
+ ## ✨ Features
8
+
9
+ - Injects version string and commit date from Git and `package.json`
10
+ - Fully customizable version format via pattern tokens
11
+ - Locale-aware and timezone-aware commit date and time formatting
12
+ - Detects missing license and appends customizable suffix
13
+ - Adds branch suffix based on `NODE_ENV`
14
+ - Injects global constants at build time — no runtime overhead or bundle size impact
15
+
16
+ ## 📦 Installation
17
+
18
+ Install using your preferred package manager:
19
+
20
+ ```bash
21
+ npm install -D vite-plugin-version-info
22
+ # or
23
+ pnpm add -D vite-plugin-version-info
24
+ ```
25
+
26
+ ## 🚀 Usage
27
+
28
+ Add the plugin to your `vite.config.ts` or `vite.config.js`:
29
+
30
+ ```ts
31
+ import versionInfo from 'vite-plugin-version-info';
32
+
33
+ export default defineConfig({
34
+ plugins: [
35
+ /* other plugins */
36
+ versionInfo({
37
+ locale: 'en-GB',
38
+ commitHashLength: 8,
39
+ noLicenseSuffix: '-proprietary',
40
+ pattern: '{version}-{commitHash}{noLicenseSuffix}',
41
+ }),
42
+ ],
43
+ });
44
+ ```
45
+
46
+ Or, with all options omitted (using defaults):
47
+
48
+ ```ts
49
+ import versionInfo from 'vite-plugin-version-info';
50
+
51
+ export default defineConfig({
52
+ plugins: [
53
+ /* other plugins */
54
+ versionInfo(),
55
+ ],
56
+ });
57
+ ```
58
+
59
+ Then use the global constants injected by the plugin anywhere in your app:
60
+
61
+ ```ts
62
+ console.log(`Build version: ${__APP_VERSION__} - committed on ${__COMMIT_DATE__}`);
63
+ ```
64
+
65
+ Example output:
66
+
67
+ ```
68
+ Build version: 1.2.3-4afb2a1e-proprietary - committed on July 7, 2025
69
+ ```
70
+
71
+ Or, using defaults:
72
+
73
+ ```
74
+ 1.2.3-nonfree develop-4afb2a1e - commited on July 7, 2025
75
+ ```
76
+
77
+ ### 🧪 Injected Globals
78
+
79
+ These globals are injected at build time and can be accessed anywhere in your UI code or logic.
80
+
81
+ | Global | Type | Description |
82
+ | ----------------- | -------- | --------------------------------------- |
83
+ | `__APP_VERSION__` | `string` | Fully formatted version string |
84
+ | `__COMMIT_DATE__` | `string` | Formatted date of the latest Git commit |
85
+
86
+ ### 🛠️ Options
87
+
88
+ | Option | Type | Default | Description |
89
+ | ------------------ | ---------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------- |
90
+ | `locale` | `string` | `'en-US'` | Locale used to format the commit date |
91
+ | `commitHashLength` | `number` | `8` | Number of characters to use from the Git commit hash |
92
+ | `intlOptions` | `Intl.DateTimeFormatOptions` | `{ dateStyle: 'long' }` | Intl.DateTimeFormat options to customize commit date formatting |
93
+ | `noLicenseSuffix` | `string` | `'-nonfree'` | Suffix appended to version string if no license is found |
94
+ | `pattern` | `string` | `'{version}{noLicenseSuffix} {currentBranch}-{commitHash}{branchSuffix}'` | Template string to format the final version string |
95
+
96
+ ### 🧩 Pattern Tokens
97
+
98
+ You can customize the `versionString` using a template string with the following tokens. These will be replaced at build time:
99
+
100
+ | Token | Description | Example |
101
+ | ------------------- | ----------------------------------------------- | -------------------------------------- |
102
+ | `{version}` | Version from your `package.json` | `1.2.3` |
103
+ | `{noLicenseSuffix}` | Appended if `license` field is missing | `-nonfree`, `-unlicensed`, or empty |
104
+ | `{currentBranch}` | Current Git branch name | `main`, `develop`, `feature/login-fix` |
105
+ | `{commitHash}` | Git commit hash truncated to `commitHashLength` | `4afb2a1e` |
106
+ | `{branchSuffix}` | `-dev` if `NODE_ENV` starts with `"dev"` | `-dev` or empty |
107
+
108
+ #### 🔧 Example Output
109
+
110
+ Given the following plugin options:
111
+
112
+ ```ts
113
+ {
114
+ pattern: '{version}{noLicenseSuffix}-{currentBranch}-{commitHash}{branchSuffix}',
115
+ commitHashLength: 8,
116
+ }
117
+ ```
118
+
119
+ And your environment:
120
+
121
+ - `version` field in `package.json` is `1.2.3`
122
+ - `license` field missing in `package.json`
123
+ - Current git branch is `develop`
124
+ - Last commit hash is `4afb2a1efddc3a34...` → shortened to `4afb2a1e`
125
+ - `NODE_ENV=development`
126
+
127
+ Then the result will be:
128
+
129
+ ```ts
130
+ versionString = '1.2.3-nonfree-develop-4afb2a1e-dev';
131
+ ```
132
+
133
+ You can fully control the format by editing the pattern string.
134
+
135
+ ## Contributing
136
+
137
+ Pull requests are welcome. For major changes, please open an issue first
138
+ to discuss what you would like to change.
139
+
140
+ Please make sure to update tests as appropriate.
141
+
142
+ ## License
143
+
144
+ [MIT](LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,126 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var child_process = require('child_process');
6
+ var fs = require('fs');
7
+ var path = require('path');
8
+ var process = require('process');
9
+ var url = require('url');
10
+
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ function _interopNamespaceDefault(e) {
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var child_process__namespace = /*#__PURE__*/_interopNamespaceDefault(child_process);
30
+
31
+ function formatDate(date, locale, options = {
32
+ dateStyle: "long",
33
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
34
+ }) {
35
+ return new Intl.DateTimeFormat(locale, options).format(date);
36
+ }
37
+ function formatVersionString(pattern, context) {
38
+ return pattern.replace(/\{(\w+)\}/g, (_, key) => {
39
+ return context[key] !== void 0 ? context[key] : `{${key}}`;
40
+ });
41
+ }
42
+ function getBranchSuffix() {
43
+ return process.env.NODE_ENV?.startsWith("dev") ? "-dev" : "";
44
+ }
45
+ function getCommitDate({ locale, intlOptions }) {
46
+ const output = runCommand('bash -c "git show -s --format=%cd --date=iso-strict|cat"');
47
+ let date = void 0;
48
+ try {
49
+ date = new Date(output);
50
+ } catch (e) {
51
+ console.error("Could not convert command output to Date:", output);
52
+ return "";
53
+ }
54
+ return formatDate(date, locale, intlOptions);
55
+ }
56
+ function getCurrentBranchName() {
57
+ return runCommand("git rev-parse --abbrev-ref HEAD");
58
+ }
59
+ function getCommitHash(short) {
60
+ return runCommand(`git rev-parse${short ? " --short" : ""} HEAD`);
61
+ }
62
+ function getVersionString({
63
+ commitHashLength,
64
+ noLicenseSuffix,
65
+ pattern
66
+ }) {
67
+ const { version, license } = readPackageJson();
68
+ const currentBranch = getCurrentBranchName();
69
+ const licenseSuffix = license ? "" : noLicenseSuffix;
70
+ const commitHash = sliceCommitHash(getCommitHash(commitHashLength < 8), commitHashLength);
71
+ const branchSuffix = getBranchSuffix();
72
+ const context = {
73
+ version,
74
+ noLicenseSuffix: licenseSuffix,
75
+ currentBranch,
76
+ commitHash,
77
+ branchSuffix
78
+ };
79
+ return formatVersionString(pattern, context);
80
+ }
81
+ function runCommand(command) {
82
+ return child_process__namespace.execSync(command).toString().trim();
83
+ }
84
+ function readPackageJson() {
85
+ const file = url.fileURLToPath(new URL(path.join(process.cwd(), "package.json"), (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
86
+ const json = fs.readFileSync(file, "utf8");
87
+ return JSON.parse(json);
88
+ }
89
+ function sliceCommitHash(hash, length) {
90
+ return hash.slice(0, length);
91
+ }
92
+
93
+ function plugin({
94
+ locale,
95
+ commitHashLength,
96
+ intlOptions,
97
+ noLicenseSuffix,
98
+ pattern
99
+ } = {}) {
100
+ return {
101
+ name: "vite-plugin-version-info",
102
+ config() {
103
+ return {
104
+ define: {
105
+ __APP_VERSION__: JSON.stringify(
106
+ getVersionString({
107
+ commitHashLength: commitHashLength ?? 8,
108
+ noLicenseSuffix: noLicenseSuffix ?? "-nonfree",
109
+ pattern: pattern ?? "{version}{noLicenseSuffix} {currentBranch}-{commitHash}{branchSuffix}"
110
+ })
111
+ ),
112
+ __COMMIT_DATE__: JSON.stringify(
113
+ getCommitDate({
114
+ locale: locale ?? "en-US",
115
+ intlOptions: intlOptions ?? {
116
+ dateStyle: "long"
117
+ }
118
+ })
119
+ )
120
+ }
121
+ };
122
+ }
123
+ };
124
+ }
125
+
126
+ exports.default = plugin;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Options for formatting the Git commit date.
3
+ */
4
+ type CommitDateOptions = {
5
+ /**
6
+ * Locale for the formatted date (e.g., 'en-GB', 'en-US').
7
+ */
8
+ locale?: string;
9
+ /**
10
+ * Intl.DateTimeFormat options for customizing date output.
11
+ */
12
+ intlOptions?: Intl.DateTimeFormatOptions;
13
+ };
14
+ /**
15
+ * Options for customizing the version string.
16
+ */
17
+ type VersionStringOptions = {
18
+ /**
19
+ * Suffix to append when no license is present (default: "-nonfree").
20
+ */
21
+ noLicenseSuffix?: string;
22
+ /**
23
+ * Template string for version output (e.g., "{version}-{commitHash}").
24
+ */
25
+ pattern?: string;
26
+ /**
27
+ * Length of Git commit hash (short = <8 chars, long otherwise).
28
+ */
29
+ commitHashLength?: number;
30
+ };
31
+ /**
32
+ * Combined plugin options for version and commit date customization.
33
+ */
34
+ type VersionInfoPluginOptions = CommitDateOptions & VersionStringOptions;
35
+
36
+ /**
37
+ * Vite plugin that injects Git version info and commit metadata into your frontend app.
38
+ *
39
+ * Injects `__APP_VERSION__` and `__COMMIT_DATE__` using the latest Git metadata.
40
+ *
41
+ * ### Example Usage
42
+ * ```ts
43
+ * console.log(__APP_VERSION__); // e.g., "1.2.3-dev-abc123"
44
+ * console.log(__COMMIT_DATE__); // e.g., "July 8, 2025"
45
+ * ```
46
+ *
47
+ * @param options - Plugin options to customize formatting and metadata injection
48
+ * @returns A Vite-compatible plugin object
49
+ */
50
+ declare function plugin({ locale, commitHashLength, intlOptions, noLicenseSuffix, pattern, }?: VersionInfoPluginOptions): {
51
+ name: string;
52
+ config(): {
53
+ define: {
54
+ __APP_VERSION__: string;
55
+ __COMMIT_DATE__: string;
56
+ };
57
+ };
58
+ };
59
+
60
+ export { plugin as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,102 @@
1
+ import * as child_process from 'child_process';
2
+ import { readFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ import process from 'process';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ function formatDate(date, locale, options = {
8
+ dateStyle: "long",
9
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
10
+ }) {
11
+ return new Intl.DateTimeFormat(locale, options).format(date);
12
+ }
13
+ function formatVersionString(pattern, context) {
14
+ return pattern.replace(/\{(\w+)\}/g, (_, key) => {
15
+ return context[key] !== void 0 ? context[key] : `{${key}}`;
16
+ });
17
+ }
18
+ function getBranchSuffix() {
19
+ return process.env.NODE_ENV?.startsWith("dev") ? "-dev" : "";
20
+ }
21
+ function getCommitDate({ locale, intlOptions }) {
22
+ const output = runCommand('bash -c "git show -s --format=%cd --date=iso-strict|cat"');
23
+ let date = void 0;
24
+ try {
25
+ date = new Date(output);
26
+ } catch (e) {
27
+ console.error("Could not convert command output to Date:", output);
28
+ return "";
29
+ }
30
+ return formatDate(date, locale, intlOptions);
31
+ }
32
+ function getCurrentBranchName() {
33
+ return runCommand("git rev-parse --abbrev-ref HEAD");
34
+ }
35
+ function getCommitHash(short) {
36
+ return runCommand(`git rev-parse${short ? " --short" : ""} HEAD`);
37
+ }
38
+ function getVersionString({
39
+ commitHashLength,
40
+ noLicenseSuffix,
41
+ pattern
42
+ }) {
43
+ const { version, license } = readPackageJson();
44
+ const currentBranch = getCurrentBranchName();
45
+ const licenseSuffix = license ? "" : noLicenseSuffix;
46
+ const commitHash = sliceCommitHash(getCommitHash(commitHashLength < 8), commitHashLength);
47
+ const branchSuffix = getBranchSuffix();
48
+ const context = {
49
+ version,
50
+ noLicenseSuffix: licenseSuffix,
51
+ currentBranch,
52
+ commitHash,
53
+ branchSuffix
54
+ };
55
+ return formatVersionString(pattern, context);
56
+ }
57
+ function runCommand(command) {
58
+ return child_process.execSync(command).toString().trim();
59
+ }
60
+ function readPackageJson() {
61
+ const file = fileURLToPath(new URL(join(process.cwd(), "package.json"), import.meta.url));
62
+ const json = readFileSync(file, "utf8");
63
+ return JSON.parse(json);
64
+ }
65
+ function sliceCommitHash(hash, length) {
66
+ return hash.slice(0, length);
67
+ }
68
+
69
+ function plugin({
70
+ locale,
71
+ commitHashLength,
72
+ intlOptions,
73
+ noLicenseSuffix,
74
+ pattern
75
+ } = {}) {
76
+ return {
77
+ name: "vite-plugin-version-info",
78
+ config() {
79
+ return {
80
+ define: {
81
+ __APP_VERSION__: JSON.stringify(
82
+ getVersionString({
83
+ commitHashLength: commitHashLength ?? 8,
84
+ noLicenseSuffix: noLicenseSuffix ?? "-nonfree",
85
+ pattern: pattern ?? "{version}{noLicenseSuffix} {currentBranch}-{commitHash}{branchSuffix}"
86
+ })
87
+ ),
88
+ __COMMIT_DATE__: JSON.stringify(
89
+ getCommitDate({
90
+ locale: locale ?? "en-US",
91
+ intlOptions: intlOptions ?? {
92
+ dateStyle: "long"
93
+ }
94
+ })
95
+ )
96
+ }
97
+ };
98
+ }
99
+ };
100
+ }
101
+
102
+ export { plugin as default };
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "vite-plugin-version-info",
3
+ "description": "A Vite plugin that injects software version metadata as build-time globals for easy display in your UI or console.",
4
+ "version": "1.0.0",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "vite",
8
+ "vite-plugin",
9
+ "package",
10
+ "version",
11
+ "git",
12
+ "commit",
13
+ "branch",
14
+ "date"
15
+ ],
16
+ "author": "lightrain <lightrain@humanity>",
17
+ "homepage": "https://codeberg.org/lightrain/vite-plugin-version-info#readme",
18
+ "bugs": {
19
+ "url": "https://codeberg.org/lightrain/vite-plugin-version-info/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://codeberg.org/lightrain/vite-plugin-version-info.git"
24
+ },
25
+ "readme": "",
26
+ "type": "module",
27
+ "peerDependencies": {
28
+ "vite": "^2.7.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "@rollup/plugin-typescript": "^12.1.4",
32
+ "@types/node": "^24.0.10",
33
+ "prettier": "^3.6.2",
34
+ "rollup": "^4.44.2",
35
+ "rollup-plugin-dts": "^6.2.1",
36
+ "rollup-plugin-esbuild": "^6.2.1",
37
+ "tslib": "^2.8.1",
38
+ "typescript": "^5.8.3",
39
+ "vite": "^6.3.5"
40
+ },
41
+ "main": "dist/index.cjs",
42
+ "types": "dist/index.d.ts",
43
+ "module": "dist/index.mjs",
44
+ "exports": {
45
+ ".": {
46
+ "types": "./dist/index.d.ts",
47
+ "import": "./dist/index.mjs",
48
+ "require": "./dist/index.cjs"
49
+ },
50
+ "./*": "./dist/*"
51
+ },
52
+ "files": [
53
+ "dist"
54
+ ],
55
+ "scripts": {
56
+ "build": "rollup -c rollup.config.ts --configPlugin typescript",
57
+ "clean": "rm -rf dist",
58
+ "dev": "rollup -c rollup.config.ts --configPlugin typescript",
59
+ "format": "prettier --write ."
60
+ }
61
+ }