@acryldev/create-blends 1.7.1 → 1.7.3

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.
Files changed (98) hide show
  1. package/{LICENSE → docs/framework/LICENSE} +3 -1
  2. package/docs/framework/README.md +70 -0
  3. package/docs/framework/agents/index.md +59 -0
  4. package/docs/framework/api/acryl.md +247 -0
  5. package/docs/framework/api/context.md +478 -0
  6. package/docs/framework/api/exception.md +80 -0
  7. package/docs/framework/api/index.md +12 -0
  8. package/docs/framework/api/presets.md +62 -0
  9. package/docs/framework/api/request.md +396 -0
  10. package/docs/framework/api/routing.md +303 -0
  11. package/docs/framework/api/summary.md +143 -0
  12. package/docs/framework/concepts/benchmarks.md +26 -0
  13. package/docs/framework/concepts/developer-experience.md +5 -0
  14. package/docs/framework/concepts/middleware.md +21 -0
  15. package/docs/framework/concepts/motivation.md +14 -0
  16. package/docs/framework/concepts/routers.md +63 -0
  17. package/docs/framework/concepts/stacks.md +235 -0
  18. package/docs/framework/concepts/web-standard.md +27 -0
  19. package/docs/framework/cordis/acryl-in-a-cordis-app.md +160 -0
  20. package/docs/framework/cordis/concepts.md +105 -0
  21. package/docs/framework/cordis/middleware.md +8 -0
  22. package/docs/framework/cordis/migration-from-0-3.md +111 -0
  23. package/docs/framework/cordis/migration-from-0-4.md +14 -0
  24. package/docs/framework/cordis/migration-from-dsh-webserver.md +109 -0
  25. package/docs/framework/cordis/migration-to-1-0.md +46 -0
  26. package/docs/framework/cordis/mounting.md +85 -0
  27. package/docs/framework/cordis/node-server.md +100 -0
  28. package/docs/framework/cordis/plugin-lifecycle.md +111 -0
  29. package/docs/framework/cordis/surfaces.md +71 -0
  30. package/docs/framework/cordis/transport-and-cancellation.md +57 -0
  31. package/docs/framework/cordis/validation.md +135 -0
  32. package/docs/framework/getting-started/basic.md +201 -0
  33. package/docs/framework/getting-started/bun.md +219 -0
  34. package/docs/framework/getting-started/deploy.md +133 -0
  35. package/docs/framework/getting-started/desktop.md +80 -0
  36. package/docs/framework/getting-started/nodejs.md +365 -0
  37. package/docs/framework/getting-started/other-runtimes.md +30 -0
  38. package/docs/framework/guides/best-practices.md +231 -0
  39. package/docs/framework/guides/bring-your-own-tool.md +218 -0
  40. package/docs/framework/guides/client-modules.md +210 -0
  41. package/docs/framework/guides/create-acrylblends.md +143 -0
  42. package/docs/framework/guides/data.md +314 -0
  43. package/docs/framework/guides/examples.md +3 -0
  44. package/docs/framework/guides/faq.md +19 -0
  45. package/docs/framework/guides/forms-and-sessions.md +235 -0
  46. package/docs/framework/guides/helpers.md +33 -0
  47. package/docs/framework/guides/jsx-dom.md +301 -0
  48. package/docs/framework/guides/jsx.md +487 -0
  49. package/docs/framework/guides/middleware.md +253 -0
  50. package/docs/framework/guides/production.md +80 -0
  51. package/docs/framework/guides/rpc.md +878 -0
  52. package/docs/framework/guides/testing.md +133 -0
  53. package/docs/framework/guides/validation.md +470 -0
  54. package/docs/framework/helpers/accepts.md +60 -0
  55. package/docs/framework/helpers/adapter.md +57 -0
  56. package/docs/framework/helpers/conninfo.md +77 -0
  57. package/docs/framework/helpers/cookie.md +232 -0
  58. package/docs/framework/helpers/css.md +282 -0
  59. package/docs/framework/helpers/dev.md +64 -0
  60. package/docs/framework/helpers/factory.md +180 -0
  61. package/docs/framework/helpers/html.md +123 -0
  62. package/docs/framework/helpers/jwt.md +184 -0
  63. package/docs/framework/helpers/proxy.md +115 -0
  64. package/docs/framework/helpers/route.md +143 -0
  65. package/docs/framework/helpers/ssg.md +390 -0
  66. package/docs/framework/helpers/streaming.md +224 -0
  67. package/docs/framework/helpers/testing.md +118 -0
  68. package/docs/framework/helpers/websocket.md +208 -0
  69. package/docs/framework/middleware/builtin/basic-auth.md +165 -0
  70. package/docs/framework/middleware/builtin/bearer-auth.md +138 -0
  71. package/docs/framework/middleware/builtin/body-limit.md +71 -0
  72. package/docs/framework/middleware/builtin/cache.md +99 -0
  73. package/docs/framework/middleware/builtin/combine.md +94 -0
  74. package/docs/framework/middleware/builtin/compress.md +59 -0
  75. package/docs/framework/middleware/builtin/context-storage.md +74 -0
  76. package/docs/framework/middleware/builtin/cors.md +134 -0
  77. package/docs/framework/middleware/builtin/csrf.md +105 -0
  78. package/docs/framework/middleware/builtin/etag.md +54 -0
  79. package/docs/framework/middleware/builtin/ip-restriction.md +69 -0
  80. package/docs/framework/middleware/builtin/jsx-renderer.md +283 -0
  81. package/docs/framework/middleware/builtin/jwk.md +192 -0
  82. package/docs/framework/middleware/builtin/jwt.md +145 -0
  83. package/docs/framework/middleware/builtin/language.md +232 -0
  84. package/docs/framework/middleware/builtin/logger.md +74 -0
  85. package/docs/framework/middleware/builtin/loopback-only.md +31 -0
  86. package/docs/framework/middleware/builtin/method-not-allowed.md +48 -0
  87. package/docs/framework/middleware/builtin/method-override.md +80 -0
  88. package/docs/framework/middleware/builtin/mount.md +103 -0
  89. package/docs/framework/middleware/builtin/pretty-json.md +53 -0
  90. package/docs/framework/middleware/builtin/request-id.md +87 -0
  91. package/docs/framework/middleware/builtin/secure-headers.md +247 -0
  92. package/docs/framework/middleware/builtin/timeout.md +98 -0
  93. package/docs/framework/middleware/builtin/timing.md +100 -0
  94. package/docs/framework/middleware/builtin/trailing-slash.md +74 -0
  95. package/docs/framework/middleware/third-party.md +4 -0
  96. package/docs/framework/workshop/README.md +294 -0
  97. package/docs/framework/workshop/facilitator.md +101 -0
  98. package/package.json +3 -3
