deno 2.8.2

Provides the deno executable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
// Copyright 2018-2026 the Deno authors. MIT license.

use std::collections::HashSet;
use std::collections::VecDeque;
use std::io::Write as _;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use deno_ast::MediaType;
use deno_ast::ModuleSpecifier;
use deno_config::deno_json::NodeModulesDirMode;
use deno_core::anyhow::Context;
use deno_core::anyhow::anyhow;
use deno_core::anyhow::bail;
use deno_core::error::AnyError;
use deno_core::futures::FutureExt;
use deno_graph::GraphKind;
use deno_graph::ModuleGraph;
use deno_npm_installer::graph::NpmCachingStrategy;
use deno_path_util::resolve_url_or_path;
use deno_path_util::url_from_file_path;
use deno_path_util::url_to_file_path;
use deno_terminal::colors;
use rand::Rng;

use super::installer::BinNameResolver;
use crate::args::CliOptions;
use crate::args::CompileFlags;
use crate::args::ConfigFlag;
use crate::args::DenoSubcommand;
use crate::args::Flags;
use crate::args::TypeCheckMode;
use crate::factory::CliFactory;
use crate::graph_util::ModuleGraphCreator;
use crate::standalone::binary::WriteBinOptions;
use crate::standalone::binary::is_standalone_binary;
use crate::util::temp::create_temp_node_modules_dir;

pub async fn compile(
  mut flags: Flags,
  mut compile_flags: CompileFlags,
) -> Result<(), AnyError> {
  // Framework detection: when the source is a directory, detect the
  // framework and generate an entrypoint automatically.
  let source_dir = if compile_flags.source_file == "." {
    Some(flags.initial_cwd.clone().unwrap_or_else(|| {
      crate::util::env::resolve_cwd(None).unwrap().to_path_buf()
    }))
  } else {
    let path = PathBuf::from(&compile_flags.source_file);
    let path = if path.is_absolute() {
      path
    } else {
      flags
        .initial_cwd
        .clone()
        .unwrap_or_else(|| {
          crate::util::env::resolve_cwd(None).unwrap().to_path_buf()
        })
        .join(path)
    };
    path.is_dir().then_some(path)
  };

  let _framework_entrypoint_file = if let Some(dir) = source_dir {
    if let Some(detection) = super::framework::detect_framework(&dir)? {
      log::info!("Detected {} framework", detection.name);
      // Run the framework's build step if needed.
      if let Some(build_cmd) = &detection.build_command {
        log::info!(
          "{} {} project...",
          colors::green("Building"),
          detection.name,
        );
        let status = std::process::Command::new(&build_cmd[0])
          .args(&build_cmd[1..])
          .current_dir(&dir)
          .status()
          .with_context(|| {
            format!("Failed to run build command: {}", build_cmd.join(" "))
          })?;
        if !status.success() {
          bail!(
            "{} build failed (exit code: {})",
            detection.name,
            status.code().unwrap_or(-1)
          );
        }
      }
      // Enable CJS detection for Node-based frameworks.
      flags.unstable_config.detect_cjs = true;
      // These frameworks emit a pre-built/bundled server entrypoint that is
      // not meant to be type checked by Deno (it references Node types that
      // aren't resolvable from the build output); the framework handles its
      // own compilation.
      if matches!(detection.name, "Next.js" | "SvelteKit")
        && !matches!(flags.type_check_mode, TypeCheckMode::None)
      {
        log::info!(
          "Disabling Deno type checking for {} compile; the framework handles app compilation itself",
          detection.name
        );
        flags.type_check_mode = TypeCheckMode::None;
      }
      // Write a temporary entrypoint file with a random suffix so we
      // never overwrite an existing project file.
      let entrypoint_path = dir.join(format!(
        ".deno_compile_entry_{:08x}.ts",
        rand::thread_rng().r#gen::<u32>()
      ));
      std::fs::write(&entrypoint_path, detection.entrypoint_code)?;
      compile_flags.source_file = entrypoint_path.display().to_string();
      if compile_flags.output.is_none()
        && let Some(dir_name) = dir.file_name()
      {
        compile_flags.output = Some(dir_name.to_string_lossy().into_owned());
      }
      // Add framework build output to includes, resolved relative to the
      // detected app directory so `deno compile ./myapp` picks up
      // `./myapp/.next` rather than `./.next`.
      for inc in detection.include_paths {
        let resolved = dir.join(&inc).display().to_string();
        if !compile_flags.include.contains(&resolved) {
          compile_flags.include.push(resolved);
        }
      }
      Some(entrypoint_path)
    } else {
      bail!(
        "Could not detect a supported framework in '{}'.\n\
         Supported frameworks: Next.js, Astro, Fresh, Remix, SvelteKit, Nuxt, SolidStart, TanStack Start, Vite SSR\n\
         Provide an explicit entrypoint instead of a directory.",
        dir.display()
      );
    }
  } else {
    None
  };

  // Keep flags.subcommand in sync so resolve_main_module sees the
  // rewritten source_file instead of the original directory path.
  flags.subcommand = DenoSubcommand::Compile(compile_flags.clone());

  // Clean up temp entrypoints on exit (framework-detected and/or bundled).
  struct CleanupGuard(Vec<PathBuf>);
  impl Drop for CleanupGuard {
    fn drop(&mut self) {
      for path in &self.0 {
        let _ = std::fs::remove_file(path);
      }
    }
  }
  // Register the framework entrypoint for cleanup up front so it's removed
  // even if a later step (e.g. bundling) fails and unwinds via `?`.
  let _framework_cleanup =
    _framework_entrypoint_file.map(|p| CleanupGuard(vec![p]));

  // use a temporary directory with a node_modules folder when the user
  // specifies an npm package for better compatibility
  let _temp_dir =
    if compile_flags.source_file.to_lowercase().starts_with("npm:")
      && flags.node_modules_dir.is_none()
      && !matches!(flags.config_flag, ConfigFlag::Path(_))
    {
      let temp_node_modules_dir = create_temp_node_modules_dir()
        .context("Failed creating temp directory for node_modules folder.")?;
      flags.initial_cwd = Some(temp_node_modules_dir.parent().to_path_buf());
      flags.internal.root_node_modules_dir_override =
        Some(temp_node_modules_dir.node_modules_dir_path().to_path_buf());
      flags.node_modules_dir = Some(NodeModulesDirMode::Auto);
      Some(temp_node_modules_dir)
    } else {
      None
    };

  let _bundle_cleanup = if compile_flags.bundle {
    log::warn!(
      "{} deno compile --bundle is experimental and may change.",
      colors::yellow("Warning")
    );
    // Auto-include the closest `package.json` to the entrypoint, if any.
    // Lots of packages read their own `package.json` for version info
    // (pi's `getPackageJsonPath()` walks up from `import.meta.url`),
    // and after bundling the bundle's URL doesn't sit next to one. We
    // ship it alongside the bundle so the walk-up succeeds without the
    // user having to thread `--include` themselves.
    let initial_cwd_for_pkg = flags.initial_cwd.clone().unwrap_or_else(|| {
      crate::util::env::resolve_cwd(None).unwrap().to_path_buf()
    });
    if let Some(pkg_json_path) =
      closest_package_json(&initial_cwd_for_pkg, &compile_flags.source_file)
    {
      let display = pkg_json_path.display().to_string();
      if !compile_flags.include.contains(&display) {
        compile_flags.include.push(display);
      }
    }
    let BundleForCompileResult {
      path: bundle_path,
      needs_npm_embed,
      referenced_abs_paths,
      extra_cleanup,
    } = run_bundle_for_compile(&flags, &compile_flags)
      .boxed_local()
      .await?;
    flags.internal.compile_bundle_embed_node_modules = needs_npm_embed;
    // Referenced files that live inside a `node_modules` tree are npm
    // packages, embedded by the binary writer's npm path. The rest are local
    // project files the bundle externalized (e.g. a sibling `.cjs` imported
    // from ESM, which the CJS-from-ESM wrapper turns into a runtime
    // require()). Those aren't covered by the npm embed, so add them to the
    // include set to ship them in the VFS at their real path — that's where
    // `__internalResolveBundlePath` looks for them at runtime.
    for path in &referenced_abs_paths {
      let in_node_modules =
        path.components().any(|c| c.as_os_str() == "node_modules");
      if !in_node_modules {
        let included = path.display().to_string();
        if !compile_flags.include.contains(&included) {
          compile_flags.include.push(included);
        }
      }
    }
    flags.internal.compile_bundle_referenced_paths = referenced_abs_paths;
    compile_flags.source_file = bundle_path.to_string_lossy().into_owned();
    // Make sure any worker bundles travel along in the VFS so the runtime
    // `new Worker(new URL(..., import.meta.url))` lookup hits them.
    for worker_path in &extra_cleanup {
      compile_flags
        .include
        .push(worker_path.display().to_string());
    }
    flags.subcommand = DenoSubcommand::Compile(compile_flags.clone());
    let mut cleanup = vec![bundle_path];
    cleanup.extend(extra_cleanup);
    Some(CleanupGuard(cleanup))
  } else {
    None
  };

  let flags = Arc::new(flags);
  // boxed_local() is to avoid large futures
  if compile_flags.eszip {
    compile_eszip(flags, compile_flags).boxed_local().await
  } else {
    compile_binary(flags, compile_flags).boxed_local().await
  }
}

