mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-08 00:02:20 +03:00
* chore(release): v3.7.9 — gemini-cli cloud code separation * chore(provider): Update Jina AI model catalog (#1874) Integrated into release/v3.7.9 * docs: update CHANGELOG for PR 1874 and retroactive credits * fix: resolve stream defaults and codex prompt mapping (#1873, #1872) * chore(compression): start caveman compression update * feat(compression): expand caveman compression and analytics pipeline Add caveman intensity levels, output mode instructions, validation, and preview diffs across the compression pipeline. Extend MCP and dashboard settings to support auto-trigger mode, system prompt preservation, MCP description compression, and caveman rule metadata. Record richer compression analytics with receipt fields, validation fallbacks, output mode data, and add the related database migration. Improve preservation handling for code, URLs, markdown, math, and other protected content while adding broad unit, integration, and golden-set coverage for caveman parity and compression behavior. * feat(compression): expose rule intensities and track usd savings Add estimated USD savings to compression analytics so saved tokens can be reported in cost terms alongside existing token metrics. Expose caveman rule intensity metadata for settings consumers and add a settings API route alias for rule lookup. Also preserve system prompts when aggressive compression falls back to lite mode. * feat(compression): RTK compression roadmap (#1889) * chore(rtk): initialize compression roadmap branch * feat(compression): add RTK engine and compression combos Introduce RTK command-aware tool-output compression alongside stacked RTK -> Caveman pipelines for mixed prompt contexts. Add engine registration, declarative RTK filter packs, language-aware Caveman rule loading, compression combo persistence and assignments, analytics grouped by engine/combo, and new MCP/API endpoints for configuration, previews, filters, and combo management. Expose the new capabilities in the dashboard with dedicated Context & Cache pages for Caveman, RTK, and compression combos, and update docs, i18n strings, migrations, and tests to cover the expanded compression surface. * feat(compression): expand RTK DSL, filter catalog, and recovery APIs Add RTK parity features across the compression pipeline, dashboard, and management APIs. This expands the built-in filter catalog, adds trust-gated custom filter loading, inline filter verification, code stripping, smarter detection, and optional redacted raw-output retention for authenticated recovery. Also extend Caveman with file-based multilingual rule packs, localized output-mode instructions, stricter preview/config schemas, engine registry metadata, analytics fields, and broad unit test coverage for RTK, rule loading, and stacked compression behavior. * fix(auth): protect oauth routes and health reset operations Require authenticated dashboard access for OAuth endpoints that can create or import provider connections when login enforcement is enabled. Move `/api/monitoring/health` to the readonly public route list so safe methods remain public while DELETE now returns 401 for anonymous requests. Also update Next.js native `.node` handling to avoid webpack parse failures from external packages such as ngrok and keytar, and add coverage for the new auth behavior. * build(compression): ship RTK rule and filter assets with app bundles Include compression JSON assets in Next output tracing, prepublish copies, and pack artifact policy checks so standalone and packaged builds can load RTK filters and caveman rule packs at runtime. Also harden compression runtime behavior by resolving alternate asset directories, scoping rule cache entries by source path, carrying RTK raw output pointers through stacked runs, degrading oversized preview diffs, and applying combo language/output mode defaults during chat routing. Add coverage for packaging rules, provider-scoped model parsing, smart truncate edge cases, raw output retention, and combo-driven compression behavior. * docs(workflows): update local repo paths to OmniRoute Replace outdated `/home/diegosouzapw/dev/proxys/9router` references with the current `OmniRoute` directory across deploy, release, and version bump workflow guides so local command examples match the renamed repository layout * feat(compression): complete RTK parity coverage * test(build): align next config assertions --------- Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com> * feat(compression): expand caveman parity and MCP metadata compression Compress MCP registry and list metadata descriptions for tools, prompts, resources, and resource templates while keeping tool-response bodies unchanged. Expose those savings in compression status as `mcp_metadata_estimate` metadata rather than provider usage. Add Caveman rule-pack support for custom regex flags and match-specific replacement maps, update English rules for upstream parity, and tighten article and pleasantry handling. Also process RTK multipart text blocks independently so mixed media content compresses safely without duplicating output. * feat(compression): unify config validation and persist MCP savings Centralize compression config schemas across settings, preview, RTK, and combo APIs to enforce consistent validation for stacked pipelines and engine-specific options. Expand caveman and stacked compression behavior by applying default combos at runtime, surfacing validation and fallback metadata, and exposing aggressive and ultra adapter schemas for configuration UI and tests. Persist MCP description compression snapshots into analytics without counting them as provider usage, and extend the dashboard with the new RTK controls and localized labels. * fix(auth): require dashboard management auth for compression preview Block preview requests unless they come from a valid management session token so protected settings cannot be probed through the preview API. Add unit coverage for unauthenticated requests, invalid bearer tokens, and successful authenticated preview execution. * fix(compression): preserve stacked defaults and secure metadata routes Only apply saved default compression combos when they contain a stacked pipeline so seeded Caveman-only defaults do not replace the builtin stacked behavior. Also require management auth for compression language pack and rules metadata endpoints, and defer usage receipt attachment until compression analytics writes have completed to keep analytics records consistent. * fix(compression): align seeded standard savings combo with stacked default Update the seeded default compression combo to use the RTK then Caveman pipeline in both fresh installs and upgraded databases. Add a targeted migration and runtime guard that only rewrites the legacy seeded record when its original metadata and single-step pipeline still match, preserving user-customized default combos. Refresh docs and tests to reflect the stacked default and expanded RTK filter catalog. * docs(compression): document RTK+Caveman stacked savings ranges Refresh the compression docs and README to describe the default stacked pipeline in terms of eligible-context savings instead of the older generic token-saving range. Add upstream RTK and Caveman benchmark references, explain the multiplicative savings math behind the stacked default, and update feature summaries plus package metadata to match the revised positioning. * feat(image-gen): add NanoGPT image generation provider (#1899) Integrated into release/v3.7.9 * fix(codex): sanitize raw responses input (#1895) Integrated into release/v3.7.9 * Fix combo provider breaker profile handling (#1891) Integrated into release/v3.7.9 * fix(combos): align strategy contracts (#1892) Integrated into release/v3.7.9 * feat(proxy): move proxy configuration to dedicated System → Proxy page (#1907) Integrated into release/v3.7.9 * feat: add K/M/B/T cost shortener to prevent UI overflow (#1902) Integrated into release/v3.7.9 * feat(providers): implement bulk paste for extra API keys (#1916) Integrated into release/v3.7.9 * fix(migrations): treat duplicate-column ALTER as no-op (#1886) Integrated into release/v3.7.9 * fix(analytics): robust model pricing resolution, dark mode charts and SQL aggregation fixes (#1896) Integrated into release/v3.7.9 (migration renumbered to 044) * fix(oauth): per-connection mutex for rotating refresh tokens (#1885) Integrated into release/v3.7.9 * fix: resolve 3 bugs — Codex tool normalization (#1914), image gen proxy (#1904), zero-arg MCP tools (#1898) - fix(codex): flatten Chat Completions tool format to Responses format in normalizeCodexTools. Prevents 'Missing required parameter: tools[0].name' upstream errors when clients send {type:'function', function:{name,...}} instead of {type:'function', name,...}. - fix(proxy): add proxy-aware execution context to image generation route. Image requests now correctly use proxy settings from the connection's ProxyRegistry assignment, matching the pattern used by chat pipeline. - fix(translator): inject properties:{} into zero-argument MCP tool schemas during Anthropic→OpenAI translation. OpenAI strict mode requires explicit properties even for empty object schemas. Closes #1914, Closes #1904, Closes #1898 * chore(release): v3.7.9 — all changes in ONE commit * fix: allow local ollama provider connections (#1893) * fix(copilot): emit compatible reasoning text deltas (#1919) Integrated into release/v3.7.9 * fix(api-manager): show validation errors inline in modals, not behind backdrop (#1920) Integrated into release/v3.7.9 * docs: update changelog and pr body with merged prs * fix(providers): route agentrouter through anthropic endpoint headers Update the AgentRouter provider registry to use the Claude-compatible messages API and required Anthropic-style authentication headers. This bypasses unauthorized_client_error responses and exposes the supported model list through passthrough configuration. Also update the changelog and release PR notes to document the fix for #1921 * feat(logs): show compression tokens in request log UI (#1923) * docs: add PR #1923 to changelog --------- Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com> Co-authored-by: backryun <bakryun0718@proton.me> Co-authored-by: Aculeasis <42580940+Aculeasis@users.noreply.github.com> Co-authored-by: Raxxoor <manker_lol@hotmail.com> Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: Tubagus <54710482+0xtbug@users.noreply.github.com> Co-authored-by: smartenok-ops <smartenok@gmail.com> Co-authored-by: Gi99lin <74502520+Gi99lin@users.noreply.github.com> Co-authored-by: ivan-mezentsev <ivan@mezentsev.me> Co-authored-by: Andrew Munsell <andrew@wizardapps.net>
559 lines
19 KiB
JavaScript
559 lines
19 KiB
JavaScript
#!/usr/bin/env node
|
||
|
||
/**
|
||
* OmniRoute — Prepublish Build Script
|
||
*
|
||
* Builds the Next.js app in standalone mode and copies output
|
||
* into the `app/` directory that gets published to npm.
|
||
*
|
||
* Run with: node scripts/prepublish.mjs
|
||
*/
|
||
|
||
import { execFileSync } from "node:child_process";
|
||
import {
|
||
existsSync,
|
||
mkdirSync,
|
||
cpSync,
|
||
rmSync,
|
||
writeFileSync,
|
||
readFileSync,
|
||
readdirSync,
|
||
statSync,
|
||
chmodSync,
|
||
} from "node:fs";
|
||
import { join, dirname } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
|
||
import {
|
||
APP_STAGING_ALLOWED_EXACT_PATHS,
|
||
APP_STAGING_ALLOWED_PATH_PREFIXES,
|
||
APP_STAGING_REMOVAL_PATHS,
|
||
findUnexpectedArtifactPaths,
|
||
} from "./pack-artifact-policy.ts";
|
||
|
||
const __filename = fileURLToPath(import.meta.url);
|
||
const __dirname = dirname(__filename);
|
||
const ROOT = join(__dirname, "..");
|
||
const NPM_BIN = process.platform === "win32" ? "npm.cmd" : "npm";
|
||
const NPX_BIN = process.platform === "win32" ? "npx.cmd" : "npx";
|
||
|
||
const APP_DIR = join(ROOT, "app");
|
||
|
||
function walkFiles(dir: string, rootDir: string = dir, files: string[] = []): string[] {
|
||
let entries: string[] = [];
|
||
try {
|
||
entries = readdirSync(dir);
|
||
} catch {
|
||
return files;
|
||
}
|
||
|
||
for (const entry of entries) {
|
||
const fullPath = join(dir, entry);
|
||
let stat;
|
||
try {
|
||
stat = statSync(fullPath);
|
||
} catch {
|
||
continue;
|
||
}
|
||
|
||
if (stat.isDirectory()) {
|
||
walkFiles(fullPath, rootDir, files);
|
||
continue;
|
||
}
|
||
|
||
files.push(
|
||
fullPath
|
||
.replace(rootDir, "")
|
||
.replace(/^[/\\]/, "")
|
||
.replace(/\\/g, "/")
|
||
);
|
||
}
|
||
|
||
return files;
|
||
}
|
||
|
||
function removeEmptyDirectories(dir: string): boolean {
|
||
let entries: string[] = [];
|
||
try {
|
||
entries = readdirSync(dir);
|
||
} catch {
|
||
return false;
|
||
}
|
||
|
||
let hasFiles = false;
|
||
for (const entry of entries) {
|
||
const fullPath = join(dir, entry);
|
||
let stat;
|
||
try {
|
||
stat = statSync(fullPath);
|
||
} catch {
|
||
continue;
|
||
}
|
||
|
||
if (stat.isDirectory()) {
|
||
const childHasFiles = removeEmptyDirectories(fullPath);
|
||
if (!childHasFiles) {
|
||
rmSync(fullPath, { recursive: true, force: true });
|
||
} else {
|
||
hasFiles = true;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
hasFiles = true;
|
||
}
|
||
|
||
return hasFiles;
|
||
}
|
||
|
||
console.log("🔨 OmniRoute — Building for npm publish...\n");
|
||
|
||
// ── Step 1: Clean previous app/ directory ──────────────────
|
||
if (existsSync(APP_DIR)) {
|
||
console.log(" 🧹 Cleaning previous app/ directory...");
|
||
rmSync(APP_DIR, { recursive: true, force: true });
|
||
}
|
||
|
||
// ── Step 2: Install dependencies ───────────────────────────
|
||
console.log(" 📦 Installing dependencies...");
|
||
execFileSync(NPM_BIN, ["install"], { cwd: ROOT, stdio: "inherit" });
|
||
|
||
// ── Step 2.5: Remove app/ directory before build ───────────
|
||
// CRITICAL: The postinstall script may create app/node_modules/@swc/helpers/,
|
||
// which causes Next.js 16 to interpret app/ as an App Router directory
|
||
// (competing with src/app/). This makes the build silently skip all real
|
||
// routes, producing a standalone with only _global-error and _not-found.
|
||
// We MUST remove app/ before running `next build`.
|
||
if (existsSync(APP_DIR)) {
|
||
console.log(" 🧹 Removing app/ created by postinstall (App Router conflict fix)...");
|
||
rmSync(APP_DIR, { recursive: true, force: true });
|
||
}
|
||
|
||
// ── Step 3: Build Next.js ──────────────────────────────────
|
||
console.log(" 🏗️ Building Next.js (standalone)...");
|
||
const nextBuildBundlerFlag =
|
||
process.env.OMNIROUTE_USE_TURBOPACK === "1" ? "--turbopack" : "--webpack";
|
||
execFileSync(NPX_BIN, ["next", "build", nextBuildBundlerFlag], {
|
||
cwd: ROOT,
|
||
stdio: "inherit",
|
||
env: {
|
||
...process.env,
|
||
NEXT_PRIVATE_BUILD_WORKER: "0",
|
||
},
|
||
});
|
||
|
||
// ── Step 4: Verify standalone output ───────────────────────
|
||
const standaloneDir = join(ROOT, ".next", "standalone");
|
||
const serverJs = join(standaloneDir, "server.js");
|
||
|
||
if (!existsSync(serverJs)) {
|
||
console.error("\n ❌ Standalone build not found at:", standaloneDir);
|
||
console.error(" Make sure next.config.mjs has: output: 'standalone'");
|
||
process.exit(1);
|
||
}
|
||
|
||
// ── Step 5: Copy standalone output to app/ ─────────────────
|
||
// ── Step 4.5: Check build for hashed external references ──────────────────────
|
||
// Warn if Turbopack-style hash suffixes are found — they will be resolved at
|
||
// runtime by the externals patch in next.config.mjs, but log for visibility.
|
||
{
|
||
const HASH_RE = /require\(["']([\w@./-]+-[0-9a-f]{16})["']\)/;
|
||
const scanDir = (
|
||
dir: string,
|
||
hits: { file: string; mod: string }[] = []
|
||
): { file: string; mod: string }[] => {
|
||
let entries: string[] = [];
|
||
try {
|
||
entries = readdirSync(dir);
|
||
} catch {
|
||
return hits;
|
||
}
|
||
for (const e of entries) {
|
||
const f = join(dir, e);
|
||
try {
|
||
if (statSync(f).isDirectory()) {
|
||
scanDir(f, hits);
|
||
continue;
|
||
}
|
||
if (!f.endsWith(".js")) continue;
|
||
const m = readFileSync(f, "utf8").match(HASH_RE);
|
||
if (m) hits.push({ file: f.replace(standaloneDir, "app"), mod: m[1] });
|
||
} catch {
|
||
continue;
|
||
}
|
||
}
|
||
return hits;
|
||
};
|
||
const hits = scanDir(join(standaloneDir, ".next", "server"));
|
||
if (hits.length > 0) {
|
||
console.warn(
|
||
" ⚠️ Hashed externals in build (will be auto-fixed at runtime by externals patch):"
|
||
);
|
||
hits.slice(0, 5).forEach((h) => console.warn());
|
||
if (hits.length > 5) console.warn();
|
||
} else {
|
||
console.log(" ✅ Build clean — no hashed externals found.");
|
||
}
|
||
}
|
||
|
||
console.log(" 📋 Copying standalone build to app/...");
|
||
mkdirSync(APP_DIR, { recursive: true });
|
||
cpSync(standaloneDir, APP_DIR, { recursive: true });
|
||
|
||
const standaloneWsSrc = join(ROOT, "scripts", "standalone-server-ws.mjs");
|
||
const responsesWsProxySrc = join(ROOT, "scripts", "responses-ws-proxy.mjs");
|
||
if (existsSync(standaloneWsSrc) && existsSync(responsesWsProxySrc)) {
|
||
console.log(" 📋 Adding Responses WebSocket standalone wrapper...");
|
||
cpSync(standaloneWsSrc, join(APP_DIR, "server-ws.mjs"));
|
||
writeFileSync(
|
||
join(APP_DIR, "responses-ws-proxy.mjs"),
|
||
'export * from "../scripts/responses-ws-proxy.mjs";\n'
|
||
);
|
||
}
|
||
|
||
// ── Next.js Turbopack Standalone Tracer Fix ───────────────
|
||
// Workaround for Next.js 15+ standalone mode missing Turbopack chunks
|
||
const staticChunksSrc = join(ROOT, ".next", "server", "chunks");
|
||
const staticChunksDest = join(APP_DIR, ".next", "server", "chunks");
|
||
if (existsSync(staticChunksSrc)) {
|
||
console.log(" 📋 Patching standalone build with missing Turbopack chunks...");
|
||
cpSync(staticChunksSrc, staticChunksDest, { recursive: true, force: false });
|
||
}
|
||
|
||
// ── Step 5.5: Sanitize hardcoded build-machine paths ───────
|
||
// Next.js standalone bakes absolute build-time paths into server.js and
|
||
// required-server-files.json (outputFileTracingRoot, appDir, turbopack root).
|
||
// Replace the build machine's absolute path with "." (current directory)
|
||
// so paths resolve relative to wherever the standalone app/ is installed.
|
||
console.log(" 🧹 Sanitizing build-machine paths...");
|
||
const buildRoot = ROOT.replace(/\\/g, "/"); // normalise for regex safety
|
||
const sanitizeTargets = [
|
||
join(APP_DIR, "server.js"),
|
||
join(APP_DIR, ".next", "required-server-files.json"),
|
||
];
|
||
let sanitisedCount = 0;
|
||
for (const filePath of sanitizeTargets) {
|
||
if (!existsSync(filePath)) continue;
|
||
let content = readFileSync(filePath, "utf8");
|
||
// Escape special regex characters in the path
|
||
const escaped = buildRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
const re = new RegExp(escaped, "g");
|
||
const matches = content.match(re);
|
||
if (matches) {
|
||
// Replace with "." so Next.js resolves paths relative to the standalone dir
|
||
content = content.replace(re, ".");
|
||
writeFileSync(filePath, content);
|
||
sanitisedCount += matches.length;
|
||
}
|
||
}
|
||
if (sanitisedCount > 0) {
|
||
console.log(` ✅ Sanitised ${sanitisedCount} hardcoded path references`);
|
||
} else {
|
||
console.log(" ℹ️ No hardcoded paths found to sanitise");
|
||
}
|
||
|
||
// ── Step 5.6: Strip Turbopack hashed externals from compiled chunks ─────────
|
||
// Even when Turbopack is disabled at build time, some instrumentation chunks
|
||
// may still emit require('package-<16hexchars>') instead of require('package').
|
||
// These hashed names don't exist in node_modules and cause MODULE_NOT_FOUND at
|
||
// runtime. We strip the hex suffix from all .js files in app/.next/server/
|
||
// to ensure all require() calls use the real package names.
|
||
{
|
||
const serverOutput = join(APP_DIR, ".next", "server");
|
||
const HASH_RE = /(['"\\])([a-z@][a-z0-9@./_-]+?-[0-9a-f]{16}(?:\/[^'"\\]+)?)\1/g;
|
||
let patchedFiles = 0;
|
||
let patchedMatches = 0;
|
||
const walkDir = (dir: string) => {
|
||
let entries: string[] = [];
|
||
try {
|
||
entries = readdirSync(dir);
|
||
} catch {
|
||
return;
|
||
}
|
||
for (const entry of entries) {
|
||
const full = join(dir, entry);
|
||
try {
|
||
const st = statSync(full);
|
||
if (st.isDirectory()) {
|
||
walkDir(full);
|
||
continue;
|
||
}
|
||
if (!entry.endsWith(".js")) continue;
|
||
const src = readFileSync(full, "utf8");
|
||
let count = 0;
|
||
const patched = src.replace(HASH_RE, (_, q, name) => {
|
||
const base = name.replace(/-[0-9a-f]{16}(?=\/|$)/, "");
|
||
count++;
|
||
return `${q}${base}${q}`;
|
||
});
|
||
if (count > 0) {
|
||
writeFileSync(full, patched);
|
||
patchedFiles++;
|
||
patchedMatches += count;
|
||
}
|
||
} catch {
|
||
/* skip unreadable files */
|
||
}
|
||
}
|
||
};
|
||
if (existsSync(serverOutput)) {
|
||
walkDir(serverOutput);
|
||
if (patchedMatches > 0) {
|
||
console.log(
|
||
` 🔧 Hash-strip: patched ${patchedMatches} hashed require() in ${patchedFiles} server chunk file(s)`
|
||
);
|
||
} else {
|
||
console.log(" ✅ Hash-strip: no hashed externals found in compiled chunks.");
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── Step 6: Copy static assets ─────────────────────────────
|
||
const staticSrc = join(ROOT, ".next", "static");
|
||
const staticDest = join(APP_DIR, ".next", "static");
|
||
if (existsSync(staticSrc)) {
|
||
console.log(" 📋 Copying static assets...");
|
||
mkdirSync(staticDest, { recursive: true });
|
||
cpSync(staticSrc, staticDest, { recursive: true });
|
||
}
|
||
|
||
// ── Step 7: Copy public/ assets ────────────────────────────
|
||
const publicSrc = join(ROOT, "public");
|
||
const publicDest = join(APP_DIR, "public");
|
||
if (existsSync(publicSrc)) {
|
||
console.log(" 📋 Copying public/ assets...");
|
||
mkdirSync(publicDest, { recursive: true });
|
||
cpSync(publicSrc, publicDest, { recursive: true });
|
||
}
|
||
|
||
// ── Step 8: Compile + copy MITM cert utilities ─────────────
|
||
const mitmSrc = join(ROOT, "src", "mitm");
|
||
const mitmDest = join(APP_DIR, "src", "mitm");
|
||
if (existsSync(mitmSrc)) {
|
||
console.log(" 🔨 Compiling MITM utilities (TypeScript → JavaScript)...");
|
||
mkdirSync(mitmDest, { recursive: true });
|
||
|
||
// Write a temporary tsconfig.json targeting the mitm directory
|
||
const mitmTsconfig = {
|
||
compilerOptions: {
|
||
target: "ES2022",
|
||
module: "NodeNext",
|
||
moduleResolution: "NodeNext",
|
||
outDir: mitmDest,
|
||
rootDir: mitmSrc,
|
||
strict: false,
|
||
noImplicitAny: false,
|
||
strictNullChecks: false,
|
||
noEmitOnError: true,
|
||
allowImportingTsExtensions: true,
|
||
rewriteRelativeImportExtensions: true,
|
||
ignoreDeprecations: "6.0",
|
||
resolveJsonModule: true,
|
||
esModuleInterop: true,
|
||
skipLibCheck: true,
|
||
types: ["node"],
|
||
baseUrl: ".",
|
||
paths: {
|
||
"@/*": ["src/*"],
|
||
},
|
||
},
|
||
include: [mitmSrc + "/**/*"],
|
||
};
|
||
const tmpTsconfigPath = join(ROOT, "tsconfig.mitm.tmp.json");
|
||
writeFileSync(tmpTsconfigPath, JSON.stringify(mitmTsconfig, null, 2));
|
||
|
||
try {
|
||
execFileSync(NPX_BIN, ["tsc", "-p", "tsconfig.mitm.tmp.json"], {
|
||
cwd: ROOT,
|
||
stdio: "inherit",
|
||
});
|
||
const mitmServerSrc = join(mitmSrc, "server.cjs");
|
||
if (existsSync(mitmServerSrc)) {
|
||
cpSync(mitmServerSrc, join(mitmDest, "server.cjs"));
|
||
}
|
||
console.log(" ✅ MITM utilities compiled to app/src/mitm/");
|
||
} catch (err: any) {
|
||
console.warn(" ⚠️ MITM compile warning (non-fatal):", err.message);
|
||
// Fallback: copy source files so at least they are present
|
||
cpSync(mitmSrc, mitmDest, { recursive: true });
|
||
} finally {
|
||
// Cleanup temp tsconfig
|
||
try {
|
||
rmSync(tmpTsconfigPath);
|
||
} catch {}
|
||
}
|
||
}
|
||
|
||
// ── Step 8.5: Bundle MCP server ────────────────────────────
|
||
const mcpSrcFile = join(ROOT, "open-sse", "mcp-server", "server.ts");
|
||
const mcpDestDir = join(APP_DIR, "open-sse", "mcp-server");
|
||
const mcpDestFile = join(mcpDestDir, "server.js");
|
||
|
||
if (existsSync(mcpSrcFile)) {
|
||
console.log(" 🔨 Bundling MCP Server (TypeScript → JavaScript)...");
|
||
mkdirSync(mcpDestDir, { recursive: true });
|
||
try {
|
||
execFileSync(
|
||
NPX_BIN,
|
||
[
|
||
"esbuild",
|
||
"open-sse/mcp-server/server.ts",
|
||
"--bundle",
|
||
"--platform=node",
|
||
"--packages=external",
|
||
"--format=esm",
|
||
"--outfile=app/open-sse/mcp-server/server.js",
|
||
],
|
||
{ cwd: ROOT, stdio: "inherit" }
|
||
);
|
||
console.log(" ✅ MCP Server bundled to app/open-sse/mcp-server/server.js");
|
||
} catch (err: any) {
|
||
console.warn(" ⚠️ MCP Server bundle error:", err.message);
|
||
}
|
||
}
|
||
|
||
// ── Step 8.7: Bundle CLI Entrypoint ──────────────────────────
|
||
const cliSrcFile = join(ROOT, "bin", "omniroute.ts");
|
||
const cliDestFile = join(ROOT, "bin", "omniroute.mjs");
|
||
|
||
if (existsSync(cliSrcFile)) {
|
||
console.log(" 🔨 Bundling CLI Entrypoint (TypeScript → JavaScript)...");
|
||
try {
|
||
execFileSync(
|
||
NPX_BIN,
|
||
[
|
||
"esbuild",
|
||
"bin/omniroute.ts",
|
||
"--bundle",
|
||
"--platform=node",
|
||
"--packages=external",
|
||
"--format=esm",
|
||
"--outfile=bin/omniroute.mjs",
|
||
],
|
||
{ cwd: ROOT, stdio: "inherit" }
|
||
);
|
||
chmodSync(cliDestFile, 0o755);
|
||
console.log(" ✅ CLI Entrypoint bundled to bin/omniroute.mjs");
|
||
} catch (err: any) {
|
||
console.warn(" ⚠️ CLI bundle error:", err.message);
|
||
}
|
||
}
|
||
|
||
// ── Step 9: Copy shared utilities needed at runtime ────────
|
||
const sharedApiKey = join(ROOT, "src", "shared", "utils", "apiKey.js");
|
||
const sharedApiKeyDest = join(APP_DIR, "src", "shared", "utils");
|
||
if (existsSync(sharedApiKey)) {
|
||
console.log(" 📋 Copying shared utilities...");
|
||
mkdirSync(sharedApiKeyDest, { recursive: true });
|
||
cpSync(sharedApiKey, join(sharedApiKeyDest, "apiKey.js"));
|
||
}
|
||
|
||
// ── Step 9.5: Copy minimal runtime sidecars required outside .next ─────────
|
||
const envExampleSrc = join(ROOT, ".env.example");
|
||
if (existsSync(envExampleSrc)) {
|
||
cpSync(envExampleSrc, join(APP_DIR, ".env.example"));
|
||
}
|
||
|
||
const openapiSpecSrc = join(ROOT, "docs", "openapi.yaml");
|
||
if (existsSync(openapiSpecSrc)) {
|
||
const docsDest = join(APP_DIR, "docs");
|
||
mkdirSync(docsDest, { recursive: true });
|
||
cpSync(openapiSpecSrc, join(docsDest, "openapi.yaml"));
|
||
}
|
||
|
||
const syncEnvSrc = join(ROOT, "scripts", "sync-env.mjs");
|
||
if (existsSync(syncEnvSrc)) {
|
||
const scriptsDest = join(APP_DIR, "scripts");
|
||
mkdirSync(scriptsDest, { recursive: true });
|
||
cpSync(syncEnvSrc, join(scriptsDest, "sync-env.mjs"));
|
||
}
|
||
|
||
const migrationsSrc = join(ROOT, "src", "lib", "db", "migrations");
|
||
if (existsSync(migrationsSrc)) {
|
||
const migrationsDest = join(APP_DIR, "src", "lib", "db", "migrations");
|
||
mkdirSync(join(APP_DIR, "src", "lib", "db"), { recursive: true });
|
||
cpSync(migrationsSrc, migrationsDest, { recursive: true, force: true });
|
||
}
|
||
|
||
const runtimeAssetDirs = [
|
||
{
|
||
source: join(ROOT, "open-sse", "services", "compression", "engines", "rtk", "filters"),
|
||
destination: join(APP_DIR, "open-sse", "services", "compression", "engines", "rtk", "filters"),
|
||
},
|
||
{
|
||
source: join(ROOT, "open-sse", "services", "compression", "rules"),
|
||
destination: join(APP_DIR, "open-sse", "services", "compression", "rules"),
|
||
},
|
||
];
|
||
for (const assetDir of runtimeAssetDirs) {
|
||
if (existsSync(assetDir.source)) {
|
||
mkdirSync(dirname(assetDir.destination), { recursive: true });
|
||
cpSync(assetDir.source, assetDir.destination, { recursive: true, force: true });
|
||
}
|
||
}
|
||
|
||
// ── Step 10: Ensure data/ directory exists ──────────────────
|
||
mkdirSync(join(APP_DIR, "data"), { recursive: true });
|
||
|
||
// ── Step 10.5: Copy @swc/helpers into standalone ───────────
|
||
// Next.js standalone tracer sometimes omits @swc/helpers from app/node_modules/,
|
||
// causing MODULE_NOT_FOUND at runtime. Always copy it explicitly.
|
||
const swcHelpersSrc = join(ROOT, "node_modules", "@swc", "helpers");
|
||
const swcHelpersDst = join(APP_DIR, "node_modules", "@swc", "helpers");
|
||
if (existsSync(swcHelpersSrc) && !existsSync(swcHelpersDst)) {
|
||
console.log(" 📋 Copying @swc/helpers to standalone app/node_modules...");
|
||
mkdirSync(join(APP_DIR, "node_modules", "@swc"), { recursive: true });
|
||
cpSync(swcHelpersSrc, swcHelpersDst, { recursive: true });
|
||
console.log(" ✅ @swc/helpers included in standalone build.");
|
||
}
|
||
|
||
// ── Step 10.6: Remove development-only residue from staged app/ ─────────────
|
||
for (const relativePath of APP_STAGING_REMOVAL_PATHS) {
|
||
const targetPath = join(APP_DIR, relativePath);
|
||
if (existsSync(targetPath)) {
|
||
console.log(` 🧹 Removing app/${relativePath} (not needed in npm package)...`);
|
||
rmSync(targetPath, { recursive: true, force: true });
|
||
console.log(` ✅ app/${relativePath} removed.`);
|
||
}
|
||
}
|
||
|
||
// ── Step 10.7: Prune any staged app/ file outside the allowed runtime set ───
|
||
const stagedFiles = walkFiles(APP_DIR);
|
||
const unexpectedStagedFiles = findUnexpectedArtifactPaths(stagedFiles, {
|
||
exactPaths: APP_STAGING_ALLOWED_EXACT_PATHS,
|
||
prefixPaths: APP_STAGING_ALLOWED_PATH_PREFIXES,
|
||
});
|
||
|
||
if (unexpectedStagedFiles.length > 0) {
|
||
console.log(" 🧹 Pruning unexpected files from staged app/...");
|
||
unexpectedStagedFiles.forEach((unexpectedPath: string) => {
|
||
rmSync(join(APP_DIR, unexpectedPath), { force: true });
|
||
console.log(` ✅ Removed app/${unexpectedPath}`);
|
||
});
|
||
removeEmptyDirectories(APP_DIR);
|
||
}
|
||
|
||
const remainingUnexpectedFiles = findUnexpectedArtifactPaths(walkFiles(APP_DIR), {
|
||
exactPaths: APP_STAGING_ALLOWED_EXACT_PATHS,
|
||
prefixPaths: APP_STAGING_ALLOWED_PATH_PREFIXES,
|
||
});
|
||
|
||
if (remainingUnexpectedFiles.length > 0) {
|
||
console.error("\n ❌ Staged app/ still contains unexpected publish artifacts:");
|
||
remainingUnexpectedFiles.forEach((violation: string) => console.error(` - app/${violation}`));
|
||
process.exit(1);
|
||
}
|
||
|
||
// ── Done ───────────────────────────────────────────────────
|
||
const appPkg = join(APP_DIR, "package.json");
|
||
if (existsSync(appPkg)) {
|
||
const pkg = JSON.parse(readFileSync(appPkg, "utf8"));
|
||
console.log(`\n ✅ Build complete!`);
|
||
console.log(` App directory: app/`);
|
||
console.log(` Server entry: app/server.js`);
|
||
} else {
|
||
console.log(`\n ✅ Build complete! (app/ ready for publish)`);
|
||
}
|
||
|
||
console.log("");
|