hono-ban 0.2.5 → 0.2.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.
Files changed (50) hide show
  1. package/dist/esm/formatters/index.js +1 -248
  2. package/dist/esm/index.js +1 -585
  3. package/package.json +9 -24
  4. package/dist/cjs/formatters/index.js +0 -280
  5. package/dist/cjs/formatters/index.js.map +0 -16
  6. package/dist/cjs/formatters/rfc7807/index.js +0 -364
  7. package/dist/cjs/formatters/rfc7807/index.js.map +0 -16
  8. package/dist/cjs/index.js +0 -617
  9. package/dist/cjs/index.js.map +0 -23
  10. package/dist/esm/formatters/index.js.map +0 -16
  11. package/dist/esm/formatters/rfc7807/index.js +0 -333
  12. package/dist/esm/formatters/rfc7807/index.js.map +0 -16
  13. package/dist/esm/index.js.map +0 -23
  14. package/src/__tests__/core/convert-error.test.ts +0 -158
  15. package/src/__tests__/core/create-error.test.ts +0 -113
  16. package/src/__tests__/core/format-error.test.ts +0 -162
  17. package/src/__tests__/factories/factories.test.ts +0 -380
  18. package/src/__tests__/formatters/default-formatter.test.ts +0 -117
  19. package/src/__tests__/middleware/README.md +0 -49
  20. package/src/__tests__/middleware/ban-middleware.test.ts.disabled +0 -23
  21. package/src/__tests__/utils/sanitize.test.ts +0 -117
  22. package/src/__tests__/utils/validate.test.ts +0 -35
  23. package/src/constants/index.ts +0 -6
  24. package/src/constants/status-codes.ts +0 -52
  25. package/src/core/convert-error.ts +0 -74
  26. package/src/core/create-error.ts +0 -65
  27. package/src/core/format-error.ts +0 -76
  28. package/src/core/index.ts +0 -8
  29. package/src/factories/client-errors.ts +0 -492
  30. package/src/factories/index.ts +0 -7
  31. package/src/factories/server-errors.ts +0 -230
  32. package/src/formatters/default/index.ts +0 -72
  33. package/src/formatters/index.ts +0 -13
  34. package/src/formatters/interfaces.ts +0 -7
  35. package/src/formatters/rfc7807/formatter.ts +0 -105
  36. package/src/formatters/rfc7807/hooks.ts +0 -73
  37. package/src/formatters/rfc7807/index.ts +0 -20
  38. package/src/formatters/rfc7807/schemas.ts +0 -88
  39. package/src/index.ts +0 -23
  40. package/src/middleware/ban-middleware.ts +0 -77
  41. package/src/middleware/index.ts +0 -6
  42. package/src/types/common.ts +0 -14
  43. package/src/types/error.ts +0 -46
  44. package/src/types/formatter.ts +0 -61
  45. package/src/types/index.ts +0 -11
  46. package/src/types/options.ts +0 -71
  47. package/src/types/rfc7807.ts +0 -93
  48. package/src/utils/index.ts +0 -7
  49. package/src/utils/sanitize.ts +0 -34
  50. package/src/utils/validate.ts +0 -24
