import ts from 'typescript'; import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync } from 'node:fs'; import { dirname, resolve, posix, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); // TypeScript reports forward-slash paths on every platform; keep ours comparable. const portable = (path) => path.split(sep).join('/'); const sourceRoot = portable(resolve(root, 'resources/scripts')); const outputRoot = portable(resolve(root, 'packages/sdk/types')); const configuration = ts.readConfigFile(resolve(root, 'tsconfig.json'), ts.sys.readFile); const parsed = ts.parseJsonConfigFileContent(configuration.config, ts.sys, root); const options = { ...parsed.options, noEmit: false, declaration: true, emitDeclarationOnly: true, noEmitOnError: true, declarationMap: false, sourceMap: false, rootDir: sourceRoot, outDir: outputRoot, newLine: ts.NewLineKind.LineFeed, }; const program = ts.createProgram({ rootNames: ['sdk/index.ts', 'sdk/api.ts', 'sdk/theme.ts', 'sdk/testing.tsx', 'vite-env.d.ts'].map((path) => resolve(sourceRoot, path)), options, }); const emitted = new Map(); const result = program.emit(undefined, (file, text) => emitted.set(posix.relative(outputRoot, portable(file)), text)); const diagnostics = [...ts.getPreEmitDiagnostics(program), ...result.diagnostics]; if (diagnostics.length) { console.error( ts.formatDiagnosticsWithColorAndContext(diagnostics, { getCanonicalFileName: (file) => file, getCurrentDirectory: () => root, getNewLine: () => '\n', }) ); process.exit(1); } for (const file of program.getSourceFiles()) { if (file.isDeclarationFile && file.fileName.startsWith(sourceRoot + '/')) emitted.set(posix.relative(sourceRoot, file.fileName), file.text); } const files = new Map(); const external = new Set(); function visit(path) { if (files.has(path)) return; const source = emitted.get(path); if (!source) throw new Error(`Missing SDK declaration: ${path}`); files.set(path, ''); const ast = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true); const replacements = []; function collect(node) { const literal = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) ? node.argument.literal : undefined; if (literal && ts.isStringLiteral(literal)) { const specifier = literal.text; if (specifier.startsWith('@/') || specifier.startsWith('@feature/') || specifier.startsWith('.')) { const target = ( specifier.startsWith('@/') ? specifier.slice(2) : specifier.startsWith('@feature/') ? `components/server/features/${specifier.slice(9)}` : posix.normalize(posix.join(posix.dirname(path), specifier)) ).replace(/\.js$/, ''); const declaration = [`${target}.d.ts`, `${target}/index.d.ts`, `${target}.ts`].find((candidate) => emitted.has(candidate) ); if (!declaration) throw new Error(`Unresolved SDK type import ${specifier} in ${path}`); visit(declaration); let portable = posix.relative(posix.dirname(path), declaration.replace(/\.d\.ts$/, '.js')); if (!portable.startsWith('.')) portable = `./${portable}`; replacements.push({ start: literal.getStart(ast), end: literal.end, text: JSON.stringify(portable) }); } else external.add(specifier); } ts.forEachChild(node, collect); } collect(ast); let text = source; for (const replacement of replacements.sort((a, b) => b.start - a.start)) text = text.slice(0, replacement.start) + replacement.text + text.slice(replacement.end); files.set(path, '// Generated by scripts/generate-sdk-types.mjs. Do not edit.\n' + text); } visit('sdk/index.d.ts'); visit('sdk/api.d.ts'); visit('sdk/theme.d.ts'); visit('sdk/testing.d.ts'); files.set( 'testing.d.ts', "// Generated by scripts/generate-sdk-types.mjs. Do not edit.\n/// \nexport * from './sdk/testing.js';\n" ); // A child theme's tests import its parents' built entries, which ship no declarations of their own. files.set( 'theme-entries.d.ts', `// Generated by scripts/generate-sdk-types.mjs. Do not edit. // A theme's built entry, as a child theme's tests import a parent: import aurora from 'aurora/dist/client.js'. declare module '*/dist/client.js' { const theme: import('./sdk/theme.js').ThemeDefinition; export default theme; } ` ); files.set( 'index.d.ts', "// Generated by scripts/generate-sdk-types.mjs. Do not edit.\nexport * from './sdk/index.js';\n" ); files.set('api.d.ts', "// Generated by scripts/generate-sdk-types.mjs. Do not edit.\nexport * from './sdk/api.js';\n"); files.set( 'theme.d.ts', "// Generated by scripts/generate-sdk-types.mjs. Do not edit.\nexport * from './sdk/theme.js';\n" ); const metadata = JSON.parse(readFileSync(resolve(root, 'packages/sdk/package.json'), 'utf8')); for (const specifier of external) { const name = specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]; if (!(name in metadata.peerDependencies) && !(name in (metadata.dependencies ?? {}))) throw new Error(`SDK type dependency ${name} is not declared`); } const existing = readdirSync(outputRoot, { recursive: true }) .map(portable) .filter((path) => path.endsWith('.d.ts')); if (process.argv.includes('--check')) { const stale = existing.filter((path) => !files.has(path)); for (const [path, text] of files) { try { if (readFileSync(resolve(outputRoot, path), 'utf8') !== text) stale.push(path); } catch { stale.push(path); } } if (stale.length) { console.error('SDK declarations are stale. Run npm run sdk:generate.\n' + stale.join('\n')); process.exit(1); } } else { for (const path of existing) if (!files.has(path)) rmSync(resolve(outputRoot, path)); for (const [path, text] of files) { mkdirSync(dirname(resolve(outputRoot, path)), { recursive: true }); writeFileSync(resolve(outputRoot, path), text); } } console.log(`SDK: ${files.size} declaration files; external types: ${[...external].sort().join(', ')}`);