struct BundleForCompileResult {
  path: PathBuf,
  /// True when esbuild's CJS-from-ESM wrapper appears in the bundle (in the
  /// main entry or any worker), which means runtime require()s against npm
  /// package paths will happen. The standalone binary writer reads this to
  /// decide whether to embed the npm tree.
  needs_npm_embed: bool,
  /// Absolute paths the bundle path-rewriter resolved. Used downstream to
  /// scope the npm-tree embed to just the packages those paths live in.
  referenced_abs_paths: Vec<PathBuf>,
  /// Worker bundle files produced alongside the main one; they live next to
  /// the main bundle and must be cleaned up too.
  extra_cleanup: Vec<PathBuf>,
}

async fn run_bundle_for_compile(
  flags: &Flags,
  compile_flags: &CompileFlags,
) -> Result<BundleForCompileResult, AnyError> {
  let bundle_flags = Arc::new(flags.clone());
  let initial_cwd = flags.initial_cwd.clone().unwrap_or_else(|| {
    crate::util::env::resolve_cwd(None).unwrap().to_path_buf()
  });

  let main_bytes = bundle_one_for_compile(
    bundle_flags.clone(),
    compile_flags.source_file.clone(),
    compile_flags.minify,
  )
  .await?;
  let main_rewrite = rewrite_absolute_bundle_paths(&main_bytes, &initial_cwd)?;
  let mut needs_npm_embed = main_rewrite.rewrote_paths;
  let mut all_referenced_paths: Vec<PathBuf> =
    main_rewrite.referenced_abs_paths.clone();

  // Scan the main bundle for `new URL("X.{ts,js,…}", import.meta.url)`
  // patterns. Each resolvable target is a potential worker entrypoint —
  // including ones the user code stashes in a variable before passing
  // to `new Worker(...)`, which the previous inline-only regex missed.
  // For each unique target we bundle it separately, write it next to
  // the main bundle, and rewrite the URL string in the main bundle to
  // point at the worker bundle's file name.
  let main_src = std::str::from_utf8(&main_rewrite.bytes)
    .context("Bundle output is not valid UTF-8")?;
  let worker_urls = discover_worker_urls(main_src, &initial_cwd);

  let mut url_replacements: Vec<(String, String)> = Vec::new();
  let mut extra_cleanup: Vec<PathBuf> = Vec::new();
  for (worker_url, worker_abs) in &worker_urls {
    let worker_bytes = bundle_one_for_compile(
      bundle_flags.clone(),
      worker_abs.display().to_string(),
      compile_flags.minify,
    )
    .await?;
    let worker_rewrite =
      rewrite_absolute_bundle_paths(&worker_bytes, &initial_cwd)?;
    needs_npm_embed |= worker_rewrite.rewrote_paths;
    all_referenced_paths.extend(worker_rewrite.referenced_abs_paths.clone());

    let worker_path = initial_cwd.join(format!(
      ".deno_compile_worker_{:08x}.mjs",
      rand::thread_rng().r#gen::<u32>()
    ));
    std::fs::write(&worker_path, &worker_rewrite.bytes).with_context(|| {
      format!(
        "Writing bundled worker entrypoint to '{}'",
        worker_path.display()
      )
    })?;
    let worker_file_name = worker_path
      .file_name()
      .unwrap()
      .to_string_lossy()
      .into_owned();
    url_replacements
      .push((worker_url.clone(), format!("./{worker_file_name}")));
    extra_cleanup.push(worker_path);
  }

  // Apply URL replacements to the main bundle source.
  let final_main_src = if url_replacements.is_empty() {
    main_src.to_string()
  } else {
    rewrite_worker_urls(main_src, &url_replacements)
  };

  let bundle_path = initial_cwd.join(format!(
    ".deno_compile_bundle_{:08x}.mjs",
    rand::thread_rng().r#gen::<u32>()
  ));
  std::fs::write(&bundle_path, final_main_src.as_bytes()).with_context(
    || format!("Writing bundled entrypoint to '{}'", bundle_path.display()),
  )?;

  Ok(BundleForCompileResult {
    path: bundle_path,
    needs_npm_embed,
    referenced_abs_paths: all_referenced_paths,
    extra_cleanup,
  })
}

