summaryrefslogtreecommitdiff
path: root/packages/webapi/run/build.js
blob: 01782074639ccc71424f527c583f81b5e41c47fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import { default as alias } from '@rollup/plugin-alias'
import { default as inject } from '@rollup/plugin-inject'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import { default as typescript } from '@rollup/plugin-typescript'
import { default as MagicString } from 'magic-string'
import {
	readFile as nodeReadFile,
	rename,
	rm,
	writeFile,
} from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
import { rollup } from 'rollup'

const readFileCache = Object.create(null)
const require = createRequire(import.meta.url)

const readFile = (/** @type {string} */ id) =>
	readFileCache[id] || (readFileCache[id] = nodeReadFile(id, 'utf8'))

const pathToDOMException = path.resolve('src', 'lib', 'DOMException.js')
const pathToEventTargetShim = path.resolve(
	'node_modules',
	'event-target-shim',
	'index.mjs'
)
const pathToStructuredClone = path.resolve(
	'node_modules',
	'@ungap',
	'structured-clone',
	'esm',
	'index.js'
)

const plugins = [
	typescript({
		tsconfig: './tsconfig.json',
	}),
	alias({
		entries: [
			{ find: '@ungap/structured-clone', replacement: pathToStructuredClone },
			{ find: 'event-target-shim', replacement: pathToEventTargetShim },
			{
				find: 'event-target-shim/dist/event-target-shim.js',
				replacement: pathToEventTargetShim,
			},
			{
				find: 'event-target-shim/dist/event-target-shim.umd.js',
				replacement: pathToEventTargetShim,
			},
			{ find: 'node-domexception', replacement: pathToDOMException },
		],
	}),
	nodeResolve({
		dedupe: ['net', 'node:net'],
	}),
	inject({
		// import { Promise as P } from 'es6-promise'
		// P: [ 'es6-promise', 'Promise' ],
		DOMException: [pathToDOMException, 'DOMException'],
		Document: ['./Document', 'Document'],
		Element: ['./Element', 'Element'],
		Event: ['event-target-shim', 'Event'],
		EventTarget: ['event-target-shim', 'EventTarget'],
		defineEventAttribute: ['event-target-shim', 'defineEventAttribute'],
		HTMLElement: ['./Element', 'HTMLElement'],
		HTMLImageElement: ['./Element', 'HTMLImageElement'],
		HTMLUnknownElement: ['./Element', 'HTMLUnknownElement'],
		MediaQueryList: ['./MediaQueryList', 'MediaQueryList'],
		Node: ['./Node', 'Node'],
		ReadableStream: ['node:stream/web', 'ReadableStream'],
		ShadowRoot: ['./Node', 'ShadowRoot'],
		Window: ['./Window', 'Window'],
		'globalThis.ReadableStream': ['node:stream/web', 'ReadableStream'],
	}),
	{
		async load(id) {
			const pathToEsm = id
			const pathToMap = `${pathToEsm}.map`

			const code = await readFile(pathToEsm, 'utf8')

			const indexes = []

			const replacements = [
				// remove unused imports
				[/(^|\n)import\s+[^']+'node:(buffer|fs|path|worker_threads)'/g, ``],
				[/const \{ stat \} = fs/g, ``],

				// remove unused polyfill utils
				[/\nif \(\s*typeof Global[\W\w]+?\n\}/g, ``],
				[/\nif \(\s*typeof window[\W\w]+?\n\}/g, ``],
				[/\nif \(!globalThis\.ReadableStream\) \{[\W\w]+?\n\}/g, ``],
				[/\nif \(typeof SymbolPolyfill[\W\w]+?\n\}/g, ``],

				// remove unused polyfills
				[/\nconst globals = getGlobals\(\);/g, ``],
				[/\nconst queueMicrotask = [\W\w]+?\n\}\)\(\);/g, ``],
				[/\nconst NativeDOMException =[^;]+;/g, ``],
				[
					/\nconst SymbolPolyfill\s*=[^;]+;/g,
					'\nconst SymbolPolyfill = Symbol;',
				],
				[
					/\n(const|let) DOMException[^;]*;/g,
					`let DOMException$1=DOMException`,
				],
				[/\nconst DOMException = globalThis.DOMException[\W\w]+?\}\)\(\)/g, ``],
				[/\nimport DOMException from 'node-domexception'/g, ``],

				// use shared AbortController methods
				[/ new DOMException\$1/g, `new DOMException`],
				[/ from 'net'/g, `from 'node:net'`],
				[/ throw createInvalidStateError/g, `throw new DOMException`],
				[/= createAbortController/g, `= new AbortController`],
				[/\nconst queueMicrotask = [\W\w]+?\n\}\)\(\)\;/g, ``],

				// remove Body.prototype.buffer deprecation notice
				[/\nBody\.prototype\.buffer[^\n]+/g, ``],

				// remove Body.prototype.data deprecation notice
				[/\n	data: \{get: deprecate[\W\w]+?\)\}/g, ``],
			]

			for (const [replacee, replacer] of replacements) {
				replacee.index = 0

				let replaced = null

				while ((replaced = replacee.exec(code)) !== null) {
					const leadIndex = replaced.index
					const tailIndex = replaced.index + replaced[0].length

					indexes.unshift([leadIndex, tailIndex, replacer])
				}
			}

			if (indexes.length) {
				const magicString = new MagicString(code)

				indexes.sort(([leadOfA], [leadOfB]) => leadOfA - leadOfB)

				for (const [leadIndex, tailindex, replacer] of indexes) {
					magicString.overwrite(leadIndex, tailindex, replacer)
				}

				const magicMap = magicString.generateMap({
					source: pathToEsm,
					file: pathToMap,
					includeContent: true,
				})

				const modifiedEsm = magicString.toString()
				const modifiedMap = magicMap.toString()

				return { code: modifiedEsm, map: modifiedMap }
			}
		},
	},
]

