Skip to content

Commit

Permalink
style: linting fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ni55aN committed Aug 29, 2024
1 parent 5cbf00a commit f339a43
Show file tree
Hide file tree
Showing 19 changed files with 155 additions and 111 deletions.
8 changes: 7 additions & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,11 @@ import tseslint from 'typescript-eslint';
import configs from './configs/eslint.mjs';

export default tseslint.config(
...configs
...configs,
{
rules: {
'no-console': 'off',
'@typescript-eslint/no-require-imports': 'off',
}
}
)
4 changes: 2 additions & 2 deletions src/build/banner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ export function getBanner(pkg: Pkg) {
license
} = pkg
const text = [
`/*!`,
'/*!',
`* ${name} v${version}`,
`* (c) ${new Date().getFullYear()} ${author}`,
`* Released under the ${license} license.`,
`* */`
'* */'
].join('\n')

return text
Expand Down
72 changes: 43 additions & 29 deletions src/build/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface OutputOptions {
export type RollupConfig = RollupOptions & { output: RollupOutputOptions[] }

export function getRollupConfig(options: ReteConfig, outputs: OutputOptions[], pkg: Pkg, outputDirectories: string[]): ({

Check warning on line 25 in src/build/config.ts

View workflow job for this annotation

GitHub Actions / ci / ci

This line has a length of 121. Maximum allowed is 120
options: ReteOptions,
options: ReteOptions
config: RollupConfig
}[]) {
if (Array.isArray(options)) {
Expand All @@ -42,7 +42,7 @@ export function getRollupConfig(options: ReteConfig, outputs: OutputOptions[], p
} = options
const localOutputDirectories = outputDirectories.map(path => join(path, outputPath))
const extensions = ['.js', '.ts', '.jsx', '.tsx']
const babelPresets = babelOptions?.presets || [
const babelPresets = babelOptions?.presets ?? [
[require('@babel/preset-env')],
require('@babel/preset-typescript')
]
Expand All @@ -63,7 +63,9 @@ export function getRollupConfig(options: ReteConfig, outputs: OutputOptions[], p
banner: getBanner(pkg),
globals,
exports: 'named' as const,
plugins: minify ? [terser()] : []
plugins: minify
? [terser()]
: []
}) as RollupOutputOptions)).flat(),
watch: {
include: `${SOURCE_FOLDER}/**`
Expand All @@ -73,40 +75,52 @@ export function getRollupConfig(options: ReteConfig, outputs: OutputOptions[], p
/^@babel\/runtime.*$/
],
plugins: [
...(head ? [
copy({
targets: [
{ src: 'README.md', dest: localOutputDirectories }
]
}),
...outputDirectories.map(output => {
const bundlesPath = join(output, outputPath)
...head
? [
copy({
targets: [
{ src: 'README.md', dest: localOutputDirectories }
]
}),
...outputDirectories.map(output => {
const bundlesPath = join(output, outputPath)

return preparePackageJson(pkg, bundlesPath, (config) => {
for (const { suffix, entries } of outputs) {
for (const entry of entries) {
config[entry] = getBundleName(suffix)
return preparePackageJson(pkg, bundlesPath, config => {
for (const { suffix, entries } of outputs) {
for (const entry of entries) {
config[entry] = getBundleName(suffix)
}
}
}

config.types = getDTSPath(input, output, bundlesPath)
config.typings = config.types
config.types = getDTSPath(input, output, bundlesPath)
config.typings = config.types
})
})
})
] : []),
...(nodeResolveOptions === false ? [] : [nodeResolve({
extensions,
...(nodeResolveOptions || {})
})]),
]
: [],
...nodeResolveOptions === false
? []
: [
nodeResolve({
extensions,
...nodeResolveOptions ?? {}
})
],
babel({
exclude: 'node_modules/**',
babelrc: false,
presets: babelPresets,
plugins: bundled ? babelOptions?.plugins : [
require('@babel/plugin-transform-runtime'),
...(babelOptions?.plugins ? babelOptions.plugins : [])
],
babelHelpers: bundled ? 'bundled' : 'runtime',
plugins: bundled
? babelOptions?.plugins
: [
require('@babel/plugin-transform-runtime'),
...babelOptions?.plugins

Check warning on line 117 in src/build/config.ts

View workflow job for this annotation

GitHub Actions / ci / ci

Unsafe spread of an `any` value in an array
? babelOptions.plugins
: []
],
babelHelpers: bundled
? 'bundled'
: 'runtime',
extensions
}),
...plugins
Expand Down
57 changes: 35 additions & 22 deletions src/build/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ function getIndex(config: RollupOptions | RollupOptions[], output: readonly stri
return config.findIndex(configItem => {
const configOutputs = !configItem.output
? []
: Array.isArray(configItem.output) ? configItem.output : [configItem.output]
: Array.isArray(configItem.output)
? configItem.output
: [configItem.output]

return configOutputs.map(({ file }) => file).find(out => out && output.includes(out))
})
Expand All @@ -22,26 +24,37 @@ function getIndex(config: RollupOptions | RollupOptions[], output: readonly stri
export async function buildDev(name: string, config: RollupOptions | RollupOptions[], outputDirectories: string[]) {
const watcher = watch(config)

// eslint-disable-next-line max-statements
watcher.on('event', async e => {
if (e.code === 'START') {
safeExec(() => lint(false, true), messages.lintingFail)
safeExec(() => generateTypes(outputDirectories), messages.typesFail)
} else if (e.code === 'BUNDLE_START') {
const index = getIndex(config, e.output)

console.log(chalk.green(`Start building ${name}${index >= 0 ? `[${index}]` : ''} ...`))
} else if (e.code === 'BUNDLE_END') {
const index = getIndex(config, e.output)
const duration = ms(e.duration, { secondsDecimalDigits: 1 })

console.log(chalk.green(`Build ${name}${index >= 0 ? `[${index}]` : ''} completed in ${duration}`))
} else if (e.code === 'ERROR') {
const { id, loc /* , codeFrame*/ } = e.error

console.log(chalk.red('Error', e.error.message))
if (loc) console.log(chalk.green(id+':'+loc.line))
// log(codeFrame) break
}
return new Promise<void>((resolve, reject) => {
// eslint-disable-next-line max-statements
watcher.on('event', e => {
if (e.code === 'START') {
void safeExec(() => lint(false, true), messages.lintingFail)
void safeExec(() => generateTypes(outputDirectories), messages.typesFail)
} else if (e.code === 'BUNDLE_START') {
const index = getIndex(config, e.output)
const indexLabel = index >= 0
? `[${index}]`
: ''

console.log(chalk.green(`Start building ${name}${indexLabel} ...`))
} else if (e.code === 'BUNDLE_END') {
const index = getIndex(config, e.output)
const duration = ms(e.duration, { secondsDecimalDigits: 1 })
const indexLabel = index >= 0
? `[${index}]`
: ''

console.log(chalk.green(`Build ${name}${indexLabel} completed in ${duration}`))
} else if (e.code === 'ERROR') {
const { id, loc /* , codeFrame*/ } = e.error

console.log(chalk.red('Error', e.error.message))
if (loc) console.log(chalk.green(`${id}:${loc.line}`))
// log(codeFrame) break
reject(new Error(e.error.message))
} else {
resolve()
}
})
})
}
6 changes: 4 additions & 2 deletions src/build/gen-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function getDTSPath(srcScript: string, distPath: string, packageDirectory

export async function generateTypes(outputDirectories: string[]) {
const config = await readTSConfig(process.cwd())
const target = config?.compilerOptions?.target || 'es5'
const target = config?.compilerOptions?.target ?? 'es5'

for (let i = 0; i < outputDirectories.length; i++) {
const outputDirectory = outputDirectories[i]
Expand All @@ -31,6 +31,8 @@ export async function generateTypes(outputDirectories: string[]) {
'--declarationMap',
'--downlevelIteration',
'--emitDeclarationOnly'
], { stdio: i === 0 ? 'inherit' : 'ignore' })
], { stdio: i === 0
? 'inherit'
: 'ignore' })
}
}
10 changes: 6 additions & 4 deletions src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ const outputs: OutputOptions[] = [

async function buildForDev(config: ReteConfig, pkg: Pkg, outputDirectories: string[]) {
const targetConfig = getRollupConfig(config, outputs, pkg, outputDirectories)
const name = Array.from(new Set(Array.isArray(config) ? config.map(c => c.name) : [config.name])).join(', ')
const name = Array.from(new Set(Array.isArray(config)
? config.map(c => c.name)
: [config.name])).join(', ')

return await buildDev(name, targetConfig.map(c => c.config), outputDirectories)

Check warning on line 28 in src/build/index.ts

View workflow job for this annotation

GitHub Actions / ci / ci

Returning a void expression from a function is forbidden. Please remove the `return` statement
}
Expand All @@ -39,7 +41,7 @@ async function build(config: ReteConfig, pkg: Pkg, outputDirectories: string[])

for (const target of targets) {
const bundle = await rollup(target.config)
const distDirectory = target.options.output || ''
const distDirectory = target.options.output ?? ''

for (const output of target.config.output) {
await bundle.generate(output)
Expand All @@ -56,8 +58,8 @@ export default async (configPath: string, watch?: boolean, outputDirectories?: s
const config = importReteConfig(fullPath)

const packagePath = join(process.cwd(), 'package.json')
const pkg = require(packagePath)
const output = outputDirectories || [join(process.cwd(), 'dist')]
const pkg = require(packagePath) as Pkg
const output = outputDirectories ?? [join(process.cwd(), 'dist')]

if (watch) {
await buildForDev(config, pkg, output)
Expand Down
1 change: 0 additions & 1 deletion src/build/package-json.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-undefined */
import fs from 'fs'
import { join } from 'path'
import { Plugin } from 'rollup'
Expand Down
6 changes: 3 additions & 3 deletions src/build/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ export interface ReteOptions {
output?: string
plugins?: RollupOptions['plugins']
babel?: {
presets?: any[];
plugins?: any[];
presets?: any[]

Check warning on line 10 in src/build/types.ts

View workflow job for this annotation

GitHub Actions / ci / ci

Unexpected any. Specify a different type
plugins?: any[]
}
nodeResolve?: RollupNodeResolveOptions | false,
nodeResolve?: RollupNodeResolveOptions | false
globals?: OutputOptions['globals']
}
export type Pkg = { name: string, version: string, author: string, license: string, scripts?: Record<string, string> }
Expand Down
6 changes: 4 additions & 2 deletions src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function setVerbose(enabled: boolean) {
verbose = enabled
}

export async function safeExec<T>(func: () => Promise<T>, failMessage: string, exit?: number): Promise<T | unknown> {
export async function safeExec<T>(func: () => Promise<T>, failMessage: string, exit?: number): Promise<unknown> {
try {
await func()
} catch (error) {
Expand All @@ -28,7 +28,9 @@ interface TSConfig {

export async function readTSConfig(cwd: string): Promise<null | TSConfig> {
const configPath = join(cwd, 'tsconfig.json')
const exists = await fs.promises.access(configPath).then(() => true).catch(() => false)
const exists = await fs.promises.access(configPath)
.then(() => true)
.catch(() => false)

if (!exists) return null

Expand Down
2 changes: 1 addition & 1 deletion src/doc/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { SOURCE_FOLDER } from '../consts'
export async function doc(entries?: string[]) {
const root = process.cwd()
const outputDir = join(root, 'docs')
const entryPoints = (entries || [join(SOURCE_FOLDER, 'index.ts')]).map(entry => join(root, entry))
const entryPoints = (entries ?? [join(SOURCE_FOLDER, 'index.ts')]).map(entry => join(root, entry))
const app = await Application.bootstrap({
excludeNotDocumented: true,
excludePrivate: true,
Expand Down
18 changes: 10 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import test from './test'

const program = createCommand()

program.version(require('../package.json').version)
program.version((require('../package.json') as { version: string }).version)

program
.command('build')
Expand All @@ -19,34 +19,36 @@ program
.option('-w --watch')
.option('-o --output <path>')
.option('-v --verbose')
.action((options: { config: string, watch?: boolean, output?: string, verbose?: boolean }) => {
.action(async (options: { config: string, watch?: boolean, output?: string, verbose?: boolean }) => {
if (options.verbose) setVerbose(true)
build(options.config, options.watch, options.output?.split(','))
await build(options.config, options.watch, options.output?.split(','))
})

program
.command('lint')
.description('Lint using ESLint and TS parser')
.option('--fix')
.action((options: { fix?: boolean }) => {
lint(options.fix)
.action(async (options: { fix?: boolean }) => {
await lint(options.fix)
})

program
.command('doc')
.description('Generate API docs')
.option('--entries <entries>', 'Comma-separated list of entry points')
.action(async (options: { entries?: string }) => {
await doc(options.entries ? options.entries.split(',') : void 0)
await doc(options.entries
? options.entries.split(',')
: void 0)
})

program
.command('test')
.description('Run tests')
.description('Run tests using Jest')
.option('-w --watch')
.action((options: { watch?: boolean }) => {
test(options.watch)
.action(async (options: { watch?: boolean }) => {
await test(options.watch)
})

program.parse(process.argv)
Expand Down
6 changes: 3 additions & 3 deletions src/lint/eslint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ export class ESLint implements BaseLinter {
const result: LintMessage = {
column: message.column,
line: message.line,
endColumn: message.endColumn || message.column,
endLine: message.endLine || message.line,
ruleId: message.ruleId || null,
endColumn: message.endColumn ?? message.column,
endLine: message.endLine ?? message.line,
ruleId: message.ruleId ?? null,
message: message.message,
severity: message.severity
}
Expand Down
Loading

0 comments on commit f339a43

Please sign in to comment.