   (:import [java.io StringReader]
            [clojure.lang Var]))
 
-(def ^:dynamic repl-state-ref nil)
+(def ^:dynamic *repl-state* nil)
 
 (defn send [{:keys [transport session id] :as req} {:keys [status] :as msg}]
   (let [res

          (reify
            clojure.lang.IDeref
            (deref [_]
              (some-> @state-ref :worker :state-ref deref :build-state :compiler-env))))))))

(defn set-worker [{:keys [session] :as msg}]
  ;; re-create this for every message so we know exactly which msg started a REPL
  (swap! session assoc #'api/*nrepl-init* #(repl-init msg %1 %2))

  ;; can only store vars in a session, always put one in though
  (when-not (contains? @session #'repl-state-ref)
    (swap! session assoc #'repl-state-ref (atom {})))

  (let [state-ref (get @session #'repl-state-ref)
        session-id (-> session meta :id)
        {:keys [build-id worker]} (get @state-ref session-id)]
    (if-not build-id
      msg
      (assoc msg ::state-ref state-ref ::worker worker ::build-id build-id))))

(defn do-cljs-load-file [{::keys [worker] :keys [file file-path] :as msg}]
  (when-some [result (worker/load-file worker {:file-path file-path :source file})]

    ;; cleanup if worker exits
    (go (<! proc-stop)
        (async/close! watch-chan)
        (worker-exit session msg))

    ;; watch worker for specific messages (ie. out/err)
    ;; send :err/:out with latest msg id to make tools happy
