expediate 1.0.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +138 -0
- package/CONTRIBUTING.md +150 -0
- package/README.md +278 -779
- package/dist/apis.d.ts +372 -12
- package/dist/apis.d.ts.map +1 -1
- package/dist/apis.js +483 -65
- package/dist/apis.js.map +1 -1
- package/dist/cjs/index.js +2290 -807
- package/dist/git.d.ts +1 -1
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +5 -5
- package/dist/git.js.map +1 -1
- package/dist/http-objects.d.ts +26 -0
- package/dist/http-objects.d.ts.map +1 -0
- package/dist/http-objects.js +588 -0
- package/dist/http-objects.js.map +1 -0
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/jwt-auth.d.ts +11 -0
- package/dist/jwt-auth.d.ts.map +1 -1
- package/dist/jwt-auth.js +9 -9
- package/dist/jwt-auth.js.map +1 -1
- package/dist/middleware.js +2 -2
- package/dist/middleware.js.map +1 -1
- package/dist/mimetypes.json +882 -1
- package/dist/misc.d.ts +161 -25
- package/dist/misc.d.ts.map +1 -1
- package/dist/misc.js +228 -80
- package/dist/misc.js.map +1 -1
- package/dist/openapi.d.ts +156 -13
- package/dist/openapi.d.ts.map +1 -1
- package/dist/openapi.js +214 -71
- package/dist/openapi.js.map +1 -1
- package/dist/router-types.d.ts +760 -0
- package/dist/router-types.d.ts.map +1 -0
- package/dist/router-types.js +23 -0
- package/dist/router-types.js.map +1 -0
- package/dist/router.d.ts +7 -530
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +128 -375
- package/dist/router.js.map +1 -1
- package/dist/static.d.ts +2 -2
- package/dist/static.d.ts.map +1 -1
- package/dist/static.js +77 -22
- package/dist/static.js.map +1 -1
- package/docs/THREAT_MODEL.md +52 -0
- package/docs/api-builder-v2-design.md +644 -0
- package/docs/api-builder-v3-design.md +397 -0
- package/docs/api-builder.md +454 -0
- package/docs/benchmark.md +27 -0
- package/docs/body-parsing.md +223 -0
- package/docs/errors.md +359 -0
- package/docs/expediate.png +0 -0
- package/docs/git.md +139 -0
- package/docs/jwt-auth.md +251 -0
- package/docs/logo.svg +12 -0
- package/docs/middleware.md +264 -0
- package/docs/openapi.md +180 -0
- package/docs/router.md +356 -0
- package/docs/static.md +128 -0
- package/docs/wiki.json +123 -0
- package/package.json +30 -8
- package/dist/cjs/apis.js +0 -327
- package/dist/cjs/git.js +0 -293
- package/dist/cjs/jwt-auth.js +0 -532
- package/dist/cjs/middleware.js +0 -511
- package/dist/cjs/mimetypes.json +0 -1
- package/dist/cjs/misc.js +0 -787
- package/dist/cjs/openapi.js +0 -485
- package/dist/cjs/router.js +0 -898
- package/dist/cjs/static.js +0 -669
package/docs/wiki.json
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "expediate",
|
|
3
|
+
"title": "Expediate — Wiki",
|
|
4
|
+
"host": "expediate.axfab.net",
|
|
5
|
+
"npm": "expediate",
|
|
6
|
+
"github": "axfab/expediate",
|
|
7
|
+
"image": "img/expediate.png",
|
|
8
|
+
"colorHue": 55,
|
|
9
|
+
"top": [
|
|
10
|
+
{
|
|
11
|
+
"id": "index.html",
|
|
12
|
+
"label": "Home",
|
|
13
|
+
"src": "README.md",
|
|
14
|
+
"icon": "<path d=\"M8 1a7 7 0 100 14A7 7 0 008 1zM7 4h2v2H7V4zm0 3h2v5H7V7z\"/>",
|
|
15
|
+
"type": "SoftwareApplication",
|
|
16
|
+
"title": "Expediate — Routing framework for Node.js",
|
|
17
|
+
"description": "A lightweight, zero-dependency TypeScript HTTP routing framework for Node.js."
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"docs": [
|
|
21
|
+
{
|
|
22
|
+
"id": "api-builder.html",
|
|
23
|
+
"label": "API Builder",
|
|
24
|
+
"src": "docs/api-builder.md",
|
|
25
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
26
|
+
"type": "TechArticle",
|
|
27
|
+
"title": "API Builder — Expediate",
|
|
28
|
+
"description": ""
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"id": "body-parsing.html",
|
|
32
|
+
"label": "Body request parsing",
|
|
33
|
+
"src": "docs/body-parsing.md",
|
|
34
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
35
|
+
"type": "TechArticle",
|
|
36
|
+
"title": "Body parsing — Expediate",
|
|
37
|
+
"description": ""
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"id": "errors.html",
|
|
41
|
+
"label": "Error handling",
|
|
42
|
+
"src": "docs/errors.md",
|
|
43
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
44
|
+
"type": "TechArticle",
|
|
45
|
+
"title": "Error handling — Expediate",
|
|
46
|
+
"description": ""
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"id": "git.html",
|
|
50
|
+
"label": "Git by http",
|
|
51
|
+
"src": "docs/git.md",
|
|
52
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
53
|
+
"type": "TechArticle",
|
|
54
|
+
"title": "Git-http — Expediate",
|
|
55
|
+
"description": ""
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"id": "jwt-auth.html",
|
|
59
|
+
"label": "JWT auth",
|
|
60
|
+
"src": "docs/jwt-auth.md",
|
|
61
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
62
|
+
"type": "TechArticle",
|
|
63
|
+
"title": "JWT auth — Expediate",
|
|
64
|
+
"description": ""
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"id": "middleware.html",
|
|
68
|
+
"label": "Middleware",
|
|
69
|
+
"src": "docs/middleware.md",
|
|
70
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
71
|
+
"type": "TechArticle",
|
|
72
|
+
"title": "Middleware — Expediate",
|
|
73
|
+
"description": ""
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"id": "router.html",
|
|
77
|
+
"label": "Router",
|
|
78
|
+
"src": "docs/router.md",
|
|
79
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
80
|
+
"type": "TechArticle",
|
|
81
|
+
"title": "Router — Expediate",
|
|
82
|
+
"description": ""
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
"id": "static.html",
|
|
86
|
+
"label": "Static",
|
|
87
|
+
"src": "docs/static.md",
|
|
88
|
+
"icon": "<path d=\"M2 2h4v4H2V2zm0 8h4v4H2v-4zm8-8h4v4h-4V2zm0 8h4v4h-4v-4z\"/>",
|
|
89
|
+
"type": "TechArticle",
|
|
90
|
+
"title": "Static — Expediate",
|
|
91
|
+
"description": ""
|
|
92
|
+
}
|
|
93
|
+
],
|
|
94
|
+
"bottom": [
|
|
95
|
+
{
|
|
96
|
+
"id": "license.html",
|
|
97
|
+
"label": "License",
|
|
98
|
+
"src": "LICENSE",
|
|
99
|
+
"icon": "<path d=\"M8 0a8 8 0 100 16A8 8 0 008 0zM4.5 7.5h7v1h-7v-1z\"/>",
|
|
100
|
+
"type": "WebPage",
|
|
101
|
+
"title": "MIT License — Expediate",
|
|
102
|
+
"description": "Expediate is released under the MIT License — free to use, modify, and distribute."
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"id": "contributing.html",
|
|
106
|
+
"label": "Contributing",
|
|
107
|
+
"src": "CONTRIBUTING.md",
|
|
108
|
+
"icon": "<path d=\"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38v-1.33c-2.23.48-2.7-1.07-2.7-1.07-.36-.92-.88-1.17-.88-1.17-.72-.49.05-.48.05-.48.8.06 1.22.82 1.22.82.7 1.2 1.85.86 2.3.65.07-.51.27-.86.5-1.06-1.78-.2-3.65-.89-3.65-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.67 7.67 0 012 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0016 8c0-4.42-3.58-8-8-8z\"/>",
|
|
109
|
+
"type": "WebPage",
|
|
110
|
+
"title": "Contributing — Expediate",
|
|
111
|
+
"description": "How to contribute to expediate: local setup, coding standards, and pull request guidelines."
|
|
112
|
+
}
|
|
113
|
+
],
|
|
114
|
+
"extra": [
|
|
115
|
+
{
|
|
116
|
+
"id": "claude.html",
|
|
117
|
+
"label": "Claude instructions",
|
|
118
|
+
"src": "CLAUDE.md",
|
|
119
|
+
"title": "Claude instructions — Expediate",
|
|
120
|
+
"description": "Documentation for the npm expediate package"
|
|
121
|
+
}
|
|
122
|
+
]
|
|
123
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "expediate",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "Web framework to create complete HTTP server.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/cjs/index.js",
|
|
7
7
|
"module": "dist/index.js",
|
|
8
8
|
"types": "dist/index.d.ts",
|
|
9
9
|
"files": [
|
|
10
|
-
"dist",
|
|
10
|
+
"dist/",
|
|
11
|
+
"docs/",
|
|
12
|
+
"CHANGELOG.md",
|
|
13
|
+
"CONTRIBUTING.md",
|
|
11
14
|
"LICENSE",
|
|
12
15
|
"README.md"
|
|
13
16
|
],
|
|
@@ -34,9 +37,22 @@
|
|
|
34
37
|
],
|
|
35
38
|
"scripts": {
|
|
36
39
|
"clean": "node -e \"require('fs').rmSync('dist', {recursive:true,force:true})\"",
|
|
37
|
-
"build": "
|
|
38
|
-
"
|
|
40
|
+
"build": "npm run build:esm && npm run build:cjs",
|
|
41
|
+
"build:esm": "tsc",
|
|
42
|
+
"build:cjs": "node scripts/build-cjs.cjs",
|
|
43
|
+
"test": "node --import tsx --test 'tests/*.test.ts'",
|
|
44
|
+
"test:coverage": "node --import tsx --test --experimental-test-coverage --test-coverage-exclude='tests/**' 'tests/*.test.ts'",
|
|
45
|
+
"fuzz": "node --import tsx --test 'tests/*.fuzz.test.ts'",
|
|
46
|
+
"bench": "npm run bench --workspace benchmarks",
|
|
47
|
+
"bench:check": "npm run bench:check --workspace benchmarks",
|
|
48
|
+
"lint": "eslint .",
|
|
49
|
+
"lint:fix": "eslint . --fix",
|
|
50
|
+
"prepack": "npm run lint && npm run test && npm run build"
|
|
39
51
|
},
|
|
52
|
+
"workspaces": [
|
|
53
|
+
"benchmarks",
|
|
54
|
+
"loadtest"
|
|
55
|
+
],
|
|
40
56
|
"homepage": "https://expediate.axfab.net/",
|
|
41
57
|
"repository": {
|
|
42
58
|
"type": "git",
|
|
@@ -45,11 +61,17 @@
|
|
|
45
61
|
"author": "Fabien Bavent <fabien.bavent@gmail.com>",
|
|
46
62
|
"contributors": [],
|
|
47
63
|
"license": "MIT",
|
|
48
|
-
"dependencies": {},
|
|
49
64
|
"devDependencies": {
|
|
50
|
-
"@
|
|
51
|
-
"
|
|
65
|
+
"@eslint/js": "^10.0.1",
|
|
66
|
+
"@types/node": "^25.9.4",
|
|
67
|
+
"esbuild": "^0.28.1",
|
|
68
|
+
"eslint": "^10.5.0",
|
|
69
|
+
"fast-check": "^3.23.0",
|
|
70
|
+
"tsx": "^4.21.0",
|
|
52
71
|
"typescript": "^5.9.3",
|
|
53
|
-
"
|
|
72
|
+
"typescript-eslint": "^8.61.1"
|
|
73
|
+
},
|
|
74
|
+
"engines": {
|
|
75
|
+
"node": ">=18.20.0"
|
|
54
76
|
}
|
|
55
77
|
}
|
package/dist/cjs/apis.js
DELETED
|
@@ -1,327 +0,0 @@
|
|
|
1
|
-
/* Copyright 2021 Fabien Bavent
|
|
2
|
-
*
|
|
3
|
-
* Permission is hereby granted, free of charge, to any person obtaining a
|
|
4
|
-
* copy of this software and associated documentation files (the "Software"),
|
|
5
|
-
* to deal in the Software without restriction, including without limitation
|
|
6
|
-
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
7
|
-
* and/or sell copies of the Software, and to permit persons to whom the
|
|
8
|
-
* Software is furnished to do so, subject to the following conditions:
|
|
9
|
-
*
|
|
10
|
-
* The above copyright notice and this permission notice shall be included
|
|
11
|
-
* in all copies or substantial portions of the Software.
|
|
12
|
-
*
|
|
13
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
14
|
-
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
-
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
|
16
|
-
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
-
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
18
|
-
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
19
|
-
* DEALINGS IN THE SOFTWARE.
|
|
20
|
-
*/
|
|
21
|
-
'use strict';
|
|
22
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
-
exports.apiBuilder = apiBuilder;
|
|
24
|
-
const router_js_1 = require("./router.js");
|
|
25
|
-
const openapi_js_1 = require("./openapi.js");
|
|
26
|
-
// ---------------------------------------------------------------------------
|
|
27
|
-
// Internal helpers
|
|
28
|
-
// ---------------------------------------------------------------------------
|
|
29
|
-
/**
|
|
30
|
-
* Instantiate a new service module for the given scope `key` and await its
|
|
31
|
-
* setup lifecycle hook.
|
|
32
|
-
*
|
|
33
|
-
* The lifecycle is:
|
|
34
|
-
* 1. **`data(key)`** — create the initial data object (`Partial<TInstance>`);
|
|
35
|
-
* methods are mixed in next to complete the shape.
|
|
36
|
-
* 2. **Mix in methods** — each entry in `service.methods` is copied onto the
|
|
37
|
-
* instance as a regular function bound to `this = instance`.
|
|
38
|
-
* 3. **`await setup()`** — if `setup` returns a `Promise`, it is fully
|
|
39
|
-
* awaited before the instance is returned. Any rejection propagates to
|
|
40
|
-
* the caller.
|
|
41
|
-
*
|
|
42
|
-
* @param service - The service definition.
|
|
43
|
-
* @param key - The scope key (`'singleton'`, `null`, or a session ID).
|
|
44
|
-
* @returns A Promise resolving to a fully initialised service instance.
|
|
45
|
-
*/
|
|
46
|
-
async function buildModule(service, key) {
|
|
47
|
-
// `data()` returns Partial<TInstance>; methods are mixed in below to complete
|
|
48
|
-
// the instance shape. The cast is intentional and safe — by the time this
|
|
49
|
-
// function returns the instance IS a full TInstance.
|
|
50
|
-
const instance = service.data
|
|
51
|
-
? service.data(key)
|
|
52
|
-
: { $key: key };
|
|
53
|
-
// Mix service methods into the instance, bound to `this = instance`.
|
|
54
|
-
// Regular function expressions are used (not arrow functions) so that each
|
|
55
|
-
// method has its own `arguments` object and `this` binding works correctly.
|
|
56
|
-
if (service.methods) {
|
|
57
|
-
for (const methodName of Object.keys(service.methods)) {
|
|
58
|
-
const method = service.methods[methodName];
|
|
59
|
-
instance[methodName] = function (...args) {
|
|
60
|
-
return method.apply(instance, args);
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
// Await setup so that async initialisation (DB connections, config fetches,
|
|
65
|
-
// etc.) completes before the instance is considered ready.
|
|
66
|
-
if (service.setup)
|
|
67
|
-
await service.setup.apply(instance, []);
|
|
68
|
-
return instance;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Resolve the correct service instance for an incoming request.
|
|
72
|
-
*
|
|
73
|
-
* Instance lifecycle by scope:
|
|
74
|
-
* - **Singleton** (`scope` absent): always returns `modules['singleton']`.
|
|
75
|
-
* The singleton is guaranteed to be fully initialised before routes run,
|
|
76
|
-
* so this path is synchronous within the async wrapper.
|
|
77
|
-
* - **Keyed** (`scope` returns a string): look up `modules[key]`; on first
|
|
78
|
-
* access, build and cache the instance (in-flight builds for the same key
|
|
79
|
-
* are deduplicated via `building` to avoid concurrent double-builds).
|
|
80
|
-
* - **Ephemeral** (`scope` returns `null`): create a fresh, uncached instance
|
|
81
|
-
* for every request.
|
|
82
|
-
*
|
|
83
|
-
* @param service - The service definition.
|
|
84
|
-
* @param modules - The resolved-instance cache (mutated on first keyed access).
|
|
85
|
-
* @param building - In-flight build-promise cache; prevents duplicate builds
|
|
86
|
-
* for the same key under concurrent requests.
|
|
87
|
-
* @param req - The incoming request.
|
|
88
|
-
* @returns A Promise resolving to the service instance for this request.
|
|
89
|
-
*/
|
|
90
|
-
async function resolveInstance(service, modules, building, req) {
|
|
91
|
-
if (typeof service.scope !== 'function') {
|
|
92
|
-
// Singleton — routes only run after setup is complete, so this is safe.
|
|
93
|
-
return modules['singleton'];
|
|
94
|
-
}
|
|
95
|
-
const key = service.scope(req);
|
|
96
|
-
if (key === null) {
|
|
97
|
-
// Ephemeral — create a fresh, uncached instance for every request.
|
|
98
|
-
return buildModule(service, null);
|
|
99
|
-
}
|
|
100
|
-
// Keyed — retrieve from resolved cache or initiate (and deduplicate) a build.
|
|
101
|
-
if (modules[key])
|
|
102
|
-
return modules[key];
|
|
103
|
-
if (!building[key]) {
|
|
104
|
-
building[key] = buildModule(service, key).then(instance => {
|
|
105
|
-
modules[key] = instance;
|
|
106
|
-
delete building[key];
|
|
107
|
-
return instance;
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
return building[key];
|
|
111
|
-
}
|
|
112
|
-
// ---------------------------------------------------------------------------
|
|
113
|
-
// Response helpers
|
|
114
|
-
// ---------------------------------------------------------------------------
|
|
115
|
-
/**
|
|
116
|
-
* Send a JSON response with the appropriate `Content-Type` header.
|
|
117
|
-
*
|
|
118
|
-
* @param res - The outgoing response.
|
|
119
|
-
* @param data - Any JSON-serialisable value.
|
|
120
|
-
*/
|
|
121
|
-
function sendJson(res, data) {
|
|
122
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
123
|
-
res.send(JSON.stringify(data));
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Translate a caught error (thrown or rejected by a service method) into an
|
|
127
|
-
* HTTP error response.
|
|
128
|
-
*
|
|
129
|
-
* Expected shape: `{ status?, data?, message? }` (see {@link ApiError}).
|
|
130
|
-
* Any other thrown value is treated as an opaque 500 Internal Server Error.
|
|
131
|
-
*
|
|
132
|
-
* @param res - The outgoing response.
|
|
133
|
-
* @param err - The caught value.
|
|
134
|
-
*/
|
|
135
|
-
function sendError(res, err) {
|
|
136
|
-
const e = err;
|
|
137
|
-
const status = e?.status ?? 500;
|
|
138
|
-
if (e?.data !== undefined) {
|
|
139
|
-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
140
|
-
res.status(status).send(JSON.stringify(e.data));
|
|
141
|
-
}
|
|
142
|
-
else {
|
|
143
|
-
res.status(status).send(e?.message ?? 'Internal error');
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
// ---------------------------------------------------------------------------
|
|
147
|
-
// Public API
|
|
148
|
-
// ---------------------------------------------------------------------------
|
|
149
|
-
/**
|
|
150
|
-
* Build an Express-compatible router from a service definition object.
|
|
151
|
-
*
|
|
152
|
-
* The returned router is suitable for mounting via `app.use()`:
|
|
153
|
-
*
|
|
154
|
-
* ```ts
|
|
155
|
-
* import myService from './my-service.js';
|
|
156
|
-
*
|
|
157
|
-
* app.use('/api', apiBuilder(myService));
|
|
158
|
-
* ```
|
|
159
|
-
*
|
|
160
|
-
* **Singleton setup lifecycle:**
|
|
161
|
-
* When `service.scope` is absent the service is a singleton. The framework
|
|
162
|
-
* pre-builds the instance eagerly and registers a **503 Service not ready**
|
|
163
|
-
* guard middleware on the router immediately. Route handlers are registered
|
|
164
|
-
* only once `setup()` resolves (or immediately, for sync setup). Any request
|
|
165
|
-
* that arrives before setup completes receives a 503 response.
|
|
166
|
-
*
|
|
167
|
-
* **Keyed / ephemeral setup lifecycle:**
|
|
168
|
-
* Route handlers are registered immediately. For each request,
|
|
169
|
-
* `resolveInstance()` is awaited inside the handler, so `setup()` is always
|
|
170
|
-
* complete before the service method is invoked.
|
|
171
|
-
*
|
|
172
|
-
* **Route handlers** declared in `service.GET`, `service.POST`, etc. are
|
|
173
|
-
* called with `this` bound to the service instance. They receive two
|
|
174
|
-
* arguments:
|
|
175
|
-
* 1. `params` — merged route + query-string parameters from `req.params`.
|
|
176
|
-
* 2. `body` — the parsed request body from `req.body` (requires a
|
|
177
|
-
* body-parsing middleware such as `json()` to run first).
|
|
178
|
-
*
|
|
179
|
-
* **Return values:**
|
|
180
|
-
* - A **truthy value** (or a `Promise` resolving to one) → serialised as JSON
|
|
181
|
-
* with status `200 OK`.
|
|
182
|
-
* - A **falsy value** (`undefined`, `null`, `false`, `0`, `''`) or a
|
|
183
|
-
* `Promise` resolving to one → `201 No Content` (useful for mutations).
|
|
184
|
-
*
|
|
185
|
-
* **Error handling:**
|
|
186
|
-
* - Throwing or rejecting with `{ status, message }` sends the
|
|
187
|
-
* corresponding HTTP error.
|
|
188
|
-
* - Throwing or rejecting with `{ status, data }` sends the `data` object
|
|
189
|
-
* as a JSON body.
|
|
190
|
-
* - Any other thrown value produces `500 Internal Server Error`.
|
|
191
|
-
*
|
|
192
|
-
* @param service - The service definition (see {@link ServiceDefinition}).
|
|
193
|
-
* @returns A router instance pre-configured with all declared routes.
|
|
194
|
-
*/
|
|
195
|
-
function apiBuilder(service) {
|
|
196
|
-
const api = (0, router_js_1.default)();
|
|
197
|
-
/** Resolved instance cache: populated once setup completes for a given key. */
|
|
198
|
-
const modules = {};
|
|
199
|
-
/** In-flight build promises: deduplicates concurrent keyed instance builds. */
|
|
200
|
-
const building = {};
|
|
201
|
-
/**
|
|
202
|
-
* Register all route handlers from a route map for a given HTTP method.
|
|
203
|
-
*
|
|
204
|
-
* Each handler:
|
|
205
|
-
* 1. Resolves the correct service instance (awaiting setup when needed).
|
|
206
|
-
* 2. Invokes the service method with `(params, body)`.
|
|
207
|
-
* 3. Sends the return value as JSON (or 201 if falsy).
|
|
208
|
-
* 4. Catches thrown / rejected {@link ApiError} objects and translates them
|
|
209
|
-
* into the appropriate HTTP error response.
|
|
210
|
-
*
|
|
211
|
-
* @param routeMap - Map of path patterns to service methods (`undefined` = skip).
|
|
212
|
-
* @param register - Registers a handler on the router for the current HTTP method.
|
|
213
|
-
*/
|
|
214
|
-
function buildRoutes(routeMap, register) {
|
|
215
|
-
if (!routeMap)
|
|
216
|
-
return;
|
|
217
|
-
// Sort routes by decreasing specificity so that more precise patterns
|
|
218
|
-
// (more segments, fewer parameters) are registered first in the router.
|
|
219
|
-
// Without this, a plain path like '/items' would match '/items/1' as a
|
|
220
|
-
// prefix and steal requests intended for '/items/:id'.
|
|
221
|
-
// Specificity = (segment count * 100) - (parameter count * 10).
|
|
222
|
-
const sortedPaths = Object.keys(routeMap).sort((a, b) => {
|
|
223
|
-
const score = (p) => {
|
|
224
|
-
const segs = p.split('/').filter(s => s.length > 0);
|
|
225
|
-
return segs.length * 100 - segs.filter(s => s.startsWith(':')).length * 10;
|
|
226
|
-
};
|
|
227
|
-
return score(b) - score(a) || b.localeCompare(a);
|
|
228
|
-
});
|
|
229
|
-
for (const path of sortedPaths) {
|
|
230
|
-
const method = routeMap[path];
|
|
231
|
-
register(path, (req, res) => {
|
|
232
|
-
const params = req.params;
|
|
233
|
-
const body = req.body;
|
|
234
|
-
// Await instance resolution (no-op microtask for singletons; may
|
|
235
|
-
// trigger async buildModule for keyed / ephemeral instances).
|
|
236
|
-
resolveInstance(service, modules, building, req)
|
|
237
|
-
.then(instance => {
|
|
238
|
-
const ret = method.apply(instance, [params, body]);
|
|
239
|
-
if (ret instanceof Promise) {
|
|
240
|
-
return ret
|
|
241
|
-
.then(val => {
|
|
242
|
-
if (val !== undefined && val !== null && val !== false && val !== 0 && val !== '')
|
|
243
|
-
sendJson(res, val);
|
|
244
|
-
else
|
|
245
|
-
res.status(201).end();
|
|
246
|
-
})
|
|
247
|
-
.catch(err => sendError(res, err));
|
|
248
|
-
}
|
|
249
|
-
if (ret !== undefined && ret !== null && ret !== false && ret !== 0 && ret !== '')
|
|
250
|
-
sendJson(res, ret);
|
|
251
|
-
else
|
|
252
|
-
res.status(201).end();
|
|
253
|
-
})
|
|
254
|
-
.catch(err => sendError(res, err));
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
/** Convenience wrapper to register routes for all five HTTP verbs. */
|
|
259
|
-
function registerAllRoutes() {
|
|
260
|
-
buildRoutes(service.GET, (path, h) => api.get(path, h));
|
|
261
|
-
buildRoutes(service.POST, (path, h) => api.post(path, h));
|
|
262
|
-
buildRoutes(service.PUT, (path, h) => api.put(path, h));
|
|
263
|
-
buildRoutes(service.DELETE, (path, h) => api.delete(path, h));
|
|
264
|
-
buildRoutes(service.PATCH, (path, h) => api.patch(path, h));
|
|
265
|
-
}
|
|
266
|
-
if (typeof service.scope !== 'function') {
|
|
267
|
-
// ── Singleton ─────────────────────────────────────────────────────────
|
|
268
|
-
// Register a "not ready" guard first so that requests arriving while
|
|
269
|
-
// setup is in progress receive 503 rather than 404.
|
|
270
|
-
let ready = false;
|
|
271
|
-
api.use('/', (_req, res, next) => {
|
|
272
|
-
if (!ready) {
|
|
273
|
-
res.statusCode = 503;
|
|
274
|
-
res.end('Service not ready');
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
next();
|
|
278
|
-
});
|
|
279
|
-
// Build the singleton asynchronously, then flip the guard and register
|
|
280
|
-
// routes. Even for synchronous setup() functions, buildModule() is async
|
|
281
|
-
// (it uses await internally), so route registration happens in a microtask
|
|
282
|
-
// that runs before any I/O callbacks — routes are always in place by the
|
|
283
|
-
// time the first HTTP request can be processed.
|
|
284
|
-
buildModule(service, 'singleton')
|
|
285
|
-
.then(instance => {
|
|
286
|
-
modules['singleton'] = instance;
|
|
287
|
-
ready = true;
|
|
288
|
-
registerAllRoutes();
|
|
289
|
-
})
|
|
290
|
-
.catch(err => {
|
|
291
|
-
// setup() rejected — log the error; the guard permanently returns 503.
|
|
292
|
-
console.error('[apiBuilder] singleton setup() rejected:', err);
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
// ── Keyed / ephemeral ─────────────────────────────────────────────────
|
|
297
|
-
// Register routes immediately. Each handler awaits resolveInstance(),
|
|
298
|
-
// which in turn awaits buildModule() for first-time keyed instances.
|
|
299
|
-
registerAllRoutes();
|
|
300
|
-
}
|
|
301
|
-
// ── OpenAPI introspection ──────────────────────────────────────────────────
|
|
302
|
-
/**
|
|
303
|
-
* Generate an OpenAPI 3.1.0 document from the service definition.
|
|
304
|
-
* Delegates to {@link openApiSpec} from `openapi.ts`.
|
|
305
|
-
*/
|
|
306
|
-
api.spec = function (opts) {
|
|
307
|
-
return (0, openapi_js_1.openApiSpec)(service, opts);
|
|
308
|
-
};
|
|
309
|
-
/**
|
|
310
|
-
* Return a middleware handler that serves the OpenAPI spec as JSON or YAML.
|
|
311
|
-
* The spec is generated once and cached on the first call to the returned handler.
|
|
312
|
-
*/
|
|
313
|
-
api.specHandler = function (opts, format = 'json') {
|
|
314
|
-
let cached = null;
|
|
315
|
-
const contentType = format === 'yaml'
|
|
316
|
-
? 'application/yaml; charset=utf-8'
|
|
317
|
-
: 'application/json; charset=utf-8';
|
|
318
|
-
return function (_req, res) {
|
|
319
|
-
if (!cached)
|
|
320
|
-
cached = (0, openapi_js_1.serializeSpec)((0, openapi_js_1.openApiSpec)(service, opts), format);
|
|
321
|
-
res.setHeader('Content-Type', contentType);
|
|
322
|
-
res.end(cached);
|
|
323
|
-
};
|
|
324
|
-
};
|
|
325
|
-
return api;
|
|
326
|
-
}
|
|
327
|
-
exports.default = apiBuilder;
|