spooder 3.2.8 → 4.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/README.md CHANGED
@@ -1,24 +1,16 @@
1
1
  <p align="center"><img src="docs/project-logo.png"/></p>
2
2
 
3
- # Spooder &middot; ![typescript](https://img.shields.io/badge/language-typescript-blue) [![license badge](https://img.shields.io/github/license/Kruithne/spooder?color=yellow)](LICENSE) ![npm version](https://img.shields.io/npm/v/spooder?color=c53635) ![bun](https://img.shields.io/badge/runtime-bun-f9f1e1)
3
+ # spooder &middot; ![typescript](https://img.shields.io/badge/language-typescript-blue) [![license badge](https://img.shields.io/github/license/Kruithne/spooder?color=yellow)](LICENSE) ![npm version](https://img.shields.io/npm/v/spooder?color=c53635) ![bun](https://img.shields.io/badge/runtime-bun-f9f1e1)
4
4
 
5
- `spooder` is a purpose-built server solution written using the [Bun](https://bun.sh/) runtime.
5
+ `spooder` is a purpose-built server solution that shifts away from the dependency hell of the Node.js ecosystem, with a focus on stability and performance, which is why:
6
+ - It is built using the [Bun](https://bun.sh/) runtime and not designed to be compatible with Node.js or other runtimes.
7
+ - It uses zero dependencies and only relies on code written explicitly for `spooder` or APIs provided by the Bun runtime, often implemented in native code.
8
+ - It provides streamlined APIs for common server tasks in a minimalistic way, without the overhead of a full-featured web framework.
9
+ - It is opinionated in its design to reduce complexity and overhead.
6
10
 
7
- ### What does it do?
8
-
9
- `spooder` consists of a command-line tool which provides automatic updating/restarting and canary functionality, and a building-block API for creating servers.
10
-
11
- ### Should I use it?
12
-
13
- Probably not. You are free to use `spooder` if you fully understand the risks and limitations of doing so, however here is a list of things you should consider before using it:
14
-
15
- ⚠️ This is not a Node.js package. It is built using the [Bun](https://bun.sh/) runtime, which is still experimental as of writing.
16
-
17
- ⚠️ It is designed to be highly opinionated and is not intended to be a general-purpose server, so configuration is limited.
18
-
19
- ⚠️ It is not a full-featured web server and only provides the functionality as required for the projects it has been built for.
20
-
21
- ⚠️ It has not been battle-tested and may contain bugs or security issues. The authors of this project are not responsible for any problems caused by using this software.
11
+ It consists of two components, the `CLI` and the `API`.
12
+ - The `CLI` is responsible for keeping the server process running, applying updates in response to source control changes, and automatically raising issues on GitHub via the canary feature.
13
+ - The `API` provides a minimal building-block style API for developing servers, with a focus on simplicity and performance.
22
14
 
23
15
  # Installation
24
16
 
@@ -32,42 +24,58 @@ bun add spooder
32
24
 
33
25
  # Configuration
34
26
 
35
- Both the runner and the API are configured in the same way by providing a `spooder` object in your `package.json` file.
27
+ Both the `CLI` and the API are configured in the same way by providing a `spooder` object in your `package.json` file.
36
28
 
37
29
  ```json
38
30
  {
39
31
  "spooder": {
40
32
  "auto_restart": 5000,
41
- "run": "bun run index.ts",
42
33
  "update": [
43
34
  "git pull",
44
35
  "bun install"
45
- ]
36
+ ],
37
+ "canary": {
38
+ "account": "",
39
+ "repository": "",
40
+ "labels": [],
41
+ "crash_console_history": 64,
42
+ "throttle": 86400,
43
+ "sanitize": true
44
+ }
46
45
  }
47
46
  }
48
47
  ```
49
48
 
50
49
  If there are any issues with the provided configuration, a warning will be printed to the console but will not halt execution. `spooder` will always fall back to default values where invalid configuration is provided.
51
50
 
52
- Configuration warnings **do not** raise `caution` events with the `spooder` canary functionality.
51
+ > [!NOTE]
52
+ > Configuration warnings **do not** raise `caution` events with the `spooder` canary functionality.
53
53
 
54
- # Runner
54
+ # CLI
55
55
 
56
- `spooder` includes a global command-line tool for running servers. It is recommended that you run this in a `screen` session.
56
+ The `CLI` component of `spooder` is a global command-line tool for running server processes.
57
57
 
58
- ```bash
59
- screen -S spooder # Create a new screen session
60
- cd /var/www/my_server/
61
- spooder
62
- ```
58
+ - [CLI > Usage](#cli-usage)
59
+ - [CLI > Auto Restart](#cli-auto-restart)
60
+ - [CLI > Auto Update](#cli-auto-update)
61
+ - [CLI > Canary](#cli-canary)
62
+ - [CLI > Canary > Crash](#cli-canary-crash)
63
+ - [CLI > Canary > Sanitization](#cli-canary-sanitization)
64
+ - [CLI > Canary > System Information](#cli-canary-system-information)
63
65
 
64
- While the intended use of this runner is for web servers, it can be used to run anything. It provides two primary features: automatic updating and automatic restarting.
65
66
 
66
- ## Entry Point
67
+ <a id="cli-usage"></a>
68
+ ## CLI > Usage
67
69
 
68
- `spooder` will attempt to launch the server from the current working directory using the command `bun run index.ts` as a default.
70
+ For convenience, it is recommended that you run this in a `screen` session.
69
71
 
70
- To customize this, provide an alternative command via the `run` configuration.
72
+ ```bash
73
+ screen -S my-website-about-fish.net
74
+ cd /var/www/my-website-about-fish.net/
75
+ spooder
76
+ ```
77
+
78
+ `spooder` will launch your server either by executing the `run` command provided in the configuration, or by executing `bun run index.ts` by default.
71
79
 
72
80
  ```json
73
81
  {
@@ -77,11 +85,22 @@ To customize this, provide an alternative command via the `run` configuration.
77
85
  }
78
86
  ```
79
87
 
80
- While `spooder` uses a `bun run` command by default, it is possible to use any command string.
88
+ While `spooder` uses a `bun run` command by default, it is possible to use any command string. For example if you wanted to launch a server using `node` instead of `bun`, you could do the following.
89
+
90
+ ```json
91
+ {
92
+ "spooder": {
93
+ "run": "node my_server.js"
94
+ }
95
+ }
96
+ ```
97
+ <a id="cli-auto-restart"></a>
98
+ ## CLI > Auto Restart
81
99
 
82
- ## Auto Restart
100
+ > [!NOTE]
101
+ > This feature is not enabled by default.
83
102
 
84
- In the event that the server exits (regardless of exit code), `spooder` can automatically restart it after a short delay. To enable this feature specify the restart delay in milliseconds as `auto_restart` in the configuration.
103
+ In the event that the server process exits, regardless of exit code, `spooder` can automatically restart it after a short delay. To enable this feature specify the restart delay in milliseconds as `auto_restart` in the configuration.
85
104
 
86
105
  ```json
87
106
  {
@@ -93,9 +112,13 @@ In the event that the server exits (regardless of exit code), `spooder` can auto
93
112
 
94
113
  If set to `0`, the server will be restarted immediately without delay. If set to `-1`, the server will not be restarted at all.
95
114
 
96
- ## Auto Update
115
+ <a id="cli-auto-update"></a>
116
+ ## CLI > Auto Update
97
117
 
98
- When starting your server, `spooder` can automatically update the source code in the working directory. To enable this feature, the necessary update commands can be provided in the configuration as an array of strings.
118
+ > [!NOTE]
119
+ > This feature is not enabled by default.
120
+
121
+ When starting or restarting a server process, `spooder` can automatically update the source code in the working directory. To enable this feature, the necessary update commands can be provided in the configuration as an array of strings.
99
122
 
100
123
  ```json
101
124
  {
@@ -108,28 +131,31 @@ When starting your server, `spooder` can automatically update the source code in
108
131
  }
109
132
  ```
110
133
 
111
- Commands will be executed in sequence, and the server will not be started until after the commands have resolved.
134
+ Each command should be a separate entry in the array and will be executed in sequence. The server process will be started once all commands have resolved.
112
135
 
113
- Each command should be a separate item in the array. Chaining commands in a single string using the `&&` or `||` operators will not work.
136
+ > [!IMPORTANT]
137
+ > Chainging commands using `&&` or `||` operators does not work.
114
138
 
115
139
  If a command in the sequence fails, the remaining commands will not be executed, however the server will still be started. This is preferred over entering a restart loop or failing to start the server at all.
116
140
 
117
- As well as being executed when the server is first started, the `update` commands are also run when `spooder` automatically restarts the server after it exits.
118
-
119
- You can utilize this to automatically update your server in response to a webhook or other event by simply exiting the process.
141
+ You can utilize this to automatically update your server in response to a webhook by exiting the process.
120
142
 
121
143
  ```ts
122
- events.on('receive-webhook', () => {
123
- // <- Gracefully finish processing here.
124
- process.exit(0);
144
+ server.webhook(process.env.WEBHOOK_SECRET, '/webhook', payload => {
145
+ setImmediate(() => server.stop(false));
146
+ return 200;
125
147
  });
126
148
  ```
127
149
 
128
- ## Canary
150
+ <a id="cli-canary"></a>
151
+ ## CLI > Canary
152
+
153
+ > [!NOTE]
154
+ > This feature is not enabled by default.
129
155
 
130
156
  `canary` is a feature in `spooder` which allows server problems to be raised as issues in your repository on GitHub.
131
157
 
132
- To enable this feature, there are a couple of steps you need to take.
158
+ To enable this feature, you will need to configure a GitHub App and configure it:
133
159
 
134
160
  ### 1. Create a GitHub App
135
161
 
@@ -142,7 +168,8 @@ Once created, install the GitHub App to your account. The app will need to be gi
142
168
 
143
169
  In addition to the **App ID** that is assigned automatically, you will also need to generate a **Private Key** for the app. This can be done by clicking the **Generate a private key** button on the app page.
144
170
 
145
- > Note: The private keys provided by GitHub are in PKCS#1 format, but only PKCS#8 is supported. You can convert the key file with the following command.
171
+ > [!NOTE]
172
+ > The private keys provided by GitHub are in PKCS#1 format, but only PKCS#8 is supported. You can convert the key file with the following command.
146
173
 
147
174
  ```bash
148
175
  openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in private-key.pem -out private-key-pkcs8.key
@@ -164,7 +191,7 @@ Each server that intends to use the canary feature will need to have the private
164
191
 
165
192
  Replace `<GITHUB_ACCOUNT_NAME>` with the account name you have installed the GitHub App to, and `<GITHUB_REPOSITORY>` with the repository name you want to use for issues.
166
193
 
167
- The repository name must in the format `owner/repo` (e.g. `facebook/react`).
194
+ The repository name must in the full-name format `owner/repo` (e.g. `facebook/react`).
168
195
 
169
196
  The `labels` property can be used to provide a list of labels to automatically add to the issue. This property is optional and can be omitted.
170
197
 
@@ -178,19 +205,29 @@ SPOODER_CANARY_KEY=/home/bond/.ssh/id_007_pcks8.key
178
205
  ```
179
206
 
180
207
  `SPOODER_CANARY_APP_ID` is the **App ID** as shown on the GitHub App page.
208
+
181
209
  `SPOODER_CANARY_KEY` is the path to the private key file in PKCS#8 format.
182
210
 
211
+ > [!NOTE]
212
+ > Since `spooder` uses the Bun runtime, you can use the `.env.local` file in the project root directory to set these environment variables per-project.
213
+
183
214
  ### 4. Use canary
184
215
 
185
216
  Once configured, `spooder` will automatically raise an issue when the server exits with a non-zero exit code.
186
217
 
187
218
  In addition, you can manually raise issues using the `spooder` API by calling `caution()` or `panic()`. More information about these functions can be found in the `API` section.
188
219
 
189
- ## Crash
220
+ If `canary` has not been configured correctly, `spooder` will only print warnings to the console when it attempts to raise an issue.
221
+
222
+ > [!WARNING]
223
+ > Consider testing the canary feature with the `caution()` function before relying on it for critical issues.
224
+
225
+ <a id="cli-canary-crash"></a>
226
+ ## CLI > Canary > Crash
190
227
 
191
228
  It is recommended that you harden your server code against unexpected exceptions and use `panic()` and `caution()` to raise issues with selected diagnostic information.
192
229
 
193
- In the event that the server does encounter an unexpected exception which causes it to exit with a non-zero exit code, `spooder` will automatically raise an issue on GitHub using the canary feature, if configured.
230
+ In the event that the server does encounter an unexpected exception which causes it to exit with a non-zero exit code, `spooder` will provide some diagnostic information in the canary report.
194
231
 
195
232
  Since this issue has been caught externally, `spooder` has no context of the exception which was raised. Instead, the canary report will contain the output from both `stdout` and `stderr`.
196
233
 
@@ -218,7 +255,7 @@ Since this issue has been caught externally, `spooder` has no context of the exc
218
255
 
219
256
  The `proc_exit_code` property contains the exit code that the server exited with.
220
257
 
221
- The `console_output` will contain the last `64` lines of output from `stdout` and `stderr` combined. This can be configured by setting the `spooder.canary.crash_console_history` property.
258
+ The `console_output` will contain the last `64` lines of output from `stdout` and `stderr` combined. This can be configured by setting the `spooder.canary.crash_console_history` property to a length of your choice.
222
259
 
223
260
  ```json
224
261
  {
@@ -230,13 +267,12 @@ The `console_output` will contain the last `64` lines of output from `stdout` an
230
267
  }
231
268
  ```
232
269
 
233
- This information is subject to sanitization, as described in the `Sanitization` section, however you should be aware that stack traces may contain sensitive information.
234
-
235
- Additionally, Bun includes a relevant code snippet from the source file where the exception was raised. This is intended to help you identify the source of the problem.
270
+ This information is subject to sanitization, as described in the `CLI > Canary > Sanitization` section, however you should be aware that stack traces may contain sensitive information.
236
271
 
237
272
  Setting `spooder.canary.crash_console_history` to `0` will omit the `console_output` property from the report entirely, which may make it harder to diagnose the problem but will ensure that no sensitive information is leaked.
238
273
 
239
- ## Sanitization
274
+ <a id="cli-canary-sanitization"></a>
275
+ ## CLI > Canary > Sanitization
240
276
 
241
277
  All reports sent via the canary feature are sanitized to prevent sensitive information from being leaked. This includes:
242
278
 
@@ -281,9 +317,11 @@ The sanitization behavior can be disabled by setting `spooder.canary.sanitize` t
281
317
  }
282
318
  ```
283
319
 
284
- While this sanitization adds a layer of protection against information leaking, it does not catch everything. You should pay special attention to messages and objects provided to the canary to not unintentionally leak sensitive information.
320
+ > [!WARNING]
321
+ > While this sanitization adds a layer of protection against information leaking, it does not catch everything. You should pay special attention to messages and objects provided to the canary to not unintentionally leak sensitive information.
285
322
 
286
- ## System Information
323
+ <a id="cli-canary-system-information"></a>
324
+ ## CLI > Canary > System Information
287
325
 
288
326
  In addition to the information provided by the developer, `spooder` also includes some system information in the canary reports.
289
327
 
@@ -322,28 +360,71 @@ In addition to the information provided by the developer, `spooder` also include
322
360
  },
323
361
  "bun": {
324
362
  "version": "0.6.4",
325
- "rev": "f02561530fda1ee9396f51c8bc99b38716e38296"
363
+ "rev": "f02561530fda1ee9396f51c8bc99b38716e38296",
364
+ "memory_usage": {
365
+ "rss": 99672064,
366
+ "heapTotal": 3039232,
367
+ "heapUsed": 2332783,
368
+ "external": 0,
369
+ "arrayBuffers": 0
370
+ },
371
+ "cpu_usage": {
372
+ "user": 50469,
373
+ "system": 0
374
+ }
326
375
  }
327
376
  }
328
377
  ```
329
378
 
330
379
  # API
331
380
 
332
- `spooder` exposes a building-block style API for developing servers. The API is designed to be minimal to leave control in the hands of the developer and not add overhead for features you may not need.
381
+ `spooder` exposes a simple yet powerful API for developing servers. The API is designed to be minimal to leave control in the hands of the developer and not add overhead for features you may not need.
382
+
383
+ - [API > Serving](#api-serving)
384
+ - [`serve(port: number): Server`](#api-serving-serve)
385
+ - [API > Routing](#api-routing)
386
+ - [`server.route(path: string, handler: RequestHandler)`](#api-routing-server-route)
387
+ - [Redirection Routes](#api-routing-redirection-routes)
388
+ - [API > Routing > RequestHandler](#api-routing-request-handler)
389
+ - [API > Routing > Fallback Handling](#api-routing-fallback-handlers)
390
+ - [`server.handle(status_code: number, handler: RequestHandler)`](#api-routing-server-handle)
391
+ - [`server.default(handler: DefaultHandler)`](#api-routing-server-default)
392
+ - [`server.error(handler: ErrorHandler)`](#api-routing-server-error)
393
+ - [API > Routing > Directory Serving](#api-routing-directory-serving)
394
+ - [`server.dir(path: string, dir: string, handler?: DirHandler)`](#api-routing-server-dir)
395
+ - [API > Routing > Server-Sent Events](#api-routing-server-sent-events)
396
+ - [`server.sse(path: string, handler: ServerSentEventHandler)`](#api-routing-server-sse)
397
+ - [API > Routing > Webhooks](#api-routing-webhooks)
398
+ - [`server.webhook(secret: string, path: string, handler: WebhookHandler)`](#api-routing-server-webhook)
399
+ - [API > Server Control](#api-server-control)
400
+ - [`server.stop(immediate: boolean)`](#api-server-control-server-stop)
401
+ - [API > Error Handling](#api-error-handling)
402
+ - [`ErrorWithMetadata(message: string, metadata: object)`](#api-error-handling-error-with-metadata)
403
+ - [`caution(err_message_or_obj: string | object, ...err: object[]): Promise<void>`](#api-error-handling-caution)
404
+ - [`panic(err_message_or_obj: string | object, ...err: object[]): Promise<void>`](#api-error-handling-panic)
405
+ - [API > Content](#api-content)
406
+ - [`template_sub(template: string, replacements: Record<string, string>): string`](#api-content-template-sub)
407
+ - [`generate_hash_subs(length: number, prefix: string): Promise<Record<string, string>>`](#api-content-generate-hash-subs)
408
+ - [`apply_range(file: BunFile, request: Request): HandlerReturnType`](#api-content-apply-range)
409
+ - [API > State Management](#api-state-management)
410
+ - [`set_cookie(res: Response, name: string, value: string, options?: CookieOptions)`](#api-state-management-set-cookie)
411
+ - [`get_cookies(source: Request | Response): Record<string, string>`](#api-state-management-get-cookies)
412
+
413
+ <a id="api-serving"></a>
414
+ ## API > Serving
415
+
416
+ <a id="api-serving-serve"></a>
417
+ ### `serve(port: number): Server`
418
+
419
+ Bootstrap a server on the specified port.
333
420
 
334
421
  ```ts
335
- import { ... } from 'spooder';
336
- ```
337
-
338
- #### `serve(port: number): Server`
339
-
340
- The `serve` function simplifies the process of boostrapping a server. Setting up a functioning server is as simple as calling the function and passing a port number to listen on.
422
+ import { serve } from 'spooder';
341
423
 
342
- ```ts
343
424
  const server = serve(8080);
344
425
  ```
345
426
 
346
- Without any additional configuration, this will create a server which listens on the specified port and responds to all requests with the following response.
427
+ By default, the server responds with:
347
428
 
348
429
  ```http
349
430
  HTTP/1.1 404 Not Found
@@ -353,11 +434,13 @@ Content-Type: text/plain;charset=utf-8
353
434
  Not Found
354
435
  ```
355
436
 
356
- To build functionality on top of this, there are a number of functions that can be called from the `Server` object.
437
+ <a id="api-routing"></a>
438
+ ## API > Routing
357
439
 
358
- #### `server.route(path: string, handler: RequestHandler)`
440
+ <a id="api-routing-server-route"></a>
441
+ ### 🔧 `server.route(path: string, handler: RequestHandler)`
359
442
 
360
- The `route` function allows you to register a handler for a specific path. The handler will be called for all requests that exactly match the given path.
443
+ Register a handler for a specific path.
361
444
 
362
445
  ```ts
363
446
  server.route('/test/route', (req, url) => {
@@ -365,372 +448,577 @@ server.route('/test/route', (req, url) => {
365
448
  });
366
449
  ```
367
450
 
368
- Additionally, routes also support named parameters. These are defined by prefixing a path segment with a colon. These are added directly to the `searchParams` property of the `URL` object.
451
+ <a id="api-routing-redirection-routes"></a>
452
+ ### Redirection Routes
453
+
454
+ `spooder` does not provide a built-in redirection handler since it's trivial to implement one using [`Response.redirect`](https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static), part of the standard Web API.
369
455
 
370
456
  ```ts
371
- server.route('/test/:param', (req, url) => {
372
- return new Response(url.searchParams.get('param'), { status: 200 });
373
- });
457
+ server.route('/redirect', () => Response.redirect('/redirected', 301));
374
458
  ```
375
- > Note: Named parameters will overwrite existing search parameters with the same name.
376
459
 
377
- By default routes are matched exactly, but you can also use a wildcard to match any path that starts with a given path.
460
+ <a id="api-routing-request-handler"></a>
461
+ ## API > Routing > RequestHandler
462
+
463
+ `RequestHandler` is a function that accepts a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object and a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) object and returns a `HandlerReturnType`.
464
+
465
+ `HandlerReturnType` must be one of the following.
466
+
467
+ | Type | Description |
468
+ | --- | --- |
469
+ | `Response` | https://developer.mozilla.org/en-US/docs/Web/API/Response |
470
+ | `Blob` | https://developer.mozilla.org/en-US/docs/Web/API/Blob |
471
+ | `BunFile` | https://bun.sh/docs/api/file-io |
472
+ | `object` | Will be serialized to JSON. |
473
+ | `string` | Will be sent as `text/html``. |
474
+ | `number` | Sets status code and sends status message as plain text. |
475
+
476
+ > [!NOTE]
477
+ > For custom JSON serialization on an object/class, implement the [`toJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) method.
478
+
479
+ `HandleReturnType` can also be a promise resolving to any of the above types, which will be awaited before sending the response.
480
+
481
+ > [!NOTE]
482
+ > Returning `Bun.file()` directly is the most efficient way to serve static files as it uses system calls to stream the file directly to the client without loading into user-space.
483
+
484
+ <a id="api-routing-query-parameters"></a>
485
+ ## API > Routing > Query Parameters
486
+
487
+ Query parameters can be accessed from the `searchParams` property on the `URL` object.
378
488
 
379
489
  ```ts
380
- server.route('/test/*', (req, url) => {
381
- return new Response('Hello, world!', { status: 200 });
490
+ server.route('/test', (req, url) => {
491
+ return new Response(url.searchParams.get('foo'), { status: 200 });
382
492
  });
383
493
  ```
384
494
 
385
- The above will match any path the starts with `/test`, such as:
386
- - `/test`
387
- - `/test/`
388
- - `/test/route`
389
- - `/test/route/foo.txt`
495
+ ```http
496
+ GET /test?foo=bar HTTP/1.1
390
497
 
391
- If you intend to use this for directory serving, you may be better suited looking at the `server.dir()` function.
498
+ HTTP/1.1 200 OK
499
+ Content-Length: 3
392
500
 
393
- Wildcards can also be placed anywhere in the path, allowing anything to be placed in a given single segment - it does not span multiple segments.
501
+ bar
502
+ ```
503
+
504
+ Named parameters can be used in paths by prefixing a path segment with a colon.
505
+
506
+ > [!NOTE]
507
+ > Named parameters will overwrite existing query parameters with the same name.
394
508
 
395
509
  ```ts
396
- server.route('/test/*/route', (req, url) => {
397
- return new Response('Hello, world!', { status: 200 });
510
+ server.route('/test/:param', (req, url) => {
511
+ return new Response(url.searchParams.get('param'), { status: 200 });
398
512
  });
399
513
  ```
400
514
 
401
- The above would allow anything to be placed in the middle segment. This behavior is documented for clarity as it is a byproduct of wildcard implementation for directories, but it is recommended you use the named parameters feature instead.
515
+ <a id="api-routing-wildcards"></a>
516
+ ## API > Routing > Wildcards
402
517
 
403
- Using the standard Web API, the route handler above receives a [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object and returns a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object, which is then sent to the client.
518
+ Wildcards can be used to match any path that starts with a given path.
404
519
 
405
- All handle registration functions in `spooder` support registering async functions which will be awaited before sending the response.
520
+ > [!NOTE]
521
+ > If you intend to use this for directory serving, you may be better suited looking at the `server.dir()` function.
406
522
 
407
523
  ```ts
408
- server.route('/test/route', async (req, url) => {
409
- await new Promise((resolve) => setTimeout(resolve, 1000));
524
+ server.route('/test/*', (req, url) => {
410
525
  return new Response('Hello, world!', { status: 200 });
411
526
  });
412
527
  ```
413
528
 
414
- To streamline this process, `spooder` allows a number of other return types to be used as shortcuts.
529
+ > [!IMPORTANT]
530
+ > Routes are [FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)) and wildcards are greedy. Wildcards should be registered last to ensure they do not consume more specific routes.
531
+
532
+ ```ts
533
+ server.route('/*', () => 301);
534
+ server.route('/test', () => 200);
415
535
 
416
- Returning a `number` type treats the number as a status code and sends a relevant response.
536
+ // Accessing /test returns 301 here, because /* matches /test first.
537
+ ```
417
538
 
418
- By default, this will be a plain text response with the applicable status message as the body. This can be overridden with `server.handle()` or `server.default()`, which will be covered later.
539
+ <a id="api-routing-fallback-handlers"></a>
540
+ ## API > Routing > Fallback Handlers
419
541
 
542
+ <a id="api-routing-server-handle"></a>
543
+ ### 🔧 `server.handle(status_code: number, handler: RequestHandler)`
544
+ Register a custom handler for a specific status code.
420
545
  ```ts
421
- server.route('/test/route', (req) => {
422
- return 500;
546
+ server.handle(500, (req) => {
547
+ return new Response('Custom Internal Server Error Message', { status: 500 });
423
548
  });
424
549
  ```
425
- ```http
426
- HTTP/1.1 500 Internal Server Error
427
- Content-Length: 21
428
- Content-Type: text/plain;charset=utf-8
429
550
 
430
- Internal Server Error
551
+ <a id="api-routing-server-default"></a>
552
+ ### 🔧 `server.default(handler: DefaultHandler)`
553
+ Register a handler for all unhandled response codes.
554
+ > [!NOTE]
555
+ > If you return a `Response` object from here, you must explicitly set the status code.
556
+ ```ts
557
+ server.default((req, status_code) => {
558
+ return new Response(`Custom handler for: ${status_code}`, { status: status_code });
559
+ });
431
560
  ```
432
561
 
433
- Returning a `Blob` type, such as the `FileBlob` returned from the `Bun.file()` API, will send the blob as the response body with the appropriate content type and length headers.
562
+ <a id="api-routing-server-error"></a>
563
+ ### 🔧 `server.error(handler: ErrorHandler)`
564
+ Register a handler for uncaught errors.
434
565
 
566
+ > [!NOTE]
567
+ > This handler does not accept asynchronous functions and must return a `Response` object.
435
568
  ```ts
436
- server.route('test/route', (req) => {
437
- // Note that calling Bun.file() does not immediately read
438
- // the file from disk, it will be streamed with the response.
439
- return Bun.file('test.png');
569
+ server.error((err, req, url) => {
570
+ return new Response('Custom Internal Server Error Message', { status: 500 });
440
571
  });
441
572
  ```
442
- ```http
443
- HTTP/1.1 200 OK
444
- Content-Length: 12345
445
- Content-Type: image/png
446
573
 
447
- <binary data>
574
+ > [!IMPORTANT]
575
+ > It is highly recommended to use `caution()` or some form of reporting to notify you when this handler is called, as it means an error went entirely uncaught.
576
+
577
+ ```ts
578
+ server.error((err, req, url) => {
579
+ // Notify yourself of the error.
580
+ caution({ err, url });
581
+
582
+ // Return a response to the client.
583
+ return new Response('Custom Internal Server Error Message', { status: 500 });
584
+ });
448
585
  ```
449
586
 
450
- Return an `object` type, such as an array or a plain object, will send the object as JSON with the appropriate content type and length headers.
587
+ <a id="api-routing-directory-serving"></a>
588
+ ## API > Routing > Directory Serving
451
589
 
590
+ <a id="api-routing-server-dir"></a>
591
+ ### 🔧 `server.dir(path: string, dir: string, handler?: DirHandler)`
592
+ Serve files from a directory.
452
593
  ```ts
453
- server.route('test/route', (req) => {
454
- return { message: 'Hello, world!' };
455
- });
594
+ server.dir('/content', './public/content');
456
595
  ```
457
- ```http
458
- HTTP/1.1 200 OK
459
- Content-Length: 25
460
- Content-Type: application/json;charset=utf-8
461
596
 
462
- {"message":"Hello, world!"}
597
+ > [!IMPORTANT]
598
+ > `server.dir` registers a wildcard route. Routes are [FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)) and wildcards are greedy. Directories should be registered last to ensure they do not consume more specific routes.
599
+
600
+ ```ts
601
+ server.dir('/', '/files');
602
+ server.route('/test', () => 200);
603
+
604
+ // Route / is equal to /* with server.dir()
605
+ // Accessing /test returns 404 here because /files/test does not exist.
463
606
  ```
464
607
 
465
- Since custom classes are also objects, you can also return a custom class instance and it will be serialized to JSON. To control the serialization process, you can implement the `toJSON()` method on your class.
608
+ By default, spooder will use the following default handler for serving directories.
466
609
 
467
610
  ```ts
468
- class User {
469
- constructor(public name: string, public age: number) {}
611
+ function default_directory_handler(file_path: string, file: BunFile, stat: DirStat, request: Request): HandlerReturnType {
612
+ // ignore hidden files by default, return 404 to prevent file sniffing
613
+ if (path.basename(file_path).startsWith('.'))
614
+ return 404; // Not Found
470
615
 
471
- toJSON() {
472
- return {
473
- name: this.name,
474
- age: this.age,
475
- };
476
- }
477
- }
616
+ if (stat.isDirectory())
617
+ return 401; // Unauthorized
478
618
 
479
- server.route('test/route', (req) => {
480
- return new User('Bob', 42);
481
- });
619
+ return apply_range(file, request);
620
+ }
482
621
  ```
483
- ```http
484
- HTTP/1.1 200 OK
485
- Content-Length: 25
486
- Content-Type: application/json;charset=utf-8
487
622
 
488
- {"name":"Bob","age":42}
489
- ```
623
+ > [!NOTE]
624
+ > Uncaught `ENOENT` errors throw from the directory handler will return a `404` response, other errors will return a `500` response.
625
+
626
+ > [!NOTE]
627
+ > The call to `apply_range` in the default directory handler will automatically slice the file based on the [`Range`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range) header. This function is also exposed as part of the `spooder` API for use in your own handlers.
628
+
629
+ Provide your own directory handler for fine-grained control.
490
630
 
491
- Any other type that is returned from a route handler will be converted to a string and sent as the response body with the appropriate length header and the content type `text/plain`.
631
+ > [!IMPORTANT]
632
+ > Providing your own handler will override the default handler defined above. Be sure to implement the same logic if you want to retain the default behavior.
633
+
634
+ | Parameter | Type | Reference |
635
+ | --- | --- | --- |
636
+ | `file_path` | `string` | The path to the file on disk. |
637
+ | `file` | `BunFile` | https://bun.sh/docs/api/file-io |
638
+ | `stat` | `fs.Stats` | https://nodejs.org/api/fs.html#class-fsstats |
639
+ | `request` | `Request` | https://developer.mozilla.org/en-US/docs/Web/API/Request |
640
+ | `url` | `URL` | https://developer.mozilla.org/en-US/docs/Web/API/URL |
492
641
 
493
642
  ```ts
494
- server.route('test/route', (req) => {
495
- return Symbol('foo');
643
+ server.dir('/static', '/static', (file_path, file, stat, request, url) => {
644
+ // Implement custom logic.
645
+ return file; // HandlerReturnType
496
646
  });
497
647
  ```
498
- ```http
499
- HTTP/1.1 200 OK
500
- Content-Length: 7
501
- Content-Type: text/plain;charset=utf-8
502
648
 
503
- Symbol(foo)
504
- ```
649
+ > [!NOTE]
650
+ > The directory handler function is only called for files that exist on disk - including directories.
505
651
 
506
- #### `server.default(handler: DefaultHandler)`
652
+ <a id="api-routing-server-sse"></a>
653
+ ## API > Routing > Server-Sent Events
507
654
 
508
- The server uses a default handler which responds to requests for which there was no handler registered, or the registered handler returned a numeric status code.
655
+ <a id="api-routing-server-sse"></a>
656
+ ### 🔧 `server.sse(path: string, handler: ServerSentEventHandler)`
509
657
 
510
- This default handler sends a simple response to the client with the status code and a body containing the status message.
658
+ Setup a [server-sent event](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) stream.
511
659
 
512
- ```http
513
- HTTP/1.1 404 Not Found
514
- Content-Length: 9
515
- Content-Type: text/plain;charset=utf-8
660
+ ```ts
661
+ server.sse('/sse', (req, url, client) => {
662
+ client.message('Hello, client!'); // Unnamed event.
663
+ client.event('named_event', 'Hello, client!'); // Named event.
516
664
 
517
- Not Found
665
+ client.message(JSON.stringify({ foo: 'bar' })); // JSON message.
666
+ });
518
667
  ```
519
668
 
520
- To customize the behavior of this handler, you can register a custom default handler using the `default` function.
669
+ `client.closed` is a promise that resolves when the client closes the connection.
521
670
 
522
671
  ```ts
523
- server.default((req, status_code) => {
524
- return new Response(`Custom error: ${status_code}`, { status: status_code });
672
+ const clients = new Set();
673
+
674
+ server.sse('/sse', (req, url, client) => {
675
+ clients.add(client);
676
+ client.closed.then(() => clients.delete(client));
525
677
  });
526
678
  ```
527
679
 
528
- Using your own default handler allows you to provide a custom response for unhandled requests based on the status code.
680
+ Connections can be manually closed with `client.close()`. This will also trigger the `client.closed` promise to resolve.
529
681
 
530
- The return type from this handler can be any of the expected return types from a normal route handler with the exception that returning a `number` type will not be treated as a status code and will instead be treated as a plain text response.
682
+ ```ts
683
+ server.sse('/sse', (req, url, client) => {
684
+ client.message('Hello, client!');
685
+
686
+ setTimeout(() => {
687
+ client.message('Goodbye, client!');
688
+ client.close();
689
+ }, 5000);
690
+ });
691
+ ```
531
692
 
532
- If is worth noting that if you return a `Response` object from this handler, you must implicitly set the status code. If you do not, the status code will be set to `200` by default.
693
+ <a id="api-routing-webhooks"></a>
694
+ ## API > Routing > Webhooks
695
+
696
+ <a id="api-routing-server-webhook"></a>
697
+ ### 🔧 `server.webhook(secret: string, path: string, handler: WebhookHandler)`
698
+
699
+ Setup a webhook handler.
533
700
 
534
701
  ```ts
535
- server.default((req, status_code) => {
536
- return new Response(`Custom error: ${status_code}`);
702
+ server.webhook(process.env.WEBHOOK_SECRET, '/webhook', payload => {
703
+ // React to the webhook.
704
+ return 200;
537
705
  });
538
706
  ```
539
- ```http
540
- HTTP/1.1 200 OK
541
- Content-Length: 18
542
- Content-Type: text/plain;charset=utf-8
543
707
 
544
- Custom error: 404
545
- ```
708
+ A webhook callback will only be called if the following critera is met by a request:
709
+ - Request method is `POST` (returns `405` otherwise)
710
+ - Header `X-Hub-Signature-256` is present (returns `400` otherwise)
711
+ - Header `Content-Type` is `application/json` (returns `401` otherwise)
712
+ - Request body is a valid JSON object (returns `500` otherwise)
713
+ - HMAC signature of the request body matches the `X-Hub-Signature-256` header (returns `401` otherwise)
546
714
 
547
- Returning anything else, such as a `Blob`, `object` or `string`, the status code will automatically be set to `status_code`. To override this behavior you must provide a `Response` object.
715
+ > [!NOTE]
716
+ > Constant-time comparison is used to prevent timing attacks when comparing the HMAC signature.
548
717
 
549
- #### `server.handle(status_code: number, handler: RequestHandler)`
718
+ <a id="api-server-control"></a>
719
+ ## API > Server Control
550
720
 
551
- The `handle` function allows you to register a handler for a specific status code. This handler will take priority over the default handler.
721
+ <a id="api-server-control-stop"></a>
722
+ ### 🔧 `server.stop(immediate: boolean)`
723
+
724
+ Stop the server process immediately, terminating all in-flight requests.
552
725
 
553
726
  ```ts
554
- server.handle(500, (req) => {
555
- return new Response('Custom Internal Server Error Message', { status: 500 });
556
- });
727
+ server.stop(true);
557
728
  ```
558
- ```http
559
- HTTP/1.1 500 Internal Server Error
560
- Content-Length: 36
561
- Content-Type: text/plain;charset=utf-8
562
729
 
563
- Custom Internal Server Error Message
730
+ Stop the server process gracefully, waiting for all in-flight requests to complete.
731
+
732
+ ```ts
733
+ server.stop(false);
564
734
  ```
565
735
 
566
- The return type from this handler can be any of the expected return types from a normal route handler with the exception that returning a `number` type will not be treated as a status code and will instead be treated as a plain text response.
736
+ <a id="api-error-handling"></a>
737
+ ## API > Error Handling
567
738
 
568
- If is worth noting that if you return a `Response` object from this handler, you must implicitly set the status code. If you do not, the status code will be set to `200` by default.
739
+ <a id="api-error-handling-error-with-metadata"></a>
740
+ ### 🔧 `ErrorWithMetadata(message: string, metadata: object)`
741
+
742
+ The `ErrorWithMetadata` class allows you to attach metadata to errors, which can be used for debugging purposes when errors are dispatched to the canary.
569
743
 
570
744
  ```ts
571
- server.handle(500, (req) => {
572
- return new Response('Custom Internal Server Error Message');
573
- });
745
+ throw new ErrorWithMetadata('Something went wrong', { foo: 'bar' });
574
746
  ```
575
- ```http
576
- HTTP/1.1 200 OK
577
- Content-Length: 36
578
- Content-Type: text/plain;charset=utf-8
579
747
 
580
- Custom Internal Server Error Message
581
- ```
748
+ Functions and promises contained in the metadata will be resolved and the return value will be used instead.
582
749
 
583
- Returning anything else, such as a `Blob`, `object` or `string`, the status code will automatically be set. To override this behavior you must provide a `Response` object.
750
+ ```ts
751
+ throw new ErrorWithMetadata('Something went wrong', { foo: () => 'bar' });
752
+ ```
584
753
 
585
- #### `server.error(handler: ErrorHandler)`
754
+ <a id="api-error-handling-caution"></a>
755
+ ### 🔧 `caution(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
586
756
 
587
- The `error` function allows you to register a handler for any uncaught errors that occur during the request handling process.
757
+ Raise a warning issue on GitHub. This is useful for non-fatal issues which you want to be notified about.
588
758
 
589
- Unlike other handlers, it does not accept asynchronous functions and it must return a `Response` object.
759
+ > [!NOTE]
760
+ > This function is only available if the canary feature is enabled.
590
761
 
591
762
  ```ts
592
- server.error((req, err) => {
593
- return new Response('Custom Internal Server Error Message', { status: 500 });
594
- });
763
+ try {
764
+ // Perform a non-critical action, such as analytics.
765
+ // ...
766
+ } catch (e) {
767
+ // `caution` is async, you can use it without awaiting.
768
+ caution(e);
769
+ }
595
770
  ```
596
- ```http
597
- HTTP/1.1 500 Internal Server Error
598
- Content-Length: 36
599
- Content-Type: text/plain;charset=utf-8
600
771
 
601
- Custom Internal Server Error Message
772
+ Additional data can be provided as objects which will be serialized to JSON and included in the report.
773
+
774
+ ```ts
775
+ caution(e, { foo: 42 });
602
776
  ```
603
- This should be used as a last resort to catch unintended errors and should not be part of your normal request handling process. Generally speaking, this handler should only be called if you have a bug in your code.
604
777
 
605
- #### `server.dir(path: string, dir: string)`
778
+ A custom error message can be provided as the first parameter
606
779
 
607
- The `dir` function allows you to serve static files from a directory on your file system.
780
+ > [!NOTE]
781
+ > Avoid including dynamic information in the title that would prevent the issue from being unique.
608
782
 
609
783
  ```ts
610
- server.dir('/content', './public/content');
784
+ caution('Custom error', e, { foo: 42 });
611
785
  ```
612
786
 
613
- The above example will serve all files from `./public/content` to any requests made to `/content`. For example `/content/test.txt` will serve the file `./public/content/test.txt`.
787
+ Issues raised with `caution()` are rate-limited. By default, the rate limit is `86400` seconds (24 hours), however this can be configured in the `spooder.canary.throttle` property.
614
788
 
615
- - This function is recursive and will serve all files from the specified directory and any subdirectories.
616
- - Requesting a directory will return a 401 response (subject to your configured handlers).
617
- - Requesting a file that does not exist will return a 404 response (subject to your configured handlers).
618
- - Requesting a file that is not readable will return a 500 response (subject to your configured handlers).
789
+ ```json
790
+ {
791
+ "spooder": {
792
+ "canary": {
793
+ "throttle": 86400
794
+ }
795
+ }
796
+ }
797
+ ```
619
798
 
620
- By default, hidden files (files prefixed with `.`) will not be served. To serve hidden files, you must set `ignoreHidden` to `false` in the `options` parameter.
799
+ Issues are considered unique by the `err_message` parameter, so avoid using dynamic information that would prevent this from being unique.
800
+
801
+ If you need to provide unique information, you can use the `err` parameter to provide an object which will be serialized to JSON and included in the issue body.
621
802
 
622
803
  ```ts
623
- server.dir('/content', './public/content', { ignoreHidden: false });
804
+ const some_important_value = Math.random();
805
+
806
+ // Bad: Do not use dynamic information in err_message.
807
+ await caution('Error with number ' + some_important_value);
808
+
809
+ // Good: Use err parameter to provide dynamic information.
810
+ await caution('Error with number', { some_important_value });
624
811
  ```
625
812
 
626
- If `ignoreHidden` is set to `true` (default) then requesting a hidden file will return a 404 response (subject to your configured handlers).
813
+ <a id="api-error-handling-panic"></a>
814
+ ### 🔧 `panic(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
815
+
816
+ This behaves the same as `caution()` with the difference that once `panic()` has raised the issue, it will exit the process with a non-zero exit code.
817
+
818
+ > [!NOTE]
819
+ > This function is only available if the canary feature is enabled.
627
820
 
628
- Additionally, the `index` property can be set to a filename such as `index.html` to serve a default file when a directory is requested.
821
+ This should only be used as an absolute last resort when the server cannot continue to run and will be unable to respond to requests.
629
822
 
630
823
  ```ts
631
- server.dir('/content', './public/content', { index: 'index.html' });
824
+ try {
825
+ // Perform a critical action.
826
+ // ...
827
+ } catch (e) {
828
+ // You should await `panic` since the process will exit.
829
+ await panic(e);
830
+ }
632
831
  ```
633
832
 
634
- The above will serve `./public/content/index.html` when `/content` is requested.
833
+ <a id="api-content"></a>
834
+ ## API > Content
635
835
 
636
- #### `server.stop(method: ServerStop)`
836
+ <a id="api-content-template-sub"></a>
837
+ ### 🔧 `template_sub(template: string, replacements: Record<string, string>): string`
637
838
 
638
- The `stop` function allows you to stop the server. `method` is one of `ServerStop.IMMEDIATE` or `ServerStop.GRACEFUL`.
839
+ Replace placeholders in a template string with values from a replacement object.
639
840
 
640
- `ServerStop.GRACEFUL` will stop accepting new requests and wait for all in-flight requests to complete before stopping the server. This is the default behavior.
841
+ > [!NOTE]
842
+ > Placeholders that do not appear in the replacement object will be left as-is. See `ignored` in below example.
641
843
 
642
- `ServerStop.IMMEDIATE` will immediately stop the server, terminating all in-flight requests.
844
+ ```ts
845
+ const template = `
846
+ <html>
847
+ <head>
848
+ <title>{title}</title>
849
+ </head>
850
+ <body>
851
+ <h1>{title}</h1>
852
+ <p>{content}</p>
853
+ <p>{ignored}</p>
854
+ </body>
855
+ </html>
856
+ `;
857
+
858
+ const replacements = {
859
+ title: 'Hello, world!',
860
+ content: 'This is a test.'
861
+ };
862
+
863
+ const html = template_sub(template, replacements);
864
+ ```
643
865
 
644
- ---
866
+ ```html
867
+ <html>
868
+ <head>
869
+ <title>Hello, world!</title>
870
+ </head>
871
+ <body>
872
+ <h1>Hello, world!</h1>
873
+ <p>This is a test.</p>
874
+ <p>{ignored}</p>
875
+ </body>
876
+ </html>
877
+ ```
645
878
 
646
- #### `ErrorWithMetadata(message: string, metadata: object)`
879
+ <a id="api-content-generate-hash-subs"></a>
880
+ ### 🔧 `generate_hash_subs(prefix: string): Promise<Record<string, string>>`
647
881
 
648
- The `ErrorWithMetadata` class is a thin wrapper around the built-in `Error` class that allows you to attach metadata to the error.
882
+ Generate a replacement table for mapping file paths to hashes in templates. This is useful for cache-busting static assets.
649
883
 
650
- Providing additional information to errors can be used for debugging purposes when errors are dispatched to the canary.
884
+ > [!IMPORTANT]
885
+ > Internally `generate_hash_subs()` uses `git ls-tree -r HEAD`, so the working directory must be a git repository.
651
886
 
652
887
  ```ts
653
- throw new ErrorWithMetadata('Something went wrong', { foo: 'bar' });
654
- ```
888
+ let hash_sub_table = {};
655
889
 
656
- For convinience, if any of the values in the `metadata` are functions, they will be called and the return value will be used instead.
890
+ generate_hash_subs().then(subs => hash_sub_table = subs).catch(caution);
657
891
 
658
- Additionally, promises will be resolved and readable streams will be converted to strings.
892
+ server.route('/test', (req, url) => {
893
+ return template_sub('Hello world {hash=docs/project-logo.png}', hash_sub_table);
894
+ });
895
+ ```
659
896
 
660
- ---
897
+ ```html
898
+ Hello world 754d9ea
899
+ ```
661
900
 
662
- #### `route_location(redirect_url: string)`
901
+ > [!IMPORTANT]
902
+ > Specify paths as they appear in git, relative to the repository root and with forward slashes (no leading slash).
663
903
 
664
- The `route_location` is a built-in request handler that redirects the client to a specified URL with the status code `301 Moved Permanently`.
904
+ By default hashes are truncated to `7` characters (a short hash), a custom length can be provided instead.
665
905
 
666
906
  ```ts
667
- server.route('test/route', route_location('https://example.com');
907
+ generate_hash_subs(40).then(...);
908
+ // d65c52a41a75db43e184d2268c6ea9f9741de63e
668
909
  ```
669
910
 
670
- The above is a much shorter equivalent to the following:
911
+ > [!NOTE]
912
+ > SHA-1 hashes are `40` characters. Git is transitioning to SHA-256, which are `64` characters. Short hashes of `7` are generally sufficient for cache-busting.
913
+
914
+ Use a different prefix other than `hash=` by passing it as the first parameter.
671
915
 
672
916
  ```ts
673
- server.route('test/route', (req, url) => {
674
- return new Response(null, {
675
- status: 301,
676
- headers: {
677
- Location: 'https://example.com',
678
- },
679
- });
917
+ generate_hash_subs(7, '#').then(subs => hash_sub_table = subs).catch(caution);
918
+
919
+ server.route('/test', (req, url) => {
920
+ return template_sub('Hello world {#docs/project-logo.png}', hash_sub_table);
680
921
  });
681
922
  ```
682
- ---
683
923
 
684
- #### `caution(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
685
- Raise a warning issue on GitHub. This is useful for non-fatal errors which you want to be notified about.
924
+ <a id="api-apply-range"></a>
925
+ ### 🔧 `apply_range(file: BunFile, request: Request): HandlerReturnType`
926
+
927
+ `apply_range` parses the `Range` header for a request and slices the file accordingly. This is used internally by `server.dir()` and exposed for convenience.
686
928
 
687
929
  ```ts
688
- try {
689
- // connect to database
690
- } catch (e) {
691
- await caution('Failed to connect to database', e);
692
- }
930
+ server.route('/test', (req, url) => {
931
+ const file = Bun.file('./test.txt');
932
+ return apply_range(file, req);
933
+ });
693
934
  ```
694
935
 
695
- Providing a custom error message is optional and can be omitted. Additionally you can also provide additional error objects which will be serialized to JSON and included in the report.
936
+ ```http
937
+ GET /test HTTP/1.1
938
+ Range: bytes=0-5
939
+
940
+ HTTP/1.1 206 Partial Content
941
+ Content-Length: 6
942
+ Content-Range: bytes 0-5/6
943
+ Content-Type: text/plain;charset=utf-8
944
+
945
+ Hello,
946
+ ```
947
+
948
+ <a id="api-state-management"></a>
949
+ ## API > State Management
950
+
951
+ <a id="api-state-management-set-cookie"></a>
952
+ ### 🔧 `set_cookie(res: Response, name: string, value: string, options?: CookieOptions)`
953
+
954
+ Set a cookie onto a `Response` object.
696
955
 
697
956
  ```ts
698
- caution(e); // provide just the error
699
- caution(e, { foo: 42 }); // additional data
700
- caution('Custom error', e, { foo: 42 }); // all
957
+ const res = new Response('Cookies!', { status: 200 });
958
+ set_cookie(res, 'my_test_cookie', 'my_cookie_value');
701
959
  ```
702
960
 
703
- To prevent spam, issues raised with `caution()` are rate-limited based on a configurable threshold in seconds. By default, the threshold is set to 24 hours per unique issue.
961
+ ```http
962
+ HTTP/1.1 200 OK
963
+ Set-Cookie: my_test_cookie=my_cookie_value
964
+ Content-Length: 8
704
965
 
705
- ```json
706
- {
707
- "spooder": {
708
- "canary": {
709
- "throttle": 86400
710
- }
711
- }
712
- }
966
+ Cookies!
713
967
  ```
714
968
 
715
- Issues are considered unique by the `err_message` parameter, so it is recommended that you do not include any dynamic information in this parameter that would prevent the issue from being unique.
969
+ > [!IMPORTANT]
970
+ > Spooder does not URL encode cookies by default. This can result in invalid cookies if they contain special characters. See `encode` option on `CookieOptions` below.
716
971
 
717
- If you need to provide unique information, you can use the `err` parameter to provide an object which will be serialized to JSON and included in the issue body.
972
+ ```ts
973
+ type CookieOptions = {
974
+ same_site?: 'Strict' | 'Lax' | 'None',
975
+ secure?: boolean,
976
+ http_only?: boolean,
977
+ path?: string,
978
+ expires?: number,
979
+ encode?: boolean
980
+ };
981
+ ```
982
+
983
+ Most of the options that can be provided as `CookieOptions` are part of the standard `Set-Cookie` header. See [HTTP Cookies - MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies).
984
+
985
+ Passing `encode` as `true` will URL encode the cookie value.
718
986
 
719
987
  ```ts
720
- const some_important_value = Math.random();
988
+ set_cookie(res, 'my_test_cookie', 'my cookie value', { encode: true });
989
+ ```
721
990
 
722
- // Bad: Do not use dynamic information in err_message.
723
- await caution('Error with number ' + some_important_value);
991
+ ```http
992
+ Set-Cookie: my_test_cookie=my%20cookie%20value
993
+ ```
724
994
 
725
- // Good: Use err parameter to provide dynamic information.
726
- await caution('Error with number', { some_important_value });
995
+ <a id="api-state-management-get-cookies"></a>
996
+ ### 🔧 `get_cookies(source: Request | Response, decode: boolean = false): Record<string, string>`
997
+
998
+ Get cookies from a `Request` or `Response` object.
999
+
1000
+ ```http
1001
+ GET /test HTTP/1.1
1002
+ Cookie: my_test_cookie=my_cookie_value
727
1003
  ```
728
- It is not required that you `await` the `caution()`, and in situations where parallel processing is required, it is recommended that you do not.
729
1004
 
730
- #### `panic(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
731
- This behaves the same as `caution()` with the difference that once `panic()` has raised the issue, it will exit the process with a non-zero exit code.
1005
+ ```ts
1006
+ const cookies = get_cookies(req);
1007
+ { my_test_cookie: 'my_cookie_value' }
1008
+ ```
1009
+
1010
+ Cookies are not URL decoded by default. This can be enabled by passing `true` as the second parameter.
1011
+
1012
+ ```http
1013
+ GET /test HTTP/1.1
1014
+ Cookie: my_test_cookie=my%20cookie%20value
1015
+ ```
1016
+ ```ts
1017
+ const cookies = get_cookies(req, true);
1018
+ { my_test_cookie: 'my cookie value' }
1019
+ ```
732
1020
 
733
- This should only be called in worst-case scenarios where the server cannot continue to run. Since the process will exit, it is recommended that you `await` the `panic()` call.
1021
+ ## Legal
1022
+ This software is provided as-is with no warranty or guarantee. The authors of this project are not responsible or liable for any problems caused by using this software or any part thereof. Use of this software does not entitle you to any support or assistance from the authors of this project.
734
1023
 
735
- ## License
736
1024
  The code in this repository is licensed under the ISC license. See the [LICENSE](LICENSE) file for more information.