Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/utils/build/assetCdnBase.ts
T

33 lines
1.3 KiB
TypeScript

// Resolve the Vite `base` value from the ASSET_CDN_URL env variable.
//
// Kept in its own module (no React Router / Vite plugin imports) so the
// pure logic can be unit-tested under vitest without booting the full
// `apps/web/vite.config.ts` plugin graph.
//
// Behaviour:
// * Dev mode (`mode === "development"`): always returns `/` so the Vite
// dev server and HMR keep serving from the origin.
// * Production / build mode: when `ASSET_CDN_URL` is set to a valid URL,
// returns the origin with a trailing slash (e.g. `https://cdn.example.com/`).
// Vite then prefixes every emitted asset URL with that origin.
// * Empty / whitespace / malformed values fall back to `/` so a
// misconfigured deploy never breaks the build outright. The env-drift
// checks in CI are the right place to fail loudly on bad URLs.
//
// See: docs/improvement-plan/03-scaling-infrastructure/asset-cdn.md
// docs/ops/asset-cdn.md
export function resolveAssetBase(
env: Partial<Record<string, string | undefined>> = process.env,
mode: string | undefined = undefined
): string {
if (mode === "development") return "/";
const raw = env.ASSET_CDN_URL?.trim();
if (!raw) return "/";
try {
const url = new URL(raw);
return `${url.origin}/`;
} catch {
return "/";
}
}