@gusto/baerly-storage 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.
Files changed (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,1756 @@
1
+ import { n as logSeqStartOf } from "./current-json-BkatBzF7.js";
2
+ import { t as BaerlyError } from "./errors-DOdL95kK.js";
3
+ import { c as lsnParts, n as runAllWithMeta, r as runByIdWithMeta } from "./query-DcSbFLJt.js";
4
+ import { p as validateWire } from "./snapshot-z_N9hpTe.js";
5
+ import { t as EMPTY_PREDICATE_WIRE } from "./wire-izfGZDvr.js";
6
+ import { i as serializeError, l as getLogger, s as CATEGORY, u as errorEnvelope } from "./observability-2IDYRuZK.js";
7
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js
8
+ var compose = (middleware, onError, onNotFound) => {
9
+ return (context, next) => {
10
+ let index = -1;
11
+ return dispatch(0);
12
+ async function dispatch(i) {
13
+ if (i <= index) throw new Error("next() called multiple times");
14
+ index = i;
15
+ let res;
16
+ let isError = false;
17
+ let handler;
18
+ if (middleware[i]) {
19
+ handler = middleware[i][0][0];
20
+ context.req.routeIndex = i;
21
+ } else handler = i === middleware.length && next || void 0;
22
+ if (handler) try {
23
+ res = await handler(context, () => dispatch(i + 1));
24
+ } catch (err) {
25
+ if (err instanceof Error && onError) {
26
+ context.error = err;
27
+ res = await onError(err, context);
28
+ isError = true;
29
+ } else throw err;
30
+ }
31
+ else if (context.finalized === false && onNotFound) res = await onNotFound(context);
32
+ if (res && (context.finalized === false || isError)) context.res = res;
33
+ return context;
34
+ }
35
+ };
36
+ };
37
+ //#endregion
38
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js
39
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
40
+ //#endregion
41
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js
42
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
43
+ const { all = false, dot = false } = options;
44
+ const contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
45
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) return parseFormData(request, {
46
+ all,
47
+ dot
48
+ });
49
+ return {};
50
+ };
51
+ async function parseFormData(request, options) {
52
+ const formData = await request.formData();
53
+ if (formData) return convertFormDataToBodyData(formData, options);
54
+ return {};
55
+ }
56
+ function convertFormDataToBodyData(formData, options) {
57
+ const form = /* @__PURE__ */ Object.create(null);
58
+ formData.forEach((value, key) => {
59
+ if (!(options.all || key.endsWith("[]"))) form[key] = value;
60
+ else handleParsingAllValues(form, key, value);
61
+ });
62
+ if (options.dot) Object.entries(form).forEach(([key, value]) => {
63
+ if (key.includes(".")) {
64
+ handleParsingNestedValues(form, key, value);
65
+ delete form[key];
66
+ }
67
+ });
68
+ return form;
69
+ }
70
+ var handleParsingAllValues = (form, key, value) => {
71
+ if (form[key] !== void 0) if (Array.isArray(form[key])) form[key].push(value);
72
+ else form[key] = [form[key], value];
73
+ else if (!key.endsWith("[]")) form[key] = value;
74
+ else form[key] = [value];
75
+ };
76
+ var handleParsingNestedValues = (form, key, value) => {
77
+ if (/(?:^|\.)__proto__\./.test(key)) return;
78
+ let nestedForm = form;
79
+ const keys = key.split(".");
80
+ keys.forEach((key2, index) => {
81
+ if (index === keys.length - 1) nestedForm[key2] = value;
82
+ else {
83
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) nestedForm[key2] = /* @__PURE__ */ Object.create(null);
84
+ nestedForm = nestedForm[key2];
85
+ }
86
+ });
87
+ };
88
+ //#endregion
89
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js
90
+ var tryDecode = (str, decoder) => {
91
+ try {
92
+ return decoder(str);
93
+ } catch {
94
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
95
+ try {
96
+ return decoder(match);
97
+ } catch {
98
+ return match;
99
+ }
100
+ });
101
+ }
102
+ };
103
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
104
+ var getPath = (request) => {
105
+ const url = request.url;
106
+ const start = url.indexOf("/", url.indexOf(":") + 4);
107
+ let i = start;
108
+ for (; i < url.length; i++) {
109
+ const charCode = url.charCodeAt(i);
110
+ if (charCode === 37) {
111
+ const queryIndex = url.indexOf("?", i);
112
+ const hashIndex = url.indexOf("#", i);
113
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
114
+ const path = url.slice(start, end);
115
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
116
+ } else if (charCode === 63 || charCode === 35) break;
117
+ }
118
+ return url.slice(start, i);
119
+ };
120
+ var getPathNoStrict = (request) => {
121
+ const result = getPath(request);
122
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
123
+ };
124
+ var mergePath = (base, sub, ...rest) => {
125
+ if (rest.length) sub = mergePath(sub, ...rest);
126
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
127
+ };
128
+ var _decodeURI = (value) => {
129
+ if (!/[%+]/.test(value)) return value;
130
+ if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
131
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
132
+ };
133
+ var _getQueryParam = (url, key, multiple) => {
134
+ let encoded;
135
+ if (!multiple && key && !/[%+]/.test(key)) {
136
+ let keyIndex2 = url.indexOf("?", 8);
137
+ if (keyIndex2 === -1) return;
138
+ if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
139
+ while (keyIndex2 !== -1) {
140
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
141
+ if (trailingKeyCode === 61) {
142
+ const valueIndex = keyIndex2 + key.length + 2;
143
+ const endIndex = url.indexOf("&", valueIndex);
144
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
145
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
146
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
147
+ }
148
+ encoded = /[%+]/.test(url);
149
+ if (!encoded) return;
150
+ }
151
+ const results = {};
152
+ encoded ??= /[%+]/.test(url);
153
+ let keyIndex = url.indexOf("?", 8);
154
+ while (keyIndex !== -1) {
155
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
156
+ let valueIndex = url.indexOf("=", keyIndex);
157
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
158
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
159
+ if (encoded) name = _decodeURI(name);
160
+ keyIndex = nextKeyIndex;
161
+ if (name === "") continue;
162
+ let value;
163
+ if (valueIndex === -1) value = "";
164
+ else {
165
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
166
+ if (encoded) value = _decodeURI(value);
167
+ }
168
+ if (multiple) {
169
+ if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
170
+ results[name].push(value);
171
+ } else results[name] ??= value;
172
+ }
173
+ return key ? results[key] : results;
174
+ };
175
+ var getQueryParam = _getQueryParam;
176
+ var getQueryParams = (url, key) => {
177
+ return _getQueryParam(url, key, true);
178
+ };
179
+ var decodeURIComponent_ = decodeURIComponent;
180
+ //#endregion
181
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js
182
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
183
+ var HonoRequest = class {
184
+ /**
185
+ * `.raw` can get the raw Request object.
186
+ *
187
+ * @see {@link https://hono.dev/docs/api/request#raw}
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * // For Cloudflare Workers
192
+ * app.post('/', async (c) => {
193
+ * const metadata = c.req.raw.cf?.hostMetadata?
194
+ * ...
195
+ * })
196
+ * ```
197
+ */
198
+ raw;
199
+ #validatedData;
200
+ #matchResult;
201
+ routeIndex = 0;
202
+ /**
203
+ * `.path` can get the pathname of the request.
204
+ *
205
+ * @see {@link https://hono.dev/docs/api/request#path}
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * app.get('/about/me', (c) => {
210
+ * const pathname = c.req.path // `/about/me`
211
+ * })
212
+ * ```
213
+ */
214
+ path;
215
+ bodyCache = {};
216
+ constructor(request, path = "/", matchResult = [[]]) {
217
+ this.raw = request;
218
+ this.path = path;
219
+ this.#matchResult = matchResult;
220
+ this.#validatedData = {};
221
+ }
222
+ param(key) {
223
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
224
+ }
225
+ #getDecodedParam(key) {
226
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
227
+ const param = this.#getParamValue(paramKey);
228
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
229
+ }
230
+ #getAllDecodedParams() {
231
+ const decoded = {};
232
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
233
+ for (const key of keys) {
234
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
235
+ if (value !== void 0) decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
236
+ }
237
+ return decoded;
238
+ }
239
+ #getParamValue(paramKey) {
240
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
241
+ }
242
+ query(key) {
243
+ return getQueryParam(this.url, key);
244
+ }
245
+ queries(key) {
246
+ return getQueryParams(this.url, key);
247
+ }
248
+ header(name) {
249
+ if (name) return this.raw.headers.get(name) ?? void 0;
250
+ const headerData = {};
251
+ this.raw.headers.forEach((value, key) => {
252
+ headerData[key] = value;
253
+ });
254
+ return headerData;
255
+ }
256
+ async parseBody(options) {
257
+ return parseBody(this, options);
258
+ }
259
+ #cachedBody = (key) => {
260
+ const { bodyCache, raw } = this;
261
+ const cachedBody = bodyCache[key];
262
+ if (cachedBody) return cachedBody;
263
+ const anyCachedKey = Object.keys(bodyCache)[0];
264
+ if (anyCachedKey) return bodyCache[anyCachedKey].then((body) => {
265
+ if (anyCachedKey === "json") body = JSON.stringify(body);
266
+ return new Response(body)[key]();
267
+ });
268
+ return bodyCache[key] = raw[key]();
269
+ };
270
+ /**
271
+ * `.json()` can parse Request body of type `application/json`
272
+ *
273
+ * @see {@link https://hono.dev/docs/api/request#json}
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * app.post('/entry', async (c) => {
278
+ * const body = await c.req.json()
279
+ * })
280
+ * ```
281
+ */
282
+ json() {
283
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
284
+ }
285
+ /**
286
+ * `.text()` can parse Request body of type `text/plain`
287
+ *
288
+ * @see {@link https://hono.dev/docs/api/request#text}
289
+ *
290
+ * @example
291
+ * ```ts
292
+ * app.post('/entry', async (c) => {
293
+ * const body = await c.req.text()
294
+ * })
295
+ * ```
296
+ */
297
+ text() {
298
+ return this.#cachedBody("text");
299
+ }
300
+ /**
301
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
302
+ *
303
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * app.post('/entry', async (c) => {
308
+ * const body = await c.req.arrayBuffer()
309
+ * })
310
+ * ```
311
+ */
312
+ arrayBuffer() {
313
+ return this.#cachedBody("arrayBuffer");
314
+ }
315
+ /**
316
+ * `.bytes()` parses the request body as a `Uint8Array`.
317
+ *
318
+ * @see {@link https://hono.dev/docs/api/request#bytes}
319
+ *
320
+ * @example
321
+ * ```ts
322
+ * app.post('/entry', async (c) => {
323
+ * const body = await c.req.bytes()
324
+ * })
325
+ * ```
326
+ */
327
+ bytes() {
328
+ return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
329
+ }
330
+ /**
331
+ * Parses the request body as a `Blob`.
332
+ * @example
333
+ * ```ts
334
+ * app.post('/entry', async (c) => {
335
+ * const body = await c.req.blob();
336
+ * });
337
+ * ```
338
+ * @see https://hono.dev/docs/api/request#blob
339
+ */
340
+ blob() {
341
+ return this.#cachedBody("blob");
342
+ }
343
+ /**
344
+ * Parses the request body as `FormData`.
345
+ * @example
346
+ * ```ts
347
+ * app.post('/entry', async (c) => {
348
+ * const body = await c.req.formData();
349
+ * });
350
+ * ```
351
+ * @see https://hono.dev/docs/api/request#formdata
352
+ */
353
+ formData() {
354
+ return this.#cachedBody("formData");
355
+ }
356
+ /**
357
+ * Adds validated data to the request.
358
+ *
359
+ * @param target - The target of the validation.
360
+ * @param data - The validated data to add.
361
+ */
362
+ addValidatedData(target, data) {
363
+ this.#validatedData[target] = data;
364
+ }
365
+ valid(target) {
366
+ return this.#validatedData[target];
367
+ }
368
+ /**
369
+ * `.url()` can get the request url strings.
370
+ *
371
+ * @see {@link https://hono.dev/docs/api/request#url}
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * app.get('/about/me', (c) => {
376
+ * const url = c.req.url // `http://localhost:8787/about/me`
377
+ * ...
378
+ * })
379
+ * ```
380
+ */
381
+ get url() {
382
+ return this.raw.url;
383
+ }
384
+ /**
385
+ * `.method()` can get the method name of the request.
386
+ *
387
+ * @see {@link https://hono.dev/docs/api/request#method}
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * app.get('/about/me', (c) => {
392
+ * const method = c.req.method // `GET`
393
+ * })
394
+ * ```
395
+ */
396
+ get method() {
397
+ return this.raw.method;
398
+ }
399
+ get [GET_MATCH_RESULT]() {
400
+ return this.#matchResult;
401
+ }
402
+ /**
403
+ * `.matchedRoutes()` can return a matched route in the handler
404
+ *
405
+ * @deprecated
406
+ *
407
+ * Use matchedRoutes helper defined in "hono/route" instead.
408
+ *
409
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * app.use('*', async function logger(c, next) {
414
+ * await next()
415
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
416
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
417
+ * console.log(
418
+ * method,
419
+ * ' ',
420
+ * path,
421
+ * ' '.repeat(Math.max(10 - path.length, 0)),
422
+ * name,
423
+ * i === c.req.routeIndex ? '<- respond from here' : ''
424
+ * )
425
+ * })
426
+ * })
427
+ * ```
428
+ */
429
+ get matchedRoutes() {
430
+ return this.#matchResult[0].map(([[, route]]) => route);
431
+ }
432
+ /**
433
+ * `routePath()` can retrieve the path registered within the handler
434
+ *
435
+ * @deprecated
436
+ *
437
+ * Use routePath helper defined in "hono/route" instead.
438
+ *
439
+ * @see {@link https://hono.dev/docs/api/request#routepath}
440
+ *
441
+ * @example
442
+ * ```ts
443
+ * app.get('/posts/:id', (c) => {
444
+ * return c.json({ path: c.req.routePath })
445
+ * })
446
+ * ```
447
+ */
448
+ get routePath() {
449
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
450
+ }
451
+ };
452
+ //#endregion
453
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js
454
+ var HtmlEscapedCallbackPhase = {
455
+ Stringify: 1,
456
+ BeforeStream: 2,
457
+ Stream: 3
458
+ };
459
+ var raw = (value, callbacks) => {
460
+ const escapedString = new String(value);
461
+ escapedString.isEscaped = true;
462
+ escapedString.callbacks = callbacks;
463
+ return escapedString;
464
+ };
465
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
466
+ if (typeof str === "object" && !(str instanceof String)) {
467
+ if (!(str instanceof Promise)) str = str.toString();
468
+ if (str instanceof Promise) str = await str;
469
+ }
470
+ const callbacks = str.callbacks;
471
+ if (!callbacks?.length) return Promise.resolve(str);
472
+ if (buffer) buffer[0] += str;
473
+ else buffer = [str];
474
+ const resStr = Promise.all(callbacks.map((c) => c({
475
+ phase,
476
+ buffer,
477
+ context
478
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
479
+ if (preserveCallbacks) return raw(await resStr, callbacks);
480
+ else return resStr;
481
+ };
482
+ //#endregion
483
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js
484
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
485
+ var setDefaultContentType = (contentType, headers) => {
486
+ return {
487
+ "Content-Type": contentType,
488
+ ...headers
489
+ };
490
+ };
491
+ var createResponseInstance = (body, init) => new Response(body, init);
492
+ var Context = class {
493
+ #rawRequest;
494
+ #req;
495
+ /**
496
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
497
+ *
498
+ * @see {@link https://hono.dev/docs/api/context#env}
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * // Environment object for Cloudflare Workers
503
+ * app.get('*', async c => {
504
+ * const counter = c.env.COUNTER
505
+ * })
506
+ * ```
507
+ */
508
+ env = {};
509
+ #var;
510
+ finalized = false;
511
+ /**
512
+ * `.error` can get the error object from the middleware if the Handler throws an error.
513
+ *
514
+ * @see {@link https://hono.dev/docs/api/context#error}
515
+ *
516
+ * @example
517
+ * ```ts
518
+ * app.use('*', async (c, next) => {
519
+ * await next()
520
+ * if (c.error) {
521
+ * // do something...
522
+ * }
523
+ * })
524
+ * ```
525
+ */
526
+ error;
527
+ #status;
528
+ #executionCtx;
529
+ #res;
530
+ #layout;
531
+ #renderer;
532
+ #notFoundHandler;
533
+ #preparedHeaders;
534
+ #matchResult;
535
+ #path;
536
+ /**
537
+ * Creates an instance of the Context class.
538
+ *
539
+ * @param req - The Request object.
540
+ * @param options - Optional configuration options for the context.
541
+ */
542
+ constructor(req, options) {
543
+ this.#rawRequest = req;
544
+ if (options) {
545
+ this.#executionCtx = options.executionCtx;
546
+ this.env = options.env;
547
+ this.#notFoundHandler = options.notFoundHandler;
548
+ this.#path = options.path;
549
+ this.#matchResult = options.matchResult;
550
+ }
551
+ }
552
+ /**
553
+ * `.req` is the instance of {@link HonoRequest}.
554
+ */
555
+ get req() {
556
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
557
+ return this.#req;
558
+ }
559
+ /**
560
+ * @see {@link https://hono.dev/docs/api/context#event}
561
+ * The FetchEvent associated with the current request.
562
+ *
563
+ * @throws Will throw an error if the context does not have a FetchEvent.
564
+ */
565
+ get event() {
566
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) return this.#executionCtx;
567
+ else throw Error("This context has no FetchEvent");
568
+ }
569
+ /**
570
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
571
+ * The ExecutionContext associated with the current request.
572
+ *
573
+ * @throws Will throw an error if the context does not have an ExecutionContext.
574
+ */
575
+ get executionCtx() {
576
+ if (this.#executionCtx) return this.#executionCtx;
577
+ else throw Error("This context has no ExecutionContext");
578
+ }
579
+ /**
580
+ * @see {@link https://hono.dev/docs/api/context#res}
581
+ * The Response object for the current request.
582
+ */
583
+ get res() {
584
+ return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });
585
+ }
586
+ /**
587
+ * Sets the Response object for the current request.
588
+ *
589
+ * @param _res - The Response object to set.
590
+ */
591
+ set res(_res) {
592
+ if (this.#res && _res) {
593
+ _res = createResponseInstance(_res.body, _res);
594
+ for (const [k, v] of this.#res.headers.entries()) {
595
+ if (k === "content-type") continue;
596
+ if (k === "set-cookie") {
597
+ const cookies = this.#res.headers.getSetCookie();
598
+ _res.headers.delete("set-cookie");
599
+ for (const cookie of cookies) _res.headers.append("set-cookie", cookie);
600
+ } else _res.headers.set(k, v);
601
+ }
602
+ }
603
+ this.#res = _res;
604
+ this.finalized = true;
605
+ }
606
+ /**
607
+ * `.render()` can create a response within a layout.
608
+ *
609
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
610
+ *
611
+ * @example
612
+ * ```ts
613
+ * app.get('/', (c) => {
614
+ * return c.render('Hello!')
615
+ * })
616
+ * ```
617
+ */
618
+ render = (...args) => {
619
+ this.#renderer ??= (content) => this.html(content);
620
+ return this.#renderer(...args);
621
+ };
622
+ /**
623
+ * Sets the layout for the response.
624
+ *
625
+ * @param layout - The layout to set.
626
+ * @returns The layout function.
627
+ */
628
+ setLayout = (layout) => this.#layout = layout;
629
+ /**
630
+ * Gets the current layout for the response.
631
+ *
632
+ * @returns The current layout function.
633
+ */
634
+ getLayout = () => this.#layout;
635
+ /**
636
+ * `.setRenderer()` can set the layout in the custom middleware.
637
+ *
638
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
639
+ *
640
+ * @example
641
+ * ```tsx
642
+ * app.use('*', async (c, next) => {
643
+ * c.setRenderer((content) => {
644
+ * return c.html(
645
+ * <html>
646
+ * <body>
647
+ * <p>{content}</p>
648
+ * </body>
649
+ * </html>
650
+ * )
651
+ * })
652
+ * await next()
653
+ * })
654
+ * ```
655
+ */
656
+ setRenderer = (renderer) => {
657
+ this.#renderer = renderer;
658
+ };
659
+ /**
660
+ * `.header()` can set headers.
661
+ *
662
+ * @see {@link https://hono.dev/docs/api/context#header}
663
+ *
664
+ * @example
665
+ * ```ts
666
+ * app.get('/welcome', (c) => {
667
+ * // Set headers
668
+ * c.header('X-Message', 'Hello!')
669
+ * c.header('Content-Type', 'text/plain')
670
+ *
671
+ * return c.body('Thank you for coming')
672
+ * })
673
+ * ```
674
+ */
675
+ header = (name, value, options) => {
676
+ if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
677
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
678
+ if (value === void 0) headers.delete(name);
679
+ else if (options?.append) headers.append(name, value);
680
+ else headers.set(name, value);
681
+ };
682
+ status = (status) => {
683
+ this.#status = status;
684
+ };
685
+ /**
686
+ * `.set()` can set the value specified by the key.
687
+ *
688
+ * @see {@link https://hono.dev/docs/api/context#set-get}
689
+ *
690
+ * @example
691
+ * ```ts
692
+ * app.use('*', async (c, next) => {
693
+ * c.set('message', 'Hono is hot!!')
694
+ * await next()
695
+ * })
696
+ * ```
697
+ */
698
+ set = (key, value) => {
699
+ this.#var ??= /* @__PURE__ */ new Map();
700
+ this.#var.set(key, value);
701
+ };
702
+ /**
703
+ * `.get()` can use the value specified by the key.
704
+ *
705
+ * @see {@link https://hono.dev/docs/api/context#set-get}
706
+ *
707
+ * @example
708
+ * ```ts
709
+ * app.get('/', (c) => {
710
+ * const message = c.get('message')
711
+ * return c.text(`The message is "${message}"`)
712
+ * })
713
+ * ```
714
+ */
715
+ get = (key) => {
716
+ return this.#var ? this.#var.get(key) : void 0;
717
+ };
718
+ /**
719
+ * `.var` can access the value of a variable.
720
+ *
721
+ * @see {@link https://hono.dev/docs/api/context#var}
722
+ *
723
+ * @example
724
+ * ```ts
725
+ * const result = c.var.client.oneMethod()
726
+ * ```
727
+ */
728
+ get var() {
729
+ if (!this.#var) return {};
730
+ return Object.fromEntries(this.#var);
731
+ }
732
+ #newResponse(data, arg, headers) {
733
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
734
+ if (typeof arg === "object" && "headers" in arg) {
735
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
736
+ for (const [key, value] of argHeaders) if (key.toLowerCase() === "set-cookie") responseHeaders.append(key, value);
737
+ else responseHeaders.set(key, value);
738
+ }
739
+ if (headers) for (const [k, v] of Object.entries(headers)) if (typeof v === "string") responseHeaders.set(k, v);
740
+ else {
741
+ responseHeaders.delete(k);
742
+ for (const v2 of v) responseHeaders.append(k, v2);
743
+ }
744
+ return createResponseInstance(data, {
745
+ status: typeof arg === "number" ? arg : arg?.status ?? this.#status,
746
+ headers: responseHeaders
747
+ });
748
+ }
749
+ newResponse = (...args) => this.#newResponse(...args);
750
+ /**
751
+ * `.body()` can return the HTTP response.
752
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
753
+ * This can also be set in `.text()`, `.json()` and so on.
754
+ *
755
+ * @see {@link https://hono.dev/docs/api/context#body}
756
+ *
757
+ * @example
758
+ * ```ts
759
+ * app.get('/welcome', (c) => {
760
+ * // Set headers
761
+ * c.header('X-Message', 'Hello!')
762
+ * c.header('Content-Type', 'text/plain')
763
+ * // Set HTTP status code
764
+ * c.status(201)
765
+ *
766
+ * // Return the response body
767
+ * return c.body('Thank you for coming')
768
+ * })
769
+ * ```
770
+ */
771
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
772
+ /**
773
+ * `.text()` can render text as `Content-Type:text/plain`.
774
+ *
775
+ * @see {@link https://hono.dev/docs/api/context#text}
776
+ *
777
+ * @example
778
+ * ```ts
779
+ * app.get('/say', (c) => {
780
+ * return c.text('Hello!')
781
+ * })
782
+ * ```
783
+ */
784
+ text = (text, arg, headers) => {
785
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
786
+ };
787
+ /**
788
+ * `.json()` can render JSON as `Content-Type:application/json`.
789
+ *
790
+ * @see {@link https://hono.dev/docs/api/context#json}
791
+ *
792
+ * @example
793
+ * ```ts
794
+ * app.get('/api', (c) => {
795
+ * return c.json({ message: 'Hello!' })
796
+ * })
797
+ * ```
798
+ */
799
+ json = (object, arg, headers) => {
800
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
801
+ };
802
+ html = (html, arg, headers) => {
803
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
804
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
805
+ };
806
+ /**
807
+ * `.redirect()` can Redirect, default status code is 302.
808
+ *
809
+ * @see {@link https://hono.dev/docs/api/context#redirect}
810
+ *
811
+ * @example
812
+ * ```ts
813
+ * app.get('/redirect', (c) => {
814
+ * return c.redirect('/')
815
+ * })
816
+ * app.get('/redirect-permanently', (c) => {
817
+ * return c.redirect('/', 301)
818
+ * })
819
+ * ```
820
+ */
821
+ redirect = (location, status) => {
822
+ const locationString = String(location);
823
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
824
+ return this.newResponse(null, status ?? 302);
825
+ };
826
+ /**
827
+ * `.notFound()` can return the Not Found Response.
828
+ *
829
+ * @see {@link https://hono.dev/docs/api/context#notfound}
830
+ *
831
+ * @example
832
+ * ```ts
833
+ * app.get('/notfound', (c) => {
834
+ * return c.notFound()
835
+ * })
836
+ * ```
837
+ */
838
+ notFound = () => {
839
+ this.#notFoundHandler ??= () => createResponseInstance();
840
+ return this.#notFoundHandler(this);
841
+ };
842
+ };
843
+ //#endregion
844
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js
845
+ var METHODS = [
846
+ "get",
847
+ "post",
848
+ "put",
849
+ "delete",
850
+ "options",
851
+ "patch"
852
+ ];
853
+ var UnsupportedPathError = class extends Error {};
854
+ //#endregion
855
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js
856
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
857
+ //#endregion
858
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js
859
+ var notFoundHandler = (c) => {
860
+ return c.text("404 Not Found", 404);
861
+ };
862
+ var errorHandler = (err, c) => {
863
+ if ("getResponse" in err) {
864
+ const res = err.getResponse();
865
+ return c.newResponse(res.body, res);
866
+ }
867
+ console.error(err);
868
+ return c.text("Internal Server Error", 500);
869
+ };
870
+ var Hono$1 = class _Hono {
871
+ get;
872
+ post;
873
+ put;
874
+ delete;
875
+ options;
876
+ patch;
877
+ all;
878
+ on;
879
+ use;
880
+ router;
881
+ getPath;
882
+ _basePath = "/";
883
+ #path = "/";
884
+ routes = [];
885
+ constructor(options = {}) {
886
+ [...METHODS, "all"].forEach((method) => {
887
+ this[method] = (args1, ...args) => {
888
+ if (typeof args1 === "string") this.#path = args1;
889
+ else this.#addRoute(method, this.#path, args1);
890
+ args.forEach((handler) => {
891
+ this.#addRoute(method, this.#path, handler);
892
+ });
893
+ return this;
894
+ };
895
+ });
896
+ this.on = (method, path, ...handlers) => {
897
+ for (const p of [path].flat()) {
898
+ this.#path = p;
899
+ for (const m of [method].flat()) handlers.map((handler) => {
900
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
901
+ });
902
+ }
903
+ return this;
904
+ };
905
+ this.use = (arg1, ...handlers) => {
906
+ if (typeof arg1 === "string") this.#path = arg1;
907
+ else {
908
+ this.#path = "*";
909
+ handlers.unshift(arg1);
910
+ }
911
+ handlers.forEach((handler) => {
912
+ this.#addRoute("ALL", this.#path, handler);
913
+ });
914
+ return this;
915
+ };
916
+ const { strict, ...optionsWithoutStrict } = options;
917
+ Object.assign(this, optionsWithoutStrict);
918
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
919
+ }
920
+ #clone() {
921
+ const clone = new _Hono({
922
+ router: this.router,
923
+ getPath: this.getPath
924
+ });
925
+ clone.errorHandler = this.errorHandler;
926
+ clone.#notFoundHandler = this.#notFoundHandler;
927
+ clone.routes = this.routes;
928
+ return clone;
929
+ }
930
+ #notFoundHandler = notFoundHandler;
931
+ errorHandler = errorHandler;
932
+ /**
933
+ * `.route()` allows grouping other Hono instance in routes.
934
+ *
935
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
936
+ *
937
+ * @param {string} path - base Path
938
+ * @param {Hono} app - other Hono instance
939
+ * @returns {Hono} routed Hono instance
940
+ *
941
+ * @example
942
+ * ```ts
943
+ * const app = new Hono()
944
+ * const app2 = new Hono()
945
+ *
946
+ * app2.get("/user", (c) => c.text("user"))
947
+ * app.route("/api", app2) // GET /api/user
948
+ * ```
949
+ */
950
+ route(path, app) {
951
+ const subApp = this.basePath(path);
952
+ app.routes.map((r) => {
953
+ let handler;
954
+ if (app.errorHandler === errorHandler) handler = r.handler;
955
+ else {
956
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
957
+ handler[COMPOSED_HANDLER] = r.handler;
958
+ }
959
+ subApp.#addRoute(r.method, r.path, handler, r.basePath);
960
+ });
961
+ return this;
962
+ }
963
+ /**
964
+ * `.basePath()` allows base paths to be specified.
965
+ *
966
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
967
+ *
968
+ * @param {string} path - base Path
969
+ * @returns {Hono} changed Hono instance
970
+ *
971
+ * @example
972
+ * ```ts
973
+ * const api = new Hono().basePath('/api')
974
+ * ```
975
+ */
976
+ basePath(path) {
977
+ const subApp = this.#clone();
978
+ subApp._basePath = mergePath(this._basePath, path);
979
+ return subApp;
980
+ }
981
+ /**
982
+ * `.onError()` handles an error and returns a customized Response.
983
+ *
984
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
985
+ *
986
+ * @param {ErrorHandler} handler - request Handler for error
987
+ * @returns {Hono} changed Hono instance
988
+ *
989
+ * @example
990
+ * ```ts
991
+ * app.onError((err, c) => {
992
+ * console.error(`${err}`)
993
+ * return c.text('Custom Error Message', 500)
994
+ * })
995
+ * ```
996
+ */
997
+ onError = (handler) => {
998
+ this.errorHandler = handler;
999
+ return this;
1000
+ };
1001
+ /**
1002
+ * `.notFound()` allows you to customize a Not Found Response.
1003
+ *
1004
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1005
+ *
1006
+ * @param {NotFoundHandler} handler - request handler for not-found
1007
+ * @returns {Hono} changed Hono instance
1008
+ *
1009
+ * @example
1010
+ * ```ts
1011
+ * app.notFound((c) => {
1012
+ * return c.text('Custom 404 Message', 404)
1013
+ * })
1014
+ * ```
1015
+ */
1016
+ notFound = (handler) => {
1017
+ this.#notFoundHandler = handler;
1018
+ return this;
1019
+ };
1020
+ /**
1021
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1022
+ *
1023
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1024
+ *
1025
+ * @param {string} path - base Path
1026
+ * @param {Function} applicationHandler - other Request Handler
1027
+ * @param {MountOptions} [options] - options of `.mount()`
1028
+ * @returns {Hono} mounted Hono instance
1029
+ *
1030
+ * @example
1031
+ * ```ts
1032
+ * import { Router as IttyRouter } from 'itty-router'
1033
+ * import { Hono } from 'hono'
1034
+ * // Create itty-router application
1035
+ * const ittyRouter = IttyRouter()
1036
+ * // GET /itty-router/hello
1037
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1038
+ *
1039
+ * const app = new Hono()
1040
+ * app.mount('/itty-router', ittyRouter.handle)
1041
+ * ```
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * const app = new Hono()
1046
+ * // Send the request to another application without modification.
1047
+ * app.mount('/app', anotherApp, {
1048
+ * replaceRequest: (req) => req,
1049
+ * })
1050
+ * ```
1051
+ */
1052
+ mount(path, applicationHandler, options) {
1053
+ let replaceRequest;
1054
+ let optionHandler;
1055
+ if (options) if (typeof options === "function") optionHandler = options;
1056
+ else {
1057
+ optionHandler = options.optionHandler;
1058
+ if (options.replaceRequest === false) replaceRequest = (request) => request;
1059
+ else replaceRequest = options.replaceRequest;
1060
+ }
1061
+ const getOptions = optionHandler ? (c) => {
1062
+ const options2 = optionHandler(c);
1063
+ return Array.isArray(options2) ? options2 : [options2];
1064
+ } : (c) => {
1065
+ let executionContext = void 0;
1066
+ try {
1067
+ executionContext = c.executionCtx;
1068
+ } catch {}
1069
+ return [c.env, executionContext];
1070
+ };
1071
+ replaceRequest ||= (() => {
1072
+ const mergedPath = mergePath(this._basePath, path);
1073
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1074
+ return (request) => {
1075
+ const url = new URL(request.url);
1076
+ url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
1077
+ return new Request(url, request);
1078
+ };
1079
+ })();
1080
+ const handler = async (c, next) => {
1081
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1082
+ if (res) return res;
1083
+ await next();
1084
+ };
1085
+ this.#addRoute("ALL", mergePath(path, "*"), handler);
1086
+ return this;
1087
+ }
1088
+ #addRoute(method, path, handler, baseRoutePath) {
1089
+ method = method.toUpperCase();
1090
+ path = mergePath(this._basePath, path);
1091
+ const r = {
1092
+ basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
1093
+ path,
1094
+ method,
1095
+ handler
1096
+ };
1097
+ this.router.add(method, path, [handler, r]);
1098
+ this.routes.push(r);
1099
+ }
1100
+ #handleError(err, c) {
1101
+ if (err instanceof Error) return this.errorHandler(err, c);
1102
+ throw err;
1103
+ }
1104
+ #dispatch(request, executionCtx, env, method) {
1105
+ if (method === "HEAD") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1106
+ const path = this.getPath(request, { env });
1107
+ const matchResult = this.router.match(method, path);
1108
+ const c = new Context(request, {
1109
+ path,
1110
+ matchResult,
1111
+ env,
1112
+ executionCtx,
1113
+ notFoundHandler: this.#notFoundHandler
1114
+ });
1115
+ if (matchResult[0].length === 1) {
1116
+ let res;
1117
+ try {
1118
+ res = matchResult[0][0][0][0](c, async () => {
1119
+ c.res = await this.#notFoundHandler(c);
1120
+ });
1121
+ } catch (err) {
1122
+ return this.#handleError(err, c);
1123
+ }
1124
+ 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);
1125
+ }
1126
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1127
+ return (async () => {
1128
+ try {
1129
+ const context = await composed(c);
1130
+ if (!context.finalized) throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1131
+ return context.res;
1132
+ } catch (err) {
1133
+ return this.#handleError(err, c);
1134
+ }
1135
+ })();
1136
+ }
1137
+ /**
1138
+ * `.fetch()` will be entry point of your app.
1139
+ *
1140
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1141
+ *
1142
+ * @param {Request} request - request Object of request
1143
+ * @param {Env} Env - env Object
1144
+ * @param {ExecutionContext} - context of execution
1145
+ * @returns {Response | Promise<Response>} response of request
1146
+ *
1147
+ */
1148
+ fetch = (request, ...rest) => {
1149
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1150
+ };
1151
+ /**
1152
+ * `.request()` is a useful method for testing.
1153
+ * You can pass a URL or pathname to send a GET request.
1154
+ * app will return a Response object.
1155
+ * ```ts
1156
+ * test('GET /hello is ok', async () => {
1157
+ * const res = await app.request('/hello')
1158
+ * expect(res.status).toBe(200)
1159
+ * })
1160
+ * ```
1161
+ * @see https://hono.dev/docs/api/hono#request
1162
+ */
1163
+ request = (input, requestInit, Env, executionCtx) => {
1164
+ if (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1165
+ input = input.toString();
1166
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
1167
+ };
1168
+ /**
1169
+ * `.fire()` automatically adds a global fetch event listener.
1170
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1171
+ * @deprecated
1172
+ * Use `fire` from `hono/service-worker` instead.
1173
+ * ```ts
1174
+ * import { Hono } from 'hono'
1175
+ * import { fire } from 'hono/service-worker'
1176
+ *
1177
+ * const app = new Hono()
1178
+ * // ...
1179
+ * fire(app)
1180
+ * ```
1181
+ * @see https://hono.dev/docs/api/hono#fire
1182
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1183
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1184
+ */
1185
+ fire = () => {
1186
+ addEventListener("fetch", (event) => {
1187
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1188
+ });
1189
+ };
1190
+ };
1191
+ //#endregion
1192
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/pattern-router/router.js
1193
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1194
+ var PatternRouter = class {
1195
+ name = "PatternRouter";
1196
+ #routes = [];
1197
+ add(method, path, handler) {
1198
+ const endsWithWildcard = path.at(-1) === "*";
1199
+ if (endsWithWildcard) path = path.slice(0, -2);
1200
+ if (path.at(-1) === "?") {
1201
+ path = path.slice(0, -1);
1202
+ this.add(method, path.replace(/\/[^/]+$/, ""), handler);
1203
+ }
1204
+ const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map((part) => {
1205
+ const match = part.match(/^\/:([^{]+)(?:{(.*)})?/);
1206
+ return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&");
1207
+ });
1208
+ try {
1209
+ this.#routes.push([
1210
+ new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
1211
+ method,
1212
+ handler
1213
+ ]);
1214
+ } catch {
1215
+ throw new UnsupportedPathError();
1216
+ }
1217
+ }
1218
+ match(method, path) {
1219
+ const handlers = [];
1220
+ for (let i = 0, len = this.#routes.length; i < len; i++) {
1221
+ const [pattern, routeMethod, handler] = this.#routes[i];
1222
+ if (routeMethod === method || routeMethod === "ALL") {
1223
+ const match = pattern.exec(path);
1224
+ if (match) handlers.push([handler, match.groups || emptyParams]);
1225
+ }
1226
+ }
1227
+ return [handlers];
1228
+ }
1229
+ };
1230
+ //#endregion
1231
+ //#region node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/preset/tiny.js
1232
+ var Hono = class extends Hono$1 {
1233
+ constructor(options = {}) {
1234
+ super(options);
1235
+ this.router = new PatternRouter();
1236
+ }
1237
+ };
1238
+ //#endregion
1239
+ //#region packages/server/src/http/since.ts
1240
+ /**
1241
+ * Long-poll `GET /v1/since` handler core. Two exports:
1242
+ *
1243
+ * - {@link longPollSince} — the long-poll itself. Fast path first;
1244
+ * if `listEventsSince` already sees events, return immediately.
1245
+ * Otherwise race a poll loop against a 25 s wall-clock timeout and
1246
+ * return either the next batch of events or
1247
+ * `{ events: [], next_cursor: <same> }` ("nothing changed within
1248
+ * the budget").
1249
+ * - {@link listEventsSince} — one poll cycle. Reads `current.json`,
1250
+ * validates the caller's cursor against `log_seq_start`, lists the
1251
+ * log keys strictly-greater than the cursor's key, GETs each body,
1252
+ * and returns the parsed `LogEntry`s in causal order.
1253
+ *
1254
+ * The handler is wired into the Hono router (`router.ts`); the
1255
+ * router itself owns request parsing and error → HTTP mapping. This
1256
+ * module owns the I/O + cursor semantics.
1257
+ *
1258
+ * Cost model. While a long-poll connection is active the per-poll
1259
+ * cost is one `Storage.get` of `current.json` plus one `Storage.get`
1260
+ * per log entry yielded. An idle reader (no new entries) pays one
1261
+ * Class A op per inner poll; with the production defaults
1262
+ * (25 s / 1 s) that is 25 ops per active connection. The
1263
+ * `< 1 Class A op / writer / hour` cost-model bound (see
1264
+ * `docs/spec/sync-protocol.md`) is for an *idle* reader — i.e. a
1265
+ * client that is *not* currently holding a long-poll open.
1266
+ * Subscribers paying for real-time-ish delivery are by definition
1267
+ * non-idle.
1268
+ */
1269
+ /**
1270
+ * Validation regex for an opaque LSN cursor. Matches the shape minted
1271
+ * by `Writer.commit` (see
1272
+ * `packages/server/src/writer.ts`) and described on
1273
+ * {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where
1274
+ * base-32 is `[0-9a-v]` and the trailing seq is two characters.
1275
+ * Mirrored from `tests/integration/log-emit.test.ts:77`.
1276
+ */
1277
+ const LSN_RE = /^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{2}$/;
1278
+ /**
1279
+ * Hard cap on log entries returned in a single poll cycle. 1024 is
1280
+ * comfortably above the largest expected per-poll batch under the
1281
+ * production 1 s poll interval and bounds the worst-case memory
1282
+ * footprint of the parsed-JSON array on a hostile workload.
1283
+ */
1284
+ const DEFAULT_MAX_EVENTS = 1024;
1285
+ /**
1286
+ * Default 25 s long-poll budget. CF Workers cap fetch CPU at 30 s on
1287
+ * the free plan; 25 s leaves slack for header serialization plus the
1288
+ * platform's bookkeeping. Node / Bun / Deno have no comparable cap,
1289
+ * but the budget is still useful as a connection-cycling hint for
1290
+ * upstream load balancers (most idle-connection timeouts are 30-60 s).
1291
+ *
1292
+ * Per-request override is via the `timeoutMs` field on
1293
+ * {@link LongPollSinceOptions} (plumbed from `sinceTimeoutMs` on
1294
+ * `CreateRouterOptions` and both Node + Cloudflare adapters).
1295
+ */
1296
+ const DEFAULT_TIMEOUT_MS = 25e3;
1297
+ /**
1298
+ * Default 1 s inner-poll interval. 25 polls × 1 list = 25 Class A
1299
+ * ops per active long-poll connection. See module docstring for the
1300
+ * cost-model trade-off.
1301
+ *
1302
+ * Per-request override is via the `pollIntervalMs` field on
1303
+ * {@link LongPollSinceOptions} (plumbed from `sincePollIntervalMs`
1304
+ * on `CreateRouterOptions` and both Node + Cloudflare adapters).
1305
+ */
1306
+ const DEFAULT_POLL_INTERVAL_MS = 1e3;
1307
+ /**
1308
+ * Long-poll wrapper around {@link listEventsSince}. Returns as soon
1309
+ * as the first non-empty poll lands, or when the wall-clock timeout
1310
+ * elapses (whichever comes first). On timeout the response is
1311
+ * `{ events: [], next_cursor: <same> }` — shipped as `200`, not `304`,
1312
+ * because the response body carries the unchanged cursor the client
1313
+ * needs for the next poll cycle.
1314
+ *
1315
+ * @throws BaerlyError{code:"SchemaError"} — invalid cursor shape, or
1316
+ * the cursor references a log entry that has been folded into a
1317
+ * snapshot and GC'd.
1318
+ */
1319
+ async function longPollSince(opts) {
1320
+ const { db, collection, cursor, signal } = opts;
1321
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1322
+ const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1323
+ if (cursor.length > 0 && !LSN_RE.test(cursor)) throw new BaerlyError("SchemaError", `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`);
1324
+ const initial = await listEventsSince({
1325
+ db,
1326
+ collection,
1327
+ cursor,
1328
+ signal
1329
+ });
1330
+ if (initial.length > 0) return {
1331
+ events: initial,
1332
+ next_cursor: initial[initial.length - 1].lsn
1333
+ };
1334
+ const deadline = Date.now() + timeoutMs;
1335
+ return new Promise((resolve, reject) => {
1336
+ let timer;
1337
+ let settled = false;
1338
+ const cleanup = () => {
1339
+ if (timer !== void 0) {
1340
+ clearTimeout(timer);
1341
+ timer = void 0;
1342
+ }
1343
+ if (signal !== void 0) signal.removeEventListener("abort", onAbort);
1344
+ };
1345
+ const settleResolve = (value) => {
1346
+ if (settled) return;
1347
+ settled = true;
1348
+ cleanup();
1349
+ resolve(value);
1350
+ };
1351
+ const settleReject = (err) => {
1352
+ if (settled) return;
1353
+ settled = true;
1354
+ cleanup();
1355
+ reject(err);
1356
+ };
1357
+ function onAbort() {
1358
+ settleResolve({
1359
+ events: [],
1360
+ next_cursor: cursor
1361
+ });
1362
+ }
1363
+ if (signal !== void 0) {
1364
+ if (signal.aborted) {
1365
+ onAbort();
1366
+ return;
1367
+ }
1368
+ signal.addEventListener("abort", onAbort, { once: true });
1369
+ }
1370
+ const tick = async () => {
1371
+ if (settled) return;
1372
+ try {
1373
+ const events = await listEventsSince({
1374
+ db,
1375
+ collection,
1376
+ cursor,
1377
+ signal
1378
+ });
1379
+ if (settled) return;
1380
+ if (events.length > 0) {
1381
+ settleResolve({
1382
+ events,
1383
+ next_cursor: events[events.length - 1].lsn
1384
+ });
1385
+ return;
1386
+ }
1387
+ const remaining = deadline - Date.now();
1388
+ if (remaining <= 0) {
1389
+ settleResolve({
1390
+ events: [],
1391
+ next_cursor: cursor
1392
+ });
1393
+ return;
1394
+ }
1395
+ timer = setTimeout(() => {
1396
+ tick();
1397
+ }, Math.min(pollIntervalMs, remaining));
1398
+ } catch (error) {
1399
+ settleReject(error);
1400
+ }
1401
+ };
1402
+ timer = setTimeout(() => {
1403
+ tick();
1404
+ }, Math.min(pollIntervalMs, timeoutMs));
1405
+ });
1406
+ }
1407
+ /**
1408
+ * One poll cycle: read `current.json`, derive the `seq` range to
1409
+ * scan from the cursor's embedded seq, GET each log entry by `seq`,
1410
+ * return the parsed `LogEntry`s in causal order.
1411
+ *
1412
+ * On-bucket log keys are `log/<seq>.json` — the same shape
1413
+ * `compactor` / `gc` / `rebuild-index` walk. Iterating
1414
+ * `[startSeq, endSeq)` and GET-ing each key directly avoids the
1415
+ * lex-`startAfter` hazard on integer filenames (`10.json` sorts
1416
+ * before `2.json` lex) and gives us the global causal ordering for
1417
+ * free — `seq` is monotonic across writer sessions.
1418
+ *
1419
+ * No `current.json` yet → `[]` (clients can poll a not-yet-existing
1420
+ * collection without erroring). Cursor inside `[0, log_seq_start)` →
1421
+ * `BaerlyError{code:"SchemaError"}`.
1422
+ */
1423
+ async function listEventsSince(opts) {
1424
+ const { db, collection, cursor, signal } = opts;
1425
+ if (cursor.length > 0 && !LSN_RE.test(cursor)) throw new BaerlyError("SchemaError", `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`);
1426
+ const read = await db.getCurrentJson(collection, signalOpt(signal));
1427
+ if (read === null) return [];
1428
+ const logSeqStart = logSeqStartOf(read.json);
1429
+ const nextSeq = read.json.next_seq;
1430
+ let startSeq;
1431
+ if (cursor.length === 0) startSeq = logSeqStart;
1432
+ else {
1433
+ const cursorSeq = lsnParts(cursor).seq;
1434
+ if (cursorSeq < logSeqStart) throw new BaerlyError("SchemaError", `cursor ${JSON.stringify(cursor)} points to a log entry that has been folded into a snapshot (log_seq_start=${logSeqStart}); re-bootstrap from a snapshot read before resuming`);
1435
+ startSeq = cursorSeq + 1;
1436
+ }
1437
+ const endSeq = Math.min(nextSeq, startSeq + DEFAULT_MAX_EVENTS);
1438
+ const entries = [];
1439
+ for (let s = startSeq; s < endSeq; s++) {
1440
+ const entry = await db.getLogEntry(collection, s, signalOpt(signal));
1441
+ if (entry === null) continue;
1442
+ entries.push(entry);
1443
+ }
1444
+ return entries;
1445
+ }
1446
+ /** Pack an optional `signal` into the `{ signal? }` shape callers expect. */
1447
+ const signalOpt = (signal) => signal === void 0 ? void 0 : { signal };
1448
+ //#endregion
1449
+ //#region packages/server/src/http/router.ts
1450
+ /**
1451
+ * HTTP dispatcher. A small Hono `app` that implements the
1452
+ * five locked CRUD routes from `contract.ts`. Mounted into both
1453
+ * adapters (`@baerly/adapter-cloudflare` and `@baerly/adapter-node`);
1454
+ * the router itself is platform-agnostic — it accepts a single
1455
+ * `Request`, dispatches against a per-request `Db`, and returns a
1456
+ * `Response` whose body follows the `HttpOkEnvelope` /
1457
+ * `HttpErrorEnvelope` shapes.
1458
+ *
1459
+ * The anonymous `GET /v1/healthz` liveness probe is served by the
1460
+ * adapters directly (see `worker.ts` / `server.ts`) — keeping it
1461
+ * upstream of the router avoids spending a `Db.create` on every
1462
+ * load-balancer probe.
1463
+ *
1464
+ * `GET /v1/since` is appended to the same factory (see `./since.ts`
1465
+ * for the long-poll core). The Cloudflare adapter wraps Worker-side
1466
+ * GETs with `caches.default` *outside* `createRouter` so the router
1467
+ * stays platform-agnostic; that wrapper EXCLUDES `/v1/since` —
1468
+ * long-poll idleness is not a cache hit.
1469
+ */
1470
+ /**
1471
+ * Build a Hono `app` that serves the CRUD routes:
1472
+ *
1473
+ * - `GET /v1/c/:collection/:id` → read one document.
1474
+ * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows
1475
+ * matching a predicate, optionally ordered and capped.
1476
+ * - `POST /v1/c/:collection` → insert. Body: `{ doc }`. → `201 { _id }`.
1477
+ * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.
1478
+ * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.
1479
+ * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.
1480
+ * - `GET /v1/count?collection=<name>&where=<json>` → scalar `{ count: N }`.
1481
+ * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.
1482
+ *
1483
+ * @example
1484
+ * ```ts
1485
+ * import { createRouter, Db } from "@gusto/baerly-storage";
1486
+ * import { MemoryStorage } from "@gusto/baerly-storage";
1487
+ *
1488
+ * const db = Db.create({ storage: new MemoryStorage(), app: "tickets", tenant: "acme" });
1489
+ * const app = createRouter({ db });
1490
+ * // CF Workers:
1491
+ * export default { async fetch(req: Request) { return app.fetch(req); } };
1492
+ * ```
1493
+ */
1494
+ function createRouter(options) {
1495
+ const { db, sinceTimeoutMs, sincePollIntervalMs } = options;
1496
+ const app = new Hono();
1497
+ app.get("/v1/c/:collection/:id", async (c) => {
1498
+ const { collection, id } = c.req.param();
1499
+ const { rows, manifestPointer, fresh } = await runByIdWithMeta(db.collectionReadContext(collection), id);
1500
+ const row = rows[0];
1501
+ if (row === void 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
1502
+ return c.json({
1503
+ data: row,
1504
+ _meta: {
1505
+ manifest_pointer: manifestPointer,
1506
+ fresh
1507
+ }
1508
+ }, 200);
1509
+ });
1510
+ app.get("/v1/c/:collection", async (c) => {
1511
+ const { collection } = c.req.param();
1512
+ const wire = parseWhereParam(c);
1513
+ const order = parseOrder(c.req.query("order"));
1514
+ const limit = parseLimit(c.req.query("limit"));
1515
+ const { rows, manifestPointer, fresh } = await runAllWithMeta(db.collectionReadContext(collection), {
1516
+ wire,
1517
+ order,
1518
+ limit
1519
+ });
1520
+ return c.json({
1521
+ data: rows,
1522
+ _meta: {
1523
+ manifest_pointer: manifestPointer,
1524
+ fresh
1525
+ }
1526
+ }, 200);
1527
+ });
1528
+ app.post("/v1/c/:collection", async (c) => {
1529
+ const { collection } = c.req.param();
1530
+ const doc = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "doc");
1531
+ const { _id } = await db.collection(collection).insert(doc);
1532
+ return c.json({ _id }, 201);
1533
+ });
1534
+ app.patch("/v1/c/:collection/:id", async (c) => {
1535
+ const { collection, id } = c.req.param();
1536
+ const patch = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "patch");
1537
+ const { modified } = await db.collection(collection).update(id, patch);
1538
+ if (modified === 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
1539
+ return c.json({ modified }, 200);
1540
+ });
1541
+ app.put("/v1/c/:collection/:id", async (c) => {
1542
+ const { collection, id } = c.req.param();
1543
+ const doc = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "doc");
1544
+ await db.collection(collection).replace(id, doc);
1545
+ return c.json({ modified: 1 }, 200);
1546
+ });
1547
+ app.delete("/v1/c/:collection/:id", async (c) => {
1548
+ const { collection, id } = c.req.param();
1549
+ const { deleted } = await db.collection(collection).delete(id);
1550
+ if (deleted === 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
1551
+ return new Response(null, { status: 204 });
1552
+ });
1553
+ app.get("/v1/count", async (c) => {
1554
+ const collection = c.req.query("collection");
1555
+ if (collection === void 0 || collection.length === 0) throw new BaerlyError("SchemaError", "GET /v1/count requires ?collection=<name>");
1556
+ const wire = parseWhereParam(c);
1557
+ const { rows, manifestPointer, fresh } = await runAllWithMeta(db.collectionReadContext(collection), {
1558
+ wire,
1559
+ order: void 0,
1560
+ limit: void 0
1561
+ });
1562
+ return c.json({
1563
+ data: { count: rows.length },
1564
+ _meta: {
1565
+ manifest_pointer: manifestPointer,
1566
+ fresh
1567
+ }
1568
+ }, 200);
1569
+ });
1570
+ app.get("/v1/since", async (c) => {
1571
+ const collection = c.req.query("collection");
1572
+ if (typeof collection !== "string" || collection.length === 0 || collection.includes("/")) throw new BaerlyError("SchemaError", "GET /v1/since requires a non-empty `collection` query parameter without `/`");
1573
+ const result = await longPollSince({
1574
+ db,
1575
+ collection,
1576
+ cursor: c.req.query("cursor") ?? "",
1577
+ signal: c.req.raw.signal,
1578
+ timeoutMs: sinceTimeoutMs,
1579
+ pollIntervalMs: sincePollIntervalMs
1580
+ });
1581
+ return c.json(result, 200);
1582
+ });
1583
+ app.onError((err, c) => mapToResponse(c, err));
1584
+ return app;
1585
+ }
1586
+ /**
1587
+ * Hard cap on request-body bytes. 1 MiB — matches `S3HttpStorage`'s
1588
+ * conformance-suite default. Over-cap → `413 PayloadTooLarge`.
1589
+ *
1590
+ * The Node adapter (`@baerly/adapter-node`) imports this constant
1591
+ * and passes it to `applyBodyCap`, which wraps the request body
1592
+ * with a counting `TransformStream` so chunked uploads trip the cap
1593
+ * mid-stream rather than materialising the full buffer. The
1594
+ * router's `readJsonBody` keeps the cap as a defence-in-depth check
1595
+ * (Content-Length pre-read + post-`arrayBuffer` length) for adapters
1596
+ * whose platform doesn't pre-cap.
1597
+ *
1598
+ * @internal — exported for tests and for the Node adapter's
1599
+ * `applyBodyCap` helper. Promote to
1600
+ * `packages/protocol/src/constants.ts` only on a third cross-
1601
+ * package consumer.
1602
+ */
1603
+ const MAX_BODY_BYTES = 1 << 20;
1604
+ /**
1605
+ * Assert that `body[field]` is a plain object (not undefined / null /
1606
+ * array / primitive). Returns the value typed as
1607
+ * `Record<string, unknown>` so the caller's next cast doesn't need
1608
+ * another guard. Throws `BaerlyError{code:"SchemaError"}` with the
1609
+ * locked wording `"Request body must be { <field>: object }"`.
1610
+ *
1611
+ * Used by POST `/v1/c/:collection` (`doc`), PATCH `/v1/c/:collection/:id`
1612
+ * (`patch`), and PUT `/v1/c/:collection/:id` (`doc`).
1613
+ *
1614
+ * @internal
1615
+ */
1616
+ const assertJsonBodyField = (body, field) => {
1617
+ const value = typeof body === "object" && body !== null ? body[field] : void 0;
1618
+ if (value === void 0 || typeof value !== "object" || value === null || Array.isArray(value)) throw new BaerlyError("SchemaError", `Request body must be { ${field}: object }`);
1619
+ return value;
1620
+ };
1621
+ /**
1622
+ * Parse the `?where=<urlencoded JSON>` query-string param. Absent or
1623
+ * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →
1624
+ * `BaerlyError{code:"SchemaError"}` with the locked wording
1625
+ * `"Invalid JSON in ?where="`. Returns the validated wire form
1626
+ * ({@link PredicateWire}).
1627
+ *
1628
+ * Wire-only validation: any clause with `field === "_id"` rejects
1629
+ * with `BaerlyError{code:"InvalidConfig"}` — agents zero-shot
1630
+ * writing `?where={"clauses":[{"op":"eq","field":"_id","value":"x"}]}`
1631
+ * against the list route get pointed at `GET /v1/c/:collection/:id`
1632
+ * instead. Kernel-internal `_id` wire construction
1633
+ * (`./collection.ts:byId`, `runByIdWithMeta`, `runInsert`) bypasses this
1634
+ * layer by design — those paths never come back through `?where=`
1635
+ * parsing.
1636
+ *
1637
+ * @internal
1638
+ */
1639
+ const parseWhereParam = (c) => {
1640
+ const whereParam = c.req.query("where");
1641
+ if (whereParam === void 0 || whereParam.length === 0) return EMPTY_PREDICATE_WIRE;
1642
+ let parsed;
1643
+ try {
1644
+ parsed = JSON.parse(whereParam);
1645
+ } catch {
1646
+ throw new BaerlyError("SchemaError", "Invalid JSON in ?where=");
1647
+ }
1648
+ return validateWire(parsed);
1649
+ };
1650
+ /**
1651
+ * Parse `?limit=<n>` as a non-negative safe integer. Returns
1652
+ * `undefined` when absent. Rejects floats, NaN, negatives, and
1653
+ * non-numeric input with `SchemaError`.
1654
+ *
1655
+ * @internal
1656
+ */
1657
+ function parseLimit(raw) {
1658
+ if (raw === void 0) return;
1659
+ const n = Number(raw);
1660
+ if (!Number.isSafeInteger(n) || n < 0) throw new BaerlyError("SchemaError", `?limit= must be a non-negative integer; got ${JSON.stringify(raw)}`);
1661
+ return n;
1662
+ }
1663
+ /**
1664
+ * Parse the `?order=<json>` query param. Mirrors the `?where=` parser
1665
+ * shape: undefined → no order, malformed JSON → `SchemaError`. The
1666
+ * engine (`runAllWithMeta` → `sortByOrderSpec`) validates the shape
1667
+ * itself, so this only handles the wire-level JSON decode.
1668
+ *
1669
+ * @internal
1670
+ */
1671
+ function parseOrder(raw) {
1672
+ if (raw === void 0 || raw.length === 0) return;
1673
+ let parsed;
1674
+ try {
1675
+ parsed = JSON.parse(raw);
1676
+ } catch {
1677
+ throw new BaerlyError("SchemaError", "Invalid JSON in ?order=");
1678
+ }
1679
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new BaerlyError("SchemaError", "?order= must encode a JSON object");
1680
+ return parsed;
1681
+ }
1682
+ const ERROR_TO_STATUS = new Map([
1683
+ ["Unauthorized", 401],
1684
+ ["AccessDenied", 403],
1685
+ ["NotFound", 404],
1686
+ ["Conflict", 409],
1687
+ ["PayloadTooLarge", 413],
1688
+ ["SchemaError", 400],
1689
+ ["InvalidConfig", 400]
1690
+ ]);
1691
+ /**
1692
+ * Map an unknown thrown value onto the wire envelope plus an HTTP
1693
+ * status code. The mapping is keyed by `BaerlyError.code` so any future
1694
+ * code addition forces a re-check here (currently unmapped codes fall
1695
+ * through to 500 by design — see the `NetworkError` / `InvalidResponse`
1696
+ * / `Internal` comment in `ERROR_TO_STATUS`).
1697
+ *
1698
+ * @internal — exported for tests and for the `/v1/since` long-poll
1699
+ * handler in `./since.ts`. The `HttpErrorEnvelope` shape is locked;
1700
+ * do not mutate it.
1701
+ */
1702
+ function mapError(err) {
1703
+ if (err instanceof BaerlyError) return {
1704
+ status: ERROR_TO_STATUS.get(err.code) ?? 500,
1705
+ envelope: errorEnvelope(err.code, err.message, err.issues)
1706
+ };
1707
+ getLogger(CATEGORY.http).error("unhandled_error", { error: serializeError(err) });
1708
+ return {
1709
+ status: 500,
1710
+ envelope: errorEnvelope("Internal", "internal error")
1711
+ };
1712
+ }
1713
+ function mapToResponse(c, err) {
1714
+ const { status, envelope } = mapError(err);
1715
+ return c.json(envelope, status);
1716
+ }
1717
+ /**
1718
+ * Read and parse the JSON request body. Returns the parsed value
1719
+ * (an `unknown` — caller narrows). Throws `BaerlyError`:
1720
+ *
1721
+ * - `"PayloadTooLarge"` (→ 413) when the body exceeds `maxBytes`,
1722
+ * detected via `Content-Length` pre-check, post-`arrayBuffer`
1723
+ * length check, or — if the host adapter pumps the body through
1724
+ * a `ReadableStream` (the Node adapter does) — a `BaerlyError`
1725
+ * surfaced via `controller.error(...)` on the upstream pump.
1726
+ * - `"SchemaError"` (→ 400) for empty bodies, JSON parse failures,
1727
+ * and any other read failure.
1728
+ *
1729
+ * Hono's `app.onError` sink routes the throw through `mapToResponse`.
1730
+ */
1731
+ async function readJsonBody(c, maxBytes) {
1732
+ const lenHeader = c.req.header("content-length");
1733
+ if (lenHeader !== void 0) {
1734
+ const parsed = Number.parseInt(lenHeader, 10);
1735
+ if (Number.isFinite(parsed) && parsed > maxBytes) throw new BaerlyError("PayloadTooLarge", `Body exceeds ${maxBytes} bytes`);
1736
+ }
1737
+ let raw;
1738
+ try {
1739
+ const buffer = await c.req.arrayBuffer();
1740
+ if (buffer.byteLength > maxBytes) throw new BaerlyError("PayloadTooLarge", `Body exceeds ${maxBytes} bytes`);
1741
+ raw = new TextDecoder().decode(buffer);
1742
+ } catch (error) {
1743
+ if (error instanceof BaerlyError) throw error;
1744
+ throw new BaerlyError("SchemaError", `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`);
1745
+ }
1746
+ if (raw.length === 0) throw new BaerlyError("SchemaError", "Empty request body");
1747
+ try {
1748
+ return JSON.parse(raw);
1749
+ } catch {
1750
+ throw new BaerlyError("SchemaError", "Invalid JSON in request body");
1751
+ }
1752
+ }
1753
+ //#endregion
1754
+ export { longPollSince as a, listEventsSince as i, createRouter as n, Hono as o, mapError as r, MAX_BODY_BYTES as t };
1755
+
1756
+ //# sourceMappingURL=http-CjUO1Bec.js.map