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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use crate::graphs::{ChunkGraph, ChunkImportPathGraph, ChunkLoadGraph, ModuleParentGraph};
use meshed::graph::traversal::{
traverse_graph, GraphTraversal, Instruction, Mode, Pathing, TraversalLog,
};
use meshed::prelude::*;
use std::collections::{HashMap, HashSet};
use std::fmt::{write, Display, Formatter};
use meshed::graph::node::Node;
use meshed::graph::traversal::Mode::Acyclic;
use meshed::graph::traversal::Pathing::DFS;
use meshed::graph::{Graph, GraphDefinition, Inverted};
use thiserror::Error;
use webpack_stats::chunk::{Chunk, ChunkId, Chunks, Files};
use webpack_stats::entry::Entrypoint;
use webpack_stats::module::{Module, ModuleIdentifier, ModuleName, Modules};
use webpack_stats::SizeBytes;
#[derive(Debug, Error)]
pub enum EntrypointTraversalError {
#[error("Module {id} does not exist")]
NoEntrypoint { id: String },
#[error("Entrypoint {id} contains invalid chunks: {chunks:?}. Expected chunk {expected}")]
InvalidEntrypointChunks {
chunks: HashSet<ChunkId>,
id: String,
expected: ChunkId,
},
#[error("An unexpected error occured when traversing the graph")]
GraphError,
}
pub fn find_possible_chunk_for(
node: &Node<ModuleParentGraph>,
origin_chunk_id: ChunkId,
origin_chunk: Option<Node<ChunkGraph>>,
import_paths: &Graph<ChunkImportPathGraph>,
) -> Option<ChunkId> {
let chunks = node.node_data();
if chunks.is_empty() || chunks.contains(&origin_chunk_id) {
return Some(origin_chunk_id);
}
if chunks.len() == 1 {
return chunks.iter().next().cloned();
}
let origin_chunk = origin_chunk?;
if let Some(edge) = origin_chunk.find_edge(|edge| chunks.contains(&edge.target.get_id())) {
return Some(edge.target.get_id());
}
let origin_chunk_node = import_paths
.query(&origin_chunk.get_id())
.cloned()
.expect("Origin chunk did not exist in inverted chunk graph");
let traversal = traverse_graph(origin_chunk_node)
.set_pathing(Pathing::DFS)
.set_mode(Mode::Acyclic)
.into_iterator(|_, edge| {
tracing::trace!(
"Check ancestor {} -> {}",
edge.origin.label(),
edge.target.label()
);
if chunks.contains(&edge.target.get_id()) {
Instruction::Halt(Some(edge.target.get_id()))
} else {
Instruction::Continue(None)
}
});
traversal.flatten().next()
}
fn annotate_with_chunk<T: GraphDefinition>(
node: &Node<T>,
chunk: Option<ChunkId>,
fallback: ChunkId,
) {
#[derive(Clone)]
struct Defaulted;
if let Some(chunk) = chunk {
tracing::trace!("Annotate {}", &chunk);
if let Some(existing_annotation) = node.get_annotation::<ChunkId>() {
if existing_annotation != chunk && node.get_annotation::<Defaulted>().is_none() {
tracing::warn!("Subsequent traversal of {} resulted in inconsistent chunk assignment {} -> {}. Module belongs to multiple chunks in traversal", node.label(), &existing_annotation, &chunk);
}
}
node.annotate(chunk);
} else if node.get_annotation::<ChunkId>().is_some() {
} else {
node.annotate(Defaulted);
node.annotate(fallback);
}
}
pub fn traverse_entrypoint(
entrypoint_id: ModuleIdentifier,
initial_chunk_id: ChunkId,
module_graph: &Inverted<ModuleParentGraph>,
truncated_chunk_graph: &Graph<ChunkGraph>,
import_paths: &Graph<ChunkImportPathGraph>,
) -> Result<GraphTraversal<ModuleParentGraph>, EntrypointTraversalError> {
let entrypoint = module_graph.inner().query(&entrypoint_id).ok_or(
EntrypointTraversalError::NoEntrypoint {
id: entrypoint_id.to_string(),
},
)?;
{
let module_chunks = entrypoint.node_data();
if module_chunks.is_empty() {
entrypoint.annotate(initial_chunk_id);
} else if module_chunks.len() == 1 {
entrypoint.annotate(module_chunks.iter().cloned().next().unwrap());
} else if !module_chunks.contains(&initial_chunk_id) {
return Err(EntrypointTraversalError::InvalidEntrypointChunks {
chunks: module_chunks.clone(),
id: entrypoint_id.to_string(),
expected: initial_chunk_id.clone(),
});
} else {
entrypoint.annotate(initial_chunk_id);
}
}
let traversal = traverse_graph(entrypoint.clone())
.set_pathing(Pathing::DFS)
.set_mode(Mode::Acyclic)
.execute(|_depth, edge| {
tracing::trace!(
"Evaluate {} -> {}",
edge.origin.label(),
edge.target.label()
);
let origin_chunk = edge
.origin
.get_annotation::<ChunkId>()
.expect("Traversal did not have a source chunk");
let target_node = &edge.target;
let origin_chunk_node = truncated_chunk_graph.query(&origin_chunk).cloned();
let chunk = find_possible_chunk_for(
target_node,
origin_chunk.clone(),
origin_chunk_node,
import_paths,
);
annotate_with_chunk(&edge.target, chunk, origin_chunk);
Instruction::Continue(())
});
Ok(traversal)
}
pub fn traverse_entry_chunk<M, C, Mv, Cv, E>(
modules: M,
chunks: C,
entrypoint: &E,
) -> Result<Inverted<ModuleParentGraph>, EntrypointTraversalError>
where
M: Modules<Mv>,
Mv: Module,
C: Chunks<Cv>,
Cv: Chunk,
E: Entrypoint,
{
let chunk_ids = entrypoint.chunks();
let mut traversal: Option<GraphTraversal<ModuleParentGraph>> = None;
let chunk_graph = ChunkGraph::build_graph(&chunks);
let valid_import_graph = ChunkImportPathGraph::build_graph(&chunks);
let module_graph = ModuleParentGraph::build_graph(&modules).invert();
for entrypoint_id in chunk_ids.iter().cloned() {
let chunk = chunk_graph
.query(&entrypoint_id)
.cloned()
.ok_or(EntrypointTraversalError::GraphError)?;
let chunk_traversal = {
traverse_graph(chunk.clone())
.set_mode(Acyclic)
.execute(|_depth, _edge| Instruction::Continue(()))
};
let truncated_chunk_graph = chunk_traversal.project_into_graph(&chunk_graph);
let import_paths = chunk_traversal.prune_graph(&valid_import_graph);
let entrypoints = chunk.node_data();
for entrypoint in entrypoints {
let traversal_log = traverse_entrypoint(
entrypoint.clone(),
entrypoint_id,
&module_graph,
&truncated_chunk_graph,
&import_paths,
);
match traversal_log {
Ok(traversal_log) => {
if let Some(old_traversal) = traversal.take() {
let next = old_traversal.merge_with(traversal_log);
traversal = Some(next);
} else {
traversal = Some(traversal_log)
}
}
Err(err) => {
tracing::warn!("{}. Skipping", err);
}
}
}
}
let traversal = traversal.unwrap();
Ok(module_graph.map_project(traversal))
}
pub struct Entrypoints<'a> {
entries: HashMap<&'a str, &'a [ChunkId]>,
}
impl<'a> Display for Entrypoints<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for (name, chunks) in self.entries.iter() {
writeln!(f, "{}:", name)?;
writeln!(f, " Chunks:")?;
for chunk in chunks.iter() {
writeln!(f, " {}", chunk)?;
}
}
Ok(())
}
}
pub fn display_entrypoints<'a, E>(entrypoints: &'a [&'a E]) -> Entrypoints<'a>
where
E: webpack_stats::entry::Entrypoint,
{
let mut map = HashMap::new();
for entry in entrypoints {
map.insert(entry.name(), entry.chunks());
}
Entrypoints { entries: map }
}
pub fn paths_to_chunk<E, C, Cv, M, Mv>(
entrypoint: &E,
target_chunk: ChunkId,
chunks: &C,
modules: &M,
) -> Inverted<ModuleParentGraph>
where
M: Modules<Mv>,
Mv: Module,
C: Chunks<Cv>,
Cv: Chunk,
E: Entrypoint,
{
let chunk_graph = ChunkGraph::build_graph(&chunks);
let import_chunk_graph = ChunkImportPathGraph::build_graph(&chunks);
let module_graph = ModuleParentGraph::build_graph(&modules).invert();
let mut paths = vec![] as Vec<Vec<(ModuleIdentifier, ModuleIdentifier)>>;
for root_chunk in entrypoint.chunks() {
if root_chunk == &target_chunk {
continue;
}
let chunk_node = chunk_graph.query(root_chunk).unwrap().clone();
for module in chunk_node.node_data() {
let module_node = module_graph.inner().query(module).unwrap().clone();
module_node.annotate(chunk_node.get_id());
let traversal = traverse_graph(module_node)
.set_mode(Acyclic)
.set_pathing(DFS);
traversal.execute(|meta, edge| {
let origin_chunk = edge
.origin
.get_annotation::<ChunkId>()
.expect("Did not have an origin chunk");
let origin_chunk_node = chunk_graph.query(&&origin_chunk).cloned();
let mut path = meta
.get_annotation::<Vec<(ModuleIdentifier, ModuleIdentifier)>>()
.unwrap_or_default();
path.push((edge.origin.get_id(), edge.target.get_id()));
let node_chunk = find_possible_chunk_for(
&edge.target,
origin_chunk.clone(),
origin_chunk_node,
&import_chunk_graph,
);
annotate_with_chunk(&edge.target, node_chunk.clone(), origin_chunk);
if let Some(chunk) = node_chunk {
if chunk == target_chunk {
paths.push(path);
return Instruction::Backtrack(());
}
}
edge.target.annotate(path);
Instruction::Continue(())
});
}
}
let mut log = TraversalLog::default();
for path in paths {
let next_log = TraversalLog::from(path);
log = log.merge_with(next_log);
}
module_graph.map_project(log)
}
pub struct EntrypointDescription<'a> {
name: &'a str,
initial_load_size: SizeBytes,
roots: Vec<Node<ChunkLoadGraph>>,
}
impl<'a> Display for EntrypointDescription<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}:", &self.name)?;
writeln!(
f,
"Initial size (uncompressed): {}",
&self.initial_load_size
)?;
writeln!(f, "Chunk Imports (* denotes asynchronous chunk):")?;
for root in self.roots.iter() {
let traversal = traverse_graph(root.clone())
.set_pathing(Pathing::DFS)
.set_mode(Mode::Acyclic)
.into_iterator(|meta, edge| Instruction::Continue((meta, edge)));
#[derive(Copy, Clone)]
struct Async;
write!(f, "├── {} ({}) [", root.get_id(), root.node_data().1)?;
for file in root.node_data().3 .0.iter() {
write!(f, "{} ", file)?;
}
writeln!(f, "]")?;
for (meta, edge) in traversal {
let depth = meta.depth();
let node = edge.target;
let indent = (depth * 4) + 4;
if !node.node_data().2 .0 {
meta.annotate(Async);
}
if meta.get_annotation::<Async>().is_some() {
write!(f, "{:>indent$}", "├*- ")?;
} else {
write!(f, "{:>indent$}", "├── ",)?;
}
write!(f, "{} ({}) [", node.label(), node.node_data().1)?;
for file in node.node_data().3 .0.iter() {
write!(f, "{},", file)?;
}
writeln!(f, "]")?;
}
}
Ok(())
}
}
#[derive(Debug, Error)]
pub enum EntrypointDescriptionError {}
pub fn describe_entrypoints<'a, C, Cv>(
chunks: C,
entrypoint_name: &'a str,
entrypoints: Entrypoints,
) -> Result<EntrypointDescription<'a>, EntrypointDescriptionError>
where
C: Chunks<Cv>,
Cv: Chunk,
{
let graph = ChunkLoadGraph::build_graph(&chunks);
let entrypoint = *entrypoints.entries.get(entrypoint_name).unwrap();
let mut output_traversal = None as Option<GraphTraversal<ChunkLoadGraph>>;
let mut root_nodes = vec![];
for chunk in entrypoint.iter() {
let chunk_node = graph.query(chunk);
let chunk_node = match chunk_node {
None => {
continue;
}
Some(node) => node.clone(),
};
let truncated = traverse_graph(chunk_node.clone())
.set_pathing(Pathing::DFS)
.set_mode(Mode::Acyclic)
.execute(|_, edge| {
let initial = &edge.target.node_data().2;
if !initial.0 {
Instruction::Skip(())
} else {
Instruction::Continue(())
}
});
let unique_paths = traverse_graph(chunk_node.clone())
.set_pathing(DFS)
.set_mode(Mode::Acyclic)
.execute(|meta, edge| {
if let Some(mut seen_in_this_path) = meta.get_annotation::<HashSet<ChunkId>>() {
if seen_in_this_path.contains(&edge.target.get_id()) {
return Instruction::Skip(());
} else {
seen_in_this_path.insert(edge.target.get_id());
}
meta.annotate(seen_in_this_path);
} else {
meta.annotate::<HashSet<ChunkId>>(HashSet::from([edge.origin.get_id()]));
}
Instruction::Continue(())
});
let projection = unique_paths.project_into_graph(&graph);
let root_node = projection.query(&chunk_node.get_id()).expect("");
root_nodes.push(root_node.clone());
if let Some(tra) = output_traversal.take() {
output_traversal = Some(tra.merge_with(truncated))
} else {
output_traversal = Some(truncated)
}
}
let output_traversal = output_traversal.unwrap();
let output_graph = output_traversal.project_into_graph(&graph);
let initial_size = output_graph
.all_nodes()
.fold(SizeBytes::default(), |acc, n| acc + n.node_data().1);
Ok(EntrypointDescription {
name: entrypoint_name,
roots: root_nodes,
initial_load_size: initial_size,
})
}
#[derive(Debug)]
pub struct ChunkDescription {
id: ChunkId,
size: SizeBytes,
files: Files,
modules: Vec<ModuleName>,
}
impl Display for ChunkDescription {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Chunk: {}", &self.id)?;
writeln!(f, "size: {}", &self.size)?;
writeln!(f, "Files:")?;
for file in self.files.0.iter() {
writeln!(f, " {}", &file)?;
}
writeln!(f, "Modules:")?;
for file in self.modules.iter() {
writeln!(f, " {}", &file)?;
}
Ok(())
}
}
pub fn describe_chunk<C: Chunks<Cv>, Cv: Chunk, M: Modules<Mv>, Mv: Module>(
chunk_id: ChunkId,
chunks: &C,
modules: &M,
) -> Option<ChunkDescription> {
let node = chunks.query(&chunk_id)?;
let index = modules.create_index();
let modules: Vec<ModuleIdentifier> = node.extract_data();
let names = modules.iter().filter_map(|id| {
let module = index.query(id)?;
Some(module.label())
});
Some(ChunkDescription {
id: chunk_id,
size: node.extract_data(),
files: node.extract_data(),
modules: names.collect(),
})
}