@almadar/sdk 0.1.0-alpha.4 → 0.1.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/dist/client/index.d.ts +3 -3
- package/dist/client/index.js +25 -11
- package/dist/client/index.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +25 -21
- package/dist/index.js.map +1 -1
- package/dist/react/index.d.ts +7 -5
- package/dist/react/index.js +3 -10
- package/dist/react/index.js.map +1 -1
- package/dist/server/express.d.ts +39 -0
- package/dist/server/express.js +472 -0
- package/dist/server/express.js.map +1 -0
- package/dist/server/hono.d.ts +33 -0
- package/dist/server/hono.js +417 -0
- package/dist/server/hono.js.map +1 -0
- package/dist/server/index.d.ts +14 -11
- package/dist/server/index.js +102 -46
- package/dist/server/index.js.map +1 -1
- package/dist/{types-BfWDIOGm.d.ts → types-D-q0c5Yt.d.ts} +26 -64
- package/package.json +15 -13
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
import { parseOrbitalSchema } from '@almadar/core';
|
|
2
|
+
|
|
3
|
+
// src/client/AlmadarClient.ts
|
|
4
|
+
|
|
5
|
+
// src/client/errors.ts
|
|
6
|
+
var AlmadarError = class extends Error {
|
|
7
|
+
code;
|
|
8
|
+
details;
|
|
9
|
+
constructor(body) {
|
|
10
|
+
super(body.message);
|
|
11
|
+
this.name = "AlmadarError";
|
|
12
|
+
this.code = body.code;
|
|
13
|
+
this.details = body.details;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var ApiKeyError = class extends AlmadarError {
|
|
17
|
+
constructor(body) {
|
|
18
|
+
super(body);
|
|
19
|
+
this.name = "ApiKeyError";
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var RateLimitedError = class extends AlmadarError {
|
|
23
|
+
retryAfterSeconds;
|
|
24
|
+
constructor(body, retryAfterSeconds) {
|
|
25
|
+
super(body);
|
|
26
|
+
this.name = "RateLimitedError";
|
|
27
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
var CatalogOutOfScopeError = class extends AlmadarError {
|
|
31
|
+
constructor(body) {
|
|
32
|
+
super(body);
|
|
33
|
+
this.name = "CatalogOutOfScopeError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var ServerError = class extends AlmadarError {
|
|
37
|
+
constructor(body) {
|
|
38
|
+
super(body);
|
|
39
|
+
this.name = "ServerError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function errorFromBody(body) {
|
|
43
|
+
switch (body.code) {
|
|
44
|
+
case 4001:
|
|
45
|
+
return new ApiKeyError(body);
|
|
46
|
+
case 4029:
|
|
47
|
+
return new RateLimitedError(body);
|
|
48
|
+
case 4040:
|
|
49
|
+
return new CatalogOutOfScopeError(body);
|
|
50
|
+
default:
|
|
51
|
+
return new ServerError(body);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/client/sseParser.ts
|
|
56
|
+
async function* parseSSE(stream) {
|
|
57
|
+
const reader = stream.getReader();
|
|
58
|
+
const decoder = new TextDecoder("utf-8");
|
|
59
|
+
let buffer = "";
|
|
60
|
+
let currentEvent = "";
|
|
61
|
+
let currentData = "";
|
|
62
|
+
try {
|
|
63
|
+
for (; ; ) {
|
|
64
|
+
const { value, done } = await reader.read();
|
|
65
|
+
if (done) break;
|
|
66
|
+
buffer += decoder.decode(value, { stream: true });
|
|
67
|
+
let newlineIdx;
|
|
68
|
+
while ((newlineIdx = indexOfNewline(buffer)) !== -1) {
|
|
69
|
+
const rawLine = buffer.slice(0, newlineIdx);
|
|
70
|
+
buffer = buffer.slice(newlineIdx + (buffer[newlineIdx] === "\r" && buffer[newlineIdx + 1] === "\n" ? 2 : 1));
|
|
71
|
+
if (rawLine === "") {
|
|
72
|
+
if (currentData !== "" || currentEvent !== "") {
|
|
73
|
+
yield { event: currentEvent, data: currentData };
|
|
74
|
+
currentEvent = "";
|
|
75
|
+
currentData = "";
|
|
76
|
+
}
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (rawLine.startsWith(":")) continue;
|
|
80
|
+
const colon = rawLine.indexOf(":");
|
|
81
|
+
const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
|
|
82
|
+
const rawValue = colon === -1 ? "" : rawLine.slice(colon + 1);
|
|
83
|
+
const value2 = rawValue.startsWith(" ") ? rawValue.slice(1) : rawValue;
|
|
84
|
+
if (field === "event") {
|
|
85
|
+
currentEvent = value2;
|
|
86
|
+
} else if (field === "data") {
|
|
87
|
+
currentData = currentData === "" ? value2 : `${currentData}
|
|
88
|
+
${value2}`;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (currentData !== "" || currentEvent !== "") {
|
|
93
|
+
yield { event: currentEvent, data: currentData };
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
reader.releaseLock();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function indexOfNewline(s) {
|
|
100
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
101
|
+
const c = s[i];
|
|
102
|
+
if (c === "\n" || c === "\r") return i;
|
|
103
|
+
}
|
|
104
|
+
return -1;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/client/AlmadarClient.ts
|
|
108
|
+
var DEFAULT_BASE_URL = "https://studio.almadar.io";
|
|
109
|
+
var POLL_BACKOFF_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
|
|
110
|
+
var AlmadarClient = class {
|
|
111
|
+
apiKey;
|
|
112
|
+
baseUrl;
|
|
113
|
+
fetchImpl;
|
|
114
|
+
constructor(opts) {
|
|
115
|
+
if (!opts.apiKey || typeof opts.apiKey !== "string") {
|
|
116
|
+
throw new Error("AlmadarClient: opts.apiKey is required");
|
|
117
|
+
}
|
|
118
|
+
this.apiKey = opts.apiKey;
|
|
119
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
120
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
121
|
+
if (typeof this.fetchImpl !== "function") {
|
|
122
|
+
throw new Error("AlmadarClient: no fetch available \u2014 pass opts.fetch for Node <18");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async generate(input) {
|
|
126
|
+
if (input.async === true) {
|
|
127
|
+
const handle = await this.requestJson("POST", "/api/v1/agent/generate", {
|
|
128
|
+
prompt: input.prompt,
|
|
129
|
+
endUserId: input.endUserId,
|
|
130
|
+
appId: input.appId,
|
|
131
|
+
async: true,
|
|
132
|
+
provider: input.provider,
|
|
133
|
+
model: input.model,
|
|
134
|
+
catalogMode: input.catalogMode,
|
|
135
|
+
stdAllowList: input.stdAllowList
|
|
136
|
+
});
|
|
137
|
+
assertString(handle.jobId, "AsyncJobHandle.jobId");
|
|
138
|
+
assertString(handle.statusUrl, "AsyncJobHandle.statusUrl");
|
|
139
|
+
return this.pollUntilComplete(handle, input.onEvent);
|
|
140
|
+
}
|
|
141
|
+
return this.streamGenerate(input);
|
|
142
|
+
}
|
|
143
|
+
async editSchema(appId, patch) {
|
|
144
|
+
if (!appId) throw new Error("AlmadarClient.editSchema: appId is required");
|
|
145
|
+
const schema = await this.requestJson("PUT", "/api/v1/agent/edit-schema", {
|
|
146
|
+
appId,
|
|
147
|
+
patch
|
|
148
|
+
});
|
|
149
|
+
assertString(schema.name, "OrbitalSchema.name");
|
|
150
|
+
return schema;
|
|
151
|
+
}
|
|
152
|
+
async compileToApp(schema, opts) {
|
|
153
|
+
const result = await this.requestJson("POST", "/api/v1/agent/compile", {
|
|
154
|
+
schema,
|
|
155
|
+
target: opts?.target,
|
|
156
|
+
shell: opts?.shell
|
|
157
|
+
});
|
|
158
|
+
assertString(result.downloadUrl, "CompileResult.downloadUrl");
|
|
159
|
+
assertString(result.expiresAt, "CompileResult.expiresAt");
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
async streamGenerate(input) {
|
|
163
|
+
const res = await this.fetchImpl(`${this.baseUrl}/api/v1/agent/generate`, {
|
|
164
|
+
method: "POST",
|
|
165
|
+
headers: this.headers({ accept: "text/event-stream", contentType: "application/json" }, input.endUserId),
|
|
166
|
+
body: JSON.stringify({
|
|
167
|
+
prompt: input.prompt,
|
|
168
|
+
endUserId: input.endUserId,
|
|
169
|
+
appId: input.appId,
|
|
170
|
+
provider: input.provider,
|
|
171
|
+
model: input.model,
|
|
172
|
+
catalogMode: input.catalogMode,
|
|
173
|
+
stdAllowList: input.stdAllowList
|
|
174
|
+
})
|
|
175
|
+
});
|
|
176
|
+
if (!res.ok) throw await this.errorFromResponse(res);
|
|
177
|
+
if (res.body === null) throw new Error("AlmadarClient.generate: server returned no body");
|
|
178
|
+
let final = null;
|
|
179
|
+
for await (const raw of parseSSE(res.body)) {
|
|
180
|
+
const event = parseSseEvent(raw.data);
|
|
181
|
+
if (event === null) continue;
|
|
182
|
+
input.onEvent?.(event);
|
|
183
|
+
if (event.type === "complete") {
|
|
184
|
+
if (event.data.schema === void 0) {
|
|
185
|
+
throw new ServerError({ code: 500, message: "`complete` event did not contain a schema" });
|
|
186
|
+
}
|
|
187
|
+
const schema = parseOrbitalSchema(event.data.schema);
|
|
188
|
+
final = { schema, appId: event.data.appId };
|
|
189
|
+
} else if (event.type === "error") {
|
|
190
|
+
throw errorFromBody({ code: 500, message: event.data.error });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (final === null) {
|
|
194
|
+
throw new ServerError({ code: 500, message: "SSE stream ended without `complete` event" });
|
|
195
|
+
}
|
|
196
|
+
return final;
|
|
197
|
+
}
|
|
198
|
+
async pollUntilComplete(handle, onEvent) {
|
|
199
|
+
let attempt = 0;
|
|
200
|
+
for (; ; ) {
|
|
201
|
+
const delay = POLL_BACKOFF_MS[Math.min(attempt, POLL_BACKOFF_MS.length - 1)];
|
|
202
|
+
await sleep(delay);
|
|
203
|
+
attempt += 1;
|
|
204
|
+
const status = await this.requestJson("GET", handle.statusUrl);
|
|
205
|
+
assertString(status.state, "JobStatus.state");
|
|
206
|
+
if (status.events !== void 0 && onEvent !== void 0) {
|
|
207
|
+
for (const e of status.events) onEvent(e);
|
|
208
|
+
}
|
|
209
|
+
if (status.state === "complete") {
|
|
210
|
+
if (status.result === void 0) {
|
|
211
|
+
throw new ServerError({ code: 500, message: "Job complete but no result returned" });
|
|
212
|
+
}
|
|
213
|
+
return status.result;
|
|
214
|
+
}
|
|
215
|
+
if (status.state === "error") {
|
|
216
|
+
throw errorFromBody({
|
|
217
|
+
code: status.errorCode ?? 500,
|
|
218
|
+
message: status.errorMessage ?? "Job failed"
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async requestJson(method, path, body) {
|
|
224
|
+
const isAbsolute = path.startsWith("http://") || path.startsWith("https://");
|
|
225
|
+
const url = isAbsolute ? path : `${this.baseUrl}${path}`;
|
|
226
|
+
const init = {
|
|
227
|
+
method,
|
|
228
|
+
headers: this.headers({
|
|
229
|
+
accept: "application/json",
|
|
230
|
+
contentType: body !== void 0 ? "application/json" : void 0
|
|
231
|
+
})
|
|
232
|
+
};
|
|
233
|
+
if (body !== void 0) init.body = JSON.stringify(body);
|
|
234
|
+
const res = await this.fetchImpl(url, init);
|
|
235
|
+
if (!res.ok) throw await this.errorFromResponse(res);
|
|
236
|
+
const text = await res.text();
|
|
237
|
+
if (text === "") {
|
|
238
|
+
throw new ServerError({ code: 500, message: "Empty response body" });
|
|
239
|
+
}
|
|
240
|
+
const parsed = JSON.parse(text);
|
|
241
|
+
return parsed;
|
|
242
|
+
}
|
|
243
|
+
headers(opts, endUserId) {
|
|
244
|
+
const h = { authorization: `Bearer ${this.apiKey}` };
|
|
245
|
+
if (opts.accept !== void 0) h["accept"] = opts.accept;
|
|
246
|
+
if (opts.contentType !== void 0) h["content-type"] = opts.contentType;
|
|
247
|
+
if (endUserId !== void 0 && endUserId !== "") h["x-end-user-id"] = endUserId;
|
|
248
|
+
return h;
|
|
249
|
+
}
|
|
250
|
+
async errorFromResponse(res) {
|
|
251
|
+
const text = await res.text();
|
|
252
|
+
let body;
|
|
253
|
+
try {
|
|
254
|
+
const parsed = text === "" ? null : JSON.parse(text);
|
|
255
|
+
body = parsed !== null && typeof parsed.code === "number" && typeof parsed.message === "string" ? parsed : {
|
|
256
|
+
code: res.status,
|
|
257
|
+
message: res.statusText !== "" ? res.statusText : "HTTP error"
|
|
258
|
+
};
|
|
259
|
+
} catch {
|
|
260
|
+
body = { code: res.status, message: text !== "" ? text : res.statusText };
|
|
261
|
+
}
|
|
262
|
+
const retryAfter = res.headers.get("retry-after");
|
|
263
|
+
const err = errorFromBody(body);
|
|
264
|
+
if (err.name === "RateLimitedError" && retryAfter !== null) {
|
|
265
|
+
const seconds = Number(retryAfter);
|
|
266
|
+
if (Number.isFinite(seconds)) {
|
|
267
|
+
Object.defineProperty(err, "retryAfterSeconds", { value: seconds, enumerable: true });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return err;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
function parseSseEvent(dataLine) {
|
|
274
|
+
if (dataLine === "") return null;
|
|
275
|
+
let payload;
|
|
276
|
+
try {
|
|
277
|
+
payload = JSON.parse(dataLine);
|
|
278
|
+
} catch {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return null;
|
|
282
|
+
if (typeof payload.type !== "string" || typeof payload.timestamp !== "number") return null;
|
|
283
|
+
return payload;
|
|
284
|
+
}
|
|
285
|
+
function assertString(v, name) {
|
|
286
|
+
if (typeof v !== "string" || v === "") {
|
|
287
|
+
throw new ServerError({ code: 500, message: `Malformed server response: ${name} is not a string` });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function sleep(ms) {
|
|
291
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// src/server/index.ts
|
|
295
|
+
function resolveEndUserId(opts, req) {
|
|
296
|
+
if (opts.endUserId) return opts.endUserId(req);
|
|
297
|
+
const header = req.headers.get("x-user-id");
|
|
298
|
+
return typeof header === "string" && header.length > 0 ? header : void 0;
|
|
299
|
+
}
|
|
300
|
+
function encodeSseEvent(event) {
|
|
301
|
+
return `data: ${JSON.stringify(event)}
|
|
302
|
+
|
|
303
|
+
`;
|
|
304
|
+
}
|
|
305
|
+
function createGenerateHandler(opts) {
|
|
306
|
+
return async (request) => {
|
|
307
|
+
let body;
|
|
308
|
+
try {
|
|
309
|
+
body = await request.json();
|
|
310
|
+
} catch {
|
|
311
|
+
return new Response(JSON.stringify({ error: "invalid JSON body" }), {
|
|
312
|
+
status: 400,
|
|
313
|
+
headers: { "content-type": "application/json" }
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const rawPrompt = body.prompt ?? body.message;
|
|
317
|
+
const prompt = typeof rawPrompt === "string" ? rawPrompt : "";
|
|
318
|
+
if (!prompt) {
|
|
319
|
+
return new Response(JSON.stringify({ error: "prompt or message is required" }), {
|
|
320
|
+
status: 400,
|
|
321
|
+
headers: { "content-type": "application/json" }
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
const bodyEndUserId = typeof body.endUserId === "string" ? body.endUserId : void 0;
|
|
325
|
+
const endUserId = bodyEndUserId ?? resolveEndUserId(opts, request);
|
|
326
|
+
const appId = typeof body.appId === "string" ? body.appId : void 0;
|
|
327
|
+
const client = new AlmadarClient({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
328
|
+
const stream = new ReadableStream({
|
|
329
|
+
async start(controller) {
|
|
330
|
+
const encoder = new TextEncoder();
|
|
331
|
+
try {
|
|
332
|
+
await client.generate({
|
|
333
|
+
prompt,
|
|
334
|
+
endUserId,
|
|
335
|
+
appId,
|
|
336
|
+
onEvent: (event) => {
|
|
337
|
+
controller.enqueue(encoder.encode(encodeSseEvent(event)));
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
} catch (err) {
|
|
341
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
342
|
+
const errorEvent = {
|
|
343
|
+
type: "error",
|
|
344
|
+
timestamp: Date.now(),
|
|
345
|
+
data: { error: message }
|
|
346
|
+
};
|
|
347
|
+
controller.enqueue(encoder.encode(encodeSseEvent(errorEvent)));
|
|
348
|
+
} finally {
|
|
349
|
+
controller.close();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
return new Response(stream, {
|
|
354
|
+
status: 200,
|
|
355
|
+
headers: {
|
|
356
|
+
"content-type": "text/event-stream",
|
|
357
|
+
"cache-control": "no-cache",
|
|
358
|
+
connection: "keep-alive"
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function createEditHandler(opts) {
|
|
364
|
+
return async (request) => {
|
|
365
|
+
let body;
|
|
366
|
+
try {
|
|
367
|
+
body = await request.json();
|
|
368
|
+
} catch {
|
|
369
|
+
return new Response(JSON.stringify({ error: "invalid JSON body" }), {
|
|
370
|
+
status: 400,
|
|
371
|
+
headers: { "content-type": "application/json" }
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
const appId = typeof body.appId === "string" ? body.appId : "";
|
|
375
|
+
if (!appId) {
|
|
376
|
+
return new Response(JSON.stringify({ error: "appId is required" }), {
|
|
377
|
+
status: 400,
|
|
378
|
+
headers: { "content-type": "application/json" }
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
const patch = body.patch;
|
|
382
|
+
if (patch === void 0 || patch === null || typeof patch !== "object") {
|
|
383
|
+
return new Response(JSON.stringify({ error: "patch is required" }), {
|
|
384
|
+
status: 400,
|
|
385
|
+
headers: { "content-type": "application/json" }
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
const client = new AlmadarClient({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
389
|
+
try {
|
|
390
|
+
const schema = await client.editSchema(appId, patch);
|
|
391
|
+
return new Response(JSON.stringify(schema), {
|
|
392
|
+
status: 200,
|
|
393
|
+
headers: { "content-type": "application/json" }
|
|
394
|
+
});
|
|
395
|
+
} catch (err) {
|
|
396
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
397
|
+
return new Response(JSON.stringify({ error: message }), {
|
|
398
|
+
status: 500,
|
|
399
|
+
headers: { "content-type": "application/json" }
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/server/express.ts
|
|
406
|
+
function expressReqToWebRequest(req) {
|
|
407
|
+
const protocol = req.protocol;
|
|
408
|
+
const host = req.get("host") ?? "localhost";
|
|
409
|
+
const url = `${protocol}://${host}${req.originalUrl}`;
|
|
410
|
+
const headers = new Headers();
|
|
411
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
412
|
+
if (typeof value === "string") {
|
|
413
|
+
headers.set(key, value);
|
|
414
|
+
} else if (Array.isArray(value)) {
|
|
415
|
+
for (const v of value) headers.append(key, v);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
const bodyJson = JSON.stringify(req.body);
|
|
419
|
+
return new Request(url, { method: req.method, headers, body: bodyJson });
|
|
420
|
+
}
|
|
421
|
+
async function pipeWebResponseToExpress(webRes, res) {
|
|
422
|
+
res.status(webRes.status);
|
|
423
|
+
webRes.headers.forEach((value, key) => {
|
|
424
|
+
res.setHeader(key, value);
|
|
425
|
+
});
|
|
426
|
+
if (webRes.body === null) {
|
|
427
|
+
res.end();
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const reader = webRes.body.getReader();
|
|
431
|
+
try {
|
|
432
|
+
for (; ; ) {
|
|
433
|
+
const { done, value } = await reader.read();
|
|
434
|
+
if (done) break;
|
|
435
|
+
res.write(value);
|
|
436
|
+
}
|
|
437
|
+
} finally {
|
|
438
|
+
reader.releaseLock();
|
|
439
|
+
res.end();
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function createGenerateHandler2(opts) {
|
|
443
|
+
const coreHandler = createGenerateHandler({
|
|
444
|
+
apiKey: opts.apiKey,
|
|
445
|
+
baseUrl: opts.baseUrl,
|
|
446
|
+
endUserId: opts.endUserId ? (webReq) => {
|
|
447
|
+
const userId = webReq.headers.get("x-user-id");
|
|
448
|
+
return userId ?? "";
|
|
449
|
+
} : void 0
|
|
450
|
+
});
|
|
451
|
+
return async (req, res) => {
|
|
452
|
+
if (opts.endUserId) {
|
|
453
|
+
const userId = opts.endUserId(req);
|
|
454
|
+
if (userId) req.headers["x-user-id"] = userId;
|
|
455
|
+
}
|
|
456
|
+
const webReq = expressReqToWebRequest(req);
|
|
457
|
+
const webRes = await coreHandler(webReq);
|
|
458
|
+
await pipeWebResponseToExpress(webRes, res);
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
function createEditHandler2(opts) {
|
|
462
|
+
const coreHandler = createEditHandler({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });
|
|
463
|
+
return async (req, res) => {
|
|
464
|
+
const webReq = expressReqToWebRequest(req);
|
|
465
|
+
const webRes = await coreHandler(webReq);
|
|
466
|
+
await pipeWebResponseToExpress(webRes, res);
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export { createEditHandler2 as createEditHandler, createGenerateHandler2 as createGenerateHandler };
|
|
471
|
+
//# sourceMappingURL=express.js.map
|
|
472
|
+
//# sourceMappingURL=express.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/client/errors.ts","../../src/client/sseParser.ts","../../src/client/AlmadarClient.ts","../../src/server/index.ts","../../src/server/express.ts"],"names":["createGenerateHandler","createEditHandler"],"mappings":";;;;;AAOO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EACA,OAAA;AAAA,EACT,YAAY,IAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,KAAK,O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cAAc,qBAAA,CAAoB;AAAA,IACtC,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,SAAA,EAAW,IAAA,CAAK,SAAA,GACZ,CAAC,MAAA,KAAoB;AAInB,MAAA,MAAM,MAAA,GAAS,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA;AAC7C,MAAA,OAAO,MAAA,IAAU,EAAA;AAAA,IACnB,CAAA,GACA;AAAA,GACL,CAAA;AACD,EAAA,OAAO,OAAO,KAAqB,GAAA,KAAwC;AACzE,IAAA,IAAI,KAAK,SAAA,EAAW;AAClB,MAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,GAAG,CAAA;AACjC,MAAA,IAAI,MAAA,EAAQ,GAAA,CAAI,OAAA,CAAQ,WAAW,CAAA,GAAI,MAAA;AAAA,IACzC;AACA,IAAA,MAAM,MAAA,GAAS,uBAAuB,GAAG,CAAA;AACzC,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,MAAM,CAAA;AACvC,IAAA,MAAM,wBAAA,CAAyB,QAAQ,GAAG,CAAA;AAAA,EAC5C,CAAA;AACF;AAOO,SAASC,mBAAkB,IAAA,EAA8C;AAC9E,EAAA,MAAM,WAAA,GAAc,kBAAgB,EAAE,MAAA,EAAQ,KAAK,MAAA,EAAQ,OAAA,EAAS,IAAA,CAAK,OAAA,EAAS,CAAA;AAClF,EAAA,OAAO,OAAO,KAAqB,GAAA,KAAwC;AACzE,IAAA,MAAM,MAAA,GAAS,uBAAuB,GAAG,CAAA;AACzC,IAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,MAAM,CAAA;AACvC,IAAA,MAAM,wBAAA,CAAyB,QAAQ,GAAG,CAAA;AAAA,EAC5C,CAAA;AACF","file":"express.js","sourcesContent":["/**\n * Typed SDK errors. Server emits a structured `ApiErrorBody`; the HTTP layer\n * maps the `code` to one of these subclasses. Customers `catch` by class.\n */\n\nimport type { ApiErrorBody } from '../types';\n\nexport class AlmadarError extends Error {\n readonly code: number;\n readonly details?: ApiErrorBody['details'];\n constructor(body: ApiErrorBody) {\n super(body.message);\n this.name = 'AlmadarError';\n this.code = body.code;\n this.details = body.details;\n }\n}\n\n/** 4001 — invalid, revoked, or missing API key. */\nexport class ApiKeyError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'ApiKeyError';\n }\n}\n\n/** 4029 — team cap (feature counter) exceeded. Retry after a billing cycle. */\nexport class RateLimitedError extends AlmadarError {\n readonly retryAfterSeconds?: number;\n constructor(body: ApiErrorBody, retryAfterSeconds?: number) {\n super(body);\n this.name = 'RateLimitedError';\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\n/** 4040 — the team's behavior catalog (subset/replace mode) cannot serve the request. */\nexport class CatalogOutOfScopeError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'CatalogOutOfScopeError';\n }\n}\n\n/** Anything else from the server with a recognized envelope but no specific subclass. */\nexport class ServerError extends AlmadarError {\n constructor(body: ApiErrorBody) {\n super(body);\n this.name = 'ServerError';\n }\n}\n\nexport function errorFromBody(body: ApiErrorBody): AlmadarError {\n switch (body.code) {\n case 4001:\n return new ApiKeyError(body);\n case 4029:\n return new RateLimitedError(body);\n case 4040:\n return new CatalogOutOfScopeError(body);\n default:\n return new ServerError(body);\n }\n}\n","/**\n * Minimal Server-Sent Events parser. Reads a `ReadableStream<Uint8Array>`\n * (the body of a `fetch` Response) and yields decoded events. Universal:\n * works in browser, Node 18+, Deno, Bun.\n *\n * Spec subset implemented:\n * - `event:` and `data:` fields\n * - dispatch on blank line\n * - newline-tolerant (CRLF + LF)\n * - skips comments (`:`-prefixed lines)\n *\n * Not implemented (we don't need them):\n * - `id:` / `retry:` fields\n * - reconnection / last-event-id\n */\n\nexport interface RawSseEvent {\n /** `event:` field value. Empty string when absent — matches the spec default. */\n event: string;\n /** Concatenated `data:` lines, joined by newlines. */\n data: string;\n}\n\nexport async function* parseSSE(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<RawSseEvent, void, void> {\n const reader = stream.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let currentEvent = '';\n let currentData = '';\n\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newlineIdx: number;\n while ((newlineIdx = indexOfNewline(buffer)) !== -1) {\n const rawLine = buffer.slice(0, newlineIdx);\n buffer = buffer.slice(newlineIdx + (buffer[newlineIdx] === '\\r' && buffer[newlineIdx + 1] === '\\n' ? 2 : 1));\n\n if (rawLine === '') {\n if (currentData !== '' || currentEvent !== '') {\n yield { event: currentEvent, data: currentData };\n currentEvent = '';\n currentData = '';\n }\n continue;\n }\n if (rawLine.startsWith(':')) continue;\n\n const colon = rawLine.indexOf(':');\n const field = colon === -1 ? rawLine : rawLine.slice(0, colon);\n const rawValue = colon === -1 ? '' : rawLine.slice(colon + 1);\n const value2 = rawValue.startsWith(' ') ? rawValue.slice(1) : rawValue;\n\n if (field === 'event') {\n currentEvent = value2;\n } else if (field === 'data') {\n currentData = currentData === '' ? value2 : `${currentData}\\n${value2}`;\n }\n }\n }\n if (currentData !== '' || currentEvent !== '') {\n yield { event: currentEvent, data: currentData };\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction indexOfNewline(s: string): number {\n for (let i = 0; i < s.length; i += 1) {\n const c = s[i];\n if (c === '\\n' || c === '\\r') return i;\n }\n return -1;\n}\n","/**\n * `AlmadarClient` — server / Node-side HTTP client targeting `/api/v1/agent/*`.\n * Authenticates with a team-bound API key (`sk_*`) issued from\n * Studio's `/settings/sdk` panel. See `docs/Almadar_Studio_SDK.md` §5.\n *\n * Never instantiate this in a browser bundle — `apiKey` must never leave\n * the customer's server.\n */\n\nimport { parseOrbitalSchema, type OrbitalSchema, type SSEEvent } from '@almadar/core';\nimport type {\n AlmadarClientOptions,\n ApiErrorBody,\n AsyncJobHandle,\n CompileOptions,\n CompileResult,\n EditSchemaPatch,\n GenerateOptions,\n GenerateResult,\n} from '../types';\nimport { errorFromBody, ServerError } from './errors';\nimport { parseSSE } from './sseParser';\n\nconst DEFAULT_BASE_URL = 'https://studio.almadar.io';\nconst POLL_BACKOFF_MS: readonly number[] = [1000, 2000, 5000, 10_000, 30_000];\n\ninterface JobStatus {\n state: 'pending' | 'complete' | 'error';\n events?: readonly SSEEvent[];\n result?: GenerateResult;\n errorCode?: number;\n errorMessage?: string;\n}\n\nexport class AlmadarClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: AlmadarClientOptions) {\n if (!opts.apiKey || typeof opts.apiKey !== 'string') {\n throw new Error('AlmadarClient: opts.apiKey is required');\n }\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n this.fetchImpl = opts.fetch ?? globalThis.fetch;\n if (typeof this.fetchImpl !== 'function') {\n throw new Error('AlmadarClient: no fetch available — pass opts.fetch for Node <18');\n }\n }\n\n async generate(input: GenerateOptions): Promise<GenerateResult> {\n if (input.async === true) {\n const handle = await this.requestJson<AsyncJobHandle>('POST', '/api/v1/agent/generate', {\n prompt: input.prompt,\n endUserId: input.endUserId,\n appId: input.appId,\n async: true,\n provider: input.provider,\n model: input.model,\n catalogMode: input.catalogMode,\n stdAllowList: input.stdAllowList,\n });\n assertString(handle.jobId, 'AsyncJobHandle.jobId');\n assertString(handle.statusUrl, 'AsyncJobHandle.statusUrl');\n return this.pollUntilComplete(handle, input.onEvent);\n }\n return this.streamGenerate(input);\n }\n\n async editSchema(appId: string, patch: EditSchemaPatch): Promise<OrbitalSchema> {\n if (!appId) throw new Error('AlmadarClient.editSchema: appId is required');\n const schema = await this.requestJson<OrbitalSchema>('PUT', '/api/v1/agent/edit-schema', {\n appId,\n patch,\n });\n assertString(schema.name, 'OrbitalSchema.name');\n return schema;\n }\n\n async compileToApp(schema: OrbitalSchema, opts?: CompileOptions): Promise<CompileResult> {\n const result = await this.requestJson<CompileResult>('POST', '/api/v1/agent/compile', {\n schema,\n target: opts?.target,\n shell: opts?.shell,\n });\n assertString(result.downloadUrl, 'CompileResult.downloadUrl');\n assertString(result.expiresAt, 'CompileResult.expiresAt');\n return result;\n }\n\n private async streamGenerate(input: GenerateOptions): Promise<GenerateResult> {\n const res = await this.fetchImpl(`${this.baseUrl}/api/v1/agent/generate`, {\n method: 'POST',\n headers: this.headers({ accept: 'text/event-stream', contentType: 'application/json' }, input.endUserId),\n body: JSON.stringify({\n prompt: input.prompt,\n endUserId: input.endUserId,\n appId: input.appId,\n provider: input.provider,\n model: input.model,\n catalogMode: input.catalogMode,\n stdAllowList: input.stdAllowList,\n }),\n });\n if (!res.ok) throw await this.errorFromResponse(res);\n if (res.body === null) throw new Error('AlmadarClient.generate: server returned no body');\n\n let final: GenerateResult | null = null;\n for await (const raw of parseSSE(res.body)) {\n const event = parseSseEvent(raw.data);\n if (event === null) continue;\n input.onEvent?.(event);\n if (event.type === 'complete') {\n if (event.data.schema === undefined) {\n throw new ServerError({ code: 500, message: '`complete` event did not contain a schema' });\n }\n const schema = parseOrbitalSchema(event.data.schema);\n final = { schema, appId: event.data.appId };\n } else if (event.type === 'error') {\n throw errorFromBody({ code: 500, message: event.data.error });\n }\n }\n if (final === null) {\n throw new ServerError({ code: 500, message: 'SSE stream ended without `complete` event' });\n }\n return final;\n }\n\n private async pollUntilComplete(\n handle: AsyncJobHandle,\n onEvent: GenerateOptions['onEvent'],\n ): Promise<GenerateResult> {\n let attempt = 0;\n for (;;) {\n const delay = POLL_BACKOFF_MS[Math.min(attempt, POLL_BACKOFF_MS.length - 1)];\n await sleep(delay);\n attempt += 1;\n const status = await this.requestJson<JobStatus>('GET', handle.statusUrl);\n assertString(status.state, 'JobStatus.state');\n if (status.events !== undefined && onEvent !== undefined) {\n for (const e of status.events) onEvent(e);\n }\n if (status.state === 'complete') {\n if (status.result === undefined) {\n throw new ServerError({ code: 500, message: 'Job complete but no result returned' });\n }\n return status.result;\n }\n if (status.state === 'error') {\n throw errorFromBody({\n code: status.errorCode ?? 500,\n message: status.errorMessage ?? 'Job failed',\n });\n }\n }\n }\n\n private async requestJson<T>(method: string, path: string, body?: object): Promise<T> {\n const isAbsolute = path.startsWith('http://') || path.startsWith('https://');\n const url = isAbsolute ? path : `${this.baseUrl}${path}`;\n const init: RequestInit = {\n method,\n headers: this.headers({\n accept: 'application/json',\n contentType: body !== undefined ? 'application/json' : undefined,\n }),\n };\n if (body !== undefined) init.body = JSON.stringify(body);\n const res = await this.fetchImpl(url, init);\n if (!res.ok) throw await this.errorFromResponse(res);\n const text = await res.text();\n if (text === '') {\n throw new ServerError({ code: 500, message: 'Empty response body' });\n }\n const parsed: T = JSON.parse(text);\n return parsed;\n }\n\n private headers(\n opts: { accept?: string; contentType?: string },\n endUserId?: string,\n ): Record<string, string> {\n const h: Record<string, string> = { authorization: `Bearer ${this.apiKey}` };\n if (opts.accept !== undefined) h['accept'] = opts.accept;\n if (opts.contentType !== undefined) h['content-type'] = opts.contentType;\n if (endUserId !== undefined && endUserId !== '') h['x-end-user-id'] = endUserId;\n return h;\n }\n\n private async errorFromResponse(res: Response): Promise<Error> {\n const text = await res.text();\n let body: ApiErrorBody;\n try {\n const parsed: ApiErrorBody | null = text === '' ? null : JSON.parse(text);\n body = parsed !== null && typeof parsed.code === 'number' && typeof parsed.message === 'string'\n ? parsed\n : {\n code: res.status,\n message: res.statusText !== '' ? res.statusText : 'HTTP error',\n };\n } catch {\n body = { code: res.status, message: text !== '' ? text : res.statusText };\n }\n const retryAfter = res.headers.get('retry-after');\n const err = errorFromBody(body);\n if (err.name === 'RateLimitedError' && retryAfter !== null) {\n const seconds = Number(retryAfter);\n if (Number.isFinite(seconds)) {\n Object.defineProperty(err, 'retryAfterSeconds', { value: seconds, enumerable: true });\n }\n }\n return err;\n }\n}\n\n/**\n * Parse one SSE `data:` line into the canonical `SSEEvent` union.\n * The server is the trusted emitter, so we validate only the envelope\n * (object with string `type` and numeric `timestamp`) and cast to the\n * discriminated union. Malformed lines are ignored.\n */\nfunction parseSseEvent(dataLine: string): SSEEvent | null {\n if (dataLine === '') return null;\n let payload;\n try {\n payload = JSON.parse(dataLine);\n } catch {\n return null;\n }\n if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) return null;\n if (typeof payload.type !== 'string' || typeof payload.timestamp !== 'number') return null;\n return payload as SSEEvent;\n}\n\nfunction assertString(v: string | undefined, name: string): asserts v is string {\n if (typeof v !== 'string' || v === '') {\n throw new ServerError({ code: 500, message: `Malformed server response: ${name} is not a string` });\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * `@almadar/sdk/server` — Framework-agnostic Web-standard Fetch handlers for\n * the Almadar agent proxy. Node-only; never import from browser or React code.\n *\n * Usage:\n * import { createGenerateHandler, createEditHandler } from '@almadar/sdk/server';\n * const handler = createGenerateHandler({ apiKey: process.env.ALMADAR_API_KEY! });\n * // handler: (request: Request) => Promise<Response>\n *\n * For framework adapters see `@almadar/sdk/server/express` and `@almadar/sdk/server/hono`.\n */\n\nimport type { OrbitalSchema } from '@almadar/core';\nimport { AlmadarClient } from '../client/AlmadarClient';\nimport type { EditSchemaRequest, EditSchemaPatch, GenerateRequest, SSEEvent } from '../types';\n\n// ============================================================================\n// Public option surface\n// ============================================================================\n\nexport interface GenerateHandlerOptions {\n /** API key issued from Studio's /settings/sdk panel. */\n apiKey: string;\n /** Defaults to https://studio.almadar.io. */\n baseUrl?: string;\n /**\n * Derive a stable end-user id from the incoming Web Request.\n * Falls back to the `x-user-id` request header when omitted.\n */\n endUserId?: (req: Request) => string;\n}\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nfunction resolveEndUserId(opts: GenerateHandlerOptions, req: Request): string | undefined {\n if (opts.endUserId) return opts.endUserId(req);\n const header = req.headers.get('x-user-id');\n return typeof header === 'string' && header.length > 0 ? header : undefined;\n}\n\nfunction encodeSseEvent(event: SSEEvent): string {\n return `data: ${JSON.stringify(event)}\\n\\n`;\n}\n\n// ============================================================================\n// createGenerateHandler\n// ============================================================================\n\n/**\n * Returns a Web-standard Fetch handler that streams a generate call as SSE.\n *\n * Body shape accepted: `{ prompt: string; endUserId?: string; appId?: string }`\n */\nexport function createGenerateHandler(\n opts: GenerateHandlerOptions,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n let body: GenerateRequest;\n try {\n body = (await request.json()) as GenerateRequest;\n } catch {\n return new Response(JSON.stringify({ error: 'invalid JSON body' }), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n });\n }\n\n const rawPrompt = body.prompt ?? body.message;\n const prompt = typeof rawPrompt === 'string' ? rawPrompt : '';\n\n if (!prompt) {\n return new Response(JSON.stringify({ error: 'prompt or message is required' }), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n });\n }\n\n const bodyEndUserId = typeof body.endUserId === 'string' ? body.endUserId : undefined;\n const endUserId = bodyEndUserId ?? resolveEndUserId(opts, request);\n const appId = typeof body.appId === 'string' ? body.appId : undefined;\n\n const client = new AlmadarClient({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const encoder = new TextEncoder();\n try {\n await client.generate({\n prompt,\n endUserId,\n appId,\n onEvent: (event: SSEEvent) => {\n controller.enqueue(encoder.encode(encodeSseEvent(event)));\n },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const errorEvent: SSEEvent = {\n type: 'error',\n timestamp: Date.now(),\n data: { error: message },\n };\n controller.enqueue(encoder.encode(encodeSseEvent(errorEvent)));\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n connection: 'keep-alive',\n },\n });\n };\n}\n\n// ============================================================================\n// createEditHandler\n// ============================================================================\n\n/**\n * Returns a Web-standard Fetch handler that calls `editSchema` and returns JSON.\n *\n * Body shape accepted: `{ appId: string; patch: EditSchemaPatch }`\n */\nexport function createEditHandler(\n opts: GenerateHandlerOptions,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n let body: EditSchemaRequest;\n try {\n body = (await request.json()) as EditSchemaRequest;\n } catch {\n return new Response(JSON.stringify({ error: 'invalid JSON body' }), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n });\n }\n\n const appId = typeof body.appId === 'string' ? body.appId : '';\n if (!appId) {\n return new Response(JSON.stringify({ error: 'appId is required' }), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n });\n }\n\n const patch: EditSchemaPatch | undefined = body.patch;\n if (patch === undefined || patch === null || typeof patch !== 'object') {\n return new Response(JSON.stringify({ error: 'patch is required' }), {\n status: 400,\n headers: { 'content-type': 'application/json' },\n });\n }\n\n const client = new AlmadarClient({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });\n\n try {\n const schema: OrbitalSchema = await client.editSchema(appId, patch);\n return new Response(JSON.stringify(schema), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: { 'content-type': 'application/json' },\n });\n }\n };\n}\n","/**\n * `@almadar/sdk/server/express` — Express adapter for the Almadar server handlers.\n *\n * Node-only. The consumer must provide their own `express` installation.\n * This module imports express TYPES only; it is never bundled with express itself.\n *\n * Usage:\n * import { createGenerateHandler, createEditHandler } from '@almadar/sdk/server/express';\n * app.post('/api/agent/generate', createGenerateHandler({ apiKey }));\n * app.put('/api/agent/edit', createEditHandler({ apiKey }));\n */\n\nimport type { Request as ExpressRequest, Response as ExpressResponse, RequestHandler } from 'express';\nimport {\n createGenerateHandler as coreGenerateHandler,\n createEditHandler as coreEditHandler,\n} from './index';\n\n// ============================================================================\n// Express-specific option surface\n// ============================================================================\n\nexport interface GenerateHandlerOptions {\n /** API key issued from Studio's /settings/sdk panel. */\n apiKey: string;\n /** Defaults to https://studio.almadar.io. */\n baseUrl?: string;\n /**\n * Derive a stable end-user id from the Express request.\n * Falls back to the `x-user-id` request header when omitted.\n */\n endUserId?: (req: ExpressRequest) => string;\n}\n\n// ============================================================================\n// Express↔Fetch bridge helpers\n// ============================================================================\n\n/**\n * Convert an Express `Request` to a Web-standard `Request`.\n * Re-serialises the already-parsed body so the core handler's `request.json()` succeeds.\n */\nfunction expressReqToWebRequest(req: ExpressRequest): Request {\n const protocol = req.protocol;\n const host = req.get('host') ?? 'localhost';\n const url = `${protocol}://${host}${req.originalUrl}`;\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (typeof value === 'string') {\n headers.set(key, value);\n } else if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n }\n }\n const bodyJson = JSON.stringify(req.body);\n return new Request(url, { method: req.method, headers, body: bodyJson });\n}\n\n/**\n * Write a Web-standard `Response` back to an express `Response`.\n * Streams the body chunk-by-chunk so SSE works without buffering.\n */\nasync function pipeWebResponseToExpress(\n webRes: Response,\n res: ExpressResponse,\n): Promise<void> {\n res.status(webRes.status);\n webRes.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n if (webRes.body === null) {\n res.end();\n return;\n }\n const reader = webRes.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n } finally {\n reader.releaseLock();\n res.end();\n }\n}\n\n// ============================================================================\n// Exported factories\n// ============================================================================\n\n/**\n * Returns an Express `RequestHandler` that streams a generate call as SSE.\n *\n * Body shape accepted: `{ prompt: string; endUserId?: string; appId?: string }`\n */\nexport function createGenerateHandler(opts: GenerateHandlerOptions): RequestHandler {\n const coreHandler = coreGenerateHandler({\n apiKey: opts.apiKey,\n baseUrl: opts.baseUrl,\n endUserId: opts.endUserId\n ? (webReq: Request) => {\n // The x-user-id header is available on the Web Request; express opts.endUserId\n // receives the original express req via closure — pass the header value as a\n // synthetic express request shaped enough for the callback.\n const userId = webReq.headers.get('x-user-id');\n return userId ?? '';\n }\n : undefined,\n });\n return async (req: ExpressRequest, res: ExpressResponse): Promise<void> => {\n if (opts.endUserId) {\n const userId = opts.endUserId(req);\n if (userId) req.headers['x-user-id'] = userId;\n }\n const webReq = expressReqToWebRequest(req);\n const webRes = await coreHandler(webReq);\n await pipeWebResponseToExpress(webRes, res);\n };\n}\n\n/**\n * Returns an Express `RequestHandler` that calls `editSchema` and returns JSON.\n *\n * Body shape accepted: `{ appId: string; patch: EditSchemaPatch }`\n */\nexport function createEditHandler(opts: GenerateHandlerOptions): RequestHandler {\n const coreHandler = coreEditHandler({ apiKey: opts.apiKey, baseUrl: opts.baseUrl });\n return async (req: ExpressRequest, res: ExpressResponse): Promise<void> => {\n const webReq = expressReqToWebRequest(req);\n const webRes = await coreHandler(webReq);\n await pipeWebResponseToExpress(webRes, res);\n };\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Handler } from 'hono';
|
|
2
|
+
import { GenerateHandlerOptions } from './index.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@almadar/sdk/server/hono` — Hono adapter for the Almadar server handlers.
|
|
6
|
+
*
|
|
7
|
+
* Hono is Fetch-native, so this is a near-passthrough: each factory wraps the
|
|
8
|
+
* core Web-standard handler in a Hono-compatible `Handler`.
|
|
9
|
+
*
|
|
10
|
+
* Node-only. The consumer must provide their own `hono` installation.
|
|
11
|
+
*
|
|
12
|
+
* Usage:
|
|
13
|
+
* import { Hono } from 'hono';
|
|
14
|
+
* import { createGenerateHandler, createEditHandler } from '@almadar/sdk/server/hono';
|
|
15
|
+
* const app = new Hono();
|
|
16
|
+
* app.post('/api/agent/generate', createGenerateHandler({ apiKey }));
|
|
17
|
+
* app.put('/api/agent/edit', createEditHandler({ apiKey }));
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Returns a Hono `Handler` that streams a generate call as SSE.
|
|
22
|
+
*
|
|
23
|
+
* Body shape accepted: `{ prompt: string; endUserId?: string; appId?: string }`
|
|
24
|
+
*/
|
|
25
|
+
declare function createGenerateHandler(opts: GenerateHandlerOptions): Handler;
|
|
26
|
+
/**
|
|
27
|
+
* Returns a Hono `Handler` that calls `editSchema` and returns JSON.
|
|
28
|
+
*
|
|
29
|
+
* Body shape accepted: `{ appId: string; patch: EditSchemaPatch }`
|
|
30
|
+
*/
|
|
31
|
+
declare function createEditHandler(opts: GenerateHandlerOptions): Handler;
|
|
32
|
+
|
|
33
|
+
export { GenerateHandlerOptions, createEditHandler, createGenerateHandler };
|