@geekmidas/constructs 10.0.0-alpha.21 → 10.0.0-alpha.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -23
- package/dist/{Endpoint-DbYQJgb-.d.cts → Endpoint-CrhoafsT.d.cts} +2 -2
- package/dist/{Endpoint-BxkRWQ8G.d.mts.map → Endpoint-CrhoafsT.d.cts.map} +1 -1
- package/dist/{Endpoint-BxkRWQ8G.d.mts → Endpoint-pTZrMs_h.d.mts} +2 -2
- package/dist/{Endpoint-DbYQJgb-.d.cts.map → Endpoint-pTZrMs_h.d.mts.map} +1 -1
- package/dist/{EndpointFactory-T06kTFHg.d.mts → EndpointFactory-BSLH4hSU.d.mts} +2 -2
- package/dist/{EndpointFactory-DE6nKtFZ.d.cts.map → EndpointFactory-BSLH4hSU.d.mts.map} +1 -1
- package/dist/{EndpointFactory-DE6nKtFZ.d.cts → EndpointFactory-CiCzFdMx.d.cts} +2 -2
- package/dist/{EndpointFactory-T06kTFHg.d.mts.map → EndpointFactory-CiCzFdMx.d.cts.map} +1 -1
- package/dist/Queue-BB2-DgqJ.cjs +123 -0
- package/dist/Queue-BB2-DgqJ.cjs.map +1 -0
- package/dist/Queue-Dfumm1WR.mjs +118 -0
- package/dist/Queue-Dfumm1WR.mjs.map +1 -0
- package/dist/Topic-BaNCgP61.cjs +107 -0
- package/dist/Topic-BaNCgP61.cjs.map +1 -0
- package/dist/Topic-QqnO_6Dl.mjs +102 -0
- package/dist/Topic-QqnO_6Dl.mjs.map +1 -0
- package/dist/adaptors/aws.d.cts +1 -1
- package/dist/adaptors/aws.d.mts +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/testing.cjs +136 -32
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +101 -13
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +101 -13
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +133 -33
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/{auth-BlO8MUkR.d.cts → auth-BR2eYxIW.d.cts} +16 -1
- package/dist/{auth-BlO8MUkR.d.cts.map → auth-BR2eYxIW.d.cts.map} +1 -1
- package/dist/{auth-CHWIdcQO.d.mts → auth-DtprqoJP.d.mts} +16 -1
- package/dist/{auth-CHWIdcQO.d.mts.map → auth-DtprqoJP.d.mts.map} +1 -1
- package/dist/auth.cjs +28 -6
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.mts +1 -1
- package/dist/auth.mjs +28 -6
- package/dist/auth.mjs.map +1 -1
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/queue/index.cjs +3 -116
- package/dist/queue/index.cjs.map +1 -1
- package/dist/queue/index.mjs +1 -114
- package/dist/queue/index.mjs.map +1 -1
- package/dist/rest-api.d.cts +2 -2
- package/dist/rest-api.d.mts +2 -2
- package/dist/topic/index.cjs +3 -100
- package/dist/topic/index.cjs.map +1 -1
- package/dist/topic/index.mjs +1 -98
- package/dist/topic/index.mjs.map +1 -1
- package/package.json +31 -31
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","names":["EnvironmentParser","ServiceDiscovery","http","TEST_CONTEXT_HEADER","Hono","ServiceDiscovery","EnvironmentParser","createObjectHeaders","createCookieHeaderAccessor","runWithRequestContext","ForbiddenError","DefaultAuditor","executeWithAuditTransaction","ResponseBuilder","Endpoint","publishConstructEvents","ServiceDiscovery","EnvironmentParser","FunctionBuilder","DefaultAuditor","runWithRequestContext","publishEvents","ServiceDiscovery","EnvironmentParser","runWithRequestContext","ServiceDiscovery","EnvironmentParser","runWithRequestContext","publishEvents","EnvironmentParser","TestBrowser","setupServer","provideKey","createMailbox","installContextFetch","randomUUID","TransactionRegistry","ServiceDiscovery","runInTestContext","test","Endpoint","KyselyDatabase","BetterAuth","Email","currentTestContext","http","hono","Hono","serviceContext","testContextOf","runAsServer"],"sources":["../../src/endpoints/MswEndpointAdaptor.ts","../../src/endpoints/TestEndpointAdaptor.ts","../../src/functions/TestFunctionAdaptor.ts","../../src/queue/TestQueueAdaptor.ts","../../src/subscribers/TestSubscriberAdaptor.ts","../../src/testing/featureTest.ts"],"sourcesContent":["import { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Service } from '@geekmidas/services';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport { TEST_CONTEXT_HEADER } from '@geekmidas/testkit/context';\nimport { Hono } from 'hono';\nimport { type HttpHandler, http } from 'msw';\nimport type { Endpoint } from './Endpoint';\nimport { HonoEndpoint } from './HonoEndpointAdaptor';\n\n/**\n * Header used to identify which test context a request belongs to — defined\n * once, in testkit, where the stamped `fetch` that writes it lives.\n */\nexport { TEST_CONTEXT_HEADER };\n\n/**\n * Per-test context containing an isolated ServiceDiscovery instance.\n * Registered in the context map and looked up per-request via the context ID header.\n */\nexport interface MswTestContext {\n\tserviceDiscovery: ServiceDiscovery<any>;\n}\n\n/**\n * Options for creating MSW handlers from endpoint constructs.\n *\n * @example\n * ```typescript\n * import { createMswHandlers, registerTestContext } from '@geekmidas/constructs/testing';\n * import { setupServer } from 'msw/node';\n *\n * // Create handlers once (global)\n * const { handlers, registerContext, removeContext } = createMswHandlers(\n * [getUsers, createUser],\n * { baseURL: 'http://localhost:3000' },\n * );\n * const server = setupServer(...handlers);\n *\n * // Per test: register an isolated context with its own services/transaction\n * it('should list users', async ({ db }) => {\n * const contextId = crypto.randomUUID();\n * registerContext(contextId, {\n * services: { database: db, auth: mockAuth },\n * });\n *\n * const api = createApi({\n * baseURL: 'http://localhost:3000',\n * headers: { [TEST_CONTEXT_HEADER]: contextId },\n * });\n *\n * const result = await api('GET /users');\n * expect(result).toBeDefined();\n *\n * removeContext(contextId);\n * });\n * ```\n */\nexport interface CreateMswHandlersOptions {\n\t/** Base URL the client fetches from (e.g., 'http://localhost:3000') */\n\tbaseURL: string;\n}\n\n/**\n * Options for registering a per-test context.\n * Follows the same pattern as TestRequestAdaptor — services, database,\n * publisher, and auditorStorage are provided explicitly.\n */\nexport interface RegisterContextOptions {\n\t/** Service instances keyed by serviceName */\n\tservices?: Record<string, unknown>;\n\t/** Database instance — required when endpoints use .database() */\n\tdatabase?: unknown;\n\t/** Event publisher service definition */\n\tpublisher?: Service;\n\t/** Audit storage instance — required when endpoints use .auditor() */\n\tauditorStorage?: unknown;\n}\n\nconst MSW_HTTP_METHODS = [\n\t'get',\n\t'post',\n\t'put',\n\t'patch',\n\t'delete',\n\t'options',\n] as const;\n\ntype MswHttpMethod = (typeof MSW_HTTP_METHODS)[number];\n\n/**\n * Result of creating MSW handlers from endpoint constructs.\n */\nexport interface CreateMswHandlersResult {\n\t/** MSW handlers to pass to setupServer() */\n\thandlers: HttpHandler[];\n\t/** Register an isolated context for a test */\n\tregisterContext: (id: string, options: RegisterContextOptions) => void;\n}\n\n/**\n * Creates MSW HTTP handlers from endpoint constructs.\n *\n * Mounts endpoints on a Hono app and creates MSW handlers that intercept\n * fetch requests and route them through `app.request()` — giving frontend\n * tests full endpoint behavior (validation, auth, sessions) without HTTP.\n *\n * Each test registers its own isolated context via `registerContext()`,\n * which is resolved per-request using the `x-test-context-id` header.\n * This allows concurrent tests with their own transactions and services.\n *\n * @param endpoints - Array of endpoint constructs to create handlers for\n * @param options - Configuration including baseURL\n * @returns MSW handlers, the Hono app, and context management functions\n */\nexport function createMswHandlers(\n\tendpoints: Endpoint<any, any, any, any, any, any>[],\n\toptions: CreateMswHandlersOptions,\n): CreateMswHandlersResult {\n\tconst { baseURL } = options;\n\tconst contexts = new Map<string, MswTestContext>();\n\n\t/**\n\t * Register an isolated context for a test.\n\t * Creates a fresh ServiceDiscovery and pre-registers all provided services.\n\t */\n\tfunction registerContext(id: string, ctxOptions: RegisterContextOptions) {\n\t\tconst envParser = new EnvironmentParser({});\n\t\tconst serviceDiscovery = new ServiceDiscovery(envParser);\n\n\t\tconst serviceDefs: Service[] = [];\n\n\t\t// Register explicit services\n\t\tif (ctxOptions.services) {\n\t\t\tfor (const [name, instance] of Object.entries(ctxOptions.services)) {\n\t\t\t\tserviceDefs.push({\n\t\t\t\t\tserviceName: name,\n\t\t\t\t\tregister: () => instance,\n\t\t\t\t} as Service);\n\t\t\t}\n\t\t}\n\n\t\t// Register database service from endpoint metadata\n\t\tif (ctxOptions.database !== undefined) {\n\t\t\tfor (const endpoint of endpoints) {\n\t\t\t\tif (endpoint.databaseService) {\n\t\t\t\t\tserviceDefs.push({\n\t\t\t\t\t\tserviceName: endpoint.databaseService.serviceName,\n\t\t\t\t\t\tregister: () => ctxOptions.database,\n\t\t\t\t\t} as Service);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register publisher service\n\t\tif (ctxOptions.publisher) {\n\t\t\tserviceDefs.push(ctxOptions.publisher);\n\t\t}\n\n\t\t// Register auditor storage service from endpoint metadata\n\t\tif (ctxOptions.auditorStorage !== undefined) {\n\t\t\tfor (const endpoint of endpoints) {\n\t\t\t\tif (endpoint.auditorStorageService) {\n\t\t\t\t\tserviceDefs.push({\n\t\t\t\t\t\tserviceName: endpoint.auditorStorageService.serviceName,\n\t\t\t\t\t\tregister: () => ctxOptions.auditorStorage,\n\t\t\t\t\t} as Service);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (serviceDefs.length > 0) {\n\t\t\tserviceDiscovery.register(serviceDefs);\n\t\t}\n\n\t\tcontexts.set(id, { serviceDiscovery });\n\t}\n\n\t// Create a Hono app per-request that uses the correct ServiceDiscovery.\n\t// We use a wrapper app that resolves the context from the header,\n\t// then delegates to a context-specific Hono app.\n\tconst handlers: HttpHandler[] = [];\n\n\tfor (const endpoint of endpoints) {\n\t\tconst method = endpoint.method.toLowerCase() as MswHttpMethod;\n\t\tif (!MSW_HTTP_METHODS.includes(method)) continue;\n\n\t\tconst mswUrl = `${baseURL}${endpoint.route}`;\n\t\tconst mswMethod = http[method];\n\n\t\thandlers.push(\n\t\t\tmswMethod(mswUrl, async ({ request }) => {\n\t\t\t\tconst contextId = request.headers.get(TEST_CONTEXT_HEADER);\n\t\t\t\tconst ctx = contextId ? contexts.get(contextId) : undefined;\n\n\t\t\t\tif (!ctx) {\n\t\t\t\t\treturn new Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\terror: 'Missing or unknown test context ID',\n\t\t\t\t\t\t\thint: `Set the '${TEST_CONTEXT_HEADER}' header to a registered context ID`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{ status: 500, headers: { 'content-type': 'application/json' } },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Build a fresh Hono app with this context's ServiceDiscovery\n\t\t\t\tconst app = new Hono();\n\t\t\t\tHonoEndpoint.addRoute(endpoint, ctx.serviceDiscovery as any, app);\n\n\t\t\t\tconst response = await app.request(request);\n\n\t\t\t\treturn new Response(response.body, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn {\n\t\thandlers,\n\t\tregisterContext,\n\t};\n}\n","import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport { ForbiddenError } from '@geekmidas/errors';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type {\n\tInferComposableStandardSchema,\n\tInferStandardSchema,\n} from '@geekmidas/schema';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishConstructEvents } from '../publisher';\nimport type { HttpMethod } from '../types';\nimport type { MappedAudit } from './audit';\nimport {\n\ttype CookieOptions,\n\tEndpoint,\n\ttype EndpointSchemas,\n\tResponseBuilder,\n} from './Endpoint';\nimport {\n\tcreateCookieHeaderAccessor,\n\tcreateObjectHeaders,\n} from './lazyAccessors';\nimport {\n\ttype AuditExecutionContext,\n\texecuteWithAuditTransaction,\n} from './processAudits';\n\nexport type TestHttpResponse<TBody = any> = {\n\tbody: TBody;\n\tstatus: number;\n\theaders: Record<string, string | string[]>;\n};\n\n/**\n * Serializes a cookie into a Set-Cookie header string\n */\nfunction serializeCookie(\n\tname: string,\n\tvalue: string,\n\toptions?: CookieOptions,\n): string {\n\tlet cookieString = `${name}=${value}`;\n\n\tif (options) {\n\t\tif (options.maxAge !== undefined) {\n\t\t\tcookieString += `; Max-Age=${options.maxAge}`;\n\t\t}\n\t\tif (options.expires) {\n\t\t\tcookieString += `; Expires=${options.expires.toUTCString()}`;\n\t\t}\n\t\tif (options.domain) {\n\t\t\tcookieString += `; Domain=${options.domain}`;\n\t\t}\n\t\tif (options.path) {\n\t\t\tcookieString += `; Path=${options.path}`;\n\t\t}\n\t\tif (options.httpOnly) {\n\t\t\tcookieString += '; HttpOnly';\n\t\t}\n\t\tif (options.secure) {\n\t\t\tcookieString += '; Secure';\n\t\t}\n\t\tif (options.sameSite) {\n\t\t\tcookieString += `; SameSite=${options.sameSite}`;\n\t\t}\n\t}\n\n\treturn cookieString;\n}\n\nexport class TestEndpointAdaptor<\n\tTRoute extends string,\n\tTMethod extends HttpMethod,\n\tTInput extends EndpointSchemas = {},\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> {\n\tstatic getDefaultServiceDiscover<\n\t\tTRoute extends string,\n\t\tTMethod extends HttpMethod,\n\t\tTInput extends EndpointSchemas = {},\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTSession = unknown,\n\t\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\t\tTEventPublisherServiceName extends string = string,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t>(\n\t\t_endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t) {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\tconstructor(\n\t\tprivate readonly endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestEndpointAdaptor.getDefaultServiceDiscover(\n\t\t\tendpoint,\n\t\t),\n\t) {}\n\n\tasync fullRequest(\n\t\tctx: TestRequestAdaptor<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t): Promise<TestHttpResponse<InferStandardSchema<TOutSchema>>> {\n\t\tconst body = await this.endpoint.parseInput((ctx as any).body, 'body');\n\t\tconst query = await this.endpoint.parseInput((ctx as any).query, 'query');\n\t\tconst params = await this.endpoint.parseInput(\n\t\t\t(ctx as any).params,\n\t\t\t'params',\n\t\t);\n\n\t\t// Lazy accessors - defer parsing until needed\n\t\tconst header = createObjectHeaders(ctx.headers);\n\t\tconst cookie = createCookieHeaderAccessor(ctx.headers.cookie);\n\n\t\t// Request context setup\n\t\tconst startTime = Date.now();\n\t\tconst requestId =\n\t\t\t(ctx as any).requestId ??\n\t\t\tctx.headers['x-request-id'] ??\n\t\t\tcrypto.randomUUID();\n\n\t\tconst logger = this.endpoint.logger.child({\n\t\t\trequestId,\n\t\t\troute: this.endpoint.route,\n\t\t\thost: ctx.headers.host,\n\t\t\tmethod: this.endpoint.method,\n\t\t}) as TLogger;\n\n\t\t// Get database from context for session extraction\n\t\tconst rawDb = (ctx as any).database as TDatabase;\n\n\t\t// Wrap handler execution in request context\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\tconst session = await this.endpoint.getSession({\n\t\t\t\tlogger,\n\t\t\t\tservices: ctx.services,\n\t\t\t\theader,\n\t\t\t\tcookie,\n\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t} as any);\n\n\t\t\t// Check authorization\n\t\t\tconst isAuthorized = await this.endpoint.authorize({\n\t\t\t\theader,\n\t\t\t\tcookie,\n\t\t\t\tservices: ctx.services,\n\t\t\t\tlogger,\n\t\t\t\tsession,\n\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\tbody,\n\t\t\t\tquery,\n\t\t\t\tparams,\n\t\t\t} as any);\n\n\t\t\tif (!isAuthorized) {\n\t\t\t\tlogger.warn('Forbidden access attempt');\n\t\t\t\tthrow new ForbiddenError(\n\t\t\t\t\t'Forbidden access to the endpoint',\n\t\t\t\t\t'You do not have permission to access this resource.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Create audit context if audit storage is provided\n\t\t\t// The auditorStorage instance is required when endpoint uses .auditor()\n\t\t\tconst auditorStorage = (ctx as any).auditorStorage as TAuditStorage;\n\t\t\tlet auditContext: AuditExecutionContext<TAuditAction> | undefined;\n\n\t\t\tif (auditorStorage) {\n\t\t\t\t// Extract actor if configured\n\t\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\t\tif (this.endpoint.actorExtractor) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tactor = await this.endpoint.actorExtractor({\n\t\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\t\tactor,\n\t\t\t\t\tstorage: auditorStorage as AuditStorage,\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tendpoint: this.endpoint.route,\n\t\t\t\t\t\tmethod: this.endpoint.method,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tauditContext = { auditor, storage: auditorStorage as AuditStorage };\n\t\t\t}\n\n\t\t\t// Warn if declarative audits are configured but no audit storage\n\t\t\tconst audits = this.endpoint.audits as MappedAudit<\n\t\t\t\tTAuditAction,\n\t\t\t\tTOutSchema\n\t\t\t>[];\n\t\t\tif (!auditContext && audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\n\t\t\t// Execute handler with automatic audit transaction support\n\t\t\tconst result = await executeWithAuditTransaction(\n\t\t\t\tauditContext,\n\t\t\t\tasync (auditor) => {\n\t\t\t\t\t// Use audit transaction as db if available (when storage has same database)\n\t\t\t\t\t// For testing, the tester controls whether to use transactional auditing\n\t\t\t\t\tconst trx = auditor?.getTransaction?.();\n\t\t\t\t\tconst db = trx ?? rawDb;\n\n\t\t\t\t\tconst responseBuilder = new ResponseBuilder();\n\t\t\t\t\tconst response = await this.endpoint.handler(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\tservices: ctx.services,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tauditor,\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t} as any,\n\t\t\t\t\t\tresponseBuilder,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Check if response has metadata\n\t\t\t\t\tlet data = response;\n\t\t\t\t\tlet metadata = responseBuilder.getMetadata();\n\n\t\t\t\t\tif (Endpoint.hasMetadata(response)) {\n\t\t\t\t\t\tdata = response.data;\n\t\t\t\t\t\tmetadata = response.metadata;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst output = await this.endpoint.parseOutput(data);\n\n\t\t\t\t\treturn { output, metadata, responseBuilder };\n\t\t\t\t},\n\t\t\t\t// Process declarative audits after handler (inside transaction)\n\t\t\t\tasync (result, auditor) => {\n\t\t\t\t\tif (!audits?.length) return;\n\n\t\t\t\t\tfor (const audit of audits) {\n\t\t\t\t\t\tif (audit.when && !audit.when(result.output as any)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst payload = audit.payload(result.output as any);\n\t\t\t\t\t\tconst entityId = audit.entityId?.(result.output as any);\n\t\t\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\t\t\ttable: audit.table,\n\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t// Pass rawDb so storage can reuse existing transactions\n\t\t\t\t{ db: rawDb },\n\t\t\t);\n\n\t\t\tconst { output, metadata } = result;\n\n\t\t\tctx.publisher && (await this.serviceDiscovery.register([ctx.publisher]));\n\t\t\tawait publishConstructEvents(\n\t\t\t\tthis.endpoint,\n\t\t\t\toutput,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t);\n\n\t\t\t// Convert cookies to Set-Cookie headers\n\t\t\tconst headers: Record<string, string | string[]> = {\n\t\t\t\t...(metadata.headers || {}),\n\t\t\t};\n\n\t\t\tif (metadata.cookies && metadata.cookies.size > 0) {\n\t\t\t\tconst setCookieValues: string[] = [];\n\t\t\t\tfor (const [name, cookie] of metadata.cookies.entries()) {\n\t\t\t\t\tsetCookieValues.push(\n\t\t\t\t\t\tserializeCookie(name, cookie.value, cookie.options),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\theaders['set-cookie'] = setCookieValues;\n\t\t\t}\n\n\t\t\t// Return HTTP response format\n\t\t\treturn {\n\t\t\t\tbody: output,\n\t\t\t\tstatus: metadata.status || 200,\n\t\t\t\theaders,\n\t\t\t};\n\t\t});\n\t}\n\n\tasync request(\n\t\tctx: TestRequestAdaptor<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t): Promise<InferStandardSchema<TOutSchema>> {\n\t\tconst response = await this.fullRequest(ctx);\n\t\treturn response.body;\n\t}\n}\n\n/**\n * Conditional audit storage requirement - required when TAuditStorage is configured\n */\ntype AuditStorageRequirement<\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n> = TAuditStorage extends undefined\n\t? {}\n\t: {\n\t\t\t/** Audit storage instance - required when endpoint uses .auditor() */\n\t\t\tauditorStorage: TAuditStorage;\n\t\t};\n\n/**\n * Conditional database requirement - required when TDatabase is configured\n */\ntype DatabaseRequirement<TDatabase = undefined> = TDatabase extends undefined\n\t? {}\n\t: {\n\t\t\t/** Database instance - required when endpoint uses .database() */\n\t\t\tdatabase: TDatabase;\n\t\t};\n\nexport type TestRequestAdaptor<\n\tTInput extends EndpointSchemas = {},\n\tTServices extends Service[] = [],\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t_TAuditStorageServiceName extends string = string,\n\tTDatabase = undefined,\n\t_TDatabaseServiceName extends string = string,\n> = {\n\tservices: ServiceRecord<TServices>;\n\theaders: Record<string, string>;\n\tpublisher?: Service<TEventPublisherServiceName, TEventPublisher>;\n} & InferComposableStandardSchema<TInput> &\n\tAuditStorageRequirement<TAuditStorage> &\n\tDatabaseRequirement<TDatabase>;\n","import type { AuditableAction, Auditor, AuditStorage } from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type {\n\tComposableStandardSchema,\n\tInferComposableStandardSchema,\n\tInferStandardSchema,\n} from '@geekmidas/schema';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishEvents } from '../publisher';\nimport type { Function } from './Function';\nimport { FunctionBuilder } from './FunctionBuilder';\n\nexport class TestFunctionAdaptor<\n\tTInput extends ComposableStandardSchema | undefined = undefined,\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\tstatic getDefaultServiceDiscovery<\n\t\tTInput extends ComposableStandardSchema | undefined = undefined,\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\t\tTEventPublisherServiceName extends string = string,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t>(\n\t\t_fn: Function<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTAuditAction,\n\t\t\tany\n\t\t>,\n\t) {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly fn: Function<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTAuditAction,\n\t\t\tany\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestFunctionAdaptor.getDefaultServiceDiscovery(\n\t\t\tfn,\n\t\t),\n\t) {}\n\n\tasync invoke(\n\t\tctx: TestFunctionRequest<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTDatabase,\n\t\t\tTAuditAction\n\t\t>,\n\t): Promise<InferStandardSchema<TOutSchema>> {\n\t\t// Parse input if schema is provided\n\n\t\tconst parsedInput = await FunctionBuilder.parseComposableStandardSchema(\n\t\t\tctx.input,\n\t\t\tthis.fn.input,\n\t\t);\n\n\t\t// Create logger with context\n\t\tconst logger = this.fn.logger.child({\n\t\t\ttest: true,\n\t\t}) as TLogger;\n\n\t\t// Register services (use provided services or register from function)\n\t\tlet services: ServiceRecord<TServices>;\n\t\tif (ctx.services) {\n\t\t\tservices = ctx.services;\n\t\t} else {\n\t\t\tservices = await this.serviceDiscovery.register(this.fn.services);\n\t\t}\n\n\t\t// Resolve database (use provided db or register from function)\n\t\tlet db: TDatabase | undefined;\n\t\tif ('db' in ctx && ctx.db !== undefined) {\n\t\t\tdb = ctx.db;\n\t\t} else if (this.fn.databaseService) {\n\t\t\tconst dbServices = await this.serviceDiscovery.register([\n\t\t\t\tthis.fn.databaseService,\n\t\t\t]);\n\t\t\tdb = dbServices[\n\t\t\t\tthis.fn.databaseService.serviceName as keyof typeof dbServices\n\t\t\t] as TDatabase;\n\t\t}\n\n\t\t// Resolve auditor (use provided auditor or create from function)\n\t\tlet auditor: Auditor<TAuditAction> | undefined;\n\t\tif ('auditor' in ctx && ctx.auditor !== undefined) {\n\t\t\tauditor = ctx.auditor;\n\t\t} else if (this.fn.auditorStorageService) {\n\t\t\tconst auditServices = await this.serviceDiscovery.register([\n\t\t\t\tthis.fn.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = auditServices[\n\t\t\t\tthis.fn.auditorStorageService.serviceName as keyof typeof auditServices\n\t\t\t] as AuditStorage;\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor: { id: 'system', type: 'system' },\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tfunction: this.fn.type,\n\t\t\t\t\ttest: true,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Wrap execution in request context for service access via context.getLogger()\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\t// Execute the function\n\t\t\tconst response = await this.fn.fn({\n\t\t\t\tinput: parsedInput,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t\tdb,\n\t\t\t\tauditor,\n\t\t\t} as any);\n\n\t\t\t// Parse output if schema is provided\n\t\t\tconst output = await this.fn.parseOutput(response);\n\n\t\t\t// Flush audits if any were recorded\n\t\t\tif (auditor) {\n\t\t\t\tconst records = auditor.getRecords();\n\t\t\t\tif (records.length > 0) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ auditCount: records.length },\n\t\t\t\t\t\t'Flushing function audits',\n\t\t\t\t\t);\n\t\t\t\t\tawait auditor.flush();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Register publisher service if provided in context\n\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t\tthis.fn.events,\n\t\t\t\toutput,\n\t\t\t\tthis.fn.publisherService,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t}) as Promise<InferStandardSchema<TOutSchema>>;\n\t}\n}\n\nexport type TestFunctionRequest<\n\tTInput extends ComposableStandardSchema | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTDatabase = undefined,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> = {\n\tinput: InferComposableStandardSchema<TInput>;\n\tservices: ServiceRecord<TServices>;\n\tpublisher?: Service<TEventPublisherServiceName, TEventPublisher>;\n\tdb?: TDatabase;\n\tauditor?: Auditor<TAuditAction>;\n} & InferComposableStandardSchema<{ input: TInput }>;\n","import { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Queue } from './Queue';\n\n/**\n * In-memory test driver for a {@link Queue} worker. Hand it a batch of messages\n * and it registers the queue's services, runs the handler in a request context,\n * and returns the handler result — no SQS/pg-boss required.\n *\n * @example\n * const adapter = new TestQueueAdaptor(ordersQueue);\n * await adapter.invoke({ messages: [{ orderId: '123' }] });\n */\nexport class TestQueueAdaptor<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tstatic getDefaultServiceDiscovery() {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly queue: Queue<TName, TMessage, TServices, TLogger>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestQueueAdaptor.getDefaultServiceDiscovery(),\n\t) {}\n\n\tasync invoke(\n\t\trequest: TestQueueRequest<TMessage, TServices>,\n\t): Promise<unknown> {\n\t\tconst logger = this.queue.logger.child({ test: true }) as TLogger;\n\n\t\tconst services =\n\t\t\trequest.services ??\n\t\t\t((await this.serviceDiscovery.register(\n\t\t\t\tthis.queue.services,\n\t\t\t)) as ServiceRecord<TServices>);\n\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, () =>\n\t\t\tthis.queue.handler({\n\t\t\t\tmessages: request.messages,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t}),\n\t\t);\n\t}\n}\n\nexport type TestQueueRequest<\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n> = {\n\tmessages: InferStandardSchema<TMessage>[];\n\tservices?: ServiceRecord<TServices>;\n};\n","import { EnvironmentParser } from '@geekmidas/envkit';\nimport type {\n\tEventPublisher,\n\tExtractPublisherMessage,\n} from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishEvents } from '../publisher';\nimport type { Subscriber } from './Subscriber';\n\n// Helper type to extract payload types for subscribed events\ntype ExtractEventPayloads<\n\tTPublisher extends EventPublisher<any> | undefined,\n\tTEventTypes extends any[],\n> = TPublisher extends EventPublisher<any>\n\t? Extract<ExtractPublisherMessage<TPublisher>, { type: TEventTypes[number] }>\n\t: never;\n\nexport class TestSubscriberAdaptor<\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTSubscribedEvents extends\n\t\tExtractPublisherMessage<TEventPublisher>['type'][] = ExtractPublisherMessage<TEventPublisher>['type'][],\n> {\n\tstatic getDefaultServiceDiscovery() {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly subscriber: Subscriber<\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTSubscribedEvents\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestSubscriberAdaptor.getDefaultServiceDiscovery(),\n\t) {}\n\n\tasync invoke(\n\t\trequest: TestSubscriberRequest<\n\t\t\tTEventPublisher,\n\t\t\tTSubscribedEvents,\n\t\t\tTServices\n\t\t>,\n\t): Promise<InferStandardSchema<OutSchema>> {\n\t\t// Create logger with test context\n\t\tconst logger = this.subscriber.logger.child({\n\t\t\ttest: true,\n\t\t}) as TLogger;\n\n\t\t// Resolve services (use provided or auto-register)\n\t\tlet services: ServiceRecord<TServices>;\n\t\tif (request.services) {\n\t\t\tservices = request.services;\n\t\t} else {\n\t\t\tservices = await this.serviceDiscovery.register(this.subscriber.services);\n\t\t}\n\n\t\t// Filter events to only subscribed types\n\t\tconst filteredEvents = this.filterEvents(request.events);\n\n\t\t// Return early if no events after filtering (mirrors AWSLambdaSubscriber)\n\t\tif (filteredEvents.length === 0) {\n\t\t\treturn { batchItemFailures: [] } as any;\n\t\t}\n\n\t\t// Wrap execution in request context for service access via context.getLogger()\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\t// Execute the subscriber handler\n\t\t\tconst result = await this.subscriber.handler({\n\t\t\t\tevents: filteredEvents,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t});\n\n\t\t\t// Validate output if schema is provided\n\t\t\tlet output: any = result;\n\t\t\tif (this.subscriber.outputSchema && result) {\n\t\t\t\tconst validationResult =\n\t\t\t\t\tawait this.subscriber.outputSchema['~standard'].validate(result);\n\n\t\t\t\tif (validationResult.issues) {\n\t\t\t\t\tthrow new Error('Subscriber output validation failed');\n\t\t\t\t}\n\n\t\t\t\toutput = validationResult.value;\n\t\t\t}\n\n\t\t\t// Publish events if configured\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t\tthis.subscriber.events,\n\t\t\t\toutput,\n\t\t\t\tthis.subscriber.publisherService,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t}) as Promise<InferStandardSchema<OutSchema>>;\n\t}\n\n\tprivate filterEvents(\n\t\tevents: ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[],\n\t): ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[] {\n\t\tif (!this.subscriber.subscribedEvents) {\n\t\t\treturn events;\n\t\t}\n\n\t\treturn events.filter((event: any) =>\n\t\t\tthis.subscriber.subscribedEvents!.includes(event.type),\n\t\t);\n\t}\n}\n\nexport type TestSubscriberRequest<\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTSubscribedEvents extends any[] = [],\n\tTServices extends Service[] = [],\n> = {\n\tevents: ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[];\n\tservices?: ServiceRecord<TServices>;\n};\n","/**\n * `featureTest`: an app, driven the way it runs deployed.\n *\n * A browser signs in and calls the API; the API calls the auth server; each\n * over its URL, each database in its own transaction. Nothing runs as a server:\n * every URL an app's constructs answer on is served in-process through MSW,\n * from the real handler, for the test that made the request. Everything else\n * with a real local equivalent — Postgres, Mailpit, MinIO — is used directly.\n *\n * ```ts\n * // test/config.ts\n * export const it = featureTest({\n * modules: import.meta.glob(['../../constructs/*.ts', '../src/endpoints/**\\/*.ts'], { eager: true }),\n * database,\n * browser: Browser,\n * });\n *\n * // a test\n * it('shows the signed-in user their profile', async ({ browser, mailbox }) => {\n * await browser.auth.signIn.magicLink({ email: 'ada@shop.test' });\n * await browser.visit((await mailbox('ada@shop.test').last()).link!);\n * expect(await browser.api.get('/profile')).toMatchObject({ email: 'ada@shop.test' });\n * });\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport { provideKey } from '@geekmidas/manifest';\nimport { ServiceDiscovery, serviceContext } from '@geekmidas/services';\nimport { Browser as TestBrowser } from '@geekmidas/testkit/browser';\nimport {\n\tcurrentTestContext,\n\tinstallContextFetch,\n\trunAsServer,\n\trunInTestContext,\n\ttestContextOf,\n} from '@geekmidas/testkit/context';\nimport { createMailbox, type Mailbox } from '@geekmidas/testkit/mailbox';\nimport { TransactionRegistry } from '@geekmidas/testkit/transactions';\nimport { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport { http } from 'msw';\nimport { setupServer } from 'msw/node';\nimport { afterAll, beforeAll, test } from 'vitest';\nimport { BetterAuth } from '../auth';\nimport { KyselyDatabase } from '../database/kysely';\nimport { Email } from '../email';\nimport { Endpoint } from '../endpoints/Endpoint';\nimport { HonoEndpoint } from '../endpoints/HonoEndpointAdaptor';\n\nexport interface FeatureTestOptions<TBrowser extends TestBrowser, DB> {\n\t/**\n\t * The modules an app's constructs and endpoints are exported from — what\n\t * `import.meta.glob(…, { eager: true })` returns, or a list of modules.\n\t * Discovery reads exports, as the build does.\n\t */\n\tmodules: Record<string, unknown> | readonly unknown[];\n\t/** The app's own database: what a test receives as `db`. */\n\tdatabase?: KyselyDatabase<DB>;\n\t/** The browser each test gets — the app's subclass, with its clients. */\n\tbrowser?: new () => TBrowser;\n\t/** The environment `gkm test` injected. Defaults to `process.env`. */\n\tenv?: Record<string, string | undefined>;\n}\n\nexport interface FeatureContext<TBrowser extends TestBrowser, DB> {\n\t/** This test's browser, already the global `fetch`. */\n\tbrowser: TBrowser;\n\t/** The app database's transaction for this test, rolled back after it. */\n\tdb: Kysely<DB>;\n\t/** The mail sent to an address during this test, read from Mailpit. */\n\tmailbox: (address: string) => Mailbox;\n}\n\ntype FeatureFn<TBrowser extends TestBrowser, DB> = (\n\tcontext: FeatureContext<TBrowser, DB>,\n) => unknown;\n\nexport interface FeatureIt<TBrowser extends TestBrowser, DB> {\n\t(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n\tonly(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n\tskip(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n}\n\n/** Everything one test owns, found again from its id. */\ninterface ContextState {\n\ttransactions: TransactionRegistry;\n\tdiscovery: ServiceDiscovery<any>;\n\t/** One app per surface, with this test's services. */\n\tsurfaces: Map<string, Promise<Hono>>;\n\t/** One auth server per construct, on this test's transaction. */\n\tauth: Map<BetterAuth, Promise<Hono>>;\n\t/** The addresses this test read mail for, cleared after it. */\n\taddresses: Set<string>;\n}\n\n/** Every test in flight in this process, by id. */\nconst contexts = new Map<string, ContextState>();\n\n/** Databases already resolving to test transactions — patched once each. */\nconst bound = new WeakSet<KyselyDatabase>();\n\nexport function featureTest<\n\tTBrowser extends TestBrowser = TestBrowser,\n\tDB = unknown,\n>(options: FeatureTestOptions<TBrowser, DB>): FeatureIt<TBrowser, DB> {\n\tconst env = options.env ?? process.env;\n\tconst envParser = new EnvironmentParser({ ...env });\n\tconst found = discover(options.modules);\n\tconst BrowserClass = (options.browser ?? TestBrowser) as new () => TBrowser;\n\n\tfor (const database of found.databases) bindToTests(database);\n\n\tconst network = setupServer(\n\t\t...surfaceHandlers(found.endpoints, env),\n\t\t...found.auths.map((auth) => authHandler(auth, env, envParser)),\n\t);\n\n\tconst inbox = found.emails\n\t\t.map((email) => env[provideKey(email.id, 'inboxUrl')])\n\t\t.find(Boolean);\n\tconst readMail = inbox ? createMailbox({ inbox }) : undefined;\n\n\tlet restoreFetch: () => void = () => {};\n\tbeforeAll(() => {\n\t\tnetwork.listen({\n\t\t\tonUnhandledRequest(request, print) {\n\t\t\t\t// A real local service — Mailpit, MinIO — is used directly; only a\n\t\t\t\t// URL with nothing real behind it has to be answered here.\n\t\t\t\tif (isLocal(new URL(request.url))) return;\n\t\t\t\tprint.error();\n\t\t\t},\n\t\t});\n\t\t// After MSW's interceptor, so the stamp is on before a request is caught.\n\t\trestoreFetch = installContextFetch();\n\t});\n\tafterAll(() => {\n\t\trestoreFetch();\n\t\tnetwork.close();\n\t});\n\n\tconst run = (fn: FeatureFn<TBrowser, DB>) => async (): Promise<void> => {\n\t\tconst id = randomUUID();\n\t\tconst state: ContextState = {\n\t\t\ttransactions: new TransactionRegistry(),\n\t\t\tdiscovery: new ServiceDiscovery(envParser),\n\t\t\tsurfaces: new Map(),\n\t\t\tauth: new Map(),\n\t\t\taddresses: new Set(),\n\t\t};\n\t\tcontexts.set(id, state);\n\n\t\ttry {\n\t\t\tawait runInTestContext(id, async () => {\n\t\t\t\tconst browser = new BrowserClass();\n\t\t\t\tconst restore = browser.install();\n\t\t\t\ttry {\n\t\t\t\t\tawait fn({\n\t\t\t\t\t\tbrowser,\n\t\t\t\t\t\tdb: options.database\n\t\t\t\t\t\t\t? await state.transactions.get(\n\t\t\t\t\t\t\t\t\toptions.database.id,\n\t\t\t\t\t\t\t\t\turlOf(options.database, envParser),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: (undefined as never),\n\t\t\t\t\t\tmailbox: (address) => {\n\t\t\t\t\t\t\tif (!readMail) throw new NoInbox();\n\t\t\t\t\t\t\tstate.addresses.add(address);\n\t\t\t\t\t\t\treturn readMail(address);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\trestore();\n\t\t\t\t}\n\t\t\t});\n\t\t} finally {\n\t\t\tcontexts.delete(id);\n\t\t\tawait Promise.all([\n\t\t\t\tstate.transactions.rollbackAll(),\n\t\t\t\t...[...state.addresses].map((address) => readMail?.(address).clear()),\n\t\t\t]);\n\t\t}\n\t};\n\n\tconst it = ((name, fn, timeout) => test(name, run(fn), timeout)) as FeatureIt<\n\t\tTBrowser,\n\t\tDB\n\t>;\n\tit.only = (name, fn, timeout) => test.only(name, run(fn), timeout);\n\tit.skip = (name, fn, timeout) => test.skip(name, run(fn), timeout);\n\treturn it;\n}\n\n/** What an app's modules export, sorted by what a test does with it. */\nfunction discover(modules: FeatureTestOptions<any, any>['modules']) {\n\tconst values = (\n\t\tArray.isArray(modules) ? modules : Object.values(modules)\n\t).flatMap((module) =>\n\t\tmodule && typeof module === 'object' ? Object.values(module) : [],\n\t);\n\n\treturn {\n\t\tendpoints: values.filter((value): value is Endpoint<any, any, any, any> =>\n\t\t\tEndpoint.isEndpoint(value),\n\t\t),\n\t\tdatabases: values.filter(\n\t\t\t(value): value is KyselyDatabase => value instanceof KyselyDatabase,\n\t\t),\n\t\tauths: values.filter(\n\t\t\t(value): value is BetterAuth => value instanceof BetterAuth,\n\t\t),\n\t\temails: values.filter((value): value is Email => value instanceof Email),\n\t};\n}\n\n/**\n * Make a database resolve, inside a test, to that test's transaction.\n *\n * Everything reaches a database through its service — an endpoint through\n * service discovery, the auth server through its tenant directly — so this is\n * the one place a test's connection can be handed over. Outside a test it is\n * the database it always was.\n */\nfunction bindToTests(database: KyselyDatabase): void {\n\tif (bound.has(database)) return;\n\tbound.add(database);\n\n\tconst service = database.service as { register: (options: any) => unknown };\n\tconst register = service.register;\n\n\tservice.register = (options) => {\n\t\tconst context = currentTestContext();\n\t\tconst state = context && contexts.get(context.id);\n\t\tif (!state) return register(options);\n\n\t\treturn state.transactions.get(\n\t\t\tdatabase.id,\n\t\t\turlOf(database, options.envParser),\n\t\t);\n\t};\n}\n\nfunction urlOf(database: { id: string }, envParser: EnvironmentParser<{}>) {\n\treturn envParser\n\t\t.create((get) => ({ url: get(provideKey(database.id, 'url')).string() }))\n\t\t.parse().url;\n}\n\n/** Each surface's endpoints, served at its URL for the test that asked. */\nfunction surfaceHandlers(\n\tendpoints: Endpoint<any, any, any, any>[],\n\tenv: Record<string, string | undefined>,\n) {\n\tconst bySurface = new Map<string, Endpoint<any, any, any, any>[]>();\n\tfor (const endpoint of endpoints) {\n\t\tconst surface = endpoint.surface?.id;\n\t\tif (!surface) continue;\n\t\tbySurface.set(surface, [...(bySurface.get(surface) ?? []), endpoint]);\n\t}\n\n\treturn [...bySurface].flatMap(([surface, served]) => {\n\t\tconst base = env[provideKey(surface, 'url')];\n\t\tif (!base) return [];\n\n\t\treturn http.all(`${trim(base)}/*`, ({ request }) =>\n\t\t\tserve(request, async (state) => {\n\t\t\t\tlet app = state.surfaces.get(surface);\n\t\t\t\tif (!app) {\n\t\t\t\t\tapp = Promise.resolve().then(() => {\n\t\t\t\t\t\tconst hono = new Hono();\n\t\t\t\t\t\tHonoEndpoint.addRoutes(served, state.discovery, hono);\n\t\t\t\t\t\treturn hono;\n\t\t\t\t\t});\n\t\t\t\t\tstate.surfaces.set(surface, app);\n\t\t\t\t}\n\t\t\t\treturn (await app).fetch(request);\n\t\t\t}),\n\t\t);\n\t});\n}\n\n/** An auth server, served at its URL, on the transaction of the test that asked. */\nfunction authHandler(\n\tauth: BetterAuth,\n\tenv: Record<string, string | undefined>,\n\tenvParser: EnvironmentParser<{}>,\n) {\n\tconst base = trim(env[provideKey(auth.id, 'url')] ?? '');\n\n\treturn http.all(`${base}${auth.basePath}/*`, ({ request }) =>\n\t\tserve(request, async (state) => {\n\t\t\tlet app = state.auth.get(auth);\n\t\t\tif (!app) {\n\t\t\t\tapp = auth\n\t\t\t\t\t.server({ envParser, context: serviceContext })\n\t\t\t\t\t.then(({ app }) => app);\n\t\t\t\tstate.auth.set(auth, app);\n\t\t\t}\n\t\t\treturn (await app).fetch(request);\n\t\t}),\n\t);\n}\n\n/** Handle a request as the server side of the test it was made for. */\nasync function serve(\n\trequest: Request,\n\thandle: (state: ContextState) => Promise<Response>,\n): Promise<Response> {\n\tconst id = testContextOf(request);\n\tconst state = id ? contexts.get(id) : undefined;\n\tif (!id || !state) throw new UnknownTestContext(request.url, id);\n\n\treturn runAsServer(id, () => handle(state));\n}\n\nfunction trim(url: string): string {\n\treturn url.replace(/\\/$/, '');\n}\n\nfunction isLocal(url: URL): boolean {\n\treturn (\n\t\turl.hostname === 'localhost' ||\n\t\turl.hostname === '127.0.0.1' ||\n\t\turl.hostname.endsWith('.localhost')\n\t);\n}\n\n/** A request reached an in-process server without a test to belong to. */\nexport class UnknownTestContext extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly id: string | undefined,\n\t) {\n\t\tsuper(\n\t\t\tid\n\t\t\t\t? `${url} was requested for test ${id}, which is not running. A ` +\n\t\t\t\t\t\t`request that outlives its test — an un-awaited call — lands here.`\n\t\t\t\t: `${url} was requested outside any test. Make the request inside a ` +\n\t\t\t\t\t\t`featureTest, so it reaches that test's transactions.`,\n\t\t);\n\t\tthis.name = 'UnknownTestContext';\n\t}\n}\n\n/** `mailbox` was used in an app that declares no Email construct. */\nexport class NoInbox extends Error {\n\tconstructor() {\n\t\tsuper(\n\t\t\t`mailbox() reads the inbox of the app's Email construct, and none was ` +\n\t\t\t\t`found in featureTest's modules — or \\`gkm test\\` did not inject its ` +\n\t\t\t\t`<ID>_INBOX_URL.`,\n\t\t);\n\t\tthis.name = 'NoInbox';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8EA,MAAM,mBAAmB;CACxB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;;;;;;AA6BA,SAAgB,kBACf,WACA,SAC0B;CAC1B,MAAM,EAAE,YAAY;CACpB,MAAM,2BAAW,IAAI,IAA4B;;;;;CAMjD,SAAS,gBAAgB,IAAY,YAAoC;EACxE,MAAM,YAAY,IAAIA,kBAAAA,kBAAkB,CAAC,CAAC;EAC1C,MAAM,mBAAmB,IAAIC,oBAAAA,iBAAiB,SAAS;EAEvD,MAAM,cAAyB,CAAC;EAGhC,IAAI,WAAW,UACd,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,WAAW,QAAQ,GAChE,YAAY,KAAK;GAChB,aAAa;GACb,gBAAgB;EACjB,CAAY;EAKd,IAAI,WAAW,aAAa,KAAA,GACtB;QAAA,MAAM,YAAY,WACtB,IAAI,SAAS,iBAAiB;IAC7B,YAAY,KAAK;KAChB,aAAa,SAAS,gBAAgB;KACtC,gBAAgB,WAAW;IAC5B,CAAY;IACZ;GACD;;EAKF,IAAI,WAAW,WACd,YAAY,KAAK,WAAW,SAAS;EAItC,IAAI,WAAW,mBAAmB,KAAA,GAC5B;QAAA,MAAM,YAAY,WACtB,IAAI,SAAS,uBAAuB;IACnC,YAAY,KAAK;KAChB,aA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ACC,wJAGD;EACA,KAAK,OAAO;CACb;AACD"}
|
|
1
|
+
{"version":3,"file":"testing.cjs","names":["EnvironmentParser","ServiceDiscovery","http","TEST_CONTEXT_HEADER","Hono","ServiceDiscovery","EnvironmentParser","createObjectHeaders","createCookieHeaderAccessor","runWithRequestContext","ForbiddenError","DefaultAuditor","executeWithAuditTransaction","ResponseBuilder","Endpoint","publishConstructEvents","ServiceDiscovery","EnvironmentParser","FunctionBuilder","DefaultAuditor","runWithRequestContext","publishEvents","ServiceDiscovery","EnvironmentParser","runWithRequestContext","ServiceDiscovery","EnvironmentParser","runWithRequestContext","publishEvents","fileURLToPath","readFileSync","TestBrowser","setupServer","installContextFetch","randomUUID","TransactionRegistry","ServiceDiscovery","runInTestContext","test","EnvironmentParser","Endpoint","KyselyDatabase","BetterAuth","Email","Topic","Queue","provideKey","createMailbox","currentTestContext","http","hono","Hono","serviceContext","testContextOf","runAsServer"],"sources":["../../src/endpoints/MswEndpointAdaptor.ts","../../src/endpoints/TestEndpointAdaptor.ts","../../src/functions/TestFunctionAdaptor.ts","../../src/queue/TestQueueAdaptor.ts","../../src/subscribers/TestSubscriberAdaptor.ts","../../src/testing/manifest.ts","../../src/testing/featureTest.ts"],"sourcesContent":["import { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Service } from '@geekmidas/services';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport { TEST_CONTEXT_HEADER } from '@geekmidas/testkit/context';\nimport { Hono } from 'hono';\nimport { type HttpHandler, http } from 'msw';\nimport type { Endpoint } from './Endpoint';\nimport { HonoEndpoint } from './HonoEndpointAdaptor';\n\n/**\n * Header used to identify which test context a request belongs to — defined\n * once, in testkit, where the stamped `fetch` that writes it lives.\n */\nexport { TEST_CONTEXT_HEADER };\n\n/**\n * Per-test context containing an isolated ServiceDiscovery instance.\n * Registered in the context map and looked up per-request via the context ID header.\n */\nexport interface MswTestContext {\n\tserviceDiscovery: ServiceDiscovery<any>;\n}\n\n/**\n * Options for creating MSW handlers from endpoint constructs.\n *\n * @example\n * ```typescript\n * import { createMswHandlers, registerTestContext } from '@geekmidas/constructs/testing';\n * import { setupServer } from 'msw/node';\n *\n * // Create handlers once (global)\n * const { handlers, registerContext, removeContext } = createMswHandlers(\n * [getUsers, createUser],\n * { baseURL: 'http://localhost:3000' },\n * );\n * const server = setupServer(...handlers);\n *\n * // Per test: register an isolated context with its own services/transaction\n * it('should list users', async ({ db }) => {\n * const contextId = crypto.randomUUID();\n * registerContext(contextId, {\n * services: { database: db, auth: mockAuth },\n * });\n *\n * const api = createApi({\n * baseURL: 'http://localhost:3000',\n * headers: { [TEST_CONTEXT_HEADER]: contextId },\n * });\n *\n * const result = await api('GET /users');\n * expect(result).toBeDefined();\n *\n * removeContext(contextId);\n * });\n * ```\n */\nexport interface CreateMswHandlersOptions {\n\t/** Base URL the client fetches from (e.g., 'http://localhost:3000') */\n\tbaseURL: string;\n}\n\n/**\n * Options for registering a per-test context.\n * Follows the same pattern as TestRequestAdaptor — services, database,\n * publisher, and auditorStorage are provided explicitly.\n */\nexport interface RegisterContextOptions {\n\t/** Service instances keyed by serviceName */\n\tservices?: Record<string, unknown>;\n\t/** Database instance — required when endpoints use .database() */\n\tdatabase?: unknown;\n\t/** Event publisher service definition */\n\tpublisher?: Service;\n\t/** Audit storage instance — required when endpoints use .auditor() */\n\tauditorStorage?: unknown;\n}\n\nconst MSW_HTTP_METHODS = [\n\t'get',\n\t'post',\n\t'put',\n\t'patch',\n\t'delete',\n\t'options',\n] as const;\n\ntype MswHttpMethod = (typeof MSW_HTTP_METHODS)[number];\n\n/**\n * Result of creating MSW handlers from endpoint constructs.\n */\nexport interface CreateMswHandlersResult {\n\t/** MSW handlers to pass to setupServer() */\n\thandlers: HttpHandler[];\n\t/** Register an isolated context for a test */\n\tregisterContext: (id: string, options: RegisterContextOptions) => void;\n}\n\n/**\n * Creates MSW HTTP handlers from endpoint constructs.\n *\n * Mounts endpoints on a Hono app and creates MSW handlers that intercept\n * fetch requests and route them through `app.request()` — giving frontend\n * tests full endpoint behavior (validation, auth, sessions) without HTTP.\n *\n * Each test registers its own isolated context via `registerContext()`,\n * which is resolved per-request using the `x-test-context-id` header.\n * This allows concurrent tests with their own transactions and services.\n *\n * @param endpoints - Array of endpoint constructs to create handlers for\n * @param options - Configuration including baseURL\n * @returns MSW handlers, the Hono app, and context management functions\n */\nexport function createMswHandlers(\n\tendpoints: Endpoint<any, any, any, any, any, any>[],\n\toptions: CreateMswHandlersOptions,\n): CreateMswHandlersResult {\n\tconst { baseURL } = options;\n\tconst contexts = new Map<string, MswTestContext>();\n\n\t/**\n\t * Register an isolated context for a test.\n\t * Creates a fresh ServiceDiscovery and pre-registers all provided services.\n\t */\n\tfunction registerContext(id: string, ctxOptions: RegisterContextOptions) {\n\t\tconst envParser = new EnvironmentParser({});\n\t\tconst serviceDiscovery = new ServiceDiscovery(envParser);\n\n\t\tconst serviceDefs: Service[] = [];\n\n\t\t// Register explicit services\n\t\tif (ctxOptions.services) {\n\t\t\tfor (const [name, instance] of Object.entries(ctxOptions.services)) {\n\t\t\t\tserviceDefs.push({\n\t\t\t\t\tserviceName: name,\n\t\t\t\t\tregister: () => instance,\n\t\t\t\t} as Service);\n\t\t\t}\n\t\t}\n\n\t\t// Register database service from endpoint metadata\n\t\tif (ctxOptions.database !== undefined) {\n\t\t\tfor (const endpoint of endpoints) {\n\t\t\t\tif (endpoint.databaseService) {\n\t\t\t\t\tserviceDefs.push({\n\t\t\t\t\t\tserviceName: endpoint.databaseService.serviceName,\n\t\t\t\t\t\tregister: () => ctxOptions.database,\n\t\t\t\t\t} as Service);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Register publisher service\n\t\tif (ctxOptions.publisher) {\n\t\t\tserviceDefs.push(ctxOptions.publisher);\n\t\t}\n\n\t\t// Register auditor storage service from endpoint metadata\n\t\tif (ctxOptions.auditorStorage !== undefined) {\n\t\t\tfor (const endpoint of endpoints) {\n\t\t\t\tif (endpoint.auditorStorageService) {\n\t\t\t\t\tserviceDefs.push({\n\t\t\t\t\t\tserviceName: endpoint.auditorStorageService.serviceName,\n\t\t\t\t\t\tregister: () => ctxOptions.auditorStorage,\n\t\t\t\t\t} as Service);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (serviceDefs.length > 0) {\n\t\t\tserviceDiscovery.register(serviceDefs);\n\t\t}\n\n\t\tcontexts.set(id, { serviceDiscovery });\n\t}\n\n\t// Create a Hono app per-request that uses the correct ServiceDiscovery.\n\t// We use a wrapper app that resolves the context from the header,\n\t// then delegates to a context-specific Hono app.\n\tconst handlers: HttpHandler[] = [];\n\n\tfor (const endpoint of endpoints) {\n\t\tconst method = endpoint.method.toLowerCase() as MswHttpMethod;\n\t\tif (!MSW_HTTP_METHODS.includes(method)) continue;\n\n\t\tconst mswUrl = `${baseURL}${endpoint.route}`;\n\t\tconst mswMethod = http[method];\n\n\t\thandlers.push(\n\t\t\tmswMethod(mswUrl, async ({ request }) => {\n\t\t\t\tconst contextId = request.headers.get(TEST_CONTEXT_HEADER);\n\t\t\t\tconst ctx = contextId ? contexts.get(contextId) : undefined;\n\n\t\t\t\tif (!ctx) {\n\t\t\t\t\treturn new Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\terror: 'Missing or unknown test context ID',\n\t\t\t\t\t\t\thint: `Set the '${TEST_CONTEXT_HEADER}' header to a registered context ID`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{ status: 500, headers: { 'content-type': 'application/json' } },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Build a fresh Hono app with this context's ServiceDiscovery\n\t\t\t\tconst app = new Hono();\n\t\t\t\tHonoEndpoint.addRoute(endpoint, ctx.serviceDiscovery as any, app);\n\n\t\t\t\tconst response = await app.request(request);\n\n\t\t\t\treturn new Response(response.body, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\theaders: response.headers,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn {\n\t\thandlers,\n\t\tregisterContext,\n\t};\n}\n","import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport { ForbiddenError } from '@geekmidas/errors';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type {\n\tInferComposableStandardSchema,\n\tInferStandardSchema,\n} from '@geekmidas/schema';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishConstructEvents } from '../publisher';\nimport type { HttpMethod } from '../types';\nimport type { MappedAudit } from './audit';\nimport {\n\ttype CookieOptions,\n\tEndpoint,\n\ttype EndpointSchemas,\n\tResponseBuilder,\n} from './Endpoint';\nimport {\n\tcreateCookieHeaderAccessor,\n\tcreateObjectHeaders,\n} from './lazyAccessors';\nimport {\n\ttype AuditExecutionContext,\n\texecuteWithAuditTransaction,\n} from './processAudits';\n\nexport type TestHttpResponse<TBody = any> = {\n\tbody: TBody;\n\tstatus: number;\n\theaders: Record<string, string | string[]>;\n};\n\n/**\n * Serializes a cookie into a Set-Cookie header string\n */\nfunction serializeCookie(\n\tname: string,\n\tvalue: string,\n\toptions?: CookieOptions,\n): string {\n\tlet cookieString = `${name}=${value}`;\n\n\tif (options) {\n\t\tif (options.maxAge !== undefined) {\n\t\t\tcookieString += `; Max-Age=${options.maxAge}`;\n\t\t}\n\t\tif (options.expires) {\n\t\t\tcookieString += `; Expires=${options.expires.toUTCString()}`;\n\t\t}\n\t\tif (options.domain) {\n\t\t\tcookieString += `; Domain=${options.domain}`;\n\t\t}\n\t\tif (options.path) {\n\t\t\tcookieString += `; Path=${options.path}`;\n\t\t}\n\t\tif (options.httpOnly) {\n\t\t\tcookieString += '; HttpOnly';\n\t\t}\n\t\tif (options.secure) {\n\t\t\tcookieString += '; Secure';\n\t\t}\n\t\tif (options.sameSite) {\n\t\t\tcookieString += `; SameSite=${options.sameSite}`;\n\t\t}\n\t}\n\n\treturn cookieString;\n}\n\nexport class TestEndpointAdaptor<\n\tTRoute extends string,\n\tTMethod extends HttpMethod,\n\tTInput extends EndpointSchemas = {},\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> {\n\tstatic getDefaultServiceDiscover<\n\t\tTRoute extends string,\n\t\tTMethod extends HttpMethod,\n\t\tTInput extends EndpointSchemas = {},\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTSession = unknown,\n\t\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\t\tTEventPublisherServiceName extends string = string,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t>(\n\t\t_endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t) {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\tconstructor(\n\t\tprivate readonly endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestEndpointAdaptor.getDefaultServiceDiscover(\n\t\t\tendpoint,\n\t\t),\n\t) {}\n\n\tasync fullRequest(\n\t\tctx: TestRequestAdaptor<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t): Promise<TestHttpResponse<InferStandardSchema<TOutSchema>>> {\n\t\tconst body = await this.endpoint.parseInput((ctx as any).body, 'body');\n\t\tconst query = await this.endpoint.parseInput((ctx as any).query, 'query');\n\t\tconst params = await this.endpoint.parseInput(\n\t\t\t(ctx as any).params,\n\t\t\t'params',\n\t\t);\n\n\t\t// Lazy accessors - defer parsing until needed\n\t\tconst header = createObjectHeaders(ctx.headers);\n\t\tconst cookie = createCookieHeaderAccessor(ctx.headers.cookie);\n\n\t\t// Request context setup\n\t\tconst startTime = Date.now();\n\t\tconst requestId =\n\t\t\t(ctx as any).requestId ??\n\t\t\tctx.headers['x-request-id'] ??\n\t\t\tcrypto.randomUUID();\n\n\t\tconst logger = this.endpoint.logger.child({\n\t\t\trequestId,\n\t\t\troute: this.endpoint.route,\n\t\t\thost: ctx.headers.host,\n\t\t\tmethod: this.endpoint.method,\n\t\t}) as TLogger;\n\n\t\t// Get database from context for session extraction\n\t\tconst rawDb = (ctx as any).database as TDatabase;\n\n\t\t// Wrap handler execution in request context\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\tconst session = await this.endpoint.getSession({\n\t\t\t\tlogger,\n\t\t\t\tservices: ctx.services,\n\t\t\t\theader,\n\t\t\t\tcookie,\n\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t} as any);\n\n\t\t\t// Check authorization\n\t\t\tconst isAuthorized = await this.endpoint.authorize({\n\t\t\t\theader,\n\t\t\t\tcookie,\n\t\t\t\tservices: ctx.services,\n\t\t\t\tlogger,\n\t\t\t\tsession,\n\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\tbody,\n\t\t\t\tquery,\n\t\t\t\tparams,\n\t\t\t} as any);\n\n\t\t\tif (!isAuthorized) {\n\t\t\t\tlogger.warn('Forbidden access attempt');\n\t\t\t\tthrow new ForbiddenError(\n\t\t\t\t\t'Forbidden access to the endpoint',\n\t\t\t\t\t'You do not have permission to access this resource.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Create audit context if audit storage is provided\n\t\t\t// The auditorStorage instance is required when endpoint uses .auditor()\n\t\t\tconst auditorStorage = (ctx as any).auditorStorage as TAuditStorage;\n\t\t\tlet auditContext: AuditExecutionContext<TAuditAction> | undefined;\n\n\t\t\tif (auditorStorage) {\n\t\t\t\t// Extract actor if configured\n\t\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\t\tif (this.endpoint.actorExtractor) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tactor = await this.endpoint.actorExtractor({\n\t\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\t\tactor,\n\t\t\t\t\tstorage: auditorStorage as AuditStorage,\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tendpoint: this.endpoint.route,\n\t\t\t\t\t\tmethod: this.endpoint.method,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tauditContext = { auditor, storage: auditorStorage as AuditStorage };\n\t\t\t}\n\n\t\t\t// Warn if declarative audits are configured but no audit storage\n\t\t\tconst audits = this.endpoint.audits as MappedAudit<\n\t\t\t\tTAuditAction,\n\t\t\t\tTOutSchema\n\t\t\t>[];\n\t\t\tif (!auditContext && audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\n\t\t\t// Execute handler with automatic audit transaction support\n\t\t\tconst result = await executeWithAuditTransaction(\n\t\t\t\tauditContext,\n\t\t\t\tasync (auditor) => {\n\t\t\t\t\t// Use audit transaction as db if available (when storage has same database)\n\t\t\t\t\t// For testing, the tester controls whether to use transactional auditing\n\t\t\t\t\tconst trx = auditor?.getTransaction?.();\n\t\t\t\t\tconst db = trx ?? rawDb;\n\n\t\t\t\t\tconst responseBuilder = new ResponseBuilder();\n\t\t\t\t\tconst response = await this.endpoint.handler(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\tservices: ctx.services,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tauditor,\n\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t} as any,\n\t\t\t\t\t\tresponseBuilder,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Check if response has metadata\n\t\t\t\t\tlet data = response;\n\t\t\t\t\tlet metadata = responseBuilder.getMetadata();\n\n\t\t\t\t\tif (Endpoint.hasMetadata(response)) {\n\t\t\t\t\t\tdata = response.data;\n\t\t\t\t\t\tmetadata = response.metadata;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst output = await this.endpoint.parseOutput(data);\n\n\t\t\t\t\treturn { output, metadata, responseBuilder };\n\t\t\t\t},\n\t\t\t\t// Process declarative audits after handler (inside transaction)\n\t\t\t\tasync (result, auditor) => {\n\t\t\t\t\tif (!audits?.length) return;\n\n\t\t\t\t\tfor (const audit of audits) {\n\t\t\t\t\t\tif (audit.when && !audit.when(result.output as any)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst payload = audit.payload(result.output as any);\n\t\t\t\t\t\tconst entityId = audit.entityId?.(result.output as any);\n\t\t\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\t\t\ttable: audit.table,\n\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t// Pass rawDb so storage can reuse existing transactions\n\t\t\t\t{ db: rawDb },\n\t\t\t);\n\n\t\t\tconst { output, metadata } = result;\n\n\t\t\tctx.publisher && (await this.serviceDiscovery.register([ctx.publisher]));\n\t\t\tawait publishConstructEvents(\n\t\t\t\tthis.endpoint,\n\t\t\t\toutput,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t);\n\n\t\t\t// Convert cookies to Set-Cookie headers\n\t\t\tconst headers: Record<string, string | string[]> = {\n\t\t\t\t...(metadata.headers || {}),\n\t\t\t};\n\n\t\t\tif (metadata.cookies && metadata.cookies.size > 0) {\n\t\t\t\tconst setCookieValues: string[] = [];\n\t\t\t\tfor (const [name, cookie] of metadata.cookies.entries()) {\n\t\t\t\t\tsetCookieValues.push(\n\t\t\t\t\t\tserializeCookie(name, cookie.value, cookie.options),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\theaders['set-cookie'] = setCookieValues;\n\t\t\t}\n\n\t\t\t// Return HTTP response format\n\t\t\treturn {\n\t\t\t\tbody: output,\n\t\t\t\tstatus: metadata.status || 200,\n\t\t\t\theaders,\n\t\t\t};\n\t\t});\n\t}\n\n\tasync request(\n\t\tctx: TestRequestAdaptor<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>,\n\t): Promise<InferStandardSchema<TOutSchema>> {\n\t\tconst response = await this.fullRequest(ctx);\n\t\treturn response.body;\n\t}\n}\n\n/**\n * Conditional audit storage requirement - required when TAuditStorage is configured\n */\ntype AuditStorageRequirement<\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n> = TAuditStorage extends undefined\n\t? {}\n\t: {\n\t\t\t/** Audit storage instance - required when endpoint uses .auditor() */\n\t\t\tauditorStorage: TAuditStorage;\n\t\t};\n\n/**\n * Conditional database requirement - required when TDatabase is configured\n */\ntype DatabaseRequirement<TDatabase = undefined> = TDatabase extends undefined\n\t? {}\n\t: {\n\t\t\t/** Database instance - required when endpoint uses .database() */\n\t\t\tdatabase: TDatabase;\n\t\t};\n\nexport type TestRequestAdaptor<\n\tTInput extends EndpointSchemas = {},\n\tTServices extends Service[] = [],\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t_TAuditStorageServiceName extends string = string,\n\tTDatabase = undefined,\n\t_TDatabaseServiceName extends string = string,\n> = {\n\tservices: ServiceRecord<TServices>;\n\theaders: Record<string, string>;\n\tpublisher?: Service<TEventPublisherServiceName, TEventPublisher>;\n} & InferComposableStandardSchema<TInput> &\n\tAuditStorageRequirement<TAuditStorage> &\n\tDatabaseRequirement<TDatabase>;\n","import type { AuditableAction, Auditor, AuditStorage } from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type {\n\tComposableStandardSchema,\n\tInferComposableStandardSchema,\n\tInferStandardSchema,\n} from '@geekmidas/schema';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishEvents } from '../publisher';\nimport type { Function } from './Function';\nimport { FunctionBuilder } from './FunctionBuilder';\n\nexport class TestFunctionAdaptor<\n\tTInput extends ComposableStandardSchema | undefined = undefined,\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\tstatic getDefaultServiceDiscovery<\n\t\tTInput extends ComposableStandardSchema | undefined = undefined,\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\t\tTEventPublisherServiceName extends string = string,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t>(\n\t\t_fn: Function<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTAuditAction,\n\t\t\tany\n\t\t>,\n\t) {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly fn: Function<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTAuditAction,\n\t\t\tany\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestFunctionAdaptor.getDefaultServiceDiscovery(\n\t\t\tfn,\n\t\t),\n\t) {}\n\n\tasync invoke(\n\t\tctx: TestFunctionRequest<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTDatabase,\n\t\t\tTAuditAction\n\t\t>,\n\t): Promise<InferStandardSchema<TOutSchema>> {\n\t\t// Parse input if schema is provided\n\n\t\tconst parsedInput = await FunctionBuilder.parseComposableStandardSchema(\n\t\t\tctx.input,\n\t\t\tthis.fn.input,\n\t\t);\n\n\t\t// Create logger with context\n\t\tconst logger = this.fn.logger.child({\n\t\t\ttest: true,\n\t\t}) as TLogger;\n\n\t\t// Register services (use provided services or register from function)\n\t\tlet services: ServiceRecord<TServices>;\n\t\tif (ctx.services) {\n\t\t\tservices = ctx.services;\n\t\t} else {\n\t\t\tservices = await this.serviceDiscovery.register(this.fn.services);\n\t\t}\n\n\t\t// Resolve database (use provided db or register from function)\n\t\tlet db: TDatabase | undefined;\n\t\tif ('db' in ctx && ctx.db !== undefined) {\n\t\t\tdb = ctx.db;\n\t\t} else if (this.fn.databaseService) {\n\t\t\tconst dbServices = await this.serviceDiscovery.register([\n\t\t\t\tthis.fn.databaseService,\n\t\t\t]);\n\t\t\tdb = dbServices[\n\t\t\t\tthis.fn.databaseService.serviceName as keyof typeof dbServices\n\t\t\t] as TDatabase;\n\t\t}\n\n\t\t// Resolve auditor (use provided auditor or create from function)\n\t\tlet auditor: Auditor<TAuditAction> | undefined;\n\t\tif ('auditor' in ctx && ctx.auditor !== undefined) {\n\t\t\tauditor = ctx.auditor;\n\t\t} else if (this.fn.auditorStorageService) {\n\t\t\tconst auditServices = await this.serviceDiscovery.register([\n\t\t\t\tthis.fn.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = auditServices[\n\t\t\t\tthis.fn.auditorStorageService.serviceName as keyof typeof auditServices\n\t\t\t] as AuditStorage;\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor: { id: 'system', type: 'system' },\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tfunction: this.fn.type,\n\t\t\t\t\ttest: true,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Wrap execution in request context for service access via context.getLogger()\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\t// Execute the function\n\t\t\tconst response = await this.fn.fn({\n\t\t\t\tinput: parsedInput,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t\tdb,\n\t\t\t\tauditor,\n\t\t\t} as any);\n\n\t\t\t// Parse output if schema is provided\n\t\t\tconst output = await this.fn.parseOutput(response);\n\n\t\t\t// Flush audits if any were recorded\n\t\t\tif (auditor) {\n\t\t\t\tconst records = auditor.getRecords();\n\t\t\t\tif (records.length > 0) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ auditCount: records.length },\n\t\t\t\t\t\t'Flushing function audits',\n\t\t\t\t\t);\n\t\t\t\t\tawait auditor.flush();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Register publisher service if provided in context\n\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t\tthis.fn.events,\n\t\t\t\toutput,\n\t\t\t\tthis.fn.publisherService,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t}) as Promise<InferStandardSchema<TOutSchema>>;\n\t}\n}\n\nexport type TestFunctionRequest<\n\tTInput extends ComposableStandardSchema | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTDatabase = undefined,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> = {\n\tinput: InferComposableStandardSchema<TInput>;\n\tservices: ServiceRecord<TServices>;\n\tpublisher?: Service<TEventPublisherServiceName, TEventPublisher>;\n\tdb?: TDatabase;\n\tauditor?: Auditor<TAuditAction>;\n} & InferComposableStandardSchema<{ input: TInput }>;\n","import { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Queue } from './Queue';\n\n/**\n * In-memory test driver for a {@link Queue} worker. Hand it a batch of messages\n * and it registers the queue's services, runs the handler in a request context,\n * and returns the handler result — no SQS/pg-boss required.\n *\n * @example\n * const adapter = new TestQueueAdaptor(ordersQueue);\n * await adapter.invoke({ messages: [{ orderId: '123' }] });\n */\nexport class TestQueueAdaptor<\n\tTName extends string = string,\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tstatic getDefaultServiceDiscovery() {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly queue: Queue<TName, TMessage, TServices, TLogger>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestQueueAdaptor.getDefaultServiceDiscovery(),\n\t) {}\n\n\tasync invoke(\n\t\trequest: TestQueueRequest<TMessage, TServices>,\n\t): Promise<unknown> {\n\t\tconst logger = this.queue.logger.child({ test: true }) as TLogger;\n\n\t\tconst services =\n\t\t\trequest.services ??\n\t\t\t((await this.serviceDiscovery.register(\n\t\t\t\tthis.queue.services,\n\t\t\t)) as ServiceRecord<TServices>);\n\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, () =>\n\t\t\tthis.queue.handler({\n\t\t\t\tmessages: request.messages,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t}),\n\t\t);\n\t}\n}\n\nexport type TestQueueRequest<\n\tTMessage extends StandardSchemaV1 = StandardSchemaV1,\n\tTServices extends Service[] = [],\n> = {\n\tmessages: InferStandardSchema<TMessage>[];\n\tservices?: ServiceRecord<TServices>;\n};\n","import { EnvironmentParser } from '@geekmidas/envkit';\nimport type {\n\tEventPublisher,\n\tExtractPublisherMessage,\n} from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { publishEvents } from '../publisher';\nimport type { Subscriber } from './Subscriber';\n\n// Helper type to extract payload types for subscribed events\ntype ExtractEventPayloads<\n\tTPublisher extends EventPublisher<any> | undefined,\n\tTEventTypes extends any[],\n> = TPublisher extends EventPublisher<any>\n\t? Extract<ExtractPublisherMessage<TPublisher>, { type: TEventTypes[number] }>\n\t: never;\n\nexport class TestSubscriberAdaptor<\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTEventPublisherServiceName extends string = string,\n\tTSubscribedEvents extends\n\t\tExtractPublisherMessage<TEventPublisher>['type'][] = ExtractPublisherMessage<TEventPublisher>['type'][],\n> {\n\tstatic getDefaultServiceDiscovery() {\n\t\treturn ServiceDiscovery.getInstance(new EnvironmentParser({}));\n\t}\n\n\tconstructor(\n\t\tprivate readonly subscriber: Subscriber<\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTEventPublisher,\n\t\t\tTEventPublisherServiceName,\n\t\t\tTSubscribedEvents\n\t\t>,\n\t\tprivate serviceDiscovery: ServiceDiscovery<any> = TestSubscriberAdaptor.getDefaultServiceDiscovery(),\n\t) {}\n\n\tasync invoke(\n\t\trequest: TestSubscriberRequest<\n\t\t\tTEventPublisher,\n\t\t\tTSubscribedEvents,\n\t\t\tTServices\n\t\t>,\n\t): Promise<InferStandardSchema<OutSchema>> {\n\t\t// Create logger with test context\n\t\tconst logger = this.subscriber.logger.child({\n\t\t\ttest: true,\n\t\t}) as TLogger;\n\n\t\t// Resolve services (use provided or auto-register)\n\t\tlet services: ServiceRecord<TServices>;\n\t\tif (request.services) {\n\t\t\tservices = request.services;\n\t\t} else {\n\t\t\tservices = await this.serviceDiscovery.register(this.subscriber.services);\n\t\t}\n\n\t\t// Filter events to only subscribed types\n\t\tconst filteredEvents = this.filterEvents(request.events);\n\n\t\t// Return early if no events after filtering (mirrors AWSLambdaSubscriber)\n\t\tif (filteredEvents.length === 0) {\n\t\t\treturn { batchItemFailures: [] } as any;\n\t\t}\n\n\t\t// Wrap execution in request context for service access via context.getLogger()\n\t\tconst requestId = `test-${Date.now()}`;\n\t\tconst startTime = Date.now();\n\n\t\treturn runWithRequestContext({ logger, requestId, startTime }, async () => {\n\t\t\t// Execute the subscriber handler\n\t\t\tconst result = await this.subscriber.handler({\n\t\t\t\tevents: filteredEvents,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t});\n\n\t\t\t// Validate output if schema is provided\n\t\t\tlet output: any = result;\n\t\t\tif (this.subscriber.outputSchema && result) {\n\t\t\t\tconst validationResult =\n\t\t\t\t\tawait this.subscriber.outputSchema['~standard'].validate(result);\n\n\t\t\t\tif (validationResult.issues) {\n\t\t\t\t\tthrow new Error('Subscriber output validation failed');\n\t\t\t\t}\n\n\t\t\t\toutput = validationResult.value;\n\t\t\t}\n\n\t\t\t// Publish events if configured\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tthis.serviceDiscovery,\n\t\t\t\tthis.subscriber.events,\n\t\t\t\toutput,\n\t\t\t\tthis.subscriber.publisherService,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t}) as Promise<InferStandardSchema<OutSchema>>;\n\t}\n\n\tprivate filterEvents(\n\t\tevents: ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[],\n\t): ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[] {\n\t\tif (!this.subscriber.subscribedEvents) {\n\t\t\treturn events;\n\t\t}\n\n\t\treturn events.filter((event: any) =>\n\t\t\tthis.subscriber.subscribedEvents!.includes(event.type),\n\t\t);\n\t}\n}\n\nexport type TestSubscriberRequest<\n\tTEventPublisher extends EventPublisher<any> | undefined = undefined,\n\tTSubscribedEvents extends any[] = [],\n\tTServices extends Service[] = [],\n> = {\n\tevents: ExtractEventPayloads<TEventPublisher, TSubscribedEvents>[];\n\tservices?: ServiceRecord<TServices>;\n};\n","/**\n * The test manifest: what `gkm test` knows about an app, written down for the\n * suite it starts.\n *\n * `gkm test` discovers the constructs, reconciles the test stage and resolves\n * its environment — then, until this existed, threw all of it away and left a\n * test to declare it again by hand. The manifest keeps it: which construct and\n * endpoint is exported where, and the environment the test stage resolved,\n * under the keys the constructs themselves derive. A feature test is built from\n * it, so nothing a test says can drift from what the app declares.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\n\n/** Where an export lives: what an import statement has to say. */\nexport interface TestManifestSource {\n\t/** Absolute path to the module. */\n\tfile: string;\n\t/** The name it is exported as. */\n\texport: string;\n}\n\nexport interface TestManifest {\n\t/** The stage the environment was resolved for — `test`. */\n\tstage: string;\n\t/** Every construct the app declares, by id. */\n\tconstructs: Record<string, { kind: string; source: TestManifestSource }>;\n\t/** Every endpoint, and the surface that serves it. */\n\tendpoints: { surface: string; source: TestManifestSource }[];\n\t/**\n\t * The test stage's environment — reconcile's output, keyed as the\n\t * constructs derive their keys.\n\t */\n\tenv: Record<string, string>;\n}\n\n/** The environment variable `gkm test` names the manifest in. */\nexport const TEST_MANIFEST_ENV = 'GKM_TEST_MANIFEST';\n\n/**\n * Read a test manifest: from a path, a `file:` URL, or — given nothing — the\n * one `gkm test` named in `GKM_TEST_MANIFEST`.\n */\nexport function loadTestManifest(from?: string | URL): TestManifest {\n\tconst location = from ?? process.env[TEST_MANIFEST_ENV];\n\tif (!location) throw new NoTestManifest();\n\n\tconst path =\n\t\tlocation instanceof URL || location.startsWith('file:')\n\t\t\t? fileURLToPath(location)\n\t\t\t: location;\n\n\treturn JSON.parse(readFileSync(path, 'utf-8')) as TestManifest;\n}\n\n/** A feature test ran without a manifest to build itself from. */\nexport class NoTestManifest extends Error {\n\tconstructor() {\n\t\tsuper(\n\t\t\t`No test manifest: run the suite with \\`gkm test\\`, which writes one ` +\n\t\t\t\t`and names it in ${TEST_MANIFEST_ENV}.`,\n\t\t);\n\t\tthis.name = 'NoTestManifest';\n\t}\n}\n","/**\n * `featureTest`: an app, driven the way it runs deployed.\n *\n * A browser signs in and calls the API; the API calls the auth server; each\n * over its URL, each database in its own transaction. Nothing runs as a server:\n * every URL an app's constructs answer on is served in-process through MSW,\n * from the real handler, for the test that made the request. Everything else\n * with a real local equivalent — Postgres, Mailpit, MinIO — is used directly.\n *\n * It is built from the test manifest `gkm test` writes — the constructs and\n * endpoints the app exports, and the environment the test stage resolved — so\n * a test declares none of it. `gkm test` also generates the configured `it`\n * and a `Browser` with a typed client per surface:\n *\n * ```ts\n * import { it } from '#test';\n *\n * it('shows the signed-in user their profile', async ({ browser, mailbox }) => {\n * await browser.auth.signIn.magicLink({ email: 'ada@shop.test' });\n * await browser.visit((await mailbox('ada@shop.test').last()).link!);\n * expect(await browser.api.get('/profile')).toMatchObject({ email: 'ada@shop.test' });\n * });\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport { provideKey } from '@geekmidas/manifest';\nimport { ServiceDiscovery, serviceContext } from '@geekmidas/services';\nimport { Browser as TestBrowser } from '@geekmidas/testkit/browser';\nimport {\n\tcurrentTestContext,\n\tinstallContextFetch,\n\trunAsServer,\n\trunInTestContext,\n\ttestContextOf,\n} from '@geekmidas/testkit/context';\nimport { createMailbox, type Mailbox } from '@geekmidas/testkit/mailbox';\nimport { TransactionRegistry } from '@geekmidas/testkit/transactions';\nimport { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport { http } from 'msw';\nimport { type SetupServer, setupServer } from 'msw/node';\nimport { afterAll, beforeAll, test } from 'vitest';\nimport { BetterAuth } from '../auth';\nimport { KyselyDatabase } from '../database/kysely';\nimport { Email } from '../email';\nimport { Endpoint } from '../endpoints/Endpoint';\nimport { HonoEndpoint } from '../endpoints/HonoEndpointAdaptor';\nimport { Queue } from '../queue/Queue';\nimport { TestQueueAdaptor } from '../queue/TestQueueAdaptor';\nimport type { Subscriber } from '../subscribers/Subscriber';\nimport { TestSubscriberAdaptor } from '../subscribers/TestSubscriberAdaptor';\nimport { Topic } from '../topic/Topic';\nimport { loadTestManifest, type TestManifest } from './manifest';\n\nexport interface FeatureTestOptions<TBrowser extends TestBrowser> {\n\t/**\n\t * What the app declares and the environment its test stage resolved.\n\t * Defaults to the manifest `gkm test` names in `GKM_TEST_MANIFEST`.\n\t */\n\tmanifest?: TestManifest;\n\t/**\n\t * The app's modules, already imported, by the absolute path the manifest\n\t * records for them. The generated harness imports them statically, from\n\t * inside the app, so they resolve the way the app's own code does — its\n\t * tsconfig paths included. A module not here is imported by path.\n\t */\n\tmodules?: Readonly<Record<string, Record<string, unknown>>>;\n\t/** The browser each test gets — the generated one, with the app's clients. */\n\tbrowser?: new () => TBrowser;\n\t/**\n\t * The database a test receives as `db`, by construct id. Defaults to the\n\t * one the app's endpoints name with `.database()`.\n\t */\n\tdatabase?: string;\n}\n\nexport interface FeatureContext<TBrowser extends TestBrowser, DB> {\n\t/** This test's browser, already the global `fetch`. */\n\tbrowser: TBrowser;\n\t/** The app database's transaction for this test, rolled back after it. */\n\tdb: Kysely<DB>;\n\t/** The mail sent to an address during this test, read from Mailpit. */\n\tmailbox: (address: string) => Mailbox;\n\t/**\n\t * What this test published to a topic or enqueued on a queue, in order.\n\t * Nothing is delivered — a subscriber or a worker is tested on its own, by\n\t * handing it events — so this is where publishing is asserted.\n\t */\n\tpublished: (channel: { id: string }) => PublishedMessage[];\n\t/**\n\t * A subscriber, run on its own — handed events rather than delivered them —\n\t * with this test's services: its databases resolve to this test's\n\t * transactions, as an endpoint's do.\n\t */\n\tsubscriber: <S extends Subscriber<any, any, any, any, any, any>>(\n\t\tsubscriber: S,\n\t) => SubscriberAdaptorOf<S>;\n\t/** A queue's worker, run on its own with this test's services. */\n\tqueue: <Q extends Queue<any, any, any, any>>(queue: Q) => QueueAdaptorOf<Q>;\n}\n\ntype SubscriberAdaptorOf<S> =\n\tS extends Subscriber<\n\t\tinfer TServices,\n\t\tinfer TLogger,\n\t\tinfer OutSchema,\n\t\tinfer TEventPublisher,\n\t\tinfer TEventPublisherServiceName,\n\t\tinfer TSubscribedEvents\n\t>\n\t\t? TestSubscriberAdaptor<\n\t\t\t\tTServices,\n\t\t\t\tTLogger,\n\t\t\t\tOutSchema,\n\t\t\t\tTEventPublisher,\n\t\t\t\tTEventPublisherServiceName,\n\t\t\t\tTSubscribedEvents\n\t\t\t>\n\t\t: never;\n\ntype QueueAdaptorOf<Q> =\n\tQ extends Queue<infer TName, infer TMessage, infer TServices, infer TLogger>\n\t\t? TestQueueAdaptor<TName, TMessage, TServices, TLogger>\n\t\t: never;\n\n/** The schema a database construct was declared with — what `db` is typed by. */\nexport type DatabaseOf<C> =\n\tC extends KyselyDatabase<infer DB, any> ? DB : unknown;\n\n/** One message as it was published: its type and its payload. */\nexport interface PublishedMessage {\n\ttype: string;\n\tpayload: unknown;\n}\n\ntype FeatureFn<TBrowser extends TestBrowser, DB> = (\n\tcontext: FeatureContext<TBrowser, DB>,\n) => unknown;\n\nexport interface FeatureIt<TBrowser extends TestBrowser, DB> {\n\t(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n\tonly(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n\tskip(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;\n}\n\n/** Everything one test owns, found again from its id. */\ninterface ContextState {\n\ttransactions: TransactionRegistry;\n\tdiscovery: ServiceDiscovery<any>;\n\t/** One app per surface, with this test's services. */\n\tsurfaces: Map<string, Promise<Hono>>;\n\t/** One auth server per construct, on this test's transaction. */\n\tauth: Map<BetterAuth, Promise<Hono>>;\n\t/** The addresses this test read mail for, cleared after it. */\n\taddresses: Set<string>;\n\t/** What this test published, by topic or queue id. */\n\tpublished: Map<string, PublishedMessage[]>;\n}\n\n/** Every test in flight in this process, by id. */\nconst contexts = new Map<string, ContextState>();\n\n/** Databases already resolving to test transactions — patched once each. */\nconst bound = new WeakSet<KyselyDatabase>();\n\n/** What the manifest points at, imported: the app's own instances. */\ninterface LoadedApp {\n\tenvParser: EnvironmentParser<{}>;\n\tendpoints: Endpoint<any, any, any, any>[];\n\tdatabases: KyselyDatabase[];\n\tauths: BetterAuth[];\n\temails: Email[];\n\t/** Every topic and queue — what a test's publishing is recorded for. */\n\tchannels: (Topic<any, any> | Queue<any, any>)[];\n\t/** What `db` is. */\n\tdatabase?: KyselyDatabase;\n\treadMail?: (address: string) => Mailbox;\n}\n\nexport function featureTest<\n\tTBrowser extends TestBrowser = TestBrowser,\n\tDB = unknown,\n>(options: FeatureTestOptions<TBrowser> = {}): FeatureIt<TBrowser, DB> {\n\tconst manifest = options.manifest ?? loadTestManifest();\n\tconst BrowserClass = (options.browser ?? TestBrowser) as new () => TBrowser;\n\n\tlet app: LoadedApp;\n\tlet network: SetupServer;\n\tlet restoreFetch: () => void = () => {};\n\n\tbeforeAll(async () => {\n\t\tapp = await load(manifest, options.database, options.modules ?? {});\n\t\tfor (const database of app.databases) bindToTests(database);\n\n\t\tnetwork = setupServer(\n\t\t\t...surfaceHandlers(app.endpoints, manifest.env),\n\t\t\t...app.auths.map((auth) =>\n\t\t\t\tauthHandler(auth, manifest.env, app.envParser),\n\t\t\t),\n\t\t);\n\t\tnetwork.listen({\n\t\t\tonUnhandledRequest(request, print) {\n\t\t\t\t// A real local service — Mailpit, MinIO — is used directly; only a\n\t\t\t\t// URL with nothing real behind it has to be answered here.\n\t\t\t\tif (isLocal(new URL(request.url))) return;\n\t\t\t\tprint.error();\n\t\t\t},\n\t\t});\n\t\t// After MSW's interceptor, so the stamp is on before a request is caught.\n\t\trestoreFetch = installContextFetch();\n\t});\n\tafterAll(() => {\n\t\trestoreFetch();\n\t\tnetwork?.close();\n\t});\n\n\tconst run = (fn: FeatureFn<TBrowser, DB>) => async (): Promise<void> => {\n\t\tconst id = randomUUID();\n\t\tconst state: ContextState = {\n\t\t\ttransactions: new TransactionRegistry(),\n\t\t\tdiscovery: new ServiceDiscovery(app.envParser),\n\t\t\tsurfaces: new Map(),\n\t\t\tauth: new Map(),\n\t\t\taddresses: new Set(),\n\t\t\tpublished: new Map(),\n\t\t};\n\t\tcontexts.set(id, state);\n\t\t// Before anything resolves them: a publisher is a service, so the one this\n\t\t// test's endpoints get is whichever is registered under its name first.\n\t\tawait state.discovery.register(recorders(app.channels, state));\n\n\t\ttry {\n\t\t\tawait runInTestContext(id, async () => {\n\t\t\t\tconst browser = new BrowserClass();\n\t\t\t\tconst restore = browser.install();\n\t\t\t\ttry {\n\t\t\t\t\tawait fn({\n\t\t\t\t\t\tbrowser,\n\t\t\t\t\t\tdb: app.database\n\t\t\t\t\t\t\t? ((await state.transactions.get(\n\t\t\t\t\t\t\t\t\tapp.database.id,\n\t\t\t\t\t\t\t\t\turlOf(app.database, app.envParser),\n\t\t\t\t\t\t\t\t)) as Kysely<DB>)\n\t\t\t\t\t\t\t: (undefined as never),\n\t\t\t\t\t\tmailbox: (address) => {\n\t\t\t\t\t\t\tif (!app.readMail) throw new NoInbox();\n\t\t\t\t\t\t\tstate.addresses.add(address);\n\t\t\t\t\t\t\treturn app.readMail(address);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpublished: (channel) => [\n\t\t\t\t\t\t\t...(state.published.get(channel.id) ?? []),\n\t\t\t\t\t\t],\n\t\t\t\t\t\tsubscriber: (subscriber) =>\n\t\t\t\t\t\t\tnew TestSubscriberAdaptor(\n\t\t\t\t\t\t\t\tsubscriber,\n\t\t\t\t\t\t\t\tstate.discovery,\n\t\t\t\t\t\t\t) as SubscriberAdaptorOf<typeof subscriber>,\n\t\t\t\t\t\tqueue: (queue) =>\n\t\t\t\t\t\t\tnew TestQueueAdaptor(queue, state.discovery) as QueueAdaptorOf<\n\t\t\t\t\t\t\t\ttypeof queue\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\trestore();\n\t\t\t\t}\n\t\t\t});\n\t\t} finally {\n\t\t\tcontexts.delete(id);\n\t\t\tawait Promise.all([\n\t\t\t\tstate.transactions.rollbackAll(),\n\t\t\t\t...[...state.addresses].map((address) =>\n\t\t\t\t\tapp.readMail?.(address).clear(),\n\t\t\t\t),\n\t\t\t]);\n\t\t}\n\t};\n\n\tconst it = ((name, fn, timeout) => test(name, run(fn), timeout)) as FeatureIt<\n\t\tTBrowser,\n\t\tDB\n\t>;\n\tit.only = (name, fn, timeout) => test.only(name, run(fn), timeout);\n\tit.skip = (name, fn, timeout) => test.skip(name, run(fn), timeout);\n\treturn it;\n}\n\n/**\n * Import what the manifest points at.\n *\n * The same modules the app runs, so a construct here *is* the app's construct —\n * the one its endpoints were built from — never a copy declared again.\n */\nasync function load(\n\tmanifest: TestManifest,\n\tdatabase: string | undefined,\n\tmodules: Readonly<Record<string, Record<string, unknown>>>,\n): Promise<LoadedApp> {\n\tconst envParser = new EnvironmentParser({ ...manifest.env });\n\tconst imported = async ({\n\t\tfile,\n\t\texport: name,\n\t}: {\n\t\tfile: string;\n\t\texport: string;\n\t}) =>\n\t\t// Imported by path only as a fallback: from inside `node_modules`, a\n\t\t// dynamic import is left to Node, which knows nothing of the app's\n\t\t// tsconfig paths — `~/router.ts` resolves in the app and not here.\n\t\t(modules[file] ?? ((await import(file)) as Record<string, unknown>))[name];\n\n\tconst constructs = await Promise.all(\n\t\tObject.values(manifest.constructs).map(({ source }) => imported(source)),\n\t);\n\tconst endpoints = (\n\t\tawait Promise.all(manifest.endpoints.map(({ source }) => imported(source)))\n\t).filter((value): value is Endpoint<any, any, any, any> =>\n\t\tEndpoint.isEndpoint(value),\n\t);\n\n\tconst unique = <T>(values: T[]) => [...new Set(values)];\n\tconst databases = unique(\n\t\tconstructs.filter(\n\t\t\t(value): value is KyselyDatabase => value instanceof KyselyDatabase,\n\t\t),\n\t);\n\tconst auths = unique(\n\t\tconstructs.filter(\n\t\t\t(value): value is BetterAuth => value instanceof BetterAuth,\n\t\t),\n\t);\n\tconst emails = unique(\n\t\tconstructs.filter((value): value is Email => value instanceof Email),\n\t);\n\tconst channels = unique(\n\t\tconstructs.filter(\n\t\t\t(value): value is Topic<any, any> | Queue<any, any> =>\n\t\t\t\tvalue instanceof Topic || value instanceof Queue,\n\t\t),\n\t);\n\n\tconst inbox = emails\n\t\t.map((email) => manifest.env[provideKey(email.id, 'inboxUrl')])\n\t\t.find(Boolean);\n\n\treturn {\n\t\tenvParser,\n\t\tendpoints,\n\t\tdatabases,\n\t\tauths,\n\t\temails,\n\t\tchannels,\n\t\tdatabase: databaseOf(databases, endpoints, database),\n\t\t...(inbox ? { readMail: createMailbox({ inbox }) } : {}),\n\t};\n}\n\n/**\n * A publisher that records rather than sends, under every name a topic or\n * queue is injected by — `users`, and the older `usersPublisher`.\n */\nfunction recorders(\n\tchannels: LoadedApp['channels'],\n\tstate: ContextState,\n): { serviceName: string; register: () => unknown }[] {\n\treturn channels.flatMap((channel) => {\n\t\tconst publisher = {\n\t\t\tasync publish(messages: PublishedMessage[]) {\n\t\t\t\tstate.published.set(channel.id, [\n\t\t\t\t\t...(state.published.get(channel.id) ?? []),\n\t\t\t\t\t...messages.map(({ type, payload }) => ({ type, payload })),\n\t\t\t\t]);\n\t\t\t},\n\t\t};\n\t\treturn [channel.service.serviceName, channel.publisher.serviceName].map(\n\t\t\t(serviceName) => ({ serviceName, register: () => publisher }),\n\t\t);\n\t});\n}\n\n/**\n * The database a test sees as `db`: the one named, or else the one the\n * endpoints were given with `.database()` — found by the service they hold,\n * which is the construct's own.\n */\nfunction databaseOf(\n\tdatabases: KyselyDatabase[],\n\tendpoints: Endpoint<any, any, any, any>[],\n\tnamed: string | undefined,\n): KyselyDatabase | undefined {\n\tif (named) {\n\t\tconst found = databases.find(({ id }) => id === named);\n\t\tif (!found)\n\t\t\tthrow new UnknownDatabase(\n\t\t\t\tnamed,\n\t\t\t\tdatabases.map(({ id }) => id),\n\t\t\t);\n\t\treturn found;\n\t}\n\n\tconst services = new Set<unknown>(\n\t\tendpoints.map((e) => e.databaseService).filter(Boolean),\n\t);\n\treturn databases.find((database) => services.has(database.service));\n}\n\n/**\n * Make a database resolve, inside a test, to that test's transaction.\n *\n * Everything reaches a database through its service — an endpoint through\n * service discovery, the auth server through its tenant directly — so this is\n * the one place a test's connection can be handed over. Outside a test it is\n * the database it always was.\n */\nfunction bindToTests(database: KyselyDatabase): void {\n\tif (bound.has(database)) return;\n\tbound.add(database);\n\n\tconst service = database.service as { register: (options: any) => unknown };\n\tconst register = service.register;\n\n\tservice.register = (options) => {\n\t\tconst context = currentTestContext();\n\t\tconst state = context && contexts.get(context.id);\n\t\tif (!state) return register(options);\n\n\t\treturn state.transactions.get(\n\t\t\tdatabase.id,\n\t\t\turlOf(database, options.envParser),\n\t\t);\n\t};\n}\n\nfunction urlOf(database: { id: string }, envParser: EnvironmentParser<{}>) {\n\treturn envParser\n\t\t.create((get) => ({ url: get(provideKey(database.id, 'url')).string() }))\n\t\t.parse().url;\n}\n\n/** Each surface's endpoints, served at its URL for the test that asked. */\nfunction surfaceHandlers(\n\tendpoints: Endpoint<any, any, any, any>[],\n\tenv: Record<string, string | undefined>,\n) {\n\tconst bySurface = new Map<string, Endpoint<any, any, any, any>[]>();\n\tfor (const endpoint of endpoints) {\n\t\tconst surface = endpoint.surface?.id;\n\t\tif (!surface) continue;\n\t\tbySurface.set(surface, [...(bySurface.get(surface) ?? []), endpoint]);\n\t}\n\n\treturn [...bySurface].flatMap(([surface, served]) => {\n\t\tconst base = env[provideKey(surface, 'url')];\n\t\tif (!base) return [];\n\n\t\treturn http.all(`${trim(base)}/*`, ({ request }) =>\n\t\t\tserve(request, async (state) => {\n\t\t\t\tlet app = state.surfaces.get(surface);\n\t\t\t\tif (!app) {\n\t\t\t\t\tapp = Promise.resolve().then(() => {\n\t\t\t\t\t\tconst hono = new Hono();\n\t\t\t\t\t\tHonoEndpoint.addRoutes(served, state.discovery, hono);\n\t\t\t\t\t\treturn hono;\n\t\t\t\t\t});\n\t\t\t\t\tstate.surfaces.set(surface, app);\n\t\t\t\t}\n\t\t\t\treturn (await app).fetch(request);\n\t\t\t}),\n\t\t);\n\t});\n}\n\n/** An auth server, served at its URL, on the transaction of the test that asked. */\nfunction authHandler(\n\tauth: BetterAuth,\n\tenv: Record<string, string | undefined>,\n\tenvParser: EnvironmentParser<{}>,\n) {\n\tconst base = trim(env[provideKey(auth.id, 'url')] ?? '');\n\n\t// The whole origin, not only `basePath`: the auth server answers its own\n\t// host deployed, and a redirect it issues — to `/` after verifying a magic\n\t// link — lands on it. Paths it does not route get its own 404.\n\treturn http.all(`${base}/*`, ({ request }) =>\n\t\tserve(request, async (state) => {\n\t\t\tlet app = state.auth.get(auth);\n\t\t\tif (!app) {\n\t\t\t\tapp = auth\n\t\t\t\t\t.server({ envParser, context: serviceContext })\n\t\t\t\t\t.then(({ app }) => app);\n\t\t\t\tstate.auth.set(auth, app);\n\t\t\t}\n\t\t\treturn (await app).fetch(request);\n\t\t}),\n\t);\n}\n\n/** Handle a request as the server side of the test it was made for. */\nasync function serve(\n\trequest: Request,\n\thandle: (state: ContextState) => Promise<Response>,\n): Promise<Response> {\n\tconst id = testContextOf(request);\n\tconst state = id ? contexts.get(id) : undefined;\n\tif (!id || !state) throw new UnknownTestContext(request.url, id);\n\n\treturn runAsServer(id, () => handle(state));\n}\n\nfunction trim(url: string): string {\n\treturn url.replace(/\\/$/, '');\n}\n\nfunction isLocal(url: URL): boolean {\n\treturn (\n\t\turl.hostname === 'localhost' ||\n\t\turl.hostname === '127.0.0.1' ||\n\t\turl.hostname.endsWith('.localhost')\n\t);\n}\n\n/** A request reached an in-process server without a test to belong to. */\nexport class UnknownTestContext extends Error {\n\tconstructor(\n\t\treadonly url: string,\n\t\treadonly id: string | undefined,\n\t) {\n\t\tsuper(\n\t\t\tid\n\t\t\t\t? `${url} was requested for test ${id}, which is not running. A ` +\n\t\t\t\t\t\t`request that outlives its test — an un-awaited call — lands here.`\n\t\t\t\t: `${url} was requested outside any test. Make the request inside a ` +\n\t\t\t\t\t\t`featureTest, so it reaches that test's transactions.`,\n\t\t);\n\t\tthis.name = 'UnknownTestContext';\n\t}\n}\n\n/** `mailbox` was used in an app that declares no Email construct. */\nexport class NoInbox extends Error {\n\tconstructor() {\n\t\tsuper(\n\t\t\t`mailbox() reads the inbox of the app's Email construct, and none was ` +\n\t\t\t\t`found in featureTest's modules — or \\`gkm test\\` did not inject its ` +\n\t\t\t\t`<ID>_INBOX_URL.`,\n\t\t);\n\t\tthis.name = 'NoInbox';\n\t}\n}\n\n/** `featureTest({ database })` named a database the app does not declare. */\nexport class UnknownDatabase extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly declared: string[],\n\t) {\n\t\tsuper(\n\t\t\t`featureTest was asked for the database '${id}', and the app declares ` +\n\t\t\t\t`${declared.length ? declared.map((d) => `'${d}'`).join(', ') : 'none'}.`,\n\t\t);\n\t\tthis.name = 'UnknownDatabase';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,MAAM,mBAAmB;CACxB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;;;;;;AA6BA,SAAgB,kBACf,WACA,SAC0B;CAC1B,MAAM,EAAE,YAAY;CACpB,MAAM,2BAAW,IAAI,IAA4B;;;;;CAMjD,SAAS,gBAAgB,IAAY,YAAoC;EACxE,MAAM,YAAY,IAAIA,kBAAAA,kBAAkB,CAAC,CAAC;EAC1C,MAAM,mBAAmB,IAAIC,oBAAAA,iBAAiB,SAAS;EAEvD,MAAM,cAAyB,CAAC;EAGhC,IAAI,WAAW,UACd,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,WAAW,QAAQ,GAChE,YAAY,KAAK;GAChB,aAAa;GACb,gBAAgB;EACjB,CAAY;EAKd,IAAI,WAAW,aAAa,KAAA,GACtB;QAAA,MAAM,YAAY,WACtB,IAAI,SAAS,iBAAiB;IAC7B,YAAY,KAAK;KAChB,aAAa,SAAS,gBAAgB;KACtC,gBAAgB,WAAW;IAC5B,CAAY;IACZ;GACD;;EAKF,IAAI,WAAW,WACd,YAAY,KAAK,WAAW,SAAS;EAItC,IAAI,WAAW,mBAAmB,KAAA,GAC5B;QAAA,MAAM,YAAY,WACtB,IAAI,SAAS,uBAAuB;IACnC,YAAY,KAAK;KAChB,aAAa,SAAS,sBAAsB;KAC5C,gBAAgB,WAAW;IAC5B,CAAY;IACZ;GACD;;EAIF,IAAI,YAAY,SAAS,GACxB,iBAAiB,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MACd,SACA,QACoB;CACpB,MAAM,MAAA,GAAKC,2BAAAA,cAAAA,CAAc,OAAO;CAChC,MAAM,QAAQ,KAAK,SAAS,IAAI,EAAE,IAAI,KAAA;CACtC,IAAI,CAAC,MAAM,CAAC,OAAO,MAAM,IAAI,mBAAmB,QAAQ,KAAK,EAAE;CAE/D,QAAA,GAAOC,2BAAAA,YAAAA,CAAY,UAAU,OAAO,KAAK,CAAC;AAC3C;AAEA,SAAS,KAAK,KAAqB;CAClC,OAAO,IAAI,QAAQ,OAAO,EAAE;AAC7B;AAEA,SAAS,QAAQ,KAAmB;CACnC,OACC,IAAI,aAAa,eACjB,IAAI,aAAa,eACjB,IAAI,SAAS,SAAS,YAAY;AAEpC;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAEnC;CACA;CAFV,YACC,KACA,IACC;EACD,MACC,KACG,GAAG,IAAI,0BAA0B,GAAG,+FAEpC,GAAG,IAAI,gHAEX;EATS,KAAA,MAAA;EACA,KAAA,KAAA;EAST,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,UAAb,cAA6B,MAAM;CAClC,cAAc;EACb,MACC,wJAGD;EACA,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,kBAAb,cAAqC,MAAM;CAEhC;CACA;CAFV,YACC,IACA,UACC;EACD,MACC,2CAA2C,GAAG,0BAC1C,SAAS,SAAS,SAAS,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,OAAO,EACzE;EANS,KAAA,KAAA;EACA,KAAA,WAAA;EAMT,KAAK,OAAO;CACb;AACD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as StandardSchemaV1 } from "../index-CeEtxDmK.cjs";
|
|
2
2
|
import { r as Function } from "../index-nBQT1tAh.cjs";
|
|
3
3
|
import { t as HttpMethod } from "../types-DMuSQeLL.cjs";
|
|
4
|
-
import { c as EndpointSchemas, i as Endpoint } from "../Endpoint-
|
|
4
|
+
import { c as EndpointSchemas, i as Endpoint } from "../Endpoint-CrhoafsT.cjs";
|
|
5
5
|
import { t as Queue } from "../Queue-Bhzi2WQC.cjs";
|
|
6
6
|
import { t as Subscriber } from "../Subscriber-DQCaiOXF.cjs";
|
|
7
7
|
import { t as KyselyDatabase } from "../kysely-CXi49zc2.cjs";
|
|
@@ -186,20 +186,77 @@ type TestSubscriberRequest<TEventPublisher extends EventPublisher<any> | undefin
|
|
|
186
186
|
services?: ServiceRecord<TServices>;
|
|
187
187
|
};
|
|
188
188
|
//#endregion
|
|
189
|
+
//#region src/testing/manifest.d.ts
|
|
190
|
+
/**
|
|
191
|
+
* The test manifest: what `gkm test` knows about an app, written down for the
|
|
192
|
+
* suite it starts.
|
|
193
|
+
*
|
|
194
|
+
* `gkm test` discovers the constructs, reconciles the test stage and resolves
|
|
195
|
+
* its environment — then, until this existed, threw all of it away and left a
|
|
196
|
+
* test to declare it again by hand. The manifest keeps it: which construct and
|
|
197
|
+
* endpoint is exported where, and the environment the test stage resolved,
|
|
198
|
+
* under the keys the constructs themselves derive. A feature test is built from
|
|
199
|
+
* it, so nothing a test says can drift from what the app declares.
|
|
200
|
+
*/
|
|
201
|
+
/** Where an export lives: what an import statement has to say. */
|
|
202
|
+
interface TestManifestSource {
|
|
203
|
+
/** Absolute path to the module. */
|
|
204
|
+
file: string;
|
|
205
|
+
/** The name it is exported as. */
|
|
206
|
+
export: string;
|
|
207
|
+
}
|
|
208
|
+
interface TestManifest {
|
|
209
|
+
/** The stage the environment was resolved for — `test`. */
|
|
210
|
+
stage: string;
|
|
211
|
+
/** Every construct the app declares, by id. */
|
|
212
|
+
constructs: Record<string, {
|
|
213
|
+
kind: string;
|
|
214
|
+
source: TestManifestSource;
|
|
215
|
+
}>;
|
|
216
|
+
/** Every endpoint, and the surface that serves it. */
|
|
217
|
+
endpoints: {
|
|
218
|
+
surface: string;
|
|
219
|
+
source: TestManifestSource;
|
|
220
|
+
}[];
|
|
221
|
+
/**
|
|
222
|
+
* The test stage's environment — reconcile's output, keyed as the
|
|
223
|
+
* constructs derive their keys.
|
|
224
|
+
*/
|
|
225
|
+
env: Record<string, string>;
|
|
226
|
+
}
|
|
227
|
+
/** The environment variable `gkm test` names the manifest in. */
|
|
228
|
+
export declare const TEST_MANIFEST_ENV = "GKM_TEST_MANIFEST";
|
|
229
|
+
/**
|
|
230
|
+
* Read a test manifest: from a path, a `file:` URL, or — given nothing — the
|
|
231
|
+
* one `gkm test` named in `GKM_TEST_MANIFEST`.
|
|
232
|
+
*/
|
|
233
|
+
export declare function loadTestManifest(from?: string | URL): TestManifest;
|
|
234
|
+
/** A feature test ran without a manifest to build itself from. */
|
|
235
|
+
export declare class NoTestManifest extends Error {
|
|
236
|
+
constructor();
|
|
237
|
+
}
|
|
238
|
+
//#endregion
|
|
189
239
|
//#region src/testing/featureTest.d.ts
|
|
190
|
-
interface FeatureTestOptions<TBrowser extends Browser
|
|
240
|
+
interface FeatureTestOptions<TBrowser extends Browser> {
|
|
241
|
+
/**
|
|
242
|
+
* What the app declares and the environment its test stage resolved.
|
|
243
|
+
* Defaults to the manifest `gkm test` names in `GKM_TEST_MANIFEST`.
|
|
244
|
+
*/
|
|
245
|
+
manifest?: TestManifest;
|
|
191
246
|
/**
|
|
192
|
-
* The
|
|
193
|
-
*
|
|
194
|
-
*
|
|
247
|
+
* The app's modules, already imported, by the absolute path the manifest
|
|
248
|
+
* records for them. The generated harness imports them statically, from
|
|
249
|
+
* inside the app, so they resolve the way the app's own code does — its
|
|
250
|
+
* tsconfig paths included. A module not here is imported by path.
|
|
195
251
|
*/
|
|
196
|
-
modules
|
|
197
|
-
/** The
|
|
198
|
-
database?: KyselyDatabase<DB>;
|
|
199
|
-
/** The browser each test gets — the app's subclass, with its clients. */
|
|
252
|
+
modules?: Readonly<Record<string, Record<string, unknown>>>;
|
|
253
|
+
/** The browser each test gets — the generated one, with the app's clients. */
|
|
200
254
|
browser?: new () => TBrowser;
|
|
201
|
-
/**
|
|
202
|
-
|
|
255
|
+
/**
|
|
256
|
+
* The database a test receives as `db`, by construct id. Defaults to the
|
|
257
|
+
* one the app's endpoints name with `.database()`.
|
|
258
|
+
*/
|
|
259
|
+
database?: string;
|
|
203
260
|
}
|
|
204
261
|
interface FeatureContext<TBrowser extends Browser, DB> {
|
|
205
262
|
/** This test's browser, already the global `fetch`. */
|
|
@@ -208,6 +265,31 @@ interface FeatureContext<TBrowser extends Browser, DB> {
|
|
|
208
265
|
db: Kysely<DB>;
|
|
209
266
|
/** The mail sent to an address during this test, read from Mailpit. */
|
|
210
267
|
mailbox: (address: string) => Mailbox;
|
|
268
|
+
/**
|
|
269
|
+
* What this test published to a topic or enqueued on a queue, in order.
|
|
270
|
+
* Nothing is delivered — a subscriber or a worker is tested on its own, by
|
|
271
|
+
* handing it events — so this is where publishing is asserted.
|
|
272
|
+
*/
|
|
273
|
+
published: (channel: {
|
|
274
|
+
id: string;
|
|
275
|
+
}) => PublishedMessage[];
|
|
276
|
+
/**
|
|
277
|
+
* A subscriber, run on its own — handed events rather than delivered them —
|
|
278
|
+
* with this test's services: its databases resolve to this test's
|
|
279
|
+
* transactions, as an endpoint's do.
|
|
280
|
+
*/
|
|
281
|
+
subscriber: <S extends Subscriber<any, any, any, any, any, any>>(subscriber: S) => SubscriberAdaptorOf<S>;
|
|
282
|
+
/** A queue's worker, run on its own with this test's services. */
|
|
283
|
+
queue: <Q extends Queue<any, any, any, any>>(queue: Q) => QueueAdaptorOf<Q>;
|
|
284
|
+
}
|
|
285
|
+
type SubscriberAdaptorOf<S> = S extends Subscriber<infer TServices, infer TLogger, infer OutSchema, infer TEventPublisher, infer TEventPublisherServiceName, infer TSubscribedEvents> ? TestSubscriberAdaptor<TServices, TLogger, OutSchema, TEventPublisher, TEventPublisherServiceName, TSubscribedEvents> : never;
|
|
286
|
+
type QueueAdaptorOf<Q> = Q extends Queue<infer TName, infer TMessage, infer TServices, infer TLogger> ? TestQueueAdaptor<TName, TMessage, TServices, TLogger> : never;
|
|
287
|
+
/** The schema a database construct was declared with — what `db` is typed by. */
|
|
288
|
+
type DatabaseOf<C> = C extends KyselyDatabase<infer DB, any> ? DB : unknown;
|
|
289
|
+
/** One message as it was published: its type and its payload. */
|
|
290
|
+
interface PublishedMessage {
|
|
291
|
+
type: string;
|
|
292
|
+
payload: unknown;
|
|
211
293
|
}
|
|
212
294
|
type FeatureFn<TBrowser extends Browser, DB> = (context: FeatureContext<TBrowser, DB>) => unknown;
|
|
213
295
|
interface FeatureIt<TBrowser extends Browser, DB> {
|
|
@@ -215,7 +297,7 @@ interface FeatureIt<TBrowser extends Browser, DB> {
|
|
|
215
297
|
only(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;
|
|
216
298
|
skip(name: string, fn: FeatureFn<TBrowser, DB>, timeout?: number): void;
|
|
217
299
|
}
|
|
218
|
-
export declare function featureTest<TBrowser extends Browser = Browser, DB = unknown>(options
|
|
300
|
+
export declare function featureTest<TBrowser extends Browser = Browser, DB = unknown>(options?: FeatureTestOptions<TBrowser>): FeatureIt<TBrowser, DB>;
|
|
219
301
|
/** A request reached an in-process server without a test to belong to. */
|
|
220
302
|
export declare class UnknownTestContext extends Error {
|
|
221
303
|
readonly url: string;
|
|
@@ -226,6 +308,12 @@ export declare class UnknownTestContext extends Error {
|
|
|
226
308
|
export declare class NoInbox extends Error {
|
|
227
309
|
constructor();
|
|
228
310
|
}
|
|
311
|
+
/** `featureTest({ database })` named a database the app does not declare. */
|
|
312
|
+
export declare class UnknownDatabase extends Error {
|
|
313
|
+
readonly id: string;
|
|
314
|
+
readonly declared: string[];
|
|
315
|
+
constructor(id: string, declared: string[]);
|
|
316
|
+
}
|
|
229
317
|
//#endregion
|
|
230
|
-
export { type CreateMswHandlersOptions, type CreateMswHandlersResult, type FeatureContext, type FeatureIt, type FeatureTestOptions, type RegisterContextOptions, TEST_CONTEXT_HEADER };
|
|
318
|
+
export { type CreateMswHandlersOptions, type CreateMswHandlersResult, type DatabaseOf, type FeatureContext, type FeatureIt, type FeatureTestOptions, type RegisterContextOptions, TEST_CONTEXT_HEADER, type TestManifest, type TestManifestSource };
|
|
231
319
|
//# sourceMappingURL=testing.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.d.cts","names":["TestBrowser"],"sources":["../../src/endpoints/MswEndpointAdaptor.ts","../../src/endpoints/TestEndpointAdaptor.ts","../../src/functions/TestFunctionAdaptor.ts","../../src/queue/TestQueueAdaptor.ts","../../src/subscribers/TestSubscriberAdaptor.ts","../../src/testing/featureTest.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAyDiB;;EAEhB;;;;;;;UAQgB;;EAEhB,WAAW;;EAEX;;EAEA,YAAY;;EAEZ;;;;;UAiBgB;;EAEhB,UAAU;;EAEV,kBAAkB,YAAY,SAAS;;;;;;;;;;;;;;;;;wBAkBxB,kBACf,WAAW,0CACX,SAAS,2BACP;;;KC9ES,iBAAiB;EAC5B,MAAM;EACN;EACA,SAAS;;qBAwCG,oBACZ,uBACA,gBAAgB,YAChB,eAAe,sBACf,mBAAmB,0CACnB,kBAAkB,gBAClB,gBAAgB,SAAS,QACzB,oBACA,wBAAwB,6CACxB,oDACA,sBAAsB,sCACtB,kDACA,qBAAqB,mCAAmC,kCAIxD,uBACA;mBAyCkB;UAgBT;SAvDF,0BACN,uBACA,gBAAgB,YAChB,eAAe,sBACf,mBAAmB,0CACnB,kBAAkB,gBAClB,gBAAgB,SAAS,QACzB,oBACA,wBAAwB,6CACxB,oDACA,sBAAsB,sCACtB,kDACA,qBAAqB,mCAAmC,kCAIxD,uBACA,8CAEA,WAAW,SACV,QACA,SACA,QACA,YACA,WACA,SACA,UACA,iBACA,4BACA,eACA,0BACA,cACA,WACA;EAKF,YACkB,UAAU,SAC1B,QACA,SACA,QACA,YACA,WACA,SACA,UACA,iBACA,4BACA,eACA,0BACA,cACA,WACA,uBAEO,mBAAkB;EAKrB,YACL,KAAK,mBACJ,QACA,WACA,iBACA,4BAC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mB,kBACpC,kBAAkB,gBAClB,gBAAgB,SAAS;mBAOP;UACT;SANF;EAIP,YACkB,OAAO,MAAM,OAAO,UAAU,WAAW,UAClD,mBAAkB;EAGrB,OACL,SAAS,iBAAiB,UAAU,aAClC;;KAsBQ,iBACX,iBAAiB,mBAAmB,kBACpC,kBAAkB;EAElB,UAAU,oBAAoB;EAC9B,WAAW,cAAc;;;;KC/CrB,qBACJ,mBAAmB,iCACnB,6BACG,mBAAmB,sBACpB,QAAQ,wBAAwB;EAAe,MAAM;;qBAG3C,sBACZ,kBAAkB,gBAClB,gBAAgB,SAAS,QACzB,kBAAkB,0CAClB,wBAAwB,6CACxB,oDACA,0BACC,wBAAwB,6BAA6B,wBAAwB;mBAO5D;UAQT;SAbF;EAIP,YACkB,YAAY,WAC5B,WACA,SACA,WACA,iBACA,4BACA,oBAEO,mBAAkB;EAGrB,OACL,SAAS,sBACR,iBACA,mBACA,aAEC,QAAQ,oBAAoB;UA4DvB;;KAaG,sBACX,wBAAwB,6CACxB,sCACA,kBAAkB;EAElB,QAAQ,qBAAqB,iBAAiB;EAC9C,WAAW,cAAc;;;;
|
|
1
|
+
{"version":3,"file":"testing.d.cts","names":["TestBrowser"],"sources":["../../src/endpoints/MswEndpointAdaptor.ts","../../src/endpoints/TestEndpointAdaptor.ts","../../src/functions/TestFunctionAdaptor.ts","../../src/queue/TestQueueAdaptor.ts","../../src/subscribers/TestSubscriberAdaptor.ts","../../src/testing/manifest.ts","../../src/testing/featureTest.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAyDiB;;EAEhB;;;;;;;UAQgB;;EAEhB,WAAW;;EAEX;;EAEA,YAAY;;EAEZ;;;;;UAiBgB;;EAEhB,UAAU;;EAEV,kBAAkB,YAAY,SAAS;;;;;;;;;;;;;;;;;wBAkBxB,kBACf,WAAW,0CACX,SAAS,2BACP;;;KC9ES,iBAAiB;EAC5B,MAAM;EACN;EACA,SAAS;;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