1 import { LoadedModule, PluginDetails } from "@medusajs/types"
2 import { existsSync } from "fs"
3 import fs from "fs/promises"
4 import path from "path"
5 import { promiseAll } from "../common/promise-all"
6 import { MODULE_PACKAGE_NAMES } from "./definition"
7
8 type PackageJson = {
9 name: string
10 exports?: unknown
11 types?: string
12 typings?: string
13 }
14
15 async function readInstalledPackageJson(
16 packageName: string,
17 fromDir: string
18 ): Promise<PackageJson | null> {
19 try {
20 const pkgJsonPath = require.resolve(
21 path.join(packageName, "package.json"),
22 { paths: [fromDir] }
23 )
24 return JSON.parse(await fs.readFile(pkgJsonPath, "utf-8"))
25 } catch {
26 return null
27 }
28 }
29
30 /**
31 * Whether `value` (an `exports` entry) contains a `types` condition, directly
32 * or nested inside other conditions (`import` / `require` / `default` / `node`…).
33 */
34 function hasTypesCondition(value: unknown): boolean {
35 if (!value || typeof value !== "object") {
36 return false
37 }
38 const record = value as Record<string, unknown>
39 if (typeof record.types === "string") {
40 return true
41 }
42 return Object.values(record).some(hasTypesCondition)
43 }
44
45 function exposesRootTypes(pkg: PackageJson): boolean {
46 if (typeof pkg.types === "string" || typeof pkg.typings === "string") {
47 return true
48 }
49
50 const exportsMap = pkg.exports
51 if (exportsMap && typeof exportsMap === "object") {
52 const rootExport = (exportsMap as Record<string, unknown>)["."]
53 if (hasTypesCondition(rootExport)) {
54 return true
55 }
56 }
57 return false
58 }
59
60 function resolvesToTypes(specifier: string, fromDir: string): boolean {
61 try {
62 const resolved = require.resolve(specifier, { paths: [fromDir] })
63 if (/\.d\.[cm]?ts$/.test(resolved)) {
64 return true
65 }
66
67 const declaration = resolved.replace(/\.[cm]?js$/, ".d.ts")
68 return existsSync(declaration)
69 } catch {
70 return false
71 }
72 }
73
74 async function shipsRootTypes(
75 specifier: string,
76 directory: string
77 ): Promise<boolean> {
78 const pkg = await readInstalledPackageJson(specifier, directory)
79 if (pkg && exposesRootTypes(pkg)) {
80 return true
81 }
82
83 return resolvesToTypes(specifier, directory)
84 }
85
86 function isBareSpecifier(specifier: unknown): specifier is string {
87 return (
88 typeof specifier === "string" &&
89 !specifier.startsWith("./") &&
90 !specifier.startsWith("../") &&
91 !path.isAbsolute(specifier)
92 )
93 }
94
95 function getModuleReferenceSpecifier(module: LoadedModule): string | undefined {
96 const definition = module.__definition
97 const resolvePath = definition?.resolvePath
98 const canonical = MODULE_PACKAGE_NAMES[definition?.key]
99
100 if (canonical) {
101 return isBareSpecifier(resolvePath) &&
102 resolvePath.startsWith("@medusajs/medusa/")
103 ? resolvePath
104 : canonical
105 }
106
107 return isBareSpecifier(resolvePath) ? resolvePath : undefined
108 }
109
110 function collectCandidates(
111 plugins: PluginDetails[],
112 modules: Record<string, LoadedModule | LoadedModule[]>
113 ): string[] {
114 const specifiers = new Set<string>()
115
116 for (const plugin of plugins) {
117 specifiers.add(plugin.name)
118 }
119
120 for (const value of Object.values(modules)) {
121 const services = Array.isArray(value) ? value : [value]
122
123 for (const service of services) {
124 const specifier = getModuleReferenceSpecifier(service)
125 if (specifier) {
126 specifiers.add(specifier)
127 }
128 }
129 }
130
131 return Array.from(specifiers)
132 }
133
134 /**
135 * Writes `<directory>/.medusa/types/augmentation-refs.d.ts` with a
136 * `/// <reference types="…" />` directive for each installed plugin and each
137 * loaded core/package module that exposes types.
138 */
139 export async function generateAugmentationRefs({
140 directory,
141 plugins,
142 modules,
143 }: {
144 directory: string
145 plugins: PluginDetails[]
146 modules?: Record<string, LoadedModule | LoadedModule[]>
147 }): Promise<void> {
148 const candidates = collectCandidates(plugins, modules ?? {})
149
150 const checked = await promiseAll(
151 candidates.map(async (resolvePath) => ({
152 resolvePath,
153 shipsTypes: await shipsRootTypes(resolvePath, directory),
154 }))
155 )
156
157 const references = checked
158 .filter((entry) => entry.shipsTypes)
159 .map((entry) => entry.resolvePath)
160
161 const referenceLines = references
162 .map((name) => `/// <reference types="${name}" />`)
163 .join("\n")
164
165 const banner = [
166 "// augmentation-refs.d.ts",
167 "// Auto-generated by Medusa — do not edit manually.",
168 "// Re-generated on `medusa build` and `medusa develop`.",
169 "",
170 ].join("\n")
171
172 const content =
173 references.length > 0
174 ? `${banner}${referenceLines}\n`
175 : `${banner}// No plugin or module type packages detected.\nexport {}\n`
176
177 const outputDir = path.join(directory, ".medusa", "types")
178 await fs.mkdir(outputDir, { recursive: true })
179 await fs.writeFile(
180 path.join(outputDir, "augmentation-refs.d.ts"),
181 content,
182 "utf-8"
183 )
184 }