-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathvite.config.ts
More file actions
3706 lines (3284 loc) · 131 KB
/
vite.config.ts
File metadata and controls
3706 lines (3284 loc) · 131 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { defineConfig } from 'vite';
import type { Plugin } from 'vite';
import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
import { networkInterfaces, tmpdir } from 'os';
import formidable from 'formidable';
import archiver from 'archiver';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { forceInlineDynamicImportsOff } from './vite-plugins/forceInlineDynamicImportsOff';
import { addAxhubMarker } from './vite-plugins/addAxhubMarker';
import { axhubComponentEnforcer } from './vite-plugins/axhubComponentEnforcer';
import { virtualHtmlPlugin } from './vite-plugins/virtualHtml';
import { websocketPlugin } from './vite-plugins/websocketPlugin';
import { injectStablePageIds } from './vite-plugins/injectStablePageIds';
import { fileSystemApiPlugin } from './vite-plugins/fileSystemApiPlugin';
import { dataManagementApiPlugin } from './vite-plugins/dataManagementApiPlugin';
import { mediaManagementApiPlugin } from './vite-plugins/mediaManagementApiPlugin';
import { codeReviewPlugin } from './vite-plugins/codeReviewPlugin';
import { autoDebugPlugin } from './vite-plugins/autoDebugPlugin';
import { configApiPlugin } from './vite-plugins/configApiPlugin';
import { aiCliPlugin } from './vite-plugins/aiCliPlugin';
import { gitVersionApiPlugin } from './vite-plugins/gitVersionApiPlugin';
import { buildAttachmentContentDisposition } from './vite-plugins/utils/contentDisposition';
import { readEntriesManifest, scanProjectEntries, writeEntriesManifestAtomic } from './vite-plugins/utils/entriesManifest';
const MAKE_STATE_DIR = path.join('.axhub', 'make');
const MAKE_CONFIG_RELATIVE_PATH = path.join(MAKE_STATE_DIR, 'axhub.config.json');
const MAKE_DEV_SERVER_INFO_RELATIVE_PATH = path.join(MAKE_STATE_DIR, '.dev-server-info.json');
const MAKE_ENTRIES_RELATIVE_PATH = path.join(MAKE_STATE_DIR, 'entries.json');
const AXURE_BRIDGE_BASE_URL = 'http://localhost:32767';
/**
* ⚠️ 运行时配置注入说明
*
* serveAdminPlugin 负责在运行时动态注入配置到 admin HTML 文件中。
* 这些配置包括:
* - window.__LOCAL_IP__: 当前机器的局域网 IP
* - window.__LOCAL_PORT__: 实际运行的端口号
* - window.__PROJECT_PREFIX__: 项目路径前缀
* - window.__IS_MIXED_PROJECT__: 是否为混合项目
*
* 🔑 为什么在运行时注入?
* - admin 文件是由 prototype-admin 构建的静态文件
* - 构建时的 IP/端口在运行时可能不同(不同机器、端口被占用等)
* - 必须在每次请求时动态获取并注入正确的配置
*/
// 获取局域网 IP 地址
function getLocalIP(): string {
const interfaces = networkInterfaces();
for (const name of Object.keys(interfaces)) {
const nets = interfaces[name];
if (!nets) continue;
for (const net of nets) {
if (net.family === 'IPv4' && !net.internal) {
return net.address;
}
}
}
return 'localhost';
}
function getRequestPathname(req: any): string {
try {
return new URL(req.url || '/', `http://${req.headers.host}`).pathname;
} catch {
return (req.url || '/').split('?')[0];
}
}
function readJsonBody(req: any): Promise<any> {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (chunk: Buffer) => {
body += chunk.toString('utf8');
});
req.on('end', () => {
if (!body) {
resolve({});
return;
}
try {
resolve(JSON.parse(body));
} catch (error) {
reject(error);
}
});
req.on('error', reject);
});
}
function readErrorString(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
function limitErrorText(value: string, maxLength: number = 500): string {
if (value.length <= maxLength) {
return value;
}
return `${value.slice(0, maxLength)}...`;
}
function serializeErrorForLog(error: any) {
const cause = error?.cause;
const stack = readErrorString(error?.stack);
const causeStack = readErrorString(cause?.stack);
return {
name: readErrorString(error?.name) || undefined,
message: readErrorString(error?.message) || undefined,
code: readErrorString(error?.code) || undefined,
errno: readErrorString(error?.errno) || undefined,
syscall: readErrorString(error?.syscall) || undefined,
address: readErrorString(error?.address) || undefined,
port: typeof error?.port === 'number' ? error.port : undefined,
causeName: readErrorString(cause?.name) || undefined,
causeMessage: readErrorString(cause?.message) || undefined,
causeCode: readErrorString(cause?.code) || undefined,
causeErrno: readErrorString(cause?.errno) || undefined,
causeSyscall: readErrorString(cause?.syscall) || undefined,
causeAddress: readErrorString(cause?.address) || undefined,
causePort: typeof cause?.port === 'number' ? cause.port : undefined,
stack: stack ? limitErrorText(stack, 1200) : undefined,
causeStack: causeStack ? limitErrorText(causeStack, 1200) : undefined,
};
}
function formatAxureProxyErrorDetails(error: any): string {
const parts: string[] = [];
const message = readErrorString(error?.message);
const causeMessage = readErrorString(error?.cause?.message);
const code = readErrorString(error?.code) || readErrorString(error?.cause?.code);
const errno = readErrorString(error?.errno) || readErrorString(error?.cause?.errno);
const syscall = readErrorString(error?.syscall) || readErrorString(error?.cause?.syscall);
const address = readErrorString(error?.address) || readErrorString(error?.cause?.address);
const port =
typeof error?.port === 'number'
? String(error.port)
: typeof error?.cause?.port === 'number'
? String(error.cause.port)
: '';
if (message) {
parts.push(message);
}
if (causeMessage && causeMessage !== message) {
parts.push(`cause=${causeMessage}`);
}
if (code) {
parts.push(`code=${code}`);
}
if (errno && errno !== code) {
parts.push(`errno=${errno}`);
}
if (syscall) {
parts.push(`syscall=${syscall}`);
}
if (address) {
parts.push(`address=${address}`);
}
if (port) {
parts.push(`port=${port}`);
}
return parts.join('; ') || 'Unknown upstream error';
}
function normalizeAxvgPayloadText(rawBody: string): string {
const source = rawBody.trim();
if (!source) {
return '// axvg\n{}';
}
if (source.startsWith('// axvg')) {
return source;
}
return `// axvg\n${source}`;
}
function isLoopbackOrPrivateHostname(hostname: string): boolean {
const normalized = String(hostname || '').trim().toLowerCase();
if (!normalized) {
return true;
}
if (
normalized === 'localhost' ||
normalized === '127.0.0.1' ||
normalized === '0.0.0.0' ||
normalized === '::1' ||
normalized === '[::1]'
) {
return true;
}
if (/^127\./.test(normalized)) {
return true;
}
if (/^10\./.test(normalized)) {
return true;
}
if (/^192\.168\./.test(normalized)) {
return true;
}
if (/^169\.254\./.test(normalized)) {
return true;
}
const match172 = normalized.match(/^172\.(\d{1,3})\./);
if (match172) {
const secondOctet = Number(match172[1]);
if (secondOctet >= 16 && secondOctet <= 31) {
return true;
}
}
return false;
}
function isAllowedProxyImageUrl(rawUrl: string): boolean {
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
return false;
}
if (isLoopbackOrPrivateHostname(parsedUrl.hostname)) {
return false;
}
return true;
}
function exportImageProxyPlugin(): Plugin {
return {
name: 'export-image-proxy-plugin',
configureServer(server: any) {
server.middlewares.use(async (req: any, res: any, next: any) => {
const pathname = getRequestPathname(req);
if (req.method !== 'GET' || pathname !== '/api/export/image-proxy') {
return next();
}
const requestUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const targetUrl = String(requestUrl.searchParams.get('url') || '').trim();
if (!targetUrl) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'Missing url query parameter' }));
return;
}
if (!isAllowedProxyImageUrl(targetUrl)) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'Unsupported proxy target url' }));
return;
}
try {
const upstreamResponse = await fetch(targetUrl, {
method: 'GET',
redirect: 'follow',
headers: {
Accept: 'image/*,*/*;q=0.8',
'User-Agent': 'AxhubMakeExportProxy/1.0',
},
});
if (!upstreamResponse.ok) {
res.statusCode = upstreamResponse.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({
error: `Upstream responded with ${upstreamResponse.status}`,
targetUrl,
}));
return;
}
const contentType = String(upstreamResponse.headers.get('content-type') || '').toLowerCase();
if (contentType && !contentType.startsWith('image/')) {
res.statusCode = 415;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({
error: `Unsupported upstream content-type: ${contentType}`,
targetUrl,
}));
return;
}
const body = Buffer.from(await upstreamResponse.arrayBuffer());
res.statusCode = 200;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cache-Control', upstreamResponse.headers.get('cache-control') || 'public, max-age=600');
res.setHeader('Content-Type', contentType || 'application/octet-stream');
res.setHeader('Content-Length', String(body.byteLength));
const etag = upstreamResponse.headers.get('etag');
if (etag) {
res.setHeader('ETag', etag);
}
const lastModified = upstreamResponse.headers.get('last-modified');
if (lastModified) {
res.setHeader('Last-Modified', lastModified);
}
res.end(body);
} catch (error: any) {
console.error('[export-image-proxy] request failed', {
targetUrl,
error: serializeErrorForLog(error),
});
res.statusCode = 502;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({
error: error?.message || 'Failed to fetch target image',
targetUrl,
}));
}
});
}
};
}
function streamDirectoryAsZip(res: any, sourceDir: string, fileName: string) {
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', buildAttachmentContentDisposition(fileName));
const archive = archiver('zip', { zlib: { level: 9 } });
archive.on('warning', (warning: any) => {
console.warn('[download-dist-plugin] ZIP warning:', warning);
});
archive.on('error', (error: any) => {
console.error('[download-dist-plugin] ZIP error:', error);
if (!res.headersSent) {
res.statusCode = 500;
res.end(JSON.stringify({ error: `Failed to create zip: ${error.message}` }));
return;
}
res.destroy(error);
});
archive.pipe(res);
archive.directory(sourceDir, false);
void archive.finalize();
}
/**
* 局域网访问控制插件
* 根据 allowLAN 配置决定是否允许非本地 IP 访问
*/
function lanAccessControlPlugin(): Plugin {
let allowLAN = true; // 在启动时确定,不再动态读取
return {
name: 'lan-access-control',
configResolved(config: any) {
// 在配置解析时读取 allowLAN 设置
const configPath = path.resolve(__dirname, MAKE_CONFIG_RELATIVE_PATH);
if (fs.existsSync(configPath)) {
try {
const axhubConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
allowLAN = axhubConfig.server?.allowLAN !== false;
console.log(`🔒 局域网访问控制: ${allowLAN ? '允许' : '禁止'}`);
} catch (e) {
// 配置读取失败,使用默认值
}
}
},
configureServer(server: any) {
server.middlewares.use((req: any, res: any, next: any) => {
// 如果允许局域网访问,直接放行
if (allowLAN) {
return next();
}
// 不允许局域网访问,检查请求来源
const clientIP = req.socket.remoteAddress || req.connection.remoteAddress;
// 本地 IP 列表(IPv4 和 IPv6)
const localIPs = [
'127.0.0.1',
'::1',
'::ffff:127.0.0.1',
'localhost'
];
// 检查是否为本地访问
const isLocalAccess = localIPs.some(ip => clientIP?.includes(ip));
if (!isLocalAccess) {
// 非本地访问,返回 403
res.statusCode = 403;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>访问被拒绝</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
background: white;
padding: 40px;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
text-align: center;
max-width: 500px;
}
h1 {
color: #e74c3c;
margin: 0 0 20px 0;
}
p {
color: #666;
line-height: 1.6;
}
.ip {
background: #f5f5f5;
padding: 10px;
border-radius: 5px;
font-family: monospace;
margin: 20px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>🚫 访问被拒绝</h1>
<p>此服务器已禁用局域网访问。</p>
<p>只允许本地访问(localhost/127.0.0.1)。</p>
<div class="ip">您的 IP: ${clientIP}</div>
<p style="font-size: 12px; color: #999;">
如需允许局域网访问,请在配置文件中设置 allowLAN: true 并重启服务器
</p>
</div>
</body>
</html>
`);
return;
}
// 本地访问,放行
next();
});
}
};
}
/**
* 写入开发服务器信息到文件的插件
* 用于 AI 调试时读取服务器配置信息
*/
function writeDevServerInfoPlugin(): Plugin {
return {
name: 'write-dev-server-info',
configureServer(server: any) {
server.httpServer?.once('listening', () => {
try {
const localIP = getLocalIP();
const actualPort = server.httpServer?.address()?.port || server.config.server?.port || 5173;
// 读取用户配置的 host(用于浏览器显示)
const configPath = path.resolve(__dirname, MAKE_CONFIG_RELATIVE_PATH);
let displayHost = 'localhost'; // 默认显示 localhost
if (fs.existsSync(configPath)) {
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
displayHost = config.server?.host || 'localhost';
} catch (e) {
// 配置文件读取失败,使用默认值
}
}
const devServerInfo = {
port: actualPort,
host: displayHost, // 用户配置的显示域名
localIP: localIP,
timestamp: new Date().toISOString()
};
const infoPath = path.resolve(__dirname, MAKE_DEV_SERVER_INFO_RELATIVE_PATH);
fs.mkdirSync(path.dirname(infoPath), { recursive: true });
fs.writeFileSync(infoPath, JSON.stringify(devServerInfo, null, 2), 'utf8');
console.log(`\n✅ Dev server info written to ${MAKE_DEV_SERVER_INFO_RELATIVE_PATH}`);
console.log(` Local: http://${displayHost}:${actualPort}`);
console.log(` Network: http://${localIP}:${actualPort}\n`);
} catch (error) {
console.error('Failed to write dev server info:', error);
}
});
}
};
}
/**
* 服务 admin 目录下的静态文件插件
*
* 🎯 核心职责:
* 1. 服务由 prototype-admin 构建的静态 HTML 文件
* 2. 在运行时动态注入配置(IP、端口、项目路径等)
* 3. 确保每次请求都使用当前机器的正确配置
*
* ⚠️ 重要:不要移除运行时注入逻辑!
* 这些配置必须在运行时动态生成,不能在构建时写死。
*/
function serveAdminPlugin(): Plugin {
// 检测项目结构:判断当前目录是否在 apps/xxx/ 下
const currentDir = __dirname;
const appsMatch = currentDir.match(/[\/\\]apps[\/\\]([^\/\\]+)/);
let projectPrefix = '';
if (appsMatch) {
// 在 apps/xxx/ 结构下,说明是混合项目
// 需要找到包含 .axhub/make/entries.json 的项目目录(通常是主项目)
const rootDir = currentDir.split(/[\/\\]apps[\/\\]/)[0];
const appsDir = path.join(rootDir, 'apps');
if (fs.existsSync(appsDir)) {
const appFolders = fs.readdirSync(appsDir);
for (const folder of appFolders) {
const folderPath = path.join(appsDir, folder);
const entriesPath = path.join(folderPath, MAKE_ENTRIES_RELATIVE_PATH);
if (fs.existsSync(entriesPath)) {
projectPrefix = `apps/${folder}/`;
break;
}
}
}
}
const isMixedProject = !!projectPrefix;
return {
name: 'serve-admin-plugin',
configureServer(server: any) {
server.middlewares.use((req: any, res: any, next: any) => {
const adminDir = path.resolve(__dirname, 'admin');
const pathname = getRequestPathname(req);
// 获取运行时的局域网 IP 和端口
const localIP = getLocalIP();
const actualPort = server.httpServer?.address()?.port || server.config.server?.port || 5173;
// 🔥 运行时动态注入配置脚本
// 注意:这些配置必须在每次请求时动态生成,不能在构建时写死
// 因为不同机器的 IP 不同,端口也可能被占用而改变
const injectScript = `
<script>
// 项目路径配置(根据项目结构自动检测)
window.__PROJECT_PREFIX__ = '${projectPrefix}';
window.__IS_MIXED_PROJECT__ = ${isMixedProject};
// 运行时注入的局域网 IP 信息
window.__LOCAL_IP__ = '${localIP}';
window.__LOCAL_PORT__ = ${actualPort};
</script>`;
// 处理根路径 / 或 /index.html
if (pathname === '/' || pathname === '/index.html') {
const indexPath = path.join(adminDir, 'index.html');
if (fs.existsSync(indexPath)) {
let html = fs.readFileSync(indexPath, 'utf8');
// 注入项目路径配置和局域网 IP
html = html.replace('</head>', `${injectScript}\n</head>`);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(html);
return;
}
}
// 处理 /*.html 请求(如 /projects.html)
if (pathname && pathname.match(/^\/[^/]+\.html$/)) {
const htmlPath = path.join(adminDir, pathname);
if (fs.existsSync(htmlPath)) {
let html = fs.readFileSync(htmlPath, 'utf8');
// 注入项目路径配置和局域网 IP
html = html.replace('</head>', `${injectScript}\n</head>`);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(html);
return;
}
}
// 处理 /assets/* 静态资源
if (pathname && pathname.startsWith('/assets/')) {
const assetPath = path.join(adminDir, pathname);
if (fs.existsSync(assetPath)) {
const ext = path.extname(assetPath);
const contentTypes: Record<string, string> = {
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
res.setHeader('Content-Type', contentTypes[ext] || 'application/octet-stream');
res.end(fs.readFileSync(assetPath));
return;
}
}
// 处理 /images/* 静态资源
if (pathname && pathname.startsWith('/images/')) {
const imagePath = path.join(adminDir, pathname);
if (fs.existsSync(imagePath)) {
const ext = path.extname(imagePath);
const contentTypes: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
res.setHeader('Content-Type', contentTypes[ext] || 'image/png');
res.end(fs.readFileSync(imagePath));
return;
}
}
// 处理 /admin/* 静态资源(如 auto-debug-client.js)
if (pathname && pathname.startsWith('/admin/')) {
const adminFilePath = path.join(adminDir, pathname.replace('/admin/', ''));
if (fs.existsSync(adminFilePath)) {
const ext = path.extname(adminFilePath);
const contentTypes: Record<string, string> = {
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.html': 'text/html; charset=utf-8'
};
res.setHeader('Content-Type', contentTypes[ext] || 'application/octet-stream');
res.end(fs.readFileSync(adminFilePath));
return;
}
}
// 处理根目录下的 .js 文件(如 /auto-debug-client.js)
if (pathname && pathname.match(/^\/[^/]+\.js$/)) {
const jsPath = path.join(adminDir, pathname);
if (fs.existsSync(jsPath)) {
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
res.end(fs.readFileSync(jsPath));
return;
}
}
// 处理 /docs/* 和 /docs/*/spec.html 请求(文档预览)
const encodedDocName = pathname?.match(/^\/docs\/([^/]+)(?:\/spec\.html)?$/)?.[1];
if (encodedDocName) {
const specTemplatePath = path.join(adminDir, 'spec-template.html');
if (fs.existsSync(specTemplatePath)) {
let html = fs.readFileSync(specTemplatePath, 'utf8');
const docName = decodeURIComponent(encodedDocName);
const docFileName = docName.endsWith('.md') ? docName : `${docName}.md`;
const specUrl = `/api/docs/${encodeURIComponent(docFileName)}`;
html = html.replace(/\{\{SPEC_URL\}\}/g, specUrl);
html = html.replace(/\{\{TITLE\}\}/g, docName);
html = html.replace(/\{\{MULTI_DOC\}\}/g, 'false');
html = html.replace(/\{\{DOCS_CONFIG\}\}/g, '[]');
// 注入项目路径配置和局域网 IP
html = html.replace('</head>', `${injectScript}\n</head>`);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(html);
return;
}
}
const encodedTemplateName = pathname?.match(/^\/templates\/([^/]+)(?:\/spec\.html)?$/)?.[1];
if (encodedTemplateName) {
const specTemplatePath = path.join(adminDir, 'spec-template.html');
if (fs.existsSync(specTemplatePath)) {
let html = fs.readFileSync(specTemplatePath, 'utf8');
const templateName = decodeURIComponent(encodedTemplateName);
const templateFileName = templateName.endsWith('.md') ? templateName : `${templateName}.md`;
const specUrl = `/api/templates/${encodeURIComponent(templateFileName)}`;
html = html.replace(/\{\{SPEC_URL\}\}/g, specUrl);
html = html.replace(/\{\{TITLE\}\}/g, templateName);
html = html.replace(/\{\{MULTI_DOC\}\}/g, 'false');
html = html.replace(/\{\{DOCS_CONFIG\}\}/g, '[]');
html = html.replace('</head>', `${injectScript}\n</head>`);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(html);
return;
}
}
next();
});
}
};
}
// 提供 /api/download-dist 端点的插件
function downloadDistPlugin(): Plugin {
return {
name: 'download-dist-plugin',
configureServer(server: any) {
server.middlewares.use((req: any, res: any, next: any) => {
const pathname = getRequestPathname(req);
if (req.method !== 'GET' || pathname !== '/api/download-dist') {
return next();
}
try {
const distDir = path.resolve(__dirname, 'dist');
if (!fs.existsSync(distDir)) {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Dist directory not found' }));
return;
}
// 读取 package.json 获取项目名称
let projectName = 'project';
try {
const pkgPath = path.resolve(__dirname, 'package.json');
if (fs.existsSync(pkgPath)) {
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
projectName = pkg.name || 'project';
}
} catch (e) {
console.warn('Failed to read project name from package.json:', e);
}
streamDirectoryAsZip(res, distDir, `${projectName}-dist.zip`);
} catch (e: any) {
console.error('Download dist error:', e);
if (!res.headersSent) {
res.statusCode = 500;
res.end(JSON.stringify({ error: e.message }));
}
}
});
}
};
}
// 提供 /api/axure-bridge/* 端点的插件(服务端转发到本地 Axure Bridge)
function axureBridgeProxyPlugin(): Plugin {
return {
name: 'axure-bridge-proxy-plugin',
configureServer(server: any) {
server.middlewares.use(async (req: any, res: any, next: any) => {
const pathname = getRequestPathname(req);
const isAvailableRoute = req.method === 'GET' && pathname === '/api/axure-bridge/available';
const isCopyRoute = req.method === 'POST' && pathname === '/api/axure-bridge/copyaxvg';
if (!isAvailableRoute && !isCopyRoute) {
return next();
}
const upstreamUrl = isAvailableRoute
? `${AXURE_BRIDGE_BASE_URL}/available`
: `${AXURE_BRIDGE_BASE_URL}/copyaxvg`;
let payloadBytes = 0;
try {
let upstreamResponse: any;
if (isAvailableRoute) {
upstreamResponse = await fetch(upstreamUrl, {
method: 'GET',
});
} else {
let rawBody = '';
try {
rawBody = await readRequestBody(req);
} catch (error: any) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: error?.message || 'Invalid request body' }));
return;
}
const requestBody = normalizeAxvgPayloadText(rawBody);
const requestBuffer = Buffer.from(requestBody, 'utf8');
payloadBytes = requestBuffer.byteLength;
upstreamResponse = await fetch(upstreamUrl, {
method: 'POST',
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Length': String(payloadBytes),
},
body: requestBuffer,
});
}
const contentType = String(upstreamResponse.headers.get('content-type') || '').toLowerCase();
const responseText = await upstreamResponse.text();
if (!upstreamResponse.ok) {
console.warn('[axure-bridge-proxy] upstream responded with error', {
route: pathname,
method: req.method,
upstreamUrl,
payloadBytes: payloadBytes || undefined,
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
bodyPreview: limitErrorText(readErrorString(responseText), 800) || undefined,
});
}
res.statusCode = upstreamResponse.status;
res.setHeader('Cache-Control', 'no-store');
if (contentType.includes('application/json')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(responseText || '{}');
return;
}
if (responseText) {
try {
const parsed = JSON.parse(responseText);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(parsed));
return;
} catch {
// 非 JSON 文本按原样透传
}
}
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(responseText);
} catch (error: any) {
const errorLog = serializeErrorForLog(error);
console.error('[axure-bridge-proxy] upstream request failed', {
route: pathname,
method: req.method,
upstreamUrl,
payloadBytes: payloadBytes || undefined,
error: errorLog,
});
res.statusCode = 502;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({
error: error?.message || 'Axure Bridge unavailable',
details: formatAxureProxyErrorDetails(error),
code: errorLog.code || errorLog.causeCode || undefined,
causeMessage: errorLog.causeMessage || undefined,
route: pathname,
method: req.method,
bridgeUrl: upstreamUrl,
payloadBytes: payloadBytes || undefined,
}));
}
});
}
};
}
// 提供 /api/version 端点的插件
function versionApiPlugin(): Plugin {
return {
name: 'version-api-plugin',
configureServer(server: any) {
server.middlewares.use((req: any, res: any, next: any) => {
const pathname = getRequestPathname(req);
if (req.method !== 'GET' || pathname !== '/api/version') {
return next();
}
try {
const pkgPath = path.resolve(__dirname, 'package.json');
const pkg = fs.existsSync(pkgPath) ? JSON.parse(fs.readFileSync(pkgPath, 'utf8')) : null;
const version = pkg?.version ?? null;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify({ version }));
} catch (e: any) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: e?.message || 'Unknown error' }));
}
});
}
};
}
function readRequestBody(req: any): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer | string) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
req.on('end', () => {
resolve(Buffer.concat(chunks).toString('utf8'));
});
req.on('error', reject);
});
}
function sanitizeDocBaseName(input: string) {
return input
.trim()
.replace(/\.md$/i, '')
.replace(/[\\/:*?"<>|]/g, '-')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
}
const PROTECTED_TEMPLATE_BASENAMES = new Set([
'spec-template',
]);
function isProtectedTemplateName(templateName: string) {
const normalizedName = String(templateName || '').trim();
if (!normalizedName) return false;
const baseName = path.basename(normalizedName, path.extname(normalizedName));
return PROTECTED_TEMPLATE_BASENAMES.has(baseName);
}
const SPEC_DOC_IMAGE_MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const SPEC_DOC_IMAGE_ALLOWED_EXTENSIONS = new Set([
'.png',
'.jpg',
'.jpeg',
'.gif',
'.webp',
'.svg',
]);
const SPEC_DOC_IMAGE_MIME_TO_EXTENSION: Record<string, string> = {
'image/png': '.png',
'image/jpeg': '.jpg',
'image/gif': '.gif',
'image/webp': '.webp',
'image/svg+xml': '.svg',
};
function safeDecodeURIComponent(input: string): string {
try {
return decodeURIComponent(input);
} catch {
return input;
}
}
function isPathInside(baseDir: string, targetPath: string): boolean {
const relative = path.relative(baseDir, targetPath);
return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}
function resolveDocumentPathFromDocUrl(docUrl: string, host?: string): { docPath: string } | { status: number; error: string } {
let pathname = '';
try {
pathname = new URL(docUrl, `http://${host || 'localhost'}`).pathname;
} catch {
return { status: 400, error: 'Invalid docUrl' };
}
const srcRoot = path.resolve(__dirname, 'src');
const docsRoot = path.resolve(srcRoot, 'docs');
if (pathname.startsWith('/api/docs/')) {
const encodedDocName = pathname.slice('/api/docs/'.length);
if (!encodedDocName) {
return { status: 400, error: 'Missing document name in docUrl' };
}
const decodedDocName = safeDecodeURIComponent(encodedDocName);
const docPath = path.resolve(docsRoot, decodedDocName);
if (!isPathInside(docsRoot, docPath)) {
return { status: 403, error: 'Forbidden path' };