|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Dashboard UI Integration Utilities |
| 5 | + * |
| 6 | + * Mirrors `studio.ts` / `account.ts` but for the opinionated, fork-ready |
| 7 | + * console (`@objectstack/dashboard`). The dashboard SPA is mounted at |
| 8 | + * `/_dashboard/` by every deployment that opts in (CLI dev server, |
| 9 | + * self-host, Vercel) — exactly the same convention as `_studio` and |
| 10 | + * `_account`. The dashboard is built with `base: '/_dashboard/'`, so its |
| 11 | + * pre-built `dist/` is served verbatim. |
| 12 | + */ |
| 13 | +import path from 'path'; |
| 14 | +import fs from 'fs'; |
| 15 | +import { createRequire } from 'module'; |
| 16 | +import { pathToFileURL } from 'url'; |
| 17 | + |
| 18 | +// ─── Constants ────────────────────────────────────────────────────── |
| 19 | + |
| 20 | +/** URL mount path for the Dashboard portal inside the ObjectStack server */ |
| 21 | +export const DASHBOARD_PATH = '/_dashboard'; |
| 22 | + |
| 23 | +// ─── Path Resolution ──────────────────────────────────────────────── |
| 24 | + |
| 25 | +/** |
| 26 | + * Resolve the filesystem path to the @objectstack/dashboard package. |
| 27 | + * Searches workspace locations first, then falls back to node_modules. |
| 28 | + */ |
| 29 | +export function resolveDashboardPath(): string | null { |
| 30 | + const cwd = process.cwd(); |
| 31 | + |
| 32 | + // Workspace candidates (monorepo layouts) |
| 33 | + const candidates = [ |
| 34 | + path.resolve(cwd, 'apps/dashboard'), |
| 35 | + path.resolve(cwd, '../../apps/dashboard'), |
| 36 | + path.resolve(cwd, '../apps/dashboard'), |
| 37 | + ]; |
| 38 | + |
| 39 | + for (const candidate of candidates) { |
| 40 | + const pkgPath = path.join(candidate, 'package.json'); |
| 41 | + if (fs.existsSync(pkgPath)) { |
| 42 | + try { |
| 43 | + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); |
| 44 | + if (pkg.name === '@objectstack/dashboard') return candidate; |
| 45 | + } catch { |
| 46 | + // Skip invalid package.json |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // Fallback: resolve from node_modules via createRequire. |
| 52 | + const resolutionBases = [ |
| 53 | + pathToFileURL(path.join(cwd, 'package.json')).href, // consumer workspace |
| 54 | + import.meta.url, // CLI package itself |
| 55 | + ]; |
| 56 | + |
| 57 | + for (const base of resolutionBases) { |
| 58 | + try { |
| 59 | + const req = createRequire(base); |
| 60 | + const resolved = req.resolve('@objectstack/dashboard/package.json'); |
| 61 | + return path.dirname(resolved); |
| 62 | + } catch { |
| 63 | + // Not resolvable from this base — try next |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Last resort: direct filesystem check in cwd/node_modules |
| 68 | + const directPath = path.join(cwd, 'node_modules', '@objectstack', 'dashboard'); |
| 69 | + if (fs.existsSync(path.join(directPath, 'package.json'))) { |
| 70 | + return directPath; |
| 71 | + } |
| 72 | + |
| 73 | + return null; |
| 74 | +} |
| 75 | + |
| 76 | +/** |
| 77 | + * Check whether the Dashboard portal has a pre-built `dist/` directory. |
| 78 | + */ |
| 79 | +export function hasDashboardDist(dashboardPath: string): boolean { |
| 80 | + return fs.existsSync(path.join(dashboardPath, 'dist', 'index.html')); |
| 81 | +} |
| 82 | + |
| 83 | +// ─── Plugin Factory ───────────────────────────────────────────────── |
| 84 | + |
| 85 | +/** |
| 86 | + * Create a lightweight kernel plugin that serves the pre-built Dashboard |
| 87 | + * portal static files at `/_dashboard/*`. |
| 88 | + * |
| 89 | + * Identical SPA-fallback semantics to `createStudioStaticPlugin` and |
| 90 | + * `createAccountStaticPlugin`: |
| 91 | + * - `index.html` is read fresh on every fallback hit (so a rebuild |
| 92 | + * producing new hashed asset names doesn't leave the browser |
| 93 | + * pointing at stale URLs). |
| 94 | + * - Hashed asset paths under `/_dashboard/assets/*` never SPA-fallback — |
| 95 | + * a real 404 surfaces a rebuild/deploy mismatch instead of the |
| 96 | + * dreaded "asset returns text/html" silent failure. |
| 97 | + */ |
| 98 | +export function createDashboardStaticPlugin(distPath: string, options?: { isDev?: boolean }) { |
| 99 | + return { |
| 100 | + name: 'com.objectstack.dashboard-static', |
| 101 | + |
| 102 | + init: async () => {}, |
| 103 | + |
| 104 | + start: async (ctx: any) => { |
| 105 | + const httpServer = ctx.getService?.('http.server'); |
| 106 | + if (!httpServer?.getRawApp) { |
| 107 | + ctx.logger?.warn?.('Dashboard static: http.server service not found — skipping'); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + const app = httpServer.getRawApp(); |
| 112 | + const absoluteDist = path.resolve(distPath); |
| 113 | + |
| 114 | + const indexPath = path.join(absoluteDist, 'index.html'); |
| 115 | + if (!fs.existsSync(indexPath)) { |
| 116 | + ctx.logger?.warn?.(`Dashboard static: dist not found at ${absoluteDist}`); |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + const readIndexHtml = () => fs.readFileSync(indexPath, 'utf-8'); |
| 121 | + |
| 122 | + // Redirect bare path to trailing-slash (SPA convention) |
| 123 | + app.get(DASHBOARD_PATH, (c: any) => c.redirect(`${DASHBOARD_PATH}/`)); |
| 124 | + |
| 125 | + // Serve static files with SPA fallback |
| 126 | + app.get(`${DASHBOARD_PATH}/*`, async (c: any) => { |
| 127 | + const reqPath = c.req.path.substring(DASHBOARD_PATH.length) || '/'; |
| 128 | + const filePath = path.join(absoluteDist, reqPath); |
| 129 | + |
| 130 | + // Security: prevent path traversal |
| 131 | + if (!filePath.startsWith(absoluteDist)) { |
| 132 | + return c.text('Forbidden', 403); |
| 133 | + } |
| 134 | + |
| 135 | + // Try serving the exact file |
| 136 | + if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) { |
| 137 | + const content = fs.readFileSync(filePath); |
| 138 | + return new Response(content, { |
| 139 | + headers: { 'content-type': mimeType(filePath) }, |
| 140 | + }); |
| 141 | + } |
| 142 | + |
| 143 | + // Hashed-asset paths must never SPA-fallback. |
| 144 | + if (reqPath.startsWith('/assets/')) { |
| 145 | + return c.text('Not Found', 404); |
| 146 | + } |
| 147 | + |
| 148 | + // SPA fallback |
| 149 | + return new Response(readIndexHtml(), { |
| 150 | + headers: { 'content-type': 'text/html; charset=utf-8' }, |
| 151 | + }); |
| 152 | + }); |
| 153 | + |
| 154 | + // Suppress unused-parameter lint when isDev isn't needed. |
| 155 | + void options; |
| 156 | + }, |
| 157 | + }; |
| 158 | +} |
| 159 | + |
| 160 | +// ─── Helpers ──────────────────────────────────────────────────────── |
| 161 | + |
| 162 | +const MIME_TYPES: Record<string, string> = { |
| 163 | + '.html': 'text/html; charset=utf-8', |
| 164 | + '.js': 'application/javascript; charset=utf-8', |
| 165 | + '.mjs': 'application/javascript; charset=utf-8', |
| 166 | + '.css': 'text/css; charset=utf-8', |
| 167 | + '.json': 'application/json; charset=utf-8', |
| 168 | + '.svg': 'image/svg+xml', |
| 169 | + '.png': 'image/png', |
| 170 | + '.jpg': 'image/jpeg', |
| 171 | + '.jpeg': 'image/jpeg', |
| 172 | + '.gif': 'image/gif', |
| 173 | + '.ico': 'image/x-icon', |
| 174 | + '.woff': 'font/woff', |
| 175 | + '.woff2': 'font/woff2', |
| 176 | + '.ttf': 'font/ttf', |
| 177 | + '.map': 'application/json', |
| 178 | +}; |
| 179 | + |
| 180 | +function mimeType(filePath: string): string { |
| 181 | + const ext = path.extname(filePath).toLowerCase(); |
| 182 | + return MIME_TYPES[ext] || 'application/octet-stream'; |
| 183 | +} |
0 commit comments