/// <reference types="webpack-env" />
/// <reference types="node" />
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
import { LoggerService, CacheServiceOptions, CacheService, ServiceRef, DatabaseService, LifecycleService, PluginMetadataService, UrlReaderService, ReadTreeResponse, ReadUrlOptions, ReadUrlResponse, ReadTreeOptions, SearchOptions, SearchResponse, TokenManagerService } from '@backstage/backend-plugin-api';
export { CacheService as CacheClient, CacheServiceOptions as CacheClientOptions, CacheServiceSetOptions as CacheClientSetOptions, DatabaseService as PluginDatabaseManager, DiscoveryService as PluginEndpointDiscovery, ReadTreeOptions, ReadTreeResponse, ReadTreeResponseDirOptions, ReadTreeResponseFile, ReadUrlOptions, ReadUrlResponse, SearchOptions, SearchResponse, SearchResponseFile, TokenManagerService as TokenManager, UrlReaderService as UrlReader } from '@backstage/backend-plugin-api';
import * as winston from 'winston';
import { Logger } from 'winston';
import express, { RequestHandler, ErrorRequestHandler, Router } from 'express';
import { Config, AppConfig } from '@backstage/config';
import { LoadConfigOptionsRemote } from '@backstage/config-loader';
import knexFactory, { Knex } from 'knex';
import { HostDiscovery as HostDiscovery$1 } from '@backstage/backend-app-api';
import { TransportStreamOptions } from 'winston-transport';
import { AzureIntegration, AzureDevOpsCredentialsProvider, BitbucketCloudIntegration, BitbucketIntegration, BitbucketServerIntegration, GerritIntegration, GithubIntegration, GithubCredentialsProvider, GitLabIntegration, GiteaIntegration, AwsS3Integration } from '@backstage/integration';
import { Readable, Writable } from 'stream';
import { AwsCredentialsManager } from '@backstage/integration-aws-node';
import * as isomorphic_git from 'isomorphic-git';
import { AuthCallback, MergeResult, ReadCommitResult } from 'isomorphic-git';
import cors from 'cors';
import { Server } from 'http';
import Docker from 'dockerode';
import { KubeConfig, V1PodTemplateSpec } from '@kubernetes/client-node';
export { isChildPath } from '@backstage/cli-common';

/**
 * Options given when constructing a {@link CacheManager}.
 *
 * @public
 */
type CacheManagerOptions = {
    /**
     * An optional logger for use by the PluginCacheManager.
     */
    logger?: LoggerService;
    /**
     * An optional handler for connection errors emitted from the underlying data
     * store.
     */
    onError?: (err: Error) => void;
};
/**
 * @public
 */
interface PluginCacheManager {
    getClient(options?: CacheServiceOptions): CacheService;
}

/**
 * Implements a Cache Manager which will automatically create new cache clients
 * for plugins when requested. All requested cache clients are created with the
 * connection details provided.
 *
 * @public
 */
declare class CacheManager {
    /**
     * Keys represent supported `backend.cache.store` values, mapped to factories
     * that return Keyv instances appropriate to the store.
     */
    private readonly storeFactories;
    /**
     * Shared memory store for the in-memory cache client. Sharing the same Map
     * instance ensures get/set/delete operations hit the same store, regardless
     * of where/when a client is instantiated.
     */
    private readonly memoryStore;
    private readonly logger;
    private readonly store;
    private readonly connection;
    private readonly useRedisSets;
    private readonly errorHandler;
    private readonly defaultTtl?;
    /**
     * Creates a new {@link CacheManager} instance by reading from the `backend`
     * config section, specifically the `.cache` key.
     *
     * @param config - The loaded application configuration.
     */
    static fromConfig(config: Config, options?: CacheManagerOptions): CacheManager;
    private constructor();
    /**
     * Generates a PluginCacheManager for consumption by plugins.
     *
     * @param pluginId - The plugin that the cache manager should be created for.
     *        Plugin names should be unique.
     */
    forPlugin(pluginId: string): PluginCacheManager;
    private getClientWithTtl;
    private getRedisClient;
    private getMemcacheClient;
    private getMemoryClient;
}
/** @public */
declare function cacheToPluginCacheManager(cache: CacheService): PluginCacheManager;

/**
 * @public
 */
type LegacyCreateRouter<TEnv> = (deps: TEnv) => Promise<RequestHandler>;
/** @ignore */
type TransformedEnv<TEnv extends Record<string, unknown>, TEnvTransforms extends {
    [key in keyof TEnv]?: (dep: TEnv[key]) => unknown;
}> = {
    [key in keyof TEnv]: TEnvTransforms[key] extends (dep: TEnv[key]) => infer R ? R : TEnv[key];
};
/**
 * Creates a new custom plugin compatibility wrapper.
 *
 * @public
 * @remarks
 *
 * Usually you can use {@link legacyPlugin} directly instead, but you might
 * need to use this if you have customized the plugin environment in your backend.
 */
