UNPKG

http-status-meaning

Version:

A comprehensive library for HTTP status codes with internationalization and use cases

3 lines (2 loc) 20.7 kB
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e="undefined"!=typeof globalThis?globalThis:e||self).httpStatusMeaning=r()}(this,(function(){"use strict";const e={100:"Continue - The server has received the request headers and the client should proceed to send the request body.",101:"Switching Protocols - The requester has asked the server to switch protocols and the server has agreed to do so.",102:"Processing - The server has received and is processing the request, but no response is available yet.",103:"Early Hints - Used to return some response headers before final HTTP message.",200:"OK - The request was successful.",201:"Created - A new resource was successfully created.",202:"Accepted - The request has been accepted for processing, but the processing has not been completed.",203:"Non-Authoritative Information - The returned information is from a cached copy instead of the origin server.",204:"No Content - The request was successful, but there's no content to return.",205:"Reset Content - The server has fulfilled the request and desires that the user agent reset the document view.",206:"Partial Content - The server is delivering only part of the resource due to a range header sent by the client.",207:"Multi-Status - The message body that follows is an XML message and can contain multiple separate response codes.",208:"Already Reported - The members of a DAV binding have already been enumerated in a previous reply.",226:"IM Used - The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.",300:"Multiple Choices - The request has more than one possible response.",301:"Moved Permanently - The URL of the requested resource has been changed permanently.",302:"Found - The URI of requested resource has been changed temporarily.",303:"See Other - The response to the request can be found under another URI using a GET method.",304:"Not Modified - The resource has not been modified since the last request.",305:"Use Proxy - The requested resource is available only through a proxy.",307:"Temporary Redirect - The request should be repeated with another URI, but future requests should still use the original URI.",308:"Permanent Redirect - The request and all future requests should be repeated using another URI.",400:"Bad Request - The request could not be understood.",401:"Unauthorized - Authentication is required.",402:"Payment Required - Payment is required for the requested resource.",403:"Forbidden - The server understood the request but refuses to authorize it.",404:"Not Found - The requested resource does not exist.",405:"Method Not Allowed - The request method is not supported for the requested resource.",406:"Not Acceptable - The requested resource cannot generate content according to the Accept headers sent.",407:"Proxy Authentication Required - The client must first authenticate itself with the proxy.",408:"Request Timeout - The server timed out waiting for the request.",409:"Conflict - The request could not be completed due to a conflict with the current state of the resource.",410:"Gone - The requested resource is no longer available and will not be available again.",411:"Length Required - The request did not specify the length of its content.",412:"Precondition Failed - The server does not meet one of the preconditions specified in the request.",413:"Payload Too Large - The request entity is larger than limits defined by server.",414:"URI Too Long - The URI provided was too long for the server to process.",415:"Unsupported Media Type - The request entity has a media type which the server or resource does not support.",416:"Range Not Satisfiable - The client has asked for a portion of the file, but the server cannot supply that portion.",417:"Expectation Failed - The server cannot meet the requirements of the Expect request-header field.",418:"I'm a teapot - The server refuses the attempt to brew coffee with a teapot.",421:"Misdirected Request - The request was directed at a server that is not able to produce a response.",422:"Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors.",423:"Locked - The resource that is being accessed is locked.",424:"Failed Dependency - The request failed due to failure of a previous request.",425:"Too Early - The server is unwilling to risk processing a request that might be replayed.",426:"Upgrade Required - The client should switch to a different protocol.",428:"Precondition Required - The origin server requires the request to be conditional.",429:"Too Many Requests - The user has sent too many requests in a given amount of time.",431:"Request Header Fields Too Large - The server is unwilling to process the request because its header fields are too large.",451:"Unavailable For Legal Reasons - The resource is unavailable due to legal reasons.",500:"Internal Server Error - A generic error message for server issues.",501:"Not Implemented - The server does not support the functionality required to fulfill the request.",502:"Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server.",503:"Service Unavailable - The server is temporarily unavailable.",504:"Gateway Timeout - The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.",505:"HTTP Version Not Supported - The server does not support the HTTP protocol version used in the request.",506:"Variant Also Negotiates - The server has an internal configuration error.",507:"Insufficient Storage - The server is unable to store the representation needed to complete the request.",508:"Loop Detected - The server detected an infinite loop while processing the request.",510:"Not Extended - Further extensions to the request are required for the server to fulfill it.",511:"Network Authentication Required - The client needs to authenticate to gain network access."},r=["en","es","fr","de","pt","it","ru","zh","ja","ar"],t={en:{Informational:"Informational",Success:"Success",Redirection:"Redirection","Client Error":"Client Error","Server Error":"Server Error",Unknown:"Unknown"},es:{Informational:"Informativo",Success:"Éxito",Redirection:"Redirección","Client Error":"Error del Cliente","Server Error":"Error del Servidor",Unknown:"Desconocido"},fr:{Informational:"Information",Success:"Succès",Redirection:"Redirection","Client Error":"Erreur Client","Server Error":"Erreur Serveur",Unknown:"Inconnu"},de:{Informational:"Information",Success:"Erfolg",Redirection:"Umleitung","Client Error":"Client-Fehler","Server Error":"Server-Fehler",Unknown:"Unbekannt"},pt:{Informational:"Informativo",Success:"Sucesso",Redirection:"Redirecionamento","Client Error":"Erro do Cliente","Server Error":"Erro do Servidor",Unknown:"Desconhecido"},it:{Informational:"Informativo",Success:"Successo",Redirection:"Reindirizzamento","Client Error":"Errore del Client","Server Error":"Errore del Server",Unknown:"Sconosciuto"},ru:{Informational:"Информационный",Success:"Успех",Redirection:"Перенаправление","Client Error":"Ошибка Клиента","Server Error":"Ошибка Сервера",Unknown:"Неизвестно"},zh:{Informational:"信息性",Success:"成功",Redirection:"重定向","Client Error":"客户端错误","Server Error":"服务器错误",Unknown:"未知"},ja:{Informational:"情報",Success:"成功",Redirection:"リダイレクション","Client Error":"クライアントエラー","Server Error":"サーバーエラー",Unknown:"不明"},ar:{Informational:"معلوماتي",Success:"نجاح",Redirection:"إعادة توجيه","Client Error":"خطأ العميل","Server Error":"خطأ الخادم",Unknown:"غير معروف"}},n={es:{200:"OK - La solicitud ha tenido éxito.",201:"Creado - Se ha creado un nuevo recurso con éxito.",400:"Solicitud incorrecta - El servidor no pudo entender la solicitud.",401:"No autorizado - Se requiere autenticación.",403:"Prohibido - El servidor entendió la solicitud, pero se niega a autorizarla.",404:"No encontrado - El recurso solicitado no existe.",500:"Error interno del servidor - Un mensaje de error genérico para problemas del servidor.",503:"Servicio no disponible - El servidor no está disponible temporalmente."},fr:{200:"OK - La requête a réussi.",201:"Créé - Une nouvelle ressource a été créée avec succès.",400:"Mauvaise demande - Le serveur n'a pas pu comprendre la requête.",401:"Non autorisé - Une authentification est nécessaire.",403:"Interdit - Le serveur a compris la requête mais refuse de l'autoriser.",404:"Non trouvé - La ressource demandée n'existe pas.",500:"Erreur interne du serveur - Un message d'erreur générique pour les problèmes de serveur.",503:"Service indisponible - Le serveur est temporairement indisponible."},de:{200:"OK - Die Anfrage war erfolgreich.",201:"Erstellt - Eine neue Ressource wurde erfolgreich erstellt.",400:"Fehlerhafte Anfrage - Die Anfrage konnte nicht verstanden werden.",401:"Nicht autorisiert - Authentifizierung ist erforderlich.",403:"Verboten - Der Server hat die Anfrage verstanden, weigert sich aber, sie zu autorisieren.",404:"Nicht gefunden - Die angeforderte Ressource existiert nicht.",500:"Interner Serverfehler - Eine generische Fehlermeldung für Serverprobleme.",503:"Dienst nicht verfügbar - Der Server ist vorübergehend nicht verfügbar."},pt:{200:"OK - A requisição foi bem-sucedida.",201:"Criado - Um novo recurso foi criado com sucesso.",400:"Requisição inválida - O servidor não conseguiu entender a requisição.",401:"Não autorizado - Autenticação é necessária.",403:"Proibido - O servidor entendeu a requisição, mas recusa-se a autorizá-la.",404:"Não encontrado - O recurso solicitado não existe.",500:"Erro interno do servidor - Uma mensagem de erro genérica para problemas no servidor.",503:"Serviço indisponível - O servidor está temporariamente indisponível."},it:{200:"OK - La richiesta è stata completata con successo.",201:"Creato - Una nuova risorsa è stata creata con successo.",400:"Richiesta errata - Il server non ha potuto comprendere la richiesta.",401:"Non autorizzato - È richiesta l'autenticazione.",403:"Vietato - Il server ha compreso la richiesta, ma si rifiuta di autorizzarla.",404:"Non trovato - La risorsa richiesta non esiste.",500:"Errore interno del server - Un messaggio di errore generico per problemi del server.",503:"Servizio non disponibile - Il server è temporaneamente non disponibile."},ru:{200:"OK - Запрос успешно выполнен.",201:"Создано - Новый ресурс был успешно создан.",400:"Плохой запрос - Сервер не смог понять запрос.",401:"Не авторизован - Требуется аутентификация.",403:"Запрещено - Сервер понял запрос, но отказывается его авторизовать.",404:"Не найдено - Запрашиваемый ресурс не существует.",500:"Внутренняя ошибка сервера - Общее сообщение об ошибке для проблем сервера.",503:"Сервис недоступен - Сервер временно недоступен."},zh:{200:"成功 - 请求成功。",201:"已创建 - 成功创建了新资源。",400:"错误请求 - 服务器无法理解该请求。",401:"未授权 - 需要身份验证。",403:"禁止 - 服务器理解请求,但拒绝授权。",404:"未找到 - 请求的资源不存在。",500:"服务器内部错误 - 服务器问题的通用错误消息。",503:"服务不可用 - 服务器暂时不可用。"},ja:{200:"OK - リクエストは成功しました。",201:"作成済み - 新しいリソースが正常に作成されました。",400:"不正なリクエスト - サーバーはリクエストを理解できませんでした。",401:"未認証 - 認証が必要です。",403:"禁止 - サーバーはリクエストを理解しましたが、承認を拒否しています。",404:"見つかりません - 要求されたリソースは存在しません。",500:"サーバー内部エラー - サーバーの問題に関する一般的なエラーメッセージ。",503:"サービス利用不可 - サーバーは一時的に利用できません。"},ar:{200:"موافق - نجح الطلب.",201:"تم الإنشاء - تم إنشاء مورد جديد بنجاح.",400:"طلب خاطئ - لم يستطع الخادم فهم الطلب.",401:"غير مصرح - المصادقة مطلوبة.",403:"محظور - فهم الخادم الطلب ولكنه يرفض تفويضه.",404:"غير موجود - المورد المطلوب غير موجود.",500:"خطأ داخلي في الخادم - رسالة خطأ عامة لمشاكل الخادم.",503:"الخدمة غير متوفرة - الخادم غير متاح مؤقتًا."}},o={100:["When uploading large files in chunks to indicate the server is ready for the next chunk","In WebSockets to confirm a handshake is in progress"],101:["During WebSocket connection establishment","When switching from HTTP to WebSockets protocol"],200:["Standard response for successful HTTP requests","Response to successful GET requests","When an API request completes successfully"],201:["After a POST request that creates a new resource","When an item is successfully added to a database","After user registration is complete"],204:["After a successful DELETE operation","When submitting a form that should not navigate away","When an update operation succeeds but no content needs to be returned"],301:["When a website has moved permanently to a new domain","Redirecting from old URLs to new URLs for SEO purposes","When consolidating multiple URLs to a canonical URL"],302:["Temporary redirects during maintenance","After a successful form submission to redirect to a confirmation page","For A/B testing to temporarily direct users to different versions"],304:["When browser cache is still valid","When a resource hasn't changed since the last request","To reduce bandwidth by not resending unchanged files"],400:["When form validation fails","When request parameters are missing or invalid","When the JSON payload is malformed"],401:["When a user tries to access a resource without logging in","When an API key is missing or invalid","When session tokens have expired"],403:["When a user is logged in but lacks permission for a resource","When IP-based restrictions prevent access","When trying to modify read-only resources"],404:["When a URL doesn't exist","When a resource has been deleted","To mask the existence of sensitive resources for security"],429:["When rate limits have been exceeded","To prevent brute force attacks","When a client is making too many requests in a short time period"],500:["When an unhandled exception occurs","During database connection failure","When the server encounters an unexpected condition"],502:["When a proxy or load balancer can't reach the upstream server","During server deployment or restart","When the backend service is down"],503:["During scheduled maintenance","When the server is overloaded","When a service is temporarily unavailable due to high traffic"]},s={"not found":404,"bad request":400,unauthorized:401,forbidden:403,"internal server error":500,"service unavailable":503,ok:200,created:201,continue:100,"moved permanently":301,found:302,"resource not found":404,"server internal error":500,"not found - the requested resource does not exist.":404},i={continue:100,switching:101,processing:102,"early hints":103,ok:200,created:201,accepted:202,"non-authoritative":203,"no content":204,reset:205,partial:206,"multi-status":207,"already reported":208,"im used":226,"multiple choices":300,"moved permanently":301,found:302,"see other":303,"not modified":304,"use proxy":305,"temporary redirect":307,"permanent redirect":308,"bad request":400,unauthorized:401,"payment required":402,forbidden:403,"not found":404,"method not allowed":405,"not acceptable":406,"proxy authentication":407,"request timeout":408,conflict:409,gone:410,"length required":411,"precondition failed":412,"payload too large":413,"uri too long":414,"unsupported media":415,"range not satisfiable":416,"expectation failed":417,teapot:418,misdirected:421,unprocessable:422,locked:423,"failed dependency":424,"too early":425,"upgrade required":426,"precondition required":428,"too many requests":429,"fields too large":431,"legal reasons":451,"internal server error":500,"not implemented":501,"bad gateway":502,"service unavailable":503,"gateway timeout":504,"http version":505,variant:506,"insufficient storage":507,"loop detected":508,"not extended":510,"network authentication":511,redirect:302,moved:301,resource:404,"server error":500,"internal error":500},a=["not a ","is not ","not an ","invalid ","no such ","unknown "];function u(e){return null==e?null:"number"==typeof e?isNaN(e)?null:e:"string"==typeof e&&/^\d+$/.test(e)?parseInt(e,10):null}function c(r){if(!r||"string"!=typeof r)return null;const t=r.toLowerCase();if(function(e){if(!e||"string"!=typeof e)return!1;const r=e.toLowerCase();return a.some((e=>r.includes(e)))}(t))return null;if(s[t])return s[t];if(t.includes("not found"))return 404;for(const e in i)if(t===e||t.includes(` ${e} `)||t.startsWith(`${e} `)||t.endsWith(` ${e}`))return i[e];if(!function(e){if(!e||"string"!=typeof e)return!1;const r=e.toLowerCase();if(s[r])return!0;for(const e of a)if(r.includes(e))return!1;for(const e in i)if(r===e||r.includes(e))return!0;return!!["not found","bad request","unauthorized","forbidden","ok","internal server error","service unavailable","created","continue"].includes(r)||["ok","success","created","found","redirect","not found","error","unauthorized","bad","forbidden","server","client","unavailable","timeout"].some((e=>r===e||r.includes(` ${e} `)||r.startsWith(`${e} `)||r.endsWith(` ${e}`)))}(t))return null;for(const[r,n]of Object.entries(e)){if(n.toLowerCase()===t)return parseInt(r,10);if(n.split(" - ")[0].toLowerCase()===t)return parseInt(r,10)}const n=[];for(const[r,o]of Object.entries(e)){o.toLowerCase().includes(t)&&n.push({code:parseInt(r,10),score:t.length})}if(n.length>0)return n.sort(((e,r)=>r.score-e.score)),n[0].code;const o=t.split(/\s+/).filter((e=>e.length>3));if(o.length>0){const r=[];for(const[t,n]of Object.entries(e)){const e=n.toLowerCase();let s=0,i=0;for(const r of o){if(["this","that","with","from","have","invalid"].includes(r))continue;new RegExp(`\\b${r}\\b`,"i").test(e)?(i++,s+=3):e.includes(r)&&(s+=1)}i>1&&(s*=2),s>0&&r.push({code:parseInt(t,10),score:s})}if(r.sort(((e,r)=>r.score-e.score)),r.length>0&&r[0].score>2)return r[0].code}return null}function d(t,o="en"){let s=u(t);return null===s&&"string"==typeof t&&(s=c(t)),null===s?"Unknown status code":"en"!==o&&r.includes(o)?n[o]?.[s]||e[s]||"Unknown status code":e[s]||"Unknown status code"}function l(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null!==r&&(r>=100&&r<200)}function h(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null!==r&&(r>=200&&r<300)}function f(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null!==r&&(r>=300&&r<400)}function p(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null!==r&&(r>=400&&r<500)}function m(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null!==r&&(r>=500&&r<600)}var v={getStatusMeaning:d,getStatusCategory:function(e,n="en"){let o,s=u(e);return null===s&&"string"==typeof e&&(s=c(e)),null===s?"en"!==n&&r.includes(n)&&t[n].Unknown||"Unknown":(o=s>=100&&s<200?"Informational":s>=200&&s<300?"Success":s>=300&&s<400?"Redirection":s>=400&&s<500?"Client Error":s>=500&&s<600?"Server Error":"Unknown","en"!==n&&r.includes(n)&&t[n][o]||o)},isInformational:l,isSuccess:h,isRedirection:f,isClientError:p,isServerError:m,getStatusCodesByCategory:function(r,t="en"){const n={};for(const o in e){const e=parseInt(o);("informational"===r&&l(e)||"success"===r&&h(e)||"redirection"===r&&f(e)||"clientError"===r&&p(e)||"serverError"===r&&m(e))&&(n[o]=d(e,t))}return n},getAllStatusCodes:function(r="en"){const t={};for(const n in e)t[n]=d(parseInt(n),r);return t},getStatusCodeUseCases:function(e){let r=u(e);return null===r&&"string"==typeof e&&(r=c(e)),null===r?[]:o[r]||[]},getSupportedLanguages:function(){return[...r]},findStatusCodeByDescription:c};return"undefined"!=typeof window&&(window.httpStatusMeaning=v),v})); //# sourceMappingURL=http-status-meaning.min.js.map