-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvite.config.js
More file actions
348 lines (333 loc) · 12.6 KB
/
Copy pathvite.config.js
File metadata and controls
348 lines (333 loc) · 12.6 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { execSync } from 'node:child_process';
import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath, URL } from 'node:url';
import vue from '@vitejs/plugin-vue';
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import { viteSingleFile } from 'vite-plugin-singlefile';
import { currentChangelogPlugin } from './build/currentChangelog.js';
import { buildTime } from './build/buildTime.js';
const packageJson = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
const fdnextPackageJson = (() => {
try {
return JSON.parse(readFileSync(new URL('./vendor/fdnext/package.json', import.meta.url), 'utf8'));
} catch {
return { version: 'dev' };
}
})();
const commitHash = (() => {
try {
return execSync('git rev-parse --short HEAD', { encoding: 'utf8' }).trim();
} catch {
return 'dev';
}
})();
const appVersion = `${packageJson.version}+${commitHash}`;
const fdnextCommitHash = (() => {
try {
return execSync('git -C vendor/fdnext rev-parse --short=7 HEAD', { encoding: 'utf8' }).trim();
} catch {
return 'dev';
}
})();
const shortFdnextCommitHash = value => String(value || '').trim().slice(0, 7) || 'dev';
const fdnextBuildCommitHash = shortFdnextCommitHash(process.env.FDNEXT_COMMIT_HASH || fdnextCommitHash);
const fdnextBuildTime = buildTime(process.env.FDNEXT_BUILD_TIME, 'FDNEXT_BUILD_TIME');
const appBuildTime = buildTime(process.env.FLASHMASTER_BUILD_TIME || process.env.VITE_FLASHMASTER_BUILD_TIME, 'FLASHMASTER_BUILD_TIME / VITE_FLASHMASTER_BUILD_TIME');
const sitemapLastmod = appBuildTime.slice(0, 10);
const fdnextVersion = fdnextPackageJson.version;
const pwaDescription = 'Memory Chip Intelligence Platform for memory-chip part-number lookup, NAND Flash ID decoding, database search, and result inspection.';
const googleTagId = 'G-61KFXH5ST6';
const canonicalOrigin = String(process.env.VITE_FLASHMASTER_CANONICAL_ORIGIN || 'https://fm.itxtech.org').replace(/\/+$/, '');
const BUILD_FLAVOR_WEB = 'web';
const BUILD_FLAVOR_SINGLEFILE = 'singlefile';
const BUILD_FLAVOR_SINGLEFILE_NANO = 'singlefile:nano';
const BUILD_FLAVOR_SINGLEFILE_PICO = 'singlefile:pico';
function resolveBuildFlavor(mode) {
const value = String(
process.env.VITE_FLASHMASTER_BUILD_FLAVOR
|| process.env.FLASHMASTER_BUILD_FLAVOR
|| mode
|| ''
).trim().toLowerCase();
if (['singlefile:nano', 'singlefile-nano', 'nano'].includes(value)) {
return BUILD_FLAVOR_SINGLEFILE_NANO;
}
if (['singlefile:pico', 'singlefile-pico', 'pico'].includes(value)) {
return BUILD_FLAVOR_SINGLEFILE_PICO;
}
if (value === BUILD_FLAVOR_SINGLEFILE) {
return BUILD_FLAVOR_SINGLEFILE;
}
return BUILD_FLAVOR_WEB;
}
function isSingleFileFlavor(flavor) {
return [
BUILD_FLAVOR_SINGLEFILE,
BUILD_FLAVOR_SINGLEFILE_NANO,
BUILD_FLAVOR_SINGLEFILE_PICO
].includes(flavor);
}
function optionalBoolean(value) {
const text = String(value ?? '').trim().toLowerCase();
if (!text) return undefined;
if (['1', 'true', 'yes', 'on', 'enabled'].includes(text)) return true;
if (['0', 'false', 'no', 'off', 'disabled'].includes(text)) return false;
return undefined;
}
function singleFileOutputFileName(flavor) {
const suffix = flavor === BUILD_FLAVOR_SINGLEFILE_NANO
? '-nano'
: flavor === BUILD_FLAVOR_SINGLEFILE_PICO
? '-pico'
: '';
return `FlashMaster-${appVersion}${suffix}.html`;
}
function singleFilePagePath(flavor) {
return `/singlefile/${singleFileOutputFileName(flavor)}`;
}
function googleTagHtml({ pagePath } = {}) {
const config = pagePath
? `gtag('config', '${googleTagId}', { page_path: ${JSON.stringify(pagePath)}, page_location: ${JSON.stringify(`${canonicalOrigin}${pagePath}`)} });`
: `gtag('config', '${googleTagId}');`;
return `
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${googleTagId}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
${config}
</script>`;
}
function singleFileHtmlPlugin({ analyticsEnabled, pagePath }) {
return {
name: 'flashmaster-singlefile-html',
enforce: 'pre',
transformIndexHtml(html) {
const googleTagPattern = /\n\s*<!-- Google tag \(gtag\.js\) -->[\s\S]*?gtag\('config', 'G-61KFXH5ST6'\);\s*<\/script>/;
return html
.replace(/\n\s*<link rel="icon"[^>]*>/g, '')
.replace(/\n\s*<link rel="apple-touch-icon"[^>]*>/g, '')
.replace(/\n\s*<link rel="manifest"[^>]*>/g, '')
.replace(googleTagPattern, analyticsEnabled ? googleTagHtml({ pagePath }) : '');
}
};
}
function singleFileCleanupPlugin(flavor) {
let outDir;
const outputFileName = singleFileOutputFileName(flavor);
const preservedHtmlFiles = new Set([
singleFileOutputFileName(BUILD_FLAVOR_SINGLEFILE),
singleFileOutputFileName(BUILD_FLAVOR_SINGLEFILE_NANO),
singleFileOutputFileName(BUILD_FLAVOR_SINGLEFILE_PICO)
]);
return {
name: 'flashmaster-singlefile-cleanup',
apply: 'build',
configResolved(config) {
outDir = resolve(config.root, config.build.outDir);
},
closeBundle() {
if (!outDir || !existsSync(outDir)) return;
for (const entry of readdirSync(outDir, { withFileTypes: true })) {
if (entry.name === 'index.html') continue;
if (preservedHtmlFiles.has(entry.name)) continue;
rmSync(join(outDir, entry.name), { recursive: true, force: true });
}
const indexHtml = join(outDir, 'index.html');
if (existsSync(indexHtml)) {
renameSync(indexHtml, join(outDir, outputFileName));
}
}
};
}
function pwaPlugin(routerMode) {
return VitePWA({
injectRegister: 'auto',
registerType: 'autoUpdate',
manifestFilename: 'site.webmanifest',
includeManifestIcons: false,
manifest: {
name: 'FlashMaster',
short_name: 'FlashMaster',
description: pwaDescription,
start_url: routerMode === 'history' ? './parts' : './#/parts',
scope: './',
display: 'standalone',
background_color: '#07111f',
theme_color: '#0f766e',
icons: [
{
src: 'AppIcon.svg',
sizes: 'any',
type: 'image/svg+xml',
purpose: 'any maskable'
},
{
src: 'AppIcon-192.png',
sizes: '192x192',
type: 'image/png',
purpose: 'any maskable'
},
{
src: 'AppIcon-512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'any maskable'
},
{
src: 'AppIcon.png',
sizes: '152x152',
type: 'image/png',
purpose: 'any'
}
]
},
workbox: {
cleanupOutdatedCaches: true,
clientsClaim: true,
globIgnores: ['**/og/**', 'registerSW.js', '**/fdnextMainEngine-*.js'],
globPatterns: ['**/*.{html,js,css,svg,png,ico}'],
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
navigateFallback: 'index.html',
skipWaiting: true
}
});
}
function sitemapLastmodPlugin(lastmod) {
let outDir;
return {
name: 'flashmaster-sitemap-lastmod',
apply: 'build',
configResolved(config) {
outDir = resolve(config.root, config.build.outDir);
},
closeBundle() {
const sitemapFile = join(outDir, 'sitemap.xml');
if (!existsSync(sitemapFile)) return;
const html = readFileSync(sitemapFile, 'utf8')
.replace(/<lastmod>[^<]*<\/lastmod>/g, `<lastmod>${lastmod}</lastmod>`);
writeFileSync(sitemapFile, html);
}
};
}
export default defineConfig(({ mode }) => {
const buildFlavor = resolveBuildFlavor(mode);
const singleFile = isSingleFileFlavor(buildFlavor);
const pico = buildFlavor === BUILD_FLAVOR_SINGLEFILE_PICO;
const minimalSingleFile = buildFlavor === BUILD_FLAVOR_SINGLEFILE_NANO || pico;
const analyticsEnabled = !minimalSingleFile;
const marketPulseEnabled = !minimalSingleFile;
const commercialBannerEnabled = !minimalSingleFile;
const erExternalLinkEnabled = optionalBoolean(
process.env.VITE_FLASHMASTER_ER_EXTERNAL_LINK
?? process.env.FLASHMASTER_ER_EXTERNAL_LINK
) ?? !minimalSingleFile;
const embeddedParserEnabled = !pico;
const inlineEmbeddedWorker = singleFile && embeddedParserEnabled;
const lockedServer = String(process.env.VITE_FLASHMASTER_LOCKED_SERVER || '').trim();
const routerMode = singleFile || process.env.VITE_FLASHMASTER_ROUTER_MODE !== 'history' ? 'hash' : 'history';
const appBase = process.env.VITE_FLASHMASTER_BASE || (routerMode === 'history' ? '/' : './');
const appSrc = fileURLToPath(new URL('./src', import.meta.url));
const aliases = [
...(singleFile ? [
{
find: '@/composables/usePwaInstall',
replacement: fileURLToPath(new URL('./src/composables/usePwaInstall-noop.js', import.meta.url))
},
...['PwaInstallDialog', 'PwaInstallPrompt'].map(component => ({
find: `@/components/${component}.vue`,
replacement: fileURLToPath(new URL('./src/components/NoopFeature.js', import.meta.url))
}))
] : []),
...(!analyticsEnabled ? [{
find: '@/services/analytics',
replacement: fileURLToPath(new URL('./src/services/analytics-noop.js', import.meta.url))
}] : []),
...(!marketPulseEnabled ? [{
find: '@/components/MarketPulse.vue',
replacement: fileURLToPath(new URL('./src/components/NoopFeature.js', import.meta.url))
}] : []),
...(!commercialBannerEnabled ? [{
find: '@/components/CommercialServiceBanner.vue',
replacement: fileURLToPath(new URL('./src/components/NoopFeature.js', import.meta.url))
}] : []),
...(!erExternalLinkEnabled ? [{
find: '@/services/fdnextResearchLink',
replacement: fileURLToPath(new URL('./src/services/fdnextResearchLink-noop.js', import.meta.url))
}] : []),
...(!embeddedParserEnabled ? [{
find: '@/services/fdnextApi',
replacement: fileURLToPath(new URL('./src/services/fdnextApiHttpOnly.js', import.meta.url))
}] : []),
...(inlineEmbeddedWorker ? [{
find: '@/services/fdnextWorkerFactory',
replacement: fileURLToPath(new URL('./src/services/fdnextWorkerFactoryInline.js', import.meta.url))
}, {
find: '@/services/fdnextMainEngine',
replacement: fileURLToPath(new URL('./src/services/fdnextMainEngineUnavailable.js', import.meta.url))
}] : []),
...(pico ? [
{
find: '@/services/vendorLogos',
replacement: fileURLToPath(new URL('./src/services/vendorLogos-noop.js', import.meta.url))
}
] : []),
{
find: '@',
replacement: appSrc
},
{
find: '@itxtech/fdnext-core',
replacement: fileURLToPath(new URL('./vendor/fdnext/packages/core/src/index.ts', import.meta.url))
}
];
return {
base: appBase,
plugins: [
currentChangelogPlugin(fileURLToPath(new URL('.', import.meta.url)), packageJson.version),
vue(),
...(singleFile ? [
singleFileHtmlPlugin({
analyticsEnabled,
pagePath: singleFilePagePath(buildFlavor)
}),
viteSingleFile({ removeViteModuleLoader: true }),
singleFileCleanupPlugin(buildFlavor)
] : [
pwaPlugin(routerMode)
]),
sitemapLastmodPlugin(sitemapLastmod)
],
build: {
outDir: singleFile ? 'dist-singlefile' : 'dist',
emptyOutDir: !singleFile,
chunkSizeWarningLimit: 3000
},
worker: inlineEmbeddedWorker ? {
// Classic inline workers also load from file:// in Chromium-based browsers.
format: 'iife'
} : undefined,
resolve: {
alias: aliases
},
define: {
VERSION: JSON.stringify(appVersion),
__FDNEXT_VERSION__: JSON.stringify(fdnextVersion),
__FDNEXT_COMMIT_HASH__: JSON.stringify(fdnextBuildCommitHash),
__FDNEXT_BUILD_TIME__: JSON.stringify(fdnextBuildTime),
__FLASHMASTER_BUILD_TIME__: JSON.stringify(appBuildTime),
__FLASHMASTER_SINGLEFILE__: JSON.stringify(singleFile),
__FLASHMASTER_MARKET_PULSE__: JSON.stringify(marketPulseEnabled),
__FLASHMASTER_ANALYTICS__: JSON.stringify(analyticsEnabled),
__FLASHMASTER_COMMERCIAL_BANNER__: JSON.stringify(commercialBannerEnabled),
__FLASHMASTER_ER_EXTERNAL_LINK__: JSON.stringify(erExternalLinkEnabled),
__FLASHMASTER_EMBEDDED_PARSER__: JSON.stringify(embeddedParserEnabled),
__FLASHMASTER_MAIN_THREAD_FALLBACK__: JSON.stringify(embeddedParserEnabled && !inlineEmbeddedWorker),
__FLASHMASTER_LOCKED_SERVER__: JSON.stringify(lockedServer),
__FLASHMASTER_BUILD_FLAVOR__: JSON.stringify(buildFlavor)
}
};
});