# als-object-serializer

> An advanced JavaScript library for serializing and deserializing complex objects including those with circular references, functions, and special object types like Date, Set, and Map. Ideal for applications needing robust handling of object serialization

Latest version **1.0.0** (published 2024-07-03) · MIT license · 0 weekly downloads

## Install

```sh
npm install als-object-serializer
pnpm add als-object-serializer
yarn add als-object-serializer
bun add als-object-serializer
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.0 |
| Published | 2024-07-03 |
| First published | 2024-07-03 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 17.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alex Sorkin |
| Maintainers | alexsorkin |
| Keywords | serialize, deserialize, JavaScript, circular references, functions, object serialization, advanced serialization, Date, Set, Map, complex objects, storage, persistence, serialization library |

## Links

- npm: https://www.npmjs.com/package/als-object-serializer
- npm.io page: https://npm.io/package/als-object-serializer

## Alternatives

- [jsforce](https://npm.io/package/jsforce.md) — 851.2K weekly downloads
- [react-native-qrcode-svg](https://npm.io/package/react-native-qrcode-svg.md) — 693.5K weekly downloads
- [@salesforce/plugin-data](https://npm.io/package/@salesforce/plugin-data.md) — 394.9K weekly downloads
- [@backstage/plugin-search-common](https://npm.io/package/@backstage/plugin-search-common.md) — 308.5K weekly downloads
- [@chain-registry/types](https://npm.io/package/@chain-registry/types.md) — 38.4K weekly downloads

## Recent versions

- 1.0.0 (latest) — 2024-07-03

## README

# als-object-serializer

`als-object-serializer` is an advanced JavaScript library designed for serializing and deserializing objects, including those with complex structures such as circular references, functions, `Date`, `RegExp`, `Set`, and `Map` objects. It uniquely preserves function definitions and manages circular dependencies within objects, making it ideal for scenarios where traditional JSON serialization is insufficient.

**Where it can be used?**
With `als-object-serializer` you can save js objects in database, localStorage (it's can be used in browser too), as script binded from backend to frontend and more. 


## Installation and import

Install `als-object-serializer` using npm:

```bash
npm install als-object-serializer
```

**NodeJS usage**

```js
const Obj = require('als-object-serializer');
```

**Browser usage**

```html
<script src="/node_modules/als-object-serializer/index.js"></script>
```

## Usage

Here’s how to use `als-object-serializer` to serialize and deserialize objects:

```javascript
const myObject = {
  name: "Alice",
  details: { age: 25, hobbies: ["reading", "gaming"] }
};

const serialized = Obj.stringify(myObject);
//serialized = {"name":"Alice","details":{"age":25,"hobbies":["reading","gaming"]}}

const parsed = Obj.parse(serializedData); 
// parsed should return an object identical to myObject
```

### Complex Example

```js
const organizers = [
   {name:'Alice',phone:'565-5654545'}
]
const complexObject = {
   date: new Date(),
   events: new Set(['conference', 'meeting', 'webinar']),
   organizers,
   details: {
      organizer: organizers[0],
      contact: function () {
         return `Contact Organizer: ${this.organizer.name}: ${this.organizer.phone}`;
      },
   }
};

const serialized = Obj.stringify(complexObject);
const parsed = Obj.parse(serialized)

console.log(serialized);
// {"date":new Date("2024-07-03T06:52:48.901Z"),"events":new Set(["conference","meeting","webinar"]),"organizers":[{"name":"Alice","phone":"565-5654545"}],"details":{"organizer":function recursiveReference(self) {return self['organizers'][0]},"contact":function () {\n         return `Contact Organizer: ${this.organizer.name}: ${this.organizer.phone}`;\n      }}}

console.log(parsed); // should return similar to complexObject object 
console.log(parsed.organizers[0] === parsed.details.organizer) // true
console.log(parsed.details.contact()) // Contact Organizer: Alice: 565-5654545
```

In example above, cyclyc reference replaced with `recursiveReference` function which had run in Obj.parse method to get the reference. The name of `recursiveReference` available in `Obj.recursiveName` and can be changed. 


## Handling Circular References

`als-object-serializer` uniquely handles circular references by converting them into a string representation that includes a custom function, `recursiveReference`. This function is designed to reconstruct the circular reference when parsed back into an object using the `objParse` method. This approach ensures that complex object graphs with circular references can be safely converted to a string and back without losing their structure.

**Note**: The string output should be used with understanding that it includes JavaScript code that reconstructs circular relationships. When deserializing, ensure that the input string is from a trusted source as the parsing mechanism executes the code within the string.

## Limitations

* Error objects are created without a stack trace; only the message is preserved.
* Buffer objects are not supported.


## Security Considerations

### Serialization of Functions

Serialization of functions with `objStringify` converts functions to their string representation using `toString()`. This process captures the function's code but not its execution context, closures, or external references. Thus, while the function's syntax is preserved, it might not be restored to its original functional state upon deserialization. Use this feature with the understanding that some functions may require additional context to operate as intended.

### Use of `new Function()`

Due to the use of `new Function()` in the `objParse` method for executing string representation, it is crucial to ensure that the serialized string passed to `objParse` is from a trusted and verified source. The execution of untrusted code can lead to serious security vulnerabilities similar to those associated with the use of `eval()`. Always validate or sanitize inputs rigorously when dealing with serialization and deserialization to prevent security issues.

### General Security Note

When using `objParse`, ensure that the input string is from a trusted source. The function utilizes `new Function()` to evaluate the string representation of an object, which can execute arbitrary code. As such, passing unverified or untrusted data to `objParse` can lead to significant security risks similar to those associated with the `eval()` function. Always validate or sanitize inputs to prevent security vulnerabilities.

---
_Source: https://npm.io/package/als-object-serializer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
