server-less-core 0.5.0

Core traits and types for server-less derive macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Core traits and types for server-less.
//!
//! This crate provides the foundational types that server-less macros generate code against.

pub mod error;
pub mod extract;
#[cfg(feature = "config")]
pub mod config;

/// Re-export of `toml` for use by `#[derive(Config)]`-generated code.
///
/// Generated serde-nested deserialization code references `toml::de::Error`
/// via this path so callers don't need to add `toml` to their own dependencies.
#[cfg(feature = "config")]
#[doc(hidden)]
pub use toml as __toml;

pub use error::{
    ErrorCode, ErrorResponse, HttpStatusFallback, HttpStatusHelper, IntoErrorCode,
    SchemaValidationError,
};
pub use extract::Context;

#[cfg(feature = "ws")]
pub use extract::WsSender;

/// One node in a CLI "manual": the reference entry for a single command path.
///
/// The manual is the whole-subtree aggregate emitted by the `--manual` flag.
/// Each leaf command in the tree contributes one `CliManualNode`; mount points
/// contribute the nodes of their subtree (recursively), with the path prefixed.
///
/// This is a serializable data structure (not a closure or scraped runtime
/// state), so the manual caches, transports, and diffs cleanly. The `--manual`
/// rendering layer turns a `Vec<CliManualNode>` into either human-readable text
/// or a path-keyed JSON object.
#[cfg(feature = "cli")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct CliManualNode {
    /// Space-separated command path from the root of the *invoked* subtree,
    /// e.g. `"edit history list"`. The root subtree's own node (if it has a
    /// default action) uses the empty string.
    pub path: String,
    /// The command's description (first paragraph of its doc comment), if any.
    pub description: Option<String>,
    /// JSON Schema of the command's input parameters.
    pub input_schema: serde_json::Value,
    /// JSON Schema of the command's return type.
    pub output_schema: serde_json::Value,
}

/// Render a flat list of manual nodes as a path-keyed JSON object.
///
/// This is the structured (`--manual --json` / `--jq`) shape: one key per
/// command path, each value carrying `description`, `input_schema`, and
/// `output_schema`. Used by `#[cli]`-generated `--manual` handling.
#[cfg(feature = "cli")]
pub fn cli_manual_to_json(nodes: &[CliManualNode]) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    for node in nodes {
        map.insert(
            node.path.clone(),
            serde_json::json!({
                "description": node.description,
                "input_schema": node.input_schema,
                "output_schema": node.output_schema,
            }),
        );
    }
    serde_json::Value::Object(map)
}

/// Render a flat list of manual nodes as human-readable reference text.
///
/// This is the default (`--manual` with no format flag) shape: a markdown-ish
/// reference page, one section per command path. Used by `#[cli]`-generated
/// `--manual` handling.
#[cfg(feature = "cli")]
pub fn cli_manual_to_text(nodes: &[CliManualNode]) -> String {
    let mut out = String::new();
    for (i, node) in nodes.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        let heading = if node.path.is_empty() {
            "(default)"
        } else {
            node.path.as_str()
        };
        out.push_str(&format!("# {heading}\n"));
        if let Some(desc) = &node.description
            && !desc.is_empty()
        {
            out.push_str(&format!("\n{desc}\n"));
        }
        if let Some(props) = node
            .input_schema
            .get("properties")
            .and_then(|p| p.as_object())
            && !props.is_empty()
        {
            out.push_str("\nParameters:\n");
            let required: std::collections::HashSet<&str> = node
                .input_schema
                .get("required")
                .and_then(|r| r.as_array())
                .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
                .unwrap_or_default();
            for (name, schema) in props {
                let ty = schema
                    .get("type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("value");
                let req = if required.contains(name.as_str()) {
                    " (required)"
                } else {
                    ""
                };
                out.push_str(&format!("  {name}: {ty}{req}\n"));
            }
        }
    }
    out
}

