Add wrangler

This commit is contained in:
2026-06-21 05:04:26 -04:00
parent 4498fa2611
commit ed7597f879
8 changed files with 2153 additions and 5 deletions
+111
View File
@@ -0,0 +1,111 @@
import { existsSync, readFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { basename } from 'node:path';
const [command, envFile, ...args] = process.argv.slice(2);
if (!['build', 'deploy'].includes(command) || !envFile) {
console.error('Usage: node scripts/cloudflare-pages.mjs <build|deploy> <env-file> [--branch name] [--project name]');
process.exit(1);
}
if (!existsSync(envFile)) {
console.error(`Missing ${envFile}. Copy the matching .example file and fill in the values first.`);
process.exit(1);
}
function parseArgs(values) {
const options = {};
for (let index = 0; index < values.length; index += 1) {
const value = values[index];
if (value === '--branch' || value === '--project') {
options[value.slice(2)] = values[index + 1];
index += 1;
}
}
return options;
}
function parseEnvFile(path) {
const entries = {};
const lines = readFileSync(path, 'utf8').split(/\r?\n/);
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const separator = trimmed.indexOf('=');
if (separator === -1) continue;
const key = trimmed.slice(0, separator).trim();
let value = trimmed.slice(separator + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
entries[key] = value;
}
return entries;
}
function applyEnv(entries) {
for (const [key, value] of Object.entries(entries)) {
if (process.env[key] === undefined) {
process.env[key] = value;
}
}
}
function run(name, commandName, commandArgs) {
return new Promise((resolve, reject) => {
const child = spawn(commandName, commandArgs, {
env: process.env,
stdio: 'inherit',
shell: process.platform === 'win32',
});
child.on('error', reject);
child.on('exit', (code) => {
if (code === 0) {
resolve();
return;
}
reject(new Error(`${name} exited with code ${code}`));
});
});
}
const envEntries = parseEnvFile(envFile);
applyEnv(envEntries);
const options = parseArgs(args);
const projectName = options.project ?? process.env.CF_PAGES_PROJECT_NAME;
const branch = options.branch ?? process.env.CF_PAGES_BRANCH;
console.log(`Using ${basename(envFile)} for ${command}.`);
console.log(`PUBLIC_SITE_URL=${process.env.PUBLIC_SITE_URL ?? '<unset>'}`);
console.log(`DIRECTUS_URL=${process.env.DIRECTUS_URL ?? '<unset>'}`);
await run('Astro build', 'npm', ['run', 'build']);
if (command === 'deploy') {
if (!projectName) {
console.error('Missing CF_PAGES_PROJECT_NAME. Set it in the env file or pass --project <name>.');
process.exit(1);
}
const wranglerArgs = ['wrangler', 'pages', 'deploy', 'dist', '--project-name', projectName];
if (branch) {
wranglerArgs.push('--branch', branch);
}
await run('Cloudflare Pages deploy', 'npx', wranglerArgs);
}