pesde 0.7.3

A package manager for the Luau programming language, supporting multiple runtimes including Roblox and Lune
Documentation
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
use crate::{
	graph::{DependencyGraph, DependencyGraphNode},
	manifest::{overrides::OverrideSpecifier, Alias, DependencyType},
	source::{
		ids::PackageId,
		pesde::PesdePackageSource,
		specifiers::DependencySpecifiers,
		traits::{PackageRef as _, PackageSource as _, RefreshOptions, ResolveOptions},
		PackageSources,
	},
	Project, RefreshedSources,
};
use std::collections::{btree_map::Entry, HashMap, VecDeque};
use tracing::{instrument, Instrument as _};

fn insert_node(
	graph: &mut DependencyGraph,
	package_id: &PackageId,
	mut node: DependencyGraphNode,
	is_top_level: bool,
) {
	if !is_top_level && node.direct.take().is_some() {
		tracing::debug!(
			"tried to insert {package_id} as direct dependency from a non top-level context",
		);
	}

	match graph.entry(package_id.clone()) {
		Entry::Vacant(entry) => {
			entry.insert(node);
		}
		Entry::Occupied(existing) => {
			let current_node = existing.into_mut();

			match (&current_node.direct, &node.direct) {
				(Some(_), Some(_)) => {
					tracing::warn!("duplicate direct dependency for {package_id}");
				}

				(None, Some(_)) => {
					current_node.direct = node.direct;
				}

				(_, _) => {}
			}
		}
	}
}

