@c-time/frelio-cli 2.4.0 → 2.5.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.
@@ -8,16 +8,17 @@ import prompts from 'prompts';
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { log, logStep, logSuccess, logError, logWarning } from '../lib/shell.js';
11
- import { generateStagingDomain, buildWorkerNames, } from '../lib/templates.js';
11
+ import { buildWorkerNames, deriveFromAdminHost, derivePreviewUrl, } from '../lib/templates.js';
12
12
  import { buildResourceLinks } from '../lib/resource-links.js';
13
13
  import { validateContentRepo, validateR2PublicUrl, validateRequired, sanitizeCloudflareName, validateCloudflareName, } from '../lib/validators.js';
14
14
  // core functions
15
15
  import { checkPrerequisitesFor } from '../core/prerequisites.js';
16
16
  import { buildConfig } from '../core/config.js';
17
17
  import { createRepo, cloneRepo, getAuthenticatedUser } from '../core/github.js';
18
- import { setupCloudflareResources } from '../core/cloudflare.js';
18
+ import { createR2Bucket, setWorkerSecretByName, deployAdminWorker } from '../core/cloudflare.js';
19
19
  import { setupContactWorker } from '../core/contact.js';
20
20
  import { setupScheduledPublishWorker } from '../core/scheduled-publish.js';
21
+ import { setupFileDeliveryWorker } from '../core/file-delivery.js';
21
22
  import { createFullContentStructure } from '../core/content-structure.js';
22
23
  import { regenerateAllConfigFiles } from '../core/file-generators.js';
23
24
  import { installBundle } from '../core/bundle.js';
