@yaop/obsidian-r2-sync 0.0.1 → 0.1.1

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.
Files changed (45) hide show
  1. package/README.md +109 -1
  2. package/dist/commands/add-device.d.ts +3 -0
  3. package/dist/commands/add-device.d.ts.map +1 -0
  4. package/dist/commands/add-device.js +26 -0
  5. package/dist/commands/add-device.js.map +1 -0
  6. package/dist/commands/deploy.d.ts +3 -0
  7. package/dist/commands/deploy.d.ts.map +1 -0
  8. package/dist/commands/deploy.js +75 -0
  9. package/dist/commands/deploy.js.map +1 -0
  10. package/dist/commands/rotate-secret.d.ts +3 -0
  11. package/dist/commands/rotate-secret.d.ts.map +1 -0
  12. package/dist/commands/rotate-secret.js +58 -0
  13. package/dist/commands/rotate-secret.js.map +1 -0
  14. package/dist/commands/setup.d.ts +3 -0
  15. package/dist/commands/setup.d.ts.map +1 -0
  16. package/dist/commands/setup.js +111 -0
  17. package/dist/commands/setup.js.map +1 -0
  18. package/dist/commands/status.d.ts +3 -0
  19. package/dist/commands/status.d.ts.map +1 -0
  20. package/dist/commands/status.js +35 -0
  21. package/dist/commands/status.js.map +1 -0
  22. package/dist/commands/teardown.d.ts +3 -0
  23. package/dist/commands/teardown.d.ts.map +1 -0
  24. package/dist/commands/teardown.js +59 -0
  25. package/dist/commands/teardown.js.map +1 -0
  26. package/dist/index.d.ts +3 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +26 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/lib/cloudflare.d.ts +81 -0
  31. package/dist/lib/cloudflare.d.ts.map +1 -0
  32. package/dist/lib/cloudflare.js +245 -0
  33. package/dist/lib/cloudflare.js.map +1 -0
  34. package/dist/lib/config.d.ts +23 -0
  35. package/dist/lib/config.d.ts.map +1 -0
  36. package/dist/lib/config.js +30 -0
  37. package/dist/lib/config.js.map +1 -0
  38. package/dist/lib/prompts.d.ts +10 -0
  39. package/dist/lib/prompts.d.ts.map +1 -0
  40. package/dist/lib/prompts.js +80 -0
  41. package/dist/lib/prompts.js.map +1 -0
  42. package/dist/worker/README.md +1 -0
  43. package/dist/worker/index.js +2640 -0
  44. package/dist/worker/index.js.map +8 -0
  45. package/package.json +27 -1
