spooder 3.2.7 → 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
- "autoRestart": 5000,
41
- "run": "bun run index.ts",
32
+ "auto_restart": 5000,
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,25 +85,40 @@ 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 `autoRestart` 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
  {
88
107
  "spooder": {
89
- "autoRestart": 5000
108
+ "auto_restart": 5000
90
109
  }
91
110
  }
92
111
  ```
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,26 +205,36 @@ 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
- 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 `stderr`.
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
 
197
234
  ```json
198
235
  {
199
- "exitCode": 1,
200
- "stderr": [
236
+ "proc_exit_code": 1,
237
+ "console_output": [
201
238
  "[2.48ms] \".env.local\"",
202
239
  "Test output",
203
240
  "Test output",
@@ -216,11 +253,26 @@ Since this issue has been caught externally, `spooder` has no context of the exc
216
253
  }
217
254
  ```
218
255
 
219
- This information is subject to sanitization, as described in the `Sanitization` section, however you should be aware that stack traces may contain sensitive information.
256
+ The `proc_exit_code` property contains the exit code that the server exited with.
220
257
 
221
- 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.
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
- ## Sanitization
260
+ ```json
261
+ {
262
+ "spooder": {
263
+ "canary": {
264
+ "crash_console_history": 128
265
+ }
266
+ }
267
+ }
268
+ ```
269
+
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.
271
+
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.
273
+
274
+ <a id="cli-canary-sanitization"></a>
275
+ ## CLI > Canary > Sanitization
224
276
 
225
277
  All reports sent via the canary feature are sanitized to prevent sensitive information from being leaked. This includes:
226
278
 
@@ -265,9 +317,11 @@ The sanitization behavior can be disabled by setting `spooder.canary.sanitize` t
265
317
  }
266
318
  ```
267
319
 
268
- 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.
269
322
 
270
- ## System Information
323
+ <a id="cli-canary-system-information"></a>
324
+ ## CLI > Canary > System Information
271
325
 
272
326
  In addition to the information provided by the developer, `spooder` also includes some system information in the canary reports.
273
327
 
@@ -303,27 +357,74 @@ In addition to the information provided by the developer, `spooder` also include
303
357
  "uv": "1.44.2",
304
358
  "napi": "8",
305
359
  "modules": "108"
360
+ },
361
+ "bun": {
362
+ "version": "0.6.4",
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
+ }
306
375
  }
307
376
  }
308
377
  ```
309
378
 
310
379
  # API
311
380
 
312
- `spooder` exposes a build-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.
313
420
 
314
421
  ```ts
315
- import { ... } from 'spooder';
316
- ```
422
+ import { serve } from 'spooder';
317
423
 
318
- #### `serve(port: number): Server`
319
-
320
- 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.
321
-
322
- ```ts
323
424
  const server = serve(8080);
324
425
  ```
325
426
 
326
- 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:
327
428
 
328
429
  ```http
329
430
  HTTP/1.1 404 Not Found
@@ -333,11 +434,13 @@ Content-Type: text/plain;charset=utf-8
333
434
  Not Found
334
435
  ```
335
436
 
336
- 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
337
439
 
338
- #### `server.route(path: string, handler: RequestHandler)`
440
+ <a id="api-routing-server-route"></a>
441
+ ### 🔧 `server.route(path: string, handler: RequestHandler)`
339
442
 
340
- 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.
341
444
 
342
445
  ```ts
