1
/*
2
 * Hurl (https://hurl.dev)
3
 * Copyright (C) 2026 Orange
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *          http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 */
18
use base64::engine::general_purpose;
19
use base64::Engine;
20
use hurl_core::ast::{
21
    Assert, Base64, Body, BooleanOption, Bytes, Capture, CertificateAttributeName, Comment, Cookie,
22
    CountOption, DurationOption, Entry, EntryOption, File, FilenameParam, Filter, FilterValue, Hex,
23
    HurlFile, JsonListElement, JsonValue, KeyValue, MultilineString, MultilineStringKind,
24
    MultipartParam, NaturalOption, OptionKind, Placeholder, Predicate, PredicateFuncValue,
25
    PredicateValue, Query, QueryValue, Regex, RegexValue, Request, Response, StatusValue,
26
    VersionValue,
27
};
28
use hurl_core::types::{Count, Duration, ToSource};
29

            
30
use crate::format::serialize_json::JValue;
31

            
32
57
pub fn format(hurl_file: &HurlFile) -> String {
33
57
    hurl_file.to_json().format()
34
}
35

            
36
pub trait ToJson {
37
    fn to_json(&self) -> JValue;
38
}
39

            
40
impl ToJson for HurlFile {
41
57
    fn to_json(&self) -> JValue {
42
57
        JValue::Object(vec![(
43
57
            "entries".to_string(),
44
214
            JValue::List(self.entries.iter().map(|e| e.to_json()).collect()),
45
        )])
46
    }
47
}
48

            
49
impl ToJson for Entry {
50
195
    fn to_json(&self) -> JValue {
51
195
        let mut attributes = vec![("request".to_string(), self.request.to_json())];
52
195
        if let Some(response) = &self.response {
53
87
            attributes.push(("response".to_string(), response.to_json()));
54
        }
55
195
        JValue::Object(attributes)
56
    }
57
}
58

            
59
impl ToJson for Request {
60
195
    fn to_json(&self) -> JValue {
61
195
        let mut attributes = vec![
62
195
            (
63
195
                "method".to_string(),
64
195
                JValue::String(self.method.to_string()),
65
195
            ),
66
195
            ("url".to_string(), JValue::String(self.url.to_string())),
67
        ];
68
195
        add_headers(&mut attributes, &self.headers);
69

            
70
195
        if !self.querystring_params().is_empty() {
71
6
            let params = self
72
6
                .querystring_params()
73
6
                .iter()
74
17
                .map(|p| p.to_json())
75
6
                .collect();
76
6
            attributes.push(("query_string_params".to_string(), JValue::List(params)));
77
        }
78
195
        if !self.form_params().is_empty() {
79
13
            let params = self.form_params().iter().map(|p| p.to_json()).collect();
80
3
            attributes.push(("form_params".to_string(), JValue::List(params)));
81
        }
82
195
        if !self.multipart_form_data().is_empty() {
83
3
            let params = self
84
3
                .multipart_form_data()
85
3
                .iter()
86
10
                .map(|p| p.to_json())
87
3
                .collect();
88
3
            attributes.push(("multipart_form_data".to_string(), JValue::List(params)));
89
        }
90
195
        if !self.cookies().is_empty() {
91
7
            let cookies = self.cookies().iter().map(|c| c.to_json()).collect();
92
3
            attributes.push(("cookies".to_string(), JValue::List(cookies)));
93
        }
94
195
        if !self.options().is_empty() {
95
310
            let options = self.options().iter().map(|c| c.to_json()).collect();
96
12
            attributes.push(("options".to_string(), JValue::List(options)));
97
        }
98
195
        if let Some(body) = &self.body {
99
48
            attributes.push(("body".to_string(), body.to_json()));
100
        }
101

            
102
        // Request comments (can be used to check custom commands)
103
195
        let comments: Vec<_> = self
104
195
            .line_terminators
105
195
            .iter()
106
239
            .filter_map(|l| l.comment.as_ref())
107
195
            .collect();
108
195
        if !comments.is_empty() {
109
33
            let comments = comments.iter().map(|c| c.to_json()).collect();
110
18
            attributes.push(("comments".to_string(), JValue::List(comments)));
111
        }
112

            
113
195
        JValue::Object(attributes)
114
    }
115
}
116

            
117
impl ToJson for Response {
118
    /// Transforms this response to a JSON object.
119
87
    fn to_json(&self) -> JValue {
120
87
        let mut attributes = vec![];
121
87
        if let Some(v) = get_json_version(&self.version.value) {
122
12
            attributes.push(("version".to_string(), JValue::String(v)));
123
        }
124
87
        if let StatusValue::Specific(n) = self.status.value {
125
87
            attributes.push(("status".to_string(), JValue::Number(n.to_string())));
126
        }
127
87
        add_headers(&mut attributes, &self.headers);
128
87
        if !self.captures().is_empty() {
129
21
            let captures = self.captures().iter().map(|c| c.to_json()).collect();
130
9
            attributes.push(("captures".to_string(), JValue::List(captures)));
131
        }
132
87
        if !self.asserts().is_empty() {
133
384
            let asserts = self.asserts().iter().map(|a| a.to_json()).collect();
134
36
            attributes.push(("asserts".to_string(), JValue::List(asserts)));
135
        }
136
87
        if let Some(body) = &self.body {
137
21
            attributes.push(("body".to_string(), body.to_json()));
138
        }
139
87
        JValue::Object(attributes)
140
    }
141
}
142

            
143
282
fn add_headers(attributes: &mut Vec<(String, JValue)>, headers: &[KeyValue]) {
144
282
    if !headers.is_empty() {
145
62
        let headers = JValue::List(headers.iter().map(|h| h.to_json()).collect());
146
24
        attributes.push(("headers".to_string(), headers));
147
    }
148
}
149

            
150
impl ToJson for Body {
151
69
    fn to_json(&self) -> JValue {
152
69
        self.value.to_json()
153
    }
154
}
155

            
156
impl ToJson for Bytes {
157
69
    fn to_json(&self) -> JValue {
158
69
        match self {
159
6
            Bytes::Base64(value) => value.to_json(),
160
3
            Bytes::Hex(value) => value.to_json(),
161
3
            Bytes::File(value) => value.to_json(),
162
6
            Bytes::Json(value) => JValue::Object(vec![
163
6
                ("type".to_string(), JValue::String("json".to_string())),
164
6
                ("value".to_string(), value.to_json()),
165
6
            ]),
166
3
            Bytes::Xml(value) => JValue::Object(vec![
167
3
                ("type".to_string(), JValue::String("xml".to_string())),
168
3
                ("value".to_string(), JValue::String(value.clone())),
169
3
            ]),
170
9
            Bytes::OnelineString(value) => JValue::Object(vec![
171
9
                ("type".to_string(), JValue::String("text".to_string())),
172
9
                ("value".to_string(), JValue::String(value.to_string())),
173
9
            ]),
174
39
            Bytes::MultilineString(multi) => {
175
                // TODO: check these values. Maybe we want to have the same
176
                // export when using:
177
                //
178
                // ~~~
179
                // GET https://foo.com
180
                // ```base64
181
                // SGVsbG8gd29ybGQ=
182
                // ```
183
                //
184
                // or
185
                //
186
                // ~~~
187
                // GET https://foo.com
188
                // base64,SGVsbG8gd29ybGQ=;
189
                // ~~~
190
39
                let lang = match multi {
191
                    MultilineString {
192
                        kind: MultilineStringKind::Text(_),
193
                        ..
194
15
                    } => "text",
195
                    MultilineString {
196
                        kind: MultilineStringKind::Json(_),
197
                        ..
198
9
                    } => "json",
199
                    MultilineString {
200
                        kind: MultilineStringKind::Xml(_),
201
                        ..
202
6
                    } => "xml",
203
                    MultilineString {
204
                        kind: MultilineStringKind::GraphQl(_),
205
                        ..
206
9
                    } => "graphql",
207
                };
208
39
                JValue::Object(vec![
209
39
                    ("type".to_string(), JValue::String(lang.to_string())),
210
39
                    ("value".to_string(), JValue::String(multi.to_string())),
211
39
                ])
212
            }
213
        }
214
    }
215
}
216

            
217
impl ToJson for Base64 {
218
6
    fn to_json(&self) -> JValue {
219
6
        let value = general_purpose::STANDARD.encode(&self.value);
220
6
        JValue::Object(vec![
221
6
            ("encoding".to_string(), JValue::String("base64".to_string())),
222
6
            ("value".to_string(), JValue::String(value)),
223
6
        ])
224
    }
225
}
226

            
227
impl ToJson for Hex {
228
3
    fn to_json(&self) -> JValue {
229
3
        let value = general_purpose::STANDARD.encode(&self.value);
230
3
        JValue::Object(vec![
231
3
            ("encoding".to_string(), JValue::String("base64".to_string())),
232
3
            ("value".to_string(), JValue::String(value)),
233
3
        ])
234
    }
235
}
236

            
237
impl ToJson for File {
238
6
    fn to_json(&self) -> JValue {
239
6
        JValue::Object(vec![
240
6
            ("type".to_string(), JValue::String("file".to_string())),
241
6
            (
242
6
                "filename".to_string(),
243
6
                JValue::String(self.filename.to_string()),
244
6
            ),
245
6
        ])
246
    }
247
}
248

            
249
87
fn get_json_version(version_value: &VersionValue) -> Option<String> {
250
87
    match version_value {
251
3
        VersionValue::Version1 => Some("HTTP/1.0".to_string()),
252
3
        VersionValue::Version11 => Some("HTTP/1.1".to_string()),
253
3
        VersionValue::Version2 => Some("HTTP/2".to_string()),
254
3
        VersionValue::Version3 => Some("HTTP/3".to_string()),
255
75
        VersionValue::VersionAny => None,
256
    }
257
}
258

            
259
impl ToJson for KeyValue {
260
84
    fn to_json(&self) -> JValue {
261
84
        let attributes = vec![
262
84
            ("name".to_string(), JValue::String(self.key.to_string())),
263
84
            ("value".to_string(), JValue::String(self.value.to_string())),
264
        ];
265
84
        JValue::Object(attributes)
266
    }
267
}
268

            
269
impl ToJson for MultipartParam {
270
9
    fn to_json(&self) -> JValue {
271
9
        match self {
272
3
            MultipartParam::Param(param) => param.to_json(),
273
6
            MultipartParam::FilenameParam(param) => param.to_json(),
274
        }
275
    }
276
}
277

            
278
impl ToJson for FilenameParam {
279
6
    fn to_json(&self) -> JValue {
280
6
        let mut attributes = vec![
281
6
            ("name".to_string(), JValue::String(self.key.to_string())),
282
6
            (
283
6
                "filename".to_string(),
284
6
                JValue::String(self.value.filename.to_string()),
285
6
            ),
286
        ];
287
6
        if let Some(content_type) = &self.value.content_type {
288
3
            attributes.push((
289
3
                "content_type".to_string(),
290
3
                JValue::String(content_type.to_string()),
291
3
            ));
292
        }
293
6
        JValue::Object(attributes)
294
    }
295
}
296

            
297
impl ToJson for Cookie {
298
6
    fn to_json(&self) -> JValue {
299
6
        let attributes = vec![
300
6
            ("name".to_string(), JValue::String(self.name.to_string())),
301
6
            ("value".to_string(), JValue::String(self.value.to_string())),
302
        ];
303
6
        JValue::Object(attributes)
304
    }
305
}
306

            
307
impl ToJson for EntryOption {
308
306
    fn to_json(&self) -> JValue {
309
306
        let value = match &self.kind {
310
6
            OptionKind::AwsSigV4(value) => JValue::String(value.to_string()),
311
6
            OptionKind::CaCertificate(filename) => JValue::String(filename.to_string()),
312
9
            OptionKind::ClientCert(filename) => JValue::String(filename.to_string()),
313
6
            OptionKind::ClientKey(filename) => JValue::String(filename.to_string()),
314
6
            OptionKind::Compressed(value) => value.to_json(),
315
6
            OptionKind::ConnectTo(value) => JValue::String(value.to_string()),
316
6
            OptionKind::ConnectTimeout(value) => value.to_json(),
317
18
            OptionKind::Delay(value) => value.to_json(),
318
6
            OptionKind::Digest(value) => value.to_json(),
319
6
            OptionKind::FollowLocation(value) => value.to_json(),
320
6
            OptionKind::FollowLocationTrusted(value) => value.to_json(),
321
6
            OptionKind::Header(value) => JValue::String(value.to_string()),
322
6
            OptionKind::Http10(value) => value.to_json(),
323
6
            OptionKind::Http11(value) => value.to_json(),
324
6
            OptionKind::Http2(value) => value.to_json(),
325
6
            OptionKind::Http3(value) => value.to_json(),
326
6
            OptionKind::Insecure(value) => value.to_json(),
327
6
            OptionKind::IpV4(value) => value.to_json(),
328
6
            OptionKind::IpV6(value) => value.to_json(),
329
6
            OptionKind::LimitRate(value) => value.to_json(),
330
6
            OptionKind::MaxRedirect(value) => value.to_json(),
331
6
            OptionKind::MaxTime(value) => value.to_json(),
332
6
            OptionKind::Negotiate(value) => value.to_json(),
333
6
            OptionKind::NetRc(value) => value.to_json(),
334
6
            OptionKind::NetRcFile(filename) => JValue::String(filename.to_string()),
335
6
            OptionKind::NetRcOptional(value) => value.to_json(),
336
6
            OptionKind::Ntlm(value) => value.to_json(),
337
6
            OptionKind::Output(filename) => JValue::String(filename.to_string()),
338
6
            OptionKind::PathAsIs(value) => value.to_json(),
339
6
            OptionKind::PinnedPublicKey(value) => JValue::String(value.to_string()),
340
6
            OptionKind::Proxy(value) => JValue::String(value.to_string()),
341
9
            OptionKind::Repeat(value) => value.to_json(),
342
6
            OptionKind::Resolve(value) => JValue::String(value.to_string()),
343
12
            OptionKind::Retry(value) => value.to_json(),
344
12
            OptionKind::RetryInterval(value) => value.to_json(),
345
6
            OptionKind::Skip(value) => value.to_json(),
346
6
            OptionKind::UnixSocket(value) => JValue::String(value.to_string()),
347
6
            OptionKind::User(value) => JValue::String(value.to_string()),
348
27
            OptionKind::Variable(value) => {
349
27
                JValue::String(format!("{}={}", value.name, value.value.to_source()))
350
            }
351
9
            OptionKind::Verbose(value) => value.to_json(),
352
6
            OptionKind::Verbosity(value) => JValue::String(value.to_string()),
353
6
            OptionKind::VeryVerbose(value) => value.to_json(),
354
        };
355

            
356
        // If the value contains the unit such as `{ "value": 10, "unit": "second" }`
357
        // The JSON for this option should still have one level
358
        // for example: { "name": "delay", "value": 10, "unit", "second" }
359
306
        let attributes = if let JValue::Object(mut attributes) = value {
360
24
            attributes.push((
361
24
                "name".to_string(),
362
24
                JValue::String(self.kind.identifier().to_string()),
363
24
            ));
364
24
            attributes
365
        } else {
366
282
            vec![
367
282
                (
368
282
                    "name".to_string(),
369
282
                    JValue::String(self.kind.identifier().to_string()),
370
282
                ),
371
282
                ("value".to_string(), value),
372
            ]
373
        };
374
306
        JValue::Object(attributes)
375
    }
376
}
377

            
378
impl ToJson for BooleanOption {
379
117
    fn to_json(&self) -> JValue {
380
117
        match self {
381
60
            BooleanOption::Literal(value) => JValue::Boolean(*value),
382
57
            BooleanOption::Placeholder(placeholder) => placeholder.to_json(),
383
        }
384
    }
385
}
386

            
387
impl ToJson for CountOption {
388
27
    fn to_json(&self) -> JValue {
389
27
        match self {
390
18
            CountOption::Literal(value) => value.to_json(),
391
9
            CountOption::Placeholder(placeholder) => placeholder.to_json(),
392
        }
393
    }
394
}
395

            
396
impl ToJson for Count {
397
18
    fn to_json(&self) -> JValue {
398
18
        match self {
399
12
            Count::Finite(n) => JValue::Number(n.to_string()),
400
6
            Count::Infinite => JValue::Number("-1".to_string()),
401
        }
402
    }
403
}
404

            
405
impl ToJson for DurationOption {
406
42
    fn to_json(&self) -> JValue {
407
42
        match self {
408
30
            DurationOption::Literal(value) => value.to_json(),
409
12
            DurationOption::Placeholder(placeholder) => placeholder.to_json(),
410
        }
411
    }
412
}
413

            
414
impl ToJson for Duration {
415
30
    fn to_json(&self) -> JValue {
416
30
        if let Some(unit) = self.unit {
417
24
            let mut attributes =
418
24
                vec![("value".to_string(), JValue::Number(self.value.to_string()))];
419
24
            attributes.push(("unit".to_string(), JValue::String(unit.to_string())));
420
24
            JValue::Object(attributes)
421
        } else {
422
6
            JValue::Number(self.value.to_string())
423
        }
424
    }
425
}
426

            
427
impl ToJson for Capture {
428
18
    fn to_json(&self) -> JValue {
429
18
        let mut attributes = vec![
430
18
            ("name".to_string(), JValue::String(self.name.to_string())),
431
18
            ("query".to_string(), self.query.to_json()),
432
        ];
433
18
        if !self.filters.is_empty() {
434
4
            let filters = JValue::List(self.filters.iter().map(|(_, f)| f.to_json()).collect());
435
3
            attributes.push(("filters".to_string(), filters));
436
        }
437
18
        if self.redacted {
438
6
            attributes.push(("redact".to_string(), JValue::Boolean(true)));
439
        }
440
18
        JValue::Object(attributes)
441
    }
442
}
443

            
444
impl ToJson for Assert {
445
372
    fn to_json(&self) -> JValue {
446
372
        let mut attributes = vec![("query".to_string(), self.query.to_json())];
447
372
        if !self.filters.is_empty() {
448
179
            let filters = JValue::List(self.filters.iter().map(|(_, f)| f.to_json()).collect());
449
114
            attributes.push(("filters".to_string(), filters));
450
        }
451
372
        attributes.push(("predicate".to_string(), self.predicate.to_json()));
452
372
        JValue::Object(attributes)
453
    }
454
}
455

            
456
impl ToJson for Query {
457
390
    fn to_json(&self) -> JValue {
458
390
        let attributes = query_value_attributes(&self.value);
459
390
        JValue::Object(attributes)
460
    }
461
}
462

            
463
390
fn query_value_attributes(query_value: &QueryValue) -> Vec<(String, JValue)> {
464
390
    let mut attributes = vec![];
465
390
    let att_type = JValue::String(query_value.identifier().to_string());
466
390
    attributes.push(("type".to_string(), att_type));
467

            
468
390
    match query_value {
469
243
        QueryValue::Jsonpath { expr, .. } => {
470
243
            attributes.push(("expr".to_string(), JValue::String(expr.to_string())));
471
        }
472
6
        QueryValue::Header { name, .. } => {
473
6
            attributes.push(("name".to_string(), JValue::String(name.to_string())));
474
        }
475
9
        QueryValue::Cookie { expr, .. } => {
476
9
            attributes.push(("expr".to_string(), JValue::String(expr.to_string())));
477
        }
478
3
        QueryValue::Xpath { expr, .. } => {
479
3
            attributes.push(("expr".to_string(), JValue::String(expr.to_string())));
480
        }
481
3
        QueryValue::Regex { value, .. } => {
482
3
            attributes.push(("expr".to_string(), value.to_json()));
483
        }
484
9
        QueryValue::Variable { name, .. } => {
485
9
            attributes.push(("name".to_string(), JValue::String(name.to_string())));
486
        }
487
        QueryValue::Certificate {
488
33
            attribute_name: field,
489
            ..
490
33
        } => {
491
33
            attributes.push(("expr".to_string(), field.to_json()));
492
        }
493
84
        _ => {}
494
    };
495
390
    attributes
496
}
497

            
498
impl ToJson for RegexValue {
499
9
    fn to_json(&self) -> JValue {
500
9
        match self {
501
3
            RegexValue::Template(template) => JValue::String(template.to_string()),
502
6
            RegexValue::Regex(regex) => regex.to_json(),
503
        }
504
    }
505
}
506

            
507
impl ToJson for Regex {
508
6
    fn to_json(&self) -> JValue {
509
6
        let attributes = vec![
510
6
            ("type".to_string(), JValue::String("regex".to_string())),
511
6
            ("value".to_string(), JValue::String(self.to_string())),
512
        ];
513
6
        JValue::Object(attributes)
514
    }
515
}
516

            
517
impl ToJson for CertificateAttributeName {
518
33
    fn to_json(&self) -> JValue {
519
33
        JValue::String(self.identifier().to_string())
520
    }
521
}
522

            
523
impl ToJson for Predicate {
524
372
    fn to_json(&self) -> JValue {
525
372
        let mut attributes = vec![];
526
372
        if self.not {
527
3
            attributes.push(("not".to_string(), JValue::Boolean(true)));
528
        }
529
372
        let identifier = self.predicate_func.value.identifier();
530
372
        attributes.push(("type".to_string(), JValue::String(identifier.to_string())));
531

            
532
372
        match &self.predicate_func.value {
533
249
            PredicateFuncValue::Equal { value, .. } => add_predicate_value(&mut attributes, value),
534
9
            PredicateFuncValue::NotEqual { value, .. } => {
535
9
                add_predicate_value(&mut attributes, value);
536
            }
537
9
            PredicateFuncValue::GreaterThan { value, .. } => {
538
9
                add_predicate_value(&mut attributes, value);
539
            }
540
3
            PredicateFuncValue::GreaterThanOrEqual { value, .. } => {
541
3
                add_predicate_value(&mut attributes, value);
542
            }
543
9
            PredicateFuncValue::LessThan { value, .. } => {
544
9
                add_predicate_value(&mut attributes, value);
545
            }
546
3
            PredicateFuncValue::LessThanOrEqual { value, .. } => {
547
3
                add_predicate_value(&mut attributes, value);
548
            }
549
9
            PredicateFuncValue::StartWith { value, .. } => {
550
9
                add_predicate_value(&mut attributes, value);
551
            }
552
6
            PredicateFuncValue::EndWith { value, .. } => {
553
6
                add_predicate_value(&mut attributes, value);
554
            }
555
9
            PredicateFuncValue::Contain { value, .. } => {
556
9
                add_predicate_value(&mut attributes, value);
557
            }
558
3
            PredicateFuncValue::Include { value, .. } => {
559
3
                add_predicate_value(&mut attributes, value);
560
            }
561
9
            PredicateFuncValue::Match { value, .. } => {
562
9
                add_predicate_value(&mut attributes, value);
563
            }
564
            PredicateFuncValue::Exist
565
            | PredicateFuncValue::IsBoolean
566
            | PredicateFuncValue::IsCollection
567
            | PredicateFuncValue::IsDate
568
            | PredicateFuncValue::IsEmpty
569
            | PredicateFuncValue::IsFloat
570
            | PredicateFuncValue::IsInteger
571
            | PredicateFuncValue::IsIpv4
572
            | PredicateFuncValue::IsIpv6
573
            | PredicateFuncValue::IsIsoDate
574
            | PredicateFuncValue::IsList
575
            | PredicateFuncValue::IsNumber
576
            | PredicateFuncValue::IsObject
577
            | PredicateFuncValue::IsString
578
54
            | PredicateFuncValue::IsUuid => {}
579
        }
580
372
        JValue::Object(attributes)
581
    }
582
}
583

            
584
318
fn add_predicate_value(attributes: &mut Vec<(String, JValue)>, predicate_value: &PredicateValue) {
585
318
    let (value, encoding) = json_predicate_value(predicate_value);
586
318
    attributes.push(("value".to_string(), value));
587
318
    if let Some(encoding) = encoding {
588
36
        attributes.push(("encoding".to_string(), JValue::String(encoding)));
589
    }
590
}
591

            
592
318
fn json_predicate_value(predicate_value: &PredicateValue) -> (JValue, Option<String>) {
593
318
    match predicate_value {
594
147
        PredicateValue::String(value) => (JValue::String(value.to_string()), None),
595
18
        PredicateValue::MultilineString(value) => (JValue::String(value.value().to_string()), None),
596
3
        PredicateValue::Bool(value) => (JValue::Boolean(*value), None),
597
3
        PredicateValue::Null => (JValue::Null, None),
598
105
        PredicateValue::Number(value) => (JValue::Number(value.to_string()), None),
599
3
        PredicateValue::File(value) => (value.to_json(), None),
600
27
        PredicateValue::Hex(value) => {
601
27
            let base64_string = general_purpose::STANDARD.encode(value.value.clone());
602
27
            (JValue::String(base64_string), Some("base64".to_string()))
603
        }
604
3
        PredicateValue::Base64(value) => {
605
3
            let base64_string = general_purpose::STANDARD.encode(value.value.clone());
606
3
            (JValue::String(base64_string), Some("base64".to_string()))
607
        }
608
3
        PredicateValue::Placeholder(value) => (JValue::String(value.to_string()), None),
609
6
        PredicateValue::Regex(value) => {
610
6
            (JValue::String(value.to_string()), Some("regex".to_string()))
611
        }
612
    }
613
}
614

            
615
impl ToJson for JsonValue {
616
102
    fn to_json(&self) -> JValue {
617
102
        match self {
618
3
            JsonValue::Null => JValue::Null,
619
45
            JsonValue::Number(s) => JValue::Number(s.to_string()),
620
18
            JsonValue::String(s) => JValue::String(s.to_string()),
621
3
            JsonValue::Boolean(v) => JValue::Boolean(*v),
622
15
            JsonValue::List { elements, .. } => {
623
56
                JValue::List(elements.iter().map(|e| e.to_json()).collect())
624
            }
625
15
            JsonValue::Object { elements, .. } => JValue::Object(
626
15
                elements
627
15
                    .iter()
628
50
                    .map(|elem| (elem.name.to_string(), elem.value.to_json()))
629
15
                    .collect(),
630
            ),
631
3
            JsonValue::Placeholder(exp) => JValue::String(format!("{{{{{exp}}}}}")),
632
        }
633
    }
634
}
635

            
636
impl ToJson for JsonListElement {
637
51
    fn to_json(&self) -> JValue {
638
51
        self.value.to_json()
639
    }
640
}
641

            
642
impl ToJson for Filter {
643
144
    fn to_json(&self) -> JValue {
644
144
        self.value.to_json()
645
    }
646
}
647

            
648
impl ToJson for FilterValue {
649
144
    fn to_json(&self) -> JValue {
650
144
        let mut attributes = vec![];
651
144
        let att_name = "type".to_string();
652
144
        let att_value = JValue::String(self.identifier().to_string());
653
144
        attributes.push((att_name, att_value));
654

            
655
144
        match self {
656
6
            FilterValue::Decode { encoding, .. } => {
657
6
                attributes.push(("encoding".to_string(), JValue::String(encoding.to_string())));
658
            }
659
6
            FilterValue::Format { fmt, .. } => {
660
6
                attributes.push(("fmt".to_string(), JValue::String(fmt.to_string())));
661
            }
662
9
            FilterValue::DateFormat { fmt, .. } => {
663
9
                attributes.push(("fmt".to_string(), JValue::String(fmt.to_string())));
664
            }
665
9
            FilterValue::JsonPath { expr, .. } => {
666
9
                attributes.push(("expr".to_string(), JValue::String(expr.to_string())));
667
            }
668
3
            FilterValue::Nth { n, .. } => {
669
3
                attributes.push(("n".to_string(), JValue::Number(n.to_string())));
670
            }
671
3
            FilterValue::Regex { value, .. } => {
672
3
                attributes.push(("expr".to_string(), value.to_json()));
673
            }
674
            FilterValue::Replace {
675
15
                old_value,
676
15
                new_value,
677
                ..
678
15
            } => {
679
15
                attributes.push((
680
15
                    "old_value".to_string(),
681
15
                    JValue::String(old_value.to_string()),
682
15
                ));
683
15
                attributes.push((
684
15
                    "new_value".to_string(),
685
15
                    JValue::String(new_value.to_string()),
686
15
                ));
687
            }
688
            FilterValue::ReplaceRegex {
689
3
                pattern, new_value, ..
690
3
            } => {
691
3
                attributes.push(("pattern".to_string(), pattern.to_json()));
692
3
                attributes.push((
693
3
                    "new_value".to_string(),
694
3
                    JValue::String(new_value.to_string()),
695
3
                ));
696
            }
697
3
            FilterValue::Split { sep, .. } => {
698
3
                attributes.push(("sep".to_string(), JValue::String(sep.to_string())));
699
            }
700
3
            FilterValue::ToDate { fmt, .. } => {
701
3
                attributes.push(("fmt".to_string(), JValue::String(fmt.to_string())));
702
            }
703
3
            FilterValue::UrlQueryParam { param, .. } => {
704
3
                attributes.push(("param".to_string(), JValue::String(param.to_string())));
705
            }
706
3
            FilterValue::XPath { expr, .. } => {
707
3
                attributes.push(("expr".to_string(), JValue::String(expr.to_string())));
708
            }
709
78
            _ => {}
710
        }
711
144
        JValue::Object(attributes)
712
    }
713
}
714

            
715
impl ToJson for Placeholder {
716
81
    fn to_json(&self) -> JValue {
717
81
        JValue::String(format!("{{{{{self}}}}}"))
718
    }
719
}
720

            
721
impl ToJson for Comment {
722
27
    fn to_json(&self) -> JValue {
723
27
        JValue::String(self.value.to_string())
724
    }
725
}
726

            
727
impl ToJson for NaturalOption {
728
6
    fn to_json(&self) -> JValue {
729
6
        match self {
730
3
            NaturalOption::Literal(value) => JValue::Number(value.to_string()),
731
3
            NaturalOption::Placeholder(placeholder) => placeholder.to_json(),
732
        }
733
    }
734
}
735
#[cfg(test)]
736
pub mod tests {
737
    use hurl_core::ast::{
738
        LineTerminator, Method, Number, PredicateFunc, SourceInfo, Status, Template,
739
        TemplateElement, Version, Whitespace, I64,
740
    };
741
    use hurl_core::reader::Pos;
742
    use hurl_core::types::ToSource;
743

            
744
    use super::*;
745

            
746
    fn whitespace() -> Whitespace {
747
        Whitespace {
748
            value: String::new(),
749
            source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
750
        }
751
    }
752

            
753
    fn line_terminator() -> LineTerminator {
754
        LineTerminator {
755
            space0: whitespace(),
756
            comment: None,
757
            newline: whitespace(),
758
        }
759
    }
760

            
761
    #[test]
762
    pub fn test_request() {
763
        assert_eq!(
764
            Request {
765
                line_terminators: vec![],
766
                space0: whitespace(),
767
                method: Method::new("GET"),
768
                space1: whitespace(),
769
                url: Template::new(
770
                    None,
771
                    vec![TemplateElement::String {
772
                        value: "http://example.com".to_string(),
773
                        source: "not_used".to_source(),
774
                    }],
775
                    SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
776
                ),
777
                line_terminator0: line_terminator(),
778
                headers: vec![KeyValue {
779
                    line_terminators: vec![],
780
                    space0: whitespace(),
781
                    key: Template::new(
782
                        None,
783
                        vec![TemplateElement::String {
784
                            value: "Foo".to_string(),
785
                            source: "unused".to_source(),
786
                        }],
787
                        SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0))
788
                    ),
789
                    space1: whitespace(),
790
                    space2: whitespace(),
791
                    value: Template::new(
792
                        None,
793
                        vec![TemplateElement::String {
794
                            value: "Bar".to_string(),
795
                            source: "unused".to_source(),
796
                        }],
797
                        SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0))
798
                    ),
799
                    line_terminator0: line_terminator(),
800
                }],
