diff --git a/package.json b/package.json index 9357b94..575afc5 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "./package.json": "./package.json" }, "scripts": { - "build": "pkg-utils build && pkg-utils --strict", + "build": "pkg-utils build && pkg-utils --strict && tsx scripts/referenceEventTypings.ts", "build:watch": "pkg-utils watch", "clean": "rimraf dist coverage", "lint": "eslint . && tsc --noEmit", diff --git a/scripts/referenceEventTypings.ts b/scripts/referenceEventTypings.ts new file mode 100644 index 0000000..2617c90 --- /dev/null +++ b/scripts/referenceEventTypings.ts @@ -0,0 +1,43 @@ +import {copyFile, readdir, readFile, writeFile} from 'node:fs/promises' +import {join as joinPath} from 'node:path' + +const referenceDirective = `/// ` + +/** + * Add a reference directive to the `events.d.ts` file at the top of every "type entry" + * file in the `dist` (output) directory. These files are eg `index.d.ts` and `index.d.cts`. + * + * This is necessary because the `events.d.ts` file contains some "shims" for APIs such as + * `Event`, `EventTarget` and `MessageEvent` that are technically part of the supported + * environments, but not always present in their typings - eg `@types/node` does not declare + * a global `MessageEvent` even though it is present in Node.js. + * + * Current build tooling (`@sanity/pkg-utils`) does not support adding reference directives + * directly, so we have to do this as a post-build step. + */ +async function referenceEventTypings() { + const distDir = joinPath(import.meta.dirname, '..', 'dist') + const srcDir = joinPath(import.meta.dirname, '..', 'src') + + const entries = await readdir(distDir) + + const typeEntries = entries.filter( + (entry) => entry.startsWith('index.') && (entry.endsWith('.d.ts') || entry.endsWith('.d.cts')), + ) + + for (const entry of typeEntries) { + const typeFile = joinPath(distDir, entry) + const typeFileContent = await readFile(typeFile, 'utf-8') + + if (!typeFileContent.includes(referenceDirective)) { + await writeFile(typeFile, `${referenceDirective}\n\n${typeFileContent}`) + } + } + + await copyFile(joinPath(srcDir, 'events.d.ts'), joinPath(distDir, 'events.d.ts')) +} + +referenceEventTypings().catch((error) => { + console.error(error) + process.exit(1) +})