better-call 1.1.4 → 1.1.6

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.cjs CHANGED
@@ -1,141 +1,9 @@
1
+ const require_error = require('./error2.cjs');
1
2
  const require_node = require('./node.cjs');
2
3
  let __better_auth_utils = require("@better-auth/utils");
3
4
  let rou3 = require("rou3");
4
5
  let zod = require("zod");
5
6
 
6
- //#region src/error.ts
7
- function isErrorStackTraceLimitWritable() {
8
- const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
9
- if (desc === void 0) return Object.isExtensible(Error);
10
- return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0;
11
- }
12
- /**
13
- * Hide internal stack frames from the error stack trace.
14
- */
15
- function hideInternalStackFrames(stack) {
16
- const lines = stack.split("\n at ");
17
- if (lines.length <= 1) return stack;
18
- lines.splice(1, 1);
19
- return lines.join("\n at ");
20
- }
21
- /**
22
- * Creates a custom error class that hides stack frames.
23
- */
24
- function makeErrorForHideStackFrame(Base, clazz) {
25
- class HideStackFramesError extends Base {
26
- #hiddenStack;
27
- constructor(...args) {
28
- if (isErrorStackTraceLimitWritable()) {
29
- const limit = Error.stackTraceLimit;
30
- Error.stackTraceLimit = 0;
31
- super(...args);
32
- Error.stackTraceLimit = limit;
33
- } else super(...args);
34
- const stack = (/* @__PURE__ */ new Error()).stack;
35
- if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name));
36
- }
37
- get errorStack() {
38
- return this.#hiddenStack;
39
- }
40
- }
41
- Object.defineProperty(HideStackFramesError.prototype, "constructor", {
42
- get() {
43
- return clazz;
44
- },
45
- enumerable: false,
46
- configurable: true
47
- });
48
- return HideStackFramesError;
49
- }
50
- const statusCodes = {
51
- OK: 200,
52
- CREATED: 201,
53
- ACCEPTED: 202,
54
- NO_CONTENT: 204,
55
- MULTIPLE_CHOICES: 300,
56
- MOVED_PERMANENTLY: 301,
57
- FOUND: 302,
58
- SEE_OTHER: 303,
59
- NOT_MODIFIED: 304,
60
- TEMPORARY_REDIRECT: 307,
61
- BAD_REQUEST: 400,
62
- UNAUTHORIZED: 401,
63
- PAYMENT_REQUIRED: 402,
64
- FORBIDDEN: 403,
65
- NOT_FOUND: 404,
66
- METHOD_NOT_ALLOWED: 405,
67
- NOT_ACCEPTABLE: 406,
68
- PROXY_AUTHENTICATION_REQUIRED: 407,
69
- REQUEST_TIMEOUT: 408,
70
- CONFLICT: 409,
71
- GONE: 410,
72
- LENGTH_REQUIRED: 411,
73
- PRECONDITION_FAILED: 412,
74
- PAYLOAD_TOO_LARGE: 413,
75
- URI_TOO_LONG: 414,
76
- UNSUPPORTED_MEDIA_TYPE: 415,
77
- RANGE_NOT_SATISFIABLE: 416,
78
- EXPECTATION_FAILED: 417,
79
- "I'M_A_TEAPOT": 418,
80
- MISDIRECTED_REQUEST: 421,
81
- UNPROCESSABLE_ENTITY: 422,
82
- LOCKED: 423,
83
- FAILED_DEPENDENCY: 424,
84
- TOO_EARLY: 425,
85
- UPGRADE_REQUIRED: 426,
86
- PRECONDITION_REQUIRED: 428,
87
- TOO_MANY_REQUESTS: 429,
88
- REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
89
- UNAVAILABLE_FOR_LEGAL_REASONS: 451,
90
- INTERNAL_SERVER_ERROR: 500,
91
- NOT_IMPLEMENTED: 501,
92
- BAD_GATEWAY: 502,
93
- SERVICE_UNAVAILABLE: 503,
94
- GATEWAY_TIMEOUT: 504,
95
- HTTP_VERSION_NOT_SUPPORTED: 505,
96
- VARIANT_ALSO_NEGOTIATES: 506,
97
- INSUFFICIENT_STORAGE: 507,
98
- LOOP_DETECTED: 508,
99
- NOT_EXTENDED: 510,
100
- NETWORK_AUTHENTICATION_REQUIRED: 511
101
- };
102
- var InternalAPIError = class extends Error {
103
- constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) {
104
- super(body?.message, body?.cause ? { cause: body.cause } : void 0);
105
- this.status = status;
106
- this.body = body;
107
- this.headers = headers;
108
- this.statusCode = statusCode;
109
- this.name = "APIError";
110
- this.status = status;
111
- this.headers = headers;
112
- this.statusCode = statusCode;
113
- this.body = body ? {
114
- code: body?.message?.toUpperCase().replace(/ /g, "_").replace(/[^A-Z0-9_]/g, ""),
115
- ...body
116
- } : void 0;
117
- }
118
- };
119
- var ValidationError = class extends InternalAPIError {
120
- constructor(message, issues) {
121
- super(400, {
122
- message,
123
- code: "VALIDATION_ERROR"
124
- });
125
- this.message = message;
126
- this.issues = issues;
127
- this.issues = issues;
128
- }
129
- };
130
- var BetterCallError = class extends Error {
131
- constructor(message) {
132
- super(message);
133
- this.name = "BetterCallError";
134
- }
135
- };
136
- const APIError = makeErrorForHideStackFrame(InternalAPIError, Error);
137
-
138
- //#endregion
139
7
  //#region src/utils.ts