343
446
  server.route('/test/route', (req, url) => {
@@ -345,372 +448,577 @@ server.route('/test/route', (req, url) => {
345
448
  });
346
449
  ```
347
450
 
348
- 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.
349
455
 
350
456
  ```ts
351
- server.route('/test/:param', (req, url) => {
352
- return new Response(url.searchParams.get('param'), { status: 200 });
353
- });
457
+ server.route('/redirect', () => Response.redirect('/redirected', 301));
354
458
  ```
355
- > Note: Named parameters will overwrite existing search parameters with the same name.
356
459
 
357
- 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.
358
488
 
359
489
  ```ts
360
- server.route('/test/*', (req, url) => {
361
- return new Response('Hello, world!', { status: 200 });
490
+ server.route('/test', (req, url) => {
491
+ return new Response(url.searchParams.get('foo'), { status: 200 });
362
492
  });
363
493
  ```
364
494
 
365
- The above will match any path the starts with `/test`, such as:
366
- - `/test`
367
- - `/test/`
368
- - `/test/route`
369
- - `/test/route/foo.txt`
495
+ ```http
496
+ GET /test?foo=bar HTTP/1.1
497
+
498
+ HTTP/1.1 200 OK
499
+ Content-Length: 3
500
+
501
+ bar
502
+ ```
370
503
 
371
- If you intend to use this for directory serving, you may be better suited looking at the `server.dir()` function.
504
+ Named parameters can be used in paths by prefixing a path segment with a colon.
372
505
 
373
- 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.
506
+ > [!NOTE]
507
+ > Named parameters will overwrite existing query parameters with the same name.
374
508
 
375
509
  ```ts
376
- server.route('/test/*/route', (req, url) => {
377
- return new Response('Hello, world!', { status: 200 });
510
+ server.route('/test/:param', (req, url) => {
511
+ return new Response(url.searchParams.get('param'), { status: 200 });
378
512
  });
379
513
  ```
380
514
 
381
- 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
382
517
 
383
- 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.
384
519
 
385
- 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.
386
522
 
387
523
  ```ts
388
- server.route('/test/route', async (req, url) => {
389
- await new Promise((resolve) => setTimeout(resolve, 1000));
524
+ server.route('/test/*', (req, url) => {
390
525
  return new Response('Hello, world!', { status: 200 });
391
526
  });
392
527
  ```
393
528
 
394
- 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.
395
531
 
396
- Returning a `number` type treats the number as a status code and sends a relevant response.
532
+ ```ts
533
+ server.route('/*', () => 301);
534
+ server.route('/test', () => 200);
397
535
 
398
- 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.
536
+ // Accessing /test returns 301 here, because /* matches /test first.
537
+ ```
538
+
539
+ <a id="api-routing-fallback-handlers"></a>
540
+ ## API > Routing > Fallback Handlers
399
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.
400
545
  ```ts
401
- server.route('/test/route', (req) => {
402
- return 500;
546
+ server.handle(500, (req) => {
547
+ return new Response('Custom Internal Server Error Message', { status: 500 });
403
548
  });
404
549
  ```
405
- ```http
406
- HTTP/1.1 500 Internal Server Error
407
- Content-Length: 21
408
- Content-Type: text/plain;charset=utf-8
409
550
 
410
- 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
+ });
411
560
  ```
412
561
 
413
- 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.
414
565
 
566
+ > [!NOTE]
567
+ > This handler does not accept asynchronous functions and must return a `Response` object.
415
568
  ```ts
416
- server.route('test/route', (req) => {
417
- // Note that calling Bun.file() does not immediately read
418
- // the file from disk, it will be streamed with the response.
419
- return Bun.file('test.png');
569
+ server.error((err, req, url) => {
570
+ return new Response('Custom Internal Server Error Message', { status: 500 });
420
571
  });
421
572
  ```
422
- ```http
423
- HTTP/1.1 200 OK
424
- Content-Length: 12345
425
- Content-Type: image/png
426
573
 
427
- <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
+ });
428
585
  ```
429
586
 
430
- 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
431
589
 
590
+ <a id="api-routing-server-dir"></a>
591
+ ### 🔧 `server.dir(path: string, dir: string, handler?: DirHandler)`
592
+ Serve files from a directory.
432
593
  ```ts
433
- server.route('test/route', (req) => {
434
- return { message: 'Hello, world!' };
435
- });
594
+ server.dir('/content', './public/content');
436
595
  ```
437
- ```http
438
- HTTP/1.1 200 OK
439
- Content-Length: 25
440
- Content-Type: application/json;charset=utf-8
441
596
 
442
- {"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.
443
606
  ```
444
607
 
445
- 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.
446
609
 
447
610
  ```ts
448
- class User {
449
- 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
450
615
 
451
- toJSON() {
452
- return {
453
- name: this.name,
454
- age: this.age,
455
- };
456
- }
457
- }
616
+ if (stat.isDirectory())
617
+ return 401; // Unauthorized
458
618
 
459
- server.route('test/route', (req) => {
460
- return new User('Bob', 42);
461
- });
619
+ return apply_range(file, request);
620
+ }
462
621
  ```
463
- ```http
464
- HTTP/1.1 200 OK
465
- Content-Length: 25
466
- Content-Type: application/json;charset=utf-8
467
622
 
468
- {"name":"Bob","age":42}
469
- ```
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.
470
630
 
471
- 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 |
472
641
 
473
642
  ```ts
474
- server.route('test/route', (req) => {
475
- return Symbol('foo');
643
+ server.dir('/static', '/static', (file_path, file, stat, request, url) => {
644
+ // Implement custom logic.
645
+ return file; // HandlerReturnType
476
646
  });
477
647
  ```
478
- ```http
479
- HTTP/1.1 200 OK
480
- Content-Length: 7
481
- Content-Type: text/plain;charset=utf-8
482
648
 
483
- Symbol(foo)
484
- ```
649
+ > [!NOTE]
650
+ > The directory handler function is only called for files that exist on disk - including directories.
485
651
 
486
- #### `server.default(handler: DefaultHandler)`
652
+ <a id="api-routing-server-sse"></a>
653
+ ## API > Routing > Server-Sent Events
487
654
 
488
- 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)`
489
657
 
490
- 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.
491
659
 
492
- ```http
493
- HTTP/1.1 404 Not Found
494
- Content-Length: 9
495
- 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.
496
664
 
497
- Not Found
665
+ client.message(JSON.stringify({ foo: 'bar' })); // JSON message.
666
+ });
498
667
  ```
499
668
 
500
- 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.
501
670
 
502
671
  ```ts
503
- server.default((req, status_code) => {
504
- 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));
677
+ });
678
+ ```
679
+
680
+ Connections can be manually closed with `client.close()`. This will also trigger the `client.closed` promise to resolve.
681
+
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);
505
690
  });
506
691
  ```
507
692
 
508
- Using your own default handler allows you to provide a custom response for unhandled requests based on the status code.
693
+ <a id="api-routing-webhooks"></a>
694
+ ## API > Routing > Webhooks
509
695
 
510
- 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.
696
+ <a id="api-routing-server-webhook"></a>
697
+ ### 🔧 `server.webhook(secret: string, path: string, handler: WebhookHandler)`
511
698
 
512
- 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.
699
+ Setup a webhook handler.
513
700
 
514
701
  ```ts
515
- server.default((req, status_code) => {
516
- return new Response(`Custom error: ${status_code}`);
702
+ server.webhook(process.env.WEBHOOK_SECRET, '/webhook', payload => {
703
+ // React to the webhook.
704
+ return 200;
517
705
  });
518
706
  ```
519
- ```http
520
- HTTP/1.1 200 OK
521
- Content-Length: 18
522
- Content-Type: text/plain;charset=utf-8
523
707
 
524
- Custom error: 404
525
- ```
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)
526
714
 
527
- 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.
528
717
 
529
- #### `server.handle(status_code: number, handler: RequestHandler)`
718
+ <a id="api-server-control"></a>
719
+ ## API > Server Control
530
720
 
531
- 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.
532
725
 
533
726
  ```ts
534
- server.handle(500, (req) => {
535
- return new Response('Custom Internal Server Error Message', { status: 500 });
536
- });
727
+ server.stop(true);
537
728
  ```
538
- ```http
539
- HTTP/1.1 500 Internal Server Error
540
- Content-Length: 36
541
- Content-Type: text/plain;charset=utf-8
542
729
 
543
- 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);
544
734
  ```
545
735
 
546
- 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
547
738
 
548
- 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.
549
743
 
550
744
  ```ts
551
- server.handle(500, (req) => {
552
- return new Response('Custom Internal Server Error Message');
553
- });
745
+ throw new ErrorWithMetadata('Something went wrong', { foo: 'bar' });
554
746
  ```
555
- ```http
556
- HTTP/1.1 200 OK
557
- Content-Length: 36
558
- Content-Type: text/plain;charset=utf-8
559
747
 
560
- Custom Internal Server Error Message
561
- ```
748
+ Functions and promises contained in the metadata will be resolved and the return value will be used instead.
562
749
 
563
- 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
+ ```
564
753
 
565
- #### `server.error(handler: ErrorHandler)`
754
+ <a id="api-error-handling-caution"></a>
755
+ ### 🔧 `caution(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
566
756
 
567
- 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.
568
758
 
569
- 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.
570
761
 
571
762
  ```ts
572
- server.error((req, err) => {
573
- return new Response('Custom Internal Server Error Message', { status: 500 });
574
- });
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
+ }
575
770
  ```
576
- ```http
577
- HTTP/1.1 500 Internal Server Error
578
- Content-Length: 36
579
- Content-Type: text/plain;charset=utf-8
580
771
 
581
- 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 });
582
776
  ```
583
- 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.
584
777
 
585
- #### `server.dir(path: string, dir: string)`
778
+ A custom error message can be provided as the first parameter
586
779
 
587
- 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.
588
782
 
589
783
  ```ts
590
- server.dir('/content', './public/content');
784
+ caution('Custom error', e, { foo: 42 });
591
785
  ```
592
786
 
593
- 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.
788
+
789
+ ```json
790
+ {
791
+ "spooder": {
792
+ "canary": {
793
+ "throttle": 86400
794
+ }
795
+ }
796
+ }
797
+ ```
594
798
 
595
- - This function is recursive and will serve all files from the specified directory and any subdirectories.
596
- - Requesting a directory will return a 401 response (subject to your configured handlers).
597
- - Requesting a file that does not exist will return a 404 response (subject to your configured handlers).
598
- - Requesting a file that is not readable will return a 500 response (subject to your configured handlers).
799
+ Issues are considered unique by the `err_message` parameter, so avoid using dynamic information that would prevent this from being unique.
599
800
 
600
- 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.
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.
601
802
 
602
803
  ```ts
603
- 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 });
604
811
  ```
605
812
 
606
- 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.
607
817
 
608
- Additionally, the `index` property can be set to a filename such as `index.html` to serve a default file when a directory is requested.
818
+ > [!NOTE]
819
+ > This function is only available if the canary feature is enabled.
820
+
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.
609
822
 
610
823
  ```ts
611
- 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
+ }
612
831
  ```
613
832
 
614
- The above will serve `./public/content/index.html` when `/content` is requested.
833
+ <a id="api-content"></a>
834
+ ## API > Content
615
835
 
616
- #### `server.stop(method: ServerStop)`
836
+ <a id="api-content-template-sub"></a>
837
+ ### 🔧 `template_sub(template: string, replacements: Record<string, string>): string`
617
838
 
618
- 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.
619
840
 
620
- `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.
621
843
 
622
- `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
+ ```
623
865
 
624
- ---
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
+ ```
625
878
 
626
- #### `ErrorWithMetadata(message: string, metadata: object)`
879
+ <a id="api-content-generate-hash-subs"></a>
880
+ ### 🔧 `generate_hash_subs(prefix: string): Promise<Record<string, string>>`
627
881
 
628
- 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.
629
883
 
630
- 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.
631
886
 
632
887
  ```ts
633
- throw new ErrorWithMetadata('Something went wrong', { foo: 'bar' });
634
- ```
888
+ let hash_sub_table = {};
635
889
 
636
- 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);
637
891
 
638
- 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
+ ```
639
896
 
640
- ---
897
+ ```html
898
+ Hello world 754d9ea
899
+ ```
641
900
 
642
- #### `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).
643
903
 
644
- 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.
645
905
 
646
906
  ```ts
647
- server.route('test/route', route_location('https://example.com');
907
+ generate_hash_subs(40).then(...);
908
+ // d65c52a41a75db43e184d2268c6ea9f9741de63e
648
909
  ```
649
910
 
650
- 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.
651
915
 
652
916
  ```ts
653
- server.route('test/route', (req, url) => {
654
- return new Response(null, {
655
- status: 301,
656
- headers: {
657
- Location: 'https://example.com',
658
- },
659
- });
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);
660
921
  });
661
922
  ```
662
- ---
663
923
 
664
- #### `caution(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
665
- 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.
666
928
 
667
929
  ```ts
668
- try {
669
- // connect to database
670
- } catch (e) {
671
- await caution('Failed to connect to database', e);
672
- }
930
+ server.route('/test', (req, url) => {
931
+ const file = Bun.file('./test.txt');
932
+ return apply_range(file, req);
933
+ });
934
+ ```
935
+
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,
673
946
  ```
674
947
 
675
- 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.
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.
676
955
 
677
956
  ```ts
678
- caution(e); // provide just the error
679
- caution(e, { foo: 42 }); // additional data
680
- 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');
681
959
  ```
682
960
 
683
- 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
684
965
 
685
- ```json
686
- {
687
- "spooder": {
688
- "canary": {
689
- "throttle": 86400
690
- }
691
- }
692
- }
966
+ Cookies!
693
967
  ```
694
968
 
695
- 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.
696
971
 
697
- 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.
698
986
 
699
987
  ```ts
700
- const some_important_value = Math.random();
988
+ set_cookie(res, 'my_test_cookie', 'my cookie value', { encode: true });
989
+ ```
701
990
 
702
- // Bad: Do not use dynamic information in err_message.
703
- await caution('Error with number ' + some_important_value);
991
+ ```http
992
+ Set-Cookie: my_test_cookie=my%20cookie%20value
993
+ ```
704
994
 
705
- // Good: Use err parameter to provide dynamic information.
706
- 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
707
1003
  ```
708
- It is not required that you `await` the `caution()`, and in situations where parallel processing is required, it is recommended that you do not.
709
1004
 
710
- #### `panic(err_message_or_obj: string | object, ...err: object[]): Promise<void>`
711
- 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
+ ```
712
1020
 
713
- 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.
714
1023
 
715
- ## License
716
1024
  The code in this repository is licensed under the ISC license. See the [LICENSE](LICENSE) file for more information.