|
| 1 | +import * as fsSync from 'node:fs'; |
1 | 2 | import * as fs from 'node:fs/promises'; |
| 3 | +import path from 'node:path'; |
| 4 | +import { Readable } from 'node:stream'; |
| 5 | +import { finished } from 'node:stream/promises'; |
2 | 6 |
|
3 | 7 | import { Plugin } from './entities/plugin.js'; |
4 | 8 |
|
5 | | -const DEFAULT_PLUGIN_REGEX = /(?<=default:).*$/g |
| 9 | +const DEFAULT_PLUGIN_URL = 'https://codify-plugin-library.s3.amazonaws.com/codify-core/index.js'; |
| 10 | +const DEFAULT_PLUGIN_REGEX = /(?<=default).*$/g |
| 11 | +const PLUGIN_CACHE_DIR = '/Library/Caches/codify/plugins' |
6 | 12 |
|
7 | 13 | export class PluginResolver { |
8 | 14 |
|
9 | | - static async resolve(name: string, version: string): Promise<Plugin> { |
| 15 | + static async resolve(name: string, version?: string): Promise<Plugin> { |
| 16 | + await PluginResolver.checkAndCreateCacheDirIfNotExists() |
10 | 17 |
|
| 18 | + // TODO: Add plugin versioning in the future |
11 | 19 | if (DEFAULT_PLUGIN_REGEX.test(name)) { |
12 | | - return this.resolveDefaultPlugin(name, version) |
| 20 | + return this.resolveDefaultPlugin() |
13 | 21 | } |
14 | 22 |
|
15 | 23 | throw new Error(`Unable to resolve plugin of name: ${name} and version: ${version}`) |
16 | 24 | } |
17 | 25 |
|
18 | | - // TODO: update this method to resolve default plugins from github in the future. |
19 | | - private static async resolveDefaultPlugin(name: string, _version: string): Promise<Plugin> { |
20 | | - const pluginName = name.match(DEFAULT_PLUGIN_REGEX)![0] |
| 26 | + private static async resolveDefaultPlugin(): Promise<Plugin> { |
21 | 27 |
|
22 | | - const defaultPluginDir = '/Users/kevinwang/Projects/codify/plugins'; |
23 | | - const pluginDirFiles = await fs.readdir(defaultPluginDir); |
24 | | - if (!pluginDirFiles.includes(pluginName)) { |
25 | | - throw new Error(`Unable to find default plugin: ${name}`) |
| 28 | + const { body } = await fetch(DEFAULT_PLUGIN_URL) |
| 29 | + if (!body) { |
| 30 | + throw new Error('Un-able to fetch default plugin. Body was null'); |
26 | 31 | } |
27 | 32 |
|
28 | | - return Plugin.create(defaultPluginDir, pluginName); |
| 33 | + const fileUrl = path.join(PLUGIN_CACHE_DIR, 'default.js'); |
| 34 | + const ws = fsSync.createWriteStream(fileUrl) |
| 35 | + |
| 36 | + // Different type definitions here for readable stream (NodeJS vs DOM). Small hack to fix that |
| 37 | + await finished(Readable.fromWeb(body as never).pipe(ws)); |
| 38 | + |
| 39 | + return new Plugin({ |
| 40 | + directory: fileUrl, |
| 41 | + name: 'default', |
| 42 | + }) |
29 | 43 | } |
30 | 44 |
|
| 45 | + private static async checkAndCreateCacheDirIfNotExists() { |
| 46 | + if (!(await fs.stat(PLUGIN_CACHE_DIR))) { |
| 47 | + await fs.mkdir(PLUGIN_CACHE_DIR); |
| 48 | + } |
| 49 | + } |
31 | 50 | } |
0 commit comments