@rhythmjs/rhythm 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -22
- package/dist/rhythm-7z989406.js +14 -0
- package/dist/rhythm.d.ts +11 -6
- package/dist/rhythm.js +38 -55
- package/dist/source.d.ts +3 -0
- package/dist/source.js +9 -0
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
# @rhythmjs/rhythm
|
|
2
2
|
|
|
3
|
-
The composition kernel at the core of Rhythm, the Bun-native backend framework, the piece `@rhythmjs/router` and `@rhythmjs/cli` are built on. It gives an application its structure (onion middleware,
|
|
3
|
+
The composition kernel at the core of Rhythm, the Bun-native backend framework, the piece `@rhythmjs/router` and `@rhythmjs/cli` are built on. It gives an application its structure (onion middleware, startup-time context, encapsulated modules, all checked at compile time) and deliberately nothing else: no router, no HTTP layer, and never will be.
|
|
4
4
|
|
|
5
5
|
## Concepts
|
|
6
6
|
|
|
7
7
|
- **Onion middleware**: `use()` wraps downstream steps, running code before _and_ after `next()`.
|
|
8
|
-
- **
|
|
8
|
+
- **Startup vs request time**: Rhythm only handles request time. Anything created at startup (a DB connection, a config object) is created by you, before serving, and handed to the app by assigning to `app.context`. Rhythm has no setup or teardown phase; you close what you opened.
|
|
9
|
+
- **Startup context**: `app.context` is a plain object typed by the second type parameter, `Rhythm<TInput, TStartup>`. Everything assigned to it is on every request context. Declare the shape once; assignments and reads are then checked.
|
|
9
10
|
- **Encapsulated modules**: `register()` mounts a child `Rhythm`; its context stays sealed unless you explicitly export fields from it.
|
|
10
|
-
- **Readonly context**: the context passed to middleware is deeply readonly at the type level; `next()` takes no arguments (pure Koa style), so state only changes via `derive()`
|
|
11
|
+
- **Readonly context**: the context passed to middleware is deeply readonly at the type level; `next()` takes no arguments (pure Koa style), so state only changes via `derive()` or startup `context`, or through a value branded with the `RhythmMutable` symbol (how `RhythmRouter`/`RhythmCli`'s response objects stay mutable).
|
|
11
12
|
|
|
12
13
|
## Example
|
|
13
14
|
|
|
14
15
|
```ts
|
|
15
16
|
import { Rhythm } from "@rhythmjs/rhythm";
|
|
16
17
|
|
|
17
|
-
const app = new Rhythm<{ userId: string }>()
|
|
18
|
-
.provide(() => ({ config: { serviceName: "greeter" } }))
|
|
19
|
-
.provide((deps) => ({
|
|
20
|
-
logger: { info: (msg: string) => console.log(`[${deps.config.serviceName}] ${msg}`) },
|
|
21
|
-
}))
|
|
18
|
+
const app = new Rhythm<{ userId: string }, { logger: { info(msg: string): void } }>()
|
|
22
19
|
.use(async (ctx, next) => {
|
|
23
20
|
const startedAt = Date.now();
|
|
24
21
|
await next();
|
|
@@ -28,11 +25,27 @@ const app = new Rhythm<{ userId: string }>()
|
|
|
28
25
|
ctx.logger.info(`hello, ${ctx.userId}`);
|
|
29
26
|
});
|
|
30
27
|
|
|
28
|
+
app.context.logger = { info: (msg) => console.log(`[greeter] ${msg}`) };
|
|
29
|
+
|
|
31
30
|
await app.run({ userId: "u1" });
|
|
32
|
-
await app.teardown();
|
|
33
31
|
```
|
|
34
32
|
|
|
35
|
-
|
|
33
|
+
On each `run()`, the middleware chain executes in registration order, onion-style.
|
|
34
|
+
|
|
35
|
+
### Startup values
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
const app = new Rhythm<{ userId: string }, { db: Db }>() // second parameter: the startup shape
|
|
39
|
+
.register(usersModule); // usersModule: Rhythm<{ userId: string; db: Db }> sees db
|
|
40
|
+
|
|
41
|
+
app.context.db = await createDb(); // startup time: yours to create and close
|
|
42
|
+
app.context.db = 1; // type error: not a Db
|
|
43
|
+
app.context.cache = x; // type error: not in the declared shape
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
TypeScript can't infer a type from a later property assignment, so the shape is declared once on the instance. `ctx.db` is then typed in every middleware, and `register()` rejects, at compile time, a module that requires context the parent's input and startup shape don't provide.
|
|
47
|
+
|
|
48
|
+
A registered module inherits its parent's context and can add its own through its own `module.context`. Those values are visible inside the module and to modules it registers, never to its parent. Per-request input wins over a startup value with the same key. Values are read when a request runs, so assign before serving; nothing checks that every declared key was assigned.
|
|
36
49
|
|
|
37
50
|
### Extending the context
|
|
38
51
|
|
|
@@ -46,37 +59,33 @@ const app = new Rhythm<{ userId: string }>()
|
|
|
46
59
|
.use((ctx) => console.log(ctx.user.name));
|
|
47
60
|
```
|
|
48
61
|
|
|
49
|
-
Keys prefixed with `#` are dropped from the context. For long-lived resources
|
|
62
|
+
Keys prefixed with `#` are dropped from the context. For long-lived resources, create them at startup and assign them to `app.context`.
|
|
50
63
|
|
|
51
64
|
### Module registration
|
|
52
65
|
|
|
53
66
|
```ts
|
|
54
67
|
import { Rhythm, derive } from "@rhythmjs/rhythm";
|
|
55
68
|
|
|
56
|
-
const authModule = new Rhythm<{ userId: string }>({ name: "auth" })
|
|
57
|
-
.provide(
|
|
58
|
-
() => ({ db: connectToUserDb() }),
|
|
59
|
-
(db) => db.close(),
|
|
60
|
-
)
|
|
69
|
+
const authModule = new Rhythm<{ userId: string }, { db: Db }>({ name: "auth" })
|
|
61
70
|
.use(derive((ctx) => ({ user: ctx.db.findUser(ctx.userId) })));
|
|
71
|
+
authModule.context.db = connectToUserDb();
|
|
62
72
|
|
|
63
73
|
const app = new Rhythm<{ userId: string }>()
|
|
64
74
|
.register(authModule, (result) => ({ user: result.user })) // only `user` crosses back
|
|
65
75
|
.use((ctx) => console.log(`hello, ${ctx.user.name}`));
|
|
66
76
|
```
|
|
67
77
|
|
|
68
|
-
|
|
78
|
+
The child runs in place: if it ends the chain without calling `next()`, the parent stops there.
|
|
69
79
|
|
|
70
80
|
## API
|
|
71
81
|
|
|
72
|
-
- `new Rhythm<TInput>(options?)`: creates a pipeline; `options.name`/`options.type` label errors from `register()`.
|
|
82
|
+
- `new Rhythm<TInput, TStartup>(options?)`: creates a pipeline; `options.name`/`options.type` label errors from `register()`.
|
|
73
83
|
- `.use(fn: (ctx, next) => Promise<void> | void)`: add an onion middleware step. `next()` takes no arguments; to extend the context pass a `derive()` middleware.
|
|
74
84
|
- `derive(fn: (ctx) => TExtra | Promise<TExtra>)`: middleware that merges `fn`'s result into the context and continues; the typed way to add fields.
|
|
75
|
-
- `.
|
|
85
|
+
- `.context`: the startup values object, typed by `Rhythm<TInput, TStartup>`. Assign to it before serving; every request context carries it. Inherited by registered modules, never by the parent.
|
|
76
86
|
- `.register(other: Rhythm, exportValue?)`: mount a child `Rhythm` module; sealed by default, opt in via `exportValue`. Controllers (`RhythmRouter`, `RhythmCli`) are not modules; they mount via `.use()` instead.
|
|
77
|
-
- `.run(input)`:
|
|
87
|
+
- `.run(input)`: dispatches `input` through the middleware chain.
|
|
78
88
|
- `.callback()`: returns the cached, reusable `(input) => Promise<TContext>` handler `run()` uses internally.
|
|
79
89
|
- `.middleware()`: returns this instance as a plain middleware, for flat mounting into a parent via `.use()` instead of `.register()`.
|
|
80
|
-
- `.
|
|
81
|
-
- `.teardown()`: disposes all providers in reverse order, cascading into registered modules.
|
|
90
|
+
- `.parent` / `.sources`: the module this one was registered into, and the tagged sources (routers, clis, any extension) below it in order, with registered modules expanded in place. Read lazily, once the app is assembled. Tag your own middleware with `withSource(fn, source)` from `@rhythmjs/rhythm/source`.
|
|
82
91
|
- `compose(middleware[])`: the standalone Koa-style onion dispatcher `Rhythm` is built on.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/source.ts
|
|
3
|
+
var SOURCE = "~source";
|
|
4
|
+
function withSource2(fn, source) {
|
|
5
|
+
Object.defineProperty(fn, SOURCE, { value: source });
|
|
6
|
+
return fn;
|
|
7
|
+
}
|
|
8
|
+
function sourceOf2(fn) {
|
|
9
|
+
if (typeof fn !== "function")
|
|
10
|
+
return;
|
|
11
|
+
return fn[SOURCE];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export { withSource2, sourceOf2 };
|
package/dist/rhythm.d.ts
CHANGED
|
@@ -5,15 +5,20 @@ export interface RhythmOptions {
|
|
|
5
5
|
[key: string]: unknown;
|
|
6
6
|
}
|
|
7
7
|
export declare function derive<TContext extends object, TExtra extends object>(fn: (ctx: TContext) => TExtra | Promise<TExtra>): DeriveMiddleware<TContext, OmitHashKeys<TExtra>>;
|
|
8
|
-
export declare class Rhythm<TInput extends object = {},
|
|
8
|
+
export declare class Rhythm<TInput extends object = {}, TStartup extends object = {}, TContext extends object = TInput & TStartup> {
|
|
9
9
|
#private;
|
|
10
|
+
/**
|
|
11
|
+
* Startup-time values (a db connection, config, ...). Declare the shape as the second type parameter, assign
|
|
12
|
+
* before serving, and every request context carries them. Registered modules inherit their parent's values and
|
|
13
|
+
* can add their own; a module's values never reach its parent.
|
|
14
|
+
*/
|
|
15
|
+
readonly context: TStartup;
|
|
16
|
+
parent?: Rhythm<any, any, any>;
|
|
10
17
|
constructor(options?: RhythmOptions);
|
|
11
|
-
|
|
18
|
+
get sources(): readonly object[];
|
|
19
|
+
use<TExtra extends object>(fn: DeriveMiddleware<TContext, TExtra>): Rhythm<TInput, TStartup, TContext & TExtra>;
|
|
12
20
|
use(fn: Middleware<TContext>): this;
|
|
13
|
-
|
|
14
|
-
register<TRegInput extends object, TRegContext extends object, TExported extends object = {}>(other: Rhythm<TRegInput, TRegContext, any> & (TContext extends TRegInput ? unknown : never), exportValue?: (result: TRegContext) => TExported): Rhythm<TInput, TContext & TExported, TProviders>;
|
|
15
|
-
setup(): Promise<void>;
|
|
16
|
-
teardown(): Promise<void>;
|
|
21
|
+
register<TRegInput extends object, TRegContext extends object, TExported extends object = {}>(other: Rhythm<TRegInput, any, TRegContext> & (TContext extends TRegInput ? unknown : never), exportValue?: (result: TRegContext) => TExported): Rhythm<TInput, TStartup, TContext & TExported>;
|
|
17
22
|
callback(): (input: TInput) => Promise<TContext>;
|
|
18
23
|
run(input: TInput): Promise<TContext>;
|
|
19
24
|
middleware(): Middleware<TContext>;
|
package/dist/rhythm.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
import {
|
|
3
3
|
compose2
|
|
4
4
|
} from "./rhythm-d9ycs7zz.js";
|
|
5
|
+
import {
|
|
6
|
+
withSource2,
|
|
7
|
+
sourceOf2
|
|
8
|
+
} from "./rhythm-7z989406.js";
|
|
5
9
|
|
|
6
10
|
// src/rhythm.ts
|
|
7
11
|
function publicEntries(value) {
|
|
@@ -26,90 +30,69 @@ function derive(fn) {
|
|
|
26
30
|
class Rhythm {
|
|
27
31
|
#middleware = [];
|
|
28
32
|
#options;
|
|
29
|
-
#
|
|
30
|
-
|
|
33
|
+
#sources = [];
|
|
34
|
+
context = {};
|
|
35
|
+
parent;
|
|
31
36
|
constructor(options = {}) {
|
|
32
37
|
this.#options = options;
|
|
33
38
|
}
|
|
39
|
+
get sources() {
|
|
40
|
+
return this.#sources.flatMap((source) => source instanceof Rhythm ? source.sources : [source]);
|
|
41
|
+
}
|
|
42
|
+
#adopt(source) {
|
|
43
|
+
if (!source)
|
|
44
|
+
return;
|
|
45
|
+
if (source instanceof Rhythm)
|
|
46
|
+
source.parent = this;
|
|
47
|
+
this.#sources.push(source);
|
|
48
|
+
}
|
|
34
49
|
use(fn) {
|
|
35
50
|
if (typeof fn !== "function")
|
|
36
51
|
throw new TypeError("middleware must be a function!");
|
|
37
52
|
this.#middleware.push(fn);
|
|
38
|
-
|
|
39
|
-
}
|
|
40
|
-
provide(factory, dispose) {
|
|
41
|
-
const entry = { factory, dispose };
|
|
42
|
-
this.#providers.push(entry);
|
|
43
|
-
this.#middleware.push(async (ctx, next) => {
|
|
44
|
-
Object.assign(ctx, publicEntries(entry.resolved));
|
|
45
|
-
await next();
|
|
46
|
-
});
|
|
53
|
+
this.#adopt(sourceOf2(fn));
|
|
47
54
|
return this;
|
|
48
55
|
}
|
|
49
56
|
register(other, exportValue) {
|
|
50
57
|
const module = other;
|
|
51
|
-
this.#
|
|
52
|
-
factory: async () => {
|
|
53
|
-
await module.setup();
|
|
54
|
-
return {};
|
|
55
|
-
},
|
|
56
|
-
dispose: () => module.teardown()
|
|
57
|
-
});
|
|
58
|
+
this.#adopt(module);
|
|
58
59
|
this.#middleware.push(async (ctx, next) => {
|
|
59
|
-
|
|
60
|
+
const inner = Object.assign({ ...ctx }, module.context);
|
|
61
|
+
let downstream;
|
|
60
62
|
try {
|
|
61
|
-
|
|
63
|
+
await compose2([...module.#middleware])(inner, async () => {
|
|
64
|
+
try {
|
|
65
|
+
if (exportValue)
|
|
66
|
+
Object.assign(ctx, exportValue(inner));
|
|
67
|
+
await next();
|
|
68
|
+
} catch (error) {
|
|
69
|
+
downstream = { error };
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
return inner;
|
|
73
|
+
});
|
|
62
74
|
} catch (cause) {
|
|
75
|
+
if (downstream && downstream.error === cause)
|
|
76
|
+
throw cause;
|
|
63
77
|
const { type = "module", name = "anonymous" } = module.#options;
|
|
64
78
|
throw new Error(`registered ${type} "${name}" failed`, { cause });
|
|
65
79
|
}
|
|
66
|
-
if (exportValue)
|
|
67
|
-
Object.assign(ctx, exportValue(result));
|
|
68
|
-
await next();
|
|
69
80
|
});
|
|
70
81
|
return this;
|
|
71
82
|
}
|
|
72
|
-
setup() {
|
|
73
|
-
if (!this.#setupPromise) {
|
|
74
|
-
this.#setupPromise = this.#resolveProviders().catch((err) => {
|
|
75
|
-
this.#setupPromise = null;
|
|
76
|
-
throw err;
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
return this.#setupPromise;
|
|
80
|
-
}
|
|
81
|
-
async#resolveProviders() {
|
|
82
|
-
const resolved = {};
|
|
83
|
-
for (const entry of this.#providers) {
|
|
84
|
-
entry.resolved = await entry.factory(resolved);
|
|
85
|
-
Object.assign(resolved, publicEntries(entry.resolved));
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
async teardown() {
|
|
89
|
-
for (const entry of [...this.#providers].reverse()) {
|
|
90
|
-
if (entry.resolved === undefined)
|
|
91
|
-
continue;
|
|
92
|
-
await entry.dispose?.(entry.resolved);
|
|
93
|
-
entry.resolved = undefined;
|
|
94
|
-
}
|
|
95
|
-
this.#setupPromise = null;
|
|
96
|
-
}
|
|
97
83
|
callback() {
|
|
98
84
|
const fn = compose2([...this.#middleware]);
|
|
99
|
-
return
|
|
100
|
-
await this.setup();
|
|
101
|
-
return fn({ ...input });
|
|
102
|
-
};
|
|
85
|
+
return (input) => fn({ ...this.context, ...input });
|
|
103
86
|
}
|
|
104
87
|
run(input) {
|
|
105
88
|
return this.callback()(input);
|
|
106
89
|
}
|
|
107
90
|
middleware() {
|
|
108
91
|
const fn = compose2([...this.#middleware]);
|
|
109
|
-
return async (ctx, next) => {
|
|
110
|
-
|
|
92
|
+
return withSource2(async (ctx, next) => {
|
|
93
|
+
Object.assign(ctx, this.context);
|
|
111
94
|
await fn(ctx, next);
|
|
112
|
-
};
|
|
95
|
+
}, this);
|
|
113
96
|
}
|
|
114
97
|
}
|
|
115
98
|
export {
|
package/dist/source.d.ts
ADDED
package/dist/source.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rhythmjs/rhythm",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.15",
|
|
4
4
|
"description": "A minimal, type-safe onion-middleware and provider composition kernel.",
|
|
5
5
|
"homepage": "https://rhythm.js.org/rhythm",
|
|
6
6
|
"license": "ISC",
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
"types": "./dist/compose.d.ts",
|
|
24
24
|
"default": "./dist/compose.js"
|
|
25
25
|
},
|
|
26
|
+
"./source": {
|
|
27
|
+
"types": "./dist/source.d.ts",
|
|
28
|
+
"default": "./dist/source.js"
|
|
29
|
+
},
|
|
26
30
|
"./types": {
|
|
27
31
|
"types": "./dist/types.d.ts",
|
|
28
32
|
"default": "./dist/types.js"
|
|
@@ -41,7 +45,7 @@
|
|
|
41
45
|
"bun": ">=1.2.0"
|
|
42
46
|
},
|
|
43
47
|
"scripts": {
|
|
44
|
-
"build": "bun build src/rhythm.ts src/compose.ts src/types.ts --outdir dist --root src --format esm --target bun --packages external --splitting && tsc -p tsconfig.build.json",
|
|
48
|
+
"build": "bun build src/rhythm.ts src/compose.ts src/source.ts src/types.ts --outdir dist --root src --format esm --target bun --packages external --splitting && tsc -p tsconfig.build.json",
|
|
45
49
|
"typecheck": "tsc --noEmit",
|
|
46
50
|
"test": "bun test"
|
|
47
51
|
}
|