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

pmcelhaney / counterfact / 8806963966

23 Apr 2024 08:41PM UTC coverage: 86.965% (+0.2%) from 86.733%
8806963966

Pull #865

github

pmcelhaney
replace .then() with await
Pull Request #865: reload everything when a file changes

893 of 987 branches covered (90.48%)

Branch coverage included in aggregate %.

10 of 19 new or added lines in 1 file covered. (52.63%)

19 existing lines in 2 files now uncovered.

2930 of 3409 relevant lines covered (85.95%)

44.03 hits per line

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

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

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

2✔
9
import { type Context, ContextRegistry } from "./context-registry.js";
2✔
10
import { determineModuleKind } from "./determine-module-kind.js";
2✔
11
import type { Module, Registry } from "./registry.js";
2✔
12
import { uncachedImport } from "./uncached-import.js";
2✔
13

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

2✔
16
const debug = createDebug("counterfact:typescript-generator:module-loader");
2✔
17

2✔
18
interface ContextModule {
2✔
19
  Context: Context;
2✔
20
}
2✔
21

2✔
22
function isContextModule(
8✔
23
  module: ContextModule | Module,
8✔
24
): module is ContextModule {
8✔
25
  return "Context" in module && typeof module.Context === "function";
8✔
26
}
8✔
27

