Files
SnowLuma/packages/core/vite.config.ts
T
DrSmoothl 4e51b4bd7d build(sqlite): wrap better-sqlite3 with @snowluma/sqlite + vendor prebuilts
Replaces "runtime npm dependency that gets `npm install`-ed into
dist/" with "TS wrapper that loads the native `.node` from
`dist/native/` like every other native binding in the project".

Why the change
--------------
The previous approach (better-sqlite3 declared in
packages/runtime/package.json, materialized by `npm install
--omit=dev` in dist/) worked but produced an artifact that needed
runtime npm install — a step the rest of SnowLuma's native bindings
don't need (websocket / snowluma-hook / ffmpeg are all standalone
`.node` files copied into `dist/native/` by vite-plugin-cp). The
asymmetry was friction: dev mode required `pnpm dist:install`,
build artifacts carried a `dist/node_modules/` tree the other
modules didn't need, and Docker images had to special-case the
glibc-vs-musl ABI lookup that prebuild-install runs.

The new shape:
  - `@snowluma/sqlite` (packages/sqlite/) — TS wrapper. Has
    `better-sqlite3` as a devDep (for the JS-layer types + the
    actual JS wrapper code that vite inlines). At runtime, calls
    `createRequire().require()` against
    `<dist|repo>/native/better-sqlite3-v<abi>-<platform>-<arch>.node`
    and passes the resolved addon to `new Database(path, {
    nativeBinding })`.
  - `packages/runtime/native/better-sqlite3-v<abi>-<triplet>.node`
    — prebuilt binaries vendored into the repo. Two ABIs ship side-
    by-side (v127 = Node 22 LTS used by CI, v137 = Node 24 used by
    dev boxes) so `process.versions.modules` picks the matching one
    at load time.
  - `tools/fetch-sqlite-prebuilts.mjs` — fetches all 5 platforms ×
    N ABIs from WiseLibs's GitHub releases. Idempotent: existing
    `.node` files skip. Accepts extra ABI args:
    `node tools/fetch-sqlite-prebuilts.mjs 12.10.0 v127 v137 v115`.

What was unwound
----------------
- packages/runtime/package.json — dependencies removed (runtime
  artifact is now self-contained, no `npm install` step needed).
- root package.json — `dist:install` script removed (no node_modules
  to install).
- .github/workflows/dev-build.yml — `Bundle runtime dependencies`
  step removed.
- .github/workflows/release.yml — kept the `Bundle runtime
  dependencies` step (was a no-op already, but harmless safety net
  in case a future runtime dep shows up).
- packages/core/vite.config.ts — `better-sqlite3` no longer
  external; vite inlines the JS wrapper (+~33 KB to bundle, ~2.84
  MB → 2.87 MB total).

Naming
------
Mirrors the existing `websocket-${triplet}.node` convention (flat
dir under `runtime/native/`, dash-separated `<platform>-<arch>`).
Adds a `v<abi>` segment because better-sqlite3 is NOT N-API — one
binary per Node ABI. Naming:

  better-sqlite3-v127-darwin-arm64.node    Node 22 / macOS arm
  better-sqlite3-v127-darwin-x64.node      Node 22 / macOS intel
  better-sqlite3-v127-linux-arm64.node     Node 22 / Linux arm
  better-sqlite3-v127-linux-x64.node       Node 22 / Linux x64
  better-sqlite3-v127-win32-x64.node       Node 22 / Windows x64
  better-sqlite3-v137-... (5)              Node 24 / same 5 hosts

Total: 10 binaries × ~1.9 MB = ~19 MB committed. Aligned with the
existing native-vendoring footprint (websocket ~2 MB × 5, snowluma-
hook ~10 MB × Windows + Linux, ffmpeg ~10-30 MB × 4).

What changes for consumers
--------------------------
Source-side: nothing. `import Database, { type Database, type
Statement } from '@snowluma/sqlite'` is a drop-in for the previous
`import Database from 'better-sqlite3'`. The wrapper re-exports the
same types and the `Database` callable factory has the same
overload set.

Runtime: `node` finds the binding at
`<dist|repo>/native/better-sqlite3-v${process.versions.modules}-
${process.platform}-${process.arch}.node`. If the ABI doesn't
match a vendored binary, the wrapper throws a clear error pointing
at `tools/fetch-sqlite-prebuilts.mjs` with the missing ABI/triplet.

