import * as i0 from '@angular/core';
import { EventEmitter, Injectable, Output, Inject, Component, Input, NgModule } from '@angular/core';
import { of } from 'rxjs';
import { RedirectBehavior, LoginType, LoginState, LoginMode } from '@laserfiche/lf-ui-components/shared';
import { JwtUtils, TokenClient, DomainUtils, SelfHostedTokenClient, PKCEUtils } from '@laserfiche/lf-api-client-core';
import * as i2 from '@laserfiche/lf-ui-components/internal-shared';
import * as i3 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i4 from '@angular/material/menu';
import { MatMenuModule } from '@angular/material/menu';
import { createCustomElement } from '@angular/elements';

// Copyright (c) Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.
const CONTENT_TYPE_WWW_FORM_URLENCODED = 'application/x-www-form-urlencoded';
class LfLoginService {
    constructor() {
        /** @internal */
        this.redirect_behavior = RedirectBehavior.Replace;
        /** @internal */
        this.authorize_url_host_name = 'laserfiche.com';
        /** @internal */
        this.login_type = LoginType.Cloud;
        /** @internal */
        this.login_identifier = this.client_id ?? '';
        /** @internal */
        this.logoutCompletedInService = new EventEmitter();
        /** @internal */
        this.loginCompletedInService = new EventEmitter();
        /** @internal */
        this.exchangeCodeForToken_lock = false;
    }
    /** @internal */
    get base64EncodedLoginIdentifier() {
        return btoa(this.login_identifier);
    }
    /** @internal */
    get accountIdStorageKey() {
        return `lf-login.${this.base64EncodedLoginIdentifier}.account-id`;
    }
    /** @internal */
    get accountEndpointsStorageKey() {
        return `lf-login.${this.base64EncodedLoginIdentifier}.account-endpoints`;
    }
    /** @internal */
    get accessTokenStorageKey() {
        return `lf-login.${this.base64EncodedLoginIdentifier}.access-token`;
    }
    /** @internal */
    get codeVerifierStorageKey() {
        return `lf-login.${this.base64EncodedLoginIdentifier}.code-verifier`;
    }
    /** @internal */
    getAccountEndpoints() {
        try {
            const accountEndpointsFromStorage = localStorage.getItem(this.accountEndpointsStorageKey);
            if (accountEndpointsFromStorage) {
                const accountEndpoints = JSON.parse(accountEndpointsFromStorage);
                return accountEndpoints;
            }
            else {
                return undefined;
            }
            // }
        }
        catch (err) {
            console.warn('Unable to retrieve accountEndpoints: ' + err.message);
            return undefined;
        }
    }
    /** @internal */
    async exchangeCodeForTokenAsync(callBackURIParams) {
        let concurrentCallsDetected = false;
        try {
            if (this.exchangeCodeForToken_lock) {
                concurrentCallsDetected = true;
                console.warn('exchangeCodeForTokenAsync is already running. Will not try again.');
                return;
            }
            this.exchangeCodeForToken_lock = true;
            this.code_verifier = localStorage.getItem(this.codeVerifierStorageKey);
            const tokenClient = this.loginProvider?.getTokenClient(callBackURIParams.cloudSubDomain);
            if (callBackURIParams.authorizationCode && this.code_verifier && tokenClient) {
                try {
                    const response = await tokenClient.getAccessTokenFromCode(callBackURIParams.authorizationCode, this.redirect_uri, this.client_id, undefined, this.code_verifier);
                    const accessToken = await this.parseTokenResponseAsync(response);
                    this.loginProvider?.storeInLocalStorage(accessToken, callBackURIParams.customerId, callBackURIParams.cloudSubDomain);
                    this._state = LoginState.LoggedIn;
                    console.info('state changed to LoggedIn');
                    this.loginCompletedInService.emit();
                }
                catch (e) {
                    const status = e.status ?? 0;
                    const message = e.message;
                    this.removeFromLocalStorage();
                    this._state = LoginState.LoggedOut;
                    console.error('Login Error (state changed to LoggedOut): ' + message);
                    this.logoutCompletedInService.emit({
                        ErrorType: status.toString(),
                        ErrorMessage: message,
                    });
                }
            }
            else if (callBackURIParams.error) {
                this._state = LoginState.LoggedOut;
                this.removeFromLocalStorage();
                this.logoutCompletedInService.emit({
                    ErrorType: callBackURIParams.error.name,
                    ErrorMessage: callBackURIParams.error.description,
                });
                console.error('Login Error (state changed to Logged Out): ' +
                    callBackURIParams.error.name +
                    ', ' +
                    callBackURIParams.error.description);
            }
            else if (callBackURIParams.authorizationCode && !this.code_verifier) {
                this._state = LoginState.LoggedOut;
                this.removeFromLocalStorage();
                this.logoutCompletedInService.emit({
                    ErrorType: 'no code verifier',
                    ErrorMessage: 'code verifier not found',
                });
                console.error('Login Error (state changed to Logged Out): unable to find code verifier');
            }
            else if (!tokenClient) {
                this._state = LoginState.LoggedOut;
                this.removeFromLocalStorage();
                this.logoutCompletedInService.emit({
                    ErrorType: 'TokenClient is undefined',
                    ErrorMessage: 'TokenClient is undefined',
                });
                console.error('Login Error (state changed to Logged Out): unable to use an undefined TokenClient', tokenClient);
            }
            else {
                throw new Error('Unexpected callBackURIParams');
            }
        }
        finally {
            if (!concurrentCallsDetected) {
                this.exchangeCodeForToken_lock = false;
            }
        }
    }
    /** @internal */
    async parseTokenResponseAsync(response) {
        try {
            const authorizationCredentials = this.getExchangeCodeSuccessResponse(response);
            return authorizationCredentials;
        }
        catch {
            throw Error('Parse token response error.');
        }
    }
    /** @internal */
    getExchangeCodeSuccessResponse(jsonResponse) {
        const accessToken = jsonResponse['access_token'];
        const refreshToken = jsonResponse['refresh_token'] ?? jsonResponse['refreshToken'];
        const expiresIn = jsonResponse['expires_in'];
        const tokenType = jsonResponse['token_type'];
        if (!accessToken)
            throw new Error('access_token undefined');
        if (!expiresIn)
            throw new Error('expires_in undefined');
        if (!tokenType)
            throw new Error('token_type undefined');
        if (!refreshToken)
            throw new Error('refresh_token undefined');
        return {
            accessToken,
            refreshToken,
            expiresIn,
            tokenType,
        };
    }
    /** @internal */
    removeFromLocalStorage() {
        this.removeCodeVerifierFromLocalStorage();
        localStorage.removeItem(this.accessTokenStorageKey);
        localStorage.removeItem(this.accountIdStorageKey);
        this.removeFromCache();
    }
    removeFromCache() {
        this._accessToken = undefined;
        this._accountInfo = undefined;
    }
    /** @internal */
    removeCodeVerifierFromLocalStorage() {
        localStorage.removeItem(this.codeVerifierStorageKey);
        this.code_verifier = undefined;
    }
    /** @internal */
    createPostTokenRequest(code) {
        const request = { method: 'POST' };
        const headers = this.getPostRequestHeaders();
        const body = {
            grant_type: 'authorization_code',
            code: code,
            redirect_uri: this.redirect_uri,
            client_id: this.client_id,
            code_verifier: this.code_verifier,
        };
        const requestBody = this.objToWWWFormUrlEncodedBody(body);
        request.headers = headers;
        request.body = requestBody;
        return request;
    }
    /** @internal */
    storeAccessToken(responseBody) {
        localStorage.setItem(this.accessTokenStorageKey, JSON.stringify(responseBody));
        this._accessToken = responseBody;
    }
    /** @internal */
    storeCodeVerifier(code_verifier) {
        localStorage.setItem(this.codeVerifierStorageKey, code_verifier);
    }
    /** @internal */
    getPostRequestHeaders() {
        const headers = {
            'Content-Type': CONTENT_TYPE_WWW_FORM_URLENCODED,
        };
        return headers;
    }
    /** @internal */
    objToWWWFormUrlEncodedBody(obj) {
        const urlSearchParams = new URLSearchParams();
        for (const i in obj) {
            urlSearchParams.set(i, obj[i]);
        }
        return urlSearchParams.toString();
    }
    /** @internal */
    parseAccessToken(accessToken) {
        const decodedAccessToken = JwtUtils.parseAccessToken(accessToken);
        const trusteeId = JwtUtils.getTrusteeIdFromLfJWT(decodedAccessToken);
        return trusteeId;
    }
    /** @internal */
    storeAccountEndpoints(accountEndpoints) {
        localStorage.setItem(this.accountEndpointsStorageKey, JSON.stringify(accountEndpoints));
        this._accountEndpoints = accountEndpoints;
    }
    /** @internal */
    storeAccountInfo(accountId, trusteeId) {
        const accountInfo = {
            accountId,
            trusteeId,
        };
        localStorage.setItem(this.accountIdStorageKey, JSON.stringify(accountInfo));
        this._accountInfo = accountInfo;
    }
    refreshServiceAccountProperties() {
        const accountInfo = localStorage.getItem(this.accountIdStorageKey);
        const accountEndpoints = localStorage.getItem(this.accountEndpointsStorageKey);
        this._accountInfo = JSON.parse(accountInfo);
        this._accountEndpoints = JSON.parse(accountEndpoints);
    }
    /** @internal */
    extractErrorFromUrl(url) {
        const error = url.searchParams.get('error');
        if (error) {
            const description = url.searchParams.get('description') ?? 'unknown';
            return { name: error, description };
        }
        else {
            return undefined;
        }
    }
    /** @internal */
    extractCodeFromUrl(url) {
        return url.searchParams.get('code') ?? undefined;
    }
    /** @internal */
    extractDomainFromUrl(url) {
        return url.searchParams.get('domain') ?? undefined;
    }
    /** @internal */
    extractCustomerIdFromUrl(url) {
        return url.searchParams.get('customerId') ?? undefined;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], propDecorators: { logoutCompletedInService: [{
                type: Output
            }], loginCompletedInService: [{
                type: Output
            }] } });

