diff --git a/backend/parsers/windmill-parser-ts/src/lib.rs b/backend/parsers/windmill-parser-ts/src/lib.rs index 8059851707..49b0a7cec2 100644 --- a/backend/parsers/windmill-parser-ts/src/lib.rs +++ b/backend/parsers/windmill-parser-ts/src/lib.rs @@ -14,6 +14,7 @@ use windmill_parser::{ Typ, }; +use swc_common::comments::{Comment, CommentKind, Comments, SingleThreadedComments}; use swc_common::{sync::Lrc, FileName, SourceMap, SourceMapper, Span, Spanned}; use swc_ecma_ast::{ ArrayLit, AssignPat, BigInt, BindingIdent, Bool, Decl, ExportDecl, Expr, ExprOrSpread, Ident, @@ -324,13 +325,16 @@ pub fn parse_deno_signature( ) -> anyhow::Result { let cm: Lrc = Default::default(); let fm = cm.new_source_file(FileName::Custom("main.ts".into()).into(), code.to_string()); + let comments = SingleThreadedComments::default(); let lexer = Lexer::new( // We want to parse ecmascript Syntax::Typescript(TsSyntax::default()), // EsVersion defaults to es5 Default::default(), StringInput::from(&*fm), - None, + // Comments only feed the JSDoc descriptions of a schema. Callers that skip + // defaults run on every job and never build one, so they skip collecting them. + (!skip_dflt).then_some(&comments), ); let mut parser = Parser::new_from(lexer); @@ -341,6 +345,7 @@ pub fn parse_deno_signature( } let mut has_preprocessor = false; + let mut param_docs = HashMap::new(); let mut entrypoint_params = None; let mut is_wac = false; @@ -356,6 +361,7 @@ pub fn parse_deno_signature( let mut symbol_table: HashMap = HashMap::new(); for item in ast { + let item_lo = item.span_lo(); // Check for named exports (e.g., export { preprocessor } from "./other") if let ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named_export)) = &item { if !has_preprocessor { @@ -419,6 +425,7 @@ pub fn parse_deno_signature( } if name == entrypoint_function { entrypoint_params = Some(fn_decl.function.params.clone()); + param_docs = jsdoc_params(comments.get_leading(item_lo)); } } Decl::Var(var_decl) if entrypoint_params.is_none() => { @@ -466,14 +473,17 @@ pub fn parse_deno_signature( param .into_iter() .map(|param| { - parse_param( + let mut arg = parse_param( &symbol_table, &mut type_resolver, param, &cm, skip_dflt, &mut c, - ) + )?; + // Like Python's docstring `Args:`, the description travels as `otyp`. + arg.otyp = arg.otyp.or_else(|| param_docs.remove(&arg.name)); + Ok(arg) }) .collect::>>() }) @@ -487,6 +497,30 @@ pub fn parse_deno_signature( Ok(r) } +/// `@param {type} name - text` lines of the entrypoint's JSDoc block, by parameter name. +/// A description continues on the next lines until a blank line or another tag. One with +/// both `[` and `|` is left out: as `otyp` it would read as a `T | T[]` union marker. +fn jsdoc_params(comments: Option>) -> HashMap { + let jsdoc = comments.and_then(|c| { + c.into_iter() + .rfind(|c| c.kind == CommentKind::Block && c.text.starts_with('*')) + }); + let (mut docs, mut last) = (HashMap::new(), None); + for line in jsdoc.iter().flat_map(|c| c.text.lines()) { + let line = line.trim().trim_start_matches('*').trim(); + if let Some(cap) = JSDOC_PARAM.captures(line) { + docs.insert(cap[1].to_string(), cap[2].to_string()); + last = Some(cap[1].to_string()); + } else if line.is_empty() || line.starts_with('@') { + last = None; + } else if let Some(doc) = last.as_ref().and_then(|n| docs.get_mut(n)) { + *doc = format!("{doc} {line}").trim_start().to_string(); + } + } + docs.retain(|_, d| !d.is_empty() && !(d.contains('[') && d.contains('|'))); + docs +} + /// Extract params from `workflow(async (...) => { ... })` or `workflow(async function(...) { ... })` fn extract_workflow_params(expr: &Expr) -> Option> { if let Expr::Call(call) = expr { @@ -751,6 +785,7 @@ fn binding_ident_to_arg( } lazy_static::lazy_static! { + static ref JSDOC_PARAM: Regex = Regex::new(r"^@param\s+(?:\{.*?\}\s*)?\[?([\w$]+)(?:=[^\]]*)?\]?(?:\s+|$)(?:-\s+)?(.*)").unwrap(); static ref IMPORTS_VERSION: Regex = Regex::new(r"^((?:\@[^\/\@]+\/[^\/\@]+)|(?:[^\/\@]+))(?:\@(?:[^\/]+))?(.*)$").unwrap(); } diff --git a/backend/parsers/windmill-parser-ts/tests/tests.rs b/backend/parsers/windmill-parser-ts/tests/tests.rs index 8b9587d3a2..ffbac9c66a 100644 --- a/backend/parsers/windmill-parser-ts/tests/tests.rs +++ b/backend/parsers/windmill-parser-ts/tests/tests.rs @@ -1045,4 +1045,39 @@ export const label = "pkg@1.2.3"; ] ); } + + #[test] + fn test_parse_deno_sig_jsdoc_param_descriptions() { + let code = r#" +/** + * Greets someone. + * @param {string} name - Who to greet + * @param [times=1] How many + * times to say it + * @param missing Not a parameter + * @param ids One [id] | many + * @returns nothing + */ +export async function main(name: string, times = 1, tags: string | string[], plain: string, ids: string) {} +"#; + let sig = parse_deno_signature(code, false, false, None).unwrap(); + let otyps: Vec<_> = sig.args.iter().map(|a| a.otyp.as_deref()).collect(); + assert_eq!( + otyps, + vec![ + Some("Who to greet"), + Some("How many times to say it"), + Some("string | string[]"), + None, + None + ] + ); + // The job path (skip_dflt) does not read comments. + let sig = parse_deno_signature(code, true, false, None).unwrap(); + let otyps: Vec<_> = sig.args.iter().map(|a| a.otyp.as_deref()).collect(); + assert_eq!( + otyps, + vec![None, None, Some("string | string[]"), None, None] + ); + } } diff --git a/backend/parsers/windmill-parser/src/json_schema.rs b/backend/parsers/windmill-parser/src/json_schema.rs index 6ca216dd89..781d06a866 100644 --- a/backend/parsers/windmill-parser/src/json_schema.rs +++ b/backend/parsers/windmill-parser/src/json_schema.rs @@ -8,7 +8,12 @@ use crate::{MainArgSignature, ObjectProperty, Typ}; /// `previous` is the schema of the version being superseded: as in the editor, it is /// updated in place, so what the user set on it (argument order, descriptions, ...) /// survives wherever the code still agrees with it. -pub fn main_arg_schema(sig: &MainArgSignature, previous: Option<&Value>) -> Value { +/// `otyp_is_doc`: the parser passes an argument's description as `otyp` (Python, TypeScript). +pub fn main_arg_schema( + sig: &MainArgSignature, + previous: Option<&Value>, + otyp_is_doc: bool, +) -> Value { let mut schema = match previous { Some(Value::Object(p)) => p.clone(), _ => json!({ @@ -35,13 +40,22 @@ pub fn main_arg_schema(sig: &MainArgSignature, previous: Option<&Value>) -> Valu } apply_typ(&arg.typ, &mut prop); // `T | T[]` marks an argument debouncing accumulates into. - if let Some(otyp) = arg - .otyp - .as_deref() - .filter(|o| o.contains('[') && o.contains('|')) - { - prop.insert("originalType".into(), json!(otyp)); - } + match arg.otyp.as_deref() { + Some(o) if o.contains('[') && o.contains('|') => { + prop.insert("originalType".into(), json!(o)) + } + Some(o) + if otyp_is_doc + && !o.is_empty() + && prop + .get("description") + .and_then(Value::as_str) + .is_none_or(str::is_empty) => + { + prop.insert("description".into(), json!(o)) + } + _ => None, + }; match &arg.default { Some(d) => prop.insert("default".into(), d.clone()), None => prop.remove("default"), @@ -66,7 +80,9 @@ pub fn main_arg_schema(sig: &MainArgSignature, previous: Option<&Value>) -> Valu Value::Object(schema) } -/// Keys a user sets on a property in the schema editor, kept whatever the code says. +/// Keys a user sets on a property in the schema editor, kept whatever the code says. A +/// description documented in code (docstring `Args:`, JSDoc `@param`) only fills one that +/// is empty, never replaces it. const USER_FIELDS: &[&str] = &[ "description", "pattern", @@ -381,7 +397,7 @@ mod tests { "gone": {"type": "string"}, }, }); - let schema = main_arg_schema(&sig, Some(&previous)); + let schema = main_arg_schema(&sig, Some(&previous), false); assert_eq!(schema["order"], json!(["db", "n"])); assert_eq!(schema["required"], json!(["n", "db", "any"])); assert_eq!( @@ -399,4 +415,51 @@ mod tests { // Untyped in the code and new: any JSON value, as the editor stores it. assert_eq!(schema["properties"]["any"]["type"], ""); } + + #[test] + fn otyp_is_a_union_marker_or_a_description() { + let name = Arg { otyp: Some("Who to greet".into()), ..arg("name", Typ::Str(None), None) }; + let tags = + Arg { otyp: Some("string | string[]".into()), ..arg("tags", Typ::Unknown, None) }; + let sig = MainArgSignature { args: vec![name, tags], ..Default::default() }; + let schema = main_arg_schema(&sig, None, true); + assert_eq!(schema["properties"]["name"]["description"], "Who to greet"); + assert_eq!( + schema["properties"]["tags"]["originalType"], + "string | string[]" + ); + let schema = main_arg_schema(&sig, None, false); + assert_eq!(schema["properties"]["name"]["description"], ""); + } + + // A description from code only fills an empty one: a typed one is kept, even when + // the code documents the argument differently or with no text. + #[test] + fn a_doc_fills_an_empty_description_and_keeps_a_typed_one() { + let doc = + |name: &str, d: &str| Arg { otyp: Some(d.into()), ..arg(name, Typ::Str(None), None) }; + let sig = MainArgSignature { + args: vec![ + doc("typed", "from code"), + doc("blank", "from code"), + doc("empty_doc", ""), + ], + ..Default::default() + }; + let previous = json!({ + "type": "object", + "properties": { + "typed": {"type": "string", "description": "typed"}, + "blank": {"type": "string", "description": ""}, + "empty_doc": {"type": "string", "description": "typed too"}, + }, + }); + let schema = main_arg_schema(&sig, Some(&previous), true); + assert_eq!(schema["properties"]["typed"]["description"], "typed"); + assert_eq!(schema["properties"]["blank"]["description"], "from code"); + assert_eq!( + schema["properties"]["empty_doc"]["description"], + "typed too" + ); + } } diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index ce45c05bf6..f8159c22eb 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -1342,7 +1342,12 @@ pub fn infer_main_schema( }; match sig { Ok(sig) => serde_json::value::to_raw_value(&windmill_parser::json_schema::main_arg_schema( - &sig, previous, + &sig, + previous, + matches!( + language.as_str(), + "python3" | "deno" | "bun" | "bunnative" | "nativets" + ), )) .ok() .map(|v| Schema(sqlx::types::Json(v))), diff --git a/cli/src/utils/metadata.ts b/cli/src/utils/metadata.ts index 15c53043b9..711d510f96 100644 --- a/cli/src/utils/metadata.ts +++ b/cli/src/utils/metadata.ts @@ -983,8 +983,17 @@ export async function inferSchema( argSigToJsonSchemaType(arg.typ, currentSchema.properties[arg.name]); // For T | T[] detection for debouncing arg accumulation - if ((arg as any).otyp && (arg as any).otyp.includes('[') && (arg as any).otyp.includes('|')) { - currentSchema.properties[arg.name].originalType = (arg as any).otyp + const otyp: string | undefined = (arg as any).otyp; + if (otyp && otyp.includes("[") && otyp.includes("|")) { + currentSchema.properties[arg.name].originalType = otyp; + } else if ( + otyp && + !currentSchema.properties[arg.name].description && + ["python3", "deno", "bun", "bunnative", "nativets"].includes(language) + ) { + // Python docstring `Args:` and TS JSDoc `@param` text: the parsers pass it as `otyp`. + // It only fills an empty description, never replaces one typed in the schema. + currentSchema.properties[arg.name].description = otyp; } // Most languages cannot write a resource default in code, so one picked in the diff --git a/cli/test/generate_metadata_unit.test.ts b/cli/test/generate_metadata_unit.test.ts index 55962d611a..77a35c2618 100644 --- a/cli/test/generate_metadata_unit.test.ts +++ b/cli/test/generate_metadata_unit.test.ts @@ -252,3 +252,21 @@ describe("generate-metadata keeps schema defaults code cannot express", () => { expect(result.schema.properties.n.default).toEqual(1); }); }); + +test("generate-metadata fills empty argument descriptions from a Python docstring", async () => { + const content = `def main(name: str, n: int = 1, blank: str = ""):\n """Greets.\n\n Args:\n name: Who to greet\n n: from code\n blank: from code too\n """\n return name\n`; + const result = await inferSchema( + "python3", + content, + { + properties: { + n: { type: "integer", description: "typed in the editor" }, + blank: { type: "string", description: "" }, + }, + }, + "test.py" + ); + expect(result.schema.properties.name.description).toEqual("Who to greet"); + expect(result.schema.properties.n.description).toEqual("typed in the editor"); + expect(result.schema.properties.blank.description).toEqual("from code too"); +}); diff --git a/frontend/src/lib/infer.ts b/frontend/src/lib/infer.ts index 3d90179b92..c39c95be79 100644 --- a/frontend/src/lib/infer.ts +++ b/frontend/src/lib/infer.ts @@ -571,8 +571,22 @@ export async function inferArgs( argSigToJsonSchemaType(arg.typ, schema.properties[arg.name]) // For T | T[] detection for debouncing arg accumulation - if ((arg as any).otyp && (arg as any).otyp.includes('[') && (arg as any).otyp.includes('|')) { - schema.properties[arg.name].originalType = (arg as any).otyp + const otyp: string | undefined = (arg as any).otyp + if (otyp && otyp.includes('[') && otyp.includes('|')) { + schema.properties[arg.name].originalType = otyp + } else if ( + otyp && + ['python3', 'deno', 'bun', 'bunnative', 'nativets'].includes(language ?? '') + ) { + // Python docstring `Args:` and TS JSDoc `@param` text: the parsers pass it as `otyp`. + // It only fills an empty description, never replaces one typed in the schema. This + // runs on every edit of the live schema, so a description the previous run filled + // from the doc still follows it: otherwise it would freeze at the first keystroke. + const current = schema.properties[arg.name].description + const previousDoc = (lastRun?.[1]?.args.find((a) => a.name == arg.name) as any)?.otyp + if (!current || current === previousDoc) { + schema.properties[arg.name].description = otyp + } } // Most languages cannot write a resource default in code, so one picked in the