|
1 | 1 | #!/usr/bin/env node |
2 | | -import('../dist/cli.js'); |
| 2 | +import { spawnSync } from 'node:child_process'; |
| 3 | +import { dirname, resolve } from 'node:path'; |
| 4 | +import { fileURLToPath } from 'node:url'; |
| 5 | + |
| 6 | +const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); |
| 7 | +const rebuildAttempted = process.env.NIGHT_WATCH_NATIVE_REBUILD_ATTEMPTED === '1'; |
| 8 | + |
| 9 | +function isBetterSqliteNativeMismatch(error) { |
| 10 | + const err = error ?? {}; |
| 11 | + const parts = [ |
| 12 | + err.code, |
| 13 | + err.message, |
| 14 | + err.stack, |
| 15 | + err.cause?.code, |
| 16 | + err.cause?.message, |
| 17 | + err.cause?.stack, |
| 18 | + ]; |
| 19 | + const text = parts.filter(Boolean).join('\n'); |
| 20 | + |
| 21 | + return ( |
| 22 | + text.includes('better_sqlite3.node') && |
| 23 | + (text.includes('NODE_MODULE_VERSION') || text.includes('ERR_DLOPEN_FAILED')) |
| 24 | + ); |
| 25 | +} |
| 26 | + |
| 27 | +function rebuildNativeSqlite() { |
| 28 | + const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm'; |
| 29 | + console.error( |
| 30 | + `[night-watch] Native SQLite module was built for a different Node.js version (${process.version}).`, |
| 31 | + ); |
| 32 | + console.error('[night-watch] Rebuilding better-sqlite3 for the current Node.js runtime...'); |
| 33 | + |
| 34 | + const result = spawnSync(npmBin, ['rebuild', 'better-sqlite3'], { |
| 35 | + cwd: packageRoot, |
| 36 | + env: { ...process.env, NIGHT_WATCH_NATIVE_REBUILD_ATTEMPTED: '1' }, |
| 37 | + stdio: 'inherit', |
| 38 | + }); |
| 39 | + |
| 40 | + if (result.error) { |
| 41 | + console.error(`[night-watch] Failed to start npm rebuild: ${result.error.message}`); |
| 42 | + process.exit(1); |
| 43 | + } |
| 44 | + |
| 45 | + if ((result.status ?? 1) !== 0) { |
| 46 | + console.error('[night-watch] Failed to rebuild better-sqlite3. Try reinstalling Night Watch:'); |
| 47 | + console.error(' npm install -g @jonit-dev/night-watch-cli'); |
| 48 | + process.exit(result.status ?? 1); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +async function run() { |
| 53 | + try { |
| 54 | + await import('../dist/cli.js'); |
| 55 | + } catch (error) { |
| 56 | + if (!isBetterSqliteNativeMismatch(error) || rebuildAttempted) { |
| 57 | + throw error; |
| 58 | + } |
| 59 | + |
| 60 | + rebuildNativeSqlite(); |
| 61 | + process.env.NIGHT_WATCH_NATIVE_REBUILD_ATTEMPTED = '1'; |
| 62 | + await import(`../dist/cli.js?native-rebuild=${Date.now()}`); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +await run(); |
0 commit comments