-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepare-docs.mjs
More file actions
792 lines (677 loc) · 25.7 KB
/
prepare-docs.mjs
File metadata and controls
792 lines (677 loc) · 25.7 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
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
detectDocsLayout,
docsLayoutPaths,
excludeNamesForRootCopy,
exists,
} from "./docs-layout.mjs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const workspaceRoot = path.resolve(__dirname, "..");
const legacyDocsToArchive = [
{
source: "building-features/hmr-and-hot-reloading-with-the-webpack-dev-server.md",
replacement: "building-features/process-managers.md",
reason:
"This guide is webpacker-era and includes obsolete package/version guidance (React on Rails 11.x, Node 12)."
},
{
source: "building-features/rails-webpacker-react-integration-options.md",
replacement: "getting-started/installation-into-an-existing-rails-app.md",
reason:
"This comparison page targets legacy integration stacks and React < 18 compatibility workarounds."
},
{
source: "deployment/troubleshooting-when-using-webpacker.md",
replacement: "deployment/troubleshooting.md",
reason:
"This page documents webpacker-3 / Rails-5 era troubleshooting and should be treated as historical reference."
},
{
source: "misc/asset-pipeline.md",
replacement: "getting-started/project-structure.md",
reason: "This page is Sprockets-era migration guidance with limited value for modern setups."
}
];
function argValue(name) {
const index = process.argv.indexOf(name);
if (index === -1) {
return null;
}
return process.argv[index + 1] ?? null;
}
const target = argValue("--target");
const useSubset = process.argv.includes("--subset");
const sourceDocs = path.join(
workspaceRoot,
"content",
"upstream",
useSubset ? "docs-subset" : "docs"
);
async function ensureExists(targetPath, message) {
try {
await fs.access(targetPath);
} catch {
throw new Error(message);
}
}
async function copyDirectoryContents(sourceDir, targetDir, options = {}) {
const {excludeNames = new Set()} = options;
await fs.mkdir(targetDir, { recursive: true });
const entries = await fs.readdir(sourceDir, { withFileTypes: true });
for (const entry of entries) {
if (excludeNames.has(entry.name)) {
continue;
}
const sourcePath = path.join(sourceDir, entry.name);
const targetPath = path.join(targetDir, entry.name);
if (entry.isDirectory()) {
await fs.cp(sourcePath, targetPath, { recursive: true });
continue;
}
await fs.copyFile(sourcePath, targetPath);
}
}
async function walkFiles(dir, callback, relativePrefix = "") {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const rel = relativePrefix ? path.join(relativePrefix, entry.name) : entry.name;
const abs = path.join(dir, entry.name);
if (entry.isDirectory()) {
await walkFiles(abs, callback, rel);
continue;
}
if (entry.isFile()) {
await callback(abs, rel);
}
}
}
function toPosix(relativePath) {
return relativePath.split(path.sep).join("/");
}
function stripMdExtension(relativePath) {
return relativePath.replace(/\.(md|mdx)$/i, "");
}
function routeForDoc(relativePath) {
return `/docs/${stripMdExtension(toPosix(relativePath))}`;
}
function resolveRelativeDocPath(currentRelativePath, rawTarget) {
const sourceDir = path.posix.dirname(toPosix(currentRelativePath));
return path.posix.normalize(path.posix.join(sourceDir, rawTarget));
}
function rewriteRelativeMarkdownLinksToAbsolute(markdown, sourceRelativePath) {
return markdown.replace(/\]\(([^)]+)\)/g, (fullMatch, rawTargetWithMaybeTitle) => {
const targetWithMaybeTitle = rawTargetWithMaybeTitle.trim();
const targetOnlyMatch = targetWithMaybeTitle.match(/^([^\s]+)(\s+["'][^"']*["'])?$/);
if (!targetOnlyMatch) {
return fullMatch;
}
const target = targetOnlyMatch[1];
const optionalTitle = targetOnlyMatch[2] ?? "";
if (
target.startsWith("http://") ||
target.startsWith("https://") ||
target.startsWith("mailto:") ||
target.startsWith("#") ||
target.startsWith("/")
) {
return fullMatch;
}
const [targetPathAndQuery, anchor = ""] = target.split("#");
const [targetPath, query = ""] = targetPathAndQuery.split("?");
const resolved = resolveRelativeDocPath(sourceRelativePath, targetPath);
if (resolved.startsWith("..")) {
return fullMatch;
}
const querySuffix = query ? `?${query}` : "";
const anchorSuffix = anchor ? `#${anchor}` : "";
const isMarkdownDoc = /\.(md|mdx)$/i.test(resolved);
const absolutePath = isMarkdownDoc ? routeForDoc(resolved) : `/docs/${resolved}`;
return `](${absolutePath}${querySuffix}${anchorSuffix}${optionalTitle})`;
});
}
async function rewriteDoc(docsRoot, relativePath, transform) {
const absolutePath = path.join(docsRoot, ...relativePath.split("/"));
if (!(await exists(absolutePath))) {
return false;
}
const original = await fs.readFile(absolutePath, "utf8");
const updated = transform(original);
if (updated !== original) {
await fs.writeFile(absolutePath, updated, "utf8");
return true;
}
return false;
}
async function rewriteDocsByPattern(docsRoot, replacements) {
let rewrittenFiles = 0;
await walkFiles(docsRoot, async (absoluteFile, relativeFile) => {
if (!relativeFile.endsWith(".md") && !relativeFile.endsWith(".mdx")) {
return;
}
const original = await fs.readFile(absoluteFile, "utf8");
let updated = original;
for (const replacement of replacements) {
updated = updated.replace(replacement.pattern, replacement.replacement);
}
if (updated !== original) {
await fs.writeFile(absoluteFile, updated, "utf8");
rewrittenFiles += 1;
}
});
return rewrittenFiles;
}
function extractTitle(markdown, fallbackTitle) {
const match = markdown.match(/^#\s+(.+)$/m);
return match ? match[1].trim() : fallbackTitle;
}
function legacyArchiveIndexMarkdown(indexRows) {
const list = indexRows
.map(
(entry) =>
`- [${entry.title}](${entry.link}) — ${entry.reason} Prefer [current guidance](${entry.replacementLink}).`
)
.join("\n");
return `# Legacy Archive
These pages remain available as historical reference, but they are no longer recommended for new projects.
${list}
`;
}
function archiveRootMarkdown() {
return `# Historical Reference
Older material is grouped here to keep the main docs focused on current React on Rails workflows.
- [Legacy Archive](./legacy/README.md)
`;
}
async function archiveLegacyDocs(docsRoot) {
const archiveIndexRows = [];
for (const entry of legacyDocsToArchive) {
const sourcePath = path.join(docsRoot, ...entry.source.split("/"));
if (!(await exists(sourcePath))) {
continue;
}
const original = await fs.readFile(sourcePath, "utf8");
const title = extractTitle(original, path.basename(entry.source, ".md"));
const archiveRelative = path.posix.join("archive", "legacy", entry.source);
const archivePath = path.join(docsRoot, ...archiveRelative.split("/"));
await fs.mkdir(path.dirname(archivePath), { recursive: true });
const archivedBody = rewriteRelativeMarkdownLinksToAbsolute(original, entry.source);
const archiveWarning = `> [!WARNING]\n> Archived legacy content. Use current docs for active guidance.\n\n`;
const archivedWithWarning = archivedBody.match(/^#\s+.+\n/m)
? archivedBody.replace(/^#\s+.+\n/m, (match) => `${match}\n${archiveWarning}`)
: `# ${title}\n\n${archiveWarning}${archivedBody}`;
await fs.writeFile(archivePath, archivedWithWarning, "utf8");
const relativeArchiveLink = toPosix(path.relative(path.dirname(sourcePath), archivePath));
const replacementRoute = routeForDoc(entry.replacement);
const stub = `# ${title}\n\n> [!WARNING]\n> This page has moved to the [legacy archive](${relativeArchiveLink}).\n> ${entry.reason}\n> For current guidance, use [this page](${replacementRoute}).\n`;
await fs.writeFile(sourcePath, stub, "utf8");
archiveIndexRows.push({
title,
link: `./${entry.source}`,
reason: entry.reason,
replacementLink: replacementRoute
});
}
if (archiveIndexRows.length === 0) {
return false;
}
const archiveRoot = path.join(docsRoot, "archive");
const legacyRoot = path.join(archiveRoot, "legacy");
await fs.mkdir(legacyRoot, { recursive: true });
await fs.writeFile(path.join(archiveRoot, "README.md"), archiveRootMarkdown(), "utf8");
await fs.writeFile(
path.join(legacyRoot, "README.md"),
legacyArchiveIndexMarkdown(archiveIndexRows),
"utf8"
);
return true;
}
export function fixProNodeRendererMdx(content) {
return content.replace("Direct render: <50ms", "Direct render: <50ms");
}
async function fixKnownDocsIssues(docsRoot) {
await rewriteDocsByPattern(docsRoot, [
{
pattern: /\]\(\.\.\/\.\.\/README\.md\)/g,
replacement: "](/docs/)"
}
]);
await rewriteDoc(docsRoot, "api-reference/redux-store-api.md", (content) =>
content.replace(
"#important-redux-shared-store-caveat",
"#redux-shared-store-caveat"
)
);
await rewriteDoc(docsRoot, "building-features/process-managers.md", (content) =>
content.replaceAll("./i18n.md#internationalization", "./i18n.md")
);
await rewriteDoc(docsRoot, "deployment/troubleshooting.md", (content) =>
content
.replace(/\(#-([^)]+)\)/g, "(#$1)")
.replace(
"## 🚨 Installation Issues",
"## 🚨 Installation Issues {#installation-issues}"
)
.replace("## 🔧 Build Issues", "## 🔧 Build Issues {#build-issues}")
.replace("## ⚡ Runtime Issues", "## ⚡ Runtime Issues {#runtime-issues}")
.replace("## 🎨 CSS Modules Issues", "## 🎨 CSS Modules Issues {#css-modules-issues}")
.replace(
"## 🖥️ Server-Side Rendering Issues",
"## 🖥️ Server-Side Rendering Issues {#server-side-rendering-issues}"
)
.replace("## 🐌 Performance Issues", "## 🐌 Performance Issues {#performance-issues}")
);
await rewriteDoc(docsRoot, "migrating/rsc-data-fetching.md", (content) =>
content.replace(
"See the [runtime validation example](#runtime-validation-for-server-actions) in the Troubleshooting guide.",
"See the [runtime validation example](./rsc-troubleshooting.md#runtime-validation-for-server-actions) in the Troubleshooting guide."
)
);
await rewriteDoc(docsRoot, "pro/caching.md", (content) =>
content.replace(
/\n# Confirming and Debugging Cache Keys\n/,
"\n## Confirming and Debugging Cache Keys\n"
)
);
await rewriteDoc(docsRoot, "configuration/README.md", (content) =>
content.replace("docs/release-notes/16.0.0.md", "../upgrading/release-notes/16.0.0.md")
);
await rewriteDoc(docsRoot, "deployment/troubleshooting-when-using-shakapacker.md", (content) =>
content.replace("React on Rails version: 13.3.5", "React on Rails version: 16.4.0")
);
await rewriteDoc(
docsRoot,
"building-features/how-to-use-different-files-for-client-and-server-rendering.md",
(content) =>
content.replace(
/^## How to use different versions of a file for client and server rendering/m,
"# How to use different versions of a file for client and server rendering"
)
);
await rewriteDoc(docsRoot, "migrating/migrating-from-react-rails.md", (content) =>
content.replace(/^## Migrate From react-rails/m, "# Migrate From react-rails")
);
await rewriteDoc(docsRoot, "pro/home-pro.md", (content) =>
content
.replace("Now supports React 18", "Now supports React 19")
.replace(
"### 🚀 Next-Gen Server Rendering: Streaming with React 18's Latest APIs",
"### 🚀 Next-Gen Server Rendering: Streaming with React 19's Latest APIs"
)
.replace(
"React on Rails Pro supports React 18's Streaming Server-Side Rendering",
"React on Rails Pro supports React 19's Streaming Server-Side Rendering"
)
);
await rewriteDoc(docsRoot, "pro/ruby-api.md", (content) =>
content.replace("using React 18's `renderToPipeableStream`", "using React 19's `renderToPipeableStream`")
);
await rewriteDoc(docsRoot, "pro/node-renderer.md", fixProNodeRendererMdx);
await rewriteDoc(docsRoot, "api-reference/view-helpers-api.md", (content) =>
content.replace("using React 18+ streaming", "using React 19+ streaming")
);
const streamDocPaths = [
"building-features/streaming-server-rendering.md",
"pro/streaming-server-rendering.md"
];
for (const streamPath of streamDocPaths) {
await rewriteDoc(docsRoot, streamPath, (content) =>
content
.replace(
"# 🚀 Streaming Server Rendering with React 18",
"# 🚀 Streaming Server Rendering with React 19"
)
.replace(
"React on Rails Pro supports streaming server rendering using React 18's latest APIs",
"React on Rails Pro supports streaming server rendering using React 19's latest APIs"
)
.replace(
"**⚠️ Important: Redux Shared Store Caveat**",
"#### Redux Shared Store Caveat {#redux-shared-store-caveat}"
)
.replaceAll("React 18's Selective Hydration", "React 19's Selective Hydration")
);
}
await rewriteDocsByPattern(docsRoot, [
{
pattern: /https:\/\/www\.shakacode\.com\/react-on-rails\/docs\//g,
replacement: "https://reactonrails.com/docs/"
},
{
pattern: /https:\/\/www\.shakacode\.com\/react-on-rails-pro\/docs\//g,
replacement: "https://reactonrails.com/docs/pro/"
},
]);
}
export async function rewriteProLinks(proDocsRoot) {
if (!(await exists(proDocsRoot))) {
return;
}
await walkFiles(proDocsRoot, async (absoluteFile, relativeFile) => {
if (!relativeFile.endsWith(".md") && !relativeFile.endsWith(".mdx")) {
return;
}
const original = await fs.readFile(absoluteFile, "utf8");
const updated = original
.replace(/((?:\.\.\/)+)oss\//g, "$1")
.replace(/https:\/\/www\.shakacode\.com\/react-on-rails\/docs\//g, "https://reactonrails.com/docs/")
.replace(/https:\/\/www\.shakacode\.com\/react-on-rails-pro\/docs\//g, "https://reactonrails.com/docs/pro/");
if (updated !== original) {
await fs.writeFile(absoluteFile, updated, "utf8");
}
});
}
export async function rewriteFlattenedOssLinks(docsRoot) {
await walkFiles(docsRoot, async (absoluteFile, relativeFile) => {
if (!relativeFile.endsWith(".md") && !relativeFile.endsWith(".mdx")) {
return;
}
if (relativeFile.startsWith("pro/")) {
return;
}
const original = await fs.readFile(absoluteFile, "utf8");
const updated = original
.replace(/\.\.\/\.\.\/pro\//g, "../pro/")
.replace(/\.\.\/\.\.\/images\//g, "../images/")
.replace(/\.\.\/\.\.\/\.\.\/assets\//g, "../../assets/")
.replace(/https:\/\/www\.shakacode\.com\/react-on-rails\/docs\//g, "https://reactonrails.com/docs/")
.replace(/https:\/\/www\.shakacode\.com\/react-on-rails-pro\/docs\//g, "https://reactonrails.com/docs/pro/");
if (updated !== original) {
await fs.writeFile(absoluteFile, updated, "utf8");
}
});
}
export async function injectProFriendlyNotice(docsRoot) {
const proIntroPath = path.join(docsRoot, "pro", "react-on-rails-pro.md");
if (!(await exists(proIntroPath))) {
return;
}
const original = await fs.readFile(proIntroPath, "utf8");
let updated = original;
// Inject slug so this doc serves at /docs/pro/ instead of /docs/pro/react-on-rails-pro
if (!updated.includes("slug:")) {
if (updated.startsWith("---")) {
// Existing frontmatter — insert slug after opening ---
updated = updated.replace(/^---\n/, "---\nslug: /pro\n");
} else {
// No frontmatter — add it
updated = `---\nslug: /pro\n---\n\n${updated}`;
}
}
if (!/Friendly license model/i.test(updated)) {
const notice = `> **Friendly license model**\n> Try React on Rails Pro freely in development, test, CI/CD, and staging. No token is required to evaluate. If no license is configured, Pro keeps running in unlicensed mode and logs license status instead of blocking your app. Production deployments require a paid license; see [Pro pricing and sign up](https://pro.reactonrails.com/).\n\n`;
updated = updated.replace(/^# React on Rails Pro\s*\n+/m, `# React on Rails Pro\n\n${notice}`);
}
if (updated !== original) {
await fs.writeFile(proIntroPath, updated, "utf8");
}
}
const githubAlertToDocusaurus = {
NOTE: "note",
TIP: "tip",
IMPORTANT: "info",
WARNING: "warning",
CAUTION: "danger",
};
const languageRemapping = {
rsc: "text",
procfile: "yaml",
Procfile: "yaml",
"Procfile.dev": "yaml",
gitignore: "ignore",
JSON: "json"
};
function detectCodeLanguage(content) {
const lines = content.split("\n");
const firstLine = lines[0] || "";
if (firstLine.startsWith("#!/")) return "bash";
if (/^\$ /.test(firstLine)) return "bash";
if (/^(yarn |npm |npx |bundle exec |rails |bin\/)/.test(firstLine)) return "bash";
if (/^[A-Z_]+=\S+$/.test(firstLine.trim()) && lines.length <= 2) return "bash";
if (/\b(const |let |var |require\(|module\.exports|import )/.test(content)) return "js";
return "text";
}
function convertGitHubAlertsInMarkdown(markdown) {
const alertPattern = /^(\s*)>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](.*)$/;
const lines = markdown.split("\n");
const result = [];
let i = 0;
let fence = null;
while (i < lines.length) {
const line = lines[i];
const normalizedLine = line.replace(/^\s*(?:>\s*)+/, "");
if (!fence) {
const openingFence = normalizedLine.match(/^\s*(`{3,}|~{3,})/);
if (openingFence) {
fence = {
marker: openingFence[1][0],
length: openingFence[1].length,
};
result.push(line);
i++;
continue;
}
} else {
result.push(line);
const closingFence = normalizedLine.match(/^\s*(`{3,}|~{3,})\s*$/);
if (
closingFence &&
closingFence[1][0] === fence.marker &&
closingFence[1].length >= fence.length
) {
fence = null;
}
i++;
continue;
}
const alertMatch = line.match(alertPattern);
if (alertMatch) {
const indent = alertMatch[1];
const admonitionType = githubAlertToDocusaurus[alertMatch[2]];
const trailing = alertMatch[3].trim();
const contentLines = [];
// Handle inline content after the alert type (e.g., "> [!WARNING] > **Title**")
if (trailing) {
contentLines.push(trailing.replace(/^>\s*/, ""));
}
i++;
while (i < lines.length && lines[i].startsWith(`${indent}>`)) {
contentLines.push(lines[i].replace(new RegExp(`^${indent}>\\s?`), ""));
i++;
}
result.push(`${indent}:::${admonitionType}`);
for (const line of contentLines) {
result.push(line ? `${indent}${line}` : "");
}
result.push(`${indent}:::`);
} else {
result.push(line);
i++;
}
}
return result.join("\n");
}
function normalizeCodeFencesInMarkdown(markdown) {
const lines = markdown.split("\n");
let inBlock = false;
let blockOpenIdx = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!inBlock && /^```\S/.test(line)) {
const lang = line.slice(3).trim();
if (languageRemapping[lang]) {
lines[i] = `\`\`\`${languageRemapping[lang]}`;
}
inBlock = true;
continue;
}
if (!inBlock && /^```\s*$/.test(line)) {
blockOpenIdx = i;
inBlock = true;
continue;
}
if (inBlock && /^```\s*$/.test(line)) {
if (blockOpenIdx >= 0) {
const blockContent = lines.slice(blockOpenIdx + 1, i).join("\n");
lines[blockOpenIdx] = `\`\`\`${detectCodeLanguage(blockContent)}`;
blockOpenIdx = -1;
}
inBlock = false;
}
}
return lines.join("\n");
}
async function convertGitHubAlerts(docsRoot) {
let filesUpdated = 0;
await walkFiles(docsRoot, async (absoluteFile, relativeFile) => {
if (!relativeFile.endsWith(".md") && !relativeFile.endsWith(".mdx")) {
return;
}
const original = await fs.readFile(absoluteFile, "utf8");
const updated = convertGitHubAlertsInMarkdown(original);
if (updated !== original) {
await fs.writeFile(absoluteFile, updated, "utf8");
filesUpdated += 1;
}
});
if (filesUpdated > 0) {
console.log(`Converted GitHub alerts to Docusaurus admonitions in ${filesUpdated} files`);
}
}
async function normalizeCodeFences(docsRoot) {
let filesUpdated = 0;
await walkFiles(docsRoot, async (absoluteFile, relativeFile) => {
if (!relativeFile.endsWith(".md") && !relativeFile.endsWith(".mdx")) {
return;
}
const original = await fs.readFile(absoluteFile, "utf8");
const updated = normalizeCodeFencesInMarkdown(original);
if (updated !== original) {
await fs.writeFile(absoluteFile, updated, "utf8");
filesUpdated += 1;
}
});
if (filesUpdated > 0) {
console.log(`Normalized code fences in ${filesUpdated} files`);
}
}
export function docsHomeMarkdown(sourceMarkdown, { hasArchive }) {
const archiveBlock = hasArchive ? "- [Historical Reference](./archive/README.md)\n" : "";
const friendlyLicenseSection = `## Friendly License Model
- Try React on Rails Pro freely in development, test, CI/CD, and staging. No token is required to evaluate.
- Production deployments require a paid license. See [Pro pricing and sign up](https://pro.reactonrails.com/) for current options. If your organization is budget-constrained, [contact us](mailto:justin@shakacode.com) about free or low-cost licenses.
`;
const updated = sourceMarkdown
.trim()
.replaceAll("(./oss/", "(./")
.replace("](https://reactonrails.com/examples)", "](/examples)")
.replace(/\n- \[Documentation website\]\(https:\/\/reactonrails\.com\/docs\/\)\s*/g, "\n")
.replace(/## Friendly evaluation policy\n\n[\s\S]*?(?=\n## )/, `${friendlyLicenseSection}\n`)
.replace("## Need more help?\n\n", `## Need more help?\n\n${archiveBlock}`);
return `---\ncustom_edit_url: null\n---\n\n${updated}\n`;
}
function archiveSidebarCategory() {
const legacyItems = legacyDocsToArchive.map(
(entry) => ` 'archive/legacy/${stripMdExtension(entry.source)}',`
);
return ` {
type: 'category',
label: 'Historical Reference',
link: {type: 'generated-index', title: 'Historical Reference'},
items: [
'archive/README',
{
type: 'category',
label: 'Legacy Archive',
items: [
'archive/legacy/README',
${legacyItems.join("\n")}
],
},
],
},`;
}
async function prepareSidebars(siteRoot, hasArchive) {
const upstreamSidebars = path.join(workspaceRoot, "content", "upstream", "sidebars.ts");
const targetSidebars = path.join(siteRoot, "sidebars.ts");
if (await exists(upstreamSidebars)) {
let content = await fs.readFile(upstreamSidebars, "utf8");
if (hasArchive) {
// Insert archive category as the last item in docsSidebar before the closing ];
const archiveCategory = archiveSidebarCategory();
content = content.replace(
/(\n \],\n\};\n)/,
`\n${archiveCategory}\n ],\n};\n`
);
}
await fs.writeFile(targetSidebars, content, "utf8");
console.log("Generated sidebars.ts from upstream");
} else {
console.warn("Warning: upstream sidebars.ts not found — using committed fallback");
}
}
async function prepareDocusaurus() {
const siteRoot = path.join(workspaceRoot, "prototypes", "docusaurus");
const docsRoot = path.join(siteRoot, "docs");
const layout = await detectDocsLayout(sourceDocs);
const layoutPaths = docsLayoutPaths(sourceDocs, layout);
const excludedRootEntries = excludeNamesForRootCopy(layout);
await ensureExists(
layoutPaths.readmePath,
`Expected docs README at ${layoutPaths.readmePath}. Check upstream docs layout before preparing.`
);
await fs.rm(docsRoot, { recursive: true, force: true });
await fs.mkdir(docsRoot, { recursive: true });
await copyDirectoryContents(layoutPaths.contentRoot, docsRoot, {
excludeNames: excludedRootEntries,
});
if (await exists(layoutPaths.proDocsRoot)) {
await fs.cp(layoutPaths.proDocsRoot, path.join(docsRoot, "pro"), { recursive: true });
}
if (await exists(layoutPaths.imagesRoot)) {
await fs.cp(layoutPaths.imagesRoot, path.join(docsRoot, "images"), { recursive: true });
}
if (await exists(layoutPaths.assetsRoot)) {
await fs.cp(layoutPaths.assetsRoot, path.join(docsRoot, "assets"), { recursive: true });
}
await rewriteProLinks(path.join(docsRoot, "pro"));
if (layout === "split") {
await rewriteFlattenedOssLinks(docsRoot);
}
await injectProFriendlyNotice(docsRoot);
await fixKnownDocsIssues(docsRoot);
await normalizeCodeFences(docsRoot);
const hasArchive = await archiveLegacyDocs(docsRoot);
await fs.unlink(path.join(docsRoot, "upgrading", "changelog.md")).catch((error) => {
if (error?.code !== "ENOENT") {
throw error;
}
});
const docsHomeSource = await fs.readFile(layoutPaths.readmePath, "utf8");
await fs.writeFile(
path.join(docsRoot, "README.md"),
docsHomeMarkdown(docsHomeSource, { hasArchive }),
"utf8"
);
await convertGitHubAlerts(docsRoot);
await prepareSidebars(siteRoot, hasArchive);
console.log(`Prepared docusaurus docs from ${sourceDocs} (${layout} layout, pro -> /pro)`);
}
async function main() {
if (target && target !== "docusaurus") {
throw new Error("Only docusaurus is supported. Use --target docusaurus.");
}
await ensureExists(
sourceDocs,
`Source docs not found at ${sourceDocs}. Run \`npm run sync:docs\` first.`
);
await prepareDocusaurus();
}
if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}