websocket.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { buttonResults } from '../resources/vue/stores/buttonResults.js'
  2. export function initWebsocket () {
  3. window.addEventListener('EventOutputChunk', onOutputChunk)
  4. reconnectWebsocket()
  5. }
  6. window.websocketAvailable = false
  7. async function reconnectWebsocket () {
  8. if (window.websocketAvailable) {
  9. return
  10. }
  11. try {
  12. window.websocketAvailable = true
  13. for await (const e of window.client.eventStream()) {
  14. handleEvent(e)
  15. }
  16. } catch (err) {
  17. console.error('Websocket connection failed: ', err)
  18. }
  19. window.websocketAvailable = false
  20. console.log('Reconnecting websocket...')
  21. }
  22. function handleEvent (msg) {
  23. const typeName = msg.event.value.$typeName.replace('olivetin.api.v1.', '')
  24. const j = new Event(typeName)
  25. j.payload = msg.event.value
  26. switch (typeName) {
  27. case 'EventOutputChunk':
  28. case 'EventConfigChanged':
  29. case 'EventEntityChanged':
  30. window.dispatchEvent(j)
  31. break
  32. case 'EventExecutionFinished':
  33. case 'EventExecutionStarted':
  34. buttonResults[msg.event.value.logEntry.executionTrackingId] = msg.event.value.logEntry
  35. window.dispatchEvent(j)
  36. break
  37. default:
  38. console.warn('Unhandled websocket message type from server: ', typeName)
  39. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + typeName, true)
  40. }
  41. }
  42. function onOutputChunk (evt) {
  43. const chunk = evt.payload
  44. if (window.terminal) {
  45. if (chunk.executionTrackingId === window.terminal.executionTrackingId) {
  46. window.terminal.write(chunk.output)
  47. }
  48. }
  49. }