Skip to content

Commit 77d273e

Browse files
committed
feat: support config and plugins
1 parent 9748be0 commit 77d273e

File tree

3 files changed

+52
-5
lines changed

3 files changed

+52
-5
lines changed

lib/cli.ts

+8-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import * as yargs from "yargs";
44
import tsw from "./index";
5-
import * as path from "path";
65

76
const { argv } = yargs
87
.alias("h", "help")
@@ -11,9 +10,15 @@ const { argv } = yargs
1110
type: "boolean",
1211
description: "Run with verbose logging",
1312
default: false
13+
})
14+
.option("config", {
15+
alias: "c",
16+
type: "string",
17+
description: "Config file path",
18+
default: "tswconfig.json"
1419
});
1520

16-
const { _ } = argv;
21+
const { _, config } = argv;
1722
const [main] = _;
1823

19-
tsw(path.resolve(process.cwd(), main));
24+
tsw(process.cwd(), main, config);

lib/index.ts

+36-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,47 @@
1+
import * as path from "path";
12
import { consoleHack } from "./core/runtime/console.hack";
23
import { httpCreateServerHack } from "./core/runtime/create-server.hack";
34
import { dnsHack } from "./core/runtime/dns.hack";
45
import { requestHack } from "./core/runtime/capture/index";
6+
import { eventBus } from "./core/bus";
7+
8+
const loadPlugins = async (
9+
basePath: string,
10+
config: typeof global.tswConfig
11+
): Promise<void> => {
12+
// eslint-disable-next-line no-restricted-syntax
13+
for (const pluginPath of config.plugins) {
14+
if (!pluginPath.trim()) {
15+
return;
16+
}
17+
18+
let absolutePath = "";
19+
if (path.isAbsolute(pluginPath)) {
20+
absolutePath = pluginPath;
21+
} else if (pluginPath.startsWith(".")) {
22+
absolutePath = path.resolve(basePath, pluginPath);
23+
} else {
24+
absolutePath = pluginPath;
25+
}
26+
27+
// eslint-disable-next-line no-await-in-loop
28+
(await import(absolutePath))(eventBus, config);
29+
}
30+
};
31+
32+
export default async (
33+
basePath: string,
34+
mainPath: string,
35+
configPath: string
36+
): Promise<void> => {
37+
global.tswConfig = await import(path.resolve(basePath, configPath));
538

6-
export default async (absolutePath2Main: string): Promise<void> => {
739
httpCreateServerHack();
840
dnsHack();
941
consoleHack();
1042
requestHack();
1143

12-
await import(absolutePath2Main);
44+
await loadPlugins(basePath, global.tswConfig);
45+
46+
await import(path.resolve(basePath, mainPath));
1347
};

typings/type.d.ts

+8
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,12 @@ declare namespace NodeJS {
2323
interface Domain {
2424
currentContext?: any;
2525
}
26+
27+
interface Global {
28+
tswConfig: {
29+
appid: string;
30+
appkey: string;
31+
plugins: string[];
32+
};
33+
}
2634
}

0 commit comments

Comments
 (0)