declare function makeLegacyPlugin<TEnv extends Record<string, unknown>, TEnvTransforms extends {
    [key in keyof TEnv]?: (dep: TEnv[key]) => unknown;
}>(envMapping: {
    [key in keyof TEnv]: ServiceRef<TEnv[key]>;
}, envTransforms: TEnvTransforms): (name: string, createRouterImport: Promise<{
    default: LegacyCreateRouter<TransformedEnv<TEnv, TEnvTransforms>>;
}>) => _backstage_backend_plugin_api.BackendFeature;
/**
 * Helper function to create a plugin from a legacy createRouter function and
 * register it with the http router based on the plugin id.
 *
 * @public
 * @remarks
 *
 * This is intended to be used by plugin authors to ease the transition to the
 * new backend system.
 *
 * @example
 *
 *```ts
 *backend.add(legacyPlugin('kafka', import('./plugins/kafka')));
 *```
 */
declare const legacyPlugin: (name: string, createRouterImport: Promise<{
    default: LegacyCreateRouter<TransformedEnv<{
        cache: _backstage_backend_plugin_api.CacheService;
        config: _backstage_backend_plugin_api.RootConfigService;
        database: _backstage_backend_plugin_api.DatabaseService;
        discovery: _backstage_backend_plugin_api.DiscoveryService;
        logger: _backstage_backend_plugin_api.LoggerService;
        permissions: _backstage_backend_plugin_api.PermissionsService;
        scheduler: _backstage_backend_plugin_api.SchedulerService;
        tokenManager: _backstage_backend_plugin_api.TokenManagerService;
        reader: _backstage_backend_plugin_api.UrlReaderService;
        identity: _backstage_backend_plugin_api.IdentityService;
    }, {
        logger: (log: _backstage_backend_plugin_api.LoggerService) => winston.Logger;
        cache: (cache: _backstage_backend_plugin_api.CacheService) => PluginCacheManager;
    }>>;
}>) => _backstage_backend_plugin_api.BackendFeature;

/**
 * Load configuration for a Backend.
 *
 * This function should only be called once, during the initialization of the backend.
 *
 * @public
 */
declare function loadBackendConfig(options: {
    logger: LoggerService;
    remote?: LoadConfigOptionsRemote;
    additionalConfigs?: AppConfig[];
    argv: string[];
    watch?: boolean;
}): Promise<Config>;

/**
 * Creation options for {@link DatabaseManager}.
 *
 * @public
 */
type DatabaseManagerOptions = {
    migrations?: DatabaseService['migrations'];
    logger?: LoggerService;
};
/**
 * Manages database connections for Backstage backend plugins.
 *
 * @public
 * @remarks
 *
 * The database manager allows the user to set connection and client settings on
 * a per pluginId basis by defining a database config block under
 * `plugin.<pluginId>` in addition to top level defaults. Optionally, a user may
 * set `prefix` which is used to prefix generated database names if config is
 * not provided.
 */
declare class DatabaseManager {
    private readonly config;
    private readonly prefix;
    private readonly options?;
    private readonly databaseCache;
    /**
     * Creates a {@link DatabaseManager} from `backend.database` config.
     *
     * @param config - The loaded application configuration.
     * @param options - An optional configuration object.
     */
    static fromConfig(config: Config, options?: DatabaseManagerOptions): DatabaseManager;
    private constructor();
    /**
     * Generates a PluginDatabaseManager for consumption by plugins.
     *
     * @param pluginId - The plugin that the database manager should be created for. Plugin names
     * should be unique as they are used to look up database config overrides under
     * `backend.database.plugin`.
     */
    forPlugin(pluginId: string, deps?: {
        lifecycle: LifecycleService;
        pluginMetadata: PluginMetadataService;
    }): DatabaseService;
    /**
     * Provides the canonical database name for a given plugin.
     *
     * This method provides the effective database name which is determined using global
     * and plugin specific database config. If no explicit database name is configured
     * and `pluginDivisionMode` is not `schema`, this method will provide a generated name
     * which is the pluginId prefixed with 'backstage_plugin_'. If `pluginDivisionMode` is
     * `schema`, it will fallback to using the default database for the knex instance.
     *
     * @param pluginId - Lookup the database name for given plugin
     * @returns String representing the plugin's database name
     */
    private getDatabaseName;
    /**
     * Provides the client type which should be used for a given plugin.
     *
     * The client type is determined by plugin specific config if present.
     * Otherwise the base client is used as the fallback.
     *
     * @param pluginId - Plugin to get the client type for
     * @returns Object with client type returned as `client` and boolean
     *          representing whether or not the client was overridden as
     *          `overridden`
     */
    private getClientType;
    private getRoleConfig;
    /**
     * Provides the knexConfig which should be used for a given plugin.
     *
     * @param pluginId - Plugin to get the knexConfig for
     * @returns The merged knexConfig value or undefined if it isn't specified
     */
    private getAdditionalKnexConfig;
    private getEnsureExistsConfig;
    private getPluginDivisionModeConfig;
    /**
     * Provides a Knex connection plugin config by combining base and plugin
     * config.
     *
     * This method provides a baseConfig for a plugin database connector. If the
     * client type has not been overridden, the global connection config will be
     * included with plugin specific config as the base. Values from the plugin
     * connection take precedence over the base. Base database name is omitted for
     * all supported databases excluding SQLite unless `pluginDivisionMode` is set
     * to `schema`.
     */
    private getConnectionConfig;
    /**
     * Provides a Knex database config for a given plugin.
     *
     * This method provides a Knex configuration object along with the plugin's
     * client type.
     *
     * @param pluginId - The plugin that the database config should correspond with
     */
    private getConfigForPlugin;
    /**
     * Provides a partial `Knex.Config` database schema override for a given
     * plugin.
     *
     * @param pluginId - Target plugin to get database schema override
     * @returns Partial `Knex.Config` with database schema override
     */
    private getSchemaOverrides;
    /**
     * Provides a partial `Knex.Config`• database name override for a given plugin.
     *
     * @param pluginId - Target plugin to get database name override
     * @returns Partial `Knex.Config` with database name override
     */
    private getDatabaseOverrides;
    /**
     * Provides a scoped Knex client for a plugin as per application config.
     *
     * @param pluginId - Plugin to get a Knex client for
     * @returns Promise which resolves to a scoped Knex database client for a
     *          plugin
     */
    private getDatabase;
    private startKeepaliveLoop;
}

