All files manifest.ts

79.42% Statements 139/175
68.57% Branches 24/35
50% Functions 4/8
79.42% Lines 139/175

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 2281x           1x 1x 1x 1x 1x 1x                                   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 1x         1x 6x   6x   6x         1x 1x 6x             6x   2x 2x 2x 2x 2x 2x 2x 2x   2x 3x         3x 2x   2x 2x 3x           3x 3x 3x   2x 2x 2x 2x 2x   1x   9x 9x 9x 9x 9x 9x     9x   9x 9x 14x 6x 6x 6x   8x   8x 8x   14x 6x     6x             14x 2x     2x   14x 3x 3x 14x 5x 5x   8x 14x           9x 9x   9x 9x   4x 4x 4x 4x 4x 4x     4x   4x   4x 4x 3x 3x 3x 3x 3x 3x   1x 1x  
import path from "node:path";
import type { CommandDef } from "citty";
import type express from "express";
import type { Kysely } from "kysely";
import type { Transport } from "nodemailer";
import type { Queue } from "plainjobs";
import { isCommand } from "./command";
import { type Config, loadAndGetConfig } from "./config";
import { isDatabase } from "./database";
import { loadModule, loadModulesfromDir } from "./file-module";
import { type Job, type Schedule, isJob, isSchedule } from "./job";
import { getLogger } from "./log";
 
export type Manifest = {
  database: Kysely<Record<string, unknown>>;
  http: () => Promise<express.Application>;
  queue: Queue;
  mailer: Transport;
  jobs: Record<string, Job<unknown>>;
  commands: Record<string, CommandDef>;
  schedules: Record<string, Schedule>;
};
 
type ModuleConfig<T> = {
  typeGuard: (m: unknown) => m is T;
  path: keyof Config["paths"];
  type: "single" | "list";
};
 
const manifestConfig: Record<keyof Manifest, ModuleConfig<unknown>> = {
  database: {
    typeGuard: isDatabase,
    path: "database",
    type: "single",
  },
  http: {
    typeGuard: (m): m is (config: Config) => Promise<express.Application> =>
      typeof m === "function",
    path: "http",
    type: "single",
  },
  queue: {
    typeGuard: (m): m is Queue =>
      typeof m === "object" && m !== null && "add" in m && "schedule" in m,
    path: "queue",
    type: "single",
  },
  mailer: {
    typeGuard: (m): m is Transport =>
      typeof m === "object" && m !== null && "sendMail" in m,
    path: "mailer",
    type: "single",
  },
  jobs: {
    typeGuard: isJob,
    path: "jobs",
    type: "list",
  },
  commands: {
    typeGuard: isCommand,
    path: "commands",
    type: "list",
  },
  schedules: {
    typeGuard: isSchedule,
    path: "schedules",
    type: "list",
  },
};
 
async function loadSingleModule<T>(
  config: Config,
  cwd: string,
  moduleConfig: ModuleConfig<T>,
): Promise<T | undefined> {
  const modulePath = path.join(cwd, config.paths[moduleConfig.path]);
  const log = getLogger("manifest");
  log.debug(`Loading single module from ${modulePath}`);
 
  try {
    const module = await loadModule(modulePath, async (m: unknown) => {
      if (!moduleConfig.typeGuard(m)) {
        throw new Error(
          `Invalid module: type guard check failed for ${moduleConfig.path}`,
        );
      }
      return m as T;
    });
 
    if (!module) return undefined;
 
    if (!module.defaultExport) {
      log.error(`No default export found in module at ${modulePath}`);
      throw new Error(`No default export found in module at ${modulePath}`);
    }
 
    log.info(`Successfully loaded single module from ${modulePath}`);
    return module.defaultExport;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "MODULE_NOT_FOUND") {
      log.warn(`Module not found at ${modulePath}`);
      return undefined;
    }
    throw error;
  }
}
 
