ObjectMiddleware.js 19.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
*/

"use strict";

const createHash = require("../util/createHash");
const ArraySerializer = require("./ArraySerializer");
const DateObjectSerializer = require("./DateObjectSerializer");
const ErrorObjectSerializer = require("./ErrorObjectSerializer");
const MapObjectSerializer = require("./MapObjectSerializer");
const NullPrototypeObjectSerializer = require("./NullPrototypeObjectSerializer");
const PlainObjectSerializer = require("./PlainObjectSerializer");
const RegExpObjectSerializer = require("./RegExpObjectSerializer");
const SerializerMiddleware = require("./SerializerMiddleware");
const SetObjectSerializer = require("./SetObjectSerializer");

/** @typedef {typeof import("../util/Hash")} Hash */
/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */
/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */

/** @typedef {new (...params: any[]) => any} Constructor */

/*

Format:

File -> Section*
Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection

ObjectSection -> ESCAPE (
	number:relativeOffset (number > 0) |
	string:request (string|null):export
) Section:value* ESCAPE ESCAPE_END_OBJECT
ReferenceSection -> ESCAPE number:relativeOffset (number < 0)
EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE)
EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE)
OtherSection -> any (except ESCAPE)

Why using null as escape value?
Multiple null values can merged by the BinaryMiddleware, which makes it very efficient
Technically any value can be used.

*/

/**
 * @typedef {Object} ObjectSerializerContext
 * @property {function(any): void} write
 */

/**
 * @typedef {Object} ObjectDeserializerContext
 * @property {function(): any} read
 */

/**
 * @typedef {Object} ObjectSerializer
 * @property {function(any, ObjectSerializerContext): void} serialize
 * @property {function(ObjectDeserializerContext): any} deserialize
 */

const setSetSize = (set, size) => {
	let i = 0;
	for (const item of set) {
		if (i++ >= size) {
			set.delete(item);
		}
	}
};

const setMapSize = (map, size) => {
	let i = 0;
	for (const item of map.keys()) {
		if (i++ >= size) {
			map.delete(item);
		}
	}
};

/**
 * @param {Buffer} buffer buffer
 * @param {string | Hash} hashFunction hash function to use
 * @returns {string} hash
 */
const toHash = (buffer, hashFunction) => {
	const hash = createHash(hashFunction);
	hash.update(buffer);
	return /** @type {string} */ (hash.digest("latin1"));
};

const ESCAPE = null;
const ESCAPE_ESCAPE_VALUE = null;
const ESCAPE_END_OBJECT = true;
const ESCAPE_UNDEFINED = false;

const CURRENT_VERSION = 2;

const serializers = new Map();
const serializerInversed = new Map();

const loadedRequests = new Set();

const NOT_SERIALIZABLE = {};

const jsTypes = new Map();
jsTypes.set(Object, new PlainObjectSerializer());
jsTypes.set(Array, new ArraySerializer());
jsTypes.set(null, new NullPrototypeObjectSerializer());
jsTypes.set(Map, new MapObjectSerializer());
jsTypes.set(Set, new SetObjectSerializer());
jsTypes.set(Date, new DateObjectSerializer());
jsTypes.set(RegExp, new RegExpObjectSerializer());
jsTypes.set(Error, new ErrorObjectSerializer(Error));
jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError));
jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError));
jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError));
jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError));
jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError));

// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers
// real Object and Array types to. These types may occur in the wild too, e. g. when
// using Structured Clone in postMessage.
if (exports.constructor !== Object) {
	const Obj = /** @type {typeof Object} */ (exports.constructor);
	const Fn = /** @type {typeof Function} */ (Obj.constructor);
	for (const [type, config] of Array.from(jsTypes)) {
		if (type) {
			const Type = new Fn(`return ${type.name};`)();
			jsTypes.set(Type, config);
		}
	}
}

