|
| 1 | +/** |
| 2 | + * Temporary Dependencies Shifter for Type Generation |
| 3 | + * |
| 4 | + * This script temporarily moves zod and zodex from 'dependencies' to 'devDependencies' |
| 5 | + * during the build process to allow tsup's --dts-resolve flag to properly include |
| 6 | + * their types in the generated declaration files. |
| 7 | + * |
| 8 | + * What this script does: |
| 9 | + * 1. Creates a backup of the original package.json file |
| 10 | + * 2. Moves zod and zodex from dependencies to devDependencies |
| 11 | + * 3. Runs tsup with --dts-resolve flag (plus any additional arguments) |
| 12 | + * 4. Restores package.json from the backup file |
| 13 | + * |
| 14 | + * Usage: |
| 15 | + * npx tsx build-with-types.ts [additional tsup arguments] |
| 16 | + * |
| 17 | + * Example: |
| 18 | + * npx tsx build-with-types.ts --minify --sourcemap |
| 19 | + */ |
| 20 | +import { execSync } from 'node:child_process'; |
| 21 | +import { |
| 22 | + copyFileSync, |
| 23 | + existsSync, |
| 24 | + readFileSync, |
| 25 | + unlinkSync, |
| 26 | + writeFileSync, |
| 27 | +} from 'node:fs'; |
| 28 | +import { join } from 'node:path'; |
| 29 | + |
| 30 | +// Dependencies that need to be temporarily moved for proper type generation |
| 31 | +const DEPENDENCIES_TO_MOVE = ['zod', 'zodex']; |
| 32 | + |
| 33 | +// Path to package.json |
| 34 | +const PACKAGE_JSON_PATH = join(process.cwd(), 'package.json'); |
| 35 | +const BACKUP_FILE_PATH = join(process.cwd(), 'package.json.bak'); |
| 36 | + |
| 37 | +// Default tsup command |
| 38 | +const DEFAULT_TSUP_ARGS = '--dts-resolve'; |
| 39 | + |
| 40 | +interface PackageJson { |
| 41 | + dependencies?: Record<string, string>; |
| 42 | + devDependencies?: Record<string, string>; |
| 43 | + [key: string]: unknown; |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Creates a backup of the package.json file |
| 48 | + */ |
| 49 | +function createBackup(): void { |
| 50 | + console.log('\n📦 STEP 1: Creating backup of package.json...'); |
| 51 | + |
| 52 | + try { |
| 53 | + copyFileSync(PACKAGE_JSON_PATH, BACKUP_FILE_PATH); |
| 54 | + console.log('✅ Backup created successfully at package.json.bak'); |
| 55 | + } catch (error) { |
| 56 | + console.error('❌ Failed to create backup file!'); |
| 57 | + throw error; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Temporarily moves specified dependencies to devDependencies |
| 63 | + * to enable proper type generation with tsup --dts-resolve |
| 64 | + * @returns {boolean} True if changes were made to package.json |
| 65 | + */ |
| 66 | +function temporarilyMoveZodDependencies(): boolean { |
| 67 | + console.log( |
| 68 | + '\n📦 STEP 2: Moving dependencies to devDependencies for type generation...', |
| 69 | + ); |
| 70 | + |
| 71 | + // Read package.json |
| 72 | + const packageJsonContent = readFileSync(PACKAGE_JSON_PATH, 'utf8'); |
| 73 | + const packageJson: PackageJson = JSON.parse(packageJsonContent); |
| 74 | + |
| 75 | + // Check if there are dependencies to process |
| 76 | + if (!packageJson.dependencies) { |
| 77 | + console.log('⚠️ No dependencies found in package.json.'); |
| 78 | + return false; |
| 79 | + } |
| 80 | + |
| 81 | + // Ensure devDependencies exists |
| 82 | + if (!packageJson.devDependencies) { |
| 83 | + packageJson.devDependencies = {}; |
| 84 | + } |
| 85 | + |
| 86 | + // Track if we made any changes |
| 87 | + let hasChanges = false; |
| 88 | + |
| 89 | + // Process each target dependency using array methods instead of loops |
| 90 | + DEPENDENCIES_TO_MOVE.forEach((depName) => { |
| 91 | + if (packageJson.dependencies?.[depName]) { |
| 92 | + // Store the version |
| 93 | + const version = packageJson.dependencies[depName]; |
| 94 | + |
| 95 | + // Move to devDependencies |
| 96 | + console.log(`📦 Moving ${depName}@${version} to devDependencies`); |
| 97 | + // @ts-expect-error this is oks |
| 98 | + packageJson.devDependencies[depName] = version; |
| 99 | + |
| 100 | + // Remove from dependencies |
| 101 | + delete packageJson.dependencies[depName]; |
| 102 | + |
| 103 | + hasChanges = true; |
| 104 | + } else { |
| 105 | + console.log( |
| 106 | + `ℹ️ Dependency ${depName} not found in dependencies, skipping.`, |
| 107 | + ); |
| 108 | + } |
| 109 | + }); |
| 110 | + |
| 111 | + // Remove dependencies section if empty |
| 112 | + if ( |
| 113 | + packageJson.dependencies && |
| 114 | + Object.keys(packageJson.dependencies).length === 0 |
| 115 | + ) { |
| 116 | + delete packageJson.dependencies; |
| 117 | + } |
| 118 | + |
| 119 | + if (!hasChanges) { |
| 120 | + console.log('ℹ️ No changes were needed.'); |
| 121 | + return false; |
| 122 | + } |
| 123 | + |
| 124 | + // Write updated package.json |
| 125 | + writeFileSync( |
| 126 | + PACKAGE_JSON_PATH, |
| 127 | + `${JSON.stringify(packageJson, null, 2)}\n`, |
| 128 | + 'utf8', |
| 129 | + ); |
| 130 | + |
| 131 | + console.log('✅ Successfully moved dependencies to devDependencies!'); |
| 132 | + return true; |
| 133 | +} |
| 134 | + |
| 135 | +/** |
| 136 | + * Runs the tsup build command with the specified arguments |
| 137 | + * @param {string[]} additionalArgs Additional arguments to pass to tsup |
| 138 | + */ |
| 139 | +function runTsupBuild(additionalArgs: string[] = []): void { |
| 140 | + console.log('\n🔨 STEP 3: Running tsup build with type resolution...'); |
| 141 | + |
| 142 | + const tsupArgs = [DEFAULT_TSUP_ARGS, ...additionalArgs] |
| 143 | + .filter(Boolean) |
| 144 | + .join(' '); |
| 145 | + const command = `npx tsup ${tsupArgs}`; |
| 146 | + |
| 147 | + console.log(`🔄 Executing: ${command}`); |
| 148 | + |
| 149 | + try { |
| 150 | + // Run tsup with stdio inherited so the user can see the build output |
| 151 | + execSync(command, { stdio: 'inherit' }); |
| 152 | + console.log('✅ Build completed successfully!'); |
| 153 | + } catch (error) { |
| 154 | + console.error('❌ Build failed!'); |
| 155 | + throw error; |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +/** |
| 160 | + * Restores the original package.json from backup |
| 161 | + */ |
| 162 | +function restoreFromBackup(): void { |
| 163 | + console.log('\n🔄 STEP 4: Restoring package.json from backup...'); |
| 164 | + |
| 165 | + try { |
| 166 | + copyFileSync(BACKUP_FILE_PATH, PACKAGE_JSON_PATH); |
| 167 | + console.log('✅ Original package.json restored successfully!'); |
| 168 | + |
| 169 | + // Clean up the backup file |
| 170 | + unlinkSync(BACKUP_FILE_PATH); |
| 171 | + console.log('🧹 Backup file removed.'); |
| 172 | + } catch (error) { |
| 173 | + console.error('❌ Failed to restore from backup!'); |
| 174 | + console.error( |
| 175 | + ` Please manually restore by copying ${BACKUP_FILE_PATH} to ${PACKAGE_JSON_PATH}`, |
| 176 | + ); |
| 177 | + throw error; |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +/** |
| 182 | + * Main function |
| 183 | + */ |
| 184 | +function main(): void { |
| 185 | + try { |
| 186 | + console.log( |
| 187 | + '🚀 Starting Temporary Dependencies Shifter for Type Generation', |
| 188 | + ); |
| 189 | + |
| 190 | + // Get any additional tsup arguments from command line |
| 191 | + const additionalTsupArgs = process.argv.slice(2); |
| 192 | + |
| 193 | + // Step 1: Create backup |
| 194 | + createBackup(); |
| 195 | + |
| 196 | + // Step 2: Move dependencies |
| 197 | + const changesMade = temporarilyMoveZodDependencies(); |
| 198 | + |
| 199 | + // Step 3: Run tsup build |
| 200 | + runTsupBuild(additionalTsupArgs); |
| 201 | + |
| 202 | + // Step 4: Restore package.json from backup (only if we made changes) |
| 203 | + if (changesMade) { |
| 204 | + restoreFromBackup(); |
| 205 | + } else { |
| 206 | + console.log( |
| 207 | + '\n🔄 STEP 4: No changes were made to package.json, but cleaning up backup file...', |
| 208 | + ); |
| 209 | + // Clean up the backup file even if no changes were made |
| 210 | + if (existsSync(BACKUP_FILE_PATH)) { |
| 211 | + unlinkSync(BACKUP_FILE_PATH); |
| 212 | + console.log('🧹 Backup file removed.'); |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + console.log('\n✨ Build process completed successfully!'); |
| 217 | + } catch (error) { |
| 218 | + console.error( |
| 219 | + '\n❌ Build process failed:', |
| 220 | + error instanceof Error ? error.message : String(error), |
| 221 | + ); |
| 222 | + |
| 223 | + // Make sure the user knows they can restore from backup in case of failure |
| 224 | + if (existsSync(BACKUP_FILE_PATH)) { |
| 225 | + console.error( |
| 226 | + `\n💡 A backup exists at ${BACKUP_FILE_PATH}. You can restore it by running:`, |
| 227 | + ); |
| 228 | + console.error(` cp ${BACKUP_FILE_PATH} ${PACKAGE_JSON_PATH}`); |
| 229 | + } |
| 230 | + |
| 231 | + process.exit(1); |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +// Execute the script |
| 236 | +main(); |
0 commit comments