@cortexkit/opencode-magic-context 0.16.2 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/dist/features/magic-context/message-index-async.d.ts +12 -0
- package/dist/features/magic-context/message-index-async.d.ts.map +1 -0
- package/dist/features/magic-context/message-index.d.ts +4 -0
- package/dist/features/magic-context/message-index.d.ts.map +1 -1
- package/dist/features/magic-context/migrations.d.ts +7 -0
- package/dist/features/magic-context/migrations.d.ts.map +1 -1
- package/dist/features/magic-context/search.d.ts +2 -2
- package/dist/features/magic-context/search.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +3 -6
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-tags.d.ts +163 -1
- package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
- package/dist/features/magic-context/storage.d.ts +1 -1
- package/dist/features/magic-context/storage.d.ts.map +1 -1
- package/dist/features/magic-context/tagger.d.ts +52 -2
- package/dist/features/magic-context/tagger.d.ts.map +1 -1
- package/dist/features/magic-context/tool-definition-tokens.d.ts +26 -3
- package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
- package/dist/features/magic-context/tool-owner-backfill.d.ts +90 -0
- package/dist/features/magic-context/tool-owner-backfill.d.ts.map +1 -0
- package/dist/features/magic-context/types.d.ts +17 -0
- package/dist/features/magic-context/types.d.ts.map +1 -1
- package/dist/hooks/auto-update-checker/cache.d.ts +12 -1
- package/dist/hooks/auto-update-checker/cache.d.ts.map +1 -1
- package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts +23 -0
- package/dist/hooks/magic-context/compartment-runner-drop-queue.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-payloads.d.ts +8 -0
- package/dist/hooks/magic-context/event-payloads.d.ts.map +1 -1
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook-handlers.d.ts +6 -0
- package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +16 -0
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/live-session-state.d.ts +13 -0
- package/dist/hooks/magic-context/live-session-state.d.ts.map +1 -1
- package/dist/hooks/magic-context/nudger.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts +24 -1
- package/dist/hooks/magic-context/read-session-chunk.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-db.d.ts +1 -0
- package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-raw.d.ts +1 -0
- package/dist/hooks/magic-context/read-session-raw.d.ts.map +1 -1
- package/dist/hooks/magic-context/strip-content.d.ts +9 -6
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/tool-drop-target.d.ts +16 -1
- package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +0 -11
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +7 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2073 -768
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts +3 -0
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/shared/models-dev-cache.d.ts +3 -10
- package/dist/shared/models-dev-cache.d.ts.map +1 -1
- package/dist/shared/native-binding.d.ts +87 -0
- package/dist/shared/native-binding.d.ts.map +1 -0
- package/dist/shared/sqlite.d.ts +0 -12
- package/dist/shared/sqlite.d.ts.map +1 -1
- package/dist/shared/tag-transcript.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/shared/conflict-detector.ts +1 -1
- package/src/shared/models-dev-cache.test.ts +64 -57
- package/src/shared/models-dev-cache.ts +49 -68
- package/src/shared/native-binding.ts +311 -0
- package/src/shared/sqlite.ts +57 -14
- package/src/shared/tag-transcript.ts +137 -126
- package/src/tui/index.tsx +2 -2
- package/dist/hooks/magic-context/reasoning-capability.d.ts +0 -23
- package/dist/hooks/magic-context/reasoning-capability.d.ts.map +0 -1
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native-binding resolver for Electron-runtime mismatches.
|
|
3
|
+
*
|
|
4
|
+
* Why this module exists
|
|
5
|
+
* ----------------------
|
|
6
|
+
* `better-sqlite3` uses raw v8/nan bindings, so its compiled `.node` file is
|
|
7
|
+
* locked to a specific NODE_MODULE_VERSION (Node-API ABI revision). When
|
|
8
|
+
* OpenCode Desktop (Electron 41 → ABI 145) loads a plugin whose `node_modules`
|
|
9
|
+
* was populated by `bun install` / `npm install` under a different runtime,
|
|
10
|
+
* the fetched prebuild is for `node-vNNN` (e.g. ABI 137 for Node 22) and
|
|
11
|
+
* Electron refuses to load it with:
|
|
12
|
+
*
|
|
13
|
+
* The module '...better_sqlite3.node' was compiled against a different
|
|
14
|
+
* Node.js version using NODE_MODULE_VERSION 137. This version of Node.js
|
|
15
|
+
* requires NODE_MODULE_VERSION 145.
|
|
16
|
+
*
|
|
17
|
+
* `onnxruntime-node` (used by `@huggingface/transformers` for local
|
|
18
|
+
* embeddings) is N-API v3 and is ABI-stable across runtimes, so it does NOT
|
|
19
|
+
* have this problem. Only `better-sqlite3` is affected.
|
|
20
|
+
*
|
|
21
|
+
* What this does
|
|
22
|
+
* --------------
|
|
23
|
+
* On plugin load, before constructing any `Database`:
|
|
24
|
+
*
|
|
25
|
+
* 1. If we are NOT running under Electron (`process.versions.electron` is
|
|
26
|
+
* unset), return null. Bun uses `bun:sqlite` and never reaches this code;
|
|
27
|
+
* Pi/Node-CLI install matching Node-vNNN prebuilds via npm, which work
|
|
28
|
+
* natively against the on-disk binary.
|
|
29
|
+
*
|
|
30
|
+
* 2. If we ARE on Electron, locate the `.node` file path that
|
|
31
|
+
* `better-sqlite3`'s default `bindings()` lookup would try first. Probe
|
|
32
|
+
* its ABI by attempting a sandboxed `process.dlopen`. If it succeeds
|
|
33
|
+
* (Electron-compatible), return null — the default lookup will work.
|
|
34
|
+
*
|
|
35
|
+
* 3. Otherwise, look for a cached Electron prebuild at
|
|
36
|
+
* `<XDG_CACHE_HOME>/cortexkit/native-bindings/better-sqlite3/v<version>/electron-v<abi>-<platform>-<arch>/better_sqlite3.node`.
|
|
37
|
+
* Download it from the `WiseLibs/better-sqlite3` GitHub release if
|
|
38
|
+
* missing, extract with `nanotar` (pure-JS, ~45 KB, zero deps), validate
|
|
39
|
+
* the ABI, and return the absolute path.
|
|
40
|
+
*
|
|
41
|
+
* The caller (`sqlite.ts`) then passes this path through `better-sqlite3`'s
|
|
42
|
+
* documented `nativeBinding` constructor option:
|
|
43
|
+
*
|
|
44
|
+
* new Database(filename, { nativeBinding: <our cached path> })
|
|
45
|
+
*
|
|
46
|
+
* `better-sqlite3` calls `require()` directly on that path, bypassing the
|
|
47
|
+
* normal `bindings()` lookup chain. This is a first-class API the maintainer
|
|
48
|
+
* added for exactly this kind of cross-runtime extension scenario — see
|
|
49
|
+
* `node_modules/better-sqlite3/lib/database.js` `nativeBinding` handling.
|
|
50
|
+
*
|
|
51
|
+
* Why we don't replace the on-disk binary
|
|
52
|
+
* ---------------------------------------
|
|
53
|
+
* An earlier iteration copied the cached Electron binary over the in-tree
|
|
54
|
+
* `node_modules/.../better_sqlite3.node`. That worked but mutates a shared
|
|
55
|
+
* resource: in monorepo dev setups (or any case where multiple runtimes
|
|
56
|
+
* share one `node_modules`), a Pi process opening the plugin from the same
|
|
57
|
+
* workspace would then load the Electron-ABI binary and fail. Returning a
|
|
58
|
+
* separate cached path keeps the on-disk file untouched so each runtime
|
|
59
|
+
* sees the binary it needs.
|
|
60
|
+
*
|
|
61
|
+
* Failure modes
|
|
62
|
+
* -------------
|
|
63
|
+
* If GitHub is unreachable (corporate firewall, offline laptop, rate limit)
|
|
64
|
+
* AND no cached binary exists, this throws. The caller (sqlite.ts →
|
|
65
|
+
* openDatabase) surfaces a `storage unavailable` error and Magic Context
|
|
66
|
+
* disables itself for the run. The user can connect to the network and
|
|
67
|
+
* restart, or wait for a cached binary from a previous successful launch.
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
71
|
+
import { createRequire } from "node:module";
|
|
72
|
+
import * as path from "node:path";
|
|
73
|
+
import { parseTarGzip } from "nanotar";
|
|
74
|
+
import { getCacheDir } from "./data-path";
|
|
75
|
+
import { log } from "./logger";
|
|
76
|
+
|
|
77
|
+
const PREFIX = "[native-binding]";
|
|
78
|
+
|
|
79
|
+
function logInfo(message: string): void {
|
|
80
|
+
log(`${PREFIX} ${message}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function logWarn(message: string): void {
|
|
84
|
+
log(`${PREFIX} WARN ${message}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Result of probing a `.node` file's ABI by attempting a sandboxed `dlopen`.
|
|
89
|
+
*
|
|
90
|
+
* - `ok: true` means the runtime accepted the binary; the on-disk file is
|
|
91
|
+
* already Electron-compatible and we don't need to do anything.
|
|
92
|
+
* - `ok: false` carries the parsed `actual` ABI for diagnostics (or `null`
|
|
93
|
+
* if the error message didn't match any known shape).
|
|
94
|
+
*/
|
|
95
|
+
type ProbeResult = { ok: true } | { ok: false; expected: string; actual: string | null };
|
|
96
|
+
|
|
97
|
+
function probeAbi(binaryPath: string): ProbeResult {
|
|
98
|
+
const expected = process.versions.modules;
|
|
99
|
+
try {
|
|
100
|
+
// Throwaway sandbox: process.dlopen runs the module's init function
|
|
101
|
+
// against `sandbox.exports`. On ABI mismatch it throws BEFORE init
|
|
102
|
+
// runs, so the binary is NOT loaded into process memory in the
|
|
103
|
+
// failure case. On success the binary IS loaded (Node refcounts
|
|
104
|
+
// these, so a second dlopen by the real `require()` is cheap).
|
|
105
|
+
const sandbox = { exports: {} as Record<string, unknown> };
|
|
106
|
+
process.dlopen(sandbox, binaryPath);
|
|
107
|
+
return { ok: true };
|
|
108
|
+
} catch (err) {
|
|
109
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
110
|
+
const pair = message.match(/NODE_MODULE_VERSION (\d+).*NODE_MODULE_VERSION (\d+)/s);
|
|
111
|
+
if (pair?.[1] && pair[2]) {
|
|
112
|
+
return { ok: false, expected: pair[2], actual: pair[1] };
|
|
113
|
+
}
|
|
114
|
+
const single = message.match(/NODE_MODULE_VERSION[ =:]+(\d+)/);
|
|
115
|
+
if (single?.[1]) {
|
|
116
|
+
return { ok: false, expected, actual: single[1] };
|
|
117
|
+
}
|
|
118
|
+
// Couldn't parse — log raw message so we can refine the regex if a
|
|
119
|
+
// future runtime emits a different shape.
|
|
120
|
+
logWarn(`could not parse ABI from dlopen error: ${message}`);
|
|
121
|
+
return { ok: false, expected, actual: null };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Locate the on-disk path `better-sqlite3` ships its `.node` file at, plus
|
|
127
|
+
* the package version. Returns null if better-sqlite3 isn't resolvable —
|
|
128
|
+
* that's a broken install we let propagate naturally through the dynamic
|
|
129
|
+
* import in sqlite.ts.
|
|
130
|
+
*/
|
|
131
|
+
function resolveBetterSqlite3OnDisk(
|
|
132
|
+
requireFn: NodeRequire,
|
|
133
|
+
): { binaryPath: string; pkgVersion: string } | null {
|
|
134
|
+
try {
|
|
135
|
+
const pkgJsonPath = requireFn.resolve("better-sqlite3/package.json");
|
|
136
|
+
const pkgDir = path.dirname(pkgJsonPath);
|
|
137
|
+
const pkgJson = requireFn(pkgJsonPath) as { version: string };
|
|
138
|
+
const binaryPath = path.join(pkgDir, "build", "Release", "better_sqlite3.node");
|
|
139
|
+
return { binaryPath, pkgVersion: pkgJson.version };
|
|
140
|
+
} catch (err) {
|
|
141
|
+
logWarn(
|
|
142
|
+
`could not resolve better-sqlite3 in node_modules: ${err instanceof Error ? err.message : String(err)}`,
|
|
143
|
+
);
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Cache directory for downloaded native bindings. Keyed by
|
|
150
|
+
* `<pkgVersion>/electron-v<abi>-<platform>-<arch>` so a Magic Context update
|
|
151
|
+
* that bumps better-sqlite3 or an OpenCode update that bumps Electron both
|
|
152
|
+
* trigger a fresh download cleanly.
|
|
153
|
+
*/
|
|
154
|
+
function getCachedBinaryPath(pkgVersion: string, abi: string): string {
|
|
155
|
+
return path.join(
|
|
156
|
+
getCacheDir(),
|
|
157
|
+
"cortexkit",
|
|
158
|
+
"native-bindings",
|
|
159
|
+
"better-sqlite3",
|
|
160
|
+
`v${pkgVersion}`,
|
|
161
|
+
`electron-v${abi}-${process.platform}-${process.arch}`,
|
|
162
|
+
"better_sqlite3.node",
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Download the Electron-targeted prebuild tarball from WiseLibs/better-sqlite3
|
|
168
|
+
* GitHub releases and extract the `.node` bytes. Throws on HTTP failure or
|
|
169
|
+
* if the tarball doesn't contain the expected file.
|
|
170
|
+
*/
|
|
171
|
+
async function downloadElectronPrebuild(pkgVersion: string, abi: string): Promise<Uint8Array> {
|
|
172
|
+
const filename = `better-sqlite3-v${pkgVersion}-electron-v${abi}-${process.platform}-${process.arch}.tar.gz`;
|
|
173
|
+
const url = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${pkgVersion}/${filename}`;
|
|
174
|
+
logInfo(`downloading ${url}`);
|
|
175
|
+
|
|
176
|
+
const response = await fetch(url, {
|
|
177
|
+
redirect: "follow",
|
|
178
|
+
headers: { "User-Agent": "magic-context-plugin/native-binding" },
|
|
179
|
+
});
|
|
180
|
+
if (!response.ok) {
|
|
181
|
+
throw new Error(
|
|
182
|
+
`failed to download Electron prebuild (HTTP ${response.status} ${response.statusText}) from ${url}`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const tarballBytes = new Uint8Array(await response.arrayBuffer());
|
|
187
|
+
logInfo(`downloaded ${(tarballBytes.length / 1024).toFixed(1)} KB; extracting`);
|
|
188
|
+
|
|
189
|
+
const files = await parseTarGzip(tarballBytes);
|
|
190
|
+
const nodeFile = files.find((f) => f.name.endsWith("better_sqlite3.node"));
|
|
191
|
+
if (!nodeFile?.data) {
|
|
192
|
+
const names = files.map((f) => f.name).join(", ");
|
|
193
|
+
throw new Error(
|
|
194
|
+
`Electron prebuild tarball did not contain better_sqlite3.node; got: [${names}]`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return nodeFile.data instanceof Uint8Array ? nodeFile.data : new Uint8Array(nodeFile.data);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Singleton promise so concurrent callers (multiple plugin init paths in the
|
|
202
|
+
* same process) only do the check + download once. Reset to null after
|
|
203
|
+
* completion so a future call can retry on transient failures.
|
|
204
|
+
*/
|
|
205
|
+
let inFlight: Promise<string | null> | null = null;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Resolve the absolute path to a `better-sqlite3` `.node` binary that the
|
|
209
|
+
* current runtime can load.
|
|
210
|
+
*
|
|
211
|
+
* - Returns `null` outside Electron (Bun uses `bun:sqlite`; Pi/Node CLI
|
|
212
|
+
* loads matching prebuilds from `node_modules` natively).
|
|
213
|
+
* - Returns `null` on Electron when the on-disk binary already matches
|
|
214
|
+
* the runtime's ABI (rare but possible — a future OpenCode build that
|
|
215
|
+
* post-install-rebuilds for Electron would hit this fast path).
|
|
216
|
+
* - Returns the cached/downloaded prebuild path on Electron when the
|
|
217
|
+
* on-disk binary's ABI doesn't match.
|
|
218
|
+
*
|
|
219
|
+
* The returned path is suitable as the `nativeBinding` option to
|
|
220
|
+
* `new Database(filename, { nativeBinding })`. better-sqlite3 calls `require()`
|
|
221
|
+
* directly on it, bypassing the default `bindings()` lookup chain — this is
|
|
222
|
+
* a documented public API in better-sqlite3, not an internal hack.
|
|
223
|
+
*/
|
|
224
|
+
export async function resolveBetterSqliteNativeBinding(): Promise<string | null> {
|
|
225
|
+
if (!process.versions.electron) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (inFlight) {
|
|
230
|
+
return inFlight;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const promise = (async () => {
|
|
234
|
+
const expected = process.versions.modules;
|
|
235
|
+
logInfo(
|
|
236
|
+
`Electron detected (v${process.versions.electron}, NODE_MODULE_VERSION ${expected}); verifying better-sqlite3 binding`,
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
const requireFn = createRequire(import.meta.url);
|
|
240
|
+
const resolved = resolveBetterSqlite3OnDisk(requireFn);
|
|
241
|
+
if (!resolved) {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
const { binaryPath: diskPath, pkgVersion } = resolved;
|
|
245
|
+
|
|
246
|
+
// Fast path: if the on-disk binary already matches the runtime's
|
|
247
|
+
// ABI, we don't need to override the lookup at all. This handles
|
|
248
|
+
// any future OpenCode build that rebuilds native modules for
|
|
249
|
+
// Electron at install time, plus the case where the user manually
|
|
250
|
+
// ran `prebuild-install --runtime=electron`.
|
|
251
|
+
if (existsSync(diskPath)) {
|
|
252
|
+
const diskProbe = probeAbi(diskPath);
|
|
253
|
+
if (diskProbe.ok) {
|
|
254
|
+
logInfo(
|
|
255
|
+
`on-disk binary already matches Electron ABI v${expected}; using default bindings() lookup`,
|
|
256
|
+
);
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
logInfo(
|
|
260
|
+
`on-disk binary ABI ${diskProbe.actual ?? "unknown"} != required ${expected}; will use Electron prebuild`,
|
|
261
|
+
);
|
|
262
|
+
} else {
|
|
263
|
+
logWarn(
|
|
264
|
+
`expected better-sqlite3 binary not found at ${diskPath}; will fetch Electron prebuild anyway`,
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Look for a cached Electron prebuild from a previous launch.
|
|
269
|
+
const cachedPath = getCachedBinaryPath(pkgVersion, expected);
|
|
270
|
+
if (existsSync(cachedPath)) {
|
|
271
|
+
const cachedProbe = probeAbi(cachedPath);
|
|
272
|
+
if (cachedProbe.ok) {
|
|
273
|
+
logInfo(`using cached Electron prebuild at ${cachedPath}`);
|
|
274
|
+
return cachedPath;
|
|
275
|
+
}
|
|
276
|
+
logWarn(
|
|
277
|
+
`cached binary at ${cachedPath} has wrong ABI (${cachedProbe.actual ?? "unknown"} != ${expected}); refetching`,
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Download fresh.
|
|
282
|
+
mkdirSync(path.dirname(cachedPath), { recursive: true });
|
|
283
|
+
const nodeFileBytes = await downloadElectronPrebuild(pkgVersion, expected);
|
|
284
|
+
writeFileSync(cachedPath, nodeFileBytes);
|
|
285
|
+
logInfo(
|
|
286
|
+
`cached Electron prebuild at ${cachedPath} (${(nodeFileBytes.length / 1024).toFixed(1)} KB)`,
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
// Validate the freshly downloaded binary before returning it — if
|
|
290
|
+
// the upstream tarball was malformed or for the wrong ABI, fail
|
|
291
|
+
// loudly here rather than letting the better-sqlite3 constructor
|
|
292
|
+
// throw a less actionable error later.
|
|
293
|
+
const finalProbe = probeAbi(cachedPath);
|
|
294
|
+
if (!finalProbe.ok) {
|
|
295
|
+
throw new Error(
|
|
296
|
+
`downloaded Electron prebuild has wrong ABI (${finalProbe.actual ?? "unknown"} != ${expected}); refusing to use`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return cachedPath;
|
|
301
|
+
})();
|
|
302
|
+
|
|
303
|
+
inFlight = promise;
|
|
304
|
+
try {
|
|
305
|
+
return await promise;
|
|
306
|
+
} finally {
|
|
307
|
+
if (inFlight === promise) {
|
|
308
|
+
inFlight = null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
package/src/shared/sqlite.ts
CHANGED
|
@@ -26,6 +26,12 @@
|
|
|
26
26
|
* in `./sqlite-helpers.ts`.
|
|
27
27
|
*/
|
|
28
28
|
|
|
29
|
+
// Type import only — better-sqlite3's runtime is loaded dynamically below.
|
|
30
|
+
// @types/better-sqlite3 has richer definitions than @types/bun's bun:sqlite
|
|
31
|
+
// types, and bun:sqlite is a structural superset for the API surface we use,
|
|
32
|
+
// so calls typed against BetterSqlite3 work under both runtimes at runtime.
|
|
33
|
+
import type BetterSqlite3 from "better-sqlite3";
|
|
34
|
+
|
|
29
35
|
// Detect Bun via process.versions.bun. Both globalThis.Bun and
|
|
30
36
|
// process.versions.bun are set by the Bun runtime, but process.versions
|
|
31
37
|
// is a lower-level surface less likely to be sandboxed by host runtimes
|
|
@@ -50,6 +56,22 @@ const isBun = typeof process !== "undefined" && typeof process.versions?.bun ===
|
|
|
50
56
|
// dynamic import — Pi's loader, esbuild, and bun build all accept it.
|
|
51
57
|
const bunSpec = "bun:" + "sqlite";
|
|
52
58
|
const betterSpec = "better-" + "sqlite3";
|
|
59
|
+
|
|
60
|
+
// Under Electron, the npm-installed better-sqlite3 binary has the wrong ABI
|
|
61
|
+
// (it's a Node prebuild but Electron embeds a different NODE_MODULE_VERSION).
|
|
62
|
+
// resolveBetterSqliteNativeBinding() detects this and downloads + caches the
|
|
63
|
+
// matching Electron prebuild, then returns its absolute path so we can pass
|
|
64
|
+
// it to better-sqlite3 via the `nativeBinding` constructor option (a
|
|
65
|
+
// documented public API). Returns null outside Electron OR when the on-disk
|
|
66
|
+
// binary already matches the runtime ABI — in those cases the default
|
|
67
|
+
// bindings() lookup just works.
|
|
68
|
+
const electronNativeBinding = isBun
|
|
69
|
+
? null
|
|
70
|
+
: await (async () => {
|
|
71
|
+
const mod = await import("./native-binding");
|
|
72
|
+
return mod.resolveBetterSqliteNativeBinding();
|
|
73
|
+
})();
|
|
74
|
+
|
|
53
75
|
const sqliteModule = isBun
|
|
54
76
|
? await import(/* @vite-ignore */ bunSpec)
|
|
55
77
|
: await import(/* @vite-ignore */ betterSpec);
|
|
@@ -57,21 +79,42 @@ const sqliteModule = isBun
|
|
|
57
79
|
// Different export shapes between the two libraries:
|
|
58
80
|
// - bun:sqlite → named export `Database`
|
|
59
81
|
// - better-sqlite3 → default export
|
|
60
|
-
const
|
|
82
|
+
const RawDatabaseImpl = isBun ? sqliteModule.Database : sqliteModule.default;
|
|
61
83
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
84
|
+
// When we resolved a non-default Electron-compatible native binding above,
|
|
85
|
+
// transparently inject it into every `new Database(...)` call. This is the
|
|
86
|
+
// public `nativeBinding` constructor option that better-sqlite3 ships
|
|
87
|
+
// specifically for cross-runtime extension scenarios — it makes
|
|
88
|
+
// better-sqlite3 `require()` the binary at the supplied path directly,
|
|
89
|
+
// bypassing the default bindings() resolver.
|
|
90
|
+
//
|
|
91
|
+
// Subclassing keeps the call sites untouched: existing
|
|
92
|
+
// `new Database(filename, { readonly: true })` invocations work as-is.
|
|
93
|
+
// Callers can still override `nativeBinding` explicitly if they need to.
|
|
94
|
+
//
|
|
95
|
+
// The TypeScript type intentionally references @types/better-sqlite3 because
|
|
96
|
+
// its definitions are richer than @types/bun's bun:sqlite types and bun:sqlite
|
|
97
|
+
// is a structural superset for the API surface we use. Calls written against
|
|
98
|
+
// this type work correctly under both runtimes at runtime.
|
|
99
|
+
//
|
|
100
|
+
// @types/better-sqlite3 uses `export = Database` (CommonJS interop), which
|
|
101
|
+
// surfaces in TypeScript as `import Database = require("better-sqlite3")`.
|
|
102
|
+
// We capture the DatabaseConstructor type from the namespace re-export.
|
|
103
|
+
const DatabaseImpl: typeof BetterSqlite3 =
|
|
104
|
+
electronNativeBinding == null
|
|
105
|
+
? (RawDatabaseImpl as typeof BetterSqlite3)
|
|
106
|
+
: (class DatabaseWithElectronBinding extends (RawDatabaseImpl as typeof BetterSqlite3) {
|
|
107
|
+
constructor(filename?: string | Buffer, options?: BetterSqlite3.Options) {
|
|
108
|
+
// Type narrowing: the surrounding ternary already proved
|
|
109
|
+
// electronNativeBinding is non-null in this branch, but
|
|
110
|
+
// TypeScript can't follow that across the class boundary.
|
|
111
|
+
const fallback = electronNativeBinding as string;
|
|
112
|
+
super(filename, {
|
|
113
|
+
...options,
|
|
114
|
+
nativeBinding: options?.nativeBinding ?? fallback,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
} as typeof BetterSqlite3);
|
|
75
118
|
|
|
76
119
|
export const Database: typeof BetterSqlite3 = DatabaseImpl;
|
|
77
120
|
|