bun_install 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
use bun_core::ZStr;
use bun_core::{Output, env_var};
use bun_paths::PathBuffer;
// TODO(port): move to <area>_sys / verify crate path for schema API
use crate::bun_schema::api as Api;

use super::Subcommand;
use super::command_line_arguments::{self, CommandLineArguments};
use bun_dotenv::Loader as DotEnvLoader;
use bun_install::{Features, Npm};

// PORT NOTE: `string` fields are `[]const u8` borrowed from CLI args / bunfig config,
// which live for the process lifetime. There is no `deinit` on Options. Mapped to
// `&'static [u8]` per PORTING.md (no lifetime params on structs).
// TODO(port): lifetime — if any source is not truly 'static, add a lifetime parameter.

pub struct Options {
    pub log_level: LogLevel,
    pub global: bool,

    // TODO(port): std.fs.Dir → bun_sys::Fd (directory handle); default was bun.FD.invalid.stdDir()
    pub global_bin_dir: bun_sys::Fd,
    pub explicit_global_directory: &'static [u8],
    /// destination directory to link bins into
    // must be a variable due to global installs and bunx
    pub bin_path: &'static ZStr,

    pub did_override_default_scope: bool,
    pub scope: Npm::registry::Scope,

    pub registries: Npm::registry::Map,
    pub cache_directory: &'static [u8],
    pub enable: Enable,
    pub do_: Do,
    pub positionals: &'static [&'static [u8]],
    pub update: Update,
    pub dry_run: bool,
    pub link_workspace_packages: bool,
    pub remote_package_features: Features,
    pub local_package_features: Features,
    pub patch_features: PatchFeatures,

    pub filter_patterns: &'static [&'static [u8]],
    pub pack_destination: &'static [u8],
    pub pack_filename: &'static [u8],
    pub pack_gzip_level: Option<&'static [u8]>,
    pub json_output: bool,

    pub max_retry_count: u16,
    pub min_simultaneous_requests: usize,

    pub max_concurrent_lifecycle_scripts: usize,

    pub publish_config: PublishConfig,

    pub ca: Box<[Box<[u8]>]>,
    pub ca_file_name: &'static [u8],

    // if set to `false` in bunfig, save a binary lockfile
    pub save_text_lockfile: Option<bool>,

    pub lockfile_only: bool,

    // `bun pm version` command options
    pub git_tag_version: bool,
    pub allow_same_version: bool,
    pub preid: &'static [u8],
    pub message: Option<&'static [u8]>,
    pub force: bool,

    // `bun pm why` command options
    pub top_only: bool,
    pub depth: Option<usize>,

    /// isolated installs (pnpm-like) or hoisted installs (yarn-like, original)
    pub node_linker: NodeLinker,

    pub public_hoist_pattern: Option<Api::PnpmMatcher>,
    pub hoist_pattern: Option<Api::PnpmMatcher>,

    // Security scanner module path
    pub security_scanner: Option<&'static [u8]>,

    // Minimum release age in ms (security feature)
    // Only install packages published at least N ms ago
    pub minimum_release_age_ms: Option<f64>,
    // Packages to exclude from minimum release age checking
    pub minimum_release_age_excludes: Option<&'static [&'static [u8]]>,

    /// Override CPU architecture for optional dependencies filtering
    pub cpu: Npm::Architecture,
    /// Override OS for optional dependencies filtering
    pub os: Npm::OperatingSystem,

    pub config_version: Option<ConfigVersion>,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            log_level: LogLevel::Default,
            global: false,
            global_bin_dir: bun_sys::Fd::INVALID,
            explicit_global_directory: b"",
            // TODO(port): bun.pathLiteral("node_modules/.bin") — platform-specific separator at comptime
            bin_path: bun_paths::path_literal!("node_modules/.bin"),
            did_override_default_scope: false,
            // PORT NOTE: Zig had `= undefined`; always assigned in `load()` before read.
            scope: Npm::registry::Scope::default(),
            registries: Npm::registry::Map::default(),
            cache_directory: b"",
            enable: Enable::default(),
            do_: Do::default(),
            positionals: &[],
            update: Update::default(),
            dry_run: false,
            link_workspace_packages: true,
            remote_package_features: Features {
                optional_dependencies: true,
                ..Features::default()
            },
            local_package_features: Features {
                optional_dependencies: true,
                dev_dependencies: true,
                workspaces: true,
                ..Features::default()
            },
            patch_features: PatchFeatures::Nothing,
            filter_patterns: &[],
            pack_destination: b"",
            pack_filename: b"",
            pack_gzip_level: None,
            json_output: false,
            max_retry_count: 5,
            min_simultaneous_requests: 4,
            // TODO(port): no default in Zig — caller must supply at construction
            max_concurrent_lifecycle_scripts: 0,
            publish_config: PublishConfig::default(),
            ca: Box::default(),
            ca_file_name: b"",
            save_text_lockfile: None,
            lockfile_only: false,
            git_tag_version: true,
            allow_same_version: false,
            preid: b"",
            message: None,
            force: false,
            top_only: false,
            depth: None,
            node_linker: NodeLinker::Auto,
            public_hoist_pattern: None,
            hoist_pattern: None,
            security_scanner: None,
            minimum_release_age_ms: None,
            minimum_release_age_excludes: None,
            cpu: Npm::Architecture::CURRENT,
            os: Npm::OperatingSystem::CURRENT,
            config_version: None,
        }
    }
}

