Skip to content

Commit

Permalink
added: check to js api
Browse files Browse the repository at this point in the history
  • Loading branch information
binjospookie committed Dec 30, 2023
1 parent 2d37b86 commit 19f914d
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 168 deletions.
34 changes: 17 additions & 17 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,23 @@ const spinner = createSpinner(`Checking exports from the ${pkg.name} package`)

const result = await baseFlow({ pkg, config, onEmpty: spinner.success })

if (!result.success) {
spinner.error()

switch (result.error.reason) {
case 'no_exports':
printError(`Nothing is exported from ${pkg.name}. Remove it.`)
break
case 'no_imports':
printError(`Nothing is imported from ${pkg.name}. Remove it.`)
break
case 'unused_exports':
printError(`Unused exports in ${pkg.name} package found`)
printSet(result.error.exports)
}
if (result.success) {
spinner.success()
process.exit(0)
}

process.exit(1)
spinner.error()

switch (result.error.reason) {
case 'no_exports':
printError(`Nothing is exported from ${pkg.name}. Remove it.`)
break
case 'no_imports':
printError(`Nothing is imported from ${pkg.name}. Remove it.`)
break
case 'unused_exports':
printError(`Unused exports in ${pkg.name} package found`)
printSet(result.error.exports)
}

spinner.success()
process.exit(0)
process.exit(1)
9 changes: 5 additions & 4 deletions src/__tests__/js-api/collectUsages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { join } from 'node:path'
import { expect, test } from 'vitest'

import { collectUsages } from '../../index.js'
import { Result } from '../../utils/index.js'

test.each([
['package-a', new Set(['T', 'Value'])],
['package-b', new Set(['Component'])],
['package-c', new Set()],
['package-d', new Set(['getRoot', 'unusedFn'])]
['package-a', Result.Ok({ usages: new Set(['T', 'Value']) })],
['package-b', Result.Ok({ usages: new Set(['Component']) })],
['package-c', Result.Err({ usages: new Set() })],
['package-d', Result.Ok({ usages: new Set(['getRoot', 'unusedFn']) })]
])('collect usages js api for %s', async (name, result) => {
const usages = await collectUsages(name, [
{
Expand Down
21 changes: 3 additions & 18 deletions src/baseFlow.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,6 @@ import { getExports } from './getExports.js'
import { fileTraversal } from './fileTraversal/index.js'
import { Result } from './utils/index.js'

/**
* @param {{
* config: {
* babelPlugins: Array<string>
* batch: number
* entry: string
* exclude: Set<string>
* extensions: Array<string>
* dir: string
* }
* pkg: {
* path: string
* }
* }}
*/
const baseFlow = async ({ pkg, config, onEmpty }) => {
const exports = await getExports({ config, pkg })
const originalExportsSize = exports.size
Expand All @@ -28,16 +13,16 @@ const baseFlow = async ({ pkg, config, onEmpty }) => {
})

if (originalExportsSize === 0) {
resolve(Result.Err({ reason: 'no_exports' }))
resolve(Result.Err({ reason: 'no_exports', exports }))
}

await fileTraversal({ config, pkg, cmd: exports.delete.bind(exports) })

if (exports.size === originalExportsSize) {
resolve(Result.Err({ reason: 'no_imports' }))
resolve(Result.Err({ reason: 'no_imports', exports }))
}

resolve(Result.Err({ exports, reason: 'unused_exports' }))
resolve(Result.Err({ reason: 'unused_exports', exports }))
})
}

Expand Down
12 changes: 0 additions & 12 deletions src/collectUsages.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
import { fileTraversal } from './fileTraversal/index.js'
import { Result } from './utils/index.js'

/**
* @param {{
* config: {
* babelPlugins: Array<string>
* batch: number
* collectUsages: string
* exclude: Set<string>
* extensions: Array<string>
* dir: string
* },
* }}
*/
const collectUsages = async ({ config }) => {
const pkg = { name: config.collectUsages, path: '' }
const usages = new Set()
Expand Down
15 changes: 0 additions & 15 deletions src/fileTraversal/getFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,6 @@ import { fdir } from 'fdir'
const formattedExtensions = list =>
list.reduce((acc, ext) => acc + (acc ? ',' : '') + ext, '')

/**
* @param {{
* config: {
* exclude: Set<string>
* extensions: Array<string>
* dir: string
* }
* pkg: {
* name: string
* path?: string
* }
* }}
*
* @returns {Array<string>}
*/
const getFiles = async ({ config, pkg }) => {
if (pkg.path) {
config.exclude.add(pkg.path)
Expand Down
18 changes: 0 additions & 18 deletions src/fileTraversal/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,6 @@
import { processBatch } from './processBatch/index.js'
import { getFiles } from './getFiles.js'

/**
* @param {{
* cmd: {function(_: string): void}
* config: {
* babelPlugins: Array<string>
* batch: number
* exclude: Set<string>
* extensions: Array<string>
* dir: string
* }
* pkg: {
* name: string
* path?: string
* }
* }}
*
* @returns {Promise<Set.<string>>}
*/
const fileTraversal = async ({ config, pkg, cmd }) => {
const files = await getFiles({ config, pkg })
const tokens = [`from '${pkg.name}'`, `from "${pkg.name}"`]
Expand Down
6 changes: 0 additions & 6 deletions src/fileTraversal/processBatch/findImport.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@ import { createReadStream } from 'node:fs'
import { Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'

/**
* @param {{
* file: string
* tokens: Array<string>
* }}
*/
const findImport = ({ file, tokens }) =>
new Promise((resolve, reject) => {
const transformStream = new Transform({
Expand Down
14 changes: 0 additions & 14 deletions src/fileTraversal/processBatch/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import { findImport } from './findImport.js'
import { traversal } from './traversal.js'

/**
* @param {{
* files: Array<string>
* cmd: {function(_: string): void}
* config: {
* babelPlugins: Array<string>
* }
* pkg: {
* name: string
* }
* tokens: Array<string>
* }}
*
*/
const processBatch = async ({ config, cmd, files, pkg, tokens }) => {
const filesPromise = files.map(async file => {
const found = await findImport({ file, tokens })
Expand Down
12 changes: 0 additions & 12 deletions src/fileTraversal/processBatch/traversal.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,6 @@ import { parse } from '@babel/parser'

import { readFile } from '../../utils/index.js'

/**
* @param {{
* file: string
* cmd: {function(_: string): void}
* config: {
* babelPlugins: Array<string>
* }
* pkg: {
* name: string
* }
* }}
*/
const traversal = async ({ file, pkg, config, cmd }) => {
const code = await readFile(file)

Expand Down
12 changes: 0 additions & 12 deletions src/getExports.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,6 @@ import parser from '@babel/parser'

import { readFile, ObservableSet } from './utils/index.js'

/**
* @param {{
* config: {
* babelPlugins: Array<string>
* }
* pkg: {
* path: string
* }
* }}
*
* @returns {Promise<Set.<string>>}
*/
const getExports = async ({ config, pkg }) => {
const code = await readFile(pkg.path)
const result = new ObservableSet()
Expand Down
94 changes: 55 additions & 39 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,68 @@
import { baseFlow } from './baseFlow.js'
import { collectUsages as _collectUsages } from './collectUsages.js'
import { BASE_CONFIG } from './getConfig.js'
import { readJSON, Result } from './utils/index.js'

/**
* @param {{
* config: {
* entry: string
* batch: number
* list: Array.<{
* babelPlugins: Array<string>
* exclude: Set<string>
* extensions
* dir
* }>
* },
* }}
*
* @returns {Promise<Array.<string>>}
*/
const find = async ({ config }) => {
const unusedExports = new Set()

const tasks = config.list(x =>
const check = async (entry, list) => {
const { name } = await readJSON('package.json')
const pkg = { name, path: entry }

const tasks = list.map(x =>
baseFlow({
pkg,
config: {
babelPlugins: x.babelPlugins,
batch: config.batch,
entry: config.entry,
exclude: x.exclude,
extensions: x.extensions,
dir: x.dir
babelPlugins: x.babelPlugins || BASE_CONFIG.babelPlugins,
batch: x.batch || BASE_CONFIG.batch,
exclude: x.exclude
? new Set([...BASE_CONFIG.exclude, ...x.exclude])
: BASE_CONFIG.exclude,
extensions: x.extensions || BASE_CONFIG.extensions,
dir: x.dir || BASE_CONFIG.dir
}
})
)

const result = await Promise.all(tasks)
const hasSuccess = result.some(x => x.success)

if (hasSuccess) {
return Result.Ok({})
}

const noExports = result[0].error.reason === 'no_exports'

if (noExports) {
return result[0]
}

const noImports = result.every(x => x.error.reason === 'no_imports')

if (noImports) {
return result[0]
}

const [head, ...tail] = result.reduce((acc, res) => {
acc.push(res.error.exports)

return acc
}, [])

if (tail.length === 0) {
return Result.Err({ reason: 'unused_exports', exports: head })
}

for (const set of tail) {
for (const item of head) {
if (!set.has(item)) {
head.delete(item)
}
}
}

return Result.Err({ reason: 'unused_exports', exports: head })
}

// name and list[0].dir are required
/**
* @param {string} name
*
* @param {{
* babelPlugins: Array<string>,
* batch: number,
* exclude: Set<string>,
* extensions: Array<string>,
* dir: string
* }[]} list
*/
const collectUsages = async (name, list) => {
const tasks = list.map(x =>
_collectUsages({
Expand All @@ -75,7 +89,9 @@ const collectUsages = async (name, list) => {
return acc
}, [])

return new Set(mergedUsages)
return mergedUsages.length === 0
? Result.Err({ usages: new Set() })
: Result.Ok({ usages: new Set(mergedUsages) })
}

export { find, collectUsages }
export { check, collectUsages }
1 change: 0 additions & 1 deletion src/utils/observableSet.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ class ObservableSet extends Set {

add(value) {
super.add(value)
this.checkSize()
}

delete(value) {
Expand Down

0 comments on commit 19f914d

Please sign in to comment.