Socket
Socket
Sign inDemoInstall

typeson

Package Overview
Dependencies
Maintainers
1
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typeson - npm Package Compare versions

Comparing version 3.0.0 to 3.0.1

2

dist/typeson.js

@@ -1,1 +0,1 @@

!function(r,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Typeson=t():r.Typeson=t()}(this,function(){return function(r){function t(n){if(e[n])return e[n].exports;var i=e[n]={exports:{},id:n,loaded:!1};return r[n].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var e={};return t.m=r,t.c=e,t.p="",t(0)}([function(r,t){function e(r){var t=[],e={},u=this.types={};this.stringify=function(r,t,e){return JSON.stringify(c(r),t,e)},this.parse=function(r,t){return f(JSON.parse(r,t))};var c=this.encapsulate=function(n){function o(r,t,e){var n=typeof t;if(n in{string:1,"boolean":1,number:1,undefined:1})return"number"===n&&(isNaN(t)||t===-(1/0)||t===1/0)?u(r,t):t;if(null==t)return t;if(e){var a=f.indexOf(t);if(!(0>a))return c[r]="#","#"+s[a];f.push(t),s.push(r)}var p=t.constructor===Object?t:u(r,t);if(p!==t)return p;if(null==t)return t;var v;if(t.constructor===Object)v={};else{if(t.constructor!==Array)return t;v=new Array(t.length)}return i(t).forEach(function(n){var i=o(r+(r?".":"")+n,t[n],e);void 0!==i&&(v[n]=i)}),v}function u(r,n){for(var i=t.length;i--;)if(t[i].test(n)){var u=t[i].type;if(e[u]){var f=c[r];c[r]=f?[u].concat(f):u}return o(r,t[i].replace(n),!1)}return n}var c={},f=[],s=[],a=o("",n,r&&"cyclic"in r?r.cyclic:!0);if(i(c).length){if(a.constructor!==Object||a.$types)return{$:a,$types:{$:c}};a.$types=c}return a},f=this.revive=function(r){function t(r,f,s){if(!c||"$types"!==r){var a=u[r];if(f&&(f.constructor===Object||f.constructor===Array)){var p=o(f)?new Array(f.length):{};i(f).forEach(function(e){var n=t(r+(r?".":"")+e,f[e],s||p);void 0!==n&&(p[e]=n)}),f=p}return a?"#"===a?n(s,f.substr(1)):[].concat(a).reduce(function(r,t){var n=e[t];if(!n)throw new Error("Unregistered type: "+t);return n(r)},f):f}}var u=r.$types,c=!0;return u?(u.$&&u.$.constructor===Object&&(r=r.$,u=u.$,c=!1),t("",r)):r};this.register=function(r){return[].concat(r).forEach(function n(r){return o(r)?r.map(n):void(r&&i(r).forEach(function(n){var i=r[n],o=t.filter(function(r){return r.type===n});o.length&&(t.splice(t.indexOf(o[0]),1),delete e[n],delete u[n]),i&&(t.push({type:n,test:i[0],replace:i[1]}),i[2]&&(e[n]=i[2]),u[n]=i)}))}),this}}function n(r,t){if(""===t)return r;var e=t.indexOf(".");if(-1!==e){var i=r[t.substr(0,e)];return void 0===i?void 0:n(i,t.substr(e+1))}return r[t]}var i=Object.keys,o=Array.isArray;r.exports=e}])});
!function(r,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Typeson=t():r.Typeson=t()}(this,function(){return function(r){function t(n){if(e[n])return e[n].exports;var o=e[n]={exports:{},id:n,loaded:!1};return r[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var e={};return t.m=r,t.c=e,t.p="",t(0)}([function(r,t){function e(r){var t=[],e={},u=this.types={};this.stringify=function(r,t,e){return JSON.stringify(c(r),t,e)},this.parse=function(r,t){return f(JSON.parse(r,t))};var c=this.encapsulate=function(n){function i(r,t,e){var n=typeof t;if(n in{string:1,"boolean":1,number:1,undefined:1})return"number"===n&&(isNaN(t)||t===-(1/0)||t===1/0)?u(r,t):t;if(null==t)return t;if(e){var a=f.indexOf(t);if(!(0>a))return c[r]="#","#"+s[a];e===!0&&(f.push(t),s.push(r))}var p=t.constructor===Object?t:u(r,t);if(p!==t)return p;if(null==t)return t;var v;if(t.constructor===Object)v={};else{if(t.constructor!==Array)return t;v=new Array(t.length)}return o(t).forEach(function(n){var o=i(r+(r?".":"")+n,t[n],e);void 0!==o&&(v[n]=o)}),v}function u(r,n){for(var o=t.length;o--;)if(t[o].test(n)){var u=t[o].type;if(e[u]){var f=c[r];c[r]=f?[u].concat(f):u}return i(r,t[o].replace(n),"readonly")}return n}var c={},f=[],s=[],a=i("",n,r&&"cyclic"in r?r.cyclic:!0);if(o(c).length){if(a.constructor!==Object||a.$types)return{$:a,$types:{$:c}};a.$types=c}return a},f=this.revive=function(r){function t(r,f,s){if(!c||"$types"!==r){var a=u[r];if(f&&(f.constructor===Object||f.constructor===Array)){var p=i(f)?new Array(f.length):{};o(f).forEach(function(e){var n=t(r+(r?".":"")+e,f[e],s||p);void 0!==n&&(p[e]=n)}),f=p}return a?"#"===a?n(s,f.substr(1)):[].concat(a).reduce(function(r,t){var n=e[t];if(!n)throw new Error("Unregistered type: "+t);return n(r)},f):f}}var u=r.$types,c=!0;return u?(u.$&&u.$.constructor===Object&&(r=r.$,u=u.$,c=!1),t("",r)):r};this.register=function(r){return[].concat(r).forEach(function n(r){return i(r)?r.map(n):void(r&&o(r).forEach(function(n){var o=r[n],i=t.filter(function(r){return r.type===n});i.length&&(t.splice(t.indexOf(i[0]),1),delete e[n],delete u[n]),o&&(t.push({type:n,test:o[0],replace:o[1]}),o[2]&&(e[n]=o[2]),u[n]=o)}))}),this}}function n(r,t){if(""===t)return r;var e=t.indexOf(".");if(-1!==e){var o=r[t.substr(0,e)];return void 0===o?void 0:n(o,t.substr(e+1))}return r[t]}var o=Object.keys,i=Array.isArray;r.exports=e}])});
{
"name": "typeson",
"version": "3.0.0",
"version": "3.0.1",
"description": "Preserves types over JSON, BSON or socket.io",

@@ -27,6 +27,7 @@ "main": "typeson.js",

"devDependencies": {
"base64-arraybuffer": "^0.1.5",
"uglify-js": "^2.6.2",
"webpack": "^1.13.1"
},
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson()\n .register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: /bar/gi});"
"tonicExample": "var Typeson = require('typeson');\nvar TSON = new Typeson().register(require('typeson-registry/presets/builtin'));\n\nTSON.stringify({foo: new Date()});"
}
# typeson.js
Preserves types over JSON, BSON or socket.io
Preserves types over JSON, BSON or socket.io.
*Only 3.4kb minified. ~1k when gzipped.*
{
**Only 1.1 kb minified and gzipped!** *plus ~100 bytes per supported type*
```js
{foo: 1} // {"foo":1}
{foo: "bar"} // {"foo":"bar"}
{foo: "bar"} // {"foo":"bar"} (simple types gives plain JSON)
{foo: new Date()} // {"foo":1464049031538, "$types":{"foo":"Date"}}

@@ -13,3 +12,3 @@ {foo: new Set([new Date()])} // {"foo":[1464127925971], "$types":{"foo":"Set","foo.0":"Date"}}

{foo: new Int8Array(3)} // {"foo":"AAAA", "$types":{"foo":"Int8Array"}}
new Date() // {"$":1464128478593, "$types":{"$":{"":"Date"}}}
new Date() // {"$":1464128478593, "$types":{"$":{"":"Date"}}} (special format at root)
```

@@ -31,5 +30,6 @@ NOTE: Typeson by itself wont support these types. Register the types you need:

```
If you really need to support all built-in types, the module `typeson-registry/presets/builtin` is still **just 1.6 kb minizied and gzipped** and adds support 32 builtin javascript types: *Date, RegExp, NaN, Infinity, -Infinity, Set, Map, ArrayBuffer, DataView, Uint8Array, Int8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, Error, SyntaxError, TypeError, RangeError, ReferenceError, EvalError, URIError, InternalError, Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat, Object String, Object Number and Object Boolean*.
# Why?
JSON can only contain simple types: strings, numbers, booleans, arrays and objects. This module makes it possible to serialize any type over JSON or other media, such as Date, Error, ArrayBuffer, etc. Typeson is just JSON that complements non-trivial properties with types. It adds a metadata property "$types" to the result that maps each non-trivial property to a type name. The type name is a reference to a registered type specification that you need to have the same on both the stringifying and the parsing side.
JSON can only contain strings, numbers, booleans, arrays and objects. If you want to serialize other types over HTTP, WebSocket, postMessage() or other channel, this module makes it possible to serialize any type over channels that normally only accepts vanilla objects. Typeson adds a metadata property "$types" to the result that maps each non-trivial property to a type name. The type name is a reference to a registered type specification that you need to have the same on both the stringifying and the parsing side.

@@ -41,9 +41,7 @@ # Type Registry

* Node
* Browser(*)
* Worker(*)
* Browser
* Worker
* ES5
(*) Typeson is a CommonJS module so you must use a web bundler like browserify, webpack or systemjs to use it in the browser or in a web worker.
# Features

@@ -53,5 +51,5 @@ * Can stringify custom and standard ES5 / ES6 classes.

* Resolves cyclic references, such as lists of objects where each object has a reference to the list
* Minimalistic: This library is a single ES5 compliant JS file of 11kb (1k minified and gzipped)
* You can register any type to be stringifyable (serializable) with your typeson instance.
* Will produce standard JSON identical to that of JSON.stringify() in case you object doesnt contain special types or cyclic references.
* You can register (almost) any type to be stringifyable (serializable) with your typeson instance.
* Output will be identical to that of JSON.stringify() in case your object doesnt contain special types or cyclic references.
* Type specs may encapsulate its type in other registered types. For example, ImageData is encapsulated as `{array: Uint8ClampedArray, width: number, height: number}`, expecting another spec to convert the Uint8ClampedArray. With the builtin preset this means it's gonna be converted to base64, but with the `socketio` preset, its gonna be converted to an ArrayBuffer that is left as-is and streamed binary over the WebSocket channel!

@@ -90,5 +88,6 @@ # Usage

```
*The above sample separates Typeson.encapsulate() from JSON.stringify(). Could also have used Typeson.stringify().*
# Use with socket.io
Socket.io can stream ArrayBuffers as real binary data. This is more efficient than encapsulating it in base64/JSON. Typeson can leave certain types, like ArrayBuffer, untouched, and leave the stringification / binarization part to other libs.
Socket.io can stream ArrayBuffers as real binary data. This is more efficient than encapsulating it in base64/JSON. Typeson can leave certain types, like ArrayBuffer, untouched, and leave the stringification / binarization part to other libs (use Typeson.encapsulate() and not Typeson.stringify()).

@@ -145,3 +144,3 @@ What socket.io doesn't do though, is preserving Dates, Errors or your custom types.

# Use with Worker.postMessage()
Web Workers have the `onmessage` and `postMessage()` communication channel that has built-in support for transferring structures using the structured clone algorithm. It supports Date and ArrayBuffer but not Errors or your own custom classes. To support Error and custom types over web worker channel, register just the types that are needed (Errors and your custom types), and then use Typeson.encapsulate() before posting message, and Typeson.revive() in the onmessage callback.
Web Workers have the `onmessage` and `postMessage()` communication channel that has built-in support for transferring structures using the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). It supports Date, ArrayBuffer and many other standard types, but not Errors or your own custom classes. To support Error and custom types over web worker channel, register just the types that are needed (Errors and your custom types), and then use Typeson.encapsulate() before posting message, and Typeson.revive() in the onmessage callback.

@@ -151,2 +150,7 @@ # API

# constructor ([options])
```js
new Typeson([options]);
```
Creates an instance of Typeson, on which you may configure additional types to support, or call encapsulate(), revive(), stringify() or parse() on.

@@ -200,2 +204,4 @@

*Arguments identical to those of JSON.stringify()*
Generates JSON based on given obj. If given obj has special types or cyclic references, the produce JSON will contain a $types property on the root where type info relies.

@@ -215,2 +221,4 @@

*Arguments identical to those of JSON.parse()*
Parses Typeson genereted JSON back into the original complex structure again.

@@ -217,0 +225,0 @@

var Typeson = require('./typeson');
var B64 = require ('base64-arraybuffer');

@@ -22,2 +23,12 @@ var typeson = new Typeson().register({

function (s) { return {NaN: NaN, Infinity: Infinity, "-Infinity": -Infinity}[s];}
],
ArrayBuffer: [
function test (x) { return x.constructor === ArrayBuffer;},
function encapsulate (b) { return B64.encode(b); },
function revive (b64) { return B64.decode(b64); }
],
DataView: [
function (x) { return x instanceof DataView; },
function (dw) { return { buffer: dw.buffer, byteOffset: dw.byteOffset, byteLength: dw.byteLength }; },
function (obj) { return new DataView(obj.buffer, obj.byteOffset, obj.byteLength); }
]

@@ -248,2 +259,14 @@ });

// Uint8Buffer is not registered.
}, function shouldResolveCyclicsInEncapsulatedObjects() {
var buf = new ArrayBuffer(16);
var data = {
buf: buf,
bar: {
data: new DataView(buf, 8, 8)
}
};
var tson = typeson.stringify(data, null, 2);
console.log(tson);
var back = typeson.parse(tson);
assert (back.buf === back.bar.data.buffer);
}]);

@@ -75,4 +75,6 @@ var keys = Object.keys,

if (refIndex < 0) {
refObjs.push(value);
refKeys.push(keypath);
if (cyclic === true) {
refObjs.push(value);
refKeys.push(keypath);
}
} else {

@@ -118,3 +120,3 @@ types[keypath] = "#";

// Now, also traverse the result in case it contains it own types to replace
return _encapsulate(key, replacers[i].replace(value), false);
return _encapsulate(key, replacers[i].replace(value), "readonly");
}

@@ -121,0 +123,0 @@ }

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc