From 4fc365a8f07ab675039549af8323eeb1dd39d030 Mon Sep 17 00:00:00 2001
From: Dario Gieselaar <dario.gieselaar@elastic.co>
Date: Thu, 16 Mar 2023 04:43:50 -0400
Subject: [PATCH] [APM] Remove TS optimization scripts (#153161)

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
---
 packages/kbn-ts-projects/ts_projects.ts       |   2 +-
 x-pack/plugins/apm/dev_docs/typescript.md     |  11 --
 .../scripts/infer_route_return_types/index.ts | 172 +++++++++---------
 .../plugins/apm/scripts/optimize_tsconfig.js  |  13 --
 .../apm/scripts/optimize_tsconfig/optimize.js | 119 ------------
 .../apm/scripts/optimize_tsconfig/paths.js    |  28 ---
 .../optimize_tsconfig/test_tsconfig.json      |  19 --
 .../scripts/optimize_tsconfig/tsconfig.json   |  18 --
 .../scripts/optimize_tsconfig/unoptimize.js   |  27 ---
 x-pack/plugins/apm/scripts/precommit.js       |  49 ++---
 .../apm/scripts/unoptimize_tsconfig.js        |  13 --
 11 files changed, 98 insertions(+), 373 deletions(-)
 delete mode 100644 x-pack/plugins/apm/dev_docs/typescript.md
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig.js
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig/optimize.js
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig/paths.js
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig/test_tsconfig.json
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json
 delete mode 100644 x-pack/plugins/apm/scripts/optimize_tsconfig/unoptimize.js
 delete mode 100644 x-pack/plugins/apm/scripts/unoptimize_tsconfig.js

diff --git a/packages/kbn-ts-projects/ts_projects.ts b/packages/kbn-ts-projects/ts_projects.ts
index 9a218fbabe816..38573bf4ca9d3 100644
--- a/packages/kbn-ts-projects/ts_projects.ts
+++ b/packages/kbn-ts-projects/ts_projects.ts
@@ -10,7 +10,7 @@ import { TsProject } from './ts_project';
 
 export const TS_PROJECTS = TsProject.loadAll({
   /** Array of repo-relative paths to projects which should be ignored and not treated as a TS project in the repo */
-  ignore: ['x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json', '**/__fixtures__/**/*'],
+  ignore: ['**/__fixtures__/**/*'],
 
   /** Array of repo-relative paths to projects which should have their type-check disabled */
   disableTypeCheck: [
diff --git a/x-pack/plugins/apm/dev_docs/typescript.md b/x-pack/plugins/apm/dev_docs/typescript.md
deleted file mode 100644
index 110c4a2d1ec97..0000000000000
--- a/x-pack/plugins/apm/dev_docs/typescript.md
+++ /dev/null
@@ -1,11 +0,0 @@
-#### Optimizing TypeScript 
-
-Kibana and X-Pack are very large TypeScript projects, and it comes at a cost. Editor responsiveness is not great, and the CLI type check for X-Pack takes about a minute. To get faster feedback, we create a smaller APM TypeScript project that only type checks the APM project and the files it uses. This optimization consists of modifying `tsconfig.json` in the X-Pack folder to only include APM files, and editing the Kibana configuration to not include any files. The script configures git to ignore any changes in these files, and has an undo script as well.
-
-To run the optimization:
-
-`$ node x-pack/plugins/apm/scripts/optimize_tsconfig`
-
-To undo the optimization:
-
-`$ node x-pack/plugins/apm/scripts/unoptimize_tsconfig`
diff --git a/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts b/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts
index ee5a05f64ca40..c3fb30e2d17ac 100644
--- a/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts
+++ b/x-pack/plugins/apm/scripts/infer_route_return_types/index.ts
@@ -21,7 +21,6 @@ import {
 import Path from 'path';
 import { execSync } from 'child_process';
 import { argv } from 'yargs';
-import { optimizeTsConfig } from '../optimize_tsconfig/optimize';
 
 // This script adds explicit return types to route handlers,
 // for performance reasons. See https://github.com/elastic/kibana/pull/123266
@@ -33,110 +32,107 @@ type ConvertibleDeclaration =
   | ArrowFunction
   | MethodDeclaration;
 
-optimizeTsConfig().then(() => {
-  const project = new Project({
-    tsConfigFilePath: Path.resolve(__dirname, '../../../../../tsconfig.json'),
-  });
+const project = new Project({
+  tsConfigFilePath: Path.resolve(__dirname, '../../../../../tsconfig.json'),
+});
 
-  const glob =
-    (argv.glob as string | undefined) ||
-    'x-pack/plugins/apm/server/**/route.ts';
+const glob =
+  (argv.glob as string | undefined) || 'x-pack/plugins/apm/server/**/route.ts';
 
-  const files = project.getSourceFiles(glob);
+const files = project.getSourceFiles(glob);
 
-  const changedFiles: SourceFile[] = [];
+const changedFiles: SourceFile[] = [];
 
-  files.forEach((file) => {
-    file.getVariableDeclarations().forEach((declaration) => {
-      const initializer = declaration.getInitializerIfKind(
-        SyntaxKind.CallExpression
-      );
+files.forEach((file) => {
+  file.getVariableDeclarations().forEach((declaration) => {
+    const initializer = declaration.getInitializerIfKind(
+      SyntaxKind.CallExpression
+    );
 
-      const argument = initializer?.getArguments()[0];
+    const argument = initializer?.getArguments()[0];
 
-      if (Node.isObjectLiteralExpression(argument)) {
-        // this gets the `handler` function
-        const handler = argument.getProperty('handler') as
-          | PropertyAssignment
-          | MethodDeclaration
-          | undefined;
+    if (Node.isObjectLiteralExpression(argument)) {
+      // this gets the `handler` function
+      const handler = argument.getProperty('handler') as
+        | PropertyAssignment
+        | MethodDeclaration
+        | undefined;
 
-        if (!handler) {
-          return;
-        }
+      if (!handler) {
+        return;
+      }
 
-        let fnDeclaration = (
-          Node.isPropertyAssignment(handler)
-            ? (handler.getInitializer() as ConvertibleDeclaration)
-            : handler
-        )
-          // remove any explicit return type
-          .removeReturnType();
+      let fnDeclaration = (
+        Node.isPropertyAssignment(handler)
+          ? (handler.getInitializer() as ConvertibleDeclaration)
+          : handler
+      )
+        // remove any explicit return type
+        .removeReturnType();
 
-        const signature = fnDeclaration.getSignature();
+      const signature = fnDeclaration.getSignature();
 
-        if (!signature) {
-          return;
+      if (!signature) {
+        return;
+      }
+
+      const returnType = signature.getReturnType();
+
+      const txt = returnType.getText(
+        fnDeclaration,
+        TypeFormatFlags.NoTruncation
+      );
+
+      fnDeclaration = fnDeclaration.setReturnType(txt);
+
+      let hasAny: boolean = false;
+
+      fnDeclaration.transform((traversal) => {
+        const node = traversal.visitChildren();
+
+        if (node.kind === SyntaxKind.AnyKeyword) {
+          hasAny = true;
         }
 
-        const returnType = signature.getReturnType();
-
-        const txt = returnType.getText(
-          fnDeclaration,
-          TypeFormatFlags.NoTruncation
-        );
-
-        fnDeclaration = fnDeclaration.setReturnType(txt);
-
-        let hasAny: boolean = false;
-
-        fnDeclaration.transform((traversal) => {
-          const node = traversal.visitChildren();
-
-          if (node.kind === SyntaxKind.AnyKeyword) {
-            hasAny = true;
-          }
-
-          if (ts.isImportTypeNode(node)) {
-            const literal = (node.argument as ts.LiteralTypeNode)
-              .literal as ts.StringLiteral;
-
-            // replace absolute paths with relative paths
-            return ts.updateImportTypeNode(
-              node,
-              ts.createLiteralTypeNode(
-                ts.createStringLiteral(
-                  `./${Path.relative(
-                    Path.dirname(file.getFilePath()),
-                    literal.text
-                  )}`
-                )
-              ),
-              node.qualifier!,
-              node.typeArguments
-            );
-          }
-
-          return node;
-        });
-
-        if (hasAny) {
-          // eslint-disable-next-line no-console
-          console.warn(`Any type detected in ${file.getFilePath()}: ${txt}`);
+        if (ts.isImportTypeNode(node)) {
+          const literal = (node.argument as ts.LiteralTypeNode)
+            .literal as ts.StringLiteral;
+
+          // replace absolute paths with relative paths
+          return ts.updateImportTypeNode(
+            node,
+            ts.createLiteralTypeNode(
+              ts.createStringLiteral(
+                `./${Path.relative(
+                  Path.dirname(file.getFilePath()),
+                  literal.text
+                )}`
+              )
+            ),
+            node.qualifier!,
+            node.typeArguments
+          );
         }
 
-        changedFiles.push(file);
+        return node;
+      });
+
+      if (hasAny) {
+        // eslint-disable-next-line no-console
+        console.warn(`Any type detected in ${file.getFilePath()}: ${txt}`);
       }
-    });
+
+      changedFiles.push(file);
+    }
   });
+});
 
-  changedFiles.forEach((file) => file.saveSync());
+changedFiles.forEach((file) => file.saveSync());
 
-  const root = Path.join(__dirname, '../../../../..');
+const root = Path.join(__dirname, '../../../../..');
 
-  // run ESLint on the changed files
-  execSync(`node scripts/eslint ${glob} --fix`, {
-    cwd: root,
-    stdio: 'inherit',
-  });
+// run ESLint on the changed files
+execSync(`node scripts/eslint ${glob} --fix`, {
+  cwd: root,
+  stdio: 'inherit',
 });
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig.js b/x-pack/plugins/apm/scripts/optimize_tsconfig.js
deleted file mode 100644
index fa15f0f582e89..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig.js
+++ /dev/null
@@ -1,13 +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; you may not use this file except in compliance with the Elastic License
- * 2.0.
- */
-
-const { optimizeTsConfig } = require('./optimize_tsconfig/optimize');
-
-optimizeTsConfig().catch((err) => {
-  console.error(err);
-  process.exit(1);
-});
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/optimize.js b/x-pack/plugins/apm/scripts/optimize_tsconfig/optimize.js
deleted file mode 100644
index fa45bfa12f3b7..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig/optimize.js
+++ /dev/null
@@ -1,119 +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; you may not use this file except in compliance with the Elastic License
- * 2.0.
- */
-
-/* eslint-disable import/no-extraneous-dependencies */
-
-const fs = require('fs');
-const { promisify } = require('util');
-const path = require('path');
-const json5 = require('json5');
-const execa = require('execa');
-const { omit } = require('lodash');
-
-const readFile = promisify(fs.readFile);
-const writeFile = promisify(fs.writeFile);
-const unlink = promisify(fs.unlink);
-
-const {
-  kibanaRoot,
-  tsconfigTpl,
-  tsconfigTplTest,
-  filesToIgnore,
-} = require('./paths');
-const { unoptimizeTsConfig } = require('./unoptimize');
-
-async function prepareBaseTsConfig() {
-  const baseConfigFilename = path.resolve(kibanaRoot, 'tsconfig.base.json');
-  const config = json5.parse(await readFile(baseConfigFilename, 'utf-8'));
-
-  await writeFile(
-    baseConfigFilename,
-    JSON.stringify(
-      {
-        ...omit(config, 'references'),
-        compilerOptions: {
-          ...config.compilerOptions,
-          incremental: false,
-          composite: false,
-        },
-        include: [],
-      },
-      null,
-      2
-    ),
-    { encoding: 'utf-8' }
-  );
-}
-
-async function addApmFilesToRootTsConfig() {
-  const template = json5.parse(await readFile(tsconfigTpl, 'utf-8'));
-  const rootTsConfigFilename = path.join(kibanaRoot, 'tsconfig.json');
-  const rootTsConfig = json5.parse(
-    await readFile(rootTsConfigFilename, 'utf-8')
-  );
-
-  await writeFile(
-    rootTsConfigFilename,
-    JSON.stringify({ ...rootTsConfig, ...template, references: [] }, null, 2),
-    { encoding: 'utf-8' }
-  );
-}
-
-async function addApmFilesToTestTsConfig() {
-  const template = json5.parse(await readFile(tsconfigTplTest, 'utf-8'));
-  const testTsConfigFilename = path.join(
-    kibanaRoot,
-    'x-pack/test/tsconfig.json'
-  );
-  const testTsConfig = json5.parse(
-    await readFile(testTsConfigFilename, 'utf-8')
-  );
-
-  await writeFile(
-    testTsConfigFilename,
-    JSON.stringify({ ...testTsConfig, ...template, references: [] }, null, 2),
-    { encoding: 'utf-8' }
-  );
-}
-
-async function setIgnoreChanges() {
-  for (const filename of filesToIgnore) {
-    await execa('git', ['update-index', '--skip-worktree', filename]);
-  }
-}
-
-async function deleteTsConfigs() {
-  const toDelete = ['apm', 'observability', 'rule_registry'];
-
-  for (const app of toDelete) {
-    await unlink(
-      path.resolve(kibanaRoot, 'x-pack/plugins', app, 'tsconfig.json')
-    );
-  }
-}
-
-async function optimizeTsConfig() {
-  await unoptimizeTsConfig();
-
-  await prepareBaseTsConfig();
-
-  await addApmFilesToRootTsConfig();
-
-  await addApmFilesToTestTsConfig();
-
-  await deleteTsConfigs();
-
-  await setIgnoreChanges();
-  // eslint-disable-next-line no-console
-  console.log(
-    'Created an optimized tsconfig.json for APM. To undo these changes, run `./scripts/unoptimize_tsconfig.js`'
-  );
-}
-
-module.exports = {
-  optimizeTsConfig,
-};
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/paths.js b/x-pack/plugins/apm/scripts/optimize_tsconfig/paths.js
deleted file mode 100644
index df430dabafc9c..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig/paths.js
+++ /dev/null
@@ -1,28 +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; you may not use this file except in compliance with the Elastic License
- * 2.0.
- */
-
-const path = require('path');
-
-const kibanaRoot = path.resolve(__dirname, '../../../../..');
-const tsconfigTpl = path.resolve(__dirname, './tsconfig.json');
-const tsconfigTplTest = path.resolve(__dirname, './test_tsconfig.json');
-
-const filesToIgnore = [
-  path.resolve(kibanaRoot, 'tsconfig.json'),
-  path.resolve(kibanaRoot, 'tsconfig.base.json'),
-  path.resolve(kibanaRoot, 'x-pack/plugins/apm', 'tsconfig.json'),
-  path.resolve(kibanaRoot, 'x-pack/plugins/observability', 'tsconfig.json'),
-  path.resolve(kibanaRoot, 'x-pack/plugins/rule_registry', 'tsconfig.json'),
-  path.resolve(kibanaRoot, 'x-pack/test', 'tsconfig.json'),
-];
-
-module.exports = {
-  kibanaRoot,
-  tsconfigTpl,
-  tsconfigTplTest,
-  filesToIgnore,
-};
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/test_tsconfig.json b/x-pack/plugins/apm/scripts/optimize_tsconfig/test_tsconfig.json
deleted file mode 100644
index 7f7cbf4e3efa2..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig/test_tsconfig.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-  "compilerOptions": {
-    "types": [
-      "node"
-    ],
-    "noErrorTruncation": true,
-    "assumeChangesOnlyAffectDirectDependencies": true
-  },
-  "include": [
-    "./apm_api_integration/**/*",
-    "../../packages/kbn-test/types/**/*",
-    "../../typings/**/*"
-  ],
-  "exclude": [
-    "**/__fixtures__/**/*",
-    "**/target/**",
-    "**/node_modules/**"
-  ]
-}
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json b/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json
deleted file mode 100644
index 25f44f14dc080..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig/tsconfig.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
-  "include": [
-    "./x-pack/plugins/apm/**/*",
-    "./x-pack/plugins/observability/**/*",
-    "./typings/**/*"
-  ],
-  "exclude": [
-    "**/__fixtures__/**/*",
-    "./x-pack/plugins/apm/ftr_e2e",
-    "./x-pack/plugins/apm/e2e",
-    "**/target/**",
-    "**/node_modules/**"
-  ],
-  "compilerOptions": {
-    "noErrorTruncation": true,
-    "assumeChangesOnlyAffectDirectDependencies": true
-  }
-}
diff --git a/x-pack/plugins/apm/scripts/optimize_tsconfig/unoptimize.js b/x-pack/plugins/apm/scripts/optimize_tsconfig/unoptimize.js
deleted file mode 100644
index ebbf16f7464e0..0000000000000
--- a/x-pack/plugins/apm/scripts/optimize_tsconfig/unoptimize.js
+++ /dev/null
@@ -1,27 +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; you may not use this file except in compliance with the Elastic License
- * 2.0.
- */
-
-/* eslint-disable import/no-extraneous-dependencies */
-
-const execa = require('execa');
-
-const { filesToIgnore } = require('./paths');
-
-async function unoptimizeTsConfig() {
-  for (const filename of filesToIgnore) {
-    await execa('git', ['update-index', '--no-skip-worktree', filename]);
-    await execa('git', ['checkout', filename]);
-  }
-}
-
-module.exports = {
-  unoptimizeTsConfig: async () => {
-    await unoptimizeTsConfig();
-    // eslint-disable-next-line no-console
-    console.log('Removed APM TypeScript optimizations');
-  },
-};
diff --git a/x-pack/plugins/apm/scripts/precommit.js b/x-pack/plugins/apm/scripts/precommit.js
index c1847432abcf7..c018770a65553 100644
--- a/x-pack/plugins/apm/scripts/precommit.js
+++ b/x-pack/plugins/apm/scripts/precommit.js
@@ -11,17 +11,12 @@
 const execa = require('execa');
 const Listr = require('listr');
 const { resolve } = require('path');
-const { argv } = require('yargs');
 
 const root = resolve(__dirname, '../../../..');
 
 const execaOpts = { cwd: root, stderr: 'pipe' };
 
-const useOptimizedTsConfig = !!argv.optimizeTs;
-
-const tsconfig = useOptimizedTsConfig
-  ? resolve(root, 'tsconfig.json')
-  : resolve(root, 'x-pack/plugins/apm/tsconfig.json');
+const tsconfig = resolve(root, 'x-pack/plugins/apm/tsconfig.json');
 
 const testTsconfig = resolve(root, 'x-pack/test/tsconfig.json');
 
@@ -33,32 +28,18 @@ const tasks = new Listr(
     },
     {
       title: 'Typescript',
-      task: () =>
-        execa(
-          'node',
-          [
-            resolve(
-              __dirname,
-              useOptimizedTsConfig
-                ? './optimize_tsconfig.js'
-                : './unoptimize_tsconfig.js'
-            ),
-          ],
-          execaOpts
-        ).then(() =>
-          Promise.all([
-            execa(
-              require.resolve('typescript/bin/tsc'),
-              ['--project', tsconfig, '--pretty', '--noEmit'],
-              execaOpts
-            ),
-            execa(
-              require.resolve('typescript/bin/tsc'),
-              ['--project', testTsconfig, '--pretty', '--noEmit'],
-              execaOpts
-            ),
-          ])
-        ),
+      task: async () => {
+        await execa('node', [
+          resolve(__dirname, '../../../../scripts/type_check.js'),
+          '--project',
+          tsconfig,
+        ]);
+        await execa('node', [
+          resolve(__dirname, '../../../../scripts/type_check.js'),
+          '--project',
+          testTsconfig,
+        ]);
+      },
     },
     {
       title: 'Jest',
@@ -69,10 +50,6 @@ const tasks = new Listr(
             resolve(__dirname, '../../../../scripts/jest.js'),
             '--config',
             resolve(__dirname, '../jest.config.js'),
-            '--reporters',
-            resolve(__dirname, '../../../../node_modules/jest-silent-reporter'),
-            '--collect-coverage',
-            'false',
             '--maxWorkers',
             4,
           ],
diff --git a/x-pack/plugins/apm/scripts/unoptimize_tsconfig.js b/x-pack/plugins/apm/scripts/unoptimize_tsconfig.js
deleted file mode 100644
index 330abd963393e..0000000000000
--- a/x-pack/plugins/apm/scripts/unoptimize_tsconfig.js
+++ /dev/null
@@ -1,13 +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; you may not use this file except in compliance with the Elastic License
- * 2.0.
- */
-
-const { unoptimizeTsConfig } = require('./optimize_tsconfig/unoptimize');
-
-unoptimizeTsConfig().catch((err) => {
-  console.error(err);
-  process.exit(1);
-});