Giter Club home page Giter Club logo

seroval's Introduction

seroval

Stringify JS values

NPM JavaScript Style Guide

Install

npm install --save seroval
yarn add seroval
pnpm add seroval

Usage

import { serialize } from 'seroval';

const object = {
  number: [Math.random(), -0, NaN, Infinity, -Infinity],
  string: ['hello world', '<script>Hello World</script>'],
  boolean: [true, false],
  null: null,
  undefined: undefined,
  bigint: 9007199254740991n,
  array: [,,,], // holes
  regexp: /[a-z0-9]+/i,
  date: new Date(),
  map: new Map([['hello', 'world']]),
  set: new Set(['hello', 'world']),
};

// self cyclic references
// recursive objects
object.self = object;
// recursive arrays
object.array.push(object.array);
// recursive maps
object.map.set('self', object.map);
// recursive sets
object.set.add(object.set);

// mutual cyclic references
object.array.push(object.map);
object.map.set('mutual', object.set);
object.set.add(object.array);

const result = serialize(object);
console.log(result);

Output (as a string):

((h,j,k,m,o)=>(o={number:[0.5337763749243287,-0,0/0,1/0,-1/0],string:["hello world","\x3Cscript>Hello World\x3C/script>"],boolean:[!0,!1],null:null,undefined:void 0,bigint:9007199254740991n,array:h=[,,,,k=(j=[],new Map([["hello","world"],["mutual",m=new Set(["hello","world"])]]))],regexp:/[a-z0-9]+/i,date:new Date("2023-12-07T17:28:57.909Z"),map:k,set:m},h[3]=h,k.set("self",k),m.add(m).add(h),o.self=o,o))()

// Formatted for readability
((h, j, k, m, o) => (
  (o = {
    number: [0.5337763749243287, -0, 0 / 0, 1 / 0, -1 / 0],
    string: ["hello world", "\x3Cscript>Hello World\x3C/script>"],
    boolean: [!0, !1],
    null: null,
    undefined: void 0,
    bigint: 9007199254740991n,
    array: (h = [
      ,
      ,
      ,
      ,
      (k =
        ((j = []),
        new Map([
          ["hello", "world"],
          ["mutual", (m = new Set(["hello", "world"]))],
        ]))),
    ]),
    regexp: /[a-z0-9]+/i,
    date: new Date("2023-12-07T17:28:57.909Z"),
    map: k,
    set: m,
  }),
  (h[3] = h),
  k.set("self", k),
  m.add(m).add(h),
  (o.self = o),
  o
))();

Docs

Sponsors

Sponsors

License

MIT © lxsmnsyc

seroval's People

Contributors

lxsmnsyc avatar samualtnorman avatar

Stargazers

Ryan Nieuwoudt avatar John Leung avatar Ivan Čurić avatar Lubomir Anastasov avatar Nyi Nyi Lwin avatar Dev Agrawal avatar Parkin Lin avatar Liu Yu avatar Heber Nobre avatar deminearchiver avatar Özgür avatar OliverGrack avatar 0x00646f616e6e63 avatar Siddharth avatar Brian McKelvey avatar Jakob Gaiswinkler avatar Hampus Hallman avatar oussama djaidri avatar  avatar Tiffiny Jenis avatar Peter Correa avatar 闻人若川 avatar Yota Toyama avatar Tsotne Nazarashvili avatar Matias Korhonen avatar Vesa Vänskä avatar Henrique Mitsuo avatar Ahmad Fauzy avatar Emin Gasimov avatar Matvey avatar Alexey Volkov avatar pnly avatar Brian Kim avatar  avatar parthbera avatar David Myers avatar Mark avatar 朱展东 avatar longlong avatar Santiago Montoya A. avatar Nate Buckareff avatar Khaled avatar Kevin Abatan avatar Pat Murray avatar Shingo Chijiiwa avatar Quentin Jaccarino avatar Evgeny avatar Denis Strelkov avatar Drew Powers avatar David Sancho avatar Ekin Koc avatar Jacob Groß avatar Alexandre Papin avatar Han Chen avatar Sagar Poudel avatar Michael Cox avatar Germano avatar Earl Celis avatar  avatar Florian Lefebvre avatar Julian Cataldo avatar Albert 理斯特 avatar Oscar Beaumont avatar Yoav Balasiano avatar Hamzat Victor Oluwabori avatar GongYI avatar  avatar Jake Champion avatar Andy Ingram avatar Conor Sinclair avatar Daniel Hayes avatar  avatar flow avatar Alejandro avatar Kacper Wojciechowski avatar Tugy avatar Donatas avatar Ayan Yenbekbay avatar Josh Wilson avatar Birk Skyum avatar xuke avatar paulost avatar Felix avatar Gabriel Castillo avatar Marc MacLeod avatar  avatar Heartlander avatar  avatar Marcus Webb avatar  avatar Joshua Amaju avatar 王洪莹 avatar Sergey avatar CallMeLaNN avatar Daniele Orlando avatar Githin George avatar  avatar Kyle Chamberlain avatar Diego Reis Carvalho avatar Luciano Mammino avatar

