better-call 0.2.13-beta.8 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1057 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+
29
+ // node_modules/set-cookie-parser/lib/set-cookie.js
30
+ var require_set_cookie = __commonJS({
31
+ "node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) {
32
+ "use strict";
33
+ var defaultParseOptions = {
34
+ decodeValues: true,
35
+ map: false,
36
+ silent: false
37
+ };
38
+ function isNonEmptyString(str) {
39
+ return typeof str === "string" && !!str.trim();
40
+ }
41
+ function parseString(setCookieValue, options) {
42
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
43
+ var nameValuePairStr = parts.shift();
44
+ var parsed = parseNameValuePair(nameValuePairStr);
45
+ var name = parsed.name;
46
+ var value = parsed.value;
47
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
48
+ try {
49
+ value = options.decodeValues ? decodeURIComponent(value) : value;
50
+ } catch (e) {
51
+ console.error(
52
+ "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.",
53
+ e
54
+ );
55
+ }
56
+ var cookie = {
57
+ name,
58
+ value
59
+ };
60
+ parts.forEach(function(part) {
61
+ var sides = part.split("=");
62
+ var key = sides.shift().trimLeft().toLowerCase();
63
+ var value2 = sides.join("=");
64
+ if (key === "expires") {
65
+ cookie.expires = new Date(value2);
66
+ } else if (key === "max-age") {
67
+ cookie.maxAge = parseInt(value2, 10);
68
+ } else if (key === "secure") {
69
+ cookie.secure = true;
70
+ } else if (key === "httponly") {
71
+ cookie.httpOnly = true;
72
+ } else if (key === "samesite") {
73
+ cookie.sameSite = value2;
74
+ } else if (key === "partitioned") {
75
+ cookie.partitioned = true;
76
+ } else {
77
+ cookie[key] = value2;
78
+ }
79
+ });
80
+ return cookie;
81
+ }
82
+ function parseNameValuePair(nameValuePairStr) {
83
+ var name = "";
84
+ var value = "";
85
+ var nameValueArr = nameValuePairStr.split("=");
86
+ if (nameValueArr.length > 1) {
87
+ name = nameValueArr.shift();
88
+ value = nameValueArr.join("=");
89
+ } else {
90
+ value = nameValuePairStr;
91
+ }
92
+ return { name, value };
93
+ }
94
+ function parse2(input, options) {
95
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
96
+ if (!input) {
97
+ if (!options.map) {
98
+ return [];
99
+ } else {
100
+ return {};
101
+ }
102
+ }
103
+ if (input.headers) {
104
+ if (typeof input.headers.getSetCookie === "function") {
105
+ input = input.headers.getSetCookie();
106
+ } else if (input.headers["set-cookie"]) {
107
+ input = input.headers["set-cookie"];
108
+ } else {
109
+ var sch = input.headers[Object.keys(input.headers).find(function(key) {
110
+ return key.toLowerCase() === "set-cookie";
111
+ })];
112
+ if (!sch && input.headers.cookie && !options.silent) {
113
+ console.warn(
114
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
115
+ );
116
+ }
117
+ input = sch;
118
+ }
119
+ }
120
+ if (!Array.isArray(input)) {
121
+ input = [input];
122
+ }
123
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
124
+ if (!options.map) {
125
+ return input.filter(isNonEmptyString).map(function(str) {
126
+ return parseString(str, options);
127
+ });
128
+ } else {
129
+ var cookies = {};
130
+ return input.filter(isNonEmptyString).reduce(function(cookies2, str) {
131
+ var cookie = parseString(str, options);
132
+ cookies2[cookie.name] = cookie;
133
+ return cookies2;
134
+ }, cookies);
135
+ }
136
+ }
137
+ function splitCookiesString2(cookiesString) {
138
+ if (Array.isArray(cookiesString)) {
139
+ return cookiesString;
140
+ }
141
+ if (typeof cookiesString !== "string") {
142
+ return [];
143
+ }
144
+ var cookiesStrings = [];
145
+ var pos = 0;
146
+ var start;
147
+ var ch;
148
+ var lastComma;
149
+ var nextStart;
150
+ var cookiesSeparatorFound;
151
+ function skipWhitespace() {
152
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
153
+ pos += 1;
154
+ }
155
+ return pos < cookiesString.length;
156
+ }
157
+ function notSpecialChar() {
158
+ ch = cookiesString.charAt(pos);
159
+ return ch !== "=" && ch !== ";" && ch !== ",";
160
+ }
161
+ while (pos < cookiesString.length) {
162
+ start = pos;
163
+ cookiesSeparatorFound = false;
164
+ while (skipWhitespace()) {
165
+ ch = cookiesString.charAt(pos);
166
+ if (ch === ",") {
167
+ lastComma = pos;
168
+ pos += 1;
169
+ skipWhitespace();
170
+ nextStart = pos;
171
+ while (pos < cookiesString.length && notSpecialChar()) {
172
+ pos += 1;
173
+ }
174
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
175
+ cookiesSeparatorFound = true;
176
+ pos = nextStart;
177
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
178
+ start = pos;
179
+ } else {
180
+ pos = lastComma + 1;
181
+ }
182
+ } else {
183
+ pos += 1;
184
+ }
185
+ }
186
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
187
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
188
+ }
189
+ }
190
+ return cookiesStrings;
191
+ }
192
+ module.exports = parse2;
193
+ module.exports.parse = parse2;
194
+ module.exports.parseString = parseString;
195
+ module.exports.splitCookiesString = splitCookiesString2;
196
+ }
197
+ });
198
+
199
+ // src/endpoint.ts
200
+ import { ZodError } from "zod";
201
+
202
+ // src/error.ts
203
+ var APIError = class extends Error {
204
+ constructor(status, body, headers) {
205
+ super(`API Error: ${status} ${body?.message ?? ""}`, {
206
+ cause: body
207
+ });
208
+ __publicField(this, "status");
209
+ __publicField(this, "headers");
210
+ __publicField(this, "body");
211
+ this.status = status;
212
+ this.body = body ?? {};
213
+ this.stack = "";
214
+ this.headers = headers ?? new Headers();
215
+ if (!this.headers.has("Content-Type")) {
216
+ this.headers.set("Content-Type", "application/json");
217
+ }
218
+ this.name = "BetterCallAPIError";
219
+ }
220
+ };
221
+
222
+ // src/helper.ts
223
+ var json = (body, option) => {
224
+ return {
225
+ response: {
226
+ body: option?.body ?? body,
227
+ status: option?.status ?? 200,
228
+ statusText: option?.statusText ?? "OK",
229
+ headers: option?.headers
230
+ },
231
+ body,
232
+ _flag: "json"
233
+ };
234
+ };
235
+
236
+ // src/cookie.ts
237
+ import { subtle } from "uncrypto";
238
+ var algorithm = { name: "HMAC", hash: "SHA-256" };
239
+ var getCryptoKey = async (secret) => {
240
+ const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
241
+ return await subtle.importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]);
242
+ };
243
+ var makeSignature = async (value, secret) => {
244
+ const key = await getCryptoKey(secret);
245
+ const signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value));
246
+ return btoa(String.fromCharCode(...new Uint8Array(signature)));
247
+ };
248
+ var verifySignature = async (base64Signature, value, secret) => {
249
+ try {
250
+ const signatureBinStr = atob(base64Signature);
251
+ const signature = new Uint8Array(signatureBinStr.length);
252
+ for (let i = 0, len = signatureBinStr.length; i < len; i++) {
253
+ signature[i] = signatureBinStr.charCodeAt(i);
254
+ }
255
+ return await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));
256
+ } catch (e) {
257
+ return false;
258
+ }
259
+ };
260
+ var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
261
+ var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
262
+ var parse = (cookie, name) => {
263
+ const pairs = cookie.trim().split(";");
264
+ return pairs.reduce((parsedCookie, pairStr) => {
265
+ pairStr = pairStr.trim();
266
+ const valueStartPos = pairStr.indexOf("=");
267
+ if (valueStartPos === -1) {
268
+ return parsedCookie;
269
+ }
270
+ const cookieName = pairStr.substring(0, valueStartPos).trim();
271
+ if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
272
+ return parsedCookie;
273
+ }
274
+ let cookieValue = pairStr.substring(valueStartPos + 1).trim();
275
+ if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
276
+ cookieValue = cookieValue.slice(1, -1);
277
+ }
278
+ if (validCookieValueRegEx.test(cookieValue)) {
279
+ parsedCookie[cookieName] = decodeURIComponent(cookieValue);
280
+ }
281
+ return parsedCookie;
282
+ }, {});
283
+ };
284
+ var parseSigned = async (cookie, secret, name) => {
285
+ const parsedCookie = {};
286
+ const secretKey = await getCryptoKey(secret);
287
+ for (const [key, value] of Object.entries(parse(cookie, name))) {
288
+ const signatureStartPos = value.lastIndexOf(".");
289
+ if (signatureStartPos < 1) {
290
+ continue;
291
+ }
292
+ const signedValue = value.substring(0, signatureStartPos);
293
+ const signature = value.substring(signatureStartPos + 1);
294
+ if (signature.length !== 44 || !signature.endsWith("=")) {
295
+ continue;
296
+ }
297
+ const isVerified = await verifySignature(signature, signedValue, secretKey);
298
+ parsedCookie[key] = isVerified ? signedValue : false;
299
+ }
300
+ return parsedCookie;
301
+ };
302
+ var _serialize = (name, value, opt = {}) => {
303
+ let cookie = `${name}=${value}`;
304
+ if (name.startsWith("__Secure-") && !opt.secure) {
305
+ opt.secure = true;
306
+ }
307
+ if (name.startsWith("__Host-")) {
308
+ if (!opt.secure) {
309
+ opt.secure = true;
310
+ }
311
+ if (opt.path !== "/") {
312
+ opt.path = "/";
313
+ }
314
+ if (opt.domain) {
315
+ opt.domain = void 0;
316
+ }
317
+ }
318
+ if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
319
+ if (opt.maxAge > 3456e4) {
320
+ throw new Error(
321
+ "Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."
322
+ );
323
+ }
324
+ cookie += `; Max-Age=${Math.floor(opt.maxAge)}`;
325
+ }
326
+ if (opt.domain && opt.prefix !== "host") {
327
+ cookie += `; Domain=${opt.domain}`;
328
+ }
329
+ if (opt.path) {
330
+ cookie += `; Path=${opt.path}`;
331
+ }
332
+ if (opt.expires) {
333
+ if (opt.expires.getTime() - Date.now() > 3456e7) {
334
+ throw new Error(
335
+ "Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."
336
+ );
337
+ }
338
+ cookie += `; Expires=${opt.expires.toUTCString()}`;
339
+ }
340
+ if (opt.httpOnly) {
341
+ cookie += "; HttpOnly";
342
+ }
343
+ if (opt.secure) {
344
+ cookie += "; Secure";
345
+ }
346
+ if (opt.sameSite) {
347
+ cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
348
+ }
349
+ if (opt.partitioned) {
350
+ if (!opt.secure) {
351
+ throw new Error("Partitioned Cookie must have Secure attributes");
352
+ }
353
+ cookie += "; Partitioned";
354
+ }
355
+ return cookie;
356
+ };
357
+ var serialize = (name, value, opt) => {
358
+ value = encodeURIComponent(value);
359
+ return _serialize(name, value, opt);
360
+ };
361
+ var serializeSigned = async (name, value, secret, opt = {}) => {
362
+ const signature = await makeSignature(value, secret);
363
+ value = `${value}.${signature}`;
364
+ value = encodeURIComponent(value);
365
+ return _serialize(name, value, opt);
366
+ };
367
+
368
+ // src/cookie-utils.ts
369
+ var getCookie = (cookie, key, prefix) => {
370
+ if (!cookie) {
371
+ return void 0;
372
+ }
373
+ let finalKey = key;
374
+ if (prefix) {
375
+ if (prefix === "secure") {
376
+ finalKey = "__Secure-" + key;
377
+ } else if (prefix === "host") {
378
+ finalKey = "__Host-" + key;
379
+ } else {
380
+ return void 0;
381
+ }
382
+ }
383
+ const obj = parse(cookie, finalKey);
384
+ return obj[finalKey];
385
+ };
386
+ var setCookie = (header, name, value, opt) => {
387
+ const existingCookies = header.get("Set-Cookie");
388
+ if (existingCookies) {
389
+ const cookies = existingCookies.split(", ");
390
+ const updatedCookies = cookies.filter((cookie2) => !cookie2.startsWith(`${name}=`));
391
+ header.delete("Set-Cookie");
392
+ updatedCookies.forEach((cookie2) => header.append("Set-Cookie", cookie2));
393
+ }
394
+ let cookie;
395
+ if (opt?.prefix === "secure") {
396
+ cookie = serialize("__Secure-" + name, value, { path: "/", ...opt, secure: true });
397
+ } else if (opt?.prefix === "host") {
398
+ cookie = serialize("__Host-" + name, value, {
399
+ ...opt,
400
+ path: "/",
401
+ secure: true,
402
+ domain: void 0
403
+ });
404
+ } else {
405
+ cookie = serialize(name, value, { path: "/", ...opt });
406
+ }
407
+ header.append("Set-Cookie", cookie);
408
+ };
409
+ var setSignedCookie = async (header, name, value, secret, opt) => {
410
+ let cookie;
411
+ if (opt?.prefix === "secure") {
412
+ cookie = await serializeSigned("__Secure-" + name, value, secret, {
413
+ path: "/",
414
+ ...opt,
415
+ secure: true
416
+ });
417
+ } else if (opt?.prefix === "host") {
418
+ cookie = await serializeSigned("__Host-" + name, value, secret, {
419
+ ...opt,
420
+ path: "/",
421
+ secure: true,
422
+ domain: void 0
423
+ });
424
+ } else {
425
+ cookie = await serializeSigned(name, value, secret, { path: "/", ...opt });
426
+ }
427
+ header.append("Set-Cookie", cookie);
428
+ };
429
+ var getSignedCookie = async (header, secret, key, prefix) => {
430
+ const cookie = header.get("cookie");
431
+ if (!cookie) {
432
+ return void 0;
433
+ }
434
+ let finalKey = key;
435
+ if (prefix) {
436
+ if (prefix === "secure") {
437
+ finalKey = "__Secure-" + key;
438
+ } else if (prefix === "host") {
439
+ finalKey = "__Host-" + key;
440
+ }
441
+ }
442
+ const obj = await parseSigned(cookie, secret, finalKey);
443
+ return obj[finalKey];
444
+ };
445
+
446
+ // src/endpoint.ts
447
+ function createEndpointCreator(opts) {
448
+ return (path, options, handler) => {
449
+ return createEndpoint(
450
+ path,
451
+ {
452
+ ...options,
453
+ use: [...options?.use || [], ...opts?.use || []]
454
+ },
455
+ handler
456
+ );
457
+ };
458
+ }
459
+ function createEndpoint(path, options, handler) {
460
+ let responseHeader = new Headers();
461
+ const handle = async (...ctx) => {
462
+ let internalCtx = {
463
+ setHeader(key, value) {
464
+ responseHeader.set(key, value);
465
+ },
466
+ setCookie(key, value, options2) {
467
+ setCookie(responseHeader, key, value, options2);
468
+ },
469
+ getCookie(key, prefix) {
470
+ const header = ctx[0]?.headers;
471
+ const cookieH = header?.get("cookie");
472
+ const cookie = getCookie(cookieH || "", key, prefix);
473
+ return cookie;
474
+ },
475
+ getSignedCookie(key, secret, prefix) {
476
+ const header = ctx[0]?.headers;
477
+ if (!header) {
478
+ throw new TypeError("Headers are required");
479
+ }
480
+ const cookie = getSignedCookie(header, secret, key, prefix);
481
+ return cookie;
482
+ },
483
+ async setSignedCookie(key, value, secret, options2) {
484
+ await setSignedCookie(responseHeader, key, value, secret, options2);
485
+ },
486
+ redirect(url) {
487
+ responseHeader.set("Location", url);
488
+ return new APIError("FOUND");
489
+ },
490
+ json,
491
+ context: ctx[0]?.context || {},
492
+ _flag: ctx[0]?.asResponse ? "router" : ctx[0]?._flag,
493
+ responseHeader,
494
+ path,
495
+ ...ctx[0] || {}
496
+ };
497
+ if (options.use?.length) {
498
+ let middlewareContexts = {};
499
+ let middlewareBody = {};
500
+ for (const middleware of options.use) {
501
+ if (typeof middleware !== "function") {
502
+ console.warn("Middleware is not a function", {
503
+ middleware
504
+ });
505
+ continue;
506
+ }
507
+ const res = await middleware(internalCtx);
508
+ if (res) {
509
+ const body = res.options?.body ? res.options.body.parse(internalCtx.body) : void 0;
510
+ middlewareContexts = {
511
+ ...middlewareContexts,
512
+ ...res
513
+ };
514
+ middlewareBody = {
515
+ ...middlewareBody,
516
+ ...body
517
+ };
518
+ }
519
+ }
520
+ internalCtx = {
521
+ ...internalCtx,
522
+ body: {
523
+ ...middlewareBody,
524
+ ...internalCtx.body
525
+ },
526
+ context: {
527
+ ...internalCtx.context || {},
528
+ ...middlewareContexts
529
+ }
530
+ };
531
+ }
532
+ try {
533
+ const body = options.body ? options.body.parse(internalCtx.body) : internalCtx.body;
534
+ internalCtx = {
535
+ ...internalCtx,
536
+ body: body ? {
537
+ ...body,
538
+ ...internalCtx.body
539
+ } : internalCtx.body
540
+ };
541
+ internalCtx.query = options.query ? options.query.parse(internalCtx.query) : internalCtx.query;
542
+ } catch (e) {
543
+ if (e instanceof ZodError) {
544
+ throw new APIError("BAD_REQUEST", {
545
+ message: e.message,
546
+ details: e.errors
547
+ });
548
+ }
549
+ throw e;
550
+ }
551
+ if (options.requireHeaders && !internalCtx.headers) {
552
+ throw new APIError("BAD_REQUEST", {
553
+ message: "Headers are required"
554
+ });
555
+ }
556
+ if (options.requireRequest && !internalCtx.request) {
557
+ throw new APIError("BAD_REQUEST", {
558
+ message: "Request is required"
559
+ });
560
+ }
561
+ try {
562
+ let res = await handler(internalCtx);
563
+ let actualResponse = res;
564
+ if (res && typeof res === "object" && "_flag" in res) {
565
+ if (res._flag === "json" && internalCtx._flag === "router") {
566
+ const h = res.response.headers;
567
+ Object.keys(h || {}).forEach((key) => {
568
+ responseHeader.set(key, h[key]);
569
+ });
570
+ responseHeader.set("Content-Type", "application/json");
571
+ actualResponse = new Response(JSON.stringify(res.response.body), {
572
+ status: res.response.status ?? 200,
573
+ statusText: res.response.statusText,
574
+ headers: responseHeader
575
+ });
576
+ } else {
577
+ actualResponse = res.body;
578
+ }
579
+ }
580
+ responseHeader = new Headers();
581
+ return actualResponse;
582
+ } catch (e) {
583
+ if (e instanceof APIError) {
584
+ responseHeader.set("Content-Type", "application/json");
585
+ e.headers = responseHeader;
586
+ responseHeader = new Headers();
587
+ throw e;
588
+ }
589
+ throw e;
590
+ }
591
+ };
592
+ handle.path = path;
593
+ handle.options = options;
594
+ handle.method = options.method;
595
+ handle.headers = responseHeader;
596
+ return handle;
597
+ }
598
+
599
+ // src/router.ts
600
+ import { createRouter as createRou3Router, addRoute, findRoute, findAllRoutes } from "rou3";
601
+
602
+ // src/utils.ts
603
+ async function getBody(request) {
604
+ const contentType = request.headers.get("content-type") || "";
605
+ if (!request.body) {
606
+ return void 0;
607
+ }
608
+ if (contentType.includes("application/json")) {
609
+ return await request.json();
610
+ }
611
+ if (contentType.includes("application/x-www-form-urlencoded")) {
612
+ const formData = await request.formData();
613
+ const result = {};
614
+ formData.forEach((value, key) => {
615
+ result[key] = value.toString();
616
+ });
617
+ return result;
618
+ }
619
+ if (contentType.includes("multipart/form-data")) {
620
+ const formData = await request.formData();
621
+ const result = {};
622
+ formData.forEach((value, key) => {
623
+ result[key] = value;
624
+ });
625
+ return result;
626
+ }
627
+ if (contentType.includes("text/plain")) {
628
+ return await request.text();
629
+ }
630
+ if (contentType.includes("application/octet-stream")) {
631
+ return await request.arrayBuffer();
632
+ }
633
+ if (contentType.includes("application/pdf") || contentType.includes("image/") || contentType.includes("video/")) {
634
+ const blob = await request.blob();
635
+ return blob;
636
+ }
637
+ if (contentType.includes("application/stream") || request.body instanceof ReadableStream) {
638
+ return request.body;
639
+ }
640
+ return await request.text();
641
+ }
642
+ function shouldSerialize(body) {
643
+ return typeof body === "object" && body !== null && !(body instanceof Blob) && !(body instanceof FormData);
644
+ }
645
+ var statusCode = {
646
+ OK: 200,
647
+ CREATED: 201,
648
+ ACCEPTED: 202,
649
+ NO_CONTENT: 204,
650
+ MULTIPLE_CHOICES: 300,
651
+ MOVED_PERMANENTLY: 301,
652
+ FOUND: 302,
653
+ SEE_OTHER: 303,
654
+ NOT_MODIFIED: 304,
655
+ TEMPORARY_REDIRECT: 307,
656
+ BAD_REQUEST: 400,
657
+ UNAUTHORIZED: 401,
658
+ PAYMENT_REQUIRED: 402,
659
+ FORBIDDEN: 403,
660
+ NOT_FOUND: 404,
661
+ METHOD_NOT_ALLOWED: 405,
662
+ NOT_ACCEPTABLE: 406,
663
+ PROXY_AUTHENTICATION_REQUIRED: 407,
664
+ REQUEST_TIMEOUT: 408,
665
+ CONFLICT: 409,
666
+ GONE: 410,
667
+ LENGTH_REQUIRED: 411,
668
+ PRECONDITION_FAILED: 412,
669
+ PAYLOAD_TOO_LARGE: 413,
670
+ URI_TOO_LONG: 414,
671
+ UNSUPPORTED_MEDIA_TYPE: 415,
672
+ RANGE_NOT_SATISFIABLE: 416,
673
+ EXPECTATION_FAILED: 417,
674
+ "I'M_A_TEAPOT": 418,
675
+ MISDIRECTED_REQUEST: 421,
676
+ UNPROCESSABLE_ENTITY: 422,
677
+ LOCKED: 423,
678
+ FAILED_DEPENDENCY: 424,
679
+ TOO_EARLY: 425,
680
+ UPGRADE_REQUIRED: 426,
681
+ PRECONDITION_REQUIRED: 428,
682
+ TOO_MANY_REQUESTS: 429,
683
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
684
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451,
685
+ INTERNAL_SERVER_ERROR: 500,
686
+ NOT_IMPLEMENTED: 501,
687
+ BAD_GATEWAY: 502,
688
+ SERVICE_UNAVAILABLE: 503,
689
+ GATEWAY_TIMEOUT: 504,
690
+ HTTP_VERSION_NOT_SUPPORTED: 505,
691
+ VARIANT_ALSO_NEGOTIATES: 506,
692
+ INSUFFICIENT_STORAGE: 507,
693
+ LOOP_DETECTED: 508,
694
+ NOT_EXTENDED: 510,
695
+ NETWORK_AUTHENTICATION_REQUIRED: 511
696
+ };
697
+
698
+ // src/router.ts
699
+ var createRouter = (endpoints, config) => {
700
+ const _endpoints = Object.values(endpoints);
701
+ const router = createRou3Router();
702
+ for (const endpoint of _endpoints) {
703
+ if (endpoint.options.metadata?.SERVER_ONLY) continue;
704
+ if (Array.isArray(endpoint.options?.method)) {
705
+ for (const method of endpoint.options.method) {
706
+ addRoute(router, method, endpoint.path, endpoint);
707
+ }
708
+ } else {
709
+ addRoute(router, endpoint.options.method, endpoint.path, endpoint);
710
+ }
711
+ }
712
+ const middlewareRouter = createRou3Router();
713
+ for (const route of config?.routerMiddleware || []) {
714
+ addRoute(middlewareRouter, "*", route.path, route.middleware);
715
+ }
716
+ const handler = async (request) => {
717
+ const url = new URL(request.url);
718
+ let path = url.pathname;
719
+ if (config?.basePath) {
720
+ path = path.split(config.basePath)[1];
721
+ }
722
+ if (!path?.length) {
723
+ config?.onError?.(new APIError("NOT_FOUND"));
724
+ console.warn(
725
+ `[better-call]: Make sure the URL has the basePath (${config?.basePath}).`
726
+ );
727
+ return new Response(null, {
728
+ status: 404,
729
+ statusText: "Not Found"
730
+ });
731
+ }
732
+ const method = request.method;
733
+ const route = findRoute(router, method, path);
734
+ const handler2 = route?.data;
735
+ const body = await getBody(request);
736
+ const headers = request.headers;
737
+ const query = Object.fromEntries(url.searchParams);
738
+ const routerMiddleware = findAllRoutes(middlewareRouter, "*", path);
739
+ if (!handler2) {
740
+ return new Response(null, {
741
+ status: 404,
742
+ statusText: "Not Found"
743
+ });
744
+ }
745
+ try {
746
+ let middlewareContext = {};
747
+ if (routerMiddleware?.length) {
748
+ for (const route2 of routerMiddleware) {
749
+ const middleware = route2.data;
750
+ const res = await middleware({
751
+ path,
752
+ method,
753
+ headers,
754
+ params: route2?.params,
755
+ request,
756
+ body,
757
+ query,
758
+ context: {
759
+ ...config?.extraContext
760
+ }
761
+ });
762
+ if (res instanceof Response) {
763
+ return res;
764
+ }
765
+ if (res?._flag === "json") {
766
+ return new Response(JSON.stringify(res), {
767
+ headers: res.headers
768
+ });
769
+ }
770
+ if (res) {
771
+ middlewareContext = {
772
+ ...res,
773
+ ...middlewareContext
774
+ };
775
+ }
776
+ }
777
+ }
778
+ const handlerRes = await handler2({
779
+ path,
780
+ method,
781
+ headers,
782
+ params: route?.params,
783
+ request,
784
+ body,
785
+ query,
786
+ _flag: "router",
787
+ context: {
788
+ ...middlewareContext,
789
+ ...config?.extraContext
790
+ }
791
+ });
792
+ if (handlerRes instanceof Response) {
793
+ return handlerRes;
794
+ }
795
+ const resBody = shouldSerialize(handlerRes) ? JSON.stringify(handlerRes) : handlerRes;
796
+ return new Response(resBody, {
797
+ headers: handler2.headers
798
+ });
799
+ } catch (e) {
800
+ if (config?.onError) {
801
+ const onErrorRes = await config.onError(e);
802
+ if (onErrorRes instanceof Response) {
803
+ return onErrorRes;
804
+ }
805
+ }
806
+ if (e instanceof APIError) {
807
+ return new Response(e.body ? JSON.stringify(e.body) : null, {
808
+ status: statusCode[e.status],
809
+ statusText: e.status,
810
+ headers: e.headers
811
+ });
812
+ }
813
+ if (config?.throwError) {
814
+ throw e;
815
+ }
816
+ return new Response(null, {
817
+ status: 500,
818
+ statusText: "Internal Server Error"
819
+ });
820
+ }
821
+ };
822
+ return {
823
+ handler: async (request) => {
824
+ const onReq = await config?.onRequest?.(request);
825
+ if (onReq instanceof Response) {
826
+ return onReq;
827
+ }
828
+ const req = onReq instanceof Request ? onReq : request;
829
+ const res = await handler(req);
830
+ const onRes = await config?.onResponse?.(res);
831
+ if (onRes instanceof Response) {
832
+ return onRes;
833
+ }
834
+ return res;
835
+ },
836
+ endpoints
837
+ };
838
+ };
839
+
840
+ // src/middleware.ts
841
+ function createMiddleware(optionsOrHandler, handler) {
842
+ if (typeof optionsOrHandler === "function") {
843
+ return createEndpoint(
844
+ "*",
845
+ {
846
+ method: "*"
847
+ },
848
+ optionsOrHandler
849
+ );
850
+ }
851
+ if (!handler) {
852
+ throw new Error("Middleware handler is required");
853
+ }
854
+ const endpoint = createEndpoint(
855
+ "*",
856
+ {
857
+ ...optionsOrHandler,
858
+ method: "*"
859
+ },
860
+ handler
861
+ );
862
+ return endpoint;
863
+ }
864
+ var createMiddlewareCreator = (opts) => {
865
+ function fn(optionsOrHandler, handler) {
866
+ if (typeof optionsOrHandler === "function") {
867
+ return createEndpoint(
868
+ "*",
869
+ {
870
+ method: "*"
871
+ },
872
+ optionsOrHandler
873
+ );
874
+ }
875
+ if (!handler) {
876
+ throw new Error("Middleware handler is required");
877
+ }
878
+ const endpoint = createEndpoint(
879
+ "*",
880
+ {
881
+ ...optionsOrHandler,
882
+ method: "*"
883
+ },
884
+ handler
885
+ );
886
+ return endpoint;
887
+ }
888
+ return fn;
889
+ };
890
+
891
+ // src/types.ts
892
+ import "zod";
893
+
894
+ // src/adapter/request.ts
895
+ var set_cookie_parser = __toESM(require_set_cookie(), 1);
896
+ function get_raw_body(req, body_size_limit) {
897
+ const h = req.headers;
898
+ if (!h["content-type"]) return null;
899
+ const content_length = Number(h["content-length"]);
900
+ if (req.httpVersionMajor === 1 && isNaN(content_length) && h["transfer-encoding"] == null || content_length === 0) {
901
+ return null;
902
+ }
903
+ let length = content_length;
904
+ if (body_size_limit) {
905
+ if (!length) {
906
+ length = body_size_limit;
907
+ } else if (length > body_size_limit) {
908
+ throw Error(
909
+ `Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`
910
+ );
911
+ }
912
+ }
913
+ if (req.destroyed) {
914
+ const readable = new ReadableStream();
915
+ readable.cancel();
916
+ return readable;
917
+ }
918
+ let size = 0;
919
+ let cancelled = false;
920
+ return new ReadableStream({
921
+ start(controller) {
922
+ req.on("error", (error) => {
923
+ cancelled = true;
924
+ controller.error(error);
925
+ });
926
+ req.on("end", () => {
927
+ if (cancelled) return;
928
+ controller.close();
929
+ });
930
+ req.on("data", (chunk) => {
931
+ if (cancelled) return;
932
+ size += chunk.length;
933
+ if (size > length) {
934
+ cancelled = true;
935
+ controller.error(
936
+ new Error(
937
+ `request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`
938
+ )
939
+ );
940
+ return;
941
+ }
942
+ controller.enqueue(chunk);
943
+ if (controller.desiredSize === null || controller.desiredSize <= 0) {
944
+ req.pause();
945
+ }
946
+ });
947
+ },
948
+ pull() {
949
+ req.resume();
950
+ },
951
+ cancel(reason) {
952
+ cancelled = true;
953
+ req.destroy(reason);
954
+ }
955
+ });
956
+ }
957
+ function getRequest({
958
+ request,
959
+ base,
960
+ bodySizeLimit
961
+ }) {
962
+ return new Request(base + request.url, {
963
+ // @ts-expect-error
964
+ duplex: "half",
965
+ method: request.method,
966
+ body: get_raw_body(request, bodySizeLimit),
967
+ headers: request.headers
968
+ });
969
+ }
970
+ async function setResponse(res, response) {
971
+ for (const [key, value] of response.headers) {
972
+ try {
973
+ res.setHeader(
974
+ key,
975
+ key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value
976
+ );
977
+ } catch (error) {
978
+ res.getHeaderNames().forEach((name) => res.removeHeader(name));
979
+ res.writeHead(500).end(String(error));
980
+ return;
981
+ }
982
+ }
983
+ res.writeHead(response.status);
984
+ if (!response.body) {
985
+ res.end();
986
+ return;
987
+ }
988
+ if (response.body.locked) {
989
+ res.end(
990
+ "Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."
991
+ );
992
+ return;
993
+ }
994
+ const reader = response.body.getReader();
995
+ if (res.destroyed) {
996
+ reader.cancel();
997
+ return;
998
+ }
999
+ const cancel = (error) => {
1000
+ res.off("close", cancel);
1001
+ res.off("error", cancel);
1002
+ reader.cancel(error).catch(() => {
1003
+ });
1004
+ if (error) res.destroy(error);
1005
+ };
1006
+ res.on("close", cancel);
1007
+ res.on("error", cancel);
1008
+ next();
1009
+ async function next() {
1010
+ try {
1011
+ for (; ; ) {
1012
+ const { done, value } = await reader.read();
1013
+ if (done) break;
1014
+ if (!res.write(value)) {
1015
+ res.once("drain", next);
1016
+ return;
1017
+ }
1018
+ }
1019
+ res.end();
1020
+ } catch (error) {
1021
+ cancel(error instanceof Error ? error : new Error(String(error)));
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ // src/adapter/node.ts
1027
+ function toNodeHandler(handler) {
1028
+ return async (req, res) => {
1029
+ const protocol = req.connection?.encrypted ? "https" : "http";
1030
+ const base = `${protocol}://${req.headers[":authority"] || req.headers.host}`;
1031
+ const response = await handler(getRequest({ base, request: req }));
1032
+ setResponse(res, response);
1033
+ };
1034
+ }
1035
+ export {
1036
+ APIError,
1037
+ createEndpoint,
1038
+ createEndpointCreator,
1039
+ createMiddleware,
1040
+ createMiddlewareCreator,
1041
+ createRouter,
1042
+ getBody,
1043
+ getCookie,
1044
+ getRequest,
1045
+ getSignedCookie,
1046
+ parse,
1047
+ parseSigned,
1048
+ serialize,
1049
+ serializeSigned,
1050
+ setCookie,
1051
+ setResponse,
1052
+ setSignedCookie,
1053
+ shouldSerialize,
1054
+ statusCode,
1055
+ toNodeHandler
1056
+ };
1057
+ //# sourceMappingURL=index.js.map