/
closure.clj
2569 lines (2141 loc) · 96 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
(ns shadow.build.closure
(:require
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.set :as set]
[cljs.analyzer :as ana]
[cljs.compiler :as comp]
[cljs.env :as env]
[shadow.cljs.util :as util]
[shadow.build.output :as output]
[shadow.build.warnings :as warnings]
[shadow.build.log :as build-log]
[shadow.build.data :as data]
[shadow.build.npm :as npm]
[shadow.build.cache :as cache]
[shadow.core-ext :as core-ext]
[shadow.build.resource :as rc]
[shadow.debug :refer (?> ?-> ?->>)]
[clojure.data.json :as json])
(:import
[java.io StringWriter ByteArrayInputStream FileOutputStream]
[com.google.javascript.jscomp
JSError SourceFile CompilerOptions CustomPassExecutionTime
CommandLineRunner VariableMap SourceMapInput DiagnosticGroups
CheckLevel JSModule CompilerOptions$LanguageMode
Result ShadowAccess SourceMap$DetailLevel SourceMap$Format
ClosureCodingConvention CompilationLevel VariableRenamingPolicy
PropertyRenamingPolicy PhaseOptimizer]
[shadow.build.closure
ReplaceCLJSConstants NodeEnvInlinePass ReplaceRequirePass PropertyCollector
NodeStuffInlinePass FindSurvivingRequireCalls]
[com.google.javascript.jscomp.deps ModuleLoader$ResolutionMode]
[java.nio.charset Charset]
[java.util.logging Logger Level]
[com.google.javascript.jscomp.parsing.parser FeatureSet]
[java.util LinkedHashMap]))
;; get rid of some annoying/useless warning log messages
;; https://github.com/google/closure-compiler/pull/2998/files
(doto (Logger/getLogger (.getName PhaseOptimizer))
(.setLevel Level/OFF))
(def SHADOW-CACHE-KEY
;; timestamp to ensure that new shadow-cljs release always invalidate caches
;; technically needs to check all files but given that they'll all be in the
;; same jar one is enough
[(data/sha1-url (io/resource "shadow/build/closure.clj"))
;; in case someone sets a specific closure dependency
(data/sha1-url (io/resource "com/google/javascript/jscomp/Compiler.class"))])
(def injected-libraries-field
(doto (-> (Class/forName "com.google.javascript.jscomp.Compiler")
(.getDeclaredField "injectedLibraries"))
(.setAccessible true)))
(def own-symbols-field
(doto (-> (Class/forName "com.google.javascript.jscomp.SymbolTable$SymbolScope")
(.getDeclaredField "ownSymbols"))
(.setAccessible true)))
;;;
;;; partially taken from cljs/closure.clj
;;; removed the things we don't need
;;;
(def check-levels
{:error CheckLevel/ERROR
:warning CheckLevel/WARNING
:off CheckLevel/OFF})
(def warning-types
(reduce
(fn [warnings [registered-name group]]
(let [kw (-> registered-name
(str/replace #"[A-Z]" #(str "-" (str/lower-case %)))
keyword)]
(assoc warnings kw group)))
{}
(DiagnosticGroups/getRegisteredGroups)))
(defn ^CompilerOptions$LanguageMode lang-key->lang-mode [key]
(case (keyword (str/replace (name key) #"^es" "ecmascript"))
:no-transpile CompilerOptions$LanguageMode/NO_TRANSPILE ;; same mode as input (for language-out only)
:ecmascript3 CompilerOptions$LanguageMode/ECMASCRIPT3
:ecmascript5 CompilerOptions$LanguageMode/ECMASCRIPT5
:ecmascript5-strict CompilerOptions$LanguageMode/ECMASCRIPT5_STRICT
:ecmascript6 CompilerOptions$LanguageMode/ECMASCRIPT_2015 ;; (deprecated and remapped)
:ecmascript6-strict CompilerOptions$LanguageMode/ECMASCRIPT_2015 ;; (deprecated and remapped)
:ecmascript-2015 CompilerOptions$LanguageMode/ECMASCRIPT_2015
:ecmascript6-typed CompilerOptions$LanguageMode/ECMASCRIPT6_TYPED
:ecmascript-2016 CompilerOptions$LanguageMode/ECMASCRIPT_2016
:ecmascript-2017 CompilerOptions$LanguageMode/ECMASCRIPT_2017
:ecmascript-next CompilerOptions$LanguageMode/ECMASCRIPT_NEXT
:ecmascript-next-in CompilerOptions$LanguageMode/ECMASCRIPT_NEXT_IN))
(defn ^FeatureSet kw->feature-set [kw]
(case kw
:bare-minimum FeatureSet/BARE_MINIMUM
:es3 FeatureSet/ES3
:es5 FeatureSet/ES5
;; FIXME: probably can't allow es6-modules variants since we can never load those
:es6 FeatureSet/ES6
:es7 FeatureSet/ES7
:es8 FeatureSet/ES8
:es2018 FeatureSet/ES2018
:es2019 FeatureSet/ES2019
:es2020 FeatureSet/ES2020
:es-next FeatureSet/ES_NEXT
:es-next-in FeatureSet/ES_NEXT_IN
(throw (ex-info "invalid :output-feature-set" {:val kw}))))
(defn set-options
[^CompilerOptions closure-opts opts state]
(when-let [level-kw (:optimizations opts)]
(when-let [level
(case level-kw
:advanced CompilationLevel/ADVANCED_OPTIMIZATIONS
:whitespace CompilationLevel/WHITESPACE_ONLY
:simple CompilationLevel/SIMPLE_OPTIMIZATIONS
:none nil
(throw (ex-info "invalid :optimizations level" opts)))]
(.setOptionsForCompilationLevel level closure-opts)))
(when (contains? opts :pretty-print)
(.setPrettyPrint closure-opts (:pretty-print opts)))
(when (:source-map opts)
(doto closure-opts
(.setSourceMapOutputPath "/dev/null")
(.setSourceMapDetailLevel
(let [lvl (:source-map-detail-level opts :all)]
(case lvl
:symbols SourceMap$DetailLevel/SYMBOLS
:all SourceMap$DetailLevel/ALL
(throw (ex-info "invalid value for :source-map-detail-level option" {:lvl lvl})))))
(.setSourceMapIncludeSourcesContent
(boolean (:source-map-include-sources-content opts true)))
(.setSourceMapFormat SourceMap$Format/V3)))
(when (contains? opts :pseudo-names)
(.setGeneratePseudoNames closure-opts (:pseudo-names opts)))
(when-let [lang-key (:language-in opts)]
(.setLanguageIn closure-opts (lang-key->lang-mode lang-key)))
(when-let [lang-key (:language-out opts)]
(.setLanguageOut closure-opts (lang-key->lang-mode lang-key)))
;; FIXME: maybe make this more customizable. may want es5 but allow class or so
(when-let [output-feature-set (:output-feature-set opts)]
(let [fs (kw->feature-set output-feature-set)]
(.setOutputFeatureSet closure-opts fs)))
(when-let [extra-annotations (:closure-extra-annotations opts)]
(. closure-opts (setExtraAnnotationNames (map name extra-annotations))))
(when (contains? opts :print-input-delimiter)
(set! (.printInputDelimiter closure-opts) (:print-input-delimiter opts)))
(when (contains? opts :closure-warnings)
(doseq [[type level] (:closure-warnings opts)]
(let [group (get warning-types type)
check-level (get check-levels level)]
(if-not (and group check-level)
(util/warn state {:type ::invalid-closure-warning :key type :level level})
(. closure-opts (setWarningLevel group check-level))))))
(when (contains? opts :closure-extra-annotations)
(. closure-opts (setExtraAnnotationNames (map name (:closure-extra-annotations opts)))))
(when (contains? opts :closure-generate-exports)
(. closure-opts (setGenerateExports (:closure-generate-exports opts))))
(when (contains? opts :rewrite-polyfills)
(. closure-opts (setRewritePolyfills (:rewrite-polyfills opts))))
(when (contains? opts :isolate-polyfills)
(. closure-opts (setIsolatePolyfills (:isolate-polyfills opts))))
(. closure-opts (setOutputCharset (Charset/forName (:closure-output-charset opts "UTF-8"))))
(when (contains? opts :variable-renaming)
(.setVariableRenaming
closure-opts
(case (:variable-renaming opts)
false VariableRenamingPolicy/OFF
:off VariableRenamingPolicy/OFF
:local VariableRenamingPolicy/LOCAL
:all VariableRenamingPolicy/ALL
(throw (ex-info "invalid :variable-renaming (use :off, :local or :all)" {})))))
(when (contains? opts :property-renaming)
(.setPropertyRenaming
closure-opts
(case (:property-renaming opts)
false PropertyRenamingPolicy/OFF
:off PropertyRenamingPolicy/OFF
true PropertyRenamingPolicy/ALL_UNQUOTED
:all-unquoted PropertyRenamingPolicy/ALL_UNQUOTED
(throw (ex-info "invalid :property-renaming (use :off or :all-unquoted)" {})))))
;; required to fix https://clojure.atlassian.net/browse/CLJS-3207
;; sometimes creates problems with reify + multiple :modules
(when (contains? opts :cross-chunk-method-motion)
(.setCrossChunkMethodMotion closure-opts (:cross-chunk-method-motion opts)))
(when (contains? opts :strip-types)
(.setStripTypes closure-opts (:strip-types opts)))
(when (contains? opts :strip-type-prefixes)
(.setStripTypePrefixes closure-opts (:strip-type-prefixes opts)))
(when (contains? opts :strip-name-prefixes)
(.setStripNamePrefixes closure-opts (:strip-name-prefixes opts)))
(when (contains? opts :strip-name-suffixes)
(.setStripNameSuffixes closure-opts (:strip-name-suffixes opts)))
(when (contains? opts :rename-prefix)
(.setRenamePrefix closure-opts (:rename-prefix opts)))
(when (contains? opts :rename-prefix-namespace)
(.setRenamePrefixNamespace closure-opts (:rename-prefix-namespace opts)))
closure-opts)
(defn ^CompilerOptions make-options []
(doto (CompilerOptions.)
(.setCodingConvention (ClosureCodingConvention.))))
(def default-externs
(delay (into [] (CommandLineRunner/getDefaultExterns))))
;; should use the exters/externs-map?
(def known-js-globals
(->> '[$CLJS
CLOSURE_BASE_PATH
COMPILED
Array
Boolean
document
Date
DocumentFragment
encodeURIComponent
Error
HTMLElement
Infinity
JSON
Number
Math
Object
ReferenceError
RegExp
self
setTimeout
String
Symbol
TypeError
console
eval
global
isFinite
isNaN
parseFloat
parseInt
performance
postMessage
process
require
WebSocket
Worker
XMLHttpRequest
window
__filename
__dirname]
(into #{} (map str))))
(defn clean-collected-properties [properties]
;; some files may have been minified by closure
;; which follows this naming pattern and we can't reserve those
;; since we need them for our :advanced build later
(if-not (set/superset? properties #{"a" "b" "c" "d" "e" "f"})
properties
;; just strip out the "short" properties
(into #{} (remove #(<= (count %) 2)) properties)))
(defn extern-props-from-cljs [state]
(->> (:build-sources state)
(map #(get-in state [:sources %]))
(filter #(= :cljs (:type %)))
(map (fn [{:keys [ns file] :as src}]
;; we know those don't need externs
(when (not= ns 'cljs.core)
(let [{:shadow/keys [js-access-properties]}
(get-in state [:compiler-env :cljs.analyzer/namespaces ns])]
js-access-properties
))))
(reduce set/union #{})))
(defn extern-globals-from-cljs [state]
(->> (:build-sources state)
(map #(get-in state [:sources %]))
(filter #(= :cljs (:type %)))
(map (fn [{:keys [ns file] :as src}]
;; we know those don't need externs
(when (not= ns 'cljs.core)
(let [{:shadow/keys [js-access-global]}
(get-in state [:compiler-env :cljs.analyzer/namespaces ns])]
js-access-global
))))
(reduce set/union #{})))
(defn externs-for-build [{:keys [build-id externs-file] :as state}]
(when (and externs-file (.exists externs-file))
(let [{props false
globals true
:as lines}
(with-open [rdr (io/reader externs-file)]
(->> (line-seq rdr)
(map str/trim)
(filter seq)
(remove #(str/starts-with? % "#"))
(group-by #(str/starts-with? % "global:"))))]
[(into #{} props)
(into #{} (map #(subs % 7)) globals)]
)))
(defn load-simplified-externs [state]
(let [[file-props file-globals]
(externs-for-build state)
content
(str (->> file-globals
(map #(comp/munge % #{}))
(sort)
(map #(str "/** @const {ShadowJS} */ var " % ";"))
(str/join "\n"))
"\n"
(->> file-props
(sort)
(map #(comp/munge % #{}))
(map #(str "ShadowJS.prototype." % ";"))
(str/join "\n")))]
(SourceFile/fromCode "simplified-externs.js" content)))
(defn generate-externs [state]
(let [js-externs?
(and (true? (get-in state [:js-options :generate-externs]))
(= :shadow (get-in state [:js-options :js-provider])))
js-props
(set/union
(when js-externs?
(:js-properties state))
(extern-props-from-cljs state))
js-globals
(set/union
(extern-globals-from-cljs state))
content
(str (->> js-globals
(remove known-js-globals)
(map #(comp/munge % #{}))
(sort)
(map #(str "/** @const {ShadowJS} */ var " % ";"))
(str/join "\n"))
"\n"
(->> js-props
(sort)
(map #(comp/munge % #{}))
(map #(str "ShadowJS.prototype." % ";"))
(str/join "\n")))]
;; not actually required but makes it easier to verify
(let [file (data/cache-file state "externs.shadow.js")]
(io/make-parents file)
(spit file content))
(SourceFile/fromCode "externs.shadow.js" content)
))
(defn load-externs [{:keys [build-modules deps-externs] :as state} generate?]
(let [externs
(distinct
(concat
(:externs state)
(get-in state [:compiler-options :externs])
;; needed to get rid of process/global errors in cljs/core.cljs
["shadow/cljs/externs/node.js"
;; always need those
"shadow/cljs/externs/process.js"]
(when (= :js (get-in state [:build-options :module-format]))
["shadow/cljs/externs/npm.js"])))
manual-externs
(when (seq externs)
(->> externs
(map
(fn [ext]
(if-let [rc (or (io/resource ext)
(let [file (io/file ext)]
(when (.exists file)
file)))]
(SourceFile/fromCode (str "EXTERNS:" ext) (slurp rc))
(do (util/warn state {:type :missing-externs :extern ext})
nil))))
(remove nil?)
;; just to force the logging
(into [])))
deps-externs
(when (get-in state [:build-options :cljsjs-externs])
(->> (for [[deps-path externs] deps-externs
{:keys [resource-name url] :as ext} externs]
;; FIXME: use url? deps-path is accurate enough for now
(SourceFile/fromCode (str "EXTERNS:" deps-path "!/" resource-name) (slurp url)))
(into [])))
simplified-externs
(load-simplified-externs state)
module-externs
(->> build-modules
(mapcat :module-externs)
(map #(str "var " % ";"))
(str/join "\n"))
all-externs
(-> []
(into @default-externs)
(into deps-externs)
(into manual-externs)
;; closure gets picky when things are defined multiple times
;; both the simplified and generated externs need this
(conj (SourceFile/fromCode
"externs-header.shadow.js"
"/** @constructor */\nfunction ShadowJS() {};\n"))
(conj simplified-externs)
(cond->
(seq module-externs)
(conj (SourceFile/fromCode "externs.modules.js" module-externs))
generate?
(conj (generate-externs state))))]
all-externs))
(defn register-cljs-protocol-properties
"this is needed to make :check-types work
It registers all known CLJS protocols with the Closure TypeRegistry
each method is as a property on Object since most of the time Closure doesn't know the proper type
and annotating everything seems unlikely."
[{::keys [compiler compiler-options]
:keys [compiler-env build-sources]
:as state}]
(when (contains? #{:warning :error} (get-in state [:compiler-options :closure-warnings :check-types]))
(let [type-reg
(.getTypeRegistry compiler)
obj-type
(.getGlobalType type-reg "Object")]
;; some general properties
(doseq [prop
["cljs$lang$protocol_mask$partition$"
"cljs$lang$macro"
"cljs$lang$test"]]
(.registerPropertyOnType type-reg prop obj-type))
;; find all protocols and register the protocol method properties
(doseq [ana-ns (vals (::ana/namespaces compiler-env))
:let [{:keys [defs]} ana-ns]
def (vals defs)
:when (-> def :meta :protocol-symbol)]
(let [{:keys [name meta]} def
{:keys [protocol-info]} meta
prefix
(str (comp/protocol-prefix name))]
;; the marker prop
;; some.prototype.cljs$core$ISeq$ = cljs.core.PROTOCOL_SENTINEL;
(.registerPropertyOnType type-reg prefix obj-type)
(doseq [[meth-name meth-sigs] (:methods protocol-info)
:let [munged-name (comp/munge meth-name)]
meth-sig meth-sigs]
(let [arity
(count meth-sig)
prop
(str prefix munged-name "$arity$" arity)]
;; register each arity some.prototype.cljs$core$ISeq$_seq$arity$1
(.registerPropertyOnType type-reg prop obj-type)
))))))
state)
(defn read-variable-map [state name]
(let [map-file (data/cache-file state name)]
(when (.exists map-file)
(try
(VariableMap/load (.getAbsolutePath map-file))
(catch Exception e
(util/error state {:type ::map-load-error :file map-file :ex e})
nil)))))
(defn use-variable-maps? [state]
(and (not (true? (get-in state [:compiler-options :pseudo-names])))
(= :advanced (get-in state [:compiler-options :optimizations]))))
(defn read-variable-maps
[{::keys [compiler compiler-options] :as state}]
(when (use-variable-maps? state)
(when-some [data (read-variable-map state "closure.property.map")]
(.setInputPropertyMap compiler-options data))
(when-some [data (read-variable-map state "closure.variable.map")]
(.setInputVariableMap compiler-options data)))
state)
(defn write-variable-map [state name map]
(when map
(let [map-file
(doto (data/cache-file state name)
(io/make-parents))
bytes
(ByteArrayInputStream. (.toBytes map))]
(with-open [out (FileOutputStream. map-file)]
(io/copy bytes out)))))
(defn write-variable-maps [{::keys [result] :as state}]
(when (use-variable-maps? state)
(write-variable-map state "closure.variable.map" (.-variableMap result))
(write-variable-map state "closure.property.map" (.-propertyMap result)))
state)
(defmethod build-log/event->str ::warnings
[{:keys [warnings]}]
(warnings/print-closure-warnings warnings))
(defn js-error-xf [state ^com.google.javascript.jscomp.Compiler cc]
(map (fn [^JSError err]
(let [source-name
(.getSourceName err)
description
(.getDescription err)
line
(.getLineNumber err)
column
(.getCharno err)
mapping
(.getSourceMapping cc source-name line column)
src
(when mapping
(let [src-name (.getOriginalFile mapping)]
(try
(data/get-source-by-name state src-name)
(catch Exception e
;; we might be importing JS files with source maps
;; which map back to source files we do not have
nil))))]
(if-not src
;; FIXME: add source-excerpt if src wasn't CLJS
{:resource-name source-name
:source-name source-name
:line line
:column column
:msg description}
(let [{:keys [resource-id resource-name file url]} src
file
(or (when file (.getAbsolutePath file))
(let [x (str url)]
(if-let [idx (str/index-of x ".m2")]
(str "~/" (subs x idx))
x))
(.getOriginalFile mapping))
line
(.getLineNumber mapping)
column
(.getColumnPosition mapping)
source-excerpt
(warnings/get-source-excerpt-for-rc state src {:line line :column column})]
{:resource-id resource-id
:resource-name resource-name
:source-name source-name
:file file
:line line
:column column
:msg description
:source-excerpt source-excerpt}
))))))
(defn closure-source-file
([name code]
(SourceFile/fromCode name code))
([name code original-name]
(-> (SourceFile/builder)
(.withOriginalPath original-name)
(.buildFromCode name code))))
(defn add-input-source-maps [{:keys [build-sources] :as state} cc]
(doseq [src-id build-sources
:let [{:keys [resource-name type output-name] :as rc}
(data/get-source-by-id state src-id)]
:when (not= :shadow-js type)]
(let [{:keys [source-map-json] :as output}
(data/get-output! state rc)
source-map-json
(or source-map-json
;; source-map is CLJS source map data, need to encode it to json so closure can read it
(output/encode-source-map-json state rc output))]
;; not using SourceFile/fromFile as the name that gets displayed in warnings sucks
;; public/js/cljs-runtime/cljs/core.cljs vs cljs/core.cljs
(->> (closure-source-file output-name source-map-json)
(SourceMapInput.)
(.addInputSourceMap cc resource-name))
)))
;; CLOSURE-WARNING: Property nodeGlobalRequire never defined on goog
;; Original: ~/.m2/repository/org/clojure/clojurescript/1.9.542/clojurescript-1.9.542.jar!/cljs/core.cljs [293:4]
;; cljs/core.cljs contains a call to goog.nodeGlobalRequire(...) which is only used in self-host mode
;; but causes the closure compiler --check to complain
;; since we are never going to use it just emit a noop to get rid of the warning
(def goog-nodeGlobalRequire-fix
"\ngoog.nodeGlobalRequire = function(path) { return false };\n")
(def constants-inject
(str "function shadow$keyword(name) { return new cljs.core.Keyword(null, name, name, null); };\n"
"function shadow$keyword_fqn(ns, name) { return new cljs.core.Keyword(ns, name, ns + \"/\" + name, null); };\n"))
(defn make-js-modules
[{:keys [build-modules build-sources] :as state}]
;; modules that only contain foreign sources must not be exposed to closure
;; since they technically do not depend on goog but closure only allows one root module
;; when optimizing
(let [skip-mods
(->> build-modules
(filter :all-foreign)
(map :module-id)
(into #{}))
required-js-names
(data/js-names-accessed-from-cljs state build-sources)
js-mods
(reduce
(fn [js-mods {:keys [module-id output-name depends-on sources goog-base] :as mod}]
(let [js-mod (JSModule. output-name)
sources
(->> sources
(map #(data/get-source-by-id state %))
(remove util/foreign?))
mod-provides
(->> sources
(map :provides)
(reduce set/union #{}))
mod-deps
(->> sources
(mapcat #(data/deps->syms state %))
(into #{}))
mod-constants-name
(str "shadow/cljs/constants/" (name module-id) ".js")]
(doseq [other-mod-id depends-on
:when (not (contains? skip-mods other-mod-id))
:let [other-mod (get js-mods other-mod-id)]]
(when-not other-mod
(throw (ex-info (format "module \"%s\" depends on undefined module \"%s\", defined modules are %s"
module-id
other-mod-id
(set (map :module-id build-modules)))
{:id module-id :other other-mod-id})))
(.addDependency js-mod other-mod))
;; every module that does not contain cljs.core will get a .constants js files as its first input
;; so the ReplaceCLJSConstants pass can write them into that file
;; special case for cljs.core since we shouldn't create keywords before they are defined
(when (and (contains? mod-deps 'cljs.core)
(not (contains? mod-provides 'cljs.core)))
(.add js-mod (closure-source-file mod-constants-name "")))
;; closure for some reason creates
;; module$demo$es6 = { ... };
;; directly without ever declaring a var for it. not sure why.
;; results in
;; Resource: demo/browser.cljs:2:18
;; variable module$demo$es6 is undeclared
;; warnings for each used module
(let [module-vars
(->> sources
(filter #(= :js (:type %)))
(map :ns)
(map comp/munge)
(str/join ","))]
(when (seq module-vars)
(.add js-mod (closure-source-file
(str "shadow/cljs/module_vars/" (name module-id) ".js")
;; var module$a,module$b,...; they will be renamed by advanced
(str "var " module-vars ";\n")))))
(doseq [{:keys [resource-name ns type] :as rc}
sources]
(let [{:keys [js]}
(data/get-output! state rc)
js
(cond
(= "goog/base.js" resource-name)
(str (output/closure-defines state)
js
goog-nodeGlobalRequire-fix)
(= :shadow-js type)
(str (when (contains? required-js-names ns)
(str "goog.provide(\"" ns "\");\n"
ns " = " (npm/shadow-js-require rc))))
:else
js)]
(.add js-mod (closure-source-file resource-name js))
(when (= ns 'cljs.core)
(.add js-mod (closure-source-file mod-constants-name constants-inject)))
))
(assoc js-mods module-id js-mod)))
{}
(->> build-modules
(remove :all-foreign)))
modules
(->> (for [{:keys [module-id] :as mod} build-modules]
(assoc mod :js-module (get js-mods module-id)))
(into []))]
(assoc state ::modules modules)))
(defn as-module-exports [defs]
(when (seq defs)
(str "\nmodule.exports={" defs "};")))
(defn make-js-module-per-source
[{:keys [compiler-env build-sources] :as state}]
(let [js-mods
(reduce
(fn [js-mods resource-id]
(let [{:keys [ns deps type resource-name output-name] :as src}
(data/get-source-by-id state resource-id)
{:keys [js] :as output}
(data/get-output! state {:resource-id resource-id})
defs
(cond
;; special case for js shim namespaces
(:export-self src)
(str "\nmodule.exports=" ns ";")
;; for every CLJS namespace, collect every ^:export def
;; and copy them to module.exports, the goog.export... will be removed
;; as that exports to global which is not what we want
ns
(->> (get-in compiler-env [::ana/namespaces ns :defs])
(vals)
(filter #(get-in % [:meta :export]))
(map :name)
(map (fn [def]
(let [export-name (-> def name str)
export-name
(if (= "default" export-name)
export-name
(-> export-name (comp/munge) (core-ext/safe-pr-str)))]
(str export-name ":" (comp/munge def)))))
(str/join ",")
(as-module-exports))
:else
nil)
base?
(= output/goog-base-id resource-id)
code
(str (when base?
(output/closure-defines state))
js
(when base?
(str goog-nodeGlobalRequire-fix
"\ngoog.global = global;"))
;; FIXME: module.exports will become window.module.exports, rewritten later
(when (seq defs)
defs))
js-mod
(JSModule. (util/flat-filename output-name))]
(when (= :cljs type)
(.add js-mod (closure-source-file (str "shadow/cljs/constants/" resource-name) "")))
(.add js-mod (closure-source-file resource-name code))
(doseq [dep
(->> (data/deps->syms state src)
(map #(data/get-source-id-by-provide state %))
(distinct)
(into []))]
(let [other-mod (get js-mods dep)]
(when-not other-mod
(throw (ex-info (format "internal module error, no mod for dep:%s" dep)
{:dep dep})))
(.addDependency js-mod other-mod)))
(assoc js-mods resource-id js-mod)))
{}
build-sources)
modules
(->> build-sources
(map (fn [resource-id]
(let [src (data/get-source-by-id state resource-id)]
{:module-id resource-id
:name (:name src)
:output-name (util/flat-filename (:output-name src))
:js-module (get js-mods resource-id)
:sources [resource-id]})))
(into []))]
(assoc state ::modules modules)))
(defn setup
[{::keys [modules]
:keys [closure-injected-libs compiler-options] :as state}]
(let [source-map?
(boolean (:source-map compiler-options))
cc
(data/make-closure-compiler)
closure-opts
(doto (make-options)
(.resetWarningsGuard)
(.setNumParallelThreads (get-in state [:compiler-options :closure-threads] 1))
;; namespaced keywords will cause a lot of repetition for namespace strings
;; allowing closure to alias them can cut the overall size a bit
;; gzip actually takes quite good care of this already but this squeezes
;; another few bytes out for no additional work
(.setAliasableStrings
(->> (:compiler-env state)
(::ana/namespaces)
(keys)
(map str)
(set)))
(.setWarningLevel DiagnosticGroups/CHECK_TYPES CheckLevel/OFF)
;; really only want the undefined variables warnings
;; must turn off CHECK_VARIABLES first or it will complain too much (REDECLARED_VARIABLES)
(.setWarningLevel DiagnosticGroups/CHECK_VARIABLES CheckLevel/OFF)
;; this one is very helpful to spot missing externs
;; (js/React...) will otherwise just work without externs
(.setWarningLevel DiagnosticGroups/UNDEFINED_VARIABLES CheckLevel/WARNING))]
(set-options closure-opts compiler-options state)
;; ensure that libs injected during transforms are injected again
;; not using polyfill-js since we might need to inject polyfills for CLJS
;; which wasn't processed yet and would clash with the manually injected libs
(let [injected-libs
(set/union
#{}
closure-injected-libs
(get-in state [:compiler-options :force-library-injection]))]
(when (seq injected-libs)
(doto closure-opts
(.setRewritePolyfills true)
(.setForceLibraryInjection injected-libs))))
;; add-input-source-maps requires options to be set, otherwise throws NPE
;; ShadowCompiler exposes this to just set options since initOptions does a bunch of stuff
;; we do not need yet
(.justSetOptions cc closure-opts)
(.setApplyInputSourceMaps closure-opts true)
(add-input-source-maps state cc)
(.addCustomPass closure-opts CustomPassExecutionTime/BEFORE_CHECKS
(ReplaceCLJSConstants. cc (true? (get-in state [:compiler-options :shadow-keywords]))))
(.addCustomPass closure-opts CustomPassExecutionTime/BEFORE_CHECKS
(NodeEnvInlinePass. cc (if (= :release (:mode state))
"production"
"development")))
;; (fn [closure-compiler compiler-options state])
(doseq [cfg (:closure-configurators compiler-options)]
(cfg cc closure-opts state))
(when (= :js (get-in state [:build-options :module-format]))
;; cut the goog.exportSymbol call CLJS may have generated
;; since they will still export to window which is not what we want
(.setStripTypePrefixes closure-opts (into #{"goog.exportSymbol"} (.-stripTypePrefixes closure-opts)))
;; can be anything but will be repeated a lot
;; $ vs $CLJS adds about 4kb to cljs.core alone but that is only 250 bytes after gzip
;; choosing $CLJS so the alias is the same in dev mode and avoiding potential conflicts
;; with jQuery or so when using only $
(.setRenamePrefixNamespace closure-opts "$CLJS"))
(assoc state
::externs (load-externs state true)
::compiler cc
::compiler-options closure-opts)))
(defn load-extern-properties [{::keys [extern-properties] :as state}]
(if extern-properties
state
(let [cc (data/make-closure-compiler)
co
(doto (make-options)
(set-options
{:optimizations :simple
:language-in :ecmascript5}
state))
externs
(load-externs state false)
result
(.compile cc externs [] co)
;; already immutable set, but incompatible
;; com.google.common.collect.RegularImmutableSet cannot be cast to clojure.lang.IPersistentCollection
extern-properties
(into #{} (ShadowAccess/getExternProperties cc))]
(when-not (.success result)
(throw (ex-info
(str "Error processing externs:\n"
(->> (.errors result)
(map str)
(str/join "\n")))
{:tag ::load-externs-failed})))
(assoc state ::extern-properties extern-properties)
)))
(defn rewrite-node-global-access [js]
(-> js
;; RescopeGlobalSymbols rewrites
;; require("react")
;; to
;; (0,window.require)("react") // FIXME: why the 0,?
;; webpack & co no not recognize this
;; so we must turn it back into
;; /*********/require("react")
;; with the padding to not mess up source maps
(str/replace "(0,window.require)(" "/*********/require(")
;; window.module.exports
;; /*****/module.exports
(str/replace "window.module.exports", "/*****/module.exports")