async fn bundle_one_for_compile(
  flags: Arc<Flags>,
  entrypoint: String,
  minify: bool,
) -> Result<Vec<u8>, AnyError> {
  // Always leave `.node` files external. esbuild has no loader for them
  // and would error if it tried to inline a native binary; with this
  // pattern the require() calls are emitted verbatim and resolved at
  // runtime against the embedded VFS by the native addon loader.
  let external = vec!["*.node".to_string()];
  super::bundle::bundle_for_compile(flags, entrypoint, external, minify)
    .boxed_local()
    .await
}

/// Find every `new URL("X.{ts,js,…}", import.meta.url)` in the bundle whose
/// `X` we can resolve to a source file on disk. Each match is a potential
/// worker entrypoint: even when the URL is stashed in a variable and only
/// later passed to `new Worker(...)` we still want to bundle it.
///
/// Resolution tries the URL as a relative path from `initial_cwd` first
/// (covers the common case where source and bundle share a directory),
/// then falls back to a basename search across the workspace — pi's
/// `dist/utils/image-resize.js` does
/// `new URL("./image-resize-worker.js", import.meta.url)` and the bundle
/// lives at `dist/.deno_compile_bundle_*.mjs`, so basename matching is
/// what locks it onto `dist/utils/image-resize-worker.js`.
///
/// Returns `(original_url_string, resolved_source_path)` pairs in source
/// order, deduped on the URL string.
fn discover_worker_urls(
  bundle_src: &str,
  initial_cwd: &Path,
) -> Vec<(String, PathBuf)> {
  // Match `new URL(<first-arg>, import.meta.url)` with `<first-arg>`
  // captured non-greedily so we handle non-literal forms like the
  // ternary pi uses:
  //   new URL(isTs ? "./worker.ts" : "./worker.js", import.meta.url)
  let call_pattern = lazy_regex::regex!(
    r#"new\s+URL\s*\(\s*(.+?)\s*,\s*import\.meta\.url\s*\)"#
  );
  let url_string_pattern =
    lazy_regex::regex!(r#""([^"\n]+\.(?:ts|tsx|js|jsx|mjs|cjs))""#);
  let mut seen = std::collections::HashSet::new();
  let mut out = Vec::new();
  for call_caps in call_pattern.captures_iter(bundle_src) {
    let first_arg = call_caps.get(1).unwrap().as_str();
    for url_caps in url_string_pattern.captures_iter(first_arg) {
      let url = url_caps.get(1).unwrap().as_str().to_string();
      if !seen.insert(url.clone()) {
        continue;
      }
      if let Some(path) = resolve_worker_url_target(&url, initial_cwd) {
        out.push((url, path));
      }
    }
  }
  out
}

fn resolve_worker_url_target(url: &str, initial_cwd: &Path) -> Option<PathBuf> {
  // Try as a literal relative path from the bundle's directory first.
  let candidate = if Path::new(url).is_absolute() {
    PathBuf::from(url)
  } else {
    initial_cwd.join(url)
  };
  if candidate.is_file() {
    return Some(candidate);
  }
  // Fall back to searching by basename across the workspace. This handles
  // bundles whose runtime location doesn't match the original source's
  // location: the URL string is preserved by esbuild but
  // `import.meta.url` now points at the bundle's directory.
  let basename = Path::new(url).file_name()?;
  find_file_by_name(initial_cwd, basename)
}

fn find_file_by_name(root: &Path, name: &std::ffi::OsStr) -> Option<PathBuf> {
  let mut pending = std::collections::VecDeque::from([root.to_path_buf()]);
  while let Some(dir) = pending.pop_front() {
    let Ok(entries) = std::fs::read_dir(&dir) else {
      continue;
    };
    for entry in entries.flatten() {
      let path = entry.path();
      let file_name = path.file_name();
      if path.is_dir() {
        if matches!(
          file_name,
          Some(n) if n == std::ffi::OsStr::new("node_modules")
            || n == std::ffi::OsStr::new(".git")
            || n == std::ffi::OsStr::new("target")
        ) {
          continue;
        }
        pending.push_back(path);
      } else if file_name == Some(name) {
        return Some(path);
      }
    }
  }
  None
}

/// Find the closest `package.json` above the entrypoint. Walks up from
/// the entrypoint's directory toward `initial_cwd` and returns the first
/// `package.json` it sees. Used to auto-include the file in the VFS so
/// `getPackageDir`-style walks at runtime succeed without the user
/// having to add a `--include` flag.
fn closest_package_json(
  initial_cwd: &Path,
  source_file: &str,
) -> Option<PathBuf> {
  let source_path = if Path::new(source_file).is_absolute() {
    PathBuf::from(source_file)
  } else {
    initial_cwd.join(source_file)
  };
  let mut dir = source_path.parent()?.to_path_buf();
  loop {
    let candidate = dir.join("package.json");
    if candidate.is_file() {
      return Some(candidate);
    }
    if !dir.pop() {
      return None;
    }
  }
}

fn rewrite_worker_urls(
  bundle_src: &str,
  replacements: &[(String, String)],
) -> String {
  // Rewrite happens inside `new URL(<arg>, import.meta.url)` only, so
  // user code that happens to contain a string matching a worker path
  // somewhere else (a log message, a regex, etc.) is left alone. Within
  // each call's `<arg>` we do a literal string-substring substitution
  // so ternaries like
  //   new URL(isTs ? "./worker.ts" : "./worker.js", import.meta.url)
  // get all of their string-literal branches rewritten.
  let pattern = lazy_regex::regex!(
    r#"(new\s+URL\s*\(\s*)(.+?)(\s*,\s*import\.meta\.url\s*\))"#
  );
  pattern
    .replace_all(bundle_src, |caps: &regex::Captures<'_>| {
      let prefix = &caps[1];
      let mut arg = caps[2].to_string();
      let suffix = &caps[3];
      for (orig, replacement) in replacements {
        let needle = format!("\"{orig}\"");
        let with = format!("\"{replacement}\"");
        arg = arg.replace(&needle, &with);
      }
      format!("{prefix}{arg}{suffix}")
    })
    .into_owned()
}

