websocket.js 1.7 KB

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