Skip to content

Commit

Permalink
Merge pull request #12 from commenthol/break-ser-to-module
Browse files Browse the repository at this point in the history
break: phase-out serializeToModule
  • Loading branch information
commenthol committed May 26, 2019
2 parents 5448453 + f49255a commit 27f170a
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 351 deletions.
56 changes: 16 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[![NPM version](https://badge.fury.io/js/serialize-to-js.svg)](https://www.npmjs.com/package/serialize-to-js/)
[![Build Status](https://secure.travis-ci.org/commenthol/serialize-to-js.svg?branch=master)](https://travis-ci.org/commenthol/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.

The following Objects are supported

Expand All @@ -23,13 +23,23 @@ The following Objects are supported
- Int32Array, Uint32Array, Float32Array
- Float64Array

> **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

<!-- !toc (minlevel=2 omit="Table of Contents") -->

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

Expand All @@ -46,7 +56,7 @@ serializes an object to javascript
#### Example - serializing regex, date, buffer, ...

```js
var serialize = require('serialize-to-js').serialize;
var serialize = require('serialize-to-js')
var obj = {
str: '<script>var a = 0 > 1</script>',
num: 3.1415,
Expand All @@ -66,7 +76,7 @@ console.log(serialize(obj))
#### Example - serializing while respecting references

```js
var serialize = require('serialize-to-js').serialize;
var serialize = require('serialize-to-js')
var obj = { object: { regexp: /^test?$/ } };
obj.reference = obj.object;
var opts = { reference: true };
Expand All @@ -93,42 +103,8 @@ console.log(opts.references);

### serializeToModule

`serializeToModule(source, opts, opts.ignoreCircular, opts.reference, opts.comment, opts.beautify) `

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 `<>/`
The `serializeToModule` has been moved to it\`s own repository at [serialize-to-module][].

**Returns**: `String`, serialized representation of `source` as module

## Contribution and License Agreement

Expand All @@ -144,4 +120,4 @@ Copyright (c) 2016- commenthol (MIT License)
See [LICENSE][] for more info.

[LICENSE]: ./LICENSE
[safer-eval]: https://github.com/commenthol/safer-eval
[serialize-to-module]: https://npmjs.com/package/serialize-to-module
132 changes: 129 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,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
130 changes: 0 additions & 130 deletions lib/serialize.js

This file was deleted.

0 comments on commit 27f170a

Please sign in to comment.