Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
stijnvanhulle committed Jan 21, 2024
1 parent 71f4eec commit 080aec8
Show file tree
Hide file tree
Showing 21 changed files with 150 additions and 96 deletions.
1 change: 0 additions & 1 deletion docs/plugins/swagger-zod/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,6 @@ export default defineConfig({
})
```


:::

### transformers
Expand Down
6 changes: 6 additions & 0 deletions examples/react-query-v5/kubb-log.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
swagger-tanstack-query Executing writeFile
Parameters swagger-tanstack-query writeFile
[
"export * from \"./models/index\";\nexport * from \"./hooks/index\";\n\n",
"/Users/stijnvanhulle/GitHub/kubb/examples/react-query-v5/src/gen/index.ts"
]
2 changes: 1 addition & 1 deletion examples/react-query-v5/kubb.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import createSwagger from '@kubb/swagger'
import createSwaggerTanstackQuery from '@kubb/swagger-tanstack-query'
import createSwaggerTS from '@kubb/swagger-ts'

/** @type {import('@kubb/core').KubbUserConfig} */
/** @type {import('@kubb/core').UserConfig} */
export const config = {
root: '.',
input: {
Expand Down
3 changes: 2 additions & 1 deletion examples/react-query-v5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"sideEffects": false,
"type": "module",
"scripts": {
"build": "tsup && vite build",
"build": "tsup && build:vite",
"build:vite": "vite build",
"clean": "npx rimraf ./dist",
"dev": "vite",
"generate": "kubb generate",
Expand Down
4 changes: 0 additions & 4 deletions examples/react-query-v5/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import react from '@vitejs/plugin-react'
import kubb from 'unplugin-kubb/vite'
import { defineConfig } from 'vite'
import createSwagger from '@kubb/swagger'
import createSwaggerTanstackQuery from '@kubb/swagger-tanstack-query'
import createSwaggerTS from '@kubb/swagger-ts'

import { config } from './kubb.config.js'

// https://vitejs.dev/config/
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/utils/getConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { getPlugins } from './getPlugins.ts'
import type { CLIOptions, Config, UserConfig } from '@kubb/core'
import type { CosmiconfigResult } from './getCosmiConfig.ts'

/**
* Converting UserConfig to Config without a change in the object beside the JSON convert.
*/
export async function getConfig(result: CosmiconfigResult, CLIOptions: CLIOptions): Promise<Array<Config> | Config> {
const config = result?.config
let kubbUserConfig = Promise.resolve(config) as Promise<UserConfig | Array<UserConfig>>
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/utils/getSummary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ export function getSummary({ pluginManager, status, hrstart, config, logger }: S
} as const

if (logLevel === LogLevel.debug) {
logger.debug(c.bold('\nGenerated files:\n'))
logger.debug(files.map((file) => `${randomCliColour(JSON.stringify(file.meta?.pluginKey))} ${file.path}`).join('\n'))
logger.emit('debug', ['\nGenerated files:\n'])
logger.emit('debug', files.map((file) => `${randomCliColour(JSON.stringify(file.meta?.pluginKey))} ${file.path}`))
}

logs.push(
Expand Down
3 changes: 0 additions & 3 deletions packages/config/tsup-config/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,6 @@ export const optionsFlat: Options = {
shims: true,
ignoreWatch: options.ignoreWatch,
esbuildPlugins: [esbuildPluginFilePathExtensions({ esmExtension: 'js', cjsExtension: 'cjs' })] as Options['esbuildPlugins'],
async onSuccess() {
await forceDefaultExport()
},
}

export default {
Expand Down
12 changes: 3 additions & 9 deletions packages/core/mocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,11 @@ export const mockedPluginManager = {
},
resolvePath: ({ baseName }) => baseName,
logger: {
info(message) {
emit(message) {
console.log(message)
},
error(message) {
console.log(message)
},
warn(message) {
console.log(message)
},
log(message) {
console.log(message)
on(eventName, args) {
},
logLevel: 'info',
},
} as PluginManager
16 changes: 8 additions & 8 deletions packages/core/src/PluginManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,11 @@ export class PluginManager {
})

if (paths && paths?.length > 1 && this.logger.logLevel === LogLevel.debug) {
this.logger.debug(
this.logger.emit('debug', [
`Cannot return a path where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough\n\nPaths: ${
JSON.stringify(paths, undefined, 2)
}\n\nFalling back on the first item.\n`,
)
])
}

return paths?.at(0)
Expand All @@ -150,11 +150,11 @@ export class PluginManager {
})

if (names && names?.length > 1 && this.logger.logLevel === LogLevel.debug) {
this.logger.debug(
this.logger.emit('debug', [
`Cannot return a name where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough\n\nNames: ${
JSON.stringify(names, undefined, 2)
}\n\nFalling back on the first item.\n`,
)
])
}

return transformReservedWord(names?.at(0) || params.name)
Expand Down Expand Up @@ -384,7 +384,7 @@ export class PluginManager {
if (this.logger.logLevel === LogLevel.info) {
const containsHookName = plugins.some((item) => item[hookName])
if (!containsHookName) {
this.logger.warn(`No hook ${hookName} found`)
this.logger.emit('warning', `No hook ${hookName} found`)
}
}

Expand Down Expand Up @@ -439,9 +439,9 @@ export class PluginManager {

if (this.logger.logLevel === LogLevel.debug) {
if (corePlugin) {
this.logger.debug(`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`)
this.logger.emit('debug', [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`])
} else {
this.logger.debug(`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`)
this.logger.emit('debug', [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`])
}
}

Expand Down Expand Up @@ -576,7 +576,7 @@ export class PluginManager {
#catcher<H extends PluginLifecycleHooks>(e: Error, plugin?: Plugin, hookName?: H) {
const text = `${e.message} (plugin: ${plugin?.name || 'unknown'}, hook: ${hookName || 'unknown'})\n`

this.logger.error(text)
this.logger.emit('error', text)
this.events.emit('error', e)
}

Expand Down
20 changes: 9 additions & 11 deletions packages/core/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ async function setup(options: BuildOptions): Promise<PluginManager> {
pluginManager.on('execute', (executer) => {
const { hookName, parameters, plugin } = executer

if (hookName === 'writeFile' && logger.spinner) {
if (hookName === 'writeFile') {
const [code] = parameters as PluginParameter<'writeFile'>

if (logger.logLevel === LogLevel.debug) {
logger.debug(`PluginKey ${c.dim(JSON.stringify(plugin.key))} \nwith source\n\n${code}`)
logger.emit('debug', [`PluginKey ${c.dim(JSON.stringify(plugin.key))} \nwith source\n\n${code}`])
}
}
})
Expand All @@ -127,8 +127,8 @@ async function setup(options: BuildOptions): Promise<PluginManager> {
return
}

if (logger.spinner && count === 0) {
logger.spinner?.start(`💾 Writing`)
if (count === 0) {
logger.emit('start', `💾 Writing`)
}
})

Expand Down Expand Up @@ -169,7 +169,7 @@ async function setup(options: BuildOptions): Promise<PluginManager> {
output,
].filter(Boolean)

logger.debug(logs.join('\n'))
logger.emit('debug', logs as string[])
}
})

Expand All @@ -188,9 +188,8 @@ export async function build(options: BuildOptions): Promise<BuildOutput> {

await pluginManager.hookParallel({ hookName: 'buildEnd' })

if (logger.logLevel === LogLevel.info && logger.spinner) {
logger.spinner.suffixText = ''
logger.spinner.succeed(`💾 Writing completed`)
if (logger.logLevel === LogLevel.info) {
logger.emit('end', `💾 Writing completed`)
}

return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager }
Expand All @@ -209,9 +208,8 @@ export async function safeBuild(options: BuildOptions): Promise<BuildOutput> {

await pluginManager.hookParallel({ hookName: 'buildEnd' })

if (logger.logLevel === LogLevel.info && logger.spinner) {
logger.spinner.suffixText = ''
logger.spinner.succeed(`💾 Writing completed`)
if (logger.logLevel === LogLevel.info) {
logger.emit('end', `💾 Writing completed`)
}
} catch (e) {
return { files: fileManager.files.map((file) => ({ ...file, source: FileManager.getSource(file) })), pluginManager, error: e as Error }
Expand Down
74 changes: 37 additions & 37 deletions packages/core/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import seedrandom from 'seedrandom'
import c, { createColors } from 'tinyrainbow'

import { writeLog } from './fs/write.ts'
import { EventEmitter } from './utils/EventEmitter.ts'

import type { Ora } from 'ora'
import type { Formatter } from 'tinyrainbow'
Expand All @@ -14,19 +15,23 @@ export const LogLevel = {

export type LogLevel = keyof typeof LogLevel

type Events = {
start: [message: string]
end: [message: string]
error: [message: string]
warning: [message: string]
debug: [logs: string[]]
}
export type Logger = {
/**
* Optional config name to show in CLI output
*/
name?: string
logLevel: LogLevel
log: (message: string | null) => void
error: (message: string | null) => void
info: (message: string | null) => void
warn: (message: string | null) => void
debug: (message: string | null) => Promise<void>

spinner?: Ora
logs: string[]
on: EventEmitter<Events>['on']
emit: EventEmitter<Events>['emit']
}

type Props = {
Expand All @@ -36,50 +41,45 @@ type Props = {
}

export function createLogger({ logLevel, name, spinner }: Props): Logger {
const logs: string[] = []
const log: Logger['log'] = (message) => {
if (message && spinner) {
spinner.text = message
logs.push(message)
const events = new EventEmitter<Events>()

events.on('start', (message) => {
if (spinner) {
spinner.start(message)
}
}
})

const error: Logger['error'] = (message) => {
if (message) {
throw new Error(message || 'Something went wrong')
events.on('end', (message) => {
if (spinner) {
spinner.suffixText = ''
spinner.succeed(message)
}
}
})

const warn: Logger['warn'] = (message) => {
if (message && spinner) {
events.on('warning', (message) => {
if (spinner) {
spinner.warn(c.yellow(message))
logs.push(message)
}
}
})

const info: Logger['warn'] = (message) => {
if (message && spinner && logLevel !== LogLevel.silent) {
spinner.info(message)
logs.push(message)
}
}
events.on('error', (message) => {
throw new Error(message || 'Something went wrong')
})

const debug: Logger['debug'] = async (message) => {
if (message) {
await writeLog(message)
}
}
events.on('debug', async (messages) => {
await writeLog(messages.join('\n'))
})

const logger: Logger = {
name,
logLevel,
log,
error,
warn,
info,
debug,
spinner,
logs,
on: (...args) => {
return events.on(...args)
},
emit: (...args) => {
return events.emit(...args)
},
}

return logger
Expand Down
6 changes: 4 additions & 2 deletions packages/react/src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ class ErrorBoundary extends Component<{ onError: Props['onError']; logger?: Logg
}

componentDidCatch(error: Error) {
this.props.onError(error)
this.props.logger?.error(error?.message)
if (error) {
this.props.onError(error)
this.props.logger?.emit('error', error.message)
}
}

render() {
Expand Down
2 changes: 1 addition & 1 deletion packages/swagger/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const definePlugin = createPlugin<PluginOptions>((options) => {
} catch (e) {
const error = e as Error

logger.warn(error?.message)
logger.emit('warning', error?.message)
return OasManager.parseFromConfig(config, { validate: false })
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/swagger/src/utils/getGroupedByTagFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export async function getGroupedByTagFiles({
.map((file: KubbFile.File<FileMeta>) => {
if (!file.meta?.tag) {
if (logger?.logLevel === LogLevel.debug) {
logger?.debug(`Could not find a tagName for ${JSON.stringify(file, undefined, 2)}`)
logger?.emit('debug', [`Could not find a tagName for ${JSON.stringify(file, undefined, 2)}`])
}

return
Expand Down
2 changes: 1 addition & 1 deletion packages/unplugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
## Install

```bash
npm i -D unplugin-kubb
npm i -D unplugin-kubb @kubb/core
```

<details>
Expand Down
3 changes: 2 additions & 1 deletion packages/unplugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
"rollup": "^3",
"vite": ">=3",
"webpack": "^4 || ^5",
"@kubb/core": "^2.4.0"
"@kubb/core": "workspace:*"
},
"peerDependenciesMeta": {
"webpack": {
Expand Down Expand Up @@ -137,6 +137,7 @@
"devDependencies": {
"@kubb/eslint-config": "workspace:*",
"@kubb/ts-config": "workspace:*",
"@kubb/core": "workspace:*",
"@kubb/tsup-config": "workspace:*",
"@nuxt/kit": "^3.9.3",
"@nuxt/schema": "^3.9.3",
Expand Down
Loading

0 comments on commit 080aec8

Please sign in to comment.