| const { log, output, input, META } = require('proc-log')
|
| const { explain } = require('./explain-eresolve.js')
|
| const { formatWithOptions } = require('./format')
|
|
|
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
|
|
| const COLOR_PALETTE = ({ chalk: c }) => ({
|
| heading: c.bold,
|
| title: c.blueBright,
|
| timing: c.magentaBright,
|
|
|
| error: c.red,
|
| warn: c.yellow,
|
| notice: c.cyanBright,
|
| http: c.green,
|
| info: c.cyan,
|
| verbose: c.blue,
|
| silly: c.blue.dim,
|
| })
|
|
|
| const LEVEL_OPTIONS = {
|
| silent: {
|
| index: 0,
|
| },
|
| error: {
|
| index: 1,
|
| },
|
| warn: {
|
| index: 2,
|
| },
|
| notice: {
|
| index: 3,
|
| },
|
| http: {
|
| index: 4,
|
| },
|
| info: {
|
| index: 5,
|
| },
|
| verbose: {
|
| index: 6,
|
| },
|
| silly: {
|
| index: 7,
|
| },
|
| }
|
|
|
| const LEVEL_METHODS = {
|
| ...LEVEL_OPTIONS,
|
| [log.KEYS.timing]: {
|
| show: ({ timing, index }) => !!timing && index !== 0,
|
| },
|
| }
|
|
|
| const setBlocking = (stream) => {
|
|
|
|
|
|
|
| if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
|
| stream._handle.setBlocking(true)
|
| }
|
| return stream
|
| }
|
|
|
|
|
| const ERROR_KEY = 'error'
|
|
|
| const JSON_ERROR_KEY = 'jsonError'
|
|
|
| const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v)
|
|
|
| const getArrayOrObject = (items) => {
|
| if (items.length) {
|
| const foundNonObject = items.find(o => !isPlainObject(o))
|
|
|
| if (foundNonObject) {
|
| return foundNonObject
|
| }
|
|
|
| if (items.every((o, i) => Object.hasOwn(o, i))) {
|
| return Object.assign([], ...items)
|
| }
|
| }
|
|
|
| return Object.assign({}, ...items.filter(o => isPlainObject(o)))
|
| }
|
|
|
| const getJsonBuffer = ({ [JSON_ERROR_KEY]: metaError }, buffer) => {
|
| const items = []
|
|
|
| const errors = metaError ? [metaError] : []
|
|
|
| for (const [, { [JSON_ERROR_KEY]: error }, obj] of buffer) {
|
| if (obj) {
|
| items.push(obj)
|
| }
|
| if (error) {
|
| errors.push(error)
|
| }
|
| }
|
|
|
| if (!items.length && !errors.length) {
|
| return null
|
| }
|
|
|
| const res = getArrayOrObject(items)
|
|
|
|
|
|
|
| if (isPlainObject(res) && errors.length) {
|
|
|
|
|
|
|
|
|
| if (res[ERROR_KEY]) {
|
| log.warn('', `overwriting existing ${ERROR_KEY} on json output`)
|
| }
|
| res[ERROR_KEY] = getArrayOrObject(errors)
|
| }
|
|
|
| return res
|
| }
|
|
|
| const withMeta = (handler) => (level, ...args) => {
|
| let meta = {}
|
| const last = args.at(-1)
|
| if (last && typeof last === 'object' && Object.hasOwn(last, META)) {
|
| meta = args.pop()
|
| }
|
| return handler(level, meta, ...args)
|
| }
|
|
|
| class Display {
|
| #logState = {
|
| buffering: true,
|
| buffer: [],
|
| }
|
|
|
| #outputState = {
|
| buffering: true,
|
| buffer: [],
|
| }
|
|
|
|
|
| #noColorChalk
|
| #stdoutChalk
|
| #stdoutColor
|
| #stderrChalk
|
| #stderrColor
|
| #logColors
|
|
|
|
|
| #progress
|
|
|
|
|
| #command
|
| #levelIndex
|
| #timing
|
| #json
|
| #heading
|
| #silent
|
|
|
|
|
| #stdout
|
| #stderr
|
|
|
| #seenNotices = new Set()
|
|
|
| constructor ({ stdout, stderr }) {
|
| this.#stdout = setBlocking(stdout)
|
| this.#stderr = setBlocking(stderr)
|
|
|
|
|
| process.on('log', this.#logHandler)
|
| process.on('output', this.#outputHandler)
|
| process.on('input', this.#inputHandler)
|
| this.#progress = new Progress({ stream: stderr })
|
| }
|
|
|
| off () {
|
| process.off('log', this.#logHandler)
|
| this.#logState.buffer.length = 0
|
| process.off('output', this.#outputHandler)
|
| this.#outputState.buffer.length = 0
|
| process.off('input', this.#inputHandler)
|
| this.#progress.off()
|
| this.#seenNotices.clear()
|
| }
|
|
|
| get chalk () {
|
| return {
|
| noColor: this.#noColorChalk,
|
| stdout: this.#stdoutChalk,
|
| stderr: this.#stderrChalk,
|
| }
|
| }
|
|
|
| async load ({
|
| command,
|
| heading,
|
| json,
|
| loglevel,
|
| progress,
|
| stderrColor,
|
| stdoutColor,
|
| timing,
|
| unicode,
|
| }) {
|
| const [{ Chalk }, { createSupportsColor }] = await Promise.all([
|
| import('chalk'),
|
| import('supports-color'),
|
| ])
|
|
|
| const level = Math.max(createSupportsColor(null).level, 1)
|
| this.#noColorChalk = new Chalk({ level: 0 })
|
| this.#stdoutColor = stdoutColor
|
| this.#stdoutChalk = stdoutColor ? new Chalk({ level }) : this.#noColorChalk
|
| this.#stderrColor = stderrColor
|
| this.#stderrChalk = stderrColor ? new Chalk({ level }) : this.#noColorChalk
|
| this.#logColors = COLOR_PALETTE({ chalk: this.#stderrChalk })
|
|
|
| this.#command = command
|
| this.#levelIndex = LEVEL_OPTIONS[loglevel].index
|
| this.#timing = timing
|
| this.#json = json
|
| this.#heading = heading
|
| this.#silent = this.#levelIndex <= 0
|
|
|
|
|
| log.resume()
|
| output.flush()
|
| this.#progress.load({
|
| unicode,
|
| enabled: !!progress && !this.#silent,
|
| })
|
| }
|
|
|
|
|
|
|
|
|
| #write (stream, options, ...args) {
|
| const colors = stream === this.#stdout ? this.#stdoutColor : this.#stderrColor
|
| const value = formatWithOptions({ colors, ...options }, ...args)
|
| this.#progress.write(() => stream.write(value))
|
| }
|
|
|
|
|
|
|
|
|
| #logHandler = withMeta((level, meta, ...args) => {
|
| switch (level) {
|
| case log.KEYS.resume:
|
| this.#logState.buffering = false
|
| this.#logState.buffer.forEach((item) => this.#tryWriteLog(...item))
|
| this.#logState.buffer.length = 0
|
| break
|
|
|
| case log.KEYS.pause:
|
| this.#logState.buffering = true
|
| break
|
|
|
| default:
|
| if (this.#logState.buffering) {
|
| this.#logState.buffer.push([level, meta, ...args])
|
| } else {
|
| this.#tryWriteLog(level, meta, ...args)
|
| }
|
| break
|
| }
|
| })
|
|
|
|
|
| #outputHandler = withMeta((level, meta, ...args) => {
|
| this.#json = typeof meta.json === 'boolean' ? meta.json : this.#json
|
| switch (level) {
|
| case output.KEYS.flush: {
|
| this.#outputState.buffering = false
|
| if (this.#json) {
|
| const json = getJsonBuffer(meta, this.#outputState.buffer)
|
| if (json) {
|
| this.#writeOutput(output.KEYS.standard, meta, JSON.stringify(json, null, 2))
|
| }
|
| } else {
|
| this.#outputState.buffer.forEach((item) => this.#writeOutput(...item))
|
| }
|
| this.#outputState.buffer.length = 0
|
| break
|
| }
|
|
|
| case output.KEYS.buffer:
|
| this.#outputState.buffer.push([output.KEYS.standard, meta, ...args])
|
| break
|
|
|
| default:
|
| if (this.#outputState.buffering) {
|
| this.#outputState.buffer.push([level, meta, ...args])
|
| } else {
|
|
|
| if (typeof args[0] === 'string' && args[0].startsWith('\n> ') && args[0].endsWith('\n')) {
|
| if (this.#silent || ['exec', 'explore'].includes(this.#command)) {
|
|
|
| break
|
| } else if (this.#json) {
|
|
|
|
|
| level = output.KEYS.error
|
| }
|
| }
|
| this.#writeOutput(level, meta, ...args)
|
| }
|
| break
|
| }
|
| })
|
|
|
| #inputHandler = withMeta((level, meta, ...args) => {
|
| switch (level) {
|
| case input.KEYS.start:
|
| log.pause()
|
| this.#outputState.buffering = true
|
| this.#progress.off()
|
| break
|
|
|
| case input.KEYS.end: {
|
| log.resume()
|
|
|
| if (meta?.silent) {
|
| output.standard()
|
| }
|
| output.flush()
|
| this.#progress.resume()
|
| break
|
| }
|
|
|
| case input.KEYS.read: {
|
|
|
| const [res, rej, p] = args
|
|
|
|
|
| input.start()
|
|
|
| return p()
|
| .then((result) => {
|
|
|
| input.end({ [META]: true, silent: meta?.silent })
|
| res(result)
|
| return result
|
| })
|
| .catch((error) => {
|
|
|
| output.standard()
|
| input.end()
|
| rej(error)
|
| })
|
| }
|
| }
|
| })
|
|
|
|
|
|
|
| #writeOutput (level, meta, ...args) {
|
| switch (level) {
|
| case output.KEYS.standard:
|
| this.#write(this.#stdout, meta, ...args)
|
| break
|
|
|
| case output.KEYS.error:
|
| this.#write(this.#stderr, meta, ...args)
|
| break
|
| }
|
| }
|
|
|
|
|
|
|
| #tryWriteLog (level, meta, ...args) {
|
| try {
|
|
|
|
|
| const [heading, message, expl] = args
|
| if (level === log.KEYS.warn && heading === 'ERESOLVE' && expl && typeof expl === 'object') {
|
| this.#writeLog(level, meta, heading, message)
|
| this.#writeLog(level, meta, '', explain(expl, this.#stderrChalk, 2))
|
| return
|
| }
|
| this.#writeLog(level, meta, ...args)
|
| } catch (ex) {
|
| try {
|
|
|
| this.#writeLog(log.KEYS.verbose, meta, '', `attempt to log crashed`, ...args, ex)
|
| } catch (ex2) {
|
|
|
|
|
| console.error(`attempt to log crashed`, ex, ex2)
|
| }
|
| }
|
| }
|
|
|
| #writeLog (level, meta, ...args) {
|
| const levelOpts = LEVEL_METHODS[level]
|
| const show = levelOpts.show ?? (({ index }) => levelOpts.index <= index)
|
| const force = meta.force && !this.#silent
|
|
|
| if (force || show({ index: this.#levelIndex, timing: this.#timing })) {
|
|
|
| const title = args.shift()
|
| const prefix = [
|
| this.#logColors.heading(this.#heading),
|
| this.#logColors[level](level),
|
| title ? this.#logColors.title(title) : null,
|
| ]
|
| const writeOpts = { prefix }
|
|
|
| if (level === 'notice') {
|
| writeOpts.redact = false
|
|
|
| if (this.#levelIndex < LEVEL_OPTIONS.verbose.index) {
|
| const noticeKey = JSON.stringify([title, ...args])
|
| if (this.#seenNotices.has(noticeKey)) {
|
| return
|
| }
|
| this.#seenNotices.add(noticeKey)
|
| }
|
| }
|
| this.#write(this.#stderr, writeOpts, ...args)
|
| }
|
| }
|
| }
|
|
|
| class Progress {
|
|
|
|
|
|
|
| static dots = { duration: 80, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] }
|
| static lines = { duration: 130, frames: ['-', '\\', '|', '/'] }
|
|
|
| #enabled = false
|
| #frameIndex = 0
|
| #interval
|
| #lastUpdate = 0
|
| #spinner
|
| #stream
|
|
|
| #timeout
|
| #rendered = false
|
|
|
|
|
| get #rendering () {
|
| return this.#enabled && !this.#timeout
|
| }
|
|
|
|
|
| get #spinning () {
|
| return this.#enabled && this.#interval
|
| }
|
|
|
| constructor ({ stream }) {
|
| this.#stream = stream
|
| }
|
|
|
| load ({ enabled, unicode }) {
|
| this.#enabled = enabled
|
| this.#spinner = unicode ? Progress.dots : Progress.lines
|
|
|
| this.#timeout = setTimeout(() => {
|
| this.#timeout = null
|
| this.#render()
|
| }, 200)
|
|
|
| this.#timeout.unref()
|
| }
|
|
|
| off () {
|
| if (!this.#enabled) {
|
| return
|
| }
|
| clearTimeout(this.#timeout)
|
| this.#timeout = null
|
| clearInterval(this.#interval)
|
| this.#interval = null
|
| this.#frameIndex = 0
|
| this.#lastUpdate = 0
|
| this.#clearSpinner()
|
| }
|
|
|
| resume () {
|
| this.#render(true)
|
| }
|
|
|
|
|
|
|
| write (write) {
|
| if (this.#spinning) {
|
| this.#clearSpinner()
|
| }
|
| write()
|
| if (this.#spinning) {
|
| this.#render()
|
| }
|
| }
|
|
|
| #render (resuming) {
|
| if (!this.#rendering) {
|
| return
|
| }
|
|
|
| this.#renderFrame(Date.now() - this.#lastUpdate >= this.#spinner.duration, resuming)
|
| if (!this.#interval) {
|
| this.#interval = setInterval(() => this.#renderFrame(true), this.#spinner.duration)
|
|
|
| this.#interval.unref()
|
| }
|
| this.#interval.refresh()
|
| }
|
|
|
| #renderFrame (next, resuming) {
|
| if (next) {
|
| this.#lastUpdate = Date.now()
|
| this.#frameIndex++
|
| if (this.#frameIndex >= this.#spinner.frames.length) {
|
| this.#frameIndex = 0
|
| }
|
| }
|
| if (!resuming) {
|
| this.#clearSpinner()
|
| }
|
| this.#stream.write(this.#spinner.frames[this.#frameIndex])
|
| this.#rendered = true
|
| }
|
|
|
| #clearSpinner () {
|
| if (!this.#rendered) {
|
| return
|
| }
|
|
|
| this.#stream.cursorTo(0)
|
| this.#stream.clearLine(1)
|
| this.#rendered = false
|
| }
|
| }
|
|
|
| module.exports = Display
|
|
|