@c-time/frelio-cli 1.8.1 → 2.1.0

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 (40) hide show
  1. package/README.md +60 -97
  2. package/dist/commands/add-staging.js +8 -8
  3. package/dist/commands/init.d.ts +1 -4
  4. package/dist/commands/init.js +37 -108
  5. package/dist/commands/set-domain.js +1 -1
  6. package/dist/commands/set-mode.js +1 -6
  7. package/dist/commands/update.d.ts +2 -2
  8. package/dist/commands/update.js +3 -8
  9. package/dist/core/__fixtures__/template/worker/index.d.ts +4 -0
  10. package/dist/core/__fixtures__/template/worker/index.js +6 -0
  11. package/dist/core/bundle.js +14 -12
  12. package/dist/core/cloudflare.d.ts +26 -11
  13. package/dist/core/cloudflare.js +28 -30
  14. package/dist/core/config.js +25 -6
  15. package/dist/core/doctor.js +6 -1
  16. package/dist/core/file-generators.d.ts +16 -13
  17. package/dist/core/file-generators.js +34 -52
  18. package/dist/core/index.d.ts +2 -3
  19. package/dist/core/index.js +2 -4
  20. package/dist/core/migrations/pages-to-workers-issue184.d.ts +28 -0
  21. package/dist/core/migrations/pages-to-workers-issue184.js +108 -0
  22. package/dist/core/migrations/registry.js +9 -1
  23. package/dist/core/migrations/types.d.ts +7 -0
  24. package/dist/core/site-mode.d.ts +5 -6
  25. package/dist/core/site-mode.js +5 -6
  26. package/dist/core/status.js +1 -2
  27. package/dist/core/template-refresh.d.ts +8 -2
  28. package/dist/core/template-refresh.js +63 -22
  29. package/dist/core/types.d.ts +0 -2
  30. package/dist/index.js +1 -4
  31. package/dist/lib/npm-registry.d.ts +4 -4
  32. package/dist/lib/npm-registry.js +4 -4
  33. package/dist/lib/resource-links.d.ts +1 -1
  34. package/dist/lib/resource-links.js +4 -4
  35. package/dist/lib/template-renderer.js +3 -6
  36. package/dist/lib/templates.d.ts +33 -57
  37. package/dist/lib/templates.js +82 -579
  38. package/package.json +3 -3
  39. package/dist/core/terraform.d.ts +0 -7
  40. package/dist/core/terraform.js +0 -47
@@ -10,19 +10,6 @@ export function resolveSiteMode(config) {
10
10
  const m = (config.siteMode ?? 'live');
11
11
  return SITE_MODES.includes(m) ? m : 'live';
12
12
  }
13
- /** productionUrl から正規化先ホスト(独自ドメイン)を導出する。無効/空なら空文字。 */
14
- export function deriveCanonicalHost(config) {
15
- try {
16
- return new URL(config.productionUrl).hostname;
17
- }
18
- catch {
19
- return '';
20
- }
21
- }
22
- /** コンテンツ配信 Pages の本番 pages.dev ホストを導出する(例: mysite.pages.dev)。 */
23
- export function deriveContentPagesDev(config) {
24
- return config.pagesProjectName ? `${config.pagesProjectName}.pages.dev` : '';
25
- }
26
13
  /**
27
14
  * ランダムな8文字のハッシュを生成(URL推測を困難にする)
28
15
  */
@@ -38,8 +25,8 @@ export function generateHash() {
38
25
  }
39
26
  /**
40
27
  * ランダムな8桁の16進サフィックスを生成(4バイト → hex)。
41
- * Pages プロジェクト名の世界的な衝突(Cloudflare の自動 `-mg1` 等)を避け、
42
- * `<project>.pages.dev` のプレビュー URL を推測困難にする(Issue #138)。
28
+ * Worker 名の世界的な衝突(Cloudflare の自動サフィックス等)を避け、
29
+ * `<worker>.workers.dev` のプレビュー URL を推測困難にする(Issue #138)。
43
30
  */