{
	let i = 1;
	for (const [type, serializer] of jsTypes) {
		serializers.set(type, {
			request: "",
			name: i++,
			serializer
		});
	}
}

for (const { request, name, serializer } of serializers.values()) {
	serializerInversed.set(`${request}/${name}`, serializer);
}

/** @type {Map<RegExp, (request: string) => boolean>} */
const loaders = new Map();

/**
 * @typedef {ComplexSerializableType[]} DeserializedType
 * @typedef {PrimitiveSerializableType[]} SerializedType
 * @extends {SerializerMiddleware<DeserializedType, SerializedType>}
 */
class ObjectMiddleware extends SerializerMiddleware {
	/**
	 * @param {function(any): void} extendContext context extensions
	 * @param {string | Hash} hashFunction hash function to use
	 */
	constructor(extendContext, hashFunction = "md4") {
		super();
		this.extendContext = extendContext;
		this._hashFunction = hashFunction;
	}
	/**
	 * @param {RegExp} regExp RegExp for which the request is tested
	 * @param {function(string): boolean} loader loader to load the request, returns true when successful
	 * @returns {void}
	 */
	static registerLoader(regExp, loader) {
		loaders.set(regExp, loader);
	}

	/**
	 * @param {Constructor} Constructor the constructor
	 * @param {string} request the request which will be required when deserializing
	 * @param {string} name the name to make multiple serializer unique when sharing a request
	 * @param {ObjectSerializer} serializer the serializer
	 * @returns {void}
	 */
	static register(Constructor, request, name, serializer) {
		const key = request + "/" + name;

		if (serializers.has(Constructor)) {
			throw new Error(
				`ObjectMiddleware.register: serializer for ${Constructor.name} is already registered`
			);
		}

		if (serializerInversed.has(key)) {
			throw new Error(
				`ObjectMiddleware.register: serializer for ${key} is already registered`
			);
		}

		serializers.set(Constructor, {
			request,
			name,
			serializer
		});

		serializerInversed.set(key, serializer);
	}

	/**
	 * @param {Constructor} Constructor the constructor
	 * @returns {void}
	 */
	static registerNotSerializable(Constructor) {
		if (serializers.has(Constructor)) {
			throw new Error(
				`ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered`
			);
		}

		serializers.set(Constructor, NOT_SERIALIZABLE);
	}

	static getSerializerFor(object) {
		const proto = Object.getPrototypeOf(object);
		let c;
		if (proto === null) {
			// Object created with Object.create(null)
			c = null;
		} else {
			c = proto.constructor;
			if (!c) {
				throw new Error(
					"Serialization of objects with prototype without valid constructor property not possible"
				);
			}
		}
		const config = serializers.get(c);

		if (!config) throw new Error(`No serializer registered for ${c.name}`);
		if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE;

		return config;
	}

	static getDeserializerFor(request, name) {
		const key = request + "/" + name;
		const serializer = serializerInversed.get(key);

		if (serializer === undefined) {
			throw new Error(`No deserializer registered for ${key}`);
		}

		return serializer;
	}

	static _getDeserializerForWithoutError(request, name) {
		const key = request + "/" + name;
		const serializer = serializerInversed.get(key);
		return serializer;
	}

