-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathapp.ts
More file actions
304 lines (262 loc) · 9.38 KB
/
app.ts
File metadata and controls
304 lines (262 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import fs, { rm } from "node:fs/promises";
import { createHttpTerminator, type HttpTerminator } from "http-terminator";
import { startRepl as startReplServer } from "./repl/repl.js";
import { createRouteFunction } from "./repl/route-builder.js";
import { adminApiMiddleware } from "./server/admin-api-middleware.js";
import type { Config } from "./server/config.js";
import { ContextRegistry } from "./server/context-registry.js";
import { createKoaApp } from "./server/create-koa-app.js";
import { Dispatcher, type DispatcherRequest } from "./server/dispatcher.js";
import { routesMiddleware } from "./server/koa-middleware.js";
import { loadOpenApiDocument } from "./server/load-openapi-document.js";
import { ModuleLoader } from "./server/module-loader.js";
import { Registry } from "./server/registry.js";
import { ScenarioRegistry } from "./server/scenario-registry.js";
import { Transpiler } from "./server/transpiler.js";
import { CodeGenerator } from "./typescript-generator/code-generator.js";
import { writeScenarioContextType } from "./typescript-generator/generate.js";
import { runtimeCanExecuteErasableTs } from "./util/runtime-can-execute-erasable-ts.js";
import { pathJoin } from "./util/forward-slash-path.js";
export { loadOpenApiDocument } from "./server/load-openapi-document.js";
type Scenario$ = {
context: Record<string, unknown>;
loadContext: (path: string) => Record<string, unknown>;
route: (path: string) => unknown;
routes: Record<string, unknown>;
};
export async function runStartupScenario(
scenarioRegistry: ScenarioRegistry,
contextRegistry: ContextRegistry,
config: Config,
openApiDocument?: Parameters<typeof createRouteFunction>[2],
): Promise<void> {
const indexModule = scenarioRegistry.getModule("index");
if (!indexModule || typeof indexModule["startup"] !== "function") {
return;
}
const scenario$: Scenario$ = {
context: contextRegistry.find("/") as Record<string, unknown>,
loadContext: (path: string) =>
contextRegistry.find(path) as Record<string, unknown>,
route: createRouteFunction(config.port, "localhost", openApiDocument),
routes: {},
};
await (indexModule["startup"] as (ctx: Scenario$) => Promise<void> | void)(
scenario$,
);
}
type MswHandlerMap = {
[key: string]: (request: MockRequest) => Promise<unknown>;
};
const allowedMethods = [
"all",
"head",
"get",
"post",
"put",
"delete",
"patch",
"options",
] as const;
export type MockRequest = DispatcherRequest & { rawPath: string };
const mswHandlers: MswHandlerMap = {};
/**
* Dispatches a single MSW (Mock Service Worker) intercepted request to the
* matching Counterfact route handler registered via {@link createMswHandlers}.
*
* @param request - The intercepted request, including the HTTP method, path,
* headers, query, body, and a `rawPath` that preserves the original URL
* before base-path stripping.
* @returns The response produced by the matching handler, or a 404 object when
* no handler has been registered for the given method and path.
*/
export async function handleMswRequest(request: MockRequest) {
const { method, rawPath } = request;
const handler = mswHandlers[`${method}:${rawPath}`];
if (handler) {
return handler(request);
}
console.warn(`No handler found for ${method} ${rawPath}`);
return { error: `No handler found for ${method} ${rawPath}`, status: 404 };
}
/**
* Loads an OpenAPI document, registers all routes from it as MSW handlers, and
* returns the list of registered routes so callers (e.g. Vitest Browser mode)
* can mount them on their own request-interception layer.
*
* @param config - Counterfact configuration; `openApiPath` and `basePath` are
* the most important fields for this function.
* @param ModuleLoaderClass - Injectable module-loader constructor, primarily
* used in tests to substitute a test-friendly implementation.
* @returns An array of `{ method, path }` objects describing every registered
* MSW handler.
*/
export async function createMswHandlers(
config: Config,
ModuleLoaderClass = ModuleLoader,
) {
// TODO: For some reason the Vitest Custom Commands needed by Vitest Browser mode fail on fs.readFile when they are called from the nested loadOpenApiDocument function.
// If we "pre-read" the file here it works. This is a workaround to avoid the issue.
await fs.readFile(config.openApiPath);
const openApiDocument = await loadOpenApiDocument(config.openApiPath);
const modulesPath = config.basePath;
const compiledPathsDirectory = pathJoin(modulesPath, ".cache");
const registry = new Registry();
const contextRegistry = new ContextRegistry();
const dispatcher = new Dispatcher(
registry,
contextRegistry,
openApiDocument,
config,
);
const moduleLoader = new ModuleLoaderClass(
compiledPathsDirectory,
registry,
contextRegistry,
);
await moduleLoader.load();
const routes = registry.routes;
const handlers = routes.flatMap((route) => {
const { methods, path } = route;
return Object.keys(methods)
.filter((method) =>
allowedMethods.includes(
method.toLowerCase() as (typeof allowedMethods)[number],
),
)
.map((method) => {
const lowerMethod = method.toLowerCase();
const apiPath = `${openApiDocument.basePath ?? ""}${path.replaceAll("{", ":").replaceAll("}", "")}`;
const handler = async (request: MockRequest) => {
return await dispatcher.request(request);
};
mswHandlers[`${method}:${apiPath}`] = handler;
return { method: lowerMethod, path: apiPath };
});
});
return handlers;
}
/**
* Creates and configures a full Counterfact server instance.
*
* Sets up the route registry, context registry, scenario registry, code
* generator, transpiler, module loader, Koa application, and OpenAPI watcher.
* The returned object exposes handles for starting the server, stopping it, and
* launching the interactive REPL.
*
* @param config - Runtime configuration (port, paths, feature flags, etc.).
* @returns An object containing the configured sub-systems and two entry-point
* functions:
* - `start(options)` — generates/watches code and optionally starts the HTTP
* server; returns a `stop()` handle.
* - `startRepl()` — launches the interactive Node.js REPL connected to the
* live server state.
*/
export async function counterfact(config: Config) {
const modulesPath = config.basePath;
const nativeTs = await runtimeCanExecuteErasableTs();
const compiledPathsDirectory = pathJoin(
modulesPath,
nativeTs ? "routes" : ".cache",
);
if (!nativeTs) {
await rm(compiledPathsDirectory, { force: true, recursive: true });
}
const registry = new Registry();
const contextRegistry = new ContextRegistry();
const scenarioRegistry = new ScenarioRegistry();
const codeGenerator = new CodeGenerator(
config.openApiPath,
config.basePath,
config.generate,
);
const openApiDocument =
config.openApiPath === "_"
? undefined
: await loadOpenApiDocument(config.openApiPath);
const dispatcher = new Dispatcher(
registry,
contextRegistry,
openApiDocument,
config,
);
const transpiler = new Transpiler(
pathJoin(modulesPath, "routes"),
compiledPathsDirectory,
"commonjs",
);
const moduleLoader = new ModuleLoader(
compiledPathsDirectory,
registry,
contextRegistry,
pathJoin(modulesPath, "scenarios"),
scenarioRegistry,
);
contextRegistry.addEventListener("context-changed", () => {
void writeScenarioContextType(modulesPath);
});
const middleware = routesMiddleware(dispatcher, config);
const adminMiddleware = config.startAdminApi
? adminApiMiddleware(registry, contextRegistry, config)
: undefined;
const koaApp = createKoaApp(middleware, config, adminMiddleware);
async function start(options: Config) {
const { generate, startServer, watch, buildCache } = options;
if (config.openApiPath !== "_" && (generate.routes || generate.types)) {
await codeGenerator.generate();
}
if (config.openApiPath !== "_" && (watch.routes || watch.types)) {
await codeGenerator.watch();
}
let httpTerminator: HttpTerminator | undefined;
if (startServer) {
await openApiDocument?.watch();
if (!nativeTs) {
await transpiler.watch();
}
await moduleLoader.load();
await moduleLoader.watch();
await runStartupScenario(
scenarioRegistry,
contextRegistry,
config,
openApiDocument,
);
const server = koaApp.listen({
port: config.port,
});
httpTerminator = createHttpTerminator({
server,
});
} else if (buildCache) {
// If we are not starting the server, we still want to transpile and load modules
await transpiler.watch();
await transpiler.stopWatching();
}
return {
async stop() {
await codeGenerator.stopWatching();
await transpiler.stopWatching();
await moduleLoader.stopWatching();
await openApiDocument?.stopWatching();
await httpTerminator?.terminate();
},
};
}
return {
contextRegistry,
koaApp,
routesMiddleware: middleware,
registry,
start,
startRepl: () =>
startReplServer(
contextRegistry,
registry,
config,
undefined, // use the default print function (stdout)
openApiDocument,
scenarioRegistry,
),
};
}