@hir4ta/mneme 0.17.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/.claude-plugin/plugin.json +29 -0
- package/.mcp.json +18 -0
- package/README.ja.md +400 -0
- package/README.md +410 -0
- package/bin/mneme.js +203 -0
- package/dist/lib/db.js +340 -0
- package/dist/lib/fuzzy-search.js +214 -0
- package/dist/lib/github.js +121 -0
- package/dist/lib/similarity.js +193 -0
- package/dist/lib/utils.js +62 -0
- package/dist/public/apple-touch-icon.png +0 -0
- package/dist/public/assets/index-BgqCALAg.css +1 -0
- package/dist/public/assets/index-EMvn4VEa.js +330 -0
- package/dist/public/assets/react-force-graph-2d-DWoBaKmT.js +46 -0
- package/dist/public/favicon-128-max.png +0 -0
- package/dist/public/favicon-256-max.png +0 -0
- package/dist/public/favicon-32-max.png +0 -0
- package/dist/public/favicon-512-max.png +0 -0
- package/dist/public/favicon-64-max.png +0 -0
- package/dist/public/index.html +15 -0
- package/dist/server.js +4791 -0
- package/dist/servers/db-server.js +30558 -0
- package/dist/servers/search-server.js +30366 -0
- package/hooks/default-tags.json +1055 -0
- package/hooks/hooks.json +61 -0
- package/hooks/post-tool-use.sh +96 -0
- package/hooks/pre-compact.sh +187 -0
- package/hooks/session-end.sh +567 -0
- package/hooks/session-start.sh +380 -0
- package/hooks/user-prompt-submit.sh +253 -0
- package/package.json +77 -0
- package/servers/db-server.ts +993 -0
- package/servers/search-server.ts +675 -0
- package/skills/AGENTS.override.md +5 -0
- package/skills/harvest/skill.md +295 -0
- package/skills/init-mneme/skill.md +101 -0
- package/skills/plan/skill.md +422 -0
- package/skills/report/skill.md +74 -0
- package/skills/resume/skill.md +278 -0
- package/skills/review/skill.md +419 -0
- package/skills/save/skill.md +482 -0
- package/skills/search/skill.md +175 -0
- package/skills/using-mneme/skill.md +185 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,4791 @@
|
|
|
1
|
+
// dashboard/server/index.ts
|
|
2
|
+
import fs4 from "node:fs";
|
|
3
|
+
import path3 from "node:path";
|
|
4
|
+
|
|
5
|
+
// node_modules/@hono/node-server/dist/index.mjs
|
|
6
|
+
import { createServer as createServerHTTP } from "http";
|
|
7
|
+
import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
|
|
8
|
+
import { Http2ServerRequest } from "http2";
|
|
9
|
+
import { Readable } from "stream";
|
|
10
|
+
import crypto from "crypto";
|
|
11
|
+
var RequestError = class extends Error {
|
|
12
|
+
constructor(message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.name = "RequestError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var toRequestError = (e) => {
|
|
18
|
+
if (e instanceof RequestError) {
|
|
19
|
+
return e;
|
|
20
|
+
}
|
|
21
|
+
return new RequestError(e.message, { cause: e });
|
|
22
|
+
};
|
|
23
|
+
var GlobalRequest = global.Request;
|
|
24
|
+
var Request2 = class extends GlobalRequest {
|
|
25
|
+
constructor(input, options) {
|
|
26
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
27
|
+
input = input[getRequestCache]();
|
|
28
|
+
}
|
|
29
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
30
|
+
;
|
|
31
|
+
options.duplex ??= "half";
|
|
32
|
+
}
|
|
33
|
+
super(input, options);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
37
|
+
const headerRecord = [];
|
|
38
|
+
const rawHeaders = incoming.rawHeaders;
|
|
39
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
40
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
41
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
42
|
+
58) {
|
|
43
|
+
headerRecord.push([key, value]);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return new Headers(headerRecord);
|
|
47
|
+
};
|
|
48
|
+
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
49
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
50
|
+
const init = {
|
|
51
|
+
method,
|
|
52
|
+
headers,
|
|
53
|
+
signal: abortController.signal
|
|
54
|
+
};
|
|
55
|
+
if (method === "TRACE") {
|
|
56
|
+
init.method = "GET";
|
|
57
|
+
const req = new Request2(url, init);
|
|
58
|
+
Object.defineProperty(req, "method", {
|
|
59
|
+
get() {
|
|
60
|
+
return "TRACE";
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
return req;
|
|
64
|
+
}
|
|
65
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
66
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
67
|
+
init.body = new ReadableStream({
|
|
68
|
+
start(controller) {
|
|
69
|
+
controller.enqueue(incoming.rawBody);
|
|
70
|
+
controller.close();
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
} else if (incoming[wrapBodyStream]) {
|
|
74
|
+
let reader;
|
|
75
|
+
init.body = new ReadableStream({
|
|
76
|
+
async pull(controller) {
|
|
77
|
+
try {
|
|
78
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
79
|
+
const { done, value } = await reader.read();
|
|
80
|
+
if (done) {
|
|
81
|
+
controller.close();
|
|
82
|
+
} else {
|
|
83
|
+
controller.enqueue(value);
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
controller.error(error);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
} else {
|
|
91
|
+
init.body = Readable.toWeb(incoming);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return new Request2(url, init);
|
|
95
|
+
};
|
|
96
|
+
var getRequestCache = Symbol("getRequestCache");
|
|
97
|
+
var requestCache = Symbol("requestCache");
|
|
98
|
+
var incomingKey = Symbol("incomingKey");
|
|
99
|
+
var urlKey = Symbol("urlKey");
|
|
100
|
+
var headersKey = Symbol("headersKey");
|
|
101
|
+
var abortControllerKey = Symbol("abortControllerKey");
|
|
102
|
+
var getAbortController = Symbol("getAbortController");
|
|
103
|
+
var requestPrototype = {
|
|
104
|
+
get method() {
|
|
105
|
+
return this[incomingKey].method || "GET";
|
|
106
|
+
},
|
|
107
|
+
get url() {
|
|
108
|
+
return this[urlKey];
|
|
109
|
+
},
|
|
110
|
+
get headers() {
|
|
111
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
112
|
+
},
|
|
113
|
+
[getAbortController]() {
|
|
114
|
+
this[getRequestCache]();
|
|
115
|
+
return this[abortControllerKey];
|
|
116
|
+
},
|
|
117
|
+
[getRequestCache]() {
|
|
118
|
+
this[abortControllerKey] ||= new AbortController();
|
|
119
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
120
|
+
this.method,
|
|
121
|
+
this[urlKey],
|
|
122
|
+
this.headers,
|
|
123
|
+
this[incomingKey],
|
|
124
|
+
this[abortControllerKey]
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
[
|
|
129
|
+
"body",
|
|
130
|
+
"bodyUsed",
|
|
131
|
+
"cache",
|
|
132
|
+
"credentials",
|
|
133
|
+
"destination",
|
|
134
|
+
"integrity",
|
|
135
|
+
"mode",
|
|
136
|
+
"redirect",
|
|
137
|
+
"referrer",
|
|
138
|
+
"referrerPolicy",
|
|
139
|
+
"signal",
|
|
140
|
+
"keepalive"
|
|
141
|
+
].forEach((k) => {
|
|
142
|
+
Object.defineProperty(requestPrototype, k, {
|
|
143
|
+
get() {
|
|
144
|
+
return this[getRequestCache]()[k];
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
149
|
+
Object.defineProperty(requestPrototype, k, {
|
|
150
|
+
value: function() {
|
|
151
|
+
return this[getRequestCache]()[k]();
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
Object.setPrototypeOf(requestPrototype, Request2.prototype);
|
|
156
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
157
|
+
const req = Object.create(requestPrototype);
|
|
158
|
+
req[incomingKey] = incoming;
|
|
159
|
+
const incomingUrl = incoming.url || "";
|
|
160
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
161
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
162
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
163
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const url2 = new URL(incomingUrl);
|
|
167
|
+
req[urlKey] = url2.href;
|
|
168
|
+
} catch (e) {
|
|
169
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
170
|
+
}
|
|
171
|
+
return req;
|
|
172
|
+
}
|
|
173
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
174
|
+
if (!host) {
|
|
175
|
+
throw new RequestError("Missing host header");
|
|
176
|
+
}
|
|
177
|
+
let scheme;
|
|
178
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
179
|
+
scheme = incoming.scheme;
|
|
180
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
181
|
+
throw new RequestError("Unsupported scheme");
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
185
|
+
}
|
|
186
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
187
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
188
|
+
throw new RequestError("Invalid host header");
|
|
189
|
+
}
|
|
190
|
+
req[urlKey] = url.href;
|
|
191
|
+
return req;
|
|
192
|
+
};
|
|
193
|
+
var responseCache = Symbol("responseCache");
|
|
194
|
+
var getResponseCache = Symbol("getResponseCache");
|
|
195
|
+
var cacheKey = Symbol("cache");
|
|
196
|
+
var GlobalResponse = global.Response;
|
|
197
|
+
var Response2 = class _Response {
|
|
198
|
+
#body;
|
|
199
|
+
#init;
|
|
200
|
+
[getResponseCache]() {
|
|
201
|
+
delete this[cacheKey];
|
|
202
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
203
|
+
}
|
|
204
|
+
constructor(body, init) {
|
|
205
|
+
let headers;
|
|
206
|
+
this.#body = body;
|
|
207
|
+
if (init instanceof _Response) {
|
|
208
|
+
const cachedGlobalResponse = init[responseCache];
|
|
209
|
+
if (cachedGlobalResponse) {
|
|
210
|
+
this.#init = cachedGlobalResponse;
|
|
211
|
+
this[getResponseCache]();
|
|
212
|
+
return;
|
|
213
|
+
} else {
|
|
214
|
+
this.#init = init.#init;
|
|
215
|
+
headers = new Headers(init.#init.headers);
|
|
216
|
+
}
|
|
217
|
+
} else {
|
|
218
|
+
this.#init = init;
|
|
219
|
+
}
|
|
220
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
221
|
+
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
|
222
|
+
this[cacheKey] = [init?.status || 200, body, headers];
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
get headers() {
|
|
226
|
+
const cache = this[cacheKey];
|
|
227
|
+
if (cache) {
|
|
228
|
+
if (!(cache[2] instanceof Headers)) {
|
|
229
|
+
cache[2] = new Headers(cache[2]);
|
|
230
|
+
}
|
|
231
|
+
return cache[2];
|
|
232
|
+
}
|
|
233
|
+
return this[getResponseCache]().headers;
|
|
234
|
+
}
|
|
235
|
+
get status() {
|
|
236
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
237
|
+
}
|
|
238
|
+
get ok() {
|
|
239
|
+
const status = this.status;
|
|
240
|
+
return status >= 200 && status < 300;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
244
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
245
|
+
get() {
|
|
246
|
+
return this[getResponseCache]()[k];
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
251
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
252
|
+
value: function() {
|
|
253
|
+
return this[getResponseCache]()[k]();
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
258
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
259
|
+
async function readWithoutBlocking(readPromise) {
|
|
260
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
261
|
+
}
|
|
262
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
263
|
+
const cancel = (error) => {
|
|
264
|
+
reader.cancel(error).catch(() => {
|
|
265
|
+
});
|
|
266
|
+
};
|
|
267
|
+
writable.on("close", cancel);
|
|
268
|
+
writable.on("error", cancel);
|
|
269
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
270
|
+
return reader.closed.finally(() => {
|
|
271
|
+
writable.off("close", cancel);
|
|
272
|
+
writable.off("error", cancel);
|
|
273
|
+
});
|
|
274
|
+
function handleStreamError(error) {
|
|
275
|
+
if (error) {
|
|
276
|
+
writable.destroy(error);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function onDrain() {
|
|
280
|
+
reader.read().then(flow, handleStreamError);
|
|
281
|
+
}
|
|
282
|
+
function flow({ done, value }) {
|
|
283
|
+
try {
|
|
284
|
+
if (done) {
|
|
285
|
+
writable.end();
|
|
286
|
+
} else if (!writable.write(value)) {
|
|
287
|
+
writable.once("drain", onDrain);
|
|
288
|
+
} else {
|
|
289
|
+
return reader.read().then(flow, handleStreamError);
|
|
290
|
+
}
|
|
291
|
+
} catch (e) {
|
|
292
|
+
handleStreamError(e);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function writeFromReadableStream(stream, writable) {
|
|
297
|
+
if (stream.locked) {
|
|
298
|
+
throw new TypeError("ReadableStream is locked.");
|
|
299
|
+
} else if (writable.destroyed) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
303
|
+
}
|
|
304
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
305
|
+
const res = {};
|
|
306
|
+
if (!(headers instanceof Headers)) {
|
|
307
|
+
headers = new Headers(headers ?? void 0);
|
|
308
|
+
}
|
|
309
|
+
const cookies = [];
|
|
310
|
+
for (const [k, v] of headers) {
|
|
311
|
+
if (k === "set-cookie") {
|
|
312
|
+
cookies.push(v);
|
|
313
|
+
} else {
|
|
314
|
+
res[k] = v;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (cookies.length > 0) {
|
|
318
|
+
res["set-cookie"] = cookies;
|
|
319
|
+
}
|
|
320
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
321
|
+
return res;
|
|
322
|
+
};
|
|
323
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
324
|
+
if (typeof global.crypto === "undefined") {
|
|
325
|
+
global.crypto = crypto;
|
|
326
|
+
}
|
|
327
|
+
var outgoingEnded = Symbol("outgoingEnded");
|
|
328
|
+
var handleRequestError = () => new Response(null, {
|
|
329
|
+
status: 400
|
|
330
|
+
});
|
|
331
|
+
var handleFetchError = (e) => new Response(null, {
|
|
332
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
333
|
+
});
|
|
334
|
+
var handleResponseError = (e, outgoing) => {
|
|
335
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
336
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
337
|
+
console.info("The user aborted a request.");
|
|
338
|
+
} else {
|
|
339
|
+
console.error(e);
|
|
340
|
+
if (!outgoing.headersSent) {
|
|
341
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
342
|
+
}
|
|
343
|
+
outgoing.end(`Error: ${err.message}`);
|
|
344
|
+
outgoing.destroy(err);
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
var flushHeaders = (outgoing) => {
|
|
348
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
349
|
+
outgoing.flushHeaders();
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
var responseViaCache = async (res, outgoing) => {
|
|
353
|
+
let [status, body, header] = res[cacheKey];
|
|
354
|
+
if (header instanceof Headers) {
|
|
355
|
+
header = buildOutgoingHttpHeaders(header);
|
|
356
|
+
}
|
|
357
|
+
if (typeof body === "string") {
|
|
358
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
359
|
+
} else if (body instanceof Uint8Array) {
|
|
360
|
+
header["Content-Length"] = body.byteLength;
|
|
361
|
+
} else if (body instanceof Blob) {
|
|
362
|
+
header["Content-Length"] = body.size;
|
|
363
|
+
}
|
|
364
|
+
outgoing.writeHead(status, header);
|
|
365
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
366
|
+
outgoing.end(body);
|
|
367
|
+
} else if (body instanceof Blob) {
|
|
368
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
369
|
+
} else {
|
|
370
|
+
flushHeaders(outgoing);
|
|
371
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
372
|
+
(e) => handleResponseError(e, outgoing)
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
;
|
|
376
|
+
outgoing[outgoingEnded]?.();
|
|
377
|
+
};
|
|
378
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
379
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
380
|
+
if (isPromise(res)) {
|
|
381
|
+
if (options.errorHandler) {
|
|
382
|
+
try {
|
|
383
|
+
res = await res;
|
|
384
|
+
} catch (err) {
|
|
385
|
+
const errRes = await options.errorHandler(err);
|
|
386
|
+
if (!errRes) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
res = errRes;
|
|
390
|
+
}
|
|
391
|
+
} else {
|
|
392
|
+
res = await res.catch(handleFetchError);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (cacheKey in res) {
|
|
396
|
+
return responseViaCache(res, outgoing);
|
|
397
|
+
}
|
|
398
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
399
|
+
if (res.body) {
|
|
400
|
+
const reader = res.body.getReader();
|
|
401
|
+
const values = [];
|
|
402
|
+
let done = false;
|
|
403
|
+
let currentReadPromise = void 0;
|
|
404
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
405
|
+
let maxReadCount = 2;
|
|
406
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
407
|
+
currentReadPromise ||= reader.read();
|
|
408
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
409
|
+
console.error(e);
|
|
410
|
+
done = true;
|
|
411
|
+
});
|
|
412
|
+
if (!chunk) {
|
|
413
|
+
if (i === 1) {
|
|
414
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
415
|
+
maxReadCount = 3;
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
currentReadPromise = void 0;
|
|
421
|
+
if (chunk.value) {
|
|
422
|
+
values.push(chunk.value);
|
|
423
|
+
}
|
|
424
|
+
if (chunk.done) {
|
|
425
|
+
done = true;
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
430
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
434
|
+
values.forEach((value) => {
|
|
435
|
+
;
|
|
436
|
+
outgoing.write(value);
|
|
437
|
+
});
|
|
438
|
+
if (done) {
|
|
439
|
+
outgoing.end();
|
|
440
|
+
} else {
|
|
441
|
+
if (values.length === 0) {
|
|
442
|
+
flushHeaders(outgoing);
|
|
443
|
+
}
|
|
444
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
445
|
+
}
|
|
446
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
447
|
+
} else {
|
|
448
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
449
|
+
outgoing.end();
|
|
450
|
+
}
|
|
451
|
+
;
|
|
452
|
+
outgoing[outgoingEnded]?.();
|
|
453
|
+
};
|
|
454
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
455
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
456
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
|
|
457
|
+
Object.defineProperty(global, "Request", {
|
|
458
|
+
value: Request2
|
|
459
|
+
});
|
|
460
|
+
Object.defineProperty(global, "Response", {
|
|
461
|
+
value: Response2
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
return async (incoming, outgoing) => {
|
|
465
|
+
let res, req;
|
|
466
|
+
try {
|
|
467
|
+
req = newRequest(incoming, options.hostname);
|
|
468
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
469
|
+
if (!incomingEnded) {
|
|
470
|
+
;
|
|
471
|
+
incoming[wrapBodyStream] = true;
|
|
472
|
+
incoming.on("end", () => {
|
|
473
|
+
incomingEnded = true;
|
|
474
|
+
});
|
|
475
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
476
|
+
;
|
|
477
|
+
outgoing[outgoingEnded] = () => {
|
|
478
|
+
if (!incomingEnded) {
|
|
479
|
+
setTimeout(() => {
|
|
480
|
+
if (!incomingEnded) {
|
|
481
|
+
setTimeout(() => {
|
|
482
|
+
incoming.destroy();
|
|
483
|
+
outgoing.destroy();
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
outgoing.on("close", () => {
|
|
492
|
+
const abortController = req[abortControllerKey];
|
|
493
|
+
if (abortController) {
|
|
494
|
+
if (incoming.errored) {
|
|
495
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
496
|
+
} else if (!outgoing.writableFinished) {
|
|
497
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (!incomingEnded) {
|
|
501
|
+
setTimeout(() => {
|
|
502
|
+
if (!incomingEnded) {
|
|
503
|
+
setTimeout(() => {
|
|
504
|
+
incoming.destroy();
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
511
|
+
if (cacheKey in res) {
|
|
512
|
+
return responseViaCache(res, outgoing);
|
|
513
|
+
}
|
|
514
|
+
} catch (e) {
|
|
515
|
+
if (!res) {
|
|
516
|
+
if (options.errorHandler) {
|
|
517
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
518
|
+
if (!res) {
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
} else if (!req) {
|
|
522
|
+
res = handleRequestError();
|
|
523
|
+
} else {
|
|
524
|
+
res = handleFetchError(e);
|
|
525
|
+
}
|
|
526
|
+
} else {
|
|
527
|
+
return handleResponseError(e, outgoing);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
532
|
+
} catch (e) {
|
|
533
|
+
return handleResponseError(e, outgoing);
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
};
|
|
537
|
+
var createAdaptorServer = (options) => {
|
|
538
|
+
const fetchCallback = options.fetch;
|
|
539
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
540
|
+
hostname: options.hostname,
|
|
541
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
542
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
543
|
+
});
|
|
544
|
+
const createServer = options.createServer || createServerHTTP;
|
|
545
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
546
|
+
return server;
|
|
547
|
+
};
|
|
548
|
+
var serve = (options, listeningListener) => {
|
|
549
|
+
const server = createAdaptorServer(options);
|
|
550
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
551
|
+
const serverInfo = server.address();
|
|
552
|
+
listeningListener && listeningListener(serverInfo);
|
|
553
|
+
});
|
|
554
|
+
return server;
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// node_modules/hono/dist/utils/mime.js
|
|
558
|
+
var getMimeType = (filename, mimes = baseMimes) => {
|
|
559
|
+
const regexp = /\.([a-zA-Z0-9]+?)$/;
|
|
560
|
+
const match2 = filename.match(regexp);
|
|
561
|
+
if (!match2) {
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
let mimeType = mimes[match2[1]];
|
|
565
|
+
if (mimeType && mimeType.startsWith("text")) {
|
|
566
|
+
mimeType += "; charset=utf-8";
|
|
567
|
+
}
|
|
568
|
+
return mimeType;
|
|
569
|
+
};
|
|
570
|
+
var _baseMimes = {
|
|
571
|
+
aac: "audio/aac",
|
|
572
|
+
avi: "video/x-msvideo",
|
|
573
|
+
avif: "image/avif",
|
|
574
|
+
av1: "video/av1",
|
|
575
|
+
bin: "application/octet-stream",
|
|
576
|
+
bmp: "image/bmp",
|
|
577
|
+
css: "text/css",
|
|
578
|
+
csv: "text/csv",
|
|
579
|
+
eot: "application/vnd.ms-fontobject",
|
|
580
|
+
epub: "application/epub+zip",
|
|
581
|
+
gif: "image/gif",
|
|
582
|
+
gz: "application/gzip",
|
|
583
|
+
htm: "text/html",
|
|
584
|
+
html: "text/html",
|
|
585
|
+
ico: "image/x-icon",
|
|
586
|
+
ics: "text/calendar",
|
|
587
|
+
jpeg: "image/jpeg",
|
|
588
|
+
jpg: "image/jpeg",
|
|
589
|
+
js: "text/javascript",
|
|
590
|
+
json: "application/json",
|
|
591
|
+
jsonld: "application/ld+json",
|
|
592
|
+
map: "application/json",
|
|
593
|
+
mid: "audio/x-midi",
|
|
594
|
+
midi: "audio/x-midi",
|
|
595
|
+
mjs: "text/javascript",
|
|
596
|
+
mp3: "audio/mpeg",
|
|
597
|
+
mp4: "video/mp4",
|
|
598
|
+
mpeg: "video/mpeg",
|
|
599
|
+
oga: "audio/ogg",
|
|
600
|
+
ogv: "video/ogg",
|
|
601
|
+
ogx: "application/ogg",
|
|
602
|
+
opus: "audio/opus",
|
|
603
|
+
otf: "font/otf",
|
|
604
|
+
pdf: "application/pdf",
|
|
605
|
+
png: "image/png",
|
|
606
|
+
rtf: "application/rtf",
|
|
607
|
+
svg: "image/svg+xml",
|
|
608
|
+
tif: "image/tiff",
|
|
609
|
+
tiff: "image/tiff",
|
|
610
|
+
ts: "video/mp2t",
|
|
611
|
+
ttf: "font/ttf",
|
|
612
|
+
txt: "text/plain",
|
|
613
|
+
wasm: "application/wasm",
|
|
614
|
+
webm: "video/webm",
|
|
615
|
+
weba: "audio/webm",
|
|
616
|
+
webmanifest: "application/manifest+json",
|
|
617
|
+
webp: "image/webp",
|
|
618
|
+
woff: "font/woff",
|
|
619
|
+
woff2: "font/woff2",
|
|
620
|
+
xhtml: "application/xhtml+xml",
|
|
621
|
+
xml: "application/xml",
|
|
622
|
+
zip: "application/zip",
|
|
623
|
+
"3gp": "video/3gpp",
|
|
624
|
+
"3g2": "video/3gpp2",
|
|
625
|
+
gltf: "model/gltf+json",
|
|
626
|
+
glb: "model/gltf-binary"
|
|
627
|
+
};
|
|
628
|
+
var baseMimes = _baseMimes;
|
|
629
|
+
|
|
630
|
+
// node_modules/@hono/node-server/dist/serve-static.mjs
|
|
631
|
+
import { createReadStream, statSync, existsSync } from "fs";
|
|
632
|
+
import { join } from "path";
|
|
633
|
+
import { versions } from "process";
|
|
634
|
+
import { Readable as Readable2 } from "stream";
|
|
635
|
+
var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
|
636
|
+
var ENCODINGS = {
|
|
637
|
+
br: ".br",
|
|
638
|
+
zstd: ".zst",
|
|
639
|
+
gzip: ".gz"
|
|
640
|
+
};
|
|
641
|
+
var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
|
642
|
+
var pr54206Applied = () => {
|
|
643
|
+
const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
|
|
644
|
+
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
|
645
|
+
};
|
|
646
|
+
var useReadableToWeb = pr54206Applied();
|
|
647
|
+
var createStreamBody = (stream) => {
|
|
648
|
+
if (useReadableToWeb) {
|
|
649
|
+
return Readable2.toWeb(stream);
|
|
650
|
+
}
|
|
651
|
+
const body = new ReadableStream({
|
|
652
|
+
start(controller) {
|
|
653
|
+
stream.on("data", (chunk) => {
|
|
654
|
+
controller.enqueue(chunk);
|
|
655
|
+
});
|
|
656
|
+
stream.on("error", (err) => {
|
|
657
|
+
controller.error(err);
|
|
658
|
+
});
|
|
659
|
+
stream.on("end", () => {
|
|
660
|
+
controller.close();
|
|
661
|
+
});
|
|
662
|
+
},
|
|
663
|
+
cancel() {
|
|
664
|
+
stream.destroy();
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
return body;
|
|
668
|
+
};
|
|
669
|
+
var getStats = (path4) => {
|
|
670
|
+
let stats;
|
|
671
|
+
try {
|
|
672
|
+
stats = statSync(path4);
|
|
673
|
+
} catch {
|
|
674
|
+
}
|
|
675
|
+
return stats;
|
|
676
|
+
};
|
|
677
|
+
var serveStatic = (options = { root: "" }) => {
|
|
678
|
+
const root = options.root || "";
|
|
679
|
+
const optionPath = options.path;
|
|
680
|
+
if (root !== "" && !existsSync(root)) {
|
|
681
|
+
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
|
682
|
+
}
|
|
683
|
+
return async (c, next) => {
|
|
684
|
+
if (c.finalized) {
|
|
685
|
+
return next();
|
|
686
|
+
}
|
|
687
|
+
let filename;
|
|
688
|
+
if (optionPath) {
|
|
689
|
+
filename = optionPath;
|
|
690
|
+
} else {
|
|
691
|
+
try {
|
|
692
|
+
filename = decodeURIComponent(c.req.path);
|
|
693
|
+
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
|
|
694
|
+
throw new Error();
|
|
695
|
+
}
|
|
696
|
+
} catch {
|
|
697
|
+
await options.onNotFound?.(c.req.path, c);
|
|
698
|
+
return next();
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
let path4 = join(
|
|
702
|
+
root,
|
|
703
|
+
!optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
|
|
704
|
+
);
|
|
705
|
+
let stats = getStats(path4);
|
|
706
|
+
if (stats && stats.isDirectory()) {
|
|
707
|
+
const indexFile = options.index ?? "index.html";
|
|
708
|
+
path4 = join(path4, indexFile);
|
|
709
|
+
stats = getStats(path4);
|
|
710
|
+
}
|
|
711
|
+
if (!stats) {
|
|
712
|
+
await options.onNotFound?.(path4, c);
|
|
713
|
+
return next();
|
|
714
|
+
}
|
|
715
|
+
const mimeType = getMimeType(path4);
|
|
716
|
+
c.header("Content-Type", mimeType || "application/octet-stream");
|
|
717
|
+
if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
|
718
|
+
const acceptEncodingSet = new Set(
|
|
719
|
+
c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
|
|
720
|
+
);
|
|
721
|
+
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
|
722
|
+
if (!acceptEncodingSet.has(encoding)) {
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
const precompressedStats = getStats(path4 + ENCODINGS[encoding]);
|
|
726
|
+
if (precompressedStats) {
|
|
727
|
+
c.header("Content-Encoding", encoding);
|
|
728
|
+
c.header("Vary", "Accept-Encoding", { append: true });
|
|
729
|
+
stats = precompressedStats;
|
|
730
|
+
path4 = path4 + ENCODINGS[encoding];
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
let result;
|
|
736
|
+
const size = stats.size;
|
|
737
|
+
const range = c.req.header("range") || "";
|
|
738
|
+
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
|
739
|
+
c.header("Content-Length", size.toString());
|
|
740
|
+
c.status(200);
|
|
741
|
+
result = c.body(null);
|
|
742
|
+
} else if (!range) {
|
|
743
|
+
c.header("Content-Length", size.toString());
|
|
744
|
+
result = c.body(createStreamBody(createReadStream(path4)), 200);
|
|
745
|
+
} else {
|
|
746
|
+
c.header("Accept-Ranges", "bytes");
|
|
747
|
+
c.header("Date", stats.birthtime.toUTCString());
|
|
748
|
+
const parts = range.replace(/bytes=/, "").split("-", 2);
|
|
749
|
+
const start = parseInt(parts[0], 10) || 0;
|
|
750
|
+
let end = parseInt(parts[1], 10) || size - 1;
|
|
751
|
+
if (size < end - start + 1) {
|
|
752
|
+
end = size - 1;
|
|
753
|
+
}
|
|
754
|
+
const chunksize = end - start + 1;
|
|
755
|
+
const stream = createReadStream(path4, { start, end });
|
|
756
|
+
c.header("Content-Length", chunksize.toString());
|
|
757
|
+
c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
|
|
758
|
+
result = c.body(createStreamBody(stream), 206);
|
|
759
|
+
}
|
|
760
|
+
await options.onFound?.(path4, c);
|
|
761
|
+
return result;
|
|
762
|
+
};
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
// node_modules/hono/dist/compose.js
|
|
766
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
767
|
+
return (context, next) => {
|
|
768
|
+
let index = -1;
|
|
769
|
+
return dispatch(0);
|
|
770
|
+
async function dispatch(i) {
|
|
771
|
+
if (i <= index) {
|
|
772
|
+
throw new Error("next() called multiple times");
|
|
773
|
+
}
|
|
774
|
+
index = i;
|
|
775
|
+
let res;
|
|
776
|
+
let isError = false;
|
|
777
|
+
let handler;
|
|
778
|
+
if (middleware[i]) {
|
|
779
|
+
handler = middleware[i][0][0];
|
|
780
|
+
context.req.routeIndex = i;
|
|
781
|
+
} else {
|
|
782
|
+
handler = i === middleware.length && next || void 0;
|
|
783
|
+
}
|
|
784
|
+
if (handler) {
|
|
785
|
+
try {
|
|
786
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
787
|
+
} catch (err) {
|
|
788
|
+
if (err instanceof Error && onError) {
|
|
789
|
+
context.error = err;
|
|
790
|
+
res = await onError(err, context);
|
|
791
|
+
isError = true;
|
|
792
|
+
} else {
|
|
793
|
+
throw err;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
} else {
|
|
797
|
+
if (context.finalized === false && onNotFound) {
|
|
798
|
+
res = await onNotFound(context);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (res && (context.finalized === false || isError)) {
|
|
802
|
+
context.res = res;
|
|
803
|
+
}
|
|
804
|
+
return context;
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
// node_modules/hono/dist/request/constants.js
|
|
810
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
811
|
+
|
|
812
|
+
// node_modules/hono/dist/utils/body.js
|
|
813
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
814
|
+
const { all = false, dot = false } = options;
|
|
815
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
816
|
+
const contentType = headers.get("Content-Type");
|
|
817
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
818
|
+
return parseFormData(request, { all, dot });
|
|
819
|
+
}
|
|
820
|
+
return {};
|
|
821
|
+
};
|
|
822
|
+
async function parseFormData(request, options) {
|
|
823
|
+
const formData = await request.formData();
|
|
824
|
+
if (formData) {
|
|
825
|
+
return convertFormDataToBodyData(formData, options);
|
|
826
|
+
}
|
|
827
|
+
return {};
|
|
828
|
+
}
|
|
829
|
+
function convertFormDataToBodyData(formData, options) {
|
|
830
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
831
|
+
formData.forEach((value, key) => {
|
|
832
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
833
|
+
if (!shouldParseAllValues) {
|
|
834
|
+
form[key] = value;
|
|
835
|
+
} else {
|
|
836
|
+
handleParsingAllValues(form, key, value);
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
if (options.dot) {
|
|
840
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
841
|
+
const shouldParseDotValues = key.includes(".");
|
|
842
|
+
if (shouldParseDotValues) {
|
|
843
|
+
handleParsingNestedValues(form, key, value);
|
|
844
|
+
delete form[key];
|
|
845
|
+
}
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
return form;
|
|
849
|
+
}
|
|
850
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
851
|
+
if (form[key] !== void 0) {
|
|
852
|
+
if (Array.isArray(form[key])) {
|
|
853
|
+
;
|
|
854
|
+
form[key].push(value);
|
|
855
|
+
} else {
|
|
856
|
+
form[key] = [form[key], value];
|
|
857
|
+
}
|
|
858
|
+
} else {
|
|
859
|
+
if (!key.endsWith("[]")) {
|
|
860
|
+
form[key] = value;
|
|
861
|
+
} else {
|
|
862
|
+
form[key] = [value];
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
867
|
+
let nestedForm = form;
|
|
868
|
+
const keys = key.split(".");
|
|
869
|
+
keys.forEach((key2, index) => {
|
|
870
|
+
if (index === keys.length - 1) {
|
|
871
|
+
nestedForm[key2] = value;
|
|
872
|
+
} else {
|
|
873
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
874
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
875
|
+
}
|
|
876
|
+
nestedForm = nestedForm[key2];
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
};
|
|
880
|
+
|
|
881
|
+
// node_modules/hono/dist/utils/url.js
|
|
882
|
+
var splitPath = (path4) => {
|
|
883
|
+
const paths = path4.split("/");
|
|
884
|
+
if (paths[0] === "") {
|
|
885
|
+
paths.shift();
|
|
886
|
+
}
|
|
887
|
+
return paths;
|
|
888
|
+
};
|
|
889
|
+
var splitRoutingPath = (routePath) => {
|
|
890
|
+
const { groups, path: path4 } = extractGroupsFromPath(routePath);
|
|
891
|
+
const paths = splitPath(path4);
|
|
892
|
+
return replaceGroupMarks(paths, groups);
|
|
893
|
+
};
|
|
894
|
+
var extractGroupsFromPath = (path4) => {
|
|
895
|
+
const groups = [];
|
|
896
|
+
path4 = path4.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
897
|
+
const mark = `@${index}`;
|
|
898
|
+
groups.push([mark, match2]);
|
|
899
|
+
return mark;
|
|
900
|
+
});
|
|
901
|
+
return { groups, path: path4 };
|
|
902
|
+
};
|
|
903
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
904
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
905
|
+
const [mark] = groups[i];
|
|
906
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
907
|
+
if (paths[j].includes(mark)) {
|
|
908
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
909
|
+
break;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
return paths;
|
|
914
|
+
};
|
|
915
|
+
var patternCache = {};
|
|
916
|
+
var getPattern = (label, next) => {
|
|
917
|
+
if (label === "*") {
|
|
918
|
+
return "*";
|
|
919
|
+
}
|
|
920
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
921
|
+
if (match2) {
|
|
922
|
+
const cacheKey2 = `${label}#${next}`;
|
|
923
|
+
if (!patternCache[cacheKey2]) {
|
|
924
|
+
if (match2[2]) {
|
|
925
|
+
patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
926
|
+
} else {
|
|
927
|
+
patternCache[cacheKey2] = [label, match2[1], true];
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return patternCache[cacheKey2];
|
|
931
|
+
}
|
|
932
|
+
return null;
|
|
933
|
+
};
|
|
934
|
+
var tryDecode = (str, decoder) => {
|
|
935
|
+
try {
|
|
936
|
+
return decoder(str);
|
|
937
|
+
} catch {
|
|
938
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
939
|
+
try {
|
|
940
|
+
return decoder(match2);
|
|
941
|
+
} catch {
|
|
942
|
+
return match2;
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
948
|
+
var getPath = (request) => {
|
|
949
|
+
const url = request.url;
|
|
950
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
951
|
+
let i = start;
|
|
952
|
+
for (; i < url.length; i++) {
|
|
953
|
+
const charCode = url.charCodeAt(i);
|
|
954
|
+
if (charCode === 37) {
|
|
955
|
+
const queryIndex = url.indexOf("?", i);
|
|
956
|
+
const path4 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
|
|
957
|
+
return tryDecodeURI(path4.includes("%25") ? path4.replace(/%25/g, "%2525") : path4);
|
|
958
|
+
} else if (charCode === 63) {
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return url.slice(start, i);
|
|
963
|
+
};
|
|
964
|
+
var getPathNoStrict = (request) => {
|
|
965
|
+
const result = getPath(request);
|
|
966
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
967
|
+
};
|
|
968
|
+
var mergePath = (base, sub, ...rest) => {
|
|
969
|
+
if (rest.length) {
|
|
970
|
+
sub = mergePath(sub, ...rest);
|
|
971
|
+
}
|
|
972
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
973
|
+
};
|
|
974
|
+
var checkOptionalParameter = (path4) => {
|
|
975
|
+
if (path4.charCodeAt(path4.length - 1) !== 63 || !path4.includes(":")) {
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
const segments = path4.split("/");
|
|
979
|
+
const results = [];
|
|
980
|
+
let basePath = "";
|
|
981
|
+
segments.forEach((segment) => {
|
|
982
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
983
|
+
basePath += "/" + segment;
|
|
984
|
+
} else if (/\:/.test(segment)) {
|
|
985
|
+
if (/\?/.test(segment)) {
|
|
986
|
+
if (results.length === 0 && basePath === "") {
|
|
987
|
+
results.push("/");
|
|
988
|
+
} else {
|
|
989
|
+
results.push(basePath);
|
|
990
|
+
}
|
|
991
|
+
const optionalSegment = segment.replace("?", "");
|
|
992
|
+
basePath += "/" + optionalSegment;
|
|
993
|
+
results.push(basePath);
|
|
994
|
+
} else {
|
|
995
|
+
basePath += "/" + segment;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
1000
|
+
};
|
|
1001
|
+
var _decodeURI = (value) => {
|
|
1002
|
+
if (!/[%+]/.test(value)) {
|
|
1003
|
+
return value;
|
|
1004
|
+
}
|
|
1005
|
+
if (value.indexOf("+") !== -1) {
|
|
1006
|
+
value = value.replace(/\+/g, " ");
|
|
1007
|
+
}
|
|
1008
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
1009
|
+
};
|
|
1010
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
1011
|
+
let encoded;
|
|
1012
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
1013
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
1014
|
+
if (keyIndex2 === -1) {
|
|
1015
|
+
return void 0;
|
|
1016
|
+
}
|
|
1017
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
1018
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1019
|
+
}
|
|
1020
|
+
while (keyIndex2 !== -1) {
|
|
1021
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
1022
|
+
if (trailingKeyCode === 61) {
|
|
1023
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
1024
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
1025
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
1026
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
1027
|
+
return "";
|
|
1028
|
+
}
|
|
1029
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1030
|
+
}
|
|
1031
|
+
encoded = /[%+]/.test(url);
|
|
1032
|
+
if (!encoded) {
|
|
1033
|
+
return void 0;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
const results = {};
|
|
1037
|
+
encoded ??= /[%+]/.test(url);
|
|
1038
|
+
let keyIndex = url.indexOf("?", 8);
|
|
1039
|
+
while (keyIndex !== -1) {
|
|
1040
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
1041
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
1042
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
1043
|
+
valueIndex = -1;
|
|
1044
|
+
}
|
|
1045
|
+
let name = url.slice(
|
|
1046
|
+
keyIndex + 1,
|
|
1047
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
1048
|
+
);
|
|
1049
|
+
if (encoded) {
|
|
1050
|
+
name = _decodeURI(name);
|
|
1051
|
+
}
|
|
1052
|
+
keyIndex = nextKeyIndex;
|
|
1053
|
+
if (name === "") {
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
let value;
|
|
1057
|
+
if (valueIndex === -1) {
|
|
1058
|
+
value = "";
|
|
1059
|
+
} else {
|
|
1060
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
1061
|
+
if (encoded) {
|
|
1062
|
+
value = _decodeURI(value);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
if (multiple) {
|
|
1066
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1067
|
+
results[name] = [];
|
|
1068
|
+
}
|
|
1069
|
+
;
|
|
1070
|
+
results[name].push(value);
|
|
1071
|
+
} else {
|
|
1072
|
+
results[name] ??= value;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return key ? results[key] : results;
|
|
1076
|
+
};
|
|
1077
|
+
var getQueryParam = _getQueryParam;
|
|
1078
|
+
var getQueryParams = (url, key) => {
|
|
1079
|
+
return _getQueryParam(url, key, true);
|
|
1080
|
+
};
|
|
1081
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1082
|
+
|
|
1083
|
+
// node_modules/hono/dist/request.js
|
|
1084
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1085
|
+
var HonoRequest = class {
|
|
1086
|
+
/**
|
|
1087
|
+
* `.raw` can get the raw Request object.
|
|
1088
|
+
*
|
|
1089
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1090
|
+
*
|
|
1091
|
+
* @example
|
|
1092
|
+
* ```ts
|
|
1093
|
+
* // For Cloudflare Workers
|
|
1094
|
+
* app.post('/', async (c) => {
|
|
1095
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1096
|
+
* ...
|
|
1097
|
+
* })
|
|
1098
|
+
* ```
|
|
1099
|
+
*/
|
|
1100
|
+
raw;
|
|
1101
|
+
#validatedData;
|
|
1102
|
+
// Short name of validatedData
|
|
1103
|
+
#matchResult;
|
|
1104
|
+
routeIndex = 0;
|
|
1105
|
+
/**
|
|
1106
|
+
* `.path` can get the pathname of the request.
|
|
1107
|
+
*
|
|
1108
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1109
|
+
*
|
|
1110
|
+
* @example
|
|
1111
|
+
* ```ts
|
|
1112
|
+
* app.get('/about/me', (c) => {
|
|
1113
|
+
* const pathname = c.req.path // `/about/me`
|
|
1114
|
+
* })
|
|
1115
|
+
* ```
|
|
1116
|
+
*/
|
|
1117
|
+
path;
|
|
1118
|
+
bodyCache = {};
|
|
1119
|
+
constructor(request, path4 = "/", matchResult = [[]]) {
|
|
1120
|
+
this.raw = request;
|
|
1121
|
+
this.path = path4;
|
|
1122
|
+
this.#matchResult = matchResult;
|
|
1123
|
+
this.#validatedData = {};
|
|
1124
|
+
}
|
|
1125
|
+
param(key) {
|
|
1126
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1127
|
+
}
|
|
1128
|
+
#getDecodedParam(key) {
|
|
1129
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1130
|
+
const param = this.#getParamValue(paramKey);
|
|
1131
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1132
|
+
}
|
|
1133
|
+
#getAllDecodedParams() {
|
|
1134
|
+
const decoded = {};
|
|
1135
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1136
|
+
for (const key of keys) {
|
|
1137
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1138
|
+
if (value !== void 0) {
|
|
1139
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
return decoded;
|
|
1143
|
+
}
|
|
1144
|
+
#getParamValue(paramKey) {
|
|
1145
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1146
|
+
}
|
|
1147
|
+
query(key) {
|
|
1148
|
+
return getQueryParam(this.url, key);
|
|
1149
|
+
}
|
|
1150
|
+
queries(key) {
|
|
1151
|
+
return getQueryParams(this.url, key);
|
|
1152
|
+
}
|
|
1153
|
+
header(name) {
|
|
1154
|
+
if (name) {
|
|
1155
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1156
|
+
}
|
|
1157
|
+
const headerData = {};
|
|
1158
|
+
this.raw.headers.forEach((value, key) => {
|
|
1159
|
+
headerData[key] = value;
|
|
1160
|
+
});
|
|
1161
|
+
return headerData;
|
|
1162
|
+
}
|
|
1163
|
+
async parseBody(options) {
|
|
1164
|
+
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
1165
|
+
}
|
|
1166
|
+
#cachedBody = (key) => {
|
|
1167
|
+
const { bodyCache, raw: raw2 } = this;
|
|
1168
|
+
const cachedBody = bodyCache[key];
|
|
1169
|
+
if (cachedBody) {
|
|
1170
|
+
return cachedBody;
|
|
1171
|
+
}
|
|
1172
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1173
|
+
if (anyCachedKey) {
|
|
1174
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1175
|
+
if (anyCachedKey === "json") {
|
|
1176
|
+
body = JSON.stringify(body);
|
|
1177
|
+
}
|
|
1178
|
+
return new Response(body)[key]();
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
return bodyCache[key] = raw2[key]();
|
|
1182
|
+
};
|
|
1183
|
+
/**
|
|
1184
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1185
|
+
*
|
|
1186
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1187
|
+
*
|
|
1188
|
+
* @example
|
|
1189
|
+
* ```ts
|
|
1190
|
+
* app.post('/entry', async (c) => {
|
|
1191
|
+
* const body = await c.req.json()
|
|
1192
|
+
* })
|
|
1193
|
+
* ```
|
|
1194
|
+
*/
|
|
1195
|
+
json() {
|
|
1196
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1200
|
+
*
|
|
1201
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1202
|
+
*
|
|
1203
|
+
* @example
|
|
1204
|
+
* ```ts
|
|
1205
|
+
* app.post('/entry', async (c) => {
|
|
1206
|
+
* const body = await c.req.text()
|
|
1207
|
+
* })
|
|
1208
|
+
* ```
|
|
1209
|
+
*/
|
|
1210
|
+
text() {
|
|
1211
|
+
return this.#cachedBody("text");
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1215
|
+
*
|
|
1216
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1217
|
+
*
|
|
1218
|
+
* @example
|
|
1219
|
+
* ```ts
|
|
1220
|
+
* app.post('/entry', async (c) => {
|
|
1221
|
+
* const body = await c.req.arrayBuffer()
|
|
1222
|
+
* })
|
|
1223
|
+
* ```
|
|
1224
|
+
*/
|
|
1225
|
+
arrayBuffer() {
|
|
1226
|
+
return this.#cachedBody("arrayBuffer");
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Parses the request body as a `Blob`.
|
|
1230
|
+
* @example
|
|
1231
|
+
* ```ts
|
|
1232
|
+
* app.post('/entry', async (c) => {
|
|
1233
|
+
* const body = await c.req.blob();
|
|
1234
|
+
* });
|
|
1235
|
+
* ```
|
|
1236
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
1237
|
+
*/
|
|
1238
|
+
blob() {
|
|
1239
|
+
return this.#cachedBody("blob");
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Parses the request body as `FormData`.
|
|
1243
|
+
* @example
|
|
1244
|
+
* ```ts
|
|
1245
|
+
* app.post('/entry', async (c) => {
|
|
1246
|
+
* const body = await c.req.formData();
|
|
1247
|
+
* });
|
|
1248
|
+
* ```
|
|
1249
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
1250
|
+
*/
|
|
1251
|
+
formData() {
|
|
1252
|
+
return this.#cachedBody("formData");
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Adds validated data to the request.
|
|
1256
|
+
*
|
|
1257
|
+
* @param target - The target of the validation.
|
|
1258
|
+
* @param data - The validated data to add.
|
|
1259
|
+
*/
|
|
1260
|
+
addValidatedData(target, data) {
|
|
1261
|
+
this.#validatedData[target] = data;
|
|
1262
|
+
}
|
|
1263
|
+
valid(target) {
|
|
1264
|
+
return this.#validatedData[target];
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* `.url()` can get the request url strings.
|
|
1268
|
+
*
|
|
1269
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
1270
|
+
*
|
|
1271
|
+
* @example
|
|
1272
|
+
* ```ts
|
|
1273
|
+
* app.get('/about/me', (c) => {
|
|
1274
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
1275
|
+
* ...
|
|
1276
|
+
* })
|
|
1277
|
+
* ```
|
|
1278
|
+
*/
|
|
1279
|
+
get url() {
|
|
1280
|
+
return this.raw.url;
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* `.method()` can get the method name of the request.
|
|
1284
|
+
*
|
|
1285
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
1286
|
+
*
|
|
1287
|
+
* @example
|
|
1288
|
+
* ```ts
|
|
1289
|
+
* app.get('/about/me', (c) => {
|
|
1290
|
+
* const method = c.req.method // `GET`
|
|
1291
|
+
* })
|
|
1292
|
+
* ```
|
|
1293
|
+
*/
|
|
1294
|
+
get method() {
|
|
1295
|
+
return this.raw.method;
|
|
1296
|
+
}
|
|
1297
|
+
get [GET_MATCH_RESULT]() {
|
|
1298
|
+
return this.#matchResult;
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
1302
|
+
*
|
|
1303
|
+
* @deprecated
|
|
1304
|
+
*
|
|
1305
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
1306
|
+
*
|
|
1307
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
1308
|
+
*
|
|
1309
|
+
* @example
|
|
1310
|
+
* ```ts
|
|
1311
|
+
* app.use('*', async function logger(c, next) {
|
|
1312
|
+
* await next()
|
|
1313
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
1314
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
1315
|
+
* console.log(
|
|
1316
|
+
* method,
|
|
1317
|
+
* ' ',
|
|
1318
|
+
* path,
|
|
1319
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
1320
|
+
* name,
|
|
1321
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
1322
|
+
* )
|
|
1323
|
+
* })
|
|
1324
|
+
* })
|
|
1325
|
+
* ```
|
|
1326
|
+
*/
|
|
1327
|
+
get matchedRoutes() {
|
|
1328
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
1332
|
+
*
|
|
1333
|
+
* @deprecated
|
|
1334
|
+
*
|
|
1335
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
1336
|
+
*
|
|
1337
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
1338
|
+
*
|
|
1339
|
+
* @example
|
|
1340
|
+
* ```ts
|
|
1341
|
+
* app.get('/posts/:id', (c) => {
|
|
1342
|
+
* return c.json({ path: c.req.routePath })
|
|
1343
|
+
* })
|
|
1344
|
+
* ```
|
|
1345
|
+
*/
|
|
1346
|
+
get routePath() {
|
|
1347
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
|
|
1351
|
+
// node_modules/hono/dist/utils/html.js
|
|
1352
|
+
var HtmlEscapedCallbackPhase = {
|
|
1353
|
+
Stringify: 1,
|
|
1354
|
+
BeforeStream: 2,
|
|
1355
|
+
Stream: 3
|
|
1356
|
+
};
|
|
1357
|
+
var raw = (value, callbacks) => {
|
|
1358
|
+
const escapedString = new String(value);
|
|
1359
|
+
escapedString.isEscaped = true;
|
|
1360
|
+
escapedString.callbacks = callbacks;
|
|
1361
|
+
return escapedString;
|
|
1362
|
+
};
|
|
1363
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1364
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1365
|
+
if (!(str instanceof Promise)) {
|
|
1366
|
+
str = str.toString();
|
|
1367
|
+
}
|
|
1368
|
+
if (str instanceof Promise) {
|
|
1369
|
+
str = await str;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
const callbacks = str.callbacks;
|
|
1373
|
+
if (!callbacks?.length) {
|
|
1374
|
+
return Promise.resolve(str);
|
|
1375
|
+
}
|
|
1376
|
+
if (buffer) {
|
|
1377
|
+
buffer[0] += str;
|
|
1378
|
+
} else {
|
|
1379
|
+
buffer = [str];
|
|
1380
|
+
}
|
|
1381
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
1382
|
+
(res) => Promise.all(
|
|
1383
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
1384
|
+
).then(() => buffer[0])
|
|
1385
|
+
);
|
|
1386
|
+
if (preserveCallbacks) {
|
|
1387
|
+
return raw(await resStr, callbacks);
|
|
1388
|
+
} else {
|
|
1389
|
+
return resStr;
|
|
1390
|
+
}
|
|
1391
|
+
};
|
|
1392
|
+
|
|
1393
|
+
// node_modules/hono/dist/context.js
|
|
1394
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1395
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1396
|
+
return {
|
|
1397
|
+
"Content-Type": contentType,
|
|
1398
|
+
...headers
|
|
1399
|
+
};
|
|
1400
|
+
};
|
|
1401
|
+
var Context = class {
|
|
1402
|
+
#rawRequest;
|
|
1403
|
+
#req;
|
|
1404
|
+
/**
|
|
1405
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
1406
|
+
*
|
|
1407
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
1408
|
+
*
|
|
1409
|
+
* @example
|
|
1410
|
+
* ```ts
|
|
1411
|
+
* // Environment object for Cloudflare Workers
|
|
1412
|
+
* app.get('*', async c => {
|
|
1413
|
+
* const counter = c.env.COUNTER
|
|
1414
|
+
* })
|
|
1415
|
+
* ```
|
|
1416
|
+
*/
|
|
1417
|
+
env = {};
|
|
1418
|
+
#var;
|
|
1419
|
+
finalized = false;
|
|
1420
|
+
/**
|
|
1421
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
1422
|
+
*
|
|
1423
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
1424
|
+
*
|
|
1425
|
+
* @example
|
|
1426
|
+
* ```ts
|
|
1427
|
+
* app.use('*', async (c, next) => {
|
|
1428
|
+
* await next()
|
|
1429
|
+
* if (c.error) {
|
|
1430
|
+
* // do something...
|
|
1431
|
+
* }
|
|
1432
|
+
* })
|
|
1433
|
+
* ```
|
|
1434
|
+
*/
|
|
1435
|
+
error;
|
|
1436
|
+
#status;
|
|
1437
|
+
#executionCtx;
|
|
1438
|
+
#res;
|
|
1439
|
+
#layout;
|
|
1440
|
+
#renderer;
|
|
1441
|
+
#notFoundHandler;
|
|
1442
|
+
#preparedHeaders;
|
|
1443
|
+
#matchResult;
|
|
1444
|
+
#path;
|
|
1445
|
+
/**
|
|
1446
|
+
* Creates an instance of the Context class.
|
|
1447
|
+
*
|
|
1448
|
+
* @param req - The Request object.
|
|
1449
|
+
* @param options - Optional configuration options for the context.
|
|
1450
|
+
*/
|
|
1451
|
+
constructor(req, options) {
|
|
1452
|
+
this.#rawRequest = req;
|
|
1453
|
+
if (options) {
|
|
1454
|
+
this.#executionCtx = options.executionCtx;
|
|
1455
|
+
this.env = options.env;
|
|
1456
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1457
|
+
this.#path = options.path;
|
|
1458
|
+
this.#matchResult = options.matchResult;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
1463
|
+
*/
|
|
1464
|
+
get req() {
|
|
1465
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1466
|
+
return this.#req;
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
1470
|
+
* The FetchEvent associated with the current request.
|
|
1471
|
+
*
|
|
1472
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
1473
|
+
*/
|
|
1474
|
+
get event() {
|
|
1475
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1476
|
+
return this.#executionCtx;
|
|
1477
|
+
} else {
|
|
1478
|
+
throw Error("This context has no FetchEvent");
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
1483
|
+
* The ExecutionContext associated with the current request.
|
|
1484
|
+
*
|
|
1485
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
1486
|
+
*/
|
|
1487
|
+
get executionCtx() {
|
|
1488
|
+
if (this.#executionCtx) {
|
|
1489
|
+
return this.#executionCtx;
|
|
1490
|
+
} else {
|
|
1491
|
+
throw Error("This context has no ExecutionContext");
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
1496
|
+
* The Response object for the current request.
|
|
1497
|
+
*/
|
|
1498
|
+
get res() {
|
|
1499
|
+
return this.#res ||= new Response(null, {
|
|
1500
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* Sets the Response object for the current request.
|
|
1505
|
+
*
|
|
1506
|
+
* @param _res - The Response object to set.
|
|
1507
|
+
*/
|
|
1508
|
+
set res(_res) {
|
|
1509
|
+
if (this.#res && _res) {
|
|
1510
|
+
_res = new Response(_res.body, _res);
|
|
1511
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1512
|
+
if (k === "content-type") {
|
|
1513
|
+
continue;
|
|
1514
|
+
}
|
|
1515
|
+
if (k === "set-cookie") {
|
|
1516
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1517
|
+
_res.headers.delete("set-cookie");
|
|
1518
|
+
for (const cookie of cookies) {
|
|
1519
|
+
_res.headers.append("set-cookie", cookie);
|
|
1520
|
+
}
|
|
1521
|
+
} else {
|
|
1522
|
+
_res.headers.set(k, v);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
this.#res = _res;
|
|
1527
|
+
this.finalized = true;
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* `.render()` can create a response within a layout.
|
|
1531
|
+
*
|
|
1532
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1533
|
+
*
|
|
1534
|
+
* @example
|
|
1535
|
+
* ```ts
|
|
1536
|
+
* app.get('/', (c) => {
|
|
1537
|
+
* return c.render('Hello!')
|
|
1538
|
+
* })
|
|
1539
|
+
* ```
|
|
1540
|
+
*/
|
|
1541
|
+
render = (...args) => {
|
|
1542
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1543
|
+
return this.#renderer(...args);
|
|
1544
|
+
};
|
|
1545
|
+
/**
|
|
1546
|
+
* Sets the layout for the response.
|
|
1547
|
+
*
|
|
1548
|
+
* @param layout - The layout to set.
|
|
1549
|
+
* @returns The layout function.
|
|
1550
|
+
*/
|
|
1551
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1552
|
+
/**
|
|
1553
|
+
* Gets the current layout for the response.
|
|
1554
|
+
*
|
|
1555
|
+
* @returns The current layout function.
|
|
1556
|
+
*/
|
|
1557
|
+
getLayout = () => this.#layout;
|
|
1558
|
+
/**
|
|
1559
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
1560
|
+
*
|
|
1561
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1562
|
+
*
|
|
1563
|
+
* @example
|
|
1564
|
+
* ```tsx
|
|
1565
|
+
* app.use('*', async (c, next) => {
|
|
1566
|
+
* c.setRenderer((content) => {
|
|
1567
|
+
* return c.html(
|
|
1568
|
+
* <html>
|
|
1569
|
+
* <body>
|
|
1570
|
+
* <p>{content}</p>
|
|
1571
|
+
* </body>
|
|
1572
|
+
* </html>
|
|
1573
|
+
* )
|
|
1574
|
+
* })
|
|
1575
|
+
* await next()
|
|
1576
|
+
* })
|
|
1577
|
+
* ```
|
|
1578
|
+
*/
|
|
1579
|
+
setRenderer = (renderer) => {
|
|
1580
|
+
this.#renderer = renderer;
|
|
1581
|
+
};
|
|
1582
|
+
/**
|
|
1583
|
+
* `.header()` can set headers.
|
|
1584
|
+
*
|
|
1585
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
1586
|
+
*
|
|
1587
|
+
* @example
|
|
1588
|
+
* ```ts
|
|
1589
|
+
* app.get('/welcome', (c) => {
|
|
1590
|
+
* // Set headers
|
|
1591
|
+
* c.header('X-Message', 'Hello!')
|
|
1592
|
+
* c.header('Content-Type', 'text/plain')
|
|
1593
|
+
*
|
|
1594
|
+
* return c.body('Thank you for coming')
|
|
1595
|
+
* })
|
|
1596
|
+
* ```
|
|
1597
|
+
*/
|
|
1598
|
+
header = (name, value, options) => {
|
|
1599
|
+
if (this.finalized) {
|
|
1600
|
+
this.#res = new Response(this.#res.body, this.#res);
|
|
1601
|
+
}
|
|
1602
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
1603
|
+
if (value === void 0) {
|
|
1604
|
+
headers.delete(name);
|
|
1605
|
+
} else if (options?.append) {
|
|
1606
|
+
headers.append(name, value);
|
|
1607
|
+
} else {
|
|
1608
|
+
headers.set(name, value);
|
|
1609
|
+
}
|
|
1610
|
+
};
|
|
1611
|
+
status = (status) => {
|
|
1612
|
+
this.#status = status;
|
|
1613
|
+
};
|
|
1614
|
+
/**
|
|
1615
|
+
* `.set()` can set the value specified by the key.
|
|
1616
|
+
*
|
|
1617
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1618
|
+
*
|
|
1619
|
+
* @example
|
|
1620
|
+
* ```ts
|
|
1621
|
+
* app.use('*', async (c, next) => {
|
|
1622
|
+
* c.set('message', 'Hono is hot!!')
|
|
1623
|
+
* await next()
|
|
1624
|
+
* })
|
|
1625
|
+
* ```
|
|
1626
|
+
*/
|
|
1627
|
+
set = (key, value) => {
|
|
1628
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
1629
|
+
this.#var.set(key, value);
|
|
1630
|
+
};
|
|
1631
|
+
/**
|
|
1632
|
+
* `.get()` can use the value specified by the key.
|
|
1633
|
+
*
|
|
1634
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1635
|
+
*
|
|
1636
|
+
* @example
|
|
1637
|
+
* ```ts
|
|
1638
|
+
* app.get('/', (c) => {
|
|
1639
|
+
* const message = c.get('message')
|
|
1640
|
+
* return c.text(`The message is "${message}"`)
|
|
1641
|
+
* })
|
|
1642
|
+
* ```
|
|
1643
|
+
*/
|
|
1644
|
+
get = (key) => {
|
|
1645
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
1646
|
+
};
|
|
1647
|
+
/**
|
|
1648
|
+
* `.var` can access the value of a variable.
|
|
1649
|
+
*
|
|
1650
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
1651
|
+
*
|
|
1652
|
+
* @example
|
|
1653
|
+
* ```ts
|
|
1654
|
+
* const result = c.var.client.oneMethod()
|
|
1655
|
+
* ```
|
|
1656
|
+
*/
|
|
1657
|
+
// c.var.propName is a read-only
|
|
1658
|
+
get var() {
|
|
1659
|
+
if (!this.#var) {
|
|
1660
|
+
return {};
|
|
1661
|
+
}
|
|
1662
|
+
return Object.fromEntries(this.#var);
|
|
1663
|
+
}
|
|
1664
|
+
#newResponse(data, arg, headers) {
|
|
1665
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
1666
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
1667
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
1668
|
+
for (const [key, value] of argHeaders) {
|
|
1669
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1670
|
+
responseHeaders.append(key, value);
|
|
1671
|
+
} else {
|
|
1672
|
+
responseHeaders.set(key, value);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
if (headers) {
|
|
1677
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1678
|
+
if (typeof v === "string") {
|
|
1679
|
+
responseHeaders.set(k, v);
|
|
1680
|
+
} else {
|
|
1681
|
+
responseHeaders.delete(k);
|
|
1682
|
+
for (const v2 of v) {
|
|
1683
|
+
responseHeaders.append(k, v2);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1689
|
+
return new Response(data, { status, headers: responseHeaders });
|
|
1690
|
+
}
|
|
1691
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1692
|
+
/**
|
|
1693
|
+
* `.body()` can return the HTTP response.
|
|
1694
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
1695
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
1696
|
+
*
|
|
1697
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
1698
|
+
*
|
|
1699
|
+
* @example
|
|
1700
|
+
* ```ts
|
|
1701
|
+
* app.get('/welcome', (c) => {
|
|
1702
|
+
* // Set headers
|
|
1703
|
+
* c.header('X-Message', 'Hello!')
|
|
1704
|
+
* c.header('Content-Type', 'text/plain')
|
|
1705
|
+
* // Set HTTP status code
|
|
1706
|
+
* c.status(201)
|
|
1707
|
+
*
|
|
1708
|
+
* // Return the response body
|
|
1709
|
+
* return c.body('Thank you for coming')
|
|
1710
|
+
* })
|
|
1711
|
+
* ```
|
|
1712
|
+
*/
|
|
1713
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1714
|
+
/**
|
|
1715
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
1716
|
+
*
|
|
1717
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
1718
|
+
*
|
|
1719
|
+
* @example
|
|
1720
|
+
* ```ts
|
|
1721
|
+
* app.get('/say', (c) => {
|
|
1722
|
+
* return c.text('Hello!')
|
|
1723
|
+
* })
|
|
1724
|
+
* ```
|
|
1725
|
+
*/
|
|
1726
|
+
text = (text, arg, headers) => {
|
|
1727
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
1728
|
+
text,
|
|
1729
|
+
arg,
|
|
1730
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
1731
|
+
);
|
|
1732
|
+
};
|
|
1733
|
+
/**
|
|
1734
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
1735
|
+
*
|
|
1736
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
1737
|
+
*
|
|
1738
|
+
* @example
|
|
1739
|
+
* ```ts
|
|
1740
|
+
* app.get('/api', (c) => {
|
|
1741
|
+
* return c.json({ message: 'Hello!' })
|
|
1742
|
+
* })
|
|
1743
|
+
* ```
|
|
1744
|
+
*/
|
|
1745
|
+
json = (object, arg, headers) => {
|
|
1746
|
+
return this.#newResponse(
|
|
1747
|
+
JSON.stringify(object),
|
|
1748
|
+
arg,
|
|
1749
|
+
setDefaultContentType("application/json", headers)
|
|
1750
|
+
);
|
|
1751
|
+
};
|
|
1752
|
+
html = (html, arg, headers) => {
|
|
1753
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1754
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1755
|
+
};
|
|
1756
|
+
/**
|
|
1757
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1758
|
+
*
|
|
1759
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1760
|
+
*
|
|
1761
|
+
* @example
|
|
1762
|
+
* ```ts
|
|
1763
|
+
* app.get('/redirect', (c) => {
|
|
1764
|
+
* return c.redirect('/')
|
|
1765
|
+
* })
|
|
1766
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1767
|
+
* return c.redirect('/', 301)
|
|
1768
|
+
* })
|
|
1769
|
+
* ```
|
|
1770
|
+
*/
|
|
1771
|
+
redirect = (location, status) => {
|
|
1772
|
+
const locationString = String(location);
|
|
1773
|
+
this.header(
|
|
1774
|
+
"Location",
|
|
1775
|
+
// Multibyes should be encoded
|
|
1776
|
+
// eslint-disable-next-line no-control-regex
|
|
1777
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1778
|
+
);
|
|
1779
|
+
return this.newResponse(null, status ?? 302);
|
|
1780
|
+
};
|
|
1781
|
+
/**
|
|
1782
|
+
* `.notFound()` can return the Not Found Response.
|
|
1783
|
+
*
|
|
1784
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1785
|
+
*
|
|
1786
|
+
* @example
|
|
1787
|
+
* ```ts
|
|
1788
|
+
* app.get('/notfound', (c) => {
|
|
1789
|
+
* return c.notFound()
|
|
1790
|
+
* })
|
|
1791
|
+
* ```
|
|
1792
|
+
*/
|
|
1793
|
+
notFound = () => {
|
|
1794
|
+
this.#notFoundHandler ??= () => new Response();
|
|
1795
|
+
return this.#notFoundHandler(this);
|
|
1796
|
+
};
|
|
1797
|
+
};
|
|
1798
|
+
|
|
1799
|
+
// node_modules/hono/dist/router.js
|
|
1800
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1801
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1802
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1803
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1804
|
+
var UnsupportedPathError = class extends Error {
|
|
1805
|
+
};
|
|
1806
|
+
|
|
1807
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1808
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1809
|
+
|
|
1810
|
+
// node_modules/hono/dist/hono-base.js
|
|
1811
|
+
var notFoundHandler = (c) => {
|
|
1812
|
+
return c.text("404 Not Found", 404);
|
|
1813
|
+
};
|
|
1814
|
+
var errorHandler = (err, c) => {
|
|
1815
|
+
if ("getResponse" in err) {
|
|
1816
|
+
const res = err.getResponse();
|
|
1817
|
+
return c.newResponse(res.body, res);
|
|
1818
|
+
}
|
|
1819
|
+
console.error(err);
|
|
1820
|
+
return c.text("Internal Server Error", 500);
|
|
1821
|
+
};
|
|
1822
|
+
var Hono = class _Hono {
|
|
1823
|
+
get;
|
|
1824
|
+
post;
|
|
1825
|
+
put;
|
|
1826
|
+
delete;
|
|
1827
|
+
options;
|
|
1828
|
+
patch;
|
|
1829
|
+
all;
|
|
1830
|
+
on;
|
|
1831
|
+
use;
|
|
1832
|
+
/*
|
|
1833
|
+
This class is like an abstract class and does not have a router.
|
|
1834
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1835
|
+
*/
|
|
1836
|
+
router;
|
|
1837
|
+
getPath;
|
|
1838
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1839
|
+
_basePath = "/";
|
|
1840
|
+
#path = "/";
|
|
1841
|
+
routes = [];
|
|
1842
|
+
constructor(options = {}) {
|
|
1843
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1844
|
+
allMethods.forEach((method) => {
|
|
1845
|
+
this[method] = (args1, ...args) => {
|
|
1846
|
+
if (typeof args1 === "string") {
|
|
1847
|
+
this.#path = args1;
|
|
1848
|
+
} else {
|
|
1849
|
+
this.#addRoute(method, this.#path, args1);
|
|
1850
|
+
}
|
|
1851
|
+
args.forEach((handler) => {
|
|
1852
|
+
this.#addRoute(method, this.#path, handler);
|
|
1853
|
+
});
|
|
1854
|
+
return this;
|
|
1855
|
+
};
|
|
1856
|
+
});
|
|
1857
|
+
this.on = (method, path4, ...handlers) => {
|
|
1858
|
+
for (const p of [path4].flat()) {
|
|
1859
|
+
this.#path = p;
|
|
1860
|
+
for (const m of [method].flat()) {
|
|
1861
|
+
handlers.map((handler) => {
|
|
1862
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
return this;
|
|
1867
|
+
};
|
|
1868
|
+
this.use = (arg1, ...handlers) => {
|
|
1869
|
+
if (typeof arg1 === "string") {
|
|
1870
|
+
this.#path = arg1;
|
|
1871
|
+
} else {
|
|
1872
|
+
this.#path = "*";
|
|
1873
|
+
handlers.unshift(arg1);
|
|
1874
|
+
}
|
|
1875
|
+
handlers.forEach((handler) => {
|
|
1876
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1877
|
+
});
|
|
1878
|
+
return this;
|
|
1879
|
+
};
|
|
1880
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1881
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1882
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1883
|
+
}
|
|
1884
|
+
#clone() {
|
|
1885
|
+
const clone = new _Hono({
|
|
1886
|
+
router: this.router,
|
|
1887
|
+
getPath: this.getPath
|
|
1888
|
+
});
|
|
1889
|
+
clone.errorHandler = this.errorHandler;
|
|
1890
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1891
|
+
clone.routes = this.routes;
|
|
1892
|
+
return clone;
|
|
1893
|
+
}
|
|
1894
|
+
#notFoundHandler = notFoundHandler;
|
|
1895
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1896
|
+
errorHandler = errorHandler;
|
|
1897
|
+
/**
|
|
1898
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1899
|
+
*
|
|
1900
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1901
|
+
*
|
|
1902
|
+
* @param {string} path - base Path
|
|
1903
|
+
* @param {Hono} app - other Hono instance
|
|
1904
|
+
* @returns {Hono} routed Hono instance
|
|
1905
|
+
*
|
|
1906
|
+
* @example
|
|
1907
|
+
* ```ts
|
|
1908
|
+
* const app = new Hono()
|
|
1909
|
+
* const app2 = new Hono()
|
|
1910
|
+
*
|
|
1911
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1912
|
+
* app.route("/api", app2) // GET /api/user
|
|
1913
|
+
* ```
|
|
1914
|
+
*/
|
|
1915
|
+
route(path4, app2) {
|
|
1916
|
+
const subApp = this.basePath(path4);
|
|
1917
|
+
app2.routes.map((r) => {
|
|
1918
|
+
let handler;
|
|
1919
|
+
if (app2.errorHandler === errorHandler) {
|
|
1920
|
+
handler = r.handler;
|
|
1921
|
+
} else {
|
|
1922
|
+
handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1923
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1924
|
+
}
|
|
1925
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
1926
|
+
});
|
|
1927
|
+
return this;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* `.basePath()` allows base paths to be specified.
|
|
1931
|
+
*
|
|
1932
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1933
|
+
*
|
|
1934
|
+
* @param {string} path - base Path
|
|
1935
|
+
* @returns {Hono} changed Hono instance
|
|
1936
|
+
*
|
|
1937
|
+
* @example
|
|
1938
|
+
* ```ts
|
|
1939
|
+
* const api = new Hono().basePath('/api')
|
|
1940
|
+
* ```
|
|
1941
|
+
*/
|
|
1942
|
+
basePath(path4) {
|
|
1943
|
+
const subApp = this.#clone();
|
|
1944
|
+
subApp._basePath = mergePath(this._basePath, path4);
|
|
1945
|
+
return subApp;
|
|
1946
|
+
}
|
|
1947
|
+
/**
|
|
1948
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
1949
|
+
*
|
|
1950
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
1951
|
+
*
|
|
1952
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
1953
|
+
* @returns {Hono} changed Hono instance
|
|
1954
|
+
*
|
|
1955
|
+
* @example
|
|
1956
|
+
* ```ts
|
|
1957
|
+
* app.onError((err, c) => {
|
|
1958
|
+
* console.error(`${err}`)
|
|
1959
|
+
* return c.text('Custom Error Message', 500)
|
|
1960
|
+
* })
|
|
1961
|
+
* ```
|
|
1962
|
+
*/
|
|
1963
|
+
onError = (handler) => {
|
|
1964
|
+
this.errorHandler = handler;
|
|
1965
|
+
return this;
|
|
1966
|
+
};
|
|
1967
|
+
/**
|
|
1968
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
1969
|
+
*
|
|
1970
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
1971
|
+
*
|
|
1972
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
1973
|
+
* @returns {Hono} changed Hono instance
|
|
1974
|
+
*
|
|
1975
|
+
* @example
|
|
1976
|
+
* ```ts
|
|
1977
|
+
* app.notFound((c) => {
|
|
1978
|
+
* return c.text('Custom 404 Message', 404)
|
|
1979
|
+
* })
|
|
1980
|
+
* ```
|
|
1981
|
+
*/
|
|
1982
|
+
notFound = (handler) => {
|
|
1983
|
+
this.#notFoundHandler = handler;
|
|
1984
|
+
return this;
|
|
1985
|
+
};
|
|
1986
|
+
/**
|
|
1987
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
1988
|
+
*
|
|
1989
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
1990
|
+
*
|
|
1991
|
+
* @param {string} path - base Path
|
|
1992
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
1993
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
1994
|
+
* @returns {Hono} mounted Hono instance
|
|
1995
|
+
*
|
|
1996
|
+
* @example
|
|
1997
|
+
* ```ts
|
|
1998
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
1999
|
+
* import { Hono } from 'hono'
|
|
2000
|
+
* // Create itty-router application
|
|
2001
|
+
* const ittyRouter = IttyRouter()
|
|
2002
|
+
* // GET /itty-router/hello
|
|
2003
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
2004
|
+
*
|
|
2005
|
+
* const app = new Hono()
|
|
2006
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
2007
|
+
* ```
|
|
2008
|
+
*
|
|
2009
|
+
* @example
|
|
2010
|
+
* ```ts
|
|
2011
|
+
* const app = new Hono()
|
|
2012
|
+
* // Send the request to another application without modification.
|
|
2013
|
+
* app.mount('/app', anotherApp, {
|
|
2014
|
+
* replaceRequest: (req) => req,
|
|
2015
|
+
* })
|
|
2016
|
+
* ```
|
|
2017
|
+
*/
|
|
2018
|
+
mount(path4, applicationHandler, options) {
|
|
2019
|
+
let replaceRequest;
|
|
2020
|
+
let optionHandler;
|
|
2021
|
+
if (options) {
|
|
2022
|
+
if (typeof options === "function") {
|
|
2023
|
+
optionHandler = options;
|
|
2024
|
+
} else {
|
|
2025
|
+
optionHandler = options.optionHandler;
|
|
2026
|
+
if (options.replaceRequest === false) {
|
|
2027
|
+
replaceRequest = (request) => request;
|
|
2028
|
+
} else {
|
|
2029
|
+
replaceRequest = options.replaceRequest;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
const getOptions = optionHandler ? (c) => {
|
|
2034
|
+
const options2 = optionHandler(c);
|
|
2035
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
2036
|
+
} : (c) => {
|
|
2037
|
+
let executionContext = void 0;
|
|
2038
|
+
try {
|
|
2039
|
+
executionContext = c.executionCtx;
|
|
2040
|
+
} catch {
|
|
2041
|
+
}
|
|
2042
|
+
return [c.env, executionContext];
|
|
2043
|
+
};
|
|
2044
|
+
replaceRequest ||= (() => {
|
|
2045
|
+
const mergedPath = mergePath(this._basePath, path4);
|
|
2046
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2047
|
+
return (request) => {
|
|
2048
|
+
const url = new URL(request.url);
|
|
2049
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
2050
|
+
return new Request(url, request);
|
|
2051
|
+
};
|
|
2052
|
+
})();
|
|
2053
|
+
const handler = async (c, next) => {
|
|
2054
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2055
|
+
if (res) {
|
|
2056
|
+
return res;
|
|
2057
|
+
}
|
|
2058
|
+
await next();
|
|
2059
|
+
};
|
|
2060
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path4, "*"), handler);
|
|
2061
|
+
return this;
|
|
2062
|
+
}
|
|
2063
|
+
#addRoute(method, path4, handler) {
|
|
2064
|
+
method = method.toUpperCase();
|
|
2065
|
+
path4 = mergePath(this._basePath, path4);
|
|
2066
|
+
const r = { basePath: this._basePath, path: path4, method, handler };
|
|
2067
|
+
this.router.add(method, path4, [handler, r]);
|
|
2068
|
+
this.routes.push(r);
|
|
2069
|
+
}
|
|
2070
|
+
#handleError(err, c) {
|
|
2071
|
+
if (err instanceof Error) {
|
|
2072
|
+
return this.errorHandler(err, c);
|
|
2073
|
+
}
|
|
2074
|
+
throw err;
|
|
2075
|
+
}
|
|
2076
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2077
|
+
if (method === "HEAD") {
|
|
2078
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2079
|
+
}
|
|
2080
|
+
const path4 = this.getPath(request, { env });
|
|
2081
|
+
const matchResult = this.router.match(method, path4);
|
|
2082
|
+
const c = new Context(request, {
|
|
2083
|
+
path: path4,
|
|
2084
|
+
matchResult,
|
|
2085
|
+
env,
|
|
2086
|
+
executionCtx,
|
|
2087
|
+
notFoundHandler: this.#notFoundHandler
|
|
2088
|
+
});
|
|
2089
|
+
if (matchResult[0].length === 1) {
|
|
2090
|
+
let res;
|
|
2091
|
+
try {
|
|
2092
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2093
|
+
c.res = await this.#notFoundHandler(c);
|
|
2094
|
+
});
|
|
2095
|
+
} catch (err) {
|
|
2096
|
+
return this.#handleError(err, c);
|
|
2097
|
+
}
|
|
2098
|
+
return res instanceof Promise ? res.then(
|
|
2099
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
2100
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2101
|
+
}
|
|
2102
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2103
|
+
return (async () => {
|
|
2104
|
+
try {
|
|
2105
|
+
const context = await composed(c);
|
|
2106
|
+
if (!context.finalized) {
|
|
2107
|
+
throw new Error(
|
|
2108
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
2109
|
+
);
|
|
2110
|
+
}
|
|
2111
|
+
return context.res;
|
|
2112
|
+
} catch (err) {
|
|
2113
|
+
return this.#handleError(err, c);
|
|
2114
|
+
}
|
|
2115
|
+
})();
|
|
2116
|
+
}
|
|
2117
|
+
/**
|
|
2118
|
+
* `.fetch()` will be entry point of your app.
|
|
2119
|
+
*
|
|
2120
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
2121
|
+
*
|
|
2122
|
+
* @param {Request} request - request Object of request
|
|
2123
|
+
* @param {Env} Env - env Object
|
|
2124
|
+
* @param {ExecutionContext} - context of execution
|
|
2125
|
+
* @returns {Response | Promise<Response>} response of request
|
|
2126
|
+
*
|
|
2127
|
+
*/
|
|
2128
|
+
fetch = (request, ...rest) => {
|
|
2129
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2130
|
+
};
|
|
2131
|
+
/**
|
|
2132
|
+
* `.request()` is a useful method for testing.
|
|
2133
|
+
* You can pass a URL or pathname to send a GET request.
|
|
2134
|
+
* app will return a Response object.
|
|
2135
|
+
* ```ts
|
|
2136
|
+
* test('GET /hello is ok', async () => {
|
|
2137
|
+
* const res = await app.request('/hello')
|
|
2138
|
+
* expect(res.status).toBe(200)
|
|
2139
|
+
* })
|
|
2140
|
+
* ```
|
|
2141
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
2142
|
+
*/
|
|
2143
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2144
|
+
if (input instanceof Request) {
|
|
2145
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2146
|
+
}
|
|
2147
|
+
input = input.toString();
|
|
2148
|
+
return this.fetch(
|
|
2149
|
+
new Request(
|
|
2150
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
2151
|
+
requestInit
|
|
2152
|
+
),
|
|
2153
|
+
Env,
|
|
2154
|
+
executionCtx
|
|
2155
|
+
);
|
|
2156
|
+
};
|
|
2157
|
+
/**
|
|
2158
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
2159
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
2160
|
+
* @deprecated
|
|
2161
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
2162
|
+
* ```ts
|
|
2163
|
+
* import { Hono } from 'hono'
|
|
2164
|
+
* import { fire } from 'hono/service-worker'
|
|
2165
|
+
*
|
|
2166
|
+
* const app = new Hono()
|
|
2167
|
+
* // ...
|
|
2168
|
+
* fire(app)
|
|
2169
|
+
* ```
|
|
2170
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
2171
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
2172
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
2173
|
+
*/
|
|
2174
|
+
fire = () => {
|
|
2175
|
+
addEventListener("fetch", (event) => {
|
|
2176
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
2177
|
+
});
|
|
2178
|
+
};
|
|
2179
|
+
};
|
|
2180
|
+
|
|
2181
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2182
|
+
var emptyParam = [];
|
|
2183
|
+
function match(method, path4) {
|
|
2184
|
+
const matchers = this.buildAllMatchers();
|
|
2185
|
+
const match2 = (method2, path22) => {
|
|
2186
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2187
|
+
const staticMatch = matcher[2][path22];
|
|
2188
|
+
if (staticMatch) {
|
|
2189
|
+
return staticMatch;
|
|
2190
|
+
}
|
|
2191
|
+
const match3 = path22.match(matcher[0]);
|
|
2192
|
+
if (!match3) {
|
|
2193
|
+
return [[], emptyParam];
|
|
2194
|
+
}
|
|
2195
|
+
const index = match3.indexOf("", 1);
|
|
2196
|
+
return [matcher[1][index], match3];
|
|
2197
|
+
};
|
|
2198
|
+
this.match = match2;
|
|
2199
|
+
return match2(method, path4);
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2203
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2204
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2205
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2206
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2207
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2208
|
+
function compareKey(a, b) {
|
|
2209
|
+
if (a.length === 1) {
|
|
2210
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2211
|
+
}
|
|
2212
|
+
if (b.length === 1) {
|
|
2213
|
+
return 1;
|
|
2214
|
+
}
|
|
2215
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2216
|
+
return 1;
|
|
2217
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2218
|
+
return -1;
|
|
2219
|
+
}
|
|
2220
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
2221
|
+
return 1;
|
|
2222
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
2223
|
+
return -1;
|
|
2224
|
+
}
|
|
2225
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
2226
|
+
}
|
|
2227
|
+
var Node = class _Node {
|
|
2228
|
+
#index;
|
|
2229
|
+
#varIndex;
|
|
2230
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
2231
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
2232
|
+
if (tokens.length === 0) {
|
|
2233
|
+
if (this.#index !== void 0) {
|
|
2234
|
+
throw PATH_ERROR;
|
|
2235
|
+
}
|
|
2236
|
+
if (pathErrorCheckOnly) {
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
this.#index = index;
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
const [token, ...restTokens] = tokens;
|
|
2243
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2244
|
+
let node;
|
|
2245
|
+
if (pattern) {
|
|
2246
|
+
const name = pattern[1];
|
|
2247
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
2248
|
+
if (name && pattern[2]) {
|
|
2249
|
+
if (regexpStr === ".*") {
|
|
2250
|
+
throw PATH_ERROR;
|
|
2251
|
+
}
|
|
2252
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
2253
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
2254
|
+
throw PATH_ERROR;
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
node = this.#children[regexpStr];
|
|
2258
|
+
if (!node) {
|
|
2259
|
+
if (Object.keys(this.#children).some(
|
|
2260
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2261
|
+
)) {
|
|
2262
|
+
throw PATH_ERROR;
|
|
2263
|
+
}
|
|
2264
|
+
if (pathErrorCheckOnly) {
|
|
2265
|
+
return;
|
|
2266
|
+
}
|
|
2267
|
+
node = this.#children[regexpStr] = new _Node();
|
|
2268
|
+
if (name !== "") {
|
|
2269
|
+
node.#varIndex = context.varIndex++;
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
2273
|
+
paramMap.push([name, node.#varIndex]);
|
|
2274
|
+
}
|
|
2275
|
+
} else {
|
|
2276
|
+
node = this.#children[token];
|
|
2277
|
+
if (!node) {
|
|
2278
|
+
if (Object.keys(this.#children).some(
|
|
2279
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2280
|
+
)) {
|
|
2281
|
+
throw PATH_ERROR;
|
|
2282
|
+
}
|
|
2283
|
+
if (pathErrorCheckOnly) {
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
node = this.#children[token] = new _Node();
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
2290
|
+
}
|
|
2291
|
+
buildRegExpStr() {
|
|
2292
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
2293
|
+
const strList = childKeys.map((k) => {
|
|
2294
|
+
const c = this.#children[k];
|
|
2295
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
2296
|
+
});
|
|
2297
|
+
if (typeof this.#index === "number") {
|
|
2298
|
+
strList.unshift(`#${this.#index}`);
|
|
2299
|
+
}
|
|
2300
|
+
if (strList.length === 0) {
|
|
2301
|
+
return "";
|
|
2302
|
+
}
|
|
2303
|
+
if (strList.length === 1) {
|
|
2304
|
+
return strList[0];
|
|
2305
|
+
}
|
|
2306
|
+
return "(?:" + strList.join("|") + ")";
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
|
|
2310
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
2311
|
+
var Trie = class {
|
|
2312
|
+
#context = { varIndex: 0 };
|
|
2313
|
+
#root = new Node();
|
|
2314
|
+
insert(path4, index, pathErrorCheckOnly) {
|
|
2315
|
+
const paramAssoc = [];
|
|
2316
|
+
const groups = [];
|
|
2317
|
+
for (let i = 0; ; ) {
|
|
2318
|
+
let replaced = false;
|
|
2319
|
+
path4 = path4.replace(/\{[^}]+\}/g, (m) => {
|
|
2320
|
+
const mark = `@\\${i}`;
|
|
2321
|
+
groups[i] = [mark, m];
|
|
2322
|
+
i++;
|
|
2323
|
+
replaced = true;
|
|
2324
|
+
return mark;
|
|
2325
|
+
});
|
|
2326
|
+
if (!replaced) {
|
|
2327
|
+
break;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
const tokens = path4.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
2331
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
2332
|
+
const [mark] = groups[i];
|
|
2333
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
2334
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
2335
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
2336
|
+
break;
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
2341
|
+
return paramAssoc;
|
|
2342
|
+
}
|
|
2343
|
+
buildRegExp() {
|
|
2344
|
+
let regexp = this.#root.buildRegExpStr();
|
|
2345
|
+
if (regexp === "") {
|
|
2346
|
+
return [/^$/, [], []];
|
|
2347
|
+
}
|
|
2348
|
+
let captureIndex = 0;
|
|
2349
|
+
const indexReplacementMap = [];
|
|
2350
|
+
const paramReplacementMap = [];
|
|
2351
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
2352
|
+
if (handlerIndex !== void 0) {
|
|
2353
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
2354
|
+
return "$()";
|
|
2355
|
+
}
|
|
2356
|
+
if (paramIndex !== void 0) {
|
|
2357
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
2358
|
+
return "";
|
|
2359
|
+
}
|
|
2360
|
+
return "";
|
|
2361
|
+
});
|
|
2362
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
2363
|
+
}
|
|
2364
|
+
};
|
|
2365
|
+
|
|
2366
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
2367
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
2368
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2369
|
+
function buildWildcardRegExp(path4) {
|
|
2370
|
+
return wildcardRegExpCache[path4] ??= new RegExp(
|
|
2371
|
+
path4 === "*" ? "" : `^${path4.replace(
|
|
2372
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
2373
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
2374
|
+
)}$`
|
|
2375
|
+
);
|
|
2376
|
+
}
|
|
2377
|
+
function clearWildcardRegExpCache() {
|
|
2378
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2379
|
+
}
|
|
2380
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
2381
|
+
const trie = new Trie();
|
|
2382
|
+
const handlerData = [];
|
|
2383
|
+
if (routes.length === 0) {
|
|
2384
|
+
return nullMatcher;
|
|
2385
|
+
}
|
|
2386
|
+
const routesWithStaticPathFlag = routes.map(
|
|
2387
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
2388
|
+
).sort(
|
|
2389
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
2390
|
+
);
|
|
2391
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
2392
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
2393
|
+
const [pathErrorCheckOnly, path4, handlers] = routesWithStaticPathFlag[i];
|
|
2394
|
+
if (pathErrorCheckOnly) {
|
|
2395
|
+
staticMap[path4] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
2396
|
+
} else {
|
|
2397
|
+
j++;
|
|
2398
|
+
}
|
|
2399
|
+
let paramAssoc;
|
|
2400
|
+
try {
|
|
2401
|
+
paramAssoc = trie.insert(path4, j, pathErrorCheckOnly);
|
|
2402
|
+
} catch (e) {
|
|
2403
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path4) : e;
|
|
2404
|
+
}
|
|
2405
|
+
if (pathErrorCheckOnly) {
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
2409
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
2410
|
+
paramCount -= 1;
|
|
2411
|
+
for (; paramCount >= 0; paramCount--) {
|
|
2412
|
+
const [key, value] = paramAssoc[paramCount];
|
|
2413
|
+
paramIndexMap[key] = value;
|
|
2414
|
+
}
|
|
2415
|
+
return [h, paramIndexMap];
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
2419
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
2420
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
2421
|
+
const map = handlerData[i][j]?.[1];
|
|
2422
|
+
if (!map) {
|
|
2423
|
+
continue;
|
|
2424
|
+
}
|
|
2425
|
+
const keys = Object.keys(map);
|
|
2426
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
2427
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
const handlerMap = [];
|
|
2432
|
+
for (const i in indexReplacementMap) {
|
|
2433
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
2434
|
+
}
|
|
2435
|
+
return [regexp, handlerMap, staticMap];
|
|
2436
|
+
}
|
|
2437
|
+
function findMiddleware(middleware, path4) {
|
|
2438
|
+
if (!middleware) {
|
|
2439
|
+
return void 0;
|
|
2440
|
+
}
|
|
2441
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
2442
|
+
if (buildWildcardRegExp(k).test(path4)) {
|
|
2443
|
+
return [...middleware[k]];
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return void 0;
|
|
2447
|
+
}
|
|
2448
|
+
var RegExpRouter = class {
|
|
2449
|
+
name = "RegExpRouter";
|
|
2450
|
+
#middleware;
|
|
2451
|
+
#routes;
|
|
2452
|
+
constructor() {
|
|
2453
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2454
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2455
|
+
}
|
|
2456
|
+
add(method, path4, handler) {
|
|
2457
|
+
const middleware = this.#middleware;
|
|
2458
|
+
const routes = this.#routes;
|
|
2459
|
+
if (!middleware || !routes) {
|
|
2460
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2461
|
+
}
|
|
2462
|
+
if (!middleware[method]) {
|
|
2463
|
+
;
|
|
2464
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
2465
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
2466
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
2467
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
2468
|
+
});
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
if (path4 === "/*") {
|
|
2472
|
+
path4 = "*";
|
|
2473
|
+
}
|
|
2474
|
+
const paramCount = (path4.match(/\/:/g) || []).length;
|
|
2475
|
+
if (/\*$/.test(path4)) {
|
|
2476
|
+
const re = buildWildcardRegExp(path4);
|
|
2477
|
+
if (method === METHOD_NAME_ALL) {
|
|
2478
|
+
Object.keys(middleware).forEach((m) => {
|
|
2479
|
+
middleware[m][path4] ||= findMiddleware(middleware[m], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
|
|
2480
|
+
});
|
|
2481
|
+
} else {
|
|
2482
|
+
middleware[method][path4] ||= findMiddleware(middleware[method], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
|
|
2483
|
+
}
|
|
2484
|
+
Object.keys(middleware).forEach((m) => {
|
|
2485
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2486
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
2487
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
});
|
|
2491
|
+
Object.keys(routes).forEach((m) => {
|
|
2492
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2493
|
+
Object.keys(routes[m]).forEach(
|
|
2494
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
2495
|
+
);
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
return;
|
|
2499
|
+
}
|
|
2500
|
+
const paths = checkOptionalParameter(path4) || [path4];
|
|
2501
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
2502
|
+
const path22 = paths[i];
|
|
2503
|
+
Object.keys(routes).forEach((m) => {
|
|
2504
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2505
|
+
routes[m][path22] ||= [
|
|
2506
|
+
...findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
|
|
2507
|
+
];
|
|
2508
|
+
routes[m][path22].push([handler, paramCount - len + i + 1]);
|
|
2509
|
+
}
|
|
2510
|
+
});
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
match = match;
|
|
2514
|
+
buildAllMatchers() {
|
|
2515
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
2516
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
2517
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
2518
|
+
});
|
|
2519
|
+
this.#middleware = this.#routes = void 0;
|
|
2520
|
+
clearWildcardRegExpCache();
|
|
2521
|
+
return matchers;
|
|
2522
|
+
}
|
|
2523
|
+
#buildMatcher(method) {
|
|
2524
|
+
const routes = [];
|
|
2525
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
2526
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
2527
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path4) => [path4, r[method][path4]]) : [];
|
|
2528
|
+
if (ownRoute.length !== 0) {
|
|
2529
|
+
hasOwnRoute ||= true;
|
|
2530
|
+
routes.push(...ownRoute);
|
|
2531
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
2532
|
+
routes.push(
|
|
2533
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path4) => [path4, r[METHOD_NAME_ALL][path4]])
|
|
2534
|
+
);
|
|
2535
|
+
}
|
|
2536
|
+
});
|
|
2537
|
+
if (!hasOwnRoute) {
|
|
2538
|
+
return null;
|
|
2539
|
+
} else {
|
|
2540
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
};
|
|
2544
|
+
|
|
2545
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
2546
|
+
var SmartRouter = class {
|
|
2547
|
+
name = "SmartRouter";
|
|
2548
|
+
#routers = [];
|
|
2549
|
+
#routes = [];
|
|
2550
|
+
constructor(init) {
|
|
2551
|
+
this.#routers = init.routers;
|
|
2552
|
+
}
|
|
2553
|
+
add(method, path4, handler) {
|
|
2554
|
+
if (!this.#routes) {
|
|
2555
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2556
|
+
}
|
|
2557
|
+
this.#routes.push([method, path4, handler]);
|
|
2558
|
+
}
|
|
2559
|
+
match(method, path4) {
|
|
2560
|
+
if (!this.#routes) {
|
|
2561
|
+
throw new Error("Fatal error");
|
|
2562
|
+
}
|
|
2563
|
+
const routers = this.#routers;
|
|
2564
|
+
const routes = this.#routes;
|
|
2565
|
+
const len = routers.length;
|
|
2566
|
+
let i = 0;
|
|
2567
|
+
let res;
|
|
2568
|
+
for (; i < len; i++) {
|
|
2569
|
+
const router = routers[i];
|
|
2570
|
+
try {
|
|
2571
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
2572
|
+
router.add(...routes[i2]);
|
|
2573
|
+
}
|
|
2574
|
+
res = router.match(method, path4);
|
|
2575
|
+
} catch (e) {
|
|
2576
|
+
if (e instanceof UnsupportedPathError) {
|
|
2577
|
+
continue;
|
|
2578
|
+
}
|
|
2579
|
+
throw e;
|
|
2580
|
+
}
|
|
2581
|
+
this.match = router.match.bind(router);
|
|
2582
|
+
this.#routers = [router];
|
|
2583
|
+
this.#routes = void 0;
|
|
2584
|
+
break;
|
|
2585
|
+
}
|
|
2586
|
+
if (i === len) {
|
|
2587
|
+
throw new Error("Fatal error");
|
|
2588
|
+
}
|
|
2589
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2590
|
+
return res;
|
|
2591
|
+
}
|
|
2592
|
+
get activeRouter() {
|
|
2593
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2594
|
+
throw new Error("No active router has been determined yet.");
|
|
2595
|
+
}
|
|
2596
|
+
return this.#routers[0];
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
|
|
2600
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
2601
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
2602
|
+
var Node2 = class _Node2 {
|
|
2603
|
+
#methods;
|
|
2604
|
+
#children;
|
|
2605
|
+
#patterns;
|
|
2606
|
+
#order = 0;
|
|
2607
|
+
#params = emptyParams;
|
|
2608
|
+
constructor(method, handler, children) {
|
|
2609
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
2610
|
+
this.#methods = [];
|
|
2611
|
+
if (method && handler) {
|
|
2612
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
2613
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
2614
|
+
this.#methods = [m];
|
|
2615
|
+
}
|
|
2616
|
+
this.#patterns = [];
|
|
2617
|
+
}
|
|
2618
|
+
insert(method, path4, handler) {
|
|
2619
|
+
this.#order = ++this.#order;
|
|
2620
|
+
let curNode = this;
|
|
2621
|
+
const parts = splitRoutingPath(path4);
|
|
2622
|
+
const possibleKeys = [];
|
|
2623
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
2624
|
+
const p = parts[i];
|
|
2625
|
+
const nextP = parts[i + 1];
|
|
2626
|
+
const pattern = getPattern(p, nextP);
|
|
2627
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
2628
|
+
if (key in curNode.#children) {
|
|
2629
|
+
curNode = curNode.#children[key];
|
|
2630
|
+
if (pattern) {
|
|
2631
|
+
possibleKeys.push(pattern[1]);
|
|
2632
|
+
}
|
|
2633
|
+
continue;
|
|
2634
|
+
}
|
|
2635
|
+
curNode.#children[key] = new _Node2();
|
|
2636
|
+
if (pattern) {
|
|
2637
|
+
curNode.#patterns.push(pattern);
|
|
2638
|
+
possibleKeys.push(pattern[1]);
|
|
2639
|
+
}
|
|
2640
|
+
curNode = curNode.#children[key];
|
|
2641
|
+
}
|
|
2642
|
+
curNode.#methods.push({
|
|
2643
|
+
[method]: {
|
|
2644
|
+
handler,
|
|
2645
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
2646
|
+
score: this.#order
|
|
2647
|
+
}
|
|
2648
|
+
});
|
|
2649
|
+
return curNode;
|
|
2650
|
+
}
|
|
2651
|
+
#getHandlerSets(node, method, nodeParams, params) {
|
|
2652
|
+
const handlerSets = [];
|
|
2653
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
2654
|
+
const m = node.#methods[i];
|
|
2655
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2656
|
+
const processedSet = {};
|
|
2657
|
+
if (handlerSet !== void 0) {
|
|
2658
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
2659
|
+
handlerSets.push(handlerSet);
|
|
2660
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
2661
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
2662
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2663
|
+
const processed = processedSet[handlerSet.score];
|
|
2664
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2665
|
+
processedSet[handlerSet.score] = true;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
return handlerSets;
|
|
2671
|
+
}
|
|
2672
|
+
search(method, path4) {
|
|
2673
|
+
const handlerSets = [];
|
|
2674
|
+
this.#params = emptyParams;
|
|
2675
|
+
const curNode = this;
|
|
2676
|
+
let curNodes = [curNode];
|
|
2677
|
+
const parts = splitPath(path4);
|
|
2678
|
+
const curNodesQueue = [];
|
|
2679
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
2680
|
+
const part = parts[i];
|
|
2681
|
+
const isLast = i === len - 1;
|
|
2682
|
+
const tempNodes = [];
|
|
2683
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
2684
|
+
const node = curNodes[j];
|
|
2685
|
+
const nextNode = node.#children[part];
|
|
2686
|
+
if (nextNode) {
|
|
2687
|
+
nextNode.#params = node.#params;
|
|
2688
|
+
if (isLast) {
|
|
2689
|
+
if (nextNode.#children["*"]) {
|
|
2690
|
+
handlerSets.push(
|
|
2691
|
+
...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
|
|
2692
|
+
);
|
|
2693
|
+
}
|
|
2694
|
+
handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
|
|
2695
|
+
} else {
|
|
2696
|
+
tempNodes.push(nextNode);
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
2700
|
+
const pattern = node.#patterns[k];
|
|
2701
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2702
|
+
if (pattern === "*") {
|
|
2703
|
+
const astNode = node.#children["*"];
|
|
2704
|
+
if (astNode) {
|
|
2705
|
+
handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
|
|
2706
|
+
astNode.#params = params;
|
|
2707
|
+
tempNodes.push(astNode);
|
|
2708
|
+
}
|
|
2709
|
+
continue;
|
|
2710
|
+
}
|
|
2711
|
+
const [key, name, matcher] = pattern;
|
|
2712
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
2713
|
+
continue;
|
|
2714
|
+
}
|
|
2715
|
+
const child = node.#children[key];
|
|
2716
|
+
const restPathString = parts.slice(i).join("/");
|
|
2717
|
+
if (matcher instanceof RegExp) {
|
|
2718
|
+
const m = matcher.exec(restPathString);
|
|
2719
|
+
if (m) {
|
|
2720
|
+
params[name] = m[0];
|
|
2721
|
+
handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
|
|
2722
|
+
if (Object.keys(child.#children).length) {
|
|
2723
|
+
child.#params = params;
|
|
2724
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2725
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2726
|
+
targetCurNodes.push(child);
|
|
2727
|
+
}
|
|
2728
|
+
continue;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
if (matcher === true || matcher.test(part)) {
|
|
2732
|
+
params[name] = part;
|
|
2733
|
+
if (isLast) {
|
|
2734
|
+
handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
|
|
2735
|
+
if (child.#children["*"]) {
|
|
2736
|
+
handlerSets.push(
|
|
2737
|
+
...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
|
|
2738
|
+
);
|
|
2739
|
+
}
|
|
2740
|
+
} else {
|
|
2741
|
+
child.#params = params;
|
|
2742
|
+
tempNodes.push(child);
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
|
|
2748
|
+
}
|
|
2749
|
+
if (handlerSets.length > 1) {
|
|
2750
|
+
handlerSets.sort((a, b) => {
|
|
2751
|
+
return a.score - b.score;
|
|
2752
|
+
});
|
|
2753
|
+
}
|
|
2754
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
|
|
2758
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2759
|
+
var TrieRouter = class {
|
|
2760
|
+
name = "TrieRouter";
|
|
2761
|
+
#node;
|
|
2762
|
+
constructor() {
|
|
2763
|
+
this.#node = new Node2();
|
|
2764
|
+
}
|
|
2765
|
+
add(method, path4, handler) {
|
|
2766
|
+
const results = checkOptionalParameter(path4);
|
|
2767
|
+
if (results) {
|
|
2768
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
2769
|
+
this.#node.insert(method, results[i], handler);
|
|
2770
|
+
}
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
this.#node.insert(method, path4, handler);
|
|
2774
|
+
}
|
|
2775
|
+
match(method, path4) {
|
|
2776
|
+
return this.#node.search(method, path4);
|
|
2777
|
+
}
|
|
2778
|
+
};
|
|
2779
|
+
|
|
2780
|
+
// node_modules/hono/dist/hono.js
|
|
2781
|
+
var Hono2 = class extends Hono {
|
|
2782
|
+
/**
|
|
2783
|
+
* Creates an instance of the Hono class.
|
|
2784
|
+
*
|
|
2785
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2786
|
+
*/
|
|
2787
|
+
constructor(options = {}) {
|
|
2788
|
+
super(options);
|
|
2789
|
+
this.router = options.router ?? new SmartRouter({
|
|
2790
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2791
|
+
});
|
|
2792
|
+
}
|
|
2793
|
+
};
|
|
2794
|
+
|
|
2795
|
+
// node_modules/hono/dist/middleware/cors/index.js
|
|
2796
|
+
var cors = (options) => {
|
|
2797
|
+
const defaults = {
|
|
2798
|
+
origin: "*",
|
|
2799
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
2800
|
+
allowHeaders: [],
|
|
2801
|
+
exposeHeaders: []
|
|
2802
|
+
};
|
|
2803
|
+
const opts = {
|
|
2804
|
+
...defaults,
|
|
2805
|
+
...options
|
|
2806
|
+
};
|
|
2807
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
2808
|
+
if (typeof optsOrigin === "string") {
|
|
2809
|
+
if (optsOrigin === "*") {
|
|
2810
|
+
return () => optsOrigin;
|
|
2811
|
+
} else {
|
|
2812
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
2813
|
+
}
|
|
2814
|
+
} else if (typeof optsOrigin === "function") {
|
|
2815
|
+
return optsOrigin;
|
|
2816
|
+
} else {
|
|
2817
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
2818
|
+
}
|
|
2819
|
+
})(opts.origin);
|
|
2820
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
2821
|
+
if (typeof optsAllowMethods === "function") {
|
|
2822
|
+
return optsAllowMethods;
|
|
2823
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
2824
|
+
return () => optsAllowMethods;
|
|
2825
|
+
} else {
|
|
2826
|
+
return () => [];
|
|
2827
|
+
}
|
|
2828
|
+
})(opts.allowMethods);
|
|
2829
|
+
return async function cors2(c, next) {
|
|
2830
|
+
function set(key, value) {
|
|
2831
|
+
c.res.headers.set(key, value);
|
|
2832
|
+
}
|
|
2833
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
2834
|
+
if (allowOrigin) {
|
|
2835
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
2836
|
+
}
|
|
2837
|
+
if (opts.credentials) {
|
|
2838
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
2839
|
+
}
|
|
2840
|
+
if (opts.exposeHeaders?.length) {
|
|
2841
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
2842
|
+
}
|
|
2843
|
+
if (c.req.method === "OPTIONS") {
|
|
2844
|
+
if (opts.origin !== "*") {
|
|
2845
|
+
set("Vary", "Origin");
|
|
2846
|
+
}
|
|
2847
|
+
if (opts.maxAge != null) {
|
|
2848
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
2849
|
+
}
|
|
2850
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
2851
|
+
if (allowMethods.length) {
|
|
2852
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
2853
|
+
}
|
|
2854
|
+
let headers = opts.allowHeaders;
|
|
2855
|
+
if (!headers?.length) {
|
|
2856
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
2857
|
+
if (requestHeaders) {
|
|
2858
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
if (headers?.length) {
|
|
2862
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
2863
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
2864
|
+
}
|
|
2865
|
+
c.res.headers.delete("Content-Length");
|
|
2866
|
+
c.res.headers.delete("Content-Type");
|
|
2867
|
+
return new Response(null, {
|
|
2868
|
+
headers: c.res.headers,
|
|
2869
|
+
status: 204,
|
|
2870
|
+
statusText: "No Content"
|
|
2871
|
+
});
|
|
2872
|
+
}
|
|
2873
|
+
await next();
|
|
2874
|
+
if (opts.origin !== "*") {
|
|
2875
|
+
c.header("Vary", "Origin", { append: true });
|
|
2876
|
+
}
|
|
2877
|
+
};
|
|
2878
|
+
};
|
|
2879
|
+
|
|
2880
|
+
// lib/db.ts
|
|
2881
|
+
import { execSync } from "node:child_process";
|
|
2882
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync } from "node:fs";
|
|
2883
|
+
import { dirname, join as join2 } from "node:path";
|
|
2884
|
+
import { fileURLToPath } from "node:url";
|
|
2885
|
+
var originalEmit = process.emit;
|
|
2886
|
+
process.emit = (event, ...args) => {
|
|
2887
|
+
if (event === "warning" && typeof args[0] === "object" && args[0] !== null && "name" in args[0] && args[0].name === "ExperimentalWarning" && "message" in args[0] && typeof args[0].message === "string" && args[0].message.includes("SQLite")) {
|
|
2888
|
+
return false;
|
|
2889
|
+
}
|
|
2890
|
+
return originalEmit.apply(process, [event, ...args]);
|
|
2891
|
+
};
|
|
2892
|
+
var { DatabaseSync } = await import("node:sqlite");
|
|
2893
|
+
var __filename = fileURLToPath(import.meta.url);
|
|
2894
|
+
var __dirname = dirname(__filename);
|
|
2895
|
+
function getCurrentUser() {
|
|
2896
|
+
try {
|
|
2897
|
+
return execSync("git config user.name", { encoding: "utf-8" }).trim();
|
|
2898
|
+
} catch {
|
|
2899
|
+
try {
|
|
2900
|
+
return execSync("whoami", { encoding: "utf-8" }).trim();
|
|
2901
|
+
} catch {
|
|
2902
|
+
return "unknown";
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
function getLocalDbPath(projectPath) {
|
|
2907
|
+
return join2(projectPath, ".mneme", "local.db");
|
|
2908
|
+
}
|
|
2909
|
+
function configurePragmas(db) {
|
|
2910
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
2911
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
2912
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
2913
|
+
}
|
|
2914
|
+
function openLocalDatabase(projectPath) {
|
|
2915
|
+
const dbPath = getLocalDbPath(projectPath);
|
|
2916
|
+
if (!existsSync2(dbPath)) {
|
|
2917
|
+
return null;
|
|
2918
|
+
}
|
|
2919
|
+
const db = new DatabaseSync(dbPath);
|
|
2920
|
+
configurePragmas(db);
|
|
2921
|
+
return db;
|
|
2922
|
+
}
|
|
2923
|
+
function getInteractionsBySessionIds(db, sessionIds) {
|
|
2924
|
+
if (sessionIds.length === 0) {
|
|
2925
|
+
return [];
|
|
2926
|
+
}
|
|
2927
|
+
const placeholders = sessionIds.map(() => "?").join(", ");
|
|
2928
|
+
const stmt = db.prepare(`
|
|
2929
|
+
SELECT * FROM interactions
|
|
2930
|
+
WHERE session_id IN (${placeholders})
|
|
2931
|
+
ORDER BY timestamp ASC, id ASC
|
|
2932
|
+
`);
|
|
2933
|
+
return stmt.all(...sessionIds);
|
|
2934
|
+
}
|
|
2935
|
+
function deleteInteractions(db, sessionId) {
|
|
2936
|
+
const stmt = db.prepare("DELETE FROM interactions WHERE session_id = ?");
|
|
2937
|
+
stmt.run(sessionId);
|
|
2938
|
+
}
|
|
2939
|
+
function deleteBackups(db, sessionId) {
|
|
2940
|
+
const stmt = db.prepare(
|
|
2941
|
+
"DELETE FROM pre_compact_backups WHERE session_id = ?"
|
|
2942
|
+
);
|
|
2943
|
+
stmt.run(sessionId);
|
|
2944
|
+
}
|
|
2945
|
+
function countInteractions(db, filter) {
|
|
2946
|
+
const conditions = [];
|
|
2947
|
+
const params = [];
|
|
2948
|
+
if (filter.sessionId) {
|
|
2949
|
+
conditions.push("session_id = ?");
|
|
2950
|
+
params.push(filter.sessionId);
|
|
2951
|
+
}
|
|
2952
|
+
if (filter.projectPath) {
|
|
2953
|
+
conditions.push("project_path = ?");
|
|
2954
|
+
params.push(filter.projectPath);
|
|
2955
|
+
}
|
|
2956
|
+
if (filter.repository) {
|
|
2957
|
+
conditions.push("repository = ?");
|
|
2958
|
+
params.push(filter.repository);
|
|
2959
|
+
}
|
|
2960
|
+
if (filter.before) {
|
|
2961
|
+
conditions.push("timestamp < ?");
|
|
2962
|
+
params.push(filter.before);
|
|
2963
|
+
}
|
|
2964
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
2965
|
+
const stmt = db.prepare(
|
|
2966
|
+
`SELECT COUNT(*) as count FROM interactions ${whereClause}`
|
|
2967
|
+
);
|
|
2968
|
+
const result = stmt.get(...params);
|
|
2969
|
+
return result.count;
|
|
2970
|
+
}
|
|
2971
|
+
|
|
2972
|
+
// lib/index/manager.ts
|
|
2973
|
+
import * as fs3 from "node:fs";
|
|
2974
|
+
import * as path2 from "node:path";
|
|
2975
|
+
|
|
2976
|
+
// lib/utils.ts
|
|
2977
|
+
import * as fs from "node:fs";
|
|
2978
|
+
function safeReadJson(filePath, fallback) {
|
|
2979
|
+
try {
|
|
2980
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
2981
|
+
return JSON.parse(content);
|
|
2982
|
+
} catch {
|
|
2983
|
+
return fallback;
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
function ensureDir(dirPath) {
|
|
2987
|
+
if (!fs.existsSync(dirPath)) {
|
|
2988
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
|
|
2992
|
+
// lib/index/builder.ts
|
|
2993
|
+
import * as fs2 from "node:fs";
|
|
2994
|
+
import * as path from "node:path";
|
|
2995
|
+
function listMonthJsonFiles(monthDir) {
|
|
2996
|
+
if (!fs2.existsSync(monthDir)) {
|
|
2997
|
+
return [];
|
|
2998
|
+
}
|
|
2999
|
+
const files = [];
|
|
3000
|
+
const entries = fs2.readdirSync(monthDir, { withFileTypes: true });
|
|
3001
|
+
for (const entry of entries) {
|
|
3002
|
+
if (entry.isFile() && entry.name.endsWith(".json")) {
|
|
3003
|
+
files.push(path.join(monthDir, entry.name));
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
return files;
|
|
3007
|
+
}
|
|
3008
|
+
function listYearMonths(dir) {
|
|
3009
|
+
if (!fs2.existsSync(dir)) {
|
|
3010
|
+
return [];
|
|
3011
|
+
}
|
|
3012
|
+
const results = [];
|
|
3013
|
+
const years = fs2.readdirSync(dir, { withFileTypes: true });
|
|
3014
|
+
for (const year of years) {
|
|
3015
|
+
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
3016
|
+
const yearPath = path.join(dir, year.name);
|
|
3017
|
+
const months = fs2.readdirSync(yearPath, { withFileTypes: true });
|
|
3018
|
+
for (const month of months) {
|
|
3019
|
+
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
3020
|
+
results.push({ year: year.name, month: month.name });
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
results.sort((a, b) => {
|
|
3024
|
+
const aKey = `${a.year}${a.month}`;
|
|
3025
|
+
const bKey = `${b.year}${b.month}`;
|
|
3026
|
+
return bKey.localeCompare(aKey);
|
|
3027
|
+
});
|
|
3028
|
+
return results;
|
|
3029
|
+
}
|
|
3030
|
+
function buildSessionIndexForMonth(mnemeDir2, year, month) {
|
|
3031
|
+
const sessionsDir = path.join(mnemeDir2, "sessions");
|
|
3032
|
+
const monthDir = path.join(sessionsDir, year, month);
|
|
3033
|
+
const files = listMonthJsonFiles(monthDir);
|
|
3034
|
+
const items = [];
|
|
3035
|
+
for (const filePath of files) {
|
|
3036
|
+
try {
|
|
3037
|
+
const session = safeReadJson(filePath, {});
|
|
3038
|
+
if (!session.id || !session.createdAt) continue;
|
|
3039
|
+
const relativePath = path.relative(sessionsDir, filePath);
|
|
3040
|
+
const interactions = session.interactions || [];
|
|
3041
|
+
const context = session.context || {};
|
|
3042
|
+
const user = context.user;
|
|
3043
|
+
const summary = session.summary || {};
|
|
3044
|
+
const title = summary.title || session.title || "";
|
|
3045
|
+
const sessionType = session.sessionType || summary.sessionType || null;
|
|
3046
|
+
items.push({
|
|
3047
|
+
id: session.id,
|
|
3048
|
+
title: title || "Untitled",
|
|
3049
|
+
goal: summary.goal || session.goal || void 0,
|
|
3050
|
+
createdAt: session.createdAt,
|
|
3051
|
+
tags: session.tags || [],
|
|
3052
|
+
sessionType,
|
|
3053
|
+
branch: context.branch || null,
|
|
3054
|
+
user: user?.name,
|
|
3055
|
+
interactionCount: interactions.length,
|
|
3056
|
+
filePath: relativePath,
|
|
3057
|
+
hasSummary: !!title && title !== "Untitled"
|
|
3058
|
+
});
|
|
3059
|
+
} catch {
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
items.sort(
|
|
3063
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3064
|
+
);
|
|
3065
|
+
return {
|
|
3066
|
+
version: 1,
|
|
3067
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3068
|
+
items
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
function buildAllSessionIndexes(mnemeDir2) {
|
|
3072
|
+
const sessionsDir = path.join(mnemeDir2, "sessions");
|
|
3073
|
+
const yearMonths = listYearMonths(sessionsDir);
|
|
3074
|
+
const indexes = /* @__PURE__ */ new Map();
|
|
3075
|
+
for (const { year, month } of yearMonths) {
|
|
3076
|
+
const key = `${year}/${month}`;
|
|
3077
|
+
const index = buildSessionIndexForMonth(mnemeDir2, year, month);
|
|
3078
|
+
if (index.items.length > 0) {
|
|
3079
|
+
indexes.set(key, index);
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
return indexes;
|
|
3083
|
+
}
|
|
3084
|
+
function buildDecisionIndexForMonth(mnemeDir2, year, month) {
|
|
3085
|
+
const decisionsDir = path.join(mnemeDir2, "decisions");
|
|
3086
|
+
const monthDir = path.join(decisionsDir, year, month);
|
|
3087
|
+
const files = listMonthJsonFiles(monthDir);
|
|
3088
|
+
const items = [];
|
|
3089
|
+
for (const filePath of files) {
|
|
3090
|
+
try {
|
|
3091
|
+
const decision = safeReadJson(filePath, {});
|
|
3092
|
+
if (!decision.id || !decision.createdAt) continue;
|
|
3093
|
+
const relativePath = path.relative(decisionsDir, filePath);
|
|
3094
|
+
const user = decision.user;
|
|
3095
|
+
items.push({
|
|
3096
|
+
id: decision.id,
|
|
3097
|
+
title: decision.title || "Untitled",
|
|
3098
|
+
createdAt: decision.createdAt,
|
|
3099
|
+
updatedAt: decision.updatedAt,
|
|
3100
|
+
tags: decision.tags || [],
|
|
3101
|
+
status: decision.status || "active",
|
|
3102
|
+
user: user?.name,
|
|
3103
|
+
filePath: relativePath
|
|
3104
|
+
});
|
|
3105
|
+
} catch {
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
items.sort(
|
|
3109
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3110
|
+
);
|
|
3111
|
+
return {
|
|
3112
|
+
version: 1,
|
|
3113
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3114
|
+
items
|
|
3115
|
+
};
|
|
3116
|
+
}
|
|
3117
|
+
function buildAllDecisionIndexes(mnemeDir2) {
|
|
3118
|
+
const decisionsDir = path.join(mnemeDir2, "decisions");
|
|
3119
|
+
const yearMonths = listYearMonths(decisionsDir);
|
|
3120
|
+
const indexes = /* @__PURE__ */ new Map();
|
|
3121
|
+
for (const { year, month } of yearMonths) {
|
|
3122
|
+
const key = `${year}/${month}`;
|
|
3123
|
+
const index = buildDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3124
|
+
if (index.items.length > 0) {
|
|
3125
|
+
indexes.set(key, index);
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
return indexes;
|
|
3129
|
+
}
|
|
3130
|
+
function getSessionYearMonths(mnemeDir2) {
|
|
3131
|
+
const sessionsDir = path.join(mnemeDir2, "sessions");
|
|
3132
|
+
return listYearMonths(sessionsDir);
|
|
3133
|
+
}
|
|
3134
|
+
function getDecisionYearMonths(mnemeDir2) {
|
|
3135
|
+
const decisionsDir = path.join(mnemeDir2, "decisions");
|
|
3136
|
+
return listYearMonths(decisionsDir);
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
// lib/index/manager.ts
|
|
3140
|
+
var INDEXES_DIR = ".indexes";
|
|
3141
|
+
function getIndexDir(mnemeDir2) {
|
|
3142
|
+
return path2.join(mnemeDir2, INDEXES_DIR);
|
|
3143
|
+
}
|
|
3144
|
+
function getSessionIndexPath(mnemeDir2, year, month) {
|
|
3145
|
+
return path2.join(getIndexDir(mnemeDir2), "sessions", year, `${month}.json`);
|
|
3146
|
+
}
|
|
3147
|
+
function getDecisionIndexPath(mnemeDir2, year, month) {
|
|
3148
|
+
return path2.join(getIndexDir(mnemeDir2), "decisions", year, `${month}.json`);
|
|
3149
|
+
}
|
|
3150
|
+
function readSessionIndexForMonth(mnemeDir2, year, month) {
|
|
3151
|
+
const indexPath = getSessionIndexPath(mnemeDir2, year, month);
|
|
3152
|
+
if (!fs3.existsSync(indexPath)) {
|
|
3153
|
+
return null;
|
|
3154
|
+
}
|
|
3155
|
+
return safeReadJson(indexPath, {
|
|
3156
|
+
version: 1,
|
|
3157
|
+
updatedAt: "",
|
|
3158
|
+
items: []
|
|
3159
|
+
});
|
|
3160
|
+
}
|
|
3161
|
+
function readDecisionIndexForMonth(mnemeDir2, year, month) {
|
|
3162
|
+
const indexPath = getDecisionIndexPath(mnemeDir2, year, month);
|
|
3163
|
+
if (!fs3.existsSync(indexPath)) {
|
|
3164
|
+
return null;
|
|
3165
|
+
}
|
|
3166
|
+
return safeReadJson(indexPath, {
|
|
3167
|
+
version: 1,
|
|
3168
|
+
updatedAt: "",
|
|
3169
|
+
items: []
|
|
3170
|
+
});
|
|
3171
|
+
}
|
|
3172
|
+
function writeSessionIndexForMonth(mnemeDir2, year, month, index) {
|
|
3173
|
+
const indexPath = getSessionIndexPath(mnemeDir2, year, month);
|
|
3174
|
+
ensureDir(path2.dirname(indexPath));
|
|
3175
|
+
fs3.writeFileSync(indexPath, JSON.stringify(index, null, 2));
|
|
3176
|
+
}
|
|
3177
|
+
function writeDecisionIndexForMonth(mnemeDir2, year, month, index) {
|
|
3178
|
+
const indexPath = getDecisionIndexPath(mnemeDir2, year, month);
|
|
3179
|
+
ensureDir(path2.dirname(indexPath));
|
|
3180
|
+
fs3.writeFileSync(indexPath, JSON.stringify(index, null, 2));
|
|
3181
|
+
}
|
|
3182
|
+
function rebuildSessionIndexForMonth(mnemeDir2, year, month) {
|
|
3183
|
+
const index = buildSessionIndexForMonth(mnemeDir2, year, month);
|
|
3184
|
+
if (index.items.length > 0) {
|
|
3185
|
+
writeSessionIndexForMonth(mnemeDir2, year, month, index);
|
|
3186
|
+
}
|
|
3187
|
+
return index;
|
|
3188
|
+
}
|
|
3189
|
+
function rebuildDecisionIndexForMonth(mnemeDir2, year, month) {
|
|
3190
|
+
const index = buildDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3191
|
+
if (index.items.length > 0) {
|
|
3192
|
+
writeDecisionIndexForMonth(mnemeDir2, year, month, index);
|
|
3193
|
+
}
|
|
3194
|
+
return index;
|
|
3195
|
+
}
|
|
3196
|
+
function rebuildAllSessionIndexes(mnemeDir2) {
|
|
3197
|
+
const allIndexes = buildAllSessionIndexes(mnemeDir2);
|
|
3198
|
+
for (const [key, index] of allIndexes) {
|
|
3199
|
+
const [year, month] = key.split("/");
|
|
3200
|
+
writeSessionIndexForMonth(mnemeDir2, year, month, index);
|
|
3201
|
+
}
|
|
3202
|
+
return allIndexes;
|
|
3203
|
+
}
|
|
3204
|
+
function rebuildAllDecisionIndexes(mnemeDir2) {
|
|
3205
|
+
const allIndexes = buildAllDecisionIndexes(mnemeDir2);
|
|
3206
|
+
for (const [key, index] of allIndexes) {
|
|
3207
|
+
const [year, month] = key.split("/");
|
|
3208
|
+
writeDecisionIndexForMonth(mnemeDir2, year, month, index);
|
|
3209
|
+
}
|
|
3210
|
+
return allIndexes;
|
|
3211
|
+
}
|
|
3212
|
+
function readRecentSessionIndexes(mnemeDir2, monthCount = 6) {
|
|
3213
|
+
const yearMonths = getSessionYearMonths(mnemeDir2);
|
|
3214
|
+
const recentMonths = yearMonths.slice(0, monthCount);
|
|
3215
|
+
const allItems = [];
|
|
3216
|
+
let latestUpdate = "";
|
|
3217
|
+
for (const { year, month } of recentMonths) {
|
|
3218
|
+
let index = readSessionIndexForMonth(mnemeDir2, year, month);
|
|
3219
|
+
if (!index || isIndexStale(index)) {
|
|
3220
|
+
index = rebuildSessionIndexForMonth(mnemeDir2, year, month);
|
|
3221
|
+
}
|
|
3222
|
+
if (index.items.length > 0) {
|
|
3223
|
+
allItems.push(...index.items);
|
|
3224
|
+
if (index.updatedAt > latestUpdate) {
|
|
3225
|
+
latestUpdate = index.updatedAt;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
allItems.sort(
|
|
3230
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3231
|
+
);
|
|
3232
|
+
return {
|
|
3233
|
+
version: 1,
|
|
3234
|
+
updatedAt: latestUpdate || (/* @__PURE__ */ new Date()).toISOString(),
|
|
3235
|
+
items: allItems
|
|
3236
|
+
};
|
|
3237
|
+
}
|
|
3238
|
+
function readRecentDecisionIndexes(mnemeDir2, monthCount = 6) {
|
|
3239
|
+
const yearMonths = getDecisionYearMonths(mnemeDir2);
|
|
3240
|
+
const recentMonths = yearMonths.slice(0, monthCount);
|
|
3241
|
+
const allItems = [];
|
|
3242
|
+
let latestUpdate = "";
|
|
3243
|
+
for (const { year, month } of recentMonths) {
|
|
3244
|
+
let index = readDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3245
|
+
if (!index || isIndexStale(index)) {
|
|
3246
|
+
index = rebuildDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3247
|
+
}
|
|
3248
|
+
if (index.items.length > 0) {
|
|
3249
|
+
allItems.push(...index.items);
|
|
3250
|
+
if (index.updatedAt > latestUpdate) {
|
|
3251
|
+
latestUpdate = index.updatedAt;
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
allItems.sort(
|
|
3256
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3257
|
+
);
|
|
3258
|
+
return {
|
|
3259
|
+
version: 1,
|
|
3260
|
+
updatedAt: latestUpdate || (/* @__PURE__ */ new Date()).toISOString(),
|
|
3261
|
+
items: allItems
|
|
3262
|
+
};
|
|
3263
|
+
}
|
|
3264
|
+
function readAllSessionIndexes(mnemeDir2) {
|
|
3265
|
+
const yearMonths = getSessionYearMonths(mnemeDir2);
|
|
3266
|
+
const allItems = [];
|
|
3267
|
+
let latestUpdate = "";
|
|
3268
|
+
for (const { year, month } of yearMonths) {
|
|
3269
|
+
let index = readSessionIndexForMonth(mnemeDir2, year, month);
|
|
3270
|
+
if (!index || isIndexStale(index)) {
|
|
3271
|
+
index = rebuildSessionIndexForMonth(mnemeDir2, year, month);
|
|
3272
|
+
}
|
|
3273
|
+
if (index.items.length > 0) {
|
|
3274
|
+
allItems.push(...index.items);
|
|
3275
|
+
if (index.updatedAt > latestUpdate) {
|
|
3276
|
+
latestUpdate = index.updatedAt;
|
|
3277
|
+
}
|
|
3278
|
+
}
|
|
3279
|
+
}
|
|
3280
|
+
allItems.sort(
|
|
3281
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3282
|
+
);
|
|
3283
|
+
return {
|
|
3284
|
+
version: 1,
|
|
3285
|
+
updatedAt: latestUpdate || (/* @__PURE__ */ new Date()).toISOString(),
|
|
3286
|
+
items: allItems
|
|
3287
|
+
};
|
|
3288
|
+
}
|
|
3289
|
+
function readAllDecisionIndexes(mnemeDir2) {
|
|
3290
|
+
const yearMonths = getDecisionYearMonths(mnemeDir2);
|
|
3291
|
+
const allItems = [];
|
|
3292
|
+
let latestUpdate = "";
|
|
3293
|
+
for (const { year, month } of yearMonths) {
|
|
3294
|
+
let index = readDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3295
|
+
if (!index || isIndexStale(index)) {
|
|
3296
|
+
index = rebuildDecisionIndexForMonth(mnemeDir2, year, month);
|
|
3297
|
+
}
|
|
3298
|
+
if (index.items.length > 0) {
|
|
3299
|
+
allItems.push(...index.items);
|
|
3300
|
+
if (index.updatedAt > latestUpdate) {
|
|
3301
|
+
latestUpdate = index.updatedAt;
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
allItems.sort(
|
|
3306
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3307
|
+
);
|
|
3308
|
+
return {
|
|
3309
|
+
version: 1,
|
|
3310
|
+
updatedAt: latestUpdate || (/* @__PURE__ */ new Date()).toISOString(),
|
|
3311
|
+
items: allItems
|
|
3312
|
+
};
|
|
3313
|
+
}
|
|
3314
|
+
function isIndexStale(index, maxAgeMs = 5 * 60 * 1e3) {
|
|
3315
|
+
if (!index || !index.updatedAt) {
|
|
3316
|
+
return true;
|
|
3317
|
+
}
|
|
3318
|
+
const updatedAt = new Date(index.updatedAt).getTime();
|
|
3319
|
+
const now = Date.now();
|
|
3320
|
+
return now - updatedAt > maxAgeMs;
|
|
3321
|
+
}
|
|
3322
|
+
|
|
3323
|
+
// dashboard/server/index.ts
|
|
3324
|
+
function sanitizeId(id) {
|
|
3325
|
+
return id.replace(/[^a-zA-Z0-9_-]/g, "");
|
|
3326
|
+
}
|
|
3327
|
+
function safeParseJsonFile(filePath) {
|
|
3328
|
+
try {
|
|
3329
|
+
return JSON.parse(fs4.readFileSync(filePath, "utf-8"));
|
|
3330
|
+
} catch (error) {
|
|
3331
|
+
console.error(`Failed to parse JSON: ${filePath}`, error);
|
|
3332
|
+
return null;
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
var app = new Hono2();
|
|
3336
|
+
var getProjectRoot = () => {
|
|
3337
|
+
return process.env.MNEME_PROJECT_ROOT || process.cwd();
|
|
3338
|
+
};
|
|
3339
|
+
var getMnemeDir = () => {
|
|
3340
|
+
return path3.join(getProjectRoot(), ".mneme");
|
|
3341
|
+
};
|
|
3342
|
+
var listJsonFiles = (dir) => {
|
|
3343
|
+
if (!fs4.existsSync(dir)) {
|
|
3344
|
+
return [];
|
|
3345
|
+
}
|
|
3346
|
+
const entries = fs4.readdirSync(dir, { withFileTypes: true });
|
|
3347
|
+
return entries.flatMap((entry) => {
|
|
3348
|
+
const fullPath = path3.join(dir, entry.name);
|
|
3349
|
+
if (entry.isDirectory()) {
|
|
3350
|
+
return listJsonFiles(fullPath);
|
|
3351
|
+
}
|
|
3352
|
+
if (entry.isFile() && entry.name.endsWith(".json")) {
|
|
3353
|
+
return [fullPath];
|
|
3354
|
+
}
|
|
3355
|
+
return [];
|
|
3356
|
+
});
|
|
3357
|
+
};
|
|
3358
|
+
var listDatedJsonFiles = (dir) => {
|
|
3359
|
+
const files = listJsonFiles(dir);
|
|
3360
|
+
return files.filter((filePath) => {
|
|
3361
|
+
const rel = path3.relative(dir, filePath);
|
|
3362
|
+
const parts = rel.split(path3.sep);
|
|
3363
|
+
if (parts.length < 3) {
|
|
3364
|
+
return false;
|
|
3365
|
+
}
|
|
3366
|
+
return /^\d{4}$/.test(parts[0]) && /^\d{2}$/.test(parts[1]);
|
|
3367
|
+
});
|
|
3368
|
+
};
|
|
3369
|
+
var findJsonFileById = (dir, id) => {
|
|
3370
|
+
const target = `${id}.json`;
|
|
3371
|
+
const queue = [dir];
|
|
3372
|
+
while (queue.length > 0) {
|
|
3373
|
+
const current = queue.shift();
|
|
3374
|
+
if (!current || !fs4.existsSync(current)) {
|
|
3375
|
+
continue;
|
|
3376
|
+
}
|
|
3377
|
+
const entries = fs4.readdirSync(current, { withFileTypes: true });
|
|
3378
|
+
for (const entry of entries) {
|
|
3379
|
+
const fullPath = path3.join(current, entry.name);
|
|
3380
|
+
if (entry.isDirectory()) {
|
|
3381
|
+
queue.push(fullPath);
|
|
3382
|
+
} else if (entry.isFile() && entry.name === target) {
|
|
3383
|
+
const rel = path3.relative(dir, fullPath);
|
|
3384
|
+
const parts = rel.split(path3.sep);
|
|
3385
|
+
if (parts.length >= 3 && /^\d{4}$/.test(parts[0]) && /^\d{2}$/.test(parts[1])) {
|
|
3386
|
+
return fullPath;
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
return null;
|
|
3392
|
+
};
|
|
3393
|
+
var rulesDir = () => path3.join(getMnemeDir(), "rules");
|
|
3394
|
+
app.use(
|
|
3395
|
+
"/api/*",
|
|
3396
|
+
cors({
|
|
3397
|
+
origin: (origin) => {
|
|
3398
|
+
if (!origin) return void 0;
|
|
3399
|
+
if (origin.startsWith("http://localhost:")) return origin;
|
|
3400
|
+
return null;
|
|
3401
|
+
}
|
|
3402
|
+
})
|
|
3403
|
+
);
|
|
3404
|
+
function parsePaginationParams(c) {
|
|
3405
|
+
return {
|
|
3406
|
+
page: Math.max(1, Number.parseInt(c.req.query("page") || "1", 10)),
|
|
3407
|
+
limit: Math.min(
|
|
3408
|
+
100,
|
|
3409
|
+
Math.max(1, Number.parseInt(c.req.query("limit") || "20", 10))
|
|
3410
|
+
),
|
|
3411
|
+
tag: c.req.query("tag"),
|
|
3412
|
+
type: c.req.query("type"),
|
|
3413
|
+
project: c.req.query("project"),
|
|
3414
|
+
search: c.req.query("search"),
|
|
3415
|
+
showUntitled: c.req.query("showUntitled") === "true",
|
|
3416
|
+
allMonths: c.req.query("allMonths") === "true"
|
|
3417
|
+
};
|
|
3418
|
+
}
|
|
3419
|
+
function paginateArray(items, page, limit) {
|
|
3420
|
+
const total = items.length;
|
|
3421
|
+
const totalPages = Math.ceil(total / limit);
|
|
3422
|
+
const start = (page - 1) * limit;
|
|
3423
|
+
const data = items.slice(start, start + limit);
|
|
3424
|
+
return {
|
|
3425
|
+
data,
|
|
3426
|
+
pagination: {
|
|
3427
|
+
page,
|
|
3428
|
+
limit,
|
|
3429
|
+
total,
|
|
3430
|
+
totalPages,
|
|
3431
|
+
hasNext: page < totalPages,
|
|
3432
|
+
hasPrev: page > 1
|
|
3433
|
+
}
|
|
3434
|
+
};
|
|
3435
|
+
}
|
|
3436
|
+
app.get("/api/project", (c) => {
|
|
3437
|
+
const projectRoot = getProjectRoot();
|
|
3438
|
+
const projectName = path3.basename(projectRoot);
|
|
3439
|
+
let repository = null;
|
|
3440
|
+
try {
|
|
3441
|
+
const gitConfigPath = path3.join(projectRoot, ".git", "config");
|
|
3442
|
+
if (fs4.existsSync(gitConfigPath)) {
|
|
3443
|
+
const gitConfig = fs4.readFileSync(gitConfigPath, "utf-8");
|
|
3444
|
+
const match2 = gitConfig.match(
|
|
3445
|
+
/url\s*=\s*.*[:/]([^/]+\/[^/]+?)(?:\.git)?$/m
|
|
3446
|
+
);
|
|
3447
|
+
if (match2) {
|
|
3448
|
+
repository = match2[1];
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
} catch {
|
|
3452
|
+
}
|
|
3453
|
+
return c.json({
|
|
3454
|
+
name: projectName,
|
|
3455
|
+
path: projectRoot,
|
|
3456
|
+
repository
|
|
3457
|
+
});
|
|
3458
|
+
});
|
|
3459
|
+
app.get("/api/sessions", async (c) => {
|
|
3460
|
+
const useIndex = c.req.query("useIndex") !== "false";
|
|
3461
|
+
const usePagination = c.req.query("paginate") !== "false";
|
|
3462
|
+
const mnemeDir2 = getMnemeDir();
|
|
3463
|
+
const params = parsePaginationParams(c);
|
|
3464
|
+
try {
|
|
3465
|
+
let items;
|
|
3466
|
+
if (useIndex) {
|
|
3467
|
+
const index = params.allMonths ? readAllSessionIndexes(mnemeDir2) : readRecentSessionIndexes(mnemeDir2);
|
|
3468
|
+
items = index.items;
|
|
3469
|
+
} else {
|
|
3470
|
+
const sessionsDir = path3.join(mnemeDir2, "sessions");
|
|
3471
|
+
const files = listDatedJsonFiles(sessionsDir);
|
|
3472
|
+
if (files.length === 0) {
|
|
3473
|
+
return usePagination ? c.json({
|
|
3474
|
+
data: [],
|
|
3475
|
+
pagination: {
|
|
3476
|
+
page: 1,
|
|
3477
|
+
limit: params.limit,
|
|
3478
|
+
total: 0,
|
|
3479
|
+
totalPages: 0,
|
|
3480
|
+
hasNext: false,
|
|
3481
|
+
hasPrev: false
|
|
3482
|
+
}
|
|
3483
|
+
}) : c.json([]);
|
|
3484
|
+
}
|
|
3485
|
+
items = files.map((filePath) => {
|
|
3486
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
3487
|
+
return JSON.parse(content);
|
|
3488
|
+
});
|
|
3489
|
+
items.sort(
|
|
3490
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3491
|
+
);
|
|
3492
|
+
}
|
|
3493
|
+
let filtered = items;
|
|
3494
|
+
if (!params.showUntitled) {
|
|
3495
|
+
filtered = filtered.filter((s) => s.hasSummary === true);
|
|
3496
|
+
}
|
|
3497
|
+
if (params.tag) {
|
|
3498
|
+
filtered = filtered.filter(
|
|
3499
|
+
(s) => s.tags?.includes(params.tag)
|
|
3500
|
+
);
|
|
3501
|
+
}
|
|
3502
|
+
if (params.type) {
|
|
3503
|
+
filtered = filtered.filter((s) => s.sessionType === params.type);
|
|
3504
|
+
}
|
|
3505
|
+
if (params.project) {
|
|
3506
|
+
const projectQuery = params.project;
|
|
3507
|
+
filtered = filtered.filter((s) => {
|
|
3508
|
+
const ctx = s.context;
|
|
3509
|
+
const projectName = ctx?.projectName;
|
|
3510
|
+
const repository = ctx?.repository;
|
|
3511
|
+
return projectName === projectQuery || repository === projectQuery || repository?.endsWith(`/${projectQuery}`);
|
|
3512
|
+
});
|
|
3513
|
+
}
|
|
3514
|
+
if (params.search) {
|
|
3515
|
+
const query = params.search.toLowerCase();
|
|
3516
|
+
filtered = filtered.filter((s) => {
|
|
3517
|
+
const title = (s.title || "").toLowerCase();
|
|
3518
|
+
const goal = (s.goal || "").toLowerCase();
|
|
3519
|
+
return title.includes(query) || goal.includes(query);
|
|
3520
|
+
});
|
|
3521
|
+
}
|
|
3522
|
+
if (!usePagination) {
|
|
3523
|
+
return c.json(filtered);
|
|
3524
|
+
}
|
|
3525
|
+
return c.json(paginateArray(filtered, params.page, params.limit));
|
|
3526
|
+
} catch (error) {
|
|
3527
|
+
console.error("Failed to read sessions:", error);
|
|
3528
|
+
return c.json({ error: "Failed to read sessions" }, 500);
|
|
3529
|
+
}
|
|
3530
|
+
});
|
|
3531
|
+
app.get("/api/sessions/graph", async (c) => {
|
|
3532
|
+
const mnemeDir2 = getMnemeDir();
|
|
3533
|
+
const showUntitled = c.req.query("showUntitled") === "true";
|
|
3534
|
+
try {
|
|
3535
|
+
const sessionsIndex = readAllSessionIndexes(mnemeDir2);
|
|
3536
|
+
const filteredItems = showUntitled ? sessionsIndex.items : sessionsIndex.items.filter((s) => s.hasSummary === true);
|
|
3537
|
+
const nodes = filteredItems.map((session) => ({
|
|
3538
|
+
id: session.id,
|
|
3539
|
+
title: session.title,
|
|
3540
|
+
type: session.sessionType || "unknown",
|
|
3541
|
+
tags: session.tags || [],
|
|
3542
|
+
createdAt: session.createdAt
|
|
3543
|
+
}));
|
|
3544
|
+
const edges = [];
|
|
3545
|
+
for (let i = 0; i < filteredItems.length; i++) {
|
|
3546
|
+
for (let j = i + 1; j < filteredItems.length; j++) {
|
|
3547
|
+
const s1 = filteredItems[i];
|
|
3548
|
+
const s2 = filteredItems[j];
|
|
3549
|
+
const sharedTags = (s1.tags || []).filter(
|
|
3550
|
+
(t) => (s2.tags || []).includes(t)
|
|
3551
|
+
);
|
|
3552
|
+
if (sharedTags.length > 0) {
|
|
3553
|
+
edges.push({
|
|
3554
|
+
source: s1.id,
|
|
3555
|
+
target: s2.id,
|
|
3556
|
+
weight: sharedTags.length
|
|
3557
|
+
});
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
return c.json({ nodes, edges });
|
|
3562
|
+
} catch (error) {
|
|
3563
|
+
console.error("Failed to build session graph:", error);
|
|
3564
|
+
return c.json({ error: "Failed to build session graph" }, 500);
|
|
3565
|
+
}
|
|
3566
|
+
});
|
|
3567
|
+
app.get("/api/sessions/:id", async (c) => {
|
|
3568
|
+
const id = sanitizeId(c.req.param("id"));
|
|
3569
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
3570
|
+
try {
|
|
3571
|
+
const filePath = findJsonFileById(sessionsDir, id);
|
|
3572
|
+
if (!filePath) {
|
|
3573
|
+
return c.json({ error: "Session not found" }, 404);
|
|
3574
|
+
}
|
|
3575
|
+
const session = safeParseJsonFile(filePath);
|
|
3576
|
+
if (!session) {
|
|
3577
|
+
return c.json({ error: "Failed to parse session" }, 500);
|
|
3578
|
+
}
|
|
3579
|
+
return c.json(session);
|
|
3580
|
+
} catch (error) {
|
|
3581
|
+
console.error("Failed to read session:", error);
|
|
3582
|
+
return c.json({ error: "Failed to read session" }, 500);
|
|
3583
|
+
}
|
|
3584
|
+
});
|
|
3585
|
+
app.get("/api/sessions/:id/markdown", async (c) => {
|
|
3586
|
+
const id = sanitizeId(c.req.param("id"));
|
|
3587
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
3588
|
+
try {
|
|
3589
|
+
const jsonPath = findJsonFileById(sessionsDir, id);
|
|
3590
|
+
if (!jsonPath) {
|
|
3591
|
+
return c.json({ error: "Session not found" }, 404);
|
|
3592
|
+
}
|
|
3593
|
+
const mdPath = jsonPath.replace(/\.json$/, ".md");
|
|
3594
|
+
if (!fs4.existsSync(mdPath)) {
|
|
3595
|
+
return c.json({ exists: false, content: null });
|
|
3596
|
+
}
|
|
3597
|
+
const content = fs4.readFileSync(mdPath, "utf-8");
|
|
3598
|
+
return c.json({ exists: true, content });
|
|
3599
|
+
} catch (error) {
|
|
3600
|
+
console.error("Failed to read session markdown:", error);
|
|
3601
|
+
return c.json({ error: "Failed to read session markdown" }, 500);
|
|
3602
|
+
}
|
|
3603
|
+
});
|
|
3604
|
+
app.delete("/api/sessions/:id", async (c) => {
|
|
3605
|
+
const id = sanitizeId(c.req.param("id"));
|
|
3606
|
+
const dryRun = c.req.query("dry-run") === "true";
|
|
3607
|
+
const mnemeDir2 = getMnemeDir();
|
|
3608
|
+
const sessionsDir = path3.join(mnemeDir2, "sessions");
|
|
3609
|
+
try {
|
|
3610
|
+
const filePath = findJsonFileById(sessionsDir, id);
|
|
3611
|
+
if (!filePath) {
|
|
3612
|
+
return c.json({ error: "Session not found" }, 404);
|
|
3613
|
+
}
|
|
3614
|
+
safeParseJsonFile(filePath);
|
|
3615
|
+
const db = openLocalDatabase(getProjectRoot());
|
|
3616
|
+
let interactionCount = 0;
|
|
3617
|
+
if (db) {
|
|
3618
|
+
interactionCount = countInteractions(db, { sessionId: id });
|
|
3619
|
+
if (!dryRun) {
|
|
3620
|
+
deleteInteractions(db, id);
|
|
3621
|
+
deleteBackups(db, id);
|
|
3622
|
+
}
|
|
3623
|
+
db.close();
|
|
3624
|
+
}
|
|
3625
|
+
if (!dryRun) {
|
|
3626
|
+
fs4.unlinkSync(filePath);
|
|
3627
|
+
const mdPath = filePath.replace(/\.json$/, ".md");
|
|
3628
|
+
if (fs4.existsSync(mdPath)) {
|
|
3629
|
+
fs4.unlinkSync(mdPath);
|
|
3630
|
+
}
|
|
3631
|
+
const sessionLinksDir = path3.join(mnemeDir2, "session-links");
|
|
3632
|
+
const linkPath = path3.join(sessionLinksDir, `${id}.json`);
|
|
3633
|
+
if (fs4.existsSync(linkPath)) {
|
|
3634
|
+
fs4.unlinkSync(linkPath);
|
|
3635
|
+
}
|
|
3636
|
+
}
|
|
3637
|
+
return c.json({
|
|
3638
|
+
deleted: dryRun ? 0 : 1,
|
|
3639
|
+
interactionsDeleted: dryRun ? 0 : interactionCount,
|
|
3640
|
+
dryRun,
|
|
3641
|
+
sessionId: id
|
|
3642
|
+
});
|
|
3643
|
+
} catch (error) {
|
|
3644
|
+
console.error("Failed to delete session:", error);
|
|
3645
|
+
return c.json({ error: "Failed to delete session" }, 500);
|
|
3646
|
+
}
|
|
3647
|
+
});
|
|
3648
|
+
app.delete("/api/sessions", async (c) => {
|
|
3649
|
+
const dryRun = c.req.query("dry-run") === "true";
|
|
3650
|
+
const projectFilter = c.req.query("project");
|
|
3651
|
+
const repositoryFilter = c.req.query("repository");
|
|
3652
|
+
const beforeFilter = c.req.query("before");
|
|
3653
|
+
const mnemeDir2 = getMnemeDir();
|
|
3654
|
+
const sessionsDir = path3.join(mnemeDir2, "sessions");
|
|
3655
|
+
try {
|
|
3656
|
+
const files = listDatedJsonFiles(sessionsDir);
|
|
3657
|
+
const sessionsToDelete = [];
|
|
3658
|
+
for (const filePath of files) {
|
|
3659
|
+
try {
|
|
3660
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
3661
|
+
const session = JSON.parse(content);
|
|
3662
|
+
let shouldDelete = true;
|
|
3663
|
+
if (projectFilter) {
|
|
3664
|
+
const sessionProject = session.context?.projectDir;
|
|
3665
|
+
if (sessionProject !== projectFilter) {
|
|
3666
|
+
shouldDelete = false;
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
if (repositoryFilter && shouldDelete) {
|
|
3670
|
+
const sessionRepo = session.context?.repository;
|
|
3671
|
+
if (sessionRepo !== repositoryFilter) {
|
|
3672
|
+
shouldDelete = false;
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
if (beforeFilter && shouldDelete) {
|
|
3676
|
+
const sessionDate = session.createdAt?.split("T")[0];
|
|
3677
|
+
if (!sessionDate || sessionDate >= beforeFilter) {
|
|
3678
|
+
shouldDelete = false;
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
if (shouldDelete) {
|
|
3682
|
+
sessionsToDelete.push({ id: session.id, path: filePath });
|
|
3683
|
+
}
|
|
3684
|
+
} catch {
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
let totalInteractions = 0;
|
|
3688
|
+
const db = openLocalDatabase(getProjectRoot());
|
|
3689
|
+
if (db) {
|
|
3690
|
+
for (const session of sessionsToDelete) {
|
|
3691
|
+
totalInteractions += countInteractions(db, { sessionId: session.id });
|
|
3692
|
+
}
|
|
3693
|
+
if (!dryRun) {
|
|
3694
|
+
for (const session of sessionsToDelete) {
|
|
3695
|
+
deleteInteractions(db, session.id);
|
|
3696
|
+
deleteBackups(db, session.id);
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
db.close();
|
|
3700
|
+
}
|
|
3701
|
+
if (!dryRun) {
|
|
3702
|
+
for (const session of sessionsToDelete) {
|
|
3703
|
+
fs4.unlinkSync(session.path);
|
|
3704
|
+
const mdPath = session.path.replace(/\.json$/, ".md");
|
|
3705
|
+
if (fs4.existsSync(mdPath)) {
|
|
3706
|
+
fs4.unlinkSync(mdPath);
|
|
3707
|
+
}
|
|
3708
|
+
const sessionLinksDir = path3.join(mnemeDir2, "session-links");
|
|
3709
|
+
const linkPath = path3.join(sessionLinksDir, `${session.id}.json`);
|
|
3710
|
+
if (fs4.existsSync(linkPath)) {
|
|
3711
|
+
fs4.unlinkSync(linkPath);
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
}
|
|
3715
|
+
return c.json({
|
|
3716
|
+
deleted: dryRun ? 0 : sessionsToDelete.length,
|
|
3717
|
+
interactionsDeleted: dryRun ? 0 : totalInteractions,
|
|
3718
|
+
wouldDelete: sessionsToDelete.length,
|
|
3719
|
+
dryRun,
|
|
3720
|
+
filters: {
|
|
3721
|
+
project: projectFilter || null,
|
|
3722
|
+
repository: repositoryFilter || null,
|
|
3723
|
+
before: beforeFilter || null
|
|
3724
|
+
}
|
|
3725
|
+
});
|
|
3726
|
+
} catch (error) {
|
|
3727
|
+
console.error("Failed to delete sessions:", error);
|
|
3728
|
+
return c.json({ error: "Failed to delete sessions" }, 500);
|
|
3729
|
+
}
|
|
3730
|
+
});
|
|
3731
|
+
app.get("/api/current-user", async (c) => {
|
|
3732
|
+
try {
|
|
3733
|
+
const user = getCurrentUser();
|
|
3734
|
+
return c.json({ user });
|
|
3735
|
+
} catch (error) {
|
|
3736
|
+
console.error("Failed to get current user:", error);
|
|
3737
|
+
return c.json({ error: "Failed to get current user" }, 500);
|
|
3738
|
+
}
|
|
3739
|
+
});
|
|
3740
|
+
app.get("/api/sessions/:id/interactions", async (c) => {
|
|
3741
|
+
const id = sanitizeId(c.req.param("id"));
|
|
3742
|
+
const mnemeDir2 = getMnemeDir();
|
|
3743
|
+
const sessionLinksDir = path3.join(mnemeDir2, "session-links");
|
|
3744
|
+
const sessionsDir = path3.join(mnemeDir2, "sessions");
|
|
3745
|
+
try {
|
|
3746
|
+
const sessionFilePath = findJsonFileById(sessionsDir, id);
|
|
3747
|
+
let projectDir = getProjectRoot();
|
|
3748
|
+
if (sessionFilePath) {
|
|
3749
|
+
const sessionData = safeParseJsonFile(sessionFilePath);
|
|
3750
|
+
if (sessionData?.context?.projectDir) {
|
|
3751
|
+
projectDir = sessionData.context.projectDir;
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
const db = openLocalDatabase(projectDir);
|
|
3755
|
+
if (!db) {
|
|
3756
|
+
return c.json({ interactions: [], count: 0 });
|
|
3757
|
+
}
|
|
3758
|
+
let masterId = id;
|
|
3759
|
+
const myLinkFile = path3.join(sessionLinksDir, `${id}.json`);
|
|
3760
|
+
if (fs4.existsSync(myLinkFile)) {
|
|
3761
|
+
try {
|
|
3762
|
+
const myLinkData = JSON.parse(fs4.readFileSync(myLinkFile, "utf-8"));
|
|
3763
|
+
if (myLinkData.masterSessionId) {
|
|
3764
|
+
masterId = myLinkData.masterSessionId;
|
|
3765
|
+
}
|
|
3766
|
+
} catch {
|
|
3767
|
+
}
|
|
3768
|
+
}
|
|
3769
|
+
const sessionIds = [masterId];
|
|
3770
|
+
if (masterId !== id) {
|
|
3771
|
+
sessionIds.push(id);
|
|
3772
|
+
}
|
|
3773
|
+
if (fs4.existsSync(sessionLinksDir)) {
|
|
3774
|
+
const linkFiles = fs4.readdirSync(sessionLinksDir);
|
|
3775
|
+
for (const linkFile of linkFiles) {
|
|
3776
|
+
if (!linkFile.endsWith(".json")) continue;
|
|
3777
|
+
const linkPath = path3.join(sessionLinksDir, linkFile);
|
|
3778
|
+
try {
|
|
3779
|
+
const linkData = JSON.parse(fs4.readFileSync(linkPath, "utf-8"));
|
|
3780
|
+
if (linkData.masterSessionId === masterId) {
|
|
3781
|
+
const childId = linkFile.replace(".json", "");
|
|
3782
|
+
if (!sessionIds.includes(childId)) {
|
|
3783
|
+
sessionIds.push(childId);
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
} catch {
|
|
3787
|
+
}
|
|
3788
|
+
}
|
|
3789
|
+
}
|
|
3790
|
+
const sessionFiles = listDatedJsonFiles(sessionsDir);
|
|
3791
|
+
for (const sessionFile of sessionFiles) {
|
|
3792
|
+
try {
|
|
3793
|
+
const sessionData = JSON.parse(fs4.readFileSync(sessionFile, "utf-8"));
|
|
3794
|
+
if (sessionData.resumedFrom === masterId && sessionData.id !== masterId) {
|
|
3795
|
+
if (!sessionIds.includes(sessionData.id)) {
|
|
3796
|
+
sessionIds.push(sessionData.id);
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
} catch {
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
const interactions = getInteractionsBySessionIds(db, sessionIds);
|
|
3803
|
+
db.close();
|
|
3804
|
+
const groupedInteractions = [];
|
|
3805
|
+
let currentInteraction = null;
|
|
3806
|
+
for (const interaction of interactions) {
|
|
3807
|
+
if (interaction.role === "user") {
|
|
3808
|
+
if (currentInteraction) {
|
|
3809
|
+
groupedInteractions.push(currentInteraction);
|
|
3810
|
+
}
|
|
3811
|
+
let hasPlanMode;
|
|
3812
|
+
let planTools;
|
|
3813
|
+
let toolsUsed;
|
|
3814
|
+
let toolDetails;
|
|
3815
|
+
if (interaction.tool_calls) {
|
|
3816
|
+
try {
|
|
3817
|
+
const metadata = JSON.parse(interaction.tool_calls);
|
|
3818
|
+
if (metadata.hasPlanMode) {
|
|
3819
|
+
hasPlanMode = true;
|
|
3820
|
+
planTools = metadata.planTools || [];
|
|
3821
|
+
}
|
|
3822
|
+
if (metadata.toolsUsed && Array.isArray(metadata.toolsUsed) && metadata.toolsUsed.length > 0) {
|
|
3823
|
+
toolsUsed = metadata.toolsUsed;
|
|
3824
|
+
}
|
|
3825
|
+
if (metadata.toolDetails && Array.isArray(metadata.toolDetails) && metadata.toolDetails.length > 0) {
|
|
3826
|
+
toolDetails = metadata.toolDetails;
|
|
3827
|
+
}
|
|
3828
|
+
} catch {
|
|
3829
|
+
}
|
|
3830
|
+
}
|
|
3831
|
+
currentInteraction = {
|
|
3832
|
+
id: `int-${String(groupedInteractions.length + 1).padStart(3, "0")}`,
|
|
3833
|
+
timestamp: interaction.timestamp,
|
|
3834
|
+
user: interaction.content,
|
|
3835
|
+
assistant: "",
|
|
3836
|
+
thinking: null,
|
|
3837
|
+
isCompactSummary: !!interaction.is_compact_summary,
|
|
3838
|
+
...hasPlanMode !== void 0 && { hasPlanMode },
|
|
3839
|
+
...planTools !== void 0 && planTools.length > 0 && { planTools },
|
|
3840
|
+
...toolsUsed !== void 0 && toolsUsed.length > 0 && { toolsUsed },
|
|
3841
|
+
...toolDetails !== void 0 && toolDetails.length > 0 && { toolDetails },
|
|
3842
|
+
...interaction.agent_id && { agentId: interaction.agent_id },
|
|
3843
|
+
...interaction.agent_type && { agentType: interaction.agent_type }
|
|
3844
|
+
};
|
|
3845
|
+
} else if (interaction.role === "assistant" && currentInteraction) {
|
|
3846
|
+
currentInteraction.assistant = interaction.content;
|
|
3847
|
+
currentInteraction.thinking = interaction.thinking || null;
|
|
3848
|
+
}
|
|
3849
|
+
}
|
|
3850
|
+
if (currentInteraction) {
|
|
3851
|
+
groupedInteractions.push(currentInteraction);
|
|
3852
|
+
}
|
|
3853
|
+
return c.json({
|
|
3854
|
+
interactions: groupedInteractions,
|
|
3855
|
+
count: groupedInteractions.length
|
|
3856
|
+
});
|
|
3857
|
+
} catch (error) {
|
|
3858
|
+
console.error("Failed to get session interactions:", error);
|
|
3859
|
+
return c.json({ error: "Failed to get session interactions" }, 500);
|
|
3860
|
+
}
|
|
3861
|
+
});
|
|
3862
|
+
app.get("/api/decisions", async (c) => {
|
|
3863
|
+
const useIndex = c.req.query("useIndex") !== "false";
|
|
3864
|
+
const usePagination = c.req.query("paginate") !== "false";
|
|
3865
|
+
const mnemeDir2 = getMnemeDir();
|
|
3866
|
+
const params = parsePaginationParams(c);
|
|
3867
|
+
try {
|
|
3868
|
+
let items;
|
|
3869
|
+
if (useIndex) {
|
|
3870
|
+
const index = params.allMonths ? readAllDecisionIndexes(mnemeDir2) : readRecentDecisionIndexes(mnemeDir2);
|
|
3871
|
+
items = index.items;
|
|
3872
|
+
} else {
|
|
3873
|
+
const decisionsDir = path3.join(mnemeDir2, "decisions");
|
|
3874
|
+
const files = listDatedJsonFiles(decisionsDir);
|
|
3875
|
+
if (files.length === 0) {
|
|
3876
|
+
return usePagination ? c.json({
|
|
3877
|
+
data: [],
|
|
3878
|
+
pagination: {
|
|
3879
|
+
page: 1,
|
|
3880
|
+
limit: params.limit,
|
|
3881
|
+
total: 0,
|
|
3882
|
+
totalPages: 0,
|
|
3883
|
+
hasNext: false,
|
|
3884
|
+
hasPrev: false
|
|
3885
|
+
}
|
|
3886
|
+
}) : c.json([]);
|
|
3887
|
+
}
|
|
3888
|
+
items = files.map((filePath) => {
|
|
3889
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
3890
|
+
return JSON.parse(content);
|
|
3891
|
+
});
|
|
3892
|
+
items.sort(
|
|
3893
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
3894
|
+
);
|
|
3895
|
+
}
|
|
3896
|
+
let filtered = items;
|
|
3897
|
+
if (params.tag) {
|
|
3898
|
+
filtered = filtered.filter(
|
|
3899
|
+
(d) => d.tags?.includes(params.tag)
|
|
3900
|
+
);
|
|
3901
|
+
}
|
|
3902
|
+
if (params.search) {
|
|
3903
|
+
const query = params.search.toLowerCase();
|
|
3904
|
+
filtered = filtered.filter((d) => {
|
|
3905
|
+
const title = (d.title || "").toLowerCase();
|
|
3906
|
+
const decision = (d.decision || "").toLowerCase();
|
|
3907
|
+
return title.includes(query) || decision.includes(query);
|
|
3908
|
+
});
|
|
3909
|
+
}
|
|
3910
|
+
if (!usePagination) {
|
|
3911
|
+
return c.json(filtered);
|
|
3912
|
+
}
|
|
3913
|
+
return c.json(paginateArray(filtered, params.page, params.limit));
|
|
3914
|
+
} catch (error) {
|
|
3915
|
+
console.error("Failed to read decisions:", error);
|
|
3916
|
+
return c.json({ error: "Failed to read decisions" }, 500);
|
|
3917
|
+
}
|
|
3918
|
+
});
|
|
3919
|
+
app.get("/api/decisions/:id", async (c) => {
|
|
3920
|
+
const id = sanitizeId(c.req.param("id"));
|
|
3921
|
+
const decisionsDir = path3.join(getMnemeDir(), "decisions");
|
|
3922
|
+
try {
|
|
3923
|
+
const filePath = findJsonFileById(decisionsDir, id);
|
|
3924
|
+
if (!filePath) {
|
|
3925
|
+
return c.json({ error: "Decision not found" }, 404);
|
|
3926
|
+
}
|
|
3927
|
+
const decision = safeParseJsonFile(filePath);
|
|
3928
|
+
if (!decision) {
|
|
3929
|
+
return c.json({ error: "Failed to parse decision" }, 500);
|
|
3930
|
+
}
|
|
3931
|
+
return c.json(decision);
|
|
3932
|
+
} catch (error) {
|
|
3933
|
+
console.error("Failed to read decision:", error);
|
|
3934
|
+
return c.json({ error: "Failed to read decision" }, 500);
|
|
3935
|
+
}
|
|
3936
|
+
});
|
|
3937
|
+
app.get("/api/info", async (c) => {
|
|
3938
|
+
const projectRoot = getProjectRoot();
|
|
3939
|
+
const mnemeDir2 = getMnemeDir();
|
|
3940
|
+
return c.json({
|
|
3941
|
+
projectRoot,
|
|
3942
|
+
mnemeDir: mnemeDir2,
|
|
3943
|
+
exists: fs4.existsSync(mnemeDir2)
|
|
3944
|
+
});
|
|
3945
|
+
});
|
|
3946
|
+
app.get("/api/rules/:id", async (c) => {
|
|
3947
|
+
const id = c.req.param("id");
|
|
3948
|
+
const dir = rulesDir();
|
|
3949
|
+
try {
|
|
3950
|
+
const filePath = path3.join(dir, `${id}.json`);
|
|
3951
|
+
if (!fs4.existsSync(filePath)) {
|
|
3952
|
+
return c.json({ error: "Rules not found" }, 404);
|
|
3953
|
+
}
|
|
3954
|
+
const rules = safeParseJsonFile(filePath);
|
|
3955
|
+
if (!rules) {
|
|
3956
|
+
return c.json({ error: "Failed to parse rules" }, 500);
|
|
3957
|
+
}
|
|
3958
|
+
return c.json(rules);
|
|
3959
|
+
} catch (error) {
|
|
3960
|
+
console.error("Failed to read rules:", error);
|
|
3961
|
+
return c.json({ error: "Failed to read rules" }, 500);
|
|
3962
|
+
}
|
|
3963
|
+
});
|
|
3964
|
+
app.put("/api/rules/:id", async (c) => {
|
|
3965
|
+
const id = c.req.param("id");
|
|
3966
|
+
if (id !== "dev-rules" && id !== "review-guidelines") {
|
|
3967
|
+
return c.json({ error: "Invalid rule type" }, 400);
|
|
3968
|
+
}
|
|
3969
|
+
const dir = rulesDir();
|
|
3970
|
+
try {
|
|
3971
|
+
const filePath = path3.join(dir, `${id}.json`);
|
|
3972
|
+
if (!fs4.existsSync(filePath)) {
|
|
3973
|
+
return c.json({ error: "Rules not found" }, 404);
|
|
3974
|
+
}
|
|
3975
|
+
const body = await c.req.json();
|
|
3976
|
+
if (!body.items || !Array.isArray(body.items)) {
|
|
3977
|
+
return c.json({ error: "Invalid rules format" }, 400);
|
|
3978
|
+
}
|
|
3979
|
+
fs4.writeFileSync(filePath, JSON.stringify(body, null, 2));
|
|
3980
|
+
return c.json(body);
|
|
3981
|
+
} catch (error) {
|
|
3982
|
+
console.error("Failed to update rules:", error);
|
|
3983
|
+
return c.json({ error: "Failed to update rules" }, 500);
|
|
3984
|
+
}
|
|
3985
|
+
});
|
|
3986
|
+
app.get("/api/timeline", async (c) => {
|
|
3987
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
3988
|
+
try {
|
|
3989
|
+
const files = listDatedJsonFiles(sessionsDir);
|
|
3990
|
+
if (files.length === 0) {
|
|
3991
|
+
return c.json({ timeline: {} });
|
|
3992
|
+
}
|
|
3993
|
+
const sessions = files.map((filePath) => {
|
|
3994
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
3995
|
+
return JSON.parse(content);
|
|
3996
|
+
});
|
|
3997
|
+
const grouped = {};
|
|
3998
|
+
for (const session of sessions) {
|
|
3999
|
+
const date = session.createdAt?.split("T")[0] || "unknown";
|
|
4000
|
+
if (!grouped[date]) grouped[date] = [];
|
|
4001
|
+
grouped[date].push({
|
|
4002
|
+
id: session.id,
|
|
4003
|
+
title: session.title || "Untitled",
|
|
4004
|
+
sessionType: session.sessionType,
|
|
4005
|
+
branch: session.context?.branch,
|
|
4006
|
+
tags: session.tags || [],
|
|
4007
|
+
createdAt: session.createdAt
|
|
4008
|
+
});
|
|
4009
|
+
}
|
|
4010
|
+
const sortedTimeline = {};
|
|
4011
|
+
for (const date of Object.keys(grouped).sort().reverse()) {
|
|
4012
|
+
sortedTimeline[date] = grouped[date].sort(
|
|
4013
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
4014
|
+
);
|
|
4015
|
+
}
|
|
4016
|
+
return c.json({ timeline: sortedTimeline });
|
|
4017
|
+
} catch (error) {
|
|
4018
|
+
console.error("Failed to build timeline:", error);
|
|
4019
|
+
return c.json({ error: "Failed to build timeline" }, 500);
|
|
4020
|
+
}
|
|
4021
|
+
});
|
|
4022
|
+
app.get("/api/tag-network", async (c) => {
|
|
4023
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
4024
|
+
try {
|
|
4025
|
+
const files = listDatedJsonFiles(sessionsDir);
|
|
4026
|
+
const tagCounts = /* @__PURE__ */ new Map();
|
|
4027
|
+
const coOccurrences = /* @__PURE__ */ new Map();
|
|
4028
|
+
for (const filePath of files) {
|
|
4029
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4030
|
+
const session = JSON.parse(content);
|
|
4031
|
+
const tags = session.tags || [];
|
|
4032
|
+
for (const tag of tags) {
|
|
4033
|
+
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
|
|
4034
|
+
}
|
|
4035
|
+
for (let i = 0; i < tags.length; i++) {
|
|
4036
|
+
for (let j = i + 1; j < tags.length; j++) {
|
|
4037
|
+
const key = [tags[i], tags[j]].sort().join("|");
|
|
4038
|
+
coOccurrences.set(key, (coOccurrences.get(key) || 0) + 1);
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
}
|
|
4042
|
+
const nodes = Array.from(tagCounts.entries()).map(([id, count]) => ({
|
|
4043
|
+
id,
|
|
4044
|
+
count
|
|
4045
|
+
}));
|
|
4046
|
+
const edges = Array.from(coOccurrences.entries()).map(([key, weight]) => {
|
|
4047
|
+
const [source, target] = key.split("|");
|
|
4048
|
+
return { source, target, weight };
|
|
4049
|
+
});
|
|
4050
|
+
return c.json({ nodes, edges });
|
|
4051
|
+
} catch (error) {
|
|
4052
|
+
console.error("Failed to build tag network:", error);
|
|
4053
|
+
return c.json({ error: "Failed to build tag network" }, 500);
|
|
4054
|
+
}
|
|
4055
|
+
});
|
|
4056
|
+
app.get("/api/decisions/:id/impact", async (c) => {
|
|
4057
|
+
const decisionId = sanitizeId(c.req.param("id"));
|
|
4058
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
4059
|
+
const patternsDir2 = path3.join(getMnemeDir(), "patterns");
|
|
4060
|
+
try {
|
|
4061
|
+
const impactedSessions = [];
|
|
4062
|
+
const impactedPatterns = [];
|
|
4063
|
+
const sessionFiles = listDatedJsonFiles(sessionsDir);
|
|
4064
|
+
for (const filePath of sessionFiles) {
|
|
4065
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4066
|
+
const session = JSON.parse(content);
|
|
4067
|
+
const hasReference = session.relatedSessions?.includes(decisionId) || session.interactions?.some(
|
|
4068
|
+
(i) => i.reasoning?.includes(decisionId) || i.choice?.includes(decisionId)
|
|
4069
|
+
);
|
|
4070
|
+
if (hasReference) {
|
|
4071
|
+
impactedSessions.push({
|
|
4072
|
+
id: session.id,
|
|
4073
|
+
title: session.title || "Untitled"
|
|
4074
|
+
});
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
const patternFiles = listJsonFiles(patternsDir2);
|
|
4078
|
+
for (const filePath of patternFiles) {
|
|
4079
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4080
|
+
const data = JSON.parse(content);
|
|
4081
|
+
const patterns = data.patterns || [];
|
|
4082
|
+
for (const pattern of patterns) {
|
|
4083
|
+
if (pattern.sourceId?.includes(decisionId) || pattern.description?.includes(decisionId)) {
|
|
4084
|
+
impactedPatterns.push({
|
|
4085
|
+
id: `${path3.basename(filePath, ".json")}-${pattern.type}`,
|
|
4086
|
+
description: pattern.description || "No description"
|
|
4087
|
+
});
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
}
|
|
4091
|
+
return c.json({
|
|
4092
|
+
decisionId,
|
|
4093
|
+
impactedSessions,
|
|
4094
|
+
impactedPatterns
|
|
4095
|
+
});
|
|
4096
|
+
} catch (error) {
|
|
4097
|
+
console.error("Failed to analyze decision impact:", error);
|
|
4098
|
+
return c.json({ error: "Failed to analyze decision impact" }, 500);
|
|
4099
|
+
}
|
|
4100
|
+
});
|
|
4101
|
+
var getOpenAIKey = () => {
|
|
4102
|
+
return process.env.OPENAI_API_KEY || null;
|
|
4103
|
+
};
|
|
4104
|
+
app.get("/api/summary/weekly", async (c) => {
|
|
4105
|
+
const mnemeDir2 = getMnemeDir();
|
|
4106
|
+
const apiKey = getOpenAIKey();
|
|
4107
|
+
try {
|
|
4108
|
+
const sessionsIndex = readRecentSessionIndexes(mnemeDir2);
|
|
4109
|
+
const decisionsIndex = readRecentDecisionIndexes(mnemeDir2);
|
|
4110
|
+
const now = /* @__PURE__ */ new Date();
|
|
4111
|
+
const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1e3);
|
|
4112
|
+
const recentSessions = sessionsIndex.items.filter(
|
|
4113
|
+
(s) => new Date(s.createdAt) >= weekAgo
|
|
4114
|
+
);
|
|
4115
|
+
const recentDecisions = decisionsIndex.items.filter(
|
|
4116
|
+
(d) => new Date(d.createdAt) >= weekAgo
|
|
4117
|
+
);
|
|
4118
|
+
const summary = {
|
|
4119
|
+
period: { start: weekAgo.toISOString(), end: now.toISOString() },
|
|
4120
|
+
stats: {
|
|
4121
|
+
sessions: recentSessions.length,
|
|
4122
|
+
decisions: recentDecisions.length,
|
|
4123
|
+
interactions: recentSessions.reduce(
|
|
4124
|
+
(sum, s) => sum + (s.interactionCount || 0),
|
|
4125
|
+
0
|
|
4126
|
+
)
|
|
4127
|
+
},
|
|
4128
|
+
topTags: getTopTags(recentSessions, 5),
|
|
4129
|
+
sessionTypes: getSessionTypeBreakdown(recentSessions),
|
|
4130
|
+
aiSummary: null
|
|
4131
|
+
};
|
|
4132
|
+
if (apiKey && (recentSessions.length > 0 || recentDecisions.length > 0)) {
|
|
4133
|
+
try {
|
|
4134
|
+
const prompt = buildSummaryPrompt(recentSessions, recentDecisions);
|
|
4135
|
+
summary.aiSummary = await generateAISummary(apiKey, prompt);
|
|
4136
|
+
} catch (aiError) {
|
|
4137
|
+
console.error("AI summary generation failed:", aiError);
|
|
4138
|
+
}
|
|
4139
|
+
}
|
|
4140
|
+
return c.json(summary);
|
|
4141
|
+
} catch (error) {
|
|
4142
|
+
console.error("Failed to generate weekly summary:", error);
|
|
4143
|
+
return c.json({ error: "Failed to generate weekly summary" }, 500);
|
|
4144
|
+
}
|
|
4145
|
+
});
|
|
4146
|
+
app.post("/api/summary/generate", async (c) => {
|
|
4147
|
+
const apiKey = getOpenAIKey();
|
|
4148
|
+
if (!apiKey) {
|
|
4149
|
+
return c.json(
|
|
4150
|
+
{
|
|
4151
|
+
error: "AI summary requires OPENAI_API_KEY environment variable (optional feature)"
|
|
4152
|
+
},
|
|
4153
|
+
400
|
|
4154
|
+
);
|
|
4155
|
+
}
|
|
4156
|
+
const body = await c.req.json();
|
|
4157
|
+
const { sessionIds, prompt: customPrompt } = body;
|
|
4158
|
+
const mnemeDir2 = getMnemeDir();
|
|
4159
|
+
const sessionsDir = path3.join(mnemeDir2, "sessions");
|
|
4160
|
+
try {
|
|
4161
|
+
const sessions = [];
|
|
4162
|
+
for (const id of sessionIds || []) {
|
|
4163
|
+
const filePath = findJsonFileById(sessionsDir, id);
|
|
4164
|
+
if (filePath) {
|
|
4165
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4166
|
+
sessions.push(JSON.parse(content));
|
|
4167
|
+
}
|
|
4168
|
+
}
|
|
4169
|
+
if (sessions.length === 0) {
|
|
4170
|
+
return c.json({ error: "No sessions found" }, 404);
|
|
4171
|
+
}
|
|
4172
|
+
const prompt = customPrompt || `Summarize the following development sessions concisely:
|
|
4173
|
+
|
|
4174
|
+
${sessions.map((s) => `- ${s.title}: ${s.goal || "No goal specified"}`).join("\n")}`;
|
|
4175
|
+
const summary = await generateAISummary(apiKey, prompt);
|
|
4176
|
+
return c.json({ summary });
|
|
4177
|
+
} catch (error) {
|
|
4178
|
+
console.error("Failed to generate summary:", error);
|
|
4179
|
+
return c.json({ error: "Failed to generate summary" }, 500);
|
|
4180
|
+
}
|
|
4181
|
+
});
|
|
4182
|
+
function getTopTags(sessions, limit) {
|
|
4183
|
+
const tagCount = {};
|
|
4184
|
+
for (const session of sessions) {
|
|
4185
|
+
for (const tag of session.tags || []) {
|
|
4186
|
+
tagCount[tag] = (tagCount[tag] || 0) + 1;
|
|
4187
|
+
}
|
|
4188
|
+
}
|
|
4189
|
+
return Object.entries(tagCount).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, limit);
|
|
4190
|
+
}
|
|
4191
|
+
function getSessionTypeBreakdown(sessions) {
|
|
4192
|
+
const breakdown = {};
|
|
4193
|
+
for (const session of sessions) {
|
|
4194
|
+
const type = session.sessionType || "unknown";
|
|
4195
|
+
breakdown[type] = (breakdown[type] || 0) + 1;
|
|
4196
|
+
}
|
|
4197
|
+
return breakdown;
|
|
4198
|
+
}
|
|
4199
|
+
function buildSummaryPrompt(sessions, decisions) {
|
|
4200
|
+
const sessionList = sessions.map((s) => `- ${s.title} (${s.sessionType || "unknown"})`).join("\n");
|
|
4201
|
+
const decisionList = decisions.map((d) => `- ${d.title} (${d.status})`).join("\n");
|
|
4202
|
+
return `Provide a brief weekly development summary (2-3 sentences) based on this activity:
|
|
4203
|
+
|
|
4204
|
+
Sessions (${sessions.length}):
|
|
4205
|
+
${sessionList || "None"}
|
|
4206
|
+
|
|
4207
|
+
Decisions (${decisions.length}):
|
|
4208
|
+
${decisionList || "None"}
|
|
4209
|
+
|
|
4210
|
+
Focus on key accomplishments and patterns.`;
|
|
4211
|
+
}
|
|
4212
|
+
async function generateAISummary(apiKey, prompt) {
|
|
4213
|
+
const response = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
4214
|
+
method: "POST",
|
|
4215
|
+
headers: {
|
|
4216
|
+
"Content-Type": "application/json",
|
|
4217
|
+
Authorization: `Bearer ${apiKey}`
|
|
4218
|
+
},
|
|
4219
|
+
body: JSON.stringify({
|
|
4220
|
+
model: "gpt-4o-mini",
|
|
4221
|
+
messages: [{ role: "user", content: prompt }],
|
|
4222
|
+
max_tokens: 200,
|
|
4223
|
+
temperature: 0.7
|
|
4224
|
+
})
|
|
4225
|
+
});
|
|
4226
|
+
if (!response.ok) {
|
|
4227
|
+
throw new Error("OpenAI API request failed");
|
|
4228
|
+
}
|
|
4229
|
+
const data = await response.json();
|
|
4230
|
+
return data.choices?.[0]?.message?.content || "Unable to generate summary.";
|
|
4231
|
+
}
|
|
4232
|
+
app.get("/api/stats/overview", async (c) => {
|
|
4233
|
+
const mnemeDir2 = getMnemeDir();
|
|
4234
|
+
try {
|
|
4235
|
+
const sessionsIndex = readAllSessionIndexes(mnemeDir2);
|
|
4236
|
+
const decisionsIndex = readAllDecisionIndexes(mnemeDir2);
|
|
4237
|
+
const validSessions = sessionsIndex.items.filter(
|
|
4238
|
+
(session) => session.interactionCount > 0 || session.hasSummary === true
|
|
4239
|
+
);
|
|
4240
|
+
const sessionTypeCount = {};
|
|
4241
|
+
for (const session of validSessions) {
|
|
4242
|
+
const type = session.sessionType || "unknown";
|
|
4243
|
+
sessionTypeCount[type] = (sessionTypeCount[type] || 0) + 1;
|
|
4244
|
+
}
|
|
4245
|
+
let totalPatterns = 0;
|
|
4246
|
+
const patternsByType = {};
|
|
4247
|
+
const patternsPath = path3.join(mnemeDir2, "patterns");
|
|
4248
|
+
if (fs4.existsSync(patternsPath)) {
|
|
4249
|
+
const patternFiles = listJsonFiles(patternsPath);
|
|
4250
|
+
for (const filePath of patternFiles) {
|
|
4251
|
+
try {
|
|
4252
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4253
|
+
const data = JSON.parse(content);
|
|
4254
|
+
const patterns = data.patterns || [];
|
|
4255
|
+
for (const pattern of patterns) {
|
|
4256
|
+
totalPatterns++;
|
|
4257
|
+
const type = pattern.type || "unknown";
|
|
4258
|
+
patternsByType[type] = (patternsByType[type] || 0) + 1;
|
|
4259
|
+
}
|
|
4260
|
+
} catch {
|
|
4261
|
+
}
|
|
4262
|
+
}
|
|
4263
|
+
}
|
|
4264
|
+
let totalRules = 0;
|
|
4265
|
+
const rulesByType = {};
|
|
4266
|
+
const rulesPath = path3.join(mnemeDir2, "rules");
|
|
4267
|
+
if (fs4.existsSync(rulesPath)) {
|
|
4268
|
+
for (const ruleType of ["dev-rules", "review-guidelines"]) {
|
|
4269
|
+
const rulePath = path3.join(rulesPath, `${ruleType}.json`);
|
|
4270
|
+
if (fs4.existsSync(rulePath)) {
|
|
4271
|
+
try {
|
|
4272
|
+
const content = fs4.readFileSync(rulePath, "utf-8");
|
|
4273
|
+
const data = JSON.parse(content);
|
|
4274
|
+
const items = data.items || [];
|
|
4275
|
+
const activeItems = items.filter(
|
|
4276
|
+
(item) => item.status === "active"
|
|
4277
|
+
);
|
|
4278
|
+
rulesByType[ruleType] = activeItems.length;
|
|
4279
|
+
totalRules += activeItems.length;
|
|
4280
|
+
} catch {
|
|
4281
|
+
}
|
|
4282
|
+
}
|
|
4283
|
+
}
|
|
4284
|
+
}
|
|
4285
|
+
return c.json({
|
|
4286
|
+
sessions: {
|
|
4287
|
+
total: validSessions.length,
|
|
4288
|
+
byType: sessionTypeCount
|
|
4289
|
+
},
|
|
4290
|
+
decisions: {
|
|
4291
|
+
total: decisionsIndex.items.length
|
|
4292
|
+
},
|
|
4293
|
+
patterns: {
|
|
4294
|
+
total: totalPatterns,
|
|
4295
|
+
byType: patternsByType
|
|
4296
|
+
},
|
|
4297
|
+
rules: {
|
|
4298
|
+
total: totalRules,
|
|
4299
|
+
byType: rulesByType
|
|
4300
|
+
}
|
|
4301
|
+
});
|
|
4302
|
+
} catch (error) {
|
|
4303
|
+
console.error("Failed to get stats overview:", error);
|
|
4304
|
+
return c.json({ error: "Failed to get stats overview" }, 500);
|
|
4305
|
+
}
|
|
4306
|
+
});
|
|
4307
|
+
app.get("/api/stats/activity", async (c) => {
|
|
4308
|
+
const mnemeDir2 = getMnemeDir();
|
|
4309
|
+
const daysParam = Number.parseInt(c.req.query("days") || "30", 10);
|
|
4310
|
+
const MAX_DAYS = 365;
|
|
4311
|
+
const safeDays = Math.min(Math.max(1, daysParam), MAX_DAYS);
|
|
4312
|
+
try {
|
|
4313
|
+
const sessionsIndex = readAllSessionIndexes(mnemeDir2);
|
|
4314
|
+
const decisionsIndex = readAllDecisionIndexes(mnemeDir2);
|
|
4315
|
+
const now = /* @__PURE__ */ new Date();
|
|
4316
|
+
const startDate = new Date(
|
|
4317
|
+
now.getTime() - (safeDays - 1) * 24 * 60 * 60 * 1e3
|
|
4318
|
+
);
|
|
4319
|
+
const activityByDate = {};
|
|
4320
|
+
for (let i = 0; i < safeDays; i++) {
|
|
4321
|
+
const d = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1e3);
|
|
4322
|
+
const dateKey = d.toISOString().split("T")[0];
|
|
4323
|
+
activityByDate[dateKey] = { sessions: 0, decisions: 0 };
|
|
4324
|
+
}
|
|
4325
|
+
for (const session of sessionsIndex.items) {
|
|
4326
|
+
const dateKey = session.createdAt.split("T")[0];
|
|
4327
|
+
if (activityByDate[dateKey]) {
|
|
4328
|
+
activityByDate[dateKey].sessions += 1;
|
|
4329
|
+
}
|
|
4330
|
+
}
|
|
4331
|
+
for (const decision of decisionsIndex.items) {
|
|
4332
|
+
const dateKey = decision.createdAt.split("T")[0];
|
|
4333
|
+
if (activityByDate[dateKey]) {
|
|
4334
|
+
activityByDate[dateKey].decisions += 1;
|
|
4335
|
+
}
|
|
4336
|
+
}
|
|
4337
|
+
const activity = Object.entries(activityByDate).map(([date, counts]) => ({ date, ...counts })).sort((a, b) => a.date.localeCompare(b.date));
|
|
4338
|
+
return c.json({ activity, days: safeDays });
|
|
4339
|
+
} catch (error) {
|
|
4340
|
+
console.error("Failed to get activity stats:", error);
|
|
4341
|
+
return c.json({ error: "Failed to get activity stats" }, 500);
|
|
4342
|
+
}
|
|
4343
|
+
});
|
|
4344
|
+
app.get("/api/stats/tags", async (c) => {
|
|
4345
|
+
const mnemeDir2 = getMnemeDir();
|
|
4346
|
+
try {
|
|
4347
|
+
const sessionsIndex = readAllSessionIndexes(mnemeDir2);
|
|
4348
|
+
const tagCount = {};
|
|
4349
|
+
for (const session of sessionsIndex.items) {
|
|
4350
|
+
for (const tag of session.tags || []) {
|
|
4351
|
+
tagCount[tag] = (tagCount[tag] || 0) + 1;
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
4354
|
+
const tags = Object.entries(tagCount).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, 20);
|
|
4355
|
+
return c.json({ tags });
|
|
4356
|
+
} catch (error) {
|
|
4357
|
+
console.error("Failed to get tag stats:", error);
|
|
4358
|
+
return c.json({ error: "Failed to get tag stats" }, 500);
|
|
4359
|
+
}
|
|
4360
|
+
});
|
|
4361
|
+
var patternsDir = () => path3.join(getMnemeDir(), "patterns");
|
|
4362
|
+
app.get("/api/patterns", async (c) => {
|
|
4363
|
+
const dir = patternsDir();
|
|
4364
|
+
try {
|
|
4365
|
+
if (!fs4.existsSync(dir)) {
|
|
4366
|
+
return c.json({ patterns: [] });
|
|
4367
|
+
}
|
|
4368
|
+
const files = listJsonFiles(dir);
|
|
4369
|
+
const allPatterns = [];
|
|
4370
|
+
for (const filePath of files) {
|
|
4371
|
+
try {
|
|
4372
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4373
|
+
const data = JSON.parse(content);
|
|
4374
|
+
const patterns = data.items || data.patterns || [];
|
|
4375
|
+
for (const pattern of patterns) {
|
|
4376
|
+
allPatterns.push({
|
|
4377
|
+
...pattern,
|
|
4378
|
+
sourceFile: path3.basename(filePath, ".json")
|
|
4379
|
+
});
|
|
4380
|
+
}
|
|
4381
|
+
} catch {
|
|
4382
|
+
}
|
|
4383
|
+
}
|
|
4384
|
+
allPatterns.sort(
|
|
4385
|
+
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
|
4386
|
+
);
|
|
4387
|
+
return c.json({ patterns: allPatterns });
|
|
4388
|
+
} catch (error) {
|
|
4389
|
+
console.error("Failed to read patterns:", error);
|
|
4390
|
+
return c.json({ error: "Failed to read patterns" }, 500);
|
|
4391
|
+
}
|
|
4392
|
+
});
|
|
4393
|
+
app.get("/api/patterns/stats", async (c) => {
|
|
4394
|
+
const dir = patternsDir();
|
|
4395
|
+
try {
|
|
4396
|
+
if (!fs4.existsSync(dir)) {
|
|
4397
|
+
return c.json({ total: 0, byType: {}, bySource: {} });
|
|
4398
|
+
}
|
|
4399
|
+
const files = listJsonFiles(dir);
|
|
4400
|
+
let total = 0;
|
|
4401
|
+
const byType = {};
|
|
4402
|
+
const bySource = {};
|
|
4403
|
+
for (const filePath of files) {
|
|
4404
|
+
try {
|
|
4405
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4406
|
+
const data = JSON.parse(content);
|
|
4407
|
+
const patterns = data.items || data.patterns || [];
|
|
4408
|
+
const sourceName = path3.basename(filePath, ".json");
|
|
4409
|
+
for (const pattern of patterns) {
|
|
4410
|
+
total++;
|
|
4411
|
+
const type = pattern.type || "unknown";
|
|
4412
|
+
byType[type] = (byType[type] || 0) + 1;
|
|
4413
|
+
bySource[sourceName] = (bySource[sourceName] || 0) + 1;
|
|
4414
|
+
}
|
|
4415
|
+
} catch {
|
|
4416
|
+
}
|
|
4417
|
+
}
|
|
4418
|
+
return c.json({ total, byType, bySource });
|
|
4419
|
+
} catch (error) {
|
|
4420
|
+
console.error("Failed to get pattern stats:", error);
|
|
4421
|
+
return c.json({ error: "Failed to get pattern stats" }, 500);
|
|
4422
|
+
}
|
|
4423
|
+
});
|
|
4424
|
+
function sessionToMarkdown(session) {
|
|
4425
|
+
const lines = [];
|
|
4426
|
+
lines.push(`# ${session.title || "Untitled Session"}`);
|
|
4427
|
+
lines.push("");
|
|
4428
|
+
lines.push(`**ID:** ${session.id}`);
|
|
4429
|
+
lines.push(`**Created:** ${session.createdAt}`);
|
|
4430
|
+
if (session.sessionType) {
|
|
4431
|
+
lines.push(`**Type:** ${session.sessionType}`);
|
|
4432
|
+
}
|
|
4433
|
+
if (session.context) {
|
|
4434
|
+
const ctx = session.context;
|
|
4435
|
+
if (ctx.branch) lines.push(`**Branch:** ${ctx.branch}`);
|
|
4436
|
+
if (ctx.user) lines.push(`**User:** ${ctx.user}`);
|
|
4437
|
+
}
|
|
4438
|
+
lines.push("");
|
|
4439
|
+
if (session.goal) {
|
|
4440
|
+
lines.push("## Goal");
|
|
4441
|
+
lines.push("");
|
|
4442
|
+
lines.push(session.goal);
|
|
4443
|
+
lines.push("");
|
|
4444
|
+
}
|
|
4445
|
+
const tags = session.tags;
|
|
4446
|
+
if (tags && tags.length > 0) {
|
|
4447
|
+
lines.push("## Tags");
|
|
4448
|
+
lines.push("");
|
|
4449
|
+
lines.push(tags.map((t) => `\`${t}\``).join(", "));
|
|
4450
|
+
lines.push("");
|
|
4451
|
+
}
|
|
4452
|
+
const interactions = session.interactions;
|
|
4453
|
+
if (interactions && interactions.length > 0) {
|
|
4454
|
+
lines.push("## Interactions");
|
|
4455
|
+
lines.push("");
|
|
4456
|
+
for (const interaction of interactions) {
|
|
4457
|
+
lines.push(`### ${interaction.choice || "Interaction"}`);
|
|
4458
|
+
lines.push("");
|
|
4459
|
+
if (interaction.reasoning) {
|
|
4460
|
+
lines.push(`**Reasoning:** ${interaction.reasoning}`);
|
|
4461
|
+
lines.push("");
|
|
4462
|
+
}
|
|
4463
|
+
if (interaction.timestamp) {
|
|
4464
|
+
lines.push(`*${interaction.timestamp}*`);
|
|
4465
|
+
lines.push("");
|
|
4466
|
+
}
|
|
4467
|
+
lines.push("---");
|
|
4468
|
+
lines.push("");
|
|
4469
|
+
}
|
|
4470
|
+
}
|
|
4471
|
+
if (session.outcome) {
|
|
4472
|
+
lines.push("## Outcome");
|
|
4473
|
+
lines.push("");
|
|
4474
|
+
lines.push(session.outcome);
|
|
4475
|
+
lines.push("");
|
|
4476
|
+
}
|
|
4477
|
+
const relatedSessions = session.relatedSessions;
|
|
4478
|
+
if (relatedSessions && relatedSessions.length > 0) {
|
|
4479
|
+
lines.push("## Related Sessions");
|
|
4480
|
+
lines.push("");
|
|
4481
|
+
for (const relId of relatedSessions) {
|
|
4482
|
+
lines.push(`- ${relId}`);
|
|
4483
|
+
}
|
|
4484
|
+
lines.push("");
|
|
4485
|
+
}
|
|
4486
|
+
lines.push("---");
|
|
4487
|
+
lines.push("*Exported from mneme*");
|
|
4488
|
+
return lines.join("\n");
|
|
4489
|
+
}
|
|
4490
|
+
function decisionToMarkdown(decision) {
|
|
4491
|
+
const lines = [];
|
|
4492
|
+
lines.push(`# ${decision.title || "Untitled Decision"}`);
|
|
4493
|
+
lines.push("");
|
|
4494
|
+
lines.push(`**ID:** ${decision.id}`);
|
|
4495
|
+
lines.push(`**Status:** ${decision.status || "unknown"}`);
|
|
4496
|
+
lines.push(`**Created:** ${decision.createdAt}`);
|
|
4497
|
+
if (decision.updatedAt) {
|
|
4498
|
+
lines.push(`**Updated:** ${decision.updatedAt}`);
|
|
4499
|
+
}
|
|
4500
|
+
lines.push("");
|
|
4501
|
+
if (decision.decision) {
|
|
4502
|
+
lines.push("## Decision");
|
|
4503
|
+
lines.push("");
|
|
4504
|
+
lines.push(decision.decision);
|
|
4505
|
+
lines.push("");
|
|
4506
|
+
}
|
|
4507
|
+
if (decision.rationale) {
|
|
4508
|
+
lines.push("## Rationale");
|
|
4509
|
+
lines.push("");
|
|
4510
|
+
lines.push(decision.rationale);
|
|
4511
|
+
lines.push("");
|
|
4512
|
+
}
|
|
4513
|
+
const tags = decision.tags;
|
|
4514
|
+
if (tags && tags.length > 0) {
|
|
4515
|
+
lines.push("## Tags");
|
|
4516
|
+
lines.push("");
|
|
4517
|
+
lines.push(tags.map((t) => `\`${t}\``).join(", "));
|
|
4518
|
+
lines.push("");
|
|
4519
|
+
}
|
|
4520
|
+
const alternatives = decision.alternatives;
|
|
4521
|
+
if (alternatives && alternatives.length > 0) {
|
|
4522
|
+
lines.push("## Alternatives Considered");
|
|
4523
|
+
lines.push("");
|
|
4524
|
+
for (const alt of alternatives) {
|
|
4525
|
+
lines.push(`### ${alt.title || "Alternative"}`);
|
|
4526
|
+
if (alt.description) {
|
|
4527
|
+
lines.push("");
|
|
4528
|
+
lines.push(alt.description);
|
|
4529
|
+
}
|
|
4530
|
+
if (alt.pros) {
|
|
4531
|
+
lines.push("");
|
|
4532
|
+
lines.push("**Pros:**");
|
|
4533
|
+
for (const pro of alt.pros) {
|
|
4534
|
+
lines.push(`- ${pro}`);
|
|
4535
|
+
}
|
|
4536
|
+
}
|
|
4537
|
+
if (alt.cons) {
|
|
4538
|
+
lines.push("");
|
|
4539
|
+
lines.push("**Cons:**");
|
|
4540
|
+
for (const con of alt.cons) {
|
|
4541
|
+
lines.push(`- ${con}`);
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
lines.push("");
|
|
4545
|
+
}
|
|
4546
|
+
}
|
|
4547
|
+
const relatedSessions = decision.relatedSessions;
|
|
4548
|
+
if (relatedSessions && relatedSessions.length > 0) {
|
|
4549
|
+
lines.push("## Related Sessions");
|
|
4550
|
+
lines.push("");
|
|
4551
|
+
for (const relId of relatedSessions) {
|
|
4552
|
+
lines.push(`- ${relId}`);
|
|
4553
|
+
}
|
|
4554
|
+
lines.push("");
|
|
4555
|
+
}
|
|
4556
|
+
lines.push("---");
|
|
4557
|
+
lines.push("*Exported from mneme*");
|
|
4558
|
+
return lines.join("\n");
|
|
4559
|
+
}
|
|
4560
|
+
app.get("/api/export/sessions/:id/markdown", async (c) => {
|
|
4561
|
+
const id = c.req.param("id");
|
|
4562
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
4563
|
+
try {
|
|
4564
|
+
const filePath = findJsonFileById(sessionsDir, id);
|
|
4565
|
+
if (!filePath) {
|
|
4566
|
+
return c.json({ error: "Session not found" }, 404);
|
|
4567
|
+
}
|
|
4568
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4569
|
+
const session = JSON.parse(content);
|
|
4570
|
+
const markdown = sessionToMarkdown(session);
|
|
4571
|
+
const filename = `session-${id}.md`;
|
|
4572
|
+
c.header("Content-Type", "text/markdown; charset=utf-8");
|
|
4573
|
+
c.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
4574
|
+
return c.text(markdown);
|
|
4575
|
+
} catch (error) {
|
|
4576
|
+
console.error("Failed to export session:", error);
|
|
4577
|
+
return c.json({ error: "Failed to export session" }, 500);
|
|
4578
|
+
}
|
|
4579
|
+
});
|
|
4580
|
+
app.get("/api/export/decisions/:id/markdown", async (c) => {
|
|
4581
|
+
const id = sanitizeId(c.req.param("id"));
|
|
4582
|
+
const decisionsDir = path3.join(getMnemeDir(), "decisions");
|
|
4583
|
+
try {
|
|
4584
|
+
const filePath = findJsonFileById(decisionsDir, id);
|
|
4585
|
+
if (!filePath) {
|
|
4586
|
+
return c.json({ error: "Decision not found" }, 404);
|
|
4587
|
+
}
|
|
4588
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4589
|
+
const decision = JSON.parse(content);
|
|
4590
|
+
const markdown = decisionToMarkdown(decision);
|
|
4591
|
+
const filename = `decision-${id}.md`;
|
|
4592
|
+
c.header("Content-Type", "text/markdown; charset=utf-8");
|
|
4593
|
+
c.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
4594
|
+
return c.text(markdown);
|
|
4595
|
+
} catch (error) {
|
|
4596
|
+
console.error("Failed to export decision:", error);
|
|
4597
|
+
return c.json({ error: "Failed to export decision" }, 500);
|
|
4598
|
+
}
|
|
4599
|
+
});
|
|
4600
|
+
app.post("/api/export/sessions/bulk", async (c) => {
|
|
4601
|
+
const body = await c.req.json();
|
|
4602
|
+
const { ids } = body;
|
|
4603
|
+
if (!ids || ids.length === 0) {
|
|
4604
|
+
return c.json({ error: "No session IDs provided" }, 400);
|
|
4605
|
+
}
|
|
4606
|
+
const sessionsDir = path3.join(getMnemeDir(), "sessions");
|
|
4607
|
+
const markdowns = [];
|
|
4608
|
+
try {
|
|
4609
|
+
for (const id of ids) {
|
|
4610
|
+
const filePath = findJsonFileById(sessionsDir, id);
|
|
4611
|
+
if (filePath) {
|
|
4612
|
+
const content = fs4.readFileSync(filePath, "utf-8");
|
|
4613
|
+
const session = JSON.parse(content);
|
|
4614
|
+
markdowns.push(sessionToMarkdown(session));
|
|
4615
|
+
}
|
|
4616
|
+
}
|
|
4617
|
+
if (markdowns.length === 0) {
|
|
4618
|
+
return c.json({ error: "No sessions found" }, 404);
|
|
4619
|
+
}
|
|
4620
|
+
const combined = markdowns.join("\n\n---\n\n");
|
|
4621
|
+
const filename = `sessions-export-${Date.now()}.md`;
|
|
4622
|
+
c.header("Content-Type", "text/markdown; charset=utf-8");
|
|
4623
|
+
c.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
4624
|
+
return c.text(combined);
|
|
4625
|
+
} catch (error) {
|
|
4626
|
+
console.error("Failed to export sessions:", error);
|
|
4627
|
+
return c.json({ error: "Failed to export sessions" }, 500);
|
|
4628
|
+
}
|
|
4629
|
+
});
|
|
4630
|
+
app.get("/api/tags", async (c) => {
|
|
4631
|
+
const tagsPath = path3.join(getMnemeDir(), "tags.json");
|
|
4632
|
+
try {
|
|
4633
|
+
if (!fs4.existsSync(tagsPath)) {
|
|
4634
|
+
return c.json({ version: 1, tags: [] });
|
|
4635
|
+
}
|
|
4636
|
+
const tags = safeParseJsonFile(tagsPath);
|
|
4637
|
+
if (!tags) {
|
|
4638
|
+
return c.json({ error: "Failed to parse tags" }, 500);
|
|
4639
|
+
}
|
|
4640
|
+
return c.json(tags);
|
|
4641
|
+
} catch (error) {
|
|
4642
|
+
console.error("Failed to read tags:", error);
|
|
4643
|
+
return c.json({ error: "Failed to read tags" }, 500);
|
|
4644
|
+
}
|
|
4645
|
+
});
|
|
4646
|
+
app.get("/api/indexes/status", async (c) => {
|
|
4647
|
+
const mnemeDir2 = getMnemeDir();
|
|
4648
|
+
try {
|
|
4649
|
+
const sessionsIndex = readAllSessionIndexes(mnemeDir2);
|
|
4650
|
+
const decisionsIndex = readAllDecisionIndexes(mnemeDir2);
|
|
4651
|
+
return c.json({
|
|
4652
|
+
sessions: {
|
|
4653
|
+
exists: sessionsIndex.items.length > 0,
|
|
4654
|
+
itemCount: sessionsIndex.items.length,
|
|
4655
|
+
updatedAt: sessionsIndex.updatedAt,
|
|
4656
|
+
isStale: isIndexStale(sessionsIndex)
|
|
4657
|
+
},
|
|
4658
|
+
decisions: {
|
|
4659
|
+
exists: decisionsIndex.items.length > 0,
|
|
4660
|
+
itemCount: decisionsIndex.items.length,
|
|
4661
|
+
updatedAt: decisionsIndex.updatedAt,
|
|
4662
|
+
isStale: isIndexStale(decisionsIndex)
|
|
4663
|
+
}
|
|
4664
|
+
});
|
|
4665
|
+
} catch (error) {
|
|
4666
|
+
console.error("Failed to get index status:", error);
|
|
4667
|
+
return c.json({ error: "Failed to get index status" }, 500);
|
|
4668
|
+
}
|
|
4669
|
+
});
|
|
4670
|
+
app.post("/api/indexes/rebuild", async (c) => {
|
|
4671
|
+
const mnemeDir2 = getMnemeDir();
|
|
4672
|
+
try {
|
|
4673
|
+
const sessionIndexes = rebuildAllSessionIndexes(mnemeDir2);
|
|
4674
|
+
const decisionIndexes = rebuildAllDecisionIndexes(mnemeDir2);
|
|
4675
|
+
let sessionCount = 0;
|
|
4676
|
+
let sessionUpdatedAt = "";
|
|
4677
|
+
for (const index of sessionIndexes.values()) {
|
|
4678
|
+
sessionCount += index.items.length;
|
|
4679
|
+
if (index.updatedAt > sessionUpdatedAt) {
|
|
4680
|
+
sessionUpdatedAt = index.updatedAt;
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
let decisionCount = 0;
|
|
4684
|
+
let decisionUpdatedAt = "";
|
|
4685
|
+
for (const index of decisionIndexes.values()) {
|
|
4686
|
+
decisionCount += index.items.length;
|
|
4687
|
+
if (index.updatedAt > decisionUpdatedAt) {
|
|
4688
|
+
decisionUpdatedAt = index.updatedAt;
|
|
4689
|
+
}
|
|
4690
|
+
}
|
|
4691
|
+
return c.json({
|
|
4692
|
+
success: true,
|
|
4693
|
+
sessions: {
|
|
4694
|
+
itemCount: sessionCount,
|
|
4695
|
+
monthCount: sessionIndexes.size,
|
|
4696
|
+
updatedAt: sessionUpdatedAt || (/* @__PURE__ */ new Date()).toISOString()
|
|
4697
|
+
},
|
|
4698
|
+
decisions: {
|
|
4699
|
+
itemCount: decisionCount,
|
|
4700
|
+
monthCount: decisionIndexes.size,
|
|
4701
|
+
updatedAt: decisionUpdatedAt || (/* @__PURE__ */ new Date()).toISOString()
|
|
4702
|
+
}
|
|
4703
|
+
});
|
|
4704
|
+
} catch (error) {
|
|
4705
|
+
return c.json(
|
|
4706
|
+
{ error: "Failed to rebuild indexes", details: String(error) },
|
|
4707
|
+
500
|
|
4708
|
+
);
|
|
4709
|
+
}
|
|
4710
|
+
});
|
|
4711
|
+
var distPath = path3.join(import.meta.dirname, "public");
|
|
4712
|
+
if (fs4.existsSync(distPath)) {
|
|
4713
|
+
app.use("/*", serveStatic({ root: distPath }));
|
|
4714
|
+
app.get("*", async (c) => {
|
|
4715
|
+
const indexPath = path3.join(distPath, "index.html");
|
|
4716
|
+
if (fs4.existsSync(indexPath)) {
|
|
4717
|
+
const content = fs4.readFileSync(indexPath, "utf-8");
|
|
4718
|
+
return c.html(content);
|
|
4719
|
+
}
|
|
4720
|
+
return c.notFound();
|
|
4721
|
+
});
|
|
4722
|
+
}
|
|
4723
|
+
var requestedPort = parseInt(process.env.PORT || "7777", 10);
|
|
4724
|
+
var maxPortAttempts = 10;
|
|
4725
|
+
var mnemeDir = getMnemeDir();
|
|
4726
|
+
if (fs4.existsSync(mnemeDir)) {
|
|
4727
|
+
try {
|
|
4728
|
+
const sessionsIndex = readRecentSessionIndexes(mnemeDir, 1);
|
|
4729
|
+
const decisionsIndex = readRecentDecisionIndexes(mnemeDir, 1);
|
|
4730
|
+
if (isIndexStale(sessionsIndex) || isIndexStale(decisionsIndex)) {
|
|
4731
|
+
console.log("Building indexes...");
|
|
4732
|
+
const sessionIndexes = rebuildAllSessionIndexes(mnemeDir);
|
|
4733
|
+
const decisionIndexes = rebuildAllDecisionIndexes(mnemeDir);
|
|
4734
|
+
let sessionCount = 0;
|
|
4735
|
+
for (const index of sessionIndexes.values()) {
|
|
4736
|
+
sessionCount += index.items.length;
|
|
4737
|
+
}
|
|
4738
|
+
let decisionCount = 0;
|
|
4739
|
+
for (const index of decisionIndexes.values()) {
|
|
4740
|
+
decisionCount += index.items.length;
|
|
4741
|
+
}
|
|
4742
|
+
console.log(
|
|
4743
|
+
`Indexed ${sessionCount} sessions, ${decisionCount} decisions`
|
|
4744
|
+
);
|
|
4745
|
+
}
|
|
4746
|
+
} catch (error) {
|
|
4747
|
+
console.warn("Failed to initialize indexes:", error);
|
|
4748
|
+
}
|
|
4749
|
+
}
|
|
4750
|
+
async function startServer(port, attempt = 1) {
|
|
4751
|
+
return new Promise((resolve, reject) => {
|
|
4752
|
+
const server = serve({
|
|
4753
|
+
fetch: app.fetch,
|
|
4754
|
+
port
|
|
4755
|
+
});
|
|
4756
|
+
server.on("error", (err) => {
|
|
4757
|
+
if (err.code === "EADDRINUSE" && attempt < maxPortAttempts) {
|
|
4758
|
+
console.log(`Port ${port} is in use, trying ${port + 1}...`);
|
|
4759
|
+
server.close();
|
|
4760
|
+
startServer(port + 1, attempt + 1).then(resolve).catch(reject);
|
|
4761
|
+
} else if (err.code === "EADDRINUSE") {
|
|
4762
|
+
reject(
|
|
4763
|
+
new Error(
|
|
4764
|
+
`Could not find an available port after ${maxPortAttempts} attempts`
|
|
4765
|
+
)
|
|
4766
|
+
);
|
|
4767
|
+
} else {
|
|
4768
|
+
reject(err);
|
|
4769
|
+
}
|
|
4770
|
+
});
|
|
4771
|
+
server.on("listening", () => {
|
|
4772
|
+
console.log(`
|
|
4773
|
+
mneme dashboard`);
|
|
4774
|
+
console.log(`Project: ${getProjectRoot()}`);
|
|
4775
|
+
console.log(`URL: http://localhost:${port}
|
|
4776
|
+
`);
|
|
4777
|
+
resolve();
|
|
4778
|
+
});
|
|
4779
|
+
});
|
|
4780
|
+
}
|
|
4781
|
+
startServer(requestedPort).catch((err) => {
|
|
4782
|
+
console.error("Failed to start server:", err.message);
|
|
4783
|
+
process.exit(1);
|
|
4784
|
+
});
|
|
4785
|
+
process.on("SIGINT", () => {
|
|
4786
|
+
console.log("\nShutting down...");
|
|
4787
|
+
process.exit(0);
|
|
4788
|
+
});
|
|
4789
|
+
process.on("SIGTERM", () => {
|
|
4790
|
+
process.exit(0);
|
|
4791
|
+
});
|