-
Notifications
You must be signed in to change notification settings - Fork 147
/
import-export.js
590 lines (468 loc) · 15.8 KB
/
import-export.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
import SOURCE_TYPE from "../constant/source-type.js"
import Visitor from "../visitor.js"
import encodeId from "../util/encode-id.js"
import errors from "../parse/errors.js"
import getNamesFromPattern from "../parse/get-names-from-pattern.js"
import keys from "../util/keys.js"
import { lineBreakRegExp } from "../acorn.js"
import overwrite from "../parse/overwrite.js"
import pad from "../parse/pad.js"
import preserveChild from "../parse/preserve-child.js"
import preserveLine from "../parse/preserve-line.js"
import shared from "../shared.js"
function init() {
const {
MODULE
} = SOURCE_TYPE
class ImportExportVisitor extends Visitor {
finalizeHoisting() {
const { top } = this
const code =
top.insertPrefix +
toModuleExport(this, this.hoistedExports) +
this.hoistedImportsString
this.magicString.prependLeft(top.insertIndex, code)
this.yieldIndex += code.length
}
reset(options) {
this.addedImportExport = false
this.addedImportMeta = false
this.assignableExports = null
this.changed = false
this.dependencySpecifiers = null
this.exportedFrom = null
this.exportedNames = null
this.exportedStars = null
this.firstLineBreakPos = -1
this.generateVarDeclarations = false
this.hoistedExports = null
this.hoistedImportsString = ""
this.importedLocals = null
this.magicString = null
this.possibleIndexes = null
this.runtimeName = null
this.sourceType = null
this.strict = false
this.temporals = null
this.top = null
this.yieldIndex = 0
if (options) {
const { magicString } = options
this.assignableExports = { __proto__: null }
this.dependencySpecifiers = { __proto__: null }
this.exportedFrom = { __proto__: null }
this.exportedNames = []
this.exportedStars = []
this.firstLineBreakPos = magicString.original.search(lineBreakRegExp)
this.generateVarDeclarations = options.generateVarDeclarations
this.hoistedExports = []
this.importedLocals = { __proto__: null }
this.magicString = magicString
this.possibleIndexes = options.possibleIndexes
this.runtimeName = options.runtimeName
this.sourceType = options.sourceType
this.strict = options.strict
this.temporals = { __proto__: null }
this.top = options.top
this.yieldIndex = options.yieldIndex
}
}
visitCallExpression(path) {
const node = path.getValue()
const { callee } = node
if (! node.arguments.length) {
path.call(this, "visitWithoutReset", "callee")
return
}
if (callee.type !== "Import") {
this.visitChildren(path)
return
}
// Support dynamic import:
// import("mod")
this.changed = true
overwrite(this, callee.start, callee.end, this.runtimeName + ".i")
path.call(this, "visitWithoutReset", "arguments")
}
visitImportDeclaration(path) {
if (this.sourceType !== MODULE) {
return
}
// Suport import statements:
// import defaultName from "mod"
// import * as name from "mod"
// import { export as alias } from "mod"
// import { export1 , export2, ...exportN } from "mod"
// import { export1 , export2 as alias2, [...] } from "mod"
// import defaultName, { export1, [ , [...] ] } from "mod"
// import defaultName, * as name from "mod"
// import "mod"
this.changed =
this.addedImportExport = true
const node = path.getValue()
const { specifiers } = node
const { length } = specifiers
const lastIndex = length - 1
const specifierMap = createSpecifierMap(this, node)
let hoistedCode = length
? (this.generateVarDeclarations ? "var " : "let ")
: ""
let i = -1
for (const specifier of specifiers) {
hoistedCode +=
specifier.local.name +
(++i === lastIndex ? ";" : ",")
}
hoistedCode += toModuleImport(
this,
node.source.value,
specifierMap
)
hoistImports(this, node, hoistedCode)
addLocals(this, specifierMap)
}
visitExportAllDeclaration(path) {
if (this.sourceType !== MODULE) {
return
}
// Support re-exporting an imported module:
// export * from "mod"
this.changed =
this.addedImportExport = true
const { exportedFrom, runtimeName } = this
const node = path.getValue()
const { original } = this.magicString
const { source } = node
const specifierName = source.value
const hoistedCode = pad(
original,
runtimeName + '.w("' + specifierName + '"',
node.start,
source.start
) + pad(
original,
',[["*",null,' + runtimeName + ".n()]]);",
source.end,
node.end
)
if (! exportedFrom[specifierName]) {
exportedFrom[specifierName] = []
}
this.exportedStars.push(specifierName)
addToDependencySpecifiers(this, specifierName)
hoistImports(this, node, hoistedCode)
}
visitExportDefaultDeclaration(path) {
if (this.sourceType !== MODULE) {
return
}
this.changed =
this.addedImportExport = true
this.exportedNames.push("default")
const node = path.getValue()
const { declaration } = node
const { runtimeName } = this
let { id, type } = declaration
if (type === "ParenthesizedExpression") {
const { expression } = declaration
id = expression.id
type = expression.type
}
const name = id
? id.name
: runtimeName + "anonymous"
const pairs = [["default", name]]
if (type === "FunctionDeclaration" ||
(id && type === "ClassDeclaration")) {
// Support exporting default function declarations:
// export default function named() {}
if (! id) {
// Convert anonymous functions to hoisted named functions.
this.magicString.prependLeft(declaration.functionParamsStart, " " + name)
}
hoistExports(this, node, pairs)
} else {
// Support exporting other default declarations:
// export default value
let prefix = runtimeName + ".d("
let suffix = ");"
if (! id &&
(type === "ArrowFunctionExpression" ||
type === "ClassDeclaration" ||
type === "ClassExpression" ||
type === "FunctionExpression")) {
// Assign anonymous functions to a variable so they're given a
// temporary name, which we'll rename later to "default".
// https://tc39.github.io/ecma262/#sec-exports-runtime-semantics-evaluation
prefix = "const " + name + "="
suffix = ";" + runtimeName + ".d(" + name + ");"
} else if (type === "SequenceExpression") {
// If the exported expression is a comma-separated sequence expression
// it may not include the vital parentheses, so we should wrap the
// expression with parentheses to make sure it's treated as a single
// argument to `runtime.default()`, rather than as multiple arguments.
prefix += "("
suffix = ")" + suffix
}
overwrite(this, node.start, declaration.start, prefix)
overwrite(this, declaration.end, node.end, suffix)
}
if (id) {
addAssignableExports(this, pairs)
}
path.call(this, "visitWithoutReset", "declaration")
}
visitExportNamedDeclaration(path) {
if (this.sourceType !== MODULE) {
return
}
this.changed =
this.addedImportExport = true
const node = path.getValue()
const { original } = this.magicString
const {
declaration,
source,
specifiers
} = node
if (declaration) {
const pairs = []
const { id, type } = declaration
if (id &&
(type === "ClassDeclaration" ||
type === "FunctionDeclaration")) {
// Support exporting named class and function declarations:
// export function named() {}
const { name } = id
pairs.push([name, name])
} else if (type === "VariableDeclaration") {
// Support exporting variable lists:
// export let name1, name2, ..., nameN
for (const { id } of declaration.declarations) {
const names = getNamesFromPattern(id)
for (const name of names) {
pairs.push([name, name])
}
}
}
hoistExports(this, node, pairs)
// Skip adding declared names to `this.assignableExports()` if the
// declaration is a const-kinded VariableDeclaration, because the
// assignmentVisitor doesn't need to worry about changes to these
// variables.
if (canExportedValuesChange(node)) {
addAssignableExports(this, pairs)
}
path.call(this, "visitWithoutReset", "declaration")
} else if (source === null) {
// Support exporting specifiers:
// export { name1, name2, ..., nameN }
const { identifiers } = this.top
const pairs = []
for (const specifier of specifiers) {
const localName = specifier.local.name
if (! Reflect.has(identifiers, localName)) {
throw new errors.SyntaxError(
original,
specifier.start,
"Export '" + localName + "' is not defined in module"
)
}
pairs.push([specifier.exported.name, localName])
}
hoistExports(this, node, pairs)
addAssignableExports(this, pairs)
} else {
// Support re-exporting specifiers of an imported module:
// export { name1, name2, ..., nameN } from "mod"
const {
exportedFrom,
exportedNames,
runtimeName
} = this
const specifierName = source.value
const fromNames =
exportedFrom[specifierName] ||
(exportedFrom[specifierName] = [])
const lastIndex = specifiers.length - 1
let hoistedCode = pad(
original,
runtimeName + '.w("' + specifierName + '"',
node.start,
source.start
)
let i = -1
let setterArgsList = ""
addToDependencySpecifiers(this, specifierName)
for (const specifier of specifiers) {
const exportedName = specifier.exported.name
const localName = specifier.local.name
setterArgsList +=
'["' +
localName + '",null,' +
runtimeName + '.f("' + localName + '","' + exportedName +
'")]' +
(++i === lastIndex ? "" : ",")
exportedNames.push(exportedName)
if (exportedName === localName) {
fromNames.push([exportedName])
} else {
fromNames.push([exportedName, localName])
}
addToDependencySpecifiers(this, specifierName, localName)
}
hoistedCode += pad(
original,
",[" + setterArgsList + "]);",
source.end,
node.end
)
hoistImports(this, node, hoistedCode)
}
}
visitMetaProperty(path) {
const { meta } = path.getValue()
if (meta.name === "import") {
// Support import.meta.
this.changed =
this.addedImportMeta = true
overwrite(this, meta.start, meta.end, this.runtimeName + "._")
}
}
}
function addAssignableExports(visitor, pairs) {
const { assignableExports } = visitor
for (const [, localName] of pairs) {
assignableExports[localName] = true
}
}
function addLocals(visitor, specifierMap) {
const { importedLocals, temporals } = visitor
for (const importedName in specifierMap) {
for (const localName of specifierMap[importedName]) {
importedLocals[localName] = true
if (importedName !== "*") {
temporals[localName] = true
}
}
}
}
function addToDependencySpecifiers(visitor, specifierName, exportedName) {
const { dependencySpecifiers } = visitor
const exportedNames =
dependencySpecifiers[specifierName] ||
(dependencySpecifiers[specifierName] = [])
if (exportedName &&
exportedName !== "*" &&
exportedNames.indexOf(exportedName) === -1) {
exportedNames.push(exportedName)
}
}
function addToSpecifierMap(visitor, specifierMap, importedName, localName) {
const localNames =
specifierMap[importedName] ||
(specifierMap[importedName] = [])
localNames.push(localName)
}
function canExportedValuesChange({ declaration, type }) {
if (type === "ExportDefaultDeclaration") {
const declType = declaration.type
return declType === "FunctionDeclaration" ||
declType === "ClassDeclaration"
}
if (type === "ExportNamedDeclaration" &&
declaration &&
declaration.type === "VariableDeclaration" &&
declaration.kind === "const") {
return false
}
return true
}
function createSpecifierMap(visitor, node) {
const { specifiers } = node
const specifierMap = { __proto__: null }
for (const specifier of specifiers) {
const { type } = specifier
let importedName = "*"
if (type === "ImportSpecifier") {
importedName = specifier.imported.name
} else if (type === "ImportDefaultSpecifier") {
importedName = "default"
}
addToSpecifierMap(visitor, specifierMap, importedName, specifier.local.name)
}
return specifierMap
}
function hoistExports(visitor, node, pairs) {
visitor.hoistedExports.push(...pairs)
if (node.declaration) {
preserveChild(visitor, node, "declaration")
} else {
preserveLine(visitor, node)
}
}
function hoistImports(visitor, node, hoistedCode) {
visitor.hoistedImportsString += hoistedCode
preserveLine(visitor, node)
}
function safeName(name, localNames) {
return localNames.indexOf(name) === -1
? name
: safeName(encodeId(name), localNames)
}
function toModuleExport(visitor, pairs) {
let code = ""
if (! pairs.length) {
return code
}
const { exportedNames } = visitor
const lastIndex = pairs.length - 1
let i = -1
code += visitor.runtimeName + ".x(["
for (const [exportedName, localName] of pairs) {
code +=
'["' + exportedName + '",()=>' +
localName +
"]" +
(++i === lastIndex ? "" : ",")
exportedNames.push(exportedName)
}
code += "]);"
return code
}
function toModuleImport(visitor, specifierName, specifierMap) {
const importedNames = keys(specifierMap)
const { length } = importedNames
let code = visitor.runtimeName + '.w("' + specifierName + '"'
addToDependencySpecifiers(visitor, specifierName)
if (! length) {
return code + ");"
}
const lastIndex = length - 1
let i = -1
code += ",["
for (const importedName of importedNames) {
const localNames = specifierMap[importedName]
const valueParam = safeName("v", localNames)
code +=
'["' +
importedName + '",' +
(importedName === "*"
? "null"
: '["' + localNames.join('","') + '"]'
) +
",function(" + valueParam + "){" +
// Multiple local variables become a compound assignment.
localNames.join("=") + "=" + valueParam +
"}]" +
(++i === lastIndex ? "" : ",")
addToDependencySpecifiers(visitor, specifierName, importedName)
}
code += "]);"
return code
}
return new ImportExportVisitor
}
export default shared.inited
? shared.module.visitorImportExport
: shared.module.visitorImportExport = init()