@@ -0,0 +1,165 @@
1
+ # Basic Auth Middleware
2
+
3
+ This middleware can apply Basic authentication to a specified path.
4
+ Implementing Basic authentication by hand is more complicated than it seems, but with this middleware, it's a breeze.
5
+
6
+ For more information about how the Basic auth scheme works under the hood, see the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme).
7
+
8
+ ## Import
9
+
10
+ ```ts
11
+ import { Acryl } from '@acryldev/blends'
12
+ import { basicAuth } from '@acryldev/blends/basic-auth'
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ const app = new Acryl()
19
+
20
+ app.use(
21
+ '/auth/*',
22
+ basicAuth({
23
+ username: 'acrylblends',
24
+ password: process.env.BASIC_AUTH_PASSWORD!,
25
+ })
26
+ )
27
+
28
+ app.get('/auth/page', (c) => {
29
+ return c.text('You are authorized')
30
+ })
31
+ ```
32
+
33
+ To restrict to a specific route + method:
34
+
35
+ ```ts
36
+ const app = new Acryl()
37
+
38
+ app.get('/auth/page', (c) => {
39
+ return c.text('Viewing page')
40
+ })
41
+
42
+ app.delete(
43
+ '/auth/page',
44
+ basicAuth({ username: 'acrylblends', password: process.env.BASIC_AUTH_PASSWORD! }),
45
+ (c) => {
46
+ return c.text('Page deleted')
47
+ }
48
+ )
49
+ ```
50
+
51
+ If you want to verify the user by yourself, specify the `verifyUser` option; returning `true` means it is accepted.
52
+
53
+ ```ts
54
+ const app = new Acryl()
55
+
56
+ app.use(
57
+ basicAuth({
58
+ verifyUser: (username, password, c) => {
59
+ return (
60
+ username === 'dynamic-user' && password === 'acrylblends-password'
61
+ )
62
+ },
63
+ })
64
+ )
65
+ ```
66
+
67
+ ## Options
68
+
69
+ ### **(required)** username: `string`
70
+
71
+ The username of the user who is authenticating.
72
+
73
+ ### **(required)** password: `string`
74
+
75
+ The password value for the provided username to authenticate against.
76
+
77
+ ### *(optional)* realm: `string`
78
+
79
+ The domain name of the realm, as part of the returned WWW-Authenticate challenge header. The default is `"Secure Area"`.
80
+ See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives
81
+
82
+ ### *(optional)* hashFunction: `Function`
83
+
84
+ A function to handle hashing for safe comparison of passwords.
85
+
86
+ ### *(optional)* verifyUser: `(username: string, password: string, c: Context) => boolean | Promise<boolean>`
87
+
88
+ The function to verify the user.
89
+
90
+ ### *(optional)* invalidUserMessage: `string | object | MessageFunction`
91
+
92
+ `MessageFunction` is `(c: Context) => string | object | Promise<string | object>`. The custom message if the user is invalid.
93
+
94
+ ### *(optional)* onAuthSuccess: `(c: Context, username: string) => void | Promise<void>`
95
+
96
+ A callback function invoked after successful authentication. This allows you to set context variables or perform side effects without re-parsing the Authorization header.
97
+
98
+ ```ts
99
+ app.use(
100
+ '/auth/*',
101
+ basicAuth({
102
+ username: 'acrylblends',
103
+ password: process.env.BASIC_AUTH_PASSWORD!,
104
+ onAuthSuccess: (c, username) => {
105
+ c.set('username', username)
106
+ },
107
+ })
108
+ )
109
+
110
+ app.get('/auth/page', (c) => {
111
+ const username = c.get('username')
112
+ return c.text(`Hello, ${username}!`)
113
+ })
114
+ ```
115
+
116
+ ## More Options
117
+
118
+ ### *(optional)* ...users: `{ username: string, password: string }[]`
119
+
120
+ ## Recipes
121
+
122
+ ### Defining Multiple Users
123
+
124
+ This middleware also allows you to pass arbitrary parameters containing objects defining more `username` and `password` pairs.
125
+
126
+ ```ts
127
+ app.use(
128
+ '/auth/*',
129
+ basicAuth(
130
+ {
131
+ username: 'acrylblends',
132
+ password: process.env.BASIC_AUTH_PASSWORD!,
133
+ // Define other params in the first object
134
+ realm: 'www.example.com',
135
+ },
136
+ {
137
+ username: 'acrylblends-admin',
138
+ password: process.env.ADMIN_PASSWORD!,
139
+ // Cannot redefine other params here
140
+ },
141
+ {
142
+ username: 'acrylblends-user-1',
143
+ password: process.env.USER_1_PASSWORD!,
144
+ // Or here
145
+ }
146
+ )
147
+ )
148
+ ```
149
+
150
+ Or less hardcoded:
151
+
152
+ ```ts
153
+ import { users } from '../config/users'
154
+
155
+ app.use(
156
+ '/auth/*',
157
+ basicAuth(
158
+ {
159
+ realm: 'www.example.com',
160
+ ...users[0],
161
+ },
162
+ ...users.slice(1)
163
+ )
164
+ )
165
+ ```
@@ -0,0 +1,138 @@
1
+ # Bearer Auth Middleware
2
+
3
+ The Bearer Auth Middleware provides authentication by verifying an API token in the Request header.
4
+ The HTTP clients accessing the endpoint will add the `Authorization` header with `Bearer {token}` as the header value.
5
+
6
+ Using `curl` from the terminal, it would look like this:
7
+
8
+ ```sh
9
+ curl -H 'Authorization: Bearer acrylblendsiscool' http://localhost:8787/auth/page
10
+ ```
11
+
12
+ ## Import
13
+
14
+ ```ts
15
+ import { Acryl } from '@acryldev/blends'
16
+ import { bearerAuth } from '@acryldev/blends/bearer-auth'
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ > [!NOTE]
22
+ > Your `token` must match the regex `/[A-Za-z0-9._~+/-]+=*/`, otherwise a 400 error will be returned. Notably, this regex accommodates both URL-safe Base64- and standard Base64-encoded JWTs. This middleware does not require the bearer token to be a JWT, just that it matches the above regex.
23
+
24
+ ```ts
25
+ const app = new Acryl()
26
+
27
+ const token = process.env.API_TOKEN!
28
+
29
+ app.use('/api/*', bearerAuth({ token }))
30
+
31
+ app.get('/api/page', (c) => {
32
+ return c.json({ message: 'You are authorized' })
33
+ })
34
+ ```
35
+
36
+ To restrict to a specific route + method:
37
+
38
+ ```ts
39
+ const app = new Acryl()
40
+
41
+ const token = process.env.API_TOKEN!
42
+
43
+ app.get('/api/page', (c) => {
44
+ return c.json({ message: 'Read posts' })
45
+ })
46
+
47
+ app.post('/api/page', bearerAuth({ token }), (c) => {
48
+ return c.json({ message: 'Created post!' }, 201)
49
+ })
50
+ ```
51
+
52
+ To implement multiple tokens (E.g., any valid token can read but create/update/delete are restricted to a privileged token):
53
+
54
+ ```ts
55
+ const app = new Acryl()
56
+
57
+ const readToken = 'read'
58
+ const privilegedToken = 'read+write'
59
+ const privilegedMethods = ['POST', 'PUT', 'PATCH', 'DELETE']
60
+
61
+ app.on('GET', '/api/page/*', async (c, next) => {
62
+ // List of valid tokens
63
+ const bearer = bearerAuth({ token: [readToken, privilegedToken] })
64
+ return bearer(c, next)
65
+ })
66
+ app.on(privilegedMethods, '/api/page/*', async (c, next) => {
67
+ // Single valid privileged token
68
+ const bearer = bearerAuth({ token: privilegedToken })
69
+ return bearer(c, next)
70
+ })
71
+
72
+ // Define handlers for GET, POST, etc.
73
+ ```
74
+
75
+ If you want to verify the value of the token yourself, specify the `verifyToken` option; returning `true` means it is accepted.
76
+
77
+ ```ts
78
+ const app = new Acryl()
79
+
80
+ app.use(
81
+ '/auth-verify-token/*',
82
+ bearerAuth({
83
+ verifyToken: async (token, c) => {
84
+ return token === 'dynamic-token'
85
+ },
86
+ })
87
+ )
88
+ ```
89
+
90
+ ## Options
91
+
92
+ ### **(required)** token: `string` | `string[]`
93
+
94
+ The string to validate the incoming bearer token against.
95
+
96
+ ### *(optional)* realm: `string`
97
+
98
+ The domain name of the realm, as part of the returned WWW-Authenticate challenge header. The default is `""`.
99
+ See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives
100
+
101
+ ### *(optional)* prefix: `string`
102
+
103
+ The prefix (or known as `schema`) for the Authorization header value. The default is `"Bearer"`.
104
+
105
+ ### *(optional)* headerName: `string`
106
+
107
+ The header name. The default value is `Authorization`.
108
+
109
+ ### *(optional)* hashFunction: `Function`
110
+
111
+ A function to handle hashing for safe comparison of authentication tokens.
112
+
113
+ ### *(optional)* verifyToken: `(token: string, c: Context) => boolean | Promise<boolean>`
114
+
115
+ The function to verify the token.
116
+
117
+ ### *(optional)* noAuthenticationHeader: `object`
118
+
119
+ Customizes the error response when the request does not have an authentication header.
120
+
121
+ - `wwwAuthenticateHeader`: `string | object | MessageFunction` - Customizes the WWW-Authenticate header value.
122
+ - `message`: `string | object | MessageFunction` - The custom message for the response body.
123
+
124
+ `MessageFunction` is `(c: Context) => string | object | Promise<string | object>`.
125
+
126
+ ### *(optional)* invalidAuthenticationHeader: `object`
127
+
128
+ Customizes the error response when the authentication header format is invalid.
129
+
130
+ - `wwwAuthenticateHeader`: `string | object | MessageFunction` - Customizes the WWW-Authenticate header value.
131
+ - `message`: `string | object | MessageFunction` - The custom message for the response body.
132
+
133
+ ### *(optional)* invalidToken: `object`
134
+
135
+ Customizes the error response when the token is invalid.
136
+
137
+ - `wwwAuthenticateHeader`: `string | object | MessageFunction` - Customizes the WWW-Authenticate header value.
138
+ - `message`: `string | object | MessageFunction` - The custom message for the response body.
@@ -0,0 +1,71 @@
1
+ # Body Limit Middleware
2
+
3
+ The Body Limit Middleware can limit the file size of the request body.
4
+
5
+ This middleware first uses the value of the `Content-Length` header in the request, if present.
6
+ If it is not set, it reads the body in the stream and executes an error handler if it is larger than the specified file size.
7
+
8
+ ## Import
9
+
10
+ ```ts
11
+ import { Acryl } from '@acryldev/blends'
12
+ import { bodyLimit } from '@acryldev/blends/body-limit'
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ const app = new Acryl()
19
+
20
+ app.post(
21
+ '/upload',
22
+ bodyLimit({
23
+ maxSize: 50 * 1024, // 50kb
24
+ onError: (c) => {
25
+ return c.text('overflow :(', 413)
26
+ },
27
+ }),
28
+ async (c) => {
29
+ const body = await c.req.parseBody()
30
+ if (body['file'] instanceof File) {
31
+ console.log(`Got file sized: ${body['file'].size}`)
32
+ }
33
+ return c.text('pass :)')
34
+ }
35
+ )
36
+ ```
37
+
38
+ ## Options
39
+
40
+ ### **(required)** maxSize: `number`
41
+
42
+ The maximum file size of the file you want to limit. The default is `100 * 1024` - `100kb`.
43
+
44
+ ### *(optional)* onError: `OnError`
45
+
46
+ The error handler to be invoked if the specified file size is exceeded.
47
+
48
+ ## Usage with Bun for large requests
49
+
50
+ If the Body Limit Middleware is used explicitly to allow a request body larger than the default, it might be necessary to make changes to your `Bun.serve` configuration accordingly. [At the time of writing](https://github.com/oven-sh/bun/blob/f2cfa15e4ef9d730fc6842ad8b79fb7ab4c71cb9/packages/bun-types/bun.d.ts#L2191), `Bun.serve`'s default request body limit is 128MiB. If you set Acryl's Body Limit Middleware to a value bigger than that, your requests will still fail and, additionally, the `onError` handler specified in the middleware will not be called. This is because `Bun.serve()` will set the status code to `413` and terminate the connection before passing the request to Acryl.
51
+
52
+ If you want to accept requests larger than 128MiB with Acryl and Bun, you need to set the limit for Bun as well:
53
+
54
+ ```ts
55
+ export default {
56
+ port: process.env['PORT'] || 3000,
57
+ fetch: app.fetch,
58
+ maxRequestBodySize: 1024 * 1024 * 200, // your value here
59
+ }
60
+ ```
61
+
62
+ or, depending on your setup:
63
+
64
+ ```ts
65
+ Bun.serve({
66
+ fetch(req, server) {
67
+ return app.fetch(req, { ip: server.requestIP(req) })
68
+ },
69
+ maxRequestBodySize: 1024 * 1024 * 200, // your value here
70
+ })
71
+ ```
@@ -0,0 +1,99 @@
1
+ # Cache Middleware
2
+
3
+ The Cache middleware uses the Web Standards' [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
4
+
5
+ It needs a Cache API on the host: the middleware reads `globalThis.caches`. Node.js, the verified runtime, does not provide one, so on Node the middleware is not enabled and says so in one line; a host that embeds an app in a runtime with a Cache API (or provides `globalThis.caches` itself) gets it. `Cache-Control` handling and the QUERY-request cache below are implemented by the middleware, not by the platform.
6
+
7
+ ## Import
8
+
9
+ ```ts
10
+ import { Acryl } from '@acryldev/blends'
11
+ import { cache } from '@acryldev/blends/cache'
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ app.get(
18
+ '*',
19
+ cache({
20
+ cacheName: 'my-app',
21
+ cacheControl: 'max-age=3600',
22
+ })
23
+ )
24
+ ```
25
+
26
+ ## Caching QUERY requests
27
+
28
+ The Cache middleware also caches responses to [QUERY](https://www.rfc-editor.org/rfc/rfc10008.html) requests. As required by RFC 10008, the cache key for a QUERY request incorporates a digest of the request content and its representation metadata, so requests with different bodies are cached separately.
29
+
30
+ QUERY requests with a body larger than `maxQueryBodySize` (64 KiB by default) bypass the cache.
31
+
32
+ > **Note.** To support this, cached entries are stored under an internal key, so they do not collide with your own requests.
33
+
34
+ ## Options
35
+
36
+ ### **(required)** cacheName: `string` | `(c: Context) => string` | `Promise<string>`
37
+
38
+ The name of the cache. Can be used to store multiple caches with different identifiers.
39
+
40
+ ### *(optional)* wait: `boolean`
41
+
42
+ A boolean indicating if Acryl should wait for the Promise of the `cache.put` function to resolve before continuing with the request. The default is `false`. A runtime whose Cache API only completes a write after the response has finished needs `true`, or the write is dropped.
43
+
44
+ ### *(optional)* cacheControl: `string`
45
+
46
+ A string of directives for the `Cache-Control` header. See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) for more information. When this option is not provided, no `Cache-Control` header is added to requests.
47
+
48
+ ### *(optional)* vary: `string` | `string[]`
49
+
50
+ Sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates. Setting this to `*` will result in an error. For more details on the Vary header and its implications for caching strategies, refer to the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary).
51
+
52
+ ### *(optional)* keyGenerator: `(c: Context) => string | Promise<string>`
53
+
54
+ Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters. The default is `c.req.url`. For QUERY requests, the key additionally includes a digest of the request content and its representation metadata.
55
+
56
+ ### *(optional)* maxQueryBodySize: `number`
57
+
58
+ The maximum QUERY request body size in bytes that can be cached. QUERY requests with a larger body bypass the cache. The default is `65536` (64 KiB).
59
+
60
+ ### *(optional)* cacheableStatusCodes: `number[]`
61
+
62
+ An array of status codes that should be cached. The default is `[200]`. Use this option to cache responses with specific status codes.
63
+
64
+ ```ts
65
+ app.get(
66
+ '*',
67
+ cache({
68
+ cacheName: 'my-app',
69
+ cacheControl: 'max-age=3600',
70
+ cacheableStatusCodes: [200, 404, 412],
71
+ })
72
+ )
73
+ ```
74
+
75
+ ### *(optional)* onCacheNotAvailable: `((reason: string) => void | Promise<void>)` | `false`
76
+
77
+ A callback function or `false` that controls the behavior when the Cache API is not available in the global scope, or when QUERY caching cannot use Web Crypto. The callback is invoked with the reason. By default, the reason is logged with `console.log`. You can provide a custom function to customize the behavior, or set it to `false` to suppress the log entirely.
78
+
79
+ ```ts
80
+ // Custom logging
81
+ app.use(
82
+ cache({
83
+ cacheName: 'my-app-v1',
84
+ onCacheNotAvailable: () => {
85
+ console.log('Custom log: Cache API is not available.')
86
+ },
87
+ })
88
+ )
89
+ ```
90
+
91
+ ```ts
92
+ // Suppress logging
93
+ app.use(
94
+ cache({
95
+ cacheName: 'my-app-v1',
96
+ onCacheNotAvailable: false,
97
+ })
98
+ )
99
+ ```
@@ -0,0 +1,94 @@
1
+ # Combine Middleware
2
+
3
+ Combine Middleware combines multiple middleware functions into a single middleware. It provides three functions:
4
+
5
+ - `some` - Runs only one of the given middleware.
6
+ - `every` - Runs all given middleware.
7
+ - `except` - Runs all given middleware only if a condition is not met.
8
+
9
+ ## Import
10
+
11
+ ```ts
12
+ import { Acryl } from '@acryldev/blends'
13
+ import { some, every, except } from '@acryldev/blends/combine'
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ Here's an example of complex access control rules using Combine Middleware.
19
+
20
+ ```ts
21
+ import { Acryl } from '@acryldev/blends'
22
+ import { bearerAuth } from '@acryldev/blends/bearer-auth'
23
+ import { getConnInfo } from '@acryldev/blends/node-server'
24
+ import { every, some } from '@acryldev/blends/combine'
25
+ import { ipRestriction } from '@acryldev/blends/ip-restriction'
26
+ import { rateLimit } from '@/my-rate-limit'
27
+
28
+ const app = new Acryl()
29
+
30
+ app.use(
31
+ '*',
32
+ some(
33
+ every(
34
+ ipRestriction(getConnInfo, { allowList: ['192.168.0.2'] }),
35
+ bearerAuth({ token })
36
+ ),
37
+ // If both conditions are met, rateLimit will not execute.
38
+ rateLimit()
39
+ )
40
+ )
41
+
42
+ app.get('/', (c) => c.text('Acryl!'))
43
+ ```
44
+
45
+ ### some
46
+
47
+ Runs the first middleware that returns true. Middleware is applied in order, and if any middleware exits successfully, subsequent middleware will not run.
48
+
49
+ ```ts
50
+ import { some } from '@acryldev/blends/combine'
51
+ import { bearerAuth } from '@acryldev/blends/bearer-auth'
52
+ import { myRateLimit } from '@/rate-limit'
53
+
54
+ // If client has a valid token, skip rate limiting.
55
+ // Otherwise, apply rate limiting.
56
+ app.use(
57
+ '/api/*',
58
+ some(bearerAuth({ token }), myRateLimit({ limit: 100 }))
59
+ )
60
+ ```
61
+
62
+ ### every
63
+
64
+ Runs all middleware and stops if any of them fail. Middleware is applied in order, and if any middleware throws an error, subsequent middleware will not run.
65
+
66
+ ```ts
67
+ import { some, every } from '@acryldev/blends/combine'
68
+ import { bearerAuth } from '@acryldev/blends/bearer-auth'
69
+ import { myCheckLocalNetwork } from '@/check-local-network'
70
+ import { myRateLimit } from '@/rate-limit'
71
+
72
+ // If client is in local network, skip authentication and rate limiting.
73
+ // Otherwise, apply authentication and rate limiting.
74
+ app.use(
75
+ '/api/*',
76
+ some(
77
+ myCheckLocalNetwork(),
78
+ every(bearerAuth({ token }), myRateLimit({ limit: 100 }))
79
+ )
80
+ )
81
+ ```
82
+
83
+ ### except
84
+
85
+ Runs all middleware except when the condition is met. You can pass a string or function as the condition. If multiple targets need to be matched, pass them as an array.
86
+
87
+ ```ts
88
+ import { except } from '@acryldev/blends/combine'
89
+ import { bearerAuth } from '@acryldev/blends/bearer-auth'
90
+
91
+ // If client is accessing public API, skip authentication.
92
+ // Otherwise, require a valid token.
93
+ app.use('/api/*', except('/api/public/*', bearerAuth({ token })))
94
+ ```
@@ -0,0 +1,59 @@
1
+ # Compress Middleware
2
+
3
+ This middleware compresses the response body, according to `Accept-Encoding` request header.
4
+
5
+ > **Note.** Node.js and Bun do not compress a response on their own, so this middleware is what compresses it. A host that already compresses at its edge does not need it.
6
+
7
+ ## Import
8
+
9
+ ```ts
10
+ import { Acryl } from '@acryldev/blends'
11
+ import { compress } from '@acryldev/blends/compress'
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ const app = new Acryl()
18
+
19
+ app.use(compress())
20
+ ```
21
+
22
+ ## Options
23
+
24
+ ### *(optional)* encoding: `'gzip'` | `'deflate'`
25
+
26
+ The compression scheme to allow for response compression. Either `gzip` or `deflate`. If not defined, both are allowed and will be used based on the `Accept-Encoding` header. `gzip` is prioritized if this option is not provided and the client provides both in the `Accept-Encoding` header.
27
+
28
+ ### *(optional)* threshold: `number`
29
+
30
+ The minimum size in bytes to compress. Defaults to 1024 bytes.
31
+
32
+ ### *(optional)* contentTypeFilter: `RegExp` | `(contentType: string) => boolean`
33
+
34
+ A `RegExp` or function to determine whether the response should be compressed based on its `Content-Type`. By default, a built-in list of compressible Content-Types is used.
35
+
36
+ You can pass a `RegExp` to compress only matching Content-Types:
37
+
38
+ ```ts
39
+ // Compress only JSON responses
40
+ app.use(compress({ contentTypeFilter: /^application\/json/ }))
41
+ ```
42
+
43
+ Or pass a function for custom logic. The built-in `COMPRESSIBLE_CONTENT_TYPE_REGEX` is also exported so you can extend the default behavior:
44
+
45
+ ```ts
46
+ import {
47
+ compress,
48
+ COMPRESSIBLE_CONTENT_TYPE_REGEX,
49
+ } from '@acryldev/blends/compress'
50
+
51
+ // Compress the default Content-Types plus a custom one
52
+ app.use(
53
+ compress({
54
+ contentTypeFilter: (type) =>
55
+ COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) ||
56
+ type === 'application/x-myformat',
57
+ })
58
+ )
59
+ ```
@@ -0,0 +1,74 @@
1
+ # Context Storage Middleware
2
+
3
+ The Context Storage Middleware stores the Acryl `Context` in the `AsyncLocalStorage`, to make it globally accessible.
4
+
5
+ > **Note.** This middleware uses `AsyncLocalStorage`. Node.js, the verified runtime, provides it; a host that embeds an app in a runtime without it cannot use this middleware.
6
+
7
+ ## Import
8
+
9
+ ```ts
10
+ import { Acryl } from '@acryldev/blends'
11
+ import {
12
+ contextStorage,
13
+ getContext,
14
+ tryGetContext,
15
+ } from '@acryldev/blends/context-storage'
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ The `getContext()` will return the current Context object if the `contextStorage()` is applied as a middleware.
21
+
22
+ ```ts
23
+ type Env = {
24
+ Variables: {
25
+ message: string
26
+ }
27
+ }
28
+
29
+ const app = new Acryl<Env>()
30
+
31
+ app.use(contextStorage())
32
+
33
+ app.use(async (c, next) => {
34
+ c.set('message', 'Hello!')
35
+ await next()
36
+ })
37
+
38
+ // You can access the variable outside the handler.
39
+ const getMessage = () => {
40
+ return getContext<Env>().var.message
41
+ }
42
+
43
+ app.get('/', (c) => {
44
+ return c.text(getMessage())
45
+ })
46
+ ```
47
+
48
+ Anything a handler puts on the context can be read further down the call stack, without passing `c` through every function:
49
+
50
+ ```ts
51
+ const app = new Acryl()
52
+
53
+ app.use(contextStorage())
54
+ app.use(async (c, next) => {
55
+ c.set('user', 'ada')
56
+ await next()
57
+ })
58
+
59
+ app.get('/', (c) => c.text(`Hello ${getUser()}`))
60
+
61
+ const getUser = () => getContext().get('user')
62
+ ```
63
+
64
+ ## tryGetContext
65
+
66
+ `tryGetContext()` works like `getContext()`, but returns `undefined` instead of throwing an error when the context is not available:
67
+
68
+ ```ts
69
+ const context = tryGetContext<Env>()
70
+ if (context) {
71
+ // Context is available
72
+ console.log(context.var.message)
73
+ }
74
+ ```