@c-time/frelio-data-json-generator 1.2.1 → 1.3.15

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/dist/cli.js ADDED
@@ -0,0 +1,1474 @@
1
+ #!/usr/bin/env node
2
+ import { validateSiteRecipe, formatZodErrors } from '@c-time/frelio-types/schemas';
3
+ import { findAffectedOutputs } from '@c-time/frelio-dependency-map';
4
+ import { readFile } from 'fs/promises';
5
+ import { existsSync, readFileSync, mkdirSync, unlinkSync, writeFileSync } from 'fs';
6
+ import { glob } from 'glob';
7
+ import { exec } from 'child_process';
8
+ import { promisify, parseArgs } from 'util';
9
+ import { join, dirname } from 'path';
10
+
11
+ // src/scope/change-detector.ts
12
+ function isContentPath(path) {
13
+ return /^contents\/(published|private)\//.test(path);
14
+ }
15
+ function isPartsPath(path) {
16
+ return /^templates\/(partials\/|_)/.test(path);
17
+ }
18
+ function isTemplatePath(path) {
19
+ return path.startsWith("templates/") && !isPartsPath(path);
20
+ }
21
+ function isContentTypePath(path) {
22
+ return /^content_types\/[^/]+\.json$/.test(path);
23
+ }
24
+ function classifyChangedFiles(gitDiff) {
25
+ const result = {
26
+ contents: { added: [], modified: [], deleted: [] },
27
+ templates: { added: [], modified: [], deleted: [] },
28
+ contentTypes: { added: [], modified: [], deleted: [] },
29
+ parts: { added: [], modified: [], deleted: [] }
30
+ };
31
+ const classify = (path, target) => {
32
+ if (isContentPath(path)) {
33
+ result.contents[target].push(path);
34
+ } else if (isPartsPath(path)) {
35
+ result.parts[target].push(path);
36
+ } else if (isTemplatePath(path)) {
37
+ result.templates[target].push(path);
38
+ } else if (isContentTypePath(path)) {
39
+ result.contentTypes[target].push(path);
40
+ }
41
+ };
42
+ for (const path of gitDiff.added) {
43
+ classify(path, "added");
44
+ }
45
+ for (const path of gitDiff.modified) {
46
+ classify(path, "modified");
47
+ }
48
+ for (const path of gitDiff.deleted) {
49
+ classify(path, "deleted");
50
+ }
51
+ return result;
52
+ }
53
+
54
+ // src/utils/path-utils.ts
55
+ var FORBIDDEN_PATTERNS = [
56
+ /\.\./,
57
+ // 親ディレクトリ参照
58
+ /\\/,
59
+ // バックスラッシュ
60
+ /^\/|^\\/,
61
+ // 先頭のスラッシュ
62
+ /\0/
63
+ // NULL文字
64
+ ];
65
+ function validateOutputPath(path) {
66
+ if (!path || path.trim() === "") {
67
+ return {
68
+ code: "INVALID_OUTPUT_PATH",
69
+ outputPath: path,
70
+ message: "\u51FA\u529B\u30D1\u30B9\u304C\u7A7A\u3067\u3059"
71
+ };
72
+ }
73
+ for (const pattern of FORBIDDEN_PATTERNS) {
74
+ if (pattern.test(path)) {
75
+ return {
76
+ code: "INVALID_OUTPUT_PATH",
77
+ outputPath: path,
78
+ message: `\u51FA\u529B\u30D1\u30B9\u306B\u7981\u6B62\u6587\u5B57\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059: ${path}`
79
+ };
80
+ }
81
+ }
82
+ if (/\{\$[^}]+\}/.test(path)) {
83
+ return {
84
+ code: "INVALID_TEMPLATE_VAR",
85
+ outputPath: path,
86
+ message: `\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u5909\u6570\u304C\u89E3\u6C7A\u3055\u308C\u3066\u3044\u307E\u305B\u3093: ${path}`
87
+ };
88
+ }
89
+ return null;
90
+ }
91
+ function sanitizePath(path) {
92
+ return path.replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, "").trim();
93
+ }
94
+ function extractContentIdFromPath(path) {
95
+ const match = path.match(/contents\/[^/]+\/[^/]+\/([^/]+)\.json$/);
96
+ return match ? match[1] : null;
97
+ }
98
+
99
+ // src/utils/glob-matcher.ts
100
+ function matchGlob(pattern, path) {
101
+ if (pattern === path) {
102
+ return true;
103
+ }
104
+ const regexPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0GLOBSTAR\0").replace(/\*/g, "[^/]*").replace(/\0GLOBSTAR\0/g, ".*");
105
+ try {
106
+ const regex = new RegExp(`^${regexPattern}$`);
107
+ return regex.test(path);
108
+ } catch {
109
+ return pattern === path;
110
+ }
111
+ }
112
+
113
+ // src/scope/parts-expander.ts
114
+ function expandPartsAffectedScope(changedParts, templateIncludes, dependencyMap) {
115
+ if (!templateIncludes) {
116
+ return [];
117
+ }
118
+ const targets = [];
119
+ const seenOutputPaths = /* @__PURE__ */ new Set();
120
+ for (const partsPath of changedParts) {
121
+ const relativePath = partsPath.startsWith("templates/") ? partsPath.slice("templates/".length) : partsPath;
122
+ for (const [partsPattern, affectedTemplates] of Object.entries(templateIncludes)) {
123
+ if (!matchGlob(partsPattern, relativePath)) {
124
+ continue;
125
+ }
126
+ if (affectedTemplates.includes("*")) {
127
+ for (const outputPath of Object.keys(dependencyMap)) {
128
+ if (!seenOutputPaths.has(outputPath)) {
129
+ seenOutputPaths.add(outputPath);
130
+ targets.push({
131
+ outputPath,
132
+ reason: "parts_changed"
133
+ });
134
+ }
135
+ }
136
+ } else {
137
+ for (const templatePath of affectedTemplates) {
138
+ const depPath = `templates/${templatePath}`;
139
+ const affected = findAffectedOutputs(dependencyMap, depPath);
140
+ for (const outputPath of affected) {
141
+ if (!seenOutputPaths.has(outputPath)) {
142
+ seenOutputPaths.add(outputPath);
143
+ targets.push({
144
+ outputPath,
145
+ reason: "parts_changed"
146
+ });
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
153
+ return targets;
154
+ }
155
+
156
+ // src/scope/scope-calculator.ts
157
+ function calculateRegenerationScope(changes, dependencyMap, recipe) {
158
+ const targets = [];
159
+ const seenOutputPaths = /* @__PURE__ */ new Set();
160
+ const addTarget = (target) => {
161
+ const key = `${target.outputPath}:${target.contentId ?? ""}`;
162
+ if (!seenOutputPaths.has(key)) {
163
+ seenOutputPaths.add(key);
164
+ targets.push(target);
165
+ }
166
+ };
167
+ for (const contentPath of [...changes.contents.added, ...changes.contents.modified]) {
168
+ const affected = findAffectedOutputs(dependencyMap, contentPath);
169
+ const contentId = extractContentIdFromPath(contentPath) ?? void 0;
170
+ for (const outputPath of affected) {
171
+ addTarget({
172
+ outputPath,
173
+ reason: "content_changed",
174
+ contentId
175
+ });
176
+ }
177
+ }
178
+ for (const templatePath of [...changes.templates.added, ...changes.templates.modified]) {
179
+ const depPath = templatePath.startsWith("templates/") ? templatePath : `templates/${templatePath}`;
180
+ const affected = findAffectedOutputs(dependencyMap, depPath);
181
+ for (const outputPath of affected) {
182
+ addTarget({
183
+ outputPath,
184
+ reason: "template_changed"
185
+ });
186
+ }
187
+ }
188
+ for (const ctPath of [...changes.contentTypes.added, ...changes.contentTypes.modified]) {
189
+ const affected = findAffectedOutputs(dependencyMap, ctPath);
190
+ for (const outputPath of affected) {
191
+ addTarget({
192
+ outputPath,
193
+ reason: "schema_changed"
194
+ });
195
+ }
196
+ }
197
+ const partsTargets = expandPartsAffectedScope(
198
+ [...changes.parts.added, ...changes.parts.modified],
199
+ recipe.templateIncludes,
200
+ dependencyMap
201
+ );
202
+ for (const target of partsTargets) {
203
+ addTarget(target);
204
+ }
205
+ for (const contentPath of changes.contents.deleted) {
206
+ const contentId = extractContentIdFromPath(contentPath) ?? void 0;
207
+ const affected = findAffectedOutputs(dependencyMap, contentPath);
208
+ for (const outputPath of affected) {
209
+ addTarget({
210
+ outputPath,
211
+ reason: "deleted",
212
+ contentId
213
+ });
214
+ }
215
+ }
216
+ return targets;
217
+ }
218
+ function getAllOutputPaths(dependencyMap) {
219
+ return Object.keys(dependencyMap).map((outputPath) => ({
220
+ outputPath,
221
+ reason: "full_rebuild"
222
+ }));
223
+ }
224
+
225
+ // src/content/content-loader.ts
226
+ var BATCH_SIZE = 50;
227
+ function parseContent(path, content) {
228
+ const json = JSON.parse(content);
229
+ const match = path.match(/contents\/[^/]+\/([^/]+)\/([^/]+)\.json$/);
230
+ const contentTypeId = match?.[1] ?? "unknown";
231
+ const contentId = match?.[2] ?? json.slug ?? json.data?.slug ?? "unknown";
232
+ return {
233
+ contentId,
234
+ contentTypeId,
235
+ slug: json.slug ?? json.data?.slug ?? contentId,
236
+ title: json.title ?? "",
237
+ status: json.status ?? "draft",
238
+ data: json.data ?? {},
239
+ createdAt: json.createdAt ?? "",
240
+ updatedAt: json.updatedAt ?? "",
241
+ publishedAt: json.publishedAt ?? null,
242
+ createdBy: json.createdBy ?? "",
243
+ filePath: path
244
+ };
245
+ }
246
+ async function loadContents(paths, fileSystem, logger) {
247
+ const results = [];
248
+ for (let i = 0; i < paths.length; i += BATCH_SIZE) {
249
+ const batch = paths.slice(i, i + BATCH_SIZE);
250
+ const batchResults = await Promise.all(
251
+ batch.map(async (path) => {
252
+ try {
253
+ const content = await fileSystem.readFile(path);
254
+ return parseContent(path, content);
255
+ } catch (error) {
256
+ logger.error(`Failed to load content: ${path}`, error);
257
+ return null;
258
+ }
259
+ })
260
+ );
261
+ results.push(...batchResults.filter((r) => r !== null));
262
+ }
263
+ return results;
264
+ }
265
+ async function loadContentsByType(contentTypeIds, contentRootPath, fileSystem, logger) {
266
+ const result = /* @__PURE__ */ new Map();
267
+ for (const contentTypeId of contentTypeIds) {
268
+ const pattern = `${contentRootPath}/contents/published/${contentTypeId}/*.json`;
269
+ const paths = await fileSystem.listFiles(pattern);
270
+ const contentPaths = paths.filter((p) => !p.includes("_index"));
271
+ logger.debug(`Loading ${contentPaths.length} contents for ${contentTypeId}`);
272
+ const contents = await loadContents(contentPaths, fileSystem, logger);
273
+ result.set(contentTypeId, contents);
274
+ }
275
+ return result;
276
+ }
277
+
278
+ // src/recipe/output-path-resolver.ts
279
+ function resolveOutputPath(template, content, pageNumber, numberFormatCount) {
280
+ let result = template;
281
+ if (pageNumber !== void 0) {
282
+ const pageStr = numberFormatCount ? pageNumber.toString().padStart(numberFormatCount, "0") : pageNumber.toString();
283
+ result = result.replace(/\{\$page\}/g, pageStr);
284
+ }
285
+ if (content) {
286
+ result = result.replace(/\{\$this\.([^}]+)\}/g, (_, key) => {
287
+ const value = getValueByKey(key, content);
288
+ if (value === void 0 || value === null) {
289
+ return `{$this.${key}}`;
290
+ }
291
+ return String(value);
292
+ });
293
+ }
294
+ return result;
295
+ }
296
+ function toHtmlOutputPath(filePath) {
297
+ return filePath.replace(/\.json$/, ".html");
298
+ }
299
+ function getValueByKey(key, content) {
300
+ if (key in content) {
301
+ return content[key];
302
+ }
303
+ if (content.data && key in content.data) {
304
+ return content.data[key];
305
+ }
306
+ const parts = key.split(".");
307
+ let value = content;
308
+ for (const part of parts) {
309
+ if (value === null || value === void 0) {
310
+ return void 0;
311
+ }
312
+ if (typeof value === "object") {
313
+ const obj = value;
314
+ if (part in obj) {
315
+ value = obj[part];
316
+ } else if ("data" in obj && typeof obj.data === "object" && obj.data !== null) {
317
+ const data = obj.data;
318
+ if (part in data) {
319
+ value = data[part];
320
+ } else {
321
+ return void 0;
322
+ }
323
+ } else {
324
+ return void 0;
325
+ }
326
+ } else {
327
+ return void 0;
328
+ }
329
+ }
330
+ return value;
331
+ }
332
+
333
+ // src/content/content-resolver.ts
334
+ async function resolveRelations(content, expand, context) {
335
+ if (!expand || expand.length === 0) {
336
+ return content.data;
337
+ }
338
+ const result = { ...content.data };
339
+ for (const expandConfig of expand) {
340
+ const fieldValue = content.data[expandConfig.field];
341
+ if (fieldValue === void 0 || fieldValue === null) {
342
+ continue;
343
+ }
344
+ if (Array.isArray(fieldValue)) {
345
+ const resolved = await resolveRelationArray(
346
+ fieldValue,
347
+ expandConfig,
348
+ context
349
+ );
350
+ result[expandConfig.field] = resolved;
351
+ } else if (typeof fieldValue === "string") {
352
+ const resolved = await resolveRelationSingle(
353
+ fieldValue,
354
+ expandConfig,
355
+ context
356
+ );
357
+ result[expandConfig.field] = resolved;
358
+ }
359
+ }
360
+ return result;
361
+ }
362
+ async function resolveRelationArray(ids, expandConfig, context) {
363
+ const results = [];
364
+ let targetIds = ids;
365
+ if (expandConfig.offset) {
366
+ targetIds = targetIds.slice(expandConfig.offset);
367
+ }
368
+ if (expandConfig.limit) {
369
+ targetIds = targetIds.slice(0, expandConfig.limit);
370
+ }
371
+ for (const id of targetIds) {
372
+ const resolved = await resolveRelationSingle(id, expandConfig, context);
373
+ if (resolved) {
374
+ results.push(resolved);
375
+ }
376
+ }
377
+ return results;
378
+ }
379
+ async function resolveRelationSingle(id, expandConfig, context) {
380
+ for (const [_, contents] of context.contentsByType) {
381
+ const found = contents.find((c) => c.contentId === id || c.slug === id);
382
+ if (found) {
383
+ let data = { ...found.data };
384
+ if (expandConfig.fields) {
385
+ const filtered = {};
386
+ for (const field of expandConfig.fields) {
387
+ if (field in data) {
388
+ filtered[field] = data[field];
389
+ }
390
+ }
391
+ filtered.contentId = found.contentId;
392
+ filtered.slug = found.slug;
393
+ filtered.title = found.title;
394
+ data = filtered;
395
+ }
396
+ if (expandConfig.expand) {
397
+ data = await resolveRelations(
398
+ { ...found, data },
399
+ expandConfig.expand,
400
+ context
401
+ );
402
+ }
403
+ return data;
404
+ }
405
+ }
406
+ context.errors.push({
407
+ code: "RELATION_NOT_FOUND",
408
+ field: expandConfig.field,
409
+ message: `\u30EA\u30EC\u30FC\u30B7\u30E7\u30F3\u5148\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${id}`
410
+ });
411
+ return null;
412
+ }
413
+
414
+ // src/transform/format-functions.ts
415
+ function formatValue(value, type, options2 = {}) {
416
+ if (value === void 0 || value === null) {
417
+ if (type === "default" && options2.defaultValue !== void 0) {
418
+ return options2.defaultValue;
419
+ }
420
+ return value;
421
+ }
422
+ switch (type) {
423
+ case "string":
424
+ return String(value);
425
+ case "date":
426
+ return formatDate(value, options2.format);
427
+ case "number":
428
+ return formatNumber(value, options2.format);
429
+ case "escape":
430
+ return escapeHtml(String(value));
431
+ case "toc":
432
+ return extractToc(String(value));
433
+ case "truncate":
434
+ return truncateString(String(value), options2.length ?? 100, options2.suffix ?? "...");
435
+ case "stripHtml":
436
+ return stripHtml(String(value));
437
+ case "slug":
438
+ return slugify(String(value));
439
+ case "lowercase":
440
+ return String(value).toLowerCase();
441
+ case "uppercase":
442
+ return String(value).toUpperCase();
443
+ case "default":
444
+ return value ?? options2.defaultValue;
445
+ case "count":
446
+ return Array.isArray(value) ? value.length : 0;
447
+ case "first":
448
+ return Array.isArray(value) ? value[0] : value;
449
+ case "last":
450
+ return Array.isArray(value) ? value[value.length - 1] : value;
451
+ case "join":
452
+ return Array.isArray(value) ? value.join(options2.separator ?? ", ") : String(value);
453
+ case "url":
454
+ return encodeURIComponent(String(value));
455
+ case "picture":
456
+ case "img":
457
+ case "srcset":
458
+ case "fileLink":
459
+ return value;
460
+ default:
461
+ return value;
462
+ }
463
+ }
464
+ function formatDate(value, format) {
465
+ const date = value instanceof Date ? value : new Date(String(value));
466
+ if (isNaN(date.getTime())) {
467
+ return String(value);
468
+ }
469
+ if (!format) {
470
+ return date.toISOString();
471
+ }
472
+ return format.replace(/YYYY/g, String(date.getFullYear())).replace(/MM/g, String(date.getMonth() + 1).padStart(2, "0")).replace(/DD/g, String(date.getDate()).padStart(2, "0")).replace(/HH/g, String(date.getHours()).padStart(2, "0")).replace(/mm/g, String(date.getMinutes()).padStart(2, "0")).replace(/ss/g, String(date.getSeconds()).padStart(2, "0"));
473
+ }
474
+ function formatNumber(value, format) {
475
+ const num = typeof value === "number" ? value : parseFloat(String(value));
476
+ if (isNaN(num)) {
477
+ return String(value);
478
+ }
479
+ if (!format) {
480
+ return String(num);
481
+ }
482
+ if (format.includes(",")) {
483
+ return num.toLocaleString();
484
+ }
485
+ return String(num);
486
+ }
487
+ function escapeHtml(str) {
488
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
489
+ }
490
+ function extractToc(html) {
491
+ const toc = [];
492
+ const regex = /<h([1-6])(?:\s+id="([^"]*)")?[^>]*>([^<]*)<\/h[1-6]>/gi;
493
+ let match;
494
+ while ((match = regex.exec(html)) !== null) {
495
+ const level = parseInt(match[1], 10);
496
+ const id = match[2] || slugify(match[3]);
497
+ const text = match[3].trim();
498
+ toc.push({ level, id, text });
499
+ }
500
+ return toc;
501
+ }
502
+ function truncateString(str, length, suffix) {
503
+ if (str.length <= length) {
504
+ return str;
505
+ }
506
+ return str.slice(0, length - suffix.length) + suffix;
507
+ }
508
+ function stripHtml(html) {
509
+ return html.replace(/<[^>]*>/g, "");
510
+ }
511
+ function slugify(str) {
512
+ return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
513
+ }
514
+
515
+ // src/content/content-filter.ts
516
+ function applyFilters(contents, filters) {
517
+ if (!filters || filters.length === 0) {
518
+ return contents;
519
+ }
520
+ return contents.filter((content) => {
521
+ for (const filter of filters) {
522
+ if (!matchesFilter(content, filter)) {
523
+ return false;
524
+ }
525
+ }
526
+ return true;
527
+ });
528
+ }
529
+ function matchesFilter(content, filter) {
530
+ const value = getFieldValue(content, filter.field);
531
+ switch (filter.operator) {
532
+ case "eq":
533
+ return value === filter.value;
534
+ case "neq":
535
+ return value !== filter.value;
536
+ case "gt":
537
+ return typeof value === "number" && typeof filter.value === "number" ? value > filter.value : false;
538
+ case "gte":
539
+ return typeof value === "number" && typeof filter.value === "number" ? value >= filter.value : false;
540
+ case "lt":
541
+ return typeof value === "number" && typeof filter.value === "number" ? value < filter.value : false;
542
+ case "lte":
543
+ return typeof value === "number" && typeof filter.value === "number" ? value <= filter.value : false;
544
+ case "in":
545
+ return Array.isArray(filter.value) && filter.value.includes(value);
546
+ case "nin":
547
+ return Array.isArray(filter.value) && !filter.value.includes(value);
548
+ case "regex":
549
+ return typeof value === "string" && typeof filter.value === "string" ? new RegExp(filter.value).test(value) : false;
550
+ case "isNull":
551
+ return value === null || value === void 0;
552
+ case "isNotNull":
553
+ return value !== null && value !== void 0;
554
+ default:
555
+ return true;
556
+ }
557
+ }
558
+ function getFieldValue(content, field) {
559
+ if (field in content) {
560
+ return content[field];
561
+ }
562
+ if (field in content.data) {
563
+ return content.data[field];
564
+ }
565
+ const parts = field.split(".");
566
+ let value = content;
567
+ for (const part of parts) {
568
+ if (value === null || value === void 0) {
569
+ return void 0;
570
+ }
571
+ value = value[part];
572
+ }
573
+ return value;
574
+ }
575
+ function applySort(contents, sort) {
576
+ if (!sort) {
577
+ return contents;
578
+ }
579
+ const sortArray = Array.isArray(sort) ? sort : [sort];
580
+ return [...contents].sort((a, b) => {
581
+ for (const s of sortArray) {
582
+ const valueA = getFieldValue(a, s.field);
583
+ const valueB = getFieldValue(b, s.field);
584
+ const comparison = compareValues(valueA, valueB);
585
+ if (comparison !== 0) {
586
+ return s.direction === "desc" ? -comparison : comparison;
587
+ }
588
+ }
589
+ return 0;
590
+ });
591
+ }
592
+ function compareValues(a, b) {
593
+ if (a === null || a === void 0) return 1;
594
+ if (b === null || b === void 0) return -1;
595
+ if (typeof a === "number" && typeof b === "number") {
596
+ return a - b;
597
+ }
598
+ if (typeof a === "string" && typeof b === "string") {
599
+ return a.localeCompare(b);
600
+ }
601
+ if (a instanceof Date && b instanceof Date) {
602
+ return a.getTime() - b.getTime();
603
+ }
604
+ if (typeof a === "string" && typeof b === "string") {
605
+ const dateA = Date.parse(a);
606
+ const dateB = Date.parse(b);
607
+ if (!isNaN(dateA) && !isNaN(dateB)) {
608
+ return dateA - dateB;
609
+ }
610
+ }
611
+ return 0;
612
+ }
613
+
614
+ // src/transform/relation-expander.ts
615
+ async function expandRelationList(field, content, context) {
616
+ let contents = context.contentsByType.get(field.contentTypeId) ?? [];
617
+ if (contents.length === 0) {
618
+ context.warnings.push({
619
+ code: "EMPTY_LIST",
620
+ outputPath: content.filePath,
621
+ message: `relationList: ${field.contentTypeId} \u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u304C\u3042\u308A\u307E\u305B\u3093`
622
+ });
623
+ return [];
624
+ }
625
+ contents = applyFilters(contents, field.filters);
626
+ contents = applySort(contents, field.sort);
627
+ if (field.offset) {
628
+ contents = contents.slice(field.offset);
629
+ }
630
+ if (field.limit) {
631
+ contents = contents.slice(0, field.limit);
632
+ }
633
+ const results = [];
634
+ for (const c of contents) {
635
+ let data = { ...c.data };
636
+ if (field.listFields && field.listFields !== null) {
637
+ const filtered = {};
638
+ for (const key of field.listFields) {
639
+ if (key in data) {
640
+ filtered[key] = data[key];
641
+ }
642
+ }
643
+ filtered.contentId = c.contentId;
644
+ filtered.slug = c.slug;
645
+ filtered.title = c.title;
646
+ data = filtered;
647
+ }
648
+ if (field.expand) {
649
+ data = await resolveRelations({ ...c, data }, field.expand, context);
650
+ }
651
+ if (field.customFields) {
652
+ data = await applyCustomFields(data, field.customFields, c, context);
653
+ }
654
+ results.push(data);
655
+ }
656
+ return results;
657
+ }
658
+
659
+ // src/transform/custom-field-transformer.ts
660
+ async function applyCustomFields(data, customFields, content, context) {
661
+ if (!customFields || customFields.length === 0) {
662
+ return data;
663
+ }
664
+ const result = { ...data };
665
+ for (const field of customFields) {
666
+ if (!field.type) {
667
+ throw new Error(
668
+ `CustomField "${field.field ?? "(unknown)"}" is missing required "type" field.`
669
+ );
670
+ }
671
+ if (field.type === "constant") {
672
+ result[field.field] = field.value;
673
+ } else if (field.type === "relationList") {
674
+ const expanded = await expandRelationList(field, content, context);
675
+ result[field.field] = expanded;
676
+ } else {
677
+ const transformed = applyTransformField(field, content, result);
678
+ result[field.field] = transformed;
679
+ }
680
+ }
681
+ return result;
682
+ }
683
+ function applyTransformField(field, content, currentData) {
684
+ const sourceValue = resolveSourceExpression(field.source, content, currentData);
685
+ return formatValue(sourceValue, field.type, {
686
+ format: field.format,
687
+ length: field.length,
688
+ suffix: field.suffix,
689
+ separator: field.separator,
690
+ defaultValue: field.defaultValue
691
+ });
692
+ }
693
+ function resolveSourceExpression(source, content, currentData) {
694
+ const singleVarMatch = source.match(/^\{\$this\.([^}]+)\}$/);
695
+ if (singleVarMatch) {
696
+ const key = singleVarMatch[1];
697
+ return getValueByKey2(key, content, currentData);
698
+ }
699
+ return source.replace(/\{\$this\.([^}]+)\}/g, (_, key) => {
700
+ const value = getValueByKey2(key, content, currentData);
701
+ return value !== void 0 && value !== null ? String(value) : "";
702
+ });
703
+ }
704
+ function getValueByKey2(key, content, currentData) {
705
+ if (key in content) {
706
+ return content[key];
707
+ }
708
+ if (key in currentData) {
709
+ return currentData[key];
710
+ }
711
+ if (key in content.data) {
712
+ return content.data[key];
713
+ }
714
+ const parts = key.split(".");
715
+ let value = content;
716
+ for (const part of parts) {
717
+ if (value === null || value === void 0) {
718
+ return void 0;
719
+ }
720
+ if (typeof value === "object" && part in value) {
721
+ value = value[part];
722
+ } else if (typeof value === "object" && "data" in value && part in value.data) {
723
+ value = value.data[part];
724
+ } else {
725
+ return void 0;
726
+ }
727
+ }
728
+ return value;
729
+ }
730
+
731
+ // src/recipe/detail-processor.ts
732
+ async function processDetailRecipes(contentTypeId, recipes, targets, context) {
733
+ const outputs = [];
734
+ const contents = context.contentsByType.get(contentTypeId) ?? [];
735
+ for (const recipe of recipes) {
736
+ for (const content of contents) {
737
+ if (!shouldProcessContent(recipe.outputPath, content, targets)) {
738
+ continue;
739
+ }
740
+ try {
741
+ const output = await processDetailContent(recipe, content, context);
742
+ if (output) {
743
+ outputs.push(output);
744
+ }
745
+ } catch (error) {
746
+ context.errors.push({
747
+ code: "CONTENT_NOT_FOUND",
748
+ contentId: content.contentId,
749
+ outputPath: recipe.outputPath,
750
+ message: `DetailPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
751
+ });
752
+ }
753
+ }
754
+ }
755
+ return outputs;
756
+ }
757
+ async function processDetailContent(recipe, content, context) {
758
+ const outputPath = sanitizePath(resolveOutputPath(recipe.outputPath, content));
759
+ const pathError = validateOutputPath(outputPath);
760
+ if (pathError) {
761
+ context.errors.push({
762
+ ...pathError,
763
+ contentId: content.contentId
764
+ });
765
+ return null;
766
+ }
767
+ let data = { ...content.data };
768
+ data.contentId = content.contentId;
769
+ data.slug = content.slug;
770
+ data.title = content.title;
771
+ data.status = content.status;
772
+ data.createdAt = content.createdAt;
773
+ data.updatedAt = content.updatedAt;
774
+ data.publishedAt = content.publishedAt;
775
+ data.createdBy = content.createdBy;
776
+ if (recipe.expand) {
777
+ data = await resolveRelations({ ...content, data }, recipe.expand, context);
778
+ }
779
+ if (recipe.customFields) {
780
+ data = await applyCustomFields(data, recipe.customFields, content, context);
781
+ }
782
+ const dataJson = {
783
+ type: "update",
784
+ template: recipe.templatePath,
785
+ outputFile: toHtmlOutputPath(outputPath),
786
+ data
787
+ };
788
+ return {
789
+ path: outputPath,
790
+ content: dataJson
791
+ };
792
+ }
793
+ function shouldProcessContent(outputPathPattern, content, targets) {
794
+ if (targets.some((t) => t.reason === "full_rebuild")) {
795
+ return true;
796
+ }
797
+ const resolvedPath = sanitizePath(resolveOutputPath(outputPathPattern, content));
798
+ for (const target of targets) {
799
+ if (target.outputPath === outputPathPattern) {
800
+ if (target.contentId && target.contentId !== content.contentId) {
801
+ continue;
802
+ }
803
+ return true;
804
+ }
805
+ if (target.outputPath === resolvedPath) {
806
+ return true;
807
+ }
808
+ if (target.contentId === content.contentId) {
809
+ return true;
810
+ }
811
+ }
812
+ return false;
813
+ }
814
+
815
+ // src/recipe/list-processor.ts
816
+ async function processListRecipes(contentTypeId, recipes, targets, context) {
817
+ const outputs = [];
818
+ for (const recipe of recipes) {
819
+ if (!shouldProcessList(recipe.outputPath, targets)) {
820
+ continue;
821
+ }
822
+ try {
823
+ if (recipe.pagination) {
824
+ const paginatedOutputs = await processListWithPagination(
825
+ contentTypeId,
826
+ recipe,
827
+ context
828
+ );
829
+ outputs.push(...paginatedOutputs);
830
+ } else {
831
+ const output = await processListWithoutPagination(
832
+ contentTypeId,
833
+ recipe,
834
+ context
835
+ );
836
+ if (output) {
837
+ outputs.push(output);
838
+ }
839
+ }
840
+ } catch (error) {
841
+ context.errors.push({
842
+ code: "FILTER_ERROR",
843
+ outputPath: recipe.outputPath,
844
+ message: `ListPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
845
+ });
846
+ }
847
+ }
848
+ return outputs;
849
+ }
850
+ async function processListWithoutPagination(contentTypeId, recipe, context) {
851
+ let contents = context.contentsByType.get(contentTypeId) ?? [];
852
+ contents = applyFilters(contents, recipe.filters);
853
+ contents = applySort(contents, recipe.sort);
854
+ if (recipe.offset) {
855
+ contents = contents.slice(recipe.offset);
856
+ }
857
+ if (recipe.limit) {
858
+ contents = contents.slice(0, recipe.limit);
859
+ }
860
+ const items = await processListItems(contents, recipe, context);
861
+ const outputPath = sanitizePath(recipe.outputPath);
862
+ const pathError = validateOutputPath(outputPath);
863
+ if (pathError) {
864
+ context.errors.push(pathError);
865
+ return null;
866
+ }
867
+ if (items.length === 0) {
868
+ context.warnings.push({
869
+ code: "EMPTY_LIST",
870
+ outputPath,
871
+ message: `\u30EA\u30B9\u30C8\u304C\u7A7A\u3067\u3059: ${contentTypeId}`
872
+ });
873
+ }
874
+ const dataJson = {
875
+ type: "update",
876
+ template: recipe.templatePath,
877
+ outputFile: toHtmlOutputPath(outputPath),
878
+ data: {
879
+ items,
880
+ totalCount: items.length
881
+ }
882
+ };
883
+ return {
884
+ path: outputPath,
885
+ content: dataJson
886
+ };
887
+ }
888
+ async function processListWithPagination(contentTypeId, recipe, context) {
889
+ let contents = context.contentsByType.get(contentTypeId) ?? [];
890
+ contents = applyFilters(contents, recipe.filters);
891
+ contents = applySort(contents, recipe.sort);
892
+ if (recipe.offset) {
893
+ contents = contents.slice(recipe.offset);
894
+ }
895
+ const { perPage, numberFormatCount, startPath } = recipe.pagination;
896
+ const totalItems = contents.length;
897
+ const totalPages = Math.max(1, Math.ceil(totalItems / perPage));
898
+ const outputs = [];
899
+ for (let page = 1; page <= totalPages; page++) {
900
+ const start = (page - 1) * perPage;
901
+ const pagedContents = contents.slice(start, start + perPage);
902
+ const pagedItems = await processPagedItems(pagedContents, recipe, context);
903
+ let outputPath;
904
+ if (page === 1 && startPath) {
905
+ outputPath = sanitizePath(startPath);
906
+ } else {
907
+ outputPath = sanitizePath(resolveOutputPath(recipe.outputPath, null, page, numberFormatCount));
908
+ }
909
+ const pathError = validateOutputPath(outputPath);
910
+ if (pathError) {
911
+ context.errors.push(pathError);
912
+ continue;
913
+ }
914
+ const dataJson = {
915
+ type: "update",
916
+ template: recipe.templatePath,
917
+ outputFile: toHtmlOutputPath(outputPath),
918
+ data: {
919
+ currentPageNumber: page,
920
+ totalPagesCount: totalPages,
921
+ totalItemsCount: totalItems,
922
+ pagedItems
923
+ }
924
+ };
925
+ outputs.push({
926
+ path: outputPath,
927
+ content: dataJson
928
+ });
929
+ }
930
+ return outputs;
931
+ }
932
+ async function processListItems(contents, recipe, context) {
933
+ const items = [];
934
+ for (const content of contents) {
935
+ let data = { ...content.data };
936
+ data.contentId = content.contentId;
937
+ data.slug = content.slug;
938
+ data.title = content.title;
939
+ if (recipe.listFields && recipe.listFields !== null) {
940
+ const filtered = {
941
+ contentId: content.contentId,
942
+ slug: content.slug,
943
+ title: content.title
944
+ };
945
+ for (const key of recipe.listFields) {
946
+ if (key in content.data) {
947
+ filtered[key] = content.data[key];
948
+ }
949
+ }
950
+ data = filtered;
951
+ }
952
+ if (recipe.expand) {
953
+ data = await resolveRelations({ ...content, data }, recipe.expand, context);
954
+ }
955
+ if (recipe.customFields) {
956
+ data = await applyCustomFields(data, recipe.customFields, content, context);
957
+ }
958
+ items.push(data);
959
+ }
960
+ return items;
961
+ }
962
+ async function processPagedItems(contents, recipe, context) {
963
+ const items = [];
964
+ for (const content of contents) {
965
+ let data = { ...content.data };
966
+ data.contentId = content.contentId;
967
+ data.slug = content.slug;
968
+ data.title = content.title;
969
+ if (recipe.items?.fields && recipe.items.fields !== null) {
970
+ const filtered = {
971
+ contentId: content.contentId,
972
+ slug: content.slug,
973
+ title: content.title
974
+ };
975
+ for (const key of recipe.items.fields) {
976
+ if (key in content.data) {
977
+ filtered[key] = content.data[key];
978
+ }
979
+ }
980
+ data = filtered;
981
+ }
982
+ if (recipe.items?.expand) {
983
+ data = await resolveRelations({ ...content, data }, recipe.items.expand, context);
984
+ }
985
+ if (recipe.customFields) {
986
+ data = await applyCustomFields(data, recipe.customFields, content, context);
987
+ }
988
+ items.push(data);
989
+ }
990
+ return items;
991
+ }
992
+ function shouldProcessList(outputPathPattern, targets) {
993
+ if (targets.some((t) => t.reason === "full_rebuild")) {
994
+ return true;
995
+ }
996
+ return targets.some((t) => t.outputPath === outputPathPattern);
997
+ }
998
+
999
+ // src/recipe/static-processor.ts
1000
+ async function processStaticRecipes(recipes, targets, context) {
1001
+ const outputs = [];
1002
+ for (const recipe of recipes) {
1003
+ if (!shouldProcessStatic(recipe.outputPath, targets)) {
1004
+ continue;
1005
+ }
1006
+ try {
1007
+ const output = await processStaticPage(recipe, context);
1008
+ if (output) {
1009
+ outputs.push(output);
1010
+ }
1011
+ } catch (error) {
1012
+ context.errors.push({
1013
+ code: "CONTENT_NOT_FOUND",
1014
+ outputPath: recipe.outputPath,
1015
+ message: `StaticPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
1016
+ });
1017
+ }
1018
+ }
1019
+ return outputs;
1020
+ }
1021
+ async function processStaticPage(recipe, context) {
1022
+ const outputPath = sanitizePath(recipe.outputPath);
1023
+ const pathError = validateOutputPath(outputPath);
1024
+ if (pathError) {
1025
+ context.errors.push(pathError);
1026
+ return null;
1027
+ }
1028
+ const dummyContent = {
1029
+ contentId: "static",
1030
+ contentTypeId: "static",
1031
+ slug: "static",
1032
+ title: "",
1033
+ status: "published",
1034
+ data: {},
1035
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1036
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1037
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1038
+ createdBy: "system",
1039
+ filePath: recipe.outputPath
1040
+ };
1041
+ let data = {};
1042
+ if (recipe.customFields) {
1043
+ data = await applyCustomFields(data, recipe.customFields, dummyContent, context);
1044
+ }
1045
+ const dataJson = {
1046
+ type: "update",
1047
+ template: recipe.templatePath,
1048
+ outputFile: toHtmlOutputPath(outputPath),
1049
+ data
1050
+ };
1051
+ return {
1052
+ path: outputPath,
1053
+ content: dataJson
1054
+ };
1055
+ }
1056
+ function shouldProcessStatic(outputPath, targets) {
1057
+ if (targets.some((t) => t.reason === "full_rebuild")) {
1058
+ return true;
1059
+ }
1060
+ return targets.some((t) => t.outputPath === outputPath);
1061
+ }
1062
+
1063
+ // src/utils/logger.ts
1064
+ function createLogger(level) {
1065
+ const shouldLog = (targetLevel) => {
1066
+ if (level === "quiet") {
1067
+ return targetLevel === "error";
1068
+ }
1069
+ if (level === "info") {
1070
+ return targetLevel !== "debug";
1071
+ }
1072
+ return true;
1073
+ };
1074
+ return {
1075
+ debug(message, ...args) {
1076
+ if (shouldLog("debug")) {
1077
+ console.log(`[DEBUG] ${message}`, ...args);
1078
+ }
1079
+ },
1080
+ info(message, ...args) {
1081
+ if (shouldLog("info")) {
1082
+ console.log(`[INFO] ${message}`, ...args);
1083
+ }
1084
+ },
1085
+ error(message, ...args) {
1086
+ if (shouldLog("error")) {
1087
+ console.error(`[ERROR] ${message}`, ...args);
1088
+ }
1089
+ }
1090
+ };
1091
+ }
1092
+
1093
+ // src/generator.ts
1094
+ async function generateDataJson(input) {
1095
+ const {
1096
+ recipe,
1097
+ dependencyMap,
1098
+ gitDiff,
1099
+ fileSystem,
1100
+ contentRootPath,
1101
+ outputRootPath,
1102
+ options: options2 = {}
1103
+ } = input;
1104
+ const {
1105
+ fullRebuild = false,
1106
+ dryRun = false,
1107
+ logLevel = "info"
1108
+ } = options2;
1109
+ const logger = createLogger(logLevel);
1110
+ const recipeValidation = validateSiteRecipe(recipe);
1111
+ if (!recipeValidation.success) {
1112
+ throw new Error(`Invalid recipe:
1113
+ ${formatZodErrors(recipeValidation.errors)}`);
1114
+ }
1115
+ logger.info(`Starting data-json generation (mode: ${fullRebuild ? "full-rebuild" : "incremental"})`);
1116
+ const errors = [];
1117
+ const warnings = [];
1118
+ let targets;
1119
+ if (fullRebuild) {
1120
+ targets = getAllOutputPaths(dependencyMap);
1121
+ logger.info(`Full rebuild: ${targets.length} outputs`);
1122
+ } else {
1123
+ const changes = classifyChangedFiles(gitDiff);
1124
+ targets = calculateRegenerationScope(changes, dependencyMap, recipe);
1125
+ logger.info(`Incremental build: ${targets.length} outputs affected`);
1126
+ if (logLevel === "debug") {
1127
+ logger.debug("Changed files:", gitDiff);
1128
+ logger.debug("Regeneration targets:", targets);
1129
+ }
1130
+ }
1131
+ if (targets.length === 0) {
1132
+ logger.info("No changes detected, nothing to regenerate");
1133
+ return createEmptyResult(dryRun, fullRebuild);
1134
+ }
1135
+ const requiredContentTypes = extractRequiredContentTypes(recipe);
1136
+ logger.debug(`Required content types: ${requiredContentTypes.join(", ")}`);
1137
+ logger.info(`Loading contents for ${requiredContentTypes.length} content types...`);
1138
+ const contentsByType = await loadContentsByType(
1139
+ requiredContentTypes,
1140
+ contentRootPath,
1141
+ fileSystem,
1142
+ logger
1143
+ );
1144
+ const totalContents = Array.from(contentsByType.values()).reduce((sum, arr) => sum + arr.length, 0);
1145
+ logger.info(`Loaded ${totalContents} contents`);
1146
+ const context = {
1147
+ contentsByType,
1148
+ fileSystem,
1149
+ contentRootPath,
1150
+ outputRootPath,
1151
+ errors,
1152
+ warnings,
1153
+ logLevel
1154
+ };
1155
+ const outputs = [];
1156
+ for (const [contentTypeId, contentTypeRecipe] of Object.entries(recipe.contentTypes)) {
1157
+ if (contentTypeRecipe.details && contentTypeRecipe.details.length > 0) {
1158
+ logger.debug(`Processing detail recipes for ${contentTypeId}`);
1159
+ const detailOutputs = await processDetailRecipes(
1160
+ contentTypeId,
1161
+ contentTypeRecipe.details,
1162
+ targets,
1163
+ context
1164
+ );
1165
+ outputs.push(...detailOutputs);
1166
+ }
1167
+ }
1168
+ for (const [contentTypeId, contentTypeRecipe] of Object.entries(recipe.contentTypes)) {
1169
+ if (contentTypeRecipe.lists && contentTypeRecipe.lists.length > 0) {
1170
+ logger.debug(`Processing list recipes for ${contentTypeId}`);
1171
+ const listOutputs = await processListRecipes(
1172
+ contentTypeId,
1173
+ contentTypeRecipe.lists,
1174
+ targets,
1175
+ context
1176
+ );
1177
+ outputs.push(...listOutputs);
1178
+ }
1179
+ }
1180
+ if (recipe.staticPages && recipe.staticPages.length > 0) {
1181
+ logger.debug("Processing static recipes");
1182
+ const staticOutputs = await processStaticRecipes(
1183
+ recipe.staticPages,
1184
+ targets,
1185
+ context
1186
+ );
1187
+ outputs.push(...staticOutputs);
1188
+ }
1189
+ const deleteOutputs = await detectDeletedOutputs(
1190
+ outputs,
1191
+ outputRootPath,
1192
+ fileSystem,
1193
+ targets,
1194
+ fullRebuild,
1195
+ logger
1196
+ );
1197
+ const deduplicatedOutputs = deduplicateOutputs(outputs, errors);
1198
+ const report = createReport({
1199
+ outputs: deduplicatedOutputs,
1200
+ deleteOutputs,
1201
+ errors: [...errors, ...context.errors],
1202
+ warnings: [...warnings, ...context.warnings],
1203
+ fullRebuild,
1204
+ dryRun});
1205
+ logger.info(`Generation completed: ${report.stats.updated} updated, ${report.stats.deleted} deleted, ${report.stats.errors} errors`);
1206
+ return {
1207
+ outputs: [...deduplicatedOutputs, ...deleteOutputs],
1208
+ report
1209
+ };
1210
+ }
1211
+ function extractRequiredContentTypes(recipe) {
1212
+ const contentTypes = /* @__PURE__ */ new Set();
1213
+ for (const contentTypeId of Object.keys(recipe.contentTypes)) {
1214
+ contentTypes.add(contentTypeId);
1215
+ }
1216
+ return Array.from(contentTypes);
1217
+ }
1218
+ async function detectDeletedOutputs(generatedOutputs, outputRootPath, fileSystem, targets, fullRebuild, logger) {
1219
+ const deleteOutputs = [];
1220
+ if (!fullRebuild) {
1221
+ const deleteTargets = targets.filter((t) => t.reason === "deleted");
1222
+ for (const target of deleteTargets) {
1223
+ const generated = generatedOutputs.some((o) => o.path === target.outputPath);
1224
+ if (!generated) {
1225
+ deleteOutputs.push({
1226
+ path: target.outputPath,
1227
+ content: {
1228
+ type: "delete",
1229
+ outputFile: toHtmlOutputPath(target.outputPath)
1230
+ }
1231
+ });
1232
+ logger.debug(`Marked for deletion: ${target.outputPath}`);
1233
+ }
1234
+ }
1235
+ return deleteOutputs;
1236
+ }
1237
+ try {
1238
+ const existingFiles = await fileSystem.listFiles(`${outputRootPath}/**/*.json`);
1239
+ const existingOutputPaths = existingFiles.filter((f) => !f.endsWith("report.json")).map((f) => f.replace(`${outputRootPath}/`, ""));
1240
+ const generatedPaths = new Set(generatedOutputs.map((o) => o.path));
1241
+ for (const existingPath of existingOutputPaths) {
1242
+ if (!generatedPaths.has(existingPath)) {
1243
+ deleteOutputs.push({
1244
+ path: existingPath,
1245
+ content: {
1246
+ type: "delete",
1247
+ outputFile: toHtmlOutputPath(existingPath)
1248
+ }
1249
+ });
1250
+ logger.debug(`Marked for deletion (orphaned): ${existingPath}`);
1251
+ }
1252
+ }
1253
+ } catch {
1254
+ logger.debug("Could not list existing files for deletion detection");
1255
+ }
1256
+ return deleteOutputs;
1257
+ }
1258
+ function deduplicateOutputs(outputs, errors) {
1259
+ const seen = /* @__PURE__ */ new Map();
1260
+ const duplicates = [];
1261
+ for (const output of outputs) {
1262
+ if (seen.has(output.path)) {
1263
+ duplicates.push(output.path);
1264
+ } else {
1265
+ seen.set(output.path, output);
1266
+ }
1267
+ }
1268
+ for (const path of duplicates) {
1269
+ errors.push({
1270
+ code: "DUPLICATE_OUTPUT_PATH",
1271
+ outputPath: path,
1272
+ message: `\u51FA\u529B\u30D1\u30B9\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059: ${path}`
1273
+ });
1274
+ }
1275
+ return Array.from(seen.values());
1276
+ }
1277
+ function createEmptyResult(dryRun, fullRebuild) {
1278
+ return {
1279
+ outputs: [],
1280
+ report: {
1281
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1282
+ mode: fullRebuild ? "full-rebuild" : "incremental",
1283
+ dryRun,
1284
+ stats: {
1285
+ updated: 0,
1286
+ deleted: 0,
1287
+ skipped: 0,
1288
+ errors: 0
1289
+ },
1290
+ outputs: [],
1291
+ errors: [],
1292
+ warnings: []
1293
+ }
1294
+ };
1295
+ }
1296
+ function createReport(params) {
1297
+ const { outputs, deleteOutputs, errors, warnings, fullRebuild, dryRun} = params;
1298
+ const outputEntries = [
1299
+ ...outputs.map((o) => ({ path: o.path, status: "updated" })),
1300
+ ...deleteOutputs.map((o) => ({ path: o.path, status: "deleted" }))
1301
+ ];
1302
+ return {
1303
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1304
+ mode: fullRebuild ? "full-rebuild" : "incremental",
1305
+ dryRun,
1306
+ stats: {
1307
+ updated: outputs.length,
1308
+ deleted: deleteOutputs.length,
1309
+ skipped: 0,
1310
+ // TODO: スキップ数をカウント
1311
+ errors: errors.length
1312
+ },
1313
+ outputs: outputEntries,
1314
+ errors,
1315
+ warnings
1316
+ };
1317
+ }
1318
+ var NodeFileSystem = class {
1319
+ /**
1320
+ * ファイルを読み込む
1321
+ *
1322
+ * @param path ファイルパス
1323
+ * @returns ファイル内容(UTF-8)
1324
+ * @throws ファイルが存在しない場合
1325
+ */
1326
+ async readFile(path) {
1327
+ return readFile(path, "utf-8");
1328
+ }
1329
+ /**
1330
+ * ファイルの存在確認
1331
+ *
1332
+ * @param path ファイルパス
1333
+ * @returns 存在すれば true
1334
+ */
1335
+ async exists(path) {
1336
+ return existsSync(path);
1337
+ }
1338
+ /**
1339
+ * glob パターンにマッチするファイル一覧を取得
1340
+ *
1341
+ * @param pattern glob パターン
1342
+ * @returns マッチしたファイルパスの配列
1343
+ */
1344
+ async listFiles(pattern) {
1345
+ const normalizedPattern = pattern.replace(/\\/g, "/");
1346
+ const files = await glob(normalizedPattern, {
1347
+ nodir: true,
1348
+ windowsPathsNoEscape: true
1349
+ });
1350
+ return files;
1351
+ }
1352
+ };
1353
+ var execAsync = promisify(exec);
1354
+ function parseGitDiff(diffText) {
1355
+ const added = [];
1356
+ const modified = [];
1357
+ const deleted = [];
1358
+ const lines = diffText.trim().split("\n").filter((line) => line.trim());
1359
+ for (const line of lines) {
1360
+ const parts = line.split(" ");
1361
+ if (parts.length < 2) continue;
1362
+ const status = parts[0].trim();
1363
+ const path = parts[parts.length - 1].trim();
1364
+ switch (status[0]) {
1365
+ // R100 のような場合は最初の文字だけ見る
1366
+ case "A":
1367
+ added.push(path);
1368
+ break;
1369
+ case "M":
1370
+ modified.push(path);
1371
+ break;
1372
+ case "D":
1373
+ deleted.push(path);
1374
+ break;
1375
+ case "R":
1376
+ if (parts.length >= 3) {
1377
+ deleted.push(parts[1].trim());
1378
+ }
1379
+ added.push(path);
1380
+ break;
1381
+ case "C":
1382
+ added.push(path);
1383
+ break;
1384
+ }
1385
+ }
1386
+ return { added, modified, deleted };
1387
+ }
1388
+ async function getGitDiff(diffRange) {
1389
+ if (!diffRange) {
1390
+ return { added: [], modified: [], deleted: [] };
1391
+ }
1392
+ try {
1393
+ const { stdout } = await execAsync(`git diff --name-status ${diffRange}`);
1394
+ return parseGitDiff(stdout);
1395
+ } catch (error) {
1396
+ const message = error instanceof Error ? error.message : String(error);
1397
+ throw new Error(`Failed to get git diff: ${message}`);
1398
+ }
1399
+ }
1400
+ var { values } = parseArgs({
1401
+ options: {
1402
+ "diff-range": { type: "string", default: "origin/main...HEAD" },
1403
+ "full-rebuild": { type: "boolean", default: false },
1404
+ "dry-run": { type: "boolean", default: false },
1405
+ "log-level": { type: "string", default: "info" }
1406
+ }
1407
+ });
1408
+ var options = {
1409
+ fullRebuild: values["full-rebuild"],
1410
+ dryRun: values["dry-run"],
1411
+ logLevel: values["log-level"]
1412
+ };
1413
+ var CONTENT_ROOT = "frelio-data/site";
1414
+ var OUTPUT_ROOT = "frelio-data/site/data/data-json";
1415
+ var REPORT_PATH = "frelio-data/site/data/report.json";
1416
+ var RECIPE_PATH = "frelio-data/admin/recipes/build-data-recipe.json";
1417
+ var DEPENDENCY_MAP_PATH = "frelio-data/site/data/_dependency-map.json";
1418
+ async function main() {
1419
+ if (!existsSync(RECIPE_PATH)) {
1420
+ console.error(`Recipe not found: ${RECIPE_PATH}`);
1421
+ process.exit(1);
1422
+ }
1423
+ const recipe = JSON.parse(readFileSync(RECIPE_PATH, "utf-8"));
1424
+ if (!existsSync(DEPENDENCY_MAP_PATH)) {
1425
+ console.error(`Dependency map not found: ${DEPENDENCY_MAP_PATH}`);
1426
+ process.exit(1);
1427
+ }
1428
+ const dependencyMap = JSON.parse(readFileSync(DEPENDENCY_MAP_PATH, "utf-8"));
1429
+ const gitDiff = options.fullRebuild ? { added: [], modified: [], deleted: [] } : await getGitDiff(values["diff-range"]);
1430
+ if (options.logLevel !== "quiet") {
1431
+ console.log(`Mode: ${options.fullRebuild ? "full-rebuild" : "incremental"}`);
1432
+ console.log(`Dry run: ${options.dryRun}`);
1433
+ }
1434
+ const result = await generateDataJson({
1435
+ recipe,
1436
+ dependencyMap,
1437
+ gitDiff,
1438
+ fileSystem: new NodeFileSystem(),
1439
+ contentRootPath: CONTENT_ROOT,
1440
+ outputRootPath: OUTPUT_ROOT,
1441
+ options
1442
+ });
1443
+ if (!options.dryRun) {
1444
+ mkdirSync(OUTPUT_ROOT, { recursive: true });
1445
+ for (const output of result.outputs) {
1446
+ if (output.content.type === "delete") {
1447
+ const fullPath = join(OUTPUT_ROOT, output.path);
1448
+ if (existsSync(fullPath)) unlinkSync(fullPath);
1449
+ }
1450
+ }
1451
+ for (const output of result.outputs) {
1452
+ if (output.content.type !== "delete") {
1453
+ const fullPath = join(OUTPUT_ROOT, output.path);
1454
+ mkdirSync(dirname(fullPath), { recursive: true });
1455
+ writeFileSync(fullPath, JSON.stringify(output.content, null, 2));
1456
+ }
1457
+ }
1458
+ }
1459
+ mkdirSync(dirname(REPORT_PATH), { recursive: true });
1460
+ writeFileSync(REPORT_PATH, JSON.stringify(result.report, null, 2));
1461
+ const { stats } = result.report;
1462
+ console.log(`
1463
+ === Summary ===`);
1464
+ console.log(`Updated: ${stats.updated}`);
1465
+ console.log(`Deleted: ${stats.deleted}`);
1466
+ console.log(`Skipped: ${stats.skipped}`);
1467
+ console.log(`Errors: ${stats.errors}`);
1468
+ }
1469
+ main().catch((error) => {
1470
+ console.error("Fatal error:", error);
1471
+ process.exit(1);
1472
+ });
1473
+ //# sourceMappingURL=cli.js.map
1474
+ //# sourceMappingURL=cli.js.map