• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pmcelhaney / counterfact / 23924365346

02 Apr 2026 10:10PM UTC coverage: 85.966% (-0.1%) from 86.092%
23924365346

push

github

web-flow
Merge pull request #1614 from pmcelhaney/copilot/fix-counterfact-crash-on-file-delete

Fix crash when a route file is deleted

1632 of 1837 branches covered (88.84%)

Branch coverage included in aggregate %.

4 of 7 new or added lines in 1 file covered. (57.14%)

8 existing lines in 1 file now uncovered.

5039 of 5923 relevant lines covered (85.08%)

64.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.36
/src/server/module-loader.ts
1
import { once } from "node:events";
2✔
2
import { existsSync } from "node:fs";
2✔
3
import fs from "node:fs/promises";
2✔
4
import nodePath, { basename, dirname } from "node:path";
2✔
5

2✔
6
import { type FSWatcher, watch } from "chokidar";
2✔
7
import createDebug from "debug";
2✔
8

2✔
9
import { CHOKIDAR_OPTIONS } from "./constants.js";
2✔
10
import { type Context, ContextRegistry } from "./context-registry.js";
2✔
11
import { determineModuleKind } from "./determine-module-kind.js";
2✔
12
import { ModuleDependencyGraph } from "./module-dependency-graph.js";
2✔
13
import type { MiddlewareFunction, Module, Registry } from "./registry.js";
2✔
14
import { uncachedImport } from "./uncached-import.js";
2✔
15

2✔
16
const { uncachedRequire } = await import("./uncached-require.cjs");
2✔
17

2✔
18
const debug = createDebug("counterfact:server:module-loader");
2✔
19

2✔
20
import {
2✔
21
  escapePathForWindows,
2✔
22
  unescapePathForWindows,
2✔
23
} from "../util/windows-escape.js";
2✔
24

2✔
25
interface ContextModule {
2✔
26
  Context?: Context;
2✔
27
}
2✔
28

2✔
29
function isContextModule(
18✔
30
  module: ContextModule | Module,
18✔
31
): module is ContextModule {
18✔
32
  return "Context" in module && typeof module.Context === "function";
18✔
33
}
18✔
34

2✔
35
function isMiddlewareModule(
4✔
36
  module: ContextModule | Module,
4✔
37
): module is ContextModule & { middleware: MiddlewareFunction } {
4✔
38
  return (
4✔
39
    "middleware" in module &&
4✔
40
    typeof Object.getOwnPropertyDescriptor(module, "middleware")?.value ===
4✔
41
      "function"
4✔
42
  );
4✔
43
}
4✔
44

