提交 364571bc 编写于 作者: M meteorlxy

style($shared-utils): lint the code

上级 bd146ec9
...@@ -46,10 +46,10 @@ describe('resolveScopePackage', () => { ...@@ -46,10 +46,10 @@ describe('resolveScopePackage', () => {
test('incorrect format', () => { test('incorrect format', () => {
const pkg2 = resolveScopePackage('vuepress/plugin-a') const pkg2 = resolveScopePackage('vuepress/plugin-a')
expect(pkg2).toEqual({ "name": "", "org": "" }) expect(pkg2).toEqual({ 'name': '', 'org': '' })
const pkg3 = resolveScopePackage('vuepress-plugin-a') const pkg3 = resolveScopePackage('vuepress-plugin-a')
expect(pkg3).toEqual({ "name": "", "org": "" }) expect(pkg3).toEqual({ 'name': '', 'org': '' })
}) })
}) })
...@@ -123,11 +123,13 @@ describe('resolvePlugin', () => { ...@@ -123,11 +123,13 @@ describe('resolvePlugin', () => {
test('relative path', () => { test('relative path', () => {
const resolved = resolvePlugin('./plugin-a') const resolved = resolvePlugin('./plugin-a')
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(resolved.entry).toBe(require('./fixtures/plugin-a')) expect(resolved.entry).toBe(require('./fixtures/plugin-a'))
}) })
test('aosolute path', () => { test('aosolute path', () => {
const resolved = resolvePlugin(path.resolve(__dirname, 'fixtures/plugin-a')) const resolved = resolvePlugin(path.resolve(__dirname, 'fixtures/plugin-a'))
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(resolved.entry).toBe(require('./fixtures/plugin-a')) expect(resolved.entry).toBe(require('./fixtures/plugin-a'))
}) })
......
...@@ -31,7 +31,7 @@ export const getType = function (fn: any) { ...@@ -31,7 +31,7 @@ export const getType = function (fn: any) {
* ['Function', 'Object'] => 'Function or Object' * ['Function', 'Object'] => 'Function or Object'
* ['Function', 'Object', 'Number'] => 'Function, Object or Number' * ['Function', 'Object', 'Number'] => 'Function, Object or Number'
*/ */
type Type = String | Number | Boolean | RegExp | Function | Record<string, any> | Array<any> type Type = string | number | boolean | RegExp | Function | Record<string, any> | Array<any>
function toNaturalMultiTypesLanguage (types: Type[]) { function toNaturalMultiTypesLanguage (types: Type[]) {
const len = types.length const len = types.length
...@@ -47,7 +47,7 @@ export function assertTypes (value: any, types: Type[]) { ...@@ -47,7 +47,7 @@ export function assertTypes (value: any, types: Type[]) {
let valid let valid
let warnMsg let warnMsg
let actualType = toRawType(value) let actualType = toRawType(value)
const expectedTypes = [] const expectedTypes: Type[] = []
if (actualType === 'AsyncFunction') { if (actualType === 'AsyncFunction') {
actualType = 'Function' actualType = 'Function'
} }
...@@ -60,9 +60,9 @@ export function assertTypes (value: any, types: Type[]) { ...@@ -60,9 +60,9 @@ export function assertTypes (value: any, types: Type[]) {
} }
if (!valid) { if (!valid) {
warnMsg = warnMsg
`expected a ${chalk.green(toNaturalMultiTypesLanguage(expectedTypes))} ` + = `expected a ${chalk.green(toNaturalMultiTypesLanguage(expectedTypes))} `
`but got ${chalk.yellow(actualType)}.` + `but got ${chalk.yellow(actualType)}.`
} }
return { valid, warnMsg } return { valid, warnMsg }
......
...@@ -12,7 +12,7 @@ import deeplyParseHeaders from './deeplyParseHeaders' ...@@ -12,7 +12,7 @@ import deeplyParseHeaders from './deeplyParseHeaders'
const cache = new LRU({ max: 1000 }) const cache = new LRU({ max: 1000 })
export = function (content: string, include = [], md: any) { export = function (content: string, include: any[] = [], md: any) {
const key = content + include.join(',') const key = content + include.join(',')
const hit = cache.get(key) const hit = cache.get(key)
if (hit) { if (hit) {
...@@ -23,11 +23,9 @@ export = function (content: string, include = [], md: any) { ...@@ -23,11 +23,9 @@ export = function (content: string, include = [], md: any) {
const res: any[] = [] const res: any[] = []
tokens.forEach((t: any, i: any) => { tokens.forEach((t: any, i: any) => {
// @ts-ignore
if (t.type === 'heading_open' && include.includes(t.tag)) { if (t.type === 'heading_open' && include.includes(t.tag)) {
const title = tokens[i + 1].content const title = tokens[i + 1].content
// @ts-ignore const slug = t.attrs.find(([name]: any[]) => name === 'id')[1]
const slug = (t.attrs).find(([name]) => name === 'id')[1]
res.push({ res.push({
level: parseInt(t.tag.slice(1), 10), level: parseInt(t.tag.slice(1), 10),
title: deeplyParseHeaders(title), title: deeplyParseHeaders(title),
......
...@@ -44,9 +44,9 @@ export = function getPermalink ({ ...@@ -44,9 +44,9 @@ export = function getPermalink ({
pattern = removeLeadingSlash(pattern) pattern = removeLeadingSlash(pattern)
const link = const link
localePath + = localePath
pattern + pattern
.replace(/:year/, String(year)) .replace(/:year/, String(year))
.replace(/:month/, String(month)) .replace(/:month/, String(month))
.replace(/:i_month/, String(iMonth)) .replace(/:i_month/, String(iMonth))
......
...@@ -68,5 +68,5 @@ export { ...@@ -68,5 +68,5 @@ export {
globby, globby,
hash, hash,
escapeHtml, escapeHtml,
semver, semver
} }
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
import chalk from 'chalk' import chalk from 'chalk'
interface LoggerOptions { interface LoggerOptions {
logLevel: number logLevel: number;
} }
class Logger { class Logger {
...@@ -90,7 +90,6 @@ class Logger { ...@@ -90,7 +90,6 @@ class Logger {
if (this.options.logLevel < 3) { if (this.options.logLevel < 3) {
return return
} }
// @ts-ignore
console.log(chalk[color](label), ...args) console.log(chalk[color](label), ...args)
} }
...@@ -107,4 +106,3 @@ class Logger { ...@@ -107,4 +106,3 @@ class Logger {
*/ */
export = new Logger() export = new Logger()
...@@ -4,6 +4,7 @@ import semver from 'semver' ...@@ -4,6 +4,7 @@ import semver from 'semver'
import env from './env' import env from './env'
function resolveFallback (request: string, options: { paths: string[] }) { function resolveFallback (request: string, options: { paths: string[] }) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Module = require('module') const Module = require('module')
const isMain = false const isMain = false
const fakeParent = new Module('', null) const fakeParent = new Module('', null)
...@@ -24,28 +25,37 @@ function resolveFallback (request: string, options: { paths: string[] }) { ...@@ -24,28 +25,37 @@ function resolveFallback (request: string, options: { paths: string[] }) {
const filename = Module._findPath(request, paths, isMain) const filename = Module._findPath(request, paths, isMain)
if (!filename) { if (!filename) {
const err = new Error(`Cannot find module '${request}'`) const err: Error & { code?: string } = new Error(`Cannot find module '${request}'`)
// @ts-ignores
err.code = 'MODULE_NOT_FOUND' err.code = 'MODULE_NOT_FOUND'
throw err throw err
} }
return filename return filename
} }
function clearRequireCache (id: string, map = new Map()) {
const module = require.cache[id]
if (module) {
map.set(id, true)
// Clear children modules
module.children.forEach((child: any) => {
if (!map.get(child.id)) clearRequireCache(child.id, map)
})
delete require.cache[id]
}
}
const resolve = semver.satisfies(process.version, '>=10.0.0') const resolve = semver.satisfies(process.version, '>=10.0.0')
? require.resolve ? require.resolve
: resolveFallback : resolveFallback
export function resolveModule (request: string, context: string): string { export function resolveModule (request: string, context: string): string {
let resolvedPath
if (env.isTest) { if (env.isTest) {
return require.resolve(request) return require.resolve(request)
} }
// module.paths is for globally install packages. // module.paths is for globally install packages.
const paths = [context || process.cwd(), ...module.paths] const paths = [context || process.cwd(), ...module.paths]
resolvedPath = resolve(request, { paths }) const resolvedPath = resolve(request, { paths })
return resolvedPath return resolvedPath
} }
...@@ -66,15 +76,3 @@ export function clearModule (request: string, context: string) { ...@@ -66,15 +76,3 @@ export function clearModule (request: string, context: string) {
clearRequireCache(resolvedPath) clearRequireCache(resolvedPath)
} }
} }
function clearRequireCache (id: string, map = new Map()) {
const module = require.cache[id]
if (module) {
map.set(id, true)
// Clear children modules
module.children.forEach((child: any) => {
if (!map.get(child.id)) clearRequireCache(child.id, map)
})
delete require.cache[id]
}
}
...@@ -17,8 +17,30 @@ import { ...@@ -17,8 +17,30 @@ import {
assertTypes assertTypes
} from './datatypes' } from './datatypes'
/**
* Parse info of scope package.
*/
const SCOPE_PACKAGE_RE = /^@(.*)\/(.*)/ const SCOPE_PACKAGE_RE = /^@(.*)\/(.*)/
export interface ScopePackage {
org: string;
name: string;
}
export function resolveScopePackage (name: string) {
if (SCOPE_PACKAGE_RE.test(name)) {
return {
org: RegExp.$1,
name: RegExp.$2
}
}
return {
org: '',
name: ''
}
}
/** /**
* Common module constructor. * Common module constructor.
*/ */
...@@ -33,20 +55,20 @@ export class CommonModule { ...@@ -33,20 +55,20 @@ export class CommonModule {
) {} ) {}
} }
function getNoopModule(error?: Error) { function getNoopModule (error?: Error) {
return new CommonModule(null, null, null, null, error) return new CommonModule(null, null, null, null, error)
} }
export interface NormalizedModuleRequest { export interface NormalizedModuleRequest {
name: string | null name: string | null;
shortcut: string | null shortcut: string | null;
} }
/** /**
* Expose ModuleResolver. * Expose ModuleResolver.
*/ */
type Type = String | Number | Boolean | RegExp | Function | Object | Record<string, any> | Array<any> type Type = string | number | boolean | RegExp | Function | Record<string, any> | Record<string, any> | Array<any>
class ModuleResolver { class ModuleResolver {
private nonScopePrefix: string private nonScopePrefix: string
...@@ -162,8 +184,8 @@ class ModuleResolver { ...@@ -162,8 +184,8 @@ class ModuleResolver {
const { shortcut, name } = this.normalizeName(req) const { shortcut, name } = this.normalizeName(req)
try { try {
const entry = this.load const entry = this.load
? loadModule(<string>name, this.cwd) ? loadModule(name as string, this.cwd)
: resolveModule(<string>name, this.cwd) : resolveModule(name as string, this.cwd)
return new CommonModule(entry, name, shortcut, true /* fromDep */) return new CommonModule(entry, name, shortcut, true /* fromDep */)
} catch (error) { } catch (error) {
return getNoopModule(error) return getNoopModule(error)
...@@ -185,8 +207,8 @@ class ModuleResolver { ...@@ -185,8 +207,8 @@ class ModuleResolver {
*/ */
normalizeName (req: string): NormalizedModuleRequest { normalizeName (req: string): NormalizedModuleRequest {
let name = null let name: string | null = null
let shortcut = null let shortcut: string | null = null
if (req.startsWith('@')) { if (req.startsWith('@')) {
const pkg = resolveScopePackage(req) const pkg = resolveScopePackage(req)
...@@ -237,28 +259,6 @@ class ModuleResolver { ...@@ -237,28 +259,6 @@ class ModuleResolver {
} }
} }
/**
* Parse info of scope package.
*/
export interface ScopePackage {
org: string;
name: string;
}
export function resolveScopePackage (name: string) {
if (SCOPE_PACKAGE_RE.test(name)) {
return {
org: RegExp.$1,
name: RegExp.$2
}
}
return {
org: '',
name: ''
}
}
export const getMarkdownItResolver = (cwd: string) => new ModuleResolver( export const getMarkdownItResolver = (cwd: string) => new ModuleResolver(
'markdown-it', '', [String, Function], true /* load module */, cwd 'markdown-it', '', [String, Function], true /* load module */, cwd
) )
......
const emojiData = require('markdown-it-emoji/lib/data/full.json') import emojiData from 'markdown-it-emoji/lib/data/full.json'
export default (str: string) => { export default (str: string) => {
return String(str).replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder) return String(str).replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder)
......
const matter = require('gray-matter') import matter from 'gray-matter'
const toml = require('toml') import toml from 'toml'
export = function parseFrontmatter (content: string) { export = function parseFrontmatter (content: string) {
return matter(content, { return matter(content, {
// eslint-disable-next-line @typescript-eslint/camelcase
excerpt_separator: '<!-- more -->', excerpt_separator: '<!-- more -->',
engines: { engines: {
toml: toml.parse.bind(toml), toml: toml.parse.bind(toml)
excerpt: false
} }
}) })
} }
// @ts-ignore
import { parse as _parse } from '@vue/component-compiler-utils' import { parse as _parse } from '@vue/component-compiler-utils'
import parseFrontmatter from './parseFrontmatter' import parseFrontmatter from './parseFrontmatter'
......
import os from 'os' import os from 'os'
class Performance { class Performance {
// @ts-ignore
private _totalMemory: number private _totalMemory: number
private _startFreeMemory: number private _startFreeMemory: number
private _endFreeMemory: number private _endFreeMemory: number
......
// string.js slugify drops non ascii chars so we have to // string.js slugify drops non ascii chars so we have to
// use a custom implementation here // use a custom implementation here
// @ts-ignore
import { remove as removeDiacritics } from 'diacritics' import { remove as removeDiacritics } from 'diacritics'
// eslint-disable-next-line no-control-regex // eslint-disable-next-line no-control-regex
......
...@@ -13,7 +13,7 @@ export = function tryChain<T, U> (resolvers: Array<Resolver<T, U>>, arg: T): U | ...@@ -13,7 +13,7 @@ export = function tryChain<T, U> (resolvers: Array<Resolver<T, U>>, arg: T): U |
continue continue
} }
try { try {
response = (<Provider<T, U>>provider)(arg) response = (provider as Provider<T, U>)(arg)
return response return response
} catch (e) { } catch (e) {
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册