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

pmcelhaney / counterfact / 9359953006

04 Jun 2024 01:52AM UTC coverage: 87.241%. Remained the same
9359953006

Pull #666

github

web-flow
Update dependency eslint-config-hardcore to v45
Pull Request #666: Update dependency eslint-config-hardcore to v45

984 of 1094 branches covered (89.95%)

Branch coverage included in aggregate %.

3228 of 3734 relevant lines covered (86.45%)

44.33 hits per line

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

85.71
/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 { 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
interface ContextModule {
2✔
21
  Context: Context;
2✔
22
}
2✔
23

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

2✔
30
export class ModuleLoader extends EventTarget {
2✔
31
  private readonly basePath: string;
10✔
32

10✔
33
  public readonly registry: Registry;
10✔
34

10✔
35
  private watcher: FSWatcher | undefined;
10✔
36

10✔
37
  private readonly contextRegistry: ContextRegistry;
10✔
38

10✔
39
  private readonly dependencyGraph = new ModuleDependencyGraph();
10✔
40

10✔
41
  private readonly uncachedImport: (moduleName: string) => Promise<unknown> =
10✔
42
    // eslint-disable-next-line @typescript-eslint/require-await
10✔
43
    async function (moduleName: string) {
10✔
44
      throw new Error(`uncachedImport not set up; importing ${moduleName}`);
×
45
    };
×
46

10✔
47
  public constructor(
10✔
48
    basePath: string,
10✔
49
    registry: Registry,
10✔
50
    contextRegistry = new ContextRegistry(),
10✔
51
  ) {
10✔
52
    super();
10✔
53
    this.basePath = basePath.replaceAll("\\", "/");
10✔
54
    this.registry = registry;
10✔
55
    this.contextRegistry = contextRegistry;
10✔
56
  }
10✔
57

10✔
58
  public async watch(): Promise<void> {
10✔
59
    this.watcher = watch(
4✔
60
      `${this.basePath}/**/*.{js,mjs,ts,mts,cjs,cts}`,
4✔
61
      CHOKIDAR_OPTIONS,
4✔
62
    ).on(
4✔
63
      "all",
4✔
64
      // eslint-disable-next-line max-statements
4✔
65
      (eventName: string, pathNameOriginal: string) => {
4✔
66
        const pathName = pathNameOriginal.replaceAll("\\", "/");
2✔
67

2✔
68
        if (pathName.includes("$.context") && eventName === "add") {
2!
69
          process.stdout.write(
×
70
            `\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`,
×
71
          );
×
72
          return;
×
73
        }
×
74

2✔
75
        if (!["add", "change", "unlink"].includes(eventName)) {
2!
76
          return;
×
77
        }
×
78

2✔
79
        const parts = nodePath.parse(pathName.replace(this.basePath, ""));
2✔
80
        const url = `/${parts.dir}/${parts.name}`
2✔
81
          .replaceAll("\\", "/")
2✔
82
          .replaceAll(/\/+/gu, "/");
2✔
83

2✔
84
        if (eventName === "unlink") {
2✔
85
          this.registry.remove(url);
2✔
86
          this.dispatchEvent(new Event("remove"));
2✔
87
        }
2✔
88
        const dependencies = this.dependencyGraph.dependentsOf(pathName);
2✔
89

2✔
90
        void this.loadEndpoint(pathName);
2✔
91
        for (const dependency of dependencies) {
2!
92
          void this.loadEndpoint(dependency);
×
93
        }
×
94
      },
2✔
95
    );
4✔
96
    await once(this.watcher, "ready");
4✔
97
  }
4✔
98

10✔
99
  public async stopWatching(): Promise<void> {
10✔
100
    await this.watcher?.close();
4✔
101
  }
4✔
102

10✔
103
  public async load(directory = ""): Promise<void> {
10✔
104
    if (
18✔
105
      !existsSync(nodePath.join(this.basePath, directory).replaceAll("\\", "/"))
18✔
106
    ) {
18!
107
      throw new Error(`Directory does not exist ${this.basePath}`);
×
108
    }
×
109

18✔
110
    const files = await fs.readdir(
18✔
111
      nodePath.join(this.basePath, directory).replaceAll("\\", "/"),
18✔
112
      {
18✔
113
        withFileTypes: true,
18✔
114
      },
18✔
115
    );
18✔
116

18✔
117
    const imports = files.flatMap(async (file): Promise<void> => {
18✔
118
      const extension = file.name.split(".").at(-1);
36✔
119

36✔
120
      if (file.isDirectory()) {
36✔
121
        await this.load(
8✔
122
          nodePath.join(directory, file.name).replaceAll("\\", "/"),
8✔
123
        );
8✔
124

8✔
125
        return;
8✔
126
      }
8✔
127

28✔
128
      if (!["cjs", "cts", "js", "mjs", "mts", "ts"].includes(extension ?? "")) {
36✔
129
        return;
12✔
130
      }
12✔
131

16✔
132
      const fullPath = nodePath
16✔
133
        .join(this.basePath, directory, file.name)
16✔
134
        .replaceAll("\\", "/");
16✔
135

16✔
136
      await this.loadEndpoint(fullPath);
16✔
137
    });
16✔
138

18✔
139
    await Promise.all(imports);
18✔
140
  }
18✔
141

10✔
142
  // eslint-disable-next-line max-statements
10✔
143
  private async loadEndpoint(pathName: string) {
10✔
144
    debug("importing module: %s", pathName);
18✔
145

18✔
146
    const directory = dirname(pathName.slice(this.basePath.length)).replaceAll(
18✔
147
      "\\",
18✔
148
      "/",
18✔
149
    );
18✔
150

18✔
151
    const url = `/${nodePath.join(
18✔
152
      directory,
18✔
153
      nodePath.parse(basename(pathName)).name,
18✔
154
    )}`
18✔
155
      .replaceAll("\\", "/")
18✔
156
      .replaceAll(/\/+/gu, "/");
18✔
157

18✔
158
    this.dependencyGraph.load(pathName);
18✔
159

18✔
160
    try {
18✔
161
      const doImport =
18✔
162
        (await determineModuleKind(pathName)) === "commonjs"
18!
163
          ? uncachedRequire
×
164
          : uncachedImport;
18✔
165

18✔
166
      // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
18✔
167
      const endpoint = (await doImport(pathName)) as ContextModule | Module;
18✔
168

18✔
169
      this.dispatchEvent(new Event("add"));
18✔
170

18✔
171
      if (basename(pathName).startsWith("_.context")) {
18✔
172
        if (isContextModule(endpoint)) {
8✔
173
          this.contextRegistry.update(
8✔
174
            directory,
8✔
175

8✔
176
            // @ts-expect-error TS says Context has no constructable signatures but that's not true?
8✔
177
            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
8✔
178
            new endpoint.Context(),
8✔
179
          );
8✔
180
        }
8✔
181
      } else {
18✔
182
        // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
10✔
183
        this.registry.add(url, endpoint as Module);
10✔
184
      }
10✔
185
    } catch (error: unknown) {
18!
186
      if (
×
187
        String(error) ===
×
188
        "SyntaxError: Identifier 'Context' has already been declared"
×
189
      ) {
×
190
        // Not sure why Node throws this error. It doesn't seem to matter.
×
191
        return;
×
192
      }
×
193

×
194
      process.stdout.write(`\nError loading ${pathName}:\n${String(error)}\n`);
×
195
    }
×
196
  }
18✔
197
}
10✔
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

© 2025 Coveralls, Inc