diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index e09e9a8c..a4379937 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -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-.zip|tar.gz – zero-install (node bundled) # SnowLuma-dev--lite.zip|tar.gz – user provides Node >= 22 diff --git a/package.json b/package.json index fbb38960..699f5ebb 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 9060e6be..8c326621 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -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:", diff --git a/packages/bridge/src/identity-service.ts b/packages/bridge/src/identity-service.ts index 21afa03f..cf68358f 100644 --- a/packages/bridge/src/identity-service.ts +++ b/packages/bridge/src/identity-service.ts @@ -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(); // ─── 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(); + private readonly stmtCache_ = new Map(); 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); diff --git a/packages/core/package.json b/packages/core/package.json index f006ec42..562a5e8e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -45,6 +45,7 @@ "@snowluma/onebot": "workspace:*", "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", + "@snowluma/sqlite": "workspace:*", "@snowluma/websocket": "workspace:*" }, "devDependencies": { diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index bb9f3423..f4ca6e86 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -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-*.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`] : []), diff --git a/packages/onebot/package.json b/packages/onebot/package.json index a597464d..d6e2e8d2 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -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:", diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index 378c0fa3..9e6ee8ca 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -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( diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 6b2e95dc..32f70d52 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -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); diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node new file mode 100644 index 00000000..f43da9ce Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-x64.node b/packages/runtime/native/better-sqlite3-v127-darwin-x64.node new file mode 100644 index 00000000..c4df275b Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-darwin-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-arm64.node b/packages/runtime/native/better-sqlite3-v127-linux-arm64.node new file mode 100644 index 00000000..b6e59662 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-linux-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-x64.node b/packages/runtime/native/better-sqlite3-v127-linux-x64.node new file mode 100644 index 00000000..dfc2a4a8 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-linux-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v127-win32-x64.node b/packages/runtime/native/better-sqlite3-v127-win32-x64.node new file mode 100644 index 00000000..b54d6060 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v127-win32-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node new file mode 100644 index 00000000..b192e495 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-x64.node b/packages/runtime/native/better-sqlite3-v137-darwin-x64.node new file mode 100644 index 00000000..c189de35 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-darwin-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-arm64.node b/packages/runtime/native/better-sqlite3-v137-linux-arm64.node new file mode 100644 index 00000000..ecc84e9b Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-linux-arm64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-x64.node b/packages/runtime/native/better-sqlite3-v137-linux-x64.node new file mode 100644 index 00000000..d475c3f6 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-linux-x64.node differ diff --git a/packages/runtime/native/better-sqlite3-v137-win32-x64.node b/packages/runtime/native/better-sqlite3-v137-win32-x64.node new file mode 100644 index 00000000..2f872f81 Binary files /dev/null and b/packages/runtime/native/better-sqlite3-v137-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 4b6415e7..4e08a3d4 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -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." } diff --git a/packages/sqlite/package.json b/packages/sqlite/package.json new file mode 100644 index 00000000..ad79d3fd --- /dev/null +++ b/packages/sqlite/package.json @@ -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/-/` 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:" + } +} diff --git a/packages/sqlite/src/index.ts b/packages/sqlite/src/index.ts new file mode 100644 index 00000000..7ccfd6a2 --- /dev/null +++ b/packages/sqlite/src/index.ts @@ -0,0 +1,118 @@ +// @snowluma/sqlite — wraps better-sqlite3 so the native `.node` binding +// is loaded from +// `dist/native/better-sqlite3-v--.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--.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: `/native/better-sqlite3-v-.node` +// - Dev: `/packages/runtime/native/better-sqlite3-v-.node` +// We probe both paths and take whichever exists. +// 3. `` is `-` (e.g. +// `darwin-arm64`, `linux-x64`, `linux-arm64`, `win32-x64`). +// 4. `` 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-.node + // — `import.meta.url` resolves to dist/ at runtime (the wrapper + // is bundled into index.mjs alongside it). + // 2. Dev: /packages/runtime/native/better-sqlite3-.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; +type DatabaseOptions = ConstructorParameters[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; diff --git a/packages/sqlite/tsconfig.json b/packages/sqlite/tsconfig.json new file mode 100644 index 00000000..4cd329d7 --- /dev/null +++ b/packages/sqlite/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 63f47782..15ab33fd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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(hono@4.12.14) - '@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/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) - 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/node@24.12.2)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + 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} bindings@1.5.0: resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} @@ -4192,7 +4201,7 @@ snapshots: baseline-browser-mapping@2.10.19: {} - better-sqlite3@11.10.0: + better-sqlite3@12.10.0: dependencies: bindings: 1.5.0 prebuild-install: 7.1.3 diff --git a/tools/fetch-sqlite-prebuilts.mjs b/tools/fetch-sqlite-prebuilts.mjs new file mode 100644 index 00000000..0af48024 --- /dev/null +++ b/tools/fetch-sqlite-prebuilts.mjs @@ -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--.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--.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); +});