import { objectHasOwn, safeCastTo } from "ts-extras";
const isObjectRecord = (value) => typeof value === "object" && value !== null;
const hasCreateFunction = (value) => isObjectRecord(value) && typeof value["create"] === "function";
const createLegacyContextCompat = (context) => new Proxy(context, {
    get: (target, property, receiver) => {
        if (property === "getSourceCode") {
            return () => target.sourceCode;
        }
        if (property === "getFilename") {
            return () => target.filename;
        }
        if (property === "getPhysicalFilename") {
            return () => target.physicalFilename;
        }
        if (property === "getCwd") {
            return () => target.cwd;
        }
        return Reflect.get(target, property, receiver);
    },
});
/**
 * Resolve a rule module from an external ESLint plugin's `rules` map.
 */
export const getExternalRuleFromPlugin = (plugin, ruleName, pluginName) => {
    if (!isObjectRecord(plugin) || !isObjectRecord(plugin["rules"])) {
        throw new TypeError(`Plugin "${pluginName}" does not expose a valid rules map.`);
    }
    const rules = plugin["rules"];
    if (!objectHasOwn(rules, ruleName)) {
        throw new Error(`Rule "${ruleName}" was not found in plugin "${pluginName}".`);
    }
    return rules[ruleName];
};
/**
 * Adapt an external rule so it points docs to this repository.
 */
export const adaptExternalRule = (externalRule, docsUrl) => {
    if (!hasCreateFunction(externalRule)) {
        throw new TypeError("External rule module does not expose create().");
    }
    const externalRuleRecord = externalRule;
    const externalMeta = isObjectRecord(externalRuleRecord["meta"])
        ? externalRuleRecord["meta"]
        : {};
    const externalDocs = isObjectRecord(externalMeta["docs"])
        ? externalMeta["docs"]
        : {};
    const create = (context) => externalRule.create(createLegacyContextCompat(context));
    return {
        ...externalRuleRecord,
        create,
        defaultOptions: Array.isArray(externalRuleRecord["defaultOptions"])
            ? safeCastTo(externalRuleRecord["defaultOptions"])
            : [],
        meta: {
            ...externalMeta,
            docs: {
                ...externalDocs,
                url: docsUrl,
            },
        },
    };
};
//# sourceMappingURL=create-external-rule.js.map