ObjectMiddleware.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const createHash = require("../util/createHash");
  6. const ArraySerializer = require("./ArraySerializer");
  7. const DateObjectSerializer = require("./DateObjectSerializer");
  8. const ErrorObjectSerializer = require("./ErrorObjectSerializer");
  9. const MapObjectSerializer = require("./MapObjectSerializer");
  10. const NullPrototypeObjectSerializer = require("./NullPrototypeObjectSerializer");
  11. const PlainObjectSerializer = require("./PlainObjectSerializer");
  12. const RegExpObjectSerializer = require("./RegExpObjectSerializer");
  13. const SerializerMiddleware = require("./SerializerMiddleware");
  14. const SetObjectSerializer = require("./SetObjectSerializer");
  15. /** @typedef {typeof import("../util/Hash")} Hash */
  16. /** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */
  17. /** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */
  18. /** @typedef {new (...params: any[]) => any} Constructor */
  19. /*
  20. Format:
  21. File -> Section*
  22. Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection
  23. ObjectSection -> ESCAPE (
  24. number:relativeOffset (number > 0) |
  25. string:request (string|null):export
  26. ) Section:value* ESCAPE ESCAPE_END_OBJECT
  27. ReferenceSection -> ESCAPE number:relativeOffset (number < 0)
  28. EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE)
  29. EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE)
  30. OtherSection -> any (except ESCAPE)
  31. Why using null as escape value?
  32. Multiple null values can merged by the BinaryMiddleware, which makes it very efficient
  33. Technically any value can be used.
  34. */
  35. /**
  36. * @typedef {Object} ObjectSerializerContext
  37. * @property {function(any): void} write
  38. */
  39. /**
  40. * @typedef {Object} ObjectDeserializerContext
  41. * @property {function(): any} read
  42. */
  43. /**
  44. * @typedef {Object} ObjectSerializer
  45. * @property {function(any, ObjectSerializerContext): void} serialize
  46. * @property {function(ObjectDeserializerContext): any} deserialize
  47. */
  48. const setSetSize = (set, size) => {
  49. let i = 0;
  50. for (const item of set) {
  51. if (i++ >= size) {
  52. set.delete(item);
  53. }
  54. }
  55. };
  56. const setMapSize = (map, size) => {
  57. let i = 0;
  58. for (const item of map.keys()) {
  59. if (i++ >= size) {
  60. map.delete(item);
  61. }
  62. }
  63. };
  64. /**
  65. * @param {Buffer} buffer buffer
  66. * @param {string | Hash} hashFunction hash function to use
  67. * @returns {string} hash
  68. */
  69. const toHash = (buffer, hashFunction) => {
  70. const hash = createHash(hashFunction);
  71. hash.update(buffer);
  72. return /** @type {string} */ (hash.digest("latin1"));
  73. };
  74. const ESCAPE = null;
  75. const ESCAPE_ESCAPE_VALUE = null;
  76. const ESCAPE_END_OBJECT = true;
  77. const ESCAPE_UNDEFINED = false;
  78. const CURRENT_VERSION = 2;
  79. const serializers = new Map();
  80. const serializerInversed = new Map();
  81. const loadedRequests = new Set();
  82. const NOT_SERIALIZABLE = {};
  83. const jsTypes = new Map();
  84. jsTypes.set(Object, new PlainObjectSerializer());
  85. jsTypes.set(Array, new ArraySerializer());
  86. jsTypes.set(null, new NullPrototypeObjectSerializer());
  87. jsTypes.set(Map, new MapObjectSerializer());
  88. jsTypes.set(Set, new SetObjectSerializer());
  89. jsTypes.set(Date, new DateObjectSerializer());
  90. jsTypes.set(RegExp, new RegExpObjectSerializer());
  91. jsTypes.set(Error, new ErrorObjectSerializer(Error));
  92. jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError));
  93. jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError));
  94. jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError));
  95. jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError));
  96. jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError));
  97. // If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers
  98. // real Object and Array types to. These types may occur in the wild too, e. g. when
  99. // using Structured Clone in postMessage.
  100. if (exports.constructor !== Object) {
  101. const Obj = /** @type {typeof Object} */ (exports.constructor);
  102. const Fn = /** @type {typeof Function} */ (Obj.constructor);
  103. for (const [type, config] of Array.from(jsTypes)) {
  104. if (type) {
  105. const Type = new Fn(`return ${type.name};`)();
  106. jsTypes.set(Type, config);
  107. }
  108. }
  109. }
  110. {
  111. let i = 1;
  112. for (const [type, serializer] of jsTypes) {
  113. serializers.set(type, {
  114. request: "",
  115. name: i++,
  116. serializer
  117. });
  118. }
  119. }
  120. for (const { request, name, serializer } of serializers.values()) {
  121. serializerInversed.set(`${request}/${name}`, serializer);
  122. }
  123. /** @type {Map<RegExp, (request: string) => boolean>} */
  124. const loaders = new Map();
  125. /**
  126. * @typedef {ComplexSerializableType[]} DeserializedType
  127. * @typedef {PrimitiveSerializableType[]} SerializedType
  128. * @extends {SerializerMiddleware<DeserializedType, SerializedType>}
  129. */
  130. class ObjectMiddleware extends SerializerMiddleware {
  131. /**
  132. * @param {function(any): void} extendContext context extensions
  133. * @param {string | Hash} hashFunction hash function to use
  134. */
  135. constructor(extendContext, hashFunction = "md4") {
  136. super();
  137. this.extendContext = extendContext;
  138. this._hashFunction = hashFunction;
  139. }
  140. /**
  141. * @param {RegExp} regExp RegExp for which the request is tested
  142. * @param {function(string): boolean} loader loader to load the request, returns true when successful
  143. * @returns {void}
  144. */
  145. static registerLoader(regExp, loader) {
  146. loaders.set(regExp, loader);
  147. }
  148. /**
  149. * @param {Constructor} Constructor the constructor
  150. * @param {string} request the request which will be required when deserializing
  151. * @param {string} name the name to make multiple serializer unique when sharing a request
  152. * @param {ObjectSerializer} serializer the serializer
  153. * @returns {void}
  154. */
  155. static register(Constructor, request, name, serializer) {
  156. const key = request + "/" + name;
  157. if (serializers.has(Constructor)) {
  158. throw new Error(
  159. `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered`
  160. );
  161. }
  162. if (serializerInversed.has(key)) {
  163. throw new Error(
  164. `ObjectMiddleware.register: serializer for ${key} is already registered`
  165. );
  166. }
  167. serializers.set(Constructor, {
  168. request,
  169. name,
  170. serializer
  171. });
  172. serializerInversed.set(key, serializer);
  173. }
  174. /**
  175. * @param {Constructor} Constructor the constructor
  176. * @returns {void}
  177. */
  178. static registerNotSerializable(Constructor) {
  179. if (serializers.has(Constructor)) {
  180. throw new Error(
  181. `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered`
  182. );
  183. }
  184. serializers.set(Constructor, NOT_SERIALIZABLE);
  185. }
  186. static getSerializerFor(object) {
  187. const proto = Object.getPrototypeOf(object);
  188. let c;
  189. if (proto === null) {
  190. // Object created with Object.create(null)
  191. c = null;
  192. } else {
  193. c = proto.constructor;
  194. if (!c) {
  195. throw new Error(
  196. "Serialization of objects with prototype without valid constructor property not possible"
  197. );
  198. }
  199. }
  200. const config = serializers.get(c);
  201. if (!config) throw new Error(`No serializer registered for ${c.name}`);
  202. if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE;
  203. return config;
  204. }
  205. static getDeserializerFor(request, name) {
  206. const key = request + "/" + name;
  207. const serializer = serializerInversed.get(key);
  208. if (serializer === undefined) {
  209. throw new Error(`No deserializer registered for ${key}`);
  210. }
  211. return serializer;
  212. }
  213. static _getDeserializerForWithoutError(request, name) {
  214. const key = request + "/" + name;
  215. const serializer = serializerInversed.get(key);
  216. return serializer;
  217. }
  218. /**
  219. * @param {DeserializedType} data data
  220. * @param {Object} context context object
  221. * @returns {SerializedType|Promise<SerializedType>} serialized data
  222. */
  223. serialize(data, context) {
  224. /** @type {any[]} */
  225. let result = [CURRENT_VERSION];
  226. let currentPos = 0;
  227. let referenceable = new Map();
  228. const addReferenceable = item => {
  229. referenceable.set(item, currentPos++);
  230. };
  231. let bufferDedupeMap = new Map();
  232. const dedupeBuffer = buf => {
  233. const len = buf.length;
  234. const entry = bufferDedupeMap.get(len);
  235. if (entry === undefined) {
  236. bufferDedupeMap.set(len, buf);
  237. return buf;
  238. }
  239. if (Buffer.isBuffer(entry)) {
  240. if (len < 32) {
  241. if (buf.equals(entry)) {
  242. return entry;
  243. }
  244. bufferDedupeMap.set(len, [entry, buf]);
  245. return buf;
  246. } else {
  247. const hash = toHash(entry, this._hashFunction);
  248. const newMap = new Map();
  249. newMap.set(hash, entry);
  250. bufferDedupeMap.set(len, newMap);
  251. const hashBuf = toHash(buf, this._hashFunction);
  252. if (hash === hashBuf) {
  253. return entry;
  254. }
  255. return buf;
  256. }
  257. } else if (Array.isArray(entry)) {
  258. if (entry.length < 16) {
  259. for (const item of entry) {
  260. if (buf.equals(item)) {
  261. return item;
  262. }
  263. }
  264. entry.push(buf);
  265. return buf;
  266. } else {
  267. const newMap = new Map();
  268. const hash = toHash(buf, this._hashFunction);
  269. let found;
  270. for (const item of entry) {
  271. const itemHash = toHash(item, this._hashFunction);
  272. newMap.set(itemHash, item);
  273. if (found === undefined && itemHash === hash) found = item;
  274. }
  275. bufferDedupeMap.set(len, newMap);
  276. if (found === undefined) {
  277. newMap.set(hash, buf);
  278. return buf;
  279. } else {
  280. return found;
  281. }
  282. }
  283. } else {
  284. const hash = toHash(buf, this._hashFunction);
  285. const item = entry.get(hash);
  286. if (item !== undefined) {
  287. return item;
  288. }
  289. entry.set(hash, buf);
  290. return buf;
  291. }
  292. };
  293. let currentPosTypeLookup = 0;
  294. let objectTypeLookup = new Map();
  295. const cycleStack = new Set();
  296. const stackToString = item => {
  297. const arr = Array.from(cycleStack);
  298. arr.push(item);
  299. return arr
  300. .map(item => {
  301. if (typeof item === "string") {
  302. if (item.length > 100) {
  303. return `String ${JSON.stringify(item.slice(0, 100)).slice(
  304. 0,
  305. -1
  306. )}..."`;
  307. }
  308. return `String ${JSON.stringify(item)}`;
  309. }
  310. try {
  311. const { request, name } = ObjectMiddleware.getSerializerFor(item);
  312. if (request) {
  313. return `${request}${name ? `.${name}` : ""}`;
  314. }
  315. } catch (e) {
  316. // ignore -> fallback
  317. }
  318. if (typeof item === "object" && item !== null) {
  319. if (item.constructor) {
  320. if (item.constructor === Object)
  321. return `Object { ${Object.keys(item).join(", ")} }`;
  322. if (item.constructor === Map) return `Map { ${item.size} items }`;
  323. if (item.constructor === Array)
  324. return `Array { ${item.length} items }`;
  325. if (item.constructor === Set) return `Set { ${item.size} items }`;
  326. if (item.constructor === RegExp) return item.toString();
  327. return `${item.constructor.name}`;
  328. }
  329. return `Object [null prototype] { ${Object.keys(item).join(
  330. ", "
  331. )} }`;
  332. }
  333. try {
  334. return `${item}`;
  335. } catch (e) {
  336. return `(${e.message})`;
  337. }
  338. })
  339. .join(" -> ");
  340. };
  341. let hasDebugInfoAttached;
  342. let ctx = {
  343. write(value, key) {
  344. try {
  345. process(value);
  346. } catch (e) {
  347. if (e !== NOT_SERIALIZABLE) {
  348. if (hasDebugInfoAttached === undefined)
  349. hasDebugInfoAttached = new WeakSet();
  350. if (!hasDebugInfoAttached.has(e)) {
  351. e.message += `\nwhile serializing ${stackToString(value)}`;
  352. hasDebugInfoAttached.add(e);
  353. }
  354. }
  355. throw e;
  356. }
  357. },
  358. setCircularReference(ref) {
  359. addReferenceable(ref);
  360. },
  361. snapshot() {
  362. return {
  363. length: result.length,
  364. cycleStackSize: cycleStack.size,
  365. referenceableSize: referenceable.size,
  366. currentPos,
  367. objectTypeLookupSize: objectTypeLookup.size,
  368. currentPosTypeLookup
  369. };
  370. },
  371. rollback(snapshot) {
  372. result.length = snapshot.length;
  373. setSetSize(cycleStack, snapshot.cycleStackSize);
  374. setMapSize(referenceable, snapshot.referenceableSize);
  375. currentPos = snapshot.currentPos;
  376. setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize);
  377. currentPosTypeLookup = snapshot.currentPosTypeLookup;
  378. },
  379. ...context
  380. };
  381. this.extendContext(ctx);
  382. const process = item => {
  383. if (Buffer.isBuffer(item)) {
  384. // check if we can emit a reference
  385. const ref = referenceable.get(item);
  386. if (ref !== undefined) {
  387. result.push(ESCAPE, ref - currentPos);
  388. return;
  389. }
  390. const alreadyUsedBuffer = dedupeBuffer(item);
  391. if (alreadyUsedBuffer !== item) {
  392. const ref = referenceable.get(alreadyUsedBuffer);
  393. if (ref !== undefined) {
  394. referenceable.set(item, ref);
  395. result.push(ESCAPE, ref - currentPos);
  396. return;
  397. }
  398. item = alreadyUsedBuffer;
  399. }
  400. addReferenceable(item);
  401. result.push(item);
  402. } else if (item === ESCAPE) {
  403. result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);
  404. } else if (
  405. typeof item === "object"
  406. // We don't have to check for null as ESCAPE is null and this has been checked before
  407. ) {
  408. // check if we can emit a reference
  409. const ref = referenceable.get(item);
  410. if (ref !== undefined) {
  411. result.push(ESCAPE, ref - currentPos);
  412. return;
  413. }
  414. if (cycleStack.has(item)) {
  415. throw new Error(
  416. `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.`
  417. );
  418. }
  419. const { request, name, serializer } =
  420. ObjectMiddleware.getSerializerFor(item);
  421. const key = `${request}/${name}`;
  422. const lastIndex = objectTypeLookup.get(key);
  423. if (lastIndex === undefined) {
  424. objectTypeLookup.set(key, currentPosTypeLookup++);
  425. result.push(ESCAPE, request, name);
  426. } else {
  427. result.push(ESCAPE, currentPosTypeLookup - lastIndex);
  428. }
  429. cycleStack.add(item);
  430. try {
  431. serializer.serialize(item, ctx);
  432. } finally {
  433. cycleStack.delete(item);
  434. }
  435. result.push(ESCAPE, ESCAPE_END_OBJECT);
  436. addReferenceable(item);
  437. } else if (typeof item === "string") {
  438. if (item.length > 1) {
  439. // short strings are shorter when not emitting a reference (this saves 1 byte per empty string)
  440. // check if we can emit a reference
  441. const ref = referenceable.get(item);
  442. if (ref !== undefined) {
  443. result.push(ESCAPE, ref - currentPos);
  444. return;
  445. }
  446. addReferenceable(item);
  447. }
  448. if (item.length > 102400 && context.logger) {
  449. context.logger.warn(
  450. `Serializing big strings (${Math.round(
  451. item.length / 1024
  452. )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)`
  453. );
  454. }
  455. result.push(item);
  456. } else if (typeof item === "function") {
  457. if (!SerializerMiddleware.isLazy(item))
  458. throw new Error("Unexpected function " + item);
  459. /** @type {SerializedType} */
  460. const serializedData =
  461. SerializerMiddleware.getLazySerializedValue(item);
  462. if (serializedData !== undefined) {
  463. if (typeof serializedData === "function") {
  464. result.push(serializedData);
  465. } else {
  466. throw new Error("Not implemented");
  467. }
  468. } else if (SerializerMiddleware.isLazy(item, this)) {
  469. throw new Error("Not implemented");
  470. } else {
  471. const data = SerializerMiddleware.serializeLazy(item, data =>
  472. this.serialize([data], context)
  473. );
  474. SerializerMiddleware.setLazySerializedValue(item, data);
  475. result.push(data);
  476. }
  477. } else if (item === undefined) {
  478. result.push(ESCAPE, ESCAPE_UNDEFINED);
  479. } else {
  480. result.push(item);
  481. }
  482. };
  483. try {
  484. for (const item of data) {
  485. process(item);
  486. }
  487. return result;
  488. } catch (e) {
  489. if (e === NOT_SERIALIZABLE) return null;
  490. throw e;
  491. } finally {
  492. // Get rid of these references to avoid leaking memory
  493. // This happens because the optimized code v8 generates
  494. // is optimized for our "ctx.write" method so it will reference
  495. // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write
  496. data =
  497. result =
  498. referenceable =
  499. bufferDedupeMap =
  500. objectTypeLookup =
  501. ctx =
  502. undefined;
  503. }
  504. }
  505. /**
  506. * @param {SerializedType} data data
  507. * @param {Object} context context object
  508. * @returns {DeserializedType|Promise<DeserializedType>} deserialized data
  509. */
  510. deserialize(data, context) {
  511. let currentDataPos = 0;
  512. const read = () => {
  513. if (currentDataPos >= data.length)
  514. throw new Error("Unexpected end of stream");
  515. return data[currentDataPos++];
  516. };
  517. if (read() !== CURRENT_VERSION)
  518. throw new Error("Version mismatch, serializer changed");
  519. let currentPos = 0;
  520. let referenceable = [];
  521. const addReferenceable = item => {
  522. referenceable.push(item);
  523. currentPos++;
  524. };
  525. let currentPosTypeLookup = 0;
  526. let objectTypeLookup = [];
  527. let result = [];
  528. let ctx = {
  529. read() {
  530. return decodeValue();
  531. },
  532. setCircularReference(ref) {
  533. addReferenceable(ref);
  534. },
  535. ...context
  536. };
  537. this.extendContext(ctx);
  538. const decodeValue = () => {
  539. const item = read();
  540. if (item === ESCAPE) {
  541. const nextItem = read();
  542. if (nextItem === ESCAPE_ESCAPE_VALUE) {
  543. return ESCAPE;
  544. } else if (nextItem === ESCAPE_UNDEFINED) {
  545. return undefined;
  546. } else if (nextItem === ESCAPE_END_OBJECT) {
  547. throw new Error(
  548. `Unexpected end of object at position ${currentDataPos - 1}`
  549. );
  550. } else {
  551. const request = nextItem;
  552. let serializer;
  553. if (typeof request === "number") {
  554. if (request < 0) {
  555. // relative reference
  556. return referenceable[currentPos + request];
  557. }
  558. serializer = objectTypeLookup[currentPosTypeLookup - request];
  559. } else {
  560. if (typeof request !== "string") {
  561. throw new Error(
  562. `Unexpected type (${typeof request}) of request ` +
  563. `at position ${currentDataPos - 1}`
  564. );
  565. }
  566. const name = read();
  567. serializer = ObjectMiddleware._getDeserializerForWithoutError(
  568. request,
  569. name
  570. );
  571. if (serializer === undefined) {
  572. if (request && !loadedRequests.has(request)) {
  573. let loaded = false;
  574. for (const [regExp, loader] of loaders) {
  575. if (regExp.test(request)) {
  576. if (loader(request)) {
  577. loaded = true;
  578. break;
  579. }
  580. }
  581. }
  582. if (!loaded) {
  583. require(request);
  584. }
  585. loadedRequests.add(request);
  586. }
  587. serializer = ObjectMiddleware.getDeserializerFor(request, name);
  588. }
  589. objectTypeLookup.push(serializer);
  590. currentPosTypeLookup++;
  591. }
  592. try {
  593. const item = serializer.deserialize(ctx);
  594. const end1 = read();
  595. if (end1 !== ESCAPE) {
  596. throw new Error("Expected end of object");
  597. }
  598. const end2 = read();
  599. if (end2 !== ESCAPE_END_OBJECT) {
  600. throw new Error("Expected end of object");
  601. }
  602. addReferenceable(item);
  603. return item;
  604. } catch (err) {
  605. // As this is only for error handling, we omit creating a Map for
  606. // faster access to this information, as this would affect performance
  607. // in the good case
  608. let serializerEntry;
  609. for (const entry of serializers) {
  610. if (entry[1].serializer === serializer) {
  611. serializerEntry = entry;
  612. break;
  613. }
  614. }
  615. const name = !serializerEntry
  616. ? "unknown"
  617. : !serializerEntry[1].request
  618. ? serializerEntry[0].name
  619. : serializerEntry[1].name
  620. ? `${serializerEntry[1].request} ${serializerEntry[1].name}`
  621. : serializerEntry[1].request;
  622. err.message += `\n(during deserialization of ${name})`;
  623. throw err;
  624. }
  625. }
  626. } else if (typeof item === "string") {
  627. if (item.length > 1) {
  628. addReferenceable(item);
  629. }
  630. return item;
  631. } else if (Buffer.isBuffer(item)) {
  632. addReferenceable(item);
  633. return item;
  634. } else if (typeof item === "function") {
  635. return SerializerMiddleware.deserializeLazy(
  636. item,
  637. data => this.deserialize(data, context)[0]
  638. );
  639. } else {
  640. return item;
  641. }
  642. };
  643. try {
  644. while (currentDataPos < data.length) {
  645. result.push(decodeValue());
  646. }
  647. return result;
  648. } finally {
  649. // Get rid of these references to avoid leaking memory
  650. // This happens because the optimized code v8 generates
  651. // is optimized for our "ctx.read" method so it will reference
  652. // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read
  653. result = referenceable = data = objectTypeLookup = ctx = undefined;
  654. }
  655. }
  656. }
  657. module.exports = ObjectMiddleware;
  658. module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE;