config.ts 1.9 KB

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