44
31
  export function generateHexSuffix() {
45
32
  const bytes = new Uint8Array(4);
@@ -47,20 +34,20 @@ export function generateHexSuffix() {
47
34
  return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
48
35
  }
49
36
  /**
50
- * Cloudflare Pages プロジェクト名(content 用・admin 用)を導出する(Issue #138)。
37
+ * Worker 名(content 用・admin 用)を導出する(Issue #138)。
51
38
  * randomSuffix=true なら content/admin それぞれに**別々の** hex サフィックスを付ける
52
39
  * (片方の名前が露出しても、もう片方を推測されないようにする)。
53
40
  *
54
- * 例: ("website", true) → { pagesProjectName: "website-1a2b3c4d",
55
- * adminPagesProjectName: "website-admin-e5f6a7b8" }
41
+ * 例: ("website", true) → { contentWorkerName: "website-1a2b3c4d",
42
+ * adminWorkerName: "website-admin-e5f6a7b8" }
56
43
  */
57
- export function buildPagesProjectNames(repoName, randomSuffix) {
44
+ export function buildWorkerNames(repoName, randomSuffix) {
58
45
  if (!randomSuffix) {
59
- return { pagesProjectName: repoName, adminPagesProjectName: `${repoName}-admin` };
46
+ return { contentWorkerName: repoName, adminWorkerName: `${repoName}-admin` };
60
47
  }
61
48
  return {
62
- pagesProjectName: `${repoName}-${generateHexSuffix()}`,
63
- adminPagesProjectName: `${repoName}-admin-${generateHexSuffix()}`,
49
+ contentWorkerName: `${repoName}-${generateHexSuffix()}`,
50
+ adminWorkerName: `${repoName}-admin-${generateHexSuffix()}`,
64
51
  };
65
52
  }
66
53
  /**
@@ -69,8 +56,7 @@ export function buildPagesProjectNames(repoName, randomSuffix) {
69
56
  *
70
57
  * productionUrl が無い/無効な場合は空文字を返す(カスタムドメイン無し)。
71
58
  * その場合プレビューは GitHub Actions の wrangler デプロイが生成する
72
- * ブランチエイリアス `staging.<project>.pages.dev` で運用する。
73
- * `*.pages.dev` の任意サブドメインは実在しないため、ここでは生成しない。
59
+ * プレビューエイリアス `<branch>-<worker>.<subdomain>.workers.dev` で運用する。
74
60
  */
75
61
  export function generateStagingDomain(productionUrl) {
76
62
  try {
@@ -117,24 +103,22 @@ export function generateConfigJson(config) {
117
103
  // ビジュアル編集・プレビューのベース URL(Issue #140)。未指定なら previewUrl を既定。
118
104
  // 未設定だと admin オリジンへフォールバックしコンテンツ資産を配信できないため明示出力する。
119
105
  templatePreviewBaseUrl: config.templatePreviewBaseUrl || config.previewUrl,
120
- pagesProjectName: config.pagesProjectName,
121
- adminPagesProjectName: config.adminPagesProjectName,
106
+ contentWorkerName: config.contentWorkerName,
107
+ adminWorkerName: config.adminWorkerName,
122
108
  r2BucketName: config.r2BucketName,
123
109
  r2PublicUrl: config.r2PublicUrl,
124
110
  // allowedOrigins は productionUrl / previewUrl からの派生値(単一ソース / Issue #24)。
125
- // wrangler.toml [vars] の ALLOWED_ORIGINS と同じ buildAllowedOrigins で導出し乖離を防ぐ。
111
+ // wrangler.admin.toml [vars] の ALLOWED_ORIGINS と同じ buildAllowedOrigins で導出し乖離を防ぐ。
126
112
  allowedOrigins: buildAllowedOrigins(config),
127
- // デプロイ管理機能(Issue #27)の表示用。account_id は非シークレットのため config.json に保持する。
128
- cloudflareAccountId: config.cloudflareAccountId ?? '',
129
113
  // 保存タイムゾーン(Issue #92)。日時の保存オフセット。
130
114
  saveTimezone: config.saveTimezone || '+09:00',
131
- // 本番ゲートのサイト公開状態(Issue #93)。エッジ実体は wrangler [vars] の SITE_MODE。
115
+ // サイト公開状態。実体はコンテンツ配信 Worker の worker/site-mode.ts に焼き込まれる。
132
116
  siteMode: resolveSiteMode(config),
133
117
  }, null, 2);
134
118
  }
135
119
  /**
136
120
  * CORS 許可オリジンの一覧を生成する(ローカル開発 + 本番/プレビュー)。
137
- * 管理画面 functions/api と file-upload Worker の双方で使用する。
121
+ * 管理画面 Worker(/api)と file-upload Worker の双方で使用する。
138
122
  */
139
123
  export function buildAllowedOrigins(config) {
140
124
  return [
@@ -144,60 +128,6 @@ export function buildAllowedOrigins(config) {
144
128
  config.previewUrl,
145
129
  ].filter(Boolean).join(',');
146
130
  }
147
- /**
148
- * ルートの wrangler.toml(Cloudflare Pages 設定)を生成する。
149
- *
150
- * Issue #23: `pages_build_output_dir` が無いと `wrangler pages deploy` が
151
- * 設定ファイルを丸ごと無視するため、R2 バインディング・環境変数がデプロイに
152
- * 反映されず、ダッシュボードでの手動設定が必須になっていた。
153
- *
154
- * このファイルはコンテンツ配信・管理画面の両 Pages デプロイで共用する:
155
- * - コンテンツ配信: `wrangler pages deploy public`(pages_build_output_dir と一致)
156
- * - 管理画面: `wrangler pages deploy .admin-deploy`(コマンドライン引数が優先)
157
- * デプロイ先ディレクトリと project 名はコマンドライン引数(`--project-name`)が
158
- * 優先されるため、1 ファイルで両デプロイに R2 バインディング・環境変数を適用できる。
159
- * いずれのデプロイ対象ディレクトリにも本ファイルは含まれない(公開されない)。
160
- */
161
- export function generateWranglerToml(config) {
162
- // デプロイ管理機能(Issue #27)の account_id(非シークレット)。
163
- // 空のときは行ごと出力しない: 空文字を [vars] に置くと wrangler pages deploy が
164
- // 実値/secret を毎デプロイで空上書きしてしまうため(Issue #137)。
165
- const accountIdBlock = config.cloudflareAccountId
166
- ? `# デプロイ管理機能(Issue #27): functions/api/deployments が Cloudflare Pages API を呼ぶのに使用。
167
- # CLOUDFLARE_API_TOKEN はシークレットのため wrangler pages secret で管理画面プロジェクトに設定する(ここには置かない)。
168
- CLOUDFLARE_ACCOUNT_ID = "${config.cloudflareAccountId}"
169
- `
170
- : '';
171
- return `# Cloudflare Pages 設定(コンテンツ配信・管理画面デプロイで共用 / Issue #23)
172
- # pages_build_output_dir を指定することで wrangler pages deploy が本ファイルを
173
- # 読み込み、R2 バインディングと環境変数をデプロイ時に自動適用する。
174
- # デプロイ先ディレクトリ・project 名はコマンドライン引数が優先される。
175
- name = "${config.pagesProjectName}"
176
- pages_build_output_dir = "public"
177
- compatibility_date = "2024-01-01"
178
-
179
- [[r2_buckets]]
180
- binding = "R2"
181
- bucket_name = "${config.r2BucketName}"
182
-
183
- # 環境変数(管理画面 functions/api が参照。コンテンツ配信側では未使用)
184
- [vars]
185
- R2_PUBLIC_URL = "${config.r2PublicUrl}"
186
- ALLOWED_ORIGINS = "${buildAllowedOrigins(config)}"
187
- CONTENT_REPO = "${config.contentRepo}"
188
- # 管理画面 OAuth の公開クライアントID(admin/config.json の githubClientId と同値)。
189
- # wrangler pages deploy は [vars] で plain env を置換するため、ここに置かないと
190
- # 毎デプロイで admin プロジェクトから消え、管理画面ログインが 500 になる(Issue #137)。
191
- GITHUB_CLIENT_ID = "${config.githubClientId}"
192
- ${accountIdBlock}PAGES_PROJECT_NAME = "${config.pagesProjectName}"
193
- # 本番ゲート(Issue #93): コンテンツ配信の functions/_middleware.ts がエッジで参照する。
194
- # SITE_MODE: live | prelaunch | maintenance | closed。
195
- # CANONICAL_HOST / CONTENT_PAGES_DEV は派生値(productionUrl ホスト / <project>.pages.dev)。
196
- SITE_MODE = "${resolveSiteMode(config)}"
197
- CANONICAL_HOST = "${deriveCanonicalHost(config)}"
198
- CONTENT_PAGES_DEV = "${deriveContentPagesDev(config)}"
199
- `;
200
- }
201
131
  export function generateWorkerWranglerToml(config) {
202
132
  const allowedOrigins = buildAllowedOrigins(config);
203
133
  return `name = "frelio-file-upload"
@@ -267,514 +197,87 @@ ${smtpBlock}
267
197
  crons = ["0 3 * * *"]
268
198
  `;
269
199
  }
270
- export function generateRedirects() {
271
- // 順序重要: 先にマッチしたルールが適用される
272
- return [
273
- '/admin/* /admin/index.html 200',
274
- '/* /public/:splat 200',
275
- '',
276
- ].join('\n');
277
- }
278
- export function generateRoutesJson() {
279
- return JSON.stringify({
280
- version: 1,
281
- include: ['/api/*', '/storage/*'],
282
- exclude: [],
283
- }, null, 2);
284
- }
285
200
  /**
286
- * コンテンツ配信側(public/)の _routes.json を生成する。
201
+ * コンテンツ配信 Worker の siteMode 焼き込みモジュール(worker/site-mode.ts)を生成する(Issue #184)。
287
202
  *
288
- * 本番ゲート(Issue #93)の functions/_middleware.ts に全リクエストを通すため
289
- * include を `/*` にする。これにより静的ページもエッジ middleware を経由する
290
- * (live モードでは即 next() で素通り)。
203
+ * siteMode をコード定数として焼き込む。変更は set-mode 後の再デプロイで反映する。
204
+ * テンプレ実ファイル(templates/content-repo/worker/site-mode.ts)と既定(live)で一致する。
291
205
  */
292
- export function generatePublicRoutesJson() {
293
- return JSON.stringify({
294
- version: 1,
295
- include: ['/*'],
296
- exclude: [],
297
- }, null, 2);
206
+ export function generateContentWorkerSiteMode(config) {
207
+ const mode = resolveSiteMode(config);
208
+ return `// このファイルは frelio-cli が config.json の siteMode から自動生成する(手動編集しない / Issue #184)。
209
+ // siteMode を変えるには \`npx @c-time/frelio-cli set-mode <mode>\` 実行後にコンテンツを再デプロイする。
210
+ // 値: live | prelaunch | maintenance | closed
211
+ export const SITE_MODE = '${mode}'
212
+ `;
298
213
  }
299
214
  /**
300
- * 本番ゲート middleware(Issue #93)を生成する。
215
+ * コンテンツ配信 Worker(Static Assets)の wrangler.toml を生成する(Issue #184)。
301
216
  *
302
- * 注意: この functions/ は管理画面 Pages にも配られる共有資産のため、
303
- * ホスト判定で「コンテンツのホスト」のみを対象にし、admin / staging /
304
- * localhost / 不明ホストは素通り(next)して CMS を保護する。
305
- *
306
- * テンプレート実ファイル
307
- * (templates/content-repo/functions/_middleware.ts)と同一文字列を返す。
308
- * 乖離は sync テストで検出する。
309
- */
310
- export function generateGateMiddleware() {
311
- return GATE_MIDDLEWARE_SOURCE;
312
- }
313
- const GATE_MIDDLEWARE_SOURCE = `/**
314
- * 本番ゲート middleware(Issue #93)
315
- *
316
- * コンテンツ配信 Pages のエッジで動作し、サイトの公開状態(siteMode)と
317
- * URL 正規化(pages.dev → 独自ドメイン 301)を制御する。
318
- *
319
- * 重要: この functions/ は管理画面 Pages にも配られる共有資産のため、
320
- * ホスト判定で「コンテンツのホスト」のみを対象にし、admin / staging /
321
- * localhost / 不明ホストは素通り(next)して CMS(/api/*)を保護する。
322
- *
323
- * 設定は wrangler.toml [vars](context.env)から読む:
324
- * SITE_MODE live | prelaunch | maintenance | closed(既定 live)
325
- * CANONICAL_HOST 正規化先ホスト(独自ドメイン。例 example.com)
326
- * CONTENT_PAGES_DEV コンテンツ Pages の本番ホスト(例 mysite.pages.dev)
217
+ * 静的アセット(SSG 出力 public/)は [assets] バインディング(ASSETS)から配信。
218
+ * /storage/* のみ run_worker_first で Worker を経由し R2 から配信する。
219
+ * siteMode が非 live のときは holding page を全リクエストで返すため run_worker_first=true にする。
327
220
  */
221
+ export function generateContentWorkerWranglerToml(config) {
222
+ const mode = resolveSiteMode(config);
223
+ const runWorkerFirst = mode === 'live' ? '["/storage/*"]' : 'true';
224
+ return `# コンテンツ配信 Worker(Cloudflare Workers Static Assets / Issue #184)
225
+ name = "${config.contentWorkerName}"
226
+ main = "worker/index.ts"
227
+ compatibility_date = "2024-09-23"
228
+ # 独自ドメインのみで配信し <project>.workers.dev は無効化する(旧 pages.dev→canonical 301 の代替)
229
+ workers_dev = false
230
+ # preview_urls は既定で workers_dev に従う(=false)ため、staging プレビューを残すには明示的に true。
231
+ # staging/staging-* は wrangler versions upload --preview-alias <branch> で
232
+ # <branch>-<worker>.<subdomain>.workers.dev の安定エイリアスを得る。
233
+ preview_urls = true
328
234
 
329
- interface GateEnv {
330
- SITE_MODE?: string
331
- CANONICAL_HOST?: string
332
- CONTENT_PAGES_DEV?: string
333
- }
334
-
335
- type GateDecision =
336
- | { action: 'next' }
337
- | { action: 'redirect'; location: string }
338
- | { action: 'block'; status: number }
339
-
340
- export function decideGate(
341
- host: string,
342
- pathname: string,
343
- search: string,
344
- env: GateEnv,
345
- ): GateDecision {
346
- const canonical = (env.CANONICAL_HOST || '').trim()
347
- const pagesDev = (env.CONTENT_PAGES_DEV || '').trim()
348
- const mode = (env.SITE_MODE || 'live').trim()
349
-
350
- const isCanonical = canonical !== '' && host === canonical
351
- const isPagesDev = pagesDev !== '' && host === pagesDev
352
-
353
- // コンテンツのホスト以外(admin / staging / localhost / 不明)は素通り = CMS 保護
354
- if (!isCanonical && !isPagesDev) return { action: 'next' }
355
-
356
- // pages.dev → 独自ドメインへ 301(canonical 設定時のみ)
357
- if (isPagesDev && !isCanonical && canonical !== '') {
358
- return { action: 'redirect', location: \`https://\${canonical}\${pathname}\${search}\` }
359
- }
360
-
361
- if (mode === 'live') return { action: 'next' }
362
-
363
- const isStorage = pathname === '/storage' || pathname.startsWith('/storage/')
364
-
365
- // 閉鎖: storage 含め全遮断(キルスイッチ)
366
- if (mode === 'closed') return { action: 'block', status: 503 }
367
- // プレ公開: storage 以外を 403(storage は CMS のサムネ/プレビュー用に配信継続)
368
- if (mode === 'prelaunch') {
369
- return isStorage ? { action: 'next' } : { action: 'block', status: 403 }
370
- }
371
- // メンテナンス: storage 以外を 503
372
- if (mode === 'maintenance') {
373
- return isStorage ? { action: 'next' } : { action: 'block', status: 503 }
374
- }
375
-
376
- // 未知の値は安全側(素通り)
377
- return { action: 'next' }
378
- }
379
-
380
- function holdingPage(status: number): string {
381
- const title = status === 403 ? '公開準備中' : 'メンテナンス中'
382
- const message =
383
- status === 403
384
- ? 'このサイトは現在準備中です。公開までしばらくお待ちください。'
385
- : 'ただいまメンテナンス中です。しばらく経ってから再度アクセスしてください。'
386
- return \`<!doctype html>
387
- <html lang="ja">
388
- <head>
389
- <meta charset="utf-8">
390
- <meta name="viewport" content="width=device-width, initial-scale=1">
391
- <meta name="robots" content="noindex">
392
- <title>\${title}</title>
393
- <style>
394
- body { font-family: system-ui, sans-serif; display: flex; min-height: 100vh; margin: 0; align-items: center; justify-content: center; background: #f5f5f5; color: #333; }
395
- .box { text-align: center; padding: 2rem; }
396
- h1 { font-size: 1.5rem; margin-bottom: 0.5rem; }
397
- p { color: #666; }
398
- </style>
399
- </head>
400
- <body>
401
- <div class="box"><h1>\${title}</h1><p>\${message}</p></div>
402
- </body>
403
- </html>
404
- \`
405
- }
406
-
407
- export const onRequest: PagesFunction<GateEnv> = async (context) => {
408
- const url = new URL(context.request.url)
409
- const decision = decideGate(url.hostname, url.pathname, url.search, context.env)
410
-
411
- if (decision.action === 'redirect') {
412
- return Response.redirect(decision.location, 301)
413
- }
414
- if (decision.action === 'block') {
415
- return new Response(holdingPage(decision.status), {
416
- status: decision.status,
417
- headers: {
418
- 'content-type': 'text/html; charset=utf-8',
419
- 'cache-control': 'no-store',
420
- },
421
- })
422
- }
423
- return context.next()
424
- }
425
- `;
426
- export function generateStorageFunction() {
427
- return `interface Env {
428
- R2: R2Bucket
429
- }
430
-
431
- export const onRequest: PagesFunction<Env> = async (context) => {
432
- const path = context.params.path
433
- const key = Array.isArray(path) ? path.join('/') : path
434
-
435
- if (!key) {
436
- return new Response('Not Found', { status: 404 })
437
- }
438
-
439
- const object = await context.env.R2.get(key)
440
- if (!object) {
441
- return new Response('Not Found', { status: 404 })
442
- }
443
-
444
- const headers = new Headers()
445
- headers.set(
446
- 'Content-Type',
447
- object.httpMetadata?.contentType || 'application/octet-stream',
448
- )
449
- headers.set('Cache-Control', 'public, max-age=31536000, immutable')
450
- headers.set('ETag', object.httpEtag)
451
-
452
- return new Response(object.body, { status: 200, headers })
453
- }
454
- `;
455
- }
456
- // --- Terraform generators ---
457
- export function generateTerraformProviders() {
458
- return `terraform {
459
- required_version = ">= 1.5.0"
460
-
461
- required_providers {
462
- cloudflare = {
463
- source = "cloudflare/cloudflare"
464
- version = "~> 5.0"
465
- }
466
- }
467
-
468
- # Cloudflare R2 をリモートバックエンドとして使う場合はコメントを外す:
469
- # backend "s3" {
470
- # bucket = "terraform-state"
471
- # key = "frelio/terraform.tfstate"
472
- # region = "auto"
473
- # skip_credentials_validation = true
474
- # skip_metadata_api_check = true
475
- # skip_region_validation = true
476
- # skip_requesting_account_id = true
477
- # skip_s3_checksum = true
478
- # endpoints = {
479
- # s3 = "https://<account_id>.r2.cloudflarestorage.com"
480
- # }
481
- # }
482
- }
483
-
484
- provider "cloudflare" {
485
- api_token = var.cloudflare_api_token
486
- }
487
- `;
488
- }
489
- export function generateTerraformVariables(config) {
490
- return `# --- 必須変数 ---
491
-
492
- variable "cloudflare_account_id" {
493
- type = string
494
- description = "Cloudflare Account ID"
495
- }
496
-
497
- variable "cloudflare_api_token" {
498
- type = string
499
- sensitive = true
500
- description = "Cloudflare API Token (Pages + R2 の操作権限が必要)"
501
- }
502
-
503
- variable "github_client_id" {
504
- type = string
505
- description = "GitHub OAuth App Client ID"
506
- }
507
-
508
- variable "github_client_secret" {
509
- type = string
510
- sensitive = true
511
- description = "GitHub OAuth App Client Secret"
512
- }
513
-
514
- # --- リソース名 ---
515
-
516
- variable "r2_bucket_name" {
517
- type = string
518
- default = "${config.r2BucketName}"
519
- description = "R2 バケット名"
520
- }
521
-
522
- variable "pages_project_name" {
523
- type = string
524
- default = "${config.pagesProjectName}"
525
- description = "コンテンツ配信 Pages プロジェクト名"
526
- }
527
-
528
- variable "admin_pages_project_name" {
529
- type = string
530
- default = "${config.adminPagesProjectName}"
531
- description = "管理画面 Pages プロジェクト名"
532
- }
533
-
534
- variable "r2_public_url" {
535
- type = string
536
- default = "${config.r2PublicUrl}"
537
- description = "R2 公開 URL(例: https://yourdomain.com/storage)"
538
- }
539
-
540
- # --- オプション: カスタムドメイン ---
541
-
542
- variable "production_domain" {
543
- type = string
544
- default = ""
545
- description = "本番カスタムドメイン(空なら *.pages.dev で運用)"
546
- }
547
-
548
- variable "admin_domain" {
549
- type = string
550
- default = ""
551
- description = "管理画面カスタムドメイン(空なら *.pages.dev で運用)"
552
- }
553
-
554
- variable "staging_domain" {
555
- type = string
556
- default = ""
557
- description = "ステージングカスタムドメイン(空ならブランチエイリアス staging.<project>.pages.dev で運用)"
558
- }
559
- `;
560
- }
561
- export function generateTerraformMain(config) {
562
- return `# --- R2 バケット ---
563
-
564
- resource "cloudflare_r2_bucket" "files" {
565
- account_id = var.cloudflare_account_id
566
- name = var.r2_bucket_name
567
- }
568
-
569
- # --- Pages プロジェクト(コンテンツ配信) ---
570
-
571
- resource "cloudflare_pages_project" "content" {
572
- account_id = var.cloudflare_account_id
573
- name = var.pages_project_name
574
- production_branch = "main"
575
- }
576
-
577
- # --- Pages プロジェクト(管理画面) ---
578
-
579
- resource "cloudflare_pages_project" "admin" {
580
- account_id = var.cloudflare_account_id
581
- name = var.admin_pages_project_name
582
- production_branch = "admin"
583
-
584
- deployment_configs {
585
- production {
586
- secrets = {
587
- GITHUB_CLIENT_SECRET = var.github_client_secret
588
- GITHUB_CLIENT_ID = var.github_client_id
589
- # デプロイ管理機能(Issue #27): functions/api/deployments が Cloudflare Pages API を呼ぶのに使用
590
- CLOUDFLARE_API_TOKEN = var.cloudflare_api_token
591
- }
592
- environment_variables = {
593
- R2_PUBLIC_URL = var.r2_public_url
594
- CLOUDFLARE_ACCOUNT_ID = var.cloudflare_account_id
595
- PAGES_PROJECT_NAME = var.pages_project_name
596
- }
597
- }
598
- }
599
- }
600
-
601
- # --- カスタムドメイン(オプション) ---
602
-
603
- resource "cloudflare_pages_domain" "production" {
604
- count = var.production_domain != "" ? 1 : 0
605
-
606
- account_id = var.cloudflare_account_id
607
- project_name = cloudflare_pages_project.content.name
608
- domain = var.production_domain
609
- }
610
-
611
- resource "cloudflare_pages_domain" "admin" {
612
- count = var.admin_domain != "" ? 1 : 0
613
-
614
- account_id = var.cloudflare_account_id
615
- project_name = cloudflare_pages_project.admin.name
616
- domain = var.admin_domain
617
- }
618
-
619
- resource "cloudflare_pages_domain" "staging" {
620
- count = var.staging_domain != "" ? 1 : 0
621
-
622
- account_id = var.cloudflare_account_id
623
- project_name = cloudflare_pages_project.content.name
624
- domain = var.staging_domain
625
- }
626
-
627
- # --- Workers(file-upload)---
628
- # Workers スクリプトは TypeScript のビルドが必要なため、
629
- # wrangler deploy で個別にデプロイすることを推奨。
630
- # Terraform で管理する場合は以下のコメントを外し、
631
- # ビルド済み JS バンドルのパスを workers_script_path に設定する。
632
- #
633
- # resource "cloudflare_workers_script" "file_upload" {
634
- # account_id = var.cloudflare_account_id
635
- # name = "frelio-file-upload"
636
- # content = file(var.workers_script_path)
637
- # module = true
638
- #
639
- # r2_bucket_binding {
640
- # name = "R2"
641
- # bucket_name = cloudflare_r2_bucket.files.name
642
- # }
643
- #
644
- # plain_text_binding {
645
- # name = "R2_PUBLIC_URL"
646
- # text = var.r2_public_url
647
- # }
648
- # }
649
-
650
- # --- Cloudflare Access(ステージング保護)---
651
- # ステージングサイトにアクセス制限を設ける場合はコメントを外す。
652
- #
653
- # resource "cloudflare_zero_trust_access_application" "staging" {
654
- # account_id = var.cloudflare_account_id
655
- # name = "Frelio Staging"
656
- # domain = var.staging_domain
657
- # type = "self_hosted"
658
- # session_duration = "24h"
659
- # auto_redirect_to_identity = false
660
- # }
661
- #
662
- # resource "cloudflare_zero_trust_access_policy" "staging_allow" {
663
- # account_id = var.cloudflare_account_id
664
- # application_id = cloudflare_zero_trust_access_application.staging.id
665
- # name = "Allow members"
666
- # decision = "allow"
667
- # precedence = 1
668
- #
669
- # include {
670
- # email = ["admin@example.com"]
671
- # }
672
- # }
673
- `;
674
- }
675
- export function generateTerraformOutputs() {
676
- return `output "r2_bucket_name" {
677
- value = cloudflare_r2_bucket.files.name
678
- description = "R2 バケット名"
679
- }
680
-
681
- output "content_pages_url" {
682
- value = "\${cloudflare_pages_project.content.name}.pages.dev"
683
- description = "コンテンツ配信 Pages URL"
684
- }
685
-
686
- output "admin_pages_url" {
687
- value = "\${cloudflare_pages_project.admin.name}.pages.dev"
688
- description = "管理画面 Pages URL"
689
- }
690
-
691
- output "production_domain" {
692
- value = length(cloudflare_pages_domain.production) > 0 ? cloudflare_pages_domain.production[0].domain : null
693
- description = "本番カスタムドメイン"
694
- }
695
-
696
- output "admin_domain" {
697
- value = length(cloudflare_pages_domain.admin) > 0 ? cloudflare_pages_domain.admin[0].domain : null
698
- description = "管理画面カスタムドメイン"
699
- }
700
- `;
701
- }
702
- export function generateTerraformTfvarsExample(config) {
703
- return `# Cloudflare
704
- cloudflare_account_id = "<YOUR_CLOUDFLARE_ACCOUNT_ID>"
705
- cloudflare_api_token = "<YOUR_CLOUDFLARE_API_TOKEN>"
706
-
707
- # GitHub OAuth
708
- github_client_id = "${config.githubClientId || '<YOUR_GITHUB_CLIENT_ID>'}"
709
- github_client_secret = "<YOUR_GITHUB_CLIENT_SECRET>"
710
-
711
- # リソース名
712
- r2_bucket_name = "${config.r2BucketName}"
713
- pages_project_name = "${config.pagesProjectName}"
714
- admin_pages_project_name = "${config.adminPagesProjectName}"
715
- r2_public_url = "${config.r2PublicUrl || '<YOUR_R2_PUBLIC_URL>'}"
235
+ [[r2_buckets]]
236
+ binding = "R2"
237
+ bucket_name = "${config.r2BucketName}"
716
238
 
717
- # カスタムドメイン(不要なら空文字のまま)
718
- production_domain = "${config.productionUrl ? new URL(config.productionUrl).hostname : ''}"
719
- admin_domain = ""
720
- staging_domain = "${config.stagingDomain}"
239
+ [assets]
240
+ directory = "./public"
241
+ binding = "ASSETS"
242
+ # 存在しない URL は public/404.html を 404 で配信(Pages の 404 慣例を踏襲)
243
+ not_found_handling = "404-page"
244
+ # siteMode=${mode}: live は /storage/* のみ Worker 経由(静的ページは Worker 非経由=コスト0)。
245
+ # 非 live は全リクエストを Worker 経由にして holding page(403/503) を返す。
246
+ run_worker_first = ${runWorkerFirst}
721
247
  `;
722
248
  }
723
- export function generateTerraformReadme() {
724
- return `# Terraform - Cloudflare インフラ管理
725
-
726
- Frelio で使用する Cloudflare リソースを Terraform で管理します。
727
-
728
- ## 前提条件
729
-
730
- - [Terraform CLI](https://developer.hashicorp.com/terraform/install) >= 1.5.0
731
- - Cloudflare API トークン(Pages + R2 の操作権限)
732
- - Cloudflare Dashboard → My Profile → API Tokens → Create Token
733
-
734
- ## セットアップ
735
-
736
- \`\`\`bash
737
- cd terraform
738
-
739
- # 1. 変数ファイルを作成
740
- cp terraform.tfvars.example terraform.tfvars
741
- # terraform.tfvars を編集し、実際の値を入力
742
-
743
- # 2. 初期化
744
- terraform init
745
-
746
- # 3. 変更確認
747
- terraform plan
748
-
749
- # 4. 適用
750
- terraform apply
751
- \`\`\`
752
-
753
- ## 注意事項
754
-
755
- - \`terraform.tfvars\` にはシークレットが含まれるため **git にコミットしないこと**
756
- - シークレットは環境変数でも設定可能: \`TF_VAR_cloudflare_api_token\`, \`TF_VAR_github_client_secret\`
757
- - Pages シークレットは write-only のため、\`terraform plan\` で常に差分が表示されます(正常動作)
758
-
759
- ## 既存リソースのインポート
760
-
761
- \`frelio init\`(wrangler ベース)で作成済みのリソースがある場合:
762
-
763
- \`\`\`bash
764
- # R2 バケット
765
- terraform import cloudflare_r2_bucket.files <account_id>/<bucket_name>
766
-
767
- # Pages プロジェクト(コンテンツ配信)
768
- terraform import cloudflare_pages_project.content <account_id>/<project_name>
249
+ /**
250
+ * 管理画面(CMS Admin)Worker の wrangler 設定(wrangler.admin.toml)を生成する(Issue #184 Phase 2)。
251
+ *
252
+ * admin の SPA は [assets](./admin)から配信し、SPA フォールバック
253
+ * (not_found_handling="single-page-application")でクライアントルーティングを成立させる。
254
+ * /api/* のみ Worker(admin-worker/index.js = esbuild バンドル済み)を経由する。
255
+ * シークレット(GITHUB_CLIENT_SECRET)は wrangler secret で投入する。
256
+ */
257
+ export function generateAdminWorkerWranglerToml(config) {
258
+ return `# 管理画面 Worker(Cloudflare Workers Static Assets / Issue #184 Phase 2)
259
+ name = "${config.adminWorkerName}"
260
+ main = "admin-worker/index.js"
261
+ compatibility_date = "2024-09-23"
769
262
 
770
- # Pages プロジェクト(管理画面)
771
- terraform import cloudflare_pages_project.admin <account_id>/<admin_project_name>
772
- \`\`\`
263
+ [[r2_buckets]]
264
+ binding = "R2"
265
+ bucket_name = "${config.r2BucketName}"
773
266
 
774
- ## リモートステート(チーム運用向け)
267
+ [assets]
268
+ directory = "./admin"
269
+ binding = "ASSETS"
270
+ # SPA: 未マッチ URL は index.html へフォールバック(クライアントサイドルーティング)
271
+ not_found_handling = "single-page-application"
272
+ # /api/* のみ Worker を経由(SPA アセットは直接配信=コスト0)
273
+ run_worker_first = ["/api/*"]
775
274
 
776
- デフォルトはローカルステートです。チームで運用する場合は \`providers.tf\` の
777
- S3 バックエンド設定をコメント解除し、Cloudflare R2 をリモートバックエンドとして使用できます。
275
+ [vars]
276
+ R2_PUBLIC_URL = "${config.r2PublicUrl}"
277
+ ALLOWED_ORIGINS = "${buildAllowedOrigins(config)}"
278
+ CONTENT_REPO = "${config.contentRepo}"
279
+ GITHUB_CLIENT_ID = "${config.githubClientId}"
280
+ # シークレットは wrangler secret put で投入: GITHUB_CLIENT_SECRET(OAuth)
778
281
  `;
779
282
  }
780
283
  /**