|
| 1 | +import fs from 'fs-extra'; |
| 2 | +import ora from 'ora'; |
| 3 | +import chalk from 'chalk'; |
| 4 | +import path from 'path'; |
| 5 | + |
| 6 | +interface MarketPlaceEntry { |
| 7 | + id: string; |
| 8 | + slug: string; |
| 9 | + description: string; |
| 10 | + status: string; |
| 11 | + tags: string[]; |
| 12 | + type: 'OPTIMIZATION' | 'MIGRATION'; |
| 13 | + transformId: string; |
| 14 | + transform: Transform; |
| 15 | +} |
| 16 | + |
| 17 | +interface Transform { |
| 18 | + author: { image: string; name: string }; |
| 19 | + id: string; |
| 20 | + name: string; |
| 21 | + sources: Source[]; |
| 22 | +} |
| 23 | + |
| 24 | +interface Source { |
| 25 | + id: string; |
| 26 | + name: string; |
| 27 | + code: string; |
| 28 | +} |
| 29 | + |
| 30 | +function writeSourceFiles(slug: string, transform: Transform, dir: string) { |
| 31 | + transform.sources.forEach(source => { |
| 32 | + const filePath = path.join(dir, slug, source.name); |
| 33 | + fs.outputFileSync(filePath, source.code); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +export async function fetchHmPkg(slug: string, dir: string) { |
| 38 | + const spinner = ora( |
| 39 | + `${chalk.green('Attempting to download Hypermod transform:')} ${slug}`, |
| 40 | + ).start(); |
| 41 | + |
| 42 | + let marketplaceEntry: MarketPlaceEntry; |
| 43 | + |
| 44 | + try { |
| 45 | + // @ts-expect-error |
| 46 | + marketplaceEntry = await fetch( |
| 47 | + `https://www.hypermod.io/api/cli/transforms/${slug.replace('hm-', '')}`, |
| 48 | + ).then((res: any) => { |
| 49 | + if (res.status === 404) { |
| 50 | + throw new Error(`Transform not found: ${slug}`); |
| 51 | + } |
| 52 | + |
| 53 | + if (!res.ok) { |
| 54 | + throw new Error(`Error fetching transform: ${res.statusText}`); |
| 55 | + } |
| 56 | + |
| 57 | + return res.json(); |
| 58 | + }); |
| 59 | + |
| 60 | + spinner.succeed( |
| 61 | + `${chalk.green( |
| 62 | + 'Found Hypermod transform:', |
| 63 | + )} https://www.hypermod.io/explore/${slug}`, |
| 64 | + ); |
| 65 | + } catch (error) { |
| 66 | + spinner.fail(`${chalk.red('Unable to fetch Hypermod transform:')} ${slug}`); |
| 67 | + throw new Error(`Unable to locate Hypermod transform: ${slug}\n${error}`); |
| 68 | + } |
| 69 | + |
| 70 | + writeSourceFiles(slug, marketplaceEntry.transform, dir); |
| 71 | + |
| 72 | + return marketplaceEntry; |
| 73 | +} |
0 commit comments