Skip to content

🎥 Make videos programmatically with React

`docs`: Parallelize twoslash type-checking with pre-warm script

Jonny Burger76b6d29db637
diff --git a/packages/docs/.gitignore b/packages/docs/.gitignore
index 16e618a66a..787b85c5bb 100644
--- a/packages/docs/.gitignore
+++ b/packages/docs/.gitignore
@@ -9,6 +9,9 @@
.cache-loader
static/_raw
+# Twoslash prewarm temp files
+.twoslash-work-*.json
+
# Misc
.DS_Store
.env.local
diff --git a/packages/docs/package.json b/packages/docs/package.json
index 99b4ece6e6..33789cbbb8 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -9,7 +9,7 @@
"formatting": "prettier --experimental-cli src --check",
"docusaurus": "docusaurus",
"start": "bun copy-raw-docs.ts && bun fetch-prompt-submissions.ts && bun update-prompt.ts && cd .. && bun run build && cd docs && docusaurus start --host 0.0.0.0",
- "build-docs": "bun copy-raw-docs.ts && bun fetch-prompt-submissions.ts && DOCUSAURUS_IGNORE_SSG_WARNINGS=true docusaurus build && bun copy-convert.ts && bun count-pages.ts",
+ "build-docs": "bun copy-raw-docs.ts && bun fetch-prompt-submissions.ts && bun prewarm-twoslash.ts && DOCUSAURUS_IGNORE_SSG_WARNINGS=true docusaurus build && bun copy-convert.ts && bun count-pages.ts",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"serve": "docusaurus serve",
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
new file mode 100644
index 0000000000..f96ea9b29a
--- /dev/null
+++ b/packages/docs/prewarm-twoslash.ts
@@ -0,0 +1,308 @@
+import {Glob} from 'bun';
+import {spawn} from 'child_process';
+import {createHash} from 'crypto';
+import {
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ unlinkSync,
+ writeFileSync,
+} from 'fs';
+import {createRequire} from 'module';
+import {cpus} from 'os';
+import {join, resolve} from 'path';
+
+const DOCS_ROOT = resolve(import.meta.dirname);
+const CACHE_ROOT = join(DOCS_ROOT, 'node_modules', '.cache', 'twoslash');
+const WORKER_PATH = join(DOCS_ROOT, 'twoslash-worker.cjs');
+const NUM_WORKERS = cpus().length;
+
+const pluginDir = join(DOCS_ROOT, '..', 'docusaurus-plugin');
+const pluginRequire = createRequire(join(pluginDir, 'package.json'));
+const shikiVersion = pluginRequire('@typescript/twoslash/package.json')
+ .version as string;
+const tsVersion = pluginRequire('typescript/package.json').version as string;
+
+interface TwoslashBlock {
+ code: string;
+ lang: string;
+ cachePath: string;
+ sourceFiles: string[];
+}
+
+function computeCachePath(code: string): string {
+ const shasum = createHash('sha1');
+ const codeSha = shasum
+ .update(`${code}-${shikiVersion}-${tsVersion}`)
+ .digest('hex');
+ return join(CACHE_ROOT, `${codeSha}.json`);
+}
+
+function addIncludes(
+ map: Map<string, string>,
+ name: string,
+ code: string,
+): void {
+ const lines: string[] = [];
+ code.split('\n').forEach((l) => {
+ const trimmed = l.trim();
+ if (trimmed.startsWith('// - ')) {
+ const key = trimmed.split('// - ')[1].split(' ')[0];
+ map.set(name + '-' + key, lines.join('\n'));
+ } else {
+ lines.push(l);
+ }
+ });
+ map.set(name, lines.join('\n'));
+}
+
+function replaceIncludes(map: Map<string, string>, code: string): string {
+ const includesRegex = /\/\/ @include: (.*)$/gm;
+ const toReplace: [number, number, string][] = [];
+
+ let match;
+ while ((match = includesRegex.exec(code)) !== null) {
+ if (match.index === includesRegex.lastIndex) {
+ includesRegex.lastIndex++;
+ }
+
+ const key = match[1];
+ const replaceWith = map.get(key);
+ if (!replaceWith) {
+ return code;
+ }
+
+ toReplace.push([match.index, match[0].length, replaceWith]);
+ }
+
+ let newCode = code.toString();
+ toReplace.reverse().forEach((r) => {
+ newCode =
+ newCode.substring(0, r[0]) + r[2] + newCode.substring(r[0] + r[1]);
+ });
+ return newCode;
+}
+
+function extractTwoslashBlocks(
+ content: string,
+ filePath: string,
+ validCachePaths: Set<string>,
+ cachePathToFiles: Map<string, string[]>,
+): TwoslashBlock[] {
+ const blocks: TwoslashBlock[] = [];
+ const includes = new Map<string, string>();
+
+ const codeBlockRegex = /^```(\S*)(.*?)\n([\s\S]*?)^```$/gm;
+
+ let match;
+ while ((match = codeBlockRegex.exec(content)) !== null) {
+ const lang = match[1];
+ const meta = match[2].trim();
+ const code = match[3];
+
+ if (lang === 'twoslash') {
+ const includeMatch = meta.match(/include\s+(\S+)/);
+ if (includeMatch) {
+ addIncludes(includes, includeMatch[1], code);
+ }
+
+ continue;
+ }
+
+ if (!meta.split(/\s+/).includes('twoslash')) {
+ continue;
+ }
+
+ const importedCode = replaceIncludes(includes, code);
+ const cachePath = computeCachePath(importedCode);
+ validCachePaths.add(cachePath);
+
+ // Track which files reference this cache path
+ const relPath = filePath.replace(DOCS_ROOT + '/', '');
+ if (!cachePathToFiles.has(cachePath)) {
+ cachePathToFiles.set(cachePath, []);
+ }
+ cachePathToFiles.get(cachePath)!.push(relPath);
+
+ if (existsSync(cachePath)) {
+ continue;
+ }
+
+ blocks.push({code: importedCode, lang, cachePath, sourceFiles: []});
+ }
+
+ return blocks;
+}
+
+interface TimingEntry {
+ cachePath: string;
+ ms: number;
+ error?: string;
+}
+
+interface WorkerResult {
+ completed: number;
+ errors: number;
+ timings: TimingEntry[];
+}
+
+function runWorker(
+ workItems: TwoslashBlock[],
+ workerId: number,
+): Promise<WorkerResult> {
+ return new Promise((resolvePromise, reject) => {
+ const tmpFile = join(DOCS_ROOT, `.twoslash-work-${workerId}.json`);
+ writeFileSync(tmpFile, JSON.stringify(workItems));
+
+ const child = spawn('node', [WORKER_PATH, tmpFile], {
+ cwd: DOCS_ROOT,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+
+ let lastReport: WorkerResult = {completed: 0, errors: 0, timings: []};
+
+ child.stdout.on('data', (data: Buffer) => {
+ const lines = data.toString().trim().split('\n');
+ for (const line of lines) {
+ try {
+ lastReport = JSON.parse(line);
+ } catch {
+ // ignore non-JSON output
+ }
+ }
+ });
+
+ child.stderr.on('data', () => {});
+
+ child.on('close', () => {
+ try {
+ unlinkSync(tmpFile);
+ } catch {}
+ resolvePromise(lastReport);
+ });
+
+ child.on('error', (err) => {
+ try {
+ unlinkSync(tmpFile);
+ } catch {}
+ reject(err);
+ });
+ });
+}
+
+async function main() {
+ const startTime = performance.now();
+
+ const glob = new Glob('**/*.{mdx,md}');
+ const dirs = ['docs', 'blog', 'learn', 'new-docs'];
+
+ const allFiles: string[] = [];
+ for (const dir of dirs) {
+ const fullDir = join(DOCS_ROOT, dir);
+ if (!existsSync(fullDir)) continue;
+ for await (const file of glob.scan(fullDir)) {
+ allFiles.push(join(fullDir, file));
+ }
+ }
+
+ const allBlocks: TwoslashBlock[] = [];
+ const validCachePaths = new Set<string>();
+ const cachePathToFiles = new Map<string, string[]>();
+ for (const file of allFiles) {
+ const content = readFileSync(file, 'utf8');
+ allBlocks.push(
+ ...extractTwoslashBlocks(content, file, validCachePaths, cachePathToFiles),
+ );
+ }
+
+ // Delete stale cache entries that no longer correspond to any twoslash block
+ if (existsSync(CACHE_ROOT)) {
+ const cachedFiles = readdirSync(CACHE_ROOT);
+ let staleCount = 0;
+ for (const file of cachedFiles) {
+ const fullPath = join(CACHE_ROOT, file);
+ if (!validCachePaths.has(fullPath)) {
+ unlinkSync(fullPath);
+ staleCount++;
+ }
+ }
+
+ if (staleCount > 0) {
+ console.log(`Deleted ${staleCount} stale cache entries`);
+ }
+ }
+
+ const uniqueBlocks = new Map<string, TwoslashBlock>();
+ for (const block of allBlocks) {
+ if (!uniqueBlocks.has(block.cachePath)) {
+ block.sourceFiles = cachePathToFiles.get(block.cachePath) || [];
+ uniqueBlocks.set(block.cachePath, block);
+ }
+ }
+
+ const uncachedBlocks = [...uniqueBlocks.values()];
+
+ if (uncachedBlocks.length === 0) {
+ const elapsed = ((performance.now() - startTime) / 1000).toFixed(1);
+ console.log(`All twoslash blocks are cached (${elapsed}s to scan)`);
+ return;
+ }
+
+ console.log(
+ `${uncachedBlocks.length} twoslash blocks to type-check (${allFiles.length} files scanned)`,
+ );
+
+ if (!existsSync(CACHE_ROOT)) {
+ mkdirSync(CACHE_ROOT, {recursive: true});
+ }
+
+ const numWorkers = Math.min(NUM_WORKERS, uncachedBlocks.length);
+ console.log(`Launching ${numWorkers} workers...`);
+
+ const chunks: TwoslashBlock[][] = Array.from({length: numWorkers}, () => []);
+ uncachedBlocks.forEach((block, i) => {
+ chunks[i % numWorkers].push(block);
+ });
+
+ const workerPromises = chunks.map((chunk, i) => runWorker(chunk, i));
+
+ const progressInterval = setInterval(() => {
+ try {
+ const cached = readdirSync(CACHE_ROOT).length;
+ const elapsed = ((performance.now() - startTime) / 1000).toFixed(0);
+ console.log(` ${elapsed}s elapsed, ~${cached} cached`);
+ } catch {}
+ }, 15000);
+
+ const results = await Promise.all(workerPromises);
+ clearInterval(progressInterval);
+
+ const totalCompleted = results.reduce((s, r) => s + r.completed, 0);
+ const totalErrors = results.reduce((s, r) => s + r.errors, 0);
+ const totalTime = ((performance.now() - startTime) / 1000).toFixed(1);
+
+ // Collect all timings and sort by duration (slowest first)
+ const allTimings: (TimingEntry & {sourceFiles: string[]})[] = [];
+ for (const result of results) {
+ for (const t of result.timings) {
+ const files = cachePathToFiles.get(t.cachePath) || [];
+ allTimings.push({...t, sourceFiles: files});
+ }
+ }
+
+ allTimings.sort((a, b) => b.ms - a.ms);
+
+ console.log(`\nTwoslash pre-warm: ${totalCompleted} blocks in ${totalTime}s using ${numWorkers} workers (${totalErrors} errors)`);
+ console.log(`\nSlowest snippets:`);
+ for (const t of allTimings.slice(0, 30)) {
+ const files = t.sourceFiles.join(', ');
+ const status = t.error ? ` ERROR: ${t.error}` : '';
+ console.log(` ${t.ms}ms - ${files}${status}`);
+ }
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/packages/docs/twoslash-worker.cjs b/packages/docs/twoslash-worker.cjs
new file mode 100644
index 0000000000..e015ff252c
--- /dev/null
+++ b/packages/docs/twoslash-worker.cjs
@@ -0,0 +1,66 @@
+const {createRequire} = require('module');
+const {writeFileSync, existsSync, mkdirSync, readFileSync} = require('fs');
+const {dirname, join} = require('path');
+
+// Resolve from the docusaurus-plugin which has these as dependencies
+const pluginDir = join(__dirname, '..', 'docusaurus-plugin');
+const pluginRequire = createRequire(join(pluginDir, 'package.json'));
+const {runTwoSlash} = pluginRequire('shiki-twoslash');
+const {ScriptTarget, ModuleKind} = pluginRequire('typescript');
+
+const settings = {
+ defaultCompilerOptions: {
+ types: ['node'],
+ target: ScriptTarget.ESNext,
+ module: ModuleKind.ESNext,
+ },
+};
+
+// Read work items from the file passed as argument
+const workFile = process.argv[2];
+const items = JSON.parse(readFileSync(workFile, 'utf8'));
+
+let completed = 0;
+let errors = 0;
+const timings = [];
+
+for (const item of items) {
+ const start = performance.now();
+ try {
+ const results = runTwoSlash(item.code, item.lang, settings);
+ const dir = dirname(item.cachePath);
+ if (!existsSync(dir)) mkdirSync(dir, {recursive: true});
+ writeFileSync(item.cachePath, JSON.stringify(results), 'utf8');
+ completed++;
+ timings.push({
+ cachePath: item.cachePath,
+ ms: Math.round(performance.now() - start),
+ });
+ } catch (error) {
+ errors++;
+ timings.push({
+ cachePath: item.cachePath,
+ ms: Math.round(performance.now() - start),
+ error: error.message.slice(0, 200),
+ });
+ }
+
+ // Report progress every 10 items
+ if ((completed + errors) % 10 === 0) {
+ process.stdout.write(
+ JSON.stringify({completed, errors, total: items.length, timings}) +
+ '\n',
+ );
+ }
+}
+
+// Final report
+process.stdout.write(
+ JSON.stringify({
+ completed,
+ errors,
+ total: items.length,
+ done: true,
+ timings,
+ }) + '\n',
+);