function isHandledTokenType(handledTypes, tokenType) {
    return handledTypes.includes(tokenType);
}
const clearStytchTokenParams = ()=>{
    const url = removeStytchTokenParams(window.location.toString());
    window.history.replaceState(null, document.title, url);
};
/**
 * Creates both parseAuthenticateUrl and authenticateByUrl from the set of handlers passed in to ensure
 * both functions agree on what is handled.
 */ const createAuthUrlHandler = (handlers)=>{
    const handledTokenTypes = Object.keys(handlers);
    const parseAuthenticateUrl = (href = window.location.href)=>{
        const url = new URL(href);
        const tokenType = url.searchParams.get('stytch_token_type');
        const token = url.searchParams.get('token');
        if (!token || !tokenType) {
            return null;
        }
        if (isHandledTokenType(handledTokenTypes, tokenType)) {
            return {
                handled: true,
                token,
                tokenType
            };
        }
        return {
            handled: false,
            token,
            tokenType
        };
    };
    const authenticateByUrl = async ({ clearParams, ...options }, href = window.location.href)=>{
        const shouldClearParams = clearParams ?? href === window.location.href;
        const parsed = parseAuthenticateUrl(href);
        if (parsed == null) return null;
        if (!parsed.handled) return parsed;
        const { token, tokenType } = parsed;
        const handler = handlers[tokenType];
        // Clear token immediately when it is "consumed" by the authenticate call to prevent reloads
        // from repeating the call
        if (shouldClearParams) {
            clearStytchTokenParams();
        }
        const data = await handler(token, options);
        return {
            handled: true,
            tokenType: tokenType,
            data
        };
    };
    return {
        authenticateByUrl,
        parseAuthenticateUrl
    };
};
// Exported for testing
function removeStytchTokenParams(href) {
    const url = new URL(href);
    const params = url.searchParams;
    params.delete('token');
    params.delete('stytch_token_type');
    return url;
}

export { clearStytchTokenParams, createAuthUrlHandler, removeStytchTokenParams };
//# sourceMappingURL=createAuthUrlHandler.mjs.map
