@tymber/common 0.0.1-alpha.0 → 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 +22 -0
- package/README.md +46 -0
- package/dist/App.d.ts +17 -0
- package/dist/App.js +236 -0
- package/dist/Component.d.ts +16 -0
- package/dist/Component.js +116 -0
- package/dist/ConfigService.d.ts +31 -0
- package/dist/ConfigService.js +75 -0
- package/dist/Context.d.ts +41 -0
- package/dist/Context.js +10 -0
- package/dist/DB.d.ts +15 -0
- package/dist/DB.js +7 -0
- package/dist/Endpoint.d.ts +21 -0
- package/dist/Endpoint.js +87 -0
- package/dist/EventEmitter.d.ts +9 -0
- package/dist/EventEmitter.js +21 -0
- package/dist/Handler.d.ts +8 -0
- package/dist/Handler.js +8 -0
- package/dist/HttpContext.d.ts +26 -0
- package/dist/HttpContext.js +11 -0
- package/dist/I18nService.d.ts +18 -0
- package/dist/I18nService.js +72 -0
- package/dist/Middleware.d.ts +6 -0
- package/dist/Middleware.js +4 -0
- package/dist/Module.d.ts +47 -0
- package/dist/Module.js +12 -0
- package/dist/PubSubService.d.ts +20 -0
- package/dist/PubSubService.js +60 -0
- package/dist/Repository.d.ts +29 -0
- package/dist/Repository.js +110 -0
- package/dist/Router.d.ts +10 -0
- package/dist/Router.js +53 -0
- package/dist/TemplateService.d.ts +22 -0
- package/dist/TemplateService.js +66 -0
- package/dist/View.d.ts +17 -0
- package/dist/View.js +48 -0
- package/dist/ViewRenderer.d.ts +16 -0
- package/dist/ViewRenderer.js +59 -0
- package/dist/contrib/accept-language-parser.d.ts +9 -0
- package/dist/contrib/accept-language-parser.js +73 -0
- package/dist/contrib/cookie.d.ts +33 -0
- package/dist/contrib/cookie.js +207 -0
- package/dist/contrib/template.d.ts +1 -0
- package/dist/contrib/template.js +107 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +32 -0
- package/dist/utils/ajv.d.ts +2 -0
- package/dist/utils/ajv.js +10 -0
- package/dist/utils/camelToSnakeCase.d.ts +1 -0
- package/dist/utils/camelToSnakeCase.js +3 -0
- package/dist/utils/computeBaseUrl.d.ts +1 -0
- package/dist/utils/computeBaseUrl.js +37 -0
- package/dist/utils/computeContentType.d.ts +1 -0
- package/dist/utils/computeContentType.js +17 -0
- package/dist/utils/createDebug.d.ts +1 -0
- package/dist/utils/createDebug.js +4 -0
- package/dist/utils/createTestApp.d.ts +8 -0
- package/dist/utils/createTestApp.js +57 -0
- package/dist/utils/escapeValue.d.ts +1 -0
- package/dist/utils/escapeValue.js +3 -0
- package/dist/utils/fs.d.ts +6 -0
- package/dist/utils/fs.js +13 -0
- package/dist/utils/isAdmin.d.ts +2 -0
- package/dist/utils/isAdmin.js +4 -0
- package/dist/utils/isProduction.d.ts +1 -0
- package/dist/utils/isProduction.js +1 -0
- package/dist/utils/loadModules.d.ts +3 -0
- package/dist/utils/loadModules.js +83 -0
- package/dist/utils/randomId.d.ts +1 -0
- package/dist/utils/randomId.js +4 -0
- package/dist/utils/randomUUID.d.ts +1 -0
- package/dist/utils/randomUUID.js +4 -0
- package/dist/utils/runMigrations.d.ts +3 -0
- package/dist/utils/runMigrations.js +85 -0
- package/dist/utils/snakeToCamelCase.d.ts +1 -0
- package/dist/utils/snakeToCamelCase.js +3 -0
- package/dist/utils/sortBy.d.ts +1 -0
- package/dist/utils/sortBy.js +8 -0
- package/dist/utils/sql.d.ts +120 -0
- package/dist/utils/sql.js +433 -0
- package/dist/utils/toNodeHandler.d.ts +2 -0
- package/dist/utils/toNodeHandler.js +91 -0
- package/dist/utils/types.d.ts +3 -0
- package/dist/utils/types.js +1 -0
- package/dist/utils/waitFor.d.ts +1 -0
- package/dist/utils/waitFor.js +5 -0
- package/package.json +33 -2
- package/src/App.ts +319 -0
- package/src/Component.ts +166 -0
- package/src/ConfigService.ts +121 -0
- package/src/Context.ts +60 -0
- package/src/DB.ts +28 -0
- package/src/Endpoint.ts +118 -0
- package/src/EventEmitter.ts +32 -0
- package/src/Handler.ts +14 -0
- package/src/HttpContext.ts +35 -0
- package/src/I18nService.ts +96 -0
- package/src/Middleware.ts +10 -0
- package/src/Module.ts +60 -0
- package/src/PubSubService.ts +77 -0
- package/src/Repository.ts +158 -0
- package/src/Router.ts +77 -0
- package/src/TemplateService.ts +97 -0
- package/src/View.ts +60 -0
- package/src/ViewRenderer.ts +71 -0
- package/src/contrib/accept-language-parser.ts +94 -0
- package/src/contrib/cookie.ts +256 -0
- package/src/contrib/template.ts +134 -0
- package/src/index.ts +54 -0
- package/src/utils/ajv.ts +13 -0
- package/src/utils/camelToSnakeCase.ts +3 -0
- package/src/utils/computeBaseUrl.ts +46 -0
- package/src/utils/computeContentType.ts +17 -0
- package/src/utils/createDebug.ts +5 -0
- package/src/utils/createTestApp.ts +84 -0
- package/src/utils/escapeValue.ts +3 -0
- package/src/utils/fs.ts +15 -0
- package/src/utils/isAdmin.ts +5 -0
- package/src/utils/isProduction.ts +2 -0
- package/src/utils/loadModules.ts +105 -0
- package/src/utils/randomId.ts +5 -0
- package/src/utils/randomUUID.ts +5 -0
- package/src/utils/runMigrations.ts +122 -0
- package/src/utils/snakeToCamelCase.ts +3 -0
- package/src/utils/sortBy.ts +8 -0
- package/src/utils/sql.ts +553 -0
- package/src/utils/toNodeHandler.ts +121 -0
- package/src/utils/types.ts +1 -0
- package/src/utils/waitFor.ts +5 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
(The MIT License)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present Damien ARRACHEQUESNE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
+
a copy of this software and associated documentation files (the
|
|
7
|
+
'Software'), to deal in the Software without restriction, including
|
|
8
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
+
the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be
|
|
14
|
+
included in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
19
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
20
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
21
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
22
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
<h1>Common module of the Tymber framework</h1>
|
|
2
|
+
|
|
3
|
+
The internals of the framework.
|
|
4
|
+
|
|
5
|
+
**Table of contents**
|
|
6
|
+
|
|
7
|
+
<!-- TOC -->
|
|
8
|
+
* [Installation](#installation)
|
|
9
|
+
* [Usage](#usage)
|
|
10
|
+
* [License](#license)
|
|
11
|
+
<!-- TOC -->
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
npm i @tymber/common
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import * as pg from "pg";
|
|
23
|
+
import { PostgresDB } from "@tymber/postgres";
|
|
24
|
+
import { App, toNodeHandler } from "@tymber/common";
|
|
25
|
+
import { CoreModule } from "@tymber/core";
|
|
26
|
+
import { createServer } from "node:http";
|
|
27
|
+
|
|
28
|
+
const pgPool = new pg.Pool({
|
|
29
|
+
user: "postgres",
|
|
30
|
+
password: "changeit",
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const db = new PostgresDB(pgPool);
|
|
34
|
+
|
|
35
|
+
const app = await App.create(db, [
|
|
36
|
+
CoreModule
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
const httpServer = createServer(toNodeHandler(app.fetch));
|
|
40
|
+
|
|
41
|
+
httpServer.listen(8080);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
|
|
46
|
+
[MIT](./LICENSE)
|
package/dist/App.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Module } from "./Module.js";
|
|
2
|
+
import { Component } from "./Component.js";
|
|
3
|
+
export declare class App {
|
|
4
|
+
private readonly assets;
|
|
5
|
+
private readonly viewRenderer;
|
|
6
|
+
private readonly router;
|
|
7
|
+
private readonly middlewares;
|
|
8
|
+
private constructor();
|
|
9
|
+
static create({ components, modules, }: {
|
|
10
|
+
components: Component[];
|
|
11
|
+
modules: Module[];
|
|
12
|
+
}): Promise<App>;
|
|
13
|
+
fetch(req: Request): Promise<Response>;
|
|
14
|
+
private renderHttp404Error;
|
|
15
|
+
private renderHttp500Error;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
package/dist/App.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { Router } from "./Router.js";
|
|
2
|
+
import { ModuleDefinitions, } from "./Module.js";
|
|
3
|
+
import { Middleware } from "./Middleware.js";
|
|
4
|
+
import { parseCookieHeader } from "./contrib/cookie.js";
|
|
5
|
+
import { HttpRedirectCode } from "./HttpContext.js";
|
|
6
|
+
import { computeBaseUrl } from "./utils/computeBaseUrl.js";
|
|
7
|
+
import { ViewRenderer } from "./ViewRenderer.js";
|
|
8
|
+
import { computeContentType } from "./utils/computeContentType.js";
|
|
9
|
+
import { loadModules } from "./utils/loadModules.js";
|
|
10
|
+
import { BaseI18nService } from "./I18nService.js";
|
|
11
|
+
import { BaseTemplateService } from "./TemplateService.js";
|
|
12
|
+
import { runMigrations } from "./utils/runMigrations.js";
|
|
13
|
+
import { createDebug } from "./utils/createDebug.js";
|
|
14
|
+
import { DB } from "./DB.js";
|
|
15
|
+
import { isProduction } from "./utils/isProduction.js";
|
|
16
|
+
import { Component, ComponentFactory } from "./Component.js";
|
|
17
|
+
import { PubSubService } from "./PubSubService.js";
|
|
18
|
+
import { FS } from "./utils/fs.js";
|
|
19
|
+
import { EnvironmentBasedConfigService } from "./ConfigService.js";
|
|
20
|
+
import { snakeToCamelCase } from "./utils/snakeToCamelCase.js";
|
|
21
|
+
const debug = createDebug("App");
|
|
22
|
+
function createRouter(modules) {
|
|
23
|
+
const router = new Router();
|
|
24
|
+
for (const module of modules) {
|
|
25
|
+
for (const { method, path, handler } of module.endpoints) {
|
|
26
|
+
router.registerRoute(method, path, handler);
|
|
27
|
+
}
|
|
28
|
+
for (const { method, path, handler } of module.views) {
|
|
29
|
+
router.registerRoute(method, path, handler);
|
|
30
|
+
}
|
|
31
|
+
for (const { method, path, handler } of module.adminEndpoints) {
|
|
32
|
+
router.registerRoute(method, path, handler);
|
|
33
|
+
}
|
|
34
|
+
for (const { method, path, handler } of module.adminViews) {
|
|
35
|
+
router.registerRoute(method, path, handler);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return router;
|
|
39
|
+
}
|
|
40
|
+
function parseQueryParams(url) {
|
|
41
|
+
const query = Object.create(null);
|
|
42
|
+
url.searchParams.forEach((value, key) => {
|
|
43
|
+
query[snakeToCamelCase(key)] = value;
|
|
44
|
+
});
|
|
45
|
+
return query;
|
|
46
|
+
}
|
|
47
|
+
export class App {
|
|
48
|
+
assets;
|
|
49
|
+
viewRenderer;
|
|
50
|
+
router;
|
|
51
|
+
middlewares = [];
|
|
52
|
+
constructor(modules, assets, viewRenderer) {
|
|
53
|
+
this.assets = assets;
|
|
54
|
+
this.viewRenderer = viewRenderer;
|
|
55
|
+
this.router = createRouter(modules);
|
|
56
|
+
for (const module of modules) {
|
|
57
|
+
this.middlewares.push(...module.middlewares);
|
|
58
|
+
}
|
|
59
|
+
this.fetch = this.fetch.bind(this);
|
|
60
|
+
}
|
|
61
|
+
static async create({ components, modules, }) {
|
|
62
|
+
const db = components.find((c) => {
|
|
63
|
+
return c instanceof DB;
|
|
64
|
+
});
|
|
65
|
+
if (!db) {
|
|
66
|
+
throw new Error("no DB component found");
|
|
67
|
+
}
|
|
68
|
+
debug("starting app in %s mode", isProduction ? "production" : "development");
|
|
69
|
+
const componentFactory = new ComponentFactory();
|
|
70
|
+
let viewRenderer;
|
|
71
|
+
componentFactory.register(PubSubService);
|
|
72
|
+
componentFactory.register(EnvironmentBasedConfigService);
|
|
73
|
+
componentFactory.register(BaseI18nService);
|
|
74
|
+
componentFactory.register(BaseTemplateService);
|
|
75
|
+
componentFactory.register(ViewRenderer, (instance) => {
|
|
76
|
+
viewRenderer = instance;
|
|
77
|
+
});
|
|
78
|
+
debug("loading modules");
|
|
79
|
+
const moduleDefinitions = await loadModules(componentFactory, modules);
|
|
80
|
+
const allComponents = componentFactory.build(new ModuleDefinitions(moduleDefinitions), ...components);
|
|
81
|
+
debug("running migrations");
|
|
82
|
+
await runMigrations(db, moduleDefinitions);
|
|
83
|
+
debug("initializing all components");
|
|
84
|
+
await Promise.all(allComponents.map((component) => component.init()));
|
|
85
|
+
const assets = new Map();
|
|
86
|
+
for (const module of modules) {
|
|
87
|
+
if (!module.assetsDir) {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
for (const filename of await FS.readDirRecursively(FS.join(module.assetsDir, "static"))) {
|
|
92
|
+
assets.set("/static/" + filename, FS.join(module.assetsDir, "static", filename));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (e) { }
|
|
96
|
+
}
|
|
97
|
+
const app = new App(moduleDefinitions, assets, viewRenderer);
|
|
98
|
+
app.close = () => {
|
|
99
|
+
debug("closing all components");
|
|
100
|
+
return Promise.all(components.map((component) => component.close())).then();
|
|
101
|
+
};
|
|
102
|
+
return app;
|
|
103
|
+
}
|
|
104
|
+
async fetch(req) {
|
|
105
|
+
const url = new URL(req.url, "http://localhost");
|
|
106
|
+
const locale = this.viewRenderer.computeLocale(req);
|
|
107
|
+
const ctx = {
|
|
108
|
+
startedAt: new Date(),
|
|
109
|
+
method: req.method,
|
|
110
|
+
path: url.pathname,
|
|
111
|
+
query: parseQueryParams(url),
|
|
112
|
+
headers: req.headers,
|
|
113
|
+
cookies: parseCookieHeader(req.headers.get("cookie") || ""),
|
|
114
|
+
abortSignal: req.signal,
|
|
115
|
+
locale,
|
|
116
|
+
responseHeaders: new Headers(),
|
|
117
|
+
render: async (view, data = {}) => {
|
|
118
|
+
try {
|
|
119
|
+
return this.viewRenderer.render(ctx, view, data);
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
return this.renderHttp500Error(ctx, e);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
redirect(path, code = HttpRedirectCode.HTTP_302_FOUND) {
|
|
126
|
+
const baseUrl = computeBaseUrl(ctx.headers);
|
|
127
|
+
// note: `Response.redirect()` does not allow to specify additional headers
|
|
128
|
+
return new Response(null, {
|
|
129
|
+
status: code,
|
|
130
|
+
headers: {
|
|
131
|
+
Location: `${baseUrl}${path}`,
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
if (ctx.path.startsWith("/static")) {
|
|
137
|
+
if (!this.assets.has(ctx.path)) {
|
|
138
|
+
return this.renderHttp404Error(ctx);
|
|
139
|
+
}
|
|
140
|
+
const contentType = computeContentType(ctx.path);
|
|
141
|
+
const absolutePath = this.assets.get(ctx.path);
|
|
142
|
+
debug("serving %s with content type %s", ctx.path, contentType);
|
|
143
|
+
return new Response(FS.createReadStream(absolutePath), {
|
|
144
|
+
headers: {
|
|
145
|
+
"content-type": contentType,
|
|
146
|
+
"cache-control": isProduction
|
|
147
|
+
? "public, max-age=31536000, immutable"
|
|
148
|
+
: "no-cache",
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
// make a copy in case a middleware is removed
|
|
153
|
+
const middlewares = this.middlewares.slice();
|
|
154
|
+
for (const middleware of middlewares) {
|
|
155
|
+
try {
|
|
156
|
+
const httpRes = await middleware.handle(ctx);
|
|
157
|
+
if (httpRes) {
|
|
158
|
+
ctx.responseHeaders.forEach((value, key) => {
|
|
159
|
+
httpRes.headers.set(key, value);
|
|
160
|
+
});
|
|
161
|
+
return httpRes;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
return this.renderHttp500Error(ctx, e);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const route = this.router.findRoute(req.method, url.pathname);
|
|
169
|
+
if (!route) {
|
|
170
|
+
return this.renderHttp404Error(ctx);
|
|
171
|
+
}
|
|
172
|
+
ctx.pathParams = route.pathParams;
|
|
173
|
+
const contentType = req.headers.get("content-type");
|
|
174
|
+
if (contentType) {
|
|
175
|
+
if (contentType !== "application/json") {
|
|
176
|
+
// TODO support other content types
|
|
177
|
+
return Response.json({
|
|
178
|
+
message: "unsupported media type",
|
|
179
|
+
}, {
|
|
180
|
+
status: 415,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
ctx.payload = await req.json();
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return Response.json({
|
|
188
|
+
message: "invalid request body",
|
|
189
|
+
}, {
|
|
190
|
+
status: 400,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
const httpRes = await route.handler.doHandle(ctx);
|
|
196
|
+
ctx.responseHeaders.forEach((value, key) => {
|
|
197
|
+
httpRes.headers.set(key, value);
|
|
198
|
+
});
|
|
199
|
+
return httpRes;
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
return this.renderHttp500Error(ctx, e);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
renderHttp404Error(ctx) {
|
|
206
|
+
const acceptHeader = ctx.headers.get("accept");
|
|
207
|
+
if (acceptHeader?.includes("text/html")) {
|
|
208
|
+
return this.viewRenderer.render(ctx, "404");
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
return Response.json({
|
|
212
|
+
message: "resource not found",
|
|
213
|
+
}, {
|
|
214
|
+
status: 404,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
renderHttp500Error(ctx, error) {
|
|
219
|
+
const acceptHeader = ctx.headers.get("accept");
|
|
220
|
+
if (acceptHeader?.includes("text/html")) {
|
|
221
|
+
return this.viewRenderer.render(ctx, "500", {
|
|
222
|
+
error,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
return Response.json({
|
|
227
|
+
message: "an unexpected error occurred",
|
|
228
|
+
}, {
|
|
229
|
+
status: 500,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
close() {
|
|
234
|
+
return Promise.resolve();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const INJECT: unique symbol;
|
|
2
|
+
export type Ctor<T> = new (...args: any[]) => T;
|
|
3
|
+
type AbstractCtor<T> = abstract new (...args: any[]) => T;
|
|
4
|
+
type Dependency = Ctor<Component> | AbstractCtor<Component>;
|
|
5
|
+
export declare abstract class Component {
|
|
6
|
+
private __isComponent;
|
|
7
|
+
static [INJECT]: Dependency[];
|
|
8
|
+
init(): void | Promise<void>;
|
|
9
|
+
close(): void | Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export declare class ComponentFactory {
|
|
12
|
+
private readonly componentTree;
|
|
13
|
+
register<T extends Component>(ctor: Ctor<T>, onCreation?: (instance: T) => void): void;
|
|
14
|
+
build(...baseComponents: Component[]): Component[];
|
|
15
|
+
}
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {} from "./Context.js";
|
|
2
|
+
export const INJECT = Symbol("dependencies");
|
|
3
|
+
export class Component {
|
|
4
|
+
__isComponent; // nominal typing
|
|
5
|
+
static [INJECT] = [];
|
|
6
|
+
init() { }
|
|
7
|
+
close() { }
|
|
8
|
+
}
|
|
9
|
+
function isSubclass(subclass, superclass) {
|
|
10
|
+
return superclass.prototype.isPrototypeOf(subclass.prototype);
|
|
11
|
+
}
|
|
12
|
+
function customConstructor(ctor, onCreation) {
|
|
13
|
+
return class extends ctor {
|
|
14
|
+
constructor(...args) {
|
|
15
|
+
super(...args);
|
|
16
|
+
onCreation(this);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export class ComponentFactory {
|
|
21
|
+
componentTree = [];
|
|
22
|
+
register(ctor, onCreation) {
|
|
23
|
+
if (onCreation) {
|
|
24
|
+
ctor = customConstructor(ctor, onCreation);
|
|
25
|
+
}
|
|
26
|
+
let level = 0;
|
|
27
|
+
// find place in the tree
|
|
28
|
+
for (const node of this.componentTree) {
|
|
29
|
+
for (const dependency of node.dependencies) {
|
|
30
|
+
if (ctor === dependency || isSubclass(ctor, dependency)) {
|
|
31
|
+
level = Math.max(level, node.level + 1);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// move dependencies at the bottom
|
|
36
|
+
// @ts-expect-error
|
|
37
|
+
const dependencies = (ctor[INJECT] || []);
|
|
38
|
+
for (const node of this.componentTree) {
|
|
39
|
+
for (const dependency of dependencies) {
|
|
40
|
+
if (node.ctor === dependency || isSubclass(node.ctor, dependency)) {
|
|
41
|
+
node.level = Math.max(node.level, level + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
this.componentTree.push({
|
|
46
|
+
ctor,
|
|
47
|
+
dependencies,
|
|
48
|
+
level,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
build(...baseComponents) {
|
|
52
|
+
const components = [...baseComponents];
|
|
53
|
+
const proxyHandler = {
|
|
54
|
+
get(target, prop) {
|
|
55
|
+
const method = target[prop];
|
|
56
|
+
if (typeof method !== "function") {
|
|
57
|
+
return method;
|
|
58
|
+
}
|
|
59
|
+
return function (...args) {
|
|
60
|
+
const isTracingEnabled = args.length > 0 && args[0].tracing?.enabled;
|
|
61
|
+
if (!isTracingEnabled) {
|
|
62
|
+
return method.apply(target, args);
|
|
63
|
+
}
|
|
64
|
+
const ctx = args[0];
|
|
65
|
+
const span = {
|
|
66
|
+
component: target.constructor.name,
|
|
67
|
+
method: prop,
|
|
68
|
+
startedAt: Date.now(),
|
|
69
|
+
duration: -1,
|
|
70
|
+
isSuccess: false,
|
|
71
|
+
};
|
|
72
|
+
ctx.tracing?.spans.push(span);
|
|
73
|
+
function completeSpan() {
|
|
74
|
+
span.duration = Date.now() - span.startedAt;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const result = method.apply(target, args);
|
|
78
|
+
if (isPromise(result)) {
|
|
79
|
+
return result
|
|
80
|
+
.then((output) => {
|
|
81
|
+
span.isSuccess = true;
|
|
82
|
+
return output;
|
|
83
|
+
})
|
|
84
|
+
.finally(() => completeSpan());
|
|
85
|
+
}
|
|
86
|
+
span.isSuccess = true;
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
completeSpan();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
this.componentTree.sort((a, b) => b.level - a.level);
|
|
96
|
+
// TODO do not instantiate components that are not used in the tree
|
|
97
|
+
for (const node of this.componentTree) {
|
|
98
|
+
const deps = node.dependencies.map((ctor) => {
|
|
99
|
+
const availableDeps = components.filter((component) => component instanceof ctor);
|
|
100
|
+
if (availableDeps.length === 0) {
|
|
101
|
+
throw `unresolved dependency ${ctor.name} for ${node.ctor.name}`;
|
|
102
|
+
}
|
|
103
|
+
return availableDeps[availableDeps.length - 1];
|
|
104
|
+
});
|
|
105
|
+
const component = new node.ctor(...deps);
|
|
106
|
+
components.push(new Proxy(component, proxyHandler));
|
|
107
|
+
}
|
|
108
|
+
return components;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function isPromise(obj) {
|
|
112
|
+
return (!!obj &&
|
|
113
|
+
typeof obj === "object" &&
|
|
114
|
+
typeof obj.then === "function" &&
|
|
115
|
+
typeof obj.catch === "function");
|
|
116
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Component } from "./Component.js";
|
|
2
|
+
import { type Context } from "./Context.js";
|
|
3
|
+
type ConfigType = "string" | "string[]" | "number" | "boolean";
|
|
4
|
+
interface ConfigDefinition {
|
|
5
|
+
key: string;
|
|
6
|
+
type: ConfigType;
|
|
7
|
+
defaultValue?: any;
|
|
8
|
+
shouldObfuscate?: boolean;
|
|
9
|
+
}
|
|
10
|
+
interface ConfigDefinitionWithValue extends ConfigDefinition {
|
|
11
|
+
value: any;
|
|
12
|
+
}
|
|
13
|
+
type ConfigValues = Record<string, any>;
|
|
14
|
+
interface ConfigHandler {
|
|
15
|
+
configDefinitions: ConfigDefinition[];
|
|
16
|
+
handler: (config: ConfigValues) => void | Promise<void>;
|
|
17
|
+
previousConfigHash: string;
|
|
18
|
+
}
|
|
19
|
+
export declare abstract class ConfigService extends Component {
|
|
20
|
+
protected handlers: ConfigHandler[];
|
|
21
|
+
subscribe(configDefinitions: ConfigDefinition[], handler: (config: ConfigValues) => void | Promise<void>): void;
|
|
22
|
+
init(): Promise<void>;
|
|
23
|
+
protected notifyConsumers(ctx: Context): Promise<void>;
|
|
24
|
+
getDefinitions(): ConfigDefinition[];
|
|
25
|
+
getCurrentConfig(ctx: Context): Promise<ConfigDefinitionWithValue[]>;
|
|
26
|
+
protected abstract getCurrentValues(ctx: Context): Promise<ConfigValues>;
|
|
27
|
+
}
|
|
28
|
+
export declare class EnvironmentBasedConfigService extends ConfigService {
|
|
29
|
+
getCurrentValues(): Promise<Record<string, any>>;
|
|
30
|
+
}
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { hash } from "node:crypto";
|
|
2
|
+
import { Component } from "./Component.js";
|
|
3
|
+
import { emptyContext } from "./Context.js";
|
|
4
|
+
export class ConfigService extends Component {
|
|
5
|
+
handlers = [];
|
|
6
|
+
subscribe(configDefinitions, handler) {
|
|
7
|
+
this.handlers.push({
|
|
8
|
+
configDefinitions,
|
|
9
|
+
handler,
|
|
10
|
+
previousConfigHash: "",
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
init() {
|
|
14
|
+
return this.notifyConsumers(emptyContext());
|
|
15
|
+
}
|
|
16
|
+
async notifyConsumers(ctx) {
|
|
17
|
+
const values = await this.getCurrentValues(ctx);
|
|
18
|
+
for (const elem of this.handlers) {
|
|
19
|
+
const config = {};
|
|
20
|
+
for (const { key, defaultValue } of elem.configDefinitions) {
|
|
21
|
+
config[key] = values[key] || defaultValue;
|
|
22
|
+
}
|
|
23
|
+
const configHash = hash("sha256", JSON.stringify(config));
|
|
24
|
+
if (configHash !== elem.previousConfigHash) {
|
|
25
|
+
elem.previousConfigHash = configHash;
|
|
26
|
+
await elem.handler(config);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
getDefinitions() {
|
|
31
|
+
return this.handlers.flatMap((elem) => elem.configDefinitions);
|
|
32
|
+
}
|
|
33
|
+
async getCurrentConfig(ctx) {
|
|
34
|
+
const values = await this.getCurrentValues(ctx);
|
|
35
|
+
const config = [];
|
|
36
|
+
for (const handler of this.handlers) {
|
|
37
|
+
for (const { key, type, defaultValue, shouldObfuscate, } of handler.configDefinitions) {
|
|
38
|
+
config.push({
|
|
39
|
+
key,
|
|
40
|
+
type,
|
|
41
|
+
defaultValue,
|
|
42
|
+
value: values[key] ?? defaultValue,
|
|
43
|
+
shouldObfuscate,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return config;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function formatValue(type, value) {
|
|
51
|
+
switch (type) {
|
|
52
|
+
case "string":
|
|
53
|
+
return value;
|
|
54
|
+
case "string[]":
|
|
55
|
+
return value.split(",");
|
|
56
|
+
case "number":
|
|
57
|
+
return parseInt(value, 10);
|
|
58
|
+
case "boolean":
|
|
59
|
+
return value === "1";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export class EnvironmentBasedConfigService extends ConfigService {
|
|
63
|
+
getCurrentValues() {
|
|
64
|
+
const availableKeys = Object.keys(process.env);
|
|
65
|
+
const values = {};
|
|
66
|
+
for (const handler of this.handlers) {
|
|
67
|
+
for (const { key, type } of handler.configDefinitions) {
|
|
68
|
+
if (availableKeys.includes(key)) {
|
|
69
|
+
values[key] = formatValue(type, process.env[key] ?? "");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return Promise.resolve(values);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Brand } from "./utils/types.js";
|
|
2
|
+
export type InternalUserId = Brand<bigint, "InternalUserId">;
|
|
3
|
+
export type UserId = Brand<string, "UserId">;
|
|
4
|
+
export type InternalGroupId = Brand<bigint, "InternalGroupId">;
|
|
5
|
+
export type GroupId = Brand<string, "GroupId">;
|
|
6
|
+
export type Role = Brand<number, "Role">;
|
|
7
|
+
export type AdminUserId = Brand<number, "AdminUserId">;
|
|
8
|
+
export interface ConnectedUser {
|
|
9
|
+
internalId: InternalUserId;
|
|
10
|
+
id: UserId;
|
|
11
|
+
firstName: string;
|
|
12
|
+
lastName: string;
|
|
13
|
+
email: string;
|
|
14
|
+
groups: Array<{
|
|
15
|
+
internalId: InternalGroupId;
|
|
16
|
+
id: GroupId;
|
|
17
|
+
label: string;
|
|
18
|
+
role: Role;
|
|
19
|
+
}>;
|
|
20
|
+
}
|
|
21
|
+
export interface Admin {
|
|
22
|
+
id: AdminUserId;
|
|
23
|
+
}
|
|
24
|
+
export interface Span {
|
|
25
|
+
component: string;
|
|
26
|
+
method: string;
|
|
27
|
+
startedAt: number;
|
|
28
|
+
duration: number;
|
|
29
|
+
isSuccess: boolean;
|
|
30
|
+
}
|
|
31
|
+
export interface Context {
|
|
32
|
+
startedAt: Date;
|
|
33
|
+
tx?: any;
|
|
34
|
+
user?: ConnectedUser;
|
|
35
|
+
admin?: Admin;
|
|
36
|
+
tracing: {
|
|
37
|
+
enabled: boolean;
|
|
38
|
+
spans: Array<Span>;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export declare function emptyContext(): Context;
|
package/dist/Context.js
ADDED
package/dist/DB.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Component } from "./Component.js";
|
|
2
|
+
import { type Context } from "./Context.js";
|
|
3
|
+
import { Statement } from "./utils/sql.js";
|
|
4
|
+
export declare abstract class DB extends Component {
|
|
5
|
+
abstract readonly name: string;
|
|
6
|
+
abstract query<T extends Record<string, any>>(ctx: Context, query: Statement): Promise<T[]>;
|
|
7
|
+
abstract run(ctx: Context, query: Statement): Promise<{
|
|
8
|
+
affectedRows: number;
|
|
9
|
+
}>;
|
|
10
|
+
abstract exec(ctx: Context, query: Statement): Promise<void>;
|
|
11
|
+
abstract startTransaction(ctx: Context, fn: () => Promise<void>): void | Promise<void>;
|
|
12
|
+
abstract createMigrationsTable(ctx: Context): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export declare class DuplicateKeyError extends Error {
|
|
15
|
+
}
|
package/dist/DB.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type HttpContext } from "./HttpContext.js";
|
|
2
|
+
import { Handler } from "./Handler.js";
|
|
3
|
+
declare abstract class BaseEndpoint extends Handler {
|
|
4
|
+
protected pathParamsSchema?: unknown;
|
|
5
|
+
protected querySchema?: unknown;
|
|
6
|
+
protected payloadSchema?: unknown;
|
|
7
|
+
private validatePathParams?;
|
|
8
|
+
private validateQuery?;
|
|
9
|
+
private validatePayload?;
|
|
10
|
+
doHandle(ctx: HttpContext): Response | Promise<Response>;
|
|
11
|
+
protected badRequest(message: string, details?: any): import("undici-types").Response;
|
|
12
|
+
}
|
|
13
|
+
export declare abstract class Endpoint extends BaseEndpoint {
|
|
14
|
+
private _endpointBrand;
|
|
15
|
+
doHandle(ctx: HttpContext): Response | Promise<Response>;
|
|
16
|
+
}
|
|
17
|
+
export declare abstract class AdminEndpoint extends BaseEndpoint {
|
|
18
|
+
private _adminEndpointBrand;
|
|
19
|
+
doHandle(ctx: HttpContext): Response | Promise<Response>;
|
|
20
|
+
}
|
|
21
|
+
export {};
|