forked from nodejs/readable-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.mjs
231 lines (183 loc) · 6.96 KB
/
build.mjs
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
225
226
227
228
229
230
231
import { transform } from '@babel/core'
import { createReadStream } from 'node:fs'
import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import process from 'node:process'
import { finished } from 'node:stream/promises'
import { fileURLToPath } from 'node:url'
import prettier from 'prettier'
import { Parse } from 'tar'
import { request } from 'undici'
import prettierConfig from '../prettier.config.cjs'
import { aliases, skippedSources, sources } from './files.mjs'
import { footers } from './footers.mjs'
import { headers } from './headers.mjs'
import { replacements } from './replacements.mjs'
import pkg from '../package.json' with { type: "json" };
const baseMatcher = /^(?:lib|test)/
const strictMatcher = /^(['"']use strict.+)/
function highlightFile(file, color) {
return `\x1b[${color}m${file.replace(process.cwd() + '/', '')}\x1b[0m`
}
function info(message) {
console.log(`\x1b[34m[INFO]\x1b[0m ${message}`)
}
async function extract(nodeVersion, tarFile) {
const sourcesMatcher = sources.map((s) => new RegExp(s))
info(`Extracting Node.js ${nodeVersion} tar file ...`)
const contents = []
const tarPrefix = `node-v${nodeVersion}/`
const parser = new Parse()
parser.on('entry', (entry) => {
const dst = entry.path.replace(tarPrefix, '')
if (
entry.type === 'Directory' ||
skippedSources.includes(dst) ||
!baseMatcher.test(dst) ||
!sourcesMatcher.some((s) => s.test(dst))
) {
return entry.resume()
}
let buffer = Buffer.alloc(0)
entry.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk])
})
entry.on('end', () => {
const content = buffer.toString('utf-8')
// Enqueue file
contents.push([dst, content])
// Some special cases when file aliasing is needed
if (aliases[dst]) {
for (const alias of aliases[dst]) {
contents.push([alias, content])
}
}
})
entry.resume()
})
await finished(tarFile.pipe(parser))
info('extraction done')
return contents
}
async function processFiles(contents) {
const replacementsKeys = Object.keys(replacements)
const headersKeys = Object.keys(headers)
const footersKeys = Object.keys(footers)
prettierConfig.parser = 'babel'
for (let [path, content] of contents) {
const modifications = []
const matchingReplacements = replacementsKeys.filter((k) => new RegExp(k).test(path))
const matchingHeaders = headersKeys.filter((k) => new RegExp(k).test(path))
const matchingFooters = footersKeys.filter((k) => new RegExp(k).test(path))
// Perform replacements
if (matchingReplacements.length) {
modifications.push(highlightFile('replacements', 33))
for (const matching of matchingReplacements) {
for (const [from, to] of replacements[matching]) {
content = content.replaceAll(new RegExp(from, 'gm'), to)
}
}
}
// Prepend headers
if (matchingHeaders.length) {
modifications.push(highlightFile('headers', 33))
for (const footerKey of matchingHeaders) {
for (const header of headers[footerKey]) {
if (content.match(strictMatcher)) {
content = content.replace(strictMatcher, `$&;${header}`)
} else {
content = header + content
}
}
}
}
// Append footers
if (matchingFooters.length) {
modifications.push(highlightFile('footers', 33))
for (const footerKey of matchingFooters) {
for (const footer of footers[footerKey]) {
content += footer
}
}
}
// Process the file through babel and prettier
if (path.endsWith('.js')) {
modifications.push(highlightFile('babel', 33), highlightFile('prettier', 33))
content = prettier.format(await transform(content).code.replaceAll('void 0', 'undefined'), prettierConfig)
}
if (!modifications.length) {
modifications.push('no modifications')
}
// Write the file
info(`Creating file ${highlightFile(path, 32)} (${modifications.join(', ')}) ...`)
await writeFile(path, content, 'utf-8')
}
}
async function downloadNode(nodeVersion) {
// Download node
const downloadUrl = `https://nodejs.org/dist/v${nodeVersion}/node-v${nodeVersion}.tar.gz`
info(`Downloading ${downloadUrl} ...`)
const { statusCode, body } = await request(downloadUrl, { pipelining: 0 })
if (statusCode !== 200) {
info(`Downloading failed with HTTP code ${statusCode}.`)
process.exit(1)
}
return body
}
async function main() {
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const rootDir = resolve(__dirname, '..')
if (process.cwd() !== rootDir) {
console.error('Please run this from the root directory of readable-stream repository.')
return process.exit(1)
}
const nodeVersion = process.argv[2] || pkg.config.node.version;
if (!nodeVersion?.match(/^\d+\.\d+\.\d+/)) {
console.error('Usage: build.js xx.yy.zz [node.tar.gz]')
return process.exit(1)
}
// Cleanup existing folder
await rm('lib', { recursive: true, force: true })
await rm('test', { recursive: true, force: true })
// Download or open the tar file
let tarFile
if (process.argv[3]) {
tarFile = createReadStream(process.argv[3])
} else {
tarFile = await downloadNode(nodeVersion)
}
// Extract contents
const contents = await extract(nodeVersion, tarFile)
// Update Node version in README.md
replacements['README.md'][0][1] = replacements['README.md'][0][1].replace('$2', nodeVersion)
replacements['README.md'][1][1] = replacements['README.md'][1][1].replace('$2', nodeVersion)
// Add custom files
contents.push(['lib/ours/browser.js', await readFile('src/browser.js', 'utf-8')])
contents.push(['lib/ours/index.js', await readFile('src/index.js', 'utf-8')])
contents.push(['lib/ours/errors.js', await readFile('src/errors.js', 'utf-8')])
contents.push(['lib/ours/primordials.js', await readFile('src/primordials.js', 'utf-8')])
contents.push(['lib/ours/util.js', await readFile('src/util.js', 'utf-8')])
for (const file of await readdir('src/test/ours')) {
contents.push([`test/ours/${file}`, await readFile(`src/test/ours/${file}`, 'utf-8')])
}
for (const file of await readdir('src/test/browser')) {
if (file.endsWith('fixtures')) {
continue
}
contents.push([`test/browser/${file}`, await readFile(`src/test/browser/${file}`, 'utf-8')])
}
for (const file of await readdir('src/test/browser/fixtures')) {
contents.push([`test/browser/fixtures/${file}`, await readFile(`src/test/browser/fixtures/${file}`, 'utf-8')])
}
contents.push(['README.md', await readFile('./README.md', 'utf-8')])
// Create paths
const paths = new Set(contents.map((c) => dirname(c[0])))
paths.delete('.')
for (const path of paths.values()) {
info(`Creating directory ${highlightFile(path, 32)} ...`)
await mkdir(path, { recursive: true, force: true })
}
// Perform replacements
await processFiles(contents)
}
await main()