spikard 0.2.5 → 0.3.1

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 (103) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -626
  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 -374
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -85
  11. data/lib/spikard/handler_wrapper.rb +113 -116
  12. data/lib/spikard/provide.rb +214 -228
  13. data/lib/spikard/response.rb +173 -109
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -21
  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 -349
  23. data/vendor/bundle/ruby/3.4.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
  24. metadata +5 -85
  25. data/vendor/crates/spikard-core/Cargo.toml +0 -40
  26. data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
  27. data/vendor/crates/spikard-core/src/bindings/response.rs +0 -133
  28. data/vendor/crates/spikard-core/src/debug.rs +0 -63
  29. data/vendor/crates/spikard-core/src/di/container.rs +0 -726
  30. data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
  31. data/vendor/crates/spikard-core/src/di/error.rs +0 -118
  32. data/vendor/crates/spikard-core/src/di/factory.rs +0 -538
  33. data/vendor/crates/spikard-core/src/di/graph.rs +0 -545
  34. data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
  35. data/vendor/crates/spikard-core/src/di/resolved.rs +0 -411
  36. data/vendor/crates/spikard-core/src/di/value.rs +0 -283
  37. data/vendor/crates/spikard-core/src/http.rs +0 -153
  38. data/vendor/crates/spikard-core/src/lib.rs +0 -28
  39. data/vendor/crates/spikard-core/src/lifecycle.rs +0 -422
  40. data/vendor/crates/spikard-core/src/parameters.rs +0 -719
  41. data/vendor/crates/spikard-core/src/problem.rs +0 -310
  42. data/vendor/crates/spikard-core/src/request_data.rs +0 -189
  43. data/vendor/crates/spikard-core/src/router.rs +0 -249
  44. data/vendor/crates/spikard-core/src/schema_registry.rs +0 -183
  45. data/vendor/crates/spikard-core/src/type_hints.rs +0 -304
  46. data/vendor/crates/spikard-core/src/validation.rs +0 -699
  47. data/vendor/crates/spikard-http/Cargo.toml +0 -58
  48. data/vendor/crates/spikard-http/src/auth.rs +0 -247
  49. data/vendor/crates/spikard-http/src/background.rs +0 -249
  50. data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
  51. data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
  52. data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
  53. data/vendor/crates/spikard-http/src/cors.rs +0 -490
  54. data/vendor/crates/spikard-http/src/debug.rs +0 -63
  55. data/vendor/crates/spikard-http/src/di_handler.rs +0 -423
  56. data/vendor/crates/spikard-http/src/handler_response.rs +0 -190
  57. data/vendor/crates/spikard-http/src/handler_trait.rs +0 -228
  58. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -284
  59. data/vendor/crates/spikard-http/src/lib.rs +0 -529
  60. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -149
  61. data/vendor/crates/spikard-http/src/lifecycle.rs +0 -428
  62. data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -285
  63. data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -86
  64. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -147
  65. data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -287
  66. data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
  67. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -190
  68. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -308
  69. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -195
  70. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  71. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  72. data/vendor/crates/spikard-http/src/query_parser.rs +0 -369
  73. data/vendor/crates/spikard-http/src/response.rs +0 -399
  74. data/vendor/crates/spikard-http/src/router.rs +0 -1
  75. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  76. data/vendor/crates/spikard-http/src/server/handler.rs +0 -80
  77. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -98
  78. data/vendor/crates/spikard-http/src/server/mod.rs +0 -805
  79. data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -119
  80. data/vendor/crates/spikard-http/src/sse.rs +0 -447
  81. data/vendor/crates/spikard-http/src/testing/form.rs +0 -14
  82. data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -60
  83. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -285
  84. data/vendor/crates/spikard-http/src/testing.rs +0 -377
  85. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  86. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  87. data/vendor/crates/spikard-http/src/websocket.rs +0 -324
  88. data/vendor/crates/spikard-rb/Cargo.toml +0 -42
  89. data/vendor/crates/spikard-rb/build.rs +0 -8
  90. data/vendor/crates/spikard-rb/src/background.rs +0 -63
  91. data/vendor/crates/spikard-rb/src/config.rs +0 -294
  92. data/vendor/crates/spikard-rb/src/conversion.rs +0 -392
  93. data/vendor/crates/spikard-rb/src/di.rs +0 -409
  94. data/vendor/crates/spikard-rb/src/handler.rs +0 -534
  95. data/vendor/crates/spikard-rb/src/lib.rs +0 -2020
  96. data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -267
  97. data/vendor/crates/spikard-rb/src/server.rs +0 -283
  98. data/vendor/crates/spikard-rb/src/sse.rs +0 -231
  99. data/vendor/crates/spikard-rb/src/test_client.rs +0 -404
  100. data/vendor/crates/spikard-rb/src/test_sse.rs +0 -143
  101. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  102. data/vendor/crates/spikard-rb/src/websocket.rs +0 -233
  103. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/diff-lcs-1.6.2/mise.toml +0 -0
