resurrect-esm 2.0.5 → 2.0.6

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.
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "cSpell.words": [
3
3
  "kybernetikos",
4
+ "minifiers",
4
5
  "registrator",
5
6
  "skeeto"
6
7
  ]
package/README.md CHANGED
@@ -5,11 +5,11 @@ An ES6 module port of ResurrectTS.
5
5
  > [!CAUTION]
6
6
  > This is *not* just a naive `exports.foo` => `export {foo}` rewrite. Some API changes have been made:
7
7
  >
8
- > * All of the "irrelevant" methods of Resurrect have been renamed using private names (that are then mangled further by esbuild).
9
- > * ResurrectError is now a top-level export, instead of living inside a Resurrect object.
10
- > * NamespaceResolver is now a top-level export, instead of living inside the Resurrect static constructor namespace.
11
- > * NamespaceResolver now has a new method, `getConstructor(name: string)`, which should return the constructor function to generate the object (it will not be called directly, so the parameters are irrelevant).
12
- > * The bug found in skeeto/resurrect-js#11 has been fixed.
8
+ > * All of the "irrelevant" methods of Resurrect have been renamed using private `#names`.
9
+ > * `ResurrectError` is now a top-level export, instead of living inside a `Resurrect` object.
10
+ > * `NamespaceResolver` is now a top-level export, instead of living inside the `Resurrect` static constructor namespace.
11
+ > * `NamespaceResolver` now has a new method, `getConstructor(name: string)`, which should return the constructor function to generate the object (the constructor itself will not be called directly, so the parameters are irrelevant).
12
+ > * The bug found in [skeeto/resurrect-js#11][issue11] has been fixed.
13
13
 
14
14
  ResurrectJS preserves object behavior (prototypes) and reference
15
15
  circularity with a special JSON encoding. Unlike flat JSON, it can
@@ -62,30 +62,13 @@ const date = necromancer.resurrect(json);
62
62
  Options are provided to the constructor as an object with these
63
63
  properties:
64
64
 
65
- * *prefix* (`"#"`): A prefix string used for temporary properties added
66
- to objects during serialization and deserialization. It is
67
- important that you don't use any properties beginning with this
68
- string. This option must be consistent between both serialization
69
- and deserialization.
65
+ * *prefix* (default: `"#"`): A prefix string used for temporary properties added to objects during serialization and deserialization. It is important that you don't use any properties beginning with this string. This option also must be the same between both serialization and deserialization.
70
66
 
71
- * *cleanup* (`false`): Perform full property cleanup after both
72
- serialization and deserialization using the `delete` operator.
73
- This may cause performance penalties (i.e. breaking hidden
74
- classes in V8) on objects that ResurrectJS touches, so enable
75
- with care.
67
+ * *cleanup* (default: false): Perform full property cleanup after both serialization and deserialization using the `delete` operator. This may cause performance penalties (i.e. breaking hidden classes and forcing de-optimization) on objects that Resurrect touches, so enable with care.
76
68
 
77
- * *revive* (`true`): Restore behavior (`__proto__`) to objects that
78
- have been resurrected. If this is set to false during
79
- serialization, resurrection information will not be encoded. You
80
- still get circularity and Date support.
69
+ * *revive* (default: true): Restore behavior (`__proto__`) to objects that have been resurrected. If this is set to false during serialization, resurrection information will not be encoded. You still get circularity and Date/HTML/URL support.
81
70
 
82
- * *resolver* (`NamespaceResolver`): Converts between a name
83
- and a prototype. Create a custom resolver if your constructors
84
- are not stored in global variables. The resolver has three methods:
85
- getName(object), getConstructor(string), and getPrototype(string).
86
-
87
- > [!CAUTION]
88
- > If you're using ES6 modules for your custom classes, you MUST use a custom resolver since module scope is not global scope!
71
+ * *resolver* (`NamespaceResolver`, default undefined): Converts between a name and a prototype. Create a custom resolver if your constructors are not stored in global variables. The resolver has three methods: `getName(object)`, `getConstructor(string)`, and `getPrototype(string)`.
89
72
 
90
73
  For example,
91
74
 
@@ -99,66 +82,51 @@ const necromancer = new Resurrect({
99
82
 
100
83
  ## Methods
101
84
 
102
- Only two methods are significant when using ResurrectJS.
85
+ There are only two public methods:
103
86
 
104
- * `.stringify(object[, replacer[, space]])`: Serializes an arbitrary
105
- object or value into a string. The `replacer` and `space`
106
- arguments are the same as [JSON.stringify][json-mdn], being
107
- passed through to this method. Note that the replacer will *not*
108
- be called for ResurrectJS's intrusive keys.
87
+ * `.stringify(object[, replacer[, space]])`: Serializes an arbitrary object or value into a string. The `replacer` and `space` arguments are the same as [JSON.stringify][json-mdn], being passed through to this method. Note that the replacer will *not* be called for Resurrect's intrusive keys (i.e. the ones that are created using the `.prefix` option).
109
88
 
110
- * `.resurrect(string)`: Deserializes an object stored in a string by
111
- a previous call to `.stringify()`. Circularity and, optionally,
112
- behavior (prototype chain) will be restored.
89
+ * `.resurrect(string)`: Deserializes an object stored in a string by a previous call to `.stringify()`. Circularity and, optionally, behavior (prototype chain) will be restored.
113
90
 
114
91
  ## Restrictions
115
92
 
116
- With the default resolver, all constructors must be named and stored
117
- in the global variable under that name. This is required so that the
118
- prototypes can be looked up and reconnected at resurrection time.
93
+ With the default resolver, all constructors must be named and stored in the global scope under that name. This is required so that the prototypes can be looked up and reconnected at resurrection time.
94
+
95
+ > [!CAUTION]
96
+ > If you're using ES6 modules for your custom classes, you MUST use a custom resolver since module scope is not global scope!
119
97
 
120
- The wrapper objects Boolean, String, and Number will be
121
- unwrapped. This means extra properties added to these objects will not
122
- be preserved.
98
+ The wrapper objects Boolean, String, and Number will be unwrapped. This means extra properties added to these objects will not be preserved.
123
99
 
124
- Functions cannot ever be serialized. Resurrect will throw an error if
125
- a function is found when traversing a data structure, rather than just silently dropping the property or replacing it with `null` like JSON.stringify does.
100
+ Functions cannot ever be serialized. Resurrect will throw an error if a function is found when traversing a data structure, rather than just silently dropping the property or replacing it with `null` like JSON.stringify does.
126
101
 
127
102
  ### Custom Resolvers
128
103
 
129
- There is a caveat with the provided resolver, NamespaceResolver: all
130
- constructors *must* be explicitly named when defined. For example, see
131
- the Foo constructor in this example,
104
+ New in 2.0.5: the NamespaceResolver will now use the name on the namespace object of whatever you pass in instead of the `.name` of the object's constructor. This is to better support minifiers that rename the class and produce code output similar to this:
132
105
 
133
106
  ```ts
134
- import { Resurrect, NamespaceResolver } from "resurrect-esm";
135
- const namespace = {
136
- Foo: class Foo {
137
- constructor() {
138
- this.bar = true;
139
- Foo.bax(this);
140
- }
141
- static bax(obj) {
142
-
143
- }
107
+ import { Resurrect as r, NamespaceResolver as e } from "resurrect-esm";
108
+ var c = class d {
109
+ constructor() {
110
+ this.bar = true;
111
+ d.bax(this);
112
+ }
113
+ static bax(obj) {
114
+
144
115
  }
145
116
  };
146
- const necromancer = new Resurrect({
147
- resolver: new NamespaceResolver(namespace)
117
+ var n = {
118
+ Foo: c, // <== Always uses name given here
119
+ };
120
+ var a = new r({
121
+ resolver: new e(n)
148
122
  });
149
123
  ```
150
124
 
151
- The constructor been assigned to the Foo property *and* the function
152
- itself has been given a matching name. This is how the resolver will
153
- find the name of the constructor in the namespace when given the
154
- constructor. Keep in mind that using this form will bind the variable
155
- Foo to the surrounding function within the body of Foo.
156
-
157
- If you're using a bundler, you **must** enable the "keep names" option
158
- for at least the classes that will be stringified, so that Resurrect.js can get the correct `.name` from the constructor functions. (For esbuild, the option is `--keep-names`.)
125
+ In the serializer above, the "name" given to the class will always be "Foo", even though the `.name` of the constructor is "c" and might be different on the next build.
159
126
 
160
127
  ## See Also
161
128
 
162
129
  * [HydrateJS](https://github.com/nanodeath/HydrateJS)
163
130
 
164
131
  [json-mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
132
+ [issue11]: https://github.com/skeeto/resurrect-js/issues/11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resurrect-esm",
3
- "version": "2.0.5",
3
+ "version": "2.0.6",
4
4
  "type": "module",
5
5
  "description": "ResurrectJS preserves object behavior (prototypes) and reference circularity with a special JSON encoding. Unlike flat JSON, it can also properly resurrect self-referential objects, objects with shared structure, Dates, RegExps, HTMLElements, NaN, Infinity, undefined (which won't get turned into null), and any other custom object type given the proper resolver.",
6
6
  "repository": {
@@ -20,7 +20,7 @@
20
20
  "url": "https://github.com/dragoncoder047"
21
21
  }
22
22
  ],
23
- "license": "UNLICENSE",
23
+ "license": "CC0-1.0",
24
24
  "bugs": {
25
25
  "url": "https://github.com/dragoncoder047/resurrect-esm/issues"
26
26
  },
@@ -37,7 +37,7 @@
37
37
  "build": "pnpm esbuild --sourcemap --platform=browser --target=esnext --format=esm resurrect.ts --outfile=resurrect.js",
38
38
  "test": "pnpm bun test",
39
39
  "test:watch": "pnpm test --watch",
40
- "prepare": "pnpm build --minify --mangle-props=^_"
40
+ "prepare": "pnpm build --minify"
41
41
  },
42
42
  "dependencies": {
43
43
  "lib0": "^0.2.117"
package/resurrect.test.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { GlobalRegistrator } from "@happy-dom/global-registrator";
2
2
  import { describe, expect, test } from "bun:test";
3
- import { NamespaceResolver, Resurrect, ResurrectError, ResurrectOptions } from "./resurrect";
3
+ import { FakeNode, NamespaceResolver, Resurrect, ResurrectError, ResurrectOptions } from "./resurrect";
4
4
 
5
5
  GlobalRegistrator.register();
6
6
 
@@ -55,7 +55,7 @@ function suite(opt?: ResurrectOptions) {
55
55
  });
56
56
 
57
57
  test("serialization with DOM elements", () => {
58
- const obj = new Resurrect.Node("<span id=foo><a id=1></a></span>");
58
+ const obj = new FakeNode("<span id=foo><a id=1></a></span>");
59
59
  const roundtripped = roundtrip(obj);
60
60
  expect(roundtripped).toBeInstanceOf(HTMLSpanElement);
61
61
  expect(roundtripped.firstChild).toBeInstanceOf(HTMLAnchorElement);
package/resurrect.ts CHANGED
@@ -1,77 +1,7 @@
1
1
  /**
2
- * # ResurrectJS
3
- * @version 1.0.3
4
- * @license Public Domain
5
- *
6
- * ResurrectJS preserves object behavior (prototypes) and reference
7
- * circularity with a special JSON encoding. Unlike regular JSON,
8
- * Date, URL, RegExp, DOM objects, and `undefined` are also properly
9
- * preserved.
10
- *
11
- * ## Examples
12
- *
13
- * function Foo() {}
14
- * Foo.prototype.greet = function() { return "hello"; };
15
- *
16
- * // Behavior is preserved:
17
- * const necromancer = new Resurrect();
18
- * const json = necromancer.stringify(new Foo());
19
- * const foo = necromancer.resurrect(json);
20
- * foo.greet(); // => "hello"
21
- *
22
- * // References to the same object are preserved:
23
- * json = necromancer.stringify([foo, foo]);
24
- * const array = necromancer.resurrect(json);
25
- * array[0] === array[1]; // => true
26
- * array[1].greet(); // => "hello"
27
- *
28
- * // Dates are restored properly
29
- * json = necromancer.stringify(new Date());
30
- * const date = necromancer.resurrect(json);
31
- * Object.prototype.toString.call(date); // => "[object Date]"
32
- *
33
- * ## Options
34
- *
35
- * Options are provided to the constructor as an object with these
36
- * properties:
37
- *
38
- * prefix ('#'): A prefix string used for temporary properties added
39
- * to objects during serialization and deserialization. It is
40
- * important that you don't use any properties beginning with this
41
- * string. This option must be consistent between both
42
- * serialization and deserialization.
43
- *
44
- * revive (true): Restore behavior (__proto__) to objects that have
45
- * been resurrected. If this is set to false during serialization,
46
- * resurrection information will not be encoded. You still get
47
- * circularity and Date/URL support.
48
- *
49
- * resolver (Resurrect.NamespaceResolver(window)): Converts between
50
- * a name and a prototype. Create a custom resolver if your
51
- * constructors are not stored in global variables. The resolver
52
- * has three methods: getName(object), getConstructor(string), and
53
- * getPrototype(string).
54
- *
55
- * For example,
56
- *
57
- * const necromancer = new Resurrect({
58
- * prefix: "__#",
59
- * });
60
- *
61
- * ## Caveats
62
- *
63
- * * With the default resolver, all constructors must be named and
64
- * stored in the global variable under that name. This is required
65
- * so that the prototypes can be looked up and reconnected at
66
- * resurrection time.
67
- *
68
- * * The wrapper objects Boolean, String, and Number will be
69
- * unwrapped. This means extra properties added to these objects
70
- * will not be preserved.
71
- *
72
- * * Functions cannot ever be serialized. Resurrect will throw an
73
- * error if a function is found when traversing a data structure.
74
- *
2
+ * resurrect-esm, a fork of resurrect-ts, which is in turn a fork of resurrect.js
3
+ * @version 2.0.6
4
+ * @license CC0
75
5
  * @see http://nullprogram.com/blog/2013/03/28/
76
6
  */
77
7
 
@@ -79,105 +9,107 @@ import { parse, stringify } from "lib0/json";
79
9
  import { keys } from "lib0/object";
80
10
 
81
11
  const getPrototypeOf = Object.getPrototypeOf;
12
+ const getOwnPropertyNames = Object.getOwnPropertyNames;
13
+ const create = Object.create;
14
+ /**
15
+ * Portable access to the global object (window, global).
16
+ * Uses indirect eval.
17
+ * @constant
18
+ */
19
+ const GLOBAL: typeof globalThis = globalThis ?? (0, eval)("this");
20
+
21
+ /**
22
+ * Escape special regular expression characters in a string.
23
+ * Uses `RegExp.escape` if available, otherwise falls back to http://stackoverflow.com/a/6969486.
24
+ * @param {string} string
25
+ * @returns {string} The string escaped for exact matches.
26
+ */
27
+ const escapeRegExp = RegExp.escape ?? ((string: string) => string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
28
+
29
+ function is(type: string) {
30
+ const string = `[object ${type}]`;
31
+ return (obj: any) => {
32
+ return {}.toString.call(obj) === string;
33
+ };
34
+ }
35
+
36
+ const isArray = is("Array") as (obj: any) => obj is any[];
37
+ const isString = is("String") as (obj: any) => obj is string;
38
+ const isBoolean = is("Boolean") as (obj: any) => obj is boolean;
39
+ const isNumber = is("Number") as (obj: any) => obj is number;
40
+ const isFunction = is("Function") as (obj: any) => obj is Function;
41
+ const isDate = is("Date") as (obj: any) => obj is Date;
42
+ const isURL = is("URL") as (obj: any) => obj is URL;
43
+ const isRegExp = is("RegExp") as (obj: any) => obj is RegExp;
44
+ const isObject = is("Object") as (obj: any) => obj is object;
45
+ function isAtom(object: any) {
46
+ return !isObject(object) && !isArray(object);
47
+ }
48
+ function isPrimitive(object: any) {
49
+ return object == null ||
50
+ isNumber(object) ||
51
+ isString(object) ||
52
+ isBoolean(object);
53
+ }
54
+
55
+ /**
56
+ * Create a DOM node from HTML source; behaves like a constructor.
57
+ */
58
+ export const FakeNode = class {
59
+ constructor(html: string) {
60
+ const div = document.createElement("a");
61
+ div.innerHTML = html;
62
+ return div.firstChild as HTMLElement;
63
+ }
64
+ } as new (x: string) => HTMLElement;
65
+
82
66
 
83
67
  export class Resurrect {
84
- private _table: any[] | null;
85
- private _cleanups: (() => void)[] = [];
68
+ #table: any[] | null;
69
+ #cleanups: (() => void)[] = [];
86
70
  prefix: string;
87
71
  cleanup: boolean;
88
72
  revive: boolean;
89
- get _refcode() { return this.prefix + "#" };
90
- get _backrefcode() { return this.prefix + "=" };
91
- get _protocode() { return this.prefix + "+" };
92
- get _origcode() { return this.prefix + "&" };
93
- get _buildcode() { return this.prefix + "@" };
94
- get _valuecode() { return this.prefix + "_" };
73
+ get #refcode() { return this.prefix + "#" };
74
+ get #backrefcode() { return this.prefix + "=" };
75
+ get #protocode() { return this.prefix + "+" };
76
+ get #origcode() { return this.prefix + "&" };
77
+ get #buildcode() { return this.prefix + "@" };
78
+ get #valuecode() { return this.prefix + "_" };
95
79
  resolver: NamespaceResolver;
96
80
  constructor(opt: ResurrectOptions = {}) {
97
- this._table = null;
81
+ this.#table = null;
98
82
  this.prefix = opt.prefix ?? "#";
99
83
  this.cleanup = opt.cleanup ?? false;
100
84
  this.revive = opt.revive ?? true;
101
- this.resolver = opt.resolver ?? new NamespaceResolver(Resurrect.GLOBAL as any);
102
- }
103
-
104
- /**
105
- * Portable access to the global object (window, global).
106
- * Uses indirect eval.
107
- * @constant
108
- */
109
- static readonly GLOBAL: typeof globalThis = globalThis ?? (0, eval)("this");
110
-
111
- /**
112
- * Escape special regular expression characters in a string.
113
- * Uses `RegExp.escape` if available, otherwise falls back to http://stackoverflow.com/a/6969486.
114
- * @param {string} string
115
- * @returns {string} The string escaped for exact matches.
116
- */
117
- private static _escapeRegExp = RegExp.escape ?? ((string: string) => string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
118
-
119
- /**
120
- * Create a DOM node from HTML source; behaves like a constructor.
121
- */
122
- static Node = class {
123
- constructor(html: string) {
124
- const div = document.createElement("a");
125
- div.innerHTML = html;
126
- return div.firstChild as HTMLElement;
127
- }
128
- } as new (x: string) => HTMLElement;
129
-
130
- private static _is(type: string) {
131
- const string = `[object ${type}]`;
132
- return (obj: any) => {
133
- return {}.toString.call(obj) === string;
134
- };
135
- }
136
-
137
- private static _isArray = Resurrect._is("Array") as (obj: any) => obj is any[];
138
- private static _isString = Resurrect._is("String") as (obj: any) => obj is string;
139
- private static _isBoolean = Resurrect._is("Boolean") as (obj: any) => obj is boolean;
140
- private static _isNumber = Resurrect._is("Number") as (obj: any) => obj is number;
141
- private static _isFunction = Resurrect._is("Function") as (obj: any) => obj is Function;
142
- private static _isDate = Resurrect._is("Date") as (obj: any) => obj is Date;
143
- private static _isURL = Resurrect._is("URL") as (obj: any) => obj is URL;
144
- private static _isRegExp = Resurrect._is("RegExp") as (obj: any) => obj is RegExp;
145
- private static _isObject = Resurrect._is("Object") as (obj: any) => obj is object;
146
- private static _isAtom(object: any) {
147
- return !Resurrect._isObject(object) && !Resurrect._isArray(object);
148
- }
149
- private static _isPrimitive(object: any) {
150
- return object == null ||
151
- Resurrect._isNumber(object) ||
152
- Resurrect._isString(object) ||
153
- Resurrect._isBoolean(object);
85
+ this.resolver = opt.resolver ?? new NamespaceResolver(GLOBAL as any);
154
86
  }
155
87
 
156
- private _cleanup() {
157
- this._cleanups.forEach(e => e());
158
- this._cleanups = [];
88
+ #cleanup() {
89
+ this.#cleanups.forEach(e => e());
90
+ this.#cleanups = [];
159
91
  }
160
92
 
161
93
  /**
162
94
  * Create a reference (encoding) to an object.
163
95
  */
164
- private _ref(object: any) {
96
+ #reference(object: any) {
165
97
  return {
166
- [this._backrefcode]: object === undefined ? -1 : object[this._refcode],
98
+ [this.#backrefcode]: object === undefined ? -1 : object[this.#refcode],
167
99
  };
168
100
  }
169
101
 
170
102
  /**
171
103
  * Lookup an object in the table by reference object.
172
104
  */
173
- private _deref(ref: any) {
174
- return this._table![ref[this._backrefcode]];
105
+ #dereference(ref: any) {
106
+ return this.#table![ref[this.#backrefcode]];
175
107
  }
176
108
 
177
109
  /**
178
110
  * Put a temporary identifier on an object and store it in the table.
179
111
  */
180
- private _tag(object: any): number {
112
+ #tagObject(object: any): number {
181
113
  if (this.revive) {
182
114
  const constructor = this.resolver.getName(object);
183
115
  if (constructor) {
@@ -185,25 +117,25 @@ export class Resurrect {
185
117
  if (this.resolver.getPrototype(constructor) !== proto) {
186
118
  throw new ResurrectError("Constructor mismatch!");
187
119
  } else {
188
- object[this._protocode] = constructor;
189
- this._cleanups.push(() => delete object[this._protocode]);
120
+ object[this.#protocode] = constructor;
121
+ this.#cleanups.push(() => delete object[this.#protocode]);
190
122
  }
191
123
  }
192
124
  }
193
- object[this._refcode] = this._table!.length;
194
- this._cleanups.push(() => delete object[this._refcode]);
195
- this._table!.push(object);
196
- return object[this._refcode];
125
+ object[this.#refcode] = this.#table!.length;
126
+ this.#cleanups.push(() => delete object[this.#refcode]);
127
+ this.#table!.push(object);
128
+ return object[this.#refcode];
197
129
  }
198
130
 
199
131
  /**
200
132
  * Create a builder object (encoding) for serialization.
201
133
  * @param value The value to pass to the constructor.
202
134
  */
203
- private _builder(name: string, value: any): object {
135
+ #createBuilderObject(name: string, value: any): object {
204
136
  return {
205
- [this._buildcode]: name,
206
- [this._valuecode]: value
137
+ [this.#buildcode]: name,
138
+ [this.#valuecode]: value
207
139
  };
208
140
  }
209
141
 
@@ -212,11 +144,11 @@ export class Resurrect {
212
144
  * @see http://stackoverflow.com/a/14378462
213
145
  * @see http://nullprogram.com/blog/2013/03/24/
214
146
  */
215
- private _build(ref: any): any {
216
- const type = this.resolver.getConstructor(ref[this._buildcode]);
147
+ #buildFromEncoding(ref: any): any {
148
+ const type = this.resolver.getConstructor(ref[this.#buildcode]);
217
149
  /* Brilliant hack by kybernetikos: */
218
- const result: any = new (type.bind.apply(type, [null].concat(ref[this._valuecode]) as [any, any[]]))();
219
- if (Resurrect._isPrimitive(result)) {
150
+ const result: any = new (type.bind.apply(type, [null].concat(ref[this.#valuecode]) as [any, any[]]))();
151
+ if (isPrimitive(result)) {
220
152
  return result.valueOf(); // unwrap
221
153
  } else {
222
154
  return result;
@@ -227,11 +159,11 @@ export class Resurrect {
227
159
  * Dereference or build an object or value from an encoding.
228
160
  * @method
229
161
  */
230
- private _decode(ref: object): object | undefined {
231
- if (this._backrefcode in ref) {
232
- return this._deref(ref);
233
- } else if (this._buildcode in ref) {
234
- return this._build(ref);
162
+ #decodeReference(ref: object): object | undefined {
163
+ if (this.#backrefcode in ref) {
164
+ return this.#dereference(ref);
165
+ } else if (this.#buildcode in ref) {
166
+ return this.#buildFromEncoding(ref);
235
167
  } else {
236
168
  throw new ResurrectError("Unknown encoding.");
237
169
  }
@@ -240,8 +172,8 @@ export class Resurrect {
240
172
  /**
241
173
  * @returns {boolean} True if the provided object is tagged for serialization.
242
174
  */
243
- private _isTagged(object: any): boolean {
244
- return (this._refcode in object) && (object[this._refcode] != null);
175
+ #isTagged(object: any): boolean {
176
+ return (this.#refcode in object) && (object[this.#refcode] != null);
245
177
  }
246
178
 
247
179
 
@@ -249,58 +181,58 @@ export class Resurrect {
249
181
  * Visit root and all its ancestors, visiting atoms with f.
250
182
  * @returns A fresh copy of root to be serialized.
251
183
  */
252
- private _visit(root: any, transform: (obj: any) => any, replacer?: (k: string, v: any) => any): any {
253
- if (Resurrect._isAtom(root)) {
184
+ #visit(root: any, transform: (obj: any) => any, replacer?: (k: string, v: any) => any): any {
185
+ if (isAtom(root)) {
254
186
  return transform(root);
255
- } else if (!this._isTagged(root)) {
187
+ } else if (!this.#isTagged(root)) {
256
188
  let copy: any = null;
257
- if (Resurrect._isArray(root)) {
189
+ if (isArray(root)) {
258
190
  copy = [];
259
- root[this._refcode as any] = this._tag(copy);
260
- this._cleanups.push(() => delete root[this._refcode as any]);
191
+ root[this.#refcode as any] = this.#tagObject(copy);
192
+ this.#cleanups.push(() => delete root[this.#refcode as any]);
261
193
  for (let i = 0; i < root.length; i++) {
262
- copy.push(this._visit(root[i], transform, replacer));
194
+ copy.push(this.#visit(root[i], transform, replacer));
263
195
  }
264
196
  } else { /* Object */
265
- copy = Object.create(getPrototypeOf(root));
266
- root[this._refcode as any] = this._tag(copy);
267
- this._cleanups.push(() => delete root[this._refcode]);
268
- for (const key of Object.getOwnPropertyNames(root)) {
197
+ copy = create(getPrototypeOf(root));
198
+ root[this.#refcode as any] = this.#tagObject(copy);
199
+ this.#cleanups.push(() => delete root[this.#refcode]);
200
+ for (const key of getOwnPropertyNames(root)) {
269
201
  let value = root[key];
270
202
  if (replacer && value !== undefined) {
271
203
  // Call replacer like JSON.stringify's replacer
272
204
  value = replacer.call(root, key, root[key]);
273
205
  if (value === undefined) continue; // Omit from result
274
206
  }
275
- copy[key] = this._visit(value, transform, replacer);
207
+ copy[key] = this.#visit(value, transform, replacer);
276
208
  }
277
209
  }
278
- copy[this._origcode] = root;
279
- return this._ref(copy);
210
+ copy[this.#origcode] = root;
211
+ return this.#reference(copy);
280
212
  } else {
281
- return this._ref(root);
213
+ return this.#reference(root);
282
214
  }
283
215
  }
284
216
 
285
217
  /**
286
218
  * Manage special atom values, possibly returning an encoding.
287
219
  */
288
- private _handleAtom(atom: any): any {
289
- const Node = Resurrect.GLOBAL.Node || function () { };
290
- if (Resurrect._isFunction(atom)) {
220
+ #encodeAtom(atom: any): any {
221
+ const Node = GLOBAL.Node || function () { };
222
+ if (isFunction(atom)) {
291
223
  throw new ResurrectError("Can't serialize functions.");
292
224
  } else if (atom instanceof Node) {
293
- return this._builder("Resurrect.Node", [new XMLSerializer().serializeToString(atom)]);
294
- } else if (Resurrect._isDate(atom)) {
295
- return this._builder("Date", [atom.toISOString()]);
296
- } else if (Resurrect._isURL(atom)) {
297
- return this._builder("URL", [atom.href]);
298
- } else if (Resurrect._isRegExp(atom)) {
299
- return this._builder("RegExp", ("" + atom).match(/\/(.+)\/([a-z]*)/)!.slice(1));
225
+ return this.#createBuilderObject("Resurrect.Node", [new XMLSerializer().serializeToString(atom)]);
226
+ } else if (isDate(atom)) {
227
+ return this.#createBuilderObject("Date", [atom.toISOString()]);
228
+ } else if (isURL(atom)) {
229
+ return this.#createBuilderObject("URL", [atom.href]);
230
+ } else if (isRegExp(atom)) {
231
+ return this.#createBuilderObject("RegExp", ("" + atom).match(/\/(.+)\/([a-z]*)/)!.slice(1));
300
232
  } else if (atom === undefined) {
301
- return this._ref(undefined);
302
- } else if (Resurrect._isNumber(atom) && (isNaN(atom) || !isFinite(atom))) {
303
- return this._builder("Number", ["" + atom]);
233
+ return this.#reference(undefined);
234
+ } else if (isNumber(atom) && (isNaN(atom) || !isFinite(atom))) {
235
+ return this.#createBuilderObject("Number", ["" + atom]);
304
236
  } else {
305
237
  return atom;
306
238
  }
@@ -310,8 +242,8 @@ export class Resurrect {
310
242
  * Hides intrusive keys from a user-supplied replacer.
311
243
  * @method
312
244
  */
313
- private _replacerWrapper<K extends string, V, U>(replacer: (k: K, v: V) => U): (k: K, v: V) => U | V {
314
- const skip = new RegExp("^" + Resurrect._escapeRegExp(this.prefix));
245
+ #replacerWrapper<K extends string, V, U>(replacer: (k: K, v: V) => U): (k: K, v: V) => U | V {
246
+ const skip = new RegExp("^" + escapeRegExp(this.prefix));
315
247
  return (k, v) => {
316
248
  if (skip.test(k)) {
317
249
  return v;
@@ -325,37 +257,37 @@ export class Resurrect {
325
257
  * Serialize an arbitrary JavaScript object, carefully preserving it.
326
258
  */
327
259
  stringify(object: any, replacer?: any[] | ((k: string, v: any) => any), space?: string | number) {
328
- if (Resurrect._isFunction(replacer)) {
329
- replacer = this._replacerWrapper(replacer);
330
- } else if (Resurrect._isArray(replacer)) {
260
+ if (isFunction(replacer)) {
261
+ replacer = this.#replacerWrapper(replacer);
262
+ } else if (isArray(replacer)) {
331
263
  const acceptKeys = replacer;
332
264
  replacer = (k, v) => acceptKeys.includes(k) ? v : undefined;
333
265
  }
334
- if (Resurrect._isAtom(object)) {
335
- return stringify(this._handleAtom(object), replacer, space);
266
+ if (isAtom(object)) {
267
+ return stringify(this.#encodeAtom(object), replacer, space);
336
268
  } else {
337
- this._cleanups = [];
338
- const table = this._table = [] as any[];
269
+ this.#cleanups = [];
270
+ const table = this.#table = [] as any[];
339
271
  try {
340
- this._visit(object, this._handleAtom.bind(this), replacer);
272
+ this.#visit(object, this.#encodeAtom.bind(this), replacer);
341
273
  } catch (e) {
342
- this._cleanup();
274
+ this.#cleanup();
343
275
  throw e;
344
276
  } finally {
345
277
  for (let i = 0; i < table.length; i++) {
346
278
  if (this.cleanup) {
347
- delete table[i]?.[this._origcode]?.[this._refcode];
279
+ delete table[i]?.[this.#origcode]?.[this.#refcode];
348
280
  } else {
349
- const obj = table[i]?.[this._origcode];
350
- if (obj) obj[this._refcode] = null;
281
+ const obj = table[i]?.[this.#origcode];
282
+ if (obj) obj[this.#refcode] = null;
351
283
  }
352
- delete table[i]?.[this._refcode];
353
- delete table[i]?.[this._origcode];
284
+ delete table[i]?.[this.#refcode];
285
+ delete table[i]?.[this.#origcode];
354
286
  }
355
- this._table = null;
287
+ this.#table = null;
356
288
  }
357
289
  const s = stringify(table, null, space);
358
- if (this.cleanup) this._cleanup();
290
+ if (this.cleanup) this.#cleanup();
359
291
  return s;
360
292
  }
361
293
  }
@@ -364,21 +296,21 @@ export class Resurrect {
364
296
  * Restore the `__proto__` of the given object to the proper value.
365
297
  * @method
366
298
  */
367
- private _fixPrototype<T extends object>(object: T): T {
368
- if (this._protocode in object) {
369
- const name = (object as any)[this._protocode];
299
+ #fixPrototype<T extends object>(object: T): T {
300
+ if (this.#protocode in object) {
301
+ const name = (object as any)[this.#protocode];
370
302
  const prototype = this.resolver.getPrototype(name);
371
303
  if ("__proto__" in object) {
372
304
  object.__proto__ = prototype;
373
305
  if (this.cleanup) {
374
- delete (object as any)[this._protocode];
306
+ delete (object as any)[this.#protocode];
375
307
  }
376
308
  return object;
377
309
  }
378
- // IE
379
- const copy = Object.create(prototype);
380
- for (const key of Object.getOwnPropertyNames(object)) {
381
- if (key !== this._protocode) {
310
+ // IE. Who uses this anyway...
311
+ const copy = create(prototype);
312
+ for (const key of getOwnPropertyNames(object)) {
313
+ if (key !== this.#protocode) {
382
314
  copy[key] = (object as any)[key];
383
315
  }
384
316
  }
@@ -394,32 +326,32 @@ export class Resurrect {
394
326
  let result = null;
395
327
  const data = parse(string);
396
328
  try {
397
- if (Resurrect._isArray(data)) {
398
- this._table = data;
329
+ if (isArray(data)) {
330
+ this.#table = data;
399
331
  /* Restore __proto__. */
400
332
  if (this.revive) {
401
- for (let i = 0; i < this._table.length; i++) {
402
- this._table[i] = this._fixPrototype(this._table[i]);
333
+ for (let i = 0; i < this.#table.length; i++) {
334
+ this.#table[i] = this.#fixPrototype(this.#table[i]);
403
335
  }
404
336
  }
405
337
  /* Re-establish object references and construct atoms. */
406
- for (let i = 0; i < this._table.length; i++) {
407
- const object = this._table[i];
408
- for (const key of Object.getOwnPropertyNames(object)) {
409
- if (!(Resurrect._isAtom(object[key]))) {
410
- object[key] = this._decode(object[key]);
338
+ for (let i = 0; i < this.#table.length; i++) {
339
+ const object = this.#table[i];
340
+ for (const key of getOwnPropertyNames(object)) {
341
+ if (!(isAtom(object[key]))) {
342
+ object[key] = this.#decodeReference(object[key]);
411
343
  }
412
344
  }
413
345
  }
414
- result = this._table[0];
415
- } else if (Resurrect._isObject(data)) {
416
- this._table = [];
417
- result = this._decode(data);
346
+ result = this.#table[0];
347
+ } else if (isObject(data)) {
348
+ this.#table = [];
349
+ result = this.#decodeReference(data);
418
350
  } else {
419
351
  result = data;
420
352
  }
421
353
  } finally {
422
- this._table = null;
354
+ this.#table = null;
423
355
  }
424
356
  return result;
425
357
  }
@@ -506,8 +438,8 @@ export class NamespaceResolver {
506
438
  * object's constructor isn't in the namespace.
507
439
  */
508
440
  getConstructor(name: string): new (...args: any[]) => any {
509
- return (name === "Resurrect.Node" ? Resurrect.Node : this.scope[name] ?? name.split(/\./).reduce((object, name) => {
441
+ return (name === "Resurrect.Node" ? FakeNode : this.scope[name] ?? name.split(/\./).reduce((object, name) => {
510
442
  return (object as any)[name];
511
- }, Resurrect.GLOBAL)) as unknown as new () => any;
443
+ }, GLOBAL)) as unknown as new () => any;
512
444
  }
513
445
  }
package/tsconfig.json CHANGED
@@ -14,6 +14,9 @@
14
14
  "lib": [
15
15
  "esnext",
16
16
  "dom",
17
+ ],
18
+ "types": [
19
+ "bun",
17
20
  ]
18
21
  }
19
22
  }