@xbghc/warden 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +179 -0
- package/dist/cli.js +4450 -0
- package/dist/web/assets/c-BIGW1oBm.js +1 -0
- package/dist/web/assets/cpp-BRuaLJcg.js +1 -0
- package/dist/web/assets/csharp-COcwbKMJ.js +1 -0
- package/dist/web/assets/css-DPfMkruS.js +1 -0
- package/dist/web/assets/dart-CF10PKvl.js +1 -0
- package/dist/web/assets/diff-D97Zzqfu.js +1 -0
- package/dist/web/assets/dockerfile-BcOcwvcX.js +1 -0
- package/dist/web/assets/dotenv-Da5cRb03.js +1 -0
- package/dist/web/assets/github-light-DAi9KRSo.js +1 -0
- package/dist/web/assets/go-CxLEBnE3.js +1 -0
- package/dist/web/assets/graphql-ChdNCCLP.js +1 -0
- package/dist/web/assets/html-GMplVEZG.js +1 -0
- package/dist/web/assets/index-BWrmu1DB.css +1 -0
- package/dist/web/assets/index-CZQadJRz.js +192 -0
- package/dist/web/assets/ini-BEwlwnbL.js +1 -0
- package/dist/web/assets/java-CylS5w8V.js +1 -0
- package/dist/web/assets/javascript-wDzz0qaB.js +1 -0
- package/dist/web/assets/json-Cp-IABpG.js +1 -0
- package/dist/web/assets/json5-C9tS-k6U.js +1 -0
- package/dist/web/assets/jsonc-Des-eS-w.js +1 -0
- package/dist/web/assets/jsx-g9-lgVsj.js +1 -0
- package/dist/web/assets/kotlin-BdnUsdx6.js +1 -0
- package/dist/web/assets/less-B1dDrJ26.js +1 -0
- package/dist/web/assets/lua-BaeVxFsk.js +1 -0
- package/dist/web/assets/makefile-CHLpvVh8.js +1 -0
- package/dist/web/assets/markdown-Cvjx9yec.js +1 -0
- package/dist/web/assets/mdx-Cmh6b_Ma.js +1 -0
- package/dist/web/assets/nginx-BpAMiNFr.js +1 -0
- package/dist/web/assets/php-Dhbhpdrm.js +1 -0
- package/dist/web/assets/prisma-Dd19v3D-.js +1 -0
- package/dist/web/assets/python-B6aJPvgy.js +1 -0
- package/dist/web/assets/ruby-BGX7qA9Y.js +1 -0
- package/dist/web/assets/rust-B1yitclQ.js +1 -0
- package/dist/web/assets/scss-OYdSNvt2.js +1 -0
- package/dist/web/assets/shellscript-Yzrsuije.js +1 -0
- package/dist/web/assets/sql-BLtJtn59.js +1 -0
- package/dist/web/assets/svelte-DZMnMd3x.js +1 -0
- package/dist/web/assets/swift-D82vCrfD.js +1 -0
- package/dist/web/assets/toml-vGWfd6FD.js +1 -0
- package/dist/web/assets/tsx-COt5Ahok.js +1 -0
- package/dist/web/assets/typescript-BPQ3VLAy.js +1 -0
- package/dist/web/assets/vue-DVfSmUF7.js +1 -0
- package/dist/web/assets/xml-sdJ4AIDG.js +1 -0
- package/dist/web/assets/yaml-Buea-lGh.js +1 -0
- package/dist/web/index.html +14 -0
- package/package.json +58 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4450 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// bin/cli.ts
|
|
4
|
+
import path7 from "path";
|
|
5
|
+
import { spawn } from "child_process";
|
|
6
|
+
import { existsSync } from "fs";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
|
|
9
|
+
// packages/server/src/index.ts
|
|
10
|
+
import net from "net";
|
|
11
|
+
|
|
12
|
+
// node_modules/.pnpm/@hono+node-server@1.19.17_hono@4.13.7/node_modules/@hono/node-server/dist/index.mjs
|
|
13
|
+
import { createServer as createServerHTTP } from "http";
|
|
14
|
+
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
15
|
+
import { Http2ServerRequest } from "http2";
|
|
16
|
+
import { Readable } from "stream";
|
|
17
|
+
import crypto2 from "crypto";
|
|
18
|
+
var RequestError = class extends Error {
|
|
19
|
+
constructor(message, options) {
|
|
20
|
+
super(message, options);
|
|
21
|
+
this.name = "RequestError";
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
var toRequestError = (e) => {
|
|
25
|
+
if (e instanceof RequestError) {
|
|
26
|
+
return e;
|
|
27
|
+
}
|
|
28
|
+
return new RequestError(e.message, { cause: e });
|
|
29
|
+
};
|
|
30
|
+
var GlobalRequest = global.Request;
|
|
31
|
+
var Request2 = class extends GlobalRequest {
|
|
32
|
+
constructor(input, options) {
|
|
33
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
34
|
+
input = input[getRequestCache]();
|
|
35
|
+
}
|
|
36
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
37
|
+
;
|
|
38
|
+
options.duplex ??= "half";
|
|
39
|
+
}
|
|
40
|
+
super(input, options);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
44
|
+
const headerRecord = [];
|
|
45
|
+
const rawHeaders = incoming.rawHeaders;
|
|
46
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
47
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
48
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
49
|
+
58) {
|
|
50
|
+
headerRecord.push([key, value]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return new Headers(headerRecord);
|
|
54
|
+
};
|
|
55
|
+
var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
|
|
56
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
57
|
+
const init = {
|
|
58
|
+
method,
|
|
59
|
+
headers,
|
|
60
|
+
signal: abortController.signal
|
|
61
|
+
};
|
|
62
|
+
if (method === "TRACE") {
|
|
63
|
+
init.method = "GET";
|
|
64
|
+
const req = new Request2(url, init);
|
|
65
|
+
Object.defineProperty(req, "method", {
|
|
66
|
+
get() {
|
|
67
|
+
return "TRACE";
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return req;
|
|
71
|
+
}
|
|
72
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
73
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
74
|
+
init.body = new ReadableStream({
|
|
75
|
+
start(controller) {
|
|
76
|
+
controller.enqueue(incoming.rawBody);
|
|
77
|
+
controller.close();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
} else if (incoming[wrapBodyStream]) {
|
|
81
|
+
let reader;
|
|
82
|
+
init.body = new ReadableStream({
|
|
83
|
+
async pull(controller) {
|
|
84
|
+
try {
|
|
85
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
86
|
+
const { done, value } = await reader.read();
|
|
87
|
+
if (done) {
|
|
88
|
+
controller.close();
|
|
89
|
+
} else {
|
|
90
|
+
controller.enqueue(value);
|
|
91
|
+
}
|
|
92
|
+
} catch (error) {
|
|
93
|
+
controller.error(error);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
} else {
|
|
98
|
+
init.body = Readable.toWeb(incoming);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return new Request2(url, init);
|
|
102
|
+
};
|
|
103
|
+
var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
|
|
104
|
+
var requestCache = /* @__PURE__ */ Symbol("requestCache");
|
|
105
|
+
var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
|
|
106
|
+
var urlKey = /* @__PURE__ */ Symbol("urlKey");
|
|
107
|
+
var headersKey = /* @__PURE__ */ Symbol("headersKey");
|
|
108
|
+
var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
|
|
109
|
+
var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
|
|
110
|
+
var requestPrototype = {
|
|
111
|
+
get method() {
|
|
112
|
+
return this[incomingKey].method || "GET";
|
|
113
|
+
},
|
|
114
|
+
get url() {
|
|
115
|
+
return this[urlKey];
|
|
116
|
+
},
|
|
117
|
+
get headers() {
|
|
118
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
119
|
+
},
|
|
120
|
+
[getAbortController]() {
|
|
121
|
+
this[getRequestCache]();
|
|
122
|
+
return this[abortControllerKey];
|
|
123
|
+
},
|
|
124
|
+
[getRequestCache]() {
|
|
125
|
+
this[abortControllerKey] ||= new AbortController();
|
|
126
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
127
|
+
this.method,
|
|
128
|
+
this[urlKey],
|
|
129
|
+
this.headers,
|
|
130
|
+
this[incomingKey],
|
|
131
|
+
this[abortControllerKey]
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
[
|
|
136
|
+
"body",
|
|
137
|
+
"bodyUsed",
|
|
138
|
+
"cache",
|
|
139
|
+
"credentials",
|
|
140
|
+
"destination",
|
|
141
|
+
"integrity",
|
|
142
|
+
"mode",
|
|
143
|
+
"redirect",
|
|
144
|
+
"referrer",
|
|
145
|
+
"referrerPolicy",
|
|
146
|
+
"signal",
|
|
147
|
+
"keepalive"
|
|
148
|
+
].forEach((k) => {
|
|
149
|
+
Object.defineProperty(requestPrototype, k, {
|
|
150
|
+
get() {
|
|
151
|
+
return this[getRequestCache]()[k];
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
156
|
+
Object.defineProperty(requestPrototype, k, {
|
|
157
|
+
value: function() {
|
|
158
|
+
return this[getRequestCache]()[k]();
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
163
|
+
value: function(depth, options, inspectFn) {
|
|
164
|
+
const props = {
|
|
165
|
+
method: this.method,
|
|
166
|
+
url: this.url,
|
|
167
|
+
headers: this.headers,
|
|
168
|
+
nativeRequest: this[requestCache]
|
|
169
|
+
};
|
|
170
|
+
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
Object.setPrototypeOf(requestPrototype, Request2.prototype);
|
|
174
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
175
|
+
const req = Object.create(requestPrototype);
|
|
176
|
+
req[incomingKey] = incoming;
|
|
177
|
+
const incomingUrl = incoming.url || "";
|
|
178
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
179
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
180
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
181
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
const url2 = new URL(incomingUrl);
|
|
185
|
+
req[urlKey] = url2.href;
|
|
186
|
+
} catch (e) {
|
|
187
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
188
|
+
}
|
|
189
|
+
return req;
|
|
190
|
+
}
|
|
191
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
192
|
+
if (!host) {
|
|
193
|
+
throw new RequestError("Missing host header");
|
|
194
|
+
}
|
|
195
|
+
let scheme;
|
|
196
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
197
|
+
scheme = incoming.scheme;
|
|
198
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
199
|
+
throw new RequestError("Unsupported scheme");
|
|
200
|
+
}
|
|
201
|
+
} else {
|
|
202
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
203
|
+
}
|
|
204
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
205
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
206
|
+
throw new RequestError("Invalid host header");
|
|
207
|
+
}
|
|
208
|
+
req[urlKey] = url.href;
|
|
209
|
+
return req;
|
|
210
|
+
};
|
|
211
|
+
var responseCache = /* @__PURE__ */ Symbol("responseCache");
|
|
212
|
+
var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
|
|
213
|
+
var cacheKey = /* @__PURE__ */ Symbol("cache");
|
|
214
|
+
var GlobalResponse = global.Response;
|
|
215
|
+
var Response2 = class _Response {
|
|
216
|
+
#body;
|
|
217
|
+
#init;
|
|
218
|
+
[getResponseCache]() {
|
|
219
|
+
delete this[cacheKey];
|
|
220
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
221
|
+
}
|
|
222
|
+
constructor(body, init) {
|
|
223
|
+
let headers;
|
|
224
|
+
this.#body = body;
|
|
225
|
+
if (init instanceof _Response) {
|
|
226
|
+
const cachedGlobalResponse = init[responseCache];
|
|
227
|
+
if (cachedGlobalResponse) {
|
|
228
|
+
this.#init = cachedGlobalResponse;
|
|
229
|
+
this[getResponseCache]();
|
|
230
|
+
return;
|
|
231
|
+
} else {
|
|
232
|
+
this.#init = init.#init;
|
|
233
|
+
headers = new Headers(init.#init.headers);
|
|
234
|
+
}
|
|
235
|
+
} else {
|
|
236
|
+
this.#init = init;
|
|
237
|
+
}
|
|
238
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
239
|
+
;
|
|
240
|
+
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
get headers() {
|
|
244
|
+
const cache = this[cacheKey];
|
|
245
|
+
if (cache) {
|
|
246
|
+
if (!(cache[2] instanceof Headers)) {
|
|
247
|
+
cache[2] = new Headers(
|
|
248
|
+
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return cache[2];
|
|
252
|
+
}
|
|
253
|
+
return this[getResponseCache]().headers;
|
|
254
|
+
}
|
|
255
|
+
get status() {
|
|
256
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
257
|
+
}
|
|
258
|
+
get ok() {
|
|
259
|
+
const status = this.status;
|
|
260
|
+
return status >= 200 && status < 300;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
264
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
265
|
+
get() {
|
|
266
|
+
return this[getResponseCache]()[k];
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
271
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
272
|
+
value: function() {
|
|
273
|
+
return this[getResponseCache]()[k]();
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
278
|
+
value: function(depth, options, inspectFn) {
|
|
279
|
+
const props = {
|
|
280
|
+
status: this.status,
|
|
281
|
+
headers: this.headers,
|
|
282
|
+
ok: this.ok,
|
|
283
|
+
nativeResponse: this[responseCache]
|
|
284
|
+
};
|
|
285
|
+
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
289
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
290
|
+
async function readWithoutBlocking(readPromise) {
|
|
291
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
292
|
+
}
|
|
293
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
294
|
+
const cancel = (error) => {
|
|
295
|
+
reader.cancel(error).catch(() => {
|
|
296
|
+
});
|
|
297
|
+
};
|
|
298
|
+
writable.on("close", cancel);
|
|
299
|
+
writable.on("error", cancel);
|
|
300
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
301
|
+
return reader.closed.finally(() => {
|
|
302
|
+
writable.off("close", cancel);
|
|
303
|
+
writable.off("error", cancel);
|
|
304
|
+
});
|
|
305
|
+
function handleStreamError(error) {
|
|
306
|
+
if (error) {
|
|
307
|
+
writable.destroy(error);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function onDrain() {
|
|
311
|
+
reader.read().then(flow, handleStreamError);
|
|
312
|
+
}
|
|
313
|
+
function flow({ done, value }) {
|
|
314
|
+
try {
|
|
315
|
+
if (done) {
|
|
316
|
+
writable.end();
|
|
317
|
+
} else if (!writable.write(value)) {
|
|
318
|
+
writable.once("drain", onDrain);
|
|
319
|
+
} else {
|
|
320
|
+
return reader.read().then(flow, handleStreamError);
|
|
321
|
+
}
|
|
322
|
+
} catch (e) {
|
|
323
|
+
handleStreamError(e);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function writeFromReadableStream(stream, writable) {
|
|
328
|
+
if (stream.locked) {
|
|
329
|
+
throw new TypeError("ReadableStream is locked.");
|
|
330
|
+
} else if (writable.destroyed) {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
334
|
+
}
|
|
335
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
336
|
+
const res = {};
|
|
337
|
+
if (!(headers instanceof Headers)) {
|
|
338
|
+
headers = new Headers(headers ?? void 0);
|
|
339
|
+
}
|
|
340
|
+
const cookies = [];
|
|
341
|
+
for (const [k, v] of headers) {
|
|
342
|
+
if (k === "set-cookie") {
|
|
343
|
+
cookies.push(v);
|
|
344
|
+
} else {
|
|
345
|
+
res[k] = v;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (cookies.length > 0) {
|
|
349
|
+
res["set-cookie"] = cookies;
|
|
350
|
+
}
|
|
351
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
352
|
+
return res;
|
|
353
|
+
};
|
|
354
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
355
|
+
if (typeof global.crypto === "undefined") {
|
|
356
|
+
global.crypto = crypto2;
|
|
357
|
+
}
|
|
358
|
+
var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
|
|
359
|
+
var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
|
|
360
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
361
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
362
|
+
var drainIncoming = (incoming) => {
|
|
363
|
+
const incomingWithDrainState = incoming;
|
|
364
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
368
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
369
|
+
try {
|
|
370
|
+
;
|
|
371
|
+
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
|
372
|
+
} catch {
|
|
373
|
+
}
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
let bytesRead = 0;
|
|
377
|
+
const cleanup = () => {
|
|
378
|
+
clearTimeout(timer);
|
|
379
|
+
incoming.off("data", onData);
|
|
380
|
+
incoming.off("end", cleanup);
|
|
381
|
+
incoming.off("error", cleanup);
|
|
382
|
+
};
|
|
383
|
+
const forceClose = () => {
|
|
384
|
+
cleanup();
|
|
385
|
+
const socket = incoming.socket;
|
|
386
|
+
if (socket && !socket.destroyed) {
|
|
387
|
+
socket.destroySoon();
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
391
|
+
timer.unref?.();
|
|
392
|
+
const onData = (chunk) => {
|
|
393
|
+
bytesRead += chunk.length;
|
|
394
|
+
if (bytesRead > MAX_DRAIN_BYTES) {
|
|
395
|
+
forceClose();
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
incoming.on("data", onData);
|
|
399
|
+
incoming.on("end", cleanup);
|
|
400
|
+
incoming.on("error", cleanup);
|
|
401
|
+
incoming.resume();
|
|
402
|
+
};
|
|
403
|
+
var handleRequestError = () => new Response(null, {
|
|
404
|
+
status: 400
|
|
405
|
+
});
|
|
406
|
+
var handleFetchError = (e) => new Response(null, {
|
|
407
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
408
|
+
});
|
|
409
|
+
var handleResponseError = (e, outgoing) => {
|
|
410
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
411
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
412
|
+
console.info("The user aborted a request.");
|
|
413
|
+
} else {
|
|
414
|
+
console.error(e);
|
|
415
|
+
if (!outgoing.headersSent) {
|
|
416
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
417
|
+
}
|
|
418
|
+
outgoing.end(`Error: ${err.message}`);
|
|
419
|
+
outgoing.destroy(err);
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
var flushHeaders = (outgoing) => {
|
|
423
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
424
|
+
outgoing.flushHeaders();
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
var responseViaCache = async (res, outgoing) => {
|
|
428
|
+
let [status, body, header] = res[cacheKey];
|
|
429
|
+
let hasContentLength = false;
|
|
430
|
+
if (!header) {
|
|
431
|
+
header = { "content-type": "text/plain; charset=UTF-8" };
|
|
432
|
+
} else if (header instanceof Headers) {
|
|
433
|
+
hasContentLength = header.has("content-length");
|
|
434
|
+
header = buildOutgoingHttpHeaders(header);
|
|
435
|
+
} else if (Array.isArray(header)) {
|
|
436
|
+
const headerObj = new Headers(header);
|
|
437
|
+
hasContentLength = headerObj.has("content-length");
|
|
438
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
439
|
+
} else {
|
|
440
|
+
for (const key in header) {
|
|
441
|
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
442
|
+
hasContentLength = true;
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (!hasContentLength) {
|
|
448
|
+
if (typeof body === "string") {
|
|
449
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
450
|
+
} else if (body instanceof Uint8Array) {
|
|
451
|
+
header["Content-Length"] = body.byteLength;
|
|
452
|
+
} else if (body instanceof Blob) {
|
|
453
|
+
header["Content-Length"] = body.size;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
outgoing.writeHead(status, header);
|
|
457
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
458
|
+
outgoing.end(body);
|
|
459
|
+
} else if (body instanceof Blob) {
|
|
460
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
461
|
+
} else {
|
|
462
|
+
flushHeaders(outgoing);
|
|
463
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
464
|
+
(e) => handleResponseError(e, outgoing)
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
;
|
|
468
|
+
outgoing[outgoingEnded]?.();
|
|
469
|
+
};
|
|
470
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
471
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
472
|
+
if (isPromise(res)) {
|
|
473
|
+
if (options.errorHandler) {
|
|
474
|
+
try {
|
|
475
|
+
res = await res;
|
|
476
|
+
} catch (err) {
|
|
477
|
+
const errRes = await options.errorHandler(err);
|
|
478
|
+
if (!errRes) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
res = errRes;
|
|
482
|
+
}
|
|
483
|
+
} else {
|
|
484
|
+
res = await res.catch(handleFetchError);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (cacheKey in res) {
|
|
488
|
+
return responseViaCache(res, outgoing);
|
|
489
|
+
}
|
|
490
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
491
|
+
if (res.body) {
|
|
492
|
+
const reader = res.body.getReader();
|
|
493
|
+
const values = [];
|
|
494
|
+
let done = false;
|
|
495
|
+
let currentReadPromise = void 0;
|
|
496
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
497
|
+
let maxReadCount = 2;
|
|
498
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
499
|
+
currentReadPromise ||= reader.read();
|
|
500
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
501
|
+
console.error(e);
|
|
502
|
+
done = true;
|
|
503
|
+
});
|
|
504
|
+
if (!chunk) {
|
|
505
|
+
if (i === 1) {
|
|
506
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
507
|
+
maxReadCount = 3;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
break;
|
|
511
|
+
}
|
|
512
|
+
currentReadPromise = void 0;
|
|
513
|
+
if (chunk.value) {
|
|
514
|
+
values.push(chunk.value);
|
|
515
|
+
}
|
|
516
|
+
if (chunk.done) {
|
|
517
|
+
done = true;
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
522
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
526
|
+
values.forEach((value) => {
|
|
527
|
+
;
|
|
528
|
+
outgoing.write(value);
|
|
529
|
+
});
|
|
530
|
+
if (done) {
|
|
531
|
+
outgoing.end();
|
|
532
|
+
} else {
|
|
533
|
+
if (values.length === 0) {
|
|
534
|
+
flushHeaders(outgoing);
|
|
535
|
+
}
|
|
536
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
537
|
+
}
|
|
538
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
539
|
+
} else {
|
|
540
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
541
|
+
outgoing.end();
|
|
542
|
+
}
|
|
543
|
+
;
|
|
544
|
+
outgoing[outgoingEnded]?.();
|
|
545
|
+
};
|
|
546
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
547
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
548
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
|
|
549
|
+
Object.defineProperty(global, "Request", {
|
|
550
|
+
value: Request2
|
|
551
|
+
});
|
|
552
|
+
Object.defineProperty(global, "Response", {
|
|
553
|
+
value: Response2
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
return async (incoming, outgoing) => {
|
|
557
|
+
let res, req;
|
|
558
|
+
try {
|
|
559
|
+
req = newRequest(incoming, options.hostname);
|
|
560
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
561
|
+
if (!incomingEnded) {
|
|
562
|
+
;
|
|
563
|
+
incoming[wrapBodyStream] = true;
|
|
564
|
+
incoming.on("end", () => {
|
|
565
|
+
incomingEnded = true;
|
|
566
|
+
});
|
|
567
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
568
|
+
;
|
|
569
|
+
outgoing[outgoingEnded] = () => {
|
|
570
|
+
if (!incomingEnded) {
|
|
571
|
+
setTimeout(() => {
|
|
572
|
+
if (!incomingEnded) {
|
|
573
|
+
setTimeout(() => {
|
|
574
|
+
drainIncoming(incoming);
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
outgoing.on("finish", () => {
|
|
582
|
+
if (!incomingEnded) {
|
|
583
|
+
drainIncoming(incoming);
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
outgoing.on("close", () => {
|
|
588
|
+
const abortController = req[abortControllerKey];
|
|
589
|
+
if (abortController) {
|
|
590
|
+
if (incoming.errored) {
|
|
591
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
592
|
+
} else if (!outgoing.writableFinished) {
|
|
593
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
if (!incomingEnded) {
|
|
597
|
+
setTimeout(() => {
|
|
598
|
+
if (!incomingEnded) {
|
|
599
|
+
setTimeout(() => {
|
|
600
|
+
drainIncoming(incoming);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
607
|
+
if (cacheKey in res) {
|
|
608
|
+
return responseViaCache(res, outgoing);
|
|
609
|
+
}
|
|
610
|
+
} catch (e) {
|
|
611
|
+
if (!res) {
|
|
612
|
+
if (options.errorHandler) {
|
|
613
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
614
|
+
if (!res) {
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
} else if (!req) {
|
|
618
|
+
res = handleRequestError();
|
|
619
|
+
} else {
|
|
620
|
+
res = handleFetchError(e);
|
|
621
|
+
}
|
|
622
|
+
} else {
|
|
623
|
+
return handleResponseError(e, outgoing);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
try {
|
|
627
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
628
|
+
} catch (e) {
|
|
629
|
+
return handleResponseError(e, outgoing);
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
};
|
|
633
|
+
var createAdaptorServer = (options) => {
|
|
634
|
+
const fetchCallback = options.fetch;
|
|
635
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
636
|
+
hostname: options.hostname,
|
|
637
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
638
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
639
|
+
});
|
|
640
|
+
const createServer = options.createServer || createServerHTTP;
|
|
641
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
642
|
+
return server;
|
|
643
|
+
};
|
|
644
|
+
var serve = (options, listeningListener) => {
|
|
645
|
+
const server = createAdaptorServer(options);
|
|
646
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
647
|
+
const serverInfo = server.address();
|
|
648
|
+
listeningListener && listeningListener(serverInfo);
|
|
649
|
+
});
|
|
650
|
+
return server;
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
// packages/server/src/app.ts
|
|
654
|
+
import path6 from "path";
|
|
655
|
+
import { randomUUID } from "crypto";
|
|
656
|
+
|
|
657
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/compose.js
|
|
658
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
659
|
+
return (context, next) => {
|
|
660
|
+
let index = -1;
|
|
661
|
+
return dispatch(0);
|
|
662
|
+
async function dispatch(i) {
|
|
663
|
+
if (i <= index) {
|
|
664
|
+
throw new Error("next() called multiple times");
|
|
665
|
+
}
|
|
666
|
+
index = i;
|
|
667
|
+
let res;
|
|
668
|
+
let isError = false;
|
|
669
|
+
let handler;
|
|
670
|
+
if (middleware[i]) {
|
|
671
|
+
handler = middleware[i][0][0];
|
|
672
|
+
context.req.routeIndex = i;
|
|
673
|
+
} else {
|
|
674
|
+
handler = i === middleware.length && next || void 0;
|
|
675
|
+
}
|
|
676
|
+
if (handler) {
|
|
677
|
+
try {
|
|
678
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
679
|
+
} catch (err) {
|
|
680
|
+
if (err instanceof Error && onError) {
|
|
681
|
+
context.error = err;
|
|
682
|
+
res = await onError(err, context);
|
|
683
|
+
isError = true;
|
|
684
|
+
} else {
|
|
685
|
+
throw err;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
} else {
|
|
689
|
+
if (context.finalized === false && onNotFound) {
|
|
690
|
+
res = await onNotFound(context);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (res && (context.finalized === false || isError)) {
|
|
694
|
+
context.res = res;
|
|
695
|
+
}
|
|
696
|
+
return context;
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/request/constants.js
|
|
702
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
703
|
+
|
|
704
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/utils/buffer.js
|
|
705
|
+
var bufferToFormData = (arrayBuffer, contentType) => {
|
|
706
|
+
const response = new Response(arrayBuffer, {
|
|
707
|
+
headers: {
|
|
708
|
+
// Normalize the media type (case-insensitive) while keeping parameters like the boundary
|
|
709
|
+
"Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
return response.formData();
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/utils/body.js
|
|
716
|
+
var MAX_NESTING_DEPTH = 32;
|
|
717
|
+
var MAX_NESTED_OBJECTS = 1e4;
|
|
718
|
+
var isRawRequest = (request) => "headers" in request;
|
|
719
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
720
|
+
const { all = false, dot = false } = options;
|
|
721
|
+
const headers = isRawRequest(request) ? request.headers : request.raw.headers;
|
|
722
|
+
const contentType = headers.get("Content-Type");
|
|
723
|
+
const mediaType = contentType?.split(";")[0].trim().toLowerCase();
|
|
724
|
+
if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") {
|
|
725
|
+
return parseFormData(request, { all, dot });
|
|
726
|
+
}
|
|
727
|
+
return {};
|
|
728
|
+
};
|
|
729
|
+
async function parseFormData(request, options) {
|
|
730
|
+
if (!isRawRequest(request) && request.bodyCache.formData) {
|
|
731
|
+
return convertFormDataToBodyData(
|
|
732
|
+
await request.bodyCache.formData,
|
|
733
|
+
options
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
const headers = isRawRequest(request) ? request.headers : request.raw.headers;
|
|
737
|
+
const arrayBuffer = await request.arrayBuffer();
|
|
738
|
+
const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
|
|
739
|
+
if (!isRawRequest(request)) {
|
|
740
|
+
request.bodyCache.formData = formDataPromise;
|
|
741
|
+
}
|
|
742
|
+
const formData = await formDataPromise;
|
|
743
|
+
if (formData) {
|
|
744
|
+
return convertFormDataToBodyData(formData, options);
|
|
745
|
+
}
|
|
746
|
+
return {};
|
|
747
|
+
}
|
|
748
|
+
function convertFormDataToBodyData(formData, options) {
|
|
749
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
750
|
+
const nestingState = { count: 0 };
|
|
751
|
+
formData.forEach((value, key) => {
|
|
752
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
753
|
+
if (!shouldParseAllValues) {
|
|
754
|
+
form[key] = value;
|
|
755
|
+
} else {
|
|
756
|
+
handleParsingAllValues(form, key, value);
|
|
757
|
+
}
|
|
758
|
+
});
|
|
759
|
+
if (options.dot) {
|
|
760
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
761
|
+
const shouldParseDotValues = key.includes(".");
|
|
762
|
+
if (shouldParseDotValues) {
|
|
763
|
+
handleParsingNestedValues(form, key, value, nestingState);
|
|
764
|
+
delete form[key];
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
return form;
|
|
769
|
+
}
|
|
770
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
771
|
+
if (form[key] !== void 0) {
|
|
772
|
+
if (Array.isArray(form[key])) {
|
|
773
|
+
;
|
|
774
|
+
form[key].push(value);
|
|
775
|
+
} else {
|
|
776
|
+
form[key] = [form[key], value];
|
|
777
|
+
}
|
|
778
|
+
} else {
|
|
779
|
+
if (!key.endsWith("[]")) {
|
|
780
|
+
form[key] = value;
|
|
781
|
+
} else {
|
|
782
|
+
form[key] = [value];
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
var handleParsingNestedValues = (form, key, value, state) => {
|
|
787
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
let nestedForm = form;
|
|
791
|
+
const keys = key.split(".", MAX_NESTING_DEPTH + 2);
|
|
792
|
+
if (keys.length > MAX_NESTING_DEPTH + 1) {
|
|
793
|
+
throwNestingLimitExceeded();
|
|
794
|
+
}
|
|
795
|
+
keys.forEach((key2, index) => {
|
|
796
|
+
if (index === keys.length - 1) {
|
|
797
|
+
nestedForm[key2] = value;
|
|
798
|
+
} else {
|
|
799
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
800
|
+
if (state.count++ >= MAX_NESTED_OBJECTS) {
|
|
801
|
+
throwNestingLimitExceeded();
|
|
802
|
+
}
|
|
803
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
804
|
+
}
|
|
805
|
+
nestedForm = nestedForm[key2];
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
};
|
|
809
|
+
var throwNestingLimitExceeded = () => {
|
|
810
|
+
throw new Error("Nesting limit exceeded");
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/utils/url.js
|
|
814
|
+
var splitPath = (path8) => {
|
|
815
|
+
const paths = path8.split("/");
|
|
816
|
+
if (paths[0] === "") {
|
|
817
|
+
paths.shift();
|
|
818
|
+
}
|
|
819
|
+
return paths;
|
|
820
|
+
};
|
|
821
|
+
var splitRoutingPath = (routePath) => {
|
|
822
|
+
const { groups, path: path8 } = extractGroupsFromPath(routePath);
|
|
823
|
+
const paths = splitPath(path8);
|
|
824
|
+
return replaceGroupMarks(paths, groups);
|
|
825
|
+
};
|
|
826
|
+
var extractGroupsFromPath = (path8) => {
|
|
827
|
+
const groups = [];
|
|
828
|
+
path8 = path8.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
829
|
+
const mark = `@${index}`;
|
|
830
|
+
groups.push([mark, match2]);
|
|
831
|
+
return mark;
|
|
832
|
+
});
|
|
833
|
+
return { groups, path: path8 };
|
|
834
|
+
};
|
|
835
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
836
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
837
|
+
const [mark] = groups[i];
|
|
838
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
839
|
+
if (paths[j].includes(mark)) {
|
|
840
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
841
|
+
break;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
return paths;
|
|
846
|
+
};
|
|
847
|
+
var patternCache = {};
|
|
848
|
+
var getPattern = (label, next) => {
|
|
849
|
+
if (label === "*") {
|
|
850
|
+
return "*";
|
|
851
|
+
}
|
|
852
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
853
|
+
if (match2) {
|
|
854
|
+
const cacheKey2 = `${label}#${next}`;
|
|
855
|
+
if (!patternCache[cacheKey2]) {
|
|
856
|
+
if (match2[2]) {
|
|
857
|
+
patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
858
|
+
} else {
|
|
859
|
+
patternCache[cacheKey2] = [label, match2[1], true];
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
return patternCache[cacheKey2];
|
|
863
|
+
}
|
|
864
|
+
return null;
|
|
865
|
+
};
|
|
866
|
+
var tryDecode = (str, decoder) => {
|
|
867
|
+
try {
|
|
868
|
+
return decoder(str);
|
|
869
|
+
} catch {
|
|
870
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
871
|
+
try {
|
|
872
|
+
return decoder(match2);
|
|
873
|
+
} catch {
|
|
874
|
+
return match2;
|
|
875
|
+
}
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
880
|
+
var getPath = (request) => {
|
|
881
|
+
const url = request.url;
|
|
882
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
883
|
+
let i = start;
|
|
884
|
+
for (; i < url.length; i++) {
|
|
885
|
+
const charCode = url.charCodeAt(i);
|
|
886
|
+
if (charCode === 37) {
|
|
887
|
+
const queryIndex = url.indexOf("?", i);
|
|
888
|
+
const hashIndex = url.indexOf("#", i);
|
|
889
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
890
|
+
const path8 = url.slice(start, end);
|
|
891
|
+
return tryDecodeURI(path8.includes("%25") ? path8.replace(/%25/g, "%2525") : path8);
|
|
892
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return url.slice(start, i);
|
|
897
|
+
};
|
|
898
|
+
var getPathNoStrict = (request) => {
|
|
899
|
+
const result = getPath(request);
|
|
900
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
901
|
+
};
|
|
902
|
+
var mergePath = (base, sub, ...rest) => {
|
|
903
|
+
if (rest.length) {
|
|
904
|
+
sub = mergePath(sub, ...rest);
|
|
905
|
+
}
|
|
906
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
907
|
+
};
|
|
908
|
+
var checkOptionalParameter = (path8) => {
|
|
909
|
+
if (path8.charCodeAt(path8.length - 1) !== 63 || !path8.includes(":")) {
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
const segments = path8.split("/");
|
|
913
|
+
const results = [];
|
|
914
|
+
let basePath = "";
|
|
915
|
+
segments.forEach((segment) => {
|
|
916
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
917
|
+
basePath += "/" + segment;
|
|
918
|
+
} else if (/\:/.test(segment)) {
|
|
919
|
+
if (segment.charCodeAt(segment.length - 1) === 63) {
|
|
920
|
+
if (results.length === 0 && basePath === "") {
|
|
921
|
+
results.push("/");
|
|
922
|
+
} else {
|
|
923
|
+
results.push(basePath);
|
|
924
|
+
}
|
|
925
|
+
const optionalSegment = segment.slice(0, -1);
|
|
926
|
+
basePath += "/" + optionalSegment;
|
|
927
|
+
results.push(basePath);
|
|
928
|
+
} else {
|
|
929
|
+
basePath += "/" + segment;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
});
|
|
933
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
934
|
+
};
|
|
935
|
+
var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
|
|
936
|
+
var _decodeURI = (value) => {
|
|
937
|
+
if (value.indexOf("+") !== -1) {
|
|
938
|
+
value = value.replace(/\+/g, " ");
|
|
939
|
+
}
|
|
940
|
+
return tryDecodeURIComponent(value);
|
|
941
|
+
};
|
|
942
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
943
|
+
const hashIndex = url.indexOf("#", 8);
|
|
944
|
+
if (hashIndex !== -1) {
|
|
945
|
+
url = url.slice(0, hashIndex);
|
|
946
|
+
}
|
|
947
|
+
let encoded;
|
|
948
|
+
if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
|
|
949
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
950
|
+
if (keyIndex2 === -1) {
|
|
951
|
+
return void 0;
|
|
952
|
+
}
|
|
953
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
954
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
955
|
+
}
|
|
956
|
+
while (keyIndex2 !== -1) {
|
|
957
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
958
|
+
if (trailingKeyCode === 61) {
|
|
959
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
960
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
961
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
962
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
963
|
+
return "";
|
|
964
|
+
}
|
|
965
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
966
|
+
}
|
|
967
|
+
encoded = /[%+]/.test(url);
|
|
968
|
+
if (!encoded) {
|
|
969
|
+
return void 0;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
const results = /* @__PURE__ */ Object.create(null);
|
|
973
|
+
encoded ??= /[%+]/.test(url);
|
|
974
|
+
let keyIndex = url.indexOf("?", 8);
|
|
975
|
+
while (keyIndex !== -1) {
|
|
976
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
977
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
978
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
979
|
+
valueIndex = -1;
|
|
980
|
+
}
|
|
981
|
+
let name = url.slice(
|
|
982
|
+
keyIndex + 1,
|
|
983
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
984
|
+
);
|
|
985
|
+
if (encoded) {
|
|
986
|
+
name = _decodeURI(name);
|
|
987
|
+
}
|
|
988
|
+
keyIndex = nextKeyIndex;
|
|
989
|
+
if (name === "") {
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
let value;
|
|
993
|
+
if (valueIndex === -1) {
|
|
994
|
+
value = "";
|
|
995
|
+
} else {
|
|
996
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
997
|
+
if (encoded) {
|
|
998
|
+
value = _decodeURI(value);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
if (multiple) {
|
|
1002
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1003
|
+
results[name] = [];
|
|
1004
|
+
}
|
|
1005
|
+
;
|
|
1006
|
+
results[name].push(value);
|
|
1007
|
+
} else {
|
|
1008
|
+
results[name] ??= value;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
return key ? results[key] : results;
|
|
1012
|
+
};
|
|
1013
|
+
var getQueryParam = _getQueryParam;
|
|
1014
|
+
var getQueryParams = (url, key) => {
|
|
1015
|
+
return _getQueryParam(url, key, true);
|
|
1016
|
+
};
|
|
1017
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1018
|
+
|
|
1019
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/request.js
|
|
1020
|
+
var HonoRequest = class {
|
|
1021
|
+
/**
|
|
1022
|
+
* `.raw` can get the raw Request object.
|
|
1023
|
+
*
|
|
1024
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1025
|
+
*
|
|
1026
|
+
* @example
|
|
1027
|
+
* ```ts
|
|
1028
|
+
* // For Cloudflare Workers
|
|
1029
|
+
* app.post('/', async (c) => {
|
|
1030
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1031
|
+
* ...
|
|
1032
|
+
* })
|
|
1033
|
+
* ```
|
|
1034
|
+
*/
|
|
1035
|
+
raw;
|
|
1036
|
+
#validatedData;
|
|
1037
|
+
// Short name of validatedData
|
|
1038
|
+
#matchResult;
|
|
1039
|
+
routeIndex = 0;
|
|
1040
|
+
/**
|
|
1041
|
+
* `.path` can get the pathname of the request.
|
|
1042
|
+
*
|
|
1043
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1044
|
+
*
|
|
1045
|
+
* @example
|
|
1046
|
+
* ```ts
|
|
1047
|
+
* app.get('/about/me', (c) => {
|
|
1048
|
+
* const pathname = c.req.path // `/about/me`
|
|
1049
|
+
* })
|
|
1050
|
+
* ```
|
|
1051
|
+
*/
|
|
1052
|
+
path;
|
|
1053
|
+
bodyCache = {};
|
|
1054
|
+
constructor(request, path8 = "/", matchResult = [[]]) {
|
|
1055
|
+
this.raw = request;
|
|
1056
|
+
this.path = path8;
|
|
1057
|
+
this.#matchResult = matchResult;
|
|
1058
|
+
}
|
|
1059
|
+
param(key) {
|
|
1060
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1061
|
+
}
|
|
1062
|
+
#getDecodedParam(key) {
|
|
1063
|
+
const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
|
|
1064
|
+
const param = this.#getParamValue(paramKey);
|
|
1065
|
+
return param && tryDecodeURIComponent(param);
|
|
1066
|
+
}
|
|
1067
|
+
#getAllDecodedParams() {
|
|
1068
|
+
const decoded = {};
|
|
1069
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
|
|
1070
|
+
for (const key of keys) {
|
|
1071
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1072
|
+
if (value !== void 0) {
|
|
1073
|
+
decoded[key] = tryDecodeURIComponent(value);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
return decoded;
|
|
1077
|
+
}
|
|
1078
|
+
#getParamValue(paramKey) {
|
|
1079
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1080
|
+
}
|
|
1081
|
+
query(key) {
|
|
1082
|
+
return getQueryParam(this.url, key);
|
|
1083
|
+
}
|
|
1084
|
+
queries(key) {
|
|
1085
|
+
return getQueryParams(this.url, key);
|
|
1086
|
+
}
|
|
1087
|
+
header(name) {
|
|
1088
|
+
if (name) {
|
|
1089
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1090
|
+
}
|
|
1091
|
+
const headerData = /* @__PURE__ */ Object.create(null);
|
|
1092
|
+
this.raw.headers.forEach((value, key) => {
|
|
1093
|
+
headerData[key] = value;
|
|
1094
|
+
});
|
|
1095
|
+
return headerData;
|
|
1096
|
+
}
|
|
1097
|
+
async parseBody(options) {
|
|
1098
|
+
return parseBody(this, options);
|
|
1099
|
+
}
|
|
1100
|
+
#cachedBody = (key) => {
|
|
1101
|
+
const { bodyCache, raw: raw2 } = this;
|
|
1102
|
+
const cachedBody = bodyCache[key];
|
|
1103
|
+
if (cachedBody) {
|
|
1104
|
+
return cachedBody;
|
|
1105
|
+
}
|
|
1106
|
+
for (const anyCachedKey in bodyCache) {
|
|
1107
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1108
|
+
if (anyCachedKey === "json") {
|
|
1109
|
+
body = JSON.stringify(body);
|
|
1110
|
+
}
|
|
1111
|
+
return new Response(body)[key]();
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
return bodyCache[key] = raw2[key]();
|
|
1115
|
+
};
|
|
1116
|
+
/**
|
|
1117
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1118
|
+
*
|
|
1119
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1120
|
+
*
|
|
1121
|
+
* @example
|
|
1122
|
+
* ```ts
|
|
1123
|
+
* app.post('/entry', async (c) => {
|
|
1124
|
+
* const body = await c.req.json()
|
|
1125
|
+
* })
|
|
1126
|
+
* ```
|
|
1127
|
+
*/
|
|
1128
|
+
json() {
|
|
1129
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1133
|
+
*
|
|
1134
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1135
|
+
*
|
|
1136
|
+
* @example
|
|
1137
|
+
* ```ts
|
|
1138
|
+
* app.post('/entry', async (c) => {
|
|
1139
|
+
* const body = await c.req.text()
|
|
1140
|
+
* })
|
|
1141
|
+
* ```
|
|
1142
|
+
*/
|
|
1143
|
+
text() {
|
|
1144
|
+
return this.#cachedBody("text");
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1148
|
+
*
|
|
1149
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1150
|
+
*
|
|
1151
|
+
* @example
|
|
1152
|
+
* ```ts
|
|
1153
|
+
* app.post('/entry', async (c) => {
|
|
1154
|
+
* const body = await c.req.arrayBuffer()
|
|
1155
|
+
* })
|
|
1156
|
+
* ```
|
|
1157
|
+
*/
|
|
1158
|
+
arrayBuffer() {
|
|
1159
|
+
return this.#cachedBody("arrayBuffer");
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
1163
|
+
*
|
|
1164
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
1165
|
+
*
|
|
1166
|
+
* @example
|
|
1167
|
+
* ```ts
|
|
1168
|
+
* app.post('/entry', async (c) => {
|
|
1169
|
+
* const body = await c.req.bytes()
|
|
1170
|
+
* })
|
|
1171
|
+
* ```
|
|
1172
|
+
*/
|
|
1173
|
+
bytes() {
|
|
1174
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Parses the request body as a `Blob`.
|
|
1178
|
+
* @example
|
|
1179
|
+
* ```ts
|
|
1180
|
+
* app.post('/entry', async (c) => {
|
|
1181
|
+
* const body = await c.req.blob();
|
|
1182
|
+
* });
|
|
1183
|
+
* ```
|
|
1184
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
1185
|
+
*/
|
|
1186
|
+
blob() {
|
|
1187
|
+
return this.#cachedBody("blob");
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* Parses the request body as `FormData`.
|
|
1191
|
+
* @example
|
|
1192
|
+
* ```ts
|
|
1193
|
+
* app.post('/entry', async (c) => {
|
|
1194
|
+
* const body = await c.req.formData();
|
|
1195
|
+
* });
|
|
1196
|
+
* ```
|
|
1197
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
1198
|
+
*/
|
|
1199
|
+
formData() {
|
|
1200
|
+
return this.#cachedBody("formData");
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Adds validated data to the request.
|
|
1204
|
+
*
|
|
1205
|
+
* @param target - The target of the validation.
|
|
1206
|
+
* @param data - The validated data to add.
|
|
1207
|
+
*/
|
|
1208
|
+
addValidatedData(target, data) {
|
|
1209
|
+
;
|
|
1210
|
+
(this.#validatedData ??= {})[target] = data;
|
|
1211
|
+
}
|
|
1212
|
+
valid(target) {
|
|
1213
|
+
return this.#validatedData?.[target];
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* `.url()` can get the request url strings.
|
|
1217
|
+
*
|
|
1218
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
1219
|
+
*
|
|
1220
|
+
* @example
|
|
1221
|
+
* ```ts
|
|
1222
|
+
* app.get('/about/me', (c) => {
|
|
1223
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
1224
|
+
* ...
|
|
1225
|
+
* })
|
|
1226
|
+
* ```
|
|
1227
|
+
*/
|
|
1228
|
+
get url() {
|
|
1229
|
+
return this.raw.url;
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* `.method()` can get the method name of the request.
|
|
1233
|
+
*
|
|
1234
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
1235
|
+
*
|
|
1236
|
+
* @example
|
|
1237
|
+
* ```ts
|
|
1238
|
+
* app.get('/about/me', (c) => {
|
|
1239
|
+
* const method = c.req.method // `GET`
|
|
1240
|
+
* })
|
|
1241
|
+
* ```
|
|
1242
|
+
*/
|
|
1243
|
+
get method() {
|
|
1244
|
+
return this.raw.method;
|
|
1245
|
+
}
|
|
1246
|
+
get [GET_MATCH_RESULT]() {
|
|
1247
|
+
return this.#matchResult;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
1251
|
+
*
|
|
1252
|
+
* @deprecated
|
|
1253
|
+
*
|
|
1254
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
1255
|
+
*
|
|
1256
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
1257
|
+
*
|
|
1258
|
+
* @example
|
|
1259
|
+
* ```ts
|
|
1260
|
+
* app.use('*', async function logger(c, next) {
|
|
1261
|
+
* await next()
|
|
1262
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
1263
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
1264
|
+
* console.log(
|
|
1265
|
+
* method,
|
|
1266
|
+
* ' ',
|
|
1267
|
+
* path,
|
|
1268
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
1269
|
+
* name,
|
|
1270
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
1271
|
+
* )
|
|
1272
|
+
* })
|
|
1273
|
+
* })
|
|
1274
|
+
* ```
|
|
1275
|
+
*/
|
|
1276
|
+
get matchedRoutes() {
|
|
1277
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
1281
|
+
*
|
|
1282
|
+
* @deprecated
|
|
1283
|
+
*
|
|
1284
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
1285
|
+
*
|
|
1286
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
1287
|
+
*
|
|
1288
|
+
* @example
|
|
1289
|
+
* ```ts
|
|
1290
|
+
* app.get('/posts/:id', (c) => {
|
|
1291
|
+
* return c.json({ path: c.req.routePath })
|
|
1292
|
+
* })
|
|
1293
|
+
* ```
|
|
1294
|
+
*/
|
|
1295
|
+
get routePath() {
|
|
1296
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
|
|
1300
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/utils/html.js
|
|
1301
|
+
var HtmlEscapedCallbackPhase = {
|
|
1302
|
+
Stringify: 1,
|
|
1303
|
+
BeforeStream: 2,
|
|
1304
|
+
Stream: 3
|
|
1305
|
+
};
|
|
1306
|
+
var raw = (value, callbacks) => {
|
|
1307
|
+
const escapedString = new String(value);
|
|
1308
|
+
escapedString.isEscaped = true;
|
|
1309
|
+
escapedString.callbacks = callbacks;
|
|
1310
|
+
return escapedString;
|
|
1311
|
+
};
|
|
1312
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1313
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1314
|
+
if (!(str instanceof Promise)) {
|
|
1315
|
+
str = str.toString();
|
|
1316
|
+
}
|
|
1317
|
+
if (str instanceof Promise) {
|
|
1318
|
+
str = await str;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
const callbacks = str.callbacks;
|
|
1322
|
+
if (!callbacks?.length) {
|
|
1323
|
+
return Promise.resolve(str);
|
|
1324
|
+
}
|
|
1325
|
+
if (buffer) {
|
|
1326
|
+
buffer[0] += str;
|
|
1327
|
+
} else {
|
|
1328
|
+
buffer = [str];
|
|
1329
|
+
}
|
|
1330
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
1331
|
+
(res) => Promise.all(
|
|
1332
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
1333
|
+
).then(() => buffer[0])
|
|
1334
|
+
);
|
|
1335
|
+
if (preserveCallbacks) {
|
|
1336
|
+
return raw(await resStr, callbacks);
|
|
1337
|
+
} else {
|
|
1338
|
+
return resStr;
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
|
|
1342
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/context.js
|
|
1343
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1344
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1345
|
+
return {
|
|
1346
|
+
"Content-Type": contentType,
|
|
1347
|
+
...headers
|
|
1348
|
+
};
|
|
1349
|
+
};
|
|
1350
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
1351
|
+
var Context = class {
|
|
1352
|
+
#rawRequest;
|
|
1353
|
+
#req;
|
|
1354
|
+
/**
|
|
1355
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
1356
|
+
*
|
|
1357
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
1358
|
+
*
|
|
1359
|
+
* @example
|
|
1360
|
+
* ```ts
|
|
1361
|
+
* // Environment object for Cloudflare Workers
|
|
1362
|
+
* app.get('*', async c => {
|
|
1363
|
+
* const counter = c.env.COUNTER
|
|
1364
|
+
* })
|
|
1365
|
+
* ```
|
|
1366
|
+
*/
|
|
1367
|
+
env = {};
|
|
1368
|
+
#var;
|
|
1369
|
+
finalized = false;
|
|
1370
|
+
/**
|
|
1371
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
1372
|
+
*
|
|
1373
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
1374
|
+
*
|
|
1375
|
+
* @example
|
|
1376
|
+
* ```ts
|
|
1377
|
+
* app.use('*', async (c, next) => {
|
|
1378
|
+
* await next()
|
|
1379
|
+
* if (c.error) {
|
|
1380
|
+
* // do something...
|
|
1381
|
+
* }
|
|
1382
|
+
* })
|
|
1383
|
+
* ```
|
|
1384
|
+
*/
|
|
1385
|
+
error;
|
|
1386
|
+
#status;
|
|
1387
|
+
#executionCtx;
|
|
1388
|
+
#res;
|
|
1389
|
+
#layout;
|
|
1390
|
+
#renderer;
|
|
1391
|
+
#notFoundHandler;
|
|
1392
|
+
#preparedHeaders;
|
|
1393
|
+
#matchResult;
|
|
1394
|
+
#path;
|
|
1395
|
+
/**
|
|
1396
|
+
* Creates an instance of the Context class.
|
|
1397
|
+
*
|
|
1398
|
+
* @param req - The Request object.
|
|
1399
|
+
* @param options - Optional configuration options for the context.
|
|
1400
|
+
*/
|
|
1401
|
+
constructor(req, options) {
|
|
1402
|
+
this.#rawRequest = req;
|
|
1403
|
+
if (options) {
|
|
1404
|
+
this.#executionCtx = options.executionCtx;
|
|
1405
|
+
this.env = options.env;
|
|
1406
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1407
|
+
this.#path = options.path;
|
|
1408
|
+
this.#matchResult = options.matchResult;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
1413
|
+
*/
|
|
1414
|
+
get req() {
|
|
1415
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1416
|
+
return this.#req;
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
1420
|
+
* The FetchEvent associated with the current request.
|
|
1421
|
+
*
|
|
1422
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
1423
|
+
*/
|
|
1424
|
+
get event() {
|
|
1425
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1426
|
+
return this.#executionCtx;
|
|
1427
|
+
} else {
|
|
1428
|
+
throw Error("This context has no FetchEvent");
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
1433
|
+
* The ExecutionContext associated with the current request.
|
|
1434
|
+
*
|
|
1435
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
1436
|
+
*/
|
|
1437
|
+
get executionCtx() {
|
|
1438
|
+
if (this.#executionCtx) {
|
|
1439
|
+
return this.#executionCtx;
|
|
1440
|
+
} else {
|
|
1441
|
+
throw Error("This context has no ExecutionContext");
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
1446
|
+
* The Response object for the current request.
|
|
1447
|
+
*/
|
|
1448
|
+
get res() {
|
|
1449
|
+
return this.#res ||= createResponseInstance(null, {
|
|
1450
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* Sets the Response object for the current request.
|
|
1455
|
+
*
|
|
1456
|
+
* @param _res - The Response object to set.
|
|
1457
|
+
*/
|
|
1458
|
+
set res(_res) {
|
|
1459
|
+
if (this.#res && _res) {
|
|
1460
|
+
_res = createResponseInstance(_res.body, _res);
|
|
1461
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1462
|
+
if (k === "content-type") {
|
|
1463
|
+
continue;
|
|
1464
|
+
}
|
|
1465
|
+
if (k === "set-cookie") {
|
|
1466
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1467
|
+
_res.headers.delete("set-cookie");
|
|
1468
|
+
for (const cookie of cookies) {
|
|
1469
|
+
_res.headers.append("set-cookie", cookie);
|
|
1470
|
+
}
|
|
1471
|
+
} else {
|
|
1472
|
+
_res.headers.set(k, v);
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
this.#res = _res;
|
|
1477
|
+
this.finalized = true;
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* `.render()` can create a response within a layout.
|
|
1481
|
+
*
|
|
1482
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1483
|
+
*
|
|
1484
|
+
* @example
|
|
1485
|
+
* ```ts
|
|
1486
|
+
* app.get('/', (c) => {
|
|
1487
|
+
* return c.render('Hello!')
|
|
1488
|
+
* })
|
|
1489
|
+
* ```
|
|
1490
|
+
*/
|
|
1491
|
+
render = (...args) => {
|
|
1492
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1493
|
+
return this.#renderer(...args);
|
|
1494
|
+
};
|
|
1495
|
+
/**
|
|
1496
|
+
* Sets the layout for the response.
|
|
1497
|
+
*
|
|
1498
|
+
* @param layout - The layout to set.
|
|
1499
|
+
* @returns The layout function.
|
|
1500
|
+
*/
|
|
1501
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1502
|
+
/**
|
|
1503
|
+
* Gets the current layout for the response.
|
|
1504
|
+
*
|
|
1505
|
+
* @returns The current layout function.
|
|
1506
|
+
*/
|
|
1507
|
+
getLayout = () => this.#layout;
|
|
1508
|
+
/**
|
|
1509
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
1510
|
+
*
|
|
1511
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1512
|
+
*
|
|
1513
|
+
* @example
|
|
1514
|
+
* ```tsx
|
|
1515
|
+
* app.use('*', async (c, next) => {
|
|
1516
|
+
* c.setRenderer((content) => {
|
|
1517
|
+
* return c.html(
|
|
1518
|
+
* <html>
|
|
1519
|
+
* <body>
|
|
1520
|
+
* <p>{content}</p>
|
|
1521
|
+
* </body>
|
|
1522
|
+
* </html>
|
|
1523
|
+
* )
|
|
1524
|
+
* })
|
|
1525
|
+
* await next()
|
|
1526
|
+
* })
|
|
1527
|
+
* ```
|
|
1528
|
+
*/
|
|
1529
|
+
setRenderer = (renderer) => {
|
|
1530
|
+
this.#renderer = renderer;
|
|
1531
|
+
};
|
|
1532
|
+
/**
|
|
1533
|
+
* `.header()` can set headers.
|
|
1534
|
+
*
|
|
1535
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
1536
|
+
*
|
|
1537
|
+
* @example
|
|
1538
|
+
* ```ts
|
|
1539
|
+
* app.get('/welcome', (c) => {
|
|
1540
|
+
* // Set headers
|
|
1541
|
+
* c.header('X-Message', 'Hello!')
|
|
1542
|
+
* c.header('Content-Type', 'text/plain')
|
|
1543
|
+
*
|
|
1544
|
+
* // Append multiple headers using the append option (e.g. Vary)
|
|
1545
|
+
* c.header('Vary', 'Accept-Encoding', { append: true })
|
|
1546
|
+
* c.header('Vary', 'User-Agent', { append: true })
|
|
1547
|
+
*
|
|
1548
|
+
* return c.body('Thank you for coming')
|
|
1549
|
+
* })
|
|
1550
|
+
* ```
|
|
1551
|
+
*/
|
|
1552
|
+
header = (name, value, options) => {
|
|
1553
|
+
if (this.finalized) {
|
|
1554
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
1555
|
+
}
|
|
1556
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
1557
|
+
if (value === void 0) {
|
|
1558
|
+
headers.delete(name);
|
|
1559
|
+
} else if (options?.append) {
|
|
1560
|
+
headers.append(name, value);
|
|
1561
|
+
} else {
|
|
1562
|
+
headers.set(name, value);
|
|
1563
|
+
}
|
|
1564
|
+
};
|
|
1565
|
+
status = (status) => {
|
|
1566
|
+
this.#status = status;
|
|
1567
|
+
};
|
|
1568
|
+
/**
|
|
1569
|
+
* `.set()` can set the value specified by the key.
|
|
1570
|
+
*
|
|
1571
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1572
|
+
*
|
|
1573
|
+
* @example
|
|
1574
|
+
* ```ts
|
|
1575
|
+
* app.use('*', async (c, next) => {
|
|
1576
|
+
* c.set('message', 'Hono is hot!!')
|
|
1577
|
+
* await next()
|
|
1578
|
+
* })
|
|
1579
|
+
* ```
|
|
1580
|
+
*/
|
|
1581
|
+
set = (key, value) => {
|
|
1582
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
1583
|
+
this.#var.set(key, value);
|
|
1584
|
+
};
|
|
1585
|
+
/**
|
|
1586
|
+
* `.get()` can use the value specified by the key.
|
|
1587
|
+
*
|
|
1588
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1589
|
+
*
|
|
1590
|
+
* @example
|
|
1591
|
+
* ```ts
|
|
1592
|
+
* app.get('/', (c) => {
|
|
1593
|
+
* const message = c.get('message')
|
|
1594
|
+
* return c.text(`The message is "${message}"`)
|
|
1595
|
+
* })
|
|
1596
|
+
* ```
|
|
1597
|
+
*/
|
|
1598
|
+
get = (key) => {
|
|
1599
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
1600
|
+
};
|
|
1601
|
+
/**
|
|
1602
|
+
* `.var` can access the value of a variable.
|
|
1603
|
+
*
|
|
1604
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
1605
|
+
*
|
|
1606
|
+
* @example
|
|
1607
|
+
* ```ts
|
|
1608
|
+
* const result = c.var.client.oneMethod()
|
|
1609
|
+
* ```
|
|
1610
|
+
*/
|
|
1611
|
+
// c.var.propName is a read-only
|
|
1612
|
+
get var() {
|
|
1613
|
+
if (!this.#var) {
|
|
1614
|
+
return {};
|
|
1615
|
+
}
|
|
1616
|
+
return Object.fromEntries(this.#var);
|
|
1617
|
+
}
|
|
1618
|
+
#newResponse(data, arg, headers) {
|
|
1619
|
+
let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
|
|
1620
|
+
if (typeof arg === "object" && arg.headers) {
|
|
1621
|
+
responseHeaders ??= new Headers();
|
|
1622
|
+
for (const [key, value] of new Headers(arg.headers)) {
|
|
1623
|
+
if (key === "set-cookie") {
|
|
1624
|
+
responseHeaders.append(key, value);
|
|
1625
|
+
} else {
|
|
1626
|
+
responseHeaders.set(key, value);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
if (headers) {
|
|
1631
|
+
if (!responseHeaders) {
|
|
1632
|
+
let count = 0;
|
|
1633
|
+
for (const k in headers) {
|
|
1634
|
+
if (++count > 1 || typeof headers[k] !== "string") {
|
|
1635
|
+
responseHeaders = new Headers();
|
|
1636
|
+
break;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
if (responseHeaders) {
|
|
1641
|
+
for (const k in headers) {
|
|
1642
|
+
const v = headers[k];
|
|
1643
|
+
if (typeof v === "string") {
|
|
1644
|
+
responseHeaders.set(k, v);
|
|
1645
|
+
} else {
|
|
1646
|
+
responseHeaders.delete(k);
|
|
1647
|
+
for (const v2 of v) {
|
|
1648
|
+
responseHeaders.append(k, v2);
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1655
|
+
return createResponseInstance(data, {
|
|
1656
|
+
status,
|
|
1657
|
+
headers: responseHeaders ?? headers
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1661
|
+
/**
|
|
1662
|
+
* `.body()` can return the HTTP response.
|
|
1663
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
1664
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
1665
|
+
*
|
|
1666
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
1667
|
+
*
|
|
1668
|
+
* @example
|
|
1669
|
+
* ```ts
|
|
1670
|
+
* app.get('/welcome', (c) => {
|
|
1671
|
+
* // Set headers
|
|
1672
|
+
* c.header('X-Message', 'Hello!')
|
|
1673
|
+
* c.header('Content-Type', 'text/plain')
|
|
1674
|
+
* // Set HTTP status code
|
|
1675
|
+
* c.status(201)
|
|
1676
|
+
*
|
|
1677
|
+
* // Return the response body
|
|
1678
|
+
* return c.body('Thank you for coming')
|
|
1679
|
+
* })
|
|
1680
|
+
* ```
|
|
1681
|
+
*/
|
|
1682
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1683
|
+
/**
|
|
1684
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
1685
|
+
*
|
|
1686
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
1687
|
+
*
|
|
1688
|
+
* @example
|
|
1689
|
+
* ```ts
|
|
1690
|
+
* app.get('/say', (c) => {
|
|
1691
|
+
* return c.text('Hello!')
|
|
1692
|
+
* })
|
|
1693
|
+
* ```
|
|
1694
|
+
*/
|
|
1695
|
+
text = (text, arg, headers) => {
|
|
1696
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
1697
|
+
text,
|
|
1698
|
+
arg,
|
|
1699
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
1700
|
+
);
|
|
1701
|
+
};
|
|
1702
|
+
/**
|
|
1703
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
1704
|
+
*
|
|
1705
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
1706
|
+
*
|
|
1707
|
+
* @example
|
|
1708
|
+
* ```ts
|
|
1709
|
+
* app.get('/api', (c) => {
|
|
1710
|
+
* return c.json({ message: 'Hello!' })
|
|
1711
|
+
* })
|
|
1712
|
+
* ```
|
|
1713
|
+
*/
|
|
1714
|
+
json = (object, arg, headers) => {
|
|
1715
|
+
return this.#newResponse(
|
|
1716
|
+
JSON.stringify(object),
|
|
1717
|
+
arg,
|
|
1718
|
+
setDefaultContentType("application/json", headers)
|
|
1719
|
+
);
|
|
1720
|
+
};
|
|
1721
|
+
html = (html, arg, headers) => {
|
|
1722
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1723
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1724
|
+
};
|
|
1725
|
+
/**
|
|
1726
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1727
|
+
*
|
|
1728
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1729
|
+
*
|
|
1730
|
+
* @example
|
|
1731
|
+
* ```ts
|
|
1732
|
+
* app.get('/redirect', (c) => {
|
|
1733
|
+
* return c.redirect('/')
|
|
1734
|
+
* })
|
|
1735
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1736
|
+
* return c.redirect('/', 301)
|
|
1737
|
+
* })
|
|
1738
|
+
* ```
|
|
1739
|
+
*/
|
|
1740
|
+
redirect = (location, status) => {
|
|
1741
|
+
const locationString = String(location);
|
|
1742
|
+
this.header(
|
|
1743
|
+
"Location",
|
|
1744
|
+
// Multibyes should be encoded
|
|
1745
|
+
// eslint-disable-next-line no-control-regex
|
|
1746
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1747
|
+
);
|
|
1748
|
+
return this.newResponse(null, status ?? 302);
|
|
1749
|
+
};
|
|
1750
|
+
/**
|
|
1751
|
+
* `.notFound()` can return the Not Found Response.
|
|
1752
|
+
*
|
|
1753
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1754
|
+
*
|
|
1755
|
+
* @example
|
|
1756
|
+
* ```ts
|
|
1757
|
+
* app.get('/notfound', (c) => {
|
|
1758
|
+
* return c.notFound()
|
|
1759
|
+
* })
|
|
1760
|
+
* ```
|
|
1761
|
+
*/
|
|
1762
|
+
notFound = () => {
|
|
1763
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1764
|
+
return this.#notFoundHandler(this);
|
|
1765
|
+
};
|
|
1766
|
+
};
|
|
1767
|
+
|
|
1768
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router.js
|
|
1769
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1770
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1771
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch", "query"];
|
|
1772
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1773
|
+
var UnsupportedPathError = class extends Error {
|
|
1774
|
+
};
|
|
1775
|
+
|
|
1776
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/utils/constants.js
|
|
1777
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1778
|
+
|
|
1779
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/hono-base.js
|
|
1780
|
+
var notFoundHandler = (c) => {
|
|
1781
|
+
return c.text("404 Not Found", 404);
|
|
1782
|
+
};
|
|
1783
|
+
var errorHandler = (err, c) => {
|
|
1784
|
+
if ("getResponse" in err) {
|
|
1785
|
+
const res = err.getResponse();
|
|
1786
|
+
return c.newResponse(res.body, res);
|
|
1787
|
+
}
|
|
1788
|
+
console.error(err);
|
|
1789
|
+
return c.text("Internal Server Error", 500);
|
|
1790
|
+
};
|
|
1791
|
+
var Hono = class _Hono {
|
|
1792
|
+
get;
|
|
1793
|
+
post;
|
|
1794
|
+
put;
|
|
1795
|
+
delete;
|
|
1796
|
+
options;
|
|
1797
|
+
patch;
|
|
1798
|
+
query;
|
|
1799
|
+
all;
|
|
1800
|
+
on;
|
|
1801
|
+
use;
|
|
1802
|
+
/*
|
|
1803
|
+
This class is like an abstract class and does not have a router.
|
|
1804
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1805
|
+
*/
|
|
1806
|
+
router;
|
|
1807
|
+
getPath;
|
|
1808
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1809
|
+
_basePath = "/";
|
|
1810
|
+
#path = "/";
|
|
1811
|
+
routes = [];
|
|
1812
|
+
constructor(options = {}) {
|
|
1813
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1814
|
+
allMethods.forEach((method) => {
|
|
1815
|
+
this[method] = (args1, ...args) => {
|
|
1816
|
+
const methodName = method.toUpperCase();
|
|
1817
|
+
if (typeof args1 === "string") {
|
|
1818
|
+
this.#path = args1;
|
|
1819
|
+
} else {
|
|
1820
|
+
this.#addRoute(methodName, this.#path, args1);
|
|
1821
|
+
}
|
|
1822
|
+
args.forEach((handler) => {
|
|
1823
|
+
this.#addRoute(methodName, this.#path, handler);
|
|
1824
|
+
});
|
|
1825
|
+
return this;
|
|
1826
|
+
};
|
|
1827
|
+
});
|
|
1828
|
+
this.on = (method, path8, ...handlers) => {
|
|
1829
|
+
for (const p of [path8].flat()) {
|
|
1830
|
+
this.#path = p;
|
|
1831
|
+
for (const m of [method].flat()) {
|
|
1832
|
+
const methodName = m.toUpperCase();
|
|
1833
|
+
for (const handler of handlers) {
|
|
1834
|
+
this.#addRoute(methodName, this.#path, handler);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
return this;
|
|
1839
|
+
};
|
|
1840
|
+
this.use = (arg1, ...handlers) => {
|
|
1841
|
+
if (typeof arg1 === "string") {
|
|
1842
|
+
this.#path = arg1;
|
|
1843
|
+
} else {
|
|
1844
|
+
this.#path = "*";
|
|
1845
|
+
handlers.unshift(arg1);
|
|
1846
|
+
}
|
|
1847
|
+
handlers.forEach((handler) => {
|
|
1848
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1849
|
+
});
|
|
1850
|
+
return this;
|
|
1851
|
+
};
|
|
1852
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1853
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1854
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1855
|
+
}
|
|
1856
|
+
#clone() {
|
|
1857
|
+
const clone = new _Hono({
|
|
1858
|
+
router: this.router,
|
|
1859
|
+
getPath: this.getPath
|
|
1860
|
+
});
|
|
1861
|
+
clone.errorHandler = this.errorHandler;
|
|
1862
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1863
|
+
clone.routes = this.routes;
|
|
1864
|
+
return clone;
|
|
1865
|
+
}
|
|
1866
|
+
#notFoundHandler = notFoundHandler;
|
|
1867
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1868
|
+
errorHandler = errorHandler;
|
|
1869
|
+
/**
|
|
1870
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1871
|
+
*
|
|
1872
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1873
|
+
*
|
|
1874
|
+
* @param {string} path - base Path
|
|
1875
|
+
* @param {Hono} app - other Hono instance
|
|
1876
|
+
* @returns {Hono} routed Hono instance
|
|
1877
|
+
*
|
|
1878
|
+
* @example
|
|
1879
|
+
* ```ts
|
|
1880
|
+
* const app = new Hono()
|
|
1881
|
+
* const app2 = new Hono()
|
|
1882
|
+
*
|
|
1883
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1884
|
+
* app.route("/api", app2) // GET /api/user
|
|
1885
|
+
* ```
|
|
1886
|
+
*/
|
|
1887
|
+
route(path8, app) {
|
|
1888
|
+
const subApp = this.basePath(path8);
|
|
1889
|
+
app.routes.map((r) => {
|
|
1890
|
+
let handler;
|
|
1891
|
+
if (app.errorHandler === errorHandler) {
|
|
1892
|
+
handler = r.handler;
|
|
1893
|
+
} else {
|
|
1894
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1895
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1896
|
+
}
|
|
1897
|
+
subApp.#addRoute(r.method, r.path, handler, r.basePath);
|
|
1898
|
+
});
|
|
1899
|
+
return this;
|
|
1900
|
+
}
|
|
1901
|
+
/**
|
|
1902
|
+
* `.basePath()` allows base paths to be specified.
|
|
1903
|
+
*
|
|
1904
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1905
|
+
*
|
|
1906
|
+
* @param {string} path - base Path
|
|
1907
|
+
* @returns {Hono} changed Hono instance
|
|
1908
|
+
*
|
|
1909
|
+
* @example
|
|
1910
|
+
* ```ts
|
|
1911
|
+
* const api = new Hono().basePath('/api')
|
|
1912
|
+
* ```
|
|
1913
|
+
*/
|
|
1914
|
+
basePath(path8) {
|
|
1915
|
+
const subApp = this.#clone();
|
|
1916
|
+
subApp._basePath = mergePath(this._basePath, path8);
|
|
1917
|
+
return subApp;
|
|
1918
|
+
}
|
|
1919
|
+
/**
|
|
1920
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
1921
|
+
*
|
|
1922
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
1923
|
+
*
|
|
1924
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
1925
|
+
* @returns {Hono} changed Hono instance
|
|
1926
|
+
*
|
|
1927
|
+
* @example
|
|
1928
|
+
* ```ts
|
|
1929
|
+
* app.onError((err, c) => {
|
|
1930
|
+
* console.error(`${err}`)
|
|
1931
|
+
* return c.text('Custom Error Message', 500)
|
|
1932
|
+
* })
|
|
1933
|
+
* ```
|
|
1934
|
+
*/
|
|
1935
|
+
onError = (handler) => {
|
|
1936
|
+
this.errorHandler = handler;
|
|
1937
|
+
return this;
|
|
1938
|
+
};
|
|
1939
|
+
/**
|
|
1940
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
1941
|
+
*
|
|
1942
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
1943
|
+
*
|
|
1944
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
1945
|
+
* @returns {Hono} changed Hono instance
|
|
1946
|
+
*
|
|
1947
|
+
* @example
|
|
1948
|
+
* ```ts
|
|
1949
|
+
* app.notFound((c) => {
|
|
1950
|
+
* return c.text('Custom 404 Message', 404)
|
|
1951
|
+
* })
|
|
1952
|
+
* ```
|
|
1953
|
+
*/
|
|
1954
|
+
notFound = (handler) => {
|
|
1955
|
+
this.#notFoundHandler = handler;
|
|
1956
|
+
return this;
|
|
1957
|
+
};
|
|
1958
|
+
/**
|
|
1959
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
1960
|
+
*
|
|
1961
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
1962
|
+
*
|
|
1963
|
+
* @param {string} path - base Path
|
|
1964
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
1965
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
1966
|
+
* @returns {Hono} mounted Hono instance
|
|
1967
|
+
*
|
|
1968
|
+
* @example
|
|
1969
|
+
* ```ts
|
|
1970
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
1971
|
+
* import { Hono } from 'hono'
|
|
1972
|
+
* // Create itty-router application
|
|
1973
|
+
* const ittyRouter = IttyRouter()
|
|
1974
|
+
* // GET /itty-router/hello
|
|
1975
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
1976
|
+
*
|
|
1977
|
+
* const app = new Hono()
|
|
1978
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
1979
|
+
* ```
|
|
1980
|
+
*
|
|
1981
|
+
* @example
|
|
1982
|
+
* ```ts
|
|
1983
|
+
* const app = new Hono()
|
|
1984
|
+
* // Send the request to another application without modification.
|
|
1985
|
+
* app.mount('/app', anotherApp, {
|
|
1986
|
+
* replaceRequest: (req) => req,
|
|
1987
|
+
* })
|
|
1988
|
+
* ```
|
|
1989
|
+
*/
|
|
1990
|
+
mount(path8, applicationHandler, options) {
|
|
1991
|
+
let replaceRequest;
|
|
1992
|
+
let optionHandler;
|
|
1993
|
+
if (options) {
|
|
1994
|
+
if (typeof options === "function") {
|
|
1995
|
+
optionHandler = options;
|
|
1996
|
+
} else {
|
|
1997
|
+
optionHandler = options.optionHandler;
|
|
1998
|
+
if (options.replaceRequest === false) {
|
|
1999
|
+
replaceRequest = (request) => request;
|
|
2000
|
+
} else {
|
|
2001
|
+
replaceRequest = options.replaceRequest;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
const getOptions = optionHandler ? (c) => {
|
|
2006
|
+
const options2 = optionHandler(c);
|
|
2007
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
2008
|
+
} : (c) => {
|
|
2009
|
+
let executionContext = void 0;
|
|
2010
|
+
try {
|
|
2011
|
+
executionContext = c.executionCtx;
|
|
2012
|
+
} catch {
|
|
2013
|
+
}
|
|
2014
|
+
return [c.env, executionContext];
|
|
2015
|
+
};
|
|
2016
|
+
replaceRequest ||= (() => {
|
|
2017
|
+
const mergedPath = mergePath(this._basePath, path8);
|
|
2018
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2019
|
+
return (request) => {
|
|
2020
|
+
const url = new URL(request.url);
|
|
2021
|
+
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
|
|
2022
|
+
return new Request(url, request);
|
|
2023
|
+
};
|
|
2024
|
+
})();
|
|
2025
|
+
const handler = async (c, next) => {
|
|
2026
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2027
|
+
if (res) {
|
|
2028
|
+
return res;
|
|
2029
|
+
}
|
|
2030
|
+
await next();
|
|
2031
|
+
};
|
|
2032
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path8, "*"), handler);
|
|
2033
|
+
return this;
|
|
2034
|
+
}
|
|
2035
|
+
#addRoute(method, path8, handler, baseRoutePath) {
|
|
2036
|
+
path8 = mergePath(this._basePath, path8);
|
|
2037
|
+
const r = {
|
|
2038
|
+
basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
|
|
2039
|
+
path: path8,
|
|
2040
|
+
method,
|
|
2041
|
+
handler
|
|
2042
|
+
};
|
|
2043
|
+
this.router.add(method, path8, [handler, r]);
|
|
2044
|
+
this.routes.push(r);
|
|
2045
|
+
}
|
|
2046
|
+
#handleError(err, c) {
|
|
2047
|
+
if (err instanceof Error) {
|
|
2048
|
+
return this.errorHandler(err, c);
|
|
2049
|
+
}
|
|
2050
|
+
throw err;
|
|
2051
|
+
}
|
|
2052
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2053
|
+
if (method === "HEAD") {
|
|
2054
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2055
|
+
}
|
|
2056
|
+
const path8 = this.getPath(request, { env });
|
|
2057
|
+
const matchResult = this.router.match(method, path8);
|
|
2058
|
+
const c = new Context(request, {
|
|
2059
|
+
path: path8,
|
|
2060
|
+
matchResult,
|
|
2061
|
+
env,
|
|
2062
|
+
executionCtx,
|
|
2063
|
+
notFoundHandler: this.#notFoundHandler
|
|
2064
|
+
});
|
|
2065
|
+
if (matchResult[0].length === 1) {
|
|
2066
|
+
let res;
|
|
2067
|
+
try {
|
|
2068
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2069
|
+
c.res = await this.#notFoundHandler(c);
|
|
2070
|
+
});
|
|
2071
|
+
} catch (err) {
|
|
2072
|
+
return this.#handleError(err, c);
|
|
2073
|
+
}
|
|
2074
|
+
return res instanceof Promise ? res.then(
|
|
2075
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
2076
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2077
|
+
}
|
|
2078
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2079
|
+
return (async () => {
|
|
2080
|
+
try {
|
|
2081
|
+
const context = await composed(c);
|
|
2082
|
+
if (!context.finalized) {
|
|
2083
|
+
throw new Error(
|
|
2084
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
2085
|
+
);
|
|
2086
|
+
}
|
|
2087
|
+
return context.res;
|
|
2088
|
+
} catch (err) {
|
|
2089
|
+
return this.#handleError(err, c);
|
|
2090
|
+
}
|
|
2091
|
+
})();
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* `.fetch()` will be entry point of your app.
|
|
2095
|
+
*
|
|
2096
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
2097
|
+
*
|
|
2098
|
+
* @param {Request} request - request Object of request
|
|
2099
|
+
* @param {Env} env - env Object
|
|
2100
|
+
* @param {ExecutionContext} executionCtx - context of execution
|
|
2101
|
+
* @returns {Response | Promise<Response>} response of request
|
|
2102
|
+
*
|
|
2103
|
+
*/
|
|
2104
|
+
fetch = (request, ...rest) => {
|
|
2105
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2106
|
+
};
|
|
2107
|
+
/**
|
|
2108
|
+
* `.request()` is a useful method for testing.
|
|
2109
|
+
* You can pass a URL or pathname to send a GET request.
|
|
2110
|
+
* app will return a Response object.
|
|
2111
|
+
* ```ts
|
|
2112
|
+
* test('GET /hello is ok', async () => {
|
|
2113
|
+
* const res = await app.request('/hello')
|
|
2114
|
+
* expect(res.status).toBe(200)
|
|
2115
|
+
* })
|
|
2116
|
+
* ```
|
|
2117
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
2118
|
+
*/
|
|
2119
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2120
|
+
if (input instanceof Request) {
|
|
2121
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2122
|
+
}
|
|
2123
|
+
input = input.toString();
|
|
2124
|
+
return this.fetch(
|
|
2125
|
+
new Request(
|
|
2126
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
2127
|
+
requestInit
|
|
2128
|
+
),
|
|
2129
|
+
Env,
|
|
2130
|
+
executionCtx
|
|
2131
|
+
);
|
|
2132
|
+
};
|
|
2133
|
+
/**
|
|
2134
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
2135
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
2136
|
+
* @deprecated
|
|
2137
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
2138
|
+
* ```ts
|
|
2139
|
+
* import { Hono } from 'hono'
|
|
2140
|
+
* import { fire } from 'hono/service-worker'
|
|
2141
|
+
*
|
|
2142
|
+
* const app = new Hono()
|
|
2143
|
+
* // ...
|
|
2144
|
+
* fire(app)
|
|
2145
|
+
* ```
|
|
2146
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
2147
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
2148
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
2149
|
+
*/
|
|
2150
|
+
fire = () => {
|
|
2151
|
+
addEventListener("fetch", (event) => {
|
|
2152
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
2153
|
+
});
|
|
2154
|
+
};
|
|
2155
|
+
};
|
|
2156
|
+
|
|
2157
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/utils.js
|
|
2158
|
+
var createNullObject = () => /* @__PURE__ */ Object.create(null);
|
|
2159
|
+
|
|
2160
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2161
|
+
var emptyParam = [];
|
|
2162
|
+
function match(method, path8) {
|
|
2163
|
+
const matchers = this.buildAllMatchers();
|
|
2164
|
+
const match2 = ((method2, path22) => {
|
|
2165
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2166
|
+
const staticMatch = matcher[2][path22];
|
|
2167
|
+
if (staticMatch) {
|
|
2168
|
+
return staticMatch;
|
|
2169
|
+
}
|
|
2170
|
+
const match3 = path22.match(matcher[0]);
|
|
2171
|
+
if (!match3) {
|
|
2172
|
+
return [[], emptyParam];
|
|
2173
|
+
}
|
|
2174
|
+
const index = match3.indexOf("", 1);
|
|
2175
|
+
return [matcher[1][index], match3];
|
|
2176
|
+
});
|
|
2177
|
+
this.match = match2;
|
|
2178
|
+
return match2(method, path8);
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2182
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2183
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2184
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2185
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2186
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2187
|
+
function compareKey(a, b) {
|
|
2188
|
+
if (a.length === 1) {
|
|
2189
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2190
|
+
}
|
|
2191
|
+
if (b.length === 1) {
|
|
2192
|
+
return 1;
|
|
2193
|
+
}
|
|
2194
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2195
|
+
return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;
|
|
2196
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2197
|
+
return -1;
|
|
2198
|
+
}
|
|
2199
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
2200
|
+
return 1;
|
|
2201
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
2202
|
+
return -1;
|
|
2203
|
+
}
|
|
2204
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
2205
|
+
}
|
|
2206
|
+
var Node = class _Node {
|
|
2207
|
+
// handler index of a dynamic path, or -1 for a static path terminal
|
|
2208
|
+
#index;
|
|
2209
|
+
#varIndex;
|
|
2210
|
+
#children = createNullObject();
|
|
2211
|
+
insert(tokens, index, paramMap, context, isStatic) {
|
|
2212
|
+
let node = this;
|
|
2213
|
+
for (let i = 0, len = tokens.length; i < len; i++) {
|
|
2214
|
+
const token = tokens[i];
|
|
2215
|
+
const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : null : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2216
|
+
let nextNode;
|
|
2217
|
+
if (pattern) {
|
|
2218
|
+
const name = pattern[1];
|
|
2219
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
2220
|
+
if (name && pattern[2]) {
|
|
2221
|
+
if (regexpStr === ".*") {
|
|
2222
|
+
throw PATH_ERROR;
|
|
2223
|
+
}
|
|
2224
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
2225
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
2226
|
+
throw PATH_ERROR;
|
|
2227
|
+
}
|
|
2228
|
+
if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {
|
|
2229
|
+
throw PATH_ERROR;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
nextNode = node.#children[regexpStr];
|
|
2233
|
+
if (!nextNode) {
|
|
2234
|
+
if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {
|
|
2235
|
+
for (const k in node.#children) {
|
|
2236
|
+
if (
|
|
2237
|
+
// a single-char pattern coexists with single-char literals as a literal does
|
|
2238
|
+
(regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2239
|
+
) {
|
|
2240
|
+
throw PATH_ERROR;
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
nextNode = node.#children[regexpStr] = new _Node();
|
|
2245
|
+
}
|
|
2246
|
+
if (name !== "") {
|
|
2247
|
+
nextNode.#varIndex ??= context.varIndex++;
|
|
2248
|
+
paramMap.push([name, nextNode.#varIndex]);
|
|
2249
|
+
}
|
|
2250
|
+
} else {
|
|
2251
|
+
nextNode = node.#children[token];
|
|
2252
|
+
if (!nextNode) {
|
|
2253
|
+
for (const k in node.#children) {
|
|
2254
|
+
if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {
|
|
2255
|
+
throw PATH_ERROR;
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
nextNode = node.#children[token] = new _Node();
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
node = nextNode;
|
|
2262
|
+
}
|
|
2263
|
+
if (node.#index !== void 0) {
|
|
2264
|
+
throw PATH_ERROR;
|
|
2265
|
+
}
|
|
2266
|
+
node.#index = isStatic ? -1 : index;
|
|
2267
|
+
}
|
|
2268
|
+
buildRegExpStr() {
|
|
2269
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
2270
|
+
const strList = childKeys.map((k) => {
|
|
2271
|
+
const c = this.#children[k];
|
|
2272
|
+
const childStr = c.buildRegExpStr();
|
|
2273
|
+
return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
|
|
2274
|
+
}).filter(Boolean);
|
|
2275
|
+
if (typeof this.#index === "number" && this.#index !== -1) {
|
|
2276
|
+
strList.unshift(`#${this.#index}`);
|
|
2277
|
+
}
|
|
2278
|
+
if (strList.length === 0) {
|
|
2279
|
+
return "";
|
|
2280
|
+
}
|
|
2281
|
+
if (strList.length === 1) {
|
|
2282
|
+
return strList[0];
|
|
2283
|
+
}
|
|
2284
|
+
return "(?:" + strList.join("|") + ")";
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2287
|
+
|
|
2288
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
2289
|
+
var Trie = class {
|
|
2290
|
+
#context = { varIndex: 0 };
|
|
2291
|
+
#root = new Node();
|
|
2292
|
+
#index = 0;
|
|
2293
|
+
// dynamic path -> [handler index, param assoc]; static paths are not registered
|
|
2294
|
+
paths = createNullObject();
|
|
2295
|
+
insert(path8, isStatic) {
|
|
2296
|
+
if (isStatic) {
|
|
2297
|
+
this.#root.insert(path8.split(""), 0, [], this.#context, true);
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
const paramAssoc = [];
|
|
2301
|
+
const groups = [];
|
|
2302
|
+
let markedPath = path8;
|
|
2303
|
+
for (let i = 0; ; ) {
|
|
2304
|
+
let replaced = false;
|
|
2305
|
+
markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
|
|
2306
|
+
const mark = `@\\${i}`;
|
|
2307
|
+
groups[i] = [mark, m];
|
|
2308
|
+
i++;
|
|
2309
|
+
replaced = true;
|
|
2310
|
+
return mark;
|
|
2311
|
+
});
|
|
2312
|
+
if (!replaced) {
|
|
2313
|
+
break;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
2317
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
2318
|
+
const [mark] = groups[i];
|
|
2319
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
2320
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
2321
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
2322
|
+
break;
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
|
|
2327
|
+
this.paths[path8] = [this.#index++, paramAssoc];
|
|
2328
|
+
}
|
|
2329
|
+
buildRegExp() {
|
|
2330
|
+
let regexp = this.#root.buildRegExpStr();
|
|
2331
|
+
if (regexp === "") {
|
|
2332
|
+
return [/^$/, [], []];
|
|
2333
|
+
}
|
|
2334
|
+
let captureIndex = 0;
|
|
2335
|
+
const indexReplacementMap = [];
|
|
2336
|
+
const paramReplacementMap = [];
|
|
2337
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
2338
|
+
if (handlerIndex !== void 0) {
|
|
2339
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
2340
|
+
return "$()";
|
|
2341
|
+
}
|
|
2342
|
+
if (paramIndex !== void 0) {
|
|
2343
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
2344
|
+
return "";
|
|
2345
|
+
}
|
|
2346
|
+
return "";
|
|
2347
|
+
});
|
|
2348
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
2349
|
+
}
|
|
2350
|
+
};
|
|
2351
|
+
|
|
2352
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
2353
|
+
var wildcardRegExpCache = createNullObject();
|
|
2354
|
+
function buildWildcardRegExp(path8) {
|
|
2355
|
+
return wildcardRegExpCache[path8] ??= new RegExp(
|
|
2356
|
+
`^${path8.replace(
|
|
2357
|
+
/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,
|
|
2358
|
+
(match2, metaChar) => metaChar ? `\\${metaChar}` : match2 === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match2 === "*" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`
|
|
2359
|
+
)}$`
|
|
2360
|
+
);
|
|
2361
|
+
}
|
|
2362
|
+
function findMiddleware(middleware, path8) {
|
|
2363
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
2364
|
+
if (buildWildcardRegExp(k).test(path8)) {
|
|
2365
|
+
return [...middleware[k]];
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
return void 0;
|
|
2369
|
+
}
|
|
2370
|
+
var RegExpRouter = class {
|
|
2371
|
+
name = "RegExpRouter";
|
|
2372
|
+
#middleware;
|
|
2373
|
+
#routes;
|
|
2374
|
+
#tries;
|
|
2375
|
+
constructor() {
|
|
2376
|
+
this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };
|
|
2377
|
+
this.#routes = { [METHOD_NAME_ALL]: createNullObject() };
|
|
2378
|
+
this.#tries = { [METHOD_NAME_ALL]: new Trie() };
|
|
2379
|
+
}
|
|
2380
|
+
#insertPath(method, path8) {
|
|
2381
|
+
try {
|
|
2382
|
+
this.#tries[method].insert(path8, !/\*|\/:/.test(path8));
|
|
2383
|
+
} catch (e) {
|
|
2384
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path8) : e;
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
add(method, path8, handler) {
|
|
2388
|
+
const middleware = this.#middleware;
|
|
2389
|
+
const routes = this.#routes;
|
|
2390
|
+
if (!middleware) {
|
|
2391
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2392
|
+
}
|
|
2393
|
+
if (!middleware[method]) {
|
|
2394
|
+
this.#tries[method] = new Trie();
|
|
2395
|
+
for (const handlerMap of [middleware, routes]) {
|
|
2396
|
+
handlerMap[method] = createNullObject();
|
|
2397
|
+
for (const p in handlerMap[METHOD_NAME_ALL]) {
|
|
2398
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
2399
|
+
this.#insertPath(method, p);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
if (path8 === "/*") {
|
|
2404
|
+
path8 = "*";
|
|
2405
|
+
}
|
|
2406
|
+
const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];
|
|
2407
|
+
if (/\*$/.test(path8)) {
|
|
2408
|
+
const re = buildWildcardRegExp(path8);
|
|
2409
|
+
for (const m of methods) {
|
|
2410
|
+
if (!middleware[m][path8]) {
|
|
2411
|
+
this.#insertPath(m, path8);
|
|
2412
|
+
middleware[m][path8] = findMiddleware(middleware[m], path8) || findMiddleware(middleware[METHOD_NAME_ALL], path8) || [];
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
for (const handlerMap of [middleware, routes]) {
|
|
2416
|
+
for (const m of methods) {
|
|
2417
|
+
for (const p in handlerMap[m]) {
|
|
2418
|
+
re.test(p) && handlerMap[m][p].push([handler, path8]);
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
return;
|
|
2423
|
+
}
|
|
2424
|
+
const paths = checkOptionalParameter(path8) || [path8];
|
|
2425
|
+
for (const path22 of paths) {
|
|
2426
|
+
for (const m of methods) {
|
|
2427
|
+
if (!routes[m][path22]) {
|
|
2428
|
+
this.#insertPath(m, path22);
|
|
2429
|
+
routes[m][path22] = findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || [];
|
|
2430
|
+
}
|
|
2431
|
+
routes[m][path22].push([handler, path22]);
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
match = match;
|
|
2436
|
+
buildAllMatchers() {
|
|
2437
|
+
const matchers = createNullObject();
|
|
2438
|
+
for (const method of Object.keys(this.#routes)) {
|
|
2439
|
+
matchers[method] = this.#buildMatcher(method);
|
|
2440
|
+
}
|
|
2441
|
+
this.#middleware = this.#routes = this.#tries = void 0;
|
|
2442
|
+
wildcardRegExpCache = createNullObject();
|
|
2443
|
+
return matchers;
|
|
2444
|
+
}
|
|
2445
|
+
#buildMatcher(method) {
|
|
2446
|
+
const middleware = this.#middleware[method];
|
|
2447
|
+
const routes = this.#routes[method];
|
|
2448
|
+
const trie = this.#tries[method];
|
|
2449
|
+
const staticMap = createNullObject();
|
|
2450
|
+
const handlerData = [];
|
|
2451
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
2452
|
+
for (const r of [middleware, routes]) {
|
|
2453
|
+
for (const path8 in r) {
|
|
2454
|
+
const handlers = r[path8];
|
|
2455
|
+
const pathData = trie.paths[path8];
|
|
2456
|
+
if (!pathData) {
|
|
2457
|
+
staticMap[path8] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
2460
|
+
handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [
|
|
2461
|
+
h,
|
|
2462
|
+
trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
|
|
2463
|
+
map[key] = paramReplacementMap[pathData[1][i][1]];
|
|
2464
|
+
return map;
|
|
2465
|
+
}, createNullObject())
|
|
2466
|
+
]);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];
|
|
2470
|
+
}
|
|
2471
|
+
};
|
|
2472
|
+
|
|
2473
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/smart-router/router.js
|
|
2474
|
+
var SmartRouter = class {
|
|
2475
|
+
name = "SmartRouter";
|
|
2476
|
+
#routers = [];
|
|
2477
|
+
#routes = [];
|
|
2478
|
+
constructor(init) {
|
|
2479
|
+
this.#routers = init.routers;
|
|
2480
|
+
}
|
|
2481
|
+
add(method, path8, handler) {
|
|
2482
|
+
if (!this.#routes) {
|
|
2483
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2484
|
+
}
|
|
2485
|
+
this.#routes.push([method, path8, handler]);
|
|
2486
|
+
}
|
|
2487
|
+
match(method, path8) {
|
|
2488
|
+
if (!this.#routes) {
|
|
2489
|
+
throw new Error("Fatal error");
|
|
2490
|
+
}
|
|
2491
|
+
const routers = this.#routers;
|
|
2492
|
+
const routes = this.#routes;
|
|
2493
|
+
const len = routers.length;
|
|
2494
|
+
let i = 0;
|
|
2495
|
+
let res;
|
|
2496
|
+
for (; i < len; i++) {
|
|
2497
|
+
const router = routers[i];
|
|
2498
|
+
try {
|
|
2499
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
2500
|
+
router.add(...routes[i2]);
|
|
2501
|
+
}
|
|
2502
|
+
res = router.match(method, path8);
|
|
2503
|
+
} catch (e) {
|
|
2504
|
+
if (e instanceof UnsupportedPathError) {
|
|
2505
|
+
continue;
|
|
2506
|
+
}
|
|
2507
|
+
throw e;
|
|
2508
|
+
}
|
|
2509
|
+
this.match = router.match.bind(router);
|
|
2510
|
+
this.#routers = [router];
|
|
2511
|
+
this.#routes = void 0;
|
|
2512
|
+
break;
|
|
2513
|
+
}
|
|
2514
|
+
if (i === len) {
|
|
2515
|
+
throw new Error("Fatal error");
|
|
2516
|
+
}
|
|
2517
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2518
|
+
return res;
|
|
2519
|
+
}
|
|
2520
|
+
get activeRouter() {
|
|
2521
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2522
|
+
throw new Error("No active router has been determined yet.");
|
|
2523
|
+
}
|
|
2524
|
+
return this.#routers[0];
|
|
2525
|
+
}
|
|
2526
|
+
};
|
|
2527
|
+
|
|
2528
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/trie-router/node.js
|
|
2529
|
+
var emptyParams = createNullObject();
|
|
2530
|
+
var order = 0;
|
|
2531
|
+
var Node2 = class _Node2 {
|
|
2532
|
+
#methods = [];
|
|
2533
|
+
#children = createNullObject();
|
|
2534
|
+
#patterns = [];
|
|
2535
|
+
#pattern;
|
|
2536
|
+
#params = emptyParams;
|
|
2537
|
+
insert(method, path8, handler) {
|
|
2538
|
+
let curNode = this;
|
|
2539
|
+
const parts = splitRoutingPath(path8);
|
|
2540
|
+
const possibleKeys = /* @__PURE__ */ new Set();
|
|
2541
|
+
let i = 0;
|
|
2542
|
+
for (const p of parts) {
|
|
2543
|
+
const nextP = parts[++i];
|
|
2544
|
+
const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
|
|
2545
|
+
const isParam = Array.isArray(pattern);
|
|
2546
|
+
const key = isParam ? pattern[0] : pattern || p;
|
|
2547
|
+
const child = curNode.#children[key] ||= new _Node2();
|
|
2548
|
+
if (pattern && !child.#pattern) {
|
|
2549
|
+
child.#pattern = pattern;
|
|
2550
|
+
curNode.#patterns.push(child);
|
|
2551
|
+
}
|
|
2552
|
+
curNode = child;
|
|
2553
|
+
if (isParam) {
|
|
2554
|
+
possibleKeys.add(pattern[1]);
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
curNode.#methods.push({
|
|
2558
|
+
[method]: {
|
|
2559
|
+
handler,
|
|
2560
|
+
possibleKeys: [...possibleKeys],
|
|
2561
|
+
score: ++order
|
|
2562
|
+
}
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
2566
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
2567
|
+
const m = node.#methods[i];
|
|
2568
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2569
|
+
if (handlerSet) {
|
|
2570
|
+
handlerSet.params = createNullObject();
|
|
2571
|
+
handlerSets.push(handlerSet);
|
|
2572
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
2573
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2574
|
+
handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
search(method, path8) {
|
|
2580
|
+
const handlerSets = [];
|
|
2581
|
+
this.#params = emptyParams;
|
|
2582
|
+
const curNode = this;
|
|
2583
|
+
let curNodes = [curNode];
|
|
2584
|
+
const parts = splitPath(path8);
|
|
2585
|
+
const curNodesQueue = [];
|
|
2586
|
+
const len = parts.length;
|
|
2587
|
+
let partOffsets = null;
|
|
2588
|
+
for (let i = 0; i < len; i++) {
|
|
2589
|
+
const part = parts[i];
|
|
2590
|
+
const isLast = i === len - 1;
|
|
2591
|
+
const tempNodes = [];
|
|
2592
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
2593
|
+
const node = curNodes[j];
|
|
2594
|
+
const nextNode = node.#children[part];
|
|
2595
|
+
if (nextNode) {
|
|
2596
|
+
nextNode.#params = node.#params;
|
|
2597
|
+
if (isLast) {
|
|
2598
|
+
if (nextNode.#children["*"]) {
|
|
2599
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
2600
|
+
}
|
|
2601
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
2602
|
+
} else {
|
|
2603
|
+
tempNodes.push(nextNode);
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
for (const child of node.#patterns) {
|
|
2607
|
+
const pattern = child.#pattern;
|
|
2608
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2609
|
+
if (typeof pattern === "string") {
|
|
2610
|
+
if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
|
|
2611
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params);
|
|
2612
|
+
if (pattern === "*") {
|
|
2613
|
+
child.#params = params;
|
|
2614
|
+
tempNodes.push(child);
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
continue;
|
|
2618
|
+
}
|
|
2619
|
+
const [, name, matcher] = pattern;
|
|
2620
|
+
if (!part && matcher === true) {
|
|
2621
|
+
continue;
|
|
2622
|
+
}
|
|
2623
|
+
if (matcher !== true) {
|
|
2624
|
+
if (!partOffsets) {
|
|
2625
|
+
partOffsets = [];
|
|
2626
|
+
let offset = path8[0] === "/" ? 1 : 0;
|
|
2627
|
+
for (let p = 0; p < len; p++) {
|
|
2628
|
+
partOffsets[p] = offset;
|
|
2629
|
+
offset += parts[p].length + 1;
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
const restPathString = path8.slice(partOffsets[i]);
|
|
2633
|
+
const m = matcher.exec(restPathString);
|
|
2634
|
+
if (m) {
|
|
2635
|
+
params[name] = m[0];
|
|
2636
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
2637
|
+
if (m[0].length === restPathString.length && child.#children["*"]) {
|
|
2638
|
+
this.#pushHandlerSets(
|
|
2639
|
+
handlerSets,
|
|
2640
|
+
child.#children["*"],
|
|
2641
|
+
method,
|
|
2642
|
+
node.#params,
|
|
2643
|
+
params
|
|
2644
|
+
);
|
|
2645
|
+
}
|
|
2646
|
+
for (const _ in child.#children) {
|
|
2647
|
+
child.#params = params;
|
|
2648
|
+
const componentCount = m[0].match(/\//g)?.length ?? 0;
|
|
2649
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2650
|
+
targetCurNodes.push(child);
|
|
2651
|
+
break;
|
|
2652
|
+
}
|
|
2653
|
+
continue;
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
if (matcher === true || matcher.test(part)) {
|
|
2657
|
+
params[name] = part;
|
|
2658
|
+
if (isLast) {
|
|
2659
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
2660
|
+
if (child.#children["*"]) {
|
|
2661
|
+
this.#pushHandlerSets(
|
|
2662
|
+
handlerSets,
|
|
2663
|
+
child.#children["*"],
|
|
2664
|
+
method,
|
|
2665
|
+
params,
|
|
2666
|
+
node.#params
|
|
2667
|
+
);
|
|
2668
|
+
}
|
|
2669
|
+
} else {
|
|
2670
|
+
child.#params = params;
|
|
2671
|
+
tempNodes.push(child);
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
const shifted = curNodesQueue.shift();
|
|
2677
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2678
|
+
}
|
|
2679
|
+
if (handlerSets[1]) {
|
|
2680
|
+
handlerSets.sort((a, b) => {
|
|
2681
|
+
return a.score - b.score;
|
|
2682
|
+
});
|
|
2683
|
+
}
|
|
2684
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2685
|
+
}
|
|
2686
|
+
};
|
|
2687
|
+
|
|
2688
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/router/trie-router/router.js
|
|
2689
|
+
var TrieRouter = class {
|
|
2690
|
+
name = "TrieRouter";
|
|
2691
|
+
#node = new Node2();
|
|
2692
|
+
add(method, path8, handler) {
|
|
2693
|
+
for (const result of checkOptionalParameter(path8) || [path8]) {
|
|
2694
|
+
this.#node.insert(method, result, handler);
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2697
|
+
match(method, path8) {
|
|
2698
|
+
return this.#node.search(method, path8);
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
|
|
2702
|
+
// node_modules/.pnpm/hono@4.13.7/node_modules/hono/dist/hono.js
|
|
2703
|
+
var Hono2 = class extends Hono {
|
|
2704
|
+
/**
|
|
2705
|
+
* Creates an instance of the Hono class.
|
|
2706
|
+
*
|
|
2707
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2708
|
+
*/
|
|
2709
|
+
constructor(options = {}) {
|
|
2710
|
+
super(options);
|
|
2711
|
+
this.router = options.router ?? new SmartRouter({
|
|
2712
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
};
|
|
2716
|
+
|
|
2717
|
+
// packages/shared/src/target.ts
|
|
2718
|
+
var TargetKeyError = class extends Error {
|
|
2719
|
+
constructor(message) {
|
|
2720
|
+
super(message);
|
|
2721
|
+
this.name = "TargetKeyError";
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
function isValidRef(ref) {
|
|
2725
|
+
if (!ref || ref.length > 256) return false;
|
|
2726
|
+
if (ref.startsWith("-") || ref.startsWith(".")) return false;
|
|
2727
|
+
if (/[\s\0]/.test(ref)) return false;
|
|
2728
|
+
if (ref.includes("..")) return false;
|
|
2729
|
+
return true;
|
|
2730
|
+
}
|
|
2731
|
+
function parseSuffix(rest) {
|
|
2732
|
+
if (rest === "working" || rest === "staged" || rest === "all") return { kind: rest };
|
|
2733
|
+
if (rest.startsWith("commit:")) {
|
|
2734
|
+
const sha = rest.slice("commit:".length);
|
|
2735
|
+
if (!isValidRef(sha)) throw new TargetKeyError(`invalid commit ref: ${sha}`);
|
|
2736
|
+
return { kind: "commit", sha };
|
|
2737
|
+
}
|
|
2738
|
+
if (rest.startsWith("range:")) {
|
|
2739
|
+
const spec = rest.slice("range:".length);
|
|
2740
|
+
const idx = spec.indexOf("..");
|
|
2741
|
+
if (idx <= 0) throw new TargetKeyError(`invalid range: ${spec}`);
|
|
2742
|
+
const base = spec.slice(0, idx);
|
|
2743
|
+
const head = spec.slice(idx + 2);
|
|
2744
|
+
if (!isValidRef(base) || !isValidRef(head)) throw new TargetKeyError(`invalid range refs: ${spec}`);
|
|
2745
|
+
return { kind: "range", base, head };
|
|
2746
|
+
}
|
|
2747
|
+
throw new TargetKeyError(`unknown target key: ${rest}`);
|
|
2748
|
+
}
|
|
2749
|
+
function parseTargetKey(key) {
|
|
2750
|
+
if (typeof key !== "string" || !key) throw new TargetKeyError("empty target key");
|
|
2751
|
+
if (key.startsWith("worktree:")) {
|
|
2752
|
+
const rest = key.slice("worktree:".length);
|
|
2753
|
+
const m = /^(.+):(working|staged|all|commit:.+|range:.+)$/.exec(rest);
|
|
2754
|
+
if (!m || !m[1] || !m[2]) throw new TargetKeyError(`invalid worktree target key: ${key}`);
|
|
2755
|
+
const worktree = m[1];
|
|
2756
|
+
if (!worktree.startsWith("/")) throw new TargetKeyError(`worktree path must be absolute: ${worktree}`);
|
|
2757
|
+
return { ...parseSuffix(m[2]), worktree };
|
|
2758
|
+
}
|
|
2759
|
+
return parseSuffix(key);
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
// packages/server/src/errors.ts
|
|
2763
|
+
var HttpError = class extends Error {
|
|
2764
|
+
constructor(status, message, code) {
|
|
2765
|
+
super(message);
|
|
2766
|
+
this.status = status;
|
|
2767
|
+
this.code = code;
|
|
2768
|
+
this.name = "HttpError";
|
|
2769
|
+
}
|
|
2770
|
+
status;
|
|
2771
|
+
code;
|
|
2772
|
+
};
|
|
2773
|
+
function badRequest(message, code = "bad_request") {
|
|
2774
|
+
return new HttpError(400, message, code);
|
|
2775
|
+
}
|
|
2776
|
+
function notFound(message, code = "not_found") {
|
|
2777
|
+
return new HttpError(404, message, code);
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
// packages/server/src/git.ts
|
|
2781
|
+
import { execFile } from "child_process";
|
|
2782
|
+
var ALLOWED_SUBCOMMANDS = /* @__PURE__ */ new Set(["rev-parse", "diff", "show", "log", "worktree", "ls-files", "status"]);
|
|
2783
|
+
var FORBIDDEN_OPTION_PREFIXES = ["--output", "--ext-diff", "--textconv", "-c", "--config-env", "--exec-path", "--git-dir", "--work-tree"];
|
|
2784
|
+
var DEFAULT_GIT_TIMEOUT_MS = 3e4;
|
|
2785
|
+
var EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
|
|
2786
|
+
var GitError = class extends HttpError {
|
|
2787
|
+
constructor(message, exitCode, stderr, status = 500, code = "git_error") {
|
|
2788
|
+
super(status, message, code);
|
|
2789
|
+
this.exitCode = exitCode;
|
|
2790
|
+
this.stderr = stderr;
|
|
2791
|
+
this.name = "GitError";
|
|
2792
|
+
}
|
|
2793
|
+
exitCode;
|
|
2794
|
+
stderr;
|
|
2795
|
+
};
|
|
2796
|
+
function assertAllowedGitArgs(args) {
|
|
2797
|
+
const sub = args[0];
|
|
2798
|
+
if (!sub || !ALLOWED_SUBCOMMANDS.has(sub)) {
|
|
2799
|
+
throw new GitError(`git sub-command not allowed: ${sub ?? "(none)"}`, null, "", 400, "git_subcommand_forbidden");
|
|
2800
|
+
}
|
|
2801
|
+
if (sub === "worktree" && args[1] !== "list") {
|
|
2802
|
+
throw new GitError(`git worktree ${args[1] ?? ""} is not allowed`, null, "", 400, "git_subcommand_forbidden");
|
|
2803
|
+
}
|
|
2804
|
+
for (const arg of args.slice(1)) {
|
|
2805
|
+
if (arg.includes("\0")) throw new GitError("NUL byte in git argument", null, "", 400, "git_bad_argument");
|
|
2806
|
+
for (const prefix of FORBIDDEN_OPTION_PREFIXES) {
|
|
2807
|
+
if (arg === prefix || arg.startsWith(prefix + "=")) {
|
|
2808
|
+
throw new GitError(`git option not allowed: ${arg}`, null, "", 400, "git_option_forbidden");
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
async function runGit(args, opts) {
|
|
2814
|
+
assertAllowedGitArgs(args);
|
|
2815
|
+
const okCodes = opts.okCodes ?? [0];
|
|
2816
|
+
return new Promise((resolve, reject) => {
|
|
2817
|
+
execFile(
|
|
2818
|
+
"git",
|
|
2819
|
+
[...args],
|
|
2820
|
+
{
|
|
2821
|
+
cwd: opts.cwd,
|
|
2822
|
+
timeout: opts.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS,
|
|
2823
|
+
maxBuffer: opts.maxBuffer ?? 256 * 1024 * 1024,
|
|
2824
|
+
encoding: "utf8",
|
|
2825
|
+
env: {
|
|
2826
|
+
...process.env,
|
|
2827
|
+
// Never take the index lock / refresh the index as a side effect of diff/status.
|
|
2828
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
2829
|
+
LC_ALL: "C",
|
|
2830
|
+
GIT_PAGER: "cat",
|
|
2831
|
+
PAGER: "cat",
|
|
2832
|
+
GIT_TERMINAL_PROMPT: "0"
|
|
2833
|
+
},
|
|
2834
|
+
windowsHide: true
|
|
2835
|
+
},
|
|
2836
|
+
(error, stdout, stderr) => {
|
|
2837
|
+
const err = error;
|
|
2838
|
+
if (err) {
|
|
2839
|
+
if (err.killed || err.signal === "SIGTERM") {
|
|
2840
|
+
reject(new GitError(`git ${args[0]} timed out`, null, stderr, 504, "git_timeout"));
|
|
2841
|
+
return;
|
|
2842
|
+
}
|
|
2843
|
+
if (err.code === "ENOENT") {
|
|
2844
|
+
reject(new GitError("git executable not found in PATH", null, "", 500, "git_missing"));
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
const code = typeof err.code === "number" ? err.code : -1;
|
|
2848
|
+
if (okCodes.includes(code)) {
|
|
2849
|
+
resolve({ stdout, stderr, code });
|
|
2850
|
+
return;
|
|
2851
|
+
}
|
|
2852
|
+
const msg = stderr.trim().split("\n")[0] || err.message;
|
|
2853
|
+
reject(new GitError(msg, code, stderr, 500, "git_failed"));
|
|
2854
|
+
return;
|
|
2855
|
+
}
|
|
2856
|
+
resolve({ stdout, stderr, code: 0 });
|
|
2857
|
+
}
|
|
2858
|
+
);
|
|
2859
|
+
});
|
|
2860
|
+
}
|
|
2861
|
+
async function refExists(cwd, ref) {
|
|
2862
|
+
try {
|
|
2863
|
+
await runGit(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { cwd });
|
|
2864
|
+
return true;
|
|
2865
|
+
} catch {
|
|
2866
|
+
return false;
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
async function revParse(cwd, ref) {
|
|
2870
|
+
try {
|
|
2871
|
+
const r = await runGit(["rev-parse", "--verify", "--quiet", ref], { cwd });
|
|
2872
|
+
return r.stdout.trim() || void 0;
|
|
2873
|
+
} catch {
|
|
2874
|
+
return void 0;
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
// packages/server/src/repo.ts
|
|
2879
|
+
import path from "path";
|
|
2880
|
+
import { realpath } from "fs/promises";
|
|
2881
|
+
async function safeRealpath(p) {
|
|
2882
|
+
try {
|
|
2883
|
+
return await realpath(p);
|
|
2884
|
+
} catch {
|
|
2885
|
+
return path.resolve(p);
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
async function resolveRepo(dir) {
|
|
2889
|
+
let top;
|
|
2890
|
+
try {
|
|
2891
|
+
const r = await runGit(["rev-parse", "--show-toplevel"], { cwd: dir });
|
|
2892
|
+
top = r.stdout.trim();
|
|
2893
|
+
} catch (e) {
|
|
2894
|
+
throw new HttpError(400, `${dir} is not inside a git repository`, "not_a_repo");
|
|
2895
|
+
}
|
|
2896
|
+
if (!top) throw new HttpError(400, `${dir} is not inside a git worktree (bare repository?)`, "not_a_repo");
|
|
2897
|
+
const root = await safeRealpath(top);
|
|
2898
|
+
const common = await runGit(["rev-parse", "--git-common-dir"], { cwd: root });
|
|
2899
|
+
const commonDir = await safeRealpath(path.resolve(root, common.stdout.trim()));
|
|
2900
|
+
const commonRoot = path.basename(commonDir) === ".git" ? path.dirname(commonDir) : root;
|
|
2901
|
+
return { root, commonRoot };
|
|
2902
|
+
}
|
|
2903
|
+
async function listWorktrees(ctx) {
|
|
2904
|
+
const r = await runGit(["worktree", "list", "--porcelain"], { cwd: ctx.root });
|
|
2905
|
+
const out = [];
|
|
2906
|
+
let cur = null;
|
|
2907
|
+
const flush = () => {
|
|
2908
|
+
if (cur && cur.path) {
|
|
2909
|
+
out.push({
|
|
2910
|
+
path: cur.path,
|
|
2911
|
+
head: cur.head ?? "",
|
|
2912
|
+
branch: cur.branch,
|
|
2913
|
+
isMain: false,
|
|
2914
|
+
detached: cur.detached ?? false,
|
|
2915
|
+
bare: cur.bare ?? false
|
|
2916
|
+
});
|
|
2917
|
+
}
|
|
2918
|
+
cur = null;
|
|
2919
|
+
};
|
|
2920
|
+
for (const line of r.stdout.split("\n")) {
|
|
2921
|
+
if (!line.trim()) {
|
|
2922
|
+
flush();
|
|
2923
|
+
continue;
|
|
2924
|
+
}
|
|
2925
|
+
if (line.startsWith("worktree ")) {
|
|
2926
|
+
flush();
|
|
2927
|
+
cur = { path: line.slice("worktree ".length) };
|
|
2928
|
+
} else if (!cur) {
|
|
2929
|
+
continue;
|
|
2930
|
+
} else if (line.startsWith("HEAD ")) cur.head = line.slice(5);
|
|
2931
|
+
else if (line.startsWith("branch ")) cur.branch = line.slice(7).replace(/^refs\/heads\//, "");
|
|
2932
|
+
else if (line === "detached") cur.detached = true;
|
|
2933
|
+
else if (line === "bare") cur.bare = true;
|
|
2934
|
+
}
|
|
2935
|
+
flush();
|
|
2936
|
+
for (const wt of out) {
|
|
2937
|
+
wt.path = await safeRealpath(wt.path);
|
|
2938
|
+
wt.isMain = wt.path === ctx.commonRoot;
|
|
2939
|
+
}
|
|
2940
|
+
return out;
|
|
2941
|
+
}
|
|
2942
|
+
async function getRepoInfo(ctx, defaultTarget) {
|
|
2943
|
+
const [branchRes, headRes, worktrees] = await Promise.all([
|
|
2944
|
+
runGit(["rev-parse", "--abbrev-ref", "HEAD"], { cwd: ctx.root }).catch(() => ({ stdout: "HEAD" })),
|
|
2945
|
+
runGit(["rev-parse", "HEAD"], { cwd: ctx.root }).catch(() => ({ stdout: "" })),
|
|
2946
|
+
listWorktrees(ctx)
|
|
2947
|
+
]);
|
|
2948
|
+
return {
|
|
2949
|
+
root: ctx.root,
|
|
2950
|
+
commonRoot: ctx.commonRoot,
|
|
2951
|
+
branch: branchRes.stdout.trim(),
|
|
2952
|
+
head: headRes.stdout.trim(),
|
|
2953
|
+
worktrees,
|
|
2954
|
+
defaultTarget
|
|
2955
|
+
};
|
|
2956
|
+
}
|
|
2957
|
+
|
|
2958
|
+
// packages/server/src/targets.ts
|
|
2959
|
+
import path2 from "path";
|
|
2960
|
+
import { readFile } from "fs/promises";
|
|
2961
|
+
|
|
2962
|
+
// packages/server/src/hash.ts
|
|
2963
|
+
import { createHash } from "crypto";
|
|
2964
|
+
function sha1(input) {
|
|
2965
|
+
return createHash("sha1").update(input).digest("hex");
|
|
2966
|
+
}
|
|
2967
|
+
function lineHash(content) {
|
|
2968
|
+
return sha1(content.trimEnd());
|
|
2969
|
+
}
|
|
2970
|
+
function hunkHash(lineContents) {
|
|
2971
|
+
return sha1(lineContents.map((l) => l.trimEnd()).join("\n").trim());
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
// packages/server/src/diffparse.ts
|
|
2975
|
+
function unquotePath(p) {
|
|
2976
|
+
if (!(p.length >= 2 && p.startsWith('"') && p.endsWith('"'))) return p;
|
|
2977
|
+
const inner = p.slice(1, -1);
|
|
2978
|
+
const bytes = [];
|
|
2979
|
+
for (let i = 0; i < inner.length; i++) {
|
|
2980
|
+
const ch = inner[i];
|
|
2981
|
+
if (ch !== "\\") {
|
|
2982
|
+
const buf = Buffer.from(ch, "utf8");
|
|
2983
|
+
for (const b of buf) bytes.push(b);
|
|
2984
|
+
continue;
|
|
2985
|
+
}
|
|
2986
|
+
const next = inner[i + 1];
|
|
2987
|
+
if (next === void 0) break;
|
|
2988
|
+
if (/[0-7]/.test(next)) {
|
|
2989
|
+
let oct = "";
|
|
2990
|
+
let j = i + 1;
|
|
2991
|
+
while (j < inner.length && oct.length < 3 && /[0-7]/.test(inner[j])) {
|
|
2992
|
+
oct += inner[j];
|
|
2993
|
+
j++;
|
|
2994
|
+
}
|
|
2995
|
+
bytes.push(parseInt(oct, 8));
|
|
2996
|
+
i = j - 1;
|
|
2997
|
+
continue;
|
|
2998
|
+
}
|
|
2999
|
+
const map = { n: 10, t: 9, r: 13, b: 8, f: 12, a: 7, v: 11, "\\": 92, '"': 34 };
|
|
3000
|
+
bytes.push(map[next] ?? next.charCodeAt(0));
|
|
3001
|
+
i++;
|
|
3002
|
+
}
|
|
3003
|
+
return Buffer.from(bytes).toString("utf8");
|
|
3004
|
+
}
|
|
3005
|
+
function stripPrefix(p, prefix) {
|
|
3006
|
+
const u = unquotePath(p);
|
|
3007
|
+
return u.startsWith(prefix) ? u.slice(2) : u;
|
|
3008
|
+
}
|
|
3009
|
+
function splitGitHeader(rest) {
|
|
3010
|
+
if (rest.startsWith('"')) {
|
|
3011
|
+
const m = /^("(?:[^"\\]|\\.)*")\s+("(?:[^"\\]|\\.)*")$/.exec(rest);
|
|
3012
|
+
if (m && m[1] && m[2]) return { a: stripPrefix(m[1], "a/"), b: stripPrefix(m[2], "b/") };
|
|
3013
|
+
}
|
|
3014
|
+
for (let i = 0; i < rest.length; i++) {
|
|
3015
|
+
if (rest[i] !== " ") continue;
|
|
3016
|
+
const left = rest.slice(0, i);
|
|
3017
|
+
const right = rest.slice(i + 1);
|
|
3018
|
+
if (left.startsWith("a/") && right.startsWith("b/") && left.slice(2) === right.slice(2)) {
|
|
3019
|
+
return { a: left.slice(2), b: stripPrefix(right, "b/") };
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
const idx = rest.indexOf(" b/");
|
|
3023
|
+
if (idx > 0) return { a: stripPrefix(rest.slice(0, idx), "a/"), b: stripPrefix(rest.slice(idx + 1), "b/") };
|
|
3024
|
+
return { a: rest, b: rest };
|
|
3025
|
+
}
|
|
3026
|
+
var HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/;
|
|
3027
|
+
function finalize(p) {
|
|
3028
|
+
let status = "modified";
|
|
3029
|
+
if (p.isNew) status = "added";
|
|
3030
|
+
else if (p.isDeleted) status = "deleted";
|
|
3031
|
+
else if (p.isRename) status = "renamed";
|
|
3032
|
+
let newPath = p.newPath ?? (p.fromPlus && p.fromPlus !== "/dev/null" ? p.fromPlus : void 0) ?? p.b;
|
|
3033
|
+
let oldPath = p.oldPath ?? (p.fromMinus && p.fromMinus !== "/dev/null" ? p.fromMinus : void 0) ?? p.a;
|
|
3034
|
+
if (status === "deleted") newPath = oldPath;
|
|
3035
|
+
if (status === "added") oldPath = newPath;
|
|
3036
|
+
let additions = 0;
|
|
3037
|
+
let deletions = 0;
|
|
3038
|
+
for (const h of p.hunks) {
|
|
3039
|
+
for (const l of h.lines) {
|
|
3040
|
+
if (l.type === "add") additions++;
|
|
3041
|
+
else if (l.type === "del") deletions++;
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
const hashInput = [status, oldPath, newPath, p.binary ? "binary" : "text", p.oldMode ?? "", p.newMode ?? "", ...p.raw].join("\n");
|
|
3045
|
+
const file = {
|
|
3046
|
+
path: newPath,
|
|
3047
|
+
status,
|
|
3048
|
+
additions,
|
|
3049
|
+
deletions,
|
|
3050
|
+
binary: p.binary,
|
|
3051
|
+
contentHash: sha1(hashInput),
|
|
3052
|
+
hunks: p.hunks
|
|
3053
|
+
};
|
|
3054
|
+
if (status === "renamed" && oldPath !== newPath) file.oldPath = oldPath;
|
|
3055
|
+
if (p.oldMode) file.oldMode = p.oldMode;
|
|
3056
|
+
if (p.newMode) file.newMode = p.newMode;
|
|
3057
|
+
return file;
|
|
3058
|
+
}
|
|
3059
|
+
function parseUnifiedDiff(text) {
|
|
3060
|
+
const files = [];
|
|
3061
|
+
const lines = text.split("\n");
|
|
3062
|
+
if (lines.length && lines[lines.length - 1] === "") lines.pop();
|
|
3063
|
+
let cur = null;
|
|
3064
|
+
let hunk = null;
|
|
3065
|
+
let oldNo = 0;
|
|
3066
|
+
let newNo = 0;
|
|
3067
|
+
let lastLine = null;
|
|
3068
|
+
const flush = () => {
|
|
3069
|
+
if (cur) files.push(finalize(cur));
|
|
3070
|
+
cur = null;
|
|
3071
|
+
hunk = null;
|
|
3072
|
+
lastLine = null;
|
|
3073
|
+
};
|
|
3074
|
+
for (let i = 0; i < lines.length; i++) {
|
|
3075
|
+
const line = lines[i];
|
|
3076
|
+
if (line.startsWith("diff --git ")) {
|
|
3077
|
+
flush();
|
|
3078
|
+
const { a, b } = splitGitHeader(line.slice("diff --git ".length));
|
|
3079
|
+
cur = { a, b, isNew: false, isDeleted: false, isRename: false, binary: false, hunks: [], raw: [] };
|
|
3080
|
+
continue;
|
|
3081
|
+
}
|
|
3082
|
+
if (!cur) continue;
|
|
3083
|
+
const c = cur;
|
|
3084
|
+
if (hunk) {
|
|
3085
|
+
const ch = line[0];
|
|
3086
|
+
if (ch === " " || ch === "+" || ch === "-" || line === "") {
|
|
3087
|
+
const content = line === "" ? "" : line.slice(1);
|
|
3088
|
+
let dl;
|
|
3089
|
+
if (ch === "+") dl = { type: "add", newLineNo: newNo++, content };
|
|
3090
|
+
else if (ch === "-") dl = { type: "del", oldLineNo: oldNo++, content };
|
|
3091
|
+
else dl = { type: "context", oldLineNo: oldNo++, newLineNo: newNo++, content };
|
|
3092
|
+
hunk.lines.push(dl);
|
|
3093
|
+
lastLine = dl;
|
|
3094
|
+
c.raw.push(line);
|
|
3095
|
+
continue;
|
|
3096
|
+
}
|
|
3097
|
+
if (line.startsWith("\\")) {
|
|
3098
|
+
if (lastLine) lastLine.noNewline = true;
|
|
3099
|
+
c.raw.push(line);
|
|
3100
|
+
continue;
|
|
3101
|
+
}
|
|
3102
|
+
hunk = null;
|
|
3103
|
+
}
|
|
3104
|
+
const hm = HUNK_RE.exec(line);
|
|
3105
|
+
if (hm) {
|
|
3106
|
+
hunk = {
|
|
3107
|
+
hash: "",
|
|
3108
|
+
oldStart: Number(hm[1]),
|
|
3109
|
+
oldLines: hm[2] === void 0 ? 1 : Number(hm[2]),
|
|
3110
|
+
newStart: Number(hm[3]),
|
|
3111
|
+
newLines: hm[4] === void 0 ? 1 : Number(hm[4]),
|
|
3112
|
+
header: hm[5] ?? "",
|
|
3113
|
+
lines: []
|
|
3114
|
+
};
|
|
3115
|
+
oldNo = hunk.oldStart;
|
|
3116
|
+
newNo = hunk.newStart;
|
|
3117
|
+
c.hunks.push(hunk);
|
|
3118
|
+
c.raw.push(line);
|
|
3119
|
+
continue;
|
|
3120
|
+
}
|
|
3121
|
+
if (line.startsWith("--- ")) {
|
|
3122
|
+
c.fromMinus = stripPrefix(line.slice(4), "a/");
|
|
3123
|
+
continue;
|
|
3124
|
+
}
|
|
3125
|
+
if (line.startsWith("+++ ")) {
|
|
3126
|
+
c.fromPlus = stripPrefix(line.slice(4), "b/");
|
|
3127
|
+
continue;
|
|
3128
|
+
}
|
|
3129
|
+
if (line.startsWith("new file mode ")) {
|
|
3130
|
+
c.isNew = true;
|
|
3131
|
+
c.newMode = line.slice("new file mode ".length);
|
|
3132
|
+
continue;
|
|
3133
|
+
}
|
|
3134
|
+
if (line.startsWith("deleted file mode ")) {
|
|
3135
|
+
c.isDeleted = true;
|
|
3136
|
+
c.oldMode = line.slice("deleted file mode ".length);
|
|
3137
|
+
continue;
|
|
3138
|
+
}
|
|
3139
|
+
if (line.startsWith("old mode ")) {
|
|
3140
|
+
c.oldMode = line.slice("old mode ".length);
|
|
3141
|
+
continue;
|
|
3142
|
+
}
|
|
3143
|
+
if (line.startsWith("new mode ")) {
|
|
3144
|
+
c.newMode = line.slice("new mode ".length);
|
|
3145
|
+
continue;
|
|
3146
|
+
}
|
|
3147
|
+
if (line.startsWith("rename from ")) {
|
|
3148
|
+
c.isRename = true;
|
|
3149
|
+
c.oldPath = unquotePath(line.slice("rename from ".length));
|
|
3150
|
+
continue;
|
|
3151
|
+
}
|
|
3152
|
+
if (line.startsWith("rename to ")) {
|
|
3153
|
+
c.isRename = true;
|
|
3154
|
+
c.newPath = unquotePath(line.slice("rename to ".length));
|
|
3155
|
+
continue;
|
|
3156
|
+
}
|
|
3157
|
+
if (line.startsWith("copy from ")) {
|
|
3158
|
+
c.oldPath = unquotePath(line.slice("copy from ".length));
|
|
3159
|
+
continue;
|
|
3160
|
+
}
|
|
3161
|
+
if (line.startsWith("copy to ")) {
|
|
3162
|
+
c.isNew = true;
|
|
3163
|
+
c.newPath = unquotePath(line.slice("copy to ".length));
|
|
3164
|
+
continue;
|
|
3165
|
+
}
|
|
3166
|
+
if (line.startsWith("Binary files ") || line === "GIT binary patch") {
|
|
3167
|
+
c.binary = true;
|
|
3168
|
+
c.raw.push(line);
|
|
3169
|
+
continue;
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
flush();
|
|
3173
|
+
for (const f of files) {
|
|
3174
|
+
for (const h of f.hunks) {
|
|
3175
|
+
h.hash = hunkHash(h.lines.map((l) => l.content));
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
return files;
|
|
3179
|
+
}
|
|
3180
|
+
|
|
3181
|
+
// packages/server/src/targets.ts
|
|
3182
|
+
var DIFF_BASE_ARGS = ["diff", "--no-color", "--no-ext-diff", "-U3", "-M", "--find-renames"];
|
|
3183
|
+
function resolveTargetContext(repo, worktrees, key) {
|
|
3184
|
+
let target;
|
|
3185
|
+
try {
|
|
3186
|
+
target = parseTargetKey(key);
|
|
3187
|
+
} catch (e) {
|
|
3188
|
+
if (e instanceof TargetKeyError) throw badRequest(e.message, "invalid_target");
|
|
3189
|
+
throw e;
|
|
3190
|
+
}
|
|
3191
|
+
let cwd = repo.root;
|
|
3192
|
+
if (target.worktree) {
|
|
3193
|
+
const wt = worktrees.find((w) => w.path === target.worktree);
|
|
3194
|
+
if (!wt) throw badRequest(`unknown worktree: ${target.worktree}`, "unknown_worktree");
|
|
3195
|
+
cwd = wt.path;
|
|
3196
|
+
}
|
|
3197
|
+
return { key, target, cwd };
|
|
3198
|
+
}
|
|
3199
|
+
async function hasHead(cwd) {
|
|
3200
|
+
return refExists(cwd, "HEAD");
|
|
3201
|
+
}
|
|
3202
|
+
async function diffArgs(ctx) {
|
|
3203
|
+
const t = ctx.target;
|
|
3204
|
+
switch (t.kind) {
|
|
3205
|
+
case "working":
|
|
3206
|
+
return [...DIFF_BASE_ARGS];
|
|
3207
|
+
case "staged":
|
|
3208
|
+
return [...DIFF_BASE_ARGS, "--cached"];
|
|
3209
|
+
case "all":
|
|
3210
|
+
return [...DIFF_BASE_ARGS, await hasHead(ctx.cwd) ? "HEAD" : EMPTY_TREE_SHA];
|
|
3211
|
+
case "commit": {
|
|
3212
|
+
if (!await refExists(ctx.cwd, t.sha)) throw badRequest(`unknown commit: ${t.sha}`, "unknown_ref");
|
|
3213
|
+
const parent = await revParse(ctx.cwd, `${t.sha}^`);
|
|
3214
|
+
return [...DIFF_BASE_ARGS, parent ?? EMPTY_TREE_SHA, t.sha];
|
|
3215
|
+
}
|
|
3216
|
+
case "range": {
|
|
3217
|
+
if (!await refExists(ctx.cwd, t.base)) throw badRequest(`unknown ref: ${t.base}`, "unknown_ref");
|
|
3218
|
+
if (!await refExists(ctx.cwd, t.head)) throw badRequest(`unknown ref: ${t.head}`, "unknown_ref");
|
|
3219
|
+
return [...DIFF_BASE_ARGS, `${t.base}...${t.head}`];
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
function includesUntracked(t) {
|
|
3224
|
+
return t.kind === "working" || t.kind === "all";
|
|
3225
|
+
}
|
|
3226
|
+
async function listUntracked(cwd) {
|
|
3227
|
+
const r = await runGit(["ls-files", "--others", "--exclude-standard", "-z"], { cwd });
|
|
3228
|
+
return r.stdout.split("\0").filter(Boolean);
|
|
3229
|
+
}
|
|
3230
|
+
async function isUntracked(cwd, file) {
|
|
3231
|
+
const r = await runGit(["ls-files", "--others", "--exclude-standard", "-z", "--", file], { cwd });
|
|
3232
|
+
return r.stdout.split("\0").filter(Boolean).includes(file);
|
|
3233
|
+
}
|
|
3234
|
+
async function untrackedDiff(cwd, file) {
|
|
3235
|
+
const r = await runGit(["diff", "--no-color", "--no-ext-diff", "-U3", "--no-index", "--", "/dev/null", file], {
|
|
3236
|
+
cwd,
|
|
3237
|
+
okCodes: [0, 1]
|
|
3238
|
+
});
|
|
3239
|
+
const parsed = parseUnifiedDiff(r.stdout);
|
|
3240
|
+
const f = parsed[0];
|
|
3241
|
+
if (!f) return void 0;
|
|
3242
|
+
f.path = file;
|
|
3243
|
+
f.status = "added";
|
|
3244
|
+
f.untracked = true;
|
|
3245
|
+
delete f.oldPath;
|
|
3246
|
+
return f;
|
|
3247
|
+
}
|
|
3248
|
+
async function mapLimit(items, limit, fn) {
|
|
3249
|
+
const results = new Array(items.length);
|
|
3250
|
+
let next = 0;
|
|
3251
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
3252
|
+
while (next < items.length) {
|
|
3253
|
+
const i = next++;
|
|
3254
|
+
results[i] = await fn(items[i]);
|
|
3255
|
+
}
|
|
3256
|
+
});
|
|
3257
|
+
await Promise.all(workers);
|
|
3258
|
+
return results;
|
|
3259
|
+
}
|
|
3260
|
+
async function listTargetDiffs(ctx) {
|
|
3261
|
+
const args = await diffArgs(ctx);
|
|
3262
|
+
const r = await runGit(args, { cwd: ctx.cwd });
|
|
3263
|
+
const files = parseUnifiedDiff(r.stdout);
|
|
3264
|
+
if (includesUntracked(ctx.target)) {
|
|
3265
|
+
const untracked = await listUntracked(ctx.cwd);
|
|
3266
|
+
const extra = await mapLimit(untracked, 8, (f) => untrackedDiff(ctx.cwd, f).catch(() => void 0));
|
|
3267
|
+
for (const f of extra) if (f) files.push(f);
|
|
3268
|
+
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
3269
|
+
}
|
|
3270
|
+
return files;
|
|
3271
|
+
}
|
|
3272
|
+
function toSummary(f) {
|
|
3273
|
+
const { hunks: _hunks, ...rest } = f;
|
|
3274
|
+
return rest;
|
|
3275
|
+
}
|
|
3276
|
+
async function getFileDiff(ctx, filePath, hints = {}) {
|
|
3277
|
+
if (!filePath || filePath.startsWith("/") || filePath.split("/").includes("..")) {
|
|
3278
|
+
throw badRequest(`invalid path: ${filePath}`, "invalid_path");
|
|
3279
|
+
}
|
|
3280
|
+
if (includesUntracked(ctx.target) && (hints.untracked || await isUntracked(ctx.cwd, filePath))) {
|
|
3281
|
+
return untrackedDiff(ctx.cwd, filePath);
|
|
3282
|
+
}
|
|
3283
|
+
const args = await diffArgs(ctx);
|
|
3284
|
+
const pathspec = [filePath];
|
|
3285
|
+
if (hints.oldPath && hints.oldPath !== filePath) pathspec.push(hints.oldPath);
|
|
3286
|
+
const r = await runGit([...args, "--", ...pathspec], { cwd: ctx.cwd });
|
|
3287
|
+
const files = parseUnifiedDiff(r.stdout);
|
|
3288
|
+
return files.find((f) => f.path === filePath) ?? files[0];
|
|
3289
|
+
}
|
|
3290
|
+
async function refForSide(ctx, side) {
|
|
3291
|
+
const t = ctx.target;
|
|
3292
|
+
switch (t.kind) {
|
|
3293
|
+
case "working":
|
|
3294
|
+
return side === "new" ? void 0 : ":0";
|
|
3295
|
+
case "staged":
|
|
3296
|
+
return side === "new" ? ":0" : "HEAD";
|
|
3297
|
+
case "all":
|
|
3298
|
+
return side === "new" ? void 0 : "HEAD";
|
|
3299
|
+
case "commit":
|
|
3300
|
+
if (side === "new") return t.sha;
|
|
3301
|
+
return await revParse(ctx.cwd, `${t.sha}^`) ?? EMPTY_TREE_SHA;
|
|
3302
|
+
case "range":
|
|
3303
|
+
return side === "new" ? t.head : t.base;
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
async function getFullFile(ctx, filePath, side) {
|
|
3307
|
+
if (!filePath || filePath.startsWith("/") || filePath.split("/").includes("..")) {
|
|
3308
|
+
throw badRequest(`invalid path: ${filePath}`, "invalid_path");
|
|
3309
|
+
}
|
|
3310
|
+
const ref = await refForSide(ctx, side);
|
|
3311
|
+
if (ref === void 0) {
|
|
3312
|
+
try {
|
|
3313
|
+
const buf = await readFile(path2.join(ctx.cwd, filePath));
|
|
3314
|
+
return buf.toString("utf8");
|
|
3315
|
+
} catch {
|
|
3316
|
+
return null;
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
try {
|
|
3320
|
+
const r = await runGit(["show", `${ref}:${filePath}`], { cwd: ctx.cwd });
|
|
3321
|
+
return r.stdout;
|
|
3322
|
+
} catch (e) {
|
|
3323
|
+
if (e instanceof HttpError && e.code === "git_failed") return null;
|
|
3324
|
+
throw e;
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
// packages/server/src/anchor.ts
|
|
3329
|
+
function sideLines(diff, side) {
|
|
3330
|
+
const out = [];
|
|
3331
|
+
diff.hunks.forEach((h, hunkIndex) => {
|
|
3332
|
+
let hunkOffset = 0;
|
|
3333
|
+
for (const l of h.lines) {
|
|
3334
|
+
if (side === "new" && l.type !== "del" && l.newLineNo !== void 0) {
|
|
3335
|
+
out.push({ line: l.newLineNo, hash: lineHash(l.content), content: l.content, hunkIndex, hunkOffset: hunkOffset++ });
|
|
3336
|
+
} else if (side === "old" && l.type !== "add" && l.oldLineNo !== void 0) {
|
|
3337
|
+
out.push({ line: l.oldLineNo, hash: lineHash(l.content), content: l.content, hunkIndex, hunkOffset: hunkOffset++ });
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
});
|
|
3341
|
+
return out;
|
|
3342
|
+
}
|
|
3343
|
+
var CONTEXT = 3;
|
|
3344
|
+
function anchorAt(lines, diff, start, count) {
|
|
3345
|
+
const covered = lines.slice(start, start + count);
|
|
3346
|
+
const first = covered[0];
|
|
3347
|
+
const last = covered[covered.length - 1];
|
|
3348
|
+
return {
|
|
3349
|
+
anchor: {
|
|
3350
|
+
hunkHash: diff.hunks[first.hunkIndex].hash,
|
|
3351
|
+
lineHashes: covered.map((l) => l.hash),
|
|
3352
|
+
contextBefore: lines.slice(Math.max(0, start - CONTEXT), start).map((l) => l.hash),
|
|
3353
|
+
contextAfter: lines.slice(start + count, start + count + CONTEXT).map((l) => l.hash),
|
|
3354
|
+
hunkLineOffset: first.hunkOffset
|
|
3355
|
+
},
|
|
3356
|
+
snippet: covered.map((l) => l.content),
|
|
3357
|
+
startLine: first.line,
|
|
3358
|
+
endLine: last.line
|
|
3359
|
+
};
|
|
3360
|
+
}
|
|
3361
|
+
function buildAnchor(diff, side, startLine, endLine) {
|
|
3362
|
+
if (endLine < startLine) [startLine, endLine] = [endLine, startLine];
|
|
3363
|
+
const lines = sideLines(diff, side);
|
|
3364
|
+
const start = lines.findIndex((l) => l.line === startLine);
|
|
3365
|
+
if (start < 0) return void 0;
|
|
3366
|
+
const count = endLine - startLine + 1;
|
|
3367
|
+
const covered = lines.slice(start, start + count);
|
|
3368
|
+
if (covered.length !== count) return void 0;
|
|
3369
|
+
for (let i = 0; i < count; i++) {
|
|
3370
|
+
const l = covered[i];
|
|
3371
|
+
if (l.line !== startLine + i) return void 0;
|
|
3372
|
+
if (l.hunkIndex !== covered[0].hunkIndex) return void 0;
|
|
3373
|
+
}
|
|
3374
|
+
return anchorAt(lines, diff, start, count);
|
|
3375
|
+
}
|
|
3376
|
+
function matchesAt(lines, start, hashes) {
|
|
3377
|
+
if (start < 0 || start + hashes.length > lines.length) return false;
|
|
3378
|
+
for (let i = 0; i < hashes.length; i++) {
|
|
3379
|
+
if (lines[start + i].hash !== hashes[i]) return false;
|
|
3380
|
+
}
|
|
3381
|
+
return true;
|
|
3382
|
+
}
|
|
3383
|
+
function contextScore(lines, start, count, anchor) {
|
|
3384
|
+
let score = 0;
|
|
3385
|
+
const before = anchor.contextBefore;
|
|
3386
|
+
for (let i = 0; i < before.length; i++) {
|
|
3387
|
+
const idx = start - before.length + i;
|
|
3388
|
+
if (idx >= 0 && lines[idx].hash === before[i]) score++;
|
|
3389
|
+
}
|
|
3390
|
+
const after = anchor.contextAfter;
|
|
3391
|
+
for (let i = 0; i < after.length; i++) {
|
|
3392
|
+
const idx = start + count + i;
|
|
3393
|
+
if (idx < lines.length && lines[idx].hash === after[i]) score++;
|
|
3394
|
+
}
|
|
3395
|
+
return score;
|
|
3396
|
+
}
|
|
3397
|
+
function locateAnchor(diff, side, anchor) {
|
|
3398
|
+
const lines = sideLines(diff, side);
|
|
3399
|
+
const n = anchor.lineHashes.length;
|
|
3400
|
+
if (n === 0) return void 0;
|
|
3401
|
+
for (let hi = 0; hi < diff.hunks.length; hi++) {
|
|
3402
|
+
if (diff.hunks[hi].hash !== anchor.hunkHash) continue;
|
|
3403
|
+
const idx = lines.findIndex((l) => l.hunkIndex === hi && l.hunkOffset === anchor.hunkLineOffset);
|
|
3404
|
+
if (idx >= 0 && matchesAt(lines, idx, anchor.lineHashes)) return idx;
|
|
3405
|
+
}
|
|
3406
|
+
const candidates = [];
|
|
3407
|
+
for (let i = 0; i + n <= lines.length; i++) {
|
|
3408
|
+
if (matchesAt(lines, i, anchor.lineHashes)) candidates.push(i);
|
|
3409
|
+
}
|
|
3410
|
+
if (candidates.length === 0) return void 0;
|
|
3411
|
+
if (candidates.length === 1) return candidates[0];
|
|
3412
|
+
let best = [];
|
|
3413
|
+
let bestScore = -1;
|
|
3414
|
+
for (const c of candidates) {
|
|
3415
|
+
const s = contextScore(lines, c, n, anchor);
|
|
3416
|
+
if (s > bestScore) {
|
|
3417
|
+
bestScore = s;
|
|
3418
|
+
best = [c];
|
|
3419
|
+
} else if (s === bestScore) {
|
|
3420
|
+
best.push(c);
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
return best.length === 1 ? best[0] : void 0;
|
|
3424
|
+
}
|
|
3425
|
+
function reanchorComment(comment, diff, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
3426
|
+
const orphan = () => comment.status === "orphaned" ? comment : { ...comment, status: "orphaned", updatedAt: now };
|
|
3427
|
+
if (!diff || diff.binary) return orphan();
|
|
3428
|
+
const idx = locateAnchor(diff, comment.side, comment.anchor);
|
|
3429
|
+
if (idx === void 0) return orphan();
|
|
3430
|
+
const lines = sideLines(diff, comment.side);
|
|
3431
|
+
const res = anchorAt(lines, diff, idx, comment.anchor.lineHashes.length);
|
|
3432
|
+
const status = comment.exportedAt ? "exported" : "active";
|
|
3433
|
+
const unchanged = comment.status === status && comment.startLine === res.startLine && comment.endLine === res.endLine && comment.anchor.hunkHash === res.anchor.hunkHash;
|
|
3434
|
+
if (unchanged) return comment;
|
|
3435
|
+
return {
|
|
3436
|
+
...comment,
|
|
3437
|
+
startLine: res.startLine,
|
|
3438
|
+
endLine: res.endLine,
|
|
3439
|
+
codeSnippet: res.snippet,
|
|
3440
|
+
anchor: res.anchor,
|
|
3441
|
+
status,
|
|
3442
|
+
updatedAt: now
|
|
3443
|
+
};
|
|
3444
|
+
}
|
|
3445
|
+
|
|
3446
|
+
// packages/server/src/state.ts
|
|
3447
|
+
import os from "os";
|
|
3448
|
+
import path3 from "path";
|
|
3449
|
+
import { mkdir, open, readFile as readFile2, rename, stat, unlink, writeFile } from "fs/promises";
|
|
3450
|
+
function dataDir() {
|
|
3451
|
+
const xdg = process.env.XDG_DATA_HOME;
|
|
3452
|
+
const base = xdg && xdg.trim() ? xdg : path3.join(os.homedir(), ".local", "share");
|
|
3453
|
+
return path3.join(base, "warden");
|
|
3454
|
+
}
|
|
3455
|
+
function repoHash(repoRoot) {
|
|
3456
|
+
return sha1(repoRoot).slice(0, 12);
|
|
3457
|
+
}
|
|
3458
|
+
function stateFilePath(repoRoot, baseDir = dataDir()) {
|
|
3459
|
+
return path3.join(baseDir, repoHash(repoRoot), "state.json");
|
|
3460
|
+
}
|
|
3461
|
+
function defaultPrefs() {
|
|
3462
|
+
return { viewMode: "unified", nvimSocketByRoot: {} };
|
|
3463
|
+
}
|
|
3464
|
+
function defaultState(repoRoot) {
|
|
3465
|
+
return { schemaVersion: 1, repoRoot, targets: {}, issues: [], prefs: defaultPrefs() };
|
|
3466
|
+
}
|
|
3467
|
+
function ensureTarget(state, key) {
|
|
3468
|
+
let t = state.targets[key];
|
|
3469
|
+
if (!t) {
|
|
3470
|
+
t = { viewed: {}, comments: [] };
|
|
3471
|
+
state.targets[key] = t;
|
|
3472
|
+
}
|
|
3473
|
+
return t;
|
|
3474
|
+
}
|
|
3475
|
+
function normalise(raw2, repoRoot) {
|
|
3476
|
+
const base = defaultState(repoRoot);
|
|
3477
|
+
if (!raw2 || typeof raw2 !== "object") return base;
|
|
3478
|
+
const r = raw2;
|
|
3479
|
+
if (r.schemaVersion !== 1) return base;
|
|
3480
|
+
const targets = {};
|
|
3481
|
+
for (const [k, v] of Object.entries(r.targets ?? {})) {
|
|
3482
|
+
if (!v || typeof v !== "object") continue;
|
|
3483
|
+
targets[k] = {
|
|
3484
|
+
viewed: typeof v.viewed === "object" && v.viewed ? v.viewed : {},
|
|
3485
|
+
comments: Array.isArray(v.comments) ? v.comments : []
|
|
3486
|
+
};
|
|
3487
|
+
}
|
|
3488
|
+
return {
|
|
3489
|
+
schemaVersion: 1,
|
|
3490
|
+
repoRoot: r.repoRoot ?? repoRoot,
|
|
3491
|
+
targets,
|
|
3492
|
+
issues: Array.isArray(r.issues) ? r.issues : [],
|
|
3493
|
+
prefs: { ...defaultPrefs(), ...r.prefs ?? {}, nvimSocketByRoot: r.prefs?.nvimSocketByRoot ?? {} }
|
|
3494
|
+
};
|
|
3495
|
+
}
|
|
3496
|
+
var LOCK_STALE_MS = 5e3;
|
|
3497
|
+
var LOCK_WAIT_MS = 5e3;
|
|
3498
|
+
async function sleep(ms) {
|
|
3499
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
3500
|
+
}
|
|
3501
|
+
var StateStore = class {
|
|
3502
|
+
constructor(file, repoRoot) {
|
|
3503
|
+
this.file = file;
|
|
3504
|
+
this.repoRoot = repoRoot;
|
|
3505
|
+
}
|
|
3506
|
+
file;
|
|
3507
|
+
repoRoot;
|
|
3508
|
+
queue = Promise.resolve();
|
|
3509
|
+
async load() {
|
|
3510
|
+
try {
|
|
3511
|
+
const text = await readFile2(this.file, "utf8");
|
|
3512
|
+
return normalise(JSON.parse(text), this.repoRoot);
|
|
3513
|
+
} catch (e) {
|
|
3514
|
+
const err = e;
|
|
3515
|
+
if (err.code === "ENOENT") return defaultState(this.repoRoot);
|
|
3516
|
+
if (e instanceof SyntaxError) {
|
|
3517
|
+
try {
|
|
3518
|
+
await rename(this.file, `${this.file}.corrupt-${Date.now()}`);
|
|
3519
|
+
} catch {
|
|
3520
|
+
}
|
|
3521
|
+
return defaultState(this.repoRoot);
|
|
3522
|
+
}
|
|
3523
|
+
throw e;
|
|
3524
|
+
}
|
|
3525
|
+
}
|
|
3526
|
+
/** Apply a mutation under lock. The callback receives the freshest on-disk state. */
|
|
3527
|
+
update(fn) {
|
|
3528
|
+
const run = async () => {
|
|
3529
|
+
await mkdir(path3.dirname(this.file), { recursive: true });
|
|
3530
|
+
const release = await this.acquireLock();
|
|
3531
|
+
try {
|
|
3532
|
+
const state = await this.load();
|
|
3533
|
+
const result = await fn(state);
|
|
3534
|
+
await this.writeAtomic(state);
|
|
3535
|
+
return result;
|
|
3536
|
+
} finally {
|
|
3537
|
+
await release();
|
|
3538
|
+
}
|
|
3539
|
+
};
|
|
3540
|
+
const p = this.queue.then(run, run);
|
|
3541
|
+
this.queue = p.catch(() => void 0);
|
|
3542
|
+
return p;
|
|
3543
|
+
}
|
|
3544
|
+
async writeAtomic(state) {
|
|
3545
|
+
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`;
|
|
3546
|
+
await writeFile(tmp, JSON.stringify(state, null, 2) + "\n", "utf8");
|
|
3547
|
+
await rename(tmp, this.file);
|
|
3548
|
+
}
|
|
3549
|
+
async acquireLock() {
|
|
3550
|
+
const lock = `${this.file}.lock`;
|
|
3551
|
+
const started = Date.now();
|
|
3552
|
+
for (; ; ) {
|
|
3553
|
+
try {
|
|
3554
|
+
const fh = await open(lock, "wx");
|
|
3555
|
+
await fh.writeFile(String(process.pid));
|
|
3556
|
+
await fh.close();
|
|
3557
|
+
return async () => {
|
|
3558
|
+
try {
|
|
3559
|
+
await unlink(lock);
|
|
3560
|
+
} catch {
|
|
3561
|
+
}
|
|
3562
|
+
};
|
|
3563
|
+
} catch (e) {
|
|
3564
|
+
const err = e;
|
|
3565
|
+
if (err.code !== "EEXIST") throw e;
|
|
3566
|
+
try {
|
|
3567
|
+
const st = await stat(lock);
|
|
3568
|
+
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
|
|
3569
|
+
await unlink(lock).catch(() => void 0);
|
|
3570
|
+
continue;
|
|
3571
|
+
}
|
|
3572
|
+
} catch {
|
|
3573
|
+
continue;
|
|
3574
|
+
}
|
|
3575
|
+
if (Date.now() - started > LOCK_WAIT_MS) {
|
|
3576
|
+
throw new Error(`timed out waiting for state lock ${lock}`);
|
|
3577
|
+
}
|
|
3578
|
+
await sleep(20);
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
};
|
|
3583
|
+
|
|
3584
|
+
// packages/server/src/export.ts
|
|
3585
|
+
var LANG_BY_EXT = {
|
|
3586
|
+
ts: "ts",
|
|
3587
|
+
tsx: "tsx",
|
|
3588
|
+
js: "js",
|
|
3589
|
+
jsx: "jsx",
|
|
3590
|
+
mjs: "js",
|
|
3591
|
+
cjs: "js",
|
|
3592
|
+
json: "json",
|
|
3593
|
+
css: "css",
|
|
3594
|
+
scss: "scss",
|
|
3595
|
+
less: "less",
|
|
3596
|
+
html: "html",
|
|
3597
|
+
vue: "vue",
|
|
3598
|
+
svelte: "svelte",
|
|
3599
|
+
md: "md",
|
|
3600
|
+
mdx: "mdx",
|
|
3601
|
+
py: "python",
|
|
3602
|
+
rb: "ruby",
|
|
3603
|
+
go: "go",
|
|
3604
|
+
rs: "rust",
|
|
3605
|
+
java: "java",
|
|
3606
|
+
kt: "kotlin",
|
|
3607
|
+
c: "c",
|
|
3608
|
+
h: "c",
|
|
3609
|
+
cc: "cpp",
|
|
3610
|
+
cpp: "cpp",
|
|
3611
|
+
hpp: "cpp",
|
|
3612
|
+
cs: "csharp",
|
|
3613
|
+
php: "php",
|
|
3614
|
+
sh: "bash",
|
|
3615
|
+
bash: "bash",
|
|
3616
|
+
zsh: "bash",
|
|
3617
|
+
yml: "yaml",
|
|
3618
|
+
yaml: "yaml",
|
|
3619
|
+
toml: "toml",
|
|
3620
|
+
sql: "sql",
|
|
3621
|
+
graphql: "graphql",
|
|
3622
|
+
lua: "lua",
|
|
3623
|
+
swift: "swift",
|
|
3624
|
+
dart: "dart"
|
|
3625
|
+
};
|
|
3626
|
+
function langForPath(filePath) {
|
|
3627
|
+
const m = /\.([A-Za-z0-9]+)$/.exec(filePath);
|
|
3628
|
+
if (!m || !m[1]) return "";
|
|
3629
|
+
return LANG_BY_EXT[m[1].toLowerCase()] ?? m[1].toLowerCase();
|
|
3630
|
+
}
|
|
3631
|
+
function formatCommentSection(c) {
|
|
3632
|
+
const range = c.startLine === c.endLine ? `${c.startLine}` : `${c.startLine}-${c.endLine}`;
|
|
3633
|
+
const width = String(c.endLine).length;
|
|
3634
|
+
const code = c.codeSnippet.map((line, i) => `${String(c.startLine + i).padStart(width, " ")} | ${line}`).join("\n");
|
|
3635
|
+
const lang = langForPath(c.filePath);
|
|
3636
|
+
const body = c.body.replace(/\r\n/g, "\n").split("\n").map((l) => l ? `> ${l}` : ">").join("\n");
|
|
3637
|
+
const fence = code.includes("```") ? "````" : "```";
|
|
3638
|
+
const orphanNote = c.status === "orphaned" ? " [orphaned: original location no longer exists]" : "";
|
|
3639
|
+
return [`## ${c.filePath}:${range} (${c.side})${orphanNote}`, `${fence}${lang}`, code, fence, body].join("\n");
|
|
3640
|
+
}
|
|
3641
|
+
function formatCommentsExport({ repoRoot, comments }) {
|
|
3642
|
+
const targets = [...new Set(comments.map((c) => c.targetKey))];
|
|
3643
|
+
const head = ["# Review comments", `Target: ${targets.join(", ") || "-"}`, `Repo: ${repoRoot}`, `Count: ${comments.length}`];
|
|
3644
|
+
const sections = comments.map(formatCommentSection);
|
|
3645
|
+
return [head.join("\n"), ...sections].join("\n\n") + "\n";
|
|
3646
|
+
}
|
|
3647
|
+
function formatIssueExport({ repoRoot, issue, comments }) {
|
|
3648
|
+
const targets = [...new Set(comments.map((c) => c.targetKey))];
|
|
3649
|
+
const head = [
|
|
3650
|
+
`# Issue: ${issue.title}`,
|
|
3651
|
+
`Status: ${issue.status}`,
|
|
3652
|
+
`Target: ${targets.join(", ") || "-"}`,
|
|
3653
|
+
`Repo: ${repoRoot}`,
|
|
3654
|
+
`Count: ${comments.length}`
|
|
3655
|
+
];
|
|
3656
|
+
const parts = [head.join("\n")];
|
|
3657
|
+
if (issue.body.trim()) parts.push(issue.body.trim());
|
|
3658
|
+
parts.push(...comments.map(formatCommentSection));
|
|
3659
|
+
return parts.join("\n\n") + "\n";
|
|
3660
|
+
}
|
|
3661
|
+
|
|
3662
|
+
// packages/server/src/nvim.ts
|
|
3663
|
+
import os2 from "os";
|
|
3664
|
+
import path4 from "path";
|
|
3665
|
+
import { execFile as execFile2 } from "child_process";
|
|
3666
|
+
import { readdir, stat as stat2 } from "fs/promises";
|
|
3667
|
+
var QUERY_TIMEOUT_MS = 500;
|
|
3668
|
+
var CACHE_TTL_MS = 1e4;
|
|
3669
|
+
function execNvim(args, timeoutMs) {
|
|
3670
|
+
return new Promise((resolve) => {
|
|
3671
|
+
execFile2("nvim", args, { timeout: timeoutMs, encoding: "utf8", windowsHide: true }, (error, stdout, stderr) => {
|
|
3672
|
+
if (error) {
|
|
3673
|
+
const err = error;
|
|
3674
|
+
resolve({ ok: false, stdout, stderr, missing: err.code === "ENOENT" });
|
|
3675
|
+
return;
|
|
3676
|
+
}
|
|
3677
|
+
resolve({ ok: true, stdout, stderr, missing: false });
|
|
3678
|
+
});
|
|
3679
|
+
});
|
|
3680
|
+
}
|
|
3681
|
+
function socketDirs(env = process.env) {
|
|
3682
|
+
const dirs = [];
|
|
3683
|
+
if (env.XDG_RUNTIME_DIR) dirs.push(env.XDG_RUNTIME_DIR);
|
|
3684
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : void 0;
|
|
3685
|
+
if (uid !== void 0) dirs.push(`/run/user/${uid}`);
|
|
3686
|
+
let user = env.USER || env.LOGNAME;
|
|
3687
|
+
if (!user) {
|
|
3688
|
+
try {
|
|
3689
|
+
user = os2.userInfo().username;
|
|
3690
|
+
} catch {
|
|
3691
|
+
user = void 0;
|
|
3692
|
+
}
|
|
3693
|
+
}
|
|
3694
|
+
const tmp = env.TMPDIR || "/tmp";
|
|
3695
|
+
if (user) dirs.push(path4.join(tmp, `nvim.${user}`));
|
|
3696
|
+
if (env.NVIM_LISTEN_ADDRESS) dirs.push(path4.dirname(env.NVIM_LISTEN_ADDRESS));
|
|
3697
|
+
return [...new Set(dirs)];
|
|
3698
|
+
}
|
|
3699
|
+
var SOCKET_NAME = /^nvim\.(\d+)\.\d+$/;
|
|
3700
|
+
async function isSocket(p) {
|
|
3701
|
+
try {
|
|
3702
|
+
return (await stat2(p)).isSocket();
|
|
3703
|
+
} catch {
|
|
3704
|
+
return false;
|
|
3705
|
+
}
|
|
3706
|
+
}
|
|
3707
|
+
async function findSockets(dirs = socketDirs()) {
|
|
3708
|
+
const found = /* @__PURE__ */ new Map();
|
|
3709
|
+
const visit = async (dir, depth) => {
|
|
3710
|
+
let entries;
|
|
3711
|
+
try {
|
|
3712
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
3713
|
+
} catch {
|
|
3714
|
+
return;
|
|
3715
|
+
}
|
|
3716
|
+
for (const ent of entries) {
|
|
3717
|
+
const full = path4.join(dir, ent.name);
|
|
3718
|
+
const m = SOCKET_NAME.exec(ent.name);
|
|
3719
|
+
if (m && (ent.isSocket() || await isSocket(full))) {
|
|
3720
|
+
found.set(full, Number(m[1]));
|
|
3721
|
+
} else if (ent.isDirectory() && depth < 1) {
|
|
3722
|
+
await visit(full, depth + 1);
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
};
|
|
3726
|
+
for (const d of dirs) await visit(d, 0);
|
|
3727
|
+
return [...found.entries()].map(([socket, pid]) => ({ socket, pid }));
|
|
3728
|
+
}
|
|
3729
|
+
var NvimService = class {
|
|
3730
|
+
constructor(dirs) {
|
|
3731
|
+
this.dirs = dirs;
|
|
3732
|
+
}
|
|
3733
|
+
dirs;
|
|
3734
|
+
cache = null;
|
|
3735
|
+
pending = null;
|
|
3736
|
+
async scan(force = false) {
|
|
3737
|
+
if (!force && this.cache && Date.now() - this.cache.at < CACHE_TTL_MS) return this.cache.result;
|
|
3738
|
+
if (this.pending) return this.pending;
|
|
3739
|
+
this.pending = this.doScan().finally(() => {
|
|
3740
|
+
this.pending = null;
|
|
3741
|
+
});
|
|
3742
|
+
const result = await this.pending;
|
|
3743
|
+
this.cache = { at: Date.now(), result };
|
|
3744
|
+
return result;
|
|
3745
|
+
}
|
|
3746
|
+
async doScan() {
|
|
3747
|
+
const sockets = await findSockets(this.dirs);
|
|
3748
|
+
let nvimAvailable = true;
|
|
3749
|
+
const instances = [];
|
|
3750
|
+
await Promise.all(
|
|
3751
|
+
sockets.map(async ({ socket, pid }) => {
|
|
3752
|
+
const r = await execNvim(["--server", socket, "--remote-expr", "getcwd()"], QUERY_TIMEOUT_MS);
|
|
3753
|
+
if (r.missing) {
|
|
3754
|
+
nvimAvailable = false;
|
|
3755
|
+
return;
|
|
3756
|
+
}
|
|
3757
|
+
if (!r.ok) return;
|
|
3758
|
+
const cwd = r.stdout.trim();
|
|
3759
|
+
if (cwd) instances.push({ socket, cwd, pid });
|
|
3760
|
+
})
|
|
3761
|
+
);
|
|
3762
|
+
instances.sort((a, b) => (a.pid ?? 0) - (b.pid ?? 0));
|
|
3763
|
+
return { nvimAvailable, instances, scannedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3764
|
+
}
|
|
3765
|
+
/** Instances whose cwd is inside `root`. */
|
|
3766
|
+
static matching(instances, root) {
|
|
3767
|
+
const norm = root.replace(/\/+$/, "");
|
|
3768
|
+
return instances.filter((i) => i.cwd === norm || i.cwd.startsWith(norm + "/"));
|
|
3769
|
+
}
|
|
3770
|
+
async open(socket, absPath, line) {
|
|
3771
|
+
const safeLine = Math.max(1, Math.floor(line) || 1);
|
|
3772
|
+
const vimStr = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
3773
|
+
const expr = `execute(['edit +${safeLine} ' . fnameescape(${vimStr(absPath)}), 'normal! zz'])`;
|
|
3774
|
+
const r = await execNvim(["--server", socket, "--remote-expr", expr], 3e3);
|
|
3775
|
+
if (r.missing) throw new Error("nvim executable not found in PATH");
|
|
3776
|
+
if (!r.ok) throw new Error(r.stderr.trim() || "failed to talk to nvim instance");
|
|
3777
|
+
this.cache = null;
|
|
3778
|
+
}
|
|
3779
|
+
};
|
|
3780
|
+
|
|
3781
|
+
// packages/server/src/static.ts
|
|
3782
|
+
import path5 from "path";
|
|
3783
|
+
import { readFile as readFile3, stat as stat3 } from "fs/promises";
|
|
3784
|
+
var MIME = {
|
|
3785
|
+
".html": "text/html; charset=utf-8",
|
|
3786
|
+
".js": "text/javascript; charset=utf-8",
|
|
3787
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
3788
|
+
".css": "text/css; charset=utf-8",
|
|
3789
|
+
".json": "application/json; charset=utf-8",
|
|
3790
|
+
".svg": "image/svg+xml",
|
|
3791
|
+
".png": "image/png",
|
|
3792
|
+
".ico": "image/x-icon",
|
|
3793
|
+
".woff": "font/woff",
|
|
3794
|
+
".woff2": "font/woff2",
|
|
3795
|
+
".wasm": "application/wasm",
|
|
3796
|
+
".map": "application/json",
|
|
3797
|
+
".txt": "text/plain; charset=utf-8"
|
|
3798
|
+
};
|
|
3799
|
+
async function serveStaticFile(c, webDir) {
|
|
3800
|
+
const root = path5.resolve(webDir);
|
|
3801
|
+
let rel;
|
|
3802
|
+
try {
|
|
3803
|
+
rel = decodeURIComponent(c.req.path);
|
|
3804
|
+
} catch {
|
|
3805
|
+
return c.text("Bad Request", 400);
|
|
3806
|
+
}
|
|
3807
|
+
let target = path5.resolve(root, "." + rel);
|
|
3808
|
+
if (target !== root && !target.startsWith(root + path5.sep)) return c.text("Forbidden", 403);
|
|
3809
|
+
try {
|
|
3810
|
+
const st = await stat3(target);
|
|
3811
|
+
if (st.isDirectory()) target = path5.join(target, "index.html");
|
|
3812
|
+
} catch {
|
|
3813
|
+
target = path5.join(root, "index.html");
|
|
3814
|
+
}
|
|
3815
|
+
let body;
|
|
3816
|
+
try {
|
|
3817
|
+
body = await readFile3(target);
|
|
3818
|
+
} catch {
|
|
3819
|
+
return c.text("Not Found", 404);
|
|
3820
|
+
}
|
|
3821
|
+
const ext = path5.extname(target).toLowerCase();
|
|
3822
|
+
const isAsset = rel.startsWith("/assets/");
|
|
3823
|
+
return new Response(new Uint8Array(body), {
|
|
3824
|
+
status: 200,
|
|
3825
|
+
headers: {
|
|
3826
|
+
"content-type": MIME[ext] ?? "application/octet-stream",
|
|
3827
|
+
"cache-control": isAsset ? "public, max-age=31536000, immutable" : "no-cache"
|
|
3828
|
+
}
|
|
3829
|
+
});
|
|
3830
|
+
}
|
|
3831
|
+
|
|
3832
|
+
// packages/server/src/app.ts
|
|
3833
|
+
var LISTING_HINT_TTL_MS = 5 * 6e4;
|
|
3834
|
+
function createApp(opts) {
|
|
3835
|
+
const { repo, store } = opts;
|
|
3836
|
+
const nvim = opts.nvim ?? new NvimService();
|
|
3837
|
+
const app = new Hono2();
|
|
3838
|
+
const listings = /* @__PURE__ */ new Map();
|
|
3839
|
+
const changedNotices = /* @__PURE__ */ new Map();
|
|
3840
|
+
let worktreeCache = null;
|
|
3841
|
+
const worktrees = async (force = false) => {
|
|
3842
|
+
if (!force && worktreeCache && Date.now() - worktreeCache.at < 1e4) return worktreeCache.list;
|
|
3843
|
+
const list = await listWorktrees(repo);
|
|
3844
|
+
worktreeCache = { at: Date.now(), list };
|
|
3845
|
+
return list;
|
|
3846
|
+
};
|
|
3847
|
+
const targetCtx = async (key) => {
|
|
3848
|
+
let list = await worktrees();
|
|
3849
|
+
try {
|
|
3850
|
+
return resolveTargetContext(repo, list, key);
|
|
3851
|
+
} catch (e) {
|
|
3852
|
+
if (e instanceof HttpError && e.code === "unknown_worktree") {
|
|
3853
|
+
list = await worktrees(true);
|
|
3854
|
+
return resolveTargetContext(repo, list, key);
|
|
3855
|
+
}
|
|
3856
|
+
throw e;
|
|
3857
|
+
}
|
|
3858
|
+
};
|
|
3859
|
+
const decodeKey = (raw2) => {
|
|
3860
|
+
try {
|
|
3861
|
+
return decodeURIComponent(raw2);
|
|
3862
|
+
} catch {
|
|
3863
|
+
throw badRequest("malformed target key", "invalid_target");
|
|
3864
|
+
}
|
|
3865
|
+
};
|
|
3866
|
+
const fileDiffWithHints = async (ctx, filePath, explicit) => {
|
|
3867
|
+
const cached = listings.get(ctx.key);
|
|
3868
|
+
const hint = cached && Date.now() - cached.at < LISTING_HINT_TTL_MS ? cached.files.find((f) => f.path === filePath) : void 0;
|
|
3869
|
+
return getFileDiff(ctx, filePath, {
|
|
3870
|
+
oldPath: explicit?.oldPath ?? hint?.oldPath,
|
|
3871
|
+
untracked: explicit?.untracked ?? hint?.untracked
|
|
3872
|
+
});
|
|
3873
|
+
};
|
|
3874
|
+
const findComment = (state, id) => {
|
|
3875
|
+
for (const [targetKey, t] of Object.entries(state.targets)) {
|
|
3876
|
+
const index = t.comments.findIndex((c) => c.id === id);
|
|
3877
|
+
if (index >= 0) return { comment: t.comments[index], targetKey, index };
|
|
3878
|
+
}
|
|
3879
|
+
return void 0;
|
|
3880
|
+
};
|
|
3881
|
+
app.onError((err, c) => {
|
|
3882
|
+
if (err instanceof HttpError) {
|
|
3883
|
+
return c.json({ error: err.message, code: err.code }, err.status);
|
|
3884
|
+
}
|
|
3885
|
+
console.error(err);
|
|
3886
|
+
return c.json({ error: err instanceof Error ? err.message : String(err), code: "internal" }, 500);
|
|
3887
|
+
});
|
|
3888
|
+
const api = new Hono2();
|
|
3889
|
+
api.get("/repo", async (c) => {
|
|
3890
|
+
const state = await store.load();
|
|
3891
|
+
const info = await getRepoInfo(repo, state.prefs.lastTarget ?? "working");
|
|
3892
|
+
worktreeCache = { at: Date.now(), list: info.worktrees };
|
|
3893
|
+
return c.json(info);
|
|
3894
|
+
});
|
|
3895
|
+
api.get("/state", async (c) => c.json(await store.load()));
|
|
3896
|
+
api.patch("/prefs", async (c) => {
|
|
3897
|
+
const body = await c.req.json();
|
|
3898
|
+
const prefs = await store.update((s) => {
|
|
3899
|
+
if (body.viewMode === "unified" || body.viewMode === "split") s.prefs.viewMode = body.viewMode;
|
|
3900
|
+
if (typeof body.lastTarget === "string") s.prefs.lastTarget = body.lastTarget;
|
|
3901
|
+
if (body.nvimSocketByRoot && typeof body.nvimSocketByRoot === "object") {
|
|
3902
|
+
s.prefs.nvimSocketByRoot = { ...s.prefs.nvimSocketByRoot, ...body.nvimSocketByRoot };
|
|
3903
|
+
}
|
|
3904
|
+
return s.prefs;
|
|
3905
|
+
});
|
|
3906
|
+
return c.json(prefs);
|
|
3907
|
+
});
|
|
3908
|
+
api.get("/targets/:key/files", async (c) => {
|
|
3909
|
+
const key = decodeKey(c.req.param("key"));
|
|
3910
|
+
const ctx = await targetCtx(key);
|
|
3911
|
+
const diffs = await listTargetDiffs(ctx);
|
|
3912
|
+
listings.set(key, { at: Date.now(), files: diffs });
|
|
3913
|
+
const notices = changedNotices.get(key) ?? /* @__PURE__ */ new Set();
|
|
3914
|
+
changedNotices.set(key, notices);
|
|
3915
|
+
const stale = [];
|
|
3916
|
+
const state = await store.load();
|
|
3917
|
+
const t = state.targets[key];
|
|
3918
|
+
const viewed = t?.viewed ?? {};
|
|
3919
|
+
for (const [p, h] of Object.entries(viewed)) {
|
|
3920
|
+
const f = diffs.find((d) => d.path === p);
|
|
3921
|
+
if (!f || f.contentHash !== h) stale.push(p);
|
|
3922
|
+
}
|
|
3923
|
+
if (stale.length) {
|
|
3924
|
+
await store.update((s) => {
|
|
3925
|
+
const ts = s.targets[key];
|
|
3926
|
+
if (!ts) return;
|
|
3927
|
+
for (const p of stale) {
|
|
3928
|
+
if (ts.viewed[p] === viewed[p]) {
|
|
3929
|
+
delete ts.viewed[p];
|
|
3930
|
+
if (diffs.some((d) => d.path === p)) notices.add(p);
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
});
|
|
3934
|
+
}
|
|
3935
|
+
const files = diffs.map((d) => ({
|
|
3936
|
+
...toSummary(d),
|
|
3937
|
+
viewed: !stale.includes(d.path) && viewed[d.path] === d.contentHash,
|
|
3938
|
+
changed: notices.has(d.path)
|
|
3939
|
+
}));
|
|
3940
|
+
const res = { targetKey: key, root: ctx.cwd, files, comments: t?.comments ?? [] };
|
|
3941
|
+
return c.json(res);
|
|
3942
|
+
});
|
|
3943
|
+
api.get("/targets/:key/file", async (c) => {
|
|
3944
|
+
const key = decodeKey(c.req.param("key"));
|
|
3945
|
+
const filePath = c.req.query("path");
|
|
3946
|
+
if (!filePath) throw badRequest("missing path");
|
|
3947
|
+
const ctx = await targetCtx(key);
|
|
3948
|
+
const oldPath = c.req.query("old") || void 0;
|
|
3949
|
+
const untracked = c.req.query("untracked") === "1" ? true : void 0;
|
|
3950
|
+
const diff = await fileDiffWithHints(ctx, filePath, { oldPath, untracked });
|
|
3951
|
+
if (!diff) throw notFound(`no diff for ${filePath} in ${key}`, "no_diff");
|
|
3952
|
+
return c.json(diff);
|
|
3953
|
+
});
|
|
3954
|
+
api.get("/targets/:key/file/full", async (c) => {
|
|
3955
|
+
const key = decodeKey(c.req.param("key"));
|
|
3956
|
+
const filePath = c.req.query("path");
|
|
3957
|
+
if (!filePath) throw badRequest("missing path");
|
|
3958
|
+
const side = c.req.query("side") === "old" ? "old" : "new";
|
|
3959
|
+
const ctx = await targetCtx(key);
|
|
3960
|
+
const content = await getFullFile(ctx, filePath, side);
|
|
3961
|
+
const res = { path: filePath, side, content };
|
|
3962
|
+
return c.json(res);
|
|
3963
|
+
});
|
|
3964
|
+
api.put("/targets/:key/viewed", async (c) => {
|
|
3965
|
+
const key = decodeKey(c.req.param("key"));
|
|
3966
|
+
await targetCtx(key);
|
|
3967
|
+
const body = await c.req.json();
|
|
3968
|
+
if (!body.path) throw badRequest("missing path");
|
|
3969
|
+
const viewed = await store.update((s) => {
|
|
3970
|
+
const t = ensureTarget(s, key);
|
|
3971
|
+
if (body.viewed && body.contentHash) t.viewed[body.path] = body.contentHash;
|
|
3972
|
+
else delete t.viewed[body.path];
|
|
3973
|
+
return t.viewed;
|
|
3974
|
+
});
|
|
3975
|
+
changedNotices.get(key)?.delete(body.path);
|
|
3976
|
+
return c.json({ viewed });
|
|
3977
|
+
});
|
|
3978
|
+
api.get("/targets/:key/comments", async (c) => {
|
|
3979
|
+
const key = decodeKey(c.req.param("key"));
|
|
3980
|
+
const state = await store.load();
|
|
3981
|
+
return c.json({ comments: state.targets[key]?.comments ?? [] });
|
|
3982
|
+
});
|
|
3983
|
+
api.post("/targets/:key/comments", async (c) => {
|
|
3984
|
+
const key = decodeKey(c.req.param("key"));
|
|
3985
|
+
const ctx = await targetCtx(key);
|
|
3986
|
+
const body = await c.req.json();
|
|
3987
|
+
if (!body.filePath || typeof body.body !== "string" || !body.body.trim()) throw badRequest("filePath and body are required");
|
|
3988
|
+
if (body.side !== "old" && body.side !== "new") throw badRequest("side must be old|new");
|
|
3989
|
+
const start = Number(body.startLine);
|
|
3990
|
+
const end = Number(body.endLine ?? body.startLine);
|
|
3991
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 1 || end < 1) throw badRequest("invalid line range");
|
|
3992
|
+
const diff = await fileDiffWithHints(ctx, body.filePath);
|
|
3993
|
+
if (!diff) throw badRequest(`file ${body.filePath} is not part of ${key}`, "no_diff");
|
|
3994
|
+
const anchored = buildAnchor(diff, body.side, start, end);
|
|
3995
|
+
if (!anchored) throw badRequest("selection is not fully visible in the diff on that side (must be inside one hunk)", "bad_selection");
|
|
3996
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3997
|
+
const comment = {
|
|
3998
|
+
id: randomUUID(),
|
|
3999
|
+
targetKey: key,
|
|
4000
|
+
filePath: body.filePath,
|
|
4001
|
+
side: body.side,
|
|
4002
|
+
startLine: anchored.startLine,
|
|
4003
|
+
endLine: anchored.endLine,
|
|
4004
|
+
codeSnippet: anchored.snippet,
|
|
4005
|
+
body: body.body,
|
|
4006
|
+
status: "active",
|
|
4007
|
+
anchor: anchored.anchor,
|
|
4008
|
+
createdAt: now,
|
|
4009
|
+
updatedAt: now
|
|
4010
|
+
};
|
|
4011
|
+
await store.update((s) => {
|
|
4012
|
+
ensureTarget(s, key).comments.push(comment);
|
|
4013
|
+
});
|
|
4014
|
+
return c.json(comment, 201);
|
|
4015
|
+
});
|
|
4016
|
+
api.patch("/targets/:key/comments/:id", async (c) => {
|
|
4017
|
+
const key = decodeKey(c.req.param("key"));
|
|
4018
|
+
const id = c.req.param("id");
|
|
4019
|
+
const ctx = await targetCtx(key);
|
|
4020
|
+
const body = await c.req.json();
|
|
4021
|
+
const state = await store.load();
|
|
4022
|
+
const existing = state.targets[key]?.comments.find((x) => x.id === id);
|
|
4023
|
+
if (!existing) throw notFound("comment not found");
|
|
4024
|
+
let patch = {};
|
|
4025
|
+
if (typeof body.body === "string") {
|
|
4026
|
+
if (!body.body.trim()) throw badRequest("body must not be empty");
|
|
4027
|
+
patch.body = body.body;
|
|
4028
|
+
}
|
|
4029
|
+
if (body.startLine !== void 0 || body.side !== void 0) {
|
|
4030
|
+
const side = body.side ?? existing.side;
|
|
4031
|
+
const start = Number(body.startLine ?? existing.startLine);
|
|
4032
|
+
const end = Number(body.endLine ?? body.startLine ?? existing.endLine);
|
|
4033
|
+
if (side !== "old" && side !== "new") throw badRequest("side must be old|new");
|
|
4034
|
+
const diff = await fileDiffWithHints(ctx, existing.filePath);
|
|
4035
|
+
if (!diff) throw badRequest(`file ${existing.filePath} is not part of ${key}`, "no_diff");
|
|
4036
|
+
const anchored = buildAnchor(diff, side, start, end);
|
|
4037
|
+
if (!anchored) throw badRequest("selection is not fully visible in the diff on that side", "bad_selection");
|
|
4038
|
+
patch = {
|
|
4039
|
+
...patch,
|
|
4040
|
+
side,
|
|
4041
|
+
startLine: anchored.startLine,
|
|
4042
|
+
endLine: anchored.endLine,
|
|
4043
|
+
codeSnippet: anchored.snippet,
|
|
4044
|
+
anchor: anchored.anchor,
|
|
4045
|
+
status: existing.exportedAt ? "exported" : "active"
|
|
4046
|
+
};
|
|
4047
|
+
}
|
|
4048
|
+
const updated = await store.update((s) => {
|
|
4049
|
+
const t = ensureTarget(s, key);
|
|
4050
|
+
const idx = t.comments.findIndex((x) => x.id === id);
|
|
4051
|
+
if (idx < 0) throw notFound("comment not found");
|
|
4052
|
+
const next = { ...t.comments[idx], ...patch, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
4053
|
+
t.comments[idx] = next;
|
|
4054
|
+
return next;
|
|
4055
|
+
});
|
|
4056
|
+
return c.json(updated);
|
|
4057
|
+
});
|
|
4058
|
+
api.delete("/targets/:key/comments/:id", async (c) => {
|
|
4059
|
+
const key = decodeKey(c.req.param("key"));
|
|
4060
|
+
const id = c.req.param("id");
|
|
4061
|
+
const removed = await store.update((s) => {
|
|
4062
|
+
const t = s.targets[key];
|
|
4063
|
+
if (!t) return false;
|
|
4064
|
+
const before = t.comments.length;
|
|
4065
|
+
t.comments = t.comments.filter((x) => x.id !== id);
|
|
4066
|
+
for (const issue of s.issues) issue.commentIds = issue.commentIds.filter((x) => x !== id);
|
|
4067
|
+
return t.comments.length !== before;
|
|
4068
|
+
});
|
|
4069
|
+
if (!removed) throw notFound("comment not found");
|
|
4070
|
+
return c.json({ ok: true });
|
|
4071
|
+
});
|
|
4072
|
+
api.post("/targets/:key/comments/reanchor", async (c) => {
|
|
4073
|
+
const key = decodeKey(c.req.param("key"));
|
|
4074
|
+
const ctx = await targetCtx(key);
|
|
4075
|
+
const body = await c.req.json().catch(() => ({})) ?? {};
|
|
4076
|
+
const provided = /* @__PURE__ */ new Map();
|
|
4077
|
+
for (const f of body.files ?? []) if (f && typeof f.path === "string" && Array.isArray(f.hunks)) provided.set(f.path, f);
|
|
4078
|
+
const state = await store.load();
|
|
4079
|
+
const comments = state.targets[key]?.comments ?? [];
|
|
4080
|
+
const paths = [...new Set(comments.map((x) => x.filePath))];
|
|
4081
|
+
const diffs = /* @__PURE__ */ new Map();
|
|
4082
|
+
await Promise.all(
|
|
4083
|
+
paths.map(async (p) => {
|
|
4084
|
+
if (provided.has(p)) {
|
|
4085
|
+
diffs.set(p, provided.get(p));
|
|
4086
|
+
return;
|
|
4087
|
+
}
|
|
4088
|
+
try {
|
|
4089
|
+
diffs.set(p, await fileDiffWithHints(ctx, p));
|
|
4090
|
+
} catch {
|
|
4091
|
+
diffs.set(p, void 0);
|
|
4092
|
+
}
|
|
4093
|
+
})
|
|
4094
|
+
);
|
|
4095
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4096
|
+
const result = await store.update((s) => {
|
|
4097
|
+
const t = ensureTarget(s, key);
|
|
4098
|
+
t.comments = t.comments.map((cm) => reanchorComment(cm, diffs.get(cm.filePath), now));
|
|
4099
|
+
return t.comments;
|
|
4100
|
+
});
|
|
4101
|
+
const res = { comments: result };
|
|
4102
|
+
return c.json(res);
|
|
4103
|
+
});
|
|
4104
|
+
api.post("/comments/export", async (c) => {
|
|
4105
|
+
const body = await c.req.json();
|
|
4106
|
+
if (!Array.isArray(body.commentIds)) throw badRequest("commentIds required");
|
|
4107
|
+
const ids = body.commentIds.filter((x) => typeof x === "string");
|
|
4108
|
+
const res = await store.update((s) => {
|
|
4109
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4110
|
+
const selected = [];
|
|
4111
|
+
for (const id of ids) {
|
|
4112
|
+
const found = findComment(s, id);
|
|
4113
|
+
if (!found) continue;
|
|
4114
|
+
const next = { ...found.comment, exportedAt: now, updatedAt: now };
|
|
4115
|
+
if (next.status === "active") next.status = "exported";
|
|
4116
|
+
s.targets[found.targetKey].comments[found.index] = next;
|
|
4117
|
+
selected.push(next);
|
|
4118
|
+
}
|
|
4119
|
+
return {
|
|
4120
|
+
text: formatCommentsExport({ repoRoot: repo.root, comments: selected }),
|
|
4121
|
+
count: selected.length,
|
|
4122
|
+
commentIds: selected.map((x) => x.id)
|
|
4123
|
+
};
|
|
4124
|
+
});
|
|
4125
|
+
return c.json(res);
|
|
4126
|
+
});
|
|
4127
|
+
api.get("/issues", async (c) => {
|
|
4128
|
+
const s = await store.load();
|
|
4129
|
+
return c.json({ issues: s.issues });
|
|
4130
|
+
});
|
|
4131
|
+
api.post("/issues", async (c) => {
|
|
4132
|
+
const body = await c.req.json();
|
|
4133
|
+
if (!body.title || !body.title.trim()) throw badRequest("title is required");
|
|
4134
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4135
|
+
const issue = {
|
|
4136
|
+
id: randomUUID(),
|
|
4137
|
+
title: body.title.trim(),
|
|
4138
|
+
body: typeof body.body === "string" ? body.body : "",
|
|
4139
|
+
status: "open",
|
|
4140
|
+
commentIds: Array.isArray(body.commentIds) ? body.commentIds.filter((x) => typeof x === "string") : [],
|
|
4141
|
+
createdAt: now,
|
|
4142
|
+
updatedAt: now
|
|
4143
|
+
};
|
|
4144
|
+
await store.update((s) => {
|
|
4145
|
+
s.issues.push(issue);
|
|
4146
|
+
});
|
|
4147
|
+
return c.json(issue, 201);
|
|
4148
|
+
});
|
|
4149
|
+
api.patch("/issues/:id", async (c) => {
|
|
4150
|
+
const id = c.req.param("id");
|
|
4151
|
+
const body = await c.req.json();
|
|
4152
|
+
const updated = await store.update((s) => {
|
|
4153
|
+
const issue = s.issues.find((i) => i.id === id);
|
|
4154
|
+
if (!issue) throw notFound("issue not found");
|
|
4155
|
+
if (typeof body.title === "string" && body.title.trim()) issue.title = body.title.trim();
|
|
4156
|
+
if (typeof body.body === "string") issue.body = body.body;
|
|
4157
|
+
if (body.status === "open" || body.status === "closed") issue.status = body.status;
|
|
4158
|
+
if (Array.isArray(body.commentIds)) issue.commentIds = [...new Set(body.commentIds.filter((x) => typeof x === "string"))];
|
|
4159
|
+
issue.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4160
|
+
return issue;
|
|
4161
|
+
});
|
|
4162
|
+
return c.json(updated);
|
|
4163
|
+
});
|
|
4164
|
+
api.delete("/issues/:id", async (c) => {
|
|
4165
|
+
const id = c.req.param("id");
|
|
4166
|
+
const removed = await store.update((s) => {
|
|
4167
|
+
const before = s.issues.length;
|
|
4168
|
+
s.issues = s.issues.filter((i) => i.id !== id);
|
|
4169
|
+
return s.issues.length !== before;
|
|
4170
|
+
});
|
|
4171
|
+
if (!removed) throw notFound("issue not found");
|
|
4172
|
+
return c.json({ ok: true });
|
|
4173
|
+
});
|
|
4174
|
+
api.post("/issues/:id/export", async (c) => {
|
|
4175
|
+
const id = c.req.param("id");
|
|
4176
|
+
const res = await store.update((s) => {
|
|
4177
|
+
const issue = s.issues.find((i) => i.id === id);
|
|
4178
|
+
if (!issue) throw notFound("issue not found");
|
|
4179
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4180
|
+
const comments = [];
|
|
4181
|
+
for (const cid of issue.commentIds) {
|
|
4182
|
+
const found = findComment(s, cid);
|
|
4183
|
+
if (!found) continue;
|
|
4184
|
+
const next = { ...found.comment, exportedAt: now, updatedAt: now };
|
|
4185
|
+
if (next.status === "active") next.status = "exported";
|
|
4186
|
+
s.targets[found.targetKey].comments[found.index] = next;
|
|
4187
|
+
comments.push(next);
|
|
4188
|
+
}
|
|
4189
|
+
return {
|
|
4190
|
+
text: formatIssueExport({ repoRoot: repo.root, issue, comments }),
|
|
4191
|
+
count: comments.length,
|
|
4192
|
+
commentIds: comments.map((x) => x.id)
|
|
4193
|
+
};
|
|
4194
|
+
});
|
|
4195
|
+
return c.json(res);
|
|
4196
|
+
});
|
|
4197
|
+
api.get("/commits", async (c) => {
|
|
4198
|
+
const limitRaw = Number(c.req.query("limit") ?? 200);
|
|
4199
|
+
const limit = Math.min(Math.max(Number.isFinite(limitRaw) ? Math.floor(limitRaw) : 200, 1), 1e3);
|
|
4200
|
+
const before = c.req.query("before") || void 0;
|
|
4201
|
+
const filePath = c.req.query("path") || void 0;
|
|
4202
|
+
const ref = c.req.query("ref") || void 0;
|
|
4203
|
+
const rootParam = c.req.query("root") || void 0;
|
|
4204
|
+
let cwd = repo.root;
|
|
4205
|
+
if (rootParam) {
|
|
4206
|
+
const wt = (await worktrees()).find((w) => w.path === rootParam);
|
|
4207
|
+
if (!wt && rootParam !== repo.root) throw badRequest("unknown root", "unknown_worktree");
|
|
4208
|
+
cwd = rootParam;
|
|
4209
|
+
}
|
|
4210
|
+
if (before && !isValidRef(before)) throw badRequest("invalid before ref");
|
|
4211
|
+
if (ref && !isValidRef(ref)) throw badRequest("invalid ref");
|
|
4212
|
+
if (filePath && (filePath.startsWith("/") || filePath.split("/").includes(".."))) throw badRequest("invalid path");
|
|
4213
|
+
const SEP = "";
|
|
4214
|
+
const args = ["log", `--max-count=${limit + 1}`, `--format=%H${SEP}%h${SEP}%an${SEP}%ae${SEP}%aI${SEP}%P${SEP}%s`];
|
|
4215
|
+
if (before) args.push(before);
|
|
4216
|
+
else if (ref) args.push(ref);
|
|
4217
|
+
if (filePath) args.push("--", filePath);
|
|
4218
|
+
let stdout = "";
|
|
4219
|
+
try {
|
|
4220
|
+
stdout = (await runGit(args, { cwd })).stdout;
|
|
4221
|
+
} catch (e) {
|
|
4222
|
+
if (e instanceof HttpError && e.code === "git_failed") stdout = "";
|
|
4223
|
+
else throw e;
|
|
4224
|
+
}
|
|
4225
|
+
let commits = stdout.split("\n").filter(Boolean).map((line) => {
|
|
4226
|
+
const [sha = "", shortSha = "", author = "", email = "", date = "", parents = "", ...rest] = line.split(SEP);
|
|
4227
|
+
return { sha, shortSha, author, email, date, parents: parents.split(" ").filter(Boolean), subject: rest.join(SEP) };
|
|
4228
|
+
});
|
|
4229
|
+
if (before) commits = commits.filter((x) => x.sha !== before && !x.sha.startsWith(before));
|
|
4230
|
+
const hasMore = commits.length > limit;
|
|
4231
|
+
const res = { commits: commits.slice(0, limit), hasMore };
|
|
4232
|
+
return c.json(res);
|
|
4233
|
+
});
|
|
4234
|
+
api.get("/nvim/instances", async (c) => {
|
|
4235
|
+
const root = c.req.query("root") || repo.root;
|
|
4236
|
+
const force = c.req.query("rescan") === "1";
|
|
4237
|
+
const scan = await nvim.scan(force);
|
|
4238
|
+
const instances = NvimService.matching(scan.instances, root);
|
|
4239
|
+
const state = await store.load();
|
|
4240
|
+
const preferred = state.prefs.nvimSocketByRoot[root];
|
|
4241
|
+
let selected;
|
|
4242
|
+
if (preferred && instances.some((i) => i.socket === preferred)) selected = preferred;
|
|
4243
|
+
else if (instances.length === 1) selected = instances[0].socket;
|
|
4244
|
+
const res = { root, nvimAvailable: scan.nvimAvailable, instances, selected, scannedAt: scan.scannedAt };
|
|
4245
|
+
return c.json(res);
|
|
4246
|
+
});
|
|
4247
|
+
api.post("/nvim/select", async (c) => {
|
|
4248
|
+
const body = await c.req.json();
|
|
4249
|
+
if (!body.root || !body.socket) throw badRequest("root and socket are required");
|
|
4250
|
+
await store.update((s) => {
|
|
4251
|
+
s.prefs.nvimSocketByRoot[body.root] = body.socket;
|
|
4252
|
+
});
|
|
4253
|
+
return c.json({ ok: true });
|
|
4254
|
+
});
|
|
4255
|
+
api.post("/nvim/open", async (c) => {
|
|
4256
|
+
const body = await c.req.json();
|
|
4257
|
+
if (!body.socket || !body.absPath) throw badRequest("socket and absPath are required");
|
|
4258
|
+
if (!path6.isAbsolute(body.absPath)) throw badRequest("absPath must be absolute");
|
|
4259
|
+
const scan = await nvim.scan();
|
|
4260
|
+
if (!scan.instances.some((i) => i.socket === body.socket)) {
|
|
4261
|
+
const fresh = await nvim.scan(true);
|
|
4262
|
+
if (!fresh.instances.some((i) => i.socket === body.socket)) throw badRequest("nvim instance not found (rescan)", "nvim_gone");
|
|
4263
|
+
}
|
|
4264
|
+
try {
|
|
4265
|
+
await nvim.open(body.socket, body.absPath, Number(body.line) || 1);
|
|
4266
|
+
} catch (e) {
|
|
4267
|
+
throw new HttpError(502, e instanceof Error ? e.message : String(e), "nvim_failed");
|
|
4268
|
+
}
|
|
4269
|
+
return c.json({ ok: true });
|
|
4270
|
+
});
|
|
4271
|
+
app.route("/api", api);
|
|
4272
|
+
app.notFound((c) => {
|
|
4273
|
+
if (c.req.path.startsWith("/api/") || c.req.path === "/api") return c.json({ error: "not found", code: "not_found" }, 404);
|
|
4274
|
+
return c.text("Not Found", 404);
|
|
4275
|
+
});
|
|
4276
|
+
if (opts.webDir) {
|
|
4277
|
+
const webDir = opts.webDir;
|
|
4278
|
+
app.get("*", (c) => {
|
|
4279
|
+
if (c.req.path === "/api" || c.req.path.startsWith("/api/")) return c.notFound();
|
|
4280
|
+
return serveStaticFile(c, webDir);
|
|
4281
|
+
});
|
|
4282
|
+
}
|
|
4283
|
+
return app;
|
|
4284
|
+
}
|
|
4285
|
+
|
|
4286
|
+
// packages/server/src/index.ts
|
|
4287
|
+
var HOST = "127.0.0.1";
|
|
4288
|
+
var DEFAULT_PORT_START = 4100;
|
|
4289
|
+
function isPortFree(port, host = HOST) {
|
|
4290
|
+
return new Promise((resolve) => {
|
|
4291
|
+
const srv = net.createServer();
|
|
4292
|
+
srv.once("error", () => resolve(false));
|
|
4293
|
+
srv.listen(port, host, () => {
|
|
4294
|
+
srv.close(() => resolve(true));
|
|
4295
|
+
});
|
|
4296
|
+
});
|
|
4297
|
+
}
|
|
4298
|
+
async function findFreePort(start = DEFAULT_PORT_START, host = HOST) {
|
|
4299
|
+
for (let p = start; p < start + 1e3; p++) {
|
|
4300
|
+
if (await isPortFree(p, host)) return p;
|
|
4301
|
+
}
|
|
4302
|
+
throw new Error(`no free port found starting at ${start}`);
|
|
4303
|
+
}
|
|
4304
|
+
async function startServer(opts) {
|
|
4305
|
+
const repo = await resolveRepo(opts.repoPath);
|
|
4306
|
+
const stateFile = opts.stateFile ?? stateFilePath(repo.commonRoot);
|
|
4307
|
+
const store = new StateStore(stateFile, repo.commonRoot);
|
|
4308
|
+
const app = createApp({ repo, store, nvim: new NvimService(), webDir: opts.webDir });
|
|
4309
|
+
let port;
|
|
4310
|
+
if (opts.port !== void 0) {
|
|
4311
|
+
if (!await isPortFree(opts.port)) throw new Error(`port ${opts.port} is already in use`);
|
|
4312
|
+
port = opts.port;
|
|
4313
|
+
} else {
|
|
4314
|
+
port = await findFreePort();
|
|
4315
|
+
}
|
|
4316
|
+
const server = await new Promise((resolve, reject) => {
|
|
4317
|
+
const s = serve({ fetch: app.fetch, hostname: HOST, port }, () => resolve(s));
|
|
4318
|
+
s.once("error", reject);
|
|
4319
|
+
});
|
|
4320
|
+
return {
|
|
4321
|
+
url: `http://${HOST}:${port}/`,
|
|
4322
|
+
port,
|
|
4323
|
+
repo,
|
|
4324
|
+
stateFile,
|
|
4325
|
+
close: () => new Promise((resolve, reject) => {
|
|
4326
|
+
server.close((err) => err ? reject(err) : resolve());
|
|
4327
|
+
})
|
|
4328
|
+
};
|
|
4329
|
+
}
|
|
4330
|
+
|
|
4331
|
+
// bin/cli.ts
|
|
4332
|
+
var VERSION = true ? "0.1.0" : "dev";
|
|
4333
|
+
function parseArgs(argv) {
|
|
4334
|
+
const args = { repoPath: process.cwd(), open: true, help: false, version: false };
|
|
4335
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4336
|
+
const a = argv[i];
|
|
4337
|
+
if (a === "--no-open") args.open = false;
|
|
4338
|
+
else if (a === "--open") args.open = true;
|
|
4339
|
+
else if (a === "--port" || a === "-p") {
|
|
4340
|
+
const v = argv[++i];
|
|
4341
|
+
if (!v || !/^\d+$/.test(v)) throw new Error("--port requires a number");
|
|
4342
|
+
args.port = Number(v);
|
|
4343
|
+
} else if (a.startsWith("--port=")) {
|
|
4344
|
+
const v = a.slice("--port=".length);
|
|
4345
|
+
if (!/^\d+$/.test(v)) throw new Error("--port requires a number");
|
|
4346
|
+
args.port = Number(v);
|
|
4347
|
+
} else if (a === "--help" || a === "-h") args.help = true;
|
|
4348
|
+
else if (a === "--version" || a === "-v") args.version = true;
|
|
4349
|
+
else if (a.startsWith("-")) throw new Error(`unknown option: ${a}`);
|
|
4350
|
+
else args.repoPath = path7.resolve(a);
|
|
4351
|
+
}
|
|
4352
|
+
return args;
|
|
4353
|
+
}
|
|
4354
|
+
function usage() {
|
|
4355
|
+
return `warden \u2014 local git diff review UI
|
|
4356
|
+
|
|
4357
|
+
Usage: warden [repoPath] [options]
|
|
4358
|
+
|
|
4359
|
+
Options:
|
|
4360
|
+
--port <n>, -p <n> Listen on a fixed port (default: first free port from 4100)
|
|
4361
|
+
--no-open Do not try to open the browser
|
|
4362
|
+
-h, --help Show this help
|
|
4363
|
+
-v, --version Print version
|
|
4364
|
+
`;
|
|
4365
|
+
}
|
|
4366
|
+
async function openBrowser(url) {
|
|
4367
|
+
const candidates = [
|
|
4368
|
+
["wslview", [url]],
|
|
4369
|
+
["explorer.exe", [url]],
|
|
4370
|
+
["xdg-open", [url]]
|
|
4371
|
+
];
|
|
4372
|
+
for (const [cmd, args] of candidates) {
|
|
4373
|
+
const ok = await new Promise((resolve) => {
|
|
4374
|
+
let child;
|
|
4375
|
+
try {
|
|
4376
|
+
child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
4377
|
+
} catch {
|
|
4378
|
+
resolve(false);
|
|
4379
|
+
return;
|
|
4380
|
+
}
|
|
4381
|
+
child.once("error", () => resolve(false));
|
|
4382
|
+
child.once("spawn", () => {
|
|
4383
|
+
child.unref();
|
|
4384
|
+
resolve(true);
|
|
4385
|
+
});
|
|
4386
|
+
});
|
|
4387
|
+
if (ok) return true;
|
|
4388
|
+
}
|
|
4389
|
+
return false;
|
|
4390
|
+
}
|
|
4391
|
+
function resolveWebDir() {
|
|
4392
|
+
const here = path7.dirname(fileURLToPath(import.meta.url));
|
|
4393
|
+
const candidates = [
|
|
4394
|
+
process.env.WARDEN_WEB_DIR,
|
|
4395
|
+
path7.join(here, "web"),
|
|
4396
|
+
// dist/cli.js -> dist/web
|
|
4397
|
+
path7.join(here, "..", "dist", "web")
|
|
4398
|
+
// bin/cli.ts (tsx dev) -> dist/web
|
|
4399
|
+
].filter((p) => !!p);
|
|
4400
|
+
for (const dir of candidates) {
|
|
4401
|
+
if (existsSync(path7.join(dir, "index.html"))) return dir;
|
|
4402
|
+
}
|
|
4403
|
+
return void 0;
|
|
4404
|
+
}
|
|
4405
|
+
async function main() {
|
|
4406
|
+
let args;
|
|
4407
|
+
try {
|
|
4408
|
+
args = parseArgs(process.argv.slice(2));
|
|
4409
|
+
} catch (e) {
|
|
4410
|
+
console.error(e.message);
|
|
4411
|
+
console.error(usage());
|
|
4412
|
+
process.exit(2);
|
|
4413
|
+
}
|
|
4414
|
+
if (args.help) {
|
|
4415
|
+
console.log(usage());
|
|
4416
|
+
return;
|
|
4417
|
+
}
|
|
4418
|
+
if (args.version) {
|
|
4419
|
+
console.log(VERSION);
|
|
4420
|
+
return;
|
|
4421
|
+
}
|
|
4422
|
+
const webDir = resolveWebDir();
|
|
4423
|
+
if (!webDir) {
|
|
4424
|
+
console.error("warning: built web assets not found (dist/web). Only the /api endpoints will be served.");
|
|
4425
|
+
}
|
|
4426
|
+
let server;
|
|
4427
|
+
try {
|
|
4428
|
+
server = await startServer({ repoPath: args.repoPath, port: args.port, webDir });
|
|
4429
|
+
} catch (e) {
|
|
4430
|
+
console.error(`warden: ${e.message}`);
|
|
4431
|
+
process.exit(1);
|
|
4432
|
+
}
|
|
4433
|
+
console.log(`warden ${VERSION}`);
|
|
4434
|
+
console.log(` repo: ${server.repo.root}`);
|
|
4435
|
+
console.log(` state: ${server.stateFile}`);
|
|
4436
|
+
console.log(` url: ${server.url}`);
|
|
4437
|
+
if (args.open) {
|
|
4438
|
+
const opened = await openBrowser(server.url);
|
|
4439
|
+
if (!opened) console.log(" (could not open a browser automatically; open the URL manually)");
|
|
4440
|
+
}
|
|
4441
|
+
const shutdown = () => {
|
|
4442
|
+
server.close().finally(() => process.exit(0));
|
|
4443
|
+
};
|
|
4444
|
+
process.on("SIGINT", shutdown);
|
|
4445
|
+
process.on("SIGTERM", shutdown);
|
|
4446
|
+
}
|
|
4447
|
+
main().catch((e) => {
|
|
4448
|
+
console.error(e);
|
|
4449
|
+
process.exit(1);
|
|
4450
|
+
});
|