JsonData.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { register } = require("../util/serialization");
  7. /**
  8. * @import {
  9. * ObjectDeserializerContext,
  10. * ObjectSerializerContext
  11. * } from "../serialization/ObjectMiddleware"
  12. */
  13. /** @import Hash from "../util/Hash" */
  14. /** @import { JsonValue } from "../util/fs" */
  15. class JsonData {
  16. /**
  17. * Creates an instance of JsonData.
  18. * @param {Buffer | JsonValue} data JSON data
  19. */
  20. constructor(data) {
  21. /** @type {Buffer | undefined} */
  22. this._buffer = undefined;
  23. /** @type {JsonValue | undefined} */
  24. this._data = undefined;
  25. if (Buffer.isBuffer(data)) {
  26. this._buffer = data;
  27. } else {
  28. this._data = data;
  29. }
  30. }
  31. /**
  32. * Returns raw JSON data.
  33. * @returns {JsonValue | undefined} Raw JSON data
  34. */
  35. get() {
  36. if (this._data === undefined && this._buffer !== undefined) {
  37. this._data = JSON.parse(this._buffer.toString());
  38. }
  39. return this._data;
  40. }
  41. /**
  42. * Updates the hash with the data contributed by this instance.
  43. * @param {Hash} hash hash to be updated
  44. * @returns {void} the updated hash
  45. */
  46. updateHash(hash) {
  47. if (this._buffer === undefined && this._data !== undefined) {
  48. this._buffer = Buffer.from(JSON.stringify(this._data));
  49. }
  50. if (this._buffer) hash.update(this._buffer);
  51. }
  52. }
  53. register(JsonData, "webpack/lib/json/JsonData", null, {
  54. /**
  55. * Serializes this instance into the provided serializer context.
  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. * Restores this instance from the provided deserializer context.
  67. * @param {ObjectDeserializerContext} context context
  68. * @returns {JsonData} deserialized JSON data
  69. */
  70. deserialize({ read }) {
  71. return new JsonData(read());
  72. }
  73. });
  74. module.exports = JsonData;