jpx-core 0.2.2

Complete JMESPath implementation with 400+ extension functions
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
//! URL parsing and manipulation functions.

use std::collections::HashSet;

use form_urlencoded;
use serde_json::Value;

use crate::functions::{Function, custom_error};
use crate::interpreter::SearchResult;
use crate::registry::register_if_enabled;
use crate::{Context, Runtime, arg, defn};

/// Register URL functions with the runtime, filtered by the enabled set.
pub fn register_filtered(runtime: &mut Runtime, enabled: &HashSet<&str>) {
    register_if_enabled(runtime, "url_encode", enabled, Box::new(UrlEncodeFn::new()));
    register_if_enabled(runtime, "url_decode", enabled, Box::new(UrlDecodeFn::new()));
    register_if_enabled(runtime, "url_parse", enabled, Box::new(UrlParseFn::new()));
    register_if_enabled(runtime, "url_build", enabled, Box::new(UrlBuildFn::new()));
    register_if_enabled(
        runtime,
        "query_string_parse",
        enabled,
        Box::new(QueryStringParseFn::new()),
    );
    register_if_enabled(
        runtime,
        "query_string_build",
        enabled,
        Box::new(QueryStringBuildFn::new()),
    );
}

// =============================================================================
// url_encode(string) -> string
// =============================================================================

defn!(UrlEncodeFn, vec![arg!(string)], None);

impl Function for UrlEncodeFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let input = args[0].as_str().ok_or_else(|| {
            crate::JmespathError::from_ctx(
                ctx,
                crate::ErrorReason::Parse("Expected string argument".to_owned()),
            )
        })?;

        let encoded = urlencoding::encode(input);
        Ok(Value::String(encoded.into_owned()))
    }
}

// =============================================================================
// url_decode(string) -> string
// =============================================================================

defn!(UrlDecodeFn, vec![arg!(string)], None);

impl Function for UrlDecodeFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let input = args[0].as_str().ok_or_else(|| {
            crate::JmespathError::from_ctx(
                ctx,
                crate::ErrorReason::Parse("Expected string argument".to_owned()),
            )
        })?;

        match urlencoding::decode(input) {
            Ok(decoded) => Ok(Value::String(decoded.into_owned())),
            Err(_) => Err(crate::JmespathError::from_ctx(
                ctx,
                crate::ErrorReason::Parse("Invalid URL-encoded input".to_owned()),
            )),
        }
    }
}

// =============================================================================
// url_parse(string) -> object (parse URL into components)
// =============================================================================

defn!(UrlParseFn, vec![arg!(string)], None);

impl Function for UrlParseFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let input = args[0].as_str().ok_or_else(|| {
            crate::JmespathError::from_ctx(
                ctx,
                crate::ErrorReason::Parse("Expected string argument".to_owned()),
            )
        })?;

        match url::Url::parse(input) {
            Ok(parsed) => {
                let mut result = serde_json::Map::new();

                result.insert(
                    "scheme".to_string(),
                    Value::String(parsed.scheme().to_string()),
                );

                if let Some(host) = parsed.host_str() {
                    result.insert("host".to_string(), Value::String(host.to_string()));
                } else {
                    result.insert("host".to_string(), Value::Null);
                }

                if let Some(port) = parsed.port() {
                    result.insert(
                        "port".to_string(),
                        Value::Number(serde_json::Number::from(port)),
                    );
                } else {
                    result.insert("port".to_string(), Value::Null);
                }

                result.insert("path".to_string(), Value::String(parsed.path().to_string()));

                if let Some(query) = parsed.query() {
                    result.insert("query".to_string(), Value::String(query.to_string()));
                } else {
                    result.insert("query".to_string(), Value::Null);
                }

                if let Some(fragment) = parsed.fragment() {
                    result.insert("fragment".to_string(), Value::String(fragment.to_string()));
                } else {
                    result.insert("fragment".to_string(), Value::Null);
                }

                if !parsed.username().is_empty() {
                    result.insert(
                        "username".to_string(),
                        Value::String(parsed.username().to_string()),
                    );
                }

                if let Some(password) = parsed.password() {
                    result.insert("password".to_string(), Value::String(password.to_string()));
                }

                // Add origin field (scheme + host + port)
                let origin = parsed.origin().ascii_serialization();
                result.insert("origin".to_string(), Value::String(origin));

                Ok(Value::Object(result))
            }
            // Return null for invalid URLs instead of an error
            Err(_) => Ok(Value::Null),
        }
    }
}

// =============================================================================
// url_build(object) -> string (build URL from components)
// =============================================================================

defn!(UrlBuildFn, vec![arg!(object)], None);

