/*! @azure/msal-common v16.10.0 2026-06-23 */
'use strict';
import { RESOURCE_DELIM } from './Constants.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { noCryptoObject, invalidState } from '../error/ClientAuthErrorCodes.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
/**
 * Appends user state with random guid, or returns random guid.
 * @param cryptoObj
 * @param userState
 * @param meta
 * @param correlationId
 */
function setRequestState(cryptoObj, userState, meta, correlationId) {
    const libraryState = generateLibraryState(cryptoObj, correlationId, meta);
    return userState
        ? `${libraryState}${RESOURCE_DELIM}${userState}`
        : libraryState;
}
/**
 * Generates the state value used by the common library.
 * @param cryptoObj
 * @param correlationId
 * @param meta
 */
function generateLibraryState(cryptoObj, correlationId, meta) {
    if (!cryptoObj) {
        throw createClientAuthError(noCryptoObject, correlationId);
    }
    // Create a state object containing a unique id and the timestamp of the request creation
    const stateObj = {
        id: cryptoObj.createNewGuid(),
    };
    if (meta) {
        stateObj.meta = meta;
    }
    const stateString = JSON.stringify(stateObj);
    return cryptoObj.base64Encode(stateString);
}
/**
 * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
 * @param base64Decode
 * @param state
 * @param correlationId
 */
function parseRequestState(base64Decode, state, correlationId) {
    if (!base64Decode) {
        throw createClientAuthError(noCryptoObject, correlationId);
    }
    if (!state) {
        throw createClientAuthError(invalidState, correlationId);
    }
    try {
        // Split the state between library state and user passed state and decode them separately
        const splitState = state.split(RESOURCE_DELIM);
        const libraryState = splitState[0];
        const userState = splitState.length > 1
            ? splitState.slice(1).join(RESOURCE_DELIM)
            : "";
        const libraryStateString = base64Decode(libraryState);
        const libraryStateObj = JSON.parse(libraryStateString);
        return {
            userRequestState: userState || "",
            libraryState: libraryStateObj,
        };
    }
    catch (e) {
        throw createClientAuthError(invalidState, correlationId);
    }
}

export { generateLibraryState, parseRequestState, setRequestState };
//# sourceMappingURL=ProtocolUtils.mjs.map
