chitralverma commented on code in PR #9333:
URL: https://github.com/apache/opendal/pull/9333#discussion_r4725725355
##########
dev/src/generate/nodejs.rs:
##########
@@ -169,6 +171,135 @@ fn metadata_field(f: metadata::MetadataField) ->
MetadataField {
}
}
+/// The core `ListOptions` fields that JS exposes, in declaration order.
+///
+/// A core field missing here is not exposed in JS, and the conversion sets it
+/// to its default.
+const LIST_OPTIONS_FIELDS: &[&str] = &["limit", "start_after", "recursive",
"versions", "deleted"];
+
+/// Render model for one field of the napi `ListOptions` object.
+#[derive(Serialize)]
+struct ListOptionsField {
+ /// snake_case name, as in core. napi exposes it in camelCase.
+ name: String,
+ /// Rust type of the napi field. napi-rs derives the TS type from it.
+ rs_type: &'static str,
+ /// The core doc comment, one entry per line.
+ doc: Vec<String>,
+}
+
+/// One field of the core `ListOptions` literal that the conversion builds.
+#[derive(Serialize)]
+struct ListOptionsConversion {
+ name: String,
+ /// Expression that reads the JS value from `value`.
+ expr: String,
+}
+
+/// Render `bindings/nodejs/src/options/list.rs` from the core `ListOptions`
+/// in `core/core/src/types/options.rs`.
+///
+/// `generated.d.ts` is derived from this file by `napi build`.
+fn generate_list_options(workspace_dir: &Path) -> Result<()> {
+ let source = workspace_dir.join("core/core/src/types/options.rs");
+ let rendered = render_list_options(&core_options::parse(&source)?)?;
+
+ let output = workspace_dir.join("bindings/nodejs/src/options/list.rs");
+ fs::write(output, format!("{rendered}\n"))?;
+ Ok(())
+}
+
+fn render_list_options(parsed: &[OptionsStruct]) -> Result<String> {
+ let Some(core) = parsed.iter().find(|options| options.name ==
"ListOptions") else {
+ bail!("core has no options struct `ListOptions`");
+ };
+
+ let mut fields = Vec::with_capacity(LIST_OPTIONS_FIELDS.len());
+ for &name in LIST_OPTIONS_FIELDS {
+ let Some(field) = core.fields.iter().find(|field| field.name == name)
else {
+ bail!("core ListOptions has no field `{name}`");
+ };
+ fields.push(ListOptionsField {
+ name: field.name.clone(),
+ rs_type: list_option_type(field)?.0,
+ doc: js_doc(&field.doc),
+ });
+ }
+
+ // List every core field instead of ending with `..Default::default()`, so
+ // a new core field fails to compile in the binding until this file is
+ // regenerated, and the regenerated conversion shows it as unexposed.
+ let mut conversions = Vec::with_capacity(core.fields.len());
+ for field in &core.fields {
+ let exposed = LIST_OPTIONS_FIELDS.contains(&field.name.as_str());
+ let expr = if exposed {
+ list_option_type(field)?.1
+ } else {
+ "Default::default()".to_string()
+ };
+ conversions.push(ListOptionsConversion {
+ name: field.name.clone(),
+ expr,
+ });
+ }
+
+ let mut env = Environment::new();
+ env.add_template("list_rs", include_str!("nodejs/list_options_rs.j2"))?;
+ Ok(env.get_template("list_rs")?.render(context! {
+ doc => js_doc(&core.doc),
+ fields => Serde(&fields),
+ conversions => Serde(&conversions),
+ has_unmirrored_fields => core.has_unmirrored_fields,
+ })?)
+}
+
+/// The napi type of an exposed core `ListOptions` field and the expression
+/// that converts it back.
+///
+/// These keep the types the binding used before codegen: `limit` is a
+/// `number` read as `u32`, so an explicit `0` reaches core as `Some(0)`, and
+/// an omitted boolean is `false`.
+fn list_option_type(field: &OptionField) -> Result<(&'static str, String)> {
+ let name = &field.name;
+ Ok(match field.kind {
+ OptionKind::OptionUsize => ("Option<u32>",
format!("value.{name}.map(|v| v as usize)")),
+ OptionKind::OptionString => ("Option<String>",
format!("value.{name}")),
+ OptionKind::Bool => ("Option<bool>",
format!("value.{name}.unwrap_or_default()")),
+ kind => bail!("core ListOptions::{name} is {kind:?}, which has no JS
type yet"),
+ })
+}
+
+/// The core doc comment as it reads in JS. napi-rs copies it into
+/// `generated.d.ts`.
+///
+/// Rustdoc links become plain code spans, because JS documentation cannot
+/// resolve Rust paths:
``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
+/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span.
+fn js_doc(lines: &[String]) -> Vec<String> {
Review Comment:
(AI-generated reply)
Done in 73cf6cdf7. Code spans that name an exposed `ListOptions` field or a
core capability now use the Node.js name, whether core writes a plain code span
or a rustdoc link. The pagination line reads `` `limit`, `startAfter` ``, and
the field docs read `` `Capability.listWithStartAfter` `` (the getter on the
`Capability` that `op.capability()` returns). The camelCase comes from `heck`,
and I checked that it matches all 98 napi `Capability` getters. Only exposed
fields and real core capabilities are rewritten. Unknown paths such as
`crate::ErrorKind::Unsupported`, and prose, stay as written. In
`generated.d.ts` only the `ListOptions` JSDoc changes. With comments removed,
it is still byte-identical to `main`.
Tests: `test_list_options_docs_use_js_names` renders the real core
`ListOptions` and checks the plain-span `startAfter` and the rustdoc-link
`Capability.listWithStartAfter`. `test_js_doc_uses_js_names` covers plain
spans, both link forms, and names it must not rewrite. Each test fails if I
turn off the field rewrite or the capability rewrite.
The other four inline comments in your review no longer show on the PR, so
I'm answering them here. The same commit fixes all four:
- The table now pins each exposed field's core kind. With core `start_after`
changed to `bool`, `generate -l nodejs` exits with `core
ListOptions::start_after is Bool, but its JS type was chosen for OptionString`,
and a generator test covers that change.
- The surface test now requires every list method to succeed on `memory`;
there is no catch. Stubbing the four methods to throw `TypeError` fails 5
tests. The previous test passed 10/10 under that stub.
- The members are compared as an exact set with `sameMembers`. Adding
`glob?: string` fails the test. The previous test passed.
- The generator creates `src/options/` before writing. With the directory
moved aside, generation recreates an identical `list.rs`. Without the fix it
fails with ENOENT.
Translating names across the other bindings is tracked in #9334.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]