[7.x] [ts] upgrade to 3.5.3 (#40228) (#40795)

* [ts] upgrade to 3.5.3 (#40228)

* [ts] upgrade to 3.5.2

* [ts] run from cwd so that relative paths are correct

* move eslint-disable-line comment into jsx attribute

* autofix eslint violations

* avoid generic type, it's not necessary and problematic

* make elasticsearch.cluster optional, many instances don't have them

* remove invalid prop

* expand AllowUnknownProperties to cleanly handle arrays

* esfilter values can sometimes be an array of strings

* allow exception objects to have unknown properties

* define accumulator as a boolean

* fix return type

* return a 404 if beat isn't found after update

* use Object.values for better types

* define return type of get() call

* define value type for Set

* define return value of get()

* define State property type

* use less get(), so ts can infer types

* define Set item type

* map state type

* make default_operator optional, since it's not always defined

* remove seemingly unused prop

* define return type of get() fn

* define inner type for state

* don't define base types are objects with index signatues

* regenerate public api docs

* make indices privileges optional too

* remove unnecessary index-signature from Exception interface

* use variadic _arg instead

* [core/plugin] use Record<string, any> rather than {}

* replace a couple more instances of {}

* revert some unnecessary changes

* remove unused types

* [reporting] output, payload, and meta are required properties

* bump to latest patch version

# Conflicts:
#	x-pack/legacy/plugins/canvas/server/usage/custom_element_collector.ts
#	x-pack/legacy/plugins/canvas/server/usage/workpad_collector.ts

* define inner type for Set

* default `config.get()` to any instead of unknown
This commit is contained in:
Spencer 2019-07-10 15:22:35 -07:00 committed by GitHub
parent 7711dde9d3
commit 1591c25148
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
85 changed files with 272 additions and 223 deletions

View file

@ -9,5 +9,5 @@ The `plugin` export at the root of a plugin's `public` directory should conform
<b>Signature:</b>
```typescript
export declare type PluginInitializer<TSetup, TStart, TPluginsSetup extends Record<string, unknown> = {}, TPluginsStart extends Record<string, unknown> = {}> = (core: PluginInitializerContext) => Plugin<TSetup, TStart, TPluginsSetup, TPluginsStart>;
export declare type PluginInitializer<TSetup, TStart, TPluginsSetup extends Record<string, any> = {}, TPluginsStart extends Record<string, any> = {}> = (core: PluginInitializerContext) => Plugin<TSetup, TStart, TPluginsSetup, TPluginsStart>;
```

View file

@ -18,6 +18,6 @@ export interface DiscoveredPlugin
| --- | --- | --- |
| [configPath](./kibana-plugin-server.discoveredplugin.configpath.md) | <code>ConfigPath</code> | Root configuration path used by the plugin, defaults to "id". |
| [id](./kibana-plugin-server.discoveredplugin.id.md) | <code>PluginName</code> | Identifier of the plugin. |
| [optionalPlugins](./kibana-plugin-server.discoveredplugin.optionalplugins.md) | <code>ReadonlyArray&lt;PluginName&gt;</code> | An optional list of the other plugins that if installed and enabled \*\*may be\*\* leveraged by this plugin for some additional functionality but otherwise are not required for this plugin to work properly. |
| [requiredPlugins](./kibana-plugin-server.discoveredplugin.requiredplugins.md) | <code>ReadonlyArray&lt;PluginName&gt;</code> | An optional list of the other plugins that \*\*must be\*\* installed and enabled for this plugin to function properly. |
| [optionalPlugins](./kibana-plugin-server.discoveredplugin.optionalplugins.md) | <code>readonly PluginName[]</code> | An optional list of the other plugins that if installed and enabled \*\*may be\*\* leveraged by this plugin for some additional functionality but otherwise are not required for this plugin to work properly. |
| [requiredPlugins](./kibana-plugin-server.discoveredplugin.requiredplugins.md) | <code>readonly PluginName[]</code> | An optional list of the other plugins that \*\*must be\*\* installed and enabled for this plugin to function properly. |

View file

@ -9,5 +9,5 @@ An optional list of the other plugins that if installed and enabled \*\*may be\*
<b>Signature:</b>
```typescript
readonly optionalPlugins: ReadonlyArray<PluginName>;
readonly optionalPlugins: readonly PluginName[];
```

View file

@ -9,5 +9,5 @@ An optional list of the other plugins that \*\*must be\*\* installed and enabled
<b>Signature:</b>
```typescript
readonly requiredPlugins: ReadonlyArray<PluginName>;
readonly requiredPlugins: readonly PluginName[];
```

View file

@ -17,5 +17,5 @@ export interface RouteConfigOptions
| Property | Type | Description |
| --- | --- | --- |
| [authRequired](./kibana-plugin-server.routeconfigoptions.authrequired.md) | <code>boolean</code> | A flag shows that authentication for a route: enabled when true disabled when false<!-- -->Enabled by default. |
| [tags](./kibana-plugin-server.routeconfigoptions.tags.md) | <code>ReadonlyArray&lt;string&gt;</code> | Additional metadata tag strings to attach to the route. |
| [tags](./kibana-plugin-server.routeconfigoptions.tags.md) | <code>readonly string[]</code> | Additional metadata tag strings to attach to the route. |

View file

@ -9,5 +9,5 @@ Additional metadata tag strings to attach to the route.
<b>Signature:</b>
```typescript
tags?: ReadonlyArray<string>;
tags?: readonly string[];
```

View file

@ -79,7 +79,7 @@
"resolutions": {
"**/@types/node": "10.12.27",
"**/@types/hapi": "^17.0.18",
"**/typescript": "^3.3.3333"
"**/typescript": "3.5.3"
},
"workspaces": {
"packages": [
@ -337,8 +337,8 @@
"@types/type-detect": "^4.0.1",
"@types/uuid": "^3.4.4",
"@types/zen-observable": "^0.8.0",
"@typescript-eslint/eslint-plugin": "^1.6.0",
"@typescript-eslint/parser": "^1.6.0",
"@typescript-eslint/eslint-plugin": "1.11.0",
"@typescript-eslint/parser": "1.11.0",
"angular-mocks": "1.4.7",
"archiver": "^3.0.0",
"babel-eslint": "10.0.2",
@ -429,7 +429,7 @@
"supertest": "^3.1.0",
"supertest-as-promised": "^4.0.2",
"tree-kill": "^1.1.0",
"typescript": "^3.3.3333",
"typescript": "3.5.3",
"typings-tester": "^0.3.2",
"vinyl-fs": "^3.0.2",
"xml2js": "^0.4.19",

View file

@ -15,8 +15,8 @@
},
"homepage": "https://github.com/elastic/eslint-config-kibana#readme",
"peerDependencies": {
"@typescript-eslint/eslint-plugin": "^1.6.0",
"@typescript-eslint/parser": "^1.6.0",
"@typescript-eslint/eslint-plugin": "1.11.0",
"@typescript-eslint/parser": "1.11.0",
"babel-eslint": "10.0.2",
"eslint": "5.16.0",
"eslint-plugin-babel": "5.3.0",

View file

@ -10,7 +10,7 @@
"kbn:bootstrap": "yarn build"
},
"devDependencies": {
"typescript": "^3.3.3333"
"typescript": "3.5.3"
},
"peerDependencies": {
"joi": "^13.5.2",

View file

@ -20,7 +20,7 @@
"@babel/core": "7.4.5",
"@babel/plugin-transform-async-to-generator": "7.4.4",
"jest": "^24.8.0",
"typescript": "^3.3.3333"
"typescript": "3.5.3"
},
"jest": {
"testEnvironment": "node"

View file

@ -28,6 +28,6 @@
"del": "^4.0.0",
"getopts": "^2.2.4",
"supports-color": "^6.1.0",
"typescript": "^3.3.3333"
"typescript": "3.5.3"
}
}

View file

@ -25,7 +25,7 @@
"del": "^4.0.0",
"getopts": "^2.2.4",
"supports-color": "^6.1.0",
"typescript": "^3.3.3333"
"typescript": "3.5.3"
},
"dependencies": {
"intl-format-cache": "^2.1.0",

View file

@ -61,7 +61,7 @@
"strip-ansi": "^4.0.0",
"strong-log-transformer": "^2.1.0",
"tempy": "^0.3.0",
"typescript": "^3.3.3333",
"typescript": "3.5.3",
"unlazy-loader": "^0.1.3",
"webpack": "^4.23.1",
"webpack-cli": "^3.1.2",

View file

@ -21,7 +21,7 @@ import { deepFreeze } from '../../../utils/';
import { MixedApp } from '../application_service';
const createStartContractMock = (
apps: ReadonlyArray<MixedApp> = []
apps: readonly MixedApp[] = []
): jest.Mocked<CapabilitiesStart> => ({
availableApps: apps,
capabilities: deepFreeze({

View file

@ -22,7 +22,7 @@ import { MixedApp } from '../application_service';
import { InjectedMetadataStart } from '../../injected_metadata';
interface StartDeps {
apps: ReadonlyArray<MixedApp>;
apps: readonly MixedApp[];
injectedMetadata: InjectedMetadataStart;
}
@ -63,7 +63,7 @@ export interface CapabilitiesStart {
* Apps available based on the current capabilities. Should be used
* to show navigation links and make routing decisions.
*/
availableApps: ReadonlyArray<MixedApp>;
availableApps: readonly MixedApp[];
}
/** @internal */

View file

@ -159,8 +159,8 @@ interface Props {
recentlyAccessed$: Rx.Observable<ChromeRecentlyAccessedHistoryItem[]>;
forceAppSwitcherNavigation$: Rx.Observable<boolean>;
helpExtension$: Rx.Observable<ChromeHelpExtension>;
navControlsLeft$: Rx.Observable<ReadonlyArray<ChromeNavControl>>;
navControlsRight$: Rx.Observable<ReadonlyArray<ChromeNavControl>>;
navControlsLeft$: Rx.Observable<readonly ChromeNavControl[]>;
navControlsRight$: Rx.Observable<readonly ChromeNavControl[]>;
intl: InjectedIntl;
basePath: HttpStart['basePath'];
}
@ -171,8 +171,8 @@ interface State {
navLinks: ReadonlyArray<ReturnType<typeof extendNavLink>>;
recentlyAccessed: ReadonlyArray<ReturnType<typeof extendRecentlyAccessedHistoryItem>>;
forceNavigation: boolean;
navControlsLeft: ReadonlyArray<ChromeNavControl>;
navControlsRight: ReadonlyArray<ChromeNavControl>;
navControlsLeft: readonly ChromeNavControl[];
navControlsRight: readonly ChromeNavControl[];
}
class HeaderUI extends Component<Props, State> {

View file

@ -28,7 +28,7 @@ import { HeaderExtension } from './header_extension';
import { ChromeNavControl } from '../../nav_controls';
interface Props {
navControls: ReadonlyArray<ChromeNavControl>;
navControls: readonly ChromeNavControl[];
side: 'left' | 'right';
}

View file

@ -47,8 +47,8 @@ export interface Plugin<
export type PluginInitializer<
TSetup,
TStart,
TPluginsSetup extends Record<string, unknown> = {},
TPluginsStart extends Record<string, unknown> = {}
TPluginsSetup extends Record<string, any> = {},
TPluginsStart extends Record<string, any> = {}
> = (core: PluginInitializerContext) => Plugin<TSetup, TStart, TPluginsSetup, TPluginsStart>;
/**
@ -60,8 +60,8 @@ export type PluginInitializer<
export class PluginWrapper<
TSetup = unknown,
TStart = unknown,
TPluginsSetup extends Record<PluginName, unknown> = Record<PluginName, unknown>,
TPluginsStart extends Record<PluginName, unknown> = Record<PluginName, unknown>
TPluginsSetup extends Record<PluginName, any> = Record<PluginName, unknown>,
TPluginsStart extends Record<PluginName, any> = Record<PluginName, unknown>
> {
public readonly name: DiscoveredPlugin['id'];
public readonly configPath: DiscoveredPlugin['configPath'];

View file

@ -26,7 +26,7 @@ import { LoadPluginBundle, UnknownPluginInitializer } from './plugin_loader';
const createLoadPluginBundleMock = (
initializerProvider: (name: PluginName) => UnknownPluginInitializer
): jest.Mock<ReturnType<LoadPluginBundle>, Parameters<LoadPluginBundle>> =>
jest.fn((addBasePath, pluginName) => {
jest.fn((addBasePath, pluginName, _ = {}) => {
return Promise.resolve(initializerProvider(pluginName)) as any;
});

View file

@ -485,7 +485,7 @@ export interface Plugin<TSetup = void, TStart = void, TPluginsSetup extends {} =
}
// @public
export type PluginInitializer<TSetup, TStart, TPluginsSetup extends Record<string, unknown> = {}, TPluginsStart extends Record<string, unknown> = {}> = (core: PluginInitializerContext) => Plugin<TSetup, TStart, TPluginsSetup, TPluginsStart>;
export type PluginInitializer<TSetup, TStart, TPluginsSetup extends Record<string, any> = {}, TPluginsStart extends Record<string, any> = {}> = (core: PluginInitializerContext) => Plugin<TSetup, TStart, TPluginsSetup, TPluginsStart>;
// @public
export interface PluginInitializerContext {

View file

@ -76,7 +76,7 @@ export class Env {
/** @internal */
public readonly staticFilesDir: string;
/** @internal */
public readonly pluginSearchPaths: ReadonlyArray<string>;
public readonly pluginSearchPaths: readonly string[];
/**
* Information about Kibana package (version, build number etc.).
@ -98,7 +98,7 @@ export class Env {
* Paths to the configuration files.
* @internal
*/
public readonly configs: ReadonlyArray<string>;
public readonly configs: readonly string[];
/**
* Indicates that this Kibana instance is run as development Node Cluster master.

View file

@ -38,7 +38,7 @@ export class RawConfigService {
private readonly config$: Observable<Config>;
constructor(
readonly configFiles: ReadonlyArray<string>,
readonly configFiles: readonly string[],
configAdapter: (rawConfig: Record<string, any>) => Config = rawConfig =>
new ObjectToConfigAdapter(rawConfig)
) {

View file

@ -49,7 +49,7 @@ function merge(target: Record<string, any>, value: any, key?: string) {
}
/** @internal */
export const getConfigFromFiles = (configFiles: ReadonlyArray<string>) => {
export const getConfigFromFiles = (configFiles: readonly string[]) => {
let mergedYaml = {};
for (const configFile of configFiles) {

View file

@ -41,7 +41,7 @@ export interface RouteConfigOptions {
/**
* Additional metadata tag strings to attach to the route.
*/
tags?: ReadonlyArray<string>;
tags?: readonly string[];
}
export interface RouteConfig<P extends ObjectType, Q extends ObjectType, B extends ObjectType> {

View file

@ -86,11 +86,11 @@ export class LegacyObjectToConfigAdapter extends ObjectToConfigAdapter {
const configValue = super.get(configPath);
switch (configPath) {
case 'logging':
return LegacyObjectToConfigAdapter.transformLogging(configValue);
return LegacyObjectToConfigAdapter.transformLogging(configValue as LegacyLoggingConfig);
case 'server':
return LegacyObjectToConfigAdapter.transformServer(configValue);
case 'plugins':
return LegacyObjectToConfigAdapter.transformPlugins(configValue);
return LegacyObjectToConfigAdapter.transformPlugins(configValue as Record<string, any>);
default:
return configValue;
}

View file

@ -81,7 +81,7 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) {
* @param pluginDirs List of the top-level directories to process.
* @param log Plugin discovery logger instance.
*/
function processPluginSearchPaths$(pluginDirs: ReadonlyArray<string>, log: Logger) {
function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) {
return from(pluginDirs).pipe(
mergeMap(dir => {
log.debug(`Scanning "${dir}" for plugin sub-directories...`);

View file

@ -67,14 +67,14 @@ export interface PluginManifest {
* An optional list of the other plugins that **must be** installed and enabled
* for this plugin to function properly.
*/
readonly requiredPlugins: ReadonlyArray<PluginName>;
readonly requiredPlugins: readonly PluginName[];
/**
* An optional list of the other plugins that if installed and enabled **may be**
* leveraged by this plugin for some additional functionality but otherwise are
* not required for this plugin to work properly.
*/
readonly optionalPlugins: ReadonlyArray<PluginName>;
readonly optionalPlugins: readonly PluginName[];
/**
* Specifies whether plugin includes some client/browser specific functionality
@ -108,14 +108,14 @@ export interface DiscoveredPlugin {
* An optional list of the other plugins that **must be** installed and enabled
* for this plugin to function properly.
*/
readonly requiredPlugins: ReadonlyArray<PluginName>;
readonly requiredPlugins: readonly PluginName[];
/**
* An optional list of the other plugins that if installed and enabled **may be**
* leveraged by this plugin for some additional functionality but otherwise are
* not required for this plugin to work properly.
*/
readonly optionalPlugins: ReadonlyArray<PluginName>;
readonly optionalPlugins: readonly PluginName[];
}
/**

View file

@ -45,12 +45,12 @@ export class PluginsConfig {
/**
* Defines directories that we should scan for the plugin subdirectories.
*/
public readonly pluginSearchPaths: ReadonlyArray<string>;
public readonly pluginSearchPaths: readonly string[];
/**
* Defines directories where an additional plugin exists.
*/
public readonly additionalPluginPaths: ReadonlyArray<string>;
public readonly additionalPluginPaths: readonly string[];
constructor(rawConfig: PluginsConfigType, env: Env) {
this.initialize = rawConfig.initialize;

View file

@ -575,7 +575,7 @@ describe('DocumentMigrator', () => {
function renameAttr(path: string, newPath: string) {
return (doc: RawSavedObjectDoc) =>
_.omit(_.set(doc, newPath, _.get(doc, path)), path) as RawSavedObjectDoc;
_.omit(_.set(doc, newPath, _.get(doc, path)) as {}, path) as RawSavedObjectDoc;
}
function setAttr(path: string, value: any) {

View file

@ -109,8 +109,8 @@ export interface CoreStart {
export interface DiscoveredPlugin {
readonly configPath: ConfigPath;
readonly id: PluginName;
readonly optionalPlugins: ReadonlyArray<PluginName>;
readonly requiredPlugins: ReadonlyArray<PluginName>;
readonly optionalPlugins: readonly PluginName[];
readonly requiredPlugins: readonly PluginName[];
}
// Warning: (ae-forgotten-export) The symbol "ElasticsearchConfig" needs to be exported by the entry point index.d.ts
@ -386,7 +386,7 @@ export type RecursiveReadonly<T> = T extends (...args: any[]) => any ? T : T ext
// @public
export interface RouteConfigOptions {
authRequired?: boolean;
tags?: ReadonlyArray<string>;
tags?: readonly string[];
}
// @public

View file

@ -40,7 +40,9 @@ export function execInProjects(
projects.map(project => ({
task: () =>
execa(cmd, getArgs(project), {
cwd: project.directory,
// execute in the current working directory so that relative paths in errors
// are relative from the right location
cwd: process.cwd(),
env: chalk.enabled ? { FORCE_COLOR: 'true' } : {},
stdio: ['ignore', 'pipe', 'pipe'],
}).catch(error => {

View file

@ -46,7 +46,11 @@ async function getSettingsFromFile(log: ToolingLog, path: string, settingOverrid
);
}
const settingsWithDefaults = defaultsDeep({}, settingOverrides, await cache.get(configProvider)!);
const settingsWithDefaults: any = defaultsDeep(
{},
settingOverrides,
await cache.get(configProvider)!
);
const logDeprecation = (error: string | Error) => log.error(error);
return transformDeprecations(settingsWithDefaults, logDeprecation);

View file

@ -53,7 +53,7 @@ describe('expressions_service', () => {
let testAst: Ast;
beforeEach(() => {
interpretAstMock = jest.fn(_ => Promise.resolve(expressionResult));
interpretAstMock = jest.fn((..._) => Promise.resolve(expressionResult));
interpreterMock = { interpretAst: interpretAstMock };
renderFunctionMock = ({
render: jest.fn(),

View file

@ -84,7 +84,7 @@ const config = chrome.getUiSettingsClient();
const recentSearchType: AutocompleteSuggestionType = 'recentSearch';
export class QueryBarInputUI extends Component<Props, State> {
public state = {
public state: State = {
isSuggestionsVisible: false,
index: null,
suggestions: [],

View file

@ -26,10 +26,16 @@ export interface FilterableContainerInput extends ContainerInput {
filters: Filter[];
}
export interface InheritedChildrenInput {
/**
* interfaces are not allowed to specify a sub-set of the required types until
* https://github.com/microsoft/TypeScript/issues/15300 is fixed so we use a type
* here instead
*/
// eslint-disable-next-line @typescript-eslint/prefer-interface
export type InheritedChildrenInput = {
filters: Filter[];
id?: string;
}
};
export class FilterableContainer extends Container<
InheritedChildrenInput,

View file

@ -25,11 +25,17 @@ import { EmbeddableFactory } from '../../embeddables';
export const HELLO_WORLD_CONTAINER = 'HELLO_WORLD_CONTAINER';
interface InheritedInput {
/**
* interfaces are not allowed to specify a sub-set of the required types until
* https://github.com/microsoft/TypeScript/issues/15300 is fixed so we use a type
* here instead
*/
// eslint-disable-next-line @typescript-eslint/prefer-interface
type InheritedInput = {
id: string;
viewMode: ViewMode;
lastName: string;
}
};
export class HelloWorldContainer extends Container<InheritedInput> {
public readonly type = HELLO_WORLD_CONTAINER;

View file

@ -65,6 +65,8 @@ class DashboardPanelUi extends React.Component<DashboardPanelUiProps, State> {
[panel: string]: any;
public mounted: boolean;
public embeddable!: Embeddable;
private panelElement?: HTMLDivElement;
constructor(props: DashboardPanelUiProps) {
super(props);
this.state = {
@ -100,7 +102,7 @@ class DashboardPanelUi extends React.Component<DashboardPanelUiProps, State> {
if (this.mounted) {
this.embeddable = embeddable;
embeddableIsInitialized(embeddable.metadata);
this.embeddable.render(this.panelElement, this.props.containerState);
this.embeddable.render(this.panelElement!, this.props.containerState);
} else {
embeddable.destroy();
}
@ -144,7 +146,7 @@ class DashboardPanelUi extends React.Component<DashboardPanelUiProps, State> {
<div
id="embeddedPanel"
className={classes}
ref={panelElement => (this.panelElement = panelElement)}
ref={panelElement => (this.panelElement = panelElement || undefined)}
>
{!this.props.initialized && <EuiLoadingChart size="l" mono />}
</div>

View file

@ -51,10 +51,16 @@ interface SearchScope extends ng.IScope {
filter?: (field: string, value: string, operator: string) => void;
}
interface SearchEmbeddableCustomization {
/**
* interfaces are not allowed to specify a sub-set of the required types until
* https://github.com/microsoft/TypeScript/issues/15300 is fixed so we use a type
* here instead
*/
// eslint-disable-next-line @typescript-eslint/prefer-interface
type SearchEmbeddableCustomization = {
sort?: string[];
columns?: string[];
}
};
interface SearchEmbeddableConfig {
onEmbeddableStateChanged: OnEmbeddableStateChanged;

View file

@ -49,7 +49,7 @@ export class VisualizeEmbeddable extends Embeddable {
private loader: VisualizeLoader;
private uiState: PersistedState;
private handler?: EmbeddedVisualizeHandler;
private customization?: object;
private customization?: { [key: string]: any };
private panelTitle?: string;
private timeRange?: TimeRange;
private query?: Query;

View file

@ -70,7 +70,7 @@ interface TypeSelectionState {
}
class TypeSelection extends React.Component<TypeSelectionProps, TypeSelectionState> {
public state = {
public state: TypeSelectionState = {
highlightedType: null,
query: '',
};

View file

@ -68,7 +68,7 @@ interface ContextMenuLinkOptions extends ContextMenuActionOptions {
/**
* An optional href to use as navigation when the action is clicked on.
*/
getHref?: (actionAPI: PanelActionAPI) => string;
getHref?: (actionAPI: PanelActionAPI) => string | undefined;
}
interface ContextMenuActionsConfig {
@ -106,7 +106,7 @@ export class ContextMenuAction {
/**
* @param {PanelActionAPI} panelActionAPI
*/
public readonly getHref?: (panelActionAPI: PanelActionAPI) => string;
public readonly getHref?: (panelActionAPI: PanelActionAPI) => string | undefined;
/**
* @param {PanelActionAPI} panelActionAPI

View file

@ -21,12 +21,12 @@ import { getFlattenedObject } from './get_flattened_object';
describe('getFlattenedObject()', () => {
it('throws when rootValue is not an object or is an array', () => {
expect(() => getFlattenedObject(1)).toThrowError();
expect(() => getFlattenedObject(Infinity)).toThrowError();
expect(() => getFlattenedObject(NaN)).toThrowError();
expect(() => getFlattenedObject(false)).toThrowError();
expect(() => getFlattenedObject(null)).toThrowError();
expect(() => getFlattenedObject(undefined)).toThrowError();
expect(() => getFlattenedObject(1 as any)).toThrowError();
expect(() => getFlattenedObject(Infinity as any)).toThrowError();
expect(() => getFlattenedObject(NaN as any)).toThrowError();
expect(() => getFlattenedObject(false as any)).toThrowError();
expect(() => getFlattenedObject(null as any)).toThrowError();
expect(() => getFlattenedObject(undefined as any)).toThrowError();
expect(() => getFlattenedObject([])).toThrowError();
});

View file

@ -33,21 +33,21 @@ function shouldReadKeys(value: unknown): value is Record<string, any> {
* @param {Object} rootValue
* @returns {Object}
*/
export function getFlattenedObject(rootValue: unknown) {
export function getFlattenedObject(rootValue: Record<string, any>) {
if (!shouldReadKeys(rootValue)) {
throw new TypeError(`Root value is not flatten-able, received ${rootValue}`);
}
return (function flatten<T extends Record<string, any>>(acc: T, prefix: string, object: T): T {
const result: { [key: string]: any } = {};
(function flatten(prefix, object) {
for (const [key, value] of Object.entries(object)) {
const path = prefix ? `${prefix}.${key}` : key;
if (shouldReadKeys(value)) {
flatten(acc, path, value);
flatten(path, value);
} else {
acc[path] = value;
result[path] = value;
}
}
return acc;
})({}, '', rootValue);
})('', rootValue);
return result;
}

View file

@ -546,7 +546,9 @@ export class WebElementWrapper {
const screenshot = await this.driver.takeScreenshot();
const buffer = Buffer.from(screenshot.toString(), 'base64');
const { width, height, x, y } = await this.getPosition();
const windowWidth = await this.driver.executeScript('return window.document.body.clientWidth');
const windowWidth: number = await this.driver.executeScript(
'return window.document.body.clientWidth'
);
const src = PNG.sync.read(buffer);
if (src.width > windowWidth) {
// on linux size of screenshot is double size of screen, scale it down

View file

@ -12,6 +12,6 @@
"build": "rm -rf './target' && tsc"
},
"devDependencies": {
"typescript": "^3.3.3333"
"typescript": "3.5.3"
}
}

View file

@ -12,6 +12,6 @@
"build": "rm -rf './target' && tsc"
},
"devDependencies": {
"typescript": "^3.3.3333"
"typescript": "3.5.3"
}
}

View file

@ -17,6 +17,6 @@
},
"devDependencies": {
"@kbn/plugin-helpers": "9.0.2",
"typescript": "^3.3.3333"
"typescript": "3.5.3"
}
}

View file

@ -17,6 +17,6 @@
},
"devDependencies": {
"@kbn/plugin-helpers": "9.0.2",
"typescript": "^3.3.3333"
"typescript": "3.5.3"
}
}

View file

@ -51,8 +51,7 @@ function TransactionLink({
path={path}
query={{
transactionId: transaction.transaction.id,
traceId: transaction.trace.id,
banana: 'ok'
traceId: transaction.trace.id
}}
>
{transaction.transaction.id}

View file

@ -9,11 +9,15 @@ export interface StringMap<T = unknown> {
}
// Allow unknown properties in an object
export type AllowUnknownProperties<Obj> = Obj extends object
? { [Prop in keyof Obj]: AllowUnknownProperties<Obj[Prop]> } & {
export type AllowUnknownProperties<T> = T extends Array<infer X>
? Array<AllowUnknownObjectProperties<X>>
: AllowUnknownObjectProperties<T>;
type AllowUnknownObjectProperties<T> = T extends object
? { [Prop in keyof T]: AllowUnknownProperties<T[Prop]> } & {
[key: string]: unknown;
}
: Obj;
: T;
export type PromiseReturnType<Func> = Func extends (
...args: any[]

View file

@ -115,7 +115,7 @@ declare module 'elasticsearch' {
export interface ESFilter {
[key: string]: {
[key: string]: string | number | StringMap | ESFilter[];
[key: string]: string | string[] | number | StringMap | ESFilter[];
};
}
}

View file

@ -147,7 +147,9 @@ export class TagEdit extends React.PureComponent<TagEditProps, TagEditState> {
<div>
<ConfigList
onTableChange={this.props.onConfigListChange}
configs={configuration_blocks} // eslint-disable-line @typescript-eslint/camelcase
configs={
configuration_blocks // eslint-disable-line @typescript-eslint/camelcase
}
onConfigClick={(action: string, block: ConfigurationBlock) => {
if (action === 'delete') {
this.props.onConfigRemoved(block);

View file

@ -48,7 +48,7 @@ export class ElasticsearchLib {
});
}
return hiddenFieldsCheck.reduce((isvalid, field) => {
return hiddenFieldsCheck.reduce((isvalid: boolean, field) => {
if (!isvalid) {
return false;
}

View file

@ -6,7 +6,6 @@
import Joi from 'joi';
import { omit } from 'lodash';
import { REQUIRED_LICENSES } from '../../../common/constants/security';
import { CMBeat } from '../../../common/domain_types';
import { BaseReturnType, ReturnTypeCreate } from '../../../common/return_types';
import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types';
import { BeatEnrollmentStatus, CMServerLibs } from '../../lib/types';
@ -34,7 +33,7 @@ export const createBeatEnrollmentRoute = (libs: CMServerLibs) => ({
},
handler: async (
request: FrameworkRequest
): Promise<BaseReturnType | ReturnTypeCreate<CMBeat>> => {
): Promise<BaseReturnType | ReturnTypeCreate<string>> => {
const { beatId } = request.params;
const enrollmentToken = request.headers['kbn-beats-enrollment-token'];

View file

@ -83,6 +83,16 @@ export const createBeatUpdateRoute = (libs: CMServerLibs) => ({
const beat = await libs.beats.getById(internalUser, beatId);
if (!beat) {
return {
error: {
message: 'Beat not found',
code: 404,
},
success: false,
};
}
return {
item: beat,
action: 'updated',

View file

@ -8,7 +8,7 @@
import uniqBy from 'lodash.uniqby';
// @ts-ignore Untyped Elastic library
import { evaluate } from 'tinymath';
import { groupBy, zipObject, omit, values } from 'lodash';
import { groupBy, zipObject, omit } from 'lodash';
import moment from 'moment';
import { ExpressionFunction } from 'src/legacy/core_plugins/interpreter/public';
// @ts-ignore Untyped local
@ -185,7 +185,7 @@ export function pointseries(): ExpressionFunction<
);
// Then compute that 1 value for each measure
values<DatatableRow[]>(measureKeys).forEach(valueRows => {
Object.values<DatatableRow[]>(measureKeys).forEach(valueRows => {
const subtable = { type: 'datatable', columns: context.columns, rows: valueRows };
const subScope = pivotObjectArray(subtable.rows, subtable.columns.map(col => col.name));
const measureValues = measureNames.map(measure => {
@ -209,7 +209,7 @@ export function pointseries(): ExpressionFunction<
// It only makes sense to uniq the rows in a point series as 2 values can not exist in the exact same place at the same time.
const resultingRows = uniqBy(
values(results).map(row => omit(row, PRIMARY_KEY)),
Object.values(results).map(row => omit(row, PRIMARY_KEY)),
JSON.stringify
);

View file

@ -122,7 +122,7 @@ const customElementCollector: TelemetryCollector = async function customElementC
const esResponse = await callCluster<CustomElementSearch>('search', customElementParams);
if (get(esResponse, 'hits.hits.length') > 0) {
if (get<number>(esResponse, 'hits.hits.length') > 0) {
const customElements = esResponse.hits.hits.map(hit => hit._source[CUSTOM_ELEMENT_TYPE]);
return summarizeCustomElements(customElements);
}

View file

@ -66,7 +66,7 @@ interface WorkpadTelemetry {
@returns Workpad Telemetry Data
*/
export function summarizeWorkpads(workpadDocs: Workpad[]): WorkpadTelemetry {
const functionSet = new Set();
const functionSet = new Set<string>();
if (workpadDocs.length === 0) {
return {};
@ -185,7 +185,7 @@ const workpadCollector: TelemetryCollector = async function(server, callCluster)
const esResponse = await callCluster<WorkpadSearch>('search', searchParams);
if (get(esResponse, 'hits.hits.length') > 0) {
if (get<number>(esResponse, 'hits.hits.length') > 0) {
const workpads = esResponse.hits.hits.map(hit => hit._source[CANVAS_TYPE]);
return summarizeWorkpads(workpads);
}

View file

@ -63,6 +63,7 @@ interface State {
groupIndex: number | null;
itemIndex: number | null;
suggestionGroups: AutocompleteSuggestionGroup[];
showOptions: boolean;
currentProps?: Props;
}
@ -93,7 +94,7 @@ export class CodeQueryBar extends Component<Props, State> {
keypress has been a major source of performance issues for us in previous implementations of the query bar.
See https://github.com/elastic/kibana/issues/14086
*/
public state = {
public state: State = {
query: this.props.query,
inputIsPristine: true,
isSuggestionsVisible: false,

View file

@ -6,7 +6,7 @@
import { editor } from 'monaco-editor';
const editors = new Set();
const editors = new Set<editor.IStandaloneCodeEditor>();
function clearSelection(ed: editor.IStandaloneCodeEditor) {
const sel = ed.getSelection();

View file

@ -33,7 +33,7 @@ export class EncryptedSavedObjectsAuditLogger {
}
public encryptAttributesSuccess(
attributesNames: ReadonlyArray<string>,
attributesNames: readonly string[],
descriptor: SavedObjectDescriptor
) {
this.auditLogger.log(
@ -46,7 +46,7 @@ export class EncryptedSavedObjectsAuditLogger {
}
public decryptAttributesSuccess(
attributesNames: ReadonlyArray<string>,
attributesNames: readonly string[],
descriptor: SavedObjectDescriptor
) {
this.auditLogger.log(

View file

@ -68,7 +68,7 @@ export class EncryptedSavedObjectsService {
*/
constructor(
encryptionKey: string,
private readonly knownTypes: ReadonlyArray<string>,
private readonly knownTypes: readonly string[],
private readonly log: Server.Logger,
private readonly audit: EncryptedSavedObjectsAuditLogger
) {
@ -281,13 +281,13 @@ export class EncryptedSavedObjectsService {
* @param descriptor Descriptor of the saved object to get AAD for.
* @param attributes All attributes of the saved object instance of the specified type.
*/
private getAAD<T extends Record<string, unknown>>(
private getAAD(
typeRegistration: EncryptedSavedObjectTypeRegistration,
descriptor: SavedObjectDescriptor,
attributes: T
attributes: Record<string, unknown>
) {
// Collect all attributes (both keys and values) that should contribute to AAD.
const attributesAAD = {} as T;
const attributesAAD: Record<string, unknown> = {};
for (const [attributeKey, attributeValue] of Object.entries(attributes)) {
if (
!typeRegistration.attributesToEncrypt.has(attributeKey) &&

View file

@ -24,7 +24,7 @@ interface SearchMarkerState {
}
export class SearchMarker extends React.PureComponent<SearchMarkerProps, SearchMarkerState> {
public readonly state = {
public readonly state: SearchMarkerState = {
hoveredPosition: null,
};

View file

@ -51,7 +51,7 @@ export interface DataFrameJobConfig extends DataFrameRequest {
export interface SimpleQuery {
query_string: {
query: string;
default_operator: DefaultOperator;
default_operator?: DefaultOperator;
};
}

View file

@ -42,7 +42,6 @@ enum WIZARD_STEPS {
interface DefinePivotStepProps {
isCurrentStep: boolean;
jobConfig: any;
pivotState: DefinePivotExposedState;
setCurrentStep: React.Dispatch<React.SetStateAction<WIZARD_STEPS>>;
setPivot: React.Dispatch<React.SetStateAction<DefinePivotExposedState>>;
@ -50,7 +49,6 @@ interface DefinePivotStepProps {
const DefinePivotStep: SFC<DefinePivotStepProps> = ({
isCurrentStep,
jobConfig,
pivotState,
setCurrentStep,
setPivot,
@ -62,7 +60,7 @@ const DefinePivotStep: SFC<DefinePivotStepProps> = ({
<div ref={definePivotRef} />
{isCurrentStep && (
<Fragment>
<DefinePivotForm onChange={setPivot} overrides={{ ...pivotState, jobConfig }} />
<DefinePivotForm onChange={setPivot} overrides={{ ...pivotState }} />
<WizardNav
next={() => setCurrentStep(WIZARD_STEPS.JOB_DETAILS)}
nextActive={pivotState.valid}
@ -137,7 +135,6 @@ export const Wizard: SFC = React.memo(() => {
children: (
<DefinePivotStep
isCurrentStep={currentStep === WIZARD_STEPS.DEFINE_PIVOT}
jobConfig={jobConfig}
pivotState={pivotState}
setCurrentStep={setCurrentStep}
setPivot={setPivot}

View file

@ -36,7 +36,7 @@ async function getStats(callCluster: (method: string, params: any) => Promise<an
},
};
const esResponse: ESQueryResponse = await callCluster('search', searchParams);
const size = _.get(esResponse, 'hits.hits.length');
const size = _.get<number>(esResponse, 'hits.hits.length');
if (size < 1) {
return;
}

View file

@ -15,8 +15,8 @@ import {
EuiText,
EuiTitle,
} from '@elastic/eui';
import { get, has } from 'lodash';
import React, { Component, Fragment } from 'react';
import { get } from 'lodash';
import { USES_HEADLESS_JOB_TYPES } from '../../common/constants';
import { JobInfo, jobQueueClient } from '../lib/job_queue_client';
@ -75,52 +75,51 @@ export class ReportInfoButton extends Component<Props, State> {
return null;
}
const jobType = get(info, 'jobtype', NA);
const processedBy =
has(info, 'kibana_name') && has(info, 'kibana_id')
? `${info.kibana_name} (${info.kibana_id})`
: UNKNOWN;
const jobType = info.jobtype || NA;
// TODO queue method (clicked UI, watcher, etc)
const jobInfoParts = {
datetimes: [
{
title: 'Created By',
description: get(info, 'created_by', NA),
description: info.created_by || NA,
},
{
title: 'Created At',
description: get(info, 'created_at', NA),
description: info.created_at || NA,
},
{
title: 'Started At',
description: get(info, 'started_at', NA),
description: info.started_at || NA,
},
{
title: 'Completed At',
description: get(info, 'completed_at', NA),
description: info.completed_at || NA,
},
{
title: 'Processed By',
description: processedBy,
description:
info.kibana_name && info.kibana_id
? `${info.kibana_name} (${info.kibana_id})`
: UNKNOWN,
},
{
title: 'Browser Timezone',
description: get(info, 'payload.browserTimezone', NA),
description: info.payload.browserTimezone || NA,
},
],
payload: [
{
title: 'Title',
description: get(info, 'payload.title', NA),
description: info.payload.title || NA,
},
{
title: 'Type',
description: get(info, 'payload.type', NA),
description: info.payload.type || NA,
},
{
title: 'Layout',
description: get(info, 'meta.layout', NA),
description: info.meta.layout || NA,
},
{
title: 'Dimensions',
@ -132,38 +131,38 @@ export class ReportInfoButton extends Component<Props, State> {
},
{
title: 'Content Type',
description: get(info, 'output.content_type') || NA,
description: info.output.content_type || NA,
},
{
title: 'Size in Bytes',
description: get(info, 'output.size') || NA,
description: info.output.size || NA,
},
],
status: [
{
title: 'Attempts',
description: get(info, 'attempts', NA),
description: info.attempts || NA,
},
{
title: 'Max Attempts',
description: get(info, 'max_attempts', NA),
description: info.max_attempts || NA,
},
{
title: 'Priority',
description: get(info, 'priority', NA),
description: info.priority || NA,
},
{
title: 'Timeout',
description: get(info, 'timeout', NA),
description: info.timeout || NA,
},
{
title: 'Status',
description: get(info, 'status', NA),
description: info.status || NA,
},
{
title: 'Browser Type',
description: USES_HEADLESS_JOB_TYPES.includes(jobType)
? get(info, 'browser_type', UNKNOWN)
? info.browser_type || UNKNOWN
: NA,
},
],

View file

@ -70,7 +70,7 @@ function getProviderOptions(server: Legacy.Server) {
basePath: config.get<string>('server.basePath'),
tokens: new Tokens({ client, log }),
...config.get('xpack.security.public'),
...config.get<any>('xpack.security.public'),
};
}

View file

@ -36,9 +36,9 @@ export function useLastEventTimeQuery<TCache = object>(
apolloClient: ApolloClient<TCache>
) {
const [loading, updateLoading] = useState(false);
const [lastSeen, updateLastSeen] = useState(null);
const [errorMessage, updateErrorMessage] = useState(null);
const [currentIndexKey, updateCurrentIndexKey] = useState(null);
const [lastSeen, updateLastSeen] = useState<number | null>(null);
const [errorMessage, updateErrorMessage] = useState<string | null>(null);
const [currentIndexKey, updateCurrentIndexKey] = useState<LastEventIndexKey | null>(null);
async function fetchLastEventTime() {
updateLoading(true);
return apolloClient

View file

@ -9,7 +9,7 @@ import { castArray, isUndefined } from 'lodash/fp';
export const encodeIpv6 = (ip: string) => ip.replace(/:/g, '-');
export const decodeIpv6 = (ip: string) => ip.replace(/-/g, ':');
export type Many<T> = T | ReadonlyArray<T>;
export type Many<T> = T | readonly T[];
export type WrapArrayIfExitts = <T>(value: Many<T>) => T[] | undefined;
/**

View file

@ -28,7 +28,7 @@ describe('authentications elasticsearch_adapter', () => {
};
test('it formats a authentication with an empty set', () => {
const fields: ReadonlyArray<string> = [''];
const fields: readonly string[] = [''];
const data = formatAuthenticationData(fields, hit, auditdFieldsMap);
const expected: AuthenticationsEdges = {
cursor: {
@ -49,7 +49,7 @@ describe('authentications elasticsearch_adapter', () => {
});
test('it formats a authentications with a source ip correctly', () => {
const fields: ReadonlyArray<string> = ['lastSuccess.source.ip'];
const fields: readonly string[] = ['lastSuccess.source.ip'];
const data = formatAuthenticationData(fields, hit, auditdFieldsMap);
const expected: AuthenticationsEdges = {
cursor: {
@ -70,7 +70,7 @@ describe('authentications elasticsearch_adapter', () => {
});
test('it formats a authentications with a host name only', () => {
const fields: ReadonlyArray<string> = ['lastSuccess.host.name'];
const fields: readonly string[] = ['lastSuccess.host.name'];
const data = formatAuthenticationData(fields, hit, auditdFieldsMap);
const expected: AuthenticationsEdges = {
cursor: {
@ -91,7 +91,7 @@ describe('authentications elasticsearch_adapter', () => {
});
test('it formats a authentications with a host id only', () => {
const fields: ReadonlyArray<string> = ['lastSuccess.host.id'];
const fields: readonly string[] = ['lastSuccess.host.id'];
const data = formatAuthenticationData(fields, hit, auditdFieldsMap);
const expected: AuthenticationsEdges = {
cursor: {
@ -112,7 +112,7 @@ describe('authentications elasticsearch_adapter', () => {
});
test('it formats a authentications with a host name and id correctly', () => {
const fields: ReadonlyArray<string> = ['lastSuccess.host.name', 'lastSuccess.host.id'];
const fields: readonly string[] = ['lastSuccess.host.name', 'lastSuccess.host.id'];
const data = formatAuthenticationData(fields, hit, auditdFieldsMap);
const expected: AuthenticationsEdges = {
cursor: {

View file

@ -81,7 +81,7 @@ export class ElasticsearchAuthenticationAdapter implements AuthenticationsAdapte
}
export const formatAuthenticationData = (
fields: ReadonlyArray<string>,
fields: readonly string[],
hit: AuthenticationHit,
fieldMap: Readonly<Record<string, string>>
): AuthenticationsEdges =>

View file

@ -81,7 +81,7 @@ describe('events elasticsearch_adapter', () => {
describe('#formatEventsData', () => {
test('it formats an event with a source of hostname correctly', () => {
const fields: ReadonlyArray<string> = ['host.name'];
const fields: readonly string[] = ['host.name'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -100,7 +100,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a source of host ip correctly', () => {
const fields: ReadonlyArray<string> = ['host.ip'];
const fields: readonly string[] = ['host.ip'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -119,7 +119,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a event category correctly', () => {
const fields: ReadonlyArray<string> = ['event.category'];
const fields: readonly string[] = ['event.category'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -139,7 +139,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a event id correctly', () => {
const fields: ReadonlyArray<string> = ['event.id'];
const fields: readonly string[] = ['event.id'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -158,7 +158,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a event module correctly', () => {
const fields: ReadonlyArray<string> = ['event.module'];
const fields: readonly string[] = ['event.module'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -177,7 +177,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a event action correctly', () => {
const fields: ReadonlyArray<string> = ['event.action'];
const fields: readonly string[] = ['event.action'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -197,7 +197,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a event severity correctly', () => {
const fields: ReadonlyArray<string> = ['event.severity'];
const fields: readonly string[] = ['event.severity'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -217,7 +217,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a suricata eve flow id correctly', () => {
const fields: ReadonlyArray<string> = ['suricata.eve.flow_id'];
const fields: readonly string[] = ['suricata.eve.flow_id'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -239,7 +239,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a suricata eve proto correctly', () => {
const fields: ReadonlyArray<string> = ['suricata.eve.proto'];
const fields: readonly string[] = ['suricata.eve.proto'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -261,7 +261,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a suricata eve alert signature correctly', () => {
const fields: ReadonlyArray<string> = ['suricata.eve.alert.signature'];
const fields: readonly string[] = ['suricata.eve.alert.signature'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -285,7 +285,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a suricata eve alert signature id correctly', () => {
const fields: ReadonlyArray<string> = ['suricata.eve.alert.signature_id'];
const fields: readonly string[] = ['suricata.eve.alert.signature_id'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -309,7 +309,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a source ip correctly', () => {
const fields: ReadonlyArray<string> = ['source.ip'];
const fields: readonly string[] = ['source.ip'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -329,7 +329,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a source port correctly', () => {
const fields: ReadonlyArray<string> = ['source.port'];
const fields: readonly string[] = ['source.port'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -349,7 +349,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a destination ip correctly', () => {
const fields: ReadonlyArray<string> = ['destination.ip'];
const fields: readonly string[] = ['destination.ip'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -369,7 +369,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a destination port correctly', () => {
const fields: ReadonlyArray<string> = ['destination.port'];
const fields: readonly string[] = ['destination.port'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -389,7 +389,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a geo region name correctly', () => {
const fields: ReadonlyArray<string> = ['geo.region_name'];
const fields: readonly string[] = ['geo.region_name'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -409,7 +409,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a geo country iso code correctly', () => {
const fields: ReadonlyArray<string> = ['geo.country_iso_code'];
const fields: readonly string[] = ['geo.country_iso_code'];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = {
cursor: {
@ -429,7 +429,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats an event with a lot of fields correctly', () => {
const fields: ReadonlyArray<string> = [
const fields: readonly string[] = [
'host.name',
'host.ip',
'suricata.eve.proto',
@ -467,7 +467,7 @@ describe('events elasticsearch_adapter', () => {
});
test('it formats a event data if fields are empty', () => {
const fields: ReadonlyArray<string> = [];
const fields: readonly string[] = [];
const data = formatEventsData(fields, hit, eventFieldsMap);
const expected: EcsEdges = { cursor: { tiebreaker: null, value: '' }, node: { _id: '' } };
@ -477,12 +477,12 @@ describe('events elasticsearch_adapter', () => {
describe('#formatTimelineData', () => {
test('it formats TimelineEdges from hit as expected ', () => {
const datafields: ReadonlyArray<string> = [
const datafields: readonly string[] = [
'@timestamp',
'host.name',
'suricata.eve.alert.signature_id',
];
const ecsfields: ReadonlyArray<string> = ['host.name', 'suricata.eve.alert.signature_id'];
const ecsfields: readonly string[] = ['host.name', 'suricata.eve.alert.signature_id'];
const data = formatTimelineData(datafields, ecsfields, hit, eventFieldsMap);
// TODO: Re-add TimelineEdges back once we settle on if data can contain numbers or not.
// otherwise delete this test.

View file

@ -178,7 +178,7 @@ export class ElasticsearchEventsAdapter implements EventsAdapter {
}
export const formatEventsData = (
fields: ReadonlyArray<string>,
fields: readonly string[],
hit: EventHit,
fieldMap: Readonly<Record<string, string>>
) =>
@ -202,8 +202,8 @@ export const formatEventsData = (
);
export const formatTimelineData = (
dataFields: ReadonlyArray<string>,
ecsFields: ReadonlyArray<string>,
dataFields: readonly string[],
ecsFields: readonly string[],
hit: EventHit,
fieldMap: Readonly<Record<string, string>>
) =>
@ -242,8 +242,8 @@ const mergeTimelineFieldsWithHit = <T>(
flattenedFields: T,
fieldMap: Readonly<Record<string, string>>,
hit: { _source: {} },
dataFields: ReadonlyArray<string>,
ecsFields: ReadonlyArray<string>
dataFields: readonly string[],
ecsFields: readonly string[]
) => {
if (fieldMap[fieldName] != null || dataFields.includes(fieldName)) {
const esField = dataFields.includes(fieldName) ? fieldName : fieldMap[fieldName];

View file

@ -156,6 +156,6 @@ export interface RequestBasicOptions {
export interface RequestOptions extends RequestBasicOptions {
pagination: PaginationInput;
fields: ReadonlyArray<string>;
fields: readonly string[];
sortField?: SortField;
}

View file

@ -88,7 +88,7 @@ describe('hosts elasticsearch_adapter', () => {
};
test('it formats a host with a source of name correctly', () => {
const fields: ReadonlyArray<string> = ['host.name'];
const fields: readonly string[] = ['host.name'];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: { tiebreaker: null, value: 'zeek-london' },
@ -99,7 +99,7 @@ describe('hosts elasticsearch_adapter', () => {
});
test('it formats a host with a source of os correctly', () => {
const fields: ReadonlyArray<string> = ['host.os.name'];
const fields: readonly string[] = ['host.os.name'];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: { tiebreaker: null, value: 'zeek-london' },
@ -110,7 +110,7 @@ describe('hosts elasticsearch_adapter', () => {
});
test('it formats a host with a source of version correctly', () => {
const fields: ReadonlyArray<string> = ['host.os.version'];
const fields: readonly string[] = ['host.os.version'];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: { tiebreaker: null, value: 'zeek-london' },
@ -121,7 +121,7 @@ describe('hosts elasticsearch_adapter', () => {
});
test('it formats a host with a source of id correctly', () => {
const fields: ReadonlyArray<string> = ['host.name'];
const fields: readonly string[] = ['host.name'];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: { tiebreaker: null, value: 'zeek-london' },
@ -132,7 +132,7 @@ describe('hosts elasticsearch_adapter', () => {
});
test('it formats a host with a source of name, lastBeat, os, and version correctly', () => {
const fields: ReadonlyArray<string> = ['host.name', 'host.os.name', 'host.os.version'];
const fields: readonly string[] = ['host.name', 'host.os.name', 'host.os.version'];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: { tiebreaker: null, value: 'zeek-london' },
@ -149,7 +149,7 @@ describe('hosts elasticsearch_adapter', () => {
});
test('it formats a host without any data if fields are empty', () => {
const fields: ReadonlyArray<string> = [];
const fields: readonly string[] = [];
const data = formatHostEdgesData(fields, buckets);
const expected: HostsEdges = {
cursor: {

View file

@ -103,10 +103,7 @@ export class ElasticsearchHostsAdapter implements HostsAdapter {
}
}
export const formatHostEdgesData = (
fields: ReadonlyArray<string>,
bucket: HostAggEsItem
): HostsEdges =>
export const formatHostEdgesData = (fields: readonly string[], bucket: HostAggEsItem): HostsEdges =>
fields.reduce<HostsEdges>(
(flattenedFields, fieldName) => {
const hostId = get('key', bucket);
@ -128,7 +125,7 @@ export const formatHostEdgesData = (
}
);
const formatHostItem = (fields: ReadonlyArray<string>, bucket: HostAggEsItem): HostItem =>
const formatHostItem = (fields: readonly string[], bucket: HostAggEsItem): HostItem =>
fields.reduce<HostItem>((flattenedFields, fieldName) => {
const fieldValue = getHostFieldValue(fieldName, bucket);
if (fieldValue != null) {

View file

@ -10,7 +10,7 @@ import { buildFieldsTermAggregation } from './helpers';
describe('#buildFieldsTermAggregation', () => {
test('it convert fields to aggregation terms', () => {
const fields: ReadonlyArray<string> = [
const fields: readonly string[] = [
'host.architecture',
'host.id',
'host.name',

View file

@ -6,7 +6,7 @@
import { AggregationRequest } from '../types';
export const buildFieldsTermAggregation = (esFields: ReadonlyArray<string>): AggregationRequest =>
export const buildFieldsTermAggregation = (esFields: readonly string[]): AggregationRequest =>
esFields.reduce<AggregationRequest>(
(res, field) => ({
...res,

View file

@ -201,7 +201,7 @@ describe('elasticsearch_adapter', () => {
};
test('it formats a uncommon process data with a source of name correctly', () => {
const fields: ReadonlyArray<string> = ['process.name'];
const fields: readonly string[] = ['process.name'];
const data = formatUncommonProcessesData(fields, hit, processFieldsMap);
const expected: UncommonProcessesEdges = {
cursor: { tiebreaker: null, value: 'cursor-1' },
@ -221,7 +221,7 @@ describe('elasticsearch_adapter', () => {
});
test('it formats a uncommon process data with a source of name and title correctly', () => {
const fields: ReadonlyArray<string> = ['process.name', 'process.title'];
const fields: readonly string[] = ['process.name', 'process.title'];
const data = formatUncommonProcessesData(fields, hit, processFieldsMap);
const expected: UncommonProcessesEdges = {
cursor: { tiebreaker: null, value: 'cursor-1' },
@ -242,7 +242,7 @@ describe('elasticsearch_adapter', () => {
});
test('it formats a uncommon process data without any data if fields is empty', () => {
const fields: ReadonlyArray<string> = [];
const fields: readonly string[] = [];
const data = formatUncommonProcessesData(fields, hit, processFieldsMap);
const expected: UncommonProcessesEdges = {
cursor: {

View file

@ -64,9 +64,7 @@ export class ElasticsearchUncommonProcessesAdapter implements UncommonProcessesA
}
}
export const getHits = (
buckets: ReadonlyArray<UncommonProcessBucket>
): ReadonlyArray<UncommonProcessHit> =>
export const getHits = (buckets: readonly UncommonProcessBucket[]): readonly UncommonProcessHit[] =>
buckets.map((bucket: Readonly<UncommonProcessBucket>) => ({
_id: bucket.process.hits.hits[0]._id,
_index: bucket.process.hits.hits[0]._index,
@ -89,7 +87,7 @@ export const getHosts = (buckets: ReadonlyArray<{ key: string; host: HostHits }>
});
export const formatUncommonProcessesData = (
fields: ReadonlyArray<string>,
fields: readonly string[],
hit: UncommonProcessHit,
fieldMap: Readonly<Record<string, string>>
): UncommonProcessesEdges =>

View file

@ -5,10 +5,10 @@
*/
export const reduceFields = (
fields: ReadonlyArray<string>,
fields: readonly string[],
fieldMap: Readonly<Record<string, string>>
): ReadonlyArray<string> =>
): readonly string[] =>
fields.reduce(
(res, field) => (fieldMap[field] != null ? [...res, fieldMap[field]] : res),
[] as ReadonlyArray<string>
[] as readonly string[]
);

View file

@ -158,7 +158,7 @@
"supertest-as-promised": "^4.0.2",
"tmp": "0.1.0",
"tree-kill": "^1.1.0",
"typescript": "^3.3.3333",
"typescript": "3.5.3",
"vinyl-fs": "^3.0.2",
"xml-crypto": "^0.10.1",
"yargs": "4.8.1"

View file

@ -22,8 +22,8 @@ export interface RoleKibanaPrivilege {
export interface CustomRoleSpecification {
name: string;
elasticsearch?: {
cluster: string[];
indices: CustomRoleSpecificationElasticsearchIndices[];
cluster?: string[];
indices?: CustomRoleSpecificationElasticsearchIndices[];
};
kibana?: RoleKibanaPrivilege[];
}

View file

@ -3678,6 +3678,11 @@
"@types/cheerio" "*"
"@types/react" "*"
"@types/eslint-visitor-keys@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#1ee30d79544ca84d68d4b3cdb0af4f205663dd2d"
integrity sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag==
"@types/eslint@^4.16.6":
version "4.16.6"
resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-4.16.6.tgz#96d4ecddbea618ab0b55eaf0dffedf387129b06c"
@ -4604,29 +4609,39 @@
resolved "https://registry.yarnpkg.com/@types/zen-observable/-/zen-observable-0.8.0.tgz#8b63ab7f1aa5321248aad5ac890a485656dcea4d"
integrity sha512-te5lMAWii1uEJ4FwLjzdlbw3+n0FZNOvFXHxQDKeT0dilh7HOzdMzV2TrJVUzq8ep7J4Na8OUYPRLSQkJHAlrg==
"@typescript-eslint/eslint-plugin@^1.6.0":
version "1.6.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-1.6.0.tgz#a5ff3128c692393fb16efa403ec7c8a5593dab0f"
integrity sha512-U224c29E2lo861TQZs6GSmyC0OYeRNg6bE9UVIiFBxN2MlA0nq2dCrgIVyyRbC05UOcrgf2Wk/CF2gGOPQKUSQ==
"@typescript-eslint/eslint-plugin@1.11.0":
version "1.11.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-1.11.0.tgz#870f752c520db04db6d3668af7479026a6f2fb9a"
integrity sha512-mXv9ccCou89C8/4avKHuPB2WkSZyY/XcTQUXd5LFZAcLw1I3mWYVjUu6eS9Ja0QkP/ClolbcW9tb3Ov/pMdcqw==
dependencies:
"@typescript-eslint/parser" "1.6.0"
"@typescript-eslint/typescript-estree" "1.6.0"
requireindex "^1.2.0"
"@typescript-eslint/experimental-utils" "1.11.0"
eslint-utils "^1.3.1"
functional-red-black-tree "^1.0.1"
regexpp "^2.0.1"
tsutils "^3.7.0"
"@typescript-eslint/parser@1.6.0", "@typescript-eslint/parser@^1.6.0":
version "1.6.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-1.6.0.tgz#f01189c8b90848e3b8e45a6cdad27870529d1804"
integrity sha512-VB9xmSbfafI+/kI4gUK3PfrkGmrJQfh0N4EScT1gZXSZyUxpsBirPL99EWZg9MmPG0pzq/gMtgkk7/rAHj4aQw==
"@typescript-eslint/experimental-utils@1.11.0":
version "1.11.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-1.11.0.tgz#594abe47091cbeabac1d6f9cfed06d0ad99eb7e3"
integrity sha512-7LbfaqF6B8oa8cp/315zxKk8FFzosRzzhF8Kn/ZRsRsnpm7Qcu25cR/9RnAQo5utZ2KIWVgaALr+ZmcbG47ruw==
dependencies:
"@typescript-eslint/typescript-estree" "1.6.0"
"@typescript-eslint/typescript-estree" "1.11.0"
eslint-scope "^4.0.0"
"@typescript-eslint/parser@1.11.0":
version "1.11.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-1.11.0.tgz#2f6d4f7e64eeb1e7c25b422f8df14d0c9e508e36"
integrity sha512-5xBExyXaxVyczrZvbRKEXvaTUFFq7gIM9BynXukXZE0zF3IQP/FxF4mPmmh3gJ9egafZFqByCpPTFm3dk4SY7Q==
dependencies:
"@types/eslint-visitor-keys" "^1.0.0"
"@typescript-eslint/experimental-utils" "1.11.0"
"@typescript-eslint/typescript-estree" "1.11.0"
eslint-visitor-keys "^1.0.0"
"@typescript-eslint/typescript-estree@1.6.0":
version "1.6.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.6.0.tgz#6cf43a07fee08b8eb52e4513b428c8cdc9751ef0"
integrity sha512-A4CanUwfaG4oXobD5y7EXbsOHjCwn8tj1RDd820etpPAjH+Icjc2K9e/DQM1Hac5zH2BSy+u6bjvvF2wwREvYA==
"@typescript-eslint/typescript-estree@1.11.0":
version "1.11.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.11.0.tgz#b7b5782aab22e4b3b6d84633652c9f41e62d37d5"
integrity sha512-fquUHF5tAx1sM2OeRCC7wVxFd1iMELWMGCzOSmJ3pLzArj9+kRixdlC4d5MncuzXpjEqc6045p3KwM0o/3FuUA==
dependencies:
lodash.unescape "4.0.1"
semver "5.5.0"
@ -24286,7 +24301,7 @@ requirefresh@^2.0.0:
dependencies:
editions "^1.1.1"
requireindex@^1.2.0, requireindex@~1.2.0:
requireindex@~1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.2.0.tgz#3463cdb22ee151902635aa6c9535d4de9c2ef1ef"
integrity sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==
@ -27823,10 +27838,10 @@ typescript-fsa@^2.0.0, typescript-fsa@^2.5.0:
resolved "https://registry.yarnpkg.com/typescript-fsa/-/typescript-fsa-2.5.0.tgz#1baec01b5e8f5f34c322679d1327016e9e294faf"
integrity sha1-G67AG16PXzTDImedEycBbp4pT68=
typescript@^3.0.3, typescript@^3.3.3333, typescript@^3.4.5, typescript@~3.0.3, typescript@~3.3.3333, typescript@~3.4.3:
version "3.3.3333"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.3.3333.tgz#171b2c5af66c59e9431199117a3bcadc66fdcfd6"
integrity sha512-JjSKsAfuHBE/fB2oZ8NxtRTk5iGcg6hkYXMnZ3Wc+b2RSqejEqTaem11mHASMnFilHrax3sLK0GDzcJrekZYLw==
typescript@3.5.3, typescript@^3.0.3, typescript@^3.3.3333, typescript@^3.4.5, typescript@~3.0.3, typescript@~3.3.3333, typescript@~3.4.3:
version "3.5.3"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.5.3.tgz#c830f657f93f1ea846819e929092f5fe5983e977"
integrity sha512-ACzBtm/PhXBDId6a6sDJfroT2pOWt/oOnk4/dElG5G33ZL776N3Y6/6bKZJBFpd+b05F3Ct9qDjMeJmRWtE2/g==
typings-tester@^0.3.2:
version "0.3.2"