diff --git a/.eslintrc.js b/.eslintrc.js
index 86ac92de9042d..aeaf6e04fdc01 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -50,7 +50,7 @@ const ELASTIC_LICENSE_HEADER = `
`;
const allMochaRulesOff = {};
-Object.keys(require('eslint-plugin-mocha').rules).forEach(k => {
+Object.keys(require('eslint-plugin-mocha').rules).forEach((k) => {
allMochaRulesOff['mocha/' + k] = 'off';
});
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a9a2f609e0913..1053cc2f65396 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -490,6 +490,14 @@ module.exports = {
};
```
+APM [Real User Monitoring agent](https://www.elastic.co/guide/en/apm/agent/rum-js/current/index.html) is not available in the Kibana distributables,
+however the agent can be enabled by setting `ELASTIC_APM_ACTIVE` to `true`.
+flags
+```
+ELASTIC_APM_ACTIVE=true yarn start
+// activates both Node.js and RUM agent
+```
+
Once the agent is active, it will trace all incoming HTTP requests to Kibana, monitor for errors, and collect process-level metrics.
The collected data will be sent to the APM Server and is viewable in the APM UI in Kibana.
diff --git a/Gruntfile.js b/Gruntfile.js
index c33a576d4340f..0216ab12f7cc5 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -19,7 +19,7 @@
require('./src/setup_node_env');
-module.exports = function(grunt) {
+module.exports = function (grunt) {
// set the config once before calling load-grunt-config
// and once during so that we have access to it via
// grunt.config.get() within the config files
diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md
index f36351c8b8f06..055ad9f37e654 100644
--- a/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md
+++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md
@@ -6,7 +6,7 @@
Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the `absolute` option to generate an absolute url (http://host:port/basePath/app/my-app)
-Note that when generating absolute urls, the protocol, host and port are determined from the browser location.
+Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location.
Signature:
diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.md
index a93bc61bac527..6f45bab3ebd2d 100644
--- a/docs/development/core/public/kibana-plugin-core-public.applicationstart.md
+++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.md
@@ -22,7 +22,8 @@ export interface ApplicationStart
| Method | Description |
| --- | --- |
-| [getUrlForApp(appId, options)](./kibana-plugin-core-public.applicationstart.geturlforapp.md) | Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the absolute
option to generate an absolute url (http://host:port/basePath/app/my-app)Note that when generating absolute urls, the protocol, host and port are determined from the browser location. |
+| [getUrlForApp(appId, options)](./kibana-plugin-core-public.applicationstart.geturlforapp.md) | Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the absolute
option to generate an absolute url (http://host:port/basePath/app/my-app)Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location. |
| [navigateToApp(appId, options)](./kibana-plugin-core-public.applicationstart.navigatetoapp.md) | Navigate to a given app |
+| [navigateToUrl(url)](./kibana-plugin-core-public.applicationstart.navigatetourl.md) | Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible.If all these criteria are true for the given url: - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space) - The pathname segment after the basePath matches any known application route (eg. /app// or any application's appRoute
configuration)Then a SPA navigation will be performed using navigateToApp
using the corresponding application and path. Otherwise, fallback to a full page reload to navigate to the url using window.location.assign
|
| [registerMountContext(contextName, provider)](./kibana-plugin-core-public.applicationstart.registermountcontext.md) | Register a context provider for application mounting. Will only be available to applications that depend on the plugin that registered this context. Deprecated, use [CoreSetup.getStartServices](./kibana-plugin-core-public.coresetup.getstartservices.md). |
diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md
new file mode 100644
index 0000000000000..86b86776b0b12
--- /dev/null
+++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md
@@ -0,0 +1,45 @@
+
+
+[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [ApplicationStart](./kibana-plugin-core-public.applicationstart.md) > [navigateToUrl](./kibana-plugin-core-public.applicationstart.navigatetourl.md)
+
+## ApplicationStart.navigateToUrl() method
+
+Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible.
+
+If all these criteria are true for the given url: - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space) - The pathname segment after the basePath matches any known application route (eg. /app// or any application's `appRoute` configuration)
+
+Then a SPA navigation will be performed using `navigateToApp` using the corresponding application and path. Otherwise, fallback to a full page reload to navigate to the url using `window.location.assign`
+
+Signature:
+
+```typescript
+navigateToUrl(url: string): Promise;
+```
+
+## Parameters
+
+| Parameter | Type | Description |
+| --- | --- | --- |
+| url | string
| an absolute url, or a relative path, to navigate to. |
+
+Returns:
+
+`Promise`
+
+## Example
+
+
+```ts
+// current url: `https://kibana:8080/base-path/s/my-space/app/dashboard`
+
+// will call `application.navigateToApp('discover', { path: '/some-path?foo=bar'})`
+application.navigateToUrl('https://kibana:8080/base-path/s/my-space/app/discover/some-path?foo=bar')
+application.navigateToUrl('/base-path/s/my-space/app/discover/some-path?foo=bar')
+
+// will perform a full page reload using `window.location.assign`
+application.navigateToUrl('https://elsewhere:8080/base-path/s/my-space/app/discover/some-path') // origin does not match
+application.navigateToUrl('/app/discover/some-path') // does not include the current basePath
+application.navigateToUrl('/base-path/s/my-space/app/unknown-app/some-path') // unknown application
+
+```
+
diff --git a/examples/alerting_example/public/alert_types/always_firing.tsx b/examples/alerting_example/public/alert_types/always_firing.tsx
index b7add1f6d43ce..130519308d3c3 100644
--- a/examples/alerting_example/public/alert_types/always_firing.tsx
+++ b/examples/alerting_example/public/alert_types/always_firing.tsx
@@ -71,7 +71,7 @@ export const AlwaysFiringExpression: React.FunctionComponent {
+ onChange={(event) => {
setAlertParams('instances', event.target.valueAsNumber);
}}
/>
diff --git a/examples/alerting_example/public/alert_types/astros.tsx b/examples/alerting_example/public/alert_types/astros.tsx
index 3411c6722ccd6..2e263e454fa0c 100644
--- a/examples/alerting_example/public/alert_types/astros.tsx
+++ b/examples/alerting_example/public/alert_types/astros.tsx
@@ -51,7 +51,7 @@ interface PeopleinSpaceParamsProps {
}
function isValueInEnum(enumeratin: Record, value: any): boolean {
- return !!Object.values(enumeratin).find(enumVal => enumVal === value);
+ return !!Object.values(enumeratin).find((enumVal) => enumVal === value);
}
export function getAlertType(): AlertTypeModel {
@@ -139,7 +139,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent
- errs.map(e => (
+ errs.map((e) => (
{field}: `: ${errs}`
@@ -189,7 +189,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent {
+ onChange={(event) => {
setAlertParams('craft', event.target.value);
setCraftTrigger({
craft: event.target.value,
@@ -238,7 +238,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent {
+ onChange={(event) => {
setAlertParams('op', event.target.value);
setOuterSpaceCapacity({
...outerSpaceCapacityTrigger,
@@ -258,7 +258,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent {
+ onChange={(event) => {
setAlertParams('outerSpaceCapacity', event.target.valueAsNumber);
setOuterSpaceCapacity({
...outerSpaceCapacityTrigger,
diff --git a/examples/alerting_example/server/alert_types/astros.ts b/examples/alerting_example/server/alert_types/astros.ts
index d22bc6164fa52..d25edc1e01b3f 100644
--- a/examples/alerting_example/server/alert_types/astros.ts
+++ b/examples/alerting_example/server/alert_types/astros.ts
@@ -68,10 +68,7 @@ export const alertType: AlertType = {
if (getOperator(op)(peopleInCraft.length, outerSpaceCapacity)) {
peopleInCraft.forEach(({ craft, name }) => {
- services
- .alertInstanceFactory(name)
- .replaceState({ craft })
- .scheduleActions('default');
+ services.alertInstanceFactory(name).replaceState({ craft }).scheduleActions('default');
});
}
diff --git a/examples/bfetch_explorer/public/components/count_until/index.tsx b/examples/bfetch_explorer/public/components/count_until/index.tsx
index ce48ce9dfe61f..73cbcf4cbdb1c 100644
--- a/examples/bfetch_explorer/public/components/count_until/index.tsx
+++ b/examples/bfetch_explorer/public/components/count_until/index.tsx
@@ -82,7 +82,7 @@ export const CountUntil: React.FC = ({ fetchStreaming }) => {
setData(Number(e.target.value))}
+ onChange={(e) => setData(Number(e.target.value))}
/>
diff --git a/examples/bfetch_explorer/public/components/double_integers/index.tsx b/examples/bfetch_explorer/public/components/double_integers/index.tsx
index d8fbe33ec73be..58940c23b1a6c 100644
--- a/examples/bfetch_explorer/public/components/double_integers/index.tsx
+++ b/examples/bfetch_explorer/public/components/double_integers/index.tsx
@@ -49,18 +49,18 @@ export const DoubleIntegers: React.FC = ({ double }) => {
setShowingResults(true);
const nums = numbers
.split('\n')
- .map(num => num.trim())
+ .map((num) => num.trim())
.filter(Boolean)
.map(Number);
counter.set(nums.length);
- nums.forEach(num => {
+ nums.forEach((num) => {
double({ num }).then(
- result => {
+ (result) => {
if (!isMounted()) return;
counter.dec();
pushResult({ num, result });
},
- error => {
+ (error) => {
if (!isMounted()) return;
counter.dec();
pushResult({ num, error });
@@ -94,7 +94,7 @@ export const DoubleIntegers: React.FC = ({ double }) => {
fullWidth
placeholder="Enter numbers in milliseconds separated by new line"
value={numbers}
- onChange={e => setNumbers(e.target.value)}
+ onChange={(e) => setNumbers(e.target.value)}
/>
diff --git a/examples/bfetch_explorer/public/containers/app/index.tsx b/examples/bfetch_explorer/public/containers/app/index.tsx
index a448c9e4f3a6a..13dee8ad9e61f 100644
--- a/examples/bfetch_explorer/public/containers/app/index.tsx
+++ b/examples/bfetch_explorer/public/containers/app/index.tsx
@@ -30,7 +30,7 @@ export const App: React.FC = () => {
const routeElements: React.ReactElement[] = [];
for (const { items } of routes) {
for (const { id, component } of items) {
- routeElements.push( component} />);
+ routeElements.push( component} />);
}
}
diff --git a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx
index cc50698e05908..029076adea666 100644
--- a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx
+++ b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx
@@ -39,7 +39,7 @@ export const Sidebar: React.FC = () => {
id,
name: title,
isSelected: true,
- items: items.map(route => ({
+ items: items.map((route) => ({
id: route.id,
name: route.title,
onClick: () => history.push(`/${route.id}`),
diff --git a/examples/bfetch_explorer/server/plugin.ts b/examples/bfetch_explorer/server/plugin.ts
index bf3b7f50ca6c8..2bfb63edefa3d 100644
--- a/examples/bfetch_explorer/server/plugin.ts
+++ b/examples/bfetch_explorer/server/plugin.ts
@@ -54,7 +54,7 @@ export class BfetchExplorerPlugin implements Plugin {
// Validate inputs.
if (num < 0) throw new Error('Invalid number');
// Wait number of specified milliseconds.
- await new Promise(r => setTimeout(r, num));
+ await new Promise((r) => setTimeout(r, num));
// Double the number and send it back.
return { num: 2 * num };
},
diff --git a/examples/demo_search/server/async_demo_search_strategy.ts b/examples/demo_search/server/async_demo_search_strategy.ts
index d2d40891a5d93..7ed5062acba48 100644
--- a/examples/demo_search/server/async_demo_search_strategy.ts
+++ b/examples/demo_search/server/async_demo_search_strategy.ts
@@ -40,7 +40,7 @@ const totalMap = new Map();
export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider = () => {
return {
- search: async request => {
+ search: async (request) => {
const id = request.id ?? generateId();
const loaded = (loadedMap.get(id) ?? 0) + 1;
@@ -52,7 +52,7 @@ export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider {
+ cancel: async (id) => {
loadedMap.delete(id);
totalMap.delete(id);
},
diff --git a/examples/demo_search/server/demo_search_strategy.ts b/examples/demo_search/server/demo_search_strategy.ts
index 5b0883be1fc51..a1fd0e45dbc8e 100644
--- a/examples/demo_search/server/demo_search_strategy.ts
+++ b/examples/demo_search/server/demo_search_strategy.ts
@@ -22,7 +22,7 @@ import { DEMO_SEARCH_STRATEGY } from '../common';
export const demoSearchStrategyProvider: TSearchStrategyProvider = () => {
return {
- search: request => {
+ search: (request) => {
return Promise.resolve({
greeting:
request.mood === 'happy'
diff --git a/examples/embeddable_examples/public/list_container/list_container_component.tsx b/examples/embeddable_examples/public/list_container/list_container_component.tsx
index da27889a27603..ae4de1c765154 100644
--- a/examples/embeddable_examples/public/list_container/list_container_component.tsx
+++ b/examples/embeddable_examples/public/list_container/list_container_component.tsx
@@ -40,7 +40,7 @@ function renderList(
embeddableServices: EmbeddableStart
) {
let number = 0;
- const list = Object.values(panels).map(panel => {
+ const list = Object.values(panels).map((panel) => {
const child = embeddable.getChild(panel.explicitInput.id);
number++;
return (
diff --git a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx
index b2882c97ef501..c059a884f08a2 100644
--- a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx
+++ b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx
@@ -55,7 +55,7 @@ function wrapSearchTerms(task: string, search?: string) {
}
function renderTasks(tasks: MultiTaskTodoInput['tasks'], search?: string) {
- return tasks.map(task => (
+ return tasks.map((task) => (
task.match(search));
+ const match = tasks.find((task) => task.match(search));
if (match) return true;
return false;
diff --git a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx
index 49dbce74788bf..f5fe01734bfa5 100644
--- a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx
+++ b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx
@@ -65,12 +65,12 @@ export class SearchableListContainerComponentInner extends Component {
+ props.embeddable.getChildIds().forEach((id) => {
checked[id] = false;
const output = props.embeddable.getChild(id).getOutput();
hasMatch[id] = hasHasMatchOutput(output) && output.hasMatch;
});
- props.embeddable.getChildIds().forEach(id => (checked[id] = false));
+ props.embeddable.getChildIds().forEach((id) => (checked[id] = false));
this.state = {
checked,
hasMatch,
@@ -78,13 +78,13 @@ export class SearchableListContainerComponentInner extends Component {
+ this.props.embeddable.getChildIds().forEach((id) => {
this.subscriptions[id] = this.props.embeddable
.getChild(id)
.getOutput$()
- .subscribe(output => {
+ .subscribe((output) => {
if (hasHasMatchOutput(output)) {
- this.setState(prevState => ({
+ this.setState((prevState) => ({
hasMatch: {
...prevState.hasMatch,
[id]: output.hasMatch,
@@ -96,7 +96,7 @@ export class SearchableListContainerComponentInner extends Component sub.unsubscribe());
+ Object.values(this.subscriptions).forEach((sub) => sub.unsubscribe());
}
private updateSearch = (search: string) => {
@@ -104,7 +104,7 @@ export class SearchableListContainerComponentInner extends Component {
- Object.values(this.props.input.panels).map(panel => {
+ Object.values(this.props.input.panels).map((panel) => {
if (this.state.checked[panel.explicitInput.id]) {
this.props.embeddable.removeEmbeddable(panel.explicitInput.id);
this.subscriptions[panel.explicitInput.id].unsubscribe();
@@ -115,7 +115,7 @@ export class SearchableListContainerComponentInner extends Component {
const { input, embeddable } = this.props;
const checked: { [key: string]: boolean } = {};
- Object.values(input.panels).map(panel => {
+ Object.values(input.panels).map((panel) => {
const child = embeddable.getChild(panel.explicitInput.id);
const output = child.getOutput();
if (hasHasMatchOutput(output) && output.hasMatch) {
@@ -126,7 +126,7 @@ export class SearchableListContainerComponentInner extends Component {
- this.setState(prevState => ({ checked: { ...prevState.checked, [id]: isChecked } }));
+ this.setState((prevState) => ({ checked: { ...prevState.checked, [id]: isChecked } }));
};
public renderControls() {
@@ -156,7 +156,7 @@ export class SearchableListContainerComponentInner extends Component this.updateSearch(ev.target.value)}
+ onChange={(ev) => this.updateSearch(ev.target.value)}
/>
@@ -183,7 +183,7 @@ export class SearchableListContainerComponentInner extends Component {
+ const list = Object.values(input.panels).map((panel) => {
const childEmbeddable = embeddable.getChild(panel.explicitInput.id);
id++;
return childEmbeddable ? (
@@ -195,7 +195,7 @@ export class SearchableListContainerComponentInner extends Component this.toggleCheck(e.target.checked, childEmbeddable.id)}
+ onChange={(e) => this.toggleCheck(e.target.checked, childEmbeddable.id)}
/>
diff --git a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx
index bc577ca36d793..a46c3ce9ed8e9 100644
--- a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx
+++ b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx
@@ -34,7 +34,7 @@ function TaskInput({ onSave }: { onSave: (task: string) => void }) {
data-test-subj="taskInputField"
value={task}
placeholder="Enter task here"
- onChange={e => setTask(e.target.value)}
+ onChange={(e) => setTask(e.target.value)}
/>
onSave(task)}>
Save
@@ -69,7 +69,7 @@ export class TodoEmbeddableFactory
*/
public getExplicitInput = async () => {
const { openModal } = await this.getStartServices();
- return new Promise<{ task: string }>(resolve => {
+ return new Promise<{ task: string }>((resolve) => {
const onSave = (task: string) => resolve({ task });
const overlay = openModal(
toMountPoint(
diff --git a/examples/embeddable_explorer/public/app.tsx b/examples/embeddable_explorer/public/app.tsx
index e18012b4b3d80..3fc7fbb3b89ef 100644
--- a/examples/embeddable_explorer/public/app.tsx
+++ b/examples/embeddable_explorer/public/app.tsx
@@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & {
};
const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => {
- const navItems = pages.map(page => ({
+ const navItems = pages.map((page) => ({
id: page.id,
name: page.title,
onClick: () => history.push(`/${page.id}`),
@@ -122,7 +122,7 @@ const EmbeddableExplorerApp = ({
];
const routes = pages.map((page, i) => (
- page.component} />
+ page.component} />
));
return (
diff --git a/examples/embeddable_explorer/public/embeddable_panel_example.tsx b/examples/embeddable_explorer/public/embeddable_panel_example.tsx
index 54cd7c5b5b2c0..98f30632ebf43 100644
--- a/examples/embeddable_explorer/public/embeddable_panel_example.tsx
+++ b/examples/embeddable_explorer/public/embeddable_panel_example.tsx
@@ -84,7 +84,7 @@ export function EmbeddablePanelExample({ embeddableServices }: Props) {
const factory = embeddableServices.getEmbeddableFactory(SEARCHABLE_LIST_CONTAINER);
const promise = factory?.create(searchableInput);
if (promise) {
- promise.then(e => {
+ promise.then((e) => {
if (ref.current) {
setEmbeddable(e);
}
diff --git a/examples/embeddable_explorer/public/todo_embeddable_example.tsx b/examples/embeddable_explorer/public/todo_embeddable_example.tsx
index 2af6c713593c6..f43a81c3e7651 100644
--- a/examples/embeddable_explorer/public/todo_embeddable_example.tsx
+++ b/examples/embeddable_explorer/public/todo_embeddable_example.tsx
@@ -82,7 +82,7 @@ export class TodoEmbeddableExample extends React.Component {
icon: 'broom',
title: 'Trash',
})
- .then(embeddable => {
+ .then((embeddable) => {
this.embeddable = embeddable;
this.setState({ loading: false });
});
@@ -135,7 +135,7 @@ export class TodoEmbeddableExample extends React.Component {
this.setState({ title: ev.target.value })}
+ onChange={(ev) => this.setState({ title: ev.target.value })}
/>
@@ -143,7 +143,7 @@ export class TodoEmbeddableExample extends React.Component {
this.setState({ icon: ev.target.value })}
+ onChange={(ev) => this.setState({ icon: ev.target.value })}
/>
@@ -153,7 +153,7 @@ export class TodoEmbeddableExample extends React.Component {
fullWidth
resize="horizontal"
data-test-subj="taskTodo"
- onChange={ev => this.setState({ task: ev.target.value })}
+ onChange={(ev) => this.setState({ task: ev.target.value })}
/>
diff --git a/examples/search_explorer/public/application.tsx b/examples/search_explorer/public/application.tsx
index ea6d65d9e2113..a7072936f268d 100644
--- a/examples/search_explorer/public/application.tsx
+++ b/examples/search_explorer/public/application.tsx
@@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & {
};
const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => {
- const navItems = pages.map(page => ({
+ const navItems = pages.map((page) => ({
id: page.id,
name: page.title,
onClick: () => history.push(`/${page.id}`),
@@ -103,7 +103,7 @@ const SearchApp = ({ basename, data, application }: SearchBarComponentParams) =>
];
const routes = pages.map((page, i) => (
- buildPage(page)} />
+ buildPage(page)} />
));
return (
diff --git a/examples/search_explorer/public/async_demo_strategy.tsx b/examples/search_explorer/public/async_demo_strategy.tsx
index 40ddcc1f48fe7..9cea556c32d54 100644
--- a/examples/search_explorer/public/async_demo_strategy.tsx
+++ b/examples/search_explorer/public/async_demo_strategy.tsx
@@ -73,7 +73,7 @@ export class AsyncDemoStrategy extends React.Component {
this.setState({ fibonacciNumbers: parseFloat(e.target.value) })}
+ onChange={(e) => this.setState({ fibonacciNumbers: parseFloat(e.target.value) })}
/>
diff --git a/examples/search_explorer/public/demo_strategy.tsx b/examples/search_explorer/public/demo_strategy.tsx
index 7c6c21d2b7aed..3de6827818e14 100644
--- a/examples/search_explorer/public/demo_strategy.tsx
+++ b/examples/search_explorer/public/demo_strategy.tsx
@@ -81,7 +81,7 @@ export class DemoStrategy extends React.Component {
this.setState({ name: e.target.value })}
+ onChange={(e) => this.setState({ name: e.target.value })}
/>
@@ -90,7 +90,7 @@ export class DemoStrategy extends React.Component {
this.setState({ mood: e.target.value })}
+ onChange={(e) => this.setState({ mood: e.target.value })}
/>
diff --git a/examples/search_explorer/public/do_search.tsx b/examples/search_explorer/public/do_search.tsx
index a6b6b9b57db4a..deadb06b16f5f 100644
--- a/examples/search_explorer/public/do_search.tsx
+++ b/examples/search_explorer/public/do_search.tsx
@@ -61,10 +61,10 @@ export class DoSearch extends React.Component {
this.abortController = new AbortController();
this.props.search(this.abortController.signal).subscribe(
- response => {
+ (response) => {
this.setState({ response, error: undefined });
},
- error => {
+ (error) => {
this.setState({ error, searching: false, response: undefined });
},
() => {
diff --git a/examples/search_explorer/public/es_strategy.tsx b/examples/search_explorer/public/es_strategy.tsx
index aaf9dada90341..bc6223c478bf5 100644
--- a/examples/search_explorer/public/es_strategy.tsx
+++ b/examples/search_explorer/public/es_strategy.tsx
@@ -92,7 +92,7 @@ export class EsSearchTest extends React.Component {
this.setState({ index: e.target.value, changes: true })}
+ onChange={(e) => this.setState({ index: e.target.value, changes: true })}
/>
@@ -101,7 +101,7 @@ export class EsSearchTest extends React.Component {
this.setState({ query: e.target.value, changes: true })}
+ onChange={(e) => this.setState({ query: e.target.value, changes: true })}
/>
diff --git a/examples/search_explorer/public/guide_section.tsx b/examples/search_explorer/public/guide_section.tsx
index 1562e33b14c2f..c13c11dc5864c 100644
--- a/examples/search_explorer/public/guide_section.tsx
+++ b/examples/search_explorer/public/guide_section.tsx
@@ -59,7 +59,7 @@ export class GuideSection extends React.Component {
}
if (props.codeSections) {
- props.codeSections.forEach(section => {
+ props.codeSections.forEach((section) => {
this.tabs.push({
name: section.title,
displayName: section.title,
@@ -79,7 +79,7 @@ export class GuideSection extends React.Component {
};
renderTabs() {
- return this.tabs.map(tab => (
+ return this.tabs.map((tab) => (
this.onSelectedTabChanged(tab.name)}
isSelected={tab.name === this.state.selectedTab}
@@ -98,7 +98,7 @@ export class GuideSection extends React.Component {
if (!this.props.codeSections) {
return undefined;
}
- const section = this.props.codeSections.find(s => s.title === this.state.selectedTab);
+ const section = this.props.codeSections.find((s) => s.title === this.state.selectedTab);
if (!section) {
throw new Error('No section named ' + this.state.selectedTab);
diff --git a/examples/state_containers_examples/public/todo/todo.tsx b/examples/state_containers_examples/public/todo/todo.tsx
index 597c2b19be0f6..b6f4f6550026b 100644
--- a/examples/state_containers_examples/public/todo/todo.tsx
+++ b/examples/state_containers_examples/public/todo/todo.tsx
@@ -61,7 +61,7 @@ const defaultGlobalState: GlobalState = { text: '' };
const globalStateContainer = createStateContainer(
defaultGlobalState,
{
- setText: state => text => ({ ...state, text }),
+ setText: (state) => (text) => ({ ...state, text }),
}
);
@@ -81,7 +81,7 @@ const TodoApp: React.FC = ({ filter }) => {
const { text } = GlobalStateHelpers.useState();
const { edit: editTodo, delete: deleteTodo, add: addTodo } = useTransitions();
const todos = useState().todos;
- const filteredTodos = todos.filter(todo => {
+ const filteredTodos = todos.filter((todo) => {
if (!filter) return true;
if (filter === 'completed') return todo.completed;
if (filter === 'not-completed') return !todo.completed;
@@ -111,13 +111,13 @@ const TodoApp: React.FC = ({ filter }) => {
- {filteredTodos.map(todo => (
+ {filteredTodos.map((todo) => (
{
+ onChange={(e) => {
editTodo({
...todo,
completed: e.target.checked,
@@ -139,7 +139,7 @@ const TodoApp: React.FC = ({ filter }) => {
))}
Global state piece:
- setText(e.target.value)} />
+ setText(e.target.value)} />
>
);
@@ -173,7 +173,7 @@ export const TodoAppPage: React.FC<{
appTitle: string;
appBasePath: string;
isInitialRoute: () => boolean;
-}> = props => {
+}> = (props) => {
const initialAppUrl = React.useRef(window.location.href);
const [useHashedUrl, setUseHashedUrl] = React.useState(false);
@@ -181,7 +181,7 @@ export const TodoAppPage: React.FC<{
* Replicates what src/legacy/ui/public/chrome/api/nav.ts did
* Persists the url in sessionStorage and tries to restore it on "componentDidMount"
*/
- useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, urlToRestore => {
+ useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, (urlToRestore) => {
// shouldRestoreUrl:
// App decides if it should restore url or not
// In this specific case, restore only if navigated to initial route
diff --git a/examples/state_containers_examples/public/with_data_services/components/app.tsx b/examples/state_containers_examples/public/with_data_services/components/app.tsx
index c820929d8a61d..baf627fd62a32 100644
--- a/examples/state_containers_examples/public/with_data_services/components/app.tsx
+++ b/examples/state_containers_examples/public/with_data_services/components/app.tsx
@@ -135,7 +135,7 @@ const App = ({
appStateContainer.set({ ...appState, name: e.target.value })}
+ onChange={(e) => appStateContainer.set({ ...appState, name: e.target.value })}
aria-label="My name"
/>
@@ -217,7 +217,7 @@ function useAppStateSyncing(
stateContainer: {
...appStateContainer,
// stateSync utils requires explicit handling of default state ("null")
- set: state => state && appStateContainer.set(state),
+ set: (state) => state && appStateContainer.set(state),
},
});
diff --git a/examples/ui_actions_explorer/public/actions/actions.tsx b/examples/ui_actions_explorer/public/actions/actions.tsx
index 64a820ab6d194..4ef8d5bf4d9c6 100644
--- a/examples/ui_actions_explorer/public/actions/actions.tsx
+++ b/examples/ui_actions_explorer/public/actions/actions.tsx
@@ -47,14 +47,14 @@ export interface PhoneContext {
export const makePhoneCallAction = createAction({
type: ACTION_CALL_PHONE_NUMBER,
getDisplayName: () => 'Call phone number',
- execute: async context => alert(`Pretend calling ${context.phone}...`),
+ execute: async (context) => alert(`Pretend calling ${context.phone}...`),
});
export const lookUpWeatherAction = createAction({
type: ACTION_TRAVEL_GUIDE,
getIconType: () => 'popout',
getDisplayName: () => 'View travel guide',
- execute: async context => {
+ execute: async (context) => {
window.open(`https://www.worldtravelguide.net/?s=${context.country}`, '_blank');
},
});
@@ -67,7 +67,7 @@ export const viewInMapsAction = createAction({
type: ACTION_VIEW_IN_MAPS,
getIconType: () => 'popout',
getDisplayName: () => 'View in maps',
- execute: async context => {
+ execute: async (context) => {
window.open(`https://www.google.com/maps/place/${context.country}`, '_blank');
},
});
@@ -90,7 +90,7 @@ function EditUserModal({
const [name, setName] = useState(user.name);
return (
- setName(e.target.value)} />
+ setName(e.target.value)} />
{
update({ ...user, name });
diff --git a/examples/ui_actions_explorer/public/app.tsx b/examples/ui_actions_explorer/public/app.tsx
index f08b8bb29bdd3..1b0667962a3c2 100644
--- a/examples/ui_actions_explorer/public/app.tsx
+++ b/examples/ui_actions_explorer/public/app.tsx
@@ -72,7 +72,7 @@ const ActionsExplorer = ({ uiActionsApi, openModal }: Props) => {
from. Using the UI Action and Trigger API makes your plugin extensible by other
plugins. Any actions attached to the `HELLO_WORLD_TRIGGER_ID` will show up here!
- setName(e.target.value)} />
+ setName(e.target.value)} />
{
diff --git a/examples/ui_actions_explorer/public/trigger_context_example.tsx b/examples/ui_actions_explorer/public/trigger_context_example.tsx
index 4b88652103966..05a9895d3fac4 100644
--- a/examples/ui_actions_explorer/public/trigger_context_example.tsx
+++ b/examples/ui_actions_explorer/public/trigger_context_example.tsx
@@ -105,7 +105,7 @@ export function TriggerContextExample({ uiActionsApi }: Props) {
];
const updateUser = (newUser: User, oldName: string) => {
- const index = rows.findIndex(u => u.name === oldName);
+ const index = rows.findIndex((u) => u.name === oldName);
const newRows = [...rows];
newRows.splice(index, 1, createRowData(newUser, uiActionsApi, updateUser));
setRows(newRows);
diff --git a/examples/url_generators_examples/public/app.tsx b/examples/url_generators_examples/public/app.tsx
index c39cd876ea9b1..82f36fa13ea71 100644
--- a/examples/url_generators_examples/public/app.tsx
+++ b/examples/url_generators_examples/public/app.tsx
@@ -67,7 +67,7 @@ export const Routes: React.FC<{}> = () => {
export const LinksExample: React.FC<{
appBasePath: string;
-}> = props => {
+}> = (props) => {
const history = React.useMemo(
() =>
createBrowserHistory({
diff --git a/examples/url_generators_examples/public/url_generator.ts b/examples/url_generators_examples/public/url_generator.ts
index f21b1c9295e66..c74ade8bf743d 100644
--- a/examples/url_generators_examples/public/url_generator.ts
+++ b/examples/url_generators_examples/public/url_generator.ts
@@ -38,7 +38,7 @@ export const createHelloPageLinkGenerator = (
getStartServices: () => Promise<{ appBasePath: string }>
): UrlGeneratorsDefinition => ({
id: HELLO_URL_GENERATOR,
- createUrl: async state => {
+ createUrl: async (state) => {
const startServices = await getStartServices();
const appBasePath = startServices.appBasePath;
const parsedUrl = url.parse(window.location.href);
@@ -72,7 +72,7 @@ export type LegacyHelloLinkGeneratorState = UrlGeneratorState<
export const helloPageLinkGeneratorV1: UrlGeneratorsDefinition = {
id: HELLO_URL_GENERATOR_V1,
isDeprecated: true,
- migrate: async state => {
+ migrate: async (state) => {
return { id: HELLO_URL_GENERATOR, state: { firstName: state.name, lastName: '' } };
},
};
diff --git a/examples/url_generators_explorer/public/app.tsx b/examples/url_generators_explorer/public/app.tsx
index 77e804ae08c5f..50dd2e075c528 100644
--- a/examples/url_generators_explorer/public/app.tsx
+++ b/examples/url_generators_explorer/public/app.tsx
@@ -81,7 +81,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
const updateLinks = async () => {
const updatedLinks = await Promise.all(
- persistedLinks.map(async savedLink => {
+ persistedLinks.map(async (savedLink) => {
const generator = getLinkGenerator(savedLink.id);
const link = await generator.createUrl(savedLink.state);
return {
@@ -109,11 +109,11 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
{
+ onChange={(e) => {
setFirstName(e.target.value);
}}
/>
- setLastName(e.target.value)} />
+ setLastName(e.target.value)} />
setPersistedLinks([
@@ -142,7 +142,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
{buildingLinks ? (
loading...
) : (
- migratedLinks.map(link => (
+ migratedLinks.map((link) => (
dateMath.parse('now', { forceNow: '2000-01-01T00:00:00.000Z' });
expect(fn).to.throwError();
});
- it('should throw an Error if passed a moment', function() {
+ it('should throw an Error if passed a moment', function () {
expect(() => dateMath.parse('now', { forceNow: moment() })).to.throwError();
});
- it('should throw an Error if passed an invalid date', function() {
+ it('should throw an Error if passed an invalid date', function () {
expect(() => dateMath.parse('now', { forceNow: new Date('foobar') })).to.throwError();
});
});
});
- describe('objects and strings', function() {
+ describe('objects and strings', function () {
let mmnt;
let date;
let string;
let now;
- beforeEach(function() {
+ beforeEach(function () {
clock = sinon.useFakeTimers(unix);
now = moment();
mmnt = moment(anchor);
@@ -99,61 +99,61 @@ describe('dateMath', function() {
string = mmnt.format(format);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- it('should return the same moment if passed a moment', function() {
+ it('should return the same moment if passed a moment', function () {
expect(dateMath.parse(mmnt)).to.eql(mmnt);
});
- it('should return a moment if passed a date', function() {
+ it('should return a moment if passed a date', function () {
expect(dateMath.parse(date).format(format)).to.eql(mmnt.format(format));
});
- it('should return a moment if passed an ISO8601 string', function() {
+ it('should return a moment if passed an ISO8601 string', function () {
expect(dateMath.parse(string).format(format)).to.eql(mmnt.format(format));
});
- it('should return the current time when parsing now', function() {
+ it('should return the current time when parsing now', function () {
expect(dateMath.parse('now').format(format)).to.eql(now.format(format));
});
- it('should use the forceNow parameter when parsing now', function() {
+ it('should use the forceNow parameter when parsing now', function () {
expect(dateMath.parse('now', { forceNow: anchoredDate }).valueOf()).to.eql(unix);
});
});
- describe('subtraction', function() {
+ describe('subtraction', function () {
let now;
let anchored;
- beforeEach(function() {
+ beforeEach(function () {
clock = sinon.useFakeTimers(unix);
now = moment();
anchored = moment(anchor);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- [5, 12, 247].forEach(len => {
- spans.forEach(span => {
+ [5, 12, 247].forEach((len) => {
+ spans.forEach((span) => {
const nowEx = `now-${len}${span}`;
const thenEx = `${anchor}||-${len}${span}`;
- it('should return ' + len + span + ' ago', function() {
+ it('should return ' + len + span + ' ago', function () {
const parsed = dateMath.parse(nowEx).format(format);
expect(parsed).to.eql(now.subtract(len, span).format(format));
});
- it('should return ' + len + span + ' before ' + anchor, function() {
+ it('should return ' + len + span + ' before ' + anchor, function () {
const parsed = dateMath.parse(thenEx).format(format);
expect(parsed).to.eql(anchored.subtract(len, span).format(format));
});
- it('should return ' + len + span + ' before forceNow', function() {
+ it('should return ' + len + span + ' before forceNow', function () {
const parsed = dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf();
expect(parsed).to.eql(anchored.subtract(len, span).valueOf());
});
@@ -161,36 +161,36 @@ describe('dateMath', function() {
});
});
- describe('addition', function() {
+ describe('addition', function () {
let now;
let anchored;
- beforeEach(function() {
+ beforeEach(function () {
clock = sinon.useFakeTimers(unix);
now = moment();
anchored = moment(anchor);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- [5, 12, 247].forEach(len => {
- spans.forEach(span => {
+ [5, 12, 247].forEach((len) => {
+ spans.forEach((span) => {
const nowEx = `now+${len}${span}`;
const thenEx = `${anchor}||+${len}${span}`;
- it('should return ' + len + span + ' from now', function() {
+ it('should return ' + len + span + ' from now', function () {
expect(dateMath.parse(nowEx).format(format)).to.eql(now.add(len, span).format(format));
});
- it('should return ' + len + span + ' after ' + anchor, function() {
+ it('should return ' + len + span + ' after ' + anchor, function () {
expect(dateMath.parse(thenEx).format(format)).to.eql(
anchored.add(len, span).format(format)
);
});
- it('should return ' + len + span + ' after forceNow', function() {
+ it('should return ' + len + span + ' after forceNow', function () {
expect(dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf()).to.eql(
anchored.add(len, span).valueOf()
);
@@ -199,40 +199,40 @@ describe('dateMath', function() {
});
});
- describe('rounding', function() {
+ describe('rounding', function () {
let now;
let anchored;
- beforeEach(function() {
+ beforeEach(function () {
clock = sinon.useFakeTimers(unix);
now = moment();
anchored = moment(anchor);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- spans.forEach(span => {
- it(`should round now to the beginning of the ${span}`, function() {
+ spans.forEach((span) => {
+ it(`should round now to the beginning of the ${span}`, function () {
expect(dateMath.parse('now/' + span).format(format)).to.eql(
now.startOf(span).format(format)
);
});
- it(`should round now to the beginning of forceNow's ${span}`, function() {
+ it(`should round now to the beginning of forceNow's ${span}`, function () {
expect(dateMath.parse('now/' + span, { forceNow: anchoredDate }).valueOf()).to.eql(
anchored.startOf(span).valueOf()
);
});
- it(`should round now to the end of the ${span}`, function() {
+ it(`should round now to the end of the ${span}`, function () {
expect(dateMath.parse('now/' + span, { roundUp: true }).format(format)).to.eql(
now.endOf(span).format(format)
);
});
- it(`should round now to the end of forceNow's ${span}`, function() {
+ it(`should round now to the end of forceNow's ${span}`, function () {
expect(
dateMath.parse('now/' + span, { roundUp: true, forceNow: anchoredDate }).valueOf()
).to.eql(anchored.endOf(span).valueOf());
@@ -240,61 +240,46 @@ describe('dateMath', function() {
});
});
- describe('math and rounding', function() {
+ describe('math and rounding', function () {
let now;
let anchored;
- beforeEach(function() {
+ beforeEach(function () {
clock = sinon.useFakeTimers(unix);
now = moment();
anchored = moment(anchor);
});
- afterEach(function() {
+ afterEach(function () {
clock.restore();
});
- it('should round to the nearest second with 0 value', function() {
+ it('should round to the nearest second with 0 value', function () {
const val = dateMath.parse('now-0s/s').format(format);
expect(val).to.eql(now.startOf('s').format(format));
});
- it('should subtract 17s, rounded to the nearest second', function() {
+ it('should subtract 17s, rounded to the nearest second', function () {
const val = dateMath.parse('now-17s/s').format(format);
- expect(val).to.eql(
- now
- .startOf('s')
- .subtract(17, 's')
- .format(format)
- );
+ expect(val).to.eql(now.startOf('s').subtract(17, 's').format(format));
});
- it('should add 555ms, rounded to the nearest millisecond', function() {
+ it('should add 555ms, rounded to the nearest millisecond', function () {
const val = dateMath.parse('now+555ms/ms').format(format);
- expect(val).to.eql(
- now
- .add(555, 'ms')
- .startOf('ms')
- .format(format)
- );
+ expect(val).to.eql(now.add(555, 'ms').startOf('ms').format(format));
});
- it('should subtract 555ms, rounded to the nearest second', function() {
+ it('should subtract 555ms, rounded to the nearest second', function () {
const val = dateMath.parse('now-555ms/s').format(format);
- expect(val).to.eql(
- now
- .subtract(555, 'ms')
- .startOf('s')
- .format(format)
- );
+ expect(val).to.eql(now.subtract(555, 'ms').startOf('s').format(format));
});
- it('should round weeks to Sunday by default', function() {
+ it('should round weeks to Sunday by default', function () {
const val = dateMath.parse('now-1w/w');
expect(val.isoWeekday()).to.eql(7);
});
- it('should round weeks based on the passed moment locale start of week setting', function() {
+ it('should round weeks based on the passed moment locale start of week setting', function () {
const m = momentClone();
// Define a locale, that has Tuesday as beginning of the week
m.defineLocale('x-test', {
@@ -304,7 +289,7 @@ describe('dateMath', function() {
expect(val.isoWeekday()).to.eql(2);
});
- it('should round up weeks based on the passed moment locale start of week setting', function() {
+ it('should round up weeks based on the passed moment locale start of week setting', function () {
const m = momentClone();
// Define a locale, that has Tuesday as beginning of the week
m.defineLocale('x-test', {
@@ -319,7 +304,7 @@ describe('dateMath', function() {
expect(val.isoWeekday()).to.eql(3 - 1);
});
- it('should round relative to forceNow', function() {
+ it('should round relative to forceNow', function () {
const val = dateMath.parse('now-0s/s', { forceNow: anchoredDate }).valueOf();
expect(val).to.eql(anchored.startOf('s').valueOf());
});
@@ -329,15 +314,15 @@ describe('dateMath', function() {
});
});
- describe('used momentjs instance', function() {
- it('should use the default moment instance if parameter not specified', function() {
+ describe('used momentjs instance', function () {
+ it('should use the default moment instance if parameter not specified', function () {
const momentSpy = sinon.spy(moment, 'isMoment');
dateMath.parse('now');
expect(momentSpy.called).to.be(true);
momentSpy.restore();
});
- it('should not use default moment instance if parameter is specified', function() {
+ it('should not use default moment instance if parameter is specified', function () {
const m = momentClone();
const momentSpy = sinon.spy(moment, 'isMoment');
const cloneSpy = sinon.spy(m, 'isMoment');
@@ -348,7 +333,7 @@ describe('dateMath', function() {
cloneSpy.restore();
});
- it('should work with multiple different instances', function() {
+ it('should work with multiple different instances', function () {
const m1 = momentClone();
const m2 = momentClone();
const m1Spy = sinon.spy(m1, 'isMoment');
@@ -365,7 +350,7 @@ describe('dateMath', function() {
m2Spy.restore();
});
- it('should use global instance after passing an instance', function() {
+ it('should use global instance after passing an instance', function () {
const m = momentClone();
const momentSpy = sinon.spy(moment, 'isMoment');
const cloneSpy = sinon.spy(m, 'isMoment');
@@ -382,12 +367,12 @@ describe('dateMath', function() {
});
});
- describe('units', function() {
- it('should have units descending for unitsDesc', function() {
+ describe('units', function () {
+ it('should have units descending for unitsDesc', function () {
expect(dateMath.unitsDesc).to.eql(['y', 'M', 'w', 'd', 'h', 'm', 's', 'ms']);
});
- it('should have units ascending for unitsAsc', function() {
+ it('should have units ascending for unitsAsc', function () {
expect(dateMath.unitsAsc).to.eql(['ms', 's', 'm', 'h', 'd', 'w', 'M', 'y']);
});
});
diff --git a/packages/elastic-datemath/src/index.js b/packages/elastic-datemath/src/index.js
index afedad3ef6f72..52ce12ddf7027 100644
--- a/packages/elastic-datemath/src/index.js
+++ b/packages/elastic-datemath/src/index.js
@@ -34,9 +34,9 @@ const units = Object.keys(unitsMap).sort((a, b) => unitsMap[b].weight - unitsMap
const unitsDesc = [...units];
const unitsAsc = [...units].reverse();
-const isDate = d => Object.prototype.toString.call(d) === '[object Date]';
+const isDate = (d) => Object.prototype.toString.call(d) === '[object Date]';
-const isValidDate = d => isDate(d) && !isNaN(d.valueOf());
+const isValidDate = (d) => isDate(d) && !isNaN(d.valueOf());
/*
* This is a simplified version of elasticsearch's date parser.
diff --git a/packages/eslint-config-kibana/package.json b/packages/eslint-config-kibana/package.json
index 34b1b0fec376f..d9aef63c0115c 100644
--- a/packages/eslint-config-kibana/package.json
+++ b/packages/eslint-config-kibana/package.json
@@ -15,8 +15,8 @@
},
"homepage": "https://github.com/elastic/eslint-config-kibana#readme",
"peerDependencies": {
- "@typescript-eslint/eslint-plugin": "^2.15.0",
- "@typescript-eslint/parser": "^2.15.0",
+ "@typescript-eslint/eslint-plugin": "^2.33.0",
+ "@typescript-eslint/parser": "^2.33.0",
"babel-eslint": "^10.0.3",
"eslint": "^6.8.0",
"eslint-plugin-babel": "^5.3.0",
diff --git a/packages/kbn-analytics/scripts/build.js b/packages/kbn-analytics/scripts/build.js
index bb28c1460c9c2..448d1ca9332f2 100644
--- a/packages/kbn-analytics/scripts/build.js
+++ b/packages/kbn-analytics/scripts/build.js
@@ -31,7 +31,7 @@ const padRight = (width, str) =>
run(
async ({ log, flags }) => {
- await withProcRunner(log, async proc => {
+ await withProcRunner(log, async (proc) => {
log.info('Deleting old output');
await del(BUILD_DIR);
@@ -43,7 +43,7 @@ run(
log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`);
await Promise.all([
- ...['web', 'node'].map(subTask =>
+ ...['web', 'node'].map((subTask) =>
proc.run(padRight(10, `babel:${subTask}`), {
cmd: 'babel',
args: [
diff --git a/packages/kbn-analytics/src/report.ts b/packages/kbn-analytics/src/report.ts
index 58891e48aa3a6..d9303d2d3af1d 100644
--- a/packages/kbn-analytics/src/report.ts
+++ b/packages/kbn-analytics/src/report.ts
@@ -86,7 +86,7 @@ export class ReportManager {
};
}
assignReports(newMetrics: Metric | Metric[]) {
- wrapArray(newMetrics).forEach(newMetric => this.assignReport(this.report, newMetric));
+ wrapArray(newMetrics).forEach((newMetric) => this.assignReport(this.report, newMetric));
return { report: this.report };
}
static createMetricKey(metric: Metric): string {
diff --git a/packages/kbn-analytics/src/reporter.ts b/packages/kbn-analytics/src/reporter.ts
index cbcdf6af63052..b20ddc0e58ba7 100644
--- a/packages/kbn-analytics/src/reporter.ts
+++ b/packages/kbn-analytics/src/reporter.ts
@@ -115,7 +115,7 @@ export class Reporter {
eventNames: string | string[],
count?: number
) => {
- const metrics = wrapArray(eventNames).map(eventName => {
+ const metrics = wrapArray(eventNames).map((eventName) => {
this.log(`${type} Metric -> (${appName}:${eventName}):`);
const report = createUiStatsMetric({ type, appName, eventName, count });
this.log(report);
diff --git a/packages/kbn-babel-code-parser/src/code_parser.js b/packages/kbn-babel-code-parser/src/code_parser.js
index 9431eb639e2e5..91927780363ac 100644
--- a/packages/kbn-babel-code-parser/src/code_parser.js
+++ b/packages/kbn-babel-code-parser/src/code_parser.js
@@ -79,7 +79,7 @@ export async function parseEntries(cwd, entries, strategy, results, wasParsed =
const sanitizedCwd = cwd || process.cwd();
// Test each entry against canRequire function
- const entriesQueue = entries.map(entry => canRequire(entry));
+ const entriesQueue = entries.map((entry) => canRequire(entry));
while (entriesQueue.length) {
// Get the first element in the queue as
diff --git a/packages/kbn-babel-code-parser/src/strategies.js b/packages/kbn-babel-code-parser/src/strategies.js
index f116abde9e0e6..2369692ad434b 100644
--- a/packages/kbn-babel-code-parser/src/strategies.js
+++ b/packages/kbn-babel-code-parser/src/strategies.js
@@ -59,7 +59,7 @@ export async function dependenciesParseStrategy(
// Get dependencies from a single file and filter
// out node native modules from the result
const dependencies = (await parseSingleFile(mainEntry, dependenciesVisitorsGenerator)).filter(
- dep => !builtinModules.includes(dep)
+ (dep) => !builtinModules.includes(dep)
);
// Return the list of all the new entries found into
diff --git a/packages/kbn-babel-code-parser/src/strategies.test.js b/packages/kbn-babel-code-parser/src/strategies.test.js
index dc2c599e81c39..e61c784cdcd54 100644
--- a/packages/kbn-babel-code-parser/src/strategies.test.js
+++ b/packages/kbn-babel-code-parser/src/strategies.test.js
@@ -84,7 +84,7 @@ describe('Code Parser Strategies', () => {
cb(null, `require('./relative_dep')`);
});
- canRequire.mockImplementation(entry => {
+ canRequire.mockImplementation((entry) => {
if (entry === `${mockCwd}dep1/relative_dep`) {
return `${entry}/index.js`;
}
diff --git a/packages/kbn-babel-code-parser/src/visitors.js b/packages/kbn-babel-code-parser/src/visitors.js
index 30014941d2a27..b159848d424fa 100644
--- a/packages/kbn-babel-code-parser/src/visitors.js
+++ b/packages/kbn-babel-code-parser/src/visitors.js
@@ -21,7 +21,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on require + require.resolve
CallExpression: ({ node }) => {
// AST check for require expressions
- const isRequire = node => {
+ const isRequire = (node) => {
return matches({
callee: {
type: 'Identifier',
@@ -31,7 +31,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
};
// AST check for require.resolve expressions
- const isRequireResolve = node => {
+ const isRequireResolve = (node) => {
return matches({
callee: {
type: 'MemberExpression',
@@ -66,7 +66,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on import
ImportDeclaration: ({ node }) => {
// AST check for supported import expressions
- const isImport = node => {
+ const isImport = (node) => {
return matches({
type: 'ImportDeclaration',
source: {
@@ -85,7 +85,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on export from
ExportNamedDeclaration: ({ node }) => {
// AST check for supported export from expressions
- const isExportFrom = node => {
+ const isExportFrom = (node) => {
return matches({
type: 'ExportNamedDeclaration',
source: {
@@ -104,7 +104,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on export * from
ExportAllDeclaration: ({ node }) => {
// AST check for supported export * from expressions
- const isExportAllFrom = node => {
+ const isExportAllFrom = (node) => {
return matches({
type: 'ExportAllDeclaration',
source: {
diff --git a/packages/kbn-babel-code-parser/src/visitors.test.js b/packages/kbn-babel-code-parser/src/visitors.test.js
index 6a29d144a4dee..d2704fa9dfb72 100644
--- a/packages/kbn-babel-code-parser/src/visitors.test.js
+++ b/packages/kbn-babel-code-parser/src/visitors.test.js
@@ -21,7 +21,7 @@ import * as parser from '@babel/parser';
import traverse from '@babel/traverse';
import { dependenciesVisitorsGenerator } from './visitors';
-const visitorsApplier = code => {
+const visitorsApplier = (code) => {
const result = [];
traverse(
parser.parse(code, {
diff --git a/packages/kbn-config-schema/src/errors/schema_error.test.ts b/packages/kbn-config-schema/src/errors/schema_error.test.ts
index 0f632b781e9a6..d5cbb5a718a6a 100644
--- a/packages/kbn-config-schema/src/errors/schema_error.test.ts
+++ b/packages/kbn-config-schema/src/errors/schema_error.test.ts
@@ -26,8 +26,8 @@ import { SchemaError } from '.';
export const cleanStack = (stack: string) =>
stack
.split('\n')
- .filter(line => !line.includes('node_modules/') && !line.includes('internal/'))
- .map(line => {
+ .filter((line) => !line.includes('node_modules/') && !line.includes('internal/'))
+ .map((line) => {
const parts = /.*\((.*)\).?/.exec(line) || [];
if (parts.length === 0) {
diff --git a/packages/kbn-config-schema/src/errors/validation_error.ts b/packages/kbn-config-schema/src/errors/validation_error.ts
index 2a4f887bc4349..0c86b61ba1e2a 100644
--- a/packages/kbn-config-schema/src/errors/validation_error.ts
+++ b/packages/kbn-config-schema/src/errors/validation_error.ts
@@ -26,12 +26,12 @@ export class ValidationError extends SchemaError {
let message = error.message;
if (error instanceof SchemaTypesError) {
const indentLevel = level || 0;
- const childErrorMessages = error.errors.map(childError =>
+ const childErrorMessages = error.errors.map((childError) =>
ValidationError.extractMessage(childError, namespace, indentLevel + 1)
);
message = `${message}\n${childErrorMessages
- .map(childErrorMessage => `${' '.repeat(indentLevel)}- ${childErrorMessage}`)
+ .map((childErrorMessage) => `${' '.repeat(indentLevel)}- ${childErrorMessage}`)
.join('\n')}`;
}
diff --git a/packages/kbn-config-schema/src/internals/index.ts b/packages/kbn-config-schema/src/internals/index.ts
index f84e14d2f741d..f3756aaf90793 100644
--- a/packages/kbn-config-schema/src/internals/index.ts
+++ b/packages/kbn-config-schema/src/internals/index.ts
@@ -42,9 +42,7 @@ function isMap(o: any): o is Map {
const anyCustomRule: Rules = {
name: 'custom',
params: {
- validator: Joi.func()
- .maxArity(1)
- .required(),
+ validator: Joi.func().maxArity(1).required(),
},
validate(params, value, state, options) {
let validationResultMessage;
diff --git a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts
index e0ef3835ca0a3..485251055d2b8 100644
--- a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts
+++ b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts
@@ -47,7 +47,7 @@ describe('isConfigSchema', () => {
expect(isConfigSchema(undefined)).toBe(false);
expect(isConfigSchema([1, 2, 3])).toBe(false);
expect(isConfigSchema({ foo: 'bar' })).toBe(false);
- expect(isConfigSchema(function() {})).toBe(false);
+ expect(isConfigSchema(function () {})).toBe(false);
});
it('returns true as long as `__isKbnConfigSchemaType` is true', () => {
diff --git a/packages/kbn-config-schema/src/types/array_type.ts b/packages/kbn-config-schema/src/types/array_type.ts
index 0df0d44a37951..2fe1fa24222a1 100644
--- a/packages/kbn-config-schema/src/types/array_type.ts
+++ b/packages/kbn-config-schema/src/types/array_type.ts
@@ -28,10 +28,7 @@ export type ArrayOptions = TypeOptions & {
export class ArrayType extends Type {
constructor(type: Type, options: ArrayOptions = {}) {
- let schema = internals
- .array()
- .items(type.getSchema().optional())
- .sparse(false);
+ let schema = internals.array().items(type.getSchema().optional()).sparse(false);
if (options.minSize !== undefined) {
schema = schema.min(options.minSize);
diff --git a/packages/kbn-config-schema/src/types/string_type.ts b/packages/kbn-config-schema/src/types/string_type.ts
index 7f49440b8d7e2..cb780bcbbc6bd 100644
--- a/packages/kbn-config-schema/src/types/string_type.ts
+++ b/packages/kbn-config-schema/src/types/string_type.ts
@@ -36,14 +36,14 @@ export class StringType extends Type {
let schema =
options.hostname === true
? internals.string().hostname()
- : internals.any().custom(value => {
+ : internals.any().custom((value) => {
if (typeof value !== 'string') {
return `expected value of type [string] but got [${typeDetect(value)}]`;
}
});
if (options.minLength !== undefined) {
- schema = schema.custom(value => {
+ schema = schema.custom((value) => {
if (value.length < options.minLength!) {
return `value has length [${value.length}] but it must have a minimum length of [${options.minLength}].`;
}
@@ -51,7 +51,7 @@ export class StringType extends Type {
}
if (options.maxLength !== undefined) {
- schema = schema.custom(value => {
+ schema = schema.custom((value) => {
if (value.length > options.maxLength!) {
return `value has length [${value.length}] but it must have a maximum length of [${options.maxLength}].`;
}
diff --git a/packages/kbn-config-schema/src/types/union_type.ts b/packages/kbn-config-schema/src/types/union_type.ts
index f4de829204e80..80fa8443e75d0 100644
--- a/packages/kbn-config-schema/src/types/union_type.ts
+++ b/packages/kbn-config-schema/src/types/union_type.ts
@@ -24,7 +24,7 @@ import { Type, TypeOptions } from './type';
export class UnionType>, T> extends Type {
constructor(types: RTS, options?: TypeOptions) {
- const schema = internals.alternatives(types.map(type => type.getSchema()));
+ const schema = internals.alternatives(types.map((type) => type.getSchema()));
super(schema, options);
}
diff --git a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts
index 4e91289610432..b38a27fdc1b48 100644
--- a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts
+++ b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts
@@ -145,7 +145,7 @@ export class CiStatsReporter {
`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds`
);
- await new Promise(resolve => setTimeout(resolve, attempt * 1000));
+ await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
}
}
}
diff --git a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts
index 4244006f4a3a3..ea4159de55749 100644
--- a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts
+++ b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts
@@ -66,7 +66,7 @@ export interface ReqOptions {
}
const delay = (ms: number) =>
- new Promise(resolve => {
+ new Promise((resolve) => {
setTimeout(resolve, ms);
});
diff --git a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts
index 1a292aff303af..4951bef91c446 100644
--- a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts
+++ b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts
@@ -33,7 +33,7 @@ export function observeReadable(readable: Readable): Rx.Observable {
Rx.fromEvent(readable, 'error').pipe(
first(),
- mergeMap(err => Rx.throwError(err))
+ mergeMap((err) => Rx.throwError(err))
)
);
}
diff --git a/packages/kbn-dev-utils/src/proc_runner/proc.ts b/packages/kbn-dev-utils/src/proc_runner/proc.ts
index c899293191f2a..59512cbb133b3 100644
--- a/packages/kbn-dev-utils/src/proc_runner/proc.ts
+++ b/packages/kbn-dev-utils/src/proc_runner/proc.ts
@@ -118,7 +118,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) {
// observe first error event
Rx.fromEvent(childProcess, 'error').pipe(
take(1),
- mergeMap(err => Rx.throwError(err))
+ mergeMap((err) => Rx.throwError(err))
)
).pipe(share());
@@ -126,7 +126,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) {
observeLines(childProcess.stdout),
observeLines(childProcess.stderr)
).pipe(
- tap(line => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)),
+ tap((line) => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)),
share()
);
diff --git a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts
index 1759ca2840c5b..c879b4595b451 100644
--- a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts
+++ b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts
@@ -50,7 +50,7 @@ export class ProcRunner {
constructor(private log: ToolingLog) {
this.signalUnsubscribe = exitHook(() => {
- this.teardown().catch(error => {
+ this.teardown().catch((error) => {
log.error(`ProcRunner teardown error: ${error.stack}`);
});
});
@@ -105,9 +105,9 @@ export class ProcRunner {
// wait for process to log matching line
await Rx.race(
proc.lines$.pipe(
- filter(line => wait.test(line)),
+ filter((line) => wait.test(line)),
first(),
- catchError(err => {
+ catchError((err) => {
if (err.name !== 'EmptyError') {
throw createCliError(`[${name}] exited without matching pattern: ${wait}`);
} else {
@@ -159,7 +159,7 @@ export class ProcRunner {
* @return {Promise}
*/
async waitForAllToStop() {
- await Promise.all(this.procs.map(proc => proc.outcomePromise));
+ await Promise.all(this.procs.map((proc) => proc.outcomePromise));
}
/**
@@ -181,19 +181,19 @@ export class ProcRunner {
this.log.warning(
'%d processes left running, stop them with procs.stop(name):',
this.procs.length,
- this.procs.map(proc => proc.name)
+ this.procs.map((proc) => proc.name)
);
}
await Promise.all(
- this.procs.map(async proc => {
+ this.procs.map(async (proc) => {
await proc.stop(signal === 'exit' ? 'SIGKILL' : signal);
})
);
}
private getProc(name: string) {
- return this.procs.find(proc => {
+ return this.procs.find((proc) => {
return proc.name === name;
});
}
@@ -209,14 +209,14 @@ export class ProcRunner {
// tie into proc outcome$, remove from _procs on compete
proc.outcome$.subscribe({
- next: code => {
+ next: (code) => {
const duration = moment.duration(Date.now() - startMs);
this.log.info('[%s] exited with %s after %s', name, code, duration.humanize());
},
complete: () => {
remove();
},
- error: error => {
+ error: (error) => {
if (this.closing) {
this.log.error(error);
}
diff --git a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts
index e37bdcc40ca1c..89127069f4b8d 100644
--- a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts
+++ b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts
@@ -22,14 +22,14 @@ import { withProcRunner } from './with_proc_runner';
import { ProcRunner } from './proc_runner';
it('passes proc runner to a function', async () => {
- await withProcRunner(new ToolingLog(), async proc => {
+ await withProcRunner(new ToolingLog(), async (proc) => {
expect(proc).toBeInstanceOf(ProcRunner);
});
});
it('calls procRunner.teardown() if function returns synchronously', async () => {
let teardownSpy;
- await withProcRunner(new ToolingLog(), async proc => {
+ await withProcRunner(new ToolingLog(), async (proc) => {
teardownSpy = jest.spyOn(proc, 'teardown');
});
@@ -41,7 +41,7 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects
let teardownSpy;
await expect(
- withProcRunner(new ToolingLog(), async proc => {
+ withProcRunner(new ToolingLog(), async (proc) => {
teardownSpy = jest.spyOn(proc, 'teardown');
throw error;
})
@@ -53,8 +53,8 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects
it('waits for promise to resolve before tearing down proc', async () => {
let teardownSpy;
- await withProcRunner(new ToolingLog(), async proc => {
- await new Promise(resolve => setTimeout(resolve, 500));
+ await withProcRunner(new ToolingLog(), async (proc) => {
+ await new Promise((resolve) => setTimeout(resolve, 500));
teardownSpy = jest.spyOn(proc, 'teardown');
});
@@ -67,8 +67,8 @@ it('waits for promise to reject before tearing down proc and rejecting with the
let teardownSpy;
await expect(
- withProcRunner(new ToolingLog(), async proc => {
- await new Promise(resolve => setTimeout(resolve, 500));
+ withProcRunner(new ToolingLog(), async (proc) => {
+ await new Promise((resolve) => setTimeout(resolve, 500));
teardownSpy = jest.spyOn(proc, 'teardown');
throw error;
})
diff --git a/packages/kbn-dev-utils/src/run/fail.ts b/packages/kbn-dev-utils/src/run/fail.ts
index a2501fc9513bf..f10ef1d52ef04 100644
--- a/packages/kbn-dev-utils/src/run/fail.ts
+++ b/packages/kbn-dev-utils/src/run/fail.ts
@@ -61,7 +61,7 @@ export function combineErrors(errors: Array) {
.filter(isFailError)
.reduce((acc, error) => Math.max(acc, error.exitCode), 1);
- const showHelp = errors.some(error => isFailError(error) && error.showHelp);
+ const showHelp = errors.some((error) => isFailError(error) && error.showHelp);
const message = errors.reduce((acc, error) => {
if (isFailError(error)) {
diff --git a/packages/kbn-dev-utils/src/run/run.ts b/packages/kbn-dev-utils/src/run/run.ts
index 35477e988d837..894db0d3fdadb 100644
--- a/packages/kbn-dev-utils/src/run/run.ts
+++ b/packages/kbn-dev-utils/src/run/run.ts
@@ -62,7 +62,7 @@ export async function run(fn: RunFn, options: Options = {}) {
writeTo: process.stdout,
});
- process.on('unhandledRejection', error => {
+ process.on('unhandledRejection', (error) => {
log.error('UNHANDLED PROMISE REJECTION');
log.error(
error instanceof Error
@@ -110,7 +110,7 @@ export async function run(fn: RunFn, options: Options = {}) {
}
try {
- await withProcRunner(log, async procRunner => {
+ await withProcRunner(log, async (procRunner) => {
await fn({
log,
flags,
diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts
index 21f02325cac66..4a0f5ca5f8a5f 100644
--- a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts
+++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts
@@ -80,29 +80,31 @@ describe('#indent()', () => {
});
});
-(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(method => {
- describe(`#${method}()`, () => {
- it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => {
- const log = new ToolingLog();
- const writeA = jest.fn();
- const writeB = jest.fn();
-
- log.setWriters([{ write: writeA }, { write: writeB }]);
-
- if (method === 'error') {
- const error = new Error('error message');
- error.stack = '... stack trace ...';
- log.error(error);
- log.error('string message');
- } else {
- log[method]('foo', 'bar', 'baz');
- }
-
- expect(writeA.mock.calls).toMatchSnapshot();
- expect(writeA.mock.calls).toEqual(writeB.mock.calls);
+(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(
+ (method) => {
+ describe(`#${method}()`, () => {
+ it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => {
+ const log = new ToolingLog();
+ const writeA = jest.fn();
+ const writeB = jest.fn();
+
+ log.setWriters([{ write: writeA }, { write: writeB }]);
+
+ if (method === 'error') {
+ const error = new Error('error message');
+ error.stack = '... stack trace ...';
+ log.error(error);
+ log.error('string message');
+ } else {
+ log[method]('foo', 'bar', 'baz');
+ }
+
+ expect(writeA.mock.calls).toMatchSnapshot();
+ expect(writeA.mock.calls).toEqual(writeB.mock.calls);
+ });
});
- });
-});
+ }
+);
describe('#getWritten$()', () => {
async function testWrittenMsgs(writers: Writer[]) {
@@ -110,10 +112,7 @@ describe('#getWritten$()', () => {
log.setWriters(writers);
const done$ = new Rx.Subject();
- const promise = log
- .getWritten$()
- .pipe(takeUntil(done$), toArray())
- .toPromise();
+ const promise = log.getWritten$().pipe(takeUntil(done$), toArray()).toPromise();
log.debug('foo');
log.info('bar');
diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts
index 46026bdc369d4..7e79077032156 100644
--- a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts
+++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts
@@ -26,7 +26,7 @@ export class ToolingLogCollectingWriter extends ToolingLogTextWriter {
super({
level: 'verbose',
writeTo: {
- write: msg => {
+ write: (msg) => {
// trim trailing new line
this.messages.push(msg.slice(0, -1));
},
diff --git a/packages/kbn-es/src/artifact.js b/packages/kbn-es/src/artifact.js
index 83dcd1cf36d2e..7d4c7a3fd2c33 100644
--- a/packages/kbn-es/src/artifact.js
+++ b/packages/kbn-es/src/artifact.js
@@ -60,7 +60,7 @@ async function retry(log, fn) {
}
log.warning('...failure, retrying in 5 seconds:', error.message);
- await new Promise(resolve => setTimeout(resolve, 5000));
+ await new Promise((resolve) => setTimeout(resolve, 5000));
log.info('...retrying');
return await doAttempt(attempt + 1);
}
@@ -120,7 +120,7 @@ async function getArtifactSpecForSnapshot(urlVersion, license, log) {
const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
const archive = manifest.archives.find(
- archive =>
+ (archive) =>
archive.version === desiredVersion &&
archive.platform === platform &&
archive.license === desiredLicense &&
diff --git a/packages/kbn-es/src/artifact.test.js b/packages/kbn-es/src/artifact.test.js
index 02e4d5318f63f..bbcf664006046 100644
--- a/packages/kbn-es/src/artifact.test.js
+++ b/packages/kbn-es/src/artifact.test.js
@@ -52,14 +52,14 @@ const createArchive = (params = {}) => {
};
};
-const mockFetch = mock =>
+const mockFetch = (mock) =>
fetch.mockReturnValue(Promise.resolve(new Response(JSON.stringify(mock))));
const previousEnvVars = {};
const ENV_VARS_TO_RESET = ['ES_SNAPSHOT_MANIFEST', 'KBN_ES_SNAPSHOT_USE_UNVERIFIED'];
beforeAll(() => {
- ENV_VARS_TO_RESET.forEach(key => {
+ ENV_VARS_TO_RESET.forEach((key) => {
if (key in process.env) {
previousEnvVars[key] = process.env[key];
delete process.env[key];
@@ -68,7 +68,7 @@ beforeAll(() => {
});
afterAll(() => {
- Object.keys(previousEnvVars).forEach(key => {
+ Object.keys(previousEnvVars).forEach((key) => {
process.env[key] = previousEnvVars[key];
});
});
diff --git a/packages/kbn-es/src/cli.js b/packages/kbn-es/src/cli.js
index ed81e01ccf8ab..61019d27bf383 100644
--- a/packages/kbn-es/src/cli.js
+++ b/packages/kbn-es/src/cli.js
@@ -26,7 +26,7 @@ const { log } = require('./utils');
function help() {
const availableCommands = Object.keys(commands).map(
- name => `${name} - ${commands[name].description}`
+ (name) => `${name} - ${commands[name].description}`
);
console.log(dedent`
diff --git a/packages/kbn-es/src/cluster.js b/packages/kbn-es/src/cluster.js
index ceb4a5b6aece1..68bcc37c65600 100644
--- a/packages/kbn-es/src/cluster.js
+++ b/packages/kbn-es/src/cluster.js
@@ -40,8 +40,8 @@ const readFile = util.promisify(fs.readFile);
// listen to data on stream until map returns anything but undefined
const first = (stream, map) =>
- new Promise(resolve => {
- const onData = data => {
+ new Promise((resolve) => {
+ const onData = (data) => {
const result = map(data);
if (result !== undefined) {
resolve(result);
@@ -180,7 +180,7 @@ exports.Cluster = class Cluster {
await Promise.race([
// wait for native realm to be setup and es to be started
Promise.all([
- first(this._process.stdout, data => {
+ first(this._process.stdout, (data) => {
if (/started/.test(data)) {
return true;
}
@@ -207,7 +207,7 @@ exports.Cluster = class Cluster {
this._exec(installPath, options);
// log native realm setup errors so they aren't uncaught
- this._nativeRealmSetup.catch(error => {
+ this._nativeRealmSetup.catch((error) => {
this._log.error(error);
this.stop();
});
@@ -287,7 +287,7 @@ exports.Cluster = class Cluster {
});
// parse log output to find http port
- const httpPort = first(this._process.stdout, data => {
+ const httpPort = first(this._process.stdout, (data) => {
const match = data.toString('utf8').match(/HttpServer.+publish_address {[0-9.]+:([0-9]+)/);
if (match) {
@@ -296,7 +296,7 @@ exports.Cluster = class Cluster {
});
// once the http port is available setup the native realm
- this._nativeRealmSetup = httpPort.then(async port => {
+ this._nativeRealmSetup = httpPort.then(async (port) => {
const caCert = await this._caCertPromise;
const nativeRealm = new NativeRealm({
port,
@@ -309,19 +309,19 @@ exports.Cluster = class Cluster {
});
// parse and forward es stdout to the log
- this._process.stdout.on('data', data => {
+ this._process.stdout.on('data', (data) => {
const lines = parseEsLog(data.toString());
- lines.forEach(line => {
+ lines.forEach((line) => {
this._log.info(line.formattedMessage);
});
});
// forward es stderr to the log
- this._process.stderr.on('data', data => this._log.error(chalk.red(data.toString())));
+ this._process.stderr.on('data', (data) => this._log.error(chalk.red(data.toString())));
// observe the exit code of the process and reflect in _outcome promies
- const exitCode = new Promise(resolve => this._process.once('exit', resolve));
- this._outcome = exitCode.then(code => {
+ const exitCode = new Promise((resolve) => this._process.once('exit', resolve));
+ this._outcome = exitCode.then((code) => {
if (this._stopCalled) {
return;
}
diff --git a/packages/kbn-es/src/errors.js b/packages/kbn-es/src/errors.js
index 099b5214bcbdb..7b39251f1327c 100644
--- a/packages/kbn-es/src/errors.js
+++ b/packages/kbn-es/src/errors.js
@@ -17,12 +17,12 @@
* under the License.
*/
-exports.createCliError = function(message) {
+exports.createCliError = function (message) {
const error = new Error(message);
error.isCliError = true;
return error;
};
-exports.isCliError = function(error) {
+exports.isCliError = function (error) {
return error && error.isCliError;
};
diff --git a/packages/kbn-es/src/install/source.js b/packages/kbn-es/src/install/source.js
index e78e9f1ff4b25..bfeff736f8cdc 100644
--- a/packages/kbn-es/src/install/source.js
+++ b/packages/kbn-es/src/install/source.js
@@ -99,15 +99,11 @@ async function sourceInfo(cwd, license, log = defaultLog) {
etag.update(sha);
// for changed files, use last modified times in hash calculation
- status.files.forEach(file => {
+ status.files.forEach((file) => {
etag.update(fs.statSync(path.join(cwd, file.path)).mtime.toString());
});
- const cwdHash = crypto
- .createHash('md5')
- .update(cwd)
- .digest('hex')
- .substr(0, 8);
+ const cwdHash = crypto.createHash('md5').update(cwd).digest('hex').substr(0, 8);
const basename = `${branch}-${task}-${cwdHash}`;
const filename = `${basename}.${ext}`;
diff --git a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js
index d374abe5db068..b860664443d1a 100644
--- a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js
+++ b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js
@@ -71,7 +71,7 @@ const delayServerClose = () => {
server.on('request', delayServerClose);
server.on('listening', delayServerClose);
-server.listen(0, '127.0.0.1', function() {
+server.listen(0, '127.0.0.1', function () {
const { port, address: hostname } = server.address();
serverUrl = new URL(
formatUrl({
diff --git a/packages/kbn-es/src/integration_tests/cluster.test.js b/packages/kbn-es/src/integration_tests/cluster.test.js
index dfbc04477bd40..0ae0ac0aac27a 100644
--- a/packages/kbn-es/src/integration_tests/cluster.test.js
+++ b/packages/kbn-es/src/integration_tests/cluster.test.js
@@ -37,7 +37,7 @@ jest.mock('../utils/extract_config_files', () => ({
const log = new ToolingLog();
function sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
+ return new Promise((resolve) => setTimeout(resolve, ms));
}
async function ensureNoResolve(promise) {
@@ -77,7 +77,7 @@ function mockEsBin({ exitCode, start }) {
beforeEach(() => {
jest.resetAllMocks();
- extractConfigFiles.mockImplementation(config => config);
+ extractConfigFiles.mockImplementation((config) => config);
});
describe('#installSource()', () => {
@@ -85,7 +85,7 @@ describe('#installSource()', () => {
let resolveInstallSource;
installSource.mockImplementationOnce(
() =>
- new Promise(resolve => {
+ new Promise((resolve) => {
resolveInstallSource = () => {
resolve({ installPath: 'foo' });
};
@@ -124,7 +124,7 @@ describe('#installSnapshot()', () => {
let resolveInstallSnapshot;
installSnapshot.mockImplementationOnce(
() =>
- new Promise(resolve => {
+ new Promise((resolve) => {
resolveInstallSnapshot = () => {
resolve({ installPath: 'foo' });
};
@@ -163,7 +163,7 @@ describe('#installArchive(path)', () => {
let resolveInstallArchive;
installArchive.mockImplementationOnce(
() =>
- new Promise(resolve => {
+ new Promise((resolve) => {
resolveInstallArchive = () => {
resolve({ installPath: 'foo' });
};
diff --git a/packages/kbn-es/src/settings.ts b/packages/kbn-es/src/settings.ts
index 58eedff207b4d..bf7160b9fee7b 100644
--- a/packages/kbn-es/src/settings.ts
+++ b/packages/kbn-es/src/settings.ts
@@ -25,7 +25,7 @@ const SECURE_SETTINGS_LIST = [
];
function isSecureSetting(settingName: string) {
- return SECURE_SETTINGS_LIST.some(secureSettingNameRegex =>
+ return SECURE_SETTINGS_LIST.some((secureSettingNameRegex) =>
secureSettingNameRegex.test(settingName)
);
}
diff --git a/packages/kbn-es/src/utils/build_snapshot.js b/packages/kbn-es/src/utils/build_snapshot.js
index 3173df700e303..ce0dc88ac1d7c 100644
--- a/packages/kbn-es/src/utils/build_snapshot.js
+++ b/packages/kbn-es/src/utils/build_snapshot.js
@@ -25,7 +25,7 @@ const { createCliError } = require('../errors');
const { findMostRecentlyChanged } = require('../utils');
const { GRADLE_BIN } = require('../paths');
-const onceEvent = (emitter, event) => new Promise(resolve => emitter.once(event, resolve));
+const onceEvent = (emitter, event) => new Promise((resolve) => emitter.once(event, resolve));
/**
* Creates archive from source
@@ -59,13 +59,13 @@ exports.buildSnapshot = async ({ license, sourcePath, log, platform = os.platfor
const stdout = readline.createInterface({ input: build.stdout });
const stderr = readline.createInterface({ input: build.stderr });
- stdout.on('line', line => log.debug(line));
- stderr.on('line', line => log.error(line));
+ stdout.on('line', (line) => log.debug(line));
+ stderr.on('line', (line) => log.error(line));
const [exitCode] = await Promise.all([
Promise.race([
onceEvent(build, 'exit'),
- onceEvent(build, 'error').then(error => {
+ onceEvent(build, 'error').then((error) => {
throw createCliError(`Error spawning gradle: ${error.message}`);
}),
]),
diff --git a/packages/kbn-es/src/utils/decompress.js b/packages/kbn-es/src/utils/decompress.js
index b4299594c5062..1fdb647b1dc0d 100644
--- a/packages/kbn-es/src/utils/decompress.js
+++ b/packages/kbn-es/src/utils/decompress.js
@@ -50,15 +50,12 @@ function decompressZip(input, output) {
resolve();
});
- zipfile.on('error', err => {
+ zipfile.on('error', (err) => {
reject(err);
});
- zipfile.on('entry', entry => {
- const zipPath = entry.fileName
- .split(/\/|\\/)
- .slice(1)
- .join(path.sep);
+ zipfile.on('entry', (entry) => {
+ const zipPath = entry.fileName.split(/\/|\\/).slice(1).join(path.sep);
const fileName = path.resolve(output, zipPath);
if (/\/$/.test(entry.fileName)) {
@@ -83,7 +80,7 @@ function decompressZip(input, output) {
});
}
-exports.decompress = async function(input, output) {
+exports.decompress = async function (input, output) {
const ext = path.extname(input);
switch (path.extname(input)) {
diff --git a/packages/kbn-es/src/utils/extract_config_files.js b/packages/kbn-es/src/utils/extract_config_files.js
index a8a44a149e9b3..d535528cef239 100644
--- a/packages/kbn-es/src/utils/extract_config_files.js
+++ b/packages/kbn-es/src/utils/extract_config_files.js
@@ -32,7 +32,7 @@ exports.extractConfigFiles = function extractConfigFiles(config, dest, options =
const originalConfig = typeof config === 'string' ? [config] : config;
const localConfig = [];
- originalConfig.forEach(prop => {
+ originalConfig.forEach((prop) => {
const [key, value] = prop.split('=');
if (isFile(value)) {
diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.js b/packages/kbn-es/src/utils/find_most_recently_changed.js
index 0fcd87978c357..3ba8865e88d92 100644
--- a/packages/kbn-es/src/utils/find_most_recently_changed.js
+++ b/packages/kbn-es/src/utils/find_most_recently_changed.js
@@ -32,7 +32,7 @@ exports.findMostRecentlyChanged = function findMostRecentlyChanged(pattern) {
throw new TypeError(`Pattern must be absolute, got ${pattern}`);
}
- const ctime = path => fs.statSync(path).ctime.getTime();
+ const ctime = (path) => fs.statSync(path).ctime.getTime();
return glob
.sync(pattern)
diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.test.js b/packages/kbn-es/src/utils/find_most_recently_changed.test.js
index ed90576990c72..ee032686bc621 100644
--- a/packages/kbn-es/src/utils/find_most_recently_changed.test.js
+++ b/packages/kbn-es/src/utils/find_most_recently_changed.test.js
@@ -18,7 +18,7 @@
*/
jest.mock('fs', () => ({
- statSync: jest.fn().mockImplementation(path => {
+ statSync: jest.fn().mockImplementation((path) => {
if (path.includes('oldest')) {
return {
ctime: new Date(2018, 2, 1),
diff --git a/packages/kbn-es/src/utils/native_realm.js b/packages/kbn-es/src/utils/native_realm.js
index f3f5f7bbdf431..573944a8cc6d0 100644
--- a/packages/kbn-es/src/utils/native_realm.js
+++ b/packages/kbn-es/src/utils/native_realm.js
@@ -77,7 +77,7 @@ exports.NativeRealm = class NativeRealm {
const reservedUsers = await this.getReservedUsers();
await Promise.all(
- reservedUsers.map(async user => {
+ reservedUsers.map(async (user) => {
await this.setPassword(user, options[`password.${user}`]);
})
);
@@ -87,7 +87,7 @@ exports.NativeRealm = class NativeRealm {
return await this._autoRetry(async () => {
const resp = await this._client.security.getUser();
const usernames = Object.keys(resp.body).filter(
- user => resp.body[user].metadata._reserved === true
+ (user) => resp.body[user].metadata._reserved === true
);
if (!usernames?.length) {
@@ -125,7 +125,7 @@ exports.NativeRealm = class NativeRealm {
const sec = 1.5 * attempt;
this._log.warning(`assuming ES isn't initialized completely, trying again in ${sec} seconds`);
- await new Promise(resolve => setTimeout(resolve, sec * 1000));
+ await new Promise((resolve) => setTimeout(resolve, sec * 1000));
return await this._autoRetry(fn, attempt + 1);
}
}
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js
index e26660f76a550..8472aaf0fc029 100644
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js
@@ -31,6 +31,6 @@
//
const PATH_IMPORT_RE = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/;
-exports.getIsPathRequest = function(source) {
+exports.getIsPathRequest = function (source) {
return PATH_IMPORT_RE.test(source);
};
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js
index 93c0f907d628d..3856281d15320 100755
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js
@@ -26,7 +26,7 @@ const DEFAULT_PLUGIN_PATH = '../..';
/*
* Resolves the path to Kibana, either from default setting or config
*/
-exports.getKibanaPath = function(config, projectRoot) {
+exports.getKibanaPath = function (config, projectRoot) {
const inConfig = config != null && config.kibanaPath;
// We only allow `.` in the config as we need it for Kibana itself
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js
index 3fb5b5dab7776..445a3cad385fc 100644
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js
@@ -49,10 +49,10 @@ function getPathType(path) {
return type;
}
-exports.isDirectory = function(path) {
+exports.isDirectory = function (path) {
return getPathType(path) === DIR;
};
-exports.isFile = function(path) {
+exports.isFile = function (path) {
return getPathType(path) === FILE;
};
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js
index 319b959883a8a..84481783b22fc 100755
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js
@@ -21,8 +21,8 @@ const { dirname, resolve } = require('path');
const glob = require('glob-all');
-exports.getPlugins = function(config, kibanaPath, projectRoot) {
- const resolveToRoot = path => resolve(projectRoot, path);
+exports.getPlugins = function (config, kibanaPath, projectRoot) {
+ const resolveToRoot = (path) => resolve(projectRoot, path);
const pluginDirs = [
...(config.pluginDirs || []).map(resolveToRoot),
@@ -39,11 +39,11 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) {
];
const globPatterns = [
- ...pluginDirs.map(dir => resolve(dir, '*/package.json')),
- ...pluginPaths.map(path => resolve(path, 'package.json')),
+ ...pluginDirs.map((dir) => resolve(dir, '*/package.json')),
+ ...pluginPaths.map((path) => resolve(path, 'package.json')),
];
- const pluginsFromMap = Object.keys(config.pluginMap || {}).map(name => {
+ const pluginsFromMap = Object.keys(config.pluginMap || {}).map((name) => {
const directory = resolveToRoot(config.pluginMap[name]);
return {
name,
@@ -53,7 +53,7 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) {
});
return pluginsFromMap.concat(
- glob.sync(globPatterns).map(pkgJsonPath => {
+ glob.sync(globPatterns).map((pkgJsonPath) => {
const path = dirname(pkgJsonPath);
const pkg = require(pkgJsonPath); // eslint-disable-line import/no-dynamic-require
return {
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js
index 5c70d63bf147b..fed40298d513f 100755
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js
@@ -55,7 +55,7 @@ function getRootPackageDir(dirRoot, dir, rootPackageName) {
}
}
-exports.getProjectRoot = function(file, config) {
+exports.getProjectRoot = function (file, config) {
const { root, dir } = parse(resolve(file));
const { rootPackageName } = config;
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js
index da0b799b338ed..6cb2f3d2901d3 100755
--- a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js
@@ -22,7 +22,7 @@ const { resolve } = require('path');
const { debug } = require('./debug');
const { getPlugins } = require('./get_plugins');
-exports.getWebpackConfig = function(kibanaPath, projectRoot, config) {
+exports.getWebpackConfig = function (kibanaPath, projectRoot, config) {
const fromKibana = (...path) => resolve(kibanaPath, ...path);
const alias = {
@@ -39,7 +39,7 @@ exports.getWebpackConfig = function(kibanaPath, projectRoot, config) {
test_utils: fromKibana('src/test_utils/public'),
};
- getPlugins(config, kibanaPath, projectRoot).forEach(plugin => {
+ getPlugins(config, kibanaPath, projectRoot).forEach((plugin) => {
alias[`plugins/${plugin.name}`] = plugin.publicDirectory;
});
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js
index 2af7d1c2f5349..9eb3234fca7b4 100644
--- a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js
@@ -32,8 +32,8 @@ function readShimNames(shimDirectory) {
}
return readdirSync(shimDirectory)
- .filter(name => !name.startsWith('.') && !name.startsWith('_'))
- .map(name => (name.endsWith('.js') ? name.slice(0, -3) : name));
+ .filter((name) => !name.startsWith('.') && !name.startsWith('_'))
+ .map((name) => (name.endsWith('.js') ? name.slice(0, -3) : name));
}
function findRelativeWebpackShims(directory) {
@@ -53,7 +53,7 @@ function findRelativeWebpackShims(directory) {
return allShims;
}
-exports.isProbablyWebpackShim = function(source, file) {
+exports.isProbablyWebpackShim = function (source, file) {
const shims = findRelativeWebpackShims(dirname(file));
- return shims.some(shim => source === shim || source.startsWith(shim + '/'));
+ return shims.some((shim) => source === shim || source.startsWith(shim + '/'));
};
diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js
index a7bb391f9b1c6..00b07f469bd9c 100644
--- a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js
+++ b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js
@@ -25,7 +25,7 @@
* @param {Array<[alias,path]>} aliasEntries
* @return {string|undefined}
*/
-exports.resolveWebpackAlias = function(source, aliasEntries) {
+exports.resolveWebpackAlias = function (source, aliasEntries) {
for (const [alias, path] of aliasEntries) {
if (source === alias) {
return path;
diff --git a/packages/kbn-eslint-plugin-eslint/lib.js b/packages/kbn-eslint-plugin-eslint/lib.js
index 56684746c479f..a7431be00e054 100644
--- a/packages/kbn-eslint-plugin-eslint/lib.js
+++ b/packages/kbn-eslint-plugin-eslint/lib.js
@@ -31,7 +31,7 @@ exports.normalizeWhitespace = function normalizeWhitespace(string) {
return string.replace(/\s+/g, ' ');
};
-exports.init = function(context, program, initStep) {
+exports.init = function (context, program, initStep) {
try {
return initStep();
} catch (error) {
diff --git a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js
index 0567307d18968..6b5564f1f8004 100644
--- a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js
+++ b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js
@@ -39,7 +39,7 @@ module.exports = {
},
],
},
- create: context => {
+ create: (context) => {
return {
Program(program) {
const licenses = init(context, program, () => {
@@ -70,8 +70,8 @@ module.exports = {
sourceCode
.getAllComments()
- .filter(node => licenses.includes(normalizeWhitespace(node.value)))
- .forEach(node => {
+ .filter((node) => licenses.includes(normalizeWhitespace(node.value)))
+ .forEach((node) => {
context.report({
node,
message: 'This license header is not allowed in this file.',
diff --git a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js
index 8119d338ee536..6027a939f1a65 100644
--- a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js
+++ b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js
@@ -22,7 +22,7 @@ const KIBANA_ROOT = path.resolve(__dirname, '../../..');
function checkModuleNameNode(context, mappings, node) {
const mapping = mappings.find(
- mapping => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`)
+ (mapping) => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`)
);
if (!mapping) {
@@ -105,7 +105,7 @@ module.exports = {
},
],
},
- create: context => {
+ create: (context) => {
const mappings = context.options[0];
return {
diff --git a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js
index f3c9fcef1985e..915ac3ed7922e 100644
--- a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js
+++ b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js
@@ -40,10 +40,10 @@ module.exports = {
},
],
},
- create: context => {
+ create: (context) => {
return {
Program(program) {
- const license = init(context, program, function() {
+ const license = init(context, program, function () {
const options = context.options[0] || {};
const license = options.license;
@@ -69,7 +69,7 @@ module.exports = {
const sourceCode = context.getSourceCode();
const comment = sourceCode
.getAllComments()
- .find(node => normalizeWhitespace(node.value) === license.nodeValue);
+ .find((node) => normalizeWhitespace(node.value) === license.nodeValue);
// no licence comment
if (!comment) {
diff --git a/packages/kbn-i18n/scripts/build.js b/packages/kbn-i18n/scripts/build.js
index 0764451c74575..62e1a35f00399 100644
--- a/packages/kbn-i18n/scripts/build.js
+++ b/packages/kbn-i18n/scripts/build.js
@@ -31,7 +31,7 @@ const padRight = (width, str) =>
run(
async ({ log, flags }) => {
- await withProcRunner(log, async proc => {
+ await withProcRunner(log, async (proc) => {
log.info('Deleting old output');
await del(BUILD_DIR);
@@ -43,7 +43,7 @@ run(
log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`);
await Promise.all([
- ...['web', 'node'].map(subTask =>
+ ...['web', 'node'].map((subTask) =>
proc.run(padRight(10, `babel:${subTask}`), {
cmd: 'babel',
args: [
diff --git a/packages/kbn-i18n/src/angular/filter.test.ts b/packages/kbn-i18n/src/angular/filter.test.ts
index 78bc279689357..5336926a64139 100644
--- a/packages/kbn-i18n/src/angular/filter.test.ts
+++ b/packages/kbn-i18n/src/angular/filter.test.ts
@@ -28,17 +28,14 @@ import * as i18n from '../core/i18n';
import { i18nFilter as angularI18nFilter } from './filter';
import { I18nProvider, I18nServiceType } from './provider';
-angular
- .module('app', [])
- .provider('i18n', I18nProvider)
- .filter('i18n', angularI18nFilter);
+angular.module('app', []).provider('i18n', I18nProvider).filter('i18n', angularI18nFilter);
describe('i18nFilter', () => {
let filter: I18nServiceType;
beforeEach(angular.mock.module('app'));
beforeEach(
- angular.mock.inject(i18nFilter => {
+ angular.mock.inject((i18nFilter) => {
filter = i18nFilter;
})
);
diff --git a/packages/kbn-i18n/src/loader.ts b/packages/kbn-i18n/src/loader.ts
index 21f540f588f46..8231ed36928d8 100644
--- a/packages/kbn-i18n/src/loader.ts
+++ b/packages/kbn-i18n/src/loader.ts
@@ -127,7 +127,7 @@ export function getRegisteredLocales() {
*/
export async function getTranslationsByLocale(locale: string): Promise {
const files = translationsRegistry[locale] || [];
- const notLoadedFiles = files.filter(file => !loadedFiles[file]);
+ const notLoadedFiles = files.filter((file) => !loadedFiles[file]);
if (notLoadedFiles.length) {
await loadAndCacheFiles(notLoadedFiles);
diff --git a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx
index db879fbae6ff1..3271ae7c98d2f 100644
--- a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx
+++ b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx
@@ -37,7 +37,7 @@ function translateFormattedMessageUsingPseudoLocale(message: string) {
if (formattedMessageDelimiter !== null) {
return message
.split(formattedMessageDelimiter[0])
- .map(part => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part)))
+ .map((part) => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part)))
.join(formattedMessageDelimiter[0]);
}
diff --git a/packages/kbn-interpreter/src/common/lib/arg.js b/packages/kbn-interpreter/src/common/lib/arg.js
index 0aa2b52e35acb..2ab74e5035866 100644
--- a/packages/kbn-interpreter/src/common/lib/arg.js
+++ b/packages/kbn-interpreter/src/common/lib/arg.js
@@ -30,7 +30,7 @@ export function Arg(config) {
this.multi = config.multi == null ? false : config.multi;
this.resolve = config.resolve == null ? true : config.resolve;
this.options = config.options || [];
- this.accepts = type => {
+ this.accepts = (type) => {
if (!this.types.length) return true;
return includes(config.types, type);
};
diff --git a/packages/kbn-interpreter/src/common/lib/ast.js b/packages/kbn-interpreter/src/common/lib/ast.js
index 61cfe94ac955c..98123f475cd92 100644
--- a/packages/kbn-interpreter/src/common/lib/ast.js
+++ b/packages/kbn-interpreter/src/common/lib/ast.js
@@ -55,7 +55,7 @@ function getExpressionArgs(block, level = 0) {
const argKeys = Object.keys(args);
const MAX_LINE_LENGTH = 80; // length before wrapping arguments
- return argKeys.map(argKey =>
+ return argKeys.map((argKey) =>
args[argKey].reduce((acc, arg) => {
const argString = getArgumentString(arg, argKey, level);
const lineLength = acc.split('\n').pop().length;
@@ -86,7 +86,7 @@ function getExpression(chain, level = 0) {
const separator = level > 0 ? ' | ' : '\n| ';
return chain
- .map(chainObj => {
+ .map((chainObj) => {
const type = getType(chainObj);
if (type === 'function') {
diff --git a/packages/kbn-interpreter/src/common/lib/fn.js b/packages/kbn-interpreter/src/common/lib/fn.js
index c6b2fcbe67799..5561c08f9c7d0 100644
--- a/packages/kbn-interpreter/src/common/lib/fn.js
+++ b/packages/kbn-interpreter/src/common/lib/fn.js
@@ -39,7 +39,7 @@ export function Fn(config) {
this.context = config.context || {};
- this.accepts = type => {
+ this.accepts = (type) => {
if (!this.context.types) return true; // If you don't tell us about context, we'll assume you don't care what you get
return includes(this.context.types, type); // Otherwise, check it
};
diff --git a/packages/kbn-interpreter/src/common/lib/get_by_alias.js b/packages/kbn-interpreter/src/common/lib/get_by_alias.js
index d7bb1bbf9e79d..04c435216b946 100644
--- a/packages/kbn-interpreter/src/common/lib/get_by_alias.js
+++ b/packages/kbn-interpreter/src/common/lib/get_by_alias.js
@@ -26,7 +26,7 @@ export function getByAlias(specs, name) {
const lowerCaseName = name.toLowerCase();
return Object.values(specs).find(({ name, aliases }) => {
if (name.toLowerCase() === lowerCaseName) return true;
- return (aliases || []).some(alias => {
+ return (aliases || []).some((alias) => {
return alias.toLowerCase() === lowerCaseName;
});
});
diff --git a/packages/kbn-interpreter/src/common/lib/registry.js b/packages/kbn-interpreter/src/common/lib/registry.js
index 3b22704b9e9c8..25b122f400711 100644
--- a/packages/kbn-interpreter/src/common/lib/registry.js
+++ b/packages/kbn-interpreter/src/common/lib/registry.js
@@ -48,7 +48,7 @@ export class Registry {
}
toArray() {
- return Object.keys(this._indexed).map(key => this.get(key));
+ return Object.keys(this._indexed).map((key) => this.get(key));
}
get(name) {
diff --git a/packages/kbn-interpreter/src/common/registries.js b/packages/kbn-interpreter/src/common/registries.js
index 2c68f5647ca73..9d73433bb2d26 100644
--- a/packages/kbn-interpreter/src/common/registries.js
+++ b/packages/kbn-interpreter/src/common/registries.js
@@ -24,7 +24,7 @@
* @param {*} newRegistries - The new set of registries
*/
export function addRegistries(registries, newRegistries) {
- Object.keys(newRegistries).forEach(registryName => {
+ Object.keys(newRegistries).forEach((registryName) => {
if (registries[registryName]) {
throw new Error(`There is already a registry named "${registryName}".`);
}
@@ -41,7 +41,7 @@ export function addRegistries(registries, newRegistries) {
* @param {*} specs - The specs to be regsitered (e.g. { types: [], browserFunctions: [] })
*/
export function register(registries, specs) {
- Object.keys(specs).forEach(registryName => {
+ Object.keys(specs).forEach((registryName) => {
if (!registries[registryName]) {
throw new Error(`There is no registry named "${registryName}".`);
}
@@ -49,7 +49,7 @@ export function register(registries, specs) {
if (!registries[registryName].register) {
throw new Error(`Registry "${registryName}" must have a register function.`);
}
- specs[registryName].forEach(f => registries[registryName].register(f));
+ specs[registryName].forEach((f) => registries[registryName].register(f));
});
return registries;
diff --git a/packages/kbn-interpreter/tasks/build/cli.js b/packages/kbn-interpreter/tasks/build/cli.js
index 86df21ee566ac..970e0f8847882 100644
--- a/packages/kbn-interpreter/tasks/build/cli.js
+++ b/packages/kbn-interpreter/tasks/build/cli.js
@@ -56,7 +56,7 @@ if (flags.help) {
process.exit();
}
-withProcRunner(log, async proc => {
+withProcRunner(log, async (proc) => {
log.info('Deleting old output');
await del(BUILD_DIR);
@@ -87,7 +87,7 @@ withProcRunner(log, async proc => {
]);
log.success('Complete');
-}).catch(error => {
+}).catch((error) => {
log.error(error);
process.exit(1);
});
diff --git a/packages/kbn-optimizer/src/cli.ts b/packages/kbn-optimizer/src/cli.ts
index a2fbe969e34d8..0916f12a7110d 100644
--- a/packages/kbn-optimizer/src/cli.ts
+++ b/packages/kbn-optimizer/src/cli.ts
@@ -77,8 +77,8 @@ run(
const extraPluginScanDirs = ([] as string[])
.concat((flags['scan-dir'] as string | string[]) || [])
- .map(p => Path.resolve(p));
- if (!extraPluginScanDirs.every(s => typeof s === 'string')) {
+ .map((p) => Path.resolve(p));
+ if (!extraPluginScanDirs.every((s) => typeof s === 'string')) {
throw createFlagError('expected --scan-dir to be a string');
}
diff --git a/packages/kbn-optimizer/src/common/array_helpers.test.ts b/packages/kbn-optimizer/src/common/array_helpers.test.ts
index 9d45217486ee8..ab5f4b694333e 100644
--- a/packages/kbn-optimizer/src/common/array_helpers.test.ts
+++ b/packages/kbn-optimizer/src/common/array_helpers.test.ts
@@ -53,11 +53,7 @@ describe('ascending/descending', () => {
].sort(() => 0.5 - Math.random());
it('sorts items using getters', () => {
- expect(
- Array.from(values)
- .sort(ascending(a, b, c))
- .map(print)
- ).toMatchInlineSnapshot(`
+ expect(Array.from(values).sort(ascending(a, b, c)).map(print)).toMatchInlineSnapshot(`
Array [
"1/2/3",
"3/2/1",
@@ -81,11 +77,7 @@ describe('ascending/descending', () => {
]
`);
- expect(
- Array.from(values)
- .sort(descending(a, b, c))
- .map(print)
- ).toMatchInlineSnapshot(`
+ expect(Array.from(values).sort(descending(a, b, c)).map(print)).toMatchInlineSnapshot(`
Array [
"9/9/9",
"8/foo/8",
diff --git a/packages/kbn-optimizer/src/common/bundle.ts b/packages/kbn-optimizer/src/common/bundle.ts
index 7581b90d60af2..9e2ad186ba40c 100644
--- a/packages/kbn-optimizer/src/common/bundle.ts
+++ b/packages/kbn-optimizer/src/common/bundle.ts
@@ -80,7 +80,7 @@ export class Bundle {
return {
spec: this.toSpec(),
mtimes: entriesToObject(
- files.map(p => [p, mtimes.get(p)] as const).sort(ascending(e => e[0]))
+ files.map((p) => [p, mtimes.get(p)] as const).sort(ascending((e) => e[0]))
),
};
}
diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts
index ba19bdc9c3be7..aba4451622dcd 100644
--- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts
+++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts
@@ -130,7 +130,7 @@ export const checks: DisallowedSyntaxCheck[] = [
{
name: '[es2018] object spread properties',
nodeType: 'ObjectExpression',
- test: (n: estree.ObjectExpression) => n.properties.some(p => p.type === 'SpreadElement'),
+ test: (n: estree.ObjectExpression) => n.properties.some((p) => p.type === 'SpreadElement'),
},
// https://github.com/estree/estree/blob/master/es2018.md#template-literals
{
@@ -142,7 +142,7 @@ export const checks: DisallowedSyntaxCheck[] = [
{
name: '[es2018] rest properties',
nodeType: 'ObjectPattern',
- test: (n: estree.ObjectPattern) => n.properties.some(p => p.type === 'RestElement'),
+ test: (n: estree.ObjectPattern) => n.properties.some((p) => p.type === 'RestElement'),
},
/**
diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts
index 7377462eb267b..8fb7559f3e22f 100644
--- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts
+++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts
@@ -26,8 +26,8 @@ import { parseFilePath } from '../parse_path';
export class DisallowedSyntaxPlugin {
apply(compiler: webpack.Compiler) {
- compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, factory => {
- factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, parser => {
+ compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, (factory) => {
+ factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, (parser) => {
parser.hooks.program.tap(DisallowedSyntaxPlugin.name, (program: acorn.Node) => {
const module = parser.state?.current;
if (!module || !module.resource) {
@@ -43,7 +43,7 @@ export class DisallowedSyntaxPlugin {
const failedChecks = new Set();
- AcornWalk.full(program, node => {
+ AcornWalk.full(program, (node) => {
const checks = checksByNodeType.get(node.type as any);
if (!checks) {
return;
@@ -63,7 +63,7 @@ export class DisallowedSyntaxPlugin {
// throw an error to trigger a parse failure, causing this module to be reported as invalid
throw new Error(
`disallowed syntax found in file ${resource}:\n - ${Array.from(failedChecks)
- .map(c => c.name)
+ .map((c) => c.name)
.join('\n - ')}`
);
});
diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts
index f6f6841532799..7458fa13eccb3 100644
--- a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts
+++ b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts
@@ -233,6 +233,6 @@ it('stops an infinite stream when unsubscribed', async () => {
// ensure summarizer still only called 10 times after a timeout
expect(summarize).toHaveBeenCalledTimes(10);
- await new Promise(resolve => setTimeout(resolve, 1000));
+ await new Promise((resolve) => setTimeout(resolve, 1000));
expect(summarize).toHaveBeenCalledTimes(10);
});
diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.ts
index d07af32f88897..d93cba5653abd 100644
--- a/packages/kbn-optimizer/src/common/event_stream_helpers.ts
+++ b/packages/kbn-optimizer/src/common/event_stream_helpers.ts
@@ -40,7 +40,7 @@ export const summarizeEventStream = (
initialState: State,
summarize: Summarizer
) => {
- return new Rx.Observable>(subscriber => {
+ return new Rx.Observable>((subscriber) => {
const eventBuffer: Event[] = [];
let processingEventBuffer = false;
@@ -93,7 +93,7 @@ export const summarizeEventStream = (
subscriber.add(
event$.subscribe(
injectEvent,
- error => {
+ (error) => {
subscriber.error(error);
},
() => {
diff --git a/packages/kbn-optimizer/src/common/index.ts b/packages/kbn-optimizer/src/common/index.ts
index 376b9ed350908..c51905be04565 100644
--- a/packages/kbn-optimizer/src/common/index.ts
+++ b/packages/kbn-optimizer/src/common/index.ts
@@ -21,7 +21,6 @@ export * from './bundle';
export * from './bundle_cache';
export * from './worker_config';
export * from './worker_messages';
-export * from './parent_messages';
export * from './compiler_messages';
export * from './ts_helpers';
export * from './rxjs_helpers';
diff --git a/packages/kbn-optimizer/src/common/parse_path.test.ts b/packages/kbn-optimizer/src/common/parse_path.test.ts
index 61be44348cfae..48749a08fb285 100644
--- a/packages/kbn-optimizer/src/common/parse_path.test.ts
+++ b/packages/kbn-optimizer/src/common/parse_path.test.ts
@@ -32,13 +32,13 @@ const FILES = [
];
describe('parseFilePath()', () => {
- it.each([...FILES, ...AMBIGUOUS])('parses %s', path => {
+ it.each([...FILES, ...AMBIGUOUS])('parses %s', (path) => {
expect(parseFilePath(path)).toMatchSnapshot();
});
});
describe('parseDirPath()', () => {
- it.each([...DIRS, ...AMBIGUOUS])('parses %s', path => {
+ it.each([...DIRS, ...AMBIGUOUS])('parses %s', (path) => {
expect(parseDirPath(path)).toMatchSnapshot();
});
});
diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts
index 72be71e6bf7ec..dda66c999b8f1 100644
--- a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts
+++ b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts
@@ -29,9 +29,9 @@ describe('pipeClosure()', () => {
let counter = 0;
const foo$ = Rx.of(1, 2, 3).pipe(
- pipeClosure(source$ => {
+ pipeClosure((source$) => {
const multiplier = ++counter;
- return source$.pipe(map(i => i * multiplier));
+ return source$.pipe(map((i) => i * multiplier));
}),
toArray()
);
@@ -71,7 +71,7 @@ describe('maybe()', () => {
describe('maybeMap()', () => {
it('calls map fn and filters out undefined values returned', async () => {
const foo$ = Rx.of(1, 2, 3, 4, 5).pipe(
- maybeMap(i => (i % 2 ? i : undefined)),
+ maybeMap((i) => (i % 2 ? i : undefined)),
toArray()
);
@@ -94,7 +94,7 @@ describe('debounceTimeBuffer()', () => {
foo$
.pipe(
debounceTimeBuffer(100),
- map(items => items.reduce((sum, n) => sum + n))
+ map((items) => items.reduce((sum, n) => sum + n))
)
.subscribe(dest);
@@ -128,7 +128,7 @@ describe('debounceTimeBuffer()', () => {
foo$
.pipe(
debounceTimeBuffer(100),
- map(items => items.reduce((sum, n) => sum + n))
+ map((items) => items.reduce((sum, n) => sum + n))
)
.subscribe(dest);
diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.ts
index f37bebb49efe9..c6385c22518aa 100644
--- a/packages/kbn-optimizer/src/common/rxjs_helpers.ts
+++ b/packages/kbn-optimizer/src/common/rxjs_helpers.ts
@@ -39,7 +39,7 @@ export const pipeClosure = (fn: Operator): Operator => {
* supporting TypeScript
*/
export const maybe = (): Operator => {
- return mergeMap(item => (item === undefined ? Rx.EMPTY : [item]));
+ return mergeMap((item) => (item === undefined ? Rx.EMPTY : [item]));
};
/**
@@ -64,7 +64,7 @@ export const debounceTimeBuffer = (ms: number) =>
pipeClosure((source$: Rx.Observable) => {
const buffer: T[] = [];
return source$.pipe(
- tap(item => buffer.push(item)),
+ tap((item) => buffer.push(item)),
debounceTime(ms),
map(() => {
const items = Array.from(buffer);
diff --git a/packages/kbn-optimizer/src/common/worker_messages.ts b/packages/kbn-optimizer/src/common/worker_messages.ts
index 0435f5b4c4011..d3c03f483d7e8 100644
--- a/packages/kbn-optimizer/src/common/worker_messages.ts
+++ b/packages/kbn-optimizer/src/common/worker_messages.ts
@@ -24,17 +24,13 @@ import {
CompilerErrorMsg,
} from './compiler_messages';
-export type InternalWorkerMsg =
- | WorkerPingMsg
+export type WorkerMsg =
| CompilerRunningMsg
| CompilerIssueMsg
| CompilerSuccessMsg
| CompilerErrorMsg
| WorkerErrorMsg;
-// ping messages are internal, they don't apper in public message streams
-export type WorkerMsg = Exclude;
-
/**
* Message sent when the worker encounters an error that it can't
* recover from, no more messages will be sent and the worker
@@ -46,10 +42,6 @@ export interface WorkerErrorMsg {
errorStack?: string;
}
-export interface WorkerPingMsg {
- type: 'ping';
-}
-
const WORKER_STATE_TYPES: ReadonlyArray = [
'running',
'compiler issue',
@@ -58,19 +50,10 @@ const WORKER_STATE_TYPES: ReadonlyArray = [
'worker error',
];
-export const isWorkerPing = (value: any): value is WorkerPingMsg =>
- typeof value === 'object' && value && value.type === 'ping';
-
export const isWorkerMsg = (value: any): value is WorkerMsg =>
typeof value === 'object' && value && WORKER_STATE_TYPES.includes(value.type);
export class WorkerMsgs {
- ping(): WorkerPingMsg {
- return {
- type: 'ping',
- };
- }
-
error(error: Error): WorkerErrorMsg {
return {
type: 'worker error',
diff --git a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts
index ff9addbb3172e..4776153935be5 100644
--- a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts
+++ b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts
@@ -85,39 +85,39 @@ it('builds expected bundles, saves bundle counts to metadata', async () => {
}
};
- const initializingStates = msgs.filter(msg => msg.state.phase === 'initializing');
+ const initializingStates = msgs.filter((msg) => msg.state.phase === 'initializing');
assert('produce at least one initializing event', initializingStates.length >= 1);
const bundleCacheStates = msgs.filter(
- msg =>
+ (msg) =>
(msg.event?.type === 'bundle cached' || msg.event?.type === 'bundle not cached') &&
msg.state.phase === 'initializing'
);
assert('produce two bundle cache events while initializing', bundleCacheStates.length === 2);
- const initializedStates = msgs.filter(msg => msg.state.phase === 'initialized');
+ const initializedStates = msgs.filter((msg) => msg.state.phase === 'initialized');
assert('produce at least one initialized event', initializedStates.length >= 1);
- const workerStarted = msgs.filter(msg => msg.event?.type === 'worker started');
+ const workerStarted = msgs.filter((msg) => msg.event?.type === 'worker started');
assert('produce one worker started event', workerStarted.length === 1);
- const runningStates = msgs.filter(msg => msg.state.phase === 'running');
+ const runningStates = msgs.filter((msg) => msg.state.phase === 'running');
assert(
'produce two or three "running" states',
runningStates.length === 2 || runningStates.length === 3
);
- const bundleNotCachedEvents = msgs.filter(msg => msg.event?.type === 'bundle not cached');
+ const bundleNotCachedEvents = msgs.filter((msg) => msg.event?.type === 'bundle not cached');
assert('produce two "bundle not cached" events', bundleNotCachedEvents.length === 2);
- const successStates = msgs.filter(msg => msg.state.phase === 'success');
+ const successStates = msgs.filter((msg) => msg.state.phase === 'success');
assert(
'produce one or two "compiler success" states',
successStates.length === 1 || successStates.length === 2
);
const otherStates = msgs.filter(
- msg =>
+ (msg) =>
msg.state.phase !== 'initializing' &&
msg.state.phase !== 'success' &&
msg.state.phase !== 'running' &&
@@ -126,7 +126,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => {
);
assert('produce zero unexpected states', otherStates.length === 0, otherStates);
- const foo = config.bundles.find(b => b.id === 'foo')!;
+ const foo = config.bundles.find((b) => b.id === 'foo')!;
expect(foo).toBeTruthy();
foo.cache.refresh();
expect(foo.cache.getModuleCount()).toBe(4);
@@ -139,7 +139,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => {
]
`);
- const bar = config.bundles.find(b => b.id === 'bar')!;
+ const bar = config.bundles.find((b) => b.id === 'bar')!;
expect(bar).toBeTruthy();
bar.cache.refresh();
expect(bar.cache.getModuleCount()).toBe(
@@ -173,7 +173,7 @@ it('uses cache on second run and exist cleanly', async () => {
const msgs = await runOptimizer(config)
.pipe(
- tap(state => {
+ tap((state) => {
if (state.event?.type === 'worker stdio') {
// eslint-disable-next-line no-console
console.log('worker', state.event.stream, state.event.chunk.toString('utf8'));
@@ -183,7 +183,7 @@ it('uses cache on second run and exist cleanly', async () => {
)
.toPromise();
- expect(msgs.map(m => m.state.phase)).toMatchInlineSnapshot(`
+ expect(msgs.map((m) => m.state.phase)).toMatchInlineSnapshot(`
Array [
"initializing",
"initializing",
@@ -202,9 +202,7 @@ it('prepares assets for distribution', async () => {
dist: true,
});
- await runOptimizer(config)
- .pipe(logOptimizerState(log, config), toArray())
- .toPromise();
+ await runOptimizer(config).pipe(logOptimizerState(log, config), toArray()).toPromise();
expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle');
expectFileMatchesSnapshotWithCompression(
diff --git a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts
index 1bfd8d3fd073a..14ff320173d60 100644
--- a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts
+++ b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts
@@ -35,7 +35,7 @@ const MOCK_REPO_DIR = Path.resolve(TMP_DIR, 'mock_repo');
expect.addSnapshotSerializer({
print: () => '',
- test: v => v instanceof Bundle,
+ test: (v) => v instanceof Bundle,
});
expect.addSnapshotSerializer(createAbsolutePathSerializer(MOCK_REPO_DIR));
diff --git a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
index c02a857883a98..91d0f308e0ef6 100644
--- a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
+++ b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
@@ -96,7 +96,7 @@ it('notifies of changes and completes once all bundles have changed', async () =
// first we change foo and bar, and after 1 second get that change comes though
if (i === 1) {
expect(event.bundles).toHaveLength(2);
- const [bar, foo] = event.bundles.sort(ascending(b => b.id));
+ const [bar, foo] = event.bundles.sort(ascending((b) => b.id));
expect(bar).toHaveProperty('id', 'bar');
expect(foo).toHaveProperty('id', 'foo');
}
@@ -110,7 +110,7 @@ it('notifies of changes and completes once all bundles have changed', async () =
// finally we change box and car together
if (i === 5) {
expect(event.bundles).toHaveLength(2);
- const [bar, foo] = event.bundles.sort(ascending(b => b.id));
+ const [bar, foo] = event.bundles.sort(ascending((b) => b.id));
expect(bar).toHaveProperty('id', 'box');
expect(foo).toHaveProperty('id', 'car');
}
diff --git a/packages/kbn-optimizer/src/log_optimizer_state.ts b/packages/kbn-optimizer/src/log_optimizer_state.ts
index 5217581d1b413..cbec159bd27a0 100644
--- a/packages/kbn-optimizer/src/log_optimizer_state.ts
+++ b/packages/kbn-optimizer/src/log_optimizer_state.ts
@@ -33,7 +33,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) {
let loggedInit = false;
return update$.pipe(
- tap(update => {
+ tap((update) => {
const { event, state } = update;
if (event?.type === 'worker stdio') {
diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts
index dd4d5c294dfc8..4671276797049 100644
--- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts
+++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts
@@ -35,7 +35,7 @@ const summarizeBundles = (w: Assignments) =>
const readConfigs = (workers: Assignments[]) =>
workers.map(
- (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map(b => b.id).join(',')}`
+ (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map((b) => b.id).join(',')}`
);
const assertReturnVal = (workers: Assignments[]) => {
diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts
index 001783b167c7a..e1bcb22230bf9 100644
--- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts
+++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts
@@ -70,16 +70,16 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number
* counts and sort them by [moduleCount, id]
*/
const bundlesWithCountsDesc = bundles
- .filter(b => b.cache.getModuleCount() !== undefined)
+ .filter((b) => b.cache.getModuleCount() !== undefined)
.sort(
descending(
- b => b.cache.getModuleCount(),
- b => b.id
+ (b) => b.cache.getModuleCount(),
+ (b) => b.id
)
);
const bundlesWithoutModuleCounts = bundles
- .filter(b => b.cache.getModuleCount() === undefined)
- .sort(descending(b => b.id));
+ .filter((b) => b.cache.getModuleCount() === undefined)
+ .sort(descending((b) => b.id));
/**
* assign largest bundles to the smallest worker until it is
@@ -87,7 +87,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number
* with module counts are assigned
*/
while (bundlesWithCountsDesc.length) {
- const [smallestWorker, nextSmallestWorker] = workers.sort(ascending(w => w.moduleCount));
+ const [smallestWorker, nextSmallestWorker] = workers.sort(ascending((w) => w.moduleCount));
while (!nextSmallestWorker || smallestWorker.moduleCount <= nextSmallestWorker.moduleCount) {
const bundle = bundlesWithCountsDesc.shift();
@@ -104,7 +104,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number
* assign bundles without module counts to workers round-robin
* starting with the smallest workers
*/
- workers.sort(ascending(w => w.moduleCount));
+ workers.sort(ascending((w) => w.moduleCount));
while (bundlesWithoutModuleCounts.length) {
for (const worker of workers) {
const bundle = bundlesWithoutModuleCounts.shift();
diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts
index 7351a3787f760..d5b0b8491f727 100644
--- a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts
+++ b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts
@@ -35,7 +35,7 @@ jest.mock('./get_changes.ts', () => ({
}));
jest.mock('./get_mtimes.ts', () => ({
- getMtimes: async (paths: string[]) => new Map(paths.map(path => [path, 12345])),
+ getMtimes: async (paths: string[]) => new Map(paths.map((path) => [path, 12345])),
}));
jest.mock('execa');
diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.ts
index 11288afa28969..e024af125312d 100644
--- a/packages/kbn-optimizer/src/optimizer/cache_keys.ts
+++ b/packages/kbn-optimizer/src/optimizer/cache_keys.ts
@@ -182,7 +182,7 @@ export async function getOptimizerCacheKey(config: OptimizerConfig) {
};
const mtimes = await getMtimes(modifiedPaths);
- for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending(e => e[0]))) {
+ for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending((e) => e[0]))) {
if (typeof mtime === 'number') {
cacheKeys.modifiedTimes[path] = mtime;
}
diff --git a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts
index 9ac156cb5b8de..07777c323637a 100644
--- a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts
+++ b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts
@@ -33,15 +33,15 @@ export async function getMtimes(paths: Iterable) {
// map paths to [path, mtimeMs] entries with concurrency of
// 100 at a time, ignoring missing paths
mergeMap(
- path =>
+ (path) =>
stat$(path).pipe(
- map(stat => [path, stat.mtimeMs] as const),
+ map((stat) => [path, stat.mtimeMs] as const),
catchError((error: any) => (error?.code === 'ENOENT' ? Rx.EMPTY : Rx.throwError(error)))
),
100
),
toArray(),
- map(entries => new Map(entries))
+ map((entries) => new Map(entries))
)
.toPromise();
}
diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts
index 36dc0ca64c6ca..2174c488ad6cc 100644
--- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts
+++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts
@@ -44,7 +44,7 @@ it('returns a bundle for core and each plugin', () => {
},
],
'/repo'
- ).map(b => b.toSpec())
+ ).map((b) => b.toSpec())
).toMatchInlineSnapshot(`
Array [
Object {
diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts
index 4741cc3c30af7..b75a8a6edc264 100644
--- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts
+++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts
@@ -25,9 +25,9 @@ import { KibanaPlatformPlugin } from './kibana_platform_plugins';
export function getPluginBundles(plugins: KibanaPlatformPlugin[], repoRoot: string) {
return plugins
- .filter(p => p.isUiPlugin)
+ .filter((p) => p.isUiPlugin)
.map(
- p =>
+ (p) =>
new Bundle({
type: 'plugin',
id: p.id,
diff --git a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts
index b4b02649259a2..8b39b5fe8d3b6 100644
--- a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts
+++ b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts
@@ -32,7 +32,7 @@ export function handleOptimizerCompletion(config: OptimizerConfig) {
return update$.pipe(
tap({
- next: update => {
+ next: (update) => {
prevState = update.state;
},
complete: () => {
diff --git a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts
index 2165878e92ff4..992feab6cd364 100644
--- a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts
+++ b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts
@@ -36,15 +36,15 @@ export function findKibanaPlatformPlugins(scanDirs: string[], paths: string[]) {
.sync(
Array.from(
new Set([
- ...scanDirs.map(dir => `${dir}/*/kibana.json`),
- ...paths.map(path => `${path}/kibana.json`),
+ ...scanDirs.map((dir) => `${dir}/*/kibana.json`),
+ ...paths.map((path) => `${path}/kibana.json`),
])
),
{
absolute: true,
}
)
- .map(path =>
+ .map((path) =>
// absolute paths returned from globby are using normalize or something so the path separators are `/` even on windows, Path.resolve solves this
readKibanaPlatformPlugin(Path.resolve(path))
);
diff --git a/packages/kbn-optimizer/src/optimizer/observe_worker.ts b/packages/kbn-optimizer/src/optimizer/observe_worker.ts
index 90c53f1ef9e87..f5c944cefb76f 100644
--- a/packages/kbn-optimizer/src/optimizer/observe_worker.ts
+++ b/packages/kbn-optimizer/src/optimizer/observe_worker.ts
@@ -22,14 +22,12 @@ import { Readable } from 'stream';
import { inspect } from 'util';
import * as Rx from 'rxjs';
-import { map, filter, takeUntil } from 'rxjs/operators';
+import { map, takeUntil } from 'rxjs/operators';
-import { isWorkerMsg, isWorkerPing, WorkerConfig, WorkerMsg, Bundle, ParentMsgs } from '../common';
+import { isWorkerMsg, WorkerConfig, WorkerMsg, Bundle } from '../common';
import { OptimizerConfig } from './optimizer_config';
-const parentMsgs = new ParentMsgs();
-
export interface WorkerStdio {
type: 'worker stdio';
stream: 'stdout' | 'stderr';
@@ -49,7 +47,7 @@ interface ProcResource extends Rx.Unsubscribable {
const isNumeric = (input: any) => String(input).match(/^[0-9]+$/);
let inspectPortCounter = 9230;
-const inspectFlagIndex = process.execArgv.findIndex(flag => flag.startsWith('--inspect'));
+const inspectFlagIndex = process.execArgv.findIndex((flag) => flag.startsWith('--inspect'));
let inspectFlag: string | undefined;
if (inspectFlagIndex !== -1) {
const argv = process.execArgv[inspectFlagIndex];
@@ -76,7 +74,7 @@ function usingWorkerProc(
) {
return Rx.using(
(): ProcResource => {
- const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map(b => b.toSpec()))];
+ const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map((b) => b.toSpec()))];
const proc = fork(require.resolve('../worker/run_worker'), args, {
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
@@ -96,7 +94,7 @@ function usingWorkerProc(
};
},
- resource => {
+ (resource) => {
const { proc } = resource as ProcResource;
return fn(proc);
}
@@ -109,7 +107,7 @@ function observeStdio$(stream: Readable, name: WorkerStdio['stream']) {
Rx.race(
Rx.fromEvent(stream, 'end'),
Rx.fromEvent(stream, 'error').pipe(
- map(error => {
+ map((error) => {
throw error;
})
)
@@ -136,7 +134,7 @@ export function observeWorker(
workerConfig: WorkerConfig,
bundles: Bundle[]
): Rx.Observable {
- return usingWorkerProc(config, workerConfig, bundles, proc => {
+ return usingWorkerProc(config, workerConfig, bundles, (proc) => {
let lastMsg: WorkerMsg;
return Rx.merge(
@@ -148,16 +146,6 @@ export function observeWorker(
observeStdio$(proc.stderr, 'stderr'),
Rx.fromEvent<[unknown]>(proc, 'message')
.pipe(
- // filter out ping messages so they don't end up in the general message stream
- filter(([msg]) => {
- if (!isWorkerPing(msg)) {
- return true;
- }
-
- proc.send(parentMsgs.pong());
- return false;
- }),
-
// validate the messages from the process
map(([msg]) => {
if (!isWorkerMsg(msg)) {
@@ -173,7 +161,7 @@ export function observeWorker(
Rx.race(
// throw into stream on error events
Rx.fromEvent(proc, 'error').pipe(
- map(error => {
+ map((error) => {
throw new Error(`worker failed to spawn: ${error.message}`);
})
),
diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts
index d6336cf867470..4ed241f3b9b2e 100644
--- a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts
+++ b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts
@@ -106,7 +106,7 @@ export class OptimizerConfig {
...(examples ? [Path.resolve('examples'), Path.resolve('x-pack/examples')] : []),
Path.resolve(repoRoot, '../kibana-extra'),
];
- if (!pluginScanDirs.every(p => Path.isAbsolute(p))) {
+ if (!pluginScanDirs.every((p) => Path.isAbsolute(p))) {
throw new TypeError('pluginScanDirs must all be absolute paths');
}
@@ -118,7 +118,7 @@ export class OptimizerConfig {
}
const pluginPaths = options.pluginPaths || [];
- if (!pluginPaths.every(s => Path.isAbsolute(s))) {
+ if (!pluginPaths.every((s) => Path.isAbsolute(s))) {
throw new TypeError('pluginPaths must all be absolute paths');
}
diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts
index ac2a9b8ce1f8b..1572f459e6ee5 100644
--- a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts
+++ b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts
@@ -80,7 +80,7 @@ function createOptimizerState(
* calculate the total state, given a set of compiler messages
*/
function getStatePhase(states: CompilerMsg[]) {
- const types = states.map(s => s.type);
+ const types = states.map((s) => s.type);
if (types.includes('running')) {
return 'running';
@@ -90,7 +90,7 @@ function getStatePhase(states: CompilerMsg[]) {
return 'issue';
}
- if (types.every(s => s === 'compiler success')) {
+ if (types.every((s) => s === 'compiler success')) {
return 'success';
}
@@ -173,7 +173,7 @@ export function createOptimizerStateSummarizer(
event.type === 'running'
) {
const compilerStates: CompilerMsg[] = [
- ...state.compilerStates.filter(c => c.bundleId !== event.bundleId),
+ ...state.compilerStates.filter((c) => c.bundleId !== event.bundleId),
event,
];
return createOptimizerState(state, {
diff --git a/packages/kbn-optimizer/src/optimizer/run_workers.ts b/packages/kbn-optimizer/src/optimizer/run_workers.ts
index e91b0d25fd72b..1f277f011004d 100644
--- a/packages/kbn-optimizer/src/optimizer/run_workers.ts
+++ b/packages/kbn-optimizer/src/optimizer/run_workers.ts
@@ -50,15 +50,15 @@ export function runWorkers(
return Rx.concat(
// first batch of bundles are based on how up-to-date the cache is
bundleCache$.pipe(
- maybeMap(event => (event.type === 'bundle not cached' ? event.bundle : undefined)),
+ maybeMap((event) => (event.type === 'bundle not cached' ? event.bundle : undefined)),
toArray()
),
// subsequent batches are defined by changeEvent$
- changeEvent$.pipe(maybeMap(c => (c.type === 'changes' ? c.bundles : undefined)))
+ changeEvent$.pipe(maybeMap((c) => (c.type === 'changes' ? c.bundles : undefined)))
).pipe(
- mergeMap(bundles =>
+ mergeMap((bundles) =>
Rx.from(assignBundlesToWorkers(bundles, config.maxWorkerCount)).pipe(
- mergeMap(assignment =>
+ mergeMap((assignment) =>
observeWorker(config, config.getWorkerConfig(optimizerCacheKey), assignment.bundles)
)
)
diff --git a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts
index 9149c483786fc..fdac4e0204fbe 100644
--- a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts
+++ b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts
@@ -38,7 +38,7 @@ function recursiveGetNextChange$(
return !bundles.length
? Rx.EMPTY
: watcher.getNextChange$(bundles, startTime).pipe(
- mergeMap(event => {
+ mergeMap((event) => {
if (event.type === 'changes detected') {
return Rx.of(event);
}
@@ -48,7 +48,7 @@ function recursiveGetNextChange$(
recursiveGetNextChange$(
watcher,
- bundles.filter(b => !event.bundles.includes(b)),
+ bundles.filter((b) => !event.bundles.includes(b)),
Date.now()
)
);
@@ -74,11 +74,11 @@ export function watchBundlesForChanges$(
initialStartTime: number
) {
return bundleCacheEvent$.pipe(
- maybeMap(event => (event.type === 'bundle cached' ? event.bundle : undefined)),
+ maybeMap((event) => (event.type === 'bundle cached' ? event.bundle : undefined)),
toArray(),
- mergeMap(bundles =>
+ mergeMap((bundles) =>
bundles.length
- ? Watcher.using(watcher => recursiveGetNextChange$(watcher, bundles, initialStartTime))
+ ? Watcher.using((watcher) => recursiveGetNextChange$(watcher, bundles, initialStartTime))
: Rx.EMPTY
)
);
diff --git a/packages/kbn-optimizer/src/optimizer/watcher.ts b/packages/kbn-optimizer/src/optimizer/watcher.ts
index 343f391921383..54c548755af5c 100644
--- a/packages/kbn-optimizer/src/optimizer/watcher.ts
+++ b/packages/kbn-optimizer/src/optimizer/watcher.ts
@@ -43,7 +43,7 @@ export class Watcher {
static using(fn: (watcher: Watcher) => Rx.Observable) {
return Rx.using(
() => new Watcher(),
- resource => fn(resource as Watcher)
+ (resource) => fn(resource as Watcher)
);
}
@@ -69,14 +69,14 @@ export class Watcher {
// debounce and bufffer change events for 1 second to create
// final change notification
this.change$.pipe(
- map(event => event[0]),
+ map((event) => event[0]),
debounceTimeBuffer(1000),
map(
(changes): Changes => ({
type: 'changes',
- bundles: bundles.filter(bundle => {
+ bundles: bundles.filter((bundle) => {
const referencedFiles = bundle.cache.getReferencedFiles();
- return changes.some(change => referencedFiles?.includes(change));
+ return changes.some((change) => referencedFiles?.includes(change));
}),
})
),
diff --git a/packages/kbn-optimizer/src/report_optimizer_stats.ts b/packages/kbn-optimizer/src/report_optimizer_stats.ts
index 06161fb2567b9..5f3153bff5175 100644
--- a/packages/kbn-optimizer/src/report_optimizer_stats.ts
+++ b/packages/kbn-optimizer/src/report_optimizer_stats.ts
@@ -29,14 +29,14 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize
let lastState: OptimizerState | undefined;
return update$.pipe(
materialize(),
- mergeMap(async n => {
+ mergeMap(async (n) => {
if (n.kind === 'N' && n.value?.state) {
lastState = n.value?.state;
}
if (n.kind === 'C' && lastState) {
await reporter.metrics(
- config.bundles.map(bundle => {
+ config.bundles.map((bundle) => {
// make the cache read from the cache file since it was likely updated by the worker
bundle.cache.refresh();
diff --git a/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts b/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts
deleted file mode 100644
index 2c1b86b380c60..0000000000000
--- a/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * 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 { EventEmitter } from 'events';
-import { inspect } from 'util';
-
-import * as Rx from 'rxjs';
-import { tap, takeUntil } from 'rxjs/operators';
-
-import { observeParentOffline, Process } from './observe_parent_offline';
-import { WorkerMsgs, ParentMsgs, isWorkerPing } from '../common';
-
-jest.useFakeTimers();
-
-beforeEach(() => {
- jest.clearAllTimers();
-});
-
-const workerMsgs = new WorkerMsgs();
-const parentMsgs = new ParentMsgs();
-class MockProcess extends EventEmitter implements Process {
- connected?: boolean;
- send?: jest.Mock;
-
- constructor(options: { connected?: boolean; send?: jest.Mock | false } = {}) {
- super();
-
- this.connected = options.connected ?? true;
- this.send = options.send === false ? undefined : options.send ?? jest.fn();
- }
-}
-
-async function record(observable: Rx.Observable): Promise {
- const notes: string[] = [];
-
- await observable
- .pipe(
- tap({
- next(value) {
- notes.push(`next: ${inspect(value)}`);
- },
- error(error) {
- notes.push(`error: ${inspect(error)}`);
- },
- complete() {
- notes.push(`complete`);
- },
- })
- )
- .toPromise();
-
- return notes;
-}
-
-async function waitForTick() {
- await new Promise(resolve => {
- process.nextTick(resolve);
- });
-}
-
-describe('emits and completes when parent exists because:', () => {
- test('process.connected is false', async () => {
- const mockProc = new MockProcess({
- connected: false,
- });
-
- const promise = record(observeParentOffline(mockProc, workerMsgs));
- jest.advanceTimersToNextTimer();
- expect(await promise).toMatchInlineSnapshot(`
- Array [
- "next: 'parent offline (disconnected)'",
- "complete",
- ]
- `);
- });
-
- test('process.send is falsey', async () => {
- const mockProc = new MockProcess({
- send: false,
- });
-
- const promise = record(observeParentOffline(mockProc, workerMsgs));
- jest.advanceTimersToNextTimer();
- expect(await promise).toMatchInlineSnapshot(`
- Array [
- "next: 'parent offline (disconnected)'",
- "complete",
- ]
- `);
- });
-
- test('process.send throws "ERR_IPC_CHANNEL_CLOSED"', async () => {
- const mockProc = new MockProcess({
- send: jest.fn(() => {
- const error = new Error();
- (error as any).code = 'ERR_IPC_CHANNEL_CLOSED';
- throw error;
- }),
- });
-
- const promise = record(observeParentOffline(mockProc, workerMsgs));
- jest.advanceTimersToNextTimer();
- expect(await promise).toMatchInlineSnapshot(`
- Array [
- "next: 'parent offline (ipc channel exception)'",
- "complete",
- ]
- `);
- });
-
- test('ping timeout', async () => {
- const mockProc = new MockProcess({});
-
- const promise = record(observeParentOffline(mockProc, workerMsgs));
- jest.advanceTimersByTime(10000);
- expect(await promise).toMatchInlineSnapshot(`
- Array [
- "next: 'parent offline (ping timeout)'",
- "complete",
- ]
- `);
- });
-});
-
-test('it emits nothing if parent responds with pongs', async () => {
- const send = jest.fn((msg: any) => {
- if (isWorkerPing(msg)) {
- process.nextTick(() => {
- mockProc.emit('message', parentMsgs.pong(), undefined);
- });
- }
- });
-
- const mockProc = new MockProcess({ send });
- const unsub$ = new Rx.Subject();
- const promise = record(observeParentOffline(mockProc, workerMsgs).pipe(takeUntil(unsub$)));
-
- jest.advanceTimersByTime(5000);
- await waitForTick();
- jest.advanceTimersByTime(5000);
- await waitForTick();
- unsub$.next();
-
- expect(await promise).toMatchInlineSnapshot(`
- Array [
- "complete",
- ]
- `);
- expect(send).toHaveBeenCalledTimes(2);
-});
diff --git a/packages/kbn-optimizer/src/worker/observe_parent_offline.ts b/packages/kbn-optimizer/src/worker/observe_parent_offline.ts
deleted file mode 100644
index ff24a0e64a399..0000000000000
--- a/packages/kbn-optimizer/src/worker/observe_parent_offline.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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 { EventEmitter } from 'events';
-
-import * as Rx from 'rxjs';
-import { mergeMap, take, first, map, catchError } from 'rxjs/operators';
-
-import { isParentPong, WorkerMsgs } from '../common';
-
-const sleep = (ms: number) => Rx.timer(ms).pipe(take(1));
-
-export interface Process extends EventEmitter {
- connected?: boolean;
- send?: (msg: any) => void;
-}
-
-/**
- * Returns an observable that will emit a value when the parent
- * process goes offline. It accomplishes this by merging several
- * signals:
- *
- * 1. process "disconnect" event
- * 2. process.connected or process.send are falsy
- * 3. a ping was sent to the parent process but it didn't respond
- * with a pong within 5 seconds
- * 4. a ping was sent to the parent process but the process.send
- * call errored with an 'ERR_IPC_CHANNEL_CLOSED' exception
- */
-export function observeParentOffline(process: Process, workerMsgs: WorkerMsgs) {
- return sleep(5000).pipe(
- mergeMap(() => {
- if (!process.connected || !process.send) {
- return Rx.of('parent offline (disconnected)');
- }
-
- process.send(workerMsgs.ping());
-
- const pong$ = Rx.fromEvent<[any]>(process, 'message').pipe(
- first(([msg]) => isParentPong(msg)),
- map(() => {
- throw new Error('parent still online');
- })
- );
-
- // give the parent some time to respond, if the ping
- // wins the race the parent is considered online
- const timeout$ = sleep(5000).pipe(map(() => 'parent offline (ping timeout)'));
-
- return Rx.race(pong$, timeout$);
- }),
-
- /**
- * resubscribe to the source observable (triggering the timer,
- * ping, wait for response) if the source observable does not
- * observe the parent being offline yet.
- *
- * Scheduling the interval this way prevents the ping timeout
- * from overlaping with the interval by only scheduling the
- * next ping once the previous ping has completed
- */
- catchError((error, resubscribe) => {
- if (error.code === 'ERR_IPC_CHANNEL_CLOSED') {
- return Rx.of('parent offline (ipc channel exception)');
- }
-
- if (error.message === 'parent still online') {
- return resubscribe;
- }
-
- throw error;
- })
- );
-}
diff --git a/packages/kbn-optimizer/src/worker/run_compilers.ts b/packages/kbn-optimizer/src/worker/run_compilers.ts
index 0dfce4b5addba..4ab289d031d72 100644
--- a/packages/kbn-optimizer/src/worker/run_compilers.ts
+++ b/packages/kbn-optimizer/src/worker/run_compilers.ts
@@ -65,8 +65,8 @@ const observeCompiler = (
* Called by webpack as a single run compilation is starting
*/
const started$ = Rx.merge(
- Rx.fromEventPattern(cb => beforeRun.tap(PLUGIN_NAME, cb)),
- Rx.fromEventPattern(cb => watchRun.tap(PLUGIN_NAME, cb))
+ Rx.fromEventPattern((cb) => beforeRun.tap(PLUGIN_NAME, cb)),
+ Rx.fromEventPattern((cb) => watchRun.tap(PLUGIN_NAME, cb))
).pipe(mapTo(compilerMsgs.running()));
/**
@@ -74,8 +74,8 @@ const observeCompiler = (
* needAdditionalPass property is set then another compilation
* is about to be started, so we shouldn't send complete quite yet
*/
- const complete$ = Rx.fromEventPattern(cb => done.tap(PLUGIN_NAME, cb)).pipe(
- maybeMap(stats => {
+ const complete$ = Rx.fromEventPattern((cb) => done.tap(PLUGIN_NAME, cb)).pipe(
+ maybeMap((stats) => {
// @ts-ignore not included in types, but it is real https://github.com/webpack/webpack/blob/ab4fa8ddb3f433d286653cd6af7e3aad51168649/lib/Watching.js#L58
if (stats.compilation.needAdditionalPass) {
return undefined;
@@ -134,7 +134,7 @@ const observeCompiler = (
);
}
- const files = Array.from(referencedFiles).sort(ascending(p => p));
+ const files = Array.from(referencedFiles).sort(ascending((p) => p));
const mtimes = new Map(
files.map((path): [string, number | undefined] => {
try {
@@ -167,8 +167,10 @@ const observeCompiler = (
* prevets assets from being emitted, and prevents watching
* from continuing.
*/
- const error$ = Rx.fromEventPattern(cb => compiler.hooks.failed.tap(PLUGIN_NAME, cb)).pipe(
- map(error => {
+ const error$ = Rx.fromEventPattern((cb) =>
+ compiler.hooks.failed.tap(PLUGIN_NAME, cb)
+ ).pipe(
+ map((error) => {
throw compilerMsgs.error(error);
})
);
@@ -184,7 +186,7 @@ const observeCompiler = (
* Run webpack compilers
*/
export const runCompilers = (workerConfig: WorkerConfig, bundles: Bundle[]) => {
- const multiCompiler = webpack(bundles.map(def => getWebpackConfig(def, workerConfig)));
+ const multiCompiler = webpack(bundles.map((def) => getWebpackConfig(def, workerConfig)));
return Rx.merge(
/**
diff --git a/packages/kbn-optimizer/src/worker/run_worker.ts b/packages/kbn-optimizer/src/worker/run_worker.ts
index 0a9adc2a3db55..f83c69477f471 100644
--- a/packages/kbn-optimizer/src/worker/run_worker.ts
+++ b/packages/kbn-optimizer/src/worker/run_worker.ts
@@ -18,12 +18,10 @@
*/
import * as Rx from 'rxjs';
-import { takeUntil } from 'rxjs/operators';
import { parseBundles, parseWorkerConfig, WorkerMsg, isWorkerMsg, WorkerMsgs } from '../common';
import { runCompilers } from './run_compilers';
-import { observeParentOffline } from './observe_parent_offline';
/**
**
@@ -66,6 +64,15 @@ const exit = (code: number) => {
}, 5000).unref();
};
+// check for connected parent on an unref'd timer rather than listening
+// to "disconnect" since that listner prevents the process from exiting
+setInterval(() => {
+ if (!process.connected) {
+ // parent is gone
+ process.exit(0);
+ }
+}, 1000).unref();
+
Rx.defer(() => {
const workerConfig = parseWorkerConfig(process.argv[2]);
const bundles = parseBundles(process.argv[3]);
@@ -74,22 +81,20 @@ Rx.defer(() => {
process.env.BROWSERSLIST_ENV = workerConfig.browserslistEnv;
return runCompilers(workerConfig, bundles);
-})
- .pipe(takeUntil(observeParentOffline(process, workerMsgs)))
- .subscribe(
- msg => {
- send(msg);
- },
- error => {
- if (isWorkerMsg(error)) {
- send(error);
- } else {
- send(workerMsgs.error(error));
- }
-
- exit(1);
- },
- () => {
- exit(0);
+}).subscribe(
+ (msg) => {
+ send(msg);
+ },
+ (error) => {
+ if (isWorkerMsg(error)) {
+ send(error);
+ } else {
+ send(workerMsgs.error(error));
}
- );
+
+ exit(1);
+ },
+ () => {
+ exit(0);
+ }
+);
diff --git a/packages/kbn-optimizer/src/worker/theme_loader.ts b/packages/kbn-optimizer/src/worker/theme_loader.ts
index 6d6686a5bde1b..5d02462ef1bb8 100644
--- a/packages/kbn-optimizer/src/worker/theme_loader.ts
+++ b/packages/kbn-optimizer/src/worker/theme_loader.ts
@@ -21,7 +21,7 @@ import webpack from 'webpack';
import { stringifyRequest } from 'loader-utils';
// eslint-disable-next-line import/no-default-export
-export default function(this: webpack.loader.LoaderContext) {
+export default function (this: webpack.loader.LoaderContext) {
return `
if (window.__kbnDarkMode__) {
require(${stringifyRequest(this, `${this.resourcePath}?dark`)})
diff --git a/packages/kbn-optimizer/src/worker/webpack.config.ts b/packages/kbn-optimizer/src/worker/webpack.config.ts
index 49bcc6e7e704c..0c9a5b0a75687 100644
--- a/packages/kbn-optimizer/src/worker/webpack.config.ts
+++ b/packages/kbn-optimizer/src/worker/webpack.config.ts
@@ -64,7 +64,7 @@ function dynamicExternals(bundle: Bundle, context: string, request: string) {
// ignore requests that don't include a /{dirname}/public for one of our
// "static" bundles as a cheap way to avoid doing path resolution
// for paths that couldn't possibly resolve to what we're looking for
- const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some(p =>
+ const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some((p) =>
request.includes(`/${p.dirname}/public`)
);
if (!reqToStaticBundle) {
@@ -100,7 +100,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
output: {
path: bundle.outputDir,
filename: `[name].${bundle.type}.js`,
- devtoolModuleFilenameTemplate: info =>
+ devtoolModuleFilenameTemplate: (info) =>
`/${bundle.type}:${bundle.id}/${Path.relative(
bundle.sourceRoot,
info.absoluteResourcePath
@@ -121,7 +121,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
externals: [
UiSharedDeps.externals,
- function(context, request, cb) {
+ function (context, request, cb) {
try {
cb(undefined, dynamicExternals(bundle, context, request));
} catch (error) {
diff --git a/packages/kbn-plugin-generator/index.js b/packages/kbn-plugin-generator/index.js
index 5f20569886d88..e61037e42d63f 100644
--- a/packages/kbn-plugin-generator/index.js
+++ b/packages/kbn-plugin-generator/index.js
@@ -61,7 +61,7 @@ exports.run = function run(argv) {
name,
targetPath,
},
- }).catch(error => {
+ }).catch((error) => {
console.error(chalk`{red fatal error}!`);
console.error(error.stack);
process.exit(1);
diff --git a/packages/kbn-plugin-generator/sao_template/sao.js b/packages/kbn-plugin-generator/sao_template/sao.js
index 9073ce865a963..7fc29b1e6bd0a 100755
--- a/packages/kbn-plugin-generator/sao_template/sao.js
+++ b/packages/kbn-plugin-generator/sao_template/sao.js
@@ -59,7 +59,7 @@ async function eslintPlugin(dir) {
}
}
-module.exports = function({ name, targetPath }) {
+module.exports = function ({ name, targetPath }) {
return {
prompts: {
customPath: {
@@ -99,7 +99,7 @@ module.exports = function({ name, targetPath }) {
},
generateTranslations: {
type: 'confirm',
- when: answers => {
+ when: (answers) => {
// only for 3rd party plugins
return !answers.customPath && answers.generateApp;
},
@@ -112,7 +112,7 @@ module.exports = function({ name, targetPath }) {
generateScss: {
type: 'confirm',
message: 'Should SCSS be used?',
- when: answers => answers.generateApp,
+ when: (answers) => answers.generateApp,
default: true,
},
generateEslint: {
@@ -135,7 +135,7 @@ module.exports = function({ name, targetPath }) {
'eslintrc.js': '.eslintrc.js',
'i18nrc.json': '.i18nrc.json',
},
- data: answers => {
+ data: (answers) => {
const pathToPlugin = answers.customPath
? resolve(answers.customPath, camelCase(name), 'public')
: resolve(targetPath, 'public');
diff --git a/packages/kbn-plugin-helpers/src/cli.ts b/packages/kbn-plugin-helpers/src/cli.ts
index ee1bca0fe3ac2..b894f854a484f 100644
--- a/packages/kbn-plugin-helpers/src/cli.ts
+++ b/packages/kbn-plugin-helpers/src/cli.ts
@@ -35,7 +35,7 @@ enableCollectingUnknownOptions(
.description('Start kibana and have it include this plugin')
.on('--help', docs('start'))
.action(
- createCommanderAction('start', command => ({
+ createCommanderAction('start', (command) => ({
flags: command.unknownOptions,
}))
)
@@ -75,7 +75,7 @@ program
.option('-p, --plugins ', "Manually specify which plugins' test bundles to run")
.on('--help', docs('test/karma'))
.action(
- createCommanderAction('testKarma', command => ({
+ createCommanderAction('testKarma', (command) => ({
dev: Boolean(command.dev),
plugins: command.plugins,
}))
diff --git a/packages/kbn-plugin-helpers/src/lib/docs.ts b/packages/kbn-plugin-helpers/src/lib/docs.ts
index 68c095209e817..fb05fd0c5c2ce 100644
--- a/packages/kbn-plugin-helpers/src/lib/docs.ts
+++ b/packages/kbn-plugin-helpers/src/lib/docs.ts
@@ -28,7 +28,7 @@ function indent(txt: string, n: number) {
export function docs(name: string) {
const md = readFileSync(resolve(__dirname, '../../src/tasks', name, 'README.md'), 'utf8');
- return function() {
+ return function () {
/* eslint-disable-next-line no-console */
console.log(`\n Docs:\n\n${indent(md, 4)}\n\n`);
};
diff --git a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts
index 77fa7f2fcae84..0d692aed06305 100644
--- a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts
+++ b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts
@@ -22,7 +22,7 @@ import { Command } from 'commander';
export function enableCollectingUnknownOptions(command: Command) {
const origParse = command.parseOptions;
command.allowUnknownOption();
- command.parseOptions = function(argv: string[]) {
+ command.parseOptions = function (argv: string[]) {
const opts = origParse.call(this, argv);
this.unknownOptions = opts.unknown;
return opts;
diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js
index c2d2ade568761..052d224b662e2 100644
--- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js
+++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js
@@ -17,7 +17,7 @@
* under the License.
*/
-module.exports = kibana =>
+module.exports = (kibana) =>
new kibana.Plugin({
uiExports: {
hacks: ['plugins/test_plugin/hack.js'],
diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js
index c2d2ade568761..052d224b662e2 100644
--- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js
+++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js
@@ -17,7 +17,7 @@
* under the License.
*/
-module.exports = kibana =>
+module.exports = (kibana) =>
new kibana.Plugin({
uiExports: {
hacks: ['plugins/test_plugin/hack.js'],
diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js
index c2d2ade568761..052d224b662e2 100644
--- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js
+++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js
@@ -17,7 +17,7 @@
* under the License.
*/
-module.exports = kibana =>
+module.exports = (kibana) =>
new kibana.Plugin({
uiExports: {
hacks: ['plugins/test_plugin/hack.js'],
diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js
index f596576fe7466..d9f20129e85f9 100644
--- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js
+++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js
@@ -91,7 +91,7 @@ describe('calling create_build', () => {
expect(mockBuild.mock.calls).toHaveLength(1);
const { files } = nameArgs(mockBuild.mock.calls[0]);
- plugin.buildSourcePatterns.forEach(file => expect(files).toContain(file));
+ plugin.buildSourcePatterns.forEach((file) => expect(files).toContain(file));
});
it('uses only files passed in', async () => {
@@ -104,7 +104,7 @@ describe('calling create_build', () => {
expect(mockBuild.mock.calls).toHaveLength(1);
const { files } = nameArgs(mockBuild.mock.calls[0]);
- options.files.forEach(file => expect(files).toContain(file));
+ options.files.forEach((file) => expect(files).toContain(file));
});
it('rejects returned promise when build fails', async () => {
diff --git a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts
index 255b2e6ef9992..aaecd11ad82af 100644
--- a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts
+++ b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts
@@ -26,7 +26,7 @@ export function rewritePackageJson(
buildVersion: string,
kibanaVersion: string
) {
- return Through2Map.obj(function(file: File) {
+ return Through2Map.obj(function (file: File) {
if (file.basename === 'package.json' && file.dirname === buildSource) {
const pkg = JSON.parse(file.contents!.toString('utf8'));
diff --git a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts
index 75affb6da8c6f..5018fd7598180 100644
--- a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts
+++ b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts
@@ -35,7 +35,7 @@ export function startTask({ plugin, options }: TaskContext) {
let args = nodeOptions.concat([script, '--dev', '--plugin-path', plugin.root]);
if (Array.isArray(plugin.includePlugins)) {
- plugin.includePlugins.forEach(path => {
+ plugin.includePlugins.forEach((path) => {
args = args.concat(['--plugin-path', path]);
});
}
diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js
index 1b670eb8cd816..baaac3d8d4a86 100644
--- a/packages/kbn-pm/dist/index.js
+++ b/packages/kbn-pm/dist/index.js
@@ -4859,7 +4859,7 @@ class ProcRunner {
this.closing = false;
this.procs = [];
this.signalUnsubscribe = exit_hook_1.default(() => {
- this.teardown().catch(error => {
+ this.teardown().catch((error) => {
log.error(`ProcRunner teardown error: ${error.stack}`);
});
});
@@ -4898,7 +4898,7 @@ class ProcRunner {
try {
if (wait instanceof RegExp) {
// wait for process to log matching line
- await Rx.race(proc.lines$.pipe(operators_1.filter(line => wait.test(line)), operators_1.first(), operators_1.catchError(err => {
+ await Rx.race(proc.lines$.pipe(operators_1.filter((line) => wait.test(line)), operators_1.first(), operators_1.catchError((err) => {
if (err.name !== 'EmptyError') {
throw errors_1.createCliError(`[${name}] exited without matching pattern: ${wait}`);
}
@@ -4943,7 +4943,7 @@ class ProcRunner {
* @return {Promise}
*/
async waitForAllToStop() {
- await Promise.all(this.procs.map(proc => proc.outcomePromise));
+ await Promise.all(this.procs.map((proc) => proc.outcomePromise));
}
/**
* Close the ProcRunner and stop all running
@@ -4959,14 +4959,14 @@ class ProcRunner {
this.closing = true;
this.signalUnsubscribe();
if (!signal && this.procs.length > 0) {
- this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map(proc => proc.name));
+ this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map((proc) => proc.name));
}
await Promise.all(this.procs.map(async (proc) => {
await proc.stop(signal === 'exit' ? 'SIGKILL' : signal);
}));
}
getProc(name) {
- return this.procs.find(proc => {
+ return this.procs.find((proc) => {
return proc.name === name;
});
}
@@ -4979,14 +4979,14 @@ class ProcRunner {
};
// tie into proc outcome$, remove from _procs on compete
proc.outcome$.subscribe({
- next: code => {
+ next: (code) => {
const duration = moment_1.default.duration(Date.now() - startMs);
this.log.info('[%s] exited with %s after %s', name, code, duration.humanize());
},
complete: () => {
remove();
},
- error: error => {
+ error: (error) => {
if (this.closing) {
this.log.error(error);
}
@@ -33599,8 +33599,8 @@ function startProc(name, options, log) {
return code;
})),
// observe first error event
- Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap(err => Rx.throwError(err)))).pipe(operators_1.share());
- const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap(line => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share());
+ Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap((err) => Rx.throwError(err)))).pipe(operators_1.share());
+ const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap((line) => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share());
const outcomePromise = Rx.merge(lines$.pipe(operators_1.ignoreElements()), outcome$).toPromise();
async function stop(signal) {
if (stopCalled) {
@@ -36584,7 +36584,7 @@ const operators_1 = __webpack_require__(270);
* - fails on the first "error" event
*/
function observeReadable(readable) {
- return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap(err => Rx.throwError(err))));
+ return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap((err) => Rx.throwError(err))));
}
exports.observeReadable = observeReadable;
@@ -36894,7 +36894,7 @@ class ToolingLogCollectingWriter extends tooling_log_text_writer_1.ToolingLogTex
super({
level: 'verbose',
writeTo: {
- write: msg => {
+ write: (msg) => {
// trim trailing new line
this.messages.push(msg.slice(0, -1));
},
@@ -39475,7 +39475,7 @@ async function run(fn, options = {}) {
level: tooling_log_1.pickLevelFromFlags(flags),
writeTo: process.stdout,
});
- process.on('unhandledRejection', error => {
+ process.on('unhandledRejection', (error) => {
log.error('UNHANDLED PROMISE REJECTION');
log.error(error instanceof Error
? error
@@ -39589,7 +39589,7 @@ function combineErrors(errors) {
const exitCode = errors
.filter(isFailError)
.reduce((acc, error) => Math.max(acc, error.exitCode), 1);
- const showHelp = errors.some(error => isFailError(error) && error.showHelp);
+ const showHelp = errors.some((error) => isFailError(error) && error.showHelp);
const message = errors.reduce((acc, error) => {
if (isFailError(error)) {
return acc + '\n' + error.message;
@@ -40091,7 +40091,7 @@ exports.uriencode = (strings, ...values) => {
return queue.reduce((acc, string, i) => `${acc}${encodeURIComponent(values[i])}${string}`, leadingString);
};
const DEFAULT_MAX_ATTEMPTS = 5;
-const delay = (ms) => new Promise(resolve => {
+const delay = (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
class KbnClientRequester {
@@ -43984,7 +43984,7 @@ class CiStatsReporter {
const reason = ((_d = (_c = error) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.status) ? `${error.response.status} response`
: 'no response';
this.log.warning(`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds`);
- await new Promise(resolve => setTimeout(resolve, attempt * 1000));
+ await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
}
}
}
diff --git a/packages/kbn-pm/package.json b/packages/kbn-pm/package.json
index be56fad8aa0ce..234877e9ae626 100644
--- a/packages/kbn-pm/package.json
+++ b/packages/kbn-pm/package.json
@@ -54,7 +54,7 @@
"multimatch": "^4.0.0",
"ncp": "^2.0.0",
"ora": "^1.4.0",
- "prettier": "^1.19.1",
+ "prettier": "^2.0.5",
"read-pkg": "^5.2.0",
"rxjs": "^6.5.3",
"spawn-sync": "^1.0.15",
diff --git a/packages/kbn-pm/src/cli.ts b/packages/kbn-pm/src/cli.ts
index c2f49356957f7..94f348e1835ed 100644
--- a/packages/kbn-pm/src/cli.ts
+++ b/packages/kbn-pm/src/cli.ts
@@ -28,8 +28,8 @@ import { log } from './utils/log';
function help() {
const availableCommands = Object.keys(commands)
- .map(commandName => commands[commandName])
- .map(command => `${command.name} - ${command.description}`);
+ .map((commandName) => commands[commandName])
+ .map((command) => `${command.name} - ${command.description}`);
log.write(dedent`
usage: kbn []
diff --git a/packages/kbn-pm/src/commands/bootstrap.ts b/packages/kbn-pm/src/commands/bootstrap.ts
index d0aa220f25f66..6146aeab21db4 100644
--- a/packages/kbn-pm/src/commands/bootstrap.ts
+++ b/packages/kbn-pm/src/commands/bootstrap.ts
@@ -69,7 +69,7 @@ export const BootstrapCommand: ICommand = {
log.write(chalk.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n'));
const checksums = options.cache ? await getAllChecksums(kbn, log) : false;
- await parallelizeBatches(batchedProjects, async project => {
+ await parallelizeBatches(batchedProjects, async (project) => {
if (project.hasScript('kbn:bootstrap')) {
const cacheFile = new BootstrapCacheFile(kbn, project, checksums);
if (cacheFile.isValid()) {
diff --git a/packages/kbn-pm/src/commands/run.ts b/packages/kbn-pm/src/commands/run.ts
index 2f4d9e8453d09..989bfef19c380 100644
--- a/packages/kbn-pm/src/commands/run.ts
+++ b/packages/kbn-pm/src/commands/run.ts
@@ -43,7 +43,7 @@ export const RunCommand: ICommand = {
chalk.bold(`\nRunning script [${chalk.green(scriptName)}] in batched topological order\n`)
);
- await parallelizeBatches(batchedProjects, async pkg => {
+ await parallelizeBatches(batchedProjects, async (pkg) => {
if (pkg.hasScript(scriptName)) {
await pkg.runScriptStreaming(scriptName, scriptArgs);
}
diff --git a/packages/kbn-pm/src/commands/watch.ts b/packages/kbn-pm/src/commands/watch.ts
index b5c493372b04f..2e18b02a1c860 100644
--- a/packages/kbn-pm/src/commands/watch.ts
+++ b/packages/kbn-pm/src/commands/watch.ts
@@ -83,7 +83,7 @@ export const WatchCommand: ICommand = {
batchedProjects.push([projects.get(kibanaProjectName)!]);
}
- await parallelizeBatches(batchedProjects, async pkg => {
+ await parallelizeBatches(batchedProjects, async (pkg) => {
const completionHint = await waitUntilWatchIsReady(
pkg.runScriptStreaming(watchScriptName).stdout
);
diff --git a/packages/kbn-pm/src/production/build_production_projects.ts b/packages/kbn-pm/src/production/build_production_projects.ts
index 0d4be8b016077..689bf51cd7bdf 100644
--- a/packages/kbn-pm/src/production/build_production_projects.ts
+++ b/packages/kbn-pm/src/production/build_production_projects.ts
@@ -46,7 +46,7 @@ export async function buildProductionProjects({
const projectGraph = buildProjectGraph(projects);
const batchedProjects = topologicallyBatchProjects(projects, projectGraph);
- const projectNames = [...projects.values()].map(project => project.name);
+ const projectNames = [...projects.values()].map((project) => project.name);
log.write(`Preparing production build for [${projectNames.join(', ')}]`);
for (const batch of batchedProjects) {
@@ -82,7 +82,7 @@ async function getProductionProjects(rootPath: string, onlyOSS?: boolean) {
productionProjects.delete('kibana');
if (onlyOSS) {
- productionProjects.forEach(project => {
+ productionProjects.forEach((project) => {
if (project.getBuildConfig().oss === false) {
productionProjects.delete(project.json.name);
}
diff --git a/packages/kbn-pm/src/run.ts b/packages/kbn-pm/src/run.ts
index 44bf5a91ee1b1..c3879c701d785 100644
--- a/packages/kbn-pm/src/run.ts
+++ b/packages/kbn-pm/src/run.ts
@@ -71,7 +71,7 @@ export async function runCommand(command: ICommand, config: Omit 0) {
- const metaOutput = keys.map(key => {
+ const metaOutput = keys.map((key) => {
const value = e.meta[key];
return `${key}: ${value}`;
});
diff --git a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts
index 7d87179f34605..282483e10ccf2 100644
--- a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts
+++ b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts
@@ -39,7 +39,7 @@ export class BootstrapCacheFile {
// sort deps by name so that the key is stable
.sort((a, b) => a.name.localeCompare(b.name))
// get the cacheKey for each project, return undefined if the cache key couldn't be determined
- .map(p => {
+ .map((p) => {
const cacheKey = checksums.get(p.name);
if (cacheKey) {
return `${p.name}:${cacheKey}`;
@@ -47,7 +47,7 @@ export class BootstrapCacheFile {
});
// if any of the relevant cache keys are undefined then the projectCacheKey must be too
- this.expectedValue = projectAndDepCacheKeys.some(k => !k)
+ this.expectedValue = projectAndDepCacheKeys.some((k) => !k)
? undefined
: [
`# this is only human readable for debugging, please don't try to parse this`,
diff --git a/packages/kbn-pm/src/utils/fs.ts b/packages/kbn-pm/src/utils/fs.ts
index 9484c3a61e608..44fc59bdeba96 100644
--- a/packages/kbn-pm/src/utils/fs.ts
+++ b/packages/kbn-pm/src/utils/fs.ts
@@ -49,7 +49,7 @@ async function statTest(path: string, block: (stats: fs.Stats) => boolean) {
* @param path
*/
export async function isSymlink(path: string) {
- return await statTest(path, stats => stats.isSymbolicLink());
+ return await statTest(path, (stats) => stats.isSymbolicLink());
}
/**
@@ -57,7 +57,7 @@ export async function isSymlink(path: string) {
* @param path
*/
export async function isDirectory(path: string) {
- return await statTest(path, stats => stats.isDirectory());
+ return await statTest(path, (stats) => stats.isDirectory());
}
/**
@@ -65,7 +65,7 @@ export async function isDirectory(path: string) {
* @param path
*/
export async function isFile(path: string) {
- return await statTest(path, stats => stats.isFile());
+ return await statTest(path, (stats) => stats.isFile());
}
/**
diff --git a/packages/kbn-pm/src/utils/kibana.ts b/packages/kbn-pm/src/utils/kibana.ts
index 58af98b2a92db..7fca4bd01822b 100644
--- a/packages/kbn-pm/src/utils/kibana.ts
+++ b/packages/kbn-pm/src/utils/kibana.ts
@@ -103,11 +103,11 @@ export class Kibana {
const allProjects = this.getAllProjects();
const filteredProjects: ProjectMap = new Map();
- const pkgJsonPaths = Array.from(allProjects.values()).map(p => p.packageJsonLocation);
+ const pkgJsonPaths = Array.from(allProjects.values()).map((p) => p.packageJsonLocation);
const filteredPkgJsonGlobs = getProjectPaths({
...options,
rootPath: this.kibanaProject.path,
- }).map(g => Path.resolve(g, 'package.json'));
+ }).map((g) => Path.resolve(g, 'package.json'));
const matchingPkgJsonPaths = multimatch(pkgJsonPaths, filteredPkgJsonGlobs);
for (const project of allProjects.values()) {
diff --git a/packages/kbn-pm/src/utils/link_project_executables.test.ts b/packages/kbn-pm/src/utils/link_project_executables.test.ts
index a6334ec850860..a19e1fd66f334 100644
--- a/packages/kbn-pm/src/utils/link_project_executables.test.ts
+++ b/packages/kbn-pm/src/utils/link_project_executables.test.ts
@@ -70,7 +70,7 @@ const projectGraph = buildProjectGraph(projectsByName);
function getFsMockCalls() {
const fs = require('./fs');
const fsMockCalls: { [key: string]: any[][] } = {};
- Object.keys(fs).map(key => {
+ Object.keys(fs).map((key) => {
if (jest.isMockFunction(fs[key])) {
fsMockCalls[key] = fs[key].mock.calls;
}
diff --git a/packages/kbn-pm/src/utils/link_project_executables.ts b/packages/kbn-pm/src/utils/link_project_executables.ts
index 25fb11f17f782..b403dfb2ecf2e 100644
--- a/packages/kbn-pm/src/utils/link_project_executables.ts
+++ b/packages/kbn-pm/src/utils/link_project_executables.ts
@@ -55,9 +55,7 @@ export async function linkProjectExecutables(
const dest = resolve(binsDir, name);
// Get relative project path with normalized path separators.
- const projectRelativePath = relative(project.path, srcPath)
- .split(sep)
- .join('/');
+ const projectRelativePath = relative(project.path, srcPath).split(sep).join('/');
log.write(chalk`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`);
diff --git a/packages/kbn-pm/src/utils/parallelize.test.ts b/packages/kbn-pm/src/utils/parallelize.test.ts
index fa23ecbb8c1e7..e85b40e0c67d8 100644
--- a/packages/kbn-pm/src/utils/parallelize.test.ts
+++ b/packages/kbn-pm/src/utils/parallelize.test.ts
@@ -22,7 +22,7 @@ import { parallelizeBatches } from './parallelize';
// As promises resolve async, we use this helper to wait for all promises that
// have been resolved to complete (aka call `then`).
const tick = () =>
- new Promise(resolve => {
+ new Promise((resolve) => {
setTimeout(resolve, 0);
});
@@ -32,7 +32,7 @@ test('parallelizes batches', async () => {
const baz = createPromiseWithResolve();
const batches = [[foo, bar], [baz]];
- const parallelize = parallelizeBatches(batches, async obj => {
+ const parallelize = parallelizeBatches(batches, async (obj) => {
obj.called = true;
await obj.promise;
});
@@ -82,7 +82,7 @@ test('schedules at most 4 calls at the same time (concurrency)', async () => {
const foobar = createPromiseWithResolve();
const batches = [[foo, bar, baz, quux, foobar]];
- const parallelize = parallelizeBatches(batches, async obj => {
+ const parallelize = parallelizeBatches(batches, async (obj) => {
obj.called = true;
await obj.promise;
});
@@ -113,7 +113,7 @@ test('rejects if any promise rejects', async () => {
const baz = createPromiseWithResolve();
const batches = [[foo, bar], [baz]];
- const parallelize = parallelizeBatches(batches, async obj => {
+ const parallelize = parallelizeBatches(batches, async (obj) => {
await obj.promise;
});
diff --git a/packages/kbn-pm/src/utils/project.ts b/packages/kbn-pm/src/utils/project.ts
index 7b0bbed5c3f46..91a3a5365b60e 100644
--- a/packages/kbn-pm/src/utils/project.ts
+++ b/packages/kbn-pm/src/utils/project.ts
@@ -229,10 +229,10 @@ export class Project {
// check for any cross-project dependency
for (const name of Object.keys(workspacesInfo)) {
const workspace = workspacesInfo[name];
- workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w));
+ workspace.workspaceDependencies.forEach((w) => unusedWorkspaces.delete(w));
}
- unusedWorkspaces.forEach(name => {
+ unusedWorkspaces.forEach((name) => {
const { dependencies, devDependencies } = this.json;
const nodeModulesPath = Path.resolve(this.nodeModulesLocation, name);
const isDependency = dependencies && dependencies.hasOwnProperty(name);
diff --git a/packages/kbn-pm/src/utils/project_checksums.ts b/packages/kbn-pm/src/utils/project_checksums.ts
index 7d939e715d411..46dde1b32c158 100644
--- a/packages/kbn-pm/src/utils/project_checksums.ts
+++ b/packages/kbn-pm/src/utils/project_checksums.ts
@@ -49,8 +49,8 @@ async function getChangesForProjects(projects: ProjectMap, kbn: Kibana, log: Too
'--exclude-standard',
'--',
...Array.from(projects.values())
- .filter(p => kbn.isPartOfRepo(p))
- .map(p => p.path),
+ .filter((p) => kbn.isPartOfRepo(p))
+ .map((p) => p.path),
],
{
cwd: kbn.getAbsolute(),
@@ -265,7 +265,7 @@ export async function getAllChecksums(kbn: Kibana, log: ToolingLog) {
const cacheKeys: ChecksumMap = new Map();
await Promise.all(
- Array.from(projects.values()).map(async project => {
+ Array.from(projects.values()).map(async (project) => {
cacheKeys.set(
project.name,
await getChecksum(project, changesByProject.get(project), yarnLock, kbn, log)
diff --git a/packages/kbn-pm/src/utils/projects.test.ts b/packages/kbn-pm/src/utils/projects.test.ts
index ba093b9d5eba1..068c72286872a 100644
--- a/packages/kbn-pm/src/utils/projects.test.ts
+++ b/packages/kbn-pm/src/utils/projects.test.ts
@@ -208,7 +208,7 @@ describe('#topologicallyBatchProjects', () => {
test('batches projects topologically based on their project dependencies', async () => {
const batches = topologicallyBatchProjects(projects, graph);
- const expectedBatches = batches.map(batch => batch.map(project => project.name));
+ const expectedBatches = batches.map((batch) => batch.map((project) => project.name));
expect(expectedBatches).toMatchSnapshot();
});
@@ -219,7 +219,7 @@ describe('#topologicallyBatchProjects', () => {
const batches = topologicallyBatchProjects(projects, graph);
- const expectedBatches = batches.map(batch => batch.map(project => project.name));
+ const expectedBatches = batches.map((batch) => batch.map((project) => project.name));
expect(expectedBatches).toMatchSnapshot();
});
@@ -228,7 +228,7 @@ describe('#topologicallyBatchProjects', () => {
test('batches projects topologically based on their project dependencies and workspaces', async () => {
const batches = topologicallyBatchProjects(projects, graph, { batchByWorkspace: true });
- const expectedBatches = batches.map(batch => batch.map(project => project.name));
+ const expectedBatches = batches.map((batch) => batch.map((project) => project.name));
expect(expectedBatches).toEqual([['kibana'], ['bar', 'foo'], ['baz', 'zorge'], ['quux']]);
});
diff --git a/packages/kbn-pm/src/utils/projects.ts b/packages/kbn-pm/src/utils/projects.ts
index a6f174b1fc5a1..1c3bf0fa3091a 100644
--- a/packages/kbn-pm/src/utils/projects.ts
+++ b/packages/kbn-pm/src/utils/projects.ts
@@ -137,7 +137,9 @@ export function topologicallyBatchProjects(
const batches = [];
if (batchByWorkspace) {
- const workspaceRootProject = Array.from(projectsToBatch.values()).find(p => p.isWorkspaceRoot);
+ const workspaceRootProject = Array.from(projectsToBatch.values()).find(
+ (p) => p.isWorkspaceRoot
+ );
if (!workspaceRootProject) {
throw new CliError(`There was no yarn workspace root found.`);
@@ -167,7 +169,7 @@ export function topologicallyBatchProjects(
const batch = [];
for (const projectName of projectsLeftToBatch) {
const projectDeps = projectGraph.get(projectName)!;
- const needsDependenciesBatched = projectDeps.some(dep => projectsLeftToBatch.has(dep.name));
+ const needsDependenciesBatched = projectDeps.some((dep) => projectsLeftToBatch.has(dep.name));
if (!needsDependenciesBatched) {
batch.push(projectsToBatch.get(projectName)!);
@@ -188,7 +190,7 @@ export function topologicallyBatchProjects(
batches.push(batch);
- batch.forEach(project => projectsLeftToBatch.delete(project.name));
+ batch.forEach((project) => projectsLeftToBatch.delete(project.name));
}
return batches;
@@ -211,7 +213,7 @@ export function includeTransitiveProjects(
? project.productionDependencies
: project.allDependencies;
- Object.keys(dependencies).forEach(dep => {
+ Object.keys(dependencies).forEach((dep) => {
if (allProjects.has(dep)) {
toProcess.push(allProjects.get(dep)!);
}
diff --git a/packages/kbn-pm/src/utils/watch.ts b/packages/kbn-pm/src/utils/watch.ts
index 0ec8b50d83905..1998c5199fb73 100644
--- a/packages/kbn-pm/src/utils/watch.ts
+++ b/packages/kbn-pm/src/utils/watch.ts
@@ -56,20 +56,20 @@ function getWatchHandlers(
}: IWatchOptions
) {
const typescriptHandler = buildOutput$.pipe(
- first(data => data.includes('$ tsc')),
+ first((data) => data.includes('$ tsc')),
map(() =>
buildOutput$.pipe(
- first(data => data.includes('Compilation complete.')),
+ first((data) => data.includes('Compilation complete.')),
mapTo('tsc')
)
)
);
const webpackHandler = buildOutput$.pipe(
- first(data => data.includes('$ webpack')),
+ first((data) => data.includes('$ webpack')),
map(() =>
buildOutput$.pipe(
- first(data => data.includes('Chunk Names')),
+ first((data) => data.includes('Chunk Names')),
mapTo('webpack')
)
)
@@ -100,7 +100,7 @@ export function waitUntilWatchIsReady(stream: NodeJS.EventEmitter, opts: IWatchO
return Rx.race(getWatchHandlers(buildOutput$, opts))
.pipe(
- mergeMap(whenReady => whenReady),
+ mergeMap((whenReady) => whenReady),
finalize(() => {
stream.removeListener('data', onDataListener);
stream.removeListener('end', onEndListener);
diff --git a/packages/kbn-pm/src/utils/workspaces.ts b/packages/kbn-pm/src/utils/workspaces.ts
index 22fa8636aea90..830a713e84ad4 100644
--- a/packages/kbn-pm/src/utils/workspaces.ts
+++ b/packages/kbn-pm/src/utils/workspaces.ts
@@ -48,7 +48,7 @@ export async function workspacePackagePaths(rootPath: string): Promise
for (const pattern of workspacesPathsPatterns) {
if (pattern.startsWith('!')) {
const pathToRemove = path.join(rootPath, pattern.slice(1), 'package.json');
- workspaceProjectsPaths = workspaceProjectsPaths.filter(p => p !== pathToRemove);
+ workspaceProjectsPaths = workspaceProjectsPaths.filter((p) => p !== pathToRemove);
}
}
diff --git a/packages/kbn-spec-to-console/bin/spec_to_console.js b/packages/kbn-spec-to-console/bin/spec_to_console.js
index 20b42c67f3b89..432890a9cb903 100644
--- a/packages/kbn-spec-to-console/bin/spec_to_console.js
+++ b/packages/kbn-spec-to-console/bin/spec_to_console.js
@@ -46,7 +46,7 @@ console.log();
console.log(files);
console.log();
-files.forEach(file => {
+files.forEach((file) => {
const spec = JSON.parse(fs.readFileSync(file));
const convertedSpec = convert(spec);
if (!Object.keys(convertedSpec).length) {
diff --git a/packages/kbn-spec-to-console/lib/convert.js b/packages/kbn-spec-to-console/lib/convert.js
index 9648ef0b85a4f..bd0dbb429cff3 100644
--- a/packages/kbn-spec-to-console/lib/convert.js
+++ b/packages/kbn-spec-to-console/lib/convert.js
@@ -22,7 +22,7 @@ const convertMethods = require('./convert/methods');
const convertPaths = require('./convert/paths');
const convertParts = require('./convert/parts');
-module.exports = spec => {
+module.exports = (spec) => {
const result = {};
/**
* TODO:
@@ -34,7 +34,7 @@ module.exports = spec => {
* from being used in autocompletion. It would be really nice if we could use this information
* instead of just not including it.
*/
- Object.keys(spec).forEach(api => {
+ Object.keys(spec).forEach((api) => {
const source = spec[api];
if (!source.url) {
@@ -42,7 +42,7 @@ module.exports = spec => {
}
if (source.url.path) {
- if (source.url.paths.every(path => Boolean(path.deprecated))) {
+ if (source.url.paths.every((path) => Boolean(path.deprecated))) {
return;
}
}
@@ -61,10 +61,10 @@ module.exports = spec => {
if (source.url.paths) {
// We filter out all deprecated url patterns here.
- const paths = source.url.paths.filter(path => !path.deprecated);
+ const paths = source.url.paths.filter((path) => !path.deprecated);
patterns = convertPaths(paths);
- paths.forEach(pathsObject => {
- pathsObject.methods.forEach(method => methodSet.add(method));
+ paths.forEach((pathsObject) => {
+ pathsObject.methods.forEach((method) => methodSet.add(method));
if (pathsObject.parts) {
for (const partName of Object.keys(pathsObject.parts)) {
urlComponents[partName] = pathsObject.parts[partName];
@@ -79,7 +79,7 @@ module.exports = spec => {
if (Object.keys(urlComponents).length) {
const components = convertParts(urlComponents);
const hasComponents =
- Object.keys(components).filter(c => {
+ Object.keys(components).filter((c) => {
return Boolean(components[c]);
}).length > 0;
if (hasComponents) {
diff --git a/packages/kbn-spec-to-console/lib/convert/methods.js b/packages/kbn-spec-to-console/lib/convert/methods.js
index b4ab8f467ae1f..89d193dd38071 100644
--- a/packages/kbn-spec-to-console/lib/convert/methods.js
+++ b/packages/kbn-spec-to-console/lib/convert/methods.js
@@ -17,6 +17,6 @@
* under the License.
*/
-module.exports = methods => {
+module.exports = (methods) => {
return methods;
};
diff --git a/packages/kbn-spec-to-console/lib/convert/params.js b/packages/kbn-spec-to-console/lib/convert/params.js
index 0d1747ae4f685..00169b12322ed 100644
--- a/packages/kbn-spec-to-console/lib/convert/params.js
+++ b/packages/kbn-spec-to-console/lib/convert/params.js
@@ -17,9 +17,9 @@
* under the License.
*/
-module.exports = params => {
+module.exports = (params) => {
const result = {};
- Object.keys(params).forEach(param => {
+ Object.keys(params).forEach((param) => {
const { type, description = '', options = [] } = params[param];
const [, defaultValue] = description.match(/\(default: (.*)\)/) || [];
switch (type) {
@@ -35,7 +35,7 @@ module.exports = params => {
case 'enum':
// This is to clean up entries like: "d (Days)". We only want the "d" part.
if (param === 'time') {
- result[param] = options.map(option => option.split(' ')[0]);
+ result[param] = options.map((option) => option.split(' ')[0]);
} else {
result[param] = options;
}
diff --git a/packages/kbn-spec-to-console/lib/convert/parts.js b/packages/kbn-spec-to-console/lib/convert/parts.js
index 040d04a0c1dc4..96cd3c94e796d 100644
--- a/packages/kbn-spec-to-console/lib/convert/parts.js
+++ b/packages/kbn-spec-to-console/lib/convert/parts.js
@@ -19,9 +19,9 @@
const replacePattern = require('../replace_pattern');
-module.exports = parts => {
+module.exports = (parts) => {
const result = {};
- Object.keys(parts).forEach(part => {
+ Object.keys(parts).forEach((part) => {
const key = replacePattern(part, { exact: true });
const options = parts[part].options;
if (options && options.length) {
diff --git a/packages/kbn-spec-to-console/lib/convert/paths.js b/packages/kbn-spec-to-console/lib/convert/paths.js
index 6c65bf48b9b06..af8897c2782f2 100644
--- a/packages/kbn-spec-to-console/lib/convert/paths.js
+++ b/packages/kbn-spec-to-console/lib/convert/paths.js
@@ -19,8 +19,8 @@
const replacePattern = require('../replace_pattern');
-module.exports = patterns => {
- return patterns.map(patternObject => {
+module.exports = (patterns) => {
+ return patterns.map((patternObject) => {
return replacePattern(patternObject.path, { brackets: true });
});
};
diff --git a/packages/kbn-spec-to-console/lib/replace_pattern.js b/packages/kbn-spec-to-console/lib/replace_pattern.js
index 29d16be3cc70f..4da75db78086d 100644
--- a/packages/kbn-spec-to-console/lib/replace_pattern.js
+++ b/packages/kbn-spec-to-console/lib/replace_pattern.js
@@ -21,7 +21,7 @@ const map = require('./static/map_interpolation');
module.exports = (pattern, { brackets, exact } = {}) => {
let newPattern = pattern;
- Object.keys(map).forEach(key => {
+ Object.keys(map).forEach((key) => {
const replaceFrom = brackets ? `{${key}}` : key;
const replaceTo = brackets ? `{${map[key]}}` : map[key];
if (exact) {
diff --git a/packages/kbn-spec-to-console/package.json b/packages/kbn-spec-to-console/package.json
index a6b3e8f96f7db..ebbf244eb2e10 100644
--- a/packages/kbn-spec-to-console/package.json
+++ b/packages/kbn-spec-to-console/package.json
@@ -18,7 +18,7 @@
"homepage": "https://github.com/jbudz/spec-to-console#readme",
"devDependencies": {
"jest": "^24.9.0",
- "prettier": "^1.19.1"
+ "prettier": "^2.0.5"
},
"dependencies": {
"commander": "^3.0.0",
diff --git a/packages/kbn-storybook/index.js b/packages/kbn-storybook/index.js
index b595de8ea1c07..c7dae20902f1a 100644
--- a/packages/kbn-storybook/index.js
+++ b/packages/kbn-storybook/index.js
@@ -27,7 +27,7 @@ const { generateStorybookEntry } = require('./lib/storybook_entry');
const { REPO_ROOT, ASSET_DIR, CURRENT_CONFIG } = require('./lib/constants');
const { buildDll } = require('./lib/dll');
-exports.runStorybookCli = config => {
+exports.runStorybookCli = (config) => {
const { name, storyGlobs } = config;
run(
async ({ flags, log, procRunner }) => {
diff --git a/packages/kbn-storybook/lib/storybook_entry.js b/packages/kbn-storybook/lib/storybook_entry.js
index dececef47f40e..9eb1b0a458c6a 100644
--- a/packages/kbn-storybook/lib/storybook_entry.js
+++ b/packages/kbn-storybook/lib/storybook_entry.js
@@ -37,7 +37,7 @@ const STORE_ENTRY_DIR = dirname(STORY_ENTRY_PATH);
exports.generateStorybookEntry = ({ log, storyGlobs }) => {
const globs = ['built_assets/css/**/*.light.css', ...storyGlobs];
log.info('Storybook globs:\n', globs);
- const norm = p => normalize(relative(STORE_ENTRY_DIR, p));
+ const norm = (p) => normalize(relative(STORE_ENTRY_DIR, p));
return Rx.defer(() =>
glob(globs, {
@@ -46,20 +46,20 @@ exports.generateStorybookEntry = ({ log, storyGlobs }) => {
onlyFiles: true,
})
).pipe(
- map(paths => {
+ map((paths) => {
log.info('Discovered Storybook entry points:\n', paths);
return new Set(paths.map(norm));
}),
mergeMap(
- paths =>
- new Rx.Observable(observer => {
+ (paths) =>
+ new Rx.Observable((observer) => {
observer.next(paths);
const chokidar = watch(globs, { cwd: REPO_ROOT })
- .on('add', path => {
+ .on('add', (path) => {
observer.next(paths.add(norm(resolve(REPO_ROOT, path))));
})
- .on('unlink', path => {
+ .on('unlink', (path) => {
observer.next(paths.delete(norm(resolve(REPO_ROOT, path))));
});
diff --git a/packages/kbn-storybook/storybook_config/middleware.js b/packages/kbn-storybook/storybook_config/middleware.js
index 046758948b2cf..9410bb66030d9 100644
--- a/packages/kbn-storybook/storybook_config/middleware.js
+++ b/packages/kbn-storybook/storybook_config/middleware.js
@@ -21,6 +21,6 @@ const serve = require('serve-static');
const path = require('path');
// Extend the Storybook Middleware to include a route to access Legacy UI assets
-module.exports = function(router) {
+module.exports = function (router) {
router.get('/ui', serve(path.resolve(__dirname, '../../../src/core/server/core_app/assets')));
};
diff --git a/packages/kbn-storybook/storybook_config/mocks/noop.js b/packages/kbn-storybook/storybook_config/mocks/noop.js
index aaddfb2ed8ac3..e78d222eaa560 100755
--- a/packages/kbn-storybook/storybook_config/mocks/noop.js
+++ b/packages/kbn-storybook/storybook_config/mocks/noop.js
@@ -17,4 +17,4 @@
* under the License.
*/
-export default function() {}
+export default function () {}
diff --git a/packages/kbn-storybook/storybook_config/webpack.config.js b/packages/kbn-storybook/storybook_config/webpack.config.js
index 779d8a4153644..2dd051882bb4b 100644
--- a/packages/kbn-storybook/storybook_config/webpack.config.js
+++ b/packages/kbn-storybook/storybook_config/webpack.config.js
@@ -29,7 +29,7 @@ const { currentConfig } = require('../../../built_assets/storybook/current.confi
module.exports = async ({ config }) => {
// Find and alter the CSS rule to replace the Kibana public path string with a path
// to the route we've added in middleware.js
- const cssRule = config.module.rules.find(rule => rule.test.source.includes('.css$'));
+ const cssRule = config.module.rules.find((rule) => rule.test.source.includes('.css$'));
cssRule.use.push({
loader: 'string-replace-loader',
options: {
diff --git a/packages/kbn-test-subj-selector/__tests__/index.js b/packages/kbn-test-subj-selector/__tests__/index.js
index e18405b99ae52..23165cefec94a 100755
--- a/packages/kbn-test-subj-selector/__tests__/index.js
+++ b/packages/kbn-test-subj-selector/__tests__/index.js
@@ -20,8 +20,8 @@
const testSubjSelector = require('../');
const expect = require('@kbn/expect');
-describe('testSubjSelector()', function() {
- it('converts subjectSelectors to cssSelectors', function() {
+describe('testSubjSelector()', function () {
+ it('converts subjectSelectors to cssSelectors', function () {
expect(testSubjSelector('foo bar')).to.eql('[data-test-subj="foo bar"]');
expect(testSubjSelector('foo > bar')).to.eql('[data-test-subj="foo"] [data-test-subj="bar"]');
expect(testSubjSelector('foo > bar baz')).to.eql(
diff --git a/packages/kbn-test-subj-selector/index.js b/packages/kbn-test-subj-selector/index.js
index 3984c15c00fef..2be59d78dc5ef 100755
--- a/packages/kbn-test-subj-selector/index.js
+++ b/packages/kbn-test-subj-selector/index.js
@@ -42,12 +42,7 @@ module.exports = function testSubjSelector(selector) {
while (terms.length) {
const term = terms.shift();
// split each term by joins/& and map to css selectors
- cssSelectors.push(
- term
- .split('&')
- .map(termToCssSelector)
- .join('')
- );
+ cssSelectors.push(term.split('&').map(termToCssSelector).join(''));
}
return cssSelectors.join(' ');
diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts
index 0c824754b1237..7cbeb18a5ebd4 100644
--- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts
+++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts
@@ -25,12 +25,8 @@ import { createPatch } from 'diff';
// turns out Jest can't encode xml diffs in their JUnit reports...
expect.addSnapshotSerializer({
- test: v => typeof v === 'string' && (v.includes('<') || v.includes('>')),
- print: v =>
- v
- .replace(//g, '›')
- .replace(/^\s+$/gm, ''),
+ test: (v) => typeof v === 'string' && (v.includes('<') || v.includes('>')),
+ print: (v) => v.replace(//g, '›').replace(/^\s+$/gm, ''),
});
jest.mock('fs', () => {
diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts
index 32ea5fa0f9033..6bc7556db8a47 100644
--- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts
+++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts
@@ -49,7 +49,7 @@ export async function addMessagesToReport(options: {
for (const testCase of makeFailedTestCaseIter(report)) {
const { classname, name } = testCase.$;
const messageList = messages
- .filter(u => u.classname === classname && u.name === name)
+ .filter((u) => u.classname === classname && u.name === name)
.reduce((acc, u) => `${acc}\n - ${u.message}`, '');
if (!messageList) {
@@ -76,7 +76,7 @@ export async function addMessagesToReport(options: {
const xml = builder
.buildObject(report)
.split('\n')
- .map(line => (line.trim() === '' ? '' : line))
+ .map((line) => (line.trim() === '' ? '' : line))
.join('\n');
if (dryRun) {
diff --git a/packages/kbn-test/src/failed_tests_reporter/github_api.ts b/packages/kbn-test/src/failed_tests_reporter/github_api.ts
index 7da79b5b67e63..a0e3bcafdf196 100644
--- a/packages/kbn-test/src/failed_tests_reporter/github_api.ts
+++ b/packages/kbn-test/src/failed_tests_reporter/github_api.ts
@@ -233,7 +233,7 @@ export class GithubApi {
this.log.error(`Unable to reach github, waiting ${waitMs}ms to retry`);
}
- await new Promise(resolve => setTimeout(resolve, waitMs));
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
return await this.request(
{
...options,
diff --git a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts
index 9324f9eb42aa5..b298c08f162bf 100644
--- a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts
+++ b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts
@@ -100,7 +100,7 @@ export function runFailedTestsReporterCli() {
}
let existingIssue: GithubIssueMini | undefined = await githubApi.findFailedTestIssue(
- i =>
+ (i) =>
getIssueMetadata(i.body, 'test.class') === failure.classname &&
getIssueMetadata(i.body, 'test.name') === failure.name
);
diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js
index 3c8daf4154236..133f4d2feb53e 100644
--- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js
+++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js
@@ -26,7 +26,7 @@ import { REPO_ROOT } from '@kbn/dev-utils';
const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js');
const BASIC_CONFIG = require.resolve('../fixtures/simple_project/config.js');
-describe('basic config file with a single app and test', function() {
+describe('basic config file with a single app and test', function () {
this.timeout(60 * 1000);
it('runs and prints expected output', () => {
diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js
index d6e7b1ac58aa4..12e28d2702c5a 100644
--- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js
+++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js
@@ -27,7 +27,7 @@ import { REPO_ROOT } from '@kbn/dev-utils';
const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js');
const FAILURE_HOOKS_CONFIG = require.resolve('../fixtures/failure_hooks/config.js');
-describe('failure hooks', function() {
+describe('failure hooks', function () {
this.timeout(60 * 1000);
it('runs and prints expected output', () => {
diff --git a/packages/kbn-test/src/functional_test_runner/cli.ts b/packages/kbn-test/src/functional_test_runner/cli.ts
index 276a51c3a6a99..fd5ee5ad3ae44 100644
--- a/packages/kbn-test/src/functional_test_runner/cli.ts
+++ b/packages/kbn-test/src/functional_test_runner/cli.ts
@@ -87,7 +87,7 @@ export function runFtrCli() {
}
};
- process.on('unhandledRejection', err =>
+ process.on('unhandledRejection', (err) =>
teardown(
err instanceof Error ? err : new Error(`non-Error type rejection value: ${inspect(err)}`)
)
diff --git a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts
index 3a66ba22ccf3d..03d4d7643607f 100644
--- a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts
+++ b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts
@@ -89,7 +89,7 @@ export class FunctionalTestRunner {
// promise-like objects which never resolve, essentially disabling them
// allowing us to load the test files and populate the mocha suites
const readStubbedProviderSpec = (type: string, providers: any) =>
- readProviderSpec(type, providers).map(p => ({
+ readProviderSpec(type, providers).map((p) => ({
...p,
fn: () => ({
then: () => {},
diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts
index ad9247523797a..e38520f00e45b 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts
@@ -114,7 +114,7 @@ export class Config {
throw new Error(`Unknown config key "${key}"`);
}
- return cloneDeep(get(this[$values], key, defaultValue), v => {
+ return cloneDeep(get(this[$values], key, defaultValue), (v) => {
if (typeof v === 'function') {
return v;
}
@@ -122,7 +122,7 @@ export class Config {
}
public getAll() {
- return cloneDeep(this[$values], v => {
+ return cloneDeep(this[$values], (v) => {
if (typeof v === 'function') {
return v;
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts
index f4b91d154cbb8..29ec28175a851 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts
@@ -30,12 +30,8 @@ const INSPECTING =
const urlPartsSchema = () =>
Joi.object()
.keys({
- protocol: Joi.string()
- .valid('http', 'https')
- .default('http'),
- hostname: Joi.string()
- .hostname()
- .default('localhost'),
+ protocol: Joi.string().valid('http', 'https').default('http'),
+ hostname: Joi.string().hostname().default('localhost'),
port: Joi.number(),
auth: Joi.string().regex(/^[^:]+:.+$/, 'username and password separated by a colon'),
username: Joi.string(),
@@ -66,33 +62,21 @@ export const schema = Joi.object()
suiteFiles: Joi.object()
.keys({
- include: Joi.array()
- .items(Joi.string())
- .default([]),
- exclude: Joi.array()
- .items(Joi.string())
- .default([]),
+ include: Joi.array().items(Joi.string()).default([]),
+ exclude: Joi.array().items(Joi.string()).default([]),
})
.default(),
suiteTags: Joi.object()
.keys({
- include: Joi.array()
- .items(Joi.string())
- .default([]),
- exclude: Joi.array()
- .items(Joi.string())
- .default([]),
+ include: Joi.array().items(Joi.string()).default([]),
+ exclude: Joi.array().items(Joi.string()).default([]),
})
.default(),
- services: Joi.object()
- .pattern(ID_PATTERN, Joi.func().required())
- .default(),
+ services: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(),
- pageObjects: Joi.object()
- .pattern(ID_PATTERN, Joi.func().required())
- .default(),
+ pageObjects: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(),
timeouts: Joi.object()
.keys({
@@ -135,9 +119,7 @@ export const schema = Joi.object()
browser: Joi.object()
.keys({
- type: Joi.string()
- .valid('chrome', 'firefox', 'ie', 'msedge')
- .default('chrome'),
+ type: Joi.string().valid('chrome', 'firefox', 'ie', 'msedge').default('chrome'),
logPollingMs: Joi.number().default(100),
})
@@ -210,9 +192,7 @@ export const schema = Joi.object()
.default(),
// definition of apps that work with `common.navigateToApp()`
- apps: Joi.object()
- .pattern(ID_PATTERN, appUrlPartsSchema())
- .default(),
+ apps: Joi.object().pattern(ID_PATTERN, appUrlPartsSchema()).default(),
// settings for the esArchiver module
esArchiver: Joi.object()
diff --git a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts
index be033e063fb9d..fdf8b3c0ddfa8 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts
@@ -39,7 +39,7 @@ export class FailureMetadata {
);
}
- lifecycle.beforeEachRunnable.add(runnable => {
+ lifecycle.beforeEachRunnable.add((runnable) => {
this.currentRunnable = runnable;
});
}
@@ -57,7 +57,7 @@ export class FailureMetadata {
}
addMessages(messages: string[]) {
- this.add(current => ({
+ this.add((current) => ({
messages: [...(Array.isArray(current.messages) ? current.messages : []), ...messages],
}));
}
@@ -76,7 +76,7 @@ export class FailureMetadata {
const slash = prefix.endsWith('/') ? '' : '/';
const urlPath = Path.relative(REPO_ROOT, repoPath)
.split(Path.sep)
- .map(c => encodeURIComponent(c))
+ .map((c) => encodeURIComponent(c))
.join('/');
if (urlPath.startsWith('..')) {
@@ -91,7 +91,7 @@ export class FailureMetadata {
url,
};
- this.add(current => ({
+ this.add((current) => ({
screenshots: [...(Array.isArray(current.screenshots) ? current.screenshots : []), screenshot],
}));
diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts
index 22b7363454361..ce242d44009f2 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts
@@ -57,7 +57,7 @@ export class LifecycleEvent {
}
try {
- await Promise.all(this.handlers.map(async fn => await fn(...args)));
+ await Promise.all(this.handlers.map(async (fn) => await fn(...args)));
} finally {
this.afterSubj.next(undefined);
if (this.options.singular) {
diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts
index 94dd76884f2ca..d17c5503c42f8 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts
@@ -104,7 +104,7 @@ describe('without randomness', () => {
const handler = jest.fn(async () => {
order.push('handler start');
- await new Promise(resolve => setTimeout(resolve, 100));
+ await new Promise((resolve) => setTimeout(resolve, 100));
order.push('handler done');
});
phase.add(handler);
@@ -124,10 +124,10 @@ describe('without randomness', () => {
const phase = new LifecyclePhase({ singular: true });
const beforeNotifs: Array> = [];
- phase.before$.pipe(materialize()).subscribe(n => beforeNotifs.push(n));
+ phase.before$.pipe(materialize()).subscribe((n) => beforeNotifs.push(n));
const afterNotifs: Array> = [];
- phase.after$.pipe(materialize()).subscribe(n => afterNotifs.push(n));
+ phase.after$.pipe(materialize()).subscribe((n) => afterNotifs.push(n));
await phase.trigger();
expect(beforeNotifs).toMatchInlineSnapshot(`
diff --git a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts
index 26a0e9617a7c7..588e32b5d274c 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts
@@ -22,7 +22,7 @@ const globalLoadPath: Array<{ ident: string; description: string }> = [];
function getPath(startAt = 0) {
return globalLoadPath
.slice(startAt)
- .map(step => step.description)
+ .map((step) => step.description)
.join(' -> ');
}
@@ -49,7 +49,7 @@ function addPathToMessage(message: string, startAt?: number) {
* @return {Any} the value produced by load()
*/
export function loadTracer(ident: any, description: string, load: () => Promise | void) {
- const isCircular = globalLoadPath.find(step => step.ident === ident);
+ const isCircular = globalLoadPath.find((step) => step.ident === ident);
if (isCircular) {
throw new Error(addPathToMessage(`Circular reference to "${description}"`));
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js
index 5c08d566d3d73..ecf8f7af87ed8 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js
@@ -31,7 +31,7 @@ export function createAssignmentProxy(object, interceptor) {
get(target, property) {
if (property === 'revertProxiedAssignments') {
- return function() {
+ return function () {
for (const [property, value] of originalValues) {
object[property] = value;
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js
index 1cac852a7e713..5d3d8fe7d759b 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js
@@ -57,12 +57,12 @@ export function decorateMochaUi(lifecycle, context) {
throw new Error(`Unexpected arguments to ${name}(${argumentsList.join(', ')})`);
}
- argumentsList[1] = function() {
+ argumentsList[1] = function () {
before(async () => {
await lifecycle.beforeTestSuite.trigger(this);
});
- this.tags = tags => {
+ this.tags = (tags) => {
this._tags = [].concat(this._tags || [], tags);
};
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js
index 302d43fac3e61..f7aaabd5a4495 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js
@@ -30,7 +30,7 @@
export function filterSuitesByTags({ log, mocha, include, exclude }) {
mocha.excludedTests = [];
// collect all the tests from some suite, including it's children
- const collectTests = suite =>
+ const collectTests = (suite) =>
suite.suites.reduce((acc, s) => acc.concat(collectTests(s)), suite.tests);
// if include tags were provided, filter the tree once to
@@ -38,8 +38,10 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) {
if (include.length) {
log.info('Only running suites (and their sub-suites) if they include the tag(s):', include);
- const isIncluded = suite => (!suite._tags ? false : suite._tags.some(t => include.includes(t)));
- const isChildIncluded = suite => suite.suites.some(s => isIncluded(s) || isChildIncluded(s));
+ const isIncluded = (suite) =>
+ !suite._tags ? false : suite._tags.some((t) => include.includes(t));
+ const isChildIncluded = (suite) =>
+ suite.suites.some((s) => isIncluded(s) || isChildIncluded(s));
(function recurse(parentSuite) {
const children = parentSuite.suites;
@@ -73,7 +75,7 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) {
if (exclude.length) {
log.info('Filtering out any suites that include the tag(s):', exclude);
- const isNotExcluded = suite => !suite._tags || !suite._tags.some(t => exclude.includes(t));
+ const isNotExcluded = (suite) => !suite._tags || !suite._tags.some((t) => exclude.includes(t));
(function recurse(parentSuite) {
const children = parentSuite.suites;
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js
index 9901f62ae71cf..6ecfadfd25d6d 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js
@@ -26,21 +26,21 @@ import Test from 'mocha/lib/test';
import { filterSuitesByTags } from './filter_suites_by_tags';
function setup({ include, exclude }) {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
const history = [];
const mocha = new Mocha({
reporter: class {
constructor(runner) {
- runner.on('hook', hook => {
+ runner.on('hook', (hook) => {
history.push(`hook: ${hook.fullTitle()}`);
});
- runner.on('pass', test => {
+ runner.on('pass', (test) => {
history.push(`test: ${test.fullTitle()}`);
});
- runner.on('suite', suite => {
+ runner.on('suite', (suite) => {
history.push(`suite: ${suite.fullTitle()}`);
});
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js
index 6ee65b1b7e394..5c23be6361866 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js
@@ -32,7 +32,7 @@ import { decorateMochaUi } from './decorate_mocha_ui';
* @return {undefined} - mutates mocha, no return value
*/
export const loadTestFiles = ({ mocha, log, lifecycle, providers, paths, updateBaselines }) => {
- const innerLoadTestFile = path => {
+ const innerLoadTestFile = (path) => {
if (typeof path !== 'string' || !isAbsolute(path)) {
throw new TypeError('loadTestFile() only accepts absolute paths');
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js
index 0e8c1bc121e15..90bea1c3aa293 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js
@@ -54,7 +54,7 @@ export function MochaReporterProvider({ getService }) {
if (config.get('junit.enabled') && config.get('junit.reportName')) {
setupJUnitReportGeneration(runner, {
reportName: config.get('junit.reportName'),
- getTestMetadata: t => failureMetadata.get(t),
+ getTestMetadata: (t) => failureMetadata.get(t),
});
}
}
@@ -76,7 +76,7 @@ export function MochaReporterProvider({ getService }) {
new ToolingLogTextWriter({
level: 'debug',
writeTo: {
- write: line => {
+ write: (line) => {
// if the current runnable is a beforeEach hook then
// `runner.suite` is set to the suite that defined the
// hook, rather than the suite executing, so instead we
@@ -104,7 +104,7 @@ export function MochaReporterProvider({ getService }) {
log.write('');
};
- onHookStart = hook => {
+ onHookStart = (hook) => {
log.write(`-> ${colors.suite(hook.title)}`);
log.indent(2);
};
@@ -113,7 +113,7 @@ export function MochaReporterProvider({ getService }) {
log.indent(-2);
};
- onSuiteStart = suite => {
+ onSuiteStart = (suite) => {
if (!suite.root) {
log.write('-: ' + colors.suite(suite.title));
}
@@ -127,28 +127,28 @@ export function MochaReporterProvider({ getService }) {
}
};
- onTestStart = test => {
+ onTestStart = (test) => {
log.write(`-> ${test.title}`);
log.indent(2);
};
- onTestEnd = test => {
+ onTestEnd = (test) => {
snapshotLogsForRunnable(test);
log.indent(-2);
};
- onPending = test => {
+ onPending = (test) => {
log.write('-> ' + colors.pending(test.title));
log.indent(2);
};
- onPass = test => {
+ onPass = (test) => {
const time = colors.speed(test.speed, ` (${ms(test.duration)})`);
const pass = colors.pass(`${symbols.ok} pass`);
log.write(`- ${pass} ${time} "${test.fullTitle()}"`);
};
- onFail = runnable => {
+ onFail = (runnable) => {
// NOTE: this is super gross
//
// - I started by trying to extract the Base.list() logic from mocha
@@ -173,8 +173,8 @@ export function MochaReporterProvider({ getService }) {
// drop the first two lines, (empty + test title)
.slice(2)
// move leading colors behind leading spaces
- .map(line => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1'))
- .map(line => ` ${line}`)
+ .map((line) => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1'))
+ .map((line) => ` ${line}`)
.join('\n')
);
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts
index 654f588fda858..a23a5fb1407a0 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts
@@ -39,7 +39,7 @@ export async function runTests(lifecycle: Lifecycle, mocha: Mocha) {
if (!runComplete) runner.abort();
});
- return new Promise(resolve => {
+ return new Promise((resolve) => {
const respond = () => resolve(runner.failures);
// if there are no tests, mocha.run() is sync
diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js
index 61851cece0e8f..3ac7a50cd28ea 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js
+++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js
@@ -42,7 +42,7 @@ export async function setupMocha(lifecycle, log, config, providers) {
});
// global beforeEach hook in root suite triggers before all others
- mocha.suite.beforeEach('global before each', async function() {
+ mocha.suite.beforeEach('global before each', async function () {
await lifecycle.beforeEachTest.trigger(this.currentTest);
});
@@ -62,15 +62,15 @@ export async function setupMocha(lifecycle, log, config, providers) {
filterSuitesByTags({
log,
mocha,
- include: config.get('suiteFiles.include').map(file => relative(REPO_ROOT, file)),
- exclude: config.get('suiteFiles.exclude').map(file => relative(REPO_ROOT, file)),
+ include: config.get('suiteFiles.include').map((file) => relative(REPO_ROOT, file)),
+ exclude: config.get('suiteFiles.exclude').map((file) => relative(REPO_ROOT, file)),
});
filterSuitesByTags({
log,
mocha,
- include: config.get('suiteTags.include').map(tag => tag.replace(/-\d+$/, '')),
- exclude: config.get('suiteTags.exclude').map(tag => tag.replace(/-\d+$/, '')),
+ include: config.get('suiteTags.include').map((tag) => tag.replace(/-\d+$/, '')),
+ exclude: config.get('suiteTags.exclude').map((tag) => tag.replace(/-\d+$/, '')),
});
return mocha;
diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts
index 7bb1b2bc153c1..2d5644fbad290 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts
@@ -34,7 +34,7 @@ export const createAsyncInstance = (
): AsyncInstance => {
let instance: T | symbol = INITIALIZING;
- const initPromise = promiseForValue.then(v => (instance = v));
+ const initPromise = promiseForValue.then((v) => (instance = v));
const loadingTarget = {
init() {
return initPromise;
diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
index f9ad86be634fc..c58747e07dcf4 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
@@ -37,7 +37,7 @@ export class ProviderCollection {
public getPageObjects = (names: string[]) => {
const pageObjects: Record = {};
- names.forEach(name => (pageObjects[name] = this.getPageObject(name)));
+ names.forEach((name) => (pageObjects[name] = this.getPageObject(name)));
return pageObjects;
};
@@ -78,7 +78,7 @@ export class ProviderCollection {
}
private findProvider(type: string, name: string) {
- return this.providers.find(p => p.type === type && p.name === name);
+ return this.providers.find((p) => p.type === type && p.name === name);
}
private getProvider(type: string, name: string) {
diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts
index be8e25f102b09..a29b220bc603b 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts
@@ -21,7 +21,7 @@ export type Providers = ReturnType;
export type Provider = Providers extends Array ? X : unknown;
export function readProviderSpec(type: string, providers: Record any>) {
- return Object.keys(providers).map(name => {
+ return Object.keys(providers).map((name) => {
return {
type,
name,
diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts
index 93a87f3496b54..1967e98306d42 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts
@@ -23,7 +23,7 @@ import { ToolingLog } from '@kbn/dev-utils';
function printArgs(args: any[]): string {
return args
- .map(arg => {
+ .map((arg) => {
if (typeof arg === 'string' || typeof arg === 'number' || arg instanceof Date) {
return inspect(arg);
}
@@ -42,7 +42,7 @@ export function createVerboseInstance(
name: string,
instance: { [k: string]: any; [i: number]: any }
) {
- if (!log.getWriters().some(l => (l as any).level.flags.verbose)) {
+ if (!log.getWriters().some((l) => (l as any).level.flags.verbose)) {
return instance;
}
@@ -54,7 +54,7 @@ export function createVerboseInstance(
return value;
}
- return function(this: any, ...args: any[]) {
+ return function (this: any, ...args: any[]) {
log.verbose(`${name}.${prop}(${printArgs(args)})`);
log.indent(2);
diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
index b6c2c0a6d511d..f879408bf2beb 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
@@ -145,8 +145,8 @@ describe('SuiteTracker', () => {
const { suiteTracker } = await runLifecycleWithMocks([root, parent, withTests]);
const suites = suiteTracker.getAllFinishedSuites();
- const finishedRoot = suites.find(s => s.title === 'root');
- const finishedWithTests = suites.find(s => s.title !== 'root');
+ const finishedRoot = suites.find((s) => s.title === 'root');
+ const finishedWithTests = suites.find((s) => s.title !== 'root');
expect(finishedRoot).toBeTruthy();
expect(finishedRoot?.hasTests).toBeFalsy();
diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts
index 8967251ea78de..b346be2d58dad 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts
@@ -70,7 +70,7 @@ export class SuiteTracker {
const config = relative(REPO_ROOT, configPathAbsolute);
- lifecycle.beforeTestSuite.add(suite => {
+ lifecycle.beforeTestSuite.add((suite) => {
const tracked = this.getTracked(suite);
tracked.startTime = new Date();
});
@@ -92,7 +92,7 @@ export class SuiteTracker {
lifecycle.testFailure.add(handleFailure);
lifecycle.testHookFailure.add(handleFailure);
- lifecycle.afterTestSuite.add(suite => {
+ lifecycle.afterTestSuite.add((suite) => {
const tracked = this.getTracked(suite);
tracked.endTime = new Date();
diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js
index 7d2414305de8e..94d510915d8e5 100644
--- a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js
+++ b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js
@@ -73,8 +73,8 @@ const options = {
export function displayHelp() {
const helpOptions = Object.keys(options)
- .filter(name => name !== '_')
- .map(name => {
+ .filter((name) => name !== '_')
+ .map((name) => {
const option = options[name];
return {
...option,
@@ -82,7 +82,7 @@ export function displayHelp() {
default: option.defaultHelp || '',
};
})
- .map(option => {
+ .map((option) => {
return `--${option.usage.padEnd(28)} ${option.desc} ${option.default}`;
})
.join(`\n `);
@@ -149,7 +149,7 @@ export function processOptions(userOptions, defaultConfigPaths) {
return {
...userOptions,
- configs: configs.map(c => resolve(c)),
+ configs: configs.map((c) => resolve(c)),
createLogger,
extraKbnOpts: userOptions._,
};
diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js
index 27335739d290e..cf49fc77e479f 100644
--- a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js
+++ b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js
@@ -30,7 +30,7 @@ import { processOptions, displayHelp } from './args';
* if no config option is passed
*/
export async function runTestsCli(defaultConfigPaths) {
- await runCli(displayHelp, async userOptions => {
+ await runCli(displayHelp, async (userOptions) => {
const options = processOptions(userOptions, defaultConfigPaths);
await runTests(options);
});
diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js
index c221ad42fcad1..e604e86de8b3a 100644
--- a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js
+++ b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js
@@ -45,8 +45,8 @@ const options = {
export function displayHelp() {
const helpOptions = Object.keys(options)
- .filter(name => name !== '_')
- .map(name => {
+ .filter((name) => name !== '_')
+ .map((name) => {
const option = options[name];
return {
...option,
@@ -54,7 +54,7 @@ export function displayHelp() {
default: option.defaultHelp || '',
};
})
- .map(option => {
+ .map((option) => {
return `--${option.usage.padEnd(30)} ${option.desc} ${option.default}`;
})
.join(`\n `);
diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js
index 5716441798aa4..d4499ee76e313 100644
--- a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js
+++ b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js
@@ -27,7 +27,7 @@ import { processOptions, displayHelp } from './args';
* if no config option is passed
*/
export async function startServersCli(defaultConfigPath) {
- await runCli(displayHelp, async userOptions => {
+ await runCli(displayHelp, async (userOptions) => {
const options = processOptions(userOptions, defaultConfigPath);
await startServers(options);
});
diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.js b/packages/kbn-test/src/functional_tests/lib/run_cli.js
index 56f6f36f5388f..51a970e1a305d 100644
--- a/packages/kbn-test/src/functional_tests/lib/run_cli.js
+++ b/packages/kbn-test/src/functional_tests/lib/run_cli.js
@@ -53,12 +53,7 @@ export async function runCli(getHelpText, run) {
if (!(error instanceof CliError)) {
// first line in the stack trace is the message, skip it as we log it directly and color it red
if (error.stack) {
- console.log(
- error.stack
- .split('\n')
- .slice(1)
- .join('\n')
- );
+ console.log(error.stack.split('\n').slice(1).join('\n'));
} else {
console.log(' (no stack trace)');
}
diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js
index 235f50f0d9dd7..959f965917530 100644
--- a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js
+++ b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js
@@ -25,7 +25,7 @@ const mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(() => {});
const actualProcessArgv = process.argv;
-const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
beforeEach(() => {
process.argv = actualProcessArgv.slice(0, 2);
@@ -72,7 +72,7 @@ it('waits for promise returned from run function to resolve before resolving', a
let resolveMockRun;
const mockRun = jest.fn().mockImplementation(
() =>
- new Promise(resolve => {
+ new Promise((resolve) => {
resolveMockRun = resolve;
})
);
diff --git a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js
index 5f58190078f0d..3d174791fffc1 100644
--- a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js
+++ b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js
@@ -63,7 +63,7 @@ export async function runElasticsearch({ config, options }) {
function getRelativeCertificateAuthorityPath(esConfig = []) {
const caConfig = esConfig.find(
- config => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0
+ (config) => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0
);
return caConfig ? caConfig.split('=')[1] : undefined;
}
diff --git a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js
index a5744d6498801..fb9f8f7a52408 100644
--- a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js
+++ b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js
@@ -58,9 +58,9 @@ function collectCliArgs(config, { installDir, extraKbnOpts }) {
return pipe(
serverArgs,
- args => (installDir ? args.filter(a => a !== '--oss') : args),
- args => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]),
- args => args.concat(extraKbnOpts || [])
+ (args) => (installDir ? args.filter((a) => a !== '--oss') : args),
+ (args) => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]),
+ (args) => args.concat(extraKbnOpts || [])
);
}
@@ -79,7 +79,7 @@ function filterCliArgs(args) {
// the current val. If so, skip this val.
if (
!allowsDuplicate(val) &&
- findIndexFrom(args, ++ind, opt => opt.split('=')[0] === val.split('=')[0]) > -1
+ findIndexFrom(args, ++ind, (opt) => opt.split('=')[0] === val.split('=')[0]) > -1
) {
return acc;
}
@@ -112,7 +112,7 @@ function isBasePathSettingOverridden(args, val, ind) {
const basePathKeys = ['--no-base-path', '--server.basePath'];
if (basePathKeys.includes(key)) {
- if (findIndexFrom(args, ++ind, opt => basePathKeys.includes(opt.split('=')[0])) > -1) {
+ if (findIndexFrom(args, ++ind, (opt) => basePathKeys.includes(opt.split('=')[0])) > -1) {
return true;
}
}
diff --git a/packages/kbn-test/src/functional_tests/tasks.js b/packages/kbn-test/src/functional_tests/tasks.js
index 8645923a13d30..7d4fc84d47bda 100644
--- a/packages/kbn-test/src/functional_tests/tasks.js
+++ b/packages/kbn-test/src/functional_tests/tasks.js
@@ -34,7 +34,7 @@ import {
import { readConfigFile } from '../functional_test_runner/lib';
-const makeSuccessMessage = options => {
+const makeSuccessMessage = (options) => {
const installDirFlag = options.installDir ? ` --kibana-install-dir=${options.installDir}` : '';
return (
@@ -92,7 +92,7 @@ export async function runTests(options) {
continue;
}
- await withProcRunner(log, async procs => {
+ await withProcRunner(log, async (procs) => {
const config = await readConfigFile(log, configPath);
let es;
@@ -128,7 +128,7 @@ export async function startServers(options) {
log,
};
- await withProcRunner(log, async procs => {
+ await withProcRunner(log, async (procs) => {
const config = await readConfigFile(log, options.config);
const es = await runElasticsearch({ config, options: opts });
diff --git a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js
index 6edd0a551ebd0..00a11432dd9e8 100644
--- a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js
+++ b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js
@@ -49,8 +49,8 @@ describe('dev/mocha/junit report generation', () => {
});
mocha.addFile(resolve(PROJECT_DIR, 'test.js'));
- await new Promise(resolve => mocha.run(resolve));
- const report = await fcb(cb =>
+ await new Promise((resolve) => mocha.run(resolve));
+ const report = await fcb((cb) =>
parseString(readFileSync(makeJunitReportPath(PROJECT_DIR, 'test')), cb)
);
diff --git a/packages/kbn-test/src/mocha/junit_report_generation.js b/packages/kbn-test/src/mocha/junit_report_generation.js
index b56741b48d367..7e39c32ee4db8 100644
--- a/packages/kbn-test/src/mocha/junit_report_generation.js
+++ b/packages/kbn-test/src/mocha/junit_report_generation.js
@@ -39,26 +39,26 @@ export function setupJUnitReportGeneration(runner, options = {}) {
const stats = {};
const results = [];
- const getDuration = node =>
+ const getDuration = (node) =>
node.startTime && node.endTime ? ((node.endTime - node.startTime) / 1000).toFixed(3) : null;
- const findAllTests = suite =>
+ const findAllTests = (suite) =>
suite.suites.reduce((acc, suite) => acc.concat(findAllTests(suite)), suite.tests);
- const setStartTime = node => {
+ const setStartTime = (node) => {
node.startTime = dateNow();
};
- const setEndTime = node => {
+ const setEndTime = (node) => {
node.endTime = dateNow();
};
- const getFullTitle = node => {
+ const getFullTitle = (node) => {
const parentTitle = node.parent && getFullTitle(node.parent);
return parentTitle ? `${parentTitle} ${node.title}` : node.title;
};
- const getPath = node => {
+ const getPath = (node) => {
if (node.file) {
return relative(rootDirectory, node.file);
}
@@ -75,7 +75,7 @@ export function setupJUnitReportGeneration(runner, options = {}) {
runner.on('hook', setStartTime);
runner.on('hook end', setEndTime);
runner.on('test', setStartTime);
- runner.on('pass', node => results.push({ node }));
+ runner.on('pass', (node) => results.push({ node }));
runner.on('pass', setEndTime);
runner.on('fail', (node, error) => results.push({ failed: true, error, node }));
runner.on('fail', setEndTime);
@@ -89,16 +89,16 @@ export function setupJUnitReportGeneration(runner, options = {}) {
}
// filter out just the failures
- const failures = results.filter(result => result.failed);
+ const failures = results.filter((result) => result.failed);
// any failure that isn't for a test is for a hook
- const failedHooks = failures.filter(result => !allTests.includes(result.node));
+ const failedHooks = failures.filter((result) => !allTests.includes(result.node));
// mocha doesn't emit 'pass' or 'fail' when it skips a test
// or a test is pending, so we find them ourselves
const skippedResults = allTests
- .filter(node => node.pending || !results.find(result => result.node === node))
- .map(node => ({ skipped: true, node }));
+ .filter((node) => node.pending || !results.find((result) => result.node === node))
+ .map((node) => ({ skipped: true, node }));
const builder = xmlBuilder.create(
'testsuites',
@@ -124,7 +124,7 @@ export function setupJUnitReportGeneration(runner, options = {}) {
});
}
- [...results, ...skippedResults].forEach(result => {
+ [...results, ...skippedResults].forEach((result) => {
const el = addTestcaseEl(result.node);
if (result.failed) {
diff --git a/packages/kbn-test/src/mocha/run_mocha_cli.js b/packages/kbn-test/src/mocha/run_mocha_cli.js
index 77f40aded1d7f..3c77fef963a76 100644
--- a/packages/kbn-test/src/mocha/run_mocha_cli.js
+++ b/packages/kbn-test/src/mocha/run_mocha_cli.js
@@ -85,7 +85,7 @@ export function runMochaCli() {
],
}
)
- .forEach(file => {
+ .forEach((file) => {
process.argv.push(file);
});
}
diff --git a/packages/kbn-ui-framework/Gruntfile.js b/packages/kbn-ui-framework/Gruntfile.js
index cf0c1643055eb..177fd1f153155 100644
--- a/packages/kbn-ui-framework/Gruntfile.js
+++ b/packages/kbn-ui-framework/Gruntfile.js
@@ -26,7 +26,7 @@ const debounce = require('lodash/function/debounce');
const platform = require('os').platform();
const isPlatformWindows = /^win/.test(platform);
-module.exports = function(grunt) {
+module.exports = function (grunt) {
grunt.initConfig({
clean: {
target: ['target'],
@@ -62,7 +62,7 @@ module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('prodBuild', ['clean:target', 'copy:makeProdBuild', 'babel:prodBuild']);
- grunt.registerTask('docSiteBuild', function() {
+ grunt.registerTask('docSiteBuild', function () {
const done = this.async();
const serverCmd = {
@@ -94,17 +94,17 @@ module.exports = function(grunt) {
uiFrameworkServerBuild.then(done);
});
- grunt.registerTask('docSiteStart', function() {
+ grunt.registerTask('docSiteStart', function () {
const done = this.async();
Promise.all([uiFrameworkWatch(), uiFrameworkServerStart()]).then(done);
});
- grunt.registerTask('compileCssLight', function() {
+ grunt.registerTask('compileCssLight', function () {
const done = this.async();
uiFrameworkCompileLight().then(done);
});
- grunt.registerTask('compileCssDark', function() {
+ grunt.registerTask('compileCssDark', function () {
const done = this.async();
uiFrameworkCompileDark().then(done);
});
@@ -146,19 +146,19 @@ module.exports = function(grunt) {
const src = 'src/kui_light.scss';
const dest = 'dist/kui_light.css';
- return new Promise(resolve => {
+ return new Promise((resolve) => {
sass.render(
{
file: src,
},
- function(error, result) {
+ function (error, result) {
if (error) {
grunt.log.error(error);
}
postcss([postcssConfig])
.process(result.css, { from: src, to: dest })
- .then(result => {
+ .then((result) => {
grunt.file.write(dest, result.css);
if (result.map) {
@@ -176,19 +176,19 @@ module.exports = function(grunt) {
const src = 'src/kui_dark.scss';
const dest = 'dist/kui_dark.css';
- return new Promise(resolve => {
+ return new Promise((resolve) => {
sass.render(
{
file: src,
},
- function(error, result) {
+ function (error, result) {
if (error) {
grunt.log.error(error);
}
postcss([postcssConfig])
.process(result.css, { from: src, to: dest })
- .then(result => {
+ .then((result) => {
grunt.file.write(dest, result.css);
if (result.map) {
diff --git a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js
index 205be7920aa60..1836d00af4ab3 100644
--- a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js
+++ b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js
@@ -25,7 +25,7 @@ export const registerSection = (id, name) => ({
name,
});
-export const unregisterSection = id => ({
+export const unregisterSection = (id) => ({
type: ActionTypes.UNREGISTER_SECTION,
id,
});
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js
index f5845becbe77f..41aeb74d24b6b 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js
@@ -19,4 +19,4 @@
import React from 'react';
-export const GuideCode = props => {props.children}
;
+export const GuideCode = (props) => {props.children}
;
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js
index b1d2f8e031f7c..b387a89b7072c 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js
@@ -65,7 +65,7 @@ export class GuideCodeViewer extends Component {
'is-code-viewer-open': this.props.isOpen,
});
- const codeSections = this.props.source.map(sourceObject =>
+ const codeSections = this.props.source.map((sourceObject) =>
this.renderSection(sourceObject.type, sourceObject.code)
);
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js
index 93470ac6de128..d968e014370f8 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js
@@ -68,7 +68,7 @@ export class GuideDemo extends Component {
});
return (
- (this.content = c)} {...rest}>
+
(this.content = c)} {...rest}>
{children}
);
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js
index b49880e0e3bfa..62d1e3ac8bedd 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js
@@ -19,7 +19,7 @@
import React from 'react';
-export const GuideLink = props => (
+export const GuideLink = (props) => (
{props.children}
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js
index f31a3b10eef4e..49225c96ba5e5 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js
@@ -120,7 +120,7 @@ export class GuideNav extends Component {
});
const componentNavItems = this.props.components
- .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1)
+ .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1)
.map((item, index) => {
const icon = item.hasReact ?
: undefined;
return (
@@ -135,7 +135,7 @@ export class GuideNav extends Component {
});
const sandboxNavItems = this.props.sandboxes
- .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1)
+ .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1)
.map((item, index) => {
const icon = item.hasReact ?
: undefined;
return (
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js
index 5d8e6993abe4e..0a7442fce4723 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js
@@ -21,7 +21,7 @@ import { connect } from 'react-redux';
import { getSections } from '../../store';
import { GuidePage } from './guide_page';
-const mapStateToProps = state => ({
+const mapStateToProps = (state) => ({
sections: getSections(state),
});
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js
index bd7dc0705c6d9..9aeca1b30e03d 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js
@@ -20,7 +20,7 @@
import PropTypes from 'prop-types';
import React from 'react';
-export const GuidePageSideNav = props => {
+export const GuidePageSideNav = (props) => {
return (
{props.title}
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js
index 26c68dfe87951..820e4728da86d 100644
--- a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js
+++ b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js
@@ -19,4 +19,4 @@
import React from 'react';
-export const GuideText = props =>
{props.children}
;
+export const GuideText = (props) =>
{props.children}
;
diff --git a/packages/kbn-ui-framework/doc_site/src/index.js b/packages/kbn-ui-framework/doc_site/src/index.js
index 5473024ae93c9..f7f1df059a041 100644
--- a/packages/kbn-ui-framework/doc_site/src/index.js
+++ b/packages/kbn-ui-framework/doc_site/src/index.js
@@ -58,16 +58,16 @@ const routes = [
];
// Update document title with route name.
-const onRouteEnter = route => {
+const onRouteEnter = (route) => {
const leafRoute = route.routes[route.routes.length - 1];
document.title = leafRoute.name
? `Kibana UI Framework - ${leafRoute.name}`
: 'Kibana UI Framework';
};
-const syncTitleWithRoutes = routesList => {
+const syncTitleWithRoutes = (routesList) => {
if (!routesList) return;
- routesList.forEach(route => {
+ routesList.forEach((route) => {
route.onEnter = onRouteEnter; // eslint-disable-line no-param-reassign
if (route.indexRoute) {
// Index routes have a weird relationship with their "parent" routes,
diff --git a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js
index 32912d5eb9c86..510a7fea7a026 100644
--- a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js
+++ b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js
@@ -159,14 +159,14 @@ export default {
return allRoutes;
},
getPreviousRoute: function getPreviousRoute(routeName) {
- const index = allRoutes.findIndex(item => {
+ const index = allRoutes.findIndex((item) => {
return item.name === routeName;
});
return index >= 0 ? allRoutes[index - 1] : undefined;
},
getNextRoute: function getNextRoute(routeName) {
- const index = allRoutes.findIndex(item => {
+ const index = allRoutes.findIndex((item) => {
return item.name === routeName;
});
diff --git a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js
index f016857ff4414..2e0678f569774 100644
--- a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js
+++ b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js
@@ -32,7 +32,7 @@ function one(str) {
}
function each(items, src, dest) {
- return items.map(item => {
+ return items.map((item) => {
const _item = item;
_item[dest] = one(_item[src]);
return _item;
diff --git a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js
index 6b61c009c5186..a86580903de68 100644
--- a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js
+++ b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js
@@ -40,7 +40,7 @@ export default function sectionsReducer(state = defaultState, action) {
case ActionTypes.UNREGISTER_SECTION: {
const sections = state.sections.slice();
- const index = sections.findIndex(section => section.id === action.id);
+ const index = sections.findIndex((section) => section.id === action.id);
sections.splice(index, 1);
return {
diff --git a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js
index a71b2ff28ee65..9f2f1dec56055 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js
@@ -36,7 +36,7 @@ import BarThreeSections from './bar_three_sections';
import barThreeSectionsSource from '!!raw-loader!./bar_three_sections';
const barThreeSectionsHtml = renderToHtml(BarThreeSections);
-export default props => (
+export default (props) => (
(
);
diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js
index 0717459151584..88edfc5242564 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js
@@ -59,7 +59,7 @@ import CheckBox from './check_box';
import checkBoxSource from '!!raw-loader!./check_box';
const checkBoxHtml = renderToHtml(CheckBox);
-export default props => (
+export default (props) => (
- this.handleChange(event, 'value1')}>
+ this.handleChange(event, 'value1')}
+ >
Apple
Bread
Cheese
@@ -44,7 +47,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value2')}
+ onChange={(event) => this.handleChange(event, 'value2')}
isDisabled
>
Disabled
@@ -52,7 +55,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value3')}
+ onChange={(event) => this.handleChange(event, 'value3')}
isInvalid
>
Invalid
@@ -60,7 +63,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value4')}
+ onChange={(event) => this.handleChange(event, 'value4')}
size="small"
>
Small
@@ -68,7 +71,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value5')}
+ onChange={(event) => this.handleChange(event, 'value5')}
size="large"
>
Large
diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js
index b56051071a6da..0d4e876d996a2 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js
@@ -40,38 +40,38 @@ class KuiTextAreaExample extends Component {
this.handleChange(event, 'value1')}
+ onChange={(event) => this.handleChange(event, 'value1')}
/>
this.handleChange(event, 'value2')}
+ onChange={(event) => this.handleChange(event, 'value2')}
/>
this.handleChange(event, 'value3')}
+ onChange={(event) => this.handleChange(event, 'value3')}
/>
this.handleChange(event, 'value4')}
+ onChange={(event) => this.handleChange(event, 'value4')}
/>
this.handleChange(event, 'value5')}
+ onChange={(event) => this.handleChange(event, 'value5')}
/>
this.handleChange(event, 'value6')}
+ onChange={(event) => this.handleChange(event, 'value6')}
/>
);
diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js
index aba16bae1269b..65c7fa765a359 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js
@@ -33,7 +33,7 @@ class KuiTextAreaNonResizableExample extends Component {
return (
this.handleChange(event, 'value1')}
+ onChange={(event) => this.handleChange(event, 'value1')}
isNonResizable
/>
);
diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js
index a3cebcb07bf2b..5bb3fabe22fa5 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js
@@ -40,39 +40,39 @@ class KuiTextInputExample extends Component {
this.handleChange(event, 'value1')}
+ onChange={(event) => this.handleChange(event, 'value1')}
/>
this.handleChange(event, 'value2')}
+ onChange={(event) => this.handleChange(event, 'value2')}
/>
this.handleChange(event, 'value3')}
+ onChange={(event) => this.handleChange(event, 'value3')}
/>
this.handleChange(event, 'value4')}
+ onChange={(event) => this.handleChange(event, 'value4')}
/>
this.handleChange(event, 'value5')}
+ onChange={(event) => this.handleChange(event, 'value5')}
/>
this.handleChange(event, 'value6')}
+ onChange={(event) => this.handleChange(event, 'value6')}
/>
);
diff --git a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js
index 9c76a8b3a1d3a..7b1a5d2785cac 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js
@@ -28,7 +28,7 @@ import FieldGroup from './field_group';
import fieldGroupSource from '!!raw-loader!./field_group';
const fieldGroupHtml = renderToHtml(FieldGroup);
-export default props => (
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
item.title.toLowerCase(),
+ getValue: (item) => item.title.toLowerCase(),
isAscending: true,
},
{
name: 'description',
- getValue: item => item.description.toLowerCase(),
+ getValue: (item) => item.description.toLowerCase(),
isAscending: true,
},
],
@@ -70,7 +70,7 @@ export class FluidTable extends Component {
);
}
- onSort = prop => {
+ onSort = (prop) => {
this.sortableProperties.sortOn(prop);
this.setState({
@@ -79,7 +79,7 @@ export class FluidTable extends Component {
};
renderRows() {
- return this.items.map(item => (
+ return this.items.map((item) => (
{item.title}
diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js
index fece33c16980a..38eaa7b396ef5 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js
@@ -137,7 +137,7 @@ export class ListingTable extends Component {
];
}
- onItemSelectionChanged = selectedRowIds => {
+ onItemSelectionChanged = (selectedRowIds) => {
this.setState({ selectedRowIds });
};
diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table.js b/packages/kbn-ui-framework/doc_site/src/views/table/table.js
index 45f6e389e7234..0c55d1dc5ed51 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/table/table.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/table/table.js
@@ -85,12 +85,12 @@ export class Table extends Component {
[
{
name: 'title',
- getValue: item => item.title.toLowerCase(),
+ getValue: (item) => item.title.toLowerCase(),
isAscending: true,
},
{
name: 'status',
- getValue: item => item.status.toLowerCase(),
+ getValue: (item) => item.status.toLowerCase(),
isAscending: true,
},
],
@@ -98,7 +98,7 @@ export class Table extends Component {
);
}
- onSort = prop => {
+ onSort = (prop) => {
this.sortableProperties.sortOn(prop);
this.setState({
@@ -106,35 +106,35 @@ export class Table extends Component {
});
};
- toggleItem = item => {
- this.setState(previousState => {
+ toggleItem = (item) => {
+ this.setState((previousState) => {
const rowToSelectedStateMap = new Map(previousState.rowToSelectedStateMap);
rowToSelectedStateMap.set(item, !rowToSelectedStateMap.get(item));
return { rowToSelectedStateMap };
});
};
- isItemChecked = item => {
+ isItemChecked = (item) => {
return this.state.rowToSelectedStateMap.get(item);
};
- togglePopover = item => {
- this.setState(previousState => {
+ togglePopover = (item) => {
+ this.setState((previousState) => {
const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap);
rowToOpenActionsPopoverMap.set(item, !rowToOpenActionsPopoverMap.get(item));
return { rowToOpenActionsPopoverMap };
});
};
- closePopover = item => {
- this.setState(previousState => {
+ closePopover = (item) => {
+ this.setState((previousState) => {
const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap);
rowToOpenActionsPopoverMap.set(item, false);
return { rowToOpenActionsPopoverMap };
});
};
- isPopoverOpen = item => {
+ isPopoverOpen = (item) => {
return this.state.rowToOpenActionsPopoverMap.get(item);
};
@@ -146,7 +146,7 @@ export class Table extends Component {
renderRows() {
const rows = [];
- this.items.forEach(item => {
+ this.items.forEach((item) => {
const classes = classNames({
'kuiTableRowCell--wrap': item.isWrapped,
});
diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js
index 9ed449ea9767b..07e328c4e5e83 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js
@@ -52,7 +52,7 @@ import { ListingTableLoadingItems } from './listing_table_loading_items';
import listingTableLoadingItemsSource from '!!raw-loader!./listing_table_loading_items'; // eslint-disable-line import/default
const listingTableLoadingItemsHtml = renderToHtml(ListingTableLoadingItems);
-export default props => (
+export default (props) => (
{
+ onSelectedTabChanged = (id) => {
this.setState({
selectedTabId: id,
});
diff --git a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js
index 0d3663167520e..125fd0fb53ae3 100644
--- a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js
+++ b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js
@@ -35,7 +35,7 @@ import Tabs from './tabs';
import tabsSource from '!!raw-loader!./tabs';
const tabsHtml = renderToHtml(Tabs);
-export default props => (
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
(
+export default (props) => (
diff --git a/packages/kbn-ui-framework/generator-kui/app/component.js b/packages/kbn-ui-framework/generator-kui/app/component.js
index 1cf03b89d54f7..bcb561f6fa729 100644
--- a/packages/kbn-ui-framework/generator-kui/app/component.js
+++ b/packages/kbn-ui-framework/generator-kui/app/component.js
@@ -39,7 +39,7 @@ module.exports = class extends Generator {
},
],
},
- ]).then(answers => {
+ ]).then((answers) => {
this.config = answers;
});
}
diff --git a/packages/kbn-ui-framework/generator-kui/app/documentation.js b/packages/kbn-ui-framework/generator-kui/app/documentation.js
index c2735f1ce978b..3cbc0263789c6 100644
--- a/packages/kbn-ui-framework/generator-kui/app/documentation.js
+++ b/packages/kbn-ui-framework/generator-kui/app/documentation.js
@@ -43,7 +43,7 @@ module.exports = class extends Generator {
},
],
},
- ]).then(answers => {
+ ]).then((answers) => {
this.config = answers;
});
}
diff --git a/packages/kbn-ui-framework/generator-kui/component/index.js b/packages/kbn-ui-framework/generator-kui/component/index.js
index 3abf84b7a2073..56c49fe6fa471 100644
--- a/packages/kbn-ui-framework/generator-kui/component/index.js
+++ b/packages/kbn-ui-framework/generator-kui/component/index.js
@@ -49,7 +49,7 @@ module.exports = class extends Generator {
type: 'confirm',
default: true,
},
- ]).then(answers => {
+ ]).then((answers) => {
this.config = answers;
if (!answers.name || !answers.name.trim()) {
@@ -62,7 +62,7 @@ module.exports = class extends Generator {
writing() {
const config = this.config;
- const writeComponent = isStatelessFunction => {
+ const writeComponent = (isStatelessFunction) => {
const componentName = utils.makeComponentName(config.name);
const cssClassName = utils.lowerCaseFirstLetter(componentName);
const fileName = config.name;
diff --git a/packages/kbn-ui-framework/generator-kui/documentation/index.js b/packages/kbn-ui-framework/generator-kui/documentation/index.js
index daaaf32c8fd22..03f8d5813b251 100644
--- a/packages/kbn-ui-framework/generator-kui/documentation/index.js
+++ b/packages/kbn-ui-framework/generator-kui/documentation/index.js
@@ -47,7 +47,7 @@ module.exports = class extends Generator {
name: 'folderName',
type: 'input',
store: true,
- default: answers => answers.name,
+ default: (answers) => answers.name,
});
prompts.push({
@@ -58,7 +58,7 @@ module.exports = class extends Generator {
});
}
- return this.prompt(prompts).then(answers => {
+ return this.prompt(prompts).then((answers) => {
this.config = answers;
});
}
diff --git a/packages/kbn-ui-framework/generator-kui/utils.js b/packages/kbn-ui-framework/generator-kui/utils.js
index c51393121777e..0f7b910451767 100644
--- a/packages/kbn-ui-framework/generator-kui/utils.js
+++ b/packages/kbn-ui-framework/generator-kui/utils.js
@@ -21,7 +21,7 @@ function makeComponentName(str, usePrefix = true) {
const words = str.split('_');
const componentName = words
- .map(function(word) {
+ .map(function (word) {
return upperCaseFirstLetter(word);
})
.join('');
@@ -30,13 +30,13 @@ function makeComponentName(str, usePrefix = true) {
}
function lowerCaseFirstLetter(str) {
- return str.replace(/\w\S*/g, function(txt) {
+ return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toLowerCase() + txt.substr(1);
});
}
function upperCaseFirstLetter(str) {
- return str.replace(/\w\S*/g, function(txt) {
+ return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1);
});
}
diff --git a/packages/kbn-ui-framework/src/components/button/button.js b/packages/kbn-ui-framework/src/components/button/button.js
index b18ca87a27b1e..e95b9209343ae 100644
--- a/packages/kbn-ui-framework/src/components/button/button.js
+++ b/packages/kbn-ui-framework/src/components/button/button.js
@@ -133,7 +133,7 @@ const KuiLinkButton = ({
children,
...rest
}) => {
- const onClick = e => {
+ const onClick = (e) => {
if (disabled) {
e.preventDefault();
}
diff --git a/packages/kbn-ui-framework/src/components/button/button.test.js b/packages/kbn-ui-framework/src/components/button/button.test.js
index d664ce85f9a37..db74308d9de8d 100644
--- a/packages/kbn-ui-framework/src/components/button/button.test.js
+++ b/packages/kbn-ui-framework/src/components/button/button.test.js
@@ -48,7 +48,7 @@ describe('KuiButton', () => {
describe('Props', () => {
describe('buttonType', () => {
- BUTTON_TYPES.forEach(buttonType => {
+ BUTTON_TYPES.forEach((buttonType) => {
describe(`${buttonType}`, () => {
test(`renders the ${buttonType} class`, () => {
const $button = render( );
diff --git a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js
index 49eaff03efd40..630d5598cab9c 100644
--- a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js
+++ b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js
@@ -22,7 +22,7 @@ import React from 'react';
import classNames from 'classnames';
-const KuiButtonGroup = props => {
+const KuiButtonGroup = (props) => {
const classes = classNames('kuiButtonGroup', {
'kuiButtonGroup--united': props.isUnited,
});
diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js
index 736e349396b7e..256d7c4a1786e 100644
--- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js
+++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js
@@ -24,7 +24,7 @@ import classNames from 'classnames';
const ICON_TYPES = ['create', 'delete', 'previous', 'next', 'loading', 'settings', 'menu'];
-const KuiButtonIcon = props => {
+const KuiButtonIcon = (props) => {
const typeToClassNameMap = {
create: 'fa-plus',
delete: 'fa-trash',
diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js
index e270f26644393..553fef1432487 100644
--- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js
+++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js
@@ -33,7 +33,7 @@ describe('KuiButtonIcon', () => {
describe('Props', () => {
describe('type', () => {
- ICON_TYPES.forEach(type => {
+ ICON_TYPES.forEach((type) => {
describe(`${type}`, () => {
test(`renders the ${type} class`, () => {
const $buttonIcon = render( );
diff --git a/packages/kbn-ui-framework/src/components/button/link_button.test.js b/packages/kbn-ui-framework/src/components/button/link_button.test.js
index 4f77af3febf54..4489dc1a46d2a 100644
--- a/packages/kbn-ui-framework/src/components/button/link_button.test.js
+++ b/packages/kbn-ui-framework/src/components/button/link_button.test.js
@@ -49,7 +49,7 @@ describe('KuiLinkButton', () => {
describe('Props', () => {
describe('buttonType', () => {
- BUTTON_TYPES.forEach(buttonType => {
+ BUTTON_TYPES.forEach((buttonType) => {
describe(`${buttonType}`, () => {
test(`renders the ${buttonType} class`, () => {
const $button = render(
diff --git a/packages/kbn-ui-framework/src/components/button/submit_button.test.js b/packages/kbn-ui-framework/src/components/button/submit_button.test.js
index fc30523649c12..77ad9eb40c55f 100644
--- a/packages/kbn-ui-framework/src/components/button/submit_button.test.js
+++ b/packages/kbn-ui-framework/src/components/button/submit_button.test.js
@@ -47,7 +47,7 @@ describe('KuiSubmitButton', () => {
describe('Props', () => {
describe('buttonType', () => {
- BUTTON_TYPES.forEach(buttonType => {
+ BUTTON_TYPES.forEach((buttonType) => {
describe(`${buttonType}`, () => {
test(`renders the ${buttonType} class`, () => {
const $button = render( );
diff --git a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js
index f6245ef654bb9..8ce225038b8b7 100644
--- a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js
+++ b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js
@@ -27,7 +27,7 @@ import { DIRECTIONS, KuiCollapseButton } from './collapse_button';
describe('KuiCollapseButton', () => {
describe('Props', () => {
describe('direction', () => {
- DIRECTIONS.forEach(direction => {
+ DIRECTIONS.forEach((direction) => {
describe(`${direction}`, () => {
test(`renders the ${direction} class`, () => {
const component = ;
diff --git a/packages/kbn-ui-framework/src/components/form/select/select.test.js b/packages/kbn-ui-framework/src/components/form/select/select.test.js
index 81c1e4d9a0ff2..056bc88016d51 100644
--- a/packages/kbn-ui-framework/src/components/form/select/select.test.js
+++ b/packages/kbn-ui-framework/src/components/form/select/select.test.js
@@ -77,7 +77,7 @@ describe('KuiSelect', () => {
});
describe('size', () => {
- SELECT_SIZE.forEach(size => {
+ SELECT_SIZE.forEach((size) => {
test(`renders ${size}`, () => {
const component = {}} />;
diff --git a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js
index eddb655094088..d87b7b76789de 100644
--- a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js
+++ b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js
@@ -87,7 +87,7 @@ describe('KuiTextArea', () => {
});
describe('size', () => {
- TEXTAREA_SIZE.forEach(size => {
+ TEXTAREA_SIZE.forEach((size) => {
test(`renders ${size}`, () => {
const component = {}} />;
diff --git a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js
index 9ef3c420bba68..41d3726582fb5 100644
--- a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js
+++ b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js
@@ -89,7 +89,7 @@ describe('KuiTextInput', () => {
});
describe('size', () => {
- TEXTINPUT_SIZE.forEach(size => {
+ TEXTINPUT_SIZE.forEach((size) => {
test(`renders ${size}`, () => {
const component = {}} />;
diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js
index 3478c159cbbb9..82b2afba7bc40 100644
--- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js
+++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js
@@ -57,7 +57,7 @@ export function KuiListingTable({
if (areAllRowsSelected()) {
onItemSelectionChanged([]);
} else {
- onItemSelectionChanged(rows.map(row => row.id));
+ onItemSelectionChanged(rows.map((row) => row.id));
}
}
diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js
index b47a1275d1565..2607caeba0dbb 100644
--- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js
+++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js
@@ -22,7 +22,7 @@ import { mount, shallow } from 'enzyme';
import { requiredProps, takeMountedSnapshot } from '../../../test';
import { KuiListingTable } from './listing_table';
-const getProps = customProps => {
+const getProps = (customProps) => {
const defaultProps = {
header: ['Breed', 'Description'],
rows: [
@@ -59,20 +59,14 @@ test('renders KuiListingTable', () => {
test('selecting a row calls onItemSelectionChanged', () => {
const props = getProps();
const component = shallow( );
- component
- .find('KuiListingTableRow')
- .at(1)
- .prop('onSelectionChanged')('1');
+ component.find('KuiListingTableRow').at(1).prop('onSelectionChanged')('1');
expect(props.onItemSelectionChanged).toHaveBeenCalledWith(['1']);
});
test('selectedRowIds is preserved when onItemSelectionChanged is called', () => {
const props = getProps({ selectedRowIds: ['3'] });
const component = shallow( );
- component
- .find('KuiListingTableRow')
- .at(0)
- .prop('onSelectionChanged')('1');
+ component.find('KuiListingTableRow').at(0).prop('onSelectionChanged')('1');
expect(props.onItemSelectionChanged).toHaveBeenCalledWith(expect.arrayContaining(['1', '3']));
});
diff --git a/packages/kbn-ui-framework/src/components/typography/typography.test.js b/packages/kbn-ui-framework/src/components/typography/typography.test.js
index 7155483354e48..b341a2c442fb2 100644
--- a/packages/kbn-ui-framework/src/components/typography/typography.test.js
+++ b/packages/kbn-ui-framework/src/components/typography/typography.test.js
@@ -35,7 +35,7 @@ describe('KuiTitle', () => {
});
describe('renders size', () => {
- SIZES.forEach(size => {
+ SIZES.forEach((size) => {
test(size, () => {
const component = render(
diff --git a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js
index 6537f0d157997..164910341f027 100644
--- a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js
+++ b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js
@@ -27,5 +27,5 @@ import uuid from 'uuid';
*/
export function htmlIdGenerator(idPrefix) {
const prefix = idPrefix || uuid.v1();
- return suffix => `${prefix}_${suffix || uuid.v1()}`;
+ return (suffix) => `${prefix}_${suffix || uuid.v1()}`;
}
diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js
index 4b08b20b68cbf..6c445bf8b747b 100644
--- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js
+++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js
@@ -73,7 +73,7 @@ export class SortableProperties {
* @returns {SortableProperty|undefined}
*/
getSortablePropertyByName(propertyName) {
- return this.sortableProperties.find(property => property.name === propertyName);
+ return this.sortableProperties.find((property) => property.name === propertyName);
}
/**
diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js
index 223724edac8b8..0037787830ac2 100644
--- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js
+++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js
@@ -22,19 +22,19 @@ import { SortableProperties } from './sortable_properties';
describe('SortProperties', () => {
const name = {
name: 'name',
- getValue: bird => bird.name,
+ getValue: (bird) => bird.name,
isAscending: true,
};
const size = {
name: 'size',
- getValue: bird => bird.size,
+ getValue: (bird) => bird.size,
isAscending: false,
};
const color = {
name: 'color',
- getValue: bird => bird.color,
+ getValue: (bird) => bird.color,
isAscending: true,
};
diff --git a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js
index 4d87930d434b5..d4567ebb800fe 100644
--- a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js
+++ b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js
@@ -23,7 +23,7 @@
* containing both React components and HTML elements. This function removes the React components,
* leaving only HTML elements in the snapshot.
*/
-export const takeMountedSnapshot = mountedComponent => {
+export const takeMountedSnapshot = (mountedComponent) => {
const html = mountedComponent.html();
const template = document.createElement('template');
template.innerHTML = html; // eslint-disable-line no-unsanitized/property
diff --git a/packages/kbn-ui-shared-deps/entry.js b/packages/kbn-ui-shared-deps/entry.js
index f19271de8ad27..26efd174f4e39 100644
--- a/packages/kbn-ui-shared-deps/entry.js
+++ b/packages/kbn-ui-shared-deps/entry.js
@@ -48,9 +48,16 @@ export const ElasticCharts = require('@elastic/charts');
export const ElasticEui = require('@elastic/eui');
export const ElasticEuiLibServices = require('@elastic/eui/lib/services');
export const ElasticEuiLibServicesFormat = require('@elastic/eui/lib/services/format');
-export const ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_light.json');
-export const ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_dark.json');
export const ElasticEuiChartsTheme = require('@elastic/eui/dist/eui_charts_theme');
+export let ElasticEuiLightTheme;
+export let ElasticEuiDarkTheme;
+if (window.__kbnThemeVersion__ === 'v7') {
+ ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_light.json');
+ ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_dark.json');
+} else {
+ ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_amsterdam_light.json');
+ ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_amsterdam_dark.json');
+}
// massive deps that we should really get rid of or reduce in size substantially
export const ElasticsearchBrowser = require('elasticsearch-browser/elasticsearch.js');
diff --git a/packages/kbn-ui-shared-deps/index.d.ts b/packages/kbn-ui-shared-deps/index.d.ts
index b829c87d91c4a..cd659b6f04853 100644
--- a/packages/kbn-ui-shared-deps/index.d.ts
+++ b/packages/kbn-ui-shared-deps/index.d.ts
@@ -42,11 +42,21 @@ export const baseCssDistFilename: string;
*/
export const darkCssDistFilename: string;
+/**
+ * Filename of the dark-theme css file in the distributable directory
+ */
+export const darkV8CssDistFilename: string;
+
/**
* Filename of the light-theme css file in the distributable directory
*/
export const lightCssDistFilename: string;
+/**
+ * Filename of the light-theme css file in the distributable directory
+ */
+export const lightV8CssDistFilename: string;
+
/**
* Externals mapping inteded to be used in a webpack config
*/
diff --git a/packages/kbn-ui-shared-deps/index.js b/packages/kbn-ui-shared-deps/index.js
index 42ed08259ac8f..9aec3ab359924 100644
--- a/packages/kbn-ui-shared-deps/index.js
+++ b/packages/kbn-ui-shared-deps/index.js
@@ -23,8 +23,10 @@ exports.distDir = Path.resolve(__dirname, 'target');
exports.jsDepFilenames = ['kbn-ui-shared-deps.@elastic.js'];
exports.jsFilename = 'kbn-ui-shared-deps.js';
exports.baseCssDistFilename = 'kbn-ui-shared-deps.css';
-exports.lightCssDistFilename = 'kbn-ui-shared-deps.light.css';
-exports.darkCssDistFilename = 'kbn-ui-shared-deps.dark.css';
+exports.lightCssDistFilename = 'kbn-ui-shared-deps.v7.light.css';
+exports.lightV8CssDistFilename = 'kbn-ui-shared-deps.v8.light.css';
+exports.darkCssDistFilename = 'kbn-ui-shared-deps.v7.dark.css';
+exports.darkV8CssDistFilename = 'kbn-ui-shared-deps.v8.dark.css';
exports.externals = {
// stateful deps
angular: '__kbnSharedDeps__.Angular',
diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json
index eddc215db5a62..d34fe3624ab26 100644
--- a/packages/kbn-ui-shared-deps/package.json
+++ b/packages/kbn-ui-shared-deps/package.json
@@ -6,7 +6,7 @@
"scripts": {
"build": "node scripts/build",
"kbn:bootstrap": "node scripts/build --dev",
- "kbn:watch": "node scripts/build --watch"
+ "kbn:watch": "node scripts/build --dev --watch"
},
"dependencies": {
"@elastic/charts": "19.2.0",
diff --git a/packages/kbn-ui-shared-deps/public_path_loader.js b/packages/kbn-ui-shared-deps/public_path_loader.js
index 6b7a27c9ca52b..fceebd6d6b3a1 100644
--- a/packages/kbn-ui-shared-deps/public_path_loader.js
+++ b/packages/kbn-ui-shared-deps/public_path_loader.js
@@ -17,7 +17,7 @@
* under the License.
*/
-module.exports = function(source) {
+module.exports = function (source) {
const options = this.query;
return `__webpack_public_path__ = window.__kbnPublicPath__['${options.key}'];${source}`;
};
diff --git a/packages/kbn-ui-shared-deps/scripts/build.js b/packages/kbn-ui-shared-deps/scripts/build.js
index e45b3dbed1748..af4e3481e624d 100644
--- a/packages/kbn-ui-shared-deps/scripts/build.js
+++ b/packages/kbn-ui-shared-deps/scripts/build.js
@@ -38,7 +38,7 @@ run(
);
/** @param {webpack.Stats} stats */
- const onCompilationComplete = stats => {
+ const onCompilationComplete = (stats) => {
const took = Math.round((stats.endTime - stats.startTime) / 1000);
if (!stats.hasErrors() && !stats.hasWarnings()) {
@@ -55,7 +55,7 @@ run(
};
if (flags.watch) {
- compiler.hooks.done.tap('report on stats', stats => {
+ compiler.hooks.done.tap('report on stats', (stats) => {
try {
onCompilationComplete(stats);
} catch (error) {
@@ -72,7 +72,7 @@ run(
log.info('Running webpack compilation...');
});
- compiler.watch({}, error => {
+ compiler.watch({}, (error) => {
if (error) {
log.error('Fatal webpack error');
log.error(error);
diff --git a/packages/kbn-ui-shared-deps/webpack.config.js b/packages/kbn-ui-shared-deps/webpack.config.js
index ca913d0f16417..7295f2e88c530 100644
--- a/packages/kbn-ui-shared-deps/webpack.config.js
+++ b/packages/kbn-ui-shared-deps/webpack.config.js
@@ -32,14 +32,22 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({
mode: dev ? 'development' : 'production',
entry: {
'kbn-ui-shared-deps': './entry.js',
- 'kbn-ui-shared-deps.dark': [
+ 'kbn-ui-shared-deps.v7.dark': [
'@elastic/eui/dist/eui_theme_dark.css',
'@elastic/charts/dist/theme_only_dark.css',
],
- 'kbn-ui-shared-deps.light': [
+ 'kbn-ui-shared-deps.v7.light': [
'@elastic/eui/dist/eui_theme_light.css',
'@elastic/charts/dist/theme_only_light.css',
],
+ 'kbn-ui-shared-deps.v8.dark': [
+ '@elastic/eui/dist/eui_theme_amsterdam_dark.css',
+ '@elastic/charts/dist/theme_only_dark.css',
+ ],
+ 'kbn-ui-shared-deps.v8.light': [
+ '@elastic/eui/dist/eui_theme_amsterdam_light.css',
+ '@elastic/charts/dist/theme_only_light.css',
+ ],
},
context: __dirname,
devtool: dev ? '#cheap-source-map' : false,
@@ -47,7 +55,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({
path: UiSharedDeps.distDir,
filename: '[name].js',
sourceMapFilename: '[file].map',
- devtoolModuleFilenameTemplate: info =>
+ devtoolModuleFilenameTemplate: (info) =>
`kbn-ui-shared-deps/${Path.relative(REPO_ROOT, info.absoluteResourcePath)}`,
library: '__kbnSharedDeps__',
},
@@ -96,7 +104,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({
cacheGroups: {
'kbn-ui-shared-deps.@elastic': {
name: 'kbn-ui-shared-deps.@elastic',
- test: m => m.resource && m.resource.includes('@elastic'),
+ test: (m) => m.resource && m.resource.includes('@elastic'),
chunks: 'all',
enforce: true,
},
diff --git a/packages/kbn-utility-types/index.ts b/packages/kbn-utility-types/index.ts
index 657d9f547de66..9a8a81460f410 100644
--- a/packages/kbn-utility-types/index.ts
+++ b/packages/kbn-utility-types/index.ts
@@ -82,9 +82,9 @@ export type Values = T extends any[] ? T[number] : T extends object ? T[keyof
* type. This is necessary in the case of distinguishing one collection from
* another.
*/
-export type UnionToIntersection = (U extends any
-? (k: U) => void
-: never) extends (k: infer I) => void
+export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (
+ k: infer I
+) => void
? I
: never;
diff --git a/scripts/es.js b/scripts/es.js
index 4f15cc11801e3..93f1d69350bac 100644
--- a/scripts/es.js
+++ b/scripts/es.js
@@ -32,7 +32,7 @@ kbnEs
'base-path': resolve(__dirname, '../.es'),
ssl: false,
})
- .catch(function(e) {
+ .catch(function (e) {
console.error(e);
process.exitCode = 1;
});
diff --git a/scripts/test_hardening.js b/scripts/test_hardening.js
index c0a20a9ff6cb4..0bc0d1c045ac0 100644
--- a/scripts/test_hardening.js
+++ b/scripts/test_hardening.js
@@ -28,10 +28,10 @@ program
.description(
'Run the tests in test/harden directory. If no files are provided, all files within the directory will be run.'
)
- .action(function(globs) {
+ .action(function (globs) {
if (globs.length === 0) globs.push(path.join('test', 'harden', '*'));
- globs.forEach(function(glob) {
- syncGlob(glob).forEach(function(filename) {
+ globs.forEach(function (glob) {
+ syncGlob(glob).forEach(function (filename) {
if (path.basename(filename)[0] === '_') return;
console.log(process.argv[0], filename);
execFileSync(process.argv[0], [filename], { stdio: 'inherit' });
diff --git a/src/apm.js b/src/apm.js
index e3f4d84d9b523..6c10539c6b7d3 100644
--- a/src/apm.js
+++ b/src/apm.js
@@ -85,7 +85,7 @@ function getConfig(serviceName) {
*/
const isKibanaDistributable = Boolean(build && build.distributable === true);
-module.exports = function(serviceName = name) {
+module.exports = function (serviceName = name) {
if (process.env.kbnWorkerType === 'optmzr') return;
const conf = getConfig(serviceName);
diff --git a/src/cli/cli.js b/src/cli/cli.js
index b6598520352a6..50a8d4c7f7f01 100644
--- a/src/cli/cli.js
+++ b/src/cli/cli.js
@@ -40,13 +40,13 @@ serveCommand(program);
program
.command('help ')
.description('Get the help for a specific command')
- .action(function(cmdName) {
+ .action(function (cmdName) {
const cmd = _.find(program.commands, { _name: cmdName });
if (!cmd) return program.error(`unknown command ${cmdName}`);
cmd.help();
});
-program.command('*', null, { noHelp: true }).action(function(cmd) {
+program.command('*', null, { noHelp: true }).action(function (cmd) {
program.error(`unknown command ${cmd}`);
});
diff --git a/src/cli/cluster/cluster_manager.test.ts b/src/cli/cluster/cluster_manager.test.ts
index 707778861fb59..66f68f815edac 100644
--- a/src/cli/cluster/cluster_manager.test.ts
+++ b/src/cli/cluster/cluster_manager.test.ts
@@ -153,7 +153,7 @@ describe('CLI cluster manager', () => {
const events: Array = [];
delayUntil().subscribe(
() => events.push('next'),
- error => events.push(error),
+ (error) => events.push(error),
() => events.push('complete')
);
diff --git a/src/cli/cluster/cluster_manager.ts b/src/cli/cluster/cluster_manager.ts
index 3b3e4d78320d2..fc94f8d585a02 100644
--- a/src/cli/cluster/cluster_manager.ts
+++ b/src/cli/cluster/cluster_manager.ts
@@ -37,7 +37,7 @@ process.env.kbnWorkerType = 'managr';
const firstAllTrue = (...sources: Array>) =>
Rx.combineLatest(...sources).pipe(
- filter(values => values.every(v => v === true)),
+ filter((values) => values.every((v) => v === true)),
take(1),
mapTo(undefined)
);
@@ -75,7 +75,7 @@ export class ClusterManager {
.pipe(
map(({ state }) => state.phase === 'success' || state.phase === 'issue'),
tap({
- error: error => {
+ error: (error) => {
this.log.bad('New platform optimizer error', error.stack);
process.exit(1);
},
@@ -139,9 +139,9 @@ export class ClusterManager {
.subscribe(this.optimizerReady$);
// broker messages between workers
- this.workers.forEach(worker => {
- worker.on('broadcast', msg => {
- this.workers.forEach(to => {
+ this.workers.forEach((worker) => {
+ worker.on('broadcast', (msg) => {
+ this.workers.forEach((to) => {
if (to !== worker && to.online) {
to.fork!.send(msg);
}
@@ -156,7 +156,7 @@ export class ClusterManager {
this.server.on('reloadLoggingConfigFromServerWorker', () => {
process.emit('message' as any, { reloadLoggingConfig: true } as any);
- this.workers.forEach(worker => {
+ this.workers.forEach((worker) => {
worker.fork!.send({ reloadLoggingConfig: true });
});
});
@@ -182,7 +182,7 @@ export class ClusterManager {
const extraPaths = [...pluginPaths, ...scanDirs];
const pluginInternalDirsIgnore = scanDirs
- .map(scanDir => resolve(scanDir, '*'))
+ .map((scanDir) => resolve(scanDir, '*'))
.concat(pluginPaths)
.reduce(
(acc, path) =>
@@ -212,10 +212,7 @@ export class ClusterManager {
shouldRedirectFromOldBasePath: (path: string) => {
// strip `s/{id}` prefix when checking for need to redirect
if (path.startsWith('s/')) {
- path = path
- .split('/')
- .slice(2)
- .join('/');
+ path = path.split('/').slice(2).join('/');
}
const isApp = path.startsWith('app/');
@@ -253,7 +250,7 @@ export class ClusterManager {
fromRoot('x-pack/legacy/server'),
fromRoot('config'),
...extraPaths,
- ].map(path => resolve(path))
+ ].map((path) => resolve(path))
)
);
diff --git a/src/cli/cluster/run_kbn_optimizer.ts b/src/cli/cluster/run_kbn_optimizer.ts
index e4bd6b98dd2b9..f36ce70f65a45 100644
--- a/src/cli/cluster/run_kbn_optimizer.ts
+++ b/src/cli/cluster/run_kbn_optimizer.ts
@@ -33,9 +33,10 @@ import { LegacyConfig } from '../../core/server/legacy';
export function runKbnOptimizer(opts: Record, config: LegacyConfig) {
const optimizerConfig = OptimizerConfig.create({
repoRoot: REPO_ROOT,
- watch: true,
+ watch: !!opts.watch,
includeCoreBundle: true,
cache: !!opts.cache,
+ dist: !!opts.dist,
oss: !!opts.oss,
examples: !!opts.runExamples,
pluginPaths: config.get('plugins.paths'),
diff --git a/src/cli/cluster/worker.ts b/src/cli/cluster/worker.ts
index c73d3edbf7df7..dc6e6d5676651 100644
--- a/src/cli/cluster/worker.ts
+++ b/src/cli/cluster/worker.ts
@@ -136,7 +136,7 @@ export class Worker extends EventEmitter {
this.processBinder.destroy();
// wait until the cluster reports this fork has exited, then resolve
- await new Promise(resolve => this.once('fork:exit', resolve));
+ await new Promise((resolve) => this.once('fork:exit', resolve));
}
}
@@ -179,7 +179,7 @@ export class Worker extends EventEmitter {
flushChangeBuffer() {
const files = _.unique(this.changes.splice(0));
const prefix = files.length > 1 ? '\n - ' : '';
- return files.reduce(function(list, file) {
+ return files.reduce(function (list, file) {
return `${list || ''}${prefix}"${file}"`;
}, '');
}
@@ -188,7 +188,7 @@ export class Worker extends EventEmitter {
if (this.fork) {
// once "exit" event is received with 0 status, start() is called again
this.shutdown();
- await new Promise(cb => this.once('online', cb));
+ await new Promise((cb) => this.once('online', cb));
return;
}
@@ -214,6 +214,6 @@ export class Worker extends EventEmitter {
this.processBinder.on('exit', () => this.shutdown());
// wait for the fork to report it is online before resolving
- await new Promise(cb => this.once('fork:online', cb));
+ await new Promise((cb) => this.once('fork:online', cb));
}
}
diff --git a/src/cli/command.js b/src/cli/command.js
index 6f083bb2a1fa2..f4781fcab1e20 100644
--- a/src/cli/command.js
+++ b/src/cli/command.js
@@ -23,7 +23,7 @@ import Chalk from 'chalk';
import help from './help';
import { Command } from 'commander';
-Command.prototype.error = function(err) {
+Command.prototype.error = function (err) {
if (err && err.message) err = err.message;
console.log(
@@ -37,7 +37,7 @@ ${help(this, ' ')}
process.exit(64); // eslint-disable-line no-process-exit
};
-Command.prototype.defaultHelp = function() {
+Command.prototype.defaultHelp = function () {
console.log(
`
${help(this, ' ')}
@@ -48,7 +48,7 @@ ${help(this, ' ')}
process.exit(64); // eslint-disable-line no-process-exit
};
-Command.prototype.unknownArgv = function(argv) {
+Command.prototype.unknownArgv = function (argv) {
if (argv) this.__unknownArgv = argv;
return this.__unknownArgv ? this.__unknownArgv.slice(0) : [];
};
@@ -57,11 +57,11 @@ Command.prototype.unknownArgv = function(argv) {
* setup the command to accept arbitrary configuration via the cli
* @return {[type]} [description]
*/
-Command.prototype.collectUnknownOptions = function() {
+Command.prototype.collectUnknownOptions = function () {
const title = `Extra ${this._name} options`;
this.allowUnknownOption();
- this.getUnknownOptions = function() {
+ this.getUnknownOptions = function () {
const opts = {};
const unknowns = this.unknownArgv();
@@ -95,17 +95,17 @@ Command.prototype.collectUnknownOptions = function() {
return this;
};
-Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function(parse, argv) {
+Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function (parse, argv) {
const opts = parse.call(this, argv);
this.unknownArgv(opts.unknown);
return opts;
});
-Command.prototype.action = _.wrap(Command.prototype.action, function(action, fn) {
- return action.call(this, function(...args) {
+Command.prototype.action = _.wrap(Command.prototype.action, function (action, fn) {
+ return action.call(this, function (...args) {
const ret = fn.apply(this, args);
if (ret && typeof ret.then === 'function') {
- ret.then(null, function(e) {
+ ret.then(null, function (e) {
console.log('FATAL CLI ERROR', e.stack);
process.exit(1);
});
diff --git a/src/cli/help.js b/src/cli/help.js
index a2dc638d2b6ee..656944d85b254 100644
--- a/src/cli/help.js
+++ b/src/cli/help.js
@@ -24,7 +24,7 @@ export default function help(command, spaces) {
return command.outputHelp();
}
- const defCmd = _.find(command.commands, function(cmd) {
+ const defCmd = _.find(command.commands, function (cmd) {
return cmd._name === 'serve';
});
@@ -53,12 +53,12 @@ function indent(str, n) {
function commandsSummary(program) {
const cmds = _.compact(
- program.commands.map(function(cmd) {
+ program.commands.map(function (cmd) {
const name = cmd._name;
if (name === '*') return;
const opts = cmd.options.length ? ' [options]' : '';
const args = cmd._args
- .map(function(arg) {
+ .map(function (arg) {
return humanReadableArgName(arg);
})
.join(' ');
@@ -67,11 +67,11 @@ function commandsSummary(program) {
})
);
- const cmdLColWidth = cmds.reduce(function(width, cmd) {
+ const cmdLColWidth = cmds.reduce(function (width, cmd) {
return Math.max(width, cmd[0].length);
}, 0);
- return cmds.reduce(function(help, cmd) {
+ return cmds.reduce(function (help, cmd) {
return `${help || ''}${_.padRight(cmd[0], cmdLColWidth)} ${cmd[1] || ''}\n`;
}, '');
}
diff --git a/src/cli/repl/index.js b/src/cli/repl/index.js
index 37a51b4d1ec9e..0b27fafcef84e 100644
--- a/src/cli/repl/index.js
+++ b/src/cli/repl/index.js
@@ -72,7 +72,7 @@ function prettyPrint(text, o, depth) {
// This lets us handle promises more gracefully than the default REPL,
// which doesn't show the results.
function promiseFriendlyWriter({ displayPrompt, getPrintDepth }) {
- return result => promisePrint(result, displayPrompt, getPrintDepth);
+ return (result) => promisePrint(result, displayPrompt, getPrintDepth);
}
function promisePrint(result, displayPrompt, getPrintDepth) {
@@ -83,8 +83,8 @@ function promisePrint(result, displayPrompt, getPrintDepth) {
Promise.resolve()
.then(() => console.log('Waiting for promise...'))
.then(() => result)
- .then(o => prettyPrint('Promise Resolved: \n', o, depth))
- .catch(err => prettyPrint('Promise Rejected: \n', err, depth))
+ .then((o) => prettyPrint('Promise Resolved: \n', o, depth))
+ .catch((err) => prettyPrint('Promise Rejected: \n', err, depth))
.then(displayPrompt);
return '';
}
diff --git a/src/cli/repl/repl.test.js b/src/cli/repl/repl.test.js
index 9abb43c338290..3a032d415e5f2 100644
--- a/src/cli/repl/repl.test.js
+++ b/src/cli/repl/repl.test.js
@@ -17,7 +17,7 @@
* under the License.
*/
-jest.mock('repl', () => ({ start: opts => ({ opts, context: {} }) }), { virtual: true });
+jest.mock('repl', () => ({ start: (opts) => ({ opts, context: {} }) }), { virtual: true });
describe('repl', () => {
const originalConsoleLog = console.log;
@@ -25,7 +25,7 @@ describe('repl', () => {
beforeEach(() => {
global.console.log = jest.fn();
- require('repl').start = opts => {
+ require('repl').start = (opts) => {
let resetHandler;
const replServer = {
opts,
@@ -188,7 +188,7 @@ describe('repl', () => {
async function waitForPrompt(replServer, fn) {
let resolveDone;
- const done = new Promise(resolve => (resolveDone = resolve));
+ const done = new Promise((resolve) => (resolveDone = resolve));
replServer.displayPrompt = () => {
resolveDone();
};
diff --git a/src/cli/serve/integration_tests/invalid_config.test.ts b/src/cli/serve/integration_tests/invalid_config.test.ts
index da6684fae8cef..fd6fa1bf192fc 100644
--- a/src/cli/serve/integration_tests/invalid_config.test.ts
+++ b/src/cli/serve/integration_tests/invalid_config.test.ts
@@ -29,10 +29,10 @@ interface LogEntry {
type: string;
}
-describe('cli invalid config support', function() {
+describe('cli invalid config support', function () {
it(
'exits with statusCode 64 and logs a single line when config is invalid',
- function() {
+ function () {
// Unused keys only throw once LegacyService starts, so disable migrations so that Core
// will finish the start lifecycle without a running Elasticsearch instance.
const { error, status, stdout } = spawnSync(
@@ -47,9 +47,9 @@ describe('cli invalid config support', function() {
.toString('utf8')
.split('\n')
.filter(Boolean)
- .map(line => JSON.parse(line) as LogEntry)
- .filter(line => line.tags.includes('fatal'))
- .map(obj => ({
+ .map((line) => JSON.parse(line) as LogEntry)
+ .filter((line) => line.tags.includes('fatal'))
+ .map((obj) => ({
...obj,
pid: '## PID ##',
'@timestamp': '## @timestamp ##',
diff --git a/src/cli/serve/integration_tests/reload_logging_config.test.ts b/src/cli/serve/integration_tests/reload_logging_config.test.ts
index 9ad8438c312a1..35391b9b58ecc 100644
--- a/src/cli/serve/integration_tests/reload_logging_config.test.ts
+++ b/src/cli/serve/integration_tests/reload_logging_config.test.ts
@@ -70,7 +70,7 @@ function watchFileUntil(path: string, matcher: RegExp, timeout: number) {
}
function containsJsonOnly(content: string[]) {
- return content.every(line => line.startsWith('{'));
+ return content.every((line) => line.startsWith('{'));
}
function createConfigManager(configPath: string) {
@@ -83,7 +83,7 @@ function createConfigManager(configPath: string) {
};
}
-describe('Server logging configuration', function() {
+describe('Server logging configuration', function () {
let child: undefined | Child.ChildProcess;
beforeEach(() => {
@@ -92,7 +92,7 @@ describe('Server logging configuration', function() {
afterEach(async () => {
if (child !== undefined) {
- const exitPromise = new Promise(resolve => child?.once('exit', resolve));
+ const exitPromise = new Promise((resolve) => child?.once('exit', resolve));
child.kill('SIGKILL');
await exitPromise;
}
@@ -110,7 +110,7 @@ describe('Server logging configuration', function() {
describe('legacy logging', () => {
it(
'should be reloadable via SIGHUP process signaling',
- async function() {
+ async function () {
const configFilePath = Path.resolve(tempDir, 'kibana.yml');
Fs.copyFileSync(legacyConfig, configFilePath);
@@ -123,17 +123,13 @@ describe('Server logging configuration', function() {
]);
const message$ = Rx.fromEvent(child.stdout, 'data').pipe(
- map(messages =>
- String(messages)
- .split('\n')
- .filter(Boolean)
- )
+ map((messages) => String(messages).split('\n').filter(Boolean))
);
await message$
.pipe(
// We know the sighup handler will be registered before this message logged
- filter(messages => messages.some(m => m.includes('setting up root'))),
+ filter((messages) => messages.some((m) => m.includes('setting up root'))),
take(1)
)
.toPromise();
@@ -141,7 +137,7 @@ describe('Server logging configuration', function() {
const lastMessage = await message$.pipe(take(1)).toPromise();
expect(containsJsonOnly(lastMessage)).toBe(true);
- createConfigManager(configFilePath).modify(oldConfig => {
+ createConfigManager(configFilePath).modify((oldConfig) => {
oldConfig.logging.json = false;
return oldConfig;
});
@@ -150,7 +146,7 @@ describe('Server logging configuration', function() {
await message$
.pipe(
- filter(messages => !containsJsonOnly(messages)),
+ filter((messages) => !containsJsonOnly(messages)),
take(1)
)
.toPromise();
@@ -160,7 +156,7 @@ describe('Server logging configuration', function() {
it(
'should recreate file handle on SIGHUP',
- async function() {
+ async function () {
const logPath = Path.resolve(tempDir, 'kibana.log');
const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log');
@@ -188,24 +184,20 @@ describe('Server logging configuration', function() {
describe('platform logging', () => {
it(
'should be reloadable via SIGHUP process signaling',
- async function() {
+ async function () {
const configFilePath = Path.resolve(tempDir, 'kibana.yml');
Fs.copyFileSync(configFileLogConsole, configFilePath);
child = Child.spawn(process.execPath, [kibanaPath, '--oss', '--config', configFilePath]);
const message$ = Rx.fromEvent(child.stdout, 'data').pipe(
- map(messages =>
- String(messages)
- .split('\n')
- .filter(Boolean)
- )
+ map((messages) => String(messages).split('\n').filter(Boolean))
);
await message$
.pipe(
// We know the sighup handler will be registered before this message logged
- filter(messages => messages.some(m => m.includes('setting up root'))),
+ filter((messages) => messages.some((m) => m.includes('setting up root'))),
take(1)
)
.toPromise();
@@ -213,7 +205,7 @@ describe('Server logging configuration', function() {
const lastMessage = await message$.pipe(take(1)).toPromise();
expect(containsJsonOnly(lastMessage)).toBe(true);
- createConfigManager(configFilePath).modify(oldConfig => {
+ createConfigManager(configFilePath).modify((oldConfig) => {
oldConfig.logging.appenders.console.layout.kind = 'pattern';
return oldConfig;
});
@@ -221,7 +213,7 @@ describe('Server logging configuration', function() {
await message$
.pipe(
- filter(messages => !containsJsonOnly(messages)),
+ filter((messages) => !containsJsonOnly(messages)),
take(1)
)
.toPromise();
@@ -230,14 +222,14 @@ describe('Server logging configuration', function() {
);
it(
'should recreate file handle on SIGHUP',
- async function() {
+ async function () {
const configFilePath = Path.resolve(tempDir, 'kibana.yml');
Fs.copyFileSync(configFileLogFile, configFilePath);
const logPath = Path.resolve(tempDir, 'kibana.log');
const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log');
- createConfigManager(configFilePath).modify(oldConfig => {
+ createConfigManager(configFilePath).modify((oldConfig) => {
oldConfig.logging.appenders.file.path = logPath;
return oldConfig;
});
diff --git a/src/cli/serve/read_keystore.js b/src/cli/serve/read_keystore.js
index c17091a11f5c1..cfe02735630f2 100644
--- a/src/cli/serve/read_keystore.js
+++ b/src/cli/serve/read_keystore.js
@@ -30,7 +30,7 @@ export function readKeystore(dataPath = getDataPath()) {
const keys = Object.keys(keystore.data);
const data = {};
- keys.forEach(key => {
+ keys.forEach((key) => {
set(data, key, keystore.data[key]);
});
diff --git a/src/cli/serve/serve.js b/src/cli/serve/serve.js
index eaec8d55f6a56..8bc65f3da7111 100644
--- a/src/cli/serve/serve.js
+++ b/src/cli/serve/serve.js
@@ -52,9 +52,9 @@ const CAN_REPL = canRequire(REPL_PATH);
const XPACK_DIR = resolve(__dirname, '../../../x-pack');
const XPACK_INSTALLED = canRequire(XPACK_DIR);
-const pathCollector = function() {
+const pathCollector = function () {
const paths = [];
- return function(path) {
+ return function (path) {
paths.push(resolve(process.cwd(), path));
return paths;
};
@@ -109,7 +109,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) {
(customElasticsearchHosts.length > 0 && customElasticsearchHosts) || [
'https://localhost:9200',
]
- ).map(hostUrl => {
+ ).map((hostUrl) => {
const parsedUrl = url.parse(hostUrl);
if (parsedUrl.hostname !== 'localhost') {
throw new Error(
@@ -159,7 +159,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) {
return rawConfig;
}
-export default function(program) {
+export default function (program) {
const command = program.command('serve');
command
@@ -213,6 +213,7 @@ export default function(program) {
.option('--dev', 'Run the server with development mode defaults')
.option('--open', 'Open a browser window to the base url after the server is started')
.option('--ssl', 'Run the dev server using HTTPS')
+ .option('--dist', 'Use production assets from kbn/optimizer')
.option(
'--no-base-path',
"Don't put a proxy in front of the dev server, which adds a random basePath"
@@ -222,7 +223,7 @@ export default function(program) {
.option('--no-dev-config', 'Prevents loading the kibana.dev.yml file in --dev mode');
}
- command.action(async function(opts) {
+ command.action(async function (opts) {
if (opts.dev && opts.devConfig !== false) {
try {
const kbnDevConfig = fromRoot('config/kibana.dev.yml');
@@ -255,12 +256,13 @@ export default function(program) {
optimize: !!opts.optimize,
oss: !!opts.oss,
cache: !!opts.cache,
+ dist: !!opts.dist,
},
features: {
isClusterModeSupported: CAN_CLUSTER,
isReplModeSupported: CAN_REPL,
},
- applyConfigOverrides: rawConfig => applyConfigOverrides(rawConfig, opts, unknownOptions),
+ applyConfigOverrides: (rawConfig) => applyConfigOverrides(rawConfig, opts, unknownOptions),
});
});
}
diff --git a/src/cli_keystore/add.test.js b/src/cli_keystore/add.test.js
index 72f15a5439ef0..320581b470c2b 100644
--- a/src/cli_keystore/add.test.js
+++ b/src/cli_keystore/add.test.js
@@ -23,14 +23,14 @@ const mockKeystoreData =
'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ==';
jest.mock('fs', () => ({
- readFileSync: jest.fn().mockImplementation(path => {
+ readFileSync: jest.fn().mockImplementation((path) => {
if (!path.includes('nonexistent')) {
return JSON.stringify(mockKeystoreData);
}
throw { code: 'ENOENT' };
}),
- existsSync: jest.fn().mockImplementation(path => {
+ existsSync: jest.fn().mockImplementation((path) => {
return !path.includes('nonexistent');
}),
writeFileSync: jest.fn(),
diff --git a/src/cli_keystore/cli_keystore.js b/src/cli_keystore/cli_keystore.js
index 7c90d88f7b0cd..e1561b343ef39 100644
--- a/src/cli_keystore/cli_keystore.js
+++ b/src/cli_keystore/cli_keystore.js
@@ -50,13 +50,13 @@ removeCli(program, keystore);
program
.command('help ')
.description('get the help for a specific command')
- .action(function(cmdName) {
+ .action(function (cmdName) {
const cmd = _.find(program.commands, { _name: cmdName });
if (!cmd) return program.error(`unknown command ${cmdName}`);
cmd.help();
});
-program.command('*', null, { noHelp: true }).action(function(cmd) {
+program.command('*', null, { noHelp: true }).action(function (cmd) {
program.error(`unknown command ${cmd}`);
});
diff --git a/src/cli_keystore/create.test.js b/src/cli_keystore/create.test.js
index 01355f51a0c55..33b5aa4bd07d8 100644
--- a/src/cli_keystore/create.test.js
+++ b/src/cli_keystore/create.test.js
@@ -23,14 +23,14 @@ const mockKeystoreData =
'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ==';
jest.mock('fs', () => ({
- readFileSync: jest.fn().mockImplementation(path => {
+ readFileSync: jest.fn().mockImplementation((path) => {
if (!path.includes('foo')) {
return JSON.stringify(mockKeystoreData);
}
throw { code: 'ENOENT' };
}),
- existsSync: jest.fn().mockImplementation(path => {
+ existsSync: jest.fn().mockImplementation((path) => {
return !path.includes('foo');
}),
writeFileSync: jest.fn(),
diff --git a/src/cli_keystore/list.test.js b/src/cli_keystore/list.test.js
index 3fb5014820865..857991b5ae3b9 100644
--- a/src/cli_keystore/list.test.js
+++ b/src/cli_keystore/list.test.js
@@ -23,14 +23,14 @@ const mockKeystoreData =
'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ==';
jest.mock('fs', () => ({
- readFileSync: jest.fn().mockImplementation(path => {
+ readFileSync: jest.fn().mockImplementation((path) => {
if (!path.includes('nonexistent')) {
return JSON.stringify(mockKeystoreData);
}
throw { code: 'ENOENT' };
}),
- existsSync: jest.fn().mockImplementation(path => {
+ existsSync: jest.fn().mockImplementation((path) => {
return !path.includes('nonexistent');
}),
}));
diff --git a/src/cli_plugin/cli.js b/src/cli_plugin/cli.js
index d1cdf983c0da4..da1068b54b4b5 100644
--- a/src/cli_plugin/cli.js
+++ b/src/cli_plugin/cli.js
@@ -43,13 +43,13 @@ removeCommand(program);
program
.command('help ')
.description('get the help for a specific command')
- .action(function(cmdName) {
+ .action(function (cmdName) {
const cmd = _.find(program.commands, { _name: cmdName });
if (!cmd) return program.error(`unknown command ${cmdName}`);
cmd.help();
});
-program.command('*', null, { noHelp: true }).action(function(cmd) {
+program.command('*', null, { noHelp: true }).action(function (cmd) {
program.error(`unknown command ${cmd}`);
});
diff --git a/src/cli_plugin/install/cleanup.js b/src/cli_plugin/install/cleanup.js
index eaa25962ef0e4..f31e028226c27 100644
--- a/src/cli_plugin/install/cleanup.js
+++ b/src/cli_plugin/install/cleanup.js
@@ -21,7 +21,7 @@ import del from 'del';
import fs from 'fs';
export function cleanPrevious(settings, logger) {
- return new Promise(function(resolve, reject) {
+ return new Promise(function (resolve, reject) {
try {
fs.statSync(settings.workingPath);
diff --git a/src/cli_plugin/install/cleanup.test.js b/src/cli_plugin/install/cleanup.test.js
index c6602636cb481..46089f61d5e83 100644
--- a/src/cli_plugin/install/cleanup.test.js
+++ b/src/cli_plugin/install/cleanup.test.js
@@ -24,32 +24,32 @@ import del from 'del';
import { cleanPrevious, cleanArtifacts } from './cleanup';
import Logger from '../lib/logger';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('pluginCleaner', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('pluginCleaner', function () {
const settings = {
workingPath: 'dummy',
};
- describe('cleanPrevious', function() {
+ describe('cleanPrevious', function () {
let errorStub;
let logger;
- beforeEach(function() {
+ beforeEach(function () {
errorStub = sinon.stub();
logger = new Logger(settings);
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
fs.statSync.restore();
del.sync.restore();
});
- it('should resolve if the working path does not exist', function() {
+ it('should resolve if the working path does not exist', function () {
sinon.stub(del, 'sync');
sinon.stub(fs, 'statSync').callsFake(() => {
const error = new Error('ENOENT');
@@ -59,75 +59,75 @@ describe('kibana cli', function() {
return cleanPrevious(settings, logger)
.catch(errorStub)
- .then(function() {
+ .then(function () {
expect(errorStub.called).toBe(false);
});
});
- it('should rethrow any exception except ENOENT from fs.statSync', function() {
+ it('should rethrow any exception except ENOENT from fs.statSync', function () {
sinon.stub(del, 'sync');
sinon.stub(fs, 'statSync').throws(new Error('An Unhandled Error'));
errorStub = sinon.stub();
return cleanPrevious(settings, logger)
.catch(errorStub)
- .then(function() {
+ .then(function () {
expect(errorStub.called).toBe(true);
});
});
- it('should log a message if there was a working directory', function() {
+ it('should log a message if there was a working directory', function () {
sinon.stub(del, 'sync');
sinon.stub(fs, 'statSync');
return cleanPrevious(settings, logger)
.catch(errorStub)
- .then(function() {
+ .then(function () {
expect(logger.log.calledWith('Found previous install attempt. Deleting...')).toBe(
true
);
});
});
- it('should rethrow any exception from del.sync', function() {
+ it('should rethrow any exception from del.sync', function () {
sinon.stub(fs, 'statSync');
sinon.stub(del, 'sync').throws(new Error('I am an error thrown by del'));
errorStub = sinon.stub();
return cleanPrevious(settings, logger)
.catch(errorStub)
- .then(function() {
+ .then(function () {
expect(errorStub.called).toBe(true);
});
});
- it('should resolve if the working path is deleted', function() {
+ it('should resolve if the working path is deleted', function () {
sinon.stub(del, 'sync');
sinon.stub(fs, 'statSync');
return cleanPrevious(settings, logger)
.catch(errorStub)
- .then(function() {
+ .then(function () {
expect(errorStub.called).toBe(false);
});
});
});
- describe('cleanArtifacts', function() {
- beforeEach(function() {});
+ describe('cleanArtifacts', function () {
+ beforeEach(function () {});
- afterEach(function() {
+ afterEach(function () {
del.sync.restore();
});
- it('should attempt to delete the working directory', function() {
+ it('should attempt to delete the working directory', function () {
sinon.stub(del, 'sync');
cleanArtifacts(settings);
expect(del.sync.calledWith(settings.workingPath)).toBe(true);
});
- it('should swallow any errors thrown by del.sync', function() {
+ it('should swallow any errors thrown by del.sync', function () {
sinon.stub(del, 'sync').throws(new Error('Something bad happened.'));
expect(() => cleanArtifacts(settings)).not.toThrow();
diff --git a/src/cli_plugin/install/download.js b/src/cli_plugin/install/download.js
index fc1fe8323520b..10d20367c1b7b 100644
--- a/src/cli_plugin/install/download.js
+++ b/src/cli_plugin/install/download.js
@@ -80,7 +80,7 @@ export function download(settings, logger) {
logger.log(`Attempting to transfer from ${sourceUrl}`);
- return _downloadSingle(settings, logger, sourceUrl).catch(err => {
+ return _downloadSingle(settings, logger, sourceUrl).catch((err) => {
const isUnsupportedProtocol = err instanceof UnsupportedProtocolError;
const isDownloadResourceNotFound = err.message === 'ENOTFOUND';
if (isUnsupportedProtocol || isDownloadResourceNotFound) {
diff --git a/src/cli_plugin/install/download.test.js b/src/cli_plugin/install/download.test.js
index ef924f28a65e7..93e5e414fed74 100644
--- a/src/cli_plugin/install/download.test.js
+++ b/src/cli_plugin/install/download.test.js
@@ -28,8 +28,8 @@ import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } fr
import { join } from 'path';
import http from 'http';
-describe('kibana cli', function() {
- describe('plugin downloader', function() {
+describe('kibana cli', function () {
+ describe('plugin downloader', function () {
const testWorkingPath = join(__dirname, '.test.data.download');
const tempArchiveFilePath = join(testWorkingPath, 'archive.part');
@@ -57,46 +57,44 @@ describe('kibana cli', function() {
throw new Error('expected the promise to reject');
}
- beforeEach(function() {
+ beforeEach(function () {
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
del.sync(testWorkingPath);
Fs.mkdirSync(testWorkingPath, { recursive: true });
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
del.sync(testWorkingPath);
});
- describe('_downloadSingle', function() {
- beforeEach(function() {});
+ describe('_downloadSingle', function () {
+ beforeEach(function () {});
- describe('http downloader', function() {
- it('should throw an ENOTFOUND error for a http ulr that returns 404', function() {
- nock('http://example.com')
- .get('/plugin.tar.gz')
- .reply(404);
+ describe('http downloader', function () {
+ it('should throw an ENOTFOUND error for a http ulr that returns 404', function () {
+ nock('http://example.com').get('/plugin.tar.gz').reply(404);
const sourceUrl = 'http://example.com/plugin.tar.gz';
- return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) {
+ return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) {
expect(err.message).toMatch(/ENOTFOUND/);
expectWorkingPathEmpty();
});
});
- it('should throw an UnsupportedProtocolError for an invalid url', function() {
+ it('should throw an UnsupportedProtocolError for an invalid url', function () {
const sourceUrl = 'i am an invalid url';
- return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) {
+ return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) {
expect(err).toBeInstanceOf(UnsupportedProtocolError);
expectWorkingPathEmpty();
});
});
- it('should download a file from a valid http url', function() {
+ it('should download a file from a valid http url', function () {
const filePath = join(__dirname, '__fixtures__/replies/banana.jpg');
nock('http://example.com')
@@ -109,40 +107,40 @@ describe('kibana cli', function() {
const sourceUrl = 'http://example.com/plugin.zip';
- return _downloadSingle(settings, logger, sourceUrl).then(function() {
+ return _downloadSingle(settings, logger, sourceUrl).then(function () {
expectWorkingPathNotEmpty();
});
});
});
- describe('local file downloader', function() {
- it('should throw an ENOTFOUND error for an invalid local file', function() {
+ describe('local file downloader', function () {
+ it('should throw an ENOTFOUND error for an invalid local file', function () {
const filePath = join(__dirname, '__fixtures__/replies/i-am-not-there.zip');
const sourceUrl = 'file://' + filePath.replace(/\\/g, '/');
- return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) {
+ return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) {
expect(err.message).toMatch(/ENOTFOUND/);
expectWorkingPathEmpty();
});
});
- it('should copy a valid local file', function() {
+ it('should copy a valid local file', function () {
const filePath = join(__dirname, '__fixtures__/replies/banana.jpg');
const sourceUrl = 'file://' + filePath.replace(/\\/g, '/');
- return _downloadSingle(settings, logger, sourceUrl).then(function() {
+ return _downloadSingle(settings, logger, sourceUrl).then(function () {
expectWorkingPathNotEmpty();
});
});
});
});
- describe('_getFilePath', function() {
- it('should decode paths', function() {
+ describe('_getFilePath', function () {
+ it('should decode paths', function () {
expect(_getFilePath('Test%20folder/file.zip')).toBe('Test folder/file.zip');
});
- it('should remove the leading slash from windows paths', function() {
+ it('should remove the leading slash from windows paths', function () {
const platform = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', { value: 'win32' });
@@ -152,8 +150,8 @@ describe('kibana cli', function() {
});
});
- describe('Windows file:// deprecation', function() {
- it('should log a warning if a file:// path is used', function() {
+ describe('Windows file:// deprecation', function () {
+ it('should log a warning if a file:// path is used', function () {
const platform = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', { value: 'win32' });
const logger = {
@@ -169,8 +167,8 @@ describe('kibana cli', function() {
});
});
- describe('download', function() {
- it('should loop through bad urls until it finds a good one.', function() {
+ describe('download', function () {
+ it('should loop through bad urls until it finds a good one.', function () {
const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip');
settings.urls = [
'http://example.com/badfile1.tar.gz',
@@ -190,7 +188,7 @@ describe('kibana cli', function() {
.get('/goodfile.tar.gz')
.replyWithFile(200, filePath);
- return download(settings, logger).then(function() {
+ return download(settings, logger).then(function () {
expect(logger.log.getCall(0).args[0]).toMatch(/badfile1.tar.gz/);
expect(logger.log.getCall(1).args[0]).toMatch(/badfile2.tar.gz/);
expect(logger.log.getCall(2).args[0]).toMatch(/I am a bad uri/);
@@ -199,7 +197,7 @@ describe('kibana cli', function() {
});
});
- it('should stop looping through urls when it finds a good one.', function() {
+ it('should stop looping through urls when it finds a good one.', function () {
const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip');
settings.urls = [
'http://example.com/badfile1.tar.gz',
@@ -221,7 +219,7 @@ describe('kibana cli', function() {
.get('/badfile3.tar.gz')
.reply(404);
- return download(settings, logger).then(function() {
+ return download(settings, logger).then(function () {
for (let i = 0; i < logger.log.callCount; i++) {
expect(logger.log.getCall(i).args[0]).not.toMatch(/badfile3.tar.gz/);
}
@@ -229,7 +227,7 @@ describe('kibana cli', function() {
});
});
- it("should throw an error when it doesn't find a good url.", function() {
+ it("should throw an error when it doesn't find a good url.", function () {
settings.urls = [
'http://example.com/badfile1.tar.gz',
'http://example.com/badfile2.tar.gz',
@@ -247,25 +245,25 @@ describe('kibana cli', function() {
.get('/badfile3.tar.gz')
.reply(404);
- return download(settings, logger).then(shouldReject, function(err) {
+ return download(settings, logger).then(shouldReject, function (err) {
expect(err.message).toMatch(/no valid url specified/i);
expectWorkingPathEmpty();
});
});
- afterAll(function() {
+ afterAll(function () {
nock.cleanAll();
});
});
- describe('proxy support', function() {
+ describe('proxy support', function () {
const proxyPort = 2626;
const proxyUrl = `http://localhost:${proxyPort}`;
let proxyHit = false;
let proxyConnectHit = false;
- const proxy = http.createServer(function(req, res) {
+ const proxy = http.createServer(function (req, res) {
proxyHit = true;
// Our test proxy simply returns an empty 200 response, since we only
// care about the download promise being resolved.
@@ -301,29 +299,29 @@ describe('kibana cli', function() {
.replyWithFile(200, join(__dirname, '__fixtures__/replies/test_plugin.zip'));
}
- beforeAll(function(done) {
+ beforeAll(function (done) {
proxy.listen(proxyPort, done);
});
- beforeEach(function() {
+ beforeEach(function () {
proxyHit = false;
proxyConnectHit = false;
});
- afterEach(function() {
+ afterEach(function () {
delete process.env.http_proxy;
delete process.env.https_proxy;
delete process.env.no_proxy;
});
- it('should use http_proxy env variable', function() {
+ it('should use http_proxy env variable', function () {
process.env.http_proxy = proxyUrl;
settings.urls = ['http://example.com/plugin.zip'];
return download(settings, logger).then(expectProxyHit);
});
- it('should use https_proxy for secure URLs', function() {
+ it('should use https_proxy for secure URLs', function () {
process.env.https_proxy = proxyUrl;
settings.urls = ['https://example.com/plugin.zip'];
@@ -340,7 +338,7 @@ describe('kibana cli', function() {
);
});
- it('should not use http_proxy for HTTPS urls', function() {
+ it('should not use http_proxy for HTTPS urls', function () {
process.env.http_proxy = proxyUrl;
settings.urls = ['https://example.com/plugin.zip'];
@@ -349,7 +347,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should not use https_proxy for HTTP urls', function() {
+ it('should not use https_proxy for HTTP urls', function () {
process.env.https_proxy = proxyUrl;
settings.urls = ['http://example.com/plugin.zip'];
@@ -358,7 +356,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should support domains in no_proxy', function() {
+ it('should support domains in no_proxy', function () {
process.env.http_proxy = proxyUrl;
process.env.no_proxy = 'foo.bar, example.com';
settings.urls = ['http://example.com/plugin.zip'];
@@ -368,7 +366,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should support subdomains in no_proxy', function() {
+ it('should support subdomains in no_proxy', function () {
process.env.http_proxy = proxyUrl;
process.env.no_proxy = 'foo.bar,plugins.example.com';
settings.urls = ['http://plugins.example.com/plugin.zip'];
@@ -378,7 +376,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should accept wildcard subdomains in no_proxy', function() {
+ it('should accept wildcard subdomains in no_proxy', function () {
process.env.http_proxy = proxyUrl;
process.env.no_proxy = 'foo.bar, .example.com';
settings.urls = ['http://plugins.example.com/plugin.zip'];
@@ -388,7 +386,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should support asterisk wildcard no_proxy syntax', function() {
+ it('should support asterisk wildcard no_proxy syntax', function () {
process.env.http_proxy = proxyUrl;
process.env.no_proxy = '*.example.com';
settings.urls = ['http://plugins.example.com/plugin.zip'];
@@ -398,7 +396,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- it('should support implicit ports in no_proxy', function() {
+ it('should support implicit ports in no_proxy', function () {
process.env.https_proxy = proxyUrl;
process.env.no_proxy = 'example.com:443';
settings.urls = ['https://example.com/plugin.zip'];
@@ -408,7 +406,7 @@ describe('kibana cli', function() {
return download(settings, logger).then(expectNoProxyHit);
});
- afterAll(function(done) {
+ afterAll(function (done) {
proxy.close(done);
});
});
diff --git a/src/cli_plugin/install/downloaders/file.js b/src/cli_plugin/install/downloaders/file.js
index eee8ddb21d6dd..56f83b03d5a90 100644
--- a/src/cli_plugin/install/downloaders/file.js
+++ b/src/cli_plugin/install/downloaders/file.js
@@ -43,7 +43,7 @@ async function copyFile({ readStream, writeStream, progress }) {
writeStream.on('error', reject);
// report progress as we transfer
- readStream.on('data', chunk => {
+ readStream.on('data', (chunk) => {
progress.progress(chunk.length);
});
diff --git a/src/cli_plugin/install/downloaders/http.js b/src/cli_plugin/install/downloaders/http.js
index 88dcdabe70dfd..0fc01453f2b4c 100644
--- a/src/cli_plugin/install/downloaders/http.js
+++ b/src/cli_plugin/install/downloaders/http.js
@@ -76,7 +76,7 @@ function downloadResponse({ resp, targetPath, progress }) {
writeStream.on('error', reject);
// report progress as we download
- resp.on('data', chunk => {
+ resp.on('data', (chunk) => {
progress.progress(chunk.length);
});
diff --git a/src/cli_plugin/install/index.test.js b/src/cli_plugin/install/index.test.js
index 6a64a673bb93e..39352f52f20fd 100644
--- a/src/cli_plugin/install/index.test.js
+++ b/src/cli_plugin/install/index.test.js
@@ -20,25 +20,25 @@
import sinon from 'sinon';
import index from './index';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('commander options', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('commander options', function () {
const program = {
- command: function() {
+ command: function () {
return program;
},
- description: function() {
+ description: function () {
return program;
},
- option: function() {
+ option: function () {
return program;
},
- action: function() {
+ action: function () {
return program;
},
};
- it('should define the command', function() {
+ it('should define the command', function () {
sinon.spy(program, 'command');
index(program);
@@ -47,7 +47,7 @@ describe('kibana cli', function() {
program.command.restore();
});
- it('should define the description', function() {
+ it('should define the description', function () {
sinon.spy(program, 'description');
index(program);
@@ -56,7 +56,7 @@ describe('kibana cli', function() {
program.description.restore();
});
- it('should define the command line options', function() {
+ it('should define the command line options', function () {
const spy = sinon.spy(program, 'option');
const options = [/-q/, /-s/, /-c/, /-t/, /-d/];
@@ -77,7 +77,7 @@ describe('kibana cli', function() {
expect(options).toHaveLength(0);
});
- it('should call the action function', function() {
+ it('should call the action function', function () {
sinon.spy(program, 'action');
index(program);
diff --git a/src/cli_plugin/install/kibana.test.js b/src/cli_plugin/install/kibana.test.js
index bbf364a755f8a..8c5dd00d09953 100644
--- a/src/cli_plugin/install/kibana.test.js
+++ b/src/cli_plugin/install/kibana.test.js
@@ -30,9 +30,9 @@ beforeEach(() => {
jest.clearAllMocks();
});
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('kibana', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('kibana', function () {
const testWorkingPath = join(__dirname, '.test.data.kibana');
const tempArchiveFilePath = join(testWorkingPath, 'archive.part');
const pluginDir = join(__dirname, 'plugins');
@@ -48,21 +48,21 @@ describe('kibana cli', function() {
const logger = new Logger(settings);
- describe('assertVersion', function() {
- beforeEach(function() {
+ describe('assertVersion', function () {
+ beforeEach(function () {
del.sync(testWorkingPath);
fs.mkdirSync(testWorkingPath, { recursive: true });
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
del.sync(testWorkingPath);
});
- it('should succeed with exact match', function() {
+ it('should succeed with exact match', function () {
const settings = {
workingPath: testWorkingPath,
tempArchiveFile: tempArchiveFilePath,
@@ -76,60 +76,60 @@ describe('kibana cli', function() {
expect(() => assertVersion(settings)).not.toThrow();
});
- it('should throw an error if plugin is missing a kibana version.', function() {
+ it('should throw an error if plugin is missing a kibana version.', function () {
expect(() => assertVersion(settings)).toThrow(
/plugin package\.json is missing both a version property/i
);
});
- it('should throw an error if plugin kibanaVersion does not match kibana version', function() {
+ it('should throw an error if plugin kibanaVersion does not match kibana version', function () {
settings.plugins[0].kibanaVersion = '1.2.3.4';
expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i);
});
- it('should not throw an error if plugin kibanaVersion matches kibana version', function() {
+ it('should not throw an error if plugin kibanaVersion matches kibana version', function () {
settings.plugins[0].kibanaVersion = '1.0.0';
expect(() => assertVersion(settings)).not.toThrow();
});
- it('should ignore version info after the dash in checks on valid version', function() {
+ it('should ignore version info after the dash in checks on valid version', function () {
settings.plugins[0].kibanaVersion = '1.0.0-foo-bar-version-1.2.3';
expect(() => assertVersion(settings)).not.toThrow();
});
- it('should ignore version info after the dash in checks on invalid version', function() {
+ it('should ignore version info after the dash in checks on invalid version', function () {
settings.plugins[0].kibanaVersion = '2.0.0-foo-bar-version-1.2.3';
expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i);
});
});
- describe('existingInstall', function() {
+ describe('existingInstall', function () {
let processExitStub;
- beforeEach(function() {
+ beforeEach(function () {
processExitStub = sinon.stub(process, 'exit');
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
});
- afterEach(function() {
+ afterEach(function () {
processExitStub.restore();
logger.log.restore();
logger.error.restore();
});
- it('should throw an error if the plugin already exists.', function() {
+ it('should throw an error if the plugin already exists.', function () {
fs.statSync.mockImplementationOnce(() => true);
existingInstall(settings, logger);
expect(logger.error.firstCall.args[0]).toMatch(/already exists/);
expect(process.exit.called).toBe(true);
});
- it('should not throw an error if the plugin does not exist.', function() {
+ it('should not throw an error if the plugin does not exist.', function () {
fs.statSync.mockImplementationOnce(() => {
throw { code: 'ENOENT' };
});
diff --git a/src/cli_plugin/install/pack.test.js b/src/cli_plugin/install/pack.test.js
index efe310a4fed40..05a60107f80ff 100644
--- a/src/cli_plugin/install/pack.test.js
+++ b/src/cli_plugin/install/pack.test.js
@@ -27,8 +27,8 @@ import { extract, getPackData } from './pack';
import { _downloadSingle } from './download';
import { join } from 'path';
-describe('kibana cli', function() {
- describe('pack', function() {
+describe('kibana cli', function () {
+ describe('pack', function () {
let testNum = 0;
const workingPathRoot = join(__dirname, '.test.data.pack');
let testWorkingPath;
@@ -37,7 +37,7 @@ describe('kibana cli', function() {
let logger;
let settings;
- beforeEach(function() {
+ beforeEach(function () {
//These tests are dependent on the file system, and I had some inconsistent
//behavior with del.sync show up. Until these tests are re-written to not
//depend on the file system, I make sure that each test uses a different
@@ -60,7 +60,7 @@ describe('kibana cli', function() {
Fs.mkdirSync(testWorkingPath, { recursive: true });
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
del.sync(workingPathRoot);
@@ -77,10 +77,10 @@ describe('kibana cli', function() {
throw new Error('expected the promise to reject');
}
- describe('extract', function() {
+ describe('extract', function () {
//Also only extracts the content from the kibana folder.
//Ignores the others.
- it('successfully extract a valid zip', function() {
+ it('successfully extract a valid zip', function () {
return copyReplyFile('test_plugin.zip')
.then(() => {
return getPackData(settings, logger);
@@ -104,8 +104,8 @@ describe('kibana cli', function() {
});
});
- describe('getPackData', function() {
- it('populate settings.plugins', function() {
+ describe('getPackData', function () {
+ it('populate settings.plugins', function () {
return copyReplyFile('test_plugin.zip')
.then(() => {
return getPackData(settings, logger);
@@ -118,7 +118,7 @@ describe('kibana cli', function() {
});
});
- it('populate settings.plugin.kibanaVersion', function() {
+ it('populate settings.plugin.kibanaVersion', function () {
//kibana.version is defined in this package.json and is different than plugin version
return copyReplyFile('test_plugin_different_version.zip')
.then(() => {
@@ -129,7 +129,7 @@ describe('kibana cli', function() {
});
});
- it('populate settings.plugin.kibanaVersion (default to plugin version)', function() {
+ it('populate settings.plugin.kibanaVersion (default to plugin version)', function () {
//kibana.version is not defined in this package.json, defaults to plugin version
return copyReplyFile('test_plugin.zip')
.then(() => {
@@ -140,7 +140,7 @@ describe('kibana cli', function() {
});
});
- it('populate settings.plugins with multiple plugins', function() {
+ it('populate settings.plugins with multiple plugins', function () {
return copyReplyFile('test_plugin_many.zip')
.then(() => {
return getPackData(settings, logger);
@@ -172,32 +172,32 @@ describe('kibana cli', function() {
});
});
- it('throw an error if there is no kibana plugin', function() {
+ it('throw an error if there is no kibana plugin', function () {
return copyReplyFile('test_plugin_no_kibana.zip')
.then(() => {
return getPackData(settings, logger);
})
- .then(shouldReject, err => {
+ .then(shouldReject, (err) => {
expect(err.message).toMatch(/No kibana plugins found in archive/i);
});
});
- it('throw an error with a corrupt zip', function() {
+ it('throw an error with a corrupt zip', function () {
return copyReplyFile('corrupt.zip')
.then(() => {
return getPackData(settings, logger);
})
- .then(shouldReject, err => {
+ .then(shouldReject, (err) => {
expect(err.message).toMatch(/error retrieving/i);
});
});
- it('throw an error if there an invalid plugin name', function() {
+ it('throw an error if there an invalid plugin name', function () {
return copyReplyFile('invalid_name.zip')
.then(() => {
return getPackData(settings, logger);
})
- .then(shouldReject, err => {
+ .then(shouldReject, (err) => {
expect(err.message).toMatch(/invalid plugin name/i);
});
});
diff --git a/src/cli_plugin/install/progress.test.js b/src/cli_plugin/install/progress.test.js
index 5430af75968bb..3b66e8b3dc86c 100644
--- a/src/cli_plugin/install/progress.test.js
+++ b/src/cli_plugin/install/progress.test.js
@@ -21,26 +21,26 @@ import sinon from 'sinon';
import Progress from './progress';
import Logger from '../lib/logger';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('progressReporter', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('progressReporter', function () {
let logger;
let progress;
- beforeEach(function() {
+ beforeEach(function () {
logger = new Logger({ silent: false, quiet: false });
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
progress = new Progress(logger);
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
});
- describe('handleData', function() {
- it('should show a max of 20 dots for full progress', function() {
+ describe('handleData', function () {
+ it('should show a max of 20 dots for full progress', function () {
progress.init(1000);
progress.progress(1000);
progress.complete();
@@ -70,7 +70,7 @@ describe('kibana cli', function() {
expect(logger.log.getCall(21).args[0]).toMatch(/complete/i);
});
- it('should show dot for each 5% of completion', function() {
+ it('should show dot for each 5% of completion', function () {
progress.init(1000);
expect(logger.log.callCount).toBe(1);
diff --git a/src/cli_plugin/install/rename.js b/src/cli_plugin/install/rename.js
index 92adb21368007..1e5d94d474375 100644
--- a/src/cli_plugin/install/rename.js
+++ b/src/cli_plugin/install/rename.js
@@ -21,7 +21,7 @@ import { rename } from 'fs';
import { delay } from 'lodash';
export function renamePlugin(workingPath, finalPath) {
- return new Promise(function(resolve, reject) {
+ return new Promise(function (resolve, reject) {
const start = Date.now();
const retryTime = 3000;
const retryDelay = 100;
diff --git a/src/cli_plugin/install/rename.test.js b/src/cli_plugin/install/rename.test.js
index c725a1218cbd2..40df75adc5efa 100644
--- a/src/cli_plugin/install/rename.test.js
+++ b/src/cli_plugin/install/rename.test.js
@@ -22,63 +22,63 @@ import fs from 'fs';
import { renamePlugin } from './rename';
-describe('plugin folder rename', function() {
+describe('plugin folder rename', function () {
let renameStub;
- beforeEach(function() {
+ beforeEach(function () {
renameStub = sinon.stub();
});
- afterEach(function() {
+ afterEach(function () {
fs.rename.restore();
});
- it('should rethrow any exceptions', function() {
+ it('should rethrow any exceptions', function () {
renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => {
cb({
code: 'error',
});
});
- return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) {
+ return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) {
expect(err.code).toBe('error');
expect(renameStub.callCount).toBe(1);
});
});
- it('should resolve if there are no errors', function() {
+ it('should resolve if there are no errors', function () {
renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => {
cb();
});
return renamePlugin('/foo/bar', '/bar/foo')
- .then(function() {
+ .then(function () {
expect(renameStub.callCount).toBe(1);
})
- .catch(function() {
+ .catch(function () {
throw new Error("We shouldn't have any errors");
});
});
- describe('Windows', function() {
+ describe('Windows', function () {
let platform;
- beforeEach(function() {
+ beforeEach(function () {
platform = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', {
value: 'win32',
});
});
- afterEach(function() {
+ afterEach(function () {
Object.defineProperty(process, 'platform', platform);
});
- it('should retry on Windows EPERM errors for up to 3 seconds', function() {
+ it('should retry on Windows EPERM errors for up to 3 seconds', function () {
renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => {
cb({
code: 'EPERM',
});
});
- return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) {
+ return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) {
expect(err.code).toBe('EPERM');
expect(renameStub.callCount).toBeGreaterThan(1);
});
diff --git a/src/cli_plugin/install/settings.js b/src/cli_plugin/install/settings.js
index 1f924caddf1b7..40c845fc37a9e 100644
--- a/src/cli_plugin/install/settings.js
+++ b/src/cli_plugin/install/settings.js
@@ -56,7 +56,7 @@ export function parse(command, options, kbnPackage) {
settings.workingPath = resolve(settings.pluginDir, '.plugin.installing');
settings.tempArchiveFile = resolve(settings.workingPath, 'archive.part');
settings.tempPackageFile = resolve(settings.workingPath, 'package.json');
- settings.setPlugin = function(plugin) {
+ settings.setPlugin = function (plugin) {
settings.plugin = plugin;
settings.pluginPath = resolve(settings.pluginDir, settings.plugin.name);
};
diff --git a/src/cli_plugin/install/settings.test.js b/src/cli_plugin/install/settings.test.js
index 1f0aef4377b40..39ca07405ade2 100644
--- a/src/cli_plugin/install/settings.test.js
+++ b/src/cli_plugin/install/settings.test.js
@@ -21,23 +21,23 @@ import { fromRoot } from '../../core/server/utils';
import { resolve } from 'path';
import { parseMilliseconds, parse } from './settings';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('command line option parsing', function() {
- describe('parseMilliseconds function', function() {
- it('should return 0 for an empty string', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('command line option parsing', function () {
+ describe('parseMilliseconds function', function () {
+ it('should return 0 for an empty string', function () {
const value = '';
const result = parseMilliseconds(value);
expect(result).toBe(0);
});
- it('should return 0 for a number with an invalid unit of measure', function() {
+ it('should return 0 for a number with an invalid unit of measure', function () {
const result = parseMilliseconds('1gigablasts');
expect(result).toBe(0);
});
- it('should assume a number with no unit of measure is specified as milliseconds', function() {
+ it('should assume a number with no unit of measure is specified as milliseconds', function () {
const result = parseMilliseconds(1);
expect(result).toBe(1);
@@ -45,53 +45,53 @@ describe('kibana cli', function() {
expect(result2).toBe(1);
});
- it('should interpret a number with "s" as the unit of measure as seconds', function() {
+ it('should interpret a number with "s" as the unit of measure as seconds', function () {
const result = parseMilliseconds('5s');
expect(result).toBe(5 * 1000);
});
- it('should interpret a number with "second" as the unit of measure as seconds', function() {
+ it('should interpret a number with "second" as the unit of measure as seconds', function () {
const result = parseMilliseconds('5second');
expect(result).toBe(5 * 1000);
});
- it('should interpret a number with "seconds" as the unit of measure as seconds', function() {
+ it('should interpret a number with "seconds" as the unit of measure as seconds', function () {
const result = parseMilliseconds('5seconds');
expect(result).toBe(5 * 1000);
});
- it('should interpret a number with "m" as the unit of measure as minutes', function() {
+ it('should interpret a number with "m" as the unit of measure as minutes', function () {
const result = parseMilliseconds('9m');
expect(result).toBe(9 * 1000 * 60);
});
- it('should interpret a number with "minute" as the unit of measure as minutes', function() {
+ it('should interpret a number with "minute" as the unit of measure as minutes', function () {
const result = parseMilliseconds('9minute');
expect(result).toBe(9 * 1000 * 60);
});
- it('should interpret a number with "minutes" as the unit of measure as minutes', function() {
+ it('should interpret a number with "minutes" as the unit of measure as minutes', function () {
const result = parseMilliseconds('9minutes');
expect(result).toBe(9 * 1000 * 60);
});
});
- describe('parse function', function() {
+ describe('parse function', function () {
const command = 'plugin name';
let options = {};
const kbnPackage = { version: 1234 };
- beforeEach(function() {
+ beforeEach(function () {
options = { pluginDir: fromRoot('plugins') };
});
- describe('timeout option', function() {
- it('should default to 0 (milliseconds)', function() {
+ describe('timeout option', function () {
+ it('should default to 0 (milliseconds)', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.timeout).toBe(0);
});
- it('should set settings.timeout property', function() {
+ it('should set settings.timeout property', function () {
options.timeout = 1234;
const settings = parse(command, options, kbnPackage);
@@ -99,14 +99,14 @@ describe('kibana cli', function() {
});
});
- describe('quiet option', function() {
- it('should default to false', function() {
+ describe('quiet option', function () {
+ it('should default to false', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.quiet).toBe(false);
});
- it('should set settings.quiet property to true', function() {
+ it('should set settings.quiet property to true', function () {
options.quiet = true;
const settings = parse(command, options, kbnPackage);
@@ -114,14 +114,14 @@ describe('kibana cli', function() {
});
});
- describe('silent option', function() {
- it('should default to false', function() {
+ describe('silent option', function () {
+ it('should default to false', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.silent).toBe(false);
});
- it('should set settings.silent property to true', function() {
+ it('should set settings.silent property to true', function () {
options.silent = true;
const settings = parse(command, options, kbnPackage);
@@ -129,14 +129,14 @@ describe('kibana cli', function() {
});
});
- describe('config option', function() {
- it('should default to ZLS', function() {
+ describe('config option', function () {
+ it('should default to ZLS', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.config).toBe('');
});
- it('should set settings.config property', function() {
+ it('should set settings.config property', function () {
options.config = 'foo bar baz';
const settings = parse(command, options, kbnPackage);
@@ -144,14 +144,14 @@ describe('kibana cli', function() {
});
});
- describe('pluginDir option', function() {
- it('should default to plugins', function() {
+ describe('pluginDir option', function () {
+ it('should default to plugins', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.pluginDir).toBe(fromRoot('plugins'));
});
- it('should set settings.config property', function() {
+ it('should set settings.config property', function () {
options.pluginDir = 'foo bar baz';
const settings = parse(command, options, kbnPackage);
@@ -159,16 +159,16 @@ describe('kibana cli', function() {
});
});
- describe('command value', function() {
- it('should set settings.plugin property', function() {
+ describe('command value', function () {
+ it('should set settings.plugin property', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.plugin).toBe(command);
});
});
- describe('urls collection', function() {
- it('should populate the settings.urls property', function() {
+ describe('urls collection', function () {
+ it('should populate the settings.urls property', function () {
const settings = parse(command, options, kbnPackage);
const expected = [
@@ -180,8 +180,8 @@ describe('kibana cli', function() {
});
});
- describe('workingPath value', function() {
- it('should set settings.workingPath property', function() {
+ describe('workingPath value', function () {
+ it('should set settings.workingPath property', function () {
options.pluginDir = 'foo/bar/baz';
const settings = parse(command, options, kbnPackage);
const expected = resolve('foo/bar/baz', '.plugin.installing');
@@ -190,8 +190,8 @@ describe('kibana cli', function() {
});
});
- describe('tempArchiveFile value', function() {
- it('should set settings.tempArchiveFile property', function() {
+ describe('tempArchiveFile value', function () {
+ it('should set settings.tempArchiveFile property', function () {
options.pluginDir = 'foo/bar/baz';
const settings = parse(command, options, kbnPackage);
const expected = resolve('foo/bar/baz', '.plugin.installing', 'archive.part');
@@ -200,8 +200,8 @@ describe('kibana cli', function() {
});
});
- describe('tempPackageFile value', function() {
- it('should set settings.tempPackageFile property', function() {
+ describe('tempPackageFile value', function () {
+ it('should set settings.tempPackageFile property', function () {
options.pluginDir = 'foo/bar/baz';
const settings = parse(command, options, kbnPackage);
const expected = resolve('foo/bar/baz', '.plugin.installing', 'package.json');
diff --git a/src/cli_plugin/install/zip.js b/src/cli_plugin/install/zip.js
index 03e6edb63b4ff..52eba2ea239a2 100644
--- a/src/cli_plugin/install/zip.js
+++ b/src/cli_plugin/install/zip.js
@@ -34,29 +34,29 @@ export function analyzeArchive(archive) {
const regExp = new RegExp('(kibana[\\\\/][^\\\\/]+)[\\\\/]package.json', 'i');
return new Promise((resolve, reject) => {
- yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) {
+ yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) {
if (err) {
return reject(err);
}
zipfile.readEntry();
- zipfile.on('entry', function(entry) {
+ zipfile.on('entry', function (entry) {
const match = entry.fileName.match(regExp);
if (!match) {
return zipfile.readEntry();
}
- zipfile.openReadStream(entry, function(err, readable) {
+ zipfile.openReadStream(entry, function (err, readable) {
const chunks = [];
if (err) {
return reject(err);
}
- readable.on('data', chunk => chunks.push(chunk));
+ readable.on('data', (chunk) => chunks.push(chunk));
- readable.on('end', function() {
+ readable.on('end', function () {
const contents = Buffer.concat(chunks).toString();
const pkg = JSON.parse(contents);
@@ -92,14 +92,14 @@ export function _isDirectory(filename) {
export function extractArchive(archive, targetDir, extractPath) {
return new Promise((resolve, reject) => {
- yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) {
+ yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) {
if (err) {
return reject(err);
}
zipfile.readEntry();
zipfile.on('close', resolve);
- zipfile.on('entry', function(entry) {
+ zipfile.on('entry', function (entry) {
let fileName = entry.fileName;
if (extractPath && fileName.startsWith(extractPath)) {
@@ -113,7 +113,7 @@ export function extractArchive(archive, targetDir, extractPath) {
}
if (_isDirectory(fileName)) {
- mkdir(fileName, { recursive: true }, function(err) {
+ mkdir(fileName, { recursive: true }, function (err) {
if (err) {
return reject(err);
}
@@ -122,13 +122,13 @@ export function extractArchive(archive, targetDir, extractPath) {
});
} else {
// file entry
- zipfile.openReadStream(entry, function(err, readStream) {
+ zipfile.openReadStream(entry, function (err, readStream) {
if (err) {
return reject(err);
}
// ensure parent directory exists
- mkdir(path.dirname(fileName), { recursive: true }, function(err) {
+ mkdir(path.dirname(fileName), { recursive: true }, function (err) {
if (err) {
return reject(err);
}
@@ -136,7 +136,7 @@ export function extractArchive(archive, targetDir, extractPath) {
readStream.pipe(
createWriteStream(fileName, { mode: entry.externalFileAttributes >>> 16 })
);
- readStream.on('end', function() {
+ readStream.on('end', function () {
zipfile.readEntry();
});
});
diff --git a/src/cli_plugin/install/zip.test.js b/src/cli_plugin/install/zip.test.js
index 8f75367ec8eb4..28367e9e24453 100644
--- a/src/cli_plugin/install/zip.test.js
+++ b/src/cli_plugin/install/zip.test.js
@@ -24,8 +24,8 @@ import glob from 'glob';
import fs from 'fs';
import { analyzeArchive, extractArchive, _isDirectory } from './zip';
-describe('kibana cli', function() {
- describe('zip', function() {
+describe('kibana cli', function () {
+ describe('zip', function () {
const repliesPath = path.resolve(__dirname, '__fixtures__', 'replies');
const archivePath = path.resolve(repliesPath, 'test_plugin.zip');
@@ -40,7 +40,7 @@ describe('kibana cli', function() {
del.sync(tempPath, { force: true });
});
- describe('analyzeArchive', function() {
+ describe('analyzeArchive', function () {
it('returns array of plugins', async () => {
const packages = await analyzeArchive(archivePath);
const plugin = packages[0];
diff --git a/src/cli_plugin/lib/log_warnings.js b/src/cli_plugin/lib/log_warnings.js
index 3adf0ba849c23..b4542acecb305 100644
--- a/src/cli_plugin/lib/log_warnings.js
+++ b/src/cli_plugin/lib/log_warnings.js
@@ -17,8 +17,8 @@
* under the License.
*/
-export default function(settings, logger) {
- process.on('warning', warning => {
+export default function (settings, logger) {
+ process.on('warning', (warning) => {
// deprecation warnings do no reflect a current problem for
// the user and therefor should be filtered out.
if (warning.name === 'DeprecationWarning') {
diff --git a/src/cli_plugin/lib/logger.test.js b/src/cli_plugin/lib/logger.test.js
index db8454f465b47..00cad1a9bbb11 100644
--- a/src/cli_plugin/lib/logger.test.js
+++ b/src/cli_plugin/lib/logger.test.js
@@ -20,21 +20,21 @@
import sinon from 'sinon';
import Logger from './logger';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('logger', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('logger', function () {
let logger;
- describe('logger.log', function() {
- beforeEach(function() {
+ describe('logger.log', function () {
+ beforeEach(function () {
sinon.stub(process.stdout, 'write');
});
- afterEach(function() {
+ afterEach(function () {
process.stdout.write.restore();
});
- it('should log messages to the console and append a new line', function() {
+ it('should log messages to the console and append a new line', function () {
logger = new Logger({ silent: false, quiet: false });
const message = 'this is my message';
@@ -45,7 +45,7 @@ describe('kibana cli', function() {
expect(process.stdout.write.getCall(callCount - 1).args[0]).toBe('\n');
});
- it('should log messages to the console and append not append a new line', function() {
+ it('should log messages to the console and append not append a new line', function () {
logger = new Logger({ silent: false, quiet: false });
for (let i = 0; i < 10; i++) {
logger.log('.', true);
@@ -68,7 +68,7 @@ describe('kibana cli', function() {
expect(process.stdout.write.getCall(12).args[0]).toBe('\n');
});
- it('should not log any messages when quiet is set', function() {
+ it('should not log any messages when quiet is set', function () {
logger = new Logger({ silent: false, quiet: true });
const message = 'this is my message';
@@ -82,7 +82,7 @@ describe('kibana cli', function() {
expect(process.stdout.write.callCount).toBe(0);
});
- it('should not log any messages when silent is set', function() {
+ it('should not log any messages when silent is set', function () {
logger = new Logger({ silent: true, quiet: false });
const message = 'this is my message';
@@ -97,16 +97,16 @@ describe('kibana cli', function() {
});
});
- describe('logger.error', function() {
- beforeEach(function() {
+ describe('logger.error', function () {
+ beforeEach(function () {
sinon.stub(process.stderr, 'write');
});
- afterEach(function() {
+ afterEach(function () {
process.stderr.write.restore();
});
- it('should log error messages to the console and append a new line', function() {
+ it('should log error messages to the console and append a new line', function () {
logger = new Logger({ silent: false, quiet: false });
const message = 'this is my error';
@@ -114,7 +114,7 @@ describe('kibana cli', function() {
expect(process.stderr.write.calledWith(message + '\n')).toBe(true);
});
- it('should log error messages to the console when quiet is set', function() {
+ it('should log error messages to the console when quiet is set', function () {
logger = new Logger({ silent: false, quiet: true });
const message = 'this is my error';
@@ -122,7 +122,7 @@ describe('kibana cli', function() {
expect(process.stderr.write.calledWith(message + '\n')).toBe(true);
});
- it('should not log any error messages when silent is set', function() {
+ it('should not log any error messages when silent is set', function () {
logger = new Logger({ silent: true, quiet: false });
const message = 'this is my error';
diff --git a/src/cli_plugin/list/list.js b/src/cli_plugin/list/list.js
index d53e868b32e36..b34631e5dfd08 100644
--- a/src/cli_plugin/list/list.js
+++ b/src/cli_plugin/list/list.js
@@ -21,7 +21,7 @@ import { statSync, readdirSync, readFileSync } from 'fs';
import { join } from 'path';
export default function list(settings, logger) {
- readdirSync(settings.pluginDir).forEach(filename => {
+ readdirSync(settings.pluginDir).forEach((filename) => {
const stat = statSync(join(settings.pluginDir, filename));
if (stat.isDirectory() && filename[0] !== '.') {
diff --git a/src/cli_plugin/list/list.test.js b/src/cli_plugin/list/list.test.js
index c6480ca52b59a..071a253fa87fe 100644
--- a/src/cli_plugin/list/list.test.js
+++ b/src/cli_plugin/list/list.test.js
@@ -30,8 +30,8 @@ function createPlugin(name, version, pluginBaseDir) {
appendFileSync(join(pluginDir, 'package.json'), '{"version": "' + version + '"}');
}
-describe('kibana cli', function() {
- describe('plugin lister', function() {
+describe('kibana cli', function () {
+ describe('plugin lister', function () {
const pluginDir = join(__dirname, '.test.data.list');
let logger;
@@ -39,7 +39,7 @@ describe('kibana cli', function() {
pluginDir: pluginDir,
};
- beforeEach(function() {
+ beforeEach(function () {
logger = new Logger(settings);
sinon.stub(logger, 'log');
sinon.stub(logger, 'error');
@@ -47,13 +47,13 @@ describe('kibana cli', function() {
mkdirSync(pluginDir, { recursive: true });
});
- afterEach(function() {
+ afterEach(function () {
logger.log.restore();
logger.error.restore();
del.sync(pluginDir);
});
- it('list all of the folders in the plugin folder', function() {
+ it('list all of the folders in the plugin folder', function () {
createPlugin('plugin1', '5.0.0-alpha2', pluginDir);
createPlugin('plugin2', '3.2.1', pluginDir);
createPlugin('plugin3', '1.2.3', pluginDir);
@@ -65,7 +65,7 @@ describe('kibana cli', function() {
expect(logger.log.calledWith('plugin3@1.2.3')).toBe(true);
});
- it('ignore folders that start with a period', function() {
+ it('ignore folders that start with a period', function () {
createPlugin('.foo', '1.0.0', pluginDir);
createPlugin('plugin1', '5.0.0-alpha2', pluginDir);
createPlugin('plugin2', '3.2.1', pluginDir);
@@ -78,7 +78,7 @@ describe('kibana cli', function() {
expect(logger.log.calledWith('.bar@1.0.0')).toBe(false);
});
- it('list should only list folders', function() {
+ it('list should only list folders', function () {
createPlugin('plugin1', '1.0.0', pluginDir);
createPlugin('plugin2', '1.0.0', pluginDir);
createPlugin('plugin3', '1.0.0', pluginDir);
@@ -91,22 +91,22 @@ describe('kibana cli', function() {
expect(logger.log.calledWith('plugin3@1.0.0')).toBe(true);
});
- it('list should throw an exception if a plugin does not have a package.json', function() {
+ it('list should throw an exception if a plugin does not have a package.json', function () {
createPlugin('plugin1', '1.0.0', pluginDir);
mkdirSync(join(pluginDir, 'empty-plugin'), { recursive: true });
- expect(function() {
+ expect(function () {
list(settings, logger);
}).toThrowError('Unable to read package.json file for plugin empty-plugin');
});
- it('list should throw an exception if a plugin have an empty package.json', function() {
+ it('list should throw an exception if a plugin have an empty package.json', function () {
createPlugin('plugin1', '1.0.0', pluginDir);
const invalidPluginDir = join(pluginDir, 'invalid-plugin');
mkdirSync(invalidPluginDir, { recursive: true });
appendFileSync(join(invalidPluginDir, 'package.json'), '');
- expect(function() {
+ expect(function () {
list(settings, logger);
}).toThrowError('Unable to read package.json file for plugin invalid-plugin');
});
diff --git a/src/cli_plugin/list/settings.test.js b/src/cli_plugin/list/settings.test.js
index 144b5d8661527..85e6cb88e82fd 100644
--- a/src/cli_plugin/list/settings.test.js
+++ b/src/cli_plugin/list/settings.test.js
@@ -20,24 +20,24 @@
import { fromRoot } from '../../core/server/utils';
import { parse } from './settings';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('command line option parsing', function() {
- describe('parse function', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('command line option parsing', function () {
+ describe('parse function', function () {
let command;
const options = {};
- beforeEach(function() {
+ beforeEach(function () {
command = { pluginDir: fromRoot('plugins') };
});
- describe('pluginDir option', function() {
- it('should default to plugins', function() {
+ describe('pluginDir option', function () {
+ it('should default to plugins', function () {
const settings = parse(command, options);
expect(settings.pluginDir).toBe(fromRoot('plugins'));
});
- it('should set settings.config property', function() {
+ it('should set settings.config property', function () {
command.pluginDir = 'foo bar baz';
const settings = parse(command, options);
diff --git a/src/cli_plugin/remove/remove.test.js b/src/cli_plugin/remove/remove.test.js
index 032a17abe209e..4bf061820aa05 100644
--- a/src/cli_plugin/remove/remove.test.js
+++ b/src/cli_plugin/remove/remove.test.js
@@ -25,15 +25,15 @@ import remove from './remove';
import { join } from 'path';
import { writeFileSync, existsSync, mkdirSync } from 'fs';
-describe('kibana cli', function() {
- describe('plugin remover', function() {
+describe('kibana cli', function () {
+ describe('plugin remover', function () {
const pluginDir = join(__dirname, '.test.data.remove');
let processExitStub;
let logger;
const settings = { pluginDir };
- beforeEach(function() {
+ beforeEach(function () {
processExitStub = sinon.stub(process, 'exit');
logger = new Logger(settings);
sinon.stub(logger, 'log');
@@ -42,14 +42,14 @@ describe('kibana cli', function() {
mkdirSync(pluginDir, { recursive: true });
});
- afterEach(function() {
+ afterEach(function () {
processExitStub.restore();
logger.log.restore();
logger.error.restore();
del.sync(pluginDir);
});
- it('throw an error if the plugin is not installed.', function() {
+ it('throw an error if the plugin is not installed.', function () {
settings.pluginPath = join(pluginDir, 'foo');
settings.plugin = 'foo';
@@ -58,7 +58,7 @@ describe('kibana cli', function() {
expect(process.exit.called).toBe(true);
});
- it('throw an error if the specified plugin is not a folder.', function() {
+ it('throw an error if the specified plugin is not a folder.', function () {
writeFileSync(join(pluginDir, 'foo'), 'This is a file, and not a folder.');
remove(settings, logger);
@@ -85,7 +85,7 @@ describe('kibana cli', function() {
);
});
- it('delete the specified folder.', function() {
+ it('delete the specified folder.', function () {
settings.pluginPath = join(pluginDir, 'foo');
mkdirSync(join(pluginDir, 'foo'), { recursive: true });
mkdirSync(join(pluginDir, 'bar'), { recursive: true });
diff --git a/src/cli_plugin/remove/settings.test.js b/src/cli_plugin/remove/settings.test.js
index 5bb4b30cfff09..b3110e1ff0499 100644
--- a/src/cli_plugin/remove/settings.test.js
+++ b/src/cli_plugin/remove/settings.test.js
@@ -20,25 +20,25 @@
import { fromRoot } from '../../core/server/utils';
import { parse } from './settings';
-describe('kibana cli', function() {
- describe('plugin installer', function() {
- describe('command line option parsing', function() {
- describe('parse function', function() {
+describe('kibana cli', function () {
+ describe('plugin installer', function () {
+ describe('command line option parsing', function () {
+ describe('parse function', function () {
const command = 'plugin name';
let options = {};
const kbnPackage = { version: 1234 };
- beforeEach(function() {
+ beforeEach(function () {
options = { pluginDir: fromRoot('plugins') };
});
- describe('quiet option', function() {
- it('should default to false', function() {
+ describe('quiet option', function () {
+ it('should default to false', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.quiet).toBe(false);
});
- it('should set settings.quiet property to true', function() {
+ it('should set settings.quiet property to true', function () {
options.quiet = true;
const settings = parse(command, options, kbnPackage);
@@ -46,14 +46,14 @@ describe('kibana cli', function() {
});
});
- describe('silent option', function() {
- it('should default to false', function() {
+ describe('silent option', function () {
+ it('should default to false', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.silent).toBe(false);
});
- it('should set settings.silent property to true', function() {
+ it('should set settings.silent property to true', function () {
options.silent = true;
const settings = parse(command, options, kbnPackage);
@@ -61,14 +61,14 @@ describe('kibana cli', function() {
});
});
- describe('config option', function() {
- it('should default to ZLS', function() {
+ describe('config option', function () {
+ it('should default to ZLS', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.config).toBe('');
});
- it('should set settings.config property', function() {
+ it('should set settings.config property', function () {
options.config = 'foo bar baz';
const settings = parse(command, options, kbnPackage);
@@ -76,14 +76,14 @@ describe('kibana cli', function() {
});
});
- describe('pluginDir option', function() {
- it('should default to plugins', function() {
+ describe('pluginDir option', function () {
+ it('should default to plugins', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.pluginDir).toBe(fromRoot('plugins'));
});
- it('should set settings.config property', function() {
+ it('should set settings.config property', function () {
options.pluginDir = 'foo bar baz';
const settings = parse(command, options, kbnPackage);
@@ -91,8 +91,8 @@ describe('kibana cli', function() {
});
});
- describe('command value', function() {
- it('should set settings.plugin property', function() {
+ describe('command value', function () {
+ it('should set settings.plugin property', function () {
const settings = parse(command, options, kbnPackage);
expect(settings.plugin).toBe(command);
diff --git a/src/core/public/application/application_leave.test.ts b/src/core/public/application/application_leave.test.ts
index e06183d8bb8d9..b560bbc0cbc25 100644
--- a/src/core/public/application/application_leave.test.ts
+++ b/src/core/public/application/application_leave.test.ts
@@ -31,16 +31,16 @@ describe('isConfirmAction', () => {
describe('getLeaveAction', () => {
it('returns the default action provided by the handler', () => {
- expect(getLeaveAction(actions => actions.default())).toEqual({
+ expect(getLeaveAction((actions) => actions.default())).toEqual({
type: AppLeaveActionType.default,
});
});
it('returns the confirm action provided by the handler', () => {
- expect(getLeaveAction(actions => actions.confirm('some message'))).toEqual({
+ expect(getLeaveAction((actions) => actions.confirm('some message'))).toEqual({
type: AppLeaveActionType.confirm,
text: 'some message',
});
- expect(getLeaveAction(actions => actions.confirm('another message', 'a title'))).toEqual({
+ expect(getLeaveAction((actions) => actions.confirm('another message', 'a title'))).toEqual({
type: AppLeaveActionType.confirm,
text: 'another message',
title: 'a title',
diff --git a/src/core/public/application/application_service.mock.ts b/src/core/public/application/application_service.mock.ts
index d2a827d381be5..24c0e66359afa 100644
--- a/src/core/public/application/application_service.mock.ts
+++ b/src/core/public/application/application_service.mock.ts
@@ -50,6 +50,7 @@ const createStartContractMock = (): jest.Mocked => {
currentAppId$: currentAppId$.asObservable(),
capabilities: capabilitiesServiceMock.createStartContract().capabilities,
navigateToApp: jest.fn(),
+ navigateToUrl: jest.fn(),
getUrlForApp: jest.fn(),
registerMountContext: jest.fn(),
};
@@ -64,7 +65,8 @@ const createInternalStartContractMock = (): jest.Mocked currentAppId$.next(appId)),
+ navigateToApp: jest.fn().mockImplementation((appId) => currentAppId$.next(appId)),
+ navigateToUrl: jest.fn(),
registerMountContext: jest.fn(),
};
};
diff --git a/src/core/public/application/application_service.test.mocks.ts b/src/core/public/application/application_service.test.mocks.ts
index d829cf18e56be..a096f05209708 100644
--- a/src/core/public/application/application_service.test.mocks.ts
+++ b/src/core/public/application/application_service.test.mocks.ts
@@ -34,3 +34,9 @@ export const createBrowserHistoryMock = jest.fn().mockReturnValue(MockHistory);
jest.doMock('history', () => ({
createBrowserHistory: createBrowserHistoryMock,
}));
+
+export const parseAppUrlMock = jest.fn();
+jest.doMock('./utils', () => ({
+ ...jest.requireActual('./utils'),
+ parseAppUrl: parseAppUrlMock,
+}));
diff --git a/src/core/public/application/application_service.test.ts b/src/core/public/application/application_service.test.ts
index 04ff844ffc150..b65a8581e5b58 100644
--- a/src/core/public/application/application_service.test.ts
+++ b/src/core/public/application/application_service.test.ts
@@ -17,6 +17,12 @@
* under the License.
*/
+import {
+ MockCapabilitiesService,
+ MockHistory,
+ parseAppUrlMock,
+} from './application_service.test.mocks';
+
import { createElement } from 'react';
import { BehaviorSubject, Subject } from 'rxjs';
import { bufferCount, take, takeUntil } from 'rxjs/operators';
@@ -26,7 +32,6 @@ import { injectedMetadataServiceMock } from '../injected_metadata/injected_metad
import { contextServiceMock } from '../context/context_service.mock';
import { httpServiceMock } from '../http/http_service.mock';
import { overlayServiceMock } from '../overlays/overlay_service.mock';
-import { MockCapabilitiesService, MockHistory } from './application_service.test.mocks';
import { MockLifecycle } from './test_types';
import { ApplicationService } from './application_service';
import { App, AppNavLinkStatus, AppStatus, AppUpdater, LegacyApp } from './types';
@@ -61,6 +66,7 @@ describe('#setup()', () => {
http,
context: contextServiceMock.createSetupContract(),
injectedMetadata: injectedMetadataServiceMock.createSetupContract(),
+ redirectTo: jest.fn(),
};
setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(false);
startDeps = { http, overlays: overlayServiceMock.createStartContract() };
@@ -92,7 +98,7 @@ describe('#setup()', () => {
const setup = service.setup(setupDeps);
const pluginId = Symbol('plugin');
- const updater$ = new BehaviorSubject(app => ({}));
+ const updater$ = new BehaviorSubject((app) => ({}));
setup.register(pluginId, createApp({ id: 'app1', updater$ }));
setup.register(pluginId, createApp({ id: 'app2' }));
const { applications$ } = await service.start(startDeps);
@@ -116,7 +122,7 @@ describe('#setup()', () => {
})
);
- updater$.next(app => ({
+ updater$.next((app) => ({
status: AppStatus.inaccessible,
tooltip: 'App inaccessible due to reason',
defaultPath: 'foo/bar',
@@ -174,6 +180,10 @@ describe('#setup()', () => {
).toThrowErrorMatchingInlineSnapshot(
`"Cannot register an application route that includes HTTP base path"`
);
+
+ expect(() =>
+ register(Symbol(), createApp({ id: 'app3', appRoute: '/base-path-i-am-not' }))
+ ).not.toThrow();
});
});
@@ -220,7 +230,7 @@ describe('#setup()', () => {
setup.register(pluginId, createApp({ id: 'app1' }));
setup.register(pluginId, createApp({ id: 'app2' }));
setup.registerAppUpdater(
- new BehaviorSubject(app => {
+ new BehaviorSubject((app) => {
if (app.id === 'app1') {
return {
status: AppStatus.inaccessible,
@@ -260,7 +270,7 @@ describe('#setup()', () => {
it(`properly combine with application's updater$`, async () => {
const setup = service.setup(setupDeps);
const pluginId = Symbol('plugin');
- const appStatusUpdater$ = new BehaviorSubject(app => ({
+ const appStatusUpdater$ = new BehaviorSubject((app) => ({
status: AppStatus.inaccessible,
navLinkStatus: AppNavLinkStatus.disabled,
}));
@@ -268,7 +278,7 @@ describe('#setup()', () => {
setup.register(pluginId, createApp({ id: 'app2' }));
setup.registerAppUpdater(
- new BehaviorSubject(app => {
+ new BehaviorSubject((app) => {
if (app.id === 'app1') {
return {
status: AppStatus.accessible,
@@ -311,7 +321,7 @@ describe('#setup()', () => {
const pluginId = Symbol('plugin');
setup.register(pluginId, createApp({ id: 'app1' }));
setup.registerAppUpdater(
- new BehaviorSubject(app => {
+ new BehaviorSubject((app) => {
return {
status: AppStatus.inaccessible,
navLinkStatus: AppNavLinkStatus.disabled,
@@ -319,7 +329,7 @@ describe('#setup()', () => {
})
);
setup.registerAppUpdater(
- new BehaviorSubject(app => {
+ new BehaviorSubject((app) => {
return {
status: AppStatus.accessible,
navLinkStatus: AppNavLinkStatus.default,
@@ -347,7 +357,7 @@ describe('#setup()', () => {
const pluginId = Symbol('plugin');
setup.register(pluginId, createApp({ id: 'app1' }));
- const statusUpdater = new BehaviorSubject(app => {
+ const statusUpdater = new BehaviorSubject((app) => {
return {
status: AppStatus.inaccessible,
navLinkStatus: AppNavLinkStatus.disabled,
@@ -357,7 +367,7 @@ describe('#setup()', () => {
const start = await service.start(startDeps);
let latestValue: ReadonlyMap = new Map();
- start.applications$.subscribe(apps => {
+ start.applications$.subscribe((apps) => {
latestValue = apps;
});
@@ -370,7 +380,7 @@ describe('#setup()', () => {
})
);
- statusUpdater.next(app => {
+ statusUpdater.next((app) => {
return {
status: AppStatus.accessible,
navLinkStatus: AppNavLinkStatus.hidden,
@@ -393,7 +403,7 @@ describe('#setup()', () => {
setup.registerLegacyApp(createLegacyApp({ id: 'app1' }));
setup.registerAppUpdater(
- new BehaviorSubject(app => {
+ new BehaviorSubject((app) => {
return {
status: AppStatus.inaccessible,
navLinkStatus: AppNavLinkStatus.hidden,
@@ -423,7 +433,7 @@ describe('#setup()', () => {
const pluginId = Symbol('plugin');
setup.register(pluginId, createApp({ id: 'app1' }));
- const updater = new BehaviorSubject(app => ({}));
+ const updater = new BehaviorSubject((app) => ({}));
setup.registerAppUpdater(updater);
const start = await service.start(startDeps);
@@ -431,17 +441,17 @@ describe('#setup()', () => {
expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined);
MockHistory.push.mockClear();
- updater.next(app => ({ defaultPath: 'default-path' }));
+ updater.next((app) => ({ defaultPath: 'default-path' }));
await start.navigateToApp('app1');
expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/default-path', undefined);
MockHistory.push.mockClear();
- updater.next(app => ({ defaultPath: 'another-path' }));
+ updater.next((app) => ({ defaultPath: 'another-path' }));
await start.navigateToApp('app1');
expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/another-path', undefined);
MockHistory.push.mockClear();
- updater.next(app => ({}));
+ updater.next((app) => ({}));
await start.navigateToApp('app1');
expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined);
MockHistory.push.mockClear();
@@ -462,12 +472,14 @@ describe('#setup()', () => {
describe('#start()', () => {
beforeEach(() => {
MockHistory.push.mockReset();
+ parseAppUrlMock.mockReset();
const http = httpServiceMock.createSetupContract({ basePath: '/base-path' });
setupDeps = {
http,
context: contextServiceMock.createSetupContract(),
injectedMetadata: injectedMetadataServiceMock.createSetupContract(),
+ redirectTo: jest.fn(),
};
setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(false);
startDeps = { http, overlays: overlayServiceMock.createStartContract() };
@@ -775,7 +787,6 @@ describe('#start()', () => {
});
it('redirects when in legacyMode', async () => {
- setupDeps.redirectTo = jest.fn();
setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true);
service.setup(setupDeps);
@@ -816,11 +827,11 @@ describe('#start()', () => {
const history = createMemoryHistory();
setupDeps.history = history;
- const flushPromises = () => new Promise(resolve => setImmediate(resolve));
+ const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
// Create an app and a promise that allows us to control when the app completes mounting
const createWaitingApp = (props: Partial): [App, () => void] => {
let finishMount: () => void;
- const mountPromise = new Promise(resolve => (finishMount = resolve));
+ const mountPromise = new Promise((resolve) => (finishMount = resolve));
const app = {
id: 'some-id',
title: 'some-title',
@@ -881,7 +892,6 @@ describe('#start()', () => {
it('sets window.location.href when navigating to legacy apps', async () => {
setupDeps.http = httpServiceMock.createSetupContract({ basePath: '/test' });
setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true);
- setupDeps.redirectTo = jest.fn();
service.setup(setupDeps);
const { navigateToApp } = await service.start(startDeps);
@@ -893,7 +903,6 @@ describe('#start()', () => {
it('handles legacy apps with subapps', async () => {
setupDeps.http = httpServiceMock.createSetupContract({ basePath: '/test' });
setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true);
- setupDeps.redirectTo = jest.fn();
const { registerLegacyApp } = service.setup(setupDeps);
@@ -905,6 +914,30 @@ describe('#start()', () => {
expect(setupDeps.redirectTo).toHaveBeenCalledWith('/test/app/baseApp');
});
});
+
+ describe('navigateToUrl', () => {
+ it('calls `redirectTo` when the url is not parseable', async () => {
+ parseAppUrlMock.mockReturnValue(undefined);
+ service.setup(setupDeps);
+ const { navigateToUrl } = await service.start(startDeps);
+
+ await navigateToUrl('/not-an-app-path');
+
+ expect(MockHistory.push).not.toHaveBeenCalled();
+ expect(setupDeps.redirectTo).toHaveBeenCalledWith('/not-an-app-path');
+ });
+
+ it('calls `navigateToApp` when the url is an internal app link', async () => {
+ parseAppUrlMock.mockReturnValue({ app: 'foo', path: '/some-path' });
+ service.setup(setupDeps);
+ const { navigateToUrl } = await service.start(startDeps);
+
+ await navigateToUrl('/an-app-path');
+
+ expect(MockHistory.push).toHaveBeenCalledWith('/app/foo/some-path', undefined);
+ expect(setupDeps.redirectTo).not.toHaveBeenCalled();
+ });
+ });
});
describe('#stop()', () => {
diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx
index 6802c2363b9f8..b52b4984fb5e1 100644
--- a/src/core/public/application/application_service.tsx
+++ b/src/core/public/application/application_service.tsx
@@ -46,17 +46,14 @@ import {
Mounter,
} from './types';
import { getLeaveAction, isConfirmAction } from './application_leave';
-import { appendAppPath } from './utils';
+import { appendAppPath, parseAppUrl, relativeToAbsolute } from './utils';
interface SetupDeps {
context: ContextSetup;
http: HttpSetup;
injectedMetadata: InjectedMetadataSetup;
history?: History;
- /**
- * Only necessary for redirecting to legacy apps
- * @deprecated
- */
+ /** Used to redirect to external urls (and legacy apps) */
redirectTo?: (path: string) => void;
}
@@ -109,6 +106,7 @@ export class ApplicationService {
private history?: History;
private mountContext?: IContextContainer;
private navigate?: (url: string, state: any) => void;
+ private redirectTo?: (url: string) => void;
public setup({
context,
@@ -131,12 +129,12 @@ export class ApplicationService {
this.navigate = (url, state) =>
// basePath not needed here because `history` is configured with basename
this.history ? this.history.push(url, state) : redirectTo(basePath.prepend(url));
-
+ this.redirectTo = redirectTo;
this.mountContext = context.createContextContainer();
const registerStatusUpdater = (application: string, updater$: Observable) => {
const updaterId = Symbol();
- const subscription = updater$.subscribe(updater => {
+ const subscription = updater$.subscribe((updater) => {
const nextValue = new Map(this.statusUpdaters$.getValue());
nextValue.set(updaterId, {
application,
@@ -160,7 +158,7 @@ export class ApplicationService {
} else {
handler = app.mount;
}
- return async params => {
+ return async (params) => {
this.currentAppId$.next(app.id);
return handler(params);
};
@@ -179,7 +177,7 @@ export class ApplicationService {
throw new Error(
`An application is already registered with the appRoute "${app.appRoute}"`
);
- } else if (basename && app.appRoute!.startsWith(basename)) {
+ } else if (basename && app.appRoute!.startsWith(`${basename}/`)) {
throw new Error('Cannot register an application route that includes HTTP base path');
}
@@ -201,14 +199,14 @@ export class ApplicationService {
legacy: false,
});
},
- registerLegacyApp: app => {
+ registerLegacyApp: (app) => {
const appRoute = `/app/${app.id.split(':')[0]}`;
if (this.registrationClosed) {
throw new Error('Applications cannot be registered after "setup"');
} else if (this.apps.has(app.id)) {
throw new Error(`An application is already registered with the id "${app.id}"`);
- } else if (basename && appRoute!.startsWith(basename)) {
+ } else if (basename && appRoute!.startsWith(`${basename}/`)) {
throw new Error('Cannot register an application route that includes HTTP base path');
}
@@ -262,7 +260,7 @@ export class ApplicationService {
const applications$ = new BehaviorSubject(availableApps);
this.statusUpdaters$
.pipe(
- map(statusUpdaters => {
+ map((statusUpdaters) => {
return new Map(
[...availableApps].map(([id, app]) => [
id,
@@ -271,18 +269,32 @@ export class ApplicationService {
);
})
)
- .subscribe(apps => applications$.next(apps));
+ .subscribe((apps) => applications$.next(apps));
const applicationStatuses$ = applications$.pipe(
- map(apps => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))),
+ map((apps) => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))),
shareReplay(1)
);
+ const navigateToApp: InternalApplicationStart['navigateToApp'] = async (
+ appId,
+ { path, state }: { path?: string; state?: any } = {}
+ ) => {
+ if (await this.shouldNavigate(overlays)) {
+ if (path === undefined) {
+ path = applications$.value.get(appId)?.defaultPath;
+ }
+ this.appLeaveHandlers.delete(this.currentAppId$.value!);
+ this.navigate!(getAppUrl(availableMounters, appId, path), state);
+ this.currentAppId$.next(appId);
+ }
+ };
+
return {
applications$,
capabilities,
currentAppId$: this.currentAppId$.pipe(
- filter(appId => appId !== undefined),
+ filter((appId) => appId !== undefined),
distinctUntilChanged(),
takeUntil(this.stop$)
),
@@ -294,14 +306,13 @@ export class ApplicationService {
const relUrl = http.basePath.prepend(getAppUrl(availableMounters, appId, path));
return absolute ? relativeToAbsolute(relUrl) : relUrl;
},
- navigateToApp: async (appId, { path, state }: { path?: string; state?: any } = {}) => {
- if (await this.shouldNavigate(overlays)) {
- if (path === undefined) {
- path = applications$.value.get(appId)?.defaultPath;
- }
- this.appLeaveHandlers.delete(this.currentAppId$.value!);
- this.navigate!(getAppUrl(availableMounters, appId, path), state);
- this.currentAppId$.next(appId);
+ navigateToApp,
+ navigateToUrl: async (url) => {
+ const appInfo = parseAppUrl(url, http.basePath, this.apps);
+ if (appInfo) {
+ return navigateToApp(appInfo.app, { path: appInfo.path });
+ } else {
+ return this.redirectTo!(url);
}
},
getComponent: () => {
@@ -314,7 +325,7 @@ export class ApplicationService {
mounters={availableMounters}
appStatuses$={applicationStatuses$}
setAppLeaveHandler={this.setAppLeaveHandler}
- setIsMounting={isMounting => httpLoadingCount$.next(isMounting ? 1 : 0)}
+ setIsMounting={(isMounting) => httpLoadingCount$.next(isMounting ? 1 : 0)}
/>
);
},
@@ -360,14 +371,14 @@ export class ApplicationService {
this.stop$.next();
this.currentAppId$.complete();
this.statusUpdaters$.complete();
- this.subscriptions.forEach(sub => sub.unsubscribe());
+ this.subscriptions.forEach((sub) => sub.unsubscribe());
window.removeEventListener('beforeunload', this.onBeforeUnload);
}
}
const updateStatus = (app: T, statusUpdaters: AppUpdaterWrapper[]): T => {
let changes: Partial = {};
- statusUpdaters.forEach(wrapper => {
+ statusUpdaters.forEach((wrapper) => {
if (wrapper.application !== allApplicationsFilter && wrapper.application !== app.id) {
return;
}
@@ -388,10 +399,3 @@ const updateStatus = (app: T, statusUpdaters: AppUpdaterWrapp
...changes,
};
};
-
-function relativeToAbsolute(url: string) {
- // convert all link urls to absolute urls
- const a = document.createElement('a');
- a.setAttribute('href', url);
- return a.href;
-}
diff --git a/src/core/public/application/integration_tests/application_service.test.tsx b/src/core/public/application/integration_tests/application_service.test.tsx
index e399fbc726977..89f90a9899dda 100644
--- a/src/core/public/application/integration_tests/application_service.test.tsx
+++ b/src/core/public/application/integration_tests/application_service.test.tsx
@@ -31,7 +31,7 @@ import { overlayServiceMock } from '../../overlays/overlay_service.mock';
import { AppMountParameters } from '../types';
import { ScopedHistory } from '../scoped_history';
-const flushPromises = () => new Promise(resolve => setImmediate(resolve));
+const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
describe('ApplicationService', () => {
let setupDeps: MockLifecycle<'setup'>;
@@ -68,7 +68,7 @@ describe('ApplicationService', () => {
const { register } = service.setup(setupDeps);
let resolveMount: () => void;
- const promise = new Promise(resolve => {
+ const promise = new Promise((resolve) => {
resolveMount = resolve;
});
@@ -102,7 +102,7 @@ describe('ApplicationService', () => {
const { register } = service.setup(setupDeps);
let resolveMount: () => void;
- const promise = new Promise(resolve => {
+ const promise = new Promise((resolve) => {
resolveMount = resolve;
});
@@ -146,7 +146,7 @@ describe('ApplicationService', () => {
id: 'app1',
title: 'App1',
mount: ({ onAppLeave }: AppMountParameters) => {
- onAppLeave(actions => actions.default());
+ onAppLeave((actions) => actions.default());
return () => undefined;
},
});
@@ -178,7 +178,7 @@ describe('ApplicationService', () => {
id: 'app1',
title: 'App1',
mount: ({ onAppLeave }: AppMountParameters) => {
- onAppLeave(actions => actions.default());
+ onAppLeave((actions) => actions.default());
return () => undefined;
},
});
@@ -213,7 +213,7 @@ describe('ApplicationService', () => {
id: 'app1',
title: 'App1',
mount: ({ onAppLeave }: AppMountParameters) => {
- onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title'));
+ onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title'));
return () => undefined;
},
});
@@ -252,7 +252,7 @@ describe('ApplicationService', () => {
id: 'app1',
title: 'App1',
mount: ({ onAppLeave }: AppMountParameters) => {
- onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title'));
+ onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title'));
return () => undefined;
},
});
diff --git a/src/core/public/application/integration_tests/router.test.tsx b/src/core/public/application/integration_tests/router.test.tsx
index 9f379859dc34f..2827b93f6d17e 100644
--- a/src/core/public/application/integration_tests/router.test.tsx
+++ b/src/core/public/application/integration_tests/router.test.tsx
@@ -45,7 +45,7 @@ describe('AppRouter', () => {
const mountersToAppStatus$ = () => {
return new BehaviorSubject(
new Map(
- [...mounters.keys()].map(id => [
+ [...mounters.keys()].map((id) => [
id,
id.startsWith('disabled') ? AppStatus.inaccessible : AppStatus.accessible,
])
diff --git a/src/core/public/application/integration_tests/utils.tsx b/src/core/public/application/integration_tests/utils.tsx
index 6c1b81a26d63c..8590fb3c820ef 100644
--- a/src/core/public/application/integration_tests/utils.tsx
+++ b/src/core/public/application/integration_tests/utils.tsx
@@ -33,7 +33,7 @@ export const createRenderer = (element: ReactElement | null): Renderer => {
const dom: Dom = element && mount({element} );
return () =>
- new Promise(async resolve => {
+ new Promise(async (resolve) => {
if (dom) {
await act(async () => {
dom.update();
diff --git a/src/core/public/application/scoped_history.test.ts b/src/core/public/application/scoped_history.test.ts
index a56cffef1e2f2..2b217e54228c2 100644
--- a/src/core/public/application/scoped_history.test.ts
+++ b/src/core/public/application/scoped_history.test.ts
@@ -217,7 +217,7 @@ describe('ScopedHistory', () => {
gh.push('/app/wow');
const h = new ScopedHistory(gh, '/app/wow');
const listenPaths: string[] = [];
- h.listen(l => listenPaths.push(l.pathname));
+ h.listen((l) => listenPaths.push(l.pathname));
h.push('/first-page');
h.push('/second-page');
h.push('/third-page');
@@ -237,7 +237,7 @@ describe('ScopedHistory', () => {
gh.push('/app/wow');
const h = new ScopedHistory(gh, '/app/wow');
const listenPaths: string[] = [];
- const unlisten = h.listen(l => listenPaths.push(l.pathname));
+ const unlisten = h.listen((l) => listenPaths.push(l.pathname));
h.push('/first-page');
unlisten();
h.push('/second-page');
@@ -252,7 +252,7 @@ describe('ScopedHistory', () => {
gh.push('/app/wow');
const h = new ScopedHistory(gh, '/app/wow');
const listenPaths: string[] = [];
- h.listen(l => listenPaths.push(l.pathname));
+ h.listen((l) => listenPaths.push(l.pathname));
h.push('/first-page');
gh.push('/app/other');
gh.push('/second-page');
diff --git a/src/core/public/application/scoped_history.ts b/src/core/public/application/scoped_history.ts
index 9fa8f0b7f8148..1a7fafa5d85c4 100644
--- a/src/core/public/application/scoped_history.ts
+++ b/src/core/public/application/scoped_history.ts
@@ -324,7 +324,7 @@ export class ScopedHistory
throw new Error(`Unrecognized history action: ${action}`);
}
- [...this.listeners].forEach(listener => {
+ [...this.listeners].forEach((listener) => {
listener(this.stripBasePath(location), action);
});
});
diff --git a/src/core/public/application/types.ts b/src/core/public/application/types.ts
index 786d11a5ced7f..c07d929fc5cea 100644
--- a/src/core/public/application/types.ts
+++ b/src/core/public/application/types.ts
@@ -659,12 +659,41 @@ export interface ApplicationStart {
*/
navigateToApp(appId: string, options?: { path?: string; state?: any }): Promise;
+ /**
+ * Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible.
+ *
+ * If all these criteria are true for the given url:
+ * - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location
+ * - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space)
+ * - The pathname segment after the basePath matches any known application route (eg. /app// or any application's `appRoute` configuration)
+ *
+ * Then a SPA navigation will be performed using `navigateToApp` using the corresponding application and path.
+ * Otherwise, fallback to a full page reload to navigate to the url using `window.location.assign`
+ *
+ * @example
+ * ```ts
+ * // current url: `https://kibana:8080/base-path/s/my-space/app/dashboard`
+ *
+ * // will call `application.navigateToApp('discover', { path: '/some-path?foo=bar'})`
+ * application.navigateToUrl('https://kibana:8080/base-path/s/my-space/app/discover/some-path?foo=bar')
+ * application.navigateToUrl('/base-path/s/my-space/app/discover/some-path?foo=bar')
+ *
+ * // will perform a full page reload using `window.location.assign`
+ * application.navigateToUrl('https://elsewhere:8080/base-path/s/my-space/app/discover/some-path') // origin does not match
+ * application.navigateToUrl('/app/discover/some-path') // does not include the current basePath
+ * application.navigateToUrl('/base-path/s/my-space/app/unknown-app/some-path') // unknown application
+ * ```
+ *
+ * @param url - an absolute url, or a relative path, to navigate to.
+ */
+ navigateToUrl(url: string): Promise;
+
/**
* Returns an URL to a given app, including the global base path.
* By default, the URL is relative (/basePath/app/my-app).
* Use the `absolute` option to generate an absolute url (http://host:port/basePath/app/my-app)
*
- * Note that when generating absolute urls, the protocol, host and port are determined from the browser location.
+ * Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location.
*
* @param appId
* @param options.path - optional path inside application to deep link to
@@ -677,7 +706,6 @@ export interface ApplicationStart {
* plugin that registered this context. Deprecated, use {@link CoreSetup.getStartServices}.
*
* @deprecated
- * @param pluginOpaqueId - The opaque ID of the plugin that is registering the context.
* @param contextName - The key of {@link AppMountContext} this provider's return value should be attached to.
* @param provider - A {@link IContextProvider} function
*/
@@ -696,7 +724,7 @@ export interface ApplicationStart {
export interface InternalApplicationStart
extends Pick<
ApplicationStart,
- 'capabilities' | 'navigateToApp' | 'getUrlForApp' | 'currentAppId$'
+ 'capabilities' | 'navigateToApp' | 'navigateToUrl' | 'getUrlForApp' | 'currentAppId$'
> {
/**
* Apps available based on the current capabilities.
diff --git a/src/core/public/application/ui/app_container.test.tsx b/src/core/public/application/ui/app_container.test.tsx
index 5d573d47bd420..229354a014103 100644
--- a/src/core/public/application/ui/app_container.test.tsx
+++ b/src/core/public/application/ui/app_container.test.tsx
@@ -37,14 +37,14 @@ describe('AppContainer', () => {
});
const flushPromises = async () => {
- await new Promise(async resolve => {
+ await new Promise(async (resolve) => {
setImmediate(() => resolve());
});
};
const createResolver = (): [Promise, () => void] => {
let resolve: () => void | undefined;
- const promise = new Promise(r => {
+ const promise = new Promise((r) => {
resolve = r;
});
return [promise, resolve!];
diff --git a/src/core/public/application/ui/app_container.tsx b/src/core/public/application/ui/app_container.tsx
index 4317ede547202..332c31c64b6ba 100644
--- a/src/core/public/application/ui/app_container.tsx
+++ b/src/core/public/application/ui/app_container.tsx
@@ -83,7 +83,7 @@ export const AppContainer: FunctionComponent = ({
appBasePath: mounter.appBasePath,
history: createScopedHistory(appPath),
element: elementRef.current!,
- onAppLeave: handler => setAppLeaveHandler(appId, handler),
+ onAppLeave: (handler) => setAppLeaveHandler(appId, handler),
})) || null;
} catch (e) {
// TODO: add error UI
diff --git a/src/core/public/application/utils.test.ts b/src/core/public/application/utils.test.ts
index 7ed0919f88c61..a86a1206fc983 100644
--- a/src/core/public/application/utils.test.ts
+++ b/src/core/public/application/utils.test.ts
@@ -17,7 +17,15 @@
* under the License.
*/
-import { removeSlashes, appendAppPath } from './utils';
+import { LegacyApp, App } from './types';
+import { BasePath } from '../http/base_path';
+import {
+ removeSlashes,
+ appendAppPath,
+ isLegacyApp,
+ relativeToAbsolute,
+ parseAppUrl,
+} from './utils';
describe('removeSlashes', () => {
it('only removes duplicates by default', () => {
@@ -69,3 +77,385 @@ describe('appendAppPath', () => {
expect(appendAppPath('/app/my-app', '/some-path#/hash')).toEqual('/app/my-app/some-path#/hash');
});
});
+
+describe('isLegacyApp', () => {
+ it('returns true for legacy apps', () => {
+ expect(
+ isLegacyApp({
+ id: 'legacy',
+ title: 'Legacy App',
+ appUrl: '/some-url',
+ legacy: true,
+ })
+ ).toEqual(true);
+ });
+ it('returns false for non-legacy apps', () => {
+ expect(
+ isLegacyApp({
+ id: 'legacy',
+ title: 'Legacy App',
+ mount: () => () => undefined,
+ legacy: false,
+ })
+ ).toEqual(false);
+ });
+});
+
+describe('relativeToAbsolute', () => {
+ it('converts a relative path to an absolute url', () => {
+ const origin = window.location.origin;
+ expect(relativeToAbsolute('path')).toEqual(`${origin}/path`);
+ expect(relativeToAbsolute('/path#hash')).toEqual(`${origin}/path#hash`);
+ expect(relativeToAbsolute('/path?query=foo')).toEqual(`${origin}/path?query=foo`);
+ });
+});
+
+describe('parseAppUrl', () => {
+ let apps: Map | LegacyApp>;
+ let basePath: BasePath;
+
+ const getOrigin = () => 'https://kibana.local:8080';
+
+ const createApp = (props: Partial): App => {
+ const app: App = {
+ id: 'some-id',
+ title: 'some-title',
+ mount: () => () => undefined,
+ ...props,
+ legacy: false,
+ };
+ apps.set(app.id, app);
+ return app;
+ };
+
+ const createLegacyApp = (props: Partial): LegacyApp => {
+ const app: LegacyApp = {
+ id: 'some-id',
+ title: 'some-title',
+ appUrl: '/my-url',
+ ...props,
+ legacy: true,
+ };
+ apps.set(app.id, app);
+ return app;
+ };
+
+ beforeEach(() => {
+ apps = new Map();
+ basePath = new BasePath('/base-path');
+
+ createApp({
+ id: 'foo',
+ });
+ createApp({
+ id: 'bar',
+ appRoute: '/custom-bar',
+ });
+ createLegacyApp({
+ id: 'legacy',
+ appUrl: '/app/legacy',
+ });
+ });
+
+ describe('with relative paths', () => {
+ it('parses the app id', () => {
+ expect(parseAppUrl('/base-path/app/foo', basePath, apps, getOrigin)).toEqual({
+ app: 'foo',
+ path: undefined,
+ });
+ expect(parseAppUrl('/base-path/custom-bar', basePath, apps, getOrigin)).toEqual({
+ app: 'bar',
+ path: undefined,
+ });
+ });
+ it('parses the path', () => {
+ expect(parseAppUrl('/base-path/app/foo/some/path', basePath, apps, getOrigin)).toEqual({
+ app: 'foo',
+ path: '/some/path',
+ });
+ expect(parseAppUrl('/base-path/custom-bar/another/path/', basePath, apps, getOrigin)).toEqual(
+ {
+ app: 'bar',
+ path: '/another/path/',
+ }
+ );
+ });
+ it('includes query and hash in the path for default app route', () => {
+ expect(parseAppUrl('/base-path/app/foo#hash/bang', basePath, apps, getOrigin)).toEqual({
+ app: 'foo',
+ path: '#hash/bang',
+ });
+ expect(parseAppUrl('/base-path/app/foo?hello=dolly', basePath, apps, getOrigin)).toEqual({
+ app: 'foo',
+ path: '?hello=dolly',
+ });
+ expect(parseAppUrl('/base-path/app/foo/path?hello=dolly', basePath, apps, getOrigin)).toEqual(
+ {
+ app: 'foo',
+ path: '/path?hello=dolly',
+ }
+ );
+ expect(parseAppUrl('/base-path/app/foo/path#hash/bang', basePath, apps, getOrigin)).toEqual({
+ app: 'foo',
+ path: '/path#hash/bang',
+ });
+ expect(
+ parseAppUrl('/base-path/app/foo/path#hash/bang?hello=dolly', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'foo',
+ path: '/path#hash/bang?hello=dolly',
+ });
+ });
+ it('includes query and hash in the path for custom app route', () => {
+ expect(parseAppUrl('/base-path/custom-bar#hash/bang', basePath, apps, getOrigin)).toEqual({
+ app: 'bar',
+ path: '#hash/bang',
+ });
+ expect(parseAppUrl('/base-path/custom-bar?hello=dolly', basePath, apps, getOrigin)).toEqual({
+ app: 'bar',
+ path: '?hello=dolly',
+ });
+ expect(
+ parseAppUrl('/base-path/custom-bar/path?hello=dolly', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'bar',
+ path: '/path?hello=dolly',
+ });
+ expect(
+ parseAppUrl('/base-path/custom-bar/path#hash/bang', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'bar',
+ path: '/path#hash/bang',
+ });
+ expect(
+ parseAppUrl('/base-path/custom-bar/path#hash/bang?hello=dolly', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'bar',
+ path: '/path#hash/bang?hello=dolly',
+ });
+ });
+ it('works with legacy apps', () => {
+ expect(parseAppUrl('/base-path/app/legacy', basePath, apps, getOrigin)).toEqual({
+ app: 'legacy',
+ path: undefined,
+ });
+ expect(
+ parseAppUrl('/base-path/app/legacy/path#hash?query=bar', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'legacy',
+ path: '/path#hash?query=bar',
+ });
+ });
+ it('returns undefined when the app is not known', () => {
+ expect(parseAppUrl('/base-path/app/non-registered', basePath, apps, getOrigin)).toEqual(
+ undefined
+ );
+ expect(parseAppUrl('/base-path/unknown-path', basePath, apps, getOrigin)).toEqual(undefined);
+ });
+ });
+
+ describe('with absolute urls', () => {
+ it('parses the app id', () => {
+ expect(
+ parseAppUrl('https://kibana.local:8080/base-path/app/foo', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'foo',
+ path: undefined,
+ });
+ expect(
+ parseAppUrl('https://kibana.local:8080/base-path/custom-bar', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'bar',
+ path: undefined,
+ });
+ });
+ it('parses the path', () => {
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo/some/path',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '/some/path',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar/another/path/',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '/another/path/',
+ });
+ });
+ it('includes query and hash in the path for default app routes', () => {
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo#hash/bang',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '#hash/bang',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '?hello=dolly',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo/path?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '/path?hello=dolly',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo/path#hash/bang',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '/path#hash/bang',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/foo/path#hash/bang?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'foo',
+ path: '/path#hash/bang?hello=dolly',
+ });
+ });
+ it('includes query and hash in the path for custom app route', () => {
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar#hash/bang',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '#hash/bang',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '?hello=dolly',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar/path?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '/path?hello=dolly',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar/path#hash/bang',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '/path#hash/bang',
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/custom-bar/path#hash/bang?hello=dolly',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'bar',
+ path: '/path#hash/bang?hello=dolly',
+ });
+ });
+ it('works with legacy apps', () => {
+ expect(
+ parseAppUrl('https://kibana.local:8080/base-path/app/legacy', basePath, apps, getOrigin)
+ ).toEqual({
+ app: 'legacy',
+ path: undefined,
+ });
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/legacy/path#hash?query=bar',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual({
+ app: 'legacy',
+ path: '/path#hash?query=bar',
+ });
+ });
+ it('returns undefined when the app is not known', () => {
+ expect(
+ parseAppUrl(
+ 'https://kibana.local:8080/base-path/app/non-registered',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual(undefined);
+ expect(
+ parseAppUrl('https://kibana.local:8080/base-path/unknown-path', basePath, apps, getOrigin)
+ ).toEqual(undefined);
+ });
+ it('returns undefined when origin does not match', () => {
+ expect(
+ parseAppUrl(
+ 'https://other-kibana.external:8080/base-path/app/foo',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual(undefined);
+ expect(
+ parseAppUrl(
+ 'https://other-kibana.external:8080/base-path/custom-bar',
+ basePath,
+ apps,
+ getOrigin
+ )
+ ).toEqual(undefined);
+ });
+ });
+});
diff --git a/src/core/public/application/utils.ts b/src/core/public/application/utils.ts
index 048f195fe1223..8987a9402f2db 100644
--- a/src/core/public/application/utils.ts
+++ b/src/core/public/application/utils.ts
@@ -17,6 +17,14 @@
* under the License.
*/
+import { IBasePath } from '../http';
+import { App, LegacyApp } from './types';
+
+export interface AppUrlInfo {
+ app: string;
+ path?: string;
+}
+
/**
* Utility to remove trailing, leading or duplicate slashes.
* By default will only remove duplicates.
@@ -52,3 +60,62 @@ export const appendAppPath = (appBasePath: string, path: string = '') => {
leading: false,
});
};
+
+export function isLegacyApp(app: App | LegacyApp): app is LegacyApp {
+ return app.legacy === true;
+}
+
+/**
+ * Converts a relative path to an absolute url.
+ * Implementation is based on a specified behavior of the browser to automatically convert
+ * a relative url to an absolute one when setting the `href` attribute of a `` html element.
+ *
+ * @example
+ * ```ts
+ * // current url: `https://kibana:8000/base-path/app/my-app`
+ * relativeToAbsolute('/base-path/app/another-app') => `https://kibana:8000/base-path/app/another-app`
+ * ```
+ */
+export const relativeToAbsolute = (url: string): string => {
+ const a = document.createElement('a');
+ a.setAttribute('href', url);
+ return a.href;
+};
+
+/**
+ * Parse given url and return the associated app id and path if any app matches.
+ * Input can either be:
+ * - a path containing the basePath, ie `/base-path/app/my-app/some-path`
+ * - an absolute url matching the `origin` of the kibana instance (as seen by the browser),
+ * i.e `https://kibana:8080/base-path/app/my-app/some-path`
+ */
+export const parseAppUrl = (
+ url: string,
+ basePath: IBasePath,
+ apps: Map | LegacyApp>,
+ getOrigin: () => string = () => window.location.origin
+): AppUrlInfo | undefined => {
+ url = removeBasePath(url, basePath, getOrigin());
+ if (!url.startsWith('/')) {
+ return undefined;
+ }
+
+ for (const app of apps.values()) {
+ const appPath = isLegacyApp(app) ? app.appUrl : app.appRoute || `/app/${app.id}`;
+
+ if (url.startsWith(appPath)) {
+ const path = url.substr(appPath.length);
+ return {
+ app: app.id,
+ path: path.length ? path : undefined,
+ };
+ }
+ }
+};
+
+const removeBasePath = (url: string, basePath: IBasePath, origin: string): string => {
+ if (url.startsWith(origin)) {
+ url = url.substring(origin.length);
+ }
+ return basePath.remove(url);
+};
diff --git a/src/core/public/chrome/chrome_service.test.ts b/src/core/public/chrome/chrome_service.test.ts
index b5cf900d9c39f..0bc305ed9e28c 100644
--- a/src/core/public/chrome/chrome_service.test.ts
+++ b/src/core/public/chrome/chrome_service.test.ts
@@ -56,7 +56,7 @@ function defaultStartDeps(availableApps?: App[]) {
if (availableApps) {
deps.application.applications$ = new Rx.BehaviorSubject>(
- new Map(availableApps.map(app => [app.id, app]))
+ new Map(availableApps.map((app) => [app.id, app]))
);
}
@@ -133,10 +133,7 @@ describe('start', () => {
describe('brand', () => {
it('updates/emits the brand as it changes', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getBrand$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getBrand$().pipe(toArray()).toPromise();
chrome.setBrand({
logo: 'big logo',
@@ -166,10 +163,7 @@ describe('start', () => {
describe('visibility', () => {
it('emits false when no application is mounted', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getIsVisible$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getIsVisible$().pipe(toArray()).toPromise();
chrome.setIsVisible(true);
chrome.setIsVisible(false);
@@ -192,10 +186,7 @@ describe('start', () => {
const { navigateToApp } = startDeps.application;
const { chrome, service } = await start({ startDeps });
- const promise = chrome
- .getIsVisible$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getIsVisible$().pipe(toArray()).toPromise();
await navigateToApp('alpha');
@@ -222,13 +213,10 @@ describe('start', () => {
]);
const { applications$, navigateToApp } = startDeps.application;
const { chrome, service } = await start({ startDeps });
- const promise = chrome
- .getIsVisible$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getIsVisible$().pipe(toArray()).toPromise();
const availableApps = await applications$.pipe(take(1)).toPromise();
- [...availableApps.keys()].forEach(appId => navigateToApp(appId));
+ [...availableApps.keys()].forEach((appId) => navigateToApp(appId));
service.stop();
await expect(promise).resolves.toMatchInlineSnapshot(`
@@ -245,10 +233,7 @@ describe('start', () => {
const startDeps = defaultStartDeps([new FakeApp('alpha', true)]);
const { navigateToApp } = startDeps.application;
const { chrome, service } = await start({ startDeps });
- const promise = chrome
- .getIsVisible$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getIsVisible$().pipe(toArray()).toPromise();
await navigateToApp('alpha');
chrome.setIsVisible(true);
@@ -267,10 +252,7 @@ describe('start', () => {
describe('application classes', () => {
it('updates/emits the application classes', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getApplicationClasses$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getApplicationClasses$().pipe(toArray()).toPromise();
chrome.addApplicationClass('foo');
chrome.addApplicationClass('foo');
@@ -318,10 +300,7 @@ describe('start', () => {
describe('badge', () => {
it('updates/emits the current badge', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getBadge$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getBadge$().pipe(toArray()).toPromise();
chrome.setBadge({ text: 'foo', tooltip: `foo's tooltip` });
chrome.setBadge({ text: 'bar', tooltip: `bar's tooltip` });
@@ -348,10 +327,7 @@ describe('start', () => {
describe('breadcrumbs', () => {
it('updates/emits the current set of breadcrumbs', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getBreadcrumbs$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getBreadcrumbs$().pipe(toArray()).toPromise();
chrome.setBreadcrumbs([{ text: 'foo' }, { text: 'bar' }]);
chrome.setBreadcrumbs([{ text: 'foo' }]);
@@ -389,10 +365,7 @@ describe('start', () => {
describe('help extension', () => {
it('updates/emits the current help extension', async () => {
const { chrome, service } = await start();
- const promise = chrome
- .getHelpExtension$()
- .pipe(toArray())
- .toPromise();
+ const promise = chrome.getHelpExtension$().pipe(toArray()).toPromise();
chrome.setHelpExtension({ appName: 'App name', content: () => () => undefined });
chrome.setHelpExtension(undefined);
diff --git a/src/core/public/chrome/chrome_service.tsx b/src/core/public/chrome/chrome_service.tsx
index a921e514050b2..fc7e78f209022 100644
--- a/src/core/public/chrome/chrome_service.tsx
+++ b/src/core/public/chrome/chrome_service.tsx
@@ -117,9 +117,9 @@ export class ChromeService {
// in the sense that the chrome UI should not be displayed until a non-chromeless app is mounting or mounted
of(true),
application.currentAppId$.pipe(
- flatMap(appId =>
+ flatMap((appId) =>
application.applications$.pipe(
- map(applications => {
+ map((applications) => {
return !!appId && applications.has(appId) && !!applications.get(appId)!.chromeless;
})
)
@@ -260,7 +260,7 @@ export class ChromeService {
getApplicationClasses$: () =>
applicationClasses$.pipe(
- map(set => [...set]),
+ map((set) => [...set]),
takeUntil(this.stop$)
),
diff --git a/src/core/public/chrome/doc_title/doc_title_service.ts b/src/core/public/chrome/doc_title/doc_title_service.ts
index 9453abe54de66..c6e9ec7a40b77 100644
--- a/src/core/public/chrome/doc_title/doc_title_service.ts
+++ b/src/core/public/chrome/doc_title/doc_title_service.ts
@@ -86,7 +86,7 @@ export class DocTitleService {
this.applyTitle(defaultTitle);
},
__legacy: {
- setBaseTitle: baseTitle => {
+ setBaseTitle: (baseTitle) => {
this.baseTitle = baseTitle;
},
},
diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts
index c8f168bbcb2f7..ac556c1d1cc5d 100644
--- a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts
+++ b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts
@@ -30,12 +30,7 @@ describe('RecentlyAccessed#start()', () => {
const navControls = getStart();
const nc = { mount: jest.fn() };
navControls.registerLeft(nc);
- expect(
- await navControls
- .getLeft$()
- .pipe(take(1))
- .toPromise()
- ).toEqual([nc]);
+ expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc]);
});
it('sorts controls by order property', async () => {
@@ -46,12 +41,7 @@ describe('RecentlyAccessed#start()', () => {
navControls.registerLeft(nc1);
navControls.registerLeft(nc2);
navControls.registerLeft(nc3);
- expect(
- await navControls
- .getLeft$()
- .pipe(take(1))
- .toPromise()
- ).toEqual([nc2, nc1, nc3]);
+ expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]);
});
});
@@ -60,12 +50,7 @@ describe('RecentlyAccessed#start()', () => {
const navControls = getStart();
const nc = { mount: jest.fn() };
navControls.registerRight(nc);
- expect(
- await navControls
- .getRight$()
- .pipe(take(1))
- .toPromise()
- ).toEqual([nc]);
+ expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc]);
});
it('sorts controls by order property', async () => {
@@ -76,12 +61,7 @@ describe('RecentlyAccessed#start()', () => {
navControls.registerRight(nc1);
navControls.registerRight(nc2);
navControls.registerRight(nc3);
- expect(
- await navControls
- .getRight$()
- .pipe(take(1))
- .toPromise()
- ).toEqual([nc2, nc1, nc3]);
+ expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]);
});
});
});
diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.ts b/src/core/public/chrome/nav_controls/nav_controls_service.ts
index 7f9c75595a4ce..167948e01cb36 100644
--- a/src/core/public/chrome/nav_controls/nav_controls_service.ts
+++ b/src/core/public/chrome/nav_controls/nav_controls_service.ts
@@ -74,12 +74,12 @@ export class NavControlsService {
getLeft$: () =>
navControlsLeft$.pipe(
- map(controls => sortBy([...controls.values()], 'order')),
+ map((controls) => sortBy([...controls.values()], 'order')),
takeUntil(this.stop$)
),
getRight$: () =>
navControlsRight$.pipe(
- map(controls => sortBy([...controls.values()], 'order')),
+ map((controls) => sortBy([...controls.values()], 'order')),
takeUntil(this.stop$)
),
};
diff --git a/src/core/public/chrome/nav_links/nav_links_service.test.ts b/src/core/public/chrome/nav_links/nav_links_service.test.ts
index 3d9a4bfdb6a56..8f610e238b0fd 100644
--- a/src/core/public/chrome/nav_links/nav_links_service.test.ts
+++ b/src/core/public/chrome/nav_links/nav_links_service.test.ts
@@ -90,7 +90,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).not.toContain('chromelessApp');
@@ -102,16 +102,16 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']);
});
it('emits multiple values', async () => {
- const navLinkIds$ = start.getNavLinks$().pipe(map(links => links.map(l => l.id)));
+ const navLinkIds$ = start.getNavLinks$().pipe(map((links) => links.map((l) => l.id)));
const emittedLinks: string[][] = [];
- navLinkIds$.subscribe(r => emittedLinks.push(r));
+ navLinkIds$.subscribe((r) => emittedLinks.push(r));
start.update('legacyApp1', { active: true });
service.stop();
@@ -122,10 +122,7 @@ describe('NavLinksService', () => {
});
it('completes when service is stopped', async () => {
- const last$ = start
- .getNavLinks$()
- .pipe(takeLast(1))
- .toPromise();
+ const last$ = start.getNavLinks$().pipe(takeLast(1)).toPromise();
service.stop();
await expect(last$).resolves.toBeInstanceOf(Array);
});
@@ -143,7 +140,7 @@ describe('NavLinksService', () => {
describe('#getAll()', () => {
it('returns a sorted array of navlinks', () => {
- expect(start.getAll().map(l => l.id)).toEqual([
+ expect(start.getAll().map((l) => l.id)).toEqual([
'app2',
'legacyApp2',
'app1',
@@ -171,7 +168,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']);
@@ -184,7 +181,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']);
@@ -197,7 +194,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).toEqual(['legacyApp1']);
@@ -211,7 +208,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.map(l => l.id))
+ map((links) => links.map((l) => l.id))
)
.toPromise()
).toEqual(['legacyApp2']);
@@ -236,7 +233,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.filter(l => l.hidden).map(l => l.id))
+ map((links) => links.filter((l) => l.hidden).map((l) => l.id))
)
.toPromise();
expect(hiddenLinkIds).toEqual(['legacyApp1']);
@@ -253,7 +250,7 @@ describe('NavLinksService', () => {
.getNavLinks$()
.pipe(
take(1),
- map(links => links.filter(l => l.hidden).map(l => l.id))
+ map((links) => links.filter((l) => l.hidden).map((l) => l.id))
)
.toPromise();
expect(hiddenLinkIds).toEqual(['legacyApp1']);
@@ -262,21 +259,15 @@ describe('NavLinksService', () => {
describe('#enableForcedAppSwitcherNavigation()', () => {
it('flips #getForceAppSwitcherNavigation$()', async () => {
- await expect(
- start
- .getForceAppSwitcherNavigation$()
- .pipe(take(1))
- .toPromise()
- ).resolves.toBe(false);
+ await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe(
+ false
+ );
start.enableForcedAppSwitcherNavigation();
- await expect(
- start
- .getForceAppSwitcherNavigation$()
- .pipe(take(1))
- .toPromise()
- ).resolves.toBe(true);
+ await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe(
+ true
+ );
});
});
});
diff --git a/src/core/public/chrome/nav_links/nav_links_service.ts b/src/core/public/chrome/nav_links/nav_links_service.ts
index fec9322b0d77d..3095bb86b72e2 100644
--- a/src/core/public/chrome/nav_links/nav_links_service.ts
+++ b/src/core/public/chrome/nav_links/nav_links_service.ts
@@ -108,7 +108,7 @@ export class NavLinksService {
public start({ application, http }: StartDeps): ChromeNavLinks {
const appLinks$ = application.applications$.pipe(
- map(apps => {
+ map((apps) => {
return new Map(
[...apps]
.filter(([, app]) => !app.chromeless)
@@ -129,7 +129,7 @@ export class NavLinksService {
return linkUpdaters.reduce((links, updater) => updater(links), appLinks);
})
)
- .subscribe(navlinks => {
+ .subscribe((navlinks) => {
navLinks$.next(navlinks);
});
@@ -158,7 +158,7 @@ export class NavLinksService {
return;
}
- const updater: LinksUpdater = navLinks =>
+ const updater: LinksUpdater = (navLinks) =>
new Map([...navLinks.entries()].filter(([linkId]) => linkId === id));
linkUpdaters$.next([...linkUpdaters$.value, updater]);
@@ -169,7 +169,7 @@ export class NavLinksService {
return;
}
- const updater: LinksUpdater = navLinks =>
+ const updater: LinksUpdater = (navLinks) =>
new Map(
[...navLinks.entries()].map(([linkId, link]) => {
return [linkId, link.id === id ? link.update(values) : link] as [
@@ -200,7 +200,7 @@ export class NavLinksService {
function sortNavLinks(navLinks: ReadonlyMap) {
return sortBy(
- [...navLinks.values()].map(link => link.properties),
+ [...navLinks.values()].map((link) => link.properties),
'order'
);
}
diff --git a/src/core/public/chrome/recently_accessed/persisted_log.ts b/src/core/public/chrome/recently_accessed/persisted_log.ts
index 421f553f6a315..ca94e0bcddfaf 100644
--- a/src/core/public/chrome/recently_accessed/persisted_log.ts
+++ b/src/core/public/chrome/recently_accessed/persisted_log.ts
@@ -57,7 +57,7 @@ export class PersistedLog {
const nextItems = [
val,
// remove any duplicate items
- ...[...this.items$.value].filter(item => !this.isEqual(item, val)),
+ ...[...this.items$.value].filter((item) => !this.isEqual(item, val)),
].slice(0, this.maxLength); // truncate
// Persist the stack to storage
@@ -73,7 +73,7 @@ export class PersistedLog {
}
public get$() {
- return this.items$.pipe(map(items => cloneDeep(items)));
+ return this.items$.pipe(map((items) => cloneDeep(items)));
}
private loadItems() {
diff --git a/src/core/public/chrome/ui/header/collapsible_nav.tsx b/src/core/public/chrome/ui/header/collapsible_nav.tsx
index 60463d8dccc9b..8bca42db23517 100644
--- a/src/core/public/chrome/ui/header/collapsible_nav.tsx
+++ b/src/core/public/chrome/ui/header/collapsible_nav.tsx
@@ -50,7 +50,7 @@ function getOrderedCategories(
) {
return sortBy(
Object.keys(mainCategories),
- categoryName => categoryDictionary[categoryName]?.order
+ (categoryName) => categoryDictionary[categoryName]?.order
);
}
@@ -94,7 +94,7 @@ export function CollapsibleNav({
storage = window.localStorage,
}: Props) {
const lockRef = useRef(null);
- const groupedNavLinks = groupBy(navLinks, link => link?.category?.id);
+ const groupedNavLinks = groupBy(navLinks, (link) => link?.category?.id);
const { undefined: unknowns = [], ...allCategorizedLinks } = groupedNavLinks;
const categoryDictionary = getAllCategories(allCategorizedLinks);
const orderedCategories = getOrderedCategories(allCategorizedLinks, categoryDictionary);
@@ -156,7 +156,7 @@ export function CollapsibleNav({
title={i18n.translate('core.ui.recentlyViewed', { defaultMessage: 'Recently viewed' })}
isCollapsible={true}
initialIsOpen={getIsCategoryOpen('recentlyViewed', storage)}
- onToggle={isCategoryOpen => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)}
+ onToggle={(isCategoryOpen) => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)}
data-test-subj="collapsibleNavGroup-recentlyViewed"
>
{recentNavLinks.length > 0 ? (
@@ -218,7 +218,7 @@ export function CollapsibleNav({
title={category.label}
isCollapsible={true}
initialIsOpen={getIsCategoryOpen(category.id, storage)}
- onToggle={isCategoryOpen => setIsCategoryOpen(category.id, isCategoryOpen, storage)}
+ onToggle={(isCategoryOpen) => setIsCategoryOpen(category.id, isCategoryOpen, storage)}
data-test-subj={`collapsibleNavGroup-${category.id}`}
>
{
super(props);
let isLocked = false;
- props.isLocked$.subscribe(initialIsLocked => (isLocked = initialIsLocked));
+ props.isLocked$.subscribe((initialIsLocked) => (isLocked = initialIsLocked));
this.state = {
appTitle: 'Kibana',
@@ -142,7 +142,7 @@ export class Header extends Component {
appTitle,
isVisible,
forceNavigation,
- navLinks: navLinks.filter(navLink => !navLink.hidden),
+ navLinks: navLinks.filter((navLink) => !navLink.hidden),
recentlyAccessed,
navControlsLeft,
navControlsRight,
@@ -183,7 +183,7 @@ export class Header extends Component {
kibanaDocLink,
kibanaVersion,
} = this.props;
- const navLinks = this.state.navLinks.map(link =>
+ const navLinks = this.state.navLinks.map((link) =>
createNavLink(
link,
this.props.legacyMode,
@@ -192,7 +192,7 @@ export class Header extends Component {
this.props.application.navigateToApp
)
);
- const recentNavLinks = this.state.recentlyAccessed.map(link =>
+ const recentNavLinks = this.state.recentlyAccessed.map((link) =>
createRecentNavLink(link, this.state.navLinks, this.props.basePath)
);
diff --git a/src/core/public/chrome/ui/header/header_badge.tsx b/src/core/public/chrome/ui/header/header_badge.tsx
index 4e529ad9a410b..d2d5e5d663300 100644
--- a/src/core/public/chrome/ui/header/header_badge.tsx
+++ b/src/core/public/chrome/ui/header/header_badge.tsx
@@ -77,7 +77,7 @@ export class HeaderBadge extends Component {
}
private subscribe() {
- this.subscription = this.props.badge$.subscribe(badge => {
+ this.subscription = this.props.badge$.subscribe((badge) => {
this.setState({
badge,
});
diff --git a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx
index 83840cff45d03..54cfc7131cb2b 100644
--- a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx
+++ b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx
@@ -70,7 +70,7 @@ export class HeaderBreadcrumbs extends Component {
}
private subscribe() {
- this.subscription = this.props.breadcrumbs$.subscribe(breadcrumbs => {
+ this.subscription = this.props.breadcrumbs$.subscribe((breadcrumbs) => {
this.setState({
breadcrumbs,
});
diff --git a/src/core/public/chrome/ui/header/header_logo.tsx b/src/core/public/chrome/ui/header/header_logo.tsx
index 4296064945455..147c7cf5dc4b1 100644
--- a/src/core/public/chrome/ui/header/header_logo.tsx
+++ b/src/core/public/chrome/ui/header/header_logo.tsx
@@ -49,7 +49,7 @@ function onClick(
return;
}
- const navLink = navLinks.find(item => item.href === anchor.href);
+ const navLink = navLinks.find((item) => item.href === anchor.href);
if (navLink && navLink.isDisabled) {
event.preventDefault();
return;
@@ -95,7 +95,7 @@ export function HeaderLogo({ href, forceNavigation, navLinks, navigateToApp }: P
onClick(e, forceNavigation, navLinks, navigateToApp)}
+ onClick={(e) => onClick(e, forceNavigation, navLinks, navigateToApp)}
href={href}
aria-label={i18n.translate('core.ui.chrome.headerGlobalNav.goHomePageIconAriaLabel', {
defaultMessage: 'Go to home page',
diff --git a/src/core/public/chrome/ui/header/nav_link.tsx b/src/core/public/chrome/ui/header/nav_link.tsx
index 8003c22b99a36..c979bb8271e1b 100644
--- a/src/core/public/chrome/ui/header/nav_link.tsx
+++ b/src/core/public/chrome/ui/header/nav_link.tsx
@@ -161,7 +161,7 @@ export function createRecentNavLink(
) {
const { link, label } = recentLink;
const href = relativeToAbsolute(basePath.prepend(link));
- const navLink = navLinks.find(nl => href.startsWith(nl.baseUrl ?? nl.subUrlBase));
+ const navLink = navLinks.find((nl) => href.startsWith(nl.baseUrl ?? nl.subUrlBase));
let titleAndAriaLabel = label;
if (navLink) {
diff --git a/src/core/public/chrome/ui/loading_indicator.tsx b/src/core/public/chrome/ui/loading_indicator.tsx
index 7729302b6b612..0209612eae08c 100644
--- a/src/core/public/chrome/ui/loading_indicator.tsx
+++ b/src/core/public/chrome/ui/loading_indicator.tsx
@@ -35,7 +35,7 @@ export class LoadingIndicator extends React.Component {
+ this.loadingCountSubscription = this.props.loadingCount$.subscribe((count) => {
this.setState({
visible: count > 0,
});
diff --git a/src/core/public/entry_point.ts b/src/core/public/entry_point.ts
index 9461acccf30b9..25180c13ccbd4 100644
--- a/src/core/public/entry_point.ts
+++ b/src/core/public/entry_point.ts
@@ -33,7 +33,11 @@ const injectedMetadata = JSON.parse(
document.querySelector('kbn-injected-metadata')!.getAttribute('data')!
);
-if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && process.env.ELASTIC_APM_ACTIVE === 'true') {
+/**
+ * `apmConfig` would be populated with relavant APM RUM agent
+ * configuration if server is started with `ELASTIC_APM_ACTIVE=true`
+ */
+if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && injectedMetadata.vars.apmConfig != null) {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { init } = require('@elastic/apm-rum');
@@ -42,8 +46,8 @@ if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && process.env.ELASTIC_APM_AC
i18n
.load(injectedMetadata.i18n.translationsUrl)
- .catch(e => e)
- .then(async i18nError => {
+ .catch((e) => e)
+ .then(async (i18nError) => {
const coreSystem = new CoreSystem({
injectedMetadata,
rootDomElement: document.body,
diff --git a/src/core/public/fatal_errors/fatal_errors_screen.tsx b/src/core/public/fatal_errors/fatal_errors_screen.tsx
index f7184b01a0a78..98eb9f0ef21d5 100644
--- a/src/core/public/fatal_errors/fatal_errors_screen.tsx
+++ b/src/core/public/fatal_errors/fatal_errors_screen.tsx
@@ -63,8 +63,8 @@ export class FatalErrorsScreen extends React.Component {
// consume error notifications and set them to the component state
this.props.errorInfo$.pipe(
- tap(error => {
- this.setState(state => ({
+ tap((error) => {
+ this.setState((state) => ({
...state,
errors: [...state.errors, error],
}));
diff --git a/src/core/public/fatal_errors/fatal_errors_service.test.ts b/src/core/public/fatal_errors/fatal_errors_service.test.ts
index 373b0efddc2cf..a39f31d2c559c 100644
--- a/src/core/public/fatal_errors/fatal_errors_service.test.ts
+++ b/src/core/public/fatal_errors/fatal_errors_service.test.ts
@@ -20,7 +20,7 @@
import * as Rx from 'rxjs';
expect.addSnapshotSerializer({
- test: val => val instanceof Rx.Observable,
+ test: (val) => val instanceof Rx.Observable,
print: () => `Rx.Observable`,
});
diff --git a/src/core/public/fatal_errors/fatal_errors_service.tsx b/src/core/public/fatal_errors/fatal_errors_service.tsx
index 309f07859ef26..403f8925b99c7 100644
--- a/src/core/public/fatal_errors/fatal_errors_service.tsx
+++ b/src/core/public/fatal_errors/fatal_errors_service.tsx
@@ -85,7 +85,7 @@ export class FatalErrorsService {
})
)
.subscribe({
- error: error => {
+ error: (error) => {
// eslint-disable-next-line no-console
console.error('Uncaught error in fatal error service internals', error);
},
@@ -145,7 +145,7 @@ export class FatalErrorsService {
private setupGlobalErrorHandlers(fatalErrorsSetup: FatalErrorsSetup) {
if (window.addEventListener) {
- window.addEventListener('unhandledrejection', function(e) {
+ window.addEventListener('unhandledrejection', function (e) {
console.log(`Detected an unhandled Promise rejection.\n${e.reason}`); // eslint-disable-line no-console
});
}
diff --git a/src/core/public/http/base_path.ts b/src/core/public/http/base_path.ts
index 67464a6196b02..ac85d71c793fe 100644
--- a/src/core/public/http/base_path.ts
+++ b/src/core/public/http/base_path.ts
@@ -49,7 +49,7 @@ export class BasePath {
public prepend = (path: string): string => {
if (!this.basePath) return path;
- return modifyUrl(path, parts => {
+ return modifyUrl(path, (parts) => {
if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) {
parts.pathname = `${this.basePath}${parts.pathname}`;
}
diff --git a/src/core/public/http/fetch.test.ts b/src/core/public/http/fetch.test.ts
index f223956075e97..d889fae335ece 100644
--- a/src/core/public/http/fetch.test.ts
+++ b/src/core/public/http/fetch.test.ts
@@ -28,7 +28,7 @@ import { BasePath } from './base_path';
import { HttpResponse, HttpFetchOptionsWithPath } from './types';
function delay(duration: number) {
- return new Promise(r => setTimeout(r, duration));
+ return new Promise((r) => setTimeout(r, duration));
}
const BASE_PATH = 'http://localhost/myBase';
@@ -44,11 +44,7 @@ describe('Fetch', () => {
});
describe('getRequestCount$', () => {
- const getCurrentRequestCount = () =>
- fetchInstance
- .getRequestCount$()
- .pipe(first())
- .toPromise();
+ const getCurrentRequestCount = () => fetchInstance.getRequestCount$().pipe(first()).toPromise();
it('should increase and decrease when request receives success response', async () => {
fetchMock.get('*', 200);
@@ -88,7 +84,7 @@ describe('Fetch', () => {
const requestCounts: number[] = [];
const subscription = fetchInstance
.getRequestCount$()
- .subscribe(count => requestCounts.push(count));
+ .subscribe((count) => requestCounts.push(count));
const success1 = fetchInstance.fetch('/success');
const success2 = fetchInstance.fetch('/success');
@@ -371,7 +367,7 @@ describe('Fetch', () => {
fetchMock.get('*', Promise.reject(abortError));
- await fetchInstance.fetch('/my/path').catch(e => {
+ await fetchInstance.fetch('/my/path').catch((e) => {
expect(e.name).toEqual('AbortError');
});
});
diff --git a/src/core/public/http/fetch.ts b/src/core/public/http/fetch.ts
index d88dc2e3a9037..bf9b4235e9444 100644
--- a/src/core/public/http/fetch.ts
+++ b/src/core/public/http/fetch.ts
@@ -212,7 +212,7 @@ const validateFetchArguments = (
);
}
- const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter(headerName =>
+ const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter((headerName) =>
headerName.startsWith('kbn-')
);
if (invalidHeaders.length) {
diff --git a/src/core/public/http/intercept.ts b/src/core/public/http/intercept.ts
index bacc8748d2680..be02ebbf94fae 100644
--- a/src/core/public/http/intercept.ts
+++ b/src/core/public/http/intercept.ts
@@ -31,7 +31,7 @@ export async function interceptRequest(
return [...interceptors].reduceRight(
(promise, interceptor) =>
promise.then(
- async fetchOptions => {
+ async (fetchOptions) => {
current = fetchOptions;
checkHalt(controller);
@@ -45,7 +45,7 @@ export async function interceptRequest(
...overrides,
};
},
- async error => {
+ async (error) => {
checkHalt(controller, error);
if (!interceptor.requestError) {
@@ -83,7 +83,7 @@ export async function interceptResponse(
return await [...interceptors].reduce(
(promise, interceptor) =>
promise.then(
- async httpResponse => {
+ async (httpResponse) => {
current = httpResponse;
checkHalt(controller);
@@ -98,7 +98,7 @@ export async function interceptResponse(
...interceptorOverrides,
};
},
- async error => {
+ async (error) => {
const request = error.request || (current && current.request);
checkHalt(controller, error);
diff --git a/src/core/public/http/loading_count_service.test.ts b/src/core/public/http/loading_count_service.test.ts
index 3ba4d315178cc..706d62b4283ba 100644
--- a/src/core/public/http/loading_count_service.test.ts
+++ b/src/core/public/http/loading_count_service.test.ts
@@ -89,10 +89,7 @@ describe('LoadingCountService', () => {
const countA$ = new Subject();
const countB$ = new Subject();
const countC$ = new Subject();
- const promise = loadingCount
- .getLoadingCount$()
- .pipe(toArray())
- .toPromise();
+ const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise();
loadingCount.addLoadingCountSource(countA$);
loadingCount.addLoadingCountSource(countB$);
@@ -125,10 +122,7 @@ describe('LoadingCountService', () => {
const { service, loadingCount } = setup();
const count$ = new Subject();
- const promise = loadingCount
- .getLoadingCount$()
- .pipe(toArray())
- .toPromise();
+ const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise();
loadingCount.addLoadingCountSource(count$);
count$.next(0);
diff --git a/src/core/public/http/loading_count_service.ts b/src/core/public/http/loading_count_service.ts
index 14b945e0801ca..e4a248daca8f2 100644
--- a/src/core/public/http/loading_count_service.ts
+++ b/src/core/public/http/loading_count_service.ts
@@ -56,7 +56,7 @@ export class LoadingCountService implements CoreService {
+ tap((count) => {
if (count < 0) {
throw new Error(
'Observables passed to loadingCount.add() must only emit positive numbers'
@@ -73,10 +73,10 @@ export class LoadingCountService implements CoreService next - prev)
)
.subscribe({
- next: delta => {
+ next: (delta) => {
this.loadingCount$.next(this.loadingCount$.getValue() + delta);
},
- error: error => fatalErrors.add(error),
+ error: (error) => fatalErrors.add(error),
});
},
};
diff --git a/src/core/public/integrations/moment/moment_service.test.mocks.ts b/src/core/public/integrations/moment/moment_service.test.mocks.ts
index bb13232157b78..4c0c584679b2c 100644
--- a/src/core/public/integrations/moment/moment_service.test.mocks.ts
+++ b/src/core/public/integrations/moment/moment_service.test.mocks.ts
@@ -22,7 +22,7 @@ export const momentMock = {
tz: {
setDefault: jest.fn(),
zone: jest.fn(
- z => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find(f => z === f.name) || null
+ (z) => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find((f) => z === f.name) || null
),
},
weekdays: jest.fn(() => ['dow1', 'dow2', 'dow3']),
diff --git a/src/core/public/integrations/moment/moment_service.test.ts b/src/core/public/integrations/moment/moment_service.test.ts
index bc48ba2a85f63..5179ff468f84d 100644
--- a/src/core/public/integrations/moment/moment_service.test.ts
+++ b/src/core/public/integrations/moment/moment_service.test.ts
@@ -32,7 +32,7 @@ describe('MomentService', () => {
});
afterEach(() => service.stop());
- const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100));
+ const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100));
test('sets initial moment config', async () => {
const tz$ = new BehaviorSubject('tz1');
diff --git a/src/core/public/integrations/styles/styles_service.test.ts b/src/core/public/integrations/styles/styles_service.test.ts
index e413e9cc2f4d7..fc75c6b3e3d06 100644
--- a/src/core/public/integrations/styles/styles_service.test.ts
+++ b/src/core/public/integrations/styles/styles_service.test.ts
@@ -25,7 +25,7 @@ import { StylesService } from './styles_service';
import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.mock';
describe('StylesService', () => {
- const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100));
+ const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100));
const getDisableAnimationsTag = () => document.querySelector('style#disableAnimationsCss')!;
afterEach(() => getDisableAnimationsTag().remove());
diff --git a/src/core/public/legacy/legacy_service.ts b/src/core/public/legacy/legacy_service.ts
index 01837ba6f5940..810416cdbfe16 100644
--- a/src/core/public/legacy/legacy_service.ts
+++ b/src/core/public/legacy/legacy_service.ts
@@ -115,8 +115,8 @@ export class LegacyPlatformService {
// Initialize legacy sub urls
core.chrome.navLinks
.getAll()
- .filter(link => link.legacy)
- .forEach(navLink => {
+ .filter((link) => link.legacy)
+ .forEach((navLink) => {
const lastSubUrl = lastSubUrlStorage.getItem(`lastSubUrl:${navLink.baseUrl}`);
core.chrome.navLinks.update(navLink.id, {
url: lastSubUrl || navLink.url || navLink.baseUrl,
@@ -135,6 +135,7 @@ export class LegacyPlatformService {
capabilities: core.application.capabilities,
getUrlForApp: core.application.getUrlForApp,
navigateToApp: core.application.navigateToApp,
+ navigateToUrl: core.application.navigateToUrl,
registerMountContext: notSupported(`core.application.registerMountContext()`),
},
};
diff --git a/src/core/public/notifications/toasts/global_toast_list.test.tsx b/src/core/public/notifications/toasts/global_toast_list.test.tsx
index dc2a9dabe791e..1d5d5b86836fd 100644
--- a/src/core/public/notifications/toasts/global_toast_list.test.tsx
+++ b/src/core/public/notifications/toasts/global_toast_list.test.tsx
@@ -34,7 +34,7 @@ it('renders matching snapshot', () => {
it('subscribes to toasts$ on mount and unsubscribes on unmount', () => {
const unsubscribeSpy = jest.fn();
- const subscribeSpy = jest.fn(observer => {
+ const subscribeSpy = jest.fn((observer) => {
observer.next([]);
return unsubscribeSpy;
});
diff --git a/src/core/public/notifications/toasts/global_toast_list.tsx b/src/core/public/notifications/toasts/global_toast_list.tsx
index f96a0a6f362bf..cb2d90ff265bf 100644
--- a/src/core/public/notifications/toasts/global_toast_list.tsx
+++ b/src/core/public/notifications/toasts/global_toast_list.tsx
@@ -47,7 +47,7 @@ export class GlobalToastList extends React.Component {
private subscription?: Rx.Subscription;
public componentDidMount() {
- this.subscription = this.props.toasts$.subscribe(toasts => {
+ this.subscription = this.props.toasts$.subscribe((toasts) => {
this.setState({ toasts });
});
}
diff --git a/src/core/public/notifications/toasts/toasts_api.test.ts b/src/core/public/notifications/toasts/toasts_api.test.ts
index 7c0ef5576256a..08e1d9711322c 100644
--- a/src/core/public/notifications/toasts/toasts_api.test.ts
+++ b/src/core/public/notifications/toasts/toasts_api.test.ts
@@ -25,10 +25,7 @@ import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.moc
import { i18nServiceMock } from '../../i18n/i18n_service.mock';
async function getCurrentToasts(toasts: ToastsApi) {
- return await toasts
- .get$()
- .pipe(take(1))
- .toPromise();
+ return await toasts.get$().pipe(take(1)).toPromise();
}
function uiSettingsMock() {
diff --git a/src/core/public/notifications/toasts/toasts_api.tsx b/src/core/public/notifications/toasts/toasts_api.tsx
index 53717b9c2e174..db65ed76d1cb1 100644
--- a/src/core/public/notifications/toasts/toasts_api.tsx
+++ b/src/core/public/notifications/toasts/toasts_api.tsx
@@ -150,7 +150,7 @@ export class ToastsApi implements IToasts {
public remove(toastOrId: Toast | string) {
const toRemove = typeof toastOrId === 'string' ? toastOrId : toastOrId.id;
const list = this.toasts$.getValue();
- const listWithoutToast = list.filter(t => t.id !== toRemove);
+ const listWithoutToast = list.filter((t) => t.id !== toRemove);
if (listWithoutToast.length !== list.length) {
this.toasts$.next(listWithoutToast);
}
diff --git a/src/core/public/overlays/banners/banners_list.tsx b/src/core/public/overlays/banners/banners_list.tsx
index ee7aa73dc34a6..6503af985f9c8 100644
--- a/src/core/public/overlays/banners/banners_list.tsx
+++ b/src/core/public/overlays/banners/banners_list.tsx
@@ -47,7 +47,7 @@ export const BannersList: React.FunctionComponent = ({ banners$ }) => {
return (
- {banners.map(banner => (
+ {banners.map((banner) => (
))}
diff --git a/src/core/public/overlays/banners/banners_service.test.ts b/src/core/public/overlays/banners/banners_service.test.ts
index f11a5d6b88bc2..8e76a18178ff0 100644
--- a/src/core/public/overlays/banners/banners_service.test.ts
+++ b/src/core/public/overlays/banners/banners_service.test.ts
@@ -31,11 +31,7 @@ describe('OverlayBannersService', () => {
});
});
- const currentBanners = () =>
- service
- .get$()
- .pipe(take(1))
- .toPromise();
+ const currentBanners = () => service.get$().pipe(take(1)).toPromise();
describe('adding banners', () => {
test('adds a single banner', async () => {
diff --git a/src/core/public/overlays/banners/banners_service.tsx b/src/core/public/overlays/banners/banners_service.tsx
index ed59ed819b1c2..c0f76a6deaac7 100644
--- a/src/core/public/overlays/banners/banners_service.tsx
+++ b/src/core/public/overlays/banners/banners_service.tsx
@@ -112,7 +112,7 @@ export class OverlayBannersService {
},
get$() {
- return banners$.pipe(map(bannerMap => [...bannerMap.values()]));
+ return banners$.pipe(map((bannerMap) => [...bannerMap.values()]));
},
getComponent() {
diff --git a/src/core/public/overlays/banners/user_banner_service.tsx b/src/core/public/overlays/banners/user_banner_service.tsx
index e3f4d9dee5b78..643d95a1e3bb4 100644
--- a/src/core/public/overlays/banners/user_banner_service.tsx
+++ b/src/core/public/overlays/banners/user_banner_service.tsx
@@ -63,7 +63,7 @@ export class UserBannerService {
id = banners.replace(
id,
- el => {
+ (el) => {
ReactDOM.render(
{
describe('openModal()', () => {
it('renders a modal to the DOM', () => {
expect(mockReactDomRender).not.toHaveBeenCalled();
- modals.open(container => {
+ modals.open((container) => {
const content = document.createElement('span');
content.textContent = 'Modal content';
container.append(content);
@@ -104,7 +104,7 @@ describe('ModalService', () => {
describe('openConfirm()', () => {
it('renders a mountpoint confirm message', () => {
expect(mockReactDomRender).not.toHaveBeenCalled();
- modals.openConfirm(container => {
+ modals.openConfirm((container) => {
const content = document.createElement('span');
content.textContent = 'Modal content';
container.append(content);
diff --git a/src/core/public/overlays/overlay.test.mocks.ts b/src/core/public/overlays/overlay.test.mocks.ts
index 563f414a0ae99..f382511d445ea 100644
--- a/src/core/public/overlays/overlay.test.mocks.ts
+++ b/src/core/public/overlays/overlay.test.mocks.ts
@@ -19,7 +19,7 @@
export const mockReactDomRender = jest.fn();
export const mockReactDomUnmount = jest.fn();
-export const mockReactDomCreatePortal = jest.fn().mockImplementation(component => component);
+export const mockReactDomCreatePortal = jest.fn().mockImplementation((component) => component);
jest.doMock('react-dom', () => ({
render: mockReactDomRender,
createPortal: mockReactDomCreatePortal,
diff --git a/src/core/public/plugins/plugin.test.ts b/src/core/public/plugins/plugin.test.ts
index 8fe745db9554d..3f77161f8c34d 100644
--- a/src/core/public/plugins/plugin.test.ts
+++ b/src/core/public/plugins/plugin.test.ts
@@ -101,7 +101,7 @@ describe('PluginWrapper', () => {
setup: jest.fn(),
start: jest.fn(async () => {
// Add small delay to ensure startDependencies is not resolved until after the plugin instance's start resolves.
- await new Promise(resolve => setTimeout(resolve, 10));
+ await new Promise((resolve) => setTimeout(resolve, 10));
expect(startDependenciesResolved).toBe(false);
return pluginStartContract;
}),
@@ -113,7 +113,7 @@ describe('PluginWrapper', () => {
const deps = { otherDep: 'value' };
// Add promise callback prior to calling `start` to ensure calls in `setup` will not resolve before `start` is
// called.
- const startDependenciesCheck = plugin.startDependencies.then(res => {
+ const startDependenciesCheck = plugin.startDependencies.then((res) => {
startDependenciesResolved = true;
expect(res).toEqual([context, deps, pluginStartContract]);
});
diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts
index c4b3c929415ee..c688373630a07 100644
--- a/src/core/public/plugins/plugin_context.ts
+++ b/src/core/public/plugins/plugin_context.ts
@@ -95,8 +95,8 @@ export function createPluginSetupContext<
): CoreSetup {
return {
application: {
- register: app => deps.application.register(plugin.opaqueId, app),
- registerAppUpdater: statusUpdater$ => deps.application.registerAppUpdater(statusUpdater$),
+ register: (app) => deps.application.register(plugin.opaqueId, app),
+ registerAppUpdater: (statusUpdater$) => deps.application.registerAppUpdater(statusUpdater$),
registerMountContext: (contextName, provider) =>
deps.application.registerMountContext(plugin.opaqueId, contextName, provider),
},
@@ -138,6 +138,7 @@ export function createPluginStartContext<
currentAppId$: deps.application.currentAppId$,
capabilities: deps.application.capabilities,
navigateToApp: deps.application.navigateToApp,
+ navigateToUrl: deps.application.navigateToUrl,
getUrlForApp: deps.application.getUrlForApp,
registerMountContext: (contextName, provider) =>
deps.application.registerMountContext(plugin.opaqueId, contextName, provider),
diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts
index 6c5ab5fcedcfd..05127e73d0c7a 100644
--- a/src/core/public/plugins/plugins_service.test.ts
+++ b/src/core/public/plugins/plugins_service.test.ts
@@ -50,7 +50,7 @@ import { contextServiceMock } from '../context/context_service.mock';
export let mockPluginInitializers: Map;
mockPluginInitializerProvider.mockImplementation(
- pluginName => mockPluginInitializers.get(pluginName)!
+ (pluginName) => mockPluginInitializers.get(pluginName)!
);
let plugins: InjectedPluginMetadata[];
@@ -251,7 +251,7 @@ describe('PluginsService', () => {
});
describe('timeout', () => {
- const flushPromises = () => new Promise(resolve => setImmediate(resolve));
+ const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
beforeAll(() => {
jest.useFakeTimers();
});
@@ -263,7 +263,7 @@ describe('PluginsService', () => {
mockPluginInitializers.set(
'pluginA',
jest.fn(() => ({
- setup: jest.fn(() => new Promise(i => i)),
+ setup: jest.fn(() => new Promise((i) => i)),
start: jest.fn(() => ({ value: 1 })),
stop: jest.fn(),
}))
@@ -344,7 +344,7 @@ describe('PluginsService', () => {
'pluginA',
jest.fn(() => ({
setup: jest.fn(() => ({ value: 1 })),
- start: jest.fn(() => new Promise(i => i)),
+ start: jest.fn(() => new Promise((i) => i)),
stop: jest.fn(),
}))
);
diff --git a/src/core/public/plugins/plugins_service.ts b/src/core/public/plugins/plugins_service.ts
index 862aa5043ad4b..f9bc40ca52601 100644
--- a/src/core/public/plugins/plugins_service.ts
+++ b/src/core/public/plugins/plugins_service.ts
@@ -60,14 +60,14 @@ export class PluginsService implements CoreService(plugins.map(p => [p.id, Symbol(p.id)]));
+ const opaqueIds = new Map(plugins.map((p) => [p.id, Symbol(p.id)]));
// Setup dependency map and plugin wrappers
plugins.forEach(({ id, plugin, config = {} }) => {
// Setup map of dependencies
this.pluginDependencies.set(id, [
...plugin.requiredPlugins,
- ...plugin.optionalPlugins.filter(optPlugin => opaqueIds.has(optPlugin)),
+ ...plugin.optionalPlugins.filter((optPlugin) => opaqueIds.has(optPlugin)),
]);
// Construct plugin wrappers, depending on the topological order set by the server.
@@ -87,7 +87,7 @@ export class PluginsService implements CoreService [
this.plugins.get(id)!.opaqueId,
- deps.map(depId => this.plugins.get(depId)!.opaqueId),
+ deps.map((depId) => this.plugins.get(depId)!.opaqueId),
])
);
}
diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md
index fbd8f474151fa..4ccded9b9afec 100644
--- a/src/core/public/public.api.md
+++ b/src/core/public/public.api.md
@@ -116,6 +116,7 @@ export interface ApplicationStart {
path?: string;
state?: any;
}): Promise;
+ navigateToUrl(url: string): Promise;
// @deprecated
registerMountContext(contextName: T, provider: IContextProvider): void;
}
diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts
index 7958a4f8134d3..cdc113871c447 100644
--- a/src/core/public/saved_objects/saved_objects_client.ts
+++ b/src/core/public/saved_objects/saved_objects_client.ts
@@ -156,8 +156,8 @@ export class SavedObjectsClient {
this.bulkGet(queue)
.then(({ savedObjects }) => {
- queue.forEach(queueItem => {
- const foundObject = savedObjects.find(savedObject => {
+ queue.forEach((queueItem) => {
+ const foundObject = savedObjects.find((savedObject) => {
return savedObject.id === queueItem.id && savedObject.type === queueItem.type;
});
@@ -168,8 +168,8 @@ export class SavedObjectsClient {
queueItem.resolve(foundObject);
});
})
- .catch(err => {
- queue.forEach(queueItem => {
+ .catch((err) => {
+ queue.forEach((queueItem) => {
queueItem.reject(err);
});
});
@@ -216,7 +216,7 @@ export class SavedObjectsClient {
}),
});
- return createRequest.then(resp => this.createSavedObject(resp));
+ return createRequest.then((resp) => this.createSavedObject(resp));
};
/**
@@ -239,8 +239,8 @@ export class SavedObjectsClient {
query,
body: JSON.stringify(objects),
});
- return request.then(resp => {
- resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d));
+ return request.then((resp) => {
+ resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d));
return renameKeys<
PromiseType>,
SavedObjectsBatchResponse
@@ -301,8 +301,8 @@ export class SavedObjectsClient {
method: 'GET',
query,
});
- return request.then(resp => {
- resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d));
+ return request.then((resp) => {
+ resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d));
return renameKeys<
PromiseType>,
SavedObjectsFindResponsePublic
@@ -350,14 +350,14 @@ export class SavedObjectsClient {
*/
public bulkGet = (objects: Array<{ id: string; type: string }> = []) => {
const path = this.getPath(['_bulk_get']);
- const filteredObjects = objects.map(obj => pick(obj, ['id', 'type']));
+ const filteredObjects = objects.map((obj) => pick(obj, ['id', 'type']));
const request: ReturnType = this.savedObjectsFetch(path, {
method: 'POST',
body: JSON.stringify(filteredObjects),
});
- return request.then(resp => {
- resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d));
+ return request.then((resp) => {
+ resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d));
return renameKeys<
PromiseType>,
SavedObjectsBatchResponse
@@ -414,7 +414,7 @@ export class SavedObjectsClient {
return this.savedObjectsFetch(path, {
method: 'PUT',
body: JSON.stringify(objects),
- }).then(resp => {
+ }).then((resp) => {
resp.saved_objects = resp.saved_objects.map((d: SavedObject) => this.createSavedObject(d));
return renameKeys<
PromiseType>,
diff --git a/src/core/public/ui_settings/ui_settings_api.test.ts b/src/core/public/ui_settings/ui_settings_api.test.ts
index 9a462e0541347..bab7081509d53 100644
--- a/src/core/public/ui_settings/ui_settings_api.test.ts
+++ b/src/core/public/ui_settings/ui_settings_api.test.ts
@@ -26,7 +26,7 @@ import { setup as httpSetup } from '../../../test_utils/public/http_test_setup';
import { UiSettingsApi } from './ui_settings_api';
function setup() {
- const { http } = httpSetup(injectedMetadata => {
+ const { http } = httpSetup((injectedMetadata) => {
injectedMetadata.getBasePath.mockReturnValue('/foo/bar');
});
@@ -181,10 +181,7 @@ describe('#getLoadingCount$()', () => {
const { uiSettingsApi } = setup();
const done$ = new Rx.Subject();
- const promise = uiSettingsApi
- .getLoadingCount$()
- .pipe(takeUntil(done$), toArray())
- .toPromise();
+ const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise();
await uiSettingsApi.batchSet('foo', 'bar');
done$.next();
@@ -209,10 +206,7 @@ describe('#getLoadingCount$()', () => {
const { uiSettingsApi } = setup();
const done$ = new Rx.Subject();
- const promise = uiSettingsApi
- .getLoadingCount$()
- .pipe(takeUntil(done$), toArray())
- .toPromise();
+ const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise();
await uiSettingsApi.batchSet('foo', 'bar');
await expect(uiSettingsApi.batchSet('foo', 'bar')).rejects.toThrowError();
@@ -230,14 +224,8 @@ describe('#stop', () => {
const { uiSettingsApi } = setup();
const promise = Promise.all([
- uiSettingsApi
- .getLoadingCount$()
- .pipe(toArray())
- .toPromise(),
- uiSettingsApi
- .getLoadingCount$()
- .pipe(toArray())
- .toPromise(),
+ uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(),
+ uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(),
]);
const batchSetPromise = uiSettingsApi.batchSet('foo', 'bar');
diff --git a/src/core/public/ui_settings/ui_settings_client.test.ts b/src/core/public/ui_settings/ui_settings_client.test.ts
index f394036e3e046..3b67efb740e7d 100644
--- a/src/core/public/ui_settings/ui_settings_client.test.ts
+++ b/src/core/public/ui_settings/ui_settings_client.test.ts
@@ -88,20 +88,14 @@ describe('#get', () => {
describe('#get$', () => {
it('emits the current value when called', async () => {
const { client } = setup();
- const values = await client
- .get$('dateFormat')
- .pipe(take(1), toArray())
- .toPromise();
+ const values = await client.get$('dateFormat').pipe(take(1), toArray()).toPromise();
expect(values).toEqual(['Browser']);
});
it('emits an error notification if the key is unknown', async () => {
const { client } = setup();
- const values = await client
- .get$('unknown key')
- .pipe(materialize())
- .toPromise();
+ const values = await client.get$('unknown key').pipe(materialize()).toPromise();
expect(values).toMatchInlineSnapshot(`
Notification {
@@ -124,10 +118,7 @@ You can use \`IUiSettingsClient.get("unknown key", defaultValue)\`, which will j
client.set('dateFormat', 'new format');
}, 10);
- const values = await client
- .get$('dateFormat')
- .pipe(take(2), toArray())
- .toPromise();
+ const values = await client.get$('dateFormat').pipe(take(2), toArray()).toPromise();
expect(values).toEqual(['Browser', 'new format']);
});
diff --git a/src/core/public/ui_settings/ui_settings_client.ts b/src/core/public/ui_settings/ui_settings_client.ts
index f5596b1bc34fc..2a7c3c2fab2f3 100644
--- a/src/core/public/ui_settings/ui_settings_client.ts
+++ b/src/core/public/ui_settings/ui_settings_client.ts
@@ -97,7 +97,7 @@ You can use \`IUiSettingsClient.get("${key}", defaultValue)\`, which will just r
return concat(
defer(() => of(this.get(key, defaultOverride))),
this.update$.pipe(
- filter(update => update.key === key),
+ filter((update) => update.key === key),
map(() => this.get(key, defaultOverride))
)
);
diff --git a/src/core/public/ui_settings/ui_settings_service.test.ts b/src/core/public/ui_settings/ui_settings_service.test.ts
index 2747a78d93fa6..4c688d5b7b2c1 100644
--- a/src/core/public/ui_settings/ui_settings_service.test.ts
+++ b/src/core/public/ui_settings/ui_settings_service.test.ts
@@ -38,7 +38,7 @@ describe('#stop', () => {
it('stops the uiSettingsClient and uiSettingsApi', async () => {
const service = new UiSettingsService();
let loadingCount$: Rx.Observable;
- defaultDeps.http.addLoadingCountSource.mockImplementation(obs$ => (loadingCount$ = obs$));
+ defaultDeps.http.addLoadingCountSource.mockImplementation((obs$) => (loadingCount$ = obs$));
const client = service.setup(defaultDeps);
service.stop();
diff --git a/src/core/public/utils/share_weak_replay.test.ts b/src/core/public/utils/share_weak_replay.test.ts
index 6eaa140e5afad..beac851aa689c 100644
--- a/src/core/public/utils/share_weak_replay.test.ts
+++ b/src/core/public/utils/share_weak_replay.test.ts
@@ -38,7 +38,7 @@ function counter({ async = true }: { async?: boolean } = {}) {
completedCounts += 1;
}
- return new Rx.Observable(subscriber => {
+ return new Rx.Observable((subscriber) => {
if (!async) {
sendCount(subscriber);
return;
@@ -53,7 +53,7 @@ async function record(observable: Rx.Observable) {
return observable
.pipe(
materialize(),
- map(n => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')),
+ map((n) => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')),
toArray()
)
.toPromise();
diff --git a/src/core/public/utils/share_weak_replay.ts b/src/core/public/utils/share_weak_replay.ts
index 74ea6cc536888..5ed6f76c5a05a 100644
--- a/src/core/public/utils/share_weak_replay.ts
+++ b/src/core/public/utils/share_weak_replay.ts
@@ -39,7 +39,7 @@ export function shareWeakReplay(bufferSize?: number): Rx.MonoTypeOperatorFunc
let subject: Rx.ReplaySubject | undefined;
const stop$ = new Rx.Subject();
- return new Rx.Observable(observer => {
+ return new Rx.Observable((observer) => {
if (!subject) {
subject = new Rx.ReplaySubject(bufferSize);
}
diff --git a/src/core/server/bootstrap.ts b/src/core/server/bootstrap.ts
index dff0c00a4625e..5dbe5a0b4f955 100644
--- a/src/core/server/bootstrap.ts
+++ b/src/core/server/bootstrap.ts
@@ -71,7 +71,7 @@ export async function bootstrap({
// This is only used by the LogRotator service
// in order to be able to reload the log configuration
// under the cluster mode
- process.on('message', msg => {
+ process.on('message', (msg) => {
if (!msg || msg.reloadLoggingConfig !== true) {
return;
}
diff --git a/src/core/server/capabilities/capabilities_service.ts b/src/core/server/capabilities/capabilities_service.ts
index d3d6b507da523..f0be9743d4d60 100644
--- a/src/core/server/capabilities/capabilities_service.ts
+++ b/src/core/server/capabilities/capabilities_service.ts
@@ -127,7 +127,7 @@ export class CapabilitiesService {
() =>
mergeCapabilities(
defaultCapabilities,
- ...this.capabilitiesProviders.map(provider => provider())
+ ...this.capabilitiesProviders.map((provider) => provider())
),
() => this.capabilitiesSwitchers
);
@@ -150,7 +150,7 @@ export class CapabilitiesService {
public start(): CapabilitiesStart {
return {
- resolveCapabilities: request => this.resolveCapabilities(request, []),
+ resolveCapabilities: (request) => this.resolveCapabilities(request, []),
};
}
}
diff --git a/src/core/server/capabilities/resolve_capabilities.ts b/src/core/server/capabilities/resolve_capabilities.ts
index dcb93bdca5f16..1be504d4bc314 100644
--- a/src/core/server/capabilities/resolve_capabilities.ts
+++ b/src/core/server/capabilities/resolve_capabilities.ts
@@ -64,7 +64,7 @@ function recursiveApplyChanges<
TSource extends Record
>(destination: TDestination, source: TSource): TDestination {
return Object.keys(destination)
- .map(key => {
+ .map((key) => {
const orig = destination[key];
const changed = source[key];
if (changed == null) {
diff --git a/src/core/server/config/config.ts b/src/core/server/config/config.ts
index b1a6a8cc525bf..a4026b1d88ac3 100644
--- a/src/core/server/config/config.ts
+++ b/src/core/server/config/config.ts
@@ -34,7 +34,7 @@ export function isConfigPath(value: unknown): value is ConfigPath {
return true;
}
- return Array.isArray(value) && value.every(segment => typeof segment === 'string');
+ return Array.isArray(value) && value.every((segment) => typeof segment === 'string');
}
/**
diff --git a/src/core/server/config/config_service.test.ts b/src/core/server/config/config_service.test.ts
index 773a444dea948..5f28fca1371b0 100644
--- a/src/core/server/config/config_service.test.ts
+++ b/src/core/server/config/config_service.test.ts
@@ -62,10 +62,10 @@ test('throws if config at path does not match schema', async () => {
.atPath('key')
.pipe(take(1))
.subscribe(
- value => {
+ (value) => {
valuesReceived.push(value);
},
- error => {
+ (error) => {
valuesReceived.push(error);
}
);
@@ -86,10 +86,10 @@ test('re-validate config when updated', async () => {
const valuesReceived: any[] = [];
await configService.atPath('key').subscribe(
- value => {
+ (value) => {
valuesReceived.push(value);
},
- error => {
+ (error) => {
valuesReceived.push(error);
}
);
@@ -133,7 +133,7 @@ test("does not push new configs when reloading if config at path hasn't changed"
await configService.setSchema('key', schema.string());
const valuesReceived: any[] = [];
- configService.atPath('key').subscribe(value => {
+ configService.atPath('key').subscribe((value) => {
valuesReceived.push(value);
});
@@ -150,7 +150,7 @@ test('pushes new config when reloading and config at path has changed', async ()
await configService.setSchema('key', schema.string());
const valuesReceived: any[] = [];
- configService.atPath('key').subscribe(value => {
+ configService.atPath('key').subscribe((value) => {
valuesReceived.push(value);
});
diff --git a/src/core/server/config/config_service.ts b/src/core/server/config/config_service.ts
index 61630f43bffb5..bceba420bb6ce 100644
--- a/src/core/server/config/config_service.ts
+++ b/src/core/server/config/config_service.ts
@@ -89,7 +89,7 @@ export class ConfigService {
const flatPath = pathToString(path);
this.deprecations.next([
...this.deprecations.value,
- ...provider(configDeprecationFactory).map(deprecation => ({
+ ...provider(configDeprecationFactory).map((deprecation) => ({
deprecation,
path: flatPath,
})),
@@ -104,9 +104,7 @@ export class ConfigService {
public async validate() {
const namespaces = [...this.schemas.keys()];
for (let i = 0; i < namespaces.length; i++) {
- await this.validateConfigAtPath(namespaces[i])
- .pipe(first())
- .toPromise();
+ await this.validateConfigAtPath(namespaces[i]).pipe(first()).toPromise();
}
await this.logDeprecation();
@@ -138,7 +136,7 @@ export class ConfigService {
*/
public optionalAtPath(path: ConfigPath) {
return this.getDistinctConfig(path).pipe(
- map(config => {
+ map((config) => {
if (config === undefined) return undefined;
return this.validateAtPath(path, config) as TSchema;
})
@@ -149,9 +147,7 @@ export class ConfigService {
const namespace = pathToString(path);
const validatedConfig = this.schemas.has(namespace)
- ? await this.atPath<{ enabled?: boolean }>(path)
- .pipe(first())
- .toPromise()
+ ? await this.atPath<{ enabled?: boolean }>(path).pipe(first()).toPromise()
: undefined;
const enabledPath = createPluginEnabledPath(path);
@@ -186,26 +182,23 @@ export class ConfigService {
const config = await this.config$.pipe(first()).toPromise();
const handledPaths = this.handledPaths.map(pathToString);
- return config.getFlattenedPaths().filter(path => !isPathHandled(path, handledPaths));
+ return config.getFlattenedPaths().filter((path) => !isPathHandled(path, handledPaths));
}
public async getUsedPaths() {
const config = await this.config$.pipe(first()).toPromise();
const handledPaths = this.handledPaths.map(pathToString);
- return config.getFlattenedPaths().filter(path => isPathHandled(path, handledPaths));
+ return config.getFlattenedPaths().filter((path) => isPathHandled(path, handledPaths));
}
private async logDeprecation() {
- const rawConfig = await this.rawConfigProvider
- .getConfig$()
- .pipe(take(1))
- .toPromise();
+ const rawConfig = await this.rawConfigProvider.getConfig$().pipe(take(1)).toPromise();
const deprecations = await this.deprecations.pipe(take(1)).toPromise();
const deprecationMessages: string[] = [];
const logger = (msg: string) => deprecationMessages.push(msg);
applyDeprecations(rawConfig, deprecations, logger);
- deprecationMessages.forEach(msg => {
+ deprecationMessages.forEach((msg) => {
this.deprecationLog.warn(msg);
});
}
@@ -228,14 +221,14 @@ export class ConfigService {
}
private validateConfigAtPath(path: ConfigPath) {
- return this.getDistinctConfig(path).pipe(map(config => this.validateAtPath(path, config)));
+ return this.getDistinctConfig(path).pipe(map((config) => this.validateAtPath(path, config)));
}
private getDistinctConfig(path: ConfigPath) {
this.markAsHandled(path);
return this.config$.pipe(
- map(config => config.get(path)),
+ map((config) => config.get(path)),
distinctUntilChanged(isEqual)
);
}
@@ -260,4 +253,4 @@ const pathToString = (path: ConfigPath) => (Array.isArray(path) ? path.join('.')
* handled paths.
*/
const isPathHandled = (path: string, handledPaths: string[]) =>
- handledPaths.some(handledPath => hasConfigPathIntersection(path, handledPath));
+ handledPaths.some((handledPath) => hasConfigPathIntersection(path, handledPath));
diff --git a/src/core/server/config/deprecation/apply_deprecations.test.ts b/src/core/server/config/deprecation/apply_deprecations.test.ts
index 25cae80d8b5cb..d7cc85add4e76 100644
--- a/src/core/server/config/deprecation/apply_deprecations.test.ts
+++ b/src/core/server/config/deprecation/apply_deprecations.test.ts
@@ -36,7 +36,7 @@ describe('applyDeprecations', () => {
const handlerC = jest.fn();
applyDeprecations(
{},
- [handlerA, handlerB, handlerC].map(h => wrapHandler(h))
+ [handlerA, handlerB, handlerC].map((h) => wrapHandler(h))
);
expect(handlerA).toHaveBeenCalledTimes(1);
expect(handlerB).toHaveBeenCalledTimes(1);
@@ -49,7 +49,7 @@ describe('applyDeprecations', () => {
const alteredConfig = { foo: 'bar' };
const handlerA = jest.fn().mockReturnValue(alteredConfig);
- const handlerB = jest.fn().mockImplementation(conf => conf);
+ const handlerB = jest.fn().mockImplementation((conf) => conf);
applyDeprecations(
initialConfig,
diff --git a/src/core/server/config/deprecation/core_deprecations.test.ts b/src/core/server/config/deprecation/core_deprecations.test.ts
index a91e128f62d2d..ebdb6f1c88b16 100644
--- a/src/core/server/config/deprecation/core_deprecations.test.ts
+++ b/src/core/server/config/deprecation/core_deprecations.test.ts
@@ -28,11 +28,11 @@ const applyCoreDeprecations = (settings: Record = {}) => {
const deprecationMessages: string[] = [];
const migrated = applyDeprecations(
settings,
- deprecations.map(deprecation => ({
+ deprecations.map((deprecation) => ({
deprecation,
path: '',
})),
- msg => deprecationMessages.push(msg)
+ (msg) => deprecationMessages.push(msg)
);
return {
messages: deprecationMessages,
diff --git a/src/core/server/config/deprecation/core_deprecations.ts b/src/core/server/config/deprecation/core_deprecations.ts
index 9e098c06ba155..483534e0c145b 100644
--- a/src/core/server/config/deprecation/core_deprecations.ts
+++ b/src/core/server/config/deprecation/core_deprecations.ts
@@ -72,26 +72,26 @@ const cspRulesDeprecation: ConfigDeprecation = (settings, fromPath, log) => {
const rules: string[] = get(settings, 'csp.rules');
if (rules) {
const parsed = new Map(
- rules.map(ruleStr => {
+ rules.map((ruleStr) => {
const parts = ruleStr.split(/\s+/);
return [parts[0], parts.slice(1)];
})
);
settings.csp.rules = [...parsed].map(([policy, sourceList]) => {
- if (sourceList.find(source => source.includes(NONCE_STRING))) {
+ if (sourceList.find((source) => source.includes(NONCE_STRING))) {
log(`csp.rules no longer supports the {nonce} syntax. Replacing with 'self' in ${policy}`);
- sourceList = sourceList.filter(source => !source.includes(NONCE_STRING));
+ sourceList = sourceList.filter((source) => !source.includes(NONCE_STRING));
// Add 'self' if not present
- if (!sourceList.find(source => source.includes(SELF_STRING))) {
+ if (!sourceList.find((source) => source.includes(SELF_STRING))) {
sourceList.push(SELF_STRING);
}
}
if (
SELF_POLICIES.includes(policy) &&
- !sourceList.find(source => source.includes(SELF_STRING))
+ !sourceList.find((source) => source.includes(SELF_STRING))
) {
log(`csp.rules must contain the 'self' source. Automatically adding to ${policy}.`);
sourceList.push(SELF_STRING);
diff --git a/src/core/server/config/deprecation/deprecation_factory.test.ts b/src/core/server/config/deprecation/deprecation_factory.test.ts
index 2595fdd923dd5..3910ee3235caf 100644
--- a/src/core/server/config/deprecation/deprecation_factory.test.ts
+++ b/src/core/server/config/deprecation/deprecation_factory.test.ts
@@ -24,7 +24,7 @@ describe('DeprecationFactory', () => {
const { rename, unused, renameFromRoot, unusedFromRoot } = configDeprecationFactory;
let deprecationMessages: string[];
- const logger: ConfigDeprecationLogger = msg => deprecationMessages.push(msg);
+ const logger: ConfigDeprecationLogger = (msg) => deprecationMessages.push(msg);
beforeEach(() => {
deprecationMessages = [];
diff --git a/src/core/server/config/ensure_deep_object.ts b/src/core/server/config/ensure_deep_object.ts
index 58865d13c1afa..6eaaef983355c 100644
--- a/src/core/server/config/ensure_deep_object.ts
+++ b/src/core/server/config/ensure_deep_object.ts
@@ -31,7 +31,7 @@ export function ensureDeepObject(obj: any): any {
}
if (Array.isArray(obj)) {
- return obj.map(item => ensureDeepObject(item));
+ return obj.map((item) => ensureDeepObject(item));
}
return Object.keys(obj).reduce((fullObject, propertyKey) => {
diff --git a/src/core/server/config/integration_tests/config_deprecation.test.ts b/src/core/server/config/integration_tests/config_deprecation.test.ts
index 5bc3887f05f93..3523b074ea5b4 100644
--- a/src/core/server/config/integration_tests/config_deprecation.test.ts
+++ b/src/core/server/config/integration_tests/config_deprecation.test.ts
@@ -36,7 +36,7 @@ describe('configuration deprecations', () => {
await root.setup();
const logs = loggingServiceMock.collect(mockLoggingService);
- const warnings = logs.warn.flatMap(i => i);
+ const warnings = logs.warn.flatMap((i) => i);
expect(warnings).not.toContain(
'"optimize.lazy" is deprecated and has been replaced by "optimize.watch"'
);
@@ -56,7 +56,7 @@ describe('configuration deprecations', () => {
await root.setup();
const logs = loggingServiceMock.collect(mockLoggingService);
- const warnings = logs.warn.flatMap(i => i);
+ const warnings = logs.warn.flatMap((i) => i);
expect(warnings).toContain(
'"optimize.lazy" is deprecated and has been replaced by "optimize.watch"'
);
diff --git a/src/core/server/config/raw_config_service.test.ts b/src/core/server/config/raw_config_service.test.ts
index f02c31d4659ca..8846ea3847f79 100644
--- a/src/core/server/config/raw_config_service.test.ts
+++ b/src/core/server/config/raw_config_service.test.ts
@@ -83,10 +83,7 @@ test('returns config at path as observable', async () => {
configService.loadConfig();
- const exampleConfig = await configService
- .getConfig$()
- .pipe(first())
- .toPromise();
+ const exampleConfig = await configService.getConfig$().pipe(first()).toPromise();
expect(exampleConfig.key).toEqual('value');
expect(Object.keys(exampleConfig)).toEqual(['key']);
@@ -100,7 +97,7 @@ test("pushes new configs when reloading even if config at path hasn't changed",
configService.loadConfig();
const valuesReceived: any[] = [];
- configService.getConfig$().subscribe(config => {
+ configService.getConfig$().subscribe((config) => {
valuesReceived.push(config);
});
@@ -129,7 +126,7 @@ test('pushes new config when reloading and config at path has changed', async ()
configService.loadConfig();
const valuesReceived: any[] = [];
- configService.getConfig$().subscribe(config => {
+ configService.getConfig$().subscribe((config) => {
valuesReceived.push(config);
});
@@ -145,7 +142,7 @@ test('pushes new config when reloading and config at path has changed', async ()
expect(Object.keys(valuesReceived[1])).toEqual(['key']);
});
-test('completes config observables when stopped', done => {
+test('completes config observables when stopped', (done) => {
expect.assertions(0);
mockGetConfigFromFiles.mockImplementation(() => ({ key: 'value' }));
diff --git a/src/core/server/config/raw_config_service.ts b/src/core/server/config/raw_config_service.ts
index 728d793f494a9..257ec612f3249 100644
--- a/src/core/server/config/raw_config_service.ts
+++ b/src/core/server/config/raw_config_service.ts
@@ -41,10 +41,10 @@ export class RawConfigService {
constructor(
public readonly configFiles: readonly string[],
- configAdapter: RawConfigAdapter = rawConfig => rawConfig
+ configAdapter: RawConfigAdapter = (rawConfig) => rawConfig
) {
this.config$ = this.rawConfigFromFile$.pipe(
- map(rawConfig => {
+ map((rawConfig) => {
if (isPlainObject(rawConfig)) {
// TODO Make config consistent, e.g. handle dots in keys
return configAdapter(cloneDeep(rawConfig));
diff --git a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts
index 2c7efe075152b..3284be5ba4750 100644
--- a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts
+++ b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts
@@ -44,7 +44,7 @@ describe('default route provider', () => {
await root.shutdown();
});
- it('redirects to the configured default route respecting basePath', async function() {
+ it('redirects to the configured default route respecting basePath', async function () {
const { status, header } = await kbnTestServer.request.get(root, '/');
expect(status).toEqual(302);
@@ -53,7 +53,7 @@ describe('default route provider', () => {
});
});
- it('ignores invalid values', async function() {
+ it('ignores invalid values', async function () {
const invalidRoutes = [
'http://not-your-kibana.com',
'///example.com',
@@ -75,7 +75,7 @@ describe('default route provider', () => {
});
});
- it('consumes valid values', async function() {
+ it('consumes valid values', async function () {
await kbnTestServer.request
.post(root, '/api/kibana/settings/defaultRoute')
.send({ value: '/valid' })
diff --git a/src/core/server/core_app/integration_tests/static_assets.test.ts b/src/core/server/core_app/integration_tests/static_assets.test.ts
index aad2510ef8c0e..23125cb3a6704 100644
--- a/src/core/server/core_app/integration_tests/static_assets.test.ts
+++ b/src/core/server/core_app/integration_tests/static_assets.test.ts
@@ -19,17 +19,17 @@
import * as kbnTestServer from '../../../../test_utils/kbn_server';
import { Root } from '../../root';
-describe('Platform assets', function() {
+describe('Platform assets', function () {
let root: Root;
- beforeAll(async function() {
+ beforeAll(async function () {
root = kbnTestServer.createRoot();
await root.setup();
await root.start();
});
- afterAll(async function() {
+ afterAll(async function () {
await root.shutdown();
});
@@ -37,15 +37,15 @@ describe('Platform assets', function() {
await kbnTestServer.request.get(root, '/ui/favicons/favicon.ico').expect(200);
});
- it('returns 404 if not found', async function() {
+ it('returns 404 if not found', async function () {
await kbnTestServer.request.get(root, '/ui/favicons/not-a-favicon.ico').expect(404);
});
- it('does not expose folder content', async function() {
+ it('does not expose folder content', async function () {
await kbnTestServer.request.get(root, '/ui/favicons/').expect(403);
});
- it('does not allow file tree traversing', async function() {
+ it('does not allow file tree traversing', async function () {
await kbnTestServer.request.get(root, '/ui/../../../../../README.md').expect(404);
});
});
diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.ts b/src/core/server/elasticsearch/elasticsearch_config.test.ts
index cb4501a51e849..ccd5fd0c7a571 100644
--- a/src/core/server/elasticsearch/elasticsearch_config.test.ts
+++ b/src/core/server/elasticsearch/elasticsearch_config.test.ts
@@ -35,11 +35,11 @@ const applyElasticsearchDeprecations = (settings: Record = {}) => {
_config[CONFIG_PATH] = settings;
const migrated = applyDeprecations(
_config,
- deprecations.map(deprecation => ({
+ deprecations.map((deprecation) => ({
deprecation,
path: CONFIG_PATH,
})),
- msg => deprecationMessages.push(msg)
+ (msg) => deprecationMessages.push(msg)
);
return {
messages: deprecationMessages,
diff --git a/src/core/server/elasticsearch/elasticsearch_config.ts b/src/core/server/elasticsearch/elasticsearch_config.ts
index c87c94bcd0b6a..cac8c75a04486 100644
--- a/src/core/server/elasticsearch/elasticsearch_config.ts
+++ b/src/core/server/elasticsearch/elasticsearch_config.ts
@@ -51,7 +51,7 @@ export const configSchema = schema.object({
schema.contextRef('dist'),
false,
schema.string({
- validate: rawConfig => {
+ validate: (rawConfig) => {
if (rawConfig === 'elastic') {
return (
'value of "elastic" is forbidden. This is a superuser account that can obfuscate ' +
@@ -96,7 +96,7 @@ export const configSchema = schema.object({
alwaysPresentCertificate: schema.boolean({ defaultValue: false }),
},
{
- validate: rawConfig => {
+ validate: (rawConfig) => {
if (rawConfig.key && rawConfig.keystore.path) {
return 'cannot use [key] when [keystore.path] is specified';
}
@@ -112,7 +112,7 @@ export const configSchema = schema.object({
schema.contextRef('dev'),
false,
schema.boolean({
- validate: rawValue => {
+ validate: (rawValue) => {
if (rawValue === true) {
return '"ignoreVersionMismatch" can only be set to true in development mode';
}
diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts
index 2667859f303d4..26144eaaa4afa 100644
--- a/src/core/server/elasticsearch/elasticsearch_service.test.ts
+++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts
@@ -34,7 +34,7 @@ import { elasticsearchServiceMock } from './elasticsearch_service.mock';
import { duration } from 'moment';
const delay = async (durationMs: number) =>
- await new Promise(resolve => setTimeout(resolve, durationMs));
+ await new Promise((resolve) => setTimeout(resolve, durationMs));
let elasticsearchService: ElasticsearchService;
const configService = configServiceMock.create();
@@ -217,7 +217,7 @@ describe('#setup', () => {
});
});
- it('esNodeVersionCompatibility$ only starts polling when subscribed to', async done => {
+ it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => {
const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient();
const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient();
MockClusterClient.mockImplementationOnce(
@@ -236,7 +236,7 @@ describe('#setup', () => {
});
});
- it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async done => {
+ it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => {
const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient();
const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient();
MockClusterClient.mockImplementationOnce(
@@ -272,7 +272,7 @@ describe('#stop', () => {
expect(mockDataClusterClientInstance.close).toHaveBeenCalledTimes(1);
});
- it('stops pollEsNodeVersions even if there are active subscriptions', async done => {
+ it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => {
expect.assertions(2);
const mockAdminClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient();
const mockDataClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient();
diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts
index 18725f04a05b5..ab9c9e11fedc8 100644
--- a/src/core/server/elasticsearch/elasticsearch_service.ts
+++ b/src/core/server/elasticsearch/elasticsearch_service.ts
@@ -77,7 +77,7 @@ export class ElasticsearchService
this.log = coreContext.logger.get('elasticsearch-service');
this.config$ = coreContext.configService
.atPath('elasticsearch')
- .pipe(map(rawConfig => new ElasticsearchConfig(rawConfig)));
+ .pipe(map((rawConfig) => new ElasticsearchConfig(rawConfig)));
}
public async setup(deps: SetupDeps): Promise {
@@ -93,8 +93,8 @@ export class ElasticsearchService
return true;
}),
switchMap(
- config =>
- new Observable(subscriber => {
+ (config) =>
+ new Observable((subscriber) => {
this.log.debug(`Creating elasticsearch clients`);
const coreClients = {
@@ -120,8 +120,8 @@ export class ElasticsearchService
const config = await this.config$.pipe(first()).toPromise();
- const adminClient$ = clients$.pipe(map(clients => clients.adminClient));
- const dataClient$ = clients$.pipe(map(clients => clients.dataClient));
+ const adminClient$ = clients$.pipe(map((clients) => clients.adminClient));
+ const dataClient$ = clients$.pipe(map((clients) => clients.dataClient));
this.adminClient = {
async callAsInternalUser(
@@ -189,7 +189,7 @@ export class ElasticsearchService
};
return {
- legacy: { config$: clients$.pipe(map(clients => clients.config)) },
+ legacy: { config$: clients$.pipe(map((clients) => clients.config)) },
esNodesCompatibility$,
adminClient: this.adminClient,
dataClient,
diff --git a/src/core/server/elasticsearch/retry_call_cluster.test.ts b/src/core/server/elasticsearch/retry_call_cluster.test.ts
index 4f391f0aba34b..8be138e6752d2 100644
--- a/src/core/server/elasticsearch/retry_call_cluster.test.ts
+++ b/src/core/server/elasticsearch/retry_call_cluster.test.ts
@@ -75,7 +75,7 @@ describe('migrationsRetryCallCluster', () => {
loggingServiceMock.clear(mockLogger);
});
- errors.forEach(errorName => {
+ errors.forEach((errorName) => {
it('retries ES API calls that rejects with ' + errorName, () => {
expect.assertions(1);
const callEsApi = jest.fn();
diff --git a/src/core/server/elasticsearch/retry_call_cluster.ts b/src/core/server/elasticsearch/retry_call_cluster.ts
index 901b801159cb6..aa3e39d948593 100644
--- a/src/core/server/elasticsearch/retry_call_cluster.ts
+++ b/src/core/server/elasticsearch/retry_call_cluster.ts
@@ -47,7 +47,7 @@ export function migrationsRetryCallCluster(
return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => {
return defer(() => apiCaller(endpoint, clientParams, options))
.pipe(
- retryWhen(error$ =>
+ retryWhen((error$) =>
error$.pipe(
concatMap((error, i) => {
if (!previousErrors.includes(error.message)) {
@@ -90,7 +90,7 @@ export function retryCallCluster(apiCaller: APICaller) {
return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => {
return defer(() => apiCaller(endpoint, clientParams, options))
.pipe(
- retryWhen(errors =>
+ retryWhen((errors) =>
errors.pipe(
concatMap((error, i) =>
iif(
diff --git a/src/core/server/elasticsearch/scoped_cluster_client.ts b/src/core/server/elasticsearch/scoped_cluster_client.ts
index 920d236935261..4b64bfba15190 100644
--- a/src/core/server/elasticsearch/scoped_cluster_client.ts
+++ b/src/core/server/elasticsearch/scoped_cluster_client.ts
@@ -89,7 +89,7 @@ export class ScopedClusterClient implements IScopedClusterClient {
const customHeaders: any = clientParams.headers;
if (isObject(customHeaders)) {
const duplicates = intersection(Object.keys(defaultHeaders), Object.keys(customHeaders));
- duplicates.forEach(duplicate => {
+ duplicates.forEach((duplicate) => {
if (defaultHeaders[duplicate] !== (customHeaders as any)[duplicate]) {
throw Error(`Cannot override default header ${duplicate}.`);
}
diff --git a/src/core/server/elasticsearch/status.test.ts b/src/core/server/elasticsearch/status.test.ts
index dd5fb04bfd1c6..ef7ca7cd04608 100644
--- a/src/core/server/elasticsearch/status.test.ts
+++ b/src/core/server/elasticsearch/status.test.ts
@@ -38,11 +38,7 @@ const nodeInfo = {
describe('calculateStatus', () => {
it('starts in unavailable', async () => {
- expect(
- await calculateStatus$(new Subject())
- .pipe(take(1))
- .toPromise()
- ).toEqual({
+ expect(await calculateStatus$(new Subject()).pipe(take(1)).toPromise()).toEqual({
level: ServiceStatusLevels.unavailable,
summary: 'Waiting for Elasticsearch',
meta: {
@@ -123,7 +119,7 @@ describe('calculateStatus', () => {
const nodeCompat$ = new Subject();
const statusUpdates: ServiceStatus[] = [];
- const subscription = calculateStatus$(nodeCompat$).subscribe(status =>
+ const subscription = calculateStatus$(nodeCompat$).subscribe((status) =>
statusUpdates.push(status)
);
diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
index 4989c4a31295c..a4cf0ffd58088 100644
--- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
+++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
@@ -30,7 +30,7 @@ const KIBANA_VERSION = '5.1.0';
function createNodes(...versions: string[]): NodesInfo {
const nodes = {} as any;
versions
- .map(version => {
+ .map((version) => {
return {
version,
http: {
@@ -121,7 +121,7 @@ describe('pollEsNodesVersion', () => {
callWithInternalUser.mockClear();
});
- it('returns iscCompatible=false and keeps polling when a poll request throws', done => {
+ it('returns iscCompatible=false and keeps polling when a poll request throws', (done) => {
expect.assertions(3);
const expectedCompatibilityResults = [false, false, true];
jest.clearAllMocks();
@@ -137,7 +137,7 @@ describe('pollEsNodesVersion', () => {
})
.pipe(take(3))
.subscribe({
- next: result => {
+ next: (result) => {
expect(result.isCompatible).toBe(expectedCompatibilityResults.shift());
},
complete: done,
@@ -145,7 +145,7 @@ describe('pollEsNodesVersion', () => {
});
});
- it('returns compatibility results', done => {
+ it('returns compatibility results', (done) => {
expect.assertions(1);
const nodes = createNodes('5.1.0', '5.2.0', '5.0.0');
callWithInternalUser.mockResolvedValueOnce(nodes);
@@ -158,7 +158,7 @@ describe('pollEsNodesVersion', () => {
})
.pipe(take(1))
.subscribe({
- next: result => {
+ next: (result) => {
expect(result).toEqual(mapNodesVersionCompatibility(nodes, KIBANA_VERSION, false));
},
complete: done,
@@ -166,7 +166,7 @@ describe('pollEsNodesVersion', () => {
});
});
- it('only emits if the node versions changed since the previous poll', done => {
+ it('only emits if the node versions changed since the previous poll', (done) => {
expect.assertions(4);
callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit
callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering
@@ -184,7 +184,7 @@ describe('pollEsNodesVersion', () => {
})
.pipe(take(4))
.subscribe({
- next: result => expect(result).toBeDefined(),
+ next: (result) => expect(result).toBeDefined(),
complete: done,
error: done,
});
diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts
index 7bd6331978d1d..776298e5869a0 100644
--- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts
+++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts
@@ -83,32 +83,32 @@ export function mapNodesVersionCompatibility(
}
const nodes = Object.keys(nodesInfo.nodes)
.sort() // Sorting ensures a stable node ordering for comparison
- .map(key => nodesInfo.nodes[key])
- .map(node => Object.assign({}, node, { name: getHumanizedNodeName(node) }));
+ .map((key) => nodesInfo.nodes[key])
+ .map((node) => Object.assign({}, node, { name: getHumanizedNodeName(node) }));
// Aggregate incompatible ES nodes.
const incompatibleNodes = nodes.filter(
- node => !esVersionCompatibleWithKibana(node.version, kibanaVersion)
+ (node) => !esVersionCompatibleWithKibana(node.version, kibanaVersion)
);
// Aggregate ES nodes which should prompt a Kibana upgrade. It's acceptable
// if ES and Kibana versions are not the same as long as they are not
// incompatible, but we should warn about it.
// Ignore version qualifiers https://github.com/elastic/elasticsearch/issues/36859
- const warningNodes = nodes.filter(node => !esVersionEqualsKibana(node.version, kibanaVersion));
+ const warningNodes = nodes.filter((node) => !esVersionEqualsKibana(node.version, kibanaVersion));
// Note: If incompatible and warning nodes are present `message` only contains
// an incompatibility notice.
let message;
if (incompatibleNodes.length > 0) {
- const incompatibleNodeNames = incompatibleNodes.map(node => node.name).join(', ');
+ const incompatibleNodeNames = incompatibleNodes.map((node) => node.name).join(', ');
if (ignoreVersionMismatch) {
message = `Ignoring version incompatibility between Kibana v${kibanaVersion} and the following Elasticsearch nodes: ${incompatibleNodeNames}`;
} else {
message = `This version of Kibana (v${kibanaVersion}) is incompatible with the following Elasticsearch nodes in your cluster: ${incompatibleNodeNames}`;
}
} else if (warningNodes.length > 0) {
- const warningNodeNames = warningNodes.map(node => node.name).join(', ');
+ const warningNodeNames = warningNodes.map((node) => node.name).join(', ');
message =
`You're running Kibana ${kibanaVersion} with some different versions of ` +
'Elasticsearch. Update Kibana or Elasticsearch to the same ' +
@@ -151,7 +151,7 @@ export const pollEsNodesVersion = ({
filterPath: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'],
})
).pipe(
- catchError(_err => {
+ catchError((_err) => {
return of({ nodes: {} });
})
);
diff --git a/src/core/server/http/auth_headers_storage.ts b/src/core/server/http/auth_headers_storage.ts
index 469e194a61fed..f532afc8b4bc7 100644
--- a/src/core/server/http/auth_headers_storage.ts
+++ b/src/core/server/http/auth_headers_storage.ts
@@ -33,7 +33,7 @@ export class AuthHeadersStorage {
public set = (request: KibanaRequest | LegacyRequest, headers: AuthHeaders) => {
this.authHeadersCache.set(ensureRawRequest(request), headers);
};
- public get: GetAuthHeaders = request => {
+ public get: GetAuthHeaders = (request) => {
return this.authHeadersCache.get(ensureRawRequest(request));
};
}
diff --git a/src/core/server/http/auth_state_storage.ts b/src/core/server/http/auth_state_storage.ts
index 10c8ccca32401..1172f06d06ab3 100644
--- a/src/core/server/http/auth_state_storage.ts
+++ b/src/core/server/http/auth_state_storage.ts
@@ -71,7 +71,7 @@ export class AuthStateStorage {
return { status, state };
};
- public isAuthenticated: IsAuthenticated = request => {
+ public isAuthenticated: IsAuthenticated = (request) => {
return this.get(request).status === AuthStatus.authenticated;
};
}
diff --git a/src/core/server/http/base_path_proxy_server.ts b/src/core/server/http/base_path_proxy_server.ts
index acefbd00ae2be..ffbdabadd03f7 100644
--- a/src/core/server/http/base_path_proxy_server.ts
+++ b/src/core/server/http/base_path_proxy_server.ts
@@ -180,9 +180,7 @@ export class BasePathProxyServer {
// condition is met (e.g. until target listener is ready).
async (request, responseToolkit) => {
apm.setTransactionName(`${request.method.toUpperCase()} /{basePath}/{kbnPath*}`);
- await delayUntil()
- .pipe(take(1))
- .toPromise();
+ await delayUntil().pipe(take(1)).toPromise();
return responseToolkit.continue;
},
],
@@ -216,9 +214,7 @@ export class BasePathProxyServer {
// Before we proxy request to a target port we may want to wait until some
// condition is met (e.g. until target listener is ready).
async (request, responseToolkit) => {
- await delayUntil()
- .pipe(take(1))
- .toPromise();
+ await delayUntil().pipe(take(1)).toPromise();
return responseToolkit.continue;
},
],
diff --git a/src/core/server/http/base_path_service.ts b/src/core/server/http/base_path_service.ts
index 5b5901b0ad6fb..093d73b2da3bf 100644
--- a/src/core/server/http/base_path_service.ts
+++ b/src/core/server/http/base_path_service.ts
@@ -69,7 +69,7 @@ export class BasePath {
*/
public prepend = (path: string): string => {
if (this.serverBasePath === '') return path;
- return modifyUrl(path, parts => {
+ return modifyUrl(path, (parts) => {
if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) {
parts.pathname = `${this.serverBasePath}${parts.pathname}`;
}
diff --git a/src/core/server/http/cookie_session_storage.test.ts b/src/core/server/http/cookie_session_storage.test.ts
index 0ca87eae6e235..a5612675c37de 100644
--- a/src/core/server/http/cookie_session_storage.test.ts
+++ b/src/core/server/http/cookie_session_storage.test.ts
@@ -101,7 +101,7 @@ const userData = { id: '42' };
const sessionDurationMs = 1000;
const path = '/';
const sessVal = () => ({ value: userData, expires: Date.now() + sessionDurationMs, path });
-const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
+const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
const cookieOptions = {
name: 'sid',
encryptionKey: 'something_at_least_32_characters',
@@ -135,9 +135,7 @@ describe('Cookie based SessionStorage', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
const cookies = response.get('set-cookie');
expect(cookies).toBeDefined();
@@ -174,9 +172,7 @@ describe('Cookie based SessionStorage', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
const cookies = response.get('set-cookie');
expect(cookies).toBeDefined();
@@ -207,9 +203,7 @@ describe('Cookie based SessionStorage', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200, { value: null });
+ const response = await supertest(innerServer.listener).get('/').expect(200, { value: null });
const cookies = response.get('set-cookie');
expect(cookies).not.toBeDefined();
@@ -414,9 +408,7 @@ describe('Cookie based SessionStorage', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
const cookies = response.get('set-cookie');
const sessionCookie = retrieveSessionCookie(cookies[0]);
diff --git a/src/core/server/http/http_config.ts b/src/core/server/http/http_config.ts
index 7c72e3270743e..289b6539fd762 100644
--- a/src/core/server/http/http_config.ts
+++ b/src/core/server/http/http_config.ts
@@ -103,7 +103,7 @@ export const config = {
}),
},
{
- validate: rawConfig => {
+ validate: (rawConfig) => {
if (!rawConfig.basePath && rawConfig.rewriteBasePath) {
return 'cannot use [rewriteBasePath] when [basePath] is not specified';
}
@@ -157,7 +157,7 @@ export class HttpConfig {
(headers, [key, value]) => {
return {
...headers,
- [key]: Array.isArray(value) ? value.map(e => convertHeader(e)) : convertHeader(value),
+ [key]: Array.isArray(value) ? value.map((e) => convertHeader(e)) : convertHeader(value),
};
},
{}
diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts
index 4fb433b5c77ba..1798c3a921da4 100644
--- a/src/core/server/http/http_server.test.ts
+++ b/src/core/server/http/http_server.test.ts
@@ -163,7 +163,7 @@ test('valid params', async () => {
await supertest(innerServer.listener)
.get('/foo/some-string')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('some-string');
});
});
@@ -193,7 +193,7 @@ test('invalid params', async () => {
await supertest(innerServer.listener)
.get('/foo/some-string')
.expect(400)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({
error: 'Bad Request',
statusCode: 400,
@@ -228,7 +228,7 @@ test('valid query', async () => {
await supertest(innerServer.listener)
.get('/foo/?bar=test&quux=123')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', quux: 123 });
});
});
@@ -258,7 +258,7 @@ test('invalid query', async () => {
await supertest(innerServer.listener)
.get('/foo/?bar=test')
.expect(400)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({
error: 'Bad Request',
statusCode: 400,
@@ -297,7 +297,7 @@ test('valid body', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
});
@@ -335,7 +335,7 @@ test('valid body with validate function', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
});
@@ -378,7 +378,7 @@ test('not inline validation - specifying params', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
});
@@ -421,7 +421,7 @@ test('not inline validation - specifying validation handler', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
});
@@ -471,7 +471,7 @@ test('not inline handler - KibanaRequest', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'TEST', baz: '123' });
});
});
@@ -520,7 +520,7 @@ test('not inline handler - RequestHandler', async () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'TEST', baz: '123' });
});
});
@@ -551,7 +551,7 @@ test('invalid body', async () => {
.post('/foo/')
.send({ bar: 'test' })
.expect(400)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({
error: 'Bad Request',
statusCode: 400,
@@ -586,7 +586,7 @@ test('handles putting', async () => {
.put('/foo/')
.send({ key: 'new value' })
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ key: 'new value' });
});
});
@@ -616,7 +616,7 @@ test('handles deleting', async () => {
await supertest(innerServer.listener)
.delete('/foo/3')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ key: 3 });
});
});
@@ -646,28 +646,22 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => {
});
test('/bar => 404', async () => {
- await supertest(innerServerListener)
- .get('/bar')
- .expect(404);
+ await supertest(innerServerListener).get('/bar').expect(404);
});
test('/bar/ => 404', async () => {
- await supertest(innerServerListener)
- .get('/bar/')
- .expect(404);
+ await supertest(innerServerListener).get('/bar/').expect(404);
});
test('/bar/foo => 404', async () => {
- await supertest(innerServerListener)
- .get('/bar/foo')
- .expect(404);
+ await supertest(innerServerListener).get('/bar/foo').expect(404);
});
test('/ => /', async () => {
await supertest(innerServerListener)
.get('/')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('value:/');
});
});
@@ -676,7 +670,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => {
await supertest(innerServerListener)
.get('/foo')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('value:/foo');
});
});
@@ -710,7 +704,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => {
await supertest(innerServerListener)
.get('/bar')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('value:/');
});
});
@@ -719,7 +713,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => {
await supertest(innerServerListener)
.get('/bar/')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('value:/');
});
});
@@ -728,21 +722,17 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => {
await supertest(innerServerListener)
.get('/bar/foo')
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.text).toBe('value:/foo');
});
});
test('/ => 404', async () => {
- await supertest(innerServerListener)
- .get('/')
- .expect(404);
+ await supertest(innerServerListener).get('/').expect(404);
});
test('/foo => 404', async () => {
- await supertest(innerServerListener)
- .get('/foo')
- .expect(404);
+ await supertest(innerServerListener).get('/foo').expect(404);
});
});
@@ -787,13 +777,9 @@ test('allows attaching metadata to attach meta-data tag strings to a route', asy
registerRouter(router);
await server.start();
- await supertest(innerServer.listener)
- .get('/with-tags')
- .expect(200, { tags });
+ await supertest(innerServer.listener).get('/with-tags').expect(200, { tags });
- await supertest(innerServer.listener)
- .get('/without-tags')
- .expect(200, { tags: [] });
+ await supertest(innerServer.listener).get('/without-tags').expect(200, { tags: [] });
});
test('exposes route details of incoming request to a route handler', async () => {
@@ -835,9 +821,7 @@ describe('conditional compression', () => {
test('with `compression.enabled: true`', async () => {
const listener = await setupServer(config);
- const response = await supertest(listener)
- .get('/')
- .set('accept-encoding', 'gzip');
+ const response = await supertest(listener).get('/').set('accept-encoding', 'gzip');
expect(response.header).toHaveProperty('content-encoding', 'gzip');
});
@@ -848,9 +832,7 @@ describe('conditional compression', () => {
compression: { enabled: false },
});
- const response = await supertest(listener)
- .get('/')
- .set('accept-encoding', 'gzip');
+ const response = await supertest(listener).get('/').set('accept-encoding', 'gzip');
expect(response.header).not.toHaveProperty('content-encoding');
});
@@ -865,9 +847,7 @@ describe('conditional compression', () => {
});
test('enables compression for no referer', async () => {
- const response = await supertest(listener)
- .get('/')
- .set('accept-encoding', 'gzip');
+ const response = await supertest(listener).get('/').set('accept-encoding', 'gzip');
expect(response.header).toHaveProperty('content-encoding', 'gzip');
});
@@ -952,14 +932,11 @@ describe('body options', () => {
registerRouter(router);
await server.start();
- await supertest(innerServer.listener)
- .post('/')
- .send({ test: 1 })
- .expect(415, {
- statusCode: 415,
- error: 'Unsupported Media Type',
- message: 'Unsupported Media Type',
- });
+ await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(415, {
+ statusCode: 415,
+ error: 'Unsupported Media Type',
+ message: 'Unsupported Media Type',
+ });
});
test('should reject the request because the payload is too large', async () => {
@@ -977,14 +954,11 @@ describe('body options', () => {
registerRouter(router);
await server.start();
- await supertest(innerServer.listener)
- .post('/')
- .send({ test: 1 })
- .expect(413, {
- statusCode: 413,
- error: 'Request Entity Too Large',
- message: 'Payload content length greater than maximum allowed: 1',
- });
+ await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(413, {
+ statusCode: 413,
+ error: 'Request Entity Too Large',
+ message: 'Payload content length greater than maximum allowed: 1',
+ });
});
test('should not parse the content in the request', async () => {
@@ -1010,14 +984,11 @@ describe('body options', () => {
registerRouter(router);
await server.start();
- await supertest(innerServer.listener)
- .post('/')
- .send({ test: 1 })
- .expect(200, {
- parse: false,
- maxBytes: 1024, // hapi populates the default
- output: 'data',
- });
+ await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(200, {
+ parse: false,
+ maxBytes: 1024, // hapi populates the default
+ output: 'data',
+ });
});
});
@@ -1043,14 +1014,11 @@ test('should return a stream in the body', async () => {
registerRouter(router);
await server.start();
- await supertest(innerServer.listener)
- .put('/')
- .send({ test: 1 })
- .expect(200, {
- parse: true,
- maxBytes: 1024, // hapi populates the default
- output: 'stream',
- });
+ await supertest(innerServer.listener).put('/').send({ test: 1 }).expect(200, {
+ parse: true,
+ maxBytes: 1024, // hapi populates the default
+ output: 'stream',
+ });
});
describe('setup contract', () => {
diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts
index 92ac5220735a1..8089ee901fa65 100644
--- a/src/core/server/http/http_server.ts
+++ b/src/core/server/http/http_server.ts
@@ -176,7 +176,7 @@ export class HttpServer {
// validation applied in ./http_tools#getServerOptions
// (All NP routes are already required to specify their own validation in order to access the payload)
validate,
- payload: [allow, maxBytes, output, parse].some(v => typeof v !== 'undefined')
+ payload: [allow, maxBytes, output, parse].some((v) => typeof v !== 'undefined')
? { allow, maxBytes, output, parse }
: undefined,
},
diff --git a/src/core/server/http/http_tools.test.ts b/src/core/server/http/http_tools.test.ts
index bdaab4f2999ed..79a1e32d1b51e 100644
--- a/src/core/server/http/http_tools.test.ts
+++ b/src/core/server/http/http_tools.test.ts
@@ -81,7 +81,7 @@ describe('timeouts', () => {
test('closes sockets on timeout', async () => {
const router = new Router('', logger.get(), enhanceWithContext);
router.get({ path: '/a', validate: false }, async (context, req, res) => {
- await new Promise(resolve => setTimeout(resolve, 2000));
+ await new Promise((resolve) => setTimeout(resolve, 2000));
return res.ok({});
});
router.get({ path: '/b', validate: false }, (context, req, res) => res.ok({}));
@@ -98,9 +98,7 @@ describe('timeouts', () => {
expect(supertest(innerServer.listener).get('/a')).rejects.toThrow('socket hang up');
- await supertest(innerServer.listener)
- .get('/b')
- .expect(200);
+ await supertest(innerServer.listener).get('/b').expect(200);
});
afterAll(async () => {
diff --git a/src/core/server/http/http_tools.ts b/src/core/server/http/http_tools.ts
index 6e785ae9f8f00..4e47cf492e287 100644
--- a/src/core/server/http/http_tools.ts
+++ b/src/core/server/http/http_tools.ts
@@ -53,7 +53,7 @@ export function getServerOptions(config: HttpConfig, { configureTLS = true } = {
// This is a default payload validation which applies to all LP routes which do not specify their own
// `validate.payload` handler, in order to reduce the likelyhood of prototype pollution vulnerabilities.
// (All NP routes are already required to specify their own validation in order to access the payload)
- payload: value => Promise.resolve(validateObject(value)),
+ payload: (value) => Promise.resolve(validateObject(value)),
},
},
state: {
@@ -104,7 +104,7 @@ export function createServer(serverOptions: ServerOptions, listenerOptions: List
server.listener.keepAliveTimeout = listenerOptions.keepaliveTimeout;
server.listener.setTimeout(listenerOptions.socketTimeout);
- server.listener.on('timeout', socket => {
+ server.listener.on('timeout', (socket) => {
socket.destroy();
});
server.listener.on('clientError', (err, socket) => {
@@ -155,7 +155,7 @@ export function defaultValidationErrorHandler(
const validationError: HapiValidationError = err as HapiValidationError;
const validationKeys: string[] = [];
- validationError.details.forEach(detail => {
+ validationError.details.forEach((detail) => {
if (detail.path.length > 0) {
validationKeys.push(Hoek.escapeHtml(detail.path.join('.')));
} else {
diff --git a/src/core/server/http/https_redirect_server.test.ts b/src/core/server/http/https_redirect_server.test.ts
index e7cd653bb9eec..a7d3cbe41aa3d 100644
--- a/src/core/server/http/https_redirect_server.test.ts
+++ b/src/core/server/http/https_redirect_server.test.ts
@@ -100,7 +100,7 @@ test('forwards http requests to https', async () => {
await supertest(getServerListener(server))
.get('/')
.expect(302)
- .then(res => {
+ .then((res) => {
expect(res.header.location).toEqual(`https://${config.host}:${config.port}/`);
});
});
diff --git a/src/core/server/http/integration_tests/core_service.test.mocks.ts b/src/core/server/http/integration_tests/core_service.test.mocks.ts
index b3adda8dd22d1..8e782970e2a8e 100644
--- a/src/core/server/http/integration_tests/core_service.test.mocks.ts
+++ b/src/core/server/http/integration_tests/core_service.test.mocks.ts
@@ -20,7 +20,7 @@ import { elasticsearchServiceMock } from '../../elasticsearch/elasticsearch_serv
export const clusterClientMock = jest.fn();
jest.doMock('../../elasticsearch/scoped_cluster_client', () => ({
- ScopedClusterClient: clusterClientMock.mockImplementation(function() {
+ ScopedClusterClient: clusterClientMock.mockImplementation(function () {
return elasticsearchServiceMock.createScopedClusterClient();
}),
}));
@@ -30,7 +30,7 @@ jest.doMock('elasticsearch', () => {
return {
...realES,
// eslint-disable-next-line object-shorthand
- Client: function() {
+ Client: function () {
return elasticsearchServiceMock.createElasticsearchClient();
},
};
diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts
index 0f0d54e88daca..73ed4e5de4b04 100644
--- a/src/core/server/http/integration_tests/lifecycle.test.ts
+++ b/src/core/server/http/integration_tests/lifecycle.test.ts
@@ -75,9 +75,7 @@ describe('OnPreAuth', () => {
});
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, 'ok');
+ await supertest(innerServer.listener).get('/').expect(200, 'ok');
expect(callingOrder).toEqual(['first', 'second']);
});
@@ -108,9 +106,7 @@ describe('OnPreAuth', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/initial')
- .expect(200, 'redirected');
+ await supertest(innerServer.listener).get('/initial').expect(200, 'redirected');
expect(urlBeforeForwarding).toBe('/initial');
expect(urlAfterForwarding).toBe('/redirectUrl');
@@ -132,9 +128,7 @@ describe('OnPreAuth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/initial')
- .expect(302);
+ const result = await supertest(innerServer.listener).get('/initial').expect(302);
expect(result.header.location).toBe(redirectUrl);
});
@@ -154,9 +148,7 @@ describe('OnPreAuth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.header['www-authenticate']).toBe('challenge');
});
@@ -172,9 +164,7 @@ describe('OnPreAuth', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -195,9 +185,7 @@ describe('OnPreAuth', () => {
registerOnPreAuth((req, res, t) => ({} as any));
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -232,9 +220,7 @@ describe('OnPreAuth', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { customField: 'undefined' });
+ await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' });
});
});
@@ -257,9 +243,7 @@ describe('OnPostAuth', () => {
});
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, 'ok');
+ await supertest(innerServer.listener).get('/').expect(200, 'ok');
expect(callingOrder).toEqual(['first', 'second']);
});
@@ -280,9 +264,7 @@ describe('OnPostAuth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/initial')
- .expect(302);
+ const result = await supertest(innerServer.listener).get('/initial').expect(302);
expect(result.header.location).toBe(redirectUrl);
});
@@ -301,9 +283,7 @@ describe('OnPostAuth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.header['www-authenticate']).toBe('challenge');
});
@@ -318,9 +298,7 @@ describe('OnPostAuth', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -340,9 +318,7 @@ describe('OnPostAuth', () => {
registerOnPostAuth((req, res, t) => ({} as any));
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -378,9 +354,7 @@ describe('OnPostAuth', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { customField: 'undefined' });
+ await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' });
});
});
@@ -410,9 +384,7 @@ describe('Auth', () => {
registerAuth((req, res, t) => t.authenticated());
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { content: 'ok' });
+ await supertest(innerServer.listener).get('/').expect(200, { content: 'ok' });
});
it('blocks access to a resource if credentials are not provided', async () => {
@@ -425,9 +397,7 @@ describe('Auth', () => {
registerAuth((req, res, t) => t.notHandled());
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body.message).toBe('Unauthorized');
});
@@ -443,9 +413,7 @@ describe('Auth', () => {
registerAuth(authenticate);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { authRequired: true });
+ await supertest(innerServer.listener).get('/').expect(200, { authRequired: true });
expect(authenticate).toHaveBeenCalledTimes(1);
});
@@ -463,9 +431,7 @@ describe('Auth', () => {
registerAuth(authenticate);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { authRequired: false });
+ await supertest(innerServer.listener).get('/').expect(200, { authRequired: false });
expect(authenticate).toHaveBeenCalledTimes(0);
});
@@ -483,9 +449,7 @@ describe('Auth', () => {
await registerAuth(authenticate);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { authRequired: true });
+ await supertest(innerServer.listener).get('/').expect(200, { authRequired: true });
expect(authenticate).toHaveBeenCalledTimes(1);
});
@@ -498,9 +462,7 @@ describe('Auth', () => {
registerAuth((req, res) => res.unauthorized());
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ await supertest(innerServer.listener).get('/').expect(401);
});
it('supports redirecting', async () => {
@@ -516,9 +478,7 @@ describe('Auth', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(302);
+ const response = await supertest(innerServer.listener).get('/').expect(302);
expect(response.header.location).toBe(redirectTo);
});
@@ -530,9 +490,7 @@ describe('Auth', () => {
registerAuth((req, res, t) => t.redirected({} as any));
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ await supertest(innerServer.listener).get('/').expect(500);
});
it(`doesn't expose internal error details`, async () => {
@@ -545,9 +503,7 @@ describe('Auth', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -582,9 +538,7 @@ describe('Auth', () => {
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
expect(response.header['set-cookie']).toBeDefined();
const cookies = response.header['set-cookie'];
@@ -628,9 +582,7 @@ describe('Auth', () => {
});
await server.start();
- const responseToSetCookie = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const responseToSetCookie = await supertest(innerServer.listener).get('/').expect(200);
expect(responseToSetCookie.header['set-cookie']).toBeDefined();
@@ -680,10 +632,7 @@ describe('Auth', () => {
await server.start();
const token = 'Basic: user:password';
- await supertest(innerServer.listener)
- .get('/')
- .set('Authorization', token)
- .expect(200);
+ await supertest(innerServer.listener).get('/').set('Authorization', token).expect(200);
expect(fromRegisterOnPreAuth).toEqual({});
expect(fromRegisterAuth).toEqual({ authorization: token });
@@ -705,9 +654,7 @@ describe('Auth', () => {
router.get({ path: '/', validate: false }, (context, req, res) => res.ok());
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']);
});
@@ -726,9 +673,7 @@ describe('Auth', () => {
router.get({ path: '/', validate: false }, (context, req, res) => res.badRequest());
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(400);
+ const response = await supertest(innerServer.listener).get('/').expect(400);
expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']);
});
@@ -755,9 +700,7 @@ describe('Auth', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const response = await supertest(innerServer.listener).get('/').expect(200);
expect(response.header['www-authenticate']).toBe('from auth interceptor');
expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(`
@@ -790,9 +733,7 @@ describe('Auth', () => {
);
await server.start();
- const response = await supertest(innerServer.listener)
- .get('/')
- .expect(400);
+ const response = await supertest(innerServer.listener).get('/').expect(400);
expect(response.header['www-authenticate']).toBe('from auth interceptor');
expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(`
@@ -819,9 +760,7 @@ describe('Auth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/initial')
- .expect(302);
+ const result = await supertest(innerServer.listener).get('/initial').expect(302);
expect(result.header.location).toBe(redirectUrl);
});
@@ -841,9 +780,7 @@ describe('Auth', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.header['www-authenticate']).toBe('challenge');
});
@@ -858,9 +795,7 @@ describe('Auth', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -880,9 +815,7 @@ describe('Auth', () => {
registerOnPostAuth((req, res, t) => ({} as any));
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -917,9 +850,7 @@ describe('Auth', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, { customField: 'undefined' });
+ await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' });
});
});
@@ -944,9 +875,7 @@ describe('OnPreResponse', () => {
});
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, 'ok');
+ await supertest(innerServer.listener).get('/').expect(200, 'ok');
expect(callingOrder).toEqual(['first', 'second']);
});
@@ -974,9 +903,7 @@ describe('OnPreResponse', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.header['x-kibana-header']).toBe('value');
expect(result.header['x-my-header']).toBe('foo');
@@ -1000,9 +927,7 @@ describe('OnPreResponse', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ await supertest(innerServer.listener).get('/').expect(200);
expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(`
Array [
@@ -1025,9 +950,7 @@ describe('OnPreResponse', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -1049,9 +972,7 @@ describe('OnPreResponse', () => {
registerOnPreResponse((req, res, t) => ({} as any));
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -1078,8 +999,6 @@ describe('OnPreResponse', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ await supertest(innerServer.listener).get('/').expect(200);
});
});
diff --git a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts
index b5364c616f17c..2120fb5b881de 100644
--- a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts
+++ b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts
@@ -94,9 +94,7 @@ describe('core lifecycle handlers', () => {
});
it('accepts requests that do not include a version header', async () => {
- await supertest(innerServer.listener)
- .get(testRoute)
- .expect(200, 'ok');
+ await supertest(innerServer.listener).get(testRoute).expect(200, 'ok');
});
it('rejects requests with an incorrect version passed in the version header', async () => {
@@ -122,9 +120,7 @@ describe('core lifecycle handlers', () => {
});
it('adds the kbn-name header', async () => {
- const result = await supertest(innerServer.listener)
- .get(testRoute)
- .expect(200, 'ok');
+ const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok');
const headers = result.header as Record;
expect(headers).toEqual(
expect.objectContaining({
@@ -134,9 +130,7 @@ describe('core lifecycle handlers', () => {
});
it('adds the kbn-name header in case of error', async () => {
- const result = await supertest(innerServer.listener)
- .get(testErrorRoute)
- .expect(400);
+ const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400);
const headers = result.header as Record;
expect(headers).toEqual(
expect.objectContaining({
@@ -146,17 +140,13 @@ describe('core lifecycle handlers', () => {
});
it('adds the custom headers', async () => {
- const result = await supertest(innerServer.listener)
- .get(testRoute)
- .expect(200, 'ok');
+ const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok');
const headers = result.header as Record;
expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' }));
});
it('adds the custom headers in case of error', async () => {
- const result = await supertest(innerServer.listener)
- .get(testErrorRoute)
- .expect(400);
+ const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400);
const headers = result.header as Record;
expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' }));
});
@@ -176,7 +166,7 @@ describe('core lifecycle handlers', () => {
return res.ok({ body: 'ok' });
});
- destructiveMethods.forEach(method => {
+ destructiveMethods.forEach((method) => {
((router as any)[method.toLowerCase()] as RouteRegistrar)(
{ path: testPath, validate: false },
(context, req, res) => {
@@ -200,7 +190,7 @@ describe('core lifecycle handlers', () => {
await server.start();
});
- nonDestructiveMethods.forEach(method => {
+ nonDestructiveMethods.forEach((method) => {
describe(`When using non-destructive ${method} method`, () => {
it('accepts requests without a token', async () => {
await getSupertest(method.toLowerCase(), testPath).expect(
@@ -217,7 +207,7 @@ describe('core lifecycle handlers', () => {
});
});
- destructiveMethods.forEach(method => {
+ destructiveMethods.forEach((method) => {
describe(`When using destructive ${method} method`, () => {
it('accepts requests with the xsrf header', async () => {
await getSupertest(method.toLowerCase(), testPath)
diff --git a/src/core/server/http/integration_tests/request.test.ts b/src/core/server/http/integration_tests/request.test.ts
index 85270174fbc04..d33757273042b 100644
--- a/src/core/server/http/integration_tests/request.test.ts
+++ b/src/core/server/http/integration_tests/request.test.ts
@@ -43,7 +43,7 @@ afterEach(async () => {
await server.stop();
});
-const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('KibanaRequest', () => {
describe('auth', () => {
describe('isAuthenticated', () => {
@@ -56,11 +56,9 @@ describe('KibanaRequest', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- isAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ isAuthenticated: false,
+ });
});
it('returns false if not authenticated on a route with authRequired: "optional"', async () => {
const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps);
@@ -72,11 +70,9 @@ describe('KibanaRequest', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- isAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ isAuthenticated: false,
+ });
});
it('returns false if redirected on a route with authRequired: "optional"', async () => {
const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps);
@@ -88,11 +84,9 @@ describe('KibanaRequest', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- isAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ isAuthenticated: false,
+ });
});
it('returns true if authenticated on a route with authRequired: "optional"', async () => {
const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps);
@@ -104,11 +98,9 @@ describe('KibanaRequest', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- isAuthenticated: true,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ isAuthenticated: true,
+ });
});
it('returns true if authenticated', async () => {
const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps);
@@ -120,17 +112,15 @@ describe('KibanaRequest', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- isAuthenticated: true,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ isAuthenticated: true,
+ });
});
});
});
describe('events', () => {
describe('aborted$', () => {
- it('emits once and completes when request aborted', async done => {
+ it('emits once and completes when request aborted', async (done) => {
expect.assertions(1);
const { server: innerServer, createRouter } = await server.setup(setupDeps);
const router = createRouter('/');
diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts
index af05229f86f20..8f3799b12eccb 100644
--- a/src/core/server/http/integration_tests/router.test.ts
+++ b/src/core/server/http/integration_tests/router.test.ts
@@ -65,12 +65,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: false,
- requestIsAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: false,
+ requestIsAuthenticated: false,
+ });
});
it('Authenticated user has access to a route', async () => {
@@ -94,12 +92,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: true,
- requestIsAuthenticated: true,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: true,
+ requestIsAuthenticated: true,
+ });
});
it('User with no credentials can access a route', async () => {
@@ -122,12 +118,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: false,
- requestIsAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: false,
+ requestIsAuthenticated: false,
+ });
});
it('User with invalid credentials cannot access a route', async () => {
@@ -142,9 +136,7 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ await supertest(innerServer.listener).get('/').expect(401);
});
it('does not redirect user and allows access to a resource', async () => {
@@ -171,12 +163,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: false,
- requestIsAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: false,
+ requestIsAuthenticated: false,
+ });
});
});
@@ -197,12 +187,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: false,
- requestIsAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: false,
+ requestIsAuthenticated: false,
+ });
});
it('Authenticated user has access to a route', async () => {
@@ -226,12 +214,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: true,
- requestIsAuthenticated: true,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: true,
+ requestIsAuthenticated: true,
+ });
});
it('User with no credentials cannot access a route', async () => {
@@ -245,9 +231,7 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ await supertest(innerServer.listener).get('/').expect(401);
});
it('User with invalid credentials cannot access a route', async () => {
@@ -262,9 +246,7 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ await supertest(innerServer.listener).get('/').expect(401);
});
it('allows redirecting an user', async () => {
@@ -284,9 +266,7 @@ describe('Options', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(302);
+ const result = await supertest(innerServer.listener).get('/').expect(302);
expect(result.header.location).toBe(redirectUrl);
});
@@ -313,12 +293,10 @@ describe('Options', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200, {
- httpAuthIsAuthenticated: false,
- requestIsAuthenticated: false,
- });
+ await supertest(innerServer.listener).get('/').expect(200, {
+ httpAuthIsAuthenticated: false,
+ requestIsAuthenticated: false,
+ });
expect(authHook).toHaveBeenCalledTimes(0);
});
@@ -352,9 +330,7 @@ describe('Cache-Control', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect('Cache-Control', 'public, max-age=1200');
+ await supertest(innerServer.listener).get('/').expect('Cache-Control', 'public, max-age=1200');
});
});
@@ -368,9 +344,7 @@ describe('Handler', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -391,9 +365,7 @@ describe('Handler', () => {
});
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -412,9 +384,7 @@ describe('Handler', () => {
router.get({ path: '/', validate: false }, (context, req, res) => 'ok' as any);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -501,11 +471,7 @@ describe('Handler', () => {
);
await server.start();
- await supertest(innerServer.listener)
- .post('/')
- .type('json')
- .send('12')
- .expect(200);
+ await supertest(innerServer.listener).post('/').type('json').send('12').expect(200);
expect(body).toEqual(12);
});
@@ -524,9 +490,7 @@ describe('handleLegacyErrors', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(404);
+ const result = await supertest(innerServer.listener).get('/').expect(404);
expect(result.body.message).toBe('Not Found');
});
@@ -546,9 +510,7 @@ describe('handleLegacyErrors', () => {
);
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body).toEqual({
error: 'Internal Server Error',
@@ -570,9 +532,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.body).toEqual({ key: 'value' });
expect(result.header['content-type']).toBe('application/json; charset=utf-8');
@@ -588,9 +548,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.text).toBe('result');
expect(result.header['content-type']).toBe('text/html; charset=utf-8');
@@ -606,9 +564,7 @@ describe('Response factory', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ await supertest(innerServer.listener).get('/').expect(200);
});
it('supports answering with Stream', async () => {
@@ -630,9 +586,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.text).toBe('abc');
expect(result.header['content-type']).toBe(undefined);
@@ -646,7 +600,7 @@ describe('Response factory', () => {
const stream = new Stream.PassThrough();
stream.write('a');
stream.write('b');
- setTimeout(function() {
+ setTimeout(function () {
stream.write('c');
stream.end();
}, 100);
@@ -656,9 +610,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.text).toBe('abc');
expect(result.header['transfer-encoding']).toBe('chunked');
@@ -681,10 +633,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200)
- .buffer(true);
+ const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true);
expect(result.header['content-encoding']).toBe('binary');
expect(result.header['content-length']).toBe('1028');
@@ -708,10 +657,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200)
- .buffer(true);
+ const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true);
expect(result.text).toBe('abc');
expect(result.header['content-length']).toBe('3');
@@ -733,9 +679,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.text).toEqual('value');
expect(result.header.etag).toBe('1234');
@@ -757,9 +701,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.text).toEqual('value');
expect(result.header.etag).toBe('1234');
@@ -781,9 +723,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.header.etag).toBe('1234');
});
@@ -803,9 +743,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.header['set-cookie']).toEqual(['foo', 'bar']);
});
@@ -822,9 +760,7 @@ describe('Response factory', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ await supertest(innerServer.listener).get('/').expect(500);
// error happens within hapi when route handler already finished execution.
expect(loggingServiceMock.collect(logger).error).toHaveLength(0);
@@ -840,9 +776,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(200);
+ const result = await supertest(innerServer.listener).get('/').expect(200);
expect(result.body).toEqual({ key: 'value' });
expect(result.header['content-type']).toBe('application/json; charset=utf-8');
@@ -858,9 +792,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(202);
+ const result = await supertest(innerServer.listener).get('/').expect(202);
expect(result.body).toEqual({ location: 'somewhere' });
expect(result.header['content-type']).toBe('application/json; charset=utf-8');
@@ -876,9 +808,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(204);
+ const result = await supertest(innerServer.listener).get('/').expect(204);
expect(result.noContent).toBe(true);
});
@@ -901,9 +831,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(302);
+ const result = await supertest(innerServer.listener).get('/').expect(302);
expect(result.text).toBe('The document has moved');
expect(result.header.location).toBe('/new-url');
@@ -924,9 +852,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -951,9 +877,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(400);
+ const result = await supertest(innerServer.listener).get('/').expect(400);
expect(result.body).toEqual({
error: 'Bad Request',
@@ -972,9 +896,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(400);
+ const result = await supertest(innerServer.listener).get('/').expect(400);
expect(result.body).toEqual({
error: 'Bad Request',
@@ -995,9 +917,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(400);
+ const result = await supertest(innerServer.listener).get('/').expect(400);
expect(result.body).toEqual({
error: 'Bad Request',
@@ -1040,7 +960,7 @@ describe('Response factory', () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
@@ -1051,7 +971,7 @@ describe('Response factory', () => {
baz: '123',
})
.expect(400)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({
error: 'Bad Request',
message: '[request body.body]: Wrong payload',
@@ -1088,7 +1008,7 @@ describe('Response factory', () => {
baz: 123,
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
@@ -1099,7 +1019,7 @@ describe('Response factory', () => {
baz: '123', // Automatic casting happens
})
.expect(200)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({ bar: 'test', baz: 123 });
});
@@ -1110,7 +1030,7 @@ describe('Response factory', () => {
baz: 'test', // Can't cast it into number
})
.expect(400)
- .then(res => {
+ .then((res) => {
expect(res.body).toEqual({
error: 'Bad Request',
message: '[request body.baz]: expected value of type [number] but got [string]',
@@ -1135,9 +1055,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body.message).toBe('no access');
expect(result.header['www-authenticate']).toBe('challenge');
@@ -1153,9 +1071,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body.message).toBe('Unauthorized');
});
@@ -1171,9 +1087,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(403);
+ const result = await supertest(innerServer.listener).get('/').expect(403);
expect(result.body.message).toBe('reason');
});
@@ -1188,9 +1102,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(403);
+ const result = await supertest(innerServer.listener).get('/').expect(403);
expect(result.body.message).toBe('Forbidden');
});
@@ -1206,9 +1118,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(404);
+ const result = await supertest(innerServer.listener).get('/').expect(404);
expect(result.body.message).toBe('file is not found');
});
@@ -1223,9 +1133,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(404);
+ const result = await supertest(innerServer.listener).get('/').expect(404);
expect(result.body.message).toBe('Not Found');
});
@@ -1241,9 +1149,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(409);
+ const result = await supertest(innerServer.listener).get('/').expect(409);
expect(result.body.message).toBe('stale version');
});
@@ -1258,9 +1164,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(409);
+ const result = await supertest(innerServer.listener).get('/').expect(409);
expect(result.body.message).toBe('Conflict');
});
@@ -1279,9 +1183,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(418);
+ const result = await supertest(innerServer.listener).get('/').expect(418);
expect(result.body).toEqual({
error: "I'm a teapot",
@@ -1305,9 +1207,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body).toEqual({
error: 'Internal Server Error',
@@ -1331,9 +1231,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body).toEqual({
error: 'Internal Server Error',
@@ -1356,9 +1254,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body).toEqual({
error: 'Internal Server Error',
@@ -1392,9 +1288,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(201);
+ const result = await supertest(innerServer.listener).get('/').expect(201);
expect(result.header.location).toBe('somewhere');
});
@@ -1415,9 +1309,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(301);
+ const result = await supertest(innerServer.listener).get('/').expect(301);
expect(result.header.location).toBe('/new-url');
});
@@ -1436,9 +1328,7 @@ describe('Response factory', () => {
await server.start();
- await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ await supertest(innerServer.listener).get('/').expect(500);
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
Array [
@@ -1463,9 +1353,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body.message).toBe('unauthorized');
});
@@ -1486,9 +1374,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body).toEqual({
error: 'Unauthorized',
@@ -1514,9 +1400,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body).toEqual({
error: 'Unauthorized',
@@ -1540,9 +1424,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(401);
+ const result = await supertest(innerServer.listener).get('/').expect(401);
expect(result.body.message).toBe('Unauthorized');
});
@@ -1560,9 +1442,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('reason');
expect(loggingServiceMock.collect(logger).error).toHaveLength(0);
@@ -1581,9 +1461,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -1607,9 +1485,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -1632,9 +1508,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
@@ -1657,9 +1531,7 @@ describe('Response factory', () => {
await server.start();
- const result = await supertest(innerServer.listener)
- .get('/')
- .expect(500);
+ const result = await supertest(innerServer.listener).get('/').expect(500);
expect(result.body.message).toBe('An internal server error occurred.');
expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(`
diff --git a/src/core/server/http/lifecycle/on_pre_response.ts b/src/core/server/http/lifecycle/on_pre_response.ts
index 050881472bc80..9c8c6fba690d1 100644
--- a/src/core/server/http/lifecycle/on_pre_response.ts
+++ b/src/core/server/http/lifecycle/on_pre_response.ts
@@ -147,7 +147,7 @@ function findHeadersIntersection(
headers: ResponseHeaders,
log: Logger
) {
- Object.keys(headers).forEach(headerName => {
+ Object.keys(headers).forEach((headerName) => {
if (Reflect.has(responseHeaders, headerName)) {
log.warn(`onPreResponseHandler rewrote a response header [${headerName}].`);
}
diff --git a/src/core/server/http/prototype_pollution/validate_object.test.ts b/src/core/server/http/prototype_pollution/validate_object.test.ts
index 9e23d6cec6444..23d6c4ae3b49f 100644
--- a/src/core/server/http/prototype_pollution/validate_object.test.ts
+++ b/src/core/server/http/prototype_pollution/validate_object.test.ts
@@ -51,8 +51,8 @@ test(`fails on circular references`, () => {
},
{ constructor: { foo: { prototype: null } } },
{ prototype: { foo: { constructor: null } } },
-].forEach(value => {
- ['headers', 'payload', 'query', 'params'].forEach(property => {
+].forEach((value) => {
+ ['headers', 'payload', 'query', 'params'].forEach((property) => {
const obj = {
[property]: value,
};
@@ -72,7 +72,7 @@ test(`fails on circular references`, () => {
JSON.parse(`{ "constructor": { "prototype" : null } }`),
JSON.parse(`{ "foo": { "constructor": { "prototype" : null } } }`),
JSON.parse(`{ "foo": { "bar": { "constructor": { "prototype" : null } } } }`),
-].forEach(value => {
+].forEach((value) => {
test(`can't submit ${JSON.stringify(value)}`, () => {
expect(() => validateObject(value)).toThrowErrorMatchingSnapshot();
});
diff --git a/src/core/server/http/router/error_wrapper.ts b/src/core/server/http/router/error_wrapper.ts
index af99812eff4b3..75d0e0d630296 100644
--- a/src/core/server/http/router/error_wrapper.ts
+++ b/src/core/server/http/router/error_wrapper.ts
@@ -20,7 +20,7 @@
import Boom from 'boom';
import { RequestHandlerWrapper } from './router';
-export const wrapErrors: RequestHandlerWrapper = handler => {
+export const wrapErrors: RequestHandlerWrapper = (handler) => {
return async (context, request, response) => {
try {
return await handler(context, request, response);
diff --git a/src/core/server/http/router/headers.ts b/src/core/server/http/router/headers.ts
index b79cc0d325f1e..f27f5e937b2c0 100644
--- a/src/core/server/http/router/headers.ts
+++ b/src/core/server/http/router/headers.ts
@@ -71,7 +71,7 @@ export function filterHeaders(
// Normalize list of headers we want to allow in upstream request
const fieldsToKeepNormalized = fieldsToKeep
.map(normalizeHeaderField)
- .filter(name => !fieldsToExcludeNormalized.includes(name));
+ .filter((name) => !fieldsToExcludeNormalized.includes(name));
return pick(headers, fieldsToKeepNormalized);
}
diff --git a/src/core/server/http/router/router.mock.ts b/src/core/server/http/router/router.mock.ts
index b43db0ca7ed5a..651d1712100ee 100644
--- a/src/core/server/http/router/router.mock.ts
+++ b/src/core/server/http/router/router.mock.ts
@@ -30,7 +30,7 @@ function create({ routerPath = '' }: { routerPath?: string } = {}): RouterMock {
put: jest.fn(),
patch: jest.fn(),
getRoutes: jest.fn(),
- handleLegacyErrors: jest.fn().mockImplementation(handler => handler),
+ handleLegacyErrors: jest.fn().mockImplementation((handler) => handler),
};
}
diff --git a/src/core/server/http/router/validator/validator.test.ts b/src/core/server/http/router/validator/validator.test.ts
index e972e2075e705..30f66f5d41fbe 100644
--- a/src/core/server/http/router/validator/validator.test.ts
+++ b/src/core/server/http/router/validator/validator.test.ts
@@ -46,7 +46,7 @@ describe('Router validator', () => {
it('should validate and infer the type from a function that does not use the resolver', () => {
const validator = RouteValidator.from({
- params: data => {
+ params: (data) => {
if (typeof data.foo === 'string') {
return { value: { foo: data.foo as string } };
}
@@ -112,7 +112,7 @@ describe('Router validator', () => {
it('should catch the errors thrown by the validate function', () => {
const validator = RouteValidator.from({
- params: data => {
+ params: (data) => {
throw new Error('Something went terribly wrong');
},
});
diff --git a/src/core/server/http/ssl_config.ts b/src/core/server/http/ssl_config.ts
index 4eb0c50e72362..75dc05d1a801b 100644
--- a/src/core/server/http/ssl_config.ts
+++ b/src/core/server/http/ssl_config.ts
@@ -65,7 +65,7 @@ export const sslSchema = schema.object(
),
},
{
- validate: ssl => {
+ validate: (ssl) => {
if (ssl.key && ssl.keystore.path) {
return 'cannot use [key] when [keystore.path] is specified';
}
diff --git a/src/core/server/legacy/config/ensure_valid_configuration.ts b/src/core/server/legacy/config/ensure_valid_configuration.ts
index a68d3df577a89..5cd1603ea65fb 100644
--- a/src/core/server/legacy/config/ensure_valid_configuration.ts
+++ b/src/core/server/legacy/config/ensure_valid_configuration.ts
@@ -36,7 +36,7 @@ export async function ensureValidConfiguration(
if (unusedConfigKeys.length > 0) {
const message = `Unknown configuration key(s): ${unusedConfigKeys
- .map(key => `"${key}"`)
+ .map((key) => `"${key}"`)
.join(', ')}. Check for spelling errors and ensure that expected plugins are installed.`;
throw new InvalidConfigurationError(message);
}
diff --git a/src/core/server/legacy/config/get_unused_config_keys.ts b/src/core/server/legacy/config/get_unused_config_keys.ts
index 20c9776f63c58..6cd193d896109 100644
--- a/src/core/server/legacy/config/get_unused_config_keys.ts
+++ b/src/core/server/legacy/config/get_unused_config_keys.ts
@@ -72,8 +72,8 @@ export async function getUnusedConfigKeys({
// Filter out keys that are marked as used in the core (e.g. by new core plugins).
return difference(inputKeys, appliedKeys).filter(
- unusedConfigKey =>
- !coreHandledConfigPaths.some(usedInCoreConfigKey =>
+ (unusedConfigKey) =>
+ !coreHandledConfigPaths.some((usedInCoreConfigKey) =>
hasConfigPathIntersection(unusedConfigKey, usedInCoreConfigKey)
)
);
diff --git a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts
index 8651d05064492..b09f9d00b3bed 100644
--- a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts
+++ b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts
@@ -27,7 +27,7 @@ jest.spyOn(configDeprecationFactory, 'unusedFromRoot');
jest.spyOn(configDeprecationFactory, 'renameFromRoot');
const executeHandlers = (handlers: ConfigDeprecation[]) => {
- handlers.forEach(handler => {
+ handlers.forEach((handler) => {
handler({}, '', () => null);
});
};
@@ -99,7 +99,7 @@ describe('convertLegacyDeprecationProvider', () => {
const migrated = applyDeprecations(
rawConfig,
- handlers.map(handler => ({ deprecation: handler, path: '' }))
+ handlers.map((handler) => ({ deprecation: handler, path: '' }))
);
expect(migrated).toEqual({ new: 'oldvalue', goodValue: 'good' });
});
diff --git a/src/core/server/legacy/legacy_internals.test.ts b/src/core/server/legacy/legacy_internals.test.ts
index dcab62627442b..2ae5e3a3fd1e8 100644
--- a/src/core/server/legacy/legacy_internals.test.ts
+++ b/src/core/server/legacy/legacy_internals.test.ts
@@ -84,7 +84,7 @@ describe('LegacyInternals', () => {
jest.fn().mockResolvedValue({ is: 'merged-core' }),
];
- injectors.forEach(injector => legacyInternals.injectUiAppVars('core', injector));
+ injectors.forEach((injector) => legacyInternals.injectUiAppVars('core', injector));
await expect(legacyInternals.getInjectedUiAppVars('core')).resolves.toMatchInlineSnapshot(`
Object {
@@ -136,10 +136,10 @@ describe('LegacyInternals', () => {
it('gets: no default injectors, with injected vars replacers, with ui app injectors, no inject arg', async () => {
uiExports.injectedVarsReplacers = [
- jest.fn(async vars => ({ ...vars, added: 'key' })),
- jest.fn(vars => vars),
- jest.fn(vars => ({ replaced: 'all' })),
- jest.fn(async vars => ({ ...vars, added: 'last-key' })),
+ jest.fn(async (vars) => ({ ...vars, added: 'key' })),
+ jest.fn((vars) => vars),
+ jest.fn((vars) => ({ replaced: 'all' })),
+ jest.fn(async (vars) => ({ ...vars, added: 'last-key' })),
];
const request = httpServerMock.createRawRequest();
@@ -186,7 +186,7 @@ describe('LegacyInternals', () => {
varsProvider({ gamma: 'gamma' }),
varsProvider({ alpha: 'beta' }),
];
- uiExports.injectedVarsReplacers = [jest.fn(async vars => ({ ...vars, gamma: 'delta' }))];
+ uiExports.injectedVarsReplacers = [jest.fn(async (vars) => ({ ...vars, gamma: 'delta' }))];
legacyInternals.injectUiAppVars('core', async () => ({ is: 'core' }));
legacyInternals.injectUiAppVars('core', () => ({ sync: 'injector' }));
diff --git a/src/core/server/legacy/legacy_service.test.ts b/src/core/server/legacy/legacy_service.test.ts
index a75f7dda302c2..d9a0ac5e4ecff 100644
--- a/src/core/server/legacy/legacy_service.test.ts
+++ b/src/core/server/legacy/legacy_service.test.ts
@@ -353,7 +353,7 @@ describe('once LegacyService is set up without connection info', () => {
describe('once LegacyService is set up in `devClusterMaster` mode', () => {
beforeEach(() => {
- configService.atPath.mockImplementation(path => {
+ configService.atPath.mockImplementation((path) => {
return new BehaviorSubject(
path === 'dev' ? { basePathProxyTargetPort: 100500 } : { basePath: '/abc' }
);
@@ -447,7 +447,7 @@ describe('#discoverPlugins()', () => {
it(`register legacy plugin's deprecation providers`, async () => {
findLegacyPluginSpecsMock.mockImplementation(
- settings =>
+ (settings) =>
Promise.resolve({
pluginSpecs: [
{
@@ -486,7 +486,7 @@ describe('#discoverPlugins()', () => {
{ getId: () => 'pluginB', getDeprecationsProvider: () => undefined },
];
findLegacyPluginSpecsMock.mockImplementation(
- settings =>
+ (settings) =>
Promise.resolve({
pluginSpecs,
pluginExtendedConfig: settings,
diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts
index b95362e1ea26e..df1ed3e100923 100644
--- a/src/core/server/legacy/legacy_service.ts
+++ b/src/core/server/legacy/legacy_service.ts
@@ -91,7 +91,7 @@ export class LegacyService implements CoreService {
this.log = logger.get('legacy-service');
this.devConfig$ = configService
.atPath(devConfig.path)
- .pipe(map(rawConfig => new DevConfig(rawConfig)));
+ .pipe(map((rawConfig) => new DevConfig(rawConfig)));
this.httpConfig$ = combineLatest(
configService.atPath(httpConfig.path),
configService.atPath(cspConfig.path)
@@ -108,7 +108,7 @@ export class LegacyService implements CoreService {
this.kbnServer.applyLoggingConfiguration(getLegacyRawConfig(config, pathConfig));
}
}),
- tap({ error: err => this.log.error(err) }),
+ tap({ error: (err) => this.log.error(err) }),
publishReplay(1)
) as ConnectableObservable<[Config, PathConfigType]>;
@@ -146,14 +146,14 @@ export class LegacyService implements CoreService {
};
const deprecationProviders = await pluginSpecs
- .map(spec => spec.getDeprecationsProvider())
+ .map((spec) => spec.getDeprecationsProvider())
.reduce(async (providers, current) => {
if (current) {
return [...(await providers), await convertLegacyDeprecationProvider(current)];
}
return providers;
}, Promise.resolve([] as ConfigDeprecationProvider[]));
- deprecationProviders.forEach(provider =>
+ deprecationProviders.forEach((provider) =>
this.coreContext.configService.addDeprecationProvider('', provider)
);
diff --git a/src/core/server/legacy/merge_vars.ts b/src/core/server/legacy/merge_vars.ts
index a1d43af2f861d..5d1820988e57a 100644
--- a/src/core/server/legacy/merge_vars.ts
+++ b/src/core/server/legacy/merge_vars.ts
@@ -25,9 +25,9 @@ export function mergeVars(...sources: LegacyVars[]): LegacyVars {
return Object.assign(
{},
...sources,
- ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap(key =>
- sources.some(source => key in source)
- ? [{ [key]: Object.assign({}, ...sources.map(source => source[key] || {})) }]
+ ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap((key) =>
+ sources.some((source) => key in source)
+ ? [{ [key]: Object.assign({}, ...sources.map((source) => source[key] || {})) }]
: []
)
);
diff --git a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts
index 44f02f0c90d4e..5039b3a55cc58 100644
--- a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts
+++ b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts
@@ -63,14 +63,14 @@ export async function findLegacyPluginSpecs(
const log$ = merge(
pack$.pipe(
- tap(definition => {
+ tap((definition) => {
const path = definition.getPath();
logger.debug(`Found plugin at ${path}`, { path });
})
),
invalidDirectoryError$.pipe(
- tap(error => {
+ tap((error) => {
logger.warn(`Unable to scan directory for plugins "${error.path}"`, {
err: error,
dir: error.path,
@@ -79,7 +79,7 @@ export async function findLegacyPluginSpecs(
),
invalidPackError$.pipe(
- tap(error => {
+ tap((error) => {
logger.warn(`Skipping non-plugin directory at ${error.path}`, {
path: error.path,
});
@@ -87,21 +87,21 @@ export async function findLegacyPluginSpecs(
),
otherError$.pipe(
- tap(error => {
+ tap((error) => {
// rethrow unhandled errors, which will fail the server
throw error;
})
),
invalidVersionSpec$.pipe(
- map(spec => {
+ map((spec) => {
const name = spec.getId();
const pluginVersion = spec.getExpectedKibanaVersion();
const kibanaVersion = packageInfo.version;
return `Plugin "${name}" was disabled because it expected Kibana version "${pluginVersion}", and found "${kibanaVersion}".`;
}),
distinct(),
- tap(message => {
+ tap((message) => {
logger.warn(message);
})
),
diff --git a/src/core/server/legacy/plugins/get_nav_links.test.ts b/src/core/server/legacy/plugins/get_nav_links.test.ts
index 5e84f27acabd5..af10706d0ea08 100644
--- a/src/core/server/legacy/plugins/get_nav_links.test.ts
+++ b/src/core/server/legacy/plugins/get_nav_links.test.ts
@@ -40,7 +40,7 @@ const createLegacyExports = ({
const createPluginSpecs = (...ids: string[]): LegacyPluginSpec[] =>
ids.map(
- id =>
+ (id) =>
({
getId: () => id,
} as LegacyPluginSpec)
diff --git a/src/core/server/legacy/plugins/get_nav_links.ts b/src/core/server/legacy/plugins/get_nav_links.ts
index 067fb204ca7f3..b1d22df41e345 100644
--- a/src/core/server/legacy/plugins/get_nav_links.ts
+++ b/src/core/server/legacy/plugins/get_nav_links.ts
@@ -66,11 +66,11 @@ function isHidden(app: LegacyAppSpec) {
export function getNavLinks(uiExports: LegacyUiExports, pluginSpecs: LegacyPluginSpec[]) {
const navLinkSpecs = uiExports.navLinkSpecs || [];
const appSpecs = (uiExports.uiAppSpecs || []).filter(
- app => app !== undefined && !isHidden(app)
+ (app) => app !== undefined && !isHidden(app)
) as LegacyAppSpec[];
- const pluginIds = (pluginSpecs || []).map(spec => spec.getId());
- appSpecs.forEach(spec => {
+ const pluginIds = (pluginSpecs || []).map((spec) => spec.getId());
+ appSpecs.forEach((spec) => {
if (spec.pluginId && !pluginIds.includes(spec.pluginId)) {
throw new Error(`Unknown plugin id "${spec.pluginId}"`);
}
diff --git a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts
index df86f5a2b4031..4a4a1b1b0e60b 100644
--- a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts
+++ b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts
@@ -36,7 +36,7 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({
}) => {
const thirdPartySpecs = specs.filter(isThirdPartyPluginSpec);
if (thirdPartySpecs.length > 0) {
- const pluginIds = thirdPartySpecs.map(spec => spec.getId());
+ const pluginIds = thirdPartySpecs.map((spec) => spec.getId());
log.warn(
`Some installed third party plugin(s) [${pluginIds.join(
', '
@@ -49,5 +49,5 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({
const isThirdPartyPluginSpec = (spec: LegacyPluginSpec): boolean => {
const pluginPath = spec.getPack().getPath();
- return !internalPaths.some(internalPath => pluginPath.indexOf(internalPath) > -1);
+ return !internalPaths.some((internalPath) => pluginPath.indexOf(internalPath) > -1);
};
diff --git a/src/core/server/logging/appenders/file/file_appender.test.ts b/src/core/server/logging/appenders/file/file_appender.test.ts
index 0483a06b199b6..bff60029faf11 100644
--- a/src/core/server/logging/appenders/file/file_appender.test.ts
+++ b/src/core/server/logging/appenders/file/file_appender.test.ts
@@ -23,7 +23,7 @@ import { LogLevel } from '../../log_level';
import { LogRecord } from '../../log_record';
import { FileAppender } from './file_appender';
-const tickMs = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+const tickMs = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
beforeEach(() => {
mockCreateWriteStream.mockReset();
diff --git a/src/core/server/logging/appenders/file/file_appender.ts b/src/core/server/logging/appenders/file/file_appender.ts
index 3aca59fb3f42c..728e82ebcec9a 100644
--- a/src/core/server/logging/appenders/file/file_appender.ts
+++ b/src/core/server/logging/appenders/file/file_appender.ts
@@ -66,7 +66,7 @@ export class FileAppender implements DisposableAppender {
* Disposes `FileAppender`. Waits for the underlying file stream to be completely flushed and closed.
*/
public async dispose() {
- await new Promise(resolve => {
+ await new Promise((resolve) => {
if (this.outputStream === undefined) {
return resolve();
}
diff --git a/src/core/server/logging/integration_tests/utils.ts b/src/core/server/logging/integration_tests/utils.ts
index 81a76ce76ad73..e4c2c8866cb92 100644
--- a/src/core/server/logging/integration_tests/utils.ts
+++ b/src/core/server/logging/integration_tests/utils.ts
@@ -55,7 +55,7 @@ export async function getPlatformLogsFromFile(path: string) {
const fileContent = await readFile(path, 'utf-8');
return fileContent
.split('\n')
- .map(s => normalizePlatformLogging(s))
+ .map((s) => normalizePlatformLogging(s))
.join('\n');
}
@@ -63,6 +63,6 @@ export async function getLegacyPlatformLogsFromFile(path: string) {
const fileContent = await readFile(path, 'utf-8');
return fileContent
.split('\n')
- .map(s => normalizeLegacyPlatformLogging(s))
+ .map((s) => normalizeLegacyPlatformLogging(s))
.join('\n');
}
diff --git a/src/core/server/logging/layouts/pattern_layout.ts b/src/core/server/logging/layouts/pattern_layout.ts
index 9490db149cc0f..7839345a3703b 100644
--- a/src/core/server/logging/layouts/pattern_layout.ts
+++ b/src/core/server/logging/layouts/pattern_layout.ts
@@ -37,7 +37,7 @@ import {
const DEFAULT_PATTERN = `[%date][%level][%logger]%meta %message`;
export const patternSchema = schema.string({
- validate: string => {
+ validate: (string) => {
DateConversion.validate!(string);
},
});
diff --git a/src/core/server/logging/logging_config.ts b/src/core/server/logging/logging_config.ts
index 8f80be7d79cb1..772909ce584e5 100644
--- a/src/core/server/logging/logging_config.ts
+++ b/src/core/server/logging/logging_config.ts
@@ -167,13 +167,13 @@ export class LoggingConfig {
];
const loggerConfigByContext = new Map(
- loggers.map(loggerConfig => toTuple(loggerConfig.context, loggerConfig))
+ loggers.map((loggerConfig) => toTuple(loggerConfig.context, loggerConfig))
);
for (const [loggerContext, loggerConfig] of loggerConfigByContext) {
// Ensure logger config only contains valid appenders.
const unsupportedAppenderKey = loggerConfig.appenders.find(
- appenderKey => !this.appenders.has(appenderKey)
+ (appenderKey) => !this.appenders.has(appenderKey)
);
if (unsupportedAppenderKey) {
diff --git a/src/core/server/logging/logging_service.ts b/src/core/server/logging/logging_service.ts
index f9535e6c8283e..2e6f895724122 100644
--- a/src/core/server/logging/logging_service.ts
+++ b/src/core/server/logging/logging_service.ts
@@ -108,7 +108,7 @@ export class LoggingService implements LoggerFactory {
const { level, appenders } = this.getLoggerConfigByContext(config, context);
const loggerLevel = LogLevel.fromId(level);
- const loggerAppenders = appenders.map(appenderKey => this.appenders.get(appenderKey)!);
+ const loggerAppenders = appenders.map((appenderKey) => this.appenders.get(appenderKey)!);
return new BaseLogger(context, loggerLevel, loggerAppenders, this.asLoggerFactory());
}
diff --git a/src/core/server/metrics/collectors/process.ts b/src/core/server/metrics/collectors/process.ts
index a3b59a7cc8b7c..b020eebcbbd0b 100644
--- a/src/core/server/metrics/collectors/process.ts
+++ b/src/core/server/metrics/collectors/process.ts
@@ -46,7 +46,7 @@ export class ProcessMetricsCollector implements MetricsCollector => {
const bench = new Bench();
- return new Promise(resolve => {
+ return new Promise((resolve) => {
setImmediate(() => {
return resolve(bench.elapsed());
});
diff --git a/src/core/server/metrics/collectors/server.ts b/src/core/server/metrics/collectors/server.ts
index 84204d0466ff3..036332c24c34f 100644
--- a/src/core/server/metrics/collectors/server.ts
+++ b/src/core/server/metrics/collectors/server.ts
@@ -45,7 +45,7 @@ export class ServerMetricsCollector implements MetricsCollector {
+ this.server.events.on('response', (request) => {
const statusCode = (request.response as ResponseObject)?.statusCode;
if (statusCode) {
if (!this.requests.statusCodes[statusCode]) {
@@ -62,7 +62,7 @@ export class ServerMetricsCollector implements MetricsCollector {
- const connections = await new Promise(resolve => {
+ const connections = await new Promise((resolve) => {
this.server.listener.getConnections((_, count) => {
resolve(count);
});
diff --git a/src/core/server/metrics/integration_tests/server_collector.test.ts b/src/core/server/metrics/integration_tests/server_collector.test.ts
index 3b982a06cf06c..4476b3c26a2e1 100644
--- a/src/core/server/metrics/integration_tests/server_collector.test.ts
+++ b/src/core/server/metrics/integration_tests/server_collector.test.ts
@@ -34,7 +34,7 @@ describe('ServerMetricsCollector', () => {
let hapiServer: HapiServer;
let router: IRouter;
- const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const sendGet = (path: string) => supertest(hapiServer.listener).get(path);
beforeEach(async () => {
@@ -81,7 +81,7 @@ describe('ServerMetricsCollector', () => {
});
it('collect disconnects requests infos', async () => {
- const never = new Promise(resolve => undefined);
+ const never = new Promise((resolve) => undefined);
const hitSubject = new BehaviorSubject(0);
router.get({ path: '/', validate: false }, async (ctx, req, res) => {
@@ -100,7 +100,7 @@ describe('ServerMetricsCollector', () => {
await hitSubject
.pipe(
- filter(count => count >= 2),
+ filter((count) => count >= 2),
take(1)
)
.toPromise();
@@ -177,7 +177,7 @@ describe('ServerMetricsCollector', () => {
const waitForHits = (hits: number) =>
hitSubject
.pipe(
- filter(count => count >= hits),
+ filter((count) => count >= hits),
take(1)
)
.toPromise();
@@ -189,12 +189,12 @@ describe('ServerMetricsCollector', () => {
// however in this test we need to send the request now and await for it later in the code.
// also using `.end` is not possible as it would execute the request twice.
// so the only option is this noop `.then`.
- const res1 = sendGet('/').then(res => res);
+ const res1 = sendGet('/').then((res) => res);
await waitForHits(1);
metrics = await collector.collect();
expect(metrics.concurrent_connections).toEqual(1);
- const res2 = sendGet('/').then(res => res);
+ const res2 = sendGet('/').then((res) => res);
await waitForHits(2);
metrics = await collector.collect();
expect(metrics.concurrent_connections).toEqual(2);
diff --git a/src/core/server/metrics/metrics_service.test.ts b/src/core/server/metrics/metrics_service.test.ts
index f6334cc5d3c0f..01a7429745cda 100644
--- a/src/core/server/metrics/metrics_service.test.ts
+++ b/src/core/server/metrics/metrics_service.test.ts
@@ -82,10 +82,7 @@ describe('MetricsService', () => {
// however the `reset` call is executed after the async call to `collect`
// meaning that we are going to miss the call if we don't wait for the
// actual observable emission that is performed after
- const waitForNextEmission = () =>
- getOpsMetrics$()
- .pipe(take(1))
- .toPromise();
+ const waitForNextEmission = () => getOpsMetrics$().pipe(take(1)).toPromise();
expect(mockOpsCollector.collect).toHaveBeenCalledTimes(1);
expect(mockOpsCollector.reset).toHaveBeenCalledTimes(1);
diff --git a/src/core/server/path/index.ts b/src/core/server/path/index.ts
index 004aa2a279927..2e05e3856bd4c 100644
--- a/src/core/server/path/index.ts
+++ b/src/core/server/path/index.ts
@@ -37,7 +37,7 @@ const DATA_PATHS = [
].filter(isString);
function findFile(paths: string[]) {
- const availablePath = paths.find(configPath => {
+ const availablePath = paths.find((configPath) => {
try {
accessSync(configPath, constants.R_OK);
return true;
diff --git a/src/core/server/plugins/discovery/plugin_manifest_parser.ts b/src/core/server/plugins/discovery/plugin_manifest_parser.ts
index 573109c9db35a..27c3ca5a71e16 100644
--- a/src/core/server/plugins/discovery/plugin_manifest_parser.ts
+++ b/src/core/server/plugins/discovery/plugin_manifest_parser.ts
@@ -154,7 +154,9 @@ export async function parseManifest(pluginPath: string, packageInfo: PackageInfo
);
}
- const unknownManifestKeys = Object.keys(manifest).filter(key => !KNOWN_MANIFEST_FIELDS.has(key));
+ const unknownManifestKeys = Object.keys(manifest).filter(
+ (key) => !KNOWN_MANIFEST_FIELDS.has(key)
+ );
if (unknownManifestKeys.length > 0) {
throw PluginDiscoveryError.invalidManifest(
manifestPath,
diff --git a/src/core/server/plugins/discovery/plugins_discovery.test.ts b/src/core/server/plugins/discovery/plugins_discovery.test.ts
index 2902aafdbf146..73f274957cbc4 100644
--- a/src/core/server/plugins/discovery/plugins_discovery.test.ts
+++ b/src/core/server/plugins/discovery/plugins_discovery.test.ts
@@ -143,7 +143,7 @@ test('properly iterates through plugin search locations', async () => {
resolve(TEST_PLUGIN_SEARCH_PATHS.nonEmptySrcPlugins, '6'),
TEST_EXTRA_PLUGIN_PATH,
]) {
- const discoveredPlugin = plugins.find(plugin => plugin.path === path)!;
+ const discoveredPlugin = plugins.find((plugin) => plugin.path === path)!;
expect(discoveredPlugin).toBeInstanceOf(PluginWrapper);
expect(discoveredPlugin.configPath).toEqual(['core', 'config']);
expect(discoveredPlugin.requiredPlugins).toEqual(['a', 'b']);
@@ -153,7 +153,7 @@ test('properly iterates through plugin search locations', async () => {
await expect(
error$
.pipe(
- map(error => error.toString()),
+ map((error) => error.toString()),
toArray()
)
.toPromise()
diff --git a/src/core/server/plugins/discovery/plugins_discovery.ts b/src/core/server/plugins/discovery/plugins_discovery.ts
index e7f82c9dc15ad..1910483211e34 100644
--- a/src/core/server/plugins/discovery/plugins_discovery.ts
+++ b/src/core/server/plugins/discovery/plugins_discovery.ts
@@ -56,7 +56,7 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) {
from(config.additionalPluginPaths),
processPluginSearchPaths$(config.pluginSearchPaths, log)
).pipe(
- mergeMap(pluginPathOrError => {
+ mergeMap((pluginPathOrError) => {
return typeof pluginPathOrError === 'string'
? createPlugin$(pluginPathOrError, log, coreContext)
: [pluginPathOrError];
@@ -83,21 +83,21 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) {
*/
function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) {
return from(pluginDirs).pipe(
- mergeMap(dir => {
+ mergeMap((dir) => {
log.debug(`Scanning "${dir}" for plugin sub-directories...`);
return fsReadDir$(dir).pipe(
- mergeMap((subDirs: string[]) => subDirs.map(subDir => resolve(dir, subDir))),
- mergeMap(path =>
+ mergeMap((subDirs: string[]) => subDirs.map((subDir) => resolve(dir, subDir))),
+ mergeMap((path) =>
fsStat$(path).pipe(
// Filter out non-directory entries from target directories, it's expected that
// these directories may contain files (e.g. `README.md` or `package.json`).
// We shouldn't silently ignore the entries we couldn't get stat for though.
- mergeMap(pathStat => (pathStat.isDirectory() ? [path] : [])),
- catchError(err => [PluginDiscoveryError.invalidPluginPath(path, err)])
+ mergeMap((pathStat) => (pathStat.isDirectory() ? [path] : [])),
+ catchError((err) => [PluginDiscoveryError.invalidPluginPath(path, err)])
)
),
- catchError(err => [PluginDiscoveryError.invalidSearchPath(dir, err)])
+ catchError((err) => [PluginDiscoveryError.invalidSearchPath(dir, err)])
);
})
);
@@ -113,7 +113,7 @@ function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) {
*/
function createPlugin$(path: string, log: Logger, coreContext: CoreContext) {
return from(parseManifest(path, coreContext.env.packageInfo, log)).pipe(
- map(manifest => {
+ map((manifest) => {
log.debug(`Successfully discovered plugin "${manifest.id}" at "${path}"`);
const opaqueId = Symbol(manifest.id);
return new PluginWrapper({
@@ -123,6 +123,6 @@ function createPlugin$(path: string, log: Logger, coreContext: CoreContext) {
initializerContext: createPluginInitializerContext(coreContext, opaqueId, manifest),
});
}),
- catchError(err => [err])
+ catchError((err) => [err])
);
}
diff --git a/src/core/server/plugins/integration_tests/plugins_service.test.ts b/src/core/server/plugins/integration_tests/plugins_service.test.ts
index 1521fc332bcdb..04f570cca489b 100644
--- a/src/core/server/plugins/integration_tests/plugins_service.test.ts
+++ b/src/core/server/plugins/integration_tests/plugins_service.test.ts
@@ -139,7 +139,7 @@ describe('PluginsService', () => {
},
start: async (core, plugins) => {
contextFromStart = { core, plugins };
- await new Promise(resolve => setTimeout(resolve, 10));
+ await new Promise((resolve) => setTimeout(resolve, 10));
expect(startDependenciesResolved).toBe(false);
return pluginStartContract;
},
diff --git a/src/core/server/plugins/plugin.test.ts b/src/core/server/plugins/plugin.test.ts
index 1e4d94dd00d0d..8d82d96f949c7 100644
--- a/src/core/server/plugins/plugin.test.ts
+++ b/src/core/server/plugins/plugin.test.ts
@@ -260,7 +260,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async
setup: jest.fn(),
start: async () => {
// delay to ensure startDependencies is not resolved until after the plugin instance's start resolves.
- await new Promise(resolve => setTimeout(resolve, 10));
+ await new Promise((resolve) => setTimeout(resolve, 10));
expect(startDependenciesResolved).toBe(false);
return pluginStartContract;
},
@@ -269,7 +269,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async
await plugin.setup({} as any, {} as any);
- const startDependenciesCheck = plugin.startDependencies.then(resolvedStartDeps => {
+ const startDependenciesCheck = plugin.startDependencies.then((resolvedStartDeps) => {
startDependenciesResolved = true;
expect(resolvedStartDeps).toEqual([startContext, pluginDeps, pluginStartContract]);
});
diff --git a/src/core/server/plugins/plugins_service.test.ts b/src/core/server/plugins/plugins_service.test.ts
index 38fda12bd290f..6f8d15838641f 100644
--- a/src/core/server/plugins/plugins_service.test.ts
+++ b/src/core/server/plugins/plugins_service.test.ts
@@ -51,7 +51,7 @@ const logger = loggingServiceMock.create();
expect.addSnapshotSerializer(createAbsolutePathSerializer());
-['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach(path => {
+['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach((path) => {
jest.doMock(join(path, 'server'), () => ({}), {
virtual: true,
});
@@ -200,7 +200,7 @@ describe('PluginsService', () => {
it('properly detects plugins that should be disabled.', async () => {
jest
.spyOn(configService, 'isEnabledAtPath')
- .mockImplementation(path => Promise.resolve(!path.includes('disabled')));
+ .mockImplementation((path) => Promise.resolve(!path.includes('disabled')));
mockPluginSystem.setupPlugins.mockResolvedValue(new Map());
diff --git a/src/core/server/plugins/plugins_service.ts b/src/core/server/plugins/plugins_service.ts
index d7a348affe94f..7441e753efa6a 100644
--- a/src/core/server/plugins/plugins_service.ts
+++ b/src/core/server/plugins/plugins_service.ts
@@ -87,7 +87,7 @@ export class PluginsService implements CoreService('plugins')
- .pipe(map(rawConfig => new PluginsConfig(rawConfig, coreContext.env)));
+ .pipe(map((rawConfig) => new PluginsConfig(rawConfig, coreContext.env)));
}
public async discover() {
@@ -153,7 +153,7 @@ export class PluginsService implements CoreService exposed)
+ Object.values(configDescriptor?.exposeToBrowser).some((exposed) => exposed)
);
})
.map(([pluginId, plugin]) => {
@@ -186,14 +186,14 @@ export class PluginsService implements CoreService errorTypesToReport.includes(error.type)),
- tap(pluginError => this.log.error(pluginError)),
+ filter((error) => errorTypesToReport.includes(error.type)),
+ tap((pluginError) => this.log.error(pluginError)),
toArray()
)
.toPromise();
if (errors.length > 0) {
throw new Error(
- `Failed to initialize plugins:${errors.map(err => `\n\t${err.message}`).join('')}`
+ `Failed to initialize plugins:${errors.map((err) => `\n\t${err.message}`).join('')}`
);
}
}
@@ -205,7 +205,7 @@ export class PluginsService implements CoreService();
await plugin$
.pipe(
- mergeMap(async plugin => {
+ mergeMap(async (plugin) => {
const configDescriptor = plugin.getConfigDescriptor();
if (configDescriptor) {
this.pluginConfigDescriptors.set(plugin.name, configDescriptor);
@@ -263,8 +263,8 @@ export class PluginsService implements CoreService !parents.includes(dep))
- .every(dependencyName =>
+ .filter((dep) => !parents.includes(dep))
+ .every((dependencyName) =>
this.shouldEnablePlugin(dependencyName, pluginEnableStatuses, [...parents, pluginName])
)
);
diff --git a/src/core/server/plugins/plugins_system.test.ts b/src/core/server/plugins/plugins_system.test.ts
index 22dfbeecbaedd..8b318ad1b735e 100644
--- a/src/core/server/plugins/plugins_system.test.ts
+++ b/src/core/server/plugins/plugins_system.test.ts
@@ -342,7 +342,7 @@ test('`uiPlugins` returns ordered Maps of all plugin manifests', async () => {
],
] as Array<[PluginWrapper, Record]>);
- [...plugins.keys()].forEach(plugin => {
+ [...plugins.keys()].forEach((plugin) => {
pluginsSystem.addPlugin(plugin);
});
@@ -371,7 +371,7 @@ test('`uiPlugins` returns only ui plugin dependencies', async () => {
createPlugin('opt-no-ui', { ui: false, server: true }),
];
- plugins.forEach(plugin => {
+ plugins.forEach((plugin) => {
pluginsSystem.addPlugin(plugin);
});
@@ -424,7 +424,7 @@ describe('setup', () => {
});
it('throws timeout error if "setup" was not completed in 30 sec.', async () => {
const plugin: PluginWrapper = createPlugin('timeout-setup');
- jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise(i => i));
+ jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise((i) => i));
pluginsSystem.addPlugin(plugin);
mockCreatePluginSetupContext.mockImplementation(() => ({}));
@@ -447,7 +447,7 @@ describe('start', () => {
it('throws timeout error if "start" was not completed in 30 sec.', async () => {
const plugin: PluginWrapper = createPlugin('timeout-start');
jest.spyOn(plugin, 'setup').mockResolvedValue({});
- jest.spyOn(plugin, 'start').mockImplementation(() => new Promise(i => i));
+ jest.spyOn(plugin, 'start').mockImplementation(() => new Promise((i) => i));
pluginsSystem.addPlugin(plugin);
mockCreatePluginSetupContext.mockImplementation(() => ({}));
diff --git a/src/core/server/plugins/plugins_system.ts b/src/core/server/plugins/plugins_system.ts
index dd2df7c8e01d1..e0401006ffac9 100644
--- a/src/core/server/plugins/plugins_system.ts
+++ b/src/core/server/plugins/plugins_system.ts
@@ -53,9 +53,9 @@ export class PluginsSystem {
[
...new Set([
...plugin.requiredPlugins,
- ...plugin.optionalPlugins.filter(optPlugin => this.plugins.has(optPlugin)),
+ ...plugin.optionalPlugins.filter((optPlugin) => this.plugins.has(optPlugin)),
]),
- ].map(depId => this.plugins.get(depId)!.opaqueId),
+ ].map((depId) => this.plugins.get(depId)!.opaqueId),
])
);
}
@@ -161,18 +161,22 @@ export class PluginsSystem {
*/
public uiPlugins() {
const uiPluginNames = [...this.getTopologicallySortedPluginNames().keys()].filter(
- pluginName => this.plugins.get(pluginName)!.includesUiPlugin
+ (pluginName) => this.plugins.get(pluginName)!.includesUiPlugin
);
const publicPlugins = new Map(
- uiPluginNames.map(pluginName => {
+ uiPluginNames.map((pluginName) => {
const plugin = this.plugins.get(pluginName)!;
return [
pluginName,
{
id: pluginName,
configPath: plugin.manifest.configPath,
- requiredPlugins: plugin.manifest.requiredPlugins.filter(p => uiPluginNames.includes(p)),
- optionalPlugins: plugin.manifest.optionalPlugins.filter(p => uiPluginNames.includes(p)),
+ requiredPlugins: plugin.manifest.requiredPlugins.filter((p) =>
+ uiPluginNames.includes(p)
+ ),
+ optionalPlugins: plugin.manifest.optionalPlugins.filter((p) =>
+ uiPluginNames.includes(p)
+ ),
},
];
})
@@ -200,7 +204,7 @@ export class PluginsSystem {
pluginName,
new Set([
...plugin.requiredPlugins,
- ...plugin.optionalPlugins.filter(dependency => this.plugins.has(dependency)),
+ ...plugin.optionalPlugins.filter((dependency) => this.plugins.has(dependency)),
]),
] as [PluginName, Set];
})
@@ -209,7 +213,7 @@ export class PluginsSystem {
// First, find a list of "start nodes" which have no outgoing edges. At least
// one such node must exist in a non-empty acyclic graph.
const pluginsWithAllDependenciesSorted = [...pluginsDependenciesGraph.keys()].filter(
- pluginName => pluginsDependenciesGraph.get(pluginName)!.size === 0
+ (pluginName) => pluginsDependenciesGraph.get(pluginName)!.size === 0
);
const sortedPluginNames = new Set();
diff --git a/src/core/server/rendering/views/fonts.tsx b/src/core/server/rendering/views/fonts.tsx
index e87179920202a..8e460a150439d 100644
--- a/src/core/server/rendering/views/fonts.tsx
+++ b/src/core/server/rendering/views/fonts.tsx
@@ -249,7 +249,7 @@ export const Fonts: FunctionComponent = ({ url }) => {
.flatMap(({ family, variants }) =>
variants.map(({ style, weight, format, sources, unicodeRange }) => {
const src = sources
- .map(source =>
+ .map((source) =>
source.startsWith(url)
? `url('${source}') format('${format || source.split('.').pop()}')`
: `local('${source}')`
diff --git a/src/core/server/root/index.test.ts b/src/core/server/root/index.test.ts
index 3b187aac022c3..5b853903ea4be 100644
--- a/src/core/server/root/index.test.ts
+++ b/src/core/server/root/index.test.ts
@@ -183,7 +183,7 @@ test('stops services if consequent logger upgrade fails', async () => {
// Wait for shutdown to be called.
await onShutdown
.pipe(
- filter(e => e !== null),
+ filter((e) => e !== null),
first()
)
.toPromise();
diff --git a/src/core/server/root/index.ts b/src/core/server/root/index.ts
index eecc6399366dc..d6d0c641e00b0 100644
--- a/src/core/server/root/index.ts
+++ b/src/core/server/root/index.ts
@@ -99,10 +99,10 @@ export class Root {
const update$ = configService.getConfig$().pipe(
// always read the logging config when the underlying config object is re-read
switchMap(() => configService.atPath('logging')),
- map(config => this.loggingService.upgrade(config)),
+ map((config) => this.loggingService.upgrade(config)),
// This specifically console.logs because we were not able to configure the logger.
// eslint-disable-next-line no-console
- tap({ error: err => console.error('Configuring logger failed:', err) }),
+ tap({ error: (err) => console.error('Configuring logger failed:', err) }),
publishReplay(1)
) as ConnectableObservable