@tonyclaw/llm-inspector 1.6.3 → 1.7.1

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.
@@ -6,7 +6,7 @@ import require$$2 from "events";
6
6
  import { r as requireSafeBuffer } from "./safe-buffer.mjs";
7
7
  import { r as requireUtil } from "./core-util-is.mjs";
8
8
  import { r as requireInherits } from "./inherits.mjs";
9
- import require$$1 from "util";
9
+ import require$$0$1 from "util";
10
10
  import { r as requireNode } from "./util-deprecate.mjs";
11
11
  import require$$11 from "node:string_decoder";
12
12
  var readable = { exports: {} };
@@ -30,7 +30,7 @@ function requireBufferList() {
30
30
  }
31
31
  }
32
32
  var Buffer = requireSafeBuffer().Buffer;
33
- var util = require$$1;
33
+ var util = require$$0$1;
34
34
  function copyBuffer(src, target, offset) {
35
35
  src.copy(target, offset);
36
36
  }
@@ -707,7 +707,7 @@ function require_stream_readable() {
707
707
  }
708
708
  var util = Object.create(/* @__PURE__ */ requireUtil());
709
709
  util.inherits = /* @__PURE__ */ requireInherits();
710
- var debugUtil = require$$1;
710
+ var debugUtil = require$$0$1;
711
711
  var debug = void 0;
