UNPKG

kist

Version:

Package Pipeline Processor

162 lines (161 loc) 7.44 kB
"use strict"; // ============================================================================ // Import // ============================================================================ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PackageManagerAction = void 0; const promises_1 = __importDefault(require("fs/promises")); const path_1 = __importDefault(require("path")); const Action_1 = require("../../core/pipeline/Action"); const package_config_js_1 = __importDefault(require("./package.config.js")); // ============================================================================ // Classes // ============================================================================ /** * PackageManagerAction handles reading, validating, and creating `package.json` * files, supporting custom configurations and merging with selected fields. */ class PackageManagerAction extends Action_1.Action { /** * Executes the package management action. * Reads an existing `package.json`, extracts selected fields, and writes a new one. * * @param options - Options specifying input path, output directory, and fields to export. * @returns A Promise that resolves when the action is completed successfully. * @throws {Error} Throws an error if neither `packageJsonPath` nor `outputDir` is provided. */ execute(options) { return __awaiter(this, void 0, void 0, function* () { const { packageJsonPath, outputDir, fields = [], // Specify which fields to copy customConfig = {}, } = options; if (!packageJsonPath) { throw new Error("The 'packageJsonPath' option is required."); } if (!outputDir) { throw new Error("The 'outputDir' option is required."); } const existingConfig = yield this.readPackageJson(packageJsonPath); const filteredConfig = this.filterFields(existingConfig, fields); yield this.createPackageJson(outputDir, filteredConfig, customConfig); }); } /** * Reads and parses an existing `package.json`. * * @param packageJsonPath - Path to the `package.json` file. * @returns Parsed JSON object. * @throws {Error} If the file does not exist or contains invalid JSON. */ readPackageJson(packageJsonPath) { return __awaiter(this, void 0, void 0, function* () { const fullPath = path_1.default.resolve(packageJsonPath); try { const fileContent = yield promises_1.default.readFile(fullPath, "utf-8"); const parsedContent = JSON.parse(fileContent); this.logInfo(`Successfully read package.json from ${fullPath}`); return parsedContent; } catch (error) { if (error.code === "ENOENT") { throw new Error(`File not found at ${fullPath}. Please ensure the path is correct.`); } else if (error.name === "SyntaxError") { throw new Error(`Invalid JSON in ${fullPath}: ${error.message}`); } else { throw new Error(`Unexpected error while reading ${fullPath}: ${error.message}`); } } }); } /** * Filters specified fields from a `package.json` object. * * @param config - The original package.json object. * @param fields - List of fields to extract. * @returns A new object containing only the selected fields. */ filterFields(config, fields) { if (!fields.length) { return config; // If no fields are specified, return the full 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; } /** * Creates a `package.json` file with selected fields and custom overrides. * * @param outputDir - Directory where the new `package.json` will be created. * @param filteredConfig - The filtered package.json fields. * @param customConfig - Custom overrides to apply. * @returns A Promise that resolves when the file has been successfully created. * @throws {Error} If the file cannot be written. */ createPackageJson(outputDir, filteredConfig, customConfig) { return __awaiter(this, void 0, void 0, function* () { const filePath = path_1.default.join(outputDir, "package.json"); // Merge default settings with filtered config and custom overrides const finalConfig = Object.assign(Object.assign(Object.assign({}, package_config_js_1.default), filteredConfig), customConfig); const data = JSON.stringify(finalConfig, null, 2); try { yield this.ensureDirectoryExists(outputDir); yield promises_1.default.writeFile(filePath, data, "utf-8"); this.logInfo(`package.json successfully created at ${filePath}`); } catch (error) { this.logError("Error creating package.json", error); throw error; } }); } /** * Ensures that the specified directory exists, creating it if it does not. * * @param dirPath - The path of the directory to verify or create. * @returns A Promise that resolves once the directory is verified or created. * @throws {Error} If the directory cannot be created. */ ensureDirectoryExists(dirPath) { return __awaiter(this, void 0, void 0, function* () { try { yield promises_1.default.mkdir(dirPath, { recursive: true }); } catch (error) { if (error.code !== "EEXIST") { throw error; } } }); } /** * Provides a description of the action. * * @returns A string description of the action. */ describe() { return "Reads an existing package.json, extracts selected fields, and creates a new one."; } } exports.PackageManagerAction = PackageManagerAction; // ============================================================================ // Export // ============================================================================ // export default PackageManagerAction;