@forinda/kickjs-testing 8.0.0 → 8.2.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/README.md CHANGED
@@ -1,60 +1,38 @@
1
1
  # @forinda/kickjs-testing
2
2
 
3
- Test utilities for KickJS — `createTestApp`, `createTestModule`, `runContributor` (single contributor in isolation), and `createTestPlugin` (plugin harness with isolated container + lifecycle invokers).
3
+ Test helpers for KickJS: `createTestApp` boots your real modules with a request client, no port needed. Also `createTestModule`, `runContributor` and `createTestPlugin` for testing pieces in isolation.
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```bash
8
- pnpm add -D @forinda/kickjs-testing
8
+ pnpm add -D @forinda/kickjs-testing supertest
9
9
  ```
10
10
 
11
- ## Quick Example
11
+ ## Quick example
12
12
 
13
13
  ```ts
14
- import { describe, it, expect } from 'vitest'
15
- import supertest from 'supertest'
14
+ import { describe, expect, it } from 'vitest'
16
15
  import { createTestApp } from '@forinda/kickjs-testing'
17
- import { UserModule, USER_REPO } from './modules/users'
18
- import { MockUserRepository } from './mocks'
16
+ import { UserModule, USER_REPO } from '../src/modules/users'
19
17
 
20
- describe('UserController', () => {
18
+ describe('users', () => {
21
19
  it('lists users', async () => {
22
- const { app } = await createTestApp({
20
+ const { client } = await createTestApp({
23
21
  modules: [UserModule()],
24
- overrides: [[USER_REPO, new MockUserRepository()]],
22
+ overrides: [[USER_REPO, new InMemoryUserRepository()]],
25
23
  })
26
24
 
27
- const res = await supertest(app.handle.bind(app)).get('/api/v1/users')
28
- expect(res.status).toBe(200)
25
+ const res = await client().get('/api/v1/users').expect(200)
26
+ expect(res.body.data).toHaveLength(1)
29
27
  })
30
28
  })
31
29
  ```
32
30
 
33
- Drive `app.handle` — it is the Application's own request listener and follows
34
- whichever runtime is configured. (`expressApp` is deprecated and throws under
35
- Fastify or h3.)
36
-
37
- ## Test the engine you deploy
38
-
39
- Pass `runtime`, the same value you give `bootstrap()`. Routing, body parsing,
40
- status handling and error mapping all live in the runtime seam, so a green
41
- Express suite says nothing about them if you ship Fastify:
42
-
43
- ```ts
44
- import { fastifyRuntime } from '@forinda/kickjs/fastify'
45
-
46
- const { app } = await createTestApp({
47
- modules: [UserModule()],
48
- runtime: fastifyRuntime(),
49
- })
50
- ```
51
-
52
- `overrides` takes entries or a `Map` as well as an object — a `createToken()`
53
- token is a frozen object, which TypeScript rejects as a computed key.
31
+ Pass `runtime` (as you do to `bootstrap()`) to test on the engine you deploy.
54
32
 
55
33
  ## Documentation
56
34
 