712
712
  if (debugUtil && debugUtil.debuglog) {
713
713
  debug = debugUtil.debuglog("stream");
@@ -1,3 +1,7 @@
1
+ import nodeHTTP from "node:http";
2
+ import { Readable, PassThrough } from "node:stream";
3
+ import nodeHTTPS from "node:https";
4
+ import nodeHTTP2 from "node:http2";
1
5
  function lazyInherit(target, source, sourceKey) {
2
6
  for (const key of [...Object.getOwnPropertyNames(source), ...Object.getOwnPropertySymbols(source)]) {
3
7
  if (key === "constructor") continue;
@@ -211,6 +215,18 @@ function callMiddleware(request, fetchHandler, middleware, index) {
211
215
  if (index === middleware.length) return fetchHandler(request);
212
216
  return middleware[index](request, () => callMiddleware(request, fetchHandler, middleware, index + 1));
213
217
  }
218
+ const errorPlugin = (server) => {
219
+ const errorHandler = server.options.error;
220
+ if (!errorHandler) return;
221
+ server.options.middleware.unshift((_req, next) => {
222
+ try {
223
+ const res = next();
224
+ return res instanceof Promise ? res.catch((error) => errorHandler(error)) : res;
225
+ } catch (error) {
226
+ return errorHandler(error);
227
+ }
228
+ });
229
+ };
214
230
  const gracefulShutdownPlugin = (server) => {
215
231
  const config = server.options?.gracefulShutdown;
216
232
  if (!globalThis.process?.on || config === false || config === void 0 && (process.env.CI || process.env.TEST)) return;
@@ -245,17 +261,388 @@ const gracefulShutdownPlugin = (server) => {
245
261
  };
246
262
  for (const sig of ["SIGINT", "SIGTERM"]) globalThis.process.on(sig, shutdown);
247
263
  };
248
- const FastResponse = Response;
264
+ async function sendNodeResponse(nodeRes, webRes) {
265
+ if (!webRes) {
266
+ nodeRes.statusCode = 500;
267
+ return endNodeResponse(nodeRes);
268
+ }
269
+ if (webRes._toNodeResponse) {
270
+ const res = webRes._toNodeResponse();
271
+ writeHead(nodeRes, res.status, res.statusText, res.headers);
272
+ if (res.body) {
273
+ if (res.body instanceof ReadableStream) return streamBody(res.body, nodeRes);
274
+ else if (typeof res.body?.pipe === "function") {
275
+ res.body.pipe(nodeRes);
276
+ return new Promise((resolve) => nodeRes.on("close", resolve));
277
+ }
278
+ nodeRes.write(res.body);
279
+ }
280
+ return endNodeResponse(nodeRes);
281
+ }
282
+ const rawHeaders = [...webRes.headers];
283
+ writeHead(nodeRes, webRes.status, webRes.statusText, rawHeaders);
284
+ return webRes.body ? streamBody(webRes.body, nodeRes) : endNodeResponse(nodeRes);
285
+ }
286
+ function writeHead(nodeRes, status, statusText, rawHeaders) {
287
+ const writeHeaders = globalThis.Deno ? rawHeaders : rawHeaders.flat();
288
+ if (!nodeRes.headersSent) if (nodeRes.req?.httpVersion === "2.0") nodeRes.writeHead(status, writeHeaders);
289
+ else nodeRes.writeHead(status, statusText, writeHeaders);
290
+ }
291
+ function endNodeResponse(nodeRes) {
292
+ return new Promise((resolve) => nodeRes.end(resolve));
293
+ }
294
+ function streamBody(stream, nodeRes) {
295
+ if (nodeRes.destroyed) {
296
+ stream.cancel();
297
+ return;
298
+ }
299
+ const reader = stream.getReader();
300
+ function streamCancel(error) {
301
+ reader.cancel(error).catch(() => {
302
+ });
303
+ if (error) nodeRes.destroy(error);
304
+ }
305
+ function streamHandle({ done, value }) {
306
+ try {
307
+ if (done) nodeRes.end();
308
+ else if (nodeRes.write(value)) reader.read().then(streamHandle, streamCancel);
309
+ else nodeRes.once("drain", () => reader.read().then(streamHandle, streamCancel));
310
+ } catch (error) {
311
+ streamCancel(error instanceof Error ? error : void 0);
312
+ }
313
+ }
314
+ nodeRes.on("close", streamCancel);
315
+ nodeRes.on("error", streamCancel);
316
+ reader.read().then(streamHandle, streamCancel);
317
+ return reader.closed.catch(streamCancel).finally(() => {
318
+ nodeRes.off("close", streamCancel);
319
+ nodeRes.off("error", streamCancel);
320
+ });
321
+ }
322
+ var NodeRequestURL = class extends FastURL {
323
+ #req;
324
+ constructor({ req }) {
325
+ const path = req.url || "/";
326
+ if (path[0] === "/") {
327
+ const qIndex = path.indexOf("?");
328
+ const pathname = qIndex === -1 ? path : path?.slice(0, qIndex) || "/";
329
+ const search = qIndex === -1 ? "" : path?.slice(qIndex) || "";
330
+ const host = req.headers.host || req.headers[":authority"] || `${req.socket.localFamily === "IPv6" ? "[" + req.socket.localAddress + "]" : req.socket.localAddress}:${req.socket?.localPort || "80"}`;
331
+ const protocol = req.socket?.encrypted || req.headers["x-forwarded-proto"] === "https" || req.headers[":scheme"] === "https" ? "https:" : "http:";
332
+ super({
333
+ protocol,
334
+ host,
335
+ pathname,
336
+ search
337
+ });
338
+ } else super(path);
339
+ this.#req = req;
340
+ }
341
+ get pathname() {
342
+ return super.pathname;
343
+ }
344
+ set pathname(value) {
345
+ this._url.pathname = value;
346
+ this.#req.url = this._url.pathname + this._url.search;
347
+ }
348
+ };
349
+ const NodeRequestHeaders = /* @__PURE__ */ (() => {
350
+ const NativeHeaders = globalThis.Headers;
351
+ class Headers2 {
352
+ #req;
353
+ #headers;
354
+ constructor(req) {
355
+ this.#req = req;
356
+ }
357
+ static [Symbol.hasInstance](val) {
358
+ return val instanceof NativeHeaders;
359
+ }
360
+ get _headers() {
361
+ if (!this.#headers) {
362
+ const headers = new NativeHeaders();
363
+ const rawHeaders = this.#req.rawHeaders;
364
+ const len = rawHeaders.length;
365
+ for (let i = 0; i < len; i += 2) {
366
+ const key = rawHeaders[i];
367
+ if (key.charCodeAt(0) === 58) continue;
368
+ const value = rawHeaders[i + 1];
369
+ headers.append(key, value);
370
+ }
371
+ this.#headers = headers;
372
+ }
373
+ return this.#headers;
374
+ }
375
+ get(name) {
376
+ if (this.#headers) return this.#headers.get(name);
377
+ const value = this.#req.headers[name.toLowerCase()];
378
+ return Array.isArray(value) ? value.join(", ") : value || null;
379
+ }
380
+ has(name) {
381
+ if (this.#headers) return this.#headers.has(name);
382
+ return name.toLowerCase() in this.#req.headers;
383
+ }
384
+ getSetCookie() {
385
+ if (this.#headers) return this.#headers.getSetCookie();
386
+ const value = this.#req.headers["set-cookie"];
387
+ return Array.isArray(value) ? value : value ? [value] : [];
388
+ }
389
+ *_entries() {
390
+ const rawHeaders = this.#req.rawHeaders;
391
+ const len = rawHeaders.length;
392
+ for (let i = 0; i < len; i += 2) {
393
+ const key = rawHeaders[i];
394
+ if (key.charCodeAt(0) === 58) continue;
395
+ yield [key.toLowerCase(), rawHeaders[i + 1]];
396
+ }
397
+ }
398
+ entries() {
399
+ return this.#headers ? this.#headers.entries() : this._entries();
400
+ }
401
+ [Symbol.iterator]() {
402
+ return this.entries();
403
+ }
404
+ }
405
+ lazyInherit(Headers2.prototype, NativeHeaders.prototype, "_headers");
406
+ Object.setPrototypeOf(Headers2, NativeHeaders);
407
+ Object.setPrototypeOf(Headers2.prototype, NativeHeaders.prototype);
408
+ return Headers2;
409
+ })();
410
+ const NodeRequest = /* @__PURE__ */ (() => {
411
+ const NativeRequest = globalThis.Request;
412
+ class Request {
413
+ runtime;
414
+ #req;
415
+ #url;
416
+ #bodyStream;
417
+ #request;
418
+ #headers;
419
+ #abortController;
420
+ constructor(ctx) {
421
+ this.#req = ctx.req;
422
+ this.runtime = {
423
+ name: "node",
424
+ node: ctx
425
+ };
426
+ }
427
+ static [Symbol.hasInstance](val) {
428
+ return val instanceof NativeRequest;
429
+ }
430
+ get ip() {
431
+ return this.#req.socket?.remoteAddress;
432
+ }
433
+ get method() {
434
+ if (this.#request) return this.#request.method;
435
+ return this.#req.method || "GET";
436
+ }
437
+ get _url() {
438
+ return this.#url ||= new NodeRequestURL({ req: this.#req });
439
+ }
440
+ set _url(url) {
441
+ this.#url = url;
442
+ }
443
+ get url() {
444
+ if (this.#request) return this.#request.url;
445
+ return this._url.href;
446
+ }
447
+ get headers() {
448
+ if (this.#request) return this.#request.headers;
449
+ return this.#headers ||= new NodeRequestHeaders(this.#req);
450
+ }
451
+ get _abortController() {
452
+ if (!this.#abortController) {
453
+ this.#abortController = new AbortController();
454
+ const { req, res } = this.runtime.node;
455
+ const abortController = this.#abortController;
456
+ const abort = (err) => abortController.abort?.(err);
457
+ if (res) res.once("close", () => {
458
+ const reqError = req.errored;
459
+ if (reqError) abort(reqError);
460
+ else if (!res.writableEnded) abort();
461
+ });
462
+ else req.once("close", () => {
463
+ if (!req.complete) abort();
464
+ });
465
+ }
466
+ return this.#abortController;
467
+ }
468
+ get signal() {
469
+ return this.#request ? this.#request.signal : this._abortController.signal;
470
+ }
471
+ get body() {
472
+ if (this.#request) return this.#request.body;
473
+ if (this.#bodyStream === void 0) {
474
+ const method = this.method;
475
+ this.#bodyStream = !(method === "GET" || method === "HEAD") ? Readable.toWeb(this.#req) : null;
476
+ }
477
+ return this.#bodyStream;
478
+ }
479
+ text() {
480
+ if (this.#request) return this.#request.text();
481
+ if (this.#bodyStream !== void 0) return this.#bodyStream ? new Response(this.#bodyStream).text() : Promise.resolve("");
482
+ return readBody(this.#req).then((buf) => buf.toString());
483
+ }
484
+ json() {
485
+ if (this.#request) return this.#request.json();
486
+ return this.text().then((text) => JSON.parse(text));
487
+ }
488
+ get _request() {
489
+ if (!this.#request) {
490
+ const body = this.body;
491
+ this.#request = new NativeRequest(this.url, {
492
+ method: this.method,
493
+ headers: this.headers,
494
+ signal: this._abortController.signal,
495
+ body,
496
+ duplex: body ? "half" : void 0
497
+ });
498
+ this.#headers = void 0;
499
+ this.#bodyStream = void 0;
500
+ }
501
+ return this.#request;
502
+ }
503
+ }
504
+ lazyInherit(Request.prototype, NativeRequest.prototype, "_request");
505
+ Object.setPrototypeOf(Request.prototype, NativeRequest.prototype);
506
+ return Request;
507
+ })();
508
+ function readBody(req) {
509
+ if ("rawBody" in req && Buffer.isBuffer(req.rawBody)) return Promise.resolve(req.rawBody);
510
+ return new Promise((resolve, reject) => {
511
+ const chunks = [];
512
+ const onData = (chunk) => {
513
+ chunks.push(chunk);
514
+ };
515
+ const onError = (err) => {
516
+ reject(err);
517
+ };
518
+ const onEnd = () => {
519
+ req.off("error", onError);
520
+ req.off("data", onData);
521
+ resolve(Buffer.concat(chunks));
522
+ };
523
+ req.on("data", onData).once("end", onEnd).once("error", onError);
524
+ });
525
+ }
526
+ const NodeResponse = /* @__PURE__ */ (() => {
527
+ const NativeResponse = globalThis.Response;
528
+ const STATUS_CODES = globalThis.process?.getBuiltinModule?.("node:http")?.STATUS_CODES || {};
529
+ class NodeResponse2 {
530
+ #body;
531
+ #init;
532
+ #headers;
533
+ #response;
534
+ constructor(body, init) {
535
+ this.#body = body;
536
+ this.#init = init;
537
+ }
538
+ static [Symbol.hasInstance](val) {
539
+ return val instanceof NativeResponse;
540
+ }
541
+ get status() {
542
+ return this.#response?.status || this.#init?.status || 200;
543
+ }
544
+ get statusText() {
545
+ return this.#response?.statusText || this.#init?.statusText || STATUS_CODES[this.status] || "";
546
+ }
547
+ get headers() {
548
+ if (this.#response) return this.#response.headers;
549
+ if (this.#headers) return this.#headers;
550
+ const initHeaders = this.#init?.headers;
551
+ return this.#headers = initHeaders instanceof Headers ? initHeaders : new Headers(initHeaders);
552
+ }
553
+ get ok() {
554
+ if (this.#response) return this.#response.ok;
555
+ const status = this.status;
556
+ return status >= 200 && status < 300;
557
+ }
558
+ get _response() {
559
+ if (this.#response) return this.#response;
560
+ let body = this.#body;
561
+ if (body && typeof body.pipe === "function" && !(body instanceof Readable)) {
562
+ const stream = new PassThrough();
563
+ body.pipe(stream);
564
+ const abort = body.abort;
565
+ if (abort) stream.once("close", () => abort());
566
+ body = stream;
567
+ }
568
+ this.#response = new NativeResponse(body, this.#headers ? {
569
+ ...this.#init,
570
+ headers: this.#headers
571
+ } : this.#init);
572
+ this.#init = void 0;
573
+ this.#headers = void 0;
574
+ this.#body = void 0;
575
+ return this.#response;
576
+ }
577
+ _toNodeResponse() {
578
+ const status = this.status;
579
+ const statusText = this.statusText;
580
+ let body;
581
+ let contentType;
582
+ let contentLength;
583
+ if (this.#response) body = this.#response.body;
584
+ else if (this.#body) if (this.#body instanceof ReadableStream) body = this.#body;
585
+ else if (typeof this.#body === "string") {
586
+ body = this.#body;
587
+ contentType = "text/plain; charset=UTF-8";
588
+ contentLength = Buffer.byteLength(this.#body);
589
+ } else if (this.#body instanceof ArrayBuffer) {
590
+ body = Buffer.from(this.#body);
591
+ contentLength = this.#body.byteLength;
592
+ } else if (this.#body instanceof Uint8Array) {
593
+ body = this.#body;
594
+ contentLength = this.#body.byteLength;
595
+ } else if (this.#body instanceof DataView) {
596
+ body = Buffer.from(this.#body.buffer);
597
+ contentLength = this.#body.byteLength;
598
+ } else if (this.#body instanceof Blob) {
599
+ body = this.#body.stream();
600
+ contentType = this.#body.type;
601
+ contentLength = this.#body.size;
602
+ } else if (typeof this.#body.pipe === "function") body = this.#body;
603
+ else body = this._response.body;
604
+ const headers = [];
605
+ const initHeaders = this.#init?.headers;
606
+ const headerEntries = this.#response?.headers || this.#headers || (initHeaders ? Array.isArray(initHeaders) ? initHeaders : initHeaders?.entries ? initHeaders.entries() : Object.entries(initHeaders).map(([k, v]) => [k.toLowerCase(), v]) : void 0);
607
+ let hasContentTypeHeader;
608
+ let hasContentLength;
609
+ if (headerEntries) for (const [key, value] of headerEntries) {
610
+ if (Array.isArray(value)) for (const v of value) headers.push([key, v]);
611
+ else headers.push([key, value]);
612
+ if (key === "content-type") hasContentTypeHeader = true;
613
+ else if (key === "content-length") hasContentLength = true;
614
+ }
615
+ if (contentType && !hasContentTypeHeader) headers.push(["content-type", contentType]);
616
+ if (contentLength && !hasContentLength) headers.push(["content-length", String(contentLength)]);
617
+ this.#init = void 0;
618
+ this.#headers = void 0;
619
+ this.#response = void 0;
620
+ this.#body = void 0;
621
+ return {
622
+ status,
623
+ statusText,
624
+ headers,
625
+ body
626
+ };
627
+ }
628
+ }
629
+ lazyInherit(NodeResponse2.prototype, NativeResponse.prototype, "_response");
630
+ Object.setPrototypeOf(NodeResponse2, NativeResponse);
631
+ Object.setPrototypeOf(NodeResponse2.prototype, NativeResponse.prototype);
632
+ return NodeResponse2;
633
+ })();
249
634
  function serve(options) {
250
- return new BunServer(options);
635
+ return new NodeServer(options);
251
636
  }
252
- var BunServer = class {
253
- runtime = "bun";
637
+ var NodeServer = class {
638
+ runtime = "node";
254
639
  options;
255
- bun = {};
640
+ node;
256
641
  serveOptions;
257
642
  fetch;
258
643
  waitUntil;
644
+ #isSecure;
645
+ #listeningPromise;
259
646
  #wait;
260
647
  constructor(options) {
261
648
  this.options = {
@@ -263,72 +650,81 @@ var BunServer = class {
263
650
  middleware: [...options.middleware || []]
264
651
  };
265
652
  for (const plugin of options.plugins || []) plugin(this);
266
- gracefulShutdownPlugin(this);
267
- const fetchHandler = wrapFetch(this);
653
+ errorPlugin(this);
654
+ const fetchHandler = this.fetch = wrapFetch(this);
268
655
  const loader = globalThis.__srvxLoader__;
269
656
  if (loader) {
270
- this.fetch = fetchHandler;
271
657
  loader(fetchHandler);
272
658
  return;
273
659
  }
660
+ gracefulShutdownPlugin(this);
274
661
  this.#wait = createWaitUntil();
275
662
  this.waitUntil = this.#wait.waitUntil;
276
- this.fetch = (request, server) => {
277
- Object.defineProperties(request, {
278
- waitUntil: { value: this.#wait?.waitUntil },
279
- runtime: {
280
- enumerable: true,
281
- value: {
282
- name: "bun",
283
- bun: { server }
284
- }
285
- },
286
- ip: {
287
- enumerable: true,
288
- get() {
289
- return server?.requestIP(request)?.address;
290
- }
291
- }
663
+ const handler = (nodeReq, nodeRes) => {
664
+ const request = new NodeRequest({
665
+ req: nodeReq,
666
+ res: nodeRes
292
667
  });
293
- return fetchHandler(request);
668
+ request.waitUntil = this.#wait?.waitUntil;
669
+ const res = fetchHandler(request);
670
+ return res instanceof Promise ? res.then((resolvedRes) => sendNodeResponse(nodeRes, resolvedRes)) : sendNodeResponse(nodeRes, res);
294
671
  };
295
672
  const tls = resolveTLSOptions(this.options);
673
+ const { port, hostname: host } = resolvePortAndHost(this.options);
296
674
  this.serveOptions = {
297
- ...resolvePortAndHost(this.options),
298
- reusePort: this.options.reusePort,
299
- error: this.options.error,
300
- ...this.options.bun,
301
- tls: {
302
- cert: tls?.cert,
303
- key: tls?.key,
304
- passphrase: tls?.passphrase,
305
- ...this.options.bun?.tls
306
- },
307
- fetch: this.fetch
675
+ port,
676
+ host,
677
+ exclusive: !this.options.reusePort,
678
+ ...tls ? {
679
+ cert: tls.cert,
680
+ key: tls.key,
681
+ passphrase: tls.passphrase
682
+ } : {},
683
+ ...this.options.node
684
+ };
685
+ let server;
686
+ this.#isSecure = !!this.serveOptions.cert && this.options.protocol !== "http";
687
+ if (this.options.node?.http2 ?? this.#isSecure) if (this.#isSecure) server = nodeHTTP2.createSecureServer({
688
+ allowHTTP1: true,
689
+ ...this.serveOptions
690
+ }, handler);
691
+ else throw new Error("node.http2 option requires tls certificate!");
692
+ else if (this.#isSecure) server = nodeHTTPS.createServer(this.serveOptions, handler);
693
+ else server = nodeHTTP.createServer(this.serveOptions, handler);
694
+ this.node = {
695
+ server,
696
+ handler
308
697
  };
309
698
  if (!options.manual) this.serve();
310
699
  }
311
700
  serve() {
312
- if (!this.bun.server) this.bun.server = Bun.serve(this.serveOptions);
313
- printListening(this.options, this.url);
314
- return Promise.resolve(this);
701
+ if (this.#listeningPromise) return Promise.resolve(this.#listeningPromise).then(() => this);
702
+ this.#listeningPromise = new Promise((resolve) => {
703
+ this.node.server.listen(this.serveOptions, () => {
704
+ printListening(this.options, this.url);
705
+ resolve();
706
+ });
707
+ });
315
708
  }
316
709
  get url() {
317
- const server = this.bun?.server;
318
- if (!server) return;
319
- const address = server.address;
320
- if (address) return fmtURL(address.address, address.port, server.protocol === "https");
321
- return server.url.href;
710
+ const addr = this.node?.server?.address();
711
+ if (!addr) return;
712
+ return typeof addr === "string" ? addr : fmtURL(addr.address, addr.port, this.#isSecure);
322
713
  }
323
714
  ready() {
324
- return Promise.resolve(this);
715
+ return Promise.resolve(this.#listeningPromise).then(() => this);
325
716
  }
326
717
  async close(closeAll) {
327
- await Promise.all([this.#wait?.wait(), Promise.resolve(this.bun?.server?.stop(closeAll))]);
718
+ await Promise.all([this.#wait?.wait(), new Promise((resolve, reject) => {
719
+ const server = this.node?.server;
720
+ if (server && closeAll && "closeAllConnections" in server) server.closeAllConnections();
721
+ if (!server || !server.listening) return resolve();
722
+ server.close((error) => error ? reject(error) : resolve());
723
+ })]);
328
724
  }
329
725
  };
330
726
  export {
331
727
  FastURL as F,
332
- FastResponse as a,
728
+ NodeResponse as N,
333
729
  serve as s
334
730
  };
@@ -1,10 +1,10 @@
1
- import require$$1 from "util";
1
+ import require$$0 from "util";
2
2
  var node;
3
3
  var hasRequiredNode;
4
4
  function requireNode() {
5
5
  if (hasRequiredNode) return node;
6
6
  hasRequiredNode = 1;
7
- node = require$$1.deprecate;
7
+ node = require$$0.deprecate;
8
8
  return node;
9
9
  }
10
10
  export {