client-addons.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const path = require('path')
  2. // Subs
  3. const channels = require('../channels')
  4. // Utils
  5. const { resolveModuleRoot } = require('../util/resolve-path')
  6. const addons = []
  7. let baseUrl = process.env.VUE_APP_CLI_UI_URL
  8. if (typeof baseUrl === 'undefined') {
  9. baseUrl = `http://localhost:${process.env.VUE_APP_GRAPHQL_PORT}`
  10. } else {
  11. baseUrl = baseUrl.replace(/ws:\/\/([a-z0-9_-]+:\d+).*/i, 'http://$1')
  12. }
  13. function list (context) {
  14. return addons
  15. }
  16. function add (options, context) {
  17. if (findOne(options.id)) remove(options.id, context)
  18. addons.push(options)
  19. context.pubsub.publish(channels.CLIENT_ADDON_ADDED, {
  20. clientAddonAdded: options
  21. })
  22. }
  23. function findOne (id, context = null) {
  24. return addons.find(
  25. addon => addon.id === id
  26. )
  27. }
  28. function remove (id, context) {
  29. const index = addons.findIndex(
  30. addon => addon.id === id
  31. )
  32. if (index !== -1) addons.splice(index, 1)
  33. }
  34. function clear (context) {
  35. for (const addon of addons) {
  36. remove(addon.id, context)
  37. }
  38. }
  39. function getUrl (addon, context) {
  40. return addon.url || `${baseUrl}/_addon/${addon.id}/index.js`
  41. }
  42. function serve (req, res) {
  43. const { id, 0: file } = req.params
  44. const addon = findOne(decodeURIComponent(id))
  45. if (addon && addon.path) {
  46. const resolvedPath = require.resolve(addon.path)
  47. const basePath = resolveModuleRoot(resolvedPath)
  48. if (basePath) {
  49. res.sendFile(path.join(basePath, file), { maxAge: 0 })
  50. } else {
  51. res.status(404)
  52. res.send(`File not found (resolved: ${resolvedPath}`)
  53. }
  54. } else {
  55. res.status(404)
  56. res.send('Addon not found in loaded addons. Try opening a vue-cli project first?')
  57. }
  58. }
  59. module.exports = {
  60. list,
  61. add,
  62. remove,
  63. findOne,
  64. getUrl,
  65. serve,
  66. clear
  67. }