-
Notifications
You must be signed in to change notification settings - Fork 387
Expand file tree
/
Copy pathprebuild.mjs
More file actions
171 lines (145 loc) · 6.48 KB
/
Copy pathprebuild.mjs
File metadata and controls
171 lines (145 loc) · 6.48 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
/**
* This script is executed before the Angular CLI's build script is executed.
* It adds environment variables to the environment file and merges the i18n files.
* This way, we don't need a webpack configuration file: It replaces
* - webpack.DefinePlugin and
* - MergeJsonWebpackPlugin
*/
import fs from 'fs';
import path from 'path';
import { hashElement } from 'folder-hash';
import { fileURLToPath } from 'url';
import { spawn } from 'node:child_process';
import * as esbuild from 'esbuild';
import { runViteOverrideCheck } from './supporting_scripts/check-vite-override.mjs';
// Runs on every `ng serve` and every client build: a vite version that does not match what
// @angular/build expects breaks the dev server silently (blank page), so fail here instead.
runViteOverrideCheck();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const languagesHash = await hashElement(path.resolve(__dirname, 'src', 'main', 'webapp', 'i18n'), {
algo: 'md5',
encoding: 'hex',
files: { include: ['*.json'] },
});
// =====================
// Environment variables
// =====================
/*
* Needed for client compilations with docker compose, where the 'APP_VERSION' property isn't injected by gradle.
*
* Returns the inferred APP_VERSION from 'build.gradle', or 'DEV' if this couldn't be retrieved
*/
function inferVersion() {
let version = 'DEV';
try {
let data = fs.readFileSync('build.gradle', 'UTF-8');
version = data.match(/\nversion\s=\s"(.*)"/);
version = version[1] ?? 'DEV';
} catch (error) {
console.log("Error while retrieving 'APP_VERSION' property");
}
return version;
}
// --develop flag is used to enable debug mode
const args = process.argv.slice(2);
const developFlag = args.includes('--develop');
const environmentConfig = `// Don't change this file manually, it will be overwritten by the build process!
export const __DEBUG_INFO_ENABLED__ = ${developFlag};
export const __VERSION__ = '${process.env.APP_VERSION || inferVersion()}';
// The root URL for API calls, ending with a '/' - for example: \`"https://www.jhipster.tech:8081/myservice/"\`.
// If you use an API server, in \`prod\` mode, you will need to enable CORS
// (see the \`jhipster.cors\` common JHipster property in the \`application-*.yml\` configurations)
export const I18N_HASH = '${languagesHash.hash}';
`;
fs.writeFileSync(path.resolve(__dirname, 'src', 'main', 'webapp', 'app', 'core', 'environments', 'environment.override.ts'), environmentConfig);
// =====================
// i18n merging
// =====================
const groups = [
{ folder: './src/main/webapp/i18n/en', output: './src/main/webapp/i18n/en.json', landingOutput: './src/main/webapp/i18n/en-landing.json' },
{ folder: './src/main/webapp/i18n/de', output: './src/main/webapp/i18n/de.json', landingOutput: './src/main/webapp/i18n/de-landing.json' },
];
// Landing page only needs `landing` (components) and `global` (menu/ribbon). Keep this list
// narrow: shipping extra keys here bloats the initial i18n request that blocks LCP.
const LANDING_NAMESPACES = ['landing', 'global'];
const isObject = (obj) => obj && typeof obj === 'object';
function deepMerge(target, source) {
if (!isObject(target) || !isObject(source)) {
return source;
}
for (const key in source) {
// prevent prototype pollution; use Object.prototype.hasOwnProperty.call so a JSON-supplied
// "hasOwnProperty" key can't shadow the method and break the check.
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
if (key === '__proto__' || key === 'constructor') continue;
const targetValue = target[key];
const sourceValue = source[key];
if (isObject(sourceValue)) {
target[key] = deepMerge(targetValue || {}, sourceValue);
} else {
target[key] = sourceValue;
}
}
return target;
}
for (const group of groups) {
try {
// create output folder if it doesn't exist
fs.mkdirSync(path.dirname(group.output), { recursive: true });
const files = fs.readdirSync(group.folder).filter((file) => file.endsWith('.json'));
const mergedContent = files.reduce((acc, file) => {
const content = JSON.parse(fs.readFileSync(path.resolve(group.folder, file)).toString());
return deepMerge(acc, content);
}, {});
await fs.promises.writeFile(group.output, JSON.stringify(mergedContent));
// Emit a landing-only slice so the landing route can hydrate i18n in ~10 KB instead of ~600 KB.
const landingContent = LANDING_NAMESPACES.reduce((acc, ns) => {
if (mergedContent[ns] !== undefined) {
acc[ns] = mergedContent[ns];
}
return acc;
}, {});
await fs.promises.writeFile(group.landingOutput, JSON.stringify(landingContent));
} catch (error) {
console.error(`Error merging JSON files for ${group.output}:`, error);
}
}
/*
* The workers of the monaco editor must be bundled separately.
* Specialized workers are available in the vs/esm/language/ directory.
* Be sure to modify the MonacoConfig if you choose to add a worker here.
* For more details, refer to https://github.com/microsoft/monaco-editor/blob/main/samples/browser-esm-esbuild/build.js
*/
const workerEntryPoints = [
'vs/language/json/json.worker.js',
'vs/language/css/css.worker.js',
'vs/language/html/html.worker.js',
'vs/language/typescript/ts.worker.js',
'vs/editor/editor.worker.js',
];
await esbuild.build({
entryPoints: workerEntryPoints.map((entry) => `node_modules/monaco-editor/esm/${entry}`),
bundle: true,
format: 'esm',
outbase: 'node_modules/monaco-editor/esm',
outdir: 'node_modules/monaco-editor/bundles',
});
await new Promise((resolve, reject) => {
const buildScript = `tum-ui:build${developFlag ? ':dev' : ''}`;
const command = process.platform === 'win32' ? 'cmd.exe' : 'pnpm';
const commandArguments = process.platform === 'win32' ? ['/d', '/s', '/c', `pnpm run ${buildScript}`] : ['run', buildScript];
const child = spawn(command, commandArguments, {
cwd: __dirname,
stdio: 'inherit',
});
child.once('error', reject);
child.once('exit', (code, signal) => {
if (code === 0) {
resolve();
return;
}
reject(new Error(`TUM UI package build failed${signal ? ` with signal ${signal}` : ` with exit code ${code}`}.`));
});
});
console.log('Pre-Build complete!');