update.mjs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { resolveModulePath } from 'exsolve';
  2. import { S as SUPPORTED_EXTENSIONS } from './shared/c12.CEGFwQZa.mjs';
  3. import { join, normalize } from 'pathe';
  4. import { mkdir, writeFile, readFile } from 'node:fs/promises';
  5. import { dirname, extname } from 'node:path';
  6. import 'node:fs';
  7. import 'node:url';
  8. import 'node:os';
  9. import 'jiti';
  10. import 'rc9';
  11. import 'defu';
  12. import 'pkg-types';
  13. import 'dotenv';
  14. const UPDATABLE_EXTS = [".js", ".ts", ".mjs", ".cjs", ".mts", ".cts"];
  15. async function updateConfig(opts) {
  16. const { parseModule } = await import('magicast');
  17. let configFile = tryResolve(`./${opts.configFile}`, opts.cwd, SUPPORTED_EXTENSIONS) || tryResolve(
  18. `./.config/${opts.configFile}`,
  19. opts.cwd,
  20. SUPPORTED_EXTENSIONS
  21. ) || tryResolve(
  22. `./.config/${opts.configFile.split(".")[0]}`,
  23. opts.cwd,
  24. SUPPORTED_EXTENSIONS
  25. );
  26. let created = false;
  27. if (!configFile) {
  28. configFile = join(
  29. opts.cwd,
  30. opts.configFile + (opts.createExtension || ".ts")
  31. );
  32. const createResult = await opts.onCreate?.({ configFile }) ?? true;
  33. if (!createResult) {
  34. throw new Error("Config file creation aborted.");
  35. }
  36. const content = typeof createResult === "string" ? createResult : `export default {}
  37. `;
  38. await mkdir(dirname(configFile), { recursive: true });
  39. await writeFile(configFile, content, "utf8");
  40. created = true;
  41. }
  42. const ext = extname(configFile);
  43. if (!UPDATABLE_EXTS.includes(ext)) {
  44. throw new Error(
  45. `Unsupported config file extension: ${ext} (${configFile}) (supported: ${UPDATABLE_EXTS.join(", ")})`
  46. );
  47. }
  48. const contents = await readFile(configFile, "utf8");
  49. const _module = parseModule(contents, opts.magicast);
  50. const defaultExport = _module.exports.default;
  51. if (!defaultExport) {
  52. throw new Error("Default export is missing in the config file!");
  53. }
  54. const configObj = defaultExport.$type === "function-call" ? defaultExport.$args[0] : defaultExport;
  55. await opts.onUpdate?.(configObj);
  56. await writeFile(configFile, _module.generate().code);
  57. return {
  58. configFile,
  59. created
  60. };
  61. }
  62. function tryResolve(path, cwd, extensions) {
  63. const res = resolveModulePath(path, {
  64. try: true,
  65. from: join(cwd, "/"),
  66. extensions,
  67. suffixes: ["", "/index"],
  68. cache: false
  69. });
  70. return res ? normalize(res) : void 0;
  71. }
  72. export { updateConfig };