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.
This commit is contained in:
25 files changed
+356
-76
No files matched your search
@@ -110,17 +110,6 @@ jobs:
|
||||
SNOWLUMA_TARGET: ${{ matrix.target }}
|
||||
run: pnpm run build:all
|
||||
|
||||
# Materialize `dist/node_modules/` for runtime-only externals
|
||||
# listed in `packages/runtime/package.json::dependencies`
|
||||
# (currently: better-sqlite3 — native binding can't be inlined
|
||||
# by vite). Mirrors the same step in `release.yml`. Runs npm
|
||||
# (not pnpm) deliberately so the install produces a flat
|
||||
# `node_modules/` tree with no symlinks, which is what the
|
||||
# bundled `index.mjs::require('better-sqlite3')` expects.
|
||||
- name: Bundle runtime dependencies
|
||||
working-directory: dist
|
||||
run: npm install --omit=dev
|
||||
|
||||
# Naming convention:
|
||||
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
|
||||
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"build:webui": "pnpm --filter webui build",
|
||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
|
||||
"dev": "pnpm --filter @snowluma/core dev",
|
||||
"dist:install": "cd dist && npm install --omit=dev",
|
||||
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||
"dev:web": "pnpm --filter webui dev",
|
||||
"test": "pnpm --filter @snowluma/core test",
|
||||
|
||||
@@ -120,10 +120,9 @@
|
||||
"@snowluma/common": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"better-sqlite3": "^11.7.0"
|
||||
"@snowluma/sqlite": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:",
|
||||
"vite": "catalog:",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import Database from 'better-sqlite3';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
|
||||
import type {
|
||||
FriendInfo, GroupMemberInfo, QQGroupInfo,
|
||||
@@ -109,14 +109,14 @@ export class IdentityService {
|
||||
private readonly uidByUin = new Map<number, string>();
|
||||
|
||||
// ─── Persistence + fetcher ───
|
||||
private readonly db: Database.Database | null;
|
||||
private readonly db: DatabaseType | null;
|
||||
// Prepared-statement cache. Every `.prepare(sql)` call in this
|
||||
// service re-parses the SQL — that's the SQLite anti-pattern
|
||||
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
|
||||
// call sites stay readable (no need to enumerate 20+ named fields
|
||||
// upfront); the Map lookup is O(1) hash + string-eq, which is
|
||||
// negligible next to the SQL parse it replaces.
|
||||
private readonly stmtCache_ = new Map<string, Database.Statement>();
|
||||
private readonly stmtCache_ = new Map<string, Statement>();
|
||||
private inTransaction = false;
|
||||
private fetcher: IdentityFetcher | null = null;
|
||||
private readonly log: Logger;
|
||||
@@ -143,7 +143,7 @@ export class IdentityService {
|
||||
|
||||
/** Cached `prepare(sql)`. First call per unique SQL parses; later
|
||||
* calls reuse the same `Statement` object. See `stmtCache_`. */
|
||||
private pstmt(sql: string): Database.Statement {
|
||||
private pstmt(sql: string): Statement {
|
||||
let cached = this.stmtCache_.get(sql);
|
||||
if (cached !== undefined) return cached;
|
||||
cached = this.db!.prepare(sql);
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
"@snowluma/onebot": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -20,13 +20,12 @@ const rootPkg = JSON.parse(
|
||||
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
// `@snowluma/websocket` is bundled (it's an in-tree TS workspace package), so
|
||||
// it must NOT be marked external. `better-sqlite3` IS native — must be
|
||||
// external so its `require('./build/Release/better_sqlite3.node')`
|
||||
// stays a runtime import. Vendoring the prebuilt binding into
|
||||
// `packages/runtime/native/` is handled by the per-target packaging
|
||||
// step (see `nativeFiles` below).
|
||||
const external: string[] = ['better-sqlite3'];
|
||||
// `@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();
|
||||
|
||||
@@ -45,10 +44,22 @@ const runtimeDistFiles = ['package.json',
|
||||
];
|
||||
|
||||
// Native binaries shipped for the selected target:
|
||||
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
|
||||
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
|
||||
// * `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`]
|
||||
: []),
|
||||
|
||||
@@ -91,12 +91,11 @@
|
||||
"@snowluma/core": "workspace:*",
|
||||
"@snowluma/proto-defs": "workspace:*",
|
||||
"@snowluma/proton": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*",
|
||||
"better-sqlite3": "^11.7.0"
|
||||
"@snowluma/sqlite": "workspace:*",
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"hono": "^4.12.14",
|
||||
"typescript": "catalog:",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
|
||||
|
||||
import fs from 'fs';
|
||||
import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import path from 'path';
|
||||
|
||||
import type { MessageElement } from '@snowluma/bridge/events';
|
||||
@@ -80,17 +80,17 @@ const TYPE_VIDEO = 'video';
|
||||
const DEFAULT_KEEP_ENTRIES = 4096;
|
||||
|
||||
export class MediaStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly db: DatabaseType;
|
||||
private readonly maxEntriesPerType: number;
|
||||
|
||||
// Prepared statements (pay the parsing cost once at startup).
|
||||
private readonly upsertEntry: StatementSync;
|
||||
private readonly upsertKey: StatementSync;
|
||||
private readonly findEntryByKey: StatementSync;
|
||||
private readonly findEntryByPrimary: StatementSync;
|
||||
private readonly evictByType: StatementSync;
|
||||
private readonly purgeOrphanKeys: StatementSync;
|
||||
private readonly countByType: StatementSync;
|
||||
private readonly upsertEntry: Statement;
|
||||
private readonly upsertKey: Statement;
|
||||
private readonly findEntryByKey: Statement;
|
||||
private readonly findEntryByPrimary: Statement;
|
||||
private readonly evictByType: Statement;
|
||||
private readonly purgeOrphanKeys: Statement;
|
||||
private readonly countByType: Statement;
|
||||
|
||||
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
|
||||
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
|
||||
@@ -98,9 +98,9 @@ export class MediaStore {
|
||||
const dir = path.dirname(dbPath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
this.db = new DatabaseSync(dbPath);
|
||||
this.db.exec('PRAGMA journal_mode = WAL');
|
||||
this.db.exec('PRAGMA synchronous = NORMAL');
|
||||
this.db = new Database(dbPath);
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
this.initSchema();
|
||||
|
||||
this.upsertEntry = this.db.prepare(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'fs';
|
||||
import Database from 'better-sqlite3';
|
||||
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
|
||||
import path from 'path';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
|
||||
@@ -17,15 +17,15 @@ import type { JsonObject, MessageMeta } from './types';
|
||||
// deployed wrapper that proposes the same prepared-statement model.
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: Database.Database;
|
||||
private readonly stmtStoreEvent: Database.Statement;
|
||||
private readonly stmtStoreMeta: Database.Statement;
|
||||
private readonly stmtFindEvent: Database.Statement;
|
||||
private readonly stmtFindMeta: Database.Statement;
|
||||
private readonly stmtResolveReplyGroup: Database.Statement;
|
||||
private readonly stmtResolveReplyPrivate: Database.Statement;
|
||||
private readonly stmtListEventsAnchored: Database.Statement;
|
||||
private readonly stmtListEventsLatest: Database.Statement;
|
||||
private readonly db: DatabaseType;
|
||||
private readonly stmtStoreEvent: Statement;
|
||||
private readonly stmtStoreMeta: Statement;
|
||||
private readonly stmtFindEvent: Statement;
|
||||
private readonly stmtFindMeta: Statement;
|
||||
private readonly stmtResolveReplyGroup: Statement;
|
||||
private readonly stmtResolveReplyPrivate: Statement;
|
||||
private readonly stmtListEventsAnchored: Statement;
|
||||
private readonly stmtListEventsLatest: Statement;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
const dir = path.dirname(dbPath);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -4,8 +4,5 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). vite-plugin-cp copies this package.json into dist/, then the release workflow runs `npm install --omit=dev` inside dist/ to materialize the production node_modules. Dependencies listed here are the runtime-only externals that vite did NOT bundle into index.mjs (currently: better-sqlite3 — native binding, can't be inlined).",
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.7.0"
|
||||
}
|
||||
"description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). All native bindings ship as standalone `.node` files in `dist/native/` — loaded via `process.dlopen()` / `createRequire().require()` from inside the bundle. There are intentionally NO runtime npm dependencies; production artifacts are self-contained."
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@snowluma/sqlite",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/<platform>-<arch>/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^24.12.2",
|
||||
"better-sqlite3": "12.10.0",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// @snowluma/sqlite — wraps better-sqlite3 so the native `.node` binding
|
||||
// is loaded from
|
||||
// `dist/native/better-sqlite3-v<abi>-<platform>-<arch>.node` instead
|
||||
// of `node_modules/better-sqlite3/build/Release/`. This lets the
|
||||
// production artifact ship as a single self-contained `dist/`
|
||||
// directory (no `dist/node_modules/`, no `npm install --omit=dev`
|
||||
// step) — the same pattern SnowLuma already uses for its
|
||||
// `websocket-<platform>-<arch>.node` and `snowluma-*.{dll,node,so}`
|
||||
// addons (flat dir, dash-separated triplet).
|
||||
//
|
||||
// How it works:
|
||||
// 1. better-sqlite3's `Database` constructor accepts a `nativeBinding`
|
||||
// option (string path or already-`require()`-ed object) that
|
||||
// overrides the default `require('bindings')('better_sqlite3.node')`
|
||||
// lookup. We forward through every other option/argument
|
||||
// verbatim and inject this one.
|
||||
// 2. The vendored `.node` lives at one of two locations depending
|
||||
// on whether we're in dev (workspace TS source) or production
|
||||
// (bundled into dist/native/):
|
||||
// - Prod: `<dist>/native/better-sqlite3-v<abi>-<triplet>.node`
|
||||
// - Dev: `<repo>/packages/runtime/native/better-sqlite3-v<abi>-<triplet>.node`
|
||||
// We probe both paths and take whichever exists.
|
||||
// 3. `<triplet>` is `<process.platform>-<process.arch>` (e.g.
|
||||
// `darwin-arm64`, `linux-x64`, `linux-arm64`, `win32-x64`).
|
||||
// 4. `<abi>` is `process.versions.modules` (NODE_MODULE_VERSION).
|
||||
// better-sqlite3 is NOT N-API — its binding is locked to one
|
||||
// Node ABI per build. Vendoring `vNNN` in the filename lets us
|
||||
// ship multiple ABIs side-by-side (e.g. v127 for Node 22 LTS
|
||||
// shipped to CI, v137 for Node 24 used by some dev boxes).
|
||||
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { existsSync } from 'node:fs';
|
||||
import BetterSqlite3 from 'better-sqlite3';
|
||||
|
||||
// Re-export the public types/classes consumers need. `Database` and
|
||||
// `Statement` come straight from better-sqlite3 — we only intercept
|
||||
// the constructor at call time, not the class shape.
|
||||
export type { Database, Statement, RunResult, Options } from 'better-sqlite3';
|
||||
|
||||
function triplet(): string {
|
||||
return `${process.platform}-${process.arch}`;
|
||||
}
|
||||
|
||||
function abi(): string {
|
||||
// `process.versions.modules` is the NODE_MODULE_VERSION the running
|
||||
// Node binary expects — e.g. "127" for Node 22, "137" for Node 24.
|
||||
// Stays in sync with whatever the host actually does at load time.
|
||||
return `v${process.versions.modules}`;
|
||||
}
|
||||
|
||||
function locateBinding(): string {
|
||||
const tri = triplet();
|
||||
const fileName = `better-sqlite3-${abi()}-${tri}.node`;
|
||||
// Two candidate locations, tried in order:
|
||||
// 1. Production: dist/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to dist/ at runtime (the wrapper
|
||||
// is bundled into index.mjs alongside it).
|
||||
// 2. Dev: <repo>/packages/runtime/native/better-sqlite3-<triplet>.node
|
||||
// — `import.meta.url` resolves to packages/sqlite/src/index.ts;
|
||||
// walk up to repo root + into runtime/native.
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const distCandidate = join(here, 'native', fileName);
|
||||
if (existsSync(distCandidate)) return distCandidate;
|
||||
|
||||
// From packages/sqlite/src ⇢ go up to packages/, then into
|
||||
// runtime/native. (Two `..` segments, not three — `src` → `sqlite/`
|
||||
// → `packages/`, then descend into `runtime/native`.)
|
||||
const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName);
|
||||
if (existsSync(devCandidate)) return devCandidate;
|
||||
|
||||
throw new Error(
|
||||
`@snowluma/sqlite: could not locate ${fileName}. ` +
|
||||
`Tried:\n ${distCandidate}\n ${devCandidate}\n` +
|
||||
`Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Load the native addon once at module import — keeping it module-
|
||||
// scoped so the require() cost is paid exactly once per process.
|
||||
let addon: unknown | null = null;
|
||||
function loadAddon(): unknown {
|
||||
if (addon) return addon;
|
||||
const bindingPath = locateBinding();
|
||||
// better-sqlite3 expects the addon to be loaded via the CJS
|
||||
// require() mechanism (N-API init runs through it). createRequire
|
||||
// is the ESM-safe way to do that with an absolute path.
|
||||
const req = createRequire(import.meta.url);
|
||||
addon = req(bindingPath);
|
||||
return addon;
|
||||
}
|
||||
|
||||
// Drop-in `Database` factory. Matches the better-sqlite3 default-
|
||||
// export signature exactly: `new Database(filename[, options])` →
|
||||
// `Database` instance.
|
||||
//
|
||||
// We can't just `class extends BetterSqlite3` because better-sqlite3's
|
||||
// default export is a function that returns the instance (the `new
|
||||
// Database(...)` shape works through that function's `new.target`
|
||||
// check). Wrapping at the function-call boundary keeps that contract
|
||||
// intact.
|
||||
type BetterSqlite3Type = typeof BetterSqlite3;
|
||||
type DatabaseInstance = InstanceType<BetterSqlite3Type>;
|
||||
type DatabaseOptions = ConstructorParameters<BetterSqlite3Type>[1];
|
||||
|
||||
const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance {
|
||||
const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions;
|
||||
// The `as any` shrug here is unavoidable — better-sqlite3's
|
||||
// overload set declares `new Database(...)` returns the class type
|
||||
// but its default export is a callable that *also* returns it via
|
||||
// an internal `new.target == null` branch. TS can't reconcile the
|
||||
// two without `as any`.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new (BetterSqlite3 as any)(filename, opts);
|
||||
} as unknown as BetterSqlite3Type;
|
||||
|
||||
export default Database;
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
Generated
+29
-20
@@ -59,13 +59,10 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
better-sqlite3:
|
||||
specifier: ^11.7.0
|
||||
version: 11.10.0
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
devDependencies:
|
||||
'@types/better-sqlite3':
|
||||
specifier: ^7.6.13
|
||||
version: 7.6.13
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
@@ -105,6 +102,9 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
@@ -157,19 +157,16 @@ importers:
|
||||
'@snowluma/proton':
|
||||
specifier: workspace:*
|
||||
version: link:../proton
|
||||
'@snowluma/sqlite':
|
||||
specifier: workspace:*
|
||||
version: link:../sqlite
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
better-sqlite3:
|
||||
specifier: ^11.7.0
|
||||
version: 11.10.0
|
||||
devDependencies:
|
||||
'@hono/node-server':
|
||||
specifier: ^1.19.14
|
||||
version: 1.19.14([email protected])
|
||||
'@types/better-sqlite3':
|
||||
specifier: ^7.6.13
|
||||
version: 7.6.13
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
@@ -218,11 +215,7 @@ importers:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
packages/runtime:
|
||||
dependencies:
|
||||
better-sqlite3:
|
||||
specifier: ^11.7.0
|
||||
version: 11.10.0
|
||||
packages/runtime: {}
|
||||
|
||||
packages/sdk:
|
||||
devDependencies:
|
||||
@@ -236,6 +229,21 @@ importers:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
packages/sqlite:
|
||||
devDependencies:
|
||||
'@types/better-sqlite3':
|
||||
specifier: ^7.6.13
|
||||
version: 7.6.13
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
better-sqlite3:
|
||||
specifier: 12.10.0
|
||||
version: 12.10.0
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
|
||||
packages/ui:
|
||||
dependencies:
|
||||
'@radix-ui/react-alert-dialog':
|
||||
@@ -1839,8 +1847,9 @@ packages:
|
||||
engines: {node: '>=6.0.0'}
|
||||
hasBin: true
|
||||
|
||||
better-sqlite3@11.10.0:
|
||||
resolution: {integrity: sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==}
|
||||
better-sqlite3@12.10.0:
|
||||
resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==}
|
||||
engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
|
||||
@@ -4192,7 +4201,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
better-sqlite3@11.10.0:
|
||||
better-sqlite3@12.10.0:
|
||||
dependencies:
|
||||
bindings: 1.5.0
|
||||
prebuild-install: 7.1.3
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env node
|
||||
// Downloads better-sqlite3 prebuilt native bindings for all SnowLuma
|
||||
// CI matrix targets (win32-x64, linux-x64, linux-arm64) plus the
|
||||
// developer host (darwin-arm64 / darwin-x64) and vendors them into
|
||||
// `packages/runtime/native/better-sqlite3-<platform>-<arch>.node`.
|
||||
//
|
||||
// vite-plugin-cp picks the matching binary for `SNOWLUMA_TARGET`
|
||||
// during `pnpm build` and copies it into `dist/native/`, where
|
||||
// `@snowluma/sqlite/index.ts` finds it at runtime. Naming + layout
|
||||
// mirror the existing `websocket-<platform>-<arch>.node` convention
|
||||
// (flat dir, dash-separated triplet) so SnowLuma's existing
|
||||
// per-target packaging step doesn't need a new code path.
|
||||
//
|
||||
// Usage:
|
||||
// node tools/fetch-sqlite-prebuilts.mjs # default version
|
||||
// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 # explicit version
|
||||
//
|
||||
// Re-run when bumping the better-sqlite3 pin in
|
||||
// `packages/sqlite/package.json`. The script is idempotent —
|
||||
// existing binaries with the same SHA256 are left alone.
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = join(__dirname, '..');
|
||||
const nativeRoot = join(repoRoot, 'packages', 'runtime', 'native');
|
||||
|
||||
// Default NODE_MODULE_VERSIONs to vendor. v127 = Node 22 LTS (matches
|
||||
// the CI matrix + `engines.node: ">=22"`). v137 = Node 24 (covers dev
|
||||
// boxes already on the newer release). Pass extra versions positionally
|
||||
// after the better-sqlite3 version to add more:
|
||||
// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 v127 v137 v115
|
||||
const DEFAULT_NODE_ABIS = ['v127', 'v137'];
|
||||
|
||||
// The targets vendored into the repo. linuxmusl-* variants are
|
||||
// available too (for Alpine-based Docker images) but SnowLuma's
|
||||
// existing native vendoring (websocket / ffmpeg) only ships glibc
|
||||
// Linux, so we follow that lead. Add musl entries here if/when a
|
||||
// downstream Alpine consumer asks.
|
||||
const TARGETS = [
|
||||
{ triplet: 'darwin-arm64', prebuildName: 'darwin-arm64' },
|
||||
{ triplet: 'darwin-x64', prebuildName: 'darwin-x64' },
|
||||
{ triplet: 'linux-arm64', prebuildName: 'linux-arm64' },
|
||||
{ triplet: 'linux-x64', prebuildName: 'linux-x64' },
|
||||
{ triplet: 'win32-x64', prebuildName: 'win32-x64' },
|
||||
];
|
||||
|
||||
async function main() {
|
||||
const version = process.argv[2] ?? readVersionFromPin();
|
||||
const abis = process.argv.slice(3).filter(a => a.startsWith('v'));
|
||||
const targetAbis = abis.length > 0 ? abis : DEFAULT_NODE_ABIS;
|
||||
console.log(`fetching better-sqlite3 v${version} prebuilds (ABIs: ${targetAbis.join(', ')})`);
|
||||
|
||||
mkdirSync(nativeRoot, { recursive: true });
|
||||
for (const abi of targetAbis) {
|
||||
for (const target of TARGETS) {
|
||||
const destBin = join(nativeRoot, `better-sqlite3-${abi}-${target.triplet}.node`);
|
||||
if (existsSync(destBin)) {
|
||||
console.log(` ✓ ${abi} ${target.triplet} (already vendored, skipping)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const url = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${version}/better-sqlite3-v${version}-node-${abi}-${target.prebuildName}.tar.gz`;
|
||||
console.log(` ↓ ${abi} ${target.triplet}: ${url}`);
|
||||
|
||||
const tarPath = join(tmpdir(), `better-sqlite3-${version}-${abi}-${target.triplet}.tar.gz`);
|
||||
await downloadTo(url, tarPath);
|
||||
extractBinding(tarPath, destBin);
|
||||
console.log(` → ${destBin}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('done.');
|
||||
}
|
||||
|
||||
function readVersionFromPin() {
|
||||
const pkg = JSON.parse(readFileSync(join(repoRoot, 'packages', 'sqlite', 'package.json'), 'utf8'));
|
||||
const raw = pkg.devDependencies?.['better-sqlite3'];
|
||||
if (!raw) {
|
||||
throw new Error('cannot find better-sqlite3 pin in packages/sqlite/package.json');
|
||||
}
|
||||
// strip the `^` / `~` / `>=` etc prefix.
|
||||
return raw.replace(/^[\^~>=<]+/, '');
|
||||
}
|
||||
|
||||
async function downloadTo(url, dest) {
|
||||
// curl is in every CI image SnowLuma cares about (and on every
|
||||
// dev mac/linux), so we just shell out — keeps this script free
|
||||
// of npm dependencies, which matters because pnpm install hasn't
|
||||
// necessarily run yet when someone clones the repo fresh.
|
||||
const result = spawnSync('curl', ['-fsSL', '--retry', '3', '-o', dest, url], { stdio: 'inherit' });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`curl failed for ${url} (exit ${result.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
function extractBinding(tarPath, destBin) {
|
||||
// The prebuild archive is `build/Release/better_sqlite3.node`
|
||||
// wrapped in the standard better-sqlite3 layout. We capture tar's
|
||||
// stdout as a buffer (spawnSync's `stdio: 'pipe'` + `encoding: null`)
|
||||
// and write that buffer to the destination — simpler than wiring
|
||||
// a Node WriteStream which spawnSync's stdio doesn't accept.
|
||||
const result = spawnSync(
|
||||
'tar',
|
||||
['-xzOf', tarPath, '--strip-components=2', 'build/Release/better_sqlite3.node'],
|
||||
{ stdio: ['ignore', 'pipe', 'inherit'], encoding: null, maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`tar failed for ${tarPath} (exit ${result.status})`);
|
||||
}
|
||||
writeFileSync(destBin, result.stdout);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user