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,1332 @@
|
|
|
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/conversions.ts
|
|
32
|
+
var conversions_exports = {};
|
|
33
|
+
__export(conversions_exports, {
|
|
34
|
+
WikiGraphConversionManager: () => WikiGraphConversionManager
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(conversions_exports);
|
|
37
|
+
var import_promises2 = require("fs/promises");
|
|
38
|
+
var import_wiki_graph_core2 = require("wiki-graph-core");
|
|
39
|
+
|
|
40
|
+
// src/llm.ts
|
|
41
|
+
var import_anthropic = require("@ai-sdk/anthropic");
|
|
42
|
+
var import_google = require("@ai-sdk/google");
|
|
43
|
+
var import_openai = require("@ai-sdk/openai");
|
|
44
|
+
var import_openai_compatible = require("@ai-sdk/openai-compatible");
|
|
45
|
+
function buildWikiGraphLLMOptions(config) {
|
|
46
|
+
const llm = config.llm;
|
|
47
|
+
if (llm?.provider === void 0 || llm.model === void 0) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"Missing LLM configuration. Set --llm for one run, or configure `wikg://local/config/llm` with provider and model."
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
model: createLanguageModel(llm.provider, llm.model, {
|
|
54
|
+
apiKey: llm.apiKey,
|
|
55
|
+
baseURL: llm.baseURL,
|
|
56
|
+
name: llm.name
|
|
57
|
+
}),
|
|
58
|
+
...config.concurrent?.request === void 0 ? {} : { concurrent: config.concurrent.request }
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function createLanguageModel(provider, model, options) {
|
|
62
|
+
switch (provider) {
|
|
63
|
+
case "anthropic": {
|
|
64
|
+
const anthropic = (0, import_anthropic.createAnthropic)({
|
|
65
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
|
|
66
|
+
...options.name === void 0 ? {} : { name: options.name }
|
|
67
|
+
});
|
|
68
|
+
return anthropic(model);
|
|
69
|
+
}
|
|
70
|
+
case "google": {
|
|
71
|
+
const google = (0, import_google.createGoogleGenerativeAI)({
|
|
72
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
|
|
73
|
+
...options.name === void 0 ? {} : { name: options.name }
|
|
74
|
+
});
|
|
75
|
+
return google(model);
|
|
76
|
+
}
|
|
77
|
+
case "openai": {
|
|
78
|
+
if (options.baseURL !== void 0) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
"openai does not accept llm.baseURL or baseURL in --llm JSON. Use openai-compatible for third-party OpenAI-style APIs."
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const openai = (0, import_openai.createOpenAI)({
|
|
84
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey },
|
|
85
|
+
...options.name === void 0 ? {} : { name: options.name }
|
|
86
|
+
});
|
|
87
|
+
return openai(model);
|
|
88
|
+
}
|
|
89
|
+
case "openai-compatible": {
|
|
90
|
+
if (options.baseURL === void 0) {
|
|
91
|
+
throw new Error(
|
|
92
|
+
"openai-compatible requires llm.baseURL or baseURL in --llm JSON."
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const openaiCompatible = (0, import_openai_compatible.createOpenAICompatible)({
|
|
96
|
+
baseURL: options.baseURL,
|
|
97
|
+
name: options.name ?? createOpenAICompatibleName(options.baseURL),
|
|
98
|
+
...options.apiKey === void 0 ? {} : { apiKey: options.apiKey }
|
|
99
|
+
});
|
|
100
|
+
return openaiCompatible(model);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function createOpenAICompatibleName(baseURL) {
|
|
105
|
+
try {
|
|
106
|
+
return new URL(baseURL).hostname;
|
|
107
|
+
} catch {
|
|
108
|
+
return "openai-compatible";
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/node-platform.ts
|
|
113
|
+
var asyncHooks = __toESM(require("async_hooks"), 1);
|
|
114
|
+
var crypto = __toESM(require("crypto"), 1);
|
|
115
|
+
var fs = __toESM(require("fs"), 1);
|
|
116
|
+
var fsPromises = __toESM(require("fs/promises"), 1);
|
|
117
|
+
var os = __toESM(require("os"), 1);
|
|
118
|
+
var pathModule = __toESM(require("path"), 1);
|
|
119
|
+
var process2 = __toESM(require("process"), 1);
|
|
120
|
+
var import_node_stream = require("stream");
|
|
121
|
+
var import_promises = require("stream/promises");
|
|
122
|
+
var sqlite3 = __toESM(require("sqlite3"), 1);
|
|
123
|
+
var yauzl = __toESM(require("yauzl"), 1);
|
|
124
|
+
var yazl = __toESM(require("yazl"), 1);
|
|
125
|
+
var import_nunjucks = require("nunjucks");
|
|
126
|
+
var import_platform = require("wiki-graph-core/platform");
|
|
127
|
+
var nodeProcess = process2.default ?? process2;
|
|
128
|
+
var nodeSqlite3 = sqlite3.default ?? sqlite3;
|
|
129
|
+
var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
|
|
130
|
+
var NodeFile = class {
|
|
131
|
+
constructor(path, name = pathModule.basename(path)) {
|
|
132
|
+
this.path = path;
|
|
133
|
+
this.identity = encodeNodeResourceIdentity("file", path);
|
|
134
|
+
this.name = name;
|
|
135
|
+
}
|
|
136
|
+
path;
|
|
137
|
+
kind = "file";
|
|
138
|
+
[NODE_RESOURCE_KIND] = "file";
|
|
139
|
+
identity;
|
|
140
|
+
name;
|
|
141
|
+
async openReader() {
|
|
142
|
+
const handle = await fsPromises.open(this.path, "r");
|
|
143
|
+
let closed = false;
|
|
144
|
+
try {
|
|
145
|
+
const stats = await handle.stat();
|
|
146
|
+
if (!stats.isFile())
|
|
147
|
+
throw new Error("File reader requires a regular file");
|
|
148
|
+
const { size } = stats;
|
|
149
|
+
return {
|
|
150
|
+
size,
|
|
151
|
+
close: async () => {
|
|
152
|
+
if (!closed) await handle.close();
|
|
153
|
+
closed = true;
|
|
154
|
+
},
|
|
155
|
+
read: async (offset, length) => {
|
|
156
|
+
if (closed) throw new Error("Cannot read from a closed FileReader");
|
|
157
|
+
assertFileRange(offset, length, size);
|
|
158
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
159
|
+
let bytesRead = 0;
|
|
160
|
+
while (bytesRead < length) {
|
|
161
|
+
const result = await handle.read(
|
|
162
|
+
buffer,
|
|
163
|
+
bytesRead,
|
|
164
|
+
length - bytesRead,
|
|
165
|
+
offset + bytesRead
|
|
166
|
+
);
|
|
167
|
+
if (result.bytesRead === 0) {
|
|
168
|
+
throw new Error("File changed while reading its byte range");
|
|
169
|
+
}
|
|
170
|
+
bytesRead += result.bytesRead;
|
|
171
|
+
}
|
|
172
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, bytesRead);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
} catch (error) {
|
|
176
|
+
await handle.close();
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async getLastModified() {
|
|
181
|
+
try {
|
|
182
|
+
return (await fsPromises.stat(this.path)).mtimeMs;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
185
|
+
return void 0;
|
|
186
|
+
}
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async openWriter() {
|
|
191
|
+
await fsPromises.mkdir(pathModule.dirname(this.path), { recursive: true });
|
|
192
|
+
const temporary = `${this.path}.tmp-${crypto.randomUUID()}`;
|
|
193
|
+
const handle = await fsPromises.open(temporary, "wx");
|
|
194
|
+
let closed = false;
|
|
195
|
+
return {
|
|
196
|
+
write: async (data) => {
|
|
197
|
+
if (closed) throw new Error("Cannot write to a closed FileWriter");
|
|
198
|
+
await writeNodeFileHandle(handle, data);
|
|
199
|
+
},
|
|
200
|
+
writeAt: async (offset, data) => {
|
|
201
|
+
if (closed) throw new Error("Cannot write to a closed FileWriter");
|
|
202
|
+
assertFileOffset(offset);
|
|
203
|
+
await writeNodeFileHandle(handle, data, offset);
|
|
204
|
+
},
|
|
205
|
+
commit: async () => {
|
|
206
|
+
if (!closed) {
|
|
207
|
+
await handle.close();
|
|
208
|
+
await fsPromises.rename(temporary, this.path);
|
|
209
|
+
}
|
|
210
|
+
closed = true;
|
|
211
|
+
},
|
|
212
|
+
abort: async () => {
|
|
213
|
+
if (!closed) {
|
|
214
|
+
await handle.close();
|
|
215
|
+
await fsPromises.rm(temporary, { force: true });
|
|
216
|
+
}
|
|
217
|
+
closed = true;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
async function writeNodeFileHandle(handle, data, position) {
|
|
223
|
+
const buffer = Buffer.from(data);
|
|
224
|
+
let written = 0;
|
|
225
|
+
while (written < buffer.byteLength) {
|
|
226
|
+
const result = await handle.write(
|
|
227
|
+
buffer,
|
|
228
|
+
written,
|
|
229
|
+
buffer.byteLength - written,
|
|
230
|
+
position === void 0 ? null : position + written
|
|
231
|
+
);
|
|
232
|
+
if (result.bytesWritten === 0) {
|
|
233
|
+
throw new Error("File writer made no progress");
|
|
234
|
+
}
|
|
235
|
+
written += result.bytesWritten;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function assertFileRange(offset, length, size) {
|
|
239
|
+
assertFileOffset(offset);
|
|
240
|
+
if (!Number.isSafeInteger(length) || length < 0) {
|
|
241
|
+
throw new RangeError(
|
|
242
|
+
"File read length must be a non-negative safe integer"
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
if (offset > size || length > size - offset) {
|
|
246
|
+
throw new RangeError("File read range exceeds the file size");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function assertFileOffset(offset) {
|
|
250
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
251
|
+
throw new RangeError("File offset must be a non-negative safe integer");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
var NodeDirectory = class _NodeDirectory {
|
|
255
|
+
constructor(path) {
|
|
256
|
+
this.path = path;
|
|
257
|
+
this.identity = encodeNodeResourceIdentity("directory", path);
|
|
258
|
+
this.name = pathModule.basename(path);
|
|
259
|
+
}
|
|
260
|
+
path;
|
|
261
|
+
kind = "directory";
|
|
262
|
+
[NODE_RESOURCE_KIND] = "directory";
|
|
263
|
+
identity;
|
|
264
|
+
name;
|
|
265
|
+
async getFile(name) {
|
|
266
|
+
assertChildName(name);
|
|
267
|
+
const file = new NodeFile(pathModule.join(this.path, name));
|
|
268
|
+
try {
|
|
269
|
+
return (await fsPromises.stat(file.path)).isFile() ? file : void 0;
|
|
270
|
+
} catch {
|
|
271
|
+
return void 0;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
async getLastModified() {
|
|
275
|
+
try {
|
|
276
|
+
return (await fsPromises.stat(this.path)).mtimeMs;
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
279
|
+
return void 0;
|
|
280
|
+
}
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
async getDirectory(name) {
|
|
285
|
+
assertChildName(name);
|
|
286
|
+
const directory = new _NodeDirectory(pathModule.join(this.path, name));
|
|
287
|
+
try {
|
|
288
|
+
return (await fsPromises.stat(directory.path)).isDirectory() ? directory : void 0;
|
|
289
|
+
} catch {
|
|
290
|
+
return void 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
async list() {
|
|
294
|
+
const entries = await fsPromises.readdir(this.path, {
|
|
295
|
+
withFileTypes: true
|
|
296
|
+
});
|
|
297
|
+
return entries.map(
|
|
298
|
+
(entry) => entry.isDirectory() ? new _NodeDirectory(pathModule.join(this.path, entry.name)) : new NodeFile(pathModule.join(this.path, entry.name), entry.name)
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
async createFile(name) {
|
|
302
|
+
assertChildName(name);
|
|
303
|
+
await fsPromises.mkdir(this.path, { recursive: true });
|
|
304
|
+
const file = new NodeFile(pathModule.join(this.path, name));
|
|
305
|
+
await fsPromises.writeFile(file.path, "", { flag: "wx" });
|
|
306
|
+
return file;
|
|
307
|
+
}
|
|
308
|
+
async createDirectory(name) {
|
|
309
|
+
assertChildName(name);
|
|
310
|
+
await fsPromises.mkdir(this.path, { recursive: true });
|
|
311
|
+
const directory = new _NodeDirectory(pathModule.join(this.path, name));
|
|
312
|
+
await fsPromises.mkdir(directory.path);
|
|
313
|
+
return directory;
|
|
314
|
+
}
|
|
315
|
+
async remove(name, options) {
|
|
316
|
+
assertChildName(name);
|
|
317
|
+
await fsPromises.rm(pathModule.join(this.path, name), {
|
|
318
|
+
force: true,
|
|
319
|
+
recursive: options?.recursive === true
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
function encodeNodeResourceIdentity(kind, path) {
|
|
324
|
+
return `node-${kind}:${Buffer.from(pathModule.resolve(path), "utf8").toString("base64url")}`;
|
|
325
|
+
}
|
|
326
|
+
function decodeNodeResourceIdentity(identity, kind) {
|
|
327
|
+
const prefix = `node-${kind}:`;
|
|
328
|
+
if (!identity.startsWith(prefix)) {
|
|
329
|
+
return pathModule.isAbsolute(identity) ? identity : void 0;
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
return Buffer.from(identity.slice(prefix.length), "base64url").toString(
|
|
333
|
+
"utf8"
|
|
334
|
+
);
|
|
335
|
+
} catch {
|
|
336
|
+
return void 0;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function assertChildName(name) {
|
|
340
|
+
if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
|
|
341
|
+
throw new TypeError(`Directory child must be a relative name: ${name}`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
var NodeDatabaseConnection = class {
|
|
345
|
+
constructor(database) {
|
|
346
|
+
this.database = database;
|
|
347
|
+
}
|
|
348
|
+
database;
|
|
349
|
+
async close() {
|
|
350
|
+
await new Promise((resolve3, reject) => {
|
|
351
|
+
this.database.close((error) => {
|
|
352
|
+
if (error) reject(error);
|
|
353
|
+
else resolve3();
|
|
354
|
+
});
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
async execute(sql) {
|
|
358
|
+
await new Promise((resolve3, reject) => {
|
|
359
|
+
this.database.exec(sql, (error) => {
|
|
360
|
+
if (error) reject(error);
|
|
361
|
+
else resolve3();
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
async queryAll(sql, params = []) {
|
|
366
|
+
return await new Promise((resolve3, reject) => {
|
|
367
|
+
this.database.all(sql, [...params], (error, rows) => {
|
|
368
|
+
if (error) reject(error);
|
|
369
|
+
else resolve3(rows);
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
async queryOne(sql, params = []) {
|
|
374
|
+
return await new Promise((resolve3, reject) => {
|
|
375
|
+
this.database.get(sql, [...params], (error, row) => {
|
|
376
|
+
if (error) reject(error);
|
|
377
|
+
else resolve3(row);
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
async run(sql, params = []) {
|
|
382
|
+
await new Promise((resolve3, reject) => {
|
|
383
|
+
this.database.run(sql, [...params], (error) => {
|
|
384
|
+
if (error) reject(error);
|
|
385
|
+
else resolve3();
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
async function openNodeDatabase(file, options) {
|
|
391
|
+
const flags = (options.mode === "readonly" ? nodeSqlite3.OPEN_READONLY : nodeSqlite3.OPEN_READWRITE | (options.create ? nodeSqlite3.OPEN_CREATE : 0)) | nodeSqlite3.OPEN_FULLMUTEX;
|
|
392
|
+
return new NodeDatabaseConnection(await openNativeNodeDatabase(file, flags));
|
|
393
|
+
}
|
|
394
|
+
async function openNativeNodeDatabase(file, flags) {
|
|
395
|
+
const path = getBrandedNodeResourcePath(file, "file");
|
|
396
|
+
if (path === void 0) {
|
|
397
|
+
throw new TypeError("The Node database adapter requires a NodeFile");
|
|
398
|
+
}
|
|
399
|
+
return await new Promise((resolve3, reject) => {
|
|
400
|
+
const database = new nodeSqlite3.Database(path, flags, (error) => {
|
|
401
|
+
if (error) reject(error);
|
|
402
|
+
else resolve3(database);
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
async function openNodeZip(file) {
|
|
407
|
+
const path = getBrandedNodeResourcePath(file, "file");
|
|
408
|
+
if (path === void 0) {
|
|
409
|
+
throw new TypeError("The Node ZIP adapter requires a NodeFile");
|
|
410
|
+
}
|
|
411
|
+
const zipFile = await new Promise((resolve3, reject) => {
|
|
412
|
+
yauzl.open(
|
|
413
|
+
path,
|
|
414
|
+
{ autoClose: false, lazyEntries: true },
|
|
415
|
+
(error, opened) => {
|
|
416
|
+
if (error || opened === void 0)
|
|
417
|
+
reject(error ?? new Error("Cannot open ZIP"));
|
|
418
|
+
else resolve3(opened);
|
|
419
|
+
}
|
|
420
|
+
);
|
|
421
|
+
});
|
|
422
|
+
const entries = await new Promise(
|
|
423
|
+
(resolve3, reject) => {
|
|
424
|
+
const discovered = /* @__PURE__ */ new Map();
|
|
425
|
+
const rejectAndClose = (error) => {
|
|
426
|
+
zipFile.close();
|
|
427
|
+
reject(
|
|
428
|
+
error instanceof Error ? error : new Error("Cannot scan ZIP central directory")
|
|
429
|
+
);
|
|
430
|
+
};
|
|
431
|
+
const resolveEntries = () => {
|
|
432
|
+
zipFile.off("error", rejectAndClose);
|
|
433
|
+
resolve3(discovered);
|
|
434
|
+
};
|
|
435
|
+
zipFile.on("entry", (entry) => {
|
|
436
|
+
if (!entry.fileName.endsWith("/")) {
|
|
437
|
+
discovered.set(entry.fileName, entry);
|
|
438
|
+
}
|
|
439
|
+
zipFile.readEntry();
|
|
440
|
+
});
|
|
441
|
+
zipFile.once("error", rejectAndClose);
|
|
442
|
+
zipFile.once("end", resolveEntries);
|
|
443
|
+
zipFile.readEntry();
|
|
444
|
+
}
|
|
445
|
+
);
|
|
446
|
+
let closed = false;
|
|
447
|
+
return {
|
|
448
|
+
close: () => {
|
|
449
|
+
if (!closed) zipFile.close();
|
|
450
|
+
closed = true;
|
|
451
|
+
return Promise.resolve();
|
|
452
|
+
},
|
|
453
|
+
copyEntry: async (name, target) => {
|
|
454
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
455
|
+
const entry = entries.get(name);
|
|
456
|
+
if (entry === void 0) return false;
|
|
457
|
+
await copyNodeZipEntry(zipFile, entry, target);
|
|
458
|
+
return true;
|
|
459
|
+
},
|
|
460
|
+
getEntrySize: (name) => {
|
|
461
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
462
|
+
return Promise.resolve(entries.get(name)?.uncompressedSize);
|
|
463
|
+
},
|
|
464
|
+
listEntries: () => Promise.resolve([...entries.keys()]),
|
|
465
|
+
readEntryRange: async (name, offset, length) => {
|
|
466
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
467
|
+
const entry = entries.get(name);
|
|
468
|
+
if (entry === void 0) return void 0;
|
|
469
|
+
return await readNodeZipEntryRange(zipFile, entry, offset, length);
|
|
470
|
+
},
|
|
471
|
+
readEntry: async (name) => {
|
|
472
|
+
if (closed) throw new Error("Cannot read a closed ZIP archive");
|
|
473
|
+
const entry = entries.get(name);
|
|
474
|
+
if (entry === void 0) return void 0;
|
|
475
|
+
return await readNodeZipEntry(zipFile, entry);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
async function copyNodeZipEntry(zipFile, entry, target) {
|
|
480
|
+
const writer = await target.openWriter();
|
|
481
|
+
try {
|
|
482
|
+
const stream = await openNodeZipEntryStream(zipFile, entry);
|
|
483
|
+
await writeNodeStream(stream, writer);
|
|
484
|
+
await writer.commit();
|
|
485
|
+
} catch (error) {
|
|
486
|
+
await writer.abort().catch(() => void 0);
|
|
487
|
+
throw error;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
async function readNodeZipEntry(zipFile, entry) {
|
|
491
|
+
return await collectNodeStream(await openNodeZipEntryStream(zipFile, entry));
|
|
492
|
+
}
|
|
493
|
+
async function readNodeZipEntryRange(zipFile, entry, offset, length) {
|
|
494
|
+
assertFileRange(offset, length, entry.uncompressedSize);
|
|
495
|
+
if (length === 0) return new Uint8Array();
|
|
496
|
+
if (entry.compressionMethod !== 0) {
|
|
497
|
+
const content2 = await collectDecodedNodeStreamRange(
|
|
498
|
+
await openNodeZipEntryStream(zipFile, entry),
|
|
499
|
+
offset,
|
|
500
|
+
length
|
|
501
|
+
);
|
|
502
|
+
return new Uint8Array(
|
|
503
|
+
content2.buffer,
|
|
504
|
+
content2.byteOffset,
|
|
505
|
+
content2.byteLength
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
const content = await collectNodeStream(
|
|
509
|
+
await openNodeZipEntryStream(zipFile, entry, {
|
|
510
|
+
decompress: null,
|
|
511
|
+
decrypt: null,
|
|
512
|
+
end: offset + length,
|
|
513
|
+
start: offset
|
|
514
|
+
})
|
|
515
|
+
);
|
|
516
|
+
return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
|
|
517
|
+
}
|
|
518
|
+
async function collectDecodedNodeStreamRange(input, offset, length) {
|
|
519
|
+
const chunks = [];
|
|
520
|
+
const end = offset + length;
|
|
521
|
+
let position = 0;
|
|
522
|
+
let collected = 0;
|
|
523
|
+
for await (const value of input) {
|
|
524
|
+
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
525
|
+
const chunkEnd = position + chunk.byteLength;
|
|
526
|
+
if (chunkEnd > offset && position < end) {
|
|
527
|
+
const selected = chunk.subarray(
|
|
528
|
+
Math.max(0, offset - position),
|
|
529
|
+
Math.min(chunk.byteLength, end - position)
|
|
530
|
+
);
|
|
531
|
+
chunks.push(selected);
|
|
532
|
+
collected += selected.byteLength;
|
|
533
|
+
}
|
|
534
|
+
position = chunkEnd;
|
|
535
|
+
if (position >= end) break;
|
|
536
|
+
}
|
|
537
|
+
if (collected !== length) {
|
|
538
|
+
throw new Error("ZIP entry changed while reading its byte range");
|
|
539
|
+
}
|
|
540
|
+
return Buffer.concat(chunks, collected);
|
|
541
|
+
}
|
|
542
|
+
async function openNodeZipEntryStream(zipFile, entry, options) {
|
|
543
|
+
return await new Promise((resolve3, reject) => {
|
|
544
|
+
const callback = (error, opened) => {
|
|
545
|
+
if (error || opened === void 0) {
|
|
546
|
+
reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
|
|
547
|
+
} else {
|
|
548
|
+
resolve3(opened);
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
if (options === void 0) zipFile.openReadStream(entry, callback);
|
|
552
|
+
else zipFile.openReadStream(entry, options, callback);
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
async function writeNodeZip(file, entries) {
|
|
556
|
+
const zipFile = new yazl.ZipFile();
|
|
557
|
+
const writer = await file.openWriter();
|
|
558
|
+
const outputStream = zipFile.outputStream;
|
|
559
|
+
const outputDone = writeNodeStream(outputStream, writer);
|
|
560
|
+
const entryState = { cancelled: false, complete: false };
|
|
561
|
+
let iterator;
|
|
562
|
+
try {
|
|
563
|
+
iterator = getNodeZipEntryIterator(entries);
|
|
564
|
+
const entriesDone = addNodeZipEntries(zipFile, iterator, entryState);
|
|
565
|
+
await Promise.race([entriesDone, outputDone]);
|
|
566
|
+
if (!entryState.complete) {
|
|
567
|
+
throw new Error("ZIP output ended before entry production completed");
|
|
568
|
+
}
|
|
569
|
+
zipFile.end();
|
|
570
|
+
await outputDone;
|
|
571
|
+
await writer.commit();
|
|
572
|
+
} catch (error) {
|
|
573
|
+
entryState.cancelled = true;
|
|
574
|
+
if (!entryState.complete && iterator !== void 0) {
|
|
575
|
+
closeNodeZipEntryIterator(iterator);
|
|
576
|
+
}
|
|
577
|
+
if (!outputStream.destroyed) {
|
|
578
|
+
outputStream.destroy(
|
|
579
|
+
error instanceof Error ? error : new Error("Cannot write ZIP archive")
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
await outputDone.catch(() => void 0);
|
|
583
|
+
await writer.abort().catch(() => void 0);
|
|
584
|
+
throw error;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
async function addNodeZipEntries(zipFile, iterator, state) {
|
|
588
|
+
while (!state.cancelled) {
|
|
589
|
+
const result = await iterator.next();
|
|
590
|
+
if (state.cancelled) return;
|
|
591
|
+
if (result.done) {
|
|
592
|
+
state.complete = true;
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
if ("file" in result.value) {
|
|
596
|
+
zipFile.addReadStream(
|
|
597
|
+
createNodeFileReadStream(result.value.file),
|
|
598
|
+
result.value.name,
|
|
599
|
+
{ compress: false }
|
|
600
|
+
);
|
|
601
|
+
} else if ("data" in result.value) {
|
|
602
|
+
zipFile.addBuffer(Buffer.from(result.value.data), result.value.name, {
|
|
603
|
+
compress: false
|
|
604
|
+
});
|
|
605
|
+
} else {
|
|
606
|
+
zipFile.addReadStream(
|
|
607
|
+
createNodeRangeReadStream(result.value),
|
|
608
|
+
result.value.name,
|
|
609
|
+
{ compress: false, size: result.value.size }
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function createNodeFileReadStream(file) {
|
|
615
|
+
return import_node_stream.Readable.from(
|
|
616
|
+
(async function* () {
|
|
617
|
+
const reader = await file.openReader();
|
|
618
|
+
try {
|
|
619
|
+
for (let offset = 0; offset < reader.size; ) {
|
|
620
|
+
const chunk = await reader.read(
|
|
621
|
+
offset,
|
|
622
|
+
Math.min(64 * 1024, reader.size - offset)
|
|
623
|
+
);
|
|
624
|
+
offset += chunk.byteLength;
|
|
625
|
+
yield chunk;
|
|
626
|
+
}
|
|
627
|
+
} finally {
|
|
628
|
+
await reader.close();
|
|
629
|
+
}
|
|
630
|
+
})()
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
function getBrandedNodeResourcePath(resource, kind) {
|
|
634
|
+
if (typeof resource !== "object" || resource === null) return void 0;
|
|
635
|
+
const candidate = resource;
|
|
636
|
+
return candidate[NODE_RESOURCE_KIND] === kind && typeof candidate.path === "string" ? candidate.path : void 0;
|
|
637
|
+
}
|
|
638
|
+
function createNodeRangeReadStream(entry) {
|
|
639
|
+
return import_node_stream.Readable.from(
|
|
640
|
+
(async function* () {
|
|
641
|
+
for (let offset = 0; offset < entry.size; ) {
|
|
642
|
+
const chunk = await entry.read(
|
|
643
|
+
offset,
|
|
644
|
+
Math.min(64 * 1024, entry.size - offset)
|
|
645
|
+
);
|
|
646
|
+
offset += chunk.byteLength;
|
|
647
|
+
yield chunk;
|
|
648
|
+
}
|
|
649
|
+
})()
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
function getNodeZipEntryIterator(entries) {
|
|
653
|
+
const asyncIterator = entries[Symbol.asyncIterator];
|
|
654
|
+
return asyncIterator === void 0 ? entries[Symbol.iterator]() : asyncIterator.call(entries);
|
|
655
|
+
}
|
|
656
|
+
function closeNodeZipEntryIterator(iterator) {
|
|
657
|
+
if (iterator.return === void 0) return;
|
|
658
|
+
try {
|
|
659
|
+
void Promise.resolve(iterator.return()).catch(() => void 0);
|
|
660
|
+
} catch {
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async function writeNodeStream(input, writer) {
|
|
664
|
+
await (0, import_promises.pipeline)(
|
|
665
|
+
input,
|
|
666
|
+
new import_node_stream.Writable({
|
|
667
|
+
write: (chunk, _encoding, callback) => {
|
|
668
|
+
void writer.write(chunk).then(
|
|
669
|
+
() => callback(),
|
|
670
|
+
(error) => callback(
|
|
671
|
+
error instanceof Error ? error : new Error("Cannot stream ZIP archive")
|
|
672
|
+
)
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
})
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
async function collectNodeStream(input) {
|
|
679
|
+
return await new Promise((resolve3, reject) => {
|
|
680
|
+
const chunks = [];
|
|
681
|
+
input.on("data", (chunk) => chunks.push(chunk));
|
|
682
|
+
input.once("error", reject);
|
|
683
|
+
input.once("end", () => resolve3(Buffer.concat(chunks)));
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
var nodeWikiGraphPlatform = {
|
|
687
|
+
asyncContext: {
|
|
688
|
+
create: () => new asyncHooks.AsyncLocalStorage()
|
|
689
|
+
},
|
|
690
|
+
database: { open: openNodeDatabase },
|
|
691
|
+
lifecycle: {
|
|
692
|
+
instanceId: `node-process:${nodeProcess.pid}`,
|
|
693
|
+
isInstanceAlive: (instanceId) => {
|
|
694
|
+
const match = /^node-process:(\d+)$/u.exec(instanceId);
|
|
695
|
+
if (match === null) return Promise.resolve(void 0);
|
|
696
|
+
try {
|
|
697
|
+
nodeProcess.kill(Number(match[1]), 0);
|
|
698
|
+
return Promise.resolve(true);
|
|
699
|
+
} catch (error) {
|
|
700
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH") {
|
|
701
|
+
return Promise.resolve(false);
|
|
702
|
+
}
|
|
703
|
+
return Promise.resolve(true);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
},
|
|
707
|
+
resources: {
|
|
708
|
+
getDirectory: (identity) => {
|
|
709
|
+
const path = decodeNodeResourceIdentity(identity, "directory");
|
|
710
|
+
return Promise.resolve(
|
|
711
|
+
path === void 0 ? void 0 : new NodeDirectory(path)
|
|
712
|
+
);
|
|
713
|
+
},
|
|
714
|
+
getFile: (identity) => {
|
|
715
|
+
const path = decodeNodeResourceIdentity(identity, "file");
|
|
716
|
+
return Promise.resolve(
|
|
717
|
+
path === void 0 ? void 0 : new NodeFile(path)
|
|
718
|
+
);
|
|
719
|
+
},
|
|
720
|
+
resolveLegacyDirectory: (reference) => {
|
|
721
|
+
const path = decodeNodeResourceIdentity(reference, "directory");
|
|
722
|
+
return Promise.resolve(
|
|
723
|
+
path === void 0 ? void 0 : new NodeDirectory(path)
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
},
|
|
727
|
+
templates: {
|
|
728
|
+
createEnvironment: (options) => new import_nunjucks.Environment(new NodeTemplateLoader(), options)
|
|
729
|
+
},
|
|
730
|
+
zip: {
|
|
731
|
+
open: openNodeZip,
|
|
732
|
+
write: writeNodeZip
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
var NodeTemplateLoader = class extends import_nunjucks.Loader {
|
|
736
|
+
#dataDirectory;
|
|
737
|
+
constructor(dataDirectory) {
|
|
738
|
+
super();
|
|
739
|
+
this.#dataDirectory = dataDirectory;
|
|
740
|
+
}
|
|
741
|
+
getSource(templateName) {
|
|
742
|
+
const name = (0, import_platform.normalizeTemplateName)(templateName);
|
|
743
|
+
const filePath = pathModule.join(
|
|
744
|
+
this.#dataDirectory ?? resolveNodeDataDirectory(),
|
|
745
|
+
name
|
|
746
|
+
);
|
|
747
|
+
return {
|
|
748
|
+
noCache: false,
|
|
749
|
+
path: name,
|
|
750
|
+
src: fs.readFileSync(filePath, "utf8")
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
function resolveNodeDataDirectory() {
|
|
755
|
+
const injected = globalThis.__WIKIGRAPH_DATA_DIR__;
|
|
756
|
+
if (typeof injected === "string" && injected !== "") return injected;
|
|
757
|
+
let directory = nodeProcess.cwd();
|
|
758
|
+
while (true) {
|
|
759
|
+
for (const candidate of [
|
|
760
|
+
pathModule.join(directory, "data"),
|
|
761
|
+
pathModule.join(directory, "packages", "core", "data")
|
|
762
|
+
]) {
|
|
763
|
+
try {
|
|
764
|
+
if (fs.statSync(candidate).isDirectory()) return candidate;
|
|
765
|
+
} catch {
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const parent = pathModule.dirname(directory);
|
|
769
|
+
if (parent === directory)
|
|
770
|
+
throw new Error("Could not locate data directory");
|
|
771
|
+
directory = parent;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/runtime-config.ts
|
|
776
|
+
var import_zod = require("zod");
|
|
777
|
+
|
|
778
|
+
// src/local-config.ts
|
|
779
|
+
var import_wiki_graph_core = require("wiki-graph-core");
|
|
780
|
+
|
|
781
|
+
// src/runtime-context.ts
|
|
782
|
+
var import_async_hooks = require("async_hooks");
|
|
783
|
+
var RUNTIME_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.runtime-context.v1");
|
|
784
|
+
var runtimeContext = getRuntimeContextStorage();
|
|
785
|
+
function getRuntimeContextStorage() {
|
|
786
|
+
const runtimeGlobal = globalThis;
|
|
787
|
+
const existing = runtimeGlobal[RUNTIME_CONTEXT_KEY];
|
|
788
|
+
if (existing !== void 0) {
|
|
789
|
+
return existing;
|
|
790
|
+
}
|
|
791
|
+
const storage = new import_async_hooks.AsyncLocalStorage();
|
|
792
|
+
Object.defineProperty(runtimeGlobal, RUNTIME_CONTEXT_KEY, {
|
|
793
|
+
configurable: false,
|
|
794
|
+
enumerable: false,
|
|
795
|
+
value: storage,
|
|
796
|
+
writable: false
|
|
797
|
+
});
|
|
798
|
+
return storage;
|
|
799
|
+
}
|
|
800
|
+
function getWikiGraphSDKRuntimeContext() {
|
|
801
|
+
return runtimeContext.getStore() ?? {
|
|
802
|
+
cwd: process.cwd(),
|
|
803
|
+
env: process.env,
|
|
804
|
+
envPolicy: "production"
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
function getWikiGraphSDKStateDir() {
|
|
808
|
+
return getWikiGraphSDKRuntimeContext().stateDir;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/local-config.ts
|
|
812
|
+
var import_path = require("path");
|
|
813
|
+
var import_os = require("os");
|
|
814
|
+
var LOCAL_CONFIG_SCHEMA_SQL = `
|
|
815
|
+
CREATE TABLE IF NOT EXISTS config_sections (
|
|
816
|
+
section TEXT PRIMARY KEY,
|
|
817
|
+
value_json TEXT NOT NULL,
|
|
818
|
+
updated_at INTEGER NOT NULL
|
|
819
|
+
);
|
|
820
|
+
`;
|
|
821
|
+
async function readLocalConfigSection(section) {
|
|
822
|
+
return await withLocalConfigDatabase(async (database) => {
|
|
823
|
+
return await readLocalConfigSectionInDatabase(database, section);
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
function validateLocalConfigSection(section, value) {
|
|
827
|
+
switch (section) {
|
|
828
|
+
case "embeddings":
|
|
829
|
+
return validateEmbeddingsConfig(value);
|
|
830
|
+
case "llm":
|
|
831
|
+
return validateLLMConfig(value);
|
|
832
|
+
case "concurrent":
|
|
833
|
+
return validateConcurrentConfig(value);
|
|
834
|
+
case "wikimedia":
|
|
835
|
+
return validateWikimediaConfig(value);
|
|
836
|
+
case "wikispine":
|
|
837
|
+
return validateWikispineConfig(value);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
async function withLocalConfigDatabase(operation) {
|
|
841
|
+
const database = await (0, import_wiki_graph_core.openSharedStateDatabase)(
|
|
842
|
+
new NodeFile(
|
|
843
|
+
(0, import_path.join)(
|
|
844
|
+
getWikiGraphSDKStateDir() ?? (0, import_path.join)((0, import_os.homedir)(), ".wikigraph"),
|
|
845
|
+
"core.sqlite"
|
|
846
|
+
)
|
|
847
|
+
),
|
|
848
|
+
LOCAL_CONFIG_SCHEMA_SQL
|
|
849
|
+
);
|
|
850
|
+
try {
|
|
851
|
+
return await operation(database);
|
|
852
|
+
} finally {
|
|
853
|
+
await database.close();
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
async function readLocalConfigSectionInDatabase(database, section) {
|
|
857
|
+
const value = await database.queryOne(
|
|
858
|
+
"SELECT value_json FROM config_sections WHERE section = ?",
|
|
859
|
+
[section],
|
|
860
|
+
(row) => String(row.value_json)
|
|
861
|
+
);
|
|
862
|
+
return value === void 0 ? {} : parseSectionJSON(section, value);
|
|
863
|
+
}
|
|
864
|
+
function parseSectionJSON(section, value) {
|
|
865
|
+
let parsed;
|
|
866
|
+
try {
|
|
867
|
+
parsed = JSON.parse(value);
|
|
868
|
+
} catch (error) {
|
|
869
|
+
throw new Error(
|
|
870
|
+
`Invalid local config JSON for ${section}: ${formatError(error)}`
|
|
871
|
+
);
|
|
872
|
+
}
|
|
873
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
874
|
+
throw new Error(
|
|
875
|
+
`Invalid local config section ${section}: expected object.`
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
return validateLocalConfigSection(section, parsed);
|
|
879
|
+
}
|
|
880
|
+
function validateEmbeddingsConfig(value) {
|
|
881
|
+
const allowedKeys = /* @__PURE__ */ new Set([
|
|
882
|
+
"apiKey",
|
|
883
|
+
"baseURL",
|
|
884
|
+
"dimensions",
|
|
885
|
+
"model",
|
|
886
|
+
"name",
|
|
887
|
+
"provider"
|
|
888
|
+
]);
|
|
889
|
+
const allowedProviders = /* @__PURE__ */ new Set(["openai", "openai-compatible"]);
|
|
890
|
+
const next = {};
|
|
891
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
892
|
+
if (!allowedKeys.has(key)) {
|
|
893
|
+
throw new Error(`Unknown embeddings config key: ${key}`);
|
|
894
|
+
}
|
|
895
|
+
if (key === "dimensions") {
|
|
896
|
+
const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
|
|
897
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
898
|
+
throw new Error("embeddings.dimensions must be a positive integer.");
|
|
899
|
+
}
|
|
900
|
+
next[key] = parsed;
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
904
|
+
throw new Error(`embeddings.${key} must be a non-empty string.`);
|
|
905
|
+
}
|
|
906
|
+
const normalized = entry.trim();
|
|
907
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
908
|
+
throw new Error(`Unknown embeddings.provider: ${normalized}`);
|
|
909
|
+
}
|
|
910
|
+
next[key] = normalized;
|
|
911
|
+
}
|
|
912
|
+
return next;
|
|
913
|
+
}
|
|
914
|
+
function validateLLMConfig(value) {
|
|
915
|
+
const allowedKeys = /* @__PURE__ */ new Set([
|
|
916
|
+
"apiKey",
|
|
917
|
+
"baseURL",
|
|
918
|
+
"model",
|
|
919
|
+
"name",
|
|
920
|
+
"provider"
|
|
921
|
+
]);
|
|
922
|
+
const allowedProviders = /* @__PURE__ */ new Set([
|
|
923
|
+
"anthropic",
|
|
924
|
+
"google",
|
|
925
|
+
"openai",
|
|
926
|
+
"openai-compatible"
|
|
927
|
+
]);
|
|
928
|
+
const next = {};
|
|
929
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
930
|
+
if (!allowedKeys.has(key)) {
|
|
931
|
+
throw new Error(`Unknown llm config key: ${key}`);
|
|
932
|
+
}
|
|
933
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
934
|
+
throw new Error(`llm.${key} must be a non-empty string.`);
|
|
935
|
+
}
|
|
936
|
+
const normalized = entry.trim();
|
|
937
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
938
|
+
throw new Error(`Unknown llm.provider: ${normalized}`);
|
|
939
|
+
}
|
|
940
|
+
next[key] = normalized;
|
|
941
|
+
}
|
|
942
|
+
return next;
|
|
943
|
+
}
|
|
944
|
+
function validateConcurrentConfig(value) {
|
|
945
|
+
const allowedKeys = /* @__PURE__ */ new Set(["job", "request"]);
|
|
946
|
+
const next = {};
|
|
947
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
948
|
+
if (!allowedKeys.has(key)) {
|
|
949
|
+
throw new Error(`Unknown concurrent config key: ${key}`);
|
|
950
|
+
}
|
|
951
|
+
const parsed = typeof entry === "number" ? entry : typeof entry === "string" ? Number(entry) : NaN;
|
|
952
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
953
|
+
throw new Error(`concurrent.${key} must be a positive integer.`);
|
|
954
|
+
}
|
|
955
|
+
next[key] = parsed;
|
|
956
|
+
}
|
|
957
|
+
return next;
|
|
958
|
+
}
|
|
959
|
+
function validateWikispineConfig(value) {
|
|
960
|
+
const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "provider", "token"]);
|
|
961
|
+
const allowedProviders = /* @__PURE__ */ new Set(["cli", "fetch"]);
|
|
962
|
+
const next = {};
|
|
963
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
964
|
+
if (!allowedKeys.has(key)) {
|
|
965
|
+
throw new Error(`Unknown wikispine config key: ${key}`);
|
|
966
|
+
}
|
|
967
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
968
|
+
throw new Error(`wikispine.${key} must be a non-empty string.`);
|
|
969
|
+
}
|
|
970
|
+
const normalized = entry.trim();
|
|
971
|
+
if (key === "provider" && !allowedProviders.has(normalized)) {
|
|
972
|
+
throw new Error(`Unknown wikispine.provider: ${normalized}`);
|
|
973
|
+
}
|
|
974
|
+
next[key] = normalized;
|
|
975
|
+
}
|
|
976
|
+
return next;
|
|
977
|
+
}
|
|
978
|
+
function validateWikimediaConfig(value) {
|
|
979
|
+
return validateEndpointConfig("wikimedia", value);
|
|
980
|
+
}
|
|
981
|
+
function validateEndpointConfig(section, value) {
|
|
982
|
+
const allowedKeys = /* @__PURE__ */ new Set(["endpoint", "token"]);
|
|
983
|
+
const next = {};
|
|
984
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
985
|
+
if (!allowedKeys.has(key)) {
|
|
986
|
+
throw new Error(`Unknown ${section} config key: ${key}`);
|
|
987
|
+
}
|
|
988
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
989
|
+
throw new Error(`${section}.${key} must be a non-empty string.`);
|
|
990
|
+
}
|
|
991
|
+
next[key] = entry.trim();
|
|
992
|
+
}
|
|
993
|
+
return next;
|
|
994
|
+
}
|
|
995
|
+
function formatError(error) {
|
|
996
|
+
return error instanceof Error ? error.message : String(error);
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/runtime-config.ts
|
|
1000
|
+
var WIKI_GRAPH_PROVIDER_VALUES = [
|
|
1001
|
+
"anthropic",
|
|
1002
|
+
"google",
|
|
1003
|
+
"openai",
|
|
1004
|
+
"openai-compatible"
|
|
1005
|
+
];
|
|
1006
|
+
var wikiGraphProviderSchema = import_zod.z.enum(WIKI_GRAPH_PROVIDER_VALUES);
|
|
1007
|
+
var inlineLLMConfigSchema = import_zod.z.object({
|
|
1008
|
+
apiKey: import_zod.z.string().min(1).optional(),
|
|
1009
|
+
baseURL: import_zod.z.string().min(1).optional(),
|
|
1010
|
+
baseUrl: import_zod.z.string().min(1).optional(),
|
|
1011
|
+
chatCompletionsUrl: import_zod.z.string().min(1).optional(),
|
|
1012
|
+
llm: import_zod.z.object({
|
|
1013
|
+
apiKey: import_zod.z.string().min(1).optional(),
|
|
1014
|
+
baseURL: import_zod.z.string().min(1).optional(),
|
|
1015
|
+
baseUrl: import_zod.z.string().min(1).optional(),
|
|
1016
|
+
chatCompletionsUrl: import_zod.z.string().min(1).optional(),
|
|
1017
|
+
model: import_zod.z.string().min(1).optional(),
|
|
1018
|
+
name: import_zod.z.string().min(1).optional(),
|
|
1019
|
+
provider: wikiGraphProviderSchema.optional()
|
|
1020
|
+
}).optional(),
|
|
1021
|
+
model: import_zod.z.string().min(1).optional(),
|
|
1022
|
+
name: import_zod.z.string().min(1).optional(),
|
|
1023
|
+
provider: wikiGraphProviderSchema.optional()
|
|
1024
|
+
});
|
|
1025
|
+
async function loadWikiGraphRuntimeConfig(options) {
|
|
1026
|
+
const [embedding, localLLM, concurrent, wikimedia, wikispine] = await Promise.all([
|
|
1027
|
+
readLocalConfigSection("embeddings"),
|
|
1028
|
+
readLocalConfigSection("llm"),
|
|
1029
|
+
readLocalConfigSection("concurrent"),
|
|
1030
|
+
readLocalConfigSection("wikimedia"),
|
|
1031
|
+
readLocalConfigSection("wikispine")
|
|
1032
|
+
]);
|
|
1033
|
+
const inlineLLMConfig = options?.llmJSON === void 0 ? void 0 : parseInlineLLMConfig(options.llmJSON);
|
|
1034
|
+
const llm = createLLMConfig({
|
|
1035
|
+
apiKey: firstDefined(inlineLLMConfig?.apiKey, readString(localLLM.apiKey)),
|
|
1036
|
+
baseURL: firstDefined(
|
|
1037
|
+
inlineLLMConfig?.baseURL,
|
|
1038
|
+
readString(localLLM.baseURL)
|
|
1039
|
+
),
|
|
1040
|
+
model: firstDefined(inlineLLMConfig?.model, readString(localLLM.model)),
|
|
1041
|
+
name: firstDefined(inlineLLMConfig?.name, readString(localLLM.name)),
|
|
1042
|
+
provider: firstDefined(
|
|
1043
|
+
inlineLLMConfig?.provider,
|
|
1044
|
+
readProvider(localLLM.provider)
|
|
1045
|
+
)
|
|
1046
|
+
});
|
|
1047
|
+
const requestConcurrent = readPositiveInteger(concurrent.request);
|
|
1048
|
+
const jobConcurrent = readPositiveInteger(concurrent.job);
|
|
1049
|
+
const envPolicy = getWikiGraphSDKRuntimeContext().envPolicy;
|
|
1050
|
+
const wikispineConfig = resolveWikispineConfig(wikispine, envPolicy);
|
|
1051
|
+
const wikimediaConfig = createWikimediaConfig(wikimedia, envPolicy);
|
|
1052
|
+
const embeddingConfig = createEmbeddingConfig(embedding);
|
|
1053
|
+
return {
|
|
1054
|
+
...jobConcurrent === void 0 && requestConcurrent === void 0 ? {} : {
|
|
1055
|
+
concurrent: {
|
|
1056
|
+
...jobConcurrent === void 0 ? {} : { job: jobConcurrent },
|
|
1057
|
+
...requestConcurrent === void 0 ? {} : { request: requestConcurrent }
|
|
1058
|
+
}
|
|
1059
|
+
},
|
|
1060
|
+
...embeddingConfig === void 0 ? {} : { embedding: embeddingConfig },
|
|
1061
|
+
...llm === void 0 ? {} : { llm },
|
|
1062
|
+
...wikimediaConfig === void 0 ? {} : { wikimedia: wikimediaConfig },
|
|
1063
|
+
...wikispineConfig === void 0 ? {} : { wikispine: wikispineConfig }
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
function createWikimediaConfig(input, envPolicy) {
|
|
1067
|
+
const endpoint = readString(input?.endpoint);
|
|
1068
|
+
const token = readString(input?.token);
|
|
1069
|
+
if (endpoint === void 0 && token === void 0) return void 0;
|
|
1070
|
+
if (token === void 0) {
|
|
1071
|
+
throw new Error(
|
|
1072
|
+
"Remote Wikimedia access requires an API key. Configure `wikg://local/config/wikimedia` token with `put token --secret`."
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
return {
|
|
1076
|
+
endpoint: endpoint ?? resolveHostedProviderEndpoint("wg-wikimedia", envPolicy),
|
|
1077
|
+
token
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
function createEmbeddingConfig(input) {
|
|
1081
|
+
const value = input ?? {};
|
|
1082
|
+
const provider = readEmbeddingProvider(value.provider);
|
|
1083
|
+
const apiKey = readString(value.apiKey);
|
|
1084
|
+
const baseURL = readString(value.baseURL);
|
|
1085
|
+
const dimensions = typeof value.dimensions === "number" && Number.isInteger(value.dimensions) && value.dimensions > 0 ? value.dimensions : void 0;
|
|
1086
|
+
const model = readString(value.model);
|
|
1087
|
+
const name = readString(value.name);
|
|
1088
|
+
if (provider === void 0 || model === void 0 || provider === "openai-compatible" && baseURL === void 0 || provider === "openai" && baseURL !== void 0) {
|
|
1089
|
+
return void 0;
|
|
1090
|
+
}
|
|
1091
|
+
return {
|
|
1092
|
+
...apiKey === void 0 ? {} : { apiKey },
|
|
1093
|
+
...baseURL === void 0 ? {} : { baseURL },
|
|
1094
|
+
...dimensions === void 0 ? {} : { dimensions },
|
|
1095
|
+
...model === void 0 ? {} : { model },
|
|
1096
|
+
...name === void 0 ? {} : { name },
|
|
1097
|
+
...provider === void 0 ? {} : { provider }
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
function parseInlineLLMConfig(value) {
|
|
1101
|
+
const normalized = normalizeString(value);
|
|
1102
|
+
if (normalized === void 0) {
|
|
1103
|
+
throw new Error("--llm must be a non-empty JSON object.");
|
|
1104
|
+
}
|
|
1105
|
+
let parsedJson;
|
|
1106
|
+
try {
|
|
1107
|
+
parsedJson = JSON.parse(normalized);
|
|
1108
|
+
} catch (error) {
|
|
1109
|
+
throw new Error(`Invalid --llm JSON: ${formatError2(error)}`);
|
|
1110
|
+
}
|
|
1111
|
+
const parsed = inlineLLMConfigSchema.safeParse(parsedJson);
|
|
1112
|
+
if (!parsed.success) {
|
|
1113
|
+
throw new Error(
|
|
1114
|
+
`Invalid --llm config: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ")}`
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
const input = parsed.data.llm ?? parsed.data;
|
|
1118
|
+
const provider = input.provider ?? inferInlineProvider(input);
|
|
1119
|
+
const baseURL = resolveInlineBaseURL(input);
|
|
1120
|
+
const config = createLLMConfig({
|
|
1121
|
+
apiKey: input.apiKey,
|
|
1122
|
+
baseURL,
|
|
1123
|
+
model: input.model,
|
|
1124
|
+
name: input.name,
|
|
1125
|
+
provider
|
|
1126
|
+
});
|
|
1127
|
+
if (config === void 0) {
|
|
1128
|
+
throw new Error("--llm must contain at least one supported LLM field.");
|
|
1129
|
+
}
|
|
1130
|
+
return config;
|
|
1131
|
+
}
|
|
1132
|
+
function inferInlineProvider(input) {
|
|
1133
|
+
if (input.provider === void 0 && (input.baseURL !== void 0 || input.baseUrl !== void 0 || input.chatCompletionsUrl !== void 0)) {
|
|
1134
|
+
return "openai-compatible";
|
|
1135
|
+
}
|
|
1136
|
+
return input.provider;
|
|
1137
|
+
}
|
|
1138
|
+
function inferBaseURLFromChatCompletionsURL(input) {
|
|
1139
|
+
if (input.chatCompletionsUrl === void 0) {
|
|
1140
|
+
return void 0;
|
|
1141
|
+
}
|
|
1142
|
+
const suffix = "/chat/completions";
|
|
1143
|
+
if (!input.chatCompletionsUrl.endsWith(suffix)) {
|
|
1144
|
+
throw new Error(
|
|
1145
|
+
"--llm chatCompletionsUrl must end with /chat/completions when baseURL is not provided."
|
|
1146
|
+
);
|
|
1147
|
+
}
|
|
1148
|
+
return input.chatCompletionsUrl.slice(0, -suffix.length);
|
|
1149
|
+
}
|
|
1150
|
+
function resolveInlineBaseURL(input) {
|
|
1151
|
+
if (input.baseURL !== void 0) {
|
|
1152
|
+
return input.baseURL;
|
|
1153
|
+
}
|
|
1154
|
+
if (input.baseUrl !== void 0) {
|
|
1155
|
+
return input.baseUrl;
|
|
1156
|
+
}
|
|
1157
|
+
return inferBaseURLFromChatCompletionsURL(input);
|
|
1158
|
+
}
|
|
1159
|
+
function createLLMConfig(input) {
|
|
1160
|
+
if (input.apiKey === void 0 && input.baseURL === void 0 && input.model === void 0 && input.name === void 0 && input.provider === void 0) {
|
|
1161
|
+
return void 0;
|
|
1162
|
+
}
|
|
1163
|
+
return {
|
|
1164
|
+
...input.apiKey === void 0 ? {} : { apiKey: input.apiKey },
|
|
1165
|
+
...input.baseURL === void 0 ? {} : { baseURL: input.baseURL },
|
|
1166
|
+
...input.model === void 0 ? {} : { model: input.model },
|
|
1167
|
+
...input.name === void 0 ? {} : { name: input.name },
|
|
1168
|
+
...input.provider === void 0 ? {} : { provider: input.provider }
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
function readProvider(value) {
|
|
1172
|
+
if (typeof value !== "string") {
|
|
1173
|
+
return void 0;
|
|
1174
|
+
}
|
|
1175
|
+
const parsed = wikiGraphProviderSchema.safeParse(value);
|
|
1176
|
+
return parsed.success ? parsed.data : void 0;
|
|
1177
|
+
}
|
|
1178
|
+
function resolveWikispineConfig(value, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
|
|
1179
|
+
const provider = readWikispineProvider(value.provider);
|
|
1180
|
+
const endpoint = readString(value.endpoint);
|
|
1181
|
+
const token = readString(value.token);
|
|
1182
|
+
if (provider === void 0) {
|
|
1183
|
+
return void 0;
|
|
1184
|
+
}
|
|
1185
|
+
if (provider === "cli") return { provider };
|
|
1186
|
+
if (token === void 0) {
|
|
1187
|
+
throw new Error(
|
|
1188
|
+
"Remote WikiSpine access requires an API key. Configure `wikg://local/config/wikispine` token with `put token --secret`."
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
return {
|
|
1192
|
+
endpoint: endpoint ?? resolveHostedProviderEndpoint("wikispine", envPolicy),
|
|
1193
|
+
provider,
|
|
1194
|
+
token
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
function resolveHostedProviderEndpoint(scope, envPolicy = getWikiGraphSDKRuntimeContext().envPolicy) {
|
|
1198
|
+
const origin = envPolicy === "development" ? "https://pdf-craft-api.oomol.dev" : "https://api.pdfcraft.ai";
|
|
1199
|
+
return `${origin}/v1/${scope}`;
|
|
1200
|
+
}
|
|
1201
|
+
function readWikispineProvider(value) {
|
|
1202
|
+
return value === "cli" || value === "fetch" ? value : void 0;
|
|
1203
|
+
}
|
|
1204
|
+
function readEmbeddingProvider(value) {
|
|
1205
|
+
return value === "openai" || value === "openai-compatible" ? value : void 0;
|
|
1206
|
+
}
|
|
1207
|
+
function readString(value) {
|
|
1208
|
+
return typeof value === "string" ? value : void 0;
|
|
1209
|
+
}
|
|
1210
|
+
function readPositiveInteger(value) {
|
|
1211
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
1212
|
+
}
|
|
1213
|
+
function firstDefined(first, second) {
|
|
1214
|
+
return first ?? second;
|
|
1215
|
+
}
|
|
1216
|
+
function normalizeString(value) {
|
|
1217
|
+
const normalized = value?.trim();
|
|
1218
|
+
return normalized === void 0 || normalized === "" ? void 0 : normalized;
|
|
1219
|
+
}
|
|
1220
|
+
function formatError2(error) {
|
|
1221
|
+
return error instanceof Error ? error.message : String(error);
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/runtime-path.ts
|
|
1225
|
+
var import_os2 = require("os");
|
|
1226
|
+
var import_path2 = require("path");
|
|
1227
|
+
function resolveWikiGraphRuntimePath(path) {
|
|
1228
|
+
const context = getWikiGraphSDKRuntimeContext();
|
|
1229
|
+
const environmentHome = context.env.HOME?.trim();
|
|
1230
|
+
const home = environmentHome === void 0 || environmentHome === "" ? (0, import_os2.homedir)() : environmentHome;
|
|
1231
|
+
if (path === "~") return home;
|
|
1232
|
+
if (path.startsWith("~/")) return (0, import_path2.resolve)(home, path.slice(2));
|
|
1233
|
+
return (0, import_path2.isAbsolute)(path) ? path : (0, import_path2.resolve)(context.cwd, path);
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// src/conversions.ts
|
|
1237
|
+
var WikiGraphConversionManager = class {
|
|
1238
|
+
#runtime;
|
|
1239
|
+
constructor(runtime) {
|
|
1240
|
+
this.#runtime = runtime;
|
|
1241
|
+
}
|
|
1242
|
+
async convert(options) {
|
|
1243
|
+
return await this.#runtime.run(async () => await this.#convert(options));
|
|
1244
|
+
}
|
|
1245
|
+
async #convert(options) {
|
|
1246
|
+
const targetStage = options.targetStage ?? "summarized";
|
|
1247
|
+
if (options.targetStage !== void 0 && options.output.format !== "wikg") {
|
|
1248
|
+
throw new Error("targetStage is only supported for wikg output.");
|
|
1249
|
+
}
|
|
1250
|
+
if (options.targetStage !== void 0 && options.input.format === "wikg") {
|
|
1251
|
+
throw new Error(
|
|
1252
|
+
"targetStage is only supported when creating a wikg archive."
|
|
1253
|
+
);
|
|
1254
|
+
}
|
|
1255
|
+
const requiresDigest = options.input.format !== "wikg";
|
|
1256
|
+
const requiresLLM = requiresDigest && targetStage !== "planned" && targetStage !== "sourced";
|
|
1257
|
+
const config = await loadWikiGraphRuntimeConfig({
|
|
1258
|
+
...options.llmJSON === void 0 ? {} : { llmJSON: options.llmJSON }
|
|
1259
|
+
});
|
|
1260
|
+
const app = new import_wiki_graph_core2.WikiGraph({
|
|
1261
|
+
...options.verbose === true ? { verbose: true } : {},
|
|
1262
|
+
...requiresLLM ? { llm: buildWikiGraphLLMOptions(config) } : {}
|
|
1263
|
+
});
|
|
1264
|
+
const documentDirectory = await prepareDigestDirectory(
|
|
1265
|
+
options.digestDirectory,
|
|
1266
|
+
requiresDigest
|
|
1267
|
+
);
|
|
1268
|
+
const write = async (archive) => {
|
|
1269
|
+
await writeArchive(archive, options.output.path, options.output.format);
|
|
1270
|
+
};
|
|
1271
|
+
if (options.input.format === "wikg") {
|
|
1272
|
+
if (!("path" in options.input)) {
|
|
1273
|
+
throw new Error("wikg input requires a file path.");
|
|
1274
|
+
}
|
|
1275
|
+
await app.openSession(
|
|
1276
|
+
new NodeFile(resolveWikiGraphRuntimePath(options.input.path)),
|
|
1277
|
+
write
|
|
1278
|
+
);
|
|
1279
|
+
} else if ("stream" in options.input) {
|
|
1280
|
+
await app.digestTextStreamSession(
|
|
1281
|
+
{
|
|
1282
|
+
...documentDirectory === void 0 ? {} : { documentDirectory },
|
|
1283
|
+
...options.onProgress === void 0 ? {} : { onProgress: options.onProgress },
|
|
1284
|
+
sourceFormat: options.input.format,
|
|
1285
|
+
stream: options.input.stream,
|
|
1286
|
+
...(options.prompt ?? config.prompt) === void 0 ? {} : { extractionPrompt: options.prompt ?? config.prompt },
|
|
1287
|
+
targetStage
|
|
1288
|
+
},
|
|
1289
|
+
write
|
|
1290
|
+
);
|
|
1291
|
+
} else {
|
|
1292
|
+
const digestOptions = {
|
|
1293
|
+
...documentDirectory === void 0 ? {} : { documentDirectory },
|
|
1294
|
+
file: new NodeFile(resolveWikiGraphRuntimePath(options.input.path)),
|
|
1295
|
+
...options.onProgress === void 0 ? {} : { onProgress: options.onProgress },
|
|
1296
|
+
...(options.prompt ?? config.prompt) === void 0 ? {} : { extractionPrompt: options.prompt ?? config.prompt },
|
|
1297
|
+
targetStage
|
|
1298
|
+
};
|
|
1299
|
+
if (options.input.format === "epub") {
|
|
1300
|
+
await app.digestEpubSession(digestOptions, write);
|
|
1301
|
+
} else if (options.input.format === "markdown") {
|
|
1302
|
+
await app.digestMarkdownSession(digestOptions, write);
|
|
1303
|
+
} else {
|
|
1304
|
+
await app.digestTxtSession(digestOptions, write);
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return {
|
|
1308
|
+
inputFormat: options.input.format,
|
|
1309
|
+
outputFormat: options.output.format,
|
|
1310
|
+
outputPath: options.output.path
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
async function prepareDigestDirectory(path, required) {
|
|
1315
|
+
const normalized = path?.trim();
|
|
1316
|
+
if (!required || normalized === void 0 || normalized === "")
|
|
1317
|
+
return void 0;
|
|
1318
|
+
const resolved = resolveWikiGraphRuntimePath(normalized);
|
|
1319
|
+
await (0, import_promises2.rm)(resolved, { force: true, recursive: true });
|
|
1320
|
+
return new NodeDirectory(resolved);
|
|
1321
|
+
}
|
|
1322
|
+
async function writeArchive(archive, path, format) {
|
|
1323
|
+
const file = new NodeFile(resolveWikiGraphRuntimePath(path));
|
|
1324
|
+
if (format === "epub") await archive.exportEpub(file);
|
|
1325
|
+
else if (format === "wikg") await archive.saveAs(file);
|
|
1326
|
+
else await archive.exportText(file);
|
|
1327
|
+
}
|
|
1328
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1329
|
+
0 && (module.exports = {
|
|
1330
|
+
WikiGraphConversionManager
|
|
1331
|
+
});
|
|
1332
|
+
//# sourceMappingURL=conversions.cjs.map
|