Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add absolute path import handling in kibana #52995

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/eslint-config-kibana/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,19 @@ module.exports = {
],

plugins: [
'import',
'@kbn/eslint-plugin-eslint',
'prettier',
],

settings: {
'import/resolver': {
'@kbn/eslint-import-resolver-kibana': {
forceNode: true,
},
},
},

parserOptions: {
ecmaVersion: 2018
},
Expand Down
9 changes: 0 additions & 9 deletions packages/eslint-config-kibana/javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,10 @@ module.exports = {
plugins: [
'mocha',
'babel',
'import',
'no-unsanitized',
'prefer-object-spread',
],

settings: {
'import/resolver': {
'@kbn/eslint-import-resolver-kibana': {
forceNode: true,
},
},
},

env: {
es6: true,
node: true,
Expand Down
15 changes: 0 additions & 15 deletions packages/eslint-config-kibana/typescript.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
// Some IDEs could not be running eslint with the correct extensions yet
// as this package was moved from typescript-eslint-parser to @typescript-eslint/parser

const semver = require('semver');
const PKG = require('../../package.json');

const eslintConfigPrettierTypescriptEslintRules = require('eslint-config-prettier/@typescript-eslint').rules;

module.exports = {
Expand All @@ -17,21 +14,9 @@ module.exports = {
plugins: [
'@typescript-eslint',
'ban',
'import',
'prefer-object-spread',
],

settings: {
'import/resolver': {
node: {
extensions: ['.mjs', '.js', '.json', '.ts', '.tsx'],
},
},
react: {
version: semver.valid(semver.coerce(PKG.dependencies.react)),
},
Comment on lines -30 to -32
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was redundant as already present in packages/eslint-config-kibana/react.js

},

env: {
es6: true,
node: true,
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-babel-preset/common_preset.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

const plugins = [
require.resolve('babel-plugin-add-module-exports'),
require.resolve('./transforms/rewrite_absolute_imports'),

// The class properties proposal was merged with the private fields proposal
// into the "class fields" proposal. Babel doesn't support this combined
Expand Down
3 changes: 2 additions & 1 deletion packages/kbn-babel-preset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"babel-plugin-filter-imports": "^4.0.0",
"babel-plugin-styled-components": "^1.10.6",
"babel-plugin-transform-define": "^2.0.0",
"babel-plugin-typescript-strip-namespaces": "^1.1.1"
"babel-plugin-typescript-strip-namespaces": "^1.1.1",
"babel-types": "^6.26.0"
}
}
93 changes: 93 additions & 0 deletions packages/kbn-babel-preset/transforms/rewrite_absolute_imports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* 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.
*/

const Path = require('path');
const { readFileSync } = require('fs');
const t = require('babel-types');

// we have to determine the root of the Kibana repo to properly resolve imports
// and since this package runs from source, and from the node_modules directory
// we are breaking the rules and embedding that info here.
const KIBANA_PACKAGE_JSON = __dirname.includes('node_modules')
? Path.resolve(__dirname, '../../../../package.json')
: Path.resolve(__dirname, '../../../package.json');

try {
const pkg = JSON.parse(readFileSync(KIBANA_PACKAGE_JSON, 'utf8'));
if (pkg.name !== 'kibana') {
throw true;
}
} catch (error) {
throw new Error(`
Unable to determine absolute path to Kibana repo, @kbn/babel-preset expects to either run
from the packages/ directory in source, or from the root of the node_modules directory
in the distributable.
`);
}

const REPO_ROOT = Path.dirname(KIBANA_PACKAGE_JSON);
const IMPORTED_FROM_ROOT_DIRS = ['src', 'x-pack'];

function isImportedFromRoot(importRequest) {
return IMPORTED_FROM_ROOT_DIRS.some(
p => importRequest === p || importRequest.startsWith(`${p}/`)
);
}

module.exports = () => ({
name: '@kbn/babel-preset/transform/rewrite_absolute_imports',
visitor: {
ImportDeclaration(path) {
const source = path.get('source');
const importPath = t.isStringLiteral(source.node) && source.node.value;

if (!importPath || !isImportedFromRoot(importPath)) {
return;
}

const { root, sourceFileName, filename } = path.hub.file.opts;

// The absolute path of the source file where the import is made from
let sourceFileAbsPath;
if (sourceFileName && Path.isAbsolute(sourceFileName)) {
sourceFileAbsPath = sourceFileName;
} else if (filename && Path.isAbsolute(filename)) {
sourceFileAbsPath = filename;
} else if (!sourceFileAbsPath && root) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: !sourceFileAbsPath can be remove

sourceFileAbsPath = Path.resolve(root, sourceFileName || filename);
} else {
throw new Error(`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this check done after all if/else branches? for cases when https://github.com/elastic/kibana/pull/52995/files#diff-0b4873344bd872a80014131ef6a02a27R73 fails

Unable to determine absolute path of file, either sourceFileName or filename opt
must be defined for the file and be absolute or combined with the root file opt.
`);
}

// The absolute path of the target file referenced in the import clause.
const importedFileAbsPath = Path.resolve(REPO_ROOT, importPath);

// The actual source-to-import relative path
let rewrittenImportPath = Path.relative(Path.dirname(sourceFileAbsPath), importedFileAbsPath);
if (!rewrittenImportPath.startsWith('.')) {
rewrittenImportPath = `./${rewrittenImportPath}`;
}

source.replaceWith(t.stringLiteral(rewrittenImportPath));
},
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
* under the License.
*/

const { join, dirname, extname } = require('path');

const { join, dirname, extname, resolve } = require('path');
const webpackResolver = require('eslint-import-resolver-webpack');
const nodeResolver = require('eslint-import-resolver-node');

const REPO_ROOT = dirname(require.resolve('../../package.json'));
const IMPORTED_FROM_ROOT_DIRS = ['src', 'x-pack'];

const {
getKibanaPath,
getProjectRoot,
Expand Down Expand Up @@ -66,9 +68,20 @@ function tryNodeResolver(importRequest, file, config) {
);
}

function isImportedFromRoot(importRequest) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I understand packages/kbn-eslint-plugin-eslint/rules/no_restricted_paths.js should integrate this resolution logic as well. Can we extract it in a common folder to share? Can be done in a separate PR.

return IMPORTED_FROM_ROOT_DIRS.some(
p => importRequest === p || importRequest.startsWith(`${p}/`)
);
}

exports.resolve = function resolveKibanaPath(importRequest, file, config) {
config = config || {};

if (isImportedFromRoot(importRequest)) {
config = { ...config, forceNode: true };
importRequest = resolve(REPO_ROOT, importRequest);
}

if (config.forceNode) {
return tryNodeResolver(importRequest, file, config);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ exports.getWebpackConfig = function(kibanaPath, projectRoot, config) {
const fromKibana = (...path) => resolve(kibanaPath, ...path);

const alias = {
src: fromKibana('src'),
'x-pack': fromKibana('x-pack'),

// Kibana defaults https://github.com/elastic/kibana/blob/6998f074542e8c7b32955db159d15661aca253d7/src/legacy/ui/ui_bundler_env.js#L30-L36
ui: fromKibana('src/legacy/ui/public'),
test_harness: fromKibana('src/test_harness/public'),
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-eslint-plugin-eslint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"babel-eslint": "^10.0.3"
},
"dependencies": {
"@kbn/dev-utils": "1.0.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this used?

"micromatch": "3.1.10",
"dedent": "^0.7.0",
"eslint-module-utils": "2.5.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ module.exports = {
}

function checkForRestrictedImportPath(importPath, node) {
const absoluteImportPath = importPath[0] === '.' ? resolve(importPath, context) : undefined;
const absoluteImportPath = resolve(importPath, context);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

paths not starting with . can be local now


const currentFilename = context.getFilename();
for (const { target, from, allowSameFolder, errorMessage = '' } of zones) {
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/config/raw_config_service.test.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@

export const mockGetConfigFromFiles = jest.fn();

jest.mock('./read_config', () => ({
jest.mock('src/core/server/config/read_config', () => ({
getConfigFromFiles: mockGetConfigFromFiles,
}));
Comment on lines -22 to 24
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(this commit will be deleted) This works even if read_config is imported using relative imports in test or sources import XXX from '../foo/read_config' (jest uses the resolved absolute path)

2 changes: 1 addition & 1 deletion src/core/server/root/index.test.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jest.doMock('../logging/logging_service', () => ({

import { configServiceMock } from '../config/config_service.mock';
export const configService = configServiceMock.create();
jest.doMock('../config/config_service', () => ({
jest.doMock('src/core/server/config/config_service', () => ({
ConfigService: jest.fn(() => configService),
}));

Expand Down
3 changes: 2 additions & 1 deletion src/dev/jest/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ export default {
'!src/legacy/ui/public/{agg_types,vis}/**/*.d.ts',
],
moduleNameMapper: {
'^src/plugins/(.*)': '<rootDir>/src/plugins/$1',
'^src/(.*)': '<rootDir>/src/$1',
'^x-pack/(.*)': '<rootDir>/x-pack/$1',
'^plugins/([^/.]*)(.*)': '<rootDir>/src/legacy/core_plugins/$1/public$2',
'^ui/(.*)': '<rootDir>/src/legacy/ui/public/$1',
'^uiExports/(.*)': '<rootDir>/src/dev/jest/mocks/file_mock.js',
Expand Down
2 changes: 2 additions & 0 deletions src/legacy/ui/ui_exports/ui_export_defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export const UI_EXPORT_DEFAULTS = {
],

webpackAliases: {
src: resolve(ROOT, 'src'),
'x-pack': resolve(ROOT, 'x-pack'),
ui: resolve(ROOT, 'src/legacy/ui/public'),
__kibanaCore__$: resolve(ROOT, 'src/core/public'),
test_harness: resolve(ROOT, 'src/test_harness/public'),
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"baseUrl": ".",
"paths": {
// Allows for importing from `kibana` package for the exported types.
"src/*": ["src/*"],
Copy link
Contributor

@mshustov mshustov Dec 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we update x-pack tsconfig as well?
update: as I can see mapping from x-pack works without adding these paths(due to baseUrl set to the root folder probably?)

"x-pack/*": ["x-pack/*"],
"kibana": ["./kibana"],
"kibana/public": ["src/core/public"],
"kibana/server": ["src/core/server"],
Expand Down
4 changes: 2 additions & 2 deletions x-pack/dev-tools/jest/create_jest_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export function createJestConfig({ kibanaDirectory, xPackKibanaDirectory }) {
moduleNameMapper: {
'^ui/(.*)': `${kibanaDirectory}/src/legacy/ui/public/$1`,
'uiExports/(.*)': fileMockPath,
'^src/core/(.*)': `${kibanaDirectory}/src/core/$1`,
'^src/legacy/(.*)': `${kibanaDirectory}/src/legacy/$1`,
'^src/(.*)': `${kibanaDirectory}/src/$1`,
'^x-pack/(.*)': `${kibanaDirectory}/x-pack/$1'`,
'^plugins/watcher/np_ready/application/models/(.*)': `${xPackKibanaDirectory}/legacy/plugins/watcher/public/np_ready/application/models/$1`,
'^plugins/([^/.]*)(.*)': `${kibanaDirectory}/src/legacy/core_plugins/$1/public$2`,
'^legacy/plugins/xpack_main/(.*);': `${xPackKibanaDirectory}/legacy/plugins/xpack_main/public/$1`,
Expand Down
2 changes: 2 additions & 0 deletions x-pack/legacy/plugins/beats_management/wallaby.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ module.exports = function(wallaby) {
rootDir: wallaby.localProjectDir,
moduleNameMapper: {
'^ui/(.*)': `${kibanaDirectory}/src/legacy/ui/public/$1`,
'^src/(.*)': `${kibanaDirectory}/src/$1`,
'^x-pack/(.*)': `${kibanaDirectory}/x-pack/$1'`,
// eslint-disable-next-line
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `${kibanaDirectory}/src/dev/jest/mocks/file_mock.js`,
'\\.(css|less|scss)$': `${kibanaDirectory}/src/dev/jest/mocks/style_mock.js`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
*/

import { get } from 'lodash';
// @ts-ignore
import { createQuery } from './create_query';
// @ts-ignore
import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants';

import {
ClusterDetailsGetter,
StatsCollectionConfig,
ClusterDetails,
} from '../../../../../../src/legacy/core_plugins/telemetry/server/collection_manager';
} from 'src/legacy/core_plugins/telemetry/server/collection_manager';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as I understand this is handled by built-in ts functionality. could you add an example for js code to make sure that server runs?

// @ts-ignore
import { createQuery } from './create_query';
// @ts-ignore
import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants';

/**
* Get a list of Cluster UUIDs that exist within the specified timespan.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { TimeRange } from 'src/plugins/data/public';
import { TimeRange, Query, esFilters } from 'src/plugins/data/public';
import {
EmbeddableInput,
EmbeddableOutput,
IEmbeddable,
EmbeddableFactory,
} from '../../../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public';
} from 'src/legacy/core_plugins/embeddable_api/public/np_ready/public';
import { inputsModel } from '../../store/inputs';
import { Query, esFilters } from '../../../../../../../src/plugins/data/public';

export interface MapEmbeddableInput extends EmbeddableInput {
filters: esFilters.Filter[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
*/

import { BehaviorSubject } from 'rxjs';
import { licenseMock } from '../common/licensing.mock';
// eslint-disable-next-line
import { licenseMock } from 'x-pack/plugins/licensing/common/licensing.mock';

import { createRouteHandlerContext } from './licensing_route_handler_context';

Expand Down
2 changes: 2 additions & 0 deletions x-pack/test_utils/jest/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export default {
collectCoverageFrom: ['legacy/plugins/**/*.js', 'legacy/common/**/*.js', 'legacy/server/**/*.js'],
moduleNameMapper: {
'^ui/(.*)': '<rootDir>**/public/$1',
'^src/(.*)': `<rootDir>/../src/$1`,
'^x-pack/(.*)': `<rootDir>/$1'`,
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/dev/jest/mocks/file_mock.js',
'\\.(css|less|scss)$': '<rootDir>/../src/dev/jest/mocks/style_mock.js',
Expand Down