Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/bunfig/bunfig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use bun_options_types::LoaderExt as _;
use bun_options_types::code_coverage_options::Reporters as CoverageReporters;
use bun_options_types::context::{MacroImportReplacementMap, MacroMap, MacroOptions};
use bun_options_types::global_cache::GlobalCache;
use bun_options_types::jsx::MemberListOption;
use bun_options_types::offline_mode::PREFER as OFFLINE_PREFER;
use bun_options_types::schema::api;

Expand Down Expand Up @@ -973,15 +974,28 @@ impl<'a> Parser<'a> {
jsx_import_source = Box::<[u8]>::from(value);
}
}
if let Some(expr) = json.get(b"jsxFragment") {
if let Some(value) = expr.as_string(self.bump) {
jsx_fragment = Box::<[u8]>::from(value);
}
}
if let Some(expr) = json.get(b"jsxFactory") {
if let Some(value) = expr.as_string(self.bump) {
jsx_factory = Box::<[u8]>::from(value);
for (key, option, text) in [
("jsxFragment", MemberListOption::Fragment, &mut jsx_fragment),
("jsxFactory", MemberListOption::Factory, &mut jsx_factory),
] {
let Some(expr) = json.get(key.as_bytes()) else {
continue;
};
let Some(value) = expr.as_string(self.bump) else {
continue;
};
if let Err(expected) = option.check(value) {
self.add_error_format(
expr.loc,
format_args!(
"Invalid {}: {}. {}",
key,
bun_core::fmt::quote(value),
expected
),
)?;
}
*text = Box::<[u8]>::from(value);
}
{
if let Some(jsx) = self.ctx.args.jsx.as_mut() {
Expand Down
59 changes: 59 additions & 0 deletions src/options_types/jsx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! crate's `schema` module — so the type sits cleanly at this tier.

use crate::schema::api;
use bun_core::identifier::is_identifier;
use bun_core::strings;
use std::borrow::Cow;

Expand Down Expand Up @@ -248,6 +249,26 @@
Cow::Owned(out)
}

/// The first member of `text` that is not an identifier, or all of `text` when it has no members (`"."`).
pub fn invalid_member(text: &[u8]) -> Option<&[u8]> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
use bun_ast::lexer_tables::{T, keyword};

let mut members = strings::tokenize(text, b".").peekable();
let Some(first) = members.next() else {
return Some(text);
};
// `first` is looked up as a variable. The exceptions are esbuild's (`ParseDefineExprOrJSON`).
let first_is_reserved = match keyword(first) {
None | Some(T::TNull | T::TThis) => false,
Some(T::TImport) => members.peek() != Some(&b"meta".as_slice()),
Some(_) => true,
};
if first_is_reserved || !is_identifier(first) {
return Some(first);
}
members.find(|member| !is_identifier(member))
}

/// `"React.createElement"` => `["React", "createElement"]`, or a copy of
/// `original` (no allocation for `Static`) when `new` names the same
/// members. `None` when `new` has no members, for example `"."`.
Expand Down Expand Up @@ -296,6 +317,44 @@
}
}

/// The member list that a `Bun.build` option, a CLI flag or a bunfig.toml key sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberListOption {
Factory,
Fragment,
}

impl MemberListOption {
/// `Err` says what `text` must be. Empty text means unset.
pub fn check(self, text: &[u8]) -> Result<(), &'static str> {

Check warning on line 329 in src/options_types/jsx.rs

View workflow job for this annotation

GitHub Actions / mordant

`check` is public and returns `Result<_, &str>`. Callers can only tell failures apart by reading the message
if text.is_empty() || Pragma::invalid_member(text).is_none() {
return Ok(());
}
match self {
MemberListOption::Factory => Err(
"Must be an identifier or a dotted chain of identifiers, for example \"h\" or \"React.createElement\"",
),
MemberListOption::Fragment if is_verbatim_constant(text) => Ok(()),
MemberListOption::Fragment => Err(
"Must be an identifier, a dotted chain of identifiers or a constant, for example \"Fragment\", \"React.Fragment\" or \"'['\"",
),
}
}
}

