Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15ff27cf41 | ||
|
|
acd101863b | ||
|
|
8476526dd7 | ||
|
|
ffcba26e64 | ||
|
|
f80834c6ab |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
.git
|
||||
.pnpm-store
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/coverage
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.DS_Store
|
||||
*.log
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM node:26-slim AS pnpm-base
|
||||
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH="${PNPM_HOME}:${PATH}"
|
||||
|
||||
RUN npm install --global pnpm@10.33.0
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
FROM pnpm-base AS deps
|
||||
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
COPY tsconfig.base.json ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
|
||||
RUN pnpm install --frozen-lockfile --filter api...
|
||||
|
||||
FROM deps AS build
|
||||
|
||||
COPY apps/api apps/api
|
||||
COPY packages/shared packages/shared
|
||||
|
||||
RUN pnpm -r --sort --filter api... run build
|
||||
|
||||
FROM pnpm-base AS prod-deps
|
||||
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
COPY packages/shared/package.json packages/shared/package.json
|
||||
|
||||
RUN pnpm install --prod --frozen-lockfile --filter api...
|
||||
|
||||
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=prod
|
||||
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/packages/shared/package.json ./packages/shared/package.json
|
||||
COPY --from=build --chown=nonroot:nonroot /app/packages/shared/dist ./packages/shared/dist
|
||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||
COPY --chown=nonroot:nonroot ./project.yaml /project.yaml
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["apps/api/dist/main.js"]
|
||||
@@ -29,7 +29,8 @@ describe('bootstrap', () => {
|
||||
const mockListen = jest
|
||||
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
|
||||
.mockResolvedValue(undefined);
|
||||
const mockApp = { listen: mockListen };
|
||||
const mockEnableCors = jest.fn();
|
||||
const mockApp = { enableCors: mockEnableCors, listen: mockListen };
|
||||
const mockedNestFactory = NestFactory as unknown as {
|
||||
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
|
||||
};
|
||||
@@ -37,6 +38,11 @@ describe('bootstrap', () => {
|
||||
|
||||
await bootstrap();
|
||||
|
||||
expect(mockEnableCors).toHaveBeenCalledWith({
|
||||
origin: expect.any(Function),
|
||||
credentials: true,
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
});
|
||||
expect(configureApp).toHaveBeenCalledWith(mockApp);
|
||||
expect(mockListen).toHaveBeenCalledWith('3123');
|
||||
});
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { configureApp } from './app.setup';
|
||||
import { createCorsOrigin } from './cors-origin';
|
||||
|
||||
export async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const nodeEnv = process.env.NODE_ENV;
|
||||
app.enableCors({
|
||||
origin: createCorsOrigin(nodeEnv),
|
||||
credentials: true,
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
});
|
||||
configureApp(app);
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createCorsOrigin,
|
||||
isAllowedCorsOrigin,
|
||||
resolveWebOrigins,
|
||||
} from './cors-origin';
|
||||
|
||||
describe('CORS origin resolution', () => {
|
||||
it('allows Cloudflare Pages preview origins in dev and staging', () => {
|
||||
const origin = 'https://807e0ea6.persona-lenz.pages.dev';
|
||||
|
||||
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
|
||||
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not allow Cloudflare Pages preview origins in prod', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://807e0ea6.persona-lenz.pages.dev', 'prod'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects similar but unsafe Pages origins', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('http://807e0ea6.persona-lenz.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://persona-lenz.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://a.b.persona-lenz.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isAllowedCorsOrigin(
|
||||
'https://807e0ea6.persona-lenz.pages.dev.evil.com',
|
||||
'staging',
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'staging'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps configured web origins allowed', () => {
|
||||
expect(
|
||||
isAllowedCorsOrigin('https://example.com', 'prod', [
|
||||
'https://example.com',
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
|
||||
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
|
||||
});
|
||||
|
||||
it('creates a Nest CORS callback from the same rules', (done) => {
|
||||
const corsOrigin = createCorsOrigin('staging');
|
||||
|
||||
expect(corsOrigin).not.toBe(true);
|
||||
if (corsOrigin === true) return;
|
||||
|
||||
corsOrigin('https://807e0ea6.persona-lenz.pages.dev', (error, allow) => {
|
||||
expect(error).toBeNull();
|
||||
expect(allow).toBe(true);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps dev CORS permissive for local development', () => {
|
||||
expect(createCorsOrigin('dev')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
|
||||
|
||||
const DEFAULT_WEB_ORIGINS = [
|
||||
'http://localhost:5173',
|
||||
'http://126.dahyeon.us:5173',
|
||||
'https://persona-lenz.dahyeon.us',
|
||||
];
|
||||
|
||||
const PAGES_DEV_ORIGIN_HOST_PATTERN =
|
||||
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.persona-lenz\.pages\.dev$/i;
|
||||
|
||||
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
|
||||
|
||||
function parseOrigin(origin: string, allowPath: boolean): URL | null {
|
||||
const trimmedOrigin = origin.trim();
|
||||
if (trimmedOrigin.length === 0) return null;
|
||||
|
||||
try {
|
||||
const url = new URL(trimmedOrigin);
|
||||
if (
|
||||
!allowPath &&
|
||||
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeOrigin(origin: string, allowPath = false): string | null {
|
||||
const url = parseOrigin(origin, allowPath);
|
||||
if (!url) return null;
|
||||
|
||||
return `${url.protocol}//${url.host}`;
|
||||
}
|
||||
|
||||
export function resolveWebOrigins(
|
||||
webOrigin = process.env.WEB_ORIGIN,
|
||||
): string[] {
|
||||
const configuredOrigins = webOrigin
|
||||
?.split(',')
|
||||
.map((origin) => normalizeOrigin(origin, true))
|
||||
.filter((origin): origin is string => origin !== null);
|
||||
|
||||
if (configuredOrigins && configuredOrigins.length > 0) {
|
||||
return configuredOrigins;
|
||||
}
|
||||
|
||||
return [...DEFAULT_WEB_ORIGINS];
|
||||
}
|
||||
|
||||
export function isPersonaLenzPagesDevOrigin(origin: string): boolean {
|
||||
const url = parseOrigin(origin, false);
|
||||
if (!url) return false;
|
||||
|
||||
return (
|
||||
url.protocol === 'https:' &&
|
||||
url.port === '' &&
|
||||
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
|
||||
);
|
||||
}
|
||||
|
||||
export function isAllowedCorsOrigin(
|
||||
requestOrigin: string | undefined,
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
webOrigins = resolveWebOrigins(),
|
||||
): boolean {
|
||||
if (!requestOrigin) return false;
|
||||
|
||||
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
|
||||
if (!normalizedRequestOrigin) return false;
|
||||
|
||||
const normalizedWebOrigins = webOrigins
|
||||
.map((origin) => normalizeOrigin(origin, true))
|
||||
.filter((origin): origin is string => origin !== null);
|
||||
|
||||
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
|
||||
isPersonaLenzPagesDevOrigin(requestOrigin)
|
||||
);
|
||||
}
|
||||
|
||||
export function createCorsOrigin(
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
webOrigin = process.env.WEB_ORIGIN,
|
||||
): true | CustomOrigin {
|
||||
if (nodeEnv === 'dev') return true;
|
||||
|
||||
const webOrigins = resolveWebOrigins(webOrigin);
|
||||
|
||||
return (requestOrigin, callback) => {
|
||||
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
VITE_API_BASE_URL=https://persona-lenz-api.dahyeon.us
|
||||
@@ -0,0 +1 @@
|
||||
VITE_API_BASE_URL=https://persona-lenz-api-staging.dahyeon.us
|
||||
@@ -7,6 +7,12 @@
|
||||
"start:dev": "vite --mode development",
|
||||
"start:staging": "vite --mode staging",
|
||||
"build": "tsc -b && vite build",
|
||||
"build:staging": "tsc -b && vite build --mode staging",
|
||||
"build:prod": "tsc -b && vite build --mode production",
|
||||
"deploy:staging": "node ../../scripts/deploy-cloudflare-pages.mjs staging",
|
||||
"deploy:prod": "node ../../scripts/deploy-cloudflare-pages.mjs prod",
|
||||
"pages:login": "wrangler login",
|
||||
"pages:whoami": "wrangler whoami",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
@@ -56,6 +62,7 @@
|
||||
"tailwindcss": "^4.1.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.62.0",
|
||||
"vite": "^8.1.1"
|
||||
"vite": "^8.1.1",
|
||||
"wrangler": "^4.107.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export const API_BASE_URL = (
|
||||
import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
).replace(/\/$/, '')
|
||||
|
||||
export function resolveApiUrl(path: string): string {
|
||||
if (/^https?:\/\//i.test(path)) return path
|
||||
const normalizedPath = path.startsWith('/') ? path : `/${path}`
|
||||
return API_BASE_URL ? `${API_BASE_URL}${normalizedPath}` : normalizedPath
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
PlayerAnalysisDto,
|
||||
SimilarPlayersDto,
|
||||
} from '@persona-lenz/shared'
|
||||
import { resolveApiUrl } from '../config'
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
@@ -19,7 +20,7 @@ export class ApiError extends Error {
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(path, init)
|
||||
response = await fetch(resolveApiUrl(path), init)
|
||||
} catch {
|
||||
throw new ApiError(0, '서버에 연결하지 못했어요. 네트워크를 확인하고 다시 시도해 주세요.')
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
"start:web:staging": "pnpm --filter web start:staging",
|
||||
"build:web:staging": "pnpm --filter web build:staging",
|
||||
"build:web:prod": "pnpm --filter web build:prod",
|
||||
"deploy:web:staging": "node scripts/deploy-cloudflare-pages.mjs staging",
|
||||
"deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod",
|
||||
"build:api": "pnpm --filter api build"
|
||||
},
|
||||
"keywords": [],
|
||||
|
||||
Generated
+796
-8
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,267 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptPath = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(scriptPath);
|
||||
const repoRoot = resolve(__dirname, "..");
|
||||
const webDir = resolve(repoRoot, "apps/web");
|
||||
|
||||
if (process.argv[1] === scriptPath) {
|
||||
main(process.argv.slice(2));
|
||||
}
|
||||
|
||||
export function main(args = process.argv.slice(2), env = process.env) {
|
||||
const target = args[0];
|
||||
if (target !== "staging" && target !== "prod") {
|
||||
console.error(
|
||||
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const viteMode = target === "prod" ? "production" : "staging";
|
||||
const projectName =
|
||||
env.CF_PAGES_PROJECT_NAME ??
|
||||
env.CLOUDFLARE_PAGES_PROJECT_NAME ??
|
||||
"persona-lenz";
|
||||
const deployPlan = resolveDeployPlan(target, env);
|
||||
|
||||
validateEnv(viteMode, env);
|
||||
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
|
||||
|
||||
const deployArgs = createPagesDeployArgs(projectName, deployPlan.pagesBranch);
|
||||
console.error(
|
||||
[
|
||||
`Deploying ${target} from ${deployPlan.sourceBranch}`,
|
||||
`to Cloudflare Pages branch ${deployPlan.pagesBranch}`,
|
||||
].join(" "),
|
||||
);
|
||||
|
||||
run("pnpm", deployArgs, webDir);
|
||||
}
|
||||
|
||||
export function createPagesDeployArgs(projectName, branch) {
|
||||
const deployArgs = [
|
||||
"exec",
|
||||
"wrangler",
|
||||
"pages",
|
||||
"deploy",
|
||||
"dist",
|
||||
"--project-name",
|
||||
projectName,
|
||||
];
|
||||
|
||||
if (branch) deployArgs.push("--branch", branch);
|
||||
return deployArgs;
|
||||
}
|
||||
|
||||
export function resolveStagingBranch(env = process.env) {
|
||||
return resolveDeployPlan("staging", env).pagesBranch;
|
||||
}
|
||||
|
||||
export function resolveDeployPlan(
|
||||
target,
|
||||
env = process.env,
|
||||
releaseBranchRowsProvider = () => {
|
||||
refreshRemoteReleaseBranches();
|
||||
return listReleaseBranchRefs();
|
||||
},
|
||||
) {
|
||||
const sourceBranch = resolveSourceBranch(
|
||||
target,
|
||||
env,
|
||||
releaseBranchRowsProvider,
|
||||
);
|
||||
const pagesBranch =
|
||||
target === "prod" ? resolveProductionBranch(env) : sourceBranch;
|
||||
|
||||
return { sourceBranch, pagesBranch };
|
||||
}
|
||||
|
||||
function resolveSourceBranch(target, env, releaseBranchRowsProvider) {
|
||||
const sourceEnvKey =
|
||||
target === "prod" ? "CF_PAGES_RELEASE_BRANCH" : "CF_PAGES_STAGING_BRANCH";
|
||||
const configuredBranch = env[sourceEnvKey]?.trim();
|
||||
if (configuredBranch) return configuredBranch;
|
||||
|
||||
const latestReleaseBranch = selectLatestReleaseBranch(
|
||||
releaseBranchRowsProvider(),
|
||||
);
|
||||
if (latestReleaseBranch) return latestReleaseBranch;
|
||||
|
||||
console.error(
|
||||
[
|
||||
`No release/* branch found for ${target} deploy.`,
|
||||
"Create a release branch, for example: git push origin main:release/1",
|
||||
`Or set ${sourceEnvKey} explicitly.`,
|
||||
].join("\n"),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function resolveProductionBranch(env) {
|
||||
return (
|
||||
env.CF_PAGES_PRODUCTION_BRANCH?.trim() ||
|
||||
env.CF_PAGES_PROD_BRANCH?.trim() ||
|
||||
"main"
|
||||
);
|
||||
}
|
||||
|
||||
export function selectLatestReleaseBranch(refRows) {
|
||||
const latestByBranch = new Map();
|
||||
|
||||
for (const row of refRows) {
|
||||
const [timestampText, refName] = row.split("\t");
|
||||
const branch = normalizeReleaseBranch(refName);
|
||||
const timestamp = Number(timestampText);
|
||||
if (!branch || !Number.isFinite(timestamp)) continue;
|
||||
|
||||
const current = latestByBranch.get(branch);
|
||||
if (!current || timestamp > current.timestamp) {
|
||||
latestByBranch.set(branch, { branch, timestamp });
|
||||
}
|
||||
}
|
||||
|
||||
const [latest] = [...latestByBranch.values()].sort((left, right) => {
|
||||
if (left.timestamp !== right.timestamp) {
|
||||
return right.timestamp - left.timestamp;
|
||||
}
|
||||
return right.branch.localeCompare(left.branch, "en", { numeric: true });
|
||||
});
|
||||
|
||||
return latest?.branch;
|
||||
}
|
||||
|
||||
export function normalizeReleaseBranch(refName) {
|
||||
const branch = refName?.trim();
|
||||
if (!branch) return undefined;
|
||||
if (branch.startsWith("origin/release/")) {
|
||||
return branch.slice("origin/".length);
|
||||
}
|
||||
if (branch.startsWith("release/")) return branch;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function listReleaseBranchRefs() {
|
||||
const result = spawnSync(
|
||||
"git",
|
||||
[
|
||||
"for-each-ref",
|
||||
"--sort=-committerdate",
|
||||
"--format=%(committerdate:unix)%09%(refname:short)",
|
||||
"refs/remotes/origin/release",
|
||||
"refs/heads/release",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
encoding: "utf8",
|
||||
shell: process.platform === "win32",
|
||||
},
|
||||
);
|
||||
|
||||
if (result.status !== 0) {
|
||||
const stderr = result.stderr?.trim();
|
||||
if (stderr) console.error(stderr);
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.stdout.split(/\r?\n/).filter(Boolean);
|
||||
}
|
||||
|
||||
function refreshRemoteReleaseBranches() {
|
||||
spawnSync("git", ["remote", "prune", "origin"], {
|
||||
cwd: repoRoot,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
spawnSync(
|
||||
"git",
|
||||
[
|
||||
"fetch",
|
||||
"--prune",
|
||||
"origin",
|
||||
"+refs/heads/release/*:refs/remotes/origin/release/*",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function run(command, args, cwd) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
stdio: "inherit",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
process.exit(result.status ?? 1);
|
||||
}
|
||||
}
|
||||
|
||||
function validateEnv(mode, env) {
|
||||
const requiredKeys = resolveRequiredEnvKeys(env);
|
||||
if (requiredKeys.length === 0) return;
|
||||
|
||||
const fileEnv = [
|
||||
".env",
|
||||
".env.local",
|
||||
`.env.${mode}`,
|
||||
`.env.${mode}.local`,
|
||||
].reduce((acc, fileName) => {
|
||||
const envFile = resolve(webDir, fileName);
|
||||
if (!existsSync(envFile)) return acc;
|
||||
return { ...acc, ...parseEnvFile(envFile) };
|
||||
}, {});
|
||||
const missing = requiredKeys.filter((key) => {
|
||||
const value = env[key] ?? fileEnv[key];
|
||||
return !value || value.includes("<");
|
||||
});
|
||||
|
||||
if (missing.length === 0) return;
|
||||
|
||||
console.error(
|
||||
[
|
||||
`Missing Cloudflare Pages ${mode} build env: ${missing.join(", ")}`,
|
||||
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
|
||||
"Set CF_PAGES_REQUIRED_ENV_KEYS to a comma-separated list when build-time env validation is needed.",
|
||||
].join("\n"),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function resolveRequiredEnvKeys(env) {
|
||||
const rawKeys = env.CF_PAGES_REQUIRED_ENV_KEYS?.trim();
|
||||
if (!rawKeys) return ["VITE_API_BASE_URL"];
|
||||
return rawKeys
|
||||
.split(",")
|
||||
.map((key) => key.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseEnvFile(path) {
|
||||
return Object.fromEntries(
|
||||
readFileSync(path, "utf8")
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.startsWith("#"))
|
||||
.map((line) => {
|
||||
const separatorIndex = line.indexOf("=");
|
||||
if (separatorIndex === -1) return [line, ""];
|
||||
const key = line.slice(0, separatorIndex).trim();
|
||||
let value = line.slice(separatorIndex + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
return [key, value];
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
|
||||
import {
|
||||
createPagesDeployArgs,
|
||||
resolveDeployPlan,
|
||||
} from "./deploy-cloudflare-pages.mjs";
|
||||
|
||||
describe("deploy-cloudflare-pages", () => {
|
||||
it("deploys prod to the production branch using the latest release branch as source", () => {
|
||||
const plan = resolveDeployPlan("prod", {}, () => [
|
||||
"1710000000\torigin/release/1",
|
||||
"1720000000\torigin/release/2",
|
||||
]);
|
||||
|
||||
assert.deepEqual(plan, {
|
||||
sourceBranch: "release/2",
|
||||
pagesBranch: "main",
|
||||
});
|
||||
assert.deepEqual(createPagesDeployArgs("persona-lenz", plan.pagesBranch), [
|
||||
"exec",
|
||||
"wrangler",
|
||||
"pages",
|
||||
"deploy",
|
||||
"dist",
|
||||
"--project-name",
|
||||
"persona-lenz",
|
||||
"--branch",
|
||||
"main",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps explicit staging branch override behavior", () => {
|
||||
const plan = resolveDeployPlan(
|
||||
"staging",
|
||||
{ CF_PAGES_STAGING_BRANCH: "release/manual" },
|
||||
() => {
|
||||
throw new Error("should not inspect git refs when branch is explicit");
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(plan, {
|
||||
sourceBranch: "release/manual",
|
||||
pagesBranch: "release/manual",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows overriding the Cloudflare Pages production branch", () => {
|
||||
const plan = resolveDeployPlan(
|
||||
"prod",
|
||||
{ CF_PAGES_PRODUCTION_BRANCH: "production" },
|
||||
() => ["1720000000\torigin/release/2"],
|
||||
);
|
||||
|
||||
assert.deepEqual(plan, {
|
||||
sourceBranch: "release/2",
|
||||
pagesBranch: "production",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user