async function loadModuleList<T>(
  config: Config,
  cwd: string,
  moduleConfig: ModuleConfig<T>,
): Promise<Record<string, T>> {
  const dirPath = path.join(cwd, config.paths[moduleConfig.path]);
  const log = getLogger("manifest");
  log.debug(`Loading module list from ${dirPath}`);
 
  const modules = await loadModulesfromDir(dirPath, async (m: unknown) => {
    if (!moduleConfig.typeGuard(m)) {
      throw new Error(
        `Invalid module: type guard check failed for ${moduleConfig.path}`,
      );
    }
    return m as T;
  });
 
  const result: Record<string, T> = {};
  for (const module of modules) {
    if (!module.defaultExport) {
      log.error(`No default export found in module at ${module.absolutePath}`);
      throw new Error(
        `No default export found in module at ${module.absolutePath}`,
      );
    }
    log.debug(`Loaded module ${module.filename}`);
    result[module.filename] = module.defaultExport;
  }
 
  log.info(
    `Successfully loaded ${Object.keys(result).length} modules from ${dirPath}`,
  );
  return result;
}
 
const memoizedManifest: { [K in keyof Manifest]?: Manifest[K] } = {};
 
export async function getManifest<K extends keyof Manifest>(
  keys: K[],
  opts: { config?: Config; cwd?: string } = {},
): Promise<Partial<Pick<Manifest, K>>> {
  const log = getLogger("manifest");
  const config = opts.config ?? (await loadAndGetConfig());
  const cwd = opts.cwd ?? process.cwd();
 
  log.info(`Getting manifest for ${keys.join(", ")}`, { cwd });
 
  const results = await Promise.all(
    keys.map(async (key) => {
      if (key in memoizedManifest) {
        log.info(`Returning memoized manifest for ${key}`);
        return [key, memoizedManifest[key]] as [K, Manifest[K] | undefined];
      }
 
      const moduleConfig = manifestConfig[key];
 
      try {
        let result: Manifest[K] | undefined;
 
        if (moduleConfig.type === "single") {
          result = (await loadSingleModule(config, cwd, moduleConfig)) as
            | Manifest[K]
            | undefined;
          if (result && key === "http") {
            const getExpressApp = result as (
              config: Config,
            ) => Promise<express.Application>;
            result = (() => getExpressApp(config)) as Manifest[K] | undefined;
            log.info("Successfully initialized express app");
          }
        } else {
          result = (await loadModuleList(config, cwd, moduleConfig)) as
            | Manifest[K]
            | undefined;
        }
 
        if (result !== undefined) {
          log.info(`Successfully got manifest for ${key}`);
          memoizedManifest[key] = result;
        } else {
          log.warn(`Manifest for ${key} is undefined`);
        }
 
        return [key, result] as [K, Manifest[K] | undefined];
      } catch (error) {
        log.error(`Failed to get manifest for ${key}`, {
          error: (error as Error).message,
        });
        throw error;
      }
    }),
  );
 
  return Object.fromEntries(results) as Partial<Pick<Manifest, K>>;
}
 
export async function getManifestOrThrow<K extends keyof Manifest>(
  keys: K[],
  opts: { config?: Config; cwd?: string } = {},
): Promise<Pick<Manifest, K>> {
  const log = getLogger("manifest");
  const config = opts.config ?? (await loadAndGetConfig());
  const cwd = opts.cwd ?? process.cwd();
 
  log.info(`Getting manifest or throw for ${keys.join(", ")}`, { cwd });
 
  const result = await getManifest(keys, opts);
 
  const missingKeys = keys.filter((key) => result[key] === undefined);
  if (missingKeys.length > 0) {
    const missingPaths = missingKeys.map((key) => {
      const modulePath = path.join(cwd, config.paths[manifestConfig[key].path]);
      return `${key} not found at ${modulePath}`;
    });
    throw new Error(`Missing manifests: ${missingPaths.join(", ")}`);
  }
 
  return result as Pick<Manifest, K>;
}