1 import { readdir } from "fs/promises"
2 import { join, normalize } from "path"
3 import { dynamicImport, readDirRecursive } from "../common"
4 import { MedusaPolicySymbol } from "../modules-sdk"
5
6 const excludedFiles = ["index.js", "index.ts"]
7 const excludedExtensions = [".d.ts", ".d.ts.map", ".js.map"]
8
9 function isPolicyExport(value: unknown): boolean {
10 return !!value && typeof value === "object" && MedusaPolicySymbol in value
11 }
12
13 /**
14 * Discover policy definitions from a directory and subdirectories
15 */
16 export async function discoverPoliciesFromDir(
17 sourcePath?: string,
18 maxDepth: number = 2
19 ): Promise<void> {
20 if (!sourcePath) {
21 return
22 }
23
24 const root = normalize(sourcePath)
25
26 const allEntries = await readDirRecursive(root, {
27 ignoreMissing: true,
28 maxDepth,
29 })
30
31 const policyDirs = allEntries
32 .filter((e) => e.isDirectory() && e.name === "policies")
33 .map((e) => join((e as any).path as string, e.name))
34
35 if (!policyDirs.length) {
36 return
37 }
38
39 await Promise.all(
40 policyDirs.map(async (scanDir) => {
41 const entries = await readdir(scanDir, { withFileTypes: true })
42 await Promise.all(
43 entries.map(async (entry) => {
44 if (entry.isDirectory()) {
45 return
46 }
47
48 if (
49 excludedExtensions.some((ext) => entry.name.endsWith(ext)) ||
50 excludedFiles.includes(entry.name)
51 ) {
52 return
53 }
54
55 // Import the file - this will execute definePolicies() calls
56 const fileExports = await dynamicImport(join(scanDir, entry.name))
57
58 // Validate that at least one export is a policy
59 const values = Object.values(fileExports)
60 const hasPolicies = values.some((value) => isPolicyExport(value))
61
62 if (!hasPolicies) {
63 console.warn(
64 `File ${entry.name} in policies directory does not export any policies`
65 )
66 }
67 })
68 )
69 })
70 )
71 }