-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathesbuild-utils.mjs
More file actions
163 lines (142 loc) · 4.9 KB
/
esbuild-utils.mjs
File metadata and controls
163 lines (142 loc) · 4.9 KB
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
/**
* Shared esbuild utilities for Socket CLI builds.
* Contains helpers for environment variable inlining and build metadata.
*/
import { mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { build } from 'esbuild'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { EnvironmentVariables } from './environment-variables.mjs'
const logger = getDefaultLogger()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootPath = path.join(__dirname, '..')
/**
* Create a standard index loader config.
* @param {Object} options - Configuration options
* @param {string} options.entryPoint - Path to entry point file
* @param {string} options.outfile - Path to output file
* @param {boolean} [options.minify=false] - Whether to minify output
* @returns {Object} esbuild configuration object
*/
export function createIndexConfig({ entryPoint, minify = false, outfile }) {
// Get inlined environment variables for build-time constant replacement.
const inlinedEnvVars = getInlinedEnvVars()
const config = {
banner: {
js: '#!/usr/bin/env node',
},
bundle: true,
entryPoints: [entryPoint],
format: 'cjs',
outfile,
platform: 'node',
// Source maps off for entry point production build.
sourcemap: false,
target: 'node18',
// Define environment variables for inlining.
define: {
'process.env.NODE_ENV': '"production"',
...createDefineEntries(inlinedEnvVars),
},
// Add plugin for post-bundle env var replacement.
plugins: [envVarReplacementPlugin(inlinedEnvVars)],
// Plugin needs to transform output.
write: false,
}
if (minify) {
config.minify = true
} else {
config.minifyWhitespace = true
config.minifyIdentifiers = true
}
return config
}
/**
* Helper to create both dot and bracket notation define keys.
* This ensures esbuild can replace both forms of process.env access.
*/
export function createDefineEntries(envVars) {
const entries = {}
for (const [key, value] of Object.entries(envVars)) {
// Dot notation: process.env.KEY
entries[`process.env.${key}`] = value
// Bracket notation: process.env["KEY"]
entries[`process.env["${key}"]`] = value
}
return entries
}
/**
* esbuild plugin to replace env vars after bundling (handles mangled identifiers).
* This is necessary because esbuild's define doesn't catch all forms after minification.
*/
export function envVarReplacementPlugin(envVars) {
return {
name: 'env-var-replacement',
setup(build) {
build.onEnd(result => {
const outputs = result.outputFiles
if (!outputs || outputs.length === 0) {
return
}
for (const output of outputs) {
let content = output.text
// Replace all forms of process.env["KEY"] access, even with mangled identifiers.
// Pattern: <anything>.env["KEY"] where <anything> could be "import_node_process21.default" etc.
for (const [key, value] of Object.entries(envVars)) {
// Match: <identifier>.env["KEY"] or <identifier>.env['KEY']
const pattern = new RegExp(`(\\w+\\.)+env\\["${key}"\\]`, 'g')
const singleQuotePattern = new RegExp(
`(\\w+\\.)+env\\['${key}'\\]`,
'g',
)
// Replace with the actual value (already JSON.stringified).
content = content.replace(pattern, value)
content = content.replace(singleQuotePattern, value)
}
// Update the output content.
output.contents = Buffer.from(content, 'utf8')
}
})
},
}
}
/**
* Get all inlined environment variables with their values.
* This reads package.json metadata and computes derived values.
*
* @returns {Record<string, string>} Object with env var names as keys and JSON-stringified values
*/
export function getInlinedEnvVars() {
// Delegate to unified EnvironmentVariables module.
return EnvironmentVariables.getDefineEntries()
}
/**
* Run an esbuild config, writing output files if write: false.
*
* @param {Object} config - esbuild configuration object
* @param {string} [description] - Description logged before/after build
*/
export async function runBuild(config, description = 'Build') {
try {
if (description) {
logger.info(`Building: ${description}`)
}
const result = await build(config)
// If write: false, manually write outputFiles.
if (result.outputFiles && result.outputFiles.length > 0) {
for (const output of result.outputFiles) {
mkdirSync(path.dirname(output.path), { recursive: true })
writeFileSync(output.path, output.contents)
}
if (description) {
logger.success(`${description} complete`)
}
}
} catch (e) {
logger.error(`Build failed: ${description || 'Unknown'}`)
logger.error(e)
process.exitCode = 1
throw e
}
}