async function build() {
	const configs = [
		{
			inputOptions: {
				input: 'src/polyfill.ts',
				plugins: plugins,
				external: ['undici'],
				onwarn(warning, warn) {
					if (warning.code !== 'UNRESOLVED_IMPORT') warn(warning)
				},
			},
			outputOptions: {
				inlineDynamicImports: true,
				file: 'mod.js',
				format: 'esm',
				sourcemap: true,
			},
		},
	]

	for (const config of configs) {
		const bundle = await rollup(config.inputOptions)

		// or write the bundle to disk
		await bundle.write(config.outputOptions)

		// closes the bundle
		await bundle.close()

		// delete the lib directory
		await rm('lib', { force: true, recursive: true })
		await rm('exclusions.d.ts', { force: true, recursive: true })
		await rm('exclusions.d.ts.map', { force: true, recursive: true })
		await rm('inheritance.d.ts', { force: true, recursive: true })
		await rm('inheritance.d.ts.map', { force: true, recursive: true })
		await rm('polyfill.d.ts.map', { force: true, recursive: true })
		await rm('polyfill.js.map', { force: true, recursive: true })
		await rm('polyfill.js', { force: true, recursive: true })
		await rm('ponyfill.d.ts', { force: true, recursive: true })
		await rm('ponyfill.d.ts.map', { force: true, recursive: true })
		await rm('ponyfill.js.map', { force: true, recursive: true })
		await rm('ponyfill.js', { force: true, recursive: true })

		await rename('polyfill.d.ts', 'mod.d.ts')

		const modDTS = await readFile('./mod.d.ts')

		writeFile(
			'mod.d.ts',
			'// organize-imports-ignore\n' +
				modDTS
					.replace('\n//# sourceMappingURL=polyfill.d.ts.map', '')
					.replace('ponyfill.js', 'mod.js')
		)
		writeFile(
			'apply.js',
			`import { polyfill } from './mod.js'\n\nexport * from './mod.js'\n\npolyfill(globalThis)\n`
		)
	}
}

build()