wiki-graph-sdk 0.7.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/LICENSE +201 -0
- package/README.md +32 -0
- package/dist/archives.cjs +2799 -0
- package/dist/archives.cjs.map +1 -0
- package/dist/archives.d.ts +249 -0
- package/dist/archives.js +2814 -0
- package/dist/archives.js.map +1 -0
- package/dist/conversions.cjs +1332 -0
- package/dist/conversions.cjs.map +1 -0
- package/dist/conversions.d.ts +37 -0
- package/dist/conversions.js +1308 -0
- package/dist/conversions.js.map +1 -0
- package/dist/data/editor/clue_reviewer.jinja +410 -0
- package/dist/data/editor/clue_reviewer_generator.jinja +428 -0
- package/dist/data/editor/revision_feedback.jinja +5 -0
- package/dist/data/editor/text_compressor.jinja +131 -0
- package/dist/data/guaranteed/response_intent_classifier.jinja +8 -0
- package/dist/data/output/epub/cover.xhtml.jinja +13 -0
- package/dist/data/output/epub/nav.xhtml.jinja +12 -0
- package/dist/data/output/epub/package.opf.xml.jinja +39 -0
- package/dist/data/output/epub/section.xhtml.jinja +12 -0
- package/dist/data/topologization/book_coherence_extraction.jinja +223 -0
- package/dist/data/topologization/chunk_extraction.jinja +233 -0
- package/dist/data/topologization/evidence_choice.jinja +38 -0
- package/dist/data/topologization/translate_chunks.jinja +138 -0
- package/dist/data/topologization/user_focused_extraction.jinja +378 -0
- package/dist/default-worker.cjs +1709 -0
- package/dist/default-worker.cjs.map +1 -0
- package/dist/default-worker.d.ts +10 -0
- package/dist/default-worker.js +1705 -0
- package/dist/default-worker.js.map +1 -0
- package/dist/embedding.cjs +1091 -0
- package/dist/embedding.cjs.map +1 -0
- package/dist/embedding.d.ts +26 -0
- package/dist/embedding.js +1062 -0
- package/dist/embedding.js.map +1 -0
- package/dist/entry-context.cjs +91 -0
- package/dist/entry-context.cjs.map +1 -0
- package/dist/entry-context.d.ts +20 -0
- package/dist/entry-context.js +68 -0
- package/dist/entry-context.js.map +1 -0
- package/dist/gc.cjs +731 -0
- package/dist/gc.cjs.map +1 -0
- package/dist/gc.d.ts +14 -0
- package/dist/gc.js +707 -0
- package/dist/gc.js.map +1 -0
- package/dist/index.cjs +4760 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +213 -0
- package/dist/index.js +4808 -0
- package/dist/index.js.map +1 -0
- package/dist/jobs-Dd5PMSId.d.ts +98 -0
- package/dist/llm.cjs +101 -0
- package/dist/llm.cjs.map +1 -0
- package/dist/llm.d.ts +7 -0
- package/dist/llm.js +79 -0
- package/dist/llm.js.map +1 -0
- package/dist/local-config.cjs +1024 -0
- package/dist/local-config.cjs.map +1 -0
- package/dist/local-config.d.ts +14 -0
- package/dist/local-config.js +989 -0
- package/dist/local-config.js.map +1 -0
- package/dist/maintenance.cjs +800 -0
- package/dist/maintenance.cjs.map +1 -0
- package/dist/maintenance.d.ts +24 -0
- package/dist/maintenance.js +778 -0
- package/dist/maintenance.js.map +1 -0
- package/dist/node-platform.cjs +758 -0
- package/dist/node-platform.cjs.map +1 -0
- package/dist/node-platform.d.ts +49 -0
- package/dist/node-platform.js +723 -0
- package/dist/node-platform.js.map +1 -0
- package/dist/planning.cjs +164 -0
- package/dist/planning.cjs.map +1 -0
- package/dist/planning.d.ts +43 -0
- package/dist/planning.js +137 -0
- package/dist/planning.js.map +1 -0
- package/dist/runtime-config.cjs +1155 -0
- package/dist/runtime-config.cjs.map +1 -0
- package/dist/runtime-config.d.ts +50 -0
- package/dist/runtime-config.js +1127 -0
- package/dist/runtime-config.js.map +1 -0
- package/dist/stage.cjs +1265 -0
- package/dist/stage.cjs.map +1 -0
- package/dist/stage.d.ts +16 -0
- package/dist/stage.js +1239 -0
- package/dist/stage.js.map +1 -0
- package/dist/wikispine.cjs +85 -0
- package/dist/wikispine.cjs.map +1 -0
- package/dist/wikispine.d.ts +6 -0
- package/dist/wikispine.js +63 -0
- package/dist/wikispine.js.map +1 -0
- package/dist/worker.cjs +738 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.ts +157 -0
- package/dist/worker.js +715 -0
- package/dist/worker.js.map +1 -0
- package/package.json +151 -0
|
@@ -0,0 +1,1091 @@
|
|
|
1
|
+
globalThis.__WIKIGRAPH_DATA_DIR__ ??= require("path").resolve(__dirname, "data");
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
29
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
|
|
31
|
+
// src/embedding.ts
|
|
32
|
+
var embedding_exports = {};
|
|
33
|
+
__export(embedding_exports, {
|
|
34
|
+
buildSearchIndexEmbeddingProvider: () => buildSearchIndexEmbeddingProvider,
|
|
35
|
+
embedQueryText: () => embedQueryText,
|
|
36
|
+
embedQueryTextWithLocalConfig: () => embedQueryTextWithLocalConfig,
|
|
37
|
+
readWikiGraphEmbeddingConfig: () => readWikiGraphEmbeddingConfig
|
|
38
|
+
});
|
|
39
|
+
module.exports = __toCommonJS(embedding_exports);
|
|
40
|
+
var import_ai = require("ai");
|
|
41
|
+
var import_openai = require("@ai-sdk/openai");
|
|
42
|
+
var import_openai_compatible = require("@ai-sdk/openai-compatible");
|
|
43
|
+
|
|
44
|
+
// src/local-config.ts
|
|
45
|
+
var import_wiki_graph_core = require("wiki-graph-core");
|
|
46
|
+
|
|
47
|
+
// src/runtime-context.ts
|
|
48
|
+
var import_async_hooks = require("async_hooks");
|
|
49
|
+
var RUNTIME_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.runtime-context.v1");
|
|
50
|
+
var runtimeContext = getRuntimeContextStorage();
|
|
51
|
+
function getRuntimeContextStorage() {
|
|
52
|
+
const runtimeGlobal = globalThis;
|
|
53
|
+
const existing = runtimeGlobal[RUNTIME_CONTEXT_KEY];
|
|
54
|
+
if (existing !== void 0) {
|
|
55
|
+
return existing;
|
|
56
|
+
}
|
|
57
|
+
const storage = new import_async_hooks.AsyncLocalStorage();
|
|
58
|
+
Object.defineProperty(runtimeGlobal, RUNTIME_CONTEXT_KEY, {
|
|
59
|
+
configurable: false,
|
|
60
|
+
enumerable: false,
|
|
61
|
+
value: storage,
|
|
62
|
+
writable: false
|
|
63
|
+
});
|
|
64
|
+
return storage;
|
|
65
|
+
}
|
|
66
|
+
function getWikiGraphSDKRuntimeContext() {
|
|
67
|
+
return runtimeContext.getStore() ?? {
|
|
68
|
+
cwd: process.cwd(),
|
|
69
|
+
env: process.env,
|
|
70
|
+
envPolicy: "production"
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function getWikiGraphSDKStateDir() {
|
|
74
|
+
return getWikiGraphSDKRuntimeContext().stateDir;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/node-platform.ts
|
|
78
|
+
var asyncHooks = __toESM(require("async_hooks"), 1);
|
|
79
|
+
var crypto = __toESM(require("crypto"), 1);
|
|
80
|
+
var fs = __toESM(require("fs"), 1);
|
|
81
|
+
var fsPromises = __toESM(require("fs/promises"), 1);
|
|
82
|
+
var os = __toESM(require("os"), 1);
|
|
83
|
+
var pathModule = __toESM(require("path"), 1);
|
|
84
|
+
var process2 = __toESM(require("process"), 1);
|
|
85
|
+
var import_node_stream = require("stream");
|
|
86
|
+
var import_promises = require("stream/promises");
|
|
87
|
+
var sqlite3 = __toESM(require("sqlite3"), 1);
|
|
88
|
+
var yauzl = __toESM(require("yauzl"), 1);
|
|
89
|
+
var yazl = __toESM(require("yazl"), 1);
|
|
90
|
+
var import_nunjucks = require("nunjucks");
|
|
91
|
+
var import_platform = require("wiki-graph-core/platform");
|
|
92
|
+
var nodeProcess = process2.default ?? process2;
|
|
93
|
+
var nodeSqlite3 = sqlite3.default ?? sqlite3;
|
|
94
|
+
var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
|
|
95
|
+
var NodeFile = class {
|
|
96
|
+
constructor(path, name = pathModule.basename(path)) {
|
|
97
|
+
this.path = path;
|
|
98
|
+
this.identity = encodeNodeResourceIdentity("file", path);
|
|
99
|
+
this.name = name;
|
|
100
|
+
}
|
|
101
|
+
path;
|
|
102
|
+
kind = "file";
|
|
103
|
+
[NODE_RESOURCE_KIND] = "file";
|
|
104
|
+
identity;
|
|
105
|
+
name;
|
|
106
|
+
async openReader() {
|
|
107
|
+
const handle = await fsPromises.open(this.path, "r");
|
|
108
|
+
let closed = false;
|
|
109
|
+
try {
|
|
110
|
+
const stats = await handle.stat();
|
|
111
|
+
if (!stats.isFile())
|
|
112
|
+
throw new Error("File reader requires a regular file");
|
|
113
|
+
const { size } = stats;
|
|
114
|
+
return {
|
|
115
|
+
size,
|
|
116
|
+
close: async () => {
|
|
117
|
+
if (!closed) await handle.close();
|
|
118
|
+
closed = true;
|
|
119
|
+
},
|
|
120
|
+
read: async (offset, length) => {
|
|
121
|
+
if (closed) throw new Error("Cannot read from a closed FileReader");
|
|
122
|
+
assertFileRange(offset, length, size);
|
|
123
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
124
|
+
let bytesRead = 0;
|
|
125
|
+
while (bytesRead < length) {
|
|
126
|
+
const result = await handle.read(
|
|
127
|
+
buffer,
|
|
128
|
+
bytesRead,
|
|
129
|
+
length - bytesRead,
|
|
130
|
+
offset + bytesRead
|
|
131
|
+
);
|
|
132
|
+
if (result.bytesRead === 0) {
|
|
133
|
+
throw new Error("File changed while reading its byte range");
|
|
134
|
+
}
|
|
135
|
+
bytesRead += result.bytesRead;
|
|
136
|
+
}
|
|
137
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, bytesRead);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
} catch (error) {
|
|
141
|
+
await handle.close();
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async getLastModified() {
|
|
146
|
+
try {
|
|
147
|
+
return (await fsPromises.stat(this.path)).mtimeMs;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
150
|
+
return void 0;
|
|
151
|
+
}
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async openWriter() {
|
|
156
|
+
await fsPromises.mkdir(pathModule.dirname(this.path), { recursive: true });
|
|
157
|
+
const temporary = `${this.path}.tmp-${crypto.randomUUID()}`;
|
|
158
|
+
const handle = await fsPromises.open(temporary, "wx");
|
|
159
|
+
let closed = false;
|
|
160
|
+
return {
|
|
161
|
+
write: async (data) => {
|
|
162
|
+
if (closed) throw new Error("Cannot write to a closed FileWriter");
|
|
163
|
+
await writeNodeFileHandle(handle, data);
|
|
164
|
+
},
|
|
165
|
+
writeAt: async (offset, data) => {
|
|
166
|
+
if (closed) throw new Error("Cannot write to a closed FileWriter");
|
|
167
|
+
assertFileOffset(offset);
|
|
168
|
+
await writeNodeFileHandle(handle, data, offset);
|
|
169
|
+
},
|
|
170
|
+
commit: async () => {
|
|
171
|
+
if (!closed) {
|
|
172
|
+
await handle.close();
|
|
173
|
+
await fsPromises.rename(temporary, this.path);
|
|
174
|
+
}
|
|
175
|
+
closed = true;
|
|
176
|
+
},
|
|
177
|
+
abort: async () => {
|
|
178
|
+
if (!closed) {
|
|
179
|
+
await handle.close();
|
|
180
|
+
await fsPromises.rm(temporary, { force: true });
|
|
181
|
+
}
|
|
182
|
+
closed = true;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
async function writeNodeFileHandle(handle, data, position) {
|
|
188
|
+
const buffer = Buffer.from(data);
|
|
189
|
+
let written = 0;
|
|
190
|
+
while (written < buffer.byteLength) {
|
|
191
|
+
const result = await handle.write(
|
|
192
|
+
buffer,
|
|
193
|
+
written,
|
|
194
|
+
buffer.byteLength - written,
|
|
195
|
+
position === void 0 ? null : position + written
|
|
196
|
+
);
|
|
197
|
+
if (result.bytesWritten === 0) {
|
|
198
|
+
throw new Error("File writer made no progress");
|
|
199
|
+
}
|
|
200
|
+
written += result.bytesWritten;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function assertFileRange(offset, length, size) {
|
|
204
|
+
assertFileOffset(offset);
|
|
205
|
+
if (!Number.isSafeInteger(length) || length < 0) {
|
|
206
|
+
throw new RangeError(
|
|
207
|
+
"File read length must be a non-negative safe integer"
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (offset > size || length > size - offset) {
|
|
211
|
+
throw new RangeError("File read range exceeds the file size");
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function assertFileOffset(offset) {
|
|
215
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
216
|
+
throw new RangeError("File offset must be a non-negative safe integer");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
var NodeDirectory = class _NodeDirectory {
|
|
220
|
+
constructor(path) {
|
|
221
|
+
this.path = path;
|
|
222
|
+
this.identity = encodeNodeResourceIdentity("directory", path);
|
|
223
|
+
this.name = pathModule.basename(path);
|
|
224
|
+
}
|
|
225
|
+
path;
|
|
226
|
+
kind = "directory";
|
|
227
|
+
[NODE_RESOURCE_KIND] = "directory";
|
|
228
|
+
identity;
|
|
229
|
+
name;
|
|
230
|
+
async getFile(name) {
|
|
231
|
+
assertChildName(name);
|
|
232
|
+
const file = new NodeFile(pathModule.join(this.path, name));
|
|
233
|
+
try {
|
|
234
|
+
return (await fsPromises.stat(file.path)).isFile() ? file : void 0;
|
|
235
|
+
} catch {
|
|
236
|
+
return void 0;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async getLastModified() {
|
|
240
|
+
try {
|
|
241
|
+
return (await fsPromises.stat(this.path)).mtimeMs;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
244
|
+
return void 0;
|
|
245
|
+
}
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async getDirectory(name) {
|
|
250
|
+
assertChildName(name);
|
|
251
|
+
const directory = new _NodeDirectory(pathModule.join(this.path, name));
|
|
252
|
+
try {
|
|
253
|
+
return (await fsPromises.stat(directory.path)).isDirectory() ? directory : void 0;
|
|
254
|
+
} catch {
|
|
255
|
+
return void 0;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
async list() {
|
|
259
|
+
const entries = await fsPromises.readdir(this.path, {
|
|
260
|
+
withFileTypes: true
|
|
261
|
+
});
|
|
262
|
+
return entries.map(
|
|
263
|
+
(entry) => entry.isDirectory() ? new _NodeDirectory(pathModule.join(this.path, entry.name)) : new NodeFile(pathModule.join(this.path, entry.name), entry.name)
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
async createFile(name) {
|
|
267
|
+
assertChildName(name);
|
|
268
|
+
await fsPromises.mkdir(this.path, { recursive: true });
|
|
269
|
+
const file = new NodeFile(pathModule.join(this.path, name));
|
|
270
|
+
await fsPromises.writeFile(file.path, "", { flag: "wx" });
|
|
271
|
+
return file;
|
|
272
|
+
}
|
|
273
|
+
async createDirectory(name) {
|
|
274
|
+
assertChildName(name);
|
|
275
|
+
await fsPromises.mkdir(this.path, { recursive: true });
|
|
276
|
+
const directory = new _NodeDirectory(pathModule.join(this.path, name));
|
|
277
|
+
await fsPromises.mkdir(directory.path);
|
|
278
|
+
return directory;
|
|
279
|
+
}
|
|
280
|
+
async remove(name, options) {
|
|
281
|
+
assertChildName(name);
|
|
282
|
+
await fsPromises.rm(pathModule.join(this.path, name), {
|
|
283
|
+
force: true,
|
|
284
|
+
recursive: options?.recursive === true
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
function encodeNodeResourceIdentity(kind, path) {
|
|
289
|
+
return `node-${kind}:${Buffer.from(pathModule.resolve(path), "utf8").toString("base64url")}`;
|
|
290
|
+
}
|
|
291
|
+
function decodeNodeResourceIdentity(identity, kind) {
|
|
292
|
+
const prefix = `node-${kind}:`;
|
|
293
|
+
if (!identity.startsWith(prefix)) {
|
|
294
|
+
return pathModule.isAbsolute(identity) ? identity : void 0;
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
return Buffer.from(identity.slice(prefix.length), "base64url").toString(
|
|
298
|
+
"utf8"
|
|
299
|
+
);
|
|
300
|
+
} catch {
|
|
301
|
+
return void 0;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function assertChildName(name) {
|
|
305
|
+
if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
|
|
306
|
+
throw new TypeError(`Directory child must be a relative name: ${name}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
var NodeDatabaseConnection = class {
|
|
310
|
+
constructor(database) {
|
|
311
|
+
this.database = database;
|
|
312
|
+
}
|
|
313
|
+
database;
|
|
314
|
+
async close() {
|
|
315
|
+
await new Promise((resolve2, reject) => {
|
|
316
|
+
this.database.close((error) => {
|
|
317
|
+
if (error) reject(error);
|
|
318
|
+
else resolve2();
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
async execute(sql) {
|
|
323
|
+
await new Promise((resolve2, reject) => {
|
|
324
|
+
this.database.exec(sql, (error) => {
|
|
325
|
+
if (error) reject(error);
|
|
326
|
+
else resolve2();
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
async queryAll(sql, params = []) {
|
|
331
|
+
return await new Promise((resolve2, reject) => {
|
|
332
|
+
this.database.all(sql, [...params], (error, rows) => {
|
|
333
|
+
if (error) reject(error);
|
|
334
|
+
else resolve2(rows);
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
async queryOne(sql, params = []) {
|
|
339
|
+
return await new Promise((resolve2, reject) => {
|
|
340
|
+
this.database.get(sql, [...params], (error, row) => {
|
|
341
|
+
if (error) reject(error);
|
|
342
|
+
else resolve2(row);
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
async run(sql, params = []) {
|
|
347
|
+
await new Promise((resolve2, reject) => {
|
|
348
|
+
this.database.run(sql, [...params], (error) => {
|
|
349
|
+
if (error) reject(error);
|
|
350
|
+
else resolve2();
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
async function openNodeDatabase(file, options) {
|
|
356
|
+
const flags = (options.mode === "readonly" ? nodeSqlite3.OPEN_READONLY : nodeSqlite3.OPEN_READWRITE | (options.create ? nodeSqlite3.OPEN_CREATE : 0)) | nodeSqlite3.OPEN_FULLMUTEX;
|
|
357
|
+
return new NodeDatabaseConnection(await openNativeNodeDatabase(file, flags));
|
|
358
|
+
}
|
|
359
|
+
async function openNativeNodeDatabase(file, flags) {
|
|
360
|
+
const path = getBrandedNodeResourcePath(file, "file");
|
|
361
|
+
if (path === void 0) {
|
|
362
|
+
throw new TypeError("The Node database adapter requires a NodeFile");
|
|
363
|
+
}
|
|
364
|
+
return await new Promise((resolve2, reject) => {
|
|
365
|
+
const database = new nodeSqlite3.Database(path, flags, (error) => {
|
|
366
|
+
if (error) reject(error);
|
|
367
|
+
else resolve2(database);
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
async function openNodeZip(file) {
|
|
372
|
+
const path = getBrandedNodeResourcePath(file, "file");
|
|
373
|
+
if (path === void 0) {
|
|
374
|
+
throw new TypeError("The Node ZIP adapter requires a NodeFile");
|
|
375
|
+
}
|
|
376
|
+
const zipFile = await new Promise((resolve2, reject) => {
|
|
377
|
+
yauzl.open(
|
|
378
|
+
path,
|
|
379
|
+
{ autoClose: false, lazyEntries: true },
|
|
380
|
+
(error, opened) => {
|
|
381
|
+
if (error || opened === void 0)
|
|
382
|
+
reject(error ?? new Error("Cannot open ZIP"));
|
|
383
|
+
else resolve2(opened);
|
|
384
|
+
}
|
|
385
|
+
);
|
|
386
|
+
});
|
|
387
|
+
const entries = await new Promise(
|
|
388
|
+
(resolve2, reject) => {
|
|
389
|
+
const discovered = /* @__PURE__ */ new Map();
|
|
390
|
+
const rejectAndClose = (error) => {
|
|
391
|
+
zipFile.close();
|
|
392
|
+
reject(
|
|
393
|
+
error instanceof Error ? error : new Error("Cannot scan ZIP central directory")
|
|
394
|
+
);
|
|
395
|
+
};
|
|
396
|
+
const resolveEntries = () => {
|
|
397
|
+
zipFile.off("error", rejectAndClose);
|
|
398
|
+
resolve2(discovered);
|
|
399
|
+
};
|
|
400
|
+
zipFile.on("entry", (entry) => {
|
|
401
|
+
if (!entry.fileName.endsWith("/")) {
|
|
402
|
+
discovered.set(entry.fileName, entry);
|
|
403
|
+
}
|
|
404
|
+
zipFile.readEntry();
|
|
405
|
+
});
|
|
406
|
+
zipFile.once("error", rejectAndClose);
|
|
407
|
+
zipFile.once("end", resolveEntries);
|
|
408
|
+
zipFile.readEntry();
|
|
409
|
+
}
|
|
410
|
+
);
|
|
411
|
+
let closed = false;
|
|
412
|
+
return {
|
|
413
|
+
close: () => {
|
|
414
|
+
if (!closed) zipFile.close();
|
|
415
|
+
closed = true;
|
|
416
|
+
return Promise.resolve();
|
|
417
|
+
},
|
|
418
|
+
copyEntry: async (name, target) => {
|
|
419
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
420
|
+
const entry = entries.get(name);
|
|
421
|
+
if (entry === void 0) return false;
|
|
422
|
+
await copyNodeZipEntry(zipFile, entry, target);
|
|
423
|
+
return true;
|
|
424
|
+
},
|
|
425
|
+
getEntrySize: (name) => {
|
|
426
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
427
|
+
return Promise.resolve(entries.get(name)?.uncompressedSize);
|
|
428
|
+
},
|
|
429
|
+
listEntries: () => Promise.resolve([...entries.keys()]),
|
|
430
|
+
readEntryRange: async (name, offset, length) => {
|
|
431
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
432
|
+
const entry = entries.get(name);
|
|
433
|
+
if (entry === void 0) return void 0;
|
|
434
|
+
return await readNodeZipEntryRange(zipFile, entry, offset, length);
|
|
435
|
+
},
|
|
436
|
+
readEntry: async (name) => {
|
|
437
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
438
|
+
const entry = entries.get(name);
|
|
439
|
+
if (entry === void 0) return void 0;
|
|
440
|
+
return await readNodeZipEntry(zipFile, entry);
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
async function copyNodeZipEntry(zipFile, entry, target) {
|
|
445
|
+
const writer = await target.openWriter();
|
|
446
|
+
try {
|
|
447
|
+
const stream = await openNodeZipEntryStream(zipFile, entry);
|
|
448
|
+
await writeNodeStream(stream, writer);
|
|
449
|
+
await writer.commit();
|
|
450
|
+
} catch (error) {
|
|
451
|
+
await writer.abort().catch(() => void 0);
|
|
452
|
+
throw error;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
async function readNodeZipEntry(zipFile, entry) {
|
|
456
|
+
return await collectNodeStream(await openNodeZipEntryStream(zipFile, entry));
|
|
457
|
+
}
|
|
458
|
+
async function readNodeZipEntryRange(zipFile, entry, offset, length) {
|
|
459
|
+
assertFileRange(offset, length, entry.uncompressedSize);
|
|
460
|
+
if (length === 0) return new Uint8Array();
|
|
461
|
+
if (entry.compressionMethod !== 0) {
|
|
462
|
+
const content2 = await collectDecodedNodeStreamRange(
|
|
463
|
+
await openNodeZipEntryStream(zipFile, entry),
|
|
464
|
+
offset,
|
|
465
|
+
length
|
|
466
|
+
);
|
|
467
|
+
return new Uint8Array(
|
|
468
|
+
content2.buffer,
|
|
469
|
+
content2.byteOffset,
|
|
470
|
+
content2.byteLength
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
const content = await collectNodeStream(
|
|
474
|
+
await openNodeZipEntryStream(zipFile, entry, {
|
|
475
|
+
decompress: null,
|
|
476
|
+
decrypt: null,
|
|
477
|
+
end: offset + length,
|
|
478
|
+
start: offset
|
|
479
|
+
})
|
|
480
|
+
);
|
|
481
|
+
return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
|
|
482
|
+
}
|
|
483
|
+
async function collectDecodedNodeStreamRange(input, offset, length) {
|
|
484
|
+
const chunks = [];
|
|
485
|
+
const end = offset + length;
|
|
486
|
+
let position = 0;
|
|
487
|
+
let collected = 0;
|
|
488
|
+
for await (const value of input) {
|
|
489
|
+
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
490
|
+
const chunkEnd = position + chunk.byteLength;
|
|
491
|
+
if (chunkEnd > offset && position < end) {
|
|
492
|
+
const selected = chunk.subarray(
|
|
493
|
+
Math.max(0, offset - position),
|
|
494
|
+
Math.min(chunk.byteLength, end - position)
|
|
495
|
+
);
|
|
496
|
+
chunks.push(selected);
|
|
497
|
+
collected += selected.byteLength;
|
|
498
|
+
}
|
|
499
|
+
position = chunkEnd;
|
|
500
|
+
if (position >= end) break;
|
|
501
|
+
}
|
|
502
|
+
if (collected !== length) {
|
|
503
|
+
throw new Error("ZIP entry changed while reading its byte range");
|
|
504
|
+
}
|
|
505
|
+
return Buffer.concat(chunks, collected);
|
|
506
|
+
}
|
|
507
|
+
async function openNodeZipEntryStream(zipFile, entry, options) {
|
|
508
|
+
return await new Promise((resolve2, reject) => {
|
|
509
|
+
const callback = (error, opened) => {
|
|
510
|
+
if (error || opened === void 0) {
|
|
511
|
+
reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
|
|
512
|
+
} else {
|
|
513
|
+
resolve2(opened);
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
if (options === void 0) zipFile.openReadStream(entry, callback);
|
|
517
|
+
else zipFile.openReadStream(entry, options, callback);
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
async function writeNodeZip(file, entries) {
|
|
521
|
+
const zipFile = new yazl.ZipFile();
|
|
522
|
+
const writer = await file.openWriter();
|
|
523
|
+
const outputStream = zipFile.outputStream;
|
|
524
|
+
const outputDone = writeNodeStream(outputStream, writer);
|
|
525
|
+
const entryState = { cancelled: false, complete: false };
|
|
526
|
+
let iterator;
|
|
527
|
+
try {
|
|
528
|
+
iterator = getNodeZipEntryIterator(entries);
|
|
529
|
+
const entriesDone = addNodeZipEntries(zipFile, iterator, entryState);
|
|
530
|
+
await Promise.race([entriesDone, outputDone]);
|
|
531
|
+
if (!entryState.complete) {
|
|
532
|
+
throw new Error("ZIP output ended before entry production completed");
|
|
533
|
+
}
|
|
534
|
+
zipFile.end();
|
|
535
|
+
await outputDone;
|
|
536
|
+
await writer.commit();
|
|
537
|
+
} catch (error) {
|
|
538
|
+
entryState.cancelled = true;
|
|
539
|
+
if (!entryState.complete && iterator !== void 0) {
|
|
540
|
+
closeNodeZipEntryIterator(iterator);
|
|
541
|
+
}
|
|
542
|
+
if (!outputStream.destroyed) {
|
|
543
|
+
outputStream.destroy(
|
|
544
|
+
error instanceof Error ? error : new Error("Cannot write ZIP archive")
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
await outputDone.catch(() => void 0);
|
|
548
|
+
await writer.abort().catch(() => void 0);
|
|
549
|
+
throw error;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
async function addNodeZipEntries(zipFile, iterator, state) {
|
|
553
|
+
while (!state.cancelled) {
|
|
554
|
+
const result = await iterator.next();
|
|
555
|
+
if (state.cancelled) return;
|
|
556
|
+
if (result.done) {
|
|
557
|
+
state.complete = true;
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if ("file" in result.value) {
|
|
561
|
+
zipFile.addReadStream(
|
|
562
|
+
createNodeFileReadStream(result.value.file),
|
|
563
|
+
result.value.name,
|
|
564
|
+
{ compress: false }
|
|
565
|
+
);
|
|
566
|
+
} else if ("data" in result.value) {
|
|
567
|
+
zipFile.addBuffer(Buffer.from(result.value.data), result.value.name, {
|
|
568
|
+
compress: false
|
|
569
|
+
});
|
|
570
|
+
} else {
|
|
571
|
+
zipFile.addReadStream(
|
|
572
|
+
createNodeRangeReadStream(result.value),
|
|
573
|
+
result.value.name,
|
|
574
|
+
{ compress: false, size: result.value.size }
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
function createNodeFileReadStream(file) {
|
|
580
|
+
return import_node_stream.Readable.from(
|
|
581
|
+
(async function* () {
|
|
582
|
+
const reader = await file.openReader();
|
|
583
|
+
try {
|
|
584
|
+
for (let offset = 0; offset < reader.size; ) {
|
|
585
|
+
const chunk = await reader.read(
|
|
586
|
+
offset,
|
|
587
|
+
Math.min(64 * 1024, reader.size - offset)
|
|
588
|
+
);
|
|
589
|
+
offset += chunk.byteLength;
|
|
590
|
+
yield chunk;
|
|
591
|
+
}
|
|
592
|
+
} finally {
|
|
593
|
+
await reader.close();
|
|
594
|
+
}
|
|
595
|
+
})()
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
function getBrandedNodeResourcePath(resource, kind) {
|
|
599
|
+
if (typeof resource !== "object" || resource === null) return void 0;
|
|
600
|
+
const candidate = resource;
|
|
601
|
+
return candidate[NODE_RESOURCE_KIND] === kind && typeof candidate.path === "string" ? candidate.path : void 0;
|
|
602
|
+
}
|
|
603
|
+
function createNodeRangeReadStream(entry) {
|
|
604
|
+
return import_node_stream.Readable.from(
|
|
605
|
+
(async function* () {
|
|
606
|
+
for (let offset = 0; offset < entry.size; ) {
|
|
607
|
+
const chunk = await entry.read(
|
|
608
|
+
offset,
|
|
609
|
+
Math.min(64 * 1024, entry.size - offset)
|
|
610
|
+
);
|
|
611
|
+
offset += chunk.byteLength;
|
|
612
|
+
yield chunk;
|
|
613
|
+
}
|
|
614
|
+
})()
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
function getNodeZipEntryIterator(entries) {
|
|
618
|
+
const asyncIterator = entries[Symbol.asyncIterator];
|
|
619
|
+
return asyncIterator === void 0 ? entries[Symbol.iterator]() : asyncIterator.call(entries);
|
|
620
|
+
}
|
|
621
|
+
function closeNodeZipEntryIterator(iterator) {
|
|
622
|
+
if (iterator.return === void 0) return;
|
|
623
|
+
try {
|
|
624
|
+
void Promise.resolve(iterator.return()).catch(() => void 0);
|
|
625
|
+
} catch {
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
async function writeNodeStream(input, writer) {
|
|
629
|
+
await (0, import_promises.pipeline)(
|
|
630
|
+
input,
|
|
631
|
+
new import_node_stream.Writable({
|
|
632
|
+
write: (chunk, _encoding, callback) => {
|
|
633
|
+
void writer.write(chunk).then(
|
|
634
|
+
() => callback(),
|
|
635
|
+
(error) => callback(
|
|
636
|
+
error instanceof Error ? error : new Error("Cannot stream ZIP archive")
|
|
637
|
+
)
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
})
|
|
641
|
+
);
|
|
642
|
+
}
|
|
643
|
+
async function collectNodeStream(input) {
|
|
644
|
+
return await new Promise((resolve2, reject) => {
|
|
645
|
+
const chunks = [];
|
|
646
|
+
input.on("data", (chunk) => chunks.push(chunk));
|
|
647
|
+
input.once("error", reject);
|
|
648
|
+
input.once("end", () => resolve2(Buffer.concat(chunks)));
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
var nodeWikiGraphPlatform = {
|
|
652
|
+
asyncContext: {
|
|
653
|
+
create: () => new asyncHooks.AsyncLocalStorage()
|
|
654
|
+
},
|
|
655
|
+
database: { open: openNodeDatabase },
|
|
656
|
+
lifecycle: {
|
|
657
|
+
instanceId: `node-process:${nodeProcess.pid}`,
|
|
658
|
+
isInstanceAlive: (instanceId) => {
|
|
659
|
+
const match = /^node-process:(\d+)$/u.exec(instanceId);
|
|
660
|
+
if (match === null) return Promise.resolve(void 0);
|
|
661
|
+
try {
|
|
662
|
+
nodeProcess.kill(Number(match[1]), 0);
|
|
663
|
+
return Promise.resolve(true);
|
|
664
|
+
} catch (error) {
|
|
665
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH") {
|
|
666
|
+
return Promise.resolve(false);
|
|
667
|
+
}
|
|
668
|
+
return Promise.resolve(true);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
},
|
|
672
|
+
resources: {
|
|
673
|
+
getDirectory: (identity) => {
|
|
674
|
+
const path = decodeNodeResourceIdentity(identity, "directory");
|
|
675
|
+
return Promise.resolve(
|
|
676
|
+
path === void 0 ? void 0 : new NodeDirectory(path)
|
|
677
|
+
);
|
|
678
|
+
},
|
|
679
|
+
getFile: (identity) => {
|
|
680
|
+
const path = decodeNodeResourceIdentity(identity, "file");
|
|
681
|
+
return Promise.resolve(
|
|
682
|
+
path === void 0 ? void 0 : new NodeFile(path)
|
|
683
|
+
);
|
|
684
|
+
},
|
|
685
|
+
resolveLegacyDirectory: (reference) => {
|
|
686
|
+
const path = decodeNodeResourceIdentity(reference, "directory");
|
|
687
|
+
return Promise.resolve(
|
|
688
|
+
path === void 0 ? void 0 : new NodeDirectory(path)
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
},
|
|
692
|
+
templates: {
|
|
693
|
+
createEnvironment: (options) => new import_nunjucks.Environment(new NodeTemplateLoader(), options)
|
|
694
|
+
},
|
|
695
|
+
zip: {
|
|
696
|
+
open: openNodeZip,
|
|
697
|
+
write: writeNodeZip
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
var NodeTemplateLoader = class extends import_nunjucks.Loader {
|
|
701
|
+
#dataDirectory;
|
|
702
|
+
constructor(dataDirectory) {
|
|
703
|
+
super();
|
|
704
|
+
this.#dataDirectory = dataDirectory;
|
|
705
|
+
}
|
|
706
|
+
getSource(templateName) {
|
|
707
|
+
const name = (0, import_platform.normalizeTemplateName)(templateName);
|
|
708
|
+
const filePath = pathModule.join(
|
|
709
|
+
this.#dataDirectory ?? resolveNodeDataDirectory(),
|
|
710
|
+
name
|
|
711
|
+
);
|
|
712
|
+
return {
|
|
713
|
+
noCache: false,
|
|
714
|
+
path: name,
|
|
715
|
+
src: fs.readFileSync(filePath, "utf8")
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
function resolveNodeDataDirectory() {
|
|
720
|
+
const injected = globalThis.__WIKIGRAPH_DATA_DIR__;
|
|
721
|
+
if (typeof injected === "string" && injected !== "") return injected;
|
|
722
|
+
let directory = nodeProcess.cwd();
|
|
723
|
+
while (true) {
|
|
724
|
+
for (const candidate of [
|
|
725
|
+
pathModule.join(directory, "data"),
|
|
726
|
+
pathModule.join(directory, "packages", "core", "data")
|
|
727
|
+
]) {
|
|
728
|
+
try {
|
|
729
|
+
if (fs.statSync(candidate).isDirectory()) return candidate;
|
|
730
|
+
} catch {
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const parent = pathModule.dirname(directory);
|
|
734
|
+
if (parent === directory)
|
|
735
|
+
throw new Error("Could not locate data directory");
|
|
736
|
+
directory = parent;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// src/local-config.ts
|
|
741
|
+
var import_path = require("path");
|
|
742
|
+
var import_os = require("os");
|
|
743
|
+
var LOCAL_CONFIG_SCHEMA_SQL = `
|
|
744
|
+
CREATE TABLE IF NOT EXISTS config_sections (
|
|
745
|
+
section TEXT PRIMARY KEY,
|
|
746
|
+
value_json TEXT NOT NULL,
|
|
747
|
+
updated_at INTEGER NOT NULL
|
|
748
|
+
);
|
|
749
|
+
`;
|
|
750
|
+
async function readLocalConfigSection(section) {
|
|
751
|
+
return await withLocalConfigDatabase(async (database) => {
|
|
752
|
+
return await readLocalConfigSectionInDatabase(database, section);
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
function validateLocalConfigSection(section, value) {
|
|
756
|
+
switch (section) {
|
|
757
|
+
case "embeddings":
|
|
758
|
+
return validateEmbeddingsConfig(value);
|
|
759
|
+
case "llm":
|
|
760
|
+
return validateLLMConfig(value);
|
|
761
|
+
case "concurrent":
|
|
762
|
+
return validateConcurrentConfig(value);
|
|
763
|
+
case "wikimedia":
|
|
764
|
+
return validateWikimediaConfig(value);
|
|
765
|
+
case "wikispine":
|
|
766
|
+
return validateWikispineConfig(value);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
async function withLocalConfigDatabase(operation) {
|
|
770
|
+
const database = await (0, import_wiki_graph_core.openSharedStateDatabase)(
|
|
771
|
+
new NodeFile(
|
|
772
|
+
(0, import_path.join)(
|
|
773
|
+
getWikiGraphSDKStateDir() ?? (0, import_path.join)((0, import_os.homedir)(), ".wikigraph"),
|
|
774
|
+
"core.sqlite"
|
|
775
|
+
)
|
|
776
|
+
),
|
|
777
|
+
LOCAL_CONFIG_SCHEMA_SQL
|
|
778
|
+
);
|
|
779
|
+
try {
|
|
780
|
+
return await operation(database);
|
|
781
|
+
} finally {
|
|
782
|
+
await database.close();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
async function readLocalConfigSectionInDatabase(database, section) {
|
|
786
|
+
const value = await database.queryOne(
|
|
787
|
+
"SELECT value_json FROM config_sections WHERE section = ?",
|
|
788
|
+
[section],
|
|
789
|
+
(row) => String(row.value_json)
|
|
790
|
+
);
|
|
791
|
+
return value === void 0 ? {} : parseSectionJSON(section, value);
|
|
792
|
+
}
|
|
793
|
+
function parseSectionJSON(section, value) {
|
|
794
|
+
let parsed;
|
|
795
|
+
try {
|
|
796
|
+
parsed = JSON.parse(value);
|
|
797
|
+
} catch (error) {
|
|
798
|
+
throw new Error(
|
|
799
|
+
`Invalid local config JSON for ${section}: ${formatError(error)}`
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
803
|
+
throw new Error(
|
|
804
|
+
`Invalid local config section ${section}: expected object.`
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
return validateLocalConfigSection(section, parsed);
|
|
808
|
+
}
|
|
809
|
+
function validateEmbeddingsConfig(value) {
|
|
810
|
+
const allowedKeys = /* @__PURE__ */ new Set([
|
|
811
|
+
"apiKey",
|
|
812
|
+
"baseURL",
|
|
813
|
+
"dimensions",
|
|
814
|
+
"model",
|
|
815
|
+
"name",
|
|
816
|
+
"provider"
|
|
817
|
+
]);
|
|
818
|
+
const allowedProviders = /* @__PURE__ */ new Set(["openai", "openai-compatible"]);
|
|
819
|
+
const next = {};
|
|
820
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
821
|
+
if (!allowedKeys.has(key)) {
|
|
822
|
+
throw new Error(`Unknown embeddings config key: ${key}`);
|
|
823
|
+
}
|
|
824
|
+
if (key === "dimensions") {
|
|
825
|
+
const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
|
|
826
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
827
|
+
throw new Error("embeddings.dimensions must be a positive integer.");
|
|
828
|
+
}
|
|
829
|
+
next[key] = parsed;
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
833
|
+
throw new Error(`embeddings.${key} must be a non-empty string.`);
|
|
834
|
+
}
|
|
835
|
+
const normalized = entry.trim();
|
|
836
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
837
|
+
throw new Error(`Unknown embeddings.provider: ${normalized}`);
|
|
838
|
+
}
|
|
839
|
+
next[key] = normalized;
|
|
840
|
+
}
|
|
841
|
+
return next;
|
|
842
|
+
}
|
|
843
|
+
function validateLLMConfig(value) {
|
|
844
|
+
const allowedKeys = /* @__PURE__ */ new Set([
|
|
845
|
+
"apiKey",
|
|
846
|
+
"baseURL",
|
|
847
|
+
"model",
|
|
848
|
+
"name",
|
|
849
|
+
"provider"
|
|
850
|
+
]);
|
|
851
|
+
const allowedProviders = /* @__PURE__ */ new Set([
|
|
852
|
+
"anthropic",
|
|
853
|
+
"google",
|
|
854
|
+
"openai",
|
|
855
|
+
"openai-compatible"
|
|
856
|
+
]);
|
|
857
|
+
const next = {};
|
|
858
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
859
|
+
if (!allowedKeys.has(key)) {
|
|
860
|
+
throw new Error(`Unknown llm config key: ${key}`);
|
|
861
|
+
}
|
|
862
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
863
|
+
throw new Error(`llm.${key} must be a non-empty string.`);
|
|
864
|
+
}
|
|
865
|
+
const normalized = entry.trim();
|
|
866
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
867
|
+
throw new Error(`Unknown llm.provider: ${normalized}`);
|
|
868
|
+
}
|
|
869
|
+
next[key] = normalized;
|
|
870
|
+
}
|
|
871
|
+
return next;
|
|
872
|
+
}
|
|
873
|
+
function validateConcurrentConfig(value) {
|
|
874
|
+
const allowedKeys = /* @__PURE__ */ new Set(["job", "request"]);
|
|
875
|
+
const next = {};
|
|
876
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
877
|
+
if (!allowedKeys.has(key)) {
|
|
878
|
+
throw new Error(`Unknown concurrent config key: ${key}`);
|
|
879
|
+
}
|
|
880
|
+
const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
|
|
881
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
882
|
+
throw new Error(`concurrent.${key} must be a positive integer.`);
|
|
883
|
+
}
|
|
884
|
+
next[key] = parsed;
|
|
885
|
+
}
|
|
886
|
+
return next;
|
|
887
|
+
}
|
|
888
|
+
function validateWikispineConfig(value) {
|
|
889
|
+
const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "provider", "token"]);
|
|
890
|
+
const allowedProviders = /* @__PURE__ */ new Set(["cli", "fetch"]);
|
|
891
|
+
const next = {};
|
|
892
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
893
|
+
if (!allowedKeys.has(key)) {
|
|
894
|
+
throw new Error(`Unknown wikispine config key: ${key}`);
|
|
895
|
+
}
|
|
896
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
897
|
+
throw new Error(`wikispine.${key} must be a non-empty string.`);
|
|
898
|
+
}
|
|
899
|
+
const normalized = entry.trim();
|
|
900
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
901
|
+
throw new Error(`Unknown wikispine.provider: ${normalized}`);
|
|
902
|
+
}
|
|
903
|
+
next[key] = normalized;
|
|
904
|
+
}
|
|
905
|
+
return next;
|
|
906
|
+
}
|
|
907
|
+
function validateWikimediaConfig(value) {
|
|
908
|
+
return validateEndpointConfig("wikimedia", value);
|
|
909
|
+
}
|
|
910
|
+
function validateEndpointConfig(section, value) {
|
|
911
|
+
const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "token"]);
|
|
912
|
+
const next = {};
|
|
913
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
914
|
+
if (!allowedKeys.has(key)) {
|
|
915
|
+
throw new Error(`Unknown ${section} config key: ${key}`);
|
|
916
|
+
}
|
|
917
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
918
|
+
throw new Error(`${section}.${key} must be a non-empty string.`);
|
|
919
|
+
}
|
|
920
|
+
next[key] = entry.trim();
|
|
921
|
+
}
|
|
922
|
+
return next;
|
|
923
|
+
}
|
|
924
|
+
function formatError(error) {
|
|
925
|
+
return error instanceof Error ? error.message : String(error);
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// src/embedding.ts
|
|
929
|
+
var EMBEDDING_BATCH_SIZE = 10;
|
|
930
|
+
async function readWikiGraphEmbeddingConfig() {
|
|
931
|
+
const config = await readLocalConfigSection("embeddings");
|
|
932
|
+
return {
|
|
933
|
+
...typeof config.apiKey === "string" ? { apiKey: config.apiKey } : {},
|
|
934
|
+
...typeof config.baseURL === "string" ? { baseURL: config.baseURL } : {},
|
|
935
|
+
...typeof config.dimensions === "number" ? { dimensions: config.dimensions } : {},
|
|
936
|
+
...typeof config.model === "string" ? { model: config.model } : {},
|
|
937
|
+
...typeof config.name === "string" ? { name: config.name } : {},
|
|
938
|
+
...typeof config.provider === "string" ? { provider: parseEmbeddingProvider(config.provider) } : {}
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
async function embedQueryText(value, config = {}) {
|
|
942
|
+
const normalized = value.trim();
|
|
943
|
+
if (normalized === "") {
|
|
944
|
+
throw new Error("Query text cannot be empty.");
|
|
945
|
+
}
|
|
946
|
+
const provider = requireEmbeddingProvider(config.provider);
|
|
947
|
+
const model = requireEmbeddingModel(config.model);
|
|
948
|
+
const embeddingModel = createEmbeddingModel(provider, model, config);
|
|
949
|
+
const providerOptions = createEmbeddingProviderOptions(provider, config);
|
|
950
|
+
const result = await (0, import_ai.embed)({
|
|
951
|
+
model: embeddingModel,
|
|
952
|
+
...providerOptions === void 0 ? {} : { providerOptions },
|
|
953
|
+
value: normalized
|
|
954
|
+
});
|
|
955
|
+
return {
|
|
956
|
+
dimensions: result.embedding.length,
|
|
957
|
+
embedding: result.embedding,
|
|
958
|
+
model,
|
|
959
|
+
provider,
|
|
960
|
+
...result.usage.tokens === void 0 ? {} : { usage: { tokens: result.usage.tokens } }
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
function buildSearchIndexEmbeddingProvider(config) {
|
|
964
|
+
const provider = requireEmbeddingProvider(config.provider);
|
|
965
|
+
const model = requireEmbeddingModel(config.model);
|
|
966
|
+
const embeddingModel = createEmbeddingModel(provider, model, config);
|
|
967
|
+
const providerOptions = createEmbeddingProviderOptions(provider, config);
|
|
968
|
+
return {
|
|
969
|
+
...config.dimensions === void 0 ? {} : { dimensions: config.dimensions },
|
|
970
|
+
identity: createEmbeddingIdentity(provider, model, config),
|
|
971
|
+
model,
|
|
972
|
+
embedTexts: async (texts, options) => {
|
|
973
|
+
const embeddings = [];
|
|
974
|
+
let tokens = 0;
|
|
975
|
+
for (const batch of chunkTexts(texts, EMBEDDING_BATCH_SIZE)) {
|
|
976
|
+
options?.signal?.throwIfAborted();
|
|
977
|
+
const result = await (0, import_ai.embedMany)({
|
|
978
|
+
...options?.signal === void 0 ? {} : { abortSignal: options.signal },
|
|
979
|
+
model: embeddingModel,
|
|
980
|
+
...providerOptions === void 0 ? {} : { providerOptions },
|
|
981
|
+
values: [...batch]
|
|
982
|
+
});
|
|
983
|
+
embeddings.push(...result.embeddings);
|
|
984
|
+
tokens += result.usage.tokens ?? 0;
|
|
985
|
+
}
|
|
986
|
+
return {
|
|
987
|
+
embeddings,
|
|
988
|
+
...tokens === 0 ? {} : { tokens }
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
function createEmbeddingIdentity(provider, model, config) {
|
|
994
|
+
return JSON.stringify({
|
|
995
|
+
...config.baseURL === void 0 ? {} : { baseURL: config.baseURL },
|
|
996
|
+
...config.dimensions === void 0 ? {} : { dimensions: config.dimensions },
|
|
997
|
+
model,
|
|
998
|
+
provider
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
function* chunkTexts(texts, size) {
|
|
1002
|
+
for (let index = 0; index < texts.length; index += size) {
|
|
1003
|
+
yield texts.slice(index, index + size);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
async function embedQueryTextWithLocalConfig(value) {
|
|
1007
|
+
return await embedQueryText(value, await readWikiGraphEmbeddingConfig());
|
|
1008
|
+
}
|
|
1009
|
+
function createEmbeddingModel(provider, model, config) {
|
|
1010
|
+
switch (provider) {
|
|
1011
|
+
case "openai": {
|
|
1012
|
+
if (config.baseURL !== void 0) {
|
|
1013
|
+
throw new Error(
|
|
1014
|
+
"openai does not accept embeddings.baseURL. Use openai-compatible for third-party OpenAI-style embeddings APIs."
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
return (0, import_openai.createOpenAI)({
|
|
1018
|
+
...config.apiKey === void 0 ? {} : { apiKey: config.apiKey },
|
|
1019
|
+
...config.name === void 0 ? {} : { name: config.name }
|
|
1020
|
+
}).embeddingModel(model);
|
|
1021
|
+
}
|
|
1022
|
+
case "openai-compatible": {
|
|
1023
|
+
if (config.baseURL === void 0) {
|
|
1024
|
+
throw new Error("openai-compatible requires embeddings.baseURL.");
|
|
1025
|
+
}
|
|
1026
|
+
return (0, import_openai_compatible.createOpenAICompatible)({
|
|
1027
|
+
baseURL: config.baseURL,
|
|
1028
|
+
name: config.name ?? createOpenAICompatibleName(config.baseURL),
|
|
1029
|
+
...config.apiKey === void 0 ? {} : { apiKey: config.apiKey }
|
|
1030
|
+
}).embeddingModel(model);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
function createEmbeddingProviderOptions(provider, config) {
|
|
1035
|
+
if (config.dimensions === void 0) {
|
|
1036
|
+
return void 0;
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
[getEmbeddingProviderOptionsName(provider, config)]: {
|
|
1040
|
+
dimensions: config.dimensions
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function getEmbeddingProviderOptionsName(provider, _config) {
|
|
1045
|
+
if (provider === "openai") {
|
|
1046
|
+
return "openai";
|
|
1047
|
+
}
|
|
1048
|
+
return "openaiCompatible";
|
|
1049
|
+
}
|
|
1050
|
+
function requireEmbeddingProvider(provider) {
|
|
1051
|
+
if (provider !== void 0) {
|
|
1052
|
+
return provider;
|
|
1053
|
+
}
|
|
1054
|
+
throw new Error(
|
|
1055
|
+
"Missing embeddings configuration. Configure `wikg://local/config/embeddings` with provider and model."
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
1058
|
+
function requireEmbeddingModel(model) {
|
|
1059
|
+
if (model !== void 0) {
|
|
1060
|
+
return model;
|
|
1061
|
+
}
|
|
1062
|
+
throw new Error(
|
|
1063
|
+
"Missing embeddings.model. Configure `wikg://local/config/embeddings` before using Dense search."
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
1066
|
+
function parseEmbeddingProvider(value) {
|
|
1067
|
+
switch (value) {
|
|
1068
|
+
case "openai":
|
|
1069
|
+
case "openai-compatible":
|
|
1070
|
+
return value;
|
|
1071
|
+
default:
|
|
1072
|
+
throw new Error(
|
|
1073
|
+
`Invalid embeddings.provider: ${value}. Expected openai or openai-compatible.`
|
|
1074
|
+
);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
function createOpenAICompatibleName(baseURL) {
|
|
1078
|
+
try {
|
|
1079
|
+
return new URL(baseURL).hostname;
|
|
1080
|
+
} catch {
|
|
1081
|
+
return "openai-compatible";
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1085
|
+
0 && (module.exports = {
|
|
1086
|
+
buildSearchIndexEmbeddingProvider,
|
|
1087
|
+
embedQueryText,
|
|
1088
|
+
embedQueryTextWithLocalConfig,
|
|
1089
|
+
readWikiGraphEmbeddingConfig
|
|
1090
|
+
});
|
|
1091
|
+
//# sourceMappingURL=embedding.cjs.map
|