Socket
Socket
Sign inDemoInstall

serialize-to-js

Package Overview
Dependencies
0
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.0.1 to 3.0.0

132

lib/index.js

@@ -1,4 +0,130 @@

module.exports = {
serialize: require('./serialize'),
serializeToModule: require('./serializeToModule')
/*
* @copyright 2016- commenthol
* @license MIT
*/
'use strict'
// dependencies
var util = require('./internal/utils')
var Ref = require('./internal/reference')
/**
* serializes an object to javascript
*
* @example <caption>serializing regex, date, buffer, ...</caption>
* var serialize = require('serialize-to-js').serialize;
* var obj = {
* str: '<script>var a = 0 > 1</script>',
* num: 3.1415,
* bool: true,
* nil: null,
* undef: undefined,
* obj: { foo: 'bar' },
* arr: [1, '2'],
* regexp: /^test?$/,
* date: new Date(),
* buffer: new Buffer('data'),
* }
* console.log(serialize(obj))
* // > {str: "\u003Cscript\u003Evar a = 0 \u003E 1\u003C\u002Fscript\u003E", num: 3.1415, bool: true, nil: null, undef: undefined, obj: {foo: "bar"}, arr: [1, "2"], regexp: /^test?$/, date: new Date("2016-04-15T16:22:52.009Z"), buffer: new Buffer('ZGF0YQ==', 'base64')}
*
* @example <caption>serializing while respecting references</caption>
* var serialize = require('serialize-to-js').serialize;
* var obj = { object: { regexp: /^test?$/ } };
* obj.reference = obj.object;
* var opts = { reference: true };
* console.log(serialize(obj, opts));
* //> {object: {regexp: /^test?$/}}
* console.log(opts.references);
* //> [ [ '.reference', '.object' ] ]
*
* @param {Object|Array|Function|Any} source - source to serialize
* @param {Object} [opts] - options
* @param {Boolean} opts.ignoreCircular - ignore circular objects
* @param {Boolean} opts.reference - reference instead of a copy (requires post-processing of opts.references)
* @param {Boolean} opts.unsafe - do not escape chars `<>/`
* @return {String} serialized representation of `source`
*/
function serialize (source, opts) {
var out = ''
var key
var tmp
var type
var i
opts = opts || {}
if (!opts._visited) {
opts._visited = []
}
if (!opts._refs) {
opts.references = []
opts._refs = new Ref(opts.references)
}
if (util.isNull(source)) {
out += 'null'
} else if (util.isArray(source)) {
tmp = source.map(function (item) {
return serialize(item, opts)
})
out += '[' + tmp.join(', ') + ']'
} else if (util.isFunction(source)) {
tmp = source.toString()
// append function to es6 function within obj
out += !/^\s*(function|\([^)]*\)\s*=>)/m.test(tmp) ? 'function ' + tmp : tmp
} else if (util.isObject(source)) {
if (util.isRegExp(source)) {
out += source.toString()
} else if (util.isDate(source)) {
out += 'new Date("' + source.toJSON() + '")'
} else if (util.isError(source)) {
out += 'new Error(' + (source.message ? '"' + source.message + '"' : '') + ')'
} else if (util.isBuffer(source)) {
// check for buffer first otherwise tests fail on node@4.4
// looks like buffers are accidentially detected as typed arrays
out += "Buffer.from('" + source.toString('base64') + "', 'base64')"
} else if ((type = util.isTypedArray(source))) {
tmp = []
for (i = 0; i < source.length; i++) {
tmp.push(source[i])
}
out += 'new ' + type + '(' +
'[' + tmp.join(', ') + ']' +
')'
} else {
tmp = []
// copy properties if not circular
if (!~opts._visited.indexOf(source)) {
opts._visited.push(source)
for (key in source) {
if (source.hasOwnProperty(key)) {
if (opts.reference && util.isObject(source[key])) {
opts._refs.push(key)
if (!opts._refs.hasReference(source[key])) {
tmp.push(Ref.wrapkey(key) + ': ' + serialize(source[key], opts))
}
opts._refs.pop()
} else {
tmp.push(Ref.wrapkey(key) + ': ' + serialize(source[key], opts))
}
}
}
out += '{' + tmp.join(', ') + '}'
opts._visited.pop()
} else {
if (opts.ignoreCircular) {
out += '{/*[Circular]*/}'
} else {
throw new Error('can not convert circular structures.')
}
}
}
} else if (util.isString(source)) {
out += '"' + (opts.unsafe ? util.unsafeString(source) : util.safeString(source)) + '"'
} else {
out += '' + source
}
return out
}
module.exports = serialize

