1 import { Logger } from "@medusajs/types"
2 import { dynamicImport, promiseAll, readDirRecursive } from "@medusajs/utils"
3 import { Dirent } from "fs"
4 import { access } from "fs/promises"
5 import { join } from "path"
6 import { logger as defaultLogger } from "../logger"
7
8 export class LinkLoader {
9 /**
10 * The directory from which to load the links
11 * @private
12 */
13 #sourceDir: string | string[]
14
15 /**
16 * The list of file names to exclude from the subscriber scan
17 * @private
18 */
19 #excludes: RegExp[] = [
20 /index\.js/,
21 /index\.ts/,
22 /\.DS_Store/,
23 /(\.ts\.map|\.js\.map|\.d\.ts|\.md)/,
24 /^_[^/\\]*(\.[^/\\]+)?$/,
25 ]
26
27 #logger: Logger
28
29 constructor(sourceDir: string | string[], logger?: Logger) {
30 this.#sourceDir = sourceDir
31 this.#logger = logger ?? defaultLogger
32 }
33
34 /**
35 * Load links from the source paths, links are registering themselves,
36 * therefore we only need to import them
37 */
38 async load() {
39 const normalizedSourcePath = Array.isArray(this.#sourceDir)
40 ? this.#sourceDir
41 : [this.#sourceDir]
42
43 const promises = normalizedSourcePath.map(async (sourcePath) => {
44 try {
45 await access(sourcePath)
46 } catch {
47 this.#logger.info(`No link to load from ${sourcePath}. skipped.`)
48 return
49 }
50
51 return await readDirRecursive(sourcePath).then(async (entries) => {
52 const fileEntries = entries.filter((entry: Dirent) => {
53 return (
54 !entry.isDirectory() &&
55 !this.#excludes.some((exclude) => exclude.test(entry.name))
56 )
57 })
58
59 this.#logger.debug(`Registering links from ${sourcePath}.`)
60
61 return await promiseAll(
62 fileEntries.map(async (entry: Dirent) => {
63 const fullPath = join(entry.path, entry.name)
64 return await dynamicImport(fullPath)
65 })
66 )
67 })
68 })
69
70 await promiseAll(promises)
71
72 this.#logger.debug(`Links registered.`)
73 }
74 }