@c-time/frelio-cli 2.3.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.
@@ -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
+ }
@@ -22,6 +22,22 @@ export declare function createD1Database(name: string): OperationResult<{
22
22
  }>;
23
23
  /** ワーカーのシークレットを設定する(cwd でワーカーディレクトリを指定) */
24
24
  export declare function setWorkerSecret(secretName: string, secretValue: string, cwd: string): OperationResult;
25
+ /**
26
+ * `wrangler deploy` の出力から公開ホストを取り出す(Issue #261)。
27
+ * workers.dev を最優先で拾う(アカウント部を含み、独自 routes より確実)。
28
+ * 見つからなければ最初の https URL のホスト。どちらも無ければ null。
29
+ */
30
+ export declare function parseDeployedHost(output: string): string | null;
31
+ /**
32
+ * 管理画面 Worker を一度デプロイし、割り当てられた公開ホストを取得する(Issue #261: deploy-first)。
33
+ *
34
+ * workers.dev の「アカウント部」はアカウント固定値で、デプロイ前にはきれいに読めない(OAuth ログイン時は特に)。
35
+ * そこで admin Worker を実際にデプロイし、その出力ホスト(`<admin>.<account>.workers.dev`)から確定する。
36
+ * projectDir に wrangler.admin.toml / admin-worker バンドル / admin(SPA)/ R2 バケットが揃っている前提。
37
+ */
38
+ export declare function deployAdminWorker(projectDir: string): OperationResult<{
39
+ host: string;
40
+ }>;
25
41
  export type CloudflareSetupResult = {
26
42
  r2Bucket: OperationResult<{
27
43
  alreadyExisted: boolean;
@@ -86,6 +86,41 @@ export function setWorkerSecret(secretName, secretValue, cwd) {
86
86
  return fail(`${secretName} の設定に失敗しました: ${e.message}`, 'EXEC_FAILED');
87
87
  }
88
88
  }
89
+ // ---------------------------------------------------------------------------
90
+ // Admin worker deploy-first(Issue #261: ホスト確定)
91
+ // ---------------------------------------------------------------------------
92
+ /**
93
+ * `wrangler deploy` の出力から公開ホストを取り出す(Issue #261)。
94
+ * workers.dev を最優先で拾う(アカウント部を含み、独自 routes より確実)。
95
+ * 見つからなければ最初の https URL のホスト。どちらも無ければ null。
96
+ */
97
+ export function parseDeployedHost(output) {
98
+ const wd = output.match(/https?:\/\/([a-z0-9-]+\.[a-z0-9-]+\.workers\.dev)\b/i);
99
+ if (wd)
100
+ return wd[1];
101
+ const any = output.match(/https?:\/\/([a-z0-9.-]+\.[a-z]{2,})(?:[/\s]|$)/i);
102
+ return any ? any[1] : null;
103
+ }
104
+ /**
105
+ * 管理画面 Worker を一度デプロイし、割り当てられた公開ホストを取得する(Issue #261: deploy-first)。
106
+ *
107
+ * workers.dev の「アカウント部」はアカウント固定値で、デプロイ前にはきれいに読めない(OAuth ログイン時は特に)。
108
+ * そこで admin Worker を実際にデプロイし、その出力ホスト(`<admin>.<account>.workers.dev`)から確定する。
109
+ * projectDir に wrangler.admin.toml / admin-worker バンドル / admin(SPA)/ R2 バケットが揃っている前提。
110
+ */
111
+ export function deployAdminWorker(projectDir) {
112
+ try {
113
+ const out = exec('wrangler deploy --config wrangler.admin.toml', { cwd: projectDir, silent: true });
114
+ const host = parseDeployedHost(out);
115
+ if (!host) {
116
+ return fail('デプロイ出力から公開ホストを取得できませんでした(wrangler の出力形式を確認してください)', 'EXEC_FAILED');
117
+ }
118
+ return ok({ host });
119
+ }
120
+ catch (e) {
121
+ return fail(`管理画面 Worker のデプロイに失敗しました: ${e.message}`, 'EXEC_FAILED');
122
+ }
123
+ }
89
124
  /**
90
125
  * Cloudflare リソースをセットアップする(Issue #184: Workers 構成)。
91
126
  *
@@ -0,0 +1,28 @@
1
+ /**
2
+ * core/config-doctor — admin/config.json の URL 設定の健全性チェック(Issue #261)
3
+ *
4
+ * init フロー再設計(workers.dev ファースト)に伴い、config の URL が
5
+ * - 未解決(独自ドメインなのに DNS 未プロビジョニング → NXDOMAIN)
6
+ * - CI の実デプロイ先(workers.dev preview-alias)と食い違う
7
+ * といった不整合を検出して警告する。読み取り専用の診断で、何も書き換えない。
8
+ */
9
+ import { type OperationResult } from './types.js';
10
+ export type ConfigUrlSeverity = 'warning' | 'info';
11
+ export type ConfigUrlFinding = {
12
+ severity: ConfigUrlSeverity;
13
+ /** 対象フィールド */
14
+ field: string;
15
+ title: string;
16
+ detail: string;
17
+ };
18
+ export type ConfigUrlReport = {
19
+ /** config.json が見つかったか(無ければチェックをスキップ) */
20
+ configFound: boolean;
21
+ findings: ConfigUrlFinding[];
22
+ /** warning が1件以上あるか */
23
+ actionable: boolean;
24
+ };
25
+ /**
26
+ * config.json の URL 群を検査する(best-effort。例外は投げない)。
27
+ */
28
+ export declare function checkConfigUrls(projectDir: string): OperationResult<ConfigUrlReport>;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * core/config-doctor — admin/config.json の URL 設定の健全性チェック(Issue #261)
3
+ *
4
+ * init フロー再設計(workers.dev ファースト)に伴い、config の URL が
5
+ * - 未解決(独自ドメインなのに DNS 未プロビジョニング → NXDOMAIN)
6
+ * - CI の実デプロイ先(workers.dev preview-alias)と食い違う
7
+ * といった不整合を検出して警告する。読み取り専用の診断で、何も書き換えない。
8
+ */
9
+ import { readConfig } from './config.js';
10
+ import { normalizeWorkersSubdomain } from '../lib/templates.js';
11
+ import { ok } from './types.js';
12
+ /** *.workers.dev のオリジンか */
13
+ function isWorkersDevUrl(url) {
14
+ return /\.workers\.dev(\/|$)/.test(url);
15
+ }
16
+ /**
17
+ * config.json の URL 群を検査する(best-effort。例外は投げない)。
18
+ */
19
+ export function checkConfigUrls(projectDir) {
20
+ const read = readConfig(projectDir);
21
+ if (!read.success)
22
+ return read;
23
+ const config = read.data.config;
24
+ if (!config) {
25
+ return ok({ configFound: false, findings: [], actionable: false });
26
+ }
27
+ const findings = [];
28
+ const sub = normalizeWorkersSubdomain(config.workersSubdomain ?? '');
29
+ const previewUrl = config.previewUrl ?? '';
30
+ // --- previewUrl ---
31
+ if (!previewUrl) {
32
+ findings.push({
33
+ severity: 'info',
34
+ field: 'previewUrl',
35
+ title: 'previewUrl 未設定',
36
+ detail: 'プレビューは CI の workers.dev エイリアス(staging-<contentWorker>.<subdomain>.workers.dev)で配信されます。独自ドメインを使う場合は終盤に `frelio set-domain` で設定してください。',
37
+ });
38
+ }
39
+ else if (!isWorkersDevUrl(previewUrl)) {
40
+ // 独自ドメインの previewUrl。DNS 未プロビジョニングだと NXDOMAIN になる(issue #261 の実害)。
41
+ findings.push({
42
+ severity: 'warning',
43
+ field: 'previewUrl',
44
+ title: 'previewUrl が独自ドメイン(未解決の恐れ)',
45
+ detail: `previewUrl=${previewUrl} は独自ドメインです。DNS をプロビジョニングしていないと解決しません(NXDOMAIN)。` +
46
+ `CI が実際に出すプレビューは staging-${config.contentWorkerName}.<subdomain>.workers.dev です。` +
47
+ '未プロビジョニングなら previewUrl を空にして workers.dev を使うか、`frelio set-domain` で正しいドメインを設定してください。',
48
+ });
49
+ }
50
+ else if (sub) {
51
+ // workers.dev の previewUrl。サブドメインが分かっていれば CI の実プレビューと一致するか検証する。
52
+ const expected = `https://staging-${config.contentWorkerName}.${sub}.workers.dev`;
53
+ if (previewUrl !== expected) {
54
+ findings.push({
55
+ severity: 'warning',
56
+ field: 'previewUrl',
57
+ title: 'previewUrl が CI の実プレビューと不一致',
58
+ detail: `previewUrl=${previewUrl} ですが、CI(build-staging.yml の --preview-alias)が出すのは ${expected} です。`,
59
+ });
60
+ }
61
+ }
62
+ // --- workersSubdomain ---
63
+ if (!sub) {
64
+ findings.push({
65
+ severity: 'info',
66
+ field: 'workersSubdomain',
67
+ title: 'workersSubdomain 未設定',
68
+ detail: '管理画面 Worker の初回デプロイで割り当てられた workers.dev サブドメインを CMS「基本設定」に設定すると、プレビュー/管理画面 URL の整合を検証できます。',
69
+ });
70
+ }
71
+ // --- productionUrl ---
72
+ if (!config.productionUrl) {
73
+ findings.push({
74
+ severity: 'info',
75
+ field: 'productionUrl',
76
+ title: 'productionUrl 未設定',
77
+ detail: '独自ドメインは終盤の `frelio set-domain` で設定できます(workers.dev だけでも開発・プレビューは成立します)。未設定だと sitemap・OGP・正規URL 等の絶対URLは生成できません。',
78
+ });
79
+ }
80
+ const actionable = findings.some((f) => f.severity === 'warning');
81
+ return ok({ configFound: true, findings, actionable });
82
+ }
@@ -7,7 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { ok, okVoid, fail, } from './types.js';
10
- import { generateStagingDomain, buildWorkerNames } from '../lib/templates.js';
10
+ import { buildWorkerNames, derivePreviewUrl } from '../lib/templates.js';
11
11
  import { validateContentRepo, validateR2PublicUrl, sanitizeCloudflareName, validateCloudflareName, } from '../lib/validators.js';
12
12
  /** read-only フィールド(updateConfig で上書き不可) */
13
13
  const READ_ONLY_FIELDS = ['contentRepo', 'githubClientId'];
@@ -123,9 +123,17 @@ export function buildConfig(params) {
123
123
  const repoName = params.contentRepo.split('/')[1];
124
124
  // Cloudflare-safe な slug(アンダースコア/大文字等を除去)を R2・Worker 名の基底にする(Issue #216)
125
125
  const repoSlug = sanitizeCloudflareName(repoName);
126
- const stagingDomain = params.stagingDomain ?? generateStagingDomain(params.productionUrl || '');
127
- const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
128
126
  const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, params.randomSuffix ?? true, { contentWorkerName: params.contentWorkerName, adminWorkerName: params.adminWorkerName });
127
+ // Issue #261: 独自の staging ドメインは init では自動生成しない(productionUrl から
128
+ // `staging-<hash>.<本番ホスト>` を導出すると未プロビジョニングで NXDOMAIN になり、
129
+ // CI が実際に出す workers.dev プレビューと恒久的に食い違うため)。独自ドメインは終盤に
130
+ // set-domain で後付けする。previewUrl は明示 stagingDomain か workers.dev サブドメインから導く。
131
+ const stagingDomain = params.stagingDomain ?? '';
132
+ const previewUrl = derivePreviewUrl({
133
+ stagingDomain,
134
+ workersSubdomain: params.workersSubdomain,
135
+ contentWorkerName,
136
+ });
129
137
  const r2BucketName = params.r2BucketName ?? `${repoSlug}-files`;
130
138
  // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare API 呼び出し前)
131
139
  for (const [label, value] of [
@@ -148,6 +156,7 @@ export function buildConfig(params) {
148
156
  r2PublicUrl: params.r2PublicUrl || '',
149
157
  contentWorkerName,
150
158
  adminWorkerName,
159
+ workersSubdomain: params.workersSubdomain || '',
151
160
  ownerUsername: params.ownerUsername || '',
152
161
  stagingDomain,
153
162
  saveTimezone: params.saveTimezone || '+09:00',
@@ -21,6 +21,12 @@ export type DomainChange = {
21
21
  stagingDomain?: string;
22
22
  r2PublicUrl?: string;
23
23
  siteTitle?: string;
24
+ /**
25
+ * ファイル限定配信ワーカー(frelio-file-delivery)の公開 URL(任意機能)。
26
+ * config.json の downloadApiUrl と workers/file-delivery/wrangler.toml の
27
+ * PUBLIC_BASE_URL を同じ新 URL に更新する(末尾スラッシュ無し)。
28
+ */
29
+ downloadApiUrl?: string;
24
30
  /** productionUrl 変更時にステージングのハッシュを保持せず再生成する */
25
31
  regenStagingHash?: boolean;
26
32
  };
@@ -14,6 +14,7 @@
14
14
  import { ok, fail, } from './types.js';
15
15
  import { readConfig, validateConfig } from './config.js';
16
16
  import { regenerateAllConfigFiles } from './file-generators.js';
17
+ import { updateFileDeliveryPublicBaseUrl } from './file-delivery.js';
17
18
  import { generateStagingDomain, rehostStagingDomain } from '../lib/templates.js';
18
19
  function safeHostname(url) {
19
20
  try {
@@ -51,6 +52,13 @@ export function changeDomain(projectDir, change) {
51
52
  merged.siteTitle = change.siteTitle;
52
53
  if (change.r2PublicUrl !== undefined)
53
54
  merged.r2PublicUrl = change.r2PublicUrl;
55
+ // ファイル限定配信ワーカー(任意): downloadApiUrl(config.json)と PUBLIC_BASE_URL は同値。
56
+ // 末尾スラッシュを除去して両者を厳密一致させる(wrangler.toml は後段で surgical に更新)。
57
+ let downloadApiUrl;
58
+ if (change.downloadApiUrl !== undefined) {
59
+ downloadApiUrl = change.downloadApiUrl.replace(/\/+$/, '');
60
+ merged.downloadApiUrl = downloadApiUrl;
61
+ }
54
62
  if (change.productionUrl !== undefined) {
55
63
  merged.productionUrl = change.productionUrl;
56
64
  const newStaging = change.regenStagingHash
@@ -90,5 +98,15 @@ export function changeDomain(projectDir, change) {
90
98
  const regen = regenerateAllConfigFiles(projectDir, merged);
91
99
  if (!regen.success)
92
100
  return regen;
93
- return ok({ config: merged, regeneratedPaths: regen.data.paths });
101
+ const regeneratedPaths = [...regen.data.paths];
102
+ // ファイル限定配信ワーカー(任意・opt-in 済みのみ): wrangler.toml の PUBLIC_BASE_URL 行だけを
103
+ // 新 URL に置換する(database_id 等の他設定・vars は温存 = keep-vars の教訓)。
104
+ // downloadApiUrl の変更指定があり、かつ wrangler.toml が存在する場合のみ更新する。
105
+ if (downloadApiUrl !== undefined) {
106
+ const updated = updateFileDeliveryPublicBaseUrl(projectDir, downloadApiUrl);
107
+ if (updated) {
108
+ regeneratedPaths.push('workers/file-delivery/wrangler.toml');
109
+ }
110
+ }
111
+ return ok({ config: merged, regeneratedPaths });
94
112
  }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * core/file-delivery — ファイル限定配信ワーカー(workers/file-delivery)のセットアップ
3
+ *
4
+ * 任意機能。「フォーム送信後にダウンロード URL を期限付きでメール配信」の受け皿。
5
+ * 専用プライベート R2 バケット作成 → D1 作成 → マイグレーション → wrangler.toml 生成、
6
+ * さらに contact ワーカーが opt-in 済みなら Service Binding(DELIVERY)を配線する。
7
+ *
8
+ * contact / scheduled-publish と同じ流儀:
9
+ * - wrangler.toml は database_id / bucket_name / PUBLIC_BASE_URL 等ユーザー設定を含むため
10
+ * init 時に一度だけ生成し、update では上書きしない(template-refresh の PROTECTED_CONFIG)。
11
+ * - シークレットは持たない(認可は users.json をサーバ側で読む fail-closed 方式)。
12
+ */
13
+ import { type ProjectConfig, type OperationResult } from './types.js';
14
+ export type FileDeliverySetupInput = {
15
+ /** このワーカーの公開ベース URL(CMS の downloadApiUrl と同じ値。末尾スラッシュ無し) */
16
+ publicBaseUrl: string;
17
+ /** 失効/期限切れトークンの保持日数(既定 30) */
18
+ tokenRetentionDays?: string;
19
+ /**
20
+ * contact ワーカーに DELIVERY Service Binding を追記するか。
21
+ * contact も opt-in 済み(wrangler.toml が生成済み)のときに true。
22
+ */
23
+ wireContact: boolean;
24
+ };
25
+ export type FileDeliverySetupResult = {
26
+ /** 限定配信用プライベート R2 バケット名(`<project>-downloads`) */
27
+ bucketName: string;
28
+ bucketAlreadyExisted: boolean;
29
+ databaseId: string;
30
+ d1AlreadyExisted: boolean;
31
+ migrated: boolean;
32
+ /** contact に DELIVERY バインディングを追記したか(未 opt-in・既に配線済みなら false) */
33
+ wiredContact: boolean;
34
+ };
35
+ /** 限定配信用のプライベート R2 バケット名を導出する(公開バケットとは別)。 */
36
+ export declare function deliveryBucketName(config: ProjectConfig): string;
37
+ /** ファイル限定配信ワーカーをセットアップする */
38
+ export declare function setupFileDeliveryWorker(projectDir: string, config: ProjectConfig, input: FileDeliverySetupInput): OperationResult<FileDeliverySetupResult>;
39
+ /**
40
+ * ファイル限定配信ワーカーの wrangler.toml の `PUBLIC_BASE_URL` 行だけを新 URL に置換する(Issue: set-domain 統合)。
41
+ *
42
+ * wrangler.toml は database_id / bucket_name 等ユーザー設定を含む PROTECTED_CONFIG のため
43
+ * 全再生成はしない。[[wrangler-keep-vars]] の教訓(既存 worker の他 vars を消さない)に従い、
44
+ * `PUBLIC_BASE_URL = "..."` の1行だけを surgical に置換する。
45
+ *
46
+ * 未 opt-in(wrangler.toml 無し)、または該当行が無い/既に同値なら false を返す(変更なし)。
47
+ */
48
+ export declare function updateFileDeliveryPublicBaseUrl(projectDir: string, publicBaseUrl: string): boolean;
49
+ /**
50
+ * contact ワーカーの wrangler.toml に DELIVERY Service Binding を追記する。
51
+ * contact 未 opt-in(wrangler.toml 無し)、または既に配線済みなら何もせず false を返す。
52
+ */
53
+ export declare function wireDeliveryIntoContact(projectDir: string): boolean;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * core/file-delivery — ファイル限定配信ワーカー(workers/file-delivery)のセットアップ
3
+ *
4
+ * 任意機能。「フォーム送信後にダウンロード URL を期限付きでメール配信」の受け皿。
5
+ * 専用プライベート R2 バケット作成 → D1 作成 → マイグレーション → wrangler.toml 生成、
6
+ * さらに contact ワーカーが opt-in 済みなら Service Binding(DELIVERY)を配線する。
7
+ *
8
+ * contact / scheduled-publish と同じ流儀:
9
+ * - wrangler.toml は database_id / bucket_name / PUBLIC_BASE_URL 等ユーザー設定を含むため
10
+ * init 時に一度だけ生成し、update では上書きしない(template-refresh の PROTECTED_CONFIG)。
11
+ * - シークレットは持たない(認可は users.json をサーバ側で読む fail-closed 方式)。
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { ok, fail } from './types.js';
16
+ import { createD1Database, createR2Bucket } from './cloudflare.js';
17
+ import { generateFileDeliveryWranglerToml } from '../lib/templates.js';
18
+ import { exec } from '../lib/shell.js';
19
+ const D1_NAME = 'frelio_downloads';
20
+ const WORKER_SUBDIR = 'workers/file-delivery';
21
+ const CONTACT_WORKER_SUBDIR = 'workers/contact';
22
+ /** contact ワーカーに追記する Service Binding ブロック(トークン発行の配線) */
23
+ const DELIVERY_SERVICE_BINDING = `
24
+ # --- ファイル限定配信(file-delivery)の配線(frelio-cli が追記)---
25
+ [[services]]
26
+ binding = "DELIVERY"
27
+ service = "frelio-file-delivery"
28
+ entrypoint = "DeliveryEntrypoint"
29
+ `;
30
+ /** 限定配信用のプライベート R2 バケット名を導出する(公開バケットとは別)。 */
31
+ export function deliveryBucketName(config) {
32
+ const repoSlug = config.contentRepo.split('/')[1] || 'site';
33
+ return `${repoSlug}-downloads`;
34
+ }
35
+ /** ファイル限定配信ワーカーをセットアップする */
36
+ export function setupFileDeliveryWorker(projectDir, config, input) {
37
+ const workerDir = path.join(projectDir, WORKER_SUBDIR);
38
+ if (!fs.existsSync(workerDir)) {
39
+ return fail(`ファイル限定配信ワーカーが見つかりません(${WORKER_SUBDIR})。バンドル展開(frelio-cli update)を先に行ってください。`, 'NOT_FOUND');
40
+ }
41
+ const bucketName = deliveryBucketName(config);
42
+ // 1. 専用プライベート R2 バケット作成(公開バケットとは別。公開 Worker には絶対バインドしない)
43
+ const r2 = createR2Bucket(bucketName);
44
+ if (!r2.success)
45
+ return r2;
46
+ // 2. D1 作成
47
+ const d1 = createD1Database(D1_NAME);
48
+ if (!d1.success)
49
+ return d1;
50
+ // 3. wrangler.toml 生成(bucket_name / database_id / PUBLIC_BASE_URL 等を埋め込む)
51
+ const toml = generateFileDeliveryWranglerToml(config, {
52
+ databaseId: d1.data.databaseId,
53
+ bucketName,
54
+ publicBaseUrl: input.publicBaseUrl,
55
+ tokenRetentionDays: input.tokenRetentionDays,
56
+ });
57
+ fs.writeFileSync(path.join(workerDir, 'wrangler.toml'), toml, 'utf-8');
58
+ // 4. マイグレーション適用(リモート。失敗は致命的ではない=後で手動適用可能)
59
+ let migrated = false;
60
+ try {
61
+ exec(`wrangler d1 migrations apply ${D1_NAME} --remote`, { cwd: workerDir, silent: true });
62
+ migrated = true;
63
+ }
64
+ catch {
65
+ migrated = false;
66
+ }
67
+ // 5. contact ワーカーが opt-in 済みなら DELIVERY Service Binding を配線する
68
+ let wiredContact = false;
69
+ if (input.wireContact) {
70
+ wiredContact = wireDeliveryIntoContact(projectDir);
71
+ }
72
+ return ok({
73
+ bucketName,
74
+ bucketAlreadyExisted: r2.alreadyExisted === true,
75
+ databaseId: d1.data.databaseId,
76
+ d1AlreadyExisted: d1.alreadyExisted === true,
77
+ migrated,
78
+ wiredContact,
79
+ });
80
+ }
81
+ /**
82
+ * ファイル限定配信ワーカーの wrangler.toml の `PUBLIC_BASE_URL` 行だけを新 URL に置換する(Issue: set-domain 統合)。
83
+ *
84
+ * wrangler.toml は database_id / bucket_name 等ユーザー設定を含む PROTECTED_CONFIG のため
85
+ * 全再生成はしない。[[wrangler-keep-vars]] の教訓(既存 worker の他 vars を消さない)に従い、
86
+ * `PUBLIC_BASE_URL = "..."` の1行だけを surgical に置換する。
87
+ *
88
+ * 未 opt-in(wrangler.toml 無し)、または該当行が無い/既に同値なら false を返す(変更なし)。
89
+ */
90
+ export function updateFileDeliveryPublicBaseUrl(projectDir, publicBaseUrl) {
91
+ const deliveryToml = path.join(projectDir, WORKER_SUBDIR, 'wrangler.toml');
92
+ if (!fs.existsSync(deliveryToml))
93
+ return false;
94
+ const current = fs.readFileSync(deliveryToml, 'utf-8');
95
+ // PUBLIC_BASE_URL = "..." の1行だけを置換(他の vars・binding は温存)
96
+ const pattern = /^(\s*PUBLIC_BASE_URL\s*=\s*).*$/m;
97
+ if (!pattern.test(current))
98
+ return false;
99
+ const next = current.replace(pattern, `$1"${publicBaseUrl}"`);
100
+ if (next === current)
101
+ return false;
102
+ fs.writeFileSync(deliveryToml, next, 'utf-8');
103
+ return true;
104
+ }
105
+ /**
106
+ * contact ワーカーの wrangler.toml に DELIVERY Service Binding を追記する。
107
+ * contact 未 opt-in(wrangler.toml 無し)、または既に配線済みなら何もせず false を返す。
108
+ */
109
+ export function wireDeliveryIntoContact(projectDir) {
110
+ const contactToml = path.join(projectDir, CONTACT_WORKER_SUBDIR, 'wrangler.toml');
111
+ if (!fs.existsSync(contactToml))
112
+ return false;
113
+ const current = fs.readFileSync(contactToml, 'utf-8');
114
+ // 冪等: 既に DELIVERY バインディングがあれば追記しない
115
+ if (/binding\s*=\s*"DELIVERY"/.test(current))
116
+ return false;
117
+ fs.writeFileSync(contactToml, `${current.replace(/\s*$/, '\n')}${DELIVERY_SERVICE_BINDING}`, 'utf-8');
118
+ return true;
119
+ }
@@ -6,6 +6,22 @@ export declare function initialCommitAndBranches(projectDir: string, contentRepo
6
6
  branches: string[];
7
7
  defaultBranch: string;
8
8
  }>;
9
+ /**
10
+ * package-lock.json を生成する(`npm install --package-lock-only`)。
11
+ *
12
+ * init は package.json を配置するが `npm install` を実行しないため、そのままでは
13
+ * package-lock.json が生成されず初回コミットに含まれない。GitHub Actions の各デプロイ
14
+ * ワークフローはロックファイルの存在を前提とするため、これが無いと **admin ブランチへの
15
+ * 初回 push で必ず1回失敗**していた(`deploy-admin` は setup-node の `cache:'npm'` が
16
+ * ロックファイルを要求し、`build-staging` / `promote-production` / `scheduled-publish` /
17
+ * `_deploy` は `npm ci` がロックファイルを要求する)。
18
+ *
19
+ * ここで生成しておくと {@link initialCommitAndBranches} の `git add -A` が拾い、初回コミット
20
+ * に含めて push できる。`--package-lock-only` なので node_modules は作らず軽量。ネットワーク
21
+ * 不通等で失敗しても後から `npm install` で生成できるため best-effort とし、呼び出し側は
22
+ * 警告に留めて続行する。既にロックファイルがあれば何もしない。
23
+ */
24
+ export declare function generateLockfile(projectDir: string): OperationResult<void>;
9
25
  /**
10
26
  * commit author に使われる git identity を取得する。
11
27
  * projectDir 内で実行するため、git が commit 時に解決する値(local→global→system)と一致する。
@@ -30,6 +30,39 @@ export function initialCommitAndBranches(projectDir, contentRepo) {
30
30
  }
31
31
  }
32
32
  // ---------------------------------------------------------------------------
33
+ // Lockfile generation (pre-commit)
34
+ // ---------------------------------------------------------------------------
35
+ /**
36
+ * package-lock.json を生成する(`npm install --package-lock-only`)。
37
+ *
38
+ * init は package.json を配置するが `npm install` を実行しないため、そのままでは
39
+ * package-lock.json が生成されず初回コミットに含まれない。GitHub Actions の各デプロイ
40
+ * ワークフローはロックファイルの存在を前提とするため、これが無いと **admin ブランチへの
41
+ * 初回 push で必ず1回失敗**していた(`deploy-admin` は setup-node の `cache:'npm'` が
42
+ * ロックファイルを要求し、`build-staging` / `promote-production` / `scheduled-publish` /
43
+ * `_deploy` は `npm ci` がロックファイルを要求する)。
44
+ *
45
+ * ここで生成しておくと {@link initialCommitAndBranches} の `git add -A` が拾い、初回コミット
46
+ * に含めて push できる。`--package-lock-only` なので node_modules は作らず軽量。ネットワーク
47
+ * 不通等で失敗しても後から `npm install` で生成できるため best-effort とし、呼び出し側は
48
+ * 警告に留めて続行する。既にロックファイルがあれば何もしない。
49
+ */
50
+ export function generateLockfile(projectDir) {
51
+ if (!fs.existsSync(`${projectDir}/package.json`)) {
52
+ return fail('package.json が見つかりません。', 'NOT_FOUND');
53
+ }
54
+ if (fs.existsSync(`${projectDir}/package-lock.json`)) {
55
+ return okVoid();
56
+ }
57
+ try {
58
+ exec('npm install --package-lock-only --ignore-scripts', { cwd: projectDir, silent: true });
59
+ return okVoid();
60
+ }
61
+ catch (e) {
62
+ return fail(`package-lock.json 生成失敗: ${e.message}`, 'EXEC_FAILED');
63
+ }
64
+ }
65
+ // ---------------------------------------------------------------------------
33
66
  // Git identity (user.name / user.email)
34
67
  // ---------------------------------------------------------------------------
35
68
  /**
@@ -18,4 +18,4 @@ export { createFullContentStructure } from './content-structure.js';
18
18
  export { scaffoldFromTemplate } from './template-scaffold.js';
19
19
  export { generateAndWriteConfigJson, generateAndWriteWorkerWranglerToml, generateAndWriteContentWorkerSiteMode, generateAndWriteContentWorkerWranglerToml, generateAndWriteAdminWorkerWranglerToml, regenerateAllConfigFiles, } from './file-generators.js';
20
20
  export { installBundle, updateBundle, getBundleVersion } from './bundle.js';
21
- export { initialCommitAndBranches, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
21
+ export { initialCommitAndBranches, generateLockfile, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
@@ -25,4 +25,4 @@ export { generateAndWriteConfigJson, generateAndWriteWorkerWranglerToml, generat
25
25
  // Bundle
26
26
  export { installBundle, updateBundle, getBundleVersion } from './bundle.js';
27
27
  // Git operations
28
- export { initialCommitAndBranches, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
28
+ export { initialCommitAndBranches, generateLockfile, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
@@ -54,6 +54,8 @@ export const PROTECTED_CONFIG = new Set([
54
54
  'workers/contact/wrangler.toml',
55
55
  // 予約反映ワーカー。CONTENT_REPO / ALLOWED_ORIGINS 等のユーザー設定を含むため update では保持する
56
56
  'workers/scheduled-publish/wrangler.toml',
57
+ // ファイル限定配信ワーカー。database_id / bucket_name / PUBLIC_BASE_URL 等を含むため update では保持する
58
+ 'workers/file-delivery/wrangler.toml',
57
59
  ]);
58
60
  function toPosix(p) {
59
61
  return p.split(path.sep).join('/');
@@ -57,4 +57,9 @@ export type BuildConfigParams = {
57
57
  */
58
58
  contentWorkerName?: string;
59
59
  adminWorkerName?: string;
60
+ /**
61
+ * Cloudflare アカウントの workers.dev サブドメイン(個人プレビュー URL の導出に使用)。
62
+ * 初回は不明なことが多いため任意。CMS「基本設定」で後から設定できる。
63
+ */
64
+ workersSubdomain?: string;
60
65
  };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * core/validate-templates — テンプレートのデータ束縛(data-gen-text / data-gen-html)の検証
3
+ *
4
+ * AI / 人が繰り返しやすい「html フィールドを data-gen-text(エスケープ出力)で束縛してしまう」
5
+ * ミスを機械的に検出する。
6
+ *
7
+ * なぜ問題か:
8
+ * ビジュアルエディタ(TipTap)は本文の段落を必ず <p>…</p> で包んで保存する(正しい HTML 出力)。
9
+ * これをテンプレートで data-gen-html(生出力)ではなく data-gen-text(HTML エスケープ)で書き出すと、
10
+ * <p> がエスケープされて `<p>…</p>` という生タグが**文字として**公開ページに露出する。
11
+ * → 属性を data-gen-html に直すのが修正(フィールドの型は変えない)。
12
+ *
13
+ * 注: content-repo 側のスタンドアロン版 `scripts/validate-templates.ts`(雛形に同梱、`npm run
14
+ * validate:templates` で実行)と同一ロジック。あちらは CMS リポジトリ内で完結させるため
15
+ * @c-time/frelio-types だけに依存する別実装。挙動を変えるときは両方を揃えること。
16
+ */
17
+ import { type OperationResult } from './types.js';
18
+ export type TemplateFinding = {
19
+ level: 'error' | 'warn';
20
+ /** プロジェクトルートからの相対パス */
21
+ file: string;
22
+ line: number;
23
+ detail: string;
24
+ };
25
+ export type ValidateTemplatesReport = {
26
+ findings: TemplateFinding[];
27
+ /** 検査したテンプレート数 */
28
+ scannedTemplateCount: number;
29
+ errorCount: number;
30
+ warnCount: number;
31
+ };
32
+ /**
33
+ * テンプレートのデータ束縛を検証する。
34
+ *
35
+ * content_types が無いディレクトリ(Frelio プロジェクトでない)は VALIDATION_ERROR を返す。
36
+ */
37
+ export declare function runValidateTemplates(projectDir: string): OperationResult<ValidateTemplatesReport>;