UNPKG

@yeoman/transform

Version:

Namespace parsing for yeoman's generator/environment stack

73 lines 2.35 kB
import { Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { Minimatch } from 'minimatch'; export { pipeline } from 'node:stream/promises'; export const filePipeline = async (source, transforms, options) => pipeline(source, ...transforms, ...(options ? [options] : [])); /** * The returned file from transform function is passed through if any. */ export function transform(function_) { return new Transform({ objectMode: true, async transform(chunk, _encoding, callback) { try { callback(undefined, await function_.call(this, chunk)); } catch (error) { callback(error); } }, }); } /** * Files will always be passed through. */ export function passthrough(function_, options = {}) { if (!function_) { return transform(f => f); } const { filter, pattern, patternOptions } = options; let patternFilter = () => true; if (pattern) { const minimatch = new Minimatch(pattern, patternOptions); patternFilter = (file) => minimatch.match(file.path); } return transform(async (file) => { if (filter && !filter(file)) { return file; } if (await patternFilter(file)) { await function_(file); } return file; }); } export function transformFileField(field, fieldValue, options) { if (typeof fieldValue === 'function') { return passthrough(async (file) => { file[field] = await fieldValue(file[field], file); }, options); } return passthrough(async (file) => { file[field] = fieldValue; }, options); } export function transformContents(function_, options) { return transformFileField('contents', function_, options); } /** * Filter file. * Files that doesn't match the filter condition are removed. */ export function filter(filter) { return transform(async (file) => ((await filter(file)) ? file : undefined)); } /** * Conditional filter on pattern. * Files that doesn't match the pattern are removed. */ export function filterPattern(pattern, options = {}) { const minimatch = new Minimatch(pattern, options.patternOptions); return filter(file => minimatch.match(file.path)); } //# sourceMappingURL=transform.js.map