-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworkspace-dev.ts
More file actions
219 lines (192 loc) · 5.56 KB
/
Copy pathworkspace-dev.ts
File metadata and controls
219 lines (192 loc) · 5.56 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
import { getPackagesSync, type Package } from '@manypkg/get-packages';
import { spawn } from 'child_process';
import graphlib, { Graph } from 'graphlib';
import path from 'path';
import {
DEBUG_LOG_TITLE,
PACKAGE_JSON,
RSLIB_READY_MESSAGE,
} from './constant.js';
import { debugLog, Logger } from './logger.js';
import { readPackageJson } from './utils.js';
interface GraphNode {
name: string;
packageJson: Package['packageJson'];
path: string;
}
export interface WorkspaceDevRunnerOptions {
cwd?: string;
workspaceFilePath?: string;
projectConfig?: Record<
string,
{
match?: (stdout: string) => boolean;
command?: string;
}
>;
}
export class WorkspaceDevRunner {
private options: WorkspaceDevRunnerOptions;
private cwd: string;
private workspaceFilePath: string;
private packages: Package[] = [];
private graph: Graph;
private visited: Record<string, boolean>;
private visiting: Record<string, boolean>;
private matched: Record<string, boolean>;
private metaData!: Package['packageJson'];
constructor(options: WorkspaceDevRunnerOptions) {
this.options = options;
this.cwd = options.cwd || process.cwd();
this.workspaceFilePath = options.workspaceFilePath || this.cwd;
this.packages = [];
this.visited = {};
this.visiting = {};
this.matched = {};
this.graph = new Graph({ directed: true });
}
async init(): Promise<void> {
this.metaData = await readPackageJson(path.join(this.cwd, PACKAGE_JSON));
this.buildDependencyGraph();
debugLog(
'Dependency graph:\n' +
`nodes: ${this.getNodes().join(', ')}\n` +
`edges: ${this.getEdges()
.map((edge) => `${edge.v} -> ${edge.w}`)
.join(', ')}\n`,
);
}
buildDependencyGraph() {
const { packages } = getPackagesSync(this.workspaceFilePath);
const currentPackage = packages.find(
(pkg) => pkg.packageJson.name === this.metaData.name,
)!;
this.packages = packages;
const initNode = (pkg: Package) => {
const { packageJson, dir } = pkg;
const { name, dependencies, devDependencies, peerDependencies } =
packageJson;
const node: GraphNode = {
name,
packageJson,
path: dir,
};
this.graph.setNode(name, node);
this.visited[name] = false;
this.visiting[name] = false;
this.matched[name] = false;
const packageName = name;
const deps = {
...dependencies,
...devDependencies,
...peerDependencies,
};
for (const depName of Object.keys(deps)) {
const isInternalDep = this.packages.some(
(p) => p.packageJson.name === depName,
);
if (isInternalDep) {
this.graph.setEdge(packageName, depName);
this.checkGraph();
const depPackage = packages.find(
(pkg) => pkg.packageJson.name === depName,
)!;
initNode(depPackage);
}
}
};
initNode(currentPackage);
}
checkGraph() {
const isAcyclic = graphlib.alg.isAcyclic(this.graph);
if (!isAcyclic) {
throw new Error(
DEBUG_LOG_TITLE + 'Dependency graph do not allow cycles.',
);
}
return isAcyclic;
}
getDependencyGraph() {
return this.graph;
}
getNodes() {
return this.graph.nodes();
}
getEdges() {
return this.graph.edges();
}
getNode(name: string) {
return this.graph.node(name);
}
getDependents(packageName: string) {
return this.graph.predecessors(packageName);
}
getDependencies(packageName: string) {
return this.graph.successors(packageName);
}
async start() {
const promises = [];
const nodes = this.getNodes().filter((node) => node !== this.metaData.name);
for (const node of nodes) {
const dependencies = this.getDependencies(node) || [];
const canStart = dependencies.every((dep) => {
const isVisiting = this.visiting[dep];
const isVisited = this.visited[dep];
return isVisited && !isVisiting;
});
if (canStart && !this.visited[node] && !this.visiting[node]) {
debugLog(`Start visit node: ${node}`);
const visitPromise = this.visitNodes(node);
promises.push(visitPromise);
}
}
await Promise.all(promises);
}
visitNodes(node: string): Promise<void> {
return new Promise((resolve) => {
this.visiting[node] = true;
const { name, path } = this.getNode(node);
const config = this.options?.projectConfig?.[name];
const child = spawn(
'npm',
['run', config?.command ? config.command : 'dev'],
{
cwd: path,
env: {
...process.env,
FORCE_COLOR: '3',
},
shell: true,
},
);
const logger = new Logger({
name,
});
child.stdout.on('data', async (data) => {
const stdout = data.toString();
if (this.matched[node]) {
logger.emitLogOnce('stdout', stdout);
return;
}
logger.appendLog('stdout', stdout);
const match = config?.match;
const matchResult = match
? match(stdout)
: stdout.match(RSLIB_READY_MESSAGE);
if (matchResult) {
logger.flushStdout();
this.matched[node] = true;
this.visited[node] = true;
this.visiting[node] = false;
await this.start();
resolve();
}
});
child.stderr.on('data', (data) => {
const stderr = data.toString();
logger.emitLogOnce('stderr', stderr);
});
child.on('close', () => {});
});
}
}