1 import fs from "fs"
2 import reporter from "../reporter/index"
3 import type { Codemod, CodemodOptions, CodemodResult } from "./types"
4 import { glob } from "glob"
5
6 const CODEMOD: Codemod = {
7 name: "replace-zod-imports",
8 description: "Replace all zod imports with @medusajs/framework/zod imports",
9 run: replaceZodImports,
10 }
11
12 export default CODEMOD
13
14 // Replacement patterns for zod imports
15 // Order matters: more specific patterns must come before general ones
16 const REPLACEMENTS = [
17 // Default import with identifier "zod": import zod from "zod" -> import { z as zod } from "@medusajs/framework/zod"
18 {
19 pattern: /import\s+zod\s+from\s+['"]zod['"]/g,
20 replacement: `import { z as zod } from "@medusajs/framework/zod"`,
21 },
22 // Default import with identifier "z": import z from "zod" -> import { z } from "@medusajs/framework/zod"
23 {
24 pattern: /import\s+z\s+from\s+['"]zod['"]/g,
25 replacement: `import { z } from "@medusajs/framework/zod"`,
26 },
27 // Namespace import with other identifier: import * as something from "zod" -> import { z as something } from "@medusajs/framework/zod"
28 {
29 pattern: /import\s+\*\s+as\s+(\w+)\s+from\s+['"]zod['"]/g,
30 replacement: `import { z as $1 } from "@medusajs/framework/zod"`,
31 },
32 // Named/type imports: import { z } from "zod" or import type { ZodSchema } from "zod"
33 {
34 pattern: /from\s+['"]zod['"]/g,
35 replacement: `from "@medusajs/framework/zod"`,
36 },
37 // CommonJS require: require("zod")
38 {
39 pattern: /require\s*\(\s*['"]zod['"]\s*\)/g,
40 replacement: `require("@medusajs/framework/zod")`,
41 },
42 ]
43
44 const ZOD_IMPORT_PATTERN = /from\s+['"]zod['"]|require\s*\(\s*['"]zod['"]\s*\)/
45
46 /**
47 * Replace all zod imports with @medusajs/framework/zod imports
48 */
49 async function replaceZodImports(
50 options: CodemodOptions
51 ): Promise<CodemodResult> {
52 const { dryRun = false } = options
53 const targetFiles = await getTargetFiles()
54 const numberOfFiles = Object.keys(targetFiles).length
55
56 if (numberOfFiles === 0) {
57 reporter.info(" No files found with zod imports")
58 return { filesScanned: 0, filesModified: 0, errors: 0 }
59 }
60
61 reporter.info(` Found ${numberOfFiles} files to process`)
62
63 let filesModified = 0
64 let errors = 0
65
66 for (const [filePath, content] of Object.entries(targetFiles)) {
67 try {
68 if (processFile(filePath, content, dryRun)) {
69 filesModified++
70 }
71 } catch (error) {
72 reporter.error(`✗ Error processing ${filePath}: ${error.message}`)
73 errors++
74 }
75 }
76
77 return { filesScanned: numberOfFiles, filesModified, errors }
78 }
79
80 /**
81 * Process a single file and replace zod imports
82 * @returns true if the file was modified, false otherwise
83 */
84 function processFile(
85 filePath: string,
86 content: string,
87 dryRun: boolean
88 ): boolean {
89 let modifiedContent = content
90
91 for (const { pattern, replacement } of REPLACEMENTS) {
92 modifiedContent = modifiedContent.replace(pattern, replacement)
93 }
94
95 if (modifiedContent === content) {
96 return false
97 }
98
99 if (dryRun) {
100 reporter.info(` Would update: ${filePath}`)
101 } else {
102 fs.writeFileSync(filePath, modifiedContent)
103 reporter.info(`✓ Updated: ${filePath}`)
104 }
105
106 return true
107 }
108
109 /**
110 * Find all TypeScript/JavaScript files that contain zod imports
111 * @returns Array of file paths with zod imports
112 */
113 async function getTargetFiles(): Promise<Record<string, string>> {
114 try {
115 // Find TypeScript/JavaScript files, excluding build artifacts, dependencies, and src/admin
116 const files = await glob("**/*.{ts,js,tsx,jsx}", {
117 ignore: [
118 "**/node_modules/**",
119 "**/.git/**",
120 "**/dist/**",
121 "**/build/**",
122 "**/coverage/**",
123 "**/.medusa/**",
124 "**/src/admin/**",
125 ],
126 nodir: true,
127 })
128
129 reporter.info(` Scanning ${files.length} files for zod imports...`)
130
131 const targetFiles: Record<string, string> = {}
132 let processedCount = 0
133
134 for (const file of files) {
135 try {
136 const content = fs.readFileSync(file, "utf8")
137
138 if (ZOD_IMPORT_PATTERN.test(content)) {
139 targetFiles[file] = content
140 }
141
142 processedCount++
143 if (processedCount % 100 === 0) {
144 process.stdout.write(
145 `\r Processed ${processedCount}/${files.length} files...`
146 )
147 }
148 } catch {
149 // Skip files that can't be read
150 continue
151 }
152 }
153
154 if (processedCount > 0) {
155 process.stdout.write(
156 `\r Processed ${processedCount} files. \n`
157 )
158 }
159
160 return targetFiles
161 } catch (error) {
162 reporter.error(`Error finding target files: ${error.message}`)
163 return {}
164 }
165 }