@lopatnov/javascripttostring 1.7.3 → 2.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/README.md CHANGED
@@ -1,170 +1,272 @@
1
- # JavaScriptToString [![Twitter](https://img.shields.io/twitter/url?url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40lopatnov%2Fjavascripttostring)](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40lopatnov%2Fjavascripttostring)
2
-
3
- [![npm](https://img.shields.io/npm/dt/@lopatnov/javascripttostring)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
4
- [![NPM version](https://badge.fury.io/js/%40lopatnov%2Fjavascripttostring.svg)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
5
- [![License](https://img.shields.io/github/license/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
6
- [![GitHub issues](https://img.shields.io/github/issues/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/issues)
7
- [![GitHub forks](https://img.shields.io/github/forks/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/network)
8
- [![GitHub stars](https://img.shields.io/github/stars/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/stargazers)
9
- ![GitHub top language](https://img.shields.io/github/languages/top/lopatnov/jsToString)
10
-
11
- [![Patreon](https://img.shields.io/badge/Donate-Patreon-informational)](https://www.patreon.com/lopatnov)
12
- [![sobe.ru](https://img.shields.io/static/v1?label=sobe.ru&message=%D0%91%D0%BB%D0%B0%D0%B3%D0%BE%D0%B4%D0%B0%D1%80%D0%BD%D0%BE%D1%81%D1%82%D1%8C&color=yellow&logo=data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAArlBMVEUAAAD//////////////////////////////////////////////////////////////////PP/3l7/9c//0yb/zAD/6ZP/zQf/++7/3FD/88X/0h7//v7/5oX/zATUqQDktgD/5HjQpgAFBACQcwD/zw/fsgCOcQD6yADZrQD2xAD8yQDnuADxwADcsADbrwDpugD3xQD5xwDjtQDywQD+ywD9ygDvvwD7yAD/1jRaObVGAAAAEHRSTlMAA3zg707pEJP8MMUBYN5fiwXJMQAAAAFiS0dEAf8CLd4AAAAHdElNRQflBgMAAxO4O2jCAAAAuElEQVQoz42S1w7CMAxFS8ueYZgNLZuyRynw/z9GdtxIkbgPceQT6Tq2vZwfEKx8wRPyiaViSYDABqQsAMq0OzxUqhbo9kBcavUM6A9AAtJAYDgC0ID7i+t4AghwfxanszlAGBnA/Flc0MfL1doA5s/ChoLtbg8QI392gpIBzf/AwYAWAsdTrIE05/nz5Xq7S6DKpenHM0pe+o/qg5Am74/0ybTkm+q6wG4iltV2LTko52idy+Banx9RYiS6Vrsc3AAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMS0wNi0wM1QwMDowMzoxOCswMDowMLvSSCkAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjEtMDYtMDNUMDA6MDM6MTgrMDA6MDDKj/CVAAAAAElFTkSuQmCC)](https://sobe.ru/na/tech_knigi)
13
- [![LinkedIn](https://img.shields.io/badge/LinkedIn-lopatnov-informational?style=social&logo=linkedin)](https://www.linkedin.com/in/lopatnov/)
14
-
15
- [![Build Status](https://travis-ci.org/lopatnov/jsToString.png?branch=master)](https://travis-ci.org/lopatnov/jsToString)
16
-
17
- JavaScript value to string runtime converter. It converts a runtime value into string a value.
18
-
19
- ## Install
20
-
21
- [![https://nodei.co/npm/@lopatnov/javascripttostring.png?downloads=true&downloadRank=true&stars=true](https://nodei.co/npm/@lopatnov/javascripttostring.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
22
-
23
- ```shell
24
- npm install @lopatnov/javascripttostring
25
- ```
26
-
27
- [Browser](//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js)
28
-
29
- ```html
30
- <script src="//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js"></script>
31
- ```
32
-
33
- ## Import package to the project
34
-
35
- ### TypeScript
36
-
37
- ```typescript
38
- import javaScriptToString from '@lopatnov/javascripttostring';
39
- ```
40
-
41
- ### JavaScript
42
-
43
- ```javascript
44
- var javaScriptToString = require("@lopatnov/javascripttostring");
45
- ```
46
-
47
- ## Convert JavaScript values into string values
48
-
49
- ```typescript
50
- javaScriptToString(value: any, options?: IJ2SOptions) => string
51
- ```
52
-
53
- where
54
-
55
- ```typescript
56
- interface IJ2SOptions {
57
- includeFunctionProperties?: boolean; // default true
58
- includeFunctionPrototype?: boolean; // default true
59
- includeBuffers?: boolean; // default true
60
- nestedObjectsAmount?: number; // default Number.POSITIVE_INFINITY
61
- nestedArraysAmount?: number; // default Number.POSITIVE_INFINITY
62
- nestedFunctionsAmount?: number; // default Number.POSITIVE_INFINITY
63
- }
64
- ```
65
-
66
- ## Examples
67
-
68
- ```typescript
69
- let myStringOfString = javaScriptToString('Hello world');
70
- console.log(myStringOfString);
71
- /* expected myStringOfString value: "\"Hello world\"" */
72
- ```
73
-
74
- ```typescript
75
- let myStringOfArray = javaScriptToString(["Hello", "World", ".", "How", "do", "you", "do", "?"]);
76
- console.log(myStringOfArray);
77
- /* expected myStringOfArray value: "[\"Hello\",\"World\",\".\",\"How\",\"do\",\"you\",\"do\",\"?\"]" */
78
- ```
79
-
80
- ```typescript
81
- let myObjectString = javaScriptToString({
82
- friend1: "Shurik",
83
- friend2: "Alex",
84
- friends: {
85
- friend3: 123456,
86
- friend4: {},
87
- friend5: ["Hola", "amigo"],
88
- friend6: () => {
89
- console.log("How you doing?");
90
- }
91
- }
92
- });
93
-
94
- console.log(myObjectString);
95
- /* expected myObjectString value:
96
- "{friend1: \"Shurik\",friend2: \"Alex\",friends: {friend3: 123456,friend4: {},friend5: [\"Hola\",\"amigo\"],friend6: () => {
97
- console.log(\"How you doing?\");
98
- }}}"
99
- */
100
- ```
101
-
102
- ```typescript
103
- let myFunctionString = javaScriptToString(function(a,b) {
104
- console.log("Just a function");
105
- })
106
-
107
- console.log(myFunctionString);
108
- /* expected myFunctionString:
109
- "function(a,b) {
110
- console.log(\"Just a function\");
111
- }"
112
- */
113
- ```
114
-
115
- ```typescript
116
- function Simple(title) {
117
- this.title = title || "world";
118
- }
119
-
120
- Simple.count = 0;
121
-
122
- Simple.prototype.show = function(){
123
- Simple.count++;
124
- console.log('title = ', this.title);
125
- console.log('count = ', Simple.count);
126
- }
127
- console.log(javaScriptToString(Simple));
128
-
129
- /* Expected:
130
-
131
- "(function(){
132
- var Simple = function Simple(title) {
133
- this.title = title || \"world\";
134
- };
135
- Simple.count = 0;
136
-
137
- Simple.prototype.show = function(){
138
- Simple.count++;
139
- console.log('title = ', this.title);
140
- console.log('count = ', Simple.count);
141
- };
142
-
143
- return Simple;
144
- }())"
145
-
146
- */
147
- ```
148
-
149
- ```javascript
150
- var x = [1,2,3];
151
- x[0] = x;
152
- console.log(javaScriptToString(x));
153
-
154
- /*
155
- "(function(){ var ___j2s_0 = [null, 2, 3]; ___j2s_0['0'] = ___j2s_0; return ___j2s_0; }())"
156
- */
157
- ```
158
-
159
- ## Demo
160
-
161
- See, how it's working: [https://runkit.com/lopatnov/javascripttostring-demo](https://runkit.com/lopatnov/javascripttostring-demo)
162
-
163
- Test it with a runkit: [https://npm.runkit.com/%40lopatnov%2Fjavascripttostring](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring)
164
-
165
- ## Rights and Agreements
166
-
167
- License [Apache-2.0](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
168
-
169
- Copyright 2019–2021 Oleksandr Lopatnov
170
-
1
+ # @lopatnov/javascripttostring
2
+
3
+ [![npm](https://img.shields.io/npm/dt/@lopatnov/javascripttostring)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
4
+ [![NPM version](https://badge.fury.io/js/%40lopatnov%2Fjavascripttostring.svg)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
5
+ [![License](https://img.shields.io/github/license/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue)](https://www.typescriptlang.org/)
7
+ [![GitHub stars](https://img.shields.io/github/stars/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/stargazers)
8
+
9
+ A TypeScript library that converts any JavaScript runtime value into its string source code representation. Supports objects, arrays, functions, circular references, cross-references, and more.
10
+
11
+ ## Table of Contents
12
+
13
+ - [Installation](#installation)
14
+ - [Usage](#usage)
15
+ - [API](#api)
16
+ - [Examples](#examples)
17
+ - [Supported Types](#supported-types)
18
+ - [Demo](#demo)
19
+ - [Documentation](#documentation)
20
+ - [Related Packages](#related-packages)
21
+ - [Contributing](#contributing)
22
+ - [Built With](#built-with)
23
+ - [License](#license)
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ npm install @lopatnov/javascripttostring
29
+ ```
30
+
31
+ ### Browser (CDN)
32
+
33
+ ```html
34
+ <script src="https://unpkg.com/@lopatnov/javascripttostring/dist/javascripttostring.umd.js"></script>
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### ES Modules
40
+
41
+ ```typescript
42
+ import javaScriptToString from "@lopatnov/javascripttostring";
43
+ ```
44
+
45
+ ### CommonJS
46
+
47
+ ```javascript
48
+ const javaScriptToString = require("@lopatnov/javascripttostring");
49
+ ```
50
+
51
+ ### Browser (UMD)
52
+
53
+ ```javascript
54
+ const javaScriptToString = window.javaScriptToString;
55
+ ```
56
+
57
+ ## API
58
+
59
+ ### javaScriptToString(value, options?): string
60
+
61
+ Converts a JavaScript value to its string source code representation.
62
+
63
+ | Parameter | Type | Description |
64
+ |-----------|------|-------------|
65
+ | `value` | `any` | The value to convert |
66
+ | `options` | `IJ2SOptions` | Optional configuration |
67
+
68
+ **Returns:** `string` - Source code representation that can be evaluated back to the original value
69
+
70
+ ### Options
71
+
72
+ | Option | Type | Default | Description |
73
+ |--------|------|---------|-------------|
74
+ | `includeFunctionProperties` | `boolean` | `true` | Include function's own properties |
75
+ | `includeFunctionPrototype` | `boolean` | `true` | Include function's prototype properties |
76
+ | `includeBuffers` | `boolean` | `true` | Include ArrayBuffer and TypedArray contents |
77
+ | `nestedObjectsAmount` | `number` | `Infinity` | Max depth for nested objects |
78
+ | `nestedArraysAmount` | `number` | `Infinity` | Max depth for nested arrays |
79
+ | `nestedFunctionsAmount` | `number` | `Infinity` | Max depth for nested functions |
80
+ | `throwOnNonSerializable` | `boolean` | `false` | Throw an error for non-serializable values (Promise, Generator, WeakRef, WeakMap, WeakSet, FinalizationRegistry) |
81
+
82
+ ## Examples
83
+
84
+ ### Primitives
85
+
86
+ ```typescript
87
+ javaScriptToString("Hello world"); // '"Hello world"'
88
+ javaScriptToString(42); // '42'
89
+ javaScriptToString(true); // 'true'
90
+ javaScriptToString(undefined); // 'undefined'
91
+ javaScriptToString(null); // 'null'
92
+ ```
93
+
94
+ ### Arrays
95
+
96
+ ```typescript
97
+ javaScriptToString(["Hello", "World"]);
98
+ // '["Hello", "World"]'
99
+ ```
100
+
101
+ ### Objects
102
+
103
+ ```typescript
104
+ javaScriptToString({
105
+ name: "Alex",
106
+ friends: ["Shurik", "Hola"],
107
+ greet: () => {
108
+ console.log("How you doing?");
109
+ }
110
+ });
111
+ // '{name: "Alex", friends: ["Shurik", "Hola"], greet: () => { console.log("How you doing?"); }}'
112
+ ```
113
+
114
+ ### Functions with Properties
115
+
116
+ ```typescript
117
+ function Simple(title) {
118
+ this.title = title || "world";
119
+ }
120
+ Simple.count = 0;
121
+ Simple.prototype.show = function () {
122
+ Simple.count++;
123
+ console.log("title =", this.title);
124
+ };
125
+
126
+ javaScriptToString(Simple);
127
+ // '(function(){ var Simple = function Simple(title) { ... }; Simple.count = 0; Simple.prototype.show = function(){ ... }; return Simple; }())'
128
+ ```
129
+
130
+ ### Circular References
131
+
132
+ Objects that reference themselves are fully supported:
133
+
134
+ ```typescript
135
+ var x = [1, 2, 3];
136
+ x[0] = x;
137
+
138
+ javaScriptToString(x);
139
+ // '(function(){ var ___ref1 = [null, 2, 3]; ___ref1[0] = ___ref1; return ___ref1; }())'
140
+ ```
141
+
142
+ ### Cross-References
143
+
144
+ Objects shared between different branches are preserved as references:
145
+
146
+ ```typescript
147
+ var shared = { value: 42 };
148
+ var obj = { a: shared, b: shared };
149
+
150
+ javaScriptToString(obj);
151
+ // Generates code where obj.a === obj.b (same reference):
152
+ // (function(){ var ___ref1 = {
153
+ // a: { value: 42 },
154
+ // b: null
155
+ // }; ___ref1.b = ___ref1.a; return ___ref1; }())
156
+ ```
157
+
158
+ ### Using with Web Workers
159
+
160
+ Combine with [@lopatnov/worker-from-string](https://www.npmjs.com/package/@lopatnov/worker-from-string) to serialize functions and data for execution in a Web Worker:
161
+
162
+ ```typescript
163
+ import javaScriptToString from "@lopatnov/javascripttostring";
164
+ import workerFromString from "@lopatnov/worker-from-string";
165
+
166
+ // Function with attached lookup data
167
+ function classify(value) {
168
+ const range = classify.ranges.find(r => value >= r.min && value < r.max);
169
+ return range ? range.label : "unknown";
170
+ }
171
+ classify.ranges = [
172
+ { min: 0, max: 30, label: "cold" },
173
+ { min: 30, max: 60, label: "warm" },
174
+ { min: 60, max: 100, label: "hot" },
175
+ ];
176
+
177
+ // Serialize and send to a worker
178
+ // javaScriptToString preserves the function AND its properties:
179
+ const code = javaScriptToString(classify);
180
+
181
+ const worker = workerFromString(`
182
+ const classify = ${code};
183
+ self.onmessage = (e) => postMessage(classify(e.data));
184
+ `);
185
+
186
+ worker.onmessage = (e) => console.log(e.data);
187
+ worker.postMessage(45); // "warm"
188
+ ```
189
+
190
+ ### Restoring Values
191
+
192
+ The generated string can be evaluated back to a working JavaScript value:
193
+
194
+ ```typescript
195
+ var original = { name: "test" };
196
+ original.self = original;
197
+
198
+ var code = javaScriptToString(original);
199
+ var restored = Function("return " + code)();
200
+
201
+ console.log(restored.self === restored); // true
202
+ console.log(restored.name); // "test"
203
+ ```
204
+
205
+ ## Supported Types
206
+
207
+ | Type | Example | Notes |
208
+ |------|---------|-------|
209
+ | Primitives | `string`, `number`, `boolean`, `undefined`, `null` | Including `-0` and `NaN` |
210
+ | BigInt | `BigInt(123)` | |
211
+ | Symbol | `Symbol("desc")`, `Symbol.for("key")` | Registry symbols preserved |
212
+ | RegExp | `/pattern/gi` | `lastIndex` preserved when non-zero |
213
+ | Date | `new Date("...")` | Invalid dates → `new Date(NaN)` |
214
+ | Error | `new Error()`, `new TypeError()` | TypeError, RangeError, ReferenceError, SyntaxError, URIError, EvalError |
215
+ | Array | `[1, 2, 3]` | Sparse arrays preserved |
216
+ | Object | `{ key: "value" }` | Including `Object.create(null)` |
217
+ | Function | `function() {}`, `() => {}`, `async function() {}` | Properties and prototype included |
218
+ | Generator Function | `function*() {}`, `async function*() {}` | |
219
+ | Map | `new Map([["key", "value"]])` | |
220
+ | Set | `new Set([1, 2, 3])` | |
221
+ | TypedArray | `Int8Array`, `Float64Array`, etc. | |
222
+ | ArrayBuffer | `new ArrayBuffer(8)`, `SharedArrayBuffer` | |
223
+ | DataView | `new DataView(buffer)` | |
224
+
225
+ ### Non-serializable Types
226
+
227
+ The following types cannot be serialized and return `"undefined"` by default. Use `throwOnNonSerializable: true` to throw an error instead:
228
+
229
+ `Promise`, `Generator`, `WeakRef`, `WeakMap`, `WeakSet`, `FinalizationRegistry`
230
+
231
+ ## Demo
232
+
233
+ Try the library interactively:
234
+
235
+ - [Interactive Demo](./demo/index.html)
236
+ - [RunKit Playground](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring)
237
+
238
+ ## Documentation
239
+
240
+ - [API Reference](./docs/index.html)
241
+ - [Changelog](./CHANGELOG.md)
242
+
243
+ ## Related Packages
244
+
245
+ | Package | Description |
246
+ |---|---|
247
+ | [@lopatnov/worker-from-string](https://www.npmjs.com/package/@lopatnov/worker-from-string) | Create Web Workers from strings — pairs well with `javaScriptToString` |
248
+ | [@lopatnov/get-internal-type](https://www.npmjs.com/package/@lopatnov/get-internal-type) | Runtime type detection used internally by this library |
249
+
250
+ ## Contributing
251
+
252
+ Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
253
+
254
+ - Bug reports → [open an issue](https://github.com/lopatnov/jsToString/issues)
255
+ - Found it useful? A [star on GitHub](https://github.com/lopatnov/jsToString) helps others discover the project
256
+
257
+ ---
258
+
259
+ ## Built With
260
+
261
+ - [TypeScript](https://www.typescriptlang.org/) — strict typing throughout
262
+ - [Rollup](https://rollupjs.org/) — bundled to ESM, CJS, and UMD formats
263
+ - [Biome](https://biomejs.dev/) — linting and formatting
264
+ - [Vitest](https://vitest.dev/) — unit testing
265
+ - [TypeDoc](https://typedoc.org/) — API documentation generation
266
+ - [@lopatnov/get-internal-type](https://github.com/lopatnov/get-internal-type) — reliable runtime type detection
267
+
268
+ ---
269
+
270
+ ## License
271
+
272
+ [Apache-2.0](https://github.com/lopatnov/jsToString/blob/master/LICENSE) © 2019–2026 [Oleksandr Lopatnov](https://github.com/lopatnov) · [LinkedIn](https://www.linkedin.com/in/lopatnov/)