@caplets/core 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.ts +2 -0
- package/dist/{engine-Bh55p8Lm.js → engine-Brwid_mq.js} +26370 -26368
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3340 -53
- package/dist/native/options.d.ts +34 -0
- package/dist/native/remote.d.ts +46 -0
- package/dist/native/service.d.ts +7 -1
- package/dist/native.d.ts +2 -0
- package/dist/native.js +276 -2
- package/dist/runtime.d.ts +3 -8
- package/dist/serve/http.d.ts +12 -0
- package/dist/serve/index.d.ts +14 -0
- package/dist/serve/options.d.ts +34 -0
- package/dist/serve/session.d.ts +21 -0
- package/dist/serve/stdio.d.ts +5 -0
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as getLiteralValue, A as ErrorCode, B as ListToolsRequestSchema, C as CompleteRequestSchema, Ct as string, Dt as __commonJSMin, E as CreateTaskResultSchema, Et as toSafeError, F as LATEST_PROTOCOL_VERSION, G as SetLevelRequestSchema, H as McpError, I as ListPromptsRequestSchema, J as assertCompleteRequestResourceTemplate, L as ListResourceTemplatesRequestSchema, M as InitializeRequestSchema, N as InitializedNotificationSchema, O as ElicitResultSchema, Ot as __require, P as JSONRPCMessageSchema, Q as isJSONRPCResultResponse, R as ListResourcesRequestSchema, S as CallToolResultSchema, St as object, T as CreateMessageResultWithToolsSchema, Tt as CapletsError, U as ReadResourceRequestSchema, V as LoggingLevelSchema, W as SUPPORTED_PROTOCOL_VERSIONS, X as isJSONRPCErrorResponse, Y as isInitializeRequest, Z as isJSONRPCRequest, _ as AjvJsonSchemaValidator, _t as discoverCapletFiles, a as capabilityDescription, at as normalizeObjectSchema, b as toJsonSchemaCompat, bt as ZodOptional, c as deleteTokenBundle, ct as safeParseAsync, dt as parseConfig, et as getObjectShape, f as ReadBuffer, ft as DEFAULT_AUTH_DIR, g as assertToolsCallTaskCapability, gt as resolveProjectConfigPath, h as assertClientRequestTaskCapability, ht as resolveProjectCapletsRoot, i as ServerRegistry, it as isZ4Schema, j as GetPromptRequestSchema, k as EmptyResultSchema, kt as __toESM, l as isTokenBundleExpired, lt as loadConfig, mt as resolveConfigPath, n as generatedToolInputSchema, nt as getSchemaDescription, o as runGenericOAuthFlow, ot as objectFromShape, p as serializeMessage, pt as resolveCapletsRoot, q as assertCompleteRequestPrompt, r as handleServerTool, rt as isSchemaOptional, s as runOAuthFlow, st as safeParse, t as CapletsEngine, tt as getParseErrorMessage, u as readTokenBundle, ut as loadConfigWithSources, v as Protocol, vt as validateCapletFile, w as CreateMessageResultSchema, wt as url, x as CallToolRequestSchema, xt as literal, y as mergeCapabilities, yt as SERVER_ID_PATTERN, z as ListRootsResultSchema } from "./engine-Brwid_mq.js";
|
|
2
2
|
import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, join, parse, relative, resolve } from "node:path";
|
|
4
|
-
import { stdin, stdout } from "node:process";
|
|
5
|
-
import { tmpdir } from "node:os";
|
|
6
4
|
import { execFileSync } from "node:child_process";
|
|
5
|
+
import process$1, { stdin, stdout } from "node:process";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
7
8
|
import { createInterface } from "node:readline/promises";
|
|
9
|
+
import { createServer } from "http";
|
|
10
|
+
import { Http2ServerRequest, constants as constants$1 } from "http2";
|
|
11
|
+
import { Readable } from "stream";
|
|
12
|
+
import crypto$1 from "crypto";
|
|
8
13
|
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
|
|
9
14
|
/**
|
|
10
15
|
* Experimental server task features for MCP SDK.
|
|
@@ -1314,16 +1319,17 @@ const EMPTY_COMPLETION_RESULT = { completion: {
|
|
|
1314
1319
|
} };
|
|
1315
1320
|
//#endregion
|
|
1316
1321
|
//#region package.json
|
|
1317
|
-
var version = "0.
|
|
1322
|
+
var version = "0.16.0";
|
|
1318
1323
|
//#endregion
|
|
1319
|
-
//#region src/
|
|
1320
|
-
var
|
|
1321
|
-
server;
|
|
1324
|
+
//#region src/serve/session.ts
|
|
1325
|
+
var CapletsMcpSession = class {
|
|
1322
1326
|
engine;
|
|
1327
|
+
server;
|
|
1323
1328
|
tools = /* @__PURE__ */ new Map();
|
|
1324
1329
|
unsubscribeReload;
|
|
1325
|
-
|
|
1326
|
-
|
|
1330
|
+
closed = false;
|
|
1331
|
+
constructor(engine, options = {}) {
|
|
1332
|
+
this.engine = engine;
|
|
1327
1333
|
this.server = options.server ?? new McpServer({
|
|
1328
1334
|
name: "caplets",
|
|
1329
1335
|
version
|
|
@@ -1334,28 +1340,15 @@ var CapletsRuntime = class {
|
|
|
1334
1340
|
async connect(transport) {
|
|
1335
1341
|
await this.server.connect(transport);
|
|
1336
1342
|
}
|
|
1337
|
-
scheduleReload() {
|
|
1338
|
-
this.engine.scheduleReload();
|
|
1339
|
-
}
|
|
1340
|
-
async reload() {
|
|
1341
|
-
return await this.engine.reload();
|
|
1342
|
-
}
|
|
1343
|
-
async close() {
|
|
1344
|
-
this.unsubscribeReload();
|
|
1345
|
-
try {
|
|
1346
|
-
await this.engine.close();
|
|
1347
|
-
} finally {
|
|
1348
|
-
await this.server.close();
|
|
1349
|
-
}
|
|
1350
|
-
}
|
|
1351
|
-
currentConfig() {
|
|
1352
|
-
return this.engine.currentConfig();
|
|
1353
|
-
}
|
|
1354
1343
|
registeredToolIds() {
|
|
1355
1344
|
return [...this.tools.keys()].sort();
|
|
1356
1345
|
}
|
|
1357
|
-
|
|
1358
|
-
|
|
1346
|
+
async close() {
|
|
1347
|
+
if (this.closed) return;
|
|
1348
|
+
this.closed = true;
|
|
1349
|
+
this.unsubscribeReload();
|
|
1350
|
+
this.tools.clear();
|
|
1351
|
+
await this.server.close();
|
|
1359
1352
|
}
|
|
1360
1353
|
reconcileTools(previous, next) {
|
|
1361
1354
|
const enabled = new Map(nextEnabledServers(next).map((server) => [server.server, server]));
|
|
@@ -1406,6 +1399,46 @@ function capletById(config, serverId) {
|
|
|
1406
1399
|
function serializeCaplet(caplet) {
|
|
1407
1400
|
return JSON.stringify(caplet ?? null);
|
|
1408
1401
|
}
|
|
1402
|
+
//#endregion
|
|
1403
|
+
//#region src/runtime.ts
|
|
1404
|
+
var CapletsRuntime = class {
|
|
1405
|
+
server;
|
|
1406
|
+
engine;
|
|
1407
|
+
session;
|
|
1408
|
+
constructor(options = {}) {
|
|
1409
|
+
this.engine = new CapletsEngine(engineOptions(options));
|
|
1410
|
+
this.session = new CapletsMcpSession(this.engine, selectSessionOptions(options));
|
|
1411
|
+
this.server = this.session.server;
|
|
1412
|
+
}
|
|
1413
|
+
async connect(transport) {
|
|
1414
|
+
await this.session.connect(transport);
|
|
1415
|
+
}
|
|
1416
|
+
scheduleReload() {
|
|
1417
|
+
this.engine.scheduleReload();
|
|
1418
|
+
}
|
|
1419
|
+
async reload() {
|
|
1420
|
+
return await this.engine.reload();
|
|
1421
|
+
}
|
|
1422
|
+
async close() {
|
|
1423
|
+
try {
|
|
1424
|
+
await this.session.close();
|
|
1425
|
+
} finally {
|
|
1426
|
+
await this.engine.close();
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
currentConfig() {
|
|
1430
|
+
return this.engine.currentConfig();
|
|
1431
|
+
}
|
|
1432
|
+
registeredToolIds() {
|
|
1433
|
+
return this.session.registeredToolIds();
|
|
1434
|
+
}
|
|
1435
|
+
watchedPaths() {
|
|
1436
|
+
return this.engine.watchedPaths();
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
function selectSessionOptions(options) {
|
|
1440
|
+
return options.server === void 0 ? {} : { server: options.server };
|
|
1441
|
+
}
|
|
1409
1442
|
function engineOptions(options) {
|
|
1410
1443
|
const engineOptions = {};
|
|
1411
1444
|
if (options.configPath !== void 0) engineOptions.configPath = options.configPath;
|
|
@@ -5357,34 +5390,3288 @@ function nearestExistingParent(path) {
|
|
|
5357
5390
|
return nearestExistingParent(parent);
|
|
5358
5391
|
}
|
|
5359
5392
|
//#endregion
|
|
5360
|
-
//#region
|
|
5361
|
-
|
|
5362
|
-
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
"
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
if (
|
|
5372
|
-
|
|
5393
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/compose.js
|
|
5394
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
5395
|
+
return (context, next) => {
|
|
5396
|
+
let index = -1;
|
|
5397
|
+
return dispatch(0);
|
|
5398
|
+
async function dispatch(i) {
|
|
5399
|
+
if (i <= index) throw new Error("next() called multiple times");
|
|
5400
|
+
index = i;
|
|
5401
|
+
let res;
|
|
5402
|
+
let isError = false;
|
|
5403
|
+
let handler;
|
|
5404
|
+
if (middleware[i]) {
|
|
5405
|
+
handler = middleware[i][0][0];
|
|
5406
|
+
context.req.routeIndex = i;
|
|
5407
|
+
} else handler = i === middleware.length && next || void 0;
|
|
5408
|
+
if (handler) try {
|
|
5409
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
5410
|
+
} catch (err) {
|
|
5411
|
+
if (err instanceof Error && onError) {
|
|
5412
|
+
context.error = err;
|
|
5413
|
+
res = await onError(err, context);
|
|
5414
|
+
isError = true;
|
|
5415
|
+
} else throw err;
|
|
5416
|
+
}
|
|
5417
|
+
else if (context.finalized === false && onNotFound) res = await onNotFound(context);
|
|
5418
|
+
if (res && (context.finalized === false || isError)) context.res = res;
|
|
5419
|
+
return context;
|
|
5373
5420
|
}
|
|
5374
|
-
|
|
5421
|
+
};
|
|
5422
|
+
};
|
|
5423
|
+
//#endregion
|
|
5424
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/http-exception.js
|
|
5425
|
+
var HTTPException = class extends Error {
|
|
5426
|
+
res;
|
|
5427
|
+
status;
|
|
5428
|
+
/**
|
|
5429
|
+
* Creates an instance of `HTTPException`.
|
|
5430
|
+
* @param status - HTTP status code for the exception. Defaults to 500.
|
|
5431
|
+
* @param options - Additional options for the exception.
|
|
5432
|
+
*/
|
|
5433
|
+
constructor(status = 500, options) {
|
|
5434
|
+
super(options?.message, { cause: options?.cause });
|
|
5435
|
+
this.res = options?.res;
|
|
5436
|
+
this.status = status;
|
|
5437
|
+
}
|
|
5438
|
+
/**
|
|
5439
|
+
* Returns the response object associated with the exception.
|
|
5440
|
+
* If a response object is not provided, a new response is created with the error message and status code.
|
|
5441
|
+
* @returns The response object.
|
|
5442
|
+
*/
|
|
5443
|
+
getResponse() {
|
|
5444
|
+
if (this.res) return new Response(this.res.body, {
|
|
5445
|
+
status: this.status,
|
|
5446
|
+
headers: this.res.headers
|
|
5447
|
+
});
|
|
5448
|
+
return new Response(this.message, { status: this.status });
|
|
5375
5449
|
}
|
|
5450
|
+
};
|
|
5451
|
+
//#endregion
|
|
5452
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/request/constants.js
|
|
5453
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
5454
|
+
//#endregion
|
|
5455
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/body.js
|
|
5456
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
5457
|
+
const { all = false, dot = false } = options;
|
|
5458
|
+
const contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
|
|
5459
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) return parseFormData(request, {
|
|
5460
|
+
all,
|
|
5461
|
+
dot
|
|
5462
|
+
});
|
|
5463
|
+
return {};
|
|
5464
|
+
};
|
|
5465
|
+
async function parseFormData(request, options) {
|
|
5466
|
+
const formData = await request.formData();
|
|
5467
|
+
if (formData) return convertFormDataToBodyData(formData, options);
|
|
5468
|
+
return {};
|
|
5376
5469
|
}
|
|
5377
|
-
function
|
|
5378
|
-
const
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5470
|
+
function convertFormDataToBodyData(formData, options) {
|
|
5471
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
5472
|
+
formData.forEach((value, key) => {
|
|
5473
|
+
if (!(options.all || key.endsWith("[]"))) form[key] = value;
|
|
5474
|
+
else handleParsingAllValues(form, key, value);
|
|
5382
5475
|
});
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5476
|
+
if (options.dot) Object.entries(form).forEach(([key, value]) => {
|
|
5477
|
+
if (key.includes(".")) {
|
|
5478
|
+
handleParsingNestedValues(form, key, value);
|
|
5479
|
+
delete form[key];
|
|
5480
|
+
}
|
|
5481
|
+
});
|
|
5482
|
+
return form;
|
|
5483
|
+
}
|
|
5484
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
5485
|
+
if (form[key] !== void 0) if (Array.isArray(form[key])) form[key].push(value);
|
|
5486
|
+
else form[key] = [form[key], value];
|
|
5487
|
+
else if (!key.endsWith("[]")) form[key] = value;
|
|
5488
|
+
else form[key] = [value];
|
|
5489
|
+
};
|
|
5490
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
5491
|
+
if (/(?:^|\.)__proto__\./.test(key)) return;
|
|
5492
|
+
let nestedForm = form;
|
|
5493
|
+
const keys = key.split(".");
|
|
5494
|
+
keys.forEach((key2, index) => {
|
|
5495
|
+
if (index === keys.length - 1) nestedForm[key2] = value;
|
|
5496
|
+
else {
|
|
5497
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
5498
|
+
nestedForm = nestedForm[key2];
|
|
5499
|
+
}
|
|
5500
|
+
});
|
|
5501
|
+
};
|
|
5502
|
+
//#endregion
|
|
5503
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/url.js
|
|
5504
|
+
var splitPath = (path) => {
|
|
5505
|
+
const paths = path.split("/");
|
|
5506
|
+
if (paths[0] === "") paths.shift();
|
|
5507
|
+
return paths;
|
|
5508
|
+
};
|
|
5509
|
+
var splitRoutingPath = (routePath) => {
|
|
5510
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
5511
|
+
return replaceGroupMarks(splitPath(path), groups);
|
|
5512
|
+
};
|
|
5513
|
+
var extractGroupsFromPath = (path) => {
|
|
5514
|
+
const groups = [];
|
|
5515
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
5516
|
+
const mark = `@${index}`;
|
|
5517
|
+
groups.push([mark, match]);
|
|
5518
|
+
return mark;
|
|
5519
|
+
});
|
|
5520
|
+
return {
|
|
5521
|
+
groups,
|
|
5522
|
+
path
|
|
5523
|
+
};
|
|
5524
|
+
};
|
|
5525
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
5526
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
5527
|
+
const [mark] = groups[i];
|
|
5528
|
+
for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
|
|
5529
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
5530
|
+
break;
|
|
5531
|
+
}
|
|
5532
|
+
}
|
|
5533
|
+
return paths;
|
|
5534
|
+
};
|
|
5535
|
+
var patternCache = {};
|
|
5536
|
+
var getPattern = (label, next) => {
|
|
5537
|
+
if (label === "*") return "*";
|
|
5538
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
5539
|
+
if (match) {
|
|
5540
|
+
const cacheKey = `${label}#${next}`;
|
|
5541
|
+
if (!patternCache[cacheKey]) if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
|
|
5542
|
+
cacheKey,
|
|
5543
|
+
match[1],
|
|
5544
|
+
new RegExp(`^${match[2]}(?=/${next})`)
|
|
5545
|
+
] : [
|
|
5546
|
+
label,
|
|
5547
|
+
match[1],
|
|
5548
|
+
new RegExp(`^${match[2]}$`)
|
|
5549
|
+
];
|
|
5550
|
+
else patternCache[cacheKey] = [
|
|
5551
|
+
label,
|
|
5552
|
+
match[1],
|
|
5553
|
+
true
|
|
5554
|
+
];
|
|
5555
|
+
return patternCache[cacheKey];
|
|
5556
|
+
}
|
|
5557
|
+
return null;
|
|
5558
|
+
};
|
|
5559
|
+
var tryDecode = (str, decoder) => {
|
|
5560
|
+
try {
|
|
5561
|
+
return decoder(str);
|
|
5562
|
+
} catch {
|
|
5563
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
5564
|
+
try {
|
|
5565
|
+
return decoder(match);
|
|
5566
|
+
} catch {
|
|
5567
|
+
return match;
|
|
5568
|
+
}
|
|
5569
|
+
});
|
|
5570
|
+
}
|
|
5571
|
+
};
|
|
5572
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
5573
|
+
var getPath = (request) => {
|
|
5574
|
+
const url = request.url;
|
|
5575
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
5576
|
+
let i = start;
|
|
5577
|
+
for (; i < url.length; i++) {
|
|
5578
|
+
const charCode = url.charCodeAt(i);
|
|
5579
|
+
if (charCode === 37) {
|
|
5580
|
+
const queryIndex = url.indexOf("?", i);
|
|
5581
|
+
const hashIndex = url.indexOf("#", i);
|
|
5582
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
5583
|
+
const path = url.slice(start, end);
|
|
5584
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
5585
|
+
} else if (charCode === 63 || charCode === 35) break;
|
|
5586
|
+
}
|
|
5587
|
+
return url.slice(start, i);
|
|
5588
|
+
};
|
|
5589
|
+
var getPathNoStrict = (request) => {
|
|
5590
|
+
const result = getPath(request);
|
|
5591
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
5592
|
+
};
|
|
5593
|
+
var mergePath = (base, sub, ...rest) => {
|
|
5594
|
+
if (rest.length) sub = mergePath(sub, ...rest);
|
|
5595
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
5596
|
+
};
|
|
5597
|
+
var checkOptionalParameter = (path) => {
|
|
5598
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
|
|
5599
|
+
const segments = path.split("/");
|
|
5600
|
+
const results = [];
|
|
5601
|
+
let basePath = "";
|
|
5602
|
+
segments.forEach((segment) => {
|
|
5603
|
+
if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
|
|
5604
|
+
else if (/\:/.test(segment)) if (/\?/.test(segment)) {
|
|
5605
|
+
if (results.length === 0 && basePath === "") results.push("/");
|
|
5606
|
+
else results.push(basePath);
|
|
5607
|
+
const optionalSegment = segment.replace("?", "");
|
|
5608
|
+
basePath += "/" + optionalSegment;
|
|
5609
|
+
results.push(basePath);
|
|
5610
|
+
} else basePath += "/" + segment;
|
|
5611
|
+
});
|
|
5612
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
5613
|
+
};
|
|
5614
|
+
var _decodeURI = (value) => {
|
|
5615
|
+
if (!/[%+]/.test(value)) return value;
|
|
5616
|
+
if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
|
|
5617
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
5618
|
+
};
|
|
5619
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
5620
|
+
let encoded;
|
|
5621
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
5622
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
5623
|
+
if (keyIndex2 === -1) return;
|
|
5624
|
+
if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
5625
|
+
while (keyIndex2 !== -1) {
|
|
5626
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
5627
|
+
if (trailingKeyCode === 61) {
|
|
5628
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
5629
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
5630
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
5631
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
|
|
5632
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
5633
|
+
}
|
|
5634
|
+
encoded = /[%+]/.test(url);
|
|
5635
|
+
if (!encoded) return;
|
|
5636
|
+
}
|
|
5637
|
+
const results = {};
|
|
5638
|
+
encoded ??= /[%+]/.test(url);
|
|
5639
|
+
let keyIndex = url.indexOf("?", 8);
|
|
5640
|
+
while (keyIndex !== -1) {
|
|
5641
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
5642
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
5643
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
|
|
5644
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
|
|
5645
|
+
if (encoded) name = _decodeURI(name);
|
|
5646
|
+
keyIndex = nextKeyIndex;
|
|
5647
|
+
if (name === "") continue;
|
|
5648
|
+
let value;
|
|
5649
|
+
if (valueIndex === -1) value = "";
|
|
5650
|
+
else {
|
|
5651
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
5652
|
+
if (encoded) value = _decodeURI(value);
|
|
5653
|
+
}
|
|
5654
|
+
if (multiple) {
|
|
5655
|
+
if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
|
|
5656
|
+
results[name].push(value);
|
|
5657
|
+
} else results[name] ??= value;
|
|
5658
|
+
}
|
|
5659
|
+
return key ? results[key] : results;
|
|
5660
|
+
};
|
|
5661
|
+
var getQueryParam = _getQueryParam;
|
|
5662
|
+
var getQueryParams = (url, key) => {
|
|
5663
|
+
return _getQueryParam(url, key, true);
|
|
5664
|
+
};
|
|
5665
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
5666
|
+
//#endregion
|
|
5667
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/request.js
|
|
5668
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
5669
|
+
var HonoRequest = class {
|
|
5670
|
+
/**
|
|
5671
|
+
* `.raw` can get the raw Request object.
|
|
5672
|
+
*
|
|
5673
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
5674
|
+
*
|
|
5675
|
+
* @example
|
|
5676
|
+
* ```ts
|
|
5677
|
+
* // For Cloudflare Workers
|
|
5678
|
+
* app.post('/', async (c) => {
|
|
5679
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
5680
|
+
* ...
|
|
5681
|
+
* })
|
|
5682
|
+
* ```
|
|
5683
|
+
*/
|
|
5684
|
+
raw;
|
|
5685
|
+
#validatedData;
|
|
5686
|
+
#matchResult;
|
|
5687
|
+
routeIndex = 0;
|
|
5688
|
+
/**
|
|
5689
|
+
* `.path` can get the pathname of the request.
|
|
5690
|
+
*
|
|
5691
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
5692
|
+
*
|
|
5693
|
+
* @example
|
|
5694
|
+
* ```ts
|
|
5695
|
+
* app.get('/about/me', (c) => {
|
|
5696
|
+
* const pathname = c.req.path // `/about/me`
|
|
5697
|
+
* })
|
|
5698
|
+
* ```
|
|
5699
|
+
*/
|
|
5700
|
+
path;
|
|
5701
|
+
bodyCache = {};
|
|
5702
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
5703
|
+
this.raw = request;
|
|
5704
|
+
this.path = path;
|
|
5705
|
+
this.#matchResult = matchResult;
|
|
5706
|
+
this.#validatedData = {};
|
|
5707
|
+
}
|
|
5708
|
+
param(key) {
|
|
5709
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
5710
|
+
}
|
|
5711
|
+
#getDecodedParam(key) {
|
|
5712
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
5713
|
+
const param = this.#getParamValue(paramKey);
|
|
5714
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
5715
|
+
}
|
|
5716
|
+
#getAllDecodedParams() {
|
|
5717
|
+
const decoded = {};
|
|
5718
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
5719
|
+
for (const key of keys) {
|
|
5720
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
5721
|
+
if (value !== void 0) decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
5722
|
+
}
|
|
5723
|
+
return decoded;
|
|
5724
|
+
}
|
|
5725
|
+
#getParamValue(paramKey) {
|
|
5726
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
5727
|
+
}
|
|
5728
|
+
query(key) {
|
|
5729
|
+
return getQueryParam(this.url, key);
|
|
5730
|
+
}
|
|
5731
|
+
queries(key) {
|
|
5732
|
+
return getQueryParams(this.url, key);
|
|
5733
|
+
}
|
|
5734
|
+
header(name) {
|
|
5735
|
+
if (name) return this.raw.headers.get(name) ?? void 0;
|
|
5736
|
+
const headerData = {};
|
|
5737
|
+
this.raw.headers.forEach((value, key) => {
|
|
5738
|
+
headerData[key] = value;
|
|
5739
|
+
});
|
|
5740
|
+
return headerData;
|
|
5741
|
+
}
|
|
5742
|
+
async parseBody(options) {
|
|
5743
|
+
return parseBody(this, options);
|
|
5744
|
+
}
|
|
5745
|
+
#cachedBody = (key) => {
|
|
5746
|
+
const { bodyCache, raw } = this;
|
|
5747
|
+
const cachedBody = bodyCache[key];
|
|
5748
|
+
if (cachedBody) return cachedBody;
|
|
5749
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
5750
|
+
if (anyCachedKey) return bodyCache[anyCachedKey].then((body) => {
|
|
5751
|
+
if (anyCachedKey === "json") body = JSON.stringify(body);
|
|
5752
|
+
return new Response(body)[key]();
|
|
5753
|
+
});
|
|
5754
|
+
return bodyCache[key] = raw[key]();
|
|
5755
|
+
};
|
|
5756
|
+
/**
|
|
5757
|
+
* `.json()` can parse Request body of type `application/json`
|
|
5758
|
+
*
|
|
5759
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
5760
|
+
*
|
|
5761
|
+
* @example
|
|
5762
|
+
* ```ts
|
|
5763
|
+
* app.post('/entry', async (c) => {
|
|
5764
|
+
* const body = await c.req.json()
|
|
5765
|
+
* })
|
|
5766
|
+
* ```
|
|
5767
|
+
*/
|
|
5768
|
+
json() {
|
|
5769
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
5770
|
+
}
|
|
5771
|
+
/**
|
|
5772
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
5773
|
+
*
|
|
5774
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
5775
|
+
*
|
|
5776
|
+
* @example
|
|
5777
|
+
* ```ts
|
|
5778
|
+
* app.post('/entry', async (c) => {
|
|
5779
|
+
* const body = await c.req.text()
|
|
5780
|
+
* })
|
|
5781
|
+
* ```
|
|
5782
|
+
*/
|
|
5783
|
+
text() {
|
|
5784
|
+
return this.#cachedBody("text");
|
|
5785
|
+
}
|
|
5786
|
+
/**
|
|
5787
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
5788
|
+
*
|
|
5789
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
5790
|
+
*
|
|
5791
|
+
* @example
|
|
5792
|
+
* ```ts
|
|
5793
|
+
* app.post('/entry', async (c) => {
|
|
5794
|
+
* const body = await c.req.arrayBuffer()
|
|
5795
|
+
* })
|
|
5796
|
+
* ```
|
|
5797
|
+
*/
|
|
5798
|
+
arrayBuffer() {
|
|
5799
|
+
return this.#cachedBody("arrayBuffer");
|
|
5800
|
+
}
|
|
5801
|
+
/**
|
|
5802
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
5803
|
+
*
|
|
5804
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
5805
|
+
*
|
|
5806
|
+
* @example
|
|
5807
|
+
* ```ts
|
|
5808
|
+
* app.post('/entry', async (c) => {
|
|
5809
|
+
* const body = await c.req.bytes()
|
|
5810
|
+
* })
|
|
5811
|
+
* ```
|
|
5812
|
+
*/
|
|
5813
|
+
bytes() {
|
|
5814
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
5815
|
+
}
|
|
5816
|
+
/**
|
|
5817
|
+
* Parses the request body as a `Blob`.
|
|
5818
|
+
* @example
|
|
5819
|
+
* ```ts
|
|
5820
|
+
* app.post('/entry', async (c) => {
|
|
5821
|
+
* const body = await c.req.blob();
|
|
5822
|
+
* });
|
|
5823
|
+
* ```
|
|
5824
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
5825
|
+
*/
|
|
5826
|
+
blob() {
|
|
5827
|
+
return this.#cachedBody("blob");
|
|
5828
|
+
}
|
|
5829
|
+
/**
|
|
5830
|
+
* Parses the request body as `FormData`.
|
|
5831
|
+
* @example
|
|
5832
|
+
* ```ts
|
|
5833
|
+
* app.post('/entry', async (c) => {
|
|
5834
|
+
* const body = await c.req.formData();
|
|
5835
|
+
* });
|
|
5836
|
+
* ```
|
|
5837
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
5838
|
+
*/
|
|
5839
|
+
formData() {
|
|
5840
|
+
return this.#cachedBody("formData");
|
|
5841
|
+
}
|
|
5842
|
+
/**
|
|
5843
|
+
* Adds validated data to the request.
|
|
5844
|
+
*
|
|
5845
|
+
* @param target - The target of the validation.
|
|
5846
|
+
* @param data - The validated data to add.
|
|
5847
|
+
*/
|
|
5848
|
+
addValidatedData(target, data) {
|
|
5849
|
+
this.#validatedData[target] = data;
|
|
5850
|
+
}
|
|
5851
|
+
valid(target) {
|
|
5852
|
+
return this.#validatedData[target];
|
|
5853
|
+
}
|
|
5854
|
+
/**
|
|
5855
|
+
* `.url()` can get the request url strings.
|
|
5856
|
+
*
|
|
5857
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
5858
|
+
*
|
|
5859
|
+
* @example
|
|
5860
|
+
* ```ts
|
|
5861
|
+
* app.get('/about/me', (c) => {
|
|
5862
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
5863
|
+
* ...
|
|
5864
|
+
* })
|
|
5865
|
+
* ```
|
|
5866
|
+
*/
|
|
5867
|
+
get url() {
|
|
5868
|
+
return this.raw.url;
|
|
5869
|
+
}
|
|
5870
|
+
/**
|
|
5871
|
+
* `.method()` can get the method name of the request.
|
|
5872
|
+
*
|
|
5873
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
5874
|
+
*
|
|
5875
|
+
* @example
|
|
5876
|
+
* ```ts
|
|
5877
|
+
* app.get('/about/me', (c) => {
|
|
5878
|
+
* const method = c.req.method // `GET`
|
|
5879
|
+
* })
|
|
5880
|
+
* ```
|
|
5881
|
+
*/
|
|
5882
|
+
get method() {
|
|
5883
|
+
return this.raw.method;
|
|
5884
|
+
}
|
|
5885
|
+
get [GET_MATCH_RESULT]() {
|
|
5886
|
+
return this.#matchResult;
|
|
5887
|
+
}
|
|
5888
|
+
/**
|
|
5889
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
5890
|
+
*
|
|
5891
|
+
* @deprecated
|
|
5892
|
+
*
|
|
5893
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
5894
|
+
*
|
|
5895
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
5896
|
+
*
|
|
5897
|
+
* @example
|
|
5898
|
+
* ```ts
|
|
5899
|
+
* app.use('*', async function logger(c, next) {
|
|
5900
|
+
* await next()
|
|
5901
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
5902
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
5903
|
+
* console.log(
|
|
5904
|
+
* method,
|
|
5905
|
+
* ' ',
|
|
5906
|
+
* path,
|
|
5907
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
5908
|
+
* name,
|
|
5909
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
5910
|
+
* )
|
|
5911
|
+
* })
|
|
5912
|
+
* })
|
|
5913
|
+
* ```
|
|
5914
|
+
*/
|
|
5915
|
+
get matchedRoutes() {
|
|
5916
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
5917
|
+
}
|
|
5918
|
+
/**
|
|
5919
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
5920
|
+
*
|
|
5921
|
+
* @deprecated
|
|
5922
|
+
*
|
|
5923
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
5924
|
+
*
|
|
5925
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
5926
|
+
*
|
|
5927
|
+
* @example
|
|
5928
|
+
* ```ts
|
|
5929
|
+
* app.get('/posts/:id', (c) => {
|
|
5930
|
+
* return c.json({ path: c.req.routePath })
|
|
5931
|
+
* })
|
|
5932
|
+
* ```
|
|
5933
|
+
*/
|
|
5934
|
+
get routePath() {
|
|
5935
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
5936
|
+
}
|
|
5937
|
+
};
|
|
5938
|
+
//#endregion
|
|
5939
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/html.js
|
|
5940
|
+
var HtmlEscapedCallbackPhase = {
|
|
5941
|
+
Stringify: 1,
|
|
5942
|
+
BeforeStream: 2,
|
|
5943
|
+
Stream: 3
|
|
5944
|
+
};
|
|
5945
|
+
var raw = (value, callbacks) => {
|
|
5946
|
+
const escapedString = new String(value);
|
|
5947
|
+
escapedString.isEscaped = true;
|
|
5948
|
+
escapedString.callbacks = callbacks;
|
|
5949
|
+
return escapedString;
|
|
5950
|
+
};
|
|
5951
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
5952
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
5953
|
+
if (!(str instanceof Promise)) str = str.toString();
|
|
5954
|
+
if (str instanceof Promise) str = await str;
|
|
5955
|
+
}
|
|
5956
|
+
const callbacks = str.callbacks;
|
|
5957
|
+
if (!callbacks?.length) return Promise.resolve(str);
|
|
5958
|
+
if (buffer) buffer[0] += str;
|
|
5959
|
+
else buffer = [str];
|
|
5960
|
+
const resStr = Promise.all(callbacks.map((c) => c({
|
|
5961
|
+
phase,
|
|
5962
|
+
buffer,
|
|
5963
|
+
context
|
|
5964
|
+
}))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
5965
|
+
if (preserveCallbacks) return raw(await resStr, callbacks);
|
|
5966
|
+
else return resStr;
|
|
5967
|
+
};
|
|
5968
|
+
//#endregion
|
|
5969
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/context.js
|
|
5970
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
5971
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
5972
|
+
return {
|
|
5973
|
+
"Content-Type": contentType,
|
|
5974
|
+
...headers
|
|
5975
|
+
};
|
|
5976
|
+
};
|
|
5977
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
5978
|
+
var Context = class {
|
|
5979
|
+
#rawRequest;
|
|
5980
|
+
#req;
|
|
5981
|
+
/**
|
|
5982
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
5983
|
+
*
|
|
5984
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
5985
|
+
*
|
|
5986
|
+
* @example
|
|
5987
|
+
* ```ts
|
|
5988
|
+
* // Environment object for Cloudflare Workers
|
|
5989
|
+
* app.get('*', async c => {
|
|
5990
|
+
* const counter = c.env.COUNTER
|
|
5991
|
+
* })
|
|
5992
|
+
* ```
|
|
5993
|
+
*/
|
|
5994
|
+
env = {};
|
|
5995
|
+
#var;
|
|
5996
|
+
finalized = false;
|
|
5997
|
+
/**
|
|
5998
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
5999
|
+
*
|
|
6000
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
6001
|
+
*
|
|
6002
|
+
* @example
|
|
6003
|
+
* ```ts
|
|
6004
|
+
* app.use('*', async (c, next) => {
|
|
6005
|
+
* await next()
|
|
6006
|
+
* if (c.error) {
|
|
6007
|
+
* // do something...
|
|
6008
|
+
* }
|
|
6009
|
+
* })
|
|
6010
|
+
* ```
|
|
6011
|
+
*/
|
|
6012
|
+
error;
|
|
6013
|
+
#status;
|
|
6014
|
+
#executionCtx;
|
|
6015
|
+
#res;
|
|
6016
|
+
#layout;
|
|
6017
|
+
#renderer;
|
|
6018
|
+
#notFoundHandler;
|
|
6019
|
+
#preparedHeaders;
|
|
6020
|
+
#matchResult;
|
|
6021
|
+
#path;
|
|
6022
|
+
/**
|
|
6023
|
+
* Creates an instance of the Context class.
|
|
6024
|
+
*
|
|
6025
|
+
* @param req - The Request object.
|
|
6026
|
+
* @param options - Optional configuration options for the context.
|
|
6027
|
+
*/
|
|
6028
|
+
constructor(req, options) {
|
|
6029
|
+
this.#rawRequest = req;
|
|
6030
|
+
if (options) {
|
|
6031
|
+
this.#executionCtx = options.executionCtx;
|
|
6032
|
+
this.env = options.env;
|
|
6033
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
6034
|
+
this.#path = options.path;
|
|
6035
|
+
this.#matchResult = options.matchResult;
|
|
6036
|
+
}
|
|
6037
|
+
}
|
|
6038
|
+
/**
|
|
6039
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
6040
|
+
*/
|
|
6041
|
+
get req() {
|
|
6042
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
6043
|
+
return this.#req;
|
|
6044
|
+
}
|
|
6045
|
+
/**
|
|
6046
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
6047
|
+
* The FetchEvent associated with the current request.
|
|
6048
|
+
*
|
|
6049
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
6050
|
+
*/
|
|
6051
|
+
get event() {
|
|
6052
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) return this.#executionCtx;
|
|
6053
|
+
else throw Error("This context has no FetchEvent");
|
|
6054
|
+
}
|
|
6055
|
+
/**
|
|
6056
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
6057
|
+
* The ExecutionContext associated with the current request.
|
|
6058
|
+
*
|
|
6059
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
6060
|
+
*/
|
|
6061
|
+
get executionCtx() {
|
|
6062
|
+
if (this.#executionCtx) return this.#executionCtx;
|
|
6063
|
+
else throw Error("This context has no ExecutionContext");
|
|
6064
|
+
}
|
|
6065
|
+
/**
|
|
6066
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
6067
|
+
* The Response object for the current request.
|
|
6068
|
+
*/
|
|
6069
|
+
get res() {
|
|
6070
|
+
return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });
|
|
6071
|
+
}
|
|
6072
|
+
/**
|
|
6073
|
+
* Sets the Response object for the current request.
|
|
6074
|
+
*
|
|
6075
|
+
* @param _res - The Response object to set.
|
|
6076
|
+
*/
|
|
6077
|
+
set res(_res) {
|
|
6078
|
+
if (this.#res && _res) {
|
|
6079
|
+
_res = createResponseInstance(_res.body, _res);
|
|
6080
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
6081
|
+
if (k === "content-type") continue;
|
|
6082
|
+
if (k === "set-cookie") {
|
|
6083
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
6084
|
+
_res.headers.delete("set-cookie");
|
|
6085
|
+
for (const cookie of cookies) _res.headers.append("set-cookie", cookie);
|
|
6086
|
+
} else _res.headers.set(k, v);
|
|
6087
|
+
}
|
|
6088
|
+
}
|
|
6089
|
+
this.#res = _res;
|
|
6090
|
+
this.finalized = true;
|
|
6091
|
+
}
|
|
6092
|
+
/**
|
|
6093
|
+
* `.render()` can create a response within a layout.
|
|
6094
|
+
*
|
|
6095
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
6096
|
+
*
|
|
6097
|
+
* @example
|
|
6098
|
+
* ```ts
|
|
6099
|
+
* app.get('/', (c) => {
|
|
6100
|
+
* return c.render('Hello!')
|
|
6101
|
+
* })
|
|
6102
|
+
* ```
|
|
6103
|
+
*/
|
|
6104
|
+
render = (...args) => {
|
|
6105
|
+
this.#renderer ??= (content) => this.html(content);
|
|
6106
|
+
return this.#renderer(...args);
|
|
6107
|
+
};
|
|
6108
|
+
/**
|
|
6109
|
+
* Sets the layout for the response.
|
|
6110
|
+
*
|
|
6111
|
+
* @param layout - The layout to set.
|
|
6112
|
+
* @returns The layout function.
|
|
6113
|
+
*/
|
|
6114
|
+
setLayout = (layout) => this.#layout = layout;
|
|
6115
|
+
/**
|
|
6116
|
+
* Gets the current layout for the response.
|
|
6117
|
+
*
|
|
6118
|
+
* @returns The current layout function.
|
|
6119
|
+
*/
|
|
6120
|
+
getLayout = () => this.#layout;
|
|
6121
|
+
/**
|
|
6122
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
6123
|
+
*
|
|
6124
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
6125
|
+
*
|
|
6126
|
+
* @example
|
|
6127
|
+
* ```tsx
|
|
6128
|
+
* app.use('*', async (c, next) => {
|
|
6129
|
+
* c.setRenderer((content) => {
|
|
6130
|
+
* return c.html(
|
|
6131
|
+
* <html>
|
|
6132
|
+
* <body>
|
|
6133
|
+
* <p>{content}</p>
|
|
6134
|
+
* </body>
|
|
6135
|
+
* </html>
|
|
6136
|
+
* )
|
|
6137
|
+
* })
|
|
6138
|
+
* await next()
|
|
6139
|
+
* })
|
|
6140
|
+
* ```
|
|
6141
|
+
*/
|
|
6142
|
+
setRenderer = (renderer) => {
|
|
6143
|
+
this.#renderer = renderer;
|
|
6144
|
+
};
|
|
6145
|
+
/**
|
|
6146
|
+
* `.header()` can set headers.
|
|
6147
|
+
*
|
|
6148
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
6149
|
+
*
|
|
6150
|
+
* @example
|
|
6151
|
+
* ```ts
|
|
6152
|
+
* app.get('/welcome', (c) => {
|
|
6153
|
+
* // Set headers
|
|
6154
|
+
* c.header('X-Message', 'Hello!')
|
|
6155
|
+
* c.header('Content-Type', 'text/plain')
|
|
6156
|
+
*
|
|
6157
|
+
* return c.body('Thank you for coming')
|
|
6158
|
+
* })
|
|
6159
|
+
* ```
|
|
6160
|
+
*/
|
|
6161
|
+
header = (name, value, options) => {
|
|
6162
|
+
if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
6163
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
6164
|
+
if (value === void 0) headers.delete(name);
|
|
6165
|
+
else if (options?.append) headers.append(name, value);
|
|
6166
|
+
else headers.set(name, value);
|
|
6167
|
+
};
|
|
6168
|
+
status = (status) => {
|
|
6169
|
+
this.#status = status;
|
|
6170
|
+
};
|
|
6171
|
+
/**
|
|
6172
|
+
* `.set()` can set the value specified by the key.
|
|
6173
|
+
*
|
|
6174
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
6175
|
+
*
|
|
6176
|
+
* @example
|
|
6177
|
+
* ```ts
|
|
6178
|
+
* app.use('*', async (c, next) => {
|
|
6179
|
+
* c.set('message', 'Hono is hot!!')
|
|
6180
|
+
* await next()
|
|
6181
|
+
* })
|
|
6182
|
+
* ```
|
|
6183
|
+
*/
|
|
6184
|
+
set = (key, value) => {
|
|
6185
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
6186
|
+
this.#var.set(key, value);
|
|
6187
|
+
};
|
|
6188
|
+
/**
|
|
6189
|
+
* `.get()` can use the value specified by the key.
|
|
6190
|
+
*
|
|
6191
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
6192
|
+
*
|
|
6193
|
+
* @example
|
|
6194
|
+
* ```ts
|
|
6195
|
+
* app.get('/', (c) => {
|
|
6196
|
+
* const message = c.get('message')
|
|
6197
|
+
* return c.text(`The message is "${message}"`)
|
|
6198
|
+
* })
|
|
6199
|
+
* ```
|
|
6200
|
+
*/
|
|
6201
|
+
get = (key) => {
|
|
6202
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
6203
|
+
};
|
|
6204
|
+
/**
|
|
6205
|
+
* `.var` can access the value of a variable.
|
|
6206
|
+
*
|
|
6207
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
6208
|
+
*
|
|
6209
|
+
* @example
|
|
6210
|
+
* ```ts
|
|
6211
|
+
* const result = c.var.client.oneMethod()
|
|
6212
|
+
* ```
|
|
6213
|
+
*/
|
|
6214
|
+
get var() {
|
|
6215
|
+
if (!this.#var) return {};
|
|
6216
|
+
return Object.fromEntries(this.#var);
|
|
6217
|
+
}
|
|
6218
|
+
#newResponse(data, arg, headers) {
|
|
6219
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
6220
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
6221
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
6222
|
+
for (const [key, value] of argHeaders) if (key.toLowerCase() === "set-cookie") responseHeaders.append(key, value);
|
|
6223
|
+
else responseHeaders.set(key, value);
|
|
6224
|
+
}
|
|
6225
|
+
if (headers) for (const [k, v] of Object.entries(headers)) if (typeof v === "string") responseHeaders.set(k, v);
|
|
6226
|
+
else {
|
|
6227
|
+
responseHeaders.delete(k);
|
|
6228
|
+
for (const v2 of v) responseHeaders.append(k, v2);
|
|
6229
|
+
}
|
|
6230
|
+
return createResponseInstance(data, {
|
|
6231
|
+
status: typeof arg === "number" ? arg : arg?.status ?? this.#status,
|
|
6232
|
+
headers: responseHeaders
|
|
6233
|
+
});
|
|
6234
|
+
}
|
|
6235
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
6236
|
+
/**
|
|
6237
|
+
* `.body()` can return the HTTP response.
|
|
6238
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
6239
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
6240
|
+
*
|
|
6241
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
6242
|
+
*
|
|
6243
|
+
* @example
|
|
6244
|
+
* ```ts
|
|
6245
|
+
* app.get('/welcome', (c) => {
|
|
6246
|
+
* // Set headers
|
|
6247
|
+
* c.header('X-Message', 'Hello!')
|
|
6248
|
+
* c.header('Content-Type', 'text/plain')
|
|
6249
|
+
* // Set HTTP status code
|
|
6250
|
+
* c.status(201)
|
|
6251
|
+
*
|
|
6252
|
+
* // Return the response body
|
|
6253
|
+
* return c.body('Thank you for coming')
|
|
6254
|
+
* })
|
|
6255
|
+
* ```
|
|
6256
|
+
*/
|
|
6257
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
6258
|
+
/**
|
|
6259
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
6260
|
+
*
|
|
6261
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
6262
|
+
*
|
|
6263
|
+
* @example
|
|
6264
|
+
* ```ts
|
|
6265
|
+
* app.get('/say', (c) => {
|
|
6266
|
+
* return c.text('Hello!')
|
|
6267
|
+
* })
|
|
6268
|
+
* ```
|
|
6269
|
+
*/
|
|
6270
|
+
text = (text, arg, headers) => {
|
|
6271
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
6272
|
+
};
|
|
6273
|
+
/**
|
|
6274
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
6275
|
+
*
|
|
6276
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
6277
|
+
*
|
|
6278
|
+
* @example
|
|
6279
|
+
* ```ts
|
|
6280
|
+
* app.get('/api', (c) => {
|
|
6281
|
+
* return c.json({ message: 'Hello!' })
|
|
6282
|
+
* })
|
|
6283
|
+
* ```
|
|
6284
|
+
*/
|
|
6285
|
+
json = (object, arg, headers) => {
|
|
6286
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
6287
|
+
};
|
|
6288
|
+
html = (html, arg, headers) => {
|
|
6289
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
6290
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
6291
|
+
};
|
|
6292
|
+
/**
|
|
6293
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
6294
|
+
*
|
|
6295
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
6296
|
+
*
|
|
6297
|
+
* @example
|
|
6298
|
+
* ```ts
|
|
6299
|
+
* app.get('/redirect', (c) => {
|
|
6300
|
+
* return c.redirect('/')
|
|
6301
|
+
* })
|
|
6302
|
+
* app.get('/redirect-permanently', (c) => {
|
|
6303
|
+
* return c.redirect('/', 301)
|
|
6304
|
+
* })
|
|
6305
|
+
* ```
|
|
6306
|
+
*/
|
|
6307
|
+
redirect = (location, status) => {
|
|
6308
|
+
const locationString = String(location);
|
|
6309
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
6310
|
+
return this.newResponse(null, status ?? 302);
|
|
6311
|
+
};
|
|
6312
|
+
/**
|
|
6313
|
+
* `.notFound()` can return the Not Found Response.
|
|
6314
|
+
*
|
|
6315
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
6316
|
+
*
|
|
6317
|
+
* @example
|
|
6318
|
+
* ```ts
|
|
6319
|
+
* app.get('/notfound', (c) => {
|
|
6320
|
+
* return c.notFound()
|
|
6321
|
+
* })
|
|
6322
|
+
* ```
|
|
6323
|
+
*/
|
|
6324
|
+
notFound = () => {
|
|
6325
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
6326
|
+
return this.#notFoundHandler(this);
|
|
6327
|
+
};
|
|
6328
|
+
};
|
|
6329
|
+
//#endregion
|
|
6330
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router.js
|
|
6331
|
+
var METHODS = [
|
|
6332
|
+
"get",
|
|
6333
|
+
"post",
|
|
6334
|
+
"put",
|
|
6335
|
+
"delete",
|
|
6336
|
+
"options",
|
|
6337
|
+
"patch"
|
|
6338
|
+
];
|
|
6339
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
6340
|
+
var UnsupportedPathError = class extends Error {};
|
|
6341
|
+
//#endregion
|
|
6342
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/constants.js
|
|
6343
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
6344
|
+
//#endregion
|
|
6345
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/hono-base.js
|
|
6346
|
+
var notFoundHandler = (c) => {
|
|
6347
|
+
return c.text("404 Not Found", 404);
|
|
6348
|
+
};
|
|
6349
|
+
var errorHandler = (err, c) => {
|
|
6350
|
+
if ("getResponse" in err) {
|
|
6351
|
+
const res = err.getResponse();
|
|
6352
|
+
return c.newResponse(res.body, res);
|
|
6353
|
+
}
|
|
6354
|
+
console.error(err);
|
|
6355
|
+
return c.text("Internal Server Error", 500);
|
|
6356
|
+
};
|
|
6357
|
+
var Hono$1 = class _Hono {
|
|
6358
|
+
get;
|
|
6359
|
+
post;
|
|
6360
|
+
put;
|
|
6361
|
+
delete;
|
|
6362
|
+
options;
|
|
6363
|
+
patch;
|
|
6364
|
+
all;
|
|
6365
|
+
on;
|
|
6366
|
+
use;
|
|
6367
|
+
router;
|
|
6368
|
+
getPath;
|
|
6369
|
+
_basePath = "/";
|
|
6370
|
+
#path = "/";
|
|
6371
|
+
routes = [];
|
|
6372
|
+
constructor(options = {}) {
|
|
6373
|
+
[...METHODS, "all"].forEach((method) => {
|
|
6374
|
+
this[method] = (args1, ...args) => {
|
|
6375
|
+
if (typeof args1 === "string") this.#path = args1;
|
|
6376
|
+
else this.#addRoute(method, this.#path, args1);
|
|
6377
|
+
args.forEach((handler) => {
|
|
6378
|
+
this.#addRoute(method, this.#path, handler);
|
|
6379
|
+
});
|
|
6380
|
+
return this;
|
|
6381
|
+
};
|
|
6382
|
+
});
|
|
6383
|
+
this.on = (method, path, ...handlers) => {
|
|
6384
|
+
for (const p of [path].flat()) {
|
|
6385
|
+
this.#path = p;
|
|
6386
|
+
for (const m of [method].flat()) handlers.map((handler) => {
|
|
6387
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
6388
|
+
});
|
|
6389
|
+
}
|
|
6390
|
+
return this;
|
|
6391
|
+
};
|
|
6392
|
+
this.use = (arg1, ...handlers) => {
|
|
6393
|
+
if (typeof arg1 === "string") this.#path = arg1;
|
|
6394
|
+
else {
|
|
6395
|
+
this.#path = "*";
|
|
6396
|
+
handlers.unshift(arg1);
|
|
6397
|
+
}
|
|
6398
|
+
handlers.forEach((handler) => {
|
|
6399
|
+
this.#addRoute("ALL", this.#path, handler);
|
|
6400
|
+
});
|
|
6401
|
+
return this;
|
|
6402
|
+
};
|
|
6403
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
6404
|
+
Object.assign(this, optionsWithoutStrict);
|
|
6405
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
6406
|
+
}
|
|
6407
|
+
#clone() {
|
|
6408
|
+
const clone = new _Hono({
|
|
6409
|
+
router: this.router,
|
|
6410
|
+
getPath: this.getPath
|
|
6411
|
+
});
|
|
6412
|
+
clone.errorHandler = this.errorHandler;
|
|
6413
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
6414
|
+
clone.routes = this.routes;
|
|
6415
|
+
return clone;
|
|
6416
|
+
}
|
|
6417
|
+
#notFoundHandler = notFoundHandler;
|
|
6418
|
+
errorHandler = errorHandler;
|
|
6419
|
+
/**
|
|
6420
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
6421
|
+
*
|
|
6422
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
6423
|
+
*
|
|
6424
|
+
* @param {string} path - base Path
|
|
6425
|
+
* @param {Hono} app - other Hono instance
|
|
6426
|
+
* @returns {Hono} routed Hono instance
|
|
6427
|
+
*
|
|
6428
|
+
* @example
|
|
6429
|
+
* ```ts
|
|
6430
|
+
* const app = new Hono()
|
|
6431
|
+
* const app2 = new Hono()
|
|
6432
|
+
*
|
|
6433
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
6434
|
+
* app.route("/api", app2) // GET /api/user
|
|
6435
|
+
* ```
|
|
6436
|
+
*/
|
|
6437
|
+
route(path, app) {
|
|
6438
|
+
const subApp = this.basePath(path);
|
|
6439
|
+
app.routes.map((r) => {
|
|
6440
|
+
let handler;
|
|
6441
|
+
if (app.errorHandler === errorHandler) handler = r.handler;
|
|
6442
|
+
else {
|
|
6443
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
6444
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
6445
|
+
}
|
|
6446
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
6447
|
+
});
|
|
6448
|
+
return this;
|
|
6449
|
+
}
|
|
6450
|
+
/**
|
|
6451
|
+
* `.basePath()` allows base paths to be specified.
|
|
6452
|
+
*
|
|
6453
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
6454
|
+
*
|
|
6455
|
+
* @param {string} path - base Path
|
|
6456
|
+
* @returns {Hono} changed Hono instance
|
|
6457
|
+
*
|
|
6458
|
+
* @example
|
|
6459
|
+
* ```ts
|
|
6460
|
+
* const api = new Hono().basePath('/api')
|
|
6461
|
+
* ```
|
|
6462
|
+
*/
|
|
6463
|
+
basePath(path) {
|
|
6464
|
+
const subApp = this.#clone();
|
|
6465
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
6466
|
+
return subApp;
|
|
6467
|
+
}
|
|
6468
|
+
/**
|
|
6469
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
6470
|
+
*
|
|
6471
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
6472
|
+
*
|
|
6473
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
6474
|
+
* @returns {Hono} changed Hono instance
|
|
6475
|
+
*
|
|
6476
|
+
* @example
|
|
6477
|
+
* ```ts
|
|
6478
|
+
* app.onError((err, c) => {
|
|
6479
|
+
* console.error(`${err}`)
|
|
6480
|
+
* return c.text('Custom Error Message', 500)
|
|
6481
|
+
* })
|
|
6482
|
+
* ```
|
|
6483
|
+
*/
|
|
6484
|
+
onError = (handler) => {
|
|
6485
|
+
this.errorHandler = handler;
|
|
6486
|
+
return this;
|
|
6487
|
+
};
|
|
6488
|
+
/**
|
|
6489
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
6490
|
+
*
|
|
6491
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
6492
|
+
*
|
|
6493
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
6494
|
+
* @returns {Hono} changed Hono instance
|
|
6495
|
+
*
|
|
6496
|
+
* @example
|
|
6497
|
+
* ```ts
|
|
6498
|
+
* app.notFound((c) => {
|
|
6499
|
+
* return c.text('Custom 404 Message', 404)
|
|
6500
|
+
* })
|
|
6501
|
+
* ```
|
|
6502
|
+
*/
|
|
6503
|
+
notFound = (handler) => {
|
|
6504
|
+
this.#notFoundHandler = handler;
|
|
6505
|
+
return this;
|
|
6506
|
+
};
|
|
6507
|
+
/**
|
|
6508
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
6509
|
+
*
|
|
6510
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
6511
|
+
*
|
|
6512
|
+
* @param {string} path - base Path
|
|
6513
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
6514
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
6515
|
+
* @returns {Hono} mounted Hono instance
|
|
6516
|
+
*
|
|
6517
|
+
* @example
|
|
6518
|
+
* ```ts
|
|
6519
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
6520
|
+
* import { Hono } from 'hono'
|
|
6521
|
+
* // Create itty-router application
|
|
6522
|
+
* const ittyRouter = IttyRouter()
|
|
6523
|
+
* // GET /itty-router/hello
|
|
6524
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
6525
|
+
*
|
|
6526
|
+
* const app = new Hono()
|
|
6527
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
6528
|
+
* ```
|
|
6529
|
+
*
|
|
6530
|
+
* @example
|
|
6531
|
+
* ```ts
|
|
6532
|
+
* const app = new Hono()
|
|
6533
|
+
* // Send the request to another application without modification.
|
|
6534
|
+
* app.mount('/app', anotherApp, {
|
|
6535
|
+
* replaceRequest: (req) => req,
|
|
6536
|
+
* })
|
|
6537
|
+
* ```
|
|
6538
|
+
*/
|
|
6539
|
+
mount(path, applicationHandler, options) {
|
|
6540
|
+
let replaceRequest;
|
|
6541
|
+
let optionHandler;
|
|
6542
|
+
if (options) if (typeof options === "function") optionHandler = options;
|
|
6543
|
+
else {
|
|
6544
|
+
optionHandler = options.optionHandler;
|
|
6545
|
+
if (options.replaceRequest === false) replaceRequest = (request) => request;
|
|
6546
|
+
else replaceRequest = options.replaceRequest;
|
|
6547
|
+
}
|
|
6548
|
+
const getOptions = optionHandler ? (c) => {
|
|
6549
|
+
const options2 = optionHandler(c);
|
|
6550
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
6551
|
+
} : (c) => {
|
|
6552
|
+
let executionContext = void 0;
|
|
6553
|
+
try {
|
|
6554
|
+
executionContext = c.executionCtx;
|
|
6555
|
+
} catch {}
|
|
6556
|
+
return [c.env, executionContext];
|
|
6557
|
+
};
|
|
6558
|
+
replaceRequest ||= (() => {
|
|
6559
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
6560
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
6561
|
+
return (request) => {
|
|
6562
|
+
const url = new URL(request.url);
|
|
6563
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
6564
|
+
return new Request(url, request);
|
|
6565
|
+
};
|
|
6566
|
+
})();
|
|
6567
|
+
const handler = async (c, next) => {
|
|
6568
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
6569
|
+
if (res) return res;
|
|
6570
|
+
await next();
|
|
6571
|
+
};
|
|
6572
|
+
this.#addRoute("ALL", mergePath(path, "*"), handler);
|
|
6573
|
+
return this;
|
|
6574
|
+
}
|
|
6575
|
+
#addRoute(method, path, handler) {
|
|
6576
|
+
method = method.toUpperCase();
|
|
6577
|
+
path = mergePath(this._basePath, path);
|
|
6578
|
+
const r = {
|
|
6579
|
+
basePath: this._basePath,
|
|
6580
|
+
path,
|
|
6581
|
+
method,
|
|
6582
|
+
handler
|
|
6583
|
+
};
|
|
6584
|
+
this.router.add(method, path, [handler, r]);
|
|
6585
|
+
this.routes.push(r);
|
|
6586
|
+
}
|
|
6587
|
+
#handleError(err, c) {
|
|
6588
|
+
if (err instanceof Error) return this.errorHandler(err, c);
|
|
6589
|
+
throw err;
|
|
6590
|
+
}
|
|
6591
|
+
#dispatch(request, executionCtx, env, method) {
|
|
6592
|
+
if (method === "HEAD") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
6593
|
+
const path = this.getPath(request, { env });
|
|
6594
|
+
const matchResult = this.router.match(method, path);
|
|
6595
|
+
const c = new Context(request, {
|
|
6596
|
+
path,
|
|
6597
|
+
matchResult,
|
|
6598
|
+
env,
|
|
6599
|
+
executionCtx,
|
|
6600
|
+
notFoundHandler: this.#notFoundHandler
|
|
6601
|
+
});
|
|
6602
|
+
if (matchResult[0].length === 1) {
|
|
6603
|
+
let res;
|
|
6604
|
+
try {
|
|
6605
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
6606
|
+
c.res = await this.#notFoundHandler(c);
|
|
6607
|
+
});
|
|
6608
|
+
} catch (err) {
|
|
6609
|
+
return this.#handleError(err, c);
|
|
6610
|
+
}
|
|
6611
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
6612
|
+
}
|
|
6613
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
6614
|
+
return (async () => {
|
|
6615
|
+
try {
|
|
6616
|
+
const context = await composed(c);
|
|
6617
|
+
if (!context.finalized) throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
6618
|
+
return context.res;
|
|
6619
|
+
} catch (err) {
|
|
6620
|
+
return this.#handleError(err, c);
|
|
6621
|
+
}
|
|
6622
|
+
})();
|
|
6623
|
+
}
|
|
6624
|
+
/**
|
|
6625
|
+
* `.fetch()` will be entry point of your app.
|
|
6626
|
+
*
|
|
6627
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
6628
|
+
*
|
|
6629
|
+
* @param {Request} request - request Object of request
|
|
6630
|
+
* @param {Env} Env - env Object
|
|
6631
|
+
* @param {ExecutionContext} - context of execution
|
|
6632
|
+
* @returns {Response | Promise<Response>} response of request
|
|
6633
|
+
*
|
|
6634
|
+
*/
|
|
6635
|
+
fetch = (request, ...rest) => {
|
|
6636
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
6637
|
+
};
|
|
6638
|
+
/**
|
|
6639
|
+
* `.request()` is a useful method for testing.
|
|
6640
|
+
* You can pass a URL or pathname to send a GET request.
|
|
6641
|
+
* app will return a Response object.
|
|
6642
|
+
* ```ts
|
|
6643
|
+
* test('GET /hello is ok', async () => {
|
|
6644
|
+
* const res = await app.request('/hello')
|
|
6645
|
+
* expect(res.status).toBe(200)
|
|
6646
|
+
* })
|
|
6647
|
+
* ```
|
|
6648
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
6649
|
+
*/
|
|
6650
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
6651
|
+
if (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
6652
|
+
input = input.toString();
|
|
6653
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
6654
|
+
};
|
|
6655
|
+
/**
|
|
6656
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
6657
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
6658
|
+
* @deprecated
|
|
6659
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
6660
|
+
* ```ts
|
|
6661
|
+
* import { Hono } from 'hono'
|
|
6662
|
+
* import { fire } from 'hono/service-worker'
|
|
6663
|
+
*
|
|
6664
|
+
* const app = new Hono()
|
|
6665
|
+
* // ...
|
|
6666
|
+
* fire(app)
|
|
6667
|
+
* ```
|
|
6668
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
6669
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
6670
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
6671
|
+
*/
|
|
6672
|
+
fire = () => {
|
|
6673
|
+
addEventListener("fetch", (event) => {
|
|
6674
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
6675
|
+
});
|
|
6676
|
+
};
|
|
6677
|
+
};
|
|
6678
|
+
//#endregion
|
|
6679
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
6680
|
+
var emptyParam = [];
|
|
6681
|
+
function match(method, path) {
|
|
6682
|
+
const matchers = this.buildAllMatchers();
|
|
6683
|
+
const match2 = ((method2, path2) => {
|
|
6684
|
+
const matcher = matchers[method2] || matchers["ALL"];
|
|
6685
|
+
const staticMatch = matcher[2][path2];
|
|
6686
|
+
if (staticMatch) return staticMatch;
|
|
6687
|
+
const match3 = path2.match(matcher[0]);
|
|
6688
|
+
if (!match3) return [[], emptyParam];
|
|
6689
|
+
const index = match3.indexOf("", 1);
|
|
6690
|
+
return [matcher[1][index], match3];
|
|
6691
|
+
});
|
|
6692
|
+
this.match = match2;
|
|
6693
|
+
return match2(method, path);
|
|
6694
|
+
}
|
|
6695
|
+
//#endregion
|
|
6696
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
6697
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
6698
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
6699
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
6700
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
6701
|
+
var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
|
|
6702
|
+
function compareKey(a, b) {
|
|
6703
|
+
if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
6704
|
+
if (b.length === 1) return 1;
|
|
6705
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) return 1;
|
|
6706
|
+
else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) return -1;
|
|
6707
|
+
if (a === LABEL_REG_EXP_STR) return 1;
|
|
6708
|
+
else if (b === LABEL_REG_EXP_STR) return -1;
|
|
6709
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
6710
|
+
}
|
|
6711
|
+
var Node$1 = class _Node {
|
|
6712
|
+
#index;
|
|
6713
|
+
#varIndex;
|
|
6714
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
6715
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
6716
|
+
if (tokens.length === 0) {
|
|
6717
|
+
if (this.#index !== void 0) throw PATH_ERROR;
|
|
6718
|
+
if (pathErrorCheckOnly) return;
|
|
6719
|
+
this.#index = index;
|
|
6720
|
+
return;
|
|
6721
|
+
}
|
|
6722
|
+
const [token, ...restTokens] = tokens;
|
|
6723
|
+
const pattern = token === "*" ? restTokens.length === 0 ? [
|
|
6724
|
+
"",
|
|
6725
|
+
"",
|
|
6726
|
+
ONLY_WILDCARD_REG_EXP_STR
|
|
6727
|
+
] : [
|
|
6728
|
+
"",
|
|
6729
|
+
"",
|
|
6730
|
+
LABEL_REG_EXP_STR
|
|
6731
|
+
] : token === "/*" ? [
|
|
6732
|
+
"",
|
|
6733
|
+
"",
|
|
6734
|
+
TAIL_WILDCARD_REG_EXP_STR
|
|
6735
|
+
] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
6736
|
+
let node;
|
|
6737
|
+
if (pattern) {
|
|
6738
|
+
const name = pattern[1];
|
|
6739
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
6740
|
+
if (name && pattern[2]) {
|
|
6741
|
+
if (regexpStr === ".*") throw PATH_ERROR;
|
|
6742
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
6743
|
+
if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
|
|
6744
|
+
}
|
|
6745
|
+
node = this.#children[regexpStr];
|
|
6746
|
+
if (!node) {
|
|
6747
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
|
|
6748
|
+
if (pathErrorCheckOnly) return;
|
|
6749
|
+
node = this.#children[regexpStr] = new _Node();
|
|
6750
|
+
if (name !== "") node.#varIndex = context.varIndex++;
|
|
6751
|
+
}
|
|
6752
|
+
if (!pathErrorCheckOnly && name !== "") paramMap.push([name, node.#varIndex]);
|
|
6753
|
+
} else {
|
|
6754
|
+
node = this.#children[token];
|
|
6755
|
+
if (!node) {
|
|
6756
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
|
|
6757
|
+
if (pathErrorCheckOnly) return;
|
|
6758
|
+
node = this.#children[token] = new _Node();
|
|
6759
|
+
}
|
|
6760
|
+
}
|
|
6761
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
6762
|
+
}
|
|
6763
|
+
buildRegExpStr() {
|
|
6764
|
+
const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
|
|
6765
|
+
const c = this.#children[k];
|
|
6766
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
6767
|
+
});
|
|
6768
|
+
if (typeof this.#index === "number") strList.unshift(`#${this.#index}`);
|
|
6769
|
+
if (strList.length === 0) return "";
|
|
6770
|
+
if (strList.length === 1) return strList[0];
|
|
6771
|
+
return "(?:" + strList.join("|") + ")";
|
|
6772
|
+
}
|
|
6773
|
+
};
|
|
6774
|
+
//#endregion
|
|
6775
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
6776
|
+
var Trie = class {
|
|
6777
|
+
#context = { varIndex: 0 };
|
|
6778
|
+
#root = new Node$1();
|
|
6779
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
6780
|
+
const paramAssoc = [];
|
|
6781
|
+
const groups = [];
|
|
6782
|
+
for (let i = 0;;) {
|
|
6783
|
+
let replaced = false;
|
|
6784
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
6785
|
+
const mark = `@\\${i}`;
|
|
6786
|
+
groups[i] = [mark, m];
|
|
6787
|
+
i++;
|
|
6788
|
+
replaced = true;
|
|
6789
|
+
return mark;
|
|
6790
|
+
});
|
|
6791
|
+
if (!replaced) break;
|
|
6792
|
+
}
|
|
6793
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
6794
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
6795
|
+
const [mark] = groups[i];
|
|
6796
|
+
for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
|
|
6797
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
6798
|
+
break;
|
|
6799
|
+
}
|
|
6800
|
+
}
|
|
6801
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
6802
|
+
return paramAssoc;
|
|
6803
|
+
}
|
|
6804
|
+
buildRegExp() {
|
|
6805
|
+
let regexp = this.#root.buildRegExpStr();
|
|
6806
|
+
if (regexp === "") return [
|
|
6807
|
+
/^$/,
|
|
6808
|
+
[],
|
|
6809
|
+
[]
|
|
6810
|
+
];
|
|
6811
|
+
let captureIndex = 0;
|
|
6812
|
+
const indexReplacementMap = [];
|
|
6813
|
+
const paramReplacementMap = [];
|
|
6814
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
6815
|
+
if (handlerIndex !== void 0) {
|
|
6816
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
6817
|
+
return "$()";
|
|
6818
|
+
}
|
|
6819
|
+
if (paramIndex !== void 0) {
|
|
6820
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
6821
|
+
return "";
|
|
6822
|
+
}
|
|
6823
|
+
return "";
|
|
6824
|
+
});
|
|
6825
|
+
return [
|
|
6826
|
+
new RegExp(`^${regexp}`),
|
|
6827
|
+
indexReplacementMap,
|
|
6828
|
+
paramReplacementMap
|
|
6829
|
+
];
|
|
6830
|
+
}
|
|
6831
|
+
};
|
|
6832
|
+
//#endregion
|
|
6833
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
6834
|
+
var nullMatcher = [
|
|
6835
|
+
/^$/,
|
|
6836
|
+
[],
|
|
6837
|
+
/* @__PURE__ */ Object.create(null)
|
|
6838
|
+
];
|
|
6839
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
6840
|
+
function buildWildcardRegExp(path) {
|
|
6841
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
6842
|
+
}
|
|
6843
|
+
function clearWildcardRegExpCache() {
|
|
6844
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
6845
|
+
}
|
|
6846
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
6847
|
+
const trie = new Trie();
|
|
6848
|
+
const handlerData = [];
|
|
6849
|
+
if (routes.length === 0) return nullMatcher;
|
|
6850
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
6851
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
6852
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
6853
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
6854
|
+
if (pathErrorCheckOnly) staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
6855
|
+
else j++;
|
|
6856
|
+
let paramAssoc;
|
|
6857
|
+
try {
|
|
6858
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
6859
|
+
} catch (e) {
|
|
6860
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
6861
|
+
}
|
|
6862
|
+
if (pathErrorCheckOnly) continue;
|
|
6863
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
6864
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
6865
|
+
paramCount -= 1;
|
|
6866
|
+
for (; paramCount >= 0; paramCount--) {
|
|
6867
|
+
const [key, value] = paramAssoc[paramCount];
|
|
6868
|
+
paramIndexMap[key] = value;
|
|
6869
|
+
}
|
|
6870
|
+
return [h, paramIndexMap];
|
|
6871
|
+
});
|
|
6872
|
+
}
|
|
6873
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
6874
|
+
for (let i = 0, len = handlerData.length; i < len; i++) for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
6875
|
+
const map = handlerData[i][j]?.[1];
|
|
6876
|
+
if (!map) continue;
|
|
6877
|
+
const keys = Object.keys(map);
|
|
6878
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
6879
|
+
}
|
|
6880
|
+
const handlerMap = [];
|
|
6881
|
+
for (const i in indexReplacementMap) handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
6882
|
+
return [
|
|
6883
|
+
regexp,
|
|
6884
|
+
handlerMap,
|
|
6885
|
+
staticMap
|
|
6886
|
+
];
|
|
6887
|
+
}
|
|
6888
|
+
function findMiddleware(middleware, path) {
|
|
6889
|
+
if (!middleware) return;
|
|
6890
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
|
|
6891
|
+
}
|
|
6892
|
+
var RegExpRouter = class {
|
|
6893
|
+
name = "RegExpRouter";
|
|
6894
|
+
#middleware;
|
|
6895
|
+
#routes;
|
|
6896
|
+
constructor() {
|
|
6897
|
+
this.#middleware = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
|
|
6898
|
+
this.#routes = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
|
|
6899
|
+
}
|
|
6900
|
+
add(method, path, handler) {
|
|
6901
|
+
const middleware = this.#middleware;
|
|
6902
|
+
const routes = this.#routes;
|
|
6903
|
+
if (!middleware || !routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
6904
|
+
if (!middleware[method]) [middleware, routes].forEach((handlerMap) => {
|
|
6905
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
6906
|
+
Object.keys(handlerMap["ALL"]).forEach((p) => {
|
|
6907
|
+
handlerMap[method][p] = [...handlerMap["ALL"][p]];
|
|
6908
|
+
});
|
|
6909
|
+
});
|
|
6910
|
+
if (path === "/*") path = "*";
|
|
6911
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
6912
|
+
if (/\*$/.test(path)) {
|
|
6913
|
+
const re = buildWildcardRegExp(path);
|
|
6914
|
+
if (method === "ALL") Object.keys(middleware).forEach((m) => {
|
|
6915
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
|
|
6916
|
+
});
|
|
6917
|
+
else middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware["ALL"], path) || [];
|
|
6918
|
+
Object.keys(middleware).forEach((m) => {
|
|
6919
|
+
if (method === "ALL" || method === m) Object.keys(middleware[m]).forEach((p) => {
|
|
6920
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
6921
|
+
});
|
|
6922
|
+
});
|
|
6923
|
+
Object.keys(routes).forEach((m) => {
|
|
6924
|
+
if (method === "ALL" || method === m) Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
6925
|
+
});
|
|
6926
|
+
return;
|
|
6927
|
+
}
|
|
6928
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
6929
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
6930
|
+
const path2 = paths[i];
|
|
6931
|
+
Object.keys(routes).forEach((m) => {
|
|
6932
|
+
if (method === "ALL" || method === m) {
|
|
6933
|
+
routes[m][path2] ||= [...findMiddleware(middleware[m], path2) || findMiddleware(middleware["ALL"], path2) || []];
|
|
6934
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
6935
|
+
}
|
|
6936
|
+
});
|
|
6937
|
+
}
|
|
6938
|
+
}
|
|
6939
|
+
match = match;
|
|
6940
|
+
buildAllMatchers() {
|
|
6941
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
6942
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
6943
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
6944
|
+
});
|
|
6945
|
+
this.#middleware = this.#routes = void 0;
|
|
6946
|
+
clearWildcardRegExpCache();
|
|
6947
|
+
return matchers;
|
|
6948
|
+
}
|
|
6949
|
+
#buildMatcher(method) {
|
|
6950
|
+
const routes = [];
|
|
6951
|
+
let hasOwnRoute = method === "ALL";
|
|
6952
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
6953
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
6954
|
+
if (ownRoute.length !== 0) {
|
|
6955
|
+
hasOwnRoute ||= true;
|
|
6956
|
+
routes.push(...ownRoute);
|
|
6957
|
+
} else if (method !== "ALL") routes.push(...Object.keys(r["ALL"]).map((path) => [path, r["ALL"][path]]));
|
|
6958
|
+
});
|
|
6959
|
+
if (!hasOwnRoute) return null;
|
|
6960
|
+
else return buildMatcherFromPreprocessedRoutes(routes);
|
|
6961
|
+
}
|
|
6962
|
+
};
|
|
6963
|
+
//#endregion
|
|
6964
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/smart-router/router.js
|
|
6965
|
+
var SmartRouter = class {
|
|
6966
|
+
name = "SmartRouter";
|
|
6967
|
+
#routers = [];
|
|
6968
|
+
#routes = [];
|
|
6969
|
+
constructor(init) {
|
|
6970
|
+
this.#routers = init.routers;
|
|
6971
|
+
}
|
|
6972
|
+
add(method, path, handler) {
|
|
6973
|
+
if (!this.#routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
6974
|
+
this.#routes.push([
|
|
6975
|
+
method,
|
|
6976
|
+
path,
|
|
6977
|
+
handler
|
|
6978
|
+
]);
|
|
6979
|
+
}
|
|
6980
|
+
match(method, path) {
|
|
6981
|
+
if (!this.#routes) throw new Error("Fatal error");
|
|
6982
|
+
const routers = this.#routers;
|
|
6983
|
+
const routes = this.#routes;
|
|
6984
|
+
const len = routers.length;
|
|
6985
|
+
let i = 0;
|
|
6986
|
+
let res;
|
|
6987
|
+
for (; i < len; i++) {
|
|
6988
|
+
const router = routers[i];
|
|
6989
|
+
try {
|
|
6990
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) router.add(...routes[i2]);
|
|
6991
|
+
res = router.match(method, path);
|
|
6992
|
+
} catch (e) {
|
|
6993
|
+
if (e instanceof UnsupportedPathError) continue;
|
|
6994
|
+
throw e;
|
|
6995
|
+
}
|
|
6996
|
+
this.match = router.match.bind(router);
|
|
6997
|
+
this.#routers = [router];
|
|
6998
|
+
this.#routes = void 0;
|
|
6999
|
+
break;
|
|
7000
|
+
}
|
|
7001
|
+
if (i === len) throw new Error("Fatal error");
|
|
7002
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
7003
|
+
return res;
|
|
7004
|
+
}
|
|
7005
|
+
get activeRouter() {
|
|
7006
|
+
if (this.#routes || this.#routers.length !== 1) throw new Error("No active router has been determined yet.");
|
|
7007
|
+
return this.#routers[0];
|
|
7008
|
+
}
|
|
7009
|
+
};
|
|
7010
|
+
//#endregion
|
|
7011
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/trie-router/node.js
|
|
7012
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
7013
|
+
var hasChildren = (children) => {
|
|
7014
|
+
for (const _ in children) return true;
|
|
7015
|
+
return false;
|
|
7016
|
+
};
|
|
7017
|
+
var Node = class _Node {
|
|
7018
|
+
#methods;
|
|
7019
|
+
#children;
|
|
7020
|
+
#patterns;
|
|
7021
|
+
#order = 0;
|
|
7022
|
+
#params = emptyParams;
|
|
7023
|
+
constructor(method, handler, children) {
|
|
7024
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
7025
|
+
this.#methods = [];
|
|
7026
|
+
if (method && handler) {
|
|
7027
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
7028
|
+
m[method] = {
|
|
7029
|
+
handler,
|
|
7030
|
+
possibleKeys: [],
|
|
7031
|
+
score: 0
|
|
7032
|
+
};
|
|
7033
|
+
this.#methods = [m];
|
|
7034
|
+
}
|
|
7035
|
+
this.#patterns = [];
|
|
7036
|
+
}
|
|
7037
|
+
insert(method, path, handler) {
|
|
7038
|
+
this.#order = ++this.#order;
|
|
7039
|
+
let curNode = this;
|
|
7040
|
+
const parts = splitRoutingPath(path);
|
|
7041
|
+
const possibleKeys = [];
|
|
7042
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
7043
|
+
const p = parts[i];
|
|
7044
|
+
const nextP = parts[i + 1];
|
|
7045
|
+
const pattern = getPattern(p, nextP);
|
|
7046
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
7047
|
+
if (key in curNode.#children) {
|
|
7048
|
+
curNode = curNode.#children[key];
|
|
7049
|
+
if (pattern) possibleKeys.push(pattern[1]);
|
|
7050
|
+
continue;
|
|
7051
|
+
}
|
|
7052
|
+
curNode.#children[key] = new _Node();
|
|
7053
|
+
if (pattern) {
|
|
7054
|
+
curNode.#patterns.push(pattern);
|
|
7055
|
+
possibleKeys.push(pattern[1]);
|
|
7056
|
+
}
|
|
7057
|
+
curNode = curNode.#children[key];
|
|
7058
|
+
}
|
|
7059
|
+
curNode.#methods.push({ [method]: {
|
|
7060
|
+
handler,
|
|
7061
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
7062
|
+
score: this.#order
|
|
7063
|
+
} });
|
|
7064
|
+
return curNode;
|
|
7065
|
+
}
|
|
7066
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
7067
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
7068
|
+
const m = node.#methods[i];
|
|
7069
|
+
const handlerSet = m[method] || m["ALL"];
|
|
7070
|
+
const processedSet = {};
|
|
7071
|
+
if (handlerSet !== void 0) {
|
|
7072
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
7073
|
+
handlerSets.push(handlerSet);
|
|
7074
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
7075
|
+
const key = handlerSet.possibleKeys[i2];
|
|
7076
|
+
const processed = processedSet[handlerSet.score];
|
|
7077
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
7078
|
+
processedSet[handlerSet.score] = true;
|
|
7079
|
+
}
|
|
7080
|
+
}
|
|
7081
|
+
}
|
|
7082
|
+
}
|
|
7083
|
+
search(method, path) {
|
|
7084
|
+
const handlerSets = [];
|
|
7085
|
+
this.#params = emptyParams;
|
|
7086
|
+
let curNodes = [this];
|
|
7087
|
+
const parts = splitPath(path);
|
|
7088
|
+
const curNodesQueue = [];
|
|
7089
|
+
const len = parts.length;
|
|
7090
|
+
let partOffsets = null;
|
|
7091
|
+
for (let i = 0; i < len; i++) {
|
|
7092
|
+
const part = parts[i];
|
|
7093
|
+
const isLast = i === len - 1;
|
|
7094
|
+
const tempNodes = [];
|
|
7095
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
7096
|
+
const node = curNodes[j];
|
|
7097
|
+
const nextNode = node.#children[part];
|
|
7098
|
+
if (nextNode) {
|
|
7099
|
+
nextNode.#params = node.#params;
|
|
7100
|
+
if (isLast) {
|
|
7101
|
+
if (nextNode.#children["*"]) this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
7102
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
7103
|
+
} else tempNodes.push(nextNode);
|
|
7104
|
+
}
|
|
7105
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
7106
|
+
const pattern = node.#patterns[k];
|
|
7107
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
7108
|
+
if (pattern === "*") {
|
|
7109
|
+
const astNode = node.#children["*"];
|
|
7110
|
+
if (astNode) {
|
|
7111
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
7112
|
+
astNode.#params = params;
|
|
7113
|
+
tempNodes.push(astNode);
|
|
7114
|
+
}
|
|
7115
|
+
continue;
|
|
7116
|
+
}
|
|
7117
|
+
const [key, name, matcher] = pattern;
|
|
7118
|
+
if (!part && !(matcher instanceof RegExp)) continue;
|
|
7119
|
+
const child = node.#children[key];
|
|
7120
|
+
if (matcher instanceof RegExp) {
|
|
7121
|
+
if (partOffsets === null) {
|
|
7122
|
+
partOffsets = new Array(len);
|
|
7123
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
7124
|
+
for (let p = 0; p < len; p++) {
|
|
7125
|
+
partOffsets[p] = offset;
|
|
7126
|
+
offset += parts[p].length + 1;
|
|
7127
|
+
}
|
|
7128
|
+
}
|
|
7129
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
7130
|
+
const m = matcher.exec(restPathString);
|
|
7131
|
+
if (m) {
|
|
7132
|
+
params[name] = m[0];
|
|
7133
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
7134
|
+
if (hasChildren(child.#children)) {
|
|
7135
|
+
child.#params = params;
|
|
7136
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
7137
|
+
(curNodesQueue[componentCount] ||= []).push(child);
|
|
7138
|
+
}
|
|
7139
|
+
continue;
|
|
7140
|
+
}
|
|
7141
|
+
}
|
|
7142
|
+
if (matcher === true || matcher.test(part)) {
|
|
7143
|
+
params[name] = part;
|
|
7144
|
+
if (isLast) {
|
|
7145
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
7146
|
+
if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
|
|
7147
|
+
} else {
|
|
7148
|
+
child.#params = params;
|
|
7149
|
+
tempNodes.push(child);
|
|
7150
|
+
}
|
|
7151
|
+
}
|
|
7152
|
+
}
|
|
7153
|
+
}
|
|
7154
|
+
const shifted = curNodesQueue.shift();
|
|
7155
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
7156
|
+
}
|
|
7157
|
+
if (handlerSets.length > 1) handlerSets.sort((a, b) => {
|
|
7158
|
+
return a.score - b.score;
|
|
7159
|
+
});
|
|
7160
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
7161
|
+
}
|
|
7162
|
+
};
|
|
7163
|
+
//#endregion
|
|
7164
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/trie-router/router.js
|
|
7165
|
+
var TrieRouter = class {
|
|
7166
|
+
name = "TrieRouter";
|
|
7167
|
+
#node;
|
|
7168
|
+
constructor() {
|
|
7169
|
+
this.#node = new Node();
|
|
7170
|
+
}
|
|
7171
|
+
add(method, path, handler) {
|
|
7172
|
+
const results = checkOptionalParameter(path);
|
|
7173
|
+
if (results) {
|
|
7174
|
+
for (let i = 0, len = results.length; i < len; i++) this.#node.insert(method, results[i], handler);
|
|
7175
|
+
return;
|
|
7176
|
+
}
|
|
7177
|
+
this.#node.insert(method, path, handler);
|
|
7178
|
+
}
|
|
7179
|
+
match(method, path) {
|
|
7180
|
+
return this.#node.search(method, path);
|
|
7181
|
+
}
|
|
7182
|
+
};
|
|
7183
|
+
//#endregion
|
|
7184
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/hono.js
|
|
7185
|
+
var Hono = class extends Hono$1 {
|
|
7186
|
+
/**
|
|
7187
|
+
* Creates an instance of the Hono class.
|
|
7188
|
+
*
|
|
7189
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
7190
|
+
*/
|
|
7191
|
+
constructor(options = {}) {
|
|
7192
|
+
super(options);
|
|
7193
|
+
this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
|
|
7194
|
+
}
|
|
7195
|
+
};
|
|
7196
|
+
object({
|
|
7197
|
+
client_id: string(),
|
|
7198
|
+
redirect_uri: string().optional().refine((value) => value === void 0 || URL.canParse(value), { message: "redirect_uri must be a valid URL" })
|
|
7199
|
+
});
|
|
7200
|
+
object({
|
|
7201
|
+
response_type: literal("code"),
|
|
7202
|
+
code_challenge: string(),
|
|
7203
|
+
code_challenge_method: literal("S256"),
|
|
7204
|
+
scope: string().optional(),
|
|
7205
|
+
state: string().optional(),
|
|
7206
|
+
resource: url().optional()
|
|
7207
|
+
});
|
|
7208
|
+
object({ grant_type: string() });
|
|
7209
|
+
object({
|
|
7210
|
+
code: string(),
|
|
7211
|
+
code_verifier: string(),
|
|
7212
|
+
redirect_uri: string().optional(),
|
|
7213
|
+
resource: url().optional()
|
|
7214
|
+
});
|
|
7215
|
+
object({
|
|
7216
|
+
refresh_token: string(),
|
|
7217
|
+
scope: string().optional(),
|
|
7218
|
+
resource: url().optional()
|
|
7219
|
+
});
|
|
7220
|
+
object({
|
|
7221
|
+
client_id: string(),
|
|
7222
|
+
client_secret: string().optional()
|
|
7223
|
+
});
|
|
7224
|
+
//#endregion
|
|
7225
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/stream.js
|
|
7226
|
+
var StreamingApi = class {
|
|
7227
|
+
writer;
|
|
7228
|
+
encoder;
|
|
7229
|
+
writable;
|
|
7230
|
+
abortSubscribers = [];
|
|
7231
|
+
responseReadable;
|
|
7232
|
+
/**
|
|
7233
|
+
* Whether the stream has been aborted.
|
|
7234
|
+
*/
|
|
7235
|
+
aborted = false;
|
|
7236
|
+
/**
|
|
7237
|
+
* Whether the stream has been closed normally.
|
|
7238
|
+
*/
|
|
7239
|
+
closed = false;
|
|
7240
|
+
constructor(writable, _readable) {
|
|
7241
|
+
this.writable = writable;
|
|
7242
|
+
this.writer = writable.getWriter();
|
|
7243
|
+
this.encoder = new TextEncoder();
|
|
7244
|
+
const reader = _readable.getReader();
|
|
7245
|
+
this.abortSubscribers.push(async () => {
|
|
7246
|
+
await reader.cancel();
|
|
7247
|
+
});
|
|
7248
|
+
this.responseReadable = new ReadableStream({
|
|
7249
|
+
async pull(controller) {
|
|
7250
|
+
const { done, value } = await reader.read();
|
|
7251
|
+
done ? controller.close() : controller.enqueue(value);
|
|
7252
|
+
},
|
|
7253
|
+
cancel: () => {
|
|
7254
|
+
if (!this.closed) this.abort();
|
|
7255
|
+
}
|
|
7256
|
+
});
|
|
7257
|
+
}
|
|
7258
|
+
async write(input) {
|
|
7259
|
+
try {
|
|
7260
|
+
if (typeof input === "string") input = this.encoder.encode(input);
|
|
7261
|
+
await this.writer.write(input);
|
|
7262
|
+
} catch {}
|
|
7263
|
+
return this;
|
|
7264
|
+
}
|
|
7265
|
+
async writeln(input) {
|
|
7266
|
+
await this.write(input + "\n");
|
|
7267
|
+
return this;
|
|
7268
|
+
}
|
|
7269
|
+
sleep(ms) {
|
|
7270
|
+
return new Promise((res) => setTimeout(res, ms));
|
|
7271
|
+
}
|
|
7272
|
+
async close() {
|
|
7273
|
+
this.closed = true;
|
|
7274
|
+
try {
|
|
7275
|
+
await this.writer.close();
|
|
7276
|
+
} catch {}
|
|
7277
|
+
}
|
|
7278
|
+
async pipe(body) {
|
|
7279
|
+
this.writer.releaseLock();
|
|
7280
|
+
await body.pipeTo(this.writable, { preventClose: true });
|
|
7281
|
+
this.writer = this.writable.getWriter();
|
|
7282
|
+
}
|
|
7283
|
+
onAbort(listener) {
|
|
7284
|
+
this.abortSubscribers.push(listener);
|
|
7285
|
+
}
|
|
7286
|
+
/**
|
|
7287
|
+
* Abort the stream.
|
|
7288
|
+
* You can call this method when stream is aborted by external event.
|
|
7289
|
+
*/
|
|
7290
|
+
abort() {
|
|
7291
|
+
if (!this.aborted) {
|
|
7292
|
+
this.aborted = true;
|
|
7293
|
+
this.abortSubscribers.forEach((subscriber) => subscriber());
|
|
7294
|
+
}
|
|
7295
|
+
}
|
|
7296
|
+
};
|
|
7297
|
+
//#endregion
|
|
7298
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/helper/streaming/sse.js
|
|
7299
|
+
var SSEStreamingApi = class extends StreamingApi {
|
|
7300
|
+
constructor(writable, readable) {
|
|
7301
|
+
super(writable, readable);
|
|
7302
|
+
}
|
|
7303
|
+
async writeSSE(message) {
|
|
7304
|
+
const dataLines = (await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {})).split(/\r\n|\r|\n/).map((line) => {
|
|
7305
|
+
return `data: ${line}`;
|
|
7306
|
+
}).join("\n");
|
|
7307
|
+
for (const key of [
|
|
7308
|
+
"event",
|
|
7309
|
+
"id",
|
|
7310
|
+
"retry"
|
|
7311
|
+
]) if (message[key] && /[\r\n]/.test(message[key])) throw new Error(`${key} must not contain "\\r" or "\\n"`);
|
|
7312
|
+
const sseData = [
|
|
7313
|
+
message.event && `event: ${message.event}`,
|
|
7314
|
+
dataLines,
|
|
7315
|
+
message.id && `id: ${message.id}`,
|
|
7316
|
+
message.retry && `retry: ${message.retry}`
|
|
7317
|
+
].filter(Boolean).join("\n") + "\n\n";
|
|
7318
|
+
await this.write(sseData);
|
|
7319
|
+
}
|
|
7320
|
+
};
|
|
7321
|
+
//#endregion
|
|
7322
|
+
//#region ../../node_modules/.pnpm/@hono+mcp@0.3.0_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__hono-rate-limiter@0.5.3_hono@4.12.19__hono@4.12.19_zod@4.4.3/node_modules/@hono/mcp/dist/index.js
|
|
7323
|
+
let isOldBunVersion = () => {
|
|
7324
|
+
const version = typeof Bun !== "undefined" ? Bun.version : void 0;
|
|
7325
|
+
if (version === void 0) return false;
|
|
7326
|
+
const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0.");
|
|
7327
|
+
isOldBunVersion = () => result;
|
|
7328
|
+
return result;
|
|
7329
|
+
};
|
|
7330
|
+
const run = async (stream, cb, onError) => {
|
|
7331
|
+
try {
|
|
7332
|
+
await cb(stream);
|
|
7333
|
+
} catch (e) {
|
|
7334
|
+
if (e instanceof Error && onError) {
|
|
7335
|
+
await onError(e, stream);
|
|
7336
|
+
await stream.writeSSE({
|
|
7337
|
+
event: "error",
|
|
7338
|
+
data: e.message
|
|
7339
|
+
});
|
|
7340
|
+
} else console.error(e);
|
|
7341
|
+
}
|
|
7342
|
+
};
|
|
7343
|
+
const contextStash = /* @__PURE__ */ new WeakMap();
|
|
7344
|
+
const streamSSE = (c, cb, onError) => {
|
|
7345
|
+
const { readable, writable } = new TransformStream();
|
|
7346
|
+
const stream = new SSEStreamingApi(writable, readable);
|
|
7347
|
+
if (isOldBunVersion()) c.req.raw.signal.addEventListener("abort", () => {
|
|
7348
|
+
if (!stream.closed) stream.abort();
|
|
7349
|
+
});
|
|
7350
|
+
contextStash.set(stream.responseReadable, c);
|
|
7351
|
+
c.header("Transfer-Encoding", "chunked");
|
|
7352
|
+
c.header("Content-Type", "text/event-stream");
|
|
7353
|
+
c.header("Cache-Control", "no-cache");
|
|
7354
|
+
c.header("Connection", "keep-alive");
|
|
7355
|
+
run(stream, cb, onError);
|
|
7356
|
+
return c.newResponse(stream.responseReadable);
|
|
7357
|
+
};
|
|
7358
|
+
var StreamableHTTPTransport = class {
|
|
7359
|
+
#started = false;
|
|
7360
|
+
#initialized = false;
|
|
7361
|
+
#onSessionInitialized;
|
|
7362
|
+
#onSessionClosed;
|
|
7363
|
+
#sessionIdGenerator;
|
|
7364
|
+
#eventStore;
|
|
7365
|
+
#enableJsonResponse = false;
|
|
7366
|
+
#standaloneSseStreamId = "_GET_stream";
|
|
7367
|
+
#streamMapping = /* @__PURE__ */ new Map();
|
|
7368
|
+
#requestToStreamMapping = /* @__PURE__ */ new Map();
|
|
7369
|
+
#requestResponseMap = /* @__PURE__ */ new Map();
|
|
7370
|
+
#allowedHosts;
|
|
7371
|
+
#allowedOrigins;
|
|
7372
|
+
#enableDnsRebindingProtection;
|
|
7373
|
+
#strictAcceptHeader;
|
|
7374
|
+
sessionId;
|
|
7375
|
+
onclose;
|
|
7376
|
+
onerror;
|
|
7377
|
+
onmessage;
|
|
7378
|
+
constructor(options) {
|
|
7379
|
+
this.#sessionIdGenerator = options?.sessionIdGenerator;
|
|
7380
|
+
this.#enableJsonResponse = options?.enableJsonResponse ?? false;
|
|
7381
|
+
this.#eventStore = options?.eventStore;
|
|
7382
|
+
this.#onSessionInitialized = options?.onsessioninitialized;
|
|
7383
|
+
this.#onSessionClosed = options?.onsessionclosed;
|
|
7384
|
+
this.#allowedHosts = options?.allowedHosts;
|
|
7385
|
+
this.#allowedOrigins = options?.allowedOrigins;
|
|
7386
|
+
this.#enableDnsRebindingProtection = options?.enableDnsRebindingProtection ?? false;
|
|
7387
|
+
this.#strictAcceptHeader = options?.strictAcceptHeader ?? false;
|
|
7388
|
+
}
|
|
7389
|
+
/**
|
|
7390
|
+
* Starts the transport. This is required by the Transport interface but is a no-op
|
|
7391
|
+
* for the Streamable HTTP transport as connections are managed per-request.
|
|
7392
|
+
*/
|
|
7393
|
+
async start() {
|
|
7394
|
+
if (this.#started) throw new Error("Transport already started");
|
|
7395
|
+
this.#started = true;
|
|
7396
|
+
}
|
|
7397
|
+
/**
|
|
7398
|
+
* Validates request headers for DNS rebinding protection.
|
|
7399
|
+
* @returns Error message if validation fails, undefined if validation passes.
|
|
7400
|
+
*/
|
|
7401
|
+
#validateRequestHeaders(ctx) {
|
|
7402
|
+
if (!this.#enableDnsRebindingProtection) return;
|
|
7403
|
+
if (this.#allowedHosts && this.#allowedHosts.length > 0) {
|
|
7404
|
+
const hostHeader = ctx.req.header("Host");
|
|
7405
|
+
if (!hostHeader || !this.#allowedHosts.includes(hostHeader)) return `Invalid Host header: ${hostHeader}`;
|
|
7406
|
+
}
|
|
7407
|
+
if (this.#allowedOrigins && this.#allowedOrigins.length > 0) {
|
|
7408
|
+
const originHeader = ctx.req.header("Origin");
|
|
7409
|
+
if (!originHeader || !this.#allowedOrigins.includes(originHeader)) return `Invalid Origin header: ${originHeader}`;
|
|
7410
|
+
}
|
|
7411
|
+
}
|
|
7412
|
+
/**
|
|
7413
|
+
* Handles an incoming HTTP request, whether GET or POST
|
|
7414
|
+
*/
|
|
7415
|
+
async handleRequest(ctx, parsedBody) {
|
|
7416
|
+
const validationError = this.#validateRequestHeaders(ctx);
|
|
7417
|
+
if (validationError) throw new HTTPException(403, { res: Response.json({
|
|
7418
|
+
jsonrpc: "2.0",
|
|
7419
|
+
error: {
|
|
7420
|
+
code: -32e3,
|
|
7421
|
+
message: validationError
|
|
7422
|
+
},
|
|
7423
|
+
id: null
|
|
7424
|
+
}) });
|
|
7425
|
+
switch (ctx.req.method) {
|
|
7426
|
+
case "GET": return this.handleGetRequest(ctx);
|
|
7427
|
+
case "POST": return this.handlePostRequest(ctx, parsedBody);
|
|
7428
|
+
case "DELETE": return this.handleDeleteRequest(ctx);
|
|
7429
|
+
default: return this.handleUnsupportedRequest(ctx);
|
|
7430
|
+
}
|
|
7431
|
+
}
|
|
7432
|
+
/**
|
|
7433
|
+
* Handles GET requests for SSE stream
|
|
7434
|
+
*/
|
|
7435
|
+
async handleGetRequest(ctx) {
|
|
7436
|
+
try {
|
|
7437
|
+
const getAcceptHeader = ctx.req.header("Accept") ?? "*/*";
|
|
7438
|
+
if (!getAcceptHeader.includes("text/event-stream") && !getAcceptHeader.includes("*/*")) throw new HTTPException(406, { res: Response.json({
|
|
7439
|
+
jsonrpc: "2.0",
|
|
7440
|
+
error: {
|
|
7441
|
+
code: -32e3,
|
|
7442
|
+
message: "Not Acceptable: Client must accept text/event-stream"
|
|
7443
|
+
},
|
|
7444
|
+
id: null
|
|
7445
|
+
}) });
|
|
7446
|
+
this.#validateSession(ctx);
|
|
7447
|
+
this.#validateProtocolVersion(ctx);
|
|
7448
|
+
if (this.sessionId !== void 0) ctx.header("mcp-session-id", this.sessionId);
|
|
7449
|
+
let streamId = this.#standaloneSseStreamId;
|
|
7450
|
+
if (this.#eventStore) {
|
|
7451
|
+
const lastEventId = ctx.req.header("last-event-id");
|
|
7452
|
+
if (lastEventId) streamId = (stream) => this.#eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
|
|
7453
|
+
try {
|
|
7454
|
+
await stream.writeSSE({
|
|
7455
|
+
id: eventId,
|
|
7456
|
+
event: "message",
|
|
7457
|
+
data: JSON.stringify(message)
|
|
7458
|
+
});
|
|
7459
|
+
} catch {
|
|
7460
|
+
this.onerror?.(/* @__PURE__ */ new Error("Failed replay events"));
|
|
7461
|
+
throw new HTTPException(500, { message: "Failed replay events" });
|
|
7462
|
+
}
|
|
7463
|
+
} });
|
|
7464
|
+
}
|
|
7465
|
+
if (typeof streamId === "string" && this.#streamMapping.get(streamId) !== void 0) throw new HTTPException(409, { res: Response.json({
|
|
7466
|
+
jsonrpc: "2.0",
|
|
7467
|
+
error: {
|
|
7468
|
+
code: -32e3,
|
|
7469
|
+
message: "Conflict: Only one SSE stream is allowed per session"
|
|
7470
|
+
},
|
|
7471
|
+
id: null
|
|
7472
|
+
}) });
|
|
7473
|
+
return streamSSE(ctx, async (stream) => {
|
|
7474
|
+
const resolvedStreamId = typeof streamId === "string" ? streamId : await streamId(stream);
|
|
7475
|
+
const keepAlive = setInterval(() => {
|
|
7476
|
+
if (!stream.closed) stream.writeSSE({
|
|
7477
|
+
data: "",
|
|
7478
|
+
event: "ping"
|
|
7479
|
+
}).catch(() => {
|
|
7480
|
+
stream.abort();
|
|
7481
|
+
});
|
|
7482
|
+
}, 3e4);
|
|
7483
|
+
if (typeof keepAlive === "object" && "unref" in keepAlive) keepAlive.unref();
|
|
7484
|
+
this.#streamMapping.set(resolvedStreamId, {
|
|
7485
|
+
ctx: { header: ctx.header },
|
|
7486
|
+
stream,
|
|
7487
|
+
cleanup: () => {
|
|
7488
|
+
clearInterval(keepAlive);
|
|
7489
|
+
this.#streamMapping.delete(resolvedStreamId);
|
|
7490
|
+
}
|
|
7491
|
+
});
|
|
7492
|
+
stream.onAbort(() => {
|
|
7493
|
+
this.#streamMapping.get(resolvedStreamId)?.cleanup();
|
|
7494
|
+
});
|
|
7495
|
+
});
|
|
7496
|
+
} catch (error) {
|
|
7497
|
+
if (error instanceof HTTPException) throw error;
|
|
7498
|
+
this.onerror?.(error);
|
|
7499
|
+
throw new HTTPException(400, { res: Response.json({
|
|
7500
|
+
jsonrpc: "2.0",
|
|
7501
|
+
error: {
|
|
7502
|
+
code: ErrorCode.ParseError,
|
|
7503
|
+
message: "Parse error",
|
|
7504
|
+
data: String(error)
|
|
7505
|
+
},
|
|
7506
|
+
id: null
|
|
7507
|
+
}) });
|
|
7508
|
+
}
|
|
7509
|
+
}
|
|
7510
|
+
/**
|
|
7511
|
+
* Handles POST requests containing JSON-RPC messages
|
|
7512
|
+
*/
|
|
7513
|
+
async handlePostRequest(ctx, parsedBody) {
|
|
7514
|
+
try {
|
|
7515
|
+
const acceptHeader = ctx.req.header("Accept") ?? "*/*";
|
|
7516
|
+
if (!(this.#strictAcceptHeader ? acceptHeader.includes("application/json") && acceptHeader.includes("text/event-stream") : acceptHeader.includes("application/json") || acceptHeader.includes("text/event-stream") || acceptHeader.includes("*/*"))) throw new HTTPException(406, { res: Response.json({
|
|
7517
|
+
jsonrpc: "2.0",
|
|
7518
|
+
error: {
|
|
7519
|
+
code: ErrorCode.ConnectionClosed,
|
|
7520
|
+
message: this.#strictAcceptHeader ? "Not Acceptable: Client must accept both application/json and text/event-stream" : "Not Acceptable: Client must accept application/json or text/event-stream"
|
|
7521
|
+
},
|
|
7522
|
+
id: null
|
|
7523
|
+
}) });
|
|
7524
|
+
if (!ctx.req.header("Content-Type")?.includes("application/json")) throw new HTTPException(415, { res: Response.json({
|
|
7525
|
+
jsonrpc: "2.0",
|
|
7526
|
+
error: {
|
|
7527
|
+
code: ErrorCode.ConnectionClosed,
|
|
7528
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
7529
|
+
},
|
|
7530
|
+
id: null
|
|
7531
|
+
}) });
|
|
7532
|
+
const authInfo = ctx.get("auth");
|
|
7533
|
+
const requestInfo = { headers: ctx.req.header() };
|
|
7534
|
+
let rawMessage = parsedBody;
|
|
7535
|
+
if (rawMessage === void 0) rawMessage = await ctx.req.json();
|
|
7536
|
+
let messages;
|
|
7537
|
+
if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
7538
|
+
else messages = [JSONRPCMessageSchema.parse(rawMessage)];
|
|
7539
|
+
const isInitializationRequest = messages.some(isInitializeRequest);
|
|
7540
|
+
if (isInitializationRequest) {
|
|
7541
|
+
if (this.#initialized && this.sessionId !== void 0) throw new HTTPException(400, { res: Response.json({
|
|
7542
|
+
jsonrpc: "2.0",
|
|
7543
|
+
error: {
|
|
7544
|
+
code: ErrorCode.InvalidRequest,
|
|
7545
|
+
message: "Invalid Request: Server already initialized"
|
|
7546
|
+
},
|
|
7547
|
+
id: null
|
|
7548
|
+
}) });
|
|
7549
|
+
if (messages.length > 1) throw new HTTPException(400, { res: Response.json({
|
|
7550
|
+
jsonrpc: "2.0",
|
|
7551
|
+
error: {
|
|
7552
|
+
code: ErrorCode.InvalidRequest,
|
|
7553
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
7554
|
+
},
|
|
7555
|
+
id: null
|
|
7556
|
+
}) });
|
|
7557
|
+
this.sessionId = this.#sessionIdGenerator?.();
|
|
7558
|
+
this.#initialized = true;
|
|
7559
|
+
if (this.sessionId && this.#onSessionInitialized) await this.#onSessionInitialized(this.sessionId);
|
|
7560
|
+
}
|
|
7561
|
+
if (!isInitializationRequest) {
|
|
7562
|
+
this.#validateSession(ctx);
|
|
7563
|
+
this.#validateProtocolVersion(ctx);
|
|
7564
|
+
}
|
|
7565
|
+
const hasRequests = messages.some(isJSONRPCRequest);
|
|
7566
|
+
if (!hasRequests) {
|
|
7567
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7568
|
+
authInfo,
|
|
7569
|
+
requestInfo
|
|
7570
|
+
});
|
|
7571
|
+
return ctx.json(null, { status: 202 });
|
|
7572
|
+
}
|
|
7573
|
+
if (hasRequests) {
|
|
7574
|
+
const streamId = crypto.randomUUID();
|
|
7575
|
+
if (!this.#enableJsonResponse && this.sessionId !== void 0) ctx.header("mcp-session-id", this.sessionId);
|
|
7576
|
+
if (this.#enableJsonResponse) return await new Promise((resolve) => {
|
|
7577
|
+
for (const message of messages) if (isJSONRPCRequest(message)) {
|
|
7578
|
+
this.#streamMapping.set(streamId, {
|
|
7579
|
+
ctx: {
|
|
7580
|
+
header: ctx.header,
|
|
7581
|
+
json: (data) => {
|
|
7582
|
+
resolve(ctx.json(data));
|
|
7583
|
+
}
|
|
7584
|
+
},
|
|
7585
|
+
cleanup: () => {
|
|
7586
|
+
this.#streamMapping.delete(streamId);
|
|
7587
|
+
}
|
|
7588
|
+
});
|
|
7589
|
+
this.#requestToStreamMapping.set(message.id, streamId);
|
|
7590
|
+
}
|
|
7591
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7592
|
+
authInfo,
|
|
7593
|
+
requestInfo
|
|
7594
|
+
});
|
|
7595
|
+
});
|
|
7596
|
+
return streamSSE(ctx, async (stream) => {
|
|
7597
|
+
for (const message of messages) if (isJSONRPCRequest(message)) {
|
|
7598
|
+
this.#streamMapping.set(streamId, {
|
|
7599
|
+
ctx: { header: ctx.header },
|
|
7600
|
+
stream,
|
|
7601
|
+
cleanup: () => {
|
|
7602
|
+
this.#streamMapping.delete(streamId);
|
|
7603
|
+
}
|
|
7604
|
+
});
|
|
7605
|
+
this.#requestToStreamMapping.set(message.id, streamId);
|
|
7606
|
+
}
|
|
7607
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7608
|
+
authInfo,
|
|
7609
|
+
requestInfo
|
|
7610
|
+
});
|
|
7611
|
+
stream.onAbort(() => {
|
|
7612
|
+
this.#streamMapping.get(streamId)?.cleanup();
|
|
7613
|
+
});
|
|
7614
|
+
});
|
|
7615
|
+
}
|
|
7616
|
+
} catch (error) {
|
|
7617
|
+
if (error instanceof HTTPException) throw error;
|
|
7618
|
+
this.onerror?.(error);
|
|
7619
|
+
throw new HTTPException(400, { res: Response.json({
|
|
7620
|
+
jsonrpc: "2.0",
|
|
7621
|
+
error: {
|
|
7622
|
+
code: ErrorCode.ParseError,
|
|
7623
|
+
message: "Parse error",
|
|
7624
|
+
data: String(error)
|
|
7625
|
+
},
|
|
7626
|
+
id: null
|
|
7627
|
+
}) });
|
|
7628
|
+
}
|
|
7629
|
+
}
|
|
7630
|
+
/**
|
|
7631
|
+
* Handles DELETE requests to terminate sessions
|
|
7632
|
+
*/
|
|
7633
|
+
async handleDeleteRequest(ctx) {
|
|
7634
|
+
this.#validateSession(ctx);
|
|
7635
|
+
this.#validateProtocolVersion(ctx);
|
|
7636
|
+
if (this.#onSessionClosed && this.sessionId) await Promise.resolve(this.#onSessionClosed(this.sessionId));
|
|
7637
|
+
await this.close();
|
|
7638
|
+
return ctx.body(null, 200);
|
|
7639
|
+
}
|
|
7640
|
+
/**
|
|
7641
|
+
* Handles unsupported requests (PUT, PATCH, etc.)
|
|
7642
|
+
*/
|
|
7643
|
+
handleUnsupportedRequest(ctx) {
|
|
7644
|
+
return ctx.json({
|
|
7645
|
+
jsonrpc: "2.0",
|
|
7646
|
+
error: {
|
|
7647
|
+
code: ErrorCode.ConnectionClosed,
|
|
7648
|
+
message: "Method not allowed."
|
|
7649
|
+
},
|
|
7650
|
+
id: null
|
|
7651
|
+
}, {
|
|
7652
|
+
status: 405,
|
|
7653
|
+
headers: { Allow: "GET, POST, DELETE" }
|
|
7654
|
+
});
|
|
7655
|
+
}
|
|
7656
|
+
/**
|
|
7657
|
+
* Validates session ID for non-initialization requests
|
|
7658
|
+
* Returns true if the session is valid, false otherwise
|
|
7659
|
+
*/
|
|
7660
|
+
#validateSession(ctx) {
|
|
7661
|
+
if (this.#sessionIdGenerator === void 0) return true;
|
|
7662
|
+
if (!this.#initialized) throw new HTTPException(400, { res: Response.json({
|
|
7663
|
+
jsonrpc: "2.0",
|
|
7664
|
+
error: {
|
|
7665
|
+
code: ErrorCode.ConnectionClosed,
|
|
7666
|
+
message: "Bad Request: Server not initialized"
|
|
7667
|
+
},
|
|
7668
|
+
id: null
|
|
7669
|
+
}) });
|
|
7670
|
+
const sessionId = ctx.req.header("mcp-session-id");
|
|
7671
|
+
if (!sessionId) throw new HTTPException(400, { res: Response.json({
|
|
7672
|
+
jsonrpc: "2.0",
|
|
7673
|
+
error: {
|
|
7674
|
+
code: ErrorCode.ConnectionClosed,
|
|
7675
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
7676
|
+
},
|
|
7677
|
+
id: null
|
|
7678
|
+
}) });
|
|
7679
|
+
if (Array.isArray(sessionId)) throw new HTTPException(400, { res: Response.json({
|
|
7680
|
+
jsonrpc: "2.0",
|
|
7681
|
+
error: {
|
|
7682
|
+
code: ErrorCode.ConnectionClosed,
|
|
7683
|
+
message: "Bad Request: Mcp-Session-Id header must be a single value"
|
|
7684
|
+
},
|
|
7685
|
+
id: null
|
|
7686
|
+
}) });
|
|
7687
|
+
if (sessionId !== this.sessionId) throw new HTTPException(404, { res: Response.json({
|
|
7688
|
+
jsonrpc: "2.0",
|
|
7689
|
+
error: {
|
|
7690
|
+
code: ErrorCode.RequestTimeout,
|
|
7691
|
+
message: "Session not found"
|
|
7692
|
+
},
|
|
7693
|
+
id: null
|
|
7694
|
+
}) });
|
|
7695
|
+
return true;
|
|
7696
|
+
}
|
|
7697
|
+
#validateProtocolVersion(ctx) {
|
|
7698
|
+
let protocolVersion = ctx.req.header("mcp-protocol-version") ?? "2025-03-26";
|
|
7699
|
+
if (Array.isArray(protocolVersion)) protocolVersion = protocolVersion[protocolVersion.length - 1];
|
|
7700
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) throw new HTTPException(404, { res: Response.json({
|
|
7701
|
+
jsonrpc: "2.0",
|
|
7702
|
+
error: {
|
|
7703
|
+
code: ErrorCode.ConnectionClosed,
|
|
7704
|
+
message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`
|
|
7705
|
+
},
|
|
7706
|
+
id: null
|
|
7707
|
+
}) });
|
|
7708
|
+
return true;
|
|
7709
|
+
}
|
|
7710
|
+
async close() {
|
|
7711
|
+
for (const { stream } of this.#streamMapping.values()) stream?.abort();
|
|
7712
|
+
this.#streamMapping.clear();
|
|
7713
|
+
this.#requestResponseMap.clear();
|
|
7714
|
+
this.onclose?.();
|
|
7715
|
+
}
|
|
7716
|
+
async send(message, options) {
|
|
7717
|
+
let requestId = options?.relatedRequestId;
|
|
7718
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id;
|
|
7719
|
+
if (requestId === void 0) {
|
|
7720
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
|
|
7721
|
+
const standaloneSse = this.#streamMapping.get(this.#standaloneSseStreamId);
|
|
7722
|
+
if (standaloneSse === void 0) return;
|
|
7723
|
+
let eventId;
|
|
7724
|
+
if (this.#eventStore) eventId = await this.#eventStore.storeEvent(this.#standaloneSseStreamId, message);
|
|
7725
|
+
return standaloneSse.stream?.writeSSE({
|
|
7726
|
+
id: eventId,
|
|
7727
|
+
event: "message",
|
|
7728
|
+
data: JSON.stringify(message)
|
|
7729
|
+
});
|
|
7730
|
+
}
|
|
7731
|
+
const streamId = this.#requestToStreamMapping.get(requestId);
|
|
7732
|
+
const response = this.#streamMapping.get(streamId);
|
|
7733
|
+
if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
7734
|
+
if (!this.#enableJsonResponse) {
|
|
7735
|
+
let eventId;
|
|
7736
|
+
if (this.#eventStore) eventId = await this.#eventStore.storeEvent(streamId, message);
|
|
7737
|
+
if (response) await response.stream?.writeSSE({
|
|
7738
|
+
id: eventId,
|
|
7739
|
+
event: "message",
|
|
7740
|
+
data: JSON.stringify(message)
|
|
7741
|
+
});
|
|
7742
|
+
}
|
|
7743
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
|
|
7744
|
+
this.#requestResponseMap.set(requestId, message);
|
|
7745
|
+
const relatedIds = Array.from(this.#requestToStreamMapping.entries()).filter(([, streamId$1]) => this.#streamMapping.get(streamId$1) === response).map(([id]) => id);
|
|
7746
|
+
if (relatedIds.every((id) => this.#requestResponseMap.has(id))) {
|
|
7747
|
+
if (!response) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
7748
|
+
if (this.#enableJsonResponse) {
|
|
7749
|
+
if (this.sessionId !== void 0) response.ctx.header("mcp-session-id", this.sessionId);
|
|
7750
|
+
const responses = relatedIds.map((id) => this.#requestResponseMap.get(id));
|
|
7751
|
+
response.ctx.json?.(responses.length === 1 ? responses[0] : responses);
|
|
7752
|
+
return;
|
|
7753
|
+
} else response.stream?.abort();
|
|
7754
|
+
for (const id of relatedIds) {
|
|
7755
|
+
this.#requestResponseMap.delete(id);
|
|
7756
|
+
this.#requestToStreamMapping.delete(id);
|
|
7757
|
+
}
|
|
7758
|
+
}
|
|
7759
|
+
}
|
|
7760
|
+
}
|
|
7761
|
+
};
|
|
7762
|
+
//#endregion
|
|
7763
|
+
//#region ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.19/node_modules/@hono/node-server/dist/index.mjs
|
|
7764
|
+
var RequestError = class extends Error {
|
|
7765
|
+
constructor(message, options) {
|
|
7766
|
+
super(message, options);
|
|
7767
|
+
this.name = "RequestError";
|
|
7768
|
+
}
|
|
7769
|
+
};
|
|
7770
|
+
var toRequestError = (e) => {
|
|
7771
|
+
if (e instanceof RequestError) return e;
|
|
7772
|
+
return new RequestError(e.message, { cause: e });
|
|
7773
|
+
};
|
|
7774
|
+
var GlobalRequest = global.Request;
|
|
7775
|
+
var Request$1 = class extends GlobalRequest {
|
|
7776
|
+
constructor(input, options) {
|
|
7777
|
+
if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
|
|
7778
|
+
if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
|
|
7779
|
+
super(input, options);
|
|
7780
|
+
}
|
|
7781
|
+
};
|
|
7782
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
7783
|
+
const headerRecord = [];
|
|
7784
|
+
const rawHeaders = incoming.rawHeaders;
|
|
7785
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
7786
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
7787
|
+
if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
|
|
7788
|
+
}
|
|
7789
|
+
return new Headers(headerRecord);
|
|
7790
|
+
};
|
|
7791
|
+
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
7792
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
7793
|
+
const init = {
|
|
7794
|
+
method,
|
|
7795
|
+
headers,
|
|
7796
|
+
signal: abortController.signal
|
|
7797
|
+
};
|
|
7798
|
+
if (method === "TRACE") {
|
|
7799
|
+
init.method = "GET";
|
|
7800
|
+
const req = new Request$1(url, init);
|
|
7801
|
+
Object.defineProperty(req, "method", { get() {
|
|
7802
|
+
return "TRACE";
|
|
7803
|
+
} });
|
|
7804
|
+
return req;
|
|
7805
|
+
}
|
|
7806
|
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
|
7807
|
+
controller.enqueue(incoming.rawBody);
|
|
7808
|
+
controller.close();
|
|
7809
|
+
} });
|
|
7810
|
+
else if (incoming[wrapBodyStream]) {
|
|
7811
|
+
let reader;
|
|
7812
|
+
init.body = new ReadableStream({ async pull(controller) {
|
|
7813
|
+
try {
|
|
7814
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
7815
|
+
const { done, value } = await reader.read();
|
|
7816
|
+
if (done) controller.close();
|
|
7817
|
+
else controller.enqueue(value);
|
|
7818
|
+
} catch (error) {
|
|
7819
|
+
controller.error(error);
|
|
7820
|
+
}
|
|
7821
|
+
} });
|
|
7822
|
+
} else init.body = Readable.toWeb(incoming);
|
|
7823
|
+
return new Request$1(url, init);
|
|
7824
|
+
};
|
|
7825
|
+
var getRequestCache = Symbol("getRequestCache");
|
|
7826
|
+
var requestCache = Symbol("requestCache");
|
|
7827
|
+
var incomingKey = Symbol("incomingKey");
|
|
7828
|
+
var urlKey = Symbol("urlKey");
|
|
7829
|
+
var headersKey = Symbol("headersKey");
|
|
7830
|
+
var abortControllerKey = Symbol("abortControllerKey");
|
|
7831
|
+
var requestPrototype = {
|
|
7832
|
+
get method() {
|
|
7833
|
+
return this[incomingKey].method || "GET";
|
|
7834
|
+
},
|
|
7835
|
+
get url() {
|
|
7836
|
+
return this[urlKey];
|
|
7837
|
+
},
|
|
7838
|
+
get headers() {
|
|
7839
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
7840
|
+
},
|
|
7841
|
+
[Symbol("getAbortController")]() {
|
|
7842
|
+
this[getRequestCache]();
|
|
7843
|
+
return this[abortControllerKey];
|
|
7844
|
+
},
|
|
7845
|
+
[getRequestCache]() {
|
|
7846
|
+
this[abortControllerKey] ||= new AbortController();
|
|
7847
|
+
return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
|
|
7848
|
+
}
|
|
7849
|
+
};
|
|
7850
|
+
[
|
|
7851
|
+
"body",
|
|
7852
|
+
"bodyUsed",
|
|
7853
|
+
"cache",
|
|
7854
|
+
"credentials",
|
|
7855
|
+
"destination",
|
|
7856
|
+
"integrity",
|
|
7857
|
+
"mode",
|
|
7858
|
+
"redirect",
|
|
7859
|
+
"referrer",
|
|
7860
|
+
"referrerPolicy",
|
|
7861
|
+
"signal",
|
|
7862
|
+
"keepalive"
|
|
7863
|
+
].forEach((k) => {
|
|
7864
|
+
Object.defineProperty(requestPrototype, k, { get() {
|
|
7865
|
+
return this[getRequestCache]()[k];
|
|
7866
|
+
} });
|
|
7867
|
+
});
|
|
7868
|
+
[
|
|
7869
|
+
"arrayBuffer",
|
|
7870
|
+
"blob",
|
|
7871
|
+
"clone",
|
|
7872
|
+
"formData",
|
|
7873
|
+
"json",
|
|
7874
|
+
"text"
|
|
7875
|
+
].forEach((k) => {
|
|
7876
|
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
|
7877
|
+
return this[getRequestCache]()[k]();
|
|
7878
|
+
} });
|
|
7879
|
+
});
|
|
7880
|
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
7881
|
+
return `Request (lightweight) ${inspectFn({
|
|
7882
|
+
method: this.method,
|
|
7883
|
+
url: this.url,
|
|
7884
|
+
headers: this.headers,
|
|
7885
|
+
nativeRequest: this[requestCache]
|
|
7886
|
+
}, {
|
|
7887
|
+
...options,
|
|
7888
|
+
depth: depth == null ? null : depth - 1
|
|
7889
|
+
})}`;
|
|
7890
|
+
} });
|
|
7891
|
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
|
7892
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
7893
|
+
const req = Object.create(requestPrototype);
|
|
7894
|
+
req[incomingKey] = incoming;
|
|
7895
|
+
const incomingUrl = incoming.url || "";
|
|
7896
|
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
7897
|
+
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
7898
|
+
try {
|
|
7899
|
+
req[urlKey] = new URL(incomingUrl).href;
|
|
7900
|
+
} catch (e) {
|
|
7901
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
7902
|
+
}
|
|
7903
|
+
return req;
|
|
7904
|
+
}
|
|
7905
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
7906
|
+
if (!host) throw new RequestError("Missing host header");
|
|
7907
|
+
let scheme;
|
|
7908
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
7909
|
+
scheme = incoming.scheme;
|
|
7910
|
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
|
7911
|
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
7912
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
7913
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
|
|
7914
|
+
req[urlKey] = url.href;
|
|
7915
|
+
return req;
|
|
7916
|
+
};
|
|
7917
|
+
var responseCache = Symbol("responseCache");
|
|
7918
|
+
var getResponseCache = Symbol("getResponseCache");
|
|
7919
|
+
var cacheKey = Symbol("cache");
|
|
7920
|
+
var GlobalResponse = global.Response;
|
|
7921
|
+
var Response2 = class _Response {
|
|
7922
|
+
#body;
|
|
7923
|
+
#init;
|
|
7924
|
+
[getResponseCache]() {
|
|
7925
|
+
delete this[cacheKey];
|
|
7926
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
7927
|
+
}
|
|
7928
|
+
constructor(body, init) {
|
|
7929
|
+
let headers;
|
|
7930
|
+
this.#body = body;
|
|
7931
|
+
if (init instanceof _Response) {
|
|
7932
|
+
const cachedGlobalResponse = init[responseCache];
|
|
7933
|
+
if (cachedGlobalResponse) {
|
|
7934
|
+
this.#init = cachedGlobalResponse;
|
|
7935
|
+
this[getResponseCache]();
|
|
7936
|
+
return;
|
|
7937
|
+
} else {
|
|
7938
|
+
this.#init = init.#init;
|
|
7939
|
+
headers = new Headers(init.#init.headers);
|
|
7940
|
+
}
|
|
7941
|
+
} else this.#init = init;
|
|
7942
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
|
7943
|
+
init?.status || 200,
|
|
7944
|
+
body,
|
|
7945
|
+
headers || init?.headers
|
|
7946
|
+
];
|
|
7947
|
+
}
|
|
7948
|
+
get headers() {
|
|
7949
|
+
const cache = this[cacheKey];
|
|
7950
|
+
if (cache) {
|
|
7951
|
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
|
|
7952
|
+
return cache[2];
|
|
7953
|
+
}
|
|
7954
|
+
return this[getResponseCache]().headers;
|
|
7955
|
+
}
|
|
7956
|
+
get status() {
|
|
7957
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
7958
|
+
}
|
|
7959
|
+
get ok() {
|
|
7960
|
+
const status = this.status;
|
|
7961
|
+
return status >= 200 && status < 300;
|
|
7962
|
+
}
|
|
7963
|
+
};
|
|
7964
|
+
[
|
|
7965
|
+
"body",
|
|
7966
|
+
"bodyUsed",
|
|
7967
|
+
"redirected",
|
|
7968
|
+
"statusText",
|
|
7969
|
+
"trailers",
|
|
7970
|
+
"type",
|
|
7971
|
+
"url"
|
|
7972
|
+
].forEach((k) => {
|
|
7973
|
+
Object.defineProperty(Response2.prototype, k, { get() {
|
|
7974
|
+
return this[getResponseCache]()[k];
|
|
7975
|
+
} });
|
|
7976
|
+
});
|
|
7977
|
+
[
|
|
7978
|
+
"arrayBuffer",
|
|
7979
|
+
"blob",
|
|
7980
|
+
"clone",
|
|
7981
|
+
"formData",
|
|
7982
|
+
"json",
|
|
7983
|
+
"text"
|
|
7984
|
+
].forEach((k) => {
|
|
7985
|
+
Object.defineProperty(Response2.prototype, k, { value: function() {
|
|
7986
|
+
return this[getResponseCache]()[k]();
|
|
7987
|
+
} });
|
|
7988
|
+
});
|
|
7989
|
+
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
7990
|
+
return `Response (lightweight) ${inspectFn({
|
|
7991
|
+
status: this.status,
|
|
7992
|
+
headers: this.headers,
|
|
7993
|
+
ok: this.ok,
|
|
7994
|
+
nativeResponse: this[responseCache]
|
|
7995
|
+
}, {
|
|
7996
|
+
...options,
|
|
7997
|
+
depth: depth == null ? null : depth - 1
|
|
7998
|
+
})}`;
|
|
7999
|
+
} });
|
|
8000
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
8001
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
8002
|
+
async function readWithoutBlocking(readPromise) {
|
|
8003
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
8004
|
+
}
|
|
8005
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
8006
|
+
const cancel = (error) => {
|
|
8007
|
+
reader.cancel(error).catch(() => {});
|
|
8008
|
+
};
|
|
8009
|
+
writable.on("close", cancel);
|
|
8010
|
+
writable.on("error", cancel);
|
|
8011
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
8012
|
+
return reader.closed.finally(() => {
|
|
8013
|
+
writable.off("close", cancel);
|
|
8014
|
+
writable.off("error", cancel);
|
|
8015
|
+
});
|
|
8016
|
+
function handleStreamError(error) {
|
|
8017
|
+
if (error) writable.destroy(error);
|
|
8018
|
+
}
|
|
8019
|
+
function onDrain() {
|
|
8020
|
+
reader.read().then(flow, handleStreamError);
|
|
8021
|
+
}
|
|
8022
|
+
function flow({ done, value }) {
|
|
8023
|
+
try {
|
|
8024
|
+
if (done) writable.end();
|
|
8025
|
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
|
8026
|
+
else return reader.read().then(flow, handleStreamError);
|
|
8027
|
+
} catch (e) {
|
|
8028
|
+
handleStreamError(e);
|
|
8029
|
+
}
|
|
8030
|
+
}
|
|
8031
|
+
}
|
|
8032
|
+
function writeFromReadableStream(stream, writable) {
|
|
8033
|
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
|
8034
|
+
else if (writable.destroyed) return;
|
|
8035
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
8036
|
+
}
|
|
8037
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
8038
|
+
const res = {};
|
|
8039
|
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
|
8040
|
+
const cookies = [];
|
|
8041
|
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
|
8042
|
+
else res[k] = v;
|
|
8043
|
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
|
8044
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
8045
|
+
return res;
|
|
8046
|
+
};
|
|
8047
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
8048
|
+
if (typeof global.crypto === "undefined") global.crypto = crypto$1;
|
|
8049
|
+
var outgoingEnded = Symbol("outgoingEnded");
|
|
8050
|
+
var incomingDraining = Symbol("incomingDraining");
|
|
8051
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
8052
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
8053
|
+
var drainIncoming = (incoming) => {
|
|
8054
|
+
const incomingWithDrainState = incoming;
|
|
8055
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
|
8056
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
8057
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
8058
|
+
try {
|
|
8059
|
+
incoming.stream?.close?.(constants$1.NGHTTP2_NO_ERROR);
|
|
8060
|
+
} catch {}
|
|
8061
|
+
return;
|
|
8062
|
+
}
|
|
8063
|
+
let bytesRead = 0;
|
|
8064
|
+
const cleanup = () => {
|
|
8065
|
+
clearTimeout(timer);
|
|
8066
|
+
incoming.off("data", onData);
|
|
8067
|
+
incoming.off("end", cleanup);
|
|
8068
|
+
incoming.off("error", cleanup);
|
|
8069
|
+
};
|
|
8070
|
+
const forceClose = () => {
|
|
8071
|
+
cleanup();
|
|
8072
|
+
const socket = incoming.socket;
|
|
8073
|
+
if (socket && !socket.destroyed) socket.destroySoon();
|
|
8074
|
+
};
|
|
8075
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
8076
|
+
timer.unref?.();
|
|
8077
|
+
const onData = (chunk) => {
|
|
8078
|
+
bytesRead += chunk.length;
|
|
8079
|
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
|
8080
|
+
};
|
|
8081
|
+
incoming.on("data", onData);
|
|
8082
|
+
incoming.on("end", cleanup);
|
|
8083
|
+
incoming.on("error", cleanup);
|
|
8084
|
+
incoming.resume();
|
|
8085
|
+
};
|
|
8086
|
+
var handleRequestError = () => new Response(null, { status: 400 });
|
|
8087
|
+
var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
|
8088
|
+
var handleResponseError = (e, outgoing) => {
|
|
8089
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
8090
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
|
8091
|
+
else {
|
|
8092
|
+
console.error(e);
|
|
8093
|
+
if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
8094
|
+
outgoing.end(`Error: ${err.message}`);
|
|
8095
|
+
outgoing.destroy(err);
|
|
8096
|
+
}
|
|
8097
|
+
};
|
|
8098
|
+
var flushHeaders = (outgoing) => {
|
|
8099
|
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
|
8100
|
+
};
|
|
8101
|
+
var responseViaCache = async (res, outgoing) => {
|
|
8102
|
+
let [status, body, header] = res[cacheKey];
|
|
8103
|
+
let hasContentLength = false;
|
|
8104
|
+
if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
|
|
8105
|
+
else if (header instanceof Headers) {
|
|
8106
|
+
hasContentLength = header.has("content-length");
|
|
8107
|
+
header = buildOutgoingHttpHeaders(header);
|
|
8108
|
+
} else if (Array.isArray(header)) {
|
|
8109
|
+
const headerObj = new Headers(header);
|
|
8110
|
+
hasContentLength = headerObj.has("content-length");
|
|
8111
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
8112
|
+
} else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
8113
|
+
hasContentLength = true;
|
|
8114
|
+
break;
|
|
8115
|
+
}
|
|
8116
|
+
if (!hasContentLength) {
|
|
8117
|
+
if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
|
|
8118
|
+
else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
|
|
8119
|
+
else if (body instanceof Blob) header["Content-Length"] = body.size;
|
|
8120
|
+
}
|
|
8121
|
+
outgoing.writeHead(status, header);
|
|
8122
|
+
if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
|
8123
|
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
8124
|
+
else {
|
|
8125
|
+
flushHeaders(outgoing);
|
|
8126
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
8127
|
+
}
|
|
8128
|
+
outgoing[outgoingEnded]?.();
|
|
8129
|
+
};
|
|
8130
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
8131
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
8132
|
+
if (isPromise(res)) if (options.errorHandler) try {
|
|
8133
|
+
res = await res;
|
|
8134
|
+
} catch (err) {
|
|
8135
|
+
const errRes = await options.errorHandler(err);
|
|
8136
|
+
if (!errRes) return;
|
|
8137
|
+
res = errRes;
|
|
8138
|
+
}
|
|
8139
|
+
else res = await res.catch(handleFetchError);
|
|
8140
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
8141
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
8142
|
+
if (res.body) {
|
|
8143
|
+
const reader = res.body.getReader();
|
|
8144
|
+
const values = [];
|
|
8145
|
+
let done = false;
|
|
8146
|
+
let currentReadPromise = void 0;
|
|
8147
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
8148
|
+
let maxReadCount = 2;
|
|
8149
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
8150
|
+
currentReadPromise ||= reader.read();
|
|
8151
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
8152
|
+
console.error(e);
|
|
8153
|
+
done = true;
|
|
8154
|
+
});
|
|
8155
|
+
if (!chunk) {
|
|
8156
|
+
if (i === 1) {
|
|
8157
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
8158
|
+
maxReadCount = 3;
|
|
8159
|
+
continue;
|
|
8160
|
+
}
|
|
8161
|
+
break;
|
|
8162
|
+
}
|
|
8163
|
+
currentReadPromise = void 0;
|
|
8164
|
+
if (chunk.value) values.push(chunk.value);
|
|
8165
|
+
if (chunk.done) {
|
|
8166
|
+
done = true;
|
|
8167
|
+
break;
|
|
8168
|
+
}
|
|
8169
|
+
}
|
|
8170
|
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
8171
|
+
}
|
|
8172
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
8173
|
+
values.forEach((value) => {
|
|
8174
|
+
outgoing.write(value);
|
|
8175
|
+
});
|
|
8176
|
+
if (done) outgoing.end();
|
|
8177
|
+
else {
|
|
8178
|
+
if (values.length === 0) flushHeaders(outgoing);
|
|
8179
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
8180
|
+
}
|
|
8181
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
|
|
8182
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
8183
|
+
outgoing.end();
|
|
8184
|
+
}
|
|
8185
|
+
outgoing[outgoingEnded]?.();
|
|
8186
|
+
};
|
|
8187
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
8188
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
8189
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
|
8190
|
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
|
8191
|
+
Object.defineProperty(global, "Response", { value: Response2 });
|
|
8192
|
+
}
|
|
8193
|
+
return async (incoming, outgoing) => {
|
|
8194
|
+
let res, req;
|
|
8195
|
+
try {
|
|
8196
|
+
req = newRequest(incoming, options.hostname);
|
|
8197
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
8198
|
+
if (!incomingEnded) {
|
|
8199
|
+
incoming[wrapBodyStream] = true;
|
|
8200
|
+
incoming.on("end", () => {
|
|
8201
|
+
incomingEnded = true;
|
|
8202
|
+
});
|
|
8203
|
+
if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
|
8204
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8205
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8206
|
+
drainIncoming(incoming);
|
|
8207
|
+
});
|
|
8208
|
+
});
|
|
8209
|
+
};
|
|
8210
|
+
outgoing.on("finish", () => {
|
|
8211
|
+
if (!incomingEnded) drainIncoming(incoming);
|
|
8212
|
+
});
|
|
8213
|
+
}
|
|
8214
|
+
outgoing.on("close", () => {
|
|
8215
|
+
if (req[abortControllerKey]) {
|
|
8216
|
+
if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
|
|
8217
|
+
else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
8218
|
+
}
|
|
8219
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8220
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8221
|
+
drainIncoming(incoming);
|
|
8222
|
+
});
|
|
8223
|
+
});
|
|
8224
|
+
});
|
|
8225
|
+
res = fetchCallback(req, {
|
|
8226
|
+
incoming,
|
|
8227
|
+
outgoing
|
|
8228
|
+
});
|
|
8229
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
8230
|
+
} catch (e) {
|
|
8231
|
+
if (!res) if (options.errorHandler) {
|
|
8232
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
8233
|
+
if (!res) return;
|
|
8234
|
+
} else if (!req) res = handleRequestError();
|
|
8235
|
+
else res = handleFetchError(e);
|
|
8236
|
+
else return handleResponseError(e, outgoing);
|
|
8237
|
+
}
|
|
8238
|
+
try {
|
|
8239
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
8240
|
+
} catch (e) {
|
|
8241
|
+
return handleResponseError(e, outgoing);
|
|
8242
|
+
}
|
|
8243
|
+
};
|
|
8244
|
+
};
|
|
8245
|
+
var createAdaptorServer = (options) => {
|
|
8246
|
+
const fetchCallback = options.fetch;
|
|
8247
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
8248
|
+
hostname: options.hostname,
|
|
8249
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
8250
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
8251
|
+
});
|
|
8252
|
+
return (options.createServer || createServer)(options.serverOptions || {}, requestListener);
|
|
8253
|
+
};
|
|
8254
|
+
var serve = (options, listeningListener) => {
|
|
8255
|
+
const server = createAdaptorServer(options);
|
|
8256
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
8257
|
+
const serverInfo = server.address();
|
|
8258
|
+
listeningListener && listeningListener(serverInfo);
|
|
8259
|
+
});
|
|
8260
|
+
return server;
|
|
8261
|
+
};
|
|
8262
|
+
//#endregion
|
|
8263
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/color.js
|
|
8264
|
+
function getColorEnabled() {
|
|
8265
|
+
const { process, Deno } = globalThis;
|
|
8266
|
+
return !(typeof Deno?.noColor === "boolean" ? Deno.noColor : process !== void 0 ? "NO_COLOR" in process?.env : false);
|
|
8267
|
+
}
|
|
8268
|
+
async function getColorEnabledAsync() {
|
|
8269
|
+
const { navigator } = globalThis;
|
|
8270
|
+
const cfWorkers = "cloudflare:workers";
|
|
8271
|
+
return !(navigator !== void 0 && navigator.userAgent === "Cloudflare-Workers" ? await (async () => {
|
|
8272
|
+
try {
|
|
8273
|
+
return "NO_COLOR" in ((await import(cfWorkers)).env ?? {});
|
|
8274
|
+
} catch {
|
|
8275
|
+
return false;
|
|
8276
|
+
}
|
|
8277
|
+
})() : !getColorEnabled());
|
|
8278
|
+
}
|
|
8279
|
+
//#endregion
|
|
8280
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/middleware/logger/index.js
|
|
8281
|
+
var humanize = (times) => {
|
|
8282
|
+
const [delimiter, separator] = [",", "."];
|
|
8283
|
+
return times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter)).join(separator);
|
|
8284
|
+
};
|
|
8285
|
+
var time = (start) => {
|
|
8286
|
+
const delta = Date.now() - start;
|
|
8287
|
+
return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]);
|
|
8288
|
+
};
|
|
8289
|
+
var colorStatus = async (status) => {
|
|
8290
|
+
if (await getColorEnabledAsync()) switch (status / 100 | 0) {
|
|
8291
|
+
case 5: return `\x1B[31m${status}\x1B[0m`;
|
|
8292
|
+
case 4: return `\x1B[33m${status}\x1B[0m`;
|
|
8293
|
+
case 3: return `\x1B[36m${status}\x1B[0m`;
|
|
8294
|
+
case 2: return `\x1B[32m${status}\x1B[0m`;
|
|
8295
|
+
}
|
|
8296
|
+
return `${status}`;
|
|
8297
|
+
};
|
|
8298
|
+
async function log(fn, prefix, method, path, status = 0, elapsed) {
|
|
8299
|
+
fn(prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`);
|
|
8300
|
+
}
|
|
8301
|
+
var logger = (fn = console.log) => {
|
|
8302
|
+
return async function logger2(c, next) {
|
|
8303
|
+
const { method, url } = c.req;
|
|
8304
|
+
const path = url.slice(url.indexOf("/", 8));
|
|
8305
|
+
await log(fn, "<--", method, path);
|
|
8306
|
+
const start = Date.now();
|
|
8307
|
+
await next();
|
|
8308
|
+
await log(fn, "-->", method, path, c.res.status, time(start));
|
|
8309
|
+
};
|
|
8310
|
+
};
|
|
8311
|
+
//#endregion
|
|
8312
|
+
//#region src/serve/http.ts
|
|
8313
|
+
function createHttpServeApp(options, engine, io = {}) {
|
|
8314
|
+
const app = new Hono();
|
|
8315
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
8316
|
+
const writeErr = io.writeErr ?? process.stderr.write.bind(process.stderr);
|
|
8317
|
+
app.use("*", logger((message, ...rest) => {
|
|
8318
|
+
writeErr(`${[message, ...rest].join(" ")}\n`);
|
|
8319
|
+
}));
|
|
8320
|
+
app.get("/", (c) => c.json({
|
|
8321
|
+
name: "caplets",
|
|
8322
|
+
transport: "http",
|
|
8323
|
+
mcp: options.path,
|
|
8324
|
+
health: "/healthz",
|
|
8325
|
+
auth: {
|
|
8326
|
+
type: "basic",
|
|
8327
|
+
enabled: options.auth.enabled
|
|
8328
|
+
}
|
|
8329
|
+
}));
|
|
8330
|
+
app.get("/healthz", (c) => c.json({
|
|
8331
|
+
status: "ok",
|
|
8332
|
+
transport: "http",
|
|
8333
|
+
mcpPath: options.path
|
|
8334
|
+
}));
|
|
8335
|
+
app.all(options.path, basicAuth(options.auth), async (c) => {
|
|
8336
|
+
const sessionId = c.req.header("mcp-session-id");
|
|
8337
|
+
if (sessionId) {
|
|
8338
|
+
const existing = sessions.get(sessionId);
|
|
8339
|
+
if (!existing) return c.json({
|
|
8340
|
+
jsonrpc: "2.0",
|
|
8341
|
+
error: {
|
|
8342
|
+
code: -32001,
|
|
8343
|
+
message: "Session not found"
|
|
8344
|
+
},
|
|
8345
|
+
id: null
|
|
8346
|
+
}, 404);
|
|
8347
|
+
return existing.transport.handleRequest(c);
|
|
8348
|
+
}
|
|
8349
|
+
if (c.req.method !== "POST") return c.json({
|
|
8350
|
+
jsonrpc: "2.0",
|
|
8351
|
+
error: {
|
|
8352
|
+
code: -32e3,
|
|
8353
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
8354
|
+
},
|
|
8355
|
+
id: null
|
|
8356
|
+
}, 400);
|
|
8357
|
+
const nextSessionId = randomUUID();
|
|
8358
|
+
const session = await createHttpSession(engine, nextSessionId, options, async (closedSessionId) => {
|
|
8359
|
+
const closed = sessions.get(closedSessionId);
|
|
8360
|
+
sessions.delete(closedSessionId);
|
|
8361
|
+
if (closed) await closed.server.close();
|
|
8362
|
+
});
|
|
8363
|
+
sessions.set(nextSessionId, session);
|
|
8364
|
+
return session.transport.handleRequest(c);
|
|
8365
|
+
});
|
|
8366
|
+
app.notFound((c) => c.json({ error: "not_found" }, 404));
|
|
8367
|
+
app.closeCapletsSessions = async () => {
|
|
8368
|
+
await Promise.allSettled([...sessions.values()].map(async (session) => {
|
|
8369
|
+
await session.server.close();
|
|
8370
|
+
}));
|
|
8371
|
+
sessions.clear();
|
|
8372
|
+
};
|
|
8373
|
+
if (options.warnUnauthenticatedNetwork) writeErr(`Warning: Caplets MCP HTTP server is listening on ${options.host} without authentication.\n`);
|
|
8374
|
+
return app;
|
|
8375
|
+
}
|
|
8376
|
+
async function serveHttp(options, engineOptions = {}, writeErr = (value) => process.stderr.write(value)) {
|
|
8377
|
+
const engine = new CapletsEngine(engineOptions);
|
|
8378
|
+
const app = createHttpServeApp(options, engine, { writeErr });
|
|
8379
|
+
installHttpSignalHandlers(serve({
|
|
8380
|
+
fetch: app.fetch,
|
|
8381
|
+
hostname: options.host,
|
|
8382
|
+
port: options.port
|
|
8383
|
+
}, () => {
|
|
8384
|
+
writeErr(`Caplets MCP HTTP server listening on http://${formatHost(options.host)}:${options.port}${options.path}\n`);
|
|
8385
|
+
writeErr(`Health check: http://${formatHost(options.host)}:${options.port}/healthz\n`);
|
|
8386
|
+
writeErr(`Basic Auth: ${options.auth.enabled ? `enabled (user: ${options.auth.user})` : "disabled"}\n`);
|
|
8387
|
+
}), app, engine, writeErr);
|
|
8388
|
+
}
|
|
8389
|
+
async function createHttpSession(engine, sessionId, options, onClose) {
|
|
8390
|
+
const transport = new StreamableHTTPTransport({
|
|
8391
|
+
sessionIdGenerator: () => sessionId,
|
|
8392
|
+
onsessionclosed: onClose,
|
|
8393
|
+
...options.loopback ? dnsRebindingOptions(options) : {}
|
|
8394
|
+
});
|
|
8395
|
+
const server = new CapletsMcpSession(engine);
|
|
8396
|
+
await server.connect(transport);
|
|
8397
|
+
return {
|
|
8398
|
+
server,
|
|
8399
|
+
transport
|
|
8400
|
+
};
|
|
8401
|
+
}
|
|
8402
|
+
function basicAuth(auth) {
|
|
8403
|
+
return async (c, next) => {
|
|
8404
|
+
if (!auth.enabled) {
|
|
8405
|
+
await next();
|
|
8406
|
+
return;
|
|
8407
|
+
}
|
|
8408
|
+
const credentials = parseBasicAuth(c.req.header("authorization") ?? "");
|
|
8409
|
+
if (!credentials || !safeEqual(credentials.user, auth.user) || !safeEqual(credentials.password, auth.password)) {
|
|
8410
|
+
c.header("www-authenticate", "Basic realm=\"caplets\"");
|
|
8411
|
+
return c.text("Unauthorized", 401);
|
|
8412
|
+
}
|
|
8413
|
+
await next();
|
|
8414
|
+
};
|
|
8415
|
+
}
|
|
8416
|
+
function parseBasicAuth(header) {
|
|
8417
|
+
const [scheme, encoded] = header.split(" ");
|
|
8418
|
+
if (scheme?.toLocaleLowerCase() !== "basic" || !encoded) return;
|
|
8419
|
+
const decoded = Buffer.from(encoded, "base64").toString("utf8");
|
|
8420
|
+
const separator = decoded.indexOf(":");
|
|
8421
|
+
if (separator < 0) return;
|
|
8422
|
+
return {
|
|
8423
|
+
user: decoded.slice(0, separator),
|
|
8424
|
+
password: decoded.slice(separator + 1)
|
|
8425
|
+
};
|
|
8426
|
+
}
|
|
8427
|
+
function safeEqual(left, right) {
|
|
8428
|
+
const leftBuffer = Buffer.from(left);
|
|
8429
|
+
const rightBuffer = Buffer.from(right);
|
|
8430
|
+
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
|
8431
|
+
}
|
|
8432
|
+
function dnsRebindingOptions(options) {
|
|
8433
|
+
const hostForHeader = options.host === "::1" ? "[::1]" : options.host;
|
|
8434
|
+
return {
|
|
8435
|
+
enableDnsRebindingProtection: true,
|
|
8436
|
+
allowedHosts: [
|
|
8437
|
+
options.host,
|
|
8438
|
+
hostForHeader,
|
|
8439
|
+
`${hostForHeader}:${options.port}`,
|
|
8440
|
+
`localhost:${options.port}`
|
|
8441
|
+
]
|
|
8442
|
+
};
|
|
8443
|
+
}
|
|
8444
|
+
function installHttpSignalHandlers(server, app, engine, writeErr) {
|
|
8445
|
+
let closing;
|
|
8446
|
+
const close = async () => {
|
|
8447
|
+
closing ??= (async () => {
|
|
8448
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
8449
|
+
await app.closeCapletsSessions();
|
|
8450
|
+
await engine.close();
|
|
8451
|
+
})();
|
|
8452
|
+
return closing;
|
|
8453
|
+
};
|
|
8454
|
+
process.once("SIGINT", () => void close().catch((error) => writeErr(`${String(error)}\n`)).finally(() => process.exit(130)));
|
|
8455
|
+
process.once("SIGTERM", () => void close().catch((error) => writeErr(`${String(error)}\n`)).finally(() => process.exit(143)));
|
|
8456
|
+
}
|
|
8457
|
+
function formatHost(host) {
|
|
8458
|
+
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
8459
|
+
}
|
|
8460
|
+
//#endregion
|
|
8461
|
+
//#region src/serve/options.ts
|
|
8462
|
+
const HTTP_ONLY_OPTIONS = [
|
|
8463
|
+
"host",
|
|
8464
|
+
"port",
|
|
8465
|
+
"path",
|
|
8466
|
+
"user",
|
|
8467
|
+
"password",
|
|
8468
|
+
"allowUnauthenticatedHttp"
|
|
8469
|
+
];
|
|
8470
|
+
function resolveServeOptions(raw, env = process.env) {
|
|
8471
|
+
const transport = parseTransport(raw.transport ?? "stdio");
|
|
8472
|
+
if (transport === "stdio") {
|
|
8473
|
+
const invalid = HTTP_ONLY_OPTIONS.filter((key) => raw[key] !== void 0);
|
|
8474
|
+
if (invalid.length > 0) throw new CapletsError("REQUEST_INVALID", `${invalid.map((key) => `--${key}`).join(", ")} ${invalid.length === 1 ? "is" : "are"} only valid with --transport http`);
|
|
8475
|
+
return { transport };
|
|
8476
|
+
}
|
|
8477
|
+
const host = nonEmpty(raw.host, "--host") ?? "127.0.0.1";
|
|
8478
|
+
const port = parsePort(raw.port ?? 5387);
|
|
8479
|
+
const path = normalizeHttpPath(raw.path ?? "/mcp");
|
|
8480
|
+
const userWasExplicit = raw.user !== void 0 || hasEnv(env.CAPLETS_SERVER_USER);
|
|
8481
|
+
const user = nonEmpty(raw.user, "--user") ?? nonEmpty(env.CAPLETS_SERVER_USER, "CAPLETS_SERVER_USER") ?? "caplets";
|
|
8482
|
+
const password = nonEmpty(raw.password, "--password") ?? nonEmpty(env.CAPLETS_SERVER_PASSWORD, "CAPLETS_SERVER_PASSWORD");
|
|
8483
|
+
if (userWasExplicit && password === void 0) throw new CapletsError("REQUEST_INVALID", "HTTP Basic Auth requires a password; pass --password or set CAPLETS_SERVER_PASSWORD.");
|
|
8484
|
+
const loopback = isLoopbackHost(host);
|
|
8485
|
+
const auth = password === void 0 ? {
|
|
8486
|
+
enabled: false,
|
|
8487
|
+
user
|
|
8488
|
+
} : {
|
|
8489
|
+
enabled: true,
|
|
8490
|
+
user,
|
|
8491
|
+
password
|
|
8492
|
+
};
|
|
8493
|
+
if (!loopback && !auth.enabled && raw.allowUnauthenticatedHttp !== true) throw new CapletsError("REQUEST_INVALID", "Unauthenticated HTTP serving on non-loopback hosts requires --allow-unauthenticated-http.");
|
|
8494
|
+
return {
|
|
8495
|
+
transport,
|
|
8496
|
+
host,
|
|
8497
|
+
port,
|
|
8498
|
+
path,
|
|
8499
|
+
auth,
|
|
8500
|
+
warnUnauthenticatedNetwork: !loopback && !auth.enabled,
|
|
8501
|
+
loopback
|
|
8502
|
+
};
|
|
8503
|
+
}
|
|
8504
|
+
function isLoopbackHost(host) {
|
|
8505
|
+
const normalized = host.toLocaleLowerCase();
|
|
8506
|
+
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
|
8507
|
+
}
|
|
8508
|
+
function parseTransport(value) {
|
|
8509
|
+
if (value === "stdio" || value === "http") return value;
|
|
8510
|
+
throw new CapletsError("REQUEST_INVALID", `Expected --transport to be stdio or http, got ${value}`);
|
|
8511
|
+
}
|
|
8512
|
+
function parsePort(value) {
|
|
8513
|
+
const parsed = typeof value === "number" ? value : Number(value);
|
|
8514
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) throw new CapletsError("REQUEST_INVALID", `Expected --port to be a valid TCP port, got ${value}`);
|
|
8515
|
+
return parsed;
|
|
8516
|
+
}
|
|
8517
|
+
function normalizeHttpPath(value) {
|
|
8518
|
+
if (!value.startsWith("/")) throw new CapletsError("REQUEST_INVALID", "HTTP --path must start with /");
|
|
8519
|
+
if (value.includes("?") || value.includes("#")) throw new CapletsError("REQUEST_INVALID", "HTTP --path must not include a query string or fragment");
|
|
8520
|
+
return value === "/" ? value : value.replace(/\/+$/u, "");
|
|
8521
|
+
}
|
|
8522
|
+
function nonEmpty(value, label) {
|
|
8523
|
+
if (value === void 0) return;
|
|
8524
|
+
const trimmed = value.trim();
|
|
8525
|
+
if (!trimmed) throw new CapletsError("REQUEST_INVALID", `${label} must not be empty`);
|
|
8526
|
+
return trimmed;
|
|
8527
|
+
}
|
|
8528
|
+
function hasEnv(value) {
|
|
8529
|
+
return value !== void 0 && value.trim() !== "";
|
|
8530
|
+
}
|
|
8531
|
+
//#endregion
|
|
8532
|
+
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
8533
|
+
/**
|
|
8534
|
+
* Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.
|
|
8535
|
+
*
|
|
8536
|
+
* This transport is only available in Node.js environments.
|
|
8537
|
+
*/
|
|
8538
|
+
var StdioServerTransport = class {
|
|
8539
|
+
constructor(_stdin = process$1.stdin, _stdout = process$1.stdout) {
|
|
8540
|
+
this._stdin = _stdin;
|
|
8541
|
+
this._stdout = _stdout;
|
|
8542
|
+
this._readBuffer = new ReadBuffer();
|
|
8543
|
+
this._started = false;
|
|
8544
|
+
this._ondata = (chunk) => {
|
|
8545
|
+
this._readBuffer.append(chunk);
|
|
8546
|
+
this.processReadBuffer();
|
|
8547
|
+
};
|
|
8548
|
+
this._onerror = (error) => {
|
|
8549
|
+
this.onerror?.(error);
|
|
8550
|
+
};
|
|
8551
|
+
}
|
|
8552
|
+
/**
|
|
8553
|
+
* Starts listening for messages on stdin.
|
|
8554
|
+
*/
|
|
8555
|
+
async start() {
|
|
8556
|
+
if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
|
|
8557
|
+
this._started = true;
|
|
8558
|
+
this._stdin.on("data", this._ondata);
|
|
8559
|
+
this._stdin.on("error", this._onerror);
|
|
8560
|
+
}
|
|
8561
|
+
processReadBuffer() {
|
|
8562
|
+
while (true) try {
|
|
8563
|
+
const message = this._readBuffer.readMessage();
|
|
8564
|
+
if (message === null) break;
|
|
8565
|
+
this.onmessage?.(message);
|
|
8566
|
+
} catch (error) {
|
|
8567
|
+
this.onerror?.(error);
|
|
8568
|
+
}
|
|
8569
|
+
}
|
|
8570
|
+
async close() {
|
|
8571
|
+
this._stdin.off("data", this._ondata);
|
|
8572
|
+
this._stdin.off("error", this._onerror);
|
|
8573
|
+
if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
|
|
8574
|
+
this._readBuffer.clear();
|
|
8575
|
+
this.onclose?.();
|
|
8576
|
+
}
|
|
8577
|
+
send(message) {
|
|
8578
|
+
return new Promise((resolve) => {
|
|
8579
|
+
const json = serializeMessage(message);
|
|
8580
|
+
if (this._stdout.write(json)) resolve();
|
|
8581
|
+
else this._stdout.once("drain", resolve);
|
|
8582
|
+
});
|
|
8583
|
+
}
|
|
8584
|
+
};
|
|
8585
|
+
//#endregion
|
|
8586
|
+
//#region src/serve/stdio.ts
|
|
8587
|
+
async function serveStdio(options = {}) {
|
|
8588
|
+
const engine = new CapletsEngine(options);
|
|
8589
|
+
const session = new CapletsMcpSession(engine);
|
|
8590
|
+
let closing = false;
|
|
8591
|
+
const close = async () => {
|
|
8592
|
+
if (closing) return;
|
|
8593
|
+
closing = true;
|
|
8594
|
+
try {
|
|
8595
|
+
await session.close();
|
|
8596
|
+
} finally {
|
|
8597
|
+
await engine.close();
|
|
8598
|
+
}
|
|
8599
|
+
};
|
|
8600
|
+
let sigintHandler;
|
|
8601
|
+
let sigtermHandler;
|
|
8602
|
+
if (options.signalHandling !== false) {
|
|
8603
|
+
sigintHandler = () => void close().finally(() => process.exit(130));
|
|
8604
|
+
sigtermHandler = () => void close().finally(() => process.exit(143));
|
|
8605
|
+
process.once("SIGINT", sigintHandler);
|
|
8606
|
+
process.once("SIGTERM", sigtermHandler);
|
|
8607
|
+
}
|
|
8608
|
+
try {
|
|
8609
|
+
await session.connect(new StdioServerTransport());
|
|
8610
|
+
} finally {
|
|
8611
|
+
if (sigintHandler) process.off("SIGINT", sigintHandler);
|
|
8612
|
+
if (sigtermHandler) process.off("SIGTERM", sigtermHandler);
|
|
8613
|
+
await close();
|
|
8614
|
+
}
|
|
8615
|
+
}
|
|
8616
|
+
//#endregion
|
|
8617
|
+
//#region src/serve/index.ts
|
|
8618
|
+
async function serveCaplets(options) {
|
|
8619
|
+
await serveResolvedCaplets(resolveServeOptions(options.raw, options.env ?? process.env), options.engine, options.writeErr);
|
|
8620
|
+
}
|
|
8621
|
+
async function serveResolvedCaplets(resolved, engineOptions = {}, writeErr) {
|
|
8622
|
+
if (resolved.transport === "stdio") {
|
|
8623
|
+
await serveStdio({
|
|
8624
|
+
...engineOptions,
|
|
8625
|
+
...writeErr ? { writeErr } : {}
|
|
8626
|
+
});
|
|
8627
|
+
return;
|
|
8628
|
+
}
|
|
8629
|
+
await serveHttp(resolved, {
|
|
8630
|
+
...engineOptions,
|
|
8631
|
+
...writeErr ? { writeErr } : {}
|
|
8632
|
+
}, writeErr);
|
|
8633
|
+
}
|
|
8634
|
+
//#endregion
|
|
8635
|
+
//#region src/cli.ts
|
|
8636
|
+
async function runCli(args, io = {}) {
|
|
8637
|
+
const program = createProgram(io);
|
|
8638
|
+
try {
|
|
8639
|
+
if (args.length === 0) {
|
|
8640
|
+
program.outputHelp();
|
|
8641
|
+
return;
|
|
8642
|
+
}
|
|
8643
|
+
await program.parseAsync([
|
|
8644
|
+
"node",
|
|
8645
|
+
"caplets",
|
|
8646
|
+
...args
|
|
8647
|
+
]);
|
|
8648
|
+
} catch (error) {
|
|
8649
|
+
if (error instanceof CommanderError) {
|
|
8650
|
+
if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.message === "(outputHelp)") return;
|
|
8651
|
+
throw new CapletsError("REQUEST_INVALID", error.message);
|
|
8652
|
+
}
|
|
8653
|
+
throw error;
|
|
8654
|
+
}
|
|
8655
|
+
}
|
|
8656
|
+
function createProgram(io = {}) {
|
|
8657
|
+
const writeOut = io.writeOut ?? ((value) => process.stdout.write(value));
|
|
8658
|
+
const writeErr = io.writeErr ?? ((value) => process.stderr.write(value));
|
|
8659
|
+
const setExitCode = io.setExitCode ?? ((code) => {
|
|
8660
|
+
process.exitCode = code;
|
|
8661
|
+
});
|
|
8662
|
+
const program = new Command();
|
|
8663
|
+
program.name("caplets").description("Progressive-disclosure gateway for MCP servers.").version(io.version ?? version).exitOverride().configureOutput({
|
|
8664
|
+
writeOut,
|
|
8665
|
+
writeErr,
|
|
8666
|
+
outputError: (value, write) => write(value)
|
|
8667
|
+
});
|
|
8668
|
+
program.command("serve").description("Serve configured Caplets as an MCP server.").option("--transport <transport>", "server transport: stdio or http").option("--host <host>", "HTTP bind host").option("--port <port>", "HTTP bind port").option("--path <path>", "HTTP MCP endpoint path").option("--user <user>", "HTTP Basic Auth username").option("--password <password>", "HTTP Basic Auth password").option("--allow-unauthenticated-http", "allow unauthenticated HTTP serving on non-loopback hosts").action(async (options) => {
|
|
8669
|
+
const resolved = resolveServeOptions(options);
|
|
8670
|
+
const configPath = envConfigPath();
|
|
8671
|
+
await (io.serve ?? ((serveOptions) => serveResolvedCaplets(serveOptions, {
|
|
8672
|
+
...configPath ? { configPath } : {},
|
|
8673
|
+
...io.authDir ? { authDir: io.authDir } : {}
|
|
8674
|
+
}, writeErr)))(resolved);
|
|
5388
8675
|
});
|
|
5389
8676
|
program.command("init").description("Create a starter Caplets config file.").option("--force", "overwrite an existing config file").action((options) => {
|
|
5390
8677
|
const configPath = envConfigPath();
|
|
@@ -5859,4 +9146,4 @@ function writeAddResult(writeOut, label, result) {
|
|
|
5859
9146
|
writeOut(result.text);
|
|
5860
9147
|
}
|
|
5861
9148
|
//#endregion
|
|
5862
|
-
export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, loadConfig, parseConfig, runCli };
|
|
9149
|
+
export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, loadConfig, parseConfig, runCli, serveCaplets, serveHttp, serveResolvedCaplets, serveStdio };
|