@code-pushup/utils 0.1.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.
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@code-pushup/utils",
3
+ "version": "0.1.0",
4
+ "dependencies": {
5
+ "@code-pushup/models": "*",
6
+ "bundle-require": "^4.0.1",
7
+ "chalk": "^5.3.0",
8
+ "@isaacs/cliui": "^8.0.2",
9
+ "simple-git": "^3.20.0",
10
+ "multi-progress-bars": "^5.0.3",
11
+ "cli-table3": "^0.6.3"
12
+ },
13
+ "type": "module",
14
+ "main": "./index.js",
15
+ "types": "./src/index.d.ts"
16
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { CliArgsObject, ProcessConfig, ProcessError, ProcessObserver, ProcessResult, executeProcess, objectToCliArgs, } from './lib/execute-process';
2
+ export { getLatestCommit, git } from './lib/git';
3
+ export { ProgressBar, getProgressBar } from './lib/progress';
4
+ export { CODE_PUSHUP_DOMAIN, FOOTER_PREFIX, README_LINK, calcDuration, compareIssueSeverity, loadReport, } from './lib/report';
5
+ export { reportToMd } from './lib/report-to-md';
6
+ export { reportToStdout } from './lib/report-to-stdout';
7
+ export { ScoredReport, scoreReport } from './lib/scoring';
8
+ export { readJsonFile, readTextFile, toUnixPath, ensureDirectoryExists, FileResult, MultipleFileResults, logMultipleFileResults, importEsmModule, pluginWorkDir, crawlFileSystem, findLineNumberInText, } from './lib/file-system';
9
+ export { verboseUtils } from './lib/verbose-utils';
10
+ export { toArray, objectToKeys, objectToEntries, countOccurrences, distinct, } from './lib/transformation';
11
+ export { slugify, pluralize, pluralizeToken, formatBytes, formatDuration, } from './lib/formatting';
12
+ export { NEW_LINE } from './lib/md';
13
+ export { logMultipleResults } from './lib/log-results';
14
+ export { isPromiseFulfilledResult, isPromiseRejectedResult, } from './lib/guards';
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Represents the process result.
3
+ * @category Types
4
+ * @public
5
+ * @property {string} stdout - The stdout of the process.
6
+ * @property {string} stderr - The stderr of the process.
7
+ * @property {number | null} code - The exit code of the process.
8
+ */
9
+ export type ProcessResult = {
10
+ stdout: string;
11
+ stderr: string;
12
+ code: number | null;
13
+ date: string;
14
+ duration: number;
15
+ };
16
+ /**
17
+ * Error class for process errors.
18
+ * Contains additional information about the process result.
19
+ * @category Error
20
+ * @public
21
+ * @class
22
+ * @extends Error
23
+ * @example
24
+ * const result = await executeProcess({})
25
+ * .catch((error) => {
26
+ * if (error instanceof ProcessError) {
27
+ * console.error(error.code);
28
+ * console.error(error.stderr);
29
+ * console.error(error.stdout);
30
+ * }
31
+ * });
32
+ *
33
+ */
34
+ export declare class ProcessError extends Error {
35
+ code: number | null;
36
+ stderr: string;
37
+ stdout: string;
38
+ constructor(result: ProcessResult);
39
+ }
40
+ /**
41
+ * Process config object. Contains the command, args and observer.
42
+ * @param cfg - process config object with command, args and observer (optional)
43
+ * @category Types
44
+ * @public
45
+ * @property {string} command - The command to execute.
46
+ * @property {string[]} args - The arguments for the command.
47
+ * @property {ProcessObserver} observer - The observer for the process.
48
+ *
49
+ * @example
50
+ *
51
+ * // bash command
52
+ * const cfg = {
53
+ * command: 'bash',
54
+ * args: ['-c', 'echo "hello world"']
55
+ * };
56
+ *
57
+ * // node command
58
+ * const cfg = {
59
+ * command: 'node',
60
+ * args: ['--version']
61
+ * };
62
+ *
63
+ * // npx command
64
+ * const cfg = {
65
+ * command: 'npx',
66
+ * args: ['--version']
67
+ *
68
+ */
69
+ export type ProcessConfig = {
70
+ command: string;
71
+ args?: string[];
72
+ cwd?: string;
73
+ observer?: ProcessObserver;
74
+ };
75
+ /**
76
+ * Process observer object. Contains the onStdout, error and complete function.
77
+ * @category Types
78
+ * @public
79
+ * @property {function} onStdout - The onStdout function of the observer (optional).
80
+ * @property {function} onError - The error function of the observer (optional).
81
+ * @property {function} onComplete - The complete function of the observer (optional).
82
+ *
83
+ * @example
84
+ * const observer = {
85
+ * onStdout: (stdout) => console.info(stdout)
86
+ * }
87
+ */
88
+ export type ProcessObserver = {
89
+ onStdout?: (stdout: string) => void;
90
+ onError?: (error: ProcessError) => void;
91
+ onComplete?: () => void;
92
+ };
93
+ /**
94
+ * Executes a process and returns a promise with the result as `ProcessResult`.
95
+ *
96
+ * @example
97
+ *
98
+ * // sync process execution
99
+ * const result = await executeProcess({
100
+ * command: 'node',
101
+ * args: ['--version']
102
+ * });
103
+ *
104
+ * console.info(result);
105
+ *
106
+ * // async process execution
107
+ * const result = await executeProcess({
108
+ * command: 'node',
109
+ * args: ['download-data.js'],
110
+ * observer: {
111
+ * onStdout: updateProgress,
112
+ * error: handleError,
113
+ * complete: cleanLogs,
114
+ * }
115
+ * });
116
+ *
117
+ * console.info(result);
118
+ *
119
+ * @param cfg - see {@link ProcessConfig}
120
+ */
121
+ export declare function executeProcess(cfg: ProcessConfig): Promise<ProcessResult>;
122
+ type ArgumentValue = number | string | boolean | string[];
123
+ export type CliArgsObject<T extends object = Record<string, ArgumentValue>> = T extends never ? Record<string, ArgumentValue | undefined> | {
124
+ _: string;
125
+ } : T;
126
+ /**
127
+ * Converts an object with different types of values into an array of command-line arguments.
128
+ *
129
+ * @example
130
+ * const args = objectToProcessArgs({
131
+ * _: ['node', 'index.js'], // node index.js
132
+ * name: 'Juanita', // --name=Juanita
133
+ * formats: ['json', 'md'] // --format=json --format=md
134
+ * });
135
+ */
136
+ export declare function objectToCliArgs<T extends object = Record<string, ArgumentValue>>(params?: CliArgsObject<T>): string[];
137
+ export {};
@@ -0,0 +1,21 @@
1
+ import { type Options } from 'bundle-require';
2
+ export declare function toUnixPath(path: string, options?: {
3
+ toRelative?: boolean;
4
+ }): string;
5
+ export declare function ensureDirectoryExists(baseDir: string): Promise<void>;
6
+ export declare function readTextFile(path: string): Promise<string>;
7
+ export declare function readJsonFile<T = unknown>(path: string): Promise<T>;
8
+ export type FileResult = readonly [string] | readonly [string, number];
9
+ export type MultipleFileResults = PromiseSettledResult<FileResult>[];
10
+ export declare function logMultipleFileResults(fileResults: MultipleFileResults, messagePrefix: string): void;
11
+ export declare class NoExportError extends Error {
12
+ constructor(filepath: string);
13
+ }
14
+ export declare function importEsmModule<T = unknown>(options: Options, parse?: (d: unknown) => T): Promise<T>;
15
+ export declare function pluginWorkDir(slug: string): string;
16
+ export declare function crawlFileSystem<T = string>(options: {
17
+ directory: string;
18
+ pattern?: string | RegExp;
19
+ fileTransform?: (filePath: string) => Promise<T> | T;
20
+ }): Promise<T[]>;
21
+ export declare function findLineNumberInText(content: string, pattern: string): number | null;
@@ -0,0 +1,5 @@
1
+ export declare function slugify(text: string): string;
2
+ export declare function pluralize(text: string): string;
3
+ export declare function formatBytes(bytes: number, decimals?: number): string;
4
+ export declare function pluralizeToken(token: string, times?: number): string;
5
+ export declare function formatDuration(duration: number): string;
@@ -0,0 +1,13 @@
1
+ export type CommitData = {
2
+ hash: string;
3
+ message: string;
4
+ author: string;
5
+ date: string;
6
+ };
7
+ export declare const git: import("simple-git").SimpleGit;
8
+ export declare function getLatestCommit(): Promise<({
9
+ hash: string;
10
+ message: string;
11
+ author: string;
12
+ date: string;
13
+ } & import("simple-git").ListLogLine) | null>;
@@ -0,0 +1,2 @@
1
+ export declare function isPromiseFulfilledResult<T>(result: PromiseSettledResult<T>): result is PromiseFulfilledResult<T>;
2
+ export declare function isPromiseRejectedResult(result: PromiseSettledResult<unknown>): result is PromiseRejectedResult;
@@ -0,0 +1,2 @@
1
+ export declare function logMultipleResults<T>(results: PromiseSettledResult<T>[], messagePrefix: string, succeededCallback?: (result: PromiseFulfilledResult<T>) => void, failedCallback?: (result: PromiseRejectedResult) => void): void;
2
+ export declare function logPromiseResults<T extends PromiseFulfilledResult<unknown> | PromiseRejectedResult>(results: T[], logMessage: string, callback: (result: T) => void): void;
@@ -0,0 +1 @@
1
+ export declare const NEW_LINE = "\n";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * <details {open}>
3
+ * <summary>{title}</summary>
4
+ * {content}
5
+ * <details>
6
+ */
7
+ export declare function details(title: string, content: string, cfg?: {
8
+ open: boolean;
9
+ }): string;
@@ -0,0 +1,16 @@
1
+ declare const stylesMap: {
2
+ readonly i: "_";
3
+ readonly b: "**";
4
+ readonly s: "~";
5
+ readonly c: "`";
6
+ };
7
+ export type FontStyle = keyof typeof stylesMap;
8
+ /**
9
+ * **{text}** // default is bold
10
+ *
11
+ * _{text}_ // italic - styles set to `['i']`
12
+ *
13
+ * ~**{text}**~ // bold & stroke-through - styles set to `['b','s']`
14
+ */
15
+ export declare function style(text: string, styles?: FontStyle[]): string;
16
+ export {};
@@ -0,0 +1,13 @@
1
+ export type Hierarchy = 1 | 2 | 3 | 4 | 5 | 6;
2
+ /**
3
+ * \# {text} // hierarchy set to 1
4
+ *
5
+ * \## {text} // hierarchy set to 2
6
+ */
7
+ export declare function headline(text: string, hierarchy?: Hierarchy): string;
8
+ export declare function h(text: string, hierarchy?: Hierarchy): string;
9
+ export declare function h2(text: string): string;
10
+ export declare function h3(text: string): string;
11
+ export declare function h4(text: string): string;
12
+ export declare function h5(text: string): string;
13
+ export declare function h6(text: string): string;
@@ -0,0 +1,7 @@
1
+ export * from './details';
2
+ export * from './headline';
3
+ export * from './table';
4
+ export * from './constants';
5
+ export * from './font-style';
6
+ export * from './link';
7
+ export * from './list';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * \# {text} // hierarchy set to 1
3
+ *
4
+ * \## {text} // hierarchy set to 2
5
+ */
6
+ export declare function link(href: string, text?: string): string;
@@ -0,0 +1,5 @@
1
+ export type Order = 'unordered' | 'checkbox';
2
+ /**
3
+ * - {text}
4
+ */
5
+ export declare function li(text: string, order?: Order): string;
@@ -0,0 +1,10 @@
1
+ export type Alignment = 'l' | 'c' | 'r';
2
+ /**
3
+ * | Table Header 1 | Table Header 2 |
4
+ * | --------------- | -------------- |
5
+ * | String 1 | 1 |
6
+ * | String 1 | 2 |
7
+ * | String 1 | 3 |
8
+ */
9
+ export declare function tableMd(data: (string | number)[][], align?: Alignment[]): string;
10
+ export declare function tableHtml(data: (string | number)[][]): string;
@@ -0,0 +1,13 @@
1
+ import { CtorOptions, MultiProgressBars } from 'multi-progress-bars';
2
+ type BarStyles = 'active' | 'done' | 'idle';
3
+ type StatusStyles = Record<BarStyles, (s: string) => string>;
4
+ export declare const barStyles: StatusStyles;
5
+ export declare const messageStyles: StatusStyles;
6
+ export type ProgressBar = {
7
+ incrementInSteps: (numSteps: number) => void;
8
+ updateTitle: (title: string) => void;
9
+ endProgress: (message?: string) => void;
10
+ };
11
+ export declare function getSingletonProgressBars(options?: Partial<CtorOptions>): MultiProgressBars;
12
+ export declare function getProgressBar(taskName: string): ProgressBar;
13
+ export {};
@@ -0,0 +1,3 @@
1
+ import { CommitData } from './git';
2
+ import { ScoredReport } from './scoring';
3
+ export declare function reportToMd(report: ScoredReport, commitData: CommitData | null): string;
@@ -0,0 +1,2 @@
1
+ import { ScoredReport } from './scoring';
2
+ export declare function reportToStdout(report: ScoredReport): string;
@@ -0,0 +1,30 @@
1
+ import { CategoryRef, IssueSeverity as CliIssueSeverity, Format, PersistConfig, Report } from '@code-pushup/models';
2
+ import { EnrichedAuditReport, EnrichedScoredAuditGroupWithAudits, ScoredReport, WeighedAuditReport } from './scoring';
3
+ export declare const FOOTER_PREFIX = "Made with \u2764 by";
4
+ export declare const CODE_PUSHUP_DOMAIN = "code-pushup.dev";
5
+ export declare const README_LINK = "https://github.com/flowup/quality-metrics-cli#readme";
6
+ export declare const reportHeadlineText = "Code PushUp Report";
7
+ export declare const reportOverviewTableHeaders: string[];
8
+ export declare const reportRawOverviewTableHeaders: string[];
9
+ export declare const reportMetaTableHeaders: string[];
10
+ export declare const pluginMetaTableHeaders: string[];
11
+ export declare const detailsTableHeaders: string[];
12
+ export declare function formatReportScore(score: number): string;
13
+ export declare function getRoundScoreMarker(score: number): string;
14
+ export declare function getSquaredScoreMarker(score: number): string;
15
+ export declare function getSeverityIcon(severity: 'info' | 'warning' | 'error'): string;
16
+ export declare function calcDuration(start: number, stop?: number): number;
17
+ export declare function countWeightedRefs(refs: CategoryRef[]): number;
18
+ export declare function countCategoryAudits(refs: CategoryRef[], plugins: ScoredReport['plugins']): number;
19
+ export declare function getAuditByRef({ slug, weight, plugin }: CategoryRef, plugins: ScoredReport['plugins']): WeighedAuditReport;
20
+ export declare function getGroupWithAudits(refSlug: string, refPlugin: string, plugins: ScoredReport['plugins']): EnrichedScoredAuditGroupWithAudits;
21
+ export declare function sortCategoryAudits(a: WeighedAuditReport, b: WeighedAuditReport): number;
22
+ export declare function sortAudits(a: EnrichedAuditReport, b: EnrichedAuditReport): number;
23
+ export declare function compareIssueSeverity(severity1: CliIssueSeverity, severity2: CliIssueSeverity): number;
24
+ type LoadedReportFormat<T extends Format> = T extends 'json' ? Report : string;
25
+ export declare function loadReport<T extends Format>(options: Required<Pick<PersistConfig, 'outputDir' | 'filename'>> & {
26
+ format: T;
27
+ }): Promise<LoadedReportFormat<T>>;
28
+ export declare function throwIsNotPresentError(itemName: string, presentPlace: string): never;
29
+ export declare function getPluginNameFromSlug(slug: string, plugins: ScoredReport['plugins']): string;
30
+ export {};
@@ -0,0 +1,29 @@
1
+ import { AuditGroup, AuditReport, CategoryConfig, PluginReport, Report } from '@code-pushup/models';
2
+ export type EnrichedAuditReport = AuditReport & {
3
+ plugin: string;
4
+ };
5
+ export type WeighedAuditReport = EnrichedAuditReport & {
6
+ weight: number;
7
+ };
8
+ export type EnrichedScoredAuditGroupWithAudits = EnrichedScoredAuditGroup & {
9
+ audits: AuditReport[];
10
+ };
11
+ type ScoredCategoryConfig = CategoryConfig & {
12
+ score: number;
13
+ };
14
+ export type EnrichedScoredAuditGroup = AuditGroup & {
15
+ plugin: string;
16
+ score: number;
17
+ };
18
+ export type ScoredReport = Omit<Report, 'plugins' | 'categories'> & {
19
+ plugins: (Omit<PluginReport, 'audits' | 'groups'> & {
20
+ audits: EnrichedAuditReport[];
21
+ groups: EnrichedScoredAuditGroup[];
22
+ })[];
23
+ categories: ScoredCategoryConfig[];
24
+ };
25
+ export declare function calculateScore<T extends {
26
+ weight: number;
27
+ }>(refs: T[], scoreFn: (ref: T) => number): number;
28
+ export declare function scoreReport(report: Report): ScoredReport;
29
+ export {};
@@ -0,0 +1,7 @@
1
+ export declare function toArray<T>(val: T | T[]): T[];
2
+ export declare function objectToKeys<T extends object>(obj: T): (keyof T)[];
3
+ export declare function objectToEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
4
+ export declare function countOccurrences<T extends PropertyKey>(values: T[]): Partial<Record<T, number>>;
5
+ export declare function distinct<T extends string | number | boolean>(array: T[]): T[];
6
+ export declare function deepClone<T>(obj: T): T;
7
+ export declare function factorOf<T>(items: T[], filterFn: (i: T) => boolean): number;
@@ -0,0 +1,4 @@
1
+ export declare const verboseUtils: (verbose: boolean) => {
2
+ log: (...args: unknown[]) => void;
3
+ exec: (fn: () => unknown) => void;
4
+ };