Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions packages/codegen/src/serialize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { serializePropValue } from "./serialize";

describe("serializePropValue", () => {
it("quotes non-identifier object keys", () => {
expect(serializePropValue({ "data-testid": "widget" })).toEqual({
value: '{ "data-testid": "widget" }',
needsBraces: true,
});
});

it("keeps simple identifier keys readable", () => {
expect(serializePropValue({ name: "widget" })).toEqual({
value: '{ name: "widget" }',
needsBraces: true,
});
});

it("preserves an own __proto__ property", () => {
const value = JSON.parse('{"__proto__":"data"}');

expect(serializePropValue(value)).toEqual({
value: '{ ["__proto__"]: "data" }',
needsBraces: true,
});
});
});
11 changes: 9 additions & 2 deletions packages/codegen/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,15 @@ export function serializePropValue(
.filter(([, v]) => v !== undefined)
.map(([k, v]) => {
const serialized = serializePropValue(v, opts).value;
// Use shorthand if key matches value for simple identifiers
return `${k}: ${serialized}`;
const quotedKey = JSON.stringify(k) ?? '""';
// A quoted __proto__ key still has special object-literal semantics.
const propertyKey =
k === "__proto__"
? `[${quotedKey}]`
: /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k)
? k
: quotedKey;
return `${propertyKey}: ${serialized}`;
});

return { value: `{ ${entries.join(", ")} }`, needsBraces: true };
Expand Down