html-reporter 8.0.2 → 8.3.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +44 -7
  3. package/lib/cli-commands/index.js +2 -1
  4. package/lib/cli-commands/remove-unused-screens/index.js +194 -0
  5. package/lib/cli-commands/remove-unused-screens/utils.js +159 -0
  6. package/lib/common-utils.js +52 -52
  7. package/lib/config/index.js +1 -1
  8. package/lib/constants/database.js +24 -4
  9. package/lib/db-utils/client.js +109 -0
  10. package/lib/db-utils/common.js +76 -0
  11. package/lib/db-utils/server.js +124 -0
  12. package/lib/gui/index.js +2 -1
  13. package/lib/gui/server.js +2 -1
  14. package/lib/gui/tool-runner/index.js +7 -7
  15. package/lib/gui/tool-runner/utils.js +10 -27
  16. package/lib/plugin-adapter.js +1 -1
  17. package/lib/plugin-api.js +17 -3
  18. package/lib/report-builder/static.js +1 -1
  19. package/lib/server-utils.js +1 -4
  20. package/lib/sqlite-adapter.js +3 -4
  21. package/lib/static/components/bottom-progress-bar/index.js +38 -0
  22. package/lib/static/components/gui.js +2 -0
  23. package/lib/static/components/report.js +2 -0
  24. package/lib/static/components/section/body/meta-info.js +1 -1
  25. package/lib/static/components/state/screenshot.js +1 -1
  26. package/lib/static/components/suites.js +39 -5
  27. package/lib/static/gui.min.css +1 -1
  28. package/lib/static/gui.min.js +19 -19
  29. package/lib/static/modules/action-names.js +2 -1
  30. package/lib/static/modules/actions.js +3 -3
  31. package/lib/static/modules/default-state.js +4 -1
  32. package/lib/static/modules/reducers/bottom-progress-bar.js +16 -0
  33. package/lib/static/modules/reducers/db.js +1 -1
  34. package/lib/static/modules/reducers/index.js +3 -1
  35. package/lib/static/modules/utils.js +0 -12
  36. package/lib/static/report.min.css +1 -1
  37. package/lib/static/report.min.js +20 -20
  38. package/lib/static/styles.css +41 -0
  39. package/lib/test-adapter.js +2 -1
  40. package/lib/tests-tree-builder/static.js +13 -13
  41. package/package.json +6 -1
  42. package/lib/constants/file-names.js +0 -6
  43. package/lib/static/modules/database-utils.js +0 -36
  44. package/lib/static/modules/sqlite.js +0 -152
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ <a name="8.3.0"></a>
6
+ # [8.3.0](https://github.com/gemini-testing/html-reporter/compare/v8.2.0...v8.3.0) (2022-03-01)
7
+
8
+
9
+ ### Features
10
+
11
+ * cli command to remove unused screens ([#415](https://github.com/gemini-testing/html-reporter/issues/415)) ([c4a3d38](https://github.com/gemini-testing/html-reporter/commit/c4a3d38))
12
+
13
+
14
+
15
+ <a name="8.2.0"></a>
16
+ # [8.2.0](https://github.com/gemini-testing/html-reporter/compare/v8.1.0...v8.2.0) (2022-01-27)
17
+
18
+
19
+ ### Features
20
+
21
+ * do not put space before title if there is no root suite ([f905879](https://github.com/gemini-testing/html-reporter/commit/f905879))
22
+
23
+
24
+
25
+ <a name="8.1.0"></a>
26
+ # [8.1.0](https://github.com/gemini-testing/html-reporter/compare/v8.0.2...v8.1.0) (2022-01-13)
27
+
28
+
29
+ ### Features
30
+
31
+ * implemented progress-bar of scroll ([49d5631](https://github.com/gemini-testing/html-reporter/commit/49d5631))
32
+
33
+
34
+
5
35
  <a name="8.0.2"></a>
6
36
  ## [8.0.2](https://github.com/gemini-testing/html-reporter/compare/v8.0.1...v8.0.2) (2021-12-28)
7
37
 
package/README.md CHANGED
@@ -425,6 +425,40 @@ Example of usage:
425
425
  npx hermione gui
426
426
  ```
427
427
 
428
+ ### remove-unused-screens
429
+
430
+ Command that adds ability to remove all unused reference images. On first step it looks for screenshots for which there are no tests on the file system. On the second step it looks for screenshots that were not used in a successful test (the result of the tests is taken from the sqlite database). For the correct execution of the second step html-report should exist on the file system and contain the result of the tests. It means you should run tests locally or download report from CI.
431
+
432
+ ```
433
+ npx hermione remove-unused-screens --help
434
+ ```
435
+
436
+ shows the following:
437
+ ```
438
+ Usage: remove-unused-screens [options]
439
+
440
+ remove screenshots which were not used when running tests
441
+
442
+ Options:
443
+
444
+ -p, --pattern <pattern> pattern for searching screenshots on the file system
445
+ --skip-questions do not ask questions during execution (default values will be used)
446
+ -h, --help output usage information
447
+
448
+ Example of usage:
449
+ Specify the folder in which all reference screenshots are located:
450
+ npx hermione remove-unused-screens -p hermione-screens-folder
451
+
452
+ Specify the mask by which all reference screenshots will be found:
453
+ npx hermione remove-unused-screens -p 'screens/**/*.png'
454
+
455
+ Specify few masks by which all reference screenshots will be found:
456
+ npx hermione remove-unused-screens -p 'screens/**/chrome/*.png' -p 'screens/**/firefox/*.png'
457
+
458
+ Don't ask me about anything and just delete unused reference screenshots:
459
+ npx hermione remove-unused-screens -p 'hermione-screens-folder' --skip-questions
460
+ ```
461
+
428
462
  ### merge-reports
429
463
 
430
464
  Command that adds ability to merge reports which are created after running the tests.
@@ -476,13 +510,16 @@ Html-reporter adds to `hermione` object with its own API.
476
510
 
477
511
  **Properties of the `hermione.htmlReporter` object**
478
512
 
479
- Property name | Description
480
- ------------------------- | -------------
481
- `events` | Events list for subscription.
482
- `extraItems` | Items list which will be added to the menu bar.
483
- `metaInfoExtenders` | Items list which will be added to the meta info.
484
- `imagesSaver` | Interface to save image into user storage.
485
- `reportsSaver` | Interface to save sqlite database into user storage.
513
+ Property name | Description
514
+ -------------------------- | -------------
515
+ `events` | Events list for subscription.
516
+ `extraItems` | Items list which will be added to the menu bar.
517
+ `metaInfoExtenders` | Items list which will be added to the meta info.
518
+ `imagesSaver` | Interface to save image into user storage.
519
+ `reportsSaver` | Interface to save sqlite database into user storage.
520
+ `downloadDatabases` | Method to download all databases from `databaseUrls.json` file.
521
+ `mergeDatabases` | Method to merge passed databases to passed report path.
522
+ `getTestsTreeFromDatabase` | Method to get tests tree from passed database.
486
523
 
487
524
  **Available events which are triggered in the main process**
488
525
 
@@ -2,5 +2,6 @@
2
2
 
3
3
  module.exports = {
4
4
  GUI: 'gui',
5
- MERGE_REPORTS: 'merge-reports'
5
+ MERGE_REPORTS: 'merge-reports',
6
+ REMOVE_UNUSED_SCREENS: 'remove-unused-screens'
6
7
  };
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fs = require('fs-extra');
5
+ const _ = require('lodash');
6
+ const ora = require('ora');
7
+ const chalk = require('chalk');
8
+ const filesize = require('filesize');
9
+ const Promise = require('bluebird');
10
+
11
+ const {REMOVE_UNUSED_SCREENS: commandName} = require('..');
12
+ const {getTestsFromFs, findScreens, askQuestion, identifyOutdatedScreens, identifyUnusedScreens, removeScreens} = require('./utils');
13
+ const {DATABASE_URLS_JSON_NAME, LOCAL_DATABASE_NAME} = require('../../constants/database');
14
+ const {logger} = require('../../common-utils');
15
+
16
+ module.exports = (program, pluginConfig, hermione) => {
17
+ program
18
+ .command(commandName)
19
+ .description('remove screenshots which were not used when running tests')
20
+ .option('-p, --pattern <pattern>', 'pattern for searching screenshots on the file system', collect)
21
+ .option('--skip-questions', 'do not ask questions during execution (default values will be used)')
22
+ .on('--help', () => logger.log(getHelpMessage()))
23
+ .action(async (options) => {
24
+ try {
25
+ const {pattern: userPatterns} = options;
26
+
27
+ if (_.isEmpty(userPatterns)) {
28
+ throw new Error(`option "pattern" is required. See examples of usage: ${chalk.green(`npx hermione ${commandName} --help`)}`);
29
+ }
30
+
31
+ const userScreenPatterns = transformPatternOption(userPatterns);
32
+ const spinner = ora({spinner: 'point'});
33
+
34
+ spinner.start('Reading hermione tests from file system');
35
+ const fsTests = await getTestsFromFs(hermione);
36
+ spinner.succeed();
37
+
38
+ logger.log(`${chalk.green(Object.keys(fsTests.byId).length)} tests were read`);
39
+
40
+ spinner.start(`Searching reference images on the file system by specified patterns:\n${userScreenPatterns.join('\n')}`);
41
+ const foundScreenPaths = await findScreens(userScreenPatterns);
42
+ spinner.succeed();
43
+
44
+ logger.log(`Found ${chalk.green(foundScreenPaths.length)} reference images`);
45
+
46
+ const shouldIdentifyOutdated = await askQuestion({
47
+ name: 'identifyOutdated',
48
+ type: 'confirm',
49
+ message: 'Identify outdated reference images (tests for them are removed)?',
50
+ default: true
51
+ }, options);
52
+
53
+ if (shouldIdentifyOutdated) {
54
+ await handleOutdatedScreens(foundScreenPaths, fsTests.screenPatterns, {spinner, cliOpts: options});
55
+ }
56
+
57
+ const shouldIdentifyUnused = await askQuestion({
58
+ name: 'identifyUnused',
59
+ type: 'confirm',
60
+ message: 'Identify unused reference images (tests passed successfully for them, but they were not used during execution)?',
61
+ default: true
62
+ }, options);
63
+
64
+ if (shouldIdentifyUnused) {
65
+ await handleUnusedScreens(foundScreenPaths, fsTests, {hermione, pluginConfig, spinner, cliOpts: options});
66
+ }
67
+ } catch (err) {
68
+ logger.error(err.stack || err);
69
+ process.exit(1);
70
+ }
71
+ });
72
+ };
73
+
74
+ async function handleOutdatedScreens(screenPaths, screenPatterns, opts = {}) {
75
+ const {spinner} = opts;
76
+
77
+ spinner.start(`Identifying outdated reference images (tests for these images do not exist)`);
78
+ const outdatedScreenPaths = identifyOutdatedScreens(screenPaths, screenPatterns);
79
+ spinner.succeed();
80
+
81
+ await handleScreens(screenPaths, {paths: outdatedScreenPaths, type: 'outdated'}, opts);
82
+ }
83
+
84
+ async function handleUnusedScreens(screenPaths, fsTests, opts = {}) {
85
+ const {hermione, pluginConfig, spinner, cliOpts} = opts;
86
+ const mainDatabaseUrls = path.resolve(pluginConfig.path, DATABASE_URLS_JSON_NAME);
87
+
88
+ const isReportPathExists = await fs.pathExists(pluginConfig.path);
89
+ if (!isReportPathExists) {
90
+ throw new Error(`Can't find html-report in "${pluginConfig.path}" folder. You should run tests or download report from CI`);
91
+ }
92
+
93
+ spinner.start('Loading databases with the test results in order to identify unused screenshots in tests');
94
+ const dbPaths = await hermione.htmlReporter.downloadDatabases([mainDatabaseUrls], {pluginConfig});
95
+ spinner.succeed();
96
+
97
+ if (_.isEmpty(dbPaths)) {
98
+ throw new Error(`Databases were not loaded from "${mainDatabaseUrls}" file`);
99
+ }
100
+
101
+ const mergedDbPath = path.resolve(pluginConfig.path, LOCAL_DATABASE_NAME);
102
+ const srcDbPaths = dbPaths.filter((dbPath) => dbPath !== mergedDbPath);
103
+
104
+ if (!_.isEmpty(srcDbPaths)) {
105
+ spinner.start('Merging databases');
106
+ await hermione.htmlReporter.mergeDatabases(srcDbPaths, pluginConfig.path);
107
+ spinner.succeed();
108
+
109
+ logger.log(`${chalk.green(srcDbPaths.length)} databases were merged to ${chalk.green(mergedDbPath)}`);
110
+ }
111
+
112
+ spinner.start(`Identifying unused reference images (tests passed successfully for them, but they were not used during execution)`);
113
+ const unusedScreenPaths = identifyUnusedScreens(fsTests, {hermione, mergedDbPath});
114
+ spinner.succeed();
115
+
116
+ await handleScreens(screenPaths, {paths: unusedScreenPaths, type: 'unused'}, {spinner, cliOpts});
117
+ }
118
+
119
+ async function handleScreens(allScreenPaths, screensToRemove, {spinner, cliOpts} = {}) {
120
+ const screenPathsToRemoveLen = screensToRemove.paths.length;
121
+
122
+ logger.log(
123
+ `Found ${chalk[screenPathsToRemoveLen > 0 ? 'red' : 'green'](screenPathsToRemoveLen)} ` +
124
+ `${screensToRemove.type} reference images out of ${chalk.bold(allScreenPaths.length)}`
125
+ );
126
+
127
+ if (_.isEmpty(screensToRemove.paths)) {
128
+ return;
129
+ }
130
+
131
+ spinner.start(`Calculating total size of ${screensToRemove.type} reference images`);
132
+ const bytes = (await Promise.map(screensToRemove.paths, (screenPath) => fs.stat(screenPath))).reduce((acc, {size}) => acc + size, 0);
133
+ spinner.succeed();
134
+
135
+ logger.log(`Total size of ${screensToRemove.type} reference images = ${chalk.red(filesize(bytes))}`);
136
+
137
+ const shouldShowList = await askQuestion({
138
+ name: 'shouldShowList',
139
+ type: 'confirm',
140
+ message: `Show list of ${screensToRemove.type} reference images? (${screenPathsToRemoveLen} paths)`,
141
+ default: false
142
+ }, cliOpts);
143
+
144
+ if (shouldShowList) {
145
+ logger.log(`List of ${screensToRemove.type} reference images:\n${screensToRemove.paths.map((p) => chalk.red(p)).join('\n')}`);
146
+ }
147
+
148
+ const shouldRemove = await askQuestion({
149
+ name: 'shouldRemove',
150
+ type: 'confirm',
151
+ message: `Remove ${screensToRemove.type} reference images?`,
152
+ default: true
153
+ }, cliOpts);
154
+
155
+ if (!shouldRemove) {
156
+ return;
157
+ }
158
+
159
+ spinner.start(`Removing ${screensToRemove.type} reference images`);
160
+ await removeScreens(screensToRemove.paths);
161
+ spinner.succeed();
162
+
163
+ logger.log(`${chalk.green(screenPathsToRemoveLen)} reference images were removed`);
164
+ }
165
+
166
+ function collect(newValue, array = []) {
167
+ return array.concat(newValue);
168
+ }
169
+
170
+ function getHelpMessage() {
171
+ const rmUnusedScreens = `npx hermione ${commandName}`;
172
+
173
+ return `
174
+ Example of usage:
175
+ Specify the folder in which all reference screenshots are located:
176
+ ${chalk.green(`${rmUnusedScreens} -p 'hermione-screens-folder'`)}
177
+
178
+ Specify the mask by which all reference screenshots will be found:
179
+ ${chalk.green(`${rmUnusedScreens} -p 'screens/**/*.png'`)}
180
+
181
+ Specify few masks by which all reference screenshots will be found:
182
+ ${chalk.green(`${rmUnusedScreens} -p 'screens/**/chrome/*.png' -p 'screens/**/firefox/*.png'`)}
183
+
184
+ Don't ask me about anything and just delete unused reference screenshots:
185
+ ${chalk.green(`${rmUnusedScreens} -p 'hermione-screens-folder' --skip-questions`)}`;
186
+ }
187
+
188
+ function transformPatternOption(patterns) {
189
+ return patterns.map(p => {
190
+ const resolvedPattern = path.resolve(process.cwd(), p);
191
+
192
+ return resolvedPattern.endsWith('.png') ? resolvedPattern : path.join(resolvedPattern, '*.png');
193
+ });
194
+ }
@@ -0,0 +1,159 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const _ = require('lodash');
5
+ const fg = require('fast-glob');
6
+ const Promise = require('bluebird');
7
+ const fs = require('fs-extra');
8
+ const inquirer = require('inquirer');
9
+
10
+ const {SUCCESS} = require('../../constants/test-statuses');
11
+
12
+ exports.getTestsFromFs = async (hermione) => {
13
+ const testsTree = {
14
+ byId: {},
15
+ screenPatterns: []
16
+ };
17
+
18
+ const testCollection = await hermione.readTests();
19
+
20
+ testCollection.eachTest((test, browserId) => {
21
+ const id = `${test.fullTitle()} ${browserId}`;
22
+ const screenPattern = hermione.config.browsers[browserId].getScreenshotPath(test, '*');
23
+
24
+ testsTree.byId[id] = {screenPattern, ...test};
25
+ });
26
+
27
+ for (const test of Object.values(testsTree.byId)) {
28
+ test.screenPaths = (await fg(test.screenPattern)) || [];
29
+ testsTree.screenPatterns.push(test.screenPattern);
30
+ }
31
+
32
+ return testsTree;
33
+ };
34
+
35
+ exports.findScreens = async (screenPatterns) => {
36
+ return _(await Promise.map(screenPatterns, pattern => fg(pattern))).flatten().uniq().value();
37
+ };
38
+
39
+ exports.askQuestion = async (question, {skipQuestions} = {}) => {
40
+ if (skipQuestions) {
41
+ return question.default;
42
+ }
43
+
44
+ const res = await inquirer.prompt([question]);
45
+
46
+ return res[question.name];
47
+ };
48
+
49
+ exports.identifyOutdatedScreens = (screenPaths, screenPatterns) => {
50
+ const shortenedScreenPaths = screenPaths.map(screenPath => path.relative(process.cwd(), screenPath));
51
+ const shortenedPatterns = screenPatterns.map(pattern => path.dirname(path.relative(process.cwd(), pattern)));
52
+ const outdatedScreens = [];
53
+
54
+ for (const screenPath of shortenedScreenPaths) {
55
+ const isFound = shortenedPatterns.some(pattern => screenPath.startsWith(pattern));
56
+
57
+ if (!isFound) {
58
+ outdatedScreens.push(screenPath);
59
+ }
60
+ }
61
+
62
+ return outdatedScreens;
63
+ };
64
+
65
+ exports.identifyUnusedScreens = (fsTests, {hermione, mergedDbPath} = {}) => {
66
+ const dbTree = hermione.htmlReporter.getTestsTreeFromDatabase(mergedDbPath);
67
+ const screenPathsBySuccessTests = getScreenPathsBySuccessTests(dbTree);
68
+ const unusedScreens = [];
69
+
70
+ for (const testId of Object.keys(screenPathsBySuccessTests)) {
71
+ const usedScreenPaths = screenPathsBySuccessTests[testId];
72
+ const successTest = fsTests.byId[testId];
73
+
74
+ if (!successTest) {
75
+ continue;
76
+ }
77
+
78
+ successTest.screenPaths.forEach(fsScreenPath => {
79
+ const isUsed = usedScreenPaths.some(usedScreenPath => fsScreenPath.endsWith(usedScreenPath));
80
+
81
+ if (!isUsed) {
82
+ unusedScreens.push(fsScreenPath);
83
+ }
84
+ });
85
+ }
86
+
87
+ return unusedScreens;
88
+ };
89
+
90
+ // in tree.browsers there are info about uniq tests in each browser
91
+ function getScreenPathsBySuccessTests(tree) {
92
+ const successTree = {};
93
+
94
+ for (const browserId of tree.browsers.allIds) {
95
+ const browser = tree.browsers.byId[browserId];
96
+ const lastResultId = _.last(browser.resultIds);
97
+ const lastResult = tree.results.byId[lastResultId];
98
+
99
+ if (lastResult.status !== SUCCESS || _.isEmpty(lastResult.imageIds)) {
100
+ continue;
101
+ }
102
+
103
+ const screenPaths = lastResult.imageIds.map(imageId => `${tree.images.byId[imageId].stateName}.png`);
104
+
105
+ successTree[browserId] = screenPaths;
106
+ }
107
+
108
+ return successTree;
109
+ }
110
+
111
+ exports.removeScreens = async (screenPaths) => {
112
+ for (let screenPath of screenPaths) {
113
+ await fs.remove(screenPath);
114
+ }
115
+
116
+ const screenPathDirs = getUniqPathDirs(screenPaths);
117
+
118
+ await clearEmptyDirs(screenPathDirs);
119
+ };
120
+
121
+ async function clearEmptyDirs(dirs) {
122
+ const clearedDirs = [];
123
+
124
+ for (let dir of dirs) {
125
+ try {
126
+ const files = await fs.readdir(dir);
127
+
128
+ if (arePathsHidden(files)) {
129
+ for (let file of files) {
130
+ await fs.remove(file);
131
+ }
132
+ } else {
133
+ continue;
134
+ }
135
+
136
+ await fs.remove(dir);
137
+
138
+ clearedDirs.push(dir);
139
+ } catch (err) {
140
+ if (err.code !== 'ENOENT') {
141
+ throw err;
142
+ }
143
+ }
144
+ }
145
+
146
+ if (_.isEmpty(clearedDirs)) {
147
+ return;
148
+ }
149
+
150
+ await clearEmptyDirs(getUniqPathDirs(clearedDirs));
151
+ }
152
+
153
+ function arePathsHidden(files) {
154
+ return files.every(file => file.startsWith('.'));
155
+ }
156
+
157
+ function getUniqPathDirs(paths) {
158
+ return _.uniq(paths.map((p) => path.dirname(p)));
159
+ }
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ const {pick} = require('lodash');
4
+ const url = require('url');
5
+ const axios = require('axios');
6
+
3
7
  const {
4
8
  SUCCESS,
5
9
  FAIL,
@@ -10,11 +14,6 @@ const {
10
14
  RUNNING,
11
15
  QUEUED
12
16
  } = require('./constants/test-statuses');
13
- const {
14
- DB_MAX_AVAILABLE_PAGE_SIZE,
15
- DB_SUITES_TABLE_NAME,
16
- DB_TYPES
17
- } = require('./constants/database');
18
17
 
19
18
  const statusPriority = [
20
19
  // non-final
@@ -24,6 +23,8 @@ const statusPriority = [
24
23
  ERROR, FAIL, UPDATED, SUCCESS, IDLE, SKIPPED
25
24
  ];
26
25
 
26
+ exports.logger = pick(console, ['log', 'warn', 'error']);
27
+
27
28
  exports.isSuccessStatus = (status) => status === SUCCESS;
28
29
  exports.isFailStatus = (status) => status === FAIL;
29
30
  exports.isIdleStatus = (status) => status === IDLE;
@@ -32,30 +33,6 @@ exports.isErroredStatus = (status) => status === ERROR;
32
33
  exports.isSkippedStatus = (status) => status === SKIPPED;
33
34
  exports.isUpdatedStatus = (status) => status === UPDATED;
34
35
 
35
- exports.selectAllQuery = (tableName) => `SELECT * FROM ${tableName}`;
36
- exports.selectAllSuitesQuery = () => exports.selectAllQuery(DB_SUITES_TABLE_NAME);
37
-
38
- exports.suitesTableColumns = [
39
- {name: 'suitePath', type: DB_TYPES.text},
40
- {name: 'suiteName', type: DB_TYPES.text},
41
- {name: 'name', type: DB_TYPES.text},
42
- {name: 'suiteUrl', type: DB_TYPES.text},
43
- {name: 'metaInfo', type: DB_TYPES.text},
44
- {name: 'description', type: DB_TYPES.text},
45
- {name: 'error', type: DB_TYPES.text},
46
- {name: 'skipReason', type: DB_TYPES.text},
47
- {name: 'imagesInfo', type: DB_TYPES.text},
48
- {name: 'screenshot', type: DB_TYPES.int}, //boolean - 0 or 1
49
- {name: 'multipleTabs', type: DB_TYPES.int}, //boolean - 0 or 1
50
- {name: 'status', type: DB_TYPES.text},
51
- {name: 'timestamp', type: DB_TYPES.int}
52
- ];
53
-
54
- exports.dbColumnIndexes = exports.suitesTableColumns.reduce((acc, {name}, index) => {
55
- acc[name] = index;
56
- return acc;
57
- }, {});
58
-
59
36
  exports.determineStatus = (statuses) => {
60
37
  if (!statuses.length) {
61
38
  return SUCCESS;
@@ -71,36 +48,59 @@ exports.determineStatus = (statuses) => {
71
48
  console.error('Unknown statuses: ' + JSON.stringify(statuses));
72
49
  };
73
50
 
74
- exports.createTablesQuery = () => [
75
- createTableQuery(DB_SUITES_TABLE_NAME, exports.suitesTableColumns)
76
- ];
51
+ exports.isUrl = (str) => {
52
+ if (typeof str !== 'string') {
53
+ return false;
54
+ }
77
55
 
78
- function createTableQuery(tableName, columns) {
79
- const formattedColumns = columns
80
- .map(({name, type}) => `${name} ${type}`)
81
- .join(', ');
56
+ const parsedUrl = url.parse(str);
82
57
 
83
- return `CREATE TABLE IF NOT EXISTS ${tableName} (${formattedColumns})`;
84
- }
58
+ return parsedUrl.host && parsedUrl.protocol;
59
+ };
85
60
 
86
- exports.mergeTables = ({db, dbPaths, getExistingTables = () => {}}) => {
87
- db.prepare(`PRAGMA page_size = ${DB_MAX_AVAILABLE_PAGE_SIZE}`).run();
61
+ exports.fetchFile = async (url, options) => {
62
+ try {
63
+ const {data, status} = await axios.get(url, options);
88
64
 
89
- for (const dbPath of dbPaths) {
90
- db.prepare(`ATTACH '${dbPath}' AS attached`).run();
65
+ return {data, status};
66
+ } catch (e) {
67
+ exports.logger.warn(`Error while fetching ${url}`, e);
91
68
 
92
- const getTablesStatement = db.prepare(`SELECT name FROM attached.sqlite_master WHERE type='table'`);
93
- const tables = getExistingTables(getTablesStatement);
69
+ // 'unknown' for request blocked by CORS policy
70
+ const status = e.response ? e.response.status : 'unknown';
94
71
 
95
- for (const tableName of tables) {
96
- db.prepare(`CREATE TABLE IF NOT EXISTS ${tableName} AS SELECT * FROM attached.${tableName} LIMIT 0`).run();
97
- db.prepare(`INSERT OR IGNORE INTO ${tableName} SELECT * FROM attached.${tableName}`).run();
98
- }
99
-
100
- db.prepare(`DETACH attached`).run();
72
+ return {data: null, status};
101
73
  }
102
74
  };
103
75
 
104
- exports.compareDatabaseRowsByTimestamp = (row1, row2) => {
105
- return row1[exports.dbColumnIndexes.timestamp] - row2[exports.dbColumnIndexes.timestamp];
76
+ exports.normalizeUrls = (urls = [], baseUrl) => {
77
+ const baseUrlsSearch = new URL(baseUrl).search;
78
+
79
+ return urls.map(url => {
80
+ try {
81
+ const newUrl = new URL(url, baseUrl);
82
+
83
+ // URL's parameters can specify directory at file server
84
+ if (isRelativeUrl(url) && !newUrl.search) {
85
+ newUrl.search = baseUrlsSearch;
86
+ }
87
+
88
+ return newUrl.href;
89
+ } catch (e) {
90
+ exports.logger.warn(`Can not normalize url '${url} for base url '${baseUrl}'`, e);
91
+
92
+ return url;
93
+ }
94
+ });
106
95
  };
96
+
97
+ function isRelativeUrl(url) {
98
+ try {
99
+ // eslint-disable-next-line no-new
100
+ new URL(url);
101
+
102
+ return false;
103
+ } catch (e) {
104
+ return true;
105
+ }
106
+ }
@@ -4,7 +4,7 @@ const _ = require('lodash');
4
4
  const configParser = require('gemini-configparser');
5
5
  const chalk = require('chalk');
6
6
 
7
- const {logger} = require('../server-utils');
7
+ const {logger} = require('../common-utils');
8
8
  const {config: configDefaults} = require('../constants/defaults');
9
9
  const saveFormats = require('../constants/save-formats');
10
10
  const {assertCustomGui} = require('./custom-gui-asserts');
@@ -1,10 +1,30 @@
1
1
  'use strict';
2
2
 
3
+ const DB_TYPES = {int: 'INT', text: 'TEXT'};
4
+ const SUITES_TABLE_COLUMNS = [
5
+ {name: 'suitePath', type: DB_TYPES.text},
6
+ {name: 'suiteName', type: DB_TYPES.text},
7
+ {name: 'name', type: DB_TYPES.text},
8
+ {name: 'suiteUrl', type: DB_TYPES.text},
9
+ {name: 'metaInfo', type: DB_TYPES.text},
10
+ {name: 'description', type: DB_TYPES.text},
11
+ {name: 'error', type: DB_TYPES.text},
12
+ {name: 'skipReason', type: DB_TYPES.text},
13
+ {name: 'imagesInfo', type: DB_TYPES.text},
14
+ {name: 'screenshot', type: DB_TYPES.int}, //boolean - 0 or 1
15
+ {name: 'multipleTabs', type: DB_TYPES.int}, //boolean - 0 or 1
16
+ {name: 'status', type: DB_TYPES.text},
17
+ {name: 'timestamp', type: DB_TYPES.int}
18
+ ];
19
+
3
20
  module.exports = {
4
21
  DB_MAX_AVAILABLE_PAGE_SIZE: 65536, // helps to speed up queries
5
22
  DB_SUITES_TABLE_NAME: 'suites',
6
- DB_TYPES: {
7
- int: 'INT',
8
- text: 'TEXT'
9
- }
23
+ SUITES_TABLE_COLUMNS,
24
+ LOCAL_DATABASE_NAME: 'sqlite.db',
25
+ DATABASE_URLS_JSON_NAME: 'databaseUrls.json',
26
+ DB_COLUMN_INDEXES: SUITES_TABLE_COLUMNS.reduce((acc, {name}, index) => {
27
+ acc[name] = index;
28
+ return acc;
29
+ }, {})
10
30
  };