// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'node:path';
import { FileSystem, Sort } from '@rushstack/node-core-library';
export class SymlinkAnalyzer {
    constructor(options = {}) {
        // The directory tree discovered so far
        this._nodesByPath = new Map();
        // The symlinks that we encountered while building the directory tree
        this._linkInfosByPath = new Map();
        this._requiredSourceParentPath = options.requiredSourceParentPath;
    }
    async analyzePathAsync(options) {
        const { inputPath, preserveLinks = false, shouldIgnoreExternalLink } = options;
        // First, try to short-circuit the analysis if we've already analyzed this path
        const resolvedPath = path.resolve(inputPath);
        const existingNode = this._nodesByPath.get(resolvedPath);
        if (existingNode) {
            return existingNode;
        }
        // Postfix a '/' to the end of the path. This will get trimmed off later, but it
        // ensures that the last path component is included in the loop below.
        let targetPath = `${resolvedPath}${path.sep}`;
        let targetPathIndex = -1;
        let currentNode;
        while ((targetPathIndex = targetPath.indexOf(path.sep, targetPathIndex + 1)) >= 0) {
            if (targetPathIndex === 0) {
                // Edge case for a Unix path like "/folder/file" --> [ "", "folder", "file" ]
                continue;
            }
            const currentPath = targetPath.slice(0, targetPathIndex);
            currentNode = this._nodesByPath.get(currentPath);
            if (currentNode === undefined) {
                const linkStats = await FileSystem.getLinkStatisticsAsync(currentPath);
                if (linkStats.isSymbolicLink()) {
                    // Link target paths can be relative or absolute, so we need to resolve them
                    const linkTargetPath = await FileSystem.readLinkAsync(currentPath);
                    const resolvedLinkTargetPath = path.resolve(path.dirname(currentPath), linkTargetPath);
                    // Do a check to make sure that the link target path is not outside the source folder
                    if (this._requiredSourceParentPath) {
                        const relativeLinkTargetPath = path.relative(this._requiredSourceParentPath, resolvedLinkTargetPath);
                        if (relativeLinkTargetPath.startsWith('..')) {
                            // Symlinks that link outside of the source folder may be ignored. Check to see if we
                            // can ignore this one and if so, return undefined.
                            if (shouldIgnoreExternalLink === null || shouldIgnoreExternalLink === void 0 ? void 0 : shouldIgnoreExternalLink(currentPath)) {
                                return undefined;
                            }
                            throw new Error(`Symlink targets not under folder "${this._requiredSourceParentPath}": ` +
                                `${currentPath} -> ${resolvedLinkTargetPath}`);
                        }
                    }
                    currentNode = {
                        kind: 'link',
                        nodePath: currentPath,
                        linkStats,
                        linkTarget: resolvedLinkTargetPath
                    };
                }
                else if (linkStats.isDirectory()) {
                    currentNode = {
                        kind: 'folder',
                        nodePath: currentPath,
                        linkStats
                    };
                }
                else if (linkStats.isFile()) {
                    currentNode = {
                        kind: 'file',
                        nodePath: currentPath,
                        linkStats
                    };
                }
                else {
                    throw new Error('Unknown object type: ' + currentPath);
                }
                this._nodesByPath.set(currentPath, currentNode);
            }
            if (!preserveLinks) {
                while ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.kind) === 'link') {
                    const targetNode = await this.analyzePathAsync({
                        inputPath: currentNode.linkTarget,
                        preserveLinks: true
                    });
                    // Have we created an ILinkInfo for this link yet?
                    if (!this._linkInfosByPath.has(currentNode.nodePath)) {
                        // Follow any symbolic links to determine whether the final target is a directory
                        const targetStats = await FileSystem.getStatisticsAsync(targetNode.nodePath);
                        const targetIsDirectory = targetStats.isDirectory();
                        const linkInfo = {
                            kind: targetIsDirectory ? 'folderLink' : 'fileLink',
                            linkPath: currentNode.nodePath,
                            targetPath: targetNode.nodePath
                        };
                        this._linkInfosByPath.set(currentNode.nodePath, linkInfo);
                    }
                    const nodeTargetPath = targetNode.nodePath;
                    const remainingPath = targetPath.slice(targetPathIndex);
                    targetPath = path.join(nodeTargetPath, remainingPath);
                    targetPathIndex = nodeTargetPath.length;
                    currentNode = targetNode;
                }
            }
            if (targetPath.length === targetPathIndex + 1) {
                // We've reached the end of the path
                break;
            }
        }
        if (!currentNode) {
            throw new Error('Unable to analyze path: ' + inputPath);
        }
        return currentNode;
    }
    /**
     * Returns a summary of all the symbolic links encountered by {@link SymlinkAnalyzer.analyzePathAsync}.
     */
    reportSymlinks() {
        const list = [...this._linkInfosByPath.values()];
        Sort.sortBy(list, (x) => x.linkPath);
        return list;
    }
}
//# sourceMappingURL=SymlinkAnalyzer.js.map