             [rksm.cloxp-cljs.analyzer :as cloxp-ana]
             [rksm.cloxp-com.server :as server]
             [rksm.cloxp-com.messenger :as msg]
-            [clojure.core.async :refer [>!! <!! >! <! go]]))
+            [clojure.core.async :refer [>!! <!! >! <! go]]
+            [fs.core :as fs]))
 
 (defn send-to-js
   [server client-id action data]

   (let [c-env (env/default-compiler-env)
         ana-env (merge (ana/empty-env) {:ns 'cljs.user})]
     (env/with-compiler-env c-env
       (cljs.repl/load-namespace cloxp-repl-env sym opts)))))

  "returns map of {:value :out :error}"
  ([form opts]
   (eval-cljs form nil opts))
  ([form cloxp-repl-env {:keys [target-id ns-sym file]
                         :or {ns-sym ana/*cljs-ns*}
                         :as opts}]

   ; for the cljs compiler we need to analyze the code. If the code isn't in a
   ; file already, put it in a temp file for ensure-ns-analyzed!
   (let [ana-file (if (or (= file "NO_SOURCE_FILE")
                          (= file "<doit>")
                          (= file "<cloxp-cljs-repl>")
                          (empty? file))
                    (let [tmp-file (fs/temp-file "cljs-doit-" ".cljs")]
                      (spit tmp-file (str "(ns " ns-sym ")\n" (pr-str form)))
                      (str tmp-file))
                    file)]
   
     ; make sure we have a repl-env, compiler-env, ana-env...
     (let [opts (or opts {})
           cloxp-repl-env (cond
                            cloxp-repl-env cloxp-repl-env
                            target-id (repl-env-for-client target-id)
                            :default (default-repl-env))
           c-env (cloxp-ana/comp-env)
           ana-env (assoc (ana/empty-env)
                          :ns (cloxp-ana/ensure-ns-analyzed! ns-sym ana-file))]

       ; this is where the unicorns go to town
       (env/with-compiler-env c-env
         (try
           {:error nil
            :out ""
            :value (binding [cljs.analyzer/*cljs-ns* ns-sym]
                     (repl/evaluate-form cloxp-repl-env
                                         ana-env
                                         (or file "<cloxp-cljs-repl>")
                                         form
                                         identity ; wrap-fn
                                         opts))}
           (catch Exception e {:error e :out "" :value nil})))))))

(defn- eval-read-obj
  "returns a map of :parsed :value :out and :error."
