-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworkspace-dev.ts
More file actions
261 lines (233 loc) · 7.19 KB
/
Copy pathworkspace-dev.ts
File metadata and controls
261 lines (233 loc) · 7.19 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import { getPackagesSync, type Package } from '@manypkg/get-packages';
import { spawn } from 'child_process';
import graphlib, { Graph } from 'graphlib';
import path from 'path';
import {
MODERN_MODULE_READY_MESSAGE,
PACKAGE_JSON,
PLUGIN_LOG_TITLE,
RSLIB_READY_MESSAGE,
TSUP_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;
workspaceFileDir?: string;
projects?: Record<
string,
{
match?: (stdout: string) => boolean;
command?: string;
skip?: boolean | 'only';
}
>;
startCurrent?: boolean;
}
export class WorkspaceDevRunner {
private options: WorkspaceDevRunnerOptions;
private cwd: string;
private workspaceFileDir: 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 = {
startCurrent: false,
...options,
};
this.cwd = options.cwd || process.cwd();
this.workspaceFileDir = options.workspaceFileDir || 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.workspaceFileDir);
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,
};
const skip = this.options.projects?.[name]?.skip;
if (skip === true) {
return;
}
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,
);
const skip = this.options.projects?.[depName]?.skip;
if (isInternalDep) {
if (skip !== true) {
this.graph.setEdge(packageName, depName);
this.checkGraph();
const depPackage = packages.find(
(pkg) => pkg.packageJson.name === depName,
)!;
if (!this.getNode(depName)) {
initNode(depPackage);
}
} else {
debugLog(
`Prune project ${depName} and its dependencies because it is marked as skip: true`,
);
}
}
}
};
initNode(currentPackage);
}
checkGraph() {
const cycles = graphlib.alg.findCycles(this.graph);
const nonSelfCycles = cycles.filter((c) => c.length !== 1);
const nonSkipCycles = nonSelfCycles.filter((group) => {
const isSkip = group.some((node) => this.options.projects?.[node]?.skip);
return !isSkip;
});
if (nonSkipCycles.length) {
throw new Error(
`${PLUGIN_LOG_TITLE} Cycle dependency graph found: ${nonSkipCycles}, you should config projects in plugin options to skip someone, or fix the cycle dependency. Otherwise, a loop of dev will occur.`,
);
}
}
async start() {
const promises = [];
const allNodes = this.getNodes();
const filterSelfNodes = allNodes.filter(
(node) => node !== this.metaData.name,
);
const nodes = this.options.startCurrent ? allNodes : filterSelfNodes;
for (const node of nodes) {
const dependencies = this.getDependencies(node) || [];
const canStart = dependencies.every((dep) => {
const selfStart = node === dep;
const isVisiting = this.visiting[dep];
const skipDep = this.options.projects?.[dep]?.skip;
const isVisited = selfStart || this.visited[dep] || skipDep;
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) => {
const { name, path } = this.getNode(node);
const logger = new Logger({
name,
});
const config = this.options?.projects?.[name];
if (config?.skip) {
this.visited[node] = true;
this.visiting[node] = false;
debugLog(`Skip visit node: ${node}`);
logger.emitLogOnce('stdout', `Skip visit node: ${name}`);
return this.start().then(() => resolve());
}
this.visiting[node] = true;
const child = spawn(
'npm',
['run', config?.command ? config.command : 'dev'],
{
cwd: path,
env: {
...process.env,
FORCE_COLOR: '3',
},
shell: true,
},
);
child.stdout.on('data', async (data) => {
const stdout = data.toString();
const content = data.toString().replace(/\n$/, '');
if (this.matched[node]) {
logger.emitLogOnce('stdout', content);
return;
}
debugLog(content, `${name}: `);
logger.appendLog('stdout', stdout);
const match = config?.match;
const matchResult = match
? match(stdout)
: stdout.match(RSLIB_READY_MESSAGE) ||
stdout.match(MODERN_MODULE_READY_MESSAGE) ||
stdout.match(TSUP_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', () => {});
});
}
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);
}
}