struct RewriteResult {
  bytes: Vec<u8>,
  rewrote_paths: bool,
  /// Absolute paths the rewriter touched. These point at the build-machine
  /// locations of files the bundled output expects to require at runtime
  /// — typically deep inside the npm cache. The binary writer uses this
  /// set to decide which npm packages to embed in the VFS.
  referenced_abs_paths: Vec<PathBuf>,
}

fn rewrite_absolute_bundle_paths(
  bundle_bytes: &[u8],
  bundle_dir: &Path,
) -> Result<RewriteResult, AnyError> {
  let src = std::str::from_utf8(bundle_bytes)
    .context("Bundle output is not valid UTF-8")?;
  // Only rewrite paths that actually exist on disk at build time — these are
  // the ones the bundler emitted referring to files it expects to be
  // reachable through the VFS at runtime.
  Ok(rewrite_absolute_bundle_paths_inner(src, bundle_dir, |p| {
    p.exists()
  }))
}

/// Core of [`rewrite_absolute_bundle_paths`], parameterized over the
/// build-time existence check so it can be unit-tested with synthetic paths.
fn rewrite_absolute_bundle_paths_inner(
  src: &str,
  bundle_dir: &Path,
  path_exists: impl Fn(&Path) -> bool,
) -> RewriteResult {
  // Match string literals that look like an absolute path to a JS/JSON source
  // file: either POSIX (`/a/b.js`) or a Windows drive-letter path
  // (`C:\a\b.js` / `C:/a/b.js`). Because the bundle is JS source, a Windows
  // path's separators arrive JS-escaped as `\\`, which the body matches as
  // ordinary (non-`"`) characters. Conservative on extension on purpose — we
  // don't want to rewrite arbitrary user-provided strings.
  //
  // Load-bearing assumption: every absolute-path literal we match is an
  // external `require(...)` argument, i.e. a *value* position where wrapping
  // it in `__internalResolveBundlePath(...)` stays valid JS. This holds
  // because esbuild emits *relative* keys (no leading `/`) for the inlined
  // `__commonJS` module map, so the only absolute literals left in the output
  // are at external require call sites. If esbuild ever emitted an absolute
  // `__commonJS` key (e.g. via a different `absWorkingDir`/outbase), this
  // would rewrite it into `{ __internalResolveBundlePath("...")(...) {...} }`,
  // a syntax error — the spec tests under `tests/specs/compile/bundle` would
  // catch that. A genuine user string literal pointing at an existing file on
  // disk would also be rewritten, but the build-time existence check below
  // keeps that to paths that really resolve through the VFS.
  let pattern = lazy_regex::regex!(
    r#""((?:[A-Za-z]:)?[\\/][^"\n]+\.(?:js|cjs|mjs|json))""#
  );

  let mut any_rewrite = false;
  let mut referenced_abs_paths: Vec<PathBuf> = Vec::new();
  let rewritten = pattern.replace_all(src, |caps: &regex::Captures<'_>| {
    // Collapse JS-escaped backslashes (`C:\\a\\b.js`) back to real
    // separators before touching the filesystem.
    let abs = caps.get(1).unwrap().as_str().replace("\\\\", "\\");
    let path = Path::new(&abs);
    if !path_exists(path) {
      return caps[0].to_string();
    }
    // Rewrite to a path relative to the bundle file. This is correct only
    // because the VFS embeds `node_modules` at the same cwd-relative offset
    // from the bundle that `diff_paths` computes here (bundle_dir =
    // initial_cwd at build time, resolved at runtime against
    // `import.meta.url`). See `fill_npm_vfs` in cli/standalone/binary.rs,
    // which preserves that cwd-relative layout when populating the VFS.
    let Some(rel) = pathdiff::diff_paths(path, bundle_dir) else {
      return caps[0].to_string();
    };
    any_rewrite = true;
    referenced_abs_paths.push(path.to_path_buf());
    let rel_str: String = rel.to_string_lossy().replace('\\', "/");
    format!("__internalResolveBundlePath({:?})", rel_str.as_str())
  });

  if !any_rewrite {
    return RewriteResult {
      bytes: src.as_bytes().to_vec(),
      rewrote_paths: false,
      referenced_abs_paths,
    };
  }

  let prefix = r#"// Injected by deno compile --bundle: resolve absolute paths emitted by
