Skip to content

Commit f89631e

Browse files
committed
Reduce duplicate require('node:...') variable assignments
1 parent 16dd1a6 commit f89631e

3 files changed

Lines changed: 51 additions & 15 deletions

File tree

.config/rollup.base.config.mjs

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import replacePlugin from '@rollup/plugin-replace'
1010
import { purgePolyfills } from 'unplugin-purge-polyfills'
1111

1212
import { readPackageJsonSync } from '@socketsecurity/registry/lib/packages'
13+
import { escapeRegExp } from '@socketsecurity/registry/lib/regexps'
1314
import { spawnSync } from '@socketsecurity/registry/lib/spawn'
1415
import { stripAnsi } from '@socketsecurity/registry/lib/strings'
1516

@@ -44,7 +45,9 @@ export const EXTERNAL_PACKAGES = [
4445
]
4546

4647
const builtinAliases = builtinModules.reduce((o, n) => {
47-
o[n] = `node:${n}`
48+
if (!n.startsWith('node:')) {
49+
o[n] = `node:${n}`
50+
}
4851
return o
4952
}, {})
5053

@@ -81,13 +84,33 @@ function getSocketCliVersionHash() {
8184
return _socketVersionHash
8285
}
8386

87+
const requiredToVarName = new Map()
88+
function getVarNameForRequireId(filename, id, lookbehindContent) {
89+
const key = `${filename}:${id}`
90+
let varName = requiredToVarName.get(key)
91+
if (varName) {
92+
return varName
93+
}
94+
const varNameRegExp = new RegExp(
95+
`(?<=var +)[$\\w]+(?=\\s*=\\s*require[$\\w]*\\(["']${escapeRegExp(id)}["']\\))`,
96+
)
97+
varName = varNameRegExp.exec(lookbehindContent)?.[0] ?? ''
98+
if (varName) {
99+
requiredToVarName.set(key, varName)
100+
}
101+
return varName
102+
}
103+
84104
export default function baseConfig(extendConfig = {}) {
85105
// Lazily access constants path properties.
86106
const { configPath, rootPath } = constants
107+
87108
const nmPath = path.join(rootPath, NODE_MODULES)
109+
88110
const extendPlugins = Array.isArray(extendConfig.plugins)
89111
? extendConfig.plugins.slice()
90112
: []
113+
91114
const extractedPlugins = { __proto__: null }
92115
if (extendPlugins.length) {
93116
for (const pluginName of [
@@ -237,7 +260,7 @@ export default function baseConfig(extendConfig = {}) {
237260
}),
238261
// Convert un-prefixed built-in imports into "node:"" prefixed forms.
239262
replacePlugin({
240-
delimiters: ['(?<=(?:require[$\\d]*\\(|from\\s*)["\'])', '(?=["\'])'],
263+
delimiters: ['(?<=(?:require[$\\w]*\\(|from\\s*)["\'])', '(?=["\'])'],
241264
preventAssignment: false,
242265
values: builtinAliases,
243266
}),
@@ -246,17 +269,17 @@ export default function baseConfig(extendConfig = {}) {
246269
// builds which causes 'tiny-colors' to be treated as an external, not bundled,
247270
// require.
248271
socketModifyPlugin({
249-
find: /require[$\d]*\(["']tiny-colors["']\)/g,
272+
find: /require[$\w]*\(["']tiny-colors["']\)/g,
250273
replace: "require('yoctocolors-cjs')",
251274
}),
252275
// Try to convert `require('u' + 'rl')` into something like `require$$2$3`.
253276
socketModifyPlugin({
254-
find: /require[$\d]*\(["']u["']\s*\+\s*["']rl["']\)/g,
255-
replace(match) {
277+
find: /require[$\w]*\(["']u["']\s*\+\s*["']rl["']\)/g,
278+
replace(match, index) {
279+
const { fileName } = this.chunk
280+
const beforeMatch = this.input.slice(0, index)
256281
return (
257-
/(?<=var +)[$\w]+(?=\s*=\s*require[$\d]*\(["']node:url["']\))/.exec(
258-
this.input,
259-
)?.[0] ?? match
282+
getVarNameForRequireId(fileName, 'node:url', beforeMatch) || match
260283
)
261284
},
262285
}),
@@ -265,9 +288,21 @@ export default function baseConfig(extendConfig = {}) {
265288
// require('node:util')
266289
// require('graceful-fs')
267290
socketModifyPlugin({
268-
find: /^\s*require[$\d]*\(["'].+?["']\);?\r?\n/gm,
291+
find: /^\s*require[$\w]*\(["'].+?["']\);?\r?\n/gm,
269292
replace: '',
270293
}),
294+
// Reduce duplicate require('node:...') variable assignments.
295+
socketModifyPlugin({
296+
find: /var +([$\w]+)\s*=\s*require[$\w]*\(["'](node:.+?)["']\)/g,
297+
replace(match, currVarName, id, index) {
298+
const { fileName } = this.chunk
299+
const beforeMatch = this.input.slice(0, index)
300+
const prevVarName = getVarNameForRequireId(fileName, id, beforeMatch)
301+
return !prevVarName || currVarName === prevVarName
302+
? match
303+
: `var ${currVarName} = ${prevVarName}`
304+
},
305+
}),
271306
...extendPlugins,
272307
],
273308
}

.config/rollup.dist.config.mjs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -409,10 +409,10 @@ export default async () => {
409409
plugins: [
410410
// Remove Rollup's browser interop for import.meta.url.
411411
socketModifyPlugin({
412-
find: /(?<=const +require[$\d]*\s*=)\s*Module\.createRequire[^;]+;/g,
412+
find: /(?<=const +require[$\w]*\s*=)\s*Module\.createRequire[^;]+;/g,
413413
replace(match) {
414414
const pathToUrlCode =
415-
/require[$\d]*(?:\([^)]+\))?\.pathToFileURL\(__filename\)\.href/.exec(
415+
/require[$\w]*(?:\([^)]+\))?\.pathToFileURL\(__filename\)\.href/.exec(
416416
match,
417417
)?.[0]
418418
return pathToUrlCode
@@ -432,7 +432,7 @@ export default async () => {
432432
...EXTERNAL_PACKAGES.map(n =>
433433
socketModifyPlugin({
434434
find: new RegExp(
435-
`(?<=require[$\\d]*(?:\\.resolve)?\\(["'])${escapeRegExp(n)}(?=(?:\\/[^"']+)?["']\\))`,
435+
`(?<=require[$\\w]*(?:\\.resolve)?\\(["'])${escapeRegExp(n)}(?=(?:\\/[^"']+)?["']\\))`,
436436
'g',
437437
),
438438
replace: id => `../external/${id}`,
@@ -441,7 +441,7 @@ export default async () => {
441441
// Replace require.resolve('node-gyp/bin/node-gyp.js') with
442442
// require('./constants.js').npmNmNodeGypPath.
443443
socketModifyPlugin({
444-
find: /require[$\d]*\.resolve\(["']node-gyp\/bin\/node-gyp.js["']\)/g,
444+
find: /require[$\w]*\.resolve\(["']node-gyp\/bin\/node-gyp.js["']\)/g,
445445
replace: "require('./constants.js').npmNmNodeGypPath",
446446
}),
447447
// Replace resolve(__dirname, '../lib/node-gyp-bin') with

scripts/rollup/socket-modify-plugin.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ function socketModifyPlugin({
1313
const filter = createFilter(include, exclude)
1414
return {
1515
name: 'socket-modify',
16-
renderChunk(code, { fileName }) {
16+
renderChunk(code, chunk) {
17+
const { fileName } = chunk
1718
if (!filter(fileName)) {
1819
return null
1920
}
@@ -26,7 +27,7 @@ function socketModifyPlugin({
2627
match.index,
2728
match.index + match[0].length,
2829
typeof replace === 'function'
29-
? Reflect.apply(replace, match, match)
30+
? Reflect.apply(replace, { ...match, chunk }, match)
3031
: String(replace),
3132
)
3233
// Exit early if not a global regexp.

0 commit comments

Comments
 (0)