1use std::collections::{BTreeMap, HashMap};
2use std::fs;
3use std::path::{Component, Path, PathBuf};
4
5use crate::discovery::read_source;
6use crate::json::json_string;
7
8pub fn is_unpinned_range(range: &str) -> bool {
13 let r = range.trim();
14 if r.is_empty() || r == "*" || r.eq_ignore_ascii_case("x") || r.eq_ignore_ascii_case("latest") {
15 return true;
16 }
17 !r.chars().any(|c| c.is_ascii_digit())
18}
19
20pub fn render_package_json(deps: &std::collections::BTreeMap<String, String>) -> String {
29 let mut out = String::from("{\n \"type\": \"module\"");
30 if !deps.is_empty() {
31 out.push_str(",\n \"dependencies\": {\n");
32 let entries: Vec<String> = deps
33 .iter()
34 .map(|(pkg, range)| format!(" {}: {}", json_string(pkg), json_string(range)))
35 .collect();
36 out.push_str(&entries.join(",\n"));
37 out.push_str("\n }");
38 }
39 out.push_str("\n}\n");
40 out
41}
42
43pub fn normalize_rel(p: &Path) -> PathBuf {
47 let mut out: Vec<std::ffi::OsString> = Vec::new();
48 for c in p.components() {
49 match c {
50 Component::CurDir => {}
51 Component::ParentDir => {
52 out.pop();
53 }
54 Component::Normal(s) => out.push(s.to_os_string()),
55 Component::RootDir | Component::Prefix(_) => {}
56 }
57 }
58 out.iter().collect()
59}
60
61#[derive(Debug, Clone)]
68pub struct ProjectPaths {
69 pub include: Vec<PathBuf>,
73 pub exclude: Vec<PathBuf>,
76}
77
78impl ProjectPaths {
79 pub fn conventional(project_root: &Path) -> Self {
85 let mut include = Vec::new();
86 for role in ["src", "tests"] {
87 if project_root.join(role).is_dir() {
88 include.push(PathBuf::from(role));
89 }
90 }
91 if include.is_empty() {
92 include.push(PathBuf::from("."));
93 }
94 ProjectPaths {
95 include,
96 exclude: Vec::new(),
97 }
98 }
99}
100
101#[cfg(test)]
110pub(crate) fn read_project_paths_with(
111 project_root: &Path,
112 overlay: &HashMap<PathBuf, String>,
113) -> ProjectPaths {
114 try_read_project_paths_with(project_root, overlay)
115 .unwrap_or_else(|_| ProjectPaths::conventional(project_root))
116}
117
118#[derive(Debug)]
121pub enum ProjectPathsError {
122 Malformed,
124 UnknownKey(String),
127 UnknownTable(String),
131 TopLevelKey(String),
133 UnknownTableKey { table: &'static str, key: String },
137 NotAStringList {
141 table: &'static str,
142 key: &'static str,
143 },
144 NotABool {
147 table: &'static str,
148 key: &'static str,
149 },
150 BadBuild { key: &'static str, reason: String },
152 BadProfile { profile: String, reason: String },
154 BadHyperdrive {
158 table: &'static str,
159 capability: String,
160 reason: String,
161 },
162 BadContainers {
164 table: &'static str,
165 capability: String,
166 reason: String,
167 },
168 BadVectorize {
170 table: &'static str,
171 capability: String,
172 reason: String,
173 },
174 BadWorkerGroup { key: String, reason: String },
178 BadDevAck { key: String, reason: String },
181 BadTestTarget { target: String, reason: String },
183 BadTestPostgres { reason: String },
185 ProjectAndPackage,
188 BadPackage { key: &'static str, reason: String },
190 BadDependency {
193 table: &'static str,
194 alias: String,
195 reason: String,
196 },
197 UnknownEntryKey {
199 table: &'static str,
200 entry: String,
201 key: String,
202 },
203 BadRegistry { name: String, reason: String },
205 RegistryCredential { name: String },
207 BadWorkspace { reason: String },
210 WorkspaceRootTable(String),
213 WorkspaceRootSources,
215 WorkspaceRoot,
218 MemberRegistries { workspace: PathBuf },
221 NestedWorkspace { workspace: PathBuf },
223}
224
225pub const MANIFEST_TABLES: &[(&str, &[&str])] = &[
229 ("project", &["name", "version"]),
230 (
231 "package",
232 &[
233 "name",
234 "version",
235 "description",
236 "license",
237 "repository",
238 "exports",
239 ],
240 ),
241 ("paths", &["include", "exclude"]),
242 ("fmt", &[]),
243 ("lsp", &["diagnostics_mode", "diagnostics_debounce_ms"]),
244 ("workers", &["compatibility_flags", "workers_dev"]),
245 (
246 "deploy",
247 &["hyperdrive", "vectorize", "containers", "workers"],
248 ),
249 (
250 "dev",
251 &[
252 "hyperdrive",
253 "ai",
254 "ai-search",
255 "mtls",
256 "analytics-sql",
257 "vectorize",
258 "vectorize-index",
259 ],
260 ),
261 (
262 "build",
263 &[
264 "out",
265 "target",
266 "platform",
267 "emit",
268 "package_manager",
269 "client",
270 ],
271 ),
272 ("check", &["d1_sql"]),
273 ("profile", PROFILE_NAMES),
274 ("unstable", &["allow"]),
275 ("test", &["targets", "mutate", "postgres"]),
276 ("workspace", &["members", "exclude"]),
277];
278
279pub const PROFILE_NAMES: &[&str] = &["dev", "release"];
283
284const PROFILE_KEYS: &[&str] = &["contracts"];
286
287pub const MANIFEST_MAP_TABLES: &[(&str, &[&str])] = &[
293 ("dependencies", crate::manifest::DEPENDENCY_KEYS),
294 ("dev-dependencies", crate::manifest::DEPENDENCY_KEYS),
295 ("registries", crate::manifest::REGISTRY_KEYS),
296];
297
298const WORKSPACE_ROOT_TABLES: &[&str] = &["workspace", "registries"];
300
301const PLANNED_TABLES: &[(&str, &str)] = &[];
304
305fn all_tables() -> impl Iterator<Item = &'static str> {
308 MANIFEST_TABLES
309 .iter()
310 .chain(MANIFEST_MAP_TABLES)
311 .map(|(t, _)| *t)
312}
313
314fn table_list(conj: &str) -> String {
318 let names: Vec<String> = all_tables().map(|t| format!("`[{t}]`")).collect();
319 match names.split_last() {
320 Some((last, rest)) if !rest.is_empty() => format!("{} {conj} {last}", rest.join(", ")),
321 _ => names.join(""),
322 }
323}
324
325pub fn did_you_mean<'a>(
327 name: &str,
328 candidates: impl IntoIterator<Item = &'a str>,
329) -> Option<&'a str> {
330 candidates
331 .into_iter()
332 .map(|c| (edit_distance(name, c), c))
333 .filter(|(d, _)| *d <= 2)
334 .min_by_key(|(d, _)| *d)
335 .map(|(_, c)| c)
336}
337
338fn edit_distance(a: &str, b: &str) -> usize {
340 let b: Vec<char> = b.chars().collect();
341 let mut row: Vec<usize> = (0..=b.len()).collect();
342 for (i, ca) in a.chars().enumerate() {
343 let mut prev = row[0];
344 row[0] = i + 1;
345 for (j, cb) in b.iter().enumerate() {
346 let cur = row[j + 1];
347 row[j + 1] = (prev + usize::from(ca != *cb)).min(row[j] + 1).min(cur + 1);
348 prev = cur;
349 }
350 }
351 row[b.len()]
352}
353
354impl std::fmt::Display for ProjectPathsError {
355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356 match self {
357 ProjectPathsError::Malformed => write!(f, "`bynk.toml` is not valid TOML"),
358 ProjectPathsError::UnknownKey(k) => {
359 write!(
360 f,
361 "`[paths]` has no key named `{k}` — did you mean `include` or `exclude`?"
362 )
363 }
364 ProjectPathsError::UnknownTable(name) => {
365 write!(f, "`bynk.toml` has no table named `[{name}]` — ")?;
366 if let Some((_, issue)) = PLANNED_TABLES.iter().find(|(t, _)| *t == name) {
367 write!(f, "it is planned but not yet supported ({issue})")
368 } else if let Some(t) = did_you_mean(name, all_tables()) {
369 write!(f, "did you mean `[{t}]`?")
370 } else {
371 write!(f, "the tables are {}", table_list("and"))
372 }
373 }
374 ProjectPathsError::TopLevelKey(key) => {
375 if all_tables().any(|t| t == key) {
378 return write!(
379 f,
380 "`{key}` in `bynk.toml` must be a table — write it as `[{key}]`"
381 );
382 }
383 write!(f, "`bynk.toml` has a key `{key}` outside any table — ")?;
384 match MANIFEST_TABLES
385 .iter()
386 .find(|(_, keys)| keys.contains(&key.as_str()))
387 {
388 Some((table, _)) => write!(f, "did you mean it under `[{table}]`?"),
389 None => write!(f, "keys belong in {}", table_list("or")),
390 }
391 }
392 ProjectPathsError::UnknownTableKey { table, key } => {
393 let keys = MANIFEST_TABLES
394 .iter()
395 .find(|(t, _)| t == table)
396 .map(|(_, k)| *k)
397 .unwrap_or_default();
398 write!(f, "`[{table}]` has no key named `{key}` — ")?;
399 match did_you_mean(key, keys.iter().copied()) {
400 Some(k) => write!(f, "did you mean `{k}`?"),
401 None => {
402 let list: Vec<String> = keys.iter().map(|k| format!("`{k}`")).collect();
403 write!(f, "its keys are {}", list.join(", "))
404 }
405 }
406 }
407 ProjectPathsError::NotAStringList { table, key } => write!(
408 f,
409 "`[{table}]` `{key}` must be a list of strings, like `{key} = [\"nodejs_compat\"]`"
410 ),
411 ProjectPathsError::NotABool { table, key } => write!(
412 f,
413 "`[{table}]` `{key}` must be `true` or `false`, like `{key} = false`"
414 ),
415 ProjectPathsError::BadBuild { key, reason } => {
416 write!(f, "`[build]` `{key}` {reason}")
417 }
418 ProjectPathsError::BadProfile { profile, reason } => {
419 write!(f, "`[profile.{profile}]` {reason}")
420 }
421 ProjectPathsError::BadHyperdrive {
422 table,
423 capability,
424 reason,
425 } => {
426 write!(f, "`[{table}.{capability}]` {reason}")
427 }
428 ProjectPathsError::BadContainers {
429 table,
430 capability,
431 reason,
432 } => {
433 write!(f, "`[{table}.{capability}]` {reason}")
434 }
435 ProjectPathsError::BadVectorize {
436 table,
437 capability,
438 reason,
439 } => {
440 write!(f, "`[{table}.{capability}]` {reason}")
441 }
442 ProjectPathsError::BadWorkerGroup { key, reason } if key.is_empty() => {
443 write!(f, "`[deploy.workers]` {reason}")
444 }
445 ProjectPathsError::BadWorkerGroup { key, reason } => {
446 write!(f, "`[deploy.workers.{key}]` {reason}")
447 }
448 ProjectPathsError::BadDevAck { key, reason } => {
449 write!(f, "`[dev]` `{key}` {reason}")
450 }
451 ProjectPathsError::BadTestTarget { target, reason } => {
452 write!(f, "`[test.targets.{target}]` {reason}")
453 }
454 ProjectPathsError::BadTestPostgres { reason } => {
455 write!(f, "`[test]` `postgres` {reason}")
456 }
457 ProjectPathsError::ProjectAndPackage => write!(
458 f,
459 "`bynk.toml` has both `[project]` and `[package]` — a package is named by `[package] name`, so remove `[project]`"
460 ),
461 ProjectPathsError::BadPackage { key, reason } => {
462 write!(f, "`[package]` `{key}` {reason}")
463 }
464 ProjectPathsError::BadDependency {
465 table,
466 alias,
467 reason,
468 } => write!(f, "`[{table}]` `{alias}` {reason}"),
469 ProjectPathsError::UnknownEntryKey { table, entry, key } => {
470 let keys = MANIFEST_MAP_TABLES
471 .iter()
472 .find(|(t, _)| t == table)
473 .map(|(_, k)| *k)
474 .unwrap_or_default();
475 let place = if *table == "registries" {
476 format!("`[registries.{entry}]`")
477 } else {
478 format!("`[{table}]` `{entry}`")
479 };
480 write!(f, "{place} has no key named `{key}` — ")?;
481 match did_you_mean(key, keys.iter().copied()) {
482 Some(k) => write!(f, "did you mean `{k}`?"),
483 None => {
484 let list: Vec<String> = keys.iter().map(|k| format!("`{k}`")).collect();
485 write!(f, "its keys are {}", list.join(", "))
486 }
487 }
488 }
489 ProjectPathsError::BadRegistry { name, reason } => {
490 write!(f, "`[registries.{name}]` {reason}")
491 }
492 ProjectPathsError::RegistryCredential { name } => write!(
493 f,
494 "`[registries.{name}]` has a `token` — credentials belong in `{}` or the user credentials file, never in `bynk.toml`",
495 crate::manifest::registry_token_var(name)
496 ),
497 ProjectPathsError::BadWorkspace { reason } => write!(f, "`[workspace]` {reason}"),
498 ProjectPathsError::WorkspaceRootTable(table) => write!(
499 f,
500 "a workspace root's `bynk.toml` holds only `[workspace]` and `[registries]` — `[{table}]` belongs in a member's `bynk.toml`"
501 ),
502 ProjectPathsError::WorkspaceRootSources => write!(
503 f,
504 "a workspace root holds no sources of its own — move them into a member"
505 ),
506 ProjectPathsError::WorkspaceRoot => write!(
507 f,
508 "this is a workspace root, not a project — run the command inside a member (`bynk check`, `fmt` and `test` run across every member from here)"
509 ),
510 ProjectPathsError::MemberRegistries { workspace } => write!(
511 f,
512 "`[registries]` belongs in the workspace root's `bynk.toml` (`{}`), not a member's",
513 workspace.join("bynk.toml").display()
514 ),
515 ProjectPathsError::NestedWorkspace { workspace } => write!(
516 f,
517 "this project is a member of the workspace at `{}`, so it can't declare a `[workspace]` of its own",
518 workspace.display()
519 ),
520 }
521 }
522}
523
524pub fn check_manifest(
535 project_root: &Path,
536 overlay: &HashMap<PathBuf, String>,
537) -> Result<(), ProjectPathsError> {
538 let toml_path = project_root.join("bynk.toml");
539 let Ok(content) = read_source(&toml_path, overlay) else {
540 return Ok(());
541 };
542 check_manifest_str(&content)?;
543 let doc = content
547 .parse::<toml::Table>()
548 .map_err(|_| ProjectPathsError::Malformed)?;
549 if (doc.contains_key("registries") || doc.contains_key("workspace"))
550 && let Some(workspace) = crate::workspace::find_parent_workspace(project_root)
551 {
552 return Err(if doc.contains_key("workspace") {
553 ProjectPathsError::NestedWorkspace { workspace }
554 } else {
555 ProjectPathsError::MemberRegistries { workspace }
556 });
557 }
558 Ok(())
559}
560
561pub fn check_manifest_str(content: &str) -> Result<(), ProjectPathsError> {
564 let doc = content
565 .parse::<toml::Table>()
566 .map_err(|_| ProjectPathsError::Malformed)?;
567 let mut declared: Vec<&'static str> = Vec::new();
568 for (name, value) in &doc {
569 if PLANNED_TABLES.iter().any(|(t, _)| t == name) {
572 return Err(ProjectPathsError::UnknownTable(name.clone()));
573 }
574 let known = MANIFEST_TABLES
575 .iter()
576 .map(|(t, keys)| (*t, *keys, false))
577 .chain(
578 MANIFEST_MAP_TABLES
579 .iter()
580 .map(|(t, keys)| (*t, *keys, true)),
581 )
582 .find(|(t, _, _)| t == name);
583 let Some((table, keys, is_map)) = known else {
584 return Err(if value.is_table() {
585 ProjectPathsError::UnknownTable(name.clone())
586 } else {
587 ProjectPathsError::TopLevelKey(name.clone())
588 });
589 };
590 let Some(entries) = value.as_table() else {
594 return Err(ProjectPathsError::TopLevelKey(name.clone()));
595 };
596 declared.push(table);
597 if is_map {
600 match table {
601 "dependencies" | "dev-dependencies" => {
602 crate::manifest::dependencies_from(table, entries)?;
603 }
604 _ => {
605 crate::manifest::registries_from(entries)?;
606 }
607 }
608 continue;
609 }
610 if keys.is_empty() {
611 continue;
612 }
613 for key in entries.keys() {
614 if !keys.contains(&key.as_str()) {
615 return Err(match table {
616 "paths" => ProjectPathsError::UnknownKey(key.clone()),
617 _ => ProjectPathsError::UnknownTableKey {
618 table,
619 key: key.clone(),
620 },
621 });
622 }
623 }
624 match table {
625 "workers" => drop(workers_config_from(entries)?),
626 "build" => drop(build_config_from(entries)?),
627 "profile" => drop(profiles_from(entries)?),
628 "unstable" => drop(unstable_config_from(entries)?),
629 "test" => {
630 drop(test_targets_from(entries)?);
631 test_postgres_from(entries)?;
632 }
633 "package" => drop(crate::manifest::package_config_from(entries)?),
634 "workspace" => drop(crate::manifest::workspace_config_from(entries)?),
635 "deploy" => {
636 drop(crate::hyperdrive::deploy_hyperdrive_from(entries)?);
637 drop(crate::vectorize::deploy_vectorize_from(entries)?);
638 drop(crate::containers::deploy_containers_from(entries)?);
639 drop(crate::worker_groups::deploy_workers_from(entries)?);
640 }
641 "dev" => {
642 drop(crate::hyperdrive::dev_hyperdrive_from(entries)?);
643 drop(crate::dev_ack::dev_acks_from(entries)?);
644 drop(crate::vectorize::dev_vectorize_index_from(entries)?);
645 }
646 _ => {}
647 }
648 }
649 if declared.contains(&"project") && declared.contains(&"package") {
651 return Err(ProjectPathsError::ProjectAndPackage);
652 }
653 if declared.contains(&"workspace")
654 && let Some(other) = declared.iter().find(|t| !WORKSPACE_ROOT_TABLES.contains(t))
655 {
656 return Err(ProjectPathsError::WorkspaceRootTable((*other).to_string()));
657 }
658 Ok(())
659}
660
661pub fn try_read_project_paths(project_root: &Path) -> Result<ProjectPaths, ProjectPathsError> {
671 let toml_path = project_root.join("bynk.toml");
672 let overlay = match fs::read_to_string(&toml_path) {
673 Ok(text) => HashMap::from([(toml_path, text)]),
674 Err(_) => HashMap::new(),
675 };
676 try_read_project_paths_with(project_root, &overlay)
677}
678
679pub fn try_read_project_paths_with(
682 project_root: &Path,
683 overlay: &HashMap<PathBuf, String>,
684) -> Result<ProjectPaths, ProjectPathsError> {
685 let toml_path = project_root.join("bynk.toml");
686 let Ok(content) = read_source(&toml_path, overlay) else {
687 return Ok(ProjectPaths::conventional(project_root));
688 };
689 let Ok(doc) = content.parse::<toml::Table>() else {
690 return Err(ProjectPathsError::Malformed);
691 };
692 let paths = doc.get("paths").and_then(|v| v.as_table());
693 if let Some(t) = paths {
694 for k in t.keys() {
695 if k != "include" && k != "exclude" {
696 return Err(ProjectPathsError::UnknownKey(k.clone()));
697 }
698 }
699 }
700 let list = |key: &str| -> Vec<PathBuf> {
701 match paths.and_then(|t| t.get(key)) {
702 Some(toml::Value::Array(items)) => items
703 .iter()
704 .filter_map(|v| v.as_str())
705 .map(PathBuf::from)
706 .collect(),
707 Some(toml::Value::String(s)) => vec![PathBuf::from(s)],
708 _ => Vec::new(),
709 }
710 };
711 let mut include = list("include");
712 let exclude = list("exclude");
713 if include.is_empty() {
714 include = ProjectPaths::conventional(project_root).include;
715 }
716 Ok(ProjectPaths { include, exclude })
717}
718
719#[derive(Debug, Clone, Default, PartialEq, Eq)]
722pub struct WorkersConfig {
723 pub compatibility_flags: Vec<String>,
729 pub workers_dev: Option<bool>,
733}
734
735pub fn try_read_workers_config_with(
743 project_root: &Path,
744 overlay: &HashMap<PathBuf, String>,
745) -> Result<WorkersConfig, ProjectPathsError> {
746 let toml_path = project_root.join("bynk.toml");
747 let Ok(content) = read_source(&toml_path, overlay) else {
748 return Ok(WorkersConfig::default());
749 };
750 let doc = content
751 .parse::<toml::Table>()
752 .map_err(|_| ProjectPathsError::Malformed)?;
753 match doc.get("workers").and_then(|v| v.as_table()) {
754 Some(t) => workers_config_from(t),
755 None => Ok(WorkersConfig::default()),
756 }
757}
758
759pub fn try_read_workers_config(project_root: &Path) -> Result<WorkersConfig, ProjectPathsError> {
761 let toml_path = project_root.join("bynk.toml");
762 let overlay = match fs::read_to_string(&toml_path) {
763 Ok(text) => HashMap::from([(toml_path, text)]),
764 Err(_) => HashMap::new(),
765 };
766 try_read_workers_config_with(project_root, &overlay)
767}
768
769#[derive(Debug, Clone, Default, PartialEq, Eq)]
773pub struct BuildConfig {
774 pub out: Option<String>,
776 pub target: Option<String>,
778 pub platform: Option<String>,
780 pub emit: Option<String>,
782 pub package_manager: Option<String>,
785 pub client: Option<ClientConfig>,
788 pub profiles: BTreeMap<String, ProfileConfig>,
790}
791
792#[derive(Debug, Clone, PartialEq, Eq)]
795pub struct ClientConfig {
796 pub out: String,
800 pub layout: ClientLayout,
803 pub services: Vec<String>,
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
810pub enum ClientLayout {
811 #[default]
813 File,
814 Dir,
816}
817
818const CLIENT_KEYS: &[&str] = &["out", "layout", "service"];
820
821#[derive(Debug, Clone, Default, PartialEq, Eq)]
824pub struct ProfileConfig {
825 pub contracts: Option<bool>,
827}
828
829pub fn try_read_build_config_with(
833 project_root: &Path,
834 overlay: &HashMap<PathBuf, String>,
835) -> Result<BuildConfig, ProjectPathsError> {
836 let toml_path = project_root.join("bynk.toml");
837 let Ok(content) = read_source(&toml_path, overlay) else {
838 return Ok(BuildConfig::default());
839 };
840 let doc = content
841 .parse::<toml::Table>()
842 .map_err(|_| ProjectPathsError::Malformed)?;
843 let mut config = match doc.get("build").and_then(|v| v.as_table()) {
844 Some(t) => build_config_from(t)?,
845 None => BuildConfig::default(),
846 };
847 if let Some(t) = doc.get("profile").and_then(|v| v.as_table()) {
848 config.profiles = profiles_from(t)?;
849 }
850 Ok(config)
851}
852
853pub fn try_read_profiles(
857 project_root: &Path,
858) -> Result<BTreeMap<String, ProfileConfig>, ProjectPathsError> {
859 let Ok(content) = fs::read_to_string(project_root.join("bynk.toml")) else {
860 return Ok(BTreeMap::new());
861 };
862 let doc = content
863 .parse::<toml::Table>()
864 .map_err(|_| ProjectPathsError::Malformed)?;
865 match doc.get("profile").and_then(|v| v.as_table()) {
866 Some(t) => profiles_from(t),
867 None => Ok(BTreeMap::new()),
868 }
869}
870
871fn profiles_from(
874 table: &toml::Table,
875) -> Result<BTreeMap<String, ProfileConfig>, ProjectPathsError> {
876 let mut out = BTreeMap::new();
877 for (name, value) in table {
878 let bad = |reason: String| ProjectPathsError::BadProfile {
879 profile: name.clone(),
880 reason,
881 };
882 if !PROFILE_NAMES.contains(&name.as_str()) {
883 return Err(ProjectPathsError::UnknownTableKey {
884 table: "profile",
885 key: name.clone(),
886 });
887 }
888 let Some(entries) = value.as_table() else {
889 return Err(bad(format!(
890 "must be a table — write it as `[profile.{name}]`"
891 )));
892 };
893 let mut config = ProfileConfig::default();
894 for (key, v) in entries {
895 if !PROFILE_KEYS.contains(&key.as_str()) {
896 return Err(bad(format!(
897 "has no key named `{key}` — its key is `contracts`"
898 )));
899 }
900 let Some(b) = v.as_bool() else {
901 return Err(bad("`contracts` must be `true` or `false`".to_string()));
902 };
903 config.contracts = Some(b);
904 }
905 out.insert(name.clone(), config);
906 }
907 Ok(out)
908}
909
910pub fn try_read_build_config(project_root: &Path) -> Result<BuildConfig, ProjectPathsError> {
912 let toml_path = project_root.join("bynk.toml");
913 let overlay = match fs::read_to_string(&toml_path) {
914 Ok(text) => HashMap::from([(toml_path, text)]),
915 Err(_) => HashMap::new(),
916 };
917 try_read_build_config_with(project_root, &overlay)
918}
919
920fn build_config_from(table: &toml::Table) -> Result<BuildConfig, ProjectPathsError> {
924 let get = |key: &'static str,
925 allowed: Option<&[&str]>|
926 -> Result<Option<String>, ProjectPathsError> {
927 let Some(v) = table.get(key) else {
928 return Ok(None);
929 };
930 let Some(s) = v.as_str() else {
931 return Err(ProjectPathsError::BadBuild {
932 key,
933 reason: "must be a string".to_string(),
934 });
935 };
936 if let Some(allowed) = allowed
937 && !allowed.contains(&s)
938 {
939 let list: Vec<String> = allowed.iter().map(|a| format!("\"{a}\"")).collect();
940 return Err(ProjectPathsError::BadBuild {
941 key,
942 reason: format!("must be one of {}, not \"{s}\"", list.join(", ")),
943 });
944 }
945 Ok(Some(s.to_string()))
946 };
947 let out = get("out", None)?;
948 if let Some(out) = &out {
949 let path = Path::new(out);
950 let escapes = path.is_absolute()
951 || path
952 .components()
953 .any(|c| matches!(c, std::path::Component::ParentDir));
954 let empty = path
955 .components()
956 .all(|c| matches!(c, std::path::Component::CurDir));
957 if escapes || empty {
958 return Err(ProjectPathsError::BadBuild {
959 key: "out",
960 reason: format!(
961 "must be a directory inside the project (relative, no `..`, not the root), not \"{out}\""
962 ),
963 });
964 }
965 }
966 Ok(BuildConfig {
967 out,
968 client: client_config_from(table.get("client"))?,
969 target: get("target", Some(&["bundle", "workers"]))?,
970 platform: get("platform", Some(&["cloudflare", "node", "browser"]))?,
971 emit: get("emit", Some(&["ts", "js"]))?,
972 package_manager: get("package_manager", Some(&["npm", "pnpm", "bun", "yarn"]))?,
973 profiles: BTreeMap::new(),
974 })
975}
976
977fn client_config_from(
981 value: Option<&toml::Value>,
982) -> Result<Option<ClientConfig>, ProjectPathsError> {
983 let Some(value) = value else {
984 return Ok(None);
985 };
986 let bad = |key: &'static str, reason: &str| ProjectPathsError::BadBuild {
987 key,
988 reason: reason.to_string(),
989 };
990 let Some(table) = value.as_table() else {
991 return Err(bad("client", "must be a table, written `[build.client]`"));
992 };
993 if let Some(key) = table.keys().find(|k| !CLIENT_KEYS.contains(&k.as_str())) {
994 return Err(ProjectPathsError::UnknownTableKey {
995 table: "build.client",
996 key: key.clone(),
997 });
998 }
999 let Some(out) = table.get("out").and_then(|v| v.as_str()) else {
1000 return Err(bad(
1001 "client.out",
1002 "is required, a path such as \"web/src/lib/api.ts\"",
1003 ));
1004 };
1005 let path = Path::new(out);
1006 let nothing = path
1007 .components()
1008 .all(|c| matches!(c, std::path::Component::CurDir));
1009 let rooted = path.components().any(|c| {
1012 matches!(
1013 c,
1014 std::path::Component::RootDir | std::path::Component::Prefix(_)
1015 )
1016 });
1017 if path.is_absolute() || rooted || nothing {
1018 return Err(bad(
1019 "client.out",
1020 "must be a path relative to the project root, not the root itself",
1021 ));
1022 }
1023 let layout = match table.get("layout").map(|v| v.as_str()) {
1024 None => ClientLayout::File,
1025 Some(Some("file")) => ClientLayout::File,
1026 Some(Some("dir")) => ClientLayout::Dir,
1027 Some(_) => return Err(bad("client.layout", "must be \"file\" or \"dir\"")),
1028 };
1029 let services = match table.get("service") {
1030 None => Vec::new(),
1031 Some(toml::Value::Array(items)) => {
1032 let mut out = Vec::new();
1033 for item in items {
1034 let Some(name) = item.as_str() else {
1035 return Err(bad("client.service", "must be a list of service names"));
1036 };
1037 out.push(name.to_string());
1038 }
1039 out
1040 }
1041 Some(_) => return Err(bad("client.service", "must be a list of service names")),
1042 };
1043 Ok(Some(ClientConfig {
1044 out: out.to_string(),
1045 layout,
1046 services,
1047 }))
1048}
1049
1050#[derive(Debug, Clone, Default, PartialEq, Eq)]
1053pub struct TestTarget {
1054 pub urls: BTreeMap<String, String>,
1057 pub secrets: Vec<String>,
1060 pub production: bool,
1062 pub vars: BTreeMap<String, String>,
1065}
1066
1067pub fn try_read_test_targets(
1071 project_root: &Path,
1072) -> Result<BTreeMap<String, TestTarget>, ProjectPathsError> {
1073 let Ok(content) = fs::read_to_string(project_root.join("bynk.toml")) else {
1074 return Ok(BTreeMap::new());
1075 };
1076 let doc = content
1077 .parse::<toml::Table>()
1078 .map_err(|_| ProjectPathsError::Malformed)?;
1079 match doc.get("test").and_then(|v| v.as_table()) {
1080 Some(t) => test_targets_from(t),
1081 None => Ok(BTreeMap::new()),
1082 }
1083}
1084
1085#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1087pub enum TestPostgres {
1088 #[default]
1091 Stub,
1092 Pglite,
1095}
1096
1097pub const PG_SCHEMA_FILE: &str = "schema.sql";
1102
1103fn test_postgres_from(table: &toml::Table) -> Result<TestPostgres, ProjectPathsError> {
1105 match table.get("postgres") {
1106 None => Ok(TestPostgres::Stub),
1107 Some(toml::Value::String(s)) if s == "stub" => Ok(TestPostgres::Stub),
1108 Some(toml::Value::String(s)) if s == "pglite" => Ok(TestPostgres::Pglite),
1109 Some(_) => Err(ProjectPathsError::BadTestPostgres {
1110 reason: "must be `\"stub\"` (the default) or `\"pglite\"`".to_string(),
1111 }),
1112 }
1113}
1114
1115pub fn test_postgres_of(doc: &toml::Table) -> TestPostgres {
1118 doc.get("test")
1119 .and_then(|v| v.as_table())
1120 .and_then(|t| test_postgres_from(t).ok())
1121 .unwrap_or_default()
1122}
1123
1124pub fn read_test_postgres(project_root: &Path) -> TestPostgres {
1127 fs::read_to_string(project_root.join("bynk.toml"))
1128 .ok()
1129 .and_then(|c| c.parse::<toml::Table>().ok())
1130 .map(|doc| test_postgres_of(&doc))
1131 .unwrap_or_default()
1132}
1133
1134fn test_targets_from(
1140 table: &toml::Table,
1141) -> Result<BTreeMap<String, TestTarget>, ProjectPathsError> {
1142 let mut out = BTreeMap::new();
1143 let Some(targets) = table.get("targets") else {
1144 return Ok(out);
1145 };
1146 let Some(targets) = targets.as_table() else {
1147 return Err(ProjectPathsError::BadTestTarget {
1148 target: "…".to_string(),
1149 reason: "must be a table of named targets, like `[test.targets.preview]`".to_string(),
1150 });
1151 };
1152 for (name, entry) in targets {
1153 let bad = |reason: &str| ProjectPathsError::BadTestTarget {
1154 target: name.clone(),
1155 reason: reason.to_string(),
1156 };
1157 let Some(entry) = entry.as_table() else {
1158 return Err(bad("must be a table"));
1159 };
1160 let strings =
1161 |v: &toml::Value, what: &str| -> Result<BTreeMap<String, String>, ProjectPathsError> {
1162 v.as_table()
1163 .ok_or_else(|| bad(&format!("`{what}` must be a table of strings")))?
1164 .iter()
1165 .map(|(k, v)| {
1166 v.as_str()
1167 .map(|s| (k.clone(), s.to_string()))
1168 .ok_or_else(|| bad(&format!("`{what}.{k}` must be a string")))
1169 })
1170 .collect()
1171 };
1172 let mut target = TestTarget::default();
1173 for (key, value) in entry {
1174 match key.as_str() {
1175 "url" => target.urls = strings(value, "url")?,
1176 "vars" => {
1177 target.vars = strings(value, "vars")?;
1178 if let Some(reserved) = target
1182 .vars
1183 .keys()
1184 .find(|k| k.starts_with(crate::env_protocol::DATASET_PREFIX))
1185 {
1186 return Err(bad(&format!(
1187 "`vars.{reserved}` is reserved: `{}…` names are set by `bynk` to carry each `Analytics` dataset's name",
1188 crate::env_protocol::DATASET_PREFIX
1189 )));
1190 }
1191 }
1192 "secrets" => {
1193 target.secrets = value
1194 .as_array()
1195 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect())
1196 .ok_or_else(|| bad("`secrets` must be a list of names"))?;
1197 }
1198 "production" => {
1199 target.production = value
1200 .as_bool()
1201 .ok_or_else(|| bad("`production` must be `true` or `false`"))?;
1202 }
1203 other => {
1204 return Err(bad(&format!(
1205 "has no key named `{other}` — its keys are `url`, `secrets`, `vars` and `production`"
1206 )));
1207 }
1208 }
1209 }
1210 if target.urls.is_empty() {
1211 return Err(bad(
1212 "names no Worker URL — add `url.<worker> = \"https://…\"`",
1213 ));
1214 }
1215 out.insert(name.clone(), target);
1216 }
1217 Ok(out)
1218}
1219
1220pub fn try_read_mutate_exclude(project_root: &Path) -> Result<Vec<String>, String> {
1225 let Ok(content) = fs::read_to_string(project_root.join("bynk.toml")) else {
1226 return Ok(Vec::new());
1227 };
1228 let doc = content
1229 .parse::<toml::Table>()
1230 .map_err(|_| "`bynk.toml` is not valid TOML".to_string())?;
1231 let Some(mutate) = doc
1232 .get("test")
1233 .and_then(|v| v.as_table())
1234 .and_then(|t| t.get("mutate"))
1235 else {
1236 return Ok(Vec::new());
1237 };
1238 let table = mutate
1239 .as_table()
1240 .ok_or_else(|| "`[test.mutate]` must be a table".to_string())?;
1241 let mut exclude = Vec::new();
1242 for (key, value) in table {
1243 match key.as_str() {
1244 "exclude" => {
1245 let list = value
1246 .as_array()
1247 .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect())
1248 .ok_or_else(|| {
1249 "`[test.mutate] exclude` must be a list of strings".to_string()
1250 })?;
1251 exclude = list;
1252 }
1253 other => {
1254 return Err(format!(
1255 "`[test.mutate]` has no key named `{other}` — its only key is `exclude`"
1256 ));
1257 }
1258 }
1259 }
1260 Ok(exclude)
1261}
1262
1263pub fn duplicate_compatibility_flag_warning(
1271 flag: &str,
1272 default: bool,
1273 manifest: PathBuf,
1274) -> crate::AttributedError {
1275 let message = if default {
1276 format!(
1277 "`bynk.toml`'s `[workers] compatibility_flags` lists `{flag}`, which every Bynk Worker already has"
1278 )
1279 } else {
1280 format!("`bynk.toml`'s `[workers] compatibility_flags` lists `{flag}` more than once")
1281 };
1282 let mut error = bynk_syntax::CompileError::new(
1283 "bynk.project.duplicate_compatibility_flag",
1284 bynk_syntax::span::Span::default(),
1285 message,
1286 );
1287 error
1288 .notes
1289 .push("the duplicate is dropped; remove it from `bynk.toml`".to_string());
1290 crate::AttributedError::new(Some(manifest), error)
1291}
1292
1293fn workers_config_from(table: &toml::Table) -> Result<WorkersConfig, ProjectPathsError> {
1296 let not_a_list = || ProjectPathsError::NotAStringList {
1297 table: "workers",
1298 key: "compatibility_flags",
1299 };
1300 let compatibility_flags = match table.get("compatibility_flags") {
1301 None => Vec::new(),
1302 Some(toml::Value::Array(items)) => items
1303 .iter()
1304 .map(|v| v.as_str().map(str::to_owned).ok_or_else(not_a_list))
1305 .collect::<Result<_, _>>()?,
1306 Some(_) => return Err(not_a_list()),
1307 };
1308 let workers_dev = match table.get("workers_dev") {
1309 None => None,
1310 Some(toml::Value::Boolean(b)) => Some(*b),
1311 Some(_) => {
1312 return Err(ProjectPathsError::NotABool {
1313 table: "workers",
1314 key: "workers_dev",
1315 });
1316 }
1317 };
1318 Ok(WorkersConfig {
1319 compatibility_flags,
1320 workers_dev,
1321 })
1322}
1323
1324#[derive(Debug, Clone, Default, PartialEq, Eq)]
1327pub struct UnstableConfig {
1328 pub allow: Vec<String>,
1333}
1334
1335pub fn try_read_unstable_config_with(
1340 project_root: &Path,
1341 overlay: &HashMap<PathBuf, String>,
1342) -> Result<UnstableConfig, ProjectPathsError> {
1343 let toml_path = project_root.join("bynk.toml");
1344 let Ok(content) = read_source(&toml_path, overlay) else {
1345 return Ok(UnstableConfig::default());
1346 };
1347 let doc = content
1348 .parse::<toml::Table>()
1349 .map_err(|_| ProjectPathsError::Malformed)?;
1350 match doc.get("unstable").and_then(|v| v.as_table()) {
1351 Some(t) => unstable_config_from(t),
1352 None => Ok(UnstableConfig::default()),
1353 }
1354}
1355
1356pub fn try_read_unstable_config(project_root: &Path) -> Result<UnstableConfig, ProjectPathsError> {
1358 let toml_path = project_root.join("bynk.toml");
1359 let overlay = match fs::read_to_string(&toml_path) {
1360 Ok(text) => HashMap::from([(toml_path, text)]),
1361 Err(_) => HashMap::new(),
1362 };
1363 try_read_unstable_config_with(project_root, &overlay)
1364}
1365
1366pub fn read_unstable_config(
1372 project_root: &Path,
1373 overlay: &HashMap<PathBuf, String>,
1374) -> UnstableConfig {
1375 let manifest = project_root.join("bynk.toml");
1376 let read = if overlay.contains_key(&manifest) {
1377 try_read_unstable_config_with(project_root, overlay)
1378 } else {
1379 try_read_unstable_config(project_root)
1380 };
1381 read.unwrap_or_default()
1382}
1383
1384fn unstable_config_from(table: &toml::Table) -> Result<UnstableConfig, ProjectPathsError> {
1387 let not_a_list = || ProjectPathsError::NotAStringList {
1388 table: "unstable",
1389 key: "allow",
1390 };
1391 let allow = match table.get("allow") {
1392 None => Vec::new(),
1393 Some(toml::Value::Array(items)) => items
1394 .iter()
1395 .map(|v| v.as_str().map(str::to_owned).ok_or_else(not_a_list))
1396 .collect::<Result<_, _>>()?,
1397 Some(_) => return Err(not_a_list()),
1398 };
1399 Ok(UnstableConfig { allow })
1400}
1401
1402#[derive(Debug, Clone, PartialEq, Eq)]
1405pub struct CheckConfig {
1406 pub d1_sql: bool,
1409}
1410
1411impl Default for CheckConfig {
1412 fn default() -> Self {
1413 Self { d1_sql: true }
1414 }
1415}
1416
1417pub fn read_check_config(project_root: &Path, overlay: &HashMap<PathBuf, String>) -> CheckConfig {
1422 let manifest = project_root.join("bynk.toml");
1423 let content = match overlay.get(&manifest) {
1424 Some(text) => Some(text.clone()),
1425 None => fs::read_to_string(&manifest).ok(),
1426 };
1427 let d1_sql = content
1428 .and_then(|c| c.parse::<toml::Table>().ok())
1429 .and_then(|doc| doc.get("check")?.as_table()?.get("d1_sql")?.as_bool())
1430 .unwrap_or(true);
1431 CheckConfig { d1_sql }
1432}
1433
1434pub fn commons_dir_for(name: &str) -> PathBuf {
1440 let mut p = PathBuf::new();
1441 let mut parts = name.split('.');
1442 let first = parts.next().unwrap_or_default();
1443 match crate::packages::PackageId::decode(first) {
1444 Some(id) => p.push(id.out_dir()),
1445 None => p.push(first),
1446 }
1447 for part in parts {
1448 p.push(part);
1449 }
1450 p
1451}
1452
1453pub fn ts_output_path(source: &Path) -> PathBuf {
1454 let mut out = source.to_path_buf();
1455 out.set_extension("ts");
1456 out
1457}
1458
1459pub fn worker_dir_name(context: &str) -> String {
1462 context.replace('.', "-")
1463}
1464
1465pub fn worker_handlers_source_path(context: &str) -> PathBuf {
1469 PathBuf::from(format!(
1470 "workers/{}/handlers.bynk",
1471 worker_dir_name(context)
1472 ))
1473}
1474
1475pub fn worker_handlers_output_path(context: &str) -> PathBuf {
1477 PathBuf::from(format!("workers/{}/handlers.ts", worker_dir_name(context)))
1478}
1479
1480pub fn worker_file_source_path(context: &str, source: &Path) -> PathBuf {
1492 let stem = source.file_stem().unwrap_or_default().to_string_lossy();
1493 PathBuf::from(format!(
1494 "workers/{}/handlers/{stem}.bynk",
1495 worker_dir_name(context)
1496 ))
1497}
1498
1499fn stem_parts(rel_path: &Path) -> Vec<String> {
1502 rel_path
1503 .with_extension("")
1504 .components()
1505 .filter_map(|c| match c {
1506 Component::Normal(s) => Some(s.to_string_lossy().to_string()),
1507 _ => None,
1508 })
1509 .collect()
1510}
1511
1512pub fn unit_path_matches(rel_path: &Path, qualified_name: &str) -> bool {
1521 let dir = commons_dir_for(qualified_name);
1524 let owned: Vec<String> = dir
1525 .components()
1526 .map(|c| c.as_os_str().to_string_lossy().into_owned())
1527 .collect();
1528 let name_parts: Vec<&str> = owned.iter().map(String::as_str).collect();
1529 let stem_parts = stem_parts(rel_path);
1530 let single_file_match = stem_parts.len() == name_parts.len()
1531 && stem_parts
1532 .iter()
1533 .zip(name_parts.iter())
1534 .all(|(a, b)| a == b);
1535 single_file_match || is_multi_file_parts(&stem_parts, &name_parts)
1536}
1537
1538fn is_multi_file_parts(stem_parts: &[String], name_parts: &[&str]) -> bool {
1541 if stem_parts.is_empty() {
1542 return false;
1543 }
1544 let parent_parts = &stem_parts[..stem_parts.len() - 1];
1545 parent_parts.len() == name_parts.len()
1546 && parent_parts
1547 .iter()
1548 .zip(name_parts.iter())
1549 .all(|(a, b)| a == b)
1550}
1551
1552pub fn is_multi_file_layout(rel_path: &Path, qualified_name: &str) -> bool {
1562 let name_parts: Vec<&str> = qualified_name.split('.').collect();
1563 is_multi_file_parts(&stem_parts(rel_path), &name_parts)
1564}
1565
1566pub fn renamed_unit_name(old_rel: &Path, old_name: &str, new_rel: &Path) -> Option<String> {
1581 let name_parts: Vec<&str> = old_name.split('.').collect();
1582 let old_stem = stem_parts(old_rel);
1583 let new_stem = stem_parts(new_rel);
1584
1585 let suffix_matches = |haystack: &[String]| {
1586 haystack.len() >= name_parts.len() && {
1587 let prefix_len = haystack.len() - name_parts.len();
1588 haystack[prefix_len..]
1589 .iter()
1590 .zip(name_parts.iter())
1591 .all(|(a, b)| a == b)
1592 }
1593 };
1594
1595 if suffix_matches(&old_stem) {
1596 let prefix_len = old_stem.len() - name_parts.len();
1597 return (new_stem.len() >= prefix_len).then(|| new_stem[prefix_len..].join("."));
1598 }
1599 if !old_stem.is_empty() {
1600 let old_parent = &old_stem[..old_stem.len() - 1];
1601 if suffix_matches(old_parent) {
1602 let prefix_len = old_parent.len() - name_parts.len();
1603 if new_stem.is_empty() {
1604 return None;
1605 }
1606 let new_parent = &new_stem[..new_stem.len() - 1];
1607 return (new_parent.len() >= prefix_len).then(|| new_parent[prefix_len..].join("."));
1608 }
1609 }
1610 None
1611}
1612
1613#[cfg(test)]
1614mod tests {
1615 use super::*;
1616 use std::path::{Path, PathBuf};
1617
1618 #[test]
1620 fn is_unpinned_range_true_for_wildcards_and_digitless() {
1621 assert!(is_unpinned_range(""));
1622 assert!(is_unpinned_range("*"));
1623 assert!(is_unpinned_range("x"));
1624 assert!(is_unpinned_range("X"));
1625 assert!(is_unpinned_range("latest"));
1626 assert!(is_unpinned_range("LATEST"));
1627 assert!(is_unpinned_range(" * ")); assert!(is_unpinned_range("workspace:*")); assert!(is_unpinned_range("beta"));
1630 }
1631
1632 #[test]
1633 fn is_unpinned_range_false_when_a_digit_is_present() {
1634 assert!(!is_unpinned_range("1.0.0"));
1635 assert!(!is_unpinned_range("^1.2"));
1636 assert!(!is_unpinned_range("~0.1"));
1637 assert!(!is_unpinned_range(">=2"));
1638 assert!(!is_unpinned_range("18"));
1639 }
1640
1641 #[test]
1643 fn read_project_paths_with_honours_a_virtual_bynk_toml() {
1644 let root = PathBuf::from("/nonexistent-bynk-test-root-57");
1645 let mut overlay = HashMap::new();
1646 overlay.insert(
1647 root.join("bynk.toml"),
1648 "[paths]\ninclude = [\"app\"]\nexclude = [\"vendor\"]\n".to_string(),
1649 );
1650 let paths = read_project_paths_with(&root, &overlay);
1651 assert_eq!(paths.include, vec![PathBuf::from("app")]);
1652 assert_eq!(paths.exclude, vec![PathBuf::from("vendor")]);
1653 }
1654
1655 #[test]
1656 fn read_project_paths_with_falls_back_to_conventional_with_no_overlay_entry() {
1657 let root = PathBuf::from("/nonexistent-bynk-test-root-57-empty");
1660 let paths = read_project_paths_with(&root, &HashMap::new());
1661 let conventional = ProjectPaths::conventional(&root);
1662 assert_eq!(paths.include, conventional.include);
1663 assert_eq!(paths.exclude, conventional.exclude);
1664 }
1665
1666 #[test]
1669 fn read_project_paths_with_honours_three_or_more_include_entries() {
1670 let root = PathBuf::from("/nonexistent-bynk-test-root-1113-many-includes");
1671 let mut overlay = HashMap::new();
1672 overlay.insert(
1673 root.join("bynk.toml"),
1674 "[paths]\ninclude = [\"src\", \"tests\", \"examples\"]\n".to_string(),
1675 );
1676 let paths = try_read_project_paths_with(&root, &overlay).expect("must parse");
1677 assert_eq!(
1678 paths.include,
1679 vec![
1680 PathBuf::from("src"),
1681 PathBuf::from("tests"),
1682 PathBuf::from("examples"),
1683 ]
1684 );
1685 }
1686
1687 #[test]
1689 fn render_package_json_declares_es_modules() {
1690 let bare = render_package_json(&std::collections::BTreeMap::new());
1692 assert_eq!(bare, "{\n \"type\": \"module\"\n}\n");
1693 let mut deps = std::collections::BTreeMap::new();
1694 deps.insert("jose".to_string(), "^5.0.0".to_string());
1695 let with_deps = render_package_json(&deps);
1696 assert_eq!(
1697 with_deps,
1698 "{\n \"type\": \"module\",\n \"dependencies\": {\n \"jose\": \"^5.0.0\"\n }\n}\n"
1699 );
1700 }
1701
1702 #[test]
1703 fn render_package_json_renders_sorted_dependencies() {
1704 let mut deps = std::collections::BTreeMap::new();
1705 deps.insert("zod".to_string(), "^3.22.4".to_string());
1706 deps.insert("hono".to_string(), "^4.0.0".to_string());
1707 let out = render_package_json(&deps);
1708 assert!(
1710 out.find("\"hono\"").unwrap() < out.find("\"zod\"").unwrap(),
1711 "dependencies render in sorted order:\n{out}"
1712 );
1713 assert!(out.contains("\"hono\": \"^4.0.0\""), "{out}");
1714 }
1715
1716 #[test]
1722 fn render_package_json_escapes_the_control_range() {
1723 let mut deps = std::collections::BTreeMap::new();
1724 deps.insert("pkg\nname".to_string(), "^1.0\u{1}0".to_string());
1725 let out = render_package_json(&deps);
1726 assert!(out.contains("\"pkg\\nname\""), "{out}");
1727 assert!(out.contains("\"^1.0\\u00010\""), "{out}");
1728 assert!(
1731 !out.lines().any(|l| l.chars().any(|c| (c as u32) < 0x20)),
1732 "a raw control character reached the output:\n{out:?}"
1733 );
1734 }
1735
1736 #[test]
1737 fn render_package_json_escapes_structural_characters() {
1738 let mut deps = std::collections::BTreeMap::new();
1739 deps.insert("a\"b".to_string(), "c\\d".to_string());
1740 let out = render_package_json(&deps);
1741 assert!(out.contains(r#""a\"b": "c\\d""#), "{out}");
1742 }
1743
1744 #[test]
1746 fn normalize_rel_resolves_dot_and_parent() {
1747 assert_eq!(
1748 normalize_rel(Path::new("./tokens.binding.ts")),
1749 PathBuf::from("tokens.binding.ts")
1750 );
1751 assert_eq!(normalize_rel(Path::new("a/./b")), PathBuf::from("a/b"));
1752 assert_eq!(normalize_rel(Path::new("a/../b")), PathBuf::from("b"));
1753 assert_eq!(normalize_rel(Path::new("a/b/../../c")), PathBuf::from("c"));
1754 assert_eq!(normalize_rel(Path::new("a/b")), PathBuf::from("a/b"));
1755 }
1756
1757 #[test]
1758 fn normalize_rel_drops_root_and_pops_through_empty() {
1759 assert_eq!(normalize_rel(Path::new("/a/b")), PathBuf::from("a/b"));
1761 assert_eq!(normalize_rel(Path::new("../a")), PathBuf::from("a"));
1763 }
1764
1765 #[test]
1767 fn commons_dir_for_splits_dotted_name_into_dirs() {
1768 assert_eq!(commons_dir_for("a.b.c"), PathBuf::from("a/b/c"));
1769 assert_eq!(commons_dir_for("foo"), PathBuf::from("foo"));
1770 }
1771
1772 #[test]
1773 fn ts_output_path_sets_ts_extension() {
1774 assert_eq!(
1775 ts_output_path(Path::new("foo.bynk")),
1776 PathBuf::from("foo.ts")
1777 );
1778 assert_eq!(
1779 ts_output_path(Path::new("a/b.bynk")),
1780 PathBuf::from("a/b.ts")
1781 );
1782 assert_eq!(ts_output_path(Path::new("foo")), PathBuf::from("foo.ts"));
1783 }
1784
1785 #[test]
1787 fn worker_paths_dasherise_and_root_under_workers() {
1788 assert_eq!(worker_dir_name("commerce.payment"), "commerce-payment");
1789 assert_eq!(worker_dir_name("plain"), "plain");
1790 assert_eq!(
1791 worker_handlers_source_path("commerce.payment"),
1792 PathBuf::from("workers/commerce-payment/handlers.bynk")
1793 );
1794 assert_eq!(
1795 worker_handlers_output_path("commerce.payment"),
1796 PathBuf::from("workers/commerce-payment/handlers.ts")
1797 );
1798 }
1799
1800 #[test]
1801 fn a_split_context_file_has_its_own_module_under_handlers() {
1802 assert_eq!(
1803 worker_file_source_path("shop.orders", Path::new("shop/orders/place.bynk")),
1804 PathBuf::from("workers/shop-orders/handlers/place.bynk")
1805 );
1806 }
1807
1808 #[test]
1810 fn unit_path_matches_single_file_layout() {
1811 assert!(unit_path_matches(Path::new("a/b/c.bynk"), "a.b.c"));
1812 assert!(unit_path_matches(Path::new("foo.bynk"), "foo"));
1813 }
1814
1815 #[test]
1816 fn unit_path_matches_multi_file_layout() {
1817 assert!(unit_path_matches(Path::new("a/b/c/handlers.bynk"), "a.b.c"));
1819 assert!(unit_path_matches(Path::new("a/b/c/anything.bynk"), "a.b.c"));
1820 }
1821
1822 #[test]
1823 fn unit_path_matches_rejects_misalignment() {
1824 assert!(!unit_path_matches(Path::new("a/b.bynk"), "a.b.c"));
1825 assert!(!unit_path_matches(Path::new("x/y/z.bynk"), "a.b.c"));
1826 }
1827
1828 #[test]
1830 fn is_multi_file_layout_true_only_for_directory_layout() {
1831 assert!(is_multi_file_layout(Path::new("thing/a.bynk"), "thing"));
1833 assert!(is_multi_file_layout(Path::new("thing/b.bynk"), "thing"));
1834 assert!(is_multi_file_layout(Path::new("a/b/one.bynk"), "a.b"));
1836 }
1837
1838 #[test]
1839 fn is_multi_file_layout_false_for_single_file_and_misalignment() {
1840 assert!(!is_multi_file_layout(Path::new("thing.bynk"), "thing"));
1842 assert!(!is_multi_file_layout(Path::new("a/b.bynk"), "a.b"));
1844 assert!(!is_multi_file_layout(Path::new("other/a.bynk"), "thing"));
1846 }
1847
1848 #[test]
1850 fn renamed_unit_name_single_file() {
1851 assert_eq!(
1852 renamed_unit_name(
1853 Path::new("a/b/c.bynk"),
1854 "a.b.c",
1855 Path::new("a/b/renamed.bynk")
1856 ),
1857 Some("a.b.renamed".to_string())
1858 );
1859 assert_eq!(
1860 renamed_unit_name(Path::new("foo.bynk"), "foo", Path::new("bar.bynk")),
1861 Some("bar".to_string())
1862 );
1863 }
1864
1865 #[test]
1866 fn renamed_unit_name_multi_file_member_rename_is_a_no_op() {
1867 assert_eq!(
1871 renamed_unit_name(
1872 Path::new("a/b/c/old.bynk"),
1873 "a.b.c",
1874 Path::new("a/b/c/new.bynk")
1875 ),
1876 Some("a.b.c".to_string())
1877 );
1878 }
1879
1880 #[test]
1881 fn renamed_unit_name_multi_file_directory_move() {
1882 assert_eq!(
1883 renamed_unit_name(
1884 Path::new("a/b/c/handlers.bynk"),
1885 "a.b.c",
1886 Path::new("a/b/renamed/handlers.bynk")
1887 ),
1888 Some("a.b.renamed".to_string())
1889 );
1890 }
1891
1892 #[test]
1893 fn renamed_unit_name_none_on_preexisting_misalignment() {
1894 assert_eq!(
1895 renamed_unit_name(Path::new("x/y/z.bynk"), "a.b.c", Path::new("x/y/w.bynk")),
1896 None
1897 );
1898 }
1899
1900 #[test]
1901 fn renamed_unit_name_tolerates_a_shared_include_root_prefix() {
1902 assert_eq!(
1908 renamed_unit_name(
1909 Path::new("src/billing/charge.bynk"),
1910 "billing.charge",
1911 Path::new("src/billing/pay.bynk")
1912 ),
1913 Some("billing.pay".to_string())
1914 );
1915 assert_eq!(
1917 renamed_unit_name(
1918 Path::new("src/a/b/c/handlers.bynk"),
1919 "a.b.c",
1920 Path::new("src/a/b/renamed/handlers.bynk")
1921 ),
1922 Some("a.b.renamed".to_string())
1923 );
1924 }
1925}
1926
1927#[cfg(test)]
1928mod manifest_tests {
1929 use super::*;
1930
1931 fn err(manifest: &str) -> String {
1932 check_manifest_str(manifest)
1933 .expect_err("the manifest is refused")
1934 .to_string()
1935 }
1936
1937 #[test]
1939 fn the_documented_tables_are_accepted() {
1940 check_manifest_str(
1941 "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[paths]\ninclude = [\"src\"]\nexclude = []\n\n\
1942 [fmt]\nindent = \"tab\"\nmax_line_width = 100\n\n[lsp]\ndiagnostics_mode = \"live\"\n\
1943 diagnostics_debounce_ms = 300\n\n[workers]\ncompatibility_flags = [\"nodejs_compat\"]\n",
1944 )
1945 .expect("accepted");
1946 check_manifest_str("").expect("an empty manifest is accepted");
1947 }
1948
1949 #[test]
1952 fn the_build_client_table_is_read() {
1953 let read = |client: &str| {
1954 let manifest = format!(
1955 "[project]\nname = \"p\"\n\n[build]\nout = \"out\"\n\n[build.client]\n{client}"
1956 );
1957 check_manifest_str(&manifest)?;
1958 let overlay = HashMap::from([(PathBuf::from("/p/bynk.toml"), manifest)]);
1959 try_read_build_config_with(Path::new("/p"), &overlay).map(|c| c.client)
1960 };
1961 assert_eq!(
1962 read("out = \"web/api.ts\"").unwrap(),
1963 Some(ClientConfig {
1964 out: "web/api.ts".to_string(),
1965 layout: ClientLayout::File,
1966 services: Vec::new(),
1967 })
1968 );
1969 assert_eq!(
1970 read("out = \"../web/api\"\nlayout = \"dir\"\nservice = [\"a\", \"u.B\"]").unwrap(),
1971 Some(ClientConfig {
1972 out: "../web/api".to_string(),
1973 layout: ClientLayout::Dir,
1974 services: vec!["a".to_string(), "u.B".to_string()],
1975 })
1976 );
1977 for (table, needle) in [
1978 ("layout = \"dir\"", "client.out"),
1979 ("out = \"\"", "client.out"),
1980 ("out = \".\"", "client.out"),
1981 ("out = \"a.ts\"\nlayout = \"zip\"", "client.layout"),
1982 ("out = \"a.ts\"\nservice = [1]", "client.service"),
1983 ("out = \"a.ts\"\nbogus = 1", "bogus"),
1984 ] {
1985 let e = read(table).expect_err(table).to_string();
1986 assert!(e.contains(needle), "{table}: {e}");
1987 }
1988 let overlay = HashMap::from([(
1990 PathBuf::from("/p/bynk.toml"),
1991 "[build]\nout = \"out\"\n".to_string(),
1992 )]);
1993 assert_eq!(
1994 try_read_build_config_with(Path::new("/p"), &overlay)
1995 .unwrap()
1996 .client,
1997 None
1998 );
1999 }
2000
2001 #[test]
2002 fn the_deploy_and_dev_tables_take_hyperdrive_entries_only() {
2003 check_manifest_str(
2004 "[deploy.hyperdrive.Main]\nconnection_env = \"MAIN_DATABASE_URL\"\n\n\
2005 [dev.hyperdrive.Main]\nconnection_env = \"LOCAL_URL\"\n",
2006 )
2007 .expect("accepted");
2008 assert!(err("[deploy]\ngroups = []\n").contains("`groups`"));
2009 assert!(err("[dev]\nport = 1\n").contains("`port`"));
2010 assert!(
2011 err("[deploy.hyperdrive.Main]\nconnection_env = \"postgres://u:p@h/d\"\n")
2012 .contains("not the string itself")
2013 );
2014 }
2015
2016 #[test]
2017 fn a_typod_table_suggests_the_nearest() {
2018 assert!(err("[pahts]\n").contains("did you mean `[paths]`?"));
2019 assert!(err("[fnt]\n").contains("did you mean `[fmt]`?"));
2020 assert!(err("[zzzzzz]\n").contains("the tables are"));
2021 }
2022
2023 #[test]
2024 fn an_unknown_key_in_project_or_lsp_suggests_the_nearest() {
2025 assert!(err("[project]\nnmae = \"p\"\n").contains("did you mean `name`?"));
2026 assert!(
2027 err("[lsp]\ndiagnostics_mod = \"live\"\n").contains("did you mean `diagnostics_mode`?")
2028 );
2029 assert!(err("[project]\nlicense = \"MIT\"\n").contains("its keys are `name`, `version`"));
2030 }
2031
2032 #[test]
2033 fn a_paths_key_keeps_its_own_error() {
2034 assert!(matches!(
2035 check_manifest_str("[paths]\nout = \"out\"\n"),
2036 Err(ProjectPathsError::UnknownKey(k)) if k == "out"
2037 ));
2038 }
2039
2040 #[test]
2041 fn a_top_level_key_points_at_its_table() {
2042 assert!(err("name = \"p\"\n").contains("did you mean it under `[project]`?"));
2043 }
2044
2045 #[test]
2048 fn a_table_name_with_a_plain_value_must_be_a_table() {
2049 assert!(err("paths = \"src\"\n").contains("must be a table — write it as `[paths]`"));
2050 assert!(err("lsp = 3\n").contains("`[lsp]`"));
2051 assert!(err("fmt = true\n").contains("`[fmt]`"));
2052 check_manifest_str("paths = { include = [\"src\"] }\n").expect("accepted");
2054 }
2055
2056 #[test]
2059 fn a_table_in_another_shape_is_refused() {
2060 assert!(err("[[deploy]]\nname = \"acme\"\n").contains("`deploy`"));
2061 assert!(err("deploy = [\"acme\"]\n").contains("`deploy`"));
2062 }
2063
2064 #[test]
2066 fn a_map_table_in_another_shape_must_be_a_table() {
2067 assert_eq!(
2068 err("[[dependencies]]\nname = \"acme\"\n"),
2069 "`dependencies` in `bynk.toml` must be a table — write it as `[dependencies]`"
2070 );
2071 assert_eq!(
2072 err("registries = [\"acme\"]\n"),
2073 "`registries` in `bynk.toml` must be a table — write it as `[registries]`"
2074 );
2075 assert_eq!(
2076 err("[dependencis]\n"),
2077 "`bynk.toml` has no table named `[dependencis]` — did you mean `[dependencies]`?"
2078 );
2079 }
2080
2081 #[test]
2083 fn fmt_keys_are_left_to_the_formatter() {
2084 check_manifest_str("[fmt]\nanything = 1\n").expect("not this check's concern");
2085 }
2086
2087 #[test]
2090 fn workers_compatibility_flags_must_be_a_list_of_strings() {
2091 let msg = "`[workers]` `compatibility_flags` must be a list of strings";
2092 assert!(err("[workers]\ncompatibility_flags = \"nodejs_compat\"\n").contains(msg));
2093 assert!(err("[workers]\ncompatibility_flags = [\"a\", 1]\n").contains(msg));
2094 assert!(err("[workers]\ncompatibility_flags = [[\"a\"]]\n").contains(msg));
2095 assert!(
2096 err("[workers]\ncompatibility_flag = []\n")
2097 .contains("did you mean `compatibility_flags`?")
2098 );
2099 check_manifest_str("[workers]\ncompatibility_flags = [\"no_such_flag_yet\"]\n")
2100 .expect("flag names are not validated");
2101 check_manifest_str("[workers]\n").expect("an empty `[workers]` is accepted");
2102 }
2103
2104 #[test]
2107 fn unstable_allow_must_be_a_list_of_strings() {
2108 let msg = "`[unstable]` `allow` must be a list of strings";
2109 assert!(err("[unstable]\nallow = \"bynk.cloudflare.R2\"\n").contains(msg));
2110 assert!(err("[unstable]\nallow = [\"a\", 1]\n").contains(msg));
2111 assert!(err("[unstable]\nallows = []\n").contains("did you mean `allow`?"));
2112 check_manifest_str("[unstable]\nallow = [\"bynk.anything\"]\n")
2113 .expect("item paths are the checker's to validate");
2114 check_manifest_str("[unstable]\n").expect("an empty `[unstable]` is accepted");
2115 }
2116
2117 #[test]
2118 fn unstable_config_reads_the_entries_in_order() {
2119 let root = PathBuf::from("/nonexistent-bynk-test-root-1963");
2120 let read = |manifest: &str| {
2121 let overlay = HashMap::from([(root.join("bynk.toml"), manifest.to_string())]);
2122 try_read_unstable_config_with(&root, &overlay)
2123 };
2124 assert_eq!(
2125 read("[unstable]\nallow = [\"b.x\", \"a.y\"]\n")
2126 .unwrap()
2127 .allow,
2128 vec!["b.x", "a.y"]
2129 );
2130 assert_eq!(
2131 read("[project]\nname = \"p\"\n").unwrap(),
2132 UnstableConfig::default()
2133 );
2134 assert!(matches!(
2135 read("[unstable]\nallow = 3\n"),
2136 Err(ProjectPathsError::NotAStringList {
2137 table: "unstable",
2138 key: "allow"
2139 })
2140 ));
2141 }
2142
2143 #[test]
2144 fn workers_config_reads_the_flags_in_order() {
2145 let root = PathBuf::from("/nonexistent-bynk-test-root-1890");
2146 let read = |manifest: &str| {
2147 let overlay = HashMap::from([(root.join("bynk.toml"), manifest.to_string())]);
2148 try_read_workers_config_with(&root, &overlay)
2149 };
2150 assert_eq!(
2151 read("[workers]\ncompatibility_flags = [\"b\", \"a\", \"b\"]\n")
2152 .unwrap()
2153 .compatibility_flags,
2154 vec!["b", "a", "b"],
2155 "order and duplicates are kept; deduplication is the emitter's"
2156 );
2157 assert_eq!(
2158 read("[project]\nname = \"p\"\n").unwrap(),
2159 WorkersConfig::default()
2160 );
2161 assert_eq!(
2162 try_read_workers_config_with(&root, &HashMap::new()).unwrap(),
2163 WorkersConfig::default(),
2164 "no manifest at all"
2165 );
2166 assert!(matches!(
2167 read("[workers]\ncompatibility_flags = [true]\n"),
2168 Err(ProjectPathsError::NotAStringList { .. })
2169 ));
2170 assert!(matches!(
2171 read("[workers\n"),
2172 Err(ProjectPathsError::Malformed)
2173 ));
2174 }
2175
2176 #[test]
2177 fn a_malformed_manifest_is_malformed() {
2178 assert!(matches!(
2179 check_manifest_str("[project\n"),
2180 Err(ProjectPathsError::Malformed)
2181 ));
2182 }
2183
2184 #[test]
2189 fn the_readers_accept_the_shapes_the_manifest_schema_offers() {
2190 let root = PathBuf::from("/nonexistent-bynk-test-root-2096");
2191 let overlay =
2192 |manifest: &str| HashMap::from([(root.join("bynk.toml"), manifest.to_string())]);
2193
2194 for manifest in [
2196 "[paths]\ninclude = \"src\"\n",
2197 "[paths]\ninclude = [\"src\"]\n",
2198 ] {
2199 check_manifest_str(manifest).expect("the manifest check accepts it");
2200 let paths = try_read_project_paths_with(&root, &overlay(manifest))
2201 .unwrap_or_else(|e| panic!("{manifest:?}: {e}"));
2202 assert_eq!(paths.include, vec![PathBuf::from("src")], "{manifest:?}");
2203 }
2204
2205 let manifest = "[workers]\ncompatibility_flags = [\"x\"]\n";
2207 check_manifest_str(manifest).expect("the manifest check accepts it");
2208 assert_eq!(
2209 try_read_workers_config_with(&root, &overlay(manifest))
2210 .unwrap()
2211 .compatibility_flags,
2212 vec!["x"]
2213 );
2214 let manifest = "[unstable]\nallow = [\"x\"]\n";
2215 check_manifest_str(manifest).expect("the manifest check accepts it");
2216 assert_eq!(
2217 try_read_unstable_config_with(&root, &overlay(manifest))
2218 .unwrap()
2219 .allow,
2220 vec!["x"]
2221 );
2222
2223 let manifest = "[workers]\ncompatibility_flags = \"x\"\n";
2226 assert!(matches!(
2227 try_read_workers_config_with(&root, &overlay(manifest)),
2228 Err(ProjectPathsError::NotAStringList { .. })
2229 ));
2230 assert!(check_manifest_str(manifest).is_err());
2231 let manifest = "[unstable]\nallow = \"x\"\n";
2232 assert!(matches!(
2233 try_read_unstable_config_with(&root, &overlay(manifest)),
2234 Err(ProjectPathsError::NotAStringList { .. })
2235 ));
2236 assert!(check_manifest_str(manifest).is_err());
2237
2238 let manifest = "[test.targets.preview]\nurl.shop-orders = \"https://x\"\nsecrets = [\"S\"]\nvars = { P = \"fake\" }\nproduction = false\n";
2240 check_manifest_str(manifest).expect("a well-formed target is accepted");
2241 let targets = test_targets_from(
2242 manifest.parse::<toml::Table>().unwrap()["test"]
2243 .as_table()
2244 .unwrap(),
2245 )
2246 .unwrap();
2247 let preview = &targets["preview"];
2248 assert_eq!(preview.urls["shop-orders"], "https://x");
2249 assert_eq!(preview.secrets, ["S"]);
2250 assert_eq!(preview.vars["P"], "fake");
2251 assert!(!preview.production);
2252 for (manifest, needle) in [
2253 ("[test.targets.p]\nsecrets = []\n", "names no Worker URL"),
2254 (
2255 "[test.targets.p]\nurl.a = \"x\"\nsecret = \"S\"\n",
2256 "no key named `secret`",
2257 ),
2258 (
2259 "[test.targets.p]\nurl.a = \"x\"\nproduction = \"yes\"\n",
2260 "`production` must be",
2261 ),
2262 ("[test.targets.p]\nurl.a = 1\n", "`url.a` must be a string"),
2263 (
2264 "[test.targets.p]\nurl.a = \"x\"\nvars = { BYNK_DATASET_ANALYTICS_SIGNUPS = \"x\" }\n",
2265 "`vars.BYNK_DATASET_ANALYTICS_SIGNUPS` is reserved",
2266 ),
2267 ("[test]\ntarget = 1\n", "no key named `target`"),
2268 ] {
2269 let err = check_manifest_str(manifest)
2270 .expect_err(manifest)
2271 .to_string();
2272 assert!(err.contains(needle), "{manifest:?}: {err}");
2273 }
2274 }
2275}