(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "n8n-workflow"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalizeParameterPath = normalizeParameterPath;
    exports.toDynamicParameterPath = toDynamicParameterPath;
    exports.findNodeParameterProperty = findNodeParameterProperty;
    exports.getDynamicNodeParameterLookup = getDynamicNodeParameterLookup;
    exports.collectDynamicNodeParameterPaths = collectDynamicNodeParameterPaths;
    exports.getRequiredNodeCredentialSlots = getRequiredNodeCredentialSlots;
    exports.hasNodeCredentials = hasNodeCredentials;
    exports.toResourceLocatorParameterValue = toResourceLocatorParameterValue;
    exports.toLoadedOptionParameterValue = toLoadedOptionParameterValue;
    exports.detectAuthenticationParameterValue = detectAuthenticationParameterValue;
    exports.formatResourceLocatorOptionsForLLM = formatResourceLocatorOptionsForLLM;
    const n8n_workflow_1 = require("n8n-workflow");
    function normalizeParameterPath(path) {
        return path
            .replace(/^parameters\./, '')
            .split('.')
            .filter((part) => part.length > 0)
            .join('.');
    }
    function toDynamicParameterPath(parameterPath) {
        return `parameters.${normalizeParameterPath(parameterPath)}`;
    }
    function isPropertyOption(item) {
        return !(0, n8n_workflow_1.isINodeProperties)(item) && !(0, n8n_workflow_1.isINodePropertyCollection)(item);
    }
    function findPropertyInProperty(property, pathParts) {
        const options = property.options;
        if (!Array.isArray(options))
            return null;
        return findPropertyInItems(options, pathParts);
    }
    function findPropertyInItems(items, pathParts) {
        if (pathParts.length === 0)
            return null;
        for (const item of items) {
            if (isPropertyOption(item))
                continue;
            if ((0, n8n_workflow_1.isINodePropertyCollection)(item)) {
                if (item.name === pathParts[0]) {
                    const nested = findPropertyInItems(item.values, pathParts.slice(1));
                    if (nested)
                        return nested;
                }
                const nested = findPropertyInItems(item.values, pathParts);
                if (nested)
                    return nested;
                continue;
            }
            if (item.name === pathParts[0]) {
                if (pathParts.length === 1)
                    return item;
                const nested = findPropertyInProperty(item, pathParts.slice(1));
                if (nested)
                    return nested;
            }
            const nested = findPropertyInProperty(item, pathParts);
            if (nested)
                return nested;
        }
        return null;
    }
    function findNodeParameterProperty(properties, parameterPath) {
        return findPropertyInItems(properties, normalizeParameterPath(parameterPath).split('.'));
    }
    function getDynamicNodeParameterLookup(property) {
        if (property.type === 'resourceLocator') {
            const listMode = property.modes?.find((mode) => mode.type === 'list' && mode.typeOptions?.searchListMethod);
            if (listMode?.typeOptions?.searchListMethod) {
                return {
                    kind: 'resourceLocator',
                    methodName: listMode.typeOptions.searchListMethod,
                    mode: listMode.name,
                    skipCredentialsCheck: listMode.typeOptions.skipCredentialsCheckInRLC === true,
                };
            }
        }
        if (property.typeOptions?.loadOptionsMethod) {
            return {
                kind: 'loadOptionsMethod',
                methodName: property.typeOptions.loadOptionsMethod,
                skipCredentialsCheck: false,
            };
        }
        if (property.typeOptions?.loadOptions) {
            return {
                kind: 'loadOptionsRouting',
                loadOptions: property.typeOptions.loadOptions,
                skipCredentialsCheck: false,
            };
        }
        return null;
    }
    function collectDynamicNodeParameterPaths(items, prefix = []) {
        const out = [];
        for (const item of items) {
            if (isPropertyOption(item))
                continue;
            if ((0, n8n_workflow_1.isINodePropertyCollection)(item)) {
                out.push(...collectDynamicNodeParameterPaths(item.values, [...prefix, item.name]));
                continue;
            }
            const path = [...prefix, item.name].join('.');
            const lookup = getDynamicNodeParameterLookup(item);
            if (lookup) {
                out.push({
                    path,
                    type: item.type,
                    method: lookup.kind === 'loadOptionsRouting' ? 'loadOptions.routing' : lookup.methodName,
                });
            }
            if (Array.isArray(item.options)) {
                out.push(...collectDynamicNodeParameterPaths(item.options, [...prefix, item.name]));
            }
        }
        return out;
    }
    function getRequiredNodeCredentialSlots(nodeType) {
        return (nodeType.credentials ?? [])
            .filter((credential) => credential.required !== false)
            .map((credential) => ({
            credentialType: credential.name,
            credentialSlot: credential.name,
            ...(credential.displayName ? { displayName: credential.displayName } : {}),
        }));
    }
    function hasNodeCredentials(credentials) {
        return credentials !== undefined && Object.keys(credentials).length > 0;
    }
    function toResourceLocatorParameterValue(option, mode) {
        const value = typeof option.value === 'boolean' ? String(option.value) : option.value;
        return {
            __rl: true,
            mode,
            value,
            cachedResultName: option.name,
            ...(option.url ? { cachedResultUrl: option.url } : {}),
        };
    }
    function toLoadedOptionParameterValue(option) {
        return option.value;
    }
    function detectAuthenticationParameterValue(nodeDesc, credentialType) {
        const authProp = nodeDesc.properties.find((p) => p.name === 'authentication');
        if (!authProp?.options)
            return undefined;
        for (const opt of authProp.options) {
            if (typeof opt === 'object' && 'value' in opt && typeof opt.value === 'string') {
                const credTypes = nodeDesc.credentials
                    ?.filter((c) => {
                    const show = c.displayOptions?.show?.authentication;
                    return Array.isArray(show) && show.includes(opt.value);
                })
                    .map((c) => c.name);
                if (credTypes?.includes(credentialType)) {
                    return opt.value;
                }
            }
        }
        return undefined;
    }
    function escapeXmlText(value) {
        return value
            .replaceAll('&', '&amp;')
            .replaceAll('<', '&lt;')
            .replaceAll('>', '&gt;')
            .replaceAll('"', '&quot;')
            .replaceAll("'", '&apos;');
    }
    function formatResourceLocatorOptionsForLLM(options, parameterPath) {
        if (options.length === 0) {
            return `No options available for parameter "${parameterPath}". The resource may require credentials to be set up first or the external service returned no results.`;
        }
        const parts = [
            `<resource_locator_options parameter="${escapeXmlText(parameterPath)}">`,
            `<total_count>${options.length}</total_count>`,
            '<options>',
        ];
        options.forEach((opt, index) => {
            parts.push(`  <option index="${index}">`);
            parts.push(`    <display_name>${escapeXmlText(opt.name)}</display_name>`);
            parts.push(`    <id>${escapeXmlText(String(opt.value))}</id>`);
            parts.push('  </option>');
        });
        parts.push('</options>');
        parts.push('</resource_locator_options>');
        return parts.join('\n');
    }
});
//# sourceMappingURL=dynamic-node-parameters.js.map