suyanhanx commented on code in PR #9333:
URL: https://github.com/apache/opendal/pull/9333#discussion_r4725692014
##########
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:
Could we render references to Node.js properties in lower camel case here?
The generated pagination docs tell callers to pass `start_after`, but napi-rs
reads `startAfter` from the JS options object. The same applies to capability
references: a caller checks `op.capability().listWithStartAfter`, while the
generated docs show `Capability::list_with_start_after`.
The pagination reference is already a plain code span in core, so it would
be good to cover both that case and a rustdoc capability link in the generator
test.
--
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]