@@ -0,0 +1,2640 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/compose.js
5
+ var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => {
6
+ return (context, next) => {
7
+ let index = -1;
8
+ return dispatch(0);
9
+ async function dispatch(i) {
10
+ if (i <= index) {
11
+ throw new Error("next() called multiple times");
12
+ }
13
+ index = i;
14
+ let res;
15
+ let isError = false;
16
+ let handler;
17
+ if (middleware[i]) {
18
+ handler = middleware[i][0][0];
19
+ context.req.routeIndex = i;
20
+ } else {
21
+ handler = i === middleware.length && next || void 0;
22
+ }
23
+ if (handler) {
24
+ try {
25
+ res = await handler(context, () => dispatch(i + 1));
26
+ } catch (err) {
27
+ if (err instanceof Error && onError) {
28
+ context.error = err;
29
+ res = await onError(err, context);
30
+ isError = true;
31
+ } else {
32
+ throw err;
33
+ }
34
+ }
35
+ } else {
36
+ if (context.finalized === false && onNotFound) {
37
+ res = await onNotFound(context);
38
+ }
39
+ }
40
+ if (res && (context.finalized === false || isError)) {
41
+ context.res = res;
42
+ }
43
+ return context;
44
+ }
45
+ __name(dispatch, "dispatch");
46
+ };
47
+ }, "compose");
48
+
49
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/request/constants.js
50
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
51
+
52
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/utils/body.js
53
+ var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => {
54
+ const { all = false, dot = false } = options;
55
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
56
+ const contentType = headers.get("Content-Type");
57
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
58
+ return parseFormData(request, { all, dot });
59
+ }
60
+ return {};
61
+ }, "parseBody");
62
+ async function parseFormData(request, options) {
63
+ const formData = await request.formData();
64
+ if (formData) {
65
+ return convertFormDataToBodyData(formData, options);
66
+ }
67
+ return {};
68
+ }
69
+ __name(parseFormData, "parseFormData");
70
+ function convertFormDataToBodyData(formData, options) {
71
+ const form = /* @__PURE__ */ Object.create(null);
72
+ formData.forEach((value, key) => {
73
+ const shouldParseAllValues = options.all || key.endsWith("[]");
74
+ if (!shouldParseAllValues) {
75
+ form[key] = value;
76
+ } else {
77
+ handleParsingAllValues(form, key, value);
78
+ }
79
+ });
80
+ if (options.dot) {
81
+ Object.entries(form).forEach(([key, value]) => {
82
+ const shouldParseDotValues = key.includes(".");
83
+ if (shouldParseDotValues) {
84
+ handleParsingNestedValues(form, key, value);
85
+ delete form[key];
86
+ }
87
+ });
88
+ }
89
+ return form;
90
+ }
91
+ __name(convertFormDataToBodyData, "convertFormDataToBodyData");
92
+ var handleParsingAllValues = /* @__PURE__ */ __name((form, key, value) => {
93
+ if (form[key] !== void 0) {
94
+ if (Array.isArray(form[key])) {
95
+ ;
96
+ form[key].push(value);
97
+ } else {
98
+ form[key] = [form[key], value];
99
+ }
100
+ } else {
101
+ if (!key.endsWith("[]")) {
102
+ form[key] = value;
103
+ } else {
104
+ form[key] = [value];
105
+ }
106
+ }
107
+ }, "handleParsingAllValues");
108
+ var handleParsingNestedValues = /* @__PURE__ */ __name((form, key, value) => {
109
+ let nestedForm = form;
110
+ const keys = key.split(".");
111
+ keys.forEach((key2, index) => {
112
+ if (index === keys.length - 1) {
113
+ nestedForm[key2] = value;
114
+ } else {
115
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
116
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
117
+ }
118
+ nestedForm = nestedForm[key2];
119
+ }
120
+ });
121
+ }, "handleParsingNestedValues");
122
+
123
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/utils/url.js
124
+ var splitPath = /* @__PURE__ */ __name((path) => {
125
+ const paths = path.split("/");
126
+ if (paths[0] === "") {
127
+ paths.shift();
128
+ }
129
+ return paths;
130
+ }, "splitPath");
131
+ var splitRoutingPath = /* @__PURE__ */ __name((routePath) => {
132
+ const { groups, path } = extractGroupsFromPath(routePath);
133
+ const paths = splitPath(path);
134
+ return replaceGroupMarks(paths, groups);
135
+ }, "splitRoutingPath");
136
+ var extractGroupsFromPath = /* @__PURE__ */ __name((path) => {
137
+ const groups = [];
138
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
139
+ const mark = `@${index}`;
140
+ groups.push([mark, match2]);
141
+ return mark;
142
+ });
143
+ return { groups, path };
144
+ }, "extractGroupsFromPath");
145
+ var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => {
146
+ for (let i = groups.length - 1; i >= 0; i--) {
147
+ const [mark] = groups[i];
148
+ for (let j = paths.length - 1; j >= 0; j--) {
149
+ if (paths[j].includes(mark)) {
150
+ paths[j] = paths[j].replace(mark, groups[i][1]);
151
+ break;
152
+ }
153
+ }
154
+ }
155
+ return paths;
156
+ }, "replaceGroupMarks");
157
+ var patternCache = {};
158
+ var getPattern = /* @__PURE__ */ __name((label, next) => {
159
+ if (label === "*") {
160
+ return "*";
161
+ }
162
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
163
+ if (match2) {
164
+ const cacheKey = `${label}#${next}`;
165
+ if (!patternCache[cacheKey]) {
166
+ if (match2[2]) {
167
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
168
+ } else {
169
+ patternCache[cacheKey] = [label, match2[1], true];
170
+ }
171
+ }
172
+ return patternCache[cacheKey];
173
+ }
174
+ return null;
175
+ }, "getPattern");
176
+ var tryDecode = /* @__PURE__ */ __name((str, decoder) => {
177
+ try {
178
+ return decoder(str);
179
+ } catch {
180
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
181
+ try {
182
+ return decoder(match2);
183
+ } catch {
184
+ return match2;
185
+ }
186
+ });
187
+ }
188
+ }, "tryDecode");
189
+ var tryDecodeURI = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURI), "tryDecodeURI");
190
+ var getPath = /* @__PURE__ */ __name((request) => {
191
+ const url = request.url;
192
+ const start = url.indexOf("/", url.indexOf(":") + 4);
193
+ let i = start;
194
+ for (; i < url.length; i++) {
195
+ const charCode = url.charCodeAt(i);
196
+ if (charCode === 37) {
197
+ const queryIndex = url.indexOf("?", i);
198
+ const hashIndex = url.indexOf("#", i);
199
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
200
+ const path = url.slice(start, end);
201
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
202
+ } else if (charCode === 63 || charCode === 35) {
203
+ break;
204
+ }
205
+ }
206
+ return url.slice(start, i);
207
+ }, "getPath");
208
+ var getPathNoStrict = /* @__PURE__ */ __name((request) => {
209
+ const result = getPath(request);
210
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
211
+ }, "getPathNoStrict");
212
+ var mergePath = /* @__PURE__ */ __name((base, sub, ...rest) => {
213
+ if (rest.length) {
214
+ sub = mergePath(sub, ...rest);
215
+ }
216
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
217
+ }, "mergePath");
218
+ var checkOptionalParameter = /* @__PURE__ */ __name((path) => {
219
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
220
+ return null;
221
+ }
222
+ const segments = path.split("/");
223
+ const results = [];
224
+ let basePath = "";
225
+ segments.forEach((segment) => {
226
+ if (segment !== "" && !/\:/.test(segment)) {
227
+ basePath += "/" + segment;
228
+ } else if (/\:/.test(segment)) {
229
+ if (/\?/.test(segment)) {
230
+ if (results.length === 0 && basePath === "") {
231
+ results.push("/");
232
+ } else {
233
+ results.push(basePath);
234
+ }
235
+ const optionalSegment = segment.replace("?", "");
236
+ basePath += "/" + optionalSegment;
237
+ results.push(basePath);
238
+ } else {
239
+ basePath += "/" + segment;
240
+ }
241
+ }
242
+ });
243
+ return results.filter((v, i, a) => a.indexOf(v) === i);
244
+ }, "checkOptionalParameter");
245
+ var _decodeURI = /* @__PURE__ */ __name((value) => {
246
+ if (!/[%+]/.test(value)) {
247
+ return value;
248
+ }
249
+ if (value.indexOf("+") !== -1) {
250
+ value = value.replace(/\+/g, " ");
251
+ }
252
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
253
+ }, "_decodeURI");
254
+ var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => {
255
+ let encoded;
256
+ if (!multiple && key && !/[%+]/.test(key)) {
257
+ let keyIndex2 = url.indexOf("?", 8);
258
+ if (keyIndex2 === -1) {
259
+ return void 0;
260
+ }
261
+ if (!url.startsWith(key, keyIndex2 + 1)) {
262
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
263
+ }
264
+ while (keyIndex2 !== -1) {
265
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
266
+ if (trailingKeyCode === 61) {
267
+ const valueIndex = keyIndex2 + key.length + 2;
268
+ const endIndex = url.indexOf("&", valueIndex);
269
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
270
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
271
+ return "";
272
+ }
273
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
274
+ }
275
+ encoded = /[%+]/.test(url);
276
+ if (!encoded) {
277
+ return void 0;
278
+ }
279
+ }
280
+ const results = {};
281
+ encoded ??= /[%+]/.test(url);
282
+ let keyIndex = url.indexOf("?", 8);
283
+ while (keyIndex !== -1) {
284
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
285
+ let valueIndex = url.indexOf("=", keyIndex);
286
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
287
+ valueIndex = -1;
288
+ }
289
+ let name = url.slice(
290
+ keyIndex + 1,
291
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
292
+ );
293
+ if (encoded) {
294
+ name = _decodeURI(name);
295
+ }
296
+ keyIndex = nextKeyIndex;
297
+ if (name === "") {
298
+ continue;
299
+ }
300
+ let value;
301
+ if (valueIndex === -1) {
302
+ value = "";
303
+ } else {
304
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
305
+ if (encoded) {
306
+ value = _decodeURI(value);
307
+ }
308
+ }
309
+ if (multiple) {
310
+ if (!(results[name] && Array.isArray(results[name]))) {
311
+ results[name] = [];
312
+ }
313
+ ;
314
+ results[name].push(value);
315
+ } else {
316
+ results[name] ??= value;
317
+ }
318
+ }
319
+ return key ? results[key] : results;
320
+ }, "_getQueryParam");
321
+ var getQueryParam = _getQueryParam;
322
+ var getQueryParams = /* @__PURE__ */ __name((url, key) => {
323
+ return _getQueryParam(url, key, true);
324
+ }, "getQueryParams");
325
+ var decodeURIComponent_ = decodeURIComponent;
326
+
327
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/request.js
328
+ var tryDecodeURIComponent = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURIComponent_), "tryDecodeURIComponent");
329
+ var HonoRequest = /* @__PURE__ */ __name(class {
330
+ /**
331
+ * `.raw` can get the raw Request object.
332
+ *
333
+ * @see {@link https://hono.dev/docs/api/request#raw}
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * // For Cloudflare Workers
338
+ * app.post('/', async (c) => {
339
+ * const metadata = c.req.raw.cf?.hostMetadata?
340
+ * ...
341
+ * })
342
+ * ```
343
+ */
344
+ raw;
345
+ #validatedData;
346
+ // Short name of validatedData
347
+ #matchResult;
348
+ routeIndex = 0;
349
+ /**
350
+ * `.path` can get the pathname of the request.
351
+ *
352
+ * @see {@link https://hono.dev/docs/api/request#path}
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * app.get('/about/me', (c) => {
357
+ * const pathname = c.req.path // `/about/me`
358
+ * })
359
+ * ```
360
+ */
361
+ path;
362
+ bodyCache = {};
363
+ constructor(request, path = "/", matchResult = [[]]) {
364
+ this.raw = request;
365
+ this.path = path;
366
+ this.#matchResult = matchResult;
367
+ this.#validatedData = {};
368
+ }
369
+ param(key) {
370
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
371
+ }
372
+ #getDecodedParam(key) {
373
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
374
+ const param = this.#getParamValue(paramKey);
375
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
376
+ }
377
+ #getAllDecodedParams() {
378
+ const decoded = {};
379
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
380
+ for (const key of keys) {
381
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
382
+ if (value !== void 0) {
383
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
384
+ }
385
+ }
386
+ return decoded;
387
+ }
388
+ #getParamValue(paramKey) {
389
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
390
+ }
391
+ query(key) {
392
+ return getQueryParam(this.url, key);
393
+ }
394
+ queries(key) {
395
+ return getQueryParams(this.url, key);
396
+ }
397
+ header(name) {
398
+ if (name) {
399
+ return this.raw.headers.get(name) ?? void 0;
400
+ }
401
+ const headerData = {};
402
+ this.raw.headers.forEach((value, key) => {
403
+ headerData[key] = value;
404
+ });
405
+ return headerData;
406
+ }
407
+ async parseBody(options) {
408
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
409
+ }
410
+ #cachedBody = (key) => {
411
+ const { bodyCache, raw: raw2 } = this;
412
+ const cachedBody = bodyCache[key];
413
+ if (cachedBody) {
414
+ return cachedBody;
415
+ }
416
+ const anyCachedKey = Object.keys(bodyCache)[0];
417
+ if (anyCachedKey) {
418
+ return bodyCache[anyCachedKey].then((body) => {
419
+ if (anyCachedKey === "json") {
420
+ body = JSON.stringify(body);
421
+ }
422
+ return new Response(body)[key]();
423
+ });
424
+ }
425
+ return bodyCache[key] = raw2[key]();
426
+ };
427
+ /**
428
+ * `.json()` can parse Request body of type `application/json`
429
+ *
430
+ * @see {@link https://hono.dev/docs/api/request#json}
431
+ *
432
+ * @example
433
+ * ```ts
434
+ * app.post('/entry', async (c) => {
435
+ * const body = await c.req.json()
436
+ * })
437
+ * ```
438
+ */
439
+ json() {
440
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
441
+ }
442
+ /**
443
+ * `.text()` can parse Request body of type `text/plain`
444
+ *
445
+ * @see {@link https://hono.dev/docs/api/request#text}
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * app.post('/entry', async (c) => {
450
+ * const body = await c.req.text()
451
+ * })
452
+ * ```
453
+ */
454
+ text() {
455
+ return this.#cachedBody("text");
456
+ }
457
+ /**
458
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
459
+ *
460
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
461
+ *
462
+ * @example
463
+ * ```ts
464
+ * app.post('/entry', async (c) => {
465
+ * const body = await c.req.arrayBuffer()
466
+ * })
467
+ * ```
468
+ */
469
+ arrayBuffer() {
470
+ return this.#cachedBody("arrayBuffer");
471
+ }
472
+ /**
473
+ * Parses the request body as a `Blob`.
474
+ * @example
475
+ * ```ts
476
+ * app.post('/entry', async (c) => {
477
+ * const body = await c.req.blob();
478
+ * });
479
+ * ```
480
+ * @see https://hono.dev/docs/api/request#blob
481
+ */
482
+ blob() {
483
+ return this.#cachedBody("blob");
484
+ }
485
+ /**
486
+ * Parses the request body as `FormData`.
487
+ * @example
488
+ * ```ts
489
+ * app.post('/entry', async (c) => {
490
+ * const body = await c.req.formData();
491
+ * });
492
+ * ```
493
+ * @see https://hono.dev/docs/api/request#formdata
494
+ */
495
+ formData() {
496
+ return this.#cachedBody("formData");
497
+ }
498
+ /**
499
+ * Adds validated data to the request.
500
+ *
501
+ * @param target - The target of the validation.
502
+ * @param data - The validated data to add.
503
+ */
504
+ addValidatedData(target, data) {
505
+ this.#validatedData[target] = data;
506
+ }
507
+ valid(target) {
508
+ return this.#validatedData[target];
509
+ }
510
+ /**
511
+ * `.url()` can get the request url strings.
512
+ *
513
+ * @see {@link https://hono.dev/docs/api/request#url}
514
+ *
515
+ * @example
516
+ * ```ts
517
+ * app.get('/about/me', (c) => {
518
+ * const url = c.req.url // `http://localhost:8787/about/me`
519
+ * ...
520
+ * })
521
+ * ```
522
+ */
523
+ get url() {
524
+ return this.raw.url;
525
+ }
526
+ /**
527
+ * `.method()` can get the method name of the request.
528
+ *
529
+ * @see {@link https://hono.dev/docs/api/request#method}
530
+ *
531
+ * @example
532
+ * ```ts
533
+ * app.get('/about/me', (c) => {
534
+ * const method = c.req.method // `GET`
535
+ * })
536
+ * ```
537
+ */
538
+ get method() {
539
+ return this.raw.method;
540
+ }
541
+ get [GET_MATCH_RESULT]() {
542
+ return this.#matchResult;
543
+ }
544
+ /**
545
+ * `.matchedRoutes()` can return a matched route in the handler
546
+ *
547
+ * @deprecated
548
+ *
549
+ * Use matchedRoutes helper defined in "hono/route" instead.
550
+ *
551
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
552
+ *
553
+ * @example
554
+ * ```ts
555
+ * app.use('*', async function logger(c, next) {
556
+ * await next()
557
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
558
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
559
+ * console.log(
560
+ * method,
561
+ * ' ',
562
+ * path,
563
+ * ' '.repeat(Math.max(10 - path.length, 0)),
564
+ * name,
565
+ * i === c.req.routeIndex ? '<- respond from here' : ''
566
+ * )
567
+ * })
568
+ * })
569
+ * ```
570
+ */
571
+ get matchedRoutes() {
572
+ return this.#matchResult[0].map(([[, route]]) => route);
573
+ }
574
+ /**
575
+ * `routePath()` can retrieve the path registered within the handler
576
+ *
577
+ * @deprecated
578
+ *
579
+ * Use routePath helper defined in "hono/route" instead.
580
+ *
581
+ * @see {@link https://hono.dev/docs/api/request#routepath}
582
+ *
583
+ * @example
584
+ * ```ts
585
+ * app.get('/posts/:id', (c) => {
586
+ * return c.json({ path: c.req.routePath })
587
+ * })
588
+ * ```
589
+ */
590
+ get routePath() {
591
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
592
+ }
593
+ }, "HonoRequest");
594
+
595
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/utils/html.js
596
+ var HtmlEscapedCallbackPhase = {
597
+ Stringify: 1,
598
+ BeforeStream: 2,
599
+ Stream: 3
600
+ };
601
+ var raw = /* @__PURE__ */ __name((value, callbacks) => {
602
+ const escapedString = new String(value);
603
+ escapedString.isEscaped = true;
604
+ escapedString.callbacks = callbacks;
605
+ return escapedString;
606
+ }, "raw");
607
+ var resolveCallback = /* @__PURE__ */ __name(async (str, phase, preserveCallbacks, context, buffer) => {
608
+ if (typeof str === "object" && !(str instanceof String)) {
609
+ if (!(str instanceof Promise)) {
610
+ str = str.toString();
611
+ }
612
+ if (str instanceof Promise) {
613
+ str = await str;
614
+ }
615
+ }
616
+ const callbacks = str.callbacks;
617
+ if (!callbacks?.length) {
618
+ return Promise.resolve(str);
619
+ }
620
+ if (buffer) {
621
+ buffer[0] += str;
622
+ } else {
623
+ buffer = [str];
624
+ }
625
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
626
+ (res) => Promise.all(
627
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
628
+ ).then(() => buffer[0])
629
+ );
630
+ if (preserveCallbacks) {
631
+ return raw(await resStr, callbacks);
632
+ } else {
633
+ return resStr;
634
+ }
635
+ }, "resolveCallback");
636
+
637
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/context.js
638
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
639
+ var setDefaultContentType = /* @__PURE__ */ __name((contentType, headers) => {
640
+ return {
641
+ "Content-Type": contentType,
642
+ ...headers
643
+ };
644
+ }, "setDefaultContentType");
645
+ var createResponseInstance = /* @__PURE__ */ __name((body, init) => new Response(body, init), "createResponseInstance");
646
+ var Context = /* @__PURE__ */ __name(class {
647
+ #rawRequest;
648
+ #req;
649
+ /**
650
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
651
+ *
652
+ * @see {@link https://hono.dev/docs/api/context#env}
653
+ *
654
+ * @example
655
+ * ```ts
656
+ * // Environment object for Cloudflare Workers
657
+ * app.get('*', async c => {
658
+ * const counter = c.env.COUNTER
659
+ * })
660
+ * ```
661
+ */
662
+ env = {};
663
+ #var;
664
+ finalized = false;
665
+ /**
666
+ * `.error` can get the error object from the middleware if the Handler throws an error.
667
+ *
668
+ * @see {@link https://hono.dev/docs/api/context#error}
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * app.use('*', async (c, next) => {
673
+ * await next()
674
+ * if (c.error) {
675
+ * // do something...
676
+ * }
677
+ * })
678
+ * ```
679
+ */
680
+ error;
681
+ #status;
682
+ #executionCtx;
683
+ #res;
684
+ #layout;
685
+ #renderer;
686
+ #notFoundHandler;
687
+ #preparedHeaders;
688
+ #matchResult;
689
+ #path;
690
+ /**
691
+ * Creates an instance of the Context class.
692
+ *
693
+ * @param req - The Request object.
694
+ * @param options - Optional configuration options for the context.
695
+ */
696
+ constructor(req, options) {
697
+ this.#rawRequest = req;
698
+ if (options) {
699
+ this.#executionCtx = options.executionCtx;
700
+ this.env = options.env;
701
+ this.#notFoundHandler = options.notFoundHandler;
702
+ this.#path = options.path;
703
+ this.#matchResult = options.matchResult;
704
+ }
705
+ }
706
+ /**
707
+ * `.req` is the instance of {@link HonoRequest}.
708
+ */
709
+ get req() {
710
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
711
+ return this.#req;
712
+ }
713
+ /**
714
+ * @see {@link https://hono.dev/docs/api/context#event}
715
+ * The FetchEvent associated with the current request.
716
+ *
717
+ * @throws Will throw an error if the context does not have a FetchEvent.
718
+ */
719
+ get event() {
720
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
721
+ return this.#executionCtx;
722
+ } else {
723
+ throw Error("This context has no FetchEvent");
724
+ }
725
+ }
726
+ /**
727
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
728
+ * The ExecutionContext associated with the current request.
729
+ *
730
+ * @throws Will throw an error if the context does not have an ExecutionContext.
731
+ */
732
+ get executionCtx() {
733
+ if (this.#executionCtx) {
734
+ return this.#executionCtx;
735
+ } else {
736
+ throw Error("This context has no ExecutionContext");
737
+ }
738
+ }
739
+ /**
740
+ * @see {@link https://hono.dev/docs/api/context#res}
741
+ * The Response object for the current request.
742
+ */
743
+ get res() {
744
+ return this.#res ||= createResponseInstance(null, {
745
+ headers: this.#preparedHeaders ??= new Headers()
746
+ });
747
+ }
748
+ /**
749
+ * Sets the Response object for the current request.
750
+ *
751
+ * @param _res - The Response object to set.
752
+ */
753
+ set res(_res) {
754
+ if (this.#res && _res) {
755
+ _res = createResponseInstance(_res.body, _res);
756
+ for (const [k, v] of this.#res.headers.entries()) {
757
+ if (k === "content-type") {
758
+ continue;
759
+ }
760
+ if (k === "set-cookie") {
761
+ const cookies = this.#res.headers.getSetCookie();
762
+ _res.headers.delete("set-cookie");
763
+ for (const cookie of cookies) {
764
+ _res.headers.append("set-cookie", cookie);
765
+ }
766
+ } else {
767
+ _res.headers.set(k, v);
768
+ }
769
+ }
770
+ }
771
+ this.#res = _res;
772
+ this.finalized = true;
773
+ }
774
+ /**
775
+ * `.render()` can create a response within a layout.
776
+ *
777
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
778
+ *
779
+ * @example
780
+ * ```ts
781
+ * app.get('/', (c) => {
782
+ * return c.render('Hello!')
783
+ * })
784
+ * ```
785
+ */
786
+ render = (...args) => {
787
+ this.#renderer ??= (content) => this.html(content);
788
+ return this.#renderer(...args);
789
+ };
790
+ /**
791
+ * Sets the layout for the response.
792
+ *
793
+ * @param layout - The layout to set.
794
+ * @returns The layout function.
795
+ */
796
+ setLayout = (layout) => this.#layout = layout;
797
+ /**
798
+ * Gets the current layout for the response.
799
+ *
800
+ * @returns The current layout function.
801
+ */
802
+ getLayout = () => this.#layout;
803
+ /**
804
+ * `.setRenderer()` can set the layout in the custom middleware.
805
+ *
806
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
807
+ *
808
+ * @example
809
+ * ```tsx
810
+ * app.use('*', async (c, next) => {
811
+ * c.setRenderer((content) => {
812
+ * return c.html(
813
+ * <html>
814
+ * <body>
815
+ * <p>{content}</p>
816
+ * </body>
817
+ * </html>
818
+ * )
819
+ * })
820
+ * await next()
821
+ * })
822
+ * ```
823
+ */
824
+ setRenderer = (renderer) => {
825
+ this.#renderer = renderer;
826
+ };
827
+ /**
828
+ * `.header()` can set headers.
829
+ *
830
+ * @see {@link https://hono.dev/docs/api/context#header}
831
+ *
832
+ * @example
833
+ * ```ts
834
+ * app.get('/welcome', (c) => {
835
+ * // Set headers
836
+ * c.header('X-Message', 'Hello!')
837
+ * c.header('Content-Type', 'text/plain')
838
+ *
839
+ * return c.body('Thank you for coming')
840
+ * })
841
+ * ```
842
+ */
843
+ header = (name, value, options) => {
844
+ if (this.finalized) {
845
+ this.#res = createResponseInstance(this.#res.body, this.#res);
846
+ }
847
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
848
+ if (value === void 0) {
849
+ headers.delete(name);
850
+ } else if (options?.append) {
851
+ headers.append(name, value);
852
+ } else {
853
+ headers.set(name, value);
854
+ }
855
+ };
856
+ status = (status) => {
857
+ this.#status = status;
858
+ };
859
+ /**
860
+ * `.set()` can set the value specified by the key.
861
+ *
862
+ * @see {@link https://hono.dev/docs/api/context#set-get}
863
+ *
864
+ * @example
865
+ * ```ts
866
+ * app.use('*', async (c, next) => {
867
+ * c.set('message', 'Hono is hot!!')
868
+ * await next()
869
+ * })
870
+ * ```
871
+ */
872
+ set = (key, value) => {
873
+ this.#var ??= /* @__PURE__ */ new Map();
874
+ this.#var.set(key, value);
875
+ };
876
+ /**
877
+ * `.get()` can use the value specified by the key.
878
+ *
879
+ * @see {@link https://hono.dev/docs/api/context#set-get}
880
+ *
881
+ * @example
882
+ * ```ts
883
+ * app.get('/', (c) => {
884
+ * const message = c.get('message')
885
+ * return c.text(`The message is "${message}"`)
886
+ * })
887
+ * ```
888
+ */
889
+ get = (key) => {
890
+ return this.#var ? this.#var.get(key) : void 0;
891
+ };
892
+ /**
893
+ * `.var` can access the value of a variable.
894
+ *
895
+ * @see {@link https://hono.dev/docs/api/context#var}
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * const result = c.var.client.oneMethod()
900
+ * ```
901
+ */
902
+ // c.var.propName is a read-only
903
+ get var() {
904
+ if (!this.#var) {
905
+ return {};
906
+ }
907
+ return Object.fromEntries(this.#var);
908
+ }
909
+ #newResponse(data, arg, headers) {
910
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
911
+ if (typeof arg === "object" && "headers" in arg) {
912
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
913
+ for (const [key, value] of argHeaders) {
914
+ if (key.toLowerCase() === "set-cookie") {
915
+ responseHeaders.append(key, value);
916
+ } else {
917
+ responseHeaders.set(key, value);
918
+ }
919
+ }
920
+ }
921
+ if (headers) {
922
+ for (const [k, v] of Object.entries(headers)) {
923
+ if (typeof v === "string") {
924
+ responseHeaders.set(k, v);
925
+ } else {
926
+ responseHeaders.delete(k);
927
+ for (const v2 of v) {
928
+ responseHeaders.append(k, v2);
929
+ }
930
+ }
931
+ }
932
+ }
933
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
934
+ return createResponseInstance(data, { status, headers: responseHeaders });
935
+ }
936
+ newResponse = (...args) => this.#newResponse(...args);
937
+ /**
938
+ * `.body()` can return the HTTP response.
939
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
940
+ * This can also be set in `.text()`, `.json()` and so on.
941
+ *
942
+ * @see {@link https://hono.dev/docs/api/context#body}
943
+ *
944
+ * @example
945
+ * ```ts
946
+ * app.get('/welcome', (c) => {
947
+ * // Set headers
948
+ * c.header('X-Message', 'Hello!')
949
+ * c.header('Content-Type', 'text/plain')
950
+ * // Set HTTP status code
951
+ * c.status(201)
952
+ *
953
+ * // Return the response body
954
+ * return c.body('Thank you for coming')
955
+ * })
956
+ * ```
957
+ */
958
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
959
+ /**
960
+ * `.text()` can render text as `Content-Type:text/plain`.
961
+ *
962
+ * @see {@link https://hono.dev/docs/api/context#text}
963
+ *
964
+ * @example
965
+ * ```ts
966
+ * app.get('/say', (c) => {
967
+ * return c.text('Hello!')
968
+ * })
969
+ * ```
970
+ */
971
+ text = (text, arg, headers) => {
972
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
973
+ text,
974
+ arg,
975
+ setDefaultContentType(TEXT_PLAIN, headers)
976
+ );
977
+ };
978
+ /**
979
+ * `.json()` can render JSON as `Content-Type:application/json`.
980
+ *
981
+ * @see {@link https://hono.dev/docs/api/context#json}
982
+ *
983
+ * @example
984
+ * ```ts
985
+ * app.get('/api', (c) => {
986
+ * return c.json({ message: 'Hello!' })
987
+ * })
988
+ * ```
989
+ */
990
+ json = (object, arg, headers) => {
991
+ return this.#newResponse(
992
+ JSON.stringify(object),
993
+ arg,
994
+ setDefaultContentType("application/json", headers)
995
+ );
996
+ };
997
+ html = (html, arg, headers) => {
998
+ const res = /* @__PURE__ */ __name((html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)), "res");
999
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1000
+ };
1001
+ /**
1002
+ * `.redirect()` can Redirect, default status code is 302.
1003
+ *
1004
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1005
+ *
1006
+ * @example
1007
+ * ```ts
1008
+ * app.get('/redirect', (c) => {
1009
+ * return c.redirect('/')
1010
+ * })
1011
+ * app.get('/redirect-permanently', (c) => {
1012
+ * return c.redirect('/', 301)
1013
+ * })
1014
+ * ```
1015
+ */
1016
+ redirect = (location, status) => {
1017
+ const locationString = String(location);
1018
+ this.header(
1019
+ "Location",
1020
+ // Multibyes should be encoded
1021
+ // eslint-disable-next-line no-control-regex
1022
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1023
+ );
1024
+ return this.newResponse(null, status ?? 302);
1025
+ };
1026
+ /**
1027
+ * `.notFound()` can return the Not Found Response.
1028
+ *
1029
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1030
+ *
1031
+ * @example
1032
+ * ```ts
1033
+ * app.get('/notfound', (c) => {
1034
+ * return c.notFound()
1035
+ * })
1036
+ * ```
1037
+ */
1038
+ notFound = () => {
1039
+ this.#notFoundHandler ??= () => createResponseInstance();
1040
+ return this.#notFoundHandler(this);
1041
+ };
1042
+ }, "Context");
1043
+
1044
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router.js
1045
+ var METHOD_NAME_ALL = "ALL";
1046
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1047
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1048
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1049
+ var UnsupportedPathError = /* @__PURE__ */ __name(class extends Error {
1050
+ }, "UnsupportedPathError");
1051
+
1052
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/utils/constants.js
1053
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1054
+
1055
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/hono-base.js
1056
+ var notFoundHandler = /* @__PURE__ */ __name((c) => {
1057
+ return c.text("404 Not Found", 404);
1058
+ }, "notFoundHandler");
1059
+ var errorHandler = /* @__PURE__ */ __name((err, c) => {
1060
+ if ("getResponse" in err) {
1061
+ const res = err.getResponse();
1062
+ return c.newResponse(res.body, res);
1063
+ }
1064
+ console.error(err);
1065
+ return c.text("Internal Server Error", 500);
1066
+ }, "errorHandler");
1067
+ var Hono = /* @__PURE__ */ __name(class _Hono {
1068
+ get;
1069
+ post;
1070
+ put;
1071
+ delete;
1072
+ options;
1073
+ patch;
1074
+ all;
1075
+ on;
1076
+ use;
1077
+ /*
1078
+ This class is like an abstract class and does not have a router.
1079
+ To use it, inherit the class and implement router in the constructor.
1080
+ */
1081
+ router;
1082
+ getPath;
1083
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1084
+ _basePath = "/";
1085
+ #path = "/";
1086
+ routes = [];
1087
+ constructor(options = {}) {
1088
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1089
+ allMethods.forEach((method) => {
1090
+ this[method] = (args1, ...args) => {
1091
+ if (typeof args1 === "string") {
1092
+ this.#path = args1;
1093
+ } else {
1094
+ this.#addRoute(method, this.#path, args1);
1095
+ }
1096
+ args.forEach((handler) => {
1097
+ this.#addRoute(method, this.#path, handler);
1098
+ });
1099
+ return this;
1100
+ };
1101
+ });
1102
+ this.on = (method, path, ...handlers) => {
1103
+ for (const p of [path].flat()) {
1104
+ this.#path = p;
1105
+ for (const m of [method].flat()) {
1106
+ handlers.map((handler) => {
1107
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1108
+ });
1109
+ }
1110
+ }
1111
+ return this;
1112
+ };
1113
+ this.use = (arg1, ...handlers) => {
1114
+ if (typeof arg1 === "string") {
1115
+ this.#path = arg1;
1116
+ } else {
1117
+ this.#path = "*";
1118
+ handlers.unshift(arg1);
1119
+ }
1120
+ handlers.forEach((handler) => {
1121
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1122
+ });
1123
+ return this;
1124
+ };
1125
+ const { strict, ...optionsWithoutStrict } = options;
1126
+ Object.assign(this, optionsWithoutStrict);
1127
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1128
+ }
1129
+ #clone() {
1130
+ const clone = new _Hono({
1131
+ router: this.router,
1132
+ getPath: this.getPath
1133
+ });
1134
+ clone.errorHandler = this.errorHandler;
1135
+ clone.#notFoundHandler = this.#notFoundHandler;
1136
+ clone.routes = this.routes;
1137
+ return clone;
1138
+ }
1139
+ #notFoundHandler = notFoundHandler;
1140
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1141
+ errorHandler = errorHandler;
1142
+ /**
1143
+ * `.route()` allows grouping other Hono instance in routes.
1144
+ *
1145
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1146
+ *
1147
+ * @param {string} path - base Path
1148
+ * @param {Hono} app - other Hono instance
1149
+ * @returns {Hono} routed Hono instance
1150
+ *
1151
+ * @example
1152
+ * ```ts
1153
+ * const app = new Hono()
1154
+ * const app2 = new Hono()
1155
+ *
1156
+ * app2.get("/user", (c) => c.text("user"))
1157
+ * app.route("/api", app2) // GET /api/user
1158
+ * ```
1159
+ */
1160
+ route(path, app2) {
1161
+ const subApp = this.basePath(path);
1162
+ app2.routes.map((r) => {
1163
+ let handler;
1164
+ if (app2.errorHandler === errorHandler) {
1165
+ handler = r.handler;
1166
+ } else {
1167
+ handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler");
1168
+ handler[COMPOSED_HANDLER] = r.handler;
1169
+ }
1170
+ subApp.#addRoute(r.method, r.path, handler);
1171
+ });
1172
+ return this;
1173
+ }
1174
+ /**
1175
+ * `.basePath()` allows base paths to be specified.
1176
+ *
1177
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1178
+ *
1179
+ * @param {string} path - base Path
1180
+ * @returns {Hono} changed Hono instance
1181
+ *
1182
+ * @example
1183
+ * ```ts
1184
+ * const api = new Hono().basePath('/api')
1185
+ * ```
1186
+ */
1187
+ basePath(path) {
1188
+ const subApp = this.#clone();
1189
+ subApp._basePath = mergePath(this._basePath, path);
1190
+ return subApp;
1191
+ }
1192
+ /**
1193
+ * `.onError()` handles an error and returns a customized Response.
1194
+ *
1195
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1196
+ *
1197
+ * @param {ErrorHandler} handler - request Handler for error
1198
+ * @returns {Hono} changed Hono instance
1199
+ *
1200
+ * @example
1201
+ * ```ts
1202
+ * app.onError((err, c) => {
1203
+ * console.error(`${err}`)
1204
+ * return c.text('Custom Error Message', 500)
1205
+ * })
1206
+ * ```
1207
+ */
1208
+ onError = (handler) => {
1209
+ this.errorHandler = handler;
1210
+ return this;
1211
+ };
1212
+ /**
1213
+ * `.notFound()` allows you to customize a Not Found Response.
1214
+ *
1215
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1216
+ *
1217
+ * @param {NotFoundHandler} handler - request handler for not-found
1218
+ * @returns {Hono} changed Hono instance
1219
+ *
1220
+ * @example
1221
+ * ```ts
1222
+ * app.notFound((c) => {
1223
+ * return c.text('Custom 404 Message', 404)
1224
+ * })
1225
+ * ```
1226
+ */
1227
+ notFound = (handler) => {
1228
+ this.#notFoundHandler = handler;
1229
+ return this;
1230
+ };
1231
+ /**
1232
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1233
+ *
1234
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1235
+ *
1236
+ * @param {string} path - base Path
1237
+ * @param {Function} applicationHandler - other Request Handler
1238
+ * @param {MountOptions} [options] - options of `.mount()`
1239
+ * @returns {Hono} mounted Hono instance
1240
+ *
1241
+ * @example
1242
+ * ```ts
1243
+ * import { Router as IttyRouter } from 'itty-router'
1244
+ * import { Hono } from 'hono'
1245
+ * // Create itty-router application
1246
+ * const ittyRouter = IttyRouter()
1247
+ * // GET /itty-router/hello
1248
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1249
+ *
1250
+ * const app = new Hono()
1251
+ * app.mount('/itty-router', ittyRouter.handle)
1252
+ * ```
1253
+ *
1254
+ * @example
1255
+ * ```ts
1256
+ * const app = new Hono()
1257
+ * // Send the request to another application without modification.
1258
+ * app.mount('/app', anotherApp, {
1259
+ * replaceRequest: (req) => req,
1260
+ * })
1261
+ * ```
1262
+ */
1263
+ mount(path, applicationHandler, options) {
1264
+ let replaceRequest;
1265
+ let optionHandler;
1266
+ if (options) {
1267
+ if (typeof options === "function") {
1268
+ optionHandler = options;
1269
+ } else {
1270
+ optionHandler = options.optionHandler;
1271
+ if (options.replaceRequest === false) {
1272
+ replaceRequest = /* @__PURE__ */ __name((request) => request, "replaceRequest");
1273
+ } else {
1274
+ replaceRequest = options.replaceRequest;
1275
+ }
1276
+ }
1277
+ }
1278
+ const getOptions = optionHandler ? (c) => {
1279
+ const options2 = optionHandler(c);
1280
+ return Array.isArray(options2) ? options2 : [options2];
1281
+ } : (c) => {
1282
+ let executionContext = void 0;
1283
+ try {
1284
+ executionContext = c.executionCtx;
1285
+ } catch {
1286
+ }
1287
+ return [c.env, executionContext];
1288
+ };
1289
+ replaceRequest ||= (() => {
1290
+ const mergedPath = mergePath(this._basePath, path);
1291
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1292
+ return (request) => {
1293
+ const url = new URL(request.url);
1294
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1295
+ return new Request(url, request);
1296
+ };
1297
+ })();
1298
+ const handler = /* @__PURE__ */ __name(async (c, next) => {
1299
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1300
+ if (res) {
1301
+ return res;
1302
+ }
1303
+ await next();
1304
+ }, "handler");
1305
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1306
+ return this;
1307
+ }
1308
+ #addRoute(method, path, handler) {
1309
+ method = method.toUpperCase();
1310
+ path = mergePath(this._basePath, path);
1311
+ const r = { basePath: this._basePath, path, method, handler };
1312
+ this.router.add(method, path, [handler, r]);
1313
+ this.routes.push(r);
1314
+ }
1315
+ #handleError(err, c) {
1316
+ if (err instanceof Error) {
1317
+ return this.errorHandler(err, c);
1318
+ }
1319
+ throw err;
1320
+ }
1321
+ #dispatch(request, executionCtx, env, method) {
1322
+ if (method === "HEAD") {
1323
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1324
+ }
1325
+ const path = this.getPath(request, { env });
1326
+ const matchResult = this.router.match(method, path);
1327
+ const c = new Context(request, {
1328
+ path,
1329
+ matchResult,
1330
+ env,
1331
+ executionCtx,
1332
+ notFoundHandler: this.#notFoundHandler
1333
+ });
1334
+ if (matchResult[0].length === 1) {
1335
+ let res;
1336
+ try {
1337
+ res = matchResult[0][0][0][0](c, async () => {
1338
+ c.res = await this.#notFoundHandler(c);
1339
+ });
1340
+ } catch (err) {
1341
+ return this.#handleError(err, c);
1342
+ }
1343
+ return res instanceof Promise ? res.then(
1344
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
1345
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1346
+ }
1347
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1348
+ return (async () => {
1349
+ try {
1350
+ const context = await composed(c);
1351
+ if (!context.finalized) {
1352
+ throw new Error(
1353
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
1354
+ );
1355
+ }
1356
+ return context.res;
1357
+ } catch (err) {
1358
+ return this.#handleError(err, c);
1359
+ }
1360
+ })();
1361
+ }
1362
+ /**
1363
+ * `.fetch()` will be entry point of your app.
1364
+ *
1365
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1366
+ *
1367
+ * @param {Request} request - request Object of request
1368
+ * @param {Env} Env - env Object
1369
+ * @param {ExecutionContext} - context of execution
1370
+ * @returns {Response | Promise<Response>} response of request
1371
+ *
1372
+ */
1373
+ fetch = (request, ...rest) => {
1374
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1375
+ };
1376
+ /**
1377
+ * `.request()` is a useful method for testing.
1378
+ * You can pass a URL or pathname to send a GET request.
1379
+ * app will return a Response object.
1380
+ * ```ts
1381
+ * test('GET /hello is ok', async () => {
1382
+ * const res = await app.request('/hello')
1383
+ * expect(res.status).toBe(200)
1384
+ * })
1385
+ * ```
1386
+ * @see https://hono.dev/docs/api/hono#request
1387
+ */
1388
+ request = (input, requestInit, Env, executionCtx) => {
1389
+ if (input instanceof Request) {
1390
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1391
+ }
1392
+ input = input.toString();
1393
+ return this.fetch(
1394
+ new Request(
1395
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
1396
+ requestInit
1397
+ ),
1398
+ Env,
1399
+ executionCtx
1400
+ );
1401
+ };
1402
+ /**
1403
+ * `.fire()` automatically adds a global fetch event listener.
1404
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1405
+ * @deprecated
1406
+ * Use `fire` from `hono/service-worker` instead.
1407
+ * ```ts
1408
+ * import { Hono } from 'hono'
1409
+ * import { fire } from 'hono/service-worker'
1410
+ *
1411
+ * const app = new Hono()
1412
+ * // ...
1413
+ * fire(app)
1414
+ * ```
1415
+ * @see https://hono.dev/docs/api/hono#fire
1416
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1417
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1418
+ */
1419
+ fire = () => {
1420
+ addEventListener("fetch", (event) => {
1421
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1422
+ });
1423
+ };
1424
+ }, "_Hono");
1425
+
1426
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/reg-exp-router/matcher.js
1427
+ var emptyParam = [];
1428
+ function match(method, path) {
1429
+ const matchers = this.buildAllMatchers();
1430
+ const match2 = /* @__PURE__ */ __name((method2, path2) => {
1431
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1432
+ const staticMatch = matcher[2][path2];
1433
+ if (staticMatch) {
1434
+ return staticMatch;
1435
+ }
1436
+ const match3 = path2.match(matcher[0]);
1437
+ if (!match3) {
1438
+ return [[], emptyParam];
1439
+ }
1440
+ const index = match3.indexOf("", 1);
1441
+ return [matcher[1][index], match3];
1442
+ }, "match2");
1443
+ this.match = match2;
1444
+ return match2(method, path);
1445
+ }
1446
+ __name(match, "match");
1447
+
1448
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/reg-exp-router/node.js
1449
+ var LABEL_REG_EXP_STR = "[^/]+";
1450
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1451
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1452
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1453
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1454
+ function compareKey(a, b) {
1455
+ if (a.length === 1) {
1456
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1457
+ }
1458
+ if (b.length === 1) {
1459
+ return 1;
1460
+ }
1461
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1462
+ return 1;
1463
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1464
+ return -1;
1465
+ }
1466
+ if (a === LABEL_REG_EXP_STR) {
1467
+ return 1;
1468
+ } else if (b === LABEL_REG_EXP_STR) {
1469
+ return -1;
1470
+ }
1471
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1472
+ }
1473
+ __name(compareKey, "compareKey");
1474
+ var Node = /* @__PURE__ */ __name(class _Node {
1475
+ #index;
1476
+ #varIndex;
1477
+ #children = /* @__PURE__ */ Object.create(null);
1478
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1479
+ if (tokens.length === 0) {
1480
+ if (this.#index !== void 0) {
1481
+ throw PATH_ERROR;
1482
+ }
1483
+ if (pathErrorCheckOnly) {
1484
+ return;
1485
+ }
1486
+ this.#index = index;
1487
+ return;
1488
+ }
1489
+ const [token, ...restTokens] = tokens;
1490
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1491
+ let node;
1492
+ if (pattern) {
1493
+ const name = pattern[1];
1494
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1495
+ if (name && pattern[2]) {
1496
+ if (regexpStr === ".*") {
1497
+ throw PATH_ERROR;
1498
+ }
1499
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1500
+ if (/\((?!\?:)/.test(regexpStr)) {
1501
+ throw PATH_ERROR;
1502
+ }
1503
+ }
1504
+ node = this.#children[regexpStr];
1505
+ if (!node) {
1506
+ if (Object.keys(this.#children).some(
1507
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1508
+ )) {
1509
+ throw PATH_ERROR;
1510
+ }
1511
+ if (pathErrorCheckOnly) {
1512
+ return;
1513
+ }
1514
+ node = this.#children[regexpStr] = new _Node();
1515
+ if (name !== "") {
1516
+ node.#varIndex = context.varIndex++;
1517
+ }
1518
+ }
1519
+ if (!pathErrorCheckOnly && name !== "") {
1520
+ paramMap.push([name, node.#varIndex]);
1521
+ }
1522
+ } else {
1523
+ node = this.#children[token];
1524
+ if (!node) {
1525
+ if (Object.keys(this.#children).some(
1526
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1527
+ )) {
1528
+ throw PATH_ERROR;
1529
+ }
1530
+ if (pathErrorCheckOnly) {
1531
+ return;
1532
+ }
1533
+ node = this.#children[token] = new _Node();
1534
+ }
1535
+ }
1536
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1537
+ }
1538
+ buildRegExpStr() {
1539
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1540
+ const strList = childKeys.map((k) => {
1541
+ const c = this.#children[k];
1542
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1543
+ });
1544
+ if (typeof this.#index === "number") {
1545
+ strList.unshift(`#${this.#index}`);
1546
+ }
1547
+ if (strList.length === 0) {
1548
+ return "";
1549
+ }
1550
+ if (strList.length === 1) {
1551
+ return strList[0];
1552
+ }
1553
+ return "(?:" + strList.join("|") + ")";
1554
+ }
1555
+ }, "_Node");
1556
+
1557
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/reg-exp-router/trie.js
1558
+ var Trie = /* @__PURE__ */ __name(class {
1559
+ #context = { varIndex: 0 };
1560
+ #root = new Node();
1561
+ insert(path, index, pathErrorCheckOnly) {
1562
+ const paramAssoc = [];
1563
+ const groups = [];
1564
+ for (let i = 0; ; ) {
1565
+ let replaced = false;
1566
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1567
+ const mark = `@\\${i}`;
1568
+ groups[i] = [mark, m];
1569
+ i++;
1570
+ replaced = true;
1571
+ return mark;
1572
+ });
1573
+ if (!replaced) {
1574
+ break;
1575
+ }
1576
+ }
1577
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1578
+ for (let i = groups.length - 1; i >= 0; i--) {
1579
+ const [mark] = groups[i];
1580
+ for (let j = tokens.length - 1; j >= 0; j--) {
1581
+ if (tokens[j].indexOf(mark) !== -1) {
1582
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1583
+ break;
1584
+ }
1585
+ }
1586
+ }
1587
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1588
+ return paramAssoc;
1589
+ }
1590
+ buildRegExp() {
1591
+ let regexp = this.#root.buildRegExpStr();
1592
+ if (regexp === "") {
1593
+ return [/^$/, [], []];
1594
+ }
1595
+ let captureIndex = 0;
1596
+ const indexReplacementMap = [];
1597
+ const paramReplacementMap = [];
1598
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1599
+ if (handlerIndex !== void 0) {
1600
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1601
+ return "$()";
1602
+ }
1603
+ if (paramIndex !== void 0) {
1604
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1605
+ return "";
1606
+ }
1607
+ return "";
1608
+ });
1609
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1610
+ }
1611
+ }, "Trie");
1612
+
1613
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/reg-exp-router/router.js
1614
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1615
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1616
+ function buildWildcardRegExp(path) {
1617
+ return wildcardRegExpCache[path] ??= new RegExp(
1618
+ path === "*" ? "" : `^${path.replace(
1619
+ /\/\*$|([.\\+*[^\]$()])/g,
1620
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
1621
+ )}$`
1622
+ );
1623
+ }
1624
+ __name(buildWildcardRegExp, "buildWildcardRegExp");
1625
+ function clearWildcardRegExpCache() {
1626
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1627
+ }
1628
+ __name(clearWildcardRegExpCache, "clearWildcardRegExpCache");
1629
+ function buildMatcherFromPreprocessedRoutes(routes) {
1630
+ const trie = new Trie();
1631
+ const handlerData = [];
1632
+ if (routes.length === 0) {
1633
+ return nullMatcher;
1634
+ }
1635
+ const routesWithStaticPathFlag = routes.map(
1636
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
1637
+ ).sort(
1638
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
1639
+ );
1640
+ const staticMap = /* @__PURE__ */ Object.create(null);
1641
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
1642
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1643
+ if (pathErrorCheckOnly) {
1644
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1645
+ } else {
1646
+ j++;
1647
+ }
1648
+ let paramAssoc;
1649
+ try {
1650
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1651
+ } catch (e) {
1652
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1653
+ }
1654
+ if (pathErrorCheckOnly) {
1655
+ continue;
1656
+ }
1657
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1658
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1659
+ paramCount -= 1;
1660
+ for (; paramCount >= 0; paramCount--) {
1661
+ const [key, value] = paramAssoc[paramCount];
1662
+ paramIndexMap[key] = value;
1663
+ }
1664
+ return [h, paramIndexMap];
1665
+ });
1666
+ }
1667
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1668
+ for (let i = 0, len = handlerData.length; i < len; i++) {
1669
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
1670
+ const map = handlerData[i][j]?.[1];
1671
+ if (!map) {
1672
+ continue;
1673
+ }
1674
+ const keys = Object.keys(map);
1675
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
1676
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1677
+ }
1678
+ }
1679
+ }
1680
+ const handlerMap = [];
1681
+ for (const i in indexReplacementMap) {
1682
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1683
+ }
1684
+ return [regexp, handlerMap, staticMap];
1685
+ }
1686
+ __name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes");
1687
+ function findMiddleware(middleware, path) {
1688
+ if (!middleware) {
1689
+ return void 0;
1690
+ }
1691
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1692
+ if (buildWildcardRegExp(k).test(path)) {
1693
+ return [...middleware[k]];
1694
+ }
1695
+ }
1696
+ return void 0;
1697
+ }
1698
+ __name(findMiddleware, "findMiddleware");
1699
+ var RegExpRouter = /* @__PURE__ */ __name(class {
1700
+ name = "RegExpRouter";
1701
+ #middleware;
1702
+ #routes;
1703
+ constructor() {
1704
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1705
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1706
+ }
1707
+ add(method, path, handler) {
1708
+ const middleware = this.#middleware;
1709
+ const routes = this.#routes;
1710
+ if (!middleware || !routes) {
1711
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1712
+ }
1713
+ if (!middleware[method]) {
1714
+ ;
1715
+ [middleware, routes].forEach((handlerMap) => {
1716
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1717
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1718
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1719
+ });
1720
+ });
1721
+ }
1722
+ if (path === "/*") {
1723
+ path = "*";
1724
+ }
1725
+ const paramCount = (path.match(/\/:/g) || []).length;
1726
+ if (/\*$/.test(path)) {
1727
+ const re = buildWildcardRegExp(path);
1728
+ if (method === METHOD_NAME_ALL) {
1729
+ Object.keys(middleware).forEach((m) => {
1730
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1731
+ });
1732
+ } else {
1733
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1734
+ }
1735
+ Object.keys(middleware).forEach((m) => {
1736
+ if (method === METHOD_NAME_ALL || method === m) {
1737
+ Object.keys(middleware[m]).forEach((p) => {
1738
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1739
+ });
1740
+ }
1741
+ });
1742
+ Object.keys(routes).forEach((m) => {
1743
+ if (method === METHOD_NAME_ALL || method === m) {
1744
+ Object.keys(routes[m]).forEach(
1745
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
1746
+ );
1747
+ }
1748
+ });
1749
+ return;
1750
+ }
1751
+ const paths = checkOptionalParameter(path) || [path];
1752
+ for (let i = 0, len = paths.length; i < len; i++) {
1753
+ const path2 = paths[i];
1754
+ Object.keys(routes).forEach((m) => {
1755
+ if (method === METHOD_NAME_ALL || method === m) {
1756
+ routes[m][path2] ||= [
1757
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1758
+ ];
1759
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1760
+ }
1761
+ });
1762
+ }
1763
+ }
1764
+ match = match;
1765
+ buildAllMatchers() {
1766
+ const matchers = /* @__PURE__ */ Object.create(null);
1767
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1768
+ matchers[method] ||= this.#buildMatcher(method);
1769
+ });
1770
+ this.#middleware = this.#routes = void 0;
1771
+ clearWildcardRegExpCache();
1772
+ return matchers;
1773
+ }
1774
+ #buildMatcher(method) {
1775
+ const routes = [];
1776
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1777
+ [this.#middleware, this.#routes].forEach((r) => {
1778
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1779
+ if (ownRoute.length !== 0) {
1780
+ hasOwnRoute ||= true;
1781
+ routes.push(...ownRoute);
1782
+ } else if (method !== METHOD_NAME_ALL) {
1783
+ routes.push(
1784
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
1785
+ );
1786
+ }
1787
+ });
1788
+ if (!hasOwnRoute) {
1789
+ return null;
1790
+ } else {
1791
+ return buildMatcherFromPreprocessedRoutes(routes);
1792
+ }
1793
+ }
1794
+ }, "RegExpRouter");
1795
+
1796
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/smart-router/router.js
1797
+ var SmartRouter = /* @__PURE__ */ __name(class {
1798
+ name = "SmartRouter";
1799
+ #routers = [];
1800
+ #routes = [];
1801
+ constructor(init) {
1802
+ this.#routers = init.routers;
1803
+ }
1804
+ add(method, path, handler) {
1805
+ if (!this.#routes) {
1806
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1807
+ }
1808
+ this.#routes.push([method, path, handler]);
1809
+ }
1810
+ match(method, path) {
1811
+ if (!this.#routes) {
1812
+ throw new Error("Fatal error");
1813
+ }
1814
+ const routers = this.#routers;
1815
+ const routes = this.#routes;
1816
+ const len = routers.length;
1817
+ let i = 0;
1818
+ let res;
1819
+ for (; i < len; i++) {
1820
+ const router = routers[i];
1821
+ try {
1822
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
1823
+ router.add(...routes[i2]);
1824
+ }
1825
+ res = router.match(method, path);
1826
+ } catch (e) {
1827
+ if (e instanceof UnsupportedPathError) {
1828
+ continue;
1829
+ }
1830
+ throw e;
1831
+ }
1832
+ this.match = router.match.bind(router);
1833
+ this.#routers = [router];
1834
+ this.#routes = void 0;
1835
+ break;
1836
+ }
1837
+ if (i === len) {
1838
+ throw new Error("Fatal error");
1839
+ }
1840
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1841
+ return res;
1842
+ }
1843
+ get activeRouter() {
1844
+ if (this.#routes || this.#routers.length !== 1) {
1845
+ throw new Error("No active router has been determined yet.");
1846
+ }
1847
+ return this.#routers[0];
1848
+ }
1849
+ }, "SmartRouter");
1850
+
1851
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/trie-router/node.js
1852
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1853
+ var hasChildren = /* @__PURE__ */ __name((children) => {
1854
+ for (const _ in children) {
1855
+ return true;
1856
+ }
1857
+ return false;
1858
+ }, "hasChildren");
1859
+ var Node2 = /* @__PURE__ */ __name(class _Node2 {
1860
+ #methods;
1861
+ #children;
1862
+ #patterns;
1863
+ #order = 0;
1864
+ #params = emptyParams;
1865
+ constructor(method, handler, children) {
1866
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1867
+ this.#methods = [];
1868
+ if (method && handler) {
1869
+ const m = /* @__PURE__ */ Object.create(null);
1870
+ m[method] = { handler, possibleKeys: [], score: 0 };
1871
+ this.#methods = [m];
1872
+ }
1873
+ this.#patterns = [];
1874
+ }
1875
+ insert(method, path, handler) {
1876
+ this.#order = ++this.#order;
1877
+ let curNode = this;
1878
+ const parts = splitRoutingPath(path);
1879
+ const possibleKeys = [];
1880
+ for (let i = 0, len = parts.length; i < len; i++) {
1881
+ const p = parts[i];
1882
+ const nextP = parts[i + 1];
1883
+ const pattern = getPattern(p, nextP);
1884
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1885
+ if (key in curNode.#children) {
1886
+ curNode = curNode.#children[key];
1887
+ if (pattern) {
1888
+ possibleKeys.push(pattern[1]);
1889
+ }
1890
+ continue;
1891
+ }
1892
+ curNode.#children[key] = new _Node2();
1893
+ if (pattern) {
1894
+ curNode.#patterns.push(pattern);
1895
+ possibleKeys.push(pattern[1]);
1896
+ }
1897
+ curNode = curNode.#children[key];
1898
+ }
1899
+ curNode.#methods.push({
1900
+ [method]: {
1901
+ handler,
1902
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1903
+ score: this.#order
1904
+ }
1905
+ });
1906
+ return curNode;
1907
+ }
1908
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
1909
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
1910
+ const m = node.#methods[i];
1911
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1912
+ const processedSet = {};
1913
+ if (handlerSet !== void 0) {
1914
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1915
+ handlerSets.push(handlerSet);
1916
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1917
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
1918
+ const key = handlerSet.possibleKeys[i2];
1919
+ const processed = processedSet[handlerSet.score];
1920
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1921
+ processedSet[handlerSet.score] = true;
1922
+ }
1923
+ }
1924
+ }
1925
+ }
1926
+ }
1927
+ search(method, path) {
1928
+ const handlerSets = [];
1929
+ this.#params = emptyParams;
1930
+ const curNode = this;
1931
+ let curNodes = [curNode];
1932
+ const parts = splitPath(path);
1933
+ const curNodesQueue = [];
1934
+ const len = parts.length;
1935
+ let partOffsets = null;
1936
+ for (let i = 0; i < len; i++) {
1937
+ const part = parts[i];
1938
+ const isLast = i === len - 1;
1939
+ const tempNodes = [];
1940
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
1941
+ const node = curNodes[j];
1942
+ const nextNode = node.#children[part];
1943
+ if (nextNode) {
1944
+ nextNode.#params = node.#params;
1945
+ if (isLast) {
1946
+ if (nextNode.#children["*"]) {
1947
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
1948
+ }
1949
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
1950
+ } else {
1951
+ tempNodes.push(nextNode);
1952
+ }
1953
+ }
1954
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
1955
+ const pattern = node.#patterns[k];
1956
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1957
+ if (pattern === "*") {
1958
+ const astNode = node.#children["*"];
1959
+ if (astNode) {
1960
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
1961
+ astNode.#params = params;
1962
+ tempNodes.push(astNode);
1963
+ }
1964
+ continue;
1965
+ }
1966
+ const [key, name, matcher] = pattern;
1967
+ if (!part && !(matcher instanceof RegExp)) {
1968
+ continue;
1969
+ }
1970
+ const child = node.#children[key];
1971
+ if (matcher instanceof RegExp) {
1972
+ if (partOffsets === null) {
1973
+ partOffsets = new Array(len);
1974
+ let offset = path[0] === "/" ? 1 : 0;
1975
+ for (let p = 0; p < len; p++) {
1976
+ partOffsets[p] = offset;
1977
+ offset += parts[p].length + 1;
1978
+ }
1979
+ }
1980
+ const restPathString = path.substring(partOffsets[i]);
1981
+ const m = matcher.exec(restPathString);
1982
+ if (m) {
1983
+ params[name] = m[0];
1984
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
1985
+ if (hasChildren(child.#children)) {
1986
+ child.#params = params;
1987
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1988
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1989
+ targetCurNodes.push(child);
1990
+ }
1991
+ continue;
1992
+ }
1993
+ }
1994
+ if (matcher === true || matcher.test(part)) {
1995
+ params[name] = part;
1996
+ if (isLast) {
1997
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
1998
+ if (child.#children["*"]) {
1999
+ this.#pushHandlerSets(
2000
+ handlerSets,
2001
+ child.#children["*"],
2002
+ method,
2003
+ params,
2004
+ node.#params
2005
+ );
2006
+ }
2007
+ } else {
2008
+ child.#params = params;
2009
+ tempNodes.push(child);
2010
+ }
2011
+ }
2012
+ }
2013
+ }
2014
+ const shifted = curNodesQueue.shift();
2015
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
2016
+ }
2017
+ if (handlerSets.length > 1) {
2018
+ handlerSets.sort((a, b) => {
2019
+ return a.score - b.score;
2020
+ });
2021
+ }
2022
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2023
+ }
2024
+ }, "_Node");
2025
+
2026
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/router/trie-router/router.js
2027
+ var TrieRouter = /* @__PURE__ */ __name(class {
2028
+ name = "TrieRouter";
2029
+ #node;
2030
+ constructor() {
2031
+ this.#node = new Node2();
2032
+ }
2033
+ add(method, path, handler) {
2034
+ const results = checkOptionalParameter(path);
2035
+ if (results) {
2036
+ for (let i = 0, len = results.length; i < len; i++) {
2037
+ this.#node.insert(method, results[i], handler);
2038
+ }
2039
+ return;
2040
+ }
2041
+ this.#node.insert(method, path, handler);
2042
+ }
2043
+ match(method, path) {
2044
+ return this.#node.search(method, path);
2045
+ }
2046
+ }, "TrieRouter");
2047
+
2048
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/hono.js
2049
+ var Hono2 = /* @__PURE__ */ __name(class extends Hono {
2050
+ /**
2051
+ * Creates an instance of the Hono class.
2052
+ *
2053
+ * @param options - Optional configuration options for the Hono instance.
2054
+ */
2055
+ constructor(options = {}) {
2056
+ super(options);
2057
+ this.router = options.router ?? new SmartRouter({
2058
+ routers: [new RegExpRouter(), new TrieRouter()]
2059
+ });
2060
+ }
2061
+ }, "Hono");
2062
+
2063
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/middleware/cors/index.js
2064
+ var cors = /* @__PURE__ */ __name((options) => {
2065
+ const defaults = {
2066
+ origin: "*",
2067
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
2068
+ allowHeaders: [],
2069
+ exposeHeaders: []
2070
+ };
2071
+ const opts = {
2072
+ ...defaults,
2073
+ ...options
2074
+ };
2075
+ const findAllowOrigin = ((optsOrigin) => {
2076
+ if (typeof optsOrigin === "string") {
2077
+ if (optsOrigin === "*") {
2078
+ return () => optsOrigin;
2079
+ } else {
2080
+ return (origin) => optsOrigin === origin ? origin : null;
2081
+ }
2082
+ } else if (typeof optsOrigin === "function") {
2083
+ return optsOrigin;
2084
+ } else {
2085
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2086
+ }
2087
+ })(opts.origin);
2088
+ const findAllowMethods = ((optsAllowMethods) => {
2089
+ if (typeof optsAllowMethods === "function") {
2090
+ return optsAllowMethods;
2091
+ } else if (Array.isArray(optsAllowMethods)) {
2092
+ return () => optsAllowMethods;
2093
+ } else {
2094
+ return () => [];
2095
+ }
2096
+ })(opts.allowMethods);
2097
+ return /* @__PURE__ */ __name(async function cors2(c, next) {
2098
+ function set(key, value) {
2099
+ c.res.headers.set(key, value);
2100
+ }
2101
+ __name(set, "set");
2102
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2103
+ if (allowOrigin) {
2104
+ set("Access-Control-Allow-Origin", allowOrigin);
2105
+ }
2106
+ if (opts.credentials) {
2107
+ set("Access-Control-Allow-Credentials", "true");
2108
+ }
2109
+ if (opts.exposeHeaders?.length) {
2110
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2111
+ }
2112
+ if (c.req.method === "OPTIONS") {
2113
+ if (opts.origin !== "*") {
2114
+ set("Vary", "Origin");
2115
+ }
2116
+ if (opts.maxAge != null) {
2117
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2118
+ }
2119
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2120
+ if (allowMethods.length) {
2121
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2122
+ }
2123
+ let headers = opts.allowHeaders;
2124
+ if (!headers?.length) {
2125
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2126
+ if (requestHeaders) {
2127
+ headers = requestHeaders.split(/\s*,\s*/);
2128
+ }
2129
+ }
2130
+ if (headers?.length) {
2131
+ set("Access-Control-Allow-Headers", headers.join(","));
2132
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2133
+ }
2134
+ c.res.headers.delete("Content-Length");
2135
+ c.res.headers.delete("Content-Type");
2136
+ return new Response(null, {
2137
+ headers: c.res.headers,
2138
+ status: 204,
2139
+ statusText: "No Content"
2140
+ });
2141
+ }
2142
+ await next();
2143
+ if (opts.origin !== "*") {
2144
+ c.header("Vary", "Origin", { append: true });
2145
+ }
2146
+ }, "cors2");
2147
+ }, "cors");
2148
+
2149
+ // ../../node_modules/.pnpm/hono@4.12.2/node_modules/hono/dist/helper/factory/index.js
2150
+ var createMiddleware = /* @__PURE__ */ __name((middleware) => middleware, "createMiddleware");
2151
+
2152
+ // src/middleware/auth.ts
2153
+ var authMiddleware = createMiddleware(async (c, next) => {
2154
+ const authHeader = c.req.header("Authorization");
2155
+ if (!authHeader?.startsWith("Bearer ")) {
2156
+ return c.json({ error: "Missing or invalid Authorization header" }, 401);
2157
+ }
2158
+ const token = authHeader.slice(7);
2159
+ const colonIndex = token.indexOf(":");
2160
+ if (colonIndex === -1) {
2161
+ return c.json({ error: "Invalid token format" }, 401);
2162
+ }
2163
+ const deviceId = token.slice(0, colonIndex);
2164
+ const providedHmac = token.slice(colonIndex + 1);
2165
+ const encoder2 = new TextEncoder();
2166
+ const key = await crypto.subtle.importKey(
2167
+ "raw",
2168
+ encoder2.encode(c.env.AUTH_SECRET),
2169
+ { name: "HMAC", hash: "SHA-256" },
2170
+ false,
2171
+ ["sign"]
2172
+ );
2173
+ const signature = await crypto.subtle.sign("HMAC", key, encoder2.encode(deviceId));
2174
+ const expectedHmac = Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
2175
+ if (expectedHmac.length !== providedHmac.length) {
2176
+ return c.json({ error: "Invalid token" }, 401);
2177
+ }
2178
+ const expectedBytes = encoder2.encode(expectedHmac);
2179
+ const providedBytes = encoder2.encode(providedHmac);
2180
+ let mismatch = 0;
2181
+ for (let i = 0; i < expectedBytes.length; i++) {
2182
+ mismatch |= expectedBytes[i] ^ providedBytes[i];
2183
+ }
2184
+ if (mismatch !== 0) {
2185
+ return c.json({ error: "Invalid token" }, 401);
2186
+ }
2187
+ c.set("deviceId", deviceId);
2188
+ await next();
2189
+ });
2190
+
2191
+ // ../shared/dist/constants.js
2192
+ var PACKAGE_VERSION = "0.1.1";
2193
+ var MANIFEST_KEY = ".obsidian-r2-sync/manifest.json";
2194
+ var FILES_PREFIX = "vault/";
2195
+ var PRESIGNED_URL_EXPIRY = 900;
2196
+
2197
+ // src/routes/health.ts
2198
+ var healthRoutes = new Hono2();
2199
+ healthRoutes.get("/", (c) => {
2200
+ return c.json({
2201
+ ok: true,
2202
+ version: PACKAGE_VERSION,
2203
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2204
+ });
2205
+ });
2206
+
2207
+ // src/routes/manifest.ts
2208
+ var manifestRoutes = new Hono2();
2209
+ manifestRoutes.get("/", async (c) => {
2210
+ const object = await c.env.BUCKET.get(MANIFEST_KEY);
2211
+ if (!object) {
2212
+ return c.json(
2213
+ {
2214
+ manifest: { files: {}, lastUpdated: (/* @__PURE__ */ new Date()).toISOString(), lastUpdatedBy: "" },
2215
+ etag: null
2216
+ },
2217
+ 200
2218
+ );
2219
+ }
2220
+ const manifest = await object.json();
2221
+ return c.json(
2222
+ { manifest, etag: object.httpEtag },
2223
+ 200,
2224
+ { ETag: object.httpEtag }
2225
+ );
2226
+ });
2227
+ manifestRoutes.put("/", async (c) => {
2228
+ const ifMatch = c.req.header("If-Match");
2229
+ const existingObject = await c.env.BUCKET.head(MANIFEST_KEY);
2230
+ if (existingObject && !ifMatch) {
2231
+ return c.json({ error: "If-Match header required for manifest updates" }, 428);
2232
+ }
2233
+ const body = await c.req.text();
2234
+ try {
2235
+ const putOptions = {};
2236
+ if (ifMatch) {
2237
+ putOptions.onlyIf = { etagMatches: ifMatch.replace(/"/g, "") };
2238
+ }
2239
+ const result = await c.env.BUCKET.put(MANIFEST_KEY, body, {
2240
+ ...putOptions,
2241
+ httpMetadata: { contentType: "application/json" }
2242
+ });
2243
+ if (result === null) {
2244
+ return c.json({ error: "Manifest has been modified by another device" }, 412);
2245
+ }
2246
+ return c.json(
2247
+ { ok: true, etag: result.httpEtag },
2248
+ 200,
2249
+ { ETag: result.httpEtag }
2250
+ );
2251
+ } catch (err) {
2252
+ return c.json({ error: "Failed to update manifest" }, 500);
2253
+ }
2254
+ });
2255
+
2256
+ // ../../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs
2257
+ var encoder = new TextEncoder();
2258
+ var HOST_SERVICES = {
2259
+ appstream2: "appstream",
2260
+ cloudhsmv2: "cloudhsm",
2261
+ email: "ses",
2262
+ marketplace: "aws-marketplace",
2263
+ mobile: "AWSMobileHubService",
2264
+ pinpoint: "mobiletargeting",
2265
+ queue: "sqs",
2266
+ "git-codecommit": "codecommit",
2267
+ "mturk-requester-sandbox": "mturk-requester",
2268
+ "personalize-runtime": "personalize"
2269
+ };
2270
+ var UNSIGNABLE_HEADERS = /* @__PURE__ */ new Set([
2271
+ "authorization",
2272
+ "content-type",
2273
+ "content-length",
2274
+ "user-agent",
2275
+ "presigned-expires",
2276
+ "expect",
2277
+ "x-amzn-trace-id",
2278
+ "range",
2279
+ "connection"
2280
+ ]);
2281
+ var AwsClient = class {
2282
+ constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {
2283
+ if (accessKeyId == null)
2284
+ throw new TypeError("accessKeyId is a required option");
2285
+ if (secretAccessKey == null)
2286
+ throw new TypeError("secretAccessKey is a required option");
2287
+ this.accessKeyId = accessKeyId;
2288
+ this.secretAccessKey = secretAccessKey;
2289
+ this.sessionToken = sessionToken;
2290
+ this.service = service;
2291
+ this.region = region;
2292
+ this.cache = cache || /* @__PURE__ */ new Map();
2293
+ this.retries = retries != null ? retries : 10;
2294
+ this.initRetryMs = initRetryMs || 50;
2295
+ }
2296
+ async sign(input, init) {
2297
+ if (input instanceof Request) {
2298
+ const { method, url, headers, body } = input;
2299
+ init = Object.assign({ method, url, headers }, init);
2300
+ if (init.body == null && headers.has("Content-Type")) {
2301
+ init.body = body != null && headers.has("X-Amz-Content-Sha256") ? body : await input.clone().arrayBuffer();
2302
+ }
2303
+ input = url;
2304
+ }
2305
+ const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));
2306
+ const signed = Object.assign({}, init, await signer.sign());
2307
+ delete signed.aws;
2308
+ try {
2309
+ return new Request(signed.url.toString(), signed);
2310
+ } catch (e) {
2311
+ if (e instanceof TypeError) {
2312
+ return new Request(signed.url.toString(), Object.assign({ duplex: "half" }, signed));
2313
+ }
2314
+ throw e;
2315
+ }
2316
+ }
2317
+ async fetch(input, init) {
2318
+ for (let i = 0; i <= this.retries; i++) {
2319
+ const fetched = fetch(await this.sign(input, init));
2320
+ if (i === this.retries) {
2321
+ return fetched;
2322
+ }
2323
+ const res = await fetched;
2324
+ if (res.status < 500 && res.status !== 429) {
2325
+ return res;
2326
+ }
2327
+ await new Promise((resolve) => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));
2328
+ }
2329
+ throw new Error("An unknown error occurred, ensure retries is not negative");
2330
+ }
2331
+ };
2332
+ __name(AwsClient, "AwsClient");
2333
+ var AwsV4Signer = class {
2334
+ constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {
2335
+ if (url == null)
2336
+ throw new TypeError("url is a required option");
2337
+ if (accessKeyId == null)
2338
+ throw new TypeError("accessKeyId is a required option");
2339
+ if (secretAccessKey == null)
2340
+ throw new TypeError("secretAccessKey is a required option");
2341
+ this.method = method || (body ? "POST" : "GET");
2342
+ this.url = new URL(url);
2343
+ this.headers = new Headers(headers || {});
2344
+ this.body = body;
2345
+ this.accessKeyId = accessKeyId;
2346
+ this.secretAccessKey = secretAccessKey;
2347
+ this.sessionToken = sessionToken;
2348
+ let guessedService, guessedRegion;
2349
+ if (!service || !region) {
2350
+ [guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);
2351
+ }
2352
+ this.service = service || guessedService || "";
2353
+ this.region = region || guessedRegion || "us-east-1";
2354
+ this.cache = cache || /* @__PURE__ */ new Map();
2355
+ this.datetime = datetime || (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
2356
+ this.signQuery = signQuery;
2357
+ this.appendSessionToken = appendSessionToken || this.service === "iotdevicegateway";
2358
+ this.headers.delete("Host");
2359
+ if (this.service === "s3" && !this.signQuery && !this.headers.has("X-Amz-Content-Sha256")) {
2360
+ this.headers.set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD");
2361
+ }
2362
+ const params = this.signQuery ? this.url.searchParams : this.headers;
2363
+ params.set("X-Amz-Date", this.datetime);
2364
+ if (this.sessionToken && !this.appendSessionToken) {
2365
+ params.set("X-Amz-Security-Token", this.sessionToken);
2366
+ }
2367
+ this.signableHeaders = ["host", ...this.headers.keys()].filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header)).sort();
2368
+ this.signedHeaders = this.signableHeaders.join(";");
2369
+ this.canonicalHeaders = this.signableHeaders.map((header) => header + ":" + (header === "host" ? this.url.host : (this.headers.get(header) || "").replace(/\s+/g, " "))).join("\n");
2370
+ this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, "aws4_request"].join("/");
2371
+ if (this.signQuery) {
2372
+ if (this.service === "s3" && !params.has("X-Amz-Expires")) {
2373
+ params.set("X-Amz-Expires", "86400");
2374
+ }
2375
+ params.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
2376
+ params.set("X-Amz-Credential", this.accessKeyId + "/" + this.credentialString);
2377
+ params.set("X-Amz-SignedHeaders", this.signedHeaders);
2378
+ }
2379
+ if (this.service === "s3") {
2380
+ try {
2381
+ this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\+/g, " "));
2382
+ } catch (e) {
2383
+ this.encodedPath = this.url.pathname;
2384
+ }
2385
+ } else {
2386
+ this.encodedPath = this.url.pathname.replace(/\/+/g, "/");
2387
+ }
2388
+ if (!singleEncode) {
2389
+ this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, "/");
2390
+ }
2391
+ this.encodedPath = encodeRfc3986(this.encodedPath);
2392
+ const seenKeys = /* @__PURE__ */ new Set();
2393
+ this.encodedSearch = [...this.url.searchParams].filter(([k]) => {
2394
+ if (!k)
2395
+ return false;
2396
+ if (this.service === "s3") {
2397
+ if (seenKeys.has(k))
2398
+ return false;
2399
+ seenKeys.add(k);
2400
+ }
2401
+ return true;
2402
+ }).map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p)))).sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0).map((pair) => pair.join("=")).join("&");
2403
+ }
2404
+ async sign() {
2405
+ if (this.signQuery) {
2406
+ this.url.searchParams.set("X-Amz-Signature", await this.signature());
2407
+ if (this.sessionToken && this.appendSessionToken) {
2408
+ this.url.searchParams.set("X-Amz-Security-Token", this.sessionToken);
2409
+ }
2410
+ } else {
2411
+ this.headers.set("Authorization", await this.authHeader());
2412
+ }
2413
+ return {
2414
+ method: this.method,
2415
+ url: this.url,
2416
+ headers: this.headers,
2417
+ body: this.body
2418
+ };
2419
+ }
2420
+ async authHeader() {
2421
+ return [
2422
+ "AWS4-HMAC-SHA256 Credential=" + this.accessKeyId + "/" + this.credentialString,
2423
+ "SignedHeaders=" + this.signedHeaders,
2424
+ "Signature=" + await this.signature()
2425
+ ].join(", ");
2426
+ }
2427
+ async signature() {
2428
+ const date = this.datetime.slice(0, 8);
2429
+ const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();
2430
+ let kCredentials = this.cache.get(cacheKey);
2431
+ if (!kCredentials) {
2432
+ const kDate = await hmac("AWS4" + this.secretAccessKey, date);
2433
+ const kRegion = await hmac(kDate, this.region);
2434
+ const kService = await hmac(kRegion, this.service);
2435
+ kCredentials = await hmac(kService, "aws4_request");
2436
+ this.cache.set(cacheKey, kCredentials);
2437
+ }
2438
+ return buf2hex(await hmac(kCredentials, await this.stringToSign()));
2439
+ }
2440
+ async stringToSign() {
2441
+ return [
2442
+ "AWS4-HMAC-SHA256",
2443
+ this.datetime,
2444
+ this.credentialString,
2445
+ buf2hex(await hash(await this.canonicalString()))
2446
+ ].join("\n");
2447
+ }
2448
+ async canonicalString() {
2449
+ return [
2450
+ this.method.toUpperCase(),
2451
+ this.encodedPath,
2452
+ this.encodedSearch,
2453
+ this.canonicalHeaders + "\n",
2454
+ this.signedHeaders,
2455
+ await this.hexBodyHash()
2456
+ ].join("\n");
2457
+ }
2458
+ async hexBodyHash() {
2459
+ let hashHeader = this.headers.get("X-Amz-Content-Sha256") || (this.service === "s3" && this.signQuery ? "UNSIGNED-PAYLOAD" : null);
2460
+ if (hashHeader == null) {
2461
+ if (this.body && typeof this.body !== "string" && !("byteLength" in this.body)) {
2462
+ throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");
2463
+ }
2464
+ hashHeader = buf2hex(await hash(this.body || ""));
2465
+ }
2466
+ return hashHeader;
2467
+ }
2468
+ };
2469
+ __name(AwsV4Signer, "AwsV4Signer");
2470
+ async function hmac(key, string) {
2471
+ const cryptoKey = await crypto.subtle.importKey(
2472
+ "raw",
2473
+ typeof key === "string" ? encoder.encode(key) : key,
2474
+ { name: "HMAC", hash: { name: "SHA-256" } },
2475
+ false,
2476
+ ["sign"]
2477
+ );
2478
+ return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(string));
2479
+ }
2480
+ __name(hmac, "hmac");
2481
+ async function hash(content) {
2482
+ return crypto.subtle.digest("SHA-256", typeof content === "string" ? encoder.encode(content) : content);
2483
+ }
2484
+ __name(hash, "hash");
2485
+ var HEX_CHARS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
2486
+ function buf2hex(arrayBuffer) {
2487
+ const buffer = new Uint8Array(arrayBuffer);
2488
+ let out = "";
2489
+ for (let idx = 0; idx < buffer.length; idx++) {
2490
+ const n = buffer[idx];
2491
+ out += HEX_CHARS[n >>> 4 & 15];
2492
+ out += HEX_CHARS[n & 15];
2493
+ }
2494
+ return out;
2495
+ }
2496
+ __name(buf2hex, "buf2hex");
2497
+ function encodeRfc3986(urlEncodedStr) {
2498
+ return urlEncodedStr.replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
2499
+ }
2500
+ __name(encodeRfc3986, "encodeRfc3986");
2501
+ function guessServiceRegion(url, headers) {
2502
+ const { hostname, pathname } = url;
2503
+ if (hostname.endsWith(".on.aws")) {
2504
+ const match3 = hostname.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);
2505
+ return match3 != null ? ["lambda", match3[1] || ""] : ["", ""];
2506
+ }
2507
+ if (hostname.endsWith(".r2.cloudflarestorage.com")) {
2508
+ return ["s3", "auto"];
2509
+ }
2510
+ if (hostname.endsWith(".backblazeb2.com")) {
2511
+ const match3 = hostname.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);
2512
+ return match3 != null ? ["s3", match3[1] || ""] : ["", ""];
2513
+ }
2514
+ const match2 = hostname.replace("dualstack.", "").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/);
2515
+ let service = match2 && match2[1] || "";
2516
+ let region = match2 && match2[2];
2517
+ if (region === "us-gov") {
2518
+ region = "us-gov-west-1";
2519
+ } else if (region === "s3" || region === "s3-accelerate") {
2520
+ region = "us-east-1";
2521
+ service = "s3";
2522
+ } else if (service === "iot") {
2523
+ if (hostname.startsWith("iot.")) {
2524
+ service = "execute-api";
2525
+ } else if (hostname.startsWith("data.jobs.iot.")) {
2526
+ service = "iot-jobs-data";
2527
+ } else {
2528
+ service = pathname === "/mqtt" ? "iotdevicegateway" : "iotdata";
2529
+ }
2530
+ } else if (service === "autoscaling") {
2531
+ const targetPrefix = (headers.get("X-Amz-Target") || "").split(".")[0];
2532
+ if (targetPrefix === "AnyScaleFrontendService") {
2533
+ service = "application-autoscaling";
2534
+ } else if (targetPrefix === "AnyScaleScalingPlannerFrontendService") {
2535
+ service = "autoscaling-plans";
2536
+ }
2537
+ } else if (region == null && service.startsWith("s3-")) {
2538
+ region = service.slice(3).replace(/^fips-|^external-1/, "");
2539
+ service = "s3";
2540
+ } else if (service.endsWith("-fips")) {
2541
+ service = service.slice(0, -5);
2542
+ } else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) {
2543
+ [service, region] = [region, service];
2544
+ }
2545
+ return [HOST_SERVICES[service] || service, region || ""];
2546
+ }
2547
+ __name(guessServiceRegion, "guessServiceRegion");
2548
+
2549
+ // src/routes/files.ts
2550
+ var fileRoutes = new Hono2();
2551
+ function validatePath(path) {
2552
+ if (!path || typeof path !== "string") {
2553
+ return "path is required";
2554
+ }
2555
+ if (path.includes("..") || path.startsWith("/") || path.startsWith("\\")) {
2556
+ return "invalid path: directory traversal not allowed";
2557
+ }
2558
+ if (path.startsWith(".obsidian-r2-sync/")) {
2559
+ return "invalid path: internal keys are not accessible";
2560
+ }
2561
+ return null;
2562
+ }
2563
+ __name(validatePath, "validatePath");
2564
+ fileRoutes.post("/upload-url", async (c) => {
2565
+ const { path } = await c.req.json();
2566
+ const pathError = validatePath(path);
2567
+ if (pathError) {
2568
+ return c.json({ error: pathError }, 400);
2569
+ }
2570
+ const r2Key = `${FILES_PREFIX}${path}`;
2571
+ const url = await generatePresignedUrl(c.env, r2Key, "PUT");
2572
+ return c.json({
2573
+ url,
2574
+ expiresAt: new Date(Date.now() + PRESIGNED_URL_EXPIRY * 1e3).toISOString()
2575
+ });
2576
+ });
2577
+ fileRoutes.post("/download-url", async (c) => {
2578
+ const { path } = await c.req.json();
2579
+ const pathError = validatePath(path);
2580
+ if (pathError) {
2581
+ return c.json({ error: pathError }, 400);
2582
+ }
2583
+ const r2Key = `${FILES_PREFIX}${path}`;
2584
+ const url = await generatePresignedUrl(c.env, r2Key, "GET");
2585
+ return c.json({
2586
+ url,
2587
+ expiresAt: new Date(Date.now() + PRESIGNED_URL_EXPIRY * 1e3).toISOString()
2588
+ });
2589
+ });
2590
+ fileRoutes.post("/delete", async (c) => {
2591
+ const { paths } = await c.req.json();
2592
+ if (!paths?.length) {
2593
+ return c.json({ error: "paths array is required" }, 400);
2594
+ }
2595
+ for (const path of paths) {
2596
+ const pathError = validatePath(path);
2597
+ if (pathError) {
2598
+ return c.json({ error: `${pathError} (${path})` }, 400);
2599
+ }
2600
+ }
2601
+ const keys = paths.map((p) => `${FILES_PREFIX}${p}`);
2602
+ await c.env.BUCKET.delete(keys);
2603
+ return c.json({ ok: true, deleted: paths.length });
2604
+ });
2605
+ async function generatePresignedUrl(env, key, method) {
2606
+ const client = new AwsClient({
2607
+ accessKeyId: env.CF_ACCESS_KEY_ID,
2608
+ secretAccessKey: env.CF_SECRET_ACCESS_KEY,
2609
+ service: "s3",
2610
+ region: "auto"
2611
+ });
2612
+ const endpoint = `https://${env.CF_ACCOUNT_ID}.r2.cloudflarestorage.com/${env.BUCKET_NAME}/${key}?X-Amz-Expires=${PRESIGNED_URL_EXPIRY}`;
2613
+ const signed = await client.sign(
2614
+ new Request(endpoint, { method }),
2615
+ { aws: { signQuery: true, allHeaders: true } }
2616
+ );
2617
+ return signed.url;
2618
+ }
2619
+ __name(generatePresignedUrl, "generatePresignedUrl");
2620
+
2621
+ // src/index.ts
2622
+ var app = new Hono2();
2623
+ app.use("*", cors());
2624
+ app.route("/health", healthRoutes);
2625
+ app.use("*", authMiddleware);
2626
+ app.route("/manifest", manifestRoutes);
2627
+ app.route("/files", fileRoutes);
2628
+ var src_default = app;
2629
+ export {
2630
+ src_default as default
2631
+ };
2632
+ /*! Bundled license information:
2633
+
2634
+ aws4fetch/dist/aws4fetch.esm.mjs:
2635
+ (**
2636
+ * @license MIT <https://opensource.org/licenses/MIT>
2637
+ * @copyright Michael Hart 2024
2638
+ *)
2639
+ */
2640
+ //# sourceMappingURL=index.js.map