/
blob.zig
4543 lines (3935 loc) · 174 KB
/
blob.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
const std = @import("std");
const Api = @import("../../api/schema.zig").Api;
const bun = @import("root").bun;
const MimeType = http.MimeType;
const ZigURL = @import("../../url.zig").URL;
const http = @import("root").bun.http;
const JSC = @import("root").bun.JSC;
const js = JSC.C;
const io = bun.io;
const Method = @import("../../http/method.zig").Method;
const FetchHeaders = JSC.FetchHeaders;
const ObjectPool = @import("../../pool.zig").ObjectPool;
const SystemError = JSC.SystemError;
const Output = @import("root").bun.Output;
const MutableString = @import("root").bun.MutableString;
const strings = @import("root").bun.strings;
const string = @import("root").bun.string;
const default_allocator = @import("root").bun.default_allocator;
const FeatureFlags = @import("root").bun.FeatureFlags;
const ArrayBuffer = @import("../base.zig").ArrayBuffer;
const Properties = @import("../base.zig").Properties;
const getAllocator = @import("../base.zig").getAllocator;
const Environment = @import("../../env.zig");
const ZigString = JSC.ZigString;
const IdentityContext = @import("../../identity_context.zig").IdentityContext;
const JSPromise = JSC.JSPromise;
const JSValue = JSC.JSValue;
const JSError = JSC.JSError;
const JSGlobalObject = JSC.JSGlobalObject;
const NullableAllocator = @import("../../nullable_allocator.zig").NullableAllocator;
const VirtualMachine = JSC.VirtualMachine;
const Task = JSC.Task;
const JSPrinter = bun.js_printer;
const picohttp = @import("root").bun.picohttp;
const StringJoiner = @import("../../string_joiner.zig");
const uws = @import("root").bun.uws;
const invalid_fd = bun.invalid_fd;
const Response = JSC.WebCore.Response;
const Body = JSC.WebCore.Body;
const Request = JSC.WebCore.Request;
const libuv = bun.windows.libuv;
const PathOrBlob = union(enum) {
path: JSC.Node.PathOrFileDescriptor,
blob: Blob,
pub fn fromJSNoCopy(ctx: js.JSContextRef, args: *JSC.Node.ArgumentsSlice, exception: js.ExceptionRef) ?PathOrBlob {
if (JSC.Node.PathOrFileDescriptor.fromJS(ctx, args, bun.default_allocator, exception)) |path| {
return PathOrBlob{
.path = path,
};
}
const arg = args.nextEat() orelse return null;
if (arg.as(Blob)) |blob| {
return PathOrBlob{
.blob = blob.*,
};
}
return null;
}
};
const WriteFilePromise = @import("./blob/WriteFile.zig").WriteFilePromise;
const WriteFileWaitFromLockedValueTask = @import("./blob/WriteFile.zig").WriteFileWaitFromLockedValueTask;
const NewReadFileHandler = @import("./blob/ReadFile.zig").NewReadFileHandler;
const WriteFile = @import("./blob/WriteFile.zig").WriteFile;
const ReadFile = @import("./blob/ReadFile.zig").ReadFile;
const WriteFileWindows = @import("./blob/WriteFile.zig").WriteFileWindows;
pub const Blob = struct {
const bloblog = Output.scoped(.Blob, false);
pub usingnamespace JSC.Codegen.JSBlob;
pub usingnamespace @import("./blob/WriteFile.zig");
pub usingnamespace @import("./blob/ReadFile.zig");
pub const ClosingState = enum(u8) {
running,
closing,
};
reported_estimated_size: usize = 0,
size: SizeType = 0,
offset: SizeType = 0,
/// When set, the blob will be freed on finalization callbacks
/// If the blob is contained in Response or Request, this must be null
allocator: ?std.mem.Allocator = null,
store: ?*Store = null,
content_type: string = "",
content_type_allocated: bool = false,
content_type_was_set: bool = false,
/// JavaScriptCore strings are either latin1 or UTF-16
/// When UTF-16, they're nearly always due to non-ascii characters
is_all_ascii: ?bool = null,
/// Was it created via file constructor?
is_jsdom_file: bool = false,
globalThis: *JSGlobalObject = undefined,
last_modified: f64 = 0.0,
/// Max int of double precision
/// 9 petabytes is probably enough for awhile
/// We want to avoid coercing to a BigInt because that's a heap allocation
/// and it's generally just harder to use
pub const SizeType = u52;
pub const max_size = std.math.maxInt(SizeType);
const serialization_version: u8 = 1;
const reserved_space_for_serialization: u32 = 128;
pub fn getFormDataEncoding(this: *Blob) ?*bun.FormData.AsyncFormData {
var content_type_slice: ZigString.Slice = this.getContentType() orelse return null;
defer content_type_slice.deinit();
const encoding = bun.FormData.Encoding.get(content_type_slice.slice()) orelse return null;
return bun.FormData.AsyncFormData.init(this.allocator orelse bun.default_allocator, encoding) catch unreachable;
}
pub fn hasContentTypeFromUser(this: *const Blob) bool {
return this.content_type_was_set or (this.store != null and this.store.?.data == .file);
}
pub fn isBunFile(this: *const Blob) bool {
const store = this.store orelse return false;
return store.data == .file;
}
const ReadFileUV = @import("./blob/ReadFile.zig").ReadFileUV;
pub fn doReadFile(this: *Blob, comptime Function: anytype, global: *JSGlobalObject) JSValue {
bloblog("doReadFile", .{});
const Handler = NewReadFileHandler(Function);
var handler = bun.new(Handler, .{
.context = this.*,
.globalThis = global,
});
if (Environment.isWindows) {
var promise = JSPromise.create(global);
const promise_value = promise.asValue(global);
promise_value.ensureStillAlive();
handler.promise.strong.set(global, promise_value);
ReadFileUV.start(handler.globalThis.bunVM().uvLoop(), this.store.?, this.offset, this.size, Handler, handler);
return promise_value;
}
const file_read = ReadFile.create(
bun.default_allocator,
this.store.?,
this.offset,
this.size,
*Handler,
handler,
Handler.run,
) catch unreachable;
var read_file_task = ReadFile.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch unreachable;
// Create the Promise only after the store has been ref()'d.
// The garbage collector runs on memory allocations
// The JSPromise is the next GC'd memory allocation.
// This shouldn't really fix anything, but it's a little safer.
var promise = JSPromise.create(global);
const promise_value = promise.asValue(global);
promise_value.ensureStillAlive();
handler.promise.strong.set(global, promise_value);
read_file_task.schedule();
bloblog("doReadFile: read_file_task scheduled", .{});
return promise_value;
}
pub fn NewInternalReadFileHandler(comptime Context: type, comptime Function: anytype) type {
return struct {
pub fn run(handler: *anyopaque, bytes_: ReadFile.ResultType) void {
Function(bun.cast(Context, handler), bytes_);
}
};
}
pub fn doReadFileInternal(this: *Blob, comptime Handler: type, ctx: Handler, comptime Function: anytype, global: *JSGlobalObject) void {
if (Environment.isWindows) {
const ReadFileHandler = NewInternalReadFileHandler(Handler, Function);
return ReadFileUV.start(libuv.Loop.get(), this.store.?, this.offset, this.size, ReadFileHandler, ctx);
}
const file_read = ReadFile.createWithCtx(
bun.default_allocator,
this.store.?,
ctx,
NewInternalReadFileHandler(Handler, Function).run,
this.offset,
this.size,
) catch unreachable;
var read_file_task = ReadFile.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch unreachable;
read_file_task.schedule();
}
const FormDataContext = struct {
allocator: std.mem.Allocator,
joiner: StringJoiner,
boundary: []const u8,
failed: bool = false,
globalThis: *JSC.JSGlobalObject,
pub fn onEntry(this: *FormDataContext, name: ZigString, entry: JSC.DOMFormData.FormDataEntry) void {
if (this.failed) return;
var globalThis = this.globalThis;
const allocator = this.allocator;
const joiner = &this.joiner;
const boundary = this.boundary;
joiner.append("--", 0, null);
joiner.append(boundary, 0, null);
joiner.append("\r\n", 0, null);
joiner.append("Content-Disposition: form-data; name=\"", 0, null);
const name_slice = name.toSlice(allocator);
joiner.append(name_slice.slice(), 0, name_slice.allocator.get());
name_slice.deinit();
switch (entry) {
.string => |value| {
joiner.append("\"\r\n\r\n", 0, null);
const value_slice = value.toSlice(allocator);
joiner.append(value_slice.slice(), 0, value_slice.allocator.get());
},
.file => |value| {
joiner.append("\"; filename=\"", 0, null);
const filename_slice = value.filename.toSlice(allocator);
joiner.append(filename_slice.slice(), 0, filename_slice.allocator.get());
filename_slice.deinit();
joiner.append("\"\r\n", 0, null);
const blob = value.blob;
const content_type = if (blob.content_type.len > 0) blob.content_type else "application/octet-stream";
joiner.append("Content-Type: ", 0, null);
joiner.append(content_type, 0, null);
joiner.append("\r\n\r\n", 0, null);
if (blob.store) |store| {
blob.resolveSize();
switch (store.data) {
.file => |file| {
// TODO: make this async + lazy
const res = JSC.Node.NodeFS.readFile(
globalThis.bunVM().nodeFS(),
.{
.encoding = .buffer,
.path = file.pathlike,
.offset = blob.offset,
.max_size = blob.size,
},
.sync,
);
switch (res) {
.err => |err| {
globalThis.throwValue(err.toJSC(globalThis));
this.failed = true;
},
.result => |result| {
joiner.append(result.slice(), 0, result.buffer.allocator);
},
}
},
.bytes => |_| {
joiner.append(blob.sharedView(), 0, null);
},
}
}
},
}
joiner.append("\r\n", 0, null);
}
};
pub fn getContentType(
this: *Blob,
) ?ZigString.Slice {
if (this.content_type.len > 0)
return ZigString.Slice.fromUTF8NeverFree(this.content_type);
return null;
}
const StructuredCloneWriter = struct {
ctx: *anyopaque,
impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(.C) void,
pub const WriteError = error{};
pub fn write(this: StructuredCloneWriter, bytes: []const u8) WriteError!usize {
this.impl(this.ctx, bytes.ptr, @as(u32, @truncate(bytes.len)));
return bytes.len;
}
};
fn _onStructuredCloneSerialize(
this: *Blob,
comptime Writer: type,
writer: Writer,
) !void {
try writer.writeInt(u8, serialization_version, .little);
try writer.writeInt(u64, @as(u64, @intCast(this.offset)), .little);
try writer.writeInt(u32, @as(u32, @truncate(this.content_type.len)), .little);
_ = try writer.write(this.content_type);
try writer.writeInt(u8, @intFromBool(this.content_type_was_set), .little);
const store_tag: Store.SerializeTag = if (this.store) |store|
if (store.data == .file) .file else .bytes
else
.empty;
try writer.writeInt(u8, @intFromEnum(store_tag), .little);
this.resolveSize();
if (this.store) |store| {
try store.serialize(Writer, writer);
}
// reserved space for future use
_ = try writer.write(&[_]u8{0} ** reserved_space_for_serialization);
}
pub fn onStructuredCloneSerialize(
this: *Blob,
globalThis: *JSC.JSGlobalObject,
ctx: *anyopaque,
writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(.C) void,
) callconv(.C) void {
_ = globalThis;
const Writer = std.io.Writer(StructuredCloneWriter, StructuredCloneWriter.WriteError, StructuredCloneWriter.write);
const writer = Writer{
.context = .{
.ctx = ctx,
.impl = writeBytes,
},
};
_onStructuredCloneSerialize(this, Writer, writer) catch return .zero;
}
pub fn onStructuredCloneTransfer(
this: *Blob,
globalThis: *JSC.JSGlobalObject,
ctx: *anyopaque,
write: *const fn (*anyopaque, ptr: [*]const u8, len: usize) callconv(.C) void,
) callconv(.C) void {
_ = write;
_ = ctx;
_ = this;
_ = globalThis;
}
fn readSlice(
reader: anytype,
len: usize,
allocator: std.mem.Allocator,
) ![]u8 {
var slice = try allocator.alloc(u8, len);
slice = slice[0..try reader.read(slice)];
if (slice.len != len) return error.TooSmall;
return slice;
}
fn _onStructuredCloneDeserialize(
globalThis: *JSC.JSGlobalObject,
comptime Reader: type,
reader: Reader,
) !JSValue {
const allocator = bun.default_allocator;
const version = try reader.readInt(u8, .little);
_ = version;
const offset = try reader.readInt(u64, .little);
const content_type_len = try reader.readInt(u32, .little);
const content_type = try readSlice(reader, content_type_len, allocator);
const content_type_was_set: bool = try reader.readInt(u8, .little) != 0;
const store_tag = try reader.readEnum(Store.SerializeTag, .little);
const blob: *Blob = switch (store_tag) {
.bytes => brk: {
const bytes_len = try reader.readInt(u32, .little);
const bytes = try readSlice(reader, bytes_len, allocator);
const blob = Blob.init(bytes, allocator, globalThis);
const blob_ = bun.new(Blob, blob);
break :brk blob_;
},
.file => brk: {
const pathlike_tag = try reader.readEnum(JSC.Node.PathOrFileDescriptor.SerializeTag, .little);
switch (pathlike_tag) {
.fd => {
const fd = try bun.FileDescriptor.readFrom(reader, .little);
var path_or_fd = JSC.Node.PathOrFileDescriptor{
.fd = fd,
};
const blob = bun.new(Blob, Blob.findOrCreateFileFromPath(
&path_or_fd,
globalThis,
));
break :brk blob;
},
.path => {
const path_len = try reader.readInt(u32, .little);
const path = try readSlice(reader, path_len, default_allocator);
var dest = JSC.Node.PathOrFileDescriptor{
.path = .{
.string = bun.PathString.init(path),
},
};
const blob = bun.new(Blob, Blob.findOrCreateFileFromPath(
&dest,
globalThis,
));
break :brk blob;
},
}
return .zero;
},
.empty => brk: {
break :brk bun.new(Blob, Blob.initEmpty(globalThis));
},
};
blob.allocator = allocator;
blob.offset = @as(u52, @intCast(offset));
if (content_type.len > 0) {
blob.content_type = content_type;
blob.content_type_allocated = true;
blob.content_type_was_set = content_type_was_set;
}
return blob.toJS(globalThis);
}
pub fn onStructuredCloneDeserialize(
globalThis: *JSC.JSGlobalObject,
ptr: [*]u8,
end: [*]u8,
) callconv(.C) JSValue {
const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr);
var buffer_stream = std.io.fixedBufferStream(ptr[0..total_length]);
const reader = buffer_stream.reader();
const blob = _onStructuredCloneDeserialize(globalThis, @TypeOf(reader), reader) catch return .zero;
if (Environment.allow_assert) {
std.debug.assert(total_length - reader.context.pos == reserved_space_for_serialization);
}
return blob;
}
const URLSearchParamsConverter = struct {
allocator: std.mem.Allocator,
buf: []u8 = "",
globalThis: *JSC.JSGlobalObject,
pub fn convert(this: *URLSearchParamsConverter, str: ZigString) void {
var out = str.toSlice(this.allocator).cloneIfNeeded(this.allocator) catch unreachable;
this.buf = @constCast(out.slice());
}
};
pub fn fromURLSearchParams(
globalThis: *JSC.JSGlobalObject,
allocator: std.mem.Allocator,
search_params: *JSC.URLSearchParams,
) Blob {
var converter = URLSearchParamsConverter{
.allocator = allocator,
.globalThis = globalThis,
};
search_params.toString(URLSearchParamsConverter, &converter, URLSearchParamsConverter.convert);
var store = Blob.Store.init(converter.buf, allocator) catch unreachable;
store.mime_type = MimeType.all.@"application/x-www-form-urlencoded";
var blob = Blob.initWithStore(store, globalThis);
blob.content_type = store.mime_type.value;
blob.content_type_was_set = true;
return blob;
}
pub fn fromDOMFormData(
globalThis: *JSC.JSGlobalObject,
allocator: std.mem.Allocator,
form_data: *JSC.DOMFormData,
) Blob {
var arena = @import("root").bun.ArenaAllocator.init(allocator);
defer arena.deinit();
var stack_allocator = std.heap.stackFallback(1024, arena.allocator());
const stack_mem_all = stack_allocator.get();
var hex_buf: [70]u8 = undefined;
const boundary = brk: {
var random = globalThis.bunVM().rareData().nextUUID().bytes;
const formatter = std.fmt.fmtSliceHexLower(&random);
break :brk std.fmt.bufPrint(&hex_buf, "-WebkitFormBoundary{any}", .{formatter}) catch unreachable;
};
var context = FormDataContext{
.allocator = allocator,
.joiner = StringJoiner{ .use_pool = false, .node_allocator = stack_mem_all },
.boundary = boundary,
.globalThis = globalThis,
};
form_data.forEach(FormDataContext, &context, FormDataContext.onEntry);
if (context.failed) {
return Blob.initEmpty(globalThis);
}
context.joiner.append("--", 0, null);
context.joiner.append(boundary, 0, null);
context.joiner.append("--\r\n", 0, null);
const store = Blob.Store.init(context.joiner.done(allocator) catch unreachable, allocator) catch unreachable;
var blob = Blob.initWithStore(store, globalThis);
blob.content_type = std.fmt.allocPrint(allocator, "multipart/form-data; boundary=\"{s}\"", .{boundary}) catch unreachable;
blob.content_type_allocated = true;
blob.content_type_was_set = true;
return blob;
}
pub fn contentType(this: *const Blob) string {
return this.content_type;
}
pub fn isDetached(this: *const Blob) bool {
return this.store == null;
}
export fn Blob__dupeFromJS(value: JSC.JSValue) ?*Blob {
const this = Blob.fromJS(value) orelse return null;
return Blob__dupe(this);
}
export fn Blob__setAsFile(this: *Blob, path_str: *bun.String) *Blob {
this.is_jsdom_file = true;
// This is not 100% correct...
if (this.store) |store| {
if (store.data == .bytes) {
if (store.data.bytes.stored_name.len == 0) {
var utf8 = path_str.toUTF8WithoutRef(bun.default_allocator).clone(bun.default_allocator) catch unreachable;
store.data.bytes.stored_name = bun.PathString.init(utf8.slice());
}
}
}
return this;
}
export fn Blob__dupe(ptr: *anyopaque) *Blob {
var this = bun.cast(*Blob, ptr);
var new = bun.new(Blob, this.dupeWithContentType(true));
new.allocator = bun.default_allocator;
return new;
}
export fn Blob__destroy(this: *Blob) void {
this.finalize();
}
export fn Blob__getFileNameString(this: *Blob) callconv(.C) bun.String {
if (this.getFileName()) |filename| {
return bun.String.fromBytes(filename);
}
return bun.String.empty;
}
comptime {
_ = Blob__dupeFromJS;
_ = Blob__destroy;
_ = Blob__dupe;
_ = Blob__setAsFile;
_ = Blob__getFileNameString;
}
pub fn writeFormatForSize(size: usize, writer: anytype, comptime enable_ansi_colors: bool) !void {
try writer.writeAll(comptime Output.prettyFmt("<r>Blob<r>", enable_ansi_colors));
try writer.print(
comptime Output.prettyFmt(" (<yellow>{any}<r>)", enable_ansi_colors),
.{
bun.fmt.size(size),
},
);
}
pub fn writeFormat(this: *const Blob, comptime Formatter: type, formatter: *Formatter, writer: anytype, comptime enable_ansi_colors: bool) !void {
const Writer = @TypeOf(writer);
if (this.isDetached()) {
try writer.writeAll(comptime Output.prettyFmt("<d>[<r>Blob<r> detached<d>]<r>", enable_ansi_colors));
return;
}
{
const store = this.store.?;
switch (store.data) {
.file => |file| {
try writer.writeAll(comptime Output.prettyFmt("<r>FileRef<r>", enable_ansi_colors));
switch (file.pathlike) {
.path => |path| {
try writer.print(
comptime Output.prettyFmt(" (<green>\"{s}\"<r>)<r>", enable_ansi_colors),
.{
path.slice(),
},
);
},
.fd => |fd| {
const fd_impl = bun.FDImpl.decode(fd);
if (comptime Environment.isWindows) {
if (fd_impl.kind == .uv) {
try writer.print(
comptime Output.prettyFmt(" (<r>fd: <yellow>{d}<r>)<r>", enable_ansi_colors),
.{fd_impl.uv()},
);
} else {
if (Environment.allow_assert) {
comptime std.debug.assert(Environment.isWindows);
@panic("this shouldn't be reachable.");
}
try writer.print(
comptime Output.prettyFmt(" (<r>fd: <yellow>{any}<r>)<r>", enable_ansi_colors),
.{fd_impl.system()},
);
}
} else {
try writer.print(
comptime Output.prettyFmt(" (<r>fd: <yellow>{d}<r>)<r>", enable_ansi_colors),
.{fd_impl.system()},
);
}
},
}
},
.bytes => {
try writeFormatForSize(this.size, writer, enable_ansi_colors);
},
}
}
if (this.content_type.len > 0 or this.offset > 0) {
try writer.writeAll(" {\n");
{
formatter.indent += 1;
defer formatter.indent -= 1;
if (this.content_type.len > 0) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("type: <green>\"{s}\"<r>", enable_ansi_colors),
.{
this.content_type,
},
);
if (this.offset > 0) {
formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable;
}
try writer.writeAll("\n");
}
if (this.offset > 0) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("offset: <yellow>{d}<r>\n", enable_ansi_colors),
.{
this.offset,
},
);
}
}
try formatter.writeIndent(Writer, writer);
try writer.writeAll("}");
}
}
const Retry = enum { @"continue", fail, no };
// we choose not to inline this so that the path buffer is not on the stack unless necessary.
noinline fn mkdirIfNotExists(this: anytype, err: bun.sys.Error, path_string: [:0]const u8, err_path: []const u8) Retry {
if (err.getErrno() == .NOENT and this.mkdirp_if_not_exists) {
if (std.fs.path.dirname(path_string)) |dirname| {
var node_fs: JSC.Node.NodeFS = .{};
switch (node_fs.mkdirRecursive(
JSC.Node.Arguments.Mkdir{
.path = .{ .string = bun.PathString.init(dirname) },
.recursive = true,
.always_return_none = true,
},
.sync,
)) {
.result => {
this.mkdirp_if_not_exists = false;
return .@"continue";
},
.err => |err2| {
if (comptime @hasField(@TypeOf(this.*), "errno")) {
this.errno = bun.errnoToZigErr(err2.errno);
}
this.system_error = err.withPath(err_path).toSystemError();
if (comptime @hasField(@TypeOf(this.*), "opened_fd")) {
this.opened_fd = invalid_fd;
}
return .fail;
},
}
}
}
return .no;
}
pub fn writeFileWithSourceDestination(
ctx: JSC.C.JSContextRef,
source_blob: *Blob,
destination_blob: *Blob,
mkdirp_if_not_exists: bool,
) JSC.JSValue {
const destination_type = std.meta.activeTag(destination_blob.store.?.data);
// Writing an empty string to a file truncates it
// This matches the behavior we do with the fast path.
// This case only really happens on Windows.
if (source_blob.store == null) {
defer destination_blob.detach();
if (destination_type == .file) {
// TODO: make this async
// TODO: mkdirp()
var result = ctx.bunVM().nodeFS().truncate(.{
.path = destination_blob.store.?.data.file.pathlike,
.len = 0,
.flags = std.os.O.CREAT,
}, .sync);
if (result == .err) {
// it might return EPERM when the parent directory doesn't exist
// #6336
if (result.err.getErrno() == .PERM) {
result.err.errno = @intCast(@intFromEnum(bun.C.E.NOENT));
}
result.err = result.err.withPathLike(destination_blob.store.?.data.file.pathlike);
return JSC.JSPromise.rejectedPromiseValue(ctx, result.toJS(ctx));
}
}
return JSC.JSPromise.resolvedPromiseValue(ctx.ptr(), JSC.JSValue.jsNumber(0));
}
const source_type = std.meta.activeTag(source_blob.store.?.data);
if (destination_type == .file and source_type == .bytes) {
var write_file_promise = bun.new(WriteFilePromise, .{
.globalThis = ctx,
});
if (comptime Environment.isWindows) {
var promise = JSPromise.create(ctx.ptr());
const promise_value = promise.asValue(ctx);
promise_value.ensureStillAlive();
write_file_promise.promise.strong.set(ctx, promise_value);
_ = WriteFileWindows.create(
ctx.bunVM().eventLoop(),
destination_blob.*,
source_blob.*,
*WriteFilePromise,
write_file_promise,
&WriteFilePromise.run,
mkdirp_if_not_exists,
);
return promise_value;
}
const file_copier = WriteFile.create(
destination_blob.*,
source_blob.*,
*WriteFilePromise,
write_file_promise,
WriteFilePromise.run,
mkdirp_if_not_exists,
) catch unreachable;
var task = WriteFile.WriteFileTask.createOnJSThread(bun.default_allocator, ctx.ptr(), file_copier) catch unreachable;
// Defer promise creation until we're just about to schedule the task
var promise = JSC.JSPromise.create(ctx.ptr());
const promise_value = promise.asValue(ctx);
write_file_promise.promise.strong.set(ctx, promise_value);
promise_value.ensureStillAlive();
task.schedule();
return promise_value;
}
// If this is file <> file, we can just copy the file
else if (destination_type == .file and source_type == .file) {
if (comptime Environment.isWindows) {
var copier = Store.CopyFileWindows.init(
destination_blob.store.?,
source_blob.store.?,
ctx.bunVM().eventLoop(),
mkdirp_if_not_exists,
destination_blob.size,
);
return copier.promise.value();
}
var file_copier = Store.CopyFile.create(
bun.default_allocator,
destination_blob.store.?,
source_blob.store.?,
destination_blob.offset,
destination_blob.size,
ctx.ptr(),
mkdirp_if_not_exists,
) catch unreachable;
file_copier.schedule();
return file_copier.promise.value();
} else if (destination_type == .bytes and source_type == .bytes) {
// If this is bytes <> bytes, we can just duplicate it
// this is an edgecase
// it will happen if someone did Bun.write(new Blob([123]), new Blob([456]))
// eventually, this could be like Buffer.concat
var clone = source_blob.dupe();
clone.allocator = bun.default_allocator;
const cloned = bun.new(Blob, clone);
cloned.allocator = bun.default_allocator;
return JSPromise.resolvedPromiseValue(ctx.ptr(), cloned.toJS(ctx));
} else if (destination_type == .bytes and source_type == .file) {
var fake_call_frame: [8]JSC.JSValue = undefined;
@memset(@as([*]u8, @ptrCast(&fake_call_frame))[0..@sizeOf(@TypeOf(fake_call_frame))], 0);
const blob_value =
source_blob.getSlice(ctx, @as(*JSC.CallFrame, @ptrCast(&fake_call_frame)));
return JSPromise.resolvedPromiseValue(
ctx.ptr(),
blob_value,
);
}
unreachable;
}
pub fn writeFile(
globalThis: *JSC.JSGlobalObject,
callframe: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
const arguments = callframe.arguments(3).slice();
var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments);
defer args.deinit();
var exception_ = [1]JSC.JSValueRef{null};
var exception = &exception_;
// accept a path or a blob
var path_or_blob = PathOrBlob.fromJSNoCopy(globalThis, &args, exception) orelse {
if (exception[0] != null) {
globalThis.throwValue(exception[0].?.value());
} else {
globalThis.throwInvalidArguments("Bun.write expects a path, file descriptor or a blob", .{});
}
return .zero;
};
defer {
if (path_or_blob == .path) {
path_or_blob.path.deinit();
}
}
var data = args.nextEat() orelse {
globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{});
return .zero;
};
if (data.isEmptyOrUndefinedOrNull()) {
globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{});
return .zero;
}
if (path_or_blob == .blob) {
if (path_or_blob.blob.store == null) {
globalThis.throwInvalidArguments("Blob is detached", .{});
return .zero;
} else {
// TODO only reset last_modified on success pathes instead of
// resetting last_modified at the beginning for better performance.
if (path_or_blob.blob.store.?.data == .file) {
// reset last_modified to force getLastModified() to reload after writing.
path_or_blob.blob.store.?.data.file.last_modified = JSC.init_timestamp;
}
}
}
const input_store: ?*Store = if (path_or_blob == .blob) path_or_blob.blob.store else null;
if (input_store) |st| st.ref();
defer if (input_store) |st| st.deref();
var needs_async = false;
var mkdirp_if_not_exists: ?bool = null;
if (args.nextEat()) |options_object| {
if (options_object.isObject()) {
if (options_object.getTruthy(globalThis, "createPath")) |create_directory| {
if (!create_directory.isBoolean()) {
globalThis.throwInvalidArgumentType("write", "options.createPath", "boolean");
return .zero;
}
mkdirp_if_not_exists = create_directory.toBoolean();
}
} else if (!options_object.isEmptyOrUndefinedOrNull()) {
globalThis.throwInvalidArgumentType("write", "options", "object");
return .zero;
}
}
if (mkdirp_if_not_exists) |mkdir| {
if (mkdir and
path_or_blob == .blob and
path_or_blob.blob.store != null and
path_or_blob.blob.store.?.data == .file and
path_or_blob.blob.store.?.data.file.pathlike == .fd)
{
globalThis.throwInvalidArguments("Cannot create a directory for a file descriptor", .{});
return .zero;
}
}
// If you're doing Bun.write(), try to go fast by writing short input on the main thread.
// This is a heuristic, but it's a good one.
//
// except if you're on Windows. Windows I/O is slower. Let's not even try.
if (comptime !Environment.isWindows) {
if (path_or_blob == .path or
// If they try to set an offset, its a little more complicated so let's avoid that
(path_or_blob.blob.offset == 0 and
// Is this a file that is known to be a pipe? Let's avoid blocking the main thread on it.
!(path_or_blob.blob.store != null and
path_or_blob.blob.store.?.data == .file and
path_or_blob.blob.store.?.data.file.mode != 0 and
bun.isRegularFile(path_or_blob.blob.store.?.data.file.mode))))
{
if (data.isString()) {
const len = data.getLength(globalThis);
if (len < 256 * 1024) {
const str = data.toBunString(globalThis);
defer str.deref();
const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path)
path_or_blob.path
else
path_or_blob.blob.store.?.data.file.pathlike;
if (pathlike == .path) {
const result = writeStringToFileFast(
globalThis,
pathlike,
str,
&needs_async,
true,
);
if (!needs_async) {
return result;