140
8
  const jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i;
141
9
  async function getBody(request, allowedMediaTypes) {
@@ -148,11 +16,11 @@ async function getBody(request, allowedMediaTypes) {
148
16
  const normalizedAllowed = allowed.toLowerCase().trim();
149
17
  return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed);
150
18
  })) {
151
- if (!normalizedContentType) throw new APIError(415, {
19
+ if (!normalizedContentType) throw new require_error.APIError(415, {
152
20
  message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`,
153
21
  code: "UNSUPPORTED_MEDIA_TYPE"
154
22
  });
155
- throw new APIError(415, {
23
+ throw new require_error.APIError(415, {
156
24
  message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`,
157
25
  code: "UNSUPPORTED_MEDIA_TYPE"
158
26
  });
@@ -182,7 +50,7 @@ async function getBody(request, allowedMediaTypes) {
182
50
  return await request.text();
183
51
  }
184
52
  function isAPIError(error) {
185
- return error instanceof APIError || error?.name === "APIError";
53
+ return error instanceof require_error.APIError || error?.name === "APIError";
186
54
  }
187
55
  function tryDecode(str) {
188
56
  try {
@@ -468,7 +336,7 @@ const createInternalContext = async (context, { options, path }) => {
468
336
  const headers = new Headers();
469
337
  let responseStatus = void 0;
470
338
  const { data, error } = await runValidation(options, context);
471
- if (error) throw new ValidationError(error.message, error.issues);
339
+ if (error) throw new require_error.ValidationError(error.message, error.issues);
472
340
  const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && context.request instanceof Request ? context.request.headers : null;
473
341
  const requestCookies = requestHeaders?.get("cookie");
474
342
  const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0;
@@ -519,10 +387,10 @@ const createInternalContext = async (context, { options, path }) => {
519
387
  },
520
388
  redirect: (url) => {
521
389
  headers.set("location", url);
522
- return new APIError("FOUND", void 0, headers);
390
+ return new require_error.APIError("FOUND", void 0, headers);
523
391
  },
524
392
  error: (status, body, headers$1) => {
525
- return new APIError(status, body, headers$1);
393
+ return new require_error.APIError(status, body, headers$1);
526
394
  },
527
395
  setStatus: (status) => {
528
396
  responseStatus = status;
@@ -563,7 +431,8 @@ function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {
563
431
  const path = typeof pathOrOptions === "string" ? pathOrOptions : void 0;
564
432
  const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions;
565
433
  const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever;
566
- if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods");
434
+ if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new require_error.BetterCallError("Body is not allowed with GET or HEAD methods");
435
+ if (path && /\/{2,}/.test(path)) throw new require_error.BetterCallError("Path cannot contain consecutive slashes");
567
436
  const internalHandler = async (...inputCtx) => {
568
437
  const context = inputCtx[0] || {};
569
438
  const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, {
@@ -571,12 +440,12 @@ function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {
571
440
  path
572
441
  }));
573
442
  if (validationError) {
574
- if (!(validationError instanceof ValidationError)) throw validationError;
443
+ if (!(validationError instanceof require_error.ValidationError)) throw validationError;
575
444
  if (options.onValidationError) await options.onValidationError({
576
445
  message: validationError.message,
577
446
  issues: validationError.issues
578
447
  });
579
- throw new APIError(400, {
448
+ throw new require_error.APIError(400, {
580
449
  message: validationError.message,
581
450
  code: "VALIDATION_ERROR"
582
451
  });
@@ -862,7 +731,8 @@ const createRouter = (endpoints, config) => {
862
731
  if (config?.routerMiddleware?.length) for (const { path, middleware } of config.routerMiddleware) (0, rou3.addRoute)(middlewareRouter, "*", path, middleware);
863
732
  const processRequest = async (request) => {
864
733
  const url = new URL(request.url);
865
- const path = config?.basePath ? url.pathname.split(config.basePath).reduce((acc, curr, index) => {
734
+ const pathname = url.pathname;
735
+ const path = config?.basePath && config.basePath !== "/" ? pathname.split(config.basePath).reduce((acc, curr, index) => {
866
736
  if (index !== 0) if (index > 1) acc.push(`${config.basePath}${curr}`);
867
737
  else acc.push(curr);
868
738
  return acc;
@@ -871,7 +741,15 @@ const createRouter = (endpoints, config) => {
871
741
  status: 404,
872
742
  statusText: "Not Found"
873
743
  });
744
+ if (/\/{2,}/.test(path)) return new Response(null, {
745
+ status: 404,
746
+ statusText: "Not Found"
747
+ });
874
748
  const route = (0, rou3.findRoute)(router, request.method, path);
749
+ if (path.endsWith("/") !== route?.data?.path?.endsWith("/") && !config?.skipTrailingSlashes) return new Response(null, {
750
+ status: 404,
751
+ statusText: "Not Found"
752
+ });
875
753
  if (!route?.data) return new Response(null, {
876
754
  status: 404,
877
755
  statusText: "Not Found"
@@ -938,9 +816,9 @@ const createRouter = (endpoints, config) => {
938
816
  };
939
817
 
940
818
  //#endregion
941
- exports.APIError = APIError;
942
- exports.BetterCallError = BetterCallError;
943
- exports.ValidationError = ValidationError;
819
+ exports.APIError = require_error.APIError;
820
+ exports.BetterCallError = require_error.BetterCallError;
821
+ exports.ValidationError = require_error.ValidationError;
944
822
  exports.createEndpoint = createEndpoint;
945
823
  exports.createInternalContext = createInternalContext;
946
824
  exports.createMiddleware = createMiddleware;
@@ -948,11 +826,11 @@ exports.createRouter = createRouter;
948
826
  exports.generator = generator;
949
827
  exports.getCookieKey = getCookieKey;
950
828
  exports.getHTML = getHTML;
951
- exports.hideInternalStackFrames = hideInternalStackFrames;
952
- exports.makeErrorForHideStackFrame = makeErrorForHideStackFrame;
829
+ exports.hideInternalStackFrames = require_error.hideInternalStackFrames;
830
+ exports.makeErrorForHideStackFrame = require_error.makeErrorForHideStackFrame;
953
831
  exports.parseCookies = parseCookies;
954
832
  exports.serializeCookie = serializeCookie;
955
833
  exports.serializeSignedCookie = serializeSignedCookie;
956
- exports.statusCodes = statusCodes;
834
+ exports.statusCodes = require_error.statusCodes;
957
835
  exports.toResponse = toResponse;
958
836
  //# sourceMappingURL=index.cjs.map