impl Project {
	/// Create a dependency graph from the project's manifest
	#[instrument(
		skip(self, previous_graph, refreshed_sources),
		ret(level = "trace"),
		level = "debug"
	)]
	pub async fn dependency_graph(
		&self,
		previous_graph: Option<&DependencyGraph>,
		refreshed_sources: RefreshedSources,
		// used by `x` command - if true, specifier indices are expected to be URLs. will not do peer dependency checks
		is_published_package: bool,
	) -> Result<DependencyGraph, Box<errors::DependencyGraphError>> {
		let manifest = self
			.deser_manifest()
			.await
			.map_err(|e| Box::new(e.into()))?;

		let all_current_dependencies = manifest
			.all_dependencies()
			.map_err(|e| Box::new(e.into()))?;

		let mut all_specifiers = all_current_dependencies
			.clone()
			.into_iter()
			.map(|(alias, (spec, ty))| ((spec, ty), alias))
			.collect::<HashMap<_, _>>();

		let mut graph = DependencyGraph::default();

		if let Some(previous_graph) = previous_graph {
			for (package_id, node) in previous_graph {
				let Some((old_alias, specifier, source_ty)) = &node.direct else {
					// this is not a direct dependency, will be added if it's still being used later
					continue;
				};

				if specifier.is_local() {
					// local dependencies must always be resolved fresh in case their FS changes
					continue;
				}

				let Some(alias) = all_specifiers.remove(&(specifier.clone(), *source_ty)) else {
					tracing::debug!(
						"dependency {package_id} (old alias {old_alias}) from old dependency graph is no longer in the manifest",
					);
					continue;
				};

				let span = tracing::info_span!("resolve from old graph", alias = alias.as_str());
				let _guard = span.enter();

				tracing::debug!("resolved {package_id} from old dependency graph");
				insert_node(
					&mut graph,
					package_id,
					DependencyGraphNode {
						direct: Some((alias.clone(), specifier.clone(), *source_ty)),
						..node.clone()
					},
					true,
				);

				let mut queue = node
					.dependencies
					.iter()
					.map(|(dep_alias, (id, _))| {
						(id, vec![alias.to_string(), dep_alias.to_string()])
					})
					.collect::<VecDeque<_>>();

				while let Some((dep_id, path)) = queue.pop_front() {
					let inner_span =
						tracing::info_span!("resolve dependency", path = path.join(">"));
					let _inner_guard = inner_span.enter();

					if let Some(dep_node) = previous_graph.get(dep_id) {
						tracing::debug!("resolved sub-dependency {dep_id}");
						if graph.contains_key(dep_id) {
							tracing::debug!(
								"sub-dependency {dep_id} already resolved in new graph",
							);
							continue;
						}
						insert_node(&mut graph, dep_id, dep_node.clone(), false);

						dep_node
							.dependencies
							.iter()
							.map(|(alias, (id, _))| {
								(
									id,
									path.iter()
										.cloned()
										.chain(std::iter::once(alias.to_string()))
										.collect(),
								)
							})
							.for_each(|dep| queue.push_back(dep));
					} else {
						tracing::warn!("dependency {dep_id} not found in previous graph");
					}
				}
			}
		}

		let mut queue = all_specifiers
			.into_iter()
			.map(|((spec, ty), alias)| {
				(
					spec,
					ty,
					None::<PackageId>,
					vec![alias],
					false,
					manifest.target.kind(),
				)
			})
			.collect::<VecDeque<_>>();

		let refresh_options = RefreshOptions {
			project: self.clone(),
		};

		while let Some((specifier, ty, dependant, path, overridden, target)) = queue.pop_front() {
			async {
				let alias = path.last().unwrap();
				let depth = path.len() - 1;

				tracing::debug!("resolving {specifier} ({ty:?})");
				let source = match &specifier {
					DependencySpecifiers::Pesde(specifier) => {
						let index_url = if !is_published_package && (depth == 0 || overridden) {
							manifest
								.indices
								.get(&specifier.index)
								.ok_or_else(|| errors::DependencyGraphError::IndexNotFound(
									specifier.index.clone(),
								))?
								.clone()
						} else {
							specifier.index
								.as_str()
								.try_into()
								// specifiers in indices store the index url in this field
								.unwrap()
						};

						PackageSources::Pesde(PesdePackageSource::new(index_url))
					}
					#[cfg(feature = "wally-compat")]
					DependencySpecifiers::Wally(specifier) => {
						let index_url = if !is_published_package && (depth == 0 || overridden) {
							manifest
								.wally_indices
								.get(&specifier.index)
								.ok_or_else(|| errors::DependencyGraphError::WallyIndexNotFound(
									specifier.index.clone(),
								))?
								.clone()
						} else {
							specifier.index
								.as_str()
								.try_into()
								// specifiers in indices store the index url in this field
								.unwrap()
						};

						PackageSources::Wally(crate::source::wally::WallyPackageSource::new(index_url))
					}
					DependencySpecifiers::Git(specifier) => PackageSources::Git(
						crate::source::git::GitPackageSource::new(specifier.repo.clone()),
					),
					DependencySpecifiers::Workspace(_) => {
						PackageSources::Workspace(crate::source::workspace::WorkspacePackageSource)
					}
					DependencySpecifiers::Path(_) => {
						PackageSources::Path(crate::source::path::PathPackageSource)
					}
				};

				refreshed_sources.refresh(
					&source,
					&refresh_options,
				)
					.await
					.map_err(|e| Box::new(e.into()))?;

				let (name, resolved, suggestions) = source
					.resolve(&specifier, &ResolveOptions {
						project: self.clone(),
						target,
						refreshed_sources: refreshed_sources.clone(),
						loose_target: false,
					})
					.await
					.map_err(|e| Box::new(e.into()))?;

				let Some(package_id) = graph
					.keys()
					.filter(|id| *id.name() == name && resolved.contains_key(id.version_id()))
					.max()
					.cloned()
					.or_else(|| resolved.last_key_value().map(|(ver, _)| PackageId::new(name, ver.clone())))
				else {
					return Err(Box::new(errors::DependencyGraphError::NoMatchingVersion(
						format!(
							"{specifier} {target}{}",
							if suggestions.is_empty() {
								"".into()
							} else {
								format!(
									" available targets: {}",
									suggestions
										.into_iter()
										.map(|t| t.to_string())
										.collect::<Vec<_>>()
										.join(", ")
								)
							}
						),
					)));
				};

				if let Some(dependant_id) = dependant {
					graph
						.get_mut(&dependant_id)
						.expect("dependant package not found in graph")
						.dependencies
						.insert(alias.clone(), (package_id.clone(), ty));
				}

				let pkg_ref = &resolved[package_id.version_id()];

				if let Some(already_resolved) = graph.get_mut(&package_id) {
					tracing::debug!("{package_id} already resolved");

					if std::mem::discriminant(&already_resolved.pkg_ref) != std::mem::discriminant(pkg_ref) {
						tracing::warn!(
                            "resolved package {package_id} has a different source than previously resolved one, this may cause issues",
                        );
					}

					if already_resolved.direct.is_none() && depth == 0 {
						already_resolved.direct = Some((alias.clone(), specifier.clone(), ty));
					}

					return Ok(());
				}

				let node = DependencyGraphNode {
					direct: (depth == 0).then(|| (alias.clone(), specifier.clone(), ty)),
					pkg_ref: pkg_ref.clone(),
					dependencies: Default::default(),
				};
				insert_node(
					&mut graph,
					&package_id,
					node,
					depth == 0,
				);

				tracing::debug!("resolved {package_id} from new dependency graph");

				for (dependency_alias, (dependency_spec, dependency_ty)) in
					pkg_ref.dependencies().clone()
				{
					if dependency_ty == DependencyType::Dev {
						// dev dependencies of dependencies are to be ignored
						continue;
					}

					let overridden = manifest.overrides.iter().find_map(|(key, spec)| {
						key.0.iter().find_map(|override_path| {
							// if the path up until the last element is the same as the current path,
							// and the last element in the path is the dependency alias,
							// then the specifier is to be overridden
							(path.len() == override_path.len() - 1
								&& path == override_path[..override_path.len() - 1]
								&& override_path.last() == Some(&dependency_alias))
								.then_some(spec)
						})
					});

					if overridden.is_some() {
						tracing::debug!(
                            "overridden specifier found for {} ({dependency_spec})",
                            path.iter()
                                .map(Alias::as_str)
                                .chain(std::iter::once(dependency_alias.as_str()))
                                .collect::<Vec<_>>()
                                .join(">"),
                        );
					}

					queue.push_back((
						match overridden {
							Some(OverrideSpecifier::Specifier(spec)) => spec.clone(),
							Some(OverrideSpecifier::Alias(alias)) => all_current_dependencies.get(alias)
								.map(|(spec, _)| spec)
								.ok_or_else(|| errors::DependencyGraphError::AliasNotFound(alias.clone()))?
								.clone(),
							None => dependency_spec,
						},
						dependency_ty,
						Some(package_id.clone()),
						path.iter()
							.cloned()
							.chain(std::iter::once(dependency_alias))
							.collect(),
						overridden.is_some(),
						package_id.version_id().target(),
					));
				}

				Ok(())
			}
				.instrument(tracing::info_span!("resolve new/changed", path = path.iter().map(Alias::as_str).collect::<Vec<_>>().join(">")))
				.await?;
		}

		Ok(graph)
	}
}

