config.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import path from 'node:path'
  2. import { debug } from '../lib/logger'
  3. import { readFile, writeFile, prettyLog, deepMerge } from '../lib/util'
  4. export type RecordMate = {
  5. /**
  6. * The hosts that have generated certificate
  7. */
  8. hosts: string[]
  9. /**
  10. * file hash
  11. */
  12. hash?: RecordHash
  13. }
  14. export type RecordHash = {
  15. key?: string
  16. cert?: string
  17. }
  18. export type ConfigOptions = {
  19. savePath: string
  20. }
  21. const CONFIG_FILE_NAME = 'config.json'
  22. class Config {
  23. /**
  24. * The mkcert version
  25. */
  26. private version: string | undefined
  27. private record: RecordMate | undefined
  28. private configFilePath: string
  29. constructor({ savePath }: ConfigOptions) {
  30. this.configFilePath = path.resolve(savePath, CONFIG_FILE_NAME)
  31. }
  32. public async init() {
  33. const str = await readFile(this.configFilePath)
  34. const options = str ? JSON.parse(str) : undefined
  35. if (options) {
  36. this.version = options.version
  37. this.record = options.record
  38. }
  39. }
  40. private async serialize() {
  41. await writeFile(this.configFilePath, prettyLog(this))
  42. }
  43. // deep merge
  44. public async merge(obj: Record<string, any>) {
  45. const currentStr = prettyLog(this)
  46. deepMerge(this, obj)
  47. const nextStr = prettyLog(this)
  48. debug(
  49. `Receive parameter\n ${prettyLog(
  50. obj
  51. )}\nUpdate config from\n ${currentStr} \nto\n ${nextStr}`
  52. )
  53. await this.serialize()
  54. }
  55. public getRecord() {
  56. return this.record
  57. }
  58. public getVersion() {
  59. return this.version
  60. }
  61. }
  62. export default Config