/// A JSON scalar (esbuild takes one for the fragment) that can be split on `.` and printed verbatim: no `.`, no `\` escape.
fn is_verbatim_constant(text: &[u8]) -> bool {
match text {
b"true" | b"false" | [b'0'] => true,
[b'1'..=b'9', digits @ ..] => digits.iter().all(u8::is_ascii_digit),
[quote @ (b'"' | b'\''), body @ .., end] => {
quote == end
&& strings::index_of_any(body, &[*quote, b'\\', b'\r', b'\n', b'.']).is_none()
}
_ => false,
}
}

/// Default JSX factory/fragment/import-source values.
pub mod defaults {
pub const FACTORY: &[&[u8]] = &[b"React", b"createElement"];
Expand Down
11 changes: 1 addition & 10 deletions src/resolver/tsconfig_json.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use bun_collections::ArrayHashMap;
use bun_core::strings;
use bun_js_parser::lexer as js_lexer;
use bun_parsers::json_parser;
use enumset::{EnumSet, EnumSetType};

Expand Down Expand Up @@ -709,15 +708,7 @@ impl TSConfigJSON {
return None;
}

let mut parts = strings::tokenize(text, b".").peekable();
// Text made of dots only ("." or "..") has no parts; report the whole text.
let invalid = if parts.peek().is_none() {
Some(text)
} else {
parts.find(|part| !js_lexer::is_identifier(part))
};

if let Some(invalid) = invalid {
if let Some(invalid) = options::jsx::Pragma::invalid_member(text) {
let warn = source.range_of_string(loc);
let _ = log.add_range_warning_fmt(
Some(source),
Expand Down
32 changes: 24 additions & 8 deletions src/runtime/api/JSBundler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -799,14 +799,30 @@ pub mod js_bundler {
drop(slice);
}

if let Some(slice) = jsx_value.get_optional_slice(global_this, b"factory")? {
this.jsx.factory = Box::<[u8]>::from(slice.slice());
drop(slice);
}

if let Some(slice) = jsx_value.get_optional_slice(global_this, b"fragment")? {
this.jsx.fragment = Box::<[u8]>::from(slice.slice());
drop(slice);
for (name, option, text) in [
(
"factory",
options::JSX::MemberListOption::Factory,
&mut this.jsx.factory,
),
(
"fragment",
options::JSX::MemberListOption::Fragment,
&mut this.jsx.fragment,
),
] {
let Some(slice) = jsx_value.get_optional_slice(global_this, name)? else {
continue;
};
if let Err(expected) = option.check(slice.slice()) {
return Err(global_this.throw_invalid_arguments(format_args!(
"Invalid jsx.{}: {}. {}",
name,
bun_core::fmt::quote(slice.slice()),
expected
)));
}
*text = Box::<[u8]>::from(slice.slice());
}

if let Some(slice) = jsx_value.get_optional_slice(global_this, b"importSource")? {
Expand Down
23 changes: 23 additions & 0 deletions src/runtime/cli/Arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1562,6 +1562,29 @@ pub(crate) fn parse(cmd: CommandTag, ctx: Context<'_>) -> crate::Result<api::Tra
let jsx_runtime = args.option(b"--jsx-runtime");
let jsx_side_effects = args.flag(b"--jsx-side-effects");

for (flag, option, value) in [
(
"--jsx-factory",
options::jsx::MemberListOption::Factory,
jsx_factory,
),
(
"--jsx-fragment",
options::jsx::MemberListOption::Fragment,
jsx_fragment,
),
] {
if let Some(value) = value
&& let Err(expected) = option.check(value)
{
Output::err_generic(
"Invalid value for {}: {}. {}",
(flag, bun_core::fmt::quote(value), expected),
);
Global::exit(1);
}
}

if matches!(cmd, CommandTag::AutoCommand | CommandTag::RunCommand) {
// "run.silent" in bunfig.toml
if args.flag(b"--silent") {
Expand Down
Loading
Loading