DataStoreSerializer.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import { getUnsafeWindow, computeHash, type DataStore } from "./index.js";
  2. export type DataStoreSerializerOptions = {
  3. /** Whether to add a checksum to the exported data */
  4. addChecksum?: boolean;
  5. /** Whether to ensure the integrity of the data when importing it (unless the checksum property doesn't exist) */
  6. ensureIntegrity?: boolean;
  7. };
  8. /** Serialized data of a DataStore instance */
  9. export type SerializedDataStore = {
  10. /** The ID of the DataStore instance */
  11. id: string;
  12. /** The serialized data */
  13. data: string;
  14. /** The format version of the data */
  15. formatVersion: number;
  16. /** Whether the data is encoded */
  17. encoded: boolean;
  18. /** The checksum of the data - key is not present for data without a checksum */
  19. checksum?: string;
  20. };
  21. /** Result of {@linkcode DataStoreSerializer.loadStoresData()} */
  22. export type LoadStoresDataResult = {
  23. /** The ID of the DataStore instance */
  24. id: string;
  25. /** The in-memory data object */
  26. data: object;
  27. }
  28. /**
  29. * Allows for easy serialization and deserialization of multiple DataStore instances.
  30. *
  31. * All methods are at least `protected`, so you can easily extend this class and overwrite them to use a different storage method or to add additional functionality.
  32. * Remember that you can call `super.methodName()` in the subclass to access the original method.
  33. *
  34. * - ⚠️ Needs to run in a secure context (HTTPS) due to the use of the SubtleCrypto API if checksumming is enabled.
  35. */
  36. export class DataStoreSerializer {
  37. protected stores: DataStore[];
  38. protected options: Required<DataStoreSerializerOptions>;
  39. constructor(stores: DataStore[], options: DataStoreSerializerOptions = {}) {
  40. if(!getUnsafeWindow().crypto || !getUnsafeWindow().crypto.subtle)
  41. throw new Error("DataStoreSerializer has to run in a secure context (HTTPS)!");
  42. this.stores = stores;
  43. this.options = {
  44. addChecksum: true,
  45. ensureIntegrity: true,
  46. ...options,
  47. };
  48. }
  49. /** Calculates the checksum of a string */
  50. protected async calcChecksum(input: string): Promise<string> {
  51. return computeHash(input, "SHA-256");
  52. }
  53. /** Serializes a DataStore instance */
  54. protected async serializeStore(storeInst: DataStore): Promise<SerializedDataStore> {
  55. const data = storeInst.encodingEnabled()
  56. ? await storeInst.encodeData(JSON.stringify(storeInst.getData()))
  57. : JSON.stringify(storeInst.getData());
  58. const checksum = this.options.addChecksum
  59. ? await this.calcChecksum(data)
  60. : undefined;
  61. return {
  62. id: storeInst.id,
  63. data,
  64. formatVersion: storeInst.formatVersion,
  65. encoded: storeInst.encodingEnabled(),
  66. checksum,
  67. };
  68. }
  69. /** Serializes the data stores into a string */
  70. public async serialize(): Promise<string> {
  71. const serData: SerializedDataStore[] = [];
  72. for(const store of this.stores)
  73. serData.push(await this.serializeStore(store));
  74. return JSON.stringify(serData);
  75. }
  76. /**
  77. * Deserializes the data exported via {@linkcode serialize()} and imports it into the DataStore instances.
  78. * Also triggers the migration process if the data format has changed.
  79. */
  80. public async deserialize(serializedData: string): Promise<void> {
  81. const deserStores: SerializedDataStore[] = JSON.parse(serializedData);
  82. for(const storeData of deserStores) {
  83. const storeInst = this.stores.find(s => s.id === storeData.id);
  84. if(!storeInst)
  85. throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
  86. if(this.options.ensureIntegrity && typeof storeData.checksum === "string") {
  87. const checksum = await this.calcChecksum(storeData.data);
  88. if(checksum !== storeData.checksum)
  89. throw new Error(`Checksum mismatch for DataStore with ID "${storeData.id}"!\nExpected: ${storeData.checksum}\nHas: ${checksum}`);
  90. }
  91. const decodedData = storeData.encoded && storeInst.encodingEnabled()
  92. ? await storeInst.decodeData(storeData.data)
  93. : storeData.data;
  94. if(storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
  95. await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
  96. else
  97. await storeInst.setData(JSON.parse(decodedData));
  98. }
  99. }
  100. /**
  101. * Loads the persistent data of the DataStore instances into the in-memory cache.
  102. * Also triggers the migration process if the data format has changed.
  103. * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
  104. */
  105. public async loadStoresData(): Promise<PromiseSettledResult<LoadStoresDataResult>[]> {
  106. return Promise.allSettled(this.stores.map(
  107. async store => ({
  108. id: store.id,
  109. data: await store.loadData(),
  110. })
  111. ));
  112. }
  113. /** Resets the persistent data of the DataStore instances to their default values. */
  114. public async resetStoresData(): Promise<PromiseSettledResult<void>[]> {
  115. return Promise.allSettled(this.stores.map(store => store.saveDefaultData()));
  116. }
  117. /**
  118. * Deletes the persistent data of the DataStore instances.
  119. * Leaves the in-memory data untouched.
  120. */
  121. public async deleteStoresData(): Promise<PromiseSettledResult<void>[]> {
  122. return Promise.allSettled(this.stores.map(store => store.deleteData()));
  123. }
  124. }