@beechcms/cli 0.4.0-preview.11 → 0.4.0-preview.13
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/dist/index.js +681 -20
- package/package.json +2 -2
- package/src/commands/deploy.ts +122 -0
- package/src/commands/init.ts +400 -0
- package/src/commands/seed-create.ts +189 -0
- package/src/commands/seed-load.ts +137 -128
- package/src/commands/validate.ts +83 -0
- package/src/index.ts +10 -2
- package/src/lib/schema-diff.ts +64 -64
- package/src/lib/wrangler.ts +108 -108
- package/tsconfig.json +16 -16
- package/tsconfig.tsbuildinfo +1 -1
- package/dist/commands/seed-load.d.ts +0 -8
- package/dist/commands/seed-load.d.ts.map +0 -1
- package/dist/commands/seed-load.js +0 -89
- package/dist/index.d.ts +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/lib/schema-diff.d.ts +0 -15
- package/dist/lib/schema-diff.d.ts.map +0 -1
- package/dist/lib/schema-diff.js +0 -37
- package/dist/lib/wrangler.d.ts +0 -17
- package/dist/lib/wrangler.d.ts.map +0 -1
- package/dist/lib/wrangler.js +0 -65
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@beechcms/cli",
|
|
3
|
-
"version": "0.4.0-preview.
|
|
3
|
+
"version": "0.4.0-preview.13",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"dev": "esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --outfile=dist/index.js --watch"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@beechcms/core": "^0.4.0-preview.
|
|
14
|
+
"@beechcms/core": "^0.4.0-preview.13",
|
|
15
15
|
"picocolors": "^1.1.1"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import pc from 'picocolors'
|
|
2
|
+
import { spawnSync } from 'node:child_process'
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { findWranglerConfig } from '../lib/wrangler.js'
|
|
5
|
+
|
|
6
|
+
export interface DeployOptions {
|
|
7
|
+
skipSeed?: boolean
|
|
8
|
+
skipCheck?: boolean
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function readWorkerName(configPath: string | null): string | null {
|
|
12
|
+
if (!configPath) return null
|
|
13
|
+
try {
|
|
14
|
+
const raw = readFileSync(configPath, 'utf-8')
|
|
15
|
+
const stripped = raw
|
|
16
|
+
.replace(/\/\/[^\n]*/g, '')
|
|
17
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
18
|
+
const parsed = JSON.parse(stripped)
|
|
19
|
+
return (parsed?.name as string) ?? null
|
|
20
|
+
} catch {
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Extracts the first workers.dev URL from wrangler deploy stdout.
|
|
26
|
+
// wrangler writes progress to stderr (shown live) and the summary to stdout (captured).
|
|
27
|
+
function extractWorkerUrl(output: string): string | null {
|
|
28
|
+
const match = output.match(/https:\/\/[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.workers\.dev\b/)
|
|
29
|
+
return match?.[0] ?? null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function checkAdmin(url: string): Promise<{ ok: boolean; status: number | null }> {
|
|
33
|
+
try {
|
|
34
|
+
const res = await fetch(`${url}/admin`, {
|
|
35
|
+
method: 'HEAD',
|
|
36
|
+
redirect: 'follow',
|
|
37
|
+
signal: AbortSignal.timeout(12_000),
|
|
38
|
+
})
|
|
39
|
+
return { ok: res.status < 500, status: res.status }
|
|
40
|
+
} catch {
|
|
41
|
+
return { ok: false, status: null }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function deploy(args: DeployOptions): Promise<void> {
|
|
46
|
+
console.log(pc.cyan('\n beech deploy\n'))
|
|
47
|
+
|
|
48
|
+
// Step 1: wrangler deploy via npm run deploy.
|
|
49
|
+
// stdout captured to extract the deployed URL; stderr stays on the terminal for live progress.
|
|
50
|
+
console.log(pc.dim(' [1/3] Deploying Worker…\n'))
|
|
51
|
+
const deployResult = spawnSync('npm', ['run', 'deploy'], {
|
|
52
|
+
stdio: ['inherit', 'pipe', 'inherit'],
|
|
53
|
+
encoding: 'utf-8',
|
|
54
|
+
cwd: process.cwd(),
|
|
55
|
+
shell: true,
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const deployStdout = deployResult.stdout ?? ''
|
|
59
|
+
if (deployStdout) process.stdout.write(deployStdout)
|
|
60
|
+
|
|
61
|
+
if (deployResult.status !== 0) {
|
|
62
|
+
console.log(pc.red('\n ✗ Worker deploy failed\n'))
|
|
63
|
+
console.log(pc.dim(' Check the output above for wrangler errors.'))
|
|
64
|
+
console.log(pc.dim(' Common causes:'))
|
|
65
|
+
console.log(pc.dim(' - Not logged in to Cloudflare → npx wrangler login'))
|
|
66
|
+
console.log(pc.dim(' - Wrong database_id in wrangler.jsonc\n'))
|
|
67
|
+
process.exit(1)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const deployedUrl = extractWorkerUrl(deployStdout)
|
|
71
|
+
console.log(pc.green('\n ✓ Worker deployed'))
|
|
72
|
+
|
|
73
|
+
// Step 2: seed:load --remote as a subprocess so that wrangler failures
|
|
74
|
+
// (which call process.exit internally) don't abort our own process.
|
|
75
|
+
if (args.skipSeed) {
|
|
76
|
+
console.log(pc.dim('\n [2/3] Skipping seed:load (--skip-seed)'))
|
|
77
|
+
} else {
|
|
78
|
+
console.log(pc.dim('\n [2/3] Syncing content schema to remote D1…\n'))
|
|
79
|
+
const seedResult = spawnSync('npx', ['beech', 'seed:load'], {
|
|
80
|
+
stdio: 'inherit',
|
|
81
|
+
cwd: process.cwd(),
|
|
82
|
+
shell: true,
|
|
83
|
+
})
|
|
84
|
+
if (seedResult.status !== 0) {
|
|
85
|
+
console.log(pc.yellow('\n ⚠ seed:load failed — run manually: npx beech seed:load'))
|
|
86
|
+
} else {
|
|
87
|
+
console.log(pc.green('\n ✓ Content schema synced'))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Step 3: check /admin reachability.
|
|
92
|
+
// Use URL extracted from deploy output; fall back to worker name from wrangler.jsonc.
|
|
93
|
+
if (args.skipCheck) {
|
|
94
|
+
console.log(pc.dim('\n [3/3] Skipping admin check (--skip-check)\n'))
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const adminBase = deployedUrl ?? (() => {
|
|
99
|
+
const workerName = readWorkerName(findWranglerConfig())
|
|
100
|
+
// We can't reliably construct the full workers.dev subdomain without knowing the account,
|
|
101
|
+
// so only use the name-based URL as a fallback when nothing better is available.
|
|
102
|
+
return workerName ? `https://${workerName}.workers.dev` : null
|
|
103
|
+
})()
|
|
104
|
+
|
|
105
|
+
if (!adminBase) {
|
|
106
|
+
console.log(pc.dim('\n [3/3] Could not determine worker URL — skipping admin check\n'))
|
|
107
|
+
console.log(pc.dim(' The deployed URL is printed by wrangler above. Open <url>/admin to verify.\n'))
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
console.log(pc.dim(`\n [3/3] Checking ${adminBase}/admin…\n`))
|
|
112
|
+
const { ok, status } = await checkAdmin(adminBase)
|
|
113
|
+
|
|
114
|
+
if (ok) {
|
|
115
|
+
console.log(pc.green(` ✓ Admin reachable at: ${adminBase}/admin\n`))
|
|
116
|
+
} else {
|
|
117
|
+
const statusStr = status != null ? ` (HTTP ${status})` : ''
|
|
118
|
+
console.log(pc.yellow(` ⚠ Admin returned an error${statusStr} at: ${adminBase}/admin\n`))
|
|
119
|
+
console.log(pc.dim(' The database may not be fully initialized.'))
|
|
120
|
+
console.log(pc.cyan(' → Run: npx beech init --db --remote\n'))
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import pc from 'picocolors'
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { resolve, basename } from 'node:path'
|
|
4
|
+
import { spawnSync } from 'node:child_process'
|
|
5
|
+
import { findWranglerConfig, resolveDbName, executeD1File, queryD1, type WranglerOptions } from '../lib/wrangler.js'
|
|
6
|
+
|
|
7
|
+
// System tables created by the base schema migration (0000_v040_base.sql).
|
|
8
|
+
// Used to detect whether the DB has been initialised.
|
|
9
|
+
const SYSTEM_TABLES = [
|
|
10
|
+
'users',
|
|
11
|
+
'refresh_tokens',
|
|
12
|
+
'password_reset_tokens',
|
|
13
|
+
'public_idempotency_keys',
|
|
14
|
+
'analytics',
|
|
15
|
+
'system_stats',
|
|
16
|
+
'activity_logs',
|
|
17
|
+
'notifications',
|
|
18
|
+
'media_objects',
|
|
19
|
+
'content_event_log',
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
// Embedded copy of 0000_v040_base.sql — all DDL uses CREATE TABLE IF NOT EXISTS,
|
|
23
|
+
// so this is safe to re-run against an already-initialised database.
|
|
24
|
+
const BASE_SCHEMA_SQL = `
|
|
25
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
26
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
27
|
+
email TEXT NOT NULL UNIQUE,
|
|
28
|
+
password_hash TEXT NOT NULL,
|
|
29
|
+
role TEXT NOT NULL DEFAULT 'editor' CHECK (role IN ('admin', 'editor')),
|
|
30
|
+
name TEXT,
|
|
31
|
+
avatar_url TEXT,
|
|
32
|
+
notification_prefs TEXT NOT NULL DEFAULT '{}',
|
|
33
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
|
37
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
38
|
+
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
39
|
+
token_hash TEXT NOT NULL,
|
|
40
|
+
expires_at INTEGER NOT NULL,
|
|
41
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
42
|
+
revoked_at INTEGER DEFAULT NULL
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
CREATE INDEX IF NOT EXISTS idx_refresh_user ON refresh_tokens(user_id);
|
|
46
|
+
CREATE INDEX IF NOT EXISTS idx_refresh_hash ON refresh_tokens(token_hash);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens(expires_at);
|
|
48
|
+
|
|
49
|
+
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
|
50
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
51
|
+
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
52
|
+
token_hash TEXT NOT NULL,
|
|
53
|
+
expires_at INTEGER NOT NULL,
|
|
54
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
55
|
+
used_at INTEGER DEFAULT NULL
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
CREATE INDEX IF NOT EXISTS idx_prt_hash ON password_reset_tokens(token_hash);
|
|
59
|
+
CREATE INDEX IF NOT EXISTS idx_prt_user ON password_reset_tokens(user_id);
|
|
60
|
+
|
|
61
|
+
CREATE TABLE IF NOT EXISTS public_idempotency_keys (
|
|
62
|
+
idempotency_key TEXT NOT NULL PRIMARY KEY,
|
|
63
|
+
request_fingerprint TEXT NOT NULL,
|
|
64
|
+
response_status INTEGER NOT NULL,
|
|
65
|
+
response_body TEXT NOT NULL,
|
|
66
|
+
created_at INTEGER NOT NULL,
|
|
67
|
+
expires_at INTEGER NOT NULL
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
CREATE INDEX IF NOT EXISTS idx_idempotency_expires ON public_idempotency_keys(expires_at);
|
|
71
|
+
|
|
72
|
+
CREATE TABLE IF NOT EXISTS analytics (
|
|
73
|
+
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
|
74
|
+
day_ts INTEGER NOT NULL,
|
|
75
|
+
metric TEXT NOT NULL,
|
|
76
|
+
seed TEXT NOT NULL DEFAULT '',
|
|
77
|
+
value INTEGER NOT NULL DEFAULT 0,
|
|
78
|
+
UNIQUE(day_ts, metric, seed)
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
CREATE INDEX IF NOT EXISTS idx_analytics_day ON analytics(day_ts);
|
|
82
|
+
CREATE INDEX IF NOT EXISTS idx_analytics_seed ON analytics(seed, day_ts);
|
|
83
|
+
|
|
84
|
+
CREATE TABLE IF NOT EXISTS system_stats (
|
|
85
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
86
|
+
value TEXT NOT NULL
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
INSERT OR IGNORE INTO system_stats (id, value) VALUES ('total_storage_bytes', '0');
|
|
90
|
+
|
|
91
|
+
CREATE TABLE IF NOT EXISTS activity_logs (
|
|
92
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
93
|
+
user_id TEXT NOT NULL,
|
|
94
|
+
user_email TEXT NOT NULL,
|
|
95
|
+
user_name TEXT,
|
|
96
|
+
action TEXT NOT NULL,
|
|
97
|
+
entity_type TEXT NOT NULL,
|
|
98
|
+
entity_id TEXT NOT NULL,
|
|
99
|
+
entity_slug TEXT,
|
|
100
|
+
details TEXT,
|
|
101
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_activity_user ON activity_logs(user_id);
|
|
105
|
+
CREATE INDEX IF NOT EXISTS idx_activity_created ON activity_logs(created_at);
|
|
106
|
+
|
|
107
|
+
CREATE TABLE IF NOT EXISTS notifications (
|
|
108
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
109
|
+
title TEXT NOT NULL,
|
|
110
|
+
message TEXT NOT NULL,
|
|
111
|
+
type TEXT NOT NULL DEFAULT 'info' CHECK (type IN ('info', 'warning', 'error')),
|
|
112
|
+
is_read INTEGER NOT NULL DEFAULT 0 CHECK (is_read IN (0, 1)),
|
|
113
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_created ON notifications(created_at);
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(is_read);
|
|
118
|
+
|
|
119
|
+
CREATE TABLE IF NOT EXISTS media_objects (
|
|
120
|
+
key TEXT NOT NULL PRIMARY KEY,
|
|
121
|
+
filename TEXT NOT NULL,
|
|
122
|
+
mime_type TEXT NOT NULL,
|
|
123
|
+
size_bytes INTEGER NOT NULL,
|
|
124
|
+
uploaded_by TEXT NOT NULL DEFAULT '',
|
|
125
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
CREATE INDEX IF NOT EXISTS idx_media_user ON media_objects(uploaded_by);
|
|
129
|
+
CREATE INDEX IF NOT EXISTS idx_media_created ON media_objects(created_at DESC);
|
|
130
|
+
|
|
131
|
+
CREATE TABLE IF NOT EXISTS content_event_log (
|
|
132
|
+
id TEXT NOT NULL PRIMARY KEY,
|
|
133
|
+
schema_slug TEXT NOT NULL,
|
|
134
|
+
entry_id TEXT NOT NULL,
|
|
135
|
+
action TEXT NOT NULL CHECK (action IN ('create', 'update', 'delete')),
|
|
136
|
+
user_id TEXT,
|
|
137
|
+
details TEXT,
|
|
138
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
CREATE INDEX IF NOT EXISTS idx_event_log_schema_slug ON content_event_log(schema_slug);
|
|
142
|
+
CREATE INDEX IF NOT EXISTS idx_event_log_created_at ON content_event_log(created_at DESC);
|
|
143
|
+
CREATE INDEX IF NOT EXISTS idx_event_log_entry_id ON content_event_log(entry_id);
|
|
144
|
+
`.trim()
|
|
145
|
+
|
|
146
|
+
const PLACEHOLDER_DB_IDS = [
|
|
147
|
+
'INCOLLA_QUI_IL_TUO_ID_D1',
|
|
148
|
+
'FILL_IN_YOUR_D1_DATABASE_ID',
|
|
149
|
+
'YOUR_D1_DATABASE_ID',
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
export interface InitOptions {
|
|
153
|
+
initDb: boolean
|
|
154
|
+
local: boolean
|
|
155
|
+
db?: string
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function checkWranglerAuth(): boolean {
|
|
159
|
+
const result = spawnSync('npx', ['wrangler', 'whoami', '--json'], {
|
|
160
|
+
encoding: 'utf-8',
|
|
161
|
+
cwd: process.cwd(),
|
|
162
|
+
shell: true,
|
|
163
|
+
})
|
|
164
|
+
return result.status === 0
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function checkWranglerPlaceholders(configPath: string): string[] {
|
|
168
|
+
try {
|
|
169
|
+
const raw = readFileSync(configPath, 'utf-8')
|
|
170
|
+
const stripped = raw
|
|
171
|
+
.replace(/\/\/[^\n]*/g, '')
|
|
172
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
173
|
+
const parsed = JSON.parse(stripped)
|
|
174
|
+
const bindings: { database_id?: string; database_name?: string }[] = parsed?.d1_databases ?? []
|
|
175
|
+
const issues: string[] = []
|
|
176
|
+
for (const b of bindings) {
|
|
177
|
+
const id = b.database_id ?? ''
|
|
178
|
+
if (!id || PLACEHOLDER_DB_IDS.includes(id)) {
|
|
179
|
+
issues.push(`d1_databases[0].database_id is "${id || '(empty)'}"`)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return issues
|
|
183
|
+
} catch {
|
|
184
|
+
return []
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function echoApiKeys(configPath: string | null | undefined): void {
|
|
189
|
+
if (!configPath) return
|
|
190
|
+
try {
|
|
191
|
+
const raw = readFileSync(configPath, 'utf-8')
|
|
192
|
+
const stripped = raw
|
|
193
|
+
.replace(/\/\/[^\n]*/g, '')
|
|
194
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
195
|
+
const parsed = JSON.parse(stripped)
|
|
196
|
+
const vars: Record<string, string> = parsed?.vars ?? {}
|
|
197
|
+
const readKey = vars['PUBLIC_READ_API_KEY']
|
|
198
|
+
const writeKey = vars['PUBLIC_WRITE_API_KEY']
|
|
199
|
+
if (!readKey && !writeKey) return
|
|
200
|
+
console.log(pc.dim(' API keys detected in wrangler.jsonc:\n'))
|
|
201
|
+
if (readKey) {
|
|
202
|
+
const masked = readKey.length > 8 ? readKey.slice(0, 4) + '****' + readKey.slice(-4) : '****'
|
|
203
|
+
console.log(pc.dim(` PUBLIC_READ_API_KEY = ${masked}`))
|
|
204
|
+
}
|
|
205
|
+
if (writeKey) {
|
|
206
|
+
const masked = writeKey.length > 8 ? writeKey.slice(0, 4) + '****' + writeKey.slice(-4) : '****'
|
|
207
|
+
console.log(pc.dim(` PUBLIC_WRITE_API_KEY = ${masked}`))
|
|
208
|
+
}
|
|
209
|
+
console.log(pc.dim('\n Use these in your frontend as the X-API-Key header.\n'))
|
|
210
|
+
} catch {
|
|
211
|
+
// wrangler.jsonc may be missing or malformed — skip silently
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function checkFiles(cwd: string, checkDevVars: boolean): boolean {
|
|
216
|
+
let ok = true
|
|
217
|
+
|
|
218
|
+
const workerExists = existsSync(resolve(cwd, 'worker.ts')) || existsSync(resolve(cwd, 'worker.js'))
|
|
219
|
+
if (!workerExists) {
|
|
220
|
+
console.log(pc.red(' ✗ worker.ts — missing (required)'))
|
|
221
|
+
ok = false
|
|
222
|
+
} else {
|
|
223
|
+
console.log(pc.green(' ✓ worker.ts'))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const configPath = findWranglerConfig()
|
|
227
|
+
const configInCwd = configPath &&
|
|
228
|
+
(configPath === resolve(cwd, 'wrangler.jsonc') ||
|
|
229
|
+
configPath === resolve(cwd, 'wrangler.json') ||
|
|
230
|
+
configPath === resolve(cwd, 'wrangler.toml'))
|
|
231
|
+
|
|
232
|
+
if (!configInCwd) {
|
|
233
|
+
console.log(pc.red(' ✗ wrangler.jsonc — missing (required)'))
|
|
234
|
+
ok = false
|
|
235
|
+
} else {
|
|
236
|
+
console.log(pc.green(` ✓ ${basename(configPath!)}`))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const seedsExists =
|
|
240
|
+
existsSync(resolve(cwd, 'seeds.ts')) ||
|
|
241
|
+
existsSync(resolve(cwd, 'seeds.js')) ||
|
|
242
|
+
existsSync(resolve(cwd, 'seed.ts')) ||
|
|
243
|
+
existsSync(resolve(cwd, 'seed.js'))
|
|
244
|
+
|
|
245
|
+
if (!seedsExists) {
|
|
246
|
+
console.log(pc.yellow(' ⚠ seeds.ts — missing (create it, then run beech seed:load)'))
|
|
247
|
+
} else {
|
|
248
|
+
console.log(pc.green(' ✓ seeds.ts'))
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (checkDevVars) {
|
|
252
|
+
if (!existsSync(resolve(cwd, '.dev.vars'))) {
|
|
253
|
+
console.log(pc.dim(' ○ .dev.vars — not found (optional: only needed for production R2 credentials)'))
|
|
254
|
+
} else {
|
|
255
|
+
console.log(pc.green(' ✓ .dev.vars'))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return ok
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function printNextSteps(local: boolean): void {
|
|
263
|
+
const localFlag = local ? ' --local' : ''
|
|
264
|
+
console.log(pc.dim(' Next steps:'))
|
|
265
|
+
console.log(pc.cyan(` 1. npx beech seed:load${localFlag}`))
|
|
266
|
+
console.log(pc.dim(' → create content tables from seeds.ts'))
|
|
267
|
+
console.log(pc.cyan(' 2. npx wrangler dev'))
|
|
268
|
+
console.log(pc.dim(' → start API + dashboard'))
|
|
269
|
+
console.log(pc.dim(' 3. Open http://localhost:8789/admin\n'))
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function getExistingTables(options: WranglerOptions): string[] | null {
|
|
273
|
+
try {
|
|
274
|
+
const rows = queryD1<{ name: string }>(
|
|
275
|
+
`SELECT name FROM sqlite_master WHERE type='table'`,
|
|
276
|
+
options
|
|
277
|
+
)
|
|
278
|
+
return rows.map(r => r.name)
|
|
279
|
+
} catch {
|
|
280
|
+
return null
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export async function init(args: InitOptions): Promise<void> {
|
|
285
|
+
const cwd = process.cwd()
|
|
286
|
+
|
|
287
|
+
console.log(pc.cyan('\n beech init — project check\n'))
|
|
288
|
+
|
|
289
|
+
const filesOk = checkFiles(cwd, args.local)
|
|
290
|
+
|
|
291
|
+
if (!filesOk) {
|
|
292
|
+
console.log(pc.red('\n ✗ Required files missing. Fix the errors above before initialising the database.\n'))
|
|
293
|
+
process.exit(1)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
console.log(pc.green('\n All required files present.\n'))
|
|
297
|
+
|
|
298
|
+
if (!args.initDb) {
|
|
299
|
+
echoApiKeys(findWranglerConfig())
|
|
300
|
+
const localFlag = args.local ? ' --local' : ''
|
|
301
|
+
console.log(pc.dim(' Next steps:'))
|
|
302
|
+
console.log(pc.dim(` 1. npx beech init --db${localFlag} # initialise D1 database`))
|
|
303
|
+
console.log(pc.dim(` 2. npx beech seed:load${localFlag} # create content tables`))
|
|
304
|
+
console.log(pc.dim(' 3. npx wrangler dev # start API + dashboard'))
|
|
305
|
+
console.log(pc.dim(' 4. Open http://localhost:8789/admin\n'))
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// --- Database initialisation ---
|
|
310
|
+
const configPath = findWranglerConfig()
|
|
311
|
+
|
|
312
|
+
// Check for placeholder database_id before touching the DB
|
|
313
|
+
if (configPath) {
|
|
314
|
+
const placeholders = checkWranglerPlaceholders(configPath)
|
|
315
|
+
if (placeholders.length > 0) {
|
|
316
|
+
console.log(pc.yellow(' ⚠ wrangler.jsonc contains placeholder values:\n'))
|
|
317
|
+
for (const issue of placeholders) {
|
|
318
|
+
console.log(pc.yellow(` - ${issue}`))
|
|
319
|
+
}
|
|
320
|
+
console.log(pc.dim('\n Update your D1 database_id in wrangler.jsonc,'))
|
|
321
|
+
console.log(pc.dim(' or create a new database with:'))
|
|
322
|
+
console.log(pc.cyan('\n npx wrangler d1 create my-project-db\n'))
|
|
323
|
+
console.log(pc.dim(' Then retry: npx beech init --db\n'))
|
|
324
|
+
process.exit(1)
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// For remote operations, verify Cloudflare auth before attempting any wrangler calls
|
|
329
|
+
if (!args.local) {
|
|
330
|
+
const authed = checkWranglerAuth()
|
|
331
|
+
if (!authed) {
|
|
332
|
+
console.log(pc.red(' ✗ Not logged in to Cloudflare\n'))
|
|
333
|
+
console.log(pc.dim(' BeechCMS needs access to your Cloudflare account to manage the D1 database.\n'))
|
|
334
|
+
console.log(pc.cyan(' → Run: npx wrangler login'))
|
|
335
|
+
console.log(pc.cyan(' → Then: npx beech init --db\n'))
|
|
336
|
+
process.exit(1)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const db = args.db ?? resolveDbName(configPath)
|
|
341
|
+
const options: WranglerOptions = { db, local: args.local, configPath }
|
|
342
|
+
|
|
343
|
+
console.log(pc.cyan(` Checking database "${db}" (${args.local ? 'local' : 'remote'})…\n`))
|
|
344
|
+
|
|
345
|
+
const existingTables = getExistingTables(options)
|
|
346
|
+
const missingTables = SYSTEM_TABLES.filter(t => !existingTables?.includes(t))
|
|
347
|
+
|
|
348
|
+
// Remote mode: verification only — do not auto-apply schema.
|
|
349
|
+
// In production, system tables are created by `wrangler deploy` migrations.
|
|
350
|
+
if (!args.local) {
|
|
351
|
+
if (existingTables === null) {
|
|
352
|
+
console.log(pc.red(' ✗ Remote database unreachable\n'))
|
|
353
|
+
console.log(pc.dim(' Most likely causes:'))
|
|
354
|
+
console.log(pc.dim(' - Wrong database_id in wrangler.jsonc'))
|
|
355
|
+
console.log(pc.dim(' - Worker not yet deployed\n'))
|
|
356
|
+
console.log(pc.dim(' Fix the configuration and re-deploy:\n'))
|
|
357
|
+
console.log(pc.cyan(' 1. Update d1_databases.database_id in wrangler.jsonc'))
|
|
358
|
+
console.log(pc.cyan(' 2. npm run deploy\n'))
|
|
359
|
+
process.exit(1)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (missingTables.length > 0) {
|
|
363
|
+
console.log(pc.yellow(` ⚠ Missing system tables: ${missingTables.join(', ')}\n`))
|
|
364
|
+
console.log(pc.dim(' Most likely causes:'))
|
|
365
|
+
console.log(pc.dim(' - Wrong database_id in wrangler.jsonc'))
|
|
366
|
+
console.log(pc.dim(' - Migrations did not run during deploy\n'))
|
|
367
|
+
console.log(pc.dim(' Fix the configuration and re-deploy:\n'))
|
|
368
|
+
console.log(pc.cyan(' 1. Update d1_databases.database_id in wrangler.jsonc'))
|
|
369
|
+
console.log(pc.cyan(' 2. npm run deploy\n'))
|
|
370
|
+
process.exit(1)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
for (const table of SYSTEM_TABLES) {
|
|
374
|
+
console.log(pc.green(` ✓ ${table}`))
|
|
375
|
+
}
|
|
376
|
+
console.log(pc.green('\n All system tables present. Remote database is initialized.\n'))
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Local mode: apply schema if tables are missing.
|
|
381
|
+
if (existingTables === null) {
|
|
382
|
+
console.log(pc.yellow(' Database unreachable or not yet created — applying base schema…\n'))
|
|
383
|
+
} else if (missingTables.length === 0) {
|
|
384
|
+
console.log(pc.green(' ✓ All system tables present. Database already initialised.\n'))
|
|
385
|
+
printNextSteps(args.local)
|
|
386
|
+
return
|
|
387
|
+
} else {
|
|
388
|
+
console.log(pc.yellow(` Missing system tables: ${missingTables.join(', ')}`))
|
|
389
|
+
console.log(pc.cyan('\n Applying base schema…\n'))
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
executeD1File(BASE_SCHEMA_SQL, options)
|
|
393
|
+
|
|
394
|
+
console.log(pc.green('\n ✓ worker.ts'))
|
|
395
|
+
console.log(pc.green(` ✓ ${configPath ? basename(configPath) : 'wrangler.jsonc'}`))
|
|
396
|
+
console.log(pc.green(' ✓ seeds.ts'))
|
|
397
|
+
console.log(pc.green(' ✓ Local D1 system tables ready\n'))
|
|
398
|
+
echoApiKeys(configPath)
|
|
399
|
+
printNextSteps(args.local)
|
|
400
|
+
}
|