function wildcardMatch(value, pattern) {
    if (pattern === "*")
        return true;
    const regexStr = pattern
        .replace(/[.+^${}()|[\]\\]/g, "\\$&")
        .replace(/\*/g, ".*")
        .replace(/\?/g, ".");
    try {
        return new RegExp(`^${regexStr}$`, "i").test(value);
    }
    catch {
        return value === pattern;
    }
}
export function evaluate(permission, pattern, ...rulesets) {
    const allRules = rulesets.flat();
    let matched;
    for (let i = allRules.length - 1; i >= 0; i--) {
        const rule = allRules[i];
        if (wildcardMatch(permission, rule.permission) && wildcardMatch(pattern, rule.pattern)) {
            matched = rule;
            break;
        }
    }
    return matched ?? { action: "allow", permission, pattern: "*" };
}
export function merge(...rulesets) {
    return rulesets.flat();
}
export function toRuleset(config) {
    const rules = [];
    for (const [key, value] of Object.entries(config)) {
        if (value === "allow" || value === "deny" || value === "ask") {
            rules.push({ permission: key, pattern: "*", action: value });
        }
        else if (typeof value === "object" && value !== null) {
            for (const [pattern, action] of Object.entries(value)) {
                if (action === "allow" || action === "deny" || action === "ask") {
                    rules.push({ permission: key, pattern, action });
                }
            }
        }
    }
    return rules;
}
//# sourceMappingURL=evaluate.js.map