57
- [kickjs.app/guide/testing](https://kickjs.app/guide/testing)
35
+ [kickjs.app/guide/testing](https://kickjs.app/guide/testing): HTTP tests, auth, jobs and sockets, contributors, environment, large suites.
58
36
 
59
37
  ## License
60
38
 
@@ -0,0 +1,333 @@
1
+
2
+ import { AppAdapter, AppModuleClass, AppModuleEntry, Application, ApplicationOptions, Container, ContextDecorator, ContextMetaKey, ContributorRegistration, ExecutionContext, KickPlugin, MetaValue, ModuleRoutes } from "@forinda/kickjs";
3
+ import express from "express";
4
+ //#region src/client.d.ts
5
+ /** A request in flight — supertest's `Test`, chainable and awaitable. */
6
+ type TestRequest = any;
7
+ /** Options for {@link TestClient} and `createTestApp(...).client()`. */
8
+ interface TestClientOptions {
9
+ /** Headers sent with every request: `{ host: 'localhost' }`, a tenant header. */
10
+ headers?: Record<string, string>;
11
+ /** Sent as `Authorization: Bearer <token>`. */
12
+ bearer?: string;
13
+ /**
14
+ * How `.as(credential)` authenticates, when it isn't a bearer token — the
15
+ * headers to send for a credential:
16
+ *
17
+ * client({ auth: (sid) => ({ cookie: `sid=${sid}` }) }).as(sessionId)
18
+ * client({ auth: (key) => ({ 'x-api-key': key }) }).as(apiKey)
19
+ *
20
+ * Default: `Authorization: Bearer <credential>`.
21
+ */
22
+ auth?: (credential: string) => Record<string, string>;
23
+ /** Prefixed to every path: `basePath: '/api/v1'`, then `.get('/users')`. */
24
+ basePath?: string;
25
+ /**
26
+ * Keep cookies between requests, like a browser — for session and CSRF
27
+ * flows. Default `false`: every request starts without cookies.
28
+ */
29
+ cookies?: boolean;
30
+ }
31
+ /**
32
+ * Requests against a test app, through whichever runtime it runs on, with
33
+ * the headers every call needs set once:
34
+ *
35
+ * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })
36
+ * await api.as(token).post('/invoices').send(body).expect(201)
37
+ */
38
+ interface TestClient {
39
+ get(path: string): TestRequest;
40
+ post(path: string): TestRequest;
41
+ put(path: string): TestRequest;
42
+ patch(path: string): TestRequest;
43
+ delete(path: string): TestRequest;
44
+ head(path: string): TestRequest;
45
+ options(path: string): TestRequest;
46
+ /**
47
+ * The same client, authenticated as `credential`: `Authorization: Bearer
48
+ * <credential>`, or the headers the client's `auth` option makes of it.
49
+ */
50
+ as(credential: string): TestClient;
51
+ /** The same client, with these headers added (or replaced). */
52
+ withHeaders(headers: Record<string, string>): TestClient;
53
+ }
54
+ //#endregion
55
+ //#region src/reset.d.ts
56
+ /** Register a reset; returns a function that unregisters it. */
57
+ declare function onTestReset(reset: () => unknown): () => void;
58
+ /** Run every registered reset, in registration order. All run even if one throws. */
59
+ declare function resetTestState(): Promise<void>;
60
+ //#endregion
61
+ //#region src/index.d.ts
62
+ /**
63
+ * Bootstrap options forwarded verbatim to the underlying Application so
64
+ * test apps exercise the same HTTP pipeline shape as production.
65
+ */
66
+ type BootstrapPassthroughOptions = Pick<ApplicationOptions, 'port' | 'apiPrefix' | 'defaultVersion' | 'middlewares' | 'onError' | 'onNotFound' | 'plugins' | 'trustProxy' | 'jsonLimit' | 'security' | 'contributors' | 'contextStore' | 'runtime' | 'health'>;
67
+ /**
68
+ * Options for creating a test application.
69
+ * Disables helmet, cors, compression, and morgan by default.
70
+ */
71
+ interface CreateTestAppOptions extends BootstrapPassthroughOptions {
72
+ /**
73
+ * Modules registered for the test run. Accepts both legacy class form
74
+ * (`UserModule extends AppModule`) and `defineModule` factory output
75
+ * (call the factory: `UserModule()`) — `Application` discriminates
76
+ * at boot.
77
+ */
78
+ modules: AppModuleEntry[];
79
+ /** Adapters to attach (auth, queue, devtools, etc.) */
80
+ adapters?: AppAdapter[];
81
+ /**
82
+ * DI overrides applied after module registration.
83
+ *
84
+ * An object literal covers string and symbol keys. It cannot cover
85
+ * `createToken()`, though — a token is a frozen OBJECT identified by
86
+ * reference, and TypeScript rejects an object as a computed key
87
+ * (`TS2464: A computed property name must be of type 'string', 'number',
88
+ * 'symbol', or 'any'`). Since tokens are the documented way to bind an
89
+ * interface to an implementation, that excluded exactly the key type most
90
+ * worth overriding in a test.
91
+ *
92
+ * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is
93
+ * a string, and the container keys tokens by reference, so the override is
94
+ * accepted and never applied.
95
+ *
96
+ * Pass entries to override a token:
97
+ *
98
+ * ```ts
99
+ * const DATABASE = createToken<Database>('app/Db/connection')
100
+ *
101
+ * await createTestApp({
102
+ * modules: [UserModule()],
103
+ * overrides: [[DATABASE, fakeDb()]],
104
+ * })
105
+ * ```
106
+ *
107
+ * A `Map` works too. The object form is unchanged.
108
+ */
109
+ overrides?: Record<symbol | string, any> | ReadonlyArray<readonly [token: unknown, value: unknown]> | ReadonlyMap<unknown, unknown>;
110
+ /**
111
+ * Use an isolated container instead of the global singleton.
112
+ * Prevents concurrent tests from interfering with each other's DI state.
113
+ * When true, Container.create() is used instead of Container.reset() + getInstance().
114
+ */
115
+ isolated?: boolean;
116
+ }
117
+ declare function createTestApp(options: CreateTestAppOptions): Promise<{
118
+ app: Application;
119
+ /**
120
+ * Requests against the app through whichever runtime it runs on, with the
121
+ * headers every call needs set once (needs supertest installed):
122
+ *
123
+ * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })
124
+ * await api.as(token).get('/me').expect(200)
125
+ */
126
+ client: (options?: TestClientOptions) => TestClient;
127
+ /**
128
+ * @deprecated Use `app.handle.bind(app)`. Only valid under the Express
129
+ * runtime — under
130
+ * any other engine this throws rather than handing back that engine's
131
+ * instance mistyped as `express.Express`, which is how a suite ends up
132
+ * silently exercising the wrong runtime.
133
+ */
134
+ expressApp: express.Express;
135
+ container: Container;
136
+ }>;
137
+ /**
138
+ * Build a quick TestModule that explicitly registers dependencies.
139
+ * Useful for integration tests that need to control the DI graph.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const TestModule = createTestModule({
144
+ * register: (c) => {
145
+ * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())
146
+ * c.register(UserController)
147
+ * },
148
+ * routes: () => buildRoutes(UserController, '/users'),
149
+ * })
150
+ * ```
151
+ */
152
+ declare function createTestModule(config: {
153
+ register: (container: Container) => void;
154
+ routes: () => ModuleRoutes | ModuleRoutes[] | null;
155
+ }): AppModuleClass;
156
+ /**
157
+ * Options for {@link runContributor}.
158
+ */
159
+ interface RunContributorOptions {
160
+ /**
161
+ * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container
162
+ * entirely — bypass for unit tests that want to assert pure resolve()
163
+ * behaviour without standing up a container.
164
+ *
165
+ * Property names must match the spec's `deps` keys; values can be real
166
+ * service instances, mocks, or test doubles.
167
+ */
168
+ deps?: Record<string, unknown>;
169
+ /**
170
+ * Pre-populate the fake context's metadata Map. Useful for testing
171
+ * contributors with `dependsOn` without running the full pipeline:
172
+ * pre-populate the dependency keys, then assert that `resolve()` reads
173
+ * them and produces the expected output.
174
+ */
175
+ initial?: Record<string, unknown>;
176
+ /** Override the fake context's `requestId` (default: `'test-req'`). */
177
+ requestId?: string;
178
+ /**
179
+ * More fields on the fake context — what an HTTP contributor reads off it:
180
+ * `{ req: { headers: { host: 'acme.example.com' } } }`.
181
+ */
182
+ ctx?: Record<string, unknown>;
183
+ /**
184
+ * Env values `getEnv` / `ConfigService` return while `resolve()` runs —
185
+ * parsed values, like `{ TRUST_PROXY: true }`. Restored afterwards.
186
+ */
187
+ env?: Record<string, unknown>;
188
+ }
189
+ /**
190
+ * Result of {@link runContributor}.
191
+ */
192
+ interface RunContributorResult<K extends string> {
193
+ /** Value returned by the contributor's `resolve()` call. */
194
+ value: MetaValue<K>;
195
+ /** The fake `ExecutionContext` used during the run. */
196
+ ctx: ExecutionContext;
197
+ /**
198
+ * Final state of the fake context's metadata Map after `resolve()`.
199
+ * Includes any `ctx.set(...)` calls the resolver made plus the final
200
+ * resolved value under the contributor's own key.
201
+ */
202
+ meta: Map<string, unknown>;
203
+ }
204
+ /**
205
+ * Run a single context contributor in isolation against a fake
206
+ * {@link ExecutionContext}. Skips the container, the topo-sort, and the
207
+ * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`
208
+ * directly so unit tests can assert pure resolve behaviour.
209
+ *
210
+ * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`
211
+ * or `await expect(...).rejects.toThrow()` against them. To exercise the
212
+ * full error matrix (optional skip, onError replacement, etc.), build a
213
+ * one-element pipeline with `buildPipeline()` and use `runContributors()`
214
+ * directly.
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const LoadProject = defineContextDecorator({
219
+ * key: 'project',
220
+ * dependsOn: ['tenant'],
221
+ * deps: { repo: ProjectRepo },
222
+ * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),
223
+ * })
224
+ *
225
+ * const { value } = await runContributor(LoadProject, {
226
+ * initial: { tenant: { id: 't-1' } },
227
+ * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },
228
+ * })
229
+ * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })
230
+ * ```
231
+ */
232
+ declare function runContributor<K extends ContextMetaKey, D extends Record<string, any> = Record<string, never>>(decorator: ContextDecorator<K, D>, options?: RunContributorOptions): Promise<RunContributorResult<K>>;
233
+ /**
234
+ * Options for {@link createTestPlugin}.
235
+ */
236
+ interface CreateTestPluginOptions {
237
+ /**
238
+ * Use an isolated container (default: `true`). Isolated harnesses never
239
+ * touch the global `Container.getInstance()` singleton, so concurrent
240
+ * tests can run without stomping each other's DI state.
241
+ */
242
+ isolated?: boolean;
243
+ /**
244
+ * Skip auto-invoking `plugin.register(container)` — useful when a test
245
+ * wants to assert container state *before* the plugin touches it.
246
+ * Defaults to `false` (register is called eagerly).
247
+ */
248
+ skipRegister?: boolean;
249
+ }
250
+ /**
251
+ * Result of {@link createTestPlugin}. Mirrors the spec sketch in
252
+ * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a
253
+ * `runContributors()` helper that builds a one-plugin pipeline against a
254
+ * fake `ExecutionContext`.
255
+ */
256
+ interface PluginTestHarness {
257
+ /** The plugin under test — exposed for direct introspection. */
258
+ readonly plugin: KickPlugin;
259
+ /** Isolated (or shared) DI container the plugin registered into. */
260
+ readonly container: Container;
261
+ /**
262
+ * Invoke `plugin.onReady(container)`. No-op if the plugin does not
263
+ * define the hook.
264
+ */
265
+ callOnReady(): Promise<void>;
266
+ /**
267
+ * Invoke `plugin.shutdown()`. No-op if the plugin does not define the
268
+ * hook.
269
+ */
270
+ shutdown(): Promise<void>;
271
+ /**
272
+ * Returns the module classes the plugin ships via `plugin.modules?()`.
273
+ * The harness does **not** auto-instantiate them — use `createTestApp`
274
+ * for that. Useful for assertions like "the plugin exposes the module I
275
+ * expect".
276
+ */
277
+ modules(): AppModuleEntry[];
278
+ /**
279
+ * Returns adapter instances the plugin ships via `plugin.adapters?()`.
280
+ * Useful for testing the adapters alongside the plugin's DI bindings.
281
+ */
282
+ adapters(): AppAdapter[];
283
+ /**
284
+ * Returns middleware entries the plugin ships via `plugin.middleware?()`.
285
+ */
286
+ middleware(): any[];
287
+ /**
288
+ * Returns contributor registrations the plugin ships via
289
+ * `plugin.contributors?()`.
290
+ */
291
+ contributors(): ContributorRegistration[];
292
+ /**
293
+ * Build a fake {@link ExecutionContext} pre-populated with the given
294
+ * metadata. Symmetric with {@link runContributor}'s fake context.
295
+ */
296
+ makeContext(initial?: Record<string, unknown>): ExecutionContext;
297
+ /**
298
+ * Run every contributor the plugin ships through a built pipeline
299
+ * against the given context. Dependencies resolve through the harness's
300
+ * container (same path production uses). Throws if the plugin's
301
+ * contributors reference `dependsOn` keys no one in the plugin provides.
302
+ */
303
+ runContributors(ctx: ExecutionContext): Promise<void>;
304
+ }
305
+ /**
306
+ * Build an isolated test harness around a single {@link KickPlugin}.
307
+ * Skips the full HTTP layer — symmetric with {@link runContributor} for
308
+ * contributors and {@link createTestApp} for integration runs.
309
+ *
310
+ * @example
311
+ * ```ts
312
+ * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
313
+ *
314
+ * // The plugin's register() already ran — resolve any bindings.
315
+ * const flags = harness.container.resolve(FLAGS_SERVICE)
316
+ *
317
+ * // Drive the post-bootstrap lifecycle.
318
+ * await harness.callOnReady()
319
+ *
320
+ * // Exercise contributors shipped by the plugin.
321
+ * const ctx = harness.makeContext({ requestId: 'req-1' })
322
+ * await harness.runContributors(ctx)
323
+ * expect(ctx.get('flags')).toEqual({ beta: true })
324
+ *
325
+ * await harness.shutdown()
326
+ * ```
327
+ */
328
+ declare function createTestPlugin(plugin: KickPlugin, options?: CreateTestPluginOptions): Promise<PluginTestHarness>;
329
+ /** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
330
+ declare const testPlugin: typeof createTestPlugin;
331
+ //#endregion
332
+ export { RunContributorResult as a, createTestPlugin as c, onTestReset as d, resetTestState as f, TestRequest as h, RunContributorOptions as i, runContributor as l, TestClientOptions as m, CreateTestPluginOptions as n, createTestApp as o, TestClient as p, PluginTestHarness as r, createTestModule as s, CreateTestAppOptions as t, testPlugin as u };
333
+ //# sourceMappingURL=index-B6ZZZiY_.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-B6ZZZiY_.d.mts","names":[],"sources":["../src/client.ts","../src/reset.ts","../src/index.ts"],"mappings":";;;;;KAIY;;UAGK;;EAEf,UAAU;;EAEV;;;;;;;;;;EAUA,QAAQ,uBAAuB;;EAE/B;;;;;EAKA;;;;;;;;;UAUe;EACf,IAAI,eAAe;EACnB,KAAK,eAAe;EACpB,IAAI,eAAe;EACnB,MAAM,eAAe;EACrB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leEntry, Application, ApplicationOptions, Container, ContextDecorator, ContextMetaKey, ContributorRegistration, ExecutionContext, KickPlugin, MetaValue, ModuleRoutes } from "@forinda/kickjs";
3
- import express from "express";
4
- //#region src/index.d.ts
5
- /**
6
- * Bootstrap options forwarded verbatim to the underlying Application so
7
- * test apps exercise the same HTTP pipeline shape as production.
8
- */
9
- type BootstrapPassthroughOptions = Pick<ApplicationOptions, 'port' | 'apiPrefix' | 'defaultVersion' | 'middlewares' | 'onError' | 'onNotFound' | 'plugins' | 'trustProxy' | 'jsonLimit' | 'security' | 'contributors' | 'contextStore' | 'runtime' | 'health'>;
10
- /**
11
- * Options for creating a test application.
12
- * Disables helmet, cors, compression, and morgan by default.
13
- */
14
- interface CreateTestAppOptions extends BootstrapPassthroughOptions {
15
- /**
16
- * Modules registered for the test run. Accepts both legacy class form
17
- * (`UserModule extends AppModule`) and `defineModule` factory output
18
- * (call the factory: `UserModule()`) — `Application` discriminates
19
- * at boot.
20
- */
21
- modules: AppModuleEntry[];
22
- /** Adapters to attach (auth, queue, devtools, etc.) */
23
- adapters?: AppAdapter[];
24
- /**
25
- * DI overrides applied after module registration.
26
- *
27
- * An object literal covers string and symbol keys. It cannot cover
28
- * `createToken()`, though — a token is a frozen OBJECT identified by
29
- * reference, and TypeScript rejects an object as a computed key
30
- * (`TS2464: A computed property name must be of type 'string', 'number',
31
- * 'symbol', or 'any'`). Since tokens are the documented way to bind an
32
- * interface to an implementation, that excluded exactly the key type most
33
- * worth overriding in a test.
34
- *
35
- * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is
36
- * a string, and the container keys tokens by reference, so the override is
37
- * accepted and never applied.
38
- *
39
- * Pass entries to override a token:
40
- *
41
- * ```ts
42
- * const DATABASE = createToken<Database>('app/Db/connection')
43
- *
44
- * await createTestApp({
45
- * modules: [UserModule()],
46
- * overrides: [[DATABASE, fakeDb()]],
47
- * })
48
- * ```
49
- *
50
- * A `Map` works too. The object form is unchanged.
51
- */
52
- overrides?: Record<symbol | string, any> | ReadonlyArray<readonly [token: unknown, value: unknown]> | ReadonlyMap<unknown, unknown>;
53
- /**
54
- * Use an isolated container instead of the global singleton.
55
- * Prevents concurrent tests from interfering with each other's DI state.
56
- * When true, Container.create() is used instead of Container.reset() + getInstance().
57
- */
58
- isolated?: boolean;
59
- }
60
- declare function createTestApp(options: CreateTestAppOptions): Promise<{
61
- app: Application;
62
- /**
63
- * @deprecated Use `app.handle.bind(app)`. Only valid under the Express
64
- * runtime — under
65
- * any other engine this throws rather than handing back that engine's
66
- * instance mistyped as `express.Express`, which is how a suite ends up
67
- * silently exercising the wrong runtime.
68
- */
69
- expressApp: express.Express;
70
- container: Container;
71
- }>;
72
- /**
73
- * Build a quick TestModule that explicitly registers dependencies.
74
- * Useful for integration tests that need to control the DI graph.
75
- *
76
- * @example
77
- * ```ts
78
- * const TestModule = createTestModule({
79
- * register: (c) => {
80
- * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())
81
- * c.register(UserController)
82
- * },
83
- * routes: () => buildRoutes(UserController, '/users'),
84
- * })
85
- * ```
86
- */
87
- declare function createTestModule(config: {
88
- register: (container: Container) => void;
89
- routes: () => ModuleRoutes | ModuleRoutes[] | null;
90
- }): AppModuleClass;
91
- /**
92
- * Options for {@link runContributor}.
93
- */
94
- interface RunContributorOptions {
95
- /**
96
- * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container
97
- * entirely — bypass for unit tests that want to assert pure resolve()
98
- * behaviour without standing up a container.
99
- *
100
- * Property names must match the spec's `deps` keys; values can be real
101
- * service instances, mocks, or test doubles.
102
- */
103
- deps?: Record<string, unknown>;
104
- /**
105
- * Pre-populate the fake context's metadata Map. Useful for testing
106
- * contributors with `dependsOn` without running the full pipeline:
107
- * pre-populate the dependency keys, then assert that `resolve()` reads
108
- * them and produces the expected output.
109
- */
110
- initial?: Record<string, unknown>;
111
- /** Override the fake context's `requestId` (default: `'test-req'`). */
112
- requestId?: string;
113
- }
114
- /**
115
- * Result of {@link runContributor}.
116
- */
117
- interface RunContributorResult<K extends string> {
118
- /** Value returned by the contributor's `resolve()` call. */
119
- value: MetaValue<K>;
120
- /** The fake `ExecutionContext` used during the run. */
121
- ctx: ExecutionContext;
122
- /**
123
- * Final state of the fake context's metadata Map after `resolve()`.
124
- * Includes any `ctx.set(...)` calls the resolver made plus the final
125
- * resolved value under the contributor's own key.
126
- */
127
- meta: Map<string, unknown>;
128
- }
129
- /**
130
- * Run a single context contributor in isolation against a fake
131
- * {@link ExecutionContext}. Skips the container, the topo-sort, and the
132
- * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`
133
- * directly so unit tests can assert pure resolve behaviour.
134
- *
135
- * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`
136
- * or `await expect(...).rejects.toThrow()` against them. To exercise the
137
- * full error matrix (optional skip, onError replacement, etc.), build a
138
- * one-element pipeline with `buildPipeline()` and use `runContributors()`
139
- * directly.
140
- *
141
- * @example
142
- * ```ts
143
- * const LoadProject = defineContextDecorator({
144
- * key: 'project',
145
- * dependsOn: ['tenant'],
146
- * deps: { repo: ProjectRepo },
147
- * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),
148
- * })
149
- *
150
- * const { value } = await runContributor(LoadProject, {
151
- * initial: { tenant: { id: 't-1' } },
152
- * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },
153
- * })
154
- * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })
155
- * ```
156
- */
157
- declare function runContributor<K extends ContextMetaKey, D extends Record<string, any> = Record<string, never>>(decorator: ContextDecorator<K, D>, options?: RunContributorOptions): Promise<RunContributorResult<K>>;
158
- /**
159
- * Options for {@link createTestPlugin}.
160
- */
161
- interface CreateTestPluginOptions {
162
- /**
163
- * Use an isolated container (default: `true`). Isolated harnesses never
164
- * touch the global `Container.getInstance()` singleton, so concurrent
165
- * tests can run without stomping each other's DI state.
166
- */
167
- isolated?: boolean;
168
- /**
169
- * Skip auto-invoking `plugin.register(container)` — useful when a test
170
- * wants to assert container state *before* the plugin touches it.
171
- * Defaults to `false` (register is called eagerly).
172
- */
173
- skipRegister?: boolean;
174
- }
175
- /**
176
- * Result of {@link createTestPlugin}. Mirrors the spec sketch in
177
- * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a
178
- * `runContributors()` helper that builds a one-plugin pipeline against a
179
- * fake `ExecutionContext`.
180
- */
181
- interface PluginTestHarness {
182
- /** The plugin under test — exposed for direct introspection. */
183
- readonly plugin: KickPlugin;
184
- /** Isolated (or shared) DI container the plugin registered into. */
185
- readonly container: Container;
186
- /**
187
- * Invoke `plugin.onReady(container)`. No-op if the plugin does not
188
- * define the hook.
189
- */
190
- callOnReady(): Promise<void>;
191
- /**
192
- * Invoke `plugin.shutdown()`. No-op if the plugin does not define the
193
- * hook.
194
- */
195
- shutdown(): Promise<void>;
196
- /**
197
- * Returns the module classes the plugin ships via `plugin.modules?()`.
198
- * The harness does **not** auto-instantiate them — use `createTestApp`
199
- * for that. Useful for assertions like "the plugin exposes the module I
200
- * expect".
201
- */
202
- modules(): AppModuleEntry[];
203
- /**
204
- * Returns adapter instances the plugin ships via `plugin.adapters?()`.
205
- * Useful for testing the adapters alongside the plugin's DI bindings.
206
- */
207
- adapters(): AppAdapter[];
208
- /**
209
- * Returns middleware entries the plugin ships via `plugin.middleware?()`.
210
- */
211
- middleware(): any[];
212
- /**
213
- * Returns contributor registrations the plugin ships via
214
- * `plugin.contributors?()`.
215
- */
216
- contributors(): ContributorRegistration[];
217
- /**
218
- * Build a fake {@link ExecutionContext} pre-populated with the given
219
- * metadata. Symmetric with {@link runContributor}'s fake context.
220
- */
221
- makeContext(initial?: Record<string, unknown>): ExecutionContext;
222
- /**
223
- * Run every contributor the plugin ships through a built pipeline
224
- * against the given context. Dependencies resolve through the harness's
225
- * container (same path production uses). Throws if the plugin's
226
- * contributors reference `dependsOn` keys no one in the plugin provides.
227
- */
228
- runContributors(ctx: ExecutionContext): Promise<void>;
229
- }
230
- /**
231
- * Build an isolated test harness around a single {@link KickPlugin}.
232
- * Skips the full HTTP layer — symmetric with {@link runContributor} for
233
- * contributors and {@link createTestApp} for integration runs.
234
- *
235
- * @example
236
- * ```ts
237
- * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
238
- *
239
- * // The plugin's register() already ran — resolve any bindings.
240
- * const flags = harness.container.resolve(FLAGS_SERVICE)
241
- *
242
- * // Drive the post-bootstrap lifecycle.
243
- * await harness.callOnReady()
244
- *
245
- * // Exercise contributors shipped by the plugin.
246
- * const ctx = harness.makeContext({ requestId: 'req-1' })
247
- * await harness.runContributors(ctx)
248
- * expect(ctx.get('flags')).toEqual({ beta: true })
249
- *
250
- * await harness.shutdown()
251
- * ```
252
- */
253
- declare function createTestPlugin(plugin: KickPlugin, options?: CreateTestPluginOptions): Promise<PluginTestHarness>;
254
- /** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
255
- declare const testPlugin: typeof createTestPlugin;
256
- //#endregion
257
- export { CreateTestAppOptions, CreateTestPluginOptions, PluginTestHarness, RunContributorOptions, RunContributorResult, createTestApp, createTestModule, createTestPlugin, runContributor, testPlugin };
258
- //# sourceMappingURL=index.d.mts.map
2
+ import { a as RunContributorResult, c as createTestPlugin, d as onTestReset, f as resetTestState, h as TestRequest, i as RunContributorOptions, l as runContributor, m as TestClientOptions, n as CreateTestPluginOptions, o as createTestApp, p as TestClient, r as PluginTestHarness, s as createTestModule, t as CreateTestAppOptions, u as testPlugin } from "./index-B6ZZZiY_.mjs";
3
+ export { CreateTestAppOptions, CreateTestPluginOptions, PluginTestHarness, RunContributorOptions, RunContributorResult, type TestClient, type TestClientOptions, type TestRequest, createTestApp, createTestModule, createTestPlugin, onTestReset, resetTestState, runContributor, testPlugin };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-testing v8.0.0
2
+ * @forinda/kickjs-testing v8.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Application,Container,MissingContextValueError,buildPipeline,runContributors}from"@forinda/kickjs";function overrideEntries(overrides){if(Array.isArray(overrides))return overrides.map(([token,value])=>[token,value]);if(overrides instanceof Map)return[...overrides.entries()];let record=overrides;return Reflect.ownKeys(record).map(key=>[key,record[key]])}async function createTestApp(options){let container;options.isolated?container=Container.create():(Container.reset(),container=Container.getInstance());let app=new Application({modules:options.modules,adapters:options.adapters,port:options.port,apiPrefix:options.apiPrefix,defaultVersion:options.defaultVersion,middlewares:options.middlewares,onError:options.onError,onNotFound:options.onNotFound,plugins:options.plugins,trustProxy:options.trustProxy,jsonLimit:options.jsonLimit,security:options.security,contributors:options.contributors,contextStore:options.contextStore,runtime:options.runtime,health:options.health});if(await Promise.resolve(app.setup()),options.isolated){for(let entry of options.modules)(typeof entry==`function`?new entry:entry).register?.(container);container.bootstrap()}if(options.overrides)for(let[token,value]of overrideEntries(options.overrides))container.registerInstance(token,value);let runtimeName=app.getActiveRuntime().name;return{app,get expressApp(){if(runtimeName!==`express`)throw Error(`createTestApp: 'expressApp' is only available under the Express runtime — this app is running '${runtimeName}'. Drive the app instead, which follows whichever engine is configured: request(app.handle.bind(app)).get('/...').`);return app.getExpressApp()},container}}function createTestModule(config){class TestModule{register(container){config.register(container)}routes(){return config.routes()}}return TestModule}async function runContributor(decorator,options={}){let meta=new Map(Object.entries(options.initial??{})),ctx={get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:options.requestId??`test-req`},value=await decorator.registration.resolve(ctx,options.deps??{});return meta.set(decorator.registration.key,value),{value,ctx,meta}}async function createTestPlugin(plugin,options={}){let container=options.isolated??!0?Container.create():(Container.reset(),Container.getInstance());return options.skipRegister||plugin.register?.(container),{plugin,container,async callOnReady(){await plugin.onReady?.(container)},async shutdown(){await plugin.shutdown?.()},modules(){return plugin.modules?.()??[]},adapters(){return plugin.adapters?.()??[]},middleware(){return plugin.middleware?.()??[]},contributors(){return[...plugin.contributors?.()??[]]},makeContext(initial={}){let meta=new Map(Object.entries(initial));return{get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:`test-req`}},async runContributors(ctx){await runContributors({pipeline:buildPipeline([...plugin.contributors?.()??[]].map(registration=>({registration,source:`adapter`,label:plugin.name}))),ctx,container})}}}const testPlugin=createTestPlugin;export{createTestApp,createTestModule,createTestPlugin,runContributor,testPlugin};
12
- //# sourceMappingURL=index.mjs.map
11
+ import{a as testPlugin,i as runContributor,n as createTestModule,o as onTestReset,r as createTestPlugin,s as resetTestState,t as createTestApp}from"./src-rXAWiyjJ.mjs";export{createTestApp,createTestModule,createTestPlugin,onTestReset,resetTestState,runContributor,testPlugin};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs-testing v8.2.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import*as kick from"@forinda/kickjs";import{Application,Container,MissingContextValueError,buildPipeline,runContributors}from"@forinda/kickjs";let supertest;async function loadSupertest(){if(supertest!==void 0)return supertest;try{supertest=(await import(`supertest`)).default}catch{supertest=null}return supertest}const METHODS=[`get`,`post`,`put`,`patch`,`delete`,`head`,`options`];function createClient(app,request,options={},sharedAgent){if(!request)throw Error(`createTestApp: client() sends requests with supertest, which isn't installed — add it as a dev dependency`);let handler=app.handle.bind(app),agent=options.cookies?sharedAgent??request.agent(handler):void 0,own=lowerCaseKeys(options.headers),headers={...own};options.credential!==void 0&&options.auth?Object.assign(headers,lowerCaseKeys(options.auth(options.credential))):options.bearer&&(headers.authorization=`Bearer ${options.bearer}`);let base=options.basePath?.replace(/\/$/,``)??``,client={};for(let method of METHODS)client[method]=path=>{let test=(agent??request(handler))[method](`${base}${path}`);for(let[name,value]of Object.entries(headers))test=test.set(name,value);return test};return client.as=credential=>createClient(app,request,options.auth?{...options,headers:own,bearer:void 0,credential}:{...options,headers:own,bearer:credential,credential:void 0},agent),client.withHeaders=extra=>{let added=lowerCaseKeys(extra),bearer=`authorization`in added?void 0:options.bearer;return createClient(app,request,{...options,bearer,headers:{...own,...added}},agent)},client}function lowerCaseKeys(headers={}){return Object.fromEntries(Object.entries(headers).map(([k,v])=>[k.toLowerCase(),v]))}const resets=new Set;function onTestReset(reset){return resets.add(reset),()=>resets.delete(reset)}async function resetTestState(){let errors=[];for(let reset of resets)try{await reset()}catch(err){errors.push(err)}if(errors.length===1)throw errors[0];if(errors.length>1)throw AggregateError(errors,`${errors.length} test resets failed`)}function overrideEntries(overrides){if(Array.isArray(overrides))return overrides.map(([token,value])=>[token,value]);if(overrides instanceof Map)return[...overrides.entries()];let record=overrides;return Reflect.ownKeys(record).map(key=>[key,record[key]])}async function createTestApp(options){let container;options.isolated?container=Container.create():(Container.reset(),container=Container.getInstance());let app=new Application({modules:options.modules,adapters:options.adapters,port:options.port,apiPrefix:options.apiPrefix,defaultVersion:options.defaultVersion,middlewares:options.middlewares,onError:options.onError,onNotFound:options.onNotFound,plugins:options.plugins,trustProxy:options.trustProxy,jsonLimit:options.jsonLimit,security:options.security,contributors:options.contributors,contextStore:options.contextStore,runtime:options.runtime,health:options.health});if(await Promise.resolve(app.setup()),options.isolated){for(let entry of options.modules)(typeof entry==`function`?new entry:entry).register?.(container);container.bootstrap()}if(options.overrides)for(let[token,value]of overrideEntries(options.overrides))container.registerInstance(token,value);let runtimeName=app.getActiveRuntime().name,request=await loadSupertest();return{app,client:clientOptions=>createClient(app,request,clientOptions),get expressApp(){if(runtimeName!==`express`)throw Error(`createTestApp: 'expressApp' is only available under the Express runtime — this app is running '${runtimeName}'. Drive the app instead, which follows whichever engine is configured: request(app.handle.bind(app)).get('/...').`);return app.getExpressApp()},container}}function createTestModule(config){class TestModule{register(container){config.register(container)}routes(){return config.routes()}}return TestModule}async function runContributor(decorator,options={}){let meta=new Map(Object.entries(options.initial??{})),ctx={get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:options.requestId??`test-req`};Object.assign(ctx,options.ctx);let run=()=>decorator.registration.resolve(ctx,options.deps??{}),withEnv=kick.withEnv;if(options.env&&!withEnv)throw Error(`runContributor: the env option needs a newer @forinda/kickjs (withEnv)`);let value=await(options.env?withEnv(options.env,run):run());return meta.set(decorator.registration.key,value),{value,ctx,meta}}async function createTestPlugin(plugin,options={}){let container=options.isolated??!0?Container.create():(Container.reset(),Container.getInstance());return options.skipRegister||plugin.register?.(container),{plugin,container,async callOnReady(){await plugin.onReady?.(container)},async shutdown(){await plugin.shutdown?.()},modules(){return plugin.modules?.()??[]},adapters(){return plugin.adapters?.()??[]},middleware(){return plugin.middleware?.()??[]},contributors(){return[...plugin.contributors?.()??[]]},makeContext(initial={}){let meta=new Map(Object.entries(initial));return{get(key){return meta.get(key)},require(key){let value=meta.get(key);if(value===void 0)throw new MissingContextValueError(key);return value},set(key,value){meta.set(key,value)},requestId:`test-req`}},async runContributors(ctx){let sources=[...plugin.contributors?.()??[]].map(registration=>({registration,source:`adapter`,label:plugin.name})),pipeline=buildPipeline(sources);await runContributors({pipeline,ctx,container})}}}const testPlugin=createTestPlugin;export{testPlugin as a,runContributor as i,createTestModule as n,onTestReset as o,createTestPlugin as r,resetTestState as s,createTestApp as t};
12
+ //# sourceMappingURL=src-rXAWiyjJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-rXAWiyjJ.mjs","names":[],"sources":["../src/client.ts","../src/reset.ts","../src/index.ts"],"sourcesContent":["import type { Application } from '@forinda/kickjs'\n\n/** A request in flight — supertest's `Test`, chainable and awaitable. */\n// supertest stays an optional peer, so its type is described, not imported.\nexport type TestRequest = any\n\n/** Options for {@link TestClient} and `createTestApp(...).client()`. */\nexport interface TestClientOptions {\n /** Headers sent with every request: `{ host: 'localhost' }`, a tenant header. */\n headers?: Record<string, string>\n /** Sent as `Authorization: Bearer <token>`. */\n bearer?: string\n /**\n * How `.as(credential)` authenticates, when it isn't a bearer token — the\n * headers to send for a credential:\n *\n * client({ auth: (sid) => ({ cookie: `sid=${sid}` }) }).as(sessionId)\n * client({ auth: (key) => ({ 'x-api-key': key }) }).as(apiKey)\n *\n * Default: `Authorization: Bearer <credential>`.\n */\n auth?: (credential: string) => Record<string, string>\n /** Prefixed to every path: `basePath: '/api/v1'`, then `.get('/users')`. */\n basePath?: string\n /**\n * Keep cookies between requests, like a browser — for session and CSRF\n * flows. Default `false`: every request starts without cookies.\n */\n cookies?: boolean\n}\n\n/**\n * Requests against a test app, through whichever runtime it runs on, with\n * the headers every call needs set once:\n *\n * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })\n * await api.as(token).post('/invoices').send(body).expect(201)\n */\nexport interface TestClient {\n get(path: string): TestRequest\n post(path: string): TestRequest\n put(path: string): TestRequest\n patch(path: string): TestRequest\n delete(path: string): TestRequest\n head(path: string): TestRequest\n options(path: string): TestRequest\n /**\n * The same client, authenticated as `credential`: `Authorization: Bearer\n * <credential>`, or the headers the client's `auth` option makes of it.\n */\n as(credential: string): TestClient\n /** The same client, with these headers added (or replaced). */\n withHeaders(headers: Record<string, string>): TestClient\n}\n\ntype Supertest = ((app: unknown) => Record<string, (path: string) => TestRequest>) & {\n agent(app: unknown): Record<string, (path: string) => TestRequest>\n}\n\nlet supertest: Supertest | null | undefined\n\n/** supertest, if installed. Loaded once, on the first test app. */\nexport async function loadSupertest(): Promise<Supertest | null> {\n if (supertest !== undefined) return supertest\n try {\n supertest = ((await import('supertest')) as unknown as { default: Supertest }).default\n } catch {\n supertest = null\n }\n return supertest\n}\n\nconst METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'] as const\n\n/** A scoped client's state: the options, and the credential `.as()` gave it. */\ntype ClientState = TestClientOptions & {\n /** The credential from the last `.as()`, when `auth` turns it into headers. */\n credential?: string\n}\n\nexport function createClient(\n app: Application,\n request: Supertest | null,\n options: ClientState = {},\n sharedAgent?: Record<string, (path: string) => TestRequest>,\n): TestClient {\n if (!request) {\n throw new Error(\n \"createTestApp: client() sends requests with supertest, which isn't installed — add it as a dev dependency\",\n )\n }\n const handler = app.handle.bind(app)\n // One agent per client keeps cookies — shared with the clients scoped from\n // it, so `.as()` / `.withHeaders()` keep the same cookie jar. Otherwise a\n // fresh request each call.\n const agent = options.cookies ? (sharedAgent ?? request.agent(handler)) : undefined\n // Header names are case-insensitive: kept lower-case so a later one replaces\n // an earlier one. The credential's headers are made from it here, never\n // carried in `options.headers`, so a new credential replaces the old one\n // whole — a bearer token, or what an earlier `.as()` sent.\n const own = lowerCaseKeys(options.headers)\n const headers = { ...own }\n if (options.credential !== undefined && options.auth) {\n Object.assign(headers, lowerCaseKeys(options.auth(options.credential)))\n } else if (options.bearer) {\n headers.authorization = `Bearer ${options.bearer}`\n }\n const base = options.basePath?.replace(/\\/$/, '') ?? ''\n\n const client = {} as TestClient\n for (const method of METHODS) {\n client[method] = (path: string) => {\n let test = (agent ?? request(handler))[method](`${base}${path}`)\n for (const [name, value] of Object.entries(headers)) test = test.set(name, value)\n return test\n }\n }\n client.as = (credential) =>\n createClient(\n app,\n request,\n options.auth\n ? { ...options, headers: own, bearer: undefined, credential }\n : { ...options, headers: own, bearer: credential, credential: undefined },\n agent,\n )\n client.withHeaders = (extra) => {\n const added = lowerCaseKeys(extra)\n // An explicit Authorization replaces the inherited bearer token.\n const bearer = 'authorization' in added ? undefined : options.bearer\n return createClient(app, request, { ...options, bearer, headers: { ...own, ...added } }, agent)\n }\n return client\n}\n\nfunction lowerCaseKeys(headers: Record<string, string> = {}): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]))\n}\n","/**\n * Test state that outlives a test: in-memory fakes, caches, module-level\n * maps. Register a reset once, next to the thing it resets; `useTestApp`\n * runs them between test files (or tests), and `resetTestState()` runs them\n * anywhere else.\n *\n * export const sentEmails: Email[] = []\n * onTestReset(() => { sentEmails.length = 0 })\n */\nconst resets = new Set<() => unknown>()\n\n/** Register a reset; returns a function that unregisters it. */\nexport function onTestReset(reset: () => unknown): () => void {\n resets.add(reset)\n return () => resets.delete(reset)\n}\n\n/** Run every registered reset, in registration order. All run even if one throws. */\nexport async function resetTestState(): Promise<void> {\n const errors: unknown[] = []\n for (const reset of resets) {\n try {\n await reset()\n } catch (err) {\n errors.push(err)\n }\n }\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) throw new AggregateError(errors, `${errors.length} test resets failed`)\n}\n","import express from 'express'\nimport {\n Application,\n Container,\n buildPipeline,\n runContributors,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type AppModuleEntry,\n type ApplicationOptions,\n type ContextDecorator,\n type ContextMetaKey,\n type ContributorRegistration,\n type ExecutionContext,\n MissingContextValueError,\n type KickPlugin,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\nimport * as kick from '@forinda/kickjs'\nimport { createClient, loadSupertest, type TestClient, type TestClientOptions } from './client'\n\nexport type { TestClient, TestClientOptions, TestRequest } from './client'\nexport { onTestReset, resetTestState } from './reset'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middlewares'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n // The engine under test. Without this every test ran Express while\n // production ran Fastify or h3 — the one thing an integration test exists\n // to rule out.\n | 'runtime'\n // Without this the option is accepted by the type and dropped on the way\n // through, so `health: false` silently kept the endpoints mounted.\n | 'health'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n /**\n * Modules registered for the test run. Accepts both legacy class form\n * (`UserModule extends AppModule`) and `defineModule` factory output\n * (call the factory: `UserModule()`) — `Application` discriminates\n * at boot.\n */\n modules: AppModuleEntry[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /**\n * DI overrides applied after module registration.\n *\n * An object literal covers string and symbol keys. It cannot cover\n * `createToken()`, though — a token is a frozen OBJECT identified by\n * reference, and TypeScript rejects an object as a computed key\n * (`TS2464: A computed property name must be of type 'string', 'number',\n * 'symbol', or 'any'`). Since tokens are the documented way to bind an\n * interface to an implementation, that excluded exactly the key type most\n * worth overriding in a test.\n *\n * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is\n * a string, and the container keys tokens by reference, so the override is\n * accepted and never applied.\n *\n * Pass entries to override a token:\n *\n * ```ts\n * const DATABASE = createToken<Database>('app/Db/connection')\n *\n * await createTestApp({\n * modules: [UserModule()],\n * overrides: [[DATABASE, fakeDb()]],\n * })\n * ```\n *\n * A `Map` works too. The object form is unchanged.\n */\n overrides?:\n | Record<symbol | string, any>\n | ReadonlyArray<readonly [token: unknown, value: unknown]>\n | ReadonlyMap<unknown, unknown>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns the Application, which drives whichever runtime is configured.\n *\n * Drive it through `app` — `app.handle` is the Application's own Node request\n * listener and follows whichever runtime is configured, so the same test runs\n * against the engine you actually deploy.\n *\n * @example\n * ```ts\n * const { app, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n *\n * @example Test the engine you actually deploy\n * ```ts\n * import { fastifyRuntime } from '@forinda/kickjs/fastify'\n *\n * const { app } = await createTestApp({ modules: [UserModule], runtime: fastifyRuntime() })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n */\n/**\n * Normalize every accepted `overrides` shape to `[token, value]` pairs.\n *\n * An array or Map keeps the token's identity, which is what the container\n * matches on; an object literal is limited to string and symbol keys by the\n * language itself.\n */\nfunction overrideEntries(\n overrides: NonNullable<CreateTestAppOptions['overrides']>,\n): Array<[unknown, unknown]> {\n if (Array.isArray(overrides)) return overrides.map(([token, value]) => [token, value])\n if (overrides instanceof Map) return [...overrides.entries()]\n const record = overrides as Record<symbol | string, unknown>\n return Reflect.ownKeys(record).map((key) => [key, record[key as never]])\n}\n\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n /**\n * Requests against the app through whichever runtime it runs on, with the\n * headers every call needs set once (needs supertest installed):\n *\n * const api = client({ headers: { host: 'localhost' }, basePath: '/api/v1' })\n * await api.as(token).get('/me').expect(200)\n */\n client: (options?: TestClientOptions) => TestClient\n /**\n * @deprecated Use `app.handle.bind(app)`. Only valid under the Express\n * runtime — under\n * any other engine this throws rather than handing back that engine's\n * instance mistyped as `express.Express`, which is how a suite ends up\n * silently exercising the wrong runtime.\n */\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Left undefined so the Application applies its OWN defaults, including\n // the shared body-parsing policy (#590). Naming a middleware list here\n // put the Application on its user-declared branch, so a test app parsed\n // only `application/json` while the same app in production also parsed\n // `+json`, forms and text — the harness quietly tested a different\n // pipeline. The Application already guards on\n // `RuntimeCapabilities.nativeBodyParsing`, which is what kept a connect\n // parser off Fastify and h3.\n middlewares: options.middlewares,\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n // Without this the option is accepted and ignored, which is worse than\n // not offering it: the suite reports Express while claiming Fastify.\n runtime: options.runtime,\n health: options.health,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const entry of options.modules) {\n // Discriminate class vs instance — `defineModule` factories return\n // AppModule instances, legacy classes need `new`. Same dispatch\n // Application.setup() runs at boot.\n const mod: AppModule = typeof entry === 'function' ? new (entry as AppModuleClass)() : entry\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const [token, value] of overrideEntries(options.overrides)) {\n container.registerInstance(token, value)\n }\n }\n\n const runtimeName = app.getActiveRuntime().name\n const request = await loadSupertest()\n\n return {\n app,\n client: (clientOptions) => createClient(app, request, clientOptions),\n get expressApp(): express.Express {\n if (runtimeName !== 'express') {\n throw new Error(\n `createTestApp: 'expressApp' is only available under the Express runtime — ` +\n `this app is running '${runtimeName}'. Drive the app instead, which follows ` +\n `whichever engine is configured: request(app.handle.bind(app)).get('/...').`,\n )\n }\n return app.getExpressApp()\n },\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n\n /**\n * More fields on the fake context — what an HTTP contributor reads off it:\n * `{ req: { headers: { host: 'acme.example.com' } } }`.\n */\n ctx?: Record<string, unknown>\n\n /**\n * Env values `getEnv` / `ConfigService` return while `resolve()` runs —\n * parsed values, like `{ TRUST_PROXY: true }`. Restored afterwards.\n */\n env?: Record<string, unknown>\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends ContextMetaKey,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n // Same contract as RequestContext.require — a resolver under test\n // that depends on an upstream key should fail here exactly the way\n // it would in production, not read `undefined`.\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n Object.assign(ctx, options.ctx)\n\n const run = () => decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n // Looked up, not imported by name: the peer range reaches back before\n // withEnv existed, and a missing named import fails the whole module.\n const withEnv = (\n kick as { withEnv?: (env: Record<string, unknown>, fn: () => unknown) => Promise<unknown> }\n ).withEnv\n if (options.env && !withEnv) {\n throw new Error('runContributor: the env option needs a newer @forinda/kickjs (withEnv)')\n }\n const value = await (options.env ? withEnv!(options.env, run) : run())\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n\n// ── Plugin unit-test harness (architecture.md §21.3.2) ──────────────────\n\n/**\n * Options for {@link createTestPlugin}.\n */\nexport interface CreateTestPluginOptions {\n /**\n * Use an isolated container (default: `true`). Isolated harnesses never\n * touch the global `Container.getInstance()` singleton, so concurrent\n * tests can run without stomping each other's DI state.\n */\n isolated?: boolean\n\n /**\n * Skip auto-invoking `plugin.register(container)` — useful when a test\n * wants to assert container state *before* the plugin touches it.\n * Defaults to `false` (register is called eagerly).\n */\n skipRegister?: boolean\n}\n\n/**\n * Result of {@link createTestPlugin}. Mirrors the spec sketch in\n * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a\n * `runContributors()` helper that builds a one-plugin pipeline against a\n * fake `ExecutionContext`.\n */\nexport interface PluginTestHarness {\n /** The plugin under test — exposed for direct introspection. */\n readonly plugin: KickPlugin\n /** Isolated (or shared) DI container the plugin registered into. */\n readonly container: Container\n\n /**\n * Invoke `plugin.onReady(container)`. No-op if the plugin does not\n * define the hook.\n */\n callOnReady(): Promise<void>\n\n /**\n * Invoke `plugin.shutdown()`. No-op if the plugin does not define the\n * hook.\n */\n shutdown(): Promise<void>\n\n /**\n * Returns the module classes the plugin ships via `plugin.modules?()`.\n * The harness does **not** auto-instantiate them — use `createTestApp`\n * for that. Useful for assertions like \"the plugin exposes the module I\n * expect\".\n */\n modules(): AppModuleEntry[]\n\n /**\n * Returns adapter instances the plugin ships via `plugin.adapters?()`.\n * Useful for testing the adapters alongside the plugin's DI bindings.\n */\n adapters(): AppAdapter[]\n\n /**\n * Returns middleware entries the plugin ships via `plugin.middleware?()`.\n */\n middleware(): any[]\n\n /**\n * Returns contributor registrations the plugin ships via\n * `plugin.contributors?()`.\n */\n contributors(): ContributorRegistration[]\n\n /**\n * Build a fake {@link ExecutionContext} pre-populated with the given\n * metadata. Symmetric with {@link runContributor}'s fake context.\n */\n makeContext(initial?: Record<string, unknown>): ExecutionContext\n\n /**\n * Run every contributor the plugin ships through a built pipeline\n * against the given context. Dependencies resolve through the harness's\n * container (same path production uses). Throws if the plugin's\n * contributors reference `dependsOn` keys no one in the plugin provides.\n */\n runContributors(ctx: ExecutionContext): Promise<void>\n}\n\n/**\n * Build an isolated test harness around a single {@link KickPlugin}.\n * Skips the full HTTP layer — symmetric with {@link runContributor} for\n * contributors and {@link createTestApp} for integration runs.\n *\n * @example\n * ```ts\n * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))\n *\n * // The plugin's register() already ran — resolve any bindings.\n * const flags = harness.container.resolve(FLAGS_SERVICE)\n *\n * // Drive the post-bootstrap lifecycle.\n * await harness.callOnReady()\n *\n * // Exercise contributors shipped by the plugin.\n * const ctx = harness.makeContext({ requestId: 'req-1' })\n * await harness.runContributors(ctx)\n * expect(ctx.get('flags')).toEqual({ beta: true })\n *\n * await harness.shutdown()\n * ```\n */\nexport async function createTestPlugin(\n plugin: KickPlugin,\n options: CreateTestPluginOptions = {},\n): Promise<PluginTestHarness> {\n const isolated = options.isolated ?? true\n\n const container = isolated ? Container.create() : (Container.reset(), Container.getInstance())\n\n if (!options.skipRegister) plugin.register?.(container)\n\n return {\n plugin,\n container,\n\n async callOnReady() {\n await plugin.onReady?.(container)\n },\n\n async shutdown() {\n await plugin.shutdown?.()\n },\n\n modules() {\n return plugin.modules?.() ?? []\n },\n\n adapters() {\n return plugin.adapters?.() ?? []\n },\n\n middleware() {\n return plugin.middleware?.() ?? []\n },\n\n contributors() {\n return [...(plugin.contributors?.() ?? [])]\n },\n\n makeContext(initial: Record<string, unknown> = {}) {\n const meta = new Map<string, unknown>(Object.entries(initial))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: 'test-req',\n }\n return ctx\n },\n\n async runContributors(ctx: ExecutionContext) {\n const regs = plugin.contributors?.() ?? []\n const sources = [...regs].map((registration) => ({\n registration,\n source: 'adapter' as const,\n label: plugin.name,\n }))\n const pipeline = buildPipeline(sources)\n await runContributors({ pipeline, ctx, container })\n },\n }\n}\n\n/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */\nexport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MAAQ,KAAK,IAAI,GAAG,EAC1B,GAAI,QAAU,IAAA,GAAW,MAAM,IAAI,yBAAyB,GAAG,EAC/D,OAAO,KACT,EACA,IAAI,IAAK,MAAO,CACd,KAAK,IAAI,IAAK,KAAK,CACrB,EACA,UAAW,UAEJ,CACX,EAEA,MAAM,gBAAgB,IAAuB,CAE3C,IAAM,QAAU,CAAC,GADJ,OAAO,eAAe,GAAK,CAAC,CACjB,CAAC,CAAC,IAAK,eAAkB,CAC/C,aACA,OAAQ,UACR,MAAO,OAAO,IAChB,EAAE,EACI,SAAW,cAAc,OAAO,EACtC,MAAM,gBAAgB,CAAE,SAAU,IAAK,SAAU,CAAC,CACpD,CACF,CACF,CAGA,MAAa,WAAa"}
@@ -0,0 +1,33 @@
1
+
2
+ import { m as TestClientOptions, p as TestClient, t as CreateTestAppOptions } from "./index-B6ZZZiY_.mjs";
3
+ import { Application, Container } from "@forinda/kickjs";
4
+ //#region src/vitest.d.ts
5
+ export interface UseTestAppOptions {
6
+ /**
7
+ * Keep one app for every file this worker runs (with `isolate: false`)
8
+ * instead of one per file — far faster for a large suite. It is shut down
9
+ * when the worker exits. Default `false`.
10
+ *
11
+ * The app is built from the options of the FIRST file that asks for it;
12
+ * later files reuse it without calling their own. Files that need a
13
+ * differently configured app name their own: `shared: 'admin-api'` keeps
14
+ * one app per name. `true` is the name `'default'`.
15
+ */
16
+ shared?: boolean | string;
17
+ /**
18
+ * When `onTestReset` resets run: before each test file (`'file'`, the
19
+ * default), before each test (`'test'`), or never (`false`).
20
+ */
21
+ reset?: 'file' | 'test' | false;
22
+ /** Client options for `t.client()` with no arguments — the usual host or base path. */
23
+ client?: TestClientOptions;
24
+ }
25
+ export interface TestAppHandle {
26
+ readonly app: Application;
27
+ readonly container: Container;
28
+ /** A request client; with no options, the defaults from `useTestApp`. */
29
+ client(options?: TestClientOptions): TestClient;
30
+ }
31
+ export declare function useTestApp(options: () => CreateTestAppOptions | Promise<CreateTestAppOptions>, settings?: UseTestAppOptions): TestAppHandle;
32
+ //#endregion
33
+ //# sourceMappingURL=vitest.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vitest.d.mts","names":[],"sources":["../src/vitest.ts"],"mappings":";;;;iBAgBiB;;;;;;;;;;;EAWf;;;;;EAKA;;EAEA,SAAS;;iBAGM;WACN,KAAK;WACL,WAAW;;EAEpB,OAAO,UAAU,oBAAoB;;wBASvB,WACd,eAAe,uBAAuB,QAAQ,uBAC9C,WAAU,oBACT"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs-testing v8.2.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{s as resetTestState,t as createTestApp}from"./src-rXAWiyjJ.mjs";import{afterAll,beforeAll,beforeEach}from"vitest";const sharedApps=new Map;let shutdownRegistered=!1;function useTestApp(options,settings={}){let created,build=async()=>createTestApp(await options());beforeAll(async()=>{if(settings.reset!==!1&&await resetTestState(),settings.shared){let name=settings.shared===!0?`default`:settings.shared,app=sharedApps.get(name);app||(app=build(),sharedApps.set(name,app)),shutdownRegistered||(shutdownRegistered=!0,process.once(`beforeExit`,()=>{for(let shared of sharedApps.values())shared.then(({app})=>app.shutdown())})),created=await app}else created=await build()}),afterAll(async()=>{settings.shared||await created?.app.shutdown(),created=void 0}),settings.reset===`test`&&beforeEach(()=>resetTestState());let ready=()=>{if(!created)throw Error(`useTestApp: the app is only available inside tests and hooks`);return created};return{get app(){return ready().app},get container(){return ready().container},client(clientOptions){return ready().client(clientOptions??settings.client)}}}export{useTestApp};
12
+ //# sourceMappingURL=vitest.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vitest.mjs","names":[],"sources":["../src/vitest.ts"],"sourcesContent":["/**\n * Vitest wiring for a test app: one call per file instead of the\n * `let app` / `beforeAll` / `afterAll` boilerplate.\n *\n * const t = useTestApp(() => ({ ...appOptions, overrides: [[MAILER, fakeMailer]] }))\n *\n * it('lists invoices', async () => {\n * await t.client().as(token).get('/api/v1/invoices').expect(200)\n * })\n */\nimport { afterAll, beforeAll, beforeEach } from 'vitest'\nimport type { Application, Container } from '@forinda/kickjs'\nimport { createTestApp, type CreateTestAppOptions } from './index'\nimport type { TestClient, TestClientOptions } from './client'\nimport { resetTestState } from './reset'\n\nexport interface UseTestAppOptions {\n /**\n * Keep one app for every file this worker runs (with `isolate: false`)\n * instead of one per file — far faster for a large suite. It is shut down\n * when the worker exits. Default `false`.\n *\n * The app is built from the options of the FIRST file that asks for it;\n * later files reuse it without calling their own. Files that need a\n * differently configured app name their own: `shared: 'admin-api'` keeps\n * one app per name. `true` is the name `'default'`.\n */\n shared?: boolean | string\n /**\n * When `onTestReset` resets run: before each test file (`'file'`, the\n * default), before each test (`'test'`), or never (`false`).\n */\n reset?: 'file' | 'test' | false\n /** Client options for `t.client()` with no arguments — the usual host or base path. */\n client?: TestClientOptions\n}\n\nexport interface TestAppHandle {\n readonly app: Application\n readonly container: Container\n /** A request client; with no options, the defaults from `useTestApp`. */\n client(options?: TestClientOptions): TestClient\n}\n\ntype Created = Awaited<ReturnType<typeof createTestApp>>\n\n/** Shared apps by name, for the life of the worker. */\nconst sharedApps = new Map<string, Promise<Created>>()\nlet shutdownRegistered = false\n\nexport function useTestApp(\n options: () => CreateTestAppOptions | Promise<CreateTestAppOptions>,\n settings: UseTestAppOptions = {},\n): TestAppHandle {\n let created: Created | undefined\n const build = async () => createTestApp(await options())\n\n beforeAll(async () => {\n if (settings.reset !== false) await resetTestState()\n if (settings.shared) {\n const name = settings.shared === true ? 'default' : settings.shared\n let app = sharedApps.get(name)\n if (!app) {\n app = build()\n sharedApps.set(name, app)\n }\n if (!shutdownRegistered) {\n shutdownRegistered = true\n // Shared apps live as long as the worker. Vitest ends its workers when\n // the run is over, so a handle an app leaves open can't hold the run\n // up; this closes them cleanly when the worker drains.\n process.once('beforeExit', () => {\n for (const shared of sharedApps.values()) void shared.then(({ app }) => app.shutdown())\n })\n }\n created = await app\n } else {\n created = await build()\n }\n })\n\n afterAll(async () => {\n if (!settings.shared) await created?.app.shutdown()\n created = undefined\n })\n\n if (settings.reset === 'test') beforeEach(() => resetTestState())\n\n const ready = (): Created => {\n if (!created) throw new Error('useTestApp: the app is only available inside tests and hooks')\n return created\n }\n return {\n get app() {\n return ready().app\n },\n get container() {\n return ready().container\n },\n client(clientOptions) {\n return ready().client(clientOptions ?? settings.client)\n },\n }\n}\n"],"mappings":";;;;;;;;;;yHA+CA,MAAM,WAAa,IAAI,IACvB,IAAI,mBAAqB,GAEzB,SAAgB,WACd,QACA,SAA8B,CAAC,EAChB,CACf,IAAI,QACE,MAAQ,SAAY,cAAc,MAAM,QAAQ,CAAC,EAEvD,UAAU,SAAY,CAEpB,GADI,SAAS,QAAU,IAAO,MAAM,eAAe,EAC/C,SAAS,OAAQ,CACnB,IAAM,KAAO,SAAS,SAAW,GAAO,UAAY,SAAS,OACzD,IAAM,WAAW,IAAI,IAAI,EACxB,MACH,IAAM,MAAM,EACZ,WAAW,IAAI,KAAM,GAAG,GAErB,qBACH,mBAAqB,GAIrB,QAAQ,KAAK,iBAAoB,CAC/B,IAAK,IAAM,UAAU,WAAW,OAAO,EAAG,OAAY,MAAM,CAAE,OAAU,IAAI,SAAS,CAAC,CACxF,CAAC,GAEH,QAAU,MAAM,GAClB,KACE,SAAU,MAAM,MAAM,CAE1B,CAAC,EAED,SAAS,SAAY,CACd,SAAS,QAAQ,MAAM,SAAS,IAAI,SAAS,EAClD,QAAU,IAAA,EACZ,CAAC,EAEG,SAAS,QAAU,QAAQ,eAAiB,eAAe,CAAC,EAEhE,IAAM,UAAuB,CAC3B,GAAI,CAAC,QAAS,MAAU,MAAM,8DAA8D,EAC5F,OAAO,OACT,EACA,MAAO,CACL,IAAI,KAAM,CACR,OAAO,MAAM,CAAC,CAAC,GACjB,EACA,IAAI,WAAY,CACd,OAAO,MAAM,CAAC,CAAC,SACjB,EACA,OAAO,cAAe,CACpB,OAAO,MAAM,CAAC,CAAC,OAAO,eAAiB,SAAS,MAAM,CACxD,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-testing",
3
- "version": "8.0.0",
3
+ "version": "8.2.0",
4
4
  "description": "Test utilities, TestModule builder, and helpers for KickJS applications",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -22,27 +22,34 @@
22
22
  ".": {
23
23
  "import": "./dist/index.mjs",
24
24
  "types": "./dist/index.d.mts"
25
+ },
26
+ "./vitest": {
27
+ "import": "./dist/vitest.mjs",
28
+ "types": "./dist/vitest.d.mts"
25
29
  }
26
30
  },
27
31
  "files": [
28
32
  "dist"
29
33
  ],
30
- "dependencies": {},
31
34
  "peerDependencies": {
35
+ "@forinda/kickjs": ">=5.18.0",
32
36
  "express": "^5.1.0",
33
- "@forinda/kickjs": ">=5.18.0"
37
+ "supertest": ">=7.0.0",
38
+ "vitest": ">=3.0.0"
34
39
  },
35
40
  "devDependencies": {
36
- "@swc/core": "^1.16.1",
41
+ "@swc/core": "^1.16.13",
37
42
  "@types/express": "^5.0.6",
38
- "@types/node": "^26.4.0",
43
+ "@types/jsonwebtoken": "^9.0.10",
44
+ "@types/node": "^26.6.4",
39
45
  "@types/supertest": "^7.2.1",
40
46
  "express": "^5.1.0",
47
+ "jsonwebtoken": "^9.0.3",
41
48
  "reflect-metadata": "^0.2.2",
42
- "supertest": "^7.2.2",
49
+ "supertest": "^7.3.1",
43
50
  "typescript": "^7.0.2",
44
- "vitest": "^4.1.11",
45
- "@forinda/kickjs": "8.0.0"
51
+ "vitest": "^5.0.3",
52
+ "@forinda/kickjs": "9.0.3"
46
53
  },
47
54
  "publishConfig": {
48
55
  "access": "public"
@@ -61,7 +68,14 @@
61
68
  "bugs": {
62
69
  "url": "https://github.com/forinda/kick-js/issues"
63
70
  },
64
- "peerDependenciesMeta": {},
71
+ "peerDependenciesMeta": {
72
+ "supertest": {
73
+ "optional": true
74
+ },
75
+ "vitest": {
76
+ "optional": true
77
+ }
78
+ },
65
79
  "scripts": {
66
80
  "build": "tsdown",
67
81
  "dev": "tsdown --watch",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;KAyBK,8BAA8B,KACjC;;;;;UA0Be,6BAA6B;;;;;;;EAO5C,SAAS;;EAET,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6BX,YACI,+BACA,wBAAwB,gBAAgB,mBACxC;;;;;;EAMJ;;iBA6CoB,cAAc,SAAS,uBAAuB;EAClE,KAAK;;;;;;;;EAQL,YAAY,QAAQ;EACpB,WAAW;;;;;;;;;;;;;;;;;iBAqGG,iBAAiB;EAC/B,WAAW,WAAW;EACtB,cAAc,eAAe;IAC3B;;;;UAiBa;;;;;;;;;EASf,OAAO;;;;;;;EAQP,UAAU;;EAGV;;;;;UAMe,qBAAqB;;EAEpC,OAAO,UAAU;;EAEjB,KAAK;;;;;;EAML,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Bc,eACpB,UAAU,gBACV,UAAU,sBAAsB,uBAEhC,WAAW,iBAAiB,GAAG,IAC/B,UAAS,wBACR,QAAQ,qBAAqB;;;;UA+Bf;;;;;;EAMf;;;;;;EAOA;;;;;;;;UASe;;WAEN,QAAQ;;WAER,WAAW;;;;;EAMpB,eAAe;;;;;EAMf,YAAY;;;;;;;EAQZ,WAAW;;;;;EAMX,YAAY;;;;EAKZ;;;;;EAMA,gBAAgB;;;;;EAMhB,YAAY,UAAU,0BAA0B;;;;;;;EAQhD,gBAAgB,KAAK,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BpB,iBACpB,QAAQ,YACR,UAAS,0BACR,QAAQ;;cAoEE,mBAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import express from 'express'\nimport {\n Application,\n Container,\n buildPipeline,\n runContributors,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type AppModuleEntry,\n type ApplicationOptions,\n type ContextDecorator,\n type ContextMetaKey,\n type ContributorRegistration,\n type ExecutionContext,\n MissingContextValueError,\n type KickPlugin,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middlewares'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n // The engine under test. Without this every test ran Express while\n // production ran Fastify or h3 — the one thing an integration test exists\n // to rule out.\n | 'runtime'\n // Without this the option is accepted by the type and dropped on the way\n // through, so `health: false` silently kept the endpoints mounted.\n | 'health'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n /**\n * Modules registered for the test run. Accepts both legacy class form\n * (`UserModule extends AppModule`) and `defineModule` factory output\n * (call the factory: `UserModule()`) — `Application` discriminates\n * at boot.\n */\n modules: AppModuleEntry[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /**\n * DI overrides applied after module registration.\n *\n * An object literal covers string and symbol keys. It cannot cover\n * `createToken()`, though — a token is a frozen OBJECT identified by\n * reference, and TypeScript rejects an object as a computed key\n * (`TS2464: A computed property name must be of type 'string', 'number',\n * 'symbol', or 'any'`). Since tokens are the documented way to bind an\n * interface to an implementation, that excluded exactly the key type most\n * worth overriding in a test.\n *\n * Worse, the obvious workaround compiles and does nothing: `[TOKEN.name]` is\n * a string, and the container keys tokens by reference, so the override is\n * accepted and never applied.\n *\n * Pass entries to override a token:\n *\n * ```ts\n * const DATABASE = createToken<Database>('app/Db/connection')\n *\n * await createTestApp({\n * modules: [UserModule()],\n * overrides: [[DATABASE, fakeDb()]],\n * })\n * ```\n *\n * A `Map` works too. The object form is unchanged.\n */\n overrides?:\n | Record<symbol | string, any>\n | ReadonlyArray<readonly [token: unknown, value: unknown]>\n | ReadonlyMap<unknown, unknown>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns the Application, which drives whichever runtime is configured.\n *\n * Drive it through `app` — `app.handle` is the Application's own Node request\n * listener and follows whichever runtime is configured, so the same test runs\n * against the engine you actually deploy.\n *\n * @example\n * ```ts\n * const { app, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n *\n * @example Test the engine you actually deploy\n * ```ts\n * import { fastifyRuntime } from '@forinda/kickjs/fastify'\n *\n * const { app } = await createTestApp({ modules: [UserModule], runtime: fastifyRuntime() })\n * const res = await request(app.handle.bind(app)).get('/api/v1/users')\n * ```\n */\n/**\n * Normalize every accepted `overrides` shape to `[token, value]` pairs.\n *\n * An array or Map keeps the token's identity, which is what the container\n * matches on; an object literal is limited to string and symbol keys by the\n * language itself.\n */\nfunction overrideEntries(\n overrides: NonNullable<CreateTestAppOptions['overrides']>,\n): Array<[unknown, unknown]> {\n if (Array.isArray(overrides)) return overrides.map(([token, value]) => [token, value])\n if (overrides instanceof Map) return [...overrides.entries()]\n const record = overrides as Record<symbol | string, unknown>\n return Reflect.ownKeys(record).map((key) => [key, record[key as never]])\n}\n\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n /**\n * @deprecated Use `app.handle.bind(app)`. Only valid under the Express\n * runtime — under\n * any other engine this throws rather than handing back that engine's\n * instance mistyped as `express.Express`, which is how a suite ends up\n * silently exercising the wrong runtime.\n */\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Left undefined so the Application applies its OWN defaults, including\n // the shared body-parsing policy (#590). Naming a middleware list here\n // put the Application on its user-declared branch, so a test app parsed\n // only `application/json` while the same app in production also parsed\n // `+json`, forms and text — the harness quietly tested a different\n // pipeline. The Application already guards on\n // `RuntimeCapabilities.nativeBodyParsing`, which is what kept a connect\n // parser off Fastify and h3.\n middlewares: options.middlewares,\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n // Without this the option is accepted and ignored, which is worse than\n // not offering it: the suite reports Express while claiming Fastify.\n runtime: options.runtime,\n health: options.health,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const entry of options.modules) {\n // Discriminate class vs instance — `defineModule` factories return\n // AppModule instances, legacy classes need `new`. Same dispatch\n // Application.setup() runs at boot.\n const mod: AppModule = typeof entry === 'function' ? new (entry as AppModuleClass)() : entry\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const [token, value] of overrideEntries(options.overrides)) {\n container.registerInstance(token, value)\n }\n }\n\n const runtimeName = app.getActiveRuntime().name\n\n return {\n app,\n get expressApp(): express.Express {\n if (runtimeName !== 'express') {\n throw new Error(\n `createTestApp: 'expressApp' is only available under the Express runtime — ` +\n `this app is running '${runtimeName}'. Drive the app instead, which follows ` +\n `whichever engine is configured: request(app.handle.bind(app)).get('/...').`,\n )\n }\n return app.getExpressApp()\n },\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends ContextMetaKey,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n // Same contract as RequestContext.require — a resolver under test\n // that depends on an upstream key should fail here exactly the way\n // it would in production, not read `undefined`.\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n\n const value = await decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n\n// ── Plugin unit-test harness (architecture.md §21.3.2) ──────────────────\n\n/**\n * Options for {@link createTestPlugin}.\n */\nexport interface CreateTestPluginOptions {\n /**\n * Use an isolated container (default: `true`). Isolated harnesses never\n * touch the global `Container.getInstance()` singleton, so concurrent\n * tests can run without stomping each other's DI state.\n */\n isolated?: boolean\n\n /**\n * Skip auto-invoking `plugin.register(container)` — useful when a test\n * wants to assert container state *before* the plugin touches it.\n * Defaults to `false` (register is called eagerly).\n */\n skipRegister?: boolean\n}\n\n/**\n * Result of {@link createTestPlugin}. Mirrors the spec sketch in\n * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a\n * `runContributors()` helper that builds a one-plugin pipeline against a\n * fake `ExecutionContext`.\n */\nexport interface PluginTestHarness {\n /** The plugin under test — exposed for direct introspection. */\n readonly plugin: KickPlugin\n /** Isolated (or shared) DI container the plugin registered into. */\n readonly container: Container\n\n /**\n * Invoke `plugin.onReady(container)`. No-op if the plugin does not\n * define the hook.\n */\n callOnReady(): Promise<void>\n\n /**\n * Invoke `plugin.shutdown()`. No-op if the plugin does not define the\n * hook.\n */\n shutdown(): Promise<void>\n\n /**\n * Returns the module classes the plugin ships via `plugin.modules?()`.\n * The harness does **not** auto-instantiate them — use `createTestApp`\n * for that. Useful for assertions like \"the plugin exposes the module I\n * expect\".\n */\n modules(): AppModuleEntry[]\n\n /**\n * Returns adapter instances the plugin ships via `plugin.adapters?()`.\n * Useful for testing the adapters alongside the plugin's DI bindings.\n */\n adapters(): AppAdapter[]\n\n /**\n * Returns middleware entries the plugin ships via `plugin.middleware?()`.\n */\n middleware(): any[]\n\n /**\n * Returns contributor registrations the plugin ships via\n * `plugin.contributors?()`.\n */\n contributors(): ContributorRegistration[]\n\n /**\n * Build a fake {@link ExecutionContext} pre-populated with the given\n * metadata. Symmetric with {@link runContributor}'s fake context.\n */\n makeContext(initial?: Record<string, unknown>): ExecutionContext\n\n /**\n * Run every contributor the plugin ships through a built pipeline\n * against the given context. Dependencies resolve through the harness's\n * container (same path production uses). Throws if the plugin's\n * contributors reference `dependsOn` keys no one in the plugin provides.\n */\n runContributors(ctx: ExecutionContext): Promise<void>\n}\n\n/**\n * Build an isolated test harness around a single {@link KickPlugin}.\n * Skips the full HTTP layer — symmetric with {@link runContributor} for\n * contributors and {@link createTestApp} for integration runs.\n *\n * @example\n * ```ts\n * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))\n *\n * // The plugin's register() already ran — resolve any bindings.\n * const flags = harness.container.resolve(FLAGS_SERVICE)\n *\n * // Drive the post-bootstrap lifecycle.\n * await harness.callOnReady()\n *\n * // Exercise contributors shipped by the plugin.\n * const ctx = harness.makeContext({ requestId: 'req-1' })\n * await harness.runContributors(ctx)\n * expect(ctx.get('flags')).toEqual({ beta: true })\n *\n * await harness.shutdown()\n * ```\n */\nexport async function createTestPlugin(\n plugin: KickPlugin,\n options: CreateTestPluginOptions = {},\n): Promise<PluginTestHarness> {\n const isolated = options.isolated ?? true\n\n const container = isolated ? Container.create() : (Container.reset(), Container.getInstance())\n\n if (!options.skipRegister) plugin.register?.(container)\n\n return {\n plugin,\n container,\n\n async callOnReady() {\n await plugin.onReady?.(container)\n },\n\n async shutdown() {\n await plugin.shutdown?.()\n },\n\n modules() {\n return plugin.modules?.() ?? []\n },\n\n adapters() {\n return plugin.adapters?.() ?? []\n },\n\n middleware() {\n return plugin.middleware?.() ?? []\n },\n\n contributors() {\n return [...(plugin.contributors?.() ?? [])]\n },\n\n makeContext(initial: Record<string, unknown> = {}) {\n const meta = new Map<string, unknown>(Object.entries(initial))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n require(key) {\n const value = meta.get(key)\n if (value === undefined) throw new MissingContextValueError(key)\n return value as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: 'test-req',\n }\n return ctx\n },\n\n async runContributors(ctx: ExecutionContext) {\n const regs = plugin.contributors?.() ?? []\n const sources = [...regs].map((registration) => ({\n registration,\n source: 'adapter' as const,\n label: plugin.name,\n }))\n const pipeline = buildPipeline(sources)\n await runContributors({ pipeline, ctx, container })\n },\n }\n}\n\n/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */\nex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