/// Trait for types that can be mounted as CLI subcommand groups.
///
/// Implemented automatically by `#[cli]` on an impl block. Allows nested
/// composition: a parent CLI can mount a child's commands as a subcommand group.
#[cfg(feature = "cli")]
pub trait CliSubcommand {
    /// Build the clap Command tree for this type's subcommands.
    fn cli_command() -> ::clap::Command;

    /// Collect the manual (whole-subtree reference) nodes for this type.
    ///
    /// `prefix` is the command path of *this* node from the root of the invoked
    /// subtree (empty at the invocation root). Each leaf appends one node; each
    /// mount point recurses into its child type with an extended prefix.
    ///
    /// The default returns an empty vec so hand-written `CliSubcommand` impls
    /// keep compiling; `#[cli]` always overrides it.
    fn cli_manual_nodes(&self, _prefix: &str) -> Vec<CliManualNode> {
        Vec::new()
    }

    /// Dispatch a matched subcommand to the appropriate method.
    fn cli_dispatch(&self, matches: &::clap::ArgMatches) -> Result<(), Box<dyn std::error::Error>>;

    /// Dispatch a matched subcommand asynchronously.
    ///
    /// Awaits the dispatched method directly without creating an internal runtime.
    /// Used by `cli_run_async` to support user-provided async runtimes.
    fn cli_dispatch_async<'a>(
        &'a self,
        matches: &'a ::clap::ArgMatches,
    ) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> + 'a {
        async move { self.cli_dispatch(matches) }
    }
}

/// Trait for types that can be mounted as MCP tool namespaces.
///
/// Implemented automatically by `#[mcp]` on an impl block. Allows nested
/// composition: a parent MCP server can mount a child's tools with a name prefix.
#[cfg(feature = "mcp")]
pub trait McpNamespace {
    /// Get tool definitions for this namespace.
    fn mcp_namespace_tools() -> Vec<serde_json::Value>;

    /// Get tool names for this namespace (without prefix).
    fn mcp_namespace_tool_names() -> Vec<String>;

    /// Call a tool by name (sync). Returns error for async-only methods.
    fn mcp_namespace_call(
        &self,
        name: &str,
        args: serde_json::Value,
    ) -> Result<serde_json::Value, String>;

    /// Call a tool by name (async).
    fn mcp_namespace_call_async(
        &self,
        name: &str,
        args: serde_json::Value,
    ) -> impl std::future::Future<Output = Result<serde_json::Value, String>> + Send;
}

/// Trait for types that can be mounted as JSON-RPC method namespaces.
///
/// Implemented automatically by `#[jsonrpc]` on an impl block. Allows nested
/// composition: a parent JSON-RPC server can mount a child's methods with a dot-separated prefix.
#[cfg(feature = "jsonrpc")]
pub trait JsonRpcMount {
    /// Get method names for this mount (without prefix).
    fn jsonrpc_mount_methods() -> Vec<String>;

