Skip to content

Commit 4e310ab

Browse files
committed
Replace console.log/error with @socketsecurity/lib logger in WASM build scripts
- Update check-rust-toolchain.mjs to use logger methods - Update build-unified-wasm.mjs to use logger methods - Use logger.progress(), logger.done(), logger.error(), logger.warn(), logger.info() - Improve consistency with other Socket scripts
1 parent 422644c commit 4e310ab

File tree

2 files changed

+90
-103
lines changed

2 files changed

+90
-103
lines changed

scripts/wasm/build-unified-wasm.mjs

Lines changed: 67 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { promises as fs } from 'node:fs'
2525
import path from 'node:path'
2626
import { fileURLToPath } from 'node:url'
2727

28+
import { logger } from '@socketsecurity/lib/logger'
2829
import { spawn } from '@socketsecurity/lib/spawn'
2930

3031
import { checkRustToolchain, getRustPaths } from './check-rust-toolchain.mjs'
@@ -68,47 +69,46 @@ async function installBinaryen() {
6869
const isMacOS = process.platform === 'darwin'
6970
const isLinux = process.platform === 'linux'
7071

71-
console.log('📦 Installing binaryen (wasm-opt)...')
72-
console.log(' This may take a few minutes...\\n')
72+
logger.progress('Installing binaryen (wasm-opt) - this may take a few minutes')
7373

7474
try {
7575
if (isMacOS) {
7676
// macOS: Try Homebrew first.
77-
console.log(' Trying Homebrew installation...')
77+
logger.substep('Trying Homebrew installation')
7878
try {
7979
await exec('brew', ['--version'])
8080
await exec('brew', ['install', 'binaryen'], { stdio: 'inherit' })
81-
console.log(' ✓ binaryen installed via Homebrew\\n')
81+
logger.done('binaryen installed via Homebrew')
8282
return true
8383
} catch {
84-
console.log(' ⚠ Homebrew not available, trying GitHub releases...')
84+
logger.warn('Homebrew not available, trying GitHub releases')
8585
}
8686
} else if (isLinux) {
8787
// Linux: Try apt-get first (Ubuntu/Debian).
88-
console.log(' Trying apt-get installation...')
88+
logger.substep('Trying apt-get installation')
8989
try {
9090
await exec('sudo', ['apt-get', 'update'], { stdio: 'pipe' })
9191
await exec('sudo', ['apt-get', 'install', '-y', 'binaryen'], { stdio: 'inherit' })
92-
console.log(' ✓ binaryen installed via apt-get\\n')
92+
logger.done('binaryen installed via apt-get')
9393
return true
9494
} catch {
95-
console.log(' ⚠ apt-get not available or failed, trying GitHub releases...')
95+
logger.warn('apt-get not available or failed, trying GitHub releases')
9696
}
9797
} else if (isWindows) {
9898
// Windows: Try chocolatey first.
99-
console.log(' Trying Chocolatey installation...')
99+
logger.substep('Trying Chocolatey installation')
100100
try {
101101
await exec('choco', ['--version'])
102102
await exec('choco', ['install', 'binaryen', '-y'], { stdio: 'inherit' })
103-
console.log(' ✓ binaryen installed via Chocolatey\\n')
103+
logger.done('binaryen installed via Chocolatey')
104104
return true
105105
} catch {
106-
console.log(' ⚠ Chocolatey not available, trying GitHub releases...')
106+
logger.warn('Chocolatey not available, trying GitHub releases')
107107
}
108108
}
109109

110110
// Fallback: Download from GitHub releases (all platforms).
111-
console.log(' Downloading pre-built binaryen from GitHub...')
111+
logger.substep('Downloading pre-built binaryen from GitHub')
112112
const version = 'version_119' // Latest stable as of implementation.
113113
let platformSuffix = ''
114114

@@ -121,15 +121,15 @@ async function installBinaryen() {
121121
}
122122

123123
const url = `https://github.com/WebAssembly/binaryen/releases/download/${version}/binaryen-${version}-${platformSuffix}.tar.gz`
124-
console.log(` URL: ${url}`)
124+
logger.substep(`URL: ${url}`)
125125

126126
// For CI/automation, we'll gracefully degrade if GitHub releases download fails.
127-
console.log(' ⚠ GitHub releases download not yet implemented')
128-
console.log(' ⚠ wasm-opt will be skipped (install manually for smaller bundles)')
127+
logger.warn('GitHub releases download not yet implemented')
128+
logger.warn('wasm-opt will be skipped (install manually for smaller bundles)')
129129
return false
130130
} catch (e) {
131-
console.error(`Failed to install binaryen: ${e.message}`)
132-
console.error(' ⚠ wasm-opt will be skipped (install manually for optimal bundle size)')
131+
logger.error(`Failed to install binaryen: ${e.message}`)
132+
logger.warn('wasm-opt will be skipped (install manually for optimal bundle size)')
133133
return false
134134
}
135135
}
@@ -139,53 +139,49 @@ const rootPath = path.join(__dirname, '../..')
139139
const wasmBundleDir = path.join(rootPath, 'wasm-bundle')
140140
const externalDir = path.join(rootPath, 'external')
141141

