[ts] set allowJs to true by default (#144281)

* [ts] set allowJs to true by default

* fix scripts/check_ts_projects, original implementation is now wildly inefficient

* produce stats in check_ts_projects to make sure it's actually working

* fix imports
This commit is contained in:
Spencer 2022-11-01 15:26:44 -07:00 committed by GitHub
parent cf7d6cc6de
commit 7d77d39e1f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
97 changed files with 419 additions and 162 deletions

View file

@ -2,7 +2,6 @@
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "target",
"allowJs": true,
"checkJs": true,
"target": "ES2022",
"module": "ESNext"

View file

@ -1,6 +1,7 @@
{
"extends": "../../tsconfig.bazel.json",
"compilerOptions": {
"allowJs": false,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./target_types",

View file

@ -3,7 +3,6 @@
"compilerOptions": {
"declaration": true,
"emitDeclarationOnly": true,
"allowJs": true,
"checkJs": true,
"outDir": "target_types",
"stripInternal": false,

View file

@ -3,7 +3,6 @@
"compilerOptions": {
"declaration": true,
"emitDeclarationOnly": true,
"allowJs": true,
"checkJs": true,
"outDir": "target_types",
"stripInternal": false,

View file

@ -1,7 +1,6 @@
{
"extends": "../../tsconfig.bazel.json",
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./target_types",

View file

@ -2,7 +2,6 @@
"extends": "../../tsconfig.bazel.json",
"compilerOptions": {
"declaration": true,
"allowJs": true,
"checkJs": true,
"outDir": "target_types",
"stripInternal": false,

View file

@ -38,7 +38,12 @@ function allTestsAreSkipped(suite) {
return childrenSkipped;
}
export function decorateMochaUi(log, lifecycle, context, { rootTags }) {
/**
* @param {import('../lifecycle').Lifecycle} lifecycle
* @param {any} context
* @param {{ rootTags?: string[] }} options
*/
export function decorateMochaUi(lifecycle, context, { rootTags }) {
// incremented at the start of each suite, decremented after
// so that in each non-suite call we can know if we are within
// a suite, or that when a suite is defined it is within a suite

View file

@ -17,7 +17,6 @@ import type { ProviderCollection } from '../providers';
import { loadTracer } from '../load_tracer';
import { decorateSnapshotUi } from '../snapshots/decorate_snapshot_ui';
// @ts-expect-error not js yet
import { decorateMochaUi } from './decorate_mocha_ui';
type TestProvider = (ctx: GenericFtrProviderContext<any, any>) => void;
@ -48,9 +47,6 @@ export const loadTests = ({
updateBaselines,
updateSnapshots,
}: Options) => {
const dockerServers = config.get('dockerServers');
const isDockerGroup = dockerServers && Object.keys(dockerServers).length;
const ctx: GenericFtrProviderContext<any, any> = {
loadTestFile,
getService: providers.getService as any,
@ -80,8 +76,7 @@ export const loadTests = ({
function withMocha(debugPath: string, fn: () => void) {
// mocha.suite hocus-pocus comes from: https://git.io/vDnXO
const context = decorateMochaUi(log, lifecycle, global, {
isDockerGroup,
const context = decorateMochaUi(lifecycle, global, {
rootTags: config.get('rootTags'),
});
mocha.suite.emit('pre-require', context, debugPath, mocha);

View file

@ -19,9 +19,7 @@ import { Config } from '../config';
import { ProviderCollection } from '../providers';
import { EsVersion } from '../es_version';
// @ts-expect-error not ts yet
import { MochaReporterProvider } from './reporter';
// @ts-expect-error not ts yet
import { validateCiGroupTags } from './validate_ci_group_tags';
interface Options {

View file

@ -11,7 +11,6 @@ import Path from 'path';
import minimatch from 'minimatch';
import { getRepoFiles } from '@kbn/get-repo-files';
// @ts-expect-error jest-preset is necessarily a JS file
import { testMatch } from '../../../jest-preset';
const UNIT_CONFIG_NAME = 'jest.config.js';

View file

@ -9,7 +9,7 @@
import url from 'url';
import { kibanaTestUser } from './users';
interface UrlParts {
export interface UrlParts {
protocol?: string;
hostname?: string;
port?: number;

View file

@ -1,7 +1,6 @@
{
"extends": "../../tsconfig.bazel.json",
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./target_types",

View file

@ -1,7 +1,6 @@
{
"extends": "../../tsconfig.bazel.json",
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "./target_types",

View file

@ -9,7 +9,7 @@
import { existsSync } from 'fs';
import { join } from 'path';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../logger';
import { getConfigDirectory, getDataPath } from '@kbn/utils';
export function getKeystore() {

View file

@ -7,7 +7,7 @@
*/
import { getKeystore } from './get_keystore';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../logger';
import fs from 'fs';
import sinon from 'sinon';

View file

@ -9,7 +9,7 @@
import { set } from '@kbn/safer-lodash-set';
import { Keystore } from '.';
import { getKeystore } from '../../cli_keystore/get_keystore';
import { getKeystore } from './get_keystore';
export function readKeystore(keystorePath = getKeystore()) {
const keystore = new Keystore(keystorePath);

View file

@ -10,13 +10,20 @@
* Logs messages and errors
*/
export class Logger {
/**
* @param {{silent?: boolean; quiet?: boolean;}} settings
*/
constructor(settings = {}) {
this.previousLineEnded = true;
this.silent = !!settings.silent;
this.quiet = !!settings.quiet;
}
log(data, sameLine) {
/**
* @param {string} data
* @param {boolean} sameLine
*/
log(data, sameLine = false) {
if (this.silent || this.quiet) return;
if (!sameLine && !this.previousLineEnded) {
@ -34,6 +41,9 @@ export class Logger {
this.previousLineEnded = !sameLine;
}
/**
* @param {string} data
*/
error(data) {
if (this.silent) return;

17
src/cli/tsconfig.json Normal file
View file

@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true
},
"include": [
"keystore/**/*",
"serve/**/*",
"*.js",
],
"kbn_references": [
{ "path": "../core/tsconfig.json" },
{ "path": "../setup_node_env/tsconfig.json" },
]
}

View file

@ -9,7 +9,7 @@
import { safeDump } from 'js-yaml';
import { isEmpty } from 'lodash';
import { interactive } from './interactive';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
export async function generate(encryptionConfig, command) {
const logger = new Logger();

View file

@ -9,7 +9,7 @@
import { EncryptionConfig } from './encryption_config';
import { generate } from './generate';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
describe('encryption key generation', () => {
const encryptionConfig = new EncryptionConfig();

View file

@ -9,7 +9,7 @@
import { EncryptionConfig } from './encryption_config';
import { generate } from './generate';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
import * as prompt from '../cli_keystore/utils/prompt';
import fs from 'fs';
import crypto from 'crypto';

View file

@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"*.js",
],
"kbn_references": [
{ "path": "../cli/tsconfig.json" },
{ "path": "../cli_keystore/tsconfig.json" },
]
}

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
import { confirm, question } from './utils';
// import from path since add.test.js mocks 'fs' required for @kbn/utils
import { createPromiseFromStreams, createConcatStream } from '@kbn/utils/target_node/src/streams';

View file

@ -30,7 +30,7 @@ import { PassThrough } from 'stream';
import { Keystore } from '../cli/keystore';
import { add } from './add';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
import * as prompt from './utils/prompt';
describe('Kibana keystore', () => {

View file

@ -10,13 +10,13 @@ import _ from 'lodash';
import { kibanaPackageJson as pkg } from '@kbn/utils';
import Command from '../cli/command';
import { getKeystore } from '../cli/keystore/get_keystore';
import { Keystore } from '../cli/keystore';
import { createCli } from './create';
import { listCli } from './list';
import { addCli } from './add';
import { removeCli } from './remove';
import { getKeystore } from './get_keystore';
const argv = process.argv.slice();
const program = new Command('bin/kibana-keystore');

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
import { confirm } from './utils';
export async function create(keystore, command, options) {

View file

@ -29,7 +29,7 @@ import sinon from 'sinon';
import { Keystore } from '../cli/keystore';
import { create } from './create';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
import * as prompt from './utils/prompt';
describe('Kibana keystore', () => {

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
export function list(keystore, command, options = {}) {
const logger = new Logger(options);

View file

@ -27,7 +27,7 @@ jest.mock('fs', () => ({
import sinon from 'sinon';
import { Keystore } from '../cli/keystore';
import { list } from './list';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
describe('Kibana keystore', () => {
describe('list', () => {

View file

@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"keystore/**/*",
"utils/**/*",
"*.js",
],
"kbn_references": [
{ "path": "../setup_node_env/tsconfig.json" },
{ "path": "../cli/tsconfig.json" },
{ "path": "../cli_plugin/tsconfig.json" },
]
}

View file

@ -11,7 +11,7 @@ import fs from 'fs';
import del from 'del';
import { cleanPrevious, cleanArtifacts } from './cleanup';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
describe('kibana cli', function () {
describe('plugin installer', function () {

View file

@ -15,7 +15,7 @@ import nock from 'nock';
import globby from 'globby';
import del from 'del';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { UnsupportedProtocolError } from '../lib/errors';
import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } from './download';

View file

@ -8,7 +8,7 @@
import { getConfigPath, kibanaPackageJson as pkg } from '@kbn/utils';
import { install } from './install';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { parse, parseMilliseconds } from './settings';
import { logWarnings } from '../lib/log_warnings';

View file

@ -13,7 +13,7 @@ import sinon from 'sinon';
import del from 'del';
import { existingInstall, assertVersion } from './kibana';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
jest.spyOn(fs, 'statSync');

View file

@ -13,7 +13,7 @@ import sinon from 'sinon';
import globby from 'globby';
import del from 'del';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { extract, getPackData } from './pack';
import { _downloadSingle } from './download';

View file

@ -9,7 +9,7 @@
import sinon from 'sinon';
import { Progress } from './progress';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
describe('kibana cli', function () {
describe('plugin installer', function () {

View file

@ -1,20 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
interface LoggerOptions {
silent?: boolean;
quiet?: boolean;
}
export declare class Logger {
constructor(settings?: LoggerOptions);
log(data: string, sameLine?: boolean): void;
error(data: string): void;
}

View file

@ -8,7 +8,7 @@
import { fromRoot } from '@kbn/utils';
import { list } from './list';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { logWarnings } from '../lib/log_warnings';
function processCommand() {

View file

@ -8,7 +8,7 @@
import { getConfigPath } from '@kbn/utils';
import { remove } from './remove';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { parse } from './settings';
import { logWarnings } from '../lib/log_warnings';

View file

@ -13,7 +13,7 @@ import sinon from 'sinon';
import globby from 'globby';
import del from 'del';
import { Logger } from '../lib/logger';
import { Logger } from '../../cli/logger';
import { remove } from './remove';
describe('kibana cli', function () {

View file

@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"install/**/*",
"lib/**/*",
"list/**/*",
"remove/**/*",
"*.js",
],
"kbn_references": [
{ "path": "../cli/tsconfig.json" },
]
}

View file

@ -24,7 +24,7 @@ import {
kibanaConfigWriter,
elasticsearch,
} from './utils';
import { Logger } from '../cli_plugin/lib/logger';
import { Logger } from '../cli/logger';
const program = new Command('bin/kibana-setup');

View file

@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"*.js",
"*.ts"
],
"kbn_references": [
{ "path": "../cli/tsconfig.json" },
{ "path": "../plugins/interactive_setup/tsconfig.json" },
]
}

View file

@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"*.js",
],
"kbn_references": [
{ "path": "../cli/tsconfig.json" },
]
}

View file

@ -9,7 +9,7 @@
import { dirname, extname, join, relative, resolve, sep, basename } from 'path';
export class File {
private path: string;
public readonly path: string;
private relativePath: string;
private ext: string;

20
src/dev/tsconfig.json Normal file
View file

@ -0,0 +1,20 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"**/*.js",
"**/*.ts",
],
"exclude": [
"target/types/**/*"
],
"kbn_references": [
{ "path": "../core/tsconfig.json" },
{ "path": "../../tsconfig.json" },
{ "path": "../../x-pack/plugins/screenshotting/tsconfig.json" },
]
}

View file

@ -31,7 +31,7 @@ export const PROJECTS = [
createProject('test/tsconfig.json', { name: 'kibana/test' }),
createProject('x-pack/test/tsconfig.json', { name: 'x-pack/test' }),
createProject('x-pack/performance/tsconfig.json', { name: 'x-pack/performance' }),
createProject('src/core/tsconfig.json'),
...findProjects(['src/*/tsconfig.json']),
createProject('.buildkite/tsconfig.json', {
// this directory has additionally dependencies which scripts/type_check can't guarantee
// are present or up-to-date, and users likely won't know how to manage either, so the

View file

@ -6,59 +6,105 @@
* Side Public License, v 1.
*/
import { resolve, relative } from 'path';
import execa from 'execa';
import Path from 'path';
import { run } from '@kbn/dev-cli-runner';
import { REPO_ROOT } from '@kbn/utils';
import { asyncMapWithLimit } from '@kbn/std';
import { createFailError } from '@kbn/dev-cli-errors';
import { getRepoFiles } from '@kbn/get-repo-files';
import globby from 'globby';
import { File } from '../file';
import { PROJECTS } from './projects';
import type { Project } from './project';
class Stats {
counts = {
files: new Map<Project, number>(),
ignored: new Map<Project, number>(),
gitMatched: new Map<Project, number>(),
};
incr(proj: Project, metric: 'files' | 'ignored' | 'gitMatched', delta = 1) {
const cur = this.counts[metric].get(proj);
this.counts[metric].set(proj, (cur ?? 0) + delta);
}
}
export async function runCheckTsProjectsCli() {
run(
async ({ log }) => {
const { stdout: files } = await execa('git', ['ls-tree', '--name-only', '-r', 'HEAD'], {
cwd: REPO_ROOT,
const stats = new Stats();
let failed = false;
const pathsAndProjects = await asyncMapWithLimit(PROJECTS, 5, async (proj) => {
const paths = await globby(proj.getIncludePatterns(), {
ignore: proj.getExcludePatterns(),
cwd: proj.directory,
onlyFiles: true,
absolute: true,
});
stats.incr(proj, 'files', paths.length);
return {
proj,
paths,
};
});
const isNotInTsProject: File[] = [];
const isInMultipleTsProjects: string[] = [];
const isInMultipleTsProjects = new Map<string, Set<Project>>();
const pathsToProject = new Map<string, Project>();
for (const { proj, paths } of pathsAndProjects) {
for (const path of paths) {
if (!pathsToProject.has(path)) {
pathsToProject.set(path, proj);
continue;
}
for (const lineRaw of files.split('\n')) {
const line = lineRaw.trim();
if (path.endsWith('.d.ts')) {
stats.incr(proj, 'ignored');
continue;
}
if (!line) {
continue;
}
const file = new File(resolve(REPO_ROOT, line));
if (!file.isTypescript() || file.isFixture()) {
continue;
}
log.verbose('Checking %s', file.getAbsolutePath());
const projects = PROJECTS.filter((p) => p.isAbsolutePathSelected(file.getAbsolutePath()));
if (projects.length === 0) {
isNotInTsProject.push(file);
}
if (projects.length > 1 && !file.isTypescriptAmbient()) {
isInMultipleTsProjects.push(
` - ${file.getRelativePath()}:\n${projects
.map((p) => ` - ${relative(process.cwd(), p.tsConfigPath)}`)
.join('\n')}`
isInMultipleTsProjects.set(
path,
new Set([...(isInMultipleTsProjects.get(path) ?? []), proj])
);
}
}
if (!isNotInTsProject.length && !isInMultipleTsProjects.length) {
log.success('All ts files belong to a single ts project');
return;
if (isInMultipleTsProjects.size) {
failed = true;
const details = Array.from(isInMultipleTsProjects)
.map(
([path, projects]) =>
` - ${Path.relative(process.cwd(), path)}:\n${Array.from(projects)
.map((p) => ` - ${Path.relative(process.cwd(), p.tsConfigPath)}`)
.join('\n')}`
)
.join('\n');
log.error(
`The following files belong to multiple tsconfig.json files listed in src/dev/typescript/projects.ts\n${details}`
);
}
const isNotInTsProject: File[] = [];
for (const { abs } of await getRepoFiles()) {
const file = new File(abs);
if (!file.isTypescript() || file.isFixture()) {
continue;
}
const proj = pathsToProject.get(file.getAbsolutePath());
if (proj === undefined) {
isNotInTsProject.push(file);
} else {
stats.incr(proj, 'gitMatched');
}
}
if (isNotInTsProject.length) {
failed = true;
log.error(
`The following files do not belong to a tsconfig.json file, or that tsconfig.json file is not listed in src/dev/typescript/projects.ts\n${isNotInTsProject
.map((file) => ` - ${file.getRelativePath()}`)
@ -66,14 +112,20 @@ export async function runCheckTsProjectsCli() {
);
}
if (isInMultipleTsProjects.length) {
const details = isInMultipleTsProjects.join('\n');
log.error(
`The following files belong to multiple tsconfig.json files listed in src/dev/typescript/projects.ts\n${details}`
);
for (const [metric, counts] of Object.entries(stats.counts)) {
log.verbose('metric:', metric);
for (const [proj, count] of Array.from(counts).sort((a, b) =>
a[0].name.localeCompare(b[0].name)
)) {
log.verbose(' ', proj.name, count);
}
}
process.exit(1);
if (failed) {
throw createFailError('see above errors');
} else {
log.success('All ts files belong to a single ts project');
}
},
{
description:

View file

@ -144,6 +144,16 @@ function createTypeCheckConfigs(projects: Project[], bazelPackages: BazelPackage
export async function runTypeCheckCli() {
run(
async ({ log, flagsReader, procRunner }) => {
if (flagsReader.boolean('clean-cache')) {
await asyncForEachWithLimit(PROJECTS, 10, async (proj) => {
await Fsp.rm(Path.resolve(proj.directory, 'target/types'), {
force: true,
recursive: true,
});
});
log.warning('Deleted all typescript caches');
}
await runBazel(['build', '//packages:build_types', '--show_result=1'], {
cwd: REPO_ROOT,
logPrefix: '\x1b[94m[bazel]\x1b[39m',
@ -234,13 +244,14 @@ export async function runTypeCheckCli() {
`,
flags: {
string: ['project'],
boolean: ['cleanup'],
boolean: ['clean-cache', 'cleanup'],
default: {
cleanup: true,
},
help: `
--project [path] Path to a tsconfig.json file determines the project to check
--help Show this message
--clean-cache Delete any existing TypeScript caches before running type check
--no-cleanup Pass to avoid deleting the temporary tsconfig files written to disk
`,
},

View file

@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"telemetry_collectors/**/*",
],
"kbn_references": [
{ "path": "../core/tsconfig.json" },
{ "path": "../plugins/usage_collection/tsconfig.json" },
]
}

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": ["common/**/*", "public/**/*", "server/**/*"],
"kbn_references": [

View file

@ -5,7 +5,7 @@
"emitDeclarationOnly": true,
"declaration": true,
},
"include": ["*.ts", ".storybook/**/*", "common/**/*", "public/**/*", "server/**/*"],
"include": ["*.ts", ".storybook/**/*.ts", "common/**/*", "public/**/*", "server/**/*"],
"kbn_references": [
{ "path": "../../core/tsconfig.json" },
{ "path": "../inspector/tsconfig.json" },

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": ["common/**/*", "public/**/*", "server/**/*", "../../../typings/**/*", ".storybook/**/*"],
"kbn_references": [

View file

@ -15,7 +15,6 @@ import { ApplicationStart } from '@kbn/core/public';
import { RedirectAppLinks } from '@kbn/kibana-react-plugin/public';
import { FeatureCatalogueEntry } from '../../../services';
import { createAppNavigationHandler } from '../app_navigation_handler';
// @ts-expect-error untyped component
import { Synopsis } from '../synopsis';
import { getServices } from '../../kibana_services';

View file

@ -13,7 +13,6 @@ import { FormattedMessage } from '@kbn/i18n-react';
import { CoreStart } from '@kbn/core/public';
import { RedirectAppLinks, useKibana } from '@kbn/kibana-react-plugin/public';
import { FeatureCatalogueEntry } from '@kbn/home-plugin/public';
// @ts-expect-error untyped component
import { Synopsis } from '../synopsis';
import { METRIC_TYPE, trackUiMetric } from '../../lib/ui_metric';

View file

@ -13,7 +13,6 @@ import { FormattedMessage } from '@kbn/i18n-react';
import { CoreStart } from '@kbn/core/public';
import { RedirectAppLinks, useKibana } from '@kbn/kibana-react-plugin/public';
import { FeatureCatalogueEntry } from '@kbn/home-plugin/public';
// @ts-expect-error untyped component
import { Synopsis } from '../synopsis';
import { METRIC_TYPE, trackUiMetric } from '../../lib/ui_metric';

View file

@ -9,6 +9,7 @@
"common/**/*",
"public/**/*",
"server/**/*",
"server/timelion.json",
"*.ts"
],
"kbn_references": [

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"common/**/*",

View file

@ -11,7 +11,9 @@
"public/**/*",
"*.ts",
// have to declare *.json explicitly due to https://github.com/microsoft/TypeScript/issues/25636
"public/test_utils/vega_map_test.json"
"public/test_utils/vega_map_test.json",
"public/test_utils/vegalite_graph.json",
"public/test_utils/vega_graph.json",
],
"kbn_references": [
{ "path": "../../../core/tsconfig.json" },

View file

@ -79,7 +79,6 @@ export const createVislibVisController = (
return;
}
// @ts-expect-error
const { Vis: Vislib } = await import('./vislib/vis');
const { uiState, event: fireEvent } = handlers;

View file

@ -8,7 +8,10 @@
"include": [
"common/**/*",
"public/**/*",
"server/**/*"
"server/**/*",
"public/fixtures/dispatch_heatmap_d3.json",
"public/fixtures/dispatch_heatmap_config.json",
"public/fixtures/dispatch_heatmap_data_point.json",
],
"kbn_references": [
{ "path": "../../../core/tsconfig.json" },

View file

@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
},
"include": [
"harden/**/*",
"root/**/*",
"*.js",
],
"kbn_references": [
{ "path": "../../tsconfig.json" },
]
}

View file

@ -12,7 +12,6 @@ import { AXE_CONFIG, AXE_OPTIONS } from '@kbn/axe-config';
import { FtrService } from '../../ftr_provider_context';
import { AxeReport, printResult } from './axe_report';
// @ts-ignore JS that is run in browser as is
import { analyzeWithAxe, analyzeWithAxeWithClient } from './analyze_with_axe';
interface AxeContext {

View file

@ -552,7 +552,14 @@ class BrowserService extends FtrService {
a2: A2,
a3: A3
): Promise<T>;
public async executeAsync<T = unknown>(fn: (...args: any[]) => void, ...args: any[]): Promise<T> {
public async executeAsync<T = unknown, A1 = unknown, A2 = unknown, A3 = unknown>(
fn: string,
...args: any[]
): Promise<T>;
public async executeAsync<T = unknown>(
fn: string | ((...args: any[]) => void),
...args: any[]
): Promise<T> {
return await this.driver.executeAsyncScript<T>(
fn,
...cloneDeepWith<any>(args, (arg) => {

View file

@ -29,6 +29,7 @@
],
"kbn_references": [
{ "path": "../src/core/tsconfig.json" },
{ "path": "../src/setup_node_env/tsconfig.json" },
{ "path": "../src/plugins/telemetry_management_section/tsconfig.json" },
{ "path": "../src/plugins/advanced_settings/tsconfig.json" },
{ "path": "../src/plugins/management/tsconfig.json" },

View file

@ -1222,6 +1222,11 @@
// We have to enable this option explicitly since `esModuleInterop` doesn't enable it automatically when ES2015 or
// ESNext module format is used.
"allowSyntheticDefaultImports": true,
// Several packages use .js files to provide types without requiring transpilation. In order for TS to support this
// regardless of where the pacakge is imported, we need to enable `allowJs` globally. In specific packages we might
// want to disable parsing of JS files, in which case `allowJs` should be set to `false` locally. These packages will
// not be able to import packages which include JS code, or import packages which depend on JS code.
"allowJs": true,
// Emits __importStar and __importDefault helpers for runtime babel ecosystem compatibility.
"esModuleInterop": true,
// Resolve modules in the same way as Node.js. Aka make `require` works the

View file

@ -1,29 +1,13 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"allowJs": true,
"outDir": "target/root_types"
},
"include": [
"kibana.d.ts",
"typings/**/*",
"package.json",
"src/cli/**/*",
"src/cli_setup/**/*",
"src/cli_plugin/**/*",
"src/cli_keystore/**/*",
"src/setup_node_env/**/*",
"src/dev/**/*",
"src/fixtures/**/*",
"x-pack/tasks/**/*",
],
"exclude": [],
"kbn_references": [
{ "path": "./src/core/tsconfig.json" },
{ "path": "./src/plugins/usage_collection/tsconfig.json" },
{ "path": "./src/plugins/interactive_setup/tsconfig.json" },
{ "path": "./x-pack/plugins/reporting/tsconfig.json" },
]
}

View file

@ -9,7 +9,6 @@
],
"compilerOptions": {
"target": "es2015",
"allowJs": true,
"outDir": "target/types",
"types": [
"cypress",

View file

@ -19,7 +19,6 @@ import { useApmParams } from '../../../hooks/use_apm_params';
import { useApmDataView } from '../../../hooks/use_apm_data_view';
import { fromQuery, toQuery } from '../links/url_helpers';
import { getBoolFilter } from './get_bool_filter';
// @ts-expect-error
import { Typeahead } from './typeahead';
import { useProcessorEvent } from './use_processor_event';

View file

@ -21,7 +21,6 @@ import {
import Path from 'path';
import { execSync } from 'child_process';
import { argv } from 'yargs';
// @ts-expect-error
import { optimizeTsConfig } from '../optimize_tsconfig/optimize';
// This script adds explicit return types to route handlers,

View file

@ -6,7 +6,6 @@
*/
import moment from 'moment';
// @ts-expect-error
import { calculateAuto } from './calculate_auto';
export function getBucketSize({
@ -22,7 +21,7 @@ export function getBucketSize({
}) {
const duration = moment.duration(end - start, 'ms');
const bucketSize = Math.max(
calculateAuto.near(numBuckets, duration).asSeconds(),
calculateAuto.near(numBuckets, duration)?.asSeconds() ?? 0,
minBucketSize || 1
);

View file

@ -12,9 +12,10 @@
"scripts/**/*",
"server/**/*",
"typings/**/*",
"jest.config.js",
// have to declare *.json explicitly due to https://github.com/microsoft/TypeScript/issues/25636
"public/**/*.json",
"server/**/*.json"
"server/**/*.json",
],
"kbn_references": [
{ "path": "../../../src/core/tsconfig.json" },

View file

@ -6,7 +6,12 @@
"declaration": true,
// the plugin contains some heavy json files
"resolveJsonModule": false
"resolveJsonModule": false,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"../../../typings/**/*",
@ -22,6 +27,7 @@
"types/**/*"
],
"kbn_references": [
{ "path": "../../../src/setup_node_env/tsconfig.json" },
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../src/plugins/bfetch/tsconfig.json" },
{ "path": "../../../src/plugins/charts/tsconfig.json" },

View file

@ -12,6 +12,9 @@
"server/**/*",
"../../../typings/**/*"
],
"exclude": [
"server/assets/*.js",
],
"kbn_references": [
{ "path": "../../../../src/core/tsconfig.json" },
{ "path": "../../cloud/tsconfig.json" },

View file

@ -14,7 +14,6 @@ import { CreateDocsResponse, ImportResults } from '../types';
import { callImportRoute, Importer, IMPORT_RETRIES, MAX_CHUNK_CHAR_COUNT } from '../importer';
import { MB } from '../../../common/constants';
import type { ImportDoc, ImportFailure, ImportResponse } from '../../../common/types';
// @ts-expect-error
import { geoJsonCleanAndValidate } from './geojson_clean_and_validate';
import { createChunks } from './create_chunks';

View file

@ -7,7 +7,6 @@
import { Feature } from 'geojson';
import { i18n } from '@kbn/i18n';
// @ts-expect-error
import { JSONLoader, loadInBatches } from '../loaders';
import type { ImportFailure } from '../../../../common/types';
import { AbstractGeoFileImporter } from '../abstract_geo_file_importer';
@ -36,12 +35,13 @@ export class GeoJsonImporter extends AbstractGeoFileImporter {
};
if (this._iterator === undefined) {
this._iterator = await loadInBatches(this._getFile(), JSONLoader, {
// TODO: loadInBatches returns an AsyncIterable, not an AsyncInterator, which doesn't necessarily have a .next() function
this._iterator = (await loadInBatches(this._getFile(), JSONLoader, {
json: {
jsonpaths: ['$.features'],
_rootObjectBatches: true,
},
});
})) as any;
}
if (!this._getIsActive() || !this._iterator) {

View file

@ -7,7 +7,6 @@
import React from 'react';
import { Feature } from 'geojson';
// @ts-expect-error
import { BrowserFileSystem, DBFLoader, loadInBatches, ShapefileLoader } from '../loaders';
import type { ImportFailure } from '../../../../common/types';
import { ShapefileEditor } from './shapefile_editor';

View file

@ -8,7 +8,6 @@
"target/**/*"
],
"compilerOptions": {
"allowJs": true,
"outDir": "target/types",
"types": [
"cypress",

View file

@ -1,7 +1,6 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"allowJs": true,
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
@ -21,7 +20,7 @@
],
"kbn_references": [
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../tsconfig.json" },
{ "path": "../../../src/setup_node_env/tsconfig.json" },
// add references to other TypeScript projects the plugin depends on
// requiredPlugins from ./kibana.json

View file

@ -5,6 +5,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"*.ts",

View file

@ -5,12 +5,14 @@
* 2.0.
*/
/** @type {[number, Record<string, string>, string]} */
export const UPLOAD_LICENSE_EXPIRED = [
200,
{ 'Content-Type': 'application/json' },
'{"acknowledged": "true", "license_status": "expired"}',
];
/** @type {[number, Record<string, string>, string]} */
export const UPLOAD_LICENSE_REQUIRES_ACK = [
200,
{ 'Content-Type': 'application/json' },
@ -25,18 +27,21 @@ export const UPLOAD_LICENSE_REQUIRES_ACK = [
}`,
];
/** @type {[number, Record<string, string>, string]} */
export const UPLOAD_LICENSE_SUCCESS = [
200,
{ 'Content-Type': 'application/json' },
'{"acknowledged": "true", "license_status": "valid"}',
];
/** @type {[number, Record<string, string>, string]} */
export const UPLOAD_LICENSE_INVALID = [
200,
{ 'Content-Type': 'application/json' },
'{"acknowledged": "true", "license_status": "invalid"}',
];
/** @type {[number, Record<string, string>, string]} */
export const UPLOAD_LICENSE_TLS_NOT_ENABLED = [
200,
{ 'Content-Type': 'application/json' },

View file

@ -11,13 +11,10 @@ import { LocationDescriptorObject } from 'history';
import { httpServiceMock, scopedHistoryMock } from '@kbn/core/public/mocks';
import { mountWithIntl } from '@kbn/test-jest-helpers';
// @ts-ignore
import { uploadLicense } from '../public/application/store/actions/upload_license';
// @ts-ignore
import { licenseManagementStore } from '../public/application/store/store';
// @ts-ignore
import { UploadLicense } from '../public/application/sections/upload_license';
import { AppContextProvider } from '../public/application/app_context';
@ -27,7 +24,6 @@ import {
UPLOAD_LICENSE_SUCCESS,
UPLOAD_LICENSE_TLS_NOT_ENABLED,
UPLOAD_LICENSE_INVALID,
// @ts-ignore
} from './api_responses';
let store: any = null;

View file

@ -28,7 +28,7 @@ import { EXTERNAL_LINKS } from '../../../../../common/constants';
import { AppContextConsumer, AppDependencies } from '../../../app_context';
import { TelemetryPluginStart, shouldShowTelemetryOptIn } from '../../../lib/telemetry';
interface Props {
export interface Props {
loadTrialStatus: () => void;
startLicenseTrial: () => void;
telemetry?: TelemetryPluginStart;

View file

@ -13,11 +13,8 @@ import { i18n } from '@kbn/i18n';
import { ToastsStart } from '@kbn/core/public';
import { ManagementAppMountParams } from '@kbn/management-plugin/public';
// @ts-expect-error
import { PipelineEditor } from './components/pipeline_editor';
// @ts-expect-error
import { Pipeline } from '../models/pipeline';
// @ts-expect-error
import * as Breadcrumbs from './breadcrumbs';
const usePipeline = (

View file

@ -24,13 +24,9 @@ const settingsDefaults = {
export class Pipeline {
/**
* Represents the pipeline for the client side editing/creating workflow
* @param {object} props An object used to instantiate a pipeline instance
* @param {string} props.id Named Id of the pipeline
* @param {string} props.description Optional description for the pipeline
* @param {object} props.pipeline The actual LS configuration as a string blob
* @param {string} props.username User who created or updated the pipeline
* @param {import('./props').Props} props}
*/
constructor(props) {
constructor(props = undefined) {
this.id = get(props, 'id');
this.description = get(props, 'description', '');
this.pipeline = get(props, 'pipeline', emptyPipeline);

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
/**
* An object used to instantiate a pipeline instance
*/
export interface Props {
/**
* Named Id of the pipeline
*/
id: string;
/**
* Optional description for the pipeline
*/
description: string;
/**
* The actual LS configuration as a string blob
*/
pipeline: string;
/**
* User who created or updated the pipeline
*/
username: string;
}

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"common/**/*",

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"common/**/*",

View file

@ -4,6 +4,11 @@
"outDir": "./target/types",
"emitDeclarationOnly": true,
"declaration": true,
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"common/**/*",

View file

@ -20,7 +20,7 @@ export function getBucketSize({
minInterval: string;
}) {
const duration = moment.duration(end - start, 'ms');
const bucketSize = Math.max(calculateAuto.near(100, duration).asSeconds(), 1);
const bucketSize = Math.max(calculateAuto.near(100, duration)?.asSeconds() ?? 0, 1);
const intervalString = `${bucketSize}s`;
const matches = minInterval && minInterval.match(/^([\d]+)([shmdwMy]|ms)$/);
const minBucketSize = matches ? Number(matches[1]) * unitToSeconds(matches[2]) : 0;

View file

@ -8,7 +8,6 @@
"target/**/*"
],
"compilerOptions": {
"allowJs": true,
"outDir": "target/types",
"types": [
"cypress",

View file

@ -20,6 +20,7 @@
],
"kbn_references": [
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../src/setup_node_env/tsconfig.json" },
// add references to other TypeScript projects the plugin depends on
// requiredPlugins from ./kibana.json

View file

@ -24,7 +24,7 @@ import {
import { ConfirmDeleteModal } from './confirm_delete_modal';
import { flattenPanelTree } from '../../../services';
class JobActionMenuUi extends Component {
export class JobActionMenuUi extends Component {
static propTypes = {
startJobs: PropTypes.func.isRequired,
stopJobs: PropTypes.func.isRequired,

View file

@ -13,6 +13,7 @@
],
"kbn_references": [
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../src/setup_node_env/tsconfig.json" },
{ "path": "../../../src/plugins/expressions/tsconfig.json" },
{ "path": "../../../src/plugins/screenshot_mode/tsconfig.json" },
{ "path": "../cloud/tsconfig.json" },

View file

@ -17,6 +17,7 @@
],
"kbn_references": [
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../src/setup_node_env/tsconfig.json" },
{ "path": "../../../src/plugins/data/tsconfig.json" },
{ "path": "../../../src/plugins/embeddable/tsconfig.json" },
{ "path": "../../../src/plugins/files/tsconfig.json"},

View file

@ -5,7 +5,12 @@
"emitDeclarationOnly": true,
"declaration": true,
"declarationMap": true,
"types": ["node"]
"types": ["node"],
// there is still a decent amount of JS in this plugin and we are taking
// advantage of the fact that TS doesn't know the types of that code and
// gives us `any`. Once that code is converted to .ts we can remove this
// and allow TS to infer types from any JS file imported.
"allowJs": false
},
"include": [
"**/*",