MCPcopy
hub / github.com/flightcontrolhq/superjson

github.com/flightcontrolhq/superjson @v2.2.5 sqlite

repository ↗ · DeepWiki ↗ · release v2.2.5 ↗
121 symbols 276 edges 22 files 1 documented · 1%
README

superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.

All Contributors

npm Language grade: JavaScript

CI

Key features

  • 🍱 Reliable serialization and deserialization
  • 🔐 Type safety with autocompletion
  • 🐾 Negligible runtime footprint
  • 💫 Framework agnostic
  • 🛠 Perfect fix for Next.js's serialisation limitations in getServerSideProps and getInitialProps

Backstory

At Blitz, we have struggled with the limitations of JSON. We often find ourselves working with Date, Map, Set or BigInt, but JSON.stringify doesn't support any of them without going through the hassle of converting manually!

Superjson solves these issues by providing a thin wrapper over JSON.stringify and JSON.parse.

Sponsors

Flightcontrol Logo

Superjson logo by NUMI:

NUMI Logo

Getting started

Install the library with your package manager of choice, e.g.:

yarn add superjson

Basic Usage

The easiest way to use Superjson is with its stringify and parse functions. If you know how to use JSON.stringify, you already know Superjson!

Easily stringify any expression you’d like:

import superjson from 'superjson';

const jsonString = superjson.stringify({ date: new Date(0) });

// jsonString === '{"json":{"date":"1970-01-01T00:00:00.000Z"},"meta":{"values":{date:"Date"}}}'

And parse your JSON like so:

const object = superjson.parse<
{ date: Date }
>(jsonString);

// object === { date: new Date(0) }

Advanced Usage

For cases where you want lower level access to the json and meta data in the output, you can use the serialize and deserialize functions.

One great use case for this is where you have an API that you want to be JSON compatible for all clients, but you still also want to transmit the meta data so clients can use superjson to fully deserialize it.

For example:

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const { json, meta } = superjson.serialize(object);

/*
json = {
  normal: 'string',
  timestamp: "2020-06-20T04:56:50.293Z",
  test: "/superjson/",
};

// note that `normal` is not included here; `meta` only has special cases
meta = {
  values: {
    timestamp: ['Date'],
    test: ['regexp'],
  }
};
*/

Using with Next.js

The getServerSideProps, getInitialProps, and getStaticProps data hooks provided by Next.js do not allow you to transmit Javascript objects like Dates. It will error unless you convert Dates to strings, etc.

Thankfully, Superjson is a perfect tool to bypass that limitation!

Next.js SWC Plugin (experimental, v13 or above)

Next.js SWC plugins are experimental, but promise a significant speedup. To use the SuperJSON SWC plugin, install it and add it to your next.config.js:

yarn add next-superjson-plugin
// next.config.js
module.exports = {
  experimental: {
    swcPlugins: [
      [
        'next-superjson-plugin',
        {
          excluded: [],
        },
      ],
    ],
  },
};

Next.js (stable Babel transform)

Install the library with your package manager of choice, e.g.:

yarn add babel-plugin-superjson-next

Add the plugin to your .babelrc. If you don't have one, create it.

{
  "presets": ["next/babel"],
  "plugins": [
    ...
    "superjson-next" // 👈
  ]
}

Done! Now you can safely use all JS datatypes in your getServerSideProps / etc. .

API

serialize

Serializes any JavaScript value into a JSON-compatible object.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const { json, meta } = serialize(object);

Returns json and meta, both JSON-compatible values.

deserialize

Deserializes the output of Superjson back into your original value.

Examples

const { json, meta } = serialize(object);

deserialize({ json, meta }, { inPlace: true });

Options

  • inPlace: boolean
  • Default: false
  • Mutate the input json object in place instead of returning a deep copy
  • inPlace: true will be much more performant on large objects if it's safe to mutate it

Returns your original value.

stringify

