/
FileEmitter.ts
387 lines (358 loc) · 11.2 KB
/
FileEmitter.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
import type Chunk from '../Chunk';
import type Graph from '../Graph';
import type Module from '../Module';
import type {
EmittedChunk,
NormalizedInputOptions,
NormalizedOutputOptions,
WarningHandler
} from '../rollup/types';
import { BuildPhase } from './buildPhase';
import { createHash } from './crypto';
import {
errAssetNotFinalisedForFileName,
errAssetReferenceIdNotFoundForSetSource,
errAssetSourceAlreadySet,
errChunkNotGeneratedForFileName,
errFailedValidation,
errFileNameConflict,
errFileReferenceIdNotFoundForFilename,
errInvalidRollupPhaseForChunkEmission,
errNoAssetSourceSet,
error,
warnDeprecation
} from './error';
import {
FILE_PLACEHOLDER,
lowercaseBundleKeys,
OutputBundleWithPlaceholders
} from './outputBundle';
import { extname } from './path';
import { isPathFragment } from './relativeId';
import { makeUnique, renderNamePattern } from './renderNamePattern';
function generateAssetFileName(
name: string | undefined,
source: string | Uint8Array,
outputOptions: NormalizedOutputOptions,
bundle: OutputBundleWithPlaceholders
): string {
const emittedName = outputOptions.sanitizeFileName(name || 'asset');
return makeUnique(
renderNamePattern(
typeof outputOptions.assetFileNames === 'function'
? outputOptions.assetFileNames({ name, source, type: 'asset' })
: outputOptions.assetFileNames,
'output.assetFileNames',
{
ext: () => extname(emittedName).substring(1),
extname: () => extname(emittedName),
hash() {
return createHash()
.update(emittedName)
.update(':')
.update(source)
.digest('hex')
.substring(0, 8);
},
name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
}
),
bundle
);
}
function reserveFileNameInBundle(
fileName: string,
bundle: OutputBundleWithPlaceholders,
warn: WarningHandler
) {
const lowercaseFileName = fileName.toLowerCase();
if (bundle[lowercaseBundleKeys].has(lowercaseFileName)) {
warn(errFileNameConflict(fileName));
} else {
bundle[fileName] = FILE_PLACEHOLDER;
}
}
interface ConsumedChunk {
fileName: string | undefined;
module: null | Module;
name: string;
type: 'chunk';
}
interface ConsumedAsset {
fileName: string | undefined;
name: string | undefined;
source: string | Uint8Array | undefined;
type: 'asset';
}
interface EmittedFile {
[key: string]: unknown;
fileName?: string;
name?: string;
type: 'chunk' | 'asset';
}
type ConsumedFile = ConsumedChunk | ConsumedAsset;
function hasValidType(
emittedFile: unknown
): emittedFile is { [key: string]: unknown; type: 'asset' | 'chunk' } {
return Boolean(
emittedFile &&
((emittedFile as { [key: string]: unknown }).type === 'asset' ||
(emittedFile as { [key: string]: unknown }).type === 'chunk')
);
}
function hasValidName(emittedFile: {
[key: string]: unknown;
type: 'asset' | 'chunk';
}): emittedFile is EmittedFile {
const validatedName = emittedFile.fileName || emittedFile.name;
return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
}
function getValidSource(
source: unknown,
emittedFile: { fileName?: string; name?: string },
fileReferenceId: string | null
): string | Uint8Array {
if (!(typeof source === 'string' || source instanceof Uint8Array)) {
const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
return error(
errFailedValidation(
`Could not set source for ${
typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'
}, asset source needs to be a string, Uint8Array or Buffer.`
)
);
}
return source;
}
function getAssetFileName(file: ConsumedAsset, referenceId: string): string {
if (typeof file.fileName !== 'string') {
return error(errAssetNotFinalisedForFileName(file.name || referenceId));
}
return file.fileName;
}
function getChunkFileName(
file: ConsumedChunk,
facadeChunkByModule: ReadonlyMap<Module, Chunk> | null
): string {
const fileName = file.fileName || (file.module && facadeChunkByModule?.get(file.module)?.id);
if (!fileName) return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
return fileName;
}
export class FileEmitter {
private bundle: OutputBundleWithPlaceholders | null = null;
private facadeChunkByModule: ReadonlyMap<Module, Chunk> | null = null;
private readonly filesByReferenceId: Map<string, ConsumedFile>;
private outputOptions: NormalizedOutputOptions | null = null;
constructor(
private readonly graph: Graph,
private readonly options: NormalizedInputOptions,
baseFileEmitter?: FileEmitter
) {
this.filesByReferenceId = baseFileEmitter
? new Map(baseFileEmitter.filesByReferenceId)
: new Map();
}
public assertAssetsFinalized = (): void => {
for (const [referenceId, emittedFile] of this.filesByReferenceId) {
if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
return error(errNoAssetSourceSet(emittedFile.name || referenceId));
}
};
public emitFile = (emittedFile: unknown): string => {
if (!hasValidType(emittedFile)) {
return error(
errFailedValidation(
`Emitted files must be of type "asset" or "chunk", received "${
emittedFile && (emittedFile as any).type
}".`
)
);
}
if (!hasValidName(emittedFile)) {
return error(
errFailedValidation(
`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${
emittedFile.fileName || emittedFile.name
}".`
)
);
}
if (emittedFile.type === 'chunk') {
return this.emitChunk(emittedFile);
}
return this.emitAsset(emittedFile);
};
public getFileName = (fileReferenceId: string): string => {
const emittedFile = this.filesByReferenceId.get(fileReferenceId);
if (!emittedFile) return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
if (emittedFile.type === 'chunk') {
return getChunkFileName(emittedFile, this.facadeChunkByModule);
}
return getAssetFileName(emittedFile, fileReferenceId);
};
public setAssetSource = (referenceId: string, requestedSource: unknown): void => {
const consumedFile = this.filesByReferenceId.get(referenceId);
if (!consumedFile) return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
if (consumedFile.type !== 'asset') {
return error(
errFailedValidation(
`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`
)
);
}
if (consumedFile.source !== undefined) {
return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
}
const source = getValidSource(requestedSource, consumedFile, referenceId);
if (this.bundle) {
this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
} else {
consumedFile.source = source;
}
};
public setOutputBundle = (
bundle: OutputBundleWithPlaceholders,
outputOptions: NormalizedOutputOptions,
facadeChunkByModule: ReadonlyMap<Module, Chunk>
): void => {
this.outputOptions = outputOptions;
this.bundle = bundle;
this.facadeChunkByModule = facadeChunkByModule;
for (const { fileName } of this.filesByReferenceId.values()) {
if (fileName) {
reserveFileNameInBundle(fileName, bundle, this.options.onwarn);
}
}
for (const [referenceId, consumedFile] of this.filesByReferenceId) {
if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
this.finalizeAsset(consumedFile, consumedFile.source, referenceId, bundle);
}
}
};
private assignReferenceId(file: ConsumedFile, idBase: string): string {
let referenceId: string | undefined;
do {
referenceId = createHash()
.update(referenceId || idBase)
.digest('hex')
.substring(0, 8);
} while (this.filesByReferenceId.has(referenceId));
this.filesByReferenceId.set(referenceId, file);
return referenceId;
}
private emitAsset(emittedAsset: EmittedFile): string {
const source =
typeof emittedAsset.source !== 'undefined'
? getValidSource(emittedAsset.source, emittedAsset, null)
: undefined;
const consumedAsset: ConsumedAsset = {
fileName: emittedAsset.fileName,
name: emittedAsset.name,
source,
type: 'asset'
};
const referenceId = this.assignReferenceId(
consumedAsset,
emittedAsset.fileName || emittedAsset.name || emittedAsset.type
);
if (this.bundle) {
if (emittedAsset.fileName) {
reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
}
if (source !== undefined) {
this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
}
}
return referenceId;
}
private emitChunk(emittedChunk: EmittedFile): string {
if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
return error(errInvalidRollupPhaseForChunkEmission());
}
if (typeof emittedChunk.id !== 'string') {
return error(
errFailedValidation(
`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`
)
);
}
const consumedChunk: ConsumedChunk = {
fileName: emittedChunk.fileName,
module: null,
name: emittedChunk.name || emittedChunk.id,
type: 'chunk'
};
this.graph.moduleLoader
.emitChunk(emittedChunk as unknown as EmittedChunk)
.then(module => (consumedChunk.module = module))
.catch(() => {
// Avoid unhandled Promise rejection as the error will be thrown later
// once module loading has finished
});
return this.assignReferenceId(consumedChunk, emittedChunk.id);
}
private finalizeAsset(
consumedFile: ConsumedFile,
source: string | Uint8Array,
referenceId: string,
bundle: OutputBundleWithPlaceholders
): void {
const fileName =
consumedFile.fileName ||
findExistingAssetFileNameWithSource(bundle, source) ||
generateAssetFileName(consumedFile.name, source, this.outputOptions!, bundle);
// We must not modify the original assets to avoid interaction between outputs
const assetWithFileName = { ...consumedFile, fileName, source };
this.filesByReferenceId.set(referenceId, assetWithFileName);
const { options } = this;
bundle[fileName] = {
fileName,
get isAsset(): true {
warnDeprecation(
'Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead',
true,
options
);
return true;
},
name: consumedFile.name,
source,
type: 'asset'
};
}
}
// TODO This can lead to a performance problem when many assets are emitted.
// Instead, we should only deduplicate string assets and use their sources as
// object keys for better performance.
function findExistingAssetFileNameWithSource(
bundle: OutputBundleWithPlaceholders,
source: string | Uint8Array
): string | null {
for (const [fileName, outputFile] of Object.entries(bundle)) {
if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source)) return fileName;
}
return null;
}
function areSourcesEqual(
sourceA: string | Uint8Array | Buffer,
sourceB: string | Uint8Array | Buffer
): boolean {
if (typeof sourceA === 'string') {
return sourceA === sourceB;
}
if (typeof sourceB === 'string') {
return false;
}
if ('equals' in sourceA) {
return sourceA.equals(sourceB);
}
if (sourceA.length !== sourceB.length) {
return false;
}
for (let index = 0; index < sourceA.length; index++) {
if (sourceA[index] !== sourceB[index]) {
return false;
}
}
return true;
}