Skip to main content

quickjs_jit_stdlib/llrt/llrt_json/
lib.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_json/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::cmp::min;
6
7use rquickjs::{
8    atom::PredefinedAtom, function::Opt, prelude::Func, Ctx, IntoJs, Object, Result, Value,
9};
10
11pub mod escape;
12pub mod parse;
13pub mod stringify;
14
15use crate::json::parse::json_parse_string;
16use crate::json::stringify::json_stringify_replacer_space;
17
18pub fn redefine_static_methods(ctx: &Ctx<'_>) -> Result<()> {
19    let globals = ctx.globals();
20    let json_module: Object = globals.get(PredefinedAtom::JSON)?;
21    json_module.set("parse", Func::from(json_parse_string))?;
22    json_module.set(
23        "stringify",
24        Func::from(|ctx, value, replacer, space| {
25            struct StringifyArgs<'js>(Ctx<'js>, Value<'js>, Opt<Value<'js>>, Opt<Value<'js>>);
26            let StringifyArgs(ctx, value, replacer, space) =
27                StringifyArgs(ctx, value, replacer, space);
28
29            let mut space_value = None;
30            let mut replacer_value = None;
31
32            if let Some(replacer) = replacer.0 {
33                if let Some(space) = space.0 {
34                    if let Some(space) = space.as_string() {
35                        let mut space = space.clone().to_string()?;
36                        space.truncate(20);
37                        space_value = Some(space);
38                    }
39                    if let Some(number) = space.as_int() {
40                        if number > 0 {
41                            space_value = Some(" ".repeat(min(10, number as usize)));
42                        }
43                    }
44                }
45                replacer_value = Some(replacer);
46            }
47
48            json_stringify_replacer_space(&ctx, value, replacer_value, space_value)
49                .map(|v| v.into_js(&ctx))?
50        }),
51    )?;
52    Ok(())
53}
54
55#[cfg(test)]
56mod tests {
57    use crate::test_support::test_sync_with;
58    use rquickjs::{prelude::Func, Array, CatchResultExt, IntoJs, Null, Object, Undefined, Value};
59
60    use crate::json::{
61        parse::{json_parse, json_parse_string},
62        stringify::{json_stringify, json_stringify_replacer_space},
63    };
64
65    static JSON: &str = r#"{"organization":{"name":"TechCorp","founding_year":2000,"departments":[{"name":"Engineering","head":{"name":"Alice Smith","title":"VP of Engineering","contact":{"email":"alice.smith@techcorp.com","phone":"+1 (555) 123-4567"}},"employees":[{"id":101,"name":"Bob Johnson","position":"Software Engineer","contact":{"email":"bob.johnson@techcorp.com","phone":"+1 (555) 234-5678"},"projects":[{"project_id":"P001","name":"Project A","status":"In Progress","description":"Developing a revolutionary software solution for clients.","start_date":"2023-01-15","end_date":null,"team":[{"id":201,"name":"Sara Davis","role":"UI/UX Designer"},{"id":202,"name":"Charlie Brown","role":"Quality Assurance Engineer"}]},{"project_id":"P002","name":"Project B","status":"Completed","description":"Upgrading existing systems to enhance performance.","start_date":"2022-05-01","end_date":"2022-11-30","team":[{"id":203,"name":"Emily White","role":"Systems Architect"},{"id":204,"name":"James Green","role":"Database Administrator"}]}]},{"id":102,"name":"Carol Williams","position":"Senior Software Engineer","contact":{"email":"carol.williams@techcorp.com","phone":"+1 (555) 345-6789"},"projects":[{"project_id":"P001","name":"Project A","status":"In Progress","description":"Working on the backend development of Project A.","start_date":"2023-01-15","end_date":null,"team":[{"id":205,"name":"Alex Turner","role":"DevOps Engineer"},{"id":206,"name":"Mia Garcia","role":"Software Developer"}]},{"project_id":"P003","name":"Project C","status":"Planning","description":"Researching and planning for a future project.","start_date":null,"end_date":null,"team":[]}]}]},{"name":"Marketing","head":{"name":"David Brown","title":"VP of Marketing","contact":{"email":"david.brown@techcorp.com","phone":"+1 (555) 456-7890"}},"employees":[{"id":201,"name":"Eva Miller","position":"Marketing Specialist","contact":{"email":"eva.miller@techcorp.com","phone":"+1 (555) 567-8901"},"campaigns":[{"campaign_id":"C001","name":"Product Launch","status":"Upcoming","description":"Planning for the launch of a new product line.","start_date":"2023-03-01","end_date":null,"team":[{"id":301,"name":"Oliver Martinez","role":"Graphic Designer"},{"id":302,"name":"Sophie Johnson","role":"Content Writer"}]},{"campaign_id":"C002","name":"Brand Awareness","status":"Ongoing","description":"Executing strategies to increase brand visibility.","start_date":"2022-11-15","end_date":"2023-01-31","team":[{"id":303,"name":"Liam Taylor","role":"Social Media Manager"},{"id":304,"name":"Ava Clark","role":"Marketing Analyst"}]}]}]}]}}"#;
66
67    #[tokio::test]
68    async fn json_parser() {
69        test_sync_with(|ctx| {
70            let json_data = [
71                r#"{"aa\"\"aaaaaaaaaaaaaaaa":"a","b":"bbb"}"#,
72                r#"{"a":"aaaaaaaaaaaaaaaaaa","b":"bbb"}"#,
73                r#"{"a":["a","a","aaaa","a"],"b":"b"}"#,
74                r#"{"type":"Buffer","data":[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]}"#,
75                r#"{"a":[{"object2":{"key1":"value1","key2":123,"key3":false,"nestedObject":{"nestedKey":"nestedValue"}},"string":"Hello, World!","emptyObj":{},"emptyArr":[],"number":42,"boolean":true,"nullValue":null,"array":[1,2,3,"four",5.5,true,null],"object":{"key1":"value1","key2":123,"key3":false,"nestedObject":{"nestedKey":"nestedValue"}}}]}"#,
76                JSON,
77            ];
78
79            for json_str in json_data {
80                let json = json_str.to_string();
81                let json2 = json.clone();
82
83                let value = json_parse(&ctx, json2)?;
84                let new_json = json_stringify_replacer_space(&ctx, value.clone(),None,Some("  ".into()))?.unwrap();
85                let builtin_json = ctx.json_stringify_replacer_space(value,Null,"  ".to_string())?.unwrap().to_string()?;
86                assert_eq!(new_json, builtin_json);
87            }
88
89            Ok(())
90        })
91        .await;
92    }
93
94    #[tokio::test]
95    async fn json_parse_non_string() {
96        test_sync_with(|ctx| {
97            ctx.globals().set("parse", Func::from(json_parse_string))?;
98
99            let result = ctx.eval::<(), _>("parse({})").catch(&ctx);
100
101            if let Err(err) = result {
102                assert_eq!(
103                   err.to_string(),
104                   "Error: \"[object Object]\" not valid JSON at index 1 ('o')\n    at <eval> (eval_script:1:1)\n"
105               );
106            } else {
107                panic!("expected error")
108            }
109
110            Ok(())
111        })
112        .await;
113    }
114
115    #[tokio::test]
116    async fn json_stringify_undefined() {
117        test_sync_with(|ctx| {
118            let stringified = json_stringify(&ctx, Undefined.into_js(&ctx)?)?;
119            let stringified_2 = ctx
120                .json_stringify(Undefined)?
121                .map(|v| v.to_string().unwrap());
122            assert_eq!(stringified, stringified_2);
123
124            let obj: Value = ctx.eval(
125                r#"let obj = { value: undefined, array: [undefined, null, 1, true, "hello", { [Symbol("sym")]: 1, [undefined]: 2}] };obj;"#,
126            )?;
127
128            let stringified = json_stringify(&ctx, obj.clone())?;
129            let stringified_2 = ctx
130                .json_stringify(obj)?
131                .map(|v| v.to_string().unwrap());
132            assert_eq!(stringified, stringified_2);
133
134            Ok(())
135        })
136        .await;
137    }
138
139    #[tokio::test]
140    async fn json_stringify_objects() {
141        test_sync_with(|ctx| {
142            let date: Value = ctx.eval("let obj = { date: new Date(0) };obj;")?;
143            let stringified = json_stringify(&ctx, date.clone())?.unwrap();
144            let stringified_2 = ctx.json_stringify(date)?.unwrap().to_string()?;
145            assert_eq!(stringified, stringified_2);
146            Ok(())
147        })
148        .await;
149    }
150
151    #[tokio::test]
152    async fn huge_numbers() {
153        test_sync_with(|ctx| {
154
155            let big_int_value = json_parse(&ctx, b"99999999999999999999999999999999999999999999999999999999999999999999999999999999999")?;
156
157            let stringified = json_stringify(&ctx, big_int_value.clone())?.unwrap();
158            let stringified_2 = ctx.json_stringify(big_int_value)?.unwrap().to_string()?.replace("e+", "e");
159            assert_eq!(stringified, stringified_2);
160
161            let big_int_value: Value = ctx.eval("999999999999")?;
162            let stringified = json_stringify(&ctx, big_int_value.clone())?.unwrap();
163            let stringified_2 = ctx.json_stringify(big_int_value)?.unwrap().to_string()?;
164            assert_eq!(stringified, stringified_2);
165
166            Ok(())
167        })
168        .await;
169    }
170
171    #[tokio::test]
172    async fn json_circular_ref() {
173        test_sync_with(|ctx| {
174            let obj1 = Object::new(ctx.clone())?;
175            let obj2 = Object::new(ctx.clone())?;
176            let obj3 = Object::new(ctx.clone())?;
177            let obj4 = Object::new(ctx.clone())?;
178            obj4.set("key", "value")?;
179            obj3.set("sub2", obj4.clone())?;
180            obj2.set("sub1", obj3)?;
181            obj1.set("root1", obj2.clone())?;
182            obj1.set("root2", obj2.clone())?;
183            obj1.set("root3", obj2.clone())?;
184
185            let value = obj1.clone().into_value();
186
187            let stringified = json_stringify(&ctx, value.clone())?.unwrap();
188            let stringified_2 = ctx.json_stringify(value.clone())?.unwrap().to_string()?;
189            assert_eq!(stringified, stringified_2);
190
191            obj4.set("recursive", obj1.clone())?;
192
193            let stringified = json_stringify(&ctx, value.clone());
194
195            if let Err(error_message) = stringified.catch(&ctx) {
196                let error_str = error_message.to_string();
197                assert_eq!(
198                    "Error: Circular reference detected at: \"...root1.sub1.sub2.recursive\"\n",
199                    error_str
200                )
201            } else {
202                panic!("Expected an error, but got Ok");
203            }
204
205            let array1 = Array::new(ctx.clone())?;
206            let array2 = Array::new(ctx.clone())?;
207            let array3 = Array::new(ctx.clone())?;
208
209            let obj5 = Object::new(ctx.clone())?;
210            obj5.set("key", obj1.clone())?;
211            array3.set(2, obj5)?;
212            array2.set(1, array3)?;
213            array1.set(0, array2)?;
214
215            obj4.remove("recursive")?;
216            obj1.set("recursiveArray", array1)?;
217
218            let stringified = json_stringify(&ctx, value.clone());
219
220            if let Err(error_message) = stringified.catch(&ctx) {
221                let error_str = error_message.to_string();
222                assert_eq!(
223                    "Error: Circular reference detected at: \"...recursiveArray[0][1][2].key\"\n",
224                    error_str
225                )
226            } else {
227                panic!("Expected an error, but got Ok");
228            }
229
230            Ok(())
231        })
232        .await;
233    }
234}