forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.zig
2703 lines (2339 loc) · 85.2 KB
/
options.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
/// This file is mostly the API schema but with all the options normalized.
/// Normalization is necessary because most fields in the API schema are optional
const std = @import("std");
const logger = bun.logger;
const Fs = @import("fs.zig");
const resolver = @import("./resolver/resolver.zig");
const api = @import("./api/schema.zig");
const Api = api.Api;
const resolve_path = @import("./resolver/resolve_path.zig");
const URL = @import("./url.zig").URL;
const ConditionsMap = @import("./resolver/package_json.zig").ESModule.ConditionsMap;
const bun = @import("root").bun;
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 FileDescriptorType = bun.FileDescriptor;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const JSC = bun.JSC;
const Runtime = @import("./runtime.zig").Runtime;
const Analytics = @import("./analytics/analytics_thread.zig");
const MacroRemap = @import("./resolver/package_json.zig").MacroMap;
const DotEnv = @import("./env_loader.zig");
pub const defines = @import("./defines.zig");
pub const Define = defines.Define;
const assert = bun.assert;
pub const WriteDestination = enum {
stdout,
disk,
// eventually: wasm
};
pub fn validatePath(
log: *logger.Log,
_: *Fs.FileSystem.Implementation,
cwd: string,
rel_path: string,
allocator: std.mem.Allocator,
_: string,
) string {
if (rel_path.len == 0) {
return "";
}
const paths = [_]string{ cwd, rel_path };
// TODO: switch to getFdPath()-based implementation
const out = std.fs.path.resolve(allocator, &paths) catch |err| {
log.addErrorFmt(
null,
logger.Loc.Empty,
allocator,
"<r><red>{s}<r> resolving external: <b>\"{s}\"<r>",
.{ @errorName(err), rel_path },
) catch unreachable;
return "";
};
return out;
}
pub fn stringHashMapFromArrays(comptime t: type, allocator: std.mem.Allocator, keys: anytype, values: anytype) !t {
var hash_map = t.init(allocator);
if (keys.len > 0) {
try hash_map.ensureTotalCapacity(@as(u32, @intCast(keys.len)));
for (keys, 0..) |key, i| {
hash_map.putAssumeCapacity(key, values[i]);
}
}
return hash_map;
}
pub const ExternalModules = struct {
node_modules: std.BufSet = undefined,
abs_paths: std.BufSet = undefined,
patterns: []const WildcardPattern = undefined,
pub const WildcardPattern = struct {
prefix: string,
suffix: string,
};
pub fn isNodeBuiltin(str: string) bool {
return bun.JSC.HardcodedModule.Aliases.has(str, .node);
}
const default_wildcard_patterns = &[_]WildcardPattern{
.{
.prefix = "/bun:",
.suffix = "",
},
// .{
// .prefix = "/src:",
// .suffix = "",
// },
// .{
// .prefix = "/blob:",
// .suffix = "",
// },
};
pub fn init(
allocator: std.mem.Allocator,
fs: *Fs.FileSystem.Implementation,
cwd: string,
externals: []const string,
log: *logger.Log,
target: Target,
) ExternalModules {
var result = ExternalModules{
.node_modules = std.BufSet.init(allocator),
.abs_paths = std.BufSet.init(allocator),
.patterns = default_wildcard_patterns[0..],
};
switch (target) {
.node => {
// TODO: fix this stupid copy
result.node_modules.hash_map.ensureTotalCapacity(NodeBuiltinPatterns.len) catch unreachable;
for (NodeBuiltinPatterns) |pattern| {
result.node_modules.insert(pattern) catch unreachable;
}
},
.bun => {
// // TODO: fix this stupid copy
// result.node_modules.hash_map.ensureTotalCapacity(BunNodeBuiltinPatternsCompat.len) catch unreachable;
// for (BunNodeBuiltinPatternsCompat) |pattern| {
// result.node_modules.insert(pattern) catch unreachable;
// }
},
else => {},
}
if (externals.len == 0) {
return result;
}
var patterns = std.ArrayList(WildcardPattern).initCapacity(allocator, default_wildcard_patterns.len) catch unreachable;
patterns.appendSliceAssumeCapacity(default_wildcard_patterns[0..]);
for (externals) |external| {
const path = external;
if (strings.indexOfChar(path, '*')) |i| {
if (strings.indexOfChar(path[i + 1 .. path.len], '*') != null) {
log.addErrorFmt(null, logger.Loc.Empty, allocator, "External path \"{s}\" cannot have more than one \"*\" wildcard", .{external}) catch unreachable;
return result;
}
patterns.append(WildcardPattern{
.prefix = external[0..i],
.suffix = external[i + 1 .. external.len],
}) catch unreachable;
} else if (resolver.isPackagePath(external)) {
result.node_modules.insert(external) catch unreachable;
} else {
const normalized = validatePath(log, fs, cwd, external, allocator, "external path");
if (normalized.len > 0) {
result.abs_paths.insert(normalized) catch unreachable;
}
}
}
result.patterns = patterns.toOwnedSlice() catch @panic("TODO");
return result;
}
const NodeBuiltinPatternsRaw = [_]string{
"_http_agent",
"_http_client",
"_http_common",
"_http_incoming",
"_http_outgoing",
"_http_server",
"_stream_duplex",
"_stream_passthrough",
"_stream_readable",
"_stream_transform",
"_stream_wrap",
"_stream_writable",
"_tls_common",
"_tls_wrap",
"assert",
"async_hooks",
"buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"diagnostics_channel",
"dns",
"domain",
"events",
"fs",
"http",
"http2",
"https",
"inspector",
"module",
"net",
"os",
"path",
"perf_hooks",
"process",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"sys",
"timers",
"tls",
"trace_events",
"tty",
"url",
"util",
"v8",
"vm",
"wasi",
"worker_threads",
"zlib",
};
pub const NodeBuiltinPatterns = NodeBuiltinPatternsRaw ++ brk: {
var builtins = NodeBuiltinPatternsRaw;
for (&builtins) |*builtin| {
builtin.* = "node:" ++ builtin.*;
}
break :brk builtins;
};
pub const BunNodeBuiltinPatternsCompat = [_]string{
"_http_agent",
"_http_client",
"_http_common",
"_http_incoming",
"_http_outgoing",
"_http_server",
"_stream_duplex",
"_stream_passthrough",
"_stream_readable",
"_stream_transform",
"_stream_wrap",
"_stream_writable",
"_tls_common",
"_tls_wrap",
"assert",
"async_hooks",
// "buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"diagnostics_channel",
"dns",
"domain",
"events",
"http",
"http2",
"https",
"inspector",
"module",
"net",
"os",
// "path",
"perf_hooks",
// "process",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"sys",
"timers",
"tls",
"trace_events",
"tty",
"url",
"util",
"v8",
"vm",
"wasi",
"worker_threads",
"zlib",
};
pub const NodeBuiltinsMap = bun.ComptimeStringMap(void, .{
.{ "_http_agent", {} },
.{ "_http_client", {} },
.{ "_http_common", {} },
.{ "_http_incoming", {} },
.{ "_http_outgoing", {} },
.{ "_http_server", {} },
.{ "_stream_duplex", {} },
.{ "_stream_passthrough", {} },
.{ "_stream_readable", {} },
.{ "_stream_transform", {} },
.{ "_stream_wrap", {} },
.{ "_stream_writable", {} },
.{ "_tls_common", {} },
.{ "_tls_wrap", {} },
.{ "assert", {} },
.{ "async_hooks", {} },
.{ "buffer", {} },
.{ "child_process", {} },
.{ "cluster", {} },
.{ "console", {} },
.{ "constants", {} },
.{ "crypto", {} },
.{ "dgram", {} },
.{ "diagnostics_channel", {} },
.{ "dns", {} },
.{ "domain", {} },
.{ "events", {} },
.{ "fs", {} },
.{ "http", {} },
.{ "http2", {} },
.{ "https", {} },
.{ "inspector", {} },
.{ "module", {} },
.{ "net", {} },
.{ "os", {} },
.{ "path", {} },
.{ "perf_hooks", {} },
.{ "process", {} },
.{ "punycode", {} },
.{ "querystring", {} },
.{ "readline", {} },
.{ "repl", {} },
.{ "stream", {} },
.{ "string_decoder", {} },
.{ "sys", {} },
.{ "timers", {} },
.{ "tls", {} },
.{ "trace_events", {} },
.{ "tty", {} },
.{ "url", {} },
.{ "util", {} },
.{ "v8", {} },
.{ "vm", {} },
.{ "wasi", {} },
.{ "worker_threads", {} },
.{ "zlib", {} },
});
};
pub const BundlePackage = enum {
always,
never,
pub const Map = bun.StringArrayHashMapUnmanaged(BundlePackage);
};
pub const ModuleType = enum {
unknown,
cjs,
esm,
pub const List = bun.ComptimeStringMap(ModuleType, .{
.{ "commonjs", ModuleType.cjs },
.{ "module", ModuleType.esm },
});
};
pub const Target = enum {
browser,
bun,
bun_macro,
node,
/// This is used by bake.Framework.ServerComponents.separate_ssr_graph
bake_server_components_ssr,
pub const Map = bun.ComptimeStringMap(Target, .{
.{ "browser", .browser },
.{ "bun", .bun },
.{ "bun_macro", .bun_macro },
.{ "macro", .bun_macro },
.{ "node", .node },
});
pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Target {
if (!value.isString()) {
return global.throwInvalidArguments("target must be a string", .{});
}
return Map.fromJS(global, value);
}
pub fn toAPI(this: Target) Api.Target {
return switch (this) {
.node => .node,
.browser => .browser,
.bun, .bake_server_components_ssr => .bun,
.bun_macro => .bun_macro,
};
}
pub inline fn isServerSide(this: Target) bool {
return switch (this) {
.bun_macro, .node, .bun, .bake_server_components_ssr => true,
else => false,
};
}
pub inline fn isBun(this: Target) bool {
return switch (this) {
.bun_macro, .bun, .bake_server_components_ssr => true,
else => false,
};
}
pub inline fn isNode(this: Target) bool {
return switch (this) {
.node => true,
else => false,
};
}
pub inline fn processBrowserDefineValue(this: Target) ?string {
return switch (this) {
.browser => "true",
else => "false",
};
}
pub fn bakeGraph(target: Target) bun.bake.Graph {
return switch (target) {
.browser => .client,
.bake_server_components_ssr => .ssr,
.bun_macro, .bun, .node => .server,
};
}
pub fn outExtensions(target: Target, allocator: std.mem.Allocator) bun.StringHashMap(string) {
var exts = bun.StringHashMap(string).init(allocator);
const out_extensions_list = [_][]const u8{ ".js", ".cjs", ".mts", ".cts", ".ts", ".tsx", ".jsx", ".json" };
if (target == .node) {
exts.ensureTotalCapacity(out_extensions_list.len * 2) catch unreachable;
for (out_extensions_list) |ext| {
exts.put(ext, ".mjs") catch unreachable;
}
} else {
exts.ensureTotalCapacity(out_extensions_list.len + 1) catch unreachable;
exts.put(".mjs", ".js") catch unreachable;
}
for (out_extensions_list) |ext| {
exts.put(ext, ".js") catch unreachable;
}
return exts;
}
pub fn from(plat: ?api.Api.Target) Target {
return switch (plat orelse api.Api.Target._none) {
.node => .node,
.browser => .browser,
.bun => .bun,
.bun_macro => .bun_macro,
else => .browser,
};
}
const MAIN_FIELD_NAMES = [_]string{
"browser",
"module",
"main",
// https://github.com/jsforum/jsforum/issues/5
// Older packages might use jsnext:main in place of module
"jsnext:main",
};
pub const DefaultMainFields: std.EnumArray(Target, []const string) = brk: {
var array = std.EnumArray(Target, []const string).initUndefined();
// Note that this means if a package specifies "module" and "main", the ES6
// module will not be selected. This means tree shaking will not work when
// targeting node environments.
//
// Some packages incorrectly treat the "module" field as "code for the browser". It
// actually means "code for ES6 environments" which includes both node and the browser.
//
// For example, the package "@firebase/app" prints a warning on startup about
// the bundler incorrectly using code meant for the browser if the bundler
// selects the "module" field instead of the "main" field.
//
// This is unfortunate but it's a problem on the side of those packages.
// They won't work correctly with other popular bundlers (with node as a target) anyway.
const list = [_]string{ MAIN_FIELD_NAMES[2], MAIN_FIELD_NAMES[1] };
array.set(Target.node, &list);
// Note that this means if a package specifies "main", "module", and
// "browser" then "browser" will win out over "module". This is the
// same behavior as webpack: https://github.com/webpack/webpack/issues/4674.
//
// This is deliberate because the presence of the "browser" field is a
// good signal that this should be preferred. Some older packages might only use CJS in their "browser"
// but in such a case they probably don't have any ESM files anyway.
const listc = [_]string{ MAIN_FIELD_NAMES[0], MAIN_FIELD_NAMES[1], MAIN_FIELD_NAMES[3], MAIN_FIELD_NAMES[2] };
const listd = [_]string{ MAIN_FIELD_NAMES[1], MAIN_FIELD_NAMES[2], MAIN_FIELD_NAMES[3] };
array.set(Target.browser, &listc);
array.set(Target.bun, &listd);
array.set(Target.bun_macro, &listd);
array.set(Target.bake_server_components_ssr, &listd);
// Original comment:
// The neutral target is for people that don't want esbuild to try to
// pick good defaults for their platform. In that case, the list of main
// fields is empty by default. You must explicitly configure it yourself.
// array.set(Target.neutral, &listc);
break :brk array;
};
pub const default_conditions: std.EnumArray(Target, []const string) = brk: {
var array = std.EnumArray(Target, []const string).initUndefined();
array.set(Target.node, &.{
"node",
});
array.set(Target.browser, &.{
"browser",
"module",
});
array.set(Target.bun, &.{
"bun",
"node",
});
array.set(Target.bake_server_components_ssr, &.{
"bun",
"node",
});
array.set(Target.bun_macro, &.{
"macro",
"bun",
"node",
});
break :brk array;
};
pub fn defaultConditions(t: Target) []const []const u8 {
return default_conditions.get(t);
}
};
pub const Format = enum {
/// ES module format
/// This is the default format
esm,
/// Immediately-invoked function expression
/// (function(){
/// ...
/// })();
iife,
/// CommonJS
cjs,
/// Bake uses a special module format for Hot-module-reloading. It includes a
/// runtime payload, sourced from src/bake/hmr-runtime-{side}.ts.
///
/// ((input_graph, config) => {
/// ... runtime code ...
/// })({
/// "module1.ts"(module) { ... },
/// "module2.ts"(module) { ... },
/// }, { metadata });
internal_bake_dev,
pub fn keepES6ImportExportSyntax(this: Format) bool {
return this == .esm;
}
pub inline fn isESM(this: Format) bool {
return this == .esm;
}
pub inline fn isAlwaysStrictMode(this: Format) bool {
return this == .esm;
}
pub const Map = bun.ComptimeStringMap(Format, .{
.{ "esm", .esm },
.{ "cjs", .cjs },
.{ "iife", .iife },
// TODO: Disable this outside of debug builds
.{ "internal_bake_dev", .internal_bake_dev },
});
pub fn fromJS(global: *JSC.JSGlobalObject, format: JSC.JSValue) bun.JSError!?Format {
if (format.isUndefinedOrNull()) return null;
if (!format.isString()) {
return global.throwInvalidArguments("format must be a string", .{});
}
return Map.fromJS(global, format) orelse {
return global.throwInvalidArguments("Invalid format - must be esm, cjs, or iife", .{});
};
}
pub fn fromString(slice: string) ?Format {
return Map.getWithEql(slice, strings.eqlComptime);
}
};
pub const Loader = enum(u8) {
jsx,
js,
ts,
tsx,
css,
file,
json,
toml,
wasm,
napi,
base64,
dataurl,
text,
bunsh,
sqlite,
sqlite_embedded,
pub inline fn isSQLite(this: Loader) bool {
return switch (this) {
.sqlite, .sqlite_embedded => true,
else => false,
};
}
pub fn shouldCopyForBundling(this: Loader, experimental_css: bool) bool {
if (experimental_css) {
return switch (this) {
.file,
.napi,
.sqlite,
.sqlite_embedded,
// TODO: loader for reading bytes and creating module or instance
.wasm,
=> true,
else => false,
};
}
return switch (this) {
.file,
.css,
.napi,
.sqlite,
.sqlite_embedded,
// TODO: loader for reading bytes and creating module or instance
.wasm,
=> true,
else => false,
};
}
pub fn toMimeType(this: Loader) bun.http.MimeType {
return switch (this) {
.jsx, .js, .ts, .tsx => bun.http.MimeType.javascript,
.css => bun.http.MimeType.css,
.toml, .json => bun.http.MimeType.json,
.wasm => bun.http.MimeType.wasm,
else => bun.http.MimeType.other,
};
}
pub const HashTable = bun.StringArrayHashMap(Loader);
pub fn canHaveSourceMap(this: Loader) bool {
return switch (this) {
.jsx, .js, .ts, .tsx => true,
else => false,
};
}
pub fn canBeRunByBun(this: Loader) bool {
return switch (this) {
.jsx, .js, .ts, .tsx, .json, .wasm, .bunsh => true,
else => false,
};
}
pub const Map = std.EnumArray(Loader, string);
pub const stdin_name: Map = brk: {
var map = Map.initFill("");
map.set(.jsx, "input.jsx");
map.set(.js, "input.js");
map.set(.ts, "input.ts");
map.set(.tsx, "input.tsx");
map.set(.css, "input.css");
map.set(.file, "input");
map.set(.json, "input.json");
map.set(.toml, "input.toml");
map.set(.wasm, "input.wasm");
map.set(.napi, "input.node");
map.set(.text, "input.txt");
map.set(.bunsh, "input.sh");
break :brk map;
};
pub inline fn stdinName(this: Loader) string {
return stdin_name.get(this);
}
pub fn fromJS(global: *JSC.JSGlobalObject, loader: JSC.JSValue) bun.JSError!?Loader {
if (loader.isUndefinedOrNull()) return null;
if (!loader.isString()) {
return global.throwInvalidArguments("loader must be a string", .{});
}
var zig_str = JSC.ZigString.init("");
loader.toZigString(&zig_str, global);
if (zig_str.len == 0) return null;
return fromString(zig_str.slice()) orelse {
return global.throwInvalidArguments("invalid loader - must be js, jsx, tsx, ts, css, file, toml, wasm, bunsh, or json", .{});
};
}
pub const names = bun.ComptimeStringMap(Loader, .{
.{ "js", .js },
.{ "mjs", .js },
.{ "cjs", .js },
.{ "cts", .ts },
.{ "mts", .ts },
.{ "jsx", .jsx },
.{ "ts", .ts },
.{ "tsx", .tsx },
.{ "css", .css },
.{ "file", .file },
.{ "json", .json },
.{ "toml", .toml },
.{ "wasm", .wasm },
.{ "node", .napi },
.{ "dataurl", .dataurl },
.{ "base64", .base64 },
.{ "txt", .text },
.{ "text", .text },
.{ "sh", .bunsh },
.{ "sqlite", .sqlite },
.{ "sqlite_embedded", .sqlite_embedded },
});
pub const api_names = bun.ComptimeStringMap(Api.Loader, .{
.{ "js", .js },
.{ "mjs", .js },
.{ "cjs", .js },
.{ "cts", .ts },
.{ "mts", .ts },
.{ "jsx", .jsx },
.{ "ts", .ts },
.{ "tsx", .tsx },
.{ "css", .css },
.{ "file", .file },
.{ "json", .json },
.{ "toml", .toml },
.{ "wasm", .wasm },
.{ "node", .napi },
.{ "dataurl", .dataurl },
.{ "base64", .base64 },
.{ "txt", .text },
.{ "text", .text },
.{ "sh", .file },
.{ "sqlite", .sqlite },
});
pub fn fromString(slice_: string) ?Loader {
var slice = slice_;
if (slice.len > 0 and slice[0] == '.') {
slice = slice[1..];
}
return names.getWithEql(slice, strings.eqlCaseInsensitiveASCIIICheckLength);
}
pub fn supportsClientEntryPoint(this: Loader) bool {
return switch (this) {
.jsx, .js, .ts, .tsx => true,
else => false,
};
}
pub fn toAPI(loader: Loader) Api.Loader {
return switch (loader) {
.jsx => .jsx,
.js => .js,
.ts => .ts,
.tsx => .tsx,
.css => .css,
.file, .bunsh => .file,
.json => .json,
.toml => .toml,
.wasm => .wasm,
.napi => .napi,
.base64 => .base64,
.dataurl => .dataurl,
.text => .text,
.sqlite_embedded, .sqlite => .sqlite,
};
}
pub fn fromAPI(loader: Api.Loader) Loader {
return switch (loader) {
._none => .file,
.jsx => .jsx,
.js => .js,
.ts => .ts,
.tsx => .tsx,
.css => .css,
.file => .file,
.json => .json,
.toml => .toml,
.wasm => .wasm,
.napi => .napi,
.base64 => .base64,
.dataurl => .dataurl,
.text => .text,
.sqlite => .sqlite,
_ => .file,
};
}
pub fn isJSX(loader: Loader) bool {
return loader == .jsx or loader == .tsx;
}
pub fn isTypeScript(loader: Loader) bool {
return loader == .tsx or loader == .ts;
}
pub fn isJavaScriptLike(loader: Loader) bool {
return switch (loader) {
.jsx, .js, .ts, .tsx => true,
else => false,
};
}
pub fn isJavaScriptLikeOrJSON(loader: Loader) bool {
return switch (loader) {
.jsx, .js, .ts, .tsx, .json => true,
// toml is included because we can serialize to the same AST as JSON
.toml => true,
else => false,
};
}
pub fn forFileName(filename: string, obj: anytype) ?Loader {
const ext = std.fs.path.extension(filename);
if (ext.len == 0 or (ext.len == 1 and ext[0] == '.')) return null;
return obj.get(ext);
}
};
const default_loaders_posix = .{
.{ ".jsx", .jsx },
.{ ".json", .json },
.{ ".js", .jsx },
.{ ".mjs", .js },
.{ ".cjs", .js },
.{ ".css", .css },
.{ ".ts", .ts },
.{ ".tsx", .tsx },
.{ ".mts", .ts },
.{ ".cts", .ts },
.{ ".toml", .toml },
.{ ".wasm", .wasm },
.{ ".node", .napi },
.{ ".txt", .text },
.{ ".text", .text },
};
const default_loaders_win32 = default_loaders_posix ++ .{
.{ ".sh", .bunsh },
};
const default_loaders = if (Environment.isWindows) default_loaders_win32 else default_loaders_posix;
pub const defaultLoaders = bun.ComptimeStringMap(Loader, default_loaders);
// https://webpack.js.org/guides/package-exports/#reference-syntax
pub const ESMConditions = struct {
default: ConditionsMap = undefined,
import: ConditionsMap = undefined,
require: ConditionsMap = undefined,
pub fn init(allocator: std.mem.Allocator, defaults: []const string) !ESMConditions {
var default_condition_amp = ConditionsMap.init(allocator);
var import_condition_map = ConditionsMap.init(allocator);
var require_condition_map = ConditionsMap.init(allocator);
try default_condition_amp.ensureTotalCapacity(defaults.len + 2);
try import_condition_map.ensureTotalCapacity(defaults.len + 2);
try require_condition_map.ensureTotalCapacity(defaults.len + 2);
import_condition_map.putAssumeCapacity("import", {});
require_condition_map.putAssumeCapacity("require", {});
for (defaults) |default| {
default_condition_amp.putAssumeCapacityNoClobber(default, {});
import_condition_map.putAssumeCapacityNoClobber(default, {});
require_condition_map.putAssumeCapacityNoClobber(default, {});
}
default_condition_amp.putAssumeCapacity("default", {});
import_condition_map.putAssumeCapacity("default", {});
require_condition_map.putAssumeCapacity("default", {});
return ESMConditions{
.default = default_condition_amp,
.import = import_condition_map,
.require = require_condition_map,
};
}
pub fn appendSlice(self: *ESMConditions, conditions: []const string) !void {
try self.default.ensureUnusedCapacity(conditions.len);
try self.import.ensureUnusedCapacity(conditions.len);
try self.require.ensureUnusedCapacity(conditions.len);
for (conditions) |condition| {
self.default.putAssumeCapacityNoClobber(condition, {});
self.import.putAssumeCapacityNoClobber(condition, {});
self.require.putAssumeCapacityNoClobber(condition, {});
}
}
};
pub const JSX = struct {
pub const RuntimeMap = bun.ComptimeStringMap(JSX.Runtime, .{
.{ "classic", .classic },
.{ "automatic", .automatic },
.{ "react", .classic },
.{ "react-jsx", .automatic },
.{ "react-jsxdev", .automatic },
.{ "solid", .solid },
});
pub const Pragma = struct {
// these need to be arrays
factory: []const string = Defaults.Factory,
fragment: []const string = Defaults.Fragment,
runtime: JSX.Runtime = .automatic,
import_source: ImportSource = .{},
/// Facilitates automatic JSX importing
/// Set on a per file basis like this:
/// /** @jsxImportSource @emotion/core */
classic_import_source: string = "react",
package_name: []const u8 = "react",
development: bool = true,
parse: bool = true,
pub const ImportSource = struct {
development: string = "react/jsx-dev-runtime",
production: string = "react/jsx-runtime",
};
pub fn hashForRuntimeTranspiler(this: *const Pragma, hasher: *std.hash.Wyhash) void {
for (this.factory) |factory| hasher.update(factory);
for (this.fragment) |fragment| hasher.update(fragment);
hasher.update(this.import_source.development);
hasher.update(this.import_source.production);
hasher.update(this.classic_import_source);
hasher.update(this.package_name);
}
pub fn importSource(this: *const Pragma) string {
return switch (this.development) {