// PORT NOTE: was an anonymous `union(enum)` field type in Zig.
pub enum PatchFeatures {
    Nothing,
    Patch,
    Commit { patches_dir: &'static [u8] },
}

#[derive(Default, Clone, Copy)]
pub struct PublishConfig {
    pub access: Option<Access>,
    pub tag: &'static [u8],
    pub otp: &'static [u8],
    pub auth_type: Option<AuthType>,
    pub tolerate_republish: bool,
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Access {
    Public,
    Restricted,
}

impl Access {
    // PORT NOTE: was `bun.ComptimeEnumMap(Access)`; ≤8 entries → plain match on &[u8].
    pub fn from_str(str: &[u8]) -> Option<Access> {
        match str {
            b"public" => Some(Access::Public),
            b"restricted" => Some(Access::Restricted),
            _ => None,
        }
    }

    /// Port of Zig `@tagName(access)` — lower-case tag name as written into the
    /// publish JSON body and summary output.
    #[inline]
    pub const fn as_str(self) -> &'static str {
        match self {
            Access::Public => "public",
            Access::Restricted => "restricted",
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum AuthType {
    Legacy,
    Web,
}

impl AuthType {
    // PORT NOTE: was `bun.ComptimeEnumMap(AuthType)`; ≤8 entries → plain match on &[u8].
    pub fn from_str(str: &[u8]) -> Option<AuthType> {
        match str {
            b"legacy" => Some(AuthType::Legacy),
            b"web" => Some(AuthType::Web),
            _ => None,
        }
    }

    /// Port of Zig `@tagName(auth_type)` — lower-case tag name as used by
    /// `npm-auth-type` header in `npm.whoami`.
    #[inline]
    pub const fn as_str(self) -> &'static str {
        match self {
            AuthType::Legacy => "legacy",
            AuthType::Web => "web",
        }
    }
}

/// `Api::NpmRegistry::from_url` — credentials embedded in the URL
/// (`user:pass@` / `:token@`) are extracted and sent.
/// PORT NOTE: upstream added `NpmRegistry::from_url` to `bun_options_types`
/// (outside this batch's scope); route through the identical canonical body in
/// `bun_api::npm_registry` instead of duplicating it.
fn registry_from_url(url: &[u8]) -> Api::NpmRegistry {
    let mut parser = bun_api::npm_registry::Parser {
        log: &mut (),
        source: &(),
    };
    // `parse_registry_url_string_impl` only fails on allocation.
    bun_core::handle_oom(parser.parse_registry_url_string_impl(url))
}

fn registry_has_credentials(registry: &Api::NpmRegistry) -> bool {
    !registry.token.is_empty() || !registry.username.is_empty() || !registry.password.is_empty()
}

impl Options {
    pub fn should_print_command_name(&self) -> bool {
        self.log_level != LogLevel::Silent && self.do_.contains(Do::SUMMARY)
    }

