@kenjura/ursa 0.96.0 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +72 -16
  3. package/bin/ursa.js +14 -1
  4. package/meta/templates/default-template/menu.js +18 -1
  5. package/meta/templates/default-template/search.js +11 -0
  6. package/meta/templates/default-template/widgets.js +4 -0
  7. package/package.json +1 -2
  8. package/src/dev.js +13 -23
  9. package/src/helper/__test__/contentHash.test.js +16 -6
  10. package/src/helper/assetBundler.js +93 -19
  11. package/src/helper/automenu.js +36 -11
  12. package/src/helper/build/__test__/autoIndex.test.js +2 -132
  13. package/src/helper/build/__test__/graph.test.js +259 -3
  14. package/src/helper/build/__test__/pass.test.js +553 -0
  15. package/src/helper/build/autoIndex.js +2 -371
  16. package/src/helper/build/excludeFilter.js +1 -2
  17. package/src/helper/build/footer.js +27 -14
  18. package/src/helper/build/graph.js +575 -152
  19. package/src/helper/build/index.js +0 -2
  20. package/src/helper/build/metadata.js +19 -5
  21. package/src/helper/build/pass.js +497 -0
  22. package/src/helper/build/precedence.js +174 -0
  23. package/src/helper/build/site.js +1270 -0
  24. package/src/helper/build/templates.js +1 -2
  25. package/src/helper/build/tracedFs.js +247 -0
  26. package/src/helper/contentHash.js +0 -78
  27. package/src/helper/customMenu.js +1 -1
  28. package/src/helper/fileRenderer.js +119 -111
  29. package/src/helper/findScriptJs.js +1 -1
  30. package/src/helper/findStyleCss.js +1 -1
  31. package/src/helper/folderConfig.js +7 -18
  32. package/src/helper/fullTextIndex.js +41 -29
  33. package/src/helper/imageProcessor.js +45 -0
  34. package/src/helper/linkValidator.js +118 -127
  35. package/src/helper/mdxRenderer.js +27 -5
  36. package/src/helper/menuLabels.js +30 -5
  37. package/src/helper/whitelistFilter.js +1 -2
  38. package/src/jobs/generate.js +67 -1829
  39. package/src/serve.js +317 -697
  40. package/src/helper/__test__/dependencyTracker.test.js +0 -157
  41. package/src/helper/build/cacheBust.js +0 -141
  42. package/src/helper/build/navCache.js +0 -145
  43. package/src/helper/build/watchCache.js +0 -33
  44. package/src/helper/dependencyTracker.js +0 -384
@@ -1,140 +1,12 @@
1
- import { recurse } from "../helper/recursive-readdir.js";
2
- import { copyFile, mkdir, readdir, readFile, stat } from "fs/promises";
3
- import { getAutomenu } from "../helper/automenu.js";
4
- import { filterAsync } from "../helper/filterAsync.js";
5
- import { isDirectory } from "../helper/isDirectory.js";
6
- import { isFolderHidden, clearConfigCache } from "../helper/folderConfig.js";
7
- import { isHiddenOrSystemPath } from "../helper/hiddenPaths.js";
8
- import { IMAGE_EXTENSIONS, isMedia } from "../helper/staticAssets.js";
9
- import {
10
- extractMetadata,
11
- extractRawMetadata,
12
- isMetadataOnly,
13
- getAutoIndexConfig,
14
- } from "../helper/metadataExtractor.js";
15
- import { injectFrontmatterTable } from "../helper/frontmatterTable.js";
16
- import {
17
- hashContent,
18
- loadHashCache,
19
- saveHashCache,
20
- needsRegeneration,
21
- outputsExist,
22
- updateHash,
23
- getUrsaDir,
24
- enforceCacheVersion,
25
- } from "../helper/contentHash.js";
26
- import {
27
- buildValidPaths,
28
- markInactiveLinks,
29
- resolveRelativeUrls,
30
- } from "../helper/linkValidator.js";
31
- import { getAndIncrementBuildId } from "../helper/ursaConfig.js";
32
- import { buildSourceTimestampIndex } from "../helper/sourceTimestamps.js";
33
- import { extractSections } from "../helper/sectionExtractor.js";
34
- import { renderFile, renderFileAsync, terminateParserPool } from "../helper/fileRenderer.js";
35
- import { buildReactRuntime } from "../helper/mdxRenderer.js";
36
- import { findStyleCss, findAllStyleCss } from "../helper/findStyleCss.js";
37
- import { findScriptJs, findAllScriptJs } from "../helper/findScriptJs.js";
38
- import { bundleMetaTemplateAssets, bundleDocumentCss, bundleDocumentJs, clearMetaBundleCache, generateSeparateCssTags, generateSeparateJsTags } from "../helper/assetBundler.js";
39
- import { buildFullTextIndex, buildIncrementalIndex, loadIndexCache, saveIndexCache } from "../helper/fullTextIndex.js";
40
- import { dependencyTracker, loadDependencyTracker, saveDependencyTracker } from "../helper/dependencyTracker.js";
41
- import { CacheBustHashMap } from "../helper/build/cacheBust.js";
42
- import { copy as copyDir, emptyDir, outputFile, remove } from "fs-extra";
43
- import { basename, dirname, extname, join, parse, resolve } from "path";
44
- import { URL } from "url";
45
- import o2x from "object-to-xml";
46
- import { existsSync } from "fs";
47
- import { createWhitelistFilter } from "../helper/whitelistFilter.js";
48
- import { processAllImages, transformImageTags, clearImageCache, copyAllImagesFast } from "../helper/imageProcessor.js";
49
- import { extractImageReferences } from "../helper/imageExtractor.js";
50
- import { checkFileSize, readFileStreaming, formatFileSize } from "../helper/streamingReader.js";
51
- import { generateBreadcrumbs } from "../helper/breadcrumbs.js";
52
- import {
53
- loadNavCache,
54
- saveNavCache,
55
- hashFileList,
56
- hashFileStats,
57
- isNavCacheValid,
58
- createNavCacheEntry,
59
- restoreMap,
60
- } from "../helper/build/navCache.js";
61
-
62
- // Import build helpers from organized modules
63
- import {
64
- generateCacheBustTimestamp,
65
- addTimestampToCssUrls,
66
- addTimestampToHtmlStaticRefs,
67
- processBatched,
68
- ProgressReporter,
69
- watchModeCache,
70
- clearWatchCache as clearWatchCacheBase,
71
- toTitleCase,
72
- parseExcludeOption,
73
- createExcludeFilter,
74
- addTrailingSlash,
75
- getTemplates,
76
- getMenu,
77
- findAllCustomMenus,
78
- getCustomMenuForFile,
79
- getTransformedMetadata,
80
- getFooter,
81
- getUrsaMetadata,
82
- generateAutoIndices,
83
- generateAutoIndexHtmlFromSource,
84
- copyMetaAssets,
85
- } from "../helper/build/index.js";
86
- import { getProfiler } from "../helper/build/profiler.js";
87
- import { reconcileAll, isInsideTemplatesFolder } from "../helper/documentTemplates.js";
88
-
89
- // Concurrency limiter for batch processing to avoid memory exhaustion
90
- const BATCH_SIZE = parseInt(process.env.URSA_BATCH_SIZE || '50', 10);
91
-
92
- // Cache for CSS path lookups to avoid repeated filesystem walks
93
- const cssPathCache = new Map();
94
-
95
- // Cache for script path lookups to avoid repeated filesystem walks
96
- const scriptPathCache = new Map();
97
-
98
- // Cache for document-level CSS/JS bundle paths to avoid re-bundling identical sets
99
- const docBundleCache = new Map();
100
-
101
- // Wrapper for clearWatchCache that passes cssPathCache and scriptPathCache
102
- export function clearWatchCache() {
103
- clearWatchCacheBase(cssPathCache);
104
- scriptPathCache.clear();
105
- docBundleCache.clear();
106
- clearMetaBundleCache();
107
- }
108
-
109
- // Clear just the script-related caches (for when script.js changes)
110
- export function clearScriptCache() {
111
- scriptPathCache.clear();
112
- // Clear all JS bundle cache entries
113
- for (const key of docBundleCache.keys()) {
114
- if (key.startsWith('js:')) {
115
- docBundleCache.delete(key);
116
- }
117
- }
118
- }
119
-
120
- // Clear just the CSS-related caches (for when style.css changes)
121
- export function clearStyleCache() {
122
- cssPathCache.clear();
123
- // Clear all CSS bundle cache entries
124
- for (const key of docBundleCache.keys()) {
125
- if (key.startsWith('css:')) {
126
- docBundleCache.delete(key);
127
- }
128
- }
129
- }
130
-
131
- const progress = new ProgressReporter();
132
-
133
- const DEFAULT_TEMPLATE_NAME =
134
- process.env.DEFAULT_TEMPLATE_NAME ?? "default-template";
135
-
136
1
  /**
137
- * Build a site from `_source` into `_output`.
2
+ * `ursa generate`: one build pass over the incremental build graph.
3
+ *
4
+ * The pass is the same one `ursa serve` runs on every change (see
5
+ * docs/SERVE.md §5.4 and src/helper/build/pass.js). A cold start is a pass in
6
+ * which every leaf is new; a warm start re-checks the persisted graph in
7
+ * `.ursa/graph.json` and recomputes only what its inputs say has changed.
8
+ * Outputs whose source is gone are deleted, so the output directory converges
9
+ * on what a clean build would produce without `--clean`.
138
10
  *
139
11
  * ## JSON-ONLY MODE (`_jsonOnly`)
140
12
  *
@@ -144,1720 +16,86 @@ const DEFAULT_TEMPLATE_NAME =
144
16
  * CSS/JS bundles, static file copying, the search and full-text indices,
145
17
  * recent-activity and menu data, and auto-generated index pages.
146
18
  *
147
- * The emitted JSON is byte-identical to what a full build writes. Every step
148
- * that is skipped operates on the assembled *page*; the JSON's `bodyHtml` is the
149
- * pre-template render, which none of them touch.
150
- *
151
- * For pipelines that consume ursa's JSON as data rather than publishing a site.
152
- * Mixing modes against one source tree is safe: the two share a hash cache, and
153
- * the per-document output check (`expectedOutputs`) asks only for the outputs
154
- * the current mode emits.
19
+ * The emitted JSON is byte-identical to what a full build writes: the JSON's
20
+ * `bodyHtml` is the pre-template render, which none of the skipped steps touch.
21
+ * Mixing modes against one source tree is safe — the graph records what each
22
+ * output consumed, and a node that was never demanded keeps its state.
155
23
  */
