Establish pattern for typing legacy plugins (#26045)

* Add legacy types and export them for plugins
* Add support for core_plugins to import from 'kibana'
This commit is contained in:
Josh Dover 2018-12-17 12:52:21 -06:00 committed by GitHub
parent 53710d8ae0
commit 08fd427125
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 548 additions and 53 deletions

48
kibana.d.ts vendored Normal file
View file

@ -0,0 +1,48 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* All exports from TS source files (where the implementation is actually done in TS).
*/
export * from './target/types/type_exports';
/**
* All exports from TS ambient definitions (where types are added for JS source in a .d.ts file).
*/
import * as LegacyElasticsearch from './src/legacy/core_plugins/elasticsearch';
import * as LegacyKibanaServer from './src/server/kbn_server';
/**
* Re-export legacy types under a namespace.
*/
// tslint:disable:no-namespace
export namespace Legacy {
export type KibanaConfig = LegacyKibanaServer.KibanaConfig;
export type Request = LegacyKibanaServer.Request;
export type ResponseToolkit = LegacyKibanaServer.ResponseToolkit;
export type Server = LegacyKibanaServer.Server;
export namespace Plugins {
export namespace elasticsearch {
export type Plugin = LegacyElasticsearch.ElasticsearchPlugin;
export type Cluster = LegacyElasticsearch.Cluster;
export type ClusterConfig = LegacyElasticsearch.ClusterConfig;
export type CallClusterOptions = LegacyElasticsearch.CallClusterOptions;
}
}
}

View file

@ -13,7 +13,7 @@
"private": true,
"version": "7.0.0",
"branch": "master",
"types": "./target/types/type_exports.d.ts",
"types": "./kibana.d.ts",
"build": {
"number": 8467,
"sha": "6cb7fec4e154faa0a4a3fee4b33dfef91b9870d9"
@ -264,7 +264,7 @@
"@types/dedent": "^0.7.0",
"@types/del": "^3.0.1",
"@types/delete-empty": "^2.0.0",
"@types/elasticsearch": "^5.0.26",
"@types/elasticsearch": "^5.0.30",
"@types/enzyme": "^3.1.12",
"@types/eslint": "^4.16.2",
"@types/execa": "^0.9.0",

View file

@ -27,14 +27,14 @@ import { first } from 'rxjs/operators';
import { LegacyService } from '.';
// @ts-ignore: implicit any for JS file
import MockClusterManager from '../../../cli/cluster/cluster_manager';
// @ts-ignore: implicit any for JS file
import MockKbnServer from '../../../server/kbn_server';
import KbnServer from '../../../server/kbn_server';
import { Config, ConfigService, Env, ObjectToConfigAdapter } from '../config';
import { getEnvOptions } from '../config/__mocks__/env';
import { logger } from '../logging/__mocks__';
import { PluginsServiceStartContract } from '../plugins/plugins_service';
import { LegacyPlatformProxy } from './legacy_platform_proxy';
const MockKbnServer: jest.Mock<KbnServer> = KbnServer as any;
const MockLegacyPlatformProxy: jest.Mock<LegacyPlatformProxy> = LegacyPlatformProxy as any;
let legacyService: LegacyService;
@ -211,7 +211,7 @@ describe('once LegacyService is started with connection info', () => {
test('reconfigures logging configuration if new config is received.', async () => {
await legacyService.start(startDeps);
const [mockKbnServer] = MockKbnServer.mock.instances;
const [mockKbnServer] = MockKbnServer.mock.instances as Array<jest.Mocked<KbnServer>>;
expect(mockKbnServer.applyLoggingConfiguration).not.toHaveBeenCalled();
config$.next(new ObjectToConfigAdapter({ logging: { verbose: true } }));
@ -224,7 +224,7 @@ describe('once LegacyService is started with connection info', () => {
test('logs error if re-configuring fails.', async () => {
await legacyService.start(startDeps);
const [mockKbnServer] = MockKbnServer.mock.instances;
const [mockKbnServer] = MockKbnServer.mock.instances as Array<jest.Mocked<KbnServer>>;
expect(mockKbnServer.applyLoggingConfiguration).not.toHaveBeenCalled();
expect(logger.mockCollect().error).toEqual([]);
@ -292,7 +292,7 @@ describe('once LegacyService is started without connection info', () => {
});
test('reconfigures logging configuration if new config is received.', async () => {
const [mockKbnServer] = MockKbnServer.mock.instances;
const [mockKbnServer] = MockKbnServer.mock.instances as Array<jest.Mocked<KbnServer>>;
expect(mockKbnServer.applyLoggingConfiguration).not.toHaveBeenCalled();
config$.next(new ObjectToConfigAdapter({ logging: { verbose: true } }));

View file

@ -46,6 +46,7 @@ export const CopySourceTask = {
'webpackShims/**',
'config/kibana.yml',
'tsconfig*.json',
'kibana.d.ts'
],
});
},

View file

@ -24,6 +24,11 @@ export const TranspileTypescriptTask = {
description: 'Transpiling sources with typescript compiler',
async run(config, log, build) {
// the types project is built inside the repo so x-pack can use it for it's in-repo build.
const typesProjectRepo = new Project(config.resolveFromRepo('tsconfig.types.json'));
const typesProjectBuild = new Project(build.resolvePath('tsconfig.types.json'));
// these projects are built in the build folder
const defaultProject = new Project(build.resolvePath('tsconfig.json'));
const browserProject = new Project(build.resolvePath('tsconfig.browser.json'));
@ -46,8 +51,15 @@ export const TranspileTypescriptTask = {
]
}));
const projects = [
typesProjectRepo.tsConfigPath,
typesProjectBuild.tsConfigPath,
defaultProject.tsConfigPath,
browserProject.tsConfigPath
];
// compile each typescript config file
for (const tsConfigPath of [defaultProject.tsConfigPath, browserProject.tsConfigPath]) {
for (const tsConfigPath of projects) {
log.info(`Compiling`, tsConfigPath, 'project');
await exec(
log,

View file

@ -0,0 +1,391 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* tslint:disable */
import {
Client as ESClient,
GenericParams,
// root params
BulkIndexDocumentsParams,
ClearScrollParams,
CountParams,
CreateDocumentParams,
DeleteDocumentParams,
DeleteDocumentByQueryParams,
DeleteScriptParams,
DeleteTemplateParams,
ExistsParams,
ExplainParams,
FieldStatsParams,
GetParams,
GetResponse,
GetScriptParams,
GetSourceParams,
GetTemplateParams,
IndexDocumentParams,
InfoParams,
MGetParams,
MSearchParams,
MSearchTemplateParams,
MTermVectorsParams,
PingParams,
PutScriptParams,
PutTemplateParams,
ReindexParams,
ReindexRethrottleParams,
RenderSearchTemplateParams,
ScrollParams,
SearchParams,
SearchShardsParams,
SearchTemplateParams,
SuggestParams,
TermvectorsParams,
UpdateDocumentParams,
UpdateDocumentByQueryParams,
MGetResponse,
MSearchResponse,
SearchResponse,
// cat
CatAliasesParams,
CatAllocationParams,
CatFielddataParams,
CatHealthParams,
CatHelpParams,
CatIndicesParams,
CatCommonParams,
CatRecoveryParams,
CatSegmentsParams,
CatShardsParams,
CatSnapshotsParams,
CatTasksParams,
CatThreadPoolParams,
// cluster
ClusterAllocationExplainParams,
ClusterGetSettingsParams,
ClusterHealthParams,
ClusterPendingTasksParams,
ClusterPutSettingsParams,
ClusterRerouteParams,
ClusterStateParams,
ClusterStatsParams,
// indices
IndicesAnalyzeParams,
IndicesClearCacheParams,
IndicesCloseParams,
IndicesCreateParams,
IndicesDeleteParams,
IndicesDeleteAliasParams,
IndicesDeleteTemplateParams,
IndicesExistsParams,
IndicesExistsAliasParams,
IndicesExistsTemplateParams,
IndicesExistsTypeParams,
IndicesFlushParams,
IndicesFlushSyncedParams,
IndicesForcemergeParams,
IndicesGetParams,
IndicesGetAliasParams,
IndicesGetFieldMappingParams,
IndicesGetMappingParams,
IndicesGetSettingsParams,
IndicesGetTemplateParams,
IndicesGetUpgradeParams,
IndicesOpenParams,
IndicesPutAliasParams,
IndicesPutMappingParams,
IndicesPutSettingsParams,
IndicesPutTemplateParams,
IndicesRecoveryParams,
IndicesRefreshParams,
IndicesRolloverParams,
IndicesSegmentsParams,
IndicesShardStoresParams,
IndicesShrinkParams,
IndicesStatsParams,
IndicesUpdateAliasesParams,
IndicesUpgradeParams,
IndicesValidateQueryParams,
// ingest
IngestDeletePipelineParams,
IngestGetPipelineParams,
IngestPutPipelineParams,
IngestSimulateParams,
// nodes
NodesHotThreadsParams,
NodesInfoParams,
NodesStatsParams,
// snapshot
SnapshotCreateParams,
SnapshotCreateRepositoryParams,
SnapshotDeleteParams,
SnapshotDeleteRepositoryParams,
SnapshotGetParams,
SnapshotGetRepositoryParams,
SnapshotRestoreParams,
SnapshotStatusParams,
SnapshotVerifyRepositoryParams,
// tasks
TasksCancelParams,
TasksGetParams,
TasksListParams,
} from 'elasticsearch';
/* tslint:enable */
export class Cluster {
public callWithRequest: CallClusterWithRequest;
public callWithInternalUser: CallClusterWithInternalUser;
public constructor(config: ClusterConfig);
}
export interface ClusterConfig {
[option: string]: any;
}
export interface Request {
headers: RequestHeaders;
}
interface RequestHeaders {
[name: string]: string;
}
interface ElasticsearchClientLogging {
error(err: Error): void;
warning(message: string): void;
trace(method: string, options: { path: string }, query?: string, statusCode?: number): void;
info(): void;
debug(): void;
close(): void;
}
interface AssistantAPIClientParams extends GenericParams {
path: '/_xpack/migration/assistance';
method: 'GET';
}
type MIGRATION_ASSISTANCE_INDEX_ACTION = 'upgrade' | 'reindex';
type MIGRATION_DEPRECATION_LEVEL = 'none' | 'info' | 'warning' | 'critical';
export interface AssistanceAPIResponse {
indices: {
[indexName: string]: {
action_required: MIGRATION_ASSISTANCE_INDEX_ACTION;
};
};
}
interface DeprecationAPIClientParams extends GenericParams {
path: '/_xpack/migration/deprecations';
method: 'GET';
}
export interface DeprecationInfo {
level: MIGRATION_DEPRECATION_LEVEL;
message: string;
url: string;
details?: string;
}
export interface DeprecationAPIResponse {
cluster_settings: DeprecationInfo[];
node_settings: DeprecationInfo[];
index_settings: {
[indexName: string]: DeprecationInfo[];
};
}
export interface CallClusterOptions {
wrap401Errors?: boolean;
}
export interface CallClusterWithRequest {
/* tslint:disable */
(request: Request, endpoint: 'bulk', params: BulkIndexDocumentsParams, options?: CallClusterOptions): ReturnType<ESClient['bulk']>;
(request: Request, endpoint: 'clearScroll', params: ClearScrollParams, options?: CallClusterOptions): ReturnType<ESClient['clearScroll']>;
(request: Request, endpoint: 'count', params: CountParams, options?: CallClusterOptions): ReturnType<ESClient['count']>;
(request: Request, endpoint: 'create', params: CreateDocumentParams, options?: CallClusterOptions): ReturnType<ESClient['create']>;
(request: Request, endpoint: 'delete', params: DeleteDocumentParams, options?: CallClusterOptions): ReturnType<ESClient['delete']>;
(request: Request, endpoint: 'deleteByQuery', params: DeleteDocumentByQueryParams, options?: CallClusterOptions): ReturnType<ESClient['deleteByQuery']>;
(request: Request, endpoint: 'deleteScript', params: DeleteScriptParams, options?: CallClusterOptions): ReturnType<ESClient['deleteScript']>;
(request: Request, endpoint: 'deleteTemplate', params: DeleteTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['deleteTemplate']>;
(request: Request, endpoint: 'exists', params: ExistsParams, options?: CallClusterOptions): ReturnType<ESClient['exists']>;
(request: Request, endpoint: 'explain', params: ExplainParams, options?: CallClusterOptions): ReturnType<ESClient['explain']>;
(request: Request, endpoint: 'fieldStats', params: FieldStatsParams, options?: CallClusterOptions): ReturnType<ESClient['fieldStats']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(request: Request, endpoint: 'get', params: GetParams, options?: CallClusterOptions): Promise<GetResponse<T>>;
(request: Request, endpoint: 'getScript', params: GetScriptParams, options?: CallClusterOptions): ReturnType<ESClient['getScript']>;
(request: Request, endpoint: 'getSource', params: GetSourceParams, options?: CallClusterOptions): ReturnType<ESClient['getSource']>;
(request: Request, endpoint: 'getTemplate', params: GetTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['getTemplate']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(request: Request, endpoint: 'index', params: IndexDocumentParams<T>, options?: CallClusterOptions): ReturnType<ESClient['index']>;
(request: Request, endpoint: 'info', params: InfoParams, options?: CallClusterOptions): ReturnType<ESClient['info']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(request: Request, endpoint: 'mget', params: MGetParams, options?: CallClusterOptions): Promise<MGetResponse<T>>;
<T>(request: Request, endpoint: 'msearch', params: MSearchParams, options?: CallClusterOptions): Promise<MSearchResponse<T>>;
<T>(request: Request, endpoint: 'msearchTemplate', params: MSearchTemplateParams, options?: CallClusterOptions): Promise<MSearchResponse<T>>;
(request: Request, endpoint: 'mtermvectors', params: MTermVectorsParams, options?: CallClusterOptions): ReturnType<ESClient['mtermvectors']>;
(request: Request, endpoint: 'ping', params: PingParams, options?: CallClusterOptions): ReturnType<ESClient['ping']>;
(request: Request, endpoint: 'putScript', params: PutScriptParams, options?: CallClusterOptions): ReturnType<ESClient['putScript']>;
(request: Request, endpoint: 'putTemplate', params: PutTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['putTemplate']>;
(request: Request, endpoint: 'reindex', params: ReindexParams, options?: CallClusterOptions): ReturnType<ESClient['reindex']>;
(request: Request, endpoint: 'reindexRethrottle', params: ReindexRethrottleParams, options?: CallClusterOptions): ReturnType<ESClient['reindexRethrottle']>;
(request: Request, endpoint: 'renderSearchTemplate', params: RenderSearchTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['renderSearchTemplate']>;
// Generic types cannot be properly looked up with ReturnType. Hard code these explicitly.
<T>(request: Request, endpoint: 'scroll', params: ScrollParams, options?: CallClusterOptions): Promise<SearchResponse<T>>;
<T>(request: Request, endpoint: 'search', params: SearchParams, options?: CallClusterOptions): Promise<SearchResponse<T>>;
(request: Request, endpoint: 'searchShards', params: SearchShardsParams, options?: CallClusterOptions): ReturnType<ESClient['searchShards']>;
(request: Request, endpoint: 'searchTemplate', params: SearchTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['searchTemplate']>;
(request: Request, endpoint: 'suggest', params: SuggestParams, options?: CallClusterOptions): ReturnType<ESClient['suggest']>;
(request: Request, endpoint: 'termvectors', params: TermvectorsParams, options?: CallClusterOptions): ReturnType<ESClient['termvectors']>;
(request: Request, endpoint: 'update', params: UpdateDocumentParams, options?: CallClusterOptions): ReturnType<ESClient['update']>;
(request: Request, endpoint: 'updateByQuery', params: UpdateDocumentByQueryParams, options?: CallClusterOptions): ReturnType<ESClient['updateByQuery']>;
// cat namespace
(request: Request, endpoint: 'cat.aliases', params: CatAliasesParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['aliases']>;
(request: Request, endpoint: 'cat.allocation', params: CatAllocationParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['allocation']>;
(request: Request, endpoint: 'cat.count', params: CatAllocationParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['count']>;
(request: Request, endpoint: 'cat.fielddata', params: CatFielddataParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['fielddata']>;
(request: Request, endpoint: 'cat.health', params: CatHealthParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['health']>;
(request: Request, endpoint: 'cat.help', params: CatHelpParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['help']>;
(request: Request, endpoint: 'cat.indices', params: CatIndicesParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['indices']>;
(request: Request, endpoint: 'cat.master', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['master']>;
(request: Request, endpoint: 'cat.nodeattrs', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['nodeattrs']>;
(request: Request, endpoint: 'cat.nodes', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['nodes']>;
(request: Request, endpoint: 'cat.pendingTasks', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['pendingTasks']>;
(request: Request, endpoint: 'cat.plugins', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['plugins']>;
(request: Request, endpoint: 'cat.recovery', params: CatRecoveryParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['recovery']>;
(request: Request, endpoint: 'cat.repositories', params: CatCommonParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['repositories']>;
(request: Request, endpoint: 'cat.segments', params: CatSegmentsParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['segments']>;
(request: Request, endpoint: 'cat.shards', params: CatShardsParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['shards']>;
(request: Request, endpoint: 'cat.snapshots', params: CatSnapshotsParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['snapshots']>;
(request: Request, endpoint: 'cat.tasks', params: CatTasksParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['tasks']>;
(request: Request, endpoint: 'cat.threadPool', params: CatThreadPoolParams, options?: CallClusterOptions): ReturnType<ESClient['cat']['threadPool']>;
// cluster namespace
(request: Request, endpoint: 'cluster.allocationExplain', params: ClusterAllocationExplainParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['allocationExplain']>;
(request: Request, endpoint: 'cluster.getSettings', params: ClusterGetSettingsParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['getSettings']>;
(request: Request, endpoint: 'cluster.health', params: ClusterHealthParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['health']>;
(request: Request, endpoint: 'cluster.pendingTasks', params: ClusterPendingTasksParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['pendingTasks']>;
(request: Request, endpoint: 'cluster.putSettings', params: ClusterPutSettingsParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['putSettings']>;
(request: Request, endpoint: 'cluster.reroute', params: ClusterRerouteParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['reroute']>;
(request: Request, endpoint: 'cluster.state', params: ClusterStateParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['state']>;
(request: Request, endpoint: 'cluster.stats', params: ClusterStatsParams, options?: CallClusterOptions): ReturnType<ESClient['cluster']['stats']>;
// indices namespace
(request: Request, endpoint: 'indices.analyze', params: IndicesAnalyzeParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['analyze']>;
(request: Request, endpoint: 'indices.clearCache', params: IndicesClearCacheParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['clearCache']>;
(request: Request, endpoint: 'indices.close', params: IndicesCloseParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['close']>;
(request: Request, endpoint: 'indices.create', params: IndicesCreateParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['create']>;
(request: Request, endpoint: 'indices.delete', params: IndicesDeleteParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['delete']>;
(request: Request, endpoint: 'indices.deleteAlias', params: IndicesDeleteAliasParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['deleteAlias']>;
(request: Request, endpoint: 'indices.deleteTemplate', params: IndicesDeleteTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['deleteTemplate']>;
(request: Request, endpoint: 'indices.exists', params: IndicesExistsParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['exists']>;
(request: Request, endpoint: 'indices.existsAlias', params: IndicesExistsAliasParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['existsAlias']>;
(request: Request, endpoint: 'indices.existsTemplate', params: IndicesExistsTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['existsTemplate']>;
(request: Request, endpoint: 'indices.existsType', params: IndicesExistsTypeParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['existsType']>;
(request: Request, endpoint: 'indices.flush', params: IndicesFlushParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['flush']>;
(request: Request, endpoint: 'indices.flushSynced', params: IndicesFlushSyncedParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['flushSynced']>;
(request: Request, endpoint: 'indices.forcemerge', params: IndicesForcemergeParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['forcemerge']>;
(request: Request, endpoint: 'indices.get', params: IndicesGetParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['get']>;
(request: Request, endpoint: 'indices.getAlias', params: IndicesGetAliasParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getAlias']>;
(request: Request, endpoint: 'indices.getFieldMapping', params: IndicesGetFieldMappingParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getFieldMapping']>;
(request: Request, endpoint: 'indices.getMapping', params: IndicesGetMappingParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getMapping']>;
(request: Request, endpoint: 'indices.getSettings', params: IndicesGetSettingsParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getSettings']>;
(request: Request, endpoint: 'indices.getTemplate', params: IndicesGetTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getTemplate']>;
(request: Request, endpoint: 'indices.getUpgrade', params: IndicesGetUpgradeParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['getUpgrade']>;
(request: Request, endpoint: 'indices.open', params: IndicesOpenParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['open']>;
(request: Request, endpoint: 'indices.putAlias', params: IndicesPutAliasParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['putAlias']>;
(request: Request, endpoint: 'indices.putMapping', params: IndicesPutMappingParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['putMapping']>;
(request: Request, endpoint: 'indices.putSettings', params: IndicesPutSettingsParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['putSettings']>;
(request: Request, endpoint: 'indices.putTemplate', params: IndicesPutTemplateParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['putTemplate']>;
(request: Request, endpoint: 'indices.recovery', params: IndicesRecoveryParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['recovery']>;
(request: Request, endpoint: 'indices.refresh', params: IndicesRefreshParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['refresh']>;
(request: Request, endpoint: 'indices.rollover', params: IndicesRolloverParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['rollover']>;
(request: Request, endpoint: 'indices.segments', params: IndicesSegmentsParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['segments']>;
(request: Request, endpoint: 'indices.shardStores', params: IndicesShardStoresParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['shardStores']>;
(request: Request, endpoint: 'indices.shrink', params: IndicesShrinkParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['shrink']>;
(request: Request, endpoint: 'indices.stats', params: IndicesStatsParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['stats']>;
(request: Request, endpoint: 'indices.updateAliases', params: IndicesUpdateAliasesParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['updateAliases']>;
(request: Request, endpoint: 'indices.upgrade', params: IndicesUpgradeParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['upgrade']>;
(request: Request, endpoint: 'indices.validateQuery', params: IndicesValidateQueryParams, options?: CallClusterOptions): ReturnType<ESClient['indices']['validateQuery']>;
// ingest namepsace
(request: Request, endpoint: 'ingest.deletePipeline', params: IngestDeletePipelineParams, options?: CallClusterOptions): ReturnType<ESClient['ingest']['deletePipeline']>;
(request: Request, endpoint: 'ingest.getPipeline', params: IngestGetPipelineParams, options?: CallClusterOptions): ReturnType<ESClient['ingest']['getPipeline']>;
(request: Request, endpoint: 'ingest.putPipeline', params: IngestPutPipelineParams, options?: CallClusterOptions): ReturnType<ESClient['ingest']['putPipeline']>;
(request: Request, endpoint: 'ingest.simulate', params: IngestSimulateParams, options?: CallClusterOptions): ReturnType<ESClient['ingest']['simulate']>;
// nodes namespace
(request: Request, endpoint: 'nodes.hotThreads', params: NodesHotThreadsParams, options?: CallClusterOptions): ReturnType<ESClient['nodes']['hotThreads']>;
(request: Request, endpoint: 'nodes.info', params: NodesInfoParams, options?: CallClusterOptions): ReturnType<ESClient['nodes']['info']>;
(request: Request, endpoint: 'nodes.stats', params: NodesStatsParams, options?: CallClusterOptions): ReturnType<ESClient['nodes']['stats']>;
// snapshot namespace
(request: Request, endpoint: 'snapshot.create', params: SnapshotCreateParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['create']>;
(request: Request, endpoint: 'snapshot.createRepository', params: SnapshotCreateRepositoryParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['createRepository']>;
(request: Request, endpoint: 'snapshot.delete', params: SnapshotDeleteParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['delete']>;
(request: Request, endpoint: 'snapshot.deleteRepository', params: SnapshotDeleteRepositoryParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['deleteRepository']>;
(request: Request, endpoint: 'snapshot.get', params: SnapshotGetParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['get']>;
(request: Request, endpoint: 'snapshot.getRepository', params: SnapshotGetRepositoryParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['getRepository']>;
(request: Request, endpoint: 'snapshot.restore', params: SnapshotRestoreParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['restore']>;
(request: Request, endpoint: 'snapshot.status', params: SnapshotStatusParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['status']>;
(request: Request, endpoint: 'snapshot.verifyRepository', params: SnapshotVerifyRepositoryParams, options?: CallClusterOptions): ReturnType<ESClient['snapshot']['verifyRepository']>;
// tasks namespace
(request: Request, endpoint: 'tasks.cancel', params: TasksCancelParams, options?: CallClusterOptions): ReturnType<ESClient['tasks']['cancel']>;
(request: Request, endpoint: 'tasks.get', params: TasksGetParams, options?: CallClusterOptions): ReturnType<ESClient['tasks']['get']>;
(request: Request, endpoint: 'tasks.list', params: TasksListParams, options?: CallClusterOptions): ReturnType<ESClient['tasks']['list']>;
/* tslint:enable */
// other APIs accessed via transport.request
(
request: Request,
endpoint: 'transport.request',
clientParams: AssistantAPIClientParams,
options?: {}
): Promise<AssistanceAPIResponse>;
(
request: Request,
endpoint: 'transport.request',
clientParams: DeprecationAPIClientParams,
options?: {}
): Promise<DeprecationAPIResponse>;
// Catch-all definition
<T = any>(
request: Request,
endpoint: string,
clientParams: GenericParams,
options?: CallClusterOptions
): Promise<T>;
}
export type CallClusterWithInternalUser = <T = any>(
endpoint: string,
clientParams: GenericParams,
options?: CallClusterOptions
) => Promise<T>;
export interface ElasticsearchPlugin {
ElasticsearchClientLogging: ElasticsearchClientLogging;
getCluster(name: string): Cluster;
createCluster(name: string, config: ClusterConfig): Cluster;
filterHeaders(originalHeaders: RequestHeaders, headersToKeep: string[]): void;
waitUntilReady(): Promise<void>;
}

View file

@ -1,4 +1,5 @@
{
"name": "elasticsearch",
"version": "kibana"
"version": "kibana",
"types": "index.d.ts"
}

56
src/server/kbn_server.d.ts vendored Normal file
View file

@ -0,0 +1,56 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Server } from 'hapi';
import { ElasticsearchPlugin } from '../legacy/core_plugins/elasticsearch';
export interface KibanaConfig {
get<T>(key: string): T;
}
// Extend the defaults with the plugins and server methods we need.
declare module 'hapi' {
interface PluginProperties {
elasticsearch: ElasticsearchPlugin;
kibana: any;
// add new plugin types here
}
interface Server {
config: () => KibanaConfig;
}
}
type KbnMixinFunc = (kbnServer: KbnServer, server: Server, config: any) => Promise<any> | void;
export default class KbnServer {
public server: Server;
public inject: Server['inject'];
constructor(settings: any, core: any);
public ready(): Promise<void>;
public mixin(...fns: KbnMixinFunc[]): Promise<void>;
public listen(): Promise<Server>;
public close(): Promise<void>;
public applyLoggingConfiguration(settings: any): void;
}
// Re-export commonly used hapi types.
export { Server, Request, ResponseToolkit } from 'hapi';

View file

@ -2,6 +2,8 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
// Allows for importing from `kibana` package for the exported types.
"kibana": ["./kibana"],
"ui/*": [
"src/ui/public/*"
],
@ -47,6 +49,7 @@
"importHelpers": true
},
"include": [
"kibana.d.ts",
"src/**/*",
"typings/**/*"
],

View file

@ -35,10 +35,9 @@
"@types/d3-shape": "^1.2.2",
"@types/d3-time": "^1.0.7",
"@types/d3-time-format": "^2.1.0",
"@types/elasticsearch": "^5.0.26",
"@types/elasticsearch": "^5.0.30",
"@types/expect.js": "^0.3.29",
"@types/graphql": "^0.13.1",
"@types/hapi": "^17.0.18",
"@types/history": "^4.6.2",
"@types/jest": "^23.3.1",
"@types/joi": "^13.4.2",

View file

@ -6,28 +6,13 @@
/* tslint:disable no-console */
import { AggregationSearchResponse, SearchParams } from 'elasticsearch';
import { Request } from 'hapi';
import { Legacy } from 'kibana';
import moment from 'moment';
function decodeEsQuery(esQuery?: string): object {
return esQuery ? JSON.parse(decodeURIComponent(esQuery)) : null;
}
interface KibanaConfig {
get: <T = void>(key: string) => T;
}
// Extend the defaults with the plugins and server methods we need.
declare module 'hapi' {
interface PluginProperties {
elasticsearch: any;
}
interface Server {
config: () => KibanaConfig;
}
}
export type ESClient = <T = void, U = void>(
type: string,
params: SearchParams
@ -38,7 +23,7 @@ export interface Setup {
end: number;
esFilterQuery?: any;
client: ESClient;
config: KibanaConfig;
config: Legacy.KibanaConfig;
}
interface APMRequestQuery {
@ -48,7 +33,7 @@ interface APMRequestQuery {
esFilterQuery: string;
}
export function setupRequest(req: Request): Setup {
export function setupRequest(req: Legacy.Request): Setup {
const query = (req.query as unknown) as APMRequestQuery;
const cluster = req.server.plugins.elasticsearch.getCluster('data');

View file

@ -5,8 +5,9 @@
*/
import { GraphQLSchema } from 'graphql';
import { Request, ResponseToolkit, Server } from 'hapi';
import { Legacy } from 'kibana';
import { GenericParams } from 'elasticsearch';
import { InfraMetricModel } from '../metrics/adapter_types';
import {
InfraBackendFrameworkAdapter,
@ -25,18 +26,11 @@ import {
HapiGraphQLPluginOptions,
} from './apollo_server_hapi';
declare module 'hapi' {
interface PluginProperties {
elasticsearch: any;
kibana: any;
}
}
export class InfraKibanaBackendFrameworkAdapter implements InfraBackendFrameworkAdapter {
public version: string;
private server: Server;
private server: Legacy.Server;
constructor(hapiServer: Server) {
constructor(hapiServer: Legacy.Server) {
this.server = hapiServer;
this.version = hapiServer.plugins.kibana.status.plugin.version;
}
@ -56,7 +50,7 @@ export class InfraKibanaBackendFrameworkAdapter implements InfraBackendFramework
public registerGraphQLEndpoint(routePath: string, schema: GraphQLSchema): void {
this.server.register<HapiGraphQLPluginOptions>({
options: {
graphqlOptions: (req: Request) => ({
graphqlOptions: (req: Legacy.Request) => ({
context: { req: wrapRequest(req) },
schema,
}),
@ -81,7 +75,7 @@ export class InfraKibanaBackendFrameworkAdapter implements InfraBackendFramework
RouteRequest extends InfraWrappableRequest,
RouteResponse extends InfraResponse
>(route: InfraFrameworkRouteOptions<RouteRequest, RouteResponse>) {
const wrappedHandler = (request: any, h: ResponseToolkit) =>
const wrappedHandler = (request: any, h: Legacy.ResponseToolkit) =>
route.handler(wrapRequest(request), h);
this.server.route({
@ -91,26 +85,31 @@ export class InfraKibanaBackendFrameworkAdapter implements InfraBackendFramework
});
}
public async callWithRequest(req: InfraFrameworkRequest<Request>, ...rest: any[]) {
public async callWithRequest(
req: InfraFrameworkRequest<Legacy.Request>,
endpoint: string,
params: GenericParams,
...rest: any[]
) {
const internalRequest = req[internalInfraFrameworkRequest];
const { elasticsearch } = internalRequest.server.plugins;
const { callWithRequest } = elasticsearch.getCluster('data');
const fields = await callWithRequest(internalRequest, ...rest);
const fields = await callWithRequest(internalRequest, endpoint, params, ...rest);
return fields;
}
public getIndexPatternsService(
request: InfraFrameworkRequest<Request>
request: InfraFrameworkRequest<Legacy.Request>
): InfraFrameworkIndexPatternsService {
if (!isServerWithIndexPatternsServiceFactory(this.server)) {
throw new Error('Failed to access indexPatternsService for the request');
}
return this.server.indexPatternsServiceFactory({
callCluster: async (method: string, args: [object], ...rest: any[]) => {
callCluster: async (method: string, args: [GenericParams], ...rest: any[]) => {
const fieldCaps = await this.callWithRequest(
request,
method,
{ ...args, allowNoIndices: true },
{ ...args, allowNoIndices: true } as GenericParams,
...rest
);
return fieldCaps;
@ -119,7 +118,7 @@ export class InfraKibanaBackendFrameworkAdapter implements InfraBackendFramework
}
public async makeTSVBRequest(
req: InfraFrameworkRequest<Request>,
req: InfraFrameworkRequest<Legacy.Request>,
model: InfraMetricModel,
timerange: { min: number; max: number },
filters: any[]
@ -159,13 +158,13 @@ export function wrapRequest<InternalRequest extends InfraWrappableRequest>(
};
}
interface ServerWithIndexPatternsServiceFactory extends Server {
interface ServerWithIndexPatternsServiceFactory extends Legacy.Server {
indexPatternsServiceFactory(options: {
callCluster: (...args: any[]) => any;
}): InfraFrameworkIndexPatternsService;
}
const isServerWithIndexPatternsServiceFactory = (
server: Server
server: Legacy.Server
): server is ServerWithIndexPatternsServiceFactory =>
typeof (server as any).indexPatternsServiceFactory === 'function';

View file

@ -1190,10 +1190,10 @@
resolved "https://registry.yarnpkg.com/@types/delete-empty/-/delete-empty-2.0.0.tgz#1647ae9e68f708a6ba778531af667ec55bc61964"
integrity sha512-sq+kwx8zA9BSugT9N+Jr8/uWjbHMZ+N/meJEzRyT3gmLq/WMtx/iSIpvdpmBUi/cvXl6Kzpvve8G2ESkabFwmg==
"@types/elasticsearch@^5.0.26":
version "5.0.28"
resolved "https://registry.yarnpkg.com/@types/elasticsearch/-/elasticsearch-5.0.28.tgz#0e4cdf7d9c9a3fe901c0da4fb9ad824c6d3b4091"
integrity sha512-hM9Rs1trCkthBz1z9UwAJKQ4/ZaNnKbKB2Utf4iuY91OssLMUHzXZP8mBrkUif4kp/bNOPt6w92L9YmL2nSMuA==
"@types/elasticsearch@^5.0.30":
version "5.0.30"
resolved "https://registry.yarnpkg.com/@types/elasticsearch/-/elasticsearch-5.0.30.tgz#3c52f7119e3a20a47e2feb8e2b4cc54030a54e23"
integrity sha512-swxiNcLOtnHhJhAE5HcUL3WsKLHr8rEQ+fwpaJ0x4dfEE3oK2kGUoyz4wCcQfvulcMm2lShyxZ+2E4BQJzsAlg==
"@types/enzyme@^3.1.12":
version "3.1.12"