-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpost-build.js
More file actions
203 lines (165 loc) Β· 5.78 KB
/
post-build.js
File metadata and controls
203 lines (165 loc) Β· 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* post-build.js - Script for generating meta.json after build
*
* Generates meta.json file with unique build version (timestamp)
* for automatic update detection
*/
const fs = require('fs');
const path = require('path');
// Configuration
const CONFIG = {
// Path to public directory (project root where index.html is located)
publicDir: path.join(__dirname, '..'),
// meta.json filename
metaFileName: 'meta.json',
// Version format: 'timestamp' or 'semver'
versionFormat: 'timestamp'
};
/**
* Generate unique build version
*/
function generateBuildVersion() {
// Use timestamp for uniqueness of each build
const timestamp = Date.now();
// Optional: can add git commit hash
let gitHash = '';
try {
const { execSync } = require('child_process');
gitHash = execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).trim();
} catch (error) {
// Git not available or not initialized - ignore
}
return {
version: timestamp.toString(),
buildTime: new Date().toISOString(),
gitHash: gitHash || null,
buildId: `${timestamp}${gitHash ? `-${gitHash}` : ''}`
};
}
/**
* Read package.json to get application version
*/
function getAppVersion() {
try {
const packageJsonPath = path.join(__dirname, '..', 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
return packageJson.version || '1.0.0';
}
} catch (error) {
console.warn('β οΈ Failed to read package.json:', error.message);
}
return '1.0.0';
}
/**
* Generate meta.json
*/
function generateMetaJson() {
try {
const buildInfo = generateBuildVersion();
const appVersion = getAppVersion();
const meta = {
// Build version (used for update checking)
version: buildInfo.version,
buildVersion: buildInfo.version,
// Application version from package.json
appVersion: appVersion,
// Additional information
buildTime: buildInfo.buildTime,
buildId: buildInfo.buildId,
gitHash: buildInfo.gitHash,
// Metadata
generated: true,
generatedAt: new Date().toISOString()
};
// Path to meta.json file (in project root where index.html is located)
const metaFilePath = path.join(CONFIG.publicDir, CONFIG.metaFileName);
// Create directory if it doesn't exist
const publicDir = path.dirname(metaFilePath);
if (!fs.existsSync(publicDir)) {
fs.mkdirSync(publicDir, { recursive: true });
console.log(`β
Created directory: ${publicDir}`);
}
// Write meta.json
fs.writeFileSync(
metaFilePath,
JSON.stringify(meta, null, 2),
'utf-8'
);
console.log('β
meta.json generated successfully');
console.log(` Version: ${meta.version}`);
console.log(` Build Time: ${meta.buildTime}`);
if (meta.gitHash) {
console.log(` Git Hash: ${meta.gitHash}`);
}
console.log(` File: ${metaFilePath}`);
return meta;
} catch (error) {
console.error('β Failed to generate meta.json:', error);
process.exit(1);
}
}
/**
* Update versions in index.html
*/
function updateIndexHtmlVersions(buildVersion) {
try {
const indexHtmlPath = path.join(CONFIG.publicDir, 'index.html');
if (!fs.existsSync(indexHtmlPath)) {
console.warn('β οΈ index.html not found, skipping version update');
return;
}
let indexHtml = fs.readFileSync(indexHtmlPath, 'utf-8');
// Update versions in query parameters for JS files
// Pattern: src="dist/app.js?v=..." or src="dist/app-boot.js?v=..."
// Also replace BUILD_VERSION placeholder
indexHtml = indexHtml.replace(/\?v=BUILD_VERSION/g, `?v=${buildVersion}`);
indexHtml = indexHtml.replace(/\?v=(\d+)/g, `?v=${buildVersion}`);
fs.writeFileSync(indexHtmlPath, indexHtml, 'utf-8');
console.log('β
index.html versions updated');
} catch (error) {
console.warn('β οΈ Failed to update index.html versions:', error.message);
}
}
/**
* Validate generated meta.json
*/
function validateMetaJson(meta) {
const requiredFields = ['version', 'buildVersion', 'buildTime'];
const missingFields = requiredFields.filter(field => !meta[field]);
if (missingFields.length > 0) {
throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
}
if (!/^\d+$/.test(meta.version)) {
throw new Error(`Invalid version format: ${meta.version} (expected timestamp)`);
}
console.log('β
meta.json validation passed');
}
// Main function
function main() {
console.log('π¨ Generating meta.json...');
console.log(` Public directory: ${CONFIG.publicDir}`);
// Check if public directory exists
if (!fs.existsSync(CONFIG.publicDir)) {
console.error(`β Public directory not found: ${CONFIG.publicDir}`);
process.exit(1);
}
// Generate meta.json
const meta = generateMetaJson();
// Validate
validateMetaJson(meta);
// Update versions in index.html
updateIndexHtmlVersions(meta.version);
console.log('β
Build metadata generation completed');
}
// Run script
if (require.main === module) {
main();
}
// Export for use in other scripts
module.exports = {
generateMetaJson,
generateBuildVersion,
getAppVersion,
validateMetaJson
};