@c-time/frelio-cli 1.4.13 → 1.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.
package/README.md CHANGED
@@ -344,12 +344,20 @@ frelio update # バンドル+テンプレートを最新
344
344
  frelio update --version v1.2.0 # 特定バージョンのバンドルに更新
345
345
  frelio update --templates-only # ワークフロー/functions/wrangler のみ再生成(バンドルは触らない)
346
346
  frelio update --bundle-only # CMS Admin バンドルのみ更新(テンプレートは触らない)
347
- frelio update --force # 差分があるファイルもバックアップせず上書き
347
+ frelio update --force # 保護設定ファイルも含め上書き(保護ファイルはバックアップ付き)
348
348
  ```
349
349
 
350
- `--templates-only` を含むテンプレート再生成では、ユーザー改変を保護するため、既存ファイルと
351
- 差分があるファイルは既定で `*.frelio-bak` にバックアップしてから上書きする(`--force` で無効化)。
352
- `admin/config.json` / `frelio-data/` / `public/` / `functions/api/` は再生成対象外。
350
+ テンプレート再生成は、ファイルを2種類に分けて扱う:
351
+
352
+ - **保護設定ファイル**(`_redirects` / `wrangler.toml` / `workers/file-upload/wrangler.toml`):
353
+ ユーザーが恒常的にカスタムを足す前提のため、`config.json` と同様に**既定では上書きせず保持**する。
354
+ 差分を検出するとスキップして警告のみ表示する。更新するには `--force` を付ける(このとき
355
+ `*.frelio-bak` にユーザー版を退避してから上書きするので、移行した 301 リダイレクト等が失われても復旧できる)。
356
+ - **システム管理ファイル**(`.github/` ワークフロー / `functions/storage` / `functions/_middleware.ts` /
357
+ `_routes.json` / `public/_routes.json`): 差分があれば既定で `*.frelio-bak` にバックアップしてから
358
+ 上書きする(`--force` でバックアップなし上書き)。
359
+
360
+ `admin/config.json` / `frelio-data/` / `public/`(`_routes.json` を除く)/ `functions/api/` は再生成対象外。
353
361
 
354
362
  ---
355
363
 
@@ -16,6 +16,7 @@ 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
18
  import { setupCloudflareResources } from '../core/cloudflare.js';
19
+ import { setupContactWorker } from '../core/contact.js';
19
20
  import { createFullContentStructure } from '../core/content-structure.js';
20
21
  import { regenerateAllConfigFiles } from '../core/file-generators.js';
21
22
  import { generateTerraformFiles } from '../core/terraform.js';
@@ -52,6 +53,9 @@ export async function initCommand(options) {
52
53
  process.exit(0);
53
54
  }
54
55
  log('');
56
+ // ── お問い合わせ機能(任意)──
57
+ const contactInput = options.skipCloudflare || options.terraform ? null : await promptContact(config);
58
+ log('');
55
59
  // ── OAuth App 案内 ──
56
60
  log('🔑 GitHub OAuth App:');
57
61
  if (!config.githubClientId) {
@@ -92,7 +96,7 @@ export async function initCommand(options) {
92
96
  }
93
97
  log('');
94
98
  // ── セットアップ実行 ──
95
- const totalSteps = getTotalSteps(options);
99
+ const totalSteps = getTotalSteps(options, !!contactInput);
96
100
  let step = 0;
97
101
  // GitHub リポジトリ作成
98
102
  if (!options.skipGithub) {
@@ -217,6 +221,29 @@ export async function initCommand(options) {
217
221
  }
218
222
  }
219
223
  }
224
+ // お問い合わせワーカー(任意)
225
+ if (contactInput) {
226
+ step++;
227
+ logStep(step, totalSteps, 'お問い合わせワーカーのセットアップ(D1・シークレット)...');
228
+ const contactResult = setupContactWorker(projectDir, config, contactInput);
229
+ if (contactResult.success) {
230
+ logSuccess(contactResult.data.alreadyExisted
231
+ ? `D1 "frelio_contact" は既に存在します(id: ${contactResult.data.databaseId})`
232
+ : `D1 "frelio_contact" 作成完了(id: ${contactResult.data.databaseId})`);
233
+ if (contactResult.data.migrated)
234
+ logSuccess('D1 マイグレーション適用完了');
235
+ else
236
+ log(' ⚠ D1 マイグレーションは後で `npm run migrate:remote`(workers/contact)で適用してください。');
237
+ for (const s of contactResult.data.secrets) {
238
+ if (!s.success)
239
+ logError(s.error);
240
+ }
241
+ logSuccess('お問い合わせワーカーのセットアップ完了(deploy は workers/contact で別途実行)');
242
+ }
243
+ else {
244
+ logError(contactResult.error);
245
+ }
246
+ }
220
247
  // git identity 確認(commit 直前 — 未設定だとデフォルト値で commit author が埋まるのを防ぐ)
221
248
  if (!options.skipGithub) {
222
249
  step++;
@@ -333,6 +360,123 @@ async function ensureGitIdentity(projectDir, ownerUsername) {
333
360
  logError(result.error);
334
361
  }
335
362
  }
363
+ /**
364
+ * お問い合わせ機能(任意)のセットアップ入力を集める。
365
+ * 対話モードのみ。スキップ/非対話なら null(=セットアップしない)。
366
+ */
367
+ async function promptContact(config) {
368
+ const isInteractive = process.stdin.isTTY === true;
369
+ if (!isInteractive)
370
+ return null;
371
+ log('📨 お問い合わせ機能(任意・D1 + Turnstile + Web Push + 自動メール):');
372
+ const enable = await prompts({
373
+ type: 'confirm',
374
+ name: 'value',
375
+ message: 'お問い合わせ機能をセットアップしますか?(後からでも設定可)',
376
+ initial: false,
377
+ }, { onCancel: () => process.exit(0) });
378
+ if (!enable.value)
379
+ return null;
380
+ const adminInboxUrl = `https://${config.adminPagesProjectName}.pages.dev/inbox`;
381
+ const base = await prompts([
382
+ {
383
+ type: 'text',
384
+ name: 'turnstileSiteKey',
385
+ message: 'Turnstile サイトキー(公開値, 任意):',
386
+ initial: '',
387
+ },
388
+ {
389
+ type: 'password',
390
+ name: 'turnstileSecret',
391
+ message: 'Turnstile シークレット(任意):',
392
+ },
393
+ {
394
+ type: 'text',
395
+ name: 'vapidPublicKey',
396
+ message: 'VAPID 公開鍵(任意, `npx web-push generate-vapid-keys` で生成):',
397
+ initial: '',
398
+ },
399
+ {
400
+ type: 'password',
401
+ name: 'vapidPrivateKey',
402
+ message: 'VAPID 秘密鍵(任意):',
403
+ },
404
+ {
405
+ type: (_prev, values) => values.vapidPublicKey ? 'text' : null,
406
+ name: 'vapidSubject',
407
+ message: 'VAPID subject(例 mailto:admin@example.com):',
408
+ initial: '',
409
+ },
410
+ {
411
+ type: 'password',
412
+ name: 'contentRepoToken',
413
+ message: '設定読み取り用 PAT(contents:read, プライベート repo では必須・任意):',
414
+ },
415
+ ], { onCancel: () => process.exit(0) });
416
+ // SMTP(自動メール)
417
+ log('');
418
+ log(' ✉ 自動メール(SMTP)。Cloudflare は port 25 不可・587/465 を使う。空欄ならスキップ。');
419
+ const smtpPrompts = await prompts([
420
+ { type: 'text', name: 'host', message: 'SMTP ホスト(空欄でスキップ):', initial: '' },
421
+ {
422
+ type: (_prev, values) => (values.host ? 'text' : null),
423
+ name: 'port',
424
+ message: 'SMTP ポート(587=STARTTLS / 465=暗黙TLS):',
425
+ initial: '587',
426
+ },
427
+ {
428
+ type: (_prev, values) => (values.host ? 'confirm' : null),
429
+ name: 'secure',
430
+ message: '暗黙TLS を使う(465 の場合 Yes)?',
431
+ initial: false,
432
+ },
433
+ {
434
+ type: (_prev, values) => (values.host ? 'text' : null),
435
+ name: 'user',
436
+ message: 'SMTP ユーザー名:',
437
+ initial: '',
438
+ },
439
+ {
440
+ type: (_prev, values) => (values.host ? 'password' : null),
441
+ name: 'pass',
442
+ message: 'SMTP パスワード:',
443
+ },
444
+ {
445
+ type: (_prev, values) => (values.host ? 'text' : null),
446
+ name: 'from',
447
+ message: '送信元アドレス(MAIL_FROM):',
448
+ initial: '',
449
+ },
450
+ {
451
+ type: (_prev, values) => (values.host ? 'text' : null),
452
+ name: 'fromName',
453
+ message: '送信元表示名(任意):',
454
+ initial: config.siteTitle || '',
455
+ },
456
+ ], { onCancel: () => process.exit(0) });
457
+ let smtp;
458
+ if (smtpPrompts.host) {
459
+ smtp = {
460
+ host: smtpPrompts.host,
461
+ port: smtpPrompts.port || '587',
462
+ secure: smtpPrompts.secure === true,
463
+ user: smtpPrompts.user || '',
464
+ from: smtpPrompts.from || '',
465
+ fromName: smtpPrompts.fromName || undefined,
466
+ };
467
+ }
468
+ return {
469
+ adminInboxUrl,
470
+ turnstileSiteKey: base.turnstileSiteKey || undefined,
471
+ turnstileSecret: base.turnstileSecret || undefined,
472
+ vapidPublicKey: base.vapidPublicKey || undefined,
473
+ vapidPrivateKey: base.vapidPrivateKey || undefined,
474
+ vapidSubject: base.vapidSubject || undefined,
475
+ smtp,
476
+ smtpPass: smtpPrompts.pass || undefined,
477
+ contentRepoToken: base.contentRepoToken || undefined,
478
+ };
479
+ }
336
480
  async function promptConfig(options) {
337
481
  const isInteractive = process.stdin.isTTY === true;
338
482
  // 必須オプションが揃っている場合 → プロンプトスキップ
@@ -506,7 +650,7 @@ function buildConfigFromOptions(options) {
506
650
  cloudflareApiToken: options.cloudflareApiToken,
507
651
  };
508
652
  }
