-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
DevPackager.js
249 lines (223 loc) Β· 7.17 KB
/
DevPackager.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
// @flow strict-local
import type {BundleGraph, PluginOptions, NamedBundle} from '@parcel/types';
import {
PromiseQueue,
relativeBundlePath,
countLines,
normalizeSeparators,
} from '@parcel/utils';
import SourceMap from '@parcel/source-map';
import invariant from 'assert';
import path from 'path';
import fs from 'fs';
import {replaceScriptDependencies, getSpecifier} from './utils';
const PRELUDE = fs
.readFileSync(path.join(__dirname, 'dev-prelude.js'), 'utf8')
.trim()
.replace(/;$/, '');
export class DevPackager {
options: PluginOptions;
bundleGraph: BundleGraph<NamedBundle>;
bundle: NamedBundle;
parcelRequireName: string;
constructor(
options: PluginOptions,
bundleGraph: BundleGraph<NamedBundle>,
bundle: NamedBundle,
parcelRequireName: string,
) {
this.options = options;
this.bundleGraph = bundleGraph;
this.bundle = bundle;
this.parcelRequireName = parcelRequireName;
}
async package(): Promise<{|contents: string, map: ?SourceMap|}> {
// Load assets
let queue = new PromiseQueue({maxConcurrent: 32});
this.bundle.traverseAssets(asset => {
queue.add(async () => {
let [code, mapBuffer] = await Promise.all([
asset.getCode(),
this.bundle.env.sourceMap && asset.getMapBuffer(),
]);
return {code, mapBuffer};
});
});
let results = await queue.run();
let assets = '';
let i = 0;
let first = true;
let map = new SourceMap(this.options.projectRoot);
let prefix = this.getPrefix();
let lineOffset = countLines(prefix);
let script: ?{|code: string, mapBuffer: ?Buffer|} = null;
this.bundle.traverse(node => {
let wrapped = first ? '' : ',';
if (node.type === 'dependency') {
let resolved = this.bundleGraph.getResolvedAsset(
node.value,
this.bundle,
);
if (resolved && resolved.type !== 'js') {
// if this is a reference to another javascript asset, we should not include
// its output, as its contents should already be loaded.
invariant(!this.bundle.hasAsset(resolved));
wrapped +=
JSON.stringify(this.bundleGraph.getAssetPublicId(resolved)) +
':[function() {},{}]';
} else {
return;
}
}
if (node.type === 'asset') {
let asset = node.value;
invariant(
asset.type === 'js',
'all assets in a js bundle must be js assets',
);
// If this is the main entry of a script rather than a module, we need to hoist it
// outside the bundle wrapper function so that its variables are exposed as globals.
if (
this.bundle.env.sourceType === 'script' &&
asset === this.bundle.getMainEntry()
) {
script = results[i++];
return;
}
let deps = {};
let dependencies = this.bundleGraph.getDependencies(asset);
for (let dep of dependencies) {
let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
if (this.bundleGraph.isDependencySkipped(dep)) {
deps[getSpecifier(dep)] = false;
} else if (resolved) {
deps[getSpecifier(dep)] =
this.bundleGraph.getAssetPublicId(resolved);
}
}
let {code, mapBuffer} = results[i];
let output = code || '';
wrapped +=
JSON.stringify(this.bundleGraph.getAssetPublicId(asset)) +
':[function(require,module,exports) {\n' +
output +
'\n},';
wrapped += JSON.stringify(deps);
wrapped += ']';
if (
this.bundle.env.isNode() &&
asset.meta.has_node_replacements === true
) {
const relPath = normalizeSeparators(
path.relative(
this.bundle.target.distDir,
path.dirname(asset.filePath),
),
);
wrapped = wrapped.replace('$parcel$dirnameReplace', relPath);
wrapped = wrapped.replace('$parcel$filenameReplace', relPath);
}
if (this.bundle.env.sourceMap) {
if (mapBuffer) {
map.addBuffer(mapBuffer, lineOffset);
} else {
map.addEmptyMap(
path
.relative(this.options.projectRoot, asset.filePath)
.replace(/\\+/g, '/'),
output,
lineOffset,
);
}
lineOffset += countLines(output) + 1;
}
i++;
}
assets += wrapped;
first = false;
});
let entries = this.bundle.getEntryAssets();
let mainEntry = this.bundle.getMainEntry();
if (
(!this.isEntry() && this.bundle.env.outputFormat === 'global') ||
this.bundle.env.sourceType === 'script'
) {
// In async bundles we don't want the main entry to execute until we require it
// as there might be dependencies in a sibling bundle that hasn't loaded yet.
entries = entries.filter(a => a.id !== mainEntry?.id);
mainEntry = null;
}
let contents =
prefix +
'({' +
assets +
'},' +
JSON.stringify(
entries.map(asset => this.bundleGraph.getAssetPublicId(asset)),
) +
', ' +
JSON.stringify(
mainEntry ? this.bundleGraph.getAssetPublicId(mainEntry) : null,
) +
', ' +
JSON.stringify(this.parcelRequireName) +
')' +
'\n';
// The entry asset of a script bundle gets hoisted outside the bundle wrapper function
// so that its variables become globals. We need to replace any require calls for
// runtimes with a parcelRequire call.
if (this.bundle.env.sourceType === 'script' && script) {
let entryMap;
let mapBuffer = script.mapBuffer;
if (mapBuffer) {
entryMap = new SourceMap(this.options.projectRoot, mapBuffer);
}
contents += replaceScriptDependencies(
this.bundleGraph,
this.bundle,
script.code,
entryMap,
this.parcelRequireName,
);
if (this.bundle.env.sourceMap && entryMap) {
map.addSourceMap(entryMap, lineOffset);
}
}
return {
contents,
map,
};
}
getPrefix(): string {
let interpreter: ?string;
let mainEntry = this.bundle.getMainEntry();
if (mainEntry && this.isEntry() && !this.bundle.target.env.isBrowser()) {
let _interpreter = mainEntry.meta.interpreter;
invariant(_interpreter == null || typeof _interpreter === 'string');
interpreter = _interpreter;
}
let importScripts = '';
if (this.bundle.env.isWorker()) {
let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
for (let b of bundles) {
importScripts += `importScripts("${relativeBundlePath(
this.bundle,
b,
)}");\n`;
}
}
return (
// If the entry asset included a hashbang, repeat it at the top of the bundle
(interpreter != null ? `#!${interpreter}\n` : '') +
importScripts +
PRELUDE
);
}
isEntry(): boolean {
return (
!this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') ||
this.bundle.env.isIsolated() ||
this.bundle.bundleBehavior === 'isolated'
);
}
}