Skip to content

Commit

Permalink
style: add eslint-plugin-unicorn and apply rules
Browse files Browse the repository at this point in the history
  • Loading branch information
maxnowack committed Jan 8, 2025
1 parent 664680b commit 993e093
Show file tree
Hide file tree
Showing 60 changed files with 875 additions and 395 deletions.
23 changes: 11 additions & 12 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { withMermaid } from 'vitepress-plugin-mermaid'
import { createRequire } from 'module'

const require = createRequire(import.meta.url)
const pkg = require('../../packages/base/core/package.json')
const package_ = require('../../packages/base/core/package.json')

function buildRedirectHtml(to: string) {
return `<!DOCTYPE html><html><title>Redirecting...</title><meta http-equiv="refresh" content="0; url=${to}"><link rel="canonical" href="${to}"><body><a href="${to}">Redirecting...</a></body></html>`
}

// https://vitepress.dev/reference/site-config
export default withMermaid({
Expand All @@ -18,7 +22,7 @@ export default withMermaid({
{ text: 'Get Started', link: '/getting-started/' },
{ text: 'Reference', link: '/reference/' },
{
text: pkg.version,
text: package_.version,
items: [
{
text: 'Changelog',
Expand Down Expand Up @@ -195,7 +199,7 @@ export default withMermaid({
hostname: 'https://signaldb.js.org',
lastmodDateOnly: true,
transformItems(items) {
const exclude = [
const exclude = new Set([
'/googlef8c159020eb311c9',
'/404',
'/examples/firebase',
Expand All @@ -206,16 +210,12 @@ export default withMermaid({
'/examples/supabase/404',
'guides/',
'integrations/',
]
return items.filter(item => !exclude.includes(item.url))
])
return items.filter(item => !exclude.has(item.url))
},
},

buildEnd: async () => {
function buildRedirectHtml(to: string) {
return `<!DOCTYPE html><html><title>Redirecting...</title><meta http-equiv="refresh" content="0; url=${to}"><link rel="canonical" href="${to}"><body><a href="${to}">Redirecting...</a></body></html>`
}

const redirects = {
'/collections.html': '/reference/core/collection/',
'/collections/index.html': '/reference/core/collection/',
Expand Down Expand Up @@ -285,10 +285,9 @@ export default withMermaid({
'/troubleshooting.html': '/troubleshooting/',
}

await Object.entries(redirects).reduce(async (promise, [from, to]) => {
await promise
for (const [from, to] of Object.entries(redirects)) {
await fs.mkdir(path.dirname(`./docs/.vitepress/dist${from}`), { recursive: true })
await fs.writeFile(`./docs/.vitepress/dist${from}`, buildRedirectHtml(to))
}, Promise.resolve())
}
},
})
3 changes: 1 addition & 2 deletions docs/.vitepress/theme/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import DefaultTheme from 'vitepress/theme'
import './custom.css'

export default DefaultTheme
export { default } from 'vitepress/theme'
2 changes: 1 addition & 1 deletion docs/sync/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ const syncManager = new SyncManager({
Below is an example implementation of a simple REST API.

```js
import { EventEmitter } from 'node:events'
import { EventEmitter } from 'events'
import { Collection, SyncManager } from '@signaldb/core'

const Authors = new Collection()
Expand Down
48 changes: 42 additions & 6 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ import testingLibraryPlugin from 'eslint-plugin-testing-library'
import jsdocPlugin from 'eslint-plugin-jsdoc'
import vitestPlugin from 'eslint-plugin-vitest'
import stylisticPlugin from '@stylistic/eslint-plugin'
import unicornPlugin from 'eslint-plugin-unicorn'
import FastGlob from 'fast-glob'
import fs from 'fs'
import path from 'path'

const { workspaces } = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf-8'))
const projectDirs = workspaces
/* istanbul ignore next -- @preserve */
const { workspaces } = JSON.parse(fs.readFileSync(new URL('package.json', import.meta.url), 'utf8'))
/* istanbul ignore next -- @preserve */
const projectDirectories = workspaces
.flatMap(pattern => FastGlob.sync(pattern, { onlyDirectories: true }))
.filter(projectPath => fs.existsSync(path.join(import.meta.url, projectPath, 'package.json')))

Expand All @@ -23,13 +26,15 @@ export default tseslint.config(
tseslintConfigs.recommendedTypeChecked,
importPlugin.recommended,
stylisticPlugin.configs['recommended-flat'],
jsdocPlugin.configs['flat/recommended-typescript'],
// jsdocPlugin.configs['flat/recommended-typescript'],
vitestPlugin.configs.recommended,
unicornPlugin.configs['flat/recommended'],
{
plugins: {
'react': reactPlugin,
'jsx-a11y': jsxA11yPlugin,
'@stylistic': stylisticPlugin,
'jsdoc': jsdocPlugin,
},
linterOptions: {
reportUnusedDisableDirectives: 'error',
Expand Down Expand Up @@ -57,6 +62,36 @@ export default tseslint.config(
'import/extensions': ['.js', '.cjs', '.mjs', '.ts', '.mts', '.tsx'],
},
rules: {
'unicorn/consistent-function-scoping': ['error', { checkArrowFunctions: false }],
'unicorn/no-useless-undefined': ['error', {
checkArguments: false,
}],
'unicorn/prevent-abbreviations': ['error', {
checkFilenames: false,
allowList: {
i: true,
fn: true,
args: true,
props: true,
refs: true,
},
}],
'unicorn/no-null': 'off',
'unicorn/prefer-event-target': 'off',
'unicorn/filename-case': ['error', {
cases: { camelCase: true, pascalCase: true },
ignore: [
String.raw`next-env\.d\.ts$`,
],
}],
'unicorn/prefer-module': 'off',
'unicorn/no-array-reduce': 'off',
'unicorn/no-array-method-this-argument': 'off',
'unicorn/no-array-callback-reference': 'off',
'unicorn/prefer-array-index-of': 'off',
'unicorn/prefer-node-protocol': 'off',
'unicorn/no-array-for-each': 'off', // disabled until this issue was resolved: https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1788
'@typescript-eslint/require-await': 'off',
'no-console': 'error',
'@stylistic/quotes': ['error', 'single', { avoidEscape: true }],
'@stylistic/indent-binary-ops': ['off'], // disabled until this issue was resolved: https://github.com/eslint-stylistic/eslint-stylistic/issues/546
Expand Down Expand Up @@ -135,8 +170,9 @@ export default tseslint.config(
{ files: ['commitlint.config.js'], languageOptions: { globals: globals.node } },
{ files: ['**/next.config.js'], languageOptions: { globals: globals.commonjs } },
// https://github.com/import-js/eslint-plugin-import/issues/1913#issuecomment-1034025709
...projectDirs.map(projectDir => ({
files: [`${projectDir}/**/*.{t,j}s`, `${projectDir}/**/*.m{t,j}s`],
/* istanbul ignore next -- @preserve */
...projectDirectories.map(projectDirectory => ({
files: [`${projectDirectory}/**/*.{t,j}s`, `${projectDirectory}/**/*.m{t,j}s`],
rules: {
'import/no-extraneous-dependencies': ['error', {
devDependencies: [
Expand All @@ -150,7 +186,7 @@ export default tseslint.config(
'**/vite.config.mts',
'**/vitest.config.mts',
],
packageDir: [import.meta.url, path.join(import.meta.url, projectDir)],
packageDir: [import.meta.url, path.join(import.meta.url, projectDirectory)],
}],
},
})),
Expand Down
6 changes: 3 additions & 3 deletions examples/appwrite/src/containers/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ const App: React.FC = () => {
type="text"
value={text}
placeholder="Type and press Enter to add a new item …"
onChange={e => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onChange={event => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (text === '') return
Todos.insert({
text,
Expand Down
14 changes: 7 additions & 7 deletions examples/appwrite/src/system/syncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ client
.setEndpoint('https://cloud.appwrite.io/v1')
.setProject('6567685ea287ba49be81')

const dbId = '65676881edfe6a3e7e2c'
const db = new Databases(client)
const databaseId = '65676881edfe6a3e7e2c'
const database = new Databases(client)

const syncManager = new SyncManager<Record<string, any>, { id: string }>({
persistenceAdapter: id => createIndexedDBAdapter(id),
Expand All @@ -20,10 +20,10 @@ const syncManager = new SyncManager<Record<string, any>, { id: string }>({
const handleChange = () => {
void onChange()
}
client.subscribe(`databases.${dbId}.collections.${name}.documents`, handleChange)
client.subscribe(`databases.${databaseId}.collections.${name}.documents`, handleChange)
},
async pull({ name }) {
const { documents } = await db.listDocuments(dbId, name)
const { documents } = await database.listDocuments(databaseId, name)
return {
items: documents.map(({
$collectionId,
Expand All @@ -41,13 +41,13 @@ const syncManager = new SyncManager<Record<string, any>, { id: string }>({
async push({ name }, { changes }) {
await Promise.all([
...changes.added.map(async ({ id, ...item }) => {
await db.createDocument(dbId, name, id, item)
await database.createDocument(databaseId, name, id, item)
}),
...changes.modified.map(async ({ id, ...item }) => {
await db.updateDocument(dbId, name, id, item)
await database.updateDocument(databaseId, name, id, item)
}),
...changes.removed.map(async (item) => {
await db.deleteDocument(dbId, name, item.id)
await database.deleteDocument(databaseId, name, item.id)
}),
])
},
Expand Down
6 changes: 3 additions & 3 deletions examples/firebase/src/containers/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ const App: React.FC = () => {
type="text"
value={text}
placeholder="Type and press Enter to add a new item …"
onChange={e => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onChange={event => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (text === '') return
Todos.insert({
text,
Expand Down
16 changes: 8 additions & 8 deletions examples/firebase/src/system/syncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getDatabase, ref, get, set, remove, update, onChildAdded, onChildChange
initializeApp({
databaseURL: 'https://signaldb-d7e71-default-rtdb.firebaseio.com',
})
const db = getDatabase()
const database = getDatabase()

const syncManager = new SyncManager({
persistenceAdapter: id => createIndexedDBAdapter(id),
Expand All @@ -18,31 +18,31 @@ const syncManager = new SyncManager({
const handleChange = () => {
void onChange()
}
onChildAdded(ref(db, name), () => {
onChildAdded(ref(database, name), () => {
void handleChange()
})
onChildChanged(ref(db, name), () => {
onChildChanged(ref(database, name), () => {
void handleChange()
})
onChildRemoved(ref(db, name), () => {
onChildRemoved(ref(database, name), () => {
void handleChange()
})
},
async pull({ name }) {
const snapshot = await get(ref(db, name))
const snapshot = await get(ref(database, name))
const items = await snapshot.val() as Record<string, any> | null
return { items: Object.values(items ?? {}) }
},
async push({ name }, { changes }) {
await Promise.all([
...changes.added.map(async (item) => {
await set(ref(db, `${name}/${item.id}`), item)
await set(ref(database, `${name}/${item.id}`), item)
}),
...changes.modified.map(async (item) => {
await update(ref(db, `${name}/${item.id}`), item)
await update(ref(database, `${name}/${item.id}`), item)
}),
...changes.removed.map(async (item) => {
await remove(ref(db, `${name}/${item.id}`))
await remove(ref(database, `${name}/${item.id}`))
}),
])
},
Expand Down
6 changes: 3 additions & 3 deletions examples/replication-http/src/containers/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ const App: React.FC = () => {
type="text"
value={text}
placeholder="Type and press Enter to add a new item …"
onChange={e => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onChange={event => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (text === '') return
Todos.insert({
text,
Expand Down
3 changes: 2 additions & 1 deletion examples/replication-http/src/system/syncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ const syncManager = new SyncManager({
text: string,
completed: boolean,
}[],
} = await authenticatedFetch(`/collections/${name}/documents`).then(res => res.json())
} = await authenticatedFetch(`/collections/${name}/documents`)
.then(fetchResult => fetchResult.json())
return {
items: result.documents.map(item => ({
id: item.$id,
Expand Down
6 changes: 3 additions & 3 deletions examples/supabase/src/containers/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ const App: React.FC = () => {
type="text"
value={text}
placeholder="Type and press Enter to add a new item …"
onChange={e => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onChange={event => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (text === '') return
Todos.insert({
text,
Expand Down
4 changes: 2 additions & 2 deletions examples/supabase/src/system/syncManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ const syncManager = new SyncManager({
.subscribe()
},
async pull({ name }) {
const docs = await supabase.from(name as any).select().returns<{ id: string }[]>()
const items = docs.data ?? []
const documents = await supabase.from(name as any).select().returns<{ id: string }[]>()
const items = documents.data ?? []
return { items }
},
async push({ name }, { changes }) {
Expand Down
Loading

0 comments on commit 993e093

Please sign in to comment.