@baseera/node 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +356 -2
- package/dist/cli.js +340 -0
- package/dist/index.cjs +541 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +306 -0
- package/dist/index.d.ts +306 -0
- package/dist/index.js +504 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
FINISH_WEBHOOK_EVENT_TYPE: () => import_core8.FINISH_WEBHOOK_EVENT_TYPE,
|
|
24
|
+
KB_REQUEST_TIMEOUT_MS: () => KB_REQUEST_TIMEOUT_MS,
|
|
25
|
+
KB_UPLOAD_TIMEOUT_MS: () => KB_UPLOAD_TIMEOUT_MS,
|
|
26
|
+
PROTOCOL_VERSION: () => import_core6.PROTOCOL_VERSION,
|
|
27
|
+
PURGE_TENANT_TIMEOUT_MS: () => PURGE_TENANT_TIMEOUT_MS,
|
|
28
|
+
SIGNAL_LIMITS: () => import_core7.SIGNAL_LIMITS,
|
|
29
|
+
TENANT_UPLOAD_TOKEN_DEFAULT_TTL_SECONDS: () => import_core8.TENANT_UPLOAD_TOKEN_DEFAULT_TTL_SECONDS,
|
|
30
|
+
TENANT_UPLOAD_TOKEN_MAX_TTL_SECONDS: () => import_core8.TENANT_UPLOAD_TOKEN_MAX_TTL_SECONDS,
|
|
31
|
+
USER_TOKEN_DEFAULT_TTL_SECONDS: () => import_core6.USER_TOKEN_DEFAULT_TTL_SECONDS,
|
|
32
|
+
USER_TOKEN_MAX_TTL_SECONDS: () => import_core6.USER_TOKEN_MAX_TTL_SECONDS,
|
|
33
|
+
VERIFY_FINISH_TIMEOUT_MS: () => VERIFY_FINISH_TIMEOUT_MS,
|
|
34
|
+
WEBHOOK_TOLERANCE_SECONDS: () => import_core8.WEBHOOK_TOLERANCE_SECONDS,
|
|
35
|
+
createBaseera: () => createBaseera,
|
|
36
|
+
generateWebhookSecret: () => import_core8.generateWebhookSecret,
|
|
37
|
+
purgeTenantKnowledge: () => purgeTenantKnowledge,
|
|
38
|
+
signTenantUploadToken: () => signTenantUploadToken,
|
|
39
|
+
signUserToken: () => import_core6.signUserToken,
|
|
40
|
+
verifyFinish: () => verifyFinish,
|
|
41
|
+
verifyWebhook: () => verifyWebhook
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(index_exports);
|
|
44
|
+
var import_core6 = require("@baseera/core");
|
|
45
|
+
|
|
46
|
+
// src/verify-finish.ts
|
|
47
|
+
var import_core = require("@baseera/core");
|
|
48
|
+
var VERIFY_FINISH_TIMEOUT_MS = 5e3;
|
|
49
|
+
var UNAVAILABLE = { ok: false, code: "unavailable" };
|
|
50
|
+
var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
51
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
52
|
+
var isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
53
|
+
function parseFinish(value) {
|
|
54
|
+
if (!isObject(value)) return null;
|
|
55
|
+
const { userId, tenantId, openBlocking, override, createdAt } = value;
|
|
56
|
+
if (typeof userId !== "string" || userId === "") return null;
|
|
57
|
+
if (tenantId !== null && typeof tenantId !== "string") return null;
|
|
58
|
+
if (!isStringArray(openBlocking)) return null;
|
|
59
|
+
if (typeof createdAt !== "string") return null;
|
|
60
|
+
let parsedOverride = null;
|
|
61
|
+
if (override !== null) {
|
|
62
|
+
if (!isObject(override) || typeof override.reason !== "string" || override.reason.trim() === "" || !isStringArray(override.checks)) return null;
|
|
63
|
+
parsedOverride = { reason: override.reason, checks: override.checks };
|
|
64
|
+
}
|
|
65
|
+
return { userId, tenantId, openBlocking, override: parsedOverride, createdAt };
|
|
66
|
+
}
|
|
67
|
+
async function verifyFinish(options) {
|
|
68
|
+
try {
|
|
69
|
+
const { receipt, entity, agentId, secretKey } = options;
|
|
70
|
+
const serverOpen = options.openBlocking ?? [];
|
|
71
|
+
if (typeof receipt !== "string" || !isObject(entity) || typeof entity.type !== "string" || typeof entity.ref !== "string" || !isStringArray(serverOpen)) return UNAVAILABLE;
|
|
72
|
+
const base = new URL(options.baseUrl);
|
|
73
|
+
if (base.protocol !== "https:" && !(base.protocol === "http:" && LOOPBACK.has(base.hostname))) return UNAVAILABLE;
|
|
74
|
+
const url = `${base.origin}${import_core.PATHS.verifyFinish}`;
|
|
75
|
+
const token = await (0, import_core.signServerToken)(secretKey, { agentId, purpose: "verify_finish" });
|
|
76
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
77
|
+
const controller = new AbortController();
|
|
78
|
+
let timer;
|
|
79
|
+
const timeout = new Promise((_, reject) => {
|
|
80
|
+
timer = setTimeout(() => {
|
|
81
|
+
controller.abort();
|
|
82
|
+
reject(new Error("timeout"));
|
|
83
|
+
}, VERIFY_FINISH_TIMEOUT_MS);
|
|
84
|
+
});
|
|
85
|
+
let response;
|
|
86
|
+
let text;
|
|
87
|
+
try {
|
|
88
|
+
const exchange = (async () => {
|
|
89
|
+
const res = await doFetch(url, {
|
|
90
|
+
method: "POST",
|
|
91
|
+
headers: { "content-type": "application/json", accept: "application/json", [import_core.HEADERS.agent]: agentId, [import_core.HEADERS.serverToken]: token },
|
|
92
|
+
body: JSON.stringify({ receipt, entity: { type: entity.type, ref: entity.ref }, openBlocking: serverOpen }),
|
|
93
|
+
redirect: "error",
|
|
94
|
+
cache: "no-store",
|
|
95
|
+
signal: controller.signal
|
|
96
|
+
});
|
|
97
|
+
return { res, text: await res.text() };
|
|
98
|
+
})();
|
|
99
|
+
exchange.catch(() => {
|
|
100
|
+
});
|
|
101
|
+
({ res: response, text } = await Promise.race([exchange, timeout]));
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
}
|
|
105
|
+
if (response.status !== 200) return UNAVAILABLE;
|
|
106
|
+
let body;
|
|
107
|
+
try {
|
|
108
|
+
body = JSON.parse(text);
|
|
109
|
+
} catch {
|
|
110
|
+
return UNAVAILABLE;
|
|
111
|
+
}
|
|
112
|
+
if (!isObject(body)) return UNAVAILABLE;
|
|
113
|
+
if (body.ok === false) {
|
|
114
|
+
return typeof body.code === "string" && import_core.VERIFY_FINISH_REFUSALS.includes(body.code) ? { ok: false, code: body.code } : UNAVAILABLE;
|
|
115
|
+
}
|
|
116
|
+
if (body.ok !== true) return UNAVAILABLE;
|
|
117
|
+
const finish = parseFinish(body.finish);
|
|
118
|
+
if (!finish) return UNAVAILABLE;
|
|
119
|
+
const covered = new Set(finish.override?.checks ?? []);
|
|
120
|
+
const mustCover = [...serverOpen, ...finish.openBlocking];
|
|
121
|
+
if (mustCover.length > 0 && (!finish.override || mustCover.some((id) => !covered.has(id)))) return { ok: false, code: "override_required" };
|
|
122
|
+
return { ok: true, finish };
|
|
123
|
+
} catch {
|
|
124
|
+
return UNAVAILABLE;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/purge-tenant-knowledge.ts
|
|
129
|
+
var import_core2 = require("@baseera/core");
|
|
130
|
+
var PURGE_TENANT_TIMEOUT_MS = 3e4;
|
|
131
|
+
var UNAVAILABLE2 = { ok: false, code: "unavailable" };
|
|
132
|
+
var LOOPBACK2 = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
133
|
+
var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
134
|
+
var isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
135
|
+
function parseRecord(value, tenantId) {
|
|
136
|
+
if (!isObject2(value)) return null;
|
|
137
|
+
const { id, tenantId: tid, sources, chunks, requestedAt, completedAt } = value;
|
|
138
|
+
if (typeof id !== "string" || tid !== tenantId || !isCount(sources) || !isCount(chunks)) return null;
|
|
139
|
+
if (typeof requestedAt !== "string" || typeof completedAt !== "string") return null;
|
|
140
|
+
return { id, tenantId, sources, chunks, requestedAt, completedAt };
|
|
141
|
+
}
|
|
142
|
+
async function purgeTenantKnowledge(options) {
|
|
143
|
+
try {
|
|
144
|
+
const { tenantId, agentId, secretKey } = options;
|
|
145
|
+
if (typeof tenantId !== "string" || tenantId.trim() === "" || tenantId.length > 256) return { ok: false, code: "invalid_request" };
|
|
146
|
+
const base = new URL(options.baseUrl);
|
|
147
|
+
if (base.protocol !== "https:" && !(base.protocol === "http:" && LOOPBACK2.has(base.hostname))) return UNAVAILABLE2;
|
|
148
|
+
const url = `${base.origin}${import_core2.PATHS.purgeTenantKnowledge(tenantId)}`;
|
|
149
|
+
const token = await (0, import_core2.signServerToken)(secretKey, { agentId, purpose: "purge_knowledge" });
|
|
150
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
151
|
+
const controller = new AbortController();
|
|
152
|
+
let timer;
|
|
153
|
+
const timeout = new Promise((_, reject) => {
|
|
154
|
+
timer = setTimeout(() => {
|
|
155
|
+
controller.abort();
|
|
156
|
+
reject(new Error("timeout"));
|
|
157
|
+
}, PURGE_TENANT_TIMEOUT_MS);
|
|
158
|
+
});
|
|
159
|
+
let response;
|
|
160
|
+
let text;
|
|
161
|
+
try {
|
|
162
|
+
const exchange = (async () => {
|
|
163
|
+
const res = await doFetch(url, {
|
|
164
|
+
method: "DELETE",
|
|
165
|
+
headers: { "content-type": "application/json", accept: "application/json", [import_core2.HEADERS.agent]: agentId, [import_core2.HEADERS.serverToken]: token },
|
|
166
|
+
body: JSON.stringify({ confirm: tenantId }),
|
|
167
|
+
redirect: "error",
|
|
168
|
+
cache: "no-store",
|
|
169
|
+
signal: controller.signal
|
|
170
|
+
});
|
|
171
|
+
return { res, text: await res.text() };
|
|
172
|
+
})();
|
|
173
|
+
exchange.catch(() => {
|
|
174
|
+
});
|
|
175
|
+
({ res: response, text } = await Promise.race([exchange, timeout]));
|
|
176
|
+
} finally {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
if (response.status === 401) return { ok: false, code: "invalid_server_token" };
|
|
180
|
+
if (response.status === 400) return { ok: false, code: "invalid_request" };
|
|
181
|
+
if (response.status !== 200) return UNAVAILABLE2;
|
|
182
|
+
let body;
|
|
183
|
+
try {
|
|
184
|
+
body = JSON.parse(text);
|
|
185
|
+
} catch {
|
|
186
|
+
return UNAVAILABLE2;
|
|
187
|
+
}
|
|
188
|
+
const record = parseRecord(body, tenantId);
|
|
189
|
+
return record ? { ok: true, record } : UNAVAILABLE2;
|
|
190
|
+
} catch {
|
|
191
|
+
return UNAVAILABLE2;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/tenant-upload-token.ts
|
|
196
|
+
var import_core3 = require("@baseera/core");
|
|
197
|
+
async function signTenantUploadToken(options) {
|
|
198
|
+
return (0, import_core3.signServerToken)(options.secretKey, {
|
|
199
|
+
agentId: options.agentId,
|
|
200
|
+
purpose: "kb_tenant_upload",
|
|
201
|
+
bind: { kb: options.knowledgeBase.toLowerCase(), tid: options.tenantId, uid: options.userId },
|
|
202
|
+
ttlSeconds: options.ttlSeconds ?? import_core3.TENANT_UPLOAD_TOKEN_DEFAULT_TTL_SECONDS,
|
|
203
|
+
...options.now ? { now: options.now } : {}
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/knowledge.ts
|
|
208
|
+
var import_core4 = require("@baseera/core");
|
|
209
|
+
var KB_REQUEST_TIMEOUT_MS = 3e4;
|
|
210
|
+
var KB_UPLOAD_TIMEOUT_MS = 12e4;
|
|
211
|
+
var SIGNAL_KEY = /^[A-Za-z0-9_.:-]{8,128}$/;
|
|
212
|
+
var LOOPBACK3 = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
213
|
+
var MIME_BY_EXTENSION = {
|
|
214
|
+
pdf: "application/pdf",
|
|
215
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
216
|
+
md: "text/markdown",
|
|
217
|
+
markdown: "text/markdown",
|
|
218
|
+
txt: "text/plain",
|
|
219
|
+
html: "text/html",
|
|
220
|
+
htm: "text/html",
|
|
221
|
+
csv: "text/csv"
|
|
222
|
+
};
|
|
223
|
+
var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
224
|
+
var fail = (code, retryAfter) => ({ ok: false, code, ...retryAfter !== void 0 ? { retryAfter } : {} });
|
|
225
|
+
function safeBase(baseUrl) {
|
|
226
|
+
try {
|
|
227
|
+
const base = new URL(baseUrl);
|
|
228
|
+
if (base.protocol !== "https:" && !(base.protocol === "http:" && LOOPBACK3.has(base.hostname))) return null;
|
|
229
|
+
return base.origin;
|
|
230
|
+
} catch {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function sha256Hex(bytes) {
|
|
235
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
236
|
+
return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
237
|
+
}
|
|
238
|
+
async function toBytes(data) {
|
|
239
|
+
if (data instanceof Uint8Array) return data;
|
|
240
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
241
|
+
return new Uint8Array(await data.arrayBuffer());
|
|
242
|
+
}
|
|
243
|
+
function createBaseera(options) {
|
|
244
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
245
|
+
const origin = safeBase(options.baseUrl);
|
|
246
|
+
async function call(method, path, body, purpose = "kb_write", extraHeaders) {
|
|
247
|
+
try {
|
|
248
|
+
if (!origin) return fail("unavailable");
|
|
249
|
+
const token = await (0, import_core4.signServerToken)(options.secretKey, { agentId: options.agentId, purpose });
|
|
250
|
+
const res = await doFetch(`${origin}${path}`, {
|
|
251
|
+
method,
|
|
252
|
+
headers: { accept: "application/json", ...body !== void 0 ? { "content-type": "application/json" } : {}, [import_core4.HEADERS.agent]: options.agentId, [import_core4.HEADERS.serverToken]: token, ...extraHeaders },
|
|
253
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
254
|
+
// A redirect would carry the token header to wherever it points: refuse it.
|
|
255
|
+
redirect: "error",
|
|
256
|
+
cache: "no-store",
|
|
257
|
+
signal: AbortSignal.timeout(KB_REQUEST_TIMEOUT_MS)
|
|
258
|
+
});
|
|
259
|
+
const text = await res.text();
|
|
260
|
+
if (res.status === 200) {
|
|
261
|
+
try {
|
|
262
|
+
return { ok: true, body: JSON.parse(text) };
|
|
263
|
+
} catch {
|
|
264
|
+
return fail("unavailable");
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
let code = "";
|
|
268
|
+
try {
|
|
269
|
+
const parsed = JSON.parse(text);
|
|
270
|
+
code = typeof parsed?.error?.code === "string" ? parsed.error.code : "";
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
273
|
+
if (res.status === 401) return fail("invalid_server_token");
|
|
274
|
+
if (res.status === 409 && code === "idempotency_conflict") return fail("idempotency_conflict");
|
|
275
|
+
if (res.status === 404 && code === "source_not_found") return { ok: false, code: "not_found" };
|
|
276
|
+
if (res.status === 404) return fail("knowledge_base_not_found");
|
|
277
|
+
if (res.status === 413) return fail("message_too_large");
|
|
278
|
+
if (res.status === 400) return fail("invalid_request");
|
|
279
|
+
if (res.status === 429) {
|
|
280
|
+
const wait = Number(res.headers.get("retry-after"));
|
|
281
|
+
return fail("rate_limited", Number.isFinite(wait) && wait > 0 ? Math.min(Math.ceil(wait), 3600) : void 0);
|
|
282
|
+
}
|
|
283
|
+
return fail("unavailable");
|
|
284
|
+
} catch {
|
|
285
|
+
return fail("unavailable");
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const parseResults = (body) => {
|
|
289
|
+
if (!isObject3(body) || !Array.isArray(body.results)) return null;
|
|
290
|
+
return body.results;
|
|
291
|
+
};
|
|
292
|
+
async function upload(url, bytes, mimeType) {
|
|
293
|
+
try {
|
|
294
|
+
const target = new URL(url);
|
|
295
|
+
if (target.protocol !== "https:" && !(target.protocol === "http:" && LOOPBACK3.has(target.hostname))) return false;
|
|
296
|
+
const res = await doFetch(url, {
|
|
297
|
+
method: "PUT",
|
|
298
|
+
headers: { "content-type": mimeType, "x-upsert": "false" },
|
|
299
|
+
body: bytes,
|
|
300
|
+
redirect: "error",
|
|
301
|
+
cache: "no-store",
|
|
302
|
+
signal: AbortSignal.timeout(KB_UPLOAD_TIMEOUT_MS)
|
|
303
|
+
});
|
|
304
|
+
await res.arrayBuffer().catch(() => {
|
|
305
|
+
});
|
|
306
|
+
return res.ok;
|
|
307
|
+
} catch {
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const rejected = (externalId, code, message) => ({ externalId, status: "rejected", error: { code, message } });
|
|
312
|
+
async function sendGroup(kb, inputs, results) {
|
|
313
|
+
const batch = [];
|
|
314
|
+
const files = inputs.filter((x) => x.input.file !== void 0);
|
|
315
|
+
for (const x of inputs) {
|
|
316
|
+
if (x.input.file !== void 0) continue;
|
|
317
|
+
const { text, url } = x.input;
|
|
318
|
+
if (text === void 0 === (url === void 0)) {
|
|
319
|
+
results[x.index] = rejected(x.input.externalId, "invalid_item", "Send exactly one of text, url or file.");
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (typeof text === "string" && text.length > import_core4.INGEST_LIMITS.textChars) {
|
|
323
|
+
results[x.index] = rejected(x.input.externalId, "too_large", `text is at most ${import_core4.INGEST_LIMITS.textChars} characters: send it as a file.`);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
batch.push({ index: x.index, item: { externalId: x.input.externalId, title: x.input.title, ...text !== void 0 ? { text } : { url }, ...x.input.metadata ? { metadata: x.input.metadata } : {}, ...x.input.tenantId ? { tenantId: x.input.tenantId } : {}, ...x.input.access !== void 0 ? { access: x.input.access } : {} } });
|
|
327
|
+
}
|
|
328
|
+
for (let from = 0; from < files.length; from += import_core4.INGEST_LIMITS.filesPerUpload) {
|
|
329
|
+
const group = files.slice(from, from + import_core4.INGEST_LIMITS.filesPerUpload);
|
|
330
|
+
const prepared = [];
|
|
331
|
+
const reservations = [];
|
|
332
|
+
for (const x of group) {
|
|
333
|
+
const file = x.input.file;
|
|
334
|
+
const ext = /\.([A-Za-z0-9]{1,8})$/.exec(file.name)?.[1]?.toLowerCase() ?? "";
|
|
335
|
+
const mimeType = file.mimeType ?? MIME_BY_EXTENSION[ext] ?? "";
|
|
336
|
+
let bytes;
|
|
337
|
+
try {
|
|
338
|
+
bytes = await toBytes(file.data);
|
|
339
|
+
} catch {
|
|
340
|
+
results[x.index] = rejected(x.input.externalId, "invalid_item", "The file's bytes could not be read.");
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (bytes.byteLength > import_core4.INGEST_LIMITS.fileBytes) {
|
|
344
|
+
results[x.index] = rejected(x.input.externalId, "too_large", "A file is at most 50 MB.");
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
prepared.push({ x, bytes, mimeType });
|
|
348
|
+
reservations.push({
|
|
349
|
+
externalId: x.input.externalId,
|
|
350
|
+
title: x.input.title,
|
|
351
|
+
fileName: file.name,
|
|
352
|
+
mimeType,
|
|
353
|
+
bytes: bytes.byteLength,
|
|
354
|
+
sha256: await sha256Hex(bytes),
|
|
355
|
+
...x.input.metadata ? { metadata: x.input.metadata } : {},
|
|
356
|
+
...x.input.tenantId ? { tenantId: x.input.tenantId } : {},
|
|
357
|
+
...x.input.access !== void 0 ? { access: x.input.access } : {}
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
if (reservations.length === 0) continue;
|
|
361
|
+
const reserved = await call("POST", import_core4.PATHS.knowledgeUploads(kb), { items: reservations });
|
|
362
|
+
if (!reserved.ok) return reserved.code === "not_found" ? fail("unavailable") : reserved;
|
|
363
|
+
const answers = parseResults(reserved.body);
|
|
364
|
+
if (!answers || answers.length !== prepared.length) return fail("unavailable");
|
|
365
|
+
for (const [i, answer] of answers.entries()) {
|
|
366
|
+
const p = prepared[i];
|
|
367
|
+
if (answer.status === "unchanged") results[p.x.index] = { externalId: p.x.input.externalId, status: "unchanged" };
|
|
368
|
+
else if (answer.status === "rejected") results[p.x.index] = rejected(p.x.input.externalId, answer.error?.code ?? "invalid_item", answer.error?.message ?? "Rejected.");
|
|
369
|
+
else if (answer.status === "upload" && answer.uploadId && answer.uploadUrl) {
|
|
370
|
+
if (!await upload(answer.uploadUrl, p.bytes, p.mimeType)) {
|
|
371
|
+
results[p.x.index] = rejected(p.x.input.externalId, "unavailable", "The file could not be uploaded. Try again.");
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
batch.push({ index: p.x.index, item: { externalId: p.x.input.externalId, title: p.x.input.title, uploadId: answer.uploadId, ...p.x.input.tenantId ? { tenantId: p.x.input.tenantId } : {} } });
|
|
375
|
+
} else {
|
|
376
|
+
return fail("unavailable");
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
let current = [];
|
|
381
|
+
let size = 0;
|
|
382
|
+
const flush = async () => {
|
|
383
|
+
if (current.length === 0) return null;
|
|
384
|
+
const sent = current;
|
|
385
|
+
current = [];
|
|
386
|
+
size = 0;
|
|
387
|
+
const res = await call("POST", import_core4.PATHS.knowledgeItems(kb), { items: sent.map((s) => s.item) });
|
|
388
|
+
if (!res.ok) return res.code === "not_found" ? fail("unavailable") : res;
|
|
389
|
+
const answers = parseResults(res.body);
|
|
390
|
+
if (!answers || answers.length !== sent.length) return fail("unavailable");
|
|
391
|
+
sent.forEach((s, i) => {
|
|
392
|
+
results[s.index] = answers[i];
|
|
393
|
+
});
|
|
394
|
+
return null;
|
|
395
|
+
};
|
|
396
|
+
for (const entry of batch) {
|
|
397
|
+
const bytes = JSON.stringify(entry.item).length + 1;
|
|
398
|
+
if (current.length >= import_core4.INGEST_LIMITS.itemsPerBatch || size + bytes > 35e5) {
|
|
399
|
+
const failure = await flush();
|
|
400
|
+
if (failure) return failure;
|
|
401
|
+
}
|
|
402
|
+
current.push(entry);
|
|
403
|
+
size += bytes;
|
|
404
|
+
}
|
|
405
|
+
return flush();
|
|
406
|
+
}
|
|
407
|
+
return {
|
|
408
|
+
async signal(entity, name, data, signalOptions) {
|
|
409
|
+
const request = { entity, name, ...data !== void 0 ? { data } : {}, ...signalOptions?.tenantId !== void 0 ? { tenantId: signalOptions.tenantId } : {} };
|
|
410
|
+
if (!(0, import_core4.parseSignalRequest)(request).ok) return fail("invalid_request");
|
|
411
|
+
const key = signalOptions?.idempotencyKey ?? crypto.randomUUID();
|
|
412
|
+
if (!SIGNAL_KEY.test(key)) return fail("invalid_request");
|
|
413
|
+
let res = await call("POST", import_core4.PATHS.signals, request, "signal", { "idempotency-key": key });
|
|
414
|
+
if (!res.ok && res.code === "unavailable") res = await call("POST", import_core4.PATHS.signals, request, "signal", { "idempotency-key": key });
|
|
415
|
+
if (!res.ok) return res.code === "not_found" ? fail("unavailable") : res;
|
|
416
|
+
return isObject3(res.body) && typeof res.body.duplicate === "boolean" ? { ok: true, duplicate: res.body.duplicate } : fail("unavailable");
|
|
417
|
+
},
|
|
418
|
+
kb: {
|
|
419
|
+
async createTenantUploadToken(input) {
|
|
420
|
+
try {
|
|
421
|
+
const now = /* @__PURE__ */ new Date();
|
|
422
|
+
const ttl = input.ttlSeconds ?? 300;
|
|
423
|
+
const token = await signTenantUploadToken({ agentId: options.agentId, secretKey: options.secretKey, ...input, ttlSeconds: ttl, now });
|
|
424
|
+
return { ok: true, token, expiresAt: new Date(now.getTime() + ttl * 1e3).toISOString() };
|
|
425
|
+
} catch {
|
|
426
|
+
return { ok: false, code: "invalid_request" };
|
|
427
|
+
}
|
|
428
|
+
},
|
|
429
|
+
async upsert(input) {
|
|
430
|
+
const many = await this.upsertMany([input]);
|
|
431
|
+
if (!many.ok) {
|
|
432
|
+
const { results: _results, ...failure } = many;
|
|
433
|
+
void _results;
|
|
434
|
+
return failure;
|
|
435
|
+
}
|
|
436
|
+
return { ok: true, item: many.results[0] };
|
|
437
|
+
},
|
|
438
|
+
async upsertMany(inputs) {
|
|
439
|
+
const results = new Array(inputs.length).fill(void 0);
|
|
440
|
+
const groups = /* @__PURE__ */ new Map();
|
|
441
|
+
inputs.forEach((input, index) => {
|
|
442
|
+
if (!input || typeof input.knowledgeBase !== "string" || input.knowledgeBase === "") {
|
|
443
|
+
results[index] = rejected(String(input?.externalId ?? ""), "invalid_item", "knowledgeBase is required.");
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const list = groups.get(input.knowledgeBase) ?? [];
|
|
447
|
+
list.push({ index, input });
|
|
448
|
+
groups.set(input.knowledgeBase, list);
|
|
449
|
+
});
|
|
450
|
+
for (const [kb, group] of groups) {
|
|
451
|
+
const failure = await sendGroup(kb, group, results);
|
|
452
|
+
if (failure) return { ...failure, results: results.filter((r) => r !== void 0) };
|
|
453
|
+
}
|
|
454
|
+
return { ok: true, results: results.map((r, i) => r ?? rejected(inputs[i]?.externalId ?? "", "unavailable", "Not sent.")) };
|
|
455
|
+
},
|
|
456
|
+
async delete(input) {
|
|
457
|
+
const query = input.tenantId ? `?tenantId=${encodeURIComponent(input.tenantId)}` : "";
|
|
458
|
+
const res = await call("DELETE", `${import_core4.PATHS.knowledgeItem(input.knowledgeBase, input.externalId)}${query}`);
|
|
459
|
+
if (!res.ok) return res.code === "not_found" ? fail("unavailable") : res;
|
|
460
|
+
return isObject3(res.body) && typeof res.body.deleted === "boolean" ? { ok: true, deleted: res.body.deleted } : fail("unavailable");
|
|
461
|
+
},
|
|
462
|
+
async status(input) {
|
|
463
|
+
const query = input.tenantId ? `?tenantId=${encodeURIComponent(input.tenantId)}` : "";
|
|
464
|
+
const res = await call("GET", `${import_core4.PATHS.knowledgeItem(input.knowledgeBase, input.externalId)}${query}`);
|
|
465
|
+
if (!res.ok) return res;
|
|
466
|
+
const b = res.body;
|
|
467
|
+
if (!isObject3(b) || typeof b.status !== "string" || typeof b.version !== "number") return fail("unavailable");
|
|
468
|
+
return { ok: true, status: b };
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// src/index.ts
|
|
475
|
+
var import_core7 = require("@baseera/core");
|
|
476
|
+
|
|
477
|
+
// src/verify-webhook.ts
|
|
478
|
+
var import_core5 = require("@baseera/core");
|
|
479
|
+
function isRequestLike(value) {
|
|
480
|
+
return typeof value === "object" && value !== null && typeof value.text === "function" && typeof value.headers?.get === "function";
|
|
481
|
+
}
|
|
482
|
+
async function verifyWebhook(first, second, third, fourth) {
|
|
483
|
+
let rawBody;
|
|
484
|
+
let header;
|
|
485
|
+
let secret;
|
|
486
|
+
let options;
|
|
487
|
+
try {
|
|
488
|
+
if (isRequestLike(first)) {
|
|
489
|
+
const source = first.bodyUsed === false && typeof first.clone === "function" ? first.clone() : first;
|
|
490
|
+
rawBody = await source.text();
|
|
491
|
+
header = first.headers.get(import_core5.WEBHOOK_SIGNATURE_HEADER);
|
|
492
|
+
secret = second;
|
|
493
|
+
options = third ?? {};
|
|
494
|
+
} else {
|
|
495
|
+
rawBody = typeof first === "string" ? first : first instanceof Uint8Array ? new TextDecoder("utf-8", { fatal: true }).decode(first) : null;
|
|
496
|
+
header = Array.isArray(second) ? second.length === 1 ? second[0] : void 0 : second;
|
|
497
|
+
secret = third;
|
|
498
|
+
options = fourth ?? {};
|
|
499
|
+
}
|
|
500
|
+
} catch {
|
|
501
|
+
return { ok: false, reason: "invalid_body" };
|
|
502
|
+
}
|
|
503
|
+
if (typeof rawBody !== "string") return { ok: false, reason: "invalid_body" };
|
|
504
|
+
const checked = await (0, import_core5.verifyWebhookSignature)(rawBody, header, secret, { toleranceSec: options.toleranceSec ?? import_core5.WEBHOOK_TOLERANCE_SECONDS, ...options.now ? { now: options.now } : {} });
|
|
505
|
+
if (!checked.ok) return checked;
|
|
506
|
+
try {
|
|
507
|
+
const event = JSON.parse(rawBody);
|
|
508
|
+
if (!event || typeof event !== "object" || typeof event.id !== "string" || typeof event.type !== "string" || typeof event.data !== "object" || event.data === null) {
|
|
509
|
+
return { ok: false, reason: "invalid_body" };
|
|
510
|
+
}
|
|
511
|
+
return { ok: true, event, timestamp: checked.timestamp };
|
|
512
|
+
} catch {
|
|
513
|
+
return { ok: false, reason: "invalid_body" };
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// src/index.ts
|
|
518
|
+
var import_core8 = require("@baseera/core");
|
|
519
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
520
|
+
0 && (module.exports = {
|
|
521
|
+
FINISH_WEBHOOK_EVENT_TYPE,
|
|
522
|
+
KB_REQUEST_TIMEOUT_MS,
|
|
523
|
+
KB_UPLOAD_TIMEOUT_MS,
|
|
524
|
+
PROTOCOL_VERSION,
|
|
525
|
+
PURGE_TENANT_TIMEOUT_MS,
|
|
526
|
+
SIGNAL_LIMITS,
|
|
527
|
+
TENANT_UPLOAD_TOKEN_DEFAULT_TTL_SECONDS,
|
|
528
|
+
TENANT_UPLOAD_TOKEN_MAX_TTL_SECONDS,
|
|
529
|
+
USER_TOKEN_DEFAULT_TTL_SECONDS,
|
|
530
|
+
USER_TOKEN_MAX_TTL_SECONDS,
|
|
531
|
+
VERIFY_FINISH_TIMEOUT_MS,
|
|
532
|
+
WEBHOOK_TOLERANCE_SECONDS,
|
|
533
|
+
createBaseera,
|
|
534
|
+
generateWebhookSecret,
|
|
535
|
+
purgeTenantKnowledge,
|
|
536
|
+
signTenantUploadToken,
|
|
537
|
+
signUserToken,
|
|
538
|
+
verifyFinish,
|
|
539
|
+
verifyWebhook
|
|
540
|
+
});
|
|
541
|
+
//# sourceMappingURL=index.cjs.map
|