#!/usr/bin/env node // Usage: node scripts/public-api/api.mjs update|check // update: writes api.txt beside the package.json of every published package. // check: regenerates the lists and fails when a committed api.txt differs. // Both read the built declarations, so `pnpm build` must have run. import { fork } from 'node:child_process'; import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { availableParallelism } from 'node:os'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { listDifferences } from './differences.mjs'; import { compareCodeUnits } from './flatten.mjs'; import { entryPointsOf, MODEL_FOLDER } from './read-api.mjs'; const here = dirname(fileURLToPath(import.meta.url)); export const LIST_FILE = 'api.txt'; const HEADER = '# Generated by `pnpm api:update` from the built declarations. Do not edit by hand.'; // The folders under packages/9-public/@prisma with a package.json, and those without one that // still hold an api.txt. export function publishedPackageDirs(root) { const scope = join(root, 'packages', '9-public', '@prisma'); const folders = readdirSync(scope) .sort(compareCodeUnits) .map((name) => join(scope, name)); return { packageDirs: folders.filter((folder) => existsSync(join(folder, 'package.json'))), leftovers: folders.filter( (folder) => !existsSync(join(folder, 'package.json')) && existsSync(join(folder, LIST_FILE)), ), }; } export function apiText(lines) { return `${[HEADER, ...lines].join('\n')}\n`; } export class WorkerError extends Error {} export function workerStopped(packageDir, root, code, signal) { const how = signal ? `on signal ${signal}` : `with exit code ${code}`; return new WorkerError( `${relative(root, packageDir)}: the worker stopped ${how} before it reported`, ); } function generateOne(packageDir, root) { return new Promise((resolveText, reject) => { const child = fork(join(here, 'worker.mjs'), [packageDir], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'], }); let reply; child.on('message', (message) => { reply = message; }); child.on('error', reject); child.on('exit', (code, signal) => { if (reply?.lines) resolveText(apiText(reply.lines)); else if (reply?.error) reject(new WorkerError(reply.error)); else reject(workerStopped(packageDir, root, code, signal)); }); }); } export async function generateLists( packageDirs, root, workers = Math.min(4, availableParallelism()), ) { const texts = new Map(); const failures = []; const sizes = new Map(); for (const packageDir of packageDirs) { try { sizes.set(packageDir, entryPointsOf(packageDir).length); } catch (error) { failures.push(error.message); } } const queue = [...sizes.keys()].sort( (a, b) => sizes.get(b) - sizes.get(a) || compareCodeUnits(a, b), ); const run = async () => { for (let packageDir = queue.shift(); packageDir; packageDir = queue.shift()) { try { texts.set(packageDir, await generateOne(packageDir, root)); } catch (error) { failures.push(error.message); } } }; await Promise.all(Array.from({ length: workers }, run)); return { texts, failures }; } export async function main({ mode, root, stdout = process.stdout, stderr = process.stderr }) { if (mode !== 'update' && mode !== 'check') { stderr.write('Usage: node scripts/public-api/api.mjs update|check\n'); return 2; } const { packageDirs, leftovers } = publishedPackageDirs(root); const { texts, failures } = await generateLists(packageDirs, root); for (const leftover of leftovers) { failures.push( `${relative(root, leftover)} has an ${LIST_FILE} but no package.json. Delete the folder if the package is gone.`, ); } if (mode === 'check') { for (const [packageDir, text] of texts) { writeFileSync(join(packageDir, MODEL_FOLDER, LIST_FILE), text); } } if (failures.length > 0) { stderr.write( `api:${mode}: could not list the API of every package:\n\n${failures.join('\n\n')}\n`, ); return 1; } const stale = []; for (const [packageDir, text] of [...texts].sort(([a], [b]) => compareCodeUnits(a, b))) { const file = join(packageDir, LIST_FILE); const committed = existsSync(file) ? readFileSync(file, 'utf8') : ''; if (committed === text) continue; stale.push({ file: relative(root, file), differences: listDifferences(committed, text) }); if (mode === 'update') writeFileSync(file, text); } if (mode === 'update') { stdout.write(`api:update: ${stale.length} of ${texts.size} lists changed\n`); for (const { file } of stale) stdout.write(` ${file}\n`); return 0; } if (stale.length === 0) { stdout.write(`api:check: all ${texts.size} lists match the build\n`); return 0; } stderr.write('api:check: these API lists do not match the build:\n'); for (const { file, differences } of stale) { stderr.write(`\n${file}\n${differences.map((line) => ` ${line}`).join('\n')}\n`); } stderr.write( [ '', 'Run `pnpm build`, then `pnpm api:update`, and commit the changed api.txt files. Do not edit or hand-merge an api.txt.', `The lists this run generated are in each package's ${MODEL_FOLDER}/${LIST_FILE}; in CI they are uploaded as the workflow artifact "api-lists", which can be downloaded from the run.`, '', ].join('\n'), ); return 1; } if (process.argv[1] === fileURLToPath(import.meta.url)) { process.exitCode = await main({ mode: process.argv[2], root: resolve(here, '..', '..') }); }