UNPKG

kist

Version:

Lightweight Package Pipeline Processor with Plugin Architecture

84 lines 3.2 kB
import fs from "fs/promises"; import path from "path"; import { Action } from "../../core/pipeline/Action.js"; import packageConfig from "./package.config.js"; export class PackageManagerAction extends Action { async execute(options) { const { packageJsonPath, outputDir, fields = [], customConfig = {}, } = options; if (!packageJsonPath) { throw new Error("The 'packageJsonPath' option is required."); } if (!outputDir) { throw new Error("The 'outputDir' option is required."); } const existingConfig = await this.readPackageJson(packageJsonPath); const filteredConfig = this.filterFields(existingConfig, fields); await this.createPackageJson(outputDir, filteredConfig, customConfig); } async readPackageJson(packageJsonPath) { const fullPath = path.resolve(packageJsonPath); try { const fileContent = await fs.readFile(fullPath, "utf-8"); const parsedContent = JSON.parse(fileContent); this.logInfo(`Successfully read package.json from ${fullPath}`); return parsedContent; } catch (error) { const err = error; if (err.code === "ENOENT") { throw new Error(`File not found at ${fullPath}. Please ensure the path is correct.`); } else if (err.name === "SyntaxError") { throw new Error(`Invalid JSON in ${fullPath}: ${err.message}`); } else { throw new Error(`Unexpected error while reading ${fullPath}: ${err.message ?? String(error)}`); } } } filterFields(config, fields) { if (!fields.length) { return config; } const filteredConfig = {}; for (const field of fields) { if (config[field] !== undefined) { filteredConfig[field] = config[field]; } } this.logInfo(`Filtered package.json fields: ${JSON.stringify(filteredConfig, null, 2)}`); return filteredConfig; } async createPackageJson(outputDir, filteredConfig, customConfig) { const filePath = path.join(outputDir, "package.json"); const finalConfig = { ...packageConfig, ...filteredConfig, ...customConfig, }; const data = JSON.stringify(finalConfig, null, 2); try { await this.ensureDirectoryExists(outputDir); await fs.writeFile(filePath, data, "utf-8"); this.logInfo(`package.json successfully created at ${filePath}`); } catch (error) { this.logError("Error creating package.json", error); throw error; } } async ensureDirectoryExists(dirPath) { try { await fs.mkdir(dirPath, { recursive: true }); } catch (error) { if (error.code !== "EEXIST") { throw error; } } } describe() { return "Reads an existing package.json, extracts selected fields, and creates a new one."; } } //# sourceMappingURL=PackageManagerAction.js.map