Repository navigation
Expand file tree
/
Copy pathConcatenatedModule.js
More file actions
3489 lines (3331 loc) · 113 KB
/
Copy pathConcatenatedModule.js
File metadata and controls
3489 lines (3331 loc) · 113 KB
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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncBailHook } = require("tapable");
const {
CachedSource,
ConcatSource,
ReplaceSource
} = require("webpack-sources");
const { DEFAULTS } = require("../config/defaults");
const { ImportPhaseUtils } = require("../dependencies/core/ImportPhase");
const Dependency = require("../graph/Dependency");
const { UsageState } = require("../graph/ExportsInfo");
const isDependencyKind = require("../graph/isDependencyKind");
const JavascriptParser = require("../javascript/JavascriptParser");
const analyzeScope = require("../javascript/ScopeAnalyzer");
const Module = require("../module/Module");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../module/ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../module/ModuleTypeConstants");
const {
getDeferredCycleModuleIds,
getDeferredCycleModules,
getKnownExportNames,
getMakeDeferredNamespaceModeFromExportsType,
getOptimizedDeferredModule
} = require("../runtime/MakeDeferredNamespaceObjectRuntime");
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
const Template = require("../template/Template");
const { equals } = require("../util/ArrayHelpers");
const LazySet = require("../util/LazySet");
const { getBuildDiagnostics } = require("../util/buildDiagnostics");
const {
compareModulesByFullName,
concatComparators
} = require("../util/comparators");
const {
RESERVED_NAMES,
addScopeSymbols,
findNewName,
getAllReferences,
getUsedNamesInScopeInfo,
isCommonJsConcatenationEnabled
} = require("../util/concatenate");
const createHash = require("../util/createHash");
const createHooksRegistry = require("../util/createHooksRegistry");
const { makePathsRelative } = require("../util/identifier");
const makeSerializable = require("../util/makeSerializable");
const { propertyAccess, propertyName } = require("../util/property");
const {
filterRuntime,
intersectRuntime,
mergeRuntimeCondition,
mergeRuntimeConditionNonFalse,
runtimeConditionToString,
subtractRuntimeCondition
} = require("../util/runtime");
const ConcatenationScope = require("./ConcatenationScope");
const { isInlinedUsedName } = require("./InlineExports");
/** @import { Source } from "webpack-sources" */
/**
* @import {
* WebpackOptionsNormalizedWithDefaults as WebpackOptions
* } from "../config/defaults"
*/
/** @import ChunkGraph from "../graph/ChunkGraph" */
/** @import CodeGenerationResults from "../module/CodeGenerationResults" */
/** @import Compilation, { FileSystemDependencies } from "../Compilation" */
/** @import { UpdateHashContext } from "../graph/Dependency" */
/** @import ESMImportDependency from "../dependencies/esm/ESMImportDependency" */
/** @import DependencyTemplates from "../template/DependencyTemplates" */
/** @import { ExportInfo } from "../graph/ExportsInfo" */
/**
* @import {
* BuildCallback,
* BuildInfo,
* BuildMeta,
* ExportsType,
* CodeGenerationContext,
* CodeGenerationResultData,
* CodeGenerationResult,
* LibIdentOptions,
* LibIdent,
* NameForCondition,
* ReadOnlyRuntimeRequirements,
* RuntimeRequirements,
* SourceTypes,
* ModuleKinds
* } from "../module/Module"
*/
/** @import ModuleGraph from "../graph/ModuleGraph" */
/**
* @import ModuleGraphConnection, {
* ConnectionState
* } from "../graph/ModuleGraphConnection"
*/
/** @import RequestShortener from "../util/RequestShortener" */
/** @import { ResolverWithOptions } from "../resolve/ResolverFactory" */
/** @import RuntimeTemplate from "../template/RuntimeTemplate" */
/**
* @import {
* JavascriptModuleBuildInfo,
* JavascriptModuleBuildMeta
* } from "../javascript/JavascriptModule"
*/
/**
* @import {
* ChunkRenderContext,
* Scope,
* Reference
* } from "../javascript/JavascriptModulesPlugin"
*/
/** @typedef {import("../javascript/ScopeAnalyzer").ScopeIdentifier} ScopeIdentifier */
/**
* @import {
* ObjectDeserializerContext
* } from "../serialization/ObjectMiddleware"
*/
/** @import Hash, { HashFunction } from "../util/Hash" */
/** @import { UsedNames, UsedNamesInScopeInfo } from "../util/concatenate" */
/** @import { InputFileSystem } from "../fs/fs" */
/** @import { AssociatedObjectForCache } from "../util/identifier" */
/** @import { RuntimeSpec } from "../util/runtime" */
/**
* @template T
* @typedef {import("../template/InitFragment")<T>} InitFragment
*/
/**
* @template T
* @typedef {import("../util/comparators").Comparator<T>} Comparator
*/
const IDENTIFIER_SCAN_REGEXP = /[$A-Za-z_][\w$]*/g;
const IDENTIFIER_SCAN_WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
/**
* Finds every identifier a generated source could resolve against the enclosing
* concatenation scope. Property names are skipped; string and comment contents
* are not, which only over-reserves.
* @param {Source} source generated source
* @returns {ReadonlySet<string>} identifier names
*/
const findIdentifiers = (source) => {
const code = source.source().toString();
/** @type {Set<string>} */
const result = new Set();
IDENTIFIER_SCAN_REGEXP.lastIndex = 0;
let match = IDENTIFIER_SCAN_REGEXP.exec(code);
while (match !== null) {
let i = match.index - 1;
while (i >= 0 && IDENTIFIER_SCAN_WHITESPACE.has(code[i])) i--;
// `a.b` can't bind to the outer scope, but the `b` of `...b` can
if (!(i >= 0 && code[i] === "." && code[i - 1] !== ".")) {
result.add(match[0]);
}
match = IDENTIFIER_SCAN_REGEXP.exec(code);
}
return result;
};
/**
* Finds the module reference identifiers not followed by the "._" that
* `createModuleReference` appends, so linking replaces only their name.
* @param {string} code generated code the references were parsed from
* @param {Reference[]} references free references of the code
* @returns {Set<number> | undefined} where each such identifier starts, undefined when there is none
*/
const findBareReferenceStarts = (code, references) => {
/** @type {Set<number> | undefined} */
let result;
for (const reference of references) {
const { name, start, end } = reference.identifier;
if (!ConcatenationScope.isModuleReference(name)) continue;
if (code.startsWith("._", end)) continue;
if (result === undefined) result = new Set();
result.add(start);
}
return result;
};
/**
* Returns the inclusive end of the text a module reference identifier replaces:
* the identifier plus the appended "._", or the identifier alone without it.
* @param {ConcatenatedModuleInfo} info module info holding the identifier
* @param {ScopeIdentifier} identifier the identifier
* @returns {number} inclusive end of the replaced text
*/
const replacedReferenceEnd = (info, identifier) =>
info.bareReferenceStarts !== undefined &&
info.bareReferenceStarts.has(identifier.start)
? identifier.end - 1
: identifier.end + 1;
/** @typedef {RawBinding | SymbolBinding} Binding */
/** @typedef {string[]} ExportName */
/**
* @typedef {object} RawBinding
* @property {ModuleInfo} info
* @property {string} rawName
* @property {string=} comment
* @property {ExportName} ids
* @property {ExportName} exportName
* @property {boolean=} accessorCall the raw name is the wrapper accessor call itself, so it binds looser than the identifier it replaces
*/
/**
* @typedef {object} SymbolBinding
* @property {ConcatenatedModuleInfo} info
* @property {string} name
* @property {string=} comment
* @property {ExportName} ids
* @property {ExportName} exportName
*/
/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */
/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo} ModuleInfoOrReference */
/** @typedef {Map<string, string>} ExportMap */
/**
* @typedef {object} ConcatenatedModuleInfo
* @property {"concatenated"} type
* @property {boolean} wrapped the body renders inside the lazy CJS wrapper with real module/exports instead of being scope-hoisted into the shared scope
* @property {boolean} eager a wrapped body reached by an eager import edge, so its accessor is called at its own slot in evaluation order
* @property {Module} module
* @property {number} index
* @property {Set<number> | undefined} shorthandIdentifierStarts where each shorthand property's identifier starts
* @property {Set<number> | undefined} bareReferenceStarts where each module reference identifier that lacks the appended "._" starts
* @property {Source | undefined} internalSource
* @property {ReplaceSource | undefined} source
* @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
* @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements
* @property {Scope | undefined} globalScope
* @property {Reference[] | undefined} unresolvedReferences the module's free references
* @property {Scope | undefined} moduleScope
* @property {Map<string, string>} internalNames
* @property {ExportMap | undefined} exportMap
* @property {ExportMap | undefined} rawExportMap
* @property {string=} namespaceExportSymbol
* @property {string | undefined} namespaceFnName name of the lazy wrapper accessor function (calling it evaluates the module and returns its exports)
* @property {string | undefined} namespaceObjectName
* @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
* @property {ConcatenationScope | undefined} concatenationScope
* @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace
* @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace
* @property {boolean} interopNamespaceObject2Used "default-only" namespace
* @property {string | undefined} interopNamespaceObject2Name "default-only" namespace
* @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule"
* @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule"
* @property {ExportsType=} exportsTypeStrict memoized getExportsType(strict=true)
* @property {ExportsType=} exportsTypeNonStrict memoized getExportsType(strict=false)
*/
/**
* @typedef {object} ExternalModuleInfo
* @property {"external"} type
* @property {boolean} wrapped the module's `require()` call is deferred behind an accessor instead of running at its own slot; unlike a wrapped concatenated member there is no body and no CJS wrapper, so any external may be wrapped
* @property {boolean} eager a wrapped module reached by an eager import edge, so its accessor is called at its own slot in evaluation order
* @property {Module} module
* @property {RuntimeSpec | boolean} runtimeCondition
* @property {NonDeferAccess} nonDeferAccess
* @property {number} index
* @property {string | undefined} name module.exports / harmony namespace object
* @property {string | undefined} namespaceFnName lazy module accessor
* @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
* @property {string | undefined} deferredName deferred module.exports / harmony namespace object
* @property {boolean} deferred the module is deferred at least once
* @property {boolean} deferredNamespaceObjectUsed deferred namespace object that being used in a not-analyzable way so it must be materialized
* @property {string | undefined} deferredNamespaceObjectName deferred namespace object that being used in a not-analyzable way so it must be materialized
* @property {boolean} specNamespaceObjectUsed an import reads the spec namespace object the module hands out
* @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace
* @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace
* @property {boolean} interopNamespaceObject2Used "default-only" namespace
* @property {string | undefined} interopNamespaceObject2Name "default-only" namespace
* @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule"
* @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule"
* @property {ExportsType=} exportsTypeStrict memoized getExportsType(strict=true)
* @property {ExportsType=} exportsTypeNonStrict memoized getExportsType(strict=false)
*/
/**
* @typedef {object} ReferenceToModuleInfo
* @property {"reference"} type
* @property {RuntimeSpec | boolean} runtimeCondition
* @property {NonDeferAccess} nonDeferAccess
* @property {ModuleInfo} target
*/
/**
* @template T
* @template {keyof T} K
* @param {K} property property
* @param {(a: T[K], b: T[K]) => 0 | 1 | -1} comparator comparator
* @returns {Comparator<T>} comparator
*/
const createComparator = (property, comparator) => (a, b) =>
comparator(a[property], b[property]);
/**
* @param {number} a a
* @param {number} b b
* @returns {0 | 1 | -1} result
*/
const compareNumbers = (a, b) => {
if (Number.isNaN(a)) {
if (!Number.isNaN(b)) {
return 1;
}
} else {
if (Number.isNaN(b)) {
return -1;
}
if (a !== b) {
return a < b ? -1 : 1;
}
}
return 0;
};
/** @typedef {{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number | undefined, dependencyIndex: number, defer?: boolean }} OrderedReference */
/** @type {Comparator<OrderedReference>} */
const bySourceOrder = createComparator("sourceOrder", compareNumbers);
/** @type {Comparator<OrderedReference>} */
const byRangeStart = createComparator(
"rangeStart",
// a reference without a range compares as equal to any other
/** @type {(a: number | undefined, b: number | undefined) => 0 | 1 | -1} */ (
compareNumbers
)
);
/** @type {Comparator<OrderedReference>} */
const byDependencyIndex = createComparator("dependencyIndex", compareNumbers);
/**
* @param {Iterable<string>} iterable iterable object
* @returns {string} joined iterable object
*/
const joinIterableWithComma = (iterable) => {
// This is more performant than Array.from().join(", ")
// as it doesn't create an array
let str = "";
let first = true;
for (const item of iterable) {
if (first) {
first = false;
} else {
str += ", ";
}
str += item;
}
return str;
};
/** @typedef {boolean} NonDeferAccess */
/**
* @param {NonDeferAccess} a a
* @param {NonDeferAccess} b b
* @returns {NonDeferAccess} merged
*/
const mergeNonDeferAccess = (a, b) => a || b;
/**
* @param {NonDeferAccess} a first
* @param {NonDeferAccess} b second
* @returns {NonDeferAccess} first - second
*/
const subtractNonDeferAccess = (a, b) => a && !b;
/**
* @typedef {object} ConcatenationEntry
* @property {"concatenated" | "external"} type
* @property {boolean} wrapped evaluation is deferred behind an accessor: a "concatenated" entry renders its body inside the lazy CJS wrapper instead of being scope-hoisted, an "external" entry only defers its `require()` call
* @property {Module} module
* @property {RuntimeSpec | boolean} runtimeCondition
* @property {NonDeferAccess} nonDeferAccess
*/
/**
* Whether a member runs inside the lazy CJS wrapper or is scope-hoisted. Only a
* NormalModule can carry a CJS body; an ESM member starts out hoisted and is
* downgraded by {@link ConcatenatedModule._createConcatenationList}.
* @param {Module} module a module taking part in the concatenation
* @returns {boolean} true, when the module renders wrapped
*/
const needWrapped = (module) =>
module.is("normal") &&
module.type.startsWith("javascript/") &&
module.buildMeta !== undefined &&
module.buildMeta.exportsType !== "namespace";
/**
* Whether a hoisted member can move into the lazy wrapper instead.
* @param {ConcatenationEntry} entry a member of the concatenation
* @returns {boolean} true, when it may be wrapped
*/
const entryCanBeWrapped = (entry) => {
// TODO in the next major release: call it directly. A module built against an older webpack
// extends a base class without it, so fall back to the check this replaced.
if (typeof entry.module.canBeWrappedInConcatenation !== "function") {
return !entry.module.type.startsWith("css/");
}
return entry.module.canBeWrappedInConcatenation();
};
/** @typedef {Set<ConcatenatedModuleInfo>} NeededNamespaceObjects */
/** @typedef {Map<Module, ModuleInfo>} ModuleToInfoMap */
/**
* getExportsType memoized on the info, which lives for one codeGeneration.
* The "dynamic" case walks the module graph, and is queried once per reference.
* @param {ModuleGraph} moduleGraph the module graph
* @param {ModuleInfo} info module info
* @param {boolean | undefined} strict strict harmony module (undefined is treated as non-strict)
* @returns {ExportsType} the exports type
*/
const getExportsType = (moduleGraph, info, strict) => {
if (strict) {
if (info.exportsTypeStrict === undefined) {
info.exportsTypeStrict = info.module.getExportsType(moduleGraph, true);
}
return info.exportsTypeStrict;
}
if (info.exportsTypeNonStrict === undefined) {
info.exportsTypeNonStrict = info.module.getExportsType(moduleGraph, false);
}
return info.exportsTypeNonStrict;
};
/**
* @param {ExternalModuleInfo} info module info
* @returns {string} module exports expression
*/
const getExternalModuleExpr = (info) =>
info.wrapped
? `${
/** @type {NonNullable<ExternalModuleInfo["namespaceFnName"]>} */
(info.namespaceFnName)
}()`
: /** @type {NonNullable<ExternalModuleInfo["name"]>} */ (info.name);
/**
* A wrapped module's interop object is declared as a lazy accessor, so reading
* it is a call. See `declareInterop`.
* @param {ModuleInfo} info module info
* @param {string | undefined} interopName interop variable name
* @returns {string} interop object expression
*/
const getInteropExpr = (info, interopName) =>
info.wrapped ? `${interopName}()` : /** @type {string} */ (interopName);
/**
* Expression for an export that is not used. A hoisted body runs at its own
* slot, but a wrapped one only runs when its accessor is called, so dropping
* the reference would drop the module's side effects with it.
* @param {ConcatenatedModuleInfo} info module info
* @param {boolean | undefined} asiSafe asiSafe
* @returns {string} expression evaluating to undefined
*/
const getUnusedExportExpr = (info, asiSafe) =>
info.wrapped
? `${asiSafe === false ? ";" : ""}/* unused export */ (${info.namespaceObjectName}, undefined)`
: "undefined /* unused export */";
/**
* Parenthesizes a reference that may already carry an ASI guard of its own,
* keeping that guard outside the new parentheses — nested it would not parse.
* @param {string} reference the reference
* @param {boolean | undefined} asiSafe asiSafe
* @returns {string} the parenthesized reference
*/
const parenthesizeReference = (reference, asiSafe) =>
asiSafe === false
? `;(${reference.startsWith(";") ? reference.slice(1) : reference})`
: `(${reference})`;
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {ModuleInfo} info module info
* @param {ExportName} exportName exportName
* @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
* @param {RuntimeSpec} runtime for which runtime
* @param {RequestShortener} requestShortener the request shortener
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {NeededNamespaceObjects} neededNamespaceObjects modules for which a namespace object should be generated
* @param {boolean} asCall asCall
* @param {boolean} depDeferred the dependency is deferred
* @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
* @param {boolean | undefined} asiSafe asiSafe
* @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
* @param {Set<InstanceType<ExportInfo>>=} alreadyVisited alreadyVisited
* @returns {Binding} the final variable
*/
const getFinalBinding = (
moduleGraph,
info,
exportName,
moduleToInfoMap,
runtime,
requestShortener,
runtimeTemplate,
neededNamespaceObjects,
asCall,
depDeferred,
strictHarmonyModule,
asiSafe,
moduleExportsAccess,
alreadyVisited
) => {
const exportsType = getExportsType(moduleGraph, info, strictHarmonyModule);
const moduleDeferred =
info.type === "external" &&
info.deferred &&
!(/** @type {BuildMeta} */ (info.module.buildMeta).async);
const deferred = depDeferred && moduleDeferred;
if (moduleExportsAccess && info.type === "concatenated") {
neededNamespaceObjects.add(info);
// ids arrive as declared names and the rendered exports object is keyed by
// used ones, so resolve here — the same way `case "external"` does below.
// Resolving in the caller instead would mangle twice.
const usedName =
exportName.length === 0
? exportName
: moduleGraph
.getExportsInfo(info.module)
.getUsedName(exportName, runtime);
if (!usedName) {
return {
info,
rawName: getUnusedExportExpr(info, asiSafe),
ids: [],
exportName
};
}
return {
info,
rawName:
/** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
(info.namespaceObjectName),
ids: /** @type {ExportName} */ (usedName),
exportName,
accessorCall: info.wrapped
};
}
if (moduleExportsAccess) {
// Skip ESM interop when require() targets a module outside the concatenation
} else if (exportName.length === 0) {
switch (exportsType) {
case "default-only":
if (deferred) info.deferredNamespaceObjectUsed = true;
else info.interopNamespaceObject2Used = true;
return {
info,
rawName: deferred
? /** @type {string} */ (info.deferredNamespaceObjectName)
: getInteropExpr(info, info.interopNamespaceObject2Name),
ids: exportName,
exportName,
accessorCall: !deferred && info.wrapped
};
case "default-with-named":
if (deferred) info.deferredNamespaceObjectUsed = true;
else info.interopNamespaceObjectUsed = true;
return {
info,
rawName: deferred
? /** @type {string} */ (info.deferredNamespaceObjectName)
: getInteropExpr(info, info.interopNamespaceObjectName),
ids: exportName,
exportName,
accessorCall: !deferred && info.wrapped
};
case "namespace":
case "dynamic":
break;
default:
throw new Error(`Unexpected exportsType ${exportsType}`);
}
} else {
switch (exportsType) {
case "namespace":
break;
case "default-with-named":
switch (exportName[0]) {
case "default":
exportName = exportName.slice(1);
if (deferred) {
// WHY: `ns.default` for a deferred default-with-named external
// module must read through the optimized `.a` getter, which
// evaluates the
// module lazily and returns its exports, rather than through the
// proxy namespace — otherwise `typeof ns.default` and
// `ns.default instanceof X` observe the proxy, not the actual
// default.
return {
info,
rawName: `${info.deferredName}.a`,
ids: exportName,
exportName
};
}
break;
case "__esModule":
return {
info,
rawName: "true /* __esModule */",
ids: exportName.slice(1),
exportName
};
}
break;
case "default-only": {
const exportId = exportName[0];
if (exportId === "__esModule") {
return {
info,
rawName: "true /* __esModule */",
ids: exportName.slice(1),
exportName
};
}
exportName = exportName.slice(1);
if (exportId !== "default") {
return {
info,
rawName:
"undefined /* non-default import from default-exporting module */",
ids: exportName,
exportName
};
}
if (deferred) {
// As with default-with-named above, a deferred default-only
// external reads through the `.a` getter, so `typeof` and
// `instanceof` see the value rather than the proxy.
return {
info,
rawName: `${info.deferredName}.a`,
ids: exportName,
exportName
};
}
break;
}
case "dynamic":
switch (exportName[0]) {
case "default": {
exportName = exportName.slice(1);
if (deferred) {
return {
info,
rawName: `${info.deferredName}.a`,
ids: exportName,
exportName
};
}
if (moduleDeferred) {
return {
info,
rawName: getExternalModuleExpr(info),
ids: exportName,
exportName,
accessorCall: info.wrapped
};
}
info.interopDefaultAccessUsed = true;
const accessor = getInteropExpr(
info,
info.interopDefaultAccessName
);
const defaultExport = asCall
? `${accessor}()`
: asiSafe
? `(${accessor}())`
: asiSafe === false
? `;(${accessor}())`
: `${accessor}.a`;
return {
info,
rawName: defaultExport,
ids: exportName,
exportName
};
}
case "__esModule":
return {
info,
rawName: "true /* __esModule */",
ids: exportName.slice(1),
exportName
};
}
break;
default:
throw new Error(`Unexpected exportsType ${exportsType}`);
}
}
if (exportName.length === 0) {
switch (info.type) {
case "concatenated":
neededNamespaceObjects.add(info);
return {
info,
rawName:
/** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
(info.namespaceObjectName),
ids: exportName,
exportName,
accessorCall: info.wrapped
};
case "external": {
if (deferred) {
info.deferredNamespaceObjectUsed = true;
return {
info,
rawName: /** @type {string} */ (info.deferredNamespaceObjectName),
ids: exportName,
exportName
};
}
// `require()` reads the exports object rather than a namespace, so
// only an import gets the spec object and interop keeps working.
const spec =
!moduleExportsAccess &&
exportsType === "namespace" &&
Boolean(
/** @type {BuildInfo} */
(info.module.buildInfo).specNamespaceObject
);
const rawName = getExternalModuleExpr(info);
if (spec) info.specNamespaceObjectUsed = true;
return {
info,
rawName: spec
? `${RuntimeGlobals.specNamespaceObject}(${rawName})`
: rawName,
ids: exportName,
exportName,
accessorCall: spec || info.wrapped
};
}
}
}
const exportsInfo = moduleGraph.getExportsInfo(info.module);
const exportInfo = exportsInfo.getExportInfo(exportName[0]);
// Lazily allocate: only the reexport-following recursion below needs it,
// most calls return before reaching this point.
if (alreadyVisited === undefined) alreadyVisited = new Set();
if (alreadyVisited.has(exportInfo)) {
return {
info,
rawName: "/* circular reexport */ Object(function x() { x() }())",
ids: [],
exportName
};
}
alreadyVisited.add(exportInfo);
switch (info.type) {
case "concatenated": {
const exportId = exportName[0];
if (exportInfo.provided === false) {
// It's not provided, but it could be on the prototype
neededNamespaceObjects.add(info);
return {
info,
rawName: /** @type {string} */ (info.namespaceObjectName),
ids: exportName,
exportName
};
}
const directExport = info.exportMap && info.exportMap.get(exportId);
if (directExport) {
const usedName = exportsInfo.getUsedName(exportName, runtime);
if (!usedName) {
return {
info,
rawName: "undefined /* unused export */",
ids: exportName.slice(1),
exportName
};
}
if (isInlinedUsedName(usedName)) {
return {
info,
// Render the inlined literal only, not its property suffix: that
// comes back in `ids` and getFinalName appends it once, so emitting
// it here too would duplicate the access.
rawName: usedName.render(
Template.toNormalComment(
`inlined export ${propertyAccess(exportName)}`
)
),
ids: usedName.suffix,
exportName
};
}
return {
info,
name: directExport,
ids: /** @type {ExportName} */ (usedName).slice(1),
exportName
};
}
const rawExport = info.rawExportMap && info.rawExportMap.get(exportId);
if (rawExport) {
return {
info,
rawName: rawExport,
ids: exportName.slice(1),
exportName
};
}
const reexport = exportInfo.findTarget(moduleGraph, (module) =>
moduleToInfoMap.has(module)
);
if (reexport === false) {
// Source module was removed because all its exports were inlined;
// we render the inlined value here instead of binding to the now-absent module.
const target = exportInfo.getTarget(moduleGraph);
if (target && target.export) {
const usedName = moduleGraph
.getExportsInfo(target.module)
.getUsedName([...target.export, ...exportName.slice(1)], runtime);
if (isInlinedUsedName(usedName)) {
return {
info,
// Literal only; suffix is appended once via `ids` (see directExport branch).
rawName: usedName.render(
Template.toNormalComment(
`inlined export ${propertyAccess(exportName)}`
)
),
ids: usedName.suffix,
exportName
};
}
}
throw new Error(
`Target module of reexport from '${info.module.readableIdentifier(
requestShortener
)}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from(
moduleToInfoMap,
([m, info]) =>
` * ${info.type} ${m.readableIdentifier(requestShortener)}`
).join("\n")}`
);
} else if (reexport) {
const refInfo = moduleToInfoMap.get(reexport.module);
// a CommonJS `exports.x = require()` re-export keeps raw exports semantics
const moduleExportsAccess =
reexport.connection.dependency !== null &&
isDependencyKind(
reexport.connection.dependency,
"commonjs-export-require"
);
return getFinalBinding(
moduleGraph,
/** @type {ModuleInfo} */ (refInfo),
reexport.export
? [...reexport.export, ...exportName.slice(1)]
: exportName.slice(1),
moduleToInfoMap,
runtime,
requestShortener,
runtimeTemplate,
neededNamespaceObjects,
asCall,
reexport.deferred,
/** @type {JavascriptModuleBuildMeta} */
(info.module.buildMeta).strictHarmonyModule,
asiSafe,
moduleExportsAccess,
alreadyVisited
);
}
// A wrapped module resolves every export through its live exports
// alias (namespaceObjectName), same as namespaceExportSymbol modules.
if (info.namespaceExportSymbol || info.wrapped) {
const usedName = exportsInfo.getUsedName(exportName, runtime);
if (!usedName) {
return {
info,
rawName: "undefined /* unused export */",
ids: exportName.slice(1),
exportName
};
}
// an inlined export never reaches the exports object, so render the
// literal instead of reading the namespace
if (isInlinedUsedName(usedName)) {
return {
info,
// Literal only; suffix is appended once via `ids` (see directExport branch).
rawName: usedName.render(
Template.toNormalComment(
`inlined export ${propertyAccess(exportName)}`
)
),
ids: usedName.suffix,
exportName
};
}
return {
info,
rawName: /** @type {string} */ (info.namespaceObjectName),
ids: /** @type {ExportName} */ (usedName),
exportName
};
}
throw new Error(
`Cannot get final name for export '${exportName.join(
"."
)}' of ${info.module.readableIdentifier(requestShortener)}`
);
}
case "external": {
const used = exportsInfo.getUsedName(exportName, runtime);
if (!used) {
return {
info,
rawName: "undefined /* unused export */",
ids: exportName.slice(1),
exportName
};
}
if (isInlinedUsedName(used)) {
return {
info,
// Literal only; suffix is appended once via `ids` (see directExport branch).
rawName: used.render(
Template.toNormalComment(
`inlined export ${propertyAccess(exportName)}`
)
),
ids: used.suffix,
exportName
};
}
const usedName = /** @type {ExportName} */ (used);
const comment = equals(usedName, exportName)
? ""
: Template.toNormalComment(`${exportName.join(".")}`);
return {
info,
rawName:
(deferred ? `${info.deferredName}.a` : getExternalModuleExpr(info)) +
comment,
ids: usedName,
exportName
};
}
}
};
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {ModuleInfo} info module info
* @param {ExportName} exportName exportName
* @param {ModuleToInfoMap} moduleToInfoMap moduleToInfoMap
* @param {RuntimeSpec} runtime for which runtime
* @param {RequestShortener} requestShortener the request shortener
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {NeededNamespaceObjects} neededNamespaceObjects modules for which a namespace object should be generated
* @param {boolean} asCall asCall
* @param {boolean} depDeferred the dependency is deferred
* @param {boolean | undefined} callContext callContext
* @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
* @param {boolean | undefined} asiSafe asiSafe
* @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
* @returns {string} the final name
*/
const getFinalName = (
moduleGraph,
info,
exportName,
moduleToInfoMap,
runtime,
requestShortener,
runtimeTemplate,