	/**
	 * @param {DeserializedType} data data
	 * @param {Object} context context object
	 * @returns {SerializedType|Promise<SerializedType>} serialized data
	 */
	serialize(data, context) {
		/** @type {any[]} */
		let result = [CURRENT_VERSION];
		let currentPos = 0;
		let referenceable = new Map();
		const addReferenceable = item => {
			referenceable.set(item, currentPos++);
		};
		let bufferDedupeMap = new Map();
		const dedupeBuffer = buf => {
			const len = buf.length;
			const entry = bufferDedupeMap.get(len);
			if (entry === undefined) {
				bufferDedupeMap.set(len, buf);
				return buf;
			}
			if (Buffer.isBuffer(entry)) {
				if (len < 32) {
					if (buf.equals(entry)) {
						return entry;
					}
					bufferDedupeMap.set(len, [entry, buf]);
					return buf;
				} else {
					const hash = toHash(entry, this._hashFunction);
					const newMap = new Map();
					newMap.set(hash, entry);
					bufferDedupeMap.set(len, newMap);
					const hashBuf = toHash(buf, this._hashFunction);
					if (hash === hashBuf) {
						return entry;
					}
					return buf;
				}
			} else if (Array.isArray(entry)) {
				if (entry.length < 16) {
					for (const item of entry) {
						if (buf.equals(item)) {
							return item;
						}
					}
					entry.push(buf);
					return buf;
				} else {
					const newMap = new Map();
					const hash = toHash(buf, this._hashFunction);
					let found;
					for (const item of entry) {
						const itemHash = toHash(item, this._hashFunction);
						newMap.set(itemHash, item);
						if (found === undefined && itemHash === hash) found = item;
					}
					bufferDedupeMap.set(len, newMap);
					if (found === undefined) {
						newMap.set(hash, buf);
						return buf;
					} else {
						return found;
					}
				}
			} else {
				const hash = toHash(buf, this._hashFunction);
				const item = entry.get(hash);
				if (item !== undefined) {
					return item;
				}
				entry.set(hash, buf);
				return buf;
			}
		};
		let currentPosTypeLookup = 0;
		let objectTypeLookup = new Map();
		const cycleStack = new Set();
		const stackToString = item => {
			const arr = Array.from(cycleStack);
			arr.push(item);
			return arr
				.map(item => {
					if (typeof item === "string") {
						if (item.length > 100) {
							return `String ${JSON.stringify(item.slice(0, 100)).slice(
								0,
								-1
							)}..."`;
						}
						return `String ${JSON.stringify(item)}`;
					}
					try {
						const { request, name } = ObjectMiddleware.getSerializerFor(item);
						if (request) {
							return `${request}${name ? `.${name}` : ""}`;
						}
					} catch (e) {
						// ignore -> fallback
					}
					if (typeof item === "object" && item !== null) {
						if (item.constructor) {
							if (item.constructor === Object)
								return `Object { ${Object.keys(item).join(", ")} }`;
							if (item.constructor === Map) return `Map { ${item.size} items }`;
							if (item.constructor === Array)
								return `Array { ${item.length} items }`;
							if (item.constructor === Set) return `Set { ${item.size} items }`;
							if (item.constructor === RegExp) return item.toString();
							return `${item.constructor.name}`;
						}
						return `Object [null prototype] { ${Object.keys(item).join(
							", "
						)} }`;
					}
					try {
						return `${item}`;
					} catch (e) {
						return `(${e.message})`;
					}
				})
				.join(" -> ");
		};
		let hasDebugInfoAttached;
		let ctx = {
			write(value, key) {
				try {
					process(value);
				} catch (e) {
					if (e !== NOT_SERIALIZABLE) {
						if (hasDebugInfoAttached === undefined)
							hasDebugInfoAttached = new WeakSet();
						if (!hasDebugInfoAttached.has(e)) {
							e.message += `\nwhile serializing ${stackToString(value)}`;
							hasDebugInfoAttached.add(e);
						}
					}
					throw e;
				}
			},
			setCircularReference(ref) {
				addReferenceable(ref);
			},
			snapshot() {
				return {
					length: result.length,
					cycleStackSize: cycleStack.size,
					referenceableSize: referenceable.size,
					currentPos,
					objectTypeLookupSize: objectTypeLookup.size,
					currentPosTypeLookup
				};
			},
			rollback(snapshot) {
				result.length = snapshot.length;
				setSetSize(cycleStack, snapshot.cycleStackSize);
				setMapSize(referenceable, snapshot.referenceableSize);
				currentPos = snapshot.currentPos;
				setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize);
				currentPosTypeLookup = snapshot.currentPosTypeLookup;
			},
			...context
		};
		this.extendContext(ctx);
		const process = item => {
			if (Buffer.isBuffer(item)) {
				// check if we can emit a reference
				const ref = referenceable.get(item);
				if (ref !== undefined) {
					result.push(ESCAPE, ref - currentPos);
					return;
				}
				const alreadyUsedBuffer = dedupeBuffer(item);
				if (alreadyUsedBuffer !== item) {
					const ref = referenceable.get(alreadyUsedBuffer);
					if (ref !== undefined) {
						referenceable.set(item, ref);
						result.push(ESCAPE, ref - currentPos);
						return;
					}
					item = alreadyUsedBuffer;
				}
				addReferenceable(item);

				result.push(item);
			} else if (item === ESCAPE) {
				result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);
			} else if (
				typeof item === "object"
				// We don't have to check for null as ESCAPE is null and this has been checked before
			) {
				// check if we can emit a reference
				const ref = referenceable.get(item);
				if (ref !== undefined) {
					result.push(ESCAPE, ref - currentPos);
					return;
				}

				if (cycleStack.has(item)) {
					throw new Error(
						`This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.`
					);
				}

				const { request, name, serializer } =
					ObjectMiddleware.getSerializerFor(item);
				const key = `${request}/${name}`;
				const lastIndex = objectTypeLookup.get(key);

				if (lastIndex === undefined) {
					objectTypeLookup.set(key, currentPosTypeLookup++);

					result.push(ESCAPE, request, name);
				} else {
					result.push(ESCAPE, currentPosTypeLookup - lastIndex);
				}

				cycleStack.add(item);

				try {
					serializer.serialize(item, ctx);
				} finally {
					cycleStack.delete(item);
				}

				result.push(ESCAPE, ESCAPE_END_OBJECT);

				addReferenceable(item);
			} else if (typeof item === "string") {
				if (item.length > 1) {
					// short strings are shorter when not emitting a reference (this saves 1 byte per empty string)
					// check if we can emit a reference
					const ref = referenceable.get(item);
					if (ref !== undefined) {
						result.push(ESCAPE, ref - currentPos);
						return;
					}
					addReferenceable(item);
				}

				if (item.length > 102400 && context.logger) {
					context.logger.warn(
						`Serializing big strings (${Math.round(
							item.length / 1024
						)}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)`
					);
				}

				result.push(item);
			} else if (typeof item === "function") {
				if (!SerializerMiddleware.isLazy(item))
					throw new Error("Unexpected function " + item);
				/** @type {SerializedType} */
				const serializedData =
					SerializerMiddleware.getLazySerializedValue(item);
				if (serializedData !== undefined) {
					if (typeof serializedData === "function") {
						result.push(serializedData);
					} else {
						throw new Error("Not implemented");
					}
				} else if (SerializerMiddleware.isLazy(item, this)) {
					throw new Error("Not implemented");
				} else {
					const data = SerializerMiddleware.serializeLazy(item, data =>
						this.serialize([data], context)
					);
					SerializerMiddleware.setLazySerializedValue(item, data);
					result.push(data);
				}
			} else if (item === undefined) {
				result.push(ESCAPE, ESCAPE_UNDEFINED);
			} else {
				result.push(item);
			}
		};

		try {
			for (const item of data) {
				process(item);
			}
			return result;
		} catch (e) {
			if (e === NOT_SERIALIZABLE) return null;

			throw e;
		} finally {
			// Get rid of these references to avoid leaking memory
			// This happens because the optimized code v8 generates
			// is optimized for our "ctx.write" method so it will reference
			// it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write
			data =
				result =
				referenceable =
				bufferDedupeMap =
				objectTypeLookup =
				ctx =
					undefined;
		}
	}

	/**
	 * @param {SerializedType} data data
	 * @param {Object} context context object
	 * @returns {DeserializedType|Promise<DeserializedType>} deserialized data
	 */
	deserialize(data, context) {
		let currentDataPos = 0;
		const read = () => {
			if (currentDataPos >= data.length)
				throw new Error("Unexpected end of stream");

			return data[currentDataPos++];
		};

		if (read() !== CURRENT_VERSION)
			throw new Error("Version mismatch, serializer changed");

		let currentPos = 0;
		let referenceable = [];
		const addReferenceable = item => {
			referenceable.push(item);
			currentPos++;
		};
		let currentPosTypeLookup = 0;
		let objectTypeLookup = [];
		let result = [];
		let ctx = {
			read() {
				return decodeValue();
			},
			setCircularReference(ref) {
				addReferenceable(ref);
			},
			...context
		};
		this.extendContext(ctx);
		const decodeValue = () => {
			const item = read();

			if (item === ESCAPE) {
				const nextItem = read();

				if (nextItem === ESCAPE_ESCAPE_VALUE) {
					return ESCAPE;
				} else if (nextItem === ESCAPE_UNDEFINED) {
					return undefined;
				} else if (nextItem === ESCAPE_END_OBJECT) {
					throw new Error(
						`Unexpected end of object at position ${currentDataPos - 1}`
					);
				} else {
					const request = nextItem;
					let serializer;

					if (typeof request === "number") {
						if (request < 0) {
							// relative reference
							return referenceable[currentPos + request];
						}
						serializer = objectTypeLookup[currentPosTypeLookup - request];
					} else {
						if (typeof request !== "string") {
							throw new Error(
								`Unexpected type (${typeof request}) of request ` +
									`at position ${currentDataPos - 1}`
							);
						}
						const name = read();

						serializer = ObjectMiddleware._getDeserializerForWithoutError(
							request,
							name
						);

						if (serializer === undefined) {
							if (request && !loadedRequests.has(request)) {
								let loaded = false;
								for (const [regExp, loader] of loaders) {
									if (regExp.test(request)) {
										if (loader(request)) {
											loaded = true;
											break;
										}
									}
								}
								if (!loaded) {
									require(request);
								}

								loadedRequests.add(request);
							}

							serializer = ObjectMiddleware.getDeserializerFor(request, name);
						}

						objectTypeLookup.push(serializer);
						currentPosTypeLookup++;
					}
					try {
						const item = serializer.deserialize(ctx);
						const end1 = read();

						if (end1 !== ESCAPE) {
							throw new Error("Expected end of object");
						}

						const end2 = read();

						if (end2 !== ESCAPE_END_OBJECT) {
							throw new Error("Expected end of object");
						}

						addReferenceable(item);

						return item;
					} catch (err) {
						// As this is only for error handling, we omit creating a Map for
						// faster access to this information, as this would affect performance
						// in the good case
						let serializerEntry;
						for (const entry of serializers) {
							if (entry[1].serializer === serializer) {
								serializerEntry = entry;
								break;
							}
						}
						const name = !serializerEntry
							? "unknown"
							: !serializerEntry[1].request
							? serializerEntry[0].name
							: serializerEntry[1].name
							? `${serializerEntry[1].request} ${serializerEntry[1].name}`
							: serializerEntry[1].request;
						err.message += `\n(during deserialization of ${name})`;
						throw err;
					}
				}
			} else if (typeof item === "string") {
				if (item.length > 1) {
					addReferenceable(item);
				}

				return item;
			} else if (Buffer.isBuffer(item)) {
				addReferenceable(item);

				return item;
			} else if (typeof item === "function") {
				return SerializerMiddleware.deserializeLazy(
					item,
					data => this.deserialize(data, context)[0]
				);
			} else {
				return item;
			}
		};

		try {
			while (currentDataPos < data.length) {
				result.push(decodeValue());
			}
			return result;
		} finally {
			// Get rid of these references to avoid leaking memory
			// This happens because the optimized code v8 generates
			// is optimized for our "ctx.read" method so it will reference
			// it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read
			result = referenceable = data = objectTypeLookup = ctx = undefined;
		}
	}
}

module.exports = ObjectMiddleware;
module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE;