-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvite.config.ts
More file actions
335 lines (289 loc) · 9.24 KB
/
vite.config.ts
File metadata and controls
335 lines (289 loc) · 9.24 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
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "node:path";
import fs from "node:fs";
import type { Plugin } from "vite";
import { fileURLToPath } from "node:url";
interface RouteStub {
slug: string;
title: string;
description: string;
ogTitle: string;
ogDescription: string;
ogImage: string;
}
const ROUTE_STUBS: RouteStub[] = [
{
slug: "mergekeys",
title: "MergeKeys — AmneziaWG Architect",
description:
"Обновите обфускацию AWG-ключа или объедините несколько ключей Amnezia VPN в один.",
ogTitle: "MergeKeys — AmneziaWG Architect",
ogDescription:
"Объединяй ключи Amnezia VPN, обновляй обфускацию — всё локально в браузере.",
ogImage: "og-mergekeys.png",
},
{
slug: "about",
title: "О проекте — AmneziaWG Architect",
description:
"Что такое AmneziaWG Architect? Это интерактивный инструмент для генерации сложных конфигураций обфускации трафика AmneziaWG. Создан для тех, кто хочет вернуть себе свободный интернет.",
ogTitle: "О проекте — AmneziaWG Architect",
ogDescription:
"Твой протокол — твои правила. Разбор архитектуры, безопасности и принципов работы генератора.",
ogImage: "og-about.png",
},
{
slug: "iaa",
title: "IAA — Веб-панель VPN",
description:
"Быстрая адаптивная панель для управления Amnezia VPN и другими VPN-решениями.",
ogTitle: "IAA — Веб-панель VPN",
ogDescription:
"Быстрая адаптивная панель для управления VPN-серверами. Amnezia, WireGuard, XRay.",
ogImage: "og-iaa.png",
},
];
export type HostPlatform = "github" | "gitlab" | "cloudflare" | "generic";
export function detectHostPlatform(): HostPlatform {
const platform = (
process.env.VITE_DEPLOY_PLATFORM ||
process.env.DEPLOY_PLATFORM ||
(process.env.GITHUB_ACTIONS && "github") ||
(process.env.GITLAB_CI && "gitlab") ||
(process.env.CF_PAGES && "cloudflare") ||
"generic"
)
.toString()
.toLowerCase();
if (platform.includes("gitlab")) return "gitlab";
if (platform.includes("cloudflare") || platform.includes("cf"))
return "cloudflare";
if (platform.includes("github")) return "github";
return "generic";
}
export function normalizeBase(input?: string | null): string {
if (!input) return "/";
let base = input.trim();
if (base === "." || base === "./") return "./";
if (base === "/") return "/";
base = base.replace(/\\/g, "/");
if (!base.startsWith("/")) base = `/${base}`;
if (!base.endsWith("/")) base += "/";
return base;
}
export function inferBase(): string {
const explicit =
process.env.VITE_BASE ||
process.env.BASE_URL ||
process.env.ASSET_BASE ||
process.env.PUBLIC_URL;
if (explicit) return normalizeBase(explicit);
const platform = detectHostPlatform();
if (platform === "cloudflare") {
return "/";
}
if (platform === "github") {
const repo = process.env.GITHUB_REPOSITORY;
if (repo) {
const [, name] = repo.split("/");
if (name) {
return `/${name}/`;
}
}
return "/";
}
if (platform === "gitlab") {
const pagesUrl = process.env.CI_PAGES_URL;
if (pagesUrl) {
try {
const urlObj = new URL(pagesUrl);
return normalizeBase(urlObj.pathname);
} catch (e) {}
}
return "/";
}
return "./";
}
export function inferSiteOrigin(): string {
const explicit =
process.env.VITE_SITE_ORIGIN ||
process.env.SITE_ORIGIN ||
process.env.VITE_PUBLIC_SITE_URL ||
process.env.PUBLIC_SITE_URL;
if (explicit) return explicit.replace(/\/+$/, "");
const repo = process.env.GITHUB_REPOSITORY;
if (repo && process.env.GITHUB_ACTIONS) {
const [owner, name] = repo.split("/");
if (owner && name) {
return `https://${owner.toLowerCase()}.github.io/${name}`;
}
}
const gitlabProject = process.env.CI_PROJECT_PATH;
const gitlabUrl = process.env.CI_PAGES_URL || process.env.PAGES_URL;
if (gitlabUrl) return gitlabUrl.replace(/\/+$/, "");
if (gitlabProject && process.env.CI_SERVER_HOST) {
return `https://${process.env.CI_SERVER_HOST}/${gitlabProject}`;
}
const cfUrl =
process.env.CF_PAGES_URL ||
process.env.CLOUDFLARE_PAGES_URL ||
process.env.PAGES_URL;
if (cfUrl) return cfUrl.replace(/\/+$/, "");
return "";
}
export function makeAbsoluteUrl(
siteOrigin: string,
base: string,
assetPath: string,
): string {
const cleanAsset = assetPath.replace(/^\.?\//, "");
if (!siteOrigin) {
return `${base}${cleanAsset}`.replace(/\/{2,}/g, "/").replace(":/", "://");
}
return new URL(
cleanAsset,
siteOrigin.endsWith("/") ? siteOrigin : `${siteOrigin}/`,
).toString();
}
export function buildStubHtml(
template: string,
route: RouteStub,
siteOrigin: string,
base: string,
): string {
const absImage = makeAbsoluteUrl(siteOrigin, base, `assets/${route.ogImage}`);
let html = template;
html = html.replace(/<title>[^<]*<\/title>/, `<title>${route.title}</title>`);
html = html.replace(
/(<meta\s+name="description"\s+content=")[^"]*(")/,
`$1${route.description}$2`,
);
if (html.includes('property="og:title"')) {
html = html.replace(
/(<meta\s+property="og:title"\s+content=")[^"]*(")/,
`$1${route.ogTitle}$2`,
);
}
if (html.includes('property="og:description"')) {
html = html.replace(
/(<meta\s+property="og:description"\s+content=")[^"]*(")/,
`$1${route.ogDescription}$2`,
);
}
if (html.includes('property="og:image"')) {
html = html.replace(
/(<meta\s+property="og:image"\s+content=")[^"]*(")/,
`$1${absImage}$2`,
);
}
if (html.includes('name="robots"')) {
html = html.replace(
/(<meta\s+name="robots"\s+content=")[^"]*(")/,
`$1index,follow$2`,
);
} else {
html = html.replace(
/<\/title>/,
`</title>\n <meta name="robots" content="index,follow" />`,
);
}
return html;
}
function createSpaFallbackPlugin(): Plugin {
return {
name: "amneziawg-architect-spa-fallback",
enforce: "post",
closeBundle() {
const outDir = path.resolve(__dirname, "dist");
const indexPath = path.join(outDir, "index.html");
if (!fs.existsSync(indexPath)) return;
const rawIndex = fs.readFileSync(indexPath, "utf-8");
const base = inferBase();
const siteOrigin = inferSiteOrigin();
const isRelativeBase = base === "./";
const effectiveBase = isRelativeBase ? "/" : base;
for (const route of ROUTE_STUBS) {
const stubDir = path.join(outDir, route.slug);
const stubIndex = path.join(stubDir, "index.html");
fs.mkdirSync(stubDir, { recursive: true });
fs.writeFileSync(
stubIndex,
buildStubHtml(rawIndex, route, siteOrigin, effectiveBase),
"utf-8",
);
}
const cfPages = path.join(outDir, "_redirects");
const fallback404 = path.join(outDir, "404.html");
const gitlabPages = path.join(outDir, "200.html");
const rewriteRules = [
"/* /index.html 200",
"/mergekeys /mergekeys/index.html 200",
"/about /about/index.html 200",
"/iaa /iaa/index.html 200",
].join("\n");
fs.writeFileSync(cfPages, rewriteRules, "utf-8");
fs.writeFileSync(gitlabPages, rawIndex, "utf-8");
// We no longer write a manual HTML 404 because Vue Router handles it via 200/404 rewrites
// or the index fallback. If needed by simple hosts, we point 404 to index
fs.writeFileSync(fallback404, rawIndex, "utf-8");
if (
process.env.GITHUB_ACTIONS ||
process.env.GITLAB_CI ||
process.env.CF_PAGES
) {
console.log(`[spa] base=${base} siteOrigin=${siteOrigin || "(auto)"}`);
}
},
};
}
function createMultiHostBuildPlugin(): Plugin {
return {
name: "amneziawg-architect-multi-host-build",
configResolved(config) {
if (config.base && config.base !== "./" && config.base !== "/") return;
},
};
}
const base = inferBase();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [vue(), createSpaFallbackPlugin(), createMultiHostBuildPlugin()],
base,
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
define: {
__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
build: {
outDir: "dist",
emptyOutDir: true,
minify: "esbuild",
sourcemap: true,
},
server: {
host: "0.0.0.0",
port: 3000,
strictPort: true,
open: true,
},
preview: {
host: "0.0.0.0",
port: 4173,
strictPort: true,
},
});
export const test = {
globals: true,
environment: "node",
include: ["src/**/__tests__/**/*.test.ts"],
coverage: {
provider: "v8",
reporter: ["text", "json-summary", "html"],
include: ["src/utils/**/*.ts"],
exclude: ["src/utils/__tests__/**"],
},
};