24
+
25
+ import { join, resolve } from "path";
26
+ import { outputFile } from "fs-extra";
27
+ import { createBuild } from "../helper/build/pass.js";
28
+ import { getProfiler } from "../helper/build/profiler.js";
29
+
156
30
  export async function generate({
157
31
  _source = join(process.cwd(), "."),
158
32
  _meta = join(process.cwd(), "meta"),
159
33
  _output = join(process.cwd(), "build"),
160
34
  _whitelist = null,
161
35
  _exclude = null,
162
- _incremental = false, // Legacy flag, now ignored (always incremental)
163
- _clean = false, // When true, ignore cache and regenerate all files
164
- _deferImages = false, // When true, copy images without processing, return promise for background processing
165
- _deferSearchIndex = false, // When true, return promise for search index building (for faster startup)
166
- _jsonOnly = false, // When true, emit only the .json data files (see JSON-ONLY MODE below)
36
+ _incremental = false, // Legacy flag, now ignored (always incremental)
37
+ _clean = false, // When true, ignore the graph and regenerate all files
38
+ _deferImages = false, // Legacy: previews are always scheduled after pages
39
+ _deferSearchIndex = false, // Legacy: indices are always scheduled after pages
40
+ _jsonOnly = false, // When true, emit only the .json data files (see JSON-ONLY MODE below)
41
+ _explain = false, // Log why each recomputed node recomputed
167
42
  } = {}) {
168
- // Initialize profiler for this build
169
43
  const profiler = getProfiler(true);
170
-
171
- console.log({ _source, _meta, _output, _whitelist, _exclude, _clean, _deferImages, _deferSearchIndex, _jsonOnly });
172
- const source = resolve(_source) + "/";
44
+ const source = resolve(_source);
173
45
  const meta = resolve(_meta);
174
- const output = resolve(_output) + "/";
175
- console.log({ source, meta, output });
176
-
177
- // Generate cache-busting timestamp for this build
178
- const cacheBustTimestamp = generateCacheBustTimestamp();
179
- const cacheBustHashes = new CacheBustHashMap();
180
- progress.logTimed(`Cache-bust timestamp: ${cacheBustTimestamp}`);
181
-
182
- // Initialize dependency tracker for this build
183
- dependencyTracker.init(source);
184
-
185
- // Clear output directory and cache when --clean is specified
186
- if (_clean) {
187
- progress.startTimer('Clean');
188
- const ursaDir = getUrsaDir(source);
189
- progress.logTimed(`Clean build: deleting cache folder ${ursaDir}`);
190
- await remove(ursaDir);
191
- progress.logTimed(`Clean build: clearing output directory ${output}`);
192
- await emptyDir(output);
193
- progress.logTimed(`Clean complete [${progress.stopTimer('Clean')}]`);
194
- }
195
-
196
- // Stamp the cache with ursa's version, discarding it if a different ursa
197
- // wrote it. Hash-skipping only compares source content, so without this an
198
- // upgrade leaves every unchanged document frozen at whatever the previous
199
- // version's templates and renderers produced.
200
- const cacheStamp = await enforceCacheVersion(source);
201
- if (cacheStamp.reset) {
202
- progress.logTimed(
203
- `Cache discarded: written by ursa ${cacheStamp.previous ?? '(unstamped)'}, now running ${cacheStamp.version}`
204
- );
205
- }
206
-
207
- if (!_clean) {
208
- // Warm start: reload persisted dependency registrations so hash-skipped
209
- // documents keep their edges (current-run registrations take precedence)
210
- const loaded = await loadDependencyTracker(source);
211
- if (loaded) {
212
- const stats = dependencyTracker.getStats();
213
- progress.logTimed(`Dependency graph loaded: ${stats.totalDocuments} documents, ${stats.uniqueFiles} dependencies`);
214
- }
215
- }
216
-
217
- // Phase: Scan source files
218
- profiler.startPhase('Scan source files');
219
- progress.startTimer('Scan');
220
- const allSourceFilenamesUnfiltered = await recurse(source, [() => false]);
221
- progress.logTimed(`Scanned ${allSourceFilenamesUnfiltered.length} files [${progress.stopTimer('Scan')}]`);
222
- profiler.endPhase('Scan source files');
223
-
224
- // Phase: Filter and classify files
225
- profiler.startPhase('Filter & classify');
226
- progress.startTimer('Filter');
227
-
228
- // Clear config cache at start of generation to pick up any changes
229
- clearConfigCache();
230
-
231
- // Apply include filter (existing functionality)
232
- const includeFilter = process.env.INCLUDE_FILTER
233
- ? (fileName) => fileName.match(process.env.INCLUDE_FILTER)
234
- : Boolean;
235
- let allSourceFilenames = allSourceFilenamesUnfiltered.filter(includeFilter);
236
-
237
- // Apply exclude filter if specified
238
- if (_exclude) {
239
- const excludedPaths = await parseExcludeOption(_exclude, source);
240
- const excludeFilter = createExcludeFilter(excludedPaths, source);
241
- const beforeCount = allSourceFilenames.length;
242
- allSourceFilenames = allSourceFilenames.filter(excludeFilter);
243
- progress.logTimed(`Exclude filter applied: ${beforeCount - allSourceFilenames.length} files excluded`);
244
- }
245
-
246
- // Apply whitelist filter if specified
247
- if (_whitelist) {
248
- const whitelistFilter = await createWhitelistFilter(_whitelist, source);
249
- allSourceFilenames = allSourceFilenames.filter(whitelistFilter);
250
- progress.logTimed(`Whitelist applied: ${allSourceFilenames.length} files after filtering`);
251
- }
252
-
253
- // Drop everything inside a folder that config.json marks `hidden: true`.
254
- //
255
- // Applied once, to the whole file list, rather than to each category
256
- // downstream. `hidden` means the folder takes no part in the build at all,
257
- // and filtering here is the only way to actually mean it: articles,
258
- // directories, images, fonts and other media, and hand-written HTML are all
259
- // derived from this list, so each of them inherits the exclusion instead of
260
- // needing its own check (and instead of silently missing one — images and
261
- // media used to be copied out of hidden folders for exactly that reason).
262
- const beforeHiddenCount = allSourceFilenames.length;
263
- allSourceFilenames = allSourceFilenames.filter(
264
- (filename) => !isFolderHidden(filename, source)
265
- );
266
- const hiddenCount = beforeHiddenCount - allSourceFilenames.length;
267
- if (hiddenCount > 0) {
268
- progress.logTimed(`Hidden folders: ${hiddenCount} paths ignored`);
269
- }
270
-
271
- // read all articles, process them, copy them to build
272
- const articleExtensions = /\.(md|mdx|txt|yml)$/;
273
- // Hidden/system folders are judged RELATIVE to the docroot — see
274
- // helper/hiddenPaths.js for why testing the absolute path silently produces
275
- // an empty site when the checkout lives under a dot-directory.
276
- const isHiddenOrSystem = (filename) => isHiddenOrSystemPath(filename, source);
277
- const allSourceFilenamesThatAreArticles = allSourceFilenames.filter(
278
- (filename) => filename.match(articleExtensions) && !isHiddenOrSystem(filename)
279
- );
280
- const allSourceFilenamesThatAreDirectories = (await filterAsync(
281
- allSourceFilenames,
282
- (filename) => isDirectory(filename)
283
- )).filter((filename) => !isHiddenOrSystem(filename));
284
-
285
- // Build set of existing HTML files in source directory (these should not be overwritten)
286
- const htmlExtensions = /\.html$/;
287
- const existingHtmlFiles = new Set(
288
- allSourceFilenames
289
- .filter(f => f.match(htmlExtensions) && !isHiddenOrSystem(f))
290
- .map(f => f.replace(source, '')) // Store relative paths for easy lookup
291
- );
292
-
293
- progress.logTimed(`Classified: ${allSourceFilenamesThatAreArticles.length} articles, ${allSourceFilenamesThatAreDirectories.length} dirs, ${existingHtmlFiles.size} HTML [${progress.stopTimer('Filter')}]`);
294
- profiler.endPhase('Filter & classify');
295
-
296
- // Drop persisted dependency registrations for documents that no longer
297
- // exist (or are excluded), so stale entries don't accumulate across runs
298
- dependencyTracker.prune(new Set(allSourceFilenamesThatAreArticles));
299
-
300
- // Phase: Document template reconciliation
301
- // Must run BEFORE article processing so that any template-driven changes
302
- // to source .md files are picked up during rendering.
303
- profiler.startPhase('Template reconciliation');
304
- progress.startTimer('Templates');
305
- const templateReconciliation = await reconcileAll(
306
- allSourceFilenamesThatAreArticles,
307
- allSourceFilenamesUnfiltered, // templates live in _templates which is filtered out of articles
308
- source
309
- );
310
- if (templateReconciliation.updated > 0 || templateReconciliation.conflicts > 0 || templateReconciliation.initialized > 0) {
311
- progress.logTimed(
312
- `📄 Document templates: ${templateReconciliation.initialized} initialized, ` +
313
- `${templateReconciliation.updated} auto-merged, ` +
314
- `${templateReconciliation.conflicts} conflicts, ` +
315
- `${templateReconciliation.unchanged} unchanged, ` +
316
- `${templateReconciliation.errors} errors`
317
- );
318
- if (templateReconciliation.conflicts > 0) {
319
- console.warn(`\n⚠️ Template conflicts require manual resolution:`);
320
- for (const msg of templateReconciliation.messages) {
321
- if (msg.includes('Conflict')) console.warn(` ${msg}`);
322
- }
323
- console.warn('');
324
- }
325
- if (templateReconciliation.errors > 0) {
326
- for (const msg of templateReconciliation.messages) {
327
- if (msg.includes('Error') || msg.includes('not found')) console.warn(` ⚠️ ${msg}`);
328
- }
329
- }
330
- }
331
- progress.logTimed(`Document templates processed [${progress.stopTimer('Templates')}]`);
332
- profiler.endPhase('Template reconciliation');
333
-
334
- // Phase: Build navigation and metadata
335
- profiler.startPhase('Build navigation');
336
- progress.startTimer('Navigation');
337
-
338
- // Check if we can use cached navigation
339
- let validPaths, templates, menu, menuData, customMenus, footer, buildId;
340
- let navCacheUsed = false;
341
-
342
- if (!_clean) {
343
- const fileListHash = hashFileList(allSourceFilenames);
344
- const fileStatsHash = await hashFileStats(allSourceFilenames);
345
- const navCache = await loadNavCache(source);
346
-
347
- if (isNavCacheValid(navCache, fileListHash, fileStatsHash)) {
348
- // Use cached navigation data
349
- navCacheUsed = true;
350
- validPaths = restoreMap(navCache.validPaths);
351
- menuData = navCache.menuData;
352
- menu = navCache.menuHtml;
353
- customMenus = restoreMap(navCache.customMenus);
354
-
355
- // Templates and footer still need to be loaded (they depend on meta directory)
356
- templates = await getTemplates(meta);
357
- buildId = getAndIncrementBuildId(resolve(_source));
358
- footer = await getFooter(source, _source, buildId);
359
-
360
- progress.logTimed(`Navigation loaded from cache: ${validPaths.size} paths, ${customMenus.size} custom menus [${progress.stopTimer('Navigation')}]`);
361
- } else {
362
- // Cache miss - build navigation from scratch
363
- validPaths = buildValidPaths(allSourceFilenamesThatAreArticles, source, allSourceFilenamesThatAreDirectories);
364
- templates = await getTemplates(meta);
365
-
366
- const menuResult = await getMenu(allSourceFilenames, source, validPaths);
367
- menu = menuResult.html;
368
- menuData = menuResult.menuData;
369
-
370
- customMenus = findAllCustomMenus(allSourceFilenames, source);
371
- buildId = getAndIncrementBuildId(resolve(_source));
372
- footer = await getFooter(source, _source, buildId);
373
-
374
- // Save to cache for next run
375
- const cacheEntry = createNavCacheEntry(
376
- fileListHash,
377
- fileStatsHash,
378
- menuData,
379
- menu,
380
- Array.from(validPaths.entries()),
381
- Array.from(customMenus.entries())
382
- );
383
- await saveNavCache(source, cacheEntry);
384
-
385
- progress.logTimed(`Navigation built: ${validPaths.size} paths, ${customMenus.size} custom menus [${progress.stopTimer('Navigation')}]`);
386
- }
387
- } else {
388
- // Clean build - ignore cache
389
- validPaths = buildValidPaths(allSourceFilenamesThatAreArticles, source, allSourceFilenamesThatAreDirectories);
390
- templates = await getTemplates(meta);
391
-
392
- const menuResult = await getMenu(allSourceFilenames, source, validPaths);
393
- menu = menuResult.html;
394
- menuData = menuResult.menuData;
395
-
396
- customMenus = findAllCustomMenus(allSourceFilenames, source);
397
- buildId = getAndIncrementBuildId(resolve(_source));
398
- footer = await getFooter(source, _source, buildId);
399
-
400
- progress.logTimed(`Navigation built (clean): ${validPaths.size} paths, ${customMenus.size} custom menus [${progress.stopTimer('Navigation')}]`);
401
- }
402
-
403
- profiler.endPhase('Build navigation');
404
-
405
- // Build the _ursa_metadata embedded in every generated JSON file (ursa + doc repo versions)
406
- const ursaMetadata = await getUrsaMetadata(_source);
407
-
408
- // Phase: Load cache
409
- profiler.startPhase('Load cache');
410
- progress.startTimer('Cache');
411
-
412
- // Load content hash cache from .ursa folder in source directory
413
- let hashCache = new Map();
414
- if (!_clean) {
415
- hashCache = await loadHashCache(source);
416
- progress.logTimed(`Loaded ${hashCache.size} cached hashes [${progress.stopTimer('Cache')}]`);
417
- } else {
418
- progress.logTimed(`Clean build: ignoring cached hashes`);
419
- progress.stopTimer('Cache');
420
- }
421
-
422
- // Last-edited times for the recent-activity feed come from git history (or
423
- // file mtimes outside git), never from when ursa ran, so --clean cannot
424
- // stamp every document with the build time.
425
- const sourceTimestamps = await buildSourceTimestampIndex(source, { log: (m) => progress.log(m) });
426
- progress.logTimed(`Source timestamps: ${sourceTimestamps.source}`);
427
- profiler.endPhase('Load cache');
428
-
429
- // Phase: Copy meta/public files
430
- //
431
- // Entirely HTML support: templates, their bundled CSS/JS, the React runtime
432
- // for MDX hydration, and a cache-bust rewrite over every .css/.js already in
433
- // the output tree. A JSON-only build renders no page, so none of it is
434
- // reachable — and the cache-bust pass alone walks the whole output dir.
435
- profiler.startPhase('Copy meta files');
436
- progress.startTimer('Meta');
437
-
438
- if (!_jsonOnly) {
439
- // create public folder
440
- const pub = join(output, "public");
441
- await mkdir(pub, { recursive: true });
442
-
443
- // Copy meta assets with new template folder structure
444
- const { copiedFiles, orphanedFiles } = await copyMetaAssets(meta, pub);
445
-
446
- // Warn about orphaned files in meta that aren't part of any template
447
- if (orphanedFiles.length > 0) {
448
- console.warn(`\n⚠️ Warning: Found ${orphanedFiles.length} orphaned file(s) in meta directory:`);
449
- console.warn(` These files are not in meta/templates/ or meta/shared/ and won't be included:`);
450
- for (const file of orphanedFiles.slice(0, 10)) {
451
- console.warn(` - ${file}`);
452
- }
453
- if (orphanedFiles.length > 10) {
454
- console.warn(` ... and ${orphanedFiles.length - 10} more`);
455
- }
456
- console.warn(` Move them to meta/templates/{templateName}/ or meta/shared/ to include them.\n`);
457
- }
458
-
459
- // Bundle meta template assets (CSS + JS) into single files per template
460
- // This must happen after copying meta to public but before cache-busting
461
- templates = await bundleMetaTemplateAssets(templates, meta, pub, { minify: true, sourcemap: false });
462
- progress.logTimed(`Meta template assets bundled`);
463
-
464
- // Build React runtime for MDX hydration (React 19 has no UMD, so we bundle locally)
465
- await buildReactRuntime(pub);
466
-
467
- // Process all CSS files in the entire output directory tree for cache-busting
468
- const allOutputFiles = await recurse(output, [() => false]);
469
- for (const cssFile of allOutputFiles.filter(f => f.endsWith('.css'))) {
470
- const cssContent = await readFile(cssFile, 'utf8');
471
- const processedCss = addTimestampToCssUrls(cssContent, cacheBustTimestamp);
472
- await outputFile(cssFile, processedCss);
473
- }
474
-
475
- // Process JS files in output for cache-busting fetch URLs
476
- for (const jsFile of allOutputFiles.filter(f => f.endsWith('.js'))) {
477
- let jsContent = await readFile(jsFile, 'utf8');
478
- jsContent = jsContent.replace(
479
- /fetch\(['"]([^'"\)]+\.(json))['"](?!\s*\+)/g,
480
- `fetch('$1?v=${cacheBustTimestamp}'`
481
- );
482
- await outputFile(jsFile, jsContent);
483
- }
484
-
485
- progress.logTimed(`Meta files copied and processed [${progress.stopTimer('Meta')}]`);
486
- } else {
487
- progress.logTimed(`JSON-only: skipped meta assets, template bundles and React runtime [${progress.stopTimer('Meta')}]`);
488
- }
489
- profiler.endPhase('Copy meta files');
490
-
491
- // Track errors for error report
492
- const errors = [];
493
-
494
- // Search index: built incrementally during article processing (lighter memory footprint)
495
- const searchIndex = [];
496
- // Full-text index: collect documents for word-to-document mapping
497
- const fullTextDocs = [];
498
- // Recent activity: collect {title, url, mtime} for all articles, keep top 10 by mtime
499
- const recentActivity = [];
500
- // Track paths of documents that were regenerated (for incremental index updates)
501
- const changedPaths = new Set();
502
- // Directory index cache: only stores minimal data needed for directory indices
503
- // Uses WeakRef-style approach - store only what's needed, clear as we go
504
- const dirIndexCache = new Map();
505
-
506
- // Track CSS files that have been copied to avoid duplicates
507
- const copiedCssFiles = new Set();
508
-
509
- // Identify all image files from the filtered source list.
510
- // A JSON-only build copies and resizes nothing, so the list stays empty and
511
- // the whitelist reference scan below (which reads every article) is skipped.
512
- const imageExtensions = IMAGE_EXTENSIONS;
513
- let allSourceFilenamesThatAreImages = _jsonOnly ? [] : allSourceFilenames.filter(
514
- (filename) => filename.match(imageExtensions) && !isHiddenOrSystem(filename)
515
- );
516
-
517
- // When using a whitelist, also include images referenced by whitelisted documents
518
- // This ensures that images used in whitelisted articles are processed even if not explicitly whitelisted
519
- if (_whitelist && !_jsonOnly) {
520
- progress.logTimed('Scanning whitelisted articles for image references...');
521
- const referencedImages = new Set();
522
-
523
- for (const articlePath of allSourceFilenamesThatAreArticles) {
524
- try {
525
- const content = await readFile(articlePath, 'utf8');
526
- const imageRefs = extractImageReferences(content, articlePath, source);
527
- imageRefs.forEach(img => referencedImages.add(img));
528
- } catch (e) {
529
- // Ignore read errors - file might not exist or be unreadable
530
- }
531
- }
532
-
533
- // Get all images from the unfiltered source list that are referenced
534
- const allImagesUnfiltered = allSourceFilenamesUnfiltered.filter(
535
- (filename) => filename.match(imageExtensions) && !isHiddenOrSystem(filename)
536
- );
537
-
538
- // Add referenced images that aren't already in the list
539
- const additionalImages = allImagesUnfiltered.filter(
540
- img => referencedImages.has(img) && !allSourceFilenamesThatAreImages.includes(img)
541
- );
542
-
543
- if (additionalImages.length > 0) {
544
- progress.logTimed(`Found ${additionalImages.length} additional images referenced by whitelisted documents`);
545
- allSourceFilenamesThatAreImages = [...allSourceFilenamesThatAreImages, ...additionalImages];
546
- }
547
- }
548
-
549
- // Phase: Process images
550
- profiler.startPhase('Process images');
551
- progress.startTimer('Images');
552
-
553
- // Handle images based on deferred mode
554
- let imageMap = new Map();
555
- let deferredImageProcessingPromise = null;
556
-
557
- if (_jsonOnly) {
558
- // `bodyHtml` in the JSON is the pre-template render; `transformImageTags`
559
- // only ever rewrote the assembled page, never this. So skipping image
560
- // processing leaves the JSON byte-identical to a full build's.
561
- progress.done('Images', `skipped (JSON-only) [${progress.stopTimer('Images')}]`);
562
- profiler.endPhase('Process images');
563
- } else if (_deferImages) {
564
- // Fast mode: just copy images without processing, defer preview generation
565
- progress.logTimed(`Copying ${allSourceFilenamesThatAreImages.length} images (preview generation deferred)...`);
566
- await copyAllImagesFast(
567
- allSourceFilenamesThatAreImages,
568
- source,
569
- output,
570
- (current, total, path) => {
571
- progress.status('Images (copy)', `${current}/${total} ${path}`);
572
- }
573
- );
574
- progress.done('Images (copy)', `${allSourceFilenamesThatAreImages.length} copied (previews deferred)`);
575
- profiler.endPhase('Process images');
576
-
577
- // Create promise for background image processing (will be returned to caller)
578
- deferredImageProcessingPromise = (async () => {
579
- progress.logTimed(`\n🖼️ Starting deferred image preview generation...`);
580
- const startTime = Date.now();
581
- const processedImageMap = await processAllImages(
582
- allSourceFilenamesThatAreImages,
583
- source,
584
- output,
585
- (current, total, path) => {
586
- progress.status('Images (previews)', `${current}/${total} ${path}`);
587
- }
588
- );
589
- const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
590
- progress.done('Images (previews)', `${allSourceFilenamesThatAreImages.length} done (${processedImageMap.size} with previews) in ${elapsed}s`);
591
-
592
- // Update the watch cache with the processed image map
593
- watchModeCache.imageMap = processedImageMap;
594
-
595
- return processedImageMap;
596
- })();
597
- } else {
598
- // Normal mode: process all images FIRST to build the preview image map
599
- // This is done before articles so we can transform img tags in the HTML
600
- progress.logTimed(`Processing ${allSourceFilenamesThatAreImages.length} images for preview generation...`);
601
- imageMap = await processAllImages(
602
- allSourceFilenamesThatAreImages,
603
- source,
604
- output,
605
- (current, total, path) => {
606
- progress.status('Images', `${current}/${total} ${path}`);
607
- }
608
- );
609
- progress.done('Images', `${allSourceFilenamesThatAreImages.length} done (${imageMap.size} with previews) [${progress.stopTimer('Images')}]`);
610
- profiler.endPhase('Process images');
611
- }
612
-
613
- // Phase: Process articles
614
- profiler.startPhase('Process articles');
615
- progress.startTimer('Articles');
616
-
617
- // Track files that were regenerated (for incremental mode stats)
618
- let regeneratedCount = 0;
619
- let skippedCount = 0;
620
- let processedCount = 0;
621
- const totalArticles = allSourceFilenamesThatAreArticles.length;
622
-
623
- progress.logTimed(`Processing ${totalArticles} articles in batches of ${BATCH_SIZE}...`);
624
-
625
- // Single pass: process all articles with batched concurrency to limit memory usage
626
- await processBatched(allSourceFilenamesThatAreArticles, async (file) => {
627
- try {
628
- processedCount++;
629
- const shortFile = file.replace(source, '');
630
- progress.status('Articles', `${processedCount}/${totalArticles} ${shortFile}`);
631
-
632
- // Use streaming for large files to reduce memory pressure
633
- const { size: fileSize, useStreaming } = await checkFileSize(file);
634
- let rawBody;
635
- if (useStreaming) {
636
- rawBody = await readFileStreaming(file, 'utf8');
637
- progress.log(`📄 Streaming large file ${shortFile} (${formatFileSize(fileSize)})`);
638
- } else {
639
- rawBody = await readFile(file, "utf8");
640
- }
641
-
642
- const type = parse(file).ext;
643
- const ext = extname(file);
644
- const base = basename(file, ext);
645
- const dir = addTrailingSlash(dirname(file)).replace(source, "");
646
-
647
- // Calculate output paths for this file
648
- const outputFilename = file
649
- .replace(source, output)
650
- .replace(parse(file).ext, ".html");
651
- const url = '/' + outputFilename.replace(output, '');
652
-
653
- // Generate URL path relative to output (for search index)
654
- const relativePath = file.replace(source, '').replace(/\.(md|mdx|txt|yml)$/, '.html');
655
- const searchUrl = relativePath.startsWith('/') ? relativePath : '/' + relativePath;
656
-
657
- // Generate title from filename (in title case)
658
- // For index/home files, use parent folder name instead
659
- const titleBase = (base === 'index' || base === 'home') ? basename(dirname(file)) : base;
660
- const title = toTitleCase(titleBase || base);
661
-
662
- // Always add to search index (lightweight: title + path only, content added lazily)
663
- searchIndex.push({
664
- title: title,
665
- path: relativePath,
666
- url: searchUrl,
667
- content: '' // Content excerpts built lazily to save memory
668
- });
669
-
670
- // Add document to full-text index (uses raw markdown content)
671
- fullTextDocs.push({
672
- path: relativePath,
673
- title: title,
674
- content: rawBody
675
- });
676
-
677
- // Collect last-edited time for recent activity tracking
678
- recentActivity.push({
679
- title: title,
680
- url: searchUrl,
681
- mtime: await sourceTimestamps.get(file)
682
- });
683
-
684
- // Check if a corresponding .html file already exists in source directory
685
- const outputHtmlRelative = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;
686
- if (existingHtmlFiles.has(outputHtmlRelative)) {
687
- progress.log(`⚠️ Warning: Skipping ${shortFile} - would overwrite existing ${outputHtmlRelative} in source`);
688
- skippedCount++;
689
- return;
690
- }
691
-
692
- // Skip metadata-only index files - they exist only to provide folder metadata
693
- // The auto-index system will generate the actual index.html for these folders
694
- if (base === 'index' && (type === '.md' || type === '.mdx') && isMetadataOnly(rawBody)) {
695
- progress.log(`ℹ️ Skipping metadata-only ${shortFile} - auto-index will generate listing`);
696
- skippedCount++;
697
- return;
698
- }
699
-
700
- // Metadata is needed both for the cache decision below and for rendering.
701
- const fileMeta = extractMetadata(rawBody);
702
-
703
- // A document with `generate-auto-index: true` renders a listing of the
704
- // source tree, so its output depends on which folders and files exist —
705
- // not just on its own text. A content hash cannot see that: adding,
706
- // renaming, or deleting a folder anywhere in the tree leaves the hash
707
- // untouched and the listing stale forever. Only a handful of documents
708
- // opt in, so always rebuild them.
709
- const hasAutoIndex = getAutoIndexConfig(fileMeta).enabled;
710
-
711
- // Check if file needs regeneration.
712
- // An unchanged hash is not enough: the hash cache lives in the source tree
713
- // and is shared across output dirs, so also require that every output this
714
- // document emits is actually present before skipping it.
715
- //
716
- // In JSON-only mode only the .json is required. That is what lets the two
717
- // modes share one hash cache safely: a JSON-only run after a full build
718
- // skips (the .json is there and is identical either way), and a full build
719
- // after a JSON-only run regenerates (the .html and .xml are missing).
720
- const expectedOutputs = _jsonOnly
721
- ? [outputFilename.replace(".html", ".json")]
722
- : [
723
- outputFilename,
724
- outputFilename.replace(".html", ".json"),
725
- outputFilename.replace(".html", ".xml"),
726
- ];
727
- const needsRegen =
728
- _clean ||
729
- hasAutoIndex ||
730
- needsRegeneration(file, rawBody, hashCache) ||
731
- !outputsExist(expectedOutputs);
732
-
733
- if (!needsRegen) {
734
- skippedCount++;
735
- // For directory indices, store minimal data (not full bodyHtml)
736
- // But include metadata for directory JSON files
737
- dirIndexCache.set(file, {
738
- name: base,
739
- url,
740
- metadata: fileMeta,
741
- });
742
- return; // Skip regenerating this file
743
- }
744
-
745
- regeneratedCount++;
746
- // Track this path for incremental search index updates
747
- changedPaths.add(relativePath);
748
-
749
- const rawMeta = extractRawMetadata(rawBody);
750
-
751
- // Lazy metadata transform - only compute if template actually uses it
752
- // This defers the potentially expensive custom transform function load
753
- let transformedMetadata = null;
754
- const getTransformedMeta = async () => {
755
- if (transformedMetadata === null) {
756
- transformedMetadata = await getTransformedMetadata(dirname(file), fileMeta);
757
- }
758
- return transformedMetadata;
759
- };
760
-
761
- // Calculate the document's URL path (e.g., "/character/index.html")
762
- const docUrlPath = '/' + dir + base + '.html';
763
-
764
- // Use async rendering with worker threads for parallel markdown parsing
765
- // Wikitext (.txt) files will fall back to main thread
766
- // For MDX files, enable hydration if frontmatter has `hydrate: true`
767
- const shouldHydrate = type === '.mdx' && fileMeta?.hydrate === true;
768
-
769
- let renderResult = await renderFileAsync({
770
- fileContents: rawBody,
771
- type,
772
- dirname: dir,
773
- basename: base,
774
- filePath: file,
775
- sourceRoot: source,
776
- useWorker: true,
777
- hydrate: shouldHydrate,
778
- });
779
-
780
- // Handle the result - can be string or { html, hydrationScript }
781
- let body;
782
- let hydrationScript = '';
783
- if (typeof renderResult === 'object' && renderResult.html) {
784
- body = renderResult.html;
785
- hydrationScript = renderResult.hydrationScript || '';
786
- } else {
787
- body = renderResult;
788
- }
789
-
790
- // Inject default H1 if body doesn't start with one
791
- if (!body || !body.trimStart().startsWith('<h1')) {
792
- const h1Title = fileMeta?.title || title;
793
- body = `<h1>${h1Title}</h1>\n` + (body || '');
794
- }
795
-
796
- // Inject breadcrumbs before the H1
797
- const breadcrumbs = generateBreadcrumbs(dir, base, fileMeta, source);
798
- if (breadcrumbs) {
799
- body = breadcrumbs + body;
800
- }
801
-
802
- // Inject frontmatter table after first H1 (for markdown files with metadata)
803
- if ((type === '.md' || type === '.mdx') && fileMeta) {
804
- body = injectFrontmatterTable(body, fileMeta);
805
- }
806
-
807
- // Handle auto-index generation for index files with generate-auto-index: true
808
- if (base === 'index' && fileMeta) {
809
- const autoIndexConfig = getAutoIndexConfig(fileMeta);
810
- if (autoIndexConfig.enabled) {
811
- // Generate auto-index HTML for this directory from source
812
- // Using source avoids race conditions with concurrent file generation
813
- const sourceDir = dirname(file);
814
- const autoIndexHtml = await generateAutoIndexHtmlFromSource(sourceDir, autoIndexConfig.depth);
815
-
816
- if (autoIndexHtml) {
817
- if (autoIndexConfig.position === 'bottom') {
818
- body = body + '\n' + autoIndexHtml;
819
- } else {
820
- body = autoIndexHtml + '\n' + body;
821
- }
822
- }
823
- }
824
- }
825
-
826
- // Everything from here to the HTML write is page assembly: per-folder
827
- // CSS/JS bundles, the template, the custom menu, link resolution and
828
- // image-tag rewriting. The JSON below is built from `body`, which is
829
- // already final — none of it feeds the JSON, so JSON-only skips it all.
830
- if (!_jsonOnly) {
831
- // Find all style.css files up the tree and bundle them into a single CSS file per folder path
832
- // (Generate mode: one CSS bundle per unique folder, minimizing requests per page load)
833
- let styleLink = "";
834
- try {
835
- const dirKey = (dir === "/" || dir === "") ? _source : resolve(_source, dir);
836
- const folderRelative = (dir === "/" || dir === "") ? "" : dir;
837
-
838
- // Check bundle cache first (dirs with same CSS ancestry share the same bundle)
839
- let cachedBundleUrl = docBundleCache.get(`css:${dirKey}`);
840
- if (cachedBundleUrl !== undefined) {
841
- if (cachedBundleUrl) {
842
- styleLink = `<link rel="stylesheet" href="${cachedBundleUrl}" />`;
843
- }
844
- } else {
845
- let cssPaths = cssPathCache.get(dirKey);
846
- if (cssPaths === undefined) {
847
- cssPaths = await findAllStyleCss(dirKey, _source);
848
- cssPathCache.set(dirKey, cssPaths);
849
- }
850
- if (cssPaths.length > 0) {
851
- // Copy all source CSS files to output (still needed for serve mode fallback)
852
- for (const cssPath of cssPaths) {
853
- if (!copiedCssFiles.has(cssPath)) {
854
- const cssOutputPath = cssPath.replace(source, output);
855
- const cssContent = await readFile(cssPath, 'utf8');
856
- await outputFile(cssOutputPath, cssContent);
857
- copiedCssFiles.add(cssPath);
858
- }
859
- }
860
- // Bundle into a single file
861
- const bundleUrl = await bundleDocumentCss(cssPaths, output, source, folderRelative, { minify: true });
862
- docBundleCache.set(`css:${dirKey}`, bundleUrl);
863
- styleLink = `<link rel="stylesheet" href="${bundleUrl}" />`;
864
- } else {
865
- docBundleCache.set(`css:${dirKey}`, null);
866
- }
867
- }
868
- } catch (e) {
869
- // ignore
870
- console.error(e);
871
- }
872
-
873
- // Find all script.js files from docroot to current dir and bundle them
874
- // (Generate mode: one JS bundle per unique folder, external not inlined)
875
- let customScript = "";
876
- try {
877
- const dirKey = (dir === "/" || dir === "") ? _source : resolve(_source, dir);
878
- const folderRelative = (dir === "/" || dir === "") ? "" : dir;
879
-
880
- let cachedBundleUrl = docBundleCache.get(`js:${dirKey}`);
881
- if (cachedBundleUrl !== undefined) {
882
- if (cachedBundleUrl) {
883
- customScript = `<script src="${cachedBundleUrl}"></script>`;
884
- }
885
- } else {
886
- let scriptPaths = scriptPathCache.get(dirKey);
887
- if (scriptPaths === undefined) {
888
- scriptPaths = await findAllScriptJs(dirKey, _source);
889
- scriptPathCache.set(dirKey, scriptPaths);
890
- }
891
- if (scriptPaths.length > 0) {
892
- const bundleUrl = await bundleDocumentJs(scriptPaths, output, source, folderRelative, { minify: true });
893
- docBundleCache.set(`js:${dirKey}`, bundleUrl);
894
- customScript = `<script src="${bundleUrl}"></script>`;
895
- } else {
896
- docBundleCache.set(`js:${dirKey}`, null);
897
- }
898
- }
899
- } catch (e) {
900
- // ignore
901
- console.error(e);
902
- }
903
-
904
- const requestedTemplateName = fileMeta && fileMeta.template;
905
- const templateName = requestedTemplateName || DEFAULT_TEMPLATE_NAME;
906
- const template = templates[templateName];
907
-
908
- if (!template) {
909
- throw new Error(`Template not found. Requested: "${templateName}". Available templates: ${Object.keys(templates).join(', ') || 'none'}`);
910
- }
911
-
912
- // Register this document's dependencies for invalidation tracking
913
- {
914
- const dirKey = (dir === "/" || dir === "") ? _source : resolve(_source, dir);
915
- const cssDeps = cssPathCache.get(dirKey) || [];
916
- const jsDeps = scriptPathCache.get(dirKey) || [];
917
- dependencyTracker.registerDocument(file, {
918
- templateName,
919
- cssPaths: cssDeps,
920
- scriptPaths: jsDeps,
921
- });
922
- }
923
-
924
- // Check if this file has a custom menu
925
- const customMenuInfo = getCustomMenuForFile(file, source, customMenus);
926
-
927
- // Lazy evaluation of transformed metadata - only compute if template uses it
928
- // This defers expensive custom transform function loading until actually needed
929
- const templateUsesTransformedMeta = template.includes('${transformedMetadata}');
930
- const lazyTransformedMeta = templateUsesTransformedMeta
931
- ? await getTransformedMeta()
932
- : '';
933
-
934
- // Build final HTML with all replacements in a single regex pass
935
- // This avoids creating 8 intermediate strings
936
- // Append hydration script to customScript if present (for MDX with hydrate: true)
937
- const finalCustomScript = hydrationScript
938
- ? customScript + '\n' + hydrationScript
939
- : customScript;
940
-
941
- const replacements = {
942
- "${title}": fileMeta?.title || title,
943
- "${menu}": menu,
944
- "${meta}": JSON.stringify(fileMeta),
945
- "${transformedMetadata}": lazyTransformedMeta,
946
- "${body}": body,
947
- "${styleLink}": styleLink,
948
- "${customScript}": finalCustomScript,
949
- "${searchIndex}": "[]", // Placeholder - search index written separately as JSON file
950
- "${footer}": footer
951
- };
952
- // Single-pass replacement using regex alternation
953
- const pattern = /\$\{(title|menu|meta|transformedMetadata|body|styleLink|customScript|searchIndex|footer)\}/g;
954
- let finalHtml = template.replace(pattern, (match) => replacements[match] ?? match);
955
-
956
- // Add menu data attributes to body
957
- if (customMenuInfo) {
958
- const menuPosition = customMenuInfo.menuPosition || 'top';
959
- finalHtml = finalHtml.replace(
960
- /<body([^>]*)>/,
961
- `<body$1 data-custom-menu="${customMenuInfo.menuJsonPath}" data-menu-position="${menuPosition}">`
962
- );
963
- } else {
964
- // No custom menu — default to top menu
965
- finalHtml = finalHtml.replace(
966
- /<body([^>]*)>/,
967
- `<body$1 data-menu-position="top">`
968
- );
969
- }
970
-
971
- // Resolve relative URLs in raw HTML elements (img src, etc.)
972
- finalHtml = resolveRelativeUrls(finalHtml, docUrlPath);
973
-
974
- // Resolve links and mark broken internal links as inactive
975
- finalHtml = markInactiveLinks(finalHtml, validPaths, docUrlPath, false);
976
-
977
- // Transform image tags to use preview images with data-fullsrc for originals
978
- // Skip in deferred mode - images will use original paths until preview generation completes
979
- if (!_deferImages) {
980
- finalHtml = transformImageTags(finalHtml, imageMap, docUrlPath);
981
- }
982
-
983
- // Add cache-busting timestamps to static file references
984
- finalHtml = addTimestampToHtmlStaticRefs(finalHtml, cacheBustTimestamp);
985
-
986
- await outputFile(outputFilename, finalHtml);
987
-
988
- // Clear finalHtml reference to allow GC
989
- finalHtml = null;
990
- }
991
-
992
- // JSON output
993
- const jsonOutputFilename = outputFilename.replace(".html", ".json");
994
-
995
- // Extract sections for markdown files
996
- const sections = (type === '.md' || type === '.mdx') ? extractSections(rawBody) : [];
997
-
998
- // Use lazy metadata for JSON output - may have been computed above for HTML
999
- const jsonTransformedMeta = await getTransformedMeta();
1000
-
1001
- const jsonObject = {
1002
- name: base,
1003
- url,
1004
- contents: rawBody,
1005
- bodyHtml: body,
1006
- metadata: fileMeta,
1007
- sections,
1008
- transformedMetadata: jsonTransformedMeta,
1009
- _ursa_metadata: ursaMetadata,
1010
- };
1011
-
1012
- // Store minimal data for directory indices, including metadata
1013
- dirIndexCache.set(file, {
1014
- name: base,
1015
- url,
1016
- metadata: fileMeta,
1017
- });
1018
-
1019
- const json = JSON.stringify(jsonObject);
1020
- await outputFile(jsonOutputFilename, json);
1021
-
1022
- // XML output
1023
- if (!_jsonOnly) {
1024
- const xmlOutputFilename = outputFilename.replace(".html", ".xml");
1025
- const xml = `<article>${o2x(jsonObject)}</article>`;
1026
- await outputFile(xmlOutputFilename, xml);
1027
- }
1028
-
1029
- // Update the content hash for this file
1030
- updateHash(file, rawBody, hashCache);
1031
- } catch (e) {
1032
- progress.log(`Error processing ${file}: ${e.message}`);
1033
- errors.push({ file, phase: 'article-generation', error: e });
1034
- }
1035
- });
1036
-
1037
- // Complete the articles status line
1038
- progress.done('Articles', `${totalArticles} done (${regeneratedCount} regenerated, ${skippedCount} unchanged) [${progress.stopTimer('Articles')}]`);
1039
- profiler.endPhase('Process articles');
1040
-
1041
- // Phase: Write search index
1042
- // Can be deferred in serve mode for faster startup
1043
- let deferredSearchIndexPromise = null;
1044
-
1045
- const buildSearchIndex = async () => {
1046
- const indexStartTime = Date.now();
1047
- progress.logTimed('Building search index...');
1048
-
1049
- // Write search index as a separate JSON file (not embedded in each page)
1050
- const searchIndexPath = join(output, 'public', 'search-index.json');
1051
- progress.log(`Writing search index with ${searchIndex.length} entries`);
1052
- await outputFile(searchIndexPath, JSON.stringify(searchIndex));
1053
-
1054
- // Build full-text index - use incremental mode when possible
1055
- let fullTextIndex;
1056
- if (!_clean && changedPaths.size > 0 && changedPaths.size < fullTextDocs.length) {
1057
- // Incremental update: only re-index changed documents
1058
- progress.log(`Incremental full-text index: ${changedPaths.size} changed, ${fullTextDocs.length - changedPaths.size} cached`);
1059
- fullTextIndex = buildIncrementalIndex(fullTextDocs, changedPaths, source);
1060
- } else {
1061
- // Full rebuild: clean build or all documents changed
1062
- progress.log(`Building full-text index from ${fullTextDocs.length} documents...`);
1063
- fullTextIndex = buildFullTextIndex(fullTextDocs);
1064
- // Save to cache for future incremental updates
1065
- saveIndexCache(source, fullTextIndex);
1066
- }
1067
-
1068
- const fullTextIndexPath = join(output, 'public', 'fulltext-index.json');
1069
- const fullTextIndexJson = JSON.stringify(fullTextIndex);
1070
- const wordCount = Object.keys(fullTextIndex).length;
1071
- progress.log(`Writing full-text index (${wordCount} unique words, ${(fullTextIndexJson.length / 1024).toFixed(1)} KB)`);
1072
- await outputFile(fullTextIndexPath, fullTextIndexJson);
1073
-
1074
- const elapsed = ((Date.now() - indexStartTime) / 1000).toFixed(1);
1075
- return { entries: searchIndex.length, words: wordCount, elapsed };
1076
- };
1077
-
1078
- if (_jsonOnly) {
1079
- // Search and full-text indices exist for the site's client-side search UI,
1080
- // which a JSON-only build does not emit. The full-text build is also the
1081
- // most expensive step after rendering.
1082
- profiler.startPhase('Write search index');
1083
- progress.done('Search index', 'skipped (JSON-only)');
1084
- profiler.endPhase('Write search index');
1085
- } else if (_deferSearchIndex) {
1086
- // Deferred mode: start building in background, return promise
1087
- profiler.startPhase('Write search index (deferred)');
1088
- progress.startTimer('Search index');
1089
- progress.log('Search index building deferred for faster startup...');
1090
- deferredSearchIndexPromise = buildSearchIndex().then(result => {
1091
- progress.done('Search index (background)', `${result.entries} entries, ${result.words} words in ${result.elapsed}s`);
1092
- return result;
1093
- });
1094
- progress.done('Search index', 'deferred [0ms]');
1095
- profiler.endPhase('Write search index (deferred)');
1096
- } else {
1097
- // Normal mode: build search index now
1098
- profiler.startPhase('Write search index');
1099
- progress.startTimer('Search index');
1100
- const result = await buildSearchIndex();
1101
- progress.done('Search index', `${result.entries} entries, ${result.words} words [${progress.stopTimer('Search index')}]`);
1102
- profiler.endPhase('Write search index');
1103
- }
1104
-
1105
- // Phase: Write recent activity data
1106
- profiler.startPhase('Write recent activity');
1107
- progress.startTimer('Recent activity');
1108
- if (!_jsonOnly) {
1109
- // Sort by mtime descending, keep top 10
1110
- recentActivity.sort((a, b) => b.mtime - a.mtime);
1111
- const top10 = recentActivity.slice(0, 10);
1112
- const recentActivityPath = join(output, 'public', 'recent-activity.json');
1113
- await outputFile(recentActivityPath, JSON.stringify(top10));
1114
- progress.done('Recent activity', `${top10.length} entries [${progress.stopTimer('Recent activity')}]`);
1115
- } else {
1116
- progress.done('Recent activity', `skipped (JSON-only) [${progress.stopTimer('Recent activity')}]`);
1117
- }
1118
- profiler.endPhase('Write recent activity');
1119
-
1120
- // Phase: Write menu data
1121
- profiler.startPhase('Write menu data');
1122
- progress.startTimer('Menu data');
1123
- if (_jsonOnly) {
1124
- // menu-data.json and the custom-menu files are read by the page shell's
1125
- // script at runtime. No pages, no readers.
1126
- progress.done('Menu data', `skipped (JSON-only) [${progress.stopTimer('Menu data')}]`);
1127
- } else {
1128
- // Write menu data as a separate JSON file (not embedded in each page)
1129
- // This dramatically reduces HTML file sizes for large sites
1130
- const menuDataPath = join(output, 'public', 'menu-data.json');
1131
- const menuDataJson = JSON.stringify(menuData);
1132
- progress.log(`Writing menu data (${(menuDataJson.length / 1024).toFixed(1)} KB)`);
1133
- await outputFile(menuDataPath, menuDataJson);
1134
-
1135
- // Write custom menu JSON files
1136
- for (const [menuDir, menuInfo] of customMenus) {
1137
- const customMenuPath = join(output, menuInfo.menuJsonPath);
1138
- // Include menuPosition in the JSON so client knows how to render
1139
- const customMenuJson = JSON.stringify({
1140
- menuData: menuInfo.menuData,
1141
- menuPosition: menuInfo.menuPosition || 'top',
1142
- });
1143
- progress.log(`Writing custom menu: ${menuInfo.menuJsonPath}`);
1144
- await outputFile(customMenuPath, customMenuJson);
1145
- }
1146
- progress.done('Menu data', `${customMenus.size + 1} files [${progress.stopTimer('Menu data')}]`);
1147
- }
1148
- profiler.endPhase('Write menu data');
1149
-
1150
- // Phase: Process directory indices
1151
- profiler.startPhase('Process directories');
1152
- progress.startTimer('Directories');
1153
-
1154
- // Output paths that a source document already owns. The generated directory
1155
- // listing below writes to <dir>.html, which collides with two things: an
1156
- // article named after its own folder (settings/dying-light.md renders to
1157
- // settings/dying-light.html) and a hand-written .html copied from the source
1158
- // tree. Those documents win — the listing must never overwrite them.
1159
- const documentOwnedOutputs = new Set(
1160
- allSourceFilenamesThatAreArticles.map((filename) =>
1161
- filename.replace(source, output).replace(/\.(md|mdx|txt|yml)$/, ".html")
1162
- )
1163
- );
1164
- for (const relativeHtmlPath of existingHtmlFiles) {
1165
- documentOwnedOutputs.add(join(output, relativeHtmlPath));
1166
- }
1167
-
1168
- // Process directory indices with batched concurrency
1169
- const totalDirs = allSourceFilenamesThatAreDirectories.length;
1170
- let processedDirs = 0;
1171
- progress.log(`Processing ${totalDirs} directories...`);
1172
- await processBatched(allSourceFilenamesThatAreDirectories, async (dirPath) => {
1173
- try {
1174
- processedDirs++;
1175
- const shortDir = dirPath.replace(source, '');
1176
- progress.status('Directories', `${processedDirs}/${totalDirs} ${shortDir}`);
1177
-
1178
- const pathsInThisDirectory = allSourceFilenames.filter((filename) =>
1179
- filename.match(new RegExp(`${dirPath}.+`))
1180
- );
1181
-
1182
- // Use minimal directory index cache instead of full jsonCache
1183
- const jsonObjects = pathsInThisDirectory
1184
- .map((path) => {
1185
- const object = dirIndexCache.get(path);
1186
- return typeof object === "object" ? object : null;
1187
- })
1188
- .filter((a) => a);
1189
-
1190
- const json = JSON.stringify(jsonObjects);
1191
-
1192
- const outputFilename = dirPath.replace(source, output) + ".json";
1193
- await outputFile(outputFilename, json);
1194
-
1195
- // html
1196
- // Rewritten every build: the listing reflects the directory's contents,
1197
- // so skipping it whenever the file already exists (the old behaviour)
1198
- // froze it at whatever the tree looked like the first time it was
1199
- // written, and new or removed documents never showed up again.
1200
- //
1201
- // The <dir>.json above is NOT skipped in JSON-only mode: it is the
1202
- // directory's record list, which is the main thing a data consumer wants.
1203
- const htmlOutputFilename = dirPath.replace(source, output) + ".html";
1204
- if (!_jsonOnly && !documentOwnedOutputs.has(htmlOutputFilename)) {
1205
- const template = templates["default-template"];
1206
- const indexHtml = `<ul>${pathsInThisDirectory
1207
- .map((path) => {
1208
- const partialPath = path
1209
- .replace(source, "")
1210
- .replace(parse(path).ext, ".html");
1211
- const name = basename(path, parse(path).ext);
1212
- return `<li><a href="${partialPath}">${name}</a></li>`;
1213
- })
1214
- .join("")}</ul>`;
1215
- let finalHtml = template;
1216
- const replacements = {
1217
- "${menu}": menu,
1218
- "${body}": indexHtml,
1219
- "${searchIndex}": "[]", // Search index now in separate file
1220
- "${title}": "Index",
1221
- "${meta}": "{}",
1222
- "${transformedMetadata}": "",
1223
- "${styleLink}": "",
1224
- "${footer}": footer
1225
- };
1226
- for (const [key, value] of Object.entries(replacements)) {
1227
- finalHtml = finalHtml.replace(key, value);
1228
- }
1229
- // Add cache-busting timestamps to static file references
1230
- finalHtml = addTimestampToHtmlStaticRefs(finalHtml, cacheBustTimestamp);
1231
- await outputFile(htmlOutputFilename, finalHtml);
1232
- }
1233
- } catch (e) {
1234
- progress.log(`Error processing directory ${dirPath}: ${e.message}`);
1235
- errors.push({ file: dirPath, phase: 'directory-index', error: e });
1236
- }
1237
- });
1238
-
1239
- progress.done('Directories', `${totalDirs} done [${progress.stopTimer('Directories')}]`);
1240
- profiler.endPhase('Process directories');
1241
-
1242
- // Clear directory index cache to free memory before processing static files
1243
- dirIndexCache.clear();
1244
-
1245
- // Phase: Process static files
1246
- profiler.startPhase('Process static files');
1247
- progress.startTimer('Static files');
1248
- // Copy static HTML files (images were already processed above with preview generation)
1249
- // Note: Images are processed before articles to enable preview transformation in HTML
1250
-
1251
- // Also copy existing HTML files from source to output (they're treated as static)
1252
- const allSourceFilenamesThatAreHtml = allSourceFilenames.filter(
1253
- (filename) => filename.match(/\.html$/) && !isHiddenOrSystem(filename)
1254
- );
1255
-
1256
- // Fonts, audio, video, PDFs: copied through untouched. Images are handled
1257
- // separately above because they also get previews; everything else that is
1258
- // neither an article nor a stylesheet belongs here. Leaving this out is what
1259
- // let `ursa serve` and `ursa generate` disagree — serve reads these straight
1260
- // off disk, so the missing copy step only ever showed up in a built site.
1261
- const allSourceFilenamesThatAreMedia = allSourceFilenames.filter(
1262
- (filename) => isMedia(filename) && !isHiddenOrSystem(filename)
1263
- );
1264
-
1265
- // JSON-only emits data, not a servable site, so nothing is copied through.
1266
- const allStaticFiles = _jsonOnly
1267
- ? []
1268
- : [...allSourceFilenamesThatAreHtml, ...allSourceFilenamesThatAreMedia];
1269
- const totalStatic = allStaticFiles.length;
1270
- let processedStatic = 0;
1271
- let copiedStatic = 0;
1272
- progress.log(
1273
- `Processing ${totalStatic} static files ` +
1274
- `(${allSourceFilenamesThatAreHtml.length} HTML, ${allSourceFilenamesThatAreMedia.length} media)...`
1275
- );
1276
- await processBatched(allStaticFiles, async (file) => {
1277
- try {
1278
- processedStatic++;
1279
- const shortFile = file.replace(source, '');
1280
- progress.status('Static files', `${processedStatic}/${totalStatic} ${shortFile}`);
1281
-
1282
- // Check if file has changed using file stat as a quick check
1283
- const fileStat = await stat(file);
1284
- const statKey = `${file}:stat`;
1285
- const newStatHash = `${fileStat.size}:${fileStat.mtimeMs}`;
1286
- const outputFilename = file.replace(source, output);
1287
- // As with articles: an unchanged stat only means the source is untouched,
1288
- // so the output must exist before this copy can be skipped.
1289
- if (hashCache.get(statKey) === newStatHash && outputsExist([outputFilename])) {
1290
- return; // Skip unchanged static file
1291
- }
1292
- hashCache.set(statKey, newStatHash);
1293
- copiedStatic++;
1294
-
1295
- await mkdir(dirname(outputFilename), { recursive: true });
1296
-
1297
- if (file.endsWith('.css')) {
1298
- // Process CSS for cache busting
1299
- const cssContent = await readFile(file, 'utf8');
1300
- const processedCss = addTimestampToCssUrls(cssContent, cacheBustTimestamp);
1301
- await outputFile(outputFilename, processedCss);
1302
- } else if (file.endsWith('.html')) {
1303
- // Process HTML files for link resolution
1304
- let htmlContent = await readFile(file, 'utf8');
1305
- // Calculate the document's URL path for relative link resolution
1306
- const docUrlPath = '/' + file.replace(source, '').replace(/^\//, '');
1307
- // Resolve relative URLs in raw HTML elements (img src, etc.)
1308
- htmlContent = resolveRelativeUrls(htmlContent, docUrlPath);
1309
- // Resolve internal links to have proper .html extensions
1310
- htmlContent = markInactiveLinks(htmlContent, validPaths, docUrlPath, false);
1311
- // Transform image tags to use preview images with data-fullsrc for originals
1312
- // Skip in deferred mode - images will use original paths until preview generation completes
1313
- if (!_deferImages) {
1314
- htmlContent = transformImageTags(htmlContent, imageMap, docUrlPath);
1315
- }
1316
- // Add cache-busting timestamps
1317
- htmlContent = addTimestampToHtmlStaticRefs(htmlContent, cacheBustTimestamp);
1318
- await outputFile(outputFilename, htmlContent);
1319
- } else {
1320
- await copyFile(file, outputFilename);
1321
- }
1322
- } catch (e) {
1323
- progress.log(`Error processing static file ${file}: ${e.message}`);
1324
- errors.push({ file, phase: 'static-file', error: e });
1325
- }
46
+ const output = resolve(_output);
47
+ console.log({ source, meta, output, whitelist: _whitelist, exclude: _exclude, clean: _clean, jsonOnly: _jsonOnly });
48
+
49
+ profiler.startPhase("Prepare");
50
+ const build = await createBuild({
51
+ source,
52
+ meta,
53
+ output,
54
+ whitelist: _whitelist,
55
+ exclude: _exclude,
56
+ clean: _clean,
57
+ jsonOnly: _jsonOnly,
58
+ explain: _explain,
1326
59
  });
1327
-
1328
- progress.done('Static files', `${totalStatic} done (${copiedStatic} copied) [${progress.stopTimer('Static files')}]`);
1329
- profiler.endPhase('Process static files');
60
+ profiler.endPhase("Prepare");
1330
61
 
1331
- // Phase: Auto-index generation
1332
- profiler.startPhase('Auto-index generation');
1333
- progress.startTimer('Auto-index');
1334
- // Automatic index generation for folders without index.html
1335
- if (_jsonOnly) {
1336
- // Auto-indices only ever emit index.html for a folder that has no index
1337
- // document of its own.
1338
- progress.done('Auto-index', `skipped (JSON-only) [${progress.stopTimer('Auto-index')}]`);
1339
- } else {
1340
- progress.log(`Checking for missing index files...`);
1341
- await generateAutoIndices(output, allSourceFilenamesThatAreDirectories, source, templates, menu, footer, allSourceFilenamesThatAreArticles, copiedCssFiles, existingHtmlFiles, cacheBustTimestamp, progress, customMenus);
1342
- progress.done('Auto-index', `checked ${allSourceFilenamesThatAreDirectories.length} directories [${progress.stopTimer('Auto-index')}]`);
1343
- }
1344
- profiler.endPhase('Auto-index generation');
1345
-
1346
- // Phase: Finalization
1347
- profiler.startPhase('Finalization');
1348
- progress.startTimer('Finalization');
1349
- // Save the hash cache to .ursa folder in source directory
1350
- if (hashCache.size > 0) {
1351
- await saveHashCache(source, hashCache);
1352
- }
1353
-
1354
- // Persist the dependency tracker so hash-skipped documents keep their
1355
- // edges on the next warm start (invalidation plans stay accurate).
1356
- //
1357
- // Not in JSON-only mode: it registers nothing (registration lives in the page
1358
- // assembly it skips), so saving would overwrite a full build's graph with an
1359
- // empty one. The hash cache is safe to share — see `expectedOutputs` above —
1360
- // but the dependency graph is not, because nothing rebuilds it.
1361
- if (!_jsonOnly) {
1362
- await saveDependencyTracker(source);
1363
- }
1364
-
1365
- // Populate watch mode cache for fast single-file regeneration.
1366
- // A JSON-only build never bundled the template assets and never processed
1367
- // images, so seeding the cache from it would make a later single-file
1368
- // regeneration emit a page with no styles.
1369
- if (!_jsonOnly) {
1370
- watchModeCache.templates = templates;
1371
- watchModeCache.menu = menu;
1372
- watchModeCache.footer = footer;
1373
- watchModeCache.validPaths = validPaths;
1374
- watchModeCache.source = source;
1375
- watchModeCache.meta = meta;
1376
- watchModeCache.output = output;
1377
- watchModeCache.hashCache = hashCache;
1378
- watchModeCache.cacheBustTimestamp = cacheBustTimestamp;
1379
- watchModeCache.cacheBustHashes = cacheBustHashes;
1380
- watchModeCache.allArticlePaths = [...allSourceFilenamesThatAreArticles];
1381
- watchModeCache.imageMap = imageMap;
1382
- watchModeCache.customMenus = customMenus;
1383
- watchModeCache.ursaMetadata = ursaMetadata;
1384
- watchModeCache.lastFullBuild = Date.now();
1385
- watchModeCache.isInitialized = true;
1386
- const depStats = dependencyTracker.getStats();
1387
- progress.log(`Watch cache initialized (${depStats.totalDocuments} documents, ${depStats.uniqueFiles} dependencies tracked)`);
62
+ profiler.startPhase("Pass");
63
+ let summary;
64
+ try {
65
+ summary = await build.runPass();
66
+ } finally {
67
+ await build.close();
1388
68
  }
69
+ profiler.endPhase("Pass");
1389
70
 
1390
- // Write error report if there were any errors
1391
- if (errors.length > 0) {
1392
- const errorReportPath = join(output, '_errors.log');
1393
- const failedFiles = errors.map(e => e.file);
1394
-
71
+ // Error report
72
+ if (summary.failures.size > 0) {
73
+ const errorReportPath = join(output, "_errors.log");
1395
74
  let report = `URSA GENERATION ERROR REPORT\n`;
1396
75
  report += `Generated: ${new Date().toISOString()}\n`;
1397
- report += `Total errors: ${errors.length}\n\n`;
1398
- report += `${'='.repeat(60)}\n`;
1399
- report += `FAILED FILES:\n`;
1400
- report += `${'='.repeat(60)}\n\n`;
1401
- failedFiles.forEach(f => {
1402
- report += ` - ${f}\n`;
1403
- });
1404
- report += `\n${'='.repeat(60)}\n`;
1405
- report += `ERROR DETAILS:\n`;
1406
- report += `${'='.repeat(60)}\n\n`;
1407
-
1408
- errors.forEach(({ file, phase, error }) => {
1409
- report += `${'─'.repeat(60)}\n`;
1410
- report += `File: ${file}\n`;
1411
- report += `Phase: ${phase}\n`;
1412
- report += `Error: ${error.message}\n`;
1413
- if (error.stack) {
1414
- report += `Stack:\n${error.stack}\n`;
1415
- }
76
+ report += `Total errors: ${summary.failures.size}\n\n`;
77
+ report += `${"=".repeat(60)}\nFAILED NODES:\n${"=".repeat(60)}\n\n`;
78
+ for (const id of summary.failures.keys()) report += ` - ${id}\n`;
79
+ report += `\n${"=".repeat(60)}\nERROR DETAILS:\n${"=".repeat(60)}\n\n`;
80
+ for (const [id, error] of summary.failures) {
81
+ const cause = error.cause ?? error;
82
+ report += `${"─".repeat(60)}\nNode: ${id}\nError: ${cause.message}\n`;
83
+ if (cause.stack) report += `Stack:\n${cause.stack}\n`;
1416
84
  report += `\n`;
1417
- });
1418
-
85
+ }
1419
86
  await outputFile(errorReportPath, report);
1420
- progress.log(`\n⚠️ ${errors.length} error(s) occurred during generation.`);
1421
- progress.log(` Error report written to: ${errorReportPath}\n`);
87
+ console.log(`\n⚠️ ${summary.failures.size} error(s) occurred during generation.`);
88
+ console.log(` Error report written to: ${errorReportPath}\n`);
1422
89
  } else {
1423
- progress.log(`\n✅ Generation complete with no errors.\n`);
90
+ console.log(`\n✅ Generation complete with no errors.\n`);
1424
91
  }
1425
-
1426
- progress.done('Finalization', `complete [${progress.stopTimer('Finalization')}]`);
1427
- profiler.endPhase('Finalization');
1428
-
1429
- // Print profiler report
1430
- progress.log(profiler.report());
1431
-
1432
- // Terminate worker pool so threads don't keep the process alive
1433
- await terminateParserPool();
1434
92
 
1435
- // Return deferred processing promises if in deferred mode
1436
- // Caller can await these to know when background processing is complete
93
+ console.log(profiler.report());
94
+
1437
95
  return {
1438
- deferredImageProcessing: deferredImageProcessingPromise,
1439
- deferredSearchIndex: deferredSearchIndexPromise
96
+ summary,
97
+ // Legacy shape: nothing is deferred any more
98
+ deferredImageProcessing: null,
99
+ deferredSearchIndex: null,
1440
100
  };
1441
101
  }
1442
-
1443
- /**
1444
- * Regenerate multiple documents affected by a dependency change (e.g., style.css, script.js, template).
1445
- * Uses the watchModeCache and dependency tracker to efficiently re-render affected documents
1446
- * with updated cache-bust timestamps.
1447
- *
1448
- * @param {string[]} documentPaths - Absolute paths to documents to regenerate
1449
- * @param {Object} options
1450
- * @param {string} options._source - Source directory
1451
- * @param {string} options._meta - Meta directory
1452
- * @param {string} options._output - Output directory
1453
- * @param {string} [options.reason] - Reason for regeneration (for logging)
1454
- * @param {string[]} [options.priorityPaths] - Document paths to regenerate first (e.g. client-viewed docs)
1455
- * @param {function} [options.onPriorityComplete] - Callback after priority paths are done (receives { regenerated, failed })
1456
- * @returns {Promise<{success: boolean, message: string, regenerated: number, failed: number}>}
1457
- */
1458
- export async function regenerateAffectedDocuments(documentPaths, {
1459
- _source,
1460
- _meta,
1461
- _output,
1462
- reason = "dependency change",
1463
- priorityPaths = [],
1464
- onPriorityComplete = null,
1465
- } = {}) {
1466
- const startTime = Date.now();
1467
-
1468
- if (!watchModeCache.isInitialized) {
1469
- return { success: false, message: "Cache not initialized - need full build first", regenerated: 0, failed: 0 };
1470
- }
1471
-
1472
- if (documentPaths.length === 0) {
1473
- return { success: true, message: "No documents to regenerate", regenerated: 0, failed: 0 };
1474
- }
1475
-
1476
- // Generate a fresh cache-bust timestamp for this invalidation pass
1477
- const newTimestamp = generateCacheBustTimestamp();
1478
- watchModeCache.cacheBustTimestamp = newTimestamp;
1479
-
1480
- let regenerated = 0;
1481
- let failed = 0;
1482
-
1483
- // Separate priority paths from the rest
1484
- const prioritySet = new Set(priorityPaths.map(p => resolve(p)));
1485
- const priorityDocs = documentPaths.filter(p => prioritySet.has(resolve(p)));
1486
- const remainingDocs = documentPaths.filter(p => !prioritySet.has(resolve(p)));
1487
-
1488
- if (priorityDocs.length > 0) {
1489
- console.log(`🔄 Regenerating ${priorityDocs.length} priority documents first, then ${remainingDocs.length} remaining (${reason})`);
1490
- } else {
1491
- console.log(`🔄 Regenerating ${documentPaths.length} documents (${reason})`);
1492
- }
1493
-
1494
- // Process priority documents first
1495
- for (const docPath of priorityDocs) {
1496
- try {
1497
- const result = await regenerateSingleFile(docPath, { _source, _meta, _output });
1498
- if (result.success) {
1499
- regenerated++;
1500
- } else {
1501
- console.warn(` ⚠️ ${docPath}: ${result.message}`);
1502
- failed++;
1503
- }
1504
- } catch (e) {
1505
- console.error(` ❌ ${docPath}: ${e.message}`);
1506
- failed++;
1507
- }
1508
- }
1509
-
1510
- // Notify caller that priority docs are done (so server can reload those clients immediately)
1511
- if (priorityDocs.length > 0 && onPriorityComplete) {
1512
- try {
1513
- onPriorityComplete({ regenerated, failed, priorityDocs });
1514
- } catch (e) {
1515
- console.error(` ⚠️ onPriorityComplete callback error: ${e.message}`);
1516
- }
1517
- }
1518
-
1519
- // Process remaining documents
1520
- for (const docPath of remainingDocs) {
1521
- try {
1522
- const result = await regenerateSingleFile(docPath, { _source, _meta, _output });
1523
- if (result.success) {
1524
- regenerated++;
1525
- } else {
1526
- console.warn(` ⚠️ ${docPath}: ${result.message}`);
1527
- failed++;
1528
- }
1529
- } catch (e) {
1530
- console.error(` ❌ ${docPath}: ${e.message}`);
1531
- failed++;
1532
- }
1533
- }
1534
-
1535
- // Persist updated dependency registrations (e.g. a doc switched templates)
1536
- if (regenerated > 0) {
1537
- await saveDependencyTracker(resolve(_source) + "/");
1538
- }
1539
-
1540
- const elapsed = Date.now() - startTime;
1541
- const msg = `Regenerated ${regenerated}/${documentPaths.length} documents in ${elapsed}ms (${reason})${failed > 0 ? `, ${failed} failed` : ""}`;
1542
- console.log(`✅ ${msg}`);
1543
- return { success: failed === 0, message: msg, regenerated, failed };
1544
- }
1545
-
1546
- /**
1547
- * Regenerate a single file without scanning the entire source directory.
1548
- * This is much faster for watch mode - only regenerate what changed.
1549
- *
1550
- * @param {string} changedFile - Absolute path to the file that changed
1551
- * @param {Object} options - Same options as generate()
1552
- * @returns {Promise<{success: boolean, message: string}>}
1553
- */
1554
- export async function regenerateSingleFile(changedFile, {
1555
- _source,
1556
- _meta,
1557
- _output,
1558
- } = {}) {
1559
- const startTime = Date.now();
1560
- const source = resolve(_source) + "/";
1561
- const meta = resolve(_meta);
1562
- const output = resolve(_output) + "/";
1563
-
1564
- // Check if this is an article file we can regenerate
1565
- const articleExtensions = /\.(md|mdx|txt|yml)$/;
1566
- if (!changedFile.match(articleExtensions)) {
1567
- return { success: false, message: `Not an article file: ${changedFile}` };
1568
- }
1569
-
1570
- // Check if cache is initialized
1571
- if (!watchModeCache.isInitialized) {
1572
- return { success: false, message: 'Cache not initialized - need full build first' };
1573
- }
1574
-
1575
- // Verify paths match cached paths
1576
- if (watchModeCache.source !== source || watchModeCache.output !== output) {
1577
- return { success: false, message: 'Paths changed - need full rebuild' };
1578
- }
1579
-
1580
- try {
1581
- const { templates, menu, footer, validPaths, hashCache, cacheBustTimestamp, imageMap, customMenus, ursaMetadata } = watchModeCache;
1582
-
1583
- const rawBody = await readFile(changedFile, "utf8");
1584
- const type = parse(changedFile).ext;
1585
- const ext = extname(changedFile);
1586
- const base = basename(changedFile, ext);
1587
- const dir = addTrailingSlash(dirname(changedFile)).replace(source, "");
1588
-
1589
- // Calculate output paths
1590
- const outputFilename = changedFile
1591
- .replace(source, output)
1592
- .replace(parse(changedFile).ext, ".html");
1593
- const url = '/' + outputFilename.replace(output, '');
1594
-
1595
- // Title from filename (for index/home, use parent folder name)
1596
- const titleBase = (base === 'index' || base === 'home') ? basename(dirname(changedFile)) : base;
1597
- const title = toTitleCase(titleBase || base);
1598
-
1599
- // Extract metadata
1600
- const fileMeta = extractMetadata(rawBody);
1601
- const transformedMetadata = await getTransformedMetadata(
1602
- dirname(changedFile),
1603
- fileMeta
1604
- );
1605
-
1606
- // Calculate the document's URL path
1607
- const docUrlPath = '/' + dir + base + '.html';
1608
-
1609
- // Check if hydration should be enabled for MDX files
1610
- const shouldHydrate = type === '.mdx' && fileMeta?.hydrate === true;
1611
-
1612
- // Render body (use async for .mdx, sync for .md/.txt)
1613
- let body;
1614
- let hydrationScript = '';
1615
- if (type === '.mdx') {
1616
- const renderResult = await renderFileAsync({
1617
- fileContents: rawBody,
1618
- type,
1619
- dirname: dir,
1620
- basename: base,
1621
- filePath: changedFile,
1622
- sourceRoot: source,
1623
- useWorker: false,
1624
- hydrate: shouldHydrate,
1625
- });
1626
-
1627
- // Handle the result - can be string or { html, hydrationScript }
1628
- if (typeof renderResult === 'object' && renderResult.html) {
1629
- body = renderResult.html;
1630
- hydrationScript = renderResult.hydrationScript || '';
1631
- } else {
1632
- body = renderResult;
1633
- }
1634
- } else {
1635
- body = renderFile({
1636
- fileContents: rawBody,
1637
- type,
1638
- dirname: dir,
1639
- basename: base,
1640
- });
1641
- }
1642
-
1643
- // Inject default H1 if body doesn't start with one
1644
- if (!body || !body.trimStart().startsWith('<h1')) {
1645
- const h1Title = fileMeta?.title || title;
1646
- body = `<h1>${h1Title}</h1>\n` + (body || '');
1647
- }
1648
-
1649
- // Inject breadcrumbs before the H1
1650
- const breadcrumbs = generateBreadcrumbs(dir, base, fileMeta, source);
1651
- if (breadcrumbs) {
1652
- body = breadcrumbs + body;
1653
- }
1654
-
1655
- // Inject frontmatter table for markdown/mdx files
1656
- if ((type === '.md' || type === '.mdx') && fileMeta) {
1657
- body = injectFrontmatterTable(body, fileMeta);
1658
- }
1659
-
1660
- // Handle auto-index generation for index files with generate-auto-index: true
1661
- if (base === 'index' && fileMeta) {
1662
- const autoIndexConfig = getAutoIndexConfig(fileMeta);
1663
- if (autoIndexConfig.enabled) {
1664
- // Generate auto-index HTML for this directory from source
1665
- const sourceDir = dirname(changedFile);
1666
- const autoIndexHtml = await generateAutoIndexHtmlFromSource(sourceDir, autoIndexConfig.depth);
1667
-
1668
- if (autoIndexHtml) {
1669
- if (autoIndexConfig.position === 'bottom') {
1670
- body = body + '\n' + autoIndexHtml;
1671
- } else {
1672
- body = autoIndexHtml + '\n' + body;
1673
- }
1674
- }
1675
- }
1676
- }
1677
-
1678
- // Find all CSS files up the tree and create separate link tags
1679
- // (regenerateSingleFile is used in serve mode, so separate tags per level for invalidation)
1680
- let styleLink = "";
1681
- let cssPaths = [];
1682
- try {
1683
- const dirKey = (dir === "/" || dir === "") ? _source : resolve(_source, dir);
1684
- cssPaths = await findAllStyleCss(dirKey, _source);
1685
- if (cssPaths.length > 0) {
1686
- // Copy all CSS files to output (always copy in single-file mode to ensure up to date)
1687
- for (const cssPath of cssPaths) {
1688
- const cssOutputPath = cssPath.replace(source, output);
1689
- const cssContent = await readFile(cssPath, 'utf8');
1690
- await outputFile(cssOutputPath, cssContent);
1691
- }
1692
- styleLink = generateSeparateCssTags(cssPaths, source);
1693
- }
1694
- } catch (e) {
1695
- // ignore
1696
- }
1697
-
1698
- // Get template
1699
- const requestedTemplateName = fileMeta && fileMeta.template;
1700
- const template =
1701
- templates[requestedTemplateName] || templates[DEFAULT_TEMPLATE_NAME];
1702
-
1703
- if (!template) {
1704
- return { success: false, message: `Template not found: ${requestedTemplateName || DEFAULT_TEMPLATE_NAME}` };
1705
- }
1706
-
1707
- // Find all script.js files from docroot to current dir and serve as separate external tags
1708
- // (Serve mode: separate tags per level for individual invalidation)
1709
- let customScript = "";
1710
- let scriptPaths = [];
1711
- try {
1712
- const dirKey = (dir === "/" || dir === "") ? _source : resolve(_source, dir);
1713
- scriptPaths = await findAllScriptJs(dirKey, _source);
1714
- if (scriptPaths.length > 0) {
1715
- // Copy all script files to output so they can be served
1716
- for (const scriptPath of scriptPaths) {
1717
- const scriptOutputPath = scriptPath.replace(source, output);
1718
- const scriptContent = await readFile(scriptPath, 'utf8');
1719
- await outputFile(scriptOutputPath, scriptContent);
1720
- }
1721
- customScript = generateSeparateJsTags(scriptPaths, source);
1722
- }
1723
- } catch (e) {
1724
- // ignore
1725
- }
1726
-
1727
- // Register this document's dependencies (template, inherited CSS/JS) so
1728
- // invalidation plans stay accurate after frontmatter/template changes.
1729
- // Persisted to .ursa/dependency-graph.json by regenerateAffectedDocuments.
1730
- const usedTemplateName = (requestedTemplateName && templates[requestedTemplateName])
1731
- ? requestedTemplateName
1732
- : DEFAULT_TEMPLATE_NAME;
1733
- dependencyTracker.registerDocument(changedFile, {
1734
- templateName: usedTemplateName,
1735
- cssPaths,
1736
- scriptPaths,
1737
- });
1738
-
1739
- // Check if this file has a custom menu
1740
- const customMenuInfo = customMenus ? getCustomMenuForFile(changedFile, source, customMenus) : null;
1741
-
1742
- // Append hydration script to customScript if present (for MDX with hydrate: true)
1743
- const finalCustomScript = hydrationScript
1744
- ? customScript + '\n' + hydrationScript
1745
- : customScript;
1746
-
1747
- // Build final HTML
1748
- let finalHtml = template;
1749
- const replacements = {
1750
- "${title}": fileMeta?.title || title,
1751
- "${menu}": menu,
1752
- "${meta}": JSON.stringify(fileMeta),
1753
- "${transformedMetadata}": transformedMetadata,
1754
- "${body}": body,
1755
- "${styleLink}": styleLink,
1756
- "${customScript}": finalCustomScript,
1757
- "${searchIndex}": "[]",
1758
- "${footer}": footer
1759
- };
1760
- for (const [key, value] of Object.entries(replacements)) {
1761
- finalHtml = finalHtml.replace(key, value);
1762
- }
1763
-
1764
- // If this page has a custom menu, add data attributes to body
1765
- if (customMenuInfo) {
1766
- const menuPosition = customMenuInfo.menuPosition || 'top';
1767
- finalHtml = finalHtml.replace(
1768
- /<body([^>]*)>/,
1769
- `<body$1 data-custom-menu="${customMenuInfo.menuJsonPath}" data-menu-position="${menuPosition}">`
1770
- );
1771
- } else {
1772
- // No custom menu — default to top menu
1773
- finalHtml = finalHtml.replace(
1774
- /<body([^>]*)>/,
1775
- `<body$1 data-menu-position="top">`
1776
- );
1777
- }
1778
-
1779
- // Resolve relative URLs in raw HTML elements (img src, etc.)
1780
- finalHtml = resolveRelativeUrls(finalHtml, docUrlPath);
1781
-
1782
- // Mark broken links
1783
- finalHtml = markInactiveLinks(finalHtml, validPaths, docUrlPath, false);
1784
-
1785
- // Transform image tags to use preview images with data-fullsrc for originals
1786
- if (imageMap) {
1787
- finalHtml = transformImageTags(finalHtml, imageMap, docUrlPath);
1788
- }
1789
-
1790
- // Add cache-busting timestamps to static file references
1791
- finalHtml = addTimestampToHtmlStaticRefs(finalHtml, cacheBustTimestamp);
1792
-
1793
- await outputFile(outputFilename, finalHtml);
1794
-
1795
- // JSON output
1796
- const jsonOutputFilename = outputFilename.replace(".html", ".json");
1797
- const sections = (type === '.md' || type === '.mdx') ? extractSections(rawBody) : [];
1798
- const jsonObject = {
1799
- name: base,
1800
- url,
1801
- contents: rawBody,
1802
- bodyHtml: body,
1803
- metadata: fileMeta,
1804
- sections,
1805
- transformedMetadata,
1806
- _ursa_metadata: ursaMetadata,
1807
- };
1808
- const json = JSON.stringify(jsonObject);
1809
- await outputFile(jsonOutputFilename, json);
1810
-
1811
- // XML output
1812
- const xmlOutputFilename = outputFilename.replace(".html", ".xml");
1813
- const xml = `<article>${o2x(jsonObject)}</article>`;
1814
- await outputFile(xmlOutputFilename, xml);
1815
-
1816
- // Folder-named index promotion (mirrors autoIndex behavior on full builds):
1817
- // If the file is named like its parent folder (e.g. aletheia/aletheia.md) and
1818
- // no explicit index.{md,mdx,txt,yml,html} exists alongside it, also write the
1819
- // same outputs to <dir>/index.html|json|xml so the canonical URL stays fresh.
1820
- const sourceDirOfFile = dirname(changedFile);
1821
- const parentFolderName = basename(sourceDirOfFile);
1822
- if (base && parentFolderName && base === parentFolderName) {
1823
- const hasExplicitIndex = ['index.md', 'index.mdx', 'index.txt', 'index.yml', 'index.html']
1824
- .some(name => existsSync(join(sourceDirOfFile, name)));
1825
- if (!hasExplicitIndex) {
1826
- const outDirOfFile = dirname(outputFilename);
1827
- await outputFile(join(outDirOfFile, 'index.html'), finalHtml);
1828
- await outputFile(join(outDirOfFile, 'index.json'), json);
1829
- await outputFile(join(outDirOfFile, 'index.xml'), xml);
1830
- }
1831
- }
1832
-
1833
- // Update hash cache
1834
- updateHash(changedFile, rawBody, hashCache);
1835
-
1836
- // Update recent-activity.json with this file's last-edited time
1837
- try {
1838
- const sourceTimestamps = await buildSourceTimestampIndex(source);
1839
- const now = await sourceTimestamps.get(changedFile);
1840
- const recentActivityPath = join(output, 'public', 'recent-activity.json');
1841
- let recentActivity = [];
1842
- try {
1843
- const existing = await readFile(recentActivityPath, 'utf8');
1844
- recentActivity = JSON.parse(existing);
1845
- } catch (e) { /* no existing file, start fresh */ }
1846
- // Remove old entry for this URL if present
1847
- recentActivity = recentActivity.filter(r => r.url !== url);
1848
- recentActivity.push({ title, url, mtime: now });
1849
- // Sort by mtime descending, keep top 10
1850
- recentActivity.sort((a, b) => b.mtime - a.mtime);
1851
- recentActivity = recentActivity.slice(0, 10);
1852
- await outputFile(recentActivityPath, JSON.stringify(recentActivity));
1853
- } catch (e) {
1854
- // ignore recent activity update errors
1855
- }
1856
-
1857
- const elapsed = Date.now() - startTime;
1858
- const shortFile = changedFile.replace(source, '');
1859
- return { success: true, message: `Regenerated ${shortFile} in ${elapsed}ms` };
1860
- } catch (e) {
1861
- return { success: false, message: `Error: ${e.message}` };
1862
- }
1863
- }