/**
 * Creates a knex database connection
 *
 * @public
 * @param dbConfig - The database config
 * @param overrides - Additional options to merge with the config
 */
declare function createDatabaseClient(dbConfig: Config, overrides?: Partial<Knex.Config>, deps?: {
    lifecycle: LifecycleService;
    pluginMetadata: PluginMetadataService;
}): knexFactory.Knex<any, any[]>;
/**
 * Ensures that the given databases all exist, creating them if they do not.
 *
 * @public
 */
declare function ensureDatabaseExists(dbConfig: Config, ...databases: Array<string>): Promise<void>;

/**
 * Tries to deduce whether a thrown error is a database conflict.
 *
 * @public
 * @param e - A thrown error
 * @returns True if the error looks like it was a conflict error thrown by a
 *          known database engine
 */
declare function isDatabaseConflictError(e: unknown): boolean;

/**
 * HostDiscovery is a basic PluginEndpointDiscovery implementation
 * that can handle plugins that are hosted in a single or multiple deployments.
 *
 * The deployment may be scaled horizontally, as long as the external URL
 * is the same for all instances. However, internal URLs will always be
 * resolved to the same host, so there won't be any balancing of internal traffic.
 *
 * @public
 */
declare const HostDiscovery: typeof HostDiscovery$1;
/**
 * SingleHostDiscovery is a basic PluginEndpointDiscovery implementation
 * that assumes that all plugins are hosted in a single deployment.
 *
 * The deployment may be scaled horizontally, as long as the external URL
 * is the same for all instances. However, internal URLs will always be
 * resolved to the same host, so there won't be any balancing of internal traffic.
 *
 * @public
 * @deprecated Use {@link HostDiscovery} instead
 */
declare const SingleHostDiscovery: typeof HostDiscovery$1;

/**
 * useHotCleanup allows cleanup of ongoing effects when a module is
 * hot-reloaded during development. The cleanup function will be called
 * whenever the module itself or any of its parent modules is hot-reloaded.
 *
 * Useful for cleaning intervals, timers, requests etc
 *
 * @public
 * @deprecated Hot module reloading is no longer supported for backends.
 * @example
 * ```ts
 * const intervalId = setInterval(doStuff, 1000);
 * useHotCleanup(module, () => clearInterval(intervalId));
 * ```
 * @param _module - Reference to the current module where you invoke the fn
 * @param cancelEffect - Fn that cleans up the ongoing effects
 */
declare function useHotCleanup(_module: NodeModule, cancelEffect: () => void): void;
/**
 * Memoizes a generated value across hot-module reloads. This is useful for
 * stateful parts of the backend, e.g. to retain a database.
 *
 * @public
 * @deprecated Hot module reloading is no longer supported for backends.
 * @example
 * ```ts
 * const db = useHotMemoize(module, () => createDB(dbParams));
 * ```
 *
 * **NOTE:** Do not use inside conditionals or loops,
 * same rules as for hooks apply (https://reactjs.org/docs/hooks-rules.html)
 *
 * @param _module - Reference to the current module where you invoke the fn
 * @param valueFactory - Fn that returns the value you want to memoize
 */
declare function useHotMemoize<T>(_module: NodeModule, valueFactory: () => T): T;

/**
 * A logger that just throws away all messages.
 *
 * @public
 */
declare function getVoidLogger(): winston.Logger;
/**
 * Gets the current root logger.
 *
 * @public
 */
declare function getRootLogger(): winston.Logger;
/**
 * Sets a completely custom default "root" logger.
 *
 * @remarks
 *
 * This is the logger instance that will be the foundation for all other logger
 * instances passed to plugins etc, in a given backend.
 *
 * Only use this if you absolutely need to make a completely custom logger.
 * Normally if you want to make light adaptations to the default logger
 * behavior, you would instead call {@link createRootLogger}.
 *
 * @public
 */
