-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
install.zig
14989 lines (13158 loc) · 671 KB
/
install.zig
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
// Default to a maximum of 64 simultaneous HTTP requests for bun install if no proxy is specified
// if a proxy IS specified, default to 64. We have different values because we might change this in the future.
// https://github.com/npm/cli/issues/7072
// https://pnpm.io/npmrc#network-concurrency (pnpm defaults to 16)
// https://yarnpkg.com/configuration/yarnrc#networkConcurrency (defaults to 50)
const default_max_simultaneous_requests_for_bun_install = 64;
const default_max_simultaneous_requests_for_bun_install_for_proxies = 64;
const bun = @import("root").bun;
const FeatureFlags = bun.FeatureFlags;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const std = @import("std");
const uws = @import("../deps/uws.zig");
const JSC = bun.JSC;
const DirInfo = @import("../resolver/dir_info.zig");
const File = bun.sys.File;
const JSLexer = bun.js_lexer;
const logger = bun.logger;
const js_parser = bun.js_parser;
const JSON = bun.JSON;
const JSPrinter = bun.js_printer;
const linker = @import("../linker.zig");
const Api = @import("../api/schema.zig").Api;
const Path = bun.path;
const configureTransformOptionsForBun = @import("../bun.js/config.zig").configureTransformOptionsForBun;
const Command = @import("../cli.zig").Command;
const BunArguments = @import("../cli.zig").Arguments;
const bundler = bun.bundler;
const DotEnv = @import("../env_loader.zig");
const which = @import("../which.zig").which;
const Run = @import("../bun_js.zig").Run;
const Fs = @import("../fs.zig");
const FileSystem = Fs.FileSystem;
const Lock = @import("../lock.zig").Lock;
const URL = @import("../url.zig").URL;
const HTTP = bun.http;
const AsyncHTTP = HTTP.AsyncHTTP;
const HTTPChannel = HTTP.HTTPChannel;
const HeaderBuilder = HTTP.HeaderBuilder;
const Integrity = @import("./integrity.zig").Integrity;
const clap = bun.clap;
const ExtractTarball = @import("./extract_tarball.zig");
pub const Npm = @import("./npm.zig");
const Bitset = bun.bit_set.DynamicBitSetUnmanaged;
const z_allocator = @import("../memory_allocator.zig").z_allocator;
const Syscall = bun.sys;
const RunCommand = @import("../cli/run_command.zig").RunCommand;
const PackageManagerCommand = @import("../cli/package_manager_command.zig").PackageManagerCommand;
threadlocal var initialized_store = false;
const Futex = @import("../futex.zig");
pub const Lockfile = @import("./lockfile.zig");
pub const PatchedDep = Lockfile.PatchedDep;
const Walker = @import("../walker_skippable.zig");
const anyhow = bun.anyhow;
pub const bun_hash_tag = ".bun-tag-";
pub const max_hex_hash_len: comptime_int = brk: {
var buf: [128]u8 = undefined;
break :brk (std.fmt.bufPrint(buf[0..], "{x}", .{std.math.maxInt(u64)}) catch @panic("Buf wasn't big enough.")).len;
};
pub const max_buntag_hash_buf_len: comptime_int = max_hex_hash_len + bun_hash_tag.len + 1;
pub const BuntagHashBuf = [max_buntag_hash_buf_len]u8;
pub fn buntaghashbuf_make(buf: *BuntagHashBuf, patch_hash: u64) [:0]u8 {
@memcpy(buf[0..bun_hash_tag.len], bun_hash_tag);
const digits = std.fmt.bufPrint(buf[bun_hash_tag.len..], "{x}", .{patch_hash}) catch bun.outOfMemory();
buf[bun_hash_tag.len + digits.len] = 0;
const bunhashtag = buf[0 .. bun_hash_tag.len + digits.len :0];
return bunhashtag;
}
pub const patch = @import("./patch_install.zig");
pub const PatchTask = patch.PatchTask;
// these bytes are skipped
// so we just make it repeat bun bun bun bun bun bun bun bun bun
// because why not
pub const alignment_bytes_to_repeat_buffer = [_]u8{0} ** 144;
const JSAst = bun.JSAst;
pub fn initializeStore() void {
if (initialized_store) {
JSAst.Expr.Data.Store.reset();
JSAst.Stmt.Data.Store.reset();
return;
}
initialized_store = true;
JSAst.Expr.Data.Store.create();
JSAst.Stmt.Data.Store.create();
}
/// The default store we use pre-allocates around 16 MB of memory per thread
/// That adds up in multi-threaded scenarios.
/// ASTMemoryAllocator uses a smaller fixed buffer allocator
pub fn initializeMiniStore() void {
const MiniStore = struct {
heap: bun.MimallocArena,
memory_allocator: JSAst.ASTMemoryAllocator,
pub threadlocal var instance: ?*@This() = null;
};
if (MiniStore.instance == null) {
var mini_store = bun.default_allocator.create(MiniStore) catch bun.outOfMemory();
mini_store.* = .{
.heap = bun.MimallocArena.init() catch bun.outOfMemory(),
.memory_allocator = undefined,
};
mini_store.memory_allocator = .{ .allocator = mini_store.heap.allocator() };
mini_store.memory_allocator.reset();
MiniStore.instance = mini_store;
mini_store.memory_allocator.push();
} else {
var mini_store = MiniStore.instance.?;
if (mini_store.memory_allocator.stack_allocator.fixed_buffer_allocator.end_index >= mini_store.memory_allocator.stack_allocator.fixed_buffer_allocator.buffer.len -| 1) {
mini_store.heap.reset();
mini_store.memory_allocator.allocator = mini_store.heap.allocator();
}
mini_store.memory_allocator.reset();
mini_store.memory_allocator.push();
}
}
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const ArrayIdentityContext = @import("../identity_context.zig").ArrayIdentityContext;
const NetworkQueue = std.fifo.LinearFifo(*NetworkTask, .{ .Static = 32 });
const PatchTaskFifo = std.fifo.LinearFifo(*PatchTask, .{ .Static = 32 });
const Semver = @import("./semver.zig");
const ExternalString = Semver.ExternalString;
const String = Semver.String;
const GlobalStringBuilder = @import("../string_builder.zig");
const SlicedString = Semver.SlicedString;
const Repository = @import("./repository.zig").Repository;
pub const Bin = @import("./bin.zig").Bin;
pub const Dependency = @import("./dependency.zig");
const Behavior = @import("./dependency.zig").Behavior;
const FolderResolution = @import("./resolvers/folder_resolver.zig").FolderResolution;
pub fn ExternalSlice(comptime Type: type) type {
return ExternalSliceAligned(Type, null);
}
pub fn ExternalSliceAligned(comptime Type: type, comptime alignment_: ?u29) type {
return extern struct {
pub const alignment = alignment_ orelse @alignOf(*Type);
pub const Slice = @This();
pub const Child: type = Type;
off: u32 = 0,
len: u32 = 0,
pub inline fn contains(this: Slice, id: u32) bool {
return id >= this.off and id < (this.len + this.off);
}
pub inline fn get(this: Slice, in: []const Type) []const Type {
if (comptime Environment.allow_assert) {
bun.assert(this.off + this.len <= in.len);
}
// it should be impossible to address this out of bounds due to the minimum here
return in.ptr[this.off..@min(in.len, this.off + this.len)];
}
pub inline fn mut(this: Slice, in: []Type) []Type {
if (comptime Environment.allow_assert) {
bun.assert(this.off + this.len <= in.len);
}
return in.ptr[this.off..@min(in.len, this.off + this.len)];
}
pub inline fn begin(this: Slice) u32 {
return this.off;
}
pub inline fn end(this: Slice) u32 {
return this.off + this.len;
}
pub fn init(buf: []const Type, in: []const Type) Slice {
// if (comptime Environment.allow_assert) {
// bun.assert(@intFromPtr(buf.ptr) <= @intFromPtr(in.ptr));
// bun.assert((@intFromPtr(in.ptr) + in.len) <= (@intFromPtr(buf.ptr) + buf.len));
// }
return Slice{
.off = @as(u32, @truncate((@intFromPtr(in.ptr) - @intFromPtr(buf.ptr)) / @sizeOf(Type))),
.len = @as(u32, @truncate(in.len)),
};
}
};
}
pub const PackageID = u32;
pub const DependencyID = u32;
pub const invalid_package_id = std.math.maxInt(PackageID);
pub const ExternalStringList = ExternalSlice(ExternalString);
pub const VersionSlice = ExternalSlice(Semver.Version);
pub const ExternalStringMap = extern struct {
name: ExternalStringList = .{},
value: ExternalStringList = .{},
};
pub const PackageNameAndVersionHash = u64;
pub const PackageNameHash = u64; // Use String.Builder.stringHash to compute this
pub const TruncatedPackageNameHash = u32; // @truncate String.Builder.stringHash to compute this
pub const Aligner = struct {
pub fn write(comptime Type: type, comptime Writer: type, writer: Writer, pos: usize) !usize {
const to_write = skipAmount(Type, pos);
const remainder: string = alignment_bytes_to_repeat_buffer[0..@min(to_write, alignment_bytes_to_repeat_buffer.len)];
try writer.writeAll(remainder);
return to_write;
}
pub inline fn skipAmount(comptime Type: type, pos: usize) usize {
return std.mem.alignForward(usize, pos, @alignOf(Type)) - pos;
}
};
const NetworkTask = struct {
http: AsyncHTTP = undefined,
task_id: u64,
url_buf: []const u8 = &[_]u8{},
retried: u16 = 0,
allocator: std.mem.Allocator,
request_buffer: MutableString = undefined,
response_buffer: MutableString = undefined,
package_manager: *PackageManager,
callback: union(Task.Tag) {
package_manifest: struct {
loaded_manifest: ?Npm.PackageManifest = null,
name: strings.StringOrTinyString,
},
extract: ExtractTarball,
git_clone: void,
git_checkout: void,
local_tarball: void,
},
/// Key in patchedDependencies in package.json
apply_patch_task: ?*PatchTask = null,
next: ?*NetworkTask = null,
pub const DedupeMapEntry = struct {
is_required: bool,
};
pub const DedupeMap = std.HashMap(u64, DedupeMapEntry, IdentityContext(u64), 80);
pub fn notify(this: *NetworkTask, async_http: *AsyncHTTP, _: anytype) void {
defer this.package_manager.wake();
async_http.real.?.* = async_http.*;
async_http.real.?.response_buffer = async_http.response_buffer;
this.package_manager.async_network_task_queue.push(this);
}
pub const Authorization = enum {
no_authorization,
allow_authorization,
};
// We must use a less restrictive Accept header value
// https://github.com/oven-sh/bun/issues/341
// https://www.jfrog.com/jira/browse/RTFACT-18398
const accept_header_value = "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*";
const default_headers_buf: string = "Accept" ++ accept_header_value;
fn appendAuth(header_builder: *HeaderBuilder, scope: *const Npm.Registry.Scope) void {
if (scope.token.len > 0) {
header_builder.appendFmt("Authorization", "Bearer {s}", .{scope.token});
} else if (scope.auth.len > 0) {
header_builder.appendFmt("Authorization", "Basic {s}", .{scope.auth});
} else {
return;
}
header_builder.append("npm-auth-type", "legacy");
}
fn countAuth(header_builder: *HeaderBuilder, scope: *const Npm.Registry.Scope) void {
if (scope.token.len > 0) {
header_builder.count("Authorization", "");
header_builder.content.cap += "Bearer ".len + scope.token.len;
} else if (scope.auth.len > 0) {
header_builder.count("Authorization", "");
header_builder.content.cap += "Basic ".len + scope.auth.len;
} else {
return;
}
header_builder.count("npm-auth-type", "legacy");
}
pub fn forManifest(
this: *NetworkTask,
name: string,
allocator: std.mem.Allocator,
scope: *const Npm.Registry.Scope,
loaded_manifest: ?*const Npm.PackageManifest,
is_optional: bool,
) !void {
this.url_buf = blk: {
// Not all registries support scoped package names when fetching the manifest.
// registry.npmjs.org supports both "@storybook%2Faddons" and "@storybook/addons"
// Other registries like AWS codeartifact only support the former.
// "npm" CLI requests the manifest with the encoded name.
var arena = std.heap.ArenaAllocator.init(bun.default_allocator);
defer arena.deinit();
var stack_fallback_allocator = std.heap.stackFallback(512, arena.allocator());
var encoded_name = name;
if (strings.containsChar(name, '/')) {
encoded_name = try std.mem.replaceOwned(u8, stack_fallback_allocator.get(), name, "/", "%2f");
}
const tmp = bun.JSC.URL.join(
bun.String.fromUTF8(scope.url.href),
bun.String.fromUTF8(encoded_name),
);
defer tmp.deref();
if (tmp.tag == .Dead) {
if (!is_optional) {
this.package_manager.log.addErrorFmt(
null,
logger.Loc.Empty,
allocator,
"Failed to join registry {} and package {} URLs",
.{ bun.fmt.QuotedFormatter{ .text = scope.url.href }, bun.fmt.QuotedFormatter{ .text = name } },
) catch bun.outOfMemory();
} else {
this.package_manager.log.addWarningFmt(
null,
logger.Loc.Empty,
allocator,
"Failed to join registry {} and package {} URLs",
.{ bun.fmt.QuotedFormatter{ .text = scope.url.href }, bun.fmt.QuotedFormatter{ .text = name } },
) catch bun.outOfMemory();
}
return error.InvalidURL;
}
if (!(tmp.hasPrefixComptime("https://") or tmp.hasPrefixComptime("http://"))) {
if (!is_optional) {
this.package_manager.log.addErrorFmt(
null,
logger.Loc.Empty,
allocator,
"Registry URL must be http:// or https://\nReceived: \"{}\"",
.{tmp},
) catch bun.outOfMemory();
} else {
this.package_manager.log.addWarningFmt(
null,
logger.Loc.Empty,
allocator,
"Registry URL must be http:// or https://\nReceived: \"{}\"",
.{tmp},
) catch bun.outOfMemory();
}
return error.InvalidURL;
}
// This actually duplicates the string! So we defer deref the WTF managed one above.
break :blk try tmp.toOwnedSlice(allocator);
};
var last_modified: string = "";
var etag: string = "";
if (loaded_manifest) |manifest| {
last_modified = manifest.pkg.last_modified.slice(manifest.string_buf);
etag = manifest.pkg.etag.slice(manifest.string_buf);
}
var header_builder = HeaderBuilder{};
countAuth(&header_builder, scope);
if (etag.len != 0) {
header_builder.count("If-None-Match", etag);
}
if (last_modified.len != 0) {
header_builder.count("If-Modified-Since", last_modified);
}
if (header_builder.header_count > 0) {
header_builder.count("Accept", accept_header_value);
if (last_modified.len > 0 and etag.len > 0) {
header_builder.content.count(last_modified);
}
try header_builder.allocate(allocator);
appendAuth(&header_builder, scope);
if (etag.len != 0) {
header_builder.append("If-None-Match", etag);
} else if (last_modified.len != 0) {
header_builder.append("If-Modified-Since", last_modified);
}
header_builder.append("Accept", accept_header_value);
if (last_modified.len > 0 and etag.len > 0) {
last_modified = header_builder.content.append(last_modified);
}
} else {
try header_builder.entries.append(
allocator,
.{
.name = .{ .offset = 0, .length = @as(u32, @truncate("Accept".len)) },
.value = .{ .offset = "Accept".len, .length = @as(u32, @truncate(default_headers_buf.len - "Accept".len)) },
},
);
header_builder.header_count = 1;
header_builder.content = GlobalStringBuilder{ .ptr = @as([*]u8, @ptrFromInt(@intFromPtr(bun.span(default_headers_buf).ptr))), .len = default_headers_buf.len, .cap = default_headers_buf.len };
}
this.response_buffer = try MutableString.init(allocator, 0);
this.allocator = allocator;
const url = URL.parse(this.url_buf);
this.http = AsyncHTTP.init(allocator, .GET, url, header_builder.entries, header_builder.content.ptr.?[0..header_builder.content.len], &this.response_buffer, "", this.getCompletionCallback(), HTTP.FetchRedirect.follow, .{
.http_proxy = this.package_manager.httpProxy(url),
});
this.http.client.flags.reject_unauthorized = this.package_manager.tlsRejectUnauthorized();
if (PackageManager.verbose_install) {
this.http.client.verbose = .headers;
}
this.callback = .{
.package_manifest = .{
.name = try strings.StringOrTinyString.initAppendIfNeeded(name, *FileSystem.FilenameStore, FileSystem.FilenameStore.instance),
.loaded_manifest = if (loaded_manifest) |manifest| manifest.* else null,
},
};
if (PackageManager.verbose_install) {
this.http.verbose = .headers;
this.http.client.verbose = .headers;
}
// Incase the ETag causes invalidation, we fallback to the last modified date.
if (last_modified.len != 0 and bun.getRuntimeFeatureFlag("BUN_FEATURE_FLAG_LAST_MODIFIED_PRETEND_304")) {
this.http.client.flags.force_last_modified = true;
this.http.client.if_modified_since = last_modified;
}
}
pub fn getCompletionCallback(this: *NetworkTask) HTTP.HTTPClientResult.Callback {
return HTTP.HTTPClientResult.Callback.New(*NetworkTask, notify).init(this);
}
pub fn schedule(this: *NetworkTask, batch: *ThreadPool.Batch) void {
this.http.schedule(this.allocator, batch);
}
pub fn forTarball(
this: *NetworkTask,
allocator: std.mem.Allocator,
tarball_: *const ExtractTarball,
scope: *const Npm.Registry.Scope,
authorization: NetworkTask.Authorization,
) !void {
this.callback = .{ .extract = tarball_.* };
const tarball = &this.callback.extract;
const tarball_url = tarball.url.slice();
if (tarball_url.len == 0) {
this.url_buf = try ExtractTarball.buildURL(
scope.url.href,
tarball.name,
tarball.resolution.value.npm.version,
this.package_manager.lockfile.buffers.string_bytes.items,
);
} else {
this.url_buf = tarball_url;
}
if (!(strings.hasPrefixComptime(this.url_buf, "https://") or strings.hasPrefixComptime(this.url_buf, "http://"))) {
const msg = .{
.fmt = "Expected tarball URL to start with https:// or http://, got {} while fetching package {}",
.args = .{ bun.fmt.QuotedFormatter{ .text = this.url_buf }, bun.fmt.QuotedFormatter{ .text = tarball.name.slice() } },
};
this.package_manager.log.addErrorFmt(null, .{}, allocator, msg.fmt, msg.args) catch unreachable;
return error.InvalidURL;
}
this.response_buffer = try MutableString.init(allocator, 0);
this.allocator = allocator;
var header_builder = HeaderBuilder{};
var header_buf: string = "";
if (authorization == .allow_authorization) {
countAuth(&header_builder, scope);
}
if (header_builder.header_count > 0) {
try header_builder.allocate(allocator);
if (authorization == .allow_authorization) {
appendAuth(&header_builder, scope);
}
header_buf = header_builder.content.ptr.?[0..header_builder.content.len];
}
const url = URL.parse(this.url_buf);
this.http = AsyncHTTP.init(allocator, .GET, url, header_builder.entries, header_buf, &this.response_buffer, "", this.getCompletionCallback(), HTTP.FetchRedirect.follow, .{
.http_proxy = this.package_manager.httpProxy(url),
});
this.http.client.flags.reject_unauthorized = this.package_manager.tlsRejectUnauthorized();
if (PackageManager.verbose_install) {
this.http.client.verbose = .headers;
}
}
};
pub const Origin = enum(u8) {
local = 0,
npm = 1,
tarball = 2,
};
pub const Features = struct {
dependencies: bool = true,
dev_dependencies: bool = false,
is_main: bool = false,
optional_dependencies: bool = false,
peer_dependencies: bool = true,
trusted_dependencies: bool = false,
workspaces: bool = false,
patched_dependencies: bool = false,
check_for_duplicate_dependencies: bool = false,
pub fn behavior(this: Features) Behavior {
var out: u8 = 0;
out |= @as(u8, @intFromBool(this.dependencies)) << 1;
out |= @as(u8, @intFromBool(this.optional_dependencies)) << 2;
out |= @as(u8, @intFromBool(this.dev_dependencies)) << 3;
out |= @as(u8, @intFromBool(this.peer_dependencies)) << 4;
out |= @as(u8, @intFromBool(this.workspaces)) << 5;
return @as(Behavior, @enumFromInt(out));
}
pub const main = Features{
.check_for_duplicate_dependencies = true,
.dev_dependencies = true,
.is_main = true,
.optional_dependencies = true,
.trusted_dependencies = true,
.patched_dependencies = true,
.workspaces = true,
};
pub const folder = Features{
.dev_dependencies = true,
.optional_dependencies = true,
};
pub const workspace = Features{
.dev_dependencies = true,
.optional_dependencies = true,
.trusted_dependencies = true,
};
pub const link = Features{
.dependencies = false,
.peer_dependencies = false,
};
pub const npm = Features{
.optional_dependencies = true,
};
pub const tarball = npm;
pub const npm_manifest = Features{
.optional_dependencies = true,
};
};
pub const PreinstallState = enum(u4) {
unknown = 0,
done,
extract,
extracting,
calc_patch_hash,
calcing_patch_hash,
apply_patch,
applying_patch,
};
/// Schedule long-running callbacks for a task
/// Slow stuff is broken into tasks, each can run independently without locks
pub const Task = struct {
tag: Tag,
request: Request,
data: Data,
status: Status = Status.waiting,
threadpool_task: ThreadPool.Task = ThreadPool.Task{ .callback = &callback },
log: logger.Log,
id: u64,
err: ?anyerror = null,
package_manager: *PackageManager,
apply_patch_task: ?*PatchTask = null,
next: ?*Task = null,
/// An ID that lets us register a callback without keeping the same pointer around
pub fn NewID(comptime Hasher: type, comptime IDType: type) type {
return struct {
pub const Type = IDType;
pub fn forNPMPackage(package_name: string, package_version: Semver.Version) IDType {
var hasher = Hasher.init(0);
hasher.update("npm-package:");
hasher.update(package_name);
hasher.update("@");
hasher.update(std.mem.asBytes(&package_version));
return hasher.final();
}
pub fn forBinLink(package_id: PackageID) IDType {
var hasher = Hasher.init(0);
hasher.update("bin-link:");
hasher.update(std.mem.asBytes(&package_id));
return hasher.final();
}
pub fn forManifest(name: string) IDType {
var hasher = Hasher.init(0);
hasher.update("manifest:");
hasher.update(name);
return hasher.final();
}
pub fn forTarball(url: string) IDType {
var hasher = Hasher.init(0);
hasher.update("tarball:");
hasher.update(url);
return hasher.final();
}
// These cannot change:
// We persist them to the filesystem.
pub fn forGitClone(url: string) IDType {
var hasher = Hasher.init(0);
hasher.update(url);
return @as(u64, 4 << 61) | @as(u64, @as(u61, @truncate(hasher.final())));
}
pub fn forGitCheckout(url: string, resolved: string) IDType {
var hasher = Hasher.init(0);
hasher.update(url);
hasher.update("@");
hasher.update(resolved);
return @as(u64, 5 << 61) | @as(u64, @as(u61, @truncate(hasher.final())));
}
};
}
pub const Id = NewID(bun.Wyhash11, u64);
pub fn callback(task: *ThreadPool.Task) void {
Output.Source.configureThread();
defer Output.flush();
var this: *Task = @fieldParentPtr("threadpool_task", task);
const manager = this.package_manager;
defer {
if (this.status == .success) {
if (this.apply_patch_task) |pt| {
defer pt.deinit();
pt.apply() catch bun.outOfMemory();
if (pt.callback.apply.logger.errors > 0) {
defer pt.callback.apply.logger.deinit();
// this.log.addErrorFmt(null, logger.Loc.Empty, bun.default_allocator, "failed to apply patch: {}", .{e}) catch unreachable;
pt.callback.apply.logger.print(Output.writer()) catch {};
}
}
}
manager.resolve_tasks.push(this);
manager.wake();
}
switch (this.tag) {
.package_manifest => {
const allocator = bun.default_allocator;
var manifest = &this.request.package_manifest;
const body = manifest.network.response_buffer.move();
defer {
bun.default_allocator.free(body);
}
const package_manifest = Npm.Registry.getPackageMetadata(
allocator,
manager.scopeForPackageName(manifest.name.slice()),
manifest.network.http.response.?,
body,
&this.log,
manifest.name.slice(),
manifest.network.callback.package_manifest.loaded_manifest,
manager,
) catch |err| {
bun.handleErrorReturnTrace(err, @errorReturnTrace());
this.err = err;
this.status = Status.fail;
this.data = .{ .package_manifest = .{} };
return;
};
switch (package_manifest) {
.fresh, .cached => |result| {
this.status = Status.success;
this.data = .{ .package_manifest = result };
return;
},
.not_found => {
this.log.addErrorFmt(null, logger.Loc.Empty, allocator, "404 - GET {s}", .{
this.request.package_manifest.name.slice(),
}) catch unreachable;
this.status = Status.fail;
this.data = .{ .package_manifest = .{} };
return;
},
}
},
.extract => {
const bytes = this.request.extract.network.response_buffer.move();
defer {
bun.default_allocator.free(bytes);
}
const result = this.request.extract.tarball.run(
bytes,
) catch |err| {
bun.handleErrorReturnTrace(err, @errorReturnTrace());
this.err = err;
this.status = Status.fail;
this.data = .{ .extract = .{} };
return;
};
this.data = .{ .extract = result };
this.status = Status.success;
},
.git_clone => {
const name = this.request.git_clone.name.slice();
const url = this.request.git_clone.url.slice();
var attempt: u8 = 1;
const dir = brk: {
if (Repository.tryHTTPS(url)) |https| break :brk Repository.download(
manager.allocator,
this.request.git_clone.env,
manager.log,
manager.getCacheDirectory(),
this.id,
name,
https,
attempt,
) catch |err| {
// Exit early if git checked and could
// not find the repository, skip ssh
if (err == error.RepositoryNotFound) {
this.err = err;
this.status = Status.fail;
this.data = .{ .git_clone = bun.invalid_fd };
return;
}
attempt += 1;
break :brk null;
};
break :brk null;
} orelse if (Repository.trySSH(url)) |ssh| Repository.download(
manager.allocator,
this.request.git_clone.env,
manager.log,
manager.getCacheDirectory(),
this.id,
name,
ssh,
attempt,
) catch |err| {
this.err = err;
this.status = Status.fail;
this.data = .{ .git_clone = bun.invalid_fd };
return;
} else {
return;
};
this.data = .{
.git_clone = bun.toFD(dir.fd),
};
this.status = Status.success;
},
.git_checkout => {
const git_checkout = &this.request.git_checkout;
const data = Repository.checkout(
manager.allocator,
this.request.git_checkout.env,
manager.log,
manager.getCacheDirectory(),
git_checkout.repo_dir.asDir(),
git_checkout.name.slice(),
git_checkout.url.slice(),
git_checkout.resolved.slice(),
) catch |err| {
this.err = err;
this.status = Status.fail;
this.data = .{ .git_checkout = .{} };
return;
};
this.data = .{
.git_checkout = data,
};
this.status = Status.success;
},
.local_tarball => {
const workspace_pkg_id = manager.lockfile.getWorkspacePkgIfWorkspaceDep(this.request.local_tarball.tarball.dependency_id);
var abs_buf: bun.PathBuffer = undefined;
const tarball_path, const normalize = if (workspace_pkg_id != invalid_package_id) tarball_path: {
const workspace_res = manager.lockfile.packages.items(.resolution)[workspace_pkg_id];
if (workspace_res.tag != .workspace) break :tarball_path .{ this.request.local_tarball.tarball.url.slice(), true };
// Construct an absolute path to the tarball.
// Normally tarball paths are always relative to the root directory, but if a
// workspace depends on a tarball path, it should be relative to the workspace.
const workspace_path = workspace_res.value.workspace.slice(manager.lockfile.buffers.string_bytes.items);
break :tarball_path .{
Path.joinAbsStringBuf(
FileSystem.instance.top_level_dir,
&abs_buf,
&[_][]const u8{
workspace_path,
this.request.local_tarball.tarball.url.slice(),
},
.auto,
),
false,
};
} else .{ this.request.local_tarball.tarball.url.slice(), true };
const result = readAndExtract(
manager.allocator,
&this.request.local_tarball.tarball,
tarball_path,
normalize,
) catch |err| {
bun.handleErrorReturnTrace(err, @errorReturnTrace());
this.err = err;
this.status = Status.fail;
this.data = .{ .extract = .{} };
return;
};
this.data = .{ .extract = result };
this.status = Status.success;
},
}
}
fn readAndExtract(
allocator: std.mem.Allocator,
tarball: *const ExtractTarball,
tarball_path: string,
normalize: bool,
) !ExtractData {
const bytes = if (normalize)
try File.readFromUserInput(std.fs.cwd(), tarball_path, allocator).unwrap()
else
try File.readFrom(bun.FD.cwd(), tarball_path, allocator).unwrap();
defer allocator.free(bytes);
return tarball.run(bytes);
}
pub const Tag = enum(u3) {
package_manifest = 0,
extract = 1,
git_clone = 2,
git_checkout = 3,
local_tarball = 4,
};
pub const Status = enum {
waiting,
success,
fail,
};
pub const Data = union {
package_manifest: Npm.PackageManifest,
extract: ExtractData,
git_clone: bun.FileDescriptor,
git_checkout: ExtractData,
};
pub const Request = union {
/// package name
// todo: Registry URL
package_manifest: struct {
name: strings.StringOrTinyString,
network: *NetworkTask,
},
extract: struct {
network: *NetworkTask,
tarball: ExtractTarball,
},
git_clone: struct {
name: strings.StringOrTinyString,
url: strings.StringOrTinyString,
env: DotEnv.Map,
},
git_checkout: struct {
repo_dir: bun.FileDescriptor,
dependency_id: DependencyID,
name: strings.StringOrTinyString,
url: strings.StringOrTinyString,
resolved: strings.StringOrTinyString,
resolution: Resolution,
env: DotEnv.Map,
},
local_tarball: struct {
tarball: ExtractTarball,
},
};
};
pub const ExtractData = struct {
url: string = "",
resolved: string = "",
json: ?struct {
path: string = "",
buf: []u8 = "",
} = null,
};
const PkgInstallKind = enum {
regular,
patch,
};
pub const PackageInstall = NewPackageInstall(.regular);
pub const PreparePatchPackageInstall = NewPackageInstall(.patch);
pub fn NewPackageInstall(comptime kind: PkgInstallKind) type {
const do_progress = kind != .patch;
const ProgressT = if (do_progress) *Progress else struct {};
return struct {
cache_dir: std.fs.Dir,
cache_dir_subpath: stringZ = "",
destination_dir_subpath: stringZ = "",
destination_dir_subpath_buf: []u8,
allocator: std.mem.Allocator,
progress: ProgressT,
package_name: string,
package_version: string,
patch: Patch = .{},
file_count: u32 = 0,
node_modules: *const PackageManager.NodeModulesFolder,
lockfile: *const Lockfile,
const ThisPackageInstall = @This();
const Patch = switch (kind) {