15

package.json
{
"name": "serialize-to-js",
"version": "2.0.1",
"version": "3.0.0",
"description": "serialize objects to javascript",

@@ -16,3 +16,3 @@ "keywords": [

"type": "git",
"url": "https://github.com/commenthol/serialize-to-js.git"
"url": "git+https://github.com/commenthol/serialize-to-js.git"
},

@@ -23,3 +23,3 @@ "license": "MIT",

"directories": {
"doc": "doc",
"lib": "lib",
"test": "test"

@@ -31,4 +31,3 @@ },

"coverage": "nyc -r text -r html npm test",
"doc": "jsdox -o doc lib/*.js",
"lint": "eslint '**/*.js'",
"lint": "eslint lib test",
"prepublishOnly": "npm run all",

@@ -47,5 +46,3 @@ "readme": "markedpp --githubid -i README.md -o README.md",

},
"dependencies": {
"js-beautify": "^1.10.0"
},
"dependencies": {},
"devDependencies": {

@@ -55,3 +52,3 @@ "eslint": "^5.16.0",

"eslint-plugin-import": "^2.17.2",
"eslint-plugin-node": "^9.0.1",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-promise": "^4.1.1",

@@ -58,0 +55,0 @@ "eslint-plugin-standard": "^4.0.0",

@@ -8,3 +8,3 @@ # serialize-to-js

Serialize objects into a `require`-able module while checking circular structures and respecting references.
Serialize objects into a string while checking circular structures and respecting references.

@@ -27,2 +27,13 @@ The following Objects are supported

> **Note:** Version >3.0.0 has moved the serializeToModule method into its own
> package at [serialize-to-module][]
>
> Migrating from 2.x to 3.x for serialize:
> ```js
> // v2.x
> const serialize = require('serialize-to-js').serialize
> // >v3.x
> const serialize = require('serialize-to-js')
> ```
## Table of Contents

@@ -34,3 +45,2 @@

* [serialize](#serialize)
* [serializeToModule](#serializetomodule)
* [Contribution and License Agreement](#contribution-and-license-agreement)

@@ -52,3 +62,3 @@ * [License](#license)

```js
var serialize = require('serialize-to-js').serialize;
var serialize = require('serialize-to-js')
var obj = {

@@ -73,3 +83,3 @@ str: '<script>var a = 0 > 1</script>',

```js
var serialize = require('serialize-to-js').serialize;
var serialize = require('serialize-to-js')
var obj = { object: { regexp: /^test?$/ } };

@@ -101,39 +111,5 @@ obj.reference = obj.object;

`serializeToModule(source, opts, opts.ignoreCircular, opts.reference, opts.comment, opts.beautify) `
The `serializeToModule` has been moved to it\`s own repository at [serialize-to-module][].
serialize to a module which can be `require`ed.
#### Example - serializing while respecting references
```js
var serialTM = require('serialize-to-js').serializeToModule;
var obj = { object: { regexp: /^test?$/ } };
obj.reference = obj.object;
console.log(serialTM(obj, { reference: true }));
//> var m = module.exports = {
//> object: {
//> regexp: /^test?$/
//> }
//> };
//> m.reference = m.object;
```
**Parameters**
**source**: `Object | Array | function | Any`, source to serialize
**opts**: `Object`, options
**opts.ignoreCircular**: `Boolean`, ignore circular objects
**opts.reference**: `Boolean`, reference instead of a copy (requires post-processing of opts.references)
**opts.comment**: `Boolean`, add a comments - useful for linting tools e.g. using 'eslint-disable'
**opts.beautify**: `Boolean | Object`, beautify output - default is `false`. If Object then use je-beautify options.
**opts.unsafe**: `Boolean`, do not escape chars `<>/`
**Returns**: `String`, serialized representation of `source` as module
## Contribution and License Agreement

@@ -153,2 +129,2 @@

[LICENSE]: ./LICENSE
[safer-eval]: https://github.com/commenthol/safer-eval
[serialize-to-module]: https://npmjs.com/package/serialize-to-module
SocketSocket SOC 2 Logo

Product

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc