Skip to main content

bynk_project/
paths.rs

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
8/// v0.17 [DECISION L] stub: a version range is *unpinned* — and rejected — when
9/// it is empty, `*`/`x`/`latest`, or otherwise carries no concrete version
10/// number. A pinned range names at least one digit (`^5`, `~1.2`, `1.2.3`,
11/// `>=1.0 <2`). No allow-list or registry check yet.
12pub 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
20/// Render the build output's minimal `package.json`: `"type": "module"`, and
21/// the adapter-declared dependencies when there are any.
22///
23/// #2148: the emitted modules are ES modules, and the emitted tsconfig's
24/// `module: NodeNext` takes each file's format from the nearest
25/// `package.json`. Declaring `"type": "module"` beside the output makes `tsc`
26/// check and build it as ES modules, under the same rules Node applies when it
27/// runs them (`.js` specifiers on relative imports, no CommonJS idioms).
28pub 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
43/// Normalise a relative path by resolving `.` and `..` components, so a binding
44/// clause like `./tokens.binding.ts` beside `src/tokens.bynk` yields the output
45/// path `tokens.binding.ts`.
46pub 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/// v0.113 (DECISION S): the project's source tree, read from `bynk.toml`'s
62/// `[paths]` section. Test-ness is a property of the `suite` declaration, not of
63/// a directory, so the layout is a flat **`include`** list of trees to compile
64/// and an **`exclude`** list of subtrees to skip — not the role-named
65/// `src`/`tests` split. Each `include` entry is a root walked for `.bynk` files;
66/// a file's identity path is relative to the `include` root that contains it.
67#[derive(Debug, Clone)]
68pub struct ProjectPaths {
69    /// Trees to compile, relative to the project root. Defaults to the
70    /// conventional roots that exist (`src`, and `tests` when present), else the
71    /// project root itself.
72    pub include: Vec<PathBuf>,
73    /// Subtrees to skip during discovery (monorepo, vendored, or generated
74    /// `.bynk`), relative to the project root.
75    pub exclude: Vec<PathBuf>,
76}
77
78impl ProjectPaths {
79    /// The default layout when `bynk.toml` declares no `[paths] include`: the
80    /// conventional `src`/`tests` roots that exist under `project_root`, or the
81    /// project root itself when neither does. This keeps a conventional
82    /// `src/`(+`tests/`) project working with no config, and lets a flat project
83    /// (`.bynk` at the root, no `src/`) compile with no config either.
84    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/// Like [`try_read_project_paths`], but honours `overlay` for `bynk.toml`
102/// itself — the in-memory test seam's (#57) one remaining disk read outside
103/// `discovery::read_source`, now routed through the same helper so a test
104/// can supply a virtual `bynk.toml` with no on-disk file at all. `#[cfg(test)]`
105/// because that's its only consumer today; drop the gate if a non-test caller
106/// needs it (`try_read_project_paths_with`, which this wraps, has none of that
107/// restriction — production code already reaches it through the always-on
108/// `try_read_project_paths`).
109#[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/// A problem in `bynk.toml` that [`try_read_project_paths`] surfaces instead
119/// of silently falling back to the conventional layout.
120#[derive(Debug)]
121pub enum ProjectPathsError {
122    /// `bynk.toml` exists but does not parse as TOML (e.g. a trailing comma).
123    Malformed,
124    /// `[paths]` has a key other than `include`/`exclude` — most likely a typo
125    /// (`inculde`) that was silently read as "no include list".
126    UnknownKey(String),
127    /// #1665: a top-level entry that isn't one of the manifest's tables
128    /// ([`MANIFEST_TABLES`]): a typo (`[pahts]`), or a table for a planned
129    /// feature (`[dependencies]`) that would otherwise read as working.
130    UnknownTable(String),
131    /// #1665: a key at the top level of `bynk.toml`, outside any table.
132    TopLevelKey(String),
133    /// #1665: a key in `[project]`, `[lsp]` or `[workers]` that the table
134    /// doesn't have. (`[paths]` reports [`Self::UnknownKey`]; `[fmt]` is
135    /// checked by its own reader, which owns its keys.)
136    UnknownTableKey { table: &'static str, key: String },
137    /// #1890: a key that must be a list of strings holds something else: a
138    /// bare string, a number, or a list with a non-string entry
139    /// (`[workers] compatibility_flags = ["a", 1]`).
140    NotAStringList {
141        table: &'static str,
142        key: &'static str,
143    },
144    /// A key that must be a boolean holds something else
145    /// (`[workers] workers_dev = "no"`).
146    NotABool {
147        table: &'static str,
148        key: &'static str,
149    },
150    /// #3054: a `[build]` key whose value isn't one the key accepts.
151    BadBuild { key: &'static str, reason: String },
152    /// #3054: a `[profile.<name>]` table that isn't well formed.
153    BadProfile { profile: String, reason: String },
154    /// #3319: a `[deploy.hyperdrive.<Capability>]` or `[dev.hyperdrive.<Capability>]`
155    /// entry that is not well formed. Never carries the value it was given: a
156    /// connection string written there is a secret.
157    BadHyperdrive {
158        table: &'static str,
159        capability: String,
160        reason: String,
161    },
162    /// #3477: a `[deploy.containers.<Capability>]` entry that is not well formed.
163    BadContainers {
164        table: &'static str,
165        capability: String,
166        reason: String,
167    },
168    /// #3479: a `[deploy.vectorize.<Capability>]` entry that is not well formed.
169    BadVectorize {
170        table: &'static str,
171        capability: String,
172        reason: String,
173    },
174    /// #3562: a `[deploy.workers.<key>]` group that is not well formed, or
175    /// that breaks a rule across groups. The reason may lead with the
176    /// `bynk.deploy.*` code it is.
177    BadWorkerGroup { key: String, reason: String },
178    /// #3478: a `[dev]` acknowledgement (`ai = "allow"`) holding anything but
179    /// `"allow"`.
180    BadDevAck { key: String, reason: String },
181    /// #2138: a `[test.targets.<name>]` entry that is not well formed.
182    BadTestTarget { target: String, reason: String },
183    /// #3321: a `[test] postgres` value that is not one the key accepts.
184    BadTestPostgres { reason: String },
185    /// #2207 (`project_and_package`): both `[project]` and `[package]`, so the
186    /// project would have two names.
187    ProjectAndPackage,
188    /// #2207: a `[package]` key whose value isn't well formed (decision D).
189    BadPackage { key: &'static str, reason: String },
190    /// #2207: a `[dependencies]`/`[dev-dependencies]` entry that isn't well
191    /// formed (decisions A and G).
192    BadDependency {
193        table: &'static str,
194        alias: String,
195        reason: String,
196    },
197    /// #2207: a key a map table's entry doesn't have.
198    UnknownEntryKey {
199        table: &'static str,
200        entry: String,
201        key: String,
202    },
203    /// #2207: a `[registries.<name>]` entry that isn't well formed (decision E).
204    BadRegistry { name: String, reason: String },
205    /// #2207 (decision E): a credential written into `[registries.<name>]`.
206    RegistryCredential { name: String },
207    /// #2207: a `[workspace]` that isn't well formed, or whose members can't
208    /// be resolved (decision C).
209    BadWorkspace { reason: String },
210    /// #2207 (decision C): a table other than `[workspace]`/`[registries]` in
211    /// a workspace root's manifest.
212    WorkspaceRootTable(String),
213    /// #2207 (decision C): a workspace root holding sources of its own.
214    WorkspaceRootSources,
215    /// #2207 (decision C): a project command run at a workspace root, which is
216    /// not a project.
217    WorkspaceRoot,
218    /// #2207 (decision C): a workspace member declaring `[registries]`, which
219    /// only the root may.
220    MemberRegistries { workspace: PathBuf },
221    /// #2207 (decision C): a workspace member that is itself a workspace.
222    NestedWorkspace { workspace: PathBuf },
223}
224
225/// #1665: the tables `bynk.toml` may hold, each with the keys it accepts.
226/// `[fmt]`'s keys are `bynk-fmt`'s to check (`FmtConfig`, `deny_unknown_fields`),
227/// so its list here is empty and unchecked.
228pub 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
279/// #3054: the named build profiles, each a `[profile.<name>]` table. The set is
280/// fixed: `dev` builds with the function-contract call-site guard, `release`
281/// without it.
282pub const PROFILE_NAMES: &[&str] = &["dev", "release"];
283
284/// The keys a `[profile.<name>]` table accepts.
285const PROFILE_KEYS: &[&str] = &["contracts"];
286
287/// #2207 (packaging slice 1): the **map tables**, each with the keys one of
288/// its entries accepts. A map table's own keys are names the user chooses
289/// (dependency aliases, registry names), checked against decision G's grammar;
290/// each entry is a table of fixed keys, refused with did-you-mean like
291/// [`MANIFEST_TABLES`]' keys are.
292pub 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
298/// The tables a workspace root's `bynk.toml` may hold (decision C).
299const WORKSPACE_ROOT_TABLES: &[&str] = &["workspace", "registries"];
300
301/// Tables a user might write for a feature that is designed but not built,
302/// with the issue that tracks it.
303const PLANNED_TABLES: &[(&str, &str)] = &[];
304
305/// Every table name `bynk.toml` accepts, fixed-key and map tables alike, in
306/// documentation order.
307fn all_tables() -> impl Iterator<Item = &'static str> {
308    MANIFEST_TABLES
309        .iter()
310        .chain(MANIFEST_MAP_TABLES)
311        .map(|(t, _)| *t)
312}
313
314/// The manifest's tables as
315/// `` `[project]`, `[paths]`, `[fmt]`, `[lsp]` <conj> `[workers]` ``, from
316/// [`MANIFEST_TABLES`], so a message can't fall behind it.
317fn 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
325/// The closest of `candidates` to `name`, if any is within two edits.
326pub 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
338/// Levenshtein distance over chars.
339fn 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                // #1770 review: a table's own name written as a plain value
376                // (`paths = "src"`).
377                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
524/// #1665: check `bynk.toml`'s table set and the keys of `[project]` and
525/// `[lsp]` ([`MANIFEST_TABLES`]). Every other reader takes only its own table
526/// and ignores the rest, so an unknown table (`[dependencies]`, a typo'd
527/// `[pahts]`) used to build cleanly with none of its intended behaviour.
528///
529/// Kept apart from [`try_read_project_paths_with`] on purpose: the CLIs call
530/// both and refuse an unknown table, while the language server reads `[paths]`
531/// alone and keeps serving, so an extra table can't cost an editor its
532/// `include` layout. `Ok` when there is no `bynk.toml`. A manifest that doesn't
533/// parse is [`ProjectPathsError::Malformed`].
534pub 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    // #2207 (decision C): a workspace member may not declare `[registries]`
544    // or a `[workspace]` of its own. Finding the workspace reads the disk, so
545    // it happens only when one of those tables is there to refuse.
546    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
561/// [`check_manifest`] over a manifest's text: every check that needs no
562/// other file.
563pub 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        // #1770 review: a planned table names its issue whatever shape it is
570        // written in (`[[deploy]]`, `deploy = [...]`).
571        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        // #1770 review: a known table's name holding a plain value
591        // (`paths = "src"`, `dependencies = ["acme"]`) would otherwise read as
592        // an absent table.
593        let Some(entries) = value.as_table() else {
594            return Err(ProjectPathsError::TopLevelKey(name.clone()));
595        };
596        declared.push(table);
597        // #2207: a map table's keys are names the user chooses; its readers
598        // check each name's grammar, then each entry's keys.
599        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    // #2207: the rules across tables.
650    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
661/// Read `bynk.toml`'s `[paths]` section, surfacing a malformed manifest — a
662/// parse failure or an unrecognised `[paths]` key — as an error instead of
663/// silently falling back to the conventional layout (the previous
664/// `read_project_paths` total form's behaviour, R3.8 — deleted in favour of
665/// this at all 18 of its callers, #1113).
666///
667/// R3.9 (#1113): `[paths] include` is no longer capped at one or two trees —
668/// [`crate::roots::Roots::trees`] walks every entry, so this no longer rejects
669/// a longer list.
670pub 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
679/// Like [`try_read_project_paths`], but honours `overlay` for `bynk.toml`
680/// itself, the same way `discovery::read_source` does for every other file.
681pub 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/// #1890: the project's `[workers]` table, settings for the Cloudflare
720/// Workers a `workers`-target build emits.
721#[derive(Debug, Clone, Default, PartialEq, Eq)]
722pub struct WorkersConfig {
723    /// Extra Cloudflare compatibility flags, in manifest order, for every
724    /// Worker's `wrangler.toml`, after the compiler's default set. The names
725    /// pass through unvalidated, since Cloudflare adds flags faster than a
726    /// list here could follow. Duplicates are kept here: the emitter drops
727    /// them and warns.
728    pub compatibility_flags: Vec<String>,
729    /// `workers_dev` for every Worker's `wrangler.toml`: whether the Worker is
730    /// served on its `*.workers.dev` URL. `None` leaves the key out, so
731    /// Cloudflare's default (on) applies.
732    pub workers_dev: Option<bool>,
733}
734
735/// Read `bynk.toml`'s `[workers]` table, honouring `overlay` for `bynk.toml`
736/// the way [`try_read_project_paths_with`] does. No manifest, or no
737/// `[workers]` table, is the empty [`WorkersConfig`]. A manifest that doesn't
738/// parse is [`ProjectPathsError::Malformed`], and a `compatibility_flags`
739/// that isn't a list of strings is [`ProjectPathsError::NotAStringList`]. The
740/// shape is checked here as well as in [`check_manifest`], because some
741/// callers (the e2e harness) read the table without the whole-manifest check.
742pub 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
759/// [`try_read_workers_config_with`], reading `bynk.toml` from disk.
760pub 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/// #3054: the project's `[build]` table, the defaults `bynk build` takes
770/// when a flag is not given. Each key is `None` when unset; `bynk build`
771/// applies the built-in default (`out`, `bundle`, `cloudflare`, `ts`).
772#[derive(Debug, Clone, Default, PartialEq, Eq)]
773pub struct BuildConfig {
774    /// Output directory, relative to the project root.
775    pub out: Option<String>,
776    /// `bundle` or `workers`.
777    pub target: Option<String>,
778    /// `cloudflare`, `node` or `browser`.
779    pub platform: Option<String>,
780    /// `ts` or `js`.
781    pub emit: Option<String>,
782    /// #3350: the package manager that installs the generated build
783    /// directory's npm packages: `npm`, `pnpm`, `bun` or `yarn`.
784    pub package_manager: Option<String>,
785    /// #3508: `[build.client]`, where `bynk build` writes the typed TypeScript
786    /// client (`bynk client`). Absent, `bynk build` writes none.
787    pub client: Option<ClientConfig>,
788    /// The `[profile.<name>]` tables present, by profile name.
789    pub profiles: BTreeMap<String, ProfileConfig>,
790}
791
792/// #3508: the `[build.client]` table: where the typed TypeScript client for the
793/// project's `from http` services is written, and how.
794#[derive(Debug, Clone, PartialEq, Eq)]
795pub struct ClientConfig {
796    /// Where to write it, relative to the project root. A file with
797    /// `layout = "file"`, a directory with `layout = "dir"`. It may leave the
798    /// project: a front end often lives beside the Bynk project, not in it.
799    pub out: String,
800    /// `file` (one module) or `dir` (`index.ts`, `types.ts`, `codecs.ts`,
801    /// `runtime.ts`).
802    pub layout: ClientLayout,
803    /// The `from http` services to include (`Name` or `unit.Name`); every one when
804    /// empty.
805    pub services: Vec<String>,
806}
807
808/// #3508: how `bynk client` lays the client out.
809#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
810pub enum ClientLayout {
811    /// One module: one thing to commit, review and diff.
812    #[default]
813    File,
814    /// A directory of modules, which is package-shaped.
815    Dir,
816}
817
818/// The `[build.client]` keys.
819const CLIENT_KEYS: &[&str] = &["out", "layout", "service"];
820
821/// #3054: one `[profile.<name>]` table. `None` leaves the profile's built-in
822/// default (`dev` on, `release` off).
823#[derive(Debug, Clone, Default, PartialEq, Eq)]
824pub struct ProfileConfig {
825    /// Whether the build carries the function-contract call-site guard.
826    pub contracts: Option<bool>,
827}
828
829/// Read `bynk.toml`'s `[build]` table, honouring `overlay` the way
830/// [`try_read_workers_config_with`] does. No manifest, or no `[build]`, is the
831/// empty [`BuildConfig`]; a bad value is [`ProjectPathsError::BadBuild`].
832pub 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
853/// Read `bynk.toml`'s `[profile]` table alone (#3107), so `bynk test` and
854/// `bynk deploy` consult the profiles without reading `[build]`. No manifest,
855/// or no `[profile]`, is empty; a bad profile is [`ProjectPathsError::BadProfile`].
856pub 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
871/// The `[profile]` table's typed content: only the names in [`PROFILE_NAMES`],
872/// each a table whose only key is a boolean `contracts`.
873fn 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
910/// [`try_read_build_config_with`], reading `bynk.toml` from disk.
911pub 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
920/// The `[build]` table's typed content: each value a string, `target`,
921/// `platform` and `emit` from their fixed sets, `out` a relative path that
922/// stays inside the project. An unknown key is [`check_manifest_str`]'s.
923fn 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
977/// #3508: the `[build.client]` table's typed content. `out` is required, a
978/// relative path that is not the project root; `layout` is `"file"` or `"dir"`;
979/// `service` is a list of service names.
980fn 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    // A root or a drive makes a path absolute (`/abs`, `C:\\abs`), and on Windows `/abs`
1010    // has no drive, so `is_absolute` alone would let it by.
1011    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/// #2138 (end-to-end testing track §3.8): a deployment `bynk test --against
1051/// <name>` may run the `system` suites against, from `[test.targets.<name>]`.
1052#[derive(Debug, Clone, Default, PartialEq, Eq)]
1053pub struct TestTarget {
1054    /// Each Worker's base URL, keyed by worker-directory name
1055    /// (`url.shop-orders = "https://…"`).
1056    pub urls: BTreeMap<String, String>,
1057    /// The secrets the deployed Workers verify with, by name. Their values
1058    /// come only from the runner's environment, never from `bynk.toml`.
1059    pub secrets: Vec<String>,
1060    /// `production = true` marks a deployment `--against` refuses.
1061    pub production: bool,
1062    /// The non-secret values the target was deployed with
1063    /// (`vars = { PAYMENTS_PROCESSOR = "fake" }`).
1064    pub vars: BTreeMap<String, String>,
1065}
1066
1067/// #2138: read `bynk.toml`'s `[test.targets]`, by name. No manifest, or no
1068/// `[test]` table, is empty. A malformed entry is
1069/// [`ProjectPathsError::BadTestTarget`].
1070pub 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/// #3321: what a test's `Postgres` instance is, `[test] postgres` in `bynk.toml`.
1086#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1087pub enum TestPostgres {
1088    /// The default: a test never reaches a database, so each operation faults
1089    /// until the case stubs it.
1090    #[default]
1091    Stub,
1092    /// PGlite, Postgres compiled to WASM, runs the statements for real on a
1093    /// fresh in-memory database per case.
1094    Pglite,
1095}
1096
1097/// The file a project's Postgres schema is kept in, at the project root. Bynk
1098/// does not own it (ADR 0799 G): when it is there, `bynk check` checks each
1099/// literal `Postgres` statement's syntax and placeholder count, and the PGlite
1100/// double applies it to each case's fresh database.
1101pub const PG_SCHEMA_FILE: &str = "schema.sql";
1102
1103/// The `[test]` table's `postgres`: `"stub"` (the default) or `"pglite"`.
1104fn 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
1115/// #3321: `[test] postgres` of an already-parsed manifest. A value that is not
1116/// well formed reads as the default (the manifest check reports it).
1117pub 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
1124/// #3321: `[test] postgres` of the project at `project_root`; the default when
1125/// there is no manifest.
1126pub 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
1134/// The `[test]` table's `targets`, each checked for shape: `url` a table of
1135/// strings (at least one), `secrets` a list of strings, `production` a
1136/// boolean, `vars` a table of strings, and nothing else. A `vars` name may not
1137/// start with [`crate::env_protocol::DATASET_PREFIX`] (#3513 B): `bynk` writes
1138/// those for `Analytics.dataset()`.
1139fn 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                    // #3513 B: `BYNK_DATASET_<BINDING>` is the variable that carries an
1179                    // `Analytics` dataset's environment-qualified name to its Worker, so a
1180                    // target may not set one and point `dataset()` at another table.
1181                    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
1220/// #3069: read `bynk.toml`'s `[test.mutate] exclude`, the path globs and
1221/// `unit.decl` names `bynk test --mutate` leaves unmutated. No manifest, no
1222/// `[test]` table or no `mutate` table is empty; anything but a list of strings
1223/// is an error naming the problem.
1224pub 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
1263/// #1890: the `bynk.project.duplicate_compatibility_flag` warning for one
1264/// flag `[workers] compatibility_flags` repeats, against `manifest` (the
1265/// project's `bynk.toml`). `default` says the repeat is of a flag every
1266/// Worker already has, rather than of an earlier entry in the list. Built
1267/// here, with the manifest's other diagnostics, rather than in `bynk-emit`,
1268/// which only finds the duplicate while merging the list (R3.5 keeps
1269/// diagnostics out of emission).
1270pub 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
1293/// The `[workers]` table's typed content. Only the value shapes are checked
1294/// here; an unknown key is [`check_manifest_str`]'s to refuse.
1295fn 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/// The project's `[unstable]` table (standard-library S3, #1963): the
1325/// experimental first-party items it opts into using.
1326#[derive(Debug, Clone, Default, PartialEq, Eq)]
1327pub struct UnstableConfig {
1328    /// Item paths (`bynk.cloudflare.R2`, `bynk.cloudflare.Kv.list`), in
1329    /// manifest order. An entry covers itself and everything under it. Whether
1330    /// each one names something experimental is the checker's to say, since it
1331    /// holds the standard library's registry.
1332    pub allow: Vec<String>,
1333}
1334
1335/// Read `bynk.toml`'s `[unstable]` table, honouring `overlay` the way
1336/// [`try_read_workers_config_with`] does. No manifest, or no `[unstable]`
1337/// table, is the empty [`UnstableConfig`]; an `allow` that isn't a list of
1338/// strings is [`ProjectPathsError::NotAStringList`].
1339pub 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
1356/// [`try_read_unstable_config_with`], reading `bynk.toml` from disk.
1357pub 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
1366/// The project's `[unstable]` table as both the build and the editor see it
1367/// (#1963 Decision E): the overlay's `bynk.toml` when it holds one (the LSP puts
1368/// the open buffer there), otherwise the one on disk (a CLI build's overlay holds
1369/// only `.bynk` sources). A missing or malformed manifest reads as empty; its
1370/// shape errors are `check_manifest`'s to report.
1371pub 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
1384/// The `[unstable]` table's typed content. Only the value shape is checked
1385/// here; an unknown key is [`check_manifest_str`]'s to refuse.
1386fn 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/// The project's `[check]` table (#3070): switches for checks that need more
1403/// than the source.
1404#[derive(Debug, Clone, PartialEq, Eq)]
1405pub struct CheckConfig {
1406    /// Whether each literal `D1` statement is prepared against the schema its
1407    /// binding's migrations build. Default `true`.
1408    pub d1_sql: bool,
1409}
1410
1411impl Default for CheckConfig {
1412    fn default() -> Self {
1413        Self { d1_sql: true }
1414    }
1415}
1416
1417/// The `[check]` table as both the build and the editor see it, read the way
1418/// [`read_unstable_config`] reads `[unstable]`: the overlay's `bynk.toml` when
1419/// it holds one, else the one on disk. A missing or malformed manifest, or a
1420/// non-boolean value, reads as the default.
1421pub 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
1434/// The path a unit's name maps to, relative to a source or output root:
1435/// `a.b` is `a/b`. A dependency's canonical unit name (#2223,
1436/// [`crate::packages::PackageId::encoded`]) maps under
1437/// `deps/<org>/<package>/`, so every name-to-path site lays a dependency's
1438/// units out there without knowing about packages.
1439pub 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
1459/// v0.8: directory name of a Worker for a given context, with dots replaced
1460/// by dashes (`commerce.payment` → `commerce-payment`).
1461pub fn worker_dir_name(context: &str) -> String {
1462    context.replace('.', "-")
1463}
1464
1465/// v0.8: project-relative synthetic source path of the workers-mode
1466/// handlers file for a given context. Used so the emitter's relative-import
1467/// machinery resolves correctly against the workers layout.
1468pub fn worker_handlers_source_path(context: &str) -> PathBuf {
1469    PathBuf::from(format!(
1470        "workers/{}/handlers.bynk",
1471        worker_dir_name(context)
1472    ))
1473}
1474
1475/// v0.8: project-relative output path of the workers-mode handlers file.
1476pub fn worker_handlers_output_path(context: &str) -> PathBuf {
1477    PathBuf::from(format!("workers/{}/handlers.ts", worker_dir_name(context)))
1478}
1479
1480/// #1820: project-relative synthetic source path of one file's module in a
1481/// context split across files, on Workers. Each file is its own module under
1482/// `workers/<dir>/handlers/`, and `handlers.ts` re-exports them all, so the
1483/// Worker's entry point and composition root, and every consumer, still
1484/// import the context from `handlers.ts`. A file keeps its stem
1485/// (`shop/orders/place.bynk` → `handlers/place.bynk`). Distinct files map to
1486/// distinct modules because every file of a split unit sits directly in its
1487/// `<name>/` directory: a `<name>.bynk` beside it is rejected
1488/// (`bynk.project.file_and_directory`), as is a file in any other directory
1489/// (`bynk.project.inconsistent_commons_name`). The emitted module is
1490/// [`ts_output_path`] of this path.
1491pub 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
1499/// The src-stripped stem components of a path (`learner/uln.bynk` → `["learner",
1500/// "uln"]`), dropping the extension and any non-`Normal` components.
1501fn 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
1512/// v0.9.1: shared between source-unit and test-unit path validation. The
1513/// caller decides which root to strip from the file path before calling.
1514///
1515/// A file belongs to `qualified_name` when it is either the single file
1516/// `<name>.bynk` (`single_file_match`: stem parts == name parts) or one file of
1517/// the directory layout `<name>/*.bynk` (`multi_file_match`: parent-dir parts ==
1518/// name parts). These two branches are the single source of truth the v0.132
1519/// barrel trigger reads via [`is_multi_file_layout`].
1520pub fn unit_path_matches(rel_path: &Path, qualified_name: &str) -> bool {
1521    // #2223: a dependency unit's canonical name maps under `deps/…`, the
1522    // path its file is given once its package is known.
1523    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
1538/// True when `stem_parts` is one file of the `<name>/*.bynk` directory layout —
1539/// the file's parent-directory parts equal the name parts.
1540fn 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
1552/// v0.132: does `rel_path` (src-stripped) place `qualified_name` under a
1553/// directory of that name — the `multi_file_match` branch of
1554/// [`unit_path_matches`]?
1555///
1556/// This is the layout where production emits `out/<name>/*.ts` per file and no
1557/// aggregate `out/<name>.ts`, so the test path's `import * as ns from
1558/// "./<name>.js"` dangles and needs an aggregating barrel. A single-file commons
1559/// (`<name>.bynk`) already owns `out/<name>.ts` and returns false, so a barrel
1560/// keyed on this predicate can never collide with it.
1561pub 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
1566/// #302: the qualified name a file moved from `old_rel` to `new_rel` should now
1567/// declare, preserving whichever [`unit_path_matches`] arrangement `old_rel`
1568/// used to satisfy against `old_name` — the dotted stem for a single-file
1569/// unit, or the dotted parent-directory for one file of a multi-file unit.
1570/// Returns `None` if `old_rel`/`old_name` don't actually satisfy either
1571/// arrangement (a pre-existing inconsistency the caller should not guess at).
1572///
1573/// `old_name` is matched as a **suffix** of `old_rel`'s stem/parent, not the
1574/// whole thing: the LSP's caller passes project-relative paths, which (unlike
1575/// the `source_path` `unit_path_matches` itself is checked against) still
1576/// carry a leading `include`-root segment (e.g. `src/`) that the qualified
1577/// name never mentions. Whatever prefix length that suffix match implies for
1578/// `old_rel` is applied unchanged to `new_rel` — correct as long as the file
1579/// stays under the same `include` root, which a rename/move normally does.
1580pub 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    // -- is_unpinned_range ----------------------------------------------------
1619    #[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("  *  ")); // trimmed before the checks
1628        assert!(is_unpinned_range("workspace:*")); // no ascii digit
1629        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    // -- read_project_paths_with (#57, in-memory test seam) -------------------
1642    #[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        // No overlay entry and no real file at this (nonexistent) root — same
1658        // fallback a missing on-disk `bynk.toml` gives.
1659        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    /// R3.9 (#1113): three or more `[paths] include` entries all round-trip —
1667    /// `try_read_project_paths_with` no longer caps the list at two.
1668    #[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    // -- render_package_json --------------------------------------------------
1688    #[test]
1689    fn render_package_json_declares_es_modules() {
1690        // #2148: with no dependencies the file is just the module-format marker.
1691        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        // BTreeMap ordering keeps the file byte-stable across builds.
1709        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    /// A package name and version range reach here from adapter declarations in
1717    /// Bynk source, so they are arbitrary text. This module used to escape only
1718    /// `"` and `\`, which let a control character through as a literal — and a
1719    /// literal control character inside a JSON string is a parse error, so the
1720    /// emitted `package.json` was invalid rather than merely odd.
1721    #[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        // No raw control character survives into the rendered document (the
1729        // pretty-printer's own newlines are all that remain).
1730        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    // -- normalize_rel --------------------------------------------------------
1745    #[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        // RootDir / Prefix components are dropped.
1760        assert_eq!(normalize_rel(Path::new("/a/b")), PathBuf::from("a/b"));
1761        // A leading `..` pops an empty stack (a no-op), so it vanishes.
1762        assert_eq!(normalize_rel(Path::new("../a")), PathBuf::from("a"));
1763    }
1764
1765    // -- commons_dir_for / ts_output_path -------------------------------------
1766    #[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    // -- worker path helpers --------------------------------------------------
1786    #[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    // -- unit_path_matches ----------------------------------------------------
1809    #[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        // `a/b/c/<any>.bynk` declaring `a.b.c` (the directory is the unit).
1818        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    // -- is_multi_file_layout (v0.132 barrel trigger) -------------------------
1829    #[test]
1830    fn is_multi_file_layout_true_only_for_directory_layout() {
1831        // Directory layout: `<name>/*.bynk` — the branch with no `out/<name>.ts`.
1832        assert!(is_multi_file_layout(Path::new("thing/a.bynk"), "thing"));
1833        assert!(is_multi_file_layout(Path::new("thing/b.bynk"), "thing"));
1834        // Dotted commons split across `src/a/b/*.bynk`.
1835        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        // Single file `<name>.bynk` already owns `out/<name>.ts` — no barrel.
1841        assert!(!is_multi_file_layout(Path::new("thing.bynk"), "thing"));
1842        // Dotted single file `a/b.bynk` for `a.b` — the file *is* `out/a/b.ts`.
1843        assert!(!is_multi_file_layout(Path::new("a/b.bynk"), "a.b"));
1844        // Wrong directory — not this unit's file.
1845        assert!(!is_multi_file_layout(Path::new("other/a.bynk"), "thing"));
1846    }
1847
1848    // -- renamed_unit_name (#302) ----------------------------------------------
1849    #[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        // Renaming one member file within the same directory doesn't change
1868        // the unit's name — the qualified name is the directory, not the
1869        // filename.
1870        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        // The LSP passes project-relative paths (ADR 0198), which still carry
1903        // a split project's `src`/`tests` root segment — `unit_path_matches`
1904        // itself is only ever checked against the root-stripped `source_path`.
1905        // `old_name` must match as a *suffix*, and the same leading-segment
1906        // count is preserved onto `new_rel`.
1907        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        // Multi-file arrangement under the same prefix.
1916        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    /// #1665: every table the docs describe, with every key, is accepted.
1938    #[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    /// #3508: `[build.client]` is read, its defaults are the file layout and every
1950    /// service, and the path may leave the project.
1951    #[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        // No table, no client.
1989        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    /// #1770 review: a known table's name holding a plain value is refused,
2046    /// not read as an absent table.
2047    #[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        // An inline table is a table.
2053        check_manifest_str("paths = { include = [\"src\"] }\n").expect("accepted");
2054    }
2055
2056    /// #1770 review: a table written as an array of tables, or as a plain
2057    /// array, is refused, not read as an absent table.
2058    #[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    /// #2207: a map table written in another shape is told to be a table.
2065    #[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    /// `[fmt]` keys are `bynk-fmt`'s to check, not this one's.
2082    #[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    /// #1890: `[workers] compatibility_flags` must be a list of strings; the
2088    /// names themselves pass through.
2089    #[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    /// #1963: `[unstable] allow` must be a list of strings; whether each names
2105    /// something experimental is the checker's to say.
2106    #[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    /// #2096: the shapes `bynk.toml`'s JSON Schema accepts for the hand-read
2185    /// tables are the shapes their readers accept, and the shapes it flags for
2186    /// `compatibility_flags`/`allow` are refused. The schema is written apart
2187    /// from these readers (`manifest_schema`), so this pins the two together.
2188    #[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        // `[paths] include`: a bare string and a list both read as the one root.
2195        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        // `[workers] compatibility_flags` and `[unstable] allow`: lists of strings.
2206        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        // A bare string is a list only for `[paths]`: the schema flags it for
2224        // these two, and so do the readers.
2225        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        // #2138: `[test.targets.<name>]`.
2239        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}