declare function setRootLogger(newLogger: winston.Logger): void;

/**
 * A winston formatting function that finds occurrences of filteredKeys
 * and replaces them with the corresponding identifier.
 *
 * @public
 */
declare function redactWinstonLogLine(info: winston.Logform.TransformableInfo): winston.Logform.TransformableInfo;
/**
 * Creates a pretty printed winston log formatter.
 *
 * @public
 */
declare const coloredFormat: winston.Logform.Format;
/**
 * Creates a default "root" logger. This also calls {@link setRootLogger} under
 * the hood.
 *
 * @remarks
 *
 * This is the logger instance that will be the foundation for all other logger
 * instances passed to plugins etc, in a given backend.
 *
 * @public
 */
declare function createRootLogger(options?: winston.LoggerOptions, env?: NodeJS.ProcessEnv): winston.Logger;

/** @public */
declare function loggerToWinstonLogger(logger: LoggerService, opts?: TransportStreamOptions): Logger;

/**
 * Options passed to the {@link errorHandler} middleware.
 *
 * @public
 */
type ErrorHandlerOptions = {
    /**
     * Whether error response bodies should show error stack traces or not.
     *
     * If not specified, by default shows stack traces only in development mode.
     */
    showStackTraces?: boolean;
    /**
     * Logger instance to log errors.
     *
     * If not specified, the root logger will be used.
     */
    logger?: LoggerService;
    /**
     * Whether any 4xx errors should be logged or not.
     *
     * If not specified, default to only logging 5xx errors.
     */
    logClientErrors?: boolean;
};
/**
 * Express middleware to handle errors during request processing.
 *
 * This is commonly the very last middleware in the chain.
 *
 * Its primary purpose is not to do translation of business logic exceptions,
 * but rather to be a global catch-all for uncaught "fatal" errors that are
 * expected to result in a 500 error. However, it also does handle some common
 * error types (such as http-error exceptions) and returns the enclosed status
 * code accordingly.
 *
 * @public
 * @returns An Express error request handler
 */
declare function errorHandler(options?: ErrorHandlerOptions): ErrorRequestHandler;

/**
 * Express middleware to handle requests for missing routes.
 *
 * Should be used as the very last handler in the chain, as it unconditionally
 * returns a 404 status.
 *
 * @public
 * @returns An Express request handler
 */
declare function notFoundHandler(): RequestHandler;

/**
 * Logs incoming requests.
 *
 * @public
 * @param logger - An optional logger to use. If not specified, the root logger will be used.
 * @returns An Express request handler
 */
declare function requestLoggingHandler(logger?: LoggerService): RequestHandler;

/**
 * A custom status checking function, passed to {@link statusCheckHandler} and
 * {@link createStatusCheckRouter}.
 *
 * @public
 */
type StatusCheck = () => Promise<any>;
/**
 * Options passed to {@link statusCheckHandler}.
 *
 * @public
 */
interface StatusCheckHandlerOptions {
    /**
     * Optional status function which returns a message.
     */
    statusCheck?: StatusCheck;
}
/**
 * Express middleware for status checks.
 *
 * This is commonly used to implement healthcheck and readiness routes.
 *
 * @public
 * @param options - An optional configuration object.
 * @returns An Express error request handler
 */
declare function statusCheckHandler(options?: StatusCheckHandlerOptions): Promise<RequestHandler>;

/**
 * Resolve a path relative to the root of a package directory.
 * Additional path arguments are resolved relative to the package dir.
 *
 * This is particularly useful when you want to access assets shipped with
 * your backend plugin package. When doing so, do not forget to include the assets
 * in your published package by adding them to `files` in your `package.json`.
 *
 * @public
 */
declare function resolvePackagePath(name: string, ...paths: string[]): string;
/**
 * Resolves a target path from a base path while guaranteeing that the result is
 * a path that point to or within the base path. This is useful for resolving
 * paths from user input, as it otherwise opens up for vulnerabilities.
 *
 * @public
 * @param base - The base directory to resolve the path from.
 * @param path - The target path, relative or absolute
 * @returns A path that is guaranteed to point to or within the base path.
 */
declare function resolveSafeChildPath(base: string, path: string): string;

/**
 * A predicate that decides whether a specific {@link @backstage/backend-plugin-api#UrlReaderService} can handle a
 * given URL.
 *
 * @public
 */
type UrlReaderPredicateTuple = {
    predicate: (url: URL) => boolean;
    reader: UrlReaderService;
};
/**
 * A factory function that can read config to construct zero or more
 * {@link @backstage/backend-plugin-api#UrlReaderService}s along with a predicate for when it should be used.
 *
 * @public
 */
type ReaderFactory = (options: {
    config: Config;
    logger: LoggerService;
    treeResponseFactory: ReadTreeResponseFactory;
}) => UrlReaderPredicateTuple[];
/**
 * An options object for {@link ReadUrlResponseFactory} factory methods.
 *
 * @public
 */
type ReadUrlResponseFactoryFromStreamOptions = {
    etag?: string;
    lastModifiedAt?: Date;
};
/**
 * Options that control execution of {@link ReadTreeResponseFactory} methods.
 *
 * @public
 */