@@ -59,48 +60,20 @@ export async function initCommand(options) {
59
60
  // ── 予約反映(任意)──
60
61
  const scheduleInput = options.skipCloudflare ? null : await promptScheduledPublish();
61
62
  log('');
62
- // ── OAuth App 案内 ──
63
- log('🔑 GitHub OAuth App:');
64
- if (!config.githubClientId) {
65
- const isInteractive = process.stdin.isTTY === true;
66
- if (!isInteractive) {
67
- logError('非対話モードでは --client-id と --client-secret が必須です。');
68
- process.exit(1);
69
- }
70
- log(' ⚠ OAuth App は GitHub の Web UI で作成が必要です。');
71
- log(' → https://github.com/settings/developers');
72
- log(' → New OAuth App:');
73
- log(` - Application name: ${config.siteTitle || config.adminWorkerName} CMS`);
74
- log(` - Homepage URL: https://${config.adminWorkerName}.<your-subdomain>.workers.dev`);
75
- log(` - Callback URL: https://${config.adminWorkerName}.<your-subdomain>.workers.dev/api/auth/callback`);
76
- log(' (<your-subdomain> は管理画面 Worker 初回デプロイ後に確定する workers.dev サブドメイン。独自ドメイン運用ならそのドメインに読み替え)');
77
- log(' - Enable Device Flow: チェックしない(Disable のまま。Frelio は認可コードフローを使用)');
78
- log('');
79
- const oauthResponse = await prompts([
80
- {
81
- type: 'text',
82
- name: 'clientId',
83
- message: 'OAuth Client ID を入力:',
84
- validate: (v) => validateRequired(v, 'Client ID'),
85
- },
86
- {
87
- type: 'password',
88
- name: 'clientSecret',
89
- message: 'OAuth Client Secret を入力:',
90
- validate: (v) => validateRequired(v, 'Client Secret'),
91
- },
92
- ]);
93
- if (!oauthResponse.clientId) {
94
- log('セットアップをキャンセルしました。');
95
- process.exit(0);
96
- }
97
- config.githubClientId = oauthResponse.clientId;
98
- config.githubClientSecret =
99
- oauthResponse.clientSecret;
63
+ // ── ファイル限定配信(任意。フォーム送信後にダウンロード URL を期限付きメール配信)──
64
+ const fileDeliveryInput = options.skipCloudflare ? null : await promptFileDelivery(!!contactInput);
65
+ // 公開 URL を把握できていれば config.json(downloadApiUrl)へ焼き込む(後続の設定ファイル生成に反映)。
66
+ // 未確定(空)なら空のまま。初回デプロイ後に基本設定で設定する。
67
+ if (fileDeliveryInput?.publicBaseUrl) {
68
+ config.downloadApiUrl = fileDeliveryInput.publicBaseUrl;
100
69
  }
101
70
  log('');
71
+ // Issue #261: OAuth の収集は「管理画面 Worker のホスト確定後」に行う(下記 collectOAuth)。
72
+ // コールバック URL は admin のホストが決まらないと作れない(ニワトリ卵)ため、
73
+ // deploy-first(admin を一度デプロイしてホストを得る)か --admin-host 指定の後に収集する。
74
+ // 非対話で Client ID/Secret が未指定の場合は promptConfig 時点で既に弾かれている。
102
75
  // ── セットアップ実行 ──
103
- const totalSteps = getTotalSteps(options, !!contactInput, !!scheduleInput);
76
+ const totalSteps = getTotalSteps(options, !!contactInput, !!scheduleInput, !!fileDeliveryInput, !options.adminHost);
104
77
  let step = 0;
105
78
  // GitHub リポジトリ作成
106
79
  if (!options.skipGithub) {
@@ -186,38 +159,66 @@ export async function initCommand(options) {
186
159
  log(` ⚠ package-lock.json を生成できませんでした(${lockResult.error})。`);
187
160
  log(' デプロイ前に `npm install` を実行し、package-lock.json をコミットしてください。');
188
161
  }
189
- // Cloudflare セットアップ
162
+ // ── Cloudflare: R2 作成 → 管理画面 Worker のホスト確定(deploy-first / Issue #261)──
163
+ // workers.dev の「アカウント部」はアカウント固定値で、デプロイ前にはきれいに読めない。
164
+ // そこで admin Worker を一度デプロイし、その出力ホスト(<admin>.<account>.workers.dev)から
165
+ // アカウント部を取り出して実在 URL を確定する。--admin-host 指定時はデプロイ検出をスキップする。
166
+ let adminHost = (options.adminHost ?? '').trim();
167
+ let adminWorkerDeployed = false; // secret 投入はワーカー存在が前提(deploy 済みなら true)
190
168
  if (!options.skipCloudflare) {
191
169
  step++;
192
- logStep(step, totalSteps, 'Cloudflare セットアップ...');
193
- const secret = config.githubClientSecret;
194
- const cfResult = setupCloudflareResources(config, secret);
195
- if (cfResult.success) {
196
- const { r2Bucket, secrets, needsWorkersDevSubdomain } = cfResult.data;
197
- if (r2Bucket.success) {
198
- logSuccess(r2Bucket.alreadyExisted
199
- ? `R2 バケット "${config.r2BucketName}" は既に存在します`
200
- : `R2 バケット "${config.r2BucketName}" 作成完了`);
170
+ logStep(step, totalSteps, 'Cloudflare: R2 バケット作成...');
171
+ const r2Bucket = createR2Bucket(config.r2BucketName);
172
+ if (r2Bucket.success) {
173
+ logSuccess(r2Bucket.alreadyExisted
174
+ ? `R2 バケット "${config.r2BucketName}" は既に存在します`
175
+ : `R2 バケット "${config.r2BucketName}" 作成完了`);
176
+ }
177
+ else {
178
+ logError(r2Bucket.error);
179
+ }
180
+ // 管理画面 Worker のホストを確定する
181
+ if (!adminHost) {
182
+ step++;
183
+ logStep(step, totalSteps, '管理画面 Worker を初回デプロイしてホストを確定...');
184
+ const deployResult = deployAdminWorker(projectDir);
185
+ if (deployResult.success) {
186
+ adminHost = deployResult.data.host;
187
+ adminWorkerDeployed = true;
188
+ logSuccess(`管理画面 Worker をデプロイしました(${adminHost})`);
201
189
  }
202
190
  else {
203
- logError(r2Bucket.error);
204
- }
205
- // Issue #184: Worker は wrangler deploy 時に自動作成される(事前作成は不要)。
206
- // admin Worker のシークレット(GITHUB_CLIENT_SECRET)は
207
- // wrangler secret put が Worker を自動作成して設定する(初回デプロイ前でも可)。
208
- for (const s of secrets) {
209
- if (s.success) {
210
- logSuccess('admin Worker シークレット設定完了');
211
- }
212
- else {
213
- logError(s.error);
214
- }
215
- }
216
- if (needsWorkersDevSubdomain) {
217
- log(' ℹ staging プレビュー URL(<branch>-<worker>.<subdomain>.workers.dev)は、admin Worker の初回デプロイで workers.dev サブドメインが登録されてから有効になります。');
191
+ logError(deployResult.error);
192
+ log(' ⚠ ホストを自動確定できませんでした。確定済みなら `--admin-host <host>` を付けて再実行するか、');
193
+ log(' 初回デプロイ後に CMS「基本設定」で workers.dev サブドメイン等を設定してください。');
218
194
  }
219
195
  }
196
+ else {
197
+ logSuccess(`管理画面ホストを指定値で確定: ${adminHost}`);
198
+ }
199
+ }
200
+ else if (adminHost) {
201
+ logSuccess(`管理画面ホストを指定値で確定: ${adminHost}`);
202
+ }
203
+ // ホストが確定したら、workers.dev のアカウント部と preview URL を config に反映して再生成する。
204
+ if (adminHost) {
205
+ const d = deriveFromAdminHost(adminHost);
206
+ if (d.isWorkersDev && d.workersSubdomain) {
207
+ config.workersSubdomain = d.workersSubdomain;
208
+ }
209
+ // 独自の staging ドメインが未設定なら workers.dev から preview URL を導く(Issue #261)。
210
+ if (!config.stagingDomain) {
211
+ config.previewUrl = derivePreviewUrl({
212
+ workersSubdomain: config.workersSubdomain,
213
+ contentWorkerName: config.contentWorkerName,
214
+ });
215
+ }
216
+ const regen = regenerateAllConfigFiles(projectDir, config);
217
+ if (!regen.success)
218
+ logError(regen.error);
220
219
  }
220
+ // ── GitHub OAuth App(ホスト確定後に正確なコールバックを提示して収集)──
221
+ await collectAndApplyOAuth(config, options, projectDir, adminHost, adminWorkerDeployed);
221
222
  // お問い合わせワーカー(任意)
222
223
  if (contactInput) {
223
224
  step++;
@@ -257,6 +258,40 @@ export async function initCommand(options) {
257
258
  logError(scheduleResult.error);
258
259
  }
259
260
  }
261
+ // ファイル限定配信ワーカー(任意)
262
+ if (fileDeliveryInput) {
263
+ step++;
264
+ logStep(step, totalSteps, 'ファイル限定配信ワーカーのセットアップ(専用 R2・D1・wrangler.toml)...');
265
+ const deliveryResult = setupFileDeliveryWorker(projectDir, config, fileDeliveryInput);
266
+ if (deliveryResult.success) {
267
+ const d = deliveryResult.data;
268
+ logSuccess(d.bucketAlreadyExisted
269
+ ? `専用プライベート R2 バケット "${d.bucketName}" は既に存在します`
270
+ : `専用プライベート R2 バケット "${d.bucketName}" 作成完了`);
271
+ logSuccess(d.d1AlreadyExisted
272
+ ? `D1 "frelio_downloads" は既に存在します(id: ${d.databaseId})`
273
+ : `D1 "frelio_downloads" 作成完了(id: ${d.databaseId})`);
274
+ if (d.migrated)
275
+ logSuccess('D1 マイグレーション適用完了');
276
+ else
277
+ log(' ⚠ D1 マイグレーションは後で workers/file-delivery で `npx wrangler d1 migrations apply frelio_downloads --remote` を実行してください。');
278
+ if (d.wiredContact) {
279
+ logSuccess('contact ワーカーに DELIVERY Service Binding を配線しました(トークン発行が有効化)');
280
+ }
281
+ else if (fileDeliveryInput.wireContact) {
282
+ log(' ℹ contact ワーカーは既に DELIVERY 配線済みでした。');
283
+ }
284
+ else {
285
+ log(' ℹ お問い合わせ機能が未 opt-in のため DELIVERY 配線は行いませんでした。');
286
+ log(' 配信フォームには contact も必要です。後から contact をセットアップし、workers/contact/wrangler.toml に');
287
+ log(' [[services]] DELIVERY(entrypoint=DeliveryEntrypoint)を追記してください。');
288
+ }
289
+ logSuccess('ファイル限定配信ワーカーのセットアップ完了(deploy は workers/file-delivery で別途 → 基本設定で downloadApiUrl を設定)');
290
+ }
291
+ else {
292
+ logError(deliveryResult.error);
293
+ }
294
+ }
260
295
  // git identity 確認(commit 直前 — 未設定だとデフォルト値で commit author が埋まるのを防ぐ)
261
296
  if (!options.skipGithub) {
262
297
  step++;
@@ -279,7 +314,11 @@ export async function initCommand(options) {
279
314
  log('');
280
315
  log('✅ セットアップ完了!');
281
316
  log('');
282
- log(` 管理画面: https://${config.adminWorkerName}.<your-subdomain>.workers.dev/(admin Worker 初回デプロイ後)`);
317
+ // Issue #261: ホストが確定(deploy-first 検出 or --admin-host)していれば実在 URL、未確定ならプレースホルダ。
318
+ const adminDisplayUrl = adminHost
319
+ ? `https://${adminHost}/${adminWorkerDeployed ? '(デプロイ済み)' : ''}`
320
+ : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev/(admin Worker 初回デプロイ後)`;
321
+ log(` 管理画面: ${adminDisplayUrl}`);
283
322
  // カスタムドメイン未設定時は staging ブランチのプレビューエイリアス(GitHub Actions の
284
323
  // wrangler versions upload --preview-alias で生成)を案内する。
285
324
  log(` プレビュー: ${config.previewUrl || `https://staging-${config.contentWorkerName}.<your-subdomain>.workers.dev`}`);
@@ -327,7 +366,12 @@ export async function initCommand(options) {
327
366
  log(' ※ トークンは対象アカウント配下の「アカウント API トークン」推奨(他顧客アカウントを巻き込まない)');
328
367
  log(' 必要権限(アカウントスコープ3行): Workers スクリプト=編集 / Workers R2 ストレージ=編集 / アカウント設定=読み取り');
329
368
  log(' 詳細: packages/cli/README.md「GitHub Actions シークレットの設定」');
330
- log(' 2. admin ブランチへ push して管理画面 Worker を初回デプロイ(workers.dev サブドメインが登録される)');
369
+ if (adminWorkerDeployed) {
370
+ log(' 2. 管理画面 Worker は init でデプロイ済み。以降の更新は admin ブランチへの push(Actions)で反映');
371
+ }
372
+ else {
373
+ log(' 2. admin ブランチへ push して管理画面 Worker を初回デプロイ(workers.dev サブドメインが登録される)');
374
+ }
331
375
  log(' 3. staging ブランチへ push してコンテンツのプレビュー、main で本番デプロイ');
332
376
  if (config.stagingDomain) {
333
377
  log(` 4. プレビュー用カスタムドメインを設定: ${config.stagingDomain}`);
@@ -338,11 +382,103 @@ export async function initCommand(options) {
338
382
  log(' - お問い合わせフォーム: workers/contact/README.md(init で未設定なら後から)');
339
383
  log(' - 予約反映(時刻ベースの自動公開/非公開): workers/scheduled-publish/README.md を参照して');
340
384
  log(' ワーカーをデプロイ(PAT: Actions=RW / Contents=RO)→ 管理画面の「基本設定」→「予約反映 API URL」に設定');
385
+ log(' - ファイル限定配信(フォーム送信後にダウンロード URL を期限付きメール配信): workers/file-delivery/README.md を参照して');
386
+ log(' ワーカーをデプロイ → wrangler.toml の PUBLIC_BASE_URL と 管理画面「基本設定」→「downloadApiUrl」に実 URL を設定');
387
+ log(' (contact ワーカーとの併用が前提。contact/wrangler.toml の DELIVERY 配線が必要)');
341
388
  log('');
342
389
  }
343
390
  // ---------------------------------------------------------------------------
344
391
  // UI helpers (prompts — commands 層に閉じる)
345
392
  // ---------------------------------------------------------------------------
393
+ /**
394
+ * GitHub OAuth App のコールバックを「ホスト確定後」に提示し、Client ID/Secret を収集・反映する(Issue #261)。
395
+ *
396
+ * deploy-first(admin Worker を一度デプロイ)か --admin-host で admin のホストが確定していれば、
397
+ * 正確なコールバック URL(`https://<host>/api/auth/callback`)を提示してから収集できる=ニワトリ卵の解消。
398
+ * 収集後、Client ID を wrangler.admin.toml / config.json に焼き込み、ワーカーが存在すれば
399
+ * GITHUB_CLIENT_SECRET を投入して再デプロイする(OAuth [vars] を反映)。
400
+ */
401
+ async function collectAndApplyOAuth(config, options, projectDir, adminHost, adminWorkerDeployed) {
402
+ log('🔑 GitHub OAuth App:');
403
+ const d = adminHost ? deriveFromAdminHost(adminHost) : null;
404
+ const homepageUrl = d ? d.adminOrigin : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev`;
405
+ const callbackUrl = d
406
+ ? d.adminCallbackUrl
407
+ : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev/api/auth/callback`;
408
+ if (!config.githubClientId) {
409
+ const isInteractive = process.stdin.isTTY === true;
410
+ if (!isInteractive) {
411
+ logError('非対話モードでは --client-id と --client-secret が必須です。');
412
+ process.exit(1);
413
+ }
414
+ log(' ⚠ OAuth App は GitHub の Web UI で作成します(下の Callback URL を確定してから作成できます)。');
415
+ log(' → https://github.com/settings/developers → New OAuth App:');
416
+ log(` - Application name: ${config.siteTitle || config.adminWorkerName} CMS`);
417
+ log(` - Homepage URL: ${homepageUrl}`);
418
+ log(` - Callback URL: ${callbackUrl}`);
419
+ if (!d) {
420
+ log(' (管理画面ホストが未確定です。確定済みなら --admin-host <host> を付けて再実行すると正確な URL を提示します。');
421
+ log(' 独自ドメイン運用ならそのドメインに読み替え)');
422
+ }
423
+ else if (d.isWorkersDev) {
424
+ log(' (検出した実在 URL。独自ドメイン化したら set-domain 実行後に OAuth App の URL も更新)');
425
+ }
426
+ log(' - Enable Device Flow: チェックしない(Frelio は認可コードフローを使用)');
427
+ log('');
428
+ const oauthResponse = await prompts([
429
+ {
430
+ type: 'text',
431
+ name: 'clientId',
432
+ message: 'OAuth Client ID を入力:',
433
+ validate: (v) => validateRequired(v, 'Client ID'),
434
+ },
435
+ {
436
+ type: 'password',
437
+ name: 'clientSecret',
438
+ message: 'OAuth Client Secret を入力:',
439
+ validate: (v) => validateRequired(v, 'Client Secret'),
440
+ },
441
+ ], { onCancel: () => process.exit(0) });
442
+ if (!oauthResponse.clientId) {
443
+ log('セットアップをキャンセルしました。');
444
+ process.exit(0);
445
+ }
446
+ config.githubClientId = oauthResponse.clientId;
447
+ config.githubClientSecret = oauthResponse.clientSecret;
448
+ // Client ID([vars])を wrangler.admin.toml / config.json に焼き込む
449
+ const regen = regenerateAllConfigFiles(projectDir, config);
450
+ if (!regen.success)
451
+ logError(regen.error);
452
+ }
453
+ else {
454
+ // 非対話(--client-id 指定)など、既に Client ID 判明。コールバック URL を案内するのみ。
455
+ log(` OAuth コールバック URL(GitHub OAuth App に設定): ${callbackUrl}`);
456
+ }
457
+ log('');
458
+ // GITHUB_CLIENT_SECRET はワーカーが存在(deploy 済み)してからでないと投入できない。
459
+ const secret = config.githubClientSecret;
460
+ if (!options.skipCloudflare && secret) {
461
+ if (adminWorkerDeployed) {
462
+ const put = setWorkerSecretByName(config.adminWorkerName, 'GITHUB_CLIENT_SECRET', secret);
463
+ if (put.success) {
464
+ logSuccess('admin Worker に GITHUB_CLIENT_SECRET を設定しました');
465
+ // Client ID([vars])の反映のため admin Worker を再デプロイ(best-effort)
466
+ const redeploy = deployAdminWorker(projectDir);
467
+ if (redeploy.success)
468
+ logSuccess('admin Worker を再デプロイしました(OAuth 設定を反映)');
469
+ else
470
+ log(` ⚠ 再デプロイに失敗(${redeploy.error})。admin ブランチ push 時の Actions で反映されます。`);
471
+ }
472
+ else {
473
+ logError(put.error);
474
+ }
475
+ }
476
+ else {
477
+ log(' ⚠ admin Worker 未デプロイのため GITHUB_CLIENT_SECRET は未投入です。初回デプロイ後に設定してください:');
478
+ log(` npx wrangler secret put GITHUB_CLIENT_SECRET --name ${config.adminWorkerName}`);
479
+ }
480
+ }
481
+ }
346
482
  /**
347
483
  * commit 直前に git identity(user.name / user.email)を確認する。
348
484
  * 未設定の場合:
@@ -421,6 +557,54 @@ async function promptScheduledPublish() {
421
557
  return null;
422
558
  return { dispatchToken: res.dispatchToken };
423
559
  }
560
+ /**
561
+ * ファイル限定配信(任意)のセットアップ入力を集める。
562
+ * 「フォーム送信後にダウンロード URL を期限付きでメール配信」機能の受け皿。
563
+ * 対話モードのみ。スキップ/非対話なら null(=セットアップしない)。
564
+ *
565
+ * @param contactEnabled お問い合わせ機能を opt-in 済みか(DELIVERY 配線の可否)。
566
+ */
567
+ async function promptFileDelivery(contactEnabled) {
568
+ const isInteractive = process.stdin.isTTY === true;
569
+ if (!isInteractive)
570
+ return null;
571
+ log('📦 ファイル限定配信(任意・フォーム送信後にダウンロード URL を期限付きメール配信):');
572
+ log(' 専用のプライベート R2 バケット(<project>-downloads)と D1(frelio_downloads)を作成します。');
573
+ log(' ※ この機能はお問い合わせ機能(contact)と併用する前提です(フォーム送信を起点にトークン発行)。');
574
+ if (!contactEnabled) {
575
+ log(' ⚠ お問い合わせ機能が未 opt-in です。今セットアップしても、配信フォームを使うには後から contact も');
576
+ log(' セットアップし、DELIVERY Service Binding を配線する必要があります。');
577
+ }
578
+ const enable = await prompts({
579
+ type: 'confirm',
580
+ name: 'value',
581
+ message: 'ファイル限定配信ワーカーをセットアップしますか?(後からでも設定可)',
582
+ initial: false,
583
+ }, { onCancel: () => process.exit(0) });
584
+ if (!enable.value)
585
+ return null;
586
+ log(' このワーカーの公開ベース URL(PUBLIC_BASE_URL / CMS の downloadApiUrl と同じ値・末尾スラッシュ無し)。');
587
+ log(' 初回デプロイまで未確定なら空欄で Enter(後から wrangler.toml と基本設定で設定)。');
588
+ const res = await prompts([
589
+ {
590
+ type: 'text',
591
+ name: 'publicBaseUrl',
592
+ message: '公開ベース URL(任意, 例: https://frelio-file-delivery.<subdomain>.workers.dev):',
593
+ initial: '',
594
+ },
595
+ {
596
+ type: 'text',
597
+ name: 'tokenRetentionDays',
598
+ message: '失効/期限切れトークンの保持日数(Cron で掃除。0 で無効):',
599
+ initial: '30',
600
+ },
601
+ ], { onCancel: () => process.exit(0) });
602
+ return {
603
+ publicBaseUrl: res.publicBaseUrl || '',
604
+ tokenRetentionDays: res.tokenRetentionDays || '30',
605
+ wireContact: contactEnabled,
606
+ };
607
+ }
424
608
  async function promptContact(config) {
425
609
  const isInteractive = process.stdin.isTTY === true;
426
610
  if (!isInteractive)
@@ -577,10 +761,13 @@ async function promptConfig(options) {
577
761
  initial: '',
578
762
  },
579
763
  {
764
+ // Issue #261: 独自の staging ドメインは「終盤のオプショナル工程」。init では空が既定。
765
+ // productionUrl からの自動生成(staging-<hash>.<本番ホスト>)はやめる(NXDOMAIN 回避)。
766
+ // workers.dev のホストは init が admin Worker をデプロイして自動確定するため、ここでは尋ねない。
580
767
  type: options.stagingDomain !== undefined ? null : 'text',
581
768
  name: 'stagingDomain',
582
- message: 'ステージングのドメイン(推測困難なハッシュ付き推奨):',
583
- initial: (_prev, values) => generateStagingDomain((options.productionUrl || values.productionUrl) || ''),
769
+ message: 'ステージングの独自ドメイン(任意・通常は空。独自ドメインは後で set-domain で設定):',
770
+ initial: '',
584
771
  },
585
772
  {
586
773
  type: options.r2BucketName !== undefined ? null : 'text',
@@ -624,8 +811,15 @@ async function promptConfig(options) {
624
811
  const repoName = contentRepo.split('/')[1];
625
812
  const repoSlug = sanitizeCloudflareName(repoName);
626
813
  const stagingDomain = options.stagingDomain ?? response.stagingDomain ?? '';
627
- const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
814
+ // Issue #261: workers.dev のアカウント部は、--admin-host 指定があればそこから導く。
815
+ // 未指定なら init のデプロイ検出フェーズで確定する(ここでは空)。
816
+ const workersSubdomain = options.adminHost
817
+ ? deriveFromAdminHost(options.adminHost).workersSubdomain
818
+ : '';
628
819
  const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true, { contentWorkerName: options.contentWorkerName, adminWorkerName: options.adminWorkerName });
820
+ // previewUrl は独自 staging ドメイン優先、無ければ workers.dev サブドメインから
821
+ // CI の preview-alias 形式(staging-<contentWorker>.<sub>.workers.dev)を導く。
822
+ const previewUrl = derivePreviewUrl({ stagingDomain, workersSubdomain, contentWorkerName });
629
823
  const r2BucketName = options.r2BucketName ?? response.r2BucketName ?? `${repoSlug}-files`;
630
824
  // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare 呼び出し前)
631
825
  for (const [label, value] of [
@@ -649,6 +843,7 @@ async function promptConfig(options) {
649
843
  r2PublicUrl: options.r2PublicUrl ?? response.r2PublicUrl ?? '',
650
844
  contentWorkerName,
651
845
  adminWorkerName,
846
+ workersSubdomain,
652
847
  ownerUsername: options.ownerUsername ?? response.ownerUsername ?? '',
653
848
  stagingDomain,
654
849
  saveTimezone: '+09:00',
@@ -665,6 +860,7 @@ function buildConfigFromOptions(options) {
665
860
  siteTitle: options.siteTitle,
666
861
  productionUrl: options.productionUrl,
667
862
  stagingDomain: options.stagingDomain,
863
+ workersSubdomain: options.adminHost ? deriveFromAdminHost(options.adminHost).workersSubdomain : undefined,
668
864
  r2BucketName: options.r2BucketName,
669
865
  r2PublicUrl: options.r2PublicUrl,
670
866
  ownerUsername: options.ownerUsername,
@@ -689,15 +885,20 @@ function buildConfigFromOptions(options) {
689
885
  githubClientSecret: options.clientSecret,
690
886
  };
691
887
  }
692
- function getTotalSteps(options, withContact = false, withSchedule = false) {
888
+ function getTotalSteps(options, withContact = false, withSchedule = false, withFileDelivery = false, willDeployAdmin = false) {
693
889
  let steps = 4; // content structure (includes workflows), bundle, config files, lockfile
694
890
  if (!options.skipGithub)
695
891
  steps += 4; // create repo, clone, git identity, commit/push
696
- if (!options.skipCloudflare)
697
- steps += 1;
892
+ if (!options.skipCloudflare) {
893
+ steps += 1; // R2 bucket 作成
894
+ if (willDeployAdmin)
895
+ steps += 1; // deploy-first(admin Worker 初回デプロイでホスト確定)
896
+ }
698
897
  if (withContact)
699
898
  steps += 1;
700
899
  if (withSchedule)
701
900
  steps += 1;
901
+ if (withFileDelivery)
902
+ steps += 1;
702
903
  return steps;
703
904
  }
@@ -10,6 +10,7 @@ type SetDomainOptions = {
10
10
  previewUrl?: string;
11
11
  stagingDomain?: string;
12
12
  r2PublicUrl?: string;
13
+ downloadApiUrl?: string;
13
14
  regenStagingHash?: boolean;
14
15
  };
15
16
  export declare function setDomainCommand(options: SetDomainOptions): Promise<void>;
@@ -5,11 +5,19 @@
5
5
  * 派生ファイル(wrangler.toml ×2 等)を一括再生成する薄いオーケストレーター。
6
6
  * core/domain の changeDomain を呼ぶだけで、新規ロジックは持たない。
7
7
  */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
8
10
  import prompts from 'prompts';
9
11
  import { log, logSuccess, logError } from '../lib/shell.js';
10
12
  import { validateProductionUrl, validateR2PublicUrl } from '../lib/validators.js';
11
13
  import { readConfig } from '../core/config.js';
12
14
  import { changeDomain } from '../core/domain.js';
15
+ /** ファイル限定配信ワーカーが opt-in 済みか(config に downloadApiUrl があるか wrangler.toml が存在する) */
16
+ function isFileDeliveryOptedIn(projectDir, currentDownloadApiUrl) {
17
+ if (currentDownloadApiUrl)
18
+ return true;
19
+ return fs.existsSync(path.join(projectDir, 'workers', 'file-delivery', 'wrangler.toml'));
20
+ }
13
21
  export async function setDomainCommand(options) {
14
22
  log('');
15
23
  log('🌐 ドメイン / URL の変更');
@@ -26,10 +34,12 @@ export async function setDomainCommand(options) {
26
34
  process.exit(1);
27
35
  }
28
36
  const current = configResult.data.config;
37
+ const downloadOptedIn = isFileDeliveryOptedIn(projectDir, current.downloadApiUrl ?? '');
29
38
  const hasFlags = options.productionUrl !== undefined ||
30
39
  options.previewUrl !== undefined ||
31
40
  options.stagingDomain !== undefined ||
32
- options.r2PublicUrl !== undefined;
41
+ options.r2PublicUrl !== undefined ||
42
+ options.downloadApiUrl !== undefined;
33
43
  // フラグ検証(指定されたもののみ)
34
44
  if (options.productionUrl !== undefined) {
35
45
  const c = validateProductionUrl(options.productionUrl);
@@ -45,6 +55,13 @@ export async function setDomainCommand(options) {
45
55
  process.exit(1);
46
56
  }
47
57
  }
58
+ if (options.downloadApiUrl !== undefined) {
59
+ const c = validateProductionUrl(options.downloadApiUrl);
60
+ if (c !== true) {
61
+ logError(`--download-api-url: ${c}`);
62
+ process.exit(1);
63
+ }
64
+ }
48
65
  const isInteractive = process.stdin.isTTY === true;
49
66
  const change = {};
50
67
  if (hasFlags) {
@@ -56,6 +73,8 @@ export async function setDomainCommand(options) {
56
73
  change.stagingDomain = options.stagingDomain;
57
74
  if (options.r2PublicUrl !== undefined)
58
75
  change.r2PublicUrl = options.r2PublicUrl;
76
+ if (options.downloadApiUrl !== undefined)
77
+ change.downloadApiUrl = options.downloadApiUrl;
59
78
  if (options.regenStagingHash)
60
79
  change.regenStagingHash = true;
61
80
  }
@@ -69,6 +88,9 @@ export async function setDomainCommand(options) {
69
88
  log(` 本番 URL : ${current.productionUrl || '(未設定)'}`);
70
89
  log(` プレビュー URL: ${current.previewUrl || '(未設定)'}`);
71
90
  log(` R2 公開 URL : ${current.r2PublicUrl || '(未設定)'}`);
91
+ if (downloadOptedIn) {
92
+ log(` 配信ワーカー URL: ${current.downloadApiUrl || '(未設定)'}`);
93
+ }
72
94
  log('');
73
95
  const res = await prompts([
74
96
  {
@@ -85,6 +107,14 @@ export async function setDomainCommand(options) {
85
107
  initial: current.r2PublicUrl || '',
86
108
  validate: (v) => validateR2PublicUrl(v),
87
109
  },
110
+ // ファイル限定配信ワーカーが opt-in 済みのときだけ聞く(PUBLIC_BASE_URL = downloadApiUrl)
111
+ {
112
+ type: downloadOptedIn ? 'text' : null,
113
+ name: 'downloadApiUrl',
114
+ message: '新しいファイル配信ワーカー URL(PUBLIC_BASE_URL と同値・変更しない場合は空欄):',
115
+ initial: current.downloadApiUrl || '',
116
+ validate: (v) => validateProductionUrl(v),
117
+ },
88
118
  {
89
119
  type: (_, values) => values.productionUrl && values.productionUrl !== current.productionUrl
90
120
  ? 'confirm'
@@ -101,6 +131,9 @@ export async function setDomainCommand(options) {
101
131
  if (res.r2PublicUrl && res.r2PublicUrl !== current.r2PublicUrl) {
102
132
  change.r2PublicUrl = res.r2PublicUrl;
103
133
  }
134
+ if (res.downloadApiUrl && res.downloadApiUrl !== current.downloadApiUrl) {
135
+ change.downloadApiUrl = res.downloadApiUrl;
136
+ }
104
137
  if (res.regenStagingHash)
105
138
  change.regenStagingHash = true;
106
139
  }
@@ -121,6 +154,9 @@ export async function setDomainCommand(options) {
121
154
  log(` 本番 URL : ${config.productionUrl || '(未設定)'}`);
122
155
  log(` プレビュー URL: ${config.previewUrl || '(未設定)'}`);
123
156
  log(` R2 公開 URL : ${config.r2PublicUrl || '(未設定)'}`);
157
+ if (config.downloadApiUrl) {
158
+ log(` 配信ワーカー URL: ${config.downloadApiUrl}`);
159
+ }
124
160
  log('');
125
161
  log(' 再生成したファイル:');
126
162
  for (const p of regeneratedPaths) {
@@ -135,7 +171,16 @@ export async function setDomainCommand(options) {
135
171
  log(' 4. GitHub OAuth App の Homepage / Callback URL を新ドメインに更新');
136
172
  log(' 5. file-upload Worker を別運用している場合は再デプロイ:');
137
173
  log(' cd workers/file-upload && npx wrangler deploy');
138
- log(' 6. 本番反映は CMS の「直接デプロイ」フローで実行');
139
- log(' 7. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
174
+ if (change.downloadApiUrl !== undefined) {
175
+ log(' 6. ファイル限定配信 Worker を再デプロイ(PUBLIC_BASE_URL 更新を反映):');
176
+ log(' cd workers/file-delivery && npx wrangler deploy');
177
+ log(' ※ 独自ドメイン化した場合は Cloudflare Dashboard で該当 Worker の Routes / カスタムドメインも合わせる');
178
+ log(' 7. 本番反映は CMS の「直接デプロイ」フローで実行');
179
+ log(' 8. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
180
+ }
181
+ else {
182
+ log(' 6. 本番反映は CMS の「直接デプロイ」フローで実行');
183
+ log(' 7. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
184
+ }
140
185
  log('');
141
186
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * frelio validate-templates - テンプレートのデータ束縛を検証する
3
+ *
4
+ * core/validate-templates の runValidateTemplates を呼ぶ薄いオーケストレーター。
5
+ * html フィールドを data-gen-text(エスケープ出力)で束縛している箇所などを検出する。
6
+ * ビジュアルエディタが付ける <p> がエスケープされ、公開ページに生タグが露出する不具合を予防する。
7
+ */
8
+ type ValidateTemplatesOptions = {
9
+ ci?: boolean;
10
+ };
11
+ export declare function validateTemplatesCommand(options: ValidateTemplatesOptions): Promise<void>;
12
+ export {};
@@ -0,0 +1,44 @@
1
+ /**
2
+ * frelio validate-templates - テンプレートのデータ束縛を検証する
3
+ *
4
+ * core/validate-templates の runValidateTemplates を呼ぶ薄いオーケストレーター。
5
+ * html フィールドを data-gen-text(エスケープ出力)で束縛している箇所などを検出する。
6
+ * ビジュアルエディタが付ける <p> がエスケープされ、公開ページに生タグが露出する不具合を予防する。
7
+ */
8
+ import { log, logSuccess, logError, logWarning } from '../lib/shell.js';
9
+ import { runValidateTemplates } from '../core/validate-templates.js';
10
+ export async function validateTemplatesCommand(options) {
11
+ log('');
12
+ log('🔎 テンプレートのデータ束縛を検証(data-gen-text / data-gen-html)');
13
+ log('');
14
+ const result = runValidateTemplates(process.cwd());
15
+ if (!result.success) {
16
+ logError(result.error);
17
+ process.exit(1);
18
+ }
19
+ const { findings, scannedTemplateCount, errorCount, warnCount } = result.data;
20
+ if (findings.length === 0) {
21
+ logSuccess(`問題は見つかりませんでした(${scannedTemplateCount} テンプレートを確認)`);
22
+ log('');
23
+ return;
24
+ }
25
+ for (const f of findings) {
26
+ const line = ` ${f.file}:${f.line} : ${f.detail}`;
27
+ if (f.level === 'error')
28
+ logError(line);
29
+ else
30
+ logWarning(line);
31
+ }
32
+ log('');
33
+ log(` ${scannedTemplateCount} テンプレートを確認 / ERROR ${errorCount} 件 / WARN ${warnCount} 件`);
34
+ if (errorCount > 0) {
35
+ log('');
36
+ log(' html フィールドの本文は data-gen-html(生出力)で出力してください' +
37
+ '(data-gen-text はエスケープするため <p> 等のタグが文字として露出します)。');
38
+ }
39
+ log('');
40
+ // ERROR は常に非ゼロ終了(明確な不具合)。WARN のみのときは --ci 指定時のみ非ゼロ。
41
+ if (errorCount > 0 || (options.ci && warnCount > 0)) {
42
+ process.exit(1);
43
+ }
44
+ }