// Copyright Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.
/** @internal */
class CloudLoginProvider {
    constructor(lfLoginService) {
        this.lfLoginService = lfLoginService;
        this.CLOUDDEV = 'clouddev';
        this.CLOUDTEST = 'cloudtest';
    }
    getTokenClient(tokenClientUrl) {
        return new TokenClient(tokenClientUrl);
    }
    getBaseAuthorizeUrl() {
        let baseAuthorizeUrl;
        const lastOAuthAuthorizeUrl = this.lfLoginService.getAccountEndpoints()?.oauthAuthorizeUrl;
        const configuredHostName = this.lfLoginService.authorize_url_host_name;
        const bothClouddev = configuredHostName.includes(this.CLOUDDEV) && lastOAuthAuthorizeUrl?.includes(this.CLOUDDEV);
        const bothCloudtest = configuredHostName.includes(this.CLOUDTEST) && lastOAuthAuthorizeUrl?.includes(this.CLOUDTEST);
        const bothCloudprod = lastOAuthAuthorizeUrl &&
            !configuredHostName.includes(this.CLOUDDEV) &&
            !configuredHostName.includes(this.CLOUDTEST) &&
            !lastOAuthAuthorizeUrl?.includes(this.CLOUDDEV) &&
            !lastOAuthAuthorizeUrl?.includes(this.CLOUDTEST);
        const sameEnvironment = bothClouddev || bothCloudtest || bothCloudprod;
        if (sameEnvironment && lastOAuthAuthorizeUrl) {
            baseAuthorizeUrl = lastOAuthAuthorizeUrl;
        }
        else {
            baseAuthorizeUrl = `https://signin.${this.lfLoginService.authorize_url_host_name}/oauth/Authorize`;
        }
        return baseAuthorizeUrl;
    }
    storeInLocalStorage(accessTokenCredentials, accountId, regionalDomain) {
        this.lfLoginService.storeAccessToken(accessTokenCredentials);
        const trusteeId = this.lfLoginService.parseAccessToken(accessTokenCredentials.accessToken);
        const endpoints = DomainUtils.getLfEndpoints(regionalDomain);
        this.lfLoginService.storeAccountInfo(accountId, trusteeId);
        this.lfLoginService.storeAccountEndpoints(endpoints);
    }
    exchangeRedirectUriQueryParams(url) {
        const authorizationCode = this.lfLoginService.extractCodeFromUrl(url);
        const domain = this.lfLoginService.extractDomainFromUrl(url);
        const customerId = this.lfLoginService.extractCustomerIdFromUrl(url);
        const error = this.lfLoginService.extractErrorFromUrl(url);
        if (authorizationCode && domain && customerId) {
            return {
                authorizationCode,
                cloudSubDomain: domain,
                customerId,
            };
        }
        else if (error) {
            return { error };
        }
        return undefined;
    }
    determineCurrentState(callBackURIParams, loginCompleted, logoutCompleted) {
        const storedAccessToken = localStorage.getItem(this.lfLoginService.accessTokenStorageKey);
        const storedAccountEndpoints = localStorage.getItem(this.lfLoginService.accountEndpointsStorageKey);
        const storedAccountId = localStorage.getItem(this.lfLoginService.accountIdStorageKey);
        if (storedAccessToken && storedAccountEndpoints && storedAccountId) {
            this.lfLoginService._accessToken = JSON.parse(storedAccessToken);
            this.lfLoginService._accountEndpoints = JSON.parse(storedAccountEndpoints);
            const accountInfo = JSON.parse(storedAccountId);
            this.lfLoginService._accountInfo = accountInfo;
            loginCompleted.emit();
            return LoginState.LoggedIn;
        }
        else if (callBackURIParams?.authorizationCode || callBackURIParams?.error) {
            return LoginState.LoggingIn;
        }
        else {
            logoutCompleted.emit();
            return LoginState.LoggedOut;
        }
    }
    logoutInitiatedViaUrl(url, logoutInitiated) {
        logoutInitiated.emit(url);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CloudLoginProvider, deps: [{ token: LfLoginService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CloudLoginProvider, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: CloudLoginProvider, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], ctorParameters: () => [{ type: LfLoginService }] });

// Copyright Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.
/** @internal */
class SelfHostedLoginProvider {
    constructor(lfLoginService, repositoryId) {
        this.lfLoginService = lfLoginService;
        this.repositoryId = repositoryId;
    }
    getTokenClient() {
        return new SelfHostedTokenClient(`${this.lfLoginService.self_hosted_base_url}/v2/Repositories/${this.repositoryId}/Token`);
    }
    getBaseAuthorizeUrl() {
        return this.lfLoginService.self_hosted_account_endpoints?.oauthAuthorizeUrl ?? '';
    }
    storeInLocalStorage(accessTokenCredentials, _accountId, _regionalDomain) {
        this.lfLoginService.storeAccessToken(accessTokenCredentials);
        if (this.lfLoginService.self_hosted_account_endpoints) {
            this.lfLoginService.storeAccountEndpoints(this.lfLoginService.self_hosted_account_endpoints);
        }
    }
    exchangeRedirectUriQueryParams(url) {
        const authorizationCode = this.lfLoginService.extractCodeFromUrl(url);
        const error = this.lfLoginService.extractErrorFromUrl(url);
        if (authorizationCode) {
            return {
                authorizationCode,
            };
        }
        else if (error) {
            return { error };
        }
        return undefined;
    }
    determineCurrentState(callBackURIParams, loginCompleted, logoutCompleted) {
        const storedAccessToken = localStorage.getItem(this.lfLoginService.accessTokenStorageKey);
        const storedAccountEndpoints = localStorage.getItem(this.lfLoginService.accountEndpointsStorageKey);
        if (storedAccessToken && storedAccountEndpoints) {
            this.lfLoginService._accessToken = JSON.parse(storedAccessToken);
            this.lfLoginService._accountEndpoints = JSON.parse(storedAccountEndpoints);
            loginCompleted.emit();
            return LoginState.LoggedIn;
        }
        else if (callBackURIParams?.authorizationCode || callBackURIParams?.error) {
            return LoginState.LoggingIn;
        }
        else {
            logoutCompleted.emit();
            return LoginState.LoggedOut;
        }
    }
    logoutInitiatedViaUrl(url, logoutInitiated) {
        if (url) {
            logoutInitiated.emit(url);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: SelfHostedLoginProvider, deps: [{ token: LfLoginService }, { token: 'repositoryId' }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: SelfHostedLoginProvider, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: SelfHostedLoginProvider, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }], ctorParameters: () => [{ type: LfLoginService }, { type: undefined, decorators: [{
                    type: Inject,
                    args: ['repositoryId']
                }] }] });

// Copyright (c) Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.
const LOGIN_REDIRECT_STATE = 'lf-login-redirect';
const CODE_CHALLENGE_METHOD = 'S256';
class LfLoginComponent {
    /**
     * @return {LfHttpRequestHandler}
     * Returns the LfHttpRequestHandler that can be used
     * to instantiate a repository API client.
     */
    get authorizationRequestHandler() {
        return {
            beforeFetchRequestAsync: this.beforeFetchRequestAsync.bind(this),
            afterFetchResponseAsync: this.afterFetchResponseAsync.bind(this),
        };
    }
    /** @internal */
    get isMenuMode() {
        return this.mode === LoginMode.Menu;
    }
    set sign_in_text(text) {
        this._sign_in_text = of(text);
    }
    set sign_out_text(text) {
        this._sign_out_text = of(text);
    }
    set signing_in_text(text) {
        this._signing_in_text = of(text);
    }
    set signing_out_text(text) {
        this._signing_out_text = of(text);
    }
    set client_id(val) {
        this.loginService.client_id = val;
    }
    get client_id() {
        return this.loginService.client_id;
    }
    set redirect_uri(val) {
        this.loginService.redirect_uri = val;
    }
    get redirect_uri() {
        return this.loginService.redirect_uri;
    }
    set scope(val) {
        this.loginService.scope = val;
    }
    get scope() {
        return this.loginService.scope;
    }
    set redirect_behavior(val) {
        this.loginService.redirect_behavior = val;
    }
    get redirect_behavior() {
        return this.loginService.redirect_behavior;
    }
    set authorize_url_host_name(val) {
        this.loginService.authorize_url_host_name = val;
    }
    get authorize_url_host_name() {
        return this.loginService.authorize_url_host_name;
    }
    set login_type(val) {
        this.loginService.login_type = val;
    }
    get login_type() {
        return this.loginService.login_type;
    }
    set login_identifier(val) {
        this.loginService.login_identifier = val;
    }
    get login_identifier() {
        return this.loginService.login_identifier;
    }
    get authorization_credentials() {
        try {
            if (this.loginService._accessToken) {
                return this.loginService._accessToken;
            }
            else {
                const accessTokenFromStorage = localStorage.getItem(this.loginService.accessTokenStorageKey);
                if (accessTokenFromStorage) {
                    const accessTokenCredentials = JSON.parse(accessTokenFromStorage);
                    return accessTokenCredentials;
                }
                else {
                    return undefined;
                }
            }
        }
        catch (err) {
            console.warn('Unable to retrieve accessToken: ' + err.message);
            return undefined;
        }
    }
    get account_endpoints() {
        return this.loginService.getAccountEndpoints();
    }
    get account_id() {
        try {
            if (this.loginService._accountInfo) {
                return this.loginService._accountInfo.accountId;
            }
            else {
                const accountInfoFromStorage = localStorage.getItem(this.loginService.accountIdStorageKey);
                if (accountInfoFromStorage) {
                    const accountInfo = JSON.parse(accountInfoFromStorage);
                    return accountInfo.accountId;
                }
                else {
                    return undefined;
                }
            }
        }
        catch (err) {
            console.warn('Unable to retrieve accountId: ' + err.message);
            return undefined;
        }
    }
    get trustee_id() {
        try {
            if (this.loginService._accountInfo) {
                return this.loginService._accountInfo.trusteeId;
            }
            else {
                const accountInfoFromStorage = localStorage.getItem(this.loginService.accountIdStorageKey);
                if (accountInfoFromStorage) {
                    const accountInfo = JSON.parse(accountInfoFromStorage);
                    return accountInfo.trusteeId;
                }
                else {
                    return undefined;
                }
            }
        }
        catch (err) {
            console.warn('Unable to retrieve trusteeId: ' + err.message);
            return undefined;
        }
    }
    get state() {
        return this.loginService._state ?? LoginState.LoggedOut;
    }
    set _state(state) {
        this.loginService._state = state;
        this.setButtonText();
    }
    async loginFlowHandler(startLoginMethodAsync) {
        try {
            const accessToken = this.authorization_credentials?.accessToken;
            if (this.state === LoginState.LoggedOut && !this.hasLoginError) {
                await startLoginMethodAsync();
                return undefined;
            }
            else {
                await this.initializeLoginAsync();
                return accessToken;
            }
        }
        catch (err) {
            this._state = LoginState.LoggedOut;
            this.ref.detectChanges();
            this.loginService.removeFromLocalStorage();
            this.logoutCompleted.emit({
                ErrorType: 'Login Error',
                ErrorMessage: err.message,
            });
            console.error('Unable to login, logged out: ' + err.message);
            return undefined;
        }
    }
    async startCloudLoginFlowAsync() {
        this.loginService.loginProvider = new CloudLoginProvider(this.loginService);
        await this.startOAuthLoginFlowAsync();
    }
    async startSelfHostedLoginFlow(accountEndpoints, repositoryId) {
        this.loginService.loginProvider = new SelfHostedLoginProvider(this.loginService, repositoryId);
        await this.startSelfHostedLoginFlowAsync(accountEndpoints);
    }
    /** @internal */
    constructor(
    /** @internal */
    ref, 
    /** @internal */
    loginService, 
    /** @internal */
    localizationService) {
        this.ref = ref;
        this.loginService = loginService;
        this.localizationService = localizationService;
        this.mode = LoginMode.Button;
        /** @internal */
        this._sign_in_text = this.localizationService.getStringLaserficheObservable('SIGN_IN');
        /** @internal */
        this._sign_out_text = this.localizationService.getStringLaserficheObservable('SIGN_OUT');
        /** @internal */
        this._signing_in_text = this.localizationService.getStringLaserficheObservable('SIGNING_IN');
        /** @internal */
        this._signing_out_text = this.localizationService.getStringLaserficheObservable('SIGNING_OUT');
        /** @internal */
        this.buttonText = this._sign_in_text;
        this.loginInitiated = new EventEmitter();
        this.logoutInitiated = new EventEmitter();
        this.loginCompleted = new EventEmitter();
        this.logoutCompleted = new EventEmitter();
        /**
         * Refreshes and returns the access token
         * @param initiateLoginFlowOnRefreshFailure
         * Indicates whether an attempt should be made to login using OAuth flow upon encountering an inability to refresh the access token.
         * @returns  {Promise<string | undefined>}
         */
        this.refreshTokenAsync = async (initiateLoginFlowOnRefreshFailure = true) => {
            try {
                const refreshToken = this.authorization_credentials?.refreshToken;
                if (!refreshToken) {
                    if (initiateLoginFlowOnRefreshFailure && !this.hasLoginError && this.state === LoginState.LoggedOut) {
                        console.warn('Unable to refresh, refreshToken is not defined. Will attempt to start the OAuth login flow');
                        await this.startOAuthLoginFlowAsync();
                    }
                    else if (this.state === LoginState.LoggingIn) {
                        console.log('Logging in. Will not attempt to refresh');
                    }
                    else {
                        console.warn('Unable to refresh, refreshToken is not defined, initiateLoginFlowOnRefreshFailure set to false');
                        this._state = LoginState.LoggedOut;
                        this.logoutCompleted.emit({
                            ErrorType: 'Refresh Token Error',
                            ErrorMessage: 'refreshToken is not defined',
                        });
                        this.ref.detectChanges();
                        this.loginService.removeFromLocalStorage();
                    }
                    return undefined;
                }
                else {
                    try {
                        const oauthRegion = this.account_endpoints?.regionalDomain;
                        if (!oauthRegion) {
                            throw new Error('Unable to refresh. Cannot construct tokenClient.');
                        }
                        const tokenClient = this.loginService.loginProvider?.getTokenClient(oauthRegion);
                        const response = await tokenClient.refreshAccessToken(refreshToken, this.client_id);
                        const newAccessToken = await this.loginService.parseTokenResponseAsync(response);
                        this.loginService.storeAccessToken(newAccessToken);
                        this._state = LoginState.LoggedIn;
                        console.info('state changed to LoggedIn');
                        this.loginCompleted.emit();
                        return newAccessToken?.accessToken;
                    }
                    catch (e) {
                        const status = e.status ?? 0;
                        if (status === 401 || status === 403) {
                            if (initiateLoginFlowOnRefreshFailure && !this.hasLoginError && this.state === LoginState.LoggedOut) {
                                console.warn('Unable to refresh. Will attempt to start the OAuth login flow');
                                await this.startOAuthLoginFlowAsync();
                            }
                            else {
                                console.warn(`Unable to refresh, initiateLoginFlowOnRefreshFailure set to ${initiateLoginFlowOnRefreshFailure}, state is ${this.state}`);
                                this._state = LoginState.LoggedOut;
                                this.ref.detectChanges();
                                this.loginService.removeFromLocalStorage();
                            }
                        }
                        throw e;
                    }
                }
            }
            catch (err) {
                this._state = LoginState.LoggedOut;
                this.ref.detectChanges();
                this.loginService.removeFromLocalStorage();
                this.logoutCompleted.emit({
                    ErrorType: 'Refresh Token Error',
                    ErrorMessage: err.message,
                });
                console.error('Unable to refresh, logged out: ' + err.message);
                return undefined;
            }
        };
        this.initLoginFlowAsync = async () => {
            return await this.loginFlowHandler(() => this.startCloudLoginFlowAsync());
        };
        this.initSelfHostedLoginFlowAsync = async (accountEndpoints, repositoryId) => {
            return await this.loginFlowHandler(() => this.startSelfHostedLoginFlow(accountEndpoints, repositoryId));
        };
        this.handleRedirectURICallbackAsync = async (url) => {
            try {
                const callbackURIParams = this.parseCallbackURI(url);
                if (callbackURIParams) {
                    await this.loginService.exchangeCodeForTokenAsync(callbackURIParams);
                }
            }
            catch (err) {
                console.error('handleRedirectURICallbackAsync error, unable to exchange token: ', err.message);
                throw err;
            }
        };
        /** @internal */
        this.hasLoginError = false;
        /** @internal */
        this.initialized = false;
        window.addEventListener('storage', (ev) => {
            this.onStorageChanged(ev);
        });
    }
    async ngAfterViewInit() {
        const accessToken = this.authorization_credentials?.accessToken;
        if (accessToken) {
            this._state = LoginState.LoggedIn;
        }
        else {
            await this.initializeLoginAsync();
        }
    }
    /** @internal */
    async ngOnChanges(changes) {
        // initialize the login state according to the access token
        const currentLoginIdentifier = changes['login_identifier'];
        if ((currentLoginIdentifier?.currentValue && currentLoginIdentifier?.isFirstChange()) ||
            currentLoginIdentifier?.previousValue !== currentLoginIdentifier?.currentValue) {
            const accessToken = this.authorization_credentials?.accessToken;
            if (accessToken) {
                this._state = LoginState.LoggedIn;
            }
            else {
                await this.initializeLoginAsync();
            }
        }
        const currentLoginType = changes['login_type'];
        if (!this.loginService.loginProvider &&
            ((currentLoginType?.currentValue && currentLoginType?.isFirstChange()) ||
                currentLoginType?.previousValue !== currentLoginType?.currentValue)) {
            this.loginService.loginProvider =
                currentLoginType.currentValue === LoginType.SelfHosted
                    ? new SelfHostedLoginProvider(this.loginService, currentLoginIdentifier.currentValue)
                    : new CloudLoginProvider(this.loginService);
        }
    }
    setButtonText() {
        if (this.state === LoginState.LoggedIn) {
            this.buttonText = this._sign_out_text;
        }
        else if (this.state === LoginState.LoggingIn) {
            this.buttonText = this._signing_in_text;
        }
        else if (this.state === LoginState.LoggingOut) {
            this.buttonText = this._signing_out_text;
        }
        else {
            this.buttonText = this._sign_in_text;
        }
    }
    onStorageChanged(ev) {
        const keyName = ev.key;
        const oldValue = ev.oldValue;
        const newValue = ev.newValue;
        if (keyName === this.loginService.accessTokenStorageKey) {
            this.onAccessTokenLocalStorageChange(oldValue, newValue);
        }
    }
    onAccessTokenLocalStorageChange(oldValue, newValue) {
        if (oldValue && !newValue) {
            // newly logged out
            this.loginService.removeFromCache();
            this._state = LoginState.LoggedOut;
            this.ref.detectChanges();
            this.logoutCompleted.emit();
        }
        else if (!oldValue && newValue) {
            // newly logged in
            this._state = LoginState.LoggingIn;
            this.ref.detectChanges();
            this.loginService.storeAccessToken(JSON.parse(newValue));
            this.loginService.refreshServiceAccountProperties();
            this._state = LoginState.LoggedIn;
            this.ref.detectChanges();
            this.loginCompleted.emit();
        }
        else if (newValue && oldValue && oldValue !== newValue) {
            // refreshed
            const newAccessToken = JSON.parse(newValue);
            this.loginService.storeAccessToken(newAccessToken);
            this.loginService.refreshServiceAccountProperties();
            this._state = LoginState.LoggedIn;
            this.ref.detectChanges();
            this.loginCompleted.emit();
        }
        else {
            // accessToken didn't change
            // do nothing
        }
    }
    /** @internal */
    get isLoggedIn() {
        return this.loginService._state === LoginState.LoggedIn;
    }
    /** @internal */
    get isIntermediateState() {
        const loggingIn = this.loginService._state === LoginState.LoggingIn;
        const loggingOut = this.loginService._state === LoginState.LoggingOut;
        return loggingIn || loggingOut;
    }
    /** @internal */
    async ngOnInit() {
        this.logoutCompleteSub = this.loginService.logoutCompletedInService.subscribe((error) => {
            this.hasLoginError = true;
            this.setButtonText();
            this.logoutCompleted.emit(error);
        });
        this.loginCompleteSub = this.loginService.loginCompletedInService.subscribe(() => {
            this.setButtonText();
            this.loginCompleted.emit();
        });
    }
    /** @internal */
    ngOnDestroy() {
        this.loginCompleteSub?.unsubscribe();
        this.logoutCompleteSub?.unsubscribe();
    }
    /** @internal */
    async initializeLoginAsync() {
        try {
            const callBackURIParams = this.parseCallbackURI(window.location.href);
            this._state =
                this.loginService.loginProvider?.determineCurrentState(callBackURIParams, this.loginCompleted, this.logoutCompleted) ?? LoginState.LoggedOut;
            this.ref.detectChanges();
            if (this.loginService._state === LoginState.LoggingIn) {
                await this.loginService.exchangeCodeForTokenAsync(callBackURIParams);
            }
        }
        catch (err) {
            this.logoutCompleted.emit({
                ErrorType: 'Login Error',
                ErrorMessage: err.message,
            });
            this.loginService.removeFromLocalStorage();
            this._state = LoginState.LoggedOut;
            console.warn('Login Error: ' + err.message);
            this.ref.detectChanges();
        }
    }
    /** @internal */
    parseCallbackURI(urlString) {
        const url = new URL(urlString);
        const state = url.searchParams.get('state');
        if (state !== LOGIN_REDIRECT_STATE) {
            return undefined;
        }
        return this.loginService.loginProvider?.exchangeRedirectUriQueryParams(url);
    }
    /** @internal */
    createRefreshTokenRequest() {
        const refreshToken = this.loginService._accessToken?.refreshToken;
        if (refreshToken) {
            const request = { method: 'POST' };
            const headers = this.loginService.getPostRequestHeaders();
            const body = {
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                client_id: this.client_id,
            };
            const requestBody = this.loginService.objToWWWFormUrlEncodedBody(body);
            request.headers = headers;
            request.body = requestBody;
            return request;
        }
        else {
            throw new Error('RefreshToken is not defined');
        }
    }
    /** @internal */
    async onLoginButtonClickAsync() {
        if (this.state === LoginState.LoggedIn) {
            this.startLogout();
        }
        else if (this.state === LoginState.LoggedOut) {
            await this.startLoginAsync();
        }
        else {
            // Do not expect to get here as the button should be disabled.
            console.warn('Intermediate state. Should not attempt to login.');
        }
    }
    /** @internal */
    async startLoginAsync() {
        try {
            await this.startCloudLoginFlowAsync();
        }
        catch (err) {
            if (this.loginService._state !== LoginState.LoggedOut) {
                this._state = LoginState.LoggedOut;
                this.ref.detectChanges();
                this.loginService.removeFromLocalStorage();
                this.logoutCompleted.emit({
                    ErrorType: 'Login Error',
                    ErrorMessage: err.message,
                });
                console.error('Login Error: ' + err.message);
            }
        }
    }
    /** @internal */
    async startOAuthLoginFlowAsync() {
        const code_verifier = PKCEUtils.generateCodeVerifier();
        this.loginService.storeCodeVerifier(code_verifier);
        this.code_challenge = await PKCEUtils.generateCodeChallengeAsync(code_verifier);
        const fullAuthorizeUrl = this.getAuthorizeUrl();
        this.loginInitiated.emit(fullAuthorizeUrl);
        this._state = LoginState.LoggingIn;
        this.ref.detectChanges();
        console.info('state changed to LoggingIn');
        this.handleRedirectBehavior(fullAuthorizeUrl, 'Log in button clicked.');
    }
    async startSelfHostedLoginFlowAsync(accountEndpoints) {
        this.loginService.self_hosted_account_endpoints = accountEndpoints;
        this.loginService.self_hosted_base_url = accountEndpoints.regionalDomain;
        await this.startOAuthLoginFlowAsync();
    }
    /** @internal */
    getAuthorizeUrl() {
        const baseAuthorizeUrl = this.loginService.loginProvider?.getBaseAuthorizeUrl();
        const baseUrl = new URL(baseAuthorizeUrl ?? '');
        if (this.client_id) {
            baseUrl.searchParams.set('client_id', this.client_id);
        }
        if (this.scope) {
            baseUrl.searchParams.set('scope', this.scope);
        }
        baseUrl.searchParams.set('redirect_uri', this.redirect_uri);
        baseUrl.searchParams.set('response_type', 'code');
        baseUrl.searchParams.set('response_mode', 'query');
        baseUrl.searchParams.set('state', LOGIN_REDIRECT_STATE);
        baseUrl.searchParams.set('code_challenge', this.code_challenge);
        baseUrl.searchParams.set('code_challenge_method', CODE_CHALLENGE_METHOD);
        return baseUrl.toString();
    }
    /** @internal */
    startLogout() {
        try {
            this._state = LoginState.LoggingOut;
            this.ref.detectChanges();
            console.info('state changed to LoggingOut');
            const logoutUrl = this.getFullLogoutUrl();
            this.loginService.loginProvider?.logoutInitiatedViaUrl(logoutUrl, this.logoutInitiated);
            this.loginService.removeFromLocalStorage();
            this._state = LoginState.LoggedOut;
            this.ref.detectChanges();
            console.info('state changed to LoggedOut');
            this.logoutCompleted.emit();
            if (logoutUrl) {
                this.handleRedirectBehavior(logoutUrl, 'Logout button clicked.');
            }
        }
        catch (err) {
            if (this.loginService._state !== LoginState.LoggedOut) {
                this.loginService.removeFromLocalStorage();
                this._state = LoginState.LoggedOut;
                this.ref.detectChanges();
                console.error('Logout error (state changed to LoggedOut): ' + err.message);
                this.logoutCompleted.emit({
                    ErrorType: 'Logout Error',
                    ErrorMessage: err.message,
                });
            }
        }
    }
    /** @internal */
    getFullLogoutUrl() {
        if (this.account_endpoints?.wsignoutUrl) {
            const acsToLfLogout = new URL(this.account_endpoints?.wsignoutUrl);
            // Warning: if we are already logged out this will behave strangely
            // won't redirect back to redirect Url
            acsToLfLogout.searchParams.set('wreply', this.redirect_uri);
            const stringUrl = acsToLfLogout.toString();
            return stringUrl;
        }
        else {
            console.warn('No account endpoint available. Did not redirect');
            return undefined;
        }
    }
    /** @internal */
    handleRedirectBehavior(stringUrl, additionalContext) {
        if (this.redirect_behavior === RedirectBehavior.Replace) {
            window.location.replace(stringUrl);
        }
        else if (this.redirect_behavior === RedirectBehavior.Popup) {
            throw new Error('Not implemented');
        }
        else {
            const concatStrings = this.concatStrings(additionalContext, 'Redirect behavior none. Redirect must be implemented by container in event initiated handler');
            console.log(concatStrings);
        }
    }
    /** @internal */
    concatStrings(firstString, secondString) {
        const firstStringExists = firstString && firstString.length > 0;
        if (firstStringExists) {
            const lastCharOfFirstString = firstString?.charAt(firstString.length - 1);
            const firstCharOfSecondString = secondString.charAt(0);
            if (lastCharOfFirstString !== ' ' && firstCharOfSecondString !== ' ') {
                return firstString + ' ' + secondString;
            }
            else if (lastCharOfFirstString === ' ' && firstCharOfSecondString === ' ') {
                return firstString + secondString.substring(1);
            }
            return firstString + secondString;
        }
        else {
            return secondString;
        }
    }
    /** @internal */
    async beforeFetchRequestAsync(url, request) {
        // must get accessToken each time
        const accessToken = this.authorization_credentials?.accessToken;
        if (accessToken) {
            const headers = request.headers;
            headers['Authorization'] = 'Bearer ' + accessToken;
            const regionalDomain = this.account_endpoints?.regionalDomain ?? '';
            return { regionalDomain };
        }
        else {
            throw new Error('Access Token undefined.');
        }
    }
    /** @internal */
    async afterFetchResponseAsync(url, response, request) {
        if (response.status === 401) {
            // this will initialize the login flow if refresh is unsuccessful
            const accessToken = await this.refreshTokenAsync(true);
            const retry = accessToken !== undefined;
            return retry;
        }
        return false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginComponent, deps: [{ token: i0.ChangeDetectorRef }, { token: LfLoginService }, { token: i2.AppLocalizationService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.14", type: LfLoginComponent, selector: "lf-login-component", inputs: { mode: "mode", authorizationRequestHandler: "authorizationRequestHandler", sign_in_text: "sign_in_text", sign_out_text: "sign_out_text", signing_in_text: "signing_in_text", signing_out_text: "signing_out_text", client_id: "client_id", redirect_uri: "redirect_uri", scope: "scope", redirect_behavior: "redirect_behavior", authorize_url_host_name: "authorize_url_host_name", login_type: "login_type", login_identifier: "login_identifier", authorization_credentials: "authorization_credentials", account_endpoints: "account_endpoints", account_id: "account_id", trustee_id: "trustee_id", state: "state", refreshTokenAsync: "refreshTokenAsync", initLoginFlowAsync: "initLoginFlowAsync", initSelfHostedLoginFlowAsync: "initSelfHostedLoginFlowAsync", handleRedirectURICallbackAsync: "handleRedirectURICallbackAsync" }, outputs: { loginInitiated: "loginInitiated", logoutInitiated: "logoutInitiated", loginCompleted: "loginCompleted", logoutCompleted: "logoutCompleted" }, usesOnChanges: true, ngImport: i0, template: "<!--Copyright (c) Laserfiche.\r\nLicensed under the MIT License. See LICENSE in the project root for license information.-->\r\n\r\n<div class=\"lf-login-button\" *ngIf=\"!isMenuMode\">\r\n  <button [disabled]=\"isIntermediateState\"\r\n    [ngClass]=\"{'primary-button': !isLoggedIn,'sec-button': isLoggedIn, 'lf-button': true, 'login-button': true}\"\r\n    (click)=\"onLoginButtonClickAsync()\">\r\n    {{buttonText | async}}\r\n  </button>\r\n</div>\r\n\r\n<div class=\"lf-login-menu\" *ngIf=\"isMenuMode\">\r\n  <button [disabled]=\"isIntermediateState\" [matMenuTriggerFor]=\"menu\" class=\"lf-login-menu-trigger\"\r\n    [ngClass]=\"{'lf-trigger-logged-in': isLoggedIn}\">\r\n    <div [ngClass]=\"{'lf-logged-in': isLoggedIn, 'lf-login-trigger-button': true}\">\r\n      <span class=\"material-icons-outlined\">\r\n        person\r\n      </span>\r\n    </div>\r\n  </button>\r\n  <mat-menu #menu=\"matMenu\" class=\"lf-login-mat-menu\">\r\n    <div mat-menu-item>\r\n      <div class=\"lf-login-menu-button\" (click)=\"onLoginButtonClickAsync()\">\r\n        <button [disabled]=\"isIntermediateState\" class=\"lf-login-menu-internal-button\">\r\n          {{buttonText | async}}\r\n        </button>\r\n      </div>\r\n    </div>\r\n  </mat-menu>\r\n</div>\r\n", styles: ["::ng-deep .login-menu-item button.lf-button.login-button{background:transparent;border:none}::ng-deep .lf-login-mat-menu .mat-mdc-menu-item{min-height:unset;line-height:34px;height:34px}::ng-deep .lf-login-mat-menu.mat-mdc-menu-panel{min-height:0;width:200px}.lf-login-menu-trigger{display:flex;align-items:center;justify-content:center;border-radius:50%;border-style:solid;border-width:1px;border-color:#333;height:30px;width:30px;padding:0;cursor:pointer}.lf-login-trigger-button{display:flex;align-items:center;justify-content:center}.lf-login-initials{line-height:1}.lf-login-menu-button{color:#333}.lf-login-menu-internal-button{background:none;border:none}.lf-login-wrapper-button{background:transparent;border:none;text-align:center}::ng-deep .lf-button.login-button{width:200px}\n"], dependencies: [{ kind: "directive", type: i3.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i4.MatMenu, selector: "mat-menu", inputs: ["backdropClass", "aria-label", "aria-labelledby", "aria-describedby", "xPosition", "yPosition", "overlapTrigger", "hasBackdrop", "class", "classList"], outputs: ["closed", "close"], exportAs: ["matMenu"] }, { kind: "component", type: i4.MatMenuItem, selector: "[mat-menu-item]", inputs: ["role", "disabled", "disableRipple"], exportAs: ["matMenuItem"] }, { kind: "directive", type: i4.MatMenuTrigger, selector: "[mat-menu-trigger-for], [matMenuTriggerFor]", inputs: ["mat-menu-trigger-for", "matMenuTriggerFor", "matMenuTriggerData", "matMenuTriggerRestoreFocus"], outputs: ["menuOpened", "onMenuOpen", "menuClosed", "onMenuClose"], exportAs: ["matMenuTrigger"] }, { kind: "pipe", type: i3.AsyncPipe, name: "async" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginComponent, decorators: [{
            type: Component,
            args: [{ selector: 'lf-login-component', template: "<!--Copyright (c) Laserfiche.\r\nLicensed under the MIT License. See LICENSE in the project root for license information.-->\r\n\r\n<div class=\"lf-login-button\" *ngIf=\"!isMenuMode\">\r\n  <button [disabled]=\"isIntermediateState\"\r\n    [ngClass]=\"{'primary-button': !isLoggedIn,'sec-button': isLoggedIn, 'lf-button': true, 'login-button': true}\"\r\n    (click)=\"onLoginButtonClickAsync()\">\r\n    {{buttonText | async}}\r\n  </button>\r\n</div>\r\n\r\n<div class=\"lf-login-menu\" *ngIf=\"isMenuMode\">\r\n  <button [disabled]=\"isIntermediateState\" [matMenuTriggerFor]=\"menu\" class=\"lf-login-menu-trigger\"\r\n    [ngClass]=\"{'lf-trigger-logged-in': isLoggedIn}\">\r\n    <div [ngClass]=\"{'lf-logged-in': isLoggedIn, 'lf-login-trigger-button': true}\">\r\n      <span class=\"material-icons-outlined\">\r\n        person\r\n      </span>\r\n    </div>\r\n  </button>\r\n  <mat-menu #menu=\"matMenu\" class=\"lf-login-mat-menu\">\r\n    <div mat-menu-item>\r\n      <div class=\"lf-login-menu-button\" (click)=\"onLoginButtonClickAsync()\">\r\n        <button [disabled]=\"isIntermediateState\" class=\"lf-login-menu-internal-button\">\r\n          {{buttonText | async}}\r\n        </button>\r\n      </div>\r\n    </div>\r\n  </mat-menu>\r\n</div>\r\n", styles: ["::ng-deep .login-menu-item button.lf-button.login-button{background:transparent;border:none}::ng-deep .lf-login-mat-menu .mat-mdc-menu-item{min-height:unset;line-height:34px;height:34px}::ng-deep .lf-login-mat-menu.mat-mdc-menu-panel{min-height:0;width:200px}.lf-login-menu-trigger{display:flex;align-items:center;justify-content:center;border-radius:50%;border-style:solid;border-width:1px;border-color:#333;height:30px;width:30px;padding:0;cursor:pointer}.lf-login-trigger-button{display:flex;align-items:center;justify-content:center}.lf-login-initials{line-height:1}.lf-login-menu-button{color:#333}.lf-login-menu-internal-button{background:none;border:none}.lf-login-wrapper-button{background:transparent;border:none;text-align:center}::ng-deep .lf-button.login-button{width:200px}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }, { type: LfLoginService }, { type: i2.AppLocalizationService }], propDecorators: { mode: [{
                type: Input
            }], authorizationRequestHandler: [{
                type: Input
            }], sign_in_text: [{
                type: Input
            }], sign_out_text: [{
                type: Input
            }], signing_in_text: [{
                type: Input
            }], signing_out_text: [{
                type: Input
            }], client_id: [{
                type: Input
            }], redirect_uri: [{
                type: Input
            }], scope: [{
                type: Input
            }], redirect_behavior: [{
                type: Input
            }], authorize_url_host_name: [{
                type: Input
            }], login_type: [{
                type: Input
            }], login_identifier: [{
                type: Input
            }], authorization_credentials: [{
                type: Input
            }], account_endpoints: [{
                type: Input
            }], account_id: [{
                type: Input
            }], trustee_id: [{
                type: Input
            }], state: [{
                type: Input
            }], loginInitiated: [{
                type: Output
            }], logoutInitiated: [{
                type: Output
            }], loginCompleted: [{
                type: Output
            }], logoutCompleted: [{
                type: Output
            }], refreshTokenAsync: [{
                type: Input
            }], initLoginFlowAsync: [{
                type: Input
            }], initSelfHostedLoginFlowAsync: [{
                type: Input
            }], handleRedirectURICallbackAsync: [{
                type: Input
            }] } });

// Copyright (c) Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.

// Copyright (c) Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.
class LfLoginModule {
    /** @internal */
    constructor(
    /** @internal */ injector) {
        const elementName = 'lf-login';
        if (window.customElements && !customElements.get(elementName)) {
            const newElement = createCustomElement(LfLoginComponent, { injector });
            customElements.define(elementName, newElement);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginModule, deps: [{ token: i0.Injector }], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LfLoginModule, bootstrap: [LfLoginComponent], declarations: [LfLoginComponent], imports: [CommonModule,
            MatMenuModule], exports: [LfLoginComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginModule, imports: [CommonModule,
            MatMenuModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LfLoginModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [
                        LfLoginComponent
                    ],
                    imports: [
                        CommonModule,
                        MatMenuModule
                    ],
                    bootstrap: [
                        LfLoginComponent
                    ],
                    exports: [
                        LfLoginComponent
                    ]
                }]
        }], ctorParameters: () => [{ type: i0.Injector }] });

// Copyright (c) Laserfiche.
// Licensed under the MIT License. See LICENSE in the project root for license information.

/**
 * Generated bundle index. Do not edit.
 */

export { LfLoginComponent, LfLoginModule };
//# sourceMappingURL=laserfiche-lf-ui-components-lf-login.mjs.map
