import { passthrough } from 'p-transform';
import { isFileStateModified } from 'mem-fs-editor/state';
import { Minimatch } from 'minimatch';
import { Piscina } from 'piscina';
import { getPackageRoot } from '../../../lib/index.js';
import { JS_PRETTIER_EXTENSIONS } from '../../generator-constants.js';
import { addLineNumbers } from '../internal/transform-utils.js';
export const createESLintTransform = function (transformOptions = {}) {
    const { extensions = JS_PRETTIER_EXTENSIONS, ignoreErrors } = transformOptions;
    const minimatch = new Minimatch(`**/*.{${extensions}}`, { dot: true });
    const pool = new Piscina({
        maxThreads: 1,
        filename: new URL('./eslint-worker.js', import.meta.url).href,
    });
    return passthrough(async (file) => {
        if (!minimatch.match(file.path) || !isFileStateModified(file)) {
            return;
        }
        const fileContents = file.contents.toString();
        const { result, error } = await pool.run({
            resolvePluginsRelativeTo: getPackageRoot(),
            filePath: file.path,
            fileContents,
        });
        if (result) {
            file.contents = Buffer.from(result);
        }
        if (error) {
            const errorMessage = `Error parsing file ${file.relative}: ${error} at ${addLineNumbers(fileContents)}`;
            if (!ignoreErrors) {
                throw new Error(errorMessage);
            }
            this?.log?.warn?.(errorMessage);
        }
    }, () => {
        pool.destroy();
    });
};