801
                sections: vec![],
802
                body: None,
803
                source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
804
            }
805
            .to_json(),
806
            JValue::Object(vec![
807
                ("method".to_string(), JValue::String("GET".to_string())),
808
                (
809
                    "url".to_string(),
810
                    JValue::String("http://example.com".to_string())
811
                ),
812
                (
813
                    "headers".to_string(),
814
                    JValue::List(vec![JValue::Object(vec![
815
                        ("name".to_string(), JValue::String("Foo".to_string())),
816
                        ("value".to_string(), JValue::String("Bar".to_string()))
817
                    ])])
818
                )
819
            ])
820
        );
821
    }
822

            
823
    #[test]
824
    pub fn test_response() {
825
        assert_eq!(
826
            Response {
827
                line_terminators: vec![],
828
                version: Version {
829
                    value: VersionValue::Version11,
830
                    source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
831
                },
832
                space0: whitespace(),
833
                status: Status {
834
                    value: StatusValue::Specific(200),
835
                    source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
836
                },
837
                space1: whitespace(),
838
                line_terminator0: line_terminator(),
839
                headers: vec![],
840
                sections: vec![],
841
                body: None,
842
                source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
843
            }
844
            .to_json(),
845
            JValue::Object(vec![
846
                (
847
                    "version".to_string(),
848
                    JValue::String("HTTP/1.1".to_string())
849
                ),
850
                ("status".to_string(), JValue::Number("200".to_string()))
851
            ])
852
        );
853
        assert_eq!(
854
            Response {
855
                line_terminators: vec![],
856
                version: Version {
857
                    value: VersionValue::VersionAny,
858
                    source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
859
                },
860
                space0: whitespace(),
861
                status: Status {
862
                    value: StatusValue::Any,
863
                    source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
864
                },
865
                space1: whitespace(),
866
                line_terminator0: line_terminator(),
867
                headers: vec![],
868
                sections: vec![],
869
                body: None,
870
                source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
871
            }
872
            .to_json(),
873
            JValue::Object(vec![])
874
        );
875
    }
