-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhelper.ts
1140 lines (1068 loc) · 39.8 KB
/
helper.ts
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
// #!/usr/bin/env babel-node
// -*- coding: utf-8 -*-
/** @module helper */
'use strict'
/* !
region header
Copyright Torben Sickert (info["~at~"]torben.website) 16.12.2012
License
-------
This library written by Torben Sickert stand under a creative commons
naming 3.0 unported license.
See https://creativecommons.org/licenses/by/3.0/deed.de
endregion
*/
// region imports
import {
copy,
currentRequire,
Encoding,
escapeRegularExpressions,
extend,
File,
isAnyMatching,
isDirectorySync,
isFileSync,
isPlainObject,
Mapping,
PlainObject,
represent,
walkDirectoryRecursivelySync
} from 'clientnode'
import {existsSync, readFileSync} from 'fs'
import {
basename, dirname, extname, join, normalize, resolve, sep, relative
} from 'path'
import {
BuildConfiguration,
Extensions,
GivenInjection,
GivenInjectionConfiguration,
NormalizedGivenInjection,
PathConfiguration,
PackageConfiguration,
PackageDescriptor,
Replacements,
ResolvedBuildConfiguration,
ResolvedBuildConfigurationItem,
SpecificExtensions
} from './type'
// endregion
// region constants
export const KNOWN_FILE_EXTENSIONS: Array<string> = [
'js', 'ts',
'json',
'css',
'eot',
'gif',
'html',
'ico',
'jpg',
'png',
'ejs',
'svg',
'ttf',
'woff', '.woff2'
]
// endregion
// region functions
// region boolean
/**
* Determines whether given file path is within given list of file locations.
* @param filePath - Path to file to check.
* @param locationsToCheck - Locations to take into account.
* @returns Value "true" if given file path is within one of given locations or
* "false" otherwise.
*/
export const isFilePathInLocation = (
filePath: string, locationsToCheck: Array<string>
): boolean => {
for (const pathToCheck of locationsToCheck)
if (resolve(filePath).startsWith(resolve(pathToCheck)))
return true
return false
}
// endregion
// region string
/**
* Strips loader informations form given module request including loader prefix
* and query parameter.
* @param moduleID - Module request to strip.
* @returns Given module id stripped.
*/
export const stripLoader = (moduleID: string): string => {
const moduleIDWithoutLoader: string = moduleID
.substring(moduleID.lastIndexOf('!') + 1)
.replace(/\.webpack\[.+\/.+\]$/, '')
return moduleIDWithoutLoader.includes('?') ?
moduleIDWithoutLoader.substring(
0, moduleIDWithoutLoader.indexOf('?')
) :
moduleIDWithoutLoader
}
// endregion
// region array
/**
* Converts given list of path to a normalized list with unique values.
* @param paths - File paths.
* @returns The given file path list with normalized unique values.
*/
export const normalizePaths = (paths: Array<string>): Array<string> =>
Array.from(new Set(paths.map((givenPath: string): string => {
givenPath = normalize(givenPath)
if (givenPath.endsWith('/'))
return givenPath.substring(0, givenPath.length - 1)
return givenPath
})))
// endregion
// region file handler
/**
* Applies file path/name placeholder replacements with given bundle associated
* informations.
* @param template - File path to process placeholder in.
* @param scope - Scope to use for processing.
* @returns Processed file path.
*/
export const renderFilePathTemplate = (
template: string, scope: Mapping<number | string> = {}
): string => {
scope = {
'[chunkhash]': '.__dummy__',
'[contenthash]': '.__dummy__',
'[fullhash]': '.__dummy__',
'[id]': '.__dummy__',
'[name]': '.__dummy__',
...scope
}
let filePath: string = template
for (const [placeholderName, value] of Object.entries(scope))
filePath = filePath.replace(
new RegExp(escapeRegularExpressions(placeholderName), 'g'),
String(value)
)
return filePath
}
/**
* Converts given request to a resolved request with given context embedded.
* @param request - Request to determine.
* @param context - Context of given request to resolve relative to.
* @param referencePath - Path to resolve local modules relative to.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of replacements to take into account.
* @param relativeModuleLocations - List of relative directory paths to search
* for modules in.
* @returns A new resolved request.
*/
export const applyContext = (
request: string,
context = './',
referencePath = './',
aliases: Mapping = {},
moduleReplacements: Replacements = {},
relativeModuleLocations: Array<string> = ['node_modules']
): false | string => {
referencePath = resolve(referencePath)
if (request.startsWith('./') && resolve(context) !== referencePath) {
request = resolve(context, request)
for (const modulePath of relativeModuleLocations) {
const pathPrefix: string = resolve(referencePath, modulePath)
if (request.startsWith(pathPrefix)) {
request = request.substring(pathPrefix.length)
if (request.startsWith('/'))
request = request.substring(1)
return applyModuleReplacements(
applyAliases(
request.substring(request.lastIndexOf('!') + 1),
aliases
),
moduleReplacements
)
}
}
if (request.startsWith(referencePath)) {
request = request.substring(referencePath.length)
if (request.startsWith('/'))
request = request.substring(1)
return applyModuleReplacements(
applyAliases(
request.substring(request.lastIndexOf('!') + 1),
aliases
),
moduleReplacements
)
}
}
return request
}
/**
* Check if given request points to an external dependency not maintained by
* current package context.
* @param request - Request to determine.
* @param context - Context of current project.
* @param requestContext - Context of given request to resolve relative to.
* @param normalizedGivenInjection - Mapping of chunk names to modules which
* should be injected.
* @param relativeExternalModuleLocations - Array of paths where external
* modules take place.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of replacements to take into account.
* @param extensions - List of file and module extensions to take into account.
* @param referencePath - Path to resolve local modules relative to.
* @param pathsToIgnore - Paths which marks location to ignore.
* @param relativeModuleLocations - List of relative file path to search for
* modules in.
* @param packageEntryFileNames - List of package entry file names to search
* for. The magic name "__package__" will search for an appreciate entry in a
* "package.json" file.
* @param packageMainPropertyNames - List of package file main property names
* to search for package representing entry module definitions.
* @param packageAliasPropertyNames - List of package file alias property names
* to search for package specific module aliases.
* @param includePattern - Array of regular expressions to explicitly mark as
* external dependency.
* @param excludePattern - Array of regular expressions to explicitly mark as
* internal dependency.
* @param inPlaceNormalLibrary - Indicates whether normal libraries should be
* external or not.
* @param inPlaceDynamicLibrary - Indicates whether requests with integrated
* loader configurations should be marked as external or not.
* @param encoding - Encoding for file names to use during file traversing.
* @returns A new resolved request indicating whether given request is an
* external one.
*/
export const determineExternalRequest = (
request: string,
context = './',
requestContext = './',
normalizedGivenInjection: NormalizedGivenInjection = {},
relativeExternalModuleLocations: Array<string> = ['node_modules'],
aliases: Mapping = {},
moduleReplacements: Replacements = {},
extensions: Extensions = {file: {
external: ['.compiled.js', '.js', '.json'],
internal: KNOWN_FILE_EXTENSIONS.map((suffix: string): string =>
`.${suffix}`
)
}},
referencePath = './',
pathsToIgnore: Array<string> = ['.git'],
relativeModuleLocations: Array<string> = ['node_modules'],
packageEntryFileNames: Array<string> = ['index', 'main'],
packageMainPropertyNames: Array<string> = ['main', 'module'],
packageAliasPropertyNames: Array<string> = [],
includePattern: Array<string | RegExp> = [],
excludePattern: Array<string | RegExp> = [],
inPlaceNormalLibrary = false,
inPlaceDynamicLibrary = true,
encoding: Encoding = 'utf-8'
): null | string => {
context = resolve(context)
requestContext = resolve(requestContext)
referencePath = resolve(referencePath)
// NOTE: We apply alias on externals additionally.
const resolvedRequest: false | string = applyModuleReplacements(
applyAliases(request.substring(request.lastIndexOf('!') + 1), aliases),
moduleReplacements
)
if (
resolvedRequest === false ||
isAnyMatching(resolvedRequest, excludePattern)
)
return null
/*
NOTE: Aliases and module replacements doesn't have to be forwarded
since we pass an already resolved request.
*/
const filePath: null | string = determineModuleFilePath(
resolvedRequest,
{},
{},
{file: extensions.file.external},
context,
requestContext,
pathsToIgnore,
relativeModuleLocations,
packageEntryFileNames,
packageMainPropertyNames,
packageAliasPropertyNames,
encoding
)
/*
NOTE: We mark dependencies as external if there file couldn't be
resolved or are specified to be external explicitly.
*/
if (
!(filePath || inPlaceNormalLibrary) ||
isAnyMatching(resolvedRequest, includePattern)
)
return (
applyContext(
resolvedRequest,
requestContext,
referencePath,
aliases,
moduleReplacements,
relativeModuleLocations
) ||
null
)
for (const chunk of Object.values(normalizedGivenInjection))
for (const moduleID of chunk)
if (determineModuleFilePath(
moduleID,
aliases,
moduleReplacements,
{file: extensions.file.internal},
context,
requestContext,
pathsToIgnore,
relativeModuleLocations,
packageEntryFileNames,
packageMainPropertyNames,
packageAliasPropertyNames,
encoding
) === filePath)
return null
const parts: Array<string> = context.split('/')
const externalModuleLocations: Array<string> = []
while (parts.length > 0) {
for (const relativePath of relativeExternalModuleLocations)
externalModuleLocations.push(
join('/', parts.join('/'), relativePath)
)
parts.splice(-1, 1)
}
/*
NOTE: We mark dependencies as external if they does not contain a
loader in their request and aren't part of the current main package or
have a file extension other than javaScript aware.
*/
if (
!inPlaceNormalLibrary &&
(
extensions.file.external.length === 0 ||
filePath &&
extensions.file.external.includes(extname(filePath)) ||
!filePath && extensions.file.external.includes('')
) &&
!(inPlaceDynamicLibrary && request.includes('!')) &&
(
!filePath && inPlaceDynamicLibrary ||
filePath &&
(
!filePath.startsWith(context) ||
isFilePathInLocation(filePath, externalModuleLocations)
)
)
)
return (
applyContext(
resolvedRequest,
requestContext,
referencePath,
aliases,
moduleReplacements,
relativeModuleLocations
) ||
null
)
return null
}
/**
* Determines asset type of given file.
* @param filePath - Path to file to analyse.
* @param buildConfiguration - Meta informations for available asset types.
* @param paths - List of paths to search if given path doesn't reference a
* file directly.
* @returns Determined file type or "null" of given file couldn't be
* determined.
*/
export const determineAssetType = (
filePath: string,
buildConfiguration: BuildConfiguration,
paths: PathConfiguration
): null | string => {
let result: null | string = null
for (const type in buildConfiguration)
if (
extname(filePath) === `.${buildConfiguration[type].extension}`
) {
result = type
break
}
if (!result)
for (const type of [paths.source, paths.target])
for (const [assetType, assetConfiguration] of Object.entries(
type.asset
))
if (
assetType !== 'base' &&
assetConfiguration &&
filePath.startsWith(assetConfiguration as string)
)
return assetType
return result
}
/**
* Adds a property with a stored array of all matching file paths, which
* matches each build configuration in given entry path and converts given
* build configuration into a sorted array were javaScript files takes
* precedence.
* @param configuration - Given build configurations.
* @param entryPath - Path to analyse nested structure.
* @param pathsToIgnore - Paths which marks location to ignore.
* @param mainFileBasenames - File basenames to sort into the front.
* @returns Converted build configuration.
*/
export const resolveBuildConfigurationFilePaths = (
configuration: BuildConfiguration,
entryPath = './',
pathsToIgnore: Array<string> = ['.git'],
mainFileBasenames: Array<string> = ['index', 'main']
): ResolvedBuildConfiguration => {
const buildConfiguration: ResolvedBuildConfiguration = []
for (const value of Object.values(configuration)) {
const newItem: ResolvedBuildConfigurationItem = extend<
ResolvedBuildConfigurationItem
>(true, {filePaths: []}, value)
for (const file of walkDirectoryRecursivelySync(
entryPath,
(file: File): false | undefined => {
if (isFilePathInLocation(file.path, pathsToIgnore))
return false
}
))
if (
file.stats?.isFile() &&
file.path.endsWith(`.${newItem.extension}`) &&
!(
newItem.ignoredExtension &&
file.path.endsWith(`.${newItem.ignoredExtension}`)
) &&
!(new RegExp(newItem.filePathPattern)).test(file.path)
)
newItem.filePaths.push(file.path)
newItem.filePaths.sort((
firstFilePath: string, secondFilePath: string
): number => {
if (mainFileBasenames.includes(basename(
firstFilePath, extname(firstFilePath)
))) {
if (mainFileBasenames.includes(basename(
secondFilePath, extname(secondFilePath)
)))
return 0
} else if (mainFileBasenames.includes(basename(
secondFilePath, extname(secondFilePath)
)))
return 1
return 0
})
buildConfiguration.push(newItem)
}
return buildConfiguration.sort((
first: ResolvedBuildConfigurationItem,
second: ResolvedBuildConfigurationItem
): number => {
if (first.outputExtension !== second.outputExtension) {
if (first.outputExtension === 'js')
return -1
if (second.outputExtension === 'js')
return 1
return first.outputExtension < second.outputExtension ? -1 : 1
}
return 0
})
}
/**
* Determines all file and directory paths related to given internal modules as
* array.
* @param givenInjection - List of module ids or module file paths.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of module replacements to take into
* account.
* @param extensions - List of file and module extensions to take into account.
* @param context - File path to resolve relative to.
* @param referencePath - Path to search for local modules.
* @param pathsToIgnore - Paths which marks location to ignore.
* @param relativeModuleLocations - List of relative file path to search for
* modules in.
* @param packageEntryFileNames - List of package entry file names to search
* for. The magic name "__package__" will search for an appreciate entry in a
* "package.json" file.
* @param packageMainPropertyNames - List of package file main property names
* to search for package representing entry module definitions.
* @param packageAliasPropertyNames - List of package file alias property names
* to search for package specific module aliases.
* @param encoding - File name encoding to use during file traversing.
* @returns Object with a file path and directory path key mapping to
* corresponding list of paths.
*/
export const determineModuleLocations = (
givenInjection: GivenInjection,
aliases: Mapping = {},
moduleReplacements: Replacements = {},
extensions: SpecificExtensions = {
file: KNOWN_FILE_EXTENSIONS.map((suffix: string): string =>
`.${suffix}`
)
},
context = './',
referencePath = '',
pathsToIgnore: Array<string> = ['.git'],
relativeModuleLocations: Array<string> = ['node_modules'],
packageEntryFileNames: Array<string> = [
'__package__', '', 'index', 'main'
],
packageMainPropertyNames: Array<string> = ['main', 'module'],
packageAliasPropertyNames: Array<string> = [],
encoding: Encoding = 'utf-8'
): {
directoryPaths: Array<string>
filePaths: Array<string>
} => {
const filePaths: Array<string> = []
const directoryPaths: Array<string> = []
const normalizedGivenInjection: NormalizedGivenInjection =
resolveModulesInFolders(
normalizeGivenInjection(givenInjection),
aliases,
moduleReplacements,
context,
referencePath,
pathsToIgnore
)
for (const chunk of Object.values(normalizedGivenInjection))
for (const moduleID of chunk) {
const filePath: null | string = determineModuleFilePath(
moduleID,
aliases,
moduleReplacements,
extensions,
context,
referencePath,
pathsToIgnore,
relativeModuleLocations,
packageEntryFileNames,
packageMainPropertyNames,
packageAliasPropertyNames,
encoding
)
if (filePath) {
filePaths.push(filePath)
const directoryPath: string = dirname(filePath)
if (!directoryPaths.includes(directoryPath))
directoryPaths.push(directoryPath)
}
}
return {filePaths, directoryPaths}
}
/**
* Determines a list of concrete file paths for given module id pointing to a
* folder which isn't a package.
* @param normalizedGivenInjection - Injection data structure of modules with
* folder references to resolve.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of replacements to take into account.
* @param context - File path to determine relative to.
* @param referencePath - Path to resolve local modules relative to.
* @param pathsToIgnore - Paths which marks location to ignore.
* @returns Given injections with resolved folder pointing modules.
*/
export const resolveModulesInFolders = (
normalizedGivenInjection: NormalizedGivenInjection,
aliases: Mapping = {},
moduleReplacements: Replacements = {},
context = './',
referencePath = '',
pathsToIgnore: Array<string> = ['.git']
): NormalizedGivenInjection => {
if (referencePath.startsWith('/'))
referencePath = relative(context, referencePath)
const result = copy(normalizedGivenInjection)
for (const chunk of Object.values(result)) {
let index = 0
for (const moduleID of copy(chunk)) {
const resolvedModuleID: false | string = applyModuleReplacements(
applyAliases(stripLoader(moduleID), aliases),
moduleReplacements
)
if (resolvedModuleID === false) {
chunk.splice(index, 1)
continue
}
const resolvedPath: string =
resolve(referencePath, resolvedModuleID)
if (isDirectorySync(resolvedPath)) {
chunk.splice(index, 1)
for (const file of walkDirectoryRecursivelySync(
resolvedPath,
(file: File): false | undefined => {
if (isFilePathInLocation(file.path, pathsToIgnore))
return false
}
))
if (file.stats?.isFile())
chunk.push(
'./' +
relative(context, resolve(resolvedPath, file.path))
)
} else if (
resolvedModuleID.startsWith('./') &&
!resolvedModuleID.startsWith(
`./${relative(context, referencePath)}`
)
)
chunk[index] = `./${relative(context, resolvedPath)}`
index += 1
}
}
return result
}
/**
* Every injection definition type can be represented as plain object (mapping
* from chunk name to array of module ids). This method converts each
* representation into the normalized plain object notation.
* @param givenInjection - Given entry injection to normalize.
* @returns Normalized representation of given entry injection.
*/
export const normalizeGivenInjection = (
givenInjection: GivenInjection
): NormalizedGivenInjection => {
let result: NormalizedGivenInjection = {}
if (Array.isArray(givenInjection))
result = {index: givenInjection}
else if (typeof givenInjection === 'string')
result = {index: [givenInjection]}
else if (isPlainObject(givenInjection)) {
let hasContent = false
const chunkNamesToDelete: Array<string> = []
for (const [chunkName, chunk] of Object.entries(givenInjection))
if (Array.isArray(chunk))
if (chunk.length > 0) {
hasContent = true
result[chunkName] = chunk
} else
chunkNamesToDelete.push(chunkName)
else {
hasContent = true
result[chunkName] = [chunk]
}
if (hasContent)
for (const chunkName of chunkNamesToDelete)
delete result[chunkName]
else
result = {index: []}
}
return result
}
/**
* Determines all concrete file paths for given injection which are marked with
* the "__auto__" indicator.
* @param givenInjection - Given entry and external injection to take into
* account.
* @param buildConfigurations - Resolved build configuration.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of replacements to take into account.
* @param extensions - List of file and module extensions to take into account.
* @param context - File path to use as starting point.
* @param referencePath - Reference path from where local files should be
* resolved.
* @param pathsToIgnore - Paths which marks location to ignore.
* @returns Given injection with resolved marked indicators.
*/
export const resolveAutoInjection = <T extends GivenInjectionConfiguration>(
givenInjection: T,
buildConfigurations: ResolvedBuildConfiguration,
aliases: Mapping = {},
moduleReplacements: Replacements = {},
extensions: Extensions = {file: {
external: ['compiled.js', '.js', '.json'],
internal: KNOWN_FILE_EXTENSIONS.map((suffix: string): string =>
`.${suffix}`
)
}},
context = './',
referencePath = '',
pathsToIgnore: Array<string> = ['.git']
): T => {
const injection: T = copy(givenInjection)
const moduleFilePathsToExclude: Array<string> = determineModuleLocations(
givenInjection.autoExclude.paths,
aliases,
moduleReplacements,
{file: extensions.file.internal},
context,
referencePath,
pathsToIgnore
).filePaths
for (const name of ['entry', 'external'] as const) {
const injectionType: GivenInjection = injection[name]
if (isPlainObject(injectionType)) {
for (let [chunkName, chunk] of Object.entries(injectionType))
if (chunk === '__auto__') {
chunk = injectionType[chunkName] = []
const modules: Mapping = getAutoInjection(
buildConfigurations,
moduleFilePathsToExclude,
givenInjection.autoExclude.pattern,
referencePath
)
for (const subChunk of Object.values(modules))
chunk.push(subChunk)
/*
Reverse array to let javaScript and main files be
the last ones to export them rather.
*/
chunk.reverse()
}
} else if (injectionType === '__auto__')
(injection[name as keyof GivenInjectionConfiguration] as Mapping) =
getAutoInjection(
buildConfigurations,
moduleFilePathsToExclude,
givenInjection.autoExclude.pattern,
referencePath
)
}
return injection
}
/**
* Determines all module file paths.
* @param buildConfigurations - Resolved build configuration.
* @param moduleFilePathsToExclude - A list of modules file paths to exclude
* (specified by path or id).
* @param moduleFilePathPatternToExclude - A list of modules file paths pattern
* to exclude (specified by path or id).
* @param context - File path to use as starting point.
* @returns All determined module file paths.
*/
export const getAutoInjection = (
buildConfigurations: ResolvedBuildConfiguration,
moduleFilePathsToExclude: Array<string>,
moduleFilePathPatternToExclude: Array<RegExp | string>,
context: string
): Mapping => {
const result: Mapping = {}
const injectedModuleIDs: Mapping<Array<string>> = {}
for (const buildConfiguration of buildConfigurations) {
if (!Object.prototype.hasOwnProperty.call(
injectedModuleIDs, buildConfiguration.outputExtension
))
injectedModuleIDs[buildConfiguration.outputExtension] = []
for (const moduleFilePath of buildConfiguration.filePaths)
if (!(
moduleFilePathsToExclude.includes(moduleFilePath) ||
isAnyMatching(
moduleFilePath.substring(context.length),
moduleFilePathPatternToExclude
)
)) {
const relativeModuleFilePath =
`./${relative(context, moduleFilePath)}`
const directoryPath: string =
dirname(relativeModuleFilePath)
const baseName: string = basename(
relativeModuleFilePath,
`.${buildConfiguration.extension}`
)
let moduleID: string = baseName
if (directoryPath !== '.')
moduleID = join(directoryPath, baseName)
/*
Ensure that each output type has only one source
representation.
*/
if (!injectedModuleIDs[
buildConfiguration.outputExtension
].includes(moduleID)) {
/*
Ensure that same module ids and different output types
can be distinguished by their extension
(JavaScript-Modules remains without extension since
they will be handled first because the build
configurations are expected to be sorted in this
context).
*/
if (Object.prototype.hasOwnProperty.call(result, moduleID))
result[relativeModuleFilePath] =
relativeModuleFilePath
else
result[moduleID] = relativeModuleFilePath
injectedModuleIDs[buildConfiguration.outputExtension]
.push(moduleID)
}
}
}
return result
}
// TODO test
/**
* Determines a resolved module file path in given package path.
* @param packagePath - Path to package to resolve in.
* @param packageMainPropertyNames - List of package file main property names
* to search for package representing entry module definitions.
* @param packageAliasPropertyNames - List of package file alias property names
* to search for package specific module aliases.
* @param encoding - Encoding to use for file names during file traversing.
* @returns Path if found and / or additional package aliases to consider.
*/
export const determineModuleFilePathInPackage = (
packagePath: string,
packageMainPropertyNames: Array<string> = ['main'],
packageAliasPropertyNames: Array<string> = [],
encoding: Encoding = 'utf-8'
): {
fileName: null | string
packageAliases: Mapping | null
} => {
const result: {
fileName: null | string
packageAliases: Mapping | null
} = {
fileName: null,
packageAliases: null
}
if (isDirectorySync(packagePath)) {
const pathToPackageJSON: string =
resolve(packagePath, 'package.json')
if (isFileSync(pathToPackageJSON)) {
let localConfiguration: PlainObject = {}
try {
localConfiguration = JSON.parse(
readFileSync(pathToPackageJSON, {encoding})
) as PlainObject
} catch (error) {
console.warn(
`Package configuration file "${pathToPackageJSON}" ` +
`could not parsed: ${represent(error)}`
)
}
for (const propertyName of packageMainPropertyNames)
if (
Object.prototype.hasOwnProperty.call(
localConfiguration, propertyName
) &&
typeof localConfiguration[propertyName] === 'string' &&
localConfiguration[propertyName]
) {
result.fileName = localConfiguration[propertyName]
break
}
for (const propertyName of packageAliasPropertyNames)
if (
Object.prototype.hasOwnProperty.call(
localConfiguration, propertyName
) &&
isPlainObject(localConfiguration[propertyName])
) {
result.packageAliases = localConfiguration[
propertyName
] as Mapping
break
}
}
}
return result
}
/**
* Determines a concrete file path for given module id.
* @param moduleID - Module id to determine.
* @param aliases - Mapping of aliases to take into account.
* @param moduleReplacements - Mapping of replacements to take into account.
* @param extensions - List of file and module extensions to take into account.
* @param context - File path to determine relative to.
* @param referencePath - Path to resolve local modules relative to.
* @param pathsToIgnore - Paths which marks location to ignore.
* @param relativeModuleLocations - List of relative file path to search for
* modules in.
* @param packageEntryFileNames - List of package entry file names to search
* for. The magic name "__package__" will search for an appreciate entry in a
* "package.json" file.
* @param packageMainPropertyNames - List of package file main property names
* to search for package representing entry module definitions.
* @param packageAliasPropertyNames - List of package file alias property names
* to search for package specific module aliases.
* @param encoding - Encoding to use for file names during file traversing.
* @returns File path or given module id if determinations has failed or wasn't
* necessary.
*/
export const determineModuleFilePath = (
moduleID: false | string,
aliases: Mapping = {},
moduleReplacements: Replacements = {},
extensions: SpecificExtensions = {
file: KNOWN_FILE_EXTENSIONS.map((suffix: string): string =>
`.${suffix}`
)
},
context = './',
referencePath = '',
pathsToIgnore: Array<string> = ['.git'],
relativeModuleLocations: Array<string> = ['node_modules'],
packageEntryFileNames: Array<string> = ['index'],
packageMainPropertyNames: Array<string> = ['main'],
packageAliasPropertyNames: Array<string> = [],
encoding: Encoding = 'utf-8'
): null | string => {
if (!moduleID)
return null
moduleID = applyModuleReplacements(
applyAliases(stripLoader(moduleID), aliases), moduleReplacements
)
if (!moduleID)
return null
let moduleFilePath: string = moduleID
if (moduleFilePath.startsWith('./'))
moduleFilePath = join(referencePath, moduleFilePath)
const moduleLocations = [referencePath].concat(
relativeModuleLocations.map((filePath: string): string =>
resolve(context, filePath)
)
)
const parts = context.split('/')
parts.splice(-1, 1)
while (parts.length > 0) {
for (const relativePath of relativeModuleLocations)
moduleLocations.push(join('/', parts.join('/'), relativePath))
parts.splice(-1, 1)
}
for (const moduleLocation of [referencePath].concat(moduleLocations))
for (let fileName of ['', '__package__'].concat(
packageEntryFileNames
))
for (const fileExtension of [''].concat(extensions.file)) {
let currentModuleFilePath: string
if (moduleFilePath.startsWith('/'))
currentModuleFilePath = resolve(moduleFilePath)
else
currentModuleFilePath =
resolve(moduleLocation, moduleFilePath)
let packageAliases: Mapping = {}
if (fileName === '__package__') {