impl Function for UrlBuildFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let obj = args[0]
            .as_object()
            .ok_or_else(|| custom_error(ctx, "Expected object argument"))?;

        let scheme = obj
            .get("scheme")
            .and_then(|v| v.as_str())
            .ok_or_else(|| custom_error(ctx, "url_build: 'scheme' is required"))?;

        let host = obj
            .get("host")
            .and_then(|v| v.as_str())
            .ok_or_else(|| custom_error(ctx, "url_build: 'host' is required"))?;

        let base = format!("{scheme}://{host}");
        let mut url = url::Url::parse(&base)
            .map_err(|e| custom_error(ctx, &format!("url_build: invalid scheme/host: {e}")))?;

        if let Some(port) = obj.get("port")
            && let Some(p) = port.as_u64()
        {
            url.set_port(Some(p as u16))
                .map_err(|()| custom_error(ctx, "url_build: cannot set port on this URL"))?;
        }

        if let Some(path) = obj.get("path").and_then(|v| v.as_str()) {
            url.set_path(path);
        }

        if let Some(query) = obj.get("query").and_then(|v| v.as_str()) {
            url.set_query(Some(query));
        }

        if let Some(fragment) = obj.get("fragment").and_then(|v| v.as_str()) {
            url.set_fragment(Some(fragment));
        }

        if let Some(username) = obj.get("username").and_then(|v| v.as_str()) {
            url.set_username(username)
                .map_err(|()| custom_error(ctx, "url_build: cannot set username on this URL"))?;
        }

        if let Some(password) = obj.get("password").and_then(|v| v.as_str()) {
            url.set_password(Some(password))
                .map_err(|()| custom_error(ctx, "url_build: cannot set password on this URL"))?;
        }

        Ok(Value::String(url.to_string()))
    }
}

// =============================================================================
// query_string_parse(string) -> object
// =============================================================================

defn!(QueryStringParseFn, vec![arg!(string)], None);

impl Function for QueryStringParseFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let input = args[0]
            .as_str()
            .ok_or_else(|| custom_error(ctx, "Expected string argument"))?;

        let mut map = serde_json::Map::new();
        for (key, value) in form_urlencoded::parse(input.as_bytes()) {
            map.insert(key.into_owned(), Value::String(value.into_owned()));
        }

        Ok(Value::Object(map))
    }
}

// =============================================================================
// query_string_build(object) -> string
// =============================================================================

defn!(QueryStringBuildFn, vec![arg!(object)], None);

impl Function for QueryStringBuildFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let obj = args[0]
            .as_object()
            .ok_or_else(|| custom_error(ctx, "Expected object argument"))?;

        let mut serializer = form_urlencoded::Serializer::new(String::new());
        for (key, value) in obj {
            let val_str = match value {
                Value::String(s) => s.clone(),
                Value::Number(n) => n.to_string(),
                Value::Bool(b) => b.to_string(),
                Value::Null => "null".to_string(),
                _ => serde_json::to_string(value).unwrap_or_default(),
            };
            serializer.append_pair(key, &val_str);
        }

        Ok(Value::String(serializer.finish()))
    }
}

#[cfg(test)]
mod tests {
    use crate::Runtime;
    use serde_json::json;

    fn setup_runtime() -> Runtime {
        Runtime::builder()
            .with_standard()
            .with_all_extensions()
            .build()
    }

