-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtbdocs.mjs
More file actions
1636 lines (1525 loc) · 70.9 KB
/
Copy pathtbdocs.mjs
File metadata and controls
1636 lines (1525 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// tbdocs orchestrator. Phases 1-4 pipeline + Phase 5-7 SAB scheduler.
//
// Usage: node builder/tbdocs.mjs [--src <path>] [--dest <path>]
// [--baseurl <prefix>] [--url <origin>] [--dry-run]
// [--no-offline] [--no-pdf] [--tolerate-missing-images]
// [--fetch-assets | --no-fetch-assets] [--profile-offline]
// [--check | --no-check] [--check-audit-index]
// [--check-findings <path>] [--serve] [--port <N>]
// [--update-page-baseline] [--update-symbol-baseline]
// [--symbol-gaps <path>]
//
// --check runs the link + integrity check over the HTML the build
// already holds in worker memory, instead of writing ~270 MB out and
// reading it back through scripts/check_links.mjs. Findings are
// identical -- scripts/check_links_diff.mjs is the gate that says so.
// A failing check sets the exit code but never aborts the build: a
// broken link still produces a site worth having on disk.
// --check-audit-index additionally diffs the derived tree index against
// what actually landed on disk; see builder/check.mjs.
//
// Default --src is "docs" relative to the current working directory.
// Default --dest is "<src>/_site". --dry-run skips all filesystem writes.
// --baseurl overrides _config.yml's baseurl (used by CI to inject the
// Pages base path).
// --url overrides _config.yml's url (used by CI to inject the Pages
// origin -- e.g. https://kubao.github.io -- so canonical URLs match
// the actual deployment instead of the configured production host).
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import yaml from "js-yaml";
import pc from "picocolors";
import { WorkerPool } from "./worker-pool.mjs";
import { Scheduler } from "./scheduler.mjs";
import { renderGantt } from "./gantt.mjs";
import { discover } from "./discover.mjs";
import { deriveCounts, validateCountNames } from "./counts.mjs";
import { computeNav } from "./nav.mjs";
import { vendorAssets } from "./vendor-assets.mjs";
import { computeSiteSeo } from "./seo.mjs";
import { resolveBookChapters } from "./book.mjs";
import { loadData } from "./data.mjs";
import {
createMarkdownIt,
buildLinkTables, serializeLinkTables,
} from "./render.mjs";
import { loadHighlightTheme } from "./highlight-theme.mjs";
import { buildInitConfig, renderSidebar } from "./template.mjs";
import { writePhase, prepareDestinations, preparePageDirs, writeFileMkdirp } from "./write.mjs";
import { writeRedirects, deriveRedirectStubs } from "./redirects.mjs";
import { writeSitemap, deriveSitemapUrls } from "./sitemap.mjs";
import { writeSearchDataFromChunks } from "./search.mjs";
import { writeOffline, enumerateVendoredThemeAssets } from "./offline.mjs";
import { buildSitePathsSync, deriveOfflineCss,
normalizeBaseurl } from "./offline-rewrite.mjs";
import { writePdf } from "./pdf.mjs";
// Only the index derivation is a static import: it runs inside dispatch,
// on the render fan-out's critical path, and check-tree.mjs pulls
// nothing heavier than node:path. The rest of the check -- and with it
// htmlparser2 -- is imported dynamically by the tasks that need it, so a
// build without --check pays nothing.
import { deriveTreeRels } from "./check-tree.mjs";
import { checkPageBaseline } from "./page-baseline.mjs";
import { checkSymbolBaseline } from "./symbol-baseline.mjs";
import { deriveSymbolIndex, reportableGaps, serializeSymbolIndex,
symbolPages, SYMBOL_INDEX_REL } from "./symbols.mjs";
import { publishPolicyFor, unpublishableSourceFiles,
unpublishableTreePaths, formatPublishRefusal } from "./publish-policy.mjs";
import { packShared } from "./sab-broadcast.mjs";
import {
allocSchedulerSAB, verifySchedulerSAB, SLICES_PER_WORKER,
HANDLERS, F_PIN_TO_PRED,
writeTaskMeta,
allocDynamicSlots, wireDynamicEdges, appendDynamicSuccessors,
setDepCount, activateDynamicTasks, packPayloads,
} from "./sab-scheduler.mjs";
const CPU_WORKER_URL = new URL("./cpu-worker.mjs", import.meta.url);
const PACKAGE_API_PATH = new URL("./package-api.json", import.meta.url);
// builder/ sits one level under the repository root. Used to state a build's
// source root the same way however it was invoked, for the page-count drift
// guard -- see page-baseline.mjs.
const REPO_ROOT = path.resolve(fileURLToPath(new URL("..", import.meta.url)));
function parseArgs(argv) {
const args = {
src: "docs",
dest: null,
baseurl: null,
url: null,
dryRun: false,
skipOffline: null,
skipPdf: null,
tolerateMissingImages: false,
profileOffline: false,
check: false,
auditIndex: false,
updatePageBaseline: false,
updateSymbolBaseline: false,
symbolGaps: null,
checkFindings: null,
serve: false,
port: 4000,
// Wall-clock with no task completing before the build gives up and
// reports what was outstanding. Generous on purpose: the longest
// single task here is worker cold boot at ~1.6 s, and a loaded CI
// box is allowed to be an order of magnitude slower than that
// without being called stalled. 0 disables the watchdog.
stallTimeoutMs: 120000,
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--src") {
args.src = argv[++i];
} else if (a.startsWith("--src=")) {
args.src = a.slice("--src=".length);
} else if (a === "--dest") {
args.dest = argv[++i];
} else if (a.startsWith("--dest=")) {
args.dest = a.slice("--dest=".length);
} else if (a === "--baseurl") {
args.baseurl = argv[++i];
} else if (a.startsWith("--baseurl=")) {
args.baseurl = a.slice("--baseurl=".length);
} else if (a === "--url") {
args.url = argv[++i];
} else if (a.startsWith("--url=")) {
args.url = a.slice("--url=".length);
} else if (a === "--dry-run") {
args.dryRun = true;
} else if (a === "--no-offline") {
args.skipOffline = true;
} else if (a === "--no-pdf") {
args.skipPdf = true;
} else if (a === "--tolerate-missing-images") {
args.tolerateMissingImages = true;
} else if (a === "--fetch-assets") {
args.fetchAssets = true;
} else if (a === "--no-fetch-assets") {
args.fetchAssets = false;
} else if (a === "--profile-offline") {
args.profileOffline = true;
} else if (a === "--check") {
args.check = true;
} else if (a === "--no-check") {
// build.bat bakes in --check; this is how to ask for a plain
// build without editing it. Flags are read in order, so a later
// --no-check wins.
args.check = false;
args.auditIndex = false;
args.checkFindings = null;
} else if (a === "--check-audit-index") {
args.check = true;
args.auditIndex = true;
} else if (a === "--check-findings") {
args.check = true;
args.checkFindings = argv[++i];
} else if (a === "--update-page-baseline") {
// Record the current inventory as the drift guard's new baseline,
// whichever direction it moved. The build only ever raises it on its
// own; lowering it is a deliberate act, so it takes a deliberate flag.
args.updatePageBaseline = true;
} else if (a === "--update-symbol-baseline") {
// The same for the URLs tB/symbols.json has published: record the
// current list whatever left it. See symbol-baseline.mjs.
args.updateSymbolBaseline = true;
} else if (a === "--symbol-gaps") {
// Write the public symbols no page documents, as JSON, to a file.
args.symbolGaps = argv[++i];
} else if (a === "--serve") {
args.serve = true;
} else if (a === "--port") {
args.port = Number(argv[++i]);
} else if (a.startsWith("--port=")) {
args.port = Number(a.slice("--port=".length));
} else if (a === "--stall-timeout" || a.startsWith("--stall-timeout=")) {
const raw = a === "--stall-timeout" ? argv[++i] : a.slice("--stall-timeout=".length);
const secs = Number(raw);
if (!Number.isFinite(secs) || secs < 0) {
throw new Error(`--stall-timeout expects seconds (0 disables), got: ${raw}`);
}
args.stallTimeoutMs = secs * 1000;
} else {
throw new Error(`Unknown argument: ${a}`);
}
}
return args;
}
export function makeTimer() {
const laps = [];
let last = Date.now();
return {
lap(label) {
const now = Date.now();
laps.push({ label, ms: now - last });
last = now;
},
summary() {
return laps.map(l => `${l.label}=${l.ms}ms`).join(" ");
},
};
}
// ── Task graph ────────────────────────────────────────────────────────────────
//
// Seeds (config, buildInfo, dot, scssLight + scssDark → scss,
// highlighterInit), the main-thread spine (config → discover → nav (sidebar) + buildInit (chrome);
// nav + buildInit → dispatch; config → loadData; discover → markdownInit;
// deriveRedirects off discover; deriveSitemap + resolveBookChapters + prepDest deferred to dispatch),
// the render fan-out (dispatch → render:0..N, each worker stashes html locally),
// the per-worker flush (prepPageDirs → flush [per worker] → flushJoin [counter barrier]),
// and write/post-write tasks
// (flushJoin + prepPageDirs → writeAssets + searchData;
// writeAssets + searchData → writeAux → writeOffline; flushJoin + dot → writePdf)
// are scheduler tasks.
// runBuild() constructs the pool + scheduler, awaits start(), logs the
// summary, and returns.
const workerCount = os.availableParallelism();
// Register a dynamic fan-in barrier: BOTH halves of its invariant, in
// one call, because writing one without the other is a data-loss bug
// that reproduces about one build in three and reports nothing.
//
// Half one is the SAB dep count, which is what orders the work. Half two
// is the `expected` list, which is what orders the STATE. A barrier
// becomes READY when the *workers* decrement its dep count, and they do
// that right after posting their result -- so the main thread can see a
// count of zero while a result message is still in its queue and the
// matching submit() has not run. The only thing holding the barrier back
// in that window is _claimMainTask's check that every name in `expected`
// is already in the results map.
//
// renderJoin went without it and silently lost data: render:i's submit()
// is what fills scheduler.state.searchChunks[i], the array starts life
// as `new Array(N)` (holes, not undefined), and Array.prototype.flat()
// skips holes without a word. One chunk arriving late meant ~6 pages
// quietly missing from search-data.json.
//
// The Map entry is replaced with a shallow clone bearing a fresh
// `expected` array, so the shared TASKS def stays untouched across
// rebuilds -- mutating it in place would leave the next build's
// allocSchedulerSAB looking at leftover "render:N" / "flush:N" names.
function registerBarrier(scheduler, views, join, joinIdx, prefix, n) {
const def = scheduler.tasks.get(join);
if (!def) throw new Error(`registerBarrier: no task def for '${join}'`);
const expected = [];
for (let i = 0; i < n; i++) expected.push(`${prefix}:${i}`);
scheduler.tasks.set(join, { ...def, expected });
setDepCount(views, joinIdx, n);
}
const TASKS = {
// ── Seeds ─────────────────────────────────────────────────────────────────
// Reads and merges _config.yml + CLI overrides. Seed on main because the
// output object flows directly into discover (identity matters, no worker
// boundary crossing needed, and it's a trivial I/O read).
config: {
expected: [],
runOnMain: true,
async execute(_, ctx) {
const text = await fs.readFile(path.join(ctx.srcRoot, "_config.yml"), "utf8");
const config = yaml.load(text);
if (ctx.opts.baseurl != null) config.baseurl = ctx.opts.baseurl;
if (ctx.opts.url != null) config.url = ctx.opts.url;
return { config };
},
submit() {},
},
// Git rev-parse / log shell-outs. Worker so they overlap with the main spine.
buildInfo: {
expected: [],
handler: "buildInfo",
submit(out, state) {
state.site.buildInfo = out.buildInfo;
},
},
// Sass compilation split across two workers so light + dark run in parallel.
// Each half is ~700 ms total serially; running concurrently saves ~200 ms.
scssLight: {
expected: [],
handler: "scssLight",
submit() {},
},
scssDark: {
expected: [],
handler: "scssDark",
submit() {},
},
// Joins the two parallel SCSS results and writes the combined CSS to
// _site/ and _site-offline/. Depends on prepDest so the output dirs
// exist (prepDest cleans them first).
scss: {
expected: ["scssLight", "scssDark", "prepDest"],
runOnMain: true,
async execute({ scssLight: { scssLightResult }, scssDark: { scssDarkResult } }, ctx, state) {
if (scssLightResult.failed || scssDarkResult.failed) {
return { scssResult: { compiled: false, failed: true } };
}
const combined = scssLightResult.css + "\n" + scssDarkResult.css;
if (ctx.opts.dryRun) {
return { scssResult: { compiled: true, css: combined } };
}
const rel = "assets/css/just-the-docs-combined.css";
const baseurl = String(state.site.config.baseurl || "");
const online = baseurl
? combined.replace(
/url\((["']?)\/(?!\/)([^)"']*)\1\)/g,
(_, q, rest) => `url(${q}${baseurl}/${rest}${q})`,
)
: combined;
const dest = path.join(ctx.destRoot, rel);
await fs.mkdir(path.dirname(dest), { recursive: true });
await fs.writeFile(dest, online, "utf8");
const skipOffline = ctx.opts.skipOffline ?? (state.site.config.also_build_offline === false);
let offlineMisses = 0;
if (!skipOffline) {
const offlineState = {
sitePaths: state.sitePaths,
caches: { rawResolution: new Map(), seg: new Map(), result: new Map() },
baseurl: normalizeBaseurl(baseurl),
};
const { css: offlineCss, misses } = deriveOfflineCss(online, rel, offlineState);
offlineMisses = misses;
const offDest = path.join(ctx.destRoot + "-offline", rel);
await fs.mkdir(path.dirname(offDest), { recursive: true });
await fs.writeFile(offDest, offlineCss, "utf8");
}
return { scssResult: { compiled: true, css: combined }, offlineMisses };
},
submit() {},
},
// Stale DOT/Graphviz SVG regeneration. WASM-based; no headless browser,
// no in-tree patches. Runs on a worker as a seed so the Graphviz.load()
// WASM init (~50 ms) hides behind the main spine.
dot: {
expected: [],
handler: "dot",
submit(out, state) {
const known = new Set(state.staticFiles.map((f) => f.srcRel));
for (const f of out.dotStats.svgFiles ?? []) {
if (!known.has(f.srcRel)) state.staticFiles.push(f);
}
},
},
// Clean and recreate the trees the run owns. A build owns three -- _site/,
// _site-offline/ and _site-pdf/ -- and all three exist after it, whichever
// passes ran. Serve mode owns _serve/ alone: it never runs the offline or PDF
// pass, and preparing all three left an empty _serve-offline/ and _serve-pdf/
// beside _serve/ after every rebuild. Deferred to after dispatch so the wipe
// doesn't contend with discover's source-file reads. Joined by write and
// searchData.
prepDest: {
expected: ["dispatch"],
runOnMain: true,
async execute(_, ctx) {
const r = ctx.destRoot;
const roots = ctx.opts.serve ? [r] : [r, r + "-offline", r + "-pdf"];
await prepareDestinations(roots, ctx.opts.dryRun);
return {};
},
submit() {},
},
// Pre-create all page output directories while render workers are busy.
// Lets writePages skip mkdir entirely — pure writeFile.
prepPageDirs: {
expected: ["prepDest"],
runOnMain: true,
async execute(_, ctx, state) {
if (ctx.opts.dryRun) return {};
const skipOffline = ctx.opts.skipOffline ?? (state.site.config.also_build_offline === false);
const offlineRoot = skipOffline ? null : ctx.destRoot + "-offline";
await preparePageDirs(state.pages, state.staticFiles, ctx.destRoot, offlineRoot);
return {};
},
submit() {},
},
// Theme CSS load. Reads the vendored .theme files and generates the
// tb-highlight.css palette; does NOT init Shiki WASM (unneeded on main
// since no code blocks are rendered here). Workers init their own full
// highlighter instances independently. Runs after config so it sits in
// the discover I/O window; chains to loadData for the same reason.
highlighterInit: {
expected: ["config"],
runOnMain: true,
async execute() {
const theme = await loadHighlightTheme();
return { highlightCss: theme.css };
},
submit(out, state) {
state.site.highlightCss = out.highlightCss;
},
},
// On-demand per-worker Shiki initializer. Workers execute it the first
// time they claim a render chunk (per-worker dep in the SAB). Once a
// worker has run it, the highlighter persists in module scope across
// init messages, so survives_reset lets rebuilds skip it.
warmInit: {
expected: [],
on_demand: true,
unique_per_worker: true,
run_when_idle: true,
survives_reset: true,
handler: "warmInit",
submit() {},
},
// On-demand per-worker render environment init: unpacks the shared
// payload, reconstructs link-table Maps, instantiates markdown-it.
// Depends on dispatch (sharedSAB must exist) and warmInit (Shiki
// must be loaded). Moves the hidden first-chunk init cost off the
// render hot path.
renderEnvInit: {
expected: ["dispatch"],
perWorkerDeps: ["warmInit"],
on_demand: true,
unique_per_worker: true,
handler: "renderEnvInit",
submit() {},
},
// Barrier: all render:i deltas merged into state.pages (renderedContent
// available). Dep count is set to N by dispatch.submit(); each render:i
// completion decrements via the SAB successor edge. Tasks that only
// need renderedContent (not page HTML on disk) depend on this.
//
// The SAB dep count alone does NOT make this a barrier over the
// *submits* -- see dispatch.submit, which populates `expected`.
renderJoin: {
expected: [], // populated by dispatch.submit
on_demand: true,
runOnMain: true,
execute(_inputs, _ctx, state) {
// This barrier's entire meaning is "every page now has
// renderedContent". Its consumers -- the search index, the PDF
// book -- skip a page that has none rather than fail, so one that
// slipped through would vanish from their output without a word.
// That is precisely how the missing-expected-list bug stayed
// hidden. Assert the claim once, here, where it is made.
const missing = state.pages.filter(p => typeof p.renderedContent !== "string");
if (missing.length) {
throw new Error(
`${missing.length} of ${state.pages.length} pages have no renderedContent ` +
`(${missing.slice(0, 5).map(p => p.destPath).join(", ")}` +
`${missing.length > 5 ? ", ..." : ""}). A render chunk's submit() did not run ` +
`before the barrier -- see the expected-list wiring in dispatch.submit().`,
);
}
return {};
},
submit() {},
},
// Barrier: all per-chunk flush:i tasks have written their pages to disk.
// Dep count is set to N by dispatch.submit(); each flush:i completion
// decrements via the SAB successor edge. Aggregates the per-chunk write
// stats from all flush:i results.
flushJoin: {
expected: [], // populated by dispatch.submit
on_demand: true,
runOnMain: true,
execute(inputs) {
let written = 0, offlineWritten = 0, offlineMisses = 0;
for (const [name, r] of Object.entries(inputs)) {
// Asserted, not defaulted. A flush result that never arrived
// would otherwise contribute zero and the totals would simply
// read low -- a number nobody can tell apart from a smaller
// site.
if (!r || typeof r.written !== "number") {
throw new Error(
`flushJoin: ${name} produced no write stats; the page count ` +
`would silently read low`
);
}
written += r.written;
offlineWritten += r.offlineWritten ?? 0;
offlineMisses += r.offlineMisses ?? 0;
}
return { written, offlineWritten, offlineMisses };
},
submit() {},
},
// ── Main-thread spine ─────────────────────────────────────────────────────
discover: {
expected: ["config"],
runOnMain: true,
async execute({ config: { config } }, ctx) {
const { pages, staticFiles } = await discover(ctx.srcRoot, config.exclude ?? []);
for (const entry of config.bundle_extra ?? []) {
const srcPath = path.resolve(ctx.srcRoot, entry.src);
const stat = await fs.stat(srcPath);
staticFiles.push({ srcPath, srcRel: entry.dest, destRel: entry.dest, size: stat.size });
}
// Everything discover() could not parse frontmatter from is about to
// be copied verbatim into a public tree. `exclude:` is a denylist and
// only refuses what someone named in advance, so the allowlist runs
// here -- before any write, while the source path is still in hand.
const policy = publishPolicyFor(config);
const strays = unpublishableSourceFiles(staticFiles, policy);
if (strays.length) {
throw new Error(formatPublishRefusal(strays, { surface: "source", label: ctx.srcRoot }));
}
return { pages, staticFiles, config };
},
submit(out, state) {
state.pages = out.pages;
state.staticFiles = out.staticFiles;
state.site.config = out.config;
for (const p of out.pages) state.pageByDest.set(p.destPath, p);
},
},
// Download third-party images (YouTube poster frames, GitHub
// user-attachment screenshots) into the committed source tree so the
// rendered site contacts nobody. Same shape as `dot`: idempotent,
// writes into <srcRoot>/assets/, and hands newly created files to the
// static-file copy pass. CI never fetches -- see vendor-assets.mjs.
vendorAssets: {
expected: ["discover"],
runOnMain: true,
async execute(_, ctx, state) {
// CI must never download: an author who wrote the markdown but
// forgot to commit the image would otherwise get a green build
// while the site went on hotlinking a third party. Explicit flags
// win; otherwise presence of $CI decides.
const allowFetch = ctx.opts.fetchAssets ?? !process.env.CI;
return await vendorAssets(ctx.srcRoot, state.pages, {
baseurl: String(state.site.config.baseurl || ""),
allowFetch,
});
},
submit(out, state) {
state.site.vendoredVideos = out.videos;
state.site.vendoredImages = out.images;
const known = new Set(state.staticFiles.map((f) => f.srcRel));
for (const f of out.files) {
if (!known.has(f.srcRel)) state.staticFiles.push(f);
}
if (out.failed > 0) process.exitCode = 1;
},
},
nav: {
expected: ["discover"],
runOnMain: true,
execute(_, ctx, state) {
const { navTree } = computeNav(state.pages, state.site.config);
state.site.navTree = navTree;
return { sidebar: renderSidebar(state.site) };
},
submit() {},
},
// Pre-renders the config-only chrome (SVG sprites, header, search footer,
// favicon, GA). No nav-tree dependency -- runs after
// discover in parallel with nav. dispatch assembles the final initData
// by merging this with the sidebar from nav.
buildInit: {
expected: ["discover"],
runOnMain: true,
execute(_, ctx, state) {
return { initData: buildInitConfig(state.site) };
},
submit() {},
},
// Link-table build + markdown-it assembly + site-level SEO constants
// (seoSiteTitle / seoLogoUrl). Only needs discover (pages + config +
// staticFiles). Per-page SEO fields are computed on render workers in
// computeChunkSeo between renderPhase and templatePhase.
markdownInit: {
// deriveRedirects is here for the counts registry alone: {{tbdocs:redirectStubs}}
// is derived from the stub set, and nothing else on this task needs it.
expected: ["discover", "vendorAssets", "deriveRedirects"],
runOnMain: true,
execute({ deriveRedirects: { stubs } }, ctx, state) {
const linkTables = buildLinkTables(state.pages);
const baseurl = String(state.site.config.baseurl || "");
const staticFileSet = new Set(state.staticFiles.map(s => s.srcRel));
// Derived here, on main, because a count has to exist before any page
// renders -- and validated here for the same reason. An unknown name
// cannot be an error inside the substitution rule: markdown-it emits an
// unrecognised inline verbatim, so the rule would publish the typo to
// readers rather than fail. See counts.mjs.
state.site.counts = deriveCounts(state, { redirectStubs: stubs.length });
const badNames = validateCountNames(state.pages, state.site.counts);
if (badNames.length) {
throw new Error(
`unknown {{tbdocs:...}} count name in ${badNames.length} place(s):\n\n` +
badNames.join("\n\n"));
}
state.site.markdown = createMarkdownIt({
highlighter: null, linkTables, baseurl, staticFiles: staticFileSet,
vendoredVideos: state.site.vendoredVideos,
vendoredImages: state.site.vendoredImages,
counts: state.site.counts,
});
state.site.linkTablesSerialized = serializeLinkTables(linkTables);
const { seoSiteTitle, seoLogoUrl } = computeSiteSeo(state.site.config, state.site.markdown);
state.site.seoSiteTitle = seoSiteTitle;
state.site.seoLogoUrl = seoLogoUrl;
return {};
},
submit() {},
},
loadData: {
expected: ["highlighterInit"],
runOnMain: true,
async execute(_, ctx, state) {
const data = await loadData(ctx.srcRoot);
state.site.data = data;
state.site.bookData = data.book ?? null;
return {};
},
submit() {},
},
// Mutates bookData._chapters with refs into state.pages. Identity-critical:
// the same page objects must be read by writePdf later (after renderPhase
// fills in renderedContent on those same objects). Deferred to after
// deriveSitemap so it runs while the main thread is idle waiting for workers.
resolveBookChapters: {
expected: ["deriveSitemap"],
runOnMain: true,
execute(_, ctx, state) {
resolveBookChapters(state.site.bookData, state.pages);
return {};
},
submit() {},
},
// Can run in parallel with nav/markdownInit -- only needs pages + config,
// both available after discover. The layout-based filter (not p.html)
// lets this run before templatePhase.
deriveRedirects: {
expected: ["discover"],
runOnMain: true,
execute(_, ctx, state) {
return { stubs: deriveRedirectStubs(state.pages, state.site) };
},
submit(out, state) {
// linkJoin needs the stub set: redirect stubs are excluded from
// the sitemap / search / canonical checks, and the build knows
// exactly which pages it generated as stubs -- the standalone
// script has to sniff for a meta refresh instead.
state.checkStubs = out.stubs;
},
},
// Deferred to after dispatch so it runs while the main thread is idle
// waiting for render workers, rather than contending during the spine.
deriveSitemap: {
expected: ["dispatch"],
runOnMain: true,
execute(_, ctx, state) {
return { urls: deriveSitemapUrls(state.pages, state.site) };
},
submit() {},
},
// ── Render fan-out ─────────────────────────────────────────────────────────
// Slices state.pages into chunks and dynamically registers render:0..N
// worker tasks plus a renderJoin barrier. Assembles initData from the
// two parallel halves: nav (sidebar) + buildInit (config-only chrome).
dispatch: {
expected: ["nav", "buildInit", "buildInfo", "dot", "deriveRedirects", "markdownInit"],
runOnMain: true,
async execute({ nav: { sidebar }, buildInit: { initData }, buildInfo: { buildInfo }, dot: _dotSignal, markdownInit: _markdownInitSignal, deriveRedirects: { stubs } }, ctx, state) {
void _dotSignal; // dependency signal only -- static files already appended in dot.submit
void _markdownInitSignal; // dependency signal only -- markdown + linkTablesSerialized + seoSiteTitle/seoLogoUrl already on state.site
const chunks = chunkPages(state.pages, ctx.workerCount);
const excludePatterns = Array.isArray(state.site.config?.offline_exclude)
? state.site.config.offline_exclude.map(String)
: [];
const themeAssetRels = [
...enumerateVendoredThemeAssets(),
"assets/css/tb-highlight.css",
"assets/css/just-the-docs-combined.css",
];
const sitePaths = buildSitePathsSync(state.pages, state.staticFiles, excludePatterns, stubs, themeAssetRels);
state.sitePaths = sitePaths;
const skipOffline = ctx.opts.skipOffline ?? (state.site.config.also_build_offline === false);
// Everything deriveTreeRels needs is settled at this point: pages
// from discover, stubs from deriveRedirects, staticFiles after dot
// and vendorAssets have appended theirs, and the theme assets right
// above. Two consumers below share it.
const common = {
pages: state.pages, staticFiles: state.staticFiles, stubs,
themeAssetRels, excludePatterns,
};
const treeNames = skipOffline ? ["online"] : ["online", "offline"];
const treeRels = new Map(treeNames.map(w => [w, deriveTreeRels(w, common)]));
// Second enforcement point for the publish allowlist, over the
// inventory each tree will actually receive. The source sweep in
// `discover` cannot see any of this: redirect stubs, vendored theme
// assets and the generated auxiliaries (sitemap.xml,
// search-data.json) are all minted by the build, not found in docs/.
// Runs unconditionally, not under --check: a build with checks off
// is exactly when nothing else is watching.
const policy = publishPolicyFor(state.site.config);
for (const [which, rels] of treeRels) {
const strays = unpublishableTreePaths(rels, policy);
if (strays.length) {
throw new Error(formatPublishRefusal(strays, {
surface: "tree", label: `the ${which} tree`,
}));
}
}
// --check: what each output tree will receive, derived from the
// build's own records. This is the treeIndex step, computed here
// rather than as its own task because the workers can only be
// handed data that goes into dispatch's shared payload -- it is
// packed and broadcast in submit() below.
const checkTrees = ctx.opts.check && !ctx.opts.dryRun ? {} : null;
if (checkTrees) {
// Only the online tree carries a base path. The offline tree's
// links are all relative after the rewrite, which is why the
// deploy workflow passes --base-path to the online pass alone.
checkTrees.online = {
rels: treeRels.get("online"),
baseurl: String(state.site.config.baseurl || ""),
};
if (!skipOffline) {
checkTrees.offline = { rels: treeRels.get("offline"), baseurl: "" };
}
state.checkTrees = checkTrees;
}
const svgContentsMap = Object.create(null);
for (const f of state.staticFiles) {
if (f.srcRel.endsWith(".svg")) {
try {
svgContentsMap[f.srcRel] = await fs.readFile(path.join(ctx.srcRoot, f.srcRel), "utf8");
} catch {}
}
}
const shared = {
siteData: {
config: state.site.config,
seoSiteTitle: state.site.seoSiteTitle,
seoLogoUrl: state.site.seoLogoUrl,
},
initData: { ...initData, sidebar },
buildInfo,
linkTablesData: state.site.linkTablesSerialized,
staticFilesArr: state.staticFiles.map(f => f.srcRel),
baseurl: String(state.site.config.baseurl || ""),
sitePathsArr: [...sitePaths],
offlineExcludePatterns: excludePatterns,
skipOffline,
svgContentsMap,
checkTrees,
// Plain objects, not Maps -- packShared serialises to JSON.
vendoredVideosObj: Object.fromEntries(state.site.vendoredVideos ?? []),
vendoredImagesObj: Object.fromEntries(state.site.vendoredImages ?? []),
counts: state.site.counts,
};
const sharedSAB = packShared(shared);
return { chunks, sharedSAB };
},
submit(out, _state, scheduler) {
const N = out.chunks.length;
const views = scheduler._views;
const idMap = scheduler._idMapping;
const renderJoinIdx = idMap.nameToIdx.get("renderJoin");
const flushJoinIdx = idMap.nameToIdx.get("flushJoin");
const renderEnvInitIdx = idMap.nameToIdx.get("renderEnvInit");
const prepPageDirsIdx = idMap.nameToIdx.get("prepPageDirs");
// Phase 17: pre-allocate searchChunks so each render:i.submit() can
// assign by chunk index regardless of completion order. After
// renderJoin fires, scheduler.state.searchChunks[0..N-1] holds every
// worker's per-chunk entries in pages-order.
scheduler.state.searchChunks = new Array(N);
scheduler.state.checkChunks = [];
// linkJoin compares against this: a chunk that never arrived would
// otherwise mean the link check quietly examined fewer pages and
// still reported a clean pass.
scheduler.state.checkChunkCount = N;
// 1. Allocate 2N slots from the generic pool.
const renderBase = allocDynamicSlots(views, idMap, N);
const flushBase = allocDynamicSlots(views, idMap, N);
// 2. Write metadata into the SAB.
for (let i = 0; i < N; i++) {
writeTaskMeta(views, renderBase + i, {
handlerIdx: HANDLERS.render,
perWorkerDeps: [renderEnvInitIdx],
});
writeTaskMeta(views, flushBase + i, {
handlerIdx: HANDLERS.flush,
priority: 1,
});
}
// 3. Wire edges: render:i → [renderJoin, flush:i],
// flush:i → [flushJoin].
const edges = [];
for (let i = 0; i < N; i++) {
edges.push({ from: renderBase + i, to: [renderJoinIdx, flushBase + i] });
edges.push({ from: flushBase + i, to: [flushJoinIdx] });
}
wireDynamicEdges(views, edges);
// Append prepPageDirs → flush:0..N-1 (so flush:i waits until the
// output dirs exist; prepPageDirs already has writeAssets as a
// static successor, so use the append helper).
const prepPageDirsToFlush = [];
for (let i = 0; i < N; i++) prepPageDirsToFlush.push(flushBase + i);
appendDynamicSuccessors(views, [{ from: prepPageDirsIdx, to: prepPageDirsToFlush }]);
// 4. Set dep counts and pinning. The two barriers go through
// registerBarrier so the dep count cannot be written without
// the matching `expected` list -- see its comment.
for (let i = 0; i < N; i++) {
setDepCount(views, flushBase + i, 2); // gated on render:i + prepPageDirs
Atomics.store(views.pinnedTo, flushBase + i, renderBase + i);
views.flags[flushBase + i] |= F_PIN_TO_PRED;
}
// 5. Register names + task defs on the main-thread scheduler so
// _onWorkerDone can look up consolidate/ganttSection/submit and
// _assembleInputs can resolve flushJoin's expected list.
for (let i = 0; i < N; i++) {
const rName = `render:${i}`;
idMap.nameToIdx.set(rName, renderBase + i);
idMap.idxToName[renderBase + i] = rName;
scheduler.tasks.set(rName, {
expected: [],
consolidate: true,
ganttSection: "Render",
// Only consulted by the stall watchdog. "render:33 never
// returned" is not actionable on its own; the six source
// paths in that chunk are, because the fault is nearly always
// one page's content.
describe: () => out.chunks[i].map(p => p.srcRel ?? p.srcPath),
submit(renderOut, state) {
for (const r of renderOut.pages) {
const p = state.pageByDest.get(r.destPath);
// Dropping the result would lose this page's
// renderedContent, and every consumer of that skips a page
// that has none rather than complaining. pageByDest is
// built from the same page list the chunks were sliced
// from, so a miss is a bug, not a condition to tolerate.
if (!p) {
throw new Error(
`render:${i} returned a page the build does not know: ${r.destPath}`,
);
}
p.renderedContent = r.renderedContent;
if (r.offlineMisses !== undefined) p.offlineMisses = r.offlineMisses;
}
state.searchChunks[i] = renderOut.searchEntries;
},
});
const fName = `flush:${i}`;
idMap.nameToIdx.set(fName, flushBase + i);
idMap.idxToName[flushBase + i] = fName;
scheduler.tasks.set(fName, {
expected: [`render:${i}`],
consolidate: true,
ganttSection: "Write",
describe: () => out.chunks[i].map(p => p.srcRel ?? p.srcPath),
submit(flushOut, state) {
// --check: the per-chunk reduction rides back on flush's
// result. Sized by findings, not by the 793k occurrences --
// those never cross the thread boundary.
if (flushOut?.check) state.checkChunks.push(flushOut.check);
},
});
}
registerBarrier(scheduler, views, "renderJoin", renderJoinIdx, "render", N);
registerBarrier(scheduler, views, "flushJoin", flushJoinIdx, "flush", N);
// 6. Pack payload, broadcast, account, activate.
const payloadSAB = packPayloads(views, renderBase, out.chunks);
scheduler.addDynamicTasks(2 * N + 2); // N render + N flush + renderJoin + flushJoin
scheduler.pool.broadcastDynamicData(payloadSAB, out.sharedSAB);
activateDynamicTasks(views, renderBase, 2 * N); // render:i activate (depCount 0);
// flush:i stay NOT_READY (depCount 1)
},
},
// ── Write and post-write tasks ─────────────────────────────────────────────
// Materialise theme JS, static files, and highlight CSS to _site/.
// Page HTML is written by per-worker flush; combined SCSS is written
// by the scss task.
writeAssets: {
// vendorAssets is listed for the same reason `dot` is: it appends
// the files it downloaded to the static-file list, and writeAssets
// copies that list. The chain prepPageDirs <- prepDest <- dispatch
// <- markdownInit happens to order them today; naming the dependency
// is what keeps that true.
expected: ["dot", "vendorAssets", "prepPageDirs", "highlighterInit"],
runOnMain: true,
async execute({ dot: _dotSignal, highlighterInit: _highlightSignal }, ctx, state) {
void _dotSignal; // dependency signal only; append already happened in dot.submit
void _highlightSignal; // dependency signal only; highlightCss already written to state.site
const generatedAssets = [];
if (state.site.highlightCss) {
generatedAssets.push({ rel: "assets/css/tb-highlight.css", content: state.site.highlightCss });
}
return writePhase(state.pages, state.staticFiles, {
destRoot: ctx.destRoot,
dryRun: ctx.opts.dryRun,
generatedAssets,
baseurl: String(state.site.config.baseurl || ""),
skipPages: true,
});
},
submit() {},
},
// Write search-data.json. Depends on renderJoin (every render:i.submit
// has stored its searchEntries in state.searchChunks[i]) and prepDest
// (_site/ exists). Result passes through to writeAux so its search.json
// field reaches writeOffline. Heavy lifting (extractSections, stripHtml,
// sanitiseContent) ran on the workers; this task only concatenates and
// renumbers.
searchData: {
expected: ["renderJoin", "prepDest"],
runOnMain: true,
async execute(_, ctx, state) {
if (ctx.opts.dryRun) return { entries: 0, json: "" };
return writeSearchDataFromChunks(state.searchChunks, ctx.destRoot);
},
submit() {},
},
// Write tB/symbols.json, the symbol index the IDE help add-in reads -- see
// builder/symbols.mjs. renderJoin because an entry's anchor is the id the
// render gave its heading, read from the HTML; prepDest for the tree. The
// package half comes from builder/package-api.json, a committed snapshot the
// build never regenerates, because regenerating it needs a twinBASIC install.
symbolIndex: {
expected: ["renderJoin", "prepDest"],
runOnMain: true,
async execute(_, ctx, state) {
let api;
try {
api = JSON.parse(await fs.readFile(PACKAGE_API_PATH, "utf8"));
} catch (err) {
if (err.code !== "ENOENT") throw err;
throw new Error("builder/package-api.json is missing, and the symbol index needs it. " +
"Restore it from git, or regenerate it with node scripts/build_package_api.mjs");
}
const pages = symbolPages(state.pages);
const result = deriveSymbolIndex({ pages, api });
const gaps = reportableGaps(result, pages, api);
if (!ctx.opts.dryRun) {
await writeFileMkdirp(path.join(ctx.destRoot, SYMBOL_INDEX_REL), serializeSymbolIndex(result, api));
}
if (ctx.opts.symbolGaps) {
await fs.writeFile(ctx.opts.symbolGaps, `${JSON.stringify(gaps, null, 1)}\n`, "utf8");
}
return {
entries: result.symbols.length,
urls: [...new Set(result.symbols.map((s) => s.url))],
gaps: gaps.length,
unplaced: result.unplaced,
};
},
submit() {},
},
// Write redirect stubs + sitemap/robots. Waits for writeAssets (theme on
// disk), searchData, deriveRedirects, and deriveSitemap.
// Passes searchStats through to writeOffline (for search-data.js).
writeAux: {