ConfigManager.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. /** Function that takes the data in the old format and returns the data in the new format. Also supports an asynchronous migration. */
  3. type MigrationFunc = (oldData: any) => any | Promise<any>;
  4. /** Dictionary of format version numbers and the function that migrates to them from the previous whole integer */
  5. export type ConfigMigrationsDict = Record<number, MigrationFunc>;
  6. /** Options for the ConfigManager instance */
  7. export interface ConfigManagerOptions<TData> {
  8. /** A unique internal ID for this configuration - choose wisely as changing it is not supported yet. */
  9. id: string;
  10. /**
  11. * The default config data object to use if no data is saved in persistent storage yet.
  12. * Until the data is loaded from persistent storage with `loadData()`, this will be the data returned by `getData()`
  13. *
  14. * ⚠️ This has to be an object that can be serialized to JSON, so no functions or circular references are allowed, they will cause unexpected behavior.
  15. */
  16. defaultConfig: TData;
  17. /**
  18. * An incremental, whole integer version number of the current format of config data.
  19. * If the format of the data is changed in any way, this number should be incremented, in which case all necessary functions of the migrations dictionary will be run consecutively.
  20. *
  21. * ⚠️ Never decrement this number and optimally don't skip any numbers either!
  22. */
  23. formatVersion: number;
  24. /**
  25. * Function to use to encode the data prior to saving it in persistent storage.
  26. * The input data is a serialized JSON object.
  27. *
  28. * You can make use of UserUtils' [`compress()`](https://github.com/Sv443-Network/UserUtils?tab=readme-ov-file#compress) function here to make the data use up less space at the cost of a little bit of performance.
  29. */
  30. encodeData?: (data: string) => string | Promise<string>,
  31. /**
  32. * Function to use to decode the data after reading it from persistent storage.
  33. * The result should be a valid JSON object.
  34. *
  35. * You can make use of UserUtils' [`decompress()`](https://github.com/Sv443-Network/UserUtils?tab=readme-ov-file#decompress) function here to make the data use up less space at the cost of a little bit of performance.
  36. */
  37. decodeData?: (data: string) => string | Promise<string>,
  38. /**
  39. * A dictionary of functions that can be used to migrate data from older versions of the configuration to newer ones.
  40. * The keys of the dictionary should be the format version that the functions can migrate to, from the previous whole integer value.
  41. * The values should be functions that take the data in the old format and return the data in the new format.
  42. * The functions will be run in order from the oldest to the newest version.
  43. * If the current format version is not in the dictionary, no migrations will be run.
  44. */
  45. migrations?: ConfigMigrationsDict;
  46. }
  47. /**
  48. * Manages a user configuration that is cached in memory and persistently saved across sessions.
  49. * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
  50. *
  51. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  52. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  53. *
  54. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
  55. */
  56. export class ConfigManager<TData = any> {
  57. public readonly id: string;
  58. public readonly formatVersion: number;
  59. public readonly defaultConfig: TData;
  60. private cachedConfig: TData;
  61. private migrations?: ConfigMigrationsDict;
  62. private encodeData: ConfigManagerOptions<TData>["encodeData"];
  63. private decodeData: ConfigManagerOptions<TData>["decodeData"];
  64. /**
  65. * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
  66. * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
  67. *
  68. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  69. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  70. *
  71. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
  72. * @param options The options for this ConfigManager instance
  73. */
  74. constructor(options: ConfigManagerOptions<TData>) {
  75. this.id = options.id;
  76. this.formatVersion = options.formatVersion;
  77. this.defaultConfig = options.defaultConfig;
  78. this.cachedConfig = options.defaultConfig;
  79. this.migrations = options.migrations;
  80. this.encodeData = options.encodeData;
  81. this.decodeData = options.decodeData;
  82. }
  83. /**
  84. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  85. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  86. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  87. */
  88. public async loadData(): Promise<TData> {
  89. try {
  90. const gmData = await GM.getValue(`_uucfg-${this.id}`, this.defaultConfig);
  91. let gmFmtVer = Number(await GM.getValue(`_uucfgver-${this.id}`));
  92. if(typeof gmData !== "string") {
  93. await this.saveDefaultData();
  94. return this.defaultConfig;
  95. }
  96. if(isNaN(gmFmtVer))
  97. await GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  98. let parsed = await this.deserializeData(gmData);
  99. if(gmFmtVer < this.formatVersion && this.migrations)
  100. parsed = await this.runMigrations(parsed, gmFmtVer);
  101. return this.cachedConfig = parsed;
  102. }
  103. catch(err) {
  104. await this.saveDefaultData();
  105. return this.defaultConfig;
  106. }
  107. }
  108. /**
  109. * Returns a copy of the data from the in-memory cache.
  110. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  111. */
  112. public getData(): TData {
  113. return this.deepCopy(this.cachedConfig);
  114. }
  115. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  116. public setData(data: TData) {
  117. this.cachedConfig = data;
  118. return new Promise<void>(async (resolve) => {
  119. await Promise.all([
  120. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(data)),
  121. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  122. ]);
  123. resolve();
  124. });
  125. }
  126. /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  127. public async saveDefaultData() {
  128. this.cachedConfig = this.defaultConfig;
  129. return new Promise<void>(async (resolve) => {
  130. await Promise.all([
  131. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(this.defaultConfig)),
  132. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  133. ]);
  134. resolve();
  135. });
  136. }
  137. /**
  138. * Call this method to clear all persistently stored data associated with this ConfigManager instance.
  139. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  140. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  141. *
  142. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  143. */
  144. public async deleteConfig() {
  145. await Promise.all([
  146. GM.deleteValue(`_uucfg-${this.id}`),
  147. GM.deleteValue(`_uucfgver-${this.id}`),
  148. ]);
  149. }
  150. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  151. protected async runMigrations(oldData: any, oldFmtVer: number): Promise<TData> {
  152. if(!this.migrations)
  153. return oldData as TData;
  154. let newData = oldData;
  155. const sortedMigrations = Object.entries(this.migrations)
  156. .sort(([a], [b]) => Number(a) - Number(b));
  157. let lastFmtVer = oldFmtVer;
  158. for(const [fmtVer, migrationFunc] of sortedMigrations) {
  159. const ver = Number(fmtVer);
  160. if(oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  161. try {
  162. const migRes = migrationFunc(newData);
  163. newData = migRes instanceof Promise ? await migRes : migRes;
  164. lastFmtVer = oldFmtVer = ver;
  165. }
  166. catch(err) {
  167. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  168. }
  169. }
  170. }
  171. await Promise.all([
  172. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(newData)),
  173. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  174. ]);
  175. return newData as TData;
  176. }
  177. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  178. private async serializeData(data: TData) {
  179. const stringData = JSON.stringify(data);
  180. if(!this.encodeData)
  181. return stringData;
  182. const encRes = this.encodeData(stringData);
  183. if(encRes instanceof Promise)
  184. return await encRes;
  185. return encRes;
  186. }
  187. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  188. private async deserializeData(data: string) {
  189. let decRes = this.decodeData ? this.decodeData(data) : undefined;
  190. if(decRes instanceof Promise)
  191. decRes = await decRes;
  192. return JSON.parse(decRes ?? data) as TData;
  193. }
  194. /** Copies a JSON-compatible object and loses its internal references */
  195. private deepCopy<T>(obj: T): T {
  196. return JSON.parse(JSON.stringify(obj));
  197. }
  198. }