142-
console.log('╔═══════════════════════════════════════════════════╗')
143-
console.log('║ Build Unified WASM Bundle ║')
144-
console.log('╚═══════════════════════════════════════════════════╝\n')
142+
logger.step('Build Unified WASM Bundle')
145143

146144
// Step 1: Check Rust toolchain.
147-
console.log('Step 1: Checking Rust toolchain...\n')
145+
logger.substep('Step 1: Checking Rust toolchain')
148146
const hasRust = await checkRustToolchain()
149147
if (!hasRust) {
150-
console.error('Rust toolchain setup failed')
151-
console.error(' Please install manually: https://rustup.rs/')
148+
logger.error('Rust toolchain setup failed')
149+
logger.error('Please install manually: https://rustup.rs/')
152150
process.exit(1)
153151
}
154152

155153
// Step 2: Download models.
156-
console.log('Step 2: Downloading model files...\n')
154+
logger.substep('Step 2: Downloading model files')
157155
const hasModels = await downloadModels()
158156
if (!hasModels) {
159-
console.error('Model download incomplete')
160-
console.error(' Please run: node scripts/wasm/convert-codet5.mjs')
157+
logger.error('Model download incomplete')
158+
logger.error('Please run: node scripts/wasm/convert-codet5.mjs')
161159
process.exit(1)
162160
}
163161

164162
// Step 2.5: Check and install binaryen for wasm-opt.
165-
console.log('Step 2.5: Checking binaryen (wasm-opt)...\n')
163+
logger.substep('Step 2.5: Checking binaryen (wasm-opt)')
166164
const hasBinaryen = await checkBinaryenInstalled()
167165
if (!hasBinaryen) {
168-
console.log('❌ binaryen (wasm-opt) not found\n')
166+
logger.warn('binaryen (wasm-opt) not found')
169167

170168
const binaryenInstalled = await installBinaryen()
171169
if (!binaryenInstalled) {
172-
console.log(
173-
'⚠ wasm-opt not available - bundle will be slightly larger\n',
174-
)
170+
logger.warn('wasm-opt not available - bundle will be slightly larger')
175171
}
176172
} else {
177-
console.log('✓ binaryen (wasm-opt) found\n')
173+
logger.info('binaryen (wasm-opt) found')
178174
}
179175

180176
// Step 3: Build WASM with wasm-pack.
181-
console.log('Step 3: Building WASM bundle...\n')
177+
logger.substep('Step 3: Building WASM bundle')
182178

183179
const { wasmPack } = getRustPaths()
184180
const pkgDir = path.join(wasmBundleDir, 'pkg')
185181

186-
console.log('📦 Running wasm-pack build...')
187-
console.log(` Source: ${wasmBundleDir}`)
188-
console.log(` Output: ${pkgDir}\n`)
182+
logger.progress('Running wasm-pack build')
183+
logger.substep(`Source: ${wasmBundleDir}`)
184+
logger.substep(`Output: ${pkgDir}`)
189185

190186
// Force wasm-pack to use rustup's toolchain by modifying PATH.
191187
const { homedir } = await import('node:os')
@@ -216,28 +212,28 @@ const buildResult = await exec(
216212
)
217213

218214
if (buildResult.code !== 0) {
219-
console.error('wasm-pack build failed')
215+
logger.error('wasm-pack build failed')
220216
process.exit(1)
221217
}
222218

223-
console.log('✓ wasm-pack build complete\n')
219+
logger.done('wasm-pack build complete')
224220

225221
// Step 4: Check size and optionally optimize.
226222
const wasmFile = path.join(pkgDir, 'socket_ai_bg.wasm')
227223
if (!existsSync(wasmFile)) {
228-
console.error(`WASM file not found: ${wasmFile}`)
224+
logger.error(`WASM file not found: ${wasmFile}`)
229225
process.exit(1)
230226
}
231227