// esbuild's CJS-from-ESM wrapper against the bundle file's runtime
// location instead of the build-time absolute path.
import { fileURLToPath as __internalFileURLToPath } from "node:url";
import * as __internalPath from "node:path";
const __internalBundleDir = __internalPath.dirname(__internalFileURLToPath(import.meta.url));
function __internalResolveBundlePath(rel) {
  return __internalPath.join(__internalBundleDir, rel);
}
"#;
  RewriteResult {
    bytes: format!("{prefix}{rewritten}").into_bytes(),
    rewrote_paths: true,
    referenced_abs_paths,
  }
}

async fn compile_binary(
  flags: Arc<Flags>,
  compile_flags: CompileFlags,
) -> Result<(), AnyError> {
  let factory = CliFactory::from_flags(flags);
  let cli_options = factory.cli_options()?;
  let module_graph_creator = factory.module_graph_creator().await?;
  let binary_writer = factory.create_compile_binary_writer().await?;
  let entrypoint = cli_options.resolve_main_module()?;
  let bin_name_resolver = factory.bin_name_resolver()?;
  let output_path = resolve_compile_executable_output_path(
    &bin_name_resolver,
    &compile_flags,
    cli_options.initial_cwd(),
  )
  .await?;
  let compile_config = cli_options.start_dir.to_compile_config()?;
  let mut effective_include = compile_config.include.clone();
  for inc in &compile_flags.include {
    if !effective_include.contains(inc) {
      effective_include.push(inc.clone());
    }
  }
  let mut effective_exclude = compile_config.exclude.clone();
  for exc in &compile_flags.exclude {
    if !effective_exclude.contains(exc) {
      effective_exclude.push(exc.clone());
    }
  }
  let roots = get_module_roots_and_include_paths(
    entrypoint,
    &effective_include,
    &effective_exclude,
    cli_options,
  )?;

  let graph =
    build_compile_graph(module_graph_creator, cli_options, &roots).await?;

  let initial_cwd =
    deno_path_util::url_from_directory_path(cli_options.initial_cwd())?;

  log::info!(
    "{} {} to {}",
    colors::green("Compile"),
    crate::util::path::relative_specifier_path_for_display(
      &initial_cwd,
      entrypoint
    ),
    {
      if let Ok(output_path) = deno_path_util::url_from_file_path(&output_path)
      {
        crate::util::path::relative_specifier_path_for_display(
          &initial_cwd,
          &output_path,
        )
      } else {
        output_path.display().to_string()
      }
    }
  );
  validate_output_path(&output_path)?;

  let mut temp_filename = output_path.file_name().unwrap().to_owned();
  temp_filename.push(format!(
    ".tmp-{}",
    faster_hex::hex_encode(
      &rand::thread_rng().r#gen::<[u8; 8]>(),
      &mut [0u8; 16]
    )
    .unwrap()
  ));
  let temp_path = output_path.with_file_name(temp_filename);

  let file = std::fs::File::create(&temp_path).with_context(|| {
    format!("Opening temporary file '{}'", temp_path.display())
  })?;

  let write_result = binary_writer
    .write_bin(WriteBinOptions {
      writer: file,
      display_output_filename: &output_path
        .file_name()
        .unwrap()
        .to_string_lossy(),
      graph: &graph,
      entrypoint,
      include_paths: &roots.include_paths,
      exclude_paths: effective_exclude
        .iter()
        .map(|p| cli_options.initial_cwd().join(p))
        .chain(std::iter::once(
          cli_options.initial_cwd().join(&output_path),
        ))
        .chain(std::iter::once(cli_options.initial_cwd().join(&temp_path)))
        .collect(),
      compile_flags: &compile_flags,
    })
    .await
    .with_context(|| {
      format!(
        "Writing deno compile executable to temporary file '{}'",
        temp_path.display()
      )
    });

  // set it as executable
  #[cfg(unix)]
  let write_result = write_result.and_then(|_| {
    use std::os::unix::fs::PermissionsExt;
    let perms = std::fs::Permissions::from_mode(0o755);
    std::fs::set_permissions(&temp_path, perms).with_context(|| {
      format!(
        "Setting permissions on temporary file '{}'",
        temp_path.display()
      )
    })
  });

  let write_result = write_result.and_then(|_| {
    std::fs::rename(&temp_path, &output_path).with_context(|| {
      format!(
        "Renaming temporary file '{}' to '{}'",
        temp_path.display(),
        output_path.display()
      )
    })
  });

  if let Err(err) = write_result {
    // errored, so attempt to remove the temporary file
    let _ = std::fs::remove_file(temp_path);
    return Err(err);
  }

  Ok(())
}

