@lopatnov/javascripttostring 1.7.2 → 2.0.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 CHANGED
@@ -177,7 +177,7 @@
177
177
 
178
178
  APPENDIX:
179
179
 
180
- Copyright 2019–2020 Oleksandr Lopatnov
180
+ Copyright 2019–2021 Oleksandr Lopatnov
181
181
 
182
182
  Licensed under the Apache License, Version 2.0 (the "License");
183
183
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -1,166 +1,259 @@
1
- # JavaScriptToString
1
+ # @lopatnov/javascripttostring
2
2
 
3
+ [![npm](https://img.shields.io/npm/dt/@lopatnov/javascripttostring)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
3
4
  [![NPM version](https://badge.fury.io/js/%40lopatnov%2Fjavascripttostring.svg)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
4
5
  [![License](https://img.shields.io/github/license/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
5
- [![Build Status](https://travis-ci.org/lopatnov/jsToString.png?branch=master)](https://travis-ci.org/lopatnov/jsToString)
6
- [![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)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)
7
+ [![GitHub stars](https://img.shields.io/github/stars/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/stargazers)
7
8
 
8
- JavaScript value to string runtime converter. It converts a runtime value into string a value.
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.
9
10
 
10
- ## Install
11
+ ## Installation
11
12
 
12
- [![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)
13
-
14
- ```shell
13
+ ```bash
15
14
  npm install @lopatnov/javascripttostring
16
15
  ```
17
16
 
18
- [Browser](//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js)
17
+ ### Browser (CDN)
19
18
 
20
19
  ```html
21
- <script src="//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js"></script>
20
+ <script src="https://unpkg.com/@lopatnov/javascripttostring"></script>
22
21
  ```
23
22
 
24
- ## Import package to the project
23
+ ## Usage
25
24
 
26
- ### TypeScript
25
+ ### ES Modules
27
26
 
28
27
  ```typescript
29
- import javaScriptToString from '@lopatnov/javascripttostring';
28
+ import javaScriptToString from "@lopatnov/javascripttostring";
30
29
  ```
31
30
 
32
- ### JavaScript
31
+ ### CommonJS
33
32
 
34
33
  ```javascript
35
- var javaScriptToString = require("@lopatnov/javascripttostring");
34
+ const javaScriptToString = require("@lopatnov/javascripttostring");
36
35
  ```
37
36
 
38
- ## Convert JavaScript values into string values
37
+ ### Browser (UMD)
39
38
 
40
- ```typescript
41
- javaScriptToString(value: any, options?: IJ2SOptions) => string
39
+ ```javascript
40
+ const javaScriptToString = window.javaScriptToString;
42
41
  ```
43
42
 
44
- where
43
+ ## API
45
44
 
46
- ```typescript
47
- interface IJ2SOptions {
48
- includeFunctionProperties?: boolean; // default true
49
- includeFunctionPrototype?: boolean; // default true
50
- includeBuffers?: boolean; // default true
51
- nestedObjectsAmount?: number; // default Number.POSITIVE_INFINITY
52
- nestedArraysAmount?: number; // default Number.POSITIVE_INFINITY
53
- nestedFunctionsAmount?: number; // default Number.POSITIVE_INFINITY
54
- }
55
- ```
45
+ ### javaScriptToString(value, options?): string
46
+
47
+ Converts a JavaScript value to its string source code representation.
48
+
49
+ | Parameter | Type | Description |
50
+ |-----------|------|-------------|
51
+ | `value` | `any` | The value to convert |
52
+ | `options` | `IJ2SOptions` | Optional configuration |
53
+
54
+ **Returns:** `string` - Source code representation that can be evaluated back to the original value
55
+
56
+ ### Options
57
+
58
+ | Option | Type | Default | Description |
59
+ |--------|------|---------|-------------|
60
+ | `includeFunctionProperties` | `boolean` | `true` | Include function's own properties |
61
+ | `includeFunctionPrototype` | `boolean` | `true` | Include function's prototype properties |
62
+ | `includeBuffers` | `boolean` | `true` | Include ArrayBuffer and TypedArray contents |
63
+ | `nestedObjectsAmount` | `number` | `Infinity` | Max depth for nested objects |
64
+ | `nestedArraysAmount` | `number` | `Infinity` | Max depth for nested arrays |
65
+ | `nestedFunctionsAmount` | `number` | `Infinity` | Max depth for nested functions |
66
+ | `throwOnNonSerializable` | `boolean` | `false` | Throw an error for non-serializable values (Promise, Generator, WeakRef, WeakMap, WeakSet, FinalizationRegistry) |
56
67
 
57
68
  ## Examples
58
69
 
70
+ ### Primitives
71
+
59
72
  ```typescript
60
- let myStringOfString = javaScriptToString('Hello world');
61
- console.log(myStringOfString);
62
- /* expected myStringOfString value: "\"Hello world\"" */
73
+ javaScriptToString("Hello world"); // '"Hello world"'
74
+ javaScriptToString(42); // '42'
75
+ javaScriptToString(true); // 'true'
76
+ javaScriptToString(undefined); // 'undefined'
77
+ javaScriptToString(null); // 'null'
63
78
  ```
64
79
 
80
+ ### Arrays
81
+
65
82
  ```typescript
66
- let myStringOfArray = javaScriptToString(["Hello", "World", ".", "How", "do", "you", "do", "?"]);
67
- console.log(myStringOfArray);
68
- /* expected myStringOfArray value: "[\"Hello\",\"World\",\".\",\"How\",\"do\",\"you\",\"do\",\"?\"]" */
83
+ javaScriptToString(["Hello", "World"]);
84
+ // '["Hello", "World"]'
69
85
  ```
70
86
 
87
+ ### Objects
88
+
71
89
  ```typescript
72
- let myObjectString = javaScriptToString({
73
- friend1: "Shurik",
74
- friend2: "Alex",
75
- friends: {
76
- friend3: 123456,
77
- friend4: {},
78
- friend5: ["Hola", "amigo"],
79
- friend6: () => {
80
- console.log("How you doing?");
81
- }
82
- }
90
+ javaScriptToString({
91
+ name: "Alex",
92
+ friends: ["Shurik", "Hola"],
93
+ greet: () => {
94
+ console.log("How you doing?");
95
+ }
83
96
  });
84
-
85
- console.log(myObjectString);
86
- /* expected myObjectString value:
87
- "{friend1: \"Shurik\",friend2: \"Alex\",friends: {friend3: 123456,friend4: {},friend5: [\"Hola\",\"amigo\"],friend6: () => {
88
- console.log(\"How you doing?\");
89
- }}}"
90
- */
97
+ // '{name: "Alex", friends: ["Shurik", "Hola"], greet: () => { console.log("How you doing?"); }}'
91
98
  ```
92
99
 
93
- ```typescript
94
- let myFunctionString = javaScriptToString(function(a,b) {
95
- console.log("Just a function");
96
- })
97
-
98
- console.log(myFunctionString);
99
- /* expected myFunctionString:
100
- "function(a,b) {
101
- console.log(\"Just a function\");
102
- }"
103
- */
104
- ```
100
+ ### Functions with Properties
105
101
 
106
102
  ```typescript
107
103
  function Simple(title) {
108
104
  this.title = title || "world";
109
105
  }
110
-
111
106
  Simple.count = 0;
112
-
113
- Simple.prototype.show = function(){
107
+ Simple.prototype.show = function () {
114
108
  Simple.count++;
115
- console.log('title = ', this.title);
116
- console.log('count = ', Simple.count);
117
- }
118
- console.log(javaScriptToString(Simple));
109
+ console.log("title =", this.title);
110
+ };
119
111
 
120
- /* Expected:
112
+ javaScriptToString(Simple);
113
+ // '(function(){ var Simple = function Simple(title) { ... }; Simple.count = 0; Simple.prototype.show = function(){ ... }; return Simple; }())'
114
+ ```
121
115
 
122
- "(function(){
123
- var Simple = function Simple(title) {
124
- this.title = title || \"world\";
125
- };
126
- Simple.count = 0;
116
+ ### Circular References
127
117
 
128
- Simple.prototype.show = function(){
129
- Simple.count++;
130
- console.log('title = ', this.title);
131
- console.log('count = ', Simple.count);
132
- };
118
+ Objects that reference themselves are fully supported:
133
119
 
134
- return Simple;
135
- }())"
120
+ ```typescript
121
+ var x = [1, 2, 3];
122
+ x[0] = x;
136
123
 
137
- */
124
+ javaScriptToString(x);
125
+ // '(function(){ var ___ref1 = [null, 2, 3]; ___ref1[0] = ___ref1; return ___ref1; }())'
138
126
  ```
139
127
 
140
- ```javascript
141
- var x = [1,2,3];
142
- x[0] = x;
143
- console.log(javaScriptToString(x));
128
+ ### Cross-References
129
+
130
+ Objects shared between different branches are preserved as references:
144
131
 
145
- /*
146
- "(function(){ var ___j2s_0 = [null, 2, 3]; ___j2s_0['0'] = ___j2s_0; return ___j2s_0; }())"
147
- */
132
+ ```typescript
133
+ var shared = { value: 42 };
134
+ var obj = { a: shared, b: shared };
135
+
136
+ javaScriptToString(obj);
137
+ // Generates code where obj.a === obj.b (same reference):
138
+ // (function(){ var ___ref1 = {
139
+ // a: { value: 42 },
140
+ // b: null
141
+ // }; ___ref1.b = ___ref1.a; return ___ref1; }())
142
+ ```
143
+
144
+ ### Using with Web Workers
145
+
146
+ 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:
147
+
148
+ ```typescript
149
+ import javaScriptToString from "@lopatnov/javascripttostring";
150
+ import workerFromString from "@lopatnov/worker-from-string";
151
+
152
+ // Function with attached lookup data
153
+ function classify(value) {
154
+ const range = classify.ranges.find(r => value >= r.min && value < r.max);
155
+ return range ? range.label : "unknown";
156
+ }
157
+ classify.ranges = [
158
+ { min: 0, max: 30, label: "cold" },
159
+ { min: 30, max: 60, label: "warm" },
160
+ { min: 60, max: 100, label: "hot" },
161
+ ];
162
+
163
+ // Serialize and send to a worker
164
+ // javaScriptToString preserves the function AND its properties:
165
+ const code = javaScriptToString(classify);
166
+
167
+ const worker = workerFromString(`
168
+ const classify = ${code};
169
+ self.onmessage = (e) => postMessage(classify(e.data));
170
+ `);
171
+
172
+ worker.onmessage = (e) => console.log(e.data);
173
+ worker.postMessage(45); // "warm"
174
+ ```
175
+
176
+ ### Restoring Values
177
+
178
+ The generated string can be evaluated back to a working JavaScript value:
179
+
180
+ ```typescript
181
+ var original = { name: "test" };
182
+ original.self = original;
183
+
184
+ var code = javaScriptToString(original);
185
+ var restored = Function("return " + code)();
186
+
187
+ console.log(restored.self === restored); // true
188
+ console.log(restored.name); // "test"
148
189
  ```
149
190
 
191
+ ## Supported Types
192
+
193
+ | Type | Example | Notes |
194
+ |------|---------|-------|
195
+ | Primitives | `string`, `number`, `boolean`, `undefined`, `null` | Including `-0` and `NaN` |
196
+ | BigInt | `BigInt(123)` | |
197
+ | Symbol | `Symbol("desc")`, `Symbol.for("key")` | Registry symbols preserved |
198
+ | RegExp | `/pattern/gi` | `lastIndex` preserved when non-zero |
199
+ | Date | `new Date("...")` | Invalid dates → `new Date(NaN)` |
200
+ | Error | `new Error()`, `new TypeError()` | TypeError, RangeError, ReferenceError, SyntaxError, URIError, EvalError |
201
+ | Array | `[1, 2, 3]` | Sparse arrays preserved |
202
+ | Object | `{ key: "value" }` | Including `Object.create(null)` |
203
+ | Function | `function() {}`, `() => {}`, `async function() {}` | Properties and prototype included |
204
+ | Generator Function | `function*() {}`, `async function*() {}` | |
205
+ | Map | `new Map([["key", "value"]])` | |
206
+ | Set | `new Set([1, 2, 3])` | |
207
+ | TypedArray | `Int8Array`, `Float64Array`, etc. | |
208
+ | ArrayBuffer | `new ArrayBuffer(8)`, `SharedArrayBuffer` | |
209
+ | DataView | `new DataView(buffer)` | |
210
+
211
+ ### Non-serializable Types
212
+
213
+ The following types cannot be serialized and return `"undefined"` by default. Use `throwOnNonSerializable: true` to throw an error instead:
214
+
215
+ `Promise`, `Generator`, `WeakRef`, `WeakMap`, `WeakSet`, `FinalizationRegistry`
216
+
150
217
  ## Demo
151
218
 
152
- See, how it's working: [https://runkit.com/lopatnov/javascripttostring-demo](https://runkit.com/lopatnov/javascripttostring-demo)
219
+ Try the library interactively:
220
+
221
+ | | Link |
222
+ |---|---|
223
+ | Interactive Demo | [demo/index.html](./demo/index.html) |
224
+ | RunKit Playground | [runkit.com](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring) |
225
+
226
+ ## Documentation
227
+
228
+ | | Link |
229
+ |---|---|
230
+ | API Reference | [docs/index.html](./docs/index.html) |
231
+ | Changelog | [CHANGELOG.md](./CHANGELOG.md) |
232
+
233
+ ## Related Packages
234
+
235
+ | Package | Description |
236
+ |---|---|
237
+ | [@lopatnov/worker-from-string](https://www.npmjs.com/package/@lopatnov/worker-from-string) | Create Web Workers from strings — pairs well with `javaScriptToString` |
238
+ | [@lopatnov/get-internal-type](https://www.npmjs.com/package/@lopatnov/get-internal-type) | Runtime type detection used internally by this library |
239
+
240
+ ## Contributing
241
+
242
+ Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
243
+
244
+ ## License
245
+
246
+ [Apache-2.0](LICENSE)
153
247
 
154
- Test it with a runkit: [https://npm.runkit.com/%40lopatnov%2Fjavascripttostring](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring)
248
+ Copyright 2019-2026 Oleksandr Lopatnov
155
249
 
156
- ## Changelog
250
+ ---
157
251
 
158
- | Version | Task |
159
- |--------:|:-----|
160
- | 1.7.0 | [Resolve references to parent elements and itself](https://github.com/lopatnov/jsToString/issues/1) |
252
+ ### Author
161
253
 
162
- ## Rights and Agreements
254
+ **Oleksandr Lopatnov**
163
255
 
164
- License [Apache-2.0](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
256
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=flat&logo=linkedin)](https://www.linkedin.com/in/lopatnov/)
257
+ [![GitHub](https://img.shields.io/badge/GitHub-Follow-black?style=flat&logo=github)](https://github.com/lopatnov)
165
258
 
166
- Copyright 2019–2020 Oleksandr Lopatnov
259
+ If you find this project useful, please consider giving it a star on GitHub!