-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathes6-convertor.js
1569 lines (1058 loc) · 53 KB
/
es6-convertor.js
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
/**
* @file The threejs convertor
*
* @author Itee <valcketristan@gmail.com>
* @license MIT
*/
const fs = require( 'fs' )
const path = require( 'path' )
const utils = require( './utils' )
////////////////////////// CONDITIONAL UTILS /////////////////////////////
/**
* Extend the String prototype if contains not exist.
* It allow to check if the string contains or not a target string
*
* @type {Function}
* @param {string} target - The string to match in current string
* @return {boolean}
*/
String.prototype.contains = String.prototype.contains || function ( target ) { return this.indexOf( target ) > -1 }
/**
* Check if the parameter is of type string
*
* @param {any} value - The value to check the string type
* @return {boolean}
*/
function isString ( value ) {
return ( typeof value === 'string' )
}
/**
* Check if the parameter is NOT of type string
*
* @param {any} value - The value to check the non string type
* @return {boolean}
*/
function isNotString ( value ) {
return ( !isString( value ) )
}
/**
* Check if the parameter is an array of string.
* Note: An array of empty string will return true.
*
* @param {any} values - The value to check if it is an array of string
* @return {boolean} - True if array of string, false otherwise
*/
function isArrayOfString ( values ) {
if ( !Array.isArray( values ) ) { return false }
for ( let index = 0, numberOfValues = values.length ; index < numberOfValues ; index++ ) {
if ( isNotString( values[ index ] ) ) { return false }
}
return true
}
///////////////////////// FILES UTILS //////////////////////////////
function _removeCommentsFrom ( file ) {
return file.replace( /\/\*[\s\S]*?\*\//g, '' ) // Multi-lines comment
.replace( /\/\/.*/g, '' ) // Single line comment
}
function _removeStringsFrom ( file ) {
return file.replace( /".*"|\'.*\'/g, '' )
}
function _getFileType ( file ) {
// Todo: use regex as global
// Todo: use Object.freeze about fileType
const es6Regex = new RegExp( /(export\s(default|var))|((import|export)[\r\n\s]*(default)?({[\w\s,]+}\s?(from)?))/, 'g' )
const amdRegex = new RegExp( /define\.amd/, 'g' )
const cjsRegex = new RegExp( /module\.exports\s*=\s*\{?[^}]*}?/g )
const classicObjectRegex = new RegExp( /(THREE.(\w+)\s*=\s*)+\s*function/g )
const prototypedObjectRegex = new RegExp( /prototype\.constructor\s?=\s?(THREE\.)?(\w)+/g )
const libRegex = new RegExp( /THREE.(\w+) = \{/g )
const es6Match = file.match( es6Regex )
if ( es6Match && es6Match.length > 0 ) {
return 'es6'
}
const amdMatch = file.match( amdRegex )
if ( amdMatch && amdMatch.length > 0 ) {
return 'amd'
}
const cjsMatch = file.match( cjsRegex )
if ( cjsMatch && cjsMatch.length > 0 ) {
return 'cjs'
}
const classicObjectMatch = file.match( classicObjectRegex )
if ( classicObjectMatch && classicObjectMatch.length > 0 ) {
return 'classic'
}
const prototypedObjectMatch = file.match( prototypedObjectRegex )
if ( prototypedObjectMatch && prototypedObjectMatch.length > 0 ) {
return 'prototype'
}
const libMatch = file.match( libRegex )
if ( libMatch && libMatch.length > 0 ) {
return 'lib'
}
return 'unknown'
}
function _convertFile ( banner, fileDatas ) {
const outputPath = fileDatas.output
const formatedImports = _formatImportStatements( outputPath, fileDatas.imports )
const formatedFile = _formatReplacementStatements( fileDatas.file, fileDatas.replacements )
const formatedExports = _formatExportStatements( outputPath, fileDatas.exports )
const outputFile = banner + formatedImports + formatedFile + formatedExports
const cleanFile = _cleanFile( outputFile )
fs.mkdirSync( path.dirname( outputPath ), { recursive: true } )
fs.writeFileSync( outputPath, cleanFile )
}
function _copyFile ( banner, fileDatas ) {
const outputPath = fileDatas.output
const file = banner + fileDatas.file
const cleanFile = _cleanFile( file )
fs.mkdirSync( path.dirname( outputPath ), { recursive: true } )
fs.writeFileSync( outputPath, cleanFile )
}
function _cleanFile ( file ) {
// Remove extra blank lines then extra semi-colon
return file.replace( /(^[\s\t]*[\r\n]){2,}/gm, '' )
.replace( /;([\r\n]*;)/gm, ';' )
}
///////////////////////// COMMON UTILS //////////////////////////////
function _makeUnique ( value, index, array ) {
return array.indexOf( value ) === index
}
/////////////////////////// ES6 CONVERTOR PRIVATE STUFF ////////////////////////////
/////////////////////////// EXPORTS MAPS ////////////////////////////
let _exportMap = {}
let _revertExportMap = {}
let _fileMap = {}
function _createDataMap ( filesPaths, edgeCases, outputBasePath ) {
let fileExtension = undefined
let baseName = undefined
let edgeCase = undefined
let file = undefined
let isJavascript = undefined
let overrideFilePath = undefined
let outputPath = undefined
let fileType = undefined
let imports = undefined
let exports = undefined
let replacements = undefined
let data = undefined
filesPaths.forEach( ( filePath ) => {
} )
}
function _createExportMap ( filesPaths, edgeCases, outputBasePath ) {
let fileExtension = undefined
let baseName = undefined
let edgeCase = undefined
let baseFile = undefined
let file = undefined
let exports = undefined
let overrideFilePath = undefined
let outputPath = undefined
filesPaths.forEach( ( filePath ) => {
fileExtension = path.extname( filePath )
baseName = path.basename( filePath, fileExtension )
edgeCase = edgeCases[ baseName ] || {}
baseFile = utils.getFileForPath( filePath )
file = _removeCommentsFrom( _removeStringsFrom( baseFile ) )
exports = _getExportsFor( file, edgeCase[ 'exports' ], edgeCase[ 'exportsOverride' ] )
if ( !exports ) {
// Fallback with file name in last resore
console.error( 'WARNING: ' + baseName + ' from ' + filePath + ' does not contains explicit or implicit export, fallback to file name as default export... If the file name does not corespond to the expected stuff, please update es6.config.edgeCases.' + baseName + '.exports' )
exports = [ baseName ]
}
outputPath = _getOutputFor( filePath, outputBasePath, edgeCase[ 'outputOverride' ] )
exports.forEach( ( exportedElement ) => {
// Check case where export is an array with 'from' or 'as'
if ( Array.isArray( exportedElement ) ) {
if ( exportedElement.length === 3 ) {
if ( exportedElement[ 1 ] === 'as' ) {
exportedElement = exportedElement[ 2 ]
} else {
console.error( 'WARNING: Element "' + exportedElement + '" in file ' + path.basename( filePath ) + ' contain multiples element or alias in an unmanaged way. Defaulting to the first element as export of the file !' )
exportedElement = exportedElement[ 0 ]
}
} else {
console.error( 'WARNING: Element "' + exportedElement + '" in file ' + path.basename( filePath ) + ' contain multiples element or alias in an unmanaged way. Defaulting to the first element as export of the file !' )
exportedElement = exportedElement[ 0 ]
}
}
// Check about duplicated exports, Keep source path when possible then jsm and finally example
const exportPath = _exportMap[ exportedElement ]
if ( exportPath ) {
// Retrieve origin of previous export
const baseExportPath = _revertExportMap[ exportedElement ]
//Todo: Need to setup a precedence over file path to determine which export is the right
const sourcePathTarget = 'sources\\'
const srcPathTarget = 'src\\'
const modulePathTarget = 'jsm\\'
const examplePathTarget = 'examples\\js\\'
if ( baseExportPath.contains( sourcePathTarget ) ) {
if ( filePath.contains( srcPathTarget ) ) {
console.error( 'ERROR: Element "' + exportedElement + '" in source folder ' + filePath + ' is already exported by source ' + baseExportPath + '! Unable to determine which source file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
} else if ( filePath.contains( modulePathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in jsm folder ' + filePath + ' is already exported by source ' + baseExportPath + '. Ignoring the jsm export ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
} else if ( filePath.contains( examplePathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in example folder ' + filePath + ' is already exported by source ' + baseExportPath + '. Ignoring the example export ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
} else {
console.error( 'ERROR: Element "' + exportedElement + '" from ' + filePath + ' is already exported by ' + baseExportPath + '! Unable to determine which file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
}
} else if ( baseExportPath.contains( modulePathTarget ) ) {
if ( filePath.contains( srcPathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in source folder ' + filePath + ' is already exported by jsm ' + baseExportPath + '. Replacing by the source file ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
_exportMap[ exportedElement ] = outputPath
_revertExportMap[ exportedElement ] = filePath
} else if ( filePath.contains( modulePathTarget ) ) {
console.error( 'ERROR: Element "' + exportedElement + '" in jsm folder ' + filePath + ' is already exported by jsm ' + baseExportPath + '! Unable to determine which jsm file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
} else if ( filePath.contains( examplePathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in example folder ' + filePath + ' is already exported by jsm ' + baseExportPath + '. Ignoring the example export ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
} else {
console.error( 'ERROR: Element "' + exportedElement + '" from ' + filePath + ' is already exported by ' + baseExportPath + '! Unable to determine which file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
}
} else if ( baseExportPath.contains( examplePathTarget ) ) {
if ( filePath.contains( srcPathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in source folder ' + filePath + ' is already exported by example ' + baseExportPath + '. Replacing by the source file ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
_exportMap[ exportedElement ] = outputPath
_revertExportMap[ exportedElement ] = filePath
} else if ( filePath.contains( modulePathTarget ) ) {
console.warn( 'WARNING: Element "' + exportedElement + '" in jsm folder ' + filePath + ' is already exported by example ' + baseExportPath + '. Replacing by the jsm export ! Please update es6.config.excludes and add the wrong exporter file: ' + baseExportPath )
_exportMap[ exportedElement ] = outputPath
_revertExportMap[ exportedElement ] = filePath
} else if ( filePath.contains( examplePathTarget ) ) {
console.error( 'ERROR: Element "' + exportedElement + '" in example folder ' + filePath + ' is already exported by example ' + baseExportPath + '! Unable to determine which example file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
} else {
console.error( 'ERROR: Element "' + exportedElement + '" from ' + filePath + ' is already exported by ' + baseExportPath + '! Unable to determine which file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
}
} else {
console.error( 'ERROR: Element "' + exportedElement + '" from unmanaged file ' + filePath + ' is already exported by unmanaged file ' + baseExportPath + '! Unable to determine which file is the right exporter !!! Please update es6.config.excludes and add the wrong exporter file.' )
}
} else {
_exportMap[ exportedElement ] = outputPath
_revertExportMap[ exportedElement ] = filePath
}
} )
} )
}
function _createFilesMap ( filesPaths, edgeCases, outputBasePath ) {
let fileExtension = undefined
let baseName = undefined
let edgeCase = undefined
let file = undefined
let baseFile = undefined
let isGLSL = undefined
let isJavascript = undefined
let overrideFilePath = undefined
let fileType = undefined
let imports = undefined
let replacements = undefined
let exports = undefined
let outputPath = undefined
let data = undefined
filesPaths.forEach( ( filePath ) => {
fileExtension = path.extname( filePath )
baseName = path.basename( filePath, fileExtension )
baseFile = utils.getFileForPath( filePath )
file = _removeCommentsFrom( baseFile )
isGLSL = ( baseName.indexOf( 'glsl' ) > -1 )
isJavascript = ( !isGLSL && fileExtension === '.js' )
if ( _fileMap[ baseName ] ) {
console.error( 'The key ' + baseName + ' already exist in the file map ! Is there a duplicate file ??? Skip it !' )
return
}
if ( isJavascript ) {
edgeCase = edgeCases[ baseName ] || {}
outputPath = _getOutputFor( filePath, outputBasePath, edgeCase[ 'outputOverride' ] )
fileType = _getFileType( file )
// Processing exports
exports = _getExportsFor( file, edgeCase[ 'exports' ], edgeCase[ 'exportsOverride' ] )
if ( !exports ) {
// Fallback with file name in last resore
console.error( 'WARNING: ' + baseName + ' from ' + filePath + ' does not contains explicit or implicit export, fallback to file name as default export... If the file name does not corespond to the expected stuff, please update es6.config.edgeCases.' + baseName + '.exports' )
exports = [ baseName ]
}
imports = _getImportsFor( {
file: _removeCommentsFrom( _removeStringsFrom( baseFile ) ),
exports: exports,
output: outputPath
} )
replacements = _getReplacementsFor( file, exports )
data = _applyEdgeCases( filePath, imports, replacements, exports, outputPath, edgeCase )
_fileMap[ baseName ] = {
path: filePath,
isJavascript: ( fileExtension === '.js' ),
fileType: fileType,
file: baseFile,
imports: data.imports,
replacements: data.replacements,
exports: data.exports,
output: data.output
}
} else {
_fileMap[ baseName ] = {
path: filePath,
isJavascript: isJavascript,
file: file,
output: _getOutputFor( filePath, outputBasePath )
}
}
} )
}
/////////////////////////// IMPORTS ////////////////////////////
function _getAllImportsStatementIn ( file, exports ) {
let statements = []
const matchs = file.match( /import\s+(?:(?:({[\w\s,]+})|([\w,*-]+))\s+)+from/g ) || []
matchs.forEach( ( value ) => {
const results = value.replace( 'import', '' )
.replace( 'from', '' )
.replace( /[{}]/g, '' )
.replace( /(?<!as)\s+(?!as)/g, '' ) // Keep "Foo as _Foo"
.split( ',' )
if ( results.length > 0 ) {
Array.prototype.push.apply( statements, results )
}
} )
return statements
}
function _getAllExtendsStatementIn ( file, exports ) {
let statements = []
// By Object.assign
const matchs = file.match( /Object\.assign\(\s*((THREE.)?(\w+)\.prototype[,]*\s*){2,}/g ) || []
matchs.forEach( ( value ) => {
const results = value.replace( /Object\.assign\(\s+/g, '' )
.replace( /THREE\./g, '' )
.replace( /\.prototype/g, '' )
.replace( /\s+/g, '' )
.split( ',' )
if ( results.length > 0 ) {
Array.prototype.push.apply( statements, results )
}
} )
return statements
}
function _getAllInheritStatementsIn ( file, exports ) {
let statements = []
const matchs = file.match( /Object\.create\(\s+((THREE.)?(\w+)\.prototype[,]?\s*)+\)/g ) || []
matchs.forEach( ( value ) => {
const results = value.replace( /Object\.create\(\s+(THREE.)?/g, '' )
.replace( /\.prototype/g, '' )
.replace( /\)/g, '' )
.replace( /\s+/g, '' )
.split( ',' )
if ( results.length > 0 ) {
Array.prototype.push.apply( statements, results )
}
} )
return statements
}
function _getAllNewStatementIn ( file, exports ) {
let statements = []
const matchs = file.match( /new\sTHREE\.(\w+)\s?/g ) || []
matchs.forEach( ( value ) => {
const result = value.replace( /new\sTHREE\./g, '' )
.replace( /\s+/g, '' )
if ( result ) { statements.push( result ) }
} )
return statements
}
function _getAllInstanceOfStatementIn ( file, exports ) {
let statements = []
const matchs = file.match( /instanceof\sTHREE.(\w+)\s?/g ) || []
matchs.forEach( ( value ) => {
const result = value.replace( /instanceof\sTHREE\./g, '' )
.replace( /\s+/g, '' )
if ( result ) { statements.push( result ) }
} )
return statements
}
function _getAllThreeObjectsIn ( file, exports ) {
let statements = []
const matchs = file.match( /(?<=THREE\.)(\w+)/g ) || []
matchs.forEach( ( value ) => {
if ( value ) { statements.push( value ) }
} )
return statements
}
function _getAllImportsFromExports ( file, exports ) {
let statements = []
for ( let exportName in _exportMap ) {
const regex = new RegExp( '(?<!\\w)' + exportName + '(?!\\w)', 'g' )
const matchs = file.match( regex ) || []
matchs.forEach( ( value ) => {
// Check if the new statement is not about the exported object !
if ( exports.includes( value ) ) {
return
}
if ( value ) { statements.push( value ) }
} )
}
return statements
}
function _getImportsFor ( fileDatas ) {
const file = fileDatas.file
const exports = fileDatas.exports
const outputPath = fileDatas.output
let statements = []
Array.prototype.push.apply( statements, _getAllImportsStatementIn( file, exports ) )
Array.prototype.push.apply( statements, _getAllInheritStatementsIn( file, exports ) )
Array.prototype.push.apply( statements, _getAllExtendsStatementIn( file, exports ) )
Array.prototype.push.apply( statements, _getAllNewStatementIn( file, exports ) )
Array.prototype.push.apply( statements, _getAllInstanceOfStatementIn( file, exports ) )
Array.prototype.push.apply( statements, _getAllImportsFromExports( file, exports ) )
Array.prototype.push.apply( statements, _getAllThreeObjectsIn( file, exports ) )
// Array.prototype.push.apply( statements, _getAllConstantStatementIn( file ) )
// Special treatment for intermediary exporter file or Class imported using "as" keyword
// A class can be inherited and dynamicaly create by new in the same file so we need to check uniqueness
return statements.flatMap( statement => {
if ( statement.contains( ' as ' ) ) {
const targetImport = statement.split( ' ' )[ 2 ]
if ( targetImport === '_Math' ) {
return [ '_Math' ]
} else if ( targetImport === 'Curves' ) {
// Equivalent to ( import * as Curves from 'intermediary exporter file Curves' )
return [
'ArcCurve',
'CatmullRomCurve3',
'CubicBezierCurve',
'CubicBezierCurve3',
'EllipseCurve',
'LineCurve',
'LineCurve3',
'QuadraticBezierCurve',
'QuadraticBezierCurve3',
'SplineCurve',
'GrannyKnot',
'HeartCurve',
'VivianiCurve',
'KnotCurve',
'HelixCurve',
'TrefoilKnot',
'TorusKnot',
'CinquefoilKnot',
'TrefoilPolynomialKnot',
'FigureEightPolynomialKnot',
'DecoratedTorusKnot4a',
'DecoratedTorusKnot4b',
'DecoratedTorusKnot5a',
'DecoratedTorusKnot5c'
]
} else if ( targetImport === 'Geometries' ) {
// Equivalent to ( import * as Geometries from 'intermediary exporter file Geometries' )
return [
'WireframeGeometry',
'TetrahedronGeometry',
'TetrahedronBufferGeometry',
'OctahedronGeometry',
'OctahedronBufferGeometry',
'IcosahedronGeometry',
'IcosahedronBufferGeometry',
'DodecahedronGeometry',
'DodecahedronBufferGeometry',
'PolyhedronGeometry',
'PolyhedronBufferGeometry',
'TubeGeometry',
'TubeBufferGeometry',
'TorusKnotGeometry',
'TorusGeometry',
'TorusBufferGeometry',
'TextGeometry',
'TextBufferGeometry',
'SphereGeometry',
'SphereBufferGeometry',
'RingGeometry',
'RingBufferGeometry',
'PlaneGeometry',
'PlaneBufferGeometry',
'LatheGeometry',
'LatheBufferGeometry',
'ShapeGeometry',
'ShapeBufferGeometry',
'ExtrudeGeometry',
'ExtrudeBufferGeometry',
'EdgesGeometry',
'ConeGeometry',
'ConeBufferGeometry',
'CylinderGeometry',
'CylinderBufferGeometry',
'CircleGeometry',
'CircleBufferGeometry',
'BoxGeometry',
'BoxBufferGeometry'
]
} else if ( targetImport === 'Materials' ) {
// Equivalent to ( import * as Materials from 'intermediary exporter file Materials' )
return [
'LineBasicMaterial',
'LineDashedMaterial',
'MeshBasicMaterial',
'MeshDepthMaterial',
'MeshDistanceMaterial',
'MeshLambertMaterial',
'MeshNormalMaterial',
'MeshPhongMaterial',
'MeshPhysicalMaterial',
'MeshStandardMaterial',
'MeshToonMaterial',
'PointsMaterial',
'RawShaderMaterial',
'ShaderMaterial',
'ShadowMaterial',
'SpriteMaterial'
]
} else if ( targetImport === 'Nodes' ) {
// Equivalent to ( import * as Nodes from 'intermediary exporter file Nodes' )
return [
'Node',
'TempNode',
'InputNode',
'ConstNode',
'VarNode',
'StructNode',
'AttributeNode',
'FunctionNode',
'ExpressionNode',
'FunctionCallNode',
'NodeLib',
'NodeUtils',
'NodeFrame',
'NodeUniform',
'NodeBuilder',
'BoolNode',
'IntNode',
'FloatNode',
'Vector2Node',
'Vector3Node',
'Vector4Node',
'ColorNode',
'Matrix3Node',
'Matrix4Node',
'TextureNode',
'CubeTextureNode',
'ScreenNode',
'ReflectorNode',
'PropertyNode',
'RTTNode',
'UVNode',
'ColorsNode',
'PositionNode',
'NormalNode',
'CameraNode',
'LightNode',
'ReflectNode',
'ScreenUVNode',
'ResolutionNode',
'MathNode',
'OperatorNode',
'CondNode',
'NoiseNode',
'CheckerNode',
'TextureCubeUVNode',
'TextureCubeNode',
'NormalMapNode',
'BumpMapNode',
'BypassNode',
'JoinNode',
'SwitchNode',
'TimerNode',
'VelocityNode',
'UVTransformNode',
'MaxMIPLevelNode',
'SpecularMIPLevelNode',
'ColorSpaceNode',
'SubSlotNode',
'BlurNode',
'ColorAdjustmentNode',
'LuminanceNode',
'RawNode',
'SpriteNode',
'PhongNode',
'StandardNode',
'MeshStandardNode',
'NodeMaterial',
'SpriteNodeMaterial',
'PhongNodeMaterial',
'StandardNodeMaterial',
'MeshStandardNodeMaterial',
'NodePostProcessing'
]
} else {
return []
}
} else {
return [ statement ]
}
} )
.filter( _makeUnique )
.filter( ( value ) => { return !( value.endsWith( '_vert' ) || value.endsWith( '_vertex' ) || value.endsWith( '_frag' ) || value.endsWith( '_fragment' ) ) } )
.filter( ( value ) => { return !exports.includes( value ) } )
}
function _formatImportStatements ( importerFilePath, objectNames ) {
let importStatements = []
let importsMap = {}
objectNames.forEach( ( objectName ) => {
if ( Array.isArray( objectName ) ) {
const exporterFilePath = objectName[ 2 ]
if ( !importsMap[ exporterFilePath ] ) {
importsMap[ exporterFilePath ] = []
}
importsMap[ exporterFilePath ].push( objectName[ 0 ] )
} else {
const exporterFilePath = _exportMap[ objectName ]
if ( !exporterFilePath ) {
console.error( 'Missing export statement for: ' + objectName + ' in ' + importerFilePath + ' this is an edge case that will probably need to be managed manually !!!' )
return
}
// Compute relative path from importer to exporter
const importerDirectoryName = path.dirname( importerFilePath )
const exporterDirectoryName = path.dirname( exporterFilePath )
const exporterBaseName = path.basename( exporterFilePath )
const relativePath = path.relative( importerDirectoryName, exporterDirectoryName )
const firstChar = relativePath[ 0 ]
const notStartWithDot = ( firstChar !== '.' )
const relativeFilePath = ( notStartWithDot ) ? './' + path.join( relativePath, exporterBaseName ) : path.join( relativePath, exporterBaseName )
const relativeFilePathNormalized = relativeFilePath.replace( /\\/g, '/' )
// That why we use path as key and not the inverse
if ( !importsMap[ relativeFilePathNormalized ] ) {
importsMap[ relativeFilePathNormalized ] = []
}
importsMap[ relativeFilePathNormalized ].push( objectName )
}
} )
for ( var importPath in importsMap ) {
let imports = importsMap[ importPath ]
let formatedImports = 'import {'
if ( imports.length === 1 ) {
formatedImports += ' ' + imports[ 0 ] + ' '
} else if ( imports.length > 1 ) {
formatedImports += '\n'
let importedObject = undefined
for ( let i = 0, numberOfImports = imports.length ; i < numberOfImports ; i++ ) {
importedObject = imports[ i ]
if ( i === numberOfImports - 1 ) {
formatedImports += '\t' + importedObject + '\n'
} else {
formatedImports += '\t' + importedObject + ',\n'
}
}
} else {
console.error( 'ERROR: ' + path.basename( importPath ) + ' does not contains imports, fallback to file name export...' )
}
formatedImports += '} from \'' + importPath + '\''
importStatements.push( formatedImports )
}
return importStatements.join( '\n' ).concat( '\n\n' ) // don't forget last feed line
}
/////////////////////////// REPLACEMENTS ////////////////////////////
function _getEs6ReplacementsFor () {
let replacements = []
replacements.push( [ /import\s+(?:(?:({[\w\s,]+})|([\w,*-]+))\s+)+from.+/g, '' ] )
replacements.push( [ /export var/g, 'var' ] )
replacements.push( [ /export function/g, 'function' ] )
replacements.push( [ /export(?:[^s]|)(\s*{(?:[\w\s,])+}\s*)(?:(?:from)?\s?['"][./]+[\w.]+['"];?)?/g, '' ] )
// replacements.push( [ /export([^s]|)\s*{(?:[\w\s,])+}\s*(?!\s?from)/g, '' ] )
// replacements.push( [ /export[^s](?:([\w*{}\n\r\t, ]+)\s*);*/g, '' ] )
return replacements
}
function _getExportsReplacementsFor ( exports ) {
let replacements = []
for ( let i = 0, numberOfExports = exports.length ; i < numberOfExports ; i++ ) {
const exportedObject = exports[ i ]
const regex2 = new RegExp( 'THREE.' + exportedObject + ' =', 'g' )
const replacement2 = 'var ' + exportedObject + ' ='
replacements.push( [ regex2, replacement2 ] )
// Todo: externalize below
// THREE.HDRLoader = THREE.RGBELoader = function ( manager ) {
const regex1 = new RegExp( ' = var ', 'g' )
const replacement1 = ' = '
replacements.push( [ regex1, replacement1 ] )
}
return replacements
}
function _getIifeReplacementsFor ( file ) {
const unspacedFile = file.replace( /\s+/g, '' )
let replacements = []
// Check if this iife is a main englobing function or inner function
const matchIife = unspacedFile.match( /^\(\s*function\s*\(\s*(\w+)?\s*\)\s*\{/g ) || []
if ( matchIife.length > 0 ) {
replacements.push( [ /\(\s*function\s*\(\s*(\w+)?\s*\)\s*\{/, '' ] )
// Check for end type with params or not
const matchParametrizedEndIife = unspacedFile.match( /}\s*\)\s*\(\s*[\w.=\s]*(\|\|\s*\{\})?\s*\);?$/ ) || []
const matchEmptyEndIife = unspacedFile.match( /}\s*\(\s*[\w]*\s*\)\s*\);?$/ ) || []
if ( matchParametrizedEndIife.length > 0 ) {
replacements.push( [ /}\s*\)\s*\(\s*[\w.=\s]*(\|\|\s*\{\})?\s*\);?/, '' ] )
} else if ( matchEmptyEndIife.length > 0 ) {
replacements.push( [ /}\s*\(\s*[\w]*\s*\)\s*\);?/, '' ] )
} else {
throw new Error( 'Unable to match end of IIFE in ' + filePath )
}
}
return replacements
}
function _getThreeReplacementsFor () {
return [
[ /THREE\.Math\./g, '_Math.' ],
[ /THREE\./g, '' ]
]
}
function _getAutoAssignementReplacementsFor () {
return [ [ /var\s?(\w+)\s?=\s?\1;/g, '' ] ]
}
function _getReplacementsFor ( file, exports ) {
let replacements = []
Array.prototype.push.apply( replacements, _getEs6ReplacementsFor() )
Array.prototype.push.apply( replacements, _getExportsReplacementsFor( exports ) )
Array.prototype.push.apply( replacements, _getIifeReplacementsFor( file ) )
Array.prototype.push.apply( replacements, _getThreeReplacementsFor() )
Array.prototype.push.apply( replacements, _getAutoAssignementReplacementsFor() )
return replacements
}
function _formatReplacementStatements ( file, replacements ) {