type ReadTreeResponseFactoryOptions = {
    stream: Readable;
    subpath?: string;
    etag: string;
    filter?: (path: string, info?: {
        size: number;
    }) => boolean;
};
/**
 * Options that control {@link ReadTreeResponseFactory.fromReadableArray}
 * execution.
 *
 * @public
 */
type FromReadableArrayOptions = Array<{
    /**
     * The raw data itself.
     */
    data: Readable;
    /**
     * The filepath of the data.
     */
    path: string;
    /**
     * Last modified date of the file contents.
     */
    lastModifiedAt?: Date;
}>;
/**
 * A factory for response factories that handle the unpacking and inspection of
 * complex responses such as archive data.
 *
 * @public
 */
interface ReadTreeResponseFactory {
    fromTarArchive(options: ReadTreeResponseFactoryOptions & {
        /**
         * Strip the first parent directory of a tar archive.
         * Defaults to true.
         */
        stripFirstDirectory?: boolean;
    }): Promise<ReadTreeResponse>;
    fromZipArchive(options: ReadTreeResponseFactoryOptions): Promise<ReadTreeResponse>;
    fromReadableArray(options: FromReadableArrayOptions): Promise<ReadTreeResponse>;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for Azure repos.
 *
 * @public
 */
declare class AzureUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: AzureIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
        credentialsProvider: AzureDevOpsCredentialsProvider;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    toString(): string;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files from Bitbucket Cloud.
 *
 * @public
 */
declare class BitbucketCloudUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: BitbucketCloudIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    toString(): string;
    private getLastCommitShortHash;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files from Bitbucket v1 and v2 APIs, such
 * as the one exposed by Bitbucket Cloud itself.
 *
 * @public
 * @deprecated in favor of BitbucketCloudUrlReader and BitbucketServerUrlReader
 */
declare class BitbucketUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: BitbucketIntegration, logger: LoggerService, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    toString(): string;
    private getLastCommitShortHash;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files from Bitbucket Server APIs.
 *
 * @public
 */
declare class BitbucketServerUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: BitbucketServerIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    toString(): string;
    private getLastCommitShortHash;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files in Gerrit.
 *
 * @remarks
 * To be able to link to Git contents for Gerrit providers in a user friendly
 * way we are depending on that there is a Gitiles installation somewhere
 * that we can link to. It is perfectly possible to integrate Gerrit with
 * Backstage without Gitiles since all API calls goes directly to Gerrit.
 * However if Gitiles is configured, readTree will use it to fetch
 * an archive instead of cloning the repository.
 *
 * The "host" variable in the config is the Gerrit host. The address where
 * Gitiles is installed may be on the same host but it could be on a
 * separate host. For example a Gerrit instance could be hosted on
 * "gerrit-review.company.com" but the repos could be browsable on a separate
 * host, e.g. "gerrit.company.com" and the human readable URL would then
 * not point to the API host.
 *
 * @public
 */
declare class GerritUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    private readonly workDir;
    static factory: ReaderFactory;
    constructor(integration: GerritIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    }, workDir: string);
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(): Promise<SearchResponse>;
    toString(): string;
    private readTreeFromGitClone;
    private readTreeFromGitiles;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files through the GitHub v3 APIs, such as
 * the one exposed by GitHub itself.
 *
 * @public
 */
declare class GithubUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: GithubIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
        credentialsProvider: GithubCredentialsProvider;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    toString(): string;
    private doReadTree;
    private doSearch;
    private getRepoDetails;
    private getDefaultBranch;
    private fetchResponse;
    private fetchJson;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for files on GitLab.
 *
 * @public
 */
declare class GitlabUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: GitLabIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(url: string, options?: SearchOptions): Promise<SearchResponse>;
    /**
     * This function splits the input globPattern string into segments using the  path separator /. It then iterates over
     * the segments from the end of the array towards the beginning, checking if the concatenated string up to that
     * segment matches the original globPattern using the minimatch function. If a match is found, it continues iterating.
     * If no match is found, it returns the concatenated string up to the current segment, which is the static part of the
     * glob pattern.
     *
     * E.g. `catalog/foo/*.yaml` will return `catalog/foo`.
     *
     * @param globPattern the glob pattern
     * @private
     */
    private getStaticPart;
    toString(): string;
    private getGitlabFetchUrl;
    private getGitlabArtifactFetchUrl;
    private resolveProjectToId;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for the Gitea v1 api.
 *
 * @public
 */
