UNPKG

@devbookhq/sdk

Version:

SDK for managing Devbook sessions from JavaScript/TypeScript

70 lines (57 loc) 1.75 kB
import { filesystemService } from './filesystem' import SessionConnection from './sessionConnection' export enum FilesystemOperation { Create = 'Create', Write = 'Write', Remove = 'Remove', Rename = 'Rename', Chmod = 'Chmod', } export interface FilesystemEvent { path: string name: string operation: FilesystemOperation // Unix epoch in nanoseconds timestamp: number isDir: boolean } export type FilesystemEventListener = (event: FilesystemEvent) => void class FilesystemWatcher { // Listeners to filesystem events. // Users of the this class can add their listeners to filesystem events // via `this.addEventListeners` private listeners: Set<FilesystemEventListener> private rpcSubscriptionID?: string constructor(private sessConn: SessionConnection, private path: string) { this.listeners = new Set<FilesystemEventListener>() } // Starts watching the path that was passed to the contructor async start() { // Already started. if (this.rpcSubscriptionID) return this.handleFilesystemEvents = this.handleFilesystemEvents.bind(this) this.rpcSubscriptionID = await this.sessConn.subscribe( filesystemService, this.handleFilesystemEvents, 'watchDir', this.path, ) } // Stops watching the path and removes all listeners. async stop() { this.listeners.clear() if (this.rpcSubscriptionID) { await this.sessConn.unsubscribe(this.rpcSubscriptionID) } } addEventListener(l: FilesystemEventListener) { this.listeners.add(l) return () => this.listeners.delete(l) } private handleFilesystemEvents(fsChange: FilesystemEvent) { this.listeners.forEach(l => { l(fsChange) }) } } export default FilesystemWatcher