509
- function getTotalSteps(options) {
653
+ function getTotalSteps(options, withContact = false) {
510
654
  let steps = 3; // content structure (includes workflows), bundle, config files
511
655
  if (!options.skipGithub)
512
656
  steps += 4; // create repo, clone, git identity, commit/push
@@ -514,5 +658,7 @@ function getTotalSteps(options) {
514
658
  steps += 1;
515
659
  else if (!options.skipCloudflare)
516
660
  steps += 1;
661
+ if (withContact)
662
+ steps += 1;
517
663
  return steps;
518
664
  }
@@ -21,6 +21,10 @@ function printRefreshSummary(r) {
21
21
  log(` ℹ 上書き前にバックアップを作成(${r.backedUp.length}、*.frelio-bak):`);
22
22
  log(list(r.backedUp));
23
23
  }
24
+ if (r.preserved.length > 0) {
25
+ log(` 🛟 ユーザー編集を検出したため保持しました(${r.preserved.length}、更新するには --force で *.frelio-bak を作成して上書き):`);
26
+ log(list(r.preserved));
27
+ }
24
28
  if (r.skipped.length > 0) {
25
29
  log(` ⚠ 差分ありのため据え置き(${r.skipped.length}、--force で上書き):`);
26
30
  log(list(r.skipped));
@@ -67,7 +71,7 @@ export async function updateCommand(options) {
67
71
  else {
68
72
  log(' 📥 テンプレート(ワークフロー / functions / wrangler)を再生成中...');
69
73
  const refresh = await refreshTemplates(projectDir, config, {
70
- mode: options.force ? 'overwrite' : 'backup',
74
+ force: options.force,
71
75
  });
72
76
  if (!refresh.success) {
73
77
  logError(refresh.error);
@@ -84,6 +88,10 @@ export async function updateCommand(options) {
84
88
  log(' 2. `npx @c-time/frelio-cli doctor` で残課題が無いか確認');
85
89
  log(' 3. develop ブランチでコミットし、各ブランチへ反映');
86
90
  log('');
91
+ log(' ⚠ 管理画面(CMS Admin)は admin ブランチへの push でのみデプロイされます。');
92
+ log(' develop へマージしただけでは反映されません。次のように admin を進めてください:');
93
+ log(' git push origin origin/develop:admin # develop はメインブランチ名に読み替え');
94
+ log('');
87
95
  log(' ℹ デプロイ管理機能(Issue #27)を使う場合は次の環境変数が必要です:');
88
96
  log(' • CLOUDFLARE_API_TOKEN … 管理画面 Pages のシークレット(wrangler pages secret put)');
89
97
  log(' • CLOUDFLARE_ACCOUNT_ID … wrangler.toml の [vars]');
@@ -11,6 +11,13 @@ export declare function createPagesProject(projectName: string, productionBranch
11
11
  alreadyExisted: boolean;
12
12
  }>;
13
13
  export declare function setPagesSecret(projectName: string, secretName: string, secretValue: string): OperationResult;
14
+ /** D1 データベースを作成し database_id を返す(冪等: 既存はその ID を返す) */
15
+ export declare function createD1Database(name: string): OperationResult<{
16
+ databaseId: string;
17
+ alreadyExisted: boolean;
18
+ }>;
19
+ /** ワーカーのシークレットを設定する(cwd でワーカーディレクトリを指定) */
20
+ export declare function setWorkerSecret(secretName: string, secretValue: string, cwd: string): OperationResult;
14
21
  export type CloudflareSetupResult = {
15
22
  r2Bucket: OperationResult<{
16
23
  alreadyExisted: boolean;
@@ -47,6 +47,53 @@ export function setPagesSecret(projectName, secretName, secretValue) {
47
47
  return fail(`${secretName} の設定に失敗しました(${projectName}): ${e.message}`, 'EXEC_FAILED');
48
48
  }
49
49
  }
50
+ /** `wrangler d1 create` の出力 or `d1 info` から database_id を抜き出す */
51
+ function parseD1Id(output) {
52
+ const m = output.match(/database_id\s*=\s*"([0-9a-fA-F-]+)"/) ?? output.match(/"uuid":\s*"([0-9a-fA-F-]+)"/);
53
+ return m ? m[1] : null;
54
+ }
55
+ /** 既存 D1 の database_id を一覧から引く */
56
+ function findExistingD1Id(name) {
57
+ try {
58
+ const out = exec(`wrangler d1 list --json`, { silent: true });
59
+ const list = JSON.parse(out);
60
+ const found = list.find((d) => d.name === name);
61
+ return found?.uuid ?? null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ /** D1 データベースを作成し database_id を返す(冪等: 既存はその ID を返す) */
68
+ export function createD1Database(name) {
69
+ try {
70
+ const out = exec(`wrangler d1 create ${name}`, { silent: true });
71
+ const id = parseD1Id(out) ?? findExistingD1Id(name);
72
+ if (!id)
73
+ return fail(`D1 "${name}" の database_id を取得できませんでした`, 'EXEC_FAILED');
74
+ return ok({ databaseId: id, alreadyExisted: false });
75
+ }
76
+ catch (error) {
77
+ const msg = error.message;
78
+ if (msg.includes('already exists')) {
79
+ const id = findExistingD1Id(name);
80
+ if (id)
81
+ return ok({ databaseId: id, alreadyExisted: true }, true);
82
+ return fail(`D1 "${name}" は既に存在しますが ID を取得できませんでした: ${msg}`, 'ALREADY_EXISTS');
83
+ }
84
+ return fail(`D1 作成失敗: ${msg}`, 'EXEC_FAILED');
85
+ }
86
+ }
87
+ /** ワーカーのシークレットを設定する(cwd でワーカーディレクトリを指定) */
88
+ export function setWorkerSecret(secretName, secretValue, cwd) {
89
+ try {
90
+ exec(`echo "${secretValue}" | wrangler secret put ${secretName}`, { cwd, silent: true });
91
+ return okVoid();
92
+ }
93
+ catch (e) {
94
+ return fail(`${secretName} の設定に失敗しました: ${e.message}`, 'EXEC_FAILED');
95
+ }
96
+ }
50
97
  export function setupCloudflareResources(config, githubClientSecret, cloudflareApiToken) {
51
98
  const r2Bucket = createR2Bucket(config.r2BucketName);
52
99
  const contentPages = createPagesProject(config.pagesProjectName, 'main');
@@ -0,0 +1,32 @@
1
+ /**
2
+ * core/contact — お問い合わせワーカー(workers/contact)のセットアップ
3
+ *
4
+ * 任意機能。D1 作成 → マイグレーション → wrangler.toml 生成 → シークレット投入。
5
+ * file-upload と異なり database_id を含むため wrangler.toml は init 時に一度だけ生成し、
6
+ * update では上書きしない(template-refresh の PROTECTED_CONFIG)。
7
+ */
8
+ import { type ProjectConfig, type OperationResult } from './types.js';
9
+ import { type ContactSmtpConfig } from '../lib/templates.js';
10
+ export type ContactSetupInput = {
11
+ /** 通知クリックで開く CMS 受信箱 URL */
12
+ adminInboxUrl: string;
13
+ turnstileSiteKey?: string;
14
+ turnstileSecret?: string;
15
+ vapidPublicKey?: string;
16
+ vapidPrivateKey?: string;
17
+ vapidSubject?: string;
18
+ /** SMTP 自動メール設定(省略時は無効) */
19
+ smtp?: ContactSmtpConfig;
20
+ /** SMTP パスワード(secret) */
21
+ smtpPass?: string;
22
+ /** 設定 JSON 読み取り用 PAT(contents:read、secret) */
23
+ contentRepoToken?: string;
24
+ };
25
+ export type ContactSetupResult = {
26
+ databaseId: string;
27
+ alreadyExisted: boolean;
28
+ migrated: boolean;
29
+ secrets: OperationResult[];
30
+ };
31
+ /** お問い合わせワーカーをセットアップする */
32
+ export declare function setupContactWorker(projectDir: string, config: ProjectConfig, input: ContactSetupInput): OperationResult<ContactSetupResult>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * core/contact — お問い合わせワーカー(workers/contact)のセットアップ
3
+ *
4
+ * 任意機能。D1 作成 → マイグレーション → wrangler.toml 生成 → シークレット投入。
5
+ * file-upload と異なり database_id を含むため wrangler.toml は init 時に一度だけ生成し、
6
+ * update では上書きしない(template-refresh の PROTECTED_CONFIG)。
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { ok, fail } from './types.js';
11
+ import { createD1Database, setWorkerSecret } from './cloudflare.js';
12
+ import { generateContactWranglerToml } from '../lib/templates.js';
13
+ import { exec } from '../lib/shell.js';
14
+ const D1_NAME = 'frelio_contact';
15
+ const WORKER_SUBDIR = 'workers/contact';
16
+ /** お問い合わせワーカーをセットアップする */
17
+ export function setupContactWorker(projectDir, config, input) {
18
+ const workerDir = path.join(projectDir, WORKER_SUBDIR);
19
+ if (!fs.existsSync(workerDir)) {
20
+ return fail(`お問い合わせワーカーが見つかりません(${WORKER_SUBDIR})。バンドル展開を先に行ってください。`, 'NOT_FOUND');
21
+ }
22
+ // 1. D1 作成
23
+ const d1 = createD1Database(D1_NAME);
24
+ if (!d1.success)
25
+ return d1;
26
+ // 2. wrangler.toml 生成(database_id を埋め込む)
27
+ const toml = generateContactWranglerToml(config, {
28
+ databaseId: d1.data.databaseId,
29
+ adminInboxUrl: input.adminInboxUrl,
30
+ turnstileSiteKey: input.turnstileSiteKey,
31
+ smtp: input.smtp,
32
+ });
33
+ fs.writeFileSync(path.join(workerDir, 'wrangler.toml'), toml, 'utf-8');
34
+ // 3. マイグレーション適用(リモート)
35
+ let migrated = false;
36
+ try {
37
+ exec(`wrangler d1 migrations apply ${D1_NAME} --remote`, { cwd: workerDir, silent: true });
38
+ migrated = true;
39
+ }
40
+ catch {
41
+ // マイグレーション失敗は致命的ではない(後で手動適用可能)
42
+ migrated = false;
43
+ }
44
+ // 4. シークレット投入
45
+ const secrets = [];
46
+ const putSecret = (name, value) => {
47
+ if (value)
48
+ secrets.push(setWorkerSecret(name, value, workerDir));
49
+ };
50
+ putSecret('VAPID_PUBLIC_KEY', input.vapidPublicKey);
51
+ putSecret('VAPID_PRIVATE_KEY', input.vapidPrivateKey);
52
+ putSecret('VAPID_SUBJECT', input.vapidSubject);
53
+ putSecret('TURNSTILE_SECRET', input.turnstileSecret);
54
+ putSecret('SMTP_PASS', input.smtpPass);
55
+ putSecret('CONTENT_REPO_TOKEN', input.contentRepoToken);
56
+ return ok({
57
+ databaseId: d1.data.databaseId,
58
+ alreadyExisted: d1.alreadyExisted === true,
59
+ migrated,
60
+ secrets,
61
+ });
62
+ }
@@ -9,8 +9,12 @@
9
9
  * - wrangler.toml / functions/storage / _redirects / _routes.json は config から決定的に生成する
10
10
  * (lib/templates.ts の生成関数を共有。set-domain と同一の正本)
11
11
  *
12
- * ユーザー改変を保護するため、既存ファイルと差分がある場合は競合モードに従う
13
- * (既定 backup: <file>.frelio-bak に退避してから上書き)。
12
+ * ユーザー改変を保護するため、ファイルを2種類に分けて扱う(Issue #150):
13
+ * - 保護設定ファイル(_redirects / wrangler.toml / workers/file-upload/wrangler.toml):
14
+ * 既定では上書きせず保持する(config.json と同様)。--force のときのみ
15
+ * <file>.frelio-bak に退避してから上書きする。
16
+ * - システム管理ファイル(.github / functions / _routes.json 等):
17
+ * 差分があれば既定 backup(<file>.frelio-bak に退避してから上書き)、--force で無バックアップ上書き。
14
18
  *
15
19
  * frelio-data/・public/・admin/config.json・functions/api/・workers/file-upload/src は触らない。
16
20
  */
@@ -28,10 +32,23 @@ export type RefreshResult = {
28
32
  skipped: string[];
29
33
  /** .frelio-bak を作成したファイル */
30
34
  backedUp: string[];
35
+ /** ユーザー編集を検出したため保持した保護設定ファイル(Issue #150。--force で上書き可) */
36
+ preserved: string[];
31
37
  };
32
38
  export type RefreshOptions = {
33
39
  targets?: RefreshTarget[];
40
+ /**
41
+ * システム管理ファイル(functions / _routes.json / .github 等)の競合時挙動。
42
+ * 既定は force に従い overwrite / backup を決める。
43
+ */
34
44
  mode?: ConflictMode;
45
+ /**
46
+ * 強制上書き(Issue #150)。
47
+ * - 保護設定ファイル(_redirects / wrangler.toml 等): true のとき *.frelio-bak を作って上書き、
48
+ * false(既定)のときは差分があれば保持する。
49
+ * - システムファイル: mode 未指定時に overwrite(true) / backup(false) を決める。
50
+ */
51
+ force?: boolean;
35
52
  /** テスト/DI 用。指定時は GitHub からの取得をスキップしこのディレクトリを使う */
36
53
  templateDir?: string;
37
54
  };
@@ -9,8 +9,12 @@
9
9
  * - wrangler.toml / functions/storage / _redirects / _routes.json は config から決定的に生成する
10
10
  * (lib/templates.ts の生成関数を共有。set-domain と同一の正本)
11
11
  *
12
- * ユーザー改変を保護するため、既存ファイルと差分がある場合は競合モードに従う
13
- * (既定 backup: <file>.frelio-bak に退避してから上書き)。
12
+ * ユーザー改変を保護するため、ファイルを2種類に分けて扱う(Issue #150):
13
+ * - 保護設定ファイル(_redirects / wrangler.toml / workers/file-upload/wrangler.toml):
14
+ * 既定では上書きせず保持する(config.json と同様)。--force のときのみ
15
+ * <file>.frelio-bak に退避してから上書きする。
16
+ * - システム管理ファイル(.github / functions / _routes.json 等):
17
+ * 差分があれば既定 backup(<file>.frelio-bak に退避してから上書き)、--force で無バックアップ上書き。
14
18
  *
15
19
  * frelio-data/・public/・admin/config.json・functions/api/・workers/file-upload/src は触らない。
16
20
  */
@@ -21,6 +25,18 @@ import { fetchTemplate, cleanupTemplate } from './template-scaffold.js';
21
25
  import { renderTemplate, projectConfigToVars } from '../lib/template-renderer.js';
22
26
  import { generateWranglerToml, generateWorkerWranglerToml, generateRedirects, generateRoutesJson, generatePublicRoutesJson, generateStorageFunction, generateGateMiddleware, } from '../lib/templates.js';
23
27
  const DEFAULT_TARGETS = ['workflows', 'wrangler', 'functions', 'routing'];
28
+ /**
29
+ * 保護対象の設定ファイル(Issue #150)。
30
+ * ユーザーが恒常的にカスタムを足す前提のファイルは、既定では上書きせず保持する
31
+ * (config.json と同様)。--force 指定時のみ *.frelio-bak を作って上書きする。
32
+ */
33
+ const PROTECTED_CONFIG = new Set([
34
+ '_redirects',
35
+ 'wrangler.toml',
36
+ 'workers/file-upload/wrangler.toml',
37
+ // database_id を含み init 時に一度だけ生成するため update では保持する
38
+ 'workers/contact/wrangler.toml',
39
+ ]);
24
40
  function toPosix(p) {
25
41
  return p.split(path.sep).join('/');
26
42
  }
@@ -85,9 +101,10 @@ function planGenerated(config, targets) {
85
101
  return planned;
86
102
  }
87
103
  /** 1ファイルを競合モードに従って適用する */
88
- function applyFile(projectDir, file, mode, result) {
104
+ function applyFile(projectDir, file, mode, result, force) {
89
105
  const dest = path.join(projectDir, file.relPath);
90
106
  const exists = fs.existsSync(dest);
107
+ const isProtected = PROTECTED_CONFIG.has(file.relPath);
91
108
  if (exists) {
92
109
  const current = fs.readFileSync(dest, 'utf-8');
93
110
  if (current === file.content) {
@@ -95,14 +112,26 @@ function applyFile(projectDir, file, mode, result) {
95
112
  return;
96
113
  }
97
114
  // 差分あり
98
- if (mode === 'skip') {
99
- result.skipped.push(file.relPath);
100
- return;
101
- }
102
- if (mode === 'backup') {
115
+ // 保護設定ファイル(Issue #150): 既定は保持。--force のときのみ backup→上書き。
116
+ if (isProtected) {
117
+ if (!force) {
118
+ result.preserved.push(file.relPath);
119
+ return;
120
+ }
121
+ // --force: 必ず *.frelio-bak を作ってから上書き(データ消失リスクを最小化)
103
122
  fs.writeFileSync(`${dest}.frelio-bak`, current, 'utf-8');
104
123
  result.backedUp.push(file.relPath);
105
124
  }
125
+ else {
126
+ if (mode === 'skip') {
127
+ result.skipped.push(file.relPath);
128
+ return;
129
+ }
130
+ if (mode === 'backup') {
131
+ fs.writeFileSync(`${dest}.frelio-bak`, current, 'utf-8');
132
+ result.backedUp.push(file.relPath);
133
+ }
134
+ }
106
135
  }
107
136
  fs.mkdirSync(path.dirname(dest), { recursive: true });
108
137
  fs.writeFileSync(dest, file.content, 'utf-8');
@@ -113,8 +142,16 @@ function applyFile(projectDir, file, mode, result) {
113
142
  */
114
143
  export async function refreshTemplates(projectDir, config, opts = {}) {
115
144
  const targets = opts.targets ?? DEFAULT_TARGETS;
116
- const mode = opts.mode ?? 'backup';
117
- const result = { written: [], unchanged: [], skipped: [], backedUp: [] };
145
+ const force = opts.force ?? false;
146
+ // システムファイルの競合モード: mode が明示されればそれを優先、無ければ force から決定
147
+ const mode = opts.mode ?? (force ? 'overwrite' : 'backup');
148
+ const result = {
149
+ written: [],
150
+ unchanged: [],
151
+ skipped: [],
152
+ backedUp: [],
153
+ preserved: [],
154
+ };
118
155
  const needsTemplate = targets.includes('workflows');
119
156
  let templateDir = opts.templateDir ?? null;
120
157
  let ownTemplate = false;
@@ -134,7 +171,7 @@ export async function refreshTemplates(projectDir, config, opts = {}) {
134
171
  }
135
172
  planned.push(...planGenerated(config, targets));
136
173
  for (const file of planned) {
137
- applyFile(projectDir, file, mode, result);
174
+ applyFile(projectDir, file, mode, result, force);
138
175
  }
139
176
  return ok(result);
140
177
  }
package/dist/index.js CHANGED
@@ -43,7 +43,7 @@ program
43
43
  .option('--version <version>', 'Specific version to install (default: latest)')
44
44
  .option('--bundle-only', 'Update only the CMS admin bundle (skip template regeneration)')
45
45
  .option('--templates-only', 'Regenerate only templates (skip CMS admin bundle)')
46
- .option('--force', 'Overwrite changed files without creating .frelio-bak backups')
46
+ .option('--force', 'Overwrite user-edited config files too. Protected config (_redirects/wrangler.toml) is backed up to *.frelio-bak before overwriting; system files are overwritten without backup')
47
47
  .action(updateCommand);
48
48
  program
49
49
  .command('doctor')
@@ -26,6 +26,9 @@ export function projectConfigToVars(config) {
26
26
  // ビジュアル編集・プレビューのベース URL(Issue #140)。未指定なら previewUrl を既定。
27
27
  templatePreviewBaseUrl: config.templatePreviewBaseUrl || config.previewUrl,
28
28
  fileUploadUrl: '/api/storage',
29
+ // お問い合わせワーカー(frelio-contact)の URL。初期は空(任意機能)。
30
+ // 公開後に CMS「基本設定」で設定する。
31
+ contactApiUrl: '',
29
32
  pagesProjectName: config.pagesProjectName,
30
33
  adminPagesProjectName: config.adminPagesProjectName,
31
34
  r2BucketName: config.r2BucketName,
@@ -99,6 +99,34 @@ export declare function buildAllowedOrigins(config: ProjectConfig): string;
99
99
  */
100
100
  export declare function generateWranglerToml(config: ProjectConfig): string;
101
101
  export declare function generateWorkerWranglerToml(config: ProjectConfig): string;
102
+ /** お問い合わせ自動メール(任意)の SMTP 接続設定 */
103
+ export type ContactSmtpConfig = {
104
+ host: string;
105
+ port: string;
106
+ /** true=暗黙TLS(465) / false=STARTTLS(587) */
107
+ secure: boolean;
108
+ user: string;
109
+ from: string;
110
+ fromName?: string;
111
+ };
112
+ export type ContactWorkerOptions = {
113
+ /** `wrangler d1 create` で取得した D1 database_id */
114
+ databaseId: string;
115
+ /** 通知クリックで開く CMS の受信箱 URL */
116
+ adminInboxUrl: string;
117
+ /** Turnstile サイトキー(公開値) */
118
+ turnstileSiteKey?: string;
119
+ /** SMTP 自動メール設定(省略時は無効) */
120
+ smtp?: ContactSmtpConfig;
121
+ };
122
+ /**
123
+ * お問い合わせワーカー(workers/contact)の wrangler.toml を生成する。
124
+ *
125
+ * file-upload と違い D1 の database_id を含むため init 時に一度だけ生成し、
126
+ * 以降の update では上書きしない(PROTECTED_CONFIG)。SMTP/CONTENT_REPO_TOKEN/
127
+ * パスワード等のシークレットは wrangler secret で別途投入する(ここには書かない)。
128
+ */
129
+ export declare function generateContactWranglerToml(config: ProjectConfig, opts: ContactWorkerOptions): string;
102
130
  export declare function generateRedirects(): string;
103
131
  export declare function generateRoutesJson(): string;
104
132
  /**
@@ -108,6 +108,9 @@ export function generateConfigJson(config) {
108
108
  contentRepo: config.contentRepo,
109
109
  githubClientId: config.githubClientId,
110
110
  fileUploadUrl: '/api/storage',
111
+ // お問い合わせワーカー(frelio-contact)の URL。初期は空(任意機能)。
112
+ // 公開後に CMS「基本設定」で設定する。
113
+ contactApiUrl: '',
111
114
  siteTitle: config.siteTitle,
112
115
  productionUrl: config.productionUrl,
113
116
  previewUrl: config.previewUrl,
@@ -211,6 +214,59 @@ ALLOWED_ORIGINS = "${allowedOrigins}"
211
214
  CONTENT_REPO = "${config.contentRepo}"
212
215
  `;
213
216
  }
217
+ /**
218
+ * お問い合わせワーカー(workers/contact)の wrangler.toml を生成する。
219
+ *
220
+ * file-upload と違い D1 の database_id を含むため init 時に一度だけ生成し、
221
+ * 以降の update では上書きしない(PROTECTED_CONFIG)。SMTP/CONTENT_REPO_TOKEN/
222
+ * パスワード等のシークレットは wrangler secret で別途投入する(ここには書かない)。
223
+ */
224
+ export function generateContactWranglerToml(config, opts) {
225
+ const allowedOrigins = buildAllowedOrigins(config);
226
+ const smtpBlock = opts.smtp
227
+ ? `SMTP_HOST = "${opts.smtp.host}"
228
+ SMTP_PORT = "${opts.smtp.port}"
229
+ SMTP_SECURE = "${opts.smtp.secure ? 'true' : 'false'}"
230
+ SMTP_USER = "${opts.smtp.user}"
231
+ MAIL_FROM = "${opts.smtp.from}"
232
+ MAIL_FROM_NAME = "${opts.smtp.fromName ?? ''}"
233
+ `
234
+ : `# 自動メール送信(任意)。有効化する場合は SMTP_HOST 等を設定し、SMTP_PASS を secret に投入する
235
+ # SMTP_HOST = "smtp.example.com"
236
+ # SMTP_PORT = "587"
237
+ # SMTP_SECURE = "false"
238
+ # SMTP_USER = "no-reply@example.com"
239
+ # MAIL_FROM = "no-reply@example.com"
240
+ # MAIL_FROM_NAME = "${config.siteTitle} お問い合わせ"
241
+ `;
242
+ return `name = "frelio-contact"
243
+ main = "src/index.ts"
244
+ compatibility_date = "2024-09-23"
245
+ compatibility_flags = ["nodejs_compat"]
246
+
247
+ [[d1_databases]]
248
+ binding = "DB"
249
+ database_name = "frelio_contact"
250
+ database_id = "${opts.databaseId}"
251
+ migrations_dir = "migrations"
252
+
253
+ [vars]
254
+ ALLOWED_ORIGINS = "${allowedOrigins}"
255
+ CONTENT_REPO = "${config.contentRepo}"
256
+ ADMIN_DATA_BRANCH = "develop"
257
+ USERS_JSON_PATH = "frelio-data/admin/structure/users.json"
258
+ RETENTION_DAYS = "365"
259
+ TURNSTILE_SITE_KEY = "${opts.turnstileSiteKey ?? ''}"
260
+ ADMIN_INBOX_URL = "${opts.adminInboxUrl}"
261
+ ${smtpBlock}
262
+ # シークレットは wrangler secret put で投入:
263
+ # VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY / VAPID_SUBJECT / TURNSTILE_SECRET
264
+ # SMTP_PASS(自動メール有効時) / CONTENT_REPO_TOKEN(contents:read、プライベート repo で必須)
265
+
266
+ [triggers]
267
+ crons = ["0 3 * * *"]
268
+ `;
269
+ }
214
270
  export function generateRedirects() {
215
271
  // 順序重要: 先にマッチしたルールが適用される
216
272
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c-time/frelio-cli",
3
- "version": "1.4.13",
3
+ "version": "1.5.0",
4
4
  "description": "Frelio CMS setup CLI",
5
5
  "license": "MIT",
6
6
  "type": "module",