@centreon/js-config 24.7.0 → 24.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ const fs = require('fs');
2
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');
3
+
4
+ class CentreonModulePlugin {
5
+ constructor(federatedComponentConfiguration) {
6
+ this.federatedComponentConfiguration = federatedComponentConfiguration;
7
+ }
8
+
9
+ apply(compiler) {
10
+ compiler.hooks.done.tap('CentreonModulePlugin', (stats) => {
11
+ const newFederatedComponentConfiguration = {
12
+ ...this.federatedComponentConfiguration,
13
+ remoteEntry: Object.keys(stats.compilation.assets).find((assetName) =>
14
+ assetName.match(/(^remoteEntry)\S+.js$/),
15
+ ),
16
+ };
17
+
18
+ if (!fs.existsSync(compiler.options.output.path)) {
19
+ fs.mkdirSync(compiler.options.output.path, { recursive: true });
20
+ }
21
+
22
+ fs.writeFileSync(
23
+ `${compiler.options.output.path}/moduleFederation.json`,
24
+ JSON.stringify(newFederatedComponentConfiguration, null, 2),
25
+ );
26
+ });
27
+ }
28
+ }
29
+
30
+ module.exports = ({
31
+ outputPath,
32
+ federatedComponentConfiguration,
33
+ }) => ({
34
+ output: {
35
+ library: '[chunkhash:8]',
36
+ path: outputPath,
37
+ },
38
+ plugins: [
39
+ new CleanWebpackPlugin({
40
+ cleanOnceBeforeBuildPatterns: [`${outputPath}/**/*.js`],
41
+ dangerouslyAllowCleanPatternsOutsideProject: true,
42
+ dry: false,
43
+ }),
44
+ new CentreonModulePlugin(federatedComponentConfiguration),
45
+ ],
46
+ });
@@ -1,19 +0,0 @@
1
- const disableMotion = (win): void => {
2
- const injectedStyleEl = win.document.getElementById('__cy_disable_motion__');
3
- if (injectedStyleEl) {
4
- return;
5
- }
6
- win.document.head.insertAdjacentHTML(
7
- 'beforeend',
8
- `
9
- <style id="__cy_disable_motion__">
10
- /* Disable CSS transitions. */
11
- *, *::before, *::after { -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; -ms-transition: none !important; transition: none !important; }
12
- /* Disable CSS animations. */
13
- *, *::before, *::after { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; -ms-animation: none !important; animation: none !important; }
14
- </style>
15
- `.trim()
16
- );
17
- };
18
-
19
- export default disableMotion;
@@ -1,36 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
-
4
- const filePath = process.argv[2];
5
-
6
- const { error: logError } = console;
7
-
8
- try {
9
- const outFile = fs.readFileSync(path.resolve(filePath)).toString();
10
- const outFileJson = JSON.parse(outFile);
11
-
12
- const coveragesWithoutNodeModules = Object.entries(outFileJson)
13
- .map(([key, value]) => {
14
- if (key.includes('node_modules')) {
15
- return undefined;
16
- }
17
-
18
- return [key, value];
19
- })
20
- .filter((v) => v);
21
-
22
- const finalOutJson = coveragesWithoutNodeModules.reduce(
23
- (acc, [key, value]) => ({
24
- ...acc,
25
- [key]: value
26
- }),
27
- {}
28
- );
29
-
30
- fs.writeFileSync(
31
- path.resolve(filePath),
32
- JSON.stringify(finalOutJson, null, 2)
33
- );
34
- } catch (error) {
35
- logError(error.message);
36
- }
@@ -1,117 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-namespace */
2
-
3
- const apiBase = '/centreon/api';
4
- const apiActionV1 = `${apiBase}/index.php`;
5
-
6
- const getStatusNumberFromString = (status: string): number => {
7
- const statuses = {
8
- critical: '2',
9
- down: '1',
10
- ok: '0',
11
- unknown: '3',
12
- unreachable: '2',
13
- up: '0',
14
- warning: '1'
15
- };
16
-
17
- if (status in statuses) {
18
- return statuses[status];
19
- }
20
-
21
- throw new Error(`Status ${status} does not exist`);
22
- };
23
-
24
- interface SubmitResult {
25
- host: string;
26
- output: string;
27
- perfdata?: string | null;
28
- service?: string | null;
29
- status: string;
30
- }
31
-
32
- Cypress.Commands.add(
33
- 'submitResults',
34
- (results: Array<SubmitResult>): Cypress.Chainable => {
35
- results.forEach(
36
- ({ host, output, perfdata = '', service = null, status }) => {
37
- const timestampNow = Math.floor(Date.now() / 1000) - 15;
38
- const updatetime = timestampNow.toString();
39
-
40
- const result = {
41
- host,
42
- output,
43
- perfdata,
44
- service,
45
- status: getStatusNumberFromString(status),
46
- updatetime
47
- };
48
-
49
- cy.request({
50
- body: {
51
- results: [result]
52
- },
53
- headers: {
54
- 'Content-Type': 'application/json',
55
- 'centreon-auth-token': window.localStorage.getItem('userTokenApiV1')
56
- },
57
- method: 'POST',
58
- url: `${apiActionV1}?action=submit&object=centreon_submit_results`
59
- });
60
- }
61
- );
62
-
63
- return cy.wrap(null);
64
- }
65
- );
66
-
67
- interface Downtime {
68
- host: string;
69
- service?: string | null;
70
- }
71
-
72
- Cypress.Commands.add(
73
- 'waitForDowntime',
74
- (downtime: Downtime): Cypress.Chainable => {
75
- cy.log('Checking hosts in database');
76
-
77
- let query = `SELECT COUNT(d.downtime_id) AS count_downtimes FROM downtimes as d
78
- INNER JOIN hosts as h ON h.host_id = d.host_id AND h.name = '${downtime.host}'`;
79
- if (downtime.service) {
80
- query += ` INNER JOIN services as s ON s.service_id = d.service_id AND s.description = '${downtime.service}'`;
81
- }
82
- query += ` WHERE d.started=1`;
83
- if (!downtime.service) {
84
- query += ` AND d.service_id = 0`;
85
- }
86
-
87
- cy.log(query);
88
-
89
- cy.waitUntil(() => {
90
- return cy
91
- .requestOnDatabase({
92
- database: 'centreon_storage',
93
- query
94
- })
95
- .then(([rows]) => {
96
- const foundDowntimesCount = rows.length ? rows[0].count_downtimes : 0;
97
-
98
- cy.log('Downtime count in database', foundDowntimesCount);
99
-
100
- return cy.wrap(foundDowntimesCount > 0);
101
- });
102
- });
103
-
104
- return cy.wrap(null);
105
- }
106
- );
107
-
108
- declare global {
109
- namespace Cypress {
110
- interface Chainable {
111
- submitResults: (props: Array<SubmitResult>) => Cypress.Chainable;
112
- waitForDowntime: (downtime: Downtime) => Cypress.Chainable;
113
- }
114
- }
115
- }
116
-
117
- export {};
@@ -1,26 +0,0 @@
1
- import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
2
- import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
3
- import { addCucumberPreprocessorPlugin } from '@badeball/cypress-cucumber-preprocessor';
4
- import createBundler from '@bahmutov/cypress-esbuild-preprocessor';
5
- import createEsbuildPlugin from '@badeball/cypress-cucumber-preprocessor/esbuild';
6
-
7
- export default async (
8
- on: Cypress.PluginEvents,
9
- config: Cypress.PluginConfigOptions
10
- ): Promise<void> => {
11
- await addCucumberPreprocessorPlugin(on, config);
12
-
13
- on(
14
- 'file:preprocessor',
15
- createBundler({
16
- plugins: [
17
- createEsbuildPlugin(config),
18
- NodeModulesPolyfillPlugin(),
19
- NodeGlobalsPolyfillPlugin({
20
- buffer: true,
21
- process: true
22
- })
23
- ]
24
- })
25
- );
26
- };
@@ -1,13 +0,0 @@
1
- module.exports = {
2
- mochawesomeReporterOptions: {
3
- consoleReporter: 'none',
4
- html: false,
5
- json: true,
6
- overwrite: true,
7
- reportDir: 'results/reports',
8
- reportFilename: '[name]-report.json'
9
- },
10
- reporterEnabled: `mochawesome,${require.resolve(
11
- '@badeball/cypress-cucumber-preprocessor/pretty-reporter'
12
- )}`
13
- };
@@ -1,259 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { execSync } from 'child_process';
3
- import { existsSync, mkdirSync } from 'fs';
4
- import path from 'path';
5
-
6
- import tar from 'tar-fs';
7
- import {
8
- DockerComposeEnvironment,
9
- GenericContainer,
10
- StartedDockerComposeEnvironment,
11
- StartedTestContainer,
12
- Wait,
13
- getContainerRuntimeClient
14
- } from 'testcontainers';
15
- import { createConnection } from 'mysql2/promise';
16
-
17
- interface Containers {
18
- [key: string]: StartedTestContainer;
19
- }
20
-
21
- export default (on: Cypress.PluginEvents): void => {
22
- let dockerEnvironment: StartedDockerComposeEnvironment | null = null;
23
- const containers: Containers = {};
24
-
25
- const getContainer = (containerName): StartedTestContainer => {
26
- let container;
27
-
28
- if (dockerEnvironment !== null) {
29
- container = dockerEnvironment.getContainer(`${containerName}-1`);
30
- } else if (containers[containerName]) {
31
- container = containers[containerName];
32
- } else {
33
- throw new Error(`Cannot get container ${containerName}`);
34
- }
35
-
36
- return container;
37
- };
38
-
39
- interface PortBinding {
40
- destination: number;
41
- source: number;
42
- }
43
-
44
- interface StartContainerProps {
45
- command?: string;
46
- image: string;
47
- name: string;
48
- portBindings: Array<PortBinding>;
49
- }
50
-
51
- interface StopContainerProps {
52
- name: string;
53
- }
54
-
55
- on('task', {
56
- copyFromContainer: async ({ destination, serviceName, source }) => {
57
- try {
58
- if (dockerEnvironment !== null) {
59
- const container = dockerEnvironment.getContainer(`${serviceName}-1`);
60
-
61
- await container
62
- .copyArchiveFromContainer(source)
63
- .then((archiveStream) => {
64
- return new Promise<void>((resolve) => {
65
- const dest = tar.extract(destination);
66
- archiveStream.pipe(dest);
67
- dest.on('finish', resolve);
68
- });
69
- });
70
- }
71
- } catch (error) {
72
- console.error(error);
73
- }
74
-
75
- return null;
76
- },
77
- copyToContainer: async ({ destination, serviceName, source, type }) => {
78
- const container = getContainer(serviceName);
79
-
80
- if (type === 'directory') {
81
- await container.copyDirectoriesToContainer([
82
- {
83
- source,
84
- target: destination
85
- }
86
- ]);
87
- } else if (type === 'file') {
88
- await container.copyFilesToContainer([
89
- {
90
- source,
91
- target: destination
92
- }
93
- ]);
94
- }
95
-
96
- return null;
97
- },
98
- createDirectory: async (directoryPath: string) => {
99
- if (!existsSync(directoryPath)) {
100
- mkdirSync(directoryPath, { recursive: true });
101
- }
102
-
103
- return null;
104
- },
105
- execInContainer: async ({ command, name }) => {
106
- const { exitCode, output } = await getContainer(name).exec([
107
- 'bash',
108
- '-c',
109
- `${command}${command.match(/[\n\r]/) ? '' : ' 2>&1'}`
110
- ]);
111
-
112
- return { exitCode, output };
113
- },
114
- getContainerId: (containerName: string) =>
115
- getContainer(containerName).getId(),
116
- getContainerIpAddress: (containerName: string) => {
117
- const container = getContainer(containerName);
118
-
119
- const networkNames = container.getNetworkNames();
120
-
121
- return container.getIpAddress(networkNames[0]);
122
- },
123
- getContainersLogs: async () => {
124
- try {
125
- const { dockerode } = (await getContainerRuntimeClient()).container;
126
- const loggedContainers = await dockerode.listContainers();
127
-
128
- return loggedContainers.reduce((acc, container) => {
129
- const containerName = container.Names[0].replace('/', '');
130
- acc[containerName] = execSync(`docker logs -t ${container.Id}`, {
131
- stdio: 'pipe'
132
- }).toString('utf8');
133
-
134
- return acc;
135
- }, {});
136
- } catch (error) {
137
- console.warn('Cannot get containers logs');
138
- console.warn(error);
139
-
140
- return null;
141
- }
142
- },
143
- requestOnDatabase: async ({ database, query }) => {
144
- let container: StartedTestContainer | null = null;
145
-
146
- if (dockerEnvironment !== null) {
147
- container = dockerEnvironment.getContainer('db-1');
148
- } else {
149
- container = getContainer('web');
150
- }
151
-
152
- const client = await createConnection({
153
- database,
154
- host: container.getHost(),
155
- password: 'centreon',
156
- port: container.getMappedPort(3306),
157
- user: 'centreon'
158
- });
159
-
160
- const [rows, fields] = await client.query(query);
161
-
162
- await client.end();
163
-
164
- return [rows, fields];
165
- },
166
- startContainer: async ({
167
- command,
168
- image,
169
- name,
170
- portBindings = []
171
- }: StartContainerProps) => {
172
- let container = await new GenericContainer(image).withName(name);
173
-
174
- portBindings.forEach(({ source, destination }) => {
175
- container = container.withExposedPorts({
176
- container: source,
177
- host: destination
178
- });
179
- });
180
-
181
- if (command) {
182
- container
183
- .withCommand(['bash', '-c', command])
184
- .withWaitStrategy(Wait.forSuccessfulCommand('ls'));
185
- }
186
-
187
- containers[name] = await container.start();
188
-
189
- return container;
190
- },
191
- startContainers: async ({
192
- composeFile,
193
- databaseImage,
194
- openidImage,
195
- profiles,
196
- samlImage,
197
- webImage
198
- }) => {
199
- try {
200
- const composeFileDir = path.dirname(composeFile);
201
- const composeFileName = path.basename(composeFile);
202
-
203
- dockerEnvironment = await new DockerComposeEnvironment(
204
- composeFileDir,
205
- composeFileName
206
- )
207
- .withEnvironment({
208
- MYSQL_IMAGE: databaseImage,
209
- OPENID_IMAGE: openidImage,
210
- SAML_IMAGE: samlImage,
211
- WEB_IMAGE: webImage
212
- })
213
- .withProfiles(...profiles)
214
- .withStartupTimeout(120000)
215
- .withWaitStrategy(
216
- 'web-1',
217
- Wait.forAll([
218
- Wait.forHealthCheck(),
219
- Wait.forLogMessage('Centreon is ready')
220
- ])
221
- )
222
- .up();
223
-
224
- return null;
225
- } catch (error) {
226
- if (error instanceof Error) {
227
- console.error(error.message);
228
- }
229
-
230
- throw error;
231
- }
232
- },
233
- stopContainer: async ({ name }: StopContainerProps) => {
234
- if (containers[name]) {
235
- const container = containers[name];
236
-
237
- await container.stop();
238
-
239
- delete containers[name];
240
- }
241
-
242
- return null;
243
- },
244
- stopContainers: async () => {
245
- if (dockerEnvironment !== null) {
246
- await dockerEnvironment.down();
247
-
248
- dockerEnvironment = null;
249
- }
250
-
251
- return null;
252
- },
253
- waitOn: async (url: string) => {
254
- execSync(`npx wait-on ${url}`);
255
-
256
- return null;
257
- }
258
- });
259
- };
@@ -1,48 +0,0 @@
1
- module.exports = {
2
- extends: [ '../node/typescript.eslintrc.js'],
3
- overrides: [
4
- {
5
- files: ["*.spec.js", "*.test.ts", "*.tests.ts"],
6
- rules: {
7
- "import/first": 0,
8
- "import/order": 0,
9
- "@typescript-eslint/ban-ts-comment": 0,
10
- "@typescript-eslint/no-explicit-any": 0
11
- }
12
- }
13
- ],
14
- rules: {
15
- "import/extensions": ["off"],
16
- "no-console": "off",
17
- "no-underscore-dangle": "off",
18
- "class-methods-use-this": "off",
19
- "@typescript-eslint/naming-convention": [
20
- "error",
21
- {
22
- format: ["camelCase", "PascalCase", "UPPER_CASE"],
23
- selector: "variable"
24
- },
25
- {
26
- filter: {
27
- match: false,
28
- regex: "(__esModule|.+-.+)"
29
- },
30
- format: ["snake_case", "camelCase", "PascalCase", "UPPER_CASE"],
31
- selector: "property",
32
- leadingUnderscore: "allow"
33
- },
34
- {
35
- filter: {
36
- match: false,
37
- regex: "^_$"
38
- },
39
- format: ["snake_case", "camelCase", "PascalCase"],
40
- selector: "parameter"
41
- }
42
- ],
43
- "@typescript-eslint/require-array-sort-compare": "error"
44
- },
45
- parserOptions: {
46
- project: ["./tsconfig.json"]
47
- }
48
- }
@@ -1,49 +0,0 @@
1
- /*
2
- * Copyright 2023 Centreon Team
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- // For a detailed explanation regarding each configuration property, visit:
18
- // https://jestjs.io/docs/en/configuration.html
19
- const path = require('path');
20
-
21
- const rootPath = path.join(__dirname);
22
-
23
-
24
-
25
- module.exports = {
26
- rootDir: rootPath,
27
- // Automatically clear mock calls and instances between every test
28
- clearMocks: true,
29
- // The directory where Jest should output its coverage files
30
- coverageDirectory: '<rootDir>/coverage',
31
- // An array of regexp pattern strings used to skip coverage collection
32
- coveragePathIgnorePatterns: ['\\\\node_modules\\\\', 'tests'],
33
-
34
- // An array of file extensions your modules use
35
- moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
36
-
37
- // Automatically reset mock state between every test
38
- // resetMocks: true,
39
-
40
- testMatch: ['**/*.(test|tests|spec|specs).+(ts|tsx|js)'],
41
-
42
- // This option allows the use of a custom results processor
43
- // testResultsProcessor: 'jest-sonar-reporter',
44
-
45
- // A map from regular expressions to paths to transformers
46
- transform: {
47
- '^.+\\.(ts|tsx)$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.json' }],
48
- },
49
- };
@@ -1,71 +0,0 @@
1
- const isDev = process.env.NODE_ENV !== 'production';
2
-
3
- const excludeNodeModulesExceptCentreonUi =
4
- /node_modules(\\|\/)\.pnpm(\\|\/)(?!(@centreon|file\+packages\+ui-context))/;
5
-
6
- module.exports = {
7
- cache: false,
8
- excludeNodeModulesExceptCentreonUi,
9
- getModuleConfiguration: (enableCoverage) => ({
10
- rules: [
11
- {
12
- exclude: [excludeNodeModulesExceptCentreonUi],
13
- test: /\.[jt]sx?$/,
14
- use: {
15
- loader: 'swc-loader',
16
- options: {
17
- jsc: {
18
- experimental: {
19
- plugins: [
20
- enableCoverage && ['swc-plugin-coverage-instrument', {}]
21
- ].filter(Boolean)
22
- },
23
- parser: {
24
- syntax: 'typescript',
25
- tsx: true
26
- },
27
- transform: {
28
- react: {
29
- development: isDev,
30
- refresh: isDev
31
- }
32
- }
33
- }
34
- }
35
- }
36
- },
37
- {
38
- test: /\.icon.svg$/,
39
- use: ['@svgr/webpack']
40
- },
41
- {
42
- exclude: excludeNodeModulesExceptCentreonUi,
43
- test: /\.(bmp|png|jpg|jpeg|gif|svg)$/,
44
- type: 'asset/inline'
45
- },
46
- {
47
- generator: {
48
- filename: '[name][ext]'
49
- },
50
- test: /\.(woff|woff2|eot|ttf|otf)$/i,
51
- type: 'asset/resource'
52
- },
53
- {
54
- test: /\.css$/i,
55
- use: ['style-loader', 'css-loader']
56
- }
57
- ]
58
- }),
59
- optimization: {
60
- splitChunks: {
61
- chunks: 'all',
62
- maxSize: 400 * 1024
63
- }
64
- },
65
- output: {
66
- chunkFilename: '[name].[chunkhash:8].chunk.js',
67
- filename: '[name].[chunkhash:8].js',
68
- libraryTarget: 'umd',
69
- umdNamedDefine: true
70
- }
71
- };