@softistx/alxia-di 0.0.0-stage → 0.3.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 +21 -0
- package/README.md +133 -2
- package/dist/di.d.ts +20 -0
- package/dist/di.d.ts.map +1 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/expose.d.ts +13 -0
- package/dist/expose.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +140 -0
- package/dist/index.js.map +14 -0
- package/dist/lazy-scope.d.ts +21 -0
- package/dist/lazy-scope.d.ts.map +1 -0
- package/dist/lifecycle.d.ts +18 -0
- package/dist/lifecycle.d.ts.map +1 -0
- package/dist/types.d.ts +87 -0
- package/dist/types.d.ts.map +1 -0
- package/docs/README.md +12 -0
- package/docs/guide/lifecycle.md +103 -0
- package/docs/guide/request-scopes.md +207 -0
- package/docs/roadmap.md +26 -0
- package/docs/troubleshooting.md +134 -0
- package/package.json +52 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/alxia-di
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Moved from `@alxia/di`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
|
|
4
|
+
|
|
5
|
+
Dependency injection for [alxia](https://www.npmjs.com/package/@softistx/alxia),
|
|
6
|
+
on `@softistx/di`: typed Tokens, no
|
|
7
|
+
decorators, no dependency. Each request gets its own Scope, created only if
|
|
8
|
+
the request uses it and disposed of when it ends. A route reads what it
|
|
9
|
+
needs from its context, exposed by name, and a Token the Container does
|
|
10
|
+
not provide fails to compile.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
bun add @softistx/alxia-di @softistx/di @softistx/alxia
|
|
14
|
+
bun add -d typescript
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`@softistx/di` is public on npmjs: no scope entry or token is needed.
|
|
18
|
+
|
|
19
|
+
The peers are `@softistx/alxia` (`^0.14.0`: `deps.lifecycle` reads the server `onStop` is given), `@softistx/di` (`^0.3.1`) and `typescript`
|
|
20
|
+
(`^6.0.3 || ^7.0.0`): the Container is the app's own, built with its copy of
|
|
21
|
+
`@softistx/di`. Your `tsconfig.json` needs:
|
|
22
|
+
|
|
23
|
+
```jsonc
|
|
24
|
+
{
|
|
25
|
+
"compilerOptions": {
|
|
26
|
+
"moduleResolution": "bundler", // `nodenext` is not supported
|
|
27
|
+
"strict": true // the provide-order checks of @softistx/di need strictFunctionTypes
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { alxia } from '@softistx/alxia';
|
|
36
|
+
import { di } from '@softistx/alxia-di';
|
|
37
|
+
import { container, token } from '@softistx/di';
|
|
38
|
+
|
|
39
|
+
interface Db {
|
|
40
|
+
orders(user: string): Promise<string[]>;
|
|
41
|
+
close(): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
declare function connect(): Promise<Db>;
|
|
44
|
+
|
|
45
|
+
const DbT = token<Db>()('db');
|
|
46
|
+
const User = token<string>()('user');
|
|
47
|
+
const Orders = token<string[]>()('orders');
|
|
48
|
+
|
|
49
|
+
const services = container()
|
|
50
|
+
.provide(DbT, () => connect(), { dispose: (db) => db.close() })
|
|
51
|
+
.slot(User) // a value each request brings
|
|
52
|
+
.provide(Orders, async ({ get }) => (await get(DbT)).orders(await get(User)), {
|
|
53
|
+
lifetime: 'scoped',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// The Container has a Slot, so `slots` is required: the request's values.
|
|
57
|
+
const deps = di(services, {
|
|
58
|
+
slots: ({ request }) => ({ user: request.headers.get('x-user') ?? 'anonymous' }),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const app = alxia()
|
|
62
|
+
.plugin(deps.lifecycle) // disposes of the Container when the app stops
|
|
63
|
+
.use(deps) // a lazy Scope per request, as `scope`
|
|
64
|
+
.group('/orders', (group) =>
|
|
65
|
+
group
|
|
66
|
+
.use(deps.expose({ orders: Orders })) // resolved, as `orders`
|
|
67
|
+
.get('/', ({ orders, reply }) => reply(200, orders)),
|
|
68
|
+
)
|
|
69
|
+
.get('/health', ({ reply }) => reply(200, 'ok')); // no Scope made, no `slots` called
|
|
70
|
+
|
|
71
|
+
await services.init(); // the singletons, before listening: never in onStart
|
|
72
|
+
app.listen(3000);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **`di(container, options)`** is a middleware: given to `use`, the routes
|
|
76
|
+
after it read `scope`, the request's Scope, typed by the Container:
|
|
77
|
+
`await scope.resolve(Orders)`.
|
|
78
|
+
- **The Scope is lazy.** It is created, and `slots` called, on its first
|
|
79
|
+
`resolve`. A request that resolves nothing costs nothing.
|
|
80
|
+
- **`slots`** is required exactly when the Container has Slots, and
|
|
81
|
+
refused when it has none. Annotate its parameter to read what an earlier
|
|
82
|
+
middleware adds, `({ user }: { user: User }) => …`: every `use` of the
|
|
83
|
+
middleware is then checked for it.
|
|
84
|
+
- **`deps.expose({ key: Token })`** resolves each Token in the request's
|
|
85
|
+
Scope and adds it to the context under its key. It stands after the
|
|
86
|
+
`di`, which the types check, and each Token is checked against the
|
|
87
|
+
Container. `scope` and the base context's keys (`reply`, `request`…) are
|
|
88
|
+
refused.
|
|
89
|
+
- **Disposal** runs once the route has answered, whether it replied or
|
|
90
|
+
threw. A failure goes to `onDisposeError` (by default `console.error`)
|
|
91
|
+
and never replaces the response. A streamed body must not use scoped
|
|
92
|
+
values once its route has answered.
|
|
93
|
+
- **`deps.lifecycle`** disposes of the Container when the last app that
|
|
94
|
+
started under it stops. The count is per Container, across every `di()`
|
|
95
|
+
over it: forks of one base, or two apps each with their own
|
|
96
|
+
`di(services)`, share it safely, and a `stop()` of an app that never
|
|
97
|
+
listened disposes of nothing
|
|
98
|
+
([Lifecycle](https://github.com/softistx/alxia/blob/develop/packages/di/docs/guide/lifecycle.md#forks)).
|
|
99
|
+
Without it, the Container is yours to dispose of.
|
|
100
|
+
|
|
101
|
+
There is no `app.services` and no registry: a route reads the Scope, or
|
|
102
|
+
what an `expose` before it put on its context by name.
|
|
103
|
+
|
|
104
|
+
## API
|
|
105
|
+
|
|
106
|
+
| export | |
|
|
107
|
+
| --- | --- |
|
|
108
|
+
| `di(container, options?)` | the middleware, given to `use`; adds `scope`, with `.expose(tokens)` and `.lifecycle` on it |
|
|
109
|
+
| `DiMiddleware` | what `di` returns |
|
|
110
|
+
| `DiOptions` | its options: `slots`, required exactly when the Container has Slots, and `onDisposeError` |
|
|
111
|
+
| `SlotsFn` | the type of `slots`: the request's context to its Slot values |
|
|
112
|
+
| `ScopeContext` | what `di` adds to the context: `scope` |
|
|
113
|
+
| `Exposed` | what an `expose` map adds to the context |
|
|
114
|
+
| `SlotsReadAny` | what `di` returns when `slots` reads its context as `any`: refused by `use` |
|
|
115
|
+
| `ScopeNotMountedError` | an `expose` that ran with no Scope on its context; code `DI_SCOPE_NOT_MOUNTED`, a `DiError` |
|
|
116
|
+
|
|
117
|
+
## Errors
|
|
118
|
+
|
|
119
|
+
The runtime errors carry a stable `code`: match on it or on the class,
|
|
120
|
+
never on the message. Each message, its cause and its fix are in
|
|
121
|
+
[Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/di/docs/troubleshooting.md).
|
|
122
|
+
|
|
123
|
+
| class | `code` | meaning |
|
|
124
|
+
| --- | --- | --- |
|
|
125
|
+
| `ScopeNotMountedError` (this package, a `DiError`) | `DI_SCOPE_NOT_MOUNTED` | an `expose` ran with no Scope on its context, past the types |
|
|
126
|
+
| `ScopeDisposedError` (`@softistx/di`) | `DI_SCOPE_DISPOSED` | a `resolve` after the request's route had answered: a streamed body, a promise left running |
|
|
127
|
+
| `ContainerDisposedError` (`@softistx/di`) | `DI_CONTAINER_DISPOSED` | the Container was disposed of while an app still serves from it |
|
|
128
|
+
| `DisposeError` (`@softistx/di`) | `DI_DISPOSE_FAILED` | a `dispose` threw; handed to `onDisposeError`, never answered |
|
|
129
|
+
|
|
130
|
+
## Documentation
|
|
131
|
+
|
|
132
|
+
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/di/docs): the request's Scope, Slots from the context, `expose` in groups and routes, disposal and streaming, the Container's lifecycle across forks, and testing.
|
|
133
|
+
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/di/docs/troubleshooting.md): a `tsc` error on `di`, `use` or `expose`, and each runtime error.
|
|
134
|
+
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/di/docs/roadmap.md): what is coming, and what is not planned.
|
package/dist/di.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Empty } from '@softistx/alxia';
|
|
2
|
+
import type { Container } from '@softistx/di';
|
|
3
|
+
import type { DiArgs, DiReturn } from './types';
|
|
4
|
+
/**
|
|
5
|
+
* A middleware that gives each request a Scope of `container`, as `scope`
|
|
6
|
+
* in the context of what follows. The Scope is lazy: created, and `slots`
|
|
7
|
+
* called, on its first `resolve`, so a request that resolves nothing costs
|
|
8
|
+
* nothing. It is disposed of once the rest of the route has answered,
|
|
9
|
+
* whether it replied or threw.
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* const deps = di(container, { slots: ({ request }) => ({ tenant: request.headers.get('x-tenant') ?? 'public' }) });
|
|
13
|
+
* const app = alxia()
|
|
14
|
+
* .plugin(deps.lifecycle)
|
|
15
|
+
* .use(deps)
|
|
16
|
+
* .group('/orders', (g) => g.use(deps.expose({ orders: Orders })).get('/', ...));
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare function di<Singletons, Scoped, Slots, Reads = Empty>(container: Container<Singletons, Scoped, Slots>, ...args: DiArgs<Slots, Reads>): DiReturn<Singletons, Scoped, Reads>;
|
|
20
|
+
//# sourceMappingURL=di.d.ts.map
|
package/dist/di.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"di.d.ts","sourceRoot":"","sources":["../src/di.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,KAAK,EAGV,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAI9C,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AA4DhD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,KAAK,EAC1D,SAAS,EAAE,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,EAC/C,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,CAkDrC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The errors `@softistx/alxia-di` throws. Each extends `@softistx/di`'s `DiError` and
|
|
3
|
+
* carries a stable `code`: match on it, or on the class, never on the message.
|
|
4
|
+
*/
|
|
5
|
+
import { DiError } from '@softistx/di';
|
|
6
|
+
/**
|
|
7
|
+
* An `expose` middleware ran with no Scope on the context. The types refuse
|
|
8
|
+
* an `expose` where no `di` middleware stands before it, so this is reached
|
|
9
|
+
* through a cast, or a context whose `scope` something else replaced.
|
|
10
|
+
*/
|
|
11
|
+
export declare class ScopeNotMountedError extends DiError {
|
|
12
|
+
readonly name = "ScopeNotMountedError";
|
|
13
|
+
readonly token: undefined;
|
|
14
|
+
readonly code = "DI_SCOPE_NOT_MOUNTED";
|
|
15
|
+
/** The keys the `expose` that threw was asked to set. */
|
|
16
|
+
readonly keys: readonly string[];
|
|
17
|
+
constructor(keys: readonly string[]);
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC;;;;GAIG;AACH,qBAAa,oBAAqB,SAAQ,OAAO;IAChD,SAAkB,IAAI,0BAA0B;IAChD,SAAiB,KAAK,EAAE,SAAS,CAAC;IAClC,QAAQ,CAAC,IAAI,0BAA0B;IACvC,yDAAyD;IACzD,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;gBAErB,IAAI,EAAE,SAAS,MAAM,EAAE;CAOnC"}
|
package/dist/expose.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { BaseContext, NextFunction } from '@softistx/alxia';
|
|
2
|
+
import type { AnyToken } from '@softistx/di';
|
|
3
|
+
import type { RuntimeScope } from './lazy-scope';
|
|
4
|
+
/**
|
|
5
|
+
* The middleware behind `deps.expose(tokens)`: resolves every Token in the
|
|
6
|
+
* context's Scope, all at once, and passes each value on under its key.
|
|
7
|
+
*/
|
|
8
|
+
export declare function exposeFrom(tokens: Readonly<Record<string, AnyToken>>): (ctx: BaseContext & {
|
|
9
|
+
readonly scope?: RuntimeScope;
|
|
10
|
+
}, next: NextFunction) => Promise<import("@softistx/alxia").Next<{
|
|
11
|
+
[k: string]: unknown;
|
|
12
|
+
}, import("@softistx/alxia").Empty>>;
|
|
13
|
+
//# sourceMappingURL=expose.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expose.d.ts","sourceRoot":"","sources":["../src/expose.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD;;;GAGG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,IAGnE,KAAK,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,YAAY,CAAA;CAAE,EACpD,MAAM,YAAY;;qCAanB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,YAAY,EACX,YAAY,EACZ,SAAS,EACT,OAAO,EACP,YAAY,EACZ,OAAO,EACP,YAAY,GACZ,MAAM,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// src/di.ts
|
|
2
|
+
import {
|
|
3
|
+
markFactory
|
|
4
|
+
} from "@softistx/alxia";
|
|
5
|
+
|
|
6
|
+
// src/errors.ts
|
|
7
|
+
import { DiError } from "@softistx/di";
|
|
8
|
+
|
|
9
|
+
class ScopeNotMountedError extends DiError {
|
|
10
|
+
name = "ScopeNotMountedError";
|
|
11
|
+
code = "DI_SCOPE_NOT_MOUNTED";
|
|
12
|
+
keys;
|
|
13
|
+
constructor(keys) {
|
|
14
|
+
super(undefined, `expose(${keys.map((k) => `'${k}'`).join(", ")}) ran on a request with no Scope: give its di() middleware to use() before it`);
|
|
15
|
+
this.keys = keys;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/expose.ts
|
|
20
|
+
function exposeFrom(tokens) {
|
|
21
|
+
const entries = Object.entries(tokens);
|
|
22
|
+
return async function expose(ctx, next) {
|
|
23
|
+
const { scope } = ctx;
|
|
24
|
+
if (typeof scope?.resolve !== "function") {
|
|
25
|
+
throw new ScopeNotMountedError(Object.keys(tokens));
|
|
26
|
+
}
|
|
27
|
+
const values = await Promise.all(entries.map(([, token]) => scope.resolve(token)));
|
|
28
|
+
return next(Object.fromEntries(entries.map(([key], i) => [key, values[i]])));
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/lazy-scope.ts
|
|
33
|
+
import { ScopeDisposedError } from "@softistx/di";
|
|
34
|
+
|
|
35
|
+
class LazyScope {
|
|
36
|
+
#create;
|
|
37
|
+
#scope;
|
|
38
|
+
#disposal;
|
|
39
|
+
constructor(create) {
|
|
40
|
+
this.#create = create;
|
|
41
|
+
}
|
|
42
|
+
resolve = async (token) => {
|
|
43
|
+
if (this.#disposal && !this.#scope)
|
|
44
|
+
throw new ScopeDisposedError(token.name);
|
|
45
|
+
this.#scope ??= this.#create();
|
|
46
|
+
return (await this.#scope).resolve(token);
|
|
47
|
+
};
|
|
48
|
+
[Symbol.asyncDispose] = () => {
|
|
49
|
+
this.#disposal ??= this.#dispose();
|
|
50
|
+
return this.#disposal;
|
|
51
|
+
};
|
|
52
|
+
async#dispose() {
|
|
53
|
+
if (!this.#scope)
|
|
54
|
+
return;
|
|
55
|
+
const scope = await this.#scope.then((created) => created, () => {
|
|
56
|
+
return;
|
|
57
|
+
});
|
|
58
|
+
await scope?.[Symbol.asyncDispose]();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/lifecycle.ts
|
|
63
|
+
var started = new WeakMap;
|
|
64
|
+
function lifecycleOf(container, dispose) {
|
|
65
|
+
let serving = started.get(container);
|
|
66
|
+
if (serving === undefined) {
|
|
67
|
+
serving = new Set;
|
|
68
|
+
started.set(container, serving);
|
|
69
|
+
}
|
|
70
|
+
const servers = serving;
|
|
71
|
+
return function lifecycle(app) {
|
|
72
|
+
return app.onStart((server) => {
|
|
73
|
+
servers.add(server);
|
|
74
|
+
}).onStop(async (server) => {
|
|
75
|
+
if (server === undefined || !servers.delete(server))
|
|
76
|
+
return;
|
|
77
|
+
if (servers.size === 0)
|
|
78
|
+
await dispose();
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/di.ts
|
|
84
|
+
var OWNED = Symbol("@softistx/alxia-di owned");
|
|
85
|
+
async function within(ctx, scope, owned, next) {
|
|
86
|
+
const outer = ctx.scope;
|
|
87
|
+
const before = ctx[OWNED];
|
|
88
|
+
try {
|
|
89
|
+
return await next(owned === undefined ? { scope } : { scope, [OWNED]: owned });
|
|
90
|
+
} finally {
|
|
91
|
+
if (outer !== undefined && ctx.scope === scope)
|
|
92
|
+
ctx.scope = outer;
|
|
93
|
+
if (owned !== undefined && ctx[OWNED] === owned) {
|
|
94
|
+
if (before === undefined)
|
|
95
|
+
delete ctx[OWNED];
|
|
96
|
+
else
|
|
97
|
+
ctx[OWNED] = before;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function logDisposeError(error, ctx) {
|
|
102
|
+
console.error(`@softistx/alxia-di: disposing the Scope of ${ctx.request.method} ${ctx.url.pathname} failed`, error);
|
|
103
|
+
}
|
|
104
|
+
function di(container, ...args) {
|
|
105
|
+
const runtime = container;
|
|
106
|
+
const { slots, onDisposeError = logDisposeError } = args[0] ?? {};
|
|
107
|
+
async function di(ctx, next) {
|
|
108
|
+
const entered = ctx[OWNED]?.get(di);
|
|
109
|
+
if (entered !== undefined)
|
|
110
|
+
return within(ctx, entered, undefined, next);
|
|
111
|
+
const scope = new LazyScope(async () => runtime.createScope(slots ? await slots(ctx) : undefined));
|
|
112
|
+
const owned = new Map(ctx[OWNED]).set(di, scope);
|
|
113
|
+
try {
|
|
114
|
+
return await within(ctx, scope, owned, next);
|
|
115
|
+
} finally {
|
|
116
|
+
await scope[Symbol.asyncDispose]().catch((error) => {
|
|
117
|
+
try {
|
|
118
|
+
onDisposeError(error, ctx);
|
|
119
|
+
} catch {}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const expose = markFactory(function expose(tokens) {
|
|
124
|
+
return exposeFrom(tokens);
|
|
125
|
+
});
|
|
126
|
+
return Object.assign(di, {
|
|
127
|
+
expose,
|
|
128
|
+
lifecycle: lifecycleOf(container, async () => {
|
|
129
|
+
await runtime[Symbol.asyncDispose]();
|
|
130
|
+
})
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
markFactory(di);
|
|
134
|
+
export {
|
|
135
|
+
ScopeNotMountedError,
|
|
136
|
+
di
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
//# debugId=CB0AFBD95BB4AFC864756E2164756E21
|
|
140
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/di.ts", "../src/errors.ts", "../src/expose.ts", "../src/lazy-scope.ts", "../src/lifecycle.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n\ttype BaseContext,\n\ttype Empty,\n\tmarkFactory,\n\ttype NextFunction,\n} from '@softistx/alxia';\nimport type { Container } from '@softistx/di';\nimport { exposeFrom } from './expose';\nimport { LazyScope, type RuntimeScope } from './lazy-scope';\nimport { lifecycleOf } from './lifecycle';\nimport type { DiArgs, DiReturn } from './types';\n\n/** A Container as the runtime sees it, its types erased. */\ninterface RuntimeContainer extends AsyncDisposable {\n\tcreateScope(slots?: Readonly<Record<string, unknown>>): RuntimeScope;\n}\n\n/** The options once the types have done their work. */\ninterface RuntimeOptions {\n\treadonly slots?: (ctx: BaseContext) => unknown;\n\treadonly onDisposeError?: (error: unknown, ctx: BaseContext) => void;\n}\n\n/** Where the context keeps the Scope each `di` entered on it. */\nconst OWNED = Symbol('@softistx/alxia-di owned');\n\n/** The context as `di` writes to it: `next` merges into this same object. */\ntype Writable = BaseContext & {\n\tscope?: unknown;\n\t[OWNED]?: Owned;\n};\n\n/** Each `di` entered on a request, to the Scope it owns there. */\ntype Owned = ReadonlyMap<object, LazyScope>;\n\n/**\n * Runs the rest with `scope` on the context, and gives back the Scope that\n * was there before (another `di`'s), so what that one runs after its own\n * `next` reads its Scope again. Unless something later replaced it; with\n * nothing before it, this Scope stays, so a late resolve is a\n * ScopeDisposedError rather than an undefined.\n */\nasync function within(\n\tctx: Writable,\n\tscope: LazyScope,\n\towned: Owned | undefined,\n\tnext: NextFunction,\n) {\n\tconst outer = ctx.scope;\n\tconst before = ctx[OWNED];\n\ttry {\n\t\treturn await next(\n\t\t\towned === undefined ? { scope } : { scope, [OWNED]: owned },\n\t\t);\n\t} finally {\n\t\tif (outer !== undefined && ctx.scope === scope) ctx.scope = outer;\n\t\tif (owned !== undefined && ctx[OWNED] === owned) {\n\t\t\tif (before === undefined) delete ctx[OWNED];\n\t\t\telse ctx[OWNED] = before;\n\t\t}\n\t}\n}\n\nfunction logDisposeError(error: unknown, ctx: BaseContext): void {\n\tconsole.error(\n\t\t`@softistx/alxia-di: disposing the Scope of ${ctx.request.method} ${ctx.url.pathname} failed`,\n\t\terror,\n\t);\n}\n\n/**\n * A middleware that gives each request a Scope of `container`, as `scope`\n * in the context of what follows. The Scope is lazy: created, and `slots`\n * called, on its first `resolve`, so a request that resolves nothing costs\n * nothing. It is disposed of once the rest of the route has answered,\n * whether it replied or threw.\n *\n * ```ts\n * const deps = di(container, { slots: ({ request }) => ({ tenant: request.headers.get('x-tenant') ?? 'public' }) });\n * const app = alxia()\n * .plugin(deps.lifecycle)\n * .use(deps)\n * .group('/orders', (g) => g.use(deps.expose({ orders: Orders })).get('/', ...));\n * ```\n */\nexport function di<Singletons, Scoped, Slots, Reads = Empty>(\n\tcontainer: Container<Singletons, Scoped, Slots>,\n\t...args: DiArgs<Slots, Reads>\n): DiReturn<Singletons, Scoped, Reads> {\n\tconst runtime = container as unknown as RuntimeContainer;\n\tconst { slots, onDisposeError = logDisposeError }: RuntimeOptions =\n\t\t(args[0] as RuntimeOptions | undefined) ?? {};\n\tasync function di(ctx: Writable, next: NextFunction) {\n\t\t// The Scopes each `di` entered on this request, on the context itself:\n\t\t// made per fetch, so a Request fetched twice gets two, and carried by\n\t\t// core's copies of it (`{ ...ctx }` keeps an own symbol key).\n\t\tconst entered = ctx[OWNED]?.get(di);\n\t\t// Given again on this request, after another `di` maybe: the first one\n\t\t// owns the Scope; this one only puts it back on the context.\n\t\tif (entered !== undefined) return within(ctx, entered, undefined, next);\n\t\tconst scope = new LazyScope(async () =>\n\t\t\truntime.createScope(\n\t\t\t\tslots\n\t\t\t\t\t? ((await slots(ctx)) as Readonly<Record<string, unknown>>)\n\t\t\t\t\t: undefined,\n\t\t\t),\n\t\t);\n\t\t// A new Map, never the one on the context: core runs a 405's owners\n\t\t// each on its own copy of the context, and a Map they shared would\n\t\t// carry one group's Scope, and the Slots its derive gave, to another.\n\t\tconst owned: Owned = new Map(ctx[OWNED]).set(di, scope);\n\t\ttry {\n\t\t\treturn await within(ctx, scope, owned, next);\n\t\t} finally {\n\t\t\t// After `next`: a streamed body still being sent may not use the\n\t\t\t// Scope's values. See the guide.\n\t\t\tawait scope[Symbol.asyncDispose]().catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tonDisposeError(error, ctx);\n\t\t\t\t} catch {\n\t\t\t\t\t// A logger that throws must not replace the response either.\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tconst expose = markFactory(function expose(\n\t\ttokens: Parameters<typeof exposeFrom>[0],\n\t) {\n\t\treturn exposeFrom(tokens);\n\t});\n\n\treturn Object.assign(di, {\n\t\texpose,\n\t\tlifecycle: lifecycleOf(container, async () => {\n\t\t\tawait runtime[Symbol.asyncDispose]();\n\t\t}),\n\t}) as never;\n}\n\nmarkFactory(di);\n",
|
|
6
|
+
"/**\n * The errors `@softistx/alxia-di` throws. Each extends `@softistx/di`'s `DiError` and\n * carries a stable `code`: match on it, or on the class, never on the message.\n */\n\nimport { DiError } from '@softistx/di';\n\n/**\n * An `expose` middleware ran with no Scope on the context. The types refuse\n * an `expose` where no `di` middleware stands before it, so this is reached\n * through a cast, or a context whose `scope` something else replaced.\n */\nexport class ScopeNotMountedError extends DiError {\n\toverride readonly name = 'ScopeNotMountedError';\n\tdeclare readonly token: undefined;\n\treadonly code = 'DI_SCOPE_NOT_MOUNTED';\n\t/** The keys the `expose` that threw was asked to set. */\n\treadonly keys: readonly string[];\n\n\tconstructor(keys: readonly string[]) {\n\t\tsuper(\n\t\t\tundefined,\n\t\t\t`expose(${keys.map((k) => `'${k}'`).join(', ')}) ran on a request with no Scope: give its di() middleware to use() before it`,\n\t\t);\n\t\tthis.keys = keys;\n\t}\n}\n",
|
|
7
|
+
"import type { BaseContext, NextFunction } from '@softistx/alxia';\nimport type { AnyToken } from '@softistx/di';\nimport { ScopeNotMountedError } from './errors';\nimport type { RuntimeScope } from './lazy-scope';\n\n/**\n * The middleware behind `deps.expose(tokens)`: resolves every Token in the\n * context's Scope, all at once, and passes each value on under its key.\n */\nexport function exposeFrom(tokens: Readonly<Record<string, AnyToken>>) {\n\tconst entries = Object.entries(tokens);\n\treturn async function expose(\n\t\tctx: BaseContext & { readonly scope?: RuntimeScope },\n\t\tnext: NextFunction,\n\t) {\n\t\tconst { scope } = ctx;\n\t\tif (typeof scope?.resolve !== 'function') {\n\t\t\tthrow new ScopeNotMountedError(Object.keys(tokens));\n\t\t}\n\t\tconst values = await Promise.all(\n\t\t\tentries.map(([, token]) => scope.resolve(token)),\n\t\t);\n\t\treturn next(\n\t\t\tObject.fromEntries(entries.map(([key], i) => [key, values[i]])),\n\t\t);\n\t};\n}\n",
|
|
8
|
+
"import { type AnyToken, ScopeDisposedError } from '@softistx/di';\n\n/** A Scope as the runtime sees it, its types erased. */\nexport interface RuntimeScope extends AsyncDisposable {\n\tresolve(token: AnyToken): Promise<unknown>;\n}\n\n/**\n * A request's Scope, created on its first `resolve` and not before: a request\n * that never resolves anything creates no Scope and computes no Slot.\n *\n * `create` runs at most once. When it fails (a Slot function that threw, a\n * Container already disposed), every `resolve` of that request rejects with\n * its error, and there is nothing to dispose of.\n */\nexport class LazyScope implements RuntimeScope {\n\treadonly #create: () => Promise<RuntimeScope>;\n\t#scope: Promise<RuntimeScope> | undefined;\n\t#disposal: Promise<void> | undefined;\n\n\tconstructor(create: () => Promise<RuntimeScope>) {\n\t\tthis.#create = create;\n\t}\n\n\t// Arrow properties, not methods: `const { resolve } = ctx.scope` keeps\n\t// working, as it does on a Scope of `@softistx/di`.\n\n\treadonly resolve = async (token: AnyToken): Promise<unknown> => {\n\t\t// Once disposed, a Scope never created stays uncreated: making one now\n\t\t// would leave it with no owner to dispose of it.\n\t\tif (this.#disposal && !this.#scope)\n\t\t\tthrow new ScopeDisposedError(token.name);\n\t\tthis.#scope ??= this.#create();\n\t\treturn (await this.#scope).resolve(token);\n\t};\n\n\t/** Disposes of the Scope if it was created. A second call does nothing. */\n\treadonly [Symbol.asyncDispose] = (): Promise<void> => {\n\t\tthis.#disposal ??= this.#dispose();\n\t\treturn this.#disposal;\n\t};\n\n\tasync #dispose(): Promise<void> {\n\t\tif (!this.#scope) return;\n\t\tconst scope = await this.#scope.then(\n\t\t\t(created) => created,\n\t\t\t// Creation failed: its error went to whoever resolved, and there is\n\t\t\t// no Scope to dispose of.\n\t\t\t() => undefined,\n\t\t);\n\t\tawait scope?.[Symbol.asyncDispose]();\n\t}\n}\n",
|
|
9
|
+
"import type { AnyAlxia, Plugin } from '@softistx/alxia';\n\n/** The servers started under each Container, shared by every `di()` over it. */\nconst started = new WeakMap<object, Set<Bun.Server<unknown>>>();\n\n/**\n * The plugin behind `deps.lifecycle`: keeps the servers the apps it was\n * given to started, in one Set per Container, and disposes of the Container\n * when the last of them stops.\n *\n * The Set is keyed by the Container, so two `di()` calls over one Container\n * count together: an app stopping under one leaves the Container to an app\n * still serving under the other. A fork takes its base's `onStart` and\n * `onStop` and runs each once of its own, so forks share the Set too. `onStop`\n * is given the server that stopped, or `undefined` on a `stop()` of an app\n * that never listened: a server the Set does not hold, or none, stops nothing\n * of ours, which also makes the plugin given twice to one app dispose once.\n * An app that listens again after a stop adds its new server; the Container,\n * once disposed of, stays disposed (see the lifecycle guide).\n */\nexport function lifecycleOf(\n\tcontainer: object,\n\tdispose: () => Promise<void>,\n): Plugin {\n\tlet serving = started.get(container);\n\tif (serving === undefined) {\n\t\tserving = new Set();\n\t\tstarted.set(container, serving);\n\t}\n\tconst servers = serving;\n\treturn function lifecycle<App extends AnyAlxia>(app: App): App {\n\t\treturn app\n\t\t\t.onStart((server) => {\n\t\t\t\tservers.add(server);\n\t\t\t})\n\t\t\t.onStop(async (server) => {\n\t\t\t\tif (server === undefined || !servers.delete(server)) return;\n\t\t\t\tif (servers.size === 0) await dispose();\n\t\t\t}) as App;\n\t};\n}\n"
|
|
10
|
+
],
|
|
11
|
+
"mappings": "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",
|
|
12
|
+
"debugId": "CB0AFBD95BB4AFC864756E2164756E21",
|
|
13
|
+
"names": []
|
|
14
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type AnyToken } from '@softistx/di';
|
|
2
|
+
/** A Scope as the runtime sees it, its types erased. */
|
|
3
|
+
export interface RuntimeScope extends AsyncDisposable {
|
|
4
|
+
resolve(token: AnyToken): Promise<unknown>;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* A request's Scope, created on its first `resolve` and not before: a request
|
|
8
|
+
* that never resolves anything creates no Scope and computes no Slot.
|
|
9
|
+
*
|
|
10
|
+
* `create` runs at most once. When it fails (a Slot function that threw, a
|
|
11
|
+
* Container already disposed), every `resolve` of that request rejects with
|
|
12
|
+
* its error, and there is nothing to dispose of.
|
|
13
|
+
*/
|
|
14
|
+
export declare class LazyScope implements RuntimeScope {
|
|
15
|
+
#private;
|
|
16
|
+
constructor(create: () => Promise<RuntimeScope>);
|
|
17
|
+
readonly resolve: (token: AnyToken) => Promise<unknown>;
|
|
18
|
+
/** Disposes of the Scope if it was created. A second call does nothing. */
|
|
19
|
+
readonly [Symbol.asyncDispose]: () => Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=lazy-scope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lazy-scope.d.ts","sourceRoot":"","sources":["../src/lazy-scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAsB,MAAM,cAAc,CAAC;AAEjE,wDAAwD;AACxD,MAAM,WAAW,YAAa,SAAQ,eAAe;IACpD,OAAO,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,qBAAa,SAAU,YAAW,YAAY;;gBAKjC,MAAM,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC;IAO/C,QAAQ,CAAC,OAAO,GAAU,OAAO,QAAQ,KAAG,OAAO,CAAC,OAAO,CAAC,CAO1D;IAEF,2EAA2E;IAC3E,QAAQ,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,QAAO,OAAO,CAAC,IAAI,CAAC,CAGhD;CAYF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Plugin } from '@softistx/alxia';
|
|
2
|
+
/**
|
|
3
|
+
* The plugin behind `deps.lifecycle`: keeps the servers the apps it was
|
|
4
|
+
* given to started, in one Set per Container, and disposes of the Container
|
|
5
|
+
* when the last of them stops.
|
|
6
|
+
*
|
|
7
|
+
* The Set is keyed by the Container, so two `di()` calls over one Container
|
|
8
|
+
* count together: an app stopping under one leaves the Container to an app
|
|
9
|
+
* still serving under the other. A fork takes its base's `onStart` and
|
|
10
|
+
* `onStop` and runs each once of its own, so forks share the Set too. `onStop`
|
|
11
|
+
* is given the server that stopped, or `undefined` on a `stop()` of an app
|
|
12
|
+
* that never listened: a server the Set does not hold, or none, stops nothing
|
|
13
|
+
* of ours, which also makes the plugin given twice to one app dispose once.
|
|
14
|
+
* An app that listens again after a stop adds its new server; the Container,
|
|
15
|
+
* once disposed of, stays disposed (see the lifecycle guide).
|
|
16
|
+
*/
|
|
17
|
+
export declare function lifecycleOf(container: object, dispose: () => Promise<void>): Plugin;
|
|
18
|
+
//# sourceMappingURL=lifecycle.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAKxD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAC1B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAC1B,MAAM,CAiBR"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { BaseContext, Empty, Middleware, MiddlewareContext, Next, Plugin } from '@softistx/alxia';
|
|
2
|
+
import type { AnyToken, Scope, ScopeResolvable, TokenValue } from '@softistx/di';
|
|
3
|
+
/** What `di` adds to the context: the request's Scope. */
|
|
4
|
+
export interface ScopeContext<Singletons, Scoped> {
|
|
5
|
+
/** The request's Scope, created on its first `resolve`. */
|
|
6
|
+
readonly scope: Scope<Singletons, Scoped>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Computes a request's Slot values from its context. `Reads` is what it
|
|
10
|
+
* reads beyond the base context, from its annotated parameter: the `user`
|
|
11
|
+
* an earlier middleware adds, which every `use` of the middleware is then
|
|
12
|
+
* checked for.
|
|
13
|
+
*/
|
|
14
|
+
export type SlotsFn<Slots, Reads> = (ctx: MiddlewareContext<Reads>) => Readonly<Slots> | PromiseLike<Readonly<Slots>>;
|
|
15
|
+
/** What every `di` call takes, Slots or not. */
|
|
16
|
+
interface CommonOptions {
|
|
17
|
+
/**
|
|
18
|
+
* Called when disposing of a request's Scope fails, after its response
|
|
19
|
+
* is decided: the error never replaces the response, nor the error the
|
|
20
|
+
* route threw. Defaults to `console.error`. What it throws is ignored.
|
|
21
|
+
*/
|
|
22
|
+
readonly onDisposeError?: (error: unknown, ctx: BaseContext) => void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `di`'s options. `slots` is required exactly when the Container has Slots,
|
|
26
|
+
* and refused when it has none.
|
|
27
|
+
*/
|
|
28
|
+
export type DiOptions<Slots, Reads = Empty> = [keyof Slots] extends [never] ? CommonOptions & {
|
|
29
|
+
readonly slots?: never;
|
|
30
|
+
} : CommonOptions & {
|
|
31
|
+
/**
|
|
32
|
+
* The request's Slot values. Called once, on the Scope's first
|
|
33
|
+
* `resolve`: never on a request that resolves nothing.
|
|
34
|
+
*/
|
|
35
|
+
readonly slots: SlotsFn<Slots, Reads>;
|
|
36
|
+
};
|
|
37
|
+
/** `di`'s parameters: the options are optional when there is no Slot. */
|
|
38
|
+
export type DiArgs<Slots, Reads> = [keyof Slots] extends [never] ? [options?: DiOptions<Slots, Reads>] : [options: DiOptions<Slots, Reads>];
|
|
39
|
+
/** A key `expose` may not set: the Scope's own, or the base context's. */
|
|
40
|
+
type Reserved = 'scope' | keyof BaseContext;
|
|
41
|
+
/**
|
|
42
|
+
* `unknown` when `expose` may take `Tokens`, else a refusal: every Token
|
|
43
|
+
* one a Scope of the Container resolves, and no key the context already
|
|
44
|
+
* holds (`scope`, `reply`, `request`...).
|
|
45
|
+
*/
|
|
46
|
+
export type Exposable<Tokens, Singletons, Scoped> = {
|
|
47
|
+
[K in keyof Tokens]: K extends Reserved ? {
|
|
48
|
+
readonly [M in `'${K & string}' is a key of the context: expose under another name`]: never;
|
|
49
|
+
} : ScopeResolvable<Tokens[K], Singletons, Scoped>;
|
|
50
|
+
};
|
|
51
|
+
/** What `expose(tokens)` adds to the context: each key, typed by its Token. */
|
|
52
|
+
export type Exposed<Tokens> = {
|
|
53
|
+
readonly [K in keyof Tokens]: TokenValue<Tokens[K]>;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* The middleware `di` makes: given to `use`, it adds `scope` to the context
|
|
57
|
+
* of what follows. `expose` builds the middleware that resolves Tokens in
|
|
58
|
+
* it, and `lifecycle` the plugin that disposes of the Container when the
|
|
59
|
+
* last app serving it stops.
|
|
60
|
+
*/
|
|
61
|
+
export type DiMiddleware<Singletons, Scoped, Reads = Empty> = Middleware<Reads, Promise<Next<ScopeContext<Singletons, Scoped>>>> & {
|
|
62
|
+
/**
|
|
63
|
+
* A middleware that resolves each Token in the request's Scope and adds
|
|
64
|
+
* it to the context under its key. It stands after this `di`: one with
|
|
65
|
+
* no `scope` in its context fails to compile.
|
|
66
|
+
*/
|
|
67
|
+
expose<const Tokens extends Readonly<Record<string, AnyToken>>>(tokens: Tokens & Exposable<Tokens, Singletons, Scoped>): Middleware<ScopeContext<Singletons, Scoped>, Promise<Next<Exposed<Tokens>>>>;
|
|
68
|
+
/**
|
|
69
|
+
* A plugin: `app.plugin(deps.lifecycle)`. Disposes of the Container when
|
|
70
|
+
* the last app it was given to that started stops, so forks of one base
|
|
71
|
+
* share it safely. Without it, the Container is the application's to
|
|
72
|
+
* dispose of.
|
|
73
|
+
*/
|
|
74
|
+
readonly lifecycle: Plugin;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* What `di` returns when `slots` reads its context as `any`: not a
|
|
78
|
+
* middleware, so `use` refuses it. `any` would let it stand where what it
|
|
79
|
+
* reads is not given.
|
|
80
|
+
*/
|
|
81
|
+
export interface SlotsReadAny {
|
|
82
|
+
readonly '~any': 'slots reads its context as any: annotate what it reads, or leave it unannotated';
|
|
83
|
+
}
|
|
84
|
+
/** What `di` returns: its middleware, unless `slots` reads `any`. */
|
|
85
|
+
export type DiReturn<Singletons, Scoped, Reads> = 0 extends 1 & Reads ? SlotsReadAny : DiMiddleware<Singletons, Scoped, Reads>;
|
|
86
|
+
export {};
|
|
87
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @softistx/alxia-di documentation
|
|
2
|
+
|
|
3
|
+
The [package README](../README.md) is the short version. This folder is the
|
|
4
|
+
long one. The Container, Tokens, lifetimes and Slots themselves are
|
|
5
|
+
[`@softistx/di`'s documentation](https://github.com/softistx/nxgt-di/tree/develop/packages/di/docs).
|
|
6
|
+
|
|
7
|
+
| Page | Read it when |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| [Request Scopes](guide/request-scopes.md) | giving routes a Scope, computing Slots from the context, exposing values to a group or a route, streaming, or testing a route |
|
|
10
|
+
| [Lifecycle](guide/lifecycle.md) | booting the Container with `init`, disposing of it on stop, or sharing it between forks |
|
|
11
|
+
| [Troubleshooting](troubleshooting.md) | `tsc` refused a `di`, a `use` or an `expose`, or a request failed with an error from this package |
|
|
12
|
+
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Lifecycle
|
|
2
|
+
|
|
3
|
+
`di` never creates the Container and, unless asked, never disposes of it.
|
|
4
|
+
This page covers booting it, disposing of it when the app stops, and
|
|
5
|
+
sharing it between forks.
|
|
6
|
+
|
|
7
|
+
## Boot: `init()` before `listen()`
|
|
8
|
+
|
|
9
|
+
Singletons are lazy. `await container.init()` creates them all, in provide
|
|
10
|
+
order, so a failing connection stops the boot rather than the first
|
|
11
|
+
request:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { alxia } from '@softistx/alxia';
|
|
15
|
+
import { di } from '@softistx/alxia-di';
|
|
16
|
+
import { container, token } from '@softistx/di';
|
|
17
|
+
|
|
18
|
+
interface Db { close(): Promise<void> }
|
|
19
|
+
declare function connect(): Promise<Db>;
|
|
20
|
+
const DbT = token<Db>()('db');
|
|
21
|
+
|
|
22
|
+
const services = container().provide(DbT, () => connect(), {
|
|
23
|
+
dispose: (db) => db.close(),
|
|
24
|
+
});
|
|
25
|
+
const deps = di(services);
|
|
26
|
+
const app = alxia().plugin(deps.lifecycle).use(deps);
|
|
27
|
+
|
|
28
|
+
await services.init(); // rejects with the first factory's error
|
|
29
|
+
app.listen(3000);
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Call it before `listen()`, never in `onStart`: `onStart` is not awaited,
|
|
33
|
+
and an error it throws is only logged, so the server would serve requests
|
|
34
|
+
with a Container that failed to boot.
|
|
35
|
+
|
|
36
|
+
## Dispose on stop: `deps.lifecycle`
|
|
37
|
+
|
|
38
|
+
`app.plugin(deps.lifecycle)` disposes of the Container when the app stops:
|
|
39
|
+
on `SIGTERM` or `SIGINT`, or `stop()`, after the requests in flight have
|
|
40
|
+
finished, within `listen`'s `stopTimeout`. Disposing runs every value's
|
|
41
|
+
`dispose` in reverse creation order.
|
|
42
|
+
|
|
43
|
+
It keeps the server each app it was given to started (`onStart` is given
|
|
44
|
+
it), and disposes of the Container when the last of them stops (`onStop`
|
|
45
|
+
is given the server that stopped). The count is per Container, across
|
|
46
|
+
every `di()` over it: two apps each with their own `di(services)` over one
|
|
47
|
+
`services` share it, and the Container is disposed of when the last of the
|
|
48
|
+
two stops, not the first. Giving `deps.lifecycle` twice to one app still
|
|
49
|
+
disposes once. That is what makes forks safe. Requires `@softistx/alxia` 0.14 or
|
|
50
|
+
later, where `onStop` receives the server.
|
|
51
|
+
|
|
52
|
+
## Forks
|
|
53
|
+
|
|
54
|
+
`app.fork()` copies a base, its `onStart` and `onStop` hooks included, and
|
|
55
|
+
each fork runs them once of its own. Two forks of a base that disposed of
|
|
56
|
+
the Container in a plain `onStop` would break each other: stopping the
|
|
57
|
+
first would dispose of the Container while the second still serves, and its
|
|
58
|
+
next request would fail with `ContainerDisposedError`.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { alxia } from '@softistx/alxia';
|
|
62
|
+
import { di } from '@softistx/alxia-di';
|
|
63
|
+
import { container } from '@softistx/di';
|
|
64
|
+
|
|
65
|
+
const services = container();
|
|
66
|
+
const deps = di(services);
|
|
67
|
+
const base = alxia().plugin(deps.lifecycle).use(deps);
|
|
68
|
+
|
|
69
|
+
const publicApi = base.fork();
|
|
70
|
+
const adminApi = base.fork();
|
|
71
|
+
publicApi.listen(3000);
|
|
72
|
+
adminApi.listen(3001);
|
|
73
|
+
|
|
74
|
+
await publicApi.stop(); // adminApi keeps the Container
|
|
75
|
+
await adminApi.stop(); // the last one: the Container is disposed of
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- Disposing twice does nothing, so an app that also disposes of the
|
|
79
|
+
Container itself does no harm.
|
|
80
|
+
- A disposed Container stays disposed: an app listening again after its
|
|
81
|
+
stop needs a new Container, and a new `di`.
|
|
82
|
+
- An app that never listened, such as one a spec calls with
|
|
83
|
+
`app.request()`, still runs every `onStop` on `stop()`, given `undefined`:
|
|
84
|
+
`deps.lifecycle` ignores it. A fork that never listened can be stopped
|
|
85
|
+
while another serves; the Container stays with the one serving.
|
|
86
|
+
|
|
87
|
+
## Without `deps.lifecycle`
|
|
88
|
+
|
|
89
|
+
The Container is then the application's: dispose of it where the
|
|
90
|
+
application decides, once nothing serves from it any more.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { alxia } from '@softistx/alxia';
|
|
94
|
+
import { di } from '@softistx/alxia-di';
|
|
95
|
+
import { container } from '@softistx/di';
|
|
96
|
+
|
|
97
|
+
const services = container();
|
|
98
|
+
const app = alxia()
|
|
99
|
+
.use(di(services))
|
|
100
|
+
.onStop(() => services[Symbol.asyncDispose]());
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Do this on one app only, never on a base that is forked.
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Request Scopes
|
|
2
|
+
|
|
3
|
+
`di` gives each request a Scope of your Container. This page covers how it
|
|
4
|
+
is created, how routes get their values, and when it is disposed of.
|
|
5
|
+
|
|
6
|
+
## The Scope on the context
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { alxia } from '@softistx/alxia';
|
|
10
|
+
import { di } from '@softistx/alxia-di';
|
|
11
|
+
import { container, token } from '@softistx/di';
|
|
12
|
+
|
|
13
|
+
const RequestId = token<string>()('requestId');
|
|
14
|
+
|
|
15
|
+
const services = container().provide(RequestId, () => crypto.randomUUID(), {
|
|
16
|
+
lifetime: 'scoped',
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const deps = di(services); // no Slot, so no options needed
|
|
20
|
+
|
|
21
|
+
const app = alxia()
|
|
22
|
+
.use(deps)
|
|
23
|
+
.get('/id', async ({ scope, reply }) => reply(200, await scope.resolve(RequestId)));
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`di` is a middleware: what it adds, `scope`, is read by the routes and the
|
|
27
|
+
middlewares declared after it, and only by those. A route declared before
|
|
28
|
+
it has no `scope`, and reading one fails to compile. Given to `use` on the
|
|
29
|
+
app, it runs on every request, a 404 included; in a group, on the group's
|
|
30
|
+
routes alone.
|
|
31
|
+
|
|
32
|
+
`scope` is a Scope of `@softistx/di`: `resolve` takes any Token the Container
|
|
33
|
+
provides, singletons included, and always returns a Promise. Its `resolve`
|
|
34
|
+
is bound, so `({ scope: { resolve } })` works.
|
|
35
|
+
|
|
36
|
+
## The Scope is lazy
|
|
37
|
+
|
|
38
|
+
Nothing happens when the middleware runs. The Scope is created on the
|
|
39
|
+
first `resolve`, from a route or from an `expose`, and only then is `slots`
|
|
40
|
+
called. A `/health` route that resolves nothing creates no Scope and never
|
|
41
|
+
computes a Slot.
|
|
42
|
+
|
|
43
|
+
## Slots
|
|
44
|
+
|
|
45
|
+
When the Container has Slots, `slots` is required, and must give a value of
|
|
46
|
+
the right type for each. It receives the request's context:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { alxia, defineMiddleware } from '@softistx/alxia';
|
|
50
|
+
import { di } from '@softistx/alxia-di';
|
|
51
|
+
import { container, token } from '@softistx/di';
|
|
52
|
+
|
|
53
|
+
interface User { id: string }
|
|
54
|
+
const Principal = token<User>()('principal');
|
|
55
|
+
const Tenant = token<string>()('tenant');
|
|
56
|
+
|
|
57
|
+
const withSlots = container().slot(Principal).slot(Tenant);
|
|
58
|
+
|
|
59
|
+
const auth = defineMiddleware(({ request, reply }, next) => {
|
|
60
|
+
const id = request.headers.get('x-user');
|
|
61
|
+
return id === null ? reply(401, { error: 'unauthorized' as const }) : next({ user: { id } });
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Annotated: it reads `user`, so the middleware is refused where no `user` is.
|
|
65
|
+
const scoped = di(withSlots, {
|
|
66
|
+
slots: ({ user, request }: { user: User; request: Request }) => ({
|
|
67
|
+
principal: user,
|
|
68
|
+
tenant: request.headers.get('x-tenant') ?? 'public',
|
|
69
|
+
}),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const app = alxia().use(auth).use(scoped);
|
|
73
|
+
// alxia().use(scoped) alone: `user` is missing from the context, a compile error
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- Unannotated, `slots` reads the base context (`request`, `url`, `cookies`…).
|
|
77
|
+
Annotated, what it reads beyond it is required where the middleware is
|
|
78
|
+
given. Annotated `any`, `di` is refused everywhere: annotate what it
|
|
79
|
+
reads, or leave it unannotated.
|
|
80
|
+
- It runs at most once per request, even under concurrent resolves, and may
|
|
81
|
+
be async. When it throws, every `resolve` of that request rejects with its
|
|
82
|
+
error, and there is no Scope to dispose of.
|
|
83
|
+
- A key that is no Slot is ignored. TypeScript does not check a function's
|
|
84
|
+
returned object for extra keys, so a misspelt Slot name shows up as the
|
|
85
|
+
missing one.
|
|
86
|
+
|
|
87
|
+
## Exposing values
|
|
88
|
+
|
|
89
|
+
`deps.expose({ key: Token })` is a middleware that resolves each Token in
|
|
90
|
+
the request's Scope and adds it to the context under its key. Give it to a
|
|
91
|
+
group's `use`, or to one route:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { alxia } from '@softistx/alxia';
|
|
95
|
+
import { di } from '@softistx/alxia-di';
|
|
96
|
+
import { container, token } from '@softistx/di';
|
|
97
|
+
|
|
98
|
+
interface Report { rows(): Promise<unknown[]> }
|
|
99
|
+
declare const report: Report;
|
|
100
|
+
const ReportT = token<Report>()('report');
|
|
101
|
+
const RequestId = token<string>()('requestId');
|
|
102
|
+
|
|
103
|
+
const deps = di(
|
|
104
|
+
container()
|
|
105
|
+
.provide(ReportT, () => report)
|
|
106
|
+
.provide(RequestId, () => crypto.randomUUID(), { lifetime: 'scoped' }),
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const app = alxia()
|
|
110
|
+
.use(deps)
|
|
111
|
+
.group('/reports', (group) =>
|
|
112
|
+
group
|
|
113
|
+
.use(deps.expose({ report: ReportT, requestId: RequestId }))
|
|
114
|
+
.get('/daily', async ({ report, requestId, reply }) =>
|
|
115
|
+
reply(200, { requestId, rows: await report.rows() }),
|
|
116
|
+
),
|
|
117
|
+
)
|
|
118
|
+
.get('/me', deps.expose({ requestId: RequestId }), ({ requestId, reply }) =>
|
|
119
|
+
reply(200, requestId),
|
|
120
|
+
);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- The Tokens are resolved together, before the route runs. A failing
|
|
124
|
+
factory is a rejection like any other: answered 500, or caught by a
|
|
125
|
+
`try`/`catch` middleware around it, and the Scope is still disposed of.
|
|
126
|
+
- A value is resolved in the request's Scope, so a route that also calls
|
|
127
|
+
`scope.resolve(RequestId)` gets the same one.
|
|
128
|
+
- Each Token is checked against the Container at compile time. `scope` and
|
|
129
|
+
the base context's keys (`reply`, `request`, `url`…) are refused as keys.
|
|
130
|
+
- It stands after a `di` of its Container: in the context it reads, `scope`
|
|
131
|
+
must be that Container's Scope, or the `use` fails to compile.
|
|
132
|
+
|
|
133
|
+
There is no `app.services`: nothing is resolved by name from the app, and
|
|
134
|
+
no route reads a value nobody exposed to it.
|
|
135
|
+
|
|
136
|
+
## Two `di` on one request
|
|
137
|
+
|
|
138
|
+
The same `deps` given twice to one route makes one Scope: the first owns it
|
|
139
|
+
and disposes of it. Two `di` of different Containers may nest, the inner
|
|
140
|
+
one in a group: inside it `scope` is the inner Scope, and once the inner
|
|
141
|
+
middleware has disposed of it, `scope` is the outer one again, so the outer
|
|
142
|
+
middleware's code after its `await next()` reads its own.
|
|
143
|
+
|
|
144
|
+
## Disposal
|
|
145
|
+
|
|
146
|
+
The Scope is disposed of once the rest of the route has answered, whether it
|
|
147
|
+
replied or threw: its scoped values and the transients it resolved, in
|
|
148
|
+
reverse creation order. Singletons belong to the Container.
|
|
149
|
+
|
|
150
|
+
A failure while disposing goes to `onDisposeError`, after the response is
|
|
151
|
+
decided, so it never replaces the response nor the route's error:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { di } from '@softistx/alxia-di';
|
|
155
|
+
import { container } from '@softistx/di';
|
|
156
|
+
|
|
157
|
+
declare const logger: { error(message: string, error: unknown): void };
|
|
158
|
+
|
|
159
|
+
const logged = di(container(), {
|
|
160
|
+
onDisposeError: (error, ctx) => logger.error(`dispose failed: ${ctx.url.pathname}`, error),
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
By default it is `console.error`. What `onDisposeError` itself throws is
|
|
165
|
+
ignored.
|
|
166
|
+
|
|
167
|
+
### Streaming
|
|
168
|
+
|
|
169
|
+
The Scope is disposed of when the route has answered, which for a streamed
|
|
170
|
+
body (server-sent events, a page rendered as it goes) is before the body
|
|
171
|
+
has been sent. Resolve what the stream needs before answering, and keep no
|
|
172
|
+
scoped value for the stream: a `resolve` made after disposal rejects with
|
|
173
|
+
`ScopeDisposedError`, and a scoped value may already be closed. A singleton
|
|
174
|
+
outlives the request and is safe to keep using.
|
|
175
|
+
|
|
176
|
+
## Testing a route
|
|
177
|
+
|
|
178
|
+
Build the app from the Container it is given, and send it requests with
|
|
179
|
+
`app.request()`: no server needed. `override` swaps a Provider for a fake:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { alxia } from '@softistx/alxia';
|
|
183
|
+
import { di } from '@softistx/alxia-di';
|
|
184
|
+
import { container, token } from '@softistx/di';
|
|
185
|
+
|
|
186
|
+
interface Db { query(sql: string): Promise<unknown[]> }
|
|
187
|
+
declare function connect(): Promise<Db>;
|
|
188
|
+
const DbT = token<Db>()('db');
|
|
189
|
+
|
|
190
|
+
const services = container().provide(DbT, () => connect());
|
|
191
|
+
|
|
192
|
+
export function makeApp(given: typeof services) {
|
|
193
|
+
const deps = di(given);
|
|
194
|
+
return alxia()
|
|
195
|
+
.use(deps)
|
|
196
|
+
.get('/rows', async ({ scope, reply }) =>
|
|
197
|
+
reply(200, await (await scope.resolve(DbT)).query('select 1')),
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// In a test:
|
|
202
|
+
const fake: Db = { query: async () => [{ id: 1 }] };
|
|
203
|
+
const res = await makeApp(services.override(DbT, fake)).request('/rows');
|
|
204
|
+
// await res.json() → [{ id: 1 }]
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
A Slot is not overridden: give `slots` the value the test needs.
|
package/docs/roadmap.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Roadmap
|
|
2
|
+
|
|
3
|
+
What `@softistx/alxia-di` gives an app, and what is coming. This page is a
|
|
4
|
+
direction, not a commitment: the version something shipped in is the only
|
|
5
|
+
number on it.
|
|
6
|
+
|
|
7
|
+
## Now
|
|
8
|
+
|
|
9
|
+
- **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-di` (it was `@alxia/di`). Same code and API; replace the dependency and the imports ([migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md)). The old name is deprecated.
|
|
10
|
+
|
|
11
|
+
## Next
|
|
12
|
+
|
|
13
|
+
Nothing scheduled yet.
|
|
14
|
+
|
|
15
|
+
## Later
|
|
16
|
+
|
|
17
|
+
- **Disposal after a streamed body.** The Scope is disposed of when the route answers, before a streamed body has been sent; waiting for the body's end, as `@softistx/alxia-telemetry` does for its span, would let a stream use scoped values.
|
|
18
|
+
|
|
19
|
+
## Not planned
|
|
20
|
+
|
|
21
|
+
- **`app.services`, or any registry on the app.** A route reads the Scope, or what an `expose` before it put on its context by name: what it depends on is in its own chain, checked by the types.
|
|
22
|
+
- **A second container.** `@softistx/alxia-di` is an adapter over `@softistx/di`, a peer: the Tokens, the lifetimes, the captive check and the Modules are its.
|
|
23
|
+
|
|
24
|
+
## Shipped
|
|
25
|
+
|
|
26
|
+
- **A Scope per request, and `expose` (0.1.0).** `use(di(container, { slots }))` gives every route after it a lazy Scope, disposed of when the request ends; `deps.expose({ key: Token })` puts resolved values on the context of a group or a route, each Token checked against the Container; `app.plugin(deps.lifecycle)` disposes of the Container when the last app serving it stops.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# Troubleshooting
|
|
2
|
+
|
|
3
|
+
One entry for each error you can hit, headed by the message you will search
|
|
4
|
+
for. Runtime errors carry a stable `code`: match on the `code` or the class,
|
|
5
|
+
never on the message. The errors of `@softistx/di` itself, such as
|
|
6
|
+
`Token 'db' is not provided` on `scope.resolve`, are in
|
|
7
|
+
[its troubleshooting page](https://github.com/softistx/nxgt-di/blob/develop/packages/di/docs/troubleshooting.md).
|
|
8
|
+
|
|
9
|
+
## Compile errors
|
|
10
|
+
|
|
11
|
+
### `Expected 2 arguments, but got 1` on `di(container)`
|
|
12
|
+
|
|
13
|
+
**When:** the Container has a Slot, and `di` was given no options.
|
|
14
|
+
|
|
15
|
+
**Fix:** compute the Slots from the request, with `slots`:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
const deps = di(services, {
|
|
19
|
+
slots: ({ request }) => ({ tenant: request.headers.get('x-tenant') ?? 'public' }),
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### `Type '() => {}' is not assignable to type 'undefined'` on `slots`
|
|
24
|
+
|
|
25
|
+
**When:** you passed `slots` for a Container that has no Slot.
|
|
26
|
+
|
|
27
|
+
**Fix:** drop `slots`, which nothing would read; or declare a Slot with
|
|
28
|
+
`.slot(Token)` first.
|
|
29
|
+
|
|
30
|
+
### `` `user` is missing from the context: add a middleware that gives it before this one `` on `use(deps)`
|
|
31
|
+
|
|
32
|
+
**When:** `slots` is annotated to read `user`, and the `di` is given to a
|
|
33
|
+
`use` where no earlier middleware adds it.
|
|
34
|
+
|
|
35
|
+
**Fix:** give the middleware that adds `user` first, `alxia().use(auth).use(deps)`,
|
|
36
|
+
or let `slots` read what the base context holds.
|
|
37
|
+
|
|
38
|
+
### `` `scope` is missing from the context `` on `use(deps.expose(...))`
|
|
39
|
+
|
|
40
|
+
**When:** an `expose` stands where no `di` stands before it: the `di` is
|
|
41
|
+
missing, comes after it, or is in another group.
|
|
42
|
+
|
|
43
|
+
**Fix:** give the `di` to `use` first, on the app or in an enclosing group.
|
|
44
|
+
|
|
45
|
+
### `` `scope` is in the context with another type than this middleware reads ``
|
|
46
|
+
|
|
47
|
+
**When:** the `expose` comes from the `di` of another Container than the one
|
|
48
|
+
whose Scope is on the context.
|
|
49
|
+
|
|
50
|
+
**Fix:** expose from the `di` whose Container provides those Tokens.
|
|
51
|
+
|
|
52
|
+
### `Token 'orders' is not provided` on `expose`
|
|
53
|
+
|
|
54
|
+
**When:** an `expose` map holds a Token the Container does not provide, or
|
|
55
|
+
provides with another value type.
|
|
56
|
+
|
|
57
|
+
**Fix:** provide it in the Container given to `di`.
|
|
58
|
+
|
|
59
|
+
### `'reply' is a key of the context: expose under another name`
|
|
60
|
+
|
|
61
|
+
**When:** an `expose` map uses `scope`, or a key of the base context such as
|
|
62
|
+
`reply`, `request`, `url`, `cookies` or `set`.
|
|
63
|
+
|
|
64
|
+
**Fix:** pick another key: `deps.expose({ replies: RepliesT })`.
|
|
65
|
+
|
|
66
|
+
### `Argument of type 'SlotsReadAny' is not assignable` on `use(deps)`
|
|
67
|
+
|
|
68
|
+
**When:** `slots` reads its context as `any`: `(ctx: any) => …`. `any` would
|
|
69
|
+
let the middleware stand where what it reads is not given.
|
|
70
|
+
|
|
71
|
+
**Fix:** annotate what it reads, `({ user }: { user: User }) => …`, or leave
|
|
72
|
+
it unannotated.
|
|
73
|
+
|
|
74
|
+
### `Property 'scope' does not exist`
|
|
75
|
+
|
|
76
|
+
**When:** a route reads `scope` but is declared before the `di`'s `use`, or
|
|
77
|
+
outside the group the `di` was given to.
|
|
78
|
+
|
|
79
|
+
**Fix:** declare the route after `use(deps)`, inside its group.
|
|
80
|
+
|
|
81
|
+
## Runtime errors
|
|
82
|
+
|
|
83
|
+
### `expose('orders') ran on a request with no Scope: give its di() middleware to use() before it`
|
|
84
|
+
|
|
85
|
+
`ScopeNotMountedError`, code `DI_SCOPE_NOT_MOUNTED`. It extends `@softistx/di`'s
|
|
86
|
+
`DiError`; `token` is `undefined`, and `keys` lists the keys of the map.
|
|
87
|
+
|
|
88
|
+
**When:** an `expose` ran with no Scope on its context. The types refuse
|
|
89
|
+
that, so it is reached through a cast, or a middleware that replaced
|
|
90
|
+
`scope` with something else.
|
|
91
|
+
|
|
92
|
+
**Fix:** remove the cast, and give the `di` to `use` before the `expose`.
|
|
93
|
+
|
|
94
|
+
### `Cannot resolve Token 'orders': the Scope has been disposed`
|
|
95
|
+
|
|
96
|
+
`ScopeDisposedError`, from `@softistx/di`, code `DI_SCOPE_DISPOSED`.
|
|
97
|
+
|
|
98
|
+
**When:** something resolved from the Scope after its route had answered:
|
|
99
|
+
usually a streamed body, or a promise left running after the route.
|
|
100
|
+
|
|
101
|
+
**Fix:** resolve what the stream needs before answering. See
|
|
102
|
+
[Streaming](guide/request-scopes.md#streaming).
|
|
103
|
+
|
|
104
|
+
### `Cannot create a Scope: the Container has been disposed`
|
|
105
|
+
|
|
106
|
+
`ContainerDisposedError`, from `@softistx/di`, code `DI_CONTAINER_DISPOSED`, on
|
|
107
|
+
a request's first `resolve`.
|
|
108
|
+
|
|
109
|
+
**When:** the Container was disposed of while an app still serves from it:
|
|
110
|
+
an `onStop` of yours disposed of it on a base that is forked, or the app
|
|
111
|
+
listened again after the stop that disposed of it.
|
|
112
|
+
|
|
113
|
+
**Fix:** dispose of it through `app.plugin(deps.lifecycle)`, which waits for
|
|
114
|
+
the last app to stop, and build a new Container for an app that listens
|
|
115
|
+
again. See [Lifecycle](guide/lifecycle.md#forks).
|
|
116
|
+
|
|
117
|
+
### `@softistx/alxia-di: disposing the Scope of GET /orders failed`
|
|
118
|
+
|
|
119
|
+
Logged by the default `onDisposeError`, followed by the error, often a
|
|
120
|
+
`DisposeError` (`DI_DISPOSE_FAILED`) from `@softistx/di` holding each failure.
|
|
121
|
+
|
|
122
|
+
**When:** a scoped value's `dispose` threw. The response was sent unchanged.
|
|
123
|
+
|
|
124
|
+
**Fix:** fix the `dispose` that threw, and pass `onDisposeError` to send the
|
|
125
|
+
error to your own logger.
|
|
126
|
+
|
|
127
|
+
### Every resolve of a request rejects with the same error
|
|
128
|
+
|
|
129
|
+
**When:** `slots` threw or rejected. The Scope was never created, so each
|
|
130
|
+
`resolve` of that request rejects with that error, and nothing is disposed
|
|
131
|
+
of.
|
|
132
|
+
|
|
133
|
+
**Fix:** make `slots` total (default a missing header), or refuse the
|
|
134
|
+
request in an earlier middleware, before anything resolves.
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@softistx/alxia-di",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Dependency injection for alxia on @softistx/di: a lazy Scope per request, disposed when it ends, and typed values exposed to the routes that read them",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"docs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"package.json",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/softistx/alxia.git",
|
|
27
|
+
"directory": "packages/di"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"registry": "https://registry.npmjs.org",
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun run ../../build.ts",
|
|
35
|
+
"test": "bun test src",
|
|
36
|
+
"typecheck": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"alxia": {
|
|
39
|
+
"entrypoints": [
|
|
40
|
+
"src/index.ts"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@softistx/alxia": "^0.28.0",
|
|
45
|
+
"@softistx/di": "^0.3.1",
|
|
46
|
+
"@types/bun": "^1.4.4"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@softistx/alxia": "^0.28.0",
|
|
50
|
+
"@softistx/di": "^0.3.1",
|
|
51
|
+
"typescript": "^6.0.3 || ^7.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|