vite.config.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { defineConfig } from 'vite';
  2. import vue from '@vitejs/plugin-vue';
  3. import fs from 'node:fs';
  4. import path from 'node:path';
  5. import { DatabaseSync } from 'node:sqlite';
  6. const outDir = path.resolve(__dirname, '../web/dist');
  7. const BACKEND_TARGET = 'http://localhost:2053';
  8. function resolveDBPath() {
  9. const envFolder = process.env.XUI_DB_FOLDER;
  10. if (envFolder) {
  11. const abs = path.isAbsolute(envFolder)
  12. ? envFolder
  13. : path.resolve(__dirname, '..', envFolder);
  14. return path.join(abs, 'x-ui.db');
  15. }
  16. const repoSubDB = path.resolve(__dirname, '..', 'x-ui', 'x-ui.db');
  17. if (fs.existsSync(repoSubDB)) return repoSubDB;
  18. const repoDB = path.resolve(__dirname, '..', 'x-ui.db');
  19. if (fs.existsSync(repoDB)) return repoDB;
  20. return '/etc/x-ui/x-ui.db';
  21. }
  22. const BASE_MIGRATED_ROUTES = {
  23. 'panel': '/index.html',
  24. 'panel/': '/index.html',
  25. 'panel/settings': '/settings.html',
  26. 'panel/settings/': '/settings.html',
  27. 'panel/inbounds': '/inbounds.html',
  28. 'panel/inbounds/': '/inbounds.html',
  29. 'panel/clients': '/clients.html',
  30. 'panel/clients/': '/clients.html',
  31. 'panel/xray': '/xray.html',
  32. 'panel/xray/': '/xray.html',
  33. 'panel/nodes': '/nodes.html',
  34. 'panel/nodes/': '/nodes.html',
  35. 'panel/api-docs': '/api-docs.html',
  36. 'panel/api-docs/': '/api-docs.html',
  37. };
  38. let cachedBasePath = '/';
  39. function readBasePathFromDB() {
  40. const dbPath = resolveDBPath();
  41. let db;
  42. try {
  43. db = new DatabaseSync(dbPath, { readOnly: true });
  44. } catch (_e) {
  45. return '/';
  46. }
  47. try {
  48. const row = db.prepare('SELECT value FROM settings WHERE key = ?').get('webBasePath');
  49. let value = row && typeof row.value === 'string' ? row.value : '/';
  50. if (!value.startsWith('/')) value = '/' + value;
  51. if (!value.endsWith('/')) value += '/';
  52. return value;
  53. } catch (_e) {
  54. return '/';
  55. } finally {
  56. db.close();
  57. }
  58. }
  59. function refreshBasePath() {
  60. cachedBasePath = readBasePathFromDB();
  61. return cachedBasePath;
  62. }
  63. // `apply: 'serve'` keeps the injection out of `vite build` — dist.go
  64. // already injects webBasePath at runtime in production.
  65. function injectBasePathPlugin() {
  66. return {
  67. name: 'xui-inject-base-path',
  68. apply: 'serve',
  69. transformIndexHtml(html) {
  70. const basePath = refreshBasePath();
  71. const escaped = basePath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  72. const tag = `<script>window.X_UI_BASE_PATH="${escaped}";</script>`;
  73. return html.replace('</head>', `${tag}</head>`);
  74. },
  75. };
  76. }
  77. function bypassMigratedRoute(req) {
  78. if (req.method !== 'GET') return undefined;
  79. const url = req.url.split('?')[0];
  80. const basePath = refreshBasePath();
  81. if (url === basePath) return '/login.html';
  82. if (url.startsWith(basePath)) {
  83. const stripped = url.slice(basePath.length);
  84. if (stripped in BASE_MIGRATED_ROUTES) return BASE_MIGRATED_ROUTES[stripped];
  85. }
  86. return undefined;
  87. }
  88. function rewriteToBackend(p) {
  89. if (cachedBasePath === '/' || p.startsWith(cachedBasePath)) return p;
  90. return cachedBasePath + p.replace(/^\//, '');
  91. }
  92. function makeBackendProxy(target) {
  93. return {
  94. target,
  95. changeOrigin: true,
  96. rewrite: rewriteToBackend,
  97. bypass: bypassMigratedRoute,
  98. configure(proxy) {
  99. let warned = false;
  100. proxy.on('error', (err, req) => {
  101. const codes = new Set();
  102. if (err && err.code) codes.add(err.code);
  103. if (err && Array.isArray(err.errors)) {
  104. for (const inner of err.errors) {
  105. if (inner && inner.code) codes.add(inner.code);
  106. }
  107. }
  108. const offline = codes.has('ECONNREFUSED') || codes.has('ECONNRESET');
  109. if (offline) {
  110. if (!warned) {
  111. warned = true;
  112. // eslint-disable-next-line no-console
  113. console.warn(
  114. `[proxy] backend ${target} is not reachable — start the Go server (e.g. \`go run main.go\`) to forward ${req?.url || 'requests'}.`,
  115. );
  116. }
  117. return;
  118. }
  119. // eslint-disable-next-line no-console
  120. console.error('[proxy]', err);
  121. });
  122. },
  123. };
  124. }
  125. export default defineConfig({
  126. plugins: [vue(), injectBasePathPlugin()],
  127. resolve: {
  128. alias: {
  129. '@': path.resolve(__dirname, 'src'),
  130. },
  131. },
  132. build: {
  133. outDir,
  134. emptyOutDir: true,
  135. sourcemap: true,
  136. target: 'es2020',
  137. chunkSizeWarningLimit: 1500,
  138. rollupOptions: {
  139. input: {
  140. index: path.resolve(__dirname, 'index.html'),
  141. login: path.resolve(__dirname, 'login.html'),
  142. settings: path.resolve(__dirname, 'settings.html'),
  143. inbounds: path.resolve(__dirname, 'inbounds.html'),
  144. clients: path.resolve(__dirname, 'clients.html'),
  145. xray: path.resolve(__dirname, 'xray.html'),
  146. nodes: path.resolve(__dirname, 'nodes.html'),
  147. apiDocs: path.resolve(__dirname, 'api-docs.html'),
  148. subpage: path.resolve(__dirname, 'subpage.html'),
  149. },
  150. output: {
  151. manualChunks(id) {
  152. if (!id.includes('node_modules')) return undefined;
  153. if (id.includes('ant-design-vue')) return 'vendor-antd';
  154. if (id.includes('@ant-design/icons-vue')) return 'vendor-icons';
  155. if (id.includes('vue-i18n')) return 'vendor-i18n';
  156. if (
  157. id.includes('/node_modules/vue/')
  158. || id.includes('/node_modules/@vue/')
  159. ) return 'vendor-vue';
  160. if (id.includes('dayjs')) return 'vendor-dayjs';
  161. if (id.includes('axios')) return 'vendor-axios';
  162. if (
  163. id.includes('vue3-persian-datetime-picker')
  164. || id.includes('moment-jalaali')
  165. || id.includes('jalaali-js')
  166. || id.includes('/node_modules/moment/')
  167. ) return 'vendor-jalali';
  168. return 'vendor';
  169. },
  170. },
  171. },
  172. },
  173. server: {
  174. port: 5173,
  175. strictPort: true,
  176. proxy: {
  177. '^/(?:[^/]+/)?(login|logout|getTwoFactorEnable|csrf-token|panel|server)(?:/|$)': makeBackendProxy(BACKEND_TARGET),
  178. '^/$': makeBackendProxy(BACKEND_TARGET),
  179. '^/[^/]+/$': makeBackendProxy(BACKEND_TARGET),
  180. '^/(?:[^/]+/)?ws$': {
  181. target: 'ws://localhost:2053',
  182. ws: true,
  183. changeOrigin: true,
  184. rewrite: rewriteToBackend,
  185. },
  186. },
  187. },
  188. });