@seclai/handlers 0.0.1 → 0.0.3

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/index.cjs CHANGED
@@ -22,7 +22,8 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  DEFAULT_API_VERSION: () => DEFAULT_API_VERSION,
24
24
  MIN_API_VERSION: () => MIN_API_VERSION,
25
- createSeclaiHandlers: () => createSeclaiHandlers
25
+ createSeclaiHandlers: () => createSeclaiHandlers,
26
+ deny: () => deny
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
28
29
 
@@ -109,52 +110,296 @@ data: ${JSON.stringify(data)}
109
110
 
110
111
  `);
111
112
  }
112
- function relayRunEvents(first, events, abort) {
113
+ var OBSERVER_ERROR_MESSAGE = "The server could not process the run.";
114
+ function relayRunEvents(first, events, abort, observer, options = {}) {
115
+ const keepReading = !!options.keepReadingAfterDisconnect && !!observer;
116
+ let pending = first;
113
117
  let closed = false;
118
+ let cancelled = false;
119
+ let closeReport;
120
+ let inflight;
114
121
  let keepalive;
122
+ let ctrl;
123
+ let draining = false;
124
+ let pulling;
115
125
  const finish = () => {
116
126
  closed = true;
117
127
  clearInterval(keepalive);
118
128
  };
119
- return new ReadableStream({
120
- start(controller) {
121
- if (!first) {
122
- finish();
123
- controller.close();
129
+ const stopUpstream = () => {
130
+ abort();
131
+ void events.return().catch(() => {
132
+ });
133
+ };
134
+ const call = async (hook) => {
135
+ try {
136
+ await hook();
137
+ return true;
138
+ } catch (err) {
139
+ try {
140
+ observer?.onError(err);
141
+ } catch {
142
+ }
143
+ return false;
144
+ }
145
+ };
146
+ const reportClose = (reason) => {
147
+ if (!observer) return Promise.resolve(true);
148
+ return closeReport ??= call(() => observer.onClose(reason));
149
+ };
150
+ const end = (controller, last) => {
151
+ if (cancelled) return;
152
+ if (last) controller.enqueue(last);
153
+ controller.close();
154
+ };
155
+ const fail = async (controller) => {
156
+ finish();
157
+ stopUpstream();
158
+ await reportClose("error");
159
+ end(controller, frame("error", { error: OBSERVER_ERROR_MESSAGE }));
160
+ };
161
+ const relay = (controller, event, source = "upstream") => {
162
+ const work = (async () => {
163
+ if (observer && !await call(() => observer.onEvent(event, source))) {
164
+ if (!closed) await fail(controller);
124
165
  return;
125
166
  }
126
- controller.enqueue(frame(first.event, first.data));
127
- keepalive = setInterval(() => {
128
- if (!closed) controller.enqueue(encoder.encode(": keepalive\n\n"));
129
- }, KEEPALIVE_INTERVAL_MS);
130
- },
131
- async pull(controller) {
167
+ if (closed || cancelled) return;
168
+ controller.enqueue(frame(event.event, event.data));
169
+ })();
170
+ inflight = work;
171
+ return work;
172
+ };
173
+ const pullOnce = async (controller) => {
174
+ if (pending) {
175
+ const event = pending;
176
+ pending = void 0;
177
+ await relay(controller, event);
178
+ return;
179
+ }
180
+ let next;
181
+ try {
182
+ next = await events.next();
183
+ } catch (err) {
184
+ if (closed) return;
185
+ await relay(
186
+ controller,
187
+ { event: "error", data: { error: streamErrorMessage(err) } },
188
+ "connection-lost"
189
+ );
132
190
  if (closed) return;
191
+ finish();
192
+ await reportClose("end");
193
+ end(controller);
194
+ return;
195
+ }
196
+ if (closed) return;
197
+ if (next.done) {
198
+ finish();
199
+ const ok = await reportClose("end");
200
+ end(controller, ok ? void 0 : frame("error", { error: OBSERVER_ERROR_MESSAGE }));
201
+ return;
202
+ }
203
+ await relay(controller, next.value);
204
+ };
205
+ const drain = async (controller) => {
206
+ await pulling;
207
+ await inflight;
208
+ if (closed) return;
209
+ if (pending) {
210
+ const event = pending;
211
+ pending = void 0;
212
+ await relay(controller, event);
213
+ }
214
+ while (!closed) {
215
+ let next;
133
216
  try {
134
- const next = await events.next();
135
- if (closed) return;
136
- if (next.done) {
137
- finish();
138
- controller.close();
139
- return;
140
- }
141
- controller.enqueue(frame(next.value.event, next.value.data));
217
+ next = await events.next();
142
218
  } catch (err) {
219
+ if (closed) return;
220
+ await relay(
221
+ controller,
222
+ { event: "error", data: { error: streamErrorMessage(err) } },
223
+ "connection-lost"
224
+ );
143
225
  if (closed) return;
144
226
  finish();
145
- controller.enqueue(frame("error", { error: streamErrorMessage(err) }));
227
+ await reportClose("end");
228
+ return;
229
+ }
230
+ if (closed) return;
231
+ if (next.done) {
232
+ finish();
233
+ await reportClose("end");
234
+ return;
235
+ }
236
+ await relay(controller, next.value);
237
+ }
238
+ };
239
+ const startDrain = (fromCancel) => {
240
+ if (draining || closed || !ctrl) return;
241
+ draining = true;
242
+ cancelled = true;
243
+ clearInterval(keepalive);
244
+ const controller = ctrl;
245
+ if (!fromCancel) {
246
+ try {
146
247
  controller.close();
248
+ } catch {
249
+ }
250
+ }
251
+ try {
252
+ observer?.onDisconnect?.();
253
+ } catch {
254
+ }
255
+ void drain(controller).catch((err) => {
256
+ try {
257
+ observer?.onError(err);
258
+ } catch {
259
+ }
260
+ });
261
+ };
262
+ return new ReadableStream({
263
+ start(controller) {
264
+ ctrl = controller;
265
+ keepalive = setInterval(() => {
266
+ if (!closed && !cancelled) controller.enqueue(encoder.encode(": keepalive\n\n"));
267
+ }, KEEPALIVE_INTERVAL_MS);
268
+ if (keepReading && options.signal) {
269
+ const { signal } = options;
270
+ const onAbort = () => startDrain(false);
271
+ if (signal.aborted) queueMicrotask(onAbort);
272
+ else signal.addEventListener("abort", onAbort, { once: true });
147
273
  }
148
274
  },
149
- cancel() {
275
+ pull(controller) {
276
+ if (closed || draining) return;
277
+ const work = pullOnce(controller);
278
+ pulling = work;
279
+ return work;
280
+ },
281
+ async cancel() {
282
+ if (keepReading) {
283
+ startDrain(true);
284
+ return;
285
+ }
286
+ cancelled = true;
150
287
  finish();
151
- abort();
152
- void events.return().catch(() => {
153
- });
288
+ stopUpstream();
289
+ const unrelayed = pending;
290
+ pending = void 0;
291
+ if (unrelayed && observer?.onUnrelayed) {
292
+ await call(() => observer.onUnrelayed(unrelayed));
293
+ }
294
+ await inflight;
295
+ await reportClose("cancel");
154
296
  }
155
297
  });
156
298
  }
157
299
 
300
+ // src/run-callbacks.ts
301
+ var NO_RESULT_MESSAGE = "The stream ended without a result.";
302
+ var TIMEOUT_MESSAGE = "Stopped waiting for the run. It may still finish on Seclai.";
303
+ var FAILED_MESSAGE = "The run failed.";
304
+ function lastAttemptError(run) {
305
+ if (!Array.isArray(run.attempts)) return null;
306
+ for (let i = run.attempts.length - 1; i >= 0; i--) {
307
+ const error = run.attempts[i]?.error;
308
+ if (typeof error === "string" && error) return error;
309
+ }
310
+ return null;
311
+ }
312
+ function toAttachments(raw) {
313
+ if (!Array.isArray(raw)) return [];
314
+ return raw.flatMap(
315
+ (item) => typeof item?.id === "string" ? [
316
+ {
317
+ id: item.id,
318
+ name: typeof item.name === "string" ? item.name : null,
319
+ mime: typeof item.mime === "string" ? item.mime : "application/octet-stream"
320
+ }
321
+ ] : []
322
+ );
323
+ }
324
+ function createRunObserver(callbacks, ctx, { keepReading = false } = {}) {
325
+ const { onEvent, onRunEnd } = callbacks;
326
+ const browserStoppedUpstream = () => !keepReading && !!ctx.request.signal?.aborted;
327
+ let runId = null;
328
+ let text = "";
329
+ let terminal;
330
+ let ended = false;
331
+ const outcome = (o) => ({
332
+ runId,
333
+ attachments: [],
334
+ ...o
335
+ });
336
+ const end = async (o) => {
337
+ if (ended) return;
338
+ ended = true;
339
+ await onRunEnd?.(o, ctx);
340
+ };
341
+ const failed = (error) => outcome({ status: "failed", output: text, error });
342
+ const cancelled = () => outcome({ status: "cancelled", output: text, error: null });
343
+ const record = (event, source) => {
344
+ const payload = typeof event.data === "object" && event.data !== null ? event.data : {};
345
+ if (typeof payload.run_id === "string" && runId === null) runId = payload.run_id;
346
+ if (terminal) return;
347
+ switch (event.event) {
348
+ case "stream_token":
349
+ if (typeof payload.token === "string") text += payload.token;
350
+ return;
351
+ case "done": {
352
+ const run = payload;
353
+ if (typeof run.run_id === "string") runId = run.run_id;
354
+ const attachments = toAttachments(run.attachments);
355
+ terminal = run.status === "failed" ? outcome({
356
+ status: "failed",
357
+ output: text,
358
+ attachments,
359
+ error: lastAttemptError(run) ?? FAILED_MESSAGE
360
+ }) : outcome({
361
+ status: "completed",
362
+ // Agents with no streaming step send no tokens, so `output`
363
+ // may be the only text.
364
+ output: typeof run.output === "string" && run.output || text,
365
+ attachments,
366
+ error: null
367
+ });
368
+ return;
369
+ }
370
+ case "error":
371
+ terminal = source === "connection-lost" && browserStoppedUpstream() ? cancelled() : failed(typeof payload.error === "string" && payload.error ? payload.error : FAILED_MESSAGE);
372
+ return;
373
+ case "timeout":
374
+ terminal = failed(TIMEOUT_MESSAGE);
375
+ return;
376
+ }
377
+ };
378
+ return {
379
+ async onEvent(event, source) {
380
+ record(event, source);
381
+ await onEvent?.(event, ctx);
382
+ if (terminal) await end(terminal);
383
+ },
384
+ onUnrelayed(event) {
385
+ record(event, "upstream");
386
+ },
387
+ async onClose(reason) {
388
+ switch (reason) {
389
+ case "end":
390
+ return end(terminal ?? (browserStoppedUpstream() ? cancelled() : failed(NO_RESULT_MESSAGE)));
391
+ case "error":
392
+ return end(failed(OBSERVER_ERROR_MESSAGE));
393
+ case "cancel":
394
+ return end(terminal ?? cancelled());
395
+ }
396
+ },
397
+ onError(err) {
398
+ console.error("@seclai/handlers: an onEvent or onRunEnd callback threw.", err);
399
+ }
400
+ };
401
+ }
402
+
158
403
  // src/handlers.ts
159
404
  var MIN_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_16;
160
405
  var DEFAULT_API_VERSION = import_sdk2.SeclaiApiVersion.V2026_10_28;
@@ -171,6 +416,10 @@ var ROUTES = {
171
416
  function wrongMethod(allow) {
172
417
  return jsonError(405, "Method not allowed.", { allow });
173
418
  }
419
+ var NOT_AUTHORIZED = "Could not authorize this request.";
420
+ function deny(status, message, headers) {
421
+ return jsonError(status, message, headers);
422
+ }
174
423
  function parseRunBody(body) {
175
424
  if (typeof body !== "object" || body === null || Array.isArray(body)) {
176
425
  return "The request body must be a JSON object.";
@@ -195,7 +444,14 @@ function createSeclaiHandlers(options) {
195
444
  apiKey,
196
445
  agentId,
197
446
  apiVersion = DEFAULT_API_VERSION,
198
- runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS
447
+ runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
448
+ keepReadingAfterDisconnect = false,
449
+ onEvent,
450
+ onRunEnd,
451
+ context,
452
+ authorizeRun,
453
+ authorizeUpload,
454
+ authorizeDownload
199
455
  } = options;
200
456
  if (!apiKey) throw new Error("createSeclaiHandlers: `apiKey` is required.");
201
457
  if (!agentId) throw new Error("createSeclaiHandlers: `agentId` is required.");
@@ -211,128 +467,212 @@ function createSeclaiHandlers(options) {
211
467
  // when called with any `this` but the global, so it can't be passed bare.
212
468
  fetch: (input, init) => globalThis.fetch(input, init)
213
469
  });
214
- const handlers = {
215
- async attachmentReferences(req) {
216
- if (req.method !== "GET") return wrongMethod("GET");
217
- try {
218
- return json(await client.getAgentAttachmentReferences(agentId));
219
- } catch (err) {
220
- return toErrorResponse(err);
221
- }
222
- },
223
- async upload(req) {
224
- if (req.method !== "POST") return wrongMethod("POST");
225
- let form;
226
- try {
227
- form = await req.formData();
228
- } catch {
229
- return jsonError(400, "The request body must be multipart form data.");
230
- }
231
- const file = form.get("file");
232
- if (file === null || typeof file === "string") {
233
- return jsonError(400, "The form must include a `file` field holding a file.");
234
- }
235
- try {
236
- const upload = await client.uploadAgentInput(agentId, {
237
- file,
238
- fileName: file.name,
239
- mimeType: file.type || void 0
240
- });
241
- return json({
242
- id: upload.id,
243
- status: upload.status,
244
- filename: upload.filename,
245
- content_type: upload.content_type,
246
- file_size: upload.file_size
247
- });
248
- } catch (err) {
249
- return toErrorResponse(err);
250
- }
251
- },
252
- async run(req) {
253
- if (req.method !== "POST") return wrongMethod("POST");
254
- let raw;
255
- try {
256
- raw = await req.json();
257
- } catch {
258
- return jsonError(400, "The request body must be JSON.");
259
- }
260
- const body = parseRunBody(raw);
261
- if (typeof body === "string") return jsonError(400, body);
262
- const upstream = new AbortController();
263
- const abort = () => upstream.abort();
264
- req.signal?.addEventListener("abort", abort, { once: true });
265
- const events = client.runStreamingAgent(
266
- agentId,
267
- {
268
- ...body.input ? { input: body.input } : {},
269
- ...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
270
- ...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
271
- },
272
- { timeoutMs: runTimeoutMs, signal: upstream.signal }
273
- );
274
- try {
275
- const first = await events.next();
276
- return new Response(
277
- relayRunEvents(first.done ? void 0 : first.value, events, abort),
278
- { headers: SSE_HEADERS }
470
+ let warnedDownloadResult = false;
471
+ async function callHook(name, req, resolveCtx, hook) {
472
+ let ctx;
473
+ try {
474
+ ctx = await resolveCtx(req);
475
+ return { value: await hook(ctx) };
476
+ } catch (err) {
477
+ if (err instanceof Response) return { response: err };
478
+ const hint = ctx === void 0 && err instanceof TypeError ? " No context was passed: set the `context` option, or call `withContext(ctx)`." : "";
479
+ console.error(`[seclai] ${name} threw, so the request got a 500.${hint}`, err);
480
+ return { response: jsonError(500, NOT_AUTHORIZED) };
481
+ }
482
+ }
483
+ const build = (resolveCtx) => {
484
+ const handlers = {
485
+ async attachmentReferences(req) {
486
+ if (req.method !== "GET") return wrongMethod("GET");
487
+ try {
488
+ return json(await client.getAgentAttachmentReferences(agentId));
489
+ } catch (err) {
490
+ return toErrorResponse(err);
491
+ }
492
+ },
493
+ async upload(req) {
494
+ if (req.method !== "POST") return wrongMethod("POST");
495
+ let form;
496
+ try {
497
+ form = await req.formData();
498
+ } catch {
499
+ return jsonError(400, "The request body must be multipart form data.");
500
+ }
501
+ const file = form.get("file");
502
+ if (file === null || typeof file === "string") {
503
+ return jsonError(400, "The form must include a `file` field holding a file.");
504
+ }
505
+ if (authorizeUpload) {
506
+ const result = await callHook(
507
+ "authorizeUpload",
508
+ req,
509
+ resolveCtx,
510
+ (ctx) => authorizeUpload(req, file, ctx)
511
+ );
512
+ if ("response" in result) return result.response;
513
+ const allowed = result.value;
514
+ if (allowed instanceof Response) return allowed;
515
+ if (allowed === false) return jsonError(403, "This upload isn't allowed.");
516
+ if (allowed !== void 0 && allowed !== true) {
517
+ console.error("[seclai] authorizeUpload returned something other than true, false, nothing or a Response, so the request got a 500.", allowed);
518
+ return jsonError(500, NOT_AUTHORIZED);
519
+ }
520
+ }
521
+ try {
522
+ const upload = await client.uploadAgentInput(agentId, {
523
+ file,
524
+ fileName: file.name,
525
+ mimeType: file.type || void 0
526
+ });
527
+ return json({
528
+ id: upload.id,
529
+ status: upload.status,
530
+ filename: upload.filename,
531
+ content_type: upload.content_type,
532
+ file_size: upload.file_size
533
+ });
534
+ } catch (err) {
535
+ return toErrorResponse(err);
536
+ }
537
+ },
538
+ async run(req) {
539
+ if (req.method !== "POST") return wrongMethod("POST");
540
+ let raw;
541
+ try {
542
+ raw = await req.json();
543
+ } catch {
544
+ return jsonError(400, "The request body must be JSON.");
545
+ }
546
+ const parsed = parseRunBody(raw);
547
+ if (typeof parsed === "string") return jsonError(400, parsed);
548
+ let body = parsed;
549
+ if (authorizeRun) {
550
+ const result = await callHook(
551
+ "authorizeRun",
552
+ req,
553
+ resolveCtx,
554
+ (ctx) => authorizeRun(req, parsed, ctx)
555
+ );
556
+ if ("response" in result) return result.response;
557
+ const verdict = result.value;
558
+ if (verdict instanceof Response) return verdict;
559
+ if (verdict === false) return jsonError(403, "This request isn't allowed.");
560
+ const kept = verdict === void 0 || verdict === true;
561
+ const rewritten = parseRunBody(kept ? parsed : verdict);
562
+ if (typeof rewritten === "string") {
563
+ console.error(
564
+ kept ? `[seclai] authorizeRun changed the body in place to one that isn't valid, so the request got a 500: ${rewritten}` : `[seclai] authorizeRun returned a body that isn't valid, so the request got a 500: ${rewritten}`
565
+ );
566
+ return jsonError(500, NOT_AUTHORIZED);
567
+ }
568
+ body = rewritten;
569
+ }
570
+ const upstream = new AbortController();
571
+ const abort = () => upstream.abort();
572
+ const keepReading = keepReadingAfterDisconnect && !!(onEvent || onRunEnd);
573
+ if (!keepReading) req.signal?.addEventListener("abort", abort, { once: true });
574
+ const events = client.runStreamingAgent(
575
+ agentId,
576
+ {
577
+ ...body.input ? { input: body.input } : {},
578
+ ...body.uploadIds?.length ? { input_upload_ids: body.uploadIds } : {},
579
+ ...body.sessionId ? { metadata: { session_id: body.sessionId } } : {}
580
+ },
581
+ { timeoutMs: runTimeoutMs, signal: upstream.signal }
279
582
  );
280
- } catch (err) {
281
- return toErrorResponse(err);
282
- }
283
- },
284
- async download(req) {
285
- if (req.method !== "GET") return wrongMethod("GET");
286
- const params = new URL(req.url).searchParams;
287
- const runId = params.get("runId") ?? "";
288
- const attachmentId = params.get("attachmentId") ?? "";
289
- const name = params.get("name") ?? void 0;
290
- if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
291
- if (!ATTACHMENT_ID.test(attachmentId)) {
292
- return jsonError(400, "`attachmentId` is not valid.");
293
- }
294
- if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
295
- return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
296
- }
297
- try {
298
- const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
299
- ...name ? { downloadName: name } : {},
300
- signal: req.signal
301
- });
302
- const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
303
- const headers = new Headers({
304
- "content-type": contentType,
305
- "cache-control": "private, no-store",
306
- "x-content-type-options": "nosniff"
307
- });
308
- const disposition = upstream.headers.get("content-disposition");
309
- if (disposition) headers.set("content-disposition", disposition);
310
- const length = upstream.headers.get("content-length");
311
- if (length && !upstream.headers.has("content-encoding")) {
312
- headers.set("content-length", length);
583
+ try {
584
+ const first = await events.next();
585
+ const observer = onEvent || onRunEnd ? createRunObserver({ onEvent, onRunEnd }, { body, request: req }, { keepReading }) : void 0;
586
+ return new Response(
587
+ relayRunEvents(
588
+ first.done ? void 0 : first.value,
589
+ events,
590
+ abort,
591
+ observer,
592
+ keepReading ? { keepReadingAfterDisconnect: true, signal: req.signal } : void 0
593
+ ),
594
+ { headers: SSE_HEADERS }
595
+ );
596
+ } catch (err) {
597
+ return toErrorResponse(err);
313
598
  }
314
- if (!contentType.toLowerCase().startsWith("application/pdf")) {
315
- headers.set("content-security-policy", "sandbox; default-src 'none'");
599
+ },
600
+ async download(req) {
601
+ if (req.method !== "GET") return wrongMethod("GET");
602
+ const params = new URL(req.url).searchParams;
603
+ const runId = params.get("runId") ?? "";
604
+ const attachmentId = params.get("attachmentId") ?? "";
605
+ const name = params.get("name") ?? void 0;
606
+ if (!UUID.test(runId)) return jsonError(400, "`runId` must be a UUID.");
607
+ if (!ATTACHMENT_ID.test(attachmentId)) {
608
+ return jsonError(400, "`attachmentId` is not valid.");
609
+ }
610
+ if (name !== void 0 && name.length > MAX_DOWNLOAD_NAME_LENGTH) {
611
+ return jsonError(400, `\`name\` must be ${MAX_DOWNLOAD_NAME_LENGTH} characters or fewer.`);
612
+ }
613
+ if (authorizeDownload) {
614
+ const result = await callHook(
615
+ "authorizeDownload",
616
+ req,
617
+ resolveCtx,
618
+ (ctx) => authorizeDownload(req, { runId, attachmentId }, ctx)
619
+ );
620
+ if ("response" in result) return result.response;
621
+ const allowed = result.value;
622
+ if (allowed instanceof Response) return allowed;
623
+ if (allowed !== true && allowed !== false && !warnedDownloadResult) {
624
+ warnedDownloadResult = true;
625
+ console.warn(
626
+ `[seclai] authorizeDownload returned ${String(allowed)}, not true or false, so the download was refused with a 404. Return true to serve the file.`
627
+ );
628
+ }
629
+ if (allowed !== true) return jsonError(404, "Not found.");
630
+ }
631
+ try {
632
+ const upstream = await client.downloadAgentRunAttachment(runId, attachmentId, {
633
+ ...name ? { downloadName: name } : {},
634
+ signal: req.signal
635
+ });
636
+ const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
637
+ const headers = new Headers({
638
+ "content-type": contentType,
639
+ "cache-control": "private, no-store",
640
+ "x-content-type-options": "nosniff"
641
+ });
642
+ const disposition = upstream.headers.get("content-disposition");
643
+ if (disposition) headers.set("content-disposition", disposition);
644
+ const length = upstream.headers.get("content-length");
645
+ if (length && !upstream.headers.has("content-encoding")) {
646
+ headers.set("content-length", length);
647
+ }
648
+ if (!contentType.toLowerCase().startsWith("application/pdf")) {
649
+ headers.set("content-security-policy", "sandbox; default-src 'none'");
650
+ }
651
+ return new Response(upstream.body, { status: upstream.status, headers });
652
+ } catch (err) {
653
+ return toErrorResponse(err);
316
654
  }
317
- return new Response(upstream.body, { status: upstream.status, headers });
318
- } catch (err) {
319
- return toErrorResponse(err);
320
655
  }
321
- }
322
- };
323
- return {
324
- ...handlers,
325
- async handle(req) {
326
- const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
327
- const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
328
- if (!name) return jsonError(404, "Not found.");
329
- return handlers[name](req);
330
- }
656
+ };
657
+ return {
658
+ ...handlers,
659
+ async handle(req) {
660
+ const segment = new URL(req.url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
661
+ const name = Object.hasOwn(ROUTES, segment) ? ROUTES[segment] : void 0;
662
+ if (!name) return jsonError(404, "Not found.");
663
+ return handlers[name](req);
664
+ }
665
+ };
331
666
  };
667
+ const unbound = build(
668
+ context ? async (req) => context(req) : async () => void 0
669
+ );
670
+ return { ...unbound, withContext: (ctx) => build(async () => ctx) };
332
671
  }
333
672
  // Annotate the CommonJS export names for ESM import in node:
334
673
  0 && (module.exports = {
335
674
  DEFAULT_API_VERSION,
336
675
  MIN_API_VERSION,
337
- createSeclaiHandlers
676
+ createSeclaiHandlers,
677
+ deny
338
678
  });