circular-reference 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 derRaab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # circular-reference
2
+
3
+ Enables `JSON.stringify()` and `JSON.parse()` for JavaScript objects with circular references.
4
+
5
+ This library provides two methods that handle circular references by injecting or resolving a special string representation (e.g., `<CircularReference path=''>` refers to the root object):
6
+
7
+ - `stringifyCircularReferences(data:any, clone=false)` replaces all circular references with a string representation of their paths within the structure. If `clone` is `true`, the function operates on a deep copy of data, leaving the original unchanged.
8
+
9
+ - `parseCircularReferences(data:any, clone=false)` restores circular references based on the encoded paths. If `clone` is `true`, it modifies a deep copy instead of data directly.
10
+
11
+
12
+ ## Install
13
+
14
+ `npm install circular-reference` or use your preferred package manager.
15
+
16
+ ## How to use
17
+
18
+ ### Basic example
19
+
20
+ ```js
21
+ import { parseCircularReferences, stringifyCircularReferences } from "circular-reference";
22
+
23
+ // Object that references itself
24
+ const objectA = {};
25
+ objectA.ref = objectA;
26
+
27
+ // Convert the object to a JSON string
28
+ objectA = stringifyCircularReferences(objectA);
29
+ const objectAString = JSON.stringify(objectA);
30
+ console.log(objectAString);
31
+ /* Output: {"ref":"<CircularReference path=''>"} */
32
+
33
+ // Restore the same structure from the json string
34
+ const objectB = JSON.parse(objectAString);
35
+ objectB = parseCircularReferences(objectB);
36
+ console.log(objectB.ref === objectB); // true
37
+ ```
38
+ **Note:** In Node.js, circular references are displayed using `<ref *X>` notation, whereas browsers will still throw a "Converting circular structure to JSON" error if you try to directly `JSON.stringify()` an unresolved circular object.
39
+
40
+ ### Complex example
41
+
42
+ ```js
43
+ import { parseCircularReferences, stringifyCircularReferences } from "circular-reference";
44
+
45
+ // Two arrays and two objects
46
+ const array1 = [];
47
+ const array2 = [];
48
+ const object1 = {};
49
+ const object2 = {};
50
+ // Each object references all objects and arrays (including itself)
51
+ object1["array1"] = array1;
52
+ object1["array2"] = array2;
53
+ object1["object1"] = object1;
54
+ object1["object2"] = object2;
55
+ object2["array1"] = array1;
56
+ object2["array2"] = array2;
57
+ object2["object1"] = object1;
58
+ object2["object2"] = object2;
59
+ // Each array references all objects and arrays (including itself)
60
+ array1.push(array1);
61
+ array1.push(array2);
62
+ array1.push(object1);
63
+ array1.push(object2);
64
+ array2.push(array1);
65
+ array2.push(array2);
66
+ array2.push(object1);
67
+ array2.push(object2);
68
+
69
+ // Save the object as a json string
70
+ stringifyCircularReferences(object1);
71
+ const dataString = JSON.stringify(object1, null, 2);
72
+ console.log(dataString);
73
+ /* Output:
74
+ {
75
+ "array1": [
76
+ "<CircularReference path='[\"array1\"]'>",
77
+ [
78
+ "<CircularReference path='[\"array1\"]'>",
79
+ "<CircularReference path='[\"array1\"][1]'>",
80
+ "<CircularReference path=''>",
81
+ {
82
+ "array1": "<CircularReference path='[\"array1\"]'>",
83
+ "array2": "<CircularReference path='[\"array1\"][1]'>",
84
+ "object1": "<CircularReference path=''>",
85
+ "object2": "<CircularReference path='[\"array1\"][1][3]'>"
86
+ }
87
+ ],
88
+ "<CircularReference path=''>",
89
+ "<CircularReference path='[\"array1\"][1][3]'>"
90
+ ],
91
+ "array2": "<CircularReference path='[\"array1\"][1]'>",
92
+ "object1": "<CircularReference path=''>",
93
+ "object2": "<CircularReference path='[\"array1\"][1][3]'>"
94
+ }
95
+ */
96
+
97
+ // Parse the object again
98
+ const data = JSON.parse(dataString);
99
+ // Resolve the circular references
100
+ parseCircularReferences(data);
101
+
102
+ // Now you have a clone of the original object with the same structure and values
103
+ console.log(data);
104
+ /* Output in Node.js (browser would throw a "Converting circular structure to JSON" error):
105
+ <ref *3> {
106
+ array1: <ref *1> [
107
+ [Circular *1],
108
+ <ref *2> [
109
+ [Circular *1],
110
+ [Circular *2],
111
+ [Circular *3],
112
+ [Object]
113
+ ],
114
+ [Circular *3],
115
+ <ref *4> {
116
+ array1: [Circular *1],
117
+ array2: [Array],
118
+ object1: [Circular *3],
119
+ object2: [Circular *4]
120
+ }
121
+ ],
122
+ array2: <ref *2> [
123
+ <ref *1> [
124
+ [Circular *1],
125
+ [Circular *2],
126
+ [Circular *3],
127
+ [Object]
128
+ ],
129
+ [Circular *2],
130
+ [Circular *3],
131
+ <ref *4> {
132
+ array1: [Array],
133
+ array2: [Circular *2],
134
+ object1: [Circular *3],
135
+ object2: [Circular *4]
136
+ }
137
+ ],
138
+ object1: [Circular *3],
139
+ object2: <ref *4> {
140
+ array1: <ref *1> [
141
+ [Circular *1],
142
+ [Array],
143
+ [Circular *3],
144
+ [Circular *4]
145
+ ],
146
+ array2: <ref *2> [
147
+ [Array],
148
+ [Circular *2],
149
+ [Circular *3],
150
+ [Circular *4]
151
+ ],
152
+ object1: [Circular *3],
153
+ object2: [Circular *4]
154
+ }
155
+ }
156
+ ```
157
+
@@ -0,0 +1,5 @@
1
+ declare const parseCircularReferences: (data: Object, clone?: boolean) => void;
2
+
3
+ declare const stringifyCircularReferences: (data: Object, clone?: boolean) => Object;
4
+
5
+ export { parseCircularReferences, stringifyCircularReferences };
@@ -0,0 +1,5 @@
1
+ declare const parseCircularReferences: (data: Object, clone?: boolean) => void;
2
+
3
+ declare const stringifyCircularReferences: (data: Object, clone?: boolean) => Object;
4
+
5
+ export { parseCircularReferences, stringifyCircularReferences };
package/dist/index.js ADDED
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ parseCircularReferences: () => parseCircularReferences,
24
+ stringifyCircularReferences: () => stringifyCircularReferences
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/path.ts
29
+ var createPathSegmentFromArrayIndex = (index) => {
30
+ return "[" + index + "]";
31
+ };
32
+ var createPathSegmentFromObjectKey = (key) => {
33
+ return '["' + key + '"]';
34
+ };
35
+ var joinPath = (pathSegments) => {
36
+ return pathSegments.join("");
37
+ };
38
+
39
+ // src/reference.ts
40
+ var PATH_PREFIX = "<CircularReference path='";
41
+ var PATH_SUFFIX = "'>";
42
+ var stringifyReferencePath = (path) => {
43
+ return PATH_PREFIX + path + PATH_SUFFIX;
44
+ };
45
+ var parseReferencePath = (reference) => {
46
+ let pathStartIndexOf = reference.indexOf(PATH_PREFIX);
47
+ if (pathStartIndexOf === -1) {
48
+ return null;
49
+ }
50
+ pathStartIndexOf += PATH_PREFIX.length;
51
+ const pathEndIndexOf = reference.lastIndexOf(PATH_SUFFIX);
52
+ if (pathEndIndexOf === -1) {
53
+ return null;
54
+ }
55
+ return reference.substring(pathStartIndexOf, pathEndIndexOf);
56
+ };
57
+
58
+ // src/parse.ts
59
+ var collectObjectPaths = (parentObj, objPathMap, path) => {
60
+ if (typeof parentObj !== "object") {
61
+ return;
62
+ }
63
+ objPathMap.set(parentObj, joinPath(path));
64
+ if (Array.isArray(parentObj)) {
65
+ for (let i = 0; i < parentObj.length; i++) {
66
+ collectObjectPaths(parentObj[i], objPathMap, path.concat([createPathSegmentFromArrayIndex(i)]));
67
+ }
68
+ return;
69
+ }
70
+ for (const key in parentObj) {
71
+ collectObjectPaths(parentObj[key], objPathMap, path.concat([createPathSegmentFromObjectKey(key)]));
72
+ }
73
+ };
74
+ var parseRecursion = (parentObj, objReferenceMap, pathObjectMap, path, unresolvedReferences) => {
75
+ if (typeof parentObj !== "object") {
76
+ return;
77
+ }
78
+ let reference = stringifyReferencePath(joinPath(path));
79
+ objReferenceMap.set(parentObj, reference);
80
+ if (Array.isArray(parentObj)) {
81
+ for (let i = 0; i < parentObj.length; i++) {
82
+ const childObject = parentObj[i];
83
+ if (objReferenceMap.has(childObject)) {
84
+ parentObj[i] = objReferenceMap.get(childObject);
85
+ continue;
86
+ }
87
+ if (typeof childObject === "string") {
88
+ const path2 = parseReferencePath(childObject);
89
+ if (path2 !== null) {
90
+ const referenceObject = pathObjectMap.get(path2);
91
+ if (referenceObject) {
92
+ parentObj[i] = referenceObject;
93
+ } else {
94
+ unresolvedReferences.push(childObject);
95
+ }
96
+ }
97
+ continue;
98
+ }
99
+ parseRecursion(childObject, objReferenceMap, pathObjectMap, path.concat([createPathSegmentFromArrayIndex(i)]), unresolvedReferences);
100
+ }
101
+ return;
102
+ }
103
+ for (const key in parentObj) {
104
+ const childObject = parentObj[key];
105
+ if (objReferenceMap.has(childObject)) {
106
+ parentObj[key] = objReferenceMap.get(childObject);
107
+ continue;
108
+ }
109
+ if (typeof childObject === "string") {
110
+ const path2 = parseReferencePath(childObject);
111
+ if (path2 !== null) {
112
+ const referenceObject = pathObjectMap.get(path2);
113
+ if (referenceObject) {
114
+ parentObj[key] = referenceObject;
115
+ } else {
116
+ unresolvedReferences.push(childObject);
117
+ }
118
+ }
119
+ continue;
120
+ }
121
+ parseRecursion(childObject, objReferenceMap, pathObjectMap, path.concat([createPathSegmentFromObjectKey(key)]), unresolvedReferences);
122
+ }
123
+ };
124
+ var parseCircularReferences = (data, clone = false) => {
125
+ if (clone) {
126
+ data = structuredClone(data);
127
+ }
128
+ let unresolvedReferencesLength = -1;
129
+ let unresolvedReferences = [];
130
+ while (unresolvedReferencesLength !== unresolvedReferences.length) {
131
+ unresolvedReferencesLength = unresolvedReferences.length;
132
+ unresolvedReferences = [];
133
+ const objPathMap = /* @__PURE__ */ new Map();
134
+ collectObjectPaths(data, objPathMap, []);
135
+ const pathObjectMap = /* @__PURE__ */ new Map();
136
+ for (const [object, path] of objPathMap) {
137
+ pathObjectMap.set(path, object);
138
+ }
139
+ parseRecursion(data, /* @__PURE__ */ new Map(), pathObjectMap, [], unresolvedReferences);
140
+ }
141
+ };
142
+
143
+ // src/stringify.ts
144
+ var stringifyRecursion = (parentObj, objReferenceMap, path) => {
145
+ if (typeof parentObj !== "object") {
146
+ return;
147
+ }
148
+ let reference = stringifyReferencePath(joinPath(path));
149
+ objReferenceMap.set(parentObj, reference);
150
+ if (Array.isArray(parentObj)) {
151
+ for (let i = 0; i < parentObj.length; i++) {
152
+ const childObject = parentObj[i];
153
+ if (objReferenceMap.has(childObject)) {
154
+ parentObj[i] = objReferenceMap.get(childObject);
155
+ continue;
156
+ }
157
+ stringifyRecursion(childObject, objReferenceMap, path.concat([createPathSegmentFromArrayIndex(i)]));
158
+ }
159
+ return;
160
+ }
161
+ for (const key in parentObj) {
162
+ const childObject = parentObj[key];
163
+ if (objReferenceMap.has(childObject)) {
164
+ parentObj[key] = objReferenceMap.get(childObject);
165
+ continue;
166
+ }
167
+ stringifyRecursion(childObject, objReferenceMap, path.concat([createPathSegmentFromObjectKey(key)]));
168
+ }
169
+ };
170
+ var stringifyCircularReferences = (data, clone = false) => {
171
+ if (clone) {
172
+ data = structuredClone(data);
173
+ }
174
+ stringifyRecursion(data, /* @__PURE__ */ new Map(), []);
175
+ return data;
176
+ };
177
+ // Annotate the CommonJS export names for ESM import in node:
178
+ 0 && (module.exports = {
179
+ parseCircularReferences,
180
+ stringifyCircularReferences
181
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,153 @@
1
+ // src/path.ts
2
+ var createPathSegmentFromArrayIndex = (index) => {
3
+ return "[" + index + "]";
4
+ };
5
+ var createPathSegmentFromObjectKey = (key) => {
6
+ return '["' + key + '"]';
7
+ };
8
+ var joinPath = (pathSegments) => {
9
+ return pathSegments.join("");
10
+ };
11
+
12
+ // src/reference.ts
13
+ var PATH_PREFIX = "<CircularReference path='";
14
+ var PATH_SUFFIX = "'>";
15
+ var stringifyReferencePath = (path) => {
16
+ return PATH_PREFIX + path + PATH_SUFFIX;
17
+ };
18
+ var parseReferencePath = (reference) => {
19
+ let pathStartIndexOf = reference.indexOf(PATH_PREFIX);
20
+ if (pathStartIndexOf === -1) {
21
+ return null;
22
+ }
23
+ pathStartIndexOf += PATH_PREFIX.length;
24
+ const pathEndIndexOf = reference.lastIndexOf(PATH_SUFFIX);
25
+ if (pathEndIndexOf === -1) {
26
+ return null;
27
+ }
28
+ return reference.substring(pathStartIndexOf, pathEndIndexOf);
29
+ };
30
+
31
+ // src/parse.ts
32
+ var collectObjectPaths = (parentObj, objPathMap, path) => {
33
+ if (typeof parentObj !== "object") {
34
+ return;
35
+ }
36
+ objPathMap.set(parentObj, joinPath(path));
37
+ if (Array.isArray(parentObj)) {
38
+ for (let i = 0; i < parentObj.length; i++) {
39
+ collectObjectPaths(parentObj[i], objPathMap, path.concat([createPathSegmentFromArrayIndex(i)]));
40
+ }
41
+ return;
42
+ }
43
+ for (const key in parentObj) {
44
+ collectObjectPaths(parentObj[key], objPathMap, path.concat([createPathSegmentFromObjectKey(key)]));
45
+ }
46
+ };
47
+ var parseRecursion = (parentObj, objReferenceMap, pathObjectMap, path, unresolvedReferences) => {
48
+ if (typeof parentObj !== "object") {
49
+ return;
50
+ }
51
+ let reference = stringifyReferencePath(joinPath(path));
52
+ objReferenceMap.set(parentObj, reference);
53
+ if (Array.isArray(parentObj)) {
54
+ for (let i = 0; i < parentObj.length; i++) {
55
+ const childObject = parentObj[i];
56
+ if (objReferenceMap.has(childObject)) {
57
+ parentObj[i] = objReferenceMap.get(childObject);
58
+ continue;
59
+ }
60
+ if (typeof childObject === "string") {
61
+ const path2 = parseReferencePath(childObject);
62
+ if (path2 !== null) {
63
+ const referenceObject = pathObjectMap.get(path2);
64
+ if (referenceObject) {
65
+ parentObj[i] = referenceObject;
66
+ } else {
67
+ unresolvedReferences.push(childObject);
68
+ }
69
+ }
70
+ continue;
71
+ }
72
+ parseRecursion(childObject, objReferenceMap, pathObjectMap, path.concat([createPathSegmentFromArrayIndex(i)]), unresolvedReferences);
73
+ }
74
+ return;
75
+ }
76
+ for (const key in parentObj) {
77
+ const childObject = parentObj[key];
78
+ if (objReferenceMap.has(childObject)) {
79
+ parentObj[key] = objReferenceMap.get(childObject);
80
+ continue;
81
+ }
82
+ if (typeof childObject === "string") {
83
+ const path2 = parseReferencePath(childObject);
84
+ if (path2 !== null) {
85
+ const referenceObject = pathObjectMap.get(path2);
86
+ if (referenceObject) {
87
+ parentObj[key] = referenceObject;
88
+ } else {
89
+ unresolvedReferences.push(childObject);
90
+ }
91
+ }
92
+ continue;
93
+ }
94
+ parseRecursion(childObject, objReferenceMap, pathObjectMap, path.concat([createPathSegmentFromObjectKey(key)]), unresolvedReferences);
95
+ }
96
+ };
97
+ var parseCircularReferences = (data, clone = false) => {
98
+ if (clone) {
99
+ data = structuredClone(data);
100
+ }
101
+ let unresolvedReferencesLength = -1;
102
+ let unresolvedReferences = [];
103
+ while (unresolvedReferencesLength !== unresolvedReferences.length) {
104
+ unresolvedReferencesLength = unresolvedReferences.length;
105
+ unresolvedReferences = [];
106
+ const objPathMap = /* @__PURE__ */ new Map();
107
+ collectObjectPaths(data, objPathMap, []);
108
+ const pathObjectMap = /* @__PURE__ */ new Map();
109
+ for (const [object, path] of objPathMap) {
110
+ pathObjectMap.set(path, object);
111
+ }
112
+ parseRecursion(data, /* @__PURE__ */ new Map(), pathObjectMap, [], unresolvedReferences);
113
+ }
114
+ };
115
+
116
+ // src/stringify.ts
117
+ var stringifyRecursion = (parentObj, objReferenceMap, path) => {
118
+ if (typeof parentObj !== "object") {
119
+ return;
120
+ }
121
+ let reference = stringifyReferencePath(joinPath(path));
122
+ objReferenceMap.set(parentObj, reference);
123
+ if (Array.isArray(parentObj)) {
124
+ for (let i = 0; i < parentObj.length; i++) {
125
+ const childObject = parentObj[i];
126
+ if (objReferenceMap.has(childObject)) {
127
+ parentObj[i] = objReferenceMap.get(childObject);
128
+ continue;
129
+ }
130
+ stringifyRecursion(childObject, objReferenceMap, path.concat([createPathSegmentFromArrayIndex(i)]));
131
+ }
132
+ return;
133
+ }
134
+ for (const key in parentObj) {
135
+ const childObject = parentObj[key];
136
+ if (objReferenceMap.has(childObject)) {
137
+ parentObj[key] = objReferenceMap.get(childObject);
138
+ continue;
139
+ }
140
+ stringifyRecursion(childObject, objReferenceMap, path.concat([createPathSegmentFromObjectKey(key)]));
141
+ }
142
+ };
143
+ var stringifyCircularReferences = (data, clone = false) => {
144
+ if (clone) {
145
+ data = structuredClone(data);
146
+ }
147
+ stringifyRecursion(data, /* @__PURE__ */ new Map(), []);
148
+ return data;
149
+ };
150
+ export {
151
+ parseCircularReferences,
152
+ stringifyCircularReferences
153
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "circular-reference",
3
+ "version": "0.1.0",
4
+ "description": "Tiny util to stringify and parse circular references in objects.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "./dist/**/*"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup",
13
+ "example": "ts-node src/examples.ts",
14
+ "lint": "tsc",
15
+ "test": "ts-node src/index.test.ts",
16
+ "release": "npx changeset publish"
17
+ },
18
+ "keywords": [
19
+ "circular",
20
+ "reference"
21
+ ],
22
+ "author": "derRaab",
23
+ "license": "MIT",
24
+ "repository": {
25
+ "url": "https://github.com/derRaab/circular-reference-js"
26
+ },
27
+ "devDependencies": {
28
+ "ts-node": "^10.9.2",
29
+ "tsup": "^8.3.6",
30
+ "typescript": "^5.7.3"
31
+ }
32
+ }