2✔
45
export class ModuleLoader extends EventTarget {
2✔
46
  private readonly basePath: string;
2✔
47

28✔
48
  public readonly registry: Registry;
28✔
49

28✔
50
  private watcher: FSWatcher | undefined;
28✔
51

28✔
52
  private readonly contextRegistry: ContextRegistry;
28✔
53

28✔
54
  private readonly dependencyGraph = new ModuleDependencyGraph();
28✔
55

28✔
56
  private readonly uncachedImport: (moduleName: string) => Promise<unknown> =
28✔
57
    async function (moduleName: string) {
28✔
58
      throw new Error(`uncachedImport not set up; importing ${moduleName}`);
×
59
    };
×
60

2✔
61
  public constructor(
2✔
62
    basePath: string,
28✔
63
    registry: Registry,
28✔
64
    contextRegistry = new ContextRegistry(),
28✔
65
  ) {
28✔
66
    super();
28✔
67
    this.basePath = basePath.replaceAll("\\", "/");
28✔
68
    this.registry = registry;
28✔
69
    this.contextRegistry = contextRegistry;
28✔
70
  }
28✔
71

2✔
72
  public async watch(): Promise<void> {
2✔
73
    this.watcher = watch(this.basePath, CHOKIDAR_OPTIONS).on(
6✔
74
      "all",
6✔
75

6✔
76
      (eventName: string, pathNameOriginal: string) => {
6✔
77
        const JS_EXTENSIONS = ["js", "mjs", "cjs", "ts", "mts", "cts"];
4✔
78

4✔
79
        if (
4✔
80
          !JS_EXTENSIONS.some((extension) =>
4✔
81
            pathNameOriginal.endsWith(`.${extension}`),
4✔
82
          )
4✔
83
        )
4✔
84
          return;
4!
85

4✔
86
        const pathName = pathNameOriginal.replaceAll("\\", "/");
4✔
87

4✔
88
        if (pathName.includes("$.context") && eventName === "add") {
4!
89
          process.stdout.write(
×
90
            `\n\n!!! The file at ${pathName} needs a minor update.\n    See https://github.com/pmcelhaney/counterfact/blob/main/docs/context-change.md\n\n\n`,
×
91
          );
×
92

×
93
          return;
×
94
        }
×
95

4✔
96
        if (!["add", "change", "unlink"].includes(eventName)) {
4!
97
          return;
×
98
        }
×
99

4✔
100
        const parts = nodePath.parse(pathName.replace(this.basePath, ""));
4✔
101
        const url = unescapePathForWindows(
4✔
102
          `/${parts.dir}/${parts.name}`
4✔
103
            .replaceAll("\\", "/")
4✔
104
            .replaceAll(/\/+/gu, "/"),
4✔
105
        );
4✔
106

4✔
107
        if (eventName === "unlink") {
4✔
108
          this.registry.remove(url);
4✔
109
          this.dispatchEvent(new Event("remove"));
4✔
110
          return;
4✔
111
        }
4!
UNCOV
112

×
UNCOV
113
        const dependencies = this.dependencyGraph.dependentsOf(pathName);
×
UNCOV
114

×
UNCOV
115
        void this.loadEndpoint(pathName);
×
UNCOV
116

×
UNCOV
117
        for (const dependency of dependencies) {
×
118
          void this.loadEndpoint(dependency);
×
119
        }
×
UNCOV
120
      },
×
121
    );
6✔
122
    await once(this.watcher, "ready");
6✔
123
  }
6✔
124

2✔
125
  public async stopWatching(): Promise<void> {
2✔
126
    await this.watcher?.close();
8✔
127
  }
8✔
128

2✔
129
  public async load(directory = ""): Promise<void> {
2✔
130
    if (
38✔
131
      !existsSync(nodePath.join(this.basePath, directory).replaceAll("\\", "/"))
38✔
132
    ) {
38!
133
      throw new Error(`Directory does not exist ${this.basePath}`);
×
134
    }
×
135

38✔
136
    const files = await fs.readdir(
38✔
137
      nodePath.join(this.basePath, directory).replaceAll("\\", "/"),
38✔
138
      {
38✔
139
        withFileTypes: true,
38✔
140
      },
38✔
141
    );
38✔
142

38✔
143
    const imports = files.flatMap(async (file): Promise<void> => {
38✔
144
      const extension = file.name.split(".").at(-1);
78✔
145

78✔
146
      if (file.isDirectory()) {
78✔
147
        await this.load(
16✔
148
          nodePath.join(directory, file.name).replaceAll("\\", "/"),
16✔
149
        );
16✔
150

16✔
151
        return;
16✔
152
      }
16✔
153

62✔
154
      if (!["cjs", "cts", "js", "mjs", "mts", "ts"].includes(extension ?? "")) {
78✔
155
        return;
28✔
156
      }
28✔
157

34✔
158
      const fullPath = nodePath
34✔
159
        .join(this.basePath, directory, file.name)
34✔
160
        .replaceAll("\\", "/");
34✔
161

34✔
162
      await this.loadEndpoint(escapePathForWindows(fullPath));
34✔
163
    });
34✔
164

38✔
165
    await Promise.all(imports);
38✔
166
  }
38✔
167

2✔
168
  private async loadEndpoint(pathName: string) {
2✔
169
    debug("importing module: %s", pathName);
34✔
170

34✔
171
    const directory = dirname(pathName.slice(this.basePath.length)).replaceAll(
34✔
172
      "\\",
34✔
173
      "/",
34✔
174
    );
34✔
175

34✔
176
    const url = unescapePathForWindows(
34✔
177
      `/${nodePath.join(directory, nodePath.parse(basename(pathName)).name)}`
34✔
178
        .replaceAll("\\", "/")
34✔
179
        .replaceAll(/\/+/gu, "/"),
34✔
180
    );
34✔
181

34✔
182
    debug(`loading pathName from dependencyGraph: ${pathName}`);
34✔
183

34✔
184
    this.dependencyGraph.load(pathName);
34✔
185

34✔
186
    try {
34✔
187
      const doImport =
34✔
188
        (await determineModuleKind(pathName)) === "commonjs"
34!
189
          ? uncachedRequire
×
190
          : uncachedImport;
34✔
191

34✔
192
      const endpoint = (await doImport(pathName).catch((error: unknown) => {
34✔
NEW
193
        console.error(`Failed to import ${pathName}:`, error);
×
UNCOV
194
      })) as ContextModule | Module;
×
195

34✔
196
      if (!endpoint) {
34!
NEW
197
        return;
×
NEW
198
      }
×
199

34✔
200
      this.dispatchEvent(new Event("add"));
34✔
201

34✔
202
      if (
34✔
203
        basename(pathName).startsWith("_.context.") &&
34✔
204
        isContextModule(endpoint)
18✔
205
      ) {
34✔
206
        const loadContext = (path: string) => this.contextRegistry.find(path);
18✔
207

18✔
208
        const contextDir = nodePath.dirname(unescapePathForWindows(pathName));
18✔
209
        const readJson = async (relativePath: string): Promise<unknown> => {
18✔
210
          const absolutePath = nodePath.resolve(contextDir, relativePath);
4✔
211
          let content: string;
4✔
212
          try {
4✔
213
            content = await fs.readFile(absolutePath, "utf8");
4✔
214
          } catch {
4!
215
            throw new Error(
×
216
              `readJson: could not read file at "${absolutePath}" (resolved from "${relativePath}" relative to "${contextDir}")`,
×
217
            );
×
218
          }
×
219
          try {
4✔
220
            return JSON.parse(content) as unknown;
4✔
221
          } catch {
4!
222
            throw new Error(
×
223
              `readJson: file at "${absolutePath}" does not contain valid JSON`,
×
224
            );
×
225
          }
×
226
        };
4✔
227

18✔
228
        this.contextRegistry.update(
18✔
229
          directory,
18✔
230

18✔
231
          // @ts-expect-error TS says Context has no constructable signatures but that's not true?
18✔
232

18✔
233
          new endpoint.Context({
18✔
234
            loadContext,
18✔
235
            readJson,
18✔
236
          }),
18✔
237
        );
18✔
238
        return;
18✔
239
      }
18✔
240

16✔
241
      if (
16✔
242
        basename(pathName).startsWith("_.middleware.") &&
16✔
243
        isMiddlewareModule(endpoint)
4✔
244
      ) {
34✔
245
        this.registry.addMiddleware(
4✔
246
          url.slice(0, url.lastIndexOf("/")) || "/",
4✔
247
          endpoint.middleware,
4✔
248
        );
4✔
249
      }
4✔
250

16✔
251
      if (url === "/index") this.registry.add("/", endpoint as Module);
34✔
252

16✔
253
      debug(`adding "${url}" to registry`);
16✔
254
      this.registry.add(url, endpoint as Module);
16✔
255
    } catch (error: unknown) {
34!
256
      if (
×
257
        String(error) ===
×
258
        "SyntaxError: Identifier 'Context' has already been declared"
×
259
      ) {
×
260
        // Not sure why Node throws this error. It doesn't seem to matter.
×
261
        return;
×
262
      }
×
263

×
264
      process.stdout.write(`\nError loading ${pathName}:\n${String(error)}\n`);
×
265

×
266
      throw error;
×
267
    }
×
268
  }
34✔
269
}
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc