spikard 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -386
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +221 -221
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +360 -360
  23. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  24. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  25. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  26. data/vendor/crates/spikard-core/src/debug.rs +63 -63
  27. data/vendor/crates/spikard-core/src/di/container.rs +726 -726
  28. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  29. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  30. data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
  31. data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
  32. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  33. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
  34. data/vendor/crates/spikard-core/src/di/value.rs +283 -283
  35. data/vendor/crates/spikard-core/src/errors.rs +39 -39
  36. data/vendor/crates/spikard-core/src/http.rs +153 -153
  37. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  38. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
  39. data/vendor/crates/spikard-core/src/parameters.rs +722 -722
  40. data/vendor/crates/spikard-core/src/problem.rs +310 -310
  41. data/vendor/crates/spikard-core/src/request_data.rs +189 -189
  42. data/vendor/crates/spikard-core/src/router.rs +249 -249
  43. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  44. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  45. data/vendor/crates/spikard-core/src/validation.rs +699 -699
  46. data/vendor/crates/spikard-http/Cargo.toml +58 -58
  47. data/vendor/crates/spikard-http/src/auth.rs +247 -247
  48. data/vendor/crates/spikard-http/src/background.rs +249 -249
  49. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  50. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  51. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  52. data/vendor/crates/spikard-http/src/cors.rs +490 -490
  53. data/vendor/crates/spikard-http/src/debug.rs +63 -63
  54. data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
  55. data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
  56. data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
  57. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
  58. data/vendor/crates/spikard-http/src/lib.rs +529 -529
  59. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
  60. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
  61. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
  62. data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
  63. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
  64. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
  65. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  66. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  67. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
  68. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
  69. data/vendor/crates/spikard-http/src/parameters.rs +1 -1
  70. data/vendor/crates/spikard-http/src/problem.rs +1 -1
  71. data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
  72. data/vendor/crates/spikard-http/src/response.rs +399 -399
  73. data/vendor/crates/spikard-http/src/router.rs +1 -1
  74. data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
  75. data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
  76. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
  77. data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
  78. data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
  79. data/vendor/crates/spikard-http/src/sse.rs +447 -447
  80. data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
  81. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  82. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
  83. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  84. data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
  85. data/vendor/crates/spikard-http/src/validation.rs +1 -1
  86. data/vendor/crates/spikard-http/src/websocket.rs +324 -324
  87. data/vendor/crates/spikard-rb/Cargo.toml +42 -42
  88. data/vendor/crates/spikard-rb/build.rs +8 -8
  89. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  90. data/vendor/crates/spikard-rb/src/config.rs +294 -294
  91. data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
  92. data/vendor/crates/spikard-rb/src/di.rs +409 -409
  93. data/vendor/crates/spikard-rb/src/handler.rs +625 -625
  94. data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
  95. data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
  96. data/vendor/crates/spikard-rb/src/server.rs +283 -283
  97. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  98. data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
  99. data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
  100. data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
  101. data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
  102. data/vendor/spikard-core/Cargo.toml +40 -40
  103. data/vendor/spikard-core/src/bindings/mod.rs +3 -3
  104. data/vendor/spikard-core/src/bindings/response.rs +133 -133
  105. data/vendor/spikard-core/src/debug.rs +63 -63
  106. data/vendor/spikard-core/src/di/container.rs +726 -726
  107. data/vendor/spikard-core/src/di/dependency.rs +273 -273
  108. data/vendor/spikard-core/src/di/error.rs +118 -118
  109. data/vendor/spikard-core/src/di/factory.rs +538 -538
  110. data/vendor/spikard-core/src/di/graph.rs +545 -545
  111. data/vendor/spikard-core/src/di/mod.rs +192 -192
  112. data/vendor/spikard-core/src/di/resolved.rs +411 -411
  113. data/vendor/spikard-core/src/di/value.rs +283 -283
  114. data/vendor/spikard-core/src/http.rs +153 -153
  115. data/vendor/spikard-core/src/lib.rs +28 -28
  116. data/vendor/spikard-core/src/lifecycle.rs +422 -422
  117. data/vendor/spikard-core/src/parameters.rs +719 -719
  118. data/vendor/spikard-core/src/problem.rs +310 -310
  119. data/vendor/spikard-core/src/request_data.rs +189 -189
  120. data/vendor/spikard-core/src/router.rs +249 -249
  121. data/vendor/spikard-core/src/schema_registry.rs +183 -183
  122. data/vendor/spikard-core/src/type_hints.rs +304 -304
  123. data/vendor/spikard-core/src/validation.rs +699 -699
  124. data/vendor/spikard-http/Cargo.toml +58 -58
  125. data/vendor/spikard-http/src/auth.rs +247 -247
  126. data/vendor/spikard-http/src/background.rs +249 -249
  127. data/vendor/spikard-http/src/bindings/mod.rs +3 -3
  128. data/vendor/spikard-http/src/bindings/response.rs +1 -1
  129. data/vendor/spikard-http/src/body_metadata.rs +8 -8
  130. data/vendor/spikard-http/src/cors.rs +490 -490
  131. data/vendor/spikard-http/src/debug.rs +63 -63
  132. data/vendor/spikard-http/src/di_handler.rs +423 -423
  133. data/vendor/spikard-http/src/handler_response.rs +190 -190
  134. data/vendor/spikard-http/src/handler_trait.rs +228 -228
  135. data/vendor/spikard-http/src/handler_trait_tests.rs +284 -284
  136. data/vendor/spikard-http/src/lib.rs +529 -529
  137. data/vendor/spikard-http/src/lifecycle/adapter.rs +149 -149
  138. data/vendor/spikard-http/src/lifecycle.rs +428 -428
  139. data/vendor/spikard-http/src/middleware/mod.rs +285 -285
  140. data/vendor/spikard-http/src/middleware/multipart.rs +86 -86
  141. data/vendor/spikard-http/src/middleware/urlencoded.rs +147 -147
  142. data/vendor/spikard-http/src/middleware/validation.rs +287 -287
  143. data/vendor/spikard-http/src/openapi/mod.rs +309 -309
  144. data/vendor/spikard-http/src/openapi/parameter_extraction.rs +190 -190
  145. data/vendor/spikard-http/src/openapi/schema_conversion.rs +308 -308
  146. data/vendor/spikard-http/src/openapi/spec_generation.rs +195 -195
  147. data/vendor/spikard-http/src/parameters.rs +1 -1
  148. data/vendor/spikard-http/src/problem.rs +1 -1
  149. data/vendor/spikard-http/src/query_parser.rs +369 -369
  150. data/vendor/spikard-http/src/response.rs +399 -399
  151. data/vendor/spikard-http/src/router.rs +1 -1
  152. data/vendor/spikard-http/src/schema_registry.rs +1 -1
  153. data/vendor/spikard-http/src/server/handler.rs +80 -80
  154. data/vendor/spikard-http/src/server/lifecycle_execution.rs +98 -98
  155. data/vendor/spikard-http/src/server/mod.rs +805 -805
  156. data/vendor/spikard-http/src/server/request_extraction.rs +119 -119
  157. data/vendor/spikard-http/src/sse.rs +447 -447
  158. data/vendor/spikard-http/src/testing/form.rs +14 -14
  159. data/vendor/spikard-http/src/testing/multipart.rs +60 -60
  160. data/vendor/spikard-http/src/testing/test_client.rs +285 -285
  161. data/vendor/spikard-http/src/testing.rs +377 -377
  162. data/vendor/spikard-http/src/type_hints.rs +1 -1
  163. data/vendor/spikard-http/src/validation.rs +1 -1
  164. data/vendor/spikard-http/src/websocket.rs +324 -324
  165. data/vendor/spikard-rb/Cargo.toml +42 -42
  166. data/vendor/spikard-rb/build.rs +8 -8
  167. data/vendor/spikard-rb/src/background.rs +63 -63
  168. data/vendor/spikard-rb/src/config.rs +294 -294
  169. data/vendor/spikard-rb/src/conversion.rs +392 -392
  170. data/vendor/spikard-rb/src/di.rs +409 -409
  171. data/vendor/spikard-rb/src/handler.rs +534 -534
  172. data/vendor/spikard-rb/src/lib.rs +2020 -2020
  173. data/vendor/spikard-rb/src/lifecycle.rs +267 -267
  174. data/vendor/spikard-rb/src/server.rs +283 -283
  175. data/vendor/spikard-rb/src/sse.rs +231 -231
  176. data/vendor/spikard-rb/src/test_client.rs +404 -404
  177. data/vendor/spikard-rb/src/test_sse.rs +143 -143
  178. data/vendor/spikard-rb/src/test_websocket.rs +221 -221
  179. data/vendor/spikard-rb/src/websocket.rs +233 -233
  180. metadata +1 -1
