repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
healer1064/Gimbal
packages/gimbal/src/module/registry.ts
<gh_stars>100-1000 import { ModuleInfo, Module } from '@/typings/module/registry'; import { Meta } from '@/typings/module'; const registry = new Map<string, ModuleInfo>(); export const register = (name: string, meta: Meta, mod: Module): void => { registry.set(name, { fn: mod, meta, }); }; export const unregister = (name: string): boolean => registry.delete(name); export const get = (name: string): Module | void => { const info = registry.get(name); return info && info.fn; }; export const getMeta = (name: string): Meta | void => { const info = registry.get(name); return info && info.meta; };
healer1064/Gimbal
packages/gimbal-core/src/utils/env.ts
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */ const envOrDefault = (variableName: string, defaultValue?: any): any => { const envValue = process.env[variableName]; // parse booleans by default if (envValue === 'true') { return true; } if (envValue === 'false') { return false; } if (envValue === undefined) { return defaultValue; } return envValue; }; export default envOrDefault;
healer1064/Gimbal
packages/gimbal/src/module/size/output.ts
import checkThreshold from '@modus/gimbal-core/lib/utils/threshold'; import bytes from 'bytes'; import { relative } from 'path'; import { Report, ReportItem } from '@/typings/command'; import { FileResult } from '@/typings/module/size'; import { CommandOptions } from '@/typings/utils/command'; const bytesConfig = { unitSeparator: ' ' }; const type = 'size'; interface ParseOptions { cwd: string; success: boolean; } const parseReport = (raw: FileResult[], options: CommandOptions): Report => { const { checkThresholds, cwd } = options; let success = true; const data = raw.map( (result: FileResult): ReportItem => { const resultSuccess = checkThresholds ? checkThreshold(result.sizeBytes, result.maxSizeBytes) : true; if (success) { success = resultSuccess; } return { label: relative(cwd, result.filePath), rawLabel: result.filePath, rawThreshold: result.maxSizeBytes, rawValue: result.size, success: resultSuccess, threshold: result.maxSize, thresholdLimit: 'upper', value: bytes(result.sizeBytes, bytesConfig), type, }; }, ); return { data: [ { data, label: 'Size Checks', rawLabel: 'Size Checks', success, type, }, ], raw, success, }; }; export default parseReport;
healer1064/Gimbal
packages/gimbal/src/output/markdown/index.ts
<reponame>healer1064/Gimbal import { TableInstanceOptions } from 'cli-table3'; import { createTable } from '../cli'; import EventEmitter from '@/event'; import { Report, ReportItem } from '@/typings/command'; import { Config } from '@/typings/components/Table'; import { CliOutputOptions } from '@/typings/output/cli'; import { MarkdownRenderTableEndEvent, MarkdownRenderTableStartEvent } from '@/typings/output/markdown'; import { CommandOptions } from '@/typings/utils/command'; const markdownTableOptions = { chars: { top: '', 'top-mid': '', 'top-left': '', 'top-right': '', bottom: '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '', left: '|', 'left-mid': '', mid: '', 'mid-mid': '', right: '|', 'right-mid': '', middle: '|', }, }; export const tableConfig: Config = { options: markdownTableOptions as TableInstanceOptions, }; export const outputTable = async ( report: Report, commandOptions: CommandOptions, options?: CliOutputOptions, ): Promise<string> => { const hasTable = options && options.table; const table = hasTable ? (options as CliOutputOptions).table : createTable(commandOptions, tableConfig); if (!table) { return ''; } if (!hasTable) { const commentRenderTableStartEvent: MarkdownRenderTableStartEvent = { commandOptions, options, report, table, }; await EventEmitter.fire(`output/markdown/render/table/start`, commentRenderTableStartEvent); } if (report.data) { report.data.forEach((item: ReportItem): void => { if (item.value != null) { table.add(item); } }); } const markdown = await table.render('markdown'); if (!hasTable) { const commentRenderTableStartEvent: MarkdownRenderTableEndEvent = { commandOptions, markdown, options, report, table, }; await EventEmitter.fire(`output/markdown/render/table/end`, commentRenderTableStartEvent); } return markdown; }; const MarkdownOutput = async (report: Report, commandOptions: CommandOptions): Promise<string> => { if (!report.data) { return ''; } const output = ['# Gimbal Report']; await Promise.all( report.data.map( async (item: ReportItem): Promise<void> => { // such a hack, are the direct children it or is there another level of nesting? // this is seeing if there is another level and nest the table under another heading if (item.data && item.data[0] && item.data[0].data && item.data[0].data.length) { const buffered = [`## ${item.label}`]; await Promise.all( item.data.map( async (childItem: ReportItem): Promise<void> => { const rendered = await outputTable(childItem, commandOptions); buffered.push(`### ${childItem.label}`, rendered); }, ), ); output.push(...buffered); } else { const rendered = await outputTable(item, commandOptions); output.push(`## ${item.label}`, rendered); } }, ), ); return `${output.join('\n\n')}\n`; }; export default MarkdownOutput;
healer1064/Gimbal
packages/gimbal/src/event/Event.spec.ts
<gh_stars>100-1000 import Event from './Event'; describe('@modus/gimbal-core/event/Event', (): void => { describe('fire', (): void => { it('should fire an event', (): void => { const fn = jest.fn().mockReturnValue('returned'); const instance = new Event('foo', fn); const ret = instance.fire('foo', 'bar'); expect(ret).toBe('returned'); expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); it('should fire an event when configured with an object', (): void => { const fn = jest.fn().mockReturnValue('returned'); const instance = new Event('foo', { fn, priority: -10, }); expect(instance.priority).toBe(-10); const ret = instance.fire('foo', 'bar'); expect(ret).toBe('returned'); expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); }); describe('createCallback', (): void => { it('should create a function to fire with', (): void => { const fn = jest.fn().mockReturnValue('returned'); const instance = new Event('foo', { fn, }); const cb = instance.createCallback('foo'); const ret = cb('bar'); expect(ret).toBe('returned'); expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); }); });
healer1064/Gimbal
packages/plugin-last-value/src/util.ts
<gh_stars>100-1000 import checkThreshold, { isPercentage, percentToNumber } from '@modus/gimbal-core/lib/utils/threshold'; import { Meta, Types } from '@/typings/module'; import { Config, ItemFailReasons, LastReportItem } from '@/typings/plugin/last-value'; import { DiffRet } from '@/typings/plugin/last-value/util'; import { PluginOptions } from '@/typings/config/plugin'; const getNumberDiff = (item: LastReportItem): DiffRet => { const lastValue = Number(item.rawLastValue); const diff = Math.abs(lastValue - (item.rawValue as number)); const change = (diff / (item.rawValue as number)) * 100; return { change, diff }; }; const getPercentageDiff = (item: LastReportItem): DiffRet => { const lastValue = isPercentage(item.rawLastValue as string) ? percentToNumber(item.rawLastValue as string) : (item.rawLastValue as number); const value = isPercentage(item.rawValue as string) ? percentToNumber(item.rawValue as string) : (item.rawValue as number); const diff = Math.abs(lastValue - value); const change = (diff / (item.rawValue as number)) * 100; return { change, diff }; }; const getSizeDiff = (item: LastReportItem): DiffRet => getNumberDiff(item); const checkDiff = ( item: LastReportItem, diff: number, numberThreshold: number, percentageThreshold: number, numberRet: string, percentageRet: string, meta: Meta, ): ItemFailReasons => { // if the diff is within the threshold, check % of diff vs last value if (checkThreshold(diff, numberThreshold, meta.thresholdLimit)) { const rawValue = isPercentage(item.rawValue as string) ? percentToNumber(item.rawValue as string) : (item.rawValue as number); const percentDiff = (diff / rawValue) * 100; return checkThreshold(percentDiff, percentageThreshold) ? false : percentageRet; } return numberRet; }; const checkNumberThreshold = (item: LastReportItem, config: Config, meta: Meta): ItemFailReasons => { const { thresholds } = config; const { diff } = getNumberDiff(item); return checkDiff(item, diff, thresholds.number, thresholds.diffPercentage, 'number', 'numberDiffPercentage', meta); }; const checkPercentageThreshold = (item: LastReportItem, config: Config, meta: Meta): ItemFailReasons => { const { thresholds } = config; const { diff } = getPercentageDiff(item); return checkDiff( item, diff, thresholds.percentage, thresholds.diffPercentage, 'percentage', 'percentageDiffPercentage', meta, ); }; const checkSizeThreshold = (item: LastReportItem, config: Config, meta: Meta): ItemFailReasons => { const { thresholds } = config; const { diff } = getSizeDiff(item); return checkDiff(item, diff, thresholds.size, thresholds.diffPercentage, 'size', 'sizeDiffPercentage', meta); }; const getThresholdType = async (item: LastReportItem, pluginOptions: PluginOptions): Promise<Types | void> => { const { bus } = pluginOptions; const { getMeta } = await bus('module/registry'); const meta = getMeta(item.type); if (!meta) { return undefined; } let { thresholdType } = meta; const { thresholdTypes } = meta; if (!thresholdType && thresholdTypes) { thresholdType = thresholdTypes[item.rawLabel]; } return thresholdType; }; export const getItemDiff = async (item: LastReportItem, pluginOptions: PluginOptions): Promise<DiffRet | void> => { const thresholdType = await getThresholdType(item, pluginOptions); switch (thresholdType) { case 'number': return getNumberDiff(item); case 'percentage': return getPercentageDiff(item); case 'size': return getSizeDiff(item); default: return undefined; } }; /* eslint-disable-next-line import/prefer-default-export */ export const doesItemFail = async ( item: LastReportItem, config: Config, pluginOptions: PluginOptions, ): Promise<ItemFailReasons> => { if (item.lastValue == null || item.rawValue === item.rawLastValue) { return false; } const { bus } = pluginOptions; const { getMeta } = await bus('module/registry'); const meta = getMeta(item.type); if (!meta) { return false; } const thresholdType = await getThresholdType(item, pluginOptions); switch (thresholdType) { case 'number': return checkNumberThreshold(item, config, meta); case 'percentage': return checkPercentageThreshold(item, config, meta); case 'size': return checkSizeThreshold(item, config, meta); default: return false; } };
healer1064/Gimbal
packages/typings/module/chrome/index.d.ts
<filename>packages/typings/module/chrome/index.d.ts import { Browser, LaunchOptions, Page } from 'puppeteer'; export interface LaunchStartEvent { config: LaunchOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class } export interface LaunchEndEvent { browser: Browser; config: LaunchOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class } export interface KillStartEvent { browser: Browser; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class } export interface KillEndEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class } export interface NewPageStartEvent { browser: Browser; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class } export interface NewPageEndEvent { browser: Browser; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class page: Page; }
healer1064/Gimbal
packages/plugin-source-map-explorer/src/index.ts
<reponame>healer1064/Gimbal import deepmerge from 'deepmerge'; import { PluginOptions } from '@/typings/config/plugin'; import { BundleObject, BundleType, Config, defaultConfig } from './config'; import { registerModule } from './mod'; const arrayMerge = (destinationArray: BundleType[], sourceArray: BundleType[]): BundleType[] => { const newDestArray = destinationArray.slice(); sourceArray.forEach((sourceItem: BundleType): void => { const isSourceString = typeof sourceItem === 'string'; const match: BundleType | void = newDestArray.find((destItem: BundleType): boolean => { if (typeof destItem === 'string') { if (isSourceString) { return destItem === sourceItem; } return destItem === (sourceItem as BundleObject).path; } if (isSourceString) { return destItem === sourceItem; } return (destItem as BundleObject).path === (sourceItem as BundleObject).path; }); if (match) { if (typeof match === 'string') { // if the match in the newDestArray is a string, we can simply replace it // with the sourceItem regardless if the sourceItem is a string or not newDestArray.splice(newDestArray.indexOf(match), 1, sourceItem); } else if (!isSourceString) { // apply sourceItem onto the match in the newDestArray if // sourceItem is an object, not a string Object.assign(match, sourceItem); } } else { // is a new item newDestArray.push(sourceItem); } }); return newDestArray; }; const SourceMapExplorer = async (pluginOptions: PluginOptions, config: Config): Promise<void> => { const pluginConfig: Config = deepmerge(defaultConfig, config, { arrayMerge, }); const catchAll = pluginConfig.bundles.filter((bundleConfig: BundleType): boolean => typeof bundleConfig === 'string' ? bundleConfig === '**/*.js' : (bundleConfig as BundleObject).path === '**/*.js' && (bundleConfig as BundleObject).disable !== true, ); const exclusions = pluginConfig.bundles.filter((bundleConfig: BundleType): boolean => typeof bundleConfig === 'string' ? bundleConfig[0] === '!' : (bundleConfig as BundleObject).path[0] === '!', ); const inclusions = pluginConfig.bundles.filter((bundleConfig: BundleType): boolean => { if (typeof bundleConfig === 'string') { return bundleConfig[0] !== '!' && bundleConfig !== '**/*.js'; } return (bundleConfig as BundleObject).path[0] !== '!' && (bundleConfig as BundleObject).path !== '**/*.js'; }); // we need to order the bundle configs. The first group is the inclusions, next is the catch all, // next the exclusions. pluginConfig.bundles = [...inclusions, ...catchAll, ...exclusions]; registerModule(pluginOptions, pluginConfig); }; export default SourceMapExplorer;
healer1064/Gimbal
packages/gimbal/src/ci/GitHubActions/index.ts
<reponame>healer1064/Gimbal import env from '@modus/gimbal-core/lib/utils/env'; import { CIMode } from '@/typings/ci'; import { VCS as VCSTypes } from '@/typings/vcs'; import GitHub from '@/vcs/GitHub'; export default class GitHubActions { private $vcs?: VCSTypes; public static is(): boolean { return env('GITHUB_ACTIONS', false) as boolean; } public get mode(): CIMode { return 'commit'; } public get name(): string { return this.constructor.name; } public get owner(): string { return env('GITHUB_REPOSITORY').split('/')[0]; } public get pr(): number | void { return undefined; } public get repo(): string { return env('GITHUB_REPOSITORY').split('/')[1]; } public get sha(): string { return env('GITHUB_SHA') as string; } public get vcs(): GitHub | void { if (this.$vcs) { return this.$vcs; } this.$vcs = new GitHub(); this.$vcs.ci = this; return this.$vcs; } }
healer1064/Gimbal
packages/gimbal-core/src/utils/Queue.ts
<reponame>healer1064/Gimbal import { Data, Mode } from '@/typings/utils/Queue'; interface Config { mode?: Mode; } class Queue { private mode: Mode = 'sequential'; private queue: Data[] = []; public constructor(config: Config = {}) { if (config.mode) { this.mode = config.mode; } } public add(...add: Data[]): void { this.queue.push(...add); } public run(...data: Data[]): Promise<Data[]> { const { mode, queue } = this; return mode === 'sequential' ? this.runSequential(queue, data) : this.runParallel(queue, data); } private runSequential(queue: Data[], data: Data[]): Promise<Data[]> { return queue.reduce( (promise: Promise<Data[]>, fn: Data): Promise<Data> => promise.then( async (rets: Data[]): Promise<Data[]> => { const ret = await fn(...data); rets.push(ret); return rets; }, ), Promise.resolve([]), ); } private runParallel(queue: Data[], data: Data[]): Promise<Data[]> { return Promise.all(queue.map((fn: Data): Promise<Data> => fn(...data))); } } export default Queue;
healer1064/Gimbal
packages/gimbal/src/module/chrome/index.ts
import deepmerge from 'deepmerge'; import puppeteer, { Browser, Page } from 'puppeteer'; import { URL } from 'url'; import Config from '@/config'; import EventEmitter from '@/event'; import { LaunchStartEvent, LaunchEndEvent, KillStartEvent, KillEndEvent, NewPageStartEvent, NewPageEndEvent, } from '@/typings/module/chrome'; import defaultConfig from './default-config'; class Chrome { private browser?: Browser; public get port(): string | void { if (this.browser) { const url: string = this.browser.wsEndpoint(); return new URL(url).port; } return undefined; } public async launch(): Promise<void> { const config = deepmerge(defaultConfig, Config.get('configs.puppeteer') || {}); const launchStartEvent: LaunchStartEvent = { config, mod: this, }; await EventEmitter.fire(`module/puppeteer/launch/start`, launchStartEvent); const browser = await puppeteer.launch(config); const launchEndEvent: LaunchEndEvent = { browser, config, mod: this, }; this.browser = browser; await EventEmitter.fire(`module/puppeteer/launch/end`, launchEndEvent); } public async kill(): Promise<void> { if (this.browser) { const killStartEvent: KillStartEvent = { browser: this.browser, mod: this, }; await EventEmitter.fire(`module/puppeteer/kill/start`, killStartEvent); await this.browser.close(); const killEndEvent: KillEndEvent = { mod: this, }; await EventEmitter.fire(`module/puppeteer/kill/end`, killEndEvent); this.browser = undefined; } } public async newPage(): Promise<Page | void> { if (this.browser) { const newPageStartEvent: NewPageStartEvent = { browser: this.browser, mod: this, }; await EventEmitter.fire(`module/puppeteer/new-page/start`, newPageStartEvent); const page = await this.browser.newPage(); const newPageEndEvent: NewPageEndEvent = { browser: this.browser, mod: this, page, }; await EventEmitter.fire(`module/puppeteer/new-page/end`, newPageEndEvent); return page; } return undefined; } } export default Chrome;
healer1064/Gimbal
packages/gimbal/src/config/loader/js.ts
<reponame>healer1064/Gimbal<filename>packages/gimbal/src/config/loader/js.ts import { Config } from '@/typings/config'; const jsLoader = async (file: string): Promise<Config> => { const config = await import(file); if (typeof config === 'function') { return config(); } return config; }; export default jsLoader;
healer1064/Gimbal
packages/gimbal/src/module/chrome/default-config.ts
<filename>packages/gimbal/src/module/chrome/default-config.ts import { LaunchOptions } from 'puppeteer'; // can accept anything from: https://github.com/GoogleChrome/puppeteer/blob/v1.14.0/docs/api.md#puppeteerlaunchoptions const defaultConfig: LaunchOptions = { // args useful for headless CI instances args: ['--no-sandbox', '–-disable-setuid-sandbox'], }; export default defaultConfig;
healer1064/Gimbal
packages/typings/vcs/GitHub/index.d.ts
import { IssuesCreateCommentParams, IssuesCreateCommentResponse, ReposCreateCommitCommentParams, ReposCreateCommitCommentResponse, Response, } from '@octokit/rest'; export interface CommitCommentStartEvent { comment: ReposCreateCommitCommentParams; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ vcs: any; // would cause circular dependency if imported the command class } export interface CommitCommentEndEvent { comment: ReposCreateCommitCommentParams; ret: Response<ReposCreateCommitCommentResponse>; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ vcs: any; // would cause circular dependency if imported the command class } export interface CommitPRStartEvent { comment: IssuesCreateCommentParams; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ vcs: any; // would cause circular dependency if imported the command class } export interface CommitPREndEvent { comment: IssuesCreateCommentParams; ret: Response<IssuesCreateCommentResponse>; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ vcs: any; // would cause circular dependency if imported the command class }
healer1064/Gimbal
packages/gimbal/src/config/jobs.ts
import spawn from '@modus/gimbal-core/lib/utils/spawn'; import { splitOnWhitespace } from '@modus/gimbal-core/lib/utils/string'; import EventEmitter from '@/event'; import Logger from '@/logger'; import { ArrayJob, Job, JobRet, JobStartEvent, JobEndEvent, JobsStartEvent, JobsEndEvent } from '@/typings/config/jobs'; import { CommandOptions } from '@/typings/utils/command'; import { CmdSpawnRet } from '@/typings/utils/spawn'; import { CHILD_GIMBAL_PROCESS } from '@/utils/constants'; const prependDashes = (option: string): string => `--${option.replace(/^-+/, '')}`; const processStringForm = async (job: string, commandOptions: CommandOptions): Promise<JobRet> => { const rest = splitOnWhitespace(job); // should never happen but an empty string was passed if (!rest.length) { return undefined; } const [node, script] = process.argv; // Check if this was executed with a path ending in "/gimbal". // If it was, then we are in compiled code as in dev, it's // the "src/index.ts" file. In dev, we need to register a couple // modules in order to support TypeScript. const runtimeArgs: string[] = script.match(/\/gimbal$/) ? [] : ['-r', 'ts-node/register', '-r', 'tsconfig-paths/register']; const args = [node, ...runtimeArgs, script, ...rest]; const jobStartEvent: JobStartEvent = { args, commandOptions, }; await EventEmitter.fire('config/job/start', jobStartEvent); try { const ret = await spawn( args, { cwd: commandOptions.cwd, env: { ...process.env, [CHILD_GIMBAL_PROCESS]: 'true', }, stdio: 'pipe', }, { noUsage: true, }, ); const jobEndEvent: JobEndEvent = { args, commandOptions, ret, }; await EventEmitter.fire('config/job/end', jobEndEvent); return ret; } catch (error) { const jobEndEvent: JobEndEvent = { args, commandOptions, error, }; await EventEmitter.fire('config/job/end', jobEndEvent); // pass the failure up but let the rejection happen upstream return error; } }; const processArrayForm = (job: ArrayJob, commandOptions: CommandOptions): Promise<JobRet> => { const splitCommand = splitOnWhitespace(job[0]); const [command] = splitCommand; if (command) { const [, { options }] = job; const optionsArr = Object.keys(options); if (optionsArr.length) { const commandString: string = optionsArr.reduce( (acc: string, key: string): string => `${acc} ${prependDashes(key)} ${options[key]}`, command, ); return processStringForm(commandString, commandOptions); } } return Promise.resolve(undefined); }; const handleResults = (ret: JobRet[]): JobRet[] => { let hasFailure = false; Logger.log( ret .map((item: void | CmdSpawnRet): string => { if (item) { if (!item.success) { hasFailure = true; } return item.logs.map((logItem: Buffer): string => logItem.toString()).join(''); } return ''; }) .join('\n'), ); if (hasFailure) { throw ret; } return ret; }; const processJobs = async (jobs: Job[], commandOptions: CommandOptions): Promise<JobRet[]> => { const startEvent: JobsStartEvent = { commandOptions, jobs, }; await EventEmitter.fire('config/jobs/start', startEvent); const ret: JobRet[] = await Promise.all( jobs.map( async (job: Job): Promise<CmdSpawnRet | void> => Array.isArray(job) ? processArrayForm(job, commandOptions) : processStringForm(job, commandOptions), ), ).then(handleResults); const endEvent: JobsEndEvent = { commandOptions, jobs, ret, }; await EventEmitter.fire('config/jobs/end', endEvent); return ret; }; export default processJobs;
healer1064/Gimbal
packages/gimbal/src/config/resolver/index.ts
import { resolvePath } from '@modus/gimbal-core/lib/utils/fs'; import { existsSync } from 'fs'; import path from 'path'; const IS_FILE_RE = /^[./]/; const IS_GIMBAL_RE = /^@\//; const IS_USER_HOME_RE = /^~/; const GIMBAL_ROOT = resolvePath(__dirname, '../..'); const resolver = (requested: string, dir: string, dirPrefix: string): string => { // if path starts with `~` then this is a filesystem path // that needs to be mapped to the user's home dir. This // should be handled by nodejs in a platform agnostic // way so we shouldn't need to do anything. if (requested.match(IS_USER_HOME_RE)) { return requested; } // if a path starts with `/` or `.` then this is a // filesystem path. if (requested.match(IS_FILE_RE)) { return resolvePath(dir, requested); } // if a path starts with '@/' then it should be looked up // as a gimbal internal plugin if (requested.match(IS_GIMBAL_RE)) { return resolvePath(GIMBAL_ROOT, requested.substr(2)); } const gimbalDir = path.join(GIMBAL_ROOT, dirPrefix, requested); if (existsSync(gimbalDir)) { return resolvePath(gimbalDir); } // see if it's a node module install on the cwd // where gimbal is running on const cwdRelativeNodeModule = path.join(dir, 'node_modules', requested); return existsSync(cwdRelativeNodeModule) ? cwdRelativeNodeModule : requested; }; export default resolver;
healer1064/Gimbal
packages/gimbal-core/src/utils/port.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 import getPort from 'get-port'; const findPort = async (): Promise<number> => { const port = await getPort({ port: getPort.makeRange(3000, 3100), }); return port; }; export default findPort;
healer1064/Gimbal
packages/typings/ci/index.d.ts
<filename>packages/typings/ci/index.d.ts export interface Cls { is: () => boolean; name: string; } export type CIMode = 'commit' | 'pr';
healer1064/Gimbal
packages/gimbal/src/output/cli/index.ts
<gh_stars>100-1000 import TableComp from '@modus/gimbal-core/lib/components/Table'; import { sectionHeading, successOrFailure } from '@modus/gimbal-core/lib/utils/colors'; import { Report, ReportItem } from '@/typings/command'; import { Config, Data, Table } from '@/typings/components/Table'; import { CliOutputOptions } from '@/typings/output/cli'; import { CommandOptions } from '@/typings/utils/command'; const successColorizeRenderer = (value: Data, item: Data): string => successOrFailure(value, item.success); export const createTable = (commandOptions: CommandOptions, config?: Config): TableComp => { const table = new TableComp({ columns: [ { header: 'Label', key: 'label', maxWidth: 50, renderer: (label, item): string => { const { data, success } = item; if (data) { // bold the label part, colorify the success part const successText = successOrFailure(success ? '[ success: ✓ ]' : '[ success: x ]', success); return `${sectionHeading(label)} ${successText}`; } return successOrFailure(label, success); }, }, { header: 'Value', key: 'value', align: 'center', renderer: successColorizeRenderer, }, ], ...config, }); if (commandOptions.checkThresholds) { table.addColumn({ header: 'Threshold', key: 'threshold', align: 'center', renderer: successColorizeRenderer, }); table.addColumn({ header: 'Success', key: 'success', align: 'center', renderer: (value: boolean | string): string => { if (value === true) { return successOrFailure('✓', value); } if (value === false) { return successOrFailure('x', value); } return value; }, }); } return table; }; export const outputTable = (report: Report, commandOptions: CommandOptions, options?: CliOutputOptions): Table => { const table = options && options.table ? options.table : createTable(commandOptions); if (report.data) { report.data.forEach((item: ReportItem): void => { // TODO handle grouped items table.add(item); }); } return table; };
healer1064/Gimbal
packages/gimbal/src/output/index.ts
import { mkdirp, resolvePath, writeFile } from '@modus/gimbal-core/lib/utils/fs'; import path from 'path'; import Config from '@/config'; import EventEmitter from '@/event'; import Logger from '@/logger'; import { Report } from '@/typings/command'; import { FileWriteStartEvent, FileWriteEndEvent, CliReportStartEvent, CliReportEndEvent, CliWriteStartEvent, CliWriteEndEvent, HtmlReportStartEvent, HtmlReportEndEvent, JsonReportStartEvent, JsonReportEndEvent, MarkdownReportStartEvent, MarkdownReportEndEvent, OutputFn, OutputItemObject, OutputItem, } from '@/typings/output'; import { CliOutputOptions } from '@/typings/output/cli'; import { CommandOptions } from '@/typings/utils/command'; import { outputTable } from './cli'; import htmlOutput from './html'; import jsonOutput from './json'; import markdownOutput from './markdown'; import { returnReportFailures } from './filter'; const writeReport = async (file: string, type: string, contents: string): Promise<boolean> => { try { const fileWriteStartEvent: FileWriteStartEvent = { contents, file, type, }; await EventEmitter.fire('output/file/write/start', fileWriteStartEvent); await writeFile(file, contents, 'utf8'); const fileWriteEndEvent: FileWriteEndEvent = { contents, file, type, }; await EventEmitter.fire('output/file/write/end', fileWriteEndEvent); Logger.log(`${type} report written to: ${file}`); return true; } catch { Logger.log(`${type} report could not be written to: ${file}`); return false; } }; const doCliOutput = async (report: Report, commandOptions: CommandOptions): Promise<void> => { const cliOptions: CliOutputOptions = {}; const cliReportStartEvent: CliReportStartEvent = { commandOptions, cliOptions, report, }; await EventEmitter.fire('output/cli/report/start', cliReportStartEvent); const table = outputTable(report, commandOptions, cliOptions); const cliReportEndEvent: CliReportEndEvent = { commandOptions, report, table, }; await EventEmitter.fire('output/cli/report/end', cliReportEndEvent); const cliWriteStartEvent: CliWriteStartEvent = { commandOptions, report, table, }; await EventEmitter.fire('output/cli/report/start', cliWriteStartEvent); const cliContents = await table.render('cli'); Logger.log(cliContents); const cliWriteEndEvent: CliWriteEndEvent = { commandOptions, contents: cliContents, report, table, }; await EventEmitter.fire('output/cli/write/end', cliWriteEndEvent); }; const doHtmlOutput: OutputFn = async (report: Report, commandOptions: CommandOptions, html: string): Promise<void> => { const file = html ? resolvePath(commandOptions.cwd, html) : commandOptions.outputHtml; if (file) { await mkdirp(path.dirname(file)); const htmlReportStartEvent: HtmlReportStartEvent = { commandOptions, file, report, }; await EventEmitter.fire('output/html/report/start', htmlReportStartEvent); const contents = await htmlOutput(report, commandOptions); const htmlReportEndEvent: HtmlReportEndEvent = { commandOptions, contents, file, report, }; await EventEmitter.fire('output/html/report/end', htmlReportEndEvent); await writeReport(file, 'HTML', contents); } }; const doJsonOutput: OutputFn = async (report: Report, commandOptions: CommandOptions, json: string): Promise<void> => { const file = json ? resolvePath(commandOptions.cwd, json) : commandOptions.outputJson; if (file) { await mkdirp(path.dirname(file)); const jsonReportStartEvent: JsonReportStartEvent = { commandOptions, file, report, }; await EventEmitter.fire('output/json/report/start', jsonReportStartEvent); const contents = jsonOutput(report); const jsonReportEndEvent: JsonReportEndEvent = { commandOptions, contents, file, report, }; await EventEmitter.fire('output/json/report/end', jsonReportEndEvent); await writeReport(file, 'JSON', contents); } }; const doMarkdownOutput: OutputFn = async ( report: Report, commandOptions: CommandOptions, markdown: string, ): Promise<void> => { const file = markdown ? resolvePath(commandOptions.cwd, markdown) : commandOptions.outputMarkdown; if (file) { await mkdirp(path.dirname(file)); const markdownReportStartEvent: MarkdownReportStartEvent = { commandOptions, file, report, }; await EventEmitter.fire('output/markdown/report/start', markdownReportStartEvent); const contents = await markdownOutput(report, commandOptions); const markdownReportEndEvent: MarkdownReportEndEvent = { commandOptions, contents, file, report, }; await EventEmitter.fire('output/markdown/report/end', markdownReportEndEvent); await writeReport(file, 'Markdown', contents); } }; const doOutput = async ( report: Report, commandOptions: CommandOptions, outputItem: OutputItem, fn: OutputFn, ): Promise<void> => { const location = typeof outputItem === 'string' ? outputItem : outputItem.path; if (outputItem && (outputItem as OutputItemObject).onlyFailures) { if (!report.success) { const filteredReport = returnReportFailures(report); await fn(filteredReport, commandOptions, location); } } else { await fn(report, commandOptions, location); } }; const output = async (report: Report, commandOptions: CommandOptions): Promise<void> => { const { cli, html, json, markdown } = Config.get('outputs', {}); if (cli !== false) { if (cli && cli.onlyFailures) { if (!report.success) { const filteredReport = returnReportFailures(report); await doCliOutput(filteredReport, commandOptions); } } else { await doCliOutput(report, commandOptions); } } if (html || commandOptions.outputHtml) { await doOutput(report, commandOptions, html, doHtmlOutput); } if (json || commandOptions.outputJson) { await doOutput(report, commandOptions, json, doJsonOutput); } if (markdown || commandOptions.outputMarkdown) { await doOutput(report, commandOptions, markdown, doMarkdownOutput); } }; export default output;
healer1064/Gimbal
packages/gimbal/src/event/index.spec.ts
beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-core/event/index', (): void => { describe('on', (): void => { it('should add a callback', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn = jest.fn().mockResolvedValue('returned'); Emitter.on('foo', fn); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); it('should be able to listen using glob event names', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn1 = jest.fn().mockResolvedValue('first'); const fn2 = jest.fn().mockResolvedValue('second'); Emitter.on('foo/*/*', fn1); Emitter.on('foo/**/*', fn2); const ret = await Emitter.fire('foo/bar/baz', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['first', 'second'], }); expect(fn1).toHaveBeenCalledWith('foo/bar/baz', 'bar'); expect(fn2).toHaveBeenCalledWith('foo/bar/baz', 'bar'); }); }); describe('un', (): void => { it('should remove listener', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn = jest.fn().mockResolvedValue('returned'); const instance = Emitter.on('foo', fn); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn).toHaveBeenCalledWith('foo', 'bar'); expect(fn.mock.calls).toEqual([['foo', 'bar']]); Emitter.un('foo', instance); const ret2 = await Emitter.fire('foo', 'bar'); expect(ret2).toEqual({ data: 'bar', rets: [], }); // same as when it was called expect(fn.mock.calls).toEqual([['foo', 'bar']]); }); it('should not remove listener of non-added event', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn = jest.fn().mockResolvedValue('returned'); const instance = Emitter.on('foo', fn); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn).toHaveBeenCalledWith('foo', 'bar'); expect(fn.mock.calls).toEqual([['foo', 'bar']]); Emitter.un('bar', instance); const ret2 = await Emitter.fire('foo', 'bar'); expect(ret2).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn.mock.calls).toEqual([['foo', 'bar'], ['foo', 'bar']]); }); it('should not remove listener not added', async (): Promise<void> => { const { default: Event } = await import('./Event'); const { default: Emitter } = await import('./index'); const fn = jest.fn().mockResolvedValue('returned'); const instance = new Event('foo', (): void => {}); Emitter.on('foo', fn); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn).toHaveBeenCalledWith('foo', 'bar'); expect(fn.mock.calls).toEqual([['foo', 'bar']]); Emitter.un('foo', instance); const ret2 = await Emitter.fire('foo', 'bar'); expect(ret2).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn.mock.calls).toEqual([['foo', 'bar'], ['foo', 'bar']]); }); }); describe('fire', (): void => { it('should be able to fire event', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn = jest.fn().mockResolvedValue('returned'); Emitter.on('foo', fn); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['returned'], }); expect(fn).toHaveBeenCalledWith('foo', 'bar'); }); it('should be able to fire event with multiple listeners', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn1 = jest.fn().mockResolvedValue('first'); const fn2 = jest.fn().mockResolvedValue('second'); Emitter.on('foo', fn1); Emitter.on('foo', fn2); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['first', 'second'], }); expect(fn1).toHaveBeenCalledWith('foo', 'bar'); expect(fn2).toHaveBeenCalledWith('foo', 'bar'); }); it('should fire by priority', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn1 = jest.fn().mockResolvedValue('first'); const fn2 = jest.fn().mockResolvedValue('second'); const fn3 = jest.fn().mockResolvedValue('third'); const fn4 = jest.fn().mockResolvedValue('fourth'); const fn5 = jest.fn().mockResolvedValue('fifth'); Emitter.on('foo', fn1); Emitter.on('foo', { fn: fn2, priority: -10, }); Emitter.on('foo', { fn: fn3, priority: -300, }); Emitter.on('foo', { fn: fn4, priority: -200, }); Emitter.on('foo/bar', fn5); const ret = await Emitter.fire('foo', 'bar'); expect(ret).toEqual({ data: 'bar', rets: ['third', 'fourth', 'second', 'first'], }); expect(fn1).toHaveBeenCalledWith('foo', 'bar'); expect(fn2).toHaveBeenCalledWith('foo', 'bar'); expect(fn3).toHaveBeenCalledWith('foo', 'bar'); expect(fn4).toHaveBeenCalledWith('foo', 'bar'); expect(fn5).not.toHaveBeenCalled(); }); it('should handle no matches', async (): Promise<void> => { const { default: Emitter } = await import('./index'); const fn1 = jest.fn().mockResolvedValue('first'); const fn2 = jest.fn().mockResolvedValue('second'); Emitter.on('foo', fn1); Emitter.on('foo', fn2); const ret = await Emitter.fire('foobar', 'bar'); expect(ret).toEqual({ data: 'bar', rets: [], }); expect(fn1).not.toHaveBeenCalled(); expect(fn2).not.toHaveBeenCalled(); }); }); });
healer1064/Gimbal
packages/typings/utils/threshold.d.ts
<reponame>healer1064/Gimbal export interface LighthouseThreshold { accessibility?: number; 'best-practices'?: number; performance?: number; pwa?: number; seo?: number; [key: string]: number | void; } export interface AdvancedThreshold extends LighthouseThreshold { // heap-snapshot module Documents?: number; Frames?: number; JSHeapTotalSize?: number; JSHeapUsedSize?: number; LayoutCount?: number; Nodes?: number; RecalcStyleDuration?: number; [name: string]: number | undefined; } export type Threshold = number | AdvancedThreshold; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ export type Parser = (obj: any) => number; export type Modes = 'above' | 'below'; export interface Options { mode?: Modes; parser?: Parser; }
healer1064/Gimbal
packages/gimbal/src/utils/constants.ts
<reponame>healer1064/Gimbal /* eslint-disable-next-line import/prefer-default-export */ export const CHILD_GIMBAL_PROCESS = 'CHILD_GIMBAL_PROCESS';
healer1064/Gimbal
packages/gimbal-core/src/components/Table/renderer/cli.ts
import Table, { Cell, HorizontalTable } from 'cli-table3'; import { Column, Data, RendererArgs } from '@/typings/components/Table'; import { sectionHeading } from '../../../utils/colors'; import Queue from '../../../utils/Queue'; const defaultConfig = { style: { head: ['white'] }, }; const renderItem = async (table: HorizontalTable, item: Data, index: number, columns: Column[]): Promise<void> => { if (item.data) { const { length: numColumns } = columns; const { label } = item; const column = columns[0]; const content = column.renderer ? await column.renderer(label, item) : sectionHeading(label); if (index > 0) { // put a spacer above group headers (except for the first) table.push([ { content: '', colSpan: numColumns, }, ]); } table.push([ { content, colSpan: numColumns, }, ]); if (item.data.length) { const queue = new Queue(); item.data.forEach((child: Data, childIndex: number): void => queue.add((): Promise<void> => renderItem(table, child, childIndex, columns)), ); await queue.run(); } } else { const ret = await Promise.all( columns.map( async (column: Column): Promise<string | Cell> => { let { [column.key]: value } = item; if (value == null) { return ''; } if (column.maxWidth && value.length > column.maxWidth) { value = `... ${value.substr(value.length - column.maxWidth)}`; } if (column.renderer) { value = await column.renderer(value, item); } if (column.align && column.align !== 'left') { return { content: value, hAlign: column.align, }; } return value; }, ), ); table.push(ret); } }; const renderCli = async ({ columns, data, options }: RendererArgs): Promise<string> => { const queue = new Queue(); const table = new Table({ ...defaultConfig, head: columns.map((column: Column): string => column.header), ...options, }) as HorizontalTable; data.forEach((item: Data, index: number): void => queue.add((): Promise<void> => renderItem(table, item, index, columns)), ); await queue.run(); return table.toString(); }; export default renderCli;
healer1064/Gimbal
packages/gimbal-core/src/utils/Process.ts
import pidusage from 'pidusage'; interface ProcessConfig { autoStart?: boolean; } interface Stat { cpu: number; // percentage (from 0 to 100*vcore) memory: number; // bytes ppid: number; // PPID pid: number; // PID ctime: number; // ms user + system time elapsed: number; // ms since the start of the process timestamp: number; // ms since epoch } interface Serialized { stats: Stat[]; } export default class Process { private interval?: NodeJS.Timeout; private pid: number; private stats: Stat[] = []; public constructor(pid?: number, config: ProcessConfig = { autoStart: true }) { this.pid = pid || process.pid; if (config.autoStart) { this.start(); } } public async capture(): Promise<void> { const stats = await pidusage(this.pid); this.stats.push(stats); } public end(): void { if (this.interval) { clearInterval(this.interval); this.interval = undefined; } pidusage.clear(); } public serialize(): Serialized { return { stats: this.stats }; } public start(): void { const interval = setInterval((): Promise<void> => this.capture(), 500) as unknown; this.interval = interval as NodeJS.Timeout; this.capture(); } }
healer1064/Gimbal
packages/gimbal/src/module/heap-snapshot/default-config.ts
import { Config } from '@/typings/module/heap-snapshot'; const defaultConfig: Config = { threshold: { Documents: 5, Frames: 2, LayoutCount: 5, Nodes: 75, RecalcStyleCount: 6, }, }; export default defaultConfig;
healer1064/Gimbal
packages/gimbal/src/module/lighthouse/default-config.ts
<filename>packages/gimbal/src/module/lighthouse/default-config.ts import { Config } from '@/typings/module/lighthouse'; const defaultConfig: Config = { extends: 'lighthouse:default', settings: { skipAudits: ['uses-http2', 'redirects-http', 'uses-long-cache-ttl'], }, threshold: { accessibility: 75, 'best-practices': 95, performance: 50, pwa: 50, seo: 90, }, }; export default defaultConfig;
healer1064/Gimbal
packages/typings/module/heap-snapshot/index.d.ts
<filename>packages/typings/module/heap-snapshot/index.d.ts import { Metrics, Page } from 'puppeteer'; import { Report } from '@/typings/command'; import { CommandOptions } from '@/typings/utils/command'; import { AdvancedThreshold } from '@/typings/utils/threshold'; export interface Config { threshold: AdvancedThreshold; } export interface HeapMetrics extends Metrics { [label: string]: number; } export interface NavigationStartEvent { config: Config; page: Page; options: CommandOptions; url: string; } export interface NavigationEndEvent { config: Config; page: Page; options: CommandOptions; url: string; } export interface AuditStartEvent { config: Config; page: Page; options: CommandOptions; url: string; } export interface AuditEndEvent { audit: Metrics; config: Config; page: Page; options: CommandOptions; url: string; } export interface ReportStartEvent { audit: Metrics; config: Config; page: Page; options: CommandOptions; url: string; } export interface ReportEndEvent { audit: Metrics; config: Config; page: Page; options: CommandOptions; report: Report; url: string; }
healer1064/Gimbal
packages/typings/command/index.d.ts
import { CommandOptions } from '@/typings/utils/command'; export type ReportThresholdLimit = 'lower' | 'upper'; export interface ReportError { message: string; stack: string[]; } export interface ReportItem { data?: ReportItem[]; label: string; lastValue?: number | string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ raw?: any; rawLabel: string; rawLastValue?: number | string; rawThreshold?: number | string; rawValue?: number | string; threshold?: number | string; thresholdLimit?: ReportThresholdLimit; value?: number | string; success: boolean; type: string; } export interface Report { error?: ReportError; data?: ReportItem[]; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ raw?: any; rawReports?: Report[]; success: boolean; } export interface StartEvent { args: string[]; commandOptions: CommandOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ command: any; // would cause circular dependency if imported the command class } export interface EndEvent { args: string[]; commandOptions: CommandOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ command: any; // would cause circular dependency if imported the command class report: Report; } export interface ActionStartEvent { args: string[]; commandOptions: CommandOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ command: any; // would cause circular dependency if imported the command class } export interface ActionEndEvent { args: string[]; commandOptions: CommandOptions; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ command: any; // would cause circular dependency if imported the command class report: Report; }
healer1064/Gimbal
packages/typings/config/jobs.d.ts
import { CommandOptions } from '@/typings/utils/command'; import { CmdSpawnRet } from '@/typings/utils/spawn'; export interface Options { [key: string]: string; } export interface OptionsCt { options: Options; } export type ArrayJob = [string, OptionsCt]; export type Job = string | ArrayJob; export type JobRet = CmdSpawnRet | void; export interface JobStartEvent { args: string[]; commandOptions: CommandOptions; } export interface JobEndSuccessEvent { args: string[]; commandOptions: CommandOptions; ret: CmdSpawnRet; } export interface JobEndFailureEvent { args: string[]; commandOptions: CommandOptions; error: Error; } export type JobEndEvent = JobEndSuccessEvent | JobEndFailureEvent; export interface JobsStartEvent { commandOptions: CommandOptions; jobs: Job[]; } export interface JobsEndEvent { commandOptions: CommandOptions; jobs: Job[]; ret: JobRet[]; }
healer1064/Gimbal
packages/plugin-mysql/src/index.ts
import envOrDefault from '@modus/gimbal-core/lib/utils/env'; import deepmerge from 'deepmerge'; import mysqlMod, { Connection, MysqlError } from 'mysql'; import { PluginOptions } from '@/typings/config/plugin'; import { GetEvent, SaveEvent } from '@/typings/plugin/last-value'; import { EnvOrDefault } from '@/typings/utils/env'; interface Base { commandPrefix?: string | string[]; host?: string; password?: string; port?: number; strict?: boolean; user?: string; } interface Config extends Base { lastValue: Item; } interface ItemConfig extends Base { database: string; table: string; } type Item = boolean | ItemConfig; const defaultConfig: Config = { lastValue: false, strict: true, }; const createConnection = (config: ItemConfig, env: EnvOrDefault): Promise<Connection | void> => new Promise((resolve, reject): void => { const connection = mysqlMod.createConnection({ host: config.host || env('GIMBAL_MYSQL_HOST', 'localhost'), user: config.user || env('GIMBAL_MYSQL_USERNAME', 'root'), password: config.password || env('GIMBAL_MYSQL_PASSWORD'), port: config.port || env('GIMBAL_MYSQL_PORT', 3306), database: config.database, }); connection.connect((error: MysqlError | null): void => { if (error) { if (config.strict) { reject(error); } else { resolve(); } } else { resolve(connection); } }); }); const mysql = async ({ bus }: PluginOptions, config: Config): Promise<void> => { const mysqlConfig = deepmerge(defaultConfig, config); if (mysqlConfig.lastValue) { const { getLastReport, init, saveLastReport } = await import('./last-value'); const event = await bus('event'); const itemConfig: ItemConfig = deepmerge( { ...mysqlConfig, database: 'gimbal', table: 'gimbal_archive', }, mysqlConfig.lastValue === true ? {} : mysqlConfig.lastValue, ); const connection = await createConnection(itemConfig, envOrDefault); await init(connection, itemConfig); event.on( 'plugin/last-value/report/get', (_eventName: string, { command }: GetEvent): Promise<void> => getLastReport(command, connection, itemConfig), ); event.on( 'plugin/last-value/report/save', (_eventName: string, { command, report }: SaveEvent): Promise<void> => saveLastReport(command, report, connection, itemConfig), ); } }; export default mysql;
healer1064/Gimbal
packages/typings/utils/command.d.ts
export interface CommandOptions { cwd: string; comment: boolean; config?: string; outputHtml?: string; outputJson?: string; outputMarkdown?: string; verbose: boolean; [name: string]: string | number | boolean | undefined; } /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ export type GetOptionsFromCommand = (cmd?: any, defaults?: any) => CommandOptions;
healer1064/Gimbal
packages/typings/output/cli.d.ts
<filename>packages/typings/output/cli.d.ts import { Table } from '@/typings/components/Table'; /* eslint-disable-next-line import/prefer-default-export */ export interface CliOutputOptions { table?: Table; }
healer1064/Gimbal
packages/gimbal/src/module/unused-source/reconcile.ts
import { ReportItem } from '@/typings/command'; import { checkThreshold, getEntryUsed } from './index'; interface Range { end: number; start: number; } const mergeRanges = (source: Range[], ranges: Range[]): Range[] => { ranges.forEach(({ start, end }: Range): void => { let foundMatch = false; let needSort = true; source.forEach((range: Range): void => { if (start >= range.start && end <= range.end) { // if start and end are within a range, skip doing anything foundMatch = true; needSort = false; } else if (start >= range.start && start <= range.end && end > range.end) { // if start is within the range and end is not /* eslint-disable-next-line no-param-reassign */ range.end = end; foundMatch = true; } else if (end <= range.end && end >= range.start && start < range.start) { // if end is within the range but start is not /* eslint-disable-next-line no-param-reassign */ range.start = start; foundMatch = true; } }); if (!foundMatch) { // wasn't in a range so add it source.push({ start, end }); } if (needSort) { // sort by start points to keep it in order source.sort((A: Range, B: Range): 0 | 1 | -1 => { if (A.start < B.start) { return -1; } if (A.start > B.start) { return 1; } return 0; }); } }); return source; }; const removeOverlaps = (source: Range[]): Range[] => source .map((range: Range, index: number, ranges: Range[]): Range | undefined => { const last = ranges[index - 1]; if (last) { if (range.start >= last.start && range.end <= last.end) { // if start and end are within a range, skip doing anything return undefined; } if (range.start >= last.start && range.start <= last.end && range.end > last.end) { // if start is within the range and end is not last.end = range.end; return undefined; } if (range.end <= last.end && range.end >= last.start && range.start < last.start) { // if end is within the range but start is not last.start = range.start; return undefined; } } return range; }) .filter(Boolean) as Range[]; const reconcile = (matches: ReportItem[]): ReportItem => { const [first, ...rest] = matches; if (rest.length) { const item: ReportItem = { ...first, }; if (item.raw && item.raw.rawEntry) { const ranges = removeOverlaps( rest.reduce( (range: Range[], currentItem: ReportItem): Range[] => mergeRanges(range, currentItem.raw.rawEntry.ranges), item.raw.rawEntry.ranges, ), ); item.raw.rawEntry.ranges = ranges; const used = getEntryUsed(item.raw.rawEntry); const unused = item.raw.total - used; const percentage = (unused / item.raw.total) * 100; const { success } = item.rawThreshold ? checkThreshold(percentage, item.rawThreshold as string) : { success: true }; item.raw.unused = unused; item.raw.unusedPercentage = `${percentage.toFixed(2)}%`; item.rawValue = item.raw.unusedPercentage; item.value = item.raw.unusedPercentage; item.success = success; } return item; } return first; }; export default reconcile;
healer1064/Gimbal
packages/gimbal/src/module/unused-source/default-config.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 import { SizeConfigs } from '@/typings/module/size'; import { UnusedSourceConfig } from '@/typings/module/unused-source'; const defaultConfig: UnusedSourceConfig = { /** * A `threshold` value can be a number or string or an array of size thresholds: * * If a string, `n%` Will check based on unused percentage where n is a number like `30%`. */ threshold: [ { maxSize: '35%', path: '**/*/*.css', }, { maxSize: '15%', path: '**/*/main.*.js', }, { maxSize: '70%', path: '**/*.js', }, { maxSize: '30%', path: '/', type: 'js', }, { maxSize: '65%', path: '/', }, ] as SizeConfigs[], // Examples: // The array of objects, the path is relative to the base url. If the url is `http://localhost/foo/bar.js` // then `/foo/bar.js` will be used to find a matching threshold based on the `path` within the object: // threshold: [ // { // maxSize: '50%', // path: '**/*/*.css', // type: 'css', // optional // }, // { // maxSize: '50%', // path: '**/*/*.js', // type: 'js', // optional // }, // { // maxSize: '50%', // path: '/' // } // ], }; export default defaultConfig;
healer1064/Gimbal
packages/typings/plugin/last-value/util.d.ts
import { Meta } from '@/typings/module'; export interface DiffRet { change: number; diff: number; } export interface Metas { [label: string]: Meta; }
healer1064/Gimbal
packages/gimbal-core/src/components/Table/renderer/html.ts
import renderMarkdown from './markdown'; import { RendererArgs } from '@/typings/components/Table'; // one day make this more powerful and create real html from a template maybe const renderHtml = (args: RendererArgs): Promise<string> => renderMarkdown(args); export default renderHtml;
healer1064/Gimbal
packages/plugin-axe/src/index.spec.ts
import realdeepmerge from 'deepmerge'; import { Meta } from '@/typings/module'; import { Module } from '@/typings/module/registry'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Deepmerge = (x: any, y: any) => any; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-axe', (): void => { it('should register module', async (): Promise<void> => { const deepmergeMock = jest.fn(); const register = jest.fn(); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: false, thresholds: { impact: 'serious', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: false, thresholds: { impact: 'serious', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should execute module', async (): Promise<void> => { const deepmergeMock = jest.fn(); const close = jest.fn().mockResolvedValue(true); const goto = jest.fn().mockResolvedValue(true); const setBypassCSP = jest.fn().mockResolvedValue(true); const newPage = jest.fn().mockResolvedValue({ close, goto, setBypassCSP, }); const chrome = { newPage }; const analyze = jest.fn().mockResolvedValue({ passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }); const disableRules = jest.fn(); const exclude = jest.fn(); const include = jest.fn(); const withRules = jest.fn(); const withTags = jest.fn(); const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const ret = await cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'https://example.com', }); expect(ret).toEqual({ data: [ { data: [ { label: 'foo', rawLabel: 'foo', rawThreshold: 'minor', rawValue: undefined, success: true, threshold: 'minor', thresholdLimit: 'upper', type: 'axe', value: '', }, { label: 'bar', rawLabel: 'bar', rawThreshold: 'minor', rawValue: 'moderate', success: false, threshold: 'minor', thresholdLimit: 'upper', type: 'axe', value: 'moderate', }, ], label: 'Axe Audits', rawLabel: 'Axe Audits', success: false, type: 'axe', }, ], raw: { passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }, success: false, }); expect(newPage).toHaveBeenCalledWith(); expect(close).toHaveBeenCalledWith(); expect(goto).toHaveBeenCalledWith('https://example.com'); expect(setBypassCSP).toHaveBeenCalledWith(true); expect(analyze).toHaveBeenCalledWith(); expect(disableRules).not.toHaveBeenCalled(); expect(exclude).not.toHaveBeenCalled(); expect(include).not.toHaveBeenCalled(); expect(withRules).not.toHaveBeenCalled(); expect(withTags).not.toHaveBeenCalled(); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ function AxePuppeteer(): any {} Object.assign(AxePuppeteer.prototype, { analyze, disableRules, exclude, include, withRules, withTags, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('axe-puppeteer', (): any => ({ AxePuppeteer, })); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should execute module with configs', async (): Promise<void> => { const deepmergeMock = jest.fn(); const close = jest.fn().mockResolvedValue(true); const goto = jest.fn().mockResolvedValue(true); const setBypassCSP = jest.fn().mockResolvedValue(true); const newPage = jest.fn().mockResolvedValue({ close, goto, setBypassCSP, }); const chrome = { newPage }; const analyze = jest.fn().mockResolvedValue({ passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }); const disableRules = jest.fn(); const exclude = jest.fn(); const include = jest.fn(); const withRules = jest.fn(); const withTags = jest.fn(); const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const ret = await cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'https://example.com', }); expect(ret).toEqual({ data: [ { data: [ { label: 'bar', rawLabel: 'bar', rawThreshold: 'serious', rawValue: 'moderate', success: true, threshold: 'serious', thresholdLimit: 'upper', type: 'axe', value: 'moderate', }, ], label: 'Axe Audits', rawLabel: 'Axe Audits', success: true, type: 'axe', }, ], raw: { passes: [ { description: 'foo description', help: 'should foo it', helpUrl: 'https://example.com/foo-help', id: 'foo', impact: undefined, tags: [], nodes: [], }, ], violations: [ { description: 'bar description', help: 'should bar it', helpUrl: 'https://example.com/bar-help', id: 'bar', impact: 'moderate', tags: [], nodes: [], }, ], }, success: true, }); expect(newPage).toHaveBeenCalledWith(); expect(close).toHaveBeenCalledWith(); expect(goto).toHaveBeenCalledWith('https://example.com'); expect(setBypassCSP).toHaveBeenCalledWith(true); expect(analyze).toHaveBeenCalledWith(); expect(disableRules).toHaveBeenCalledWith('rule-1'); expect(exclude).toHaveBeenCalledWith(['.a', '.b > c']); expect(include).toHaveBeenCalledWith('#z'); expect(withRules).toHaveBeenCalledWith(['rule-2']); expect(withTags).toHaveBeenCalledWith(['blah']); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ function AxePuppeteer(): any {} Object.assign(AxePuppeteer.prototype, { analyze, disableRules, exclude, include, withRules, withTags, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('axe-puppeteer', (): any => ({ AxePuppeteer, })); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { disabledRules: 'rule-1', exclude: ['.a', '.b > c'], include: '#z', rules: ['rule-2'], showSuccesses: false, tags: ['blah'], thresholds: { impact: 3, }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { disabledRules: 'rule-1', exclude: ['.a', '.b > c'], include: '#z', rules: ['rule-2'], showSuccesses: false, tags: ['blah'], thresholds: { impact: 3, }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); it('should handle error on opening new page', async (): Promise<void> => { const deepmergeMock = jest.fn(); const newPage = jest.fn().mockResolvedValue(null); const chrome = { newPage }; const register = jest.fn().mockImplementationOnce( async (type: string, meta: Meta, cb: Module): Promise<void> => { expect(type).toBe('axe'); expect(meta).toEqual({ thresholdLimit: 'upper', thresholdType: 'number', }); const check = cb({ chrome, commandOptions: { comment: true, cwd: __dirname, verbose: false, }, url: 'http://example.com', }); await expect(check).rejects.toThrow(new Error('Could not open page to analyze with axe')); expect(newPage).toHaveBeenCalledWith(); }, ); const bus = jest.fn().mockResolvedValue({ event: { on(): void {}, }, register, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: Axe } = await import('./index'); await Axe( { bus, dir: 'foo', }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { showSuccesses: true, thresholds: { impact: 'none', }, }, { showSuccesses: true, thresholds: { impact: 'minor', }, }, ); expect(bus).toHaveBeenCalledWith('module/registry'); expect(register).toHaveBeenCalledWith( 'axe', { thresholdLimit: 'upper', thresholdType: 'number' }, expect.any(Function), ); }); });
healer1064/Gimbal
packages/gimbal/src/command/reconcile.ts
import deepmerge from 'deepmerge'; import reconcile from '@/module/reconcile'; import { Report, ReportItem } from '@/typings/command'; const findMatches = (item: ReportItem, type: string, rest: Report[]): ReportItem[] => { const matches: ReportItem[] = [item]; rest.forEach((report: Report): void => { if (report.data) { report.data.forEach((reportItem: ReportItem): void => { if (reportItem.data && reportItem.type === type) { reportItem.data.forEach((reportDataItem: ReportItem): void => { // need a better way as these may be the same on different things // unused source root path (http://localhost:3000/) may have different // types or be the page total. This would work if the threshold is // different but could be the same... if (reportDataItem.rawLabel === item.rawLabel && reportDataItem.rawThreshold === item.rawThreshold) { matches.push(reportDataItem); } }); } }); } }); return matches; }; const reconcileReports = (reports: Report | Report[]): Report => { if (Array.isArray(reports)) { const [first, ...rest] = reports; const cloned: Report = deepmerge(first, {}); // clone the reports prior to reconciling so that they are unchanged first.rawReports = reports; if (cloned.data) { cloned.data.forEach((report: ReportItem): void => { if (report.data) { // .map() creates a new array instance, make sure to poke it onto the report /* eslint-disable-next-line no-param-reassign */ report.data = report.data.map( (item: ReportItem): ReportItem => { const matches = findMatches(item, report.type, rest); return reconcile(matches, report.type); }, ); /* eslint-disable-next-line no-param-reassign */ report.success = report.data.every((item: ReportItem): boolean => item.success); } }); cloned.success = cloned.data.every((item: ReportItem): boolean => item.success); } return cloned; } return reports; }; export default reconcileReports;
healer1064/Gimbal
packages/plugin-sqlite/src/index.spec.ts
<reponame>healer1064/Gimbal import realdeepmerge from 'deepmerge'; import sqlite3 from 'sqlite3'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Deepmerge = (x: any, y: any) => any; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Mkdirp = (filepath: string) => Promise<any>; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-sqlite', (): void => { describe('no database stuff', (): void => { it('should initialize core', async (): Promise<void> => { const deepmergeMock = jest.fn(); const bus = jest.fn(); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: sqlite } = await import('./index'); await sqlite( { bus, dir: 'foo', }, { file: ':memory:', }, ); expect(deepmergeMock).toHaveBeenCalledWith( { file: 'gimbal.db', lastValue: false, }, { file: ':memory:', }, ); expect(bus).not.toHaveBeenCalled(); }); it('should resolve path to file', async (): Promise<void> => { const deepmergeMock = jest.fn(); const resolvePath = jest.fn().mockReturnValue('foo/bar'); const bus = jest.fn(); jest.doMock( '@modus/gimbal-core/lib/utils/fs', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): any => ({ resolvePath, }), ); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); const { default: sqlite } = await import('./index'); await sqlite( { bus, commandOptions: { comment: true, cwd: 'cwd', verbose: false, }, dir: 'foo', }, {}, ); expect(deepmergeMock).toHaveBeenCalledWith( { file: 'gimbal.db', lastValue: false, }, {}, ); expect(resolvePath).toHaveBeenCalledWith('cwd', 'gimbal.db'); expect(bus).not.toHaveBeenCalled(); }); }); describe('database stuff', (): void => { it('should create database and init last value', async (): Promise<void> => { const deepmergeMock = jest.fn(); const resolvePath = jest.fn().mockReturnValue('foo/bar'); const mkdirpMock = jest.fn().mockResolvedValue('good'); const init = jest.fn().mockResolvedValue('good'); const on = jest.fn(); const bus = jest.fn().mockResolvedValue({ on, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); jest.doMock('mkdirp', (): Mkdirp => mkdirpMock); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./last-value', (): any => ({ init, })); const { default: sqlite } = await import('./index'); await sqlite( { bus, commandOptions: { comment: true, cwd: 'cwd', verbose: false, }, dir: 'foo', }, { file: ':memory:', lastValue: true, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { file: 'gimbal.db', lastValue: false, }, { file: ':memory:', lastValue: true, }, ); expect(resolvePath).not.toHaveBeenCalled(); expect(mkdirpMock).not.toHaveBeenCalled(); expect(init).toHaveBeenCalledWith({ db: new sqlite3.Database(':memory:'), file: ':memory:', lastValue: true, table: 'gimbal_archive', }); expect(on.mock.calls).toEqual([ ['plugin/last-value/report/get', expect.any(Function)], ['plugin/last-value/report/save', expect.any(Function)], ]); expect(bus).toHaveBeenCalledWith('event'); }); it('should trigger event listeners', async (): Promise<void> => { const deepmergeMock = jest.fn(); const resolvePath = jest.fn().mockReturnValue('foo/bar'); const mkdirpMock = jest.fn().mockResolvedValue('good'); const getLastReport = jest.fn().mockResolvedValue('good'); const init = jest.fn().mockResolvedValue('good'); const saveLastReport = jest.fn().mockResolvedValue('good'); const on = jest .fn() /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ .mockImplementation((eventName, cb): any => cb(eventName, { command: 'foo', report: 'bar' })); const bus = jest.fn().mockResolvedValue({ on, }); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any): any => { deepmergeMock(x, y); return realdeepmerge(x, y); }, ); jest.doMock('mkdirp', (): Mkdirp => mkdirpMock); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./last-value', (): any => ({ getLastReport, init, saveLastReport, })); const { default: sqlite } = await import('./index'); await sqlite( { bus, commandOptions: { comment: true, cwd: 'cwd', verbose: false, }, dir: 'foo', }, { file: ':memory:', lastValue: { table: 'hello_there', }, }, ); expect(deepmergeMock).toHaveBeenCalledWith( { file: 'gimbal.db', lastValue: false, }, { file: ':memory:', lastValue: { table: 'hello_there', }, }, ); expect(resolvePath).not.toHaveBeenCalled(); expect(mkdirpMock).not.toHaveBeenCalled(); expect(init).toHaveBeenCalledWith({ db: new sqlite3.Database(':memory:'), file: ':memory:', lastValue: { table: 'hello_there', }, table: 'hello_there', }); expect(getLastReport).toHaveBeenCalledWith('foo', { db: new sqlite3.Database(':memory:'), file: ':memory:', lastValue: { table: 'hello_there', }, table: 'hello_there', }); expect(saveLastReport).toHaveBeenCalledWith('foo', 'bar', { db: new sqlite3.Database(':memory:'), file: ':memory:', lastValue: { table: 'hello_there', }, table: 'hello_there', }); expect(on.mock.calls).toEqual([ ['plugin/last-value/report/get', expect.any(Function)], ['plugin/last-value/report/save', expect.any(Function)], ]); expect(bus).toHaveBeenCalledWith('event'); }); }); });
healer1064/Gimbal
packages/typings/utils/fs.d.ts
<filename>packages/typings/utils/fs.d.ts<gh_stars>100-1000 /* eslint-disable-next-line import/prefer-default-export */ export type ResolvePath = (...paths: string[]) => string;
healer1064/Gimbal
packages/gimbal/src/modules.ts
import audit from '@/command/audit'; import { preparseOptions } from '@/command'; import Config from '@/config'; (async (): Promise<void> => { // Parse config. Audits will consume config automatically const options = preparseOptions(); await Config.load(options.cwd, options); })(); // eslint-disable-next-line import/prefer-default-export export { audit };
healer1064/Gimbal
packages/gimbal/src/command/audit/program.ts
<gh_stars>100-1000 import action from './index'; import Command from '@/command'; // eslint-disable-next-line no-new export default new Command({ action, command: 'audit', });
healer1064/Gimbal
packages/gimbal/src/module/heap-snapshot/meta.ts
<filename>packages/gimbal/src/module/heap-snapshot/meta.ts import { Meta } from '@/typings/module'; const meta: Meta = { thresholdLimit: 'upper', thresholdTypes: { Documents: 'number', Frames: 'number', JSHeapTotalSize: 'size', JSHeapUsedSize: 'size', LayoutCount: 'number', Nodes: 'number', RecalcStyleCount: 'number', }, }; export default meta;
healer1064/Gimbal
packages/plugin-last-value/src/index.spec.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-last-value', (): void => { it('should add option to commander', async (): Promise<void> => { const option = jest.fn(); const bus = jest .fn() .mockResolvedValueOnce({ on(): void {}, }) .mockResolvedValueOnce({ option, }); const { default: plugin } = await import('./index'); await plugin( { bus, dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ); expect(option).toHaveBeenCalledWith( '--no-check-last-values', 'Set to disable checking last values vs current values.', true, ); expect(bus.mock.calls).toEqual([['event'], ['commander']]); }); it('should add listeners', async (): Promise<void> => { const option = jest.fn(); const on = jest.fn(); const bus = jest .fn() .mockResolvedValueOnce({ on, }) .mockResolvedValueOnce({ option, }); const { default: plugin } = await import('./index'); await plugin( { bus, dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ); expect(option).toHaveBeenCalledWith( '--no-check-last-values', 'Set to disable checking last values vs current values.', true, ); expect(on.mock.calls).toEqual([ ['output/cli/report/end', expect.any(Function)], ['output/markdown/render/table/start', expect.any(Function)], ['command/*/action/end', expect.any(Function)], ['command/*/end', expect.any(Function)], ]); expect(bus.mock.calls).toEqual([['event'], ['commander']]); }); it('should handle listeners', async (): Promise<void> => { const option = jest.fn(); const on = jest .fn() /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ .mockImplementation((eventName, cb): any => cb(eventName, { commandOptions: { checkLastValues: true }, report: 'bar', table: 'table' }), ); const addColumn = jest.fn().mockResolvedValue('foo'); const getLastReport = jest.fn().mockResolvedValue('foo'); const saveReport = jest.fn().mockResolvedValue('foo'); const bus = jest .fn() .mockResolvedValueOnce({ on, }) .mockResolvedValueOnce({ option, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./render', (): any => ({ addColumn, })); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./storage', (): any => ({ getLastReport, saveReport, })); const { default: plugin } = await import('./index'); await plugin( { bus, dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ); expect(option).toHaveBeenCalledWith( '--no-check-last-values', 'Set to disable checking last values vs current values.', true, ); expect(on.mock.calls).toEqual([ ['output/cli/report/end', expect.any(Function)], ['output/markdown/render/table/start', expect.any(Function)], ['command/*/action/end', expect.any(Function)], ['command/*/end', expect.any(Function)], ]); expect(addColumn.mock.calls).toEqual([ // from 'output/cli/report/end' event [ 'table', { bus, dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ], // from 'output/markdown/render/table/start' event [ 'table', { bus: expect.any(Function), dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ], ]); expect(getLastReport).toHaveBeenCalledWith( 'command/*/action/end', { bus: expect.any(Function), dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, 'bar', { on: expect.any(Function), }, ); expect(saveReport).toHaveBeenCalledWith( 'command/*/end', { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, 'bar', { on: expect.any(Function), }, ); expect(bus.mock.calls).toEqual([['event'], ['commander']]); }); it('should not fire listeners', async (): Promise<void> => { const option = jest.fn(); const on = jest .fn() /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ .mockImplementation((eventName, cb): any => cb(eventName, { commandOptions: { checkLastValues: false }, report: 'bar', table: 'table' }), ); const addColumn = jest.fn().mockResolvedValue('foo'); const getLastReport = jest.fn().mockResolvedValue('foo'); const saveReport = jest.fn().mockResolvedValue('foo'); const bus = jest .fn() .mockResolvedValueOnce({ on, }) .mockResolvedValueOnce({ option, }); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./render', (): any => ({ addColumn, })); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./storage', (): any => ({ getLastReport, saveReport, })); const { default: plugin } = await import('./index'); await plugin( { bus, dir: 'foo', }, { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }, ); expect(option).toHaveBeenCalledWith( '--no-check-last-values', 'Set to disable checking last values vs current values.', true, ); expect(on.mock.calls).toEqual([ ['output/cli/report/end', expect.any(Function)], ['output/markdown/render/table/start', expect.any(Function)], ['command/*/action/end', expect.any(Function)], ['command/*/end', expect.any(Function)], ]); expect(addColumn).not.toHaveBeenCalled(); expect(getLastReport).not.toHaveBeenCalled(); expect(saveReport).not.toHaveBeenCalled(); expect(bus.mock.calls).toEqual([['event'], ['commander']]); }); });
healer1064/Gimbal
packages/gimbal/src/config/audits.ts
<gh_stars>100-1000 import program, { Command } from 'commander'; import audit from '@/command/audit/program'; const processAudits = (): Promise<void> => audit.run(program.commands.find((cmd: Command): boolean => cmd.name() === 'audit')); export default processAudits;
healer1064/Gimbal
packages/typings/output/index.d.ts
<filename>packages/typings/output/index.d.ts<gh_stars>100-1000 import { Table } from '@/typings/components/Table'; import { Report } from '@/typings/command'; import { CliOutputOptions } from '@/typings/output/cli'; import { CommandOptions } from '@/typings/utils/command'; export interface FileWriteStartEvent { contents: string; file: string; type: string; } export interface FileWriteEndEvent { contents: string; file: string; type: string; } export interface CliReportStartEvent { commandOptions: CommandOptions; cliOptions: CliOutputOptions; report: Report; } export interface CliReportEndEvent { commandOptions: CommandOptions; report: Report; table: Table | void; } export interface CliWriteStartEvent { commandOptions: CommandOptions; report: Report; table: Table | void; } export interface CliWriteEndEvent { commandOptions: CommandOptions; contents: string; report: Report; table: Table | void; } export interface HtmlReportStartEvent { commandOptions: CommandOptions; file: string; report: Report; } export interface HtmlReportEndEvent { commandOptions: CommandOptions; contents: string; file: string; report: Report; } export interface JsonReportStartEvent { commandOptions: CommandOptions; file: string; report: Report; } export interface JsonReportEndEvent { commandOptions: CommandOptions; contents: string; file: string; report: Report; } export interface MarkdownReportStartEvent { commandOptions: CommandOptions; file: string; report: Report; } export interface MarkdownReportEndEvent { commandOptions: CommandOptions; contents: string; file: string; report: Report; } export interface OutputItemObject { onlyFailures?: boolean; path: string; } export type OutputItem = string | OutputItemObject; export type OutputFn = (report: Report, commandOptions: CommandOptions, location: string) => Promise<void>;
healer1064/Gimbal
packages/gimbal/src/module/unused-source/index.ts
import deepmerge from 'deepmerge'; import minimatch from 'minimatch'; import { CoverageEntry, Page } from 'puppeteer'; import { URL } from 'url'; import Config from '@/config'; import EventEmitter from '@/event'; import { Report } from '@/typings/command'; import { SizeConfigs } from '@/typings/module/size'; import { CoverageRange, Entry, UnusedSourceConfig, AuditStartEvent, AuditEndEvent, AuditParseStartEvent, AuditParseEndEvent, NavigateStartEvent, NavigateEndEvent, ReportStartEvent, ReportEndEvent, } from '@/typings/module/unused-source'; import { CommandOptions } from '@/typings/utils/command'; import defaultConfig from './default-config'; import parseReport from './output'; interface CheckThresholdRet { success: boolean; threshold?: string; } type EntryType = 'css' | 'js' | undefined; const doThresholdMatch = (url: string, threshold: SizeConfigs): boolean => { const info = new URL(url); // use the pathname, not the whole url to make the // threshold path config simpler return minimatch(info.pathname, threshold.path); }; const isThresholdMatch = (url: string, threshold: SizeConfigs, type?: EntryType): boolean => { // only attempt to find a match if both types match if (threshold.type === type) { return doThresholdMatch(url, threshold); } return !threshold.type && doThresholdMatch(url, threshold); }; export const getThreshold = (url: string, thresholds: SizeConfigs[], type?: EntryType): string | void => { // attempt to find a matching threshold const threshold = thresholds.find((item: SizeConfigs): boolean => isThresholdMatch(url, item, type)); if (threshold) { return threshold.maxSize; } // if no threshold was found, if there was a type passed, let's try // to find a threshold match that doesn't have a type on it. return type ? getThreshold(url, thresholds) : undefined; }; export const checkThreshold = (percentage: number, threshold?: string): CheckThresholdRet => { if (threshold == null) { // if no threshold, then this is valid return { success: true, }; } // threshold is a percentage as a string // remove % off end const thresholdNum = threshold.substr(0, threshold.length - 1); return { success: percentage <= Number(thresholdNum), threshold, }; }; export const getEntryUsed = (entry: CoverageEntry): number => entry.ranges.reduce((used: number, range: CoverageRange): number => used + range.end - range.start - 1, 0); const sortThreshold = (thresholds: SizeConfigs[]): SizeConfigs[] => { thresholds.sort((last: SizeConfigs, current: SizeConfigs): 0 | 1 | -1 => { if (last.type == null && current.type != null) { return 1; } if (last.type != null && current.type == null) { return -1; } if (last.type && current.type) { if (last.type < current.type) { return -1; } if (last.type > current.type) { return 1; } } return 0; }); return thresholds; }; const arrayMerge = (destinationArray: SizeConfigs[], sourceArray: SizeConfigs[]): SizeConfigs[] => { const newDestinationArray = destinationArray.slice(); sourceArray.forEach((sourceItem: SizeConfigs): void => { const match = newDestinationArray.find( (destItem: SizeConfigs): boolean => destItem.path === sourceItem.path && destItem.type === sourceItem.type, ); if (match) { // apply config onto default Object.assign(match, sourceItem); } else { // is a new item newDestinationArray.push(sourceItem); } }); return newDestinationArray; }; const UnusedCSS = async ( page: Page, url: string, options: CommandOptions, config: UnusedSourceConfig = Config.get('configs.unused-source', {}), ): Promise<Report> => { const { checkThresholds } = options; const sourceConfig = deepmerge(defaultConfig, config, { arrayMerge, }); const isThresholdArray = Array.isArray(sourceConfig.threshold); const thresholds: string | SizeConfigs[] = isThresholdArray ? sortThreshold(sourceConfig.threshold as SizeConfigs[]) : sourceConfig.threshold; const auditStartEvent: AuditStartEvent = { config: sourceConfig, options, page, url, }; await EventEmitter.fire(`module/unused-source/audit/start`, auditStartEvent); await Promise.all([page.coverage.startCSSCoverage(), page.coverage.startJSCoverage()]); const navigateStartEvent: NavigateStartEvent = { config: sourceConfig, options, page, url, }; await EventEmitter.fire(`module/unused-source/navigate/start`, navigateStartEvent); await page.goto(url); const navigateEndEvent: NavigateEndEvent = { config: sourceConfig, options, page, url, }; await EventEmitter.fire(`module/unused-source/navigate/end`, navigateEndEvent); const [css, js]: [CoverageEntry[], CoverageEntry[]] = await Promise.all([ page.coverage.stopCSSCoverage(), page.coverage.stopJSCoverage(), ]); const auditEndEvent: AuditEndEvent = { config: sourceConfig, css, js, options, page, url, }; await EventEmitter.fire(`module/unused-source/audit/end`, auditEndEvent); let total = 0; let used = 0; const parseEntry = (type: EntryType): ((entry: CoverageEntry) => Entry) => (entry: CoverageEntry): Entry => { const entryTotal = entry.text.length; const entryUsed = getEntryUsed(entry); total += entryTotal; used += entryUsed; const unused = entryTotal - entryUsed; const percentage = (unused / entryTotal) * 100; const threshold = isThresholdArray ? getThreshold(entry.url, thresholds as SizeConfigs[], type) : (thresholds as string); const checked = checkThresholds ? checkThreshold(percentage, threshold as string) : { success: true }; return { ...checked, rawEntry: entry, total: entryTotal, unused, unusedPercentage: `${percentage.toFixed(2)}%`, url: entry.url, used: entryUsed, }; }; const auditParseStartEvent: AuditParseStartEvent = { config: sourceConfig, css, js, options, page, url, }; await EventEmitter.fire(`module/unused-source/audit/parse/start`, auditParseStartEvent); const parsedCss = css.map(parseEntry('css')); const parsedJs = js.map(parseEntry('js')); const unused = total - used; const percentage = (unused / total) * 100; const threshold = isThresholdArray ? getThreshold(url, thresholds as SizeConfigs[]) : (thresholds as string); const checked = checkThresholds ? checkThreshold(percentage, threshold as string) : { success: true }; const pageTotal: Entry = { ...checked, total, unused, unusedPercentage: `${percentage.toFixed(2)}%`, url, used, }; const auditParseEndEvent: AuditParseEndEvent = { config: sourceConfig, css, js, options, pageTotal, page, parsedCss, parsedJs, url, }; await EventEmitter.fire(`module/unused-source/audit/parse/end`, auditParseEndEvent); const audit: Entry[] = [pageTotal, ...parsedCss, ...parsedJs]; const reportStartEvent: ReportStartEvent = { audit, config, options, url, }; await EventEmitter.fire(`module/unused-source/report/start`, reportStartEvent); const report = parseReport(audit, options); const reportEndEvent: ReportEndEvent = { audit, config, options, report, url, }; await EventEmitter.fire(`module/unused-source/report/end`, reportEndEvent); return report; }; export default UnusedCSS;
healer1064/Gimbal
packages/gimbal/src/output/filter.ts
<reponame>healer1064/Gimbal import { Report, ReportItem } from '@/typings/command'; export const filterReportItemsFailures = (item: ReportItem): ReportItem | undefined => { if (item.success) { return undefined; } if (item.data) { // recursive const data = item.data.map(filterReportItemsFailures).filter(Boolean) as ReportItem[]; return { ...item, data, }; } return item; }; export const returnReportFailures = (report: Report | ReportItem): Report => { if (report.data) { const data = report.data.map(filterReportItemsFailures).filter(Boolean) as ReportItem[]; return { ...report, data, }; } return report; };
healer1064/Gimbal
packages/gimbal/src/event/Event.ts
import { Callback, CreatedCallback, Config } from '@/typings/event/Event'; import { Data } from '@/typings/utils/Queue'; class Event { private event: string; private fn: Callback; public priority = 0; public constructor(event: string, config: Callback | Config) { this.event = event; if (typeof config === 'function') { this.fn = config; } else { this.fn = config.fn; if (config.priority) { this.priority = config.priority; } } } public fire(event: string, data: Data): Data | void { return this.fn(event, data); } public createCallback(event: string): CreatedCallback { return this.fire.bind(this, event); } } export default Event;
healer1064/Gimbal
packages/plugin-source-map-explorer/src/index.spec.ts
import realdeepmerge from 'deepmerge'; import { PluginOptions } from '@/typings/config/plugin'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Deepmerge = (x: any, y: any, opts?: any) => any; const pluginOptions: PluginOptions = { bus: (): string => '', dir: 'foo', }; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-source-map-explorer', (): void => { it('should register module', async (): Promise<void> => { const deepmergeMock = jest.fn(); const registerModule = jest.fn(); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any, opts?: any): any => { deepmergeMock(x, y, opts); return realdeepmerge(x, y, opts); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./mod', (): any => ({ registerModule, })); const { default: plugin } = await import('./index'); await plugin(pluginOptions, { bundles: [], }); expect(deepmergeMock).toHaveBeenCalledWith( { bundles: ['**/*.js'], }, { bundles: [], }, { arrayMerge: expect.any(Function), isMergeableObject: expect.any(Function), }, ); expect(registerModule).toHaveBeenCalledWith( { bus: expect.any(Function), dir: 'foo', }, { bundles: ['**/*.js'], }, ); }); it('should order bundles properly', async (): Promise<void> => { const deepmergeMock = jest.fn(); const registerModule = jest.fn(); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any, opts?: any): any => { deepmergeMock(x, y, opts); return realdeepmerge(x, y, opts); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./mod', (): any => ({ registerModule, })); const { default: plugin } = await import('./index'); await plugin(pluginOptions, { bundles: [ { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', ], }); expect(deepmergeMock).toHaveBeenCalledWith( { bundles: ['**/*.js'], }, { bundles: [ { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', ], }, { arrayMerge: expect.any(Function), isMergeableObject: expect.any(Function), }, ); expect(registerModule).toHaveBeenCalledWith( { bus: expect.any(Function), dir: 'foo', }, { bundles: [ { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, '**/*.js', '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', ], }, ); }); it('should order bundles properly with overwriting default catch all', async (): Promise<void> => { const deepmergeMock = jest.fn(); const registerModule = jest.fn(); jest.doMock( 'deepmerge', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (): Deepmerge => (x: any, y: any, opts?: any): any => { deepmergeMock(x, y, opts); return realdeepmerge(x, y, opts); }, ); /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jest.doMock('./mod', (): any => ({ registerModule, })); const { default: plugin } = await import('./index'); await plugin(pluginOptions, { bundles: [ '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', { path: '**/*.js', thresholds: { foo: '1 KB', }, }, { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, ], }); expect(deepmergeMock).toHaveBeenCalledWith( { bundles: ['**/*.js'], }, { bundles: [ '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', { path: '**/*.js', thresholds: { foo: '1 KB', }, }, { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, ], }, { arrayMerge: expect.any(Function), isMergeableObject: expect.any(Function), }, ); expect(registerModule).toHaveBeenCalledWith( { bus: expect.any(Function), dir: 'foo', }, { bundles: [ { path: '**/main.*.js', thresholds: { 'App.js': '450 B', 'index.js': '100 B', 'logo.svg': '250 B', 'serviceWorker.js': '300 B', '<unmapped>': '150 B', }, }, { path: '**/2.*.js', thresholds: { 'react/index.js': '50 B', 'object-assign/index.js': '1 KB', 'react-dom/index.js': '300 B', 'react/cjs/react.production.min.js': '7 KB', 'react-dom/cjs/react-dom.production.min.js': '110 KB', 'scheduler/index.js': '50 B', 'scheduler/cjs/scheduler.production.min.js': '5 KB', 'webpack/buildin/global.js': '150 B', '<unmapped>': '150 B', }, }, { path: '**/*.js', thresholds: { foo: '1 KB', }, }, '!precache-manifest*', '!service-worker.js', '!**/runtime*.js', ], }, ); }); });
healer1064/Gimbal
packages/plugin-mysql/src/last-value/index.ts
import { Connection, MysqlError } from 'mysql'; import { Report } from '@/typings/command'; interface Config { commandPrefix?: string | string[]; database: string; table: string; } /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ type Row = any; const VAR_RE = /\${(.+?):(.+?)(?:,\s*(.+?))?(?:,\s*(.+?))?}/; const getCommandPrefix = (config: Config): string | void => { if (config.commandPrefix) { if (Array.isArray(config.commandPrefix)) { return config.commandPrefix.find((prefix: string): boolean => Boolean(prefix) && !prefix.match(VAR_RE)); } if (!config.commandPrefix.match(VAR_RE)) { return config.commandPrefix; } } return undefined; }; const parseCommand = (command: string, config: Config): string => { const prefix = getCommandPrefix(config); return prefix ? `${prefix}-${command}` : command; }; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ const query = (connection: Connection | void, sql: string, params?: any): Promise<any> => new Promise((resolve, reject): void => { if (connection) { connection.query( sql, params, /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (error: MysqlError | null, results: any): any => { if (error) { reject(error); } else { resolve(results); } }, ); } else { resolve(); } }); export const init = async (connection: Connection | void, config: Config): Promise<void> => { /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', 'Creating table...'); return query( connection, `CREATE TABLE IF NOT EXISTS ${config.table} ( id INT NOT NULL AUTO_INCREMENT, command VARCHAR(255) NOT NULL, date DATETIME NOT NULL, report LONGTEXT NOT NULL, PRIMARY KEY (id, command), UNIQUE INDEX id_UNIQUE (id ASC)) ENGINE=INNODB;`, /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ ).then((ret: any): any => { /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', 'Table created!'); return ret; }); }; export const getLastReport = async (command: string, connection: Connection | void, config: Config): Promise<void> => { const parsedCommand = parseCommand(command, config); /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', `Getting last report for "${parsedCommand}" command...`); return query( connection, `SELECT command, date, report FROM ${config.table} WHERE command = ? ORDER BY date DESC LIMIT 1;`, [parsedCommand], ).then( ([row]: Row[] = []): Row => { if (row) { /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', 'Got last report!'); if (config.commandPrefix) { /* eslint-disable-next-line no-param-reassign */ row.command = row.command.replace(parsedCommand, command); } } else { /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', 'Did not find a last report.'); } return row; }, ); }; export const saveLastReport = async ( command: string, report: Report, connection: Connection | void, config: Config, ): Promise<void> => { const parsedCommand = parseCommand(command, config); /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', `Saving new report for "${parsedCommand}" command...`); return query(connection, `INSERT INTO ${config.table} (command, date, report) VALUES (?, NOW(), ?);`, [ parsedCommand, JSON.stringify(report), /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ ]).then((ret: any): any => { /* eslint-disable-next-line no-console */ console.log('[@modus/gimbal-plugin-mysql]', 'Saved new report!'); return ret; }); };
healer1064/Gimbal
packages/plugin-source-map-explorer/src/mod.ts
<gh_stars>100-1000 import { resolvePath } from '@modus/gimbal-core/lib/utils/fs'; import bytes from 'bytes'; import globby from 'globby'; import minimatch from 'minimatch'; // @ts-ignore import explore from 'source-map-explorer'; // looks like their types are nested in the src dir of dist... import { ExploreBundleResult, ExploreResult } from 'source-map-explorer/dist/src'; import { Report, ReportItem } from '@/typings/command'; import { PluginOptions } from '@/typings/config/plugin'; import { Options } from '@/typings/module/registry'; import { BundleObject, BundleType, Config, meta, type } from './config'; type RunModuleFn = (options: Options) => Promise<Report>; interface RawReport extends ExploreResult { bundle: string; } const bytesConfig = { unitSeparator: ' ' }; export const getThreshold = (file: string, bundleConfig: BundleType): string | undefined => { if (typeof bundleConfig === 'string') { return undefined; } const key = Object.keys(bundleConfig.thresholds).find((threshold: string): boolean => minimatch(file, threshold)); return key && bundleConfig.thresholds[key]; }; export const parseBundle = (rawBundle: RawReport, bundleConfig: BundleType): ReportItem => { const data: ReportItem[] = []; let success = true; rawBundle.bundles.forEach((bundleResult: ExploreBundleResult): void => { Object.keys(bundleResult.files).forEach((file: string): void => { const size = bundleResult.files[file]; const threshold = getThreshold(file, bundleConfig as BundleObject); const rawThreshold = threshold == null ? threshold : bytes(threshold); const fileSuccess = rawThreshold == null ? true : size <= rawThreshold; if (success) { success = fileSuccess; } data.push({ label: file, rawLabel: file, rawThreshold, rawValue: size, success: fileSuccess, threshold, type, value: bytes(size, bytesConfig), }); }); }); return { data, label: rawBundle.bundle, rawLabel: rawBundle.bundle, success, type, }; }; export const runModule = (pluginConfig: Config): RunModuleFn => async ({ commandOptions, }: Options): Promise<Report> => { const globBase = resolvePath(commandOptions.cwd, commandOptions.buildDir as string); const globs: string[] = pluginConfig.bundles.map((glob: BundleType): string => { const normalizedGlob: BundleObject = typeof glob === 'string' ? { path: glob, thresholds: {} } : glob; const { path } = normalizedGlob; // need to move the ! to the front so globby can ignore it return path[0] === '!' ? `!${resolvePath(globBase, path.substr(1))}` : resolvePath(globBase, path); }); const paths = await globby(globs); const raw = await Promise.all( paths.map( async (bundle: string): Promise<false | RawReport> => { try { // SME will complain if sourcemaps contain just one file, but we don't control that // in bundles generated by 3rd parties like webpack runtime or Ionic const explored = await explore(bundle); return { bundle, ...explored, }; } catch { return false; } }, ), ); const data = [ ...(raw as RawReport[]).filter(Boolean).map( (entry: RawReport): ReportItem => { const globMatch = globs.find((glob: string): boolean => minimatch(entry.bundle, glob)); const index = globs.indexOf(globMatch as string); const bundleConfig = pluginConfig.bundles[index]; return parseBundle(entry, bundleConfig); }, ), ]; const success = data.every((item: ReportItem): boolean => item.success); return { data: [ { data, label: 'Source Map Explorer Audits', rawLabel: 'Source Map Explorer Audits', success, type, }, ], raw, success, }; }; export const registerModule = async ({ bus }: PluginOptions, pluginConfig: Config): Promise<void> => { const { register } = await bus('module/registry'); register(type, meta, runModule(pluginConfig)); };
healer1064/Gimbal
packages/gimbal-core/src/utils/colors.spec.ts
import { sectionHeading, successOrFailure } from './colors'; describe('@modus/gimbal-core/utils/colors', (): void => { describe('sectionHeading', (): void => { it('should bold text', (): void => { const ret = sectionHeading('this should be bold'); expect(ret).toBe('this should be bold'); }); }); describe('successOrFailure', (): void => { it('should be green for success', (): void => { const ret = successOrFailure('this should be green', true); expect(ret).toBe('this should be green'); }); it('should be red for failure', (): void => { const ret = successOrFailure('this should be red', false); expect(ret).toBe('this should be red'); }); }); });
healer1064/Gimbal
packages/gimbal-core/src/utils/threshold.spec.ts
<gh_stars>100-1000 import checkThreshold, { checkPercentage, checkValue, isPercentage, percentToNumber } from './threshold'; describe('@modus/gimbal-core/utils/threshold', (): void => { describe('checkPercentage', (): void => { describe('lower mode', (): void => { it('should succeed', (): void => { const ret = checkPercentage('4%', '2%', 'lower'); expect(ret).toBe(true); }); it('should succeed when same value', (): void => { const ret = checkPercentage('4%', '4%', 'lower'); expect(ret).toBe(true); }); it('should fail', (): void => { const ret = checkPercentage('4%', '5%', 'lower'); expect(ret).toBe(false); }); }); describe('upper mode', (): void => { it('should succeed', (): void => { const ret = checkPercentage('4%', '5%', 'upper'); expect(ret).toBe(true); }); it('should succeed when same value', (): void => { const ret = checkPercentage('4%', '4%', 'upper'); expect(ret).toBe(true); }); it('should fail', (): void => { const ret = checkPercentage('4%', '3%', 'upper'); expect(ret).toBe(false); }); }); }); describe('checkValue', (): void => { describe('lower mode', (): void => { it('should succeed', (): void => { const ret = checkValue(4, 2, 'lower'); expect(ret).toBe(true); }); it('should succeed when same value', (): void => { const ret = checkValue(4, 4, 'lower'); expect(ret).toBe(true); }); it('should fail', (): void => { const ret = checkValue(4, 5, 'lower'); expect(ret).toBe(false); }); }); describe('upper mode', (): void => { it('should succeed', (): void => { const ret = checkValue(4, 5, 'upper'); expect(ret).toBe(true); }); it('should succeed when same value', (): void => { const ret = checkValue(4, 4, 'upper'); expect(ret).toBe(true); }); it('should fail', (): void => { const ret = checkValue(4, 3, 'upper'); expect(ret).toBe(false); }); }); }); describe('isPercentage', (): void => { it('should be a percentage', (): void => { const ret = isPercentage('1%'); expect(ret).toBe(true); }); it('should not be a percentage', (): void => { const ret = isPercentage(1458917245); expect(ret).toBe(false); }); }); describe('percentToNumber', (): void => { it('should return a number', (): void => { const ret = percentToNumber('58%'); expect(ret).toBe(58); }); }); describe('checkThreshold', (): void => { describe('lower mode', (): void => { it('should succeed with a percentage', (): void => { const ret = checkThreshold('4%', '2%', 'lower'); expect(ret).toBe(true); }); it('should succeed with a percentage when same value', (): void => { const ret = checkThreshold('4%', '4%', 'lower'); expect(ret).toBe(true); }); it('should fail with a percentage', (): void => { const ret = checkThreshold('4%', '5%', 'lower'); expect(ret).toBe(false); }); it('should succeed with a value', (): void => { const ret = checkThreshold(4, 2, 'lower'); expect(ret).toBe(true); }); it('should succeed with a value when same value', (): void => { const ret = checkThreshold(4, 4, 'lower'); expect(ret).toBe(true); }); it('should fail with a value', (): void => { const ret = checkThreshold(4, 5, 'lower'); expect(ret).toBe(false); }); }); describe('upper mode', (): void => { it('should succeed with a percentage', (): void => { const ret = checkThreshold('4%', '5%'); expect(ret).toBe(true); }); it('should succeed with a percentage when same value', (): void => { const ret = checkThreshold('4%', '4%'); expect(ret).toBe(true); }); it('should fail with a percentage', (): void => { const ret = checkThreshold('4%', '3%'); expect(ret).toBe(false); }); it('should succeed with a value', (): void => { const ret = checkThreshold(4, 5); expect(ret).toBe(true); }); it('should succeed with a value when same value', (): void => { const ret = checkThreshold(4, 4); expect(ret).toBe(true); }); it('should fail with a value', (): void => { const ret = checkThreshold(4, 3); expect(ret).toBe(false); }); }); }); });
healer1064/Gimbal
packages/gimbal/src/module/reconcile.ts
import { ReportItem } from '@/typings/command'; import HeapSnapshotReconcile from './heap-snapshot/reconcile'; import LighthouseReconcile from './lighthouse/reconcile'; import UnusedSourceReconcile from './unused-source/reconcile'; const reconcile = (matches: ReportItem[], type: string): ReportItem => { switch (type) { case 'heap-snapshot': return HeapSnapshotReconcile(matches); case 'lighthouse': return LighthouseReconcile(matches); case 'unused-source': return UnusedSourceReconcile(matches); default: // cannot reconcile // maybe we can do some default reconciliation? return matches[0]; } }; export default reconcile;
healer1064/Gimbal
packages/gimbal/src/vcs/comment/index.ts
<filename>packages/gimbal/src/vcs/comment/index.ts import whichCI from '@/ci'; import Config from '@/config'; import EventEmitter from '@/event'; import { namedLogger } from '@/logger'; import { outputTable } from '@/output/markdown'; import { filterReportItemsFailures } from '@/output/filter'; import { Report, ReportItem } from '@/typings/command'; import { CommandOptions } from '@/typings/utils/command'; import { CommentBuildStartEvent, CommentBuildEndEvent, CommentRenderTableStartEvent, CommentRenderTableEndEvent, CommentStartEvent, CommentEndEvent, CommentObject, Comment, } from '@/typings/vcs/comment'; const logger = namedLogger('gimbal/vcs/comment'); const noFailuresText = 'No Failures'; const renderItem = async ( reportItem: ReportItem, commandOptions: CommandOptions, comment: Comment, ): Promise<string> => { if (!reportItem.data) { return ''; } const numFailed = reportItem.data.reduce( (num: number, dataItem: ReportItem): number => num + (dataItem.success ? 0 : 1), 0, ); const commentRenderTableStartEvent: CommentRenderTableStartEvent = { commandOptions, reportItem, }; await EventEmitter.fire(`vcs/comment/render/table/start`, commentRenderTableStartEvent); const output = []; const { onlyFailures } = comment as CommentObject; if (reportItem.data && reportItem.data[0] && reportItem.data[0].data && reportItem.data[0].data.length) { if (onlyFailures && !numFailed) { output.push(noFailuresText); } else { const buffered = [`## ${reportItem.label}`]; await Promise.all( reportItem.data.map( async (childItem: ReportItem): Promise<void> => { if (!onlyFailures || (onlyFailures && !childItem.success)) { const rendered = await outputTable(childItem, commandOptions); buffered.push(`### ${childItem.label}`, rendered); } }, ), ); output.push(...buffered); } } else if (onlyFailures && reportItem.success) { output.push(noFailuresText); } else { const rendered = await outputTable( onlyFailures && reportItem ? (filterReportItemsFailures(reportItem as ReportItem) as ReportItem) : reportItem, commandOptions, ); output.push(`## ${reportItem.label}`, rendered); } const renderedTable = output.join('\n\n'); const commentRenderTableEndEvent: CommentRenderTableEndEvent = { commandOptions, renderedTable, reportItem, }; await EventEmitter.fire(`vcs/comment/render/table/end`, commentRenderTableEndEvent); return `<details><summary>${reportItem.label} (${numFailed} failure${numFailed === 1 ? '' : 's'})</summary> <p> ${renderedTable} </p> </details>`; }; const vcsComment = async (report: Report, commandOptions: CommandOptions): Promise<void> => { if (report.data) { const comment = Config.get('configs.comment', commandOptions.comment); if (comment) { const ci = whichCI(); if (ci) { logger.verbose(`Detected CI: ${ci.name}`); const { vcs } = ci; if (vcs) { logger.verbose(`Detected VCS: ${vcs.name}`); const commentBuildStartEvent: CommentBuildStartEvent = { ci, report, vcs, }; await EventEmitter.fire(`vcs/comment/build/start`, commentBuildStartEvent); const renderedReport = report.data ? await Promise.all( report.data.map((item: ReportItem): Promise<string> => renderItem(item, commandOptions, comment)), ) : []; let markdown = renderedReport.join('\n\n').trim(); const commentBuildEndEvent: CommentBuildEndEvent = { ci, markdown, report, vcs, }; const { data }: { data: CommentBuildEndEvent } = await EventEmitter.fire( `vcs/comment/build/end`, commentBuildEndEvent, ); if (data.markdown) { /* eslint-disable-next-line prefer-destructuring */ markdown = data.markdown; } if (markdown) { const commentStartEvent: CommentStartEvent = { ci, comment: markdown, report, vcs, }; await EventEmitter.fire(`vcs/comment/start`, commentStartEvent); logger.verbose('Commenting on VCS...'); await vcs.comment(markdown); const commentEndEvent: CommentEndEvent = { ci, comment: markdown, report, vcs, }; await EventEmitter.fire(`vcs/comment/end`, commentEndEvent); } } else { logger.verbose('No VCS detected'); } } else { logger.verbose('No CI detected'); } } } }; export default vcsComment;
healer1064/Gimbal
packages/typings/module/lighthouse/index.d.ts
<filename>packages/typings/module/lighthouse/index.d.ts<gh_stars>100-1000 import { Report } from '@/typings/command'; import { Threshold } from '@/typings/utils/threshold'; export interface AuditRef { group?: string; id: string; weight: number; } export interface Category { auditRefs: AuditRef[]; description?: string; id: string; manualDescription?: string; score: number; title: string; } export interface Categories { [name: string]: Category; } export interface ConfigSettings { skipAudits?: string[]; } export interface Config { extends?: string; outputHtml?: string; settings?: ConfigSettings; threshold: Threshold; } export interface Options { chromePort: string; output?: string[]; } export interface Result { audits: {}; categories: Categories; categoryGroups: {}; configSettings: {}; environment: {}; fetchTime: string; finalUrl: string; i18n: {}; lighthouseVersion: string; requestedUrl: string; runWarnings: string[]; timing: {}; userAgent: string; } export interface Audit { lhr: Result; report?: string[]; } export interface AuditStartEvent { config: Config; options: Options; url: string; } export interface AuditEndEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ audit: any; // lighthouse doesn't have types yet config: Config; options: Options; url: string; } export interface ReportStartEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ audit: any; // lighthouse doesn't have types yet config: Config; options: Options; url: string; } export interface ReportEndEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ audit: any; // lighthouse doesn't have types yet config: Config; options: Options; report: Report; url: string; }
healer1064/Gimbal
packages/typings/components/Table/index.d.ts
<reponame>healer1064/Gimbal import { TableInstanceOptions } from 'cli-table3'; export type Alignments = 'left' | 'center' | 'right'; export interface Column { align?: Alignments; header: string; key: string; maxWidth?: number; renderer?: Renderer; } export interface Config { columns?: Column[]; data?: Data[]; options?: TableInstanceOptions; } export type Finder = (item: Column | Data, index: number) => boolean; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ export type Data = any; export type Renderer = (value: Data, item: Data) => string | Promise<string>; export type Renders = 'cli' | 'html' | 'markdown'; export interface RendererArgs { columns: Column[]; data: Data[]; options?: TableInstanceOptions; } export interface Table { add: (item: Data, index?: number) => void; addColumn: (column: Column, index?: number) => void; find: (callback: Finder, getIndex: boolean) => Data | number | void; findColumn: (callback: Finder, getIndex: boolean) => Column | number | void; get: (index: number) => Data | void; getColumn: (index: number) => Column | void; remove: (item: Data) => void; removeColumn: (column: Column) => void; render: (type: Renders) => Promise<string>; set: (data: Data[]) => void; }
healer1064/Gimbal
packages/gimbal/src/logger/index.ts
<reponame>healer1064/Gimbal import { pad } from '@modus/gimbal-core/lib/utils/string'; import colors from 'colors/safe'; import Config from '@/config'; import { Logger, LoggerArgs, LoggerFunction, LoggerGroupFunction } from '@/typings/logger'; const colorsArray = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray']; let last: number; const $defaultLevels = ['verbose', 'log', 'error']; const [, $defaultLevel] = $defaultLevels; let $levels: string[]; // possible levels to log out let $allowedLevel: string; // one of the values from $levels or 'silent' for no logging let $indentLevel: number; // the number of spaces to indent by when grouping export const setFromConfigs = (): void => { $levels = Config.get('configs.logger.levels', $defaultLevels); $allowedLevel = Config.get('configs.logger.level', $defaultLevel); $indentLevel = Config.get('configs.logger.indent', 2); }; /* eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars */ const emptyLoggerFn: LoggerFunction = (..._val: LoggerArgs): void => {}; // checks to see whether the requested level is allowed to be logged const isLevelAllowed = (level: string): boolean => { const allowed = $levels.indexOf($allowedLevel); const requested = $levels.indexOf(level); return requested > -1 && requested >= allowed; }; /* eslint-disable-next-line no-console */ const log = (...logs: LoggerArgs): void => console.log(...logs); // logs out the passed string with indentation. The indentation is calculated // by multiplying the passed indent value and $indentLevel const logIndented = (val: LoggerArgs, indent = 0): void => { let item: string; if (val) { const indention = pad($indentLevel * indent); if (typeof val === 'string') { item = `${indention}${val}`; } else if (val instanceof Error && val.stack) { item = val.stack .split(/\n/) .map((line: string): string => `${indention}${line}`) .join('\n'); } else if (typeof val === 'object') { item = JSON.stringify(val) .split(/\n/) .map((line: string): string => `${indention}${line}`) .join('\n'); } else { item = `${pad($indentLevel * indent)}${val}`; } } else { item = ''; } log(item); }; // logs out a group of strings. An array of strings or sub string arrays should // be passed in. const logGroup = (group: LoggerArgs, indent = 0): void => { group.forEach((val: LoggerArgs): void => { if (Array.isArray(val)) { logGroup(val, indent + 1); } else { logIndented(val, indent); } }); }; // handles the grouped logging of all arguments passed const group = (...groups: LoggerArgs): void => { [...groups].forEach((grp): void => { logGroup(grp as LoggerArgs); }); }; // Sets the allowed logging level export const setLevel = (level: string): void => { const index = $levels.findIndex(($level: string): boolean => $level.toLowerCase() === level.toLowerCase()); if (index > -1) { $allowedLevel = $levels[index]; } else { throw new Error(`Level "${level}" not found in ${JSON.stringify($levels)}`); } }; const createLoggerFunction = (level: string, time = false, ...prefixes: string[]): LoggerFunction => ( ...val: LoggerArgs ): void => { if (isLevelAllowed(level)) { const parsedPrefixes = prefixes.slice(); if (time) { parsedPrefixes.push(`[${new Date().toISOString()}]`); } log(...parsedPrefixes, ...val); } }; const createLoggerGroupFunction = (level: string, fn?: LoggerFunction): LoggerGroupFunction => ( ...groups: LoggerArgs ): void => { if (isLevelAllowed(level)) { if (fn) { fn(); } group(...groups); } }; const levelMaker = (level: string, logger: Logger): void => { /* eslint-disable-next-line no-param-reassign */ logger[level] = createLoggerFunction(level); /* eslint-disable-next-line no-param-reassign */ logger.group[level] = createLoggerGroupFunction(level); }; // Sets the allowed logging levels // The levels passed are added as callable methods on Console // i.e. pass ['info', 'error'] and you can then log out with // Console.info('string') or Console.error('string) with each // respecting the $allowedLevel // // Additionally, a 'group' property is set on the returned object. The // 'group' property also has a method for each logging level. These functions // expect an array of strings / sub-arrays to be passed in order to indent by // nested array level // // If $allowedLevel is undefined the first level passed is set // as the $allowedLevel export const createLogger = (maker = levelMaker): Logger => { const logger: Logger = { error: emptyLoggerFn, group: {}, log: emptyLoggerFn, verbose: emptyLoggerFn, }; $levels.forEach((level): void => maker(level, logger)); return logger; }; const getNextColor = (): string => { if (last == null) { last = 0; } else { last += 1; } if (last >= colorsArray.length) { // start back from beginning last = 0; } return colorsArray[last]; }; // Allows you to pass a name string that returns a logging function that // logs the string passed prefixed with the name. The level logged is the // current $allowedLevel // // The returned function has a method for logging each of the levels currently // allowed. // // Additionally, a 'group' property is set on the returned function. The // 'group' property also has a method for each logging level. These functions // expect an array of strings / sub-arrays to be passed in order to indent by // nested array level export const namedLogger = (name: string, timeStamp = true): Logger => { const nextColor = getNextColor(); return createLogger((level: string, logger: Logger): void => { // @ts-ignore const nameColor = colors[nextColor](name); const fn = createLoggerFunction(level, timeStamp, nameColor); /* eslint-disable-next-line no-param-reassign */ logger[level] = fn; /* eslint-disable-next-line no-param-reassign */ logger.group[level] = createLoggerGroupFunction(level, fn); }); }; setFromConfigs(); // The main logger object const DefaultLogger: Logger = createLogger(); export default DefaultLogger;
healer1064/Gimbal
packages/gimbal/src/module/unused-source/meta.ts
<filename>packages/gimbal/src/module/unused-source/meta.ts<gh_stars>100-1000 import { Meta } from '@/typings/module'; const meta: Meta = { thresholdLimit: 'upper', thresholdType: 'percentage', }; export default meta;
healer1064/Gimbal
packages/typings/utils/Queue.d.ts
<filename>packages/typings/utils/Queue.d.ts /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ export type Data = any; export type Mode = 'sequential' | 'parallel';
healer1064/Gimbal
packages/typings/vcs/index.d.ts
<gh_stars>100-1000 import { URL } from 'url'; import GitHub from '@/vcs/GitHub'; export interface Cls { is: (url: URL) => boolean; name: string; } export type VCS = GitHub;
healer1064/Gimbal
packages/gimbal/src/output/html/index.ts
import { readFile } from '@modus/gimbal-core/lib/utils/fs'; import marked from 'marked'; import path from 'path'; import generateMarkdown from '@/output/markdown'; import { Report } from '@/typings/command'; import { CommandOptions } from '@/typings/utils/command'; // use table's html render type when we get to building real html const HtmlOutput = async (report: Report, options: CommandOptions): Promise<string> => { const markdown = await generateMarkdown(report, options); const html = marked(markdown); const template = await readFile(path.join(__dirname, 'template.html'), 'utf8'); return template.replace('{%body%}', html); }; export default HtmlOutput;
healer1064/Gimbal
packages/gimbal/src/module/serve/index.ts
<gh_stars>100-1000 import deepmerge from 'deepmerge'; import { existsSync } from 'fs'; import http from 'http'; // @ts-ignore import handler from 'serve-handler'; import Config from '@/config'; import EventEmitter from '@/event'; import { CloseStartEvent, CloseEndEvent, CreateServerStartEvent, CreateServerEndEvent, ListenStartEvent, ListenEndEvent, } from '@/typings/module/serve'; interface ServeOptions { port: number; public: string; } class Serve { private port: number; private public: string; private server?: http.Server; public constructor(options: ServeOptions) { this.port = options.port; this.public = options.public; } public start(): Promise<void> { return new Promise( /* eslint-disable-next-line no-async-promise-executor */ async (resolve): Promise<void> => { const { port, public: dir } = this; if (!existsSync(dir)) { throw new Error(`Cannot host nonexistent directory: ${dir}`); } const createServerStartEvent: CreateServerStartEvent = { dir, mod: this, port, }; await EventEmitter.fire(`module/serve/create-server/start`, createServerStartEvent); const handlerOptions = deepmerge(Config.get('configs.serve', {}), { public: dir, }); const server = http.createServer((request, response): void => handler(request, response, handlerOptions)); const createServerEndEvent: CreateServerEndEvent = { dir, mod: this, port, server, }; await EventEmitter.fire(`module/serve/create-server/end`, createServerEndEvent); this.server = server; const listenStartEvent: ListenStartEvent = { dir, mod: this, port, server, }; await EventEmitter.fire(`module/serve/listen/start`, listenStartEvent); server.listen( port, async (): Promise<void> => { const listenEndEvent: ListenEndEvent = { dir, mod: this, port, server, }; await EventEmitter.fire(`module/serve/listen/end`, listenEndEvent); resolve(); }, ); }, ); } public stop(): Promise<void> { return new Promise( /* eslint-disable-next-line no-async-promise-executor */ async (resolve): Promise<void> => { const { server } = this; if (server) { const closeStartEvent: CloseStartEvent = { mod: this, server, }; await EventEmitter.fire(`module/serve/close/start`, closeStartEvent); server.close( async (): Promise<void> => { const closeEndEvent: CloseEndEvent = { mod: this, }; await EventEmitter.fire(`module/serve/close/end`, closeEndEvent); this.server = undefined; resolve(); }, ); } else { resolve(); } }, ); } } export default Serve;
healer1064/Gimbal
packages/gimbal/src/module/lighthouse/reconcile.ts
import checkThreshold from '@modus/gimbal-core/lib/utils/threshold'; import { ReportItem } from '@/typings/command'; const reconcile = (matches: ReportItem[]): ReportItem => { const [first] = matches; if (matches.length > 1) { const item: ReportItem = { ...first, }; const totalScore = matches.reduce( (last: number, match: ReportItem): number => (match.rawValue as number) + last, 0, ); const averageScore = totalScore / matches.length; // get average const value = averageScore * 100; item.rawValue = averageScore; item.value = value.toFixed(0); item.success = item.rawThreshold == null || checkThreshold(value, item.rawThreshold as number, 'lower'); return item; } return first; }; export default reconcile;
healer1064/Gimbal
packages/gimbal/src/output/json/index.ts
<filename>packages/gimbal/src/output/json/index.ts import { Report } from '@/typings/command'; const JsonOutput = (report: Report): string => JSON.stringify(report, null, 2); export default JsonOutput;
healer1064/Gimbal
packages/typings/config/index.d.ts
// @ts-ignore import lighthouse from 'lighthouse'; import { Plugin } from '@/typings/config/plugin'; import { Modules } from '@/typings/module'; import { Config as HeapSnapshotConfig } from '@/typings/module/heap-snapshot'; import { SizeConfigs } from '@/typings/module/size'; import { UnusedSourceConfig } from '@/typings/module/unused-source'; import { CommandOptions } from '@/typings/utils/command'; export type PluginType = string | Plugin; export interface Configs { 'heap-snapshot': HeapSnapshotConfig; lighthouse: lighthouse.Config.Json; size: SizeConfigs[]; 'unused-source': UnusedSourceConfig; } export interface Outputs { html?: string; json?: string; markdown?: string; } export interface Config { audits?: Modules[]; configs?: Configs; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ jobs?: any; // still have to decide what this will look like fully outputs?: Outputs; plugins?: string[]; } export type LoaderFn = (file: string) => Promise<Config>; export interface LoaderMap { js: LoaderFn; json: LoaderFn; yaml: LoaderFn; yml: LoaderFn; [name: string]: LoaderFn; } export interface LoadStartEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ Config: any; // would cause circular dependency if imported the command class commandOptions: CommandOptions; dir: string; file: string; force: boolean; } export interface LoadEndEvent extends LoadStartEvent { config: Config; }
healer1064/Gimbal
packages/typings/plugin/last-value/index.d.ts
<filename>packages/typings/plugin/last-value/index.d.ts import { ReportItem, Report } from '@/typings/command'; import { PluginConfig } from '@/typings/config/plugin'; export type InspectCallback = () => void | Promise<void>; export type ItemFailReasons = string | false; export interface Config { failOnBreach: boolean; saveOnlyOnSuccess: boolean; storage?: PluginConfig; thresholds: { diffPercentage: number; number: number; percentage: number; size: number; }; } export type LastReportItem = { command: string; lastValue: number | string; lastValueChange?: number; lastValueDiff?: number; rawLastValue: number | string; report: string | Report; } & ReportItem; export interface GetEvent { command: string; } export interface SaveEvent { command: string; report: Report; }
healer1064/Gimbal
packages/typings/utils/spawn.d.ts
<reponame>healer1064/Gimbal import { StdioOptions } from 'child_process'; export interface CmdSpawnOptions { cwd?: string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ env?: any; // cannot get ProcessEnv to work stdio?: StdioOptions; timeout?: number; } export interface CmdSpawnRet { code: number; end: Date; logs: Buffer[]; // TODO type os /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ os?: any; start: Date; success: boolean; }
healer1064/Gimbal
packages/plugin-source-map-explorer/src/config.spec.ts
<filename>packages/plugin-source-map-explorer/src/config.spec.ts import { defaultConfig, meta, type } from './config'; describe('@modus/gimbal-plugin-source-map-explorer/config', (): void => { it('should export properly', (): void => { expect(defaultConfig).toEqual({ bundles: ['**/*.js'], }); expect(meta).toEqual({ maxNumRoutes: 1, thresholdLimit: 'upper', thresholdType: 'size', }); expect(type).toBe('source-map-explorer'); }); });
healer1064/Gimbal
packages/gimbal-core/src/utils/spawn.ts
<reponame>healer1064/Gimbal<filename>packages/gimbal-core/src/utils/spawn.ts import { spawn } from 'child_process'; import { CmdSpawnOptions, CmdSpawnRet } from '@/typings/utils/spawn'; import OS from './Process'; interface CmdSpawnConfig { noUsage?: boolean; } const cmdSpawn = (args: string[], options?: CmdSpawnOptions, config: CmdSpawnConfig = {}): Promise<CmdSpawnRet> => { return new Promise<CmdSpawnRet>((resolve, reject): void => { const start = new Date(); const spawned = spawn(args[0], args.slice(1), { cwd: process.cwd(), env: process.env, timeout: 5 * 1000 * 60, // 5 minutes ...options, }); const os = config.noUsage ? undefined : new OS(spawned.pid); const logs: Buffer[] = []; if (spawned.stderr && spawned.stdout) { const onLog = (data: Buffer): void => { if (os) { os.capture(); } logs.push(data); }; spawned.stderr.on('data', (data: Buffer): void => onLog(data)); spawned.stdout.on('data', (data: Buffer): void => onLog(data)); } spawned.on('close', (code: number): void => { if (os) { os.end(); } const end = new Date(); const ret: CmdSpawnRet = { code, end, logs, os, start, success: code === 0, }; if (code) { reject(ret); } else { resolve(ret); } }); }); }; export default cmdSpawn;
healer1064/Gimbal
packages/gimbal-core/src/logger/ci.ts
<filename>packages/gimbal-core/src/logger/ci.ts<gh_stars>100-1000 /* eslint-disable-next-line no-console */ export const startSpinner = (name: string): void => console.log(` [ ${name} ] starting...`); export const finishSpinner = (name: string, success: boolean, output: string): void => /* eslint-disable-next-line no-console */ console.log(`${success ? '✓' : '✗'} [ ${name} ] - ${success ? 'Success!' : 'Failed!'} - ${output}`);
healer1064/Gimbal
packages/gimbal/src/event/index.ts
<filename>packages/gimbal/src/event/index.ts import Queue from '@modus/gimbal-core/lib/utils/Queue'; import minimatch from 'minimatch'; import { FireRet } from '@/typings/event'; import { Callback, CreatedCallback, Config } from '@/typings/event/Event'; import { Data } from '@/typings/utils/Queue'; import Event from './Event'; interface EventMap { [name: string]: Event[]; } class Emitter { private events: EventMap = {}; public on(event: string, config: Callback | Config): Event { const { events } = this; if (!events[event]) { events[event] = []; } const instance = new Event(event, config); events[event].push(instance); return instance; } public un(event: string, instance: Event): void { const { events } = this; const { [event]: arr } = events; const index = arr && arr.indexOf(instance); if (arr && index !== -1) { arr.splice(index, 1); } } public async fire(event: string, data: Data): Promise<FireRet> { const { events } = this; const matched: Event[] = []; const ret: FireRet = { data, rets: [], }; Object.keys(events).forEach((name: string): void => { const match = minimatch(event, name); if (match) { matched.push(...events[name]); } }); if (matched.length > 0) { const queue = new Queue(); matched.sort((last: Event, next: Event): number => { const lastPriority = last.priority || 0; const nextPriority = next.priority || 0; if (lastPriority < nextPriority) { return -1; } if (lastPriority > nextPriority) { return 1; } return 0; }); const args = matched.map((eventInstance: Event): CreatedCallback => eventInstance.createCallback(event)); queue.add(...args); const rets = await queue.run(data); ret.rets.push(...rets); } return ret; } } export { Event }; export default new Emitter();
healer1064/Gimbal
packages/plugin-last-value/src/storage.spec.ts
import { PluginOptions } from '@/typings/config/plugin'; import { Emitter } from '@/typings/event'; const pluginOptions: PluginOptions = { bus(): void {}, dir: 'foo', }; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-last-value/storage', (): void => { describe('getLastReport', (): void => { it('should handle no last report', async (): Promise<void> => { const report = { success: true }; const fire = jest.fn().mockResolvedValue({ rets: [] }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no child data', async (): Promise<void> => { const report = { success: true }; const fire = jest.fn().mockResolvedValue({ rets: [{ report: {} }], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no parent data', async (): Promise<void> => { const report = { data: [ { label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Bar', rawLabel: 'Bar', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no matched child data', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Bar', rawLabel: 'Bar', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle not changing success', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], success: false, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should apply last values on report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: (1 / 3) * 100, lastValueDiff: 1, rawLabel: 'Foo', rawLastValue: 2, rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should apply last values on report as a string that fails', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: 80, lastValueDiff: 8, rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should handle unknown threshold type', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ getMeta: (): void => undefined, }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry']]); }); it('should allow threshold breach failure', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport( 'command/size', { ...pluginOptions, bus, }, config, report, EventEmitter, ); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: 80, lastValueDiff: 8, rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).toHaveBeenCalledWith('module/registry'); }); }); describe('saveReport', (): void => { it('should save successful report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/save', { command: 'size', report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, }); }); it('should not save failed report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).not.toHaveBeenCalled(); }); it('should save failed report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: false, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/save', { command: 'size', report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, }); }); }); });
healer1064/Gimbal
packages/gimbal-core/src/utils/string.spec.ts
import { pad, splitOnWhitespace } from './string'; describe('@modus/gimbal-core/utils/string', (): void => { describe('pad', (): void => { it('should pad a string', (): void => { const ret = pad(4); expect(ret).toBe(' '); }); it('should pad a string with a character', (): void => { const ret = pad(4, '-'); expect(ret).toBe('----'); }); }); describe('splitOnWhitespace', (): void => { it('should split', (): void => { const ret = splitOnWhitespace('hello there'); expect(ret).toEqual(['hello', 'there']); }); it('should split with lots of spaces', (): void => { const ret = splitOnWhitespace(' hello there '); expect(ret).toEqual(['hello', 'there']); }); }); });
healer1064/Gimbal
packages/gimbal-core/src/utils/fs.ts
import fs from 'fs'; import mkdirpMod from 'mkdirp'; import path from 'path'; import { promisify } from 'util'; import getSize from 'get-folder-size'; export const getDirectorySize = promisify(getSize); export const mkdirp = promisify(mkdirpMod); export const readDir = promisify(fs.readdir); export const readFile = promisify(fs.readFile); export const stats = promisify(fs.stat); export const exists = promisify(fs.exists); export const writeFile = promisify(fs.writeFile); export const resolvePath = (...paths: string[]): string => { if (paths.length) { if (paths[0][0] === '~') { return `${process.env.HOME}${paths[0].slice(1)}`; } return path.resolve(...paths); } return process.cwd(); };
healer1064/Gimbal
packages/typings/utils/env.d.ts
/* eslint-disable-next-line import/prefer-default-export,@typescript-eslint/no-explicit-any */ export type EnvOrDefault = (variableName: string, defaultValue?: any) => any;
healer1064/Gimbal
packages/gimbal-core/src/utils/string.ts
export const pad = (amount: number, character = ' '): string => new Array(amount).fill(character).join(''); export const splitOnWhitespace = (str: string): string[] => str.trim().split(/\s+/);
healer1064/Gimbal
packages/gimbal-core/src/components/index.ts
/* eslint-disable-next-line import/prefer-default-export */ export { default as Table } from './Table';
healer1064/Gimbal
packages/gimbal-core/src/utils/colors.ts
<filename>packages/gimbal-core/src/utils/colors.ts import { green, red, bold } from 'colors'; export const sectionHeading = (text: string): string => bold(text); export const successOrFailure = (item: string, success: boolean): string => (success ? green(item) : red(item));
healer1064/Gimbal
packages/typings/logger/index.d.ts
export interface SpinniesConfig { color?: string; disableSpins?: boolean; failColor?: string; failPrefix?: string; spinnerColor?: string; succeedColor?: string; succeedPrefix?: string; spinner?: { frames: string[]; interval: number; }; } export interface SpinniesOptions { color?: string; failColor?: string; status?: 'fail' | 'non-spinnable' | 'spinning' | 'stopped' | 'succeed'; succeedColor?: string; text: string; } export interface SpinniesFailure { failColor?: string; text: string; } export interface SpinniesSuccess { succeedColor?: string; text: string; } export type SpinniesFinish = SpinniesFailure | SpinniesSuccess; /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ interface DeepArray<T> extends Array<T | DeepArray<T>> {} /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ export type LoggerArgs = DeepArray<any>; export type LoggerFunction = (...val: LoggerArgs) => void; export type LoggerGroupFunction = (...groups: LoggerArgs) => void; export interface LoggerGroup { [name: string]: LoggerGroupFunction; } export interface Logger { error: LoggerFunction; group: LoggerGroup; log: LoggerFunction; verbose: LoggerFunction; [name: string]: LoggerFunction | LoggerGroup; }
healer1064/Gimbal
packages/typings/output/markdown/index.d.ts
<gh_stars>100-1000 import { Report } from '@/typings/command'; import { Table } from '@/typings/components/Table'; import { CliOutputOptions } from '@/typings/output/cli'; import { CommandOptions } from '@/typings/utils/command'; export interface MarkdownRenderTableStartEvent { commandOptions: CommandOptions; options?: CliOutputOptions; report: Report; table: Table; } export interface MarkdownRenderTableEndEvent extends MarkdownRenderTableStartEvent { markdown: string; }
healer1064/Gimbal
packages/gimbal/src/config/plugin/index.ts
<reponame>healer1064/Gimbal import program from 'commander'; import deepmerge from 'deepmerge'; import resolver from '@/config/resolver'; import EventEmitter from '@/event'; import { PluginConfig, Plugin, PluginOptions } from '@/typings/config/plugin'; import { CommandOptions } from '@/typings/utils/command'; import { LoadEndEvent } from '@/typings/config'; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ const bus = async (name: string): Promise<any> => { if (name === 'commander') { return program; } const imported = await import(`${__dirname}/../../${name}`); if (imported.default) { return imported.default; } return imported; }; interface Map { [label: string]: PluginConfig; } // this is the object that gets passed to a plugin function const options: PluginOptions = { bus, dir: __dirname, }; const map: Map = {}; const parsePlugins = async ( plugins: (string | PluginConfig)[], dir: string, commandOptions: CommandOptions, /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ ): Promise<any[]> => { const pluginConfigs = await Promise.all( plugins.map( async (plugin: string | PluginConfig): Promise<PluginConfig> => { const obj: PluginConfig = typeof plugin === 'string' ? { plugin, name: plugin } : plugin; const resolved = await import(resolver(obj.plugin as string, dir, 'plugin')); return { ...obj, plugin: resolved as Plugin, }; }, ), ); return Promise.all( pluginConfigs.map( /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (config: PluginConfig): any => { const { plugin, ...pluginConfig } = config; if (pluginConfig.enabled === false) { // global config to disable plugin return undefined; } const func = (plugin as Plugin).default; map[config.name] = config; // since we could be in user land, let's clone // the options object incase someone messes with // it that could cause issues. // Also return it in case it's a promise, we can // wait for it. return func({ ...options, commandOptions: { ...commandOptions }, dir }, deepmerge(pluginConfig, {})); }, ), ); }; EventEmitter.on( 'config/load/end', /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ async (_eventName: string, { commandOptions, config: { plugins }, dir }: LoadEndEvent): Promise<void | any[]> => plugins && plugins.length ? parsePlugins(plugins, dir, commandOptions) : undefined, ); export default parsePlugins;
healer1064/Gimbal
packages/gimbal/src/module/size/register.ts
<reponame>healer1064/Gimbal import { register } from '@/module/registry'; import Size from '@/module/size'; import { Report } from '@/typings/command'; import { Options } from '@/typings/module/registry'; import meta from './meta'; register('size', meta, ({ commandOptions }: Options): Promise<Report> => Size(commandOptions));
healer1064/Gimbal
packages/plugin-last-value/src/render.ts
import bytes from 'bytes'; import { doesItemFail } from './util'; import { Table } from '@/typings/components/Table'; import { Config, LastReportItem } from '@/typings/plugin/last-value'; import { PluginOptions } from '@/typings/config/plugin'; type Renderer = (lastValue: number | string | void, item: LastReportItem) => Promise<string>; const bytesConfig = { unitSeparator: ' ', }; const decimalize = (value: number): string => (value % 1 ? value.toFixed(2) : `${value}`); export const renderDiffPercentage = (lastValue: string, item: LastReportItem): string => { const { lastValueChange, lastValueDiff } = item; if (lastValueChange && lastValueDiff) { const diffPrefix = lastValueDiff > 0 ? '+' : ''; return `${lastValue} ${diffPrefix}${decimalize(lastValueChange)}%`; } return lastValue; }; export const renderDifference = (lastValue: number, item: LastReportItem): string => { const diff = item.lastValueDiff; if (diff) { const diffPrefix = diff > 0 ? '+' : ''; return `${lastValue} ${diffPrefix}${bytes(diff, bytesConfig)}`; } return `${lastValue}`; }; export const createRenderer = (pluginOptions: PluginOptions, config: Config): Renderer => async ( lastValue: number | string | void, item: LastReportItem, ): Promise<string> => { const failure = await doesItemFail(item, config, pluginOptions); switch (failure) { case 'number': case 'percentage': case 'size': return renderDifference(lastValue as number, item); case 'numberDiffPercentage': case 'percentageDiffPercentage': case 'sizeDiffPercentage': return renderDiffPercentage(lastValue as string, item); default: return lastValue == null ? '' : `${lastValue}`; } }; export const addColumn = (table: Table | void, pluginOptions: PluginOptions, config: Config): void => { if (table) { const index = (table.findColumn((column): boolean => column.header === 'Value', true) as number) + 1; table.addColumn( { header: 'Last Value', key: 'lastValue', align: 'center', renderer: createRenderer(pluginOptions, config), }, index, ); } };
healer1064/Gimbal
packages/gimbal/src/utils/command.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 import { resolvePath } from '@modus/gimbal-core/lib/utils/fs'; import program, { Command } from 'commander'; import { existsSync } from 'fs'; import { CommandOptions } from '@/typings/utils/command'; const defaultConfig: CommandOptions = { cwd: resolvePath(), comment: true, verbose: false, }; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ const getOptions = (cmd?: Command, existingOptions?: CommandOptions, Config?: any): CommandOptions => { const existing: CommandOptions = existingOptions || defaultConfig; const options: CommandOptions = { ...existing, }; if (cmd) { const cmdOptions = cmd.options; if (cmdOptions) { cmdOptions.forEach( /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ (option: any): void => { const name = option.attributeName(); const value = Config ? Config.get(`configs.${name}`, cmd[name]) : cmd[name]; if (value != null) { options[name] = value; } }, ); } } if (existingOptions) { options.cwd = resolvePath(options.cwd); if (!existsSync(options.cwd)) { throw new Error(`--cwd not found: ${options.cwd}`); } if (options.outputHtml) { options.outputHtml = resolvePath(options.cwd, options.outputHtml); } if (options.outputJson) { options.outputJson = resolvePath(options.cwd, options.outputJson); } if (options.outputMarkdown) { options.outputMarkdown = resolvePath(options.cwd, options.outputMarkdown); } } return options; }; /* eslint-disable-next-line import/prefer-default-export, @typescript-eslint/no-explicit-any */ export const getOptionsFromCommand = (cmd?: any, defaults?: any, Config?: any): CommandOptions => { // get command options first const cmdOptions: CommandOptions = getOptions(cmd, undefined, Config); // get the global options to always take precedent over command options // in case there are option conflicts const options: CommandOptions = getOptions(program, cmdOptions, Config); if (defaults) { const parsed = typeof defaults === 'function' ? defaults(options) : defaults; return { ...parsed, ...options, }; } return options; };
healer1064/Gimbal
packages/gimbal/src/config/loader/yaml.ts
import env from '@modus/gimbal-core/lib/utils/env'; import { readFile } from '@modus/gimbal-core/lib/utils/fs'; import yaml from 'js-yaml'; import { Config } from '@/typings/config'; const VAR_RE = /\${(.+?):(.+?)(?:,\s*(.+?))?(?:,\s*(.+?))?}/gm; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ const parseValue = (value: any): any => { if (value === 'true') { return true; } if (value === 'false') { return false; } return value; }; const yamlLoader = async (file: string): Promise<Config> => { const source = await readFile(file, 'utf8'); // this will allow for variable replacement. The following are the supported types and formats: // - ${env:SOME_VAR} // The type is "env" which will lookup "SOME_VAR" on process.env. If the var is not found // then the text will not be replaced. // If the type is unrecognized, the text will not be replaced. const doc = source.replace( VAR_RE, (text: string, type: string, prop: string, trueValue?: string, falseValue?: string): string => { if (type === 'env') { const ret = env(prop); if (ret) { if (trueValue) { return parseValue(trueValue); } } else if (falseValue) { return parseValue(falseValue); } return ret === undefined ? text : ret; } return text; }, ); return yaml.safeLoad(doc, { filename: file, json: true, }); }; export default yamlLoader;
healer1064/Gimbal
packages/typings/module/serve/index.d.ts
import http from 'http'; export interface CreateServerStartEvent { dir: string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class port: number; } export interface CreateServerEndEvent { dir: string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class port: number; server: http.Server; } export interface ListenStartEvent { dir: string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class port: number; server: http.Server; } export interface ListenEndEvent { dir: string; /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class port: number; server: http.Server; } export interface CloseStartEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class server: http.Server; } export interface CloseEndEvent { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ mod: any; // would cause circular dependency if imported the command class }
healer1064/Gimbal
packages/gimbal/src/module/heap-snapshot/index.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 import { Metrics, Page } from 'puppeteer'; import Config from '@/config'; import EventEmitter from '@/event'; import { Report } from '@/typings/command'; import { Config as HeapSnapshotConfig, HeapMetrics, AuditStartEvent, AuditEndEvent, NavigationStartEvent, NavigationEndEvent, ReportStartEvent, ReportEndEvent, } from '@/typings/module/heap-snapshot'; import { CommandOptions } from '@/typings/utils/command'; import defaultConfig from './default-config'; import parseReport from './output'; const heapSnapshot = async ( page: Page, url: string, options: CommandOptions, config: HeapSnapshotConfig = Config.get('configs.heap-snapshot', defaultConfig), ): Promise<Report> => { const navigationStartEvent: NavigationStartEvent = { config, page, options, url, }; await EventEmitter.fire(`module/heap-snapsnot/navigation/start`, navigationStartEvent); await page.goto(url); const navigationEndEvent: NavigationEndEvent = { config, page, options, url, }; await EventEmitter.fire(`module/heap-snapsnot/navigation/end`, navigationEndEvent); const auditStartEvent: AuditStartEvent = { config, page, options, url, }; await EventEmitter.fire(`module/heap-snapsnot/audit/start`, auditStartEvent); const audit: Metrics = await page.metrics(); const auditEndEvent: AuditEndEvent = { audit, config, page, options, url, }; await EventEmitter.fire(`module/heap-snapsnot/audit/end`, auditEndEvent); const reportStartEvent: ReportStartEvent = { audit, config, page, options, url, }; await EventEmitter.fire(`module/heap-snapsnot/report/start`, reportStartEvent); const report = parseReport(audit as HeapMetrics, config, options); const reportEndEvent: ReportEndEvent = { audit, config, page, options, report, url, }; await EventEmitter.fire(`module/heap-snapsnot/report/end`, reportEndEvent); return report; }; export default heapSnapshot;
healer1064/Gimbal
packages/gimbal-core/src/utils/threshold.ts
<gh_stars>100-1000 type Modes = 'lower' | 'upper'; const PERCENTAGE_RE = /^(\d+(?:\.\d+)?)\s*%$/; export const isPercentage = (value: number | string): boolean => String(value).match(PERCENTAGE_RE) != null; export const percentToNumber = (value: string): number => Number(value.replace(PERCENTAGE_RE, '$1')); export const checkValue = (value: number, threshold: number, mode: Modes): boolean => mode === 'lower' ? value >= threshold // lower means value should be above or equal to the threshold : value <= threshold; // upper mode means value should be below or equal to the threshold export const checkPercentage = (raw: string, rawThreshold: string, mode: Modes): boolean => { const threshold = percentToNumber(rawThreshold); const value = percentToNumber(raw); return checkValue(value, threshold, mode); }; const checkThreshold = (value: number | string, threshold: number | string, mode: Modes = 'upper'): boolean => isPercentage(value) ? checkPercentage(value as string, threshold as string, mode) : checkValue(value as number, threshold as number, mode); export default checkThreshold;
healer1064/Gimbal
packages/gimbal/src/module/lighthouse/meta.ts
import { Meta } from '@/typings/module'; const meta: Meta = { thresholdLimit: 'lower', thresholdTypes: { Accessibility: 'number', 'Best Practices': 'number', Performance: 'number', pwa: 'number', seo: 'number', }, }; export default meta;
healer1064/Gimbal
packages/gimbal/src/vcs/index.ts
<reponame>healer1064/Gimbal import { URL } from 'url'; import Config from '@/config'; import { Cls, VCS as VCSTypes } from '@/typings/vcs'; import GitHubCls from './GitHub'; const GIT_URL_RE = /((git|ssh|http(s)?)|(git@[\w.]+))(:(\/\/)?)([\w.@:/\-~]+)(\.git)(\/)?/; export const GitHub = 'GitHub'; interface Tests { [label: string]: Cls; } interface VCSConfig { provider: string; } const tests: Tests = { [GitHub]: GitHubCls, }; let vcs: GitHubCls | void; const normalizeConfiguredVCS = (configuredVCS?: string | VCSConfig): VCSConfig | void => { if (configuredVCS) { return typeof configuredVCS === 'string' ? { provider: configuredVCS } : configuredVCS; } return undefined; }; const gitUrlToHttpUrl = (gitUrl: string): string => { const matches = gitUrl.match(GIT_URL_RE); if (!matches) { return gitUrl; } const ssh = Boolean(matches[4]); // a ssh url has git@github.com, we just want github.com const start = ssh ? matches[4].split('@')[1] : matches[7]; // https url has it part of the 7 index used in start const end = ssh ? `/${matches[7]}` : ''; return `https://${start}${end}`; }; const whichVCS = (repoUrl: string): VCSTypes | void => { if (vcs) { return vcs; } const configuredVCS = normalizeConfiguredVCS(Config.get('configs.vcs')); const url = new URL(gitUrlToHttpUrl(repoUrl)); const VCS = configuredVCS ? configuredVCS.provider : Object.keys(tests).find((key: string): boolean => tests[key].is(url)); if (VCS === GitHub) { vcs = new GitHubCls(); return vcs; } return undefined; }; export default whichVCS;
healer1064/Gimbal
packages/gimbal/src/module/heap-snapshot/reconcile.ts
import checkThreshold from '@modus/gimbal-core/lib/utils/threshold'; import { ReportItem } from '@/typings/command'; const reconcile = (matches: ReportItem[]): ReportItem => { const [first] = matches; if (matches.length > 1) { const item: ReportItem = { ...first, }; const number = matches.reduce((last: number, match: ReportItem): number => (match.rawValue as number) + last, 0); const value = number / matches.length; // get average item.rawValue = value; item.value = value.toFixed(0); item.success = item.rawThreshold == null || checkThreshold(value, item.rawThreshold); return item; } return first; }; export default reconcile;
healer1064/Gimbal
packages/gimbal-core/src/components/Table/renderer/markdown.ts
<reponame>healer1064/Gimbal // @ts-ignore import stripAnsi from 'strip-ansi'; import { Column, RendererArgs } from '@/typings/components/Table'; import renderCli from './cli'; type AlignmentValues = '----' | ':---:' | '---:'; interface Alignment { center: AlignmentValues; left: AlignmentValues; right: AlignmentValues; } interface BorderItem { [name: string]: AlignmentValues; } const alignments: Alignment = { center: ':---:', left: '----', right: '---:', }; const renderMarkdown = async ({ columns, data, options }: RendererArgs): Promise<string> => { const item: BorderItem = { label: alignments.left, rawLabel: alignments.left, threshold: alignments.center, success: alignments.center, value: alignments.center, }; columns.forEach((column: Column): void => { const char = alignments[column.align || 'left']; item[column.key] = char; }); data.unshift(item); return stripAnsi(await renderCli({ columns, data, options })); }; export default renderMarkdown;
healer1064/Gimbal
packages/gimbal/src/ci/TravisCI/index.ts
<reponame>healer1064/Gimbal<gh_stars>100-1000 import env from '@modus/gimbal-core/lib/utils/env'; import { CIMode } from '@/typings/ci'; import { VCS as VCSTypes } from '@/typings/vcs'; import GitHub from '@/vcs/GitHub'; export default class TravisCI { private $vcs?: VCSTypes; private get slugSplit(): string[] { const slug = env('TRAVIS_REPO_SLUG'); return slug.split('/'); } public static is(): boolean { return env('TRAVIS', false) as boolean; } public get mode(): CIMode { return env('TRAVIS_PULL_REQUEST') ? 'pr' : 'commit'; } public get name(): string { return this.constructor.name; } public get owner(): string { return this.slugSplit[0]; } public get pr(): number | void { const pr = env('TRAVIS_PULL_REQUEST'); return pr ? (pr as number) : undefined; } public get repo(): string { return this.slugSplit[1]; } public get sha(): string { return env('TRAVIS_COMMIT') as string; } public get vcs(): GitHub | void { if (this.$vcs) { return this.$vcs; } const slug = env('TRAVIS_REPO_SLUG'); if (slug) { this.$vcs = new GitHub(); this.$vcs.ci = this; return this.$vcs; } return undefined; } }
healer1064/Gimbal
packages/gimbal-core/src/utils/env.spec.ts
import envOrDefault from './env'; const ORIG_ENV = process.env; beforeEach((): void => { process.env = {}; }); afterEach((): void => { process.env = { ...ORIG_ENV }; }); describe('@modus/gimbal-core/utils/env', (): void => { describe('envOrDefault', (): void => { test('should return the value', (): void => { process.env.foo = 'bar'; const ret = envOrDefault('foo'); expect(ret).toBe('bar'); }); test('should return true as a boolean', (): void => { process.env.foo = 'true'; const ret = envOrDefault('foo'); expect(ret).toBe(true); }); test('should return false as a boolean', (): void => { process.env.foo = 'false'; const ret = envOrDefault('foo'); expect(ret).toBe(false); }); test('should return default value', (): void => { const ret = envOrDefault('foo', 'baz'); expect(ret).toBe('baz'); }); }); });
healer1064/Gimbal
packages/plugin-last-value/src/index.ts
<reponame>healer1064/Gimbal<filename>packages/plugin-last-value/src/index.ts import deepmerge from 'deepmerge'; import { addColumn } from './render'; import { getLastReport, saveReport } from './storage'; import { ActionEndEvent, EndEvent } from '@/typings/command'; import { PluginOptions } from '@/typings/config/plugin'; import { Config, InspectCallback } from '@/typings/plugin/last-value'; import { CliReportEndEvent } from '@/typings/output'; import { CommandOptions } from '@/typings/utils/command'; const defaultConfig: Config = { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 2, number: 1, percentage: 1, size: 1000, }, }; type EventRet = void | Promise<void>; const inspectCommandOptions = (commandOptions: CommandOptions, callback: InspectCallback): void | Promise<void> => { if (commandOptions.checkLastValues) { return callback(); } return undefined; }; const LastValue = async (pluginOptions: PluginOptions, config: Config): Promise<void> => { const { bus } = pluginOptions; const pluginConfig = deepmerge(defaultConfig, config); const event = await bus('event'); const program = await bus('commander'); program.option('--no-check-last-values', 'Set to disable checking last values vs current values.', true); event.on( 'output/cli/report/end', (name: string, { commandOptions, table }: CliReportEndEvent): EventRet => inspectCommandOptions(commandOptions, (): void => addColumn(table, pluginOptions, pluginConfig)), ); event.on( 'output/markdown/render/table/start', (name: string, { commandOptions, table }: CliReportEndEvent): EventRet => inspectCommandOptions(commandOptions, (): void => addColumn(table, pluginOptions, pluginConfig)), ); event.on( 'command/*/action/end', (name: string, { commandOptions, report }: ActionEndEvent): EventRet => inspectCommandOptions( commandOptions, (): Promise<void> => getLastReport(name, pluginOptions, pluginConfig, report, event), ), ); event.on( 'command/*/end', (name: string, { commandOptions, report }: EndEvent): EventRet => inspectCommandOptions(commandOptions, (): Promise<void> => saveReport(name, pluginConfig, report, event)), ); }; export default LastValue;
Jarvie8176/valheim-ec2-dashboard
packages/api/src/index.ts
import Bluebird from "bluebird"; import express from "express"; import helmet from "helmet"; import cors from "cors"; import AWS from "aws-sdk"; const app = express(); app.use(helmet()); app.use(cors()); const port = process.env.API_PORT; const instanceId = <string>process.env.INSTANCE_ID; app.get("/api/server/start", (_req, res) => { Bluebird.try(async () => { const ec2 = new AWS.EC2({ region: "us-east-1" }); const apiResult = await ec2 .startInstances({ InstanceIds: [instanceId], }) .promise(); console.log(apiResult); res.json({ message: "success", }); }).catch((err) => { console.error(err.stack); res.status(500); res.json({ message: err.message, }); }); }); app.get("/api/server/stop", (_req, res) => { Bluebird.try(async () => { const ec2 = new AWS.EC2({ region: "us-east-1" }); const apiResult = await ec2 .stopInstances({ InstanceIds: [instanceId], }) .promise(); console.log(apiResult); res.json({ message: "success", }); }).catch((err) => { console.error(err.stack); res.status(500); res.json({ message: err.message, }); }); }); app.get("/api/server/status", (_req, res) => { Bluebird.try(async () => { const ec2 = new AWS.EC2({ region: "us-east-1" }); const apiResult = await ec2 .describeInstanceStatus({ IncludeAllInstances: true, InstanceIds: [instanceId], }) .promise(); console.log(apiResult); const instanceData = apiResult?.InstanceStatuses?.[0]; const instanceStatus = instanceData?.InstanceState?.Name; res.json({ status: instanceStatus, }); }).catch((err) => { console.error(err.stack); res.status(500); res.json({ message: err.message, }); }); }); ((): void => { app.listen(port, () => { console.log(`server listening on ${port}`); }); })();
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/serverStatus.ui.tsx
<reponame>Jarvie8176/valheim-ec2-dashboard import { Fragment, FunctionComponent } from "react"; import { ServerStatusDto } from "./serverStatus.dto"; import { Grid } from "@material-ui/core"; import { InfoCard } from "./infoCard.ui"; import { isNil } from "lodash"; type Props = { serverStatus: ServerStatusDto; }; export const ServerStatusUi: FunctionComponent<Props> = (props) => { const activePlayerCount = props.serverStatus.server?.players; const maxPlayerCount = props.serverStatus.server?.max_players; const playerCountMessage = !isNil(activePlayerCount) ? `${activePlayerCount}/${maxPlayerCount}` : "N/A"; const syncTimestamp = props.serverStatus.syncTimestamp?.toString() || "N/A"; const hostStatusMessage = props.serverStatus.host?.status || "N/A"; const serverStatusMessage = props.serverStatus.server ? "Running" : "Stopped"; console.log(props.serverStatus); return ( <Fragment> <Grid item> <InfoCard title={"Host Status"} content={hostStatusMessage} /> </Grid> <Grid item> <InfoCard title={"Server Status"} content={serverStatusMessage} /> </Grid> <Grid item> <InfoCard title={"Players Online"} content={playerCountMessage} /> </Grid> <Grid item> <InfoCard title={"Synced At"} content={syncTimestamp} /> </Grid> </Fragment> ); };