UNPKG

hono-ban

Version:

HTTP-friendly error objects for Hono, inspired by Boom

2 lines (1 loc) 9.76 kB
var $={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"};function L(x){if(typeof x!=="number"||isNaN(x))return 500;if(x<400||x>=600)return 500;return x}function G(x){let f=L(x.statusCode??500),y={status:f,message:x.message??$[f],isBan:!0};if(x.data!==void 0)y.data=x.data;if(x.headers)y.headers={...x.headers};if(x.allow)y.allow=Array.isArray(x.allow)?[...x.allow]:[x.allow];if(x.cause){if(y.cause=x.cause,x.cause instanceof Error)y.causeStack=x.cause.stack}if(x.formatter)y.formatter=x.formatter;if(x.sanitize)y.sanitize=[...x.sanitize];if(x.includeStackTrace!==void 0)y.includeStackTrace=x.includeStackTrace;return Error.captureStackTrace(y,G),y}function v(x,f){return typeof x==="object"&&x!==null&&"isBan"in x&&x.isBan===!0&&(!f||x.status===f)}function I(x,f={}){if(v(x))return{status:f.statusCode??x.status,message:f.message??x.message,isBan:!0,data:f.data!==void 0?f.data:x.data,headers:{...x.headers,...f.headers},allow:f.allow?Array.isArray(f.allow)?[...f.allow]:[f.allow]:x.allow,cause:f.cause??x.cause,stack:x.stack,causeStack:x.causeStack,formatter:x.formatter??f.formatter,sanitize:x.sanitize?[...x.sanitize||[],...f.sanitize||[]]:f.sanitize,includeStackTrace:x.includeStackTrace!==void 0?x.includeStackTrace:f.includeStackTrace};if(x instanceof Error)return G({...f,message:f.message??x.message,cause:x});return G({...f,message:f.message??(typeof x==="string"?x:"Unknown error"),cause:x})}function R(x,f,y={}){return f.format(x,y.headers,y.sanitize,y.includeStackTrace)}function _(x,f){let y=new Headers({"Content-Type":"application/json",...x.headers});if(x.allow?.length)y.set("Allow",x.allow.join(", "));let M=x.data&&typeof x.data==="object"&&"isDeveloperError"in x.data&&x.data.isDeveloperError===!0;return new Response(JSON.stringify(f),{status:x.status,headers:y})}function Z(x,f){if(!f.length)return x;if(Array.isArray(x))return x.map((y)=>Z(y,f));if(x!==null&&typeof x==="object")return Object.entries(x).reduce((y,[M,X])=>{if(f.includes(M))return y;return y[M]=Z(X,f),y},{});return x}var P={contentType:"application/json",format(x,f={},y=[],M=!1){let{status:X,message:J,data:Q}=x,Y={statusCode:X,error:$[X]||"Unknown Error"};if(typeof J==="string")Y.message=J;let w=Q&&typeof Q==="object"&&"isDeveloperError"in Q&&Q.isDeveloperError===!0;if(M||w){if(x.stack)Y.stack=x.stack;if(x.causeStack)Y.causeStack=x.causeStack}if(Q!==void 0)Y.data=Q;return Z(Y,y)}};import{z as j}from"@hono/zod-openapi";var b=j.object({name:j.string().openapi({example:"username",description:"The field name that failed validation"}),reason:j.string().openapi({example:"String must contain at least 3 character(s)",description:"The reason for validation failure"})}),q=j.object({name:j.string().openapi({example:"email",description:"The field name that violated a constraint"}),reason:j.string().openapi({example:"Email already exists",description:"The reason for the constraint violation"}),resource:j.string().openapi({example:"user",description:"The resource type that contains the constraint"}),constraint:j.string().openapi({example:"unique",description:"The type of constraint that was violated"})}),F=j.object({"invalid-params":j.array(b).optional(),violations:j.array(q).optional()}),V=j.object({type:j.string().url().openapi({example:"https://api.example.com/problems/validation-error",description:"A URI reference that identifies the problem type"}),title:j.string().openapi({example:"Validation Failed",description:"A short, human-readable summary of the problem type"}),status:j.number().int().min(400).max(599).openapi({example:400,description:"The HTTP status code"}),detail:j.string().optional().openapi({example:"The request contains invalid fields",description:"A human-readable explanation specific to this occurrence of the problem"}),instance:j.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:j.string().datetime().optional().openapi({example:"2025-02-26T12:34:56.789Z",description:"When the error occurred"})}).merge(F);function z(x={}){let f=x.baseUrl||"https://api.example.com/problems";return{contentType:"application/problem+json",format(y){let M={type:`${f}/${y.status}`,title:$[y.status]||"Unknown Error",status:y.status,detail:y.message,instance:`urn:uuid:${crypto.randomUUID()}`,timestamp:new Date().toISOString()};if(y.data?.["invalid-params"])return V.parse({...M,"invalid-params":y.data["invalid-params"]});if(y.data?.violations)return V.parse({...M,violations:y.data.violations});return V.parse(M)}}}function T(x){return{"invalid-params":b.array().parse(x)}}function N(x){return{"invalid-params":b.array().parse(x.errors.map((f)=>({name:f.path.join("."),reason:f.message})))}}function C(x,f,y,M="unique"){return{violations:q.array().parse([{name:x,reason:f,resource:y,constraint:M}])}}import{ZodError as l}from"zod";function K(x,f,y){if(typeof f==="string")return G({...y,statusCode:x,message:f});return G({...f,...y,statusCode:x})}function U(x,f){return K(400,x,f)}function x7(x,f){return K(401,x,f)}function f7(x,f){return K(402,x,f)}function y7(x,f){return K(403,x,f)}function K7(x,f){return K(404,x,f)}function M7(x,f){return K(405,x,f)}function j7(x,f){return K(406,x,f)}function G7(x,f){return K(407,x,f)}function H7(x,f){return K(408,x,f)}function J7(x,f){return K(409,x,f)}function Q7(x,f){return K(410,x,f)}function X7(x,f){return K(411,x,f)}function Y7(x,f){return K(412,x,f)}function $7(x,f){return K(413,x,f)}function b7(x,f){return K(414,x,f)}function V7(x,f){return K(415,x,f)}function Z7(x,f){return K(416,x,f)}function q7(x,f){return K(417,x,f)}function B7(x,f){return K(418,x,f)}function w7(x,f){return K(421,x,f)}function N7(x,f){return K(422,x,f)}function k7(x,f){return K(423,x,f)}function L7(x,f){return K(424,x,f)}function I7(x,f){return K(425,x,f)}function R7(x,f){return K(426,x,f)}function _7(x,f){return K(428,x,f)}function P7(x,f){return K(429,x,f)}function F7(x,f){return K(431,x,f)}function U7(x,f){return K(451,x,f)}function H(x,f,y){if(typeof f==="string")return G({...y,statusCode:x,message:f});return G({...f,...y,statusCode:x})}function v7(x,f){return H(500,x,f)}function z7(x,f){return H(501,x,f)}function T7(x,f){return H(502,x,f)}function C7(x,f){return H(503,x,f)}function l7(x,f){return H(504,x,f)}function W7(x,f){return H(505,x,f)}function h7(x,f){return H(506,x,f)}function S7(x,f){return H(507,x,f)}function E7(x,f){return H(508,x,f)}function d7(x,f){return H(510,x,f)}function u7(x,f){return H(511,x,f)}function c7(x,f){let y=typeof x==="string"?{...f,message:x}:{...x,...f},M={isDeveloperError:!0,...y.data||{}};return G({...y,statusCode:500,data:M})}function A(x){return(f,y)=>{if(!f.success&&"error"in f&&f.error instanceof l){let M=N(f.error);throw U({message:x?.message||"Validation Error",data:M,formatter:x?.formatter,headers:x?.headers,sanitize:x?.sanitize,includeStackTrace:x?.includeStackTrace})}}}var W=A();var B={formatter:P,sanitize:[],includeStackTrace:!1,headers:{}};function k(x={}){let f={...B,...x,formatter:x.formatter?x.formatter:B.formatter,headers:{...B.headers,...x.headers},sanitize:[...B.sanitize,...x.sanitize||[]]};return async(y,M)=>{try{await M()}catch(X){let J=I(X,{formatter:f.formatter,headers:f.headers,sanitize:f.sanitize,includeStackTrace:f.includeStackTrace}),Q=J.formatter||f.formatter,Y=[...f.sanitize||[],...J.sanitize||[]],w=J.includeStackTrace!==void 0?J.includeStackTrace:f.includeStackTrace,D=R(J,Q,{headers:J.headers||f.headers,sanitize:Y,includeStackTrace:w});return _(J,D)}}}var Qx=k;export{h7 as variantAlsoNegotiates,b7 as uriTooLong,R7 as upgradeRequired,V7 as unsupportedMediaType,x7 as unauthorized,P7 as tooManyRequests,I7 as tooEarly,B7 as teapot,C7 as serverUnavailable,W as rfc7807Hook,Q7 as resourceGone,Z7 as rangeNotSatisfiable,G7 as proxyAuthRequired,_7 as preconditionRequired,Y7 as preconditionFailed,f7 as paymentRequired,z7 as notImplemented,K7 as notFound,d7 as notExtended,j7 as notAcceptable,u7 as networkAuthRequired,w7 as misdirectedRequest,M7 as methodNotAllowed,E7 as loopDetected,k7 as locked,X7 as lengthRequired,v as isBanError,v7 as internal,S7 as insufficientStorage,U7 as illegal,W7 as httpVersionNotSupported,F7 as headerFieldsTooLarge,l7 as gatewayTimeout,R as formatError,y7 as forbidden,L7 as failedDependency,q7 as expectationFailed,$7 as entityTooLarge,P as defaultFormatter,Qx as default,N as createRFC7807ZodValidationError,T as createRFC7807ValidationError,A as createRFC7807Hook,z as createRFC7807Formatter,C as createRFC7807ConstraintViolation,_ as createErrorResponse,G as createError,I as convertToBanError,J7 as conflict,H7 as clientTimeout,U as badRequest,c7 as badImplementation,T7 as badGateway,N7 as badData,$ as STATUS_CODES,b as RFC7807ValidationParamSchema,F as RFC7807ErrorDataSchema,V as RFC7807DetailsSchema,q as RFC7807ConstraintViolationSchema};