@beechcms/cli 0.6.0-preview.1 → 0.6.0-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/coverage/index.html +21 -21
- package/coverage/lcov-report/index.html +21 -21
- package/coverage/lcov-report/validate.ts.html +99 -402
- package/coverage/lcov.info +76 -176
- package/coverage/validate.ts.html +99 -402
- package/dist/commands/seed-load.d.ts +8 -0
- package/dist/commands/seed-load.d.ts.map +1 -0
- package/dist/commands/seed-load.js +89 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/lib/schema-diff.d.ts +15 -0
- package/dist/lib/schema-diff.d.ts.map +1 -0
- package/dist/lib/schema-diff.js +37 -0
- package/dist/lib/wrangler.d.ts +17 -0
- package/dist/lib/wrangler.d.ts.map +1 -0
- package/dist/lib/wrangler.js +65 -0
- package/package.json +2 -2
- package/src/commands/deploy.ts +126 -126
- package/src/commands/init.ts +599 -599
- package/src/commands/onboard.ts +32 -32
- package/src/commands/seed-create.ts +192 -192
- package/src/commands/seed-load.ts +235 -235
- package/src/commands/update.ts +54 -54
- package/src/commands/validate.ts +80 -80
- package/src/index.ts +17 -17
- package/src/lib/schema-diff.ts +150 -150
- package/src/lib/wrangler.ts +129 -129
- package/tsconfig.json +16 -16
- package/tsconfig.tsbuildinfo +1 -1
- package/vitest.config.ts +33 -32
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import pc from 'picocolors';
|
|
2
|
+
import { SEED_REGISTRY, generateCreateTable, generateIndexes, generateFtsTable, generateFtsTriggers, } from '@beech/core';
|
|
3
|
+
import { executeD1File, findWranglerConfig, resolveDbName } from '../lib/wrangler.js';
|
|
4
|
+
import { diffSeed } from '../lib/schema-diff.js';
|
|
5
|
+
function buildStatements(seed) {
|
|
6
|
+
const stmts = [generateCreateTable(seed), ...generateIndexes(seed)];
|
|
7
|
+
const fts = generateFtsTable(seed);
|
|
8
|
+
if (fts) {
|
|
9
|
+
stmts.push(fts, ...generateFtsTriggers(seed));
|
|
10
|
+
}
|
|
11
|
+
return stmts;
|
|
12
|
+
}
|
|
13
|
+
async function runDiff(options) {
|
|
14
|
+
const seeds = Object.values(SEED_REGISTRY);
|
|
15
|
+
console.log(pc.cyan('\n Diffing schema…\n'));
|
|
16
|
+
let allOk = true;
|
|
17
|
+
for (const seed of seeds) {
|
|
18
|
+
const result = await diffSeed(seed, options);
|
|
19
|
+
const tableName = `content_${seed.slug}`;
|
|
20
|
+
if (!result.tableExists) {
|
|
21
|
+
console.log(pc.red(` ✗ ${tableName} — table missing`));
|
|
22
|
+
allOk = false;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const problems = result.columns.filter(c => c.status !== 'ok');
|
|
26
|
+
if (problems.length === 0) {
|
|
27
|
+
console.log(pc.green(` ✓ ${tableName}`));
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
allOk = false;
|
|
31
|
+
console.log(pc.yellow(` ⚠ ${tableName}`));
|
|
32
|
+
for (const col of problems) {
|
|
33
|
+
if (col.status === 'missing') {
|
|
34
|
+
console.log(pc.red(` + missing column: ${col.name} ${col.expectedType}`));
|
|
35
|
+
}
|
|
36
|
+
else if (col.status === 'extra') {
|
|
37
|
+
console.log(pc.dim(` ~ extra column: ${col.name} ${col.actualType}`));
|
|
38
|
+
}
|
|
39
|
+
else if (col.status === 'type_mismatch') {
|
|
40
|
+
console.log(pc.red(` ≠ type mismatch: ${col.name} (expected ${col.expectedType}, got ${col.actualType})`));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
console.log('');
|
|
45
|
+
if (allOk) {
|
|
46
|
+
console.log(pc.green(' Schema matches seeds. No action needed.\n'));
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
console.log(pc.yellow(' Run `beech seed:load` to apply missing tables/columns.\n'));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function runLoad(options, dryRun) {
|
|
53
|
+
const seeds = Object.values(SEED_REGISTRY);
|
|
54
|
+
if (dryRun) {
|
|
55
|
+
console.log(pc.cyan('\n -- dry-run: SQL that would be executed\n'));
|
|
56
|
+
for (const seed of seeds) {
|
|
57
|
+
const stmts = buildStatements(seed);
|
|
58
|
+
console.log(pc.dim(` -- content_${seed.slug}`));
|
|
59
|
+
for (const stmt of stmts) {
|
|
60
|
+
console.log(stmt + '\n');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
console.log(pc.cyan(`\n Loading seeds into ${options.local ? 'local' : 'remote'} D1 (${options.db})…\n`));
|
|
66
|
+
for (const seed of seeds) {
|
|
67
|
+
const stmts = buildStatements(seed);
|
|
68
|
+
const sql = stmts.join('\n\n') + '\n';
|
|
69
|
+
process.stdout.write(` ${pc.dim('→')} content_${seed.slug}… `);
|
|
70
|
+
executeD1File(sql, options);
|
|
71
|
+
console.log(pc.green('done'));
|
|
72
|
+
}
|
|
73
|
+
console.log(pc.green('\n All seeds loaded.\n'));
|
|
74
|
+
}
|
|
75
|
+
export async function seedLoad(args) {
|
|
76
|
+
const configPath = findWranglerConfig();
|
|
77
|
+
const db = args.db ?? resolveDbName(configPath);
|
|
78
|
+
const options = {
|
|
79
|
+
db,
|
|
80
|
+
local: args.local,
|
|
81
|
+
configPath,
|
|
82
|
+
};
|
|
83
|
+
if (args.diff) {
|
|
84
|
+
await runDiff(options);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
await runLoad(options, args.dryRun);
|
|
88
|
+
}
|
|
89
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAA;AAClD,YAAY,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Seed } from '@beech/core';
|
|
2
|
+
import type { WranglerOptions } from './wrangler.js';
|
|
3
|
+
export interface ColumnDiff {
|
|
4
|
+
name: string;
|
|
5
|
+
status: 'ok' | 'missing' | 'extra' | 'type_mismatch';
|
|
6
|
+
expectedType?: string;
|
|
7
|
+
actualType?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface SeedDiff {
|
|
10
|
+
slug: string;
|
|
11
|
+
tableExists: boolean;
|
|
12
|
+
columns: ColumnDiff[];
|
|
13
|
+
}
|
|
14
|
+
export declare function diffSeed(seed: Seed, options: WranglerOptions): Promise<SeedDiff>;
|
|
15
|
+
//# sourceMappingURL=schema-diff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-diff.d.ts","sourceRoot":"","sources":["../../src/lib/schema-diff.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAEvC,OAAO,KAAK,EAAE,eAAe,EAAS,MAAM,eAAe,CAAA;AAU3D,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,IAAI,GAAG,SAAS,GAAG,OAAO,GAAG,eAAe,CAAA;IACpD,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,OAAO,CAAA;IACpB,OAAO,EAAE,UAAU,EAAE,CAAA;CACtB;AAED,wBAAsB,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsCtF"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getExpectedColumns } from '@beech/core';
|
|
2
|
+
import { queryD1 } from './wrangler.js';
|
|
3
|
+
export async function diffSeed(seed, options) {
|
|
4
|
+
const tableName = `content_${seed.slug}`;
|
|
5
|
+
const expected = getExpectedColumns(seed);
|
|
6
|
+
let actual;
|
|
7
|
+
try {
|
|
8
|
+
actual = queryD1(`PRAGMA table_info(${tableName})`, options);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return { slug: seed.slug, tableExists: false, columns: expected.map(c => ({ name: c.name, status: 'missing', expectedType: c.sqlType })) };
|
|
12
|
+
}
|
|
13
|
+
if (actual.length === 0) {
|
|
14
|
+
return { slug: seed.slug, tableExists: false, columns: expected.map(c => ({ name: c.name, status: 'missing', expectedType: c.sqlType })) };
|
|
15
|
+
}
|
|
16
|
+
const actualMap = new Map(actual.map(r => [r.name, r]));
|
|
17
|
+
const expectedSet = new Set(expected.map(c => c.name));
|
|
18
|
+
const columns = [];
|
|
19
|
+
for (const col of expected) {
|
|
20
|
+
const actual = actualMap.get(col.name);
|
|
21
|
+
if (!actual) {
|
|
22
|
+
columns.push({ name: col.name, status: 'missing', expectedType: col.sqlType });
|
|
23
|
+
}
|
|
24
|
+
else if (actual.type.toUpperCase() !== col.sqlType) {
|
|
25
|
+
columns.push({ name: col.name, status: 'type_mismatch', expectedType: col.sqlType, actualType: actual.type });
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
columns.push({ name: col.name, status: 'ok' });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
for (const row of actual) {
|
|
32
|
+
if (!expectedSet.has(row.name)) {
|
|
33
|
+
columns.push({ name: row.name, status: 'extra', actualType: row.type });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return { slug: seed.slug, tableExists: true, columns };
|
|
37
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface WranglerOptions {
|
|
2
|
+
db: string;
|
|
3
|
+
local: boolean;
|
|
4
|
+
configPath: string | null;
|
|
5
|
+
}
|
|
6
|
+
export interface D1Row {
|
|
7
|
+
[key: string]: unknown;
|
|
8
|
+
}
|
|
9
|
+
/** Esegue SQL da file temporaneo via `wrangler d1 execute --file`. */
|
|
10
|
+
export declare function executeD1File(sql: string, options: WranglerOptions): void;
|
|
11
|
+
/** Esegue una query SQL e ritorna i risultati come array di oggetti (--json). */
|
|
12
|
+
export declare function queryD1<T extends D1Row = D1Row>(sql: string, options: WranglerOptions): T[];
|
|
13
|
+
/** Trova il path di wrangler.jsonc in apps/api/ relativo a cwd. */
|
|
14
|
+
export declare function findWranglerConfig(): string | null;
|
|
15
|
+
/** Risolve il nome del database D1 da wrangler.jsonc (grepping 'database_name'). */
|
|
16
|
+
export declare function resolveDbName(configPath: string | null): string;
|
|
17
|
+
//# sourceMappingURL=wrangler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrangler.d.ts","sourceRoot":"","sources":["../../src/lib/wrangler.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,OAAO,CAAA;IACd,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B;AAED,MAAM,WAAW,KAAK;IACpB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAgBD,sEAAsE;AACtE,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,IAAI,CAYzE;AAED,iFAAiF;AACjF,wBAAgB,OAAO,CAAC,CAAC,SAAS,KAAK,GAAG,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,CAAC,EAAE,CAc3F;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,MAAM,GAAG,IAAI,CAGlD;AAED,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAS/D"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { execSync, spawnSync } from 'node:child_process';
|
|
2
|
+
import { writeFileSync, rmSync, existsSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
function buildArgs(options) {
|
|
6
|
+
const args = [];
|
|
7
|
+
if (options.configPath)
|
|
8
|
+
args.push('--config', options.configPath);
|
|
9
|
+
if (options.local)
|
|
10
|
+
args.push('--local');
|
|
11
|
+
else
|
|
12
|
+
args.push('--remote');
|
|
13
|
+
return args;
|
|
14
|
+
}
|
|
15
|
+
/** Esegue SQL da file temporaneo via `wrangler d1 execute --file`. */
|
|
16
|
+
export function executeD1File(sql, options) {
|
|
17
|
+
const tmpFile = join(tmpdir(), `beech-seed-${Date.now()}.sql`);
|
|
18
|
+
try {
|
|
19
|
+
writeFileSync(tmpFile, sql, 'utf-8');
|
|
20
|
+
const args = ['d1', 'execute', options.db, '--file', tmpFile, ...buildArgs(options)];
|
|
21
|
+
const result = spawnSync('npx', ['wrangler', ...args], { stdio: 'inherit', cwd: process.cwd() });
|
|
22
|
+
if (result.status !== 0) {
|
|
23
|
+
process.exit(result.status ?? 1);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
try {
|
|
28
|
+
rmSync(tmpFile);
|
|
29
|
+
}
|
|
30
|
+
catch { }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Esegue una query SQL e ritorna i risultati come array di oggetti (--json). */
|
|
34
|
+
export function queryD1(sql, options) {
|
|
35
|
+
const args = ['d1', 'execute', options.db, '--command', sql, '--json', ...buildArgs(options)];
|
|
36
|
+
const result = spawnSync('npx', ['wrangler', ...args], { encoding: 'utf-8', cwd: process.cwd() });
|
|
37
|
+
if (result.status !== 0) {
|
|
38
|
+
throw new Error(`wrangler d1 execute failed:\n${result.stderr}`);
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(result.stdout);
|
|
42
|
+
return (parsed[0]?.results ?? []);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw new Error(`Failed to parse wrangler JSON output:\n${result.stdout}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Trova il path di wrangler.jsonc in apps/api/ relativo a cwd. */
|
|
49
|
+
export function findWranglerConfig() {
|
|
50
|
+
const candidate = resolve(process.cwd(), 'apps', 'api', 'wrangler.jsonc');
|
|
51
|
+
return existsSync(candidate) ? candidate : null;
|
|
52
|
+
}
|
|
53
|
+
/** Risolve il nome del database D1 da wrangler.jsonc (grepping 'database_name'). */
|
|
54
|
+
export function resolveDbName(configPath) {
|
|
55
|
+
if (!configPath)
|
|
56
|
+
return 'beech-db';
|
|
57
|
+
try {
|
|
58
|
+
const content = execSync(`cat "${configPath}"`, { encoding: 'utf-8' });
|
|
59
|
+
const match = content.match(/"database_name"\s*:\s*"([^"]+)"/);
|
|
60
|
+
return match?.[1] ?? 'beech-db';
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return 'beech-db';
|
|
64
|
+
}
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@beechcms/cli",
|
|
3
|
-
"version": "0.6.0-preview.
|
|
3
|
+
"version": "0.6.0-preview.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"test:coverage": "vitest run --coverage"
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"@beechcms/core": "^0.6.0-preview.
|
|
16
|
+
"@beechcms/core": "^0.6.0-preview.2",
|
|
17
17
|
"picocolors": "^1.1.1"
|
|
18
18
|
},
|
|
19
19
|
"devDependencies": {
|
package/src/commands/deploy.ts
CHANGED
|
@@ -1,126 +1,126 @@
|
|
|
1
|
-
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Copyright (c) 2024–2026 Flavio De Musso
|
|
3
|
-
|
|
4
|
-
import pc from 'picocolors'
|
|
5
|
-
import { spawnSync } from 'node:child_process'
|
|
6
|
-
import { readFileSync } from 'node:fs'
|
|
7
|
-
import { findWranglerConfig } from '../lib/wrangler.js'
|
|
8
|
-
|
|
9
|
-
export interface DeployOptions {
|
|
10
|
-
skipSeed?: boolean
|
|
11
|
-
skipCheck?: boolean
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function readWorkerName(configPath: string | null): string | null {
|
|
15
|
-
if (!configPath) return null
|
|
16
|
-
try {
|
|
17
|
-
const raw = readFileSync(configPath, 'utf-8')
|
|
18
|
-
const stripped = raw
|
|
19
|
-
.replace(/\/\/[^\n]*/g, '')
|
|
20
|
-
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
21
|
-
const parsed = JSON.parse(stripped)
|
|
22
|
-
return (parsed?.name as string) ?? null
|
|
23
|
-
} catch {
|
|
24
|
-
return null
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Extracts the first workers.dev URL from wrangler deploy stdout.
|
|
29
|
-
// wrangler writes progress to stderr (shown live) and the summary to stdout (captured).
|
|
30
|
-
function extractWorkerUrl(output: string): string | null {
|
|
31
|
-
const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.workers\.dev\b/)
|
|
32
|
-
return match?.[0] ?? null
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
async function checkAdmin(url: string): Promise<{ ok: boolean; status: number | null }> {
|
|
36
|
-
try {
|
|
37
|
-
const res = await fetch(`${url}/admin`, {
|
|
38
|
-
method: 'HEAD',
|
|
39
|
-
redirect: 'follow',
|
|
40
|
-
signal: AbortSignal.timeout(12_000),
|
|
41
|
-
})
|
|
42
|
-
return { ok: res.status < 500, status: res.status }
|
|
43
|
-
} catch {
|
|
44
|
-
return { ok: false, status: null }
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export async function deploy(args: DeployOptions): Promise<void> {
|
|
49
|
-
console.log(pc.cyan('\n beech deploy\n'))
|
|
50
|
-
|
|
51
|
-
// Step 1: wrangler deploy via npm run deploy.
|
|
52
|
-
// stdout captured to extract the deployed URL; stderr stays on the terminal for live progress.
|
|
53
|
-
console.log(pc.dim(' [1/3] Deploying Worker…\n'))
|
|
54
|
-
const deployResult = spawnSync('npm', ['run', 'deploy'], {
|
|
55
|
-
stdio: ['inherit', 'pipe', 'inherit'],
|
|
56
|
-
encoding: 'utf-8',
|
|
57
|
-
cwd: process.cwd(),
|
|
58
|
-
shell: true,
|
|
59
|
-
})
|
|
60
|
-
|
|
61
|
-
const deployStdout = deployResult.stdout ?? ''
|
|
62
|
-
if (deployStdout) process.stdout.write(deployStdout)
|
|
63
|
-
|
|
64
|
-
if (deployResult.status !== 0) {
|
|
65
|
-
console.log(pc.red('\n ✗ Worker deploy failed\n'))
|
|
66
|
-
console.log(pc.dim(' Check the wrangler output above for details.'))
|
|
67
|
-
console.log(pc.cyan('\n → Run: npx wrangler login # if not authenticated'))
|
|
68
|
-
console.log(pc.cyan(' → Or: Update wrangler.jsonc # if database_id is wrong\n'))
|
|
69
|
-
process.exit(1)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const deployedUrl = extractWorkerUrl(deployStdout)
|
|
73
|
-
console.log(pc.green('\n ✓ Worker deployed'))
|
|
74
|
-
|
|
75
|
-
// Step 2: seed:load --remote as a subprocess so that wrangler failures
|
|
76
|
-
// (which call process.exit internally) don't abort our own process.
|
|
77
|
-
if (args.skipSeed) {
|
|
78
|
-
console.log(pc.dim('\n [2/3] Skipping seed:load (--skip-seed)'))
|
|
79
|
-
} else {
|
|
80
|
-
console.log(pc.dim('\n [2/3] Syncing content schema to remote D1…\n'))
|
|
81
|
-
const seedResult = spawnSync('npx', ['beech', 'seed:load'], {
|
|
82
|
-
stdio: 'inherit',
|
|
83
|
-
cwd: process.cwd(),
|
|
84
|
-
shell: true,
|
|
85
|
-
})
|
|
86
|
-
if (seedResult.status !== 0) {
|
|
87
|
-
console.log(pc.yellow('\n ⚠ seed:load failed\n'))
|
|
88
|
-
console.log(pc.dim(' Sync the remote content schema manually:'))
|
|
89
|
-
console.log(pc.cyan(' → Run: npx beech seed:load\n'))
|
|
90
|
-
} else {
|
|
91
|
-
console.log(pc.green('\n ✓ Content schema synced'))
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Step 3: check /admin reachability.
|
|
96
|
-
// Use URL extracted from deploy output; fall back to worker name from wrangler.jsonc.
|
|
97
|
-
if (args.skipCheck) {
|
|
98
|
-
console.log(pc.dim('\n [3/3] Skipping admin check (--skip-check)\n'))
|
|
99
|
-
return
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const adminBase = deployedUrl ?? (() => {
|
|
103
|
-
const workerName = readWorkerName(findWranglerConfig())
|
|
104
|
-
// We can't reliably construct the full workers.dev subdomain without knowing the account,
|
|
105
|
-
// so only use the name-based URL as a fallback when nothing better is available.
|
|
106
|
-
return workerName ? `https://${workerName}.workers.dev` : null
|
|
107
|
-
})()
|
|
108
|
-
|
|
109
|
-
if (!adminBase) {
|
|
110
|
-
console.log(pc.dim('\n [3/3] Could not determine worker URL — skipping admin check\n'))
|
|
111
|
-
console.log(pc.dim(' The deployed URL is printed by wrangler above. Open <url>/admin to verify.\n'))
|
|
112
|
-
return
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
console.log(pc.dim(`\n [3/3] Checking ${adminBase}/admin…\n`))
|
|
116
|
-
const { ok, status } = await checkAdmin(adminBase)
|
|
117
|
-
|
|
118
|
-
if (ok) {
|
|
119
|
-
console.log(pc.green(` ✓ Admin reachable at: ${adminBase}/admin\n`))
|
|
120
|
-
} else {
|
|
121
|
-
const statusStr = status != null ? ` (HTTP ${status})` : ''
|
|
122
|
-
console.log(pc.yellow(` ⚠ Admin returned an error${statusStr} at: ${adminBase}/admin\n`))
|
|
123
|
-
console.log(pc.dim(' The database may not be fully initialized.'))
|
|
124
|
-
console.log(pc.cyan(' → Run: npx beech init --db --remote\n'))
|
|
125
|
-
}
|
|
126
|
-
}
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2024–2026 Flavio De Musso
|
|
3
|
+
|
|
4
|
+
import pc from 'picocolors'
|
|
5
|
+
import { spawnSync } from 'node:child_process'
|
|
6
|
+
import { readFileSync } from 'node:fs'
|
|
7
|
+
import { findWranglerConfig } from '../lib/wrangler.js'
|
|
8
|
+
|
|
9
|
+
export interface DeployOptions {
|
|
10
|
+
skipSeed?: boolean
|
|
11
|
+
skipCheck?: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function readWorkerName(configPath: string | null): string | null {
|
|
15
|
+
if (!configPath) return null
|
|
16
|
+
try {
|
|
17
|
+
const raw = readFileSync(configPath, 'utf-8')
|
|
18
|
+
const stripped = raw
|
|
19
|
+
.replace(/\/\/[^\n]*/g, '')
|
|
20
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
21
|
+
const parsed = JSON.parse(stripped)
|
|
22
|
+
return (parsed?.name as string) ?? null
|
|
23
|
+
} catch {
|
|
24
|
+
return null
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Extracts the first workers.dev URL from wrangler deploy stdout.
|
|
29
|
+
// wrangler writes progress to stderr (shown live) and the summary to stdout (captured).
|
|
30
|
+
function extractWorkerUrl(output: string): string | null {
|
|
31
|
+
const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.workers\.dev\b/)
|
|
32
|
+
return match?.[0] ?? null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function checkAdmin(url: string): Promise<{ ok: boolean; status: number | null }> {
|
|
36
|
+
try {
|
|
37
|
+
const res = await fetch(`${url}/admin`, {
|
|
38
|
+
method: 'HEAD',
|
|
39
|
+
redirect: 'follow',
|
|
40
|
+
signal: AbortSignal.timeout(12_000),
|
|
41
|
+
})
|
|
42
|
+
return { ok: res.status < 500, status: res.status }
|
|
43
|
+
} catch {
|
|
44
|
+
return { ok: false, status: null }
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function deploy(args: DeployOptions): Promise<void> {
|
|
49
|
+
console.log(pc.cyan('\n beech deploy\n'))
|
|
50
|
+
|
|
51
|
+
// Step 1: wrangler deploy via npm run deploy.
|
|
52
|
+
// stdout captured to extract the deployed URL; stderr stays on the terminal for live progress.
|
|
53
|
+
console.log(pc.dim(' [1/3] Deploying Worker…\n'))
|
|
54
|
+
const deployResult = spawnSync('npm', ['run', 'deploy'], {
|
|
55
|
+
stdio: ['inherit', 'pipe', 'inherit'],
|
|
56
|
+
encoding: 'utf-8',
|
|
57
|
+
cwd: process.cwd(),
|
|
58
|
+
shell: true,
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const deployStdout = deployResult.stdout ?? ''
|
|
62
|
+
if (deployStdout) process.stdout.write(deployStdout)
|
|
63
|
+
|
|
64
|
+
if (deployResult.status !== 0) {
|
|
65
|
+
console.log(pc.red('\n ✗ Worker deploy failed\n'))
|
|
66
|
+
console.log(pc.dim(' Check the wrangler output above for details.'))
|
|
67
|
+
console.log(pc.cyan('\n → Run: npx wrangler login # if not authenticated'))
|
|
68
|
+
console.log(pc.cyan(' → Or: Update wrangler.jsonc # if database_id is wrong\n'))
|
|
69
|
+
process.exit(1)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const deployedUrl = extractWorkerUrl(deployStdout)
|
|
73
|
+
console.log(pc.green('\n ✓ Worker deployed'))
|
|
74
|
+
|
|
75
|
+
// Step 2: seed:load --remote as a subprocess so that wrangler failures
|
|
76
|
+
// (which call process.exit internally) don't abort our own process.
|
|
77
|
+
if (args.skipSeed) {
|
|
78
|
+
console.log(pc.dim('\n [2/3] Skipping seed:load (--skip-seed)'))
|
|
79
|
+
} else {
|
|
80
|
+
console.log(pc.dim('\n [2/3] Syncing content schema to remote D1…\n'))
|
|
81
|
+
const seedResult = spawnSync('npx', ['beech', 'seed:load'], {
|
|
82
|
+
stdio: 'inherit',
|
|
83
|
+
cwd: process.cwd(),
|
|
84
|
+
shell: true,
|
|
85
|
+
})
|
|
86
|
+
if (seedResult.status !== 0) {
|
|
87
|
+
console.log(pc.yellow('\n ⚠ seed:load failed\n'))
|
|
88
|
+
console.log(pc.dim(' Sync the remote content schema manually:'))
|
|
89
|
+
console.log(pc.cyan(' → Run: npx beech seed:load\n'))
|
|
90
|
+
} else {
|
|
91
|
+
console.log(pc.green('\n ✓ Content schema synced'))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Step 3: check /admin reachability.
|
|
96
|
+
// Use URL extracted from deploy output; fall back to worker name from wrangler.jsonc.
|
|
97
|
+
if (args.skipCheck) {
|
|
98
|
+
console.log(pc.dim('\n [3/3] Skipping admin check (--skip-check)\n'))
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const adminBase = deployedUrl ?? (() => {
|
|
103
|
+
const workerName = readWorkerName(findWranglerConfig())
|
|
104
|
+
// We can't reliably construct the full workers.dev subdomain without knowing the account,
|
|
105
|
+
// so only use the name-based URL as a fallback when nothing better is available.
|
|
106
|
+
return workerName ? `https://${workerName}.workers.dev` : null
|
|
107
|
+
})()
|
|
108
|
+
|
|
109
|
+
if (!adminBase) {
|
|
110
|
+
console.log(pc.dim('\n [3/3] Could not determine worker URL — skipping admin check\n'))
|
|
111
|
+
console.log(pc.dim(' The deployed URL is printed by wrangler above. Open <url>/admin to verify.\n'))
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
console.log(pc.dim(`\n [3/3] Checking ${adminBase}/admin…\n`))
|
|
116
|
+
const { ok, status } = await checkAdmin(adminBase)
|
|
117
|
+
|
|
118
|
+
if (ok) {
|
|
119
|
+
console.log(pc.green(` ✓ Admin reachable at: ${adminBase}/admin\n`))
|
|
120
|
+
} else {
|
|
121
|
+
const statusStr = status != null ? ` (HTTP ${status})` : ''
|
|
122
|
+
console.log(pc.yellow(` ⚠ Admin returned an error${statusStr} at: ${adminBase}/admin\n`))
|
|
123
|
+
console.log(pc.dim(' The database may not be fully initialized.'))
|
|
124
|
+
console.log(pc.cyan(' → Run: npx beech init --db --remote\n'))
|
|
125
|
+
}
|
|
126
|
+
}
|