[79a0317] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 3 | Author Tobias Koppers @sokra
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | "use strict";
|
---|
| 7 |
|
---|
| 8 | const { register } = require("../util/serialization");
|
---|
| 9 |
|
---|
| 10 | /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
|
---|
| 11 | /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
|
---|
| 12 | /** @typedef {import("../util/Hash")} Hash */
|
---|
| 13 | /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
|
---|
| 14 |
|
---|
| 15 | class JsonData {
|
---|
| 16 | /**
|
---|
| 17 | * @param {Buffer | RawJsonData} data JSON data
|
---|
| 18 | */
|
---|
| 19 | constructor(data) {
|
---|
| 20 | /** @type {Buffer | undefined} */
|
---|
| 21 | this._buffer = undefined;
|
---|
| 22 | /** @type {RawJsonData | undefined} */
|
---|
| 23 | this._data = undefined;
|
---|
| 24 | if (Buffer.isBuffer(data)) {
|
---|
| 25 | this._buffer = data;
|
---|
| 26 | } else {
|
---|
| 27 | this._data = data;
|
---|
| 28 | }
|
---|
| 29 | }
|
---|
| 30 |
|
---|
| 31 | /**
|
---|
| 32 | * @returns {RawJsonData|undefined} Raw JSON data
|
---|
| 33 | */
|
---|
| 34 | get() {
|
---|
| 35 | if (this._data === undefined && this._buffer !== undefined) {
|
---|
| 36 | this._data = JSON.parse(this._buffer.toString());
|
---|
| 37 | }
|
---|
| 38 | return this._data;
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | /**
|
---|
| 42 | * @param {Hash} hash hash to be updated
|
---|
| 43 | * @returns {void} the updated hash
|
---|
| 44 | */
|
---|
| 45 | updateHash(hash) {
|
---|
| 46 | if (this._buffer === undefined && this._data !== undefined) {
|
---|
| 47 | this._buffer = Buffer.from(JSON.stringify(this._data));
|
---|
| 48 | }
|
---|
| 49 |
|
---|
| 50 | if (this._buffer) hash.update(this._buffer);
|
---|
| 51 | }
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | register(JsonData, "webpack/lib/json/JsonData", null, {
|
---|
| 55 | /**
|
---|
| 56 | * @param {JsonData} obj JSONData object
|
---|
| 57 | * @param {ObjectSerializerContext} context context
|
---|
| 58 | */
|
---|
| 59 | serialize(obj, { write }) {
|
---|
| 60 | if (obj._buffer === undefined && obj._data !== undefined) {
|
---|
| 61 | obj._buffer = Buffer.from(JSON.stringify(obj._data));
|
---|
| 62 | }
|
---|
| 63 | write(obj._buffer);
|
---|
| 64 | },
|
---|
| 65 | /**
|
---|
| 66 | * @param {ObjectDeserializerContext} context context
|
---|
| 67 | * @returns {JsonData} deserialized JSON data
|
---|
| 68 | */
|
---|
| 69 | deserialize({ read }) {
|
---|
| 70 | return new JsonData(read());
|
---|
| 71 | }
|
---|
| 72 | });
|
---|
| 73 |
|
---|
| 74 | module.exports = JsonData;
|
---|