async fn compile_eszip(
  flags: Arc<Flags>,
  compile_flags: CompileFlags,
) -> Result<(), AnyError> {
  let factory = CliFactory::from_flags(flags);
  let cli_options = factory.cli_options()?;
  let module_graph_creator = factory.module_graph_creator().await?;
  let parsed_source_cache = factory.parsed_source_cache()?;
  let compiler_options_resolver = factory.compiler_options_resolver()?;
  let bin_name_resolver = factory.bin_name_resolver()?;
  let entrypoint = cli_options.resolve_main_module()?;
  let mut output_path = resolve_compile_executable_output_path(
    &bin_name_resolver,
    &compile_flags,
    cli_options.initial_cwd(),
  )
  .await?;
  output_path.set_extension("eszip");

  let maybe_import_map_specifier =
    cli_options.resolve_specified_import_map_specifier()?;
  let compile_config = cli_options.start_dir.to_compile_config()?;
  let mut effective_include = compile_config.include.clone();
  for inc in &compile_flags.include {
    if !effective_include.contains(inc) {
      effective_include.push(inc.clone());
    }
  }
  let mut effective_exclude = compile_config.exclude.clone();
  for exc in &compile_flags.exclude {
    if !effective_exclude.contains(exc) {
      effective_exclude.push(exc.clone());
    }
  }
  let roots = get_module_roots_and_include_paths(
    entrypoint,
    &effective_include,
    &effective_exclude,
    cli_options,
  )?;

  let graph =
    build_compile_graph(module_graph_creator, cli_options, &roots).await?;

  let transpile_and_emit_options = compiler_options_resolver
    .for_specifier(cli_options.workspace().root_dir_url())
    .transpile_options()?;
  let transpile_options = transpile_and_emit_options.transpile.clone();
  let emit_options = transpile_and_emit_options.emit.clone();

  let parser = parsed_source_cache.as_capturing_parser();
  let root_dir_url = cli_options.workspace().root_dir_url();
  log::debug!("Binary root dir: {}", root_dir_url);
  let relative_file_base = eszip::EszipRelativeFileBaseUrl::new(root_dir_url);
  let mut eszip = eszip::EszipV2::from_graph(eszip::FromGraphOptions {
    graph,
    parser,
    transpile_options,
    emit_options,
    relative_file_base: Some(relative_file_base),
    npm_packages: None,
    module_kind_resolver: Default::default(),
    npm_snapshot: Default::default(),
  })?;

  if let Some(import_map_specifier) = maybe_import_map_specifier {
    let import_map_path = import_map_specifier.to_file_path().unwrap();
    let import_map_content = std::fs::read_to_string(&import_map_path)
      .with_context(|| {
        format!("Failed to read import map: {:?}", import_map_path)
      })?;

    let import_map_specifier_str = if let Some(relative_import_map_specifier) =
      root_dir_url.make_relative(&import_map_specifier)
    {
      relative_import_map_specifier
    } else {
      import_map_specifier.to_string()
    };

    eszip.add_import_map(
      eszip::ModuleKind::Json,
      import_map_specifier_str,
      import_map_content.as_bytes().to_vec().into(),
    );
  }

  log::info!(
    "{} {} to {}",
    colors::green("Compile"),
    entrypoint,
    output_path.display(),
  );
  validate_output_path(&output_path)?;

  let mut file = std::fs::File::create(&output_path).with_context(|| {
    format!("Opening ESZip file '{}'", output_path.display())
  })?;

  let write_result = {
    let r = file.write_all(&eszip.into_bytes());
    drop(file);
    r
  };

  if let Err(err) = write_result {
    let _ = std::fs::remove_file(output_path);
    return Err(err.into());
  }

  Ok(())
}

/// This function writes out a final binary to specified path. If output path
/// is not already standalone binary it will return error instead.
fn validate_output_path(output_path: &Path) -> Result<(), AnyError> {
  if output_path.exists() {
    // If the output is a directory, throw error
    if output_path.is_dir() {
      bail!(
        concat!(
          "Could not compile to file '{}' because a directory exists with ",
          "the same name. You can use the `--output <file-path>` flag to ",
          "provide an alternative name."
        ),
        output_path.display()
      );
    }

    // Make sure we don't overwrite any file not created by Deno compiler because
    // this filename is chosen automatically in some cases.
    if !is_standalone_binary(output_path) {
      bail!(
        concat!(
          "Could not compile to file '{}' because the file already exists ",
          "and cannot be overwritten. Please delete the existing file or ",
          "use the `--output <file-path>` flag to provide an alternative name."
        ),
        output_path.display()
      );
    }

    // Remove file if it was indeed a deno compiled binary, to avoid corruption
    // (see https://github.com/denoland/deno/issues/10310)
    std::fs::remove_file(output_path)?;
  } else {
    let output_base = &output_path.parent().unwrap();
    if output_base.exists() && output_base.is_file() {
      bail!(
        concat!(
          "Could not compile to file '{}' because its parent directory ",
          "is an existing file. You can use the `--output <file-path>` flag to ",
          "provide an alternative name.",
        ),
        output_base.display(),
      );
    }
    std::fs::create_dir_all(output_base)?;
  }

  Ok(())
}

struct CompileModuleRoots {
  /// Strict graph roots (entrypoint, `--preload` and `--require` modules)
  /// whose graph resolution errors should fail compilation.
  strict: Vec<ModuleSpecifier>,
  /// JS-like files brought in via `--include`; they are embedded and
  /// transpiled but treated as best-effort assets, so their graph resolution
  /// errors must not fail compilation (see #27505).
  include: Vec<ModuleSpecifier>,
  /// Raw files/directories embedded into the VFS.
  include_paths: Vec<ModuleSpecifier>,
}

/// Builds the module graph stored in the compiled binary.
///
/// Only the strict roots are validated/type checked; `--include` modules are
/// best-effort assets whose unresolved imports are embedded as-is rather than
/// surfaced as errors (#27505).
async fn build_compile_graph(
  module_graph_creator: &ModuleGraphCreator,
  cli_options: &CliOptions,
  roots: &CompileModuleRoots,
) -> Result<ModuleGraph, AnyError> {
  let checked_graph = module_graph_creator
    .create_graph_and_maybe_check(roots.strict.clone())
    .await?;

  if roots.include.is_empty() && !cli_options.type_check_mode().is_true() {
    // Fast path: no includes and no type checking, so the validated graph is
    // exactly what we want to store.
    Ok(Arc::try_unwrap(checked_graph).unwrap())
  } else {
    // Build a code-only graph that also includes the `--include` module roots.
    // `create_graph` does not validate, so unresolved imports inside included
    // assets are embedded as-is rather than surfaced as errors. We also use
    // this path after type checking so type information isn't stored in the
    // binary.
    let mut all_roots = roots.strict.clone();
    all_roots.extend(roots.include.iter().cloned());
    module_graph_creator
      .create_graph(GraphKind::CodeOnly, all_roots, NpmCachingStrategy::Eager)
      .await
  }
}

