Repository navigation
Deduplicate small helpers across crypto, api objects, sockets, valkey, napi, bake, and coverage - #37366
Deduplicate small helpers across crypto, api objects, sockets, valkey, napi, bake, and coverage#37366robobun wants to merge 11 commits into
Conversation
…urcemap, threading, url
Resolved src/bun_core/string/mod.rs: #33909 switched return types to crate::CrateResult<()> in write_pre_quoted_string and quote_for_json, which this branch restructures into the const-generic write_pre_quoted_string_inner; carried CrateResult<()> into both the adapter and _inner signatures. Resolved src/router/lib.rs and src/sourcemap/Chunk.rs: #33909 touched return types inside blocks this branch deletes (orphaned router test scaffolding, uncalled print_source_map_contents); kept the deletions after re-verifying zero callers on current main. Restored Node::find_last in src/collections/pool.rs: gained a test caller via #33311.
…update --interactive
…, napi, bake, and coverage
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it consolidates logic across 17 files in many independent subsystems (napi FFI, socket callback dispatch, crypto digest paths, bake transpiler init, the valkey command-macro table, JSON5→shared expr_to_js), a human look would still be worthwhile — several of the dedups delegate to shared implementations whose edge-case behavior (e.g. object-key handling in bun_js_parser_jsc::expr_to_js, the unified BuildConfigSubset type) isn't byte-identical to what was removed.
Checked and ruled out:
is_array_buffer_like()matches the exact 14-variant list it replaces in HashObject.- The valkey
cmd!/cmd_varargs!collapse preserves each call site's null-handling mode (strict/skip_null/required) against the original 7 macros. napi_string_slicepreserves the null/length/NAPI_AUTO_LENGTH branch order andtransfer_to_jsrouting.StaticCryptoHasher::digest_to_bytesstill readsoutput_digest_slice(which aliasesoutput_digest_bufin theNonearm) after theoutput_digestrefactor.
Extended reasoning...
Overview
This PR is split 8/8 of #32023 and deduplicates local helper logic across 17 files: CryptoHasher digest-output parsing, PasswordObject verify-algorithm parsing, HashObject/JSON5Object/MarkdownObject/csrf_jsc argument parsing, ServerWebSocket.publish* prologues, udp_socket setsockopt paths, socket_body callback-dispatch tails, the valkey command-macro table (7 macros → 2), the NAPI napi_create_string_* prologue, bake's init_transpiler variants (merged into init_transpiler_impl with BuildConfigSubset unified to a single type), the DevServer field-destructure exhaustiveness check (macro-ized), and CodeCoverage byte-offset→line resolution.
Security risks
None identified. The changes are refactors of argument parsing and dispatch; no new trust boundaries, no changes to validation ordering that would weaken checks. The CSRF option-parsing helpers preserve the same algorithm allowlist and non-empty-string checks.
Level of scrutiny
High. Although framed as pure code motion, several consolidations are semantic delegations rather than cut-and-paste: JSON5's expr_to_js now routes through bun_js_parser_jsc::expr_to_js (which uses put_to_property_key and create_empty_array+put_index instead of the removed put_may_be_index/create_array_from_iter, and errors on unknown node types instead of returning undefined); the bake keystone BuildConfigSubset mirror struct is deleted in favor of re-exporting bake_body::BuildConfigSubset (which carries two extra fields); and the valkey macro collapse re-encodes per-command null-handling as a mode token. These touch napi FFI (unsafe slice construction), socket re-entrancy paths, and bundler configuration — all areas where subtle divergence is easy to miss.
Other factors
No bugs were found by the multi-agent bug hunter. I spot-checked is_array_buffer_like (exact match), the napi slice helper (branch order preserved, transfer_to_js still used), the output_digest refactor in StaticCryptoHasher (the None branch still reads the fallback buffer via the returned &mut), and traced each valkey call site's mode against its original macro. The PR description documents the one intentional semantic change (verify_sync returning Err(JsError::Thrown) instead of Ok(JSValue::ZERO), which the host_fn boundary maps identically). Given the breadth (17 files, ~10 subsystems) and that this is the final split of a series a maintainer explicitly asked to be broken up, deferring to human review.
|
Updated 6:05 AM PT - Aug 11th, 2026
❌ @alii, your commit 9f5a05c has some failures in 🧪 To try this PR locally: bunx bun-pr 37366That installs a local version of the PR into your bun-37366 --bun |
2f5dd36 to
9ae3ff5
Compare
### Problem
- `Bun.CSRF.generate` and `Bun.CSRF.verify` each read the `encoding`
option with their own copy of the same code: `get("encoding")`,
`Encoding::from_js_with_default_on_empty`, the `Encoding` to
`csrf::TokenFormat` match, and the `Invalid format` error (which
appeared four times). `src/runtime/api/csrf_jsc.rs:99-120` and
`:254-275` before this change.
- mordant's `same_match_twice` reports the second copy; it is the
`same_match_twice:src/runtime/api/csrf_jsc.rs` entry in
`mordant-baseline.toml`.
### Fix
- One `get_optional_token_format(options, global)` helper in
`csrf_jsc.rs`, next to the existing `get_optional_int_u64`, called from
both functions at the same point in the option-reading order. The `None`
from an unknown encoding name and the non-token encodings share the one
error arm, so the message exists once.
- The mapping stays in `csrf_jsc.rs` rather than on an enum:
`TokenFormat` lives in `bun_csrf`, which cannot see
`crate::node::Encoding`, and this file is `TokenFormat`'s only user. The
comment on the reverse mapping (used to encode the token) still named
`TokenFormat::to_node_encoding`, removed in #35002; reworded.
- Removed the baseline entry. `bun run rust:mordant` over the workspace
is clean with it removed; with the entry removed but the old source
restored it reports the one finding at `csrf_jsc.rs:265`, so the entry
was this site.
- No behavior change. Compared the release build against this build on
the same script covering every rejected encoding (`utf8`, `latin1`,
`buffer`, `bogus`, `null`, a number, an object), case-insensitive names,
`""`, `undefined`, and the order in which the option properties are read
by both functions: identical output.
- Verified with `bun bd test test/js/bun/util/csrf.test.ts` (25 pass).
Added one test pinning the error message for both functions and the `""`
default, since that path was not covered; it passes before and after, as
expected for a refactor.
### Background
- `crate::node::Encoding` is the Buffer encoding enum (`utf8`, `hex`,
`base64`, ...). `from_js_with_default_on_empty` parses a JS value as an
encoding name, returning the given default for `""` and `None` for names
it does not know.
- `csrf::TokenFormat` is the three-variant enum (`Base64`, `Base64Url`,
`Hex`) the `bun_csrf` crate encodes and decodes tokens with. The CSRF
API accepts the encoding option as a Buffer encoding name and narrows it
to a `TokenFormat`, which is the mapping this PR deduplicates.
- mordant is the lint pack run by `bun run rust:mordant`;
`mordant-baseline.toml` records the accepted count of findings per
(lint, file), and CI fails only on findings above the recorded count, so
fixing a finding means deleting its entry.
- #37366 (an 82-file dedup PR stacked on #32022) contains an equivalent
helper for this file among many others; when it is rebased, its
`csrf_jsc.rs` hunk becomes redundant with this one.
---------
Co-authored-by: Alistair Smith <hi@alistair.sh>
b5b9aaa to
23cbfb4
Compare
What this does
A collection of independent, file-local dedups that did not warrant their own PRs:
CryptoHasherdigest-output parsing (output_digest, shared by the fivedigest*entry points),PasswordObjectverify-algorithm parsing (shared byverify/verifySync),HashObject/JSON5Object(delegates to the sharedbun_js_parser_jsc::expr_to_js) /MarkdownObject/csrf_jscoption parsing,ServerWebSocketandudp_socketsend-path argument handling,socket_body's four identical callback-dispatch tails (call_socket_handler), the valkey command table, the NAPInapi_create_string_*prologue (napi_string_slice+set_string_result), bake's threeinit_transpilervariants (init_transpiler_impl), andCodeCoveragereport emission.Split 8 of 8 from #32023, which alii asked to be broken up. Pure code motion and deletion; no intended behavior change. Stacked on
claude/split/install-cli(merge order: foundations → install-cli → these, in any order among themselves).Notes from rebasing against main
Most of the conflict resolution from the parent PR's two rebases landed in these files; the surviving code keeps main's semantics in every case:
socket_bodyuses main'sRc<Handlers>/exit_scopeAPI (#31859, #33388);napiroutes main'stransfer_to_jsleak fix (#32303) through the shared helper;JSON5ObjectkeepsOwnedStringfrom #32331;MarkdownObjectroutes both call sites through main'sparser_err_to_js(which gainedInputTooLarge/TooManyBlocksin #32752/#33078);csrfcalls main'sget_optional_slicemethod (#32355); bake signatures usecrate::Result(#33909).PasswordObject::verify_sync's unknown-algorithm-with-pending-exception branch returnedOk(JSValue::ZERO)and now returnsErr(JsError::Thrown)like its async twin; the host_fn boundary maps both to the same zero return (src/jsc/host_fn.rs).Verification
cargo check), and the union of all eight splits is byte-identical to Deduplicate jsc bindings, runtime api, test matchers, and shell builtins #32023's headf29ce8fe4, which CI ran at 285/286 green (the one red was the fleet-widenapi.test.tsGC-timing flake on windows x64-baseline).