@beechcms/cms 0.4.0-preview.12 → 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.
Files changed (4) hide show
  1. package/README.md +107 -107
  2. package/bin/cli.mjs +188 -129
  3. package/bin/create.mjs +433 -428
  4. package/package.json +14 -2
package/bin/create.mjs CHANGED
@@ -1,428 +1,433 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
-
4
- import * as p from '@clack/prompts'
5
- import pc from 'picocolors'
6
- import { execSync } from 'node:child_process'
7
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
8
- import { resolve, join } from 'node:path'
9
- import { randomBytes } from 'node:crypto'
10
- import { fileURLToPath } from 'node:url'
11
- import { dirname } from 'node:path'
12
-
13
- const __dirname = dirname(fileURLToPath(import.meta.url))
14
-
15
- // ── Template registry ─────────────────────────────────────────────────────────
16
-
17
- const TEMPLATES = {
18
- blog: {
19
- label: 'Blog',
20
- hint: 'posts with rich text, cover image, tags and authors',
21
- file: 'blog.ts',
22
- registryEntries: ['posts: POST_SEED', 'authors: AUTHOR_SEED'],
23
- },
24
- gallery: {
25
- label: 'Gallery',
26
- hint: 'media items with image, tags and featured flag',
27
- file: 'gallery.ts',
28
- registryEntries: ['gallery: GALLERY_SEED'],
29
- },
30
- contact: {
31
- label: 'Contact',
32
- hint: 'public form submissions with masked email and read status',
33
- file: 'contact.ts',
34
- registryEntries: ['messages: MESSAGE_SEED'],
35
- },
36
- }
37
-
38
- function readTemplate(filename) {
39
- return readFileSync(join(__dirname, 'templates', filename), 'utf8')
40
- }
41
-
42
- function buildSeedsFile(selectedKeys) {
43
- const header = `import type { Seed } from '@beechcms/core'\n\n`
44
-
45
- if (selectedKeys.length === 0) {
46
- const example = readFileSync(join(__dirname, 'templates', 'empty.ts'), 'utf8')
47
- return (
48
- header +
49
- example +
50
- '\nexport const SEED_REGISTRY: Record<string, Seed> = {}\n\n' +
51
- 'export function getSeed(slug: string): Seed | null {\n' +
52
- ' return SEED_REGISTRY[slug] ?? null\n' +
53
- '}\n'
54
- )
55
- }
56
-
57
- const blocks = selectedKeys.map((key) =>
58
- readFileSync(join(__dirname, 'templates', TEMPLATES[key].file), 'utf8')
59
- )
60
-
61
- const registryEntries = selectedKeys.flatMap((key) => TEMPLATES[key].registryEntries)
62
- const registry =
63
- 'export const SEED_REGISTRY: Record<string, Seed> = {\n' +
64
- registryEntries.map((e) => ` ${e},`).join('\n') +
65
- '\n}\n'
66
-
67
- const getSeed =
68
- '\nexport function getSeed(slug: string): Seed | null {\n' +
69
- ' return SEED_REGISTRY[slug] ?? null\n' +
70
- '}\n'
71
-
72
- return header + blocks.join('\n') + '\n' + registry + getSeed
73
- }
74
-
75
- // ── Helpers ───────────────────────────────────────────────────────────────────
76
-
77
- function generateSecret(bytes = 32) {
78
- return randomBytes(bytes).toString('hex')
79
- }
80
-
81
- function writeFile(path, content) {
82
- writeFileSync(path, content, 'utf8')
83
- }
84
-
85
- function buildWorkerTs() {
86
- return `/// <reference types="@cloudflare/workers-types" />
87
- import { createBeechApp } from '@beechcms/api'
88
- import { SEED_REGISTRY } from './seeds'
89
-
90
- export default createBeechApp({ seeds: SEED_REGISTRY })
91
- `
92
- }
93
-
94
- function buildSeedsTs(selectedKeys) {
95
- return buildSeedsFile(selectedKeys)
96
- }
97
-
98
- function buildPackageJson(name) {
99
- return JSON.stringify({
100
- name,
101
- version: '0.1.0',
102
- private: true,
103
- type: 'module',
104
- scripts: {
105
- dev: 'wrangler dev --port 8789',
106
- deploy: 'wrangler deploy --minify',
107
- 'seed:load': 'npx beech seed:load',
108
- 'seed:load:local': 'npx beech seed:load --local',
109
- 'db:migrate:local': 'wrangler d1 migrations apply ' + name + '-db --local',
110
- 'db:reset:local': 'node -e "require(\'fs\').rmSync(\'.wrangler/state\',{recursive:true,force:true})" && npm run db:migrate:local',
111
- },
112
- dependencies: {
113
- '@beechcms/api': '^0.4.0-preview.6',
114
- '@beechcms/core': '^0.4.0-preview.6',
115
- },
116
- devDependencies: {
117
- '@cloudflare/workers-types': '^4.0.0',
118
- wrangler: '^4.0.0',
119
- typescript: '^5.0.0',
120
- },
121
- }, null, 2) + '\n'
122
- }
123
-
124
- function buildWranglerJsonc(cfg) {
125
- return `{
126
- "name": "${cfg.name}-api",
127
- "main": "worker.ts",
128
- "compatibility_date": "2025-01-01",
129
-
130
- "vars": {
131
- "JWT_SECRET": "${cfg.jwtSecret}",
132
- "CORS_ORIGINS": "${cfg.corsOrigins}",
133
- "PUBLIC_READ_API_KEY": "${cfg.publicReadKey}",
134
- "PUBLIC_WRITE_API_KEY": "${cfg.publicWriteKey}",
135
- "APP_URL": "${cfg.appUrl || 'http://localhost:5173'}"
136
- },
137
-
138
- "assets": {
139
- "binding": "ASSETS",
140
- "directory": "node_modules/@beechcms/api/assets/dashboard"
141
- },
142
-
143
- "d1_databases": [
144
- {
145
- "binding": "DB",
146
- "database_name": "${cfg.d1Name}",
147
- "database_id": "${cfg.d1Id}",
148
- "migrations_dir": "node_modules/@beechcms/api/migrations"
149
- }
150
- ],
151
-
152
- "r2_buckets": [
153
- {
154
- "binding": "MEDIA_BUCKET",
155
- "bucket_name": "${cfg.r2Bucket}"
156
- }
157
- ]
158
- }
159
- `
160
- }
161
-
162
- function buildDevVars(cloudflare) {
163
- if (cloudflare) {
164
- return [
165
- `R2_ACCESS_KEY_ID=${cloudflare.r2AccessKey}`,
166
- `R2_SECRET_ACCESS_KEY=${cloudflare.r2SecretKey}`,
167
- `R2_ENDPOINT=${cloudflare.r2Endpoint}`,
168
- `R2_BUCKET_NAME=${cloudflare.r2Bucket}`,
169
- ].join('\n') + '\n'
170
- }
171
- return [
172
- '# Fill these in before starting the dev server.',
173
- '# Guide: https://developers.cloudflare.com/r2/api/s3/tokens/',
174
- 'R2_ACCESS_KEY_ID=',
175
- 'R2_SECRET_ACCESS_KEY=',
176
- 'R2_ENDPOINT=https://<YOUR_ACCOUNT_ID>.r2.cloudflarestorage.com',
177
- 'R2_BUCKET_NAME=',
178
- ].join('\n') + '\n'
179
- }
180
-
181
- function buildTsConfig() {
182
- return JSON.stringify({
183
- compilerOptions: {
184
- target: 'ES2022',
185
- module: 'ES2022',
186
- moduleResolution: 'bundler',
187
- strict: true,
188
- types: ['@cloudflare/workers-types'],
189
- },
190
- include: ['*.ts'],
191
- }, null, 2) + '\n'
192
- }
193
-
194
- // ── Cloudflare prompts ────────────────────────────────────────────────────────
195
-
196
- async function askCloudflareConfig(name) {
197
- p.note(
198
- [
199
- 'You will need a free Cloudflare account with:',
200
- '',
201
- ` D1 database → ${pc.cyan('npx wrangler d1 create ' + name + '-db')}`,
202
- ` R2 bucket → ${pc.cyan('npx wrangler r2 bucket create ' + name + '-media')}`,
203
- '',
204
- 'Docs: https://developers.cloudflare.com/d1/',
205
- ' https://developers.cloudflare.com/r2/',
206
- ].join('\n'),
207
- 'Prerequisites'
208
- )
209
-
210
- const accountId = await p.text({
211
- message: 'Cloudflare Account ID',
212
- hint: 'dash.cloudflare.com right sidebar → "Account ID"',
213
- validate: (v) => { if (!v.trim()) return 'Required' },
214
- })
215
- if (p.isCancel(accountId)) return null
216
-
217
- const d1Name = await p.text({
218
- message: 'D1 Database name',
219
- initialValue: `${name}-db`,
220
- validate: (v) => { if (!v.trim()) return 'Required' },
221
- })
222
- if (p.isCancel(d1Name)) return null
223
-
224
- const d1Id = await p.text({
225
- message: 'D1 Database ID',
226
- placeholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
227
- hint: `Run: npx wrangler d1 create ${d1Name} — copy the "database_id" from the output`,
228
- validate: (v) => { if (!v.trim()) return 'Required — create the D1 database first and paste its ID here' },
229
- })
230
- if (p.isCancel(d1Id)) return null
231
-
232
- const r2Bucket = await p.text({
233
- message: 'R2 Bucket name',
234
- initialValue: `${name}-media`,
235
- validate: (v) => { if (!v.trim()) return 'Required' },
236
- })
237
- if (p.isCancel(r2Bucket)) return null
238
-
239
- p.note(
240
- [
241
- 'Create an R2 API token:',
242
- ' Cloudflare Dashboard → R2 → "Manage R2 API Tokens"',
243
- ` → Create Token Object Read & Write → bucket: ${r2Bucket}`,
244
- ].join('\n'),
245
- 'R2 credentials'
246
- )
247
-
248
- const r2AccessKey = await p.text({
249
- message: 'R2 Access Key ID',
250
- validate: (v) => { if (!v.trim()) return 'Required' },
251
- })
252
- if (p.isCancel(r2AccessKey)) return null
253
-
254
- const r2SecretKey = await p.password({
255
- message: 'R2 Secret Access Key',
256
- validate: (v) => { if (!v.trim()) return 'Required' },
257
- })
258
- if (p.isCancel(r2SecretKey)) return null
259
-
260
- const appUrl = await p.text({
261
- message: 'Production dashboard URL (for CORS)',
262
- placeholder: `https://cms.${name}.com`,
263
- hint: 'Leave empty to configure later in wrangler.jsonc',
264
- })
265
- if (p.isCancel(appUrl)) return null
266
-
267
- return {
268
- accountId: accountId.trim(),
269
- d1Name: d1Name.trim(),
270
- d1Id: d1Id.trim(),
271
- r2Bucket: r2Bucket.trim(),
272
- r2AccessKey: r2AccessKey.trim(),
273
- r2SecretKey: r2SecretKey.trim(),
274
- r2Endpoint: `https://${accountId.trim()}.r2.cloudflarestorage.com`,
275
- appUrl: appUrl?.trim() ?? '',
276
- }
277
- }
278
-
279
- // ── Main ──────────────────────────────────────────────────────────────────────
280
-
281
- async function main() {
282
- const argv = process.argv.slice(2)
283
- const silent = argv.includes('--yes') || argv.includes('-y') || !process.stdout.isTTY
284
-
285
- console.log()
286
- p.intro(pc.bgGreen(pc.black(' @beechcms/cms ')))
287
-
288
- let name, selectedTemplates, cloudflare
289
-
290
- if (silent) {
291
- // Non-interactive: use first positional arg or default name, no templates, skip Cloudflare
292
- const positional = argv.find((a) => !a.startsWith('-'))
293
- name = positional ?? 'my-beech-project'
294
- selectedTemplates = []
295
- cloudflare = null
296
- console.log(pc.dim(` Running in non-interactive mode. Project name: ${name}`))
297
- } else {
298
- // Project name
299
- const projectName = await p.text({
300
- message: 'Project name',
301
- placeholder: 'my-website',
302
- validate: (v) => {
303
- if (!v.trim()) return 'Required'
304
- if (!/^[a-z0-9][a-z0-9-]*$/.test(v.trim())) return 'Lowercase letters, numbers and hyphens only'
305
- },
306
- })
307
- if (p.isCancel(projectName)) { p.cancel('Cancelled'); process.exit(0) }
308
- name = projectName.trim()
309
-
310
- // Content types
311
- const tmpl = await p.multiselect({
312
- message: 'Which content types do you need?',
313
- hint: 'Space to select, Enter to confirm. You can add more later in seeds.ts',
314
- options: [
315
- { value: 'blog', label: 'Blog', hint: 'posts with rich text, cover image, tags and authors' },
316
- { value: 'gallery', label: 'Gallery', hint: 'media items with image, tags and featured flag' },
317
- { value: 'contact', label: 'Contact', hint: 'public form submissions with masked email and read status' },
318
- ],
319
- required: false,
320
- })
321
- if (p.isCancel(tmpl)) { p.cancel('Cancelled'); process.exit(0) }
322
- selectedTemplates = tmpl
323
-
324
- // Cloudflare now or later?
325
- const configureNow = await p.confirm({
326
- message: 'Configure Cloudflare credentials now?',
327
- hint: 'Choose "No" to scaffold the project and fill in the values later',
328
- initialValue: true,
329
- })
330
- if (p.isCancel(configureNow)) { p.cancel('Cancelled'); process.exit(0) }
331
-
332
- if (configureNow) {
333
- cloudflare = await askCloudflareConfig(name)
334
- if (!cloudflare) { p.cancel('Cancelled'); process.exit(0) }
335
- }
336
- }
337
-
338
- const targetDir = resolve(process.cwd(), name)
339
- if (existsSync(targetDir)) {
340
- p.cancel(`Directory '${name}' already exists. Choose a different name or delete the folder.`)
341
- process.exit(1)
342
- }
343
-
344
- const jwtSecret = generateSecret(32)
345
- const publicReadKey = generateSecret(16)
346
- const publicWriteKey = generateSecret(16)
347
-
348
- const corsOrigins = cloudflare
349
- ? ['http://localhost:5173', 'http://localhost:5174', cloudflare.appUrl]
350
- .filter(Boolean).join(',')
351
- : 'http://localhost:5173,http://localhost:5174'
352
-
353
- // Scaffold
354
- const s = p.spinner()
355
- s.start('Scaffolding project…')
356
-
357
- mkdirSync(targetDir, { recursive: true })
358
-
359
- writeFile(join(targetDir, 'seeds.ts'), buildSeedsTs(selectedTemplates))
360
- writeFile(join(targetDir, 'worker.ts'), buildWorkerTs())
361
- writeFile(join(targetDir, 'package.json'), buildPackageJson(name))
362
- writeFile(join(targetDir, 'tsconfig.json'), buildTsConfig())
363
- writeFile(join(targetDir, 'wrangler.jsonc'), buildWranglerJsonc({
364
- name,
365
- d1Name: cloudflare?.d1Name ?? `${name}-db`,
366
- d1Id: cloudflare?.d1Id ?? 'FILL_IN_YOUR_D1_DATABASE_ID',
367
- r2Bucket: cloudflare?.r2Bucket ?? `${name}-media`,
368
- jwtSecret,
369
- corsOrigins,
370
- publicReadKey,
371
- publicWriteKey,
372
- appUrl: cloudflare?.appUrl ?? '',
373
- }))
374
- writeFile(join(targetDir, '.dev.vars'), buildDevVars(cloudflare))
375
- writeFile(join(targetDir, '.gitignore'), '.wrangler\nnode_modules\n.dev.vars\ndist\n')
376
-
377
- s.stop('Project scaffolded')
378
-
379
- // Init git
380
- s.start('Initialising git repository…')
381
- try {
382
- execSync(`git -C "${targetDir}" init -q`, { stdio: 'pipe' })
383
- execSync(`git -C "${targetDir}" add -A`, { stdio: 'pipe' })
384
- execSync(`git -C "${targetDir}" commit -q -m "feat: initialise BeechCMS project"`, { stdio: 'pipe' })
385
- s.stop('Git initialised')
386
- } catch {
387
- s.stop('Git skipped (not available)')
388
- }
389
-
390
- const pendingConfig = !cloudflare
391
- const step = (n) => pc.bold(String(n + (pendingConfig ? 1 : 0)))
392
- console.log()
393
- p.note(
394
- [
395
- `${pc.bold('1. Enter the project')}`,
396
- ` ${pc.cyan('cd ' + name)}`,
397
- '',
398
- `${pc.bold('2. Install dependencies')}`,
399
- ` ${pc.cyan('npm install')}`,
400
- '',
401
- ...(pendingConfig ? [
402
- `${pc.bold('3. Complete Cloudflare configuration')} ${pc.yellow('← pending')}`,
403
- ` Edit ${pc.underline('wrangler.jsonc')} → fill in ${pc.yellow('database_id')} and R2 bucket`,
404
- ` Edit ${pc.underline('.dev.vars')} → fill in R2 credentials`,
405
- ` Guide: https://developers.cloudflare.com/d1/`,
406
- '',
407
- ] : []),
408
- `${step(3)}. Run local migrations`,
409
- ` ${pc.cyan('npm run db:migrate:local')}`,
410
- '',
411
- `${step(4)}. Start the dev server`,
412
- ` ${pc.cyan('npx wrangler dev')}`,
413
- '',
414
- `${step(5)}. Deploy to production`,
415
- ` ${pc.cyan('npm run deploy')}`,
416
- '',
417
- `${pc.dim('Your content types are defined in seeds.ts')}`,
418
- `${pc.dim('JWT secret and API keys have been auto-generated.')}`,
419
- ].join('\n'),
420
- 'Next steps'
421
- )
422
- p.outro(pc.green(`✔ BeechCMS project ready ${name}/`))
423
- }
424
-
425
- main().catch((err) => {
426
- console.error(err)
427
- process.exit(1)
428
- })
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+
4
+ import * as p from '@clack/prompts'
5
+ import pc from 'picocolors'
6
+ import { execSync } from 'node:child_process'
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
8
+ import { resolve, join } from 'node:path'
9
+ import { randomBytes } from 'node:crypto'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { dirname } from 'node:path'
12
+
13
+ const __dirname = dirname(fileURLToPath(import.meta.url))
14
+
15
+ // ── Template registry ─────────────────────────────────────────────────────────
16
+
17
+ const TEMPLATES = {
18
+ blog: {
19
+ label: 'Blog',
20
+ hint: 'posts with rich text, cover image, tags and authors',
21
+ file: 'blog.ts',
22
+ registryEntries: ['posts: POST_SEED', 'authors: AUTHOR_SEED'],
23
+ },
24
+ gallery: {
25
+ label: 'Gallery',
26
+ hint: 'media items with image, tags and featured flag',
27
+ file: 'gallery.ts',
28
+ registryEntries: ['gallery: GALLERY_SEED'],
29
+ },
30
+ contact: {
31
+ label: 'Contact',
32
+ hint: 'public form submissions with masked email and read status',
33
+ file: 'contact.ts',
34
+ registryEntries: ['messages: MESSAGE_SEED'],
35
+ },
36
+ }
37
+
38
+ function readTemplate(filename) {
39
+ return readFileSync(join(__dirname, 'templates', filename), 'utf8')
40
+ }
41
+
42
+ function buildSeedsFile(selectedKeys) {
43
+ const header = `import type { Seed } from '@beechcms/core'\n\n`
44
+
45
+ if (selectedKeys.length === 0) {
46
+ const example = readFileSync(join(__dirname, 'templates', 'empty.ts'), 'utf8')
47
+ return (
48
+ header +
49
+ example +
50
+ '\nexport const SEED_REGISTRY: Record<string, Seed> = {}\n\n' +
51
+ 'export function getSeed(slug: string): Seed | null {\n' +
52
+ ' return SEED_REGISTRY[slug] ?? null\n' +
53
+ '}\n'
54
+ )
55
+ }
56
+
57
+ const blocks = selectedKeys.map((key) =>
58
+ readFileSync(join(__dirname, 'templates', TEMPLATES[key].file), 'utf8')
59
+ )
60
+
61
+ const registryEntries = selectedKeys.flatMap((key) => TEMPLATES[key].registryEntries)
62
+ const registry =
63
+ 'export const SEED_REGISTRY: Record<string, Seed> = {\n' +
64
+ registryEntries.map((e) => ` ${e},`).join('\n') +
65
+ '\n}\n'
66
+
67
+ const getSeed =
68
+ '\nexport function getSeed(slug: string): Seed | null {\n' +
69
+ ' return SEED_REGISTRY[slug] ?? null\n' +
70
+ '}\n'
71
+
72
+ return header + blocks.join('\n') + '\n' + registry + getSeed
73
+ }
74
+
75
+ // ── Helpers ───────────────────────────────────────────────────────────────────
76
+
77
+ function generateSecret(bytes = 32) {
78
+ return randomBytes(bytes).toString('hex')
79
+ }
80
+
81
+ function writeFile(path, content) {
82
+ writeFileSync(path, content, 'utf8')
83
+ }
84
+
85
+ function buildWorkerTs() {
86
+ return `/// <reference types="@cloudflare/workers-types" />
87
+ import { createBeechApp } from '@beechcms/api'
88
+ import { SEED_REGISTRY } from './seeds'
89
+
90
+ export default createBeechApp({ seeds: Object.values(SEED_REGISTRY) })
91
+ `
92
+ }
93
+
94
+ function buildSeedsTs(selectedKeys) {
95
+ return buildSeedsFile(selectedKeys)
96
+ }
97
+
98
+ function buildPackageJson(name) {
99
+ return JSON.stringify({
100
+ name,
101
+ version: '0.1.0',
102
+ private: true,
103
+ type: 'module',
104
+ scripts: {
105
+ dev: 'wrangler dev --port 8789',
106
+ deploy: 'wrangler deploy --minify',
107
+ 'seed:load': 'npx beech seed:load',
108
+ 'seed:load:local': 'npx beech seed:load --local',
109
+ 'db:migrate:local': 'wrangler d1 migrations apply ' + name + '-db --local',
110
+ 'db:reset:local': 'node -e "require(\'fs\').rmSync(\'.wrangler/state\',{recursive:true,force:true})" && npm run db:migrate:local',
111
+ },
112
+ dependencies: {
113
+ '@beechcms/api': '^0.4.0-preview.12',
114
+ '@beechcms/core': '^0.4.0-preview.12',
115
+ },
116
+ devDependencies: {
117
+ '@cloudflare/workers-types': '^4.0.0',
118
+ wrangler: '^4.0.0',
119
+ typescript: '^5.0.0',
120
+ },
121
+ }, null, 2) + '\n'
122
+ }
123
+
124
+ function buildWranglerJsonc(cfg) {
125
+ return `{
126
+ "name": "${cfg.name}-api",
127
+ "main": "worker.ts",
128
+ "compatibility_date": "2025-01-01",
129
+
130
+ "vars": {
131
+ "JWT_SECRET": "${cfg.jwtSecret}",
132
+ "CORS_ORIGINS": "${cfg.corsOrigins}",
133
+ "PUBLIC_READ_API_KEY": "${cfg.publicReadKey}",
134
+ "PUBLIC_WRITE_API_KEY": "${cfg.publicWriteKey}",
135
+ "APP_URL": "${cfg.appUrl || 'http://localhost:5173'}"
136
+ },
137
+
138
+ "assets": {
139
+ "binding": "ASSETS",
140
+ "directory": "node_modules/@beechcms/api/assets/dashboard"
141
+ },
142
+
143
+ "d1_databases": [
144
+ {
145
+ "binding": "DB",
146
+ "database_name": "${cfg.d1Name}",
147
+ "database_id": "${cfg.d1Id}",
148
+ "migrations_dir": "node_modules/@beechcms/api/migrations"
149
+ }
150
+ ],
151
+
152
+ "r2_buckets": [
153
+ {
154
+ "binding": "MEDIA_BUCKET",
155
+ "bucket_name": "${cfg.r2Bucket}"
156
+ }
157
+ ]
158
+ }
159
+ `
160
+ }
161
+
162
+ function buildDevVars(cloudflare) {
163
+ if (cloudflare) {
164
+ return [
165
+ `R2_ACCESS_KEY_ID=${cloudflare.r2AccessKey}`,
166
+ `R2_SECRET_ACCESS_KEY=${cloudflare.r2SecretKey}`,
167
+ `R2_ENDPOINT=${cloudflare.r2Endpoint}`,
168
+ `R2_BUCKET_NAME=${cloudflare.r2Bucket}`,
169
+ ].join('\n') + '\n'
170
+ }
171
+ return [
172
+ '# R2 credentials only needed if you want production-like S3 media uploads locally.',
173
+ '# For local development, media uploads work automatically via the Miniflare R2 binding.',
174
+ '# Fill these in only when testing production media behaviour:',
175
+ '# Guide: https://developers.cloudflare.com/r2/api/s3/tokens/',
176
+ 'R2_ACCESS_KEY_ID=',
177
+ 'R2_SECRET_ACCESS_KEY=',
178
+ 'R2_ENDPOINT=https://<YOUR_ACCOUNT_ID>.r2.cloudflarestorage.com',
179
+ 'R2_BUCKET_NAME=',
180
+ ].join('\n') + '\n'
181
+ }
182
+
183
+ function buildTsConfig() {
184
+ return JSON.stringify({
185
+ compilerOptions: {
186
+ target: 'ES2022',
187
+ module: 'ES2022',
188
+ moduleResolution: 'bundler',
189
+ strict: true,
190
+ types: ['@cloudflare/workers-types'],
191
+ },
192
+ include: ['*.ts'],
193
+ }, null, 2) + '\n'
194
+ }
195
+
196
+ // ── Cloudflare prompts ────────────────────────────────────────────────────────
197
+
198
+ async function askCloudflareConfig(name) {
199
+ p.note(
200
+ [
201
+ 'You will need a free Cloudflare account with:',
202
+ '',
203
+ ` D1 database → ${pc.cyan('npx wrangler d1 create ' + name + '-db')}`,
204
+ ` R2 bucket → ${pc.cyan('npx wrangler r2 bucket create ' + name + '-media')}`,
205
+ '',
206
+ 'Docs: https://developers.cloudflare.com/d1/',
207
+ ' https://developers.cloudflare.com/r2/',
208
+ ].join('\n'),
209
+ 'Prerequisites'
210
+ )
211
+
212
+ const accountId = await p.text({
213
+ message: 'Cloudflare Account ID',
214
+ hint: 'dash.cloudflare.com → right sidebar → "Account ID"',
215
+ validate: (v) => { if (!v.trim()) return 'Required' },
216
+ })
217
+ if (p.isCancel(accountId)) return null
218
+
219
+ const d1Name = await p.text({
220
+ message: 'D1 Database name',
221
+ initialValue: `${name}-db`,
222
+ validate: (v) => { if (!v.trim()) return 'Required' },
223
+ })
224
+ if (p.isCancel(d1Name)) return null
225
+
226
+ const d1Id = await p.text({
227
+ message: 'D1 Database ID',
228
+ placeholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
229
+ hint: `Run: npx wrangler d1 create ${d1Name} — copy the "database_id" from the output`,
230
+ validate: (v) => { if (!v.trim()) return 'Required — create the D1 database first and paste its ID here' },
231
+ })
232
+ if (p.isCancel(d1Id)) return null
233
+
234
+ const r2Bucket = await p.text({
235
+ message: 'R2 Bucket name',
236
+ initialValue: `${name}-media`,
237
+ validate: (v) => { if (!v.trim()) return 'Required' },
238
+ })
239
+ if (p.isCancel(r2Bucket)) return null
240
+
241
+ p.note(
242
+ [
243
+ 'Create an R2 API token:',
244
+ ' Cloudflare Dashboard → R2 → "Manage R2 API Tokens"',
245
+ ` → Create Token → Object Read & Write → bucket: ${r2Bucket}`,
246
+ ].join('\n'),
247
+ 'R2 credentials'
248
+ )
249
+
250
+ const r2AccessKey = await p.text({
251
+ message: 'R2 Access Key ID',
252
+ validate: (v) => { if (!v.trim()) return 'Required' },
253
+ })
254
+ if (p.isCancel(r2AccessKey)) return null
255
+
256
+ const r2SecretKey = await p.password({
257
+ message: 'R2 Secret Access Key',
258
+ validate: (v) => { if (!v.trim()) return 'Required' },
259
+ })
260
+ if (p.isCancel(r2SecretKey)) return null
261
+
262
+ const appUrl = await p.text({
263
+ message: 'Production dashboard URL (for CORS)',
264
+ placeholder: `https://cms.${name}.com`,
265
+ hint: 'Leave empty to configure later in wrangler.jsonc',
266
+ })
267
+ if (p.isCancel(appUrl)) return null
268
+
269
+ return {
270
+ accountId: accountId.trim(),
271
+ d1Name: d1Name.trim(),
272
+ d1Id: d1Id.trim(),
273
+ r2Bucket: r2Bucket.trim(),
274
+ r2AccessKey: r2AccessKey.trim(),
275
+ r2SecretKey: r2SecretKey.trim(),
276
+ r2Endpoint: `https://${accountId.trim()}.r2.cloudflarestorage.com`,
277
+ appUrl: appUrl?.trim() ?? '',
278
+ }
279
+ }
280
+
281
+ // ── Main ──────────────────────────────────────────────────────────────────────
282
+
283
+ async function main() {
284
+ const argv = process.argv.slice(2)
285
+ const silent = argv.includes('--yes') || argv.includes('-y') || !process.stdout.isTTY
286
+
287
+ console.log()
288
+ p.intro(pc.bgGreen(pc.black(' @beechcms/cms ')))
289
+
290
+ let name, selectedTemplates, cloudflare
291
+
292
+ if (silent) {
293
+ // Non-interactive: use first positional arg or default name, skip Cloudflare
294
+ const positional = argv.find((a) => !a.startsWith('-'))
295
+ name = positional ?? 'my-beech-project'
296
+ const withExamples = argv.includes('--with-examples') || argv.includes('--examples')
297
+ selectedTemplates = withExamples ? ['blog'] : []
298
+ cloudflare = null
299
+ const examplesNote = withExamples ? ' (with blog example content types)' : ''
300
+ console.log(pc.dim(` Running in non-interactive mode. Project name: ${name}${examplesNote}`))
301
+ } else {
302
+ // Project name
303
+ const projectName = await p.text({
304
+ message: 'Project name',
305
+ placeholder: 'my-website',
306
+ validate: (v) => {
307
+ if (!v.trim()) return 'Required'
308
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(v.trim())) return 'Lowercase letters, numbers and hyphens only'
309
+ },
310
+ })
311
+ if (p.isCancel(projectName)) { p.cancel('Cancelled'); process.exit(0) }
312
+ name = projectName.trim()
313
+
314
+ // Content types
315
+ const tmpl = await p.multiselect({
316
+ message: 'Which content types do you need?',
317
+ hint: 'Space to select, Enter to confirm. You can add more later in seeds.ts',
318
+ options: [
319
+ { value: 'blog', label: 'Blog', hint: 'posts with rich text, cover image, tags and authors' },
320
+ { value: 'gallery', label: 'Gallery', hint: 'media items with image, tags and featured flag' },
321
+ { value: 'contact', label: 'Contact', hint: 'public form submissions with masked email and read status' },
322
+ ],
323
+ required: false,
324
+ })
325
+ if (p.isCancel(tmpl)) { p.cancel('Cancelled'); process.exit(0) }
326
+ selectedTemplates = tmpl
327
+
328
+ // Cloudflare now or later?
329
+ const configureNow = await p.confirm({
330
+ message: 'Configure Cloudflare credentials now?',
331
+ hint: 'Choose "No" to scaffold the project and fill in the values later',
332
+ initialValue: true,
333
+ })
334
+ if (p.isCancel(configureNow)) { p.cancel('Cancelled'); process.exit(0) }
335
+
336
+ if (configureNow) {
337
+ cloudflare = await askCloudflareConfig(name)
338
+ if (!cloudflare) { p.cancel('Cancelled'); process.exit(0) }
339
+ }
340
+ }
341
+
342
+ const targetDir = resolve(process.cwd(), name)
343
+ if (existsSync(targetDir)) {
344
+ p.cancel(`Directory '${name}' already exists. Choose a different name or delete the folder.`)
345
+ process.exit(1)
346
+ }
347
+
348
+ const jwtSecret = generateSecret(32)
349
+ const publicReadKey = generateSecret(16)
350
+ const publicWriteKey = generateSecret(16)
351
+
352
+ const corsOrigins = cloudflare
353
+ ? ['http://localhost:5173', 'http://localhost:5174', cloudflare.appUrl]
354
+ .filter(Boolean).join(',')
355
+ : 'http://localhost:5173,http://localhost:5174'
356
+
357
+ // Scaffold
358
+ const s = p.spinner()
359
+ s.start('Scaffolding project…')
360
+
361
+ mkdirSync(targetDir, { recursive: true })
362
+
363
+ writeFile(join(targetDir, 'seeds.ts'), buildSeedsTs(selectedTemplates))
364
+ writeFile(join(targetDir, 'worker.ts'), buildWorkerTs())
365
+ writeFile(join(targetDir, 'package.json'), buildPackageJson(name))
366
+ writeFile(join(targetDir, 'tsconfig.json'), buildTsConfig())
367
+ writeFile(join(targetDir, 'wrangler.jsonc'), buildWranglerJsonc({
368
+ name,
369
+ d1Name: cloudflare?.d1Name ?? `${name}-db`,
370
+ d1Id: cloudflare?.d1Id ?? 'FILL_IN_YOUR_D1_DATABASE_ID',
371
+ r2Bucket: cloudflare?.r2Bucket ?? `${name}-media`,
372
+ jwtSecret,
373
+ corsOrigins,
374
+ publicReadKey,
375
+ publicWriteKey,
376
+ appUrl: cloudflare?.appUrl ?? '',
377
+ }))
378
+ writeFile(join(targetDir, '.dev.vars'), buildDevVars(cloudflare))
379
+ writeFile(join(targetDir, '.gitignore'), '.wrangler\nnode_modules\n.dev.vars\ndist\n')
380
+
381
+ s.stop('Project scaffolded')
382
+
383
+ // Init git
384
+ s.start('Initialising git repository…')
385
+ try {
386
+ execSync(`git -C "${targetDir}" init -q`, { stdio: 'pipe' })
387
+ execSync(`git -C "${targetDir}" add -A`, { stdio: 'pipe' })
388
+ execSync(`git -C "${targetDir}" commit -q -m "feat: initialise BeechCMS project"`, { stdio: 'pipe' })
389
+ s.stop('Git initialised')
390
+ } catch {
391
+ s.stop('Git skipped (not available)')
392
+ }
393
+
394
+ const pendingConfig = !cloudflare
395
+ const step = (n) => pc.bold(String(n + (pendingConfig ? 1 : 0)))
396
+ console.log()
397
+ p.note(
398
+ [
399
+ `${pc.bold('1. Enter the project')}`,
400
+ ` ${pc.cyan('cd ' + name)}`,
401
+ '',
402
+ `${pc.bold('2. Install dependencies')}`,
403
+ ` ${pc.cyan('npm install')}`,
404
+ '',
405
+ ...(pendingConfig ? [
406
+ `${pc.bold('3. Complete Cloudflare configuration')} ${pc.yellow('← pending')}`,
407
+ ` Edit ${pc.underline('wrangler.jsonc')} → fill in ${pc.yellow('database_id')} (D1) and ${pc.yellow('bucket_name')} (R2)`,
408
+ ` Guide: https://developers.cloudflare.com/d1/`,
409
+ ` ${pc.dim('Note: media uploads work locally without R2 credentials (.dev.vars optional)')}`,
410
+ '',
411
+ ] : []),
412
+ `${step(3)}. Run local migrations`,
413
+ ` ${pc.cyan('npm run db:migrate:local')}`,
414
+ '',
415
+ `${step(4)}. Start the dev server`,
416
+ ` ${pc.cyan('npx wrangler dev')}`,
417
+ ` Then open: ${pc.underline('http://localhost:8789/admin')}`,
418
+ '',
419
+ `${step(5)}. Deploy to production`,
420
+ ` ${pc.cyan('npm run deploy')}`,
421
+ '',
422
+ `${pc.dim('Your content types are defined in seeds.ts')}`,
423
+ `${pc.dim('JWT secret and API keys have been auto-generated.')}`,
424
+ ].join('\n'),
425
+ 'Next steps'
426
+ )
427
+ p.outro(pc.green(`✔ BeechCMS project ready — ${name}/`))
428
+ }
429
+
430
+ main().catch((err) => {
431
+ console.error(err)
432
+ process.exit(1)
433
+ })