fn get_module_roots_and_include_paths(
  entrypoint: &ModuleSpecifier,
  include: &[String],
  exclude: &[String],
  cli_options: &Arc<CliOptions>,
) -> Result<CompileModuleRoots, AnyError> {
  let initial_cwd = cli_options.initial_cwd();

  fn is_module_graph_module(url: &ModuleSpecifier) -> bool {
    if url.scheme() != "file" {
      return true;
    }
    is_module_graph_media_type(MediaType::from_specifier(url))
  }

  fn is_module_graph_media_type(media_type: MediaType) -> bool {
    match media_type {
      MediaType::JavaScript
      | MediaType::Jsx
      | MediaType::Mjs
      | MediaType::Cjs
      | MediaType::TypeScript
      | MediaType::Mts
      | MediaType::Cts
      | MediaType::Dts
      | MediaType::Dmts
      | MediaType::Dcts
      | MediaType::Tsx
      | MediaType::Json
      | MediaType::Wasm => true,
      MediaType::Css
      | MediaType::Html
      | MediaType::Jsonc
      | MediaType::Json5
      | MediaType::Markdown
      | MediaType::SourceMap
      | MediaType::Sql
      | MediaType::Unknown => false,
    }
  }

  fn analyze_path(
    url: &ModuleSpecifier,
    excluded_paths: &HashSet<PathBuf>,
    searched_paths: &mut HashSet<PathBuf>,
    mut add_path: impl FnMut(&Path),
  ) -> Result<(), AnyError> {
    let Ok(path) = url_to_file_path(url) else {
      return Ok(());
    };
    let mut pending = VecDeque::from([path]);
    while let Some(path) = pending.pop_front() {
      if !searched_paths.insert(path.clone()) {
        continue;
      }
      if excluded_paths.contains(&path) {
        continue;
      }
      if !path.is_dir() {
        add_path(&path);
        continue;
      }
      for entry in std::fs::read_dir(&path).with_context(|| {
        format!("Failed reading directory '{}'", path.display())
      })? {
        let entry = entry.with_context(|| {
          format!("Failed reading entry in directory '{}'", path.display())
        })?;
        pending.push_back(entry.path());
      }
    }
    Ok(())
  }

  let mut searched_paths = HashSet::new();
  let mut module_roots = Vec::new();
  let mut include_module_roots = Vec::new();
  let mut include_paths = Vec::new();
  let exclude_set = exclude
    .iter()
    .map(|path| initial_cwd.join(path))
    .collect::<HashSet<_>>();
  module_roots.push(entrypoint.clone());
  for side_module in include {
    let url = resolve_url_or_path(side_module, initial_cwd)?;
    if is_module_graph_module(&url) {
      include_module_roots.push(url.clone());
    } else {
      analyze_path(&url, &exclude_set, &mut searched_paths, |file_path| {
        let media_type = MediaType::from_path(file_path);
        if is_module_graph_media_type(media_type)
          && let Ok(file_url) = url_from_file_path(file_path)
        {
          include_module_roots.push(file_url);
        }
      })?;
    }
    if url.scheme() == "file" {
      include_paths.push(url);
    }
  }

  for preload_module in cli_options.preload_modules()? {
    module_roots.push(preload_module);
  }

  for require_module in cli_options.require_modules()? {
    module_roots.push(require_module);
  }

  Ok(CompileModuleRoots {
    strict: module_roots,
    include: include_module_roots,
    include_paths,
  })
}

async fn resolve_compile_executable_output_path(
  bin_name_resolver: &BinNameResolver<'_>,
  compile_flags: &CompileFlags,
  current_dir: &Path,
) -> Result<PathBuf, AnyError> {
  let module_specifier =
    resolve_url_or_path(&compile_flags.source_file, current_dir)?;

  let output_flag = compile_flags.output.clone();
  let mut output_path = if let Some(out) = output_flag.as_ref() {
    let mut out_path = PathBuf::from(out);
    if out.ends_with('/') || out.ends_with('\\') {
      if let Some(infer_file_name) = bin_name_resolver
        .infer_name_from_url(&module_specifier)
        .await
        .map(PathBuf::from)
      {
        out_path = out_path.join(infer_file_name);
      }
    } else {
      out_path = out_path.to_path_buf();
    }
    Some(out_path)
  } else {
    None
  };

  if output_flag.is_none() {
    output_path = bin_name_resolver
      .infer_name_from_url(&module_specifier)
      .await
      .map(PathBuf::from)
  }

  output_path.ok_or_else(|| anyhow!(
    "An executable name was not provided. One could not be inferred from the URL. Aborting.",
  )).map(|output_path| {
    get_os_specific_filepath(output_path, &compile_flags.target)
  })
}

fn get_os_specific_filepath(
  output: PathBuf,
  target: &Option<String>,
) -> PathBuf {
  let is_windows = match target {
    Some(target) => target.contains("windows"),
    None => cfg!(windows),
  };
  if is_windows && output.extension().unwrap_or_default() != "exe" {
    if let Some(ext) = output.extension() {
      // keep version in my-exe-0.1.0 -> my-exe-0.1.0.exe
      output.with_extension(format!("{}.exe", ext.to_string_lossy()))
    } else {
      output.with_extension("exe")
    }
  } else {
    output
  }
}

#[cfg(test)]
mod test {
  use deno_npm::registry::TestNpmRegistryApi;
  use deno_npm::resolution::NpmVersionResolver;