876

            
877
    fn header_query() -> Query {
878
        Query {
879
            source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
880
            value: QueryValue::Header {
881
                space0: whitespace(),
882
                name: Template::new(
883
                    None,
884
                    vec![TemplateElement::String {
885
                        value: "Content-Length".to_string(),
886
                        source: "Content-Length".to_source(),
887
                    }],
888
                    SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
889
                ),
890
            },
891
        }
892
    }
893

            
894
    fn header_capture() -> Capture {
895
        Capture {
896
            line_terminators: vec![],
897
            space0: whitespace(),
898
            name: Template::new(
899
                None,
900
                vec![TemplateElement::String {
901
                    value: "size".to_string(),
902
                    source: "unused".to_source(),
903
                }],
904
                SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
905
            ),
906
            space1: whitespace(),
907
            space2: whitespace(),
908
            query: header_query(),
909
            filters: vec![],
910
            space3: whitespace(),
911
            redacted: false,
912
            line_terminator0: line_terminator(),
913
        }
914
    }
915

            
916
    fn header_assert() -> Assert {
917
        Assert {
918
            line_terminators: vec![],
919
            space0: whitespace(),
920
            query: header_query(),
921
            filters: vec![],
922
            space1: whitespace(),
923
            predicate: equal_int_predicate(10),
924
            line_terminator0: line_terminator(),
925
        }
926
    }
