Debian Codegraph @

packages/babel-parser/test/helpers/serialization.js

raw
1 const { parse: JSONParse, stringify } = JSON;
2
3 // We give JSON files that needed our special serialization the extension
4 // ".extended.json" instead of just ".json" so that we can only use our
5 // deserialization function in those cases (which is slower), and in all
6 // other instances just rely on normal JSON.parse with no deserialization
7 // function.
8 const isExtended = filename => /\.extended\.json$/.test(filename);
9
10 // We've only serialized one BigInt in the entire test suite:
11 //
12 // packages/babel-parser/test/fixtures/estree/bigInt/basic/output.extended.json
13 //
14 // This is because only estree actually includes the BigInt value in the Literal
15 // node. If the JS environment doesn't support bigint, then estree will just
16 // use null for the value. We also happen to just throw the AST information away
17 // with estree tests, so in the event that we're running on an older version of
18 // Node that doesn't support bigint, it is safe to deserialize to null.
19 const toBigInt = global.BigInt || (() => null);
20
21 const SerializationKey = "$$ babel internal serialized type";
22
23 /* eslint-disable no-confusing-arrow */
24 export const deserialize = (filename, options, string) =>
25 withErrors(
26 options.throws,
27 !!string &&
28 JSONParse(
29 string,
30 isExtended(filename) &&
31 ((key, value) =>
32 key !== "value" ||
33 !value ||
34 typeof value !== "object" ||
35 !value[SerializationKey]
36 ? value
37 : value[SerializationKey] === "RegExp"
38 ? new RegExp(value.source, value.flags)
39 : toBigInt(value.value)),
40 ),
41 );
42
43 // For now we assemble this structure here, but in the future we should just
44 // store the entire thing into output.json, instead of thrown errors in
45 // options.json. If we end up going with
46 // https://github.com/babel/babel/issues/14175, then as a side-effect we'll
47 // actually get this behavior for free, since everything will always just be
48 // store in the errors array.
49 function withErrors(throws, ast) {
50 const threw = !!throws && toError(throws);
51 const errors = !!ast && !!ast.errors && ast.errors.map(toError);
52
53 return { threw, ast: errors ? { ...ast, errors } : ast };
54 }
55
56 // This is more complicated than it needs to be because for unfortunately thrown
57 // errors and recovered errors are serialized slightly differently. Thrown
58 // errors are serialized *without* their corresponding class name (the result of
59 // calling .toString() on the error), while errors in the errors array of the
60 // AST are serialized *with* the class name (the result of just storing the
61 // contents of the message). As such, the type information is lost for thrown
62 // errors, but it just happens to be that they're all SyntaxErrors.
63 //
64 // Because of this, we have to account for both cases here, so if the name is
65 // present, we use it, otherwise, we just assume it's a SyntaxError. In the
66 // future, we should serialize the errors into an object representation instead
67 // of just a string, which we can use to additionally store the location info so
68 // we can test that too.
69 const ErrorPrefixRegExp = /^[A-Za-z]*Error:\s/;
70 const toError = message =>
71 /^Error/.test(message.replace(ErrorPrefixRegExp, ""))
72 ? Error(message.replace(ErrorPrefixRegExp, ""))
73 : SyntaxError(message.replace(ErrorPrefixRegExp, ""));
74
75 const LocRegExp = /"loc":(\s*\{(?:[^}{]+|\{(?:[^}{]+|\([^}{]*\})*\})*\})/gm;
76 const StartEndRegExp = /("(start|end)":\s*(\d+),\s*){2}/gm;
77 const CompactRegExp = new RegExp(
78 `${StartEndRegExp.source}${LocRegExp.source}`,
79 "gm",
80 );
81
82 export function serialize(value) {
83 let extended = false;
84 const toExended = (name, data) => (
85 (extended = true), { [SerializationKey]: name, ...data }
86 );
87 const encode = (key, value) =>
88 typeof value === "bigint"
89 ? toExended("bigint", { value: value + "" })
90 : value instanceof RegExp
91 ? toExended("RegExp", { source: value.source, flags: value.flags })
92 : value instanceof Error
93 ? value + ""
94 : value;
95 const serialized = stringify(value, encode, 2).replace(
96 CompactRegExp,
97 // This is safe since none of the values can have spaces in them.
98 string => string.replace(/\s+/gm, () => ""),
99 );
100
101 return [extended, serialized];
102 }