    /// Dispatch a method call (sync). Returns error for async-only methods.
    fn jsonrpc_mount_dispatch(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value, String>;

    /// Dispatch a method call (async).
    fn jsonrpc_mount_dispatch_async(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> impl std::future::Future<Output = Result<serde_json::Value, String>> + Send;
}

/// Trait for types that can be mounted as WebSocket method namespaces.
///
/// Implemented automatically by `#[ws]` on an impl block. Allows nested
/// composition: a parent WebSocket server can mount a child's methods with a dot-separated prefix.
#[cfg(feature = "ws")]
pub trait WsMount {
    /// Get method names for this mount (without prefix).
    fn ws_mount_methods() -> Vec<String>;

    /// Dispatch a method call (sync). Returns error for async-only methods.
    fn ws_mount_dispatch(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value, String>;

    /// Dispatch a method call (async).
    fn ws_mount_dispatch_async(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> impl std::future::Future<Output = Result<serde_json::Value, String>> + Send;
}

/// Trait for types that can be mounted as HTTP route groups.
///
/// Implemented automatically by `#[http]` on an impl block. Allows nested
/// composition: a parent HTTP server can mount a child's routes under a path prefix.
#[cfg(feature = "http")]
pub trait HttpMount: Send + Sync + 'static {
    /// Build an axum Router for this mount's routes.
    fn http_mount_router(self: ::std::sync::Arc<Self>) -> ::axum::Router;

    /// Get full OpenAPI path definitions for this mount (including any nested mounts).
    ///
    /// Paths are relative to the mount point. The parent prefixes them when composing.
    fn http_mount_openapi_paths() -> Vec<server_less_openapi::OpenApiPath>
    where
        Self: Sized;
}

/// Format a `serde_json::Value` according to the active JSON output flag.
///
/// This function is only called when at least one JSON flag is active
/// (`--json`, `--jsonl`, or `--jq`). The overall CLI default output path
/// (human-readable `Display` text) is generated directly by the `#[cli]`
/// macro and does not go through this function.
///
/// Flag precedence (first match wins):
///
/// - `jq`: filter the value using jaq (jq implemented in Rust, no external binary needed)
/// - `jsonl`: one compact JSON object per line (arrays are unwrapped; non-arrays emit a single line)
/// - `json` (`true`): compact JSON — `serde_json::to_string`, no whitespace
/// - `json` (`false`) with no other flag active: pretty-printed JSON — only reachable when called
///   directly, not from `#[cli]`-generated code (which always sets at least one flag)
#[cfg(feature = "cli")]
pub fn cli_format_output(
    value: serde_json::Value,
    jsonl: bool,
    json: bool,
    jq: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
    if let Some(filter) = jq {
        use jaq_core::load::{Arena, File as JaqFile, Loader};
        use jaq_core::{Compiler, Ctx, Vars, data, unwrap_valr};
        use jaq_json::Val;

        let loader =
            Loader::new(jaq_core::defs().chain(jaq_std::defs()).chain(jaq_json::defs()));
        let arena = Arena::default();

        let program = JaqFile {
            code: filter,
            path: (),
        };

        let modules = loader
            .load(&arena, program)
            .map_err(|errs| format!("jq parse error: {:?}", errs))?;

        let filter_compiled = Compiler::default()
            .with_funs(jaq_core::funs().chain(jaq_std::funs()).chain(jaq_json::funs()))
            .compile(modules)
            .map_err(|errs| format!("jq compile error: {:?}", errs))?;

        let val: Val = serde_json::from_value(value)?;
        let ctx = Ctx::<data::JustLut<Val>>::new(&filter_compiled.lut, Vars::new([]));
        let out = filter_compiled.id.run((ctx, val)).map(unwrap_valr);

        let mut results = Vec::new();
        for result in out {
            match result {
                Ok(v) => results.push(v.to_string()),
                Err(e) => return Err(format!("jq runtime error: {:?}", e).into()),
            }
        }

        Ok(results.join("\n"))
    } else if jsonl {
        match value {
            serde_json::Value::Array(items) => {
                let lines: Vec<String> = items
                    .iter()
                    .map(serde_json::to_string)
                    .collect::<Result<_, _>>()?;
                Ok(lines.join("\n"))
            }
            other => Ok(serde_json::to_string(&other)?),
        }
    } else if json {
        Ok(serde_json::to_string(&value)?)
    } else {
        Ok(serde_json::to_string_pretty(&value)?)
    }
}

/// Generate a JSON Schema for a type at runtime using schemars.
///
/// Called by `--output-schema` in `#[cli]`-generated code when the `jsonschema`
/// feature is enabled. Users must `#[derive(schemars::JsonSchema)]` on their
/// return types to use this.
#[cfg(feature = "jsonschema")]
pub fn cli_schema_for<T: schemars::JsonSchema>() -> serde_json::Value {
    serde_json::to_value(schemars::schema_for!(T))
        .unwrap_or_else(|_| serde_json::json!({"type": "object"}))
}

/// A clap [`TypedValueParser`] that uses [`schemars::JsonSchema`] to surface
/// enum variants as possible values, and [`std::str::FromStr`] for actual parsing.
///
/// When `T` is an enum deriving `JsonSchema`, its variants appear in `--help`
/// output and clap's error messages with no extra derives on the user type.
/// For non-enum types (e.g. `String`, `u32`), this is a transparent pass-through
/// to `FromStr`.
///
/// Used automatically by `#[cli]`-generated code when both the `cli` and
/// `jsonschema` features are enabled.
#[cfg(all(feature = "cli", feature = "jsonschema"))]
#[derive(Clone)]
pub struct SchemaValueParser<T: Clone + Send + Sync + 'static> {
    /// Enum variant names as `'static` str. We leak each string once at
    /// parser-construction time (command build, not per-parse), which is
    /// acceptable for a CLI binary: the leak is bounded (a few bytes per
    /// variant) and the memory is reclaimed when the process exits.
    variants: Option<std::sync::Arc<[&'static str]>>,
    _marker: std::marker::PhantomData<T>,
}

#[cfg(all(feature = "cli", feature = "jsonschema"))]
impl<T> Default for SchemaValueParser<T>
where
    T: schemars::JsonSchema + std::str::FromStr + Clone + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(feature = "cli", feature = "jsonschema"))]
impl<T> SchemaValueParser<T>
where
    T: schemars::JsonSchema + std::str::FromStr + Clone + Send + Sync + 'static,
{
    /// Creates a new `SchemaValueParser`, extracting allowed enum variants if available.
    pub fn new() -> Self {
        let variants = extract_enum_variants::<T>().map(|strings| {
            let leaked: Vec<&'static str> = strings
                .into_iter()
                .map(|s| Box::leak(s.into_boxed_str()) as &'static str)
                .collect();
            leaked.into()
        });
        Self {
            variants,
            _marker: std::marker::PhantomData,
        }
    }
}

#[cfg(all(feature = "cli", feature = "jsonschema"))]
fn extract_enum_variants<T: schemars::JsonSchema>() -> Option<Vec<String>> {
    let schema_value = serde_json::to_value(schemars::schema_for!(T)).ok()?;
    let enum_values = schema_value.get("enum")?.as_array()?;
    let variants: Vec<String> = enum_values
        .iter()
        .filter_map(|v| v.as_str().map(String::from))
        .collect();
    if variants.is_empty() {
        None
    } else {
        Some(variants)
    }
}

#[cfg(all(feature = "cli", feature = "jsonschema"))]
impl<T> ::clap::builder::TypedValueParser for SchemaValueParser<T>
where
    T: schemars::JsonSchema + std::str::FromStr + Clone + Send + Sync + 'static,
    <T as std::str::FromStr>::Err: std::fmt::Display,
{
    type Value = T;

    fn parse_ref(
        &self,
        _cmd: &::clap::Command,
        _arg: Option<&::clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<T, ::clap::Error> {
        let s = value
            .to_str()
            .ok_or_else(|| ::clap::Error::new(::clap::error::ErrorKind::InvalidUtf8))?;
        s.parse::<T>()
            .map_err(|e| ::clap::Error::raw(::clap::error::ErrorKind::ValueValidation, e))
    }

    fn possible_values(&self) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
        self.variants.as_ref().map(|variants| {
            let v: Vec<_> = variants
                .iter()
                .map(|s| clap::builder::PossibleValue::new(*s))
                .collect();
            Box::new(v.into_iter()) as Box<dyn Iterator<Item = clap::builder::PossibleValue>>
        })
    }
}

/// Runtime method metadata with string-based types.
///
/// This is a simplified, serialization-friendly representation of method
/// information intended for runtime introspection and tooling. Types are
/// stored as strings rather than `syn` AST nodes.
///
/// **Not to be confused with [`server_less_parse::MethodInfo`]**, which is
/// the richer, `syn`-based representation used internally by proc macros
/// during code generation. The parse version retains full type information
/// (`syn::Type`, `syn::Ident`) and supports `#[param(...)]` attributes.
#[derive(Debug, Clone)]
pub struct MethodInfo {
    /// Method name (e.g., "create_user")
    pub name: String,
    /// Documentation string from /// comments
    pub docs: Option<String>,
    /// Parameter names and their type strings
    pub params: Vec<ParamInfo>,
    /// Return type string
    pub return_type: String,
    /// Whether the method is async
    pub is_async: bool,
    /// Whether the return type is a Stream
    pub is_streaming: bool,
    /// Whether the return type is `Option<T>`
    pub is_optional: bool,
    /// Whether the return type is `Result<T, E>`
    pub is_result: bool,
    /// Group display name for categorization
    pub group: Option<String>,
}

/// Runtime parameter metadata with string-based types.
///
/// See [`MethodInfo`] for the relationship between this type and
/// `server_less_parse::ParamInfo`.
#[derive(Debug, Clone)]
pub struct ParamInfo {
    /// Parameter name
    pub name: String,
    /// Type as string
    pub ty: String,
    /// Whether this is an `Option<T>`
    pub is_optional: bool,
    /// Whether this looks like an ID parameter (ends with _id or is named id)
    pub is_id: bool,
}

/// Runtime HTTP method enum used in generated introspection code.
///
/// See also [`server_less_parse::HttpMethod`] for the compile-time equivalent used
/// by proc macros during code generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
}

impl HttpMethod {
    /// Infer HTTP method from function name prefix
    pub fn infer_from_name(name: &str) -> Self {
        if name.starts_with("get_")
            || name.starts_with("fetch_")
            || name.starts_with("read_")
            || name.starts_with("list_")
            || name.starts_with("find_")
            || name.starts_with("search_")
        {
            HttpMethod::Get
        } else if name.starts_with("create_")
            || name.starts_with("add_")
            || name.starts_with("new_")
        {
            HttpMethod::Post
        } else if name.starts_with("update_") || name.starts_with("set_") {
            HttpMethod::Put
        } else if name.starts_with("patch_") || name.starts_with("modify_") {
            HttpMethod::Patch
        } else if name.starts_with("delete_") || name.starts_with("remove_") {
            HttpMethod::Delete
        } else {
            // Default to POST for RPC-style methods
            HttpMethod::Post
        }
    }

