flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.13k stars 91 forks source link

URL support? #200

Closed narumincho closed 2 years ago

narumincho commented 2 years ago
import superjson from "superjson";

const str = superjson.stringify({
  name: "John",
  age: 30n,
  avatar: new URL("https://picsum.photos/200"),
});
/*
 * v1.9.1:   {"json":{"name":"John","age":"30","avatar":"https://picsum.photos/200"},"meta":{"values":{"age":["bigint"]}}
 * expected: {"json":{"name":"John","age":"30","avatar":"https://picsum.photos/200"},"meta":{"values":{"age":["bigint"],"avatar":["url"]}}}
 */
console.log(str);

const parsed = superjson.parse(str);
/*
 * v1.9.1 : { name: 'John', age: 30n, avatar: 'https://picsum.photos/200' }
 * expected:
 * {
 *   name: 'John',
 *   age: 30n,
 *   avatar: URL {
 *     href: 'https://picsum.photos/200',
 *     origin: 'https://picsum.photos',
 *     protocol: 'https:',
 *     username: '',
 *     password: '',
 *     host: 'picsum.photos',
 *     hostname: 'picsum.photos',
 *     port: '',
 *     pathname: '/200',
 *     search: '',
 *     searchParams: URLSearchParams {},
 *     hash: ''
 *   }
 * }
 * ```
 */
console.log(parsed);

I think it is good to express URLs as URL types to make it clear that the API handles valid URLs.

Skn0tt commented 2 years ago

Oh absolutely, love that idea now that URL is a (somewhat) standard type! Would you be interested in contributing the code for that? I think adding another simpleTransformation like this and then some tests in index.test.ts should do the trick.

(excuse the late reply, was on PTO)

narumincho commented 2 years ago

I'll try