Skip to content

Commit

Permalink
Implement --drop (#14492)
Browse files Browse the repository at this point in the history
Co-authored-by: dave caruso <me@paperdave.net>
  • Loading branch information
Jarred-Sumner and paperclover authored Oct 12, 2024
1 parent bbb41be commit c77fc5d
Show file tree
Hide file tree
Showing 26 changed files with 362 additions and 143 deletions.
20 changes: 20 additions & 0 deletions docs/bundler/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,26 @@ $ bun build ./index.tsx --outdir ./out --footer="// built with love in SF"

{% /codetabs %}

### `drop`

Remove function calls from a bundle. For example, `--drop=console` will remove all calls to `console.log`. Arguments to calls will also be removed, regardless of if those arguments may have side effects. Dropping `debugger` will remove all `debugger` statements.

{% codetabs %}

```ts#JavaScript
await Bun.build({
entrypoints: ['./index.tsx'],
outdir: './out',
drop: ["console", "debugger", "anyIdentifier.or.propertyAccess"],
})
```

```bash#CLI
$ bun build ./index.tsx --outdir ./out --drop=console --drop=debugger --drop=anyIdentifier.or.propertyAccess
```

{% /codetabs %}

### `experimentalCss`

Whether to enable _experimental_ support for bundling CSS files. Defaults to `false`.
Expand Down
3 changes: 1 addition & 2 deletions docs/bundler/vs-esbuild.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,7 @@ In Bun's CLI, simple boolean flags like `--minify` do not accept an argument. Ot
---

- `--drop`
- n/a
- Not supported
- `--drop`

---

Expand Down
5 changes: 5 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1612,6 +1612,11 @@ declare module "bun" {
* Enable CSS support.
*/
experimentalCss?: boolean;

/**
* Drop function calls to matching property accesses.
*/
drop?: string[];
}

namespace Password {
Expand Down
2 changes: 2 additions & 0 deletions src/api/schema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1635,6 +1635,8 @@ pub const Api = struct {
/// define
define: ?StringMap = null,

drop: []const []const u8 = &.{},

/// preserve_symlinks
preserve_symlinks: ?bool = null,

Expand Down
4 changes: 2 additions & 2 deletions src/bun.js/api/BunObject.zig
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ pub fn inspect(

// we are going to always clone to keep things simple for now
// the common case here will be stack-allocated, so it should be fine
var out = ZigString.init(array.toOwnedSliceLeaky()).withEncoding();
var out = ZigString.init(array.slice()).withEncoding();
const ret = out.toJS(globalThis);
array.deinit();
return ret;
Expand Down Expand Up @@ -3932,7 +3932,7 @@ const TOMLObject = struct {
return .zero;
};

const slice = writer.ctx.buffer.toOwnedSliceLeaky();
const slice = writer.ctx.buffer.slice();
var out = bun.String.fromUTF8(slice);
defer out.deref();

Expand Down
17 changes: 16 additions & 1 deletion src/bun.js/api/JSBundler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ pub const JSBundler = struct {
banner: OwnedString = OwnedString.initEmpty(bun.default_allocator),
footer: OwnedString = OwnedString.initEmpty(bun.default_allocator),
experimental_css: bool = false,
drop: bun.StringSet = bun.StringSet.init(bun.default_allocator),

pub const List = bun.StringArrayHashMapUnmanaged(Config);

Expand Down Expand Up @@ -191,7 +192,6 @@ pub const JSBundler = struct {
try this.banner.appendSliceExact(slice.slice());
}


if (try config.getOptional(globalThis, "footer", ZigString.Slice)) |slice| {
defer slice.deinit();
try this.footer.appendSliceExact(slice.slice());
Expand Down Expand Up @@ -351,6 +351,18 @@ pub const JSBundler = struct {
}
}

if (try config.getOwnArray(globalThis, "drop")) |drops| {
var iter = drops.arrayIterator(globalThis);
while (iter.next()) |entry| {
var slice = entry.toSliceOrNull(globalThis) orelse {
globalThis.throwInvalidArguments("Expected drop to be an array of strings", .{});
return error.JSError;
};
defer slice.deinit();
try this.drop.insert(slice.slice());
}
}

// if (try config.getOptional(globalThis, "dir", ZigString.Slice)) |slice| {
// defer slice.deinit();
// this.appendSliceExact(slice.slice()) catch unreachable;
Expand Down Expand Up @@ -544,6 +556,9 @@ pub const JSBundler = struct {
self.rootdir.deinit();
self.public_path.deinit();
self.conditions.deinit();
self.drop.deinit();
self.banner.deinit();
self.footer.deinit();
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/api/html_rewriter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ pub const HTMLRewriter = struct {

// pub fn done(this: *StreamOutputSink) void {
// var prev_value = this.response.body.value;
// var bytes = this.bytes.toOwnedSliceLeaky();
// var bytes = this.bytes.slice();
// this.response.body.value = .{
// .Blob = JSC.WebCore.Blob.init(bytes, this.bytes.allocator, this.global),
// };
Expand Down
12 changes: 6 additions & 6 deletions src/bun.js/bindings/bindings.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3129,7 +3129,7 @@ pub const JSGlobalObject = opaque {
return ZigString.static(fmt).toErrorInstance(this);

// Ensure we clone it.
var str = ZigString.initUTF8(buf.toOwnedSliceLeaky());
var str = ZigString.initUTF8(buf.slice());

return str.toErrorInstance(this);
} else {
Expand All @@ -3148,7 +3148,7 @@ pub const JSGlobalObject = opaque {
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
var str = ZigString.fromUTF8(buf.slice());
return str.toTypeErrorInstance(this);
} else {
return ZigString.static(fmt).toTypeErrorInstance(this);
Expand All @@ -3162,7 +3162,7 @@ pub const JSGlobalObject = opaque {
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
var str = ZigString.fromUTF8(buf.slice());
return str.toSyntaxErrorInstance(this);
} else {
return ZigString.static(fmt).toSyntaxErrorInstance(this);
Expand All @@ -3176,7 +3176,7 @@ pub const JSGlobalObject = opaque {
defer buf.deinit();
var writer = buf.writer();
writer.print(fmt, args) catch return ZigString.static(fmt).toErrorInstance(this);
var str = ZigString.fromUTF8(buf.toOwnedSliceLeaky());
var str = ZigString.fromUTF8(buf.slice());
return str.toRangeErrorInstance(this);
} else {
return ZigString.static(fmt).toRangeErrorInstance(this);
Expand Down Expand Up @@ -4619,7 +4619,7 @@ pub const JSValue = enum(JSValueReprInt) {

var writer = buf.writer();
try writer.print(fmt, args);
return String.init(buf.toOwnedSliceLeaky()).toJS(globalThis);
return String.init(buf.slice()).toJS(globalThis);
}

/// Create a JSValue string from a zig format-print (fmt + args), with pretty format
Expand All @@ -4633,7 +4633,7 @@ pub const JSValue = enum(JSValueReprInt) {
switch (Output.enable_ansi_colors) {
inline else => |enabled| try writer.print(Output.prettyFmt(fmt, enabled), args),
}
return String.init(buf.toOwnedSliceLeaky()).toJS(globalThis);
return String.init(buf.slice()).toJS(globalThis);
}

pub fn fromEntries(globalThis: *JSGlobalObject, keys_array: [*c]ZigString, values_array: [*c]ZigString, strings_count: usize, clone: bool) JSValue {
Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/module_loader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2143,7 +2143,7 @@ pub const ModuleLoader = struct {
writer.writeAll(";\n") catch bun.outOfMemory();
}

const public_url = bun.String.createUTF8(buf.toOwnedSliceLeaky());
const public_url = bun.String.createUTF8(buf.slice());
return ResolvedSource{
.allocator = &jsc_vm.allocator,
.source_code = public_url,
Expand Down
4 changes: 2 additions & 2 deletions src/bun.js/test/diff_format.zig
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ pub const DiffFormatter = struct {
buffered_writer.flush() catch unreachable;
}

const received_slice = received_buf.toOwnedSliceLeaky();
const expected_slice = expected_buf.toOwnedSliceLeaky();
const received_slice = received_buf.slice();
const expected_slice = expected_buf.slice();

if (this.not) {
const not_fmt = "Expected: not <green>{s}<r>";
Expand Down
6 changes: 3 additions & 3 deletions src/bun.js/test/expect.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2757,7 +2757,7 @@ pub const Expect = struct {
};
defer pretty_value.deinit();

if (strings.eqlLong(pretty_value.toOwnedSliceLeaky(), saved_value, true)) {
if (strings.eqlLong(pretty_value.slice(), saved_value, true)) {
Jest.runner.?.snapshots.passed += 1;
return .undefined;
}
Expand All @@ -2766,7 +2766,7 @@ pub const Expect = struct {
const signature = comptime getSignature("toMatchSnapshot", "<green>expected<r>", false);
const fmt = signature ++ "\n\n{any}\n";
const diff_format = DiffFormatter{
.received_string = pretty_value.toOwnedSliceLeaky(),
.received_string = pretty_value.slice(),
.expected_string = saved_value,
.globalThis = globalThis,
};
Expand Down Expand Up @@ -5443,7 +5443,7 @@ pub const ExpectCustomAsymmetricMatcher = struct {
return .zero;
};
if (printed) {
return bun.String.init(mutable_string.toOwnedSliceLeaky()).toJS();
return bun.String.init(mutable_string.slice()).toJS();
}
return ExpectMatcherUtils.printValue(globalThis, this, null);
}
Expand Down
4 changes: 2 additions & 2 deletions src/bun.js/test/jest.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1788,7 +1788,7 @@ inline fn createScope(
buffer.reset();
appendParentLabel(&buffer, parent) catch @panic("Bun ran out of memory while filtering tests");
buffer.append(label) catch unreachable;
const str = bun.String.fromBytes(buffer.toOwnedSliceLeaky());
const str = bun.String.fromBytes(buffer.slice());
is_skip = !regex.matches(str);
if (is_skip) {
tag_to_use = .skip;
Expand Down Expand Up @@ -2087,7 +2087,7 @@ fn eachBind(
buffer.reset();
appendParentLabel(&buffer, parent) catch @panic("Bun ran out of memory while filtering tests");
buffer.append(formattedLabel) catch unreachable;
const str = bun.String.fromBytes(buffer.toOwnedSliceLeaky());
const str = bun.String.fromBytes(buffer.slice());
is_skip = !regex.matches(str);
}

Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/web_worker.zig
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ pub const WebWorker = struct {
bun.outOfMemory();
};
JSC.markBinding(@src());
WebWorker__dispatchError(globalObject, worker.cpp_worker, bun.String.createUTF8(array.toOwnedSliceLeaky()), error_instance);
WebWorker__dispatchError(globalObject, worker.cpp_worker, bun.String.createUTF8(array.slice()), error_instance);
if (vm.worker) |worker_| {
_ = worker.setRequestedTerminate();
worker.parent_poll_ref.unrefConcurrently(worker.parent);
Expand Down
17 changes: 9 additions & 8 deletions src/bundler/bundle_v2.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ pub const BundleV2 = struct {
.entry_points = config.entry_points.keys(),
.target = config.target.toAPI(),
.absolute_working_dir = if (config.dir.list.items.len > 0)
config.dir.toOwnedSliceLeaky()
config.dir.slice()
else
null,
.inject = &.{},
Expand All @@ -1449,6 +1449,7 @@ pub const BundleV2 = struct {
.env_files = &.{},
.conditions = config.conditions.map.keys(),
.ignore_dce_annotations = bundler.options.ignore_dce_annotations,
.drop = config.drop.map.keys(),
},
completion.env,
);
Expand All @@ -1466,8 +1467,8 @@ pub const BundleV2 = struct {
bundler.options.output_format = config.format;
bundler.options.bytecode = config.bytecode;

bundler.options.output_dir = config.outdir.toOwnedSliceLeaky();
bundler.options.root_dir = config.rootdir.toOwnedSliceLeaky();
bundler.options.output_dir = config.outdir.slice();
bundler.options.root_dir = config.rootdir.slice();
bundler.options.minify_syntax = config.minify.syntax;
bundler.options.minify_whitespace = config.minify.whitespace;
bundler.options.minify_identifiers = config.minify.identifiers;
Expand All @@ -1478,8 +1479,8 @@ pub const BundleV2 = struct {
bundler.options.emit_dce_annotations = config.emit_dce_annotations orelse !config.minify.whitespace;
bundler.options.ignore_dce_annotations = config.ignore_dce_annotations;
bundler.options.experimental_css = config.experimental_css;
bundler.options.banner = config.banner.toOwnedSlice();
bundler.options.footer = config.footer.toOwnedSlice();
bundler.options.banner = config.banner.slice();
bundler.options.footer = config.footer.slice();

bundler.configureLinker();
try bundler.configureDefines();
Expand Down Expand Up @@ -1545,7 +1546,7 @@ pub const BundleV2 = struct {
bun.default_allocator.dupe(
u8,
bun.path.joinAbsString(
this.config.outdir.toOwnedSliceLeaky(),
this.config.outdir.slice(),
&[_]string{output_file.dest_path},
.auto,
),
Expand All @@ -1555,7 +1556,7 @@ pub const BundleV2 = struct {
u8,
bun.path.joinAbsString(
Fs.FileSystem.instance.top_level_dir,
&[_]string{ this.config.dir.toOwnedSliceLeaky(), this.config.outdir.toOwnedSliceLeaky(), output_file.dest_path },
&[_]string{ this.config.dir.slice(), this.config.outdir.slice(), output_file.dest_path },
.auto,
),
) catch unreachable
Expand Down Expand Up @@ -8950,7 +8951,7 @@ pub const LinkerContext = struct {
const input = c.parse_graph.input_files.items(.source)[chunk.entry_point.source_index].path;
var buf = MutableString.initEmpty(worker.allocator);
js_printer.quoteForJSONBuffer(input.pretty, &buf, true) catch bun.outOfMemory();
const str = buf.toOwnedSliceLeaky(); // worker.allocator is an arena
const str = buf.slice(); // worker.allocator is an arena
j.pushStatic(str);
line_offset.advance(str);
}
Expand Down
9 changes: 6 additions & 3 deletions src/cli.zig
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,11 @@ pub const Arguments = struct {
};

const transpiler_params_ = [_]ParamType{
clap.parseParam("--main-fields <STR>... Main fields to lookup in package.json. Defaults to --target dependent") catch unreachable,
clap.parseParam("--main-fields <STR>... Main fields to lookup in package.json. Defaults to --target dependent") catch unreachable,
clap.parseParam("--extension-order <STR>... Defaults to: .tsx,.ts,.jsx,.js,.json ") catch unreachable,
clap.parseParam("--tsconfig-override <STR> Specify custom tsconfig.json. Default <d>$cwd<r>/tsconfig.json") catch unreachable,
clap.parseParam("-d, --define <STR>... Substitute K:V while parsing, e.g. --define process.env.NODE_ENV:\"development\". Values are parsed as JSON.") catch unreachable,
clap.parseParam("--tsconfig-override <STR> Specify custom tsconfig.json. Default <d>$cwd<r>/tsconfig.json") catch unreachable,
clap.parseParam("-d, --define <STR>... Substitute K:V while parsing, e.g. --define process.env.NODE_ENV:\"development\". Values are parsed as JSON.") catch unreachable,
clap.parseParam("--drop <STR>... Remove function calls, e.g. --drop=console removes all console.* calls.") catch unreachable,
clap.parseParam("-l, --loader <STR>... Parse files with .ext:loader, e.g. --loader .js:jsx. Valid loaders: js, jsx, ts, tsx, json, toml, text, file, wasm, napi") catch unreachable,
clap.parseParam("--no-macros Disable macros from being executed in the bundler, transpiler and runtime") catch unreachable,
clap.parseParam("--jsx-factory <STR> Changes the function called when compiling JSX elements using the classic JSX runtime") catch unreachable,
Expand Down Expand Up @@ -590,6 +591,8 @@ pub const Arguments = struct {
};
}

opts.drop = args.options("--drop");

const loader_tuple = try LoaderColonList.resolve(allocator, args.options("--loader"));

if (loader_tuple.keys.len > 0) {
Expand Down
4 changes: 3 additions & 1 deletion src/cli/build_command.zig
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ pub const BuildCommand = struct {

this_bundler.options.banner = ctx.bundler_options.banner;
this_bundler.options.footer = ctx.bundler_options.footer;
this_bundler.options.drop = ctx.args.drop;

this_bundler.options.experimental_css = ctx.bundler_options.experimental_css;

Expand Down Expand Up @@ -236,10 +237,11 @@ pub const BuildCommand = struct {
allocator,
user_defines.keys,
user_defines.values,
), log, allocator)
), ctx.args.drop, log, allocator)
else
null,
null,
this_bundler.options.define.drop_debugger,
);

try bun.bake.addImportMetaDefines(allocator, this_bundler.options.define, .development, .server);
Expand Down
2 changes: 1 addition & 1 deletion src/cli/upgrade_command.zig
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ pub const UpgradeCommand = struct {
else => return error.HTTPError,
}

const bytes = zip_file_buffer.toOwnedSliceLeaky();
const bytes = zip_file_buffer.slice();

progress.end();
refresher.refresh();
Expand Down
Loading

0 comments on commit c77fc5d

Please sign in to comment.