sendkit-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/db.d.ts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +132 -0
- package/dist/oauth-store.d.ts +17 -0
- package/dist/oauth-store.js +85 -0
- package/dist/pkce.d.ts +7 -0
- package/dist/routes/auth.d.ts +2 -0
- package/dist/routes/auth.js +1764 -0
- package/dist/users.d.ts +9 -0
- package/dist/users.js +79 -0
- package/package.json +43 -0
|
@@ -0,0 +1,1764 @@
|
|
|
1
|
+
// src/oauth-store.ts
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// src/db.ts
|
|
5
|
+
import { Database } from "bun:sqlite";
|
|
6
|
+
var db = new Database("sendkit.db", { create: true });
|
|
7
|
+
db.exec("PRAGMA journal_mode = WAL;");
|
|
8
|
+
db.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
10
|
+
id TEXT PRIMARY KEY,
|
|
11
|
+
username TEXT UNIQUE NOT NULL,
|
|
12
|
+
password_hash TEXT NOT NULL,
|
|
13
|
+
telegram_bot_token TEXT,
|
|
14
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
15
|
+
);
|
|
16
|
+
`);
|
|
17
|
+
db.exec(`
|
|
18
|
+
CREATE TABLE IF NOT EXISTS authorization_codes (
|
|
19
|
+
code TEXT PRIMARY KEY,
|
|
20
|
+
user_id TEXT NOT NULL,
|
|
21
|
+
code_challenge TEXT NOT NULL,
|
|
22
|
+
redirect_uri TEXT NOT NULL,
|
|
23
|
+
expires_at INTEGER NOT NULL,
|
|
24
|
+
used INTEGER NOT NULL DEFAULT 0,
|
|
25
|
+
FOREIGN KEY (user_id) REFERENCES users(id)
|
|
26
|
+
);
|
|
27
|
+
`);
|
|
28
|
+
db.exec(`
|
|
29
|
+
CREATE TABLE IF NOT EXISTS access_tokens (
|
|
30
|
+
token TEXT PRIMARY KEY,
|
|
31
|
+
user_id TEXT NOT NULL,
|
|
32
|
+
expires_at INTEGER NOT NULL,
|
|
33
|
+
FOREIGN KEY (user_id) REFERENCES users(id)
|
|
34
|
+
);
|
|
35
|
+
`);
|
|
36
|
+
|
|
37
|
+
// src/oauth-store.ts
|
|
38
|
+
var AUTH_CODE_TTL_MS = 5 * 60 * 1000;
|
|
39
|
+
var ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;
|
|
40
|
+
function generateSecureToken() {
|
|
41
|
+
return randomBytes(32).toString("hex");
|
|
42
|
+
}
|
|
43
|
+
function createAuthorizationCode(params) {
|
|
44
|
+
const code = generateSecureToken();
|
|
45
|
+
const expiresAt = Date.now() + AUTH_CODE_TTL_MS;
|
|
46
|
+
db.query(`INSERT INTO authorization_codes (code, user_id, code_challenge, redirect_uri, expires_at)
|
|
47
|
+
VALUES (?, ?, ?, ?, ?)`).run(code, params.userId, params.codeChallenge, params.redirectUri, expiresAt);
|
|
48
|
+
return code;
|
|
49
|
+
}
|
|
50
|
+
function consumeAuthorizationCode(code) {
|
|
51
|
+
const row = db.query(`SELECT user_id, code_challenge, redirect_uri, expires_at, used
|
|
52
|
+
FROM authorization_codes WHERE code = ?`).get(code);
|
|
53
|
+
if (!row)
|
|
54
|
+
return null;
|
|
55
|
+
if (row.used)
|
|
56
|
+
return null;
|
|
57
|
+
if (Date.now() > row.expires_at)
|
|
58
|
+
return null;
|
|
59
|
+
db.query("UPDATE authorization_codes SET used = 1 WHERE code = ?").run(code);
|
|
60
|
+
return {
|
|
61
|
+
userId: row.user_id,
|
|
62
|
+
codeChallenge: row.code_challenge,
|
|
63
|
+
redirectUri: row.redirect_uri
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function createAccessToken(userId) {
|
|
67
|
+
const token = generateSecureToken();
|
|
68
|
+
const expiresAt = Date.now() + ACCESS_TOKEN_TTL_MS;
|
|
69
|
+
db.query("INSERT INTO access_tokens (token, user_id, expires_at) VALUES (?, ?, ?)").run(token, userId, expiresAt);
|
|
70
|
+
return { token, expiresIn: ACCESS_TOKEN_TTL_MS / 1000 };
|
|
71
|
+
}
|
|
72
|
+
function validateAccessToken(token) {
|
|
73
|
+
const row = db.query("SELECT user_id, expires_at FROM access_tokens WHERE token = ?").get(token);
|
|
74
|
+
if (!row)
|
|
75
|
+
return null;
|
|
76
|
+
if (Date.now() > row.expires_at)
|
|
77
|
+
return null;
|
|
78
|
+
return { userId: row.user_id };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/users.ts
|
|
82
|
+
import { randomUUID } from "node:crypto";
|
|
83
|
+
async function createUser(username, password) {
|
|
84
|
+
const existing = db.query("SELECT id FROM users WHERE username = ?").get(username);
|
|
85
|
+
if (existing) {
|
|
86
|
+
throw new Error("Username already taken");
|
|
87
|
+
}
|
|
88
|
+
const id = randomUUID();
|
|
89
|
+
const passwordHash = await Bun.password.hash(password);
|
|
90
|
+
db.query("INSERT INTO users (id, username, password_hash) VALUES (?, ?, ?)").run(id, username, passwordHash);
|
|
91
|
+
return { id, username, telegramBotToken: null };
|
|
92
|
+
}
|
|
93
|
+
async function verifyUser(username, password) {
|
|
94
|
+
const row = db.query("SELECT id, username, password_hash, telegram_bot_token FROM users WHERE username = ?").get(username);
|
|
95
|
+
if (!row)
|
|
96
|
+
return null;
|
|
97
|
+
const passwordMatches = await Bun.password.verify(password, row.password_hash);
|
|
98
|
+
if (!passwordMatches)
|
|
99
|
+
return null;
|
|
100
|
+
return {
|
|
101
|
+
id: row.id,
|
|
102
|
+
username: row.username,
|
|
103
|
+
telegramBotToken: row.telegram_bot_token
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function getUserById(id) {
|
|
107
|
+
const row = db.query("SELECT id, username, telegram_bot_token FROM users WHERE id = ?").get(id);
|
|
108
|
+
if (!row)
|
|
109
|
+
return null;
|
|
110
|
+
return {
|
|
111
|
+
id: row.id,
|
|
112
|
+
username: row.username,
|
|
113
|
+
telegramBotToken: row.telegram_bot_token
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function setTelegramBotToken(userId, botToken) {
|
|
117
|
+
db.query("UPDATE users SET telegram_bot_token = ? WHERE id = ?").run(botToken, userId);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ../../node_modules/hono/dist/compose.js
|
|
121
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
122
|
+
return (context, next) => {
|
|
123
|
+
let index = -1;
|
|
124
|
+
return dispatch(0);
|
|
125
|
+
async function dispatch(i) {
|
|
126
|
+
if (i <= index) {
|
|
127
|
+
throw new Error("next() called multiple times");
|
|
128
|
+
}
|
|
129
|
+
index = i;
|
|
130
|
+
let res;
|
|
131
|
+
let isError = false;
|
|
132
|
+
let handler;
|
|
133
|
+
if (middleware[i]) {
|
|
134
|
+
handler = middleware[i][0][0];
|
|
135
|
+
context.req.routeIndex = i;
|
|
136
|
+
} else {
|
|
137
|
+
handler = i === middleware.length && next || undefined;
|
|
138
|
+
}
|
|
139
|
+
if (handler) {
|
|
140
|
+
try {
|
|
141
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
142
|
+
} catch (err) {
|
|
143
|
+
if (err instanceof Error && onError) {
|
|
144
|
+
context.error = err;
|
|
145
|
+
res = await onError(err, context);
|
|
146
|
+
isError = true;
|
|
147
|
+
} else {
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
if (context.finalized === false && onNotFound) {
|
|
153
|
+
res = await onNotFound(context);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (res && (context.finalized === false || isError)) {
|
|
157
|
+
context.res = res;
|
|
158
|
+
}
|
|
159
|
+
return context;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// ../../node_modules/hono/dist/request/constants.js
|
|
165
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
166
|
+
|
|
167
|
+
// ../../node_modules/hono/dist/utils/body.js
|
|
168
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
169
|
+
const { all = false, dot = false } = options;
|
|
170
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
171
|
+
const contentType = headers.get("Content-Type");
|
|
172
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
173
|
+
return parseFormData(request, { all, dot });
|
|
174
|
+
}
|
|
175
|
+
return {};
|
|
176
|
+
};
|
|
177
|
+
async function parseFormData(request, options) {
|
|
178
|
+
const formData = await request.formData();
|
|
179
|
+
if (formData) {
|
|
180
|
+
return convertFormDataToBodyData(formData, options);
|
|
181
|
+
}
|
|
182
|
+
return {};
|
|
183
|
+
}
|
|
184
|
+
function convertFormDataToBodyData(formData, options) {
|
|
185
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
186
|
+
formData.forEach((value, key) => {
|
|
187
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
188
|
+
if (!shouldParseAllValues) {
|
|
189
|
+
form[key] = value;
|
|
190
|
+
} else {
|
|
191
|
+
handleParsingAllValues(form, key, value);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
if (options.dot) {
|
|
195
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
196
|
+
const shouldParseDotValues = key.includes(".");
|
|
197
|
+
if (shouldParseDotValues) {
|
|
198
|
+
handleParsingNestedValues(form, key, value);
|
|
199
|
+
delete form[key];
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return form;
|
|
204
|
+
}
|
|
205
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
206
|
+
if (form[key] !== undefined) {
|
|
207
|
+
if (Array.isArray(form[key])) {
|
|
208
|
+
form[key].push(value);
|
|
209
|
+
} else {
|
|
210
|
+
form[key] = [form[key], value];
|
|
211
|
+
}
|
|
212
|
+
} else {
|
|
213
|
+
if (!key.endsWith("[]")) {
|
|
214
|
+
form[key] = value;
|
|
215
|
+
} else {
|
|
216
|
+
form[key] = [value];
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
221
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
let nestedForm = form;
|
|
225
|
+
const keys = key.split(".");
|
|
226
|
+
keys.forEach((key2, index) => {
|
|
227
|
+
if (index === keys.length - 1) {
|
|
228
|
+
nestedForm[key2] = value;
|
|
229
|
+
} else {
|
|
230
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
231
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
232
|
+
}
|
|
233
|
+
nestedForm = nestedForm[key2];
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// ../../node_modules/hono/dist/utils/url.js
|
|
239
|
+
var splitPath = (path) => {
|
|
240
|
+
const paths = path.split("/");
|
|
241
|
+
if (paths[0] === "") {
|
|
242
|
+
paths.shift();
|
|
243
|
+
}
|
|
244
|
+
return paths;
|
|
245
|
+
};
|
|
246
|
+
var splitRoutingPath = (routePath) => {
|
|
247
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
248
|
+
const paths = splitPath(path);
|
|
249
|
+
return replaceGroupMarks(paths, groups);
|
|
250
|
+
};
|
|
251
|
+
var extractGroupsFromPath = (path) => {
|
|
252
|
+
const groups = [];
|
|
253
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
254
|
+
const mark = `@${index}`;
|
|
255
|
+
groups.push([mark, match]);
|
|
256
|
+
return mark;
|
|
257
|
+
});
|
|
258
|
+
return { groups, path };
|
|
259
|
+
};
|
|
260
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
261
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
262
|
+
const [mark] = groups[i];
|
|
263
|
+
for (let j = paths.length - 1;j >= 0; j--) {
|
|
264
|
+
if (paths[j].includes(mark)) {
|
|
265
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return paths;
|
|
271
|
+
};
|
|
272
|
+
var patternCache = {};
|
|
273
|
+
var getPattern = (label, next) => {
|
|
274
|
+
if (label === "*") {
|
|
275
|
+
return "*";
|
|
276
|
+
}
|
|
277
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
278
|
+
if (match) {
|
|
279
|
+
const cacheKey = `${label}#${next}`;
|
|
280
|
+
if (!patternCache[cacheKey]) {
|
|
281
|
+
if (match[2]) {
|
|
282
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
|
|
283
|
+
} else {
|
|
284
|
+
patternCache[cacheKey] = [label, match[1], true];
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return patternCache[cacheKey];
|
|
288
|
+
}
|
|
289
|
+
return null;
|
|
290
|
+
};
|
|
291
|
+
var tryDecode = (str, decoder) => {
|
|
292
|
+
try {
|
|
293
|
+
return decoder(str);
|
|
294
|
+
} catch {
|
|
295
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
296
|
+
try {
|
|
297
|
+
return decoder(match);
|
|
298
|
+
} catch {
|
|
299
|
+
return match;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
305
|
+
var getPath = (request) => {
|
|
306
|
+
const url = request.url;
|
|
307
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
308
|
+
let i = start;
|
|
309
|
+
for (;i < url.length; i++) {
|
|
310
|
+
const charCode = url.charCodeAt(i);
|
|
311
|
+
if (charCode === 37) {
|
|
312
|
+
const queryIndex = url.indexOf("?", i);
|
|
313
|
+
const hashIndex = url.indexOf("#", i);
|
|
314
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
315
|
+
const path = url.slice(start, end);
|
|
316
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
317
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return url.slice(start, i);
|
|
322
|
+
};
|
|
323
|
+
var getPathNoStrict = (request) => {
|
|
324
|
+
const result = getPath(request);
|
|
325
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
326
|
+
};
|
|
327
|
+
var mergePath = (base, sub, ...rest) => {
|
|
328
|
+
if (rest.length) {
|
|
329
|
+
sub = mergePath(sub, ...rest);
|
|
330
|
+
}
|
|
331
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
332
|
+
};
|
|
333
|
+
var checkOptionalParameter = (path) => {
|
|
334
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
const segments = path.split("/");
|
|
338
|
+
const results = [];
|
|
339
|
+
let basePath = "";
|
|
340
|
+
segments.forEach((segment) => {
|
|
341
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
342
|
+
basePath += "/" + segment;
|
|
343
|
+
} else if (/\:/.test(segment)) {
|
|
344
|
+
if (/\?/.test(segment)) {
|
|
345
|
+
if (results.length === 0 && basePath === "") {
|
|
346
|
+
results.push("/");
|
|
347
|
+
} else {
|
|
348
|
+
results.push(basePath);
|
|
349
|
+
}
|
|
350
|
+
const optionalSegment = segment.replace("?", "");
|
|
351
|
+
basePath += "/" + optionalSegment;
|
|
352
|
+
results.push(basePath);
|
|
353
|
+
} else {
|
|
354
|
+
basePath += "/" + segment;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
359
|
+
};
|
|
360
|
+
var _decodeURI = (value) => {
|
|
361
|
+
if (!/[%+]/.test(value)) {
|
|
362
|
+
return value;
|
|
363
|
+
}
|
|
364
|
+
if (value.indexOf("+") !== -1) {
|
|
365
|
+
value = value.replace(/\+/g, " ");
|
|
366
|
+
}
|
|
367
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
368
|
+
};
|
|
369
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
370
|
+
let encoded;
|
|
371
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
372
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
373
|
+
if (keyIndex2 === -1) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
377
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
378
|
+
}
|
|
379
|
+
while (keyIndex2 !== -1) {
|
|
380
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
381
|
+
if (trailingKeyCode === 61) {
|
|
382
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
383
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
384
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
|
|
385
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
386
|
+
return "";
|
|
387
|
+
}
|
|
388
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
389
|
+
}
|
|
390
|
+
encoded = /[%+]/.test(url);
|
|
391
|
+
if (!encoded) {
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const results = {};
|
|
396
|
+
encoded ??= /[%+]/.test(url);
|
|
397
|
+
let keyIndex = url.indexOf("?", 8);
|
|
398
|
+
while (keyIndex !== -1) {
|
|
399
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
400
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
401
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
402
|
+
valueIndex = -1;
|
|
403
|
+
}
|
|
404
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
|
|
405
|
+
if (encoded) {
|
|
406
|
+
name = _decodeURI(name);
|
|
407
|
+
}
|
|
408
|
+
keyIndex = nextKeyIndex;
|
|
409
|
+
if (name === "") {
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
let value;
|
|
413
|
+
if (valueIndex === -1) {
|
|
414
|
+
value = "";
|
|
415
|
+
} else {
|
|
416
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
|
|
417
|
+
if (encoded) {
|
|
418
|
+
value = _decodeURI(value);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (multiple) {
|
|
422
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
423
|
+
results[name] = [];
|
|
424
|
+
}
|
|
425
|
+
results[name].push(value);
|
|
426
|
+
} else {
|
|
427
|
+
results[name] ??= value;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return key ? results[key] : results;
|
|
431
|
+
};
|
|
432
|
+
var getQueryParam = _getQueryParam;
|
|
433
|
+
var getQueryParams = (url, key) => {
|
|
434
|
+
return _getQueryParam(url, key, true);
|
|
435
|
+
};
|
|
436
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
437
|
+
|
|
438
|
+
// ../../node_modules/hono/dist/request.js
|
|
439
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
440
|
+
var HonoRequest = class {
|
|
441
|
+
raw;
|
|
442
|
+
#validatedData;
|
|
443
|
+
#matchResult;
|
|
444
|
+
routeIndex = 0;
|
|
445
|
+
path;
|
|
446
|
+
bodyCache = {};
|
|
447
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
448
|
+
this.raw = request;
|
|
449
|
+
this.path = path;
|
|
450
|
+
this.#matchResult = matchResult;
|
|
451
|
+
this.#validatedData = {};
|
|
452
|
+
}
|
|
453
|
+
param(key) {
|
|
454
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
455
|
+
}
|
|
456
|
+
#getDecodedParam(key) {
|
|
457
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
458
|
+
const param = this.#getParamValue(paramKey);
|
|
459
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
460
|
+
}
|
|
461
|
+
#getAllDecodedParams() {
|
|
462
|
+
const decoded = {};
|
|
463
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
464
|
+
for (const key of keys) {
|
|
465
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
466
|
+
if (value !== undefined) {
|
|
467
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return decoded;
|
|
471
|
+
}
|
|
472
|
+
#getParamValue(paramKey) {
|
|
473
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
474
|
+
}
|
|
475
|
+
query(key) {
|
|
476
|
+
return getQueryParam(this.url, key);
|
|
477
|
+
}
|
|
478
|
+
queries(key) {
|
|
479
|
+
return getQueryParams(this.url, key);
|
|
480
|
+
}
|
|
481
|
+
header(name) {
|
|
482
|
+
if (name) {
|
|
483
|
+
return this.raw.headers.get(name) ?? undefined;
|
|
484
|
+
}
|
|
485
|
+
const headerData = {};
|
|
486
|
+
this.raw.headers.forEach((value, key) => {
|
|
487
|
+
headerData[key] = value;
|
|
488
|
+
});
|
|
489
|
+
return headerData;
|
|
490
|
+
}
|
|
491
|
+
async parseBody(options) {
|
|
492
|
+
return parseBody(this, options);
|
|
493
|
+
}
|
|
494
|
+
#cachedBody = (key) => {
|
|
495
|
+
const { bodyCache, raw } = this;
|
|
496
|
+
const cachedBody = bodyCache[key];
|
|
497
|
+
if (cachedBody) {
|
|
498
|
+
return cachedBody;
|
|
499
|
+
}
|
|
500
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
501
|
+
if (anyCachedKey) {
|
|
502
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
503
|
+
if (anyCachedKey === "json") {
|
|
504
|
+
body = JSON.stringify(body);
|
|
505
|
+
}
|
|
506
|
+
return new Response(body)[key]();
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
return bodyCache[key] = raw[key]();
|
|
510
|
+
};
|
|
511
|
+
json() {
|
|
512
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
513
|
+
}
|
|
514
|
+
text() {
|
|
515
|
+
return this.#cachedBody("text");
|
|
516
|
+
}
|
|
517
|
+
arrayBuffer() {
|
|
518
|
+
return this.#cachedBody("arrayBuffer");
|
|
519
|
+
}
|
|
520
|
+
bytes() {
|
|
521
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
522
|
+
}
|
|
523
|
+
blob() {
|
|
524
|
+
return this.#cachedBody("blob");
|
|
525
|
+
}
|
|
526
|
+
formData() {
|
|
527
|
+
return this.#cachedBody("formData");
|
|
528
|
+
}
|
|
529
|
+
addValidatedData(target, data) {
|
|
530
|
+
this.#validatedData[target] = data;
|
|
531
|
+
}
|
|
532
|
+
valid(target) {
|
|
533
|
+
return this.#validatedData[target];
|
|
534
|
+
}
|
|
535
|
+
get url() {
|
|
536
|
+
return this.raw.url;
|
|
537
|
+
}
|
|
538
|
+
get method() {
|
|
539
|
+
return this.raw.method;
|
|
540
|
+
}
|
|
541
|
+
get [GET_MATCH_RESULT]() {
|
|
542
|
+
return this.#matchResult;
|
|
543
|
+
}
|
|
544
|
+
get matchedRoutes() {
|
|
545
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
546
|
+
}
|
|
547
|
+
get routePath() {
|
|
548
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
// ../../node_modules/hono/dist/utils/html.js
|
|
553
|
+
var HtmlEscapedCallbackPhase = {
|
|
554
|
+
Stringify: 1,
|
|
555
|
+
BeforeStream: 2,
|
|
556
|
+
Stream: 3
|
|
557
|
+
};
|
|
558
|
+
var raw = (value, callbacks) => {
|
|
559
|
+
const escapedString = new String(value);
|
|
560
|
+
escapedString.isEscaped = true;
|
|
561
|
+
escapedString.callbacks = callbacks;
|
|
562
|
+
return escapedString;
|
|
563
|
+
};
|
|
564
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
565
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
566
|
+
if (!(str instanceof Promise)) {
|
|
567
|
+
str = str.toString();
|
|
568
|
+
}
|
|
569
|
+
if (str instanceof Promise) {
|
|
570
|
+
str = await str;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
const callbacks = str.callbacks;
|
|
574
|
+
if (!callbacks?.length) {
|
|
575
|
+
return Promise.resolve(str);
|
|
576
|
+
}
|
|
577
|
+
if (buffer) {
|
|
578
|
+
buffer[0] += str;
|
|
579
|
+
} else {
|
|
580
|
+
buffer = [str];
|
|
581
|
+
}
|
|
582
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
583
|
+
if (preserveCallbacks) {
|
|
584
|
+
return raw(await resStr, callbacks);
|
|
585
|
+
} else {
|
|
586
|
+
return resStr;
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// ../../node_modules/hono/dist/context.js
|
|
591
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
592
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
593
|
+
return {
|
|
594
|
+
"Content-Type": contentType,
|
|
595
|
+
...headers
|
|
596
|
+
};
|
|
597
|
+
};
|
|
598
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
599
|
+
var Context = class {
|
|
600
|
+
#rawRequest;
|
|
601
|
+
#req;
|
|
602
|
+
env = {};
|
|
603
|
+
#var;
|
|
604
|
+
finalized = false;
|
|
605
|
+
error;
|
|
606
|
+
#status;
|
|
607
|
+
#executionCtx;
|
|
608
|
+
#res;
|
|
609
|
+
#layout;
|
|
610
|
+
#renderer;
|
|
611
|
+
#notFoundHandler;
|
|
612
|
+
#preparedHeaders;
|
|
613
|
+
#matchResult;
|
|
614
|
+
#path;
|
|
615
|
+
constructor(req, options) {
|
|
616
|
+
this.#rawRequest = req;
|
|
617
|
+
if (options) {
|
|
618
|
+
this.#executionCtx = options.executionCtx;
|
|
619
|
+
this.env = options.env;
|
|
620
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
621
|
+
this.#path = options.path;
|
|
622
|
+
this.#matchResult = options.matchResult;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
get req() {
|
|
626
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
627
|
+
return this.#req;
|
|
628
|
+
}
|
|
629
|
+
get event() {
|
|
630
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
631
|
+
return this.#executionCtx;
|
|
632
|
+
} else {
|
|
633
|
+
throw Error("This context has no FetchEvent");
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
get executionCtx() {
|
|
637
|
+
if (this.#executionCtx) {
|
|
638
|
+
return this.#executionCtx;
|
|
639
|
+
} else {
|
|
640
|
+
throw Error("This context has no ExecutionContext");
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
get res() {
|
|
644
|
+
return this.#res ||= createResponseInstance(null, {
|
|
645
|
+
headers: this.#preparedHeaders ??= new Headers
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
set res(_res) {
|
|
649
|
+
if (this.#res && _res) {
|
|
650
|
+
_res = createResponseInstance(_res.body, _res);
|
|
651
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
652
|
+
if (k === "content-type") {
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (k === "set-cookie") {
|
|
656
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
657
|
+
_res.headers.delete("set-cookie");
|
|
658
|
+
for (const cookie of cookies) {
|
|
659
|
+
_res.headers.append("set-cookie", cookie);
|
|
660
|
+
}
|
|
661
|
+
} else {
|
|
662
|
+
_res.headers.set(k, v);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
this.#res = _res;
|
|
667
|
+
this.finalized = true;
|
|
668
|
+
}
|
|
669
|
+
render = (...args) => {
|
|
670
|
+
this.#renderer ??= (content) => this.html(content);
|
|
671
|
+
return this.#renderer(...args);
|
|
672
|
+
};
|
|
673
|
+
setLayout = (layout) => this.#layout = layout;
|
|
674
|
+
getLayout = () => this.#layout;
|
|
675
|
+
setRenderer = (renderer) => {
|
|
676
|
+
this.#renderer = renderer;
|
|
677
|
+
};
|
|
678
|
+
header = (name, value, options) => {
|
|
679
|
+
if (this.finalized) {
|
|
680
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
681
|
+
}
|
|
682
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
|
|
683
|
+
if (value === undefined) {
|
|
684
|
+
headers.delete(name);
|
|
685
|
+
} else if (options?.append) {
|
|
686
|
+
headers.append(name, value);
|
|
687
|
+
} else {
|
|
688
|
+
headers.set(name, value);
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
status = (status) => {
|
|
692
|
+
this.#status = status;
|
|
693
|
+
};
|
|
694
|
+
set = (key, value) => {
|
|
695
|
+
this.#var ??= /* @__PURE__ */ new Map;
|
|
696
|
+
this.#var.set(key, value);
|
|
697
|
+
};
|
|
698
|
+
get = (key) => {
|
|
699
|
+
return this.#var ? this.#var.get(key) : undefined;
|
|
700
|
+
};
|
|
701
|
+
get var() {
|
|
702
|
+
if (!this.#var) {
|
|
703
|
+
return {};
|
|
704
|
+
}
|
|
705
|
+
return Object.fromEntries(this.#var);
|
|
706
|
+
}
|
|
707
|
+
#newResponse(data, arg, headers) {
|
|
708
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
|
|
709
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
710
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
711
|
+
for (const [key, value] of argHeaders) {
|
|
712
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
713
|
+
responseHeaders.append(key, value);
|
|
714
|
+
} else {
|
|
715
|
+
responseHeaders.set(key, value);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
if (headers) {
|
|
720
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
721
|
+
if (typeof v === "string") {
|
|
722
|
+
responseHeaders.set(k, v);
|
|
723
|
+
} else {
|
|
724
|
+
responseHeaders.delete(k);
|
|
725
|
+
for (const v2 of v) {
|
|
726
|
+
responseHeaders.append(k, v2);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
732
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
733
|
+
}
|
|
734
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
735
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
736
|
+
text = (text, arg, headers) => {
|
|
737
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
738
|
+
};
|
|
739
|
+
json = (object, arg, headers) => {
|
|
740
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
741
|
+
};
|
|
742
|
+
html = (html, arg, headers) => {
|
|
743
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
744
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
745
|
+
};
|
|
746
|
+
redirect = (location, status) => {
|
|
747
|
+
const locationString = String(location);
|
|
748
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
749
|
+
return this.newResponse(null, status ?? 302);
|
|
750
|
+
};
|
|
751
|
+
notFound = () => {
|
|
752
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
753
|
+
return this.#notFoundHandler(this);
|
|
754
|
+
};
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
// ../../node_modules/hono/dist/router.js
|
|
758
|
+
var METHOD_NAME_ALL = "ALL";
|
|
759
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
760
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
761
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
762
|
+
var UnsupportedPathError = class extends Error {
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
// ../../node_modules/hono/dist/utils/constants.js
|
|
766
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
767
|
+
|
|
768
|
+
// ../../node_modules/hono/dist/hono-base.js
|
|
769
|
+
var notFoundHandler = (c) => {
|
|
770
|
+
return c.text("404 Not Found", 404);
|
|
771
|
+
};
|
|
772
|
+
var errorHandler = (err, c) => {
|
|
773
|
+
if ("getResponse" in err) {
|
|
774
|
+
const res = err.getResponse();
|
|
775
|
+
return c.newResponse(res.body, res);
|
|
776
|
+
}
|
|
777
|
+
console.error(err);
|
|
778
|
+
return c.text("Internal Server Error", 500);
|
|
779
|
+
};
|
|
780
|
+
var Hono = class _Hono {
|
|
781
|
+
get;
|
|
782
|
+
post;
|
|
783
|
+
put;
|
|
784
|
+
delete;
|
|
785
|
+
options;
|
|
786
|
+
patch;
|
|
787
|
+
all;
|
|
788
|
+
on;
|
|
789
|
+
use;
|
|
790
|
+
router;
|
|
791
|
+
getPath;
|
|
792
|
+
_basePath = "/";
|
|
793
|
+
#path = "/";
|
|
794
|
+
routes = [];
|
|
795
|
+
constructor(options = {}) {
|
|
796
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
797
|
+
allMethods.forEach((method) => {
|
|
798
|
+
this[method] = (args1, ...args) => {
|
|
799
|
+
if (typeof args1 === "string") {
|
|
800
|
+
this.#path = args1;
|
|
801
|
+
} else {
|
|
802
|
+
this.#addRoute(method, this.#path, args1);
|
|
803
|
+
}
|
|
804
|
+
args.forEach((handler) => {
|
|
805
|
+
this.#addRoute(method, this.#path, handler);
|
|
806
|
+
});
|
|
807
|
+
return this;
|
|
808
|
+
};
|
|
809
|
+
});
|
|
810
|
+
this.on = (method, path, ...handlers) => {
|
|
811
|
+
for (const p of [path].flat()) {
|
|
812
|
+
this.#path = p;
|
|
813
|
+
for (const m of [method].flat()) {
|
|
814
|
+
handlers.map((handler) => {
|
|
815
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return this;
|
|
820
|
+
};
|
|
821
|
+
this.use = (arg1, ...handlers) => {
|
|
822
|
+
if (typeof arg1 === "string") {
|
|
823
|
+
this.#path = arg1;
|
|
824
|
+
} else {
|
|
825
|
+
this.#path = "*";
|
|
826
|
+
handlers.unshift(arg1);
|
|
827
|
+
}
|
|
828
|
+
handlers.forEach((handler) => {
|
|
829
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
830
|
+
});
|
|
831
|
+
return this;
|
|
832
|
+
};
|
|
833
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
834
|
+
Object.assign(this, optionsWithoutStrict);
|
|
835
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
836
|
+
}
|
|
837
|
+
#clone() {
|
|
838
|
+
const clone = new _Hono({
|
|
839
|
+
router: this.router,
|
|
840
|
+
getPath: this.getPath
|
|
841
|
+
});
|
|
842
|
+
clone.errorHandler = this.errorHandler;
|
|
843
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
844
|
+
clone.routes = this.routes;
|
|
845
|
+
return clone;
|
|
846
|
+
}
|
|
847
|
+
#notFoundHandler = notFoundHandler;
|
|
848
|
+
errorHandler = errorHandler;
|
|
849
|
+
route(path, app) {
|
|
850
|
+
const subApp = this.basePath(path);
|
|
851
|
+
app.routes.map((r) => {
|
|
852
|
+
let handler;
|
|
853
|
+
if (app.errorHandler === errorHandler) {
|
|
854
|
+
handler = r.handler;
|
|
855
|
+
} else {
|
|
856
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
857
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
858
|
+
}
|
|
859
|
+
subApp.#addRoute(r.method, r.path, handler, r.basePath);
|
|
860
|
+
});
|
|
861
|
+
return this;
|
|
862
|
+
}
|
|
863
|
+
basePath(path) {
|
|
864
|
+
const subApp = this.#clone();
|
|
865
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
866
|
+
return subApp;
|
|
867
|
+
}
|
|
868
|
+
onError = (handler) => {
|
|
869
|
+
this.errorHandler = handler;
|
|
870
|
+
return this;
|
|
871
|
+
};
|
|
872
|
+
notFound = (handler) => {
|
|
873
|
+
this.#notFoundHandler = handler;
|
|
874
|
+
return this;
|
|
875
|
+
};
|
|
876
|
+
mount(path, applicationHandler, options) {
|
|
877
|
+
let replaceRequest;
|
|
878
|
+
let optionHandler;
|
|
879
|
+
if (options) {
|
|
880
|
+
if (typeof options === "function") {
|
|
881
|
+
optionHandler = options;
|
|
882
|
+
} else {
|
|
883
|
+
optionHandler = options.optionHandler;
|
|
884
|
+
if (options.replaceRequest === false) {
|
|
885
|
+
replaceRequest = (request) => request;
|
|
886
|
+
} else {
|
|
887
|
+
replaceRequest = options.replaceRequest;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
const getOptions = optionHandler ? (c) => {
|
|
892
|
+
const options2 = optionHandler(c);
|
|
893
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
894
|
+
} : (c) => {
|
|
895
|
+
let executionContext = undefined;
|
|
896
|
+
try {
|
|
897
|
+
executionContext = c.executionCtx;
|
|
898
|
+
} catch {}
|
|
899
|
+
return [c.env, executionContext];
|
|
900
|
+
};
|
|
901
|
+
replaceRequest ||= (() => {
|
|
902
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
903
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
904
|
+
return (request) => {
|
|
905
|
+
const url = new URL(request.url);
|
|
906
|
+
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
|
|
907
|
+
return new Request(url, request);
|
|
908
|
+
};
|
|
909
|
+
})();
|
|
910
|
+
const handler = async (c, next) => {
|
|
911
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
912
|
+
if (res) {
|
|
913
|
+
return res;
|
|
914
|
+
}
|
|
915
|
+
await next();
|
|
916
|
+
};
|
|
917
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
918
|
+
return this;
|
|
919
|
+
}
|
|
920
|
+
#addRoute(method, path, handler, baseRoutePath) {
|
|
921
|
+
method = method.toUpperCase();
|
|
922
|
+
path = mergePath(this._basePath, path);
|
|
923
|
+
const r = {
|
|
924
|
+
basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,
|
|
925
|
+
path,
|
|
926
|
+
method,
|
|
927
|
+
handler
|
|
928
|
+
};
|
|
929
|
+
this.router.add(method, path, [handler, r]);
|
|
930
|
+
this.routes.push(r);
|
|
931
|
+
}
|
|
932
|
+
#handleError(err, c) {
|
|
933
|
+
if (err instanceof Error) {
|
|
934
|
+
return this.errorHandler(err, c);
|
|
935
|
+
}
|
|
936
|
+
throw err;
|
|
937
|
+
}
|
|
938
|
+
#dispatch(request, executionCtx, env, method) {
|
|
939
|
+
if (method === "HEAD") {
|
|
940
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
941
|
+
}
|
|
942
|
+
const path = this.getPath(request, { env });
|
|
943
|
+
const matchResult = this.router.match(method, path);
|
|
944
|
+
const c = new Context(request, {
|
|
945
|
+
path,
|
|
946
|
+
matchResult,
|
|
947
|
+
env,
|
|
948
|
+
executionCtx,
|
|
949
|
+
notFoundHandler: this.#notFoundHandler
|
|
950
|
+
});
|
|
951
|
+
if (matchResult[0].length === 1) {
|
|
952
|
+
let res;
|
|
953
|
+
try {
|
|
954
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
955
|
+
c.res = await this.#notFoundHandler(c);
|
|
956
|
+
});
|
|
957
|
+
} catch (err) {
|
|
958
|
+
return this.#handleError(err, c);
|
|
959
|
+
}
|
|
960
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
961
|
+
}
|
|
962
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
963
|
+
return (async () => {
|
|
964
|
+
try {
|
|
965
|
+
const context = await composed(c);
|
|
966
|
+
if (!context.finalized) {
|
|
967
|
+
throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
968
|
+
}
|
|
969
|
+
return context.res;
|
|
970
|
+
} catch (err) {
|
|
971
|
+
return this.#handleError(err, c);
|
|
972
|
+
}
|
|
973
|
+
})();
|
|
974
|
+
}
|
|
975
|
+
fetch = (request, ...rest) => {
|
|
976
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
977
|
+
};
|
|
978
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
979
|
+
if (input instanceof Request) {
|
|
980
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
981
|
+
}
|
|
982
|
+
input = input.toString();
|
|
983
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
984
|
+
};
|
|
985
|
+
fire = () => {
|
|
986
|
+
addEventListener("fetch", (event) => {
|
|
987
|
+
event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
|
|
988
|
+
});
|
|
989
|
+
};
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
// ../../node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
993
|
+
var emptyParam = [];
|
|
994
|
+
function match(method, path) {
|
|
995
|
+
const matchers = this.buildAllMatchers();
|
|
996
|
+
const match2 = (method2, path2) => {
|
|
997
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
998
|
+
const staticMatch = matcher[2][path2];
|
|
999
|
+
if (staticMatch) {
|
|
1000
|
+
return staticMatch;
|
|
1001
|
+
}
|
|
1002
|
+
const match3 = path2.match(matcher[0]);
|
|
1003
|
+
if (!match3) {
|
|
1004
|
+
return [[], emptyParam];
|
|
1005
|
+
}
|
|
1006
|
+
const index = match3.indexOf("", 1);
|
|
1007
|
+
return [matcher[1][index], match3];
|
|
1008
|
+
};
|
|
1009
|
+
this.match = match2;
|
|
1010
|
+
return match2(method, path);
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
// ../../node_modules/hono/dist/router/reg-exp-router/node.js
|
|
1014
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
1015
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
1016
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
1017
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
1018
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
1019
|
+
function compareKey(a, b) {
|
|
1020
|
+
if (a.length === 1) {
|
|
1021
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
1022
|
+
}
|
|
1023
|
+
if (b.length === 1) {
|
|
1024
|
+
return 1;
|
|
1025
|
+
}
|
|
1026
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1027
|
+
return 1;
|
|
1028
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1029
|
+
return -1;
|
|
1030
|
+
}
|
|
1031
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
1032
|
+
return 1;
|
|
1033
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
1034
|
+
return -1;
|
|
1035
|
+
}
|
|
1036
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
1037
|
+
}
|
|
1038
|
+
var Node = class _Node {
|
|
1039
|
+
#index;
|
|
1040
|
+
#varIndex;
|
|
1041
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
1042
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
1043
|
+
if (tokens.length === 0) {
|
|
1044
|
+
if (this.#index !== undefined) {
|
|
1045
|
+
throw PATH_ERROR;
|
|
1046
|
+
}
|
|
1047
|
+
if (pathErrorCheckOnly) {
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
this.#index = index;
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const [token, ...restTokens] = tokens;
|
|
1054
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1055
|
+
let node;
|
|
1056
|
+
if (pattern) {
|
|
1057
|
+
const name = pattern[1];
|
|
1058
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
1059
|
+
if (name && pattern[2]) {
|
|
1060
|
+
if (regexpStr === ".*") {
|
|
1061
|
+
throw PATH_ERROR;
|
|
1062
|
+
}
|
|
1063
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
1064
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
1065
|
+
throw PATH_ERROR;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
node = this.#children[regexpStr];
|
|
1069
|
+
if (!node) {
|
|
1070
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1071
|
+
throw PATH_ERROR;
|
|
1072
|
+
}
|
|
1073
|
+
if (pathErrorCheckOnly) {
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
node = this.#children[regexpStr] = new _Node;
|
|
1077
|
+
if (name !== "") {
|
|
1078
|
+
node.#varIndex = context.varIndex++;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
1082
|
+
paramMap.push([name, node.#varIndex]);
|
|
1083
|
+
}
|
|
1084
|
+
} else {
|
|
1085
|
+
node = this.#children[token];
|
|
1086
|
+
if (!node) {
|
|
1087
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1088
|
+
throw PATH_ERROR;
|
|
1089
|
+
}
|
|
1090
|
+
if (pathErrorCheckOnly) {
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
node = this.#children[token] = new _Node;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
1097
|
+
}
|
|
1098
|
+
buildRegExpStr() {
|
|
1099
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
1100
|
+
const strList = childKeys.map((k) => {
|
|
1101
|
+
const c = this.#children[k];
|
|
1102
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
1103
|
+
});
|
|
1104
|
+
if (typeof this.#index === "number") {
|
|
1105
|
+
strList.unshift(`#${this.#index}`);
|
|
1106
|
+
}
|
|
1107
|
+
if (strList.length === 0) {
|
|
1108
|
+
return "";
|
|
1109
|
+
}
|
|
1110
|
+
if (strList.length === 1) {
|
|
1111
|
+
return strList[0];
|
|
1112
|
+
}
|
|
1113
|
+
return "(?:" + strList.join("|") + ")";
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
|
|
1117
|
+
// ../../node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
1118
|
+
var Trie = class {
|
|
1119
|
+
#context = { varIndex: 0 };
|
|
1120
|
+
#root = new Node;
|
|
1121
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
1122
|
+
const paramAssoc = [];
|
|
1123
|
+
const groups = [];
|
|
1124
|
+
for (let i = 0;; ) {
|
|
1125
|
+
let replaced = false;
|
|
1126
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
1127
|
+
const mark = `@\\${i}`;
|
|
1128
|
+
groups[i] = [mark, m];
|
|
1129
|
+
i++;
|
|
1130
|
+
replaced = true;
|
|
1131
|
+
return mark;
|
|
1132
|
+
});
|
|
1133
|
+
if (!replaced) {
|
|
1134
|
+
break;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
1138
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
1139
|
+
const [mark] = groups[i];
|
|
1140
|
+
for (let j = tokens.length - 1;j >= 0; j--) {
|
|
1141
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
1142
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
1143
|
+
break;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
1148
|
+
return paramAssoc;
|
|
1149
|
+
}
|
|
1150
|
+
buildRegExp() {
|
|
1151
|
+
let regexp = this.#root.buildRegExpStr();
|
|
1152
|
+
if (regexp === "") {
|
|
1153
|
+
return [/^$/, [], []];
|
|
1154
|
+
}
|
|
1155
|
+
let captureIndex = 0;
|
|
1156
|
+
const indexReplacementMap = [];
|
|
1157
|
+
const paramReplacementMap = [];
|
|
1158
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
1159
|
+
if (handlerIndex !== undefined) {
|
|
1160
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
1161
|
+
return "$()";
|
|
1162
|
+
}
|
|
1163
|
+
if (paramIndex !== undefined) {
|
|
1164
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
1165
|
+
return "";
|
|
1166
|
+
}
|
|
1167
|
+
return "";
|
|
1168
|
+
});
|
|
1169
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
|
|
1173
|
+
// ../../node_modules/hono/dist/router/reg-exp-router/router.js
|
|
1174
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
1175
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1176
|
+
function buildWildcardRegExp(path) {
|
|
1177
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
1178
|
+
}
|
|
1179
|
+
function clearWildcardRegExpCache() {
|
|
1180
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1181
|
+
}
|
|
1182
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
1183
|
+
const trie = new Trie;
|
|
1184
|
+
const handlerData = [];
|
|
1185
|
+
if (routes.length === 0) {
|
|
1186
|
+
return nullMatcher;
|
|
1187
|
+
}
|
|
1188
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
1189
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
1190
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
|
|
1191
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
1192
|
+
if (pathErrorCheckOnly) {
|
|
1193
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
1194
|
+
} else {
|
|
1195
|
+
j++;
|
|
1196
|
+
}
|
|
1197
|
+
let paramAssoc;
|
|
1198
|
+
try {
|
|
1199
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
1200
|
+
} catch (e) {
|
|
1201
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
1202
|
+
}
|
|
1203
|
+
if (pathErrorCheckOnly) {
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
1207
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
1208
|
+
paramCount -= 1;
|
|
1209
|
+
for (;paramCount >= 0; paramCount--) {
|
|
1210
|
+
const [key, value] = paramAssoc[paramCount];
|
|
1211
|
+
paramIndexMap[key] = value;
|
|
1212
|
+
}
|
|
1213
|
+
return [h, paramIndexMap];
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
1217
|
+
for (let i = 0, len = handlerData.length;i < len; i++) {
|
|
1218
|
+
for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
|
|
1219
|
+
const map = handlerData[i][j]?.[1];
|
|
1220
|
+
if (!map) {
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const keys = Object.keys(map);
|
|
1224
|
+
for (let k = 0, len3 = keys.length;k < len3; k++) {
|
|
1225
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const handlerMap = [];
|
|
1230
|
+
for (const i in indexReplacementMap) {
|
|
1231
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
1232
|
+
}
|
|
1233
|
+
return [regexp, handlerMap, staticMap];
|
|
1234
|
+
}
|
|
1235
|
+
function findMiddleware(middleware, path) {
|
|
1236
|
+
if (!middleware) {
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
1240
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
1241
|
+
return [...middleware[k]];
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
var RegExpRouter = class {
|
|
1247
|
+
name = "RegExpRouter";
|
|
1248
|
+
#middleware;
|
|
1249
|
+
#routes;
|
|
1250
|
+
constructor() {
|
|
1251
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1252
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1253
|
+
}
|
|
1254
|
+
add(method, path, handler) {
|
|
1255
|
+
const middleware = this.#middleware;
|
|
1256
|
+
const routes = this.#routes;
|
|
1257
|
+
if (!middleware || !routes) {
|
|
1258
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1259
|
+
}
|
|
1260
|
+
if (!middleware[method]) {
|
|
1261
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
1262
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
1263
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
1264
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
1265
|
+
});
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
if (path === "/*") {
|
|
1269
|
+
path = "*";
|
|
1270
|
+
}
|
|
1271
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
1272
|
+
if (/\*$/.test(path)) {
|
|
1273
|
+
const re = buildWildcardRegExp(path);
|
|
1274
|
+
if (method === METHOD_NAME_ALL) {
|
|
1275
|
+
Object.keys(middleware).forEach((m) => {
|
|
1276
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1277
|
+
});
|
|
1278
|
+
} else {
|
|
1279
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1280
|
+
}
|
|
1281
|
+
Object.keys(middleware).forEach((m) => {
|
|
1282
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1283
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
1284
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
});
|
|
1288
|
+
Object.keys(routes).forEach((m) => {
|
|
1289
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1290
|
+
Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
1291
|
+
}
|
|
1292
|
+
});
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
1296
|
+
for (let i = 0, len = paths.length;i < len; i++) {
|
|
1297
|
+
const path2 = paths[i];
|
|
1298
|
+
Object.keys(routes).forEach((m) => {
|
|
1299
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1300
|
+
routes[m][path2] ||= [
|
|
1301
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
1302
|
+
];
|
|
1303
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
1304
|
+
}
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
match = match;
|
|
1309
|
+
buildAllMatchers() {
|
|
1310
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
1311
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
1312
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
1313
|
+
});
|
|
1314
|
+
this.#middleware = this.#routes = undefined;
|
|
1315
|
+
clearWildcardRegExpCache();
|
|
1316
|
+
return matchers;
|
|
1317
|
+
}
|
|
1318
|
+
#buildMatcher(method) {
|
|
1319
|
+
const routes = [];
|
|
1320
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
1321
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
1322
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
1323
|
+
if (ownRoute.length !== 0) {
|
|
1324
|
+
hasOwnRoute ||= true;
|
|
1325
|
+
routes.push(...ownRoute);
|
|
1326
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
1327
|
+
routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
if (!hasOwnRoute) {
|
|
1331
|
+
return null;
|
|
1332
|
+
} else {
|
|
1333
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
};
|
|
1337
|
+
|
|
1338
|
+
// ../../node_modules/hono/dist/router/reg-exp-router/prepared-router.js
|
|
1339
|
+
var PreparedRegExpRouter = class {
|
|
1340
|
+
name = "PreparedRegExpRouter";
|
|
1341
|
+
#matchers;
|
|
1342
|
+
#relocateMap;
|
|
1343
|
+
constructor(matchers, relocateMap) {
|
|
1344
|
+
this.#matchers = matchers;
|
|
1345
|
+
this.#relocateMap = relocateMap;
|
|
1346
|
+
}
|
|
1347
|
+
#addWildcard(method, handlerData) {
|
|
1348
|
+
const matcher = this.#matchers[method];
|
|
1349
|
+
matcher[1].forEach((list) => list && list.push(handlerData));
|
|
1350
|
+
Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
|
|
1351
|
+
}
|
|
1352
|
+
#addPath(method, path, handler, indexes, map) {
|
|
1353
|
+
const matcher = this.#matchers[method];
|
|
1354
|
+
if (!map) {
|
|
1355
|
+
matcher[2][path][0].push([handler, {}]);
|
|
1356
|
+
} else {
|
|
1357
|
+
indexes.forEach((index) => {
|
|
1358
|
+
if (typeof index === "number") {
|
|
1359
|
+
matcher[1][index].push([handler, map]);
|
|
1360
|
+
} else {
|
|
1361
|
+
matcher[2][index || path][0].push([handler, map]);
|
|
1362
|
+
}
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
add(method, path, handler) {
|
|
1367
|
+
if (!this.#matchers[method]) {
|
|
1368
|
+
const all = this.#matchers[METHOD_NAME_ALL];
|
|
1369
|
+
const staticMap = {};
|
|
1370
|
+
for (const key in all[2]) {
|
|
1371
|
+
staticMap[key] = [all[2][key][0].slice(), emptyParam];
|
|
1372
|
+
}
|
|
1373
|
+
this.#matchers[method] = [
|
|
1374
|
+
all[0],
|
|
1375
|
+
all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
|
|
1376
|
+
staticMap
|
|
1377
|
+
];
|
|
1378
|
+
}
|
|
1379
|
+
if (path === "/*" || path === "*") {
|
|
1380
|
+
const handlerData = [handler, {}];
|
|
1381
|
+
if (method === METHOD_NAME_ALL) {
|
|
1382
|
+
for (const m in this.#matchers) {
|
|
1383
|
+
this.#addWildcard(m, handlerData);
|
|
1384
|
+
}
|
|
1385
|
+
} else {
|
|
1386
|
+
this.#addWildcard(method, handlerData);
|
|
1387
|
+
}
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
const data = this.#relocateMap[path];
|
|
1391
|
+
if (!data) {
|
|
1392
|
+
throw new Error(`Path ${path} is not registered`);
|
|
1393
|
+
}
|
|
1394
|
+
for (const [indexes, map] of data) {
|
|
1395
|
+
if (method === METHOD_NAME_ALL) {
|
|
1396
|
+
for (const m in this.#matchers) {
|
|
1397
|
+
this.#addPath(m, path, handler, indexes, map);
|
|
1398
|
+
}
|
|
1399
|
+
} else {
|
|
1400
|
+
this.#addPath(method, path, handler, indexes, map);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
buildAllMatchers() {
|
|
1405
|
+
return this.#matchers;
|
|
1406
|
+
}
|
|
1407
|
+
match = match;
|
|
1408
|
+
};
|
|
1409
|
+
|
|
1410
|
+
// ../../node_modules/hono/dist/router/smart-router/router.js
|
|
1411
|
+
var SmartRouter = class {
|
|
1412
|
+
name = "SmartRouter";
|
|
1413
|
+
#routers = [];
|
|
1414
|
+
#routes = [];
|
|
1415
|
+
constructor(init) {
|
|
1416
|
+
this.#routers = init.routers;
|
|
1417
|
+
}
|
|
1418
|
+
add(method, path, handler) {
|
|
1419
|
+
if (!this.#routes) {
|
|
1420
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1421
|
+
}
|
|
1422
|
+
this.#routes.push([method, path, handler]);
|
|
1423
|
+
}
|
|
1424
|
+
match(method, path) {
|
|
1425
|
+
if (!this.#routes) {
|
|
1426
|
+
throw new Error("Fatal error");
|
|
1427
|
+
}
|
|
1428
|
+
const routers = this.#routers;
|
|
1429
|
+
const routes = this.#routes;
|
|
1430
|
+
const len = routers.length;
|
|
1431
|
+
let i = 0;
|
|
1432
|
+
let res;
|
|
1433
|
+
for (;i < len; i++) {
|
|
1434
|
+
const router = routers[i];
|
|
1435
|
+
try {
|
|
1436
|
+
for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
|
|
1437
|
+
router.add(...routes[i2]);
|
|
1438
|
+
}
|
|
1439
|
+
res = router.match(method, path);
|
|
1440
|
+
} catch (e) {
|
|
1441
|
+
if (e instanceof UnsupportedPathError) {
|
|
1442
|
+
continue;
|
|
1443
|
+
}
|
|
1444
|
+
throw e;
|
|
1445
|
+
}
|
|
1446
|
+
this.match = router.match.bind(router);
|
|
1447
|
+
this.#routers = [router];
|
|
1448
|
+
this.#routes = undefined;
|
|
1449
|
+
break;
|
|
1450
|
+
}
|
|
1451
|
+
if (i === len) {
|
|
1452
|
+
throw new Error("Fatal error");
|
|
1453
|
+
}
|
|
1454
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
1455
|
+
return res;
|
|
1456
|
+
}
|
|
1457
|
+
get activeRouter() {
|
|
1458
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
1459
|
+
throw new Error("No active router has been determined yet.");
|
|
1460
|
+
}
|
|
1461
|
+
return this.#routers[0];
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
1464
|
+
|
|
1465
|
+
// ../../node_modules/hono/dist/router/trie-router/node.js
|
|
1466
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
1467
|
+
var hasChildren = (children) => {
|
|
1468
|
+
for (const _ in children) {
|
|
1469
|
+
return true;
|
|
1470
|
+
}
|
|
1471
|
+
return false;
|
|
1472
|
+
};
|
|
1473
|
+
var Node2 = class _Node2 {
|
|
1474
|
+
#methods;
|
|
1475
|
+
#children;
|
|
1476
|
+
#patterns;
|
|
1477
|
+
#order = 0;
|
|
1478
|
+
#params = emptyParams;
|
|
1479
|
+
constructor(method, handler, children) {
|
|
1480
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
1481
|
+
this.#methods = [];
|
|
1482
|
+
if (method && handler) {
|
|
1483
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
1484
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
1485
|
+
this.#methods = [m];
|
|
1486
|
+
}
|
|
1487
|
+
this.#patterns = [];
|
|
1488
|
+
}
|
|
1489
|
+
insert(method, path, handler) {
|
|
1490
|
+
this.#order = ++this.#order;
|
|
1491
|
+
let curNode = this;
|
|
1492
|
+
const parts = splitRoutingPath(path);
|
|
1493
|
+
const possibleKeys = [];
|
|
1494
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
1495
|
+
const p = parts[i];
|
|
1496
|
+
const nextP = parts[i + 1];
|
|
1497
|
+
const pattern = getPattern(p, nextP);
|
|
1498
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
1499
|
+
if (key in curNode.#children) {
|
|
1500
|
+
curNode = curNode.#children[key];
|
|
1501
|
+
if (pattern) {
|
|
1502
|
+
possibleKeys.push(pattern[1]);
|
|
1503
|
+
}
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
1506
|
+
curNode.#children[key] = new _Node2;
|
|
1507
|
+
if (pattern) {
|
|
1508
|
+
curNode.#patterns.push(pattern);
|
|
1509
|
+
possibleKeys.push(pattern[1]);
|
|
1510
|
+
}
|
|
1511
|
+
curNode = curNode.#children[key];
|
|
1512
|
+
}
|
|
1513
|
+
curNode.#methods.push({
|
|
1514
|
+
[method]: {
|
|
1515
|
+
handler,
|
|
1516
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
1517
|
+
score: this.#order
|
|
1518
|
+
}
|
|
1519
|
+
});
|
|
1520
|
+
return curNode;
|
|
1521
|
+
}
|
|
1522
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
1523
|
+
for (let i = 0, len = node.#methods.length;i < len; i++) {
|
|
1524
|
+
const m = node.#methods[i];
|
|
1525
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
1526
|
+
const processedSet = {};
|
|
1527
|
+
if (handlerSet !== undefined) {
|
|
1528
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
1529
|
+
handlerSets.push(handlerSet);
|
|
1530
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
1531
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
|
|
1532
|
+
const key = handlerSet.possibleKeys[i2];
|
|
1533
|
+
const processed = processedSet[handlerSet.score];
|
|
1534
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
1535
|
+
processedSet[handlerSet.score] = true;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
search(method, path) {
|
|
1542
|
+
const handlerSets = [];
|
|
1543
|
+
this.#params = emptyParams;
|
|
1544
|
+
const curNode = this;
|
|
1545
|
+
let curNodes = [curNode];
|
|
1546
|
+
const parts = splitPath(path);
|
|
1547
|
+
const curNodesQueue = [];
|
|
1548
|
+
const len = parts.length;
|
|
1549
|
+
let partOffsets = null;
|
|
1550
|
+
for (let i = 0;i < len; i++) {
|
|
1551
|
+
const part = parts[i];
|
|
1552
|
+
const isLast = i === len - 1;
|
|
1553
|
+
const tempNodes = [];
|
|
1554
|
+
for (let j = 0, len2 = curNodes.length;j < len2; j++) {
|
|
1555
|
+
const node = curNodes[j];
|
|
1556
|
+
const nextNode = node.#children[part];
|
|
1557
|
+
if (nextNode) {
|
|
1558
|
+
nextNode.#params = node.#params;
|
|
1559
|
+
if (isLast) {
|
|
1560
|
+
if (nextNode.#children["*"]) {
|
|
1561
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
1562
|
+
}
|
|
1563
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
1564
|
+
} else {
|
|
1565
|
+
tempNodes.push(nextNode);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
|
|
1569
|
+
const pattern = node.#patterns[k];
|
|
1570
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
1571
|
+
if (pattern === "*") {
|
|
1572
|
+
const astNode = node.#children["*"];
|
|
1573
|
+
if (astNode) {
|
|
1574
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
1575
|
+
astNode.#params = params;
|
|
1576
|
+
tempNodes.push(astNode);
|
|
1577
|
+
}
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
const [key, name, matcher] = pattern;
|
|
1581
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
1582
|
+
continue;
|
|
1583
|
+
}
|
|
1584
|
+
const child = node.#children[key];
|
|
1585
|
+
if (matcher instanceof RegExp) {
|
|
1586
|
+
if (partOffsets === null) {
|
|
1587
|
+
partOffsets = new Array(len);
|
|
1588
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
1589
|
+
for (let p = 0;p < len; p++) {
|
|
1590
|
+
partOffsets[p] = offset;
|
|
1591
|
+
offset += parts[p].length + 1;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
1595
|
+
const m = matcher.exec(restPathString);
|
|
1596
|
+
if (m) {
|
|
1597
|
+
params[name] = m[0];
|
|
1598
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
1599
|
+
if (hasChildren(child.#children)) {
|
|
1600
|
+
child.#params = params;
|
|
1601
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
1602
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
1603
|
+
targetCurNodes.push(child);
|
|
1604
|
+
}
|
|
1605
|
+
continue;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
if (matcher === true || matcher.test(part)) {
|
|
1609
|
+
params[name] = part;
|
|
1610
|
+
if (isLast) {
|
|
1611
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
1612
|
+
if (child.#children["*"]) {
|
|
1613
|
+
this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
|
|
1614
|
+
}
|
|
1615
|
+
} else {
|
|
1616
|
+
child.#params = params;
|
|
1617
|
+
tempNodes.push(child);
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
const shifted = curNodesQueue.shift();
|
|
1623
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
1624
|
+
}
|
|
1625
|
+
if (handlerSets.length > 1) {
|
|
1626
|
+
handlerSets.sort((a, b) => {
|
|
1627
|
+
return a.score - b.score;
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
|
|
1634
|
+
// ../../node_modules/hono/dist/router/trie-router/router.js
|
|
1635
|
+
var TrieRouter = class {
|
|
1636
|
+
name = "TrieRouter";
|
|
1637
|
+
#node;
|
|
1638
|
+
constructor() {
|
|
1639
|
+
this.#node = new Node2;
|
|
1640
|
+
}
|
|
1641
|
+
add(method, path, handler) {
|
|
1642
|
+
const results = checkOptionalParameter(path);
|
|
1643
|
+
if (results) {
|
|
1644
|
+
for (let i = 0, len = results.length;i < len; i++) {
|
|
1645
|
+
this.#node.insert(method, results[i], handler);
|
|
1646
|
+
}
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
this.#node.insert(method, path, handler);
|
|
1650
|
+
}
|
|
1651
|
+
match(method, path) {
|
|
1652
|
+
return this.#node.search(method, path);
|
|
1653
|
+
}
|
|
1654
|
+
};
|
|
1655
|
+
|
|
1656
|
+
// ../../node_modules/hono/dist/hono.js
|
|
1657
|
+
var Hono2 = class extends Hono {
|
|
1658
|
+
constructor(options = {}) {
|
|
1659
|
+
super(options);
|
|
1660
|
+
this.router = options.router ?? new SmartRouter({
|
|
1661
|
+
routers: [new RegExpRouter, new TrieRouter]
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
};
|
|
1665
|
+
|
|
1666
|
+
// src/pkce.ts
|
|
1667
|
+
async function verifyPkce(codeVerifier, storedCodeChallenge) {
|
|
1668
|
+
const encoder = new TextEncoder;
|
|
1669
|
+
const data = encoder.encode(codeVerifier);
|
|
1670
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
1671
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
1672
|
+
let binary = "";
|
|
1673
|
+
for (const byte of hashArray) {
|
|
1674
|
+
binary += String.fromCharCode(byte);
|
|
1675
|
+
}
|
|
1676
|
+
const computedChallenge = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1677
|
+
return computedChallenge === storedCodeChallenge;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// src/routes/auth.ts
|
|
1681
|
+
var authRoutes = new Hono2;
|
|
1682
|
+
authRoutes.post("/register", async (c) => {
|
|
1683
|
+
const body = await c.req.json();
|
|
1684
|
+
if (!body.username || !body.password || !body.telegramBotToken) {
|
|
1685
|
+
return c.json({ error: "username, password, and telegramBotToken are all required" }, 400);
|
|
1686
|
+
}
|
|
1687
|
+
try {
|
|
1688
|
+
const user = await createUser(body.username, body.password);
|
|
1689
|
+
setTelegramBotToken(user.id, body.telegramBotToken);
|
|
1690
|
+
return c.json({ id: user.id, username: user.username }, 201);
|
|
1691
|
+
} catch (err) {
|
|
1692
|
+
const message = err instanceof Error ? err.message : "Registration failed";
|
|
1693
|
+
return c.json({ error: message }, 400);
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
authRoutes.get("/authorize", (c) => {
|
|
1697
|
+
const redirectUri = c.req.query("redirect_uri") ?? "";
|
|
1698
|
+
const codeChallenge = c.req.query("code_challenge") ?? "";
|
|
1699
|
+
const state = c.req.query("state") ?? "";
|
|
1700
|
+
const clientId = c.req.query("client_id") ?? "";
|
|
1701
|
+
if (!redirectUri || !codeChallenge) {
|
|
1702
|
+
return c.text("Missing redirect_uri or code_challenge", 400);
|
|
1703
|
+
}
|
|
1704
|
+
return c.html(`
|
|
1705
|
+
<html>
|
|
1706
|
+
<body>
|
|
1707
|
+
<h2>Sign in to sendkit</h2>
|
|
1708
|
+
<form method="POST" action="/authorize">
|
|
1709
|
+
<input type="hidden" name="redirect_uri" value="${redirectUri}" />
|
|
1710
|
+
<input type="hidden" name="code_challenge" value="${codeChallenge}" />
|
|
1711
|
+
<input type="hidden" name="state" value="${state}" />
|
|
1712
|
+
<input type="hidden" name="client_id" value="${clientId}" />
|
|
1713
|
+
<input type="text" name="username" placeholder="Username" required /><br/>
|
|
1714
|
+
<input type="password" name="password" placeholder="Password" required /><br/>
|
|
1715
|
+
<button type="submit">Log in</button>
|
|
1716
|
+
</form>
|
|
1717
|
+
</body>
|
|
1718
|
+
</html>
|
|
1719
|
+
`);
|
|
1720
|
+
});
|
|
1721
|
+
authRoutes.post("/authorize", async (c) => {
|
|
1722
|
+
const form = await c.req.parseBody();
|
|
1723
|
+
const username = String(form.username ?? "");
|
|
1724
|
+
const password = String(form.password ?? "");
|
|
1725
|
+
const redirectUri = String(form.redirect_uri ?? "");
|
|
1726
|
+
const codeChallenge = String(form.code_challenge ?? "");
|
|
1727
|
+
const state = String(form.state ?? "");
|
|
1728
|
+
const user = await verifyUser(username, password);
|
|
1729
|
+
if (!user) {
|
|
1730
|
+
return c.text("Invalid username or password", 401);
|
|
1731
|
+
}
|
|
1732
|
+
const code = createAuthorizationCode({
|
|
1733
|
+
userId: user.id,
|
|
1734
|
+
codeChallenge,
|
|
1735
|
+
redirectUri
|
|
1736
|
+
});
|
|
1737
|
+
const redirectUrl = new URL(redirectUri);
|
|
1738
|
+
redirectUrl.searchParams.set("code", code);
|
|
1739
|
+
redirectUrl.searchParams.set("state", state);
|
|
1740
|
+
return c.redirect(redirectUrl.toString());
|
|
1741
|
+
});
|
|
1742
|
+
authRoutes.post("/token", async (c) => {
|
|
1743
|
+
const body = await c.req.json();
|
|
1744
|
+
if (!body.code || !body.code_verifier) {
|
|
1745
|
+
return c.json({ error: "code and code_verifier are required" }, 400);
|
|
1746
|
+
}
|
|
1747
|
+
const stored = consumeAuthorizationCode(body.code);
|
|
1748
|
+
if (!stored) {
|
|
1749
|
+
return c.json({ error: "Invalid, expired, or already-used code" }, 400);
|
|
1750
|
+
}
|
|
1751
|
+
const pkceValid = await verifyPkce(body.code_verifier, stored.codeChallenge);
|
|
1752
|
+
if (!pkceValid) {
|
|
1753
|
+
return c.json({ error: "PKCE verification failed" }, 400);
|
|
1754
|
+
}
|
|
1755
|
+
const { token, expiresIn } = createAccessToken(stored.userId);
|
|
1756
|
+
return c.json({
|
|
1757
|
+
access_token: token,
|
|
1758
|
+
token_type: "Bearer",
|
|
1759
|
+
expires_in: expiresIn
|
|
1760
|
+
});
|
|
1761
|
+
});
|
|
1762
|
+
export {
|
|
1763
|
+
authRoutes
|
|
1764
|
+
};
|