webpack/lib/serialization/NullPrototypeObjectSerializ...

52 lines
1.2 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
2023-05-23 02:32:23 +08:00
/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
class NullPrototypeObjectSerializer {
2023-05-23 02:32:23 +08:00
/**
2024-06-11 21:09:50 +08:00
* @template {object} T
2023-05-23 02:32:23 +08:00
* @param {T} obj null object
* @param {ObjectSerializerContext} context context
*/
serialize(obj, context) {
/** @type {string[]} */
const keys = Object.keys(obj);
for (const key of keys) {
2023-05-23 02:32:23 +08:00
context.write(key);
}
2023-05-23 02:32:23 +08:00
context.write(null);
for (const key of keys) {
2024-08-09 01:03:17 +08:00
context.write(obj[/** @type {keyof T} */ (key)]);
}
}
2024-07-31 12:23:44 +08:00
2023-05-23 02:32:23 +08:00
/**
2024-06-11 21:09:50 +08:00
* @template {object} T
2023-05-23 02:32:23 +08:00
* @param {ObjectDeserializerContext} context context
* @returns {T} null object
*/
deserialize(context) {
/** @type {T} */
const obj = Object.create(null);
2023-05-23 02:32:23 +08:00
/** @type {string[]} */
const keys = [];
2023-05-23 02:32:23 +08:00
/** @type {string | null} */
let key = context.read();
while (key !== null) {
keys.push(key);
2023-05-23 02:32:23 +08:00
key = context.read();
}
for (const key of keys) {
2024-08-09 01:03:17 +08:00
obj[/** @type {keyof T} */ (key)] = context.read();
}
return obj;
}
}
module.exports = NullPrototypeObjectSerializer;