@stratal/testing 0.0.18 → 0.0.19
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/dist/index.d.mts +36 -18
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +48 -23
- package/dist/index.mjs.map +1 -1
- package/dist/storage/index.mjs +1 -1
- package/dist/{storage-CGRm_2Nh.mjs → storage-DZbrPg-l.mjs} +4 -4
- package/dist/{storage-CGRm_2Nh.mjs.map → storage-DZbrPg-l.mjs.map} +1 -1
- package/package.json +13 -13
package/dist/index.d.mts
CHANGED
|
@@ -6,6 +6,7 @@ import { ConnectionName, DatabaseService } from "@stratal/framework/database";
|
|
|
6
6
|
import { Seeder } from "stratal/seeder";
|
|
7
7
|
import { DetectionStrategy } from "stratal/i18n";
|
|
8
8
|
import { AuthService } from "@stratal/framework/auth";
|
|
9
|
+
import { Macroable } from "stratal/macroable";
|
|
9
10
|
import { HttpResponse, RequestHandler, http } from "msw";
|
|
10
11
|
import { CommandInput, CommandResult } from "stratal/quarry";
|
|
11
12
|
|
|
@@ -23,7 +24,7 @@ import { CommandInput, CommandResult } from "stratal/quarry";
|
|
|
23
24
|
* .assertJsonPath('data.id', userId)
|
|
24
25
|
* ```
|
|
25
26
|
*/
|
|
26
|
-
declare class TestResponse {
|
|
27
|
+
declare class TestResponse extends Macroable {
|
|
27
28
|
private readonly response;
|
|
28
29
|
private jsonData;
|
|
29
30
|
private textData;
|
|
@@ -186,15 +187,23 @@ declare class TestResponse {
|
|
|
186
187
|
* .send()
|
|
187
188
|
* ```
|
|
188
189
|
*/
|
|
189
|
-
declare class TestHttpRequest {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
190
|
+
declare class TestHttpRequest extends Macroable {
|
|
191
|
+
protected readonly method: string;
|
|
192
|
+
protected readonly path: string;
|
|
193
|
+
protected readonly module: TestingModule;
|
|
194
|
+
protected readonly host: string | null;
|
|
195
|
+
protected body: unknown;
|
|
196
|
+
protected requestHeaders: Headers;
|
|
197
|
+
protected actingAsUser: {
|
|
198
|
+
id: string;
|
|
199
|
+
} | null;
|
|
200
|
+
protected authResolver: ((module: TestingModule, user: {
|
|
201
|
+
id: string;
|
|
202
|
+
}) => Promise<Headers>) | null;
|
|
203
|
+
protected localeConfig: {
|
|
204
|
+
locale: string;
|
|
205
|
+
strategy: DetectionStrategy;
|
|
206
|
+
} | null;
|
|
198
207
|
constructor(method: string, path: string, headers: Headers, module: TestingModule, host?: string | null, localeConfig?: {
|
|
199
208
|
locale: string;
|
|
200
209
|
strategy: DetectionStrategy;
|
|
@@ -231,7 +240,7 @@ declare class TestHttpRequest {
|
|
|
231
240
|
* Calls module.fetch() - NOT SELF.fetch()
|
|
232
241
|
*/
|
|
233
242
|
send(): Promise<TestResponse>;
|
|
234
|
-
|
|
243
|
+
protected applyAuthentication(): Promise<void>;
|
|
235
244
|
}
|
|
236
245
|
//#endregion
|
|
237
246
|
//#region src/core/http/test-http-client.d.ts
|
|
@@ -256,23 +265,28 @@ declare class TestHttpClient {
|
|
|
256
265
|
private defaultHeaders;
|
|
257
266
|
private host;
|
|
258
267
|
private localeConfig;
|
|
259
|
-
constructor(module: TestingModule
|
|
268
|
+
constructor(module: TestingModule, host?: string | null, headers?: Headers, localeConfig?: {
|
|
269
|
+
locale: string;
|
|
270
|
+
strategy: DetectionStrategy;
|
|
271
|
+
} | null);
|
|
260
272
|
/**
|
|
261
|
-
* Set the host for the request
|
|
273
|
+
* Set the host for the request (returns a new client).
|
|
274
|
+
* Also sets the Host header to ensure domain routing works
|
|
275
|
+
* even when the runtime reads the header instead of the URL host.
|
|
262
276
|
*/
|
|
263
|
-
forHost(host: string):
|
|
277
|
+
forHost(host: string): TestHttpClient;
|
|
264
278
|
/**
|
|
265
|
-
* Set default headers for all requests
|
|
279
|
+
* Set default headers for all requests (returns a new client)
|
|
266
280
|
*/
|
|
267
|
-
withHeaders(headers: Record<string, string>):
|
|
281
|
+
withHeaders(headers: Record<string, string>): TestHttpClient;
|
|
268
282
|
/**
|
|
269
|
-
* Set the locale for all requests from this client.
|
|
283
|
+
* Set the locale for all requests from this client (returns a new client).
|
|
270
284
|
* If strategy is not provided, resolves from the module's I18n configuration.
|
|
271
285
|
*
|
|
272
286
|
* @param locale - Locale code (e.g., 'en', 'fr')
|
|
273
287
|
* @param strategy - Detection strategy override
|
|
274
288
|
*/
|
|
275
|
-
withLocale(locale: string, strategy?: DetectionStrategy):
|
|
289
|
+
withLocale(locale: string, strategy?: DetectionStrategy): TestHttpClient;
|
|
276
290
|
/**
|
|
277
291
|
* Create a GET request
|
|
278
292
|
*/
|
|
@@ -611,6 +625,10 @@ declare class TestingModule {
|
|
|
611
625
|
* Get HTTP test client for making requests
|
|
612
626
|
*/
|
|
613
627
|
get http(): TestHttpClient;
|
|
628
|
+
/**
|
|
629
|
+
* Get Inertia test client for making Inertia requests
|
|
630
|
+
*/
|
|
631
|
+
get inertia(): TestHttpClient;
|
|
614
632
|
/**
|
|
615
633
|
* Get fake storage service for assertions
|
|
616
634
|
*/
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/core/http/test-response.ts","../src/core/http/test-http-request.ts","../src/core/http/test-http-client.ts","../src/core/quarry/test-command-result.ts","../src/core/quarry/test-command-request.ts","../src/core/sse/test-sse-connection.ts","../src/core/sse/test-sse-request.ts","../src/core/ws/test-ws-connection.ts","../src/core/ws/test-ws-request.ts","../src/core/testing-module.ts","../src/core/testing-module-builder.ts","../src/core/override/provider-override-builder.ts","../src/core/test.ts","../src/core/http/path-utils.ts","../src/core/http/fetch-mock.types.ts","../src/core/http/mock-fetch.ts","../src/auth/acting-as.ts","../src/errors/test-error.ts","../src/errors/setup-error.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/core/http/test-response.ts","../src/core/http/test-http-request.ts","../src/core/http/test-http-client.ts","../src/core/quarry/test-command-result.ts","../src/core/quarry/test-command-request.ts","../src/core/sse/test-sse-connection.ts","../src/core/sse/test-sse-request.ts","../src/core/ws/test-ws-connection.ts","../src/core/ws/test-ws-request.ts","../src/core/testing-module.ts","../src/core/testing-module-builder.ts","../src/core/override/provider-override-builder.ts","../src/core/test.ts","../src/core/http/path-utils.ts","../src/core/http/fetch-mock.types.ts","../src/core/http/mock-fetch.ts","../src/auth/acting-as.ts","../src/errors/test-error.ts","../src/errors/setup-error.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiBA;cAAa,YAAA,SAAqB,SAAA;EAAA,iBAIH,QAAA;EAAA,QAHrB,QAAA;EAAA,QACA,QAAA;cAEqB,QAAA,EAAU,QAAA;EA4BJ;;;EAAA,IArB/B,GAAA,CAAA,GAAO,QAAA;EAoI0C;;;EAAA,IA7HjD,MAAA,CAAA;EAkMuC;;;EAAA,IA3LvC,OAAA,CAAA,GAAW,OAAA;EAgRyC;;;EAzQlD,IAAA,aAAA,CAAA,GAAqB,OAAA,CAAQ,CAAA;EAhCM;;;EA0CnC,IAAA,CAAA,GAAQ,OAAA;EAzCN;;;EAqDR,QAAA,CAAA;EAlD6B;;;EAyD7B,aAAA,CAAA;EApCI;;;EA2CJ,eAAA,CAAA;EApC2B;;;EA2C3B,gBAAA,CAAA;EArBA;;;EA4BA,kBAAA,CAAA;EAAA;;;EAOA,eAAA,CAAA;EAqBA;;;EAdA,cAAA,CAAA;EA+CM;;;EAxCN,mBAAA,CAAA;EA2DM;;;EApDN,iBAAA,CAAA;EAmEM;;;EA5DN,YAAA,CAAa,QAAA;EA8Ec;;;EAnE3B,gBAAA,CAAA;EAoF2C;;;EArErC,UAAA,CAAW,QAAA,EAAU,MAAA,oBAA0B,OAAA;EAyFnD;;;;;;EAtEI,cAAA,CAAe,IAAA,UAAc,QAAA,YAAoB,OAAA;EAgH1B;;;EAjGvB,mBAAA,CA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;;iBA4BpD,eAAA,CAAgB,QAAA,GAAW,cAAA,KAAmB,SAAA;;;;;;;;;;;;;;;cCzFjD,QAAA;EAAA,iBACkB,WAAA;cAAA,WAAA,EAAa,WAAA;EAEpC,oBAAA,CAAqB,IAAA;IAAQ,EAAA;EAAA,IAAe,OAAA,CAAQ,OAAA;AAAA;;;;;;;cCnC/C,SAAA,SAAkB,KAAA;EAAA,SAGX,KAAA,GAAQ,KAAA;cADxB,OAAA,UACgB,KAAA,GAAQ,KAAA;AAAA;;;;;;;cCDf,cAAA,SAAuB,SAAA;cACtB,OAAA,UAAiB,KAAA,GAAQ,KAAA;AAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as __decorate, t as FakeStorageService } from "./storage-
|
|
1
|
+
import { n as __decorate, t as FakeStorageService } from "./storage-DZbrPg-l.mjs";
|
|
2
2
|
import { Application } from "stratal";
|
|
3
3
|
import { LogLevel } from "stratal/logger";
|
|
4
4
|
import { Module } from "stratal/module";
|
|
@@ -9,6 +9,7 @@ import { connectionSymbol } from "@stratal/framework/database";
|
|
|
9
9
|
import { SEEDER_TOKENS, SeederNotRegisteredError } from "stratal/seeder";
|
|
10
10
|
import { I18N_TOKENS } from "stratal/i18n";
|
|
11
11
|
import { AUTH_SERVICE } from "@stratal/framework/auth";
|
|
12
|
+
import { Macroable } from "stratal/macroable";
|
|
12
13
|
import { setSessionCookie } from "better-auth/cookies";
|
|
13
14
|
import { convertSetCookieToCookie } from "better-auth/test";
|
|
14
15
|
import { HttpResponse, HttpResponse as HttpResponse$1, http, http as http$1 } from "msw";
|
|
@@ -247,10 +248,11 @@ function hasValueAtPath(obj, path) {
|
|
|
247
248
|
* .assertJsonPath('data.id', userId)
|
|
248
249
|
* ```
|
|
249
250
|
*/
|
|
250
|
-
var TestResponse = class {
|
|
251
|
+
var TestResponse = class extends Macroable {
|
|
251
252
|
jsonData = null;
|
|
252
253
|
textData = null;
|
|
253
254
|
constructor(response) {
|
|
255
|
+
super();
|
|
254
256
|
this.response = response;
|
|
255
257
|
}
|
|
256
258
|
/**
|
|
@@ -500,12 +502,14 @@ var TestResponse = class {
|
|
|
500
502
|
* .send()
|
|
501
503
|
* ```
|
|
502
504
|
*/
|
|
503
|
-
var TestHttpRequest = class {
|
|
505
|
+
var TestHttpRequest = class extends Macroable {
|
|
504
506
|
body = null;
|
|
505
507
|
requestHeaders;
|
|
506
508
|
actingAsUser = null;
|
|
509
|
+
authResolver = null;
|
|
507
510
|
localeConfig;
|
|
508
511
|
constructor(method, path, headers, module, host = null, localeConfig = null) {
|
|
512
|
+
super();
|
|
509
513
|
this.method = method;
|
|
510
514
|
this.path = path;
|
|
511
515
|
this.module = module;
|
|
@@ -555,6 +559,7 @@ var TestHttpRequest = class {
|
|
|
555
559
|
*/
|
|
556
560
|
actingAs(user) {
|
|
557
561
|
this.actingAsUser = user;
|
|
562
|
+
this.authResolver = null;
|
|
558
563
|
return this;
|
|
559
564
|
}
|
|
560
565
|
/**
|
|
@@ -576,9 +581,13 @@ var TestHttpRequest = class {
|
|
|
576
581
|
}
|
|
577
582
|
async applyAuthentication() {
|
|
578
583
|
if (!this.actingAsUser) return;
|
|
584
|
+
if (this.authResolver) {
|
|
585
|
+
const headers = await this.authResolver(this.module, this.actingAsUser);
|
|
586
|
+
for (const [key, value] of headers.entries()) this.requestHeaders.set(key, value);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
579
589
|
await this.module.runInRequestScope(async () => {
|
|
580
|
-
const
|
|
581
|
-
const authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers();
|
|
590
|
+
const authHeaders = await new ActingAs(this.module.get(AUTH_SERVICE)).createSessionForUser(this.actingAsUser);
|
|
582
591
|
for (const [key, value] of authHeaders.entries()) this.requestHeaders.set(key, value);
|
|
583
592
|
});
|
|
584
593
|
}
|
|
@@ -601,29 +610,36 @@ var TestHttpRequest = class {
|
|
|
601
610
|
* response.assertCreated()
|
|
602
611
|
* ```
|
|
603
612
|
*/
|
|
604
|
-
var TestHttpClient = class {
|
|
605
|
-
defaultHeaders
|
|
606
|
-
host
|
|
607
|
-
localeConfig
|
|
608
|
-
constructor(module) {
|
|
613
|
+
var TestHttpClient = class TestHttpClient {
|
|
614
|
+
defaultHeaders;
|
|
615
|
+
host;
|
|
616
|
+
localeConfig;
|
|
617
|
+
constructor(module, host = null, headers = new Headers(), localeConfig = null) {
|
|
609
618
|
this.module = module;
|
|
619
|
+
this.host = host;
|
|
620
|
+
this.defaultHeaders = headers;
|
|
621
|
+
this.localeConfig = localeConfig;
|
|
610
622
|
}
|
|
611
623
|
/**
|
|
612
|
-
* Set the host for the request
|
|
624
|
+
* Set the host for the request (returns a new client).
|
|
625
|
+
* Also sets the Host header to ensure domain routing works
|
|
626
|
+
* even when the runtime reads the header instead of the URL host.
|
|
613
627
|
*/
|
|
614
628
|
forHost(host) {
|
|
615
|
-
|
|
616
|
-
|
|
629
|
+
const newHeaders = new Headers(this.defaultHeaders);
|
|
630
|
+
newHeaders.set("Host", host);
|
|
631
|
+
return new TestHttpClient(this.module, host, newHeaders, this.localeConfig);
|
|
617
632
|
}
|
|
618
633
|
/**
|
|
619
|
-
* Set default headers for all requests
|
|
634
|
+
* Set default headers for all requests (returns a new client)
|
|
620
635
|
*/
|
|
621
636
|
withHeaders(headers) {
|
|
622
|
-
|
|
623
|
-
|
|
637
|
+
const newHeaders = new Headers(this.defaultHeaders);
|
|
638
|
+
for (const [key, value] of Object.entries(headers)) newHeaders.set(key, value);
|
|
639
|
+
return new TestHttpClient(this.module, this.host, newHeaders, this.localeConfig);
|
|
624
640
|
}
|
|
625
641
|
/**
|
|
626
|
-
* Set the locale for all requests from this client.
|
|
642
|
+
* Set the locale for all requests from this client (returns a new client).
|
|
627
643
|
* If strategy is not provided, resolves from the module's I18n configuration.
|
|
628
644
|
*
|
|
629
645
|
* @param locale - Locale code (e.g., 'en', 'fr')
|
|
@@ -631,12 +647,12 @@ var TestHttpClient = class {
|
|
|
631
647
|
*/
|
|
632
648
|
withLocale(locale, strategy) {
|
|
633
649
|
const resolved = strategy ?? resolveLocaleStrategy(this.module);
|
|
634
|
-
|
|
650
|
+
const newHeaders = new Headers(this.defaultHeaders);
|
|
651
|
+
applyLocaleToHeaders(newHeaders, locale, resolved);
|
|
652
|
+
return new TestHttpClient(this.module, this.host, newHeaders, {
|
|
635
653
|
locale,
|
|
636
654
|
strategy: resolved
|
|
637
|
-
};
|
|
638
|
-
applyLocaleToHeaders(this.defaultHeaders, locale, resolved);
|
|
639
|
-
return this;
|
|
655
|
+
});
|
|
640
656
|
}
|
|
641
657
|
/**
|
|
642
658
|
* Create a GET request
|
|
@@ -1273,6 +1289,15 @@ var TestingModule = class {
|
|
|
1273
1289
|
return this._http;
|
|
1274
1290
|
}
|
|
1275
1291
|
/**
|
|
1292
|
+
* Get Inertia test client for making Inertia requests
|
|
1293
|
+
*/
|
|
1294
|
+
get inertia() {
|
|
1295
|
+
return this.http.withHeaders({
|
|
1296
|
+
"X-Inertia": "true",
|
|
1297
|
+
"X-Inertia-Version": "1"
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1276
1301
|
* Get fake storage service for assertions
|
|
1277
1302
|
*/
|
|
1278
1303
|
get storage() {
|
|
@@ -1312,7 +1337,7 @@ var TestingModule = class {
|
|
|
1312
1337
|
* Execute an HTTP request through HonoApp
|
|
1313
1338
|
*/
|
|
1314
1339
|
async fetch(request) {
|
|
1315
|
-
return this.app.
|
|
1340
|
+
return (await this.app.ensureHono()).fetch(request, this.env, this.ctx);
|
|
1316
1341
|
}
|
|
1317
1342
|
/**
|
|
1318
1343
|
* Run callback in request scope (for DB operations, service access)
|
|
@@ -1448,8 +1473,8 @@ var TestingModuleBuilder = class {
|
|
|
1448
1473
|
env,
|
|
1449
1474
|
ctx
|
|
1450
1475
|
});
|
|
1451
|
-
app.container.registerSingleton(STORAGE_TOKENS.StorageService, FakeStorageService);
|
|
1452
1476
|
await app.initialize();
|
|
1477
|
+
app.container.registerSingleton(STORAGE_TOKENS.StorageService, FakeStorageService);
|
|
1453
1478
|
for (const override of this.overrides) switch (override.type) {
|
|
1454
1479
|
case "value":
|
|
1455
1480
|
app.container.registerValue(override.token, override.implementation);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["http","HttpResponse"],"sources":["../src/core/override/provider-override-builder.ts","../src/core/http/locale-helper.ts","../src/auth/acting-as.ts","../src/core/http/path-utils.ts","../src/core/http/test-response.ts","../src/core/http/test-http-request.ts","../src/core/http/test-http-client.ts","../src/core/quarry/test-command-result.ts","../src/core/quarry/test-command-request.ts","../src/core/sse/test-sse-connection.ts","../src/core/sse/test-sse-request.ts","../src/core/ws/test-ws-connection.ts","../src/core/ws/test-ws-request.ts","../src/core/testing-module.ts","../src/core/testing-module-builder.ts","../src/core/test.ts","../src/core/http/mock-fetch.ts","../src/errors/test-error.ts","../src/errors/setup-error.ts"],"sourcesContent":["import { type Container } from 'stratal/di'\nimport { type InjectionToken } from 'stratal/module'\nimport type { TestingModuleBuilder } from '../testing-module-builder'\n\n/**\n * Provider override configuration\n */\nexport interface ProviderOverrideConfig<T = unknown> {\n token: InjectionToken<T>\n type: 'value' | 'class' | 'factory' | 'existing'\n implementation: T | (new (...args: unknown[]) => T) | ((container: Container) => T) | InjectionToken<T>\n}\n\n/**\n * Fluent builder for provider overrides\n *\n * Provides a NestJS-style API for overriding providers in tests.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule],\n * })\n * .overrideProvider(EMAIL_TOKENS.EmailService)\n * .useValue(mockEmailService)\n * .compile()\n * ```\n */\nexport class ProviderOverrideBuilder<T> {\n constructor(\n private readonly parent: TestingModuleBuilder,\n private readonly token: InjectionToken<T>\n ) { }\n\n /**\n * Use a static value as the provider\n *\n * The value will be registered directly in the container.\n *\n * @param value - The value to use as the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useValue(value: T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'value',\n implementation: value,\n })\n }\n\n /**\n * Use a class as the provider\n *\n * The class will be registered as a singleton.\n *\n * @param cls - The class constructor to use as the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useClass(cls: new (...args: unknown[]) => T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'class',\n implementation: cls,\n })\n }\n\n /**\n * Use a factory function as the provider\n *\n * The factory receives the container and should return the provider instance.\n *\n * @param factory - Factory function that creates the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useFactory(factory: (container: Container) => T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'factory',\n implementation: factory,\n })\n }\n\n /**\n * Use an existing token as the provider (alias)\n *\n * The override token will resolve to the same instance as the target token.\n *\n * @param existingToken - The token to alias\n * @returns The parent TestingModuleBuilder for chaining\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [MyModule],\n * })\n * .overrideProvider(ABSTRACT_TOKEN)\n * .useExisting(ConcreteService)\n * .compile()\n * ```\n */\n useExisting(existingToken: InjectionToken<T>): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'existing',\n implementation: existingToken,\n })\n }\n}\n","import type { DetectionStrategy, I18nModuleOptions } from 'stratal/i18n'\nimport { I18N_TOKENS } from 'stratal/i18n'\nimport type { TestingModule } from '../testing-module'\n\n/**\n * Resolve the configured detection strategy from the testing module's DI container.\n * Falls back to 'cookie' if I18n is not configured.\n */\nexport function resolveLocaleStrategy(module: TestingModule): DetectionStrategy {\n try {\n const options = module.get<I18nModuleOptions>(I18N_TOKENS.Options)\n const detection = options.detection\n if (detection && 'strategy' in detection && detection.strategy) {\n return detection.strategy\n }\n return 'cookie'\n } catch {\n return 'cookie'\n }\n}\n\n/**\n * Apply locale to request headers based on detection strategy.\n */\nexport function applyLocaleToHeaders(\n headers: Headers,\n locale: string,\n strategy: DetectionStrategy,\n): void {\n switch (strategy) {\n case 'cookie':\n headers.set('Cookie', `locale=${locale}`)\n break\n case 'header':\n headers.set('Accept-Language', locale)\n break\n }\n}\n\n/**\n * Apply locale to URL based on detection strategy.\n */\nexport function applyLocaleToUrl(\n url: URL,\n locale: string,\n strategy: DetectionStrategy,\n): void {\n if (strategy === 'querystring') {\n url.searchParams.set('locale', locale)\n }\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { type GenericEndpointContext } from 'better-auth'\nimport { setSessionCookie } from 'better-auth/cookies'\nimport { convertSetCookieToCookie } from 'better-auth/test'\n\nasync function makeSignature(value: string, secret: string): Promise<string> {\n const algorithm = { name: 'HMAC', hash: 'SHA-256' }\n const secretBuf = new TextEncoder().encode(secret)\n const key = await crypto.subtle.importKey('raw', secretBuf, algorithm, false, ['sign'])\n const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value))\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n}\n\nfunction buildCookieString(name: string, value: string, options: Record<string, unknown> = {}): string {\n const encodedValue = encodeURIComponent(value)\n let str = `${name}=${encodedValue}`\n if (options.path) str += `; Path=${options.path as string}`\n if (options.httpOnly) str += '; HttpOnly'\n if (options.secure) str += '; Secure'\n if (options.sameSite) str += `; SameSite=${options.sameSite as string}`\n if (options.maxAge !== undefined) str += `; Max-Age=${Math.floor(options.maxAge as number)}`\n return str\n}\n\n/**\n * ActingAs\n *\n * Creates authentication sessions for testing.\n * Uses Better Auth's internalAdapter to create real database sessions.\n *\n * @example\n * ```typescript\n * const actingAs = new ActingAs(authService)\n * const headers = await actingAs.createSessionForUser({ id: 'user-123' })\n * ```\n */\nexport class ActingAs {\n constructor(private readonly authService: AuthService) { }\n\n async createSessionForUser(user: { id: string }): Promise<Headers> {\n const auth = this.authService.auth\n const ctx = await auth.$context\n\n const secret = ctx.secret\n\n const session = await ctx.internalAdapter.createSession(\n user.id,\n undefined,\n { ipAddress: '127.0.0.1', userAgent: 'test-client' }\n )\n\n const dbUser = await ctx.internalAdapter.findUserById(user.id)\n if (!dbUser) {\n throw new Error(`User not found: ${user.id}`)\n }\n\n const responseHeaders = new Headers()\n const mockCtx = {\n context: ctx,\n getSignedCookie: () => null,\n setSignedCookie: async (name: string, value: string, _secret: string, options: Record<string, unknown> = {}) => {\n const signature = await makeSignature(value, secret)\n const signedValue = `${value}.${signature}`\n responseHeaders.append('Set-Cookie', buildCookieString(name, signedValue, options))\n },\n setCookie: (name: string, value: string, options: Record<string, unknown> = {}) => {\n responseHeaders.append('Set-Cookie', buildCookieString(name, value, options))\n },\n }\n\n await setSessionCookie(mockCtx as unknown as GenericEndpointContext, { session, user: dbUser }, false)\n return convertSetCookieToCookie(responseHeaders)\n }\n}\n","/**\n * Get value at dot-notation path.\n */\nexport function getValueAtPath(obj: unknown, path: string): unknown {\n const parts = path.split('.')\n let current: unknown = obj\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined\n }\n current = (current as Record<string, unknown>)[part]\n }\n\n return current\n}\n\n/**\n * Check if a path exists in the object (even if value is null/undefined).\n */\nexport function hasValueAtPath(obj: unknown, path: string): boolean {\n const parts = path.split('.')\n let current: unknown = obj\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return false\n }\n\n if (typeof current !== 'object') {\n return false\n }\n\n const record = current as Record<string, unknown>\n\n if (!(part in record)) {\n return false\n }\n\n current = record[part]\n }\n\n return true\n}\n","import { expect } from 'vitest'\nimport { getValueAtPath, hasValueAtPath } from './path-utils'\n\n/**\n * TestResponse\n *\n * Wrapper around Response with assertion methods.\n *\n * @example\n * ```typescript\n * response\n * .assertOk()\n * .assertStatus(200)\n * .assertJsonPath('data.id', userId)\n * ```\n */\nexport class TestResponse {\n private jsonData: unknown = null\n private textData: string | null = null\n\n constructor(private readonly response: Response) {}\n\n /**\n * Get the raw Response object.\n */\n get raw(): Response {\n return this.response\n }\n\n /**\n * Get the response status code.\n */\n get status(): number {\n return this.response.status\n }\n\n /**\n * Get response headers.\n */\n get headers(): Headers {\n return this.response.headers\n }\n\n /**\n * Get the response body as JSON.\n */\n async json<T = unknown>(): Promise<T> {\n if (this.jsonData === null) {\n this.jsonData = await this.response.clone().json()\n }\n return this.jsonData as T\n }\n\n /**\n * Get the response body as text.\n */\n async text(): Promise<string> {\n this.textData ??= await this.response.clone().text()\n return this.textData\n }\n\n // ============================================================\n // Status Assertions\n // ============================================================\n\n /**\n * Assert response status is 200 OK.\n */\n assertOk(): this {\n return this.assertStatus(200)\n }\n\n /**\n * Assert response status is 201 Created.\n */\n assertCreated(): this {\n return this.assertStatus(201)\n }\n\n /**\n * Assert response status is 204 No Content.\n */\n assertNoContent(): this {\n return this.assertStatus(204)\n }\n\n /**\n * Assert response status is 400 Bad Request.\n */\n assertBadRequest(): this {\n return this.assertStatus(400)\n }\n\n /**\n * Assert response status is 401 Unauthorized.\n */\n assertUnauthorized(): this {\n return this.assertStatus(401)\n }\n\n /**\n * Assert response status is 403 Forbidden.\n */\n assertForbidden(): this {\n return this.assertStatus(403)\n }\n\n /**\n * Assert response status is 404 Not Found.\n */\n assertNotFound(): this {\n return this.assertStatus(404)\n }\n\n /**\n * Assert response status is 422 Unprocessable Entity.\n */\n assertUnprocessable(): this {\n return this.assertStatus(422)\n }\n\n /**\n * Assert response status is 500 Internal Server Error.\n */\n assertServerError(): this {\n return this.assertStatus(500)\n }\n\n /**\n * Assert response has the given status code.\n */\n assertStatus(expected: number): this {\n expect(\n this.response.status,\n `Expected status ${expected}, got ${this.response.status}`\n ).toBe(expected)\n return this\n }\n\n /**\n * Assert response status is in the 2xx success range.\n */\n assertSuccessful(): this {\n expect(\n this.response.status >= 200 && this.response.status < 300,\n `Expected successful status (2xx), got ${this.response.status}`\n ).toBe(true)\n return this\n }\n\n // ============================================================\n // JSON Assertions\n // ============================================================\n\n /**\n * Assert JSON response contains the given data.\n */\n async assertJson(expected: Record<string, unknown>): Promise<this> {\n const actual = await this.json<Record<string, unknown>>()\n\n for (const [key, value] of Object.entries(expected)) {\n expect(\n actual[key],\n `Expected JSON key \"${key}\" to be ${JSON.stringify(value)}, got ${JSON.stringify(actual[key])}`\n ).toStrictEqual(value)\n }\n\n return this\n }\n\n /**\n * Assert JSON response has value at the given path.\n *\n * @param path - Dot-notation path (e.g., 'data.user.id')\n * @param expected - Expected value at path\n */\n async assertJsonPath(path: string, expected: unknown): Promise<this> {\n const json = await this.json()\n const actual = getValueAtPath(json, path)\n\n expect(\n actual,\n `Expected JSON path \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`\n ).toStrictEqual(expected)\n\n return this\n }\n\n /**\n * Assert JSON response structure matches the given schema.\n */\n async assertJsonStructure(structure: string[]): Promise<this> {\n const json = await this.json<Record<string, unknown>>()\n\n for (const key of structure) {\n expect(\n key in json,\n `Expected JSON to have key \"${key}\", got keys: ${JSON.stringify(Object.keys(json))}`\n ).toBe(true)\n }\n\n return this\n }\n\n /**\n * Assert a JSON path exists (value can be anything, including null).\n *\n * @param path - Dot-notation path (e.g., 'data.user.id')\n */\n async assertJsonPathExists(path: string): Promise<this> {\n const json = await this.json()\n const exists = hasValueAtPath(json, path)\n\n expect(\n exists,\n `Expected JSON path \"${path}\" to exist`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert a JSON path does not exist.\n *\n * @param path - Dot-notation path (e.g., 'data.user.deletedAt')\n */\n async assertJsonPathMissing(path: string): Promise<this> {\n const json = await this.json()\n const exists = hasValueAtPath(json, path)\n\n expect(\n exists,\n `Expected JSON path \"${path}\" to not exist`\n ).toBe(false)\n\n return this\n }\n\n /**\n * Assert JSON value at path matches a custom predicate.\n *\n * @param path - Dot-notation path (e.g., 'data.items')\n * @param matcher - Predicate function to validate the value\n */\n async assertJsonPathMatches(\n path: string,\n matcher: (value: unknown) => boolean\n ): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n matcher(value),\n `Expected JSON path \"${path}\" to match predicate, got ${JSON.stringify(value)}`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert string value at path contains a substring.\n *\n * @param path - Dot-notation path (e.g., 'data.message')\n * @param substring - Substring to search for\n */\n async assertJsonPathContains(path: string, substring: string): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n typeof value === 'string',\n `Expected JSON path \"${path}\" to be a string, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as string).includes(substring),\n `Expected JSON path \"${path}\" to contain \"${substring}\", got \"${String(value)}\"`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert array value at path includes a specific item.\n *\n * @param path - Dot-notation path (e.g., 'data.tags')\n * @param item - Item to search for in the array\n */\n async assertJsonPathIncludes(path: string, item: unknown): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n Array.isArray(value),\n `Expected JSON path \"${path}\" to be an array, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as unknown[]).includes(item),\n `Expected JSON path \"${path}\" to include ${JSON.stringify(item)}`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert array length at path equals the expected count.\n *\n * @param path - Dot-notation path (e.g., 'data.items')\n * @param count - Expected array length\n */\n async assertJsonPathCount(path: string, count: number): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n Array.isArray(value),\n `Expected JSON path \"${path}\" to be an array, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as unknown[]).length,\n `Expected JSON path \"${path}\" to have ${count} items, got ${(value as unknown[]).length}`\n ).toBe(count)\n\n return this\n }\n\n /**\n * Assert multiple JSON paths at once (batch assertion).\n *\n * @param expectations - Object mapping paths to expected values\n */\n async assertJsonPaths(expectations: Record<string, unknown>): Promise<this> {\n const json = await this.json()\n\n for (const [path, expected] of Object.entries(expectations)) {\n const actual = getValueAtPath(json, path)\n expect(\n actual,\n `Expected JSON path \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`\n ).toStrictEqual(expected)\n }\n\n return this\n }\n\n // ============================================================\n // Header Assertions\n // ============================================================\n\n /**\n * Assert response has the given header.\n */\n assertHeader(name: string, expected?: string): this {\n const actual = this.response.headers.get(name)\n\n expect(\n actual !== null,\n `Expected header \"${name}\" to be present`\n ).toBe(true)\n\n if (expected !== undefined) {\n expect(\n actual,\n `Expected header \"${name}\" to be \"${expected}\", got \"${actual}\"`\n ).toBe(expected)\n }\n\n return this\n }\n\n /**\n * Assert response does not have the given header.\n */\n assertHeaderMissing(name: string): this {\n const actual = this.response.headers.get(name)\n\n expect(\n actual,\n `Expected header \"${name}\" to be absent, but got \"${actual}\"`\n ).toBeNull()\n\n return this\n }\n\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, applyLocaleToUrl, resolveLocaleStrategy } from './locale-helper'\nimport { TestResponse } from './test-response'\n\n/**\n * TestHttpRequest\n *\n * Request builder with fluent API for configuring test HTTP requests.\n *\n * @example\n * ```typescript\n * const response = await module.http\n * .post('/api/v1/register')\n * .withBody({ name: 'Test School' })\n * .withHeaders({ 'X-Custom': 'value' })\n * .send()\n * ```\n *\n * @example Authenticated request\n * ```typescript\n * const response = await module.http\n * .get('/api/v1/profile')\n * .actingAs({ id: user.id })\n * .send()\n * ```\n */\nexport class TestHttpRequest {\n\tprivate body: unknown = null\n\tprivate requestHeaders: Headers\n\tprivate actingAsUser: { id: string } | null = null\n\tprivate localeConfig: { locale: string; strategy: DetectionStrategy } | null\n\n\tconstructor(\n\t\tprivate readonly method: string,\n\t\tprivate readonly path: string,\n\t\theaders: Headers,\n\t\tprivate readonly module: TestingModule,\n\t\tprivate readonly host: string | null = null,\n\t\tlocaleConfig: { locale: string; strategy: DetectionStrategy } | null = null,\n\t) {\n\t\tthis.requestHeaders = new Headers(headers)\n\t\tthis.localeConfig = localeConfig\n\t}\n\n\t/**\n\t * Set the request body\n\t */\n\twithBody(data: unknown): this {\n\t\tthis.body = data\n\t\treturn this\n\t}\n\n\t/**\n\t * Add headers to the request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this request.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t *\n\t * @param locale - Locale code (e.g., 'en', 'fr')\n\t * @param strategy - Detection strategy override\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tthis.localeConfig = { locale, strategy: resolved }\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Set Content-Type to application/json\n\t */\n\tasJson(): this {\n\t\tthis.requestHeaders.set('Content-Type', 'application/json')\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the request as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the request and return response\n\t *\n\t * Calls module.fetch() - NOT SELF.fetch()\n\t */\n\tasync send(): Promise<TestResponse> {\n\t\tawait this.applyAuthentication()\n\n\t\t// Auto-set Content-Type for body\n\t\tif (this.body && !this.requestHeaders.has('Content-Type')) {\n\t\t\tthis.requestHeaders.set('Content-Type', 'application/json')\n\t\t}\n\n\t\t// Build request\n\t\tconst url = new URL(this.path, `http://${this.host ?? 'localhost'}`)\n\n\t\t// Apply locale to URL for querystring strategy\n\t\tif (this.localeConfig) {\n\t\t\tapplyLocaleToUrl(url, this.localeConfig.locale, this.localeConfig.strategy)\n\t\t}\n\n\t\tconst request = new Request(url.toString(), {\n\t\t\tmethod: this.method,\n\t\t\theaders: this.requestHeaders,\n\t\t\tbody: this.body ? JSON.stringify(this.body) : null,\n\t\t})\n\n\t\t// Call module.fetch() - NO SELF.fetch()\n\t\tconst response = await this.module.fetch(request)\n\t\treturn new TestResponse(response)\n\t}\n\n\tprivate async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers()\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { DetectionStrategy } from 'stratal/i18n'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from './locale-helper'\nimport { TestHttpRequest } from './test-http-request'\n\n/**\n * TestHttpClient\n *\n * Fluent HTTP client for making test requests.\n *\n * @example\n * ```typescript\n * const response = await module.http\n * .forHost('example.com')\n * .post('/api/v1/users')\n * .withBody({ name: 'Test' })\n * .send()\n *\n * response.assertCreated()\n * ```\n */\nexport class TestHttpClient {\n private defaultHeaders: Headers = new Headers()\n private host: string | null = null\n private localeConfig: { locale: string; strategy: DetectionStrategy } | null = null\n\n constructor(private readonly module: TestingModule) { }\n\n /**\n * Set the host for the request\n */\n forHost(host: string): this {\n this.host = host\n return this\n }\n\n /**\n * Set default headers for all requests\n */\n withHeaders(headers: Record<string, string>): this {\n for (const [key, value] of Object.entries(headers)) {\n this.defaultHeaders.set(key, value)\n }\n return this\n }\n\n /**\n * Set the locale for all requests from this client.\n * If strategy is not provided, resolves from the module's I18n configuration.\n *\n * @param locale - Locale code (e.g., 'en', 'fr')\n * @param strategy - Detection strategy override\n */\n withLocale(locale: string, strategy?: DetectionStrategy): this {\n const resolved = strategy ?? resolveLocaleStrategy(this.module)\n this.localeConfig = { locale, strategy: resolved }\n applyLocaleToHeaders(this.defaultHeaders, locale, resolved)\n return this\n }\n\n /**\n * Create a GET request\n */\n get(path: string): TestHttpRequest {\n return this.createRequest('GET', path)\n }\n\n /**\n * Create a POST request\n */\n post(path: string): TestHttpRequest {\n return this.createRequest('POST', path)\n }\n\n /**\n * Create a PUT request\n */\n put(path: string): TestHttpRequest {\n return this.createRequest('PUT', path)\n }\n\n /**\n * Create a PATCH request\n */\n patch(path: string): TestHttpRequest {\n return this.createRequest('PATCH', path)\n }\n\n /**\n * Create a DELETE request\n */\n delete(path: string): TestHttpRequest {\n return this.createRequest('DELETE', path)\n }\n\n private createRequest(method: string, path: string): TestHttpRequest {\n return new TestHttpRequest(method, path, this.defaultHeaders, this.module, this.host, this.localeConfig)\n }\n}\n","import type { CommandResult } from 'stratal/quarry'\nimport { expect } from 'vitest'\n\n/**\n * Fluent assertion wrapper for command results.\n *\n * @example\n * ```typescript\n * const result = await module\n * .quarry('users:create')\n * .withInput({ email: 'test@example.com' })\n * .run()\n *\n * result.assertSuccessful()\n * result.assertOutputContains('User created')\n * ```\n */\nexport class TestCommandResult {\n constructor(private readonly result: CommandResult) {}\n\n get exitCode(): number {\n return this.result.exitCode\n }\n\n get output(): string[] {\n return this.result.output\n }\n\n get errors(): string[] {\n return this.result.errors\n }\n\n assertSuccessful(): this {\n expect(this.result.exitCode, `Expected exit code 0, got ${this.result.exitCode}. Errors: ${this.result.errors.join(', ')}`).toBe(0)\n expect(this.result.errors, 'Expected no errors').toHaveLength(0)\n return this\n }\n\n assertFailed(exitCode?: number): this {\n if (exitCode !== undefined) {\n expect(this.result.exitCode, `Expected exit code ${exitCode}, got ${this.result.exitCode}`).toBe(exitCode)\n } else {\n expect(this.result.exitCode, 'Expected non-zero exit code').not.toBe(0)\n }\n return this\n }\n\n assertExitCode(code: number): this {\n expect(this.result.exitCode, `Expected exit code ${code}, got ${this.result.exitCode}`).toBe(code)\n return this\n }\n\n assertOutputContains(text: string): this {\n const joined = this.result.output.join('\\n')\n expect(joined, `Expected output to contain \"${text}\"`).toContain(text)\n return this\n }\n\n assertOutputMissing(text: string): this {\n const joined = this.result.output.join('\\n')\n expect(joined, `Expected output NOT to contain \"${text}\"`).not.toContain(text)\n return this\n }\n\n assertErrorContains(text: string): this {\n const joined = this.result.errors.join('\\n')\n expect(joined, `Expected errors to contain \"${text}\"`).toContain(text)\n return this\n }\n\n assertErrorMissing(text: string): this {\n const joined = this.result.errors.join('\\n')\n expect(joined, `Expected errors NOT to contain \"${text}\"`).not.toContain(text)\n return this\n }\n}\n","import type { CommandInput } from 'stratal/quarry'\nimport type { TestingModule } from '../testing-module'\nimport { TestCommandResult } from './test-command-result'\n\n/**\n * Fluent builder for testing Quarry commands.\n *\n * @example\n * ```typescript\n * const result = await module\n * .quarry('users:create')\n * .withInput({ email: 'test@example.com', admin: true })\n * .run()\n *\n * result.assertSuccessful()\n * result.assertOutputContains('User created')\n * ```\n */\nexport class TestCommandRequest {\n private _input: CommandInput = {}\n\n constructor(\n private readonly commandName: string,\n private readonly module: TestingModule,\n ) {}\n\n /**\n * Set the flat input for the command.\n */\n withInput(input: CommandInput): this {\n this._input = { ...input }\n return this\n }\n\n /**\n * Execute the command and return a TestCommandResult for assertions.\n */\n async run(): Promise<TestCommandResult> {\n const result = await this.module.application.handleCommand(this.commandName, this._input)\n return new TestCommandResult(result)\n }\n}\n","import { expect } from \"vitest\"\n\n/**\n * Represents a parsed SSE event\n */\nexport interface TestSseEvent {\n\tdata: string\n\tevent?: string\n\tid?: string\n\tretry?: number\n}\n\n/**\n * TestSseConnection\n *\n * Live SSE connection wrapper with assertion helpers for testing.\n *\n * @example\n * ```typescript\n * const sse = await module.sse('/streaming/sse').connect()\n * await sse.assertEvent({ event: 'message', data: 'hello', id: '1' })\n * await sse.waitForEnd()\n * ```\n */\nexport class TestSseConnection {\n\tprivate readonly eventQueue: TestSseEvent[] = []\n\tprivate eventWaiters: ((event: TestSseEvent) => void)[] = []\n\tprivate streamEnded = false\n\tprivate endWaiters: (() => void)[] = []\n\n\tconstructor(private readonly response: Response) {\n\t\tthis.startReading()\n\t}\n\n\t/**\n\t * Wait for the next SSE event\n\t */\n\tasync waitForEvent(timeout = 5000): Promise<TestSseEvent> {\n\t\tif (this.eventQueue.length > 0) {\n\t\t\treturn this.eventQueue.shift()!\n\t\t}\n\n\t\tif (this.streamEnded) {\n\t\t\tthrow new Error('SSE: stream has ended, no more events')\n\t\t}\n\n\t\treturn new Promise<TestSseEvent>((resolve, reject) => {\n\t\t\tconst waiter = (event: TestSseEvent) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(event)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.eventWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.eventWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: no event received within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.eventWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Wait for the stream to end\n\t */\n\tasync waitForEnd(timeout = 5000): Promise<void> {\n\t\tif (this.streamEnded) return\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst waiter = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve()\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.endWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.endWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: stream did not end within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.endWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Collect all remaining events until the stream ends\n\t */\n\tasync collectEvents(timeout = 5000): Promise<TestSseEvent[]> {\n\t\tconst events: TestSseEvent[] = []\n\n\t\tif (this.streamEnded) {\n\t\t\treturn [...this.eventQueue.splice(0)]\n\t\t}\n\n\t\treturn new Promise<TestSseEvent[]>((resolve, reject) => {\n\t\t\t// Listen for new events until stream ends\n\t\t\tconst originalDispatch = this.dispatchEvent.bind(this)\n\t\t\tthis.dispatchEvent = (event: TestSseEvent) => {\n\t\t\t\tevents.push(event)\n\t\t\t\toriginalDispatch(event)\n\t\t\t}\n\n\t\t\tconst endWaiter = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tthis.dispatchEvent = originalDispatch\n\t\t\t\tresolve(events)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.dispatchEvent = originalDispatch\n\t\t\t\tconst index = this.endWaiters.indexOf(endWaiter)\n\t\t\t\tif (index !== -1) this.endWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: stream did not end within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\t// Drain any queued events first\n\t\t\tevents.push(...this.eventQueue.splice(0))\n\n\t\t\tthis.endWaiters.push(endWaiter)\n\t\t})\n\t}\n\n\t/**\n\t * Assert that the next event matches the expected partial shape\n\t */\n\tasync assertEvent(expected: Partial<TestSseEvent>, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\texpect(event).toMatchObject(expected)\n\t}\n\n\t/**\n\t * Assert that the next event's data matches the expected string\n\t */\n\tasync assertEventData(expected: string, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\texpect(event.data, `Expected SSE data \"${expected}\", got \"${event.data}\"`).toBe(expected)\n\t}\n\n\t/**\n\t * Assert that the next event's data is JSON matching the expected value\n\t */\n\tasync assertJsonEventData<T>(expected: T, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\tconst parsed = JSON.parse(event.data) as unknown\n\t\texpect(parsed).toEqual(expected)\n\t}\n\n\t/**\n\t * Access the raw Response\n\t */\n\tget raw(): Response {\n\t\treturn this.response\n\t}\n\n\tprivate startReading(): void {\n\t\tconst body = this.response.body\n\t\tif (!body) {\n\t\t\tthis.streamEnded = true\n\t\t\treturn\n\t\t}\n\n\t\tconst reader = body.getReader() as ReadableStreamDefaultReader<Uint8Array>\n\t\tconst decoder = new TextDecoder()\n\t\tlet buffer = ''\n\n\t\tconst read = async (): Promise<void> => {\n\t\t\ttry {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read()\n\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\t// Parse any remaining buffered data\n\t\t\t\t\t\tif (buffer.trim()) {\n\t\t\t\t\t\t\tconst event = this.parseEvent(buffer)\n\t\t\t\t\t\t\tif (event) this.dispatchEvent(event)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.streamEnded = true\n\t\t\t\t\t\tfor (const waiter of this.endWaiters) {\n\t\t\t\t\t\t\twaiter()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.endWaiters = []\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true })\n\n\t\t\t\t\t// Split on double newlines (SSE event boundary)\n\t\t\t\t\tconst parts = buffer.split('\\n\\n')\n\t\t\t\t\t// Last part may be incomplete, keep it in the buffer\n\t\t\t\t\tbuffer = parts.pop()!\n\n\t\t\t\t\tfor (const part of parts) {\n\t\t\t\t\t\tif (!part.trim()) continue\n\t\t\t\t\t\tconst event = this.parseEvent(part)\n\t\t\t\t\t\tif (event) this.dispatchEvent(event)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tthis.streamEnded = true\n\t\t\t\tfor (const waiter of this.endWaiters) {\n\t\t\t\t\twaiter()\n\t\t\t\t}\n\t\t\t\tthis.endWaiters = []\n\t\t\t}\n\t\t}\n\n\t\tvoid read()\n\t}\n\n\tprivate parseEvent(raw: string): TestSseEvent | null {\n\t\tconst lines = raw.split('\\n')\n\t\tconst dataLines: string[] = []\n\t\tlet event: string | undefined\n\t\tlet id: string | undefined\n\t\tlet retry: number | undefined\n\n\t\tfor (const line of lines) {\n\t\t\tif (line.startsWith(':')) continue // comment line\n\n\t\t\tconst colonIndex = line.indexOf(':')\n\t\t\tif (colonIndex === -1) continue\n\n\t\t\tconst field = line.slice(0, colonIndex)\n\t\t\t// Strip optional leading space after colon\n\t\t\tconst value = line[colonIndex + 1] === ' ' ? line.slice(colonIndex + 2) : line.slice(colonIndex + 1)\n\n\t\t\tswitch (field) {\n\t\t\t\tcase 'data':\n\t\t\t\t\tdataLines.push(value)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'event':\n\t\t\t\t\tevent = value\n\t\t\t\t\tbreak\n\t\t\t\tcase 'id':\n\t\t\t\t\tid = value\n\t\t\t\t\tbreak\n\t\t\t\tcase 'retry': {\n\t\t\t\t\tconst parsed = parseInt(value, 10)\n\t\t\t\t\tif (!isNaN(parsed)) retry = parsed\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dataLines.length === 0) return null\n\n\t\tconst result: TestSseEvent = { data: dataLines.join('\\n') }\n\t\tif (event !== undefined) result.event = event\n\t\tif (id !== undefined) result.id = id\n\t\tif (retry !== undefined) result.retry = retry\n\n\t\treturn result\n\t}\n\n\tprivate dispatchEvent(event: TestSseEvent): void {\n\t\tif (this.eventWaiters.length > 0) {\n\t\t\tthis.eventWaiters.shift()!(event)\n\t\t} else {\n\t\t\tthis.eventQueue.push(event)\n\t\t}\n\t}\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { expect } from 'vitest'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from '../http/locale-helper'\nimport { TestSseConnection } from './test-sse-connection'\n\n/**\n * TestSseRequest\n *\n * Builder for SSE connection requests. Follows the TestWsRequest pattern.\n *\n * @example\n * ```typescript\n * const sse = await module.sse('/streaming/sse').connect()\n * await sse.assertEvent({ event: 'message', data: 'hello' })\n * await sse.waitForEnd()\n * ```\n *\n * @example Authenticated SSE\n * ```typescript\n * const sse = await module.sse('/streaming/sse').actingAs({ id: user.id }).connect()\n * ```\n */\nexport class TestSseRequest {\n\tprivate requestHeaders: Headers = new Headers()\n\tprivate actingAsUser: { id: string } | null = null\n\n\tconstructor(\n\t\tprivate readonly path: string,\n\t\tprivate readonly module: TestingModule,\n\t) { }\n\n\t/**\n\t * Add custom headers to the request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this SSE connection.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the SSE connection as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the request and return a live SSE connection\n\t */\n\tasync connect(): Promise<TestSseConnection> {\n\t\tawait this.applyAuthentication()\n\n\t\tthis.requestHeaders.set('Accept', 'text/event-stream')\n\n\t\tconst url = new URL(this.path, 'http://localhost')\n\t\tconst request = new Request(url.toString(), {\n\t\t\theaders: this.requestHeaders,\n\t\t})\n\n\t\tconst response = await this.module.fetch(request)\n\n\t\texpect(\n\t\t\tresponse.status,\n\t\t\t`Expected status 200, got ${response.status}`,\n\t\t).toBe(200)\n\n\t\tconst contentType = response.headers.get('content-type') ?? ''\n\t\texpect(\n\t\t\tcontentType.includes('text/event-stream'),\n\t\t\t`Expected content-type \"text/event-stream\", got \"${contentType}\"`,\n\t\t).toBe(true)\n\n\t\treturn new TestSseConnection(response)\n\t}\n\n\tprivate async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers()\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import { expect } from \"vitest\";\n\n/**\n * TestWsConnection\n *\n * Live WebSocket connection wrapper with assertion helpers for testing.\n *\n * @example\n * ```typescript\n * const ws = await module.ws('/ws/chat').connect()\n * ws.send('hello')\n * await ws.assertMessage('echo:hello')\n * ws.close()\n * await ws.waitForClose()\n * ```\n */\nexport class TestWsConnection {\n\tprivate readonly messageQueue: (string | ArrayBuffer)[] = []\n\tprivate messageWaiters: ((data: string | ArrayBuffer) => void)[] = []\n\tprivate closeEvent: { code?: number; reason?: string } | null = null\n\tprivate closeWaiters: ((event: { code?: number; reason?: string }) => void)[] = []\n\n\tconstructor(private readonly ws: WebSocket) {\n\t\tthis.ws.addEventListener('message', (event: MessageEvent) => {\n\t\t\tconst data = event.data as string | ArrayBuffer\n\t\t\tif (this.messageWaiters.length > 0) {\n\t\t\t\tthis.messageWaiters.shift()!(data)\n\t\t\t} else {\n\t\t\t\tthis.messageQueue.push(data)\n\t\t\t}\n\t\t})\n\n\t\tthis.ws.addEventListener('close', (event: CloseEvent) => {\n\t\t\tthis.closeEvent = { code: event.code, reason: event.reason }\n\t\t\tfor (const waiter of this.closeWaiters) {\n\t\t\t\twaiter(this.closeEvent)\n\t\t\t}\n\t\t\tthis.closeWaiters = []\n\t\t})\n\t}\n\n\t/**\n\t * Send a message through the WebSocket\n\t */\n\tsend(data: string | ArrayBuffer | Uint8Array): void {\n\t\tthis.ws.send(data)\n\t}\n\n\t/**\n\t * Close the WebSocket connection\n\t */\n\tclose(code?: number, reason?: string): void {\n\t\tthis.ws.close(code, reason)\n\t}\n\n\t/**\n\t * Wait for the next message, returning its data\n\t */\n\tasync waitForMessage(timeout = 5000): Promise<string | ArrayBuffer> {\n\t\tif (this.messageQueue.length > 0) {\n\t\t\treturn this.messageQueue.shift()!\n\t\t}\n\n\t\treturn new Promise<string | ArrayBuffer>((resolve, reject) => {\n\t\t\tconst waiter = (data: string | ArrayBuffer) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(data)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.messageWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.messageWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`WebSocket: no message received within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.messageWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Wait for the connection to close\n\t */\n\tasync waitForClose(timeout = 5000): Promise<{ code?: number; reason?: string }> {\n\t\tif (this.closeEvent) {\n\t\t\treturn this.closeEvent\n\t\t}\n\n\t\treturn new Promise<{ code?: number; reason?: string }>((resolve, reject) => {\n\t\t\tconst waiter = (event: { code?: number; reason?: string }) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(event)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.closeWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.closeWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`WebSocket: connection did not close within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.closeWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Assert that the next message equals the expected value\n\t */\n\tasync assertMessage(expected: string, timeout = 5000): Promise<void> {\n\t\tconst data = await this.waitForMessage(timeout)\n\t\tconst message = typeof data === 'string' ? data : '[ArrayBuffer]'\n\t\texpect(message, `Expected WebSocket message \"${expected}\", got \"${message}\"`).toBe(expected)\n\t}\n\n\t/**\n\t * Assert that the connection closes, optionally with an expected code\n\t */\n\tasync assertClosed(expectedCode?: number, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForClose(timeout)\n\t\tif (expectedCode !== undefined) {\n\t\t\texpect(event.code, `Expected close code ${expectedCode}, got ${event.code}`).toBe(expectedCode)\n\t\t}\n\t}\n\n\t/**\n\t * Access the raw Cloudflare WebSocket\n\t */\n\tget raw(): WebSocket {\n\t\treturn this.ws\n\t}\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { expect } from 'vitest'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from '../http/locale-helper'\nimport { TestWsConnection } from './test-ws-connection'\n\n/**\n * TestWsRequest\n *\n * Builder for WebSocket upgrade requests. Follows the TestHttpRequest pattern.\n *\n * @example\n * ```typescript\n * const ws = await module.ws('/ws/chat').connect()\n * ws.send('hello')\n * await ws.assertMessage('echo:hello')\n * ws.close()\n * ```\n *\n * @example Authenticated WebSocket\n * ```typescript\n * const ws = await module.ws('/ws/chat').actingAs({ id: user.id }).connect()\n * ```\n */\nexport class TestWsRequest {\n\tprivate requestHeaders: Headers = new Headers()\n\tprivate actingAsUser: { id: string } | null = null\n\n\tconstructor(\n\t\tprivate readonly path: string,\n\t\tprivate readonly module: TestingModule,\n\t) { }\n\n\t/**\n\t * Add custom headers to the upgrade request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this WebSocket connection.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the WebSocket connection as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the upgrade request and return a live WebSocket connection\n\t */\n\tasync connect(): Promise<TestWsConnection> {\n\t\tawait this.applyAuthentication()\n\n\t\tthis.requestHeaders.set('Upgrade', 'websocket')\n\t\tthis.requestHeaders.set('Connection', 'Upgrade')\n\t\tthis.requestHeaders.set('Sec-WebSocket-Key', 'dGhlIHNhbXBsZSBub25jZQ==')\n\t\tthis.requestHeaders.set('Sec-WebSocket-Version', '13')\n\n\t\tconst url = new URL(this.path, 'http://localhost')\n\t\tconst request = new Request(url.toString(), {\n\t\t\theaders: this.requestHeaders,\n\t\t})\n\n\t\tconst response = await this.module.fetch(request)\n\n\t\texpect(\n\t\t\tresponse.status,\n\t\t\t`Expected status 101 (Switching Protocols), got ${response.status}`,\n\t\t).toBe(101)\n\n\t\tconst ws = (response as Response & { webSocket: WebSocket | null }).webSocket\n\t\tif (!ws) {\n\t\t\tthrow new Error('Response did not include a WebSocket connection')\n\t\t}\n\n\t\tws.accept()\n\n\t\treturn new TestWsConnection(ws)\n\t}\n\n\tprivate async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers()\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { ConnectionName, DatabaseService } from '@stratal/framework/database'\nimport { connectionSymbol } from '@stratal/framework/database'\nimport type { Application, Constructor, StratalEnv, StratalExecutionContext } from 'stratal'\nimport { DI_TOKENS, type Container } from 'stratal/di'\nimport { type InjectionToken } from 'stratal/module'\nimport { SEEDER_TOKENS, type Seeder, type SeederRegistry, SeederNotRegisteredError } from 'stratal/seeder'\nimport { STORAGE_TOKENS } from 'stratal/storage'\nimport { expect } from 'vitest'\nimport type { FakeStorageService } from '../storage'\nimport { TestHttpClient } from './http/test-http-client'\nimport { TestCommandRequest } from './quarry/test-command-request'\nimport { TestSseRequest } from './sse/test-sse-request'\nimport { TestWsRequest } from './ws/test-ws-request'\n\n/**\n * TestingModule\n *\n * Provides access to the test application, container, HTTP client, and utilities.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * modules: [RegistrationModule],\n * }).compile()\n *\n * // Make HTTP requests\n * const response = await module.http\n * .post('/api/v1/register')\n * .withBody({ ... })\n * .send()\n *\n * // Access services\n * const service = module.get(REGISTRATION_TOKENS.RegistrationService)\n *\n * // Database utilities\n * await module.truncateDb()\n * await module.seed(UserSeeder)\n * await module.assertDatabaseHas('user', { email: 'test@example.com' })\n *\n * // Cleanup\n * await module.close()\n * ```\n */\nexport class TestingModule {\n private _http: TestHttpClient | null = null\n private readonly _requestContainer: Container\n\n constructor(\n private readonly app: Application,\n private readonly env: StratalEnv,\n private readonly ctx: StratalExecutionContext,\n ) {\n const mockContext = this.app.createMockRouterContext()\n this._requestContainer = this.app.container.createRequestScope(mockContext)\n }\n\n /**\n * Resolve a service from the container\n */\n get<T>(token: InjectionToken<T>): T {\n return this._requestContainer.resolve(token)\n }\n\n /**\n * Get HTTP test client for making requests\n */\n get http(): TestHttpClient {\n this._http ??= new TestHttpClient(this)\n return this._http\n }\n\n /**\n * Get fake storage service for assertions\n */\n get storage(): FakeStorageService {\n return this.get<FakeStorageService>(STORAGE_TOKENS.StorageService)\n }\n\n /**\n * Create a WebSocket test request builder for the given path\n */\n ws(path: string): TestWsRequest {\n return new TestWsRequest(path, this)\n }\n\n /**\n * Create an SSE test request builder for the given path\n */\n sse(path: string): TestSseRequest {\n return new TestSseRequest(path, this)\n }\n\n /**\n * Create a Quarry command test request builder\n */\n quarry(name: string): TestCommandRequest {\n return new TestCommandRequest(name, this)\n }\n\n /**\n * Get Application instance\n */\n get application(): Application {\n return this.app\n }\n\n /**\n * Get DI Container (request-scoped)\n */\n get container(): Container {\n return this._requestContainer\n }\n\n /**\n * Execute an HTTP request through HonoApp\n */\n async fetch(request: Request): Promise<Response> {\n return this.app.hono.fetch(request, this.env, this.ctx as ExecutionContext)\n }\n\n /**\n * Run callback in request scope (for DB operations, service access)\n */\n async runInRequestScope<T>(callback: (container: Container) => T | Promise<T>): Promise<T> {\n const mockContext = this.app.createMockRouterContext()\n return this.app.container.runInRequestScope(mockContext, callback)\n }\n\n /**\n * Get database service instance (resolved in request scope)\n */\n getDb(): DatabaseService\n getDb<K extends ConnectionName>(name: K): DatabaseService<K>\n getDb(name?: string): unknown {\n const token = name ? connectionSymbol(name) : DI_TOKENS.Database\n return this._requestContainer.resolve(token)\n }\n\n /**\n * Truncate all non-prisma tables in the database\n */\n async truncateDb(name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const tables = await db.$queryRaw<{ tablename: string }[]>`\n SELECT tablename::text as tablename FROM pg_tables\n WHERE schemaname = current_schema()\n AND tablename NOT LIKE '_prisma%'\n `\n if (tables.length === 0) return\n const tableList = tables.map((t) => `\"${t.tablename}\"`).join(', ')\n await db.$executeRawUnsafe(`TRUNCATE ${tableList} RESTART IDENTITY CASCADE`)\n }\n\n /**\n * Run seeders by class constructor in the request-scoped container\n */\n async seed(...SeederClasses: Constructor<Seeder>[]): Promise<void> {\n const registry = this._requestContainer.resolve<SeederRegistry>(SEEDER_TOKENS.SeederRegistry)\n for (const SeederClass of SeederClasses) {\n if (!registry.has(SeederClass)) {\n throw new SeederNotRegisteredError(SeederClass.name)\n }\n await registry.run(SeederClass, { container: this._requestContainer })\n }\n }\n\n /**\n * Assert that a record exists in the database\n */\n async assertDatabaseHas(table: string, data: Record<string, unknown>, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { findFirst: (opts: unknown) => Promise<unknown> }\n const result = await model.findFirst({ where: data })\n expect(result, `Expected ${table} with ${JSON.stringify(data)}`).not.toBeNull()\n }\n\n /**\n * Assert that a record does not exist in the database\n */\n async assertDatabaseMissing(table: string, data: Record<string, unknown>, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { findFirst: (opts: unknown) => Promise<unknown> }\n const result = await model.findFirst({ where: data })\n expect(result, `Expected ${table} NOT to have ${JSON.stringify(data)}`).toBeNull()\n }\n\n /**\n * Assert the number of records in a table\n */\n async assertDatabaseCount(table: string, expected: number, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { count: () => Promise<number> }\n const actual = await model.count()\n expect(actual, `Expected ${table} count ${expected}, got ${actual}`).toBe(expected)\n }\n\n /**\n * Cleanup - call in afterAll\n */\n async close(): Promise<void> {\n await this._requestContainer.dispose()\n await this.app.shutdown()\n }\n}\n","import {\n Application,\n type ApplicationConfig,\n type Constructor,\n type StratalEnv,\n type StratalExecutionContext,\n} from 'stratal'\nimport { type Container } from 'stratal/di'\nimport { LogLevel } from 'stratal/logger'\nimport { type InjectionToken, Module, type ModuleClass, type ModuleOptions } from 'stratal/module'\nimport { STORAGE_TOKENS } from 'stratal/storage'\nimport { FakeStorageService } from '../storage'\nimport { ProviderOverrideBuilder, type ProviderOverrideConfig } from './override'\nimport { Test } from './test'\nimport { TestingModule } from './testing-module'\n\n/**\n * Configuration for creating a testing module\n *\n * Extends ModuleOptions to support all module properties like NestJS.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule, GeoModule],\n * providers: [{ provide: MOCK_TOKEN, useValue: mockValue }],\n * controllers: [TestController],\n * }).compile()\n * ```\n */\nexport interface TestingModuleConfig extends ModuleOptions {\n /** Optional environment overrides */\n env?: Partial<StratalEnv>\n /** Logging configuration. Defaults: level=ERROR, formatter='json' */\n logging?: ApplicationConfig['logging']\n}\n\n/**\n * Builder for creating test modules with provider overrides\n */\nexport class TestingModuleBuilder {\n private overrides: ProviderOverrideConfig<object>[] = []\n\n constructor(private config: TestingModuleConfig) { }\n\n /**\n * Override a provider with a custom implementation\n */\n overrideProvider<T>(token: InjectionToken<T>): ProviderOverrideBuilder<T> {\n return new ProviderOverrideBuilder(this, token)\n }\n\n /**\n * Add a provider override (internal use by ProviderOverrideBuilder)\n *\n * @internal\n */\n addProviderOverride<T>(override: ProviderOverrideConfig<T>): this {\n this.overrides.push(override as ProviderOverrideConfig<object>)\n return this\n }\n\n /**\n * Merge additional environment bindings\n */\n withEnv(env: Partial<StratalEnv>): this {\n this.config.env = { ...this.config.env, ...env }\n return this\n }\n\n private async getCloudflareWorkers() {\n try {\n return await import('cloudflare:workers')\n } catch {\n return null\n }\n }\n\n /**\n * Compile the testing module\n *\n * Creates the Application, applies overrides, initializes, and returns TestingModule.\n */\n async compile(): Promise<TestingModule> {\n const cf = await this.getCloudflareWorkers()\n\n const env = { ...cf?.env, ...this.config.env } as StratalEnv\n const ctx: StratalExecutionContext = {\n waitUntil: cf ? cf.waitUntil : (p) => {\n p.catch(() => {\n //\n })\n },\n }\n\n // Build root module from config\n const baseModules = Test.getBaseModules()\n const allImports = [...baseModules, ...(this.config.imports ?? [])]\n\n const rootModule = this.createTestRootModule({\n imports: allImports,\n providers: this.config.providers,\n controllers: this.config.controllers,\n consumers: this.config.consumers,\n jobs: this.config.jobs,\n })\n\n const app = new Application({\n module: rootModule,\n logging: {\n level: this.config.logging?.level ?? LogLevel.ERROR,\n formatter: this.config.logging?.formatter ?? 'pretty',\n },\n env,\n ctx,\n })\n\n // Auto-register FakeStorageService (can be overridden by user)\n app.container.registerSingleton(STORAGE_TOKENS.StorageService, FakeStorageService)\n\n await app.initialize()\n\n // Apply user overrides AFTER initialize so they replace module-registered providers\n for (const override of this.overrides) {\n switch (override.type) {\n case 'value':\n app.container.registerValue(override.token, override.implementation)\n break\n case 'class':\n app.container.registerSingleton(\n override.token,\n override.implementation as Constructor\n )\n break\n case 'factory':\n app.container.registerFactory(\n override.token,\n override.implementation as (c: Container) => object\n )\n break\n case 'existing':\n app.container.registerExisting(\n override.token,\n override.implementation as InjectionToken<object>\n )\n break\n }\n }\n\n return new TestingModule(app, env, ctx)\n }\n\n /**\n * Create a test root module with the given options\n */\n private createTestRootModule(options: ModuleOptions): ModuleClass {\n @Module(options)\n class TestRootModule { }\n return TestRootModule\n }\n}\n","import { type DynamicModule, type ModuleClass } from 'stratal/module'\nimport { TestingModuleBuilder, type TestingModuleConfig } from './testing-module-builder'\n\n/**\n * Test\n *\n * Static class for creating testing modules.\n * Provides a NestJS-style API for configuring test modules.\n *\n * @example\n * ```typescript\n * // In vitest.setup.ts:\n * Test.setBaseModules([CoreModule])\n *\n * // In test files:\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule, GeoModule],\n * })\n * .overrideProvider(EMAIL_TOKENS.EmailService)\n * .useValue(mockEmailService)\n * .compile()\n * ```\n */\nexport class Test {\n /**\n * Base modules to include in all test modules\n * Set once in vitest.setup.ts\n */\n private static baseModules: (ModuleClass | DynamicModule)[] = []\n\n /**\n * Set base modules to include in all test modules\n * Should be called once in vitest.setup.ts\n *\n * @param modules - Modules to include before test-specific modules (e.g., CoreModule)\n */\n static setBaseModules(modules: (ModuleClass | DynamicModule)[]): void {\n this.baseModules = modules\n }\n\n /**\n * Get base modules\n */\n static getBaseModules(): (ModuleClass | DynamicModule)[] {\n return this.baseModules\n }\n\n /**\n * Create a testing module builder\n *\n * @param config - Configuration with modules and optional env overrides\n * @returns TestingModuleBuilder for configuring and compiling the module\n */\n static createTestingModule(config: TestingModuleConfig): TestingModuleBuilder {\n return new TestingModuleBuilder(config)\n }\n}\n","import { http, HttpResponse, type RequestHandler } from 'msw'\nimport { setupServer, type SetupServer } from 'msw/node'\nimport type { MockErrorOptions, MockJsonOptions } from './fetch-mock.types'\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options'\n\n/**\n * MSW-based fetch mock for declarative HTTP mocking in tests.\n *\n * Replaces the old Cloudflare `fetchMock` (undici MockAgent) with MSW's `setupServer`.\n * Works in both Node.js and workerd test environments.\n *\n * @example\n * ```typescript\n * import { createMockFetch } from '@stratal/testing'\n *\n * const mock = createMockFetch()\n *\n * beforeAll(() => mock.listen())\n * afterEach(() => mock.reset())\n * afterAll(() => mock.close())\n *\n * it('should mock external API', async () => {\n * mock.mockJsonResponse('https://api.example.com/data', { success: true })\n *\n * const response = await fetch('https://api.example.com/data')\n * const json = await response.json()\n *\n * expect(json.success).toBe(true)\n * })\n * ```\n */\nexport class MockFetch {\n private server: SetupServer\n\n constructor(handlers: RequestHandler[] = []) {\n this.server = setupServer(...handlers)\n }\n\n /** Start intercepting. Call in beforeAll/beforeEach. */\n listen() {\n this.server.listen({ onUnhandledRequest: 'error' })\n }\n\n /** Reset runtime handlers. Call in afterEach. */\n reset() {\n this.server.resetHandlers()\n }\n\n /** Stop intercepting. Call in afterAll. */\n close() {\n this.server.close()\n }\n\n /** Add runtime handler(s) for a single test. */\n use(...handlers: RequestHandler[]) {\n this.server.use(...handlers)\n }\n\n /**\n * Mock a JSON response.\n *\n * @param url - Full URL to mock (e.g., 'https://api.example.com/users')\n * @param data - JSON data to return\n * @param options - HTTP method, status code, headers\n *\n * @example\n * ```typescript\n * mock.mockJsonResponse('https://api.example.com/users', { users: [] })\n * mock.mockJsonResponse('https://api.example.com/users', { created: true }, { method: 'POST', status: 201 })\n * ```\n */\n mockJsonResponse(url: string, data: Record<string, unknown> | unknown[], options: MockJsonOptions = {}) {\n const method = (options.method ?? 'GET').toLowerCase() as HttpMethod\n const handler = http[method](url, () =>\n HttpResponse.json(data, {\n status: options.status ?? 200,\n headers: options.headers,\n }),\n )\n this.server.use(handler)\n }\n\n /**\n * Mock an error response.\n *\n * @param url - Full URL to mock\n * @param status - HTTP error status code\n * @param message - Optional error message\n * @param options - HTTP method, headers\n *\n * @example\n * ```typescript\n * mock.mockError('https://api.example.com/fail', 401, 'Unauthorized')\n * mock.mockError('https://api.example.com/fail', 500, 'Server Error', { method: 'POST' })\n * ```\n */\n mockError(url: string, status: number, message?: string, options: MockErrorOptions = {}) {\n const method = (options.method ?? 'GET').toLowerCase() as HttpMethod\n const body = message ? { error: message } : undefined\n this.server.use(\n http[method](url, () =>\n HttpResponse.json(body, { status, headers: options.headers }),\n ),\n )\n }\n}\n\n/**\n * Factory function to create a new MockFetch instance\n *\n * @param handlers - Optional initial MSW request handlers\n * @returns A new MockFetch instance\n *\n * @example\n * ```typescript\n * import { createMockFetch } from '@stratal/testing'\n *\n * const mock = createMockFetch()\n *\n * beforeAll(() => mock.listen())\n * afterEach(() => mock.reset())\n * afterAll(() => mock.close())\n * ```\n */\nexport function createMockFetch(handlers?: RequestHandler[]): MockFetch {\n return new MockFetch(handlers)\n}\n","/**\n * Base error class for all test framework errors.\n * Extends from Error and allows easy identification via `instanceof`.\n */\nexport class TestError extends Error {\n constructor(\n message: string,\n public readonly cause?: Error\n ) {\n super(message)\n this.name = 'TestError'\n\n // Maintain proper stack trace\n Error.captureStackTrace(this, this.constructor)\n }\n}\n","import { TestError } from './test-error'\n\n/**\n * Error thrown when test setup fails.\n * Examples: schema creation failure, migration failure, application bootstrap failure.\n */\nexport class TestSetupError extends TestError {\n constructor(message: string, cause?: Error) {\n super(`Test setup failed: ${message}`, cause)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,0BAAb,MAAwC;CACtC,YACE,QACA,OACA;AAFiB,OAAA,SAAA;AACA,OAAA,QAAA;;;;;;;;;;CAWnB,SAAS,OAAgC;AACvC,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;;CAWJ,SAAS,KAA0D;AACjE,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;;CAWJ,WAAW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,MAAM,KAAK,YAAY;;;;;;;;;ACPnD,IAAa,iBAAb,cAAoC,UAAU;CAC5C,YAAY,SAAiB,OAAe;AAC1C,QAAM,sBAAsB,WAAW,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["http","HttpResponse"],"sources":["../src/core/override/provider-override-builder.ts","../src/core/http/locale-helper.ts","../src/auth/acting-as.ts","../src/core/http/path-utils.ts","../src/core/http/test-response.ts","../src/core/http/test-http-request.ts","../src/core/http/test-http-client.ts","../src/core/quarry/test-command-result.ts","../src/core/quarry/test-command-request.ts","../src/core/sse/test-sse-connection.ts","../src/core/sse/test-sse-request.ts","../src/core/ws/test-ws-connection.ts","../src/core/ws/test-ws-request.ts","../src/core/testing-module.ts","../src/core/testing-module-builder.ts","../src/core/test.ts","../src/core/http/mock-fetch.ts","../src/errors/test-error.ts","../src/errors/setup-error.ts"],"sourcesContent":["import { type Container } from 'stratal/di'\nimport { type InjectionToken } from 'stratal/module'\nimport type { TestingModuleBuilder } from '../testing-module-builder'\n\n/**\n * Provider override configuration\n */\nexport interface ProviderOverrideConfig<T = unknown> {\n token: InjectionToken<T>\n type: 'value' | 'class' | 'factory' | 'existing'\n implementation: T | (new (...args: unknown[]) => T) | ((container: Container) => T) | InjectionToken<T>\n}\n\n/**\n * Fluent builder for provider overrides\n *\n * Provides a NestJS-style API for overriding providers in tests.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule],\n * })\n * .overrideProvider(EMAIL_TOKENS.EmailService)\n * .useValue(mockEmailService)\n * .compile()\n * ```\n */\nexport class ProviderOverrideBuilder<T> {\n constructor(\n private readonly parent: TestingModuleBuilder,\n private readonly token: InjectionToken<T>\n ) { }\n\n /**\n * Use a static value as the provider\n *\n * The value will be registered directly in the container.\n *\n * @param value - The value to use as the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useValue(value: T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'value',\n implementation: value,\n })\n }\n\n /**\n * Use a class as the provider\n *\n * The class will be registered as a singleton.\n *\n * @param cls - The class constructor to use as the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useClass(cls: new (...args: unknown[]) => T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'class',\n implementation: cls,\n })\n }\n\n /**\n * Use a factory function as the provider\n *\n * The factory receives the container and should return the provider instance.\n *\n * @param factory - Factory function that creates the provider\n * @returns The parent TestingModuleBuilder for chaining\n */\n useFactory(factory: (container: Container) => T): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'factory',\n implementation: factory,\n })\n }\n\n /**\n * Use an existing token as the provider (alias)\n *\n * The override token will resolve to the same instance as the target token.\n *\n * @param existingToken - The token to alias\n * @returns The parent TestingModuleBuilder for chaining\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [MyModule],\n * })\n * .overrideProvider(ABSTRACT_TOKEN)\n * .useExisting(ConcreteService)\n * .compile()\n * ```\n */\n useExisting(existingToken: InjectionToken<T>): TestingModuleBuilder {\n return this.parent.addProviderOverride({\n token: this.token,\n type: 'existing',\n implementation: existingToken,\n })\n }\n}\n","import type { DetectionStrategy, I18nModuleOptions } from 'stratal/i18n'\nimport { I18N_TOKENS } from 'stratal/i18n'\nimport type { TestingModule } from '../testing-module'\n\n/**\n * Resolve the configured detection strategy from the testing module's DI container.\n * Falls back to 'cookie' if I18n is not configured.\n */\nexport function resolveLocaleStrategy(module: TestingModule): DetectionStrategy {\n try {\n const options = module.get<I18nModuleOptions>(I18N_TOKENS.Options)\n const detection = options.detection\n if (detection && 'strategy' in detection && detection.strategy) {\n return detection.strategy\n }\n return 'cookie'\n } catch {\n return 'cookie'\n }\n}\n\n/**\n * Apply locale to request headers based on detection strategy.\n */\nexport function applyLocaleToHeaders(\n headers: Headers,\n locale: string,\n strategy: DetectionStrategy,\n): void {\n switch (strategy) {\n case 'cookie':\n headers.set('Cookie', `locale=${locale}`)\n break\n case 'header':\n headers.set('Accept-Language', locale)\n break\n }\n}\n\n/**\n * Apply locale to URL based on detection strategy.\n */\nexport function applyLocaleToUrl(\n url: URL,\n locale: string,\n strategy: DetectionStrategy,\n): void {\n if (strategy === 'querystring') {\n url.searchParams.set('locale', locale)\n }\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { type GenericEndpointContext } from 'better-auth'\nimport { setSessionCookie } from 'better-auth/cookies'\nimport { convertSetCookieToCookie } from 'better-auth/test'\n\nasync function makeSignature(value: string, secret: string): Promise<string> {\n const algorithm = { name: 'HMAC', hash: 'SHA-256' }\n const secretBuf = new TextEncoder().encode(secret)\n const key = await crypto.subtle.importKey('raw', secretBuf, algorithm, false, ['sign'])\n const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value))\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n}\n\nfunction buildCookieString(name: string, value: string, options: Record<string, unknown> = {}): string {\n const encodedValue = encodeURIComponent(value)\n let str = `${name}=${encodedValue}`\n if (options.path) str += `; Path=${options.path as string}`\n if (options.httpOnly) str += '; HttpOnly'\n if (options.secure) str += '; Secure'\n if (options.sameSite) str += `; SameSite=${options.sameSite as string}`\n if (options.maxAge !== undefined) str += `; Max-Age=${Math.floor(options.maxAge as number)}`\n return str\n}\n\n/**\n * ActingAs\n *\n * Creates authentication sessions for testing.\n * Uses Better Auth's internalAdapter to create real database sessions.\n *\n * @example\n * ```typescript\n * const actingAs = new ActingAs(authService)\n * const headers = await actingAs.createSessionForUser({ id: 'user-123' })\n * ```\n */\nexport class ActingAs {\n constructor(private readonly authService: AuthService) { }\n\n async createSessionForUser(user: { id: string }): Promise<Headers> {\n const auth = this.authService.auth\n const ctx = await auth.$context\n\n const secret = ctx.secret\n\n const session = await ctx.internalAdapter.createSession(\n user.id,\n undefined,\n { ipAddress: '127.0.0.1', userAgent: 'test-client' }\n )\n\n const dbUser = await ctx.internalAdapter.findUserById(user.id)\n if (!dbUser) {\n throw new Error(`User not found: ${user.id}`)\n }\n\n const responseHeaders = new Headers()\n const mockCtx = {\n context: ctx,\n getSignedCookie: () => null,\n setSignedCookie: async (name: string, value: string, _secret: string, options: Record<string, unknown> = {}) => {\n const signature = await makeSignature(value, secret)\n const signedValue = `${value}.${signature}`\n responseHeaders.append('Set-Cookie', buildCookieString(name, signedValue, options))\n },\n setCookie: (name: string, value: string, options: Record<string, unknown> = {}) => {\n responseHeaders.append('Set-Cookie', buildCookieString(name, value, options))\n },\n }\n\n await setSessionCookie(mockCtx as unknown as GenericEndpointContext, { session, user: dbUser }, false)\n return convertSetCookieToCookie(responseHeaders)\n }\n}\n","/**\n * Get value at dot-notation path.\n */\nexport function getValueAtPath(obj: unknown, path: string): unknown {\n const parts = path.split('.')\n let current: unknown = obj\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined\n }\n current = (current as Record<string, unknown>)[part]\n }\n\n return current\n}\n\n/**\n * Check if a path exists in the object (even if value is null/undefined).\n */\nexport function hasValueAtPath(obj: unknown, path: string): boolean {\n const parts = path.split('.')\n let current: unknown = obj\n\n for (const part of parts) {\n if (current === null || current === undefined) {\n return false\n }\n\n if (typeof current !== 'object') {\n return false\n }\n\n const record = current as Record<string, unknown>\n\n if (!(part in record)) {\n return false\n }\n\n current = record[part]\n }\n\n return true\n}\n","import { Macroable } from 'stratal/macroable'\nimport { expect } from 'vitest'\nimport { getValueAtPath, hasValueAtPath } from './path-utils'\n\n/**\n * TestResponse\n *\n * Wrapper around Response with assertion methods.\n *\n * @example\n * ```typescript\n * response\n * .assertOk()\n * .assertStatus(200)\n * .assertJsonPath('data.id', userId)\n * ```\n */\nexport class TestResponse extends Macroable {\n private jsonData: unknown = null\n private textData: string | null = null\n\n constructor(private readonly response: Response) {\n super()\n }\n\n /**\n * Get the raw Response object.\n */\n get raw(): Response {\n return this.response\n }\n\n /**\n * Get the response status code.\n */\n get status(): number {\n return this.response.status\n }\n\n /**\n * Get response headers.\n */\n get headers(): Headers {\n return this.response.headers\n }\n\n /**\n * Get the response body as JSON.\n */\n async json<T = unknown>(): Promise<T> {\n if (this.jsonData === null) {\n this.jsonData = await this.response.clone().json()\n }\n return this.jsonData as T\n }\n\n /**\n * Get the response body as text.\n */\n async text(): Promise<string> {\n this.textData ??= await this.response.clone().text()\n return this.textData\n }\n\n // ============================================================\n // Status Assertions\n // ============================================================\n\n /**\n * Assert response status is 200 OK.\n */\n assertOk(): this {\n return this.assertStatus(200)\n }\n\n /**\n * Assert response status is 201 Created.\n */\n assertCreated(): this {\n return this.assertStatus(201)\n }\n\n /**\n * Assert response status is 204 No Content.\n */\n assertNoContent(): this {\n return this.assertStatus(204)\n }\n\n /**\n * Assert response status is 400 Bad Request.\n */\n assertBadRequest(): this {\n return this.assertStatus(400)\n }\n\n /**\n * Assert response status is 401 Unauthorized.\n */\n assertUnauthorized(): this {\n return this.assertStatus(401)\n }\n\n /**\n * Assert response status is 403 Forbidden.\n */\n assertForbidden(): this {\n return this.assertStatus(403)\n }\n\n /**\n * Assert response status is 404 Not Found.\n */\n assertNotFound(): this {\n return this.assertStatus(404)\n }\n\n /**\n * Assert response status is 422 Unprocessable Entity.\n */\n assertUnprocessable(): this {\n return this.assertStatus(422)\n }\n\n /**\n * Assert response status is 500 Internal Server Error.\n */\n assertServerError(): this {\n return this.assertStatus(500)\n }\n\n /**\n * Assert response has the given status code.\n */\n assertStatus(expected: number): this {\n expect(\n this.response.status,\n `Expected status ${expected}, got ${this.response.status}`\n ).toBe(expected)\n return this\n }\n\n /**\n * Assert response status is in the 2xx success range.\n */\n assertSuccessful(): this {\n expect(\n this.response.status >= 200 && this.response.status < 300,\n `Expected successful status (2xx), got ${this.response.status}`\n ).toBe(true)\n return this\n }\n\n // ============================================================\n // JSON Assertions\n // ============================================================\n\n /**\n * Assert JSON response contains the given data.\n */\n async assertJson(expected: Record<string, unknown>): Promise<this> {\n const actual = await this.json<Record<string, unknown>>()\n\n for (const [key, value] of Object.entries(expected)) {\n expect(\n actual[key],\n `Expected JSON key \"${key}\" to be ${JSON.stringify(value)}, got ${JSON.stringify(actual[key])}`\n ).toStrictEqual(value)\n }\n\n return this\n }\n\n /**\n * Assert JSON response has value at the given path.\n *\n * @param path - Dot-notation path (e.g., 'data.user.id')\n * @param expected - Expected value at path\n */\n async assertJsonPath(path: string, expected: unknown): Promise<this> {\n const json = await this.json()\n const actual = getValueAtPath(json, path)\n\n expect(\n actual,\n `Expected JSON path \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`\n ).toStrictEqual(expected)\n\n return this\n }\n\n /**\n * Assert JSON response structure matches the given schema.\n */\n async assertJsonStructure(structure: string[]): Promise<this> {\n const json = await this.json<Record<string, unknown>>()\n\n for (const key of structure) {\n expect(\n key in json,\n `Expected JSON to have key \"${key}\", got keys: ${JSON.stringify(Object.keys(json))}`\n ).toBe(true)\n }\n\n return this\n }\n\n /**\n * Assert a JSON path exists (value can be anything, including null).\n *\n * @param path - Dot-notation path (e.g., 'data.user.id')\n */\n async assertJsonPathExists(path: string): Promise<this> {\n const json = await this.json()\n const exists = hasValueAtPath(json, path)\n\n expect(\n exists,\n `Expected JSON path \"${path}\" to exist`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert a JSON path does not exist.\n *\n * @param path - Dot-notation path (e.g., 'data.user.deletedAt')\n */\n async assertJsonPathMissing(path: string): Promise<this> {\n const json = await this.json()\n const exists = hasValueAtPath(json, path)\n\n expect(\n exists,\n `Expected JSON path \"${path}\" to not exist`\n ).toBe(false)\n\n return this\n }\n\n /**\n * Assert JSON value at path matches a custom predicate.\n *\n * @param path - Dot-notation path (e.g., 'data.items')\n * @param matcher - Predicate function to validate the value\n */\n async assertJsonPathMatches(\n path: string,\n matcher: (value: unknown) => boolean\n ): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n matcher(value),\n `Expected JSON path \"${path}\" to match predicate, got ${JSON.stringify(value)}`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert string value at path contains a substring.\n *\n * @param path - Dot-notation path (e.g., 'data.message')\n * @param substring - Substring to search for\n */\n async assertJsonPathContains(path: string, substring: string): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n typeof value === 'string',\n `Expected JSON path \"${path}\" to be a string, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as string).includes(substring),\n `Expected JSON path \"${path}\" to contain \"${substring}\", got \"${String(value)}\"`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert array value at path includes a specific item.\n *\n * @param path - Dot-notation path (e.g., 'data.tags')\n * @param item - Item to search for in the array\n */\n async assertJsonPathIncludes(path: string, item: unknown): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n Array.isArray(value),\n `Expected JSON path \"${path}\" to be an array, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as unknown[]).includes(item),\n `Expected JSON path \"${path}\" to include ${JSON.stringify(item)}`\n ).toBe(true)\n\n return this\n }\n\n /**\n * Assert array length at path equals the expected count.\n *\n * @param path - Dot-notation path (e.g., 'data.items')\n * @param count - Expected array length\n */\n async assertJsonPathCount(path: string, count: number): Promise<this> {\n const json = await this.json()\n const value = getValueAtPath(json, path)\n\n expect(\n Array.isArray(value),\n `Expected JSON path \"${path}\" to be an array, got ${typeof value}`\n ).toBe(true)\n\n expect(\n (value as unknown[]).length,\n `Expected JSON path \"${path}\" to have ${count} items, got ${(value as unknown[]).length}`\n ).toBe(count)\n\n return this\n }\n\n /**\n * Assert multiple JSON paths at once (batch assertion).\n *\n * @param expectations - Object mapping paths to expected values\n */\n async assertJsonPaths(expectations: Record<string, unknown>): Promise<this> {\n const json = await this.json()\n\n for (const [path, expected] of Object.entries(expectations)) {\n const actual = getValueAtPath(json, path)\n expect(\n actual,\n `Expected JSON path \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`\n ).toStrictEqual(expected)\n }\n\n return this\n }\n\n // ============================================================\n // Header Assertions\n // ============================================================\n\n /**\n * Assert response has the given header.\n */\n assertHeader(name: string, expected?: string): this {\n const actual = this.response.headers.get(name)\n\n expect(\n actual !== null,\n `Expected header \"${name}\" to be present`\n ).toBe(true)\n\n if (expected !== undefined) {\n expect(\n actual,\n `Expected header \"${name}\" to be \"${expected}\", got \"${actual}\"`\n ).toBe(expected)\n }\n\n return this\n }\n\n /**\n * Assert response does not have the given header.\n */\n assertHeaderMissing(name: string): this {\n const actual = this.response.headers.get(name)\n\n expect(\n actual,\n `Expected header \"${name}\" to be absent, but got \"${actual}\"`\n ).toBeNull()\n\n return this\n }\n\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { Macroable } from 'stratal/macroable'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, applyLocaleToUrl, resolveLocaleStrategy } from './locale-helper'\nimport { TestResponse } from './test-response'\n\n/**\n * TestHttpRequest\n *\n * Request builder with fluent API for configuring test HTTP requests.\n *\n * @example\n * ```typescript\n * const response = await module.http\n * .post('/api/v1/register')\n * .withBody({ name: 'Test School' })\n * .withHeaders({ 'X-Custom': 'value' })\n * .send()\n * ```\n *\n * @example Authenticated request\n * ```typescript\n * const response = await module.http\n * .get('/api/v1/profile')\n * .actingAs({ id: user.id })\n * .send()\n * ```\n */\nexport class TestHttpRequest extends Macroable {\n\tprotected body: unknown = null\n\tprotected requestHeaders: Headers\n\tprotected actingAsUser: { id: string } | null = null\n\tprotected authResolver: ((module: TestingModule, user: { id: string }) => Promise<Headers>) | null = null\n\tprotected localeConfig: { locale: string; strategy: DetectionStrategy } | null\n\n\tconstructor(\n\t\tprotected readonly method: string,\n\t\tprotected readonly path: string,\n\t\theaders: Headers,\n\t\tprotected readonly module: TestingModule,\n\t\tprotected readonly host: string | null = null,\n\t\tlocaleConfig: { locale: string; strategy: DetectionStrategy } | null = null,\n\t) {\n\t\tsuper()\n\t\tthis.requestHeaders = new Headers(headers)\n\t\tthis.localeConfig = localeConfig\n\t}\n\n\t/**\n\t * Set the request body\n\t */\n\twithBody(data: unknown): this {\n\t\tthis.body = data\n\t\treturn this\n\t}\n\n\t/**\n\t * Add headers to the request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this request.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t *\n\t * @param locale - Locale code (e.g., 'en', 'fr')\n\t * @param strategy - Detection strategy override\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tthis.localeConfig = { locale, strategy: resolved }\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Set Content-Type to application/json\n\t */\n\tasJson(): this {\n\t\tthis.requestHeaders.set('Content-Type', 'application/json')\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the request as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\tthis.authResolver = null\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the request and return response\n\t *\n\t * Calls module.fetch() - NOT SELF.fetch()\n\t */\n\tasync send(): Promise<TestResponse> {\n\t\tawait this.applyAuthentication()\n\n\t\t// Auto-set Content-Type for body\n\t\tif (this.body && !this.requestHeaders.has('Content-Type')) {\n\t\t\tthis.requestHeaders.set('Content-Type', 'application/json')\n\t\t}\n\n\t\t// Build request\n\t\tconst url = new URL(this.path, `http://${this.host ?? 'localhost'}`)\n\n\t\t// Apply locale to URL for querystring strategy\n\t\tif (this.localeConfig) {\n\t\t\tapplyLocaleToUrl(url, this.localeConfig.locale, this.localeConfig.strategy)\n\t\t}\n\n\t\tconst request = new Request(url.toString(), {\n\t\t\tmethod: this.method,\n\t\t\theaders: this.requestHeaders,\n\t\t\tbody: this.body ? JSON.stringify(this.body) : null,\n\t\t})\n\n\t\t// Call module.fetch() - NO SELF.fetch()\n\t\tconst response = await this.module.fetch(request)\n\t\treturn new TestResponse(response)\n\t}\n\n\tprotected async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tif (this.authResolver) {\n\t\t\tconst headers = await this.authResolver(this.module, this.actingAsUser)\n\t\t\tfor (const [key, value] of headers.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = await actingAs.createSessionForUser(this.actingAsUser!)\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { DetectionStrategy } from 'stratal/i18n'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from './locale-helper'\nimport { TestHttpRequest } from './test-http-request'\n\n/**\n * TestHttpClient\n *\n * Fluent HTTP client for making test requests.\n *\n * @example\n * ```typescript\n * const response = await module.http\n * .forHost('example.com')\n * .post('/api/v1/users')\n * .withBody({ name: 'Test' })\n * .send()\n *\n * response.assertCreated()\n * ```\n */\nexport class TestHttpClient {\n private defaultHeaders: Headers\n private host: string | null\n private localeConfig: { locale: string; strategy: DetectionStrategy } | null\n\n constructor(\n private readonly module: TestingModule,\n host: string | null = null,\n headers: Headers = new Headers(),\n localeConfig: { locale: string; strategy: DetectionStrategy } | null = null,\n ) {\n this.host = host\n this.defaultHeaders = headers\n this.localeConfig = localeConfig\n }\n\n /**\n * Set the host for the request (returns a new client).\n * Also sets the Host header to ensure domain routing works\n * even when the runtime reads the header instead of the URL host.\n */\n forHost(host: string): TestHttpClient {\n const newHeaders = new Headers(this.defaultHeaders)\n newHeaders.set('Host', host)\n return new TestHttpClient(this.module, host, newHeaders, this.localeConfig)\n }\n\n /**\n * Set default headers for all requests (returns a new client)\n */\n withHeaders(headers: Record<string, string>): TestHttpClient {\n const newHeaders = new Headers(this.defaultHeaders)\n for (const [key, value] of Object.entries(headers)) {\n newHeaders.set(key, value)\n }\n return new TestHttpClient(this.module, this.host, newHeaders, this.localeConfig)\n }\n\n /**\n * Set the locale for all requests from this client (returns a new client).\n * If strategy is not provided, resolves from the module's I18n configuration.\n *\n * @param locale - Locale code (e.g., 'en', 'fr')\n * @param strategy - Detection strategy override\n */\n withLocale(locale: string, strategy?: DetectionStrategy): TestHttpClient {\n const resolved = strategy ?? resolveLocaleStrategy(this.module)\n const newHeaders = new Headers(this.defaultHeaders)\n applyLocaleToHeaders(newHeaders, locale, resolved)\n return new TestHttpClient(this.module, this.host, newHeaders, { locale, strategy: resolved })\n }\n\n /**\n * Create a GET request\n */\n get(path: string): TestHttpRequest {\n return this.createRequest('GET', path)\n }\n\n /**\n * Create a POST request\n */\n post(path: string): TestHttpRequest {\n return this.createRequest('POST', path)\n }\n\n /**\n * Create a PUT request\n */\n put(path: string): TestHttpRequest {\n return this.createRequest('PUT', path)\n }\n\n /**\n * Create a PATCH request\n */\n patch(path: string): TestHttpRequest {\n return this.createRequest('PATCH', path)\n }\n\n /**\n * Create a DELETE request\n */\n delete(path: string): TestHttpRequest {\n return this.createRequest('DELETE', path)\n }\n\n private createRequest(method: string, path: string): TestHttpRequest {\n return new TestHttpRequest(method, path, this.defaultHeaders, this.module, this.host, this.localeConfig)\n }\n}\n","import type { CommandResult } from 'stratal/quarry'\nimport { expect } from 'vitest'\n\n/**\n * Fluent assertion wrapper for command results.\n *\n * @example\n * ```typescript\n * const result = await module\n * .quarry('users:create')\n * .withInput({ email: 'test@example.com' })\n * .run()\n *\n * result.assertSuccessful()\n * result.assertOutputContains('User created')\n * ```\n */\nexport class TestCommandResult {\n constructor(private readonly result: CommandResult) {}\n\n get exitCode(): number {\n return this.result.exitCode\n }\n\n get output(): string[] {\n return this.result.output\n }\n\n get errors(): string[] {\n return this.result.errors\n }\n\n assertSuccessful(): this {\n expect(this.result.exitCode, `Expected exit code 0, got ${this.result.exitCode}. Errors: ${this.result.errors.join(', ')}`).toBe(0)\n expect(this.result.errors, 'Expected no errors').toHaveLength(0)\n return this\n }\n\n assertFailed(exitCode?: number): this {\n if (exitCode !== undefined) {\n expect(this.result.exitCode, `Expected exit code ${exitCode}, got ${this.result.exitCode}`).toBe(exitCode)\n } else {\n expect(this.result.exitCode, 'Expected non-zero exit code').not.toBe(0)\n }\n return this\n }\n\n assertExitCode(code: number): this {\n expect(this.result.exitCode, `Expected exit code ${code}, got ${this.result.exitCode}`).toBe(code)\n return this\n }\n\n assertOutputContains(text: string): this {\n const joined = this.result.output.join('\\n')\n expect(joined, `Expected output to contain \"${text}\"`).toContain(text)\n return this\n }\n\n assertOutputMissing(text: string): this {\n const joined = this.result.output.join('\\n')\n expect(joined, `Expected output NOT to contain \"${text}\"`).not.toContain(text)\n return this\n }\n\n assertErrorContains(text: string): this {\n const joined = this.result.errors.join('\\n')\n expect(joined, `Expected errors to contain \"${text}\"`).toContain(text)\n return this\n }\n\n assertErrorMissing(text: string): this {\n const joined = this.result.errors.join('\\n')\n expect(joined, `Expected errors NOT to contain \"${text}\"`).not.toContain(text)\n return this\n }\n}\n","import type { CommandInput } from 'stratal/quarry'\nimport type { TestingModule } from '../testing-module'\nimport { TestCommandResult } from './test-command-result'\n\n/**\n * Fluent builder for testing Quarry commands.\n *\n * @example\n * ```typescript\n * const result = await module\n * .quarry('users:create')\n * .withInput({ email: 'test@example.com', admin: true })\n * .run()\n *\n * result.assertSuccessful()\n * result.assertOutputContains('User created')\n * ```\n */\nexport class TestCommandRequest {\n private _input: CommandInput = {}\n\n constructor(\n private readonly commandName: string,\n private readonly module: TestingModule,\n ) {}\n\n /**\n * Set the flat input for the command.\n */\n withInput(input: CommandInput): this {\n this._input = { ...input }\n return this\n }\n\n /**\n * Execute the command and return a TestCommandResult for assertions.\n */\n async run(): Promise<TestCommandResult> {\n const result = await this.module.application.handleCommand(this.commandName, this._input)\n return new TestCommandResult(result)\n }\n}\n","import { expect } from \"vitest\"\n\n/**\n * Represents a parsed SSE event\n */\nexport interface TestSseEvent {\n\tdata: string\n\tevent?: string\n\tid?: string\n\tretry?: number\n}\n\n/**\n * TestSseConnection\n *\n * Live SSE connection wrapper with assertion helpers for testing.\n *\n * @example\n * ```typescript\n * const sse = await module.sse('/streaming/sse').connect()\n * await sse.assertEvent({ event: 'message', data: 'hello', id: '1' })\n * await sse.waitForEnd()\n * ```\n */\nexport class TestSseConnection {\n\tprivate readonly eventQueue: TestSseEvent[] = []\n\tprivate eventWaiters: ((event: TestSseEvent) => void)[] = []\n\tprivate streamEnded = false\n\tprivate endWaiters: (() => void)[] = []\n\n\tconstructor(private readonly response: Response) {\n\t\tthis.startReading()\n\t}\n\n\t/**\n\t * Wait for the next SSE event\n\t */\n\tasync waitForEvent(timeout = 5000): Promise<TestSseEvent> {\n\t\tif (this.eventQueue.length > 0) {\n\t\t\treturn this.eventQueue.shift()!\n\t\t}\n\n\t\tif (this.streamEnded) {\n\t\t\tthrow new Error('SSE: stream has ended, no more events')\n\t\t}\n\n\t\treturn new Promise<TestSseEvent>((resolve, reject) => {\n\t\t\tconst waiter = (event: TestSseEvent) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(event)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.eventWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.eventWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: no event received within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.eventWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Wait for the stream to end\n\t */\n\tasync waitForEnd(timeout = 5000): Promise<void> {\n\t\tif (this.streamEnded) return\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst waiter = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve()\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.endWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.endWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: stream did not end within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.endWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Collect all remaining events until the stream ends\n\t */\n\tasync collectEvents(timeout = 5000): Promise<TestSseEvent[]> {\n\t\tconst events: TestSseEvent[] = []\n\n\t\tif (this.streamEnded) {\n\t\t\treturn [...this.eventQueue.splice(0)]\n\t\t}\n\n\t\treturn new Promise<TestSseEvent[]>((resolve, reject) => {\n\t\t\t// Listen for new events until stream ends\n\t\t\tconst originalDispatch = this.dispatchEvent.bind(this)\n\t\t\tthis.dispatchEvent = (event: TestSseEvent) => {\n\t\t\t\tevents.push(event)\n\t\t\t\toriginalDispatch(event)\n\t\t\t}\n\n\t\t\tconst endWaiter = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tthis.dispatchEvent = originalDispatch\n\t\t\t\tresolve(events)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.dispatchEvent = originalDispatch\n\t\t\t\tconst index = this.endWaiters.indexOf(endWaiter)\n\t\t\t\tif (index !== -1) this.endWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`SSE: stream did not end within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\t// Drain any queued events first\n\t\t\tevents.push(...this.eventQueue.splice(0))\n\n\t\t\tthis.endWaiters.push(endWaiter)\n\t\t})\n\t}\n\n\t/**\n\t * Assert that the next event matches the expected partial shape\n\t */\n\tasync assertEvent(expected: Partial<TestSseEvent>, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\texpect(event).toMatchObject(expected)\n\t}\n\n\t/**\n\t * Assert that the next event's data matches the expected string\n\t */\n\tasync assertEventData(expected: string, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\texpect(event.data, `Expected SSE data \"${expected}\", got \"${event.data}\"`).toBe(expected)\n\t}\n\n\t/**\n\t * Assert that the next event's data is JSON matching the expected value\n\t */\n\tasync assertJsonEventData<T>(expected: T, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForEvent(timeout)\n\t\tconst parsed = JSON.parse(event.data) as unknown\n\t\texpect(parsed).toEqual(expected)\n\t}\n\n\t/**\n\t * Access the raw Response\n\t */\n\tget raw(): Response {\n\t\treturn this.response\n\t}\n\n\tprivate startReading(): void {\n\t\tconst body = this.response.body\n\t\tif (!body) {\n\t\t\tthis.streamEnded = true\n\t\t\treturn\n\t\t}\n\n\t\tconst reader = body.getReader() as ReadableStreamDefaultReader<Uint8Array>\n\t\tconst decoder = new TextDecoder()\n\t\tlet buffer = ''\n\n\t\tconst read = async (): Promise<void> => {\n\t\t\ttry {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read()\n\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\t// Parse any remaining buffered data\n\t\t\t\t\t\tif (buffer.trim()) {\n\t\t\t\t\t\t\tconst event = this.parseEvent(buffer)\n\t\t\t\t\t\t\tif (event) this.dispatchEvent(event)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.streamEnded = true\n\t\t\t\t\t\tfor (const waiter of this.endWaiters) {\n\t\t\t\t\t\t\twaiter()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.endWaiters = []\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true })\n\n\t\t\t\t\t// Split on double newlines (SSE event boundary)\n\t\t\t\t\tconst parts = buffer.split('\\n\\n')\n\t\t\t\t\t// Last part may be incomplete, keep it in the buffer\n\t\t\t\t\tbuffer = parts.pop()!\n\n\t\t\t\t\tfor (const part of parts) {\n\t\t\t\t\t\tif (!part.trim()) continue\n\t\t\t\t\t\tconst event = this.parseEvent(part)\n\t\t\t\t\t\tif (event) this.dispatchEvent(event)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tthis.streamEnded = true\n\t\t\t\tfor (const waiter of this.endWaiters) {\n\t\t\t\t\twaiter()\n\t\t\t\t}\n\t\t\t\tthis.endWaiters = []\n\t\t\t}\n\t\t}\n\n\t\tvoid read()\n\t}\n\n\tprivate parseEvent(raw: string): TestSseEvent | null {\n\t\tconst lines = raw.split('\\n')\n\t\tconst dataLines: string[] = []\n\t\tlet event: string | undefined\n\t\tlet id: string | undefined\n\t\tlet retry: number | undefined\n\n\t\tfor (const line of lines) {\n\t\t\tif (line.startsWith(':')) continue // comment line\n\n\t\t\tconst colonIndex = line.indexOf(':')\n\t\t\tif (colonIndex === -1) continue\n\n\t\t\tconst field = line.slice(0, colonIndex)\n\t\t\t// Strip optional leading space after colon\n\t\t\tconst value = line[colonIndex + 1] === ' ' ? line.slice(colonIndex + 2) : line.slice(colonIndex + 1)\n\n\t\t\tswitch (field) {\n\t\t\t\tcase 'data':\n\t\t\t\t\tdataLines.push(value)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'event':\n\t\t\t\t\tevent = value\n\t\t\t\t\tbreak\n\t\t\t\tcase 'id':\n\t\t\t\t\tid = value\n\t\t\t\t\tbreak\n\t\t\t\tcase 'retry': {\n\t\t\t\t\tconst parsed = parseInt(value, 10)\n\t\t\t\t\tif (!isNaN(parsed)) retry = parsed\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (dataLines.length === 0) return null\n\n\t\tconst result: TestSseEvent = { data: dataLines.join('\\n') }\n\t\tif (event !== undefined) result.event = event\n\t\tif (id !== undefined) result.id = id\n\t\tif (retry !== undefined) result.retry = retry\n\n\t\treturn result\n\t}\n\n\tprivate dispatchEvent(event: TestSseEvent): void {\n\t\tif (this.eventWaiters.length > 0) {\n\t\t\tthis.eventWaiters.shift()!(event)\n\t\t} else {\n\t\t\tthis.eventQueue.push(event)\n\t\t}\n\t}\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { expect } from 'vitest'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from '../http/locale-helper'\nimport { TestSseConnection } from './test-sse-connection'\n\n/**\n * TestSseRequest\n *\n * Builder for SSE connection requests. Follows the TestWsRequest pattern.\n *\n * @example\n * ```typescript\n * const sse = await module.sse('/streaming/sse').connect()\n * await sse.assertEvent({ event: 'message', data: 'hello' })\n * await sse.waitForEnd()\n * ```\n *\n * @example Authenticated SSE\n * ```typescript\n * const sse = await module.sse('/streaming/sse').actingAs({ id: user.id }).connect()\n * ```\n */\nexport class TestSseRequest {\n\tprivate requestHeaders: Headers = new Headers()\n\tprivate actingAsUser: { id: string } | null = null\n\n\tconstructor(\n\t\tprivate readonly path: string,\n\t\tprivate readonly module: TestingModule,\n\t) { }\n\n\t/**\n\t * Add custom headers to the request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this SSE connection.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the SSE connection as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the request and return a live SSE connection\n\t */\n\tasync connect(): Promise<TestSseConnection> {\n\t\tawait this.applyAuthentication()\n\n\t\tthis.requestHeaders.set('Accept', 'text/event-stream')\n\n\t\tconst url = new URL(this.path, 'http://localhost')\n\t\tconst request = new Request(url.toString(), {\n\t\t\theaders: this.requestHeaders,\n\t\t})\n\n\t\tconst response = await this.module.fetch(request)\n\n\t\texpect(\n\t\t\tresponse.status,\n\t\t\t`Expected status 200, got ${response.status}`,\n\t\t).toBe(200)\n\n\t\tconst contentType = response.headers.get('content-type') ?? ''\n\t\texpect(\n\t\t\tcontentType.includes('text/event-stream'),\n\t\t\t`Expected content-type \"text/event-stream\", got \"${contentType}\"`,\n\t\t).toBe(true)\n\n\t\treturn new TestSseConnection(response)\n\t}\n\n\tprivate async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers()\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import { expect } from \"vitest\";\n\n/**\n * TestWsConnection\n *\n * Live WebSocket connection wrapper with assertion helpers for testing.\n *\n * @example\n * ```typescript\n * const ws = await module.ws('/ws/chat').connect()\n * ws.send('hello')\n * await ws.assertMessage('echo:hello')\n * ws.close()\n * await ws.waitForClose()\n * ```\n */\nexport class TestWsConnection {\n\tprivate readonly messageQueue: (string | ArrayBuffer)[] = []\n\tprivate messageWaiters: ((data: string | ArrayBuffer) => void)[] = []\n\tprivate closeEvent: { code?: number; reason?: string } | null = null\n\tprivate closeWaiters: ((event: { code?: number; reason?: string }) => void)[] = []\n\n\tconstructor(private readonly ws: WebSocket) {\n\t\tthis.ws.addEventListener('message', (event: MessageEvent) => {\n\t\t\tconst data = event.data as string | ArrayBuffer\n\t\t\tif (this.messageWaiters.length > 0) {\n\t\t\t\tthis.messageWaiters.shift()!(data)\n\t\t\t} else {\n\t\t\t\tthis.messageQueue.push(data)\n\t\t\t}\n\t\t})\n\n\t\tthis.ws.addEventListener('close', (event: CloseEvent) => {\n\t\t\tthis.closeEvent = { code: event.code, reason: event.reason }\n\t\t\tfor (const waiter of this.closeWaiters) {\n\t\t\t\twaiter(this.closeEvent)\n\t\t\t}\n\t\t\tthis.closeWaiters = []\n\t\t})\n\t}\n\n\t/**\n\t * Send a message through the WebSocket\n\t */\n\tsend(data: string | ArrayBuffer | Uint8Array): void {\n\t\tthis.ws.send(data)\n\t}\n\n\t/**\n\t * Close the WebSocket connection\n\t */\n\tclose(code?: number, reason?: string): void {\n\t\tthis.ws.close(code, reason)\n\t}\n\n\t/**\n\t * Wait for the next message, returning its data\n\t */\n\tasync waitForMessage(timeout = 5000): Promise<string | ArrayBuffer> {\n\t\tif (this.messageQueue.length > 0) {\n\t\t\treturn this.messageQueue.shift()!\n\t\t}\n\n\t\treturn new Promise<string | ArrayBuffer>((resolve, reject) => {\n\t\t\tconst waiter = (data: string | ArrayBuffer) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(data)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.messageWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.messageWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`WebSocket: no message received within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.messageWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Wait for the connection to close\n\t */\n\tasync waitForClose(timeout = 5000): Promise<{ code?: number; reason?: string }> {\n\t\tif (this.closeEvent) {\n\t\t\treturn this.closeEvent\n\t\t}\n\n\t\treturn new Promise<{ code?: number; reason?: string }>((resolve, reject) => {\n\t\t\tconst waiter = (event: { code?: number; reason?: string }) => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve(event)\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tconst index = this.closeWaiters.indexOf(waiter)\n\t\t\t\tif (index !== -1) this.closeWaiters.splice(index, 1)\n\t\t\t\treject(new Error(`WebSocket: connection did not close within ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tthis.closeWaiters.push(waiter)\n\t\t})\n\t}\n\n\t/**\n\t * Assert that the next message equals the expected value\n\t */\n\tasync assertMessage(expected: string, timeout = 5000): Promise<void> {\n\t\tconst data = await this.waitForMessage(timeout)\n\t\tconst message = typeof data === 'string' ? data : '[ArrayBuffer]'\n\t\texpect(message, `Expected WebSocket message \"${expected}\", got \"${message}\"`).toBe(expected)\n\t}\n\n\t/**\n\t * Assert that the connection closes, optionally with an expected code\n\t */\n\tasync assertClosed(expectedCode?: number, timeout = 5000): Promise<void> {\n\t\tconst event = await this.waitForClose(timeout)\n\t\tif (expectedCode !== undefined) {\n\t\t\texpect(event.code, `Expected close code ${expectedCode}, got ${event.code}`).toBe(expectedCode)\n\t\t}\n\t}\n\n\t/**\n\t * Access the raw Cloudflare WebSocket\n\t */\n\tget raw(): WebSocket {\n\t\treturn this.ws\n\t}\n}\n","import type { AuthService } from '@stratal/framework/auth'\nimport { AUTH_SERVICE } from '@stratal/framework/auth'\nimport type { DetectionStrategy } from 'stratal/i18n'\nimport { expect } from 'vitest'\nimport { ActingAs } from '../../auth'\nimport type { TestingModule } from '../testing-module'\nimport { applyLocaleToHeaders, resolveLocaleStrategy } from '../http/locale-helper'\nimport { TestWsConnection } from './test-ws-connection'\n\n/**\n * TestWsRequest\n *\n * Builder for WebSocket upgrade requests. Follows the TestHttpRequest pattern.\n *\n * @example\n * ```typescript\n * const ws = await module.ws('/ws/chat').connect()\n * ws.send('hello')\n * await ws.assertMessage('echo:hello')\n * ws.close()\n * ```\n *\n * @example Authenticated WebSocket\n * ```typescript\n * const ws = await module.ws('/ws/chat').actingAs({ id: user.id }).connect()\n * ```\n */\nexport class TestWsRequest {\n\tprivate requestHeaders: Headers = new Headers()\n\tprivate actingAsUser: { id: string } | null = null\n\n\tconstructor(\n\t\tprivate readonly path: string,\n\t\tprivate readonly module: TestingModule,\n\t) { }\n\n\t/**\n\t * Add custom headers to the upgrade request\n\t */\n\twithHeaders(headers: Record<string, string>): this {\n\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\tthis.requestHeaders.set(key, value)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the locale for this WebSocket connection.\n\t * If strategy is not provided, resolves from the module's I18n configuration.\n\t */\n\twithLocale(locale: string, strategy?: DetectionStrategy): this {\n\t\tconst resolved = strategy ?? resolveLocaleStrategy(this.module)\n\t\tapplyLocaleToHeaders(this.requestHeaders, locale, resolved)\n\t\treturn this\n\t}\n\n\t/**\n\t * Authenticate the WebSocket connection as a specific user\n\t */\n\tactingAs(user: { id: string }): this {\n\t\tthis.actingAsUser = user\n\t\treturn this\n\t}\n\n\t/**\n\t * Send the upgrade request and return a live WebSocket connection\n\t */\n\tasync connect(): Promise<TestWsConnection> {\n\t\tawait this.applyAuthentication()\n\n\t\tthis.requestHeaders.set('Upgrade', 'websocket')\n\t\tthis.requestHeaders.set('Connection', 'Upgrade')\n\t\tthis.requestHeaders.set('Sec-WebSocket-Key', 'dGhlIHNhbXBsZSBub25jZQ==')\n\t\tthis.requestHeaders.set('Sec-WebSocket-Version', '13')\n\n\t\tconst url = new URL(this.path, 'http://localhost')\n\t\tconst request = new Request(url.toString(), {\n\t\t\theaders: this.requestHeaders,\n\t\t})\n\n\t\tconst response = await this.module.fetch(request)\n\n\t\texpect(\n\t\t\tresponse.status,\n\t\t\t`Expected status 101 (Switching Protocols), got ${response.status}`,\n\t\t).toBe(101)\n\n\t\tconst ws = (response as Response & { webSocket: WebSocket | null }).webSocket\n\t\tif (!ws) {\n\t\t\tthrow new Error('Response did not include a WebSocket connection')\n\t\t}\n\n\t\tws.accept()\n\n\t\treturn new TestWsConnection(ws)\n\t}\n\n\tprivate async applyAuthentication(): Promise<void> {\n\t\tif (!this.actingAsUser) return\n\n\t\tawait this.module.runInRequestScope(async () => {\n\t\t\tconst authService = this.module.get<AuthService>(AUTH_SERVICE)\n\t\t\tconst actingAs = new ActingAs(authService)\n\t\t\tconst authHeaders = this.actingAsUser ? await actingAs.createSessionForUser(this.actingAsUser) : new Headers()\n\n\t\t\tfor (const [key, value] of authHeaders.entries()) {\n\t\t\t\tthis.requestHeaders.set(key, value)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { ConnectionName, DatabaseService } from '@stratal/framework/database'\nimport { connectionSymbol } from '@stratal/framework/database'\nimport type { Application, Constructor, StratalEnv, StratalExecutionContext } from 'stratal'\nimport { DI_TOKENS, type Container } from 'stratal/di'\nimport { type InjectionToken } from 'stratal/module'\nimport { SEEDER_TOKENS, SeederNotRegisteredError, type Seeder, type SeederRegistry } from 'stratal/seeder'\nimport { STORAGE_TOKENS } from 'stratal/storage'\nimport { expect } from 'vitest'\nimport type { FakeStorageService } from '../storage'\nimport { TestHttpClient } from './http/test-http-client'\nimport { TestCommandRequest } from './quarry/test-command-request'\nimport { TestSseRequest } from './sse/test-sse-request'\nimport { TestWsRequest } from './ws/test-ws-request'\n\n/**\n * TestingModule\n *\n * Provides access to the test application, container, HTTP client, and utilities.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * modules: [RegistrationModule],\n * }).compile()\n *\n * // Make HTTP requests\n * const response = await module.http\n * .post('/api/v1/register')\n * .withBody({ ... })\n * .send()\n *\n * // Access services\n * const service = module.get(REGISTRATION_TOKENS.RegistrationService)\n *\n * // Database utilities\n * await module.truncateDb()\n * await module.seed(UserSeeder)\n * await module.assertDatabaseHas('user', { email: 'test@example.com' })\n *\n * // Cleanup\n * await module.close()\n * ```\n */\nexport class TestingModule {\n private _http: TestHttpClient | null = null\n private readonly _requestContainer: Container\n\n constructor(\n private readonly app: Application,\n private readonly env: StratalEnv,\n private readonly ctx: StratalExecutionContext,\n ) {\n const mockContext = this.app.createMockRouterContext()\n this._requestContainer = this.app.container.createRequestScope(mockContext)\n }\n\n /**\n * Resolve a service from the container\n */\n get<T>(token: InjectionToken<T>): T {\n return this._requestContainer.resolve(token)\n }\n\n /**\n * Get HTTP test client for making requests\n */\n get http(): TestHttpClient {\n this._http ??= new TestHttpClient(this)\n return this._http\n }\n\n\n /**\n * Get Inertia test client for making Inertia requests\n */\n get inertia(): TestHttpClient {\n return this.http.withHeaders({ 'X-Inertia': 'true', 'X-Inertia-Version': '1' })\n }\n\n /**\n * Get fake storage service for assertions\n */\n get storage(): FakeStorageService {\n return this.get<FakeStorageService>(STORAGE_TOKENS.StorageService)\n }\n\n /**\n * Create a WebSocket test request builder for the given path\n */\n ws(path: string): TestWsRequest {\n return new TestWsRequest(path, this)\n }\n\n /**\n * Create an SSE test request builder for the given path\n */\n sse(path: string): TestSseRequest {\n return new TestSseRequest(path, this)\n }\n\n /**\n * Create a Quarry command test request builder\n */\n quarry(name: string): TestCommandRequest {\n return new TestCommandRequest(name, this)\n }\n\n /**\n * Get Application instance\n */\n get application(): Application {\n return this.app\n }\n\n /**\n * Get DI Container (request-scoped)\n */\n get container(): Container {\n return this._requestContainer\n }\n\n /**\n * Execute an HTTP request through HonoApp\n */\n async fetch(request: Request): Promise<Response> {\n const hono = await this.app.ensureHono()\n return hono.fetch(request, this.env, this.ctx as ExecutionContext)\n }\n\n /**\n * Run callback in request scope (for DB operations, service access)\n */\n async runInRequestScope<T>(callback: (container: Container) => T | Promise<T>): Promise<T> {\n const mockContext = this.app.createMockRouterContext()\n return this.app.container.runInRequestScope(mockContext, callback)\n }\n\n /**\n * Get database service instance (resolved in request scope)\n */\n getDb(): DatabaseService\n getDb<K extends ConnectionName>(name: K): DatabaseService<K>\n getDb(name?: string): unknown {\n const token = name ? connectionSymbol(name) : DI_TOKENS.Database\n return this._requestContainer.resolve(token)\n }\n\n /**\n * Truncate all non-prisma tables in the database\n */\n async truncateDb(name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const tables = await db.$queryRaw<{ tablename: string }[]>`\n SELECT tablename::text as tablename FROM pg_tables\n WHERE schemaname = current_schema()\n AND tablename NOT LIKE '_prisma%'\n `\n if (tables.length === 0) return\n const tableList = tables.map((t) => `\"${t.tablename}\"`).join(', ')\n await db.$executeRawUnsafe(`TRUNCATE ${tableList} RESTART IDENTITY CASCADE`)\n }\n\n /**\n * Run seeders by class constructor in the request-scoped container\n */\n async seed(...SeederClasses: Constructor<Seeder>[]): Promise<void> {\n const registry = this._requestContainer.resolve<SeederRegistry>(SEEDER_TOKENS.SeederRegistry)\n for (const SeederClass of SeederClasses) {\n if (!registry.has(SeederClass)) {\n throw new SeederNotRegisteredError(SeederClass.name)\n }\n await registry.run(SeederClass, { container: this._requestContainer })\n }\n }\n\n /**\n * Assert that a record exists in the database\n */\n async assertDatabaseHas(table: string, data: Record<string, unknown>, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { findFirst: (opts: unknown) => Promise<unknown> }\n const result = await model.findFirst({ where: data })\n expect(result, `Expected ${table} with ${JSON.stringify(data)}`).not.toBeNull()\n }\n\n /**\n * Assert that a record does not exist in the database\n */\n async assertDatabaseMissing(table: string, data: Record<string, unknown>, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { findFirst: (opts: unknown) => Promise<unknown> }\n const result = await model.findFirst({ where: data })\n expect(result, `Expected ${table} NOT to have ${JSON.stringify(data)}`).toBeNull()\n }\n\n /**\n * Assert the number of records in a table\n */\n async assertDatabaseCount(table: string, expected: number, name?: ConnectionName): Promise<void> {\n const db = this.getDb(name!)\n const model = (db as unknown as Record<string, unknown>)[table] as { count: () => Promise<number> }\n const actual = await model.count()\n expect(actual, `Expected ${table} count ${expected}, got ${actual}`).toBe(expected)\n }\n\n /**\n * Cleanup - call in afterAll\n */\n async close(): Promise<void> {\n await this._requestContainer.dispose()\n await this.app.shutdown()\n }\n}\n","import {\n Application,\n type ApplicationConfig,\n type Constructor,\n type StratalEnv,\n type StratalExecutionContext,\n} from 'stratal'\nimport { type Container } from 'stratal/di'\nimport { LogLevel } from 'stratal/logger'\nimport { type InjectionToken, Module, type ModuleClass, type ModuleOptions } from 'stratal/module'\nimport { STORAGE_TOKENS } from 'stratal/storage'\nimport { FakeStorageService } from '../storage'\nimport { ProviderOverrideBuilder, type ProviderOverrideConfig } from './override'\nimport { Test } from './test'\nimport { TestingModule } from './testing-module'\n\n/**\n * Configuration for creating a testing module\n *\n * Extends ModuleOptions to support all module properties like NestJS.\n *\n * @example\n * ```typescript\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule, GeoModule],\n * providers: [{ provide: MOCK_TOKEN, useValue: mockValue }],\n * controllers: [TestController],\n * }).compile()\n * ```\n */\nexport interface TestingModuleConfig extends ModuleOptions {\n /** Optional environment overrides */\n env?: Partial<StratalEnv>\n /** Logging configuration. Defaults: level=ERROR, formatter='json' */\n logging?: ApplicationConfig['logging']\n}\n\n/**\n * Builder for creating test modules with provider overrides\n */\nexport class TestingModuleBuilder {\n private overrides: ProviderOverrideConfig<object>[] = []\n\n constructor(private config: TestingModuleConfig) { }\n\n /**\n * Override a provider with a custom implementation\n */\n overrideProvider<T>(token: InjectionToken<T>): ProviderOverrideBuilder<T> {\n return new ProviderOverrideBuilder(this, token)\n }\n\n /**\n * Add a provider override (internal use by ProviderOverrideBuilder)\n *\n * @internal\n */\n addProviderOverride<T>(override: ProviderOverrideConfig<T>): this {\n this.overrides.push(override as ProviderOverrideConfig<object>)\n return this\n }\n\n /**\n * Merge additional environment bindings\n */\n withEnv(env: Partial<StratalEnv>): this {\n this.config.env = { ...this.config.env, ...env }\n return this\n }\n\n private async getCloudflareWorkers() {\n try {\n return await import('cloudflare:workers')\n } catch {\n return null\n }\n }\n\n /**\n * Compile the testing module\n *\n * Creates the Application, applies overrides, initializes, and returns TestingModule.\n */\n async compile(): Promise<TestingModule> {\n const cf = await this.getCloudflareWorkers()\n\n const env = { ...cf?.env, ...this.config.env } as StratalEnv\n const ctx: StratalExecutionContext = {\n waitUntil: cf ? cf.waitUntil : (p) => {\n p.catch(() => {\n //\n })\n },\n }\n\n // Build root module from config\n const baseModules = Test.getBaseModules()\n const allImports = [...baseModules, ...(this.config.imports ?? [])]\n\n const rootModule = this.createTestRootModule({\n imports: allImports,\n providers: this.config.providers,\n controllers: this.config.controllers,\n consumers: this.config.consumers,\n jobs: this.config.jobs,\n })\n\n const app = new Application({\n module: rootModule,\n logging: {\n level: this.config.logging?.level ?? LogLevel.ERROR,\n formatter: this.config.logging?.formatter ?? 'pretty',\n },\n env,\n ctx,\n })\n\n await app.initialize()\n\n // Auto-register FakeStorageService after initialize so it replaces module-registered StorageService\n app.container.registerSingleton(STORAGE_TOKENS.StorageService, FakeStorageService)\n\n // Apply user overrides AFTER initialize so they replace module-registered providers\n for (const override of this.overrides) {\n switch (override.type) {\n case 'value':\n app.container.registerValue(override.token, override.implementation)\n break\n case 'class':\n app.container.registerSingleton(\n override.token,\n override.implementation as Constructor\n )\n break\n case 'factory':\n app.container.registerFactory(\n override.token,\n override.implementation as (c: Container) => object\n )\n break\n case 'existing':\n app.container.registerExisting(\n override.token,\n override.implementation as InjectionToken<object>\n )\n break\n }\n }\n\n return new TestingModule(app, env, ctx)\n }\n\n /**\n * Create a test root module with the given options\n */\n private createTestRootModule(options: ModuleOptions): ModuleClass {\n @Module(options)\n class TestRootModule { }\n return TestRootModule\n }\n}\n","import { type DynamicModule, type ModuleClass } from 'stratal/module'\nimport { TestingModuleBuilder, type TestingModuleConfig } from './testing-module-builder'\n\n/**\n * Test\n *\n * Static class for creating testing modules.\n * Provides a NestJS-style API for configuring test modules.\n *\n * @example\n * ```typescript\n * // In vitest.setup.ts:\n * Test.setBaseModules([CoreModule])\n *\n * // In test files:\n * const module = await Test.createTestingModule({\n * imports: [RegistrationModule, GeoModule],\n * })\n * .overrideProvider(EMAIL_TOKENS.EmailService)\n * .useValue(mockEmailService)\n * .compile()\n * ```\n */\nexport class Test {\n /**\n * Base modules to include in all test modules\n * Set once in vitest.setup.ts\n */\n private static baseModules: (ModuleClass | DynamicModule)[] = []\n\n /**\n * Set base modules to include in all test modules\n * Should be called once in vitest.setup.ts\n *\n * @param modules - Modules to include before test-specific modules (e.g., CoreModule)\n */\n static setBaseModules(modules: (ModuleClass | DynamicModule)[]): void {\n this.baseModules = modules\n }\n\n /**\n * Get base modules\n */\n static getBaseModules(): (ModuleClass | DynamicModule)[] {\n return this.baseModules\n }\n\n /**\n * Create a testing module builder\n *\n * @param config - Configuration with modules and optional env overrides\n * @returns TestingModuleBuilder for configuring and compiling the module\n */\n static createTestingModule(config: TestingModuleConfig): TestingModuleBuilder {\n return new TestingModuleBuilder(config)\n }\n}\n","import { http, HttpResponse, type RequestHandler } from 'msw'\nimport { setupServer, type SetupServer } from 'msw/node'\nimport type { MockErrorOptions, MockJsonOptions } from './fetch-mock.types'\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options'\n\n/**\n * MSW-based fetch mock for declarative HTTP mocking in tests.\n *\n * Replaces the old Cloudflare `fetchMock` (undici MockAgent) with MSW's `setupServer`.\n * Works in both Node.js and workerd test environments.\n *\n * @example\n * ```typescript\n * import { createMockFetch } from '@stratal/testing'\n *\n * const mock = createMockFetch()\n *\n * beforeAll(() => mock.listen())\n * afterEach(() => mock.reset())\n * afterAll(() => mock.close())\n *\n * it('should mock external API', async () => {\n * mock.mockJsonResponse('https://api.example.com/data', { success: true })\n *\n * const response = await fetch('https://api.example.com/data')\n * const json = await response.json()\n *\n * expect(json.success).toBe(true)\n * })\n * ```\n */\nexport class MockFetch {\n private server: SetupServer\n\n constructor(handlers: RequestHandler[] = []) {\n this.server = setupServer(...handlers)\n }\n\n /** Start intercepting. Call in beforeAll/beforeEach. */\n listen() {\n this.server.listen({ onUnhandledRequest: 'error' })\n }\n\n /** Reset runtime handlers. Call in afterEach. */\n reset() {\n this.server.resetHandlers()\n }\n\n /** Stop intercepting. Call in afterAll. */\n close() {\n this.server.close()\n }\n\n /** Add runtime handler(s) for a single test. */\n use(...handlers: RequestHandler[]) {\n this.server.use(...handlers)\n }\n\n /**\n * Mock a JSON response.\n *\n * @param url - Full URL to mock (e.g., 'https://api.example.com/users')\n * @param data - JSON data to return\n * @param options - HTTP method, status code, headers\n *\n * @example\n * ```typescript\n * mock.mockJsonResponse('https://api.example.com/users', { users: [] })\n * mock.mockJsonResponse('https://api.example.com/users', { created: true }, { method: 'POST', status: 201 })\n * ```\n */\n mockJsonResponse(url: string, data: Record<string, unknown> | unknown[], options: MockJsonOptions = {}) {\n const method = (options.method ?? 'GET').toLowerCase() as HttpMethod\n const handler = http[method](url, () =>\n HttpResponse.json(data, {\n status: options.status ?? 200,\n headers: options.headers,\n }),\n )\n this.server.use(handler)\n }\n\n /**\n * Mock an error response.\n *\n * @param url - Full URL to mock\n * @param status - HTTP error status code\n * @param message - Optional error message\n * @param options - HTTP method, headers\n *\n * @example\n * ```typescript\n * mock.mockError('https://api.example.com/fail', 401, 'Unauthorized')\n * mock.mockError('https://api.example.com/fail', 500, 'Server Error', { method: 'POST' })\n * ```\n */\n mockError(url: string, status: number, message?: string, options: MockErrorOptions = {}) {\n const method = (options.method ?? 'GET').toLowerCase() as HttpMethod\n const body = message ? { error: message } : undefined\n this.server.use(\n http[method](url, () =>\n HttpResponse.json(body, { status, headers: options.headers }),\n ),\n )\n }\n}\n\n/**\n * Factory function to create a new MockFetch instance\n *\n * @param handlers - Optional initial MSW request handlers\n * @returns A new MockFetch instance\n *\n * @example\n * ```typescript\n * import { createMockFetch } from '@stratal/testing'\n *\n * const mock = createMockFetch()\n *\n * beforeAll(() => mock.listen())\n * afterEach(() => mock.reset())\n * afterAll(() => mock.close())\n * ```\n */\nexport function createMockFetch(handlers?: RequestHandler[]): MockFetch {\n return new MockFetch(handlers)\n}\n","/**\n * Base error class for all test framework errors.\n * Extends from Error and allows easy identification via `instanceof`.\n */\nexport class TestError extends Error {\n constructor(\n message: string,\n public readonly cause?: Error\n ) {\n super(message)\n this.name = 'TestError'\n\n // Maintain proper stack trace\n Error.captureStackTrace(this, this.constructor)\n }\n}\n","import { TestError } from './test-error'\n\n/**\n * Error thrown when test setup fails.\n * Examples: schema creation failure, migration failure, application bootstrap failure.\n */\nexport class TestSetupError extends TestError {\n constructor(message: string, cause?: Error) {\n super(`Test setup failed: ${message}`, cause)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,0BAAb,MAAwC;CACtC,YACE,QACA,OACA;AAFiB,OAAA,SAAA;AACA,OAAA,QAAA;;;;;;;;;;CAWnB,SAAS,OAAgC;AACvC,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;;CAWJ,SAAS,KAA0D;AACjE,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;;CAWJ,WAAW,SAA4D;AACrE,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;;;;;;;;;;;;CAqBJ,YAAY,eAAwD;AAClE,SAAO,KAAK,OAAO,oBAAoB;GACrC,OAAO,KAAK;GACZ,MAAM;GACN,gBAAgB;GACjB,CAAC;;;;;;;;;ACjGN,SAAgB,sBAAsB,QAA0C;AAC9E,KAAI;EAEF,MAAM,YADU,OAAO,IAAuB,YAAY,QACjC,CAAC;AAC1B,MAAI,aAAa,cAAc,aAAa,UAAU,SACpD,QAAO,UAAU;AAEnB,SAAO;SACD;AACN,SAAO;;;;;;AAOX,SAAgB,qBACd,SACA,QACA,UACM;AACN,SAAQ,UAAR;EACE,KAAK;AACH,WAAQ,IAAI,UAAU,UAA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hC,IAAa,YAAb,cAA+B,MAAM;CACnC,YACE,SACA,OACA;AACA,QAAM,QAAQ;AAFE,OAAA,QAAA;AAGhB,OAAK,OAAO;AAGZ,QAAM,kBAAkB,MAAM,KAAK,YAAY;;;;;;;;;ACPnD,IAAa,iBAAb,cAAoC,UAAU;CAC5C,YAAY,SAAiB,OAAe;AAC1C,QAAM,sBAAsB,WAAW,MAAM"}
|
package/dist/storage/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as FakeStorageService } from "../storage-
|
|
1
|
+
import { t as FakeStorageService } from "../storage-DZbrPg-l.mjs";
|
|
2
2
|
export { FakeStorageService };
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { FileNotFoundError, STORAGE_TOKENS, StorageService } from "stratal/storage";
|
|
2
2
|
import { Transient, inject } from "stratal/di";
|
|
3
3
|
import { expect } from "vitest";
|
|
4
|
-
//#region \0@oxc-project+runtime@0.
|
|
4
|
+
//#region \0@oxc-project+runtime@0.127.0/helpers/decorateMetadata.js
|
|
5
5
|
function __decorateMetadata(k, v) {
|
|
6
6
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
7
7
|
}
|
|
8
8
|
//#endregion
|
|
9
|
-
//#region \0@oxc-project+runtime@0.
|
|
9
|
+
//#region \0@oxc-project+runtime@0.127.0/helpers/decorateParam.js
|
|
10
10
|
function __decorateParam(paramIndex, decorator) {
|
|
11
11
|
return function(target, key) {
|
|
12
12
|
decorator(target, key, paramIndex);
|
|
13
13
|
};
|
|
14
14
|
}
|
|
15
15
|
//#endregion
|
|
16
|
-
//#region \0@oxc-project+runtime@0.
|
|
16
|
+
//#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
|
|
17
17
|
function __decorate(decorators, target, key, desc) {
|
|
18
18
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
19
19
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -202,4 +202,4 @@ FakeStorageService = __decorate([
|
|
|
202
202
|
//#endregion
|
|
203
203
|
export { __decorate as n, FakeStorageService as t };
|
|
204
204
|
|
|
205
|
-
//# sourceMappingURL=storage-
|
|
205
|
+
//# sourceMappingURL=storage-DZbrPg-l.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage-CGRm_2Nh.mjs","names":[],"sources":["../src/storage/fake-storage.service.ts"],"sourcesContent":["import { Transient, inject } from 'stratal/di'\nimport {\n FileNotFoundError,\n STORAGE_TOKENS,\n type StorageManagerService,\n StorageService,\n type StreamingBlobPayloadInputTypes,\n type DownloadResult,\n type PresignedUrlResult,\n type StorageConfig,\n type UploadOptions,\n type UploadResult,\n} from 'stratal/storage'\nimport { expect } from 'vitest'\n\n/**\n * Stored file representation in memory\n */\nexport interface StoredFile {\n content: Uint8Array\n mimeType: string\n size: number\n metadata?: Record<string, string>\n uploadedAt: Date\n}\n\n/**\n * FakeStorageService\n *\n * In-memory storage implementation for testing.\n * Registered by default in TestingModuleBuilder.\n *\n * Similar to Laravel's Storage::fake() - stores files in memory\n * and provides assertion helpers for testing.\n *\n * @example\n * ```typescript\n * // Access via TestingModule\n * module.storage.assertExists('path/to/file.pdf')\n * module.storage.assertMissing('deleted/file.pdf')\n * module.storage.clear() // Reset between tests\n * ```\n */\n@Transient(STORAGE_TOKENS.StorageService)\nexport class FakeStorageService extends StorageService {\n private files = new Map<string, StoredFile>()\n\n constructor(\n @inject(STORAGE_TOKENS.StorageManager)\n protected readonly storageManager: StorageManagerService,\n @inject(STORAGE_TOKENS.Options)\n protected readonly options: StorageConfig\n ) {\n super(storageManager, options)\n }\n\n /**\n * Upload content to fake storage\n */\n async upload(\n body: StreamingBlobPayloadInputTypes,\n relativePath: string,\n options: UploadOptions,\n disk?: string\n ): Promise<UploadResult> {\n const content = await this.bodyToUint8Array(body)\n const diskName = this.resolveDisk(disk)\n\n this.files.set(relativePath, {\n content,\n mimeType: options.mimeType ?? 'application/octet-stream',\n size: options.size,\n metadata: options.metadata,\n uploadedAt: new Date(),\n })\n\n return {\n path: relativePath,\n disk: diskName,\n fullPath: relativePath,\n size: options.size,\n mimeType: options.mimeType ?? 'application/octet-stream',\n uploadedAt: new Date(),\n }\n }\n\n /**\n * Download a file from fake storage\n */\n download(path: string): Promise<DownloadResult> {\n const file = this.files.get(path)\n\n if (!file) {\n return Promise.reject(new FileNotFoundError(path))\n }\n\n return Promise.resolve({\n toStream: () => new ReadableStream({\n start(controller) {\n controller.enqueue(file.content)\n controller.close()\n },\n }),\n toString: () => Promise.resolve(new TextDecoder().decode(file.content)),\n toArrayBuffer: () => Promise.resolve(file.content),\n contentType: file.mimeType,\n size: file.size,\n metadata: file.metadata,\n })\n }\n\n /**\n * Delete a file from fake storage\n */\n delete(path: string): Promise<void> {\n this.files.delete(path)\n return Promise.resolve()\n }\n\n /**\n * Check if a file exists in fake storage\n */\n exists(path: string): Promise<boolean> {\n return Promise.resolve(this.files.has(path))\n }\n\n /**\n * Generate a fake presigned download URL\n */\n getPresignedDownloadUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'GET', expiresIn))\n }\n\n /**\n * Generate a fake presigned upload URL\n */\n getPresignedUploadUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'PUT', expiresIn))\n }\n\n /**\n * Generate a fake presigned delete URL\n */\n getPresignedDeleteUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'DELETE', expiresIn))\n }\n\n /**\n * Chunked upload (same as regular upload for fake)\n */\n async chunkedUpload(\n body: StreamingBlobPayloadInputTypes,\n path: string,\n options: Omit<UploadOptions, 'size'> & { size?: number },\n disk?: string\n ): Promise<UploadResult> {\n const content = await this.bodyToUint8Array(body)\n const size = options.size ?? content.length\n\n return this.upload(body, path, { ...options, size }, disk)\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Test Assertion Helpers\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Assert that a file exists at the given path\n *\n * @param path - Path to check\n * @throws AssertionError if file does not exist\n */\n assertExists(path: string): void {\n expect(\n this.files.has(path),\n `Expected file to exist at: ${path}\\nStored files: ${this.getStoredPaths().join(', ') || '(none)'}`\n ).toBe(true)\n }\n\n /**\n * Assert that a file does NOT exist at the given path\n *\n * @param path - Path to check\n * @throws AssertionError if file exists\n */\n assertMissing(path: string): void {\n expect(\n this.files.has(path),\n `Expected file NOT to exist at: ${path}`\n ).toBe(false)\n }\n\n /**\n * Assert storage is empty\n *\n * @throws AssertionError if any files exist\n */\n assertEmpty(): void {\n expect(\n this.files.size,\n `Expected storage to be empty but found ${this.files.size} files: ${this.getStoredPaths().join(', ')}`\n ).toBe(0)\n }\n\n /**\n * Assert storage has exactly N files\n *\n * @param count - Expected number of files\n * @throws AssertionError if count doesn't match\n */\n assertCount(count: number): void {\n expect(\n this.files.size,\n `Expected ${count} files in storage but found ${this.files.size}`\n ).toBe(count)\n }\n\n /**\n * Get all stored files (for inspection)\n */\n getStoredFiles(): Map<string, StoredFile> {\n return new Map(this.files)\n }\n\n /**\n * Get all stored file paths\n */\n getStoredPaths(): string[] {\n return Array.from(this.files.keys())\n }\n\n /**\n * Get a specific file by path\n */\n getFile(path: string): StoredFile | undefined {\n return this.files.get(path)\n }\n\n /**\n * Clear all stored files (call in beforeEach for test isolation)\n */\n clear(): void {\n this.files.clear()\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Helpers\n // ─────────────────────────────────────────────────────────────────────────\n\n private createPresignedUrl(\n path: string,\n method: 'GET' | 'PUT' | 'DELETE' | 'HEAD',\n expiresIn = 300\n ): PresignedUrlResult {\n const expiresAt = new Date(Date.now() + expiresIn * 1000)\n\n return {\n url: `https://fake-storage.test/${path}?method=${method}&expires=${expiresAt.toISOString()}`,\n expiresIn,\n expiresAt,\n method,\n }\n }\n\n private async bodyToUint8Array(body: StreamingBlobPayloadInputTypes | null | undefined): Promise<Uint8Array> {\n if (!body) {\n return new Uint8Array(0)\n }\n\n if (body instanceof Uint8Array) {\n return body\n }\n\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body)\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body)\n }\n\n if (body instanceof Blob) {\n const buffer = await body.arrayBuffer()\n return new Uint8Array(buffer)\n }\n\n if (body instanceof ReadableStream) {\n return new Uint8Array(await new Response(body).arrayBuffer())\n }\n\n // FormData or URLSearchParams - convert via Response\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return new Uint8Array(await new Response(body).arrayBuffer())\n }\n\n return new Uint8Array(0)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4CO,IAAA,qBAAA,MAAM,2BAA2B,eAAe;CACrD,wBAAgB,IAAI,KAAyB;CAE7C,YACE,gBAEA,SAEA;AACA,QAAM,gBAAgB,QAAQ;AAJX,OAAA,iBAAA;AAEA,OAAA,UAAA;;;;;CAQrB,MAAM,OACJ,MACA,cACA,SACA,MACuB;EACvB,MAAM,UAAU,MAAM,KAAK,iBAAiB,KAAK;EACjD,MAAM,WAAW,KAAK,YAAY,KAAK;AAEvC,OAAK,MAAM,IAAI,cAAc;GAC3B;GACA,UAAU,QAAQ,YAAY;GAC9B,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,4BAAY,IAAI,MAAM;GACvB,CAAC;AAEF,SAAO;GACL,MAAM;GACN,MAAM;GACN,UAAU;GACV,MAAM,QAAQ;GACd,UAAU,QAAQ,YAAY;GAC9B,4BAAY,IAAI,MAAM;GACvB;;;;;CAMH,SAAS,MAAuC;EAC9C,MAAM,OAAO,KAAK,MAAM,IAAI,KAAK;AAEjC,MAAI,CAAC,KACH,QAAO,QAAQ,OAAO,IAAI,kBAAkB,KAAK,CAAC;AAGp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AKpC,OAAO,eAAe,eAAe,CAAA;oBAErC,OAAO,eAAe,QAAQ,CAAA"}
|
|
1
|
+
{"version":3,"file":"storage-DZbrPg-l.mjs","names":[],"sources":["../src/storage/fake-storage.service.ts"],"sourcesContent":["import { Transient, inject } from 'stratal/di'\nimport {\n FileNotFoundError,\n STORAGE_TOKENS,\n type StorageManagerService,\n StorageService,\n type StreamingBlobPayloadInputTypes,\n type DownloadResult,\n type PresignedUrlResult,\n type StorageConfig,\n type UploadOptions,\n type UploadResult,\n} from 'stratal/storage'\nimport { expect } from 'vitest'\n\n/**\n * Stored file representation in memory\n */\nexport interface StoredFile {\n content: Uint8Array\n mimeType: string\n size: number\n metadata?: Record<string, string>\n uploadedAt: Date\n}\n\n/**\n * FakeStorageService\n *\n * In-memory storage implementation for testing.\n * Registered by default in TestingModuleBuilder.\n *\n * Similar to Laravel's Storage::fake() - stores files in memory\n * and provides assertion helpers for testing.\n *\n * @example\n * ```typescript\n * // Access via TestingModule\n * module.storage.assertExists('path/to/file.pdf')\n * module.storage.assertMissing('deleted/file.pdf')\n * module.storage.clear() // Reset between tests\n * ```\n */\n@Transient(STORAGE_TOKENS.StorageService)\nexport class FakeStorageService extends StorageService {\n private files = new Map<string, StoredFile>()\n\n constructor(\n @inject(STORAGE_TOKENS.StorageManager)\n protected readonly storageManager: StorageManagerService,\n @inject(STORAGE_TOKENS.Options)\n protected readonly options: StorageConfig\n ) {\n super(storageManager, options)\n }\n\n /**\n * Upload content to fake storage\n */\n async upload(\n body: StreamingBlobPayloadInputTypes,\n relativePath: string,\n options: UploadOptions,\n disk?: string\n ): Promise<UploadResult> {\n const content = await this.bodyToUint8Array(body)\n const diskName = this.resolveDisk(disk)\n\n this.files.set(relativePath, {\n content,\n mimeType: options.mimeType ?? 'application/octet-stream',\n size: options.size,\n metadata: options.metadata,\n uploadedAt: new Date(),\n })\n\n return {\n path: relativePath,\n disk: diskName,\n fullPath: relativePath,\n size: options.size,\n mimeType: options.mimeType ?? 'application/octet-stream',\n uploadedAt: new Date(),\n }\n }\n\n /**\n * Download a file from fake storage\n */\n download(path: string): Promise<DownloadResult> {\n const file = this.files.get(path)\n\n if (!file) {\n return Promise.reject(new FileNotFoundError(path))\n }\n\n return Promise.resolve({\n toStream: () => new ReadableStream({\n start(controller) {\n controller.enqueue(file.content)\n controller.close()\n },\n }),\n toString: () => Promise.resolve(new TextDecoder().decode(file.content)),\n toArrayBuffer: () => Promise.resolve(file.content),\n contentType: file.mimeType,\n size: file.size,\n metadata: file.metadata,\n })\n }\n\n /**\n * Delete a file from fake storage\n */\n delete(path: string): Promise<void> {\n this.files.delete(path)\n return Promise.resolve()\n }\n\n /**\n * Check if a file exists in fake storage\n */\n exists(path: string): Promise<boolean> {\n return Promise.resolve(this.files.has(path))\n }\n\n /**\n * Generate a fake presigned download URL\n */\n getPresignedDownloadUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'GET', expiresIn))\n }\n\n /**\n * Generate a fake presigned upload URL\n */\n getPresignedUploadUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'PUT', expiresIn))\n }\n\n /**\n * Generate a fake presigned delete URL\n */\n getPresignedDeleteUrl(\n path: string,\n expiresIn?: number\n ): Promise<PresignedUrlResult> {\n return Promise.resolve(this.createPresignedUrl(path, 'DELETE', expiresIn))\n }\n\n /**\n * Chunked upload (same as regular upload for fake)\n */\n async chunkedUpload(\n body: StreamingBlobPayloadInputTypes,\n path: string,\n options: Omit<UploadOptions, 'size'> & { size?: number },\n disk?: string\n ): Promise<UploadResult> {\n const content = await this.bodyToUint8Array(body)\n const size = options.size ?? content.length\n\n return this.upload(body, path, { ...options, size }, disk)\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Test Assertion Helpers\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Assert that a file exists at the given path\n *\n * @param path - Path to check\n * @throws AssertionError if file does not exist\n */\n assertExists(path: string): void {\n expect(\n this.files.has(path),\n `Expected file to exist at: ${path}\\nStored files: ${this.getStoredPaths().join(', ') || '(none)'}`\n ).toBe(true)\n }\n\n /**\n * Assert that a file does NOT exist at the given path\n *\n * @param path - Path to check\n * @throws AssertionError if file exists\n */\n assertMissing(path: string): void {\n expect(\n this.files.has(path),\n `Expected file NOT to exist at: ${path}`\n ).toBe(false)\n }\n\n /**\n * Assert storage is empty\n *\n * @throws AssertionError if any files exist\n */\n assertEmpty(): void {\n expect(\n this.files.size,\n `Expected storage to be empty but found ${this.files.size} files: ${this.getStoredPaths().join(', ')}`\n ).toBe(0)\n }\n\n /**\n * Assert storage has exactly N files\n *\n * @param count - Expected number of files\n * @throws AssertionError if count doesn't match\n */\n assertCount(count: number): void {\n expect(\n this.files.size,\n `Expected ${count} files in storage but found ${this.files.size}`\n ).toBe(count)\n }\n\n /**\n * Get all stored files (for inspection)\n */\n getStoredFiles(): Map<string, StoredFile> {\n return new Map(this.files)\n }\n\n /**\n * Get all stored file paths\n */\n getStoredPaths(): string[] {\n return Array.from(this.files.keys())\n }\n\n /**\n * Get a specific file by path\n */\n getFile(path: string): StoredFile | undefined {\n return this.files.get(path)\n }\n\n /**\n * Clear all stored files (call in beforeEach for test isolation)\n */\n clear(): void {\n this.files.clear()\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Private Helpers\n // ─────────────────────────────────────────────────────────────────────────\n\n private createPresignedUrl(\n path: string,\n method: 'GET' | 'PUT' | 'DELETE' | 'HEAD',\n expiresIn = 300\n ): PresignedUrlResult {\n const expiresAt = new Date(Date.now() + expiresIn * 1000)\n\n return {\n url: `https://fake-storage.test/${path}?method=${method}&expires=${expiresAt.toISOString()}`,\n expiresIn,\n expiresAt,\n method,\n }\n }\n\n private async bodyToUint8Array(body: StreamingBlobPayloadInputTypes | null | undefined): Promise<Uint8Array> {\n if (!body) {\n return new Uint8Array(0)\n }\n\n if (body instanceof Uint8Array) {\n return body\n }\n\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body)\n }\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body)\n }\n\n if (body instanceof Blob) {\n const buffer = await body.arrayBuffer()\n return new Uint8Array(buffer)\n }\n\n if (body instanceof ReadableStream) {\n return new Uint8Array(await new Response(body).arrayBuffer())\n }\n\n // FormData or URLSearchParams - convert via Response\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return new Uint8Array(await new Response(body).arrayBuffer())\n }\n\n return new Uint8Array(0)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4CO,IAAA,qBAAA,MAAM,2BAA2B,eAAe;CACrD,wBAAgB,IAAI,KAAyB;CAE7C,YACE,gBAEA,SAEA;AACA,QAAM,gBAAgB,QAAQ;AAJX,OAAA,iBAAA;AAEA,OAAA,UAAA;;;;;CAQrB,MAAM,OACJ,MACA,cACA,SACA,MACuB;EACvB,MAAM,UAAU,MAAM,KAAK,iBAAiB,KAAK;EACjD,MAAM,WAAW,KAAK,YAAY,KAAK;AAEvC,OAAK,MAAM,IAAI,cAAc;GAC3B;GACA,UAAU,QAAQ,YAAY;GAC9B,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB,4BAAY,IAAI,MAAM;GACvB,CAAC;AAEF,SAAO;GACL,MAAM;GACN,MAAM;GACN,UAAU;GACV,MAAM,QAAQ;GACd,UAAU,QAAQ,YAAY;GAC9B,4BAAY,IAAI,MAAM;GACvB;;;;;CAMH,SAAS,MAAuC;EAC9C,MAAM,OAAO,KAAK,MAAM,IAAI,KAAK;AAEjC,MAAI,CAAC,KACH,QAAO,QAAQ,OAAO,IAAI,kBAAkB,KAAK,CAAC;AAGpD,SAAO,QAAQ,QAAQ;GACrB,gBAAgB,IAAI,eAAe,EACjC,MAAM,YAAY;AAChB,eAAW,QAAQ,KAAK,QAAQ;AAChC,eAAW,OAAO;MAErB,CAAC;GACF,gBAAgB,QAAQ,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,QA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0.19",
|
|
4
4
|
"description": "Testing utilities and mocks for Stratal framework applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -66,15 +66,15 @@
|
|
|
66
66
|
"lint:fix": "npx oxlint --fix ."
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@cloudflare/vitest-pool-workers": "^0.
|
|
69
|
+
"@cloudflare/vitest-pool-workers": "^0.15.0",
|
|
70
70
|
"@golevelup/ts-vitest": "^4.0.0",
|
|
71
|
-
"msw": "^2.
|
|
71
|
+
"msw": "^2.13.6"
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
|
-
"@stratal/framework": "^0.0.
|
|
74
|
+
"@stratal/framework": "^0.0.19",
|
|
75
75
|
"better-auth": "^1.4.9",
|
|
76
76
|
"reflect-metadata": "^0.2.2",
|
|
77
|
-
"stratal": "^0.0.
|
|
77
|
+
"stratal": "^0.0.19",
|
|
78
78
|
"vitest": "^4.1.0"
|
|
79
79
|
},
|
|
80
80
|
"peerDependenciesMeta": {
|
|
@@ -86,16 +86,16 @@
|
|
|
86
86
|
}
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"@cloudflare/workers-types": "4.
|
|
89
|
+
"@cloudflare/workers-types": "4.20260426.1",
|
|
90
90
|
"@stratal/framework": "workspace:*",
|
|
91
|
-
"@types/node": "^25.
|
|
92
|
-
"@vitest/runner": "~4.1.
|
|
93
|
-
"@vitest/snapshot": "~4.1.
|
|
94
|
-
"better-auth": "^1.
|
|
91
|
+
"@types/node": "^25.6.0",
|
|
92
|
+
"@vitest/runner": "~4.1.5",
|
|
93
|
+
"@vitest/snapshot": "~4.1.5",
|
|
94
|
+
"better-auth": "^1.6.9",
|
|
95
95
|
"reflect-metadata": "^0.2.2",
|
|
96
96
|
"stratal": "workspace:*",
|
|
97
|
-
"tsdown": "^0.21.
|
|
98
|
-
"typescript": "^6.0.
|
|
99
|
-
"vitest": "~4.1.
|
|
97
|
+
"tsdown": "^0.21.10",
|
|
98
|
+
"typescript": "^6.0.3",
|
|
99
|
+
"vitest": "~4.1.5"
|
|
100
100
|
}
|
|
101
101
|
}
|