-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmodule-loader.test.ts
More file actions
655 lines (508 loc) · 20.3 KB
/
Copy pathmodule-loader.test.ts
File metadata and controls
655 lines (508 loc) · 20.3 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/* eslint-disable @typescript-eslint/no-explicit-any */
import { once } from "node:events";
import { usingTemporaryFiles } from "using-temporary-files";
import { ContextRegistry } from "../../src/server/context-registry.js";
import { ModuleLoader } from "../../src/server/module-loader.js";
import { MiddlewareFunction, Registry } from "../../src/server/registry.js";
describe("a module loader", () => {
it("finds a file and adds it to the registry", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"a/b/c.js",
`export function GET() {
return {
body: "GET from a/b/c"
};
}`,
);
await $.add(
"hello.js",
`
export function GET() {
return {
body: "hello"
};
}`,
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path(""), registry);
await loader.load();
expect(registry.exists("GET", "/hello")).toBe(true);
expect(registry.exists("POST", "/hello")).toBe(false);
expect(registry.exists("GET", "/goodbye")).toBe(false);
expect(registry.exists("GET", "/a/b/c")).toBe(true);
});
});
it("maps /index to /", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"index.js",
`export function GET() {
return {
body: "GET from a/b/c"
};
}`,
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path(""), registry);
await loader.load();
expect(registry.exists("GET", "/index")).toBe(true);
expect(registry.exists("GET", "/")).toBe(true);
});
});
it("updates the registry when a file is deleted", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"delete-me.js",
'export function GET() { return { body: "Goodbye" }; }',
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path("."), registry);
await loader.load();
await loader.watch();
expect(registry.exists("GET", "/delete-me")).toBe(true);
await $.remove("delete-me.js");
await once(loader, "remove");
expect(registry.exists("GET", "/delete-me")).toBe(false);
await loader.stopWatching();
});
});
it("does not crash when a context file is deleted", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("_.context.js", "export class Context { value = 42 }");
await $.add(
"hello.js",
'export function GET() { return { body: "hello" }; }',
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path("."), registry);
await loader.load();
await loader.watch();
await $.remove("_.context.js");
await once(loader, "remove");
// Should not crash and the route should still be accessible
expect(registry.exists("GET", "/hello")).toBe(true);
await loader.stopWatching();
});
});
it("ignores files with the wrong file extension", async () => {
await usingTemporaryFiles(async ($) => {
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path("."), registry);
await $.add(
"module.js",
'export function GET() { return { body: "hello" }; }',
);
await $.add("package.json", '{"type": "module"}');
await $.add("README.md", "readme");
await loader.load();
await loader.watch();
await $.add("other.txt", "should not be loaded");
expect(registry.exists("GET", "/module")).toBe(true);
expect(registry.exists("GET", "/READMEx")).toBe(false);
expect(registry.exists("GET", "/other")).toBe(false);
expect(registry.exists("GET", "/types")).toBe(false);
await loader.stopWatching();
});
});
// This should work but I can't figure out how to break the
// module cache when running through Jest (which uses the
// experimental module API).
it.skip("updates the registry when a file is changed", async () => {
await usingTemporaryFiles(async ($) => {
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path("."), registry);
await $.add(
"change.js",
'export function GET(): { body } { return { body: "before change" }; }',
);
await $.add("package.json", '{ "type": "module" }');
await loader.watch();
await $.add(
"change.js",
'export function GET() { return { body: "after change" }; }',
);
await once(loader, "change");
const response = registry.endpoint(
"GET",
"/change",
// @ts-expect-error - not going to create a whole context object for a test
)({ headers: {}, matchedPath: "", path: {}, query: {} });
// @ts-expect-error - TypeScript doesn't know that the response will have a body property
expect(response.body).toBe("after change");
expect(registry.exists("GET", "/late/addition")).toBe(true);
await loader.stopWatching();
});
});
it("finds a context and adds it to the context registry", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("_.context.js", 'export class Context { name = "main"};');
await $.add(
"hello/_.context.js",
'export class Context { name = "hello"};',
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
expect(contextRegistry.find("/hello").name).toBe("hello");
expect(contextRegistry.find("/hello/world").name).toBe("hello");
expect(contextRegistry.find("/some/other/path").name).toBe("main");
});
});
it("finds a middleware and adds it to the registry", async () => {
const names = new Map();
class MiddlewareExposingRegistry extends Registry {
public addMiddleware(url: string, callback: MiddlewareFunction): void {
names.set(
url,
// @ts-expect-error not passing arguments to the callback
callback(),
);
}
}
await usingTemporaryFiles(async ($) => {
await $.add(
"_.middleware.js",
'export function middleware() { return "root"; }',
);
await $.add(
"hello/_.middleware.js",
'export function middleware() { return "hello"; }',
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new MiddlewareExposingRegistry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
expect(names.get("/")).toBe("root");
expect(names.get("/hello")).toBe("hello");
});
});
it("provides the parent context if the local _.context.ts doesn't export a default", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("_.context.js", "export class Context { value = 0 }");
await $.add(
"hello/_.context.js",
"export class Context { value = 100 }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
const rootContext = contextRegistry.find("/");
const helloContext = contextRegistry.find("/hello");
rootContext.value = 1;
helloContext.value = 101;
expect(contextRegistry.find("/").value).toBe(1);
expect(contextRegistry.find("/other").value).toBe(1);
expect(contextRegistry.find("/hello").value).toBe(101);
expect(contextRegistry.find("/hello/world").value).toBe(101);
});
});
it("provides the loadContext helper for accessing nested contexts", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"_.context.js",
"export class Context { constructor({loadContext}) { this.loadContext = loadContext } }",
);
await $.add("a/_.context.js", "export class Context { name = 'a' }");
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
expect(rootContext?.loadContext("/a")?.name).toBe("a");
});
});
it("provides readJson for reading JSON files relative to the context file", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("data.json", '{"name": "test", "value": 42}');
await $.add(
"_.context.js",
"export class Context { constructor({ readJson }) { this.readJson = readJson; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
const data = await rootContext.readJson("./data.json");
expect(data).toEqual({ name: "test", value: 42 });
});
});
it("resolves readJson paths relative to the context file's directory", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("shared/data.json", '{"shared": true}');
await $.add(
"sub/_.context.js",
"export class Context { constructor({ readJson }) { this.readJson = readJson; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
const subContext = contextRegistry.find("/sub") as any;
const data = await subContext.readJson("../shared/data.json");
expect(data).toEqual({ shared: true });
});
});
it("passes openApiDocument to the Context constructor", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"_.context.js",
"export class Context { constructor({ openApiDocument }) { this.openApiDocument = openApiDocument; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const openApiDocument = { paths: { "/hello": {} } };
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
undefined,
undefined,
openApiDocument,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
expect(rootContext?.openApiDocument.paths).toEqual({ "/hello": {} });
});
});
it("defaults openApiDocument to an empty object when none is provided", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"_.context.js",
"export class Context { constructor({ openApiDocument }) { this.openApiDocument = openApiDocument; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
expect(rootContext?.openApiDocument).toBeDefined();
expect(typeof rootContext?.openApiDocument).toBe("object");
});
});
it("reflects in-place document updates through the proxy", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"_.context.js",
"export class Context { constructor({ openApiDocument }) { this.openApiDocument = openApiDocument; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const openApiDocument: { paths: Record<string, unknown> } = {
paths: {},
};
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
undefined,
undefined,
openApiDocument,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
const capturedReference = rootContext?.openApiDocument;
// Simulate what OpenApiDocument.load() does on reload: mutate the
// underlying object in-place, bypassing the read-only proxy
openApiDocument.paths = { "/added": {} };
expect(rootContext?.openApiDocument).toBe(capturedReference);
expect(rootContext?.openApiDocument.paths).toEqual({ "/added": {} });
});
});
it("proxy reflects mutated document properties", async () => {
await usingTemporaryFiles(async ($) => {
await $.add(
"_.context.js",
"export class Context { constructor({ openApiDocument }) { this.openApiDocument = openApiDocument; } }",
);
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const contextRegistry: ContextRegistry = new ContextRegistry();
const openApiDocument: { paths: Record<string, unknown> } = {
paths: { "/hello": {} },
};
const loader: ModuleLoader = new ModuleLoader(
$.path("."),
registry,
contextRegistry,
undefined,
undefined,
openApiDocument,
);
await loader.load();
const rootContext = contextRegistry.find("/") as any;
// Capture the proxy reference — it should remain stable
const capturedReference = rootContext?.openApiDocument;
// Simulate what OpenApiDocument.load() does on reload: mutate in-place
openApiDocument.paths = { "/goodbye": {} };
// The proxy reference is stable
expect(rootContext?.openApiDocument).toBe(capturedReference);
// But the data it reads reflects the mutated document
expect(rootContext?.openApiDocument.paths).toEqual({ "/goodbye": {} });
expect(rootContext?.openApiDocument.paths["/hello"]).toBeUndefined();
});
});
// can't test because I can't get Jest to refresh modules
it.skip("updates the registry when a dependency is updated", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("package.json", '{ "type": "module" }');
await $.add("x.js", 'export const x = "original";');
await $.add(
"main.js",
'import { x } from "./x.js"; export function GET() { return x; }',
);
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path("."), registry);
await loader.load();
await loader.watch();
// @ts-expect-error - not going to create a whole request object for a test
const response = await registry.endpoint("GET", "/main")({});
await $.add("x.js", 'export const x = "changed";');
await once(loader, "add");
expect(response).toEqual("changed");
await loader.stopWatching();
});
});
it("registers a 500 handler for an ESM route file with a syntax error", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("bad-syntax.js", "this is not valid javascript @@@");
await $.add("package.json", '{ "type": "module" }');
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path(""), registry);
await loader.load();
expect(registry.exists("GET", "/bad-syntax")).toBe(true);
// @ts-expect-error - not going to create a whole request object for a test
const response = await registry.endpoint("GET", "/bad-syntax")({});
expect(response?.status).toBe(500);
expect(response?.body).toContain("bad-syntax.js");
});
});
it("registers a 500 handler for a CJS route file with a syntax error", async () => {
await usingTemporaryFiles(async ($) => {
await $.add("bad-syntax.cjs", "this is not valid javascript @@@");
const registry: Registry = new Registry();
const loader: ModuleLoader = new ModuleLoader($.path(""), registry);
await loader.load();
expect(registry.exists("GET", "/bad-syntax")).toBe(true);
// @ts-expect-error - not going to create a whole request object for a test
const response = await registry.endpoint("GET", "/bad-syntax")({});
expect(response?.status).toBe(500);
expect(response?.body).toContain("bad-syntax.cjs");
expect(response?.body).toContain("syntax error");
});
});
});
describe("ModuleLoader scenario loading", () => {
it("loads scenario files into the ScenarioRegistry on load()", async () => {
const { ScenarioRegistry } =
await import("../../src/server/scenario-registry.js");
await usingTemporaryFiles(async ($) => {
await $.add("routes/package.json", '{ "type": "module" }');
await $.add(
"scenarios/index.js",
`export function soldPets() {}
export function resetAll() {}
export const notAFunction = 42;`,
);
await $.add("scenarios/package.json", '{ "type": "module" }');
const registry = new Registry();
const scenarioRegistry = new ScenarioRegistry();
const loader = new ModuleLoader(
$.path("routes"),
registry,
undefined,
$.path("scenarios"),
scenarioRegistry,
);
await loader.load();
const names = scenarioRegistry.getExportedFunctionNames("index");
expect(names).toContain("soldPets");
expect(names).toContain("resetAll");
// Non-functions are still stored but getExportedFunctionNames filters them
expect(names).not.toContain("notAFunction");
});
});
it("stores a nested scenario file under a slash-delimited key", async () => {
const { ScenarioRegistry } =
await import("../../src/server/scenario-registry.js");
await usingTemporaryFiles(async ($) => {
await $.add("routes/package.json", '{ "type": "module" }');
await $.add("scenarios/pets/index.js", `export function sold() {}`);
await $.add("scenarios/pets/package.json", '{ "type": "module" }');
const registry = new Registry();
const scenarioRegistry = new ScenarioRegistry();
const loader = new ModuleLoader(
$.path("routes"),
registry,
undefined,
$.path("scenarios"),
scenarioRegistry,
);
await loader.load();
const names = scenarioRegistry.getExportedFunctionNames("pets/index");
expect(names).toContain("sold");
});
});
it("does not throw when the scenarios directory does not exist", async () => {
const { ScenarioRegistry } =
await import("../../src/server/scenario-registry.js");
await usingTemporaryFiles(async ($) => {
await $.add("routes/package.json", '{ "type": "module" }');
const registry = new Registry();
const scenarioRegistry = new ScenarioRegistry();
const loader = new ModuleLoader(
$.path("routes"),
registry,
undefined,
$.path("scenarios"), // does not exist
scenarioRegistry,
);
await expect(loader.load()).resolves.toBeUndefined();
expect(scenarioRegistry.getFileKeys()).toHaveLength(0);
});
});
});