2✔
28
export class ModuleLoader extends EventTarget {
2✔
29
  private readonly basePath: string;
12✔
30

12✔
31
  public readonly registry: Registry;
12✔
32

12✔
33
  private watcher: FSWatcher | undefined;
12✔
34

12✔
35
  private readonly contextRegistry: ContextRegistry;
12✔
36

12✔
37
  private uncachedImport: (moduleName: string) => Promise<unknown> =
12✔
38
    // eslint-disable-next-line @typescript-eslint/require-await
12✔
39
    async function (moduleName: string) {
12✔
40
      throw new Error(`uncachedImport not set up; importing ${moduleName}`);
×
41
    };
×
42

12✔
43
  public constructor(
12✔
44
    basePath: string,
12✔
45
    registry: Registry,
12✔
46
    contextRegistry = new ContextRegistry(),
12✔
47
  ) {
12✔
48
    super();
12✔
49
    this.basePath = basePath.replaceAll("\\", "/");
12✔
50
    this.registry = registry;
12✔
51
    this.contextRegistry = contextRegistry;
12✔
52
  }
12✔
53

12✔
54
  public async watch(): Promise<void> {
12✔
55
    this.watcher = watch(`${this.basePath}/**/*.{js,mjs,ts,mts}`).on(
6✔
56
      "all",
6✔
57
      // eslint-disable-next-line max-statements, @typescript-eslint/no-misused-promises
6✔
58
      async (eventName: string, pathNameOriginal: string) => {
6✔
59
        const pathName = pathNameOriginal.replaceAll("\\", "/");
8✔
60

8✔
61
        if (pathName.includes("$.context") && eventName === "add") {
8!
62
          process.stdout.write(
×
63
            `\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`,
×
UNCOV
64
          );
×
65
          return;
×
UNCOV
66
        }
×
67

8✔
68
        if (!["add", "change", "unlink"].includes(eventName)) {
8!
UNCOV
69
          return;
×
UNCOV
70
        }
×
71

8✔
72
        const parts = nodePath.parse(pathName.replace(this.basePath, ""));
8✔
73
        const url = `/${parts.dir}/${parts.name}`
8✔
74
          .replaceAll("\\", "/")
8✔
75
          .replaceAll(/\/+/gu, "/");
8✔
76

8✔
77
        if (eventName === "unlink") {
8✔
78
          this.registry.remove(url);
2✔
79
          this.dispatchEvent(new Event("remove"));
2✔
80
        }
2✔
81

8✔
82
        debug("importing module: %s", pathName);
8✔
83
        const endpoint = await this.uncachedImport(pathName);
8✔
84

8✔
85
        this.dispatchEvent(new Event(eventName));
8✔
86

8✔
87
        if (pathName.includes("_.context")) {
8!
NEW
UNCOV
88
          this.contextRegistry.update(
×
NEW
89
            parts.dir,
×
NEW
UNCOV
90

×
NEW
91
            // @ts-expect-error TS says Context has no constructable signatures but that's not true?
×
NEW
UNCOV
92
            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/consistent-type-assertions
×
NEW
93
            new (endpoint as ContextModule).Context(),
×
NEW
94
          );
×
NEW
95
          return;
×
NEW
UNCOV
96
        }
×
97

8✔
98
        // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
8✔
99
        this.registry.add(url, endpoint as Module);
8✔
100
      },
8✔
101
    );
6✔
102
    await once(this.watcher, "ready");
6✔
103
  }
6✔
104

12✔
105
  public async stopWatching(): Promise<void> {
12✔
106
    await this.watcher?.close();
6✔
107
  }
6✔
108

12✔
109
  public async load(directory = ""): Promise<void> {
12✔
110
    const moduleKind = await determineModuleKind(this.basePath);
20✔
111

20✔
112
    this.uncachedImport =
20✔
113
      moduleKind === "module" ? uncachedImport : uncachedRequire;
20!
114

20✔
115
    if (
20✔
116
      !existsSync(nodePath.join(this.basePath, directory).replaceAll("\\", "/"))
20✔
117
    ) {
20!
118
      throw new Error(`Directory does not exist ${this.basePath}`);
×
119
    }
×
120

20✔
121
    const files = await fs.readdir(
20✔
122
      nodePath.join(this.basePath, directory).replaceAll("\\", "/"),
20✔
123
      {
20✔
124
        withFileTypes: true,
20✔
125
      },
20✔
126
    );
20✔
127

20✔
128
    const imports = files.flatMap(async (file): Promise<void> => {
20✔
129
      const extension = file.name.split(".").at(-1);
38✔
130

38✔
131
      if (file.isDirectory()) {
38✔
132
        await this.load(
8✔
133
          nodePath.join(directory, file.name).replaceAll("\\", "/"),
8✔
134
        );
8✔
135

8✔
136
        return;
8✔
137
      }
8✔
138

30✔
139
      if (!["js", "mjs", "mts", "ts"].includes(extension ?? "")) {
38✔
140
        return;
14✔
141
      }
14✔
142

16✔
143
      const fullPath = nodePath
16✔
144
        .join(this.basePath, directory, file.name)
16✔
145
        .replaceAll("\\", "/");
16✔
146
      await this.loadEndpoint(fullPath, directory, file);
16✔
147
    });
16✔
148

20✔
149
    await Promise.all(imports);
20✔
150
  }
20✔
151

12✔
152
  private async loadEndpoint(
12✔
153
    fullPath: string,
16✔
154
    directory: string,
16✔
155
    file: Dirent,
16✔
156
  ) {
16✔
157
    try {
16✔
158
      // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
16✔
159
      const endpoint: ContextModule | Module = (await this.uncachedImport(
16✔
160
        fullPath,
16✔
161
      )) as ContextModule | Module;
16✔
162

16✔
163
      if (file.name.includes("_.context")) {
16✔
164
        if (isContextModule(endpoint)) {
8✔
165
          this.contextRegistry.add(
8✔
166
            `/${directory.replaceAll("\\", "/")}`,
8✔
167

8✔
168
            // @ts-expect-error TS says Context has no constructable signatures but that's not true?
8✔
169
            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
8✔
170
            new endpoint.Context(),
8✔
171
          );
8✔
172
        }
8✔
173
      } else {
8✔
174
        const url = `/${nodePath.join(
8✔
175
          directory,
8✔
176
          nodePath.parse(file.name).name,
8✔
177
        )}`
8✔
178
          .replaceAll("\\", "/")
8✔
179
          .replaceAll(/\/+/gu, "/");
8✔
180

8✔
181
        // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
8✔
182
        this.registry.add(url, endpoint as Module);
8✔
183
      }
8✔
184
    } catch (error: unknown) {
16!
UNCOV
185
      if (
×
UNCOV
186
        String(error) ===
×
UNCOV
187
        "SyntaxError: Identifier 'Context' has already been declared"
×
UNCOV
188
      ) {
×
UNCOV
189
        // Not sure why Node throws this error. It doesn't seem to matter.
×
UNCOV
190
        return;
×
UNCOV
191
      }
×
UNCOV
192

×
UNCOV
193
      process.stdout.write(`\nError loading ${fullPath}:\n${String(error)}\n`);
×
UNCOV
194
    }
×
195
  }
16✔
196
}
12✔
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