  pub use super::*;
  use crate::http_util::HttpClientProvider;
  use crate::util::env::resolve_cwd;

  #[tokio::test]
  async fn resolve_compile_executable_output_path_target_linux() {
    let http_client = HttpClientProvider::new(None, None);
    let npm_api = TestNpmRegistryApi::default();
    let npm_version_resolver = NpmVersionResolver::default();
    let bin_name_resolver =
      BinNameResolver::new(&http_client, &npm_api, &npm_version_resolver);
    let path = resolve_compile_executable_output_path(
      &bin_name_resolver,
      &CompileFlags {
        source_file: "mod.ts".to_string(),
        output: Some(String::from("./file")),
        args: Vec::new(),
        target: Some("x86_64-unknown-linux-gnu".to_string()),
        no_terminal: false,
        icon: None,
        include: Default::default(),
        exclude: Default::default(),
        eszip: true,
        self_extracting: false,
        bundle: false,
        minify: false,
      },
      &resolve_cwd(None).unwrap(),
    )
    .await
    .unwrap();

    // no extension, no matter what the operating system is
    // because the target was specified as linux
    // https://github.com/denoland/deno/issues/9667
    assert_eq!(path.file_name().unwrap(), "file");
  }

  #[tokio::test]
  async fn resolve_compile_executable_output_path_target_windows() {
    let http_client = HttpClientProvider::new(None, None);
    let npm_api = TestNpmRegistryApi::default();
    let npm_version_resolver = NpmVersionResolver::default();
    let bin_name_resolver =
      BinNameResolver::new(&http_client, &npm_api, &npm_version_resolver);
    let path = resolve_compile_executable_output_path(
      &bin_name_resolver,
      &CompileFlags {
        source_file: "mod.ts".to_string(),
        output: Some(String::from("./file")),
        args: Vec::new(),
        target: Some("x86_64-pc-windows-msvc".to_string()),
        include: Default::default(),
        exclude: Default::default(),
        icon: None,
        no_terminal: false,
        eszip: true,
        self_extracting: false,
        bundle: false,
        minify: false,
      },
      &resolve_cwd(None).unwrap(),
    )
    .await
    .unwrap();
    assert_eq!(path.file_name().unwrap(), "file.exe");
  }

  #[test]
  fn test_os_specific_file_path() {
    fn run_test(path: &str, target: Option<&str>, expected: &str) {
      assert_eq!(
        get_os_specific_filepath(
          PathBuf::from(path),
          &target.map(|s| s.to_string())
        ),
        PathBuf::from(expected)
      );
    }

    if cfg!(windows) {
      run_test("C:\\my-exe", None, "C:\\my-exe.exe");
      run_test("C:\\my-exe.exe", None, "C:\\my-exe.exe");
      run_test("C:\\my-exe-0.1.2", None, "C:\\my-exe-0.1.2.exe");
    } else {
      run_test("my-exe", Some("linux"), "my-exe");
      run_test("my-exe-0.1.2", Some("linux"), "my-exe-0.1.2");
    }

    run_test("C:\\my-exe", Some("windows"), "C:\\my-exe.exe");
    run_test("C:\\my-exe.exe", Some("windows"), "C:\\my-exe.exe");
    run_test("C:\\my-exe.0.1.2", Some("windows"), "C:\\my-exe.0.1.2.exe");
    run_test("my-exe-0.1.2", Some("linux"), "my-exe-0.1.2");
  }

  #[test]
  fn test_rewrite_absolute_bundle_paths_native() {
    // Use the platform-native absolute path layout so this exercises the
    // real shape esbuild emits on each OS. On Windows the require() string in
    // the bundle is a drive-letter path with JS-escaped backslashes
    // (`C:\\proj\\dist\\pkg\\index.js`), which the previous Unix-only regex
    // never matched — leaving the require pointed at a non-existent
    // build-time path at runtime.
    let bundle_dir = if cfg!(windows) {
      PathBuf::from("C:\\proj\\dist")
    } else {
      PathBuf::from("/proj/dist")
    };
    let abs = bundle_dir.join("pkg").join("index.js");
    // Escape backslashes the way they appear inside a JS string literal.
    let abs_in_js = abs.to_string_lossy().replace('\\', "\\\\");
    let src = format!("var m = require(\"{abs_in_js}\");\n");

    let result =
      rewrite_absolute_bundle_paths_inner(&src, &bundle_dir, |_| true);

    assert!(result.rewrote_paths);
    let out = String::from_utf8(result.bytes).unwrap();
    assert!(
      out.contains(r#"__internalResolveBundlePath("pkg/index.js")"#),
      "unexpected output: {out}"
    );
  }

  #[test]
  fn test_rewrite_absolute_bundle_paths_skips_missing() {
    let bundle_dir = PathBuf::from("/proj/dist");
    let src = "var m = require(\"/does/not/exist.js\");\n";
    let result =
      rewrite_absolute_bundle_paths_inner(src, &bundle_dir, |_| false);
    assert!(!result.rewrote_paths);
    assert_eq!(result.bytes.as_slice(), src.as_bytes());
  }

  #[test]
  fn test_rewrite_absolute_bundle_paths_skips_relative_key() {
    // esbuild emits *relative* keys (no leading `/`) for inlined
    // `__commonJS` modules. Those are object-literal keys, not require()
    // arguments — rewriting one into `__internalResolveBundlePath("...")`
    // would be a syntax error. The leading-separator anchor in the pattern
    // keeps them untouched even when the path exists on disk (`|_| true`).
    let bundle_dir = PathBuf::from("/proj/dist");
    let src = "var b = { \"pkg/index.js\"(exports, module) { module.exports = 1; } };\n";
    let result =
      rewrite_absolute_bundle_paths_inner(src, &bundle_dir, |_| true);
    assert!(!result.rewrote_paths);
    assert_eq!(result.bytes.as_slice(), src.as_bytes());
  }
}