Skip to content

Commit

Permalink
fix: improve edge cases of literalToAst
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 15, 2023
1 parent effae7c commit f9b6296
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/proxy/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,22 @@ export function proxify<T>(node: ESNode): Proxified<T> {
const PROXY_KEY = "__magicast_proxy";

export function literalToAst(value: any): ESNode {
if (value[PROXY_KEY]) {
return value.$ast;
if (value === undefined) {
return recast.types.builders.identifier("undefined") as any;
}
if (value === null) {
// eslint-disable-next-line unicorn/no-null
return recast.types.builders.literal(null) as any;
}
if (Array.isArray(value)) {
return recast.types.builders.arrayExpression(
value.map((n) => literalToAst(n)) as any
) as any;
}
if (typeof value === "object") {
if (PROXY_KEY in value) {
return value.$ast;
}
return recast.types.builders.objectExpression(
Object.entries(value).map(([key, value]) => {
return recast.types.builders.property(
Expand Down
23 changes: 23 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, it, expect } from "vitest";
import { print } from "recast";
import { literalToAst } from "../src/proxy/_utils";

describe('literalToAst', () => {
// eslint-disable-next-line unicorn/consistent-function-scoping
function run(value: any) {
return print(literalToAst(value)).code;
}

it('should work', () => {
expect(run(1)).toMatchInlineSnapshot('"1"')
expect(run(true)).toMatchInlineSnapshot('"true"')
expect(run(undefined)).toMatchInlineSnapshot('"undefined"')
// eslint-disable-next-line unicorn/no-null
expect(run(null)).toMatchInlineSnapshot('"null"')
expect(run([undefined, 1, { foo:'bar' }])).toMatchInlineSnapshot(`
"[undefined, 1, {
foo: \\"bar\\"
}]"
`)
})
})

0 comments on commit f9b6296

Please sign in to comment.