@joetjen/cooper-fastify 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jan Oetjen
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,209 @@
1
- # Temporary Holding Version
1
+ # cooper-fastify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ cooper-fastify is a [Fastify](https://fastify.dev) plugin that loads your
4
+ application's [CASC](https://github.com/joetjen/cooper/blob/main/guides/casc/CASC.md)
5
+ configuration once, at startup, and puts it on `fastify.config`. It also
6
+ gives the server's own options -- body limit, timeouts, logger, TLS --
7
+ to the `Fastify()` factory from the same document.
8
+
9
+ Fastify has no configuration system of its own. This plugin takes the
10
+ place of `@fastify/env` and of `dotenv`: `.env` files are read by
11
+ [`cooper`](https://github.com/joetjen/node-cooper) itself. The loading
12
+ and reading are [`cooper-config`](https://github.com/joetjen/node-cooper-config)'s,
13
+ so `fastify.config.get(...)` and `require('@joetjen/cooper-config').get(...)` read
14
+ the same configuration.
15
+
16
+ ```text
17
+ # config/config.casc
18
+ #@version = 1.0
19
+
20
+ fastify {
21
+ bodyLimit = 1MiB
22
+ requestTimeout = 30s
23
+ trustProxy = true
24
+ logger { level = "info" }
25
+ https {
26
+ key = !file("certs/server.key")
27
+ cert = !file("certs/server.crt")
28
+ }
29
+ listen { port = 8443, host = "0.0.0.0" }
30
+ }
31
+
32
+ db {
33
+ host = "db.internal"
34
+ *password = ${DB_PASSWORD}
35
+ }
36
+
37
+ import "${COOPER_ENV}/*.casc"
38
+ ```
39
+
40
+ ```js
41
+ import Fastify from 'fastify';
42
+ import cooper, { serverOptions, listenOptions } from '@joetjen/cooper-fastify';
43
+
44
+ const app = Fastify(await serverOptions()); // loads config/config.casc, once
45
+ await app.register(cooper); // fastify.config
46
+
47
+ app.get('/db', async (request) => ({ host: request.server.config.get('db.host') }));
48
+
49
+ await app.listen(listenOptions());
50
+ ```
51
+
52
+ ## Install
53
+
54
+ ```sh
55
+ npm install @joetjen/cooper-fastify
56
+ ```
57
+
58
+ `fastify` 5 is a peer dependency, so your own is used. `cooper-config`
59
+ and `cooper` come along. You need Node.js 20 or later. `require` works
60
+ the same way as `import`.
61
+
62
+ ## The plugin
63
+
64
+ ```js
65
+ await app.register(cooper, options?);
66
+ ```
67
+
68
+ Registering it loads the configuration and decorates the instance with
69
+ `config`. The plugin is wrapped with `fastify-plugin`, so the
70
+ configuration lands on the instance that registers it, and every plugin
71
+ and route below sees it.
72
+
73
+ | | |
74
+ | --- | --- |
75
+ | options given | loads with them, cooper-config's load options (`path`, `root`, `env`, `dotenvDir`, `modules`, `tags`, ...) |
76
+ | no options, something loaded | reads that: by `serverOptions()`, the preload entry or `cooper-config` itself |
77
+ | no options, nothing loaded | loads `config/config.casc` under the project root |
78
+ | an unknown option | `TypeError` |
79
+ | the document does not load | `ready()` rejects with `CooperConfigError`; the server never starts |
80
+ | `prefix`, `logLevel`, `logSerializers` | Fastify's, left to Fastify |
81
+
82
+ The project root is the directory of the nearest `package.json` above
83
+ the working directory.
84
+
85
+ ## Reading: `fastify.config`
86
+
87
+ ```js
88
+ app.config.get('db.port', 5432); // the value, or the fallback when there is none
89
+ app.config.require('db.host'); // the value, or a CooperConfigError naming the path
90
+ app.config.has('db.replica'); // whether anything, null included, is there
91
+ app.config.all(); // the whole configuration
92
+ request.server.config.get('db.host') // the same, in a route
93
+ ```
94
+
95
+ Paths are dotted (`'db.pool.size'`) or an array of segments for a key
96
+ holding a dot (`['dotted.key', 'inner']`). Every value is deep-frozen,
97
+ and so is `fastify.config`. Byte sizes arrive as bytes and durations as
98
+ milliseconds; the [`cooper-config` README](https://github.com/joetjen/node-cooper-config#conversion)
99
+ has the full table, and how each block's secrets arrive.
100
+
101
+ TypeScript knows `fastify.config` once the package is imported:
102
+
103
+ ```ts
104
+ const host = app.config.require<string>('db.host');
105
+ ```
106
+
107
+ ## The server's options: `serverOptions()` and `listenOptions()`
108
+
109
+ Fastify takes its server options once, when `Fastify()` creates the
110
+ app, before any plugin runs. So the plugin cannot set them, and
111
+ `serverOptions()` reads them first:
112
+
113
+ ```js
114
+ const app = Fastify(await serverOptions(options?));
115
+ await app.listen(listenOptions());
116
+ ```
117
+
118
+ - `serverOptions()` loads the configuration by the plugin's rule and
119
+ returns the `fastify` block without its `listen` block. The plugin
120
+ registered afterwards without options reads the same load.
121
+ - `listenOptions()` returns the `fastify.listen` block. It loads
122
+ nothing.
123
+ - Both return fresh, mutable objects, and an empty one when there is no
124
+ block.
125
+ - The keys are Fastify's own, camel case included.
126
+
127
+ ### Code: `!module`
128
+
129
+ Options that are functions or objects -- `genReqId`, a log `stream`, a
130
+ `loggerInstance`, `querystringParser` -- are named with CASC's `!module`
131
+ and mapped in code:
132
+
133
+ ```text
134
+ fastify {
135
+ genReqId = !module("App.RequestId")
136
+ }
137
+ ```
138
+
139
+ ```js
140
+ const app = Fastify(await serverOptions({
141
+ modules: { 'App.RequestId': './lib/request-id.js' }, // its default export
142
+ // or: { 'App.RequestId': genReqId } // the value itself
143
+ }));
144
+ ```
145
+
146
+ A document can only choose among the names the application mapped. It
147
+ can never name a file of code, not even through `${...}`. A `!module`
148
+ anywhere in the block is resolved. This is why `serverOptions()` is
149
+ asynchronous: a mapped path is imported.
150
+
151
+ ### Files: `!file`
152
+
153
+ `!file("path")` is a file's contents, as UTF-8 text, for options that
154
+ take contents rather than a path -- `https.key`, `https.cert`,
155
+ `https.ca`:
156
+
157
+ ```text
158
+ fastify {
159
+ https {
160
+ key = !file("certs/server.key") # relative to the project root
161
+ cert = !file("${TLS_CERT}") # or a path from the environment
162
+ }
163
+ }
164
+ ```
165
+
166
+ - An absolute path is read as it is.
167
+ - A file that is not there fails the load, naming it.
168
+ - `!file` works everywhere in the document, not only in `fastify`.
169
+ - A `file` tag of your own, passed in `tags`, replaces it.
170
+ - It is cooper-fastify's tag, not part of CASC: a document using it
171
+ loads only where it is registered.
172
+ - An application loading with `cooper-config` directly can register it
173
+ with `tags: { file: fileTag(root) }`.
174
+
175
+ ## Startup without `serverOptions()`
176
+
177
+ When nothing reads the configuration before the plugin, registering it
178
+ is enough. To load it before any of your code runs, preload it:
179
+
180
+ ```sh
181
+ node --import @joetjen/cooper-fastify/register app.js # ES modules
182
+ node --require @joetjen/cooper-fastify/register app.js # CommonJS
183
+ ```
184
+
185
+ Use `@joetjen/cooper-fastify/register` rather than `@joetjen/cooper-config/register`,
186
+ because only this one registers `!file`. A document that does not load
187
+ stops the process with its message and exit code 1.
188
+
189
+ ## Per-environment configuration
190
+
191
+ `${COOPER_ENV}` names the environment (`dev`, `test`, `prod`), falling
192
+ back to `NODE_ENV`, and `.env.<env>` is chosen by it. See the
193
+ [`cooper-config` README](https://github.com/joetjen/node-cooper-config#per-environment-configuration-cooper_env).
194
+
195
+ ## Development
196
+
197
+ ```sh
198
+ npm install
199
+ npm run precommit
200
+ ```
201
+
202
+ `npm run precommit` type-checks the JSDoc (`tsc --checkJs --noEmit`)
203
+ and the TypeScript declarations, and runs the Mocha suite. See
204
+ [CONTRIBUTING.md](CONTRIBUTING.md) and the
205
+ [cheatsheet](guides/CHEATSHEET.md).
206
+
207
+ ## License
208
+
209
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,65 @@
1
+ # cooper-fastify cheatsheet
2
+
3
+ ## Startup
4
+
5
+ ```js
6
+ import Fastify from 'fastify';
7
+ import cooper, { serverOptions, listenOptions } from '@joetjen/cooper-fastify';
8
+
9
+ const app = Fastify(await serverOptions(options?)); // loads, once
10
+ await app.register(cooper); // fastify.config
11
+ await app.listen(listenOptions());
12
+ ```
13
+
14
+ ```sh
15
+ node --import @joetjen/cooper-fastify/register app.js # or preload: ESM
16
+ node --require @joetjen/cooper-fastify/register app.js # CJS
17
+ ```
18
+
19
+ ## When the configuration is loaded
20
+
21
+ | Call | Loads |
22
+ | --- | --- |
23
+ | `register(cooper, options)` / `serverOptions(options)` | with `options`, always |
24
+ | `register(cooper)` / `serverOptions()` | nothing if already loaded, else the defaults |
25
+ | `listenOptions()` | never |
26
+ | `@joetjen/cooper-fastify/register` | the defaults, before the application |
27
+
28
+ | | |
29
+ | --- | --- |
30
+ | options | cooper-config's: `path`, `root`, `env`, `dotenv*`, `resolvers`, `tags`, `importSchemes`, `modules`, `cache`, `watchEnv` |
31
+ | unknown option | `TypeError` |
32
+ | document does not load | `ready()` / `serverOptions()` rejects with `CooperConfigError`; preload exits 1 |
33
+ | no `config/config.casc` | empty configuration |
34
+
35
+ ## Reading
36
+
37
+ ```js
38
+ app.config.get(path, fallback?) // value, or fallback
39
+ app.config.require(path) // value, or CooperConfigError
40
+ app.config.has(path) // true for a present null
41
+ app.config.all() // everything, deep-frozen
42
+ request.server.config // the same, in a route
43
+ ```
44
+
45
+ `path`: `'a.b.c'` or `['dotted.key', 'inner']`.
46
+
47
+ ## The `fastify` block
48
+
49
+ ```text
50
+ fastify {
51
+ bodyLimit = 1MiB # 1048576
52
+ requestTimeout = 30s # 30000
53
+ logger { level = "info" }
54
+ genReqId = !module("App.RequestId") # mapped in code
55
+ https { key = !file("certs/server.key") } # the file's text
56
+ listen { port = 8080, host = "0.0.0.0" } # listenOptions() only
57
+ }
58
+ ```
59
+
60
+ | | |
61
+ | --- | --- |
62
+ | keys | Fastify's own, camel case |
63
+ | `!module("Name")` | `modules[Name]`: a value as is, a specifier's default export |
64
+ | `!file("path")` | UTF-8 contents; relative to the project root, or absolute; `${...}` allowed |
65
+ | result | fresh, mutable; `{}` without a block |
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@joetjen/cooper-fastify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "author": "Jan Oetjen <joetjen.riveting388@passmail.net> (http://joetjen.net)",
9
+ "description": "A Fastify plugin that loads an application's CASC configuration once, at startup, with cooper-config, and puts it on fastify.config -- the server's own options included.",
10
+ "homepage": "https://github.com/joetjen/node-cooper-fastify",
11
+ "type": "module",
12
+ "main": "./src/cooper-fastify.cjs",
13
+ "types": "./types/cooper-fastify.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./types/cooper-fastify.d.ts",
17
+ "import": "./src/cooper-fastify.js",
18
+ "require": "./src/cooper-fastify.cjs",
19
+ "default": "./src/cooper-fastify.cjs"
20
+ },
21
+ "./register": {
22
+ "import": "./src/register.js",
23
+ "require": "./src/register.cjs",
24
+ "default": "./src/register.cjs"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "types",
31
+ "guides"
32
+ ],
33
+ "license": "Apache-2.0",
34
+ "directories": {
35
+ "src": "./src"
36
+ },
37
+ "dependencies": {
38
+ "@joetjen/cooper": "^0.1.1",
39
+ "@joetjen/cooper-config": "^0.1.0",
40
+ "fastify-plugin": "^6.0.0"
41
+ },
42
+ "peerDependencies": {
43
+ "fastify": "^5.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^26.2.0",
47
+ "auto-changelog": "^2.6.0",
48
+ "chai": "^6.2.2",
49
+ "fastify": "^5.12.5",
50
+ "mocha": "^12.0.3",
51
+ "typedoc": "^0.28.20",
52
+ "typescript": "~6.0"
53
+ },
54
+ "engines": {
55
+ "node": ">=20.0.0",
56
+ "npm": ">=9.0.0"
57
+ },
58
+ "scripts": {
59
+ "test": "npx mocha --recursive test/",
60
+ "autotest": "npx mocha --recursive --watch test/",
61
+ "typecheck": "npx tsc --checkJs --noEmit && npx tsc --noEmit -p test/types",
62
+ "precommit": "npm run typecheck && npm test",
63
+ "docs": "npx typedoc",
64
+ "version": "npx auto-changelog --package --template keepachangelog && git add CHANGELOG.md"
65
+ },
66
+ "repository": {
67
+ "type": "git",
68
+ "url": "git://github.com/joetjen/node-cooper-fastify.git"
69
+ },
70
+ "bugs": {
71
+ "url": "https://github.com/joetjen/node-cooper-fastify/issues",
72
+ "email": "joetjen.riveting388@passmail.net"
73
+ },
74
+ "keywords": [
75
+ "casc",
76
+ "cooper",
77
+ "config",
78
+ "configuration",
79
+ "fastify",
80
+ "fastify-plugin"
81
+ ]
82
+ }
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview The plugin: registering it loads the application's CASC
5
+ * configuration, and `fastify.config` reads it.
6
+ *
7
+ * ```js
8
+ * const app = Fastify(await serverOptions());
9
+ * await app.register(cooper);
10
+ * app.config.get('db.host');
11
+ * ```
12
+ *
13
+ * **Fastify has no configuration system of its own**, so there is nothing
14
+ * to feed and nothing to replace but `@fastify/env`, whose
15
+ * `fastify.config` this takes the name of. The configuration itself is
16
+ * `cooper-config`'s, loaded once and process-wide, so `fastify.config` and
17
+ * a plain `require('@joetjen/cooper-config').get(...)` read the same thing.
18
+ *
19
+ * It is wrapped with `fastify-plugin`: a configuration belongs to the
20
+ * whole application, not to the encapsulation context that happened to
21
+ * register it.
22
+ */
23
+
24
+ const fp = require('fastify-plugin');
25
+ const cooperConfig = require('@joetjen/cooper-config');
26
+ const { ensureLoaded } = require('./load.cjs');
27
+ const { serverOptions, listenOptions } = require('./server-options.cjs');
28
+ const { fileTag } = require('./file-tag.cjs');
29
+ const version = require('./version.cjs');
30
+
31
+ /**
32
+ * What `fastify.config` is: cooper-config's four readers, frozen, so no
33
+ * plugin can swap the configuration out from under the others.
34
+ * @typedef {Readonly<{get: typeof cooperConfig.get, require: typeof cooperConfig.require, has: typeof cooperConfig.has, all: typeof cooperConfig.all}>} ConfigReader
35
+ */
36
+
37
+ /** @type {ConfigReader} */
38
+ const reader = Object.freeze({
39
+ get: cooperConfig.get,
40
+ require: cooperConfig.require,
41
+ has: cooperConfig.has,
42
+ all: cooperConfig.all,
43
+ });
44
+
45
+ /**
46
+ * Loads the configuration and decorates the instance with `config`.
47
+ *
48
+ * Its options are cooper-config's load options. Given none, it reads a
49
+ * configuration already loaded -- by `serverOptions()`, the preload entry
50
+ * or the application -- and loads the defaults only when there is none.
51
+ * A document that does not load rejects, so `ready()` does and the server
52
+ * never starts.
53
+ *
54
+ * @param {import('fastify').FastifyInstance} fastify
55
+ * @param {Record<string, unknown>} options
56
+ * @returns {Promise<void>}
57
+ */
58
+ async function cooperFastify(fastify, options) {
59
+ ensureLoaded(options);
60
+ fastify.decorate('config', reader);
61
+ }
62
+
63
+ const plugin = fp(cooperFastify, { name: '@joetjen/cooper-fastify', fastify: '5.x' });
64
+
65
+ // The CommonJS module is the plugin, as Fastify's plugins are, with the
66
+ // rest of the API on it. `default` and `cooperFastify` are the names a
67
+ // transpiled default import and a named import look for.
68
+ module.exports = plugin;
69
+ module.exports.default = plugin;
70
+ module.exports.cooperFastify = plugin;
71
+ module.exports.serverOptions = serverOptions;
72
+ module.exports.listenOptions = listenOptions;
73
+ module.exports.fileTag = fileTag;
74
+ module.exports.version = version;
@@ -0,0 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+
3
+ const requireCjs = createRequire(import.meta.url);
4
+ const plugin = requireCjs('./cooper-fastify.cjs');
5
+
6
+ /** @type {typeof plugin.serverOptions} */
7
+ const serverOptions = plugin.serverOptions;
8
+ /** @type {typeof plugin.listenOptions} */
9
+ const listenOptions = plugin.listenOptions;
10
+ /** @type {typeof plugin.fileTag} */
11
+ const fileTag = plugin.fileTag;
12
+ /** @type {string} */
13
+ const version = plugin.version;
14
+
15
+ export { plugin as cooperFastify, serverOptions, listenOptions, fileTag, version };
16
+
17
+ export default plugin;
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview `!file("...")`: a file's contents as a configuration
5
+ * value, and the project root a relative path is read from.
6
+ *
7
+ * **For the options that take contents rather than a path.** Fastify's
8
+ * `https` key, certificate and CA are the reason this exists: they are
9
+ * PEM text, and without the tag they could only be read in code, outside
10
+ * the configuration that otherwise describes the server.
11
+ *
12
+ * **This tag is cooper-fastify's, not CASC's.** A document using it loads
13
+ * only where it is registered. That is the same bargain the Laravel
14
+ * adapter's path tags make, and it stays here until a second integration
15
+ * needs it.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ /**
22
+ * The project root: the directory of the nearest `package.json` found
23
+ * walking up from `cwd`, else `cwd` itself.
24
+ *
25
+ * The same rule `cooper-config` finds `config/config.casc` by, so a
26
+ * relative `!file` path and the document are read from one directory.
27
+ * Repeated here because `cooper-config` does not export it.
28
+ *
29
+ * @param {string} [cwd] -- where to start (default `process.cwd()`)
30
+ * @returns {string} an absolute path
31
+ */
32
+ function projectRoot(cwd = process.cwd()) {
33
+ const start = path.resolve(cwd);
34
+ for (let dir = start; ; dir = path.dirname(dir)) {
35
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
36
+ if (path.dirname(dir) === dir) return start;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The `!file` tag for a project rooted at `root`: it reads the file its
42
+ * argument names -- relative to `root`, or absolute -- as UTF-8 text.
43
+ *
44
+ * Text, not a `Buffer`, because what it is for is text: PEM keys and
45
+ * certificates, which Fastify and `node:tls` take as strings.
46
+ *
47
+ * **The environment may choose the file** (`!file("${TLS_KEY}")`), which
48
+ * `!module` deliberately does not allow for code: reading a file runs
49
+ * nothing.
50
+ *
51
+ * @param {string} root -- the directory a relative path is read from
52
+ * @returns {(argument: unknown) => string}
53
+ * @example
54
+ * loadFileSync('config/config.casc', { tags: { file: fileTag(process.cwd()) } });
55
+ */
56
+ function fileTag(root) {
57
+ return function file(argument) {
58
+ if (typeof argument !== 'string') {
59
+ throw new TypeError(`!file takes a path as a string, not ${typeof argument === 'object' ? String(argument) : JSON.stringify(argument) ?? String(argument)}`);
60
+ }
61
+ const absolute = path.resolve(root, argument);
62
+ try {
63
+ return fs.readFileSync(absolute, 'utf8');
64
+ } catch (err) {
65
+ const code = /** @type {NodeJS.ErrnoException} */ (err).code ?? /** @type {Error} */ (err).message;
66
+ throw new Error(`cannot read ${absolute} (${code})`);
67
+ }
68
+ };
69
+ }
70
+
71
+ module.exports = { fileTag, projectRoot };
package/src/load.cjs ADDED
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview When the configuration is loaded, and with what: the one
5
+ * rule the plugin, `serverOptions()` and the preload entry share.
6
+ *
7
+ * - **Options given: load with them**, whatever was loaded before. They
8
+ * are a request for that configuration.
9
+ * - **No options: read what is loaded**, so `serverOptions(options)`
10
+ * followed by `register(cooper)` is one load, not two -- and a load the
11
+ * application made with `cooper-config` itself, or through a preload,
12
+ * is the one the plugin reads.
13
+ * - **No options and nothing loaded: load the defaults.**
14
+ *
15
+ * Every load registers `!file`, beside the application's own tags.
16
+ */
17
+
18
+ const path = require('node:path');
19
+ const cooperConfig = require('@joetjen/cooper-config');
20
+ const { fileTag, projectRoot } = require('./file-tag.cjs');
21
+
22
+ /**
23
+ * Fastify's own `register()` options. Fastify hands them to the plugin
24
+ * along with the rest, and they are not cooper-config's to refuse.
25
+ */
26
+ const FASTIFY_REGISTER_OPTIONS = ['prefix', 'logLevel', 'logSerializers'];
27
+
28
+ /**
29
+ * Loads the configuration by the rule above.
30
+ * @param {Record<string, unknown>} [options] -- cooper-config's load options, Fastify's register options among them or not
31
+ * @returns {void}
32
+ * @throws {TypeError} for an option cooper-config does not know
33
+ * @throws {import('@joetjen/cooper-config').CooperConfigError} when the document does not load
34
+ */
35
+ function ensureLoaded(options = {}) {
36
+ const own = withoutFastifyOptions(options);
37
+ if (Object.keys(own).length === 0 && isLoaded()) return;
38
+ cooperConfig.load(withFileTag(own));
39
+ }
40
+
41
+ /**
42
+ * `options` without Fastify's own register options.
43
+ * @param {Record<string, unknown>} options
44
+ * @returns {Record<string, unknown>}
45
+ */
46
+ function withoutFastifyOptions(options) {
47
+ /** @type {Record<string, unknown>} */
48
+ const own = {};
49
+ for (const [key, value] of Object.entries(options)) {
50
+ if (!FASTIFY_REGISTER_OPTIONS.includes(key)) own[key] = value;
51
+ }
52
+ return own;
53
+ }
54
+
55
+ /**
56
+ * `options` with `!file` among its tags, rooted where the document is
57
+ * read from. **The application's own `file` tag wins**, as a tag of
58
+ * cooper's own name does over cooper's built-in.
59
+ * @param {Record<string, unknown>} options
60
+ * @returns {Record<string, unknown>}
61
+ */
62
+ function withFileTag(options) {
63
+ const root = typeof options.root === 'string' ? path.resolve(options.root) : projectRoot();
64
+ const file = fileTag(root);
65
+ const tags = options.tags;
66
+ if (tags instanceof Map) return { ...options, tags: new Map([['file', file], ...tags]) };
67
+ return { ...options, tags: { file, .../** @type {Record<string, unknown>} */ (tags ?? {}) } };
68
+ }
69
+
70
+ /**
71
+ * Whether a configuration has been loaded in this process. `cooper-config`
72
+ * answers that only by refusing to read before a load.
73
+ * @returns {boolean}
74
+ */
75
+ function isLoaded() {
76
+ try {
77
+ cooperConfig.all();
78
+ return true;
79
+ } catch (err) {
80
+ if (err instanceof cooperConfig.CooperConfigError) return false;
81
+ throw err;
82
+ }
83
+ }
84
+
85
+ module.exports = { ensureLoaded, withFileTag };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview The preload entry: `node --import @joetjen/cooper-fastify/register`
5
+ * (or `--require`) loads the configuration with its defaults before the
6
+ * application's own code, `!file` included -- which is why it is not
7
+ * `@joetjen/cooper-config/register`, whose load does not know the tag.
8
+ *
9
+ * A configuration that fails to load stops the process here, with the
10
+ * error's message and exit code 1 rather than a stack trace: the trace
11
+ * would point into this library, and what needs fixing is the document.
12
+ */
13
+
14
+ const { CooperConfigError } = require('@joetjen/cooper-config');
15
+ const { ensureLoaded } = require('./load.cjs');
16
+
17
+ try {
18
+ ensureLoaded();
19
+ } catch (err) {
20
+ if (!(err instanceof CooperConfigError)) throw err;
21
+ process.stderr.write(`cooper-fastify: ${err.message}\n`);
22
+ process.exit(1);
23
+ }
@@ -0,0 +1,3 @@
1
+ // The ESM face of `register.cjs`: importing it runs the CJS module once,
2
+ // against the same process-wide store `cooper-config` reads from.
3
+ import './register.cjs';
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview `serverOptions()` and `listenOptions()`: the `fastify`
5
+ * block, as the `Fastify()` factory and `listen()` take it.
6
+ *
7
+ * **The server's options are fixed when it is created**, before any
8
+ * plugin runs, so the plugin cannot set them. These two read the
9
+ * configuration first -- `serverOptions()` loading it -- for the factory
10
+ * call, which is what lets a server's body limit, timeouts and logger live
11
+ * in the same document as everything else, under the same overlays.
12
+ *
13
+ * The keys are Fastify's own, camel case and all: a second spelling of
14
+ * every option would be one more thing to learn and nothing to gain.
15
+ * Byte sizes and durations already arrive as bytes and milliseconds, the
16
+ * units Fastify takes them in.
17
+ */
18
+
19
+ const cooperConfig = require('@joetjen/cooper-config');
20
+ const { ModuleRef } = require('@joetjen/cooper');
21
+ const { ensureLoaded } = require('./load.cjs');
22
+
23
+ /** The block both read. */
24
+ const BLOCK = 'fastify';
25
+
26
+ /** The sub-block that is `listen()`'s and not the factory's. */
27
+ const LISTEN = 'listen';
28
+
29
+ /**
30
+ * The `fastify` block, without its `listen` block, for `Fastify()`.
31
+ *
32
+ * Loads the configuration by the plugin's rule (see `load.cjs`): with
33
+ * `options`, or reading what is loaded when there are none. **Every
34
+ * `!module("Name")` in the block becomes what the application mapped the
35
+ * name to**: the value itself, or the default export of the module a
36
+ * specifier names, which is why this is asynchronous. A document can
37
+ * choose only among the names the application mapped, never a file of
38
+ * code.
39
+ *
40
+ * @param {import('../types/cooper-fastify.js').CooperFastifyOptions} [options]
41
+ * @returns {Promise<Record<string, any>>} a fresh, mutable object; empty when there is no `fastify` block
42
+ * @throws {TypeError} for an option cooper-config does not know
43
+ * @throws {import('@joetjen/cooper-config').CooperConfigError} when the document does not load
44
+ * @example
45
+ * const app = Fastify(await serverOptions({ modules: { 'App.RequestId': genReqId } }));
46
+ */
47
+ async function serverOptions(options) {
48
+ ensureLoaded(/** @type {Record<string, unknown>} */ (options ?? {}));
49
+ const { [LISTEN]: _listen, ...rest } = /** @type {Record<string, unknown>} */ (cooperConfig.get(BLOCK, {}));
50
+ return /** @type {Record<string, any>} */ (await thawed(rest));
51
+ }
52
+
53
+ /**
54
+ * The `fastify.listen` block, for `listen()`.
55
+ *
56
+ * It reads what is loaded and loads nothing: it is called once the app
57
+ * exists, and by then `serverOptions()` or the plugin has loaded.
58
+ *
59
+ * @returns {Record<string, any>} a fresh, mutable object; empty when there is no such block
60
+ * @throws {import('@joetjen/cooper-config').CooperConfigError} before anything is loaded
61
+ * @example
62
+ * await app.listen(listenOptions());
63
+ */
64
+ function listenOptions() {
65
+ return /** @type {Record<string, any>} */ (copy(cooperConfig.get([BLOCK, LISTEN], {})));
66
+ }
67
+
68
+ /**
69
+ * A mutable copy of a configuration value with every `ModuleRef` in it
70
+ * replaced by its target.
71
+ *
72
+ * Mutable because Fastify, pino and `node:http` were written for option
73
+ * objects they may fill in, and the configuration is frozen.
74
+ *
75
+ * @param {unknown} value
76
+ * @returns {Promise<unknown>}
77
+ */
78
+ async function thawed(value) {
79
+ if (value instanceof ModuleRef) return target(value);
80
+ if (Array.isArray(value)) return Promise.all(value.map(thawed));
81
+ if (isPlain(value)) {
82
+ /** @type {Record<string, unknown>} */
83
+ const out = {};
84
+ for (const [key, inner] of Object.entries(/** @type {object} */ (value))) out[key] = await thawed(inner);
85
+ return out;
86
+ }
87
+ return value;
88
+ }
89
+
90
+ /**
91
+ * What a `!module` names: the mapped value as it is, or, for a specifier,
92
+ * the module's default export -- what a function or a class is exported
93
+ * as, from CommonJS and ES modules alike -- else its namespace.
94
+ * @param {InstanceType<typeof ModuleRef>} ref
95
+ * @returns {Promise<unknown>}
96
+ */
97
+ async function target(ref) {
98
+ const loaded = await ref.load();
99
+ if (ref.specifier === undefined) return loaded;
100
+ return loaded !== null && typeof loaded === 'object' && 'default' in loaded ? loaded.default : loaded;
101
+ }
102
+
103
+ /**
104
+ * The synchronous copy `listenOptions()` makes: blocks and lists, nothing
105
+ * resolved.
106
+ * @param {unknown} value
107
+ * @returns {unknown}
108
+ */
109
+ function copy(value) {
110
+ if (Array.isArray(value)) return value.map(copy);
111
+ if (isPlain(value)) {
112
+ /** @type {Record<string, unknown>} */
113
+ const out = {};
114
+ for (const [key, inner] of Object.entries(/** @type {object} */ (value))) out[key] = copy(inner);
115
+ return out;
116
+ }
117
+ return value;
118
+ }
119
+
120
+ /**
121
+ * Whether `value` is a block: a plain or null-prototype object, not one
122
+ * of cooper's values or anything the application mapped.
123
+ * @param {unknown} value
124
+ * @returns {boolean}
125
+ */
126
+ function isPlain(value) {
127
+ if (value === null || typeof value !== 'object') return false;
128
+ const proto = Object.getPrototypeOf(value);
129
+ return proto === null || proto === Object.prototype;
130
+ }
131
+
132
+ module.exports = { serverOptions, listenOptions };
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ const { version } = require('../package.json');
4
+
5
+ /**
6
+ * The installed `cooper-fastify` package version, read from `package.json`.
7
+ * @type {string}
8
+ */
9
+ module.exports = version;
@@ -0,0 +1,66 @@
1
+ // Types for TypeScript applications. The implementation is JavaScript,
2
+ // checked by `tsc --checkJs`; these say what it gives a TypeScript caller,
3
+ // above all that `fastify.config` exists once the plugin is registered.
4
+
5
+ import type { FastifyListenOptions, FastifyPluginAsync } from 'fastify';
6
+
7
+ /** A path into the configuration: `'db.pool.size'`, or segments for a key holding a dot. */
8
+ export type KeyPath = string | readonly string[];
9
+
10
+ /** What `fastify.config` is: cooper-config's readers. */
11
+ export interface ConfigReader {
12
+ /** The value at `path`, or `fallback` when there is none. */
13
+ get<T = any>(path: KeyPath, fallback?: T): T;
14
+ /** The value at `path`, which must be there. */
15
+ require<T = any>(path: KeyPath): T;
16
+ /** Whether anything, `null` included, is at `path`. */
17
+ has(path: KeyPath): boolean;
18
+ /** The whole configuration, deep-frozen. */
19
+ all(): Readonly<Record<string, any>>;
20
+ }
21
+
22
+ /** cooper-config's load options. */
23
+ export interface CooperFastifyOptions {
24
+ /** The CASC file; a relative one against the project root (default `config/config.casc`). */
25
+ path?: string;
26
+ /** The project root (default: the directory of the nearest `package.json`). */
27
+ root?: string;
28
+ env?: Record<string, string>;
29
+ dotenv?: boolean;
30
+ dotenvEnv?: string | null;
31
+ dotenvFiles?: string[];
32
+ dotenvDir?: string;
33
+ dotenvOverride?: boolean;
34
+ resolvers?: Record<string, (...args: any[]) => unknown> | Map<string, (...args: any[]) => unknown>;
35
+ tags?: Record<string, (argument: any) => unknown> | Map<string, (argument: any) => unknown>;
36
+ importSchemes?: Record<string, (...args: any[]) => unknown>;
37
+ /** What each `!module("Name")` means: a value, or a specifier whose default export is used. */
38
+ modules?: Record<string, unknown> | Map<string, unknown>;
39
+ cache?: boolean;
40
+ watchEnv?: boolean;
41
+ }
42
+
43
+ declare module 'fastify' {
44
+ interface FastifyInstance {
45
+ /** The application's configuration, loaded by cooper-fastify. */
46
+ config: ConfigReader;
47
+ }
48
+ }
49
+
50
+ /** The plugin. Registering it loads the configuration and decorates the instance with `config`. */
51
+ declare const cooperFastify: FastifyPluginAsync<CooperFastifyOptions>;
52
+
53
+ /** The `fastify` block, without `listen`, for the `Fastify()` factory; loads the configuration. */
54
+ export function serverOptions(options?: CooperFastifyOptions): Promise<Record<string, any>>;
55
+
56
+ /** The `fastify.listen` block, for `listen()`. */
57
+ export function listenOptions(): FastifyListenOptions;
58
+
59
+ /** The `!file` tag for a project rooted at `root`. */
60
+ export function fileTag(root: string): (argument: unknown) => string;
61
+
62
+ /** The installed package version. */
63
+ export const version: string;
64
+
65
+ export { cooperFastify };
66
+ export default cooperFastify;