logs.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /** @typedef {'warn' | 'error' | 'info' | 'done'} LogType */
  2. /**
  3. * @typedef Log
  4. * @prop {string} id
  5. * @prop {string} date
  6. * @prop {LogType} type
  7. * @prop {string} tag
  8. * @prop {string} message
  9. */
  10. const shortId = require('shortid')
  11. const { events } = require('@vue/cli-shared-utils/lib/logger')
  12. const { generateTitle } = require('@vue/cli/lib/util/clearConsole')
  13. // Subs
  14. const channels = require('../channels')
  15. // Context
  16. const getContext = require('../context')
  17. /** @type {Log []} */
  18. let logs = []
  19. /**
  20. * @param {Log} log
  21. * @param {any} context
  22. */
  23. exports.add = function (log, context) {
  24. /** @type {Log} */
  25. const item = {
  26. id: shortId.generate(),
  27. date: new Date().toISOString(),
  28. tag: null,
  29. ...log
  30. }
  31. logs.push(item)
  32. context.pubsub.publish(channels.CONSOLE_LOG_ADDED, {
  33. consoleLogAdded: item
  34. })
  35. return item
  36. }
  37. exports.list = function (context) {
  38. return logs
  39. }
  40. exports.last = function (context) {
  41. if (logs.length) {
  42. return logs[logs.length - 1]
  43. }
  44. return null
  45. }
  46. exports.clear = function (context) {
  47. logs = []
  48. return logs
  49. }
  50. // Init
  51. {
  52. const context = getContext()
  53. events.on('log', log => {
  54. exports.add(log, context)
  55. })
  56. exports.add({
  57. type: 'info',
  58. tag: null,
  59. message: generateTitle(true)
  60. }, context)
  61. }