|
| 1 | +import { |
| 2 | + CodifyCliSender, |
| 3 | + CreatePlan, |
| 4 | + DestroyPlan, |
| 5 | + ModifyPlan, |
| 6 | + ParameterChange, |
| 7 | + RefreshContext, |
| 8 | + Resource, |
| 9 | + ResourceSettings |
| 10 | +} from 'codify-plugin-lib'; |
| 11 | +import { ResourceConfig } from 'codify-schemas'; |
| 12 | +import { createHash } from 'node:crypto'; |
| 13 | +import * as fsSync from 'node:fs'; |
| 14 | +import fs from 'node:fs/promises'; |
| 15 | +import path from 'node:path'; |
| 16 | +import { Readable } from 'node:stream'; |
| 17 | +import { finished } from 'node:stream/promises'; |
| 18 | +import trash from 'trash'; |
| 19 | + |
| 20 | +import { FileUtils } from '../../utils/file-utils.js'; |
| 21 | +import schema from './remote-file-schema.json' |
| 22 | + |
| 23 | +export interface FileConfig extends ResourceConfig{ |
| 24 | + path: string; |
| 25 | + remote?: string; |
| 26 | + hash?: string; |
| 27 | + onlyCreate: boolean; |
| 28 | +} |
| 29 | + |
| 30 | +export class RemoteFileResource extends Resource<FileConfig> { |
| 31 | + getSettings(): ResourceSettings<FileConfig> { |
| 32 | + return { |
| 33 | + id: 'remote-file', |
| 34 | + allowMultiple: true, |
| 35 | + schema, |
| 36 | + parameterSettings: { |
| 37 | + path: { type: 'directory' }, |
| 38 | + remote: { type: 'string', canModify: true }, |
| 39 | + onlyCreate: { type: 'boolean', setting: true, default: false }, |
| 40 | + hash: { type: 'string', canModify: true }, |
| 41 | + }, |
| 42 | + transformation: { |
| 43 | + to: async (input: Partial<FileConfig>) => { |
| 44 | + if (this.isRemoteCodifyFile(input.remote!)) { |
| 45 | + return this.getRemoteCodifyFileConfig(input) |
| 46 | + } |
| 47 | + |
| 48 | + return input; |
| 49 | + }, |
| 50 | + from: async (input: Partial<FileConfig>) => input, |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + async refresh(parameters: Partial<FileConfig>, context: RefreshContext<FileConfig>): Promise<Partial<FileConfig> | null> { |
| 56 | + if (!parameters.path) { |
| 57 | + throw new Error('Path must be specified'); |
| 58 | + } |
| 59 | + |
| 60 | + if (!(await FileUtils.exists(parameters.path))) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | + const current = await fs.readFile(parameters.path, 'utf8'); |
| 65 | + const currentHash = createHash('md5').update(current).digest('hex'); |
| 66 | + |
| 67 | + return { |
| 68 | + ...parameters, |
| 69 | + hash: parameters.onlyCreate ? parameters.hash : currentHash, |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + async create(plan: CreatePlan<FileConfig>): Promise<void> { |
| 74 | + return this.updateCodifyFile(plan.desiredConfig); |
| 75 | + } |
| 76 | + |
| 77 | + async modify(pc: ParameterChange<FileConfig>, plan: ModifyPlan<FileConfig>): Promise<void> { |
| 78 | + return this.updateCodifyFile(plan.desiredConfig); |
| 79 | + } |
| 80 | + |
| 81 | + destroy(plan: DestroyPlan<FileConfig>): Promise<void> { |
| 82 | + return trash(plan.currentConfig.path); |
| 83 | + } |
| 84 | + |
| 85 | + private async updateCodifyFile(config: FileConfig) { |
| 86 | + const { path: filePath, remote } = config; |
| 87 | + const resolvedPath = path.resolve(filePath); |
| 88 | + |
| 89 | + if (!(await FileUtils.dirExists(path.dirname(resolvedPath)))) { |
| 90 | + await fs.mkdir(path.dirname(resolvedPath), { recursive: true }); |
| 91 | + } |
| 92 | + |
| 93 | + if (this.isRemoteCodifyFile(remote!)) { |
| 94 | + const { documentId, fileId } = this.extractCodifyFileInfo(remote!); |
| 95 | + const fileStream = fsSync.createWriteStream(filePath, { flags: 'wx' }); |
| 96 | + |
| 97 | + const credentials = await CodifyCliSender.getCodifyCliCredentials(); |
| 98 | + const response = await fetch(`https://api.codifycli.com/v1/documents/${documentId}/file/${fileId}`, { |
| 99 | + method: 'GET', |
| 100 | + headers: { |
| 101 | + 'Authorization': `Bearer ${credentials}`, |
| 102 | + }, |
| 103 | + }); |
| 104 | + |
| 105 | + if (!response.ok) { |
| 106 | + throw new Error(`Unable to fetch file ${remote}, ${await response.text()}`); |
| 107 | + } |
| 108 | + |
| 109 | + console.log(`Updating file ${filePath} with contents from ${remote}`); |
| 110 | + await finished(Readable.fromWeb(response.body as any).pipe(fileStream)); |
| 111 | + } else { |
| 112 | + console.log(`Updating file ${filePath} with contents`); |
| 113 | + await fs.writeFile(filePath, remote ?? ''); |
| 114 | + } |
| 115 | + |
| 116 | + console.log(`Finished updating file ${filePath}`); |
| 117 | + } |
| 118 | + |
| 119 | + private isRemoteCodifyFile(contents: string) { |
| 120 | + return contents?.startsWith('codify://'); |
| 121 | + } |
| 122 | + |
| 123 | + private async getRemoteCodifyFileConfig(parameters: Partial<FileConfig>): Promise<Partial<FileConfig>> { |
| 124 | + const { documentId, fileId } = this.extractCodifyFileInfo(parameters.remote!); |
| 125 | + |
| 126 | + const credentials = await CodifyCliSender.getCodifyCliCredentials(); |
| 127 | + const response = await fetch((`https://api.codifycli.com/v1/documents/${documentId}/file/${fileId}/hash`), { |
| 128 | + method: 'GET', |
| 129 | + headers: { |
| 130 | + 'Authorization': `Bearer ${credentials}`, |
| 131 | + }, |
| 132 | + }); |
| 133 | + |
| 134 | + if (!response.ok) { |
| 135 | + return { |
| 136 | + ...parameters, |
| 137 | + hash: undefined, |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + const data = await response.json(); |
| 142 | + |
| 143 | + return { |
| 144 | + ...parameters, |
| 145 | + hash: data.hash, |
| 146 | + }; |
| 147 | + } |
| 148 | + |
| 149 | + private extractCodifyFileInfo(url: string) { |
| 150 | + const regex = /codify:\/\/(.*):(.*)/ |
| 151 | + |
| 152 | + const [, group1, group2] = regex.exec(url) ?? []; |
| 153 | + if (!group1 || !group2) { |
| 154 | + throw new Error(`Invalid codify url ${url} for file`); |
| 155 | + } |
| 156 | + |
| 157 | + return { |
| 158 | + documentId: group1, |
| 159 | + fileId: group2, |
| 160 | + } |
| 161 | + } |
| 162 | +} |
0 commit comments