d3ro-voice/scripts/ci/verify-native-abi.mjs
Yun Chan fb5f76f57f fix(desktop): upgrade better-sqlite3 to 13 so the Electron 43 installer builds and opens its database
better-sqlite3 12.8.0 has no prebuild for Electron 43 (ABI 148) and does not compile against
its V8 API, so the v1.18.0 installer build stopped in fix-native-abi and was never published.
13.2.0 ships Node-API prebuilds in the package; one binary runs on Node and Electron.

- fix-native-abi.mjs: nothing to swap when the packaged module is a Node-API prebuild.
- verify-native-abi.mjs: require the target prebuild, fail on a shadowing build/Release binary,
  and open a database through the packaged module.
- electron-builder: leave out the linux prebuilds we do not ship.

Verified: desktop 2,933 tests on Node 24, and WAL/transaction/FTS5 queries in an Electron
43.8.10 main process.
2026-11-20 15:30:08 +09:00

239 lines
8.7 KiB
JavaScript

// scripts/ci/verify-native-abi.mjs
// 패키징된 Electron 앱의 네이티브 모이 "Electron ABI"로 빌드됐는지 검증한다.
//
// 배경(실측 사고): 설치본에 Node ABI(131)로 빌드된 better_sqlite3.node가 들어가
// 앱이 시작하자마자 "NODE_MODULE_VERSION 131 ... requires 130"으로 죽었다.
// 원인은 패키징에서 네이티브 재빌드를 건너뛴 것(npmRebuild=false)이었고, 조용히 지나갔다.
//
// 검증 방법: 호스트 Node로 모듈을 로드해 본다.
// - 로드 성공 → 호스트 Node ABI로 빌드된 것 = Electron용이 아님 → 실패
// - NODE_MODULE_VERSION 불일치로 거부 → 다른 런타임(Electron)용 = 통과
// - 파일 없음 → 실패
//
// 사용:
// node scripts/ci/verify-native-abi.mjs # release/<version>/win-unpacked 자동 탐색
// node scripts/ci/verify-native-abi.mjs --dir <packagedDir>
// node scripts/ci/verify-native-abi.mjs --self-test # 필수 prebuild 누락 fixture 검증
import { spawnSync } from 'node:child_process'
import {
existsSync,
mkdtempSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
/** N-API 기반이라 Electron ABI 재빌드는 불필요하지만, 대상 플랫폼 prebuild는 필수다. */
const REQUIRED_NAPI = [
{ name: 'uiohook-napi', binaryName: 'uiohook-napi.node' },
]
function inferPackagedTarget(directory) {
const directoryName = basename(directory)
if (directoryName === 'win-unpacked') return { platform: 'win32', arch: 'x64' }
const macDirectory = /^mac-(.+)$/.exec(directoryName)
if (macDirectory) return { platform: 'darwin', arch: macDirectory[1] }
if (directoryName === 'mac') return { platform: 'darwin', arch: process.arch }
return { platform: process.platform, arch: process.arch }
}
function requiredNapiResults(unpackedRoot, target) {
const failures = []
const notes = []
for (const module of REQUIRED_NAPI) {
const binaryPath = join(
unpackedRoot,
module.name,
'prebuilds',
`${target.platform}-${target.arch}`,
module.binaryName,
)
if (!existsSync(binaryPath)) {
failures.push(
`${module.name}: ${target.platform}-${target.arch} 필수 N-API prebuild가 없습니다 → ${binaryPath}`,
)
} else {
notes.push(
`${module.name}: ${target.platform}-${target.arch} 필수 N-API prebuild 존재 확인`,
)
}
}
return { failures, notes }
}
function runSelfTest() {
const fixtureRoot = mkdtempSync(join(tmpdir(), 'd3ro-native-abi-'))
const target = { platform: 'win32', arch: 'x64' }
const binaryPath = join(
fixtureRoot,
'uiohook-napi',
'prebuilds',
'win32-x64',
'uiohook-napi.node',
)
try {
const missing = requiredNapiResults(fixtureRoot, target)
if (missing.failures.length !== 1 || !missing.failures[0].includes(binaryPath)) {
throw new Error('누락된 win32-x64 prebuild가 실패로 고정되지 않았습니다.')
}
mkdirSync(dirname(binaryPath), { recursive: true })
writeFileSync(binaryPath, 'fixture')
const present = requiredNapiResults(fixtureRoot, target)
if (present.failures.length !== 0 || present.notes.length !== 1) {
throw new Error('존재하는 win32-x64 prebuild fixture가 통과하지 못했습니다.')
}
console.log('[native-abi] SELF-TEST GREEN — win32-x64 prebuild 누락/존재 계약 확인')
} finally {
rmSync(fixtureRoot, { recursive: true, force: true })
}
}
if (process.argv.includes('--self-test')) {
runSelfTest()
process.exit(0)
}
const dirFlagIndex = process.argv.indexOf('--dir')
let packagedDir =
dirFlagIndex >= 0 && process.argv[dirFlagIndex + 1]
? resolve(process.argv[dirFlagIndex + 1])
: null
if (!packagedDir) {
const version = JSON.parse(
readFileSync(join(root, 'release', 'product-version.json'), 'utf8'),
).version
const releaseDir = join(root, 'apps', 'desktop', 'release', version)
if (existsSync(releaseDir)) {
const candidates = readdirSync(releaseDir).filter((name) =>
/unpacked$/.test(name) || name === 'win-unpacked' || name === 'mac-arm64',
)
if (candidates.length > 0) {
packagedDir = join(releaseDir, candidates[0])
}
}
}
if (!packagedDir || !existsSync(packagedDir)) {
console.error(
'패키징 산출물 디렉토리를 찾을 수 없습니다. --dir로 지정하세요 (예: apps/desktop/release/1.3.3/win-unpacked).',
)
process.exit(1)
}
const unpackedRoot = join(packagedDir, 'resources', 'app.asar.unpacked', 'node_modules')
/** Electron ABI(V8 내부 API)에 의존해 재빌드가 반드시 필요한 모듈 */
const REQUIRED_ELECTRON_ABI = [
{
name: 'better-sqlite3',
binary: join('better-sqlite3', 'build', 'Release', 'better_sqlite3.node'),
},
]
const failures = []
const notes = []
const packagedTarget = inferPackagedTarget(packagedDir)
/**
* better-sqlite3 13+ 는 Node-API 프리빌드를 패키지에 싣는다 (prebuilds/<platform>-<arch>.node).
* Node-API 는 런타임 ABI 에 묶이지 않으므로 "호스트 Node 가 거부해야 통과" 규칙이 뒤집힌다:
* 대상 플랫폼 프리빌드가 있어야 하고, 호스트와 같은 플랫폼이면 실제로 열어 질의까지 해 본다.
* build/Release 바이너리가 함께 있으면 로더가 그것을 먼저 집으므로(옛 ABI 종속 빌드) 실패로 본다.
*/
function verifyNapiSqlite(moduleDir) {
const prebuild = join(moduleDir, 'prebuilds', `${packagedTarget.platform}-${packagedTarget.arch}.node`)
if (!existsSync(prebuild)) return null
if (existsSync(join(moduleDir, 'build', 'Release', 'better_sqlite3.node'))) {
return { failure: 'better-sqlite3: Node-API 프리빌드와 build/Release 바이너리가 함께 있습니다 — 로더가 옛 빌드를 먼저 집습니다.' }
}
if (packagedTarget.platform !== process.platform || packagedTarget.arch !== process.arch) {
return { note: `better-sqlite3: ${packagedTarget.platform}-${packagedTarget.arch} Node-API 프리빌드 존재 확인` }
}
const probe = spawnSync(
process.execPath,
[
'-e',
`const D=require(${JSON.stringify(moduleDir)});const d=new D(':memory:');` +
`if(d.prepare('select 1 as one').get().one!==1)process.exit(3);d.close()`,
],
{ encoding: 'utf8' },
)
if (probe.status !== 0) {
const output = `${probe.stdout ?? ''}${probe.stderr ?? ''}`.trim().split(String.fromCharCode(10)).slice(0, 3).join(' | ')
return { failure: `better-sqlite3: 패키징된 Node-API 모듈이 열리지 않습니다 → ${output}` }
}
return { note: 'better-sqlite3: 패키징된 Node-API 모듈로 DB 를 열고 질의함 (런타임 ABI 무관)' }
}
for (const module of REQUIRED_ELECTRON_ABI) {
if (module.name === 'better-sqlite3') {
const napi = verifyNapiSqlite(join(unpackedRoot, 'better-sqlite3'))
if (napi) {
if (napi.failure) failures.push(napi.failure)
else notes.push(napi.note)
continue
}
}
const binaryPath = join(unpackedRoot, module.binary)
if (!existsSync(binaryPath)) {
failures.push(`${module.name}: 패키징된 네이티브 바이너리가 없습니다 → ${binaryPath}`)
continue
}
// 호스트 Node로 로드 시도: 성공하면 Electron ABI가 아니다.
const probe = spawnSync(
process.execPath,
['-e', `require(${JSON.stringify(binaryPath.replace(/\\/g, '\\\\'))})`],
{ encoding: 'utf8' },
)
const output = `${probe.stdout ?? ''}${probe.stderr ?? ''}`
if (probe.status === 0) {
failures.push(
[
`${module.name}: 호스트 Node에서 로드됩니다 = Electron ABI가 아니다.`,
' 패키징 전에 Electron용으로 재빌드해야 합니다 (electron-builder npmRebuild=true,',
' 또는 `npx @electron/rebuild -v <electronVersion>`).',
].join('\n'),
)
continue
}
if (/NODE_MODULE_VERSION/.test(output)) {
notes.push(`${module.name}: Electron ABI 확인 (${output.split('\n')[0].slice(0, 80)})`)
} else {
failures.push(`${module.name}: 알 수 없는 오류로 로드 실패 → ${output.split('\n')[0]}`)
}
}
const napiResults = requiredNapiResults(unpackedRoot, packagedTarget)
failures.push(...napiResults.failures)
notes.push(...napiResults.notes)
for (const note of notes) console.log(`[native-abi] ${note}`)
if (failures.length > 0) {
console.error('[native-abi] 검증 실패:')
for (const failure of failures) console.error(` - ${failure}`)
process.exit(1)
}
console.log('[native-abi] GREEN — 패키징된 네이티브 모듈이 Electron에서 실행 가능한 ABI입니다.')