"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.BranchCommitEnricher = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../util/index.js");
/**
 * Utility for enriching commits from a {@link Branch} before these commits are applied and submitted.
 */
class BranchCommitEnricher {
    constructor(enricher) {
        this.enricher = enricher;
        /**
         * Maps each local commit to the corresponding enriched change.
         * @remarks
         * Entries are added when the commits are {@link BranchCommitEnricher.prepareChanges | prepared}.
         * Each entry is removed when it is {@link BranchCommitEnricher.retrieveChange | retrieved}.
         * In the event that an entry is not explicitly removed, it will eventually be {@link WeakMap | dropped from memory} along with the associated commit.
         */
        this.prepared = new WeakMap();
    }
    /**
     * Process the given commits for later {@link BranchCommitEnricher.retrieveChange | retrieval}.
     * @param commits - The commits to prepare.
     */
    prepareChanges(commits) {
        if ((0, index_js_1.hasSome)(commits)) {
            const startingState = commits[0].parent;
            (0, internal_1.assert)(startingState !== undefined, 0xcc1 /* New commits must have a parent. */);
            const enrichedCommits = this.enricher.enrich(startingState, commits);
            for (const [index, commit] of commits.entries()) {
                const enrichedCommit = enrichedCommits[index];
                (0, internal_1.assert)(enrichedCommit !== undefined, 0xcc2 /* Missing enriched commit. */);
                this.prepared.set(commit, enrichedCommit);
            }
        }
    }
    /**
     * Retrieves the enriched change for the given commit.
     * @param commit - A commit that was already {@link BranchCommitEnricher.prepareChanges | prepared}.
     * @remarks A commit can only be enriched once - subsequent calls to this method with the same commit will throw an error.
     * @returns The enriched change corresponding to the given `commit`.
     */
    retrieveChange(commit) {
        const prepared = this.prepared.get(commit);
        (0, internal_1.assert)(prepared !== undefined, 0x980 /* Unknown commit */);
        this.prepared.delete(commit);
        return prepared;
    }
}
exports.BranchCommitEnricher = BranchCommitEnricher;
//# sourceMappingURL=branchCommitEnricher.js.map