declare class GiteaUrlReader implements UrlReaderService {
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(integration: GiteaIntegration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(): Promise<SearchResponse>;
    toString(): string;
    private getLastCommitHash;
}

/**
 * Implements a {@link @backstage/backend-plugin-api#UrlReaderService} for AWS S3 buckets.
 *
 * @public
 */
declare class AwsS3UrlReader implements UrlReaderService {
    private readonly credsManager;
    private readonly integration;
    private readonly deps;
    static factory: ReaderFactory;
    constructor(credsManager: AwsCredentialsManager, integration: AwsS3Integration, deps: {
        treeResponseFactory: ReadTreeResponseFactory;
    });
    /**
     * If accessKeyId and secretAccessKey are missing, the standard credentials provider chain will be used:
     * https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html
     */
    private static buildStaticCredentials;
    private static buildCredentials;
    private buildS3Client;
    private retrieveS3ObjectData;
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(url: string, options?: ReadTreeOptions): Promise<ReadTreeResponse>;
    search(): Promise<SearchResponse>;
    toString(): string;
}

/**
 * A {@link @backstage/backend-plugin-api#UrlReaderService} that does a plain fetch of the URL.
 *
 * @public
 */
declare class FetchUrlReader implements UrlReaderService {
    /**
     * The factory creates a single reader that will be used for reading any URL that's listed
     * in configuration at `backend.reading.allow`. The allow list contains a list of objects describing
     * targets to allow, containing the following fields:
     *
     * `host`:
     *   Either full hostnames to match, or subdomain wildcard matchers with a leading '*'.
     *   For example 'example.com' and '*.example.com' are valid values, 'prod.*.example.com' is not.
     *
     * `paths`:
     *   An optional list of paths which are allowed. If the list is omitted all paths are allowed.
     */
    static factory: ReaderFactory;
    read(url: string): Promise<Buffer>;
    readUrl(url: string, options?: ReadUrlOptions): Promise<ReadUrlResponse>;
    readTree(): Promise<ReadTreeResponse>;
    search(): Promise<SearchResponse>;
    toString(): string;
}

/**
 * Utility class for UrlReader implementations to create valid ReadUrlResponse
 * instances from common response primitives.
 *
 * @public
 */
declare class ReadUrlResponseFactory {
    /**
     * Resolves a ReadUrlResponse from a Readable stream.
     */
    static fromReadable(stream: Readable, options?: ReadUrlResponseFactoryFromStreamOptions): Promise<ReadUrlResponse>;
    /**
     * Resolves a ReadUrlResponse from an old-style NodeJS.ReadableStream.
     */
    static fromNodeJSReadable(oldStyleStream: NodeJS.ReadableStream, options?: ReadUrlResponseFactoryFromStreamOptions): Promise<ReadUrlResponse>;
}

/**
 * Creation options for {@link @backstage/backend-plugin-api#UrlReaderService}.
 *
 * @public
 */
type UrlReadersOptions = {
    /** Root config object */
    config: Config;
    /** Logger used by all the readers */
    logger: LoggerService;
    /** A list of factories used to construct individual readers that match on URLs */
    factories?: ReaderFactory[];
};
/**
 * Helps construct {@link @backstage/backend-plugin-api#UrlReaderService}s.
 *
 * @public
 */
declare class UrlReaders {
    /**
     * Creates a custom {@link @backstage/backend-plugin-api#UrlReaderService} wrapper for your own set of factories.
     */
    static create(options: UrlReadersOptions): UrlReaderService;
    /**
     * Creates a {@link @backstage/backend-plugin-api#UrlReaderService} wrapper that includes all the default factories
     * from this package.
     *
     * Any additional factories passed will be loaded before the default ones.
     */
    static default(options: UrlReadersOptions): UrlReaderService;
}

/**
 * Configure static credential for authentication
 *
 * @public
 */
type StaticAuthOptions = {
    username?: string;
    password?: string;
    token?: string;
    logger?: LoggerService;
};
/**
 * Configure an authentication callback that can provide credentials on demand
 *
 * @public
 */
type AuthCallbackOptions = {
    onAuth: AuthCallback;
    logger?: LoggerService;
};
/**
 * A convenience wrapper around the `isomorphic-git` library.
 *
 * @public
 */
declare class Git {
    private readonly config;
    private readonly headers;
    private constructor();
    add(options: {
        dir: string;
        filepath: string;
    }): Promise<void>;
    addRemote(options: {
        dir: string;
        remote: string;
        url: string;
        force?: boolean;
    }): Promise<void>;
    deleteRemote(options: {
        dir: string;
        remote: string;
    }): Promise<void>;
    checkout(options: {
        dir: string;
        ref: string;
    }): Promise<void>;
    branch(options: {
        dir: string;
        ref: string;
    }): Promise<void>;
    commit(options: {
        dir: string;
        message: string;
        author: {
            name: string;
            email: string;
        };
        committer: {
            name: string;
            email: string;
        };
    }): Promise<string>;
    /** https://isomorphic-git.org/docs/en/clone */
    clone(options: {
        url: string;
        dir: string;
        ref?: string;
        depth?: number;
        noCheckout?: boolean;
    }): Promise<void>;
    /** https://isomorphic-git.org/docs/en/currentBranch */
    currentBranch(options: {
        dir: string;
        fullName?: boolean;
    }): Promise<string | undefined>;
    /** https://isomorphic-git.org/docs/en/fetch */
    fetch(options: {
        dir: string;
        remote?: string;
        tags?: boolean;
    }): Promise<void>;
    init(options: {
        dir: string;
        defaultBranch?: string;
    }): Promise<void>;
    /** https://isomorphic-git.org/docs/en/merge */
    merge(options: {
        dir: string;
        theirs: string;
        ours?: string;
        author: {
            name: string;
            email: string;
        };
        committer: {
            name: string;
            email: string;
        };
    }): Promise<MergeResult>;
    push(options: {
        dir: string;
        remote: string;
        remoteRef?: string;
        force?: boolean;
    }): Promise<isomorphic_git.PushResult>;
    /** https://isomorphic-git.org/docs/en/readCommit */
    readCommit(options: {
        dir: string;
        sha: string;
    }): Promise<ReadCommitResult>;
    /** https://isomorphic-git.org/docs/en/remove */
    remove(options: {
        dir: string;
        filepath: string;
    }): Promise<void>;
    /** https://isomorphic-git.org/docs/en/resolveRef */
    resolveRef(options: {
        dir: string;
        ref: string;
    }): Promise<string>;
    /** https://isomorphic-git.org/docs/en/log */
    log(options: {
        dir: string;
        ref?: string;
    }): Promise<ReadCommitResult[]>;
    private onAuth;
    private onProgressHandler;
    static fromAuth: (options: StaticAuthOptions | AuthCallbackOptions) => Git;
}

/**
 * A helper for building backend service instances.
 *
 * @public
 */
type ServiceBuilder = {
    /**
     * Sets the service parameters based on configuration.
     *
     * @param config - The configuration to read
     */
    loadConfig(config: Config): ServiceBuilder;
    /**
     * Sets the port to listen on.
     *
     * If no port is specified, the service will first look for an environment
     * variable named PORT and use that if present, otherwise it picks a default
     * port (7007).
     *
     * @param port - The port to listen on
     */
    setPort(port: number): ServiceBuilder;
    /**
     * Sets the host to listen on.
     *
     * '' is express default, which listens to all interfaces.
     *
     * @param host - The host to listen on
     */
    setHost(host: string): ServiceBuilder;
    /**
     * Sets the logger to use for service-specific logging.
     *
     * If no logger is given, the default root logger is used.
     *
     * @param logger - A winston logger
     */
    setLogger(logger: LoggerService): ServiceBuilder;
    /**
     * Enables CORS handling using the given settings.
     *
     * If this method is not called, the resulting service will not have any
     * built in CORS handling.
     *
     * @param options - Standard CORS options
     */
    enableCors(options: cors.CorsOptions): ServiceBuilder;
    /**
     * Configure self-signed certificate generation options.
     *
     * If this method is not called, the resulting service will use sensible defaults
     *
     * @param options - Standard certificate options
     */
    setHttpsSettings(settings: {
        certificate: {
            key: string;
            cert: string;
        } | {
            hostname: string;
        };
    }): ServiceBuilder;
    /**
     * Adds a router (similar to the express .use call) to the service.
     *
     * @param root - The root URL to bind to (e.g. "/api/function1")
     * @param router - An express router
     */
    addRouter(root: string, router: Router | RequestHandler): ServiceBuilder;
    /**
     * Set the request logging handler
     *
     * If no handler is given the default one is used
     *
     * @param requestLoggingHandler - a factory function that given a logger returns an handler
     */
    setRequestLoggingHandler(requestLoggingHandler: RequestLoggingHandlerFactory): ServiceBuilder;
    /**
     * Sets an additional errorHandler to run before the defaultErrorHandler.
     *
     * For execution of only the custom error handler make sure to also invoke disableDefaultErrorHandler()
     * otherwise the defaultErrorHandler is executed at the end of the error middleware chain.
     *
     * @param errorHandler - an error handler
     */
    setErrorHandler(errorHandler: ErrorRequestHandler): ServiceBuilder;
    /**
     * Disables the default error handler
     */
    disableDefaultErrorHandler(): ServiceBuilder;
    /**
     * Starts the server using the given settings.
     */
    start(): Promise<Server>;
};
/**
 * A factory for request loggers.
 *
 * @public
 */
type RequestLoggingHandlerFactory = (logger?: LoggerService) => RequestHandler;

/**
 * Creates a new service builder.
 *
 * @public
 */
declare function createServiceBuilder(_module: NodeModule): ServiceBuilder;

/**
 * Creates a default status checking router, that you can add to your express
 * app.
 *
 * @remarks
 *
 * This adds a `/healthcheck` route (or any other path, if given as an
 * argument), which your infra can call to see if the service is ready to serve
 * requests.
 *
 * @public
 */
declare function createStatusCheckRouter(options: {
    logger: LoggerService;
    /**
     * The path (including a leading slash) that the health check should be
     * mounted on.
     *
     * @defaultValue '/healthcheck'
     */
    path?: string;
    /**
     * If not implemented, the default express middleware always returns 200.
     * Override this to implement your own logic for a health check.
     */
    statusCheck?: StatusCheck;
}): Promise<express.Router>;

/**
 * Options for {@link ServerTokenManager}.
 *
 * @public
 */
interface ServerTokenManagerOptions {
    /**
     * The logger to use.
     */
    logger: LoggerService;
}
/**
 * Creates and validates tokens for use during service-to-service
 * authentication.
 *
 * @public
 */
declare class ServerTokenManager implements TokenManagerService {
    private readonly options;
    private readonly verificationKeys;
    private signingKey;
    private privateKeyPromise;
    private currentTokenPromise;
    /**
     * Creates a token manager that issues static fake tokens and never fails
     * authentication. This can be useful for testing.
     */
    static noop(): TokenManagerService;
    static fromConfig(config: Config, options: ServerTokenManagerOptions): ServerTokenManager;
    private constructor();
    private generateKeys;
    getToken(): Promise<{
        token: string;
    }>;
    authenticate(token: string): Promise<void>;
}

/**
 * Options passed to the {@link ContainerRunner.runContainer} method.
 *
 * @public
 */
type RunContainerOptions = {
    imageName: string;
    command?: string | string[];
    args: string[];
    logStream?: Writable;
    mountDirs?: Record<string, string>;
    workingDir?: string;
    envVars?: Record<string, string>;
    pullImage?: boolean;
    defaultUser?: boolean;
};
/**
 * Handles the running of containers, on behalf of others.
 *
 * @public
 */
interface ContainerRunner {
    /**
     * Runs a container image to completion.
     */
    runContainer(opts: RunContainerOptions): Promise<void>;
}

/**
 * A {@link ContainerRunner} for Docker containers.
 *
 * @public
 */
declare class DockerContainerRunner implements ContainerRunner {
    private readonly dockerClient;
    constructor(options: {
        dockerClient: Docker;
    });
    runContainer(options: RunContainerOptions): Promise<void>;
}

/**
 * An existing Kubernetes volume that will be used as base for mounts.
 *
 * Every mount must start with the 'basePath'.
 *
 * @public
 */
type KubernetesContainerRunnerMountBase = {
    volumeName: string;
    basePath: string;
};
/**
 * Options to create a {@link KubernetesContainerRunner}
 *
 * Kubernetes Jobs will be created on the provided 'namespace'
 * and their names will be prefixed with the provided 'name'.
 *
 * 'podTemplate' defines a Pod template for the Jobs. It has to include
 * a volume definition named as the {@link KubernetesContainerRunnerMountBase} 'volumeName'.
 *
 * @public
 */
type KubernetesContainerRunnerOptions = {
    kubeConfig: KubeConfig;
    name: string;
    namespace?: string;
    mountBase?: KubernetesContainerRunnerMountBase;
    podTemplate?: V1PodTemplateSpec;
    timeoutMs?: number;
};
/**
 * A {@link ContainerRunner} for Kubernetes.
 *
 * Runs containers leveraging Jobs on a Kubernetes cluster
 *
 * @public
 */
declare class KubernetesContainerRunner implements ContainerRunner {
    private readonly kubeConfig;
    private readonly batchV1Api;
    private readonly log;
    private readonly name;
    private readonly namespace;
    private readonly mountBase?;
    private readonly podTemplate?;
    private readonly timeoutMs;
    private readonly containerName;
    private getNamespace;
    private validateMountBase;
    constructor(options: KubernetesContainerRunnerOptions);
    runContainer(options: RunContainerOptions): Promise<void>;
    private handleError;
    private watchPod;
    private tailLogs;
    private waitPod;
    private createJob;
    private runJob;
}

export { AuthCallbackOptions, AwsS3UrlReader, AzureUrlReader, BitbucketCloudUrlReader, BitbucketServerUrlReader, BitbucketUrlReader, CacheManager, CacheManagerOptions, ContainerRunner, DatabaseManager, DatabaseManagerOptions, DockerContainerRunner, ErrorHandlerOptions, FetchUrlReader, FromReadableArrayOptions, GerritUrlReader, Git, GiteaUrlReader, GithubUrlReader, GitlabUrlReader, HostDiscovery, KubernetesContainerRunner, KubernetesContainerRunnerMountBase, KubernetesContainerRunnerOptions, LegacyCreateRouter, PluginCacheManager, ReadTreeResponseFactory, ReadTreeResponseFactoryOptions, ReadUrlResponseFactory, ReadUrlResponseFactoryFromStreamOptions, ReaderFactory, RequestLoggingHandlerFactory, RunContainerOptions, ServerTokenManager, ServerTokenManagerOptions, ServiceBuilder, SingleHostDiscovery, StaticAuthOptions, StatusCheck, StatusCheckHandlerOptions, UrlReaderPredicateTuple, UrlReaders, UrlReadersOptions, cacheToPluginCacheManager, coloredFormat, createDatabaseClient, createRootLogger, createServiceBuilder, createStatusCheckRouter, ensureDatabaseExists, errorHandler, getRootLogger, getVoidLogger, isDatabaseConflictError, legacyPlugin, loadBackendConfig, loggerToWinstonLogger, makeLegacyPlugin, notFoundHandler, redactWinstonLogLine, requestLoggingHandler, resolvePackagePath, resolveSafeChildPath, setRootLogger, statusCheckHandler, useHotCleanup, useHotMemoize };
