Skip to content

Commit

Permalink
chore: add linter strict-boolean-expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack-Works committed Feb 7, 2020
1 parent 684467e commit a2ec465
Show file tree
Hide file tree
Showing 14 changed files with 783 additions and 47 deletions.
1 change: 1 addition & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jobs:
paths:
- node_modules
key: v1-dependencies-{{ checksum "yarn.lock" }}
- run: yarn eslint
- run: yarn build
- save_cache:
paths:
Expand Down
6 changes: 6 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
es
doc
temp
*.spec.ts
*.test.ts
umd
37 changes: 37 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module",
"project": "./tsconfig.json"
},
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [],
"env": {},
"rules": {
"no-debugger": "error",
"no-plusplus": "error",
"no-bitwise": "error",
"no-new-wrappers": "error",
"constructor-super": "error",
"no-redeclare": "error",
"no-eval": "error",
"no-template-curly-in-string": "error",
"no-return-await": "error",
"no-sparse-arrays": "error",
"dot-notation": "error",
"no-fallthrough": "error",
"prefer-const": "error",
"eqeqeq": "error",
"no-extra-bind": "error",
"use-isnan": "error",
"@typescript-eslint/strict-boolean-expressions": [
2,
{
"allowNullable": true,
"allowSafe": true,
"ignoreRhs": true
}
]
}
}
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"build": "cross-env NODE_ENV=production npm-run-all --parallel clean \"build:tsc -- {@}\" build:rollup",
"build:tsc": "tsc",
"build:rollup": "rollup -c -m",
"eslint": "eslint . --ext .ts,.tsx",
"eslint:watch": "yarn esw . --ext .ts,.tsx -w --color",
"clean": "rimraf ./es ./umd",
"prepublishOnly": "npm run build",
"doc": "npm-run-all --serial build:tsc doc:api doc:md",
Expand All @@ -38,7 +40,11 @@
"@rollup/plugin-replace": "^2.3.1",
"@types/lodash-es": "^4.1.4",
"@types/mocha": "^7.0.1",
"@typescript-eslint/eslint-plugin": "^2.19.0",
"@typescript-eslint/parser": "^2.19.0",
"cross-env": "^7.0.0",
"eslint": "^6.8.0",
"eslint-watch": "^6.0.1",
"jsdom": "^16.1.0",
"jsdom-global": "^3.0.2",
"mocha": "^7.0.1",
Expand Down
9 changes: 5 additions & 4 deletions src/DOM/Proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function DOMProxy<
let virtualAfter: After | null = null
let virtualAfterShadow: ShadowRoot | null = null
/** All changes applied on the `proxy` */
let changes: ActionTypes[keyof ActionTypes][] = []
const changes: ActionTypes[keyof ActionTypes][] = []
/** Read Traps */
const readonlyTraps: ProxyHandler<any> = {
ownKeys: () => {
Expand Down Expand Up @@ -132,7 +132,7 @@ export function DOMProxy<
const modifyTrapsNotWrite = modifyTraps(false)
const proxy = Proxy.revocable(defaultCurrent, { ...readonlyTraps, ...modifyTrapsWrite })
function hasStyle(e: Node): e is HTMLElement {
return !!(e as any).style
return 'style' in e
}
/** Call before realCurrent change */
function undoEffects(nextCurrent?: Node | null) {
Expand All @@ -144,7 +144,7 @@ export function DOMProxy<
} else if (attr === 'appendChild') {
if (!nextCurrent) {
const node = (change.op.thisArg as Parameters<HTMLElement['appendChild']>)[0]
node && current.removeChild(node)
if (node !== undefined) current.removeChild(node)
}
}
} else if (change.type === 'modifyStyle') {
Expand All @@ -170,7 +170,7 @@ export function DOMProxy<
const replayable = ['appendChild', 'addEventListener', 'before', 'after']
const key: keyof Node = change.op.name as any
if (replayable.indexOf(key) !== -1) {
if (current[key]) {
if (current[key] !== undefined) {
;(current[key] as any)(...change.op.param)
} else {
console.warn(current, `doesn't have method "${key}", replay failed.`)
Expand Down Expand Up @@ -294,6 +294,7 @@ export function DOMProxy<
DOMProxyDevtoolsEnhancer.allDOMProxy.set(DOMProxyObject, changes)
return DOMProxyObject
}
// eslint-disable-next-line no-redeclare
export namespace DOMProxy {
export function enhanceDebugger() {
installCustomObjectFormatter(new DOMProxyDevtoolsEnhancer())
Expand Down
16 changes: 8 additions & 8 deletions src/DOM/Watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ export abstract class Watcher<T, Before extends Element, After extends Element,
/** window.requestIdleCallback, or polyfill. */
protected readonly requestIdleCallback = requestIdleCallback
/** For debug usage. Just keep it. */
private readonly stack = new Error().stack || ''
private readonly stack = new Error().stack ?? ''
//#endregion
//#region Warnings
/**
Expand Down Expand Up @@ -722,10 +722,10 @@ type useForeachReturns<T> =

function applyUseForeachCallback<T>(callback: useForeachReturns<T>) {
const cb = callback as useForeachReturns<Node>
let remove: any, change: any, mutation: any
if (cb === undefined) {
} else if (typeof cb === 'function') remove = cb
else if (cb) {
type f = undefined | ((...args: any[]) => any)
let remove: f, change: f, mutation: f
if (typeof cb === 'function') remove = cb
else if (cb !== undefined) {
const { onNodeMutation, onRemove, onTargetChanged } = cb
;[remove, change, mutation] = [onRemove, onTargetChanged, onNodeMutation]
}
Expand Down Expand Up @@ -759,17 +759,17 @@ interface WarningOptions {
function warning(_: Partial<WarningOptions> = {}) {
const { dev, once, fn } = { ...({ dev: false, once: true, fn: () => {} } as WarningOptions), ..._ }
if (dev) if (process.env.NODE_ENV !== 'development') return { warn(f = fn) {}, ignored: true, stack: '' }
const [_0, _1, _2, ...lines] = (new Error().stack || '').split('\n')
const [_0, _1, _2, ...lines] = (new Error().stack ?? '').split('\n')
const stack = lines.join('\n')
let warned = 0
const obj = {
ignored: false,
stack,
warn(f = fn) {
if (obj.ignored) return
if (warned && once) return
if (warned > 0 && once) return
if (typeof once === 'number' && warned <= once) return
warned++
warned = warned + 1
f(stack)
},
}
Expand Down
2 changes: 1 addition & 1 deletion src/Debuggers/DOMProxyDevtoolsEnhancer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class DOMProxyDevtoolsEnhancer implements React.CustomObjectFormatter {
decorateShadow(obj: ShadowRoot) {
return <span>{`#shadow-root (${obj.mode})`}</span>
}
body(obj: DOMProxy<any, any, any>, clearState: boolean) {
body(obj: DOMProxy<Node, Element, Element>, clearState: boolean) {
const [state, setState, render] = React.useState(obj, x)
if (clearState) setState({ refreshed: false })

Expand Down
2 changes: 1 addition & 1 deletion src/Debuggers/LiveSelectorDevtoolsEnhancer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class LiveSelectorDevtoolsEnhancer implements React.CustomObjectFormatter
// @ts-ignore
initialElements: obj.initialElements,
// @ts-ignore
stack: obj.stack || '',
stack: obj.stack ?? '',
// @ts-ignore
selectorChain: obj.selectorChain,
}
Expand Down
12 changes: 10 additions & 2 deletions src/Debuggers/WatcherDevtoolsEnhancer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ export class WatcherDevtoolsEnhancer implements React.CustomObjectFormatter {
setState({ refreshed: true })
forceRender()
}
function isNil(x: any): boolean {
if (x === null || x === undefined) return false
return true
}
return (
<div>
<span variant={['fade']}>Last values:</span>
Expand All @@ -102,13 +106,17 @@ export class WatcherDevtoolsEnhancer implements React.CustomObjectFormatter {
<span variant={['fade']}>Other:</span>
<table>
{this.optionsRow('LiveSelector', priv.liveSelector, () => false)}
{this.optionsRow('ConsistentWatchRoot', priv.consistentWatchRoot, x => x === document.body || !x)}
{this.optionsRow(
'ConsistentWatchRoot',
priv.consistentWatchRoot,
x => x === document.body || isNil(x),
)}
{this.optionsRow('DomProxyOptions', priv.domProxyOption, x => Object.keys(x).length === 0)}
{this.optionsRow('KeyComparer', priv.keyComparer, x => x(test, test))}
{this.optionsRow('ValueComparer', priv.valueComparer, x => x(test, test))}
{this.optionsRow('MapNodeToKey', priv.mapNodeToKey, x => x(test, 0, []) === test)}
{this.optionsRow('FirstDOMProxy', obj.firstDOMProxy, x => true)}
{this.optionsRow('stopWatchOnDisconnected', priv.stopWatchOnDisconnected, x => !x)}
{this.optionsRow('stopWatchOnDisconnected', priv.stopWatchOnDisconnected, isNil)}
</table>
<br />
<div variant={['bigint']}>Actions:</div>
Expand Down
2 changes: 1 addition & 1 deletion src/Extension/AutomatedTabTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export function AutomatedTabTask<T extends Record<string, (...args: any[]) => Pr

let finalURL: string
if (typeof urlOrTabID === 'string') finalURL = urlOrTabID
else finalURL = url || ''
else finalURL = url ?? ''
function proxyTrap(_target: unknown, taskName: string | number | symbol) {
return (...taskArgs: any[]) => {
if (typeof taskName !== 'string') throw new TypeError('Key must be a string')
Expand Down
15 changes: 8 additions & 7 deletions src/Extension/Context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@ export type Contexts = 'background' | 'content' | 'webpage' | 'unknown' | 'optio
*/
export function GetContext(): Contexts {
if (typeof location === 'undefined') return 'unknown'
if (typeof browser !== 'undefined') {
if (location.protocol.match('-extension')) {
if (typeof browser !== 'undefined' && browser !== null) {
const scheme = location.protocol.match('-extension')
const backgroundURL = browser.extension?.getBackgroundPage()?.location?.href
if (scheme || location.hostname === 'localhost') {
if (
browser.extension && browser.extension.getBackgroundPage
? browser.extension.getBackgroundPage().location.href === location.href
: ['generated', 'background', 'page', '.html'].every(x => location.pathname.match(x))
backgroundURL === location.href ||
['generated', 'background', 'page', '.html'].every(x => location.pathname.match(x))
)
return 'background'
return 'options'
}
if (browser.runtime && browser.runtime.getManifest) return 'content'
if (scheme) return 'options'
if (browser.runtime?.getManifest !== undefined) return 'content'
}
// What about rollup?
if (location.hostname === 'localhost') return 'debugging'
Expand Down
10 changes: 5 additions & 5 deletions src/Extension/MessageCenter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export class MessageCenter<ITypedMessages> {
public serialization: Serialization = NoSerialization
private eventEmitter = mitt()
private listener = async (request: unknown) => {
let { key, data, instanceKey } = (await this.serialization.deserialization(request)) as InternalMessageType
const { key, data, instanceKey } = (await this.serialization.deserialization(request)) as InternalMessageType
// Message is not for us
if (this.instanceKey !== (instanceKey || '')) return
if (!key || !data) return
if (this.instanceKey !== (instanceKey ?? '')) return
if (key === undefined) return
if (this.log) {
console.log(
`%cReceive%c %c${key.toString()}`,
Expand Down Expand Up @@ -97,14 +97,14 @@ export class MessageCenter<ITypedMessages> {
const serialized = await this.serialization.serialization({
data,
key,
instanceKey: this.instanceKey || '',
instanceKey: this.instanceKey ?? '',
} as InternalMessageType)
if (typeof browser !== 'undefined') {
browser.runtime?.sendMessage?.(serialized).catch(noop)
// Send message to Content Script
browser.tabs?.query({ discarded: false }).then(tabs => {
for (const tab of tabs) {
if (tab.id) browser.tabs.sendMessage(tab.id, serialized).catch(noop)
if (tab.id !== undefined) browser.tabs.sendMessage(tab.id, serialized).catch(noop)
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion src/util/sleep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const timeout = <T>(promise: PromiseLike<T>, time: number, rejectReason?:
const race = Promise.race([
promise,
new Promise<T>((r, reject) => {
timer = setTimeout(() => reject(new Error(rejectReason || 'timeout')), time)
timer = setTimeout(() => reject(new Error(rejectReason ?? 'timeout')), time)
}),
])
race.finally(() => clearTimeout(timer))
Expand Down
Loading

0 comments on commit a2ec465

Please sign in to comment.