|
| 1 | +import fs from "node:fs"; |
| 2 | +import path from "node:path"; |
| 3 | +import { createRequire } from "node:module"; |
| 4 | +import { fileURLToPath } from "node:url"; |
| 5 | + |
| 6 | +interface PackageJson { |
| 7 | + dependencies?: Record<string, string>; |
| 8 | + devDependencies?: Record<string, string>; |
| 9 | + optionalDependencies?: Record<string, string>; |
| 10 | +} |
| 11 | + |
| 12 | +export interface StandaloneBuildOptions { |
| 13 | + root: string; |
| 14 | + outDir: string; |
| 15 | + /** |
| 16 | + * Test hook: override vinext package root used for embedding runtime files. |
| 17 | + */ |
| 18 | + vinextPackageRoot?: string; |
| 19 | +} |
| 20 | + |
| 21 | +export interface StandaloneBuildResult { |
| 22 | + standaloneDir: string; |
| 23 | + copiedPackages: string[]; |
| 24 | +} |
| 25 | + |
| 26 | +interface QueueEntry { |
| 27 | + packageName: string; |
| 28 | + resolver: NodeRequire; |
| 29 | +} |
| 30 | + |
| 31 | +function readPackageJson(packageJsonPath: string): PackageJson { |
| 32 | + return JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as PackageJson; |
| 33 | +} |
| 34 | + |
| 35 | +function runtimeDeps(pkg: PackageJson): string[] { |
| 36 | + return Object.keys({ |
| 37 | + ...pkg.dependencies, |
| 38 | + ...pkg.optionalDependencies, |
| 39 | + }); |
| 40 | +} |
| 41 | + |
| 42 | +function walkFiles(dir: string): string[] { |
| 43 | + const files: string[] = []; |
| 44 | + const entries = fs.readdirSync(dir, { withFileTypes: true }); |
| 45 | + for (const entry of entries) { |
| 46 | + const fullPath = path.join(dir, entry.name); |
| 47 | + if (entry.isDirectory()) { |
| 48 | + files.push(...walkFiles(fullPath)); |
| 49 | + } else { |
| 50 | + files.push(fullPath); |
| 51 | + } |
| 52 | + } |
| 53 | + return files; |
| 54 | +} |
| 55 | + |
| 56 | +function packageNameFromSpecifier(specifier: string): string | null { |
| 57 | + if ( |
| 58 | + specifier.startsWith(".") || |
| 59 | + specifier.startsWith("/") || |
| 60 | + specifier.startsWith("node:") || |
| 61 | + specifier.startsWith("#") |
| 62 | + ) { |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + if (specifier.startsWith("@")) { |
| 67 | + const parts = specifier.split("/"); |
| 68 | + if (parts.length >= 2) { |
| 69 | + return `${parts[0]}/${parts[1]}`; |
| 70 | + } |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + return specifier.split("/")[0] || null; |
| 75 | +} |
| 76 | + |
| 77 | +function collectServerExternalPackages(serverDir: string): string[] { |
| 78 | + const packages = new Set<string>(); |
| 79 | + const files = walkFiles(serverDir).filter((filePath) => /\.(c|m)?js$/.test(filePath)); |
| 80 | + |
| 81 | + const importExportRE = /(?:import|export)\s+(?:[^"'()]*?\s+from\s+)?["']([^"']+)["']/g; |
| 82 | + const dynamicImportRE = /import\(\s*["']([^"']+)["']\s*\)/g; |
| 83 | + const requireRE = /require\(\s*["']([^"']+)["']\s*\)/g; |
| 84 | + |
| 85 | + for (const filePath of files) { |
| 86 | + const code = fs.readFileSync(filePath, "utf-8"); |
| 87 | + |
| 88 | + for (const regex of [importExportRE, dynamicImportRE, requireRE]) { |
| 89 | + regex.lastIndex = 0; |
| 90 | + let match: RegExpExecArray | null; |
| 91 | + while ((match = regex.exec(code)) !== null) { |
| 92 | + const packageName = packageNameFromSpecifier(match[1]); |
| 93 | + if (packageName) { |
| 94 | + packages.add(packageName); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return [...packages]; |
| 101 | +} |
| 102 | + |
| 103 | +function copyPackageAndRuntimeDeps( |
| 104 | + root: string, |
| 105 | + targetNodeModulesDir: string, |
| 106 | + initialPackages: string[], |
| 107 | +): string[] { |
| 108 | + const rootResolver = createRequire(path.join(root, "package.json")); |
| 109 | + const copied = new Set<string>(); |
| 110 | + const queue: QueueEntry[] = initialPackages.map((packageName) => ({ |
| 111 | + packageName, |
| 112 | + resolver: rootResolver, |
| 113 | + })); |
| 114 | + |
| 115 | + while (queue.length > 0) { |
| 116 | + const entry = queue.shift(); |
| 117 | + if (!entry) continue; |
| 118 | + if (copied.has(entry.packageName)) continue; |
| 119 | + |
| 120 | + let packageJsonPath: string; |
| 121 | + try { |
| 122 | + packageJsonPath = entry.resolver.resolve(`${entry.packageName}/package.json`); |
| 123 | + } catch { |
| 124 | + continue; |
| 125 | + } |
| 126 | + |
| 127 | + const packageRoot = path.dirname(packageJsonPath); |
| 128 | + const packageTarget = path.join(targetNodeModulesDir, entry.packageName); |
| 129 | + fs.mkdirSync(path.dirname(packageTarget), { recursive: true }); |
| 130 | + fs.cpSync(packageRoot, packageTarget, { recursive: true, dereference: true }); |
| 131 | + |
| 132 | + copied.add(entry.packageName); |
| 133 | + |
| 134 | + const packageResolver = createRequire(packageJsonPath); |
| 135 | + const pkg = readPackageJson(packageJsonPath); |
| 136 | + for (const depName of runtimeDeps(pkg)) { |
| 137 | + if (!copied.has(depName)) { |
| 138 | + queue.push({ packageName: depName, resolver: packageResolver }); |
| 139 | + } |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + return [...copied]; |
| 144 | +} |
| 145 | + |
| 146 | +function resolveVinextPackageRoot(explicitRoot?: string): string { |
| 147 | + if (explicitRoot) { |
| 148 | + return path.resolve(explicitRoot); |
| 149 | + } |
| 150 | + |
| 151 | + const currentDir = path.dirname(fileURLToPath(import.meta.url)); |
| 152 | + // dist/build/standalone.js -> package root is ../.. |
| 153 | + return path.resolve(currentDir, "..", ".."); |
| 154 | +} |
| 155 | + |
| 156 | +function writeStandaloneServerEntry(filePath: string): void { |
| 157 | + const content = `#!/usr/bin/env node |
| 158 | +const path = require("node:path"); |
| 159 | +
|
| 160 | +async function main() { |
| 161 | + const { startProdServer } = await import("vinext/server/prod-server"); |
| 162 | + const port = Number.parseInt(process.env.PORT ?? "3000", 10); |
| 163 | + const host = process.env.HOSTNAME ?? "0.0.0.0"; |
| 164 | +
|
| 165 | + await startProdServer({ |
| 166 | + port, |
| 167 | + host, |
| 168 | + outDir: path.join(__dirname, "dist"), |
| 169 | + }); |
| 170 | +} |
| 171 | +
|
| 172 | +main().catch((error) => { |
| 173 | + console.error("[vinext] Failed to start standalone server"); |
| 174 | + console.error(error); |
| 175 | + process.exit(1); |
| 176 | +}); |
| 177 | +`; |
| 178 | + fs.writeFileSync(filePath, content, "utf-8"); |
| 179 | + fs.chmodSync(filePath, 0o755); |
| 180 | +} |
| 181 | + |
| 182 | +/** |
| 183 | + * Emit standalone production output for self-hosted deployments. |
| 184 | + * |
| 185 | + * Creates: |
| 186 | + * - <outDir>/standalone/server.js |
| 187 | + * - <outDir>/standalone/dist/{client,server} |
| 188 | + * - <outDir>/standalone/node_modules (runtime deps only) |
| 189 | + */ |
| 190 | +export function emitStandaloneOutput(options: StandaloneBuildOptions): StandaloneBuildResult { |
| 191 | + const root = path.resolve(options.root); |
| 192 | + const outDir = path.resolve(options.outDir); |
| 193 | + const clientDir = path.join(outDir, "client"); |
| 194 | + const serverDir = path.join(outDir, "server"); |
| 195 | + |
| 196 | + if (!fs.existsSync(clientDir) || !fs.existsSync(serverDir)) { |
| 197 | + throw new Error(`No build output found in ${outDir}. Run vinext build first.`); |
| 198 | + } |
| 199 | + |
| 200 | + const standaloneDir = path.join(outDir, "standalone"); |
| 201 | + const standaloneDistDir = path.join(standaloneDir, "dist"); |
| 202 | + const standaloneNodeModulesDir = path.join(standaloneDir, "node_modules"); |
| 203 | + |
| 204 | + fs.rmSync(standaloneDir, { recursive: true, force: true }); |
| 205 | + fs.mkdirSync(standaloneDistDir, { recursive: true }); |
| 206 | + |
| 207 | + fs.cpSync(clientDir, path.join(standaloneDistDir, "client"), { |
| 208 | + recursive: true, |
| 209 | + dereference: true, |
| 210 | + }); |
| 211 | + fs.cpSync(serverDir, path.join(standaloneDistDir, "server"), { |
| 212 | + recursive: true, |
| 213 | + dereference: true, |
| 214 | + }); |
| 215 | + |
| 216 | + const publicDir = path.join(root, "public"); |
| 217 | + if (fs.existsSync(publicDir)) { |
| 218 | + fs.cpSync(publicDir, path.join(standaloneDir, "public"), { |
| 219 | + recursive: true, |
| 220 | + dereference: true, |
| 221 | + }); |
| 222 | + } |
| 223 | + |
| 224 | + fs.mkdirSync(standaloneNodeModulesDir, { recursive: true }); |
| 225 | + |
| 226 | + const appPkg = readPackageJson(path.join(root, "package.json")); |
| 227 | + const appRuntimeDeps = runtimeDeps(appPkg); |
| 228 | + const serverRuntimeDeps = collectServerExternalPackages(serverDir); |
| 229 | + const initialPackages = [...new Set([...appRuntimeDeps, ...serverRuntimeDeps])].filter( |
| 230 | + (name) => name !== "vinext", |
| 231 | + ); |
| 232 | + const copiedPackages = copyPackageAndRuntimeDeps( |
| 233 | + root, |
| 234 | + standaloneNodeModulesDir, |
| 235 | + initialPackages, |
| 236 | + ); |
| 237 | + |
| 238 | + // Always embed the exact vinext runtime that produced this build. |
| 239 | + const vinextPackageRoot = resolveVinextPackageRoot(options.vinextPackageRoot); |
| 240 | + const vinextDistDir = path.join(vinextPackageRoot, "dist"); |
| 241 | + if (!fs.existsSync(vinextDistDir)) { |
| 242 | + throw new Error(`vinext runtime dist/ not found at ${vinextPackageRoot}`); |
| 243 | + } |
| 244 | + const vinextTargetDir = path.join(standaloneNodeModulesDir, "vinext"); |
| 245 | + fs.mkdirSync(vinextTargetDir, { recursive: true }); |
| 246 | + fs.copyFileSync( |
| 247 | + path.join(vinextPackageRoot, "package.json"), |
| 248 | + path.join(vinextTargetDir, "package.json"), |
| 249 | + ); |
| 250 | + fs.cpSync(vinextDistDir, path.join(vinextTargetDir, "dist"), { |
| 251 | + recursive: true, |
| 252 | + dereference: true, |
| 253 | + }); |
| 254 | + |
| 255 | + writeStandaloneServerEntry(path.join(standaloneDir, "server.js")); |
| 256 | + |
| 257 | + return { |
| 258 | + standaloneDir, |
| 259 | + copiedPackages: [...new Set([...copiedPackages, "vinext"])], |
| 260 | + }; |
| 261 | +} |
0 commit comments