232228
let stats = await fs.stat(wasmFile)
233229
const originalSize = stats.size
234-
console.log(
235-
`📊 WASM bundle size: ${(originalSize / 1024 / 1024).toFixed(2)} MB`,
230+
logger.info(
231+
`WASM bundle size: ${(originalSize / 1024 / 1024).toFixed(2)} MB`,
236232
)
237233

238234
// Try to optimize with wasm-opt if available.
239235
try {
240-
console.log('\n🔧 Optimizing with wasm-opt...')
236+
logger.progress('Optimizing with wasm-opt')
241237
const optResult = await exec('wasm-opt', ['-Oz', wasmFile, '-o', wasmFile], {
242238
stdio: 'inherit',
243239
})
@@ -246,26 +242,24 @@ try {
246242
stats = await fs.stat(wasmFile)
247243
const optimizedSize = stats.size
248244
const savings = ((1 - optimizedSize / originalSize) * 100).toFixed(1)
249-
console.log(
250-
`Optimized size: ${(optimizedSize / 1024 / 1024).toFixed(2)} MB (${savings}% smaller)\n`,
245+
logger.done(
246+
`Optimized size: ${(optimizedSize / 1024 / 1024).toFixed(2)} MB (${savings}% smaller)`,
251247
)
252248
} else {
253-
console.log(
254-
'⚠ wasm-opt optimization failed (continuing with unoptimized)\n',
255-
)
249+
logger.warn('wasm-opt optimization failed (continuing with unoptimized)')
256250
}
257251
} catch (_e) {
258-
console.log('⚠ wasm-opt not available (install binaryen for optimization)\n')
252+
logger.warn('wasm-opt not available (install binaryen for optimization)')
259253
}
260254

261255
// Step 5: Embed as base64 in JavaScript.
262-
console.log('Step 5: Embedding WASM as base64...\n')
256+
logger.substep('Step 5: Embedding WASM as base64')
263257

264-
console.log('📖 Reading WASM binary...')
258+
logger.progress('Reading WASM binary')
265259
const wasmData = await fs.readFile(wasmFile)
266-
console.log(` ✓ Read ${wasmData.length} bytes`)
260+
logger.done(`Read ${wasmData.length} bytes`)
267261

268-
console.log('🗜️ Compressing with brotli (quality 11 - maximum)...')
262+
logger.progress('Compressing with brotli (quality 11 - maximum)')
269263
const { constants } = await import('node:zlib')
270264
const wasmCompressed = brotliCompressSync(wasmData, {
271265
params: {
@@ -278,16 +272,16 @@ const compressionRatio = (
278272
(wasmCompressed.length / wasmData.length) *
279273
100
280274
).toFixed(1)
281-
console.log(
282-
`Compressed: ${wasmCompressed.length} bytes (${compressionRatio}% of original)`,
275+
logger.done(
276+
`Compressed: ${wasmCompressed.length} bytes (${compressionRatio}% of original)`,
283277
)
284278

285-
console.log('🔤 Encoding as base64...')
279+
logger.progress('Encoding as base64')
286280
const wasmBase64 = wasmCompressed.toString('base64')
287-
console.log(` ✓ Encoded: ${wasmBase64.length} bytes\n`)
281+
logger.done(`Encoded: ${wasmBase64.length} bytes`)
288282

289283
// Generate socket-ai-sync.mjs.
290-
console.log('📝 Generating external/socket-ai-sync.mjs...')
284+
logger.progress('Generating external/socket-ai-sync.mjs')
291285

292286
const syncContent = `/**
293287
* Unified WASM Loader for Socket CLI AI Features
@@ -451,27 +445,25 @@ export function getEmbeddedSizes() {
451445
const outputPath = path.join(externalDir, 'socket-ai-sync.mjs')
452446
await fs.writeFile(outputPath, syncContent, 'utf-8')
453447

454-
console.log(` ✓ Generated ${outputPath}`)
455-
console.log(
456-
`File size: ${(syncContent.length / 1024 / 1024).toFixed(2)} MB\n`,
448+
logger.done(`Generated ${outputPath}`)
449+
logger.done(
450+
`File size: ${(syncContent.length / 1024 / 1024).toFixed(2)} MB`,
457451
)
458452

459-
console.log('╔═══════════════════════════════════════════════════╗')
460-
console.log('║ Build Complete ║')
461-
console.log('╚═══════════════════════════════════════════════════╝\n')
453+
logger.success('Build Complete')
462454

463-
console.log('📊 Summary:')
464-
console.log(
465-
` Original WASM: ${(wasmData.length / 1024 / 1024).toFixed(2)} MB`,
455+
logger.info('Summary:')
456+
logger.info(
457+
` Original WASM: ${(wasmData.length / 1024 / 1024).toFixed(2)} MB`,
466458
)
467-
console.log(
468-
` Compressed: ${(wasmCompressed.length / 1024 / 1024).toFixed(2)} MB`,
459+
logger.info(
460+
` Compressed: ${(wasmCompressed.length / 1024 / 1024).toFixed(2)} MB`,
469461
)
470-
console.log(` Base64: ${(wasmBase64.length / 1024 / 1024).toFixed(2)} MB`)
471-
console.log(
472-
`\n Total savings: ${((1 - wasmCompressed.length / wasmData.length) * 100).toFixed(1)}%`,
462+
logger.info(` Base64: ${(wasmBase64.length / 1024 / 1024).toFixed(2)} MB`)
463+
logger.info(
464+
` Total savings: ${((1 - wasmCompressed.length / wasmData.length) * 100).toFixed(1)}%`,
473465
)
474-
console.log('\nNext steps:')
475-
console.log(' 1. This file will be bundled into dist/cli.js by Rollup')
476-
console.log(' 2. Rollup output will be compressed to dist/cli.js.bz')
477-
console.log(' 3. Native stub or index.js will decompress and execute')
466+
logger.info('Next steps:')
467+
logger.info(' 1. This file will be bundled into dist/cli.js by Rollup')
468+
logger.info(' 2. Rollup output will be compressed to dist/cli.js.bz')
469+
logger.info(' 3. Native stub or index.js will decompress and execute')

0 commit comments

Comments
 (0)