@@ -1,285 +0,0 @@
1
- //! HTTP middleware for request validation
2
- //!
3
- //! Provides middleware stack setup, JSON schema validation, multipart/form-data parsing,
4
- //! and URL-encoded form data handling.
5
-
6
- pub mod multipart;
7
- pub mod urlencoded;
8
- pub mod validation;
9
-
10
- use axum::{
11
- body::Body,
12
- extract::{FromRequest, Multipart, Request},
13
- http::StatusCode,
14
- middleware::Next,
15
- response::{IntoResponse, Response},
16
- };
17
- use serde_json::json;
18
- use std::collections::HashMap;
19
- use std::sync::Arc;
20
-
21
- /// Route information for middleware validation
22
- #[derive(Debug, Clone)]
23
- pub struct RouteInfo {
24
- /// Whether this route expects a JSON request body
25
- pub expects_json_body: bool,
26
- }
27
-
28
- /// Registry of route metadata indexed by (method, path)
29
- pub type RouteRegistry = Arc<HashMap<(String, String), RouteInfo>>;
30
-
31
- /// Middleware to validate Content-Type headers and related requirements
32
- ///
33
- /// This middleware performs comprehensive request body validation and transformation:
34
- ///
35
- /// - **Content-Type Validation:** Ensures the request's Content-Type header matches the
36
- /// expected format for the route (if configured).
37
- ///
38
- /// - **Multipart Form Data:** Automatically parses `multipart/form-data` requests and
39
- /// transforms them into JSON format for uniform downstream processing.
40
- ///
41
- /// - **URL-Encoded Forms:** Parses `application/x-www-form-urlencoded` requests and
42
- /// converts them to JSON.
43
- ///
44
- /// - **JSON Validation:** Validates JSON request bodies for well-formedness (when the
45
- /// Content-Type is `application/json`).
46
- ///
47
- /// - **Content-Length:** Validates that the Content-Length header is present and
48
- /// reasonable for POST, PUT, and PATCH requests.
49
- ///
50
- /// # Behavior
51
- ///
52
- /// For request methods POST, PUT, and PATCH:
53
- /// 1. Checks if the route expects a JSON body (via `RouteRegistry`)
54
- /// 2. Validates Content-Type headers based on route configuration
55
- /// 3. Parses the request body according to Content-Type:
56
- /// - `multipart/form-data` → JSON (form fields as object properties)
57
- /// - `application/x-www-form-urlencoded` → JSON (URL parameters as object)
58
- /// - `application/json` → Validates JSON syntax
59
- /// 4. Transforms the request to have `Content-Type: application/json`
60
- /// 5. Passes the transformed request to the next middleware
61
- ///
62
- /// For GET, DELETE, and other methods: passes through with minimal validation.
63
- ///
64
- /// # Errors
65
- ///
66
- /// Returns HTTP error responses for:
67
- /// - `400 Bad Request` - Failed to read request body, invalid JSON, malformed forms, invalid Content-Length
68
- /// - `500 Internal Server Error` - Failed to serialize transformed body
69
- ///
70
- /// # Examples
71
- ///
72
- /// ```rust
73
- /// use axum::{middleware::Next, extract::Request};
74
- /// use spikard_http::middleware::validate_content_type_middleware;
75
- ///
76
- /// // This is typically used as middleware in an Axum router:
77
- /// // router.layer(axum::middleware::from_fn(validate_content_type_middleware))
78
- /// ```
79
- pub async fn validate_content_type_middleware(request: Request, next: Next) -> Result<Response, Response> {
80
- use axum::body::to_bytes;
81
- use axum::http::Request as HttpRequest;
82
-
83
- let (parts, body) = request.into_parts();
84
- let headers = &parts.headers;
85
-
86
- let route_info = parts.extensions.get::<RouteRegistry>().and_then(|registry| {
87
- let method = parts.method.as_str();
88
- let path = parts.uri.path();
89
- registry.get(&(method.to_string(), path.to_string())).cloned()
90
- });
91
-
92
- let method = &parts.method;
93
- if method == axum::http::Method::POST || method == axum::http::Method::PUT || method == axum::http::Method::PATCH {
94
- if let Some(info) = &route_info
95
- && info.expects_json_body
96
- {
97
- validation::validate_json_content_type(headers)?;
98
- }
99
-
100
- validation::validate_content_type_headers(headers, 0)?;
101
-
102
- let (final_parts, final_body) = if let Some(content_type) = headers.get(axum::http::header::CONTENT_TYPE) {
103
- if let Ok(content_type_str) = content_type.to_str() {
104
- let parsed_mime = content_type_str.parse::<mime::Mime>().ok();
105
-
106
- let is_multipart = parsed_mime
107
- .as_ref()
108
- .map(|mime| mime.type_() == mime::MULTIPART && mime.subtype() == "form-data")
109
- .unwrap_or(false);
110
-
111
- let is_form_urlencoded = parsed_mime
112
- .as_ref()
113
- .map(|mime| mime.type_() == mime::APPLICATION && mime.subtype() == "x-www-form-urlencoded")
114
- .unwrap_or(false);
115
-
116
- if is_multipart {
117
- let mut response_headers = parts.headers.clone();
118
-
119
- let request = HttpRequest::from_parts(parts, body);
120
- let multipart = match Multipart::from_request(request, &()).await {
121
- Ok(mp) => mp,
122
- Err(e) => {
123
- let error_body = json!({
124
- "error": format!("Failed to parse multipart data: {}", e)
125
- });
126
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
127
- }
128
- };
129
-
130
- let json_body = match multipart::parse_multipart_to_json(multipart).await {
131
- Ok(json) => json,
132
- Err(e) => {
133
- let error_body = json!({
134
- "error": format!("Failed to process multipart data: {}", e)
135
- });
136
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
137
- }
138
- };
139
-
140
- let json_bytes = match serde_json::to_vec(&json_body) {
141
- Ok(bytes) => bytes,
142
- Err(e) => {
143
- let error_body = json!({
144
- "error": format!("Failed to serialize multipart data to JSON: {}", e)
145
- });
146
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
147
- }
148
- };
149
-
150
- response_headers.insert(
151
- axum::http::header::CONTENT_TYPE,
152
- axum::http::HeaderValue::from_static("application/json"),
153
- );
154
-
155
- let mut new_request = axum::http::Request::new(Body::from(json_bytes));
156
- *new_request.headers_mut() = response_headers;
157
-
158
- return Ok(next.run(new_request).await);
159
- } else if is_form_urlencoded {
160
- let body_bytes = match to_bytes(body, usize::MAX).await {
161
- Ok(bytes) => bytes,
162
- Err(_) => {
163
- let error_body = json!({
164
- "error": "Failed to read request body"
165
- });
166
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
167
- }
168
- };
169
-
170
- validation::validate_content_length(headers, body_bytes.len())?;
171
-
172
- let json_body = if body_bytes.is_empty() {
173
- serde_json::json!({})
174
- } else {
175
- match urlencoded::parse_urlencoded_to_json(&body_bytes) {
176
- Ok(json_body) => json_body,
177
- Err(e) => {
178
- let error_body = json!({
179
- "error": format!("Failed to parse URL-encoded form data: {}", e)
180
- });
181
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
182
- }
183
- }
184
- };
185
-
186
- let json_bytes = match serde_json::to_vec(&json_body) {
187
- Ok(bytes) => bytes,
188
- Err(e) => {
189
- let error_body = json!({
190
- "error": format!("Failed to serialize URL-encoded form data to JSON: {}", e)
191
- });
192
- return Err((StatusCode::INTERNAL_SERVER_ERROR, axum::Json(error_body)).into_response());
193
- }
194
- };
195
-
196
- let mut new_parts = parts;
197
- new_parts.headers.insert(
198
- axum::http::header::CONTENT_TYPE,
199
- axum::http::HeaderValue::from_static("application/json"),
200
- );
201
-
202
- (new_parts, Body::from(json_bytes))
203
- } else {
204
- let body_bytes = match to_bytes(body, usize::MAX).await {
205
- Ok(bytes) => bytes,
206
- Err(_) => {
207
- let error_body = json!({
208
- "error": "Failed to read request body"
209
- });
210
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
211
- }
212
- };
213
-
214
- validation::validate_content_length(headers, body_bytes.len())?;
215
-
216
- let is_json = parsed_mime
217
- .as_ref()
218
- .map(validation::is_json_content_type)
219
- .unwrap_or(false);
220
-
221
- if is_json
222
- && !body_bytes.is_empty()
223
- && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
224
- {
225
- let error_body = json!({
226
- "detail": "Invalid request format"
227
- });
228
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
229
- }
230
-
231
- (parts, Body::from(body_bytes))
232
- }
233
- } else {
234
- let body_bytes = match to_bytes(body, usize::MAX).await {
235
- Ok(bytes) => bytes,
236
- Err(_) => {
237
- let error_body = json!({
238
- "error": "Failed to read request body"
239
- });
240
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
241
- }
242
- };
243
-
244
- validation::validate_content_length(headers, body_bytes.len())?;
245
-
246
- (parts, Body::from(body_bytes))
247
- }
248
- } else {
249
- let body_bytes = match to_bytes(body, usize::MAX).await {
250
- Ok(bytes) => bytes,
251
- Err(_) => {
252
- let error_body = json!({
253
- "error": "Failed to read request body"
254
- });
255
- return Err((StatusCode::BAD_REQUEST, axum::Json(error_body)).into_response());
256
- }
257
- };
258
-
259
- validation::validate_content_length(headers, body_bytes.len())?;
260
-
261
- (parts, Body::from(body_bytes))
262
- };
263
-
264
- let request = HttpRequest::from_parts(final_parts, final_body);
265
- Ok(next.run(request).await)
266
- } else {
267
- validation::validate_content_type_headers(headers, 0)?;
268
-
269
- let request = HttpRequest::from_parts(parts, body);
270
- Ok(next.run(request).await)
271
- }
272
- }
273
-
274
- #[cfg(test)]
275
- mod tests {
276
- use super::*;
277
-
278
- #[test]
279
- fn test_route_info_creation() {
280
- let info = RouteInfo {
281
- expects_json_body: true,
282
- };
283
- assert!(info.expects_json_body);
284
- }
285
- }
@@ -1,86 +0,0 @@
1
- //! Multipart form-data parsing
2
-
3
- use axum::extract::Multipart;
4
- use serde_json::json;
5
-
6
- /// Size threshold for streaming vs buffering multipart fields
7
- /// Fields larger than this will be streamed chunk-by-chunk
8
- const MULTIPART_STREAMING_THRESHOLD: usize = 1024 * 1024;
9
-
10
- /// Parse multipart/form-data to JSON
11
- ///
12
- /// This handles:
13
- /// - File uploads → {"filename": "...", "size": N, "content": "...", "content_type": "..."}
14
- /// - Form fields → plain string values
15
- /// - Mixed files and data → combined in single JSON object
16
- /// - Large files → streamed chunk-by-chunk (async)
17
- /// - Small files → buffered in memory
18
- /// - Multiple values with same field name → aggregated into arrays
19
- ///
20
- /// Streaming strategy:
21
- /// - Files > 1MB: Use field.chunk().await for async streaming
22
- /// - Files <= 1MB: Use field.bytes().await for buffered loading
23
- pub async fn parse_multipart_to_json(
24
- mut multipart: Multipart,
25
- ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
26
- use rustc_hash::FxHashMap;
27
-
28
- let mut field_values: FxHashMap<String, Vec<serde_json::Value>> = FxHashMap::default();
29
-
30
- while let Some(field) = multipart.next_field().await? {
31
- let name = field.name().ok_or("Field missing name")?.to_string();
32
-
33
- let field_value = if let Some(filename) = field.file_name() {
34
- let filename = filename.to_string();
35
- let content_type = field
36
- .content_type()
37
- .map(|ct| ct.to_string())
38
- .unwrap_or_else(|| "application/octet-stream".to_string());
39
-
40
- let bytes = field.bytes().await?;
41
- let size = bytes.len();
42
-
43
- let is_text_like = content_type.starts_with("text/") || content_type == "application/json";
44
- let content = if is_text_like || size <= MULTIPART_STREAMING_THRESHOLD {
45
- String::from_utf8_lossy(&bytes).to_string()
46
- } else {
47
- format!("<binary data, {} bytes>", size)
48
- };
49
-
50
- json!({
51
- "filename": filename,
52
- "size": size,
53
- "content": content,
54
- "content_type": content_type
55
- })
56
- } else {
57
- let value = field.text().await?;
58
-
59
- if (value.starts_with('[') && value.ends_with(']')) || (value.starts_with('{') && value.ends_with('}')) {
60
- if let Ok(parsed_json) = serde_json::from_str::<serde_json::Value>(&value) {
61
- parsed_json
62
- } else {
63
- json!(value)
64
- }
65
- } else {
66
- json!(value)
67
- }
68
- };
69
-
70
- field_values.entry(name).or_default().push(field_value);
71
- }
72
-
73
- let result: serde_json::Map<String, serde_json::Value> = field_values
74
- .into_iter()
75
- .map(|(key, mut values)| {
76
- if values.len() == 1 {
77
- let val = values.pop().unwrap_or(serde_json::Value::Null);
78
- (key, val)
79
- } else {
80
- (key, serde_json::Value::Array(values))
81
- }
82
- })
83
- .collect();
84
-
85
- Ok(json!(result))
86
- }
@@ -1,147 +0,0 @@
1
- //! URL-encoded form data parsing
2
-
3
- use std::collections::HashMap;
4
-
5
- /// Parse URL-encoded form data to JSON
6
- ///
7
- /// This handles:
8
- /// - Array notation: tags[]=value1&tags[]=value2 → {"tags": ["value1", "value2"]}
9
- /// - Nested objects: profile[name]=John → {"profile": {"name": "John"}}
10
- /// - Type conversion: age=30 → {"age": 30}, active=true → {"active": true}
11
- /// - Multiple values: tags=a&tags=b → {"tags": ["a", "b"]}
12
- /// - Empty strings: Preserved as empty strings (unlike query parameter parsing)
13
- ///
14
- /// Strategy:
15
- /// - If brackets present → use serde_qs (handles nested objects, arrays with [])
16
- /// - Otherwise → use custom parser that preserves empty strings and handles duplicate keys
17
- pub fn parse_urlencoded_to_json(data: &[u8]) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
18
- let body_str = std::str::from_utf8(data)?;
19
-
20
- if body_str.contains('[') {
21
- let config = serde_qs::Config::new(10, false);
22
- let parsed: HashMap<String, serde_json::Value> = config.deserialize_str(body_str)?;
23
- let mut json_value = serde_json::to_value(parsed)?;
24
- convert_types_recursive(&mut json_value);
25
- Ok(json_value)
26
- } else {
27
- Ok(parse_urlencoded_simple(data))
28
- }
29
- }
30
-
31
- /// Parse simple URL-encoded data (no brackets) while preserving empty strings
32
- fn parse_urlencoded_simple(data: &[u8]) -> serde_json::Value {
33
- use rustc_hash::FxHashMap;
34
- use urlencoding::decode;
35
-
36
- let mut array_map: FxHashMap<String, Vec<serde_json::Value>> = FxHashMap::default();
37
-
38
- let body_str = String::from_utf8_lossy(data);
39
- let body_str = body_str.replace('+', " ");
40
-
41
- for pair in body_str.split('&') {
42
- if pair.is_empty() {
43
- continue;
44
- }
45
-
46
- let (key, value) = if let Some((k, v)) = pair.split_once('=') {
47
- (
48
- decode(k).unwrap_or_default().to_string(),
49
- decode(v).unwrap_or_default().to_string(),
50
- )
51
- } else {
52
- (pair.to_string(), String::new())
53
- };
54
-
55
- let json_value = convert_string_to_json_value(&value);
56
-
57
- match array_map.get_mut(&key) {
58
- Some(entry) => {
59
- entry.push(json_value);
60
- }
61
- None => {
62
- array_map.insert(key, vec![json_value]);
63
- }
64
- }
65
- }
66
-
67
- array_map
68
- .iter()
69
- .map(|(key, value)| {
70
- if value.len() == 1 {
71
- (key, value[0].clone())
72
- } else {
73
- (key, serde_json::Value::Array(value.clone()))
74
- }
75
- })
76
- .collect::<serde_json::Value>()
77
- }
78
-
79
- /// Try to parse a string as an integer
80
- fn try_parse_integer(s: &str) -> Option<serde_json::Value> {
81
- s.parse::<i64>().ok().map(|i| serde_json::Value::Number(i.into()))
82
- }
83
-
84
- /// Try to parse a string as a float
85
- fn try_parse_float(s: &str) -> Option<serde_json::Value> {
86
- s.parse::<f64>()
87
- .ok()
88
- .and_then(|f| serde_json::Number::from_f64(f).map(serde_json::Value::Number))
89
- }
90
-
91
- /// Try to parse a string as a boolean (true/false, case-insensitive)
92
- fn try_parse_boolean(s: &str) -> Option<serde_json::Value> {
93
- match s.to_lowercase().as_str() {
94
- "true" => Some(serde_json::Value::Bool(true)),
95
- "false" => Some(serde_json::Value::Bool(false)),
96
- _ => None,
97
- }
98
- }
99
-
100
- /// Convert a string value to appropriate JSON type while preserving empty strings
101
- pub fn convert_string_to_json_value(s: &str) -> serde_json::Value {
102
- if s.is_empty() {
103
- return serde_json::Value::String(String::new());
104
- }
105
-
106
- try_parse_integer(s)
107
- .or_else(|| try_parse_float(s))
108
- .or_else(|| try_parse_boolean(s))
109
- .or_else(|| {
110
- if s == "null" {
111
- Some(serde_json::Value::Null)
112
- } else {
113
- None
114
- }
115
- })
116
- .unwrap_or_else(|| serde_json::Value::String(s.to_string()))
117
- }
118
-
119
- /// Recursively convert string values to appropriate types (numbers, booleans)
120
- /// while preserving empty strings
121
- fn convert_types_recursive(value: &mut serde_json::Value) {
122
- match value {
123
- serde_json::Value::String(s) => {
124
- if s.is_empty() {
125
- return;
126
- }
127
-
128
- if let Some(parsed) = try_parse_integer(s)
129
- .or_else(|| try_parse_float(s))
130
- .or_else(|| try_parse_boolean(s))
131
- {
132
- *value = parsed;
133
- }
134
- }
135
- serde_json::Value::Array(arr) => {
136
- for item in arr.iter_mut() {
137
- convert_types_recursive(item);
138
- }
139
- }
140
- serde_json::Value::Object(obj) => {
141
- for (_, v) in obj.iter_mut() {
142
- convert_types_recursive(v);
143
- }
144
- }
145
- _ => {}
146
- }
147
- }