Skip to content

πŸŽ₯ Make videos programmatically with React

Docs: Share Twoslash cache between worktrees (#9183)

Igor Samokhovetsa8c98cc9c221
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index 767b8897fa..5315c4c42c 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -1,16 +1,23 @@
import type {ChildProcessWithoutNullStreams} from 'child_process';
import {spawn} from 'child_process';
-import {createHash} from 'crypto';
import {existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync} from 'fs';
import {createRequire} from 'module';
import {availableParallelism, cpus, totalmem} from 'os';
-import {dirname, join, resolve} from 'path';
+import {basename, dirname, join, resolve} from 'path';
import {createInterface} from 'readline';
import {Glob} from 'bun';
+import {
+ createTwoslashCacheContext,
+ garbageCollectSharedTwoslashCache,
+ getTwoslashCacheKey,
+ getTwoslashLocalCachePath,
+ getTwoslashVersions,
+ publishLocalTwoslashCacheEntry,
+ readTwoslashCacheEntry,
+} from '../docusaurus-plugin/src/twoslash-cache';
import {expandElementSourceReferences} from './plugins/element-source-utils';
const DOCS_ROOT = resolve(import.meta.dirname);
-const CACHE_ROOT = join(DOCS_ROOT, 'node_modules', '.cache', 'twoslash');
const WORKER_SOURCE_PATH = join(DOCS_ROOT, 'twoslash-worker.mjs');
const WORKER_PATH = join(
DOCS_ROOT,
@@ -71,10 +78,11 @@ const RECYCLE_EXIT_CODE = 42;
const pluginDir = join(DOCS_ROOT, '..', 'docusaurus-plugin');
const pluginRequire = createRequire(join(pluginDir, 'package.json'));
-const twoslashVersion = pluginRequire('twoslash/package.json')
- .version as string;
-const shikiVersion = pluginRequire('shiki/package.json').version as string;
-const tsVersion = pluginRequire('typescript/package.json').version as string;
+const cacheContext = createTwoslashCacheContext({
+ docsRoot: DOCS_ROOT,
+ versions: getTwoslashVersions(pluginRequire.resolve),
+});
+const CACHE_ROOT = cacheContext.localRoot;
interface TwoslashBlock {
code: string;
@@ -87,14 +95,23 @@ interface WorkUnit {
items: TwoslashBlock[];
}
-function computeCachePath(code: string): string {
- const shasum = createHash('sha1');
- const codeSha = shasum
- .update(
- `${code}-${twoslashVersion}-${shikiVersion}-${tsVersion}-github-dark`,
- )
- .digest('hex');
- return join(CACHE_ROOT, `${codeSha}.json`);
+function computeCacheLocation(
+ code: string,
+ lang: string,
+): {key: string; path: string} {
+ const key = getTwoslashCacheKey({code, lang, context: cacheContext});
+ return {key, path: getTwoslashLocalCachePath(cacheContext, key)};
+}
+
+function publishLocalCacheEntries(validCachePaths: Set<string>): void {
+ for (const cachePath of validCachePaths) {
+ publishLocalTwoslashCacheEntry({
+ context: cacheContext,
+ key: basename(cachePath, '.json'),
+ });
+ }
+
+ garbageCollectSharedTwoslashCache(cacheContext);
}
function addIncludes(
@@ -199,7 +216,8 @@ function extractTwoslashBlocks(
}
const importedCode = replaceIncludes(includes, code);
- const cachePath = computeCachePath(importedCode);
+ const cacheLocation = computeCacheLocation(importedCode, lang);
+ const cachePath = cacheLocation.path;
validCachePaths.add(cachePath);
// Track which files reference this cache path
@@ -209,7 +227,12 @@ function extractTwoslashBlocks(
}
cachePathToFiles.get(cachePath)!.push(relPath);
- if (existsSync(cachePath)) {
+ if (
+ readTwoslashCacheEntry({
+ context: cacheContext,
+ key: cacheLocation.key,
+ }) !== null
+ ) {
continue;
}
@@ -385,6 +408,7 @@ async function main() {
const uncachedBlocks = [...uniqueBlocks.values()];
if (uncachedBlocks.length === 0) {
+ publishLocalCacheEntries(validCachePaths);
const elapsed = ((performance.now() - startTime) / 1000).toFixed(1);
console.log(`All twoslash blocks are cached (${elapsed}s to scan)`);
return;
@@ -566,10 +590,11 @@ async function main() {
if (unfinished.length > 0) {
const requeue: TwoslashBlock[] = [];
for (const item of unfinished) {
- // A worker can be killed while writing. Only its batched completion
- // message proves the final cache file is complete.
+ // Workers publish cache files using an atomic rename, so an existing
+ // final path is complete even when the completion message was lost.
if (existsSync(item.cachePath)) {
- unlinkSync(item.cachePath);
+ recordResult({cachePath: item.cachePath, ms: 0});
+ continue;
}
const attempt = (attempts.get(item.cachePath) ?? 0) + 1;
@@ -754,6 +779,7 @@ async function main() {
process.exit(1);
}
+ publishLocalCacheEntries(validCachePaths);
process.exit(0);
}
diff --git a/packages/docs/twoslash-worker.mjs b/packages/docs/twoslash-worker.mjs
index c814f2d9cc..6785bbf30e 100644
--- a/packages/docs/twoslash-worker.mjs
+++ b/packages/docs/twoslash-worker.mjs
@@ -1,9 +1,14 @@
-import {existsSync, mkdirSync, writeFileSync} from 'fs';
+import {existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync} from 'fs';
import {dirname} from 'path';
import {createInterface} from 'readline';
import {rendererClassic, transformerTwoslash} from '@shikijs/twoslash';
import {createHighlighter} from 'shiki';
import {createTwoslasher} from 'twoslash';
+import {
+ getTwoslashCompilerOptions,
+ TWOSLASH_EXPLICIT_TRIGGER,
+ TWOSLASH_THEME,
+} from '../docusaurus-plugin/src/twoslash-cache.ts';
// Exit code by which a worker asks to be replaced (memory recycling).
// Keep in sync with prewarm-twoslash.ts.
@@ -19,19 +24,13 @@ const LANGS = ['tsx', 'ts', 'jsx', 'javascript'];
// Create Language Service ONCE per worker β€” reused across all units
const twoslasher = createTwoslasher({
- compilerOptions: {
- types: ['node'],
- target: 99 /* ESNext */,
- module: 99 /* ESNext */,
- jsx: 4 /* ReactJSX */,
- skipLibCheck: true,
- },
+ compilerOptions: getTwoslashCompilerOptions(),
});
const transformer = transformerTwoslash({
twoslasher,
renderer: rendererClassic(),
- explicitTrigger: false,
+ explicitTrigger: TWOSLASH_EXPLICIT_TRIGGER,
});
const send = (message) => {
@@ -39,7 +38,7 @@ const send = (message) => {
};
const highlighter = await createHighlighter({
- themes: ['github-dark'],
+ themes: [TWOSLASH_THEME],
langs: LANGS,
});
@@ -48,13 +47,22 @@ const processItem = (item) => {
try {
const html = highlighter.codeToHtml(item.code, {
lang: item.lang,
- theme: 'github-dark',
+ theme: TWOSLASH_THEME,
transformers: [transformer],
});
const dir = dirname(item.cachePath);
if (!existsSync(dir)) mkdirSync(dir, {recursive: true});
- writeFileSync(item.cachePath, html, 'utf8');
+ const temporaryCachePath = `${item.cachePath}.${process.pid}.tmp`;
+ try {
+ writeFileSync(temporaryCachePath, html, 'utf8');
+ renameSync(temporaryCachePath, item.cachePath);
+ } finally {
+ if (existsSync(temporaryCachePath)) {
+ unlinkSync(temporaryCachePath);
+ }
+ }
+
return {
cachePath: item.cachePath,
ms: Math.round(performance.now() - start),
diff --git a/packages/docusaurus-plugin/package.json b/packages/docusaurus-plugin/package.json
index 7a9e55ee40..81ae41e132 100644
--- a/packages/docusaurus-plugin/package.json
+++ b/packages/docusaurus-plugin/package.json
@@ -5,7 +5,8 @@
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint src",
- "make": "tsgo -d"
+ "make": "tsgo -d",
+ "test": "bun test src"
},
"author": "Jonny Burger <[email protected]>",
"license": "UNLICENSED",
diff --git a/packages/docusaurus-plugin/src/caching.ts b/packages/docusaurus-plugin/src/caching.ts
index 390ab01f00..4f811a2d89 100644
--- a/packages/docusaurus-plugin/src/caching.ts
+++ b/packages/docusaurus-plugin/src/caching.ts
@@ -1,30 +1,48 @@
/* eslint-disable no-console */
+import {createRequire} from 'module';
+import {resolve} from 'path';
import {rendererClassic, transformerTwoslash} from '@shikijs/twoslash';
import type {HighlighterGeneric} from 'shiki/core';
import {createTwoslasher} from 'twoslash';
+import {
+ createTwoslashCacheContext,
+ getTwoslashCacheKey,
+ getTwoslashCompilerOptions,
+ getTwoslashVersions,
+ readTwoslashCacheEntry,
+ TWOSLASH_EXPLICIT_TRIGGER,
+ TWOSLASH_THEME,
+ writeTwoslashCacheEntry,
+} from './twoslash-cache';
let cachedTwoslasher: ReturnType<typeof createTwoslasher> | null = null;
+let cacheContext: ReturnType<typeof createTwoslashCacheContext> | null = null;
function getTwoslasher() {
if (!cachedTwoslasher) {
cachedTwoslasher = createTwoslasher({
- compilerOptions: {
- types: ['node'],
- target: 99 /* ESNext */,
- module: 99 /* ESNext */,
- jsx: 4 /* ReactJSX */,
- skipLibCheck: true,
- },
+ compilerOptions: getTwoslashCompilerOptions(),
});
}
return cachedTwoslasher;
}
+const getCacheContext = () => {
+ if (!cacheContext) {
+ const packageRequire = createRequire(__filename);
+ cacheContext = createTwoslashCacheContext({
+ docsRoot: resolve(process.cwd()),
+ versions: getTwoslashVersions(packageRequire.resolve),
+ });
+ }
+
+ return cacheContext;
+};
+
/**
- * Keeps a cache of the HTML responses in node_modules/.cache/twoslash
- * which should keep CI times down β€” but also during dev time.
- * Returns an HTML string (final rendered output).
+ * Keeps a local cache of the final HTML and shares immutable entries with the
+ * other worktrees belonging to the same Git repository.
*/
export const cachedTwoslashCall = (
code: string,
@@ -32,68 +50,30 @@ export const cachedTwoslashCall = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
highlighter: HighlighterGeneric<any, any>,
): string => {
- const {createHash} = require('crypto');
- const {readFileSync, existsSync, mkdirSync, writeFileSync} = require('fs');
- const {join} = require('path');
-
- const {createRequire} = require('module');
- const _require = createRequire(__filename);
- const readPkgVersion = (pkg: string) => {
- const entryPath = _require.resolve(pkg);
- let dir = require('path').dirname(entryPath);
- while (dir !== '/') {
- const p = join(dir, 'package.json');
- if (existsSync(p)) {
- return JSON.parse(readFileSync(p, 'utf8')).version as string;
- }
-
- dir = require('path').dirname(dir);
+ const context = getCacheContext();
+ const key = getTwoslashCacheKey({code, lang, context});
+ const cached = readTwoslashCacheEntry({context, key});
+ if (cached !== null) {
+ if (process.env.debug) {
+ console.log(`Using cached Twoslash result ${key}`);
}
- return 'unknown';
- };
-
- const twoslashVersion = readPkgVersion('twoslash');
- const shikiVersion = readPkgVersion('shiki');
- const tsVersion = readPkgVersion('typescript');
-
- const shasum = createHash('sha1');
- const codeSha = shasum
- .update(
- `${code}-${twoslashVersion}-${shikiVersion}-${tsVersion}-github-dark`,
- )
- .digest('hex');
-
- const getNmCache = () => {
- const p = join(process.cwd(), 'node_modules', '.cache', 'twoslash');
- return p;
- };
-
- const cacheRoot = getNmCache();
- const cachePath = join(cacheRoot, `${codeSha}.json`);
-
- if (existsSync(cachePath)) {
- if (process.env.debug)
- console.log(`Using cached twoslash results from ${cachePath}`);
-
- return readFileSync(cachePath, 'utf8');
+ return cached;
}
const twoslasher = getTwoslasher();
-
const html = highlighter.codeToHtml(code, {
lang,
- theme: 'github-dark',
+ theme: TWOSLASH_THEME,
transformers: [
transformerTwoslash({
twoslasher,
renderer: rendererClassic(),
- explicitTrigger: false,
+ explicitTrigger: TWOSLASH_EXPLICIT_TRIGGER,
}),
],
});
- if (!existsSync(cacheRoot)) mkdirSync(cacheRoot, {recursive: true});
- writeFileSync(cachePath, html, 'utf8');
+ writeTwoslashCacheEntry({context, key, html});
return html;
};
diff --git a/packages/docusaurus-plugin/src/twoslash-cache.test.ts b/packages/docusaurus-plugin/src/twoslash-cache.test.ts
new file mode 100644
index 0000000000..5e60f5498d
--- /dev/null
+++ b/packages/docusaurus-plugin/src/twoslash-cache.test.ts
@@ -0,0 +1,317 @@
+import {afterEach, describe, expect, test} from 'bun:test';
+import {execFileSync} from 'child_process';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ utimesSync,
+ writeFileSync,
+} from 'fs';
+import {tmpdir} from 'os';
+import {join} from 'path';
+import {pathToFileURL} from 'url';
+import {
+ garbageCollectSharedTwoslashCache,
+ getSharedTwoslashCacheRoot,
+ getTwoslashCacheKey,
+ getTwoslashEnvironmentHash,
+ readTwoslashCacheEntry,
+ type TwoslashCacheContext,
+ writeTwoslashCacheEntry,
+} from './twoslash-cache';
+
+const temporaryDirectories: string[] = [];
+
+const makeContext = (
+ root: string,
+ localName: string,
+ environmentHash = 'environment-a',
+): TwoslashCacheContext => ({
+ localRoot: join(root, localName),
+ sharedRoot: join(root, 'shared'),
+ environmentHash,
+ versions: {
+ twoslash: '1.0.0',
+ shiki: '1.0.0',
+ typescript: '1.0.0',
+ shikiTwoslash: '1.0.0',
+ },
+});
+
+const makeTemporaryDirectory = () => {
+ const directory = mkdtempSync(join(tmpdir(), 'remotion-twoslash-cache-'));
+ temporaryDirectories.push(directory);
+ return directory;
+};
+
+const makeEnvironmentRepository = (
+ root: string,
+ name: string,
+ declaration: string,
+): string => {
+ const repository = join(root, name);
+ const docsRoot = join(repository, 'packages', 'docs');
+ const packageRoot = join(repository, 'packages', 'example');
+ mkdirSync(docsRoot, {recursive: true});
+ mkdirSync(join(packageRoot, 'dist'), {recursive: true});
+ writeFileSync(join(repository, 'bun.lock'), 'lockfile', 'utf8');
+ writeFileSync(join(repository, 'package.json'), '{}', 'utf8');
+ writeFileSync(join(docsRoot, 'package.json'), '{}', 'utf8');
+ writeFileSync(join(packageRoot, 'package.json'), '{}', 'utf8');
+ writeFileSync(join(packageRoot, 'dist', 'index.d.ts'), declaration, 'utf8');
+ execFileSync('git', ['init', '--quiet', repository]);
+ execFileSync('git', [
+ '-C',
+ repository,
+ 'add',
+ 'bun.lock',
+ 'package.json',
+ 'packages/docs/package.json',
+ 'packages/example/package.json',
+ ]);
+ return docsRoot;
+};
+
+afterEach(() => {
+ for (const directory of temporaryDirectories.splice(0)) {
+ rmSync(directory, {recursive: true, force: true});
+ }
+
+ delete process.env.TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS;
+ delete process.env.TWOSLASH_SHARED_CACHE_MAX_AGE_MS;
+});
+
+describe('Twoslash cache keys', () => {
+ test('fingerprint generated workspace declarations', () => {
+ const root = makeTemporaryDirectory();
+ const first = makeEnvironmentRepository(
+ root,
+ 'first',
+ 'export declare const value: string;',
+ );
+ const second = makeEnvironmentRepository(
+ root,
+ 'second',
+ 'export declare const value: number;',
+ );
+ const sameAsFirst = makeEnvironmentRepository(
+ root,
+ 'third',
+ 'export declare const value: string;',
+ );
+
+ expect(getTwoslashEnvironmentHash(second)).not.toBe(
+ getTwoslashEnvironmentHash(first),
+ );
+ expect(getTwoslashEnvironmentHash(sameAsFirst)).toBe(
+ getTwoslashEnvironmentHash(first),
+ );
+ });
+
+ test('include the language and type environment', () => {
+ const root = makeTemporaryDirectory();
+ const context = makeContext(root, 'local-a');
+ const base = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context,
+ });
+ const differentLanguage = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'tsx',
+ context,
+ });
+ const differentEnvironment = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context: makeContext(root, 'local-b', 'environment-b'),
+ });
+ const differentVersions = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context: {
+ ...context,
+ versions: {...context.versions, shikiTwoslash: '2.0.0'},
+ },
+ });
+
+ expect(differentLanguage).not.toBe(base);
+ expect(differentEnvironment).not.toBe(base);
+ expect(differentVersions).not.toBe(base);
+ });
+});
+
+describe('shared Twoslash cache', () => {
+ test('uses the same root for all Git worktrees', () => {
+ const root = makeTemporaryDirectory();
+ const repository = join(root, 'repository');
+ const worktree = join(root, 'worktree');
+ mkdirSync(repository);
+ execFileSync('git', ['init', '--quiet', repository]);
+ execFileSync('git', [
+ '-C',
+ repository,
+ 'config',
+ 'user.email',
+ ]);
+ execFileSync('git', ['-C', repository, 'config', 'user.name', 'Test']);
+ writeFileSync(join(repository, 'file'), 'content', 'utf8');
+ execFileSync('git', ['-C', repository, 'add', 'file']);
+ execFileSync('git', [
+ '-C',
+ repository,
+ 'commit',
+ '--quiet',
+ '-m',
+ 'Initial',
+ ]);
+ execFileSync('git', [
+ '-C',
+ repository,
+ 'worktree',
+ 'add',
+ '--quiet',
+ '--detach',
+ worktree,
+ ]);
+
+ expect(getSharedTwoslashCacheRoot(worktree)).toBe(
+ getSharedTwoslashCacheRoot(repository),
+ );
+ });
+
+ test('hydrates another worktree and does not replace immutable entries', () => {
+ const root = makeTemporaryDirectory();
+ const first = makeContext(root, 'local-a');
+ const second = makeContext(root, 'local-b');
+ const third = makeContext(root, 'local-c');
+ const key = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context: first,
+ });
+
+ writeTwoslashCacheEntry({context: first, key, html: '<pre>first</pre>'});
+ expect(readTwoslashCacheEntry({context: second, key})).toBe(
+ '<pre>first</pre>',
+ );
+
+ writeTwoslashCacheEntry({context: second, key, html: '<pre>second</pre>'});
+ expect(readTwoslashCacheEntry({context: third, key})).toBe(
+ '<pre>first</pre>',
+ );
+ });
+
+ test('publishes one complete entry when processes race', async () => {
+ const root = makeTemporaryDirectory();
+ const context = makeContext(root, 'local-parent');
+ const key = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context,
+ });
+ const candidates = Array.from(
+ {length: 6},
+ (_, index) => `<pre>worker-${index}</pre>`,
+ );
+ const moduleUrl = pathToFileURL(join(__dirname, 'twoslash-cache.ts')).href;
+ const script = `
+ import {writeTwoslashCacheEntry} from ${JSON.stringify(moduleUrl)};
+ const context = JSON.parse(process.env.TWOSLASH_TEST_CONTEXT);
+ writeTwoslashCacheEntry({
+ context,
+ key: process.env.TWOSLASH_TEST_KEY,
+ html: process.env.TWOSLASH_TEST_HTML,
+ });
+ `;
+ const processes = candidates.map((html, index) =>
+ Bun.spawn({
+ cmd: [process.execPath, '-e', script],
+ env: {
+ ...process.env,
+ TWOSLASH_TEST_CONTEXT: JSON.stringify({
+ ...context,
+ localRoot: join(root, `local-worker-${index}`),
+ }),
+ TWOSLASH_TEST_KEY: key,
+ TWOSLASH_TEST_HTML: html,
+ },
+ stderr: 'pipe',
+ stdout: 'ignore',
+ }),
+ );
+ const exitCodes = await Promise.all(
+ processes.map((process) => process.exited),
+ );
+
+ expect(exitCodes).toEqual(candidates.map(() => 0));
+ const cached = readTwoslashCacheEntry({
+ context: makeContext(root, 'local-reader'),
+ key,
+ });
+ expect(cached).not.toBeNull();
+ if (cached === null) {
+ throw new Error('Expected a shared cache entry');
+ }
+
+ expect(candidates).toContain(cached);
+ expect(
+ readdirSync(context.sharedRoot!).filter(
+ (file) => file.endsWith('.tmp') || file.endsWith('.lock'),
+ ),
+ ).toEqual([]);
+ });
+
+ test('rejects and repairs corrupt shared entries', () => {
+ const root = makeTemporaryDirectory();
+ const first = makeContext(root, 'local-a');
+ const second = makeContext(root, 'local-b');
+ const third = makeContext(root, 'local-c');
+ const key = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context: first,
+ });
+ const sharedPath = join(first.sharedRoot!, `${key}.json`);
+
+ writeTwoslashCacheEntry({context: first, key, html: '<pre>first</pre>'});
+ writeFileSync(sharedPath, 'corrupt', 'utf8');
+ expect(readTwoslashCacheEntry({context: second, key})).toBeNull();
+
+ writeTwoslashCacheEntry({
+ context: second,
+ key,
+ html: '<pre>repaired</pre>',
+ });
+ expect(readTwoslashCacheEntry({context: third, key})).toBe(
+ '<pre>repaired</pre>',
+ );
+ });
+
+ test('garbage-collects old shared entries without deleting local entries', () => {
+ const root = makeTemporaryDirectory();
+ const context = makeContext(root, 'local-a');
+ const key = getTwoslashCacheKey({
+ code: 'const value = 1;',
+ lang: 'ts',
+ context,
+ });
+ const sharedPath = join(context.sharedRoot!, `${key}.json`);
+ const localPath = join(context.localRoot, `${key}.json`);
+
+ writeTwoslashCacheEntry({context, key, html: '<pre>cached</pre>'});
+ const old = new Date(Date.now() - 10_000);
+ utimesSync(sharedPath, old, old);
+ process.env.TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS = '0';
+ process.env.TWOSLASH_SHARED_CACHE_MAX_AGE_MS = '1';
+
+ garbageCollectSharedTwoslashCache(context);
+
+ expect(existsSync(sharedPath)).toBeFalse();
+ expect(readFileSync(localPath, 'utf8')).toBe('<pre>cached</pre>');
+ });
+});
diff --git a/packages/docusaurus-plugin/src/twoslash-cache.ts b/packages/docusaurus-plugin/src/twoslash-cache.ts
new file mode 100644
index 0000000000..27225aec47
--- /dev/null
+++ b/packages/docusaurus-plugin/src/twoslash-cache.ts
@@ -0,0 +1,637 @@
+import {execFileSync} from 'child_process';
+import {createHash, randomBytes} from 'crypto';
+import {
+ existsSync,
+ linkSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ utimesSync,
+ writeFileSync,
+} from 'fs';
+import {dirname, join, relative, resolve} from 'path';
+
+export const TWOSLASH_CACHE_SCHEMA_VERSION = 2;
+export const TWOSLASH_THEME = 'github-dark';
+export const TWOSLASH_EXPLICIT_TRIGGER = false;
+export const TWOSLASH_RENDERER = 'classic';
+
+const SHARED_CACHE_FILE_VERSION = 1;
+const DAY_MS = 24 * 60 * 60 * 1000;
+const DEFAULT_MAX_CACHE_AGE_MS = 90 * DAY_MS;
+const DEFAULT_MAX_CACHE_BYTES = 512 * 1024 * 1024;
+const DEFAULT_GC_INTERVAL_MS = DAY_MS;
+
+export const getTwoslashCompilerOptions = () => ({
+ types: ['node'],
+ target: 99 /* ESNext */,
+ module: 99 /* ESNext */,
+ jsx: 4 /* ReactJSX */,
+ skipLibCheck: true,
+});
+
+export interface TwoslashVersions {
+ twoslash: string;
+ shiki: string;
+ typescript: string;
+ shikiTwoslash: string;
+}
+
+export interface TwoslashCacheContext {
+ localRoot: string;
+ sharedRoot: string | null;
+ environmentHash: string;
+ versions: TwoslashVersions;
+}
+
+interface SharedCacheHeader {
+ fileVersion: number;
+ key: string;
+ contentHash: string;
+}
+
+const environmentHashCache = new Map<string, string>();
+
+const isNodeError = (error: unknown, code: string): boolean => {
+ return (
+ error instanceof Error &&
+ 'code' in error &&
+ (error as NodeJS.ErrnoException).code === code
+ );
+};
+
+const safeUnlink = (path: string): void => {
+ try {
+ unlinkSync(path);
+ } catch (error) {
+ if (!isNodeError(error, 'ENOENT')) {
+ throw error;
+ }
+ }
+};
+
+const getTemporaryPath = (path: string): string => {
+ return `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
+};
+
+const writeFileAtomically = (path: string, contents: string): void => {
+ mkdirSync(dirname(path), {recursive: true});
+ const temporaryPath = getTemporaryPath(path);
+ writeFileSync(temporaryPath, contents, {encoding: 'utf8', flag: 'wx'});
+
+ try {
+ renameSync(temporaryPath, path);
+ } catch (error) {
+ // Another process may have published the same deterministic entry.
+ if (!existsSync(path)) {
+ throw error;
+ }
+ } finally {
+ if (existsSync(temporaryPath)) {
+ safeUnlink(temporaryPath);
+ }
+ }
+};
+
+const findPackageVersion = (
+ packageName: string,
+ resolvePackage: (packageName: string) => string,
+): string => {
+ let currentDir = dirname(resolvePackage(packageName));
+
+ while (true) {
+ const packageJsonPath = join(currentDir, 'package.json');
+ if (existsSync(packageJsonPath)) {
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8')) as {
+ version?: string;
+ };
+ if (packageJson.version) {
+ return packageJson.version;
+ }
+ }
+
+ const parent = dirname(currentDir);
+ if (parent === currentDir) {
+ return 'unknown';
+ }
+
+ currentDir = parent;
+ }
+};
+
+export const getTwoslashVersions = (
+ resolvePackage: (packageName: string) => string,
+): TwoslashVersions => {
+ return {
+ twoslash: findPackageVersion('twoslash', resolvePackage),
+ shiki: findPackageVersion('shiki', resolvePackage),
+ typescript: findPackageVersion('typescript', resolvePackage),
+ shikiTwoslash: findPackageVersion('@shikijs/twoslash', resolvePackage),
+ };
+};
+
+const getGitPath = (cwd: string, argument: string): string | null => {
+ try {
+ return execFileSync(
+ 'git',
+ ['-C', cwd, 'rev-parse', '--path-format=absolute', argument],
+ {encoding: 'utf8'},
+ ).trim();
+ } catch {
+ return null;
+ }
+};
+
+export const getSharedTwoslashCacheRoot = (cwd: string): string | null => {
+ if (process.env.TWOSLASH_SHARED_CACHE_DIR) {
+ return resolve(process.env.TWOSLASH_SHARED_CACHE_DIR);
+ }
+
+ const gitCommonDir = getGitPath(cwd, '--git-common-dir');
+ if (!gitCommonDir) {
+ return null;
+ }
+
+ return join(
+ gitCommonDir,
+ 'remotion-cache',
+ 'twoslash',
+ `v${TWOSLASH_CACHE_SCHEMA_VERSION}`,
+ );
+};
+
+const getRepositoryRoot = (docsRoot: string): string => {
+ return (
+ getGitPath(docsRoot, '--show-toplevel') ?? resolve(docsRoot, '..', '..')
+ );
+};
+
+const getTrackedEnvironmentFiles = (repositoryRoot: string): string[] => {
+ try {
+ const output = execFileSync(
+ 'git',
+ [
+ '-C',
+ repositoryRoot,
+ 'ls-files',
+ '-z',
+ '--',
+ 'bun.lock',
+ 'package.json',
+ ':(glob)packages/**/package.json',
+ ':(glob)packages/**/*.d.ts',
+ ':(glob)packages/**/*.d.mts',
+ ':(glob)packages/**/*.d.cts',
+ ],
+ {encoding: 'buffer', maxBuffer: 10 * 1024 * 1024},
+ );
+
+ return output.toString('utf8').split('\0').filter(Boolean).sort();
+ } catch {
+ return ['bun.lock', 'package.json'];
+ }
+};
+
+const collectDeclarationFiles = (directory: string, output: string[]): void => {
+ if (!existsSync(directory)) {
+ return;
+ }
+
+ for (const entry of readdirSync(directory, {withFileTypes: true})) {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ collectDeclarationFiles(path, output);
+ } else if (/\.d\.(?:ts|mts|cts)$/.test(entry.name)) {
+ output.push(path);
+ }
+ }
+};
+
+const hashFile = (
+ hash: ReturnType<typeof createHash>,
+ repositoryRoot: string,
+ path: string,
+): void => {
+ const relativePath = relative(repositoryRoot, path);
+ hash.update(relativePath);
+ hash.update('\0');
+ if (existsSync(path)) {
+ hash.update(readFileSync(path, 'utf8'));
+ } else {
+ hash.update('<missing>');
+ }
+
+ hash.update('\0');
+};
+
+export const getTwoslashEnvironmentHash = (docsRoot: string): string => {
+ const repositoryRoot = getRepositoryRoot(docsRoot);
+ const cached = environmentHashCache.get(repositoryRoot);
+ if (cached) {
+ return cached;
+ }
+
+ const hash = createHash('sha256');
+ const trackedFiles = getTrackedEnvironmentFiles(repositoryRoot);
+ const packageDirectories = new Set<string>();
+
+ for (const relativePath of trackedFiles) {
+ const absolutePath = join(repositoryRoot, relativePath);
+ hashFile(hash, repositoryRoot, absolutePath);
+ if (relativePath.endsWith('package.json')) {
+ packageDirectories.add(dirname(absolutePath));
+ }
+ }
+
+ const declarationFiles: string[] = [];
+ for (const packageDirectory of packageDirectories) {
+ collectDeclarationFiles(join(packageDirectory, 'dist'), declarationFiles);
+ }
+
+ for (const declarationFile of declarationFiles.sort()) {
+ hashFile(hash, repositoryRoot, declarationFile);
+ }
+
+ const digest = hash.digest('hex');
+ environmentHashCache.set(repositoryRoot, digest);
+ return digest;
+};
+
+export const createTwoslashCacheContext = ({
+ docsRoot,
+ versions,
+}: {
+ docsRoot: string;
+ versions: TwoslashVersions;
+}): TwoslashCacheContext => {
+ return {
+ localRoot: join(docsRoot, 'node_modules', '.cache', 'twoslash'),
+ sharedRoot: getSharedTwoslashCacheRoot(docsRoot),
+ environmentHash: getTwoslashEnvironmentHash(docsRoot),
+ versions,
+ };
+};
+
+export const getTwoslashCacheKey = ({
+ code,
+ lang,
+ context,
+}: {
+ code: string;
+ lang: string;
+ context: TwoslashCacheContext;
+}): string => {
+ return createHash('sha256')
+ .update(
+ JSON.stringify({
+ schemaVersion: TWOSLASH_CACHE_SCHEMA_VERSION,
+ code,
+ lang,
+ theme: TWOSLASH_THEME,
+ compilerOptions: getTwoslashCompilerOptions(),
+ transformer: {
+ renderer: TWOSLASH_RENDERER,
+ explicitTrigger: TWOSLASH_EXPLICIT_TRIGGER,
+ },
+ versions: context.versions,
+ environmentHash: context.environmentHash,
+ }),
+ )
+ .digest('hex');
+};
+
+export const getTwoslashLocalCachePath = (
+ context: TwoslashCacheContext,
+ key: string,
+): string => {
+ return join(context.localRoot, `${key}.json`);
+};
+
+const getSharedCachePath = (
+ context: TwoslashCacheContext,
+ key: string,
+): string | null => {
+ return context.sharedRoot ? join(context.sharedRoot, `${key}.json`) : null;
+};
+
+const serializeSharedCacheEntry = (key: string, html: string): string => {
+ const header: SharedCacheHeader = {
+ fileVersion: SHARED_CACHE_FILE_VERSION,
+ key,
+ contentHash: createHash('sha256').update(html).digest('hex'),
+ };
+ return `${JSON.stringify(header)}\n${html}`;
+};
+
+const deserializeSharedCacheEntry = (
+ contents: string,
+ expectedKey: string,
+): string | null => {
+ const headerEnd = contents.indexOf('\n');
+ if (headerEnd === -1) {
+ return null;
+ }
+
+ try {
+ const header = JSON.parse(
+ contents.slice(0, headerEnd),
+ ) as SharedCacheHeader;
+ const html = contents.slice(headerEnd + 1);
+ if (
+ header.fileVersion !== SHARED_CACHE_FILE_VERSION ||
+ header.key !== expectedKey ||
+ header.contentHash !== createHash('sha256').update(html).digest('hex')
+ ) {
+ return null;
+ }
+
+ return html;
+ } catch {
+ return null;
+ }
+};
+
+const readSharedCacheEntry = (path: string, key: string): string | null => {
+ try {
+ return deserializeSharedCacheEntry(readFileSync(path, 'utf8'), key);
+ } catch {
+ return null;
+ }
+};
+
+const touchSharedCacheEntry = (path: string): void => {
+ try {
+ const stats = statSync(path);
+ if (Date.now() - stats.mtimeMs > DAY_MS) {
+ const now = new Date();
+ utimesSync(path, now, now);
+ }
+ } catch {
+ // Cache maintenance must not fail a docs build.
+ }
+};
+
+const publishSharedCacheEntry = (
+ path: string,
+ key: string,
+ html: string,
+): void => {
+ const existing = readSharedCacheEntry(path, key);
+ if (existing !== null) {
+ touchSharedCacheEntry(path);
+ return;
+ }
+
+ mkdirSync(dirname(path), {recursive: true});
+ const temporaryPath = getTemporaryPath(path);
+ writeFileSync(temporaryPath, serializeSharedCacheEntry(key, html), {
+ encoding: 'utf8',
+ flag: 'wx',
+ });
+
+ try {
+ if (!existsSync(path)) {
+ try {
+ // A hard link installs the immutable object without replacing a winner.
+ linkSync(temporaryPath, path);
+ return;
+ } catch (error) {
+ if (
+ !isNodeError(error, 'EEXIST') &&
+ readSharedCacheEntry(path, key) !== null
+ ) {
+ return;
+ }
+ }
+ }
+
+ if (readSharedCacheEntry(path, key) !== null) {
+ return;
+ }
+
+ // Corrupt entries and filesystems without hard links use a per-key lock
+ // before atomically installing the replacement.
+ const lockPath = `${path}.lock`;
+ try {
+ mkdirSync(lockPath);
+ } catch {
+ return;
+ }
+
+ try {
+ if (readSharedCacheEntry(path, key) === null) {
+ if (existsSync(path)) {
+ safeUnlink(path);
+ }
+
+ renameSync(temporaryPath, path);
+ }
+ } finally {
+ rmSync(lockPath, {recursive: true, force: true});
+ }
+ } finally {
+ if (existsSync(temporaryPath)) {
+ safeUnlink(temporaryPath);
+ }
+ }
+};
+
+export const readTwoslashCacheEntry = ({
+ context,
+ key,
+}: {
+ context: TwoslashCacheContext;
+ key: string;
+}): string | null => {
+ const localPath = getTwoslashLocalCachePath(context, key);
+ try {
+ const localContents = readFileSync(localPath, 'utf8');
+ if (localContents.length > 0) {
+ return localContents;
+ }
+ } catch {
+ // Fall through to the shared cache.
+ }
+
+ const sharedPath = getSharedCachePath(context, key);
+ if (!sharedPath) {
+ return null;
+ }
+
+ const html = readSharedCacheEntry(sharedPath, key);
+ if (html === null) {
+ return null;
+ }
+
+ touchSharedCacheEntry(sharedPath);
+ writeFileAtomically(localPath, html);
+ return html;
+};
+
+export const writeTwoslashCacheEntry = ({
+ context,
+ key,
+ html,
+}: {
+ context: TwoslashCacheContext;
+ key: string;
+ html: string;
+}): void => {
+ writeFileAtomically(getTwoslashLocalCachePath(context, key), html);
+ const sharedPath = getSharedCachePath(context, key);
+ if (!sharedPath) {
+ return;
+ }
+
+ try {
+ publishSharedCacheEntry(sharedPath, key, html);
+ } catch {
+ // The local cache is sufficient for this build. A later prewarm can retry
+ // publishing to the shared cache.
+ }
+};
+
+export const publishLocalTwoslashCacheEntry = ({
+ context,
+ key,
+}: {
+ context: TwoslashCacheContext;
+ key: string;
+}): void => {
+ const sharedPath = getSharedCachePath(context, key);
+ if (!sharedPath) {
+ return;
+ }
+
+ try {
+ const html = readFileSync(getTwoslashLocalCachePath(context, key), 'utf8');
+ if (html.length > 0) {
+ publishSharedCacheEntry(sharedPath, key, html);
+ }
+ } catch {
+ // Publishing is only an optimization.
+ }
+};
+
+const readEnvNumber = (name: string, fallback: number): number => {
+ const value = process.env[name];
+ if (!value) {
+ return fallback;
+ }
+
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
+};
+
+export const garbageCollectSharedTwoslashCache = (
+ context: TwoslashCacheContext,
+): void => {
+ if (!context.sharedRoot || !existsSync(context.sharedRoot)) {
+ return;
+ }
+
+ const now = Date.now();
+ const gcIntervalMs = readEnvNumber(
+ 'TWOSLASH_SHARED_CACHE_GC_INTERVAL_MS',
+ DEFAULT_GC_INTERVAL_MS,
+ );
+ const stampPath = join(context.sharedRoot, '.gc-stamp');
+ try {
+ if (now - statSync(stampPath).mtimeMs < gcIntervalMs) {
+ return;
+ }
+ } catch {
+ // No previous GC stamp.
+ }
+
+ const lockPath = join(context.sharedRoot, '.gc-lock');
+ try {
+ mkdirSync(lockPath);
+ } catch {
+ try {
+ if (now - statSync(lockPath).mtimeMs <= DAY_MS) {
+ return;
+ }
+
+ rmSync(lockPath, {recursive: true, force: true});
+ mkdirSync(lockPath);
+ } catch {
+ return;
+ }
+ }
+
+ try {
+ const maxAgeMs = readEnvNumber(
+ 'TWOSLASH_SHARED_CACHE_MAX_AGE_MS',
+ DEFAULT_MAX_CACHE_AGE_MS,
+ );
+ const maxBytes = readEnvNumber(
+ 'TWOSLASH_SHARED_CACHE_MAX_BYTES',
+ DEFAULT_MAX_CACHE_BYTES,
+ );
+ const entries: {path: string; size: number; mtimeMs: number}[] = [];
+
+ for (const file of readdirSync(context.sharedRoot)) {
+ const path = join(context.sharedRoot, file);
+ if (file.endsWith('.tmp') || file.endsWith('.lock')) {
+ try {
+ if (now - statSync(path).mtimeMs > DAY_MS) {
+ if (file.endsWith('.lock')) {
+ rmSync(path, {recursive: true, force: true});
+ } else {
+ safeUnlink(path);
+ }
+ }
+ } catch {
+ // The file disappeared concurrently.
+ }
+
+ continue;
+ }
+
+ if (!file.endsWith('.json')) {
+ continue;
+ }
+
+ try {
+ const stats = statSync(path);
+ const key = file.slice(0, -'.json'.length);
+ if (
+ now - stats.mtimeMs > maxAgeMs ||
+ readSharedCacheEntry(path, key) === null
+ ) {
+ safeUnlink(path);
+ continue;
+ }
+
+ entries.push({path, size: stats.size, mtimeMs: stats.mtimeMs});
+ } catch {
+ // The entry disappeared concurrently.
+ }
+ }
+
+ let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
+ for (const entry of entries.sort((a, b) => a.mtimeMs - b.mtimeMs)) {
+ if (totalBytes <= maxBytes) {
+ break;
+ }
+
+ try {
+ safeUnlink(entry.path);
+ totalBytes -= entry.size;
+ } catch {
+ // Keep going if another process is using or removed the entry.
+ }
+ }
+
+ writeFileAtomically(stampPath, String(now));
+ } catch {
+ // Shared cache maintenance must never fail prewarming.
+ } finally {
+ rmSync(lockPath, {recursive: true, force: true});
+ }
+};