Watchers

Rafael Masson avatar Denis Pushkarev avatar  avatar  avatar  avatar

seroval's Issues

serialise date to number instead of string

surely it's better to serialise a date to the format new Date(1682085024851) instead of new Date("2023-04-21T13:50:24.851Z")?

the number is smaller and the string needs parsing.

I might be wrong though and there's something I'm missing. I'm curious if that's the case.

Thanks.

Combined types

Objects that are iterable, Promise-like, null constructor and Object constructor are currently exclusive from one another. Maybe there's a way to serialize them in a way that the entire behavior is combined.

Edge Case: Mistake on isolating Map entries

const a = {
  d: {},
  map: new Map,
  b: {
    c: {
      foo: 'bar'
    }
  }
};

a.map.set(a, a.b.c);

a.b.c.parent = a.b;
a.b.c.d = a.d;

This causes a.b.c to be undefined because the origin reference, located at a.map, is deferred due to recursion.

serialize 0x prefix string object key as number

Encountered this while using SolidStart.

When object string key contains 0x prefix it gets serialised as hex number.

For context, address identifiers in crypto such as Ethereum are commonly hex addresses.

import { deserialize, serialize } from "seroval"

const original = {
  "0x1": 2
}

const output = serialize(original)
console.log("output", output)
// output ({0x1:2})

const result = deserialize(output)
console.log("deserialize", result)
// deserialize { '1': 2 }

Feature: JSON string serializer

Add toJSONString and fromJSONString to skip the use of JSON.stringify and JSON.parse in userland (also because JSON.stringify has some bottleneck)

Better serialization for `Blob` and `File`

Currently Blob and File relies on ArrayBuffer serialization, which means it uses the Uint8Array indirectly. This serialization form is accurate, but is probably too large for consideration. Blob accepts Uint8Array, ArrayBuffer, DataView and string, so it's probably ideal if the string format can be utilized instead.

Inside of getCrossReferenceHeader script, getting error Uncaught SyntaxError: Unexpected identifier '_$HY'

I am trying Solid-js 1.8.3 and renderToStringAsync, and I got a hydration script injected with an error like below:

                               | Uncaught SyntaxError: Unexpected identifier '_$HY'
                               V
(self.$R=self.$R||{})["s2-"]=[]_$HY.r["s2-0-0-0-0-0-0"]=($R=>($R[0]=_$.P()))($R["s2-"]);($R=>(_$.Ps($R[0],!0)))($R["s2-"]);

After I added the semicolon here, the hydration script could be parsed by the browser:

(self.$R = self.$R || {})["s2-"] = [];
_$HY.r["s2-0-0-0-0-0-0"] = (($R) => ($R[0] = _$.P()))($R["s2-"]);
(($R) => _$.Ps($R[0], !0))($R["s2-"]);

Maybe there is a missing semicolon here? I noticed that the id == null has a semicolon included but the id != null case does not have a semicolon at the end.

export function getCrossReferenceHeader(id?: string): string {
  if (id == null) {
    return `self.${GLOBAL_CONTEXT_REFERENCES}=self.${GLOBAL_CONTEXT_REFERENCES}||[];`;
  }
- return `(self.${GLOBAL_CONTEXT_REFERENCES}=self.${GLOBAL_CONTEXT_REFERENCES}||{})["${serializeString(id)}"]=[]`;
+ return `(self.${GLOBAL_CONTEXT_REFERENCES}=self.${GLOBAL_CONTEXT_REFERENCES}||{})["${serializeString(id)}"]=[];`;
}

Allow opting out of serialization

If possible, it'll be pretty convenient to mark some value to be not serialized. Imagine this arbitrary API:

import { serialize, NoSerialization } from "seroval";

console.log(serialize({
  title: "My Article",
  load: new NoSerialization(() => import("./my-article.mdx")),
})) // { title: "My Article" }

In this case, without NoSerialization, the load property should've filtered first not to make any serialization error, since anonymous functions are not serializable. However, because it's marked as NoSerialization, Seroval can just skip the serialization and remove the property.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.