@softistx/alxia-context-storage 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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,102 @@
1
- # Temporary Holding Version
1
+ # @softistx/alxia-context-storage
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Moved from `@alxia/context-storage`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
4
+
5
+ The request's context, anywhere it runs — a service, a repository, a logger
6
+ three calls down — without passing it: [alxia](https://www.npmjs.com/package/@softistx/alxia)'s
7
+ `hono/context-storage`, on `AsyncLocalStorage`, **typed by the app**. No
8
+ dependency.
9
+
10
+ ```sh
11
+ bun add @softistx/alxia-context-storage @softistx/alxia
12
+ bun add -d typescript
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { alxia } from '@softistx/alxia';
19
+ import { contextStorage } from '@softistx/alxia-context-storage';
20
+ import { session } from '@softistx/alxia-janus';
21
+
22
+ const base = alxia().decorate({ db }).use(session(auth, { required: true }));
23
+
24
+ export const requestContext = contextStorage<typeof base>();
25
+
26
+ const app = base
27
+ .use(requestContext)
28
+ .get('/orders', async ({ reply }) => reply(200, await listOrders()));
29
+ ```
30
+
31
+ ```ts
32
+ // orders.ts — no context passed down
33
+ import { requestContext } from './app';
34
+
35
+ export async function listOrders() {
36
+ const { db, user, set } = requestContext.context(); // typed: user, db
37
+ set.headers.set('cache-control', 'private');
38
+ return db.orders.forUser(user.id);
39
+ }
40
+ ```
41
+
42
+ The context holds through every `await`, timer and promise of the
43
+ request, and never leaks into another's: twenty concurrent requests read
44
+ twenty contexts.
45
+
46
+ With `@softistx/alxia`'s `Register` naming `base`, `contextStorage()` needs no
47
+ type argument: it reads the registered context, `AppContext`. Either way
48
+ the app that mounts it must give that context, a compile error otherwise:
49
+
50
+ ```ts
51
+ declare module '@softistx/alxia' {
52
+ interface Register {
53
+ context: typeof base;
54
+ }
55
+ }
56
+
57
+ export const requestContext = contextStorage(); // context(): AppContext
58
+ base.use(requestContext); // ok
59
+ alxia().use(requestContext); // compile error: Property 'db' is missing in type 'BaseContext & Empty'
60
+ ```
61
+
62
+ Requiring that context of the app is new in 0.4.0: a middleware used on an app
63
+ that does not give it, which read `undefined` at runtime, is now a compile
64
+ error ([Upgrading](https://github.com/softistx/alxia/blob/develop/packages/core/docs/upgrading.md#the-context-registered-once-register-and-defineroutes)).
65
+
66
+ ## Reading it
67
+
68
+ | | |
69
+ | --- | --- |
70
+ | `requestContext.context()` | the route's context, typed by the app the middleware was given: the request, `set`, `reply`, and what every middleware before it added. Throws outside |
71
+ | `requestContext.tryContext()` | the same, or `undefined`: code that runs in and out of requests |
72
+ | `getContext<Ctx>()`, `tryGetContext<Ctx>()` | untyped, as `hono/context-storage`'s: `Ctx` is yours to state |
73
+ | `getRequestContext()`, `tryGetRequestContext()` | the request as a middleware after it sees it — in a 404 too — with the `route` it reached (`undefined` when none) and its `error`; the `try` form returns `undefined` outside a request |
74
+ | `runWithContext(ctx, work)` | runs `work` with a context: a job, a queue consumer, a test of a service |
75
+
76
+ Give it to `use` before the routes whose code reads it, and before the
77
+ middlewares that read the context: it runs on every request the app takes,
78
+ a 404 included. `getRequestContext()` works in every middleware after it;
79
+ `getContext()` only in a request that reached a route. Outside a request,
80
+ or where the middleware did not run (a route declared before it),
81
+ `getContext()` throws a `ContextStorageError` coded `OUTSIDE_REQUEST`; in
82
+ a request that reached no route, `NOT_ROUTED`.
83
+
84
+ Pass it to `app.use` called: `use(contextStorage)`, uncalled, is refused by
85
+ `tsc` (`TS2345`), and throws where it is declared
86
+ ([troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/context-storage/docs/troubleshooting.md#use-argument-1-looks-like-a-factory-contextstorage-call-it-usecontextstorage)).
87
+
88
+ ## API
89
+
90
+ | export | |
91
+ | --- | --- |
92
+ | `contextStorage<App>()` | the middleware, given to `app.use`, with `context()` and `tryContext()` typed by `App` — by default the app `@softistx/alxia`'s `Register` names, `BaseContext` when none — and required of the app that mounts it |
93
+ | `StoredContext<App>` | what `context()` returns: `ContextOf<App>`, or `BaseContext` when `App` is no app |
94
+ | `ContextStorageMiddleware<App>` | its type: a middleware with `context()` and `tryContext()` |
95
+ | `getContext`, `tryGetContext`, `getRequestContext`, `tryGetRequestContext`, `runWithContext` | the store, untyped |
96
+ | `ContextStorageError`, `ContextStorageErrorCode` | why there is no context |
97
+
98
+ ## Documentation
99
+
100
+ - [Guide](https://github.com/softistx/alxia/tree/develop/packages/context-storage/docs): what the middleware stores and when, reading it from a service or a logger, its typing, where it sits among the other middlewares, what a timer or a detached callback sees, and jobs and tests with `runWithContext`.
101
+ - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/context-storage/docs/troubleshooting.md): a `ContextStorageError`, the `TypeError` of `use(contextStorage)`, or a `tsc` error, and what to do about it.
102
+ - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/context-storage/docs/roadmap.md): what is coming, and what is not planned.
@@ -0,0 +1,2 @@
1
+ export { ContextStorageError, type ContextStorageErrorCode, type ContextStorageMiddleware, contextStorage, getContext, getRequestContext, runWithContext, type StoredContext, tryGetContext, tryGetRequestContext, } from './storage';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,mBAAmB,EACnB,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,EAC7B,cAAc,EACd,UAAU,EACV,iBAAiB,EACjB,cAAc,EACd,KAAK,aAAa,EAClB,aAAa,EACb,oBAAoB,GACpB,MAAM,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,71 @@
1
+ // src/storage.ts
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import {
4
+ defineMiddleware,
5
+ markFactory,
6
+ settle
7
+ } from "@softistx/alxia";
8
+
9
+ class ContextStorageError extends Error {
10
+ name = "ContextStorageError";
11
+ code;
12
+ constructor(code) {
13
+ super(code === "OUTSIDE_REQUEST" ? "getContext(): called outside a request — use tryGetContext(), or runWithContext() in a job or a test" : "getContext(): this request reached no route declared after contextStorage() — use it earlier, or getRequestContext()");
14
+ this.code = code;
15
+ }
16
+ }
17
+ var storage = new AsyncLocalStorage;
18
+ function getContext() {
19
+ const holder = storage.getStore();
20
+ if (holder === undefined)
21
+ throw new ContextStorageError("OUTSIDE_REQUEST");
22
+ if (holder.ctx === undefined)
23
+ throw new ContextStorageError("NOT_ROUTED");
24
+ return holder.ctx;
25
+ }
26
+ function tryGetContext() {
27
+ return storage.getStore()?.ctx;
28
+ }
29
+ function getRequestContext() {
30
+ const holder = storage.getStore();
31
+ if (holder === undefined)
32
+ throw new ContextStorageError("OUTSIDE_REQUEST");
33
+ return holder.request;
34
+ }
35
+ function tryGetRequestContext() {
36
+ return storage.getStore()?.request;
37
+ }
38
+ function runWithContext(ctx, work) {
39
+ return storage.run({ request: ctx, ctx }, work);
40
+ }
41
+ function contextStorage(...uncalled) {
42
+ if (uncalled.length > 0) {
43
+ throw new TypeError("contextStorage is a factory: use(contextStorage()), not use(contextStorage)");
44
+ }
45
+ const middleware = defineMiddleware(function contextStorage(ctx, next) {
46
+ const routed = ctx.route === undefined ? undefined : ctx;
47
+ const current = storage.getStore();
48
+ if (current !== undefined && current.request.url === ctx.url) {
49
+ current.ctx = routed ?? current.ctx;
50
+ return settle(ctx, next());
51
+ }
52
+ return storage.run({ request: ctx, ctx: routed }, () => settle(ctx, next()));
53
+ });
54
+ return Object.assign(middleware, {
55
+ context: () => getContext(),
56
+ tryContext: () => tryGetContext()
57
+ });
58
+ }
59
+ markFactory(contextStorage);
60
+ export {
61
+ ContextStorageError,
62
+ contextStorage,
63
+ getContext,
64
+ getRequestContext,
65
+ runWithContext,
66
+ tryGetContext,
67
+ tryGetRequestContext
68
+ };
69
+
70
+ //# debugId=B117479A08EB86F864756E2164756E21
71
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/storage.ts"],
4
+ "sourcesContent": [
5
+ "import { AsyncLocalStorage } from 'node:async_hooks';\nimport {\n\ttype BaseContext,\n\ttype ContextOf,\n\tdefineMiddleware,\n\ttype Empty,\n\ttype Middleware,\n\ttype Mounted,\n\tmarkFactory,\n\ttype RegisteredBase,\n\ttype RequestContext,\n\ttype RequiresOf,\n\tsettle,\n} from '@softistx/alxia';\n\n/** Why there is no context to read. */\nexport type ContextStorageErrorCode =\n\t/** Called outside any request: at startup, in a job, after the response. */\n\t| 'OUTSIDE_REQUEST'\n\t/** In a request `contextStorage()` ran on, but that reached no route: a 404, a 405. A route it did not run on is `OUTSIDE_REQUEST`. */\n\t| 'NOT_ROUTED';\n\nexport class ContextStorageError extends Error {\n\toverride readonly name = 'ContextStorageError';\n\treadonly code: ContextStorageErrorCode;\n\n\tconstructor(code: ContextStorageErrorCode) {\n\t\tsuper(\n\t\t\tcode === 'OUTSIDE_REQUEST'\n\t\t\t\t? 'getContext(): called outside a request — use tryGetContext(), or runWithContext() in a job or a test'\n\t\t\t\t: 'getContext(): this request reached no route declared after contextStorage() — use it earlier, or getRequestContext()',\n\t\t);\n\t\tthis.code = code;\n\t}\n}\n\ninterface Holder {\n\treadonly request: RequestContext;\n\tctx: BaseContext | undefined;\n}\n\n/**\n * One store for the process: every `contextStorage()` writes to it, and\n * `getContext()` reads it wherever it is called — the way `hono/context-storage`\n * works, so code written against one ports to the other.\n */\nconst storage = new AsyncLocalStorage<Holder>();\n\n/**\n * The context of the route the current request reached: what its handler\n * reads — the request, `set`, `reply`, and what every hook before it added.\n * Throws a `ContextStorageError` outside a route declared after\n * `contextStorage()`.\n *\n * `Ctx` types what the hooks added; prefer the typed `context()` of the middleware\n * itself, typed by the app.\n */\nexport function getContext<Ctx extends object = Empty>(): BaseContext & Ctx {\n\tconst holder = storage.getStore();\n\tif (holder === undefined) throw new ContextStorageError('OUTSIDE_REQUEST');\n\tif (holder.ctx === undefined) throw new ContextStorageError('NOT_ROUTED');\n\treturn holder.ctx as BaseContext & Ctx;\n}\n\n/** `getContext()`, or `undefined` where it would throw: code that runs in and out of requests. */\nexport function tryGetContext<Ctx extends object = Empty>():\n\t| (BaseContext & Ctx)\n\t| undefined {\n\treturn storage.getStore()?.ctx as (BaseContext & Ctx) | undefined;\n}\n\n/**\n * The request as a middleware sees it — in a 404 too — with the route it\n * reached and the error it failed with.\n */\nexport function getRequestContext(): RequestContext {\n\tconst holder = storage.getStore();\n\tif (holder === undefined) throw new ContextStorageError('OUTSIDE_REQUEST');\n\treturn holder.request;\n}\n\n/** `getRequestContext()`, or `undefined` outside a request. */\nexport function tryGetRequestContext(): RequestContext | undefined {\n\treturn storage.getStore()?.request;\n}\n\n/**\n * Runs `work` with `ctx` as the current context: a job, a queue consumer,\n * a test calling a service that reads `getContext()`.\n */\nexport function runWithContext<T>(ctx: BaseContext, work: () => T): T {\n\treturn storage.run({ request: ctx, ctx }, work);\n}\n\n/**\n * The middleware, and its context typed by the app it follows. It\n * requires that context of the app that uses it, beyond the base context:\n * `app.use` on an app that does not give it is a compile error.\n */\nexport type ContextStorageMiddleware<App> = Middleware<\n\tRequiresOf<StoredContext<App>, 'context'>,\n\tPromise<Response>\n> & {\n\t/** `getContext()`, typed by `App`. */\n\tcontext(): StoredContext<App>;\n\t/** `tryGetContext()`, typed by `App`. */\n\ttryContext(): StoredContext<App> | undefined;\n};\n\n/** What `context()` reads: the context of `App`, or the base context when `App` is no app. */\nexport type StoredContext<App> = [ContextOf<App>] extends [never]\n\t? BaseContext\n\t: Mounted<ContextOf<App>>;\n\n/**\n * The request's context, anywhere it runs, as a middleware: from the\n * routes declared after it, every function their handlers call — however\n * deep, through every `await` and timer — reads it with `getContext()`,\n * without it being passed down; the answer to an error too, a try/catch\n * middleware's included. Give it to `use` before the middlewares whose errors\n * your own middleware answers: what the rest throws is answered inside\n * it, as the route would.\n *\n * Typed by the app it is used on: give the plugin that app's type, and its\n * `context()` returns what its routes read — the `user` a session derived, the\n * `db` decorated. Given none, the app `Register` names in `@softistx/alxia`\n * (`BaseContext` when nothing is registered). Either way the app that uses\n * it must give that context: using it before is a compile error.\n *\n * ```ts\n * const base = alxia().decorate({ db }).use(session(auth, { required: true }));\n * export const requestContext = contextStorage<typeof base>();\n * const app = base.use(requestContext).get('/orders', ({ reply }) => reply(200, listOrders()));\n *\n * // orders.ts — no context passed\n * export const listOrders = () => {\n * const { db, user } = requestContext.context();\n * return db.orders.forUser(user.id);\n * };\n * ```\n */\nexport function contextStorage<App = RegisteredBase>(\n\t...uncalled: readonly never[]\n): ContextStorageMiddleware<App> {\n\tif (uncalled.length > 0) {\n\t\t// `use(contextStorage)`: the factory runs as the middleware, handed\n\t\t// each request's context, and would store none of them.\n\t\tthrow new TypeError(\n\t\t\t'contextStorage is a factory: use(contextStorage()), not use(contextStorage)',\n\t\t);\n\t}\n\tconst middleware = defineMiddleware(function contextStorage(ctx, next) {\n\t\t// A route's context; none for a request no route matches.\n\t\tconst routed = ctx.route === undefined ? undefined : ctx;\n\t\tconst current = storage.getStore();\n\t\t// A second one, on the same request: the context it reaches is the route's.\n\t\tif (current !== undefined && current.request.url === ctx.url) {\n\t\t\tcurrent.ctx = routed ?? current.ctx;\n\t\t\treturn settle(ctx, next());\n\t\t}\n\t\treturn storage.run({ request: ctx, ctx: routed }, () =>\n\t\t\tsettle(ctx, next()),\n\t\t);\n\t});\n\treturn Object.assign(middleware, {\n\t\tcontext: () => getContext(),\n\t\ttryContext: () => tryGetContext(),\n\t}) as unknown as ContextStorageMiddleware<App>;\n}\n\nmarkFactory(contextStorage);\n"
6
+ ],
7
+ "mappings": ";AAAA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,MAAM,4BAA4B,MAAM;AAAA,EAC5B,OAAO;AAAA,EAChB;AAAA,EAET,WAAW,CAAC,MAA+B;AAAA,IAC1C,MACC,SAAS,oBACN,yGACA,sHACJ;AAAA,IACA,KAAK,OAAO;AAAA;AAEd;AAYA,IAAM,UAAU,IAAI;AAWb,SAAS,UAAsC,GAAsB;AAAA,EAC3E,MAAM,SAAS,QAAQ,SAAS;AAAA,EAChC,IAAI,WAAW;AAAA,IAAW,MAAM,IAAI,oBAAoB,iBAAiB;AAAA,EACzE,IAAI,OAAO,QAAQ;AAAA,IAAW,MAAM,IAAI,oBAAoB,YAAY;AAAA,EACxE,OAAO,OAAO;AAAA;AAIR,SAAS,aAAyC,GAE5C;AAAA,EACZ,OAAO,QAAQ,SAAS,GAAG;AAAA;AAOrB,SAAS,iBAAiB,GAAmB;AAAA,EACnD,MAAM,SAAS,QAAQ,SAAS;AAAA,EAChC,IAAI,WAAW;AAAA,IAAW,MAAM,IAAI,oBAAoB,iBAAiB;AAAA,EACzE,OAAO,OAAO;AAAA;AAIR,SAAS,oBAAoB,GAA+B;AAAA,EAClE,OAAO,QAAQ,SAAS,GAAG;AAAA;AAOrB,SAAS,cAAiB,CAAC,KAAkB,MAAkB;AAAA,EACrE,OAAO,QAAQ,IAAI,EAAE,SAAS,KAAK,IAAI,GAAG,IAAI;AAAA;AAkDxC,SAAS,cAAoC,IAChD,UAC6B;AAAA,EAChC,IAAI,SAAS,SAAS,GAAG;AAAA,IAGxB,MAAM,IAAI,UACT,6EACD;AAAA,EACD;AAAA,EACA,MAAM,aAAa,iBAAiB,SAAS,cAAc,CAAC,KAAK,MAAM;AAAA,IAEtE,MAAM,SAAS,IAAI,UAAU,YAAY,YAAY;AAAA,IACrD,MAAM,UAAU,QAAQ,SAAS;AAAA,IAEjC,IAAI,YAAY,aAAa,QAAQ,QAAQ,QAAQ,IAAI,KAAK;AAAA,MAC7D,QAAQ,MAAM,UAAU,QAAQ;AAAA,MAChC,OAAO,OAAO,KAAK,KAAK,CAAC;AAAA,IAC1B;AAAA,IACA,OAAO,QAAQ,IAAI,EAAE,SAAS,KAAK,KAAK,OAAO,GAAG,MACjD,OAAO,KAAK,KAAK,CAAC,CACnB;AAAA,GACA;AAAA,EACD,OAAO,OAAO,OAAO,YAAY;AAAA,IAChC,SAAS,MAAM,WAAW;AAAA,IAC1B,YAAY,MAAM,cAAc;AAAA,EACjC,CAAC;AAAA;AAGF,YAAY,cAAc;",
8
+ "debugId": "B117479A08EB86F864756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,78 @@
1
+ import { type BaseContext, type ContextOf, type Empty, type Middleware, type Mounted, type RegisteredBase, type RequestContext, type RequiresOf } from '@softistx/alxia';
2
+ /** Why there is no context to read. */
3
+ export type ContextStorageErrorCode =
4
+ /** Called outside any request: at startup, in a job, after the response. */
5
+ 'OUTSIDE_REQUEST'
6
+ /** In a request `contextStorage()` ran on, but that reached no route: a 404, a 405. A route it did not run on is `OUTSIDE_REQUEST`. */
7
+ | 'NOT_ROUTED';
8
+ export declare class ContextStorageError extends Error {
9
+ readonly name = "ContextStorageError";
10
+ readonly code: ContextStorageErrorCode;
11
+ constructor(code: ContextStorageErrorCode);
12
+ }
13
+ /**
14
+ * The context of the route the current request reached: what its handler
15
+ * reads — the request, `set`, `reply`, and what every hook before it added.
16
+ * Throws a `ContextStorageError` outside a route declared after
17
+ * `contextStorage()`.
18
+ *
19
+ * `Ctx` types what the hooks added; prefer the typed `context()` of the middleware
20
+ * itself, typed by the app.
21
+ */
22
+ export declare function getContext<Ctx extends object = Empty>(): BaseContext & Ctx;
23
+ /** `getContext()`, or `undefined` where it would throw: code that runs in and out of requests. */
24
+ export declare function tryGetContext<Ctx extends object = Empty>(): (BaseContext & Ctx) | undefined;
25
+ /**
26
+ * The request as a middleware sees it — in a 404 too — with the route it
27
+ * reached and the error it failed with.
28
+ */
29
+ export declare function getRequestContext(): RequestContext;
30
+ /** `getRequestContext()`, or `undefined` outside a request. */
31
+ export declare function tryGetRequestContext(): RequestContext | undefined;
32
+ /**
33
+ * Runs `work` with `ctx` as the current context: a job, a queue consumer,
34
+ * a test calling a service that reads `getContext()`.
35
+ */
36
+ export declare function runWithContext<T>(ctx: BaseContext, work: () => T): T;
37
+ /**
38
+ * The middleware, and its context typed by the app it follows. It
39
+ * requires that context of the app that uses it, beyond the base context:
40
+ * `app.use` on an app that does not give it is a compile error.
41
+ */
42
+ export type ContextStorageMiddleware<App> = Middleware<RequiresOf<StoredContext<App>, 'context'>, Promise<Response>> & {
43
+ /** `getContext()`, typed by `App`. */
44
+ context(): StoredContext<App>;
45
+ /** `tryGetContext()`, typed by `App`. */
46
+ tryContext(): StoredContext<App> | undefined;
47
+ };
48
+ /** What `context()` reads: the context of `App`, or the base context when `App` is no app. */
49
+ export type StoredContext<App> = [ContextOf<App>] extends [never] ? BaseContext : Mounted<ContextOf<App>>;
50
+ /**
51
+ * The request's context, anywhere it runs, as a middleware: from the
52
+ * routes declared after it, every function their handlers call — however
53
+ * deep, through every `await` and timer — reads it with `getContext()`,
54
+ * without it being passed down; the answer to an error too, a try/catch
55
+ * middleware's included. Give it to `use` before the middlewares whose errors
56
+ * your own middleware answers: what the rest throws is answered inside
57
+ * it, as the route would.
58
+ *
59
+ * Typed by the app it is used on: give the plugin that app's type, and its
60
+ * `context()` returns what its routes read — the `user` a session derived, the
61
+ * `db` decorated. Given none, the app `Register` names in `@softistx/alxia`
62
+ * (`BaseContext` when nothing is registered). Either way the app that uses
63
+ * it must give that context: using it before is a compile error.
64
+ *
65
+ * ```ts
66
+ * const base = alxia().decorate({ db }).use(session(auth, { required: true }));
67
+ * export const requestContext = contextStorage<typeof base>();
68
+ * const app = base.use(requestContext).get('/orders', ({ reply }) => reply(200, listOrders()));
69
+ *
70
+ * // orders.ts — no context passed
71
+ * export const listOrders = () => {
72
+ * const { db, user } = requestContext.context();
73
+ * return db.orders.forUser(user.id);
74
+ * };
75
+ * ```
76
+ */
77
+ export declare function contextStorage<App = RegisteredBase>(...uncalled: readonly never[]): ContextStorageMiddleware<App>;
78
+ //# sourceMappingURL=storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,WAAW,EAChB,KAAK,SAAS,EAEd,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,OAAO,EAEZ,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,UAAU,EAEf,MAAM,iBAAiB,CAAC;AAEzB,uCAAuC;AACvC,MAAM,MAAM,uBAAuB;AAClC,4EAA4E;AAC1E,iBAAiB;AACnB,uIAAuI;GACrI,YAAY,CAAC;AAEhB,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,SAAkB,IAAI,yBAAyB;IAC/C,QAAQ,CAAC,IAAI,EAAE,uBAAuB,CAAC;gBAE3B,IAAI,EAAE,uBAAuB;CAQzC;AAcD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,GAAG,SAAS,MAAM,GAAG,KAAK,KAAK,WAAW,GAAG,GAAG,CAK1E;AAED,kGAAkG;AAClG,wBAAgB,aAAa,CAAC,GAAG,SAAS,MAAM,GAAG,KAAK,KACrD,CAAC,WAAW,GAAG,GAAG,CAAC,GACnB,SAAS,CAEX;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,CAIlD;AAED,+DAA+D;AAC/D,wBAAgB,oBAAoB,IAAI,cAAc,GAAG,SAAS,CAEjE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAEpE;AAED;;;;GAIG;AACH,MAAM,MAAM,wBAAwB,CAAC,GAAG,IAAI,UAAU,CACrD,UAAU,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,SAAS,CAAC,EACzC,OAAO,CAAC,QAAQ,CAAC,CACjB,GAAG;IACH,sCAAsC;IACtC,OAAO,IAAI,aAAa,CAAC,GAAG,CAAC,CAAC;IAC9B,yCAAyC;IACzC,UAAU,IAAI,aAAa,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;CAC7C,CAAC;AAEF,8FAA8F;AAC9F,MAAM,MAAM,aAAa,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GAC9D,WAAW,GACX,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,cAAc,CAAC,GAAG,GAAG,cAAc,EAClD,GAAG,QAAQ,EAAE,SAAS,KAAK,EAAE,GAC3B,wBAAwB,CAAC,GAAG,CAAC,CAyB/B"}
package/docs/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # @softistx/alxia-context-storage documentation
2
+
3
+ The [package README](../README.md) is the short version. This folder is
4
+ the long one: what the middleware stores and when, how to read it from a
5
+ service, a repository or a logger, how its type follows the app, where it
6
+ sits among an app's middlewares, and what a timer or a detached callback sees.
7
+
8
+ | Page | Read it when |
9
+ | --- | --- |
10
+ | [Guide](guide.md) | reading the request's context from code the handler calls, typing it, placing the middleware among the others, running a job or a test with a context, or wondering what a timer sees |
11
+ | [Troubleshooting](troubleshooting.md) | `getContext()` threw a `ContextStorageError`, a service read the wrong context or none, `use(contextStorage)` threw a `TypeError`, or `tsc` refused the middleware or its type |
12
+ | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
package/docs/guide.md ADDED
@@ -0,0 +1,454 @@
1
+ # Guide
2
+
3
+ This page covers what `contextStorage()` stores and when, how code outside
4
+ a handler reads it, how its type follows the app, where the middleware sits
5
+ among an app's middlewares, and what `AsyncLocalStorage` does and does not carry.
6
+
7
+ ```ts
8
+ import { alxia } from '@softistx/alxia';
9
+ import { contextStorage } from '@softistx/alxia-context-storage';
10
+
11
+ const base = alxia()
12
+ .decorate({ greeting: 'Hello' })
13
+ .derive(({ request }) => ({ user: request.headers.get('x-user') ?? 'anonymous' }));
14
+
15
+ const requestContext = contextStorage<typeof base>();
16
+
17
+ // three calls down, no context passed
18
+ function greet(): string {
19
+ const { greeting, user } = requestContext.context(); // typed: greeting, user
20
+ return `${greeting}, ${user}`;
21
+ }
22
+
23
+ const app = base.use(requestContext).get('/hello', ({ reply }) => reply(200, greet()));
24
+
25
+ app.listen(3000);
26
+ ```
27
+
28
+ `curl -H 'x-user: Ada' localhost:3000/hello` answers `Hello, Ada`. `greet`
29
+ could live in another module, behind any number of `await`s: it reads the
30
+ context of the request that called it, and never another's.
31
+
32
+ ## The signature
33
+
34
+ ```ts
35
+ // `uncalled` takes nothing: it makes `use(contextStorage)` a compile error.
36
+ // `App` defaults to the app `Register` names in `@softistx/alxia` (`RegisteredBase`)
37
+ function contextStorage<App = RegisteredBase>(...uncalled: readonly never[]): ContextStorageMiddleware<App>;
38
+
39
+ // A middleware: it requires `App`'s context of the app that mounts it.
40
+ type ContextStorageMiddleware<App> = Middleware<
41
+ RequiresOf<StoredContext<App>, 'context'>,
42
+ Promise<Response>
43
+ > & {
44
+ context(): StoredContext<App>;
45
+ tryContext(): StoredContext<App> | undefined;
46
+ };
47
+
48
+ // What `context()` returns: `App`'s context, or `BaseContext` when `App` is no app
49
+ type StoredContext<App> = [ContextOf<App>] extends [never] ? BaseContext : Mounted<ContextOf<App>>;
50
+
51
+ function getContext<Ctx extends object = Empty>(): BaseContext & Ctx;
52
+ function tryGetContext<Ctx extends object = Empty>(): (BaseContext & Ctx) | undefined;
53
+ function getRequestContext(): RequestContext;
54
+ function tryGetRequestContext(): RequestContext | undefined;
55
+ function runWithContext<T>(ctx: BaseContext, work: () => T): T;
56
+
57
+ class ContextStorageError extends Error {
58
+ readonly name: 'ContextStorageError';
59
+ readonly code: ContextStorageErrorCode;
60
+ }
61
+
62
+ type ContextStorageErrorCode = 'OUTSIDE_REQUEST' | 'NOT_ROUTED';
63
+ ```
64
+
65
+ `contextStorage()` returns a middleware: pass it to `app.use`, called — `use(contextStorage)` fails `tsc` with `TS2345`, and throws where it is declared ([troubleshooting](troubleshooting.md#use-argument-1-looks-like-a-factory-contextstorage-call-it-usecontextstorage)). It adds
66
+ nothing to the app's type, but it requires `StoredContext<App>` of the app
67
+ that mounts it: `app.use` on an app that does not give that context is a compile
68
+ error. `BaseContext`, `RequestContext`, `ContextOf`, `RegisteredBase`,
69
+ `Middleware`, `RequiresOf` and `Mounted` come from `@softistx/alxia`.
70
+
71
+ | Export | Returns | Where it would have nothing |
72
+ | --- | --- | --- |
73
+ | `requestContext.context()` | the route's context, typed by `App` | throws a `ContextStorageError` |
74
+ | `requestContext.tryContext()` | the same | `undefined` |
75
+ | `getContext<Ctx>()` | the route's context, as `BaseContext & Ctx`: `Ctx` is yours to state | throws a `ContextStorageError` |
76
+ | `tryGetContext<Ctx>()` | the same | `undefined` |
77
+ | `getRequestContext()` | the request as a middleware sees it: `request`, `url`, `ip`, `server`, `route` (`undefined` when no route matched) and, once a route has failed, `error` | throws a `ContextStorageError` coded `OUTSIDE_REQUEST` |
78
+ | `tryGetRequestContext()` | the same | `undefined` |
79
+ | `runWithContext(ctx, work)` | what `work` returns, with `ctx` as the current context while it runs | — |
80
+
81
+ There is one store per copy of the package: every `contextStorage()` writes
82
+ to it, and `getContext()` reads it wherever it is called. Two of them on one
83
+ app read the same context.
84
+
85
+ ## What it stores, and when
86
+
87
+ `contextStorage()` is a middleware: it opens a store around the rest of the
88
+ chain, holding the request's context, and records the route's context in
89
+ it when the request reached a route. A `use()` on the app runs on every
90
+ request, in declaration order, so what each function reads depends on
91
+ whether the middleware ran on the request, and where the code runs
92
+ relative to it:
93
+
94
+ | Code running in | `getRequestContext()` | `tryGetRequestContext()` | `getContext()` | `tryGetContext()` |
95
+ | --- | --- | --- | --- | --- |
96
+ | a middleware declared **before** it | throws `OUTSIDE_REQUEST` | `undefined` | throws `OUTSIDE_REQUEST` | `undefined` |
97
+ | a middleware after it, on a request a route matched | the request, with its `route` | the same | the route's context, **before validation**: no `params`, `query` or `body` yet, and without what later middlewares add | the same |
98
+ | a middleware after it, on a request no route matched (a 404, a 405) | the request, `route` `undefined` | the same | throws `NOT_ROUTED` | `undefined` |
99
+ | the handler of a route the middleware ran on, and everything it calls | the request | the same | the context the handler receives, with what the middlewares added | the same |
100
+ | a middleware that catches an error, after it | the request, with `route` and `error` | the same | the same context | the same |
101
+ | a route declared **before** it, or outside the `group` it is used in | throws `OUTSIDE_REQUEST` | `undefined` | throws `OUTSIDE_REQUEST` | `undefined` |
102
+ | a socket's handlers (`open`, `message`, `close`) | throws `OUTSIDE_REQUEST` | `undefined` | throws `OUTSIDE_REQUEST` | `undefined` |
103
+ | startup, a job, a timer started at startup | throws `OUTSIDE_REQUEST` | `undefined` | throws `OUTSIDE_REQUEST` | `undefined` |
104
+
105
+ `contextStorage()` settles `next()`: an error the rest of the chain throws
106
+ is answered inside the store, as the route would answer it, so a
107
+ middleware that reads the context while answering an error still finds it.
108
+
109
+ The two errors carry these messages:
110
+
111
+ | `code` | `message` |
112
+ | --- | --- |
113
+ | `OUTSIDE_REQUEST` | `getContext(): called outside a request — use tryGetContext(), or runWithContext() in a job or a test` |
114
+ | `NOT_ROUTED` | `getContext(): this request reached no route declared after contextStorage() — use it earlier, or getRequestContext()` |
115
+
116
+ Thrown inside a route, either one answers a `500 {"error":"internal"}` and
117
+ is logged, like any other error. `code` tells them apart:
118
+
119
+ ```ts
120
+ import { ContextStorageError, getContext } from '@softistx/alxia-context-storage';
121
+
122
+ try {
123
+ getContext();
124
+ } catch (error) {
125
+ if (error instanceof ContextStorageError) console.log(error.code); // 'OUTSIDE_REQUEST'
126
+ }
127
+ ```
128
+
129
+ Code that runs both in and out of requests uses `tryContext()`,
130
+ `tryGetContext()` or `tryGetRequestContext()` instead of catching.
131
+
132
+ The context is the whole of what the handler reads: the request, `set` to
133
+ add a header or a cookie to the response, `reply` and `redirect`, and what
134
+ every middleware added — so a service three calls down can set a response header,
135
+ as `listOrders` does below.
136
+
137
+ ## Reading it from outside the handler
138
+
139
+ Keep the app's base and the middleware in a module of their own, and import it
140
+ from every service, repository or logger that reads it. The handlers
141
+ then call those without passing anything down.
142
+
143
+ ```ts
144
+ // context.ts
145
+ import { alxia } from '@softistx/alxia';
146
+ import { contextStorage } from '@softistx/alxia-context-storage';
147
+
148
+ export interface Order {
149
+ readonly id: number;
150
+ readonly userId: number;
151
+ readonly total: number;
152
+ }
153
+
154
+ const db = { orders: [{ id: 1, userId: 1, total: 42 }] as Order[] };
155
+ const users = new Map([['Bearer ada', { id: 1, name: 'Ada' }]]);
156
+
157
+ export const base = alxia()
158
+ .decorate({ db })
159
+ .derive(({ request, reply }) => {
160
+ const user = users.get(request.headers.get('authorization') ?? '');
161
+ return user ? { user } : reply(401, { error: 'unauthenticated' as const });
162
+ });
163
+
164
+ export const requestContext = contextStorage<typeof base>();
165
+ ```
166
+
167
+ ```ts
168
+ // orders.ts
169
+ import { requestContext } from './context';
170
+
171
+ export async function listOrders() {
172
+ const { db, user, set } = requestContext.context();
173
+ set.headers.set('cache-control', 'private');
174
+ return db.orders.filter((order) => order.userId === user.id);
175
+ }
176
+ ```
177
+
178
+ ```ts
179
+ // app.ts
180
+ import { base, requestContext } from './context';
181
+ import { listOrders } from './orders';
182
+
183
+ export const app = base
184
+ .use(requestContext)
185
+ .get('/orders', async ({ reply }) => reply(200, await listOrders()));
186
+ ```
187
+
188
+ A logger is the code that runs in and out of requests: at startup, in a 404,
189
+ in a route. `tryGetRequestContext()` gives it the request wherever the
190
+ middleware ran, and `tryContext()` the user where a route was reached:
191
+
192
+ ```ts
193
+ // log.ts
194
+ import { tryGetRequestContext } from '@softistx/alxia-context-storage';
195
+ import { requestContext } from './context';
196
+
197
+ export function log(message: string): void {
198
+ const request = tryGetRequestContext(); // undefined outside a request
199
+ console.log(
200
+ JSON.stringify({
201
+ message,
202
+ method: request?.request.method,
203
+ route: request?.route,
204
+ user: requestContext.tryContext()?.user.id,
205
+ }),
206
+ );
207
+ }
208
+ ```
209
+
210
+ `log('listing orders')` from `listOrders` prints the method, `/orders` and
211
+ the user's id; from startup, the message alone.
212
+
213
+ ## Typing it
214
+
215
+ `contextStorage<App>()` takes the type of an app, and `context()` and `tryContext()`
216
+ return what a route declared next on that app would read: `ContextOf<App>`.
217
+
218
+ | `App` | `context()` returns |
219
+ | --- | --- |
220
+ | none: `contextStorage()` | the context `@softistx/alxia`'s `Register` names, `AppContext`; with nothing registered, `BaseContext`: the request, `set`, `reply`, `redirect`, `route`, `pathParams` |
221
+ | `typeof base` | `ContextOf<typeof base>`: `BaseContext` plus everything `base`'s `decorate`, `derive` and middlewares added |
222
+
223
+ ```ts
224
+ import { alxia } from '@softistx/alxia';
225
+ import { contextStorage } from '@softistx/alxia-context-storage';
226
+
227
+ const base = alxia()
228
+ .decorate({ greeting: 'Hello' })
229
+ .derive(({ request }) => ({ user: request.headers.get('x-user') ?? 'anonymous' }));
230
+
231
+ const typed = contextStorage<typeof base>();
232
+ const untyped = contextStorage();
233
+
234
+ export function whoIsAsking(): string {
235
+ untyped.context().route; // string: BaseContext only
236
+ // untyped.context().user — error TS2339: Property 'user' does not exist on type 'BaseContext'.
237
+ return typed.context().user; // string
238
+ }
239
+ ```
240
+
241
+ With `Register` augmented beside `base`
242
+ ([`@softistx/alxia`'s `Register`](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/types.md#register-and-appcontext)),
243
+ `contextStorage()` is `contextStorage<typeof base>()` with no import of
244
+ `base`:
245
+
246
+ ```ts
247
+ declare module '@softistx/alxia' {
248
+ interface Register {
249
+ context: typeof base;
250
+ }
251
+ }
252
+
253
+ export const requestContext = contextStorage(); // context().user: string
254
+ ```
255
+
256
+ Four rules follow from typing by an app:
257
+
258
+ - **The app that mounts it must give that context.** The middleware requires
259
+ what `context()` reads beyond `BaseContext`, as a `definePlugin` does:
260
+ `alxia().use(contextStorage<typeof base>())` is a compile error, since
261
+ `context()` would claim a `user` that no middleware of that app adds.
262
+
263
+ - **Type it by the app before the middleware, never by the app that mounts it.**
264
+ `const app = alxia().use(requestContext)…` with
265
+ `requestContext = contextStorage<typeof app>()` is a circular type, which
266
+ `tsc` refuses with `TS7022`. Declare `base` first, as above. Registered,
267
+ the same holds: give `contextStorage()` to the app after `base`, never
268
+ to the registered `base` itself.
269
+ - **What a middleware after it adds is there at runtime, not in the
270
+ type.** `context()` knows `base`, so a `derive` added after
271
+ `base.use(requestContext)` is missing from its type. Put the middlewares
272
+ whose values services read in `base`, or state the type with `getContext<Ctx>()`.
273
+ - **A route's own `params`, `query`, `body` and `headers` are not in it**:
274
+ they belong to one route's `validate(…)`, not to the app. Read them in
275
+ the handler and pass them down, or state them:
276
+
277
+ ```ts
278
+ import { getContext } from '@softistx/alxia-context-storage';
279
+
280
+ // in code that only ever runs under GET /orders/:id, after its validate({ params })
281
+ const { params } = getContext<{ params: { id: number } }>();
282
+ ```
283
+
284
+ `getContext<Ctx>()` and `tryGetContext<Ctx>()` believe what `Ctx` says,
285
+ as `hono/context-storage`'s do: nothing checks it against the route.
286
+
287
+ ## Where it sits
288
+
289
+ `app.use(contextStorage())` runs on every request, a 404 included, and
290
+ wraps what is declared after it, in the same app or group. So **use it
291
+ before the routes whose code reads the context**, and after the middlewares
292
+ whose values services read:
293
+
294
+ ```ts
295
+ import { alxia } from '@softistx/alxia';
296
+ import { contextStorage, getContext } from '@softistx/alxia-context-storage';
297
+
298
+ const requestContext = contextStorage();
299
+
300
+ const app = alxia()
301
+ .get('/health', ({ reply }) => reply(200, 'ok')) // getContext() throws NOT_ROUTED here
302
+ .use(requestContext)
303
+ .derive(() => ({ startedAt: Date.now() })) // after it: may call code that reads it
304
+ .get('/me', ({ reply }) => reply(200, getContext().route)); // '/me'
305
+ ```
306
+
307
+ A middleware declared before `contextStorage()` that ends the request, a
308
+ `401` from a guard, ends it before the middleware runs: nothing it calls
309
+ finds a store. Put the guards after `contextStorage()` when the code that
310
+ answers needs the context; put it after the observers (`logger`,
311
+ `telemetry`) and before an error-handling `try`/`catch` that reads it.
312
+
313
+ | Placement | Effect |
314
+ | --- | --- |
315
+ | first on the app | every route after it, and every middleware after it, can read it; a request no route matches gets `getRequestContext()` too; `context()` is typed `BaseContext` unless typed by an app declared before it |
316
+ | after `decorate` and `derive` | the usual place: typed by them, and every route after reads it |
317
+ | inside a `group` | the group's routes read it; a route outside the group, or a request no route matches, throws `OUTSIDE_REQUEST`: the middleware never ran |
318
+ | twice | harmless: one store, one context per request |
319
+
320
+ `contextStorage()` is a middleware, not an app: declare routes on the app,
321
+ and pass `contextStorage()` to `app.use` called — the uncalled form is
322
+ [refused](troubleshooting.md#use-argument-1-looks-like-a-factory-contextstorage-call-it-usecontextstorage).
323
+
324
+ ## What `AsyncLocalStorage` carries
325
+
326
+ The store follows the request's asynchronous work: every `await`, promise,
327
+ `setTimeout` and microtask started while the request runs reads the
328
+ context of that request, and concurrent requests never see each other's.
329
+
330
+ ```ts
331
+ async function greet(): Promise<string> {
332
+ await Bun.sleep(10);
333
+ await new Promise((resolve) => setTimeout(resolve, 1));
334
+ const { greeting, user } = requestContext.context(); // still this request's
335
+ return `${greeting} ${user}`;
336
+ }
337
+ ```
338
+
339
+ A server-sent event stream's generator runs while the response streams, and
340
+ reads the context too.
341
+
342
+ What it carries is decided where a callback is **scheduled**, not where it
343
+ runs:
344
+
345
+ | The callback | Sees |
346
+ | --- | --- |
347
+ | a `setTimeout` or promise started in the request, firing after the response is sent | that request's context, stale: `context()` does not throw, but `set` no longer reaches any response |
348
+ | a `setInterval`, queue consumer or pool started at startup | nothing: `context()` throws `OUTSIDE_REQUEST`, `tryContext()` is `undefined` |
349
+ | a function pushed into a queue in the request, and run by something started at startup | nothing, as above |
350
+ | an `EventEmitter` listener | the context of the code that called `emit`, since listeners run synchronously |
351
+ | a WebSocket's `open`, `message` and `close` | nothing: a socket's handlers run outside the chain |
352
+
353
+ So work that outlives the request — a write-behind, an e-mail, an audit
354
+ event — takes what it needs **before** it is detached, instead of reading
355
+ the context when it runs:
356
+
357
+ ```ts
358
+ import { requestContext } from './context';
359
+
360
+ const pending: (() => Promise<void>)[] = [];
361
+
362
+ export function auditLater(action: string): void {
363
+ const { user, route } = requestContext.context(); // read now, in the request
364
+ pending.push(async () => {
365
+ console.log(JSON.stringify({ action, user: user.id, route }));
366
+ });
367
+ }
368
+
369
+ setInterval(() => {
370
+ for (const job of pending.splice(0)) void job(); // runs outside any request
371
+ }, 1000);
372
+ ```
373
+
374
+ For a socket, read what a message needs from `socket.data`, which holds the
375
+ upgrade's context.
376
+
377
+ ## Jobs and tests: `runWithContext`
378
+
379
+ `runWithContext(ctx, work)` runs `work` with `ctx` as the current context,
380
+ for code that reads it outside any request: a queue consumer, a scheduled
381
+ job, a unit test of a service. `getContext()` and `getRequestContext()` both
382
+ return `ctx` while it runs, and `work`'s return value — a promise included
383
+ — comes back as it is.
384
+
385
+ `ctx` is a `BaseContext`. A job has no request to build one from, so give it
386
+ what the code reads, and say that is all it is:
387
+
388
+ ```ts
389
+ import type { ContextOf } from '@softistx/alxia';
390
+ import { runWithContext } from '@softistx/alxia-context-storage';
391
+ import { type base } from './context';
392
+ import { listOrders } from './orders';
393
+
394
+ type Ctx = ContextOf<typeof base>;
395
+
396
+ const job = {
397
+ db: { orders: [{ id: 7, userId: 0, total: 1 }] },
398
+ user: { id: 0, name: 'nightly' },
399
+ set: { headers: new Headers(), cookies: new Bun.CookieMap() },
400
+ } satisfies Partial<Ctx>;
401
+
402
+ const orders = await runWithContext(job as unknown as Ctx, () => listOrders());
403
+ ```
404
+
405
+ `satisfies` checks the fields you give against the app's context; the cast
406
+ admits the ones you left out, which the code must not read.
407
+
408
+ A test covers both sides — the service through a real request, and alone:
409
+
410
+ ```ts
411
+ import { describe, expect, test } from 'bun:test';
412
+ import type { ContextOf } from '@softistx/alxia';
413
+ import { runWithContext } from '@softistx/alxia-context-storage';
414
+ import { app } from './app';
415
+ import { type base } from './context';
416
+ import { listOrders } from './orders';
417
+
418
+ describe('listOrders', () => {
419
+ test('reads the user of the request it runs in', async () => {
420
+ const response = await app.request('/orders', {
421
+ headers: { authorization: 'Bearer ada' },
422
+ });
423
+ expect(response.status).toBe(200);
424
+ expect(response.headers.get('cache-control')).toBe('private');
425
+ expect(await response.json()).toEqual([{ id: 1, userId: 1, total: 42 }]);
426
+ });
427
+
428
+ test('concurrent requests never see each other', async () => {
429
+ const answers = await Promise.all(
430
+ ['Bearer ada', 'Bearer nobody', 'Bearer ada'].map(
431
+ async (authorization) =>
432
+ (await app.request('/orders', { headers: { authorization } })).status,
433
+ ),
434
+ );
435
+ expect(answers).toEqual([200, 401, 200]);
436
+ });
437
+
438
+ test('runs alone, with a context of its own', async () => {
439
+ const ctx = {
440
+ db: { orders: [{ id: 2, userId: 9, total: 5 }] },
441
+ user: { id: 9, name: 'test' },
442
+ set: { headers: new Headers(), cookies: new Bun.CookieMap() },
443
+ } satisfies Partial<ContextOf<typeof base>>;
444
+
445
+ const orders = await runWithContext(ctx as unknown as ContextOf<typeof base>, listOrders);
446
+
447
+ expect(orders).toEqual([{ id: 2, userId: 9, total: 5 }]);
448
+ expect(ctx.set.headers.get('cache-control')).toBe('private');
449
+ });
450
+ });
451
+ ```
452
+
453
+ When `getContext()` throws, or a service reads the wrong context,
454
+ [Troubleshooting](troubleshooting.md) starts from the message.
@@ -0,0 +1,61 @@
1
+ # Roadmap
2
+
3
+ What `@softistx/alxia-context-storage` gives an app, and what is coming. This page
4
+ is a direction, not a commitment: the version something shipped in is the
5
+ only number on it. Every release, with each change it made, is in
6
+ [`CHANGELOG.md`](https://github.com/softistx/alxia/blob/develop/packages/context-storage/CHANGELOG.md).
7
+
8
+ ## Now
9
+
10
+ - **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-context-storage` (it was `@alxia/context-storage`). 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.
11
+
12
+ ## Next
13
+
14
+ Nothing scheduled yet.
15
+
16
+ ## Later
17
+
18
+ Nothing scheduled yet.
19
+
20
+ ## Not planned
21
+
22
+ - **A runtime dependency.** `@softistx/alxia-context-storage` declares no
23
+ dependency, only peers: `@softistx/alxia` and `typescript`. It is built on
24
+ `@softistx/alxia`'s public API and the runtime's own `AsyncLocalStorage`.
25
+
26
+ ## Shipped
27
+
28
+ ### 0.3.0
29
+
30
+ - **A middleware, not a plugin (0.4).** `app.use(contextStorage())` opens the store on every request, a 404 included: `getRequestContext()` works in every middleware after it, and an error is answered inside it, so a middleware that catches it still reads the context. `app.plugin(contextStorage())`, the deprecated plugin form, was removed with alxia 0.5: give it to `use`.
31
+
32
+ ### 0.2.0
33
+
34
+ - **Typed by `Register`.** With `@alxia/core`'s `Register` naming the
35
+ base, `contextStorage()` needs no type argument: `context()` reads the
36
+ registered context. Typed either way, the middleware requires that context
37
+ of the app that mounts it, a compile error otherwise.
38
+
39
+ ### 0.1.0
40
+
41
+ - **The request's context anywhere it runs.** `alxia().use(contextStorage())`
42
+ lets a service, a repository or a logger read the context of the route
43
+ that called it with `getContext()`, without it being passed down, through
44
+ every `await`, timer and promise, and never another request's.
45
+ - **Typed by the app.** `contextStorage<typeof base>()` gives `context()` and
46
+ `tryContext()` what a route declared next on `base` reads: the values its
47
+ `decorate` and `derive` added.
48
+ - **The request before routing.** `getRequestContext()` reads the request
49
+ before routing and in a 404, with the route it
50
+ reached and the error it failed with; `tryGetRequestContext()` returns
51
+ `undefined` outside a request instead of throwing.
52
+ - **Jobs and tests.** `runWithContext(ctx, work)` runs code that reads the
53
+ context outside a request.
54
+ - **A refusal that says why.** Where there is no context, `getContext()`
55
+ throws a `ContextStorageError` coded `OUTSIDE_REQUEST` or `NOT_ROUTED`,
56
+ and `tryGetContext()` returns `undefined`.
57
+ `use(contextStorage)`, the factory uncalled, fails `tsc` and throws
58
+ where it is declared (since alxia 0.5), rather than answering its routes 500.
59
+ - **Ported from `hono/context-storage`.** One store, and `getContext()`
60
+ read wherever it is called, as Hono's is: code written against one ports
61
+ to the other.
@@ -0,0 +1,314 @@
1
+ # Troubleshooting
2
+
3
+ Each entry is headed by the text you see: an error in the server log, a
4
+ behaviour that prints nothing, or an error from `tsc`. A
5
+ `ContextStorageError` thrown inside a route also answers the request with
6
+ `500 {"error":"internal"}`; the message is in the server log.
7
+
8
+ **Runtime**
9
+
10
+ - [`use(): argument 1 looks like a factory (contextStorage): call it, use(contextStorage())`](#use-argument-1-looks-like-a-factory-contextstorage-call-it-usecontextstorage), and `TypeError: contextStorage is a factory: use(contextStorage()), not use(contextStorage)`
11
+ - [`ContextStorageError: getContext(): called outside a request — use tryGetContext(), or runWithContext() in a job or a test`](#contextstorageerror-getcontext-called-outside-a-request--use-trygetcontext-or-runwithcontext-in-a-job-or-a-test)
12
+ - [`ContextStorageError: getContext(): this request reached no route declared after contextStorage() — use it earlier, or getRequestContext()`](#contextstorageerror-getcontext-this-request-reached-no-route-declared-after-contextstorage--use-it-earlier-or-getrequestcontext)
13
+ - [A header set from a timer never reaches the response](#a-header-set-from-a-timer-never-reaches-the-response)
14
+
15
+ **Types**
16
+
17
+ - [`'requestContext' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.`](#requestcontext-implicitly-has-type-any-because-it-does-not-have-a-type-annotation-and-is-referenced-directly-or-indirectly-in-its-own-initializer)
18
+ - [`Property 'user' does not exist on type 'BaseContext'.`](#property-user-does-not-exist-on-type-basecontext)
19
+ - [`Property 'params' does not exist on type 'BaseContext & …'.`](#property-params-does-not-exist-on-type-basecontext--)
20
+ - [`Object literal may only specify known properties, and 'db' does not exist in type 'BaseContext'.`](#object-literal-may-only-specify-known-properties-and-db-does-not-exist-in-type-basecontext)
21
+ - [`Property 'user' is missing in type 'BaseContext & Empty' but required in type '{ user: string; }'`](#property-user-is-missing-in-type-basecontext--empty-but-required-in-type--user-string-)
22
+
23
+ ## Runtime
24
+
25
+ ### `use(): argument 1 looks like a factory (contextStorage): call it, use(contextStorage())`
26
+
27
+ `tsc` reports the same mistake first:
28
+
29
+ ```text
30
+ error TS2345: Argument of type '<App = Alxia<Empty, "">>(...uncalled: readonly never[]) => ContextStorageMiddleware<App>' is not assignable to parameter of type '…'.
31
+ Type '<App = Alxia<Empty, "">>(...uncalled: readonly never[]) => ContextStorageMiddleware<App>' is not assignable to type '(ctx: never, next: NextFunction) => … & "this looks like a factory given uncalled: call it, as use(cors()) and not use(cors)"'.
32
+ Types of parameters 'uncalled' and 'next' are incompatible.
33
+ Type 'NextFunction' is not assignable to type 'never'.
34
+ ```
35
+
36
+ **When:** `.use(contextStorage)`, the factory given to `app.use` without
37
+ being called. It throws where the app is declared, since alxia 0.5; before,
38
+ each request the routes after it answered was a 500, with
39
+ `TypeError: contextStorage is a factory: use(contextStorage()), not use(contextStorage)`
40
+ in the server log, which a factory run past `use` still throws.
41
+
42
+ **Why:** `contextStorage` is marked as a factory, so `use`, a route and
43
+ `plugin` refuse it. Run as a middleware, it would make a new middleware
44
+ each time and store nothing.
45
+
46
+ **Fix:** call it, once, and keep the result:
47
+
48
+ ```ts
49
+ export const requestContext = contextStorage<typeof base>();
50
+
51
+ const app = base.use(requestContext);
52
+ ```
53
+
54
+ ### `ContextStorageError: getContext(): called outside a request — use tryGetContext(), or runWithContext() in a job or a test`
55
+
56
+ `error.code` is `'OUTSIDE_REQUEST'`. `getContext()`, `requestContext.context()`
57
+ and `getRequestContext()` all throw it.
58
+
59
+ **When:** the code that reads the context runs where no request is:
60
+
61
+ - at the top level of a module, or in code run at startup;
62
+ - in a job, a queue consumer, or a callback run by a `setInterval` started
63
+ at startup — including a function pushed onto a queue during a request
64
+ and run later by such a timer;
65
+ - in a route declared **before** `use(requestContext)`, or outside the
66
+ `group` it is used in: the middleware never ran on that request;
67
+ - in a middleware declared before it, which runs outside the store;
68
+ - in a WebSocket's `open`, `message` or `close`, since a socket's handlers
69
+ run outside the chain;
70
+ - with two copies of `@softistx/alxia-context-storage` installed: each has its own
71
+ store, so the middleware from one is invisible to `getContext()` from the other.
72
+
73
+ **Why:** the context lives in an `AsyncLocalStorage` that the middleware opens
74
+ for each request it runs on. A callback reads the store that was current where it was
75
+ **scheduled**; anything started outside a request has none.
76
+
77
+ **Fix:** in code that runs in and out of requests, use `tryContext()` —
78
+ or `tryGetRequestContext()` for the request alone:
79
+
80
+ ```ts
81
+ const user = requestContext.tryContext()?.user; // undefined outside a request
82
+ const method = tryGetRequestContext()?.request.method; // the same
83
+ ```
84
+
85
+ In a job, a consumer or a test, give the code a context to read:
86
+
87
+ ```ts
88
+ import type { ContextOf } from '@softistx/alxia';
89
+ import { runWithContext } from '@softistx/alxia-context-storage';
90
+
91
+ type Ctx = ContextOf<typeof base>;
92
+
93
+ const job = {
94
+ db,
95
+ user: { id: 0, name: 'nightly' },
96
+ set: { headers: new Headers(), cookies: new Bun.CookieMap() },
97
+ } satisfies Partial<Ctx>;
98
+
99
+ await runWithContext(job as unknown as Ctx, () => listOrders());
100
+ ```
101
+
102
+ For work that outlives the request, read the context in the request and
103
+ hand the values over:
104
+
105
+ ```ts
106
+ export function auditLater(action: string): void {
107
+ const { user } = requestContext.context(); // in the request
108
+ pending.push(() => audit(action, user.id)); // runs later, needs nothing
109
+ }
110
+ ```
111
+
112
+ In a socket handler, read what the upgrade's middlewares added from
113
+ `socket.data`. For two copies, `bun pm ls --all | grep context-storage`
114
+ shows them; align the versions the app and its dependencies ask for.
115
+
116
+ ### `ContextStorageError: getContext(): this request reached no route declared after contextStorage() — use it earlier, or getRequestContext()`
117
+
118
+ `error.code` is `'NOT_ROUTED'`.
119
+
120
+ **When:** in a request the middleware ran on, but that reached no route:
121
+ a 404 or a 405, in a middleware after `use(requestContext)`, or in code
122
+ that middleware calls.
123
+
124
+ **Why:** `use(requestContext)` on the app runs on every request, and records
125
+ the route's context only when a route matched: for an unmatched request
126
+ there is a request and no route.
127
+
128
+ **Fix:** in a middleware, or in code that also runs for a 404, read the
129
+ request instead, which holds wherever the middleware ran:
130
+
131
+ ```ts
132
+ import { defineMiddleware } from '@softistx/alxia';
133
+ import { getRequestContext } from '@softistx/alxia-context-storage';
134
+
135
+ app.use(requestContext).use(
136
+ defineMiddleware(async (_ctx, next) => {
137
+ const response = await next();
138
+ const { request, route } = getRequestContext(); // route is undefined for a 404
139
+ console.log(request.method, route ?? 'unmatched', response.status);
140
+ return response;
141
+ }),
142
+ );
143
+ ```
144
+
145
+ A route declared before the middleware, or outside its `group`, throws
146
+ `OUTSIDE_REQUEST` instead (see above): mount it before the routes whose
147
+ code reads it.
148
+
149
+ ### A header set from a timer never reaches the response
150
+
151
+ **When:** a `setTimeout`, a promise that is not awaited, or a callback
152
+ started in a request calls `requestContext.context().set.headers.set(…)` — or
153
+ sets a cookie — after the handler has returned.
154
+
155
+ **Why:** the callback still reads the request's context — `context()` does not
156
+ throw — but the response was already sent. The context is stale, not gone.
157
+
158
+ **Fix:** await the work that shapes the response before replying, and
159
+ detach only what does not:
160
+
161
+ ```ts
162
+ const app = base.use(requestContext).get('/orders', async ({ reply }) => {
163
+ const orders = await listOrders(); // sets cache-control while the response is open
164
+ void sendReceipt(); // detached: must not touch `set`
165
+ return reply(200, orders);
166
+ });
167
+ ```
168
+
169
+
170
+ ## Types
171
+
172
+ ### `'requestContext' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.`
173
+
174
+ ```text
175
+ error TS7022: 'app' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
176
+ error TS7022: 'requestContext' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
177
+ ```
178
+
179
+ Often with `TS2448: Block-scoped variable 'requestContext' used before its declaration.`
180
+
181
+ **When:** the middleware is typed by the app that mounts it:
182
+
183
+ ```ts
184
+ export const app = alxia().decorate({ db }).use(requestContext).get(/* … */);
185
+ export const requestContext = contextStorage<typeof app>(); // circular
186
+ ```
187
+
188
+ **Why:** `app`'s type depends on the middleware, and the middleware's on `app`.
189
+
190
+ **Fix:** type it by the app as it stands **before** the middleware:
191
+
192
+ ```ts
193
+ export const base = alxia().decorate({ db });
194
+ export const requestContext = contextStorage<typeof base>();
195
+ export const app = base.use(requestContext).get('/orders', ({ reply }) => reply(200, 'ok'));
196
+ ```
197
+
198
+ ### `Property 'user' does not exist on type 'BaseContext'.`
199
+
200
+ ```text
201
+ error TS2339: Property 'user' does not exist on type 'BaseContext'.
202
+ ```
203
+
204
+ Also as `Property 'user' does not exist on type 'BaseContext & Empty & { readonly db: … }'.`
205
+
206
+ **When:** reading from `context()` a value a middleware adds, and either
207
+
208
+ - the middleware was made without an app type, `contextStorage()`, and
209
+ `@softistx/alxia`'s `Register` names no base; or
210
+ - it is `contextStorage()` given to the registered `base` itself, which
211
+ cannot read `Register` while `base` is being typed; or
212
+ - it is typed by `base`, and the middleware adding `user` comes after it:
213
+ `base.use(requestContext).derive(() => ({ user }))`.
214
+
215
+ **Why:** `context()` returns `ContextOf<App>`: what a route declared next on
216
+ `App` reads. With no `App`, that is `BaseContext`; a middleware after `App` is
217
+ not in it. At runtime the value is there.
218
+
219
+ **Fix:** declare every middleware whose values services read in `base`, then type
220
+ it by `base` — or register `base` with `@softistx/alxia`'s `Register` and
221
+ give `contextStorage()` to the app after `base`, never to `base` itself:
222
+
223
+ ```ts
224
+ const base = alxia()
225
+ .decorate({ db })
226
+ .derive(({ request }) => ({ user: request.headers.get('x-user') ?? 'anonymous' }));
227
+
228
+ export const requestContext = contextStorage<typeof base>();
229
+ // requestContext.context().user: string
230
+ ```
231
+
232
+ ### `Property 'params' does not exist on type 'BaseContext & …'.`
233
+
234
+ ```text
235
+ error TS2339: Property 'params' does not exist on type 'BaseContext & Empty & { readonly db: … }'.
236
+ ```
237
+
238
+ The same for `query`, `body` and `headers`.
239
+
240
+ **When:** reading a route's validated input from `requestContext.context()`.
241
+
242
+ **Why:** those belong to one route's `validate(…)`, not to the app, so the
243
+ app's context does not have them. The app's middlewares run before a
244
+ route's own, `validate` among them: a `derive` reads the request as it
245
+ arrived, the body `undefined`, even at runtime.
246
+
247
+ **Fix:** pass them from the handler, or, in code that only runs under one
248
+ route, state them:
249
+
250
+ ```ts
251
+ import { getContext } from '@softistx/alxia-context-storage';
252
+
253
+ const { params } = getContext<{ params: { id: number } }>(); // nothing checks this
254
+ ```
255
+
256
+ ### `Object literal may only specify known properties, and 'db' does not exist in type 'BaseContext'.`
257
+
258
+ ```text
259
+ error TS2353: Object literal may only specify known properties, and 'db' does not exist in type 'BaseContext'.
260
+ ```
261
+
262
+ **When:** `runWithContext({ db, user }, work)`, with a context written by
263
+ hand for a job or a test.
264
+
265
+ **Why:** `runWithContext` takes a `BaseContext`: a whole request context.
266
+ A job has no request, so a literal has neither the fields it requires nor
267
+ room for the ones the app adds.
268
+
269
+ **Fix:** check the fields against the app's context with `satisfies`, and
270
+ cast — `work` must then read only what you gave:
271
+
272
+ ```ts
273
+ import type { ContextOf } from '@softistx/alxia';
274
+
275
+ type Ctx = ContextOf<typeof base>;
276
+
277
+ const ctx = {
278
+ db,
279
+ user: { id: 0, name: 'job' },
280
+ set: { headers: new Headers(), cookies: new Bun.CookieMap() }, // listOrders sets a header
281
+ } satisfies Partial<Ctx>;
282
+
283
+ runWithContext(ctx as unknown as Ctx, () => listOrders());
284
+ ```
285
+
286
+ ### `Property 'user' is missing in type 'BaseContext & Empty' but required in type '{ user: string; }'`
287
+
288
+ ```text
289
+ error TS2769: No overload matches this call.
290
+ …
291
+ Type 'BaseContext & Empty' is not assignable to type 'MiddlewareContext<{ user: string; }>'.
292
+ Property 'user' is missing in type 'BaseContext & Empty' but required in type '{ user: string; }'.
293
+ ```
294
+
295
+ **When:** an app uses the middleware typed by another app, `contextStorage<typeof
296
+ base>()`, or by the registered one, `contextStorage()`, and does not give
297
+ what that app's middlewares add:
298
+
299
+ ```ts
300
+ const base = alxia().derive(({ request }) => ({ user: request.headers.get('x-user') ?? 'anonymous' }));
301
+ const requestContext = contextStorage<typeof base>();
302
+
303
+ alxia().use(requestContext);
304
+ ```
305
+
306
+ **Why:** `context()` would return a `user` that no middleware of this app adds:
307
+ at runtime it would be `undefined`.
308
+
309
+ **Fix:** mount it on the app it is typed by, after `base`:
310
+
311
+ ```ts
312
+ base.use(requestContext);
313
+ ```
314
+
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
- "name": "@softistx/alxia-context-storage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@softistx/alxia-context-storage",
3
+ "version": "0.4.0",
4
+ "description": "The request's context anywhere it runs — a service, a repository, a logger — through AsyncLocalStorage: alxia's hono/context-storage, typed by the app",
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/context-storage"
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
+ "@types/bun": "^1.4.4",
46
+ "zod": "^4.6.5"
47
+ },
48
+ "peerDependencies": {
49
+ "@softistx/alxia": "^0.28.0",
50
+ "typescript": "^6.0.3 || ^7.0.0"
51
+ }
52
+ }