dsh-brain/lib/mnemon/fork/providers/http.js

126 lines
4.9 KiB
JavaScript

export function bearerAuthHeader(apiKey) {
if (typeof apiKey !== 'string')
return undefined;
const token = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, '').trim();
return token === '' ? undefined : `Bearer ${token}`;
}
export function jsonObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? value
: undefined;
}
export function jsonString(value) {
return typeof value === 'string' ? value : undefined;
}
export function jsonNumber(value) {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
export function jsonArray(value) {
return Array.isArray(value) ? value : [];
}
export function firstArray(value, ...keys) {
if (Array.isArray(value))
return value;
const root = jsonObject(value);
for (const key of keys)
if (Array.isArray(root?.[key]))
return root[key];
const nested = jsonObject(root?.data);
for (const key of keys)
if (Array.isArray(nested?.[key]))
return nested[key];
return [];
}
function errorDetail(payload) {
if (typeof payload === 'string')
return payload.trim() || undefined;
const root = jsonObject(payload);
const direct = jsonString(root?.message) ?? jsonString(root?.error) ?? jsonString(root?.detail);
if (direct !== undefined)
return direct;
const error = jsonObject(root?.error);
return jsonString(error?.message) ?? jsonString(error?.detail);
}
export class HttpMemoryProvider {
memorySpaces;
label;
requestFetch;
requestTimeoutMs;
/** @deprecated Use memorySpaces. */
memoryBodies;
constructor(memorySpaces, options = {}) {
this.memorySpaces = memorySpaces;
this.memoryBodies = memorySpaces;
this.label = options.label;
this.requestFetch = options.fetch ?? globalThis.fetch;
this.requestTimeoutMs = options.requestTimeoutMs ?? 15_000;
}
async graph(body, signal) {
const items = await this.list(body, { limit: 200 }, signal);
return {
nodes: items.map(item => ({ ...item, color: '#6574d9' })),
edges: [],
generatedAt: new Date().toISOString(),
};
}
connection(body) {
if ((body.provider.typeId ?? body.provider.id) !== this.id)
throw new Error(`${this.id} cannot serve provider ${body.provider.id}`);
return this.memorySpaces.providerConnection(body.id, body.provider.id);
}
async request(body, path, options = {}) {
const connection = this.connection(body);
return this.requestConnection(connection, path, options);
}
async requestConnection(connection, path, options = {}) {
const endpoint = String(connection.endpoint ?? '').replace(/\/+$/u, '');
const label = this.label ?? this.id;
if (endpoint === '')
throw new Error(`${label} endpoint is not configured`);
if (!path.startsWith('/'))
throw new Error(`${label} request path must be absolute`);
options.signal?.throwIfAborted();
const controller = new AbortController();
const relay = () => controller.abort(options.signal?.reason);
options.signal?.addEventListener('abort', relay, { once: true });
const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
const timer = setTimeout(() => controller.abort(new Error(`${label} request timed out`)), timeoutMs);
const headers = new Headers(options.headers);
if (options.json !== undefined && !headers.has('Content-Type'))
headers.set('Content-Type', 'application/json');
try {
const response = await this.requestFetch(`${endpoint}${path}`, {
method: options.method ?? (options.json === undefined ? 'GET' : 'POST'),
headers,
...(options.json === undefined ? {} : { body: JSON.stringify(options.json) }),
signal: controller.signal,
});
const raw = await response.text();
let payload = {};
if (raw !== '') {
try {
payload = JSON.parse(raw);
}
catch {
payload = raw;
}
}
if (!response.ok) {
const detail = errorDetail(payload);
throw Object.assign(new Error(`${label} HTTP ${response.status}${detail === undefined ? '' : `: ${detail}`}`), { status: response.status });
}
return payload;
}
catch (error) {
if (controller.signal.aborted && options.signal?.aborted !== true) {
throw new Error(`${label} request timed out after ${timeoutMs}ms`);
}
throw error;
}
finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', relay);
}
}
}