    /// Resolve the registry scope for a (possibly @-scoped) package name.
    ///
    /// Hoisted onto `Options` so callers that already hold a borrow of
    /// `pm.lockfile` can disjointly borrow `pm.options` instead of needing the
    /// whole `&PackageManager`.
    pub fn scope_for_package_name(&self, name: &[u8]) -> &Npm::registry::Scope {
        if name.is_empty() || name[0] != b'@' {
            return &self.scope;
        }
        self.registries
            .get(&Npm::registry::Scope::hash(Npm::registry::Scope::get_name(
                name,
            )))
            .unwrap_or(&self.scope)
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
pub enum LogLevel {
    #[default]
    Default,
    Verbose,
    Silent,
    Quiet,
    DefaultNoProgress,
    VerboseNoProgress,
}

impl LogLevel {
    #[inline]
    pub fn is_verbose(self) -> bool {
        matches!(self, LogLevel::VerboseNoProgress | LogLevel::Verbose)
    }
    #[inline]
    pub fn show_progress(self) -> bool {
        matches!(self, LogLevel::Default | LogLevel::Verbose)
    }
}

pub use crate::config_version::ConfigVersion;
pub use bun_install_types::NodeLinker::NodeLinker;

#[derive(Default, Copy, Clone)]
pub struct Update {
    pub development: bool,
    pub optional: bool,
    pub peer: bool,
}

// PORT NOTE: `std.fs.cwd().makeOpenPath` → `bun_sys::Dir::cwd().make_open_path()`
// (mkdir -p + open dir). Return type was `!std.fs.Dir`; callers store the raw
// `Fd` (`options.global_bin_dir: Fd`), so unwrap to `.fd`.
pub fn open_global_dir(explicit_global_dir: &[u8]) -> Result<bun_sys::Fd, bun_core::Error> {
    use bun_paths::{platform, resolve_path::join_abs_string_buf};
    use bun_sys::{Dir, OpenDirOptions};

    if let Some(home_dir) = env_var::BUN_INSTALL_GLOBAL_DIR.get() {
        return Dir::cwd()
            .make_open_path(home_dir, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    if !explicit_global_dir.is_empty() {
        return Dir::cwd()
            .make_open_path(explicit_global_dir, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    if let Some(home_dir) = env_var::BUN_INSTALL.get() {
        let mut buf = PathBuffer::uninit();
        let parts: [&[u8]; 2] = [b"install", b"global"];
        let path = join_abs_string_buf::<platform::Auto>(home_dir, &mut buf.0, &parts);
        return Dir::cwd()
            .make_open_path(path, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    if let Some(home_dir) = env_var::XDG_CACHE_HOME
        .get()
        .or_else(|| env_var::HOME.get())
    {
        let mut buf = PathBuffer::uninit();
        let parts: [&[u8]; 3] = [b".bun", b"install", b"global"];
        let path = join_abs_string_buf::<platform::Auto>(home_dir, &mut buf.0, &parts);
        return Dir::cwd()
            .make_open_path(path, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    Err(bun_core::err!("No global directory found"))
}

pub(crate) fn open_global_bin_dir(
    opts_: Option<&Api::BunInstall>,
) -> Result<bun_sys::Fd, bun_core::Error> {
    use bun_paths::{platform, resolve_path::join_abs_string_buf};
    use bun_sys::{Dir, OpenDirOptions};

    if let Some(home_dir) = env_var::BUN_INSTALL_BIN.get() {
        return Dir::cwd()
            .make_open_path(home_dir, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    if let Some(opts) = opts_ {
        if let Some(home_dir) = &opts.global_bin_dir {
            if !home_dir.is_empty() {
                return Dir::cwd()
                    .make_open_path(home_dir, OpenDirOptions::default())
                    .map(|d| d.into_raw());
            }
        }
    }

    if let Some(home_dir) = env_var::BUN_INSTALL.get() {
        let mut buf = PathBuffer::uninit();
        let parts: [&[u8]; 1] = [b"bin"];
        let path = join_abs_string_buf::<platform::Auto>(home_dir, &mut buf.0, &parts);
        return Dir::cwd()
            .make_open_path(path, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    if let Some(home_dir) = env_var::XDG_CACHE_HOME
        .get()
        .or_else(|| env_var::HOME.get())
    {
        let mut buf = PathBuffer::uninit();
        let parts: [&[u8]; 2] = [b".bun", b"bin"];
        let path = join_abs_string_buf::<platform::Auto>(home_dir, &mut buf.0, &parts);
        return Dir::cwd()
            .make_open_path(path, OpenDirOptions::default())
            .map(|d| d.into_raw());
    }

    Err(bun_core::err!(
        "Missing global bin directory: try setting $BUN_INSTALL"
    ))
}

// PORT NOTE: Zig borrowed `[]const u8` from `Api.BunInstall` (process-lifetime
// arena). Rust `BunInstall` owns `Box<[u8]>`; Options stores `&'static [u8]`
// per the "no struct lifetime params" porting convention. Park a clone for the
// lifetime of the install command (matches Zig's never-reset config arena) via
// the named hand-off helper.
#[inline]
fn leak_static(s: &[u8]) -> &'static [u8] {
    bun_core::heap::release(s.to_vec().into_boxed_slice())
}

impl Options {
    pub fn load(
        &mut self,
        log: &mut bun_ast::Log,
        env: &mut DotEnvLoader,
        maybe_cli: Option<CommandLineArguments>,
        // Spec PackageManagerOptions.zig:224 `bun_install_: ?*Api.BunInstall` —
        // every access below is a read of `config.*`; no field is ever written.
        // Taking `&` (not `&mut`) keeps provenance coherent with the bundler/
        // resolver storage (`Option<NonNull<api::BunInstall>>`).
        bun_install_: Option<&Api::BunInstall>,
        subcommand: Subcommand,
    ) -> Result<(), bun_alloc::AllocError> {
        let mut base = Api::NpmRegistry::default();
        // PORT NOTE: reshaped for borrowck — Zig captures `*Api.BunInstall` twice via `if (bun_install_) |config|`.
        let bun_install_ref = bun_install_;
        if let Some(config) = bun_install_ref {
            if let Some(registry) = &config.default_registry {
                base = registry.clone();
            }
            if let Some(link_workspace_packages) = config.link_workspace_packages {
                self.link_workspace_packages = link_workspace_packages;
            }
        }

        if base.url.is_empty() {
            base.url = Npm::registry::DEFAULT_URL.as_bytes().into();
        }
        // PORT NOTE: Zig passes `base` by-value (struct copy); clone so the
        // `base.url` fallback below in the scoped-registry loop stays valid.
        self.scope = Npm::registry::Scope::from_api(b"", base.clone(), env)?;
        // PORT NOTE: Zig `defer { this.did_override_default_scope = ... }` moved to end of fn;
        // on the OOM error path the field is irrelevant (process aborts).

        if let Some(config) = bun_install_ref {
            if let Some(cache_directory) = config.cache_directory.as_deref() {
                self.cache_directory = leak_static(cache_directory);
            }

            if let Some(scoped) = &config.scoped {
                for (name, registry_) in scoped.scopes.keys().iter().zip(scoped.scopes.values()) {
                    debug_assert_eq!(scoped.scopes.keys().len(), scoped.scopes.values().len());
                    let mut registry = registry_.clone();
                    if registry.url.is_empty() {
                        registry.url.clone_from(&base.url);
                    }
                    self.registries.put(
                        Npm::registry::Scope::hash(name),
                        Npm::registry::Scope::from_api(name, registry, env)?,
                    )?;
                }
            }

            if let Some(ca) = &config.ca {
                match ca {
                    Api::Ca::List(ca_list) => {
                        self.ca.clone_from(ca_list);
                    }
                    Api::Ca::Str(ca_str) => {
                        // Zig `&.{ca_str}` — single-element slice; own it (no `Box::leak`).
                        self.ca = vec![ca_str.clone()].into_boxed_slice();
                    }
                }
            }

            if let Some(node_linker) = config.node_linker {
                // `Api::NodeLinker` is a re-export of `bun_install_types::NodeLinker`.
                self.node_linker = node_linker;
            }

            if let Some(global_store) = config.global_store {
                self.enable.set(Enable::GLOBAL_VIRTUAL_STORE, global_store);
            }

            if let Some(security_scanner) = config.security_scanner.as_deref() {
                self.security_scanner = Some(leak_static(security_scanner));
                self.do_.set(Do::PREFETCH_RESOLVED_TARBALLS, false);
            }

            if let Some(cafile) = config.cafile.as_deref() {
                self.ca_file_name = leak_static(cafile);
            }

            if config.disable_cache.unwrap_or(false) {
                self.enable.set(Enable::CACHE, false);
            }

            if config.disable_manifest_cache.unwrap_or(false) {
                self.enable.set(Enable::MANIFEST_CACHE, false);
            }

            if config.force.unwrap_or(false) {
                self.enable.set(Enable::MANIFEST_CACHE_CONTROL, false);
                self.enable.set(Enable::FORCE_INSTALL, true);
            }

            if config.save_yarn_lockfile.unwrap_or(false) {
                self.do_.set(Do::SAVE_YARN_LOCK, true);
            }

            if let Some(save_lockfile) = config.save_lockfile {
                self.do_.set(Do::SAVE_LOCKFILE, save_lockfile);
                self.enable.set(Enable::FORCE_SAVE_LOCKFILE, true);
            }

            if let Some(save) = config.save_dev {
                self.local_package_features.dev_dependencies = save;
                // remote packages should never install dev dependencies
                // (TODO: unless git dependency with postinstalls)
            }

            if let Some(save) = config.save_optional {
                self.remote_package_features.optional_dependencies = save;
                self.local_package_features.optional_dependencies = save;
            }

            if let Some(save) = config.save_peer {
                self.remote_package_features.peer_dependencies = save;
                self.local_package_features.peer_dependencies = save;
            }

            if let Some(exact) = config.exact {
                self.enable.set(Enable::EXACT_VERSIONS, exact);
            }

            if let Some(production) = config.production {
                if production {
                    self.local_package_features.dev_dependencies = false;
                    self.enable.set(Enable::FAIL_EARLY, true);
                    self.enable.set(Enable::FROZEN_LOCKFILE, true);
                    self.enable.set(Enable::FORCE_SAVE_LOCKFILE, false);
                }
            }

            if let Some(frozen_lockfile) = config.frozen_lockfile {
                if frozen_lockfile {
                    self.enable.set(Enable::FROZEN_LOCKFILE, true);
                }
            }

            if let Some(save_text_lockfile) = config.save_text_lockfile {
                self.save_text_lockfile = Some(save_text_lockfile);
            }

            if let Some(jobs) = config.concurrent_scripts {
                self.max_concurrent_lifecycle_scripts = jobs as usize;
            }

            if let Some(ignore_scripts) = config.ignore_scripts {
                if ignore_scripts {
                    self.do_.set(Do::RUN_SCRIPTS, false);
                }
            }

            if let Some(min_age_ms) = config.minimum_release_age_ms {
                self.minimum_release_age_ms = Some(min_age_ms);
            }

            if let Some(exclusions) = &config.minimum_release_age_excludes {
                let leaked: Vec<&'static [u8]> =
                    exclusions.iter().map(|e| leak_static(e)).collect();
                // Parked for the lifetime of the install command (config arena
                // equivalent), same as `leak_static` above.
                self.minimum_release_age_excludes =
                    Some(&*bun_core::heap::release(leaked.into_boxed_slice()));
            }

            // `PnpmMatcher` is move-only; `config` is `&` here so the matchers
            // are taken by the owning caller (`PackageManager::init`) right
            // after `load()` returns. The runtime auto-install path never uses
            // the isolated linker, so it has nothing to transfer.

            if let Some(global_dir) = config.global_dir.as_deref() {
                self.explicit_global_directory = leak_static(global_dir);
            }
        }

        if let Some(val) = env.get(b"BUN_INSTALL_GLOBAL_STORE") {
            self.enable.set(Enable::GLOBAL_VIRTUAL_STORE, val != b"0");
        }

        let default_disable_progress_bar: bool = 'brk: {
            if let Some(prog) = env.get(b"BUN_INSTALL_PROGRESS") {
                break 'brk prog == b"0";
            }

            if env.is_ci() {
                break 'brk true;
            }

            break 'brk Output::stderr_descriptor_type() != Output::DescriptorType::Terminal;
        };

        // technically, npm_config is case in-sensitive
        // load_registry:
        {
            const REGISTRY_KEYS: [&[u8]; 3] = [
                b"BUN_CONFIG_REGISTRY",
                b"NPM_CONFIG_REGISTRY",
                b"npm_config_registry",
            ];
            let mut did_set = false;

            // PORT NOTE: was `inline for`; homogeneous elements → plain for.
            for registry_key in REGISTRY_KEYS {
                if !did_set {
                    if let Some(registry_) = env.get(registry_key) {
                        if !registry_.is_empty()
                            && (registry_.starts_with(b"https://")
                                || registry_.starts_with(b"http://"))
                        {
                            let mut api_registry = registry_from_url(registry_);
                            // Credentials in the URL win, as they do for `registry=` in .npmrc.
                            if !registry_has_credentials(&api_registry) {
                                let prev_url = self.scope.url.url();
                                let new_url = bun_url::URL::parse(&api_registry.url);
                                if bun_core::without_trailing_slash(new_url.host)
                                    == bun_core::without_trailing_slash(prev_url.host)
                                    && (new_url.is_https() || !prev_url.is_https())
                                {
                                    api_registry.token = core::mem::take(&mut self.scope.token);
                                }
                            }
                            self.scope = Npm::registry::Scope::from_api(b"", api_registry, env)?;
                            did_set = true;
                        }
                    }
                }
            }
        }

        if let Some(cli) = &maybe_cli {
            if !cli.registry.is_empty() {
                let api_registry = registry_from_url(cli.registry);
                if registry_has_credentials(&api_registry) {
                    self.scope = Npm::registry::Scope::from_api(b"", api_registry, env)?;
                } else {
                    let new_url = bun_url::URL::parse(&api_registry.url);
                    let same_origin = {
                        let prev_url = self.scope.url.url();
                        bun_core::without_trailing_slash(new_url.host)
                            == bun_core::without_trailing_slash(prev_url.host)
                            && (new_url.is_https() || !prev_url.is_https())
                    };
                    if !same_origin {
                        self.scope.token = Box::default();
                        self.scope.auth = Box::default();
                        self.scope.user = Box::default();
                    }
                    let href = api_registry.url;
                    self.scope.url_hash =
                        Npm::registry::Scope::hash(bun_core::without_trailing_slash(&href));
                    self.scope.url = bun_url::OwnedURL::from_href(href);
                }
            }
        }

        {
            const TOKEN_KEYS: [&[u8]; 3] = [
                b"BUN_CONFIG_TOKEN",
                b"NPM_CONFIG_TOKEN",
                b"npm_config_token",
            ];
            let mut did_set = false;

            // PORT NOTE: was `inline for`; homogeneous elements → plain for.
            for registry_key in TOKEN_KEYS {
                if !did_set {
                    if let Some(registry_) = env.get(registry_key) {
                        if !registry_.is_empty() {
                            self.scope.token = registry_.into();
                            did_set = true;
                            // stage1 bug: break inside inline is broken
                            // break :load_registry;
                        }
                    }
                }
            }
        }

        if env.get(b"BUN_CONFIG_YARN_LOCKFILE").is_some() {
            self.do_.set(Do::SAVE_YARN_LOCK, true);
        }

        if let Some(retry_count) = env.get(b"BUN_CONFIG_HTTP_RETRY_COUNT") {
            // PORT NOTE: Zig `parseInt(u16, str, 10) catch null` — `Result` → `.ok()`.
            if let Ok(int) = bun_core::parse_int::<u16>(retry_count, 10) {
                self.max_retry_count = int;
            }
        }

        bun_http::async_http::load_env(log, env);

        if let Some(check_bool) = env.get(b"BUN_CONFIG_SKIP_SAVE_LOCKFILE") {
            self.do_.set(Do::SAVE_LOCKFILE, check_bool == b"0");
        }

        if let Some(check_bool) = env.get(b"BUN_CONFIG_SKIP_LOAD_LOCKFILE") {
            self.do_.set(Do::LOAD_LOCKFILE, check_bool == b"0");
        }

        if let Some(check_bool) = env.get(b"BUN_CONFIG_SKIP_INSTALL_PACKAGES") {
            self.do_.set(Do::INSTALL_PACKAGES, check_bool == b"0");
        }

        if let Some(check_bool) = env.get(b"BUN_CONFIG_NO_VERIFY") {
            self.do_.set(Do::VERIFY_INTEGRITY, check_bool != b"0");
        }

        // Update should never read from manifest cache
        if subcommand == Subcommand::Update {
            self.enable.set(Enable::MANIFEST_CACHE, false);
            self.enable.set(Enable::MANIFEST_CACHE_CONTROL, false);
        }

        if let Some(cli) = maybe_cli {
            self.do_.set(Do::ANALYZE, cli.analyze);
            self.enable
                .set(Enable::ONLY_MISSING, cli.only_missing || cli.analyze);

            if let Some(cache_dir) = cli.cache_dir {
                self.cache_directory = cache_dir;
            }

            if cli.exact {
                self.enable.set(Enable::EXACT_VERSIONS, true);
            }

            if !cli.token.is_empty() {
                self.scope.token = cli.token.into();
            }

            if cli.no_save {
                self.do_.set(Do::SAVE_LOCKFILE, false);
                self.do_.set(Do::WRITE_PACKAGE_JSON, false);
            }

            if cli.dry_run {
                self.do_.set(Do::INSTALL_PACKAGES, false);
                self.dry_run = true;
                self.do_.set(Do::WRITE_PACKAGE_JSON, false);
                self.do_.set(Do::SAVE_LOCKFILE, false);
            }

            if cli.no_summary || cli.silent {
                self.do_.set(Do::SUMMARY, false);
            }

            self.filter_patterns = cli.filters;
            self.pack_destination = cli.pack_destination;
            self.pack_filename = cli.pack_filename;
            self.pack_gzip_level = cli.pack_gzip_level;
            self.json_output = cli.json_output;

            if cli.no_cache {
                self.enable.set(Enable::MANIFEST_CACHE, false);
                self.enable.set(Enable::MANIFEST_CACHE_CONTROL, false);
            }

            if let Some(omit) = cli.omit {
                if omit.dev {
                    self.local_package_features.dev_dependencies = false;
                    // remote packages should never install dev dependencies
                    // (TODO: unless git dependency with postinstalls)
                }

                if omit.optional {
                    self.local_package_features.optional_dependencies = false;
                    self.remote_package_features.optional_dependencies = false;
                }

                if omit.peer {
                    self.local_package_features.peer_dependencies = false;
                    self.remote_package_features.peer_dependencies = false;
                }
            }

            if cli.ignore_scripts {
                self.do_.set(Do::RUN_SCRIPTS, false);
            }

            if cli.trusted {
                self.do_.set(Do::TRUST_DEPENDENCIES_FROM_ARGS, true);
            }

            if let Some(save_text_lockfile) = cli.save_text_lockfile {
                self.save_text_lockfile = Some(save_text_lockfile);
            }

            if let Some(min_age_ms) = cli.minimum_release_age_ms {
                self.minimum_release_age_ms = Some(min_age_ms);
            }

            self.lockfile_only = cli.lockfile_only;

            if cli.lockfile_only {
                self.do_.set(Do::PREFETCH_RESOLVED_TARBALLS, false);
            }

            if let Some(node_linker) = cli.node_linker {
                self.node_linker = node_linker;
            }

            let disable_progress_bar = default_disable_progress_bar || cli.no_progress;

            if cli.verbose {
                self.log_level = if disable_progress_bar {
                    LogLevel::VerboseNoProgress
                } else {
                    LogLevel::Verbose
                };
                // SAFETY: main-thread CLI option load — single writer (Zig: `verbose_install = true`).
                super::PackageManager::set_verbose_install(true);
            } else if cli.silent {
                self.log_level = LogLevel::Silent;
                super::PackageManager::set_verbose_install(false);
            } else if cli.quiet {
                self.log_level = LogLevel::Quiet;
                super::PackageManager::set_verbose_install(false);
            } else {
                self.log_level = if disable_progress_bar {
                    LogLevel::DefaultNoProgress
                } else {
                    LogLevel::Default
                };
                super::PackageManager::set_verbose_install(false);
            }

            if cli.no_verify {
                self.do_.set(Do::VERIFY_INTEGRITY, false);
            }

            if cli.yarn {
                self.do_.set(Do::SAVE_YARN_LOCK, true);
            }

            if let Some(backend) = cli.backend {
                // Zig: `PackageInstall.supported_method = backend` — atomic store,
                // main-thread CLI option load (single writer).
                crate::package_install::SUPPORTED_METHOD
                    .store(backend as u8, core::sync::atomic::Ordering::Relaxed);
            }

            // CPU and OS are now parsed as enums in CommandLineArguments, just copy them
            self.cpu = cli.cpu;
            self.os = cli.os;

            self.do_.set(Do::UPDATE_TO_LATEST, cli.latest);
            self.do_.set(Do::RECURSIVE, cli.recursive);

            if !cli.positionals.is_empty() {
                self.positionals = cli.positionals;
            }

            if cli.production {
                self.local_package_features.dev_dependencies = false;
                self.enable.set(Enable::FAIL_EARLY, true);
                self.enable.set(Enable::FROZEN_LOCKFILE, true);
            }

            if cli.frozen_lockfile {
                self.enable.set(Enable::FROZEN_LOCKFILE, true);
            }

            if cli.force {
                self.enable.set(Enable::MANIFEST_CACHE_CONTROL, false);
                self.enable.set(Enable::FORCE_INSTALL, true);
                self.enable.set(Enable::FORCE_SAVE_LOCKFILE, true);
            }

            if cli.development {
                self.update.development = cli.development;
            } else if cli.optional {
                self.update.optional = cli.optional;
            } else if cli.peer {
                self.update.peer = cli.peer;
            }

            match &cli.patch {
                command_line_arguments::PatchOpts::Nothing => {}
                command_line_arguments::PatchOpts::Patch => {
                    self.patch_features = PatchFeatures::Patch;
                }
                command_line_arguments::PatchOpts::Commit { patches_dir } => {
                    self.patch_features = PatchFeatures::Commit {
                        patches_dir: *patches_dir,
                    };
                }
            }

            if let Some(cli_access) = cli.publish_config.access {
                self.publish_config.access = Some(cli_access);
            }
            if !cli.publish_config.tag.is_empty() {
                self.publish_config.tag = cli.publish_config.tag;
            }
            if !cli.publish_config.otp.is_empty() {
                self.publish_config.otp = cli.publish_config.otp;
            }
            if let Some(auth_type) = cli.publish_config.auth_type {
                self.publish_config.auth_type = Some(auth_type);
            }
            self.publish_config.tolerate_republish = cli.tolerate_republish;

            if !cli.ca.is_empty() {
                self.ca = cli.ca.iter().map(|s| Box::<[u8]>::from(*s)).collect();
            }
            if !cli.ca_file_name.is_empty() {
                self.ca_file_name = cli.ca_file_name;
            }

            // `bun pm version` command options
            self.git_tag_version = cli.git_tag_version;
            self.allow_same_version = cli.allow_same_version;
            self.preid = cli.preid;
            self.message = cli.message;
            self.force = cli.force;

            // `bun pm why` command options
            self.top_only = cli.top_only;
            self.depth = cli.depth;
        } else {
            self.log_level = if default_disable_progress_bar {
                LogLevel::DefaultNoProgress
            } else {
                LogLevel::Default
            };
            // SAFETY: main-thread CLI option load — single writer.
            super::PackageManager::set_verbose_install(false);
        }

        // If the lockfile is frozen, don't save it to disk.
        if self.enable.contains(Enable::FROZEN_LOCKFILE) {
            self.do_.set(Do::SAVE_LOCKFILE, false);
            self.enable.set(Enable::FORCE_SAVE_LOCKFILE, false);
        }

        // PORT NOTE: moved from `defer { ... }` after scope assignment (see note above).
        self.did_override_default_scope = self.scope.url_hash != *Npm::registry::DEFAULT_URL_HASH;

        Ok(())
    }
}

bitflags::bitflags! {
    #[derive(Copy, Clone, PartialEq, Eq)]
    pub struct Do: u16 {
        const SAVE_LOCKFILE                = 1 << 0;
        const LOAD_LOCKFILE                = 1 << 1;
        const INSTALL_PACKAGES             = 1 << 2;
        const WRITE_PACKAGE_JSON           = 1 << 3;
        const RUN_SCRIPTS                  = 1 << 4;
        const SAVE_YARN_LOCK               = 1 << 5;
        const PRINT_META_HASH_STRING       = 1 << 6;
        const VERIFY_INTEGRITY             = 1 << 7;
        const SUMMARY                      = 1 << 8;
        const TRUST_DEPENDENCIES_FROM_ARGS = 1 << 9;
        const UPDATE_TO_LATEST             = 1 << 10;
        const ANALYZE                      = 1 << 11;
        const RECURSIVE                    = 1 << 12;
        const PREFETCH_RESOLVED_TARBALLS   = 1 << 13;
        // _: u2 padding
    }
}

impl Default for Do {
    fn default() -> Self {
        Do::SAVE_LOCKFILE
            | Do::LOAD_LOCKFILE
            | Do::INSTALL_PACKAGES
            | Do::WRITE_PACKAGE_JSON
            | Do::RUN_SCRIPTS
            | Do::VERIFY_INTEGRITY
            | Do::SUMMARY
            | Do::PREFETCH_RESOLVED_TARBALLS
    }
}

bitflags::bitflags! {
    #[derive(Copy, Clone, PartialEq, Eq)]
    pub struct Enable: u16 {
        const MANIFEST_CACHE         = 1 << 0;
        const MANIFEST_CACHE_CONTROL = 1 << 1;
        const CACHE                  = 1 << 2;
        const FAIL_EARLY             = 1 << 3;
        const FROZEN_LOCKFILE        = 1 << 4;

        // Don't save the lockfile unless there were actual changes
        // unless...
        const FORCE_SAVE_LOCKFILE    = 1 << 5;

        const FORCE_INSTALL          = 1 << 6;

        const EXACT_VERSIONS         = 1 << 7;
        const ONLY_MISSING           = 1 << 8;
        /// Isolated linker only: materialize package entries once into a shared
        /// `<cache>/links/` directory and symlink `node_modules/.bun/<pkg>` into
        /// it, instead of clonefiling every package into every project on every
        /// install. Off by default; set BUN_INSTALL_GLOBAL_STORE=1 or
        /// `install.globalStore = true` in bunfig to enable.
        const GLOBAL_VIRTUAL_STORE   = 1 << 9;
        // _: u6 padding
    }
}

impl Default for Enable {
    fn default() -> Self {
        Enable::MANIFEST_CACHE | Enable::MANIFEST_CACHE_CONTROL | Enable::CACHE
    }
}

// Field-style accessors for Zig parity (`options.do.save_lockfile = false` /
// `if options.do.install_packages { ... }`). The bitflags struct is `Copy`,
// so getters return by value and setters take `&mut self`.
impl Do {
    #[inline]
    pub fn save_lockfile(self) -> bool {
        self.contains(Do::SAVE_LOCKFILE)
    }
    #[inline]
    pub fn set_save_lockfile(&mut self, v: bool) {
        self.set(Do::SAVE_LOCKFILE, v);
    }
    #[inline]
    pub fn load_lockfile(self) -> bool {
        self.contains(Do::LOAD_LOCKFILE)
    }
    #[inline]
    pub fn set_load_lockfile(&mut self, v: bool) {
        self.set(Do::LOAD_LOCKFILE, v);
    }
    #[inline]
    pub fn install_packages(self) -> bool {
        self.contains(Do::INSTALL_PACKAGES)
    }
    #[inline]
    pub fn set_install_packages(&mut self, v: bool) {
        self.set(Do::INSTALL_PACKAGES, v);
    }
    #[inline]
    pub fn write_package_json(self) -> bool {
        self.contains(Do::WRITE_PACKAGE_JSON)
    }
    #[inline]
    pub fn set_write_package_json(&mut self, v: bool) {
        self.set(Do::WRITE_PACKAGE_JSON, v);
    }
    #[inline]
    pub fn run_scripts(self) -> bool {
        self.contains(Do::RUN_SCRIPTS)
    }
    #[inline]
    pub fn set_run_scripts(&mut self, v: bool) {
        self.set(Do::RUN_SCRIPTS, v);
    }
    #[inline]
    pub fn save_yarn_lock(self) -> bool {
        self.contains(Do::SAVE_YARN_LOCK)
    }
    #[inline]
    pub fn set_save_yarn_lock(&mut self, v: bool) {
        self.set(Do::SAVE_YARN_LOCK, v);
    }
    #[inline]
    pub fn print_meta_hash_string(self) -> bool {
        self.contains(Do::PRINT_META_HASH_STRING)
    }
    #[inline]
    pub fn set_print_meta_hash_string(&mut self, v: bool) {
        self.set(Do::PRINT_META_HASH_STRING, v);
    }
    #[inline]
    pub fn verify_integrity(self) -> bool {
        self.contains(Do::VERIFY_INTEGRITY)
    }
    #[inline]
    pub fn set_verify_integrity(&mut self, v: bool) {
        self.set(Do::VERIFY_INTEGRITY, v);
    }
    #[inline]
    pub fn summary(self) -> bool {
        self.contains(Do::SUMMARY)
    }
    #[inline]
    pub fn set_summary(&mut self, v: bool) {
        self.set(Do::SUMMARY, v);
    }
    #[inline]
    pub fn trust_dependencies_from_args(self) -> bool {
        self.contains(Do::TRUST_DEPENDENCIES_FROM_ARGS)
    }
    #[inline]
    pub fn set_trust_dependencies_from_args(&mut self, v: bool) {
        self.set(Do::TRUST_DEPENDENCIES_FROM_ARGS, v);
    }
    #[inline]
    pub fn update_to_latest(self) -> bool {
        self.contains(Do::UPDATE_TO_LATEST)
    }
    #[inline]
    pub fn set_update_to_latest(&mut self, v: bool) {
        self.set(Do::UPDATE_TO_LATEST, v);
    }
    #[inline]
    pub fn analyze(self) -> bool {
        self.contains(Do::ANALYZE)
    }
    #[inline]
    pub fn set_analyze(&mut self, v: bool) {
        self.set(Do::ANALYZE, v);
    }
    #[inline]
    pub fn recursive(self) -> bool {
        self.contains(Do::RECURSIVE)
    }
    #[inline]
    pub fn set_recursive(&mut self, v: bool) {
        self.set(Do::RECURSIVE, v);
    }
    #[inline]
    pub fn prefetch_resolved_tarballs(self) -> bool {
        self.contains(Do::PREFETCH_RESOLVED_TARBALLS)
    }
    #[inline]
    pub fn set_prefetch_resolved_tarballs(&mut self, v: bool) {
        self.set(Do::PREFETCH_RESOLVED_TARBALLS, v);
    }
}

// Field-style accessors for Zig parity (`options.enable.cache = false` /
// `if options.enable.manifest_cache { ... }`). The bitflags struct is `Copy`,
// so getters return by value and setters take `&mut self`.
impl Enable {
    #[inline]
    pub fn cache(self) -> bool {
        self.contains(Enable::CACHE)
    }
    #[inline]
    pub fn set_cache(&mut self, v: bool) {
        self.set(Enable::CACHE, v);
    }
    #[inline]
    pub fn manifest_cache(self) -> bool {
        self.contains(Enable::MANIFEST_CACHE)
    }
    #[inline]
    pub fn set_manifest_cache(&mut self, v: bool) {
        self.set(Enable::MANIFEST_CACHE, v);
    }
    #[inline]
    pub fn manifest_cache_control(self) -> bool {
        self.contains(Enable::MANIFEST_CACHE_CONTROL)
    }
    #[inline]
    pub fn set_manifest_cache_control(&mut self, v: bool) {
        self.set(Enable::MANIFEST_CACHE_CONTROL, v);
    }
    #[inline]
    pub fn fail_early(self) -> bool {
        self.contains(Enable::FAIL_EARLY)
    }
    #[inline]
    pub fn frozen_lockfile(self) -> bool {
        self.contains(Enable::FROZEN_LOCKFILE)
    }
    #[inline]
    pub fn force_save_lockfile(self) -> bool {
        self.contains(Enable::FORCE_SAVE_LOCKFILE)
    }
    #[inline]
    pub fn force_install(self) -> bool {
        self.contains(Enable::FORCE_INSTALL)
    }
    #[inline]
    pub fn exact_versions(self) -> bool {
        self.contains(Enable::EXACT_VERSIONS)
    }
    #[inline]
    pub fn only_missing(self) -> bool {
        self.contains(Enable::ONLY_MISSING)
    }
    #[inline]
    pub fn global_virtual_store(self) -> bool {
        self.contains(Enable::GLOBAL_VIRTUAL_STORE)
    }
}

// ported from: src/install/PackageManager/PackageManagerOptions.zig