@c4a/server-cli 0.4.12-alpha.2 → 0.4.12-alpha.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/serve.js CHANGED
@@ -98,7 +98,7 @@ var init_serverConfig = __esm(() => {
98
98
  DEFAULT_SERVER_CONFIG = {
99
99
  server: {
100
100
  port: 5100,
101
- host: "0.0.0.0"
101
+ host: "::"
102
102
  },
103
103
  doc_db: {
104
104
  provider: "sqlite",
@@ -106,7 +106,7 @@ var init_serverConfig = __esm(() => {
106
106
  path: "./data/c4a.db"
107
107
  },
108
108
  mongodb: {
109
- uri: "mongodb://localhost:27017/c4a",
109
+ uri: "mongodb://localhost:27017/c4a?directConnection=true",
110
110
  database: "c4a"
111
111
  }
112
112
  },
@@ -11668,6 +11668,32 @@ var init_utils = __esm(() => {
11668
11668
  // ../core/src/constants.ts
11669
11669
  var DEFAULT_USER_ID = "user_admin", DEFAULT_USER_NAME = "admin", DEFAULT_WORKSPACE_ID = "ws_default", DEFAULT_WORKSPACE_NAME = "默认大脑", DEFAULT_CLOUD_LIBRARY_ID = "lib_cloud_default", DEFAULT_CLOUD_LIBRARY_NAME = "个人云", DAEMON_OFFLINE_THRESHOLD = 60000;
11670
11670
 
11671
+ // ../core/src/fileTypes.ts
11672
+ function getFileExtension(name) {
11673
+ const dot = name.lastIndexOf(".");
11674
+ return dot >= 0 ? name.slice(dot).toLowerCase() : "";
11675
+ }
11676
+ var INDEXABLE_CODE_EXTENSIONS, INDEXABLE_DOC_EXTENSIONS, INDEXABLE_EXTENSIONS, UPLOAD_ALLOWED_EXTENSIONS, TEXT_EXTENSIONS, UPLOAD_MAX_FILE_SIZE, UPLOAD_MAX_FILES = 10;
11677
+ var init_fileTypes = __esm(() => {
11678
+ INDEXABLE_CODE_EXTENSIONS = new Set([".ts", ".tsx"]);
11679
+ INDEXABLE_DOC_EXTENSIONS = new Set([".md"]);
11680
+ INDEXABLE_EXTENSIONS = new Set([
11681
+ ...INDEXABLE_CODE_EXTENSIONS,
11682
+ ...INDEXABLE_DOC_EXTENSIONS
11683
+ ]);
11684
+ UPLOAD_ALLOWED_EXTENSIONS = new Set([
11685
+ ".md",
11686
+ ".doc",
11687
+ ".docx",
11688
+ ".pdf",
11689
+ ".ppt",
11690
+ ".pptx",
11691
+ ".txt"
11692
+ ]);
11693
+ TEXT_EXTENSIONS = new Set([".md", ".txt"]);
11694
+ UPLOAD_MAX_FILE_SIZE = 5 * 1024 * 1024;
11695
+ });
11696
+
11671
11697
  // ../core/src/wsEvents.ts
11672
11698
  var WS_DAEMON_CONNECTED = "ws:daemon:connected", WS_DAEMON_STATUS = "ws:daemon:status";
11673
11699
 
@@ -11677,6 +11703,7 @@ var init_src = __esm(() => {
11677
11703
  init_schemas();
11678
11704
  init_errors2();
11679
11705
  init_utils();
11706
+ init_fileTypes();
11680
11707
  });
11681
11708
 
11682
11709
  // ../../node_modules/.bun/@mikro-orm+core@6.6.7/node_modules/@mikro-orm/core/enums.js
@@ -143247,532 +143274,2231 @@ var init_milvusVectorStore = __esm(() => {
143247
143274
  init_src();
143248
143275
  });
143249
143276
 
143250
- // ../../node_modules/.bun/@hono+node-server@1.19.9+eb2864ea6bc646ec/node_modules/@hono/node-server/dist/index.mjs
143251
- var exports_dist = {};
143252
- __export(exports_dist, {
143253
- serve: () => serve,
143254
- getRequestListener: () => getRequestListener,
143255
- createAdaptorServer: () => createAdaptorServer,
143256
- RequestError: () => RequestError
143257
- });
143258
- import { createServer as createServerHTTP } from "http";
143259
- import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
143260
- import { Http2ServerRequest } from "http2";
143261
- import { Readable } from "stream";
143262
- import crypto2 from "crypto";
143263
- async function readWithoutBlocking(readPromise) {
143264
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(undefined))]);
143265
- }
143266
- function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
143267
- const cancel = (error40) => {
143268
- reader.cancel(error40).catch(() => {});
143277
+ // ../../node_modules/.bun/ms@2.1.3/node_modules/ms/index.js
143278
+ var require_ms2 = __commonJS((exports, module) => {
143279
+ var s = 1000;
143280
+ var m = s * 60;
143281
+ var h = m * 60;
143282
+ var d = h * 24;
143283
+ var w = d * 7;
143284
+ var y = d * 365.25;
143285
+ module.exports = function(val, options) {
143286
+ options = options || {};
143287
+ var type = typeof val;
143288
+ if (type === "string" && val.length > 0) {
143289
+ return parse5(val);
143290
+ } else if (type === "number" && isFinite(val)) {
143291
+ return options.long ? fmtLong(val) : fmtShort(val);
143292
+ }
143293
+ throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
143269
143294
  };
143270
- writable.on("close", cancel);
143271
- writable.on("error", cancel);
143272
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
143273
- return reader.closed.finally(() => {
143274
- writable.off("close", cancel);
143275
- writable.off("error", cancel);
143276
- });
143277
- function handleStreamError(error40) {
143278
- if (error40) {
143279
- writable.destroy(error40);
143295
+ function parse5(str) {
143296
+ str = String(str);
143297
+ if (str.length > 100) {
143298
+ return;
143299
+ }
143300
+ var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
143301
+ if (!match2) {
143302
+ return;
143303
+ }
143304
+ var n = parseFloat(match2[1]);
143305
+ var type = (match2[2] || "ms").toLowerCase();
143306
+ switch (type) {
143307
+ case "years":
143308
+ case "year":
143309
+ case "yrs":
143310
+ case "yr":
143311
+ case "y":
143312
+ return n * y;
143313
+ case "weeks":
143314
+ case "week":
143315
+ case "w":
143316
+ return n * w;
143317
+ case "days":
143318
+ case "day":
143319
+ case "d":
143320
+ return n * d;
143321
+ case "hours":
143322
+ case "hour":
143323
+ case "hrs":
143324
+ case "hr":
143325
+ case "h":
143326
+ return n * h;
143327
+ case "minutes":
143328
+ case "minute":
143329
+ case "mins":
143330
+ case "min":
143331
+ case "m":
143332
+ return n * m;
143333
+ case "seconds":
143334
+ case "second":
143335
+ case "secs":
143336
+ case "sec":
143337
+ case "s":
143338
+ return n * s;
143339
+ case "milliseconds":
143340
+ case "millisecond":
143341
+ case "msecs":
143342
+ case "msec":
143343
+ case "ms":
143344
+ return n;
143345
+ default:
143346
+ return;
143280
143347
  }
143281
143348
  }
143282
- function onDrain() {
143283
- reader.read().then(flow, handleStreamError);
143284
- }
143285
- function flow({ done, value }) {
143286
- try {
143287
- if (done) {
143288
- writable.end();
143289
- } else if (!writable.write(value)) {
143290
- writable.once("drain", onDrain);
143291
- } else {
143292
- return reader.read().then(flow, handleStreamError);
143293
- }
143294
- } catch (e) {
143295
- handleStreamError(e);
143349
+ function fmtShort(ms) {
143350
+ var msAbs = Math.abs(ms);
143351
+ if (msAbs >= d) {
143352
+ return Math.round(ms / d) + "d";
143353
+ }
143354
+ if (msAbs >= h) {
143355
+ return Math.round(ms / h) + "h";
143296
143356
  }
143357
+ if (msAbs >= m) {
143358
+ return Math.round(ms / m) + "m";
143359
+ }
143360
+ if (msAbs >= s) {
143361
+ return Math.round(ms / s) + "s";
143362
+ }
143363
+ return ms + "ms";
143297
143364
  }
143298
- }
143299
- function writeFromReadableStream(stream, writable) {
143300
- if (stream.locked) {
143301
- throw new TypeError("ReadableStream is locked.");
143302
- } else if (writable.destroyed) {
143303
- return;
143365
+ function fmtLong(ms) {
143366
+ var msAbs = Math.abs(ms);
143367
+ if (msAbs >= d) {
143368
+ return plural(ms, msAbs, d, "day");
143369
+ }
143370
+ if (msAbs >= h) {
143371
+ return plural(ms, msAbs, h, "hour");
143372
+ }
143373
+ if (msAbs >= m) {
143374
+ return plural(ms, msAbs, m, "minute");
143375
+ }
143376
+ if (msAbs >= s) {
143377
+ return plural(ms, msAbs, s, "second");
143378
+ }
143379
+ return ms + " ms";
143304
143380
  }
143305
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
143306
- }
143307
- var RequestError, toRequestError = (e) => {
143308
- if (e instanceof RequestError) {
143309
- return e;
143381
+ function plural(ms, msAbs, n, name21) {
143382
+ var isPlural = msAbs >= n * 1.5;
143383
+ return Math.round(ms / n) + " " + name21 + (isPlural ? "s" : "");
143310
143384
  }
143311
- return new RequestError(e.message, { cause: e });
143312
- }, GlobalRequest, Request2, newHeadersFromIncoming = (incoming) => {
143313
- const headerRecord = [];
143314
- const rawHeaders = incoming.rawHeaders;
143315
- for (let i = 0;i < rawHeaders.length; i += 2) {
143316
- const { [i]: key, [i + 1]: value } = rawHeaders;
143317
- if (key.charCodeAt(0) !== 58) {
143318
- headerRecord.push([key, value]);
143385
+ });
143386
+
143387
+ // ../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/common.js
143388
+ var require_common7 = __commonJS((exports, module) => {
143389
+ function setup(env) {
143390
+ createDebug.debug = createDebug;
143391
+ createDebug.default = createDebug;
143392
+ createDebug.coerce = coerce2;
143393
+ createDebug.disable = disable;
143394
+ createDebug.enable = enable;
143395
+ createDebug.enabled = enabled;
143396
+ createDebug.humanize = require_ms2();
143397
+ createDebug.destroy = destroy;
143398
+ Object.keys(env).forEach((key) => {
143399
+ createDebug[key] = env[key];
143400
+ });
143401
+ createDebug.names = [];
143402
+ createDebug.skips = [];
143403
+ createDebug.formatters = {};
143404
+ function selectColor(namespace) {
143405
+ let hash2 = 0;
143406
+ for (let i = 0;i < namespace.length; i++) {
143407
+ hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
143408
+ hash2 |= 0;
143409
+ }
143410
+ return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
143319
143411
  }
143320
- }
143321
- return new Headers(headerRecord);
143322
- }, wrapBodyStream, newRequestFromIncoming = (method, url2, headers, incoming, abortController) => {
143323
- const init = {
143324
- method,
143325
- headers,
143326
- signal: abortController.signal
143327
- };
143328
- if (method === "TRACE") {
143329
- init.method = "GET";
143330
- const req = new Request2(url2, init);
143331
- Object.defineProperty(req, "method", {
143332
- get() {
143333
- return "TRACE";
143412
+ createDebug.selectColor = selectColor;
143413
+ function createDebug(namespace) {
143414
+ let prevTime;
143415
+ let enableOverride = null;
143416
+ let namespacesCache;
143417
+ let enabledCache;
143418
+ function debug(...args) {
143419
+ if (!debug.enabled) {
143420
+ return;
143421
+ }
143422
+ const self2 = debug;
143423
+ const curr = Number(new Date);
143424
+ const ms = curr - (prevTime || curr);
143425
+ self2.diff = ms;
143426
+ self2.prev = prevTime;
143427
+ self2.curr = curr;
143428
+ prevTime = curr;
143429
+ args[0] = createDebug.coerce(args[0]);
143430
+ if (typeof args[0] !== "string") {
143431
+ args.unshift("%O");
143432
+ }
143433
+ let index = 0;
143434
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format) => {
143435
+ if (match2 === "%%") {
143436
+ return "%";
143437
+ }
143438
+ index++;
143439
+ const formatter = createDebug.formatters[format];
143440
+ if (typeof formatter === "function") {
143441
+ const val = args[index];
143442
+ match2 = formatter.call(self2, val);
143443
+ args.splice(index, 1);
143444
+ index--;
143445
+ }
143446
+ return match2;
143447
+ });
143448
+ createDebug.formatArgs.call(self2, args);
143449
+ const logFn = self2.log || createDebug.log;
143450
+ logFn.apply(self2, args);
143334
143451
  }
143335
- });
143336
- return req;
143337
- }
143338
- if (!(method === "GET" || method === "HEAD")) {
143339
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
143340
- init.body = new ReadableStream({
143341
- start(controller) {
143342
- controller.enqueue(incoming.rawBody);
143343
- controller.close();
143452
+ debug.namespace = namespace;
143453
+ debug.useColors = createDebug.useColors();
143454
+ debug.color = createDebug.selectColor(namespace);
143455
+ debug.extend = extend2;
143456
+ debug.destroy = createDebug.destroy;
143457
+ Object.defineProperty(debug, "enabled", {
143458
+ enumerable: true,
143459
+ configurable: false,
143460
+ get: () => {
143461
+ if (enableOverride !== null) {
143462
+ return enableOverride;
143463
+ }
143464
+ if (namespacesCache !== createDebug.namespaces) {
143465
+ namespacesCache = createDebug.namespaces;
143466
+ enabledCache = createDebug.enabled(namespace);
143467
+ }
143468
+ return enabledCache;
143469
+ },
143470
+ set: (v) => {
143471
+ enableOverride = v;
143344
143472
  }
143345
143473
  });
143346
- } else if (incoming[wrapBodyStream]) {
143347
- let reader;
143348
- init.body = new ReadableStream({
143349
- async pull(controller) {
143350
- try {
143351
- reader ||= Readable.toWeb(incoming).getReader();
143352
- const { done, value } = await reader.read();
143353
- if (done) {
143354
- controller.close();
143355
- } else {
143356
- controller.enqueue(value);
143357
- }
143358
- } catch (error40) {
143359
- controller.error(error40);
143474
+ if (typeof createDebug.init === "function") {
143475
+ createDebug.init(debug);
143476
+ }
143477
+ return debug;
143478
+ }
143479
+ function extend2(namespace, delimiter) {
143480
+ const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
143481
+ newDebug.log = this.log;
143482
+ return newDebug;
143483
+ }
143484
+ function enable(namespaces) {
143485
+ createDebug.save(namespaces);
143486
+ createDebug.namespaces = namespaces;
143487
+ createDebug.names = [];
143488
+ createDebug.skips = [];
143489
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
143490
+ for (const ns of split) {
143491
+ if (ns[0] === "-") {
143492
+ createDebug.skips.push(ns.slice(1));
143493
+ } else {
143494
+ createDebug.names.push(ns);
143495
+ }
143496
+ }
143497
+ }
143498
+ function matchesTemplate(search2, template) {
143499
+ let searchIndex = 0;
143500
+ let templateIndex = 0;
143501
+ let starIndex = -1;
143502
+ let matchIndex = 0;
143503
+ while (searchIndex < search2.length) {
143504
+ if (templateIndex < template.length && (template[templateIndex] === search2[searchIndex] || template[templateIndex] === "*")) {
143505
+ if (template[templateIndex] === "*") {
143506
+ starIndex = templateIndex;
143507
+ matchIndex = searchIndex;
143508
+ templateIndex++;
143509
+ } else {
143510
+ searchIndex++;
143511
+ templateIndex++;
143360
143512
  }
143513
+ } else if (starIndex !== -1) {
143514
+ templateIndex = starIndex + 1;
143515
+ matchIndex++;
143516
+ searchIndex = matchIndex;
143517
+ } else {
143518
+ return false;
143361
143519
  }
143362
- });
143363
- } else {
143364
- init.body = Readable.toWeb(incoming);
143520
+ }
143521
+ while (templateIndex < template.length && template[templateIndex] === "*") {
143522
+ templateIndex++;
143523
+ }
143524
+ return templateIndex === template.length;
143365
143525
  }
143366
- }
143367
- return new Request2(url2, init);
143368
- }, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest = (incoming, defaultHostname) => {
143369
- const req = Object.create(requestPrototype);
143370
- req[incomingKey] = incoming;
143371
- const incomingUrl = incoming.url || "";
143372
- if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
143373
- if (incoming instanceof Http2ServerRequest) {
143374
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
143526
+ function disable() {
143527
+ const namespaces = [
143528
+ ...createDebug.names,
143529
+ ...createDebug.skips.map((namespace) => "-" + namespace)
143530
+ ].join(",");
143531
+ createDebug.enable("");
143532
+ return namespaces;
143375
143533
  }
143376
- try {
143377
- const url22 = new URL(incomingUrl);
143378
- req[urlKey] = url22.href;
143379
- } catch (e) {
143380
- throw new RequestError("Invalid absolute URL", { cause: e });
143534
+ function enabled(name21) {
143535
+ for (const skip of createDebug.skips) {
143536
+ if (matchesTemplate(name21, skip)) {
143537
+ return false;
143538
+ }
143539
+ }
143540
+ for (const ns of createDebug.names) {
143541
+ if (matchesTemplate(name21, ns)) {
143542
+ return true;
143543
+ }
143544
+ }
143545
+ return false;
143381
143546
  }
143382
- return req;
143547
+ function coerce2(val) {
143548
+ if (val instanceof Error) {
143549
+ return val.stack || val.message;
143550
+ }
143551
+ return val;
143552
+ }
143553
+ function destroy() {
143554
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
143555
+ }
143556
+ createDebug.enable(createDebug.load());
143557
+ return createDebug;
143383
143558
  }
143384
- const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
143385
- if (!host) {
143386
- throw new RequestError("Missing host header");
143559
+ module.exports = setup;
143560
+ });
143561
+
143562
+ // ../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/browser.js
143563
+ var require_browser2 = __commonJS((exports, module) => {
143564
+ exports.formatArgs = formatArgs;
143565
+ exports.save = save;
143566
+ exports.load = load;
143567
+ exports.useColors = useColors;
143568
+ exports.storage = localstorage();
143569
+ exports.destroy = (() => {
143570
+ let warned = false;
143571
+ return () => {
143572
+ if (!warned) {
143573
+ warned = true;
143574
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
143575
+ }
143576
+ };
143577
+ })();
143578
+ exports.colors = [
143579
+ "#0000CC",
143580
+ "#0000FF",
143581
+ "#0033CC",
143582
+ "#0033FF",
143583
+ "#0066CC",
143584
+ "#0066FF",
143585
+ "#0099CC",
143586
+ "#0099FF",
143587
+ "#00CC00",
143588
+ "#00CC33",
143589
+ "#00CC66",
143590
+ "#00CC99",
143591
+ "#00CCCC",
143592
+ "#00CCFF",
143593
+ "#3300CC",
143594
+ "#3300FF",
143595
+ "#3333CC",
143596
+ "#3333FF",
143597
+ "#3366CC",
143598
+ "#3366FF",
143599
+ "#3399CC",
143600
+ "#3399FF",
143601
+ "#33CC00",
143602
+ "#33CC33",
143603
+ "#33CC66",
143604
+ "#33CC99",
143605
+ "#33CCCC",
143606
+ "#33CCFF",
143607
+ "#6600CC",
143608
+ "#6600FF",
143609
+ "#6633CC",
143610
+ "#6633FF",
143611
+ "#66CC00",
143612
+ "#66CC33",
143613
+ "#9900CC",
143614
+ "#9900FF",
143615
+ "#9933CC",
143616
+ "#9933FF",
143617
+ "#99CC00",
143618
+ "#99CC33",
143619
+ "#CC0000",
143620
+ "#CC0033",
143621
+ "#CC0066",
143622
+ "#CC0099",
143623
+ "#CC00CC",
143624
+ "#CC00FF",
143625
+ "#CC3300",
143626
+ "#CC3333",
143627
+ "#CC3366",
143628
+ "#CC3399",
143629
+ "#CC33CC",
143630
+ "#CC33FF",
143631
+ "#CC6600",
143632
+ "#CC6633",
143633
+ "#CC9900",
143634
+ "#CC9933",
143635
+ "#CCCC00",
143636
+ "#CCCC33",
143637
+ "#FF0000",
143638
+ "#FF0033",
143639
+ "#FF0066",
143640
+ "#FF0099",
143641
+ "#FF00CC",
143642
+ "#FF00FF",
143643
+ "#FF3300",
143644
+ "#FF3333",
143645
+ "#FF3366",
143646
+ "#FF3399",
143647
+ "#FF33CC",
143648
+ "#FF33FF",
143649
+ "#FF6600",
143650
+ "#FF6633",
143651
+ "#FF9900",
143652
+ "#FF9933",
143653
+ "#FFCC00",
143654
+ "#FFCC33"
143655
+ ];
143656
+ function useColors() {
143657
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
143658
+ return true;
143659
+ }
143660
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
143661
+ return false;
143662
+ }
143663
+ let m;
143664
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
143387
143665
  }
143388
- let scheme;
143389
- if (incoming instanceof Http2ServerRequest) {
143390
- scheme = incoming.scheme;
143391
- if (!(scheme === "http" || scheme === "https")) {
143392
- throw new RequestError("Unsupported scheme");
143666
+ function formatArgs(args) {
143667
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
143668
+ if (!this.useColors) {
143669
+ return;
143393
143670
  }
143394
- } else {
143395
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
143671
+ const c = "color: " + this.color;
143672
+ args.splice(1, 0, c, "color: inherit");
143673
+ let index = 0;
143674
+ let lastC = 0;
143675
+ args[0].replace(/%[a-zA-Z%]/g, (match2) => {
143676
+ if (match2 === "%%") {
143677
+ return;
143678
+ }
143679
+ index++;
143680
+ if (match2 === "%c") {
143681
+ lastC = index;
143682
+ }
143683
+ });
143684
+ args.splice(lastC, 0, c);
143396
143685
  }
143397
- const url2 = new URL(`${scheme}://${host}${incomingUrl}`);
143398
- if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) {
143399
- throw new RequestError("Invalid host header");
143686
+ exports.log = console.debug || console.log || (() => {});
143687
+ function save(namespaces) {
143688
+ try {
143689
+ if (namespaces) {
143690
+ exports.storage.setItem("debug", namespaces);
143691
+ } else {
143692
+ exports.storage.removeItem("debug");
143693
+ }
143694
+ } catch (error40) {}
143400
143695
  }
143401
- req[urlKey] = url2.href;
143402
- return req;
143403
- }, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders = (headers) => {
143404
- const res = {};
143405
- if (!(headers instanceof Headers)) {
143406
- headers = new Headers(headers ?? undefined);
143696
+ function load() {
143697
+ let r;
143698
+ try {
143699
+ r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
143700
+ } catch (error40) {}
143701
+ if (!r && typeof process !== "undefined" && "env" in process) {
143702
+ r = process.env.DEBUG;
143703
+ }
143704
+ return r;
143407
143705
  }
143408
- const cookies = [];
143409
- for (const [k, v] of headers) {
143410
- if (k === "set-cookie") {
143411
- cookies.push(v);
143706
+ function localstorage() {
143707
+ try {
143708
+ return localStorage;
143709
+ } catch (error40) {}
143710
+ }
143711
+ module.exports = require_common7()(exports);
143712
+ var { formatters } = module.exports;
143713
+ formatters.j = function(v) {
143714
+ try {
143715
+ return JSON.stringify(v);
143716
+ } catch (error40) {
143717
+ return "[UnexpectedJSONParseError]: " + error40.message;
143718
+ }
143719
+ };
143720
+ });
143721
+
143722
+ // ../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/node.js
143723
+ var require_node6 = __commonJS((exports, module) => {
143724
+ var tty = __require("tty");
143725
+ var util3 = __require("util");
143726
+ exports.init = init;
143727
+ exports.log = log;
143728
+ exports.formatArgs = formatArgs;
143729
+ exports.save = save;
143730
+ exports.load = load;
143731
+ exports.useColors = useColors;
143732
+ exports.destroy = util3.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
143733
+ exports.colors = [6, 2, 3, 4, 5, 1];
143734
+ try {
143735
+ const supportsColor = require_supports_color();
143736
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
143737
+ exports.colors = [
143738
+ 20,
143739
+ 21,
143740
+ 26,
143741
+ 27,
143742
+ 32,
143743
+ 33,
143744
+ 38,
143745
+ 39,
143746
+ 40,
143747
+ 41,
143748
+ 42,
143749
+ 43,
143750
+ 44,
143751
+ 45,
143752
+ 56,
143753
+ 57,
143754
+ 62,
143755
+ 63,
143756
+ 68,
143757
+ 69,
143758
+ 74,
143759
+ 75,
143760
+ 76,
143761
+ 77,
143762
+ 78,
143763
+ 79,
143764
+ 80,
143765
+ 81,
143766
+ 92,
143767
+ 93,
143768
+ 98,
143769
+ 99,
143770
+ 112,
143771
+ 113,
143772
+ 128,
143773
+ 129,
143774
+ 134,
143775
+ 135,
143776
+ 148,
143777
+ 149,
143778
+ 160,
143779
+ 161,
143780
+ 162,
143781
+ 163,
143782
+ 164,
143783
+ 165,
143784
+ 166,
143785
+ 167,
143786
+ 168,
143787
+ 169,
143788
+ 170,
143789
+ 171,
143790
+ 172,
143791
+ 173,
143792
+ 178,
143793
+ 179,
143794
+ 184,
143795
+ 185,
143796
+ 196,
143797
+ 197,
143798
+ 198,
143799
+ 199,
143800
+ 200,
143801
+ 201,
143802
+ 202,
143803
+ 203,
143804
+ 204,
143805
+ 205,
143806
+ 206,
143807
+ 207,
143808
+ 208,
143809
+ 209,
143810
+ 214,
143811
+ 215,
143812
+ 220,
143813
+ 221
143814
+ ];
143815
+ }
143816
+ } catch (error40) {}
143817
+ exports.inspectOpts = Object.keys(process.env).filter((key) => {
143818
+ return /^debug_/i.test(key);
143819
+ }).reduce((obj, key) => {
143820
+ const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
143821
+ return k.toUpperCase();
143822
+ });
143823
+ let val = process.env[key];
143824
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
143825
+ val = true;
143826
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
143827
+ val = false;
143828
+ } else if (val === "null") {
143829
+ val = null;
143412
143830
  } else {
143413
- res[k] = v;
143831
+ val = Number(val);
143414
143832
  }
143833
+ obj[prop] = val;
143834
+ return obj;
143835
+ }, {});
143836
+ function useColors() {
143837
+ return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
143415
143838
  }
143416
- if (cookies.length > 0) {
143417
- res["set-cookie"] = cookies;
143839
+ function formatArgs(args) {
143840
+ const { namespace: name21, useColors: useColors2 } = this;
143841
+ if (useColors2) {
143842
+ const c = this.color;
143843
+ const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
143844
+ const prefix = ` ${colorCode};1m${name21} \x1B[0m`;
143845
+ args[0] = prefix + args[0].split(`
143846
+ `).join(`
143847
+ ` + prefix);
143848
+ args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
143849
+ } else {
143850
+ args[0] = getDate() + name21 + " " + args[0];
143851
+ }
143418
143852
  }
143419
- res["content-type"] ??= "text/plain; charset=UTF-8";
143420
- return res;
143421
- }, X_ALREADY_SENT = "x-hono-already-sent", outgoingEnded, handleRequestError = () => new Response(null, {
143422
- status: 400
143423
- }), handleFetchError2 = (e) => new Response(null, {
143424
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
143425
- }), handleResponseError = (e, outgoing) => {
143426
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
143427
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
143428
- console.info("The user aborted a request.");
143429
- } else {
143430
- console.error(e);
143431
- if (!outgoing.headersSent) {
143432
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
143853
+ function getDate() {
143854
+ if (exports.inspectOpts.hideDate) {
143855
+ return "";
143433
143856
  }
143434
- outgoing.end(`Error: ${err.message}`);
143435
- outgoing.destroy(err);
143857
+ return new Date().toISOString() + " ";
143436
143858
  }
143437
- }, flushHeaders = (outgoing) => {
143438
- if ("flushHeaders" in outgoing && outgoing.writable) {
143439
- outgoing.flushHeaders();
143859
+ function log(...args) {
143860
+ return process.stderr.write(util3.formatWithOptions(exports.inspectOpts, ...args) + `
143861
+ `);
143440
143862
  }
143441
- }, responseViaCache = async (res, outgoing) => {
143442
- let [status, body, header] = res[cacheKey];
143443
- if (header instanceof Headers) {
143444
- header = buildOutgoingHttpHeaders(header);
143863
+ function save(namespaces) {
143864
+ if (namespaces) {
143865
+ process.env.DEBUG = namespaces;
143866
+ } else {
143867
+ delete process.env.DEBUG;
143868
+ }
143445
143869
  }
143446
- if (typeof body === "string") {
143447
- header["Content-Length"] = Buffer.byteLength(body);
143448
- } else if (body instanceof Uint8Array) {
143449
- header["Content-Length"] = body.byteLength;
143450
- } else if (body instanceof Blob) {
143451
- header["Content-Length"] = body.size;
143870
+ function load() {
143871
+ return process.env.DEBUG;
143452
143872
  }
143453
- outgoing.writeHead(status, header);
143454
- if (typeof body === "string" || body instanceof Uint8Array) {
143455
- outgoing.end(body);
143456
- } else if (body instanceof Blob) {
143457
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
143873
+ function init(debug) {
143874
+ debug.inspectOpts = {};
143875
+ const keys = Object.keys(exports.inspectOpts);
143876
+ for (let i = 0;i < keys.length; i++) {
143877
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
143878
+ }
143879
+ }
143880
+ module.exports = require_common7()(exports);
143881
+ var { formatters } = module.exports;
143882
+ formatters.o = function(v) {
143883
+ this.inspectOpts.colors = this.useColors;
143884
+ return util3.inspect(v, this.inspectOpts).split(`
143885
+ `).map((str) => str.trim()).join(" ");
143886
+ };
143887
+ formatters.O = function(v) {
143888
+ this.inspectOpts.colors = this.useColors;
143889
+ return util3.inspect(v, this.inspectOpts);
143890
+ };
143891
+ });
143892
+
143893
+ // ../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/index.js
143894
+ var require_src3 = __commonJS((exports, module) => {
143895
+ if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) {
143896
+ module.exports = require_browser2();
143458
143897
  } else {
143459
- flushHeaders(outgoing);
143460
- await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
143898
+ module.exports = require_node6();
143461
143899
  }
143462
- outgoing[outgoingEnded]?.();
143463
- }, isPromise = (res) => typeof res.then === "function", responseViaResponseObject = async (res, outgoing, options = {}) => {
143464
- if (isPromise(res)) {
143465
- if (options.errorHandler) {
143900
+ });
143901
+
143902
+ // ../../node_modules/.bun/follow-redirects@1.15.11/node_modules/follow-redirects/debug.js
143903
+ var require_debug = __commonJS((exports, module) => {
143904
+ var debug;
143905
+ module.exports = function() {
143906
+ if (!debug) {
143466
143907
  try {
143467
- res = await res;
143468
- } catch (err) {
143469
- const errRes = await options.errorHandler(err);
143470
- if (!errRes) {
143471
- return;
143472
- }
143473
- res = errRes;
143908
+ debug = require_src3()("follow-redirects");
143909
+ } catch (error40) {}
143910
+ if (typeof debug !== "function") {
143911
+ debug = function() {};
143474
143912
  }
143475
- } else {
143476
- res = await res.catch(handleFetchError2);
143477
143913
  }
143914
+ debug.apply(null, arguments);
143915
+ };
143916
+ });
143917
+
143918
+ // ../../node_modules/.bun/follow-redirects@1.15.11/node_modules/follow-redirects/index.js
143919
+ var require_follow_redirects = __commonJS((exports, module) => {
143920
+ var url2 = __require("url");
143921
+ var URL2 = url2.URL;
143922
+ var http = __require("http");
143923
+ var https = __require("https");
143924
+ var Writable = __require("stream").Writable;
143925
+ var assert2 = __require("assert");
143926
+ var debug = require_debug();
143927
+ (function detectUnsupportedEnvironment() {
143928
+ var looksLikeNode = typeof process !== "undefined";
143929
+ var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
143930
+ var looksLikeV8 = isFunction(Error.captureStackTrace);
143931
+ if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
143932
+ console.warn("The follow-redirects package should be excluded from browser builds.");
143933
+ }
143934
+ })();
143935
+ var useNativeURL = false;
143936
+ try {
143937
+ assert2(new URL2(""));
143938
+ } catch (error40) {
143939
+ useNativeURL = error40.code === "ERR_INVALID_URL";
143940
+ }
143941
+ var preservedUrlFields = [
143942
+ "auth",
143943
+ "host",
143944
+ "hostname",
143945
+ "href",
143946
+ "path",
143947
+ "pathname",
143948
+ "port",
143949
+ "protocol",
143950
+ "query",
143951
+ "search",
143952
+ "hash"
143953
+ ];
143954
+ var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
143955
+ var eventHandlers = Object.create(null);
143956
+ events.forEach(function(event) {
143957
+ eventHandlers[event] = function(arg1, arg2, arg3) {
143958
+ this._redirectable.emit(event, arg1, arg2, arg3);
143959
+ };
143960
+ });
143961
+ var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError);
143962
+ var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed");
143963
+ var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError);
143964
+ var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit");
143965
+ var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
143966
+ var destroy = Writable.prototype.destroy || noop2;
143967
+ function RedirectableRequest(options, responseCallback) {
143968
+ Writable.call(this);
143969
+ this._sanitizeOptions(options);
143970
+ this._options = options;
143971
+ this._ended = false;
143972
+ this._ending = false;
143973
+ this._redirectCount = 0;
143974
+ this._redirects = [];
143975
+ this._requestBodyLength = 0;
143976
+ this._requestBodyBuffers = [];
143977
+ if (responseCallback) {
143978
+ this.on("response", responseCallback);
143979
+ }
143980
+ var self2 = this;
143981
+ this._onNativeResponse = function(response) {
143982
+ try {
143983
+ self2._processResponse(response);
143984
+ } catch (cause) {
143985
+ self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
143986
+ }
143987
+ };
143988
+ this._performRequest();
143478
143989
  }
143479
- if (cacheKey in res) {
143480
- return responseViaCache(res, outgoing);
143481
- }
143482
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
143483
- if (res.body) {
143484
- const reader = res.body.getReader();
143485
- const values = [];
143486
- let done = false;
143487
- let currentReadPromise = undefined;
143488
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
143489
- let maxReadCount = 2;
143490
- for (let i = 0;i < maxReadCount; i++) {
143491
- currentReadPromise ||= reader.read();
143492
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
143493
- console.error(e);
143494
- done = true;
143495
- });
143496
- if (!chunk) {
143497
- if (i === 1) {
143498
- await new Promise((resolve2) => setTimeout(resolve2));
143499
- maxReadCount = 3;
143500
- continue;
143990
+ RedirectableRequest.prototype = Object.create(Writable.prototype);
143991
+ RedirectableRequest.prototype.abort = function() {
143992
+ destroyRequest(this._currentRequest);
143993
+ this._currentRequest.abort();
143994
+ this.emit("abort");
143995
+ };
143996
+ RedirectableRequest.prototype.destroy = function(error40) {
143997
+ destroyRequest(this._currentRequest, error40);
143998
+ destroy.call(this, error40);
143999
+ return this;
144000
+ };
144001
+ RedirectableRequest.prototype.write = function(data, encoding, callback) {
144002
+ if (this._ending) {
144003
+ throw new WriteAfterEndError;
144004
+ }
144005
+ if (!isString(data) && !isBuffer(data)) {
144006
+ throw new TypeError("data should be a string, Buffer or Uint8Array");
144007
+ }
144008
+ if (isFunction(encoding)) {
144009
+ callback = encoding;
144010
+ encoding = null;
144011
+ }
144012
+ if (data.length === 0) {
144013
+ if (callback) {
144014
+ callback();
144015
+ }
144016
+ return;
144017
+ }
144018
+ if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
144019
+ this._requestBodyLength += data.length;
144020
+ this._requestBodyBuffers.push({ data, encoding });
144021
+ this._currentRequest.write(data, encoding, callback);
144022
+ } else {
144023
+ this.emit("error", new MaxBodyLengthExceededError);
144024
+ this.abort();
144025
+ }
144026
+ };
144027
+ RedirectableRequest.prototype.end = function(data, encoding, callback) {
144028
+ if (isFunction(data)) {
144029
+ callback = data;
144030
+ data = encoding = null;
144031
+ } else if (isFunction(encoding)) {
144032
+ callback = encoding;
144033
+ encoding = null;
144034
+ }
144035
+ if (!data) {
144036
+ this._ended = this._ending = true;
144037
+ this._currentRequest.end(null, null, callback);
144038
+ } else {
144039
+ var self2 = this;
144040
+ var currentRequest = this._currentRequest;
144041
+ this.write(data, encoding, function() {
144042
+ self2._ended = true;
144043
+ currentRequest.end(null, null, callback);
144044
+ });
144045
+ this._ending = true;
144046
+ }
144047
+ };
144048
+ RedirectableRequest.prototype.setHeader = function(name21, value) {
144049
+ this._options.headers[name21] = value;
144050
+ this._currentRequest.setHeader(name21, value);
144051
+ };
144052
+ RedirectableRequest.prototype.removeHeader = function(name21) {
144053
+ delete this._options.headers[name21];
144054
+ this._currentRequest.removeHeader(name21);
144055
+ };
144056
+ RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
144057
+ var self2 = this;
144058
+ function destroyOnTimeout(socket) {
144059
+ socket.setTimeout(msecs);
144060
+ socket.removeListener("timeout", socket.destroy);
144061
+ socket.addListener("timeout", socket.destroy);
144062
+ }
144063
+ function startTimer(socket) {
144064
+ if (self2._timeout) {
144065
+ clearTimeout(self2._timeout);
144066
+ }
144067
+ self2._timeout = setTimeout(function() {
144068
+ self2.emit("timeout");
144069
+ clearTimer();
144070
+ }, msecs);
144071
+ destroyOnTimeout(socket);
144072
+ }
144073
+ function clearTimer() {
144074
+ if (self2._timeout) {
144075
+ clearTimeout(self2._timeout);
144076
+ self2._timeout = null;
144077
+ }
144078
+ self2.removeListener("abort", clearTimer);
144079
+ self2.removeListener("error", clearTimer);
144080
+ self2.removeListener("response", clearTimer);
144081
+ self2.removeListener("close", clearTimer);
144082
+ if (callback) {
144083
+ self2.removeListener("timeout", callback);
144084
+ }
144085
+ if (!self2.socket) {
144086
+ self2._currentRequest.removeListener("socket", startTimer);
144087
+ }
144088
+ }
144089
+ if (callback) {
144090
+ this.on("timeout", callback);
144091
+ }
144092
+ if (this.socket) {
144093
+ startTimer(this.socket);
144094
+ } else {
144095
+ this._currentRequest.once("socket", startTimer);
144096
+ }
144097
+ this.on("socket", destroyOnTimeout);
144098
+ this.on("abort", clearTimer);
144099
+ this.on("error", clearTimer);
144100
+ this.on("response", clearTimer);
144101
+ this.on("close", clearTimer);
144102
+ return this;
144103
+ };
144104
+ [
144105
+ "flushHeaders",
144106
+ "getHeader",
144107
+ "setNoDelay",
144108
+ "setSocketKeepAlive"
144109
+ ].forEach(function(method) {
144110
+ RedirectableRequest.prototype[method] = function(a, b) {
144111
+ return this._currentRequest[method](a, b);
144112
+ };
144113
+ });
144114
+ ["aborted", "connection", "socket"].forEach(function(property) {
144115
+ Object.defineProperty(RedirectableRequest.prototype, property, {
144116
+ get: function() {
144117
+ return this._currentRequest[property];
144118
+ }
144119
+ });
144120
+ });
144121
+ RedirectableRequest.prototype._sanitizeOptions = function(options) {
144122
+ if (!options.headers) {
144123
+ options.headers = {};
144124
+ }
144125
+ if (options.host) {
144126
+ if (!options.hostname) {
144127
+ options.hostname = options.host;
144128
+ }
144129
+ delete options.host;
144130
+ }
144131
+ if (!options.pathname && options.path) {
144132
+ var searchPos = options.path.indexOf("?");
144133
+ if (searchPos < 0) {
144134
+ options.pathname = options.path;
144135
+ } else {
144136
+ options.pathname = options.path.substring(0, searchPos);
144137
+ options.search = options.path.substring(searchPos);
144138
+ }
144139
+ }
144140
+ };
144141
+ RedirectableRequest.prototype._performRequest = function() {
144142
+ var protocol = this._options.protocol;
144143
+ var nativeProtocol = this._options.nativeProtocols[protocol];
144144
+ if (!nativeProtocol) {
144145
+ throw new TypeError("Unsupported protocol " + protocol);
144146
+ }
144147
+ if (this._options.agents) {
144148
+ var scheme = protocol.slice(0, -1);
144149
+ this._options.agent = this._options.agents[scheme];
144150
+ }
144151
+ var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
144152
+ request._redirectable = this;
144153
+ for (var event of events) {
144154
+ request.on(event, eventHandlers[event]);
144155
+ }
144156
+ this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : this._options.path;
144157
+ if (this._isRedirect) {
144158
+ var i = 0;
144159
+ var self2 = this;
144160
+ var buffers = this._requestBodyBuffers;
144161
+ (function writeNext(error40) {
144162
+ if (request === self2._currentRequest) {
144163
+ if (error40) {
144164
+ self2.emit("error", error40);
144165
+ } else if (i < buffers.length) {
144166
+ var buffer = buffers[i++];
144167
+ if (!request.finished) {
144168
+ request.write(buffer.data, buffer.encoding, writeNext);
144169
+ }
144170
+ } else if (self2._ended) {
144171
+ request.end();
143501
144172
  }
143502
- break;
143503
144173
  }
143504
- currentReadPromise = undefined;
143505
- if (chunk.value) {
143506
- values.push(chunk.value);
144174
+ })();
144175
+ }
144176
+ };
144177
+ RedirectableRequest.prototype._processResponse = function(response) {
144178
+ var statusCode = response.statusCode;
144179
+ if (this._options.trackRedirects) {
144180
+ this._redirects.push({
144181
+ url: this._currentUrl,
144182
+ headers: response.headers,
144183
+ statusCode
144184
+ });
144185
+ }
144186
+ var location = response.headers.location;
144187
+ if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
144188
+ response.responseUrl = this._currentUrl;
144189
+ response.redirects = this._redirects;
144190
+ this.emit("response", response);
144191
+ this._requestBodyBuffers = [];
144192
+ return;
144193
+ }
144194
+ destroyRequest(this._currentRequest);
144195
+ response.destroy();
144196
+ if (++this._redirectCount > this._options.maxRedirects) {
144197
+ throw new TooManyRedirectsError;
144198
+ }
144199
+ var requestHeaders;
144200
+ var beforeRedirect = this._options.beforeRedirect;
144201
+ if (beforeRedirect) {
144202
+ requestHeaders = Object.assign({
144203
+ Host: response.req.getHeader("host")
144204
+ }, this._options.headers);
144205
+ }
144206
+ var method = this._options.method;
144207
+ if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
144208
+ this._options.method = "GET";
144209
+ this._requestBodyBuffers = [];
144210
+ removeMatchingHeaders(/^content-/i, this._options.headers);
144211
+ }
144212
+ var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
144213
+ var currentUrlParts = parseUrl(this._currentUrl);
144214
+ var currentHost = currentHostHeader || currentUrlParts.host;
144215
+ var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost }));
144216
+ var redirectUrl = resolveUrl(location, currentUrl);
144217
+ debug("redirecting to", redirectUrl.href);
144218
+ this._isRedirect = true;
144219
+ spreadUrlObject(redirectUrl, this._options);
144220
+ if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
144221
+ removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
144222
+ }
144223
+ if (isFunction(beforeRedirect)) {
144224
+ var responseDetails = {
144225
+ headers: response.headers,
144226
+ statusCode
144227
+ };
144228
+ var requestDetails = {
144229
+ url: currentUrl,
144230
+ method,
144231
+ headers: requestHeaders
144232
+ };
144233
+ beforeRedirect(this._options, responseDetails, requestDetails);
144234
+ this._sanitizeOptions(this._options);
144235
+ }
144236
+ this._performRequest();
144237
+ };
144238
+ function wrap4(protocols) {
144239
+ var exports2 = {
144240
+ maxRedirects: 21,
144241
+ maxBodyLength: 10 * 1024 * 1024
144242
+ };
144243
+ var nativeProtocols = {};
144244
+ Object.keys(protocols).forEach(function(scheme) {
144245
+ var protocol = scheme + ":";
144246
+ var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
144247
+ var wrappedProtocol = exports2[scheme] = Object.create(nativeProtocol);
144248
+ function request(input, options, callback) {
144249
+ if (isURL(input)) {
144250
+ input = spreadUrlObject(input);
144251
+ } else if (isString(input)) {
144252
+ input = spreadUrlObject(parseUrl(input));
144253
+ } else {
144254
+ callback = options;
144255
+ options = validateUrl(input);
144256
+ input = { protocol };
143507
144257
  }
143508
- if (chunk.done) {
143509
- done = true;
143510
- break;
144258
+ if (isFunction(options)) {
144259
+ callback = options;
144260
+ options = null;
144261
+ }
144262
+ options = Object.assign({
144263
+ maxRedirects: exports2.maxRedirects,
144264
+ maxBodyLength: exports2.maxBodyLength
144265
+ }, input, options);
144266
+ options.nativeProtocols = nativeProtocols;
144267
+ if (!isString(options.host) && !isString(options.hostname)) {
144268
+ options.hostname = "::1";
143511
144269
  }
144270
+ assert2.equal(options.protocol, protocol, "protocol mismatch");
144271
+ debug("options", options);
144272
+ return new RedirectableRequest(options, callback);
143512
144273
  }
143513
- if (done && !("content-length" in resHeaderRecord)) {
143514
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
144274
+ function get(input, options, callback) {
144275
+ var wrappedRequest = wrappedProtocol.request(input, options, callback);
144276
+ wrappedRequest.end();
144277
+ return wrappedRequest;
143515
144278
  }
143516
- }
143517
- outgoing.writeHead(res.status, resHeaderRecord);
143518
- values.forEach((value) => {
143519
- outgoing.write(value);
144279
+ Object.defineProperties(wrappedProtocol, {
144280
+ request: { value: request, configurable: true, enumerable: true, writable: true },
144281
+ get: { value: get, configurable: true, enumerable: true, writable: true }
144282
+ });
143520
144283
  });
143521
- if (done) {
143522
- outgoing.end();
144284
+ return exports2;
144285
+ }
144286
+ function noop2() {}
144287
+ function parseUrl(input) {
144288
+ var parsed;
144289
+ if (useNativeURL) {
144290
+ parsed = new URL2(input);
143523
144291
  } else {
143524
- if (values.length === 0) {
143525
- flushHeaders(outgoing);
144292
+ parsed = validateUrl(url2.parse(input));
144293
+ if (!isString(parsed.protocol)) {
144294
+ throw new InvalidUrlError({ input });
143526
144295
  }
143527
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
143528
144296
  }
143529
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
143530
- outgoing.writeHead(res.status, resHeaderRecord);
143531
- outgoing.end();
144297
+ return parsed;
143532
144298
  }
143533
- outgoing[outgoingEnded]?.();
143534
- }, getRequestListener = (fetchCallback, options = {}) => {
143535
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
143536
- if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
143537
- Object.defineProperty(global, "Request", {
143538
- value: Request2
143539
- });
143540
- Object.defineProperty(global, "Response", {
143541
- value: Response2
144299
+ function resolveUrl(relative, base2) {
144300
+ return useNativeURL ? new URL2(relative, base2) : parseUrl(url2.resolve(base2, relative));
144301
+ }
144302
+ function validateUrl(input) {
144303
+ if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
144304
+ throw new InvalidUrlError({ input: input.href || input });
144305
+ }
144306
+ if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
144307
+ throw new InvalidUrlError({ input: input.href || input });
144308
+ }
144309
+ return input;
144310
+ }
144311
+ function spreadUrlObject(urlObject, target) {
144312
+ var spread = target || {};
144313
+ for (var key of preservedUrlFields) {
144314
+ spread[key] = urlObject[key];
144315
+ }
144316
+ if (spread.hostname.startsWith("[")) {
144317
+ spread.hostname = spread.hostname.slice(1, -1);
144318
+ }
144319
+ if (spread.port !== "") {
144320
+ spread.port = Number(spread.port);
144321
+ }
144322
+ spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
144323
+ return spread;
144324
+ }
144325
+ function removeMatchingHeaders(regex, headers) {
144326
+ var lastValue;
144327
+ for (var header in headers) {
144328
+ if (regex.test(header)) {
144329
+ lastValue = headers[header];
144330
+ delete headers[header];
144331
+ }
144332
+ }
144333
+ return lastValue === null || typeof lastValue === "undefined" ? undefined : String(lastValue).trim();
144334
+ }
144335
+ function createErrorType(code, message, baseClass) {
144336
+ function CustomError(properties) {
144337
+ if (isFunction(Error.captureStackTrace)) {
144338
+ Error.captureStackTrace(this, this.constructor);
144339
+ }
144340
+ Object.assign(this, properties || {});
144341
+ this.code = code;
144342
+ this.message = this.cause ? message + ": " + this.cause.message : message;
144343
+ }
144344
+ CustomError.prototype = new (baseClass || Error);
144345
+ Object.defineProperties(CustomError.prototype, {
144346
+ constructor: {
144347
+ value: CustomError,
144348
+ enumerable: false
144349
+ },
144350
+ name: {
144351
+ value: "Error [" + code + "]",
144352
+ enumerable: false
144353
+ }
143542
144354
  });
144355
+ return CustomError;
143543
144356
  }
143544
- return async (incoming, outgoing) => {
143545
- let res, req;
143546
- try {
143547
- req = newRequest(incoming, options.hostname);
143548
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
143549
- if (!incomingEnded) {
143550
- incoming[wrapBodyStream] = true;
143551
- incoming.on("end", () => {
143552
- incomingEnded = true;
143553
- });
143554
- if (incoming instanceof Http2ServerRequest2) {
143555
- outgoing[outgoingEnded] = () => {
143556
- if (!incomingEnded) {
143557
- setTimeout(() => {
143558
- if (!incomingEnded) {
143559
- setTimeout(() => {
143560
- incoming.destroy();
143561
- outgoing.destroy();
143562
- });
143563
- }
143564
- });
143565
- }
143566
- };
143567
- }
144357
+ function destroyRequest(request, error40) {
144358
+ for (var event of events) {
144359
+ request.removeListener(event, eventHandlers[event]);
144360
+ }
144361
+ request.on("error", noop2);
144362
+ request.destroy(error40);
144363
+ }
144364
+ function isSubdomain(subdomain, domain2) {
144365
+ assert2(isString(subdomain) && isString(domain2));
144366
+ var dot = subdomain.length - domain2.length - 1;
144367
+ return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain2);
144368
+ }
144369
+ function isString(value) {
144370
+ return typeof value === "string" || value instanceof String;
144371
+ }
144372
+ function isFunction(value) {
144373
+ return typeof value === "function";
144374
+ }
144375
+ function isBuffer(value) {
144376
+ return typeof value === "object" && "length" in value;
144377
+ }
144378
+ function isURL(value) {
144379
+ return URL2 && value instanceof URL2;
144380
+ }
144381
+ module.exports = wrap4({ http, https });
144382
+ module.exports.wrap = wrap4;
144383
+ });
144384
+
144385
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/http-proxy/common.js
144386
+ var require_common8 = __commonJS((exports) => {
144387
+ Object.defineProperty(exports, "__esModule", { value: true });
144388
+ exports.isSSL = undefined;
144389
+ exports.setupOutgoing = setupOutgoing;
144390
+ exports.setupSocket = setupSocket;
144391
+ exports.getPort = getPort;
144392
+ exports.hasEncryptedConnection = hasEncryptedConnection;
144393
+ exports.urlJoin = urlJoin;
144394
+ exports.rewriteCookieProperty = rewriteCookieProperty;
144395
+ exports.toURL = toURL;
144396
+ var node_tls_1 = __require("node:tls");
144397
+ var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
144398
+ exports.isSSL = /^https|wss/;
144399
+ var HEADER_BLACKLIST = "trailer";
144400
+ var HTTP2_HEADER_BLACKLIST = [
144401
+ ":method",
144402
+ ":path",
144403
+ ":scheme",
144404
+ ":authority",
144405
+ "connection",
144406
+ "keep-alive"
144407
+ ];
144408
+ function setupOutgoing(outgoing, options, req, forward) {
144409
+ const target = options[forward || "target"];
144410
+ outgoing.port = +(target.port ?? (target.protocol !== undefined && exports.isSSL.test(target.protocol) ? 443 : 80));
144411
+ for (const e of [
144412
+ "host",
144413
+ "hostname",
144414
+ "socketPath",
144415
+ "pfx",
144416
+ "key",
144417
+ "passphrase",
144418
+ "cert",
144419
+ "ca",
144420
+ "ciphers",
144421
+ "secureProtocol"
144422
+ ]) {
144423
+ outgoing[e] = target[e];
144424
+ }
144425
+ outgoing.method = options.method || req.method;
144426
+ outgoing.headers = { ...req.headers };
144427
+ if (req.headers?.[":authority"]) {
144428
+ outgoing.headers.host = req.headers[":authority"];
144429
+ }
144430
+ if (options.headers) {
144431
+ outgoing.headers = { ...outgoing.headers, ...options.headers };
144432
+ }
144433
+ for (const header in outgoing.headers) {
144434
+ if (HEADER_BLACKLIST == header.toLowerCase()) {
144435
+ delete outgoing.headers[header];
144436
+ break;
143568
144437
  }
143569
- outgoing.on("close", () => {
143570
- const abortController = req[abortControllerKey];
143571
- if (abortController) {
143572
- if (incoming.errored) {
143573
- req[abortControllerKey].abort(incoming.errored.toString());
143574
- } else if (!outgoing.writableFinished) {
143575
- req[abortControllerKey].abort("Client connection prematurely closed.");
143576
- }
144438
+ }
144439
+ if (req.httpVersionMajor > 1) {
144440
+ for (const header of HTTP2_HEADER_BLACKLIST) {
144441
+ delete outgoing.headers[header];
144442
+ }
144443
+ }
144444
+ if (options.auth) {
144445
+ delete outgoing.headers.authorization;
144446
+ outgoing.auth = options.auth;
144447
+ }
144448
+ if (options.ca) {
144449
+ outgoing.ca = options.ca;
144450
+ }
144451
+ if (target.protocol !== undefined && exports.isSSL.test(target.protocol)) {
144452
+ outgoing.rejectUnauthorized = typeof options.secure === "undefined" ? true : options.secure;
144453
+ }
144454
+ outgoing.agent = options.agent || false;
144455
+ outgoing.localAddress = options.localAddress;
144456
+ if (!outgoing.agent) {
144457
+ outgoing.headers = outgoing.headers || {};
144458
+ if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) {
144459
+ outgoing.headers.connection = "close";
144460
+ }
144461
+ }
144462
+ const targetPath = target && options.prependPath !== false && "pathname" in target ? getPath2(`${target.pathname}${target.search ?? ""}`) : "/";
144463
+ let outgoingPath = options.toProxy ? req.url : getPath2(req.url);
144464
+ outgoingPath = !options.ignorePath ? outgoingPath : "";
144465
+ outgoing.path = urlJoin(targetPath, outgoingPath ?? "");
144466
+ if (options.changeOrigin) {
144467
+ outgoing.headers.host = target.protocol !== undefined && required2(outgoing.port, target.protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
144468
+ }
144469
+ outgoing.url = "href" in target && target.href || (target.protocol === "https" ? "https" : "http") + "://" + outgoing.host + (outgoing.port ? ":" + outgoing.port : "");
144470
+ if (req.httpVersionMajor > 1) {
144471
+ for (const header of HTTP2_HEADER_BLACKLIST) {
144472
+ delete outgoing.headers[header];
144473
+ }
144474
+ }
144475
+ return outgoing;
144476
+ }
144477
+ function setupSocket(socket) {
144478
+ socket.setTimeout(0);
144479
+ socket.setNoDelay(true);
144480
+ socket.setKeepAlive(true, 0);
144481
+ return socket;
144482
+ }
144483
+ function getPort(req) {
144484
+ const hostHeader = req.headers[":authority"] || req.headers.host;
144485
+ const res = hostHeader ? hostHeader.match(/:(\d+)/) : "";
144486
+ return res ? res[1] : hasEncryptedConnection(req) ? "443" : "80";
144487
+ }
144488
+ function hasEncryptedConnection(req) {
144489
+ const conn = req.connection;
144490
+ return conn instanceof node_tls_1.TLSSocket && conn.encrypted || Boolean(conn.pair);
144491
+ }
144492
+ function urlJoin(...args) {
144493
+ const queryParams = [];
144494
+ let queryParamRaw = "";
144495
+ args.forEach((url2, index) => {
144496
+ const qpStart = url2.indexOf("?");
144497
+ if (qpStart !== -1) {
144498
+ queryParams.push(url2.substring(qpStart + 1));
144499
+ args[index] = url2.substring(0, qpStart);
144500
+ }
144501
+ });
144502
+ queryParamRaw = queryParams.filter(Boolean).join("&");
144503
+ let retSegs = "";
144504
+ for (const seg of args) {
144505
+ if (!seg) {
144506
+ continue;
144507
+ }
144508
+ if (retSegs.endsWith("/")) {
144509
+ if (seg.startsWith("/")) {
144510
+ retSegs += seg.slice(1);
144511
+ } else {
144512
+ retSegs += seg;
143577
144513
  }
143578
- if (!incomingEnded) {
143579
- setTimeout(() => {
143580
- if (!incomingEnded) {
143581
- setTimeout(() => {
143582
- incoming.destroy();
143583
- });
143584
- }
143585
- });
144514
+ } else {
144515
+ if (seg.startsWith("/")) {
144516
+ retSegs += seg;
144517
+ } else {
144518
+ retSegs += "/" + seg;
143586
144519
  }
144520
+ }
144521
+ }
144522
+ return queryParamRaw ? retSegs + "?" + queryParamRaw : retSegs;
144523
+ }
144524
+ function rewriteCookieProperty(header, config2, property) {
144525
+ if (Array.isArray(header)) {
144526
+ return header.map((headerElement) => {
144527
+ return rewriteCookieProperty(headerElement, config2, property);
143587
144528
  });
143588
- res = fetchCallback(req, { incoming, outgoing });
143589
- if (cacheKey in res) {
143590
- return responseViaCache(res, outgoing);
144529
+ }
144530
+ return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), (match2, prefix, previousValue) => {
144531
+ let newValue;
144532
+ if (previousValue in config2) {
144533
+ newValue = config2[previousValue];
144534
+ } else if ("*" in config2) {
144535
+ newValue = config2["*"];
144536
+ } else {
144537
+ return match2;
143591
144538
  }
143592
- } catch (e) {
143593
- if (!res) {
143594
- if (options.errorHandler) {
143595
- res = await options.errorHandler(req ? e : toRequestError(e));
143596
- if (!res) {
143597
- return;
143598
- }
143599
- } else if (!req) {
143600
- res = handleRequestError();
143601
- } else {
143602
- res = handleFetchError2(e);
143603
- }
144539
+ if (newValue) {
144540
+ return prefix + newValue;
143604
144541
  } else {
143605
- return handleResponseError(e, outgoing);
144542
+ return "";
143606
144543
  }
144544
+ });
144545
+ }
144546
+ function hasPort(host) {
144547
+ return !!~host.indexOf(":");
144548
+ }
144549
+ function getPath2(url2) {
144550
+ if (url2 === "" || url2?.startsWith("?")) {
144551
+ return url2;
143607
144552
  }
143608
- try {
143609
- return await responseViaResponseObject(res, outgoing, options);
143610
- } catch (e) {
143611
- return handleResponseError(e, outgoing);
144553
+ const u = toURL(url2);
144554
+ return `${u.pathname ?? ""}${u.search ?? ""}`;
144555
+ }
144556
+ function toURL(url2) {
144557
+ if (url2 instanceof URL) {
144558
+ return url2;
144559
+ } else if (typeof url2 === "object" && "href" in url2 && typeof url2.href === "string") {
144560
+ url2 = url2.href;
143612
144561
  }
143613
- };
143614
- }, createAdaptorServer = (options) => {
143615
- const fetchCallback = options.fetch;
143616
- const requestListener = getRequestListener(fetchCallback, {
143617
- hostname: options.hostname,
143618
- overrideGlobalObjects: options.overrideGlobalObjects,
143619
- autoCleanupIncoming: options.autoCleanupIncoming
144562
+ if (!url2) {
144563
+ url2 = "";
144564
+ }
144565
+ if (typeof url2 != "string") {
144566
+ url2 = `${url2}`;
144567
+ }
144568
+ if (url2.startsWith("//")) {
144569
+ url2 = `http://base.invalid${url2}`;
144570
+ }
144571
+ return new URL(url2, "http://base.invalid");
144572
+ }
144573
+ function required2(port, protocol) {
144574
+ protocol = protocol.split(":")[0];
144575
+ port = +port;
144576
+ if (!port)
144577
+ return false;
144578
+ switch (protocol) {
144579
+ case "http":
144580
+ case "ws":
144581
+ return port !== 80;
144582
+ case "https":
144583
+ case "wss":
144584
+ return port !== 443;
144585
+ }
144586
+ return port !== 0;
144587
+ }
144588
+ });
144589
+
144590
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-outgoing.js
144591
+ var require_web_outgoing = __commonJS((exports) => {
144592
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
144593
+ if (k2 === undefined)
144594
+ k2 = k;
144595
+ var desc = Object.getOwnPropertyDescriptor(m, k);
144596
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
144597
+ desc = { enumerable: true, get: function() {
144598
+ return m[k];
144599
+ } };
144600
+ }
144601
+ Object.defineProperty(o, k2, desc);
144602
+ } : function(o, m, k, k2) {
144603
+ if (k2 === undefined)
144604
+ k2 = k;
144605
+ o[k2] = m[k];
143620
144606
  });
143621
- const createServer = options.createServer || createServerHTTP;
143622
- const server = createServer(options.serverOptions || {}, requestListener);
143623
- return server;
143624
- }, serve = (options, listeningListener) => {
143625
- const server = createAdaptorServer(options);
143626
- server.listen(options?.port ?? 3000, options.hostname, () => {
143627
- const serverInfo = server.address();
143628
- listeningListener && listeningListener(serverInfo);
144607
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
144608
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
144609
+ } : function(o, v) {
144610
+ o["default"] = v;
143629
144611
  });
143630
- return server;
143631
- };
143632
- var init_dist2 = __esm(() => {
143633
- RequestError = class extends Error {
143634
- constructor(message, options) {
143635
- super(message, options);
143636
- this.name = "RequestError";
144612
+ var __importStar = exports && exports.__importStar || function() {
144613
+ var ownKeys = function(o) {
144614
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
144615
+ var ar = [];
144616
+ for (var k in o2)
144617
+ if (Object.prototype.hasOwnProperty.call(o2, k))
144618
+ ar[ar.length] = k;
144619
+ return ar;
144620
+ };
144621
+ return ownKeys(o);
144622
+ };
144623
+ return function(mod4) {
144624
+ if (mod4 && mod4.__esModule)
144625
+ return mod4;
144626
+ var result = {};
144627
+ if (mod4 != null) {
144628
+ for (var k = ownKeys(mod4), i = 0;i < k.length; i++)
144629
+ if (k[i] !== "default")
144630
+ __createBinding(result, mod4, k[i]);
144631
+ }
144632
+ __setModuleDefault(result, mod4);
144633
+ return result;
144634
+ };
144635
+ }();
144636
+ Object.defineProperty(exports, "__esModule", { value: true });
144637
+ exports.OUTGOING_PASSES = undefined;
144638
+ exports.removeChunked = removeChunked;
144639
+ exports.setConnection = setConnection;
144640
+ exports.setRedirectHostRewrite = setRedirectHostRewrite;
144641
+ exports.writeHeaders = writeHeaders;
144642
+ exports.writeStatusCode = writeStatusCode;
144643
+ var common = __importStar(require_common8());
144644
+ var redirectRegex = /^201|30(1|2|7|8)$/;
144645
+ function removeChunked(_req, _res, proxyRes) {
144646
+ delete proxyRes.headers["transfer-encoding"];
144647
+ }
144648
+ function setConnection(req, _res, proxyRes) {
144649
+ if (req.httpVersion === "1.0") {
144650
+ proxyRes.headers["connection"] = req.headers["connection"] || "close";
144651
+ } else if (req.httpVersion !== "2.0" && !proxyRes.headers["connection"]) {
144652
+ proxyRes.headers["connection"] = req.headers["connection"] || "keep-alive";
144653
+ }
144654
+ }
144655
+ function setRedirectHostRewrite(req, _res, proxyRes, options) {
144656
+ if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(`${proxyRes.statusCode}`)) {
144657
+ const target = common.toURL(options.target);
144658
+ const location = proxyRes.headers["location"];
144659
+ if (typeof location != "string") {
144660
+ return;
144661
+ }
144662
+ const u = common.toURL(location);
144663
+ if (target.host != u.host) {
144664
+ return;
144665
+ }
144666
+ if (options.hostRewrite) {
144667
+ u.host = options.hostRewrite;
144668
+ } else if (options.autoRewrite) {
144669
+ u.host = req.headers[":authority"] ?? req.headers["host"] ?? "";
144670
+ }
144671
+ if (options.protocolRewrite) {
144672
+ u.protocol = options.protocolRewrite;
144673
+ }
144674
+ proxyRes.headers["location"] = u.toString();
143637
144675
  }
143638
- };
143639
- GlobalRequest = global.Request;
143640
- Request2 = class extends GlobalRequest {
143641
- constructor(input, options) {
143642
- if (typeof input === "object" && getRequestCache in input) {
143643
- input = input[getRequestCache]();
144676
+ }
144677
+ function writeHeaders(_req, res, proxyRes, options) {
144678
+ const rewriteCookieDomainConfig = typeof options.cookieDomainRewrite === "string" ? { "*": options.cookieDomainRewrite } : options.cookieDomainRewrite;
144679
+ const rewriteCookiePathConfig = typeof options.cookiePathRewrite === "string" ? { "*": options.cookiePathRewrite } : options.cookiePathRewrite;
144680
+ const preserveHeaderKeyCase = options.preserveHeaderKeyCase;
144681
+ const setHeader = (key, header) => {
144682
+ if (header == undefined) {
144683
+ return;
144684
+ }
144685
+ if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") {
144686
+ header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
143644
144687
  }
143645
- if (typeof options?.body?.getReader !== "undefined") {
143646
- options.duplex ??= "half";
144688
+ if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") {
144689
+ header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
144690
+ }
144691
+ res.setHeader(String(key).trim(), header);
144692
+ };
144693
+ let rawHeaderKeyMap;
144694
+ if (preserveHeaderKeyCase && proxyRes.rawHeaders != null) {
144695
+ rawHeaderKeyMap = {};
144696
+ for (let i = 0;i < proxyRes.rawHeaders.length; i += 2) {
144697
+ const key = proxyRes.rawHeaders[i];
144698
+ rawHeaderKeyMap[key.toLowerCase()] = key;
143647
144699
  }
143648
- super(input, options);
143649
144700
  }
143650
- };
143651
- wrapBodyStream = Symbol("wrapBodyStream");
143652
- getRequestCache = Symbol("getRequestCache");
143653
- requestCache = Symbol("requestCache");
143654
- incomingKey = Symbol("incomingKey");
143655
- urlKey = Symbol("urlKey");
143656
- headersKey = Symbol("headersKey");
143657
- abortControllerKey = Symbol("abortControllerKey");
143658
- getAbortController = Symbol("getAbortController");
143659
- requestPrototype = {
143660
- get method() {
143661
- return this[incomingKey].method || "GET";
143662
- },
143663
- get url() {
143664
- return this[urlKey];
143665
- },
143666
- get headers() {
143667
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
143668
- },
143669
- [getAbortController]() {
143670
- this[getRequestCache]();
143671
- return this[abortControllerKey];
143672
- },
143673
- [getRequestCache]() {
143674
- this[abortControllerKey] ||= new AbortController;
143675
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
144701
+ for (const key0 in proxyRes.headers) {
144702
+ let key = key0;
144703
+ if (_req.httpVersionMajor > 1 && (key === "connection" || key === "keep-alive")) {
144704
+ continue;
144705
+ }
144706
+ const header = proxyRes.headers[key];
144707
+ if (preserveHeaderKeyCase && rawHeaderKeyMap) {
144708
+ key = rawHeaderKeyMap[key] ?? key;
144709
+ }
144710
+ setHeader(key, header);
143676
144711
  }
144712
+ }
144713
+ function writeStatusCode(_req, res, proxyRes) {
144714
+ res.statusCode = proxyRes.statusCode;
144715
+ if (proxyRes.statusMessage && _req.httpVersionMajor === 1) {
144716
+ res.statusMessage = proxyRes.statusMessage;
144717
+ }
144718
+ }
144719
+ exports.OUTGOING_PASSES = {
144720
+ removeChunked,
144721
+ setConnection,
144722
+ setRedirectHostRewrite,
144723
+ writeHeaders,
144724
+ writeStatusCode
143677
144725
  };
143678
- [
143679
- "body",
143680
- "bodyUsed",
143681
- "cache",
143682
- "credentials",
143683
- "destination",
143684
- "integrity",
143685
- "mode",
143686
- "redirect",
143687
- "referrer",
143688
- "referrerPolicy",
143689
- "signal",
143690
- "keepalive"
143691
- ].forEach((k) => {
143692
- Object.defineProperty(requestPrototype, k, {
143693
- get() {
143694
- return this[getRequestCache]()[k];
143695
- }
143696
- });
144726
+ });
144727
+
144728
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-incoming.js
144729
+ var require_web_incoming = __commonJS((exports) => {
144730
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
144731
+ if (k2 === undefined)
144732
+ k2 = k;
144733
+ var desc = Object.getOwnPropertyDescriptor(m, k);
144734
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
144735
+ desc = { enumerable: true, get: function() {
144736
+ return m[k];
144737
+ } };
144738
+ }
144739
+ Object.defineProperty(o, k2, desc);
144740
+ } : function(o, m, k, k2) {
144741
+ if (k2 === undefined)
144742
+ k2 = k;
144743
+ o[k2] = m[k];
143697
144744
  });
143698
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
143699
- Object.defineProperty(requestPrototype, k, {
143700
- value: function() {
143701
- return this[getRequestCache]()[k]();
143702
- }
143703
- });
144745
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
144746
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
144747
+ } : function(o, v) {
144748
+ o["default"] = v;
143704
144749
  });
143705
- Object.setPrototypeOf(requestPrototype, Request2.prototype);
143706
- responseCache = Symbol("responseCache");
143707
- getResponseCache = Symbol("getResponseCache");
143708
- cacheKey = Symbol("cache");
143709
- GlobalResponse = global.Response;
143710
- Response2 = class _Response {
143711
- #body;
143712
- #init;
143713
- [getResponseCache]() {
143714
- delete this[cacheKey];
143715
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
144750
+ var __importStar = exports && exports.__importStar || function() {
144751
+ var ownKeys = function(o) {
144752
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
144753
+ var ar = [];
144754
+ for (var k in o2)
144755
+ if (Object.prototype.hasOwnProperty.call(o2, k))
144756
+ ar[ar.length] = k;
144757
+ return ar;
144758
+ };
144759
+ return ownKeys(o);
144760
+ };
144761
+ return function(mod4) {
144762
+ if (mod4 && mod4.__esModule)
144763
+ return mod4;
144764
+ var result = {};
144765
+ if (mod4 != null) {
144766
+ for (var k = ownKeys(mod4), i = 0;i < k.length; i++)
144767
+ if (k[i] !== "default")
144768
+ __createBinding(result, mod4, k[i]);
144769
+ }
144770
+ __setModuleDefault(result, mod4);
144771
+ return result;
144772
+ };
144773
+ }();
144774
+ Object.defineProperty(exports, "__esModule", { value: true });
144775
+ exports.WEB_PASSES = undefined;
144776
+ exports.deleteLength = deleteLength;
144777
+ exports.timeout = timeout;
144778
+ exports.XHeaders = XHeaders;
144779
+ exports.stream = stream;
144780
+ var http = __importStar(__require("node:http"));
144781
+ var https = __importStar(__require("node:https"));
144782
+ var followRedirects = __importStar(require_follow_redirects());
144783
+ var common = __importStar(require_common8());
144784
+ var web_outgoing_1 = require_web_outgoing();
144785
+ var node_stream_1 = __require("node:stream");
144786
+ var web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
144787
+ var nativeAgents = { http, https };
144788
+ function deleteLength(req) {
144789
+ if ((req.method === "DELETE" || req.method === "OPTIONS") && !req.headers["content-length"]) {
144790
+ req.headers["content-length"] = "0";
144791
+ delete req.headers["transfer-encoding"];
144792
+ }
144793
+ }
144794
+ function timeout(req, _res, options) {
144795
+ if (options.timeout) {
144796
+ req.socket.setTimeout(options.timeout);
144797
+ }
144798
+ }
144799
+ function XHeaders(req, _res, options) {
144800
+ if (!options.xfwd) {
144801
+ return;
143716
144802
  }
143717
- constructor(body, init) {
143718
- let headers;
143719
- this.#body = body;
143720
- if (init instanceof _Response) {
143721
- const cachedGlobalResponse = init[responseCache];
143722
- if (cachedGlobalResponse) {
143723
- this.#init = cachedGlobalResponse;
143724
- this[getResponseCache]();
144803
+ const encrypted = common.hasEncryptedConnection(req);
144804
+ const values = {
144805
+ for: req.connection.remoteAddress || req.socket.remoteAddress,
144806
+ port: common.getPort(req),
144807
+ proto: encrypted ? "https" : "http"
144808
+ };
144809
+ for (const header of ["for", "port", "proto"]) {
144810
+ req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
144811
+ }
144812
+ req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers["host"] || "";
144813
+ }
144814
+ function stream(req, res, options, _, server, cb) {
144815
+ server.emit("start", req, res, options.target || options.forward);
144816
+ if (options.fetch || options.fetchOptions || process.env.FORCE_FETCH_PATH === "true") {
144817
+ return stream2(req, res, options, _, server, cb);
144818
+ }
144819
+ const agents = options.followRedirects ? followRedirects : nativeAgents;
144820
+ const http2 = agents.http;
144821
+ const https2 = agents.https;
144822
+ if (options.forward) {
144823
+ const proto2 = options.forward.protocol === "https:" ? https2 : http2;
144824
+ const outgoingOptions2 = common.setupOutgoing(options.ssl || {}, options, req, "forward");
144825
+ const forwardReq = proto2.request(outgoingOptions2);
144826
+ const forwardError = createErrorHandler(forwardReq, options.forward);
144827
+ req.on("error", forwardError);
144828
+ forwardReq.on("error", forwardError);
144829
+ (options.buffer || req).pipe(forwardReq);
144830
+ if (!options.target) {
144831
+ return res.end();
144832
+ }
144833
+ }
144834
+ const proto = options.target.protocol === "https:" ? https2 : http2;
144835
+ const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
144836
+ const proxyReq = proto.request(outgoingOptions);
144837
+ proxyReq.on("socket", (socket) => {
144838
+ if (server && !proxyReq.getHeader("expect")) {
144839
+ server.emit("proxyReq", proxyReq, req, res, options, socket);
144840
+ }
144841
+ });
144842
+ if (options.proxyTimeout) {
144843
+ proxyReq.setTimeout(options.proxyTimeout, () => {
144844
+ proxyReq.destroy();
144845
+ });
144846
+ }
144847
+ res.on("close", () => {
144848
+ const aborted2 = !res.writableFinished;
144849
+ if (aborted2) {
144850
+ proxyReq.destroy();
144851
+ }
144852
+ });
144853
+ const proxyError = createErrorHandler(proxyReq, options.target);
144854
+ req.on("error", proxyError);
144855
+ proxyReq.on("error", proxyError);
144856
+ function createErrorHandler(proxyReq2, url2) {
144857
+ return (err) => {
144858
+ if (req.socket.destroyed && err.code === "ECONNRESET") {
144859
+ server.emit("econnreset", err, req, res, url2);
144860
+ proxyReq2.destroy();
143725
144861
  return;
144862
+ }
144863
+ if (cb) {
144864
+ cb(err, req, res, url2);
143726
144865
  } else {
143727
- this.#init = init.#init;
143728
- headers = new Headers(init.#init.headers);
144866
+ server.emit("error", err, req, res, url2);
144867
+ }
144868
+ };
144869
+ }
144870
+ (options.buffer || req).pipe(proxyReq);
144871
+ proxyReq.on("response", (proxyRes) => {
144872
+ server?.emit("proxyRes", proxyRes, req, res);
144873
+ if (!res.headersSent && !options.selfHandleResponse) {
144874
+ for (const pass of web_o) {
144875
+ pass(req, res, proxyRes, options);
144876
+ }
144877
+ }
144878
+ if (!res.finished) {
144879
+ proxyRes.on("end", () => {
144880
+ server?.emit("end", req, res, proxyRes);
144881
+ });
144882
+ if (!options.selfHandleResponse) {
144883
+ proxyRes.pipe(res);
143729
144884
  }
143730
144885
  } else {
143731
- this.#init = init;
144886
+ server?.emit("end", req, res, proxyRes);
143732
144887
  }
143733
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
143734
- headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
143735
- this[cacheKey] = [init?.status || 200, body, headers];
144888
+ });
144889
+ }
144890
+ async function stream2(req, res, options, _, server, cb) {
144891
+ const handleError2 = (err, target) => {
144892
+ const e = err;
144893
+ if (e.code === undefined && e.cause?.code) {
144894
+ e.code = e.cause.code;
143736
144895
  }
143737
- }
143738
- get headers() {
143739
- const cache = this[cacheKey];
143740
- if (cache) {
143741
- if (!(cache[2] instanceof Headers)) {
143742
- cache[2] = new Headers(cache[2]);
144896
+ if (cb) {
144897
+ cb(err, req, res, target);
144898
+ } else {
144899
+ server.emit("error", err, req, res, target);
144900
+ }
144901
+ };
144902
+ req.on("error", (err) => {
144903
+ if (req.socket.destroyed && err.code === "ECONNRESET") {
144904
+ const target = options.target || options.forward;
144905
+ if (target) {
144906
+ server.emit("econnreset", err, req, res, target);
143743
144907
  }
143744
- return cache[2];
144908
+ return;
144909
+ }
144910
+ handleError2(err);
144911
+ });
144912
+ const customFetch = options.fetch || fetch;
144913
+ const fetchOptions = options.fetchOptions ?? {};
144914
+ const prepareRequest = (outgoing) => {
144915
+ const requestOptions2 = {
144916
+ method: outgoing.method,
144917
+ ...fetchOptions.requestOptions
144918
+ };
144919
+ const headers = new Headers(fetchOptions.requestOptions?.headers);
144920
+ if (!fetchOptions.requestOptions?.headers && outgoing.headers) {
144921
+ for (const [key, value] of Object.entries(outgoing.headers)) {
144922
+ if (typeof key === "string") {
144923
+ if (Array.isArray(value)) {
144924
+ for (const v of value) {
144925
+ headers.append(key, v);
144926
+ }
144927
+ } else if (value != null) {
144928
+ headers.append(key, value);
144929
+ }
144930
+ }
144931
+ }
144932
+ }
144933
+ if (options.auth) {
144934
+ headers.set("authorization", `Basic ${Buffer.from(options.auth).toString("base64")}`);
144935
+ }
144936
+ if (options.proxyTimeout) {
144937
+ requestOptions2.signal = AbortSignal.timeout(options.proxyTimeout);
144938
+ }
144939
+ requestOptions2.headers = headers;
144940
+ if (options.buffer) {
144941
+ requestOptions2.body = options.buffer;
144942
+ } else if (req.method !== "GET" && req.method !== "HEAD") {
144943
+ requestOptions2.body = req;
144944
+ requestOptions2.duplex = "half";
144945
+ }
144946
+ return requestOptions2;
144947
+ };
144948
+ if (options.forward) {
144949
+ const outgoingOptions2 = common.setupOutgoing(options.ssl || {}, options, req, "forward");
144950
+ const requestOptions2 = prepareRequest(outgoingOptions2);
144951
+ let targetUrl2 = new URL(outgoingOptions2.url).origin + outgoingOptions2.path;
144952
+ if (targetUrl2.startsWith("ws")) {
144953
+ targetUrl2 = targetUrl2.replace("ws", "http");
144954
+ }
144955
+ if (fetchOptions.onBeforeRequest) {
144956
+ try {
144957
+ await fetchOptions.onBeforeRequest(requestOptions2, req, res, options);
144958
+ } catch (err) {
144959
+ handleError2(err, options.forward);
144960
+ return;
144961
+ }
144962
+ }
144963
+ try {
144964
+ const result = await customFetch(targetUrl2, requestOptions2);
144965
+ if (fetchOptions.onAfterResponse) {
144966
+ try {
144967
+ await fetchOptions.onAfterResponse(result, req, res, options);
144968
+ } catch (err) {
144969
+ handleError2(err, options.forward);
144970
+ return;
144971
+ }
144972
+ }
144973
+ } catch (err) {
144974
+ handleError2(err, options.forward);
144975
+ }
144976
+ if (!options.target) {
144977
+ return res.end();
143745
144978
  }
143746
- return this[getResponseCache]().headers;
143747
144979
  }
143748
- get status() {
143749
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
144980
+ const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
144981
+ const requestOptions = prepareRequest(outgoingOptions);
144982
+ let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
144983
+ if (targetUrl.startsWith("ws")) {
144984
+ targetUrl = targetUrl.replace("ws", "http");
143750
144985
  }
143751
- get ok() {
143752
- const status = this.status;
143753
- return status >= 200 && status < 300;
144986
+ if (fetchOptions.onBeforeRequest) {
144987
+ try {
144988
+ await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
144989
+ } catch (err) {
144990
+ handleError2(err, options.target);
144991
+ return;
144992
+ }
144993
+ }
144994
+ try {
144995
+ const response = await customFetch(targetUrl, requestOptions);
144996
+ if (fetchOptions.onAfterResponse) {
144997
+ try {
144998
+ await fetchOptions.onAfterResponse(response, req, res, options);
144999
+ } catch (err) {
145000
+ handleError2(err, options.target);
145001
+ return;
145002
+ }
145003
+ }
145004
+ const fakeProxyRes = {
145005
+ statusCode: response.status,
145006
+ statusMessage: response.statusText,
145007
+ headers: Object.fromEntries(response.headers.entries()),
145008
+ rawHeaders: Object.entries(response.headers).flatMap(([key, value]) => {
145009
+ if (Array.isArray(value)) {
145010
+ return value.flatMap((v) => v != null ? [key, v] : []);
145011
+ }
145012
+ return value != null ? [key, value] : [];
145013
+ })
145014
+ };
145015
+ server?.emit("proxyRes", fakeProxyRes, req, res);
145016
+ if (!res.headersSent && !options.selfHandleResponse) {
145017
+ for (const pass of web_o) {
145018
+ pass(req, res, fakeProxyRes, options);
145019
+ }
145020
+ }
145021
+ if (!res.writableEnded) {
145022
+ const nodeStream = response.body ? node_stream_1.Readable.from(response.body) : null;
145023
+ if (nodeStream) {
145024
+ nodeStream.on("error", (err) => {
145025
+ handleError2(err, options.target);
145026
+ });
145027
+ nodeStream.on("end", () => {
145028
+ server?.emit("end", req, res, fakeProxyRes);
145029
+ });
145030
+ if (!options.selfHandleResponse) {
145031
+ nodeStream.pipe(res, { end: true });
145032
+ } else {
145033
+ nodeStream.resume();
145034
+ }
145035
+ } else {
145036
+ server?.emit("end", req, res, fakeProxyRes);
145037
+ }
145038
+ } else {
145039
+ server?.emit("end", req, res, fakeProxyRes);
145040
+ }
145041
+ } catch (err) {
145042
+ handleError2(err, options.target);
145043
+ }
145044
+ }
145045
+ exports.WEB_PASSES = { deleteLength, timeout, XHeaders, stream };
145046
+ });
145047
+
145048
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/http-proxy/passes/ws-incoming.js
145049
+ var require_ws_incoming = __commonJS((exports) => {
145050
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
145051
+ if (k2 === undefined)
145052
+ k2 = k;
145053
+ var desc = Object.getOwnPropertyDescriptor(m, k);
145054
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
145055
+ desc = { enumerable: true, get: function() {
145056
+ return m[k];
145057
+ } };
143754
145058
  }
145059
+ Object.defineProperty(o, k2, desc);
145060
+ } : function(o, m, k, k2) {
145061
+ if (k2 === undefined)
145062
+ k2 = k;
145063
+ o[k2] = m[k];
145064
+ });
145065
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
145066
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
145067
+ } : function(o, v) {
145068
+ o["default"] = v;
145069
+ });
145070
+ var __importStar = exports && exports.__importStar || function() {
145071
+ var ownKeys = function(o) {
145072
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
145073
+ var ar = [];
145074
+ for (var k in o2)
145075
+ if (Object.prototype.hasOwnProperty.call(o2, k))
145076
+ ar[ar.length] = k;
145077
+ return ar;
145078
+ };
145079
+ return ownKeys(o);
145080
+ };
145081
+ return function(mod4) {
145082
+ if (mod4 && mod4.__esModule)
145083
+ return mod4;
145084
+ var result = {};
145085
+ if (mod4 != null) {
145086
+ for (var k = ownKeys(mod4), i = 0;i < k.length; i++)
145087
+ if (k[i] !== "default")
145088
+ __createBinding(result, mod4, k[i]);
145089
+ }
145090
+ __setModuleDefault(result, mod4);
145091
+ return result;
145092
+ };
145093
+ }();
145094
+ var __importDefault = exports && exports.__importDefault || function(mod4) {
145095
+ return mod4 && mod4.__esModule ? mod4 : { default: mod4 };
143755
145096
  };
143756
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
143757
- Object.defineProperty(Response2.prototype, k, {
143758
- get() {
143759
- return this[getResponseCache]()[k];
145097
+ Object.defineProperty(exports, "__esModule", { value: true });
145098
+ exports.WS_PASSES = undefined;
145099
+ exports.numOpenSockets = numOpenSockets;
145100
+ exports.checkMethodAndHeader = checkMethodAndHeader;
145101
+ exports.XHeaders = XHeaders;
145102
+ exports.stream = stream;
145103
+ var http = __importStar(__require("node:http"));
145104
+ var https = __importStar(__require("node:https"));
145105
+ var common = __importStar(require_common8());
145106
+ var web_outgoing_1 = require_web_outgoing();
145107
+ var debug_1 = __importDefault(require_src3());
145108
+ var log = (0, debug_1.default)("http-proxy-3:ws-incoming");
145109
+ var web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
145110
+ function createSocketCounter(name21) {
145111
+ let sockets = new Set;
145112
+ return ({ add, rm: rm2 } = {}) => {
145113
+ if (add) {
145114
+ if (!add.id) {
145115
+ add.id = Math.random();
145116
+ }
145117
+ if (!sockets.has(add.id)) {
145118
+ sockets.add(add.id);
145119
+ }
145120
+ }
145121
+ if (rm2) {
145122
+ if (!rm2.id) {
145123
+ rm2.id = Math.random();
145124
+ }
145125
+ if (sockets.has(rm2.id)) {
145126
+ sockets.delete(rm2.id);
145127
+ }
145128
+ }
145129
+ log("socket counter:", { [name21]: sockets.size }, add ? "add" : rm2 ? "rm" : "");
145130
+ return sockets.size;
145131
+ };
145132
+ }
145133
+ var socketCounter = createSocketCounter("socket");
145134
+ var proxySocketCounter = createSocketCounter("proxySocket");
145135
+
145136
+ class MockResponse {
145137
+ constructor() {
145138
+ this.headers = {};
145139
+ this.statusCode = 200;
145140
+ this.statusMessage = "";
145141
+ }
145142
+ setHeader(key, value) {
145143
+ this.headers[key] = value;
145144
+ return this;
145145
+ }
145146
+ }
145147
+ function numOpenSockets() {
145148
+ return socketCounter() + proxySocketCounter();
145149
+ }
145150
+ function checkMethodAndHeader(req, socket) {
145151
+ log("websocket: checkMethodAndHeader");
145152
+ if (req.method !== "GET" || !req.headers.upgrade) {
145153
+ socket.destroy();
145154
+ return true;
145155
+ }
145156
+ if (req.headers.upgrade.toLowerCase() !== "websocket") {
145157
+ socket.destroy();
145158
+ return true;
145159
+ }
145160
+ }
145161
+ function XHeaders(req, _socket, options) {
145162
+ if (!options.xfwd)
145163
+ return;
145164
+ log("websocket: XHeaders");
145165
+ const values = {
145166
+ for: req.connection.remoteAddress || req.socket.remoteAddress,
145167
+ port: common.getPort(req),
145168
+ proto: common.hasEncryptedConnection(req) ? "wss" : "ws"
145169
+ };
145170
+ for (const header of ["for", "port", "proto"]) {
145171
+ req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
145172
+ }
145173
+ }
145174
+ function stream(req, socket, options, head, server, cb) {
145175
+ log("websocket: new stream");
145176
+ const proxySockets = [];
145177
+ socketCounter({ add: socket });
145178
+ const cleanUpProxySockets = () => {
145179
+ for (const p4 of proxySockets) {
145180
+ p4.end();
143760
145181
  }
145182
+ };
145183
+ socket.on("close", () => {
145184
+ socketCounter({ rm: socket });
145185
+ cleanUpProxySockets();
143761
145186
  });
143762
- });
143763
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
143764
- Object.defineProperty(Response2.prototype, k, {
143765
- value: function() {
143766
- return this[getResponseCache]()[k]();
145187
+ socket.on("error", cleanUpProxySockets);
145188
+ const createHttpHeader = (line, headers) => {
145189
+ return Object.keys(headers).reduce((head2, key) => {
145190
+ const value = headers[key];
145191
+ if (!Array.isArray(value)) {
145192
+ head2.push(key + ": " + value);
145193
+ return head2;
145194
+ }
145195
+ for (let i = 0;i < value.length; i++) {
145196
+ head2.push(key + ": " + value[i]);
145197
+ }
145198
+ return head2;
145199
+ }, [line]).join(`\r
145200
+ `) + `\r
145201
+ \r
145202
+ `;
145203
+ };
145204
+ common.setupSocket(socket);
145205
+ if (head && head.length) {
145206
+ socket.unshift(head);
145207
+ }
145208
+ const proto = common.isSSL.test(options.target.protocol) ? https : http;
145209
+ const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
145210
+ const proxyReq = proto.request(outgoingOptions);
145211
+ if (server) {
145212
+ server.emit("proxyReqWs", proxyReq, req, socket, options, head);
145213
+ }
145214
+ proxyReq.on("error", onOutgoingError);
145215
+ proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
145216
+ log("upgrade");
145217
+ proxySocketCounter({ add: proxySocket });
145218
+ proxySockets.push(proxySocket);
145219
+ proxySocket.on("close", () => {
145220
+ proxySocketCounter({ rm: proxySocket });
145221
+ });
145222
+ proxySocket.on("error", onOutgoingError);
145223
+ proxySocket.on("end", () => {
145224
+ server.emit("close", proxyRes, proxySocket, proxyHead);
145225
+ });
145226
+ proxySocket.on("close", () => {
145227
+ socket.end();
145228
+ });
145229
+ common.setupSocket(proxySocket);
145230
+ if (proxyHead && proxyHead.length) {
145231
+ proxySocket.unshift(proxyHead);
145232
+ }
145233
+ socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
145234
+ proxySocket.pipe(socket).pipe(proxySocket);
145235
+ server.emit("open", proxySocket);
145236
+ });
145237
+ function onOutgoingError(err) {
145238
+ if (cb) {
145239
+ cb(err, req, socket);
145240
+ } else {
145241
+ server.emit("error", err, req, socket);
145242
+ }
145243
+ socket.destroySoon();
145244
+ }
145245
+ proxyReq.on("response", (proxyRes) => {
145246
+ log("got non-ws HTTP response", {
145247
+ statusCode: proxyRes.statusCode,
145248
+ statusMessage: proxyRes.statusMessage
145249
+ });
145250
+ const res = new MockResponse;
145251
+ for (const pass of web_o) {
145252
+ pass(req, res, proxyRes, options);
145253
+ }
145254
+ let writeChunk = (chunk) => {
145255
+ socket.write(chunk);
145256
+ };
145257
+ if (req.httpVersion === "1.1" && proxyRes.headers["content-length"] === undefined) {
145258
+ res.headers["transfer-encoding"] = "chunked";
145259
+ writeChunk = (chunk) => {
145260
+ socket.write(chunk.length.toString(16));
145261
+ socket.write(`\r
145262
+ `);
145263
+ socket.write(chunk);
145264
+ socket.write(`\r
145265
+ `);
145266
+ };
145267
+ }
145268
+ const proxyHead = createHttpHeader(`HTTP/${req.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}`, res.headers);
145269
+ if (!socket.destroyed) {
145270
+ socket.write(proxyHead);
145271
+ proxyRes.on("data", (chunk) => {
145272
+ writeChunk(chunk);
145273
+ });
145274
+ proxyRes.on("end", () => {
145275
+ writeChunk("");
145276
+ socket.destroySoon();
145277
+ });
145278
+ } else {
145279
+ proxyRes.resume();
143767
145280
  }
143768
145281
  });
145282
+ proxyReq.end();
145283
+ }
145284
+ exports.WS_PASSES = { checkMethodAndHeader, XHeaders, stream };
145285
+ });
145286
+
145287
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/http-proxy/index.js
145288
+ var require_http_proxy = __commonJS((exports) => {
145289
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
145290
+ if (k2 === undefined)
145291
+ k2 = k;
145292
+ var desc = Object.getOwnPropertyDescriptor(m, k);
145293
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
145294
+ desc = { enumerable: true, get: function() {
145295
+ return m[k];
145296
+ } };
145297
+ }
145298
+ Object.defineProperty(o, k2, desc);
145299
+ } : function(o, m, k, k2) {
145300
+ if (k2 === undefined)
145301
+ k2 = k;
145302
+ o[k2] = m[k];
143769
145303
  });
143770
- Object.setPrototypeOf(Response2, GlobalResponse);
143771
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
143772
- if (typeof global.crypto === "undefined") {
143773
- global.crypto = crypto2;
145304
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
145305
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
145306
+ } : function(o, v) {
145307
+ o["default"] = v;
145308
+ });
145309
+ var __importStar = exports && exports.__importStar || function() {
145310
+ var ownKeys = function(o) {
145311
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
145312
+ var ar = [];
145313
+ for (var k in o2)
145314
+ if (Object.prototype.hasOwnProperty.call(o2, k))
145315
+ ar[ar.length] = k;
145316
+ return ar;
145317
+ };
145318
+ return ownKeys(o);
145319
+ };
145320
+ return function(mod4) {
145321
+ if (mod4 && mod4.__esModule)
145322
+ return mod4;
145323
+ var result = {};
145324
+ if (mod4 != null) {
145325
+ for (var k = ownKeys(mod4), i = 0;i < k.length; i++)
145326
+ if (k[i] !== "default")
145327
+ __createBinding(result, mod4, k[i]);
145328
+ }
145329
+ __setModuleDefault(result, mod4);
145330
+ return result;
145331
+ };
145332
+ }();
145333
+ var __importDefault = exports && exports.__importDefault || function(mod4) {
145334
+ return mod4 && mod4.__esModule ? mod4 : { default: mod4 };
145335
+ };
145336
+ Object.defineProperty(exports, "__esModule", { value: true });
145337
+ exports.ProxyServer = undefined;
145338
+ var http = __importStar(__require("node:http"));
145339
+ var http2 = __importStar(__require("node:http2"));
145340
+ var web_incoming_1 = require_web_incoming();
145341
+ var ws_incoming_1 = require_ws_incoming();
145342
+ var node_events_1 = __require("node:events");
145343
+ var debug_1 = __importDefault(require_src3());
145344
+ var common_1 = require_common8();
145345
+ var log = (0, debug_1.default)("http-proxy-3");
145346
+
145347
+ class ProxyServer extends node_events_1.EventEmitter {
145348
+ constructor(options = {}) {
145349
+ super();
145350
+ this.createRightProxy = (type) => {
145351
+ log("createRightProxy", { type });
145352
+ return (options2) => {
145353
+ return (...args) => {
145354
+ const req = args[0];
145355
+ log("proxy: ", { type, path: req.url });
145356
+ const res = args[1];
145357
+ const passes = type === "ws" ? this.wsPasses : this.webPasses;
145358
+ if (type == "ws") {
145359
+ res.on("error", (err) => {
145360
+ this.emit("error", err, req, res);
145361
+ });
145362
+ }
145363
+ let counter = args.length - 1;
145364
+ let head;
145365
+ let cb;
145366
+ if (typeof args[counter] === "function") {
145367
+ cb = args[counter];
145368
+ counter--;
145369
+ }
145370
+ let requestOptions;
145371
+ if (!(args[counter] instanceof Buffer) && args[counter] !== res) {
145372
+ requestOptions = { ...options2, ...args[counter] };
145373
+ counter--;
145374
+ } else {
145375
+ requestOptions = { ...options2 };
145376
+ }
145377
+ if (args[counter] instanceof Buffer) {
145378
+ head = args[counter];
145379
+ }
145380
+ for (const e of ["target", "forward"]) {
145381
+ if (typeof requestOptions[e] === "string") {
145382
+ requestOptions[e] = (0, common_1.toURL)(requestOptions[e]);
145383
+ }
145384
+ }
145385
+ if (!requestOptions.target && !requestOptions.forward) {
145386
+ this.emit("error", new Error("Must set target or forward"), req, res);
145387
+ return;
145388
+ }
145389
+ for (const pass of passes) {
145390
+ if (pass(req, res, requestOptions, head, this, cb)) {
145391
+ break;
145392
+ }
145393
+ }
145394
+ };
145395
+ };
145396
+ };
145397
+ this.onError = (err) => {
145398
+ if (this.listeners("error").length === 1) {
145399
+ throw err;
145400
+ }
145401
+ };
145402
+ this.listen = (port, hostname2) => {
145403
+ log("listen", { port, hostname: hostname2 });
145404
+ const requestListener = (req, res) => {
145405
+ this.web(req, res);
145406
+ };
145407
+ this._server = this.options.ssl ? http2.createSecureServer({ ...this.options.ssl, allowHTTP1: true }, requestListener) : http.createServer(requestListener);
145408
+ if (this.options.ws) {
145409
+ this._server.on("upgrade", (req, socket, head) => {
145410
+ this.ws(req, socket, head);
145411
+ });
145412
+ }
145413
+ this._server.listen(port, hostname2);
145414
+ return this;
145415
+ };
145416
+ this.address = () => {
145417
+ return this._server?.address();
145418
+ };
145419
+ this.close = (cb) => {
145420
+ if (this._server == null) {
145421
+ cb?.();
145422
+ return;
145423
+ }
145424
+ this._server.close((err) => {
145425
+ this._server = null;
145426
+ cb?.(err);
145427
+ });
145428
+ };
145429
+ this.before = (type, passName, cb) => {
145430
+ if (type !== "ws" && type !== "web") {
145431
+ throw new Error("type must be `web` or `ws`");
145432
+ }
145433
+ const passes = type === "ws" ? this.wsPasses : this.webPasses;
145434
+ let i = false;
145435
+ passes.forEach((v, idx) => {
145436
+ if (v.name === passName) {
145437
+ i = idx;
145438
+ }
145439
+ });
145440
+ if (i === false) {
145441
+ throw new Error("No such pass");
145442
+ }
145443
+ passes.splice(i, 0, cb);
145444
+ };
145445
+ this.after = (type, passName, cb) => {
145446
+ if (type !== "ws" && type !== "web") {
145447
+ throw new Error("type must be `web` or `ws`");
145448
+ }
145449
+ const passes = type === "ws" ? this.wsPasses : this.webPasses;
145450
+ let i = false;
145451
+ passes.forEach((v, idx) => {
145452
+ if (v.name === passName) {
145453
+ i = idx;
145454
+ }
145455
+ });
145456
+ if (i === false) {
145457
+ throw new Error("No such pass");
145458
+ }
145459
+ passes.splice(i++, 0, cb);
145460
+ };
145461
+ log("creating a ProxyServer", options);
145462
+ options.prependPath = options.prependPath !== false;
145463
+ this.options = options;
145464
+ this.web = this.createRightProxy("web")(options);
145465
+ this.ws = this.createRightProxy("ws")(options);
145466
+ this.webPasses = Object.values(web_incoming_1.WEB_PASSES);
145467
+ this.wsPasses = Object.values(ws_incoming_1.WS_PASSES);
145468
+ this.on("error", this.onError);
145469
+ }
145470
+ static createProxyServer(options) {
145471
+ return new ProxyServer(options);
145472
+ }
145473
+ static createServer(options) {
145474
+ return new ProxyServer(options);
145475
+ }
145476
+ static createProxy(options) {
145477
+ return new ProxyServer(options);
145478
+ }
143774
145479
  }
143775
- outgoingEnded = Symbol("outgoingEnded");
145480
+ exports.ProxyServer = ProxyServer;
145481
+ });
145482
+
145483
+ // ../../node_modules/.bun/http-proxy-3@1.23.2/node_modules/http-proxy-3/dist/lib/index.js
145484
+ var require_lib9 = __commonJS((exports) => {
145485
+ Object.defineProperty(exports, "__esModule", { value: true });
145486
+ exports.numOpenSockets = exports.ProxyServer = undefined;
145487
+ exports.createProxyServer = createProxyServer;
145488
+ exports.createServer = createProxyServer;
145489
+ exports.createProxy = createProxyServer;
145490
+ var index_1 = require_http_proxy();
145491
+ Object.defineProperty(exports, "ProxyServer", { enumerable: true, get: function() {
145492
+ return index_1.ProxyServer;
145493
+ } });
145494
+ var ws_incoming_1 = require_ws_incoming();
145495
+ Object.defineProperty(exports, "numOpenSockets", { enumerable: true, get: function() {
145496
+ return ws_incoming_1.numOpenSockets;
145497
+ } });
145498
+ function createProxyServer(options = {}) {
145499
+ return new index_1.ProxyServer(options);
145500
+ }
145501
+ exports.default = index_1.ProxyServer;
143776
145502
  });
143777
145503
 
143778
145504
  // ../api/src/index.ts
@@ -145508,16 +147234,29 @@ var Factory = class {
145508
147234
  var createMiddleware = (middleware) => middleware;
145509
147235
 
145510
147236
  // ../api/src/middleware/errorHandler.ts
147237
+ function getTimestamp() {
147238
+ const d = new Date;
147239
+ const pad2 = (n) => String(n).padStart(2, "0");
147240
+ const pad3 = (n) => String(n).padStart(3, "0");
147241
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.${pad3(d.getMilliseconds())}`;
147242
+ }
145511
147243
  function handleError(error, c) {
147244
+ const timestamp = getTimestamp();
145512
147245
  if (error instanceof C4AError) {
147246
+ console.error(`[api] C4AError [${error.code}]: ${error.message}`, error.details || "");
145513
147247
  const status = mapErrorCodeToStatus(error.code);
145514
- return c.json(error.toResponse(), status);
147248
+ const response2 = error.toResponse();
147249
+ return c.json({ ...response2, timestamp }, status);
145515
147250
  }
147251
+ const isDev = true;
147252
+ const errorMessage = error instanceof Error ? error.message : String(error);
147253
+ const errorStack = isDev && error instanceof Error ? error.stack : undefined;
145516
147254
  console.error("[api] Unhandled error:", error);
145517
147255
  const response = {
145518
147256
  code: "UNKNOWN" /* UNKNOWN */,
145519
- message: "Internal Server Error",
145520
- details: null
147257
+ message: isDev ? `Internal Server Error: ${errorMessage}` : "Internal Server Error",
147258
+ details: errorStack ? { stack: errorStack } : null,
147259
+ timestamp
145521
147260
  };
145522
147261
  return c.json(response, 500);
145523
147262
  }
@@ -146500,6 +148239,10 @@ __legacyDecorateClassTS([
146500
148239
  Property({ type: "string", nullable: true }),
146501
148240
  __legacyMetadataTS("design:type", String)
146502
148241
  ], SourceContentRecord.prototype, "content_hash", undefined);
148242
+ __legacyDecorateClassTS([
148243
+ Property({ type: "string", nullable: true }),
148244
+ __legacyMetadataTS("design:type", String)
148245
+ ], SourceContentRecord.prototype, "content_encoding", undefined);
146503
148246
  __legacyDecorateClassTS([
146504
148247
  Property({ type: "date" }),
146505
148248
  __legacyMetadataTS("design:type", typeof Date === "undefined" ? Object : Date)
@@ -146780,6 +148523,16 @@ class DocStore {
146780
148523
  const orm = this.orm;
146781
148524
  await orm.getSchemaGenerator().updateSchema();
146782
148525
  }
148526
+ async safeFlush() {
148527
+ try {
148528
+ await this.em.flush();
148529
+ } catch (error) {
148530
+ if (this.docProvider === "mongodb" && error instanceof Error && error.message.includes("Transaction numbers are only allowed")) {
148531
+ throw new C4AError("STORAGE_FAILED" /* STORAGE_FAILED */, "MongoDB 事务失败:单机 MongoDB 不支持事务。请配置 MongoDB 副本集(Replica Set)以启用事务支持。" + "参考:https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set/", { originalError: error.message });
148532
+ }
148533
+ throw error;
148534
+ }
148535
+ }
146783
148536
  async save(entity2) {
146784
148537
  DocStore.assertEntity(entity2);
146785
148538
  const existing = await this.em.findOne(EntityRecord, { id: entity2.id });
@@ -146788,7 +148541,7 @@ class DocStore {
146788
148541
  } else {
146789
148542
  this.em.create(EntityRecord, DocStore.toEntityRecord(entity2));
146790
148543
  }
146791
- await this.em.flush();
148544
+ await this.safeFlush();
146792
148545
  return entity2;
146793
148546
  }
146794
148547
  async read(id2) {
@@ -146859,7 +148612,7 @@ class DocStore {
146859
148612
  this.em.create(RelationRecord, DocStore.toRelationRecord(relation2));
146860
148613
  }
146861
148614
  }
146862
- await this.em.flush();
148615
+ await this.safeFlush();
146863
148616
  }
146864
148617
  async deleteRelationsForEntity(entityId) {
146865
148618
  await this.em.nativeDelete(RelationRecord, {
@@ -178900,9 +180653,6 @@ var withTransaction = async (em, fn) => {
178900
180653
  return fn(em);
178901
180654
  };
178902
180655
  var isSourceType = (value) => value === "code" || value === "doc" || value === "feishu" || value === "web";
178903
- var UPLOAD_ALLOWED_EXTENSIONS = new Set([".md", ".doc", ".docx", ".pdf", ".ppt", ".pptx", ".txt"]);
178904
- var UPLOAD_MAX_FILE_SIZE = 5 * 1024 * 1024;
178905
- var UPLOAD_MAX_FILES = 10;
178906
180656
  var findNodeByPath = (tree, targetPath) => {
178907
180657
  for (const node of tree) {
178908
180658
  if (node.path === targetPath)
@@ -179287,14 +181037,21 @@ function createSourcesRouter(storageProvider) {
179287
181037
  if (typeof file2.content !== "string") {
179288
181038
  throw new C4AError("VALIDATION_FAILED" /* VALIDATION_FAILED */, "Missing content", { file_name: file2.file_name });
179289
181039
  }
179290
- const ext = file2.file_name.includes(".") ? `.${file2.file_name.split(".").pop().toLowerCase()}` : "";
181040
+ const ext = getFileExtension(file2.file_name);
179291
181041
  if (!UPLOAD_ALLOWED_EXTENSIONS.has(ext)) {
179292
181042
  throw new C4AError("VALIDATION_FAILED" /* VALIDATION_FAILED */, "Unsupported file type", {
179293
181043
  file_name: file2.file_name,
179294
181044
  extension: ext
179295
181045
  });
179296
181046
  }
179297
- if (Buffer.byteLength(file2.content, "utf-8") > UPLOAD_MAX_FILE_SIZE) {
181047
+ if (file2.encoding === "base64") {
181048
+ const decodedSize = Math.ceil(file2.content.length * 3 / 4);
181049
+ if (decodedSize > UPLOAD_MAX_FILE_SIZE) {
181050
+ throw new C4AError("VALIDATION_FAILED" /* VALIDATION_FAILED */, "File exceeds 5MB limit", {
181051
+ file_name: file2.file_name
181052
+ });
181053
+ }
181054
+ } else if (Buffer.byteLength(file2.content, "utf-8") > UPLOAD_MAX_FILE_SIZE) {
179298
181055
  throw new C4AError("VALIDATION_FAILED" /* VALIDATION_FAILED */, "File exceeds 5MB limit", {
179299
181056
  file_name: file2.file_name
179300
181057
  });
@@ -179322,7 +181079,8 @@ function createSourcesRouter(storageProvider) {
179322
181079
  const now2 = new Date;
179323
181080
  for (const file2 of files) {
179324
181081
  const nodePath = parentPath ? `${parentPath}/${file2.file_name}` : file2.file_name;
179325
- const hash2 = contentHash(file2.content);
181082
+ const hashInput = file2.encoding === "base64" ? Buffer.from(file2.content, "base64") : file2.content;
181083
+ const hash2 = contentHash(hashInput);
179326
181084
  const newNode = {
179327
181085
  path: nodePath,
179328
181086
  kind: "source",
@@ -179349,6 +181107,7 @@ function createSourcesRouter(storageProvider) {
179349
181107
  cnt.source_path = nodePath;
179350
181108
  cnt.content = file2.content;
179351
181109
  cnt.content_hash = hash2;
181110
+ cnt.content_encoding = file2.encoding === "base64" ? "base64" : null;
179352
181111
  cnt.created_at = now2;
179353
181112
  cnt.updated_at = now2;
179354
181113
  emTx.persist(cnt);
@@ -179375,7 +181134,8 @@ function createSourcesRouter(storageProvider) {
179375
181134
  const now2 = new Date;
179376
181135
  const records = [];
179377
181136
  for (const file2 of files) {
179378
- const hash2 = contentHash(file2.content);
181137
+ const hashInput = file2.encoding === "base64" ? Buffer.from(file2.content, "base64") : file2.content;
181138
+ const hash2 = contentHash(hashInput);
179379
181139
  const rec = new SourceRecord;
179380
181140
  rec.id = `src_${generateUUID()}`;
179381
181141
  rec.library_id = libraryId;
@@ -179396,6 +181156,7 @@ function createSourcesRouter(storageProvider) {
179396
181156
  cnt.source_path = "";
179397
181157
  cnt.content = file2.content;
179398
181158
  cnt.content_hash = hash2;
181159
+ cnt.content_encoding = file2.encoding === "base64" ? "base64" : null;
179399
181160
  cnt.created_at = now2;
179400
181161
  cnt.updated_at = now2;
179401
181162
  emTx.persist(cnt);
@@ -179586,6 +181347,7 @@ function createSourcesRouter(storageProvider) {
179586
181347
  source_path: content.source_path,
179587
181348
  content: content.content,
179588
181349
  content_hash: content.content_hash,
181350
+ content_encoding: content.content_encoding ?? null,
179589
181351
  created_at: content.created_at,
179590
181352
  updated_at: content.updated_at
179591
181353
  }, 200);
@@ -179774,9 +181536,537 @@ function createApiApp(options = {}) {
179774
181536
 
179775
181537
  // ../server/src/serve.ts
179776
181538
  init_src();
179777
- init_dist2();
181539
+
181540
+ // ../../node_modules/.bun/@hono+node-server@1.19.9+eb2864ea6bc646ec/node_modules/@hono/node-server/dist/index.mjs
181541
+ import { createServer as createServerHTTP } from "http";
181542
+ import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
181543
+ import { Http2ServerRequest } from "http2";
181544
+ import { Readable } from "stream";
181545
+ import crypto2 from "crypto";
181546
+ var RequestError = class extends Error {
181547
+ constructor(message, options) {
181548
+ super(message, options);
181549
+ this.name = "RequestError";
181550
+ }
181551
+ };
181552
+ var toRequestError = (e) => {
181553
+ if (e instanceof RequestError) {
181554
+ return e;
181555
+ }
181556
+ return new RequestError(e.message, { cause: e });
181557
+ };
181558
+ var GlobalRequest = global.Request;
181559
+ var Request2 = class extends GlobalRequest {
181560
+ constructor(input, options) {
181561
+ if (typeof input === "object" && getRequestCache in input) {
181562
+ input = input[getRequestCache]();
181563
+ }
181564
+ if (typeof options?.body?.getReader !== "undefined") {
181565
+ options.duplex ??= "half";
181566
+ }
181567
+ super(input, options);
181568
+ }
181569
+ };
181570
+ var newHeadersFromIncoming = (incoming) => {
181571
+ const headerRecord = [];
181572
+ const rawHeaders = incoming.rawHeaders;
181573
+ for (let i = 0;i < rawHeaders.length; i += 2) {
181574
+ const { [i]: key, [i + 1]: value } = rawHeaders;
181575
+ if (key.charCodeAt(0) !== 58) {
181576
+ headerRecord.push([key, value]);
181577
+ }
181578
+ }
181579
+ return new Headers(headerRecord);
181580
+ };
181581
+ var wrapBodyStream = Symbol("wrapBodyStream");
181582
+ var newRequestFromIncoming = (method, url2, headers, incoming, abortController) => {
181583
+ const init = {
181584
+ method,
181585
+ headers,
181586
+ signal: abortController.signal
181587
+ };
181588
+ if (method === "TRACE") {
181589
+ init.method = "GET";
181590
+ const req = new Request2(url2, init);
181591
+ Object.defineProperty(req, "method", {
181592
+ get() {
181593
+ return "TRACE";
181594
+ }
181595
+ });
181596
+ return req;
181597
+ }
181598
+ if (!(method === "GET" || method === "HEAD")) {
181599
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
181600
+ init.body = new ReadableStream({
181601
+ start(controller) {
181602
+ controller.enqueue(incoming.rawBody);
181603
+ controller.close();
181604
+ }
181605
+ });
181606
+ } else if (incoming[wrapBodyStream]) {
181607
+ let reader;
181608
+ init.body = new ReadableStream({
181609
+ async pull(controller) {
181610
+ try {
181611
+ reader ||= Readable.toWeb(incoming).getReader();
181612
+ const { done, value } = await reader.read();
181613
+ if (done) {
181614
+ controller.close();
181615
+ } else {
181616
+ controller.enqueue(value);
181617
+ }
181618
+ } catch (error40) {
181619
+ controller.error(error40);
181620
+ }
181621
+ }
181622
+ });
181623
+ } else {
181624
+ init.body = Readable.toWeb(incoming);
181625
+ }
181626
+ }
181627
+ return new Request2(url2, init);
181628
+ };
181629
+ var getRequestCache = Symbol("getRequestCache");
181630
+ var requestCache = Symbol("requestCache");
181631
+ var incomingKey = Symbol("incomingKey");
181632
+ var urlKey = Symbol("urlKey");
181633
+ var headersKey = Symbol("headersKey");
181634
+ var abortControllerKey = Symbol("abortControllerKey");
181635
+ var getAbortController = Symbol("getAbortController");
181636
+ var requestPrototype = {
181637
+ get method() {
181638
+ return this[incomingKey].method || "GET";
181639
+ },
181640
+ get url() {
181641
+ return this[urlKey];
181642
+ },
181643
+ get headers() {
181644
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
181645
+ },
181646
+ [getAbortController]() {
181647
+ this[getRequestCache]();
181648
+ return this[abortControllerKey];
181649
+ },
181650
+ [getRequestCache]() {
181651
+ this[abortControllerKey] ||= new AbortController;
181652
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
181653
+ }
181654
+ };
181655
+ [
181656
+ "body",
181657
+ "bodyUsed",
181658
+ "cache",
181659
+ "credentials",
181660
+ "destination",
181661
+ "integrity",
181662
+ "mode",
181663
+ "redirect",
181664
+ "referrer",
181665
+ "referrerPolicy",
181666
+ "signal",
181667
+ "keepalive"
181668
+ ].forEach((k) => {
181669
+ Object.defineProperty(requestPrototype, k, {
181670
+ get() {
181671
+ return this[getRequestCache]()[k];
181672
+ }
181673
+ });
181674
+ });
181675
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
181676
+ Object.defineProperty(requestPrototype, k, {
181677
+ value: function() {
181678
+ return this[getRequestCache]()[k]();
181679
+ }
181680
+ });
181681
+ });
181682
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
181683
+ var newRequest = (incoming, defaultHostname) => {
181684
+ const req = Object.create(requestPrototype);
181685
+ req[incomingKey] = incoming;
181686
+ const incomingUrl = incoming.url || "";
181687
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
181688
+ if (incoming instanceof Http2ServerRequest) {
181689
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
181690
+ }
181691
+ try {
181692
+ const url22 = new URL(incomingUrl);
181693
+ req[urlKey] = url22.href;
181694
+ } catch (e) {
181695
+ throw new RequestError("Invalid absolute URL", { cause: e });
181696
+ }
181697
+ return req;
181698
+ }
181699
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
181700
+ if (!host) {
181701
+ throw new RequestError("Missing host header");
181702
+ }
181703
+ let scheme;
181704
+ if (incoming instanceof Http2ServerRequest) {
181705
+ scheme = incoming.scheme;
181706
+ if (!(scheme === "http" || scheme === "https")) {
181707
+ throw new RequestError("Unsupported scheme");
181708
+ }
181709
+ } else {
181710
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
181711
+ }
181712
+ const url2 = new URL(`${scheme}://${host}${incomingUrl}`);
181713
+ if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) {
181714
+ throw new RequestError("Invalid host header");
181715
+ }
181716
+ req[urlKey] = url2.href;
181717
+ return req;
181718
+ };
181719
+ var responseCache = Symbol("responseCache");
181720
+ var getResponseCache = Symbol("getResponseCache");
181721
+ var cacheKey = Symbol("cache");
181722
+ var GlobalResponse = global.Response;
181723
+ var Response2 = class _Response {
181724
+ #body;
181725
+ #init;
181726
+ [getResponseCache]() {
181727
+ delete this[cacheKey];
181728
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
181729
+ }
181730
+ constructor(body, init) {
181731
+ let headers;
181732
+ this.#body = body;
181733
+ if (init instanceof _Response) {
181734
+ const cachedGlobalResponse = init[responseCache];
181735
+ if (cachedGlobalResponse) {
181736
+ this.#init = cachedGlobalResponse;
181737
+ this[getResponseCache]();
181738
+ return;
181739
+ } else {
181740
+ this.#init = init.#init;
181741
+ headers = new Headers(init.#init.headers);
181742
+ }
181743
+ } else {
181744
+ this.#init = init;
181745
+ }
181746
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
181747
+ headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
181748
+ this[cacheKey] = [init?.status || 200, body, headers];
181749
+ }
181750
+ }
181751
+ get headers() {
181752
+ const cache = this[cacheKey];
181753
+ if (cache) {
181754
+ if (!(cache[2] instanceof Headers)) {
181755
+ cache[2] = new Headers(cache[2]);
181756
+ }
181757
+ return cache[2];
181758
+ }
181759
+ return this[getResponseCache]().headers;
181760
+ }
181761
+ get status() {
181762
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
181763
+ }
181764
+ get ok() {
181765
+ const status = this.status;
181766
+ return status >= 200 && status < 300;
181767
+ }
181768
+ };
181769
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
181770
+ Object.defineProperty(Response2.prototype, k, {
181771
+ get() {
181772
+ return this[getResponseCache]()[k];
181773
+ }
181774
+ });
181775
+ });
181776
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
181777
+ Object.defineProperty(Response2.prototype, k, {
181778
+ value: function() {
181779
+ return this[getResponseCache]()[k]();
181780
+ }
181781
+ });
181782
+ });
181783
+ Object.setPrototypeOf(Response2, GlobalResponse);
181784
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
181785
+ async function readWithoutBlocking(readPromise) {
181786
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(undefined))]);
181787
+ }
181788
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
181789
+ const cancel = (error40) => {
181790
+ reader.cancel(error40).catch(() => {});
181791
+ };
181792
+ writable.on("close", cancel);
181793
+ writable.on("error", cancel);
181794
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
181795
+ return reader.closed.finally(() => {
181796
+ writable.off("close", cancel);
181797
+ writable.off("error", cancel);
181798
+ });
181799
+ function handleStreamError(error40) {
181800
+ if (error40) {
181801
+ writable.destroy(error40);
181802
+ }
181803
+ }
181804
+ function onDrain() {
181805
+ reader.read().then(flow, handleStreamError);
181806
+ }
181807
+ function flow({ done, value }) {
181808
+ try {
181809
+ if (done) {
181810
+ writable.end();
181811
+ } else if (!writable.write(value)) {
181812
+ writable.once("drain", onDrain);
181813
+ } else {
181814
+ return reader.read().then(flow, handleStreamError);
181815
+ }
181816
+ } catch (e) {
181817
+ handleStreamError(e);
181818
+ }
181819
+ }
181820
+ }
181821
+ function writeFromReadableStream(stream, writable) {
181822
+ if (stream.locked) {
181823
+ throw new TypeError("ReadableStream is locked.");
181824
+ } else if (writable.destroyed) {
181825
+ return;
181826
+ }
181827
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
181828
+ }
181829
+ var buildOutgoingHttpHeaders = (headers) => {
181830
+ const res = {};
181831
+ if (!(headers instanceof Headers)) {
181832
+ headers = new Headers(headers ?? undefined);
181833
+ }
181834
+ const cookies = [];
181835
+ for (const [k, v] of headers) {
181836
+ if (k === "set-cookie") {
181837
+ cookies.push(v);
181838
+ } else {
181839
+ res[k] = v;
181840
+ }
181841
+ }
181842
+ if (cookies.length > 0) {
181843
+ res["set-cookie"] = cookies;
181844
+ }
181845
+ res["content-type"] ??= "text/plain; charset=UTF-8";
181846
+ return res;
181847
+ };
181848
+ var X_ALREADY_SENT = "x-hono-already-sent";
181849
+ if (typeof global.crypto === "undefined") {
181850
+ global.crypto = crypto2;
181851
+ }
181852
+ var outgoingEnded = Symbol("outgoingEnded");
181853
+ var handleRequestError = () => new Response(null, {
181854
+ status: 400
181855
+ });
181856
+ var handleFetchError2 = (e) => new Response(null, {
181857
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
181858
+ });
181859
+ var handleResponseError = (e, outgoing) => {
181860
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
181861
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
181862
+ console.info("The user aborted a request.");
181863
+ } else {
181864
+ console.error(e);
181865
+ if (!outgoing.headersSent) {
181866
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
181867
+ }
181868
+ outgoing.end(`Error: ${err.message}`);
181869
+ outgoing.destroy(err);
181870
+ }
181871
+ };
181872
+ var flushHeaders = (outgoing) => {
181873
+ if ("flushHeaders" in outgoing && outgoing.writable) {
181874
+ outgoing.flushHeaders();
181875
+ }
181876
+ };
181877
+ var responseViaCache = async (res, outgoing) => {
181878
+ let [status, body, header] = res[cacheKey];
181879
+ if (header instanceof Headers) {
181880
+ header = buildOutgoingHttpHeaders(header);
181881
+ }
181882
+ if (typeof body === "string") {
181883
+ header["Content-Length"] = Buffer.byteLength(body);
181884
+ } else if (body instanceof Uint8Array) {
181885
+ header["Content-Length"] = body.byteLength;
181886
+ } else if (body instanceof Blob) {
181887
+ header["Content-Length"] = body.size;
181888
+ }
181889
+ outgoing.writeHead(status, header);
181890
+ if (typeof body === "string" || body instanceof Uint8Array) {
181891
+ outgoing.end(body);
181892
+ } else if (body instanceof Blob) {
181893
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
181894
+ } else {
181895
+ flushHeaders(outgoing);
181896
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
181897
+ }
181898
+ outgoing[outgoingEnded]?.();
181899
+ };
181900
+ var isPromise = (res) => typeof res.then === "function";
181901
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
181902
+ if (isPromise(res)) {
181903
+ if (options.errorHandler) {
181904
+ try {
181905
+ res = await res;
181906
+ } catch (err) {
181907
+ const errRes = await options.errorHandler(err);
181908
+ if (!errRes) {
181909
+ return;
181910
+ }
181911
+ res = errRes;
181912
+ }
181913
+ } else {
181914
+ res = await res.catch(handleFetchError2);
181915
+ }
181916
+ }
181917
+ if (cacheKey in res) {
181918
+ return responseViaCache(res, outgoing);
181919
+ }
181920
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
181921
+ if (res.body) {
181922
+ const reader = res.body.getReader();
181923
+ const values = [];
181924
+ let done = false;
181925
+ let currentReadPromise = undefined;
181926
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
181927
+ let maxReadCount = 2;
181928
+ for (let i = 0;i < maxReadCount; i++) {
181929
+ currentReadPromise ||= reader.read();
181930
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
181931
+ console.error(e);
181932
+ done = true;
181933
+ });
181934
+ if (!chunk) {
181935
+ if (i === 1) {
181936
+ await new Promise((resolve2) => setTimeout(resolve2));
181937
+ maxReadCount = 3;
181938
+ continue;
181939
+ }
181940
+ break;
181941
+ }
181942
+ currentReadPromise = undefined;
181943
+ if (chunk.value) {
181944
+ values.push(chunk.value);
181945
+ }
181946
+ if (chunk.done) {
181947
+ done = true;
181948
+ break;
181949
+ }
181950
+ }
181951
+ if (done && !("content-length" in resHeaderRecord)) {
181952
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
181953
+ }
181954
+ }
181955
+ outgoing.writeHead(res.status, resHeaderRecord);
181956
+ values.forEach((value) => {
181957
+ outgoing.write(value);
181958
+ });
181959
+ if (done) {
181960
+ outgoing.end();
181961
+ } else {
181962
+ if (values.length === 0) {
181963
+ flushHeaders(outgoing);
181964
+ }
181965
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
181966
+ }
181967
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
181968
+ outgoing.writeHead(res.status, resHeaderRecord);
181969
+ outgoing.end();
181970
+ }
181971
+ outgoing[outgoingEnded]?.();
181972
+ };
181973
+ var getRequestListener = (fetchCallback, options = {}) => {
181974
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
181975
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
181976
+ Object.defineProperty(global, "Request", {
181977
+ value: Request2
181978
+ });
181979
+ Object.defineProperty(global, "Response", {
181980
+ value: Response2
181981
+ });
181982
+ }
181983
+ return async (incoming, outgoing) => {
181984
+ let res, req;
181985
+ try {
181986
+ req = newRequest(incoming, options.hostname);
181987
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
181988
+ if (!incomingEnded) {
181989
+ incoming[wrapBodyStream] = true;
181990
+ incoming.on("end", () => {
181991
+ incomingEnded = true;
181992
+ });
181993
+ if (incoming instanceof Http2ServerRequest2) {
181994
+ outgoing[outgoingEnded] = () => {
181995
+ if (!incomingEnded) {
181996
+ setTimeout(() => {
181997
+ if (!incomingEnded) {
181998
+ setTimeout(() => {
181999
+ incoming.destroy();
182000
+ outgoing.destroy();
182001
+ });
182002
+ }
182003
+ });
182004
+ }
182005
+ };
182006
+ }
182007
+ }
182008
+ outgoing.on("close", () => {
182009
+ const abortController = req[abortControllerKey];
182010
+ if (abortController) {
182011
+ if (incoming.errored) {
182012
+ req[abortControllerKey].abort(incoming.errored.toString());
182013
+ } else if (!outgoing.writableFinished) {
182014
+ req[abortControllerKey].abort("Client connection prematurely closed.");
182015
+ }
182016
+ }
182017
+ if (!incomingEnded) {
182018
+ setTimeout(() => {
182019
+ if (!incomingEnded) {
182020
+ setTimeout(() => {
182021
+ incoming.destroy();
182022
+ });
182023
+ }
182024
+ });
182025
+ }
182026
+ });
182027
+ res = fetchCallback(req, { incoming, outgoing });
182028
+ if (cacheKey in res) {
182029
+ return responseViaCache(res, outgoing);
182030
+ }
182031
+ } catch (e) {
182032
+ if (!res) {
182033
+ if (options.errorHandler) {
182034
+ res = await options.errorHandler(req ? e : toRequestError(e));
182035
+ if (!res) {
182036
+ return;
182037
+ }
182038
+ } else if (!req) {
182039
+ res = handleRequestError();
182040
+ } else {
182041
+ res = handleFetchError2(e);
182042
+ }
182043
+ } else {
182044
+ return handleResponseError(e, outgoing);
182045
+ }
182046
+ }
182047
+ try {
182048
+ return await responseViaResponseObject(res, outgoing, options);
182049
+ } catch (e) {
182050
+ return handleResponseError(e, outgoing);
182051
+ }
182052
+ };
182053
+ };
182054
+ var createAdaptorServer = (options) => {
182055
+ const fetchCallback = options.fetch;
182056
+ const requestListener = getRequestListener(fetchCallback, {
182057
+ hostname: options.hostname,
182058
+ overrideGlobalObjects: options.overrideGlobalObjects,
182059
+ autoCleanupIncoming: options.autoCleanupIncoming
182060
+ });
182061
+ const createServer = options.createServer || createServerHTTP;
182062
+ const server = createServer(options.serverOptions || {}, requestListener);
182063
+ return server;
182064
+ };
182065
+
182066
+ // ../server/src/serve.ts
182067
+ var import_http_proxy_3 = __toESM(require_lib9(), 1);
179778
182068
  var import_yaml3 = __toESM(require_dist(), 1);
179779
- import { createServer as createHttpServer } from "node:http";
182069
+ import { createServer as createHttpServer, ServerResponse } from "node:http";
179780
182070
  import { existsSync as existsSync5 } from "node:fs";
179781
182071
  import { readFile as readFile4 } from "node:fs/promises";
179782
182072
  import path8 from "node:path";
@@ -180391,6 +182681,22 @@ class DaemonManager {
180391
182681
  }
180392
182682
  }
180393
182683
 
182684
+ // ../server/src/index.ts
182685
+ function createServer(options = {}) {
182686
+ const app = new Hono2;
182687
+ const storageProvider = options.storageProvider ?? createDefaultStorageProvider();
182688
+ const { injectWebSocket, wss, upgradeWebSocket, broadcastToWebClients } = createWsEndpoint(app);
182689
+ const daemonManager = new DaemonManager(storageProvider, broadcastToWebClients);
182690
+ const apiApp = createApiApp({
182691
+ ...options,
182692
+ storageProvider,
182693
+ contextVariables: { daemonManager }
182694
+ });
182695
+ app.route("/api/v1", apiApp);
182696
+ app.get("/ws/daemon", upgradeWebSocket(() => daemonManager.createWsHandlers()));
182697
+ return { app, injectWebSocket, wss, daemonManager };
182698
+ }
182699
+
180394
182700
  // ../server/src/static.ts
180395
182701
  import { existsSync as existsSync4 } from "node:fs";
180396
182702
  import { readFile as readFile3 } from "node:fs/promises";
@@ -180623,25 +182929,6 @@ function mountStatic(app, staticDir) {
180623
182929
  });
180624
182930
  }
180625
182931
 
180626
- // ../server/src/index.ts
180627
- function createServer(options = {}) {
180628
- const app = new Hono2;
180629
- const storageProvider = options.storageProvider ?? createDefaultStorageProvider();
180630
- const { injectWebSocket, wss, upgradeWebSocket, broadcastToWebClients } = createWsEndpoint(app);
180631
- const daemonManager = new DaemonManager(storageProvider, broadcastToWebClients);
180632
- const apiApp = createApiApp({
180633
- ...options,
180634
- storageProvider,
180635
- contextVariables: { daemonManager }
180636
- });
180637
- app.route("/api/v1", apiApp);
180638
- app.get("/ws/daemon", upgradeWebSocket(() => daemonManager.createWsHandlers()));
180639
- if (options.staticDir) {
180640
- mountStatic(app, options.staticDir);
180641
- }
180642
- return { app, injectWebSocket, wss, daemonManager };
180643
- }
180644
-
180645
182932
  // ../server/src/bootstrap.ts
180646
182933
  init_src();
180647
182934
  async function bootstrapPhase0(em) {
@@ -180715,10 +183002,17 @@ function timestamp() {
180715
183002
  const pad3 = (n) => String(n).padStart(3, "0");
180716
183003
  return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}.${pad3(d.getMilliseconds())}`;
180717
183004
  }
183005
+ var originalLog = console.log.bind(console);
180718
183006
  var originalInfo = console.info.bind(console);
180719
183007
  var originalError = console.error.bind(console);
183008
+ console.log = (...args) => originalLog(`[${timestamp()}]`, ...args);
180720
183009
  console.info = (...args) => originalInfo(`[${timestamp()}]`, ...args);
180721
183010
  console.error = (...args) => originalError(`[${timestamp()}]`, ...args);
183011
+ function displayHost(host) {
183012
+ if (host === "::" || host === "0.0.0.0")
183013
+ return "127.0.0.1";
183014
+ return host;
183015
+ }
180722
183016
  function isPlainObject4(value) {
180723
183017
  return typeof value === "object" && value !== null && !Array.isArray(value);
180724
183018
  }
@@ -180741,9 +183035,22 @@ async function loadServerListenConfig() {
180741
183035
  const host = typeof serverSection.host === "string" ? serverSection.host : defaults2.host;
180742
183036
  return { port, host };
180743
183037
  }
183038
+ function attachPortErrorHandler(server, label) {
183039
+ server.on("error", (error40) => {
183040
+ const err = error40;
183041
+ if (err?.code === "EADDRINUSE") {
183042
+ console.error(`${label} 端口已被占用`);
183043
+ process.exit(1);
183044
+ }
183045
+ const message = error40 instanceof Error ? error40.message : String(error40);
183046
+ console.error(`${label} error: ${message}`);
183047
+ });
183048
+ }
180744
183049
  async function startServer() {
180745
183050
  const { host, port } = await loadServerListenConfig();
180746
183051
  const isDev = process.env.C4A_DEV === "1";
183052
+ const webPort = port + 20;
183053
+ const dHost = displayHost(host);
180747
183054
  const currentDir = path8.dirname(fileURLToPath(import.meta.url));
180748
183055
  const webPkgDir = path8.resolve(currentDir, "..", "..", "web");
180749
183056
  function resolveStaticDir() {
@@ -180757,77 +183064,71 @@ async function startServer() {
180757
183064
  }
180758
183065
  return;
180759
183066
  }
180760
- const staticDir = !isDev ? resolveStaticDir() : undefined;
180761
- const storageProvider = createDefaultStorageProvider();
180762
- const options = {
180763
- storageProvider
180764
- };
180765
- if (staticDir)
180766
- options.staticDir = staticDir;
180767
- const { app, injectWebSocket } = createServer(options);
180768
- tryBootstrapPhase0(storageProvider);
180769
183067
  if (isDev) {
180770
- const { getRequestListener: getRequestListener2 } = await Promise.resolve().then(() => (init_dist2(), exports_dist));
180771
183068
  const { createServer: createViteServer } = await import("vite");
180772
- const honoListener = getRequestListener2(app.fetch);
180773
- let vite;
180774
- const server = createHttpServer((req, res) => {
180775
- const url2 = req.url ?? "/";
180776
- if (url2.startsWith("/api/") || url2 === "/ws" || url2.startsWith("/ws/")) {
180777
- honoListener(req, res);
180778
- } else {
180779
- vite.middlewares(req, res, () => {
180780
- honoListener(req, res);
180781
- });
180782
- }
180783
- });
180784
- vite = await createViteServer({
183069
+ const vite = await createViteServer({
180785
183070
  root: webPkgDir,
180786
- server: { middlewareMode: true, hmr: { server } },
183071
+ server: { port: webPort, host, strictPort: true },
180787
183072
  appType: "spa"
180788
183073
  });
180789
- injectWebSocket(server);
180790
- const upgradeListeners = server.listeners("upgrade");
180791
- const honoUpgrade = upgradeListeners[upgradeListeners.length - 1];
180792
- server.removeListener("upgrade", honoUpgrade);
180793
- server.on("upgrade", (req, socket, head) => {
180794
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
180795
- if (pathname === "/ws" || pathname === "/ws/daemon") {
180796
- honoUpgrade(req, socket, head);
180797
- }
180798
- });
180799
- server.on("error", (error40) => {
180800
- const err = error40;
180801
- if (err?.code === "EADDRINUSE") {
180802
- console.error("端口已被占用");
180803
- process.exit(1);
180804
- }
180805
- const message = error40 instanceof Error ? error40.message : String(error40);
180806
- console.error(`Server error: ${message}`);
180807
- });
180808
- server.listen(port, host, () => {
180809
- console.info(`C4A Server (dev) 已启动: http://${host}:${port}`);
180810
- console.info(`Vite HMR 已启用,修改 web 源码后自动热更新`);
180811
- });
183074
+ await vite.listen();
183075
+ console.info(`Vite Dev Server: http://${dHost}:${webPort}`);
180812
183076
  } else {
180813
- const server = createAdaptorServer({ fetch: app.fetch });
180814
- server.on("error", (error40) => {
180815
- const err = error40;
180816
- if (err?.code === "EADDRINUSE") {
180817
- console.error("端口已被占用");
180818
- process.exit(1);
180819
- }
180820
- const message = error40 instanceof Error ? error40.message : String(error40);
180821
- console.error(`Server error: ${message}`);
180822
- });
180823
- injectWebSocket(server);
180824
- server.listen(port, host, () => {
180825
- console.info(`C4A Server 已启动: http://${host}:${port}`);
180826
- if (staticDir) {
180827
- console.info(`静态资源托管: ${staticDir}`);
180828
- }
180829
- });
183077
+ const staticDir = resolveStaticDir();
183078
+ if (staticDir) {
183079
+ const webApp = new Hono2;
183080
+ mountStatic(webApp, staticDir);
183081
+ const webServer = createAdaptorServer({ fetch: webApp.fetch });
183082
+ attachPortErrorHandler(webServer, "Web Server");
183083
+ await new Promise((resolve2) => {
183084
+ webServer.listen(webPort, host, () => {
183085
+ console.info(`Web Server (static): http://${dHost}:${webPort}`);
183086
+ console.info(` 静态资源: ${staticDir}`);
183087
+ resolve2();
183088
+ });
183089
+ });
183090
+ }
180830
183091
  }
183092
+ const storageProvider = createDefaultStorageProvider();
183093
+ const { app, injectWebSocket } = createServer({ storageProvider });
183094
+ tryBootstrapPhase0(storageProvider);
183095
+ const honoListener = getRequestListener(app.fetch);
183096
+ const webProxy = import_http_proxy_3.createProxyServer({ target: `http://${dHost}:${webPort}` });
183097
+ const gateway2 = createHttpServer((req, res) => {
183098
+ const url2 = req.url ?? "/";
183099
+ if (url2.startsWith("/api/") || url2 === "/ws" || url2.startsWith("/ws/")) {
183100
+ honoListener(req, res);
183101
+ } else {
183102
+ webProxy.web(req, res);
183103
+ }
183104
+ });
183105
+ injectWebSocket(gateway2);
183106
+ const upgradeListeners = gateway2.listeners("upgrade");
183107
+ const honoUpgrade = upgradeListeners[upgradeListeners.length - 1];
183108
+ gateway2.removeAllListeners("upgrade");
183109
+ gateway2.on("upgrade", (req, socket, head) => {
183110
+ const url2 = req.url ?? "/";
183111
+ if (url2 === "/ws" || url2.startsWith("/ws/")) {
183112
+ honoUpgrade(req, socket, head);
183113
+ } else {
183114
+ socket.destroy();
183115
+ }
183116
+ });
183117
+ attachPortErrorHandler(gateway2, "Gateway");
183118
+ webProxy.on("error", (_err, _req, res) => {
183119
+ if (res instanceof ServerResponse && !res.headersSent) {
183120
+ res.writeHead(503, { "Content-Type": "text/plain" });
183121
+ res.end("Web server not ready");
183122
+ }
183123
+ });
183124
+ await new Promise((resolve2) => {
183125
+ gateway2.listen(port, host, () => {
183126
+ console.info(`C4A Gateway: http://${dHost}:${port}`);
183127
+ console.info(` → API+WS (in-process)`);
183128
+ console.info(` → Web http://${dHost}:${webPort}`);
183129
+ resolve2();
183130
+ });
183131
+ });
180831
183132
  }
180832
183133
  async function tryBootstrapPhase0(storageProvider) {
180833
183134
  try {