Bumped better-sqlite3 from 11.10.0 → 12.10.0 because v11 only had
prebuilt up to Node ABI v127 (no v137 = no Node 24). v12.10.0
ships both. Both versions are API-compat (the breaking changes
between v11 and v12 were either internal or in error-handling
paths SnowLuma doesn't exercise).

Verification
------------
- pnpm -r typecheck (12 projects): clean
- @snowluma/core test: 302/302
- @snowluma/onebot test: 250/250 (552/552 combined, unchanged from
  the perf-series baseline)
- Bench numbers preserved — wrapper indirection is sub-μs:
  storeMeta ~11 μs, storeEvent ~17 μs, findMeta hit ~1.1 μs (all
  within noise of the post-RoadMap-#5 measurements).
- Vite build clean, bundle = 2.87 MB / 230 KB gzip
- `dist/index.mjs` no longer contains a `node:sqlite` import (it
  did before — media-store hadn't migrated; now neither it nor
  message-store reach into the Node builtin).

Bonus side-fix: `packages/onebot/src/media-store.ts` also moved
off `node:sqlite` (caught by the post-build bundle grep — the
file was using `DatabaseSync` + `StatementSync` from the builtin
even though it had already been written to cache its prepared
statements). Its hot paths now go through the same wrapper.
2026-05-21 13:49:19 +08:00

168 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
import protobufVitePlugin from '@snowluma/proton/vite';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
const distDir = path.resolve(repoRoot, 'dist');
const runtimeDir = path.resolve(repoRoot, 'packages', 'runtime');
const nativeDir = path.resolve(runtimeDir, 'native');
// Single source of truth for the user-facing app version: monorepo root package.json.
const rootPkg = JSON.parse(
fs.readFileSync(path.resolve(repoRoot, 'package.json'), 'utf-8'),
) as { version: string };
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
// in-tree TS workspace wrappers that route their native `.node`
// addons through `dist/native/`. Only Node builtins stay external;
// the actual `better-sqlite3` JS wrapper is pulled in via the
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
const external: string[] = [];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
const runtimeSrc = toPosix(runtimeDir);
const nativeSrc = toPosix(nativeDir);
// Target selection: `SNOWLUMA_TARGET=<platform>-<arch>` overrides the host
// detection, enabling cross-target packaging on CI.
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
const [targetPlatform, targetArch] = targetTriple.split('-');
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
// so its launcher/shell script differ per target.
const runtimeDistFiles = ['package.json',
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
];
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
// by @snowluma/sqlite. Two ABIs
// vendored side-by-side
// (v127 = Node 22 LTS, v137 =
// Node 24) so the runtime can
// pick whichever matches the
// host's `process.versions.modules`.
// Vendored via
// `tools/fetch-sqlite-prebuilts.mjs`
// from WiseLibs's prebuild releases.
const SQLITE_ABIS = ['v127', 'v137'];
const nativeFiles = [
`websocket-${targetTriple}.node`,
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),
...(targetPlatform === 'linux'
? [`snowluma-${targetTriple}.node`, `snowluma-${targetTriple}.so`]
: []),
];
// FFmpeg native addon ported from NapCat. Uses NapCat's
// `<platform>.<arch>` naming so the prebuilt binaries can be vendored
// as-is without renaming. Lives under `native/ffmpeg/` to keep it
// separate from the SnowLuma flat-naming addons above.
const ffmpegAddonFile = `ffmpegAddon.${targetPlatform}.${targetArch}.node`;
const ffmpegSrcDir = path.resolve(nativeDir, 'ffmpeg');
// Fail fast if any expected native binary is missing from packages/runtime/native/.
// vite-plugin-cp only emits a warning on missing source files; we want a hard
// error so CI can't accidentally ship an incomplete archive.
const missingNatives = nativeFiles.filter(
(f) => !fs.existsSync(path.join(nativeDir, f)),
);
if (!fs.existsSync(path.join(ffmpegSrcDir, ffmpegAddonFile))) {
missingNatives.push(`ffmpeg/${ffmpegAddonFile}`);
}
if (missingNatives.length > 0) {
throw new Error(
`Missing native binaries for target ${targetTriple}:\n` +
missingNatives.map((f) => ` - ${path.join(nativeDir, f)}`).join('\n'),
);
}
const BaseConfigPlugin: PluginOption[] = [
// Proton substitutes every `protobuf_encode<T>` / `protobuf_decode<T>`
// call site with a monomorphized codec at build time. WITHOUT this
// plugin in the plugins array the runtime fallback in
// `@snowluma/proton/runtime.ts` throws on the first call (and the
// packaged Win/Linux release does exactly that). It MUST appear
// before `cp` so the transform runs on every source file Vite asks
// for, regardless of where `cp` later copies emitted assets.
protobufVitePlugin(),
cp({
targets: [
...runtimeDistFiles.map((file) => ({
src: `${runtimeSrc}/${file}`,
dest: distDir,
flatten: true,
})),
...nativeFiles.map((f) => ({
src: `${nativeSrc}/${f}`,
dest: path.join(distDir, 'native'),
flatten: true,
})),
{
src: `${toPosix(ffmpegSrcDir)}/${ffmpegAddonFile}`,
dest: path.join(distDir, 'native', 'ffmpeg'),
flatten: true,
},
]
})
];
const BaseConfig = (source_map: boolean = false) => defineConfig({
resolve: {
conditions: ['node', 'default'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
build: {
sourcemap: source_map,
target: 'esnext',
minify: false,
lib: {
entry: {
index: path.resolve(__dirname, 'src/index.ts')
},
formats: ['es'],
fileName: (_, entryName) => `${entryName}.mjs`
},
rollupOptions: {
external: [...nodeModules, ...external]
},
// Emit to monorepo root dist/ so the existing release pipeline keeps working.
outDir: distDir,
// Required since outDir is outside the vite project root.
emptyOutDir: true
},
define: {
__BUILD_WEBUI__: process.env.BUILD_WEBUI === 'true',
__APP_VERSION__: JSON.stringify(rootPkg.version)
}
});
export default defineConfig(({ mode }): UserConfig => {
if (mode === 'development') {
return {
...BaseConfig(true),
plugins: [...BaseConfigPlugin]
};
}
return {
...BaseConfig(),
plugins: [...BaseConfigPlugin]
};
});