fourohfour 1.0.0-test → 1.0.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. This project follows [Semantic Versioning](https://semver.org/).
4
+
5
+ ## 1.0.0 - Unreleased
6
+
7
+ First release.
8
+
9
+ - `Status` constants for every IANA-registered code, named after the RFC 9110 reason phrase and typed as literals (`Status.OK` is the type `200`). Legacy names (`UNPROCESSABLE_ENTITY`, `PAYLOAD_TOO_LARGE`, `REQUEST_ENTITY_TOO_LARGE`, ...) are kept as deprecated aliases.
10
+ - `Unofficial` constants for common non-standard codes: 418, 419, 420, IIS 440/449, nginx 444/494-499, 509, Cloudflare 520-527, 598/599 and more, flagged `official: false`.
11
+ - `Reason` map with RFC 9110 phrases (413 *Content Too Large*, 422 *Unprocessable Content*).
12
+ - `reason(code, { legacy })`: reason phrase, with Node.js-compatible legacy phrases on request; literal return types for known codes.
13
+ - `code(phrase)`: reverse lookup ignoring case and punctuation; accepts legacy phrases and constant names.
14
+ - `info(code)`: name, category, official/deprecated flags, RFC section and link, description, aliases, and retryable/cacheable/empty-body flags.
15
+ - `allCodes()`, `category()`.
16
+ - Predicates: `isValid`, `isKnown`, `isOfficial`, `isInformational`, `isSuccess`, `isRedirection`, `isClientError`, `isServerError`, `isError`, `isRedirect`, `isRedirectWithBody`, `isRetryable`, `isEmptyBody`, `isCacheable`.
17
+ - `HttpError` and `createError()`: `status`, `statusCode`, `expose`, `headers`, `cause`; `toJSON()` returns RFC 9457 problem details and `toResponse()` a web `Response`. `isHttpError()` works across duplicate installs.
18
+ - Types: `StatusCode`, `UnofficialStatusCode`, `KnownStatusCode`, `InformationalStatus`, `SuccessStatus`, `RedirectionStatus`, `ClientErrorStatus`, `ServerErrorStatus`, `ErrorStatus`, `ReasonPhrase<C>`, `CodeOf<P>`, `StatusName`, `StatusInfo`, `ProblemDetails`.
19
+ - Tree-shakeable named exports, ESM + CommonJS, zero dependencies.
package/README.md CHANGED
@@ -1,18 +1,629 @@
1
1
  # fourohfour
2
2
 
3
- HTTP status codes and reason phrases as typed constants. Work in progress.
3
+ HTTP status codes as typed constants, with reason phrases, lookups, helper checks and an error class.
4
4
 
5
- > This is an early placeholder release. The full API is coming soon.
5
+ [![npm version](https://img.shields.io/npm/v/fourohfour.svg)](https://www.npmjs.com/package/fourohfour) [![bundle size](https://img.shields.io/bundlephobia/minzip/fourohfour)](https://bundlephobia.com/package/fourohfour) [![license](https://img.shields.io/npm/l/fourohfour.svg)](LICENSE)
6
+
7
+ fourohfour gives you every HTTP status code as a named constant, with the current reason phrase from RFC 9110 (the HTTP standard). It also answers common questions, such as "should I retry this request?". Its `HttpError` class turns into RFC 9457 problem details, a standard JSON format for API errors. Use it in servers, API clients and anywhere you check or send status codes.
8
+
9
+ ## Features
10
+
11
+ - **Typed constants**: `Status.OK` has the type `200`, not `number`, so TypeScript can narrow `switch` statements and unions.
12
+ - **Current names**: every IANA-registered code with its RFC 9110 phrase (413 *Content Too Large*, 422 *Unprocessable Content*). Old names still work as deprecated aliases.
13
+ - **Unofficial codes kept apart**: 418, 419, 420, nginx 444 and 494-499, Cloudflare 520-527 and more live in `Unofficial`, marked `official: false`.
14
+ - **Lookups both ways**: `reason(404)` and `code('not found')`. Case and punctuation do not matter. Unknown values return `undefined` instead of throwing.
15
+ - **Helper checks**: `isRetryable`, `isRedirect`, `isEmptyBody`, `isCacheable`, class checks such as `isClientError`, and `info()` with spec links and descriptions.
16
+ - **`HttpError`**: same shape as an `http-errors` error. `toJSON()` gives problem details and `toResponse()` gives a web `Response`.
17
+ - **Small and tree-shakeable** (your bundler drops what you do not import): `Status` alone is about 0.75 KB gzipped, everything is about 6.6 KB.
18
+ - **Zero dependencies**, ESM and CommonJS, TypeScript types included.
19
+
20
+ ## Installation
6
21
 
7
22
  ```sh
8
23
  npm install fourohfour
9
24
  ```
10
25
 
26
+ ```sh
27
+ pnpm add fourohfour
28
+ yarn add fourohfour
29
+ bun add fourohfour
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ ```js
35
+ import { Status, reason, code, isRetryable, HttpError } from 'fourohfour'
36
+
37
+ Status.NOT_FOUND // => 404
38
+ reason(404) // => 'Not Found'
39
+ reason(413) // => 'Content Too Large'
40
+ reason(413, { legacy: true }) // => 'Payload Too Large' (what Node.js says)
41
+ code('not found') // => 404
42
+ code('Unprocessable Entity') // => 422 (old names work)
43
+ isRetryable(503) // => true
44
+
45
+ const error = new HttpError(404, 'No user with id 42')
46
+ error.toJSON()
47
+ // => { type: 'about:blank', title: 'Not Found', status: 404, detail: 'No user with id 42' }
48
+ ```
49
+
50
+ With CommonJS:
51
+
52
+ ```js
53
+ const { Status } = require('fourohfour')
54
+ ```
55
+
56
+ ## Table of contents
57
+
58
+ - [Usage](#usage)
59
+ - [API](#api)
60
+ - [Comparison](#comparison)
61
+ - [Migrating from other packages](#migrating-from-other-packages)
62
+ - [Notes and limitations](#notes-and-limitations)
63
+ - [Requirements](#requirements)
64
+ - [License](#license)
65
+
66
+ ## Usage
67
+
68
+ ### Compare a status code with a constant
69
+
70
+ ```js
71
+ import { Status } from 'fourohfour'
72
+
73
+ if (res.status === Status.NO_CONTENT) return null
74
+ if (res.status === Status.NOT_FOUND) return undefined
75
+ ```
76
+
77
+ Hover a constant in your editor to see its phrase and the RFC that defines it.
78
+
79
+ ### Get the reason phrase for a code
80
+
81
+ ```js
82
+ import { reason } from 'fourohfour'
83
+
84
+ reason(404) // => 'Not Found'
85
+ reason('503') // => 'Service Unavailable'
86
+ reason(299) // => undefined
87
+
88
+ console.log(`${req.method} ${req.url} ${res.statusCode} ${reason(res.statusCode)}`)
89
+ // Prints: GET /users/42 404 Not Found
90
+ ```
91
+
92
+ ### Find the code for a phrase or name
93
+
94
+ ```js
95
+ import { code } from 'fourohfour'
96
+
97
+ code('Not Found') // => 404
98
+ code('NOT_FOUND') // => 404
99
+ code('Gateway Time-out') // => 504
100
+ code('Nope') // => undefined
101
+ ```
102
+
103
+ ### Decide what to do with a response
104
+
105
+ ```js
106
+ import { isRetryable, isEmptyBody } from 'fourohfour'
107
+
108
+ if (isRetryable(res.status)) await retryLater(res.headers.get('retry-after'))
109
+
110
+ if (isEmptyBody(status)) res.end()
111
+ else res.end(body)
112
+ ```
113
+
114
+ `isRetryable` is `true` for 408, 425, 429, 500, 502, 503 and 504. See [Helper checks](#helper-checks) for the full list.
115
+
116
+ ### Throw an HTTP error
117
+
118
+ ```js
119
+ import { HttpError, createError } from 'fourohfour'
120
+
121
+ throw new HttpError(404) // message: 'Not Found'
122
+ throw new HttpError(404, 'No user with id 42')
123
+ throw new HttpError(429, { headers: { 'Retry-After': '60' } })
124
+ throw new HttpError(502, 'Payment provider failed', { cause: err })
125
+ throw createError(403, 'Admins only') // same as new HttpError(...)
126
+ ```
127
+
128
+ ### Send errors from an Express app
129
+
130
+ ```js
131
+ import { HttpError, isHttpError, PROBLEM_JSON } from 'fourohfour'
132
+
133
+ app.use((err, req, res, next) => {
134
+ const e = isHttpError(err) ? err : new HttpError(500, { cause: err })
135
+ res.status(e.status).set(e.headers).type(PROBLEM_JSON).json(e)
136
+ })
137
+ ```
138
+
139
+ `res.json(e)` calls `e.toJSON()`, so the client gets problem details.
140
+
141
+ ### Return errors from a fetch handler
142
+
143
+ `toResponse()` gives a web-standard `Response`. Use it in fetch handlers, edge functions, Bun, Deno and Hono.
144
+
145
+ ```js
146
+ import { HttpError, isHttpError } from 'fourohfour'
147
+
148
+ export default {
149
+ async fetch(req) {
150
+ try {
151
+ return await handle(req)
152
+ } catch (err) {
153
+ return (isHttpError(err) ? err : new HttpError(500, { cause: err })).toResponse()
154
+ }
155
+ },
156
+ }
157
+ ```
158
+
159
+ ### Keep internal error messages private
160
+
161
+ By default, `toJSON()` includes your message for 4xx errors and leaves it out for 5xx errors. This stops internal details from reaching the client.
162
+
163
+ ```js
164
+ import { HttpError, isRetryable, reason } from 'fourohfour'
165
+
166
+ new HttpError(500, 'SQL error near "users"').toJSON()
167
+ // => { type: 'about:blank', title: 'Internal Server Error', status: 500 }
168
+
169
+ // Report an upstream failure. Keep the details in `cause` for your logs.
170
+ const res = await fetch(url)
171
+ if (!res.ok) {
172
+ throw new HttpError(isRetryable(res.status) ? 503 : 502, {
173
+ cause: new Error(`${url}: ${res.status} ${reason(res.status) ?? ''}`),
174
+ })
175
+ }
176
+ ```
177
+
178
+ ### Accept only some status codes in TypeScript
179
+
180
+ ```ts
181
+ import { Status } from 'fourohfour'
182
+ import type { SuccessStatus } from 'fourohfour'
183
+
184
+ function send(status: SuccessStatus, body: unknown) { /* ... */ }
185
+
186
+ send(Status.OK, data) // OK
187
+ send(Status.NOT_FOUND, data) // Type error: 404 is not a success status
188
+ ```
189
+
190
+ ### List every status code
191
+
192
+ ```js
193
+ import { allCodes } from 'fourohfour'
194
+
195
+ allCodes() // => [100, 101, 102, 103, 200, ...] (61 official codes)
196
+ allCodes({ unofficial: true }) // => [100, 101, 102, 103, 104, 200, ...] (88 codes)
197
+ ```
198
+
199
+ Use `allCodes()` instead of `Object.values(Status)`. `Status` has deprecated aliases, so some codes appear more than once in it.
200
+
201
+ ## API
202
+
203
+ All exports are named. There is no default export.
204
+
205
+ ### Status, Unofficial, Reason
206
+
207
+ ```ts
208
+ const Status: { readonly CONTINUE: 100; readonly OK: 200; readonly NOT_FOUND: 404; /* ... */ }
209
+ const Unofficial: { readonly IM_A_TEAPOT: 418; readonly CLIENT_CLOSED_REQUEST: 499; /* ... */ }
210
+ const Reason: { readonly 200: 'OK'; readonly 404: 'Not Found'; /* ... */ }
211
+ ```
212
+
213
+ - `Status` has every IANA-registered code, named after its RFC 9110 reason phrase.
214
+ - `Unofficial` has codes that are common but not registered.
215
+ - `Reason` maps every known code, official and unofficial, to its reason phrase.
216
+
217
+ ```js
218
+ import { Status, Unofficial, Reason } from 'fourohfour'
219
+
220
+ Status.OK // => 200
221
+ Status.UNPROCESSABLE_CONTENT // => 422
222
+ Status.UNPROCESSABLE_ENTITY // => 422 (deprecated alias)
223
+ Unofficial.CLIENT_CLOSED_REQUEST // => 499
224
+ Reason[404] // => 'Not Found'
225
+ ```
226
+
227
+ Deprecated aliases in `Status` are kept so old code still compiles. Editors show them struck through.
228
+
229
+ | Alias | Code | Use instead |
230
+ |---|---|---|
231
+ | `MOVED_TEMPORARILY` | 302 | `FOUND` |
232
+ | `PAYLOAD_TOO_LARGE` | 413 | `CONTENT_TOO_LARGE` |
233
+ | `REQUEST_ENTITY_TOO_LARGE` | 413 | `CONTENT_TOO_LARGE` |
234
+ | `REQUEST_TOO_LONG` | 413 | `CONTENT_TOO_LARGE` |
235
+ | `REQUEST_URI_TOO_LONG` | 414 | `URI_TOO_LONG` |
236
+ | `REQUESTED_RANGE_NOT_SATISFIABLE` | 416 | `RANGE_NOT_SATISFIABLE` |
237
+ | `UNPROCESSABLE_ENTITY` | 422 | `UNPROCESSABLE_CONTENT` |
238
+
239
+ <details>
240
+ <summary>All codes in <code>Unofficial</code></summary>
241
+
242
+ | Code | Name | Source |
243
+ |---|---|---|
244
+ | 104 | Upload Resumption Supported | IETF draft (temporary IANA registration) |
245
+ | 218 | This Is Fine | Apache |
246
+ | 306 | Switch Proxy | Reserved by RFC 9110, unused |
247
+ | 418 | I'm a Teapot | RFC 2324, reserved by RFC 9110 |
248
+ | 419 | Page Expired | Laravel |
249
+ | 420 | Enhance Your Calm | Twitter |
250
+ | 440 | Login Time-out | Microsoft IIS |
251
+ | 444 | No Response | nginx |
252
+ | 449 | Retry With | Microsoft IIS |
253
+ | 450 | Blocked by Windows Parental Controls | Microsoft |
254
+ | 494 | Request Header Too Large | nginx |
255
+ | 495 | SSL Certificate Error | nginx |
256
+ | 496 | SSL Certificate Required | nginx |
257
+ | 497 | HTTP Request Sent to HTTPS Port | nginx |
258
+ | 498 | Invalid Token | Esri ArcGIS |
259
+ | 499 | Client Closed Request | nginx |
260
+ | 509 | Bandwidth Limit Exceeded | Apache, cPanel |
261
+ | 520-527 | Unknown Error, Web Server Is Down, Connection Timed Out, Origin Is Unreachable, A Timeout Occurred, SSL Handshake Failed, Invalid SSL Certificate, Railgun Error | Cloudflare |
262
+ | 598, 599 | Network Read / Connect Timeout Error | Proxy convention |
263
+
264
+ </details>
265
+
266
+ ### reason(code, options?)
267
+
268
+ ```ts
269
+ function reason<C extends KnownStatusCode>(code: C, options?: { legacy?: false }): ReasonPhrase<C>
270
+ function reason(code: number | string, options?: ReasonOptions): string | undefined
271
+ ```
272
+
273
+ Returns the reason phrase for a code. Accepts numbers and numeric strings. Returns `undefined` for unknown codes. With a literal code, the return type is the literal phrase: `reason(404)` has the type `'Not Found'`.
274
+
275
+ | Option | Type | Default | Description |
276
+ |---|---|---|---|
277
+ | `legacy` | `boolean` | `false` | Return the older phrase that Node.js `http.STATUS_CODES` and `statuses` use. Only 413 (*Payload Too Large*) and 422 (*Unprocessable Entity*) differ from RFC 9110. |
278
+
279
+ ```js
280
+ reason(404) // => 'Not Found'
281
+ reason(499) // => 'Client Closed Request'
282
+ reason(422, { legacy: true }) // => 'Unprocessable Entity'
283
+ ```
284
+
285
+ ### code(phrase)
286
+
287
+ ```ts
288
+ function code<P extends ReasonPhrase>(phrase: P): CodeOf<P>
289
+ function code(phrase: string): KnownStatusCode | undefined
290
+ ```
291
+
292
+ Returns the code for a reason phrase or constant name. Case, spaces, hyphens, underscores and apostrophes are ignored. Old phrases and numeric strings also work. Returns `undefined` if nothing matches.
293
+
294
+ ```js
295
+ code('Not Found') // => 404
296
+ code("i'm a teapot") // => 418
297
+ code('Request Entity Too Large') // => 413
298
+ code('404') // => 404
299
+ ```
300
+
301
+ ### info(code)
302
+
303
+ ```ts
304
+ function info<C extends KnownStatusCode>(code: C): StatusInfo<C>
305
+ function info(code: number | string): StatusInfo | undefined
306
+ ```
307
+
308
+ Returns everything known about a code, or `undefined` for unknown codes.
309
+
310
+ ```js
311
+ info(413)
312
+ // => {
313
+ // code: 413,
314
+ // reason: 'Content Too Large',
315
+ // name: 'CONTENT_TOO_LARGE',
316
+ // category: 'client-error',
317
+ // official: true,
318
+ // deprecated: false,
319
+ // spec: 'RFC 9110, Section 15.5.14',
320
+ // url: 'https://www.rfc-editor.org/rfc/rfc9110#section-15.5.14',
321
+ // description: 'The request content is larger than the server is willing to process.',
322
+ // aliases: ['Payload Too Large', 'Request Entity Too Large'],
323
+ // retryable: false,
324
+ // cacheable: false,
325
+ // emptyBody: false,
326
+ // }
327
+
328
+ info(522).spec // => 'Cloudflare'
329
+ info(522).url // => undefined
330
+ ```
331
+
332
+ | Field | Type | Description |
333
+ |---|---|---|
334
+ | `code` | `number` | The code, for example `404`. |
335
+ | `reason` | `string` | The reason phrase. |
336
+ | `name` | `string` | The constant name in `Status` or `Unofficial`, for example `'NOT_FOUND'`. |
337
+ | `category` | `Category` | See [`category()`](#categorycode). |
338
+ | `official` | `boolean` | `true` if registered with IANA. |
339
+ | `deprecated` | `boolean` | `true` for 305 Use Proxy, 510 Not Extended (obsolete) and 527 Railgun Error. |
340
+ | `spec` | `string` | Where the code is defined, for example `'RFC 9110, Section 15.5.5'` or `'nginx'`. |
341
+ | `url` | `string \| undefined` | Link to the definition, when a public spec exists. |
342
+ | `description` | `string` | One sentence about what the code means. |
343
+ | `aliases` | `string[]` | Older phrases for the same code. |
344
+ | `retryable` | `boolean` | Same as `isRetryable(code)`. |
345
+ | `cacheable` | `boolean` | Same as `isCacheable(code)`. |
346
+ | `emptyBody` | `boolean` | Same as `isEmptyBody(code)`. |
347
+
348
+ `info()` holds all descriptions (about 5.5 KB gzipped). The other functions do not import them.
349
+
350
+ ### allCodes(options?)
351
+
352
+ ```ts
353
+ function allCodes(options?: { unofficial?: false }): StatusCode[]
354
+ function allCodes(options: AllCodesOptions): KnownStatusCode[]
355
+ ```
356
+
357
+ Returns every official code, sorted from low to high.
358
+
359
+ | Option | Type | Default | Description |
360
+ |---|---|---|---|
361
+ | `unofficial` | `boolean` | `false` | Also include the codes in `Unofficial`. |
362
+
363
+ ### category(code)
364
+
365
+ ```ts
366
+ const category: (code: unknown) => Category | undefined
367
+ type Category = 'informational' | 'success' | 'redirection' | 'client-error' | 'server-error'
368
+ ```
369
+
370
+ Returns the class of a code, from its first digit. Works for any integer from 100 to 599, known or not, and for numeric strings. Returns `undefined` for anything else.
371
+
11
372
  ```js
12
- const { hello } = require('fourohfour') // or: import { hello } from 'fourohfour'
13
- console.log(hello()) // 'Hello, world! (from fourohfour)'
373
+ category(404) // => 'client-error'
374
+ category('503') // => 'server-error'
375
+ category(299) // => 'success'
376
+ category(600) // => undefined
377
+ ```
378
+
379
+ ### Helper checks
380
+
381
+ ```ts
382
+ const isValid: (code: unknown) => code is number
383
+ const isKnown: (code: unknown) => code is KnownStatusCode
384
+ const isOfficial: (code: unknown) => code is StatusCode
385
+ const isRetryable: (code: unknown) => boolean // and the other checks below
386
+ ```
387
+
388
+ Every check returns `false` for anything that is not a status code (`NaN`, `404.5`, `null`, ...). The class and behavior checks also accept numeric strings like `'404'`. The type guards (functions that also narrow the TypeScript type) `isValid`, `isKnown` and `isOfficial` accept numbers only.
389
+
390
+ | Function | Returns `true` for |
391
+ |---|---|
392
+ | `isValid(code)` | Any integer from 100 to 599 (the range RFC 9110 allows) |
393
+ | `isKnown(code)` | Codes in `Status` or `Unofficial` |
394
+ | `isOfficial(code)` | IANA-registered codes (in `Status`) |
395
+ | `isInformational(code)` | 1xx |
396
+ | `isSuccess(code)` | 2xx |
397
+ | `isRedirection(code)` | 3xx, including 304 |
398
+ | `isClientError(code)` | 4xx |
399
+ | `isServerError(code)` | 5xx |
400
+ | `isError(code)` | 4xx and 5xx |
401
+ | `isRedirect(code)` | 301, 302, 303, 307, 308: redirects to follow with the `Location` header (the Fetch standard's list) |
402
+ | `isRedirectWithBody(code)` | 307, 308: the client must repeat the same method and body (for 301 and 302 it may switch to GET, for 303 it must) |
403
+ | `isRetryable(code)` | 408, 425, 429, 500, 502, 503, 504 |
404
+ | `isEmptyBody(code)` | 1xx, 204, 205, 304: the response never has a body |
405
+ | `isCacheable(code)` | 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501: cacheable by default (RFC 9110 section 15.1) |
406
+
407
+ `isValid` narrows `unknown` to `number`. `isKnown` narrows to `KnownStatusCode` and `isOfficial` to `StatusCode`.
408
+
409
+ ### new HttpError(status, message?, options?)
410
+
411
+ ```ts
412
+ class HttpError<S extends number = number> extends Error {
413
+ constructor(status: S, message?: string, options?: HttpErrorOptions)
414
+ constructor(status: S, options?: HttpErrorOptions)
415
+ }
14
416
  ```
15
417
 
418
+ An error with an HTTP status code. `status` must be an integer from 400 to 599, otherwise a `RangeError` is thrown. The message defaults to the reason phrase, or `'Client Error'` / `'Server Error'` for unknown codes.
419
+
420
+ | Option | Type | Default | Description |
421
+ |---|---|---|---|
422
+ | `cause` | `unknown` | - | The original error, kept as `error.cause`. |
423
+ | `headers` | `Record<string, string>` | `{}` | Headers to send, such as `Retry-After`, `Allow` or `WWW-Authenticate`. |
424
+ | `expose` | `boolean` | `true` for 4xx, `false` for 5xx | Whether the message is safe to send to clients. When `false`, `toJSON()` leaves out `detail`. |
425
+ | `type` | `string` | `'about:blank'` | RFC 9457 problem type (a URI). |
426
+ | `title` | `string` | The reason phrase | RFC 9457 title. |
427
+ | `instance` | `string` | - | RFC 9457 URI for this one occurrence. |
428
+ | `extensions` | `Record<string, unknown>` | `{}` | Extra fields for `toJSON()`. They cannot overwrite `type`, `title`, `status`, `detail` or `instance`. |
429
+
430
+ | Property | Description |
431
+ |---|---|
432
+ | `status`, `statusCode` | The status code. With a literal, typed as the literal: `new HttpError(404).status` has the type `404`. |
433
+ | `message` | Your message, or the reason phrase. |
434
+ | `expose` | Whether `message` is safe to send to clients. |
435
+ | `headers` | Headers to send with the response. |
436
+ | `cause` | The `cause` option. |
437
+ | `type`, `title`, `instance`, `extensions` | RFC 9457 fields, from the options. |
438
+
439
+ It has the same shape as an `http-errors` error (`status`, `statusCode`, `expose`, `headers`), so Express and Koa error handling treat it like one.
440
+
441
+ ### createError(status, message?, options?)
442
+
443
+ ```ts
444
+ function createError<S extends number>(status: S, message?: string, options?: HttpErrorOptions): HttpError<S>
445
+ function createError<S extends number>(status: S, options?: HttpErrorOptions): HttpError<S>
446
+ ```
447
+
448
+ Same as `new HttpError(...)`.
449
+
450
+ ### error.toJSON()
451
+
452
+ ```ts
453
+ toJSON(): ProblemDetails
454
+ ```
455
+
456
+ Returns RFC 9457 problem details. `detail` is the message. It is included only when the error is exposed and the message is different from the title. `JSON.stringify(error)` uses `toJSON()`.
457
+
458
+ ```js
459
+ new HttpError(404, 'No user with id 42').toJSON()
460
+ // => { type: 'about:blank', title: 'Not Found', status: 404, detail: 'No user with id 42' }
461
+
462
+ new HttpError(422, 'Invalid order', {
463
+ type: 'https://example.com/problems/validation',
464
+ title: 'Validation failed',
465
+ instance: '/orders/12',
466
+ extensions: { errors: [{ field: 'email', message: 'is required' }] },
467
+ }).toJSON()
468
+ // => {
469
+ // type: 'https://example.com/problems/validation',
470
+ // title: 'Validation failed',
471
+ // status: 422,
472
+ // detail: 'Invalid order',
473
+ // instance: '/orders/12',
474
+ // errors: [{ field: 'email', message: 'is required' }],
475
+ // }
476
+ ```
477
+
478
+ ### error.toResponse()
479
+
480
+ ```ts
481
+ toResponse(): Response
482
+ ```
483
+
484
+ Returns a web-standard `Response` with the problem details as the body, the error's status, `Content-Type: application/problem+json` and the error's headers.
485
+
486
+ ```js
487
+ const res = new HttpError(429, { headers: { 'Retry-After': '60' } }).toResponse()
488
+ res.status // => 429
489
+ res.headers.get('content-type') // => 'application/problem+json'
490
+ res.headers.get('retry-after') // => '60'
491
+ ```
492
+
493
+ ### isHttpError(value)
494
+
495
+ ```ts
496
+ const isHttpError: (value: unknown) => value is HttpError
497
+ ```
498
+
499
+ Returns `true` for an `HttpError`, also one created by a different copy of fourohfour (for example, when two versions are installed).
500
+
501
+ ### PROBLEM_JSON
502
+
503
+ ```ts
504
+ const PROBLEM_JSON = 'application/problem+json'
505
+ ```
506
+
507
+ The media type for RFC 9457 problem details.
508
+
509
+ ### Types
510
+
511
+ ```ts
512
+ import type {
513
+ StatusCode, // 100 | 101 | ... | 511 (official)
514
+ UnofficialStatusCode, // 104 | 218 | 306 | 418 | ... | 599
515
+ KnownStatusCode, // both
516
+ InformationalStatus, SuccessStatus, RedirectionStatus,
517
+ ClientErrorStatus, // 400 | 401 | ... | 451 (official 4xx)
518
+ ServerErrorStatus, // 500 | ... | 511
519
+ ErrorStatus, // ClientErrorStatus | ServerErrorStatus
520
+ ReasonPhrase, // ReasonPhrase<404> = 'Not Found'
521
+ CodeOf, // CodeOf<'Not Found'> = 404
522
+ StatusName, // 'OK' | 'NOT_FOUND' | ...
523
+ UnofficialStatusName, // 'IM_A_TEAPOT' | 'CLIENT_CLOSED_REQUEST' | ...
524
+ StatusInfo, Category, ReasonOptions, AllCodesOptions,
525
+ HttpErrorOptions, ProblemDetails,
526
+ } from 'fourohfour'
527
+ ```
528
+
529
+ ## Comparison
530
+
531
+ Checked against `http-status-codes@2.3.0`, `http-status@2.1.0` and `statuses@2.0.2`.
532
+
533
+ | | `http-status-codes` | `http-status` | `statuses` | fourohfour |
534
+ |---|---|---|---|---|
535
+ | Constants | `StatusCodes.NOT_FOUND` (TS `enum`) | `status.NOT_FOUND` | No | `Status.NOT_FOUND` (literal type) |
536
+ | 413 / 422 phrase | `Request Entity Too Large` / `Unprocessable Entity` | `Request Entity Too Large` / `Unprocessable Entity` | `Payload Too Large` / `Unprocessable Entity` | `Content Too Large` / `Unprocessable Content` (RFC 9110), legacy on request |
537
+ | All IANA codes | No (missing 208, 226, 425, 506, 508, 510) | Yes | Yes | Yes |
538
+ | Unofficial codes | 418, 419, 420 mixed in, not marked | Yes, separate `extra` objects | 418, 509 mixed in | Yes, separate `Unofficial`, `official: false` |
539
+ | Phrase to code | Exact case only, throws | No | Yes, any case, throws | Yes, any case or punctuation, legacy names, constant names |
540
+ | Unknown code | Throws | `undefined` | Throws | `undefined` |
541
+ | Helper checks | No | No | `redirect`, `empty`, `retry` (502-504) maps | Class checks, `isRetryable`, `isRedirect`, `isEmptyBody`, `isCacheable`, ... |
542
+ | Spec links / descriptions | In JSDoc | Descriptions | No | `info()`: RFC section, URL, description, flags |
543
+ | Error class | No | No | No | `HttpError` with RFC 9457 `toJSON()` / `toResponse()` |
544
+ | Bundle for `NOT_FOUND` (min+gz, esbuild) | 2.8 KB | 7.5 KB | n/a | 0.75 KB |
545
+ | ESM / CommonJS | Yes / Yes | Yes / Yes | No / Yes | Yes / Yes |
546
+ | TypeScript types | Yes | Yes | `@types/statuses` | Yes, built in |
547
+
548
+ ## Migrating from other packages
549
+
550
+ ### From http-status-codes
551
+
552
+ ```js
553
+ // Before
554
+ import { StatusCodes, ReasonPhrases, getReasonPhrase, getStatusCode } from 'http-status-codes'
555
+
556
+ StatusCodes.NOT_FOUND
557
+ ReasonPhrases.NOT_FOUND
558
+ getReasonPhrase(404)
559
+ getStatusCode('Not Found')
560
+
561
+ // After
562
+ import { Status, Reason, reason, code } from 'fourohfour'
563
+
564
+ Status.NOT_FOUND
565
+ Reason[Status.NOT_FOUND]
566
+ reason(404)
567
+ code('Not Found')
568
+ ```
569
+
570
+ Differences:
571
+
572
+ - Lookups return `undefined` instead of throwing.
573
+ - `REQUEST_TOO_LONG` and `UNPROCESSABLE_ENTITY` still work but are marked deprecated.
574
+ - `IM_A_TEAPOT` is `Unofficial.IM_A_TEAPOT`.
575
+ - 419 and 420 are Laravel's *Page Expired* and Twitter's *Enhance Your Calm* in `Unofficial`, not *Insufficient Space on Resource* and *Method Failure*.
576
+
577
+ ### From http-status
578
+
579
+ | Before | After |
580
+ |---|---|
581
+ | `status.NOT_FOUND` | `Status.NOT_FOUND` |
582
+ | `status[404]` | `reason(404)` or `Reason[404]` |
583
+ | `status['404_MESSAGE']` | `info(404).description` |
584
+ | `status['404_CLASS']` | `category(404)` |
585
+ | `status.extra.nginx[499]` | `reason(499)` |
586
+
587
+ ### From statuses
588
+
589
+ | Before | After | Note |
590
+ |---|---|---|
591
+ | `status(404)` | `reason(404, { legacy: true })` | Same phrases as `statuses` and Node.js |
592
+ | `status('not found')` | `code('not found')` | |
593
+ | `status.redirect[n]` | `isRedirect(n)` | `statuses` also lists 300 and 305 |
594
+ | `status.empty[n]` | `isEmptyBody(n)` | Also `true` for 1xx here |
595
+ | `status.retry[n]` | `isRetryable(n)` | Also `true` for 408, 425, 429 and 500 here |
596
+
597
+ ### From http-errors
598
+
599
+ ```js
600
+ // Before
601
+ import createError from 'http-errors'
602
+ // After
603
+ import { createError } from 'fourohfour'
604
+
605
+ throw createError(404, 'No user with id 42')
606
+ ```
607
+
608
+ `createError(404, 'msg')` works the same, and the error has `status`, `statusCode`, `expose` and `headers`. One difference: a status outside 400-599 throws a `RangeError`. `http-errors` prints a deprecation warning and keeps going.
609
+
610
+ ## Notes and limitations
611
+
612
+ - Lookups (`reason`, `code`, `info`, `category`) return `undefined` for unknown input. They never throw, so check the result.
613
+ - `Status` contains deprecated aliases, so `Object.values(Status)` has duplicate codes. Use `allCodes()` to list codes.
614
+ - The type guards `isValid`, `isKnown` and `isOfficial` return `false` for strings, even `'404'`. The other checks accept numeric strings.
615
+ - `HttpError` only accepts 400 to 599. Other values throw a `RangeError`.
616
+ - Some unofficial codes mean different things to different vendors. fourohfour uses the meanings in the `Unofficial` table above.
617
+ - `info()` adds about 5.5 KB gzipped because it holds all descriptions. Import it only if you need it.
618
+ - `toResponse()` needs a global `Response` class. Node.js 20+, Bun, Deno, browsers and edge runtimes all have one.
619
+
620
+ ## Requirements
621
+
622
+ - Node.js 20 or newer. Also works in Bun, Deno, browsers and edge runtimes.
623
+ - ESM and CommonJS builds.
624
+ - TypeScript types included.
625
+ - Zero dependencies.
626
+
16
627
  ## License
17
628
 
18
629
  MIT