config.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { featInfo } from "./features/index";
  2. import { FeatureConfig } from "./types";
  3. import { log } from "./utils";
  4. export const defaultFeatures = (Object.keys(featInfo) as (keyof typeof featInfo)[]).reduce<Partial<FeatureConfig>>((acc, key) => {
  5. acc[key] = featInfo[key].default as unknown as undefined;
  6. return acc;
  7. }, {}) as FeatureConfig;
  8. let featuresCache: FeatureConfig | undefined;
  9. /**
  10. * Returns the current FeatureConfig in memory or reads it from GM storage
  11. * Automatically applies defaults for non-existant keys
  12. * @param forceRead Set to true to force reading the config from GM storage
  13. */
  14. export async function getFeatures(forceRead = false) {
  15. if(featuresCache === undefined || forceRead)
  16. await saveFeatureConf(featuresCache = { ...defaultFeatures, ...await loadFeatureConf() }); // look at this sexy one liner
  17. return featuresCache;
  18. }
  19. /** Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved */
  20. export async function loadFeatureConf(): Promise<FeatureConfig> {
  21. const defConf = Object.freeze({ ...defaultFeatures });
  22. try {
  23. const featureConf = await GM.getValue("betterytm-config") as string;
  24. if(typeof featureConf !== "string") {
  25. await setDefaultFeatConf();
  26. return featuresCache = defConf;
  27. }
  28. return featuresCache = Object.freeze(featureConf ? JSON.parse(featureConf) : defConf);
  29. }
  30. catch(err) {
  31. await setDefaultFeatConf();
  32. return featuresCache = defConf;
  33. }
  34. }
  35. /**
  36. * Saves a feature configuration saved persistently
  37. * @param featureConf
  38. */
  39. export function saveFeatureConf(featureConf: FeatureConfig) {
  40. if(!featureConf || typeof featureConf != "object")
  41. throw new TypeError("Feature config not provided or invalid");
  42. log("Saving new feature config:", featureConf);
  43. featuresCache = { ...featureConf };
  44. return GM.setValue("betterytm-config", JSON.stringify(featureConf));
  45. }
  46. /** Resets the featuresCache synchronously and the persistent features storage asynchronously to its default values */
  47. export function setDefaultFeatConf() {
  48. featuresCache = { ...defaultFeatures };
  49. return GM.setValue("betterytm-config", JSON.stringify(defaultFeatures));
  50. }