    #[test]
    fn test_url_encode() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_encode(@)").unwrap();
        let data = json!("hello world");
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "hello%20world");
    }

    #[test]
    fn test_url_decode() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_decode(@)").unwrap();
        let data = json!("hello%20world");
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "hello world");
    }

    #[test]
    fn test_url_parse() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_parse(@)").unwrap();
        let data = json!("https://example.com:8080/path?query=1#frag");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("scheme").unwrap().as_str().unwrap(), "https");
        assert_eq!(obj.get("host").unwrap().as_str().unwrap(), "example.com");
        assert_eq!(obj.get("port").unwrap().as_f64().unwrap() as u16, 8080);
    }

    #[test]
    fn test_url_parse_origin() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_parse(@)").unwrap();
        let data = json!("https://example.com:8080/path");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(
            obj.get("origin").unwrap().as_str().unwrap(),
            "https://example.com:8080"
        );
    }

    #[test]
    fn test_url_parse_invalid_returns_null() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_parse(@)").unwrap();
        let data = json!("not a valid url");
        let result = expr.search(&data).unwrap();
        assert!(result.is_null());
    }

    // url_build tests

    #[test]
    fn test_url_build_minimal() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_build(@)").unwrap();
        let data = json!({"scheme": "https", "host": "example.com"});
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "https://example.com/");
    }

    #[test]
    fn test_url_build_full() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_build(@)").unwrap();
        let data = json!({
            "scheme": "https",
            "host": "example.com",
            "port": 8080,
            "path": "/api/v1",
            "query": "key=value",
            "fragment": "section",
            "username": "user",
            "password": "pass"
        });
        let result = expr.search(&data).unwrap();
        assert_eq!(
            result.as_str().unwrap(),
            "https://user:pass@example.com:8080/api/v1?key=value#section"
        );
    }

    #[test]
    fn test_url_build_roundtrip() {
        let runtime = setup_runtime();
        let original = "https://example.com:8080/path?q=1#frag";
        let parse_expr = runtime.compile("url_parse(@)").unwrap();
        let parsed = parse_expr.search(&json!(original)).unwrap();

        let build_expr = runtime.compile("url_build(@)").unwrap();
        let rebuilt = build_expr.search(&parsed).unwrap();
        assert_eq!(rebuilt.as_str().unwrap(), original);
    }

    // query_string_parse tests

    #[test]
    fn test_query_string_parse_basic() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_parse(@)").unwrap();
        let data = json!("foo=bar&baz=qux");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("foo").unwrap().as_str().unwrap(), "bar");
        assert_eq!(obj.get("baz").unwrap().as_str().unwrap(), "qux");
    }

    #[test]
    fn test_query_string_parse_encoded() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_parse(@)").unwrap();
        let data = json!("greeting=hello%20world&special=a%2Bb");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(
            obj.get("greeting").unwrap().as_str().unwrap(),
            "hello world"
        );
        assert_eq!(obj.get("special").unwrap().as_str().unwrap(), "a+b");
    }

    #[test]
    fn test_query_string_parse_empty() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_parse(@)").unwrap();
        let data = json!("");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert!(obj.is_empty());
    }

    // query_string_build tests

    #[test]
    fn test_query_string_build_basic() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_build(@)").unwrap();
        let data = json!({"foo": "bar", "baz": "qux"});
        let result = expr.search(&data).unwrap();
        let qs = result.as_str().unwrap();
        // Object key order is deterministic in serde_json
        assert!(qs.contains("foo=bar"));
        assert!(qs.contains("baz=qux"));
    }

    #[test]
    fn test_query_string_build_special_chars() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_build(@)").unwrap();
        let data = json!({"greeting": "hello world", "op": "a+b"});
        let result = expr.search(&data).unwrap();
        let qs = result.as_str().unwrap();
        assert!(qs.contains("greeting=hello+world"));
        assert!(qs.contains("op=a%2Bb"));
    }

    #[test]
    fn test_query_string_build_empty() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_build(@)").unwrap();
        let data = json!({});
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_url_encode_special_chars() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_encode(@)").unwrap();

        let result = expr.search(&json!("a&b=c")).unwrap();
        assert_eq!(result.as_str().unwrap(), "a%26b%3Dc");

        let result = expr.search(&json!("foo/bar?baz")).unwrap();
        assert_eq!(result.as_str().unwrap(), "foo%2Fbar%3Fbaz");
    }

    #[test]
    fn test_url_decode_passthrough() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_decode(@)").unwrap();

        // Plain text without percent-encoding passes through
        let result = expr.search(&json!("hello")).unwrap();
        assert_eq!(result.as_str().unwrap(), "hello");
    }

    #[test]
    fn test_url_encode_decode_roundtrip() {
        let runtime = setup_runtime();
        let data = json!("hello world & goodbye=yes");
        let encode = runtime.compile("url_encode(@)").unwrap();
        let encoded = encode.search(&data).unwrap();

        let decode = runtime.compile("url_decode(@)").unwrap();
        let decoded = decode.search(&encoded).unwrap();
        assert_eq!(decoded.as_str().unwrap(), "hello world & goodbye=yes");
    }

    #[test]
    fn test_url_parse_no_port() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_parse(@)").unwrap();
        let data = json!("https://example.com/path");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("host").unwrap().as_str().unwrap(), "example.com");
        assert!(obj.get("port").unwrap().is_null());
        assert_eq!(obj.get("path").unwrap().as_str().unwrap(), "/path");
    }

    #[test]
    fn test_url_parse_query_and_fragment() {
        let runtime = setup_runtime();
        let expr = runtime.compile("url_parse(@)").unwrap();
        let data = json!("https://example.com/path?key=val#section");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("query").unwrap().as_str().unwrap(), "key=val");
        assert_eq!(obj.get("fragment").unwrap().as_str().unwrap(), "section");
    }

    #[test]
    fn test_query_string_parse_no_value() {
        let runtime = setup_runtime();
        let expr = runtime.compile("query_string_parse(@)").unwrap();
        // Key with no value
        let data = json!("flag&key=value");
        let result = expr.search(&data).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("flag").unwrap().as_str().unwrap(), "");
        assert_eq!(obj.get("key").unwrap().as_str().unwrap(), "value");
    }

    #[test]
    fn test_query_string_roundtrip() {
        let runtime = setup_runtime();
        let original = json!({"name": "John Doe", "age": "30"});
        let build = runtime.compile("query_string_build(@)").unwrap();
        let qs = build.search(&original).unwrap();

        let parse = runtime.compile("query_string_parse(@)").unwrap();
        let parsed = parse.search(&qs).unwrap();
        let obj = parsed.as_object().unwrap();
        assert_eq!(obj.get("name").unwrap().as_str().unwrap(), "John Doe");
        assert_eq!(obj.get("age").unwrap().as_str().unwrap(), "30");
    }
}