@@ -1,304 +1,304 @@
1
- //! Path parameter type hint parsing
2
- //!
3
- //! Supports FastAPI-style type syntax in route paths:
4
- //! - `/items/{id:uuid}` → auto-generates UUID validation
5
- //! - `/users/{user_id:int}` → auto-generates integer type
6
- //! - `/files/{path:path}` → wildcard path capture
7
- //!
8
- //! Explicit parameter schemas override auto-generated ones.
9
-
10
- use regex::Regex;
11
- use serde_json::{Value, json};
12
- use std::collections::HashMap;
13
- use std::sync::OnceLock;
14
-
15
- /// Regex for matching type hints in path parameters
16
- static TYPE_HINT_REGEX: OnceLock<Regex> = OnceLock::new();
17
-
18
- /// Regex for matching wildcard path parameters
19
- static PATH_TYPE_REGEX: OnceLock<Regex> = OnceLock::new();
20
-
21
- /// Get the type hint regex (compiled once)
22
- fn type_hint_regex() -> &'static Regex {
23
- TYPE_HINT_REGEX.get_or_init(|| Regex::new(r"\{([^:}]+):([^}]+)\}").unwrap())
24
- }
25
-
26
- /// Get the path type regex (compiled once)
27
- fn path_type_regex() -> &'static Regex {
28
- PATH_TYPE_REGEX.get_or_init(|| Regex::new(r"\{([^:}]+):path\}").unwrap())
29
- }
30
-
31
- /// Parse type hints from a route path
32
- ///
33
- /// # Examples
34
- ///
35
- /// ```
36
- /// use spikard_core::type_hints::parse_type_hints;
37
- ///
38
- /// let hints = parse_type_hints("/items/{id:uuid}/tags/{tag_id:int}");
39
- /// assert_eq!(hints.get("id"), Some(&"uuid".to_string()));
40
- /// assert_eq!(hints.get("tag_id"), Some(&"int".to_string()));
41
- /// ```
42
- pub fn parse_type_hints(route_path: &str) -> HashMap<String, String> {
43
- let mut hints = HashMap::new();
44
- let re = type_hint_regex();
45
-
46
- for cap in re.captures_iter(route_path) {
47
- let param_name = cap.get(1).unwrap().as_str().to_string();
48
- let type_hint = cap.get(2).unwrap().as_str().to_string();
49
- hints.insert(param_name, type_hint);
50
- }
51
-
52
- hints
53
- }
54
-
55
- /// Strip type hints from path for Axum compatibility
56
- ///
57
- /// Converts FastAPI-style syntax to Axum syntax:
58
- /// - `/items/{id:uuid}` → `/items/{id}`
59
- /// - `/files/{path:path}` → `/files/{*path}` (wildcard for Axum v0.7)
60
- ///
61
- /// # Examples
62
- ///
63
- /// ```
64
- /// use spikard_core::type_hints::strip_type_hints;
65
- ///
66
- /// assert_eq!(strip_type_hints("/items/{id:uuid}"), "/items/{id}");
67
- /// assert_eq!(strip_type_hints("/files/{path:path}"), "/files/{*path}");
68
- /// ```
69
- pub fn strip_type_hints(route_path: &str) -> String {
70
- let path_re = path_type_regex();
71
- let route_path = path_re.replace_all(route_path, "{*$1}");
72
-
73
- let re = type_hint_regex();
74
- re.replace_all(&route_path, "{$1}").to_string()
75
- }
76
-
77
- /// Generate JSON Schema from a type hint
78
- ///
79
- /// # Supported Types
80
- ///
81
- /// - `uuid` → `{"type": "string", "format": "uuid"}`
82
- /// - `int` / `integer` → `{"type": "integer"}`
83
- /// - `str` / `string` → `{"type": "string"}`
84
- /// - `float` / `number` → `{"type": "number"}`
85
- /// - `bool` / `boolean` → `{"type": "boolean"}`
86
- /// - `date` → `{"type": "string", "format": "date"}`
87
- /// - `datetime` → `{"type": "string", "format": "date-time"}`
88
- /// - `path` → `{"type": "string"}` (wildcard capture)
89
- pub fn type_hint_to_schema(type_hint: &str) -> Value {
90
- match type_hint {
91
- "uuid" => json!({
92
- "type": "string",
93
- "format": "uuid"
94
- }),
95
- "int" | "integer" => json!({
96
- "type": "integer"
97
- }),
98
- "str" | "string" => json!({
99
- "type": "string"
100
- }),
101
- "float" | "number" => json!({
102
- "type": "number"
103
- }),
104
- "bool" | "boolean" => json!({
105
- "type": "boolean"
106
- }),
107
- "date" => json!({
108
- "type": "string",
109
- "format": "date"
110
- }),
111
- "datetime" | "date-time" => json!({
112
- "type": "string",
113
- "format": "date-time"
114
- }),
115
- "path" => json!({
116
- "type": "string"
117
- }),
118
- _ => json!({
119
- "type": "string"
120
- }),
121
- }
122
- }
123
-
124
- /// Auto-generate parameter schema from type hints in route path
125
- ///
126
- /// Creates a JSON Schema with path parameters based on type hints.
127
- /// Returns None if no type hints are found.
128
- ///
129
- /// # Examples
130
- ///
131
- /// ```
132
- /// use spikard_core::type_hints::auto_generate_parameter_schema;
133
- /// use serde_json::json;
134
- ///
135
- /// let schema = auto_generate_parameter_schema("/items/{id:uuid}");
136
- /// assert_eq!(schema, Some(json!({
137
- /// "type": "object",
138
- /// "properties": {
139
- /// "id": {
140
- /// "type": "string",
141
- /// "format": "uuid",
142
- /// "source": "path"
143
- /// }
144
- /// },
145
- /// "required": ["id"]
146
- /// })));
147
- /// ```
148
- pub fn auto_generate_parameter_schema(route_path: &str) -> Option<Value> {
149
- let type_hints = parse_type_hints(route_path);
150
-
151
- if type_hints.is_empty() {
152
- return None;
153
- }
154
-
155
- let mut properties = serde_json::Map::new();
156
- let mut required = Vec::new();
157
-
158
- for (param_name, type_hint) in type_hints {
159
- let mut param_schema = type_hint_to_schema(&type_hint);
160
-
161
- if let Some(obj) = param_schema.as_object_mut() {
162
- obj.insert("source".to_string(), json!("path"));
163
- }
164
-
165
- properties.insert(param_name.clone(), param_schema);
166
- required.push(json!(param_name));
167
- }
168
-
169
- Some(json!({
170
- "type": "object",
171
- "properties": properties,
172
- "required": required
173
- }))
174
- }
175
-
176
- /// Merge auto-generated schema with explicit schema
177
- ///
178
- /// Explicit schema takes precedence. Only auto-generates schemas for
179
- /// parameters not explicitly defined.
180
- ///
181
- /// # Examples
182
- ///
183
- /// ```
184
- /// use spikard_core::type_hints::merge_parameter_schemas;
185
- /// use serde_json::json;
186
- ///
187
- /// let auto_schema = json!({
188
- /// "type": "object",
189
- /// "properties": {
190
- /// "id": {"type": "string", "format": "uuid", "source": "path"},
191
- /// "count": {"type": "integer", "source": "path"}
192
- /// },
193
- /// "required": ["id", "count"]
194
- /// });
195
- ///
196
- /// let explicit_schema = json!({
197
- /// "type": "object",
198
- /// "properties": {
199
- /// "count": {"type": "integer", "minimum": 1, "maximum": 100, "source": "path"}
200
- /// },
201
- /// "required": ["count"]
202
- /// });
203
- ///
204
- /// let merged = merge_parameter_schemas(auto_schema, explicit_schema);
205
- /// // Result: auto-generated id + explicit count with constraints
206
- /// ```
207
- pub fn merge_parameter_schemas(auto_schema: Value, explicit_schema: Value) -> Value {
208
- let mut result = auto_schema.clone();
209
-
210
- let auto_props = result.get_mut("properties").and_then(|v| v.as_object_mut());
211
- let explicit_props = explicit_schema.get("properties").and_then(|v| v.as_object());
212
-
213
- if let (Some(auto_props), Some(explicit_props)) = (auto_props, explicit_props) {
214
- for (key, value) in explicit_props {
215
- auto_props.insert(key.clone(), value.clone());
216
- }
217
- }
218
-
219
- if let Some(explicit_required) = explicit_schema.get("required").and_then(|v| v.as_array())
220
- && let Some(auto_required) = result.get_mut("required").and_then(|v| v.as_array_mut())
221
- {
222
- for req in explicit_required {
223
- if !auto_required.contains(req) {
224
- auto_required.push(req.clone());
225
- }
226
- }
227
- }
228
-
229
- result
230
- }
231
-
232
- #[cfg(test)]
233
- mod tests {
234
- use super::*;
235
-
236
- #[test]
237
- fn test_parse_type_hints() {
238
- let hints = parse_type_hints("/items/{id:uuid}");
239
- assert_eq!(hints.get("id"), Some(&"uuid".to_string()));
240
-
241
- let hints = parse_type_hints("/users/{user_id:int}/posts/{post_id:int}");
242
- assert_eq!(hints.get("user_id"), Some(&"int".to_string()));
243
- assert_eq!(hints.get("post_id"), Some(&"int".to_string()));
244
- }
245
-
246
- #[test]
247
- fn test_strip_type_hints() {
248
- assert_eq!(strip_type_hints("/items/{id:uuid}"), "/items/{id}");
249
- assert_eq!(strip_type_hints("/files/{path:path}"), "/files/{*path}");
250
- assert_eq!(
251
- strip_type_hints("/users/{user_id:int}/posts/{post_id:int}"),
252
- "/users/{user_id}/posts/{post_id}"
253
- );
254
- }
255
-
256
- #[test]
257
- fn test_type_hint_to_schema() {
258
- let schema = type_hint_to_schema("uuid");
259
- assert_eq!(schema["type"], "string");
260
- assert_eq!(schema["format"], "uuid");
261
-
262
- let schema = type_hint_to_schema("int");
263
- assert_eq!(schema["type"], "integer");
264
- }
265
-
266
- #[test]
267
- fn test_auto_generate_parameter_schema() {
268
- let schema = auto_generate_parameter_schema("/items/{id:uuid}").unwrap();
269
- assert_eq!(schema["type"], "object");
270
- assert_eq!(schema["properties"]["id"]["type"], "string");
271
- assert_eq!(schema["properties"]["id"]["format"], "uuid");
272
- assert_eq!(schema["required"], json!(["id"]));
273
- }
274
-
275
- #[test]
276
- fn test_no_type_hints() {
277
- let schema = auto_generate_parameter_schema("/items/{id}");
278
- assert!(schema.is_none());
279
- }
280
-
281
- #[test]
282
- fn test_merge_schemas() {
283
- let auto_schema = json!({
284
- "type": "object",
285
- "properties": {
286
- "id": {"type": "string", "format": "uuid", "source": "path"}
287
- },
288
- "required": ["id"]
289
- });
290
-
291
- let explicit_schema = json!({
292
- "type": "object",
293
- "properties": {
294
- "count": {"type": "integer", "minimum": 1, "source": "path"}
295
- },
296
- "required": ["count"]
297
- });
298
-
299
- let merged = merge_parameter_schemas(auto_schema, explicit_schema);
300
- assert!(merged["properties"]["id"].is_object());
301
- assert!(merged["properties"]["count"].is_object());
302
- assert_eq!(merged["properties"]["count"]["minimum"], 1);
303
- }
304
- }
1
+ //! Path parameter type hint parsing
2
+ //!
3
+ //! Supports FastAPI-style type syntax in route paths:
4
+ //! - `/items/{id:uuid}` → auto-generates UUID validation
5
+ //! - `/users/{user_id:int}` → auto-generates integer type
6
+ //! - `/files/{path:path}` → wildcard path capture
7
+ //!
8
+ //! Explicit parameter schemas override auto-generated ones.
9
+
10
+ use regex::Regex;
11
+ use serde_json::{Value, json};
12
+ use std::collections::HashMap;
13
+ use std::sync::OnceLock;
14
+
15
+ /// Regex for matching type hints in path parameters
16
+ static TYPE_HINT_REGEX: OnceLock<Regex> = OnceLock::new();
17
+
18
+ /// Regex for matching wildcard path parameters
19
+ static PATH_TYPE_REGEX: OnceLock<Regex> = OnceLock::new();
20
+
21
+ /// Get the type hint regex (compiled once)
22
+ fn type_hint_regex() -> &'static Regex {
23
+ TYPE_HINT_REGEX.get_or_init(|| Regex::new(r"\{([^:}]+):([^}]+)\}").unwrap())
24
+ }
25
+
26
+ /// Get the path type regex (compiled once)
27
+ fn path_type_regex() -> &'static Regex {
28
+ PATH_TYPE_REGEX.get_or_init(|| Regex::new(r"\{([^:}]+):path\}").unwrap())
29
+ }
30
+
31
+ /// Parse type hints from a route path
32
+ ///
33
+ /// # Examples
34
+ ///
35
+ /// ```
36
+ /// use spikard_core::type_hints::parse_type_hints;
37
+ ///
38
+ /// let hints = parse_type_hints("/items/{id:uuid}/tags/{tag_id:int}");
39
+ /// assert_eq!(hints.get("id"), Some(&"uuid".to_string()));
40
+ /// assert_eq!(hints.get("tag_id"), Some(&"int".to_string()));
41
+ /// ```
42
+ pub fn parse_type_hints(route_path: &str) -> HashMap<String, String> {
43
+ let mut hints = HashMap::new();
44
+ let re = type_hint_regex();
45
+
46
+ for cap in re.captures_iter(route_path) {
47
+ let param_name = cap.get(1).unwrap().as_str().to_string();
48
+ let type_hint = cap.get(2).unwrap().as_str().to_string();
49
+ hints.insert(param_name, type_hint);
50
+ }
51
+
52
+ hints
53
+ }
54
+
55
+ /// Strip type hints from path for Axum compatibility
56
+ ///
57
+ /// Converts FastAPI-style syntax to Axum syntax:
58
+ /// - `/items/{id:uuid}` → `/items/{id}`
59
+ /// - `/files/{path:path}` → `/files/{*path}` (wildcard for Axum v0.7)
60
+ ///
61
+ /// # Examples
62
+ ///
63
+ /// ```
64
+ /// use spikard_core::type_hints::strip_type_hints;
65
+ ///
66
+ /// assert_eq!(strip_type_hints("/items/{id:uuid}"), "/items/{id}");
67
+ /// assert_eq!(strip_type_hints("/files/{path:path}"), "/files/{*path}");
68
+ /// ```
69
+ pub fn strip_type_hints(route_path: &str) -> String {
70
+ let path_re = path_type_regex();
71
+ let route_path = path_re.replace_all(route_path, "{*$1}");
72
+
73
+ let re = type_hint_regex();
74
+ re.replace_all(&route_path, "{$1}").to_string()
75
+ }
76
+
77
+ /// Generate JSON Schema from a type hint
78
+ ///
79
+ /// # Supported Types
80
+ ///
81
+ /// - `uuid` → `{"type": "string", "format": "uuid"}`
82
+ /// - `int` / `integer` → `{"type": "integer"}`
83
+ /// - `str` / `string` → `{"type": "string"}`
84
+ /// - `float` / `number` → `{"type": "number"}`
85
+ /// - `bool` / `boolean` → `{"type": "boolean"}`
86
+ /// - `date` → `{"type": "string", "format": "date"}`
87
+ /// - `datetime` → `{"type": "string", "format": "date-time"}`
88
+ /// - `path` → `{"type": "string"}` (wildcard capture)
89
+ pub fn type_hint_to_schema(type_hint: &str) -> Value {
90
+ match type_hint {
91
+ "uuid" => json!({
92
+ "type": "string",
93
+ "format": "uuid"
94
+ }),
95
+ "int" | "integer" => json!({
96
+ "type": "integer"
97
+ }),
98
+ "str" | "string" => json!({
99
+ "type": "string"
100
+ }),
101
+ "float" | "number" => json!({
102
+ "type": "number"
103
+ }),
104
+ "bool" | "boolean" => json!({
105
+ "type": "boolean"
106
+ }),
107
+ "date" => json!({
108
+ "type": "string",
109
+ "format": "date"
110
+ }),
111
+ "datetime" | "date-time" => json!({
112
+ "type": "string",
113
+ "format": "date-time"
114
+ }),
115
+ "path" => json!({
116
+ "type": "string"
117
+ }),
118
+ _ => json!({
119
+ "type": "string"
120
+ }),
121
+ }
122
+ }
123
+
124
+ /// Auto-generate parameter schema from type hints in route path
125
+ ///
126
+ /// Creates a JSON Schema with path parameters based on type hints.
127
+ /// Returns None if no type hints are found.
128
+ ///
129
+ /// # Examples
130
+ ///
131
+ /// ```
132
+ /// use spikard_core::type_hints::auto_generate_parameter_schema;
133
+ /// use serde_json::json;
134
+ ///
135
+ /// let schema = auto_generate_parameter_schema("/items/{id:uuid}");
136
+ /// assert_eq!(schema, Some(json!({
137
+ /// "type": "object",
138
+ /// "properties": {
139
+ /// "id": {
140
+ /// "type": "string",
141
+ /// "format": "uuid",
142
+ /// "source": "path"
143
+ /// }
144
+ /// },
145
+ /// "required": ["id"]
146
+ /// })));
147
+ /// ```
148
+ pub fn auto_generate_parameter_schema(route_path: &str) -> Option<Value> {
149
+ let type_hints = parse_type_hints(route_path);
150
+
151
+ if type_hints.is_empty() {
152
+ return None;
153
+ }
154
+
155
+ let mut properties = serde_json::Map::new();
156
+ let mut required = Vec::new();
157
+
158
+ for (param_name, type_hint) in type_hints {
159
+ let mut param_schema = type_hint_to_schema(&type_hint);
160
+
161
+ if let Some(obj) = param_schema.as_object_mut() {
162
+ obj.insert("source".to_string(), json!("path"));
163
+ }
164
+
165
+ properties.insert(param_name.clone(), param_schema);
166
+ required.push(json!(param_name));
167
+ }
168
+
169
+ Some(json!({
170
+ "type": "object",
171
+ "properties": properties,
172
+ "required": required
173
+ }))
174
+ }
175
+
176
+ /// Merge auto-generated schema with explicit schema
177
+ ///
178
+ /// Explicit schema takes precedence. Only auto-generates schemas for
179
+ /// parameters not explicitly defined.
180
+ ///
181
+ /// # Examples
182
+ ///
183
+ /// ```
184
+ /// use spikard_core::type_hints::merge_parameter_schemas;
185
+ /// use serde_json::json;
186
+ ///
187
+ /// let auto_schema = json!({
188
+ /// "type": "object",
189
+ /// "properties": {
190
+ /// "id": {"type": "string", "format": "uuid", "source": "path"},
191
+ /// "count": {"type": "integer", "source": "path"}
192
+ /// },
193
+ /// "required": ["id", "count"]
194
+ /// });
195
+ ///
196
+ /// let explicit_schema = json!({
197
+ /// "type": "object",
198
+ /// "properties": {
199
+ /// "count": {"type": "integer", "minimum": 1, "maximum": 100, "source": "path"}
200
+ /// },
201
+ /// "required": ["count"]
202
+ /// });
203
+ ///
204
+ /// let merged = merge_parameter_schemas(auto_schema, explicit_schema);
205
+ /// // Result: auto-generated id + explicit count with constraints
206
+ /// ```
207
+ pub fn merge_parameter_schemas(auto_schema: Value, explicit_schema: Value) -> Value {
208
+ let mut result = auto_schema.clone();
209
+
210
+ let auto_props = result.get_mut("properties").and_then(|v| v.as_object_mut());
211
+ let explicit_props = explicit_schema.get("properties").and_then(|v| v.as_object());
212
+
213
+ if let (Some(auto_props), Some(explicit_props)) = (auto_props, explicit_props) {
214
+ for (key, value) in explicit_props {
215
+ auto_props.insert(key.clone(), value.clone());
216
+ }
217
+ }
218
+
219
+ if let Some(explicit_required) = explicit_schema.get("required").and_then(|v| v.as_array())
220
+ && let Some(auto_required) = result.get_mut("required").and_then(|v| v.as_array_mut())
221
+ {
222
+ for req in explicit_required {
223
+ if !auto_required.contains(req) {
224
+ auto_required.push(req.clone());
225
+ }
226
+ }
227
+ }
228
+
229
+ result
230
+ }
231
+
232
+ #[cfg(test)]
233
+ mod tests {
234
+ use super::*;
235
+
236
+ #[test]
237
+ fn test_parse_type_hints() {
238
+ let hints = parse_type_hints("/items/{id:uuid}");
239
+ assert_eq!(hints.get("id"), Some(&"uuid".to_string()));
240
+
241
+ let hints = parse_type_hints("/users/{user_id:int}/posts/{post_id:int}");
242
+ assert_eq!(hints.get("user_id"), Some(&"int".to_string()));
243
+ assert_eq!(hints.get("post_id"), Some(&"int".to_string()));
244
+ }
245
+
246
+ #[test]
247
+ fn test_strip_type_hints() {
248
+ assert_eq!(strip_type_hints("/items/{id:uuid}"), "/items/{id}");
249
+ assert_eq!(strip_type_hints("/files/{path:path}"), "/files/{*path}");
250
+ assert_eq!(
251
+ strip_type_hints("/users/{user_id:int}/posts/{post_id:int}"),
252
+ "/users/{user_id}/posts/{post_id}"
253
+ );
254
+ }
255
+
256
+ #[test]
257
+ fn test_type_hint_to_schema() {
258
+ let schema = type_hint_to_schema("uuid");
259
+ assert_eq!(schema["type"], "string");
260
+ assert_eq!(schema["format"], "uuid");
261
+
262
+ let schema = type_hint_to_schema("int");
263
+ assert_eq!(schema["type"], "integer");
264
+ }
265
+
266
+ #[test]
267
+ fn test_auto_generate_parameter_schema() {
268
+ let schema = auto_generate_parameter_schema("/items/{id:uuid}").unwrap();
269
+ assert_eq!(schema["type"], "object");
270
+ assert_eq!(schema["properties"]["id"]["type"], "string");
271
+ assert_eq!(schema["properties"]["id"]["format"], "uuid");
272
+ assert_eq!(schema["required"], json!(["id"]));
273
+ }
274
+
275
+ #[test]
276
+ fn test_no_type_hints() {
277
+ let schema = auto_generate_parameter_schema("/items/{id}");
278
+ assert!(schema.is_none());
279
+ }
280
+
281
+ #[test]
282
+ fn test_merge_schemas() {
283
+ let auto_schema = json!({
284
+ "type": "object",
285
+ "properties": {
286
+ "id": {"type": "string", "format": "uuid", "source": "path"}
287
+ },
288
+ "required": ["id"]
289
+ });
290
+
291
+ let explicit_schema = json!({
292
+ "type": "object",
293
+ "properties": {
294
+ "count": {"type": "integer", "minimum": 1, "source": "path"}
295
+ },
296
+ "required": ["count"]
297
+ });
298
+
299
+ let merged = merge_parameter_schemas(auto_schema, explicit_schema);
300
+ assert!(merged["properties"]["id"].is_object());
301
+ assert!(merged["properties"]["count"].is_object());
302
+ assert_eq!(merged["properties"]["count"]["minimum"], 1);
303
+ }
304
+ }