    /// Returns the HTTP method as an uppercase string slice (e.g. `"GET"`, `"POST"`).
    pub fn as_str(&self) -> &'static str {
        match self {
            HttpMethod::Get => "GET",
            HttpMethod::Post => "POST",
            HttpMethod::Put => "PUT",
            HttpMethod::Patch => "PATCH",
            HttpMethod::Delete => "DELETE",
        }
    }
}

/// Pluralize an English word using common rules.
///
/// Rules applied in order:
/// - Already ends in `s`, `x`, `z`, `ch`, or `sh` → append `es`
/// - Ends in a consonant followed by `y` → replace `y` with `ies`
/// - Everything else → append `s`
fn pluralize(word: &str) -> String {
    if word.ends_with('s')
        || word.ends_with('x')
        || word.ends_with('z')
        || word.ends_with("ch")
        || word.ends_with("sh")
    {
        format!("{word}es")
    } else if word.ends_with('y')
        && word.len() >= 2
        && !matches!(
            word.as_bytes()[word.len() - 2],
            b'a' | b'e' | b'i' | b'o' | b'u'
        )
    {
        // consonant + y → drop y, add ies
        format!("{}ies", &word[..word.len() - 1])
    } else {
        format!("{word}s")
    }
}

/// Infer a REST path from a method name and HTTP method.
///
/// This is the runtime version used in generated introspection code. It does not
/// have access to parameter information, so it cannot infer `/{id}` paths contextually.
/// See `server_less_parse` (or `server_less_macros::openapi_gen`) for the richer
/// compile-time version that uses parameter names to infer `/{id}` paths.
pub fn infer_path(method_name: &str, http_method: HttpMethod) -> String {
    // Strip common prefixes to get the resource name
    let resource = method_name
        .strip_prefix("get_")
        .or_else(|| method_name.strip_prefix("fetch_"))
        .or_else(|| method_name.strip_prefix("read_"))
        .or_else(|| method_name.strip_prefix("list_"))
        .or_else(|| method_name.strip_prefix("find_"))
        .or_else(|| method_name.strip_prefix("search_"))
        .or_else(|| method_name.strip_prefix("create_"))
        .or_else(|| method_name.strip_prefix("add_"))
        .or_else(|| method_name.strip_prefix("new_"))
        .or_else(|| method_name.strip_prefix("update_"))
        .or_else(|| method_name.strip_prefix("set_"))
        .or_else(|| method_name.strip_prefix("patch_"))
        .or_else(|| method_name.strip_prefix("modify_"))
        .or_else(|| method_name.strip_prefix("delete_"))
        .or_else(|| method_name.strip_prefix("remove_"))
        .unwrap_or(method_name);

    // Pluralize for collection endpoints.
    // If the resource already ends in 's' it is likely already plural (e.g. the
    // caller wrote `list_users` and we stripped the prefix to get "users").
    // For singular forms we apply English pluralization rules.
    let path_resource = if resource.ends_with('s') {
        resource.to_string()
    } else {
        pluralize(resource)
    };

    match http_method {
        // Collection operations
        HttpMethod::Post => format!("/{path_resource}"),
        HttpMethod::Get
            if method_name.starts_with("list_")
                || method_name.starts_with("search_")
                || method_name.starts_with("find_") =>
        {
            format!("/{path_resource}")
        }
        // Single resource operations
        HttpMethod::Get | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete => {
            format!("/{path_resource}/{{id}}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pluralize() {
        // ends in s/x/z/ch/sh → add es
        assert_eq!(pluralize("index"), "indexes");
        assert_eq!(pluralize("status"), "statuses");
        assert_eq!(pluralize("match"), "matches");
        assert_eq!(pluralize("box"), "boxes");
        assert_eq!(pluralize("buzz"), "buzzes");
        assert_eq!(pluralize("brush"), "brushes");
        // consonant + y → ies
        assert_eq!(pluralize("query"), "queries");
        // vowel + y → plain s (key, day, …)
        assert_eq!(pluralize("key"), "keys");
        // default → add s
        assert_eq!(pluralize("item"), "items");
    }

    #[test]
    fn test_http_method_inference() {
        assert_eq!(HttpMethod::infer_from_name("get_user"), HttpMethod::Get);
        assert_eq!(HttpMethod::infer_from_name("list_users"), HttpMethod::Get);
        assert_eq!(HttpMethod::infer_from_name("create_user"), HttpMethod::Post);
        assert_eq!(HttpMethod::infer_from_name("update_user"), HttpMethod::Put);
        assert_eq!(
            HttpMethod::infer_from_name("delete_user"),
            HttpMethod::Delete
        );
        assert_eq!(
            HttpMethod::infer_from_name("do_something"),
            HttpMethod::Post
        ); // RPC fallback
    }

    #[test]
    fn test_path_inference() {
        assert_eq!(infer_path("create_user", HttpMethod::Post), "/users");
        assert_eq!(infer_path("get_user", HttpMethod::Get), "/users/{id}");
        assert_eq!(infer_path("list_users", HttpMethod::Get), "/users");
        assert_eq!(infer_path("delete_user", HttpMethod::Delete), "/users/{id}");
    }
}