/// Errors that can occur when resolving dependencies
pub mod errors {
	use crate::manifest::Alias;
	use thiserror::Error;

	/// Errors that can occur when creating a dependency graph
	#[derive(Debug, Error)]
	#[non_exhaustive]
	pub enum DependencyGraphError {
		/// An error occurred while deserializing the manifest
		#[error("failed to deserialize manifest")]
		ManifestRead(#[from] crate::errors::ManifestReadError),

		/// An error occurred while reading all dependencies from the manifest
		#[error("error getting all project dependencies")]
		AllDependencies(#[from] crate::manifest::errors::AllDependenciesError),

		/// An index was not found in the manifest
		#[error("index named `{0}` not found in manifest")]
		IndexNotFound(String),

		/// A Wally index was not found in the manifest
		#[cfg(feature = "wally-compat")]
		#[error("wally index named `{0}` not found in manifest")]
		WallyIndexNotFound(String),

		/// An error occurred while refreshing a package source
		#[error("error refreshing package source")]
		Refresh(#[from] crate::source::errors::RefreshError),

		/// An error occurred while resolving a package
		#[error("error resolving package")]
		Resolve(#[from] crate::source::errors::ResolveError),

		/// No matching version was found for a specifier
		#[error("no matching version found for {0}")]
		NoMatchingVersion(String),

		/// An alias for an override was not found in the manifest
		#[error("alias `{0}` not found in manifest")]
		AliasNotFound(Alias),
	}
}