/
closure.clj
1887 lines (1712 loc) · 76.4 KB
/
closure.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.closure
"Compile ClojureScript to JavaScript with optimizations from Google
Closure Compiler producing runnable JavaScript.
The Closure Compiler (compiler.jar) must be on the classpath.
Use the 'build' function for end-to-end compilation.
build = compile -> add-dependencies -> optimize -> output
Two protocols are defined: IJavaScript and Compilable. The
Compilable protocol is satisfied by something which can return one
or more IJavaScripts.
With IJavaScript objects in hand, calling add-dependencies will
produce a sequence of IJavaScript objects which includes all
required dependencies from the Closure library and ClojureScript,
in dependency order. This function replaces the closurebuilder
tool.
The optimize function converts one or more IJavaScripts into a
single string of JavaScript source code using the Closure Compiler
API.
The produced output is either a single string of optimized
JavaScript or a deps file for use during development.
"
(:refer-clojure :exclude [compile])
(:require [cljs.util :as util]
[cljs.compiler :as comp]
[cljs.analyzer :as ana]
[cljs.source-map :as sm]
[cljs.env :as env]
[cljs.js-deps :as deps]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.data.json :as json])
(:import [java.io File BufferedInputStream StringWriter]
[java.net URL]
[java.util.logging Level]
[java.util List Random]
[java.util.concurrent TimeUnit]
[com.google.javascript.jscomp CompilerOptions CompilationLevel
CompilerOptions$LanguageMode SourceMap$Format
SourceMap$DetailLevel ClosureCodingConvention SourceFile
Result JSError CheckLevel DiagnosticGroups
CommandLineRunner AnonymousFunctionNamingPolicy
JSModule JSModuleGraph SourceMap ProcessCommonJSModules
ES6ModuleLoader AbstractCompiler TransformAMDToCJSModule
ProcessEs6Modules CompilerInput]
[com.google.javascript.rhino Node]
[java.security MessageDigest]
[javax.xml.bind DatatypeConverter]
[java.nio.file Path Paths Files StandardWatchEventKinds WatchKey
WatchEvent FileVisitor FileVisitResult]
[com.sun.nio.file SensitivityWatchEventModifier]
[com.google.common.base Throwables]))
(def name-chars (map char (concat (range 48 57) (range 65 90) (range 97 122))))
(defn random-char []
(nth name-chars (.nextInt (Random.) (count name-chars))))
(defn random-string [length]
(apply str (take length (repeatedly random-char))))
(util/compile-if
(.getConstructor ES6ModuleLoader
(into-array java.lang.Class
[java.util.List java.lang.Iterable]))
(do (def is-new-es6-loader? true)
(def default-module-root ES6ModuleLoader/DEFAULT_FILENAME_PREFIX))
(def is-new-es6-loader? false))
(util/compile-if
(.getConstructor ES6ModuleLoader
(into-array java.lang.Class
[AbstractCompiler java.lang.String]))
(def is-old-es6-loader? true)
(def is-old-es6-loader? false))
(util/compile-if
(and (.getConstructor ProcessCommonJSModules
(into-array java.lang.Class
[com.google.javascript.jscomp.Compiler ES6ModuleLoader]))
(or is-new-es6-loader? is-old-es6-loader?))
(def can-convert-commonjs? true)
(def can-convert-commonjs? false))
(util/compile-if
(and can-convert-commonjs?
(.getConstructor TransformAMDToCJSModule
(into-array java.lang.Class
[AbstractCompiler])))
(def can-convert-amd? true)
(def can-convert-amd? false))
(util/compile-if
(and (.getConstructor ProcessEs6Modules
(into-array java.lang.Class
[com.google.javascript.jscomp.Compiler ES6ModuleLoader Boolean/TYPE]))
(or is-new-es6-loader? is-old-es6-loader?))
(def can-convert-es6? true)
(def can-convert-es6? false))
;; Closure API
;; ===========
(defmulti js-source-file (fn [_ source] (class source)))
(defmethod js-source-file String [^String name ^String source]
(SourceFile/fromCode name source))
(defmethod js-source-file File [_ ^File source]
(SourceFile/fromFile source))
(defmethod js-source-file BufferedInputStream [^String name ^BufferedInputStream source]
(SourceFile/fromInputStream name source))
(def check-level
{:error CheckLevel/ERROR
:warning CheckLevel/WARNING
:off CheckLevel/OFF})
(def warning-types
{:access-controls DiagnosticGroups/ACCESS_CONTROLS
:ambiguous-function-decl DiagnosticGroups/AMBIGUOUS_FUNCTION_DECL
:debugger-statement-present DiagnosticGroups/DEBUGGER_STATEMENT_PRESENT
:check-regexp DiagnosticGroups/CHECK_REGEXP
:check-types DiagnosticGroups/CHECK_TYPES
:check-useless-code DiagnosticGroups/CHECK_USELESS_CODE
:check-variables DiagnosticGroups/CHECK_VARIABLES
:const DiagnosticGroups/CONST
:constant-property DiagnosticGroups/CONSTANT_PROPERTY
:deprecated DiagnosticGroups/DEPRECATED
:duplicate-message DiagnosticGroups/DUPLICATE_MESSAGE
:es5-strict DiagnosticGroups/ES5_STRICT
:externs-validation DiagnosticGroups/EXTERNS_VALIDATION
:fileoverview-jsdoc DiagnosticGroups/FILEOVERVIEW_JSDOC
:global-this DiagnosticGroups/GLOBAL_THIS
:internet-explorer-checks DiagnosticGroups/INTERNET_EXPLORER_CHECKS
:invalid-casts DiagnosticGroups/INVALID_CASTS
:missing-properties DiagnosticGroups/MISSING_PROPERTIES
:non-standard-jsdoc DiagnosticGroups/NON_STANDARD_JSDOC
:strict-module-dep-check DiagnosticGroups/STRICT_MODULE_DEP_CHECK
:tweaks DiagnosticGroups/TWEAKS
:undefined-names DiagnosticGroups/UNDEFINED_NAMES
:undefined-variables DiagnosticGroups/UNDEFINED_VARIABLES
:unknown-defines DiagnosticGroups/UNKNOWN_DEFINES
:visiblity DiagnosticGroups/VISIBILITY})
(defn set-options
"TODO: Add any other options that we would like to support."
[opts ^CompilerOptions compiler-options]
(when (contains? opts :pretty-print)
(set! (.prettyPrint compiler-options) (:pretty-print opts)))
(when (contains? opts :pseudo-names)
(set! (.generatePseudoNames compiler-options) (:pseudo-names opts)))
(when (contains? opts :anon-fn-naming-policy)
(let [policy (:anon-fn-naming-policy opts)]
(set! (.anonymousFunctionNaming compiler-options)
(case policy
:off AnonymousFunctionNamingPolicy/OFF
:unmapped AnonymousFunctionNamingPolicy/UNMAPPED
:mapped AnonymousFunctionNamingPolicy/MAPPED
(throw (IllegalArgumentException. (str "Invalid :anon-fn-naming-policy value " policy " - only :off, :unmapped, :mapped permitted")))))))
(when (contains? opts :language-in)
(case (:language-in opts)
:ecmascript5 (.setLanguageIn compiler-options CompilerOptions$LanguageMode/ECMASCRIPT5)
:ecmascript5-strict (.setLanguageIn compiler-options CompilerOptions$LanguageMode/ECMASCRIPT5_STRICT)
:ecmascript3 (.setLanguageIn compiler-options CompilerOptions$LanguageMode/ECMASCRIPT3)))
(when (contains? opts :language-out)
(case (:language-out opts)
:ecmascript5 (.setLanguageOut compiler-options CompilerOptions$LanguageMode/ECMASCRIPT5)
:ecmascript5-strict (.setLanguageOut compiler-options CompilerOptions$LanguageMode/ECMASCRIPT5_STRICT)
:ecmascript3 (.setLanguageOut compiler-options CompilerOptions$LanguageMode/ECMASCRIPT3)))
(when (contains? opts :print-input-delimiter)
(set! (.printInputDelimiter compiler-options)
(:print-input-delimiter opts)))
(when (contains? opts :closure-warnings)
(doseq [[type level] (:closure-warnings opts)]
(. compiler-options
(setWarningLevel (type warning-types) (level check-level)))))
(when (contains? opts :closure-extra-annotations)
(. compiler-options
(setExtraAnnotationNames (map name (:closure-extra-annotations opts)))))
compiler-options)
(defn ^CompilerOptions make-options
"Create a CompilerOptions object and set options from opts map."
[opts]
(let [level (case (:optimizations opts)
:advanced CompilationLevel/ADVANCED_OPTIMIZATIONS
:whitespace CompilationLevel/WHITESPACE_ONLY
:simple CompilationLevel/SIMPLE_OPTIMIZATIONS)
compiler-options (doto (CompilerOptions.)
(.setCodingConvention (ClosureCodingConvention.)))]
(doseq [[key val] (:closure-defines opts)]
(let [key (name key)]
(cond
(string? val) (.setDefineToStringLiteral compiler-options key val)
(integer? val) (.setDefineToIntegerLiteral compiler-options key val)
(float? val) (.setDefineToDoubleLiteral compiler-options key val)
(or (true? val)
(false? val)) (.setDefineToBooleanLiteral compiler-options key val)
:else (println "value for" key "must be string, int, float, or bool"))))
(if-let [extra-annotations (:closure-extra-annotations opts)]
(. compiler-options (setExtraAnnotationNames (map name extra-annotations))))
(when (contains? opts :source-map)
(if (:modules opts)
;; name is not actually used by Closur in :modules case,
;; but we need to provide _something_ for Closure to not
;; complain
(set! (.sourceMapOutputPath compiler-options)
(str (io/file (util/output-directory opts)
"cljs_modules.map")))
(set! (.sourceMapOutputPath compiler-options)
(:source-map opts)))
(set! (.sourceMapDetailLevel compiler-options)
SourceMap$DetailLevel/ALL)
(set! (.sourceMapFormat compiler-options)
SourceMap$Format/V3))
(do
(.setOptionsForCompilationLevel level compiler-options)
(set-options opts compiler-options)
compiler-options)))
(defn load-externs
"Externs are JavaScript files which contain empty definitions of
functions which will be provided by the environment. Any function in
an extern file will not be renamed during optimization.
Options may contain an :externs key with a list of file paths to
load. The :use-only-custom-externs flag may be used to indicate that
the default externs should be excluded."
[{:keys [externs use-only-custom-externs target ups-externs]}]
(let [validate (fn validate [p us]
(if (empty? us)
(throw (IllegalArgumentException.
(str "Extern " p " does not exist")))
us))
filter-cp-js (fn [paths]
(for [p paths
u (deps/find-js-classpath p)]
u))
filter-js (fn [paths]
(for [p paths
u (deps/find-js-resources p)]
u))
add-target (fn [ext]
(cons (io/resource "cljs/externs.js")
(if (= :nodejs target)
(cons (io/resource "cljs/nodejs_externs.js")
(or ext []))
ext)))
load-js (fn [ext]
(map #(js-source-file (.getFile %) (slurp %)) ext))]
(let [js-sources (-> externs filter-js add-target load-js)
ups-sources (-> ups-externs filter-cp-js load-js)
all-sources (concat js-sources ups-sources)]
(if use-only-custom-externs
all-sources
(into all-sources (CommandLineRunner/getDefaultExterns))))))
(defn ^com.google.javascript.jscomp.Compiler make-closure-compiler []
(let [compiler (com.google.javascript.jscomp.Compiler.)]
(com.google.javascript.jscomp.Compiler/setLoggingLevel Level/WARNING)
compiler))
(defn report-failure [^Result result]
(let [errors (.errors result)
warnings (.warnings result)]
(doseq [next (seq errors)]
(println "ERROR:" (.toString ^JSError next)))
(doseq [next (seq warnings)]
(println "WARNING:" (.toString ^JSError next)))))
;; Protocols for IJavaScript and Compilable
;; ========================================
(defprotocol ISourceMap
(-source-url [this] "Return the CLJS source url")
(-source-map [this] "Return the CLJS compiler generated JS source mapping"))
(extend-protocol deps/IJavaScript
String
(-foreign? [this] false)
(-closure-lib? [this] false)
(-url [this] nil)
(-provides [this] (:provides (deps/parse-js-ns (string/split-lines this))))
(-requires [this] (:requires (deps/parse-js-ns (string/split-lines this))))
(-source [this] this)
clojure.lang.IPersistentMap
(-foreign? [this] (:foreign this))
(-closure-lib? [this] (:closure-lib this))
(-url [this] (or (:url this)
(deps/to-url (:file this))))
(-provides [this] (map name (:provides this)))
(-requires [this] (map name (:requires this)))
(-source [this] (if-let [s (:source this)]
s (with-open [reader (io/reader (deps/-url this))]
(slurp reader)))))
(defrecord JavaScriptFile [foreign ^URL url ^URL source-url provides requires lines source-map]
deps/IJavaScript
(-foreign? [this] foreign)
(-closure-lib? [this] (:closure-lib this))
(-url [this] url)
(-provides [this] provides)
(-requires [this] requires)
(-source [this]
(with-open [reader (io/reader url)]
(slurp reader)))
ISourceMap
(-source-url [this] source-url)
(-source-map [this] source-map))
(defn javascript-file
([foreign ^URL url provides requires]
(javascript-file foreign url nil provides requires nil nil))
([foreign ^URL url source-url provides requires lines source-map]
(assert (first provides) (str source-url " does not provide a namespace"))
(JavaScriptFile. foreign url source-url (map name provides) (map name requires) lines source-map)))
(defn map->javascript-file [m]
(merge
(javascript-file
(:foreign m)
(when-let [f (:file m)]
(deps/to-url f))
(when-let [sf (:source-file m)]
(deps/to-url sf))
(:provides m)
(:requires m)
(:lines m)
(:source-map m))
(when (:closure-lib m)
{:closure-lib true})
(when (:macros-ns m)
{:macros-ns true})))
(defn read-js
"Read a JavaScript file returning a map of file information."
[f]
(let [source (slurp f)
m (deps/parse-js-ns (string/split-lines source))]
(map->javascript-file (assoc m :file f))))
;; Compile
;; =======
(defprotocol Inputs
(-paths [this] "Returns the file paths to the source inputs"))
(extend-protocol Inputs
String
(-paths [this] [(io/file this)])
File
(-paths [this] [this]))
(defprotocol Compilable
(-compile [this opts] "Returns one or more IJavaScripts."))
(defn compile-form-seq
"Compile a sequence of forms to a JavaScript source string."
[forms]
(comp/with-core-cljs nil
(fn []
(with-out-str
(binding [ana/*cljs-ns* 'cljs.user]
(doseq [form forms]
(comp/emit (ana/analyze (ana/empty-env) form))))))))
(defn compiled-file
"Given a map with at least a :file key, return a map with
{:file .. :provides .. :requires ..}.
Compiled files are cached so they will only be read once."
[m]
(let [path (.getPath (.toURL ^File (:file m)))
js (if (:provides m)
(map->javascript-file m)
(if-let [js (get-in @env/*compiler* [::compiled-cljs path])]
js
(read-js (:file m))))]
(swap! env/*compiler* update-in [::compiled-cljs] assoc path js)
js))
(defn compile
"Given a Compilable, compile it and return an IJavaScript."
[compilable opts]
(-compile compilable opts))
(defn compile-file
"Compile a single cljs file. If no output-file is specified, returns
a string of compiled JavaScript. With an output-file option, the
compiled JavaScript will written to this location and the function
returns a JavaScriptFile. In either case the return value satisfies
IJavaScript."
[^File file {:keys [output-file output-to] :as opts}]
(if output-file
(let [out-file (io/file (util/output-directory opts)
(or output-file output-to))]
(compiled-file (comp/compile-file file out-file opts)))
(let [path (.getPath ^File file)]
(binding [ana/*cljs-file* path]
(with-open [rdr (io/reader file)]
(compile-form-seq (ana/forms-seq* rdr path)))))))
(defn compile-dir
"Recursively compile all cljs files under the given source
directory. Return a list of JavaScriptFiles."
[^File src-dir opts]
(let [out-dir (util/output-directory opts)]
(map compiled-file
(comp/compile-root src-dir out-dir opts))))
(defn ^String path-from-jarfile
"Given the URL of a file within a jar, return the path of the file
from the root of the jar."
[^URL url]
(last (string/split (.getFile url) #"\.jar!/")))
(defn jar-file-to-disk
"Copy a file contained within a jar to disk. Return the created file."
[url out-dir]
(let [out-file (io/file out-dir (path-from-jarfile url))
content (with-open [reader (io/reader url)]
(slurp reader))]
(util/mkdirs out-file)
(spit out-file content)
out-file))
;; TODO: it would be nice if we could consolidate requires-compilation?
;; logic - David
(defn compile-from-jar
"Compile a file from a jar."
[this {:keys [output-file] :as opts}]
(or (when output-file
(let [out-file (io/file (util/output-directory opts) output-file)]
(when (and (.exists out-file)
(= (util/compiled-by-version out-file)
(util/clojurescript-version)))
(compile-file
(io/file (util/output-directory opts)
(last (string/split (.getPath ^URL this) #"\.jar!/")))
opts))))
(let [file-on-disk (jar-file-to-disk this (util/output-directory opts))]
(-compile file-on-disk opts))))
(extend-protocol Compilable
File
(-compile [this opts]
(if (.isDirectory this)
(compile-dir this opts)
(compile-file this opts)))
URL
(-compile [this opts]
(case (.getProtocol this)
"file" (-compile (io/file this) opts)
"jar" (compile-from-jar this opts)))
clojure.lang.PersistentList
(-compile [this opts]
(compile-form-seq [this]))
String
(-compile [this opts] (-compile (io/file this) opts))
clojure.lang.PersistentVector
(-compile [this opts] (compile-form-seq this))
)
(comment
;; compile a file in memory
(-compile "samples/hello/src/hello/core.cljs" {})
;; compile a file to disk - see file @ 'out/clojure/set.js'
(-compile (io/resource "clojure/set.cljs") {:output-file "clojure/set.js"})
;; compile a project
(-compile (io/file "samples/hello/src") {})
;; compile a project with a custom output directory
(-compile (io/file "samples/hello/src") {:output-dir "my-output"})
;; compile a form
(-compile '(defn plus-one [x] (inc x)) {})
;; compile a vector of forms
(-compile '[(ns test.app (:require [goog.array :as array]))
(defn plus-one [x] (inc x))]
{})
)
(defn js-dependencies
"Given a sequence of Closure namespace strings, return the list of
all dependencies. The returned list includes all Google and
third-party library dependencies.
Third-party libraries are configured using the :libs option where
the value is a list of directories containing third-party
libraries."
[opts requires]
(loop [requires requires
visited (set requires)
deps #{}]
(if (seq requires)
(let [node (or (get (@env/*compiler* :js-dependency-index) (first requires))
(deps/find-classpath-lib (first requires)))
new-req (remove #(contains? visited %) (:requires node))]
(recur (into (rest requires) new-req)
(into visited new-req)
(conj deps node)))
(remove nil? deps))))
(comment
;; find dependencies
(js-dependencies {} ["goog.array"])
;; find dependencies in an external library
(js-dependencies {:libs ["closure/library/third_party/closure"]} ["goog.dom.query"])
)
(defn get-compiled-cljs
"Return an IJavaScript for this file. Compiled output will be
written to the working directory."
[opts {:keys [relative-path uri]}]
(let [js-file (comp/rename-to-js relative-path)
compiled (-compile uri (merge opts {:output-file js-file}))]
(cond-> compiled
;; TODO: IJavaScript :provides :requires should really
;; always be Vector<MungedString> - David
(= ["cljs.js"] (into [] (map str) (deps/-provides compiled)))
(update-in [:requires] concat ["cljs.core$macros"]))))
(defn cljs-source-for-namespace
"Given a namespace return the corresponding source with either a .cljs or
.cljc extension."
[ns]
(if (= "cljs.core$macros" (str ns))
(let [relpath "cljs/core.cljc"]
{:relative-path relpath :uri (io/resource relpath)})
(let [path (-> (munge ns) (string/replace \. \/))
relpath (str path ".cljs")]
(if-let [res (io/resource relpath)]
{:relative-path relpath :uri res}
(let [relpath (str path ".cljc")]
(if-let [res (io/resource relpath)]
{:relative-path relpath :uri res}))))))
(defn source-for-namespace
"Given a namespace and compilation environment return the relative path and
uri of the corresponding source regardless of the source language extension:
.cljs, .cljc, .js"
[ns compiler-env]
(let [ns-str (str (comp/munge ns {}))
path (string/replace ns-str \. \/)
relpath (str path ".cljs")]
(if-let [cljs-res (io/resource relpath)]
{:relative-path relpath :uri cljs-res}
(let [relpath (str path ".cljc")]
(if-let [cljc-res (io/resource relpath)]
{:relative-path relpath :uri cljc-res}
(let [relpath (str path ".js")]
(if-let [js-res (io/resource relpath)]
{:relative-path relpath :uri js-res}
(let [ijs (get-in @compiler-env [:js-dependency-index (str ns)])
relpath (or (:file ijs) (:url ijs))]
(if-let [js-res (and relpath
;; try to parse URL, otherwise just return local
;; resource
(or (and (util/url? relpath) relpath)
(try (URL. relpath) (catch Throwable t))
(io/resource relpath)))]
{:relative-path relpath :uri js-res}
(throw
(IllegalArgumentException.
(str "Namespace " ns " does not exist"))))))))))))
(defn cljs-dependencies
"Given a list of all required namespaces, return a list of
IJavaScripts which are the cljs dependencies. The returned list will
not only include the explicitly required files but any transitive
dependencies as well. JavaScript files will be compiled to the
working directory if they do not already exist.
Only load dependencies from the classpath."
[opts requires]
(letfn [(cljs-deps [lib-names]
(->> lib-names
(remove #(or ((@env/*compiler* :js-dependency-index) %)
(deps/find-classpath-lib %)))
(map cljs-source-for-namespace)
(remove (comp nil? :uri))))]
(loop [required-files (cljs-deps requires)
visited (set required-files)
js-deps #{}]
(if (seq required-files)
(let [next-file (first required-files)
js (get-compiled-cljs opts next-file)
new-req (remove #(contains? visited %) (cljs-deps (deps/-requires js)))]
(recur (into (rest required-files) new-req)
(into visited new-req)
(conj js-deps js)))
(disj js-deps nil)))))
(comment
;; only get cljs deps
(cljs-dependencies {} ["goog.string" "cljs.core"])
;; get transitive deps
(cljs-dependencies {} ["clojure.string"])
;; don't get cljs.core twice
(cljs-dependencies {} ["cljs.core" "clojure.string"])
)
(defn add-dependencies
"Given one or more IJavaScript objects in dependency order, produce
a new sequence of IJavaScript objects which includes the input list
plus all dependencies in dependency order."
[opts & inputs]
(let [inputs (set inputs)
requires (set (mapcat deps/-requires inputs))
required-cljs (clojure.set/difference (cljs-dependencies opts requires) inputs)
required-js (js-dependencies opts
(into (set (mapcat deps/-requires required-cljs)) requires))
provided (set (mapcat deps/-provides (clojure.set/union inputs required-cljs required-js)))
unprovided (clojure.set/difference requires provided #{"constants-table"})]
(when (seq unprovided)
(ana/warning :unprovided @env/*compiler* {:unprovided (sort unprovided)}))
(cons
(javascript-file nil (io/resource "goog/base.js") ["goog"] nil)
(deps/dependency-order
(concat
(map
(fn [{:keys [foreign url file provides requires] :as js-map}]
(let [url (or url (io/resource file))]
(merge
(javascript-file foreign url provides requires)
js-map)))
required-js)
[(when (-> @env/*compiler* :options :emit-constants)
(let [url (deps/to-url (str (util/output-directory opts) "/constants_table.js"))]
(javascript-file nil url url ["constants-table"] ["cljs.core"] nil nil)))]
required-cljs
inputs)))))
(defn preamble-from-paths [paths]
(when-let [missing (seq (remove io/resource paths))]
(ana/warning :preamble-missing @env/*compiler* {:missing (sort missing)}))
(let [resources (remove nil? (map io/resource paths))]
(str (string/join "\n" (map slurp resources)) "\n")))
(defn make-preamble [{:keys [target preamble hashbang]}]
(str (when (and (= :nodejs target) (not (false? hashbang)))
(str "#!" (or hashbang "/usr/bin/env node") "\n"))
(when preamble (preamble-from-paths preamble))))
(comment
;; add dependencies to literal js
(add-dependencies {} "goog.provide('test.app');\ngoog.require('cljs.core');")
(add-dependencies {} "goog.provide('test.app');\ngoog.require('goog.array');")
(add-dependencies {} (str "goog.provide('test.app');\n"
"goog.require('goog.array');\n"
"goog.require('clojure.set');"))
;; add dependencies with external lib
(add-dependencies {:libs ["closure/library/third_party/closure"]}
(str "goog.provide('test.app');\n"
"goog.require('goog.array');\n"
"goog.require('goog.dom.query');"))
;; add dependencies with foreign lib
(add-dependencies {:foreign-libs [{:file "samples/hello/src/hello/core.cljs"
:provides ["example.lib"]}]}
(str "goog.provide('test.app');\n"
"goog.require('example.lib');\n"))
;; add dependencies to a JavaScriptFile record
(add-dependencies {} (javascript-file false
(deps/to-url "samples/hello/src/hello/core.cljs")
["hello.core"]
["goog.array"]))
)
;; Optimize
;; ========
(defmulti javascript-name class)
(defmethod javascript-name URL [^URL url]
(if url (.getPath url) "cljs/user.js"))
(defmethod javascript-name String [s]
(if-let [name (first (deps/-provides s))] name "cljs/user.js"))
(defmethod javascript-name JavaScriptFile [js] (javascript-name (deps/-url js)))
(defn build-provides
"Given a vector of provides, builds required goog.provide statements"
[provides]
(apply str (map #(str "goog.provide('" % "');\n") provides)))
(defmethod js-source-file JavaScriptFile [_ js]
(when-let [url (deps/-url js)]
(js-source-file (javascript-name url) (io/input-stream url))))
(defn add-cljs-base-module
([modules] (add-cljs-base-module modules nil))
([modules opts]
(reduce
(fn [modules module-name]
(if-not (= module-name :cljs-base)
(update-in modules [module-name :depends-on]
(fnil identity #{:cljs-base}))
modules))
(update-in modules [:cljs-base :output-to]
(fnil io/file
(io/file
(util/output-directory opts)
"cljs_base.js")))
(keys modules))))
(comment
(add-cljs-base-module
{:cljs-base
{:output-to "out/modules/base.js"}
:core
{:output-to "out/modules/core.js"
:entries '#{cljs.core}}
:landing
{:output-to "out/modules/reader.js"
:entries '#{cljs.reader}
:depends-on #{:core}}})
)
(defn sort-modules [modules-with-base]
(letfn [(get-deps [module]
(reduce
(fn [ret [name {:keys [depends-on] :as module-desc}]]
(cond-> ret
(contains? depends-on module) (conj name)))
[] modules-with-base))]
(vec (map (fn [module-name]
[module-name (module-name modules-with-base)])
(into [:cljs-base] (util/topo-sort :cljs-base get-deps))))))
(comment
(sort-modules
(add-cljs-base-module
{:cljs-base
{:output-to "out/module/base.js"}
:core
{:output-to "out/modules/core.js"
:entries '#{cljs.core}}
:landing
{:output-to "out/modules/reader.js"
:entries '#{cljs.reader}
:depends-on #{:core}}}))
)
(defn build-modules
"Given a list of IJavaScript sources in dependency order and compiler options
return a dependency sorted list of module name / description tuples. The
module descriptions will be augmented with a :closure-module entry holding
the Closure JSModule. Each module description will also be augmented with
a :foreign-deps vector containing foreign IJavaScript sources in dependency
order."
[sources opts]
(let [find-entry (fn [sources entry]
(some
(fn [source]
(let [matcher
(into #{}
[(name entry) (name (comp/munge entry))])]
(when (some matcher (:provides source))
source)))
sources))
used (atom {})
[sources' modules]
(reduce
(fn [[sources ret] [name {:keys [entries output-to depends-on] :as module-desc}]]
(assert (or (= name :cljs-base) (not (empty? entries)))
(str "Module " name " does not define any :entries"))
(when (:verbose opts)
(util/debug-prn "Building module" name))
(let [js-module (JSModule. (clojure.core/name name))
[sources' module-sources]
;; compute inputs for a closure module
;; as well as sources difference
(reduce
(fn [[sources ret] entry-sym]
(if-let [entry (find-entry sources entry-sym)]
(do
(swap! used assoc entry-sym name)
[(remove #{entry} sources) (conj ret entry)])
(if (contains? @used entry-sym)
(throw
(IllegalArgumentException.
(str "Already used namespace " entry-sym " "
"in module " (get @used entry-sym))))
(throw
(IllegalArgumentException.
(str "Could not find namespace " entry-sym))))))
[sources []] entries)
foreign-deps (atom [])]
;; add inputs to module
(doseq [ijs module-sources]
(when (:verbose opts)
(util/debug-prn " adding entry" (:provides ijs)))
(if-not (deps/-foreign? ijs)
(.add js-module
^SourceFile (js-source-file (javascript-name ijs) ijs))
(swap! foreign-deps conj ijs)))
;; add module dependencies, will always work
;; since modules are already in dependency order
(doseq [dep depends-on]
(if-let [parent-module (get-in (into {} ret) [dep :closure-module])]
(do
(when (:verbose opts)
(util/debug-prn " module" name "depends on" dep))
(.addDependency js-module ^JSModule parent-module))
(throw (IllegalArgumentException.
(str "Parent module " dep " does not exist")))))
[sources'
(conj ret
[name (assoc module-desc
:closure-module js-module
:foreign-deps @foreign-deps)])]))
[sources []] (sort-modules (add-cljs-base-module (:modules opts) opts)))
cljs-base-closure-module (get-in (into {} modules) [:cljs-base :closure-module])
foreign-deps (atom [])]
(when (:verbose opts)
(util/debug-prn "Adding remaining namespaces to" :cljs-base))
;; add anything left to :cljs-base module
(doseq [source sources']
(when (:verbose opts)
(util/debug-prn " adding entry" (:provides source)))
(if-not (deps/-foreign? source)
(.add ^JSModule cljs-base-closure-module
(js-source-file (javascript-name source) source))
(swap! foreign-deps conj source)))
(assoc-in modules [0 1 :foreign-deps] @foreign-deps)))
(comment
(build "samples/hello/src"
{:optimizations :none
:output-dir "out"
:output-to "out/hello.js"
:source-map true})
(let [modules
(build-modules
[(map->javascript-file
(ana/parse-ns 'cljs.core (io/file "out/cljs/core.js") nil))
(map->javascript-file
(ana/parse-ns 'cljs.reader (io/file "out/cljs/reader.js") nil))]
{:optimizations :advanced
:output-dir "out"
:cache-analysis true
:modules {:core
{:output-to "out/modules/core.js"
:entries '#{cljs.core}}
:landing
{:output-to "out/modules/reader.js"
:entries '#{cljs.reader}
:depends-on #{:core}}}})]
modules)
)
(defn emit-optimized-source-map
"Given a JSON parsed Google Closure JavaScript to JavaScript source map,
the entire list of original IJavaScript sources output a merged JavaScript
to ClojureScript source map file with the given file name. opts should
supply :preamble-line-count and :foreign-deps-line-count if they are
relevant."
[sm-json sources name opts]
(let [closure-source-map (sm/decode-reverse sm-json)]
(loop [sources (seq sources)
relpaths {}
merged (sorted-map-by
(sm/source-compare
(remove nil?
(map (fn [source]
(if-let [^URL source-url (:source-url source)]
(.getPath source-url)
(if-let [^URL url (:url source)]
(.getPath url))))
sources))))]
(if sources
(let [source (first sources)]
(recur
(next sources)
(let [{:keys [provides source-url]} source]
(if (and provides source-url)
(assoc relpaths
(.getPath ^URL source-url)
(util/ns->relpath (first provides) (util/ext source-url)))
relpaths))
(if-let [url (:url source)]
(let [path (.getPath ^URL url)]
(if-let [compiled (get-in @env/*compiler* [::comp/compiled-cljs path])]
(if-let [source-url (:source-url source)]
(assoc merged
(.getPath ^URL source-url)
(sm/merge-source-maps
(:source-map compiled)
(get closure-source-map path)))
merged)
(assoc merged path (get closure-source-map path))))
merged)))
(spit
(io/file name)
(sm/encode merged
{:preamble-line-count (+ (:preamble-line-count opts 0)
(:foreign-deps-line-count opts 0))
:lines (+ (:lineCount sm-json)
(:preamble-line-count opts 0)
(:foreign-deps-line-count opts 0)
2)
:file name
:output-dir (util/output-directory opts)
:source-map (:source-map opts)
:source-map-path (:source-map-path opts)
:source-map-timestamp (:source-map-timestamp opts)
:source-map-pretty-print (:source-map-pretty-print opts)
:relpaths relpaths}))))))
(defn optimize-modules
"Use the Closure Compiler to optimize one or more Closure JSModules. Returns
a dependency sorted list of module name and description tuples."
[opts & sources]
;; the following pre-condition can't be enabled
;; lein-cljsbuild adds :output-to?
#_{:pre [(and (contains? opts :modules)
(not (contains? opts :output-to)))]}
(assert (= (count (:modules opts))
(count (into #{}
(map (comp :output-to second)
(:modules opts)))))
"Each :output-to of :modules must be unique")
(let [closure-compiler (make-closure-compiler)
^List externs (load-externs opts)
compiler-options (make-options opts)
sources (if (= :whitespace (:optimizations opts))
(cons "var CLOSURE_NO_DEPS = true;" sources)
sources)
modules (build-modules sources opts)
^List inputs (map (comp :closure-module second) modules)
_ (doseq [^JSModule input inputs]
(.sortInputsByDeps input closure-compiler))
^Result result (.compileModules closure-compiler externs inputs compiler-options)
^SourceMap source-map (when (:source-map opts)
(.getSourceMap closure-compiler))]
(assert (or (nil? (:source-map opts)) source-map)
"Could not create source maps for modules")
(if (.success result)
(vec
(for [[name {:keys [output-to closure-module] :as module}] modules]
[name
(merge
(assoc module
:source
(do
(when source-map (.reset source-map))
(.toSource closure-compiler ^JSModule closure-module)))
(when source-map
(let [sw (StringWriter.)
source-map-name (str output-to ".map.closure")]
(.appendTo source-map sw source-map-name)
{:source-map-json (.toString sw)
:source-map-name source-map-name})))]))
(report-failure result))))
(defn optimize
"Use the Closure Compiler to optimize one or more JavaScript files."
[opts & sources]
(when (or ana/*verbose* (:verbose opts))
(util/debug-prn "Applying optimizations" (:optimizations opts) "to" (count sources) "sources"))
(let [closure-compiler (make-closure-compiler)
^List externs (load-externs opts)
compiler-options (make-options opts)
sources (if (= :whitespace (:optimizations opts))
(cons "var CLOSURE_NO_DEPS = true;" sources)
sources)