Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

toSrc

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

toSrc - npm Package Compare versions

Comparing version 0.1.1 to 0.1.2

423

lib/toSrc.js

@@ -8,236 +8,253 @@ /**

* array are converted to undefined.</p>
*
* @version 0.1.0
*/
(function(){ // wrapper to hide vars
"use strict"; // run code in ES5 strict mode
// Requirements
// Requirements
// Variables
var knownObjs; // stores all nested structures that have been processed to detect circular references
// Variables
var knownObjs; // stores all nested structures that have been processed to detect circular references
// Assigning a number to every type, so type-checking will be a bit faster
var typeOfObject = 1,
typeOfArray = 2,
typeOfString = 3,
typeOfNull = 4,
typeOfUndefined = 5,
typeOfFunction = 6,
typeOfBoolean = 7,
typeOfNumber = 8,
typeOfRegExp = 9,
typeOfDate = 10,
possibleTypes = {
Object: typeOfObject,
Array: typeOfArray,
String: typeOfString,
Null: typeOfNull,
Undefined: typeOfUndefined,
Function: typeOfFunction,
Boolean: typeOfBoolean,
Number: typeOfNumber,
RegExp: typeOfRegExp,
Date: typeOfDate
};
// Assigning a number to every type, so type-checking will be a bit faster
var typeOfObject = 1,
typeOfArray = 2,
typeOfString = 3,
typeOfNull = 4,
typeOfUndefined = 5,
typeOfFunction = 6,
typeOfBoolean = 7,
typeOfNumber = 8,
typeOfRegExp = 9,
typeOfDate = 10,
possibleTypes = {
Object: typeOfObject,
Array: typeOfArray,
String: typeOfString,
Null: typeOfNull,
Undefined: typeOfUndefined,
Function: typeOfFunction,
Boolean: typeOfBoolean,
Number: typeOfNumber,
RegExp: typeOfRegExp,
Date: typeOfDate
};
/**
* <p>The only way to check for a type in JavaScript is to compare the
* result of the internal .toString() method (returns something like [object Array])</p>
*
* <p>The type can be something of:
* <ul>
* <li>Object</li>
* <li>Array</li>
* <li>Date</li>
* <li>Function</li>
* <li>RegExp</li>
* <li>Number</li>
* <li>Boolean</li>
* <li>String</li>
* <li>Null</li>
* <li>Undefined</li>
* </ul>
* The first character of the type must be a capital letter (unlike you may be
* used to the typeof operator)
* </p>
*
* <p></p>
*
* @private
* @param {Mixed} obj
* @returns {Boolean} result
*/
function typeOf(obj) {
if (obj === null) {
return typeOfNull;
} else if (obj === undefined) {
return typeOfUndefined;
} else {
return possibleTypes[
Object.prototype.toString.call(obj).slice(8, -1) // Returns a string like "Object", "Array", "String", ...
];
/**
* <p>The only way to check for a type in JavaScript is to compare the
* result of the internal .toString() method (returns something like [object Array])</p>
*
* <p>The type can be something of:
* <ul>
* <li>Object</li>
* <li>Array</li>
* <li>Date</li>
* <li>Function</li>
* <li>RegExp</li>
* <li>Number</li>
* <li>Boolean</li>
* <li>String</li>
* <li>Null</li>
* <li>Undefined</li>
* </ul>
* The first character of the type must be a capital letter (unlike you may be
* used to the typeof operator)
* </p>
*
* <p></p>
*
* @private
* @param {*} obj
* @returns {Boolean} result
*/
function typeOf(obj) {
if (obj === null) {
return typeOfNull;
} else if (obj === undefined) {
return typeOfUndefined;
} else {
return possibleTypes[
Object.prototype.toString.call(obj).slice(8, -1) // Returns a string like "Object", "Array", "String", ...
];
}
}
}
/**
* Serializes a function. Usually you can call .toString() on all functions
* that are have been defined in JavaScript. Unfortunately this doesn't work
* on native functions like Date, String, etc.. In this case this function
* returns the function name;
*
* @param {Function} fn
* @return {String}
*/
function serializeFunction(fn) {
var src = fn.toString();
// Because search is faster than match, we perform first the .search().
// We're assuming that native functions are less likely to be stringified
// than custom functions
if (src.search(/^function \w+\(\) \{\s*\[native code\]\s*\}$/) === -1) { // IF TRUE: It's a regular function defined in JavaScript
return src;
} else { // IF TRUE: It's a native function with native code that can't be stringified
return src.match(/^function (\w+)\(\) \{\s*\[native code\]\s*\}$/)[1]; // returns the function name
}
}
/**
* <p>Converts any object into valid source code.</p>
*
* <p>If you dont pass a depth-parameter, it will default to 1. In this case
* all objects within an object or an array are converted to undefined.</p>
*
* @private
* @param {Mixed} obj
* @param {Integer} depth
* @returns {String} source code
*/
function toSrcRecursive(obj, depth) {
var type = typeOf(obj),
objString,
key,
i, l;
if (depth === undefined || depth === null) {
depth = 1;
}
/**
* <p>Converts any object into valid source code.</p>
*
* <p>If you dont pass a depth-parameter, it will default to 1. In this case
* all objects within an object or an array are converted to undefined.</p>
*
* @private
* @param {*} obj
* @param {Integer} depth
* @returns {String} source code
*/
function toSrcRecursive(obj, depth) {
var type = typeOf(obj),
objString,
key,
i, l;
// We start with nested structures like Objects or Arrays to make
// recursion really fast
if (type === typeOfObject) {
if(depth > 0) {
if(knownObjs.indexOf(obj) !== -1) {
console.log('toSrc warning: Circular reference detected within object ', obj);
if (depth === undefined || depth === null) {
depth = 1;
}
return 'undefined';
// We start with nested structures like Objects or Arrays to make
// recursion really fast
if (type === typeOfObject) {
if(depth > 0) {
if(knownObjs.indexOf(obj) !== -1) {
console.log('toSrc warning: Circular reference detected within object ', obj);
return 'undefined';
} else {
knownObjs.push(obj);
}
objString = '{';
for(key in obj) { if(obj.hasOwnProperty(key)) {
objString += '"' + key + '": ' + toSrcRecursive(obj[key], depth - 1) + ', ';
}}
if(objString.length > 1) {
objString = objString.substring(0, objString.length - 2);
}
objString += '}';
} else {
knownObjs.push(obj);
objString = 'undefined';
}
objString = '{';
for(key in obj) { if(obj.hasOwnProperty(key)) {
objString += '"' + key + '": ' + toSrcRecursive(obj[key], depth - 1) + ', ';
}}
if(objString.length > 1) {
objString = objString.substring(0, objString.length - 2);
return objString;
} else if (type === typeOfArray) {
if(depth > 0) {
if(knownObjs.indexOf(obj) !== -1) {
console.log('toSrc warning: Circular reference detected within array ', obj);
return 'undefined';
} else {
knownObjs.push(obj);
}
objString = '[';
for(i=0, l=obj.length; i<l; i++) {
objString += toSrcRecursive(obj[i], depth - 1) + ', ';
}
if(objString.length > 1) {
objString = objString.substring(0, objString.length - 2);
}
objString += ']';
} else {
objString = 'undefined';
}
objString += '}';
} else {
objString = 'undefined';
}
return objString;
} else if (type === typeOfArray) {
if(depth > 0) {
if(knownObjs.indexOf(obj) !== -1) {
console.log('toSrc warning: Circular reference detected within array ', obj);
return 'undefined';
return objString;
} else if (type === typeOfString) {
return '"'+ obj + '"';
} else if (type === typeOfNull) {
return 'null';
} else if (type === typeOfUndefined) {
return 'undefined';
} else if (type === typeOfFunction) {
return serializeFunction(obj);
} else if (type === typeOfBoolean) {
return obj.toString();
} else if (type === typeOfNumber) {
if(obj === Number.MAX_VALUE) {
return 'Number.MAX_VALUE';
} else if(obj === Number.MIN_VALUE) {
return 'Number.MIN_VALUE';
} else if(obj === Math.E) {
return 'Math.E';
} else if(obj === Math.LN2) {
return 'Math.LN2';
} else if(obj === Math.LN10) {
return 'Math.LN10';
} else if(obj === Math.LOG2E) {
return 'Math.LOG2E';
} else if(obj === Math.LOG10E) {
return 'Math.LOG10E';
} else if(obj === Math.PI) {
return 'Math.PI';
} else if(obj === Math.SQRT1_2) {
return 'Math.SQRT1_2';
} else if(obj === Math.SQRT2) {
return 'Math.SQRT2';
} else {
knownObjs.push(obj);
return obj.toString();
}
objString = '[';
for(i=0, l=obj.length; i<l; i++) {
objString += toSrcRecursive(obj[i], depth - 1) + ', ';
}
if(objString.length > 1) {
objString = objString.substring(0, objString.length - 2);
}
objString += ']';
} else if (type === typeOfRegExp) {
return obj.toString();
} else if (type === typeOfDate) {
return 'new Date(' + obj.getTime() + ')';
} else {
objString = 'undefined';
return 'undefined'; // fallback for not supported types like XML
}
return objString;
} else if (type === typeOfString) {
return '"'+ obj + '"';
} else if (type === typeOfNull) {
return 'null';
} else if (type === typeOfUndefined) {
return 'undefined';
} else if (type === typeOfFunction) {
return obj.toString();
} else if (type === typeOfBoolean) {
return obj.toString();
} else if (type === typeOfNumber) {
if(obj === Number.MAX_VALUE) {
return 'Number.MAX_VALUE';
} else if(obj === Number.MIN_VALUE) {
return 'Number.MIN_VALUE';
} else if(obj === Math.E) {
return 'Math.E';
} else if(obj === Math.LN2) {
return 'Math.LN2';
} else if(obj === Math.LN10) {
return 'Math.LN10';
} else if(obj === Math.LOG2E) {
return 'Math.LOG2E';
} else if(obj === Math.LOG10E) {
return 'Math.LOG10E';
} else if(obj === Math.PI) {
return 'Math.PI';
} else if(obj === Math.SQRT1_2) {
return 'Math.SQRT1_2';
} else if(obj === Math.SQRT2) {
return 'Math.SQRT2';
} else {
return obj.toString();
}
} else if (type === typeOfRegExp) {
return obj.toString();
} else if (type === typeOfDate) {
return 'new Date(' + obj.getTime() + ')';
} else {
return 'undefined'; // fallback for not supported types like XML
}
}
/**
* <p>Converts any object into valid source code.</p>
*
* <p>If you dont pass a depth-parameter, it will default to 1. In this case
* all objects within an object or an array are converted to undefined.</p>
*
* <p>Types that can be converted by this module are:
* <ul>
* <li>Object</li>
* <li>Array</li>
* <li>Date</li>
* <li>Function</li>
* <li>RegExp</li>
* <li>Number</li>
* <li>Boolean</li>
* <li>String</li>
* <li>Null</li>
* <li>Undefined</li>
* </ul>
* </p>
*
* @param {Mixed} obj
* @param {Integer} depth
* @returns {String} source code
*/
function toSrc(obj, depth) {
var result;
/**
* <p>Converts any object into valid source code.</p>
*
* <p>If you dont pass a depth-parameter, it will default to 1. In this case
* all objects within an object or an array are converted to undefined.</p>
*
* <p>Types that can be converted by this module are:
* <ul>
* <li>Object</li>
* <li>Array</li>
* <li>Date</li>
* <li>Function</li>
* <li>RegExp</li>
* <li>Number</li>
* <li>Boolean</li>
* <li>String</li>
* <li>Null</li>
* <li>Undefined</li>
* </ul>
* </p>
*
* @param {*} obj
* @param {Integer} depth
* @returns {String} source code
*/
function toSrc(obj, depth) {
var result;
knownObjs = []; // resetting the knownObjs
result = toSrcRecursive(obj, depth);
knownObjs = []; // resetting the knownObjs
result = toSrcRecursive(obj, depth);
return result;
}
return result;
}
if(typeof window !== 'undefined') { // IF TRUE: We're within a browser context
if (window.toSrc === undefined) {
window.toSrc = toSrc;
} else {
console.log("Name collision: window.toSrc already exists...");
if(typeof window !== 'undefined') { // IF TRUE: We're within a browser context
if (window.toSrc === undefined) {
window.toSrc = toSrc;
} else {
console.log("Name collision: window.toSrc already exists...");
}
} else if(typeof module !== 'undefined'){ // IF TRUE: We're within a commonJS context (like node.js)
module.exports = toSrc;
}
} else if(typeof module !== 'undefined'){ // IF TRUE: We're within a commonJS context (like node.js)
module.exports = toSrc;
}
})();
{
"name": "toSrc",
"description": "Turns every JavaScript object or primitive into valid source code.",
"version": "0.1.1",
"homepage": "https://github.com/pandaa/toSrc",
"repository": "git://github.com/pandaa/toSrc.git",
"author": "Johannes Ewald <mail@johannesewald.de>",
"version": "0.1.2",
"homepage": "http://jhnns.github.com/toSrc",
"repository": {
"type": "git",
"url": "git://github.com/jhnns/toSrc.git"
},
"author" : {
"name" : "Johannes Ewald",
"email" : "mail@johannesewald.de",
"web" : "http://johannesewald.de"
},
"main": "./lib/toSrc.js",
"keywords": ["toSource", "toSrc", "source", "object", "serialization", "stringify", "JSON", "eval", "vm", "obj2src"],
"bugs" : {
"url" : "http://github.com/jhnns/toSrc/issues",
"email" : "mail@johannesewald.de"
},
"dependencies": {},

@@ -11,0 +22,0 @@ "devDependencies": {},

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

toSrc
**toSrc**
========

@@ -12,2 +12,4 @@

-----------------------------------------------------------------
Installation

@@ -17,18 +19,4 @@ ------------

Usage
-----
* **Params**
-----------------------------------------------------------------
1. **obj**: *The object to stringify. Can also be a primitive like `1` or `true`.*
2. **depth** (optional): *The depth to go. All nested structures like objects or arrays deeper than this will be undefined. Defaults to 1, meaning that every object or array will be undefined by default.*
* **In node.js**
`require("toSrc")(obj, depth);`
* **In the browser**
Just call `toSrc(obj, depth);`
Examples

@@ -46,2 +34,3 @@ -----

toSrc("1"); // = '"1"'
toSrc('1'); // = '"1"' toSrc always uses double-quotes

@@ -56,3 +45,3 @@ // Constants

toSrc(/myRegEx/gi); // = '/myRegEx/gi'
toSrc(new RegExp("myRegEx"); // = '/myRegEx/'
toSrc(new RegExp("myRegEx")); // = '/myRegEx/'

@@ -65,7 +54,7 @@ // Date

///////////////////////////////////////
toSrc(function() {
function testFunc() {
var test = "hello";
}); /* = 'function () {
var test = "hello";
}' */
}
toSrc(testFunc); /* = 'function () {\n var test = "hello";\n}' */
toSrc(String); // = 'String', native functions don't expose the source code

@@ -81,5 +70,5 @@ // Arrays

toSrc({
"regEx": /regex/gi,
"anotherObj": {
"test": "test"
regEx: /regex/gi,
anotherObj: {
test: "test"
}

@@ -99,11 +88,58 @@ });

For more examples, check out the `test/test.js`
For more examples check out `test/test.js`
-----------------------------------------------------------------
API
-----
**toSrc(***obj*, *depth***)**
- *{ * } obj*: The object to stringify. Can also be a primitive like `1` or `true`.
- *{Number=1} depth*: The depth to go. All nested structures like objects or arrays deeper than this will be undefined. Defaults to 1, meaning that every object or array within `obj` will be undefined by default.
**In node.js**
`require("toSrc")(obj, depth);`
**In the browser**
Just call `toSrc(obj, depth);`
-----------------------------------------------------------------
Notes
-----
* **Circular references** will be undefined. No error is thrown, but a warning is logged.
* All **math constants** are restored to their source representation, e.g.: `toSrc(Math.PI); // = 'Math.PI' instead of 3.14...`
* All **dates** are restored to their original time of creation, e.g.: `toSrc(new Date()) // = 'new Date(<time of creation in ms>)'`
* **Dynamic regular expressions** created via `new RegExp()` will NOT be dynamic anymore. `toSrc(new RegExp(someString))` will return `'/<value of someString>/'` instead of `'new RegExp(someString)'
* Circular references will be undefined. No error is thrown, but a warning is logged.
* All math constants are restored to their source representation, e.g.: `toSrc(Math.PI); // = 'Math.PI' instead of 3.14...`
* All dates are restored to their original time of creation, e.g.: `toSrc(new Date()) // = 'new Date(<time of creation in ms>)'`
* Dynamic regular expressions created via `new RegExp()` will **not** be dynamic anymore. `toSrc(new RegExp(someString))` will return `'/<value of someString>/'` instead of `'new RegExp(someString)'
Feel free to modify the code to meet your needs.
-----------------------------------------------------------------
## License
(The MIT License)
Copyright (c) 2012 Johannes Ewald &lt;mail@johannesewald.de&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@@ -5,3 +5,4 @@ //////////////////////////////////////////////////////////////////////////////////

var toSrc = require('../lib/toSrc'),
assert = require('assert');
assert = require('assert'),
_log = console.log;

@@ -94,3 +95,12 @@ function typeOf(obj) {

},
"referenceTestObj": referenceTestObj
"referenceTestObj": referenceTestObj,
"Boolean": Boolean,
"String": String,
"Number": Number,
"Array": Array,
"Function": Function,
"Object": Object,
"RegExp": RegExp,
"Date": Date,
"Error": Error
};

@@ -160,9 +170,13 @@

testObj.circularRef = testObj
console.log('You should see a warning now...');
testObj.circularRef = testObj;
console.log = function (msg) { // stubbing console.log
console.log.times++;
};
console.log.times = 0;
eval('var copy = ' + toSrc(testObj, 3));
assert.equal(checkIdentity(testObj, copy), false);
assert.strictEqual(console.log.times, 1); // toSrc should print a warning on console.log
console.log = _log; // returning stub

Sorry, the diff of this file is not supported yet

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