1use crate::emsg;
7use std::path::{Path, PathBuf};
8use std::process::ExitCode;
9
10use clap::ValueEnum;
11
12use crate::project::{BuildTarget, CompileOptions, SchemaLock, compile_project};
13use bynk_check::firstparty::Platform;
14
15#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
18pub enum CliProfile {
19 Dev,
21 Release,
24}
25
26impl CliProfile {
27 fn name(self) -> &'static str {
28 match self {
29 CliProfile::Dev => "dev",
30 CliProfile::Release => "release",
31 }
32 }
33
34 fn contracts_by_default(self) -> bool {
37 self == CliProfile::Dev
38 }
39}
40
41pub fn profile_contracts(
46 profiles: &std::collections::BTreeMap<String, bynk_project::ProfileConfig>,
47 profile: CliProfile,
48) -> bool {
49 profiles
50 .get(profile.name())
51 .and_then(|p| p.contracts)
52 .unwrap_or_else(|| profile.contracts_by_default())
53}
54
55pub fn project_contracts(root: &Path, profile: CliProfile) -> Result<bool, String> {
57 let profiles = bynk_project::try_read_profiles(root).map_err(|e| e.to_string())?;
59 Ok(profile_contracts(&profiles, profile))
60}
61
62pub fn refuse_release_contracts(root: &Path) -> Result<(), String> {
66 if project_contracts(root, CliProfile::Release)? {
67 return Err("`[profile.release] contracts = true` in `bynk.toml` would put contract checks in what is deployed, and a deployment never carries them — set it to `false` or remove it (it still applies to `bynk build`)".to_string());
68 }
69 Ok(())
70}
71
72pub fn refuse_undeployable_project(root: &Path) -> Result<(), String> {
75 bynk_project::worker_groups::try_read_worker_groups(root)
78 .map_err(|e| format!("invalid `[deploy.workers]` in `bynk.toml`: {e}"))?;
79 refuse_release_contracts(root)
80}
81
82#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
84pub enum CliTarget {
85 Bundle,
88 Workers,
91}
92
93impl From<CliTarget> for BuildTarget {
94 fn from(t: CliTarget) -> Self {
95 match t {
96 CliTarget::Bundle => BuildTarget::Bundle,
97 CliTarget::Workers => BuildTarget::Workers,
98 }
99 }
100}
101
102#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
108pub enum EmitFormat {
109 #[default]
111 Ts,
112 Js,
114}
115
116#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
119pub enum CliPlatform {
120 #[default]
122 Cloudflare,
123 Node,
125 Browser,
129}
130
131impl From<CliPlatform> for Platform {
132 fn from(p: CliPlatform) -> Self {
133 match p {
134 CliPlatform::Cloudflare => Platform::Cloudflare,
135 CliPlatform::Node => Platform::Node,
136 CliPlatform::Browser => Platform::Browser,
137 }
138 }
139}
140
141#[derive(Clone, Debug)]
143pub struct CompileArgs {
144 pub input: PathBuf,
146 pub output: PathBuf,
148 pub target: CliTarget,
149 pub platform: CliPlatform,
150 pub emit: EmitFormat,
151 pub sources_stdin: bool,
153 pub contracts: bool,
157}
158
159#[derive(Clone, Debug, Default)]
161pub struct BuildArgs {
162 pub input: PathBuf,
164 pub out: Option<PathBuf>,
165 pub target: Option<CliTarget>,
166 pub platform: Option<CliPlatform>,
167 pub emit: Option<EmitFormat>,
168 pub profile: Option<CliProfile>,
170}
171
172pub fn run_build(prog: &str, args: BuildArgs) -> ExitCode {
176 let BuildArgs {
177 input,
178 out,
179 target,
180 platform,
181 emit,
182 profile,
183 } = args;
184 if !input.is_dir() {
185 emsg!(
186 "{prog}: error: `build` takes a project directory; use `{prog} compile` for a single file"
187 );
188 return ExitCode::FAILURE;
189 }
190 let config = match bynk_project::try_read_build_config(&input) {
191 Ok(c) => c,
192 Err(e) => {
193 emsg!("{prog}: error: {e}");
194 return ExitCode::FAILURE;
195 }
196 };
197 fn parse<T: ValueEnum>(key: &str, value: Option<&str>) -> Result<Option<T>, String> {
201 match value {
202 None => Ok(None),
203 Some(v) => T::from_str(v, true).map(Some).map_err(|_| {
204 format!("`[build]` `{key}` = \"{v}\" is not a value this `bynk` knows")
205 }),
206 }
207 }
208 let resolved = (|| -> Result<_, String> {
209 Ok((
210 target
211 .or(parse("target", config.target.as_deref())?)
212 .unwrap_or(CliTarget::Bundle),
213 platform
214 .or(parse("platform", config.platform.as_deref())?)
215 .unwrap_or_default(),
216 emit.or(parse("emit", config.emit.as_deref())?)
217 .unwrap_or_default(),
218 ))
219 })();
220 let (target, platform, emit) = match resolved {
221 Ok(r) => r,
222 Err(e) => {
223 emsg!("{prog}: error: {e}");
224 return ExitCode::FAILURE;
225 }
226 };
227 let profile = profile.unwrap_or(CliProfile::Release);
231 let contracts = profile_contracts(&config.profiles, profile);
232 let output = out.unwrap_or_else(|| input.join(config.out.as_deref().unwrap_or("out")));
233 if let Err(e) = check_output_dir(&input, &output) {
234 emsg!("{prog}: error: {e}");
235 return ExitCode::FAILURE;
236 }
237 let code = run_compile_reporting(
238 prog,
239 CompileArgs {
240 input,
241 output: output.clone(),
242 target,
243 platform,
244 emit,
245 sources_stdin: false,
246 contracts,
247 },
248 crate::progress::terminal_sink(),
249 );
250 if code == ExitCode::SUCCESS {
251 let target = match target {
252 CliTarget::Bundle => "bundle",
253 CliTarget::Workers => "workers",
254 };
255 let profile = match (profile, contracts) {
256 (CliProfile::Release, false) => String::new(),
257 (p, c) => format!(
258 " ({} profile, contracts {})",
259 p.name(),
260 if c { "on" } else { "off" }
261 ),
262 };
263 emsg!("{prog}: built {target}{profile} -> {}", output.display());
264 }
265 code
266}
267
268fn resolve(path: &Path) -> PathBuf {
271 let mut rest = Vec::new();
272 let mut cur = path.to_path_buf();
273 loop {
274 if let Ok(real) = cur.canonicalize() {
275 return rest.iter().rev().fold(real, |acc, c| acc.join(c));
276 }
277 match (cur.file_name().map(ToOwned::to_owned), cur.parent()) {
278 (Some(name), Some(parent)) => {
279 rest.push(name);
280 cur = if parent.as_os_str().is_empty() {
281 PathBuf::from(".")
282 } else {
283 parent.to_path_buf()
284 };
285 }
286 _ => return path.to_path_buf(),
287 }
288 }
289}
290
291fn holds_bynk_source(dir: &Path) -> bool {
293 let Ok(entries) = std::fs::read_dir(dir) else {
294 return false;
295 };
296 entries.flatten().any(|e| {
297 let path = e.path();
298 let name = e.file_name();
299 let name = name.to_string_lossy();
300 match e.file_type() {
301 Ok(t) if t.is_dir() => {
302 name != "node_modules" && !name.starts_with('.') && holds_bynk_source(&path)
303 }
304 Ok(t) if t.is_file() => path.extension().is_some_and(|x| x == "bynk"),
305 _ => false,
306 }
307 })
308}
309
310fn check_output_dir(project: &Path, output: &Path) -> Result<(), String> {
316 let root = resolve(project);
317 let out = resolve(output);
320 let shown = output.display();
321 if !out.starts_with(&root) || out == root {
322 return Err(format!(
323 "the output directory `{shown}` must be a directory inside the project, not the project root or a path outside it"
324 ));
325 }
326 let paths = bynk_project::try_read_project_paths(project)
327 .unwrap_or_else(|_| bynk_project::ProjectPaths::conventional(project));
328 for include in &paths.include {
329 let source = resolve(&project.join(include));
330 if source == root {
333 continue;
334 }
335 if out.starts_with(&source) || source.starts_with(&out) {
336 return Err(format!(
337 "the output directory `{shown}` overlaps the source root `{}`, and a build deletes files it did not write from its output directory; choose another `[build] out`",
338 include.display()
339 ));
340 }
341 }
342 if holds_bynk_source(&out) {
343 return Err(format!(
344 "the output directory `{shown}` holds `.bynk` sources, and a build deletes files it did not write from its output directory; choose another `[build] out`"
345 ));
346 }
347 Ok(())
348}
349
350pub fn run_compile(prog: &str, args: CompileArgs) -> ExitCode {
352 run_compile_reporting(prog, args, None)
353}
354
355fn run_compile_reporting(
357 prog: &str,
358 args: CompileArgs,
359 progress: Option<crate::project::ProgressSink>,
360) -> ExitCode {
361 let CompileArgs {
362 input,
363 output,
364 target,
365 platform,
366 emit,
367 sources_stdin,
368 contracts,
369 } = args;
370 if sources_stdin && !input.is_dir() {
371 emsg!("{prog}: error: --sources-stdin needs a project directory, not a single file");
372 return ExitCode::FAILURE;
373 }
374 if input.is_dir() {
375 compile_dir(
376 prog,
377 &input,
378 &output,
379 DirSettings {
380 target,
381 platform,
382 emit,
383 sources_stdin,
384 contracts,
385 progress,
386 },
387 )
388 } else {
389 compile_file(prog, &input, &output, emit)
390 }
391}
392
393struct DirSettings {
395 target: CliTarget,
396 platform: CliPlatform,
397 emit: EmitFormat,
398 sources_stdin: bool,
399 contracts: bool,
400 progress: Option<crate::project::ProgressSink>,
401}
402
403fn compile_dir(prog: &str, input: &Path, output: &Path, settings: DirSettings) -> ExitCode {
404 let DirSettings {
405 target,
406 platform,
407 emit,
408 sources_stdin,
409 contracts,
410 progress,
411 } = settings;
412 let schema_lock = match crate::schema_lock::read(input) {
417 Ok(_) if sources_stdin => SchemaLock::Off,
419 Ok(existing) => SchemaLock::On { existing },
420 Err(e) => {
421 emsg!(
422 "{prog}: error: could not read {}: {e}",
423 crate::schema_lock::lock_path(input).display()
424 );
425 return ExitCode::FAILURE;
426 }
427 };
428 let options: CompileOptions = match crate::try_project_options(input) {
429 Ok(o) => o
436 .target(target.into())
437 .platform(platform.into())
438 .schema_registry(schema_lock)
439 .contracts(contracts)
440 .progress(progress)
441 .out_dir(Some(output.to_path_buf()))
442 .tests(false),
443 Err(e) => {
444 emsg!("{prog}: error: {}", e.render(false));
447 return ExitCode::FAILURE;
448 }
449 };
450 let options = if sources_stdin {
451 match overlay_from_stdin(options, input) {
452 Ok(o) => o,
453 Err(e) => {
454 emsg!("{prog}: error: {e}");
455 return ExitCode::FAILURE;
456 }
457 }
458 } else {
459 options
460 };
461 match compile_project(&options) {
463 Ok(out) => {
464 if let Some(content) = &out.schema_lock
469 && let Err(e) = crate::schema_lock::write_reporting(prog, input, content)
470 {
471 emsg!(
472 "{prog}: warning: could not write {}: {e}",
473 crate::schema_lock::lock_path(input).display()
474 );
475 }
476 let out = match emit {
482 EmitFormat::Ts => out,
483 EmitFormat::Js => match crate::strip::strip_project_to_js(out) {
484 Ok(out) => out,
485 Err(e) => {
486 emsg!("{prog}: error: could not produce JavaScript output: {e}");
487 return ExitCode::FAILURE;
488 }
489 },
490 };
491 match crate::write_output(&out, output) {
492 Ok(()) => {
493 crate::print_project_warnings(&out.warnings, &out.snapshots, &out.display_root);
495 ExitCode::SUCCESS
496 }
497 Err(e) => {
498 emsg!(
499 "{prog}: error: could not write output under `{}`: {e}",
500 output.display()
501 );
502 ExitCode::FAILURE
503 }
504 }
505 }
506 Err(failure) => {
507 crate::print_project_failure(&failure);
508 ExitCode::FAILURE
509 }
510 }
511}
512
513fn compile_file(prog: &str, input: &Path, output: &Path, emit: EmitFormat) -> ExitCode {
514 let source = match std::fs::read_to_string(input) {
515 Ok(s) => s,
516 Err(e) => {
517 emsg!("{prog}: error: could not read `{}`: {e}", input.display());
518 return ExitCode::FAILURE;
519 }
520 };
521 let filename = input.display().to_string();
522 match bynk_emit::compile_with_warnings(&source, &filename) {
523 Ok(compiled) => {
524 let body = match emit {
527 EmitFormat::Ts => compiled.ts,
528 EmitFormat::Js => match bynk_strip::strip_types(&compiled.ts, &filename) {
529 Ok(js) => js,
530 Err(e) => {
531 emsg!("{prog}: error: could not produce JavaScript output: {e}");
532 return ExitCode::FAILURE;
533 }
534 },
535 };
536 if let Some(parent) = output.parent() {
537 let _ = std::fs::create_dir_all(parent);
538 }
539 if let Err(e) = std::fs::write(output, body) {
540 emsg!("{prog}: error: could not write `{}`: {e}", output.display());
541 return ExitCode::FAILURE;
542 }
543 let warnings = crate::render::without_hints(&compiled.warnings);
546 if !warnings.is_empty() {
547 crate::render::print_errors(&warnings, &source, &filename, crate::colour::stderr());
548 }
549 ExitCode::SUCCESS
550 }
551 Err(errors) => {
552 crate::render::print_errors(&errors, &source, &filename, crate::colour::stderr());
553 ExitCode::FAILURE
554 }
555 }
556}
557
558fn overlay_from_stdin(
560 options: CompileOptions,
561 root: &Path,
562) -> Result<CompileOptions, Box<dyn std::error::Error>> {
563 use std::io::Read as _;
564 let mut json = String::new();
565 std::io::stdin().read_to_string(&mut json)?;
566 let overlay = crate::source_overlay::parse_overlay(&json)?;
567 Ok(crate::source_overlay::apply_overlay(
568 options, root, overlay,
569 )?)
570}
571
572#[cfg(test)]
573mod profile_tests {
574 use super::*;
575 use bynk_project::ProfileConfig;
576
577 type Profiles = std::collections::BTreeMap<String, ProfileConfig>;
578
579 fn with(dev: Option<bool>, release: Option<bool>) -> Profiles {
580 let mut c = Profiles::new();
581 for (name, v) in [("dev", dev), ("release", release)] {
582 if v.is_some() {
583 c.insert(name.to_string(), ProfileConfig { contracts: v });
584 }
585 }
586 c
587 }
588
589 #[test]
590 fn a_profile_defaults_then_its_table_overrides() {
591 let none = with(None, None);
592 assert!(profile_contracts(&none, CliProfile::Dev));
593 assert!(!profile_contracts(&none, CliProfile::Release));
594 let set = with(Some(false), Some(true));
595 assert!(!profile_contracts(&set, CliProfile::Dev));
596 assert!(profile_contracts(&set, CliProfile::Release));
597 }
598
599 #[test]
600 fn one_profiles_table_does_not_touch_the_other() {
601 let only_dev = with(Some(false), None);
602 assert!(!profile_contracts(&only_dev, CliProfile::Dev));
603 assert!(!profile_contracts(&only_dev, CliProfile::Release));
604 }
605}
606
607#[cfg(test)]
608mod worker_group_refusal_tests {
609 use std::fs;
610
611 fn project(name: &str, manifest: &str) -> std::path::PathBuf {
612 let root =
613 std::env::temp_dir().join(format!("bynk-refuse-groups-{name}-{}", std::process::id()));
614 let _ = fs::remove_dir_all(&root);
615 fs::create_dir_all(&root).unwrap();
616 fs::write(root.join("bynk.toml"), manifest).unwrap();
617 root
618 }
619
620 #[test]
624 fn deploy_accepts_a_group_and_refuses_a_malformed_table() {
625 let good = project(
626 "good",
627 "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[deploy.workers.core]\ncontexts = [\"a\", \"b\"]\n",
628 );
629 assert!(super::refuse_undeployable_project(&good).is_ok());
630 let bad = project(
631 "bad-deploy",
632 "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[deploy.workers]\ncore = 3\n",
633 );
634 let err = super::refuse_undeployable_project(&bad).unwrap_err();
635 assert!(err.starts_with("invalid `[deploy.workers]`"), "{err}");
636 let _ = fs::remove_dir_all(&good);
637 let _ = fs::remove_dir_all(&bad);
638 }
639}