Serializes and then stringifies your JavaScript value.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const jsonString = stringify(object);

Returns string.

parse

Parses and then deserializes the JSON string returned by stringify.

Examples

const jsonString = stringify(object);

parse(jsonString);

Returns your original value.


Superjson supports many extra types which JSON does not. You can serialize all these:

type supported by standard JSON? supported by Superjson?
string
number
boolean
null
Array
Object
undefined
bigint
Date
RegExp
Set
Map
Error
URL

Recipes

SuperJSON by default only supports built-in data types to keep bundle-size as low as possible. Here are some recipes you can use to extend to non-default data types.

Place them in some central utility file and make sure they're executed before any other SuperJSON calls. In a Next.js project, _app.ts would be a good spot for that.

Decimal.js / Prisma.Decimal

import { Decimal } from 'decimal.js';

SuperJSON.registerCustom<Decimal, string>(
  {
    isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
    serialize: v => v.toJSON(),
    deserialize: v => new Decimal(v),
  },
  'decimal.js'
);

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Dylan Brookes Dylan Brookes 💻 📖 🎨 ⚠️ Simon Knott Simon Knott 💻 🤔 ⚠️ 📖 Brandon Bayer Brandon Bayer 🤔 Jeremy Liberman Jeremy Liberman ⚠️ 💻 Joris Joris 💻 tomhooijenga tomhooijenga 💻 🐛 Ademílson F. Tonato Ademílson F. Tonato ⚠️
Piotr Monwid-Olechnowicz Piotr Monwid-Olechnowicz 🤔 Alex Johansson Alex Johansson 💻 ⚠️ Simon Edelmann Simon Edelmann 🐛 💻 🤔 Sam Garson Sam Garson 🐛 Mark Hughes Mark Hughes 🐛 Lxxyx Lxxyx 💻 Máximo Mussini Máximo Mussini 💻

Extension points exported contracts — how you extend this code

RegisterOptions (Interface)
(no doc)
src/class-registry.ts
Result (Interface)
(no doc)
src/plainer.ts
CustomTransfomer (Interface)
(no doc)
src/custom-transformer-registry.ts
JSONArray (Interface)
(no doc)
src/types.ts
JSONObject (Interface)
(no doc)
src/types.ts
SuperJSONArray (Interface)
(no doc)
src/types.ts
SuperJSONObject (Interface)
(no doc)
src/types.ts
SuperJSONResult (Interface)
(no doc)
src/types.ts

Core symbols most depended-on inside this repo

serialize
called by 21
src/index.ts
deserialize
called by 20
src/index.ts
isPrimitive
called by 18
src/is.ts
stringify
called by 14
src/index.ts
parse
called by 14
src/index.ts
isPlainObject
called by 13
src/is.ts
isArray
called by 12
src/is.ts
simpleTransformation
called by 10
src/transformer.ts

Shape

Function 52
Method 35
Class 26
Interface 8

Languages

TypeScript100%

Modules by API surface

src/index.test.ts22 symbols
src/is.ts21 symbols
src/index.ts11 symbols
src/plainer.ts10 symbols
src/registry.ts7 symbols
src/double-indexed-kv.ts6 symbols
src/custom-transformer-registry.ts6 symbols
src/class-registry.ts6 symbols
src/util.ts5 symbols
src/types.ts5 symbols
src/transformer.ts5 symbols
src/transformer.test.ts4 symbols

Dependencies from manifests, versioned

@types/debug4.1.5 · 1×
@types/mongodb3.6.12 · 1×
@types/node18.7.18 · 1×
benchmark2.1.4 · 1×
copy-anything4 · 1×
decimal.js10.3.1 · 1×
eslint-plugin-es51.5.0 · 1×
husky6.0.0 · 1×
mongodb3.6.6 · 1×
publish-please5.5.2 · 1×
tsdx0.14.1 · 1×
typescript4.2.4 · 1×

For agents

$ claude mcp add superjson \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact