1 import { isAbsolute } from "path"
2
3 /**
4 * Resolves a module identifier relative to the Medusa project directory
5 * instead of relative to the directory `@medusajs/utils` itself happens to
6 * be installed in.
7 *
8 * @param id - a bare specifier, subpath specifier, or absolute path
9 * @param projectDir - the root directory of the Medusa application
10 * @returns the resolved absolute path, or `id` untouched when it cannot be
11 * resolved from the project. Returning `id` keeps the previous
12 * behaviour (and the previous error message) for callers that pass it
13 * straight to `require`.
14 */
15 export function resolveFromProject(
16 id: string,
17 projectDir: string = process.cwd()
18 ): string {
19 if (isAbsolute(id)) {
20 return id
21 }
22
23 try {
24 return require.resolve(id, { paths: [projectDir] })
25 } catch (error) {
26 if (
27 error?.code !== "MODULE_NOT_FOUND" &&
28 error?.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED"
29 ) {
30 throw error
31 }
32
33 /**
34 * Fall back to the default resolution algorithm so anything reachable from
35 * `@medusajs/utils` itself (for example when Medusa is executed from
36 * outside the project directory) keeps resolving.
37 */
38 return id
39 }
40 }