Skip to content

Commit d3b6849

Browse files
committed
fix: reference possibly missing event typings
1 parent 101028d commit d3b6849

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"./package.json": "./package.json"
2020
},
2121
"scripts": {
22-
"build": "pkg-utils build && pkg-utils --strict",
22+
"build": "pkg-utils build && pkg-utils --strict && tsx scripts/referenceEventTypings.ts",
2323
"build:watch": "pkg-utils watch",
2424
"clean": "rimraf dist coverage",
2525
"lint": "eslint . && tsc --noEmit",

scripts/referenceEventTypings.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import {copyFile, readdir, readFile, writeFile} from 'node:fs/promises'
2+
import {join as joinPath} from 'node:path'
3+
4+
const referenceDirective = `/// <reference path="events.d.ts" />`
5+
6+
/**
7+
* Add a reference directive to the `events.d.ts` file at the top of every "type entry"
8+
* file in the `dist` (output) directory. These files are eg `index.d.ts` and `index.d.cts`.
9+
*
10+
* This is necessary because the `events.d.ts` file contains some "shims" for APIs such as
11+
* `Event`, `EventTarget` and `MessageEvent` that are technically part of the supported
12+
* environments, but not always present in their typings - eg `@types/node` does not declare
13+
* a global `MessageEvent` even though it is present in Node.js.
14+
*
15+
* Current build tooling (`@sanity/pkg-utils`) does not support adding reference directives
16+
* directly, so we have to do this as a post-build step.
17+
*/
18+
async function referenceEventTypings() {
19+
const distDir = joinPath(import.meta.dirname, '..', 'dist')
20+
const srcDir = joinPath(import.meta.dirname, '..', 'src')
21+
22+
const entries = await readdir(distDir)
23+
24+
const typeEntries = entries.filter(
25+
(entry) => entry.startsWith('index.') && (entry.endsWith('.d.ts') || entry.endsWith('.d.cts')),
26+
)
27+
28+
for (const entry of typeEntries) {
29+
const typeFile = joinPath(distDir, entry)
30+
const typeFileContent = await readFile(typeFile, 'utf-8')
31+
32+
if (!typeFileContent.includes(referenceDirective)) {
33+
await writeFile(typeFile, `${referenceDirective}\n\n${typeFileContent}`)
34+
}
35+
}
36+
37+
await copyFile(joinPath(srcDir, 'events.d.ts'), joinPath(distDir, 'events.d.ts'))
38+
}
39+
40+
referenceEventTypings().catch((error) => {
41+
console.error(error)
42+
process.exit(1)
43+
})

0 commit comments

Comments
 (0)