@@ -1,248 +1 @@
1
- // src/constants/status-codes.ts
2
- var STATUS_CODES = {
3
- 400: "Bad Request",
4
- 401: "Unauthorized",
5
- 402: "Payment Required",
6
- 403: "Forbidden",
7
- 404: "Not Found",
8
- 405: "Method Not Allowed",
9
- 406: "Not Acceptable",
10
- 407: "Proxy Authentication Required",
11
- 408: "Request Timeout",
12
- 409: "Conflict",
13
- 410: "Gone",
14
- 411: "Length Required",
15
- 412: "Precondition Failed",
16
- 413: "Payload Too Large",
17
- 414: "URI Too Long",
18
- 415: "Unsupported Media Type",
19
- 416: "Range Not Satisfiable",
20
- 417: "Expectation Failed",
21
- 418: "I'm a teapot",
22
- 421: "Misdirected Request",
23
- 422: "Unprocessable Entity",
24
- 423: "Locked",
25
- 424: "Failed Dependency",
26
- 425: "Too Early",
27
- 426: "Upgrade Required",
28
- 428: "Precondition Required",
29
- 429: "Too Many Requests",
30
- 431: "Request Header Fields Too Large",
31
- 451: "Unavailable For Legal Reasons",
32
- 500: "Internal Server Error",
33
- 501: "Not Implemented",
34
- 502: "Bad Gateway",
35
- 503: "Service Unavailable",
36
- 504: "Gateway Timeout",
37
- 505: "HTTP Version Not Supported",
38
- 506: "Variant Also Negotiates",
39
- 507: "Insufficient Storage",
40
- 508: "Loop Detected",
41
- 510: "Not Extended",
42
- 511: "Network Authentication Required"
43
- };
44
-
45
- // src/formatters/rfc7807/schemas.ts
46
- import { z } from "@hono/zod-openapi";
47
- var RFC7807ValidationParamSchema = z.object({
48
- name: z.string().openapi({
49
- example: "username",
50
- description: "The field name that failed validation"
51
- }),
52
- reason: z.string().openapi({
53
- example: "String must contain at least 3 character(s)",
54
- description: "The reason for validation failure"
55
- })
56
- });
57
- var RFC7807ConstraintViolationSchema = z.object({
58
- name: z.string().openapi({
59
- example: "email",
60
- description: "The field name that violated a constraint"
61
- }),
62
- reason: z.string().openapi({
63
- example: "Email already exists",
64
- description: "The reason for the constraint violation"
65
- }),
66
- resource: z.string().openapi({
67
- example: "user",
68
- description: "The resource type that contains the constraint"
69
- }),
70
- constraint: z.string().openapi({
71
- example: "unique",
72
- description: "The type of constraint that was violated"
73
- })
74
- });
75
- var RFC7807ErrorDataSchema = z.object({
76
- "invalid-params": z.array(RFC7807ValidationParamSchema).optional(),
77
- violations: z.array(RFC7807ConstraintViolationSchema).optional()
78
- });
79
- var RFC7807DetailsSchema = z.object({
80
- type: z.string().url().openapi({
81
- example: "https://api.example.com/problems/validation-error",
82
- description: "A URI reference that identifies the problem type"
83
- }),
84
- title: z.string().openapi({
85
- example: "Validation Failed",
86
- description: "A short, human-readable summary of the problem type"
87
- }),
88
- status: z.number().int().min(400).max(599).openapi({
89
- example: 400,
90
- description: "The HTTP status code"
91
- }),
92
- detail: z.string().optional().openapi({
93
- example: "The request contains invalid fields",
94
- description: "A human-readable explanation specific to this occurrence of the problem"
95
- }),
96
- instance: z.string().url().optional().openapi({
97
- example: "urn:uuid:6b56944d-5e89-4b4d-9ca7-c1be3d1f0e3f",
98
- description: "A URI reference that identifies the specific occurrence of the problem"
99
- }),
100
- timestamp: z.string().datetime().optional().openapi({
101
- example: "2025-02-26T12:34:56.789Z",
102
- description: "When the error occurred"
103
- })
104
- }).merge(RFC7807ErrorDataSchema);
105
-
106
- // src/formatters/rfc7807/formatter.ts
107
- function createRFC7807Formatter(options = {}) {
108
- const baseUrl = options.baseUrl || "https://api.example.com/problems";
109
- return {
110
- contentType: "application/problem+json",
111
- format(error) {
112
- const base = {
113
- type: `${baseUrl}/${error.status}`,
114
- title: STATUS_CODES[error.status] || "Unknown Error",
115
- status: error.status,
116
- detail: error.message,
117
- instance: `urn:uuid:${crypto.randomUUID()}`,
118
- timestamp: new Date().toISOString()
119
- };
120
- if (error.data?.["invalid-params"]) {
121
- return RFC7807DetailsSchema.parse({
122
- ...base,
123
- "invalid-params": error.data["invalid-params"]
124
- });
125
- }
126
- if (error.data?.violations) {
127
- return RFC7807DetailsSchema.parse({
128
- ...base,
129
- violations: error.data.violations
130
- });
131
- }
132
- return RFC7807DetailsSchema.parse(base);
133
- }
134
- };
135
- }
136
- function createRFC7807ValidationError(params) {
137
- return {
138
- "invalid-params": RFC7807ValidationParamSchema.array().parse(params)
139
- };
140
- }
141
- function createRFC7807ZodValidationError(error) {
142
- return {
143
- "invalid-params": RFC7807ValidationParamSchema.array().parse(error.errors.map((e) => ({
144
- name: e.path.join("."),
145
- reason: e.message
146
- })))
147
- };
148
- }
149
- function createRFC7807ConstraintViolation(name, reason, resource, constraint = "unique") {
150
- return {
151
- violations: RFC7807ConstraintViolationSchema.array().parse([
152
- {
153
- name,
154
- reason,
155
- resource,
156
- constraint
157
- }
158
- ])
159
- };
160
- }
161
- // src/formatters/rfc7807/hooks.ts
162
- import { ZodError } from "zod";
163
-
164
- // src/utils/validate.ts
165
- function validateStatusCode(code) {
166
- if (typeof code !== "number" || isNaN(code)) {
167
- return 500;
168
- }
169
- if (code < 400 || code >= 600) {
170
- return 500;
171
- }
172
- return code;
173
- }
174
-
175
- // src/core/create-error.ts
176
- function createError(options) {
177
- const status = validateStatusCode(options.statusCode ?? 500);
178
- const error = {
179
- status,
180
- message: options.message ?? STATUS_CODES[status],
181
- isBan: true
182
- };
183
- if (options.data !== undefined) {
184
- error.data = options.data;
185
- }
186
- if (options.headers) {
187
- error.headers = { ...options.headers };
188
- }
189
- if (options.allow) {
190
- error.allow = Array.isArray(options.allow) ? [...options.allow] : [options.allow];
191
- }
192
- if (options.cause) {
193
- error.cause = options.cause;
194
- if (options.cause instanceof Error) {
195
- error.causeStack = options.cause.stack;
196
- }
197
- }
198
- Error.captureStackTrace(error, createError);
199
- return error;
200
- }
201
-
202
- // src/factories/client-errors.ts
203
- function createErrorWithStatus(statusCode, messageOrOptions, options) {
204
- if (typeof messageOrOptions === "string") {
205
- return createError({
206
- ...options,
207
- statusCode,
208
- message: messageOrOptions
209
- });
210
- }
211
- return createError({ ...messageOrOptions, ...options, statusCode });
212
- }
213
- function badRequest(messageOrOptions, options) {
214
- return createErrorWithStatus(400, messageOrOptions, options);
215
- }
216
-
217
- // src/formatters/rfc7807/hooks.ts
218
- function createRFC7807Hook(options) {
219
- return (result, c) => {
220
- if (!result.success && "error" in result && result.error instanceof ZodError) {
221
- const validationData = createRFC7807ZodValidationError(result.error);
222
- throw badRequest({
223
- message: options?.message || "Validation Error",
224
- data: validationData,
225
- formatter: options?.formatter,
226
- headers: options?.headers,
227
- sanitize: options?.sanitize,
228
- includeStackTrace: options?.includeStackTrace
229
- });
230
- }
231
- };
232
- }
233
- var rfc7807Hook = createRFC7807Hook();
234
- export {
235
- rfc7807Hook,
236
- createRFC7807ZodValidationError,
237
- createRFC7807ValidationError,
238
- createRFC7807Hook,
239
- createRFC7807Formatter,
240
- createRFC7807ConstraintViolation,
241
- RFC7807ValidationParamSchema,
242
- RFC7807ErrorDataSchema,
243
- RFC7807DetailsSchema,
244
- RFC7807ConstraintViolationSchema
245
- };
246
-
247
- //# debugId=1740D2E71854C97164756E2164756E21
248
- //# sourceMappingURL=index.js.map
1
+ var N={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};import{z as B}from"@hono/zod-openapi";var J=B.object({name:B.string().openapi({example:"username",description:"The field name that failed validation"}),reason:B.string().openapi({example:"String must contain at least 3 character(s)",description:"The reason for validation failure"})}),Q=B.object({name:B.string().openapi({example:"email",description:"The field name that violated a constraint"}),reason:B.string().openapi({example:"Email already exists",description:"The reason for the constraint violation"}),resource:B.string().openapi({example:"user",description:"The resource type that contains the constraint"}),constraint:B.string().openapi({example:"unique",description:"The type of constraint that was violated"})}),$=B.object({"invalid-params":B.array(J).optional(),violations:B.array(Q).optional()}),K=B.object({type:B.string().url().openapi({example:"https://api.example.com/problems/validation-error",description:"A URI reference that identifies the problem type"}),title:B.string().openapi({example:"Validation Failed",description:"A short, human-readable summary of the problem type"}),status:B.number().int().min(400).max(599).openapi({example:400,description:"The HTTP status code"}),detail:B.string().optional().openapi({example:"The request contains invalid fields",description:"A human-readable explanation specific to this occurrence of the problem"}),instance:B.string().url().optional().openapi({example:"urn:uuid:6b56944d-5e89-4b4d-9ca7-c1be3d1f0e3f",description:"A URI reference that identifies the specific occurrence of the problem"}),timestamp:B.string().datetime().optional().openapi({example:"2025-02-26T12:34:56.789Z",description:"When the error occurred"})}).merge($);function M(x={}){let j=x.baseUrl||"https://api.example.com/problems";return{contentType:"application/problem+json",format(H){let G={type:`${j}/${H.status}`,title:N[H.status]||"Unknown Error",status:H.status,detail:H.message,instance:`urn:uuid:${crypto.randomUUID()}`,timestamp:new Date().toISOString()};if(H.data?.["invalid-params"])return K.parse({...G,"invalid-params":H.data["invalid-params"]});if(H.data?.violations)return K.parse({...G,violations:H.data.violations});return K.parse(G)}}}function V(x){return{"invalid-params":J.array().parse(x)}}function Y(x){return{"invalid-params":J.array().parse(x.errors.map((j)=>({name:j.path.join("."),reason:j.message})))}}function Z(x,j,H,G="unique"){return{violations:Q.array().parse([{name:x,reason:j,resource:H,constraint:G}])}}import{ZodError as q}from"zod";function k(x){if(typeof x!=="number"||isNaN(x))return 500;if(x<400||x>=600)return 500;return x}function X(x){let j=k(x.statusCode??500),H={status:j,message:x.message??N[j],isBan:!0};if(x.data!==void 0)H.data=x.data;if(x.headers)H.headers={...x.headers};if(x.allow)H.allow=Array.isArray(x.allow)?[...x.allow]:[x.allow];if(x.cause){if(H.cause=x.cause,x.cause instanceof Error)H.causeStack=x.cause.stack}return Error.captureStackTrace(H,X),H}function _(x,j,H){if(typeof j==="string")return X({...H,statusCode:x,message:j});return X({...j,...H,statusCode:x})}function I(x,j){return _(400,x,j)}function L(x){return(j,H)=>{if(!j.success&&"error"in j&&j.error instanceof q){let G=Y(j.error);throw I({message:x?.message||"Validation Error",data:G,formatter:x?.formatter,headers:x?.headers,sanitize:x?.sanitize,includeStackTrace:x?.includeStackTrace})}}}var y=L();export{y as rfc7807Hook,Y as createRFC7807ZodValidationError,V as createRFC7807ValidationError,L as createRFC7807Hook,M as createRFC7807Formatter,Z as createRFC7807ConstraintViolation,J as RFC7807ValidationParamSchema,$ as RFC7807ErrorDataSchema,K as RFC7807DetailsSchema,Q as RFC7807ConstraintViolationSchema};