927

            
928
    fn equal_int_predicate(value: i64) -> Predicate {
929
        Predicate {
930
            not: false,
931
            space0: whitespace(),
932
            predicate_func: PredicateFunc {
933
                source_info: SourceInfo::new(Pos::new(0, 0), Pos::new(0, 0)),
934
                value: PredicateFuncValue::Equal {
935
                    space0: whitespace(),
936
                    value: PredicateValue::Number(Number::Integer(I64::new(
937
                        value,
938
                        value.to_string().to_source(),
939
                    ))),
940
                },
941
            },
942
        }
943
    }
944

            
945
    #[test]
946
    pub fn test_query() {
947
        assert_eq!(
948
            header_query().to_json(),
949
            JValue::Object(vec![
950
                ("type".to_string(), JValue::String("header".to_string())),
951
                (
952
                    "name".to_string(),
953
                    JValue::String("Content-Length".to_string())
954
                ),
955
            ])
956
        );
957
    }
958

            
959
    #[test]
960
    pub fn test_capture() {
961
        assert_eq!(
962
            header_capture().to_json(),
963
            JValue::Object(vec![
964
                ("name".to_string(), JValue::String("size".to_string())),
965
                (
966
                    "query".to_string(),
967
                    JValue::Object(vec![
968
                        ("type".to_string(), JValue::String("header".to_string())),
969
                        (
970
                            "name".to_string(),
971
                            JValue::String("Content-Length".to_string())
972
                        ),
973
                    ])
974
                ),
975
            ])
976
        );
977
    }
978

            
979
    #[test]
980
    pub fn test_predicate() {
981
        assert_eq!(
982
            equal_int_predicate(10).to_json(),
983
            JValue::Object(vec![
984
                ("type".to_string(), JValue::String("==".to_string())),
985
                ("value".to_string(), JValue::Number("10".to_string()))
986
            ]),
987
        );
988
    }
989

            
990
    #[test]
991
    pub fn test_assert() {
992
        assert_eq!(
993
            header_assert().to_json(),
994
            JValue::Object(vec![
995
                (
996
                    "query".to_string(),
997
                    JValue::Object(vec![
998
                        ("type".to_string(), JValue::String("header".to_string())),
999
                        (
                            "name".to_string(),
                            JValue::String("Content-Length".to_string())
                        ),
                    ])
                ),
                (
                    "predicate".to_string(),
                    JValue::Object(vec![
                        ("type".to_string(), JValue::String("==".to_string())),
                        